]> git.ipfire.org Git - thirdparty/linux.git/blame - drivers/gpu/drm/i915/i915_gem.c
drm/i915: Allow DBLSCAN user modes with eDP/LVDS/DSI
[thirdparty/linux.git] / drivers / gpu / drm / i915 / i915_gem.c
CommitLineData
673a394b 1/*
be6a0376 2 * Copyright © 2008-2015 Intel Corporation
673a394b
EA
3 *
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:
10 *
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
13 * Software.
14 *
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
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Eric Anholt <eric@anholt.net>
25 *
26 */
27
760285e7 28#include <drm/drmP.h>
0de23977 29#include <drm/drm_vma_manager.h>
760285e7 30#include <drm/i915_drm.h>
673a394b 31#include "i915_drv.h"
57822dc6 32#include "i915_gem_clflush.h"
eb82289a 33#include "i915_vgpu.h"
1c5d22f7 34#include "i915_trace.h"
652c393a 35#include "intel_drv.h"
5d723d7a 36#include "intel_frontbuffer.h"
0ccdacf6 37#include "intel_mocs.h"
59b449d5 38#include "intel_workarounds.h"
465c403c 39#include "i915_gemfs.h"
6b5e90f5 40#include <linux/dma-fence-array.h>
fe3288b5 41#include <linux/kthread.h>
c13d87ea 42#include <linux/reservation.h>
5949eac4 43#include <linux/shmem_fs.h>
5a0e3ad6 44#include <linux/slab.h>
20e4933c 45#include <linux/stop_machine.h>
673a394b 46#include <linux/swap.h>
79e53945 47#include <linux/pci.h>
1286ff73 48#include <linux/dma-buf.h>
673a394b 49
fbbd37b3 50static void i915_gem_flush_free_objects(struct drm_i915_private *i915);
61050808 51
2c22569b
CW
52static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
53{
e27ab73d 54 if (obj->cache_dirty)
b50a5371
AS
55 return false;
56
b8f55be6 57 if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE))
2c22569b
CW
58 return true;
59
bd3d2252 60 return obj->pin_global; /* currently in use by HW, keep flushed */
2c22569b
CW
61}
62
4f1959ee 63static int
bb6dc8d9 64insert_mappable_node(struct i915_ggtt *ggtt,
4f1959ee
AS
65 struct drm_mm_node *node, u32 size)
66{
67 memset(node, 0, sizeof(*node));
82ad6443 68 return drm_mm_insert_node_in_range(&ggtt->vm.mm, node,
4e64e553
CW
69 size, 0, I915_COLOR_UNEVICTABLE,
70 0, ggtt->mappable_end,
71 DRM_MM_INSERT_LOW);
4f1959ee
AS
72}
73
74static void
75remove_mappable_node(struct drm_mm_node *node)
76{
77 drm_mm_remove_node(node);
78}
79
73aa808f
CW
80/* some bookkeeping */
81static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
3ef7f228 82 u64 size)
73aa808f 83{
c20e8355 84 spin_lock(&dev_priv->mm.object_stat_lock);
73aa808f
CW
85 dev_priv->mm.object_count++;
86 dev_priv->mm.object_memory += size;
c20e8355 87 spin_unlock(&dev_priv->mm.object_stat_lock);
73aa808f
CW
88}
89
90static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
3ef7f228 91 u64 size)
73aa808f 92{
c20e8355 93 spin_lock(&dev_priv->mm.object_stat_lock);
73aa808f
CW
94 dev_priv->mm.object_count--;
95 dev_priv->mm.object_memory -= size;
c20e8355 96 spin_unlock(&dev_priv->mm.object_stat_lock);
73aa808f
CW
97}
98
21dd3734 99static int
33196ded 100i915_gem_wait_for_error(struct i915_gpu_error *error)
30dbf0c0 101{
30dbf0c0
CW
102 int ret;
103
4c7d62c6
CW
104 might_sleep();
105
0a6759c6
DV
106 /*
107 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
108 * userspace. If it takes that long something really bad is going on and
109 * we should simply try to bail out and fail as gracefully as possible.
110 */
1f83fee0 111 ret = wait_event_interruptible_timeout(error->reset_queue,
8c185eca 112 !i915_reset_backoff(error),
b52992c0 113 I915_RESET_TIMEOUT);
0a6759c6
DV
114 if (ret == 0) {
115 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
116 return -EIO;
117 } else if (ret < 0) {
30dbf0c0 118 return ret;
d98c52cf
CW
119 } else {
120 return 0;
0a6759c6 121 }
30dbf0c0
CW
122}
123
54cf91dc 124int i915_mutex_lock_interruptible(struct drm_device *dev)
76c1dec1 125{
fac5e23e 126 struct drm_i915_private *dev_priv = to_i915(dev);
76c1dec1
CW
127 int ret;
128
33196ded 129 ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
76c1dec1
CW
130 if (ret)
131 return ret;
132
133 ret = mutex_lock_interruptible(&dev->struct_mutex);
134 if (ret)
135 return ret;
136
76c1dec1
CW
137 return 0;
138}
30dbf0c0 139
e4d2006f
CW
140static u32 __i915_gem_park(struct drm_i915_private *i915)
141{
4dfacb0b
CW
142 GEM_TRACE("\n");
143
e4d2006f
CW
144 lockdep_assert_held(&i915->drm.struct_mutex);
145 GEM_BUG_ON(i915->gt.active_requests);
643b450a 146 GEM_BUG_ON(!list_empty(&i915->gt.active_rings));
e4d2006f
CW
147
148 if (!i915->gt.awake)
149 return I915_EPOCH_INVALID;
150
151 GEM_BUG_ON(i915->gt.epoch == I915_EPOCH_INVALID);
152
153 /*
154 * Be paranoid and flush a concurrent interrupt to make sure
155 * we don't reactivate any irq tasklets after parking.
156 *
157 * FIXME: Note that even though we have waited for execlists to be idle,
158 * there may still be an in-flight interrupt even though the CSB
159 * is now empty. synchronize_irq() makes sure that a residual interrupt
160 * is completed before we continue, but it doesn't prevent the HW from
161 * raising a spurious interrupt later. To complete the shield we should
162 * coordinate disabling the CS irq with flushing the interrupts.
163 */
164 synchronize_irq(i915->drm.irq);
165
166 intel_engines_park(i915);
a89d1f92 167 i915_timelines_park(i915);
e4d2006f
CW
168
169 i915_pmu_gt_parked(i915);
3365e226 170 i915_vma_parked(i915);
e4d2006f
CW
171
172 i915->gt.awake = false;
173
174 if (INTEL_GEN(i915) >= 6)
175 gen6_rps_idle(i915);
176
177 intel_display_power_put(i915, POWER_DOMAIN_GT_IRQ);
178
179 intel_runtime_pm_put(i915);
180
181 return i915->gt.epoch;
182}
183
184void i915_gem_park(struct drm_i915_private *i915)
185{
4dfacb0b
CW
186 GEM_TRACE("\n");
187
e4d2006f
CW
188 lockdep_assert_held(&i915->drm.struct_mutex);
189 GEM_BUG_ON(i915->gt.active_requests);
190
191 if (!i915->gt.awake)
192 return;
193
194 /* Defer the actual call to __i915_gem_park() to prevent ping-pongs */
195 mod_delayed_work(i915->wq, &i915->gt.idle_work, msecs_to_jiffies(100));
196}
197
198void i915_gem_unpark(struct drm_i915_private *i915)
199{
4dfacb0b
CW
200 GEM_TRACE("\n");
201
e4d2006f
CW
202 lockdep_assert_held(&i915->drm.struct_mutex);
203 GEM_BUG_ON(!i915->gt.active_requests);
204
205 if (i915->gt.awake)
206 return;
207
208 intel_runtime_pm_get_noresume(i915);
209
210 /*
211 * It seems that the DMC likes to transition between the DC states a lot
212 * when there are no connected displays (no active power domains) during
213 * command submission.
214 *
215 * This activity has negative impact on the performance of the chip with
216 * huge latencies observed in the interrupt handler and elsewhere.
217 *
218 * Work around it by grabbing a GT IRQ power domain whilst there is any
219 * GT activity, preventing any DC state transitions.
220 */
221 intel_display_power_get(i915, POWER_DOMAIN_GT_IRQ);
222
223 i915->gt.awake = true;
224 if (unlikely(++i915->gt.epoch == 0)) /* keep 0 as invalid */
225 i915->gt.epoch = 1;
226
227 intel_enable_gt_powersave(i915);
228 i915_update_gfx_val(i915);
229 if (INTEL_GEN(i915) >= 6)
230 gen6_rps_busy(i915);
231 i915_pmu_gt_unparked(i915);
232
233 intel_engines_unpark(i915);
234
235 i915_queue_hangcheck(i915);
236
237 queue_delayed_work(i915->wq,
238 &i915->gt.retire_work,
239 round_jiffies_up_relative(HZ));
240}
241
5a125c3c
EA
242int
243i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
05394f39 244 struct drm_file *file)
5a125c3c 245{
72e96d64 246 struct drm_i915_private *dev_priv = to_i915(dev);
62106b4f 247 struct i915_ggtt *ggtt = &dev_priv->ggtt;
72e96d64 248 struct drm_i915_gem_get_aperture *args = data;
ca1543be 249 struct i915_vma *vma;
ff8f7975 250 u64 pinned;
5a125c3c 251
82ad6443 252 pinned = ggtt->vm.reserved;
73aa808f 253 mutex_lock(&dev->struct_mutex);
82ad6443 254 list_for_each_entry(vma, &ggtt->vm.active_list, vm_link)
20dfbde4 255 if (i915_vma_is_pinned(vma))
ca1543be 256 pinned += vma->node.size;
82ad6443 257 list_for_each_entry(vma, &ggtt->vm.inactive_list, vm_link)
20dfbde4 258 if (i915_vma_is_pinned(vma))
ca1543be 259 pinned += vma->node.size;
73aa808f 260 mutex_unlock(&dev->struct_mutex);
5a125c3c 261
82ad6443 262 args->aper_size = ggtt->vm.total;
0206e353 263 args->aper_available_size = args->aper_size - pinned;
6299f992 264
5a125c3c
EA
265 return 0;
266}
267
b91b09ee 268static int i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
00731155 269{
93c76a3d 270 struct address_space *mapping = obj->base.filp->f_mapping;
dbb4351b 271 drm_dma_handle_t *phys;
6a2c4232
CW
272 struct sg_table *st;
273 struct scatterlist *sg;
dbb4351b 274 char *vaddr;
6a2c4232 275 int i;
b91b09ee 276 int err;
00731155 277
6a2c4232 278 if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
b91b09ee 279 return -EINVAL;
6a2c4232 280
dbb4351b
CW
281 /* Always aligning to the object size, allows a single allocation
282 * to handle all possible callers, and given typical object sizes,
283 * the alignment of the buddy allocation will naturally match.
284 */
285 phys = drm_pci_alloc(obj->base.dev,
750fae23 286 roundup_pow_of_two(obj->base.size),
dbb4351b
CW
287 roundup_pow_of_two(obj->base.size));
288 if (!phys)
b91b09ee 289 return -ENOMEM;
dbb4351b
CW
290
291 vaddr = phys->vaddr;
6a2c4232
CW
292 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
293 struct page *page;
294 char *src;
295
296 page = shmem_read_mapping_page(mapping, i);
dbb4351b 297 if (IS_ERR(page)) {
b91b09ee 298 err = PTR_ERR(page);
dbb4351b
CW
299 goto err_phys;
300 }
6a2c4232
CW
301
302 src = kmap_atomic(page);
303 memcpy(vaddr, src, PAGE_SIZE);
304 drm_clflush_virt_range(vaddr, PAGE_SIZE);
305 kunmap_atomic(src);
306
09cbfeaf 307 put_page(page);
6a2c4232
CW
308 vaddr += PAGE_SIZE;
309 }
310
c033666a 311 i915_gem_chipset_flush(to_i915(obj->base.dev));
6a2c4232
CW
312
313 st = kmalloc(sizeof(*st), GFP_KERNEL);
dbb4351b 314 if (!st) {
b91b09ee 315 err = -ENOMEM;
dbb4351b
CW
316 goto err_phys;
317 }
6a2c4232
CW
318
319 if (sg_alloc_table(st, 1, GFP_KERNEL)) {
320 kfree(st);
b91b09ee 321 err = -ENOMEM;
dbb4351b 322 goto err_phys;
6a2c4232
CW
323 }
324
325 sg = st->sgl;
326 sg->offset = 0;
327 sg->length = obj->base.size;
00731155 328
dbb4351b 329 sg_dma_address(sg) = phys->busaddr;
6a2c4232
CW
330 sg_dma_len(sg) = obj->base.size;
331
dbb4351b 332 obj->phys_handle = phys;
b91b09ee 333
a5c08166 334 __i915_gem_object_set_pages(obj, st, sg->length);
b91b09ee
MA
335
336 return 0;
dbb4351b
CW
337
338err_phys:
339 drm_pci_free(obj->base.dev, phys);
b91b09ee
MA
340
341 return err;
6a2c4232
CW
342}
343
e27ab73d
CW
344static void __start_cpu_write(struct drm_i915_gem_object *obj)
345{
c0a51fd0
CK
346 obj->read_domains = I915_GEM_DOMAIN_CPU;
347 obj->write_domain = I915_GEM_DOMAIN_CPU;
e27ab73d
CW
348 if (cpu_write_needs_clflush(obj))
349 obj->cache_dirty = true;
350}
351
6a2c4232 352static void
2b3c8317 353__i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
e5facdf9
CW
354 struct sg_table *pages,
355 bool needs_clflush)
6a2c4232 356{
a4f5ea64 357 GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
00731155 358
a4f5ea64
CW
359 if (obj->mm.madv == I915_MADV_DONTNEED)
360 obj->mm.dirty = false;
6a2c4232 361
e5facdf9 362 if (needs_clflush &&
c0a51fd0 363 (obj->read_domains & I915_GEM_DOMAIN_CPU) == 0 &&
b8f55be6 364 !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
2b3c8317 365 drm_clflush_sg(pages);
03ac84f1 366
e27ab73d 367 __start_cpu_write(obj);
03ac84f1
CW
368}
369
370static void
371i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj,
372 struct sg_table *pages)
373{
e5facdf9 374 __i915_gem_object_release_shmem(obj, pages, false);
03ac84f1 375
a4f5ea64 376 if (obj->mm.dirty) {
93c76a3d 377 struct address_space *mapping = obj->base.filp->f_mapping;
6a2c4232 378 char *vaddr = obj->phys_handle->vaddr;
00731155
CW
379 int i;
380
381 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
6a2c4232
CW
382 struct page *page;
383 char *dst;
384
385 page = shmem_read_mapping_page(mapping, i);
386 if (IS_ERR(page))
387 continue;
388
389 dst = kmap_atomic(page);
390 drm_clflush_virt_range(vaddr, PAGE_SIZE);
391 memcpy(dst, vaddr, PAGE_SIZE);
392 kunmap_atomic(dst);
393
394 set_page_dirty(page);
a4f5ea64 395 if (obj->mm.madv == I915_MADV_WILLNEED)
00731155 396 mark_page_accessed(page);
09cbfeaf 397 put_page(page);
00731155
CW
398 vaddr += PAGE_SIZE;
399 }
a4f5ea64 400 obj->mm.dirty = false;
00731155
CW
401 }
402
03ac84f1
CW
403 sg_free_table(pages);
404 kfree(pages);
dbb4351b
CW
405
406 drm_pci_free(obj->base.dev, obj->phys_handle);
6a2c4232
CW
407}
408
409static void
410i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
411{
a4f5ea64 412 i915_gem_object_unpin_pages(obj);
6a2c4232
CW
413}
414
415static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
416 .get_pages = i915_gem_object_get_pages_phys,
417 .put_pages = i915_gem_object_put_pages_phys,
418 .release = i915_gem_object_release_phys,
419};
420
581ab1fe
CW
421static const struct drm_i915_gem_object_ops i915_gem_object_ops;
422
35a9611c 423int i915_gem_object_unbind(struct drm_i915_gem_object *obj)
aa653a68
CW
424{
425 struct i915_vma *vma;
426 LIST_HEAD(still_in_list);
02bef8f9
CW
427 int ret;
428
429 lockdep_assert_held(&obj->base.dev->struct_mutex);
aa653a68 430
02bef8f9
CW
431 /* Closed vma are removed from the obj->vma_list - but they may
432 * still have an active binding on the object. To remove those we
433 * must wait for all rendering to complete to the object (as unbinding
434 * must anyway), and retire the requests.
aa653a68 435 */
5888fc9e 436 ret = i915_gem_object_set_to_cpu_domain(obj, false);
02bef8f9
CW
437 if (ret)
438 return ret;
439
aa653a68
CW
440 while ((vma = list_first_entry_or_null(&obj->vma_list,
441 struct i915_vma,
442 obj_link))) {
443 list_move_tail(&vma->obj_link, &still_in_list);
444 ret = i915_vma_unbind(vma);
445 if (ret)
446 break;
447 }
448 list_splice(&still_in_list, &obj->vma_list);
449
450 return ret;
451}
452
e95433c7
CW
453static long
454i915_gem_object_wait_fence(struct dma_fence *fence,
455 unsigned int flags,
456 long timeout,
562d9bae 457 struct intel_rps_client *rps_client)
00e60f26 458{
e61e0f51 459 struct i915_request *rq;
00e60f26 460
e95433c7 461 BUILD_BUG_ON(I915_WAIT_INTERRUPTIBLE != 0x1);
00e60f26 462
e95433c7
CW
463 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
464 return timeout;
465
466 if (!dma_fence_is_i915(fence))
467 return dma_fence_wait_timeout(fence,
468 flags & I915_WAIT_INTERRUPTIBLE,
469 timeout);
470
471 rq = to_request(fence);
e61e0f51 472 if (i915_request_completed(rq))
e95433c7
CW
473 goto out;
474
e9af4ea2
CW
475 /*
476 * This client is about to stall waiting for the GPU. In many cases
e95433c7
CW
477 * this is undesirable and limits the throughput of the system, as
478 * many clients cannot continue processing user input/output whilst
479 * blocked. RPS autotuning may take tens of milliseconds to respond
480 * to the GPU load and thus incurs additional latency for the client.
481 * We can circumvent that by promoting the GPU frequency to maximum
482 * before we wait. This makes the GPU throttle up much more quickly
483 * (good for benchmarks and user experience, e.g. window animations),
484 * but at a cost of spending more power processing the workload
485 * (bad for battery). Not all clients even want their results
486 * immediately and for them we should just let the GPU select its own
487 * frequency to maximise efficiency. To prevent a single client from
488 * forcing the clocks too high for the whole system, we only allow
489 * each client to waitboost once in a busy period.
490 */
e61e0f51 491 if (rps_client && !i915_request_started(rq)) {
e95433c7 492 if (INTEL_GEN(rq->i915) >= 6)
562d9bae 493 gen6_rps_boost(rq, rps_client);
00e60f26
CW
494 }
495
e61e0f51 496 timeout = i915_request_wait(rq, flags, timeout);
e95433c7
CW
497
498out:
e61e0f51
CW
499 if (flags & I915_WAIT_LOCKED && i915_request_completed(rq))
500 i915_request_retire_upto(rq);
e95433c7 501
e95433c7
CW
502 return timeout;
503}
504
505static long
506i915_gem_object_wait_reservation(struct reservation_object *resv,
507 unsigned int flags,
508 long timeout,
562d9bae 509 struct intel_rps_client *rps_client)
e95433c7 510{
e54ca977 511 unsigned int seq = __read_seqcount_begin(&resv->seq);
e95433c7 512 struct dma_fence *excl;
e54ca977 513 bool prune_fences = false;
e95433c7
CW
514
515 if (flags & I915_WAIT_ALL) {
516 struct dma_fence **shared;
517 unsigned int count, i;
00e60f26
CW
518 int ret;
519
e95433c7
CW
520 ret = reservation_object_get_fences_rcu(resv,
521 &excl, &count, &shared);
00e60f26
CW
522 if (ret)
523 return ret;
00e60f26 524
e95433c7
CW
525 for (i = 0; i < count; i++) {
526 timeout = i915_gem_object_wait_fence(shared[i],
527 flags, timeout,
562d9bae 528 rps_client);
d892e939 529 if (timeout < 0)
e95433c7 530 break;
00e60f26 531
e95433c7
CW
532 dma_fence_put(shared[i]);
533 }
534
535 for (; i < count; i++)
536 dma_fence_put(shared[i]);
537 kfree(shared);
e54ca977 538
fa73055b
CW
539 /*
540 * If both shared fences and an exclusive fence exist,
541 * then by construction the shared fences must be later
542 * than the exclusive fence. If we successfully wait for
543 * all the shared fences, we know that the exclusive fence
544 * must all be signaled. If all the shared fences are
545 * signaled, we can prune the array and recover the
546 * floating references on the fences/requests.
547 */
e54ca977 548 prune_fences = count && timeout >= 0;
e95433c7
CW
549 } else {
550 excl = reservation_object_get_excl_rcu(resv);
00e60f26
CW
551 }
552
fa73055b 553 if (excl && timeout >= 0)
562d9bae
SAK
554 timeout = i915_gem_object_wait_fence(excl, flags, timeout,
555 rps_client);
e95433c7
CW
556
557 dma_fence_put(excl);
558
fa73055b
CW
559 /*
560 * Opportunistically prune the fences iff we know they have *all* been
03d1cac6
CW
561 * signaled and that the reservation object has not been changed (i.e.
562 * no new fences have been added).
563 */
e54ca977 564 if (prune_fences && !__read_seqcount_retry(&resv->seq, seq)) {
03d1cac6
CW
565 if (reservation_object_trylock(resv)) {
566 if (!__read_seqcount_retry(&resv->seq, seq))
567 reservation_object_add_excl_fence(resv, NULL);
568 reservation_object_unlock(resv);
569 }
e54ca977
CW
570 }
571
e95433c7 572 return timeout;
00e60f26
CW
573}
574
b7268c5e
CW
575static void __fence_set_priority(struct dma_fence *fence,
576 const struct i915_sched_attr *attr)
6b5e90f5 577{
e61e0f51 578 struct i915_request *rq;
6b5e90f5
CW
579 struct intel_engine_cs *engine;
580
c218ee03 581 if (dma_fence_is_signaled(fence) || !dma_fence_is_i915(fence))
6b5e90f5
CW
582 return;
583
584 rq = to_request(fence);
585 engine = rq->engine;
6b5e90f5 586
4f6d8fcf
CW
587 local_bh_disable();
588 rcu_read_lock(); /* RCU serialisation for set-wedged protection */
47650db0 589 if (engine->schedule)
b7268c5e 590 engine->schedule(rq, attr);
47650db0 591 rcu_read_unlock();
4f6d8fcf 592 local_bh_enable(); /* kick the tasklets if queues were reprioritised */
6b5e90f5
CW
593}
594
b7268c5e
CW
595static void fence_set_priority(struct dma_fence *fence,
596 const struct i915_sched_attr *attr)
6b5e90f5
CW
597{
598 /* Recurse once into a fence-array */
599 if (dma_fence_is_array(fence)) {
600 struct dma_fence_array *array = to_dma_fence_array(fence);
601 int i;
602
603 for (i = 0; i < array->num_fences; i++)
b7268c5e 604 __fence_set_priority(array->fences[i], attr);
6b5e90f5 605 } else {
b7268c5e 606 __fence_set_priority(fence, attr);
6b5e90f5
CW
607 }
608}
609
610int
611i915_gem_object_wait_priority(struct drm_i915_gem_object *obj,
612 unsigned int flags,
b7268c5e 613 const struct i915_sched_attr *attr)
6b5e90f5
CW
614{
615 struct dma_fence *excl;
616
617 if (flags & I915_WAIT_ALL) {
618 struct dma_fence **shared;
619 unsigned int count, i;
620 int ret;
621
622 ret = reservation_object_get_fences_rcu(obj->resv,
623 &excl, &count, &shared);
624 if (ret)
625 return ret;
626
627 for (i = 0; i < count; i++) {
b7268c5e 628 fence_set_priority(shared[i], attr);
6b5e90f5
CW
629 dma_fence_put(shared[i]);
630 }
631
632 kfree(shared);
633 } else {
634 excl = reservation_object_get_excl_rcu(obj->resv);
635 }
636
637 if (excl) {
b7268c5e 638 fence_set_priority(excl, attr);
6b5e90f5
CW
639 dma_fence_put(excl);
640 }
641 return 0;
642}
643
e95433c7
CW
644/**
645 * Waits for rendering to the object to be completed
646 * @obj: i915 gem object
647 * @flags: how to wait (under a lock, for all rendering or just for writes etc)
648 * @timeout: how long to wait
a0a8b1cf 649 * @rps_client: client (user process) to charge for any waitboosting
00e60f26 650 */
e95433c7
CW
651int
652i915_gem_object_wait(struct drm_i915_gem_object *obj,
653 unsigned int flags,
654 long timeout,
562d9bae 655 struct intel_rps_client *rps_client)
00e60f26 656{
e95433c7
CW
657 might_sleep();
658#if IS_ENABLED(CONFIG_LOCKDEP)
659 GEM_BUG_ON(debug_locks &&
660 !!lockdep_is_held(&obj->base.dev->struct_mutex) !=
661 !!(flags & I915_WAIT_LOCKED));
662#endif
663 GEM_BUG_ON(timeout < 0);
00e60f26 664
d07f0e59
CW
665 timeout = i915_gem_object_wait_reservation(obj->resv,
666 flags, timeout,
562d9bae 667 rps_client);
e95433c7 668 return timeout < 0 ? timeout : 0;
00e60f26
CW
669}
670
671static struct intel_rps_client *to_rps_client(struct drm_file *file)
672{
673 struct drm_i915_file_private *fpriv = file->driver_priv;
674
562d9bae 675 return &fpriv->rps_client;
00e60f26
CW
676}
677
00731155
CW
678static int
679i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
680 struct drm_i915_gem_pwrite *args,
03ac84f1 681 struct drm_file *file)
00731155 682{
00731155 683 void *vaddr = obj->phys_handle->vaddr + args->offset;
3ed605bc 684 char __user *user_data = u64_to_user_ptr(args->data_ptr);
6a2c4232
CW
685
686 /* We manually control the domain here and pretend that it
687 * remains coherent i.e. in the GTT domain, like shmem_pwrite.
688 */
77a0d1ca 689 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
10466d2a
CW
690 if (copy_from_user(vaddr, user_data, args->size))
691 return -EFAULT;
00731155 692
6a2c4232 693 drm_clflush_virt_range(vaddr, args->size);
10466d2a 694 i915_gem_chipset_flush(to_i915(obj->base.dev));
063e4e6b 695
d59b21ec 696 intel_fb_obj_flush(obj, ORIGIN_CPU);
10466d2a 697 return 0;
00731155
CW
698}
699
187685cb 700void *i915_gem_object_alloc(struct drm_i915_private *dev_priv)
42dcedd4 701{
efab6d8d 702 return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
42dcedd4
CW
703}
704
705void i915_gem_object_free(struct drm_i915_gem_object *obj)
706{
fac5e23e 707 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
efab6d8d 708 kmem_cache_free(dev_priv->objects, obj);
42dcedd4
CW
709}
710
ff72145b
DA
711static int
712i915_gem_create(struct drm_file *file,
12d79d78 713 struct drm_i915_private *dev_priv,
ff72145b
DA
714 uint64_t size,
715 uint32_t *handle_p)
673a394b 716{
05394f39 717 struct drm_i915_gem_object *obj;
a1a2d1d3
PP
718 int ret;
719 u32 handle;
673a394b 720
ff72145b 721 size = roundup(size, PAGE_SIZE);
8ffc0246
CW
722 if (size == 0)
723 return -EINVAL;
673a394b
EA
724
725 /* Allocate the new object */
12d79d78 726 obj = i915_gem_object_create(dev_priv, size);
fe3db79b
CW
727 if (IS_ERR(obj))
728 return PTR_ERR(obj);
673a394b 729
05394f39 730 ret = drm_gem_handle_create(file, &obj->base, &handle);
202f2fef 731 /* drop reference from allocate - handle holds it now */
f0cd5182 732 i915_gem_object_put(obj);
d861e338
DV
733 if (ret)
734 return ret;
202f2fef 735
ff72145b 736 *handle_p = handle;
673a394b
EA
737 return 0;
738}
739
ff72145b
DA
740int
741i915_gem_dumb_create(struct drm_file *file,
742 struct drm_device *dev,
743 struct drm_mode_create_dumb *args)
744{
745 /* have to work out size/pitch and return them */
de45eaf7 746 args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
ff72145b 747 args->size = args->pitch * args->height;
12d79d78 748 return i915_gem_create(file, to_i915(dev),
da6b51d0 749 args->size, &args->handle);
ff72145b
DA
750}
751
e27ab73d
CW
752static bool gpu_write_needs_clflush(struct drm_i915_gem_object *obj)
753{
754 return !(obj->cache_level == I915_CACHE_NONE ||
755 obj->cache_level == I915_CACHE_WT);
756}
757
ff72145b
DA
758/**
759 * Creates a new mm object and returns a handle to it.
14bb2c11
TU
760 * @dev: drm device pointer
761 * @data: ioctl data blob
762 * @file: drm file pointer
ff72145b
DA
763 */
764int
765i915_gem_create_ioctl(struct drm_device *dev, void *data,
766 struct drm_file *file)
767{
12d79d78 768 struct drm_i915_private *dev_priv = to_i915(dev);
ff72145b 769 struct drm_i915_gem_create *args = data;
63ed2cb2 770
12d79d78 771 i915_gem_flush_free_objects(dev_priv);
fbbd37b3 772
12d79d78 773 return i915_gem_create(file, dev_priv,
da6b51d0 774 args->size, &args->handle);
ff72145b
DA
775}
776
ef74921b
CW
777static inline enum fb_op_origin
778fb_write_origin(struct drm_i915_gem_object *obj, unsigned int domain)
779{
780 return (domain == I915_GEM_DOMAIN_GTT ?
781 obj->frontbuffer_ggtt_origin : ORIGIN_CPU);
782}
783
7125397b 784void i915_gem_flush_ggtt_writes(struct drm_i915_private *dev_priv)
ef74921b 785{
7125397b
CW
786 /*
787 * No actual flushing is required for the GTT write domain for reads
788 * from the GTT domain. Writes to it "immediately" go to main memory
789 * as far as we know, so there's no chipset flush. It also doesn't
790 * land in the GPU render cache.
ef74921b
CW
791 *
792 * However, we do have to enforce the order so that all writes through
793 * the GTT land before any writes to the device, such as updates to
794 * the GATT itself.
795 *
796 * We also have to wait a bit for the writes to land from the GTT.
797 * An uncached read (i.e. mmio) seems to be ideal for the round-trip
798 * timing. This issue has only been observed when switching quickly
799 * between GTT writes and CPU reads from inside the kernel on recent hw,
800 * and it appears to only affect discrete GTT blocks (i.e. on LLC
7125397b
CW
801 * system agents we cannot reproduce this behaviour, until Cannonlake
802 * that was!).
ef74921b 803 */
7125397b 804
ef74921b
CW
805 wmb();
806
7125397b
CW
807 intel_runtime_pm_get(dev_priv);
808 spin_lock_irq(&dev_priv->uncore.lock);
809
810 POSTING_READ_FW(RING_HEAD(RENDER_RING_BASE));
811
812 spin_unlock_irq(&dev_priv->uncore.lock);
813 intel_runtime_pm_put(dev_priv);
814}
815
816static void
817flush_write_domain(struct drm_i915_gem_object *obj, unsigned int flush_domains)
818{
819 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
820 struct i915_vma *vma;
821
c0a51fd0 822 if (!(obj->write_domain & flush_domains))
7125397b
CW
823 return;
824
c0a51fd0 825 switch (obj->write_domain) {
ef74921b 826 case I915_GEM_DOMAIN_GTT:
7125397b 827 i915_gem_flush_ggtt_writes(dev_priv);
ef74921b
CW
828
829 intel_fb_obj_flush(obj,
830 fb_write_origin(obj, I915_GEM_DOMAIN_GTT));
7125397b 831
e2189dd0 832 for_each_ggtt_vma(vma, obj) {
7125397b
CW
833 if (vma->iomap)
834 continue;
835
836 i915_vma_unset_ggtt_write(vma);
837 }
ef74921b
CW
838 break;
839
840 case I915_GEM_DOMAIN_CPU:
841 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
842 break;
e27ab73d
CW
843
844 case I915_GEM_DOMAIN_RENDER:
845 if (gpu_write_needs_clflush(obj))
846 obj->cache_dirty = true;
847 break;
ef74921b
CW
848 }
849
c0a51fd0 850 obj->write_domain = 0;
ef74921b
CW
851}
852
8461d226
DV
853static inline int
854__copy_to_user_swizzled(char __user *cpu_vaddr,
855 const char *gpu_vaddr, int gpu_offset,
856 int length)
857{
858 int ret, cpu_offset = 0;
859
860 while (length > 0) {
861 int cacheline_end = ALIGN(gpu_offset + 1, 64);
862 int this_length = min(cacheline_end - gpu_offset, length);
863 int swizzled_gpu_offset = gpu_offset ^ 64;
864
865 ret = __copy_to_user(cpu_vaddr + cpu_offset,
866 gpu_vaddr + swizzled_gpu_offset,
867 this_length);
868 if (ret)
869 return ret + length;
870
871 cpu_offset += this_length;
872 gpu_offset += this_length;
873 length -= this_length;
874 }
875
876 return 0;
877}
878
8c59967c 879static inline int
4f0c7cfb
BW
880__copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
881 const char __user *cpu_vaddr,
8c59967c
DV
882 int length)
883{
884 int ret, cpu_offset = 0;
885
886 while (length > 0) {
887 int cacheline_end = ALIGN(gpu_offset + 1, 64);
888 int this_length = min(cacheline_end - gpu_offset, length);
889 int swizzled_gpu_offset = gpu_offset ^ 64;
890
891 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
892 cpu_vaddr + cpu_offset,
893 this_length);
894 if (ret)
895 return ret + length;
896
897 cpu_offset += this_length;
898 gpu_offset += this_length;
899 length -= this_length;
900 }
901
902 return 0;
903}
904
4c914c0c
BV
905/*
906 * Pins the specified object's pages and synchronizes the object with
907 * GPU accesses. Sets needs_clflush to non-zero if the caller should
908 * flush the object from the CPU cache.
909 */
910int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
43394c7d 911 unsigned int *needs_clflush)
4c914c0c
BV
912{
913 int ret;
914
e95433c7 915 lockdep_assert_held(&obj->base.dev->struct_mutex);
4c914c0c 916
e95433c7 917 *needs_clflush = 0;
43394c7d
CW
918 if (!i915_gem_object_has_struct_page(obj))
919 return -ENODEV;
4c914c0c 920
e95433c7
CW
921 ret = i915_gem_object_wait(obj,
922 I915_WAIT_INTERRUPTIBLE |
923 I915_WAIT_LOCKED,
924 MAX_SCHEDULE_TIMEOUT,
925 NULL);
c13d87ea
CW
926 if (ret)
927 return ret;
928
a4f5ea64 929 ret = i915_gem_object_pin_pages(obj);
9764951e
CW
930 if (ret)
931 return ret;
932
b8f55be6
CW
933 if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ ||
934 !static_cpu_has(X86_FEATURE_CLFLUSH)) {
7f5f95d8
CW
935 ret = i915_gem_object_set_to_cpu_domain(obj, false);
936 if (ret)
937 goto err_unpin;
938 else
939 goto out;
940 }
941
ef74921b 942 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
a314d5cb 943
43394c7d
CW
944 /* If we're not in the cpu read domain, set ourself into the gtt
945 * read domain and manually flush cachelines (if required). This
946 * optimizes for the case when the gpu will dirty the data
947 * anyway again before the next pread happens.
948 */
e27ab73d 949 if (!obj->cache_dirty &&
c0a51fd0 950 !(obj->read_domains & I915_GEM_DOMAIN_CPU))
7f5f95d8 951 *needs_clflush = CLFLUSH_BEFORE;
4c914c0c 952
7f5f95d8 953out:
9764951e 954 /* return with the pages pinned */
43394c7d 955 return 0;
9764951e
CW
956
957err_unpin:
958 i915_gem_object_unpin_pages(obj);
959 return ret;
43394c7d
CW
960}
961
962int i915_gem_obj_prepare_shmem_write(struct drm_i915_gem_object *obj,
963 unsigned int *needs_clflush)
964{
965 int ret;
966
e95433c7
CW
967 lockdep_assert_held(&obj->base.dev->struct_mutex);
968
43394c7d
CW
969 *needs_clflush = 0;
970 if (!i915_gem_object_has_struct_page(obj))
971 return -ENODEV;
972
e95433c7
CW
973 ret = i915_gem_object_wait(obj,
974 I915_WAIT_INTERRUPTIBLE |
975 I915_WAIT_LOCKED |
976 I915_WAIT_ALL,
977 MAX_SCHEDULE_TIMEOUT,
978 NULL);
43394c7d
CW
979 if (ret)
980 return ret;
981
a4f5ea64 982 ret = i915_gem_object_pin_pages(obj);
9764951e
CW
983 if (ret)
984 return ret;
985
b8f55be6
CW
986 if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE ||
987 !static_cpu_has(X86_FEATURE_CLFLUSH)) {
7f5f95d8
CW
988 ret = i915_gem_object_set_to_cpu_domain(obj, true);
989 if (ret)
990 goto err_unpin;
991 else
992 goto out;
993 }
994
ef74921b 995 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
a314d5cb 996
43394c7d
CW
997 /* If we're not in the cpu write domain, set ourself into the
998 * gtt write domain and manually flush cachelines (as required).
999 * This optimizes for the case when the gpu will use the data
1000 * right away and we therefore have to clflush anyway.
1001 */
e27ab73d 1002 if (!obj->cache_dirty) {
7f5f95d8 1003 *needs_clflush |= CLFLUSH_AFTER;
43394c7d 1004
e27ab73d
CW
1005 /*
1006 * Same trick applies to invalidate partially written
1007 * cachelines read before writing.
1008 */
c0a51fd0 1009 if (!(obj->read_domains & I915_GEM_DOMAIN_CPU))
e27ab73d
CW
1010 *needs_clflush |= CLFLUSH_BEFORE;
1011 }
43394c7d 1012
7f5f95d8 1013out:
43394c7d 1014 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
a4f5ea64 1015 obj->mm.dirty = true;
9764951e 1016 /* return with the pages pinned */
43394c7d 1017 return 0;
9764951e
CW
1018
1019err_unpin:
1020 i915_gem_object_unpin_pages(obj);
1021 return ret;
4c914c0c
BV
1022}
1023
23c18c71
DV
1024static void
1025shmem_clflush_swizzled_range(char *addr, unsigned long length,
1026 bool swizzled)
1027{
e7e58eb5 1028 if (unlikely(swizzled)) {
23c18c71
DV
1029 unsigned long start = (unsigned long) addr;
1030 unsigned long end = (unsigned long) addr + length;
1031
1032 /* For swizzling simply ensure that we always flush both
1033 * channels. Lame, but simple and it works. Swizzled
1034 * pwrite/pread is far from a hotpath - current userspace
1035 * doesn't use it at all. */
1036 start = round_down(start, 128);
1037 end = round_up(end, 128);
1038
1039 drm_clflush_virt_range((void *)start, end - start);
1040 } else {
1041 drm_clflush_virt_range(addr, length);
1042 }
1043
1044}
1045
d174bd64
DV
1046/* Only difference to the fast-path function is that this can handle bit17
1047 * and uses non-atomic copy and kmap functions. */
1048static int
bb6dc8d9 1049shmem_pread_slow(struct page *page, int offset, int length,
d174bd64
DV
1050 char __user *user_data,
1051 bool page_do_bit17_swizzling, bool needs_clflush)
1052{
1053 char *vaddr;
1054 int ret;
1055
1056 vaddr = kmap(page);
1057 if (needs_clflush)
bb6dc8d9 1058 shmem_clflush_swizzled_range(vaddr + offset, length,
23c18c71 1059 page_do_bit17_swizzling);
d174bd64
DV
1060
1061 if (page_do_bit17_swizzling)
bb6dc8d9 1062 ret = __copy_to_user_swizzled(user_data, vaddr, offset, length);
d174bd64 1063 else
bb6dc8d9 1064 ret = __copy_to_user(user_data, vaddr + offset, length);
d174bd64
DV
1065 kunmap(page);
1066
f60d7f0c 1067 return ret ? - EFAULT : 0;
d174bd64
DV
1068}
1069
bb6dc8d9
CW
1070static int
1071shmem_pread(struct page *page, int offset, int length, char __user *user_data,
1072 bool page_do_bit17_swizzling, bool needs_clflush)
1073{
1074 int ret;
1075
1076 ret = -ENODEV;
1077 if (!page_do_bit17_swizzling) {
1078 char *vaddr = kmap_atomic(page);
1079
1080 if (needs_clflush)
1081 drm_clflush_virt_range(vaddr + offset, length);
1082 ret = __copy_to_user_inatomic(user_data, vaddr + offset, length);
1083 kunmap_atomic(vaddr);
1084 }
1085 if (ret == 0)
1086 return 0;
1087
1088 return shmem_pread_slow(page, offset, length, user_data,
1089 page_do_bit17_swizzling, needs_clflush);
1090}
1091
1092static int
1093i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
1094 struct drm_i915_gem_pread *args)
1095{
1096 char __user *user_data;
1097 u64 remain;
1098 unsigned int obj_do_bit17_swizzling;
1099 unsigned int needs_clflush;
1100 unsigned int idx, offset;
1101 int ret;
1102
1103 obj_do_bit17_swizzling = 0;
1104 if (i915_gem_object_needs_bit17_swizzle(obj))
1105 obj_do_bit17_swizzling = BIT(17);
1106
1107 ret = mutex_lock_interruptible(&obj->base.dev->struct_mutex);
1108 if (ret)
1109 return ret;
1110
1111 ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
1112 mutex_unlock(&obj->base.dev->struct_mutex);
1113 if (ret)
1114 return ret;
1115
1116 remain = args->size;
1117 user_data = u64_to_user_ptr(args->data_ptr);
1118 offset = offset_in_page(args->offset);
1119 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1120 struct page *page = i915_gem_object_get_page(obj, idx);
1121 int length;
1122
1123 length = remain;
1124 if (offset + length > PAGE_SIZE)
1125 length = PAGE_SIZE - offset;
1126
1127 ret = shmem_pread(page, offset, length, user_data,
1128 page_to_phys(page) & obj_do_bit17_swizzling,
1129 needs_clflush);
1130 if (ret)
1131 break;
1132
1133 remain -= length;
1134 user_data += length;
1135 offset = 0;
1136 }
1137
1138 i915_gem_obj_finish_shmem_access(obj);
1139 return ret;
1140}
1141
1142static inline bool
1143gtt_user_read(struct io_mapping *mapping,
1144 loff_t base, int offset,
1145 char __user *user_data, int length)
b50a5371 1146{
afe722be 1147 void __iomem *vaddr;
bb6dc8d9 1148 unsigned long unwritten;
b50a5371 1149
b50a5371 1150 /* We can use the cpu mem copy function because this is X86. */
afe722be
VS
1151 vaddr = io_mapping_map_atomic_wc(mapping, base);
1152 unwritten = __copy_to_user_inatomic(user_data,
1153 (void __force *)vaddr + offset,
1154 length);
bb6dc8d9
CW
1155 io_mapping_unmap_atomic(vaddr);
1156 if (unwritten) {
afe722be
VS
1157 vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
1158 unwritten = copy_to_user(user_data,
1159 (void __force *)vaddr + offset,
1160 length);
bb6dc8d9
CW
1161 io_mapping_unmap(vaddr);
1162 }
b50a5371
AS
1163 return unwritten;
1164}
1165
1166static int
bb6dc8d9
CW
1167i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
1168 const struct drm_i915_gem_pread *args)
b50a5371 1169{
bb6dc8d9
CW
1170 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1171 struct i915_ggtt *ggtt = &i915->ggtt;
b50a5371 1172 struct drm_mm_node node;
bb6dc8d9
CW
1173 struct i915_vma *vma;
1174 void __user *user_data;
1175 u64 remain, offset;
b50a5371
AS
1176 int ret;
1177
bb6dc8d9
CW
1178 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1179 if (ret)
1180 return ret;
1181
1182 intel_runtime_pm_get(i915);
1183 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
a3259ca9
CW
1184 PIN_MAPPABLE |
1185 PIN_NONFAULT |
1186 PIN_NONBLOCK);
18034584
CW
1187 if (!IS_ERR(vma)) {
1188 node.start = i915_ggtt_offset(vma);
1189 node.allocated = false;
49ef5294 1190 ret = i915_vma_put_fence(vma);
18034584
CW
1191 if (ret) {
1192 i915_vma_unpin(vma);
1193 vma = ERR_PTR(ret);
1194 }
1195 }
058d88c4 1196 if (IS_ERR(vma)) {
bb6dc8d9 1197 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
b50a5371 1198 if (ret)
bb6dc8d9
CW
1199 goto out_unlock;
1200 GEM_BUG_ON(!node.allocated);
b50a5371
AS
1201 }
1202
1203 ret = i915_gem_object_set_to_gtt_domain(obj, false);
1204 if (ret)
1205 goto out_unpin;
1206
bb6dc8d9 1207 mutex_unlock(&i915->drm.struct_mutex);
b50a5371 1208
bb6dc8d9
CW
1209 user_data = u64_to_user_ptr(args->data_ptr);
1210 remain = args->size;
1211 offset = args->offset;
b50a5371
AS
1212
1213 while (remain > 0) {
1214 /* Operation in this page
1215 *
1216 * page_base = page offset within aperture
1217 * page_offset = offset within page
1218 * page_length = bytes to copy for this page
1219 */
1220 u32 page_base = node.start;
1221 unsigned page_offset = offset_in_page(offset);
1222 unsigned page_length = PAGE_SIZE - page_offset;
1223 page_length = remain < page_length ? remain : page_length;
1224 if (node.allocated) {
1225 wmb();
82ad6443
CW
1226 ggtt->vm.insert_page(&ggtt->vm,
1227 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1228 node.start, I915_CACHE_NONE, 0);
b50a5371
AS
1229 wmb();
1230 } else {
1231 page_base += offset & PAGE_MASK;
1232 }
bb6dc8d9 1233
73ebd503 1234 if (gtt_user_read(&ggtt->iomap, page_base, page_offset,
bb6dc8d9 1235 user_data, page_length)) {
b50a5371
AS
1236 ret = -EFAULT;
1237 break;
1238 }
1239
1240 remain -= page_length;
1241 user_data += page_length;
1242 offset += page_length;
1243 }
1244
bb6dc8d9 1245 mutex_lock(&i915->drm.struct_mutex);
b50a5371
AS
1246out_unpin:
1247 if (node.allocated) {
1248 wmb();
82ad6443 1249 ggtt->vm.clear_range(&ggtt->vm, node.start, node.size);
b50a5371
AS
1250 remove_mappable_node(&node);
1251 } else {
058d88c4 1252 i915_vma_unpin(vma);
b50a5371 1253 }
bb6dc8d9
CW
1254out_unlock:
1255 intel_runtime_pm_put(i915);
1256 mutex_unlock(&i915->drm.struct_mutex);
f60d7f0c 1257
eb01459f
EA
1258 return ret;
1259}
1260
673a394b
EA
1261/**
1262 * Reads data from the object referenced by handle.
14bb2c11
TU
1263 * @dev: drm device pointer
1264 * @data: ioctl data blob
1265 * @file: drm file pointer
673a394b
EA
1266 *
1267 * On error, the contents of *data are undefined.
1268 */
1269int
1270i915_gem_pread_ioctl(struct drm_device *dev, void *data,
05394f39 1271 struct drm_file *file)
673a394b
EA
1272{
1273 struct drm_i915_gem_pread *args = data;
05394f39 1274 struct drm_i915_gem_object *obj;
bb6dc8d9 1275 int ret;
673a394b 1276
51311d0a
CW
1277 if (args->size == 0)
1278 return 0;
1279
1280 if (!access_ok(VERIFY_WRITE,
3ed605bc 1281 u64_to_user_ptr(args->data_ptr),
51311d0a
CW
1282 args->size))
1283 return -EFAULT;
1284
03ac0642 1285 obj = i915_gem_object_lookup(file, args->handle);
258a5ede
CW
1286 if (!obj)
1287 return -ENOENT;
673a394b 1288
7dcd2499 1289 /* Bounds check source. */
966d5bf5 1290 if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
ce9d419d 1291 ret = -EINVAL;
bb6dc8d9 1292 goto out;
ce9d419d
CW
1293 }
1294
db53a302
CW
1295 trace_i915_gem_object_pread(obj, args->offset, args->size);
1296
e95433c7
CW
1297 ret = i915_gem_object_wait(obj,
1298 I915_WAIT_INTERRUPTIBLE,
1299 MAX_SCHEDULE_TIMEOUT,
1300 to_rps_client(file));
258a5ede 1301 if (ret)
bb6dc8d9 1302 goto out;
258a5ede 1303
bb6dc8d9 1304 ret = i915_gem_object_pin_pages(obj);
258a5ede 1305 if (ret)
bb6dc8d9 1306 goto out;
673a394b 1307
bb6dc8d9 1308 ret = i915_gem_shmem_pread(obj, args);
9c870d03 1309 if (ret == -EFAULT || ret == -ENODEV)
bb6dc8d9 1310 ret = i915_gem_gtt_pread(obj, args);
b50a5371 1311
bb6dc8d9
CW
1312 i915_gem_object_unpin_pages(obj);
1313out:
f0cd5182 1314 i915_gem_object_put(obj);
eb01459f 1315 return ret;
673a394b
EA
1316}
1317
0839ccb8
KP
1318/* This is the fast write path which cannot handle
1319 * page faults in the source data
9b7530cc 1320 */
0839ccb8 1321
fe115628
CW
1322static inline bool
1323ggtt_write(struct io_mapping *mapping,
1324 loff_t base, int offset,
1325 char __user *user_data, int length)
9b7530cc 1326{
afe722be 1327 void __iomem *vaddr;
0839ccb8 1328 unsigned long unwritten;
9b7530cc 1329
4f0c7cfb 1330 /* We can use the cpu mem copy function because this is X86. */
afe722be
VS
1331 vaddr = io_mapping_map_atomic_wc(mapping, base);
1332 unwritten = __copy_from_user_inatomic_nocache((void __force *)vaddr + offset,
0839ccb8 1333 user_data, length);
fe115628
CW
1334 io_mapping_unmap_atomic(vaddr);
1335 if (unwritten) {
afe722be
VS
1336 vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
1337 unwritten = copy_from_user((void __force *)vaddr + offset,
1338 user_data, length);
fe115628
CW
1339 io_mapping_unmap(vaddr);
1340 }
bb6dc8d9 1341
bb6dc8d9
CW
1342 return unwritten;
1343}
1344
3de09aa3
EA
1345/**
1346 * This is the fast pwrite path, where we copy the data directly from the
1347 * user into the GTT, uncached.
fe115628 1348 * @obj: i915 GEM object
14bb2c11 1349 * @args: pwrite arguments structure
3de09aa3 1350 */
673a394b 1351static int
fe115628
CW
1352i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
1353 const struct drm_i915_gem_pwrite *args)
673a394b 1354{
fe115628 1355 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4f1959ee
AS
1356 struct i915_ggtt *ggtt = &i915->ggtt;
1357 struct drm_mm_node node;
fe115628
CW
1358 struct i915_vma *vma;
1359 u64 remain, offset;
1360 void __user *user_data;
4f1959ee 1361 int ret;
b50a5371 1362
fe115628
CW
1363 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1364 if (ret)
1365 return ret;
935aaa69 1366
8bd81815
CW
1367 if (i915_gem_object_has_struct_page(obj)) {
1368 /*
1369 * Avoid waking the device up if we can fallback, as
1370 * waking/resuming is very slow (worst-case 10-100 ms
1371 * depending on PCI sleeps and our own resume time).
1372 * This easily dwarfs any performance advantage from
1373 * using the cache bypass of indirect GGTT access.
1374 */
1375 if (!intel_runtime_pm_get_if_in_use(i915)) {
1376 ret = -EFAULT;
1377 goto out_unlock;
1378 }
1379 } else {
1380 /* No backing pages, no fallback, we must force GGTT access */
1381 intel_runtime_pm_get(i915);
1382 }
1383
058d88c4 1384 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
a3259ca9
CW
1385 PIN_MAPPABLE |
1386 PIN_NONFAULT |
1387 PIN_NONBLOCK);
18034584
CW
1388 if (!IS_ERR(vma)) {
1389 node.start = i915_ggtt_offset(vma);
1390 node.allocated = false;
49ef5294 1391 ret = i915_vma_put_fence(vma);
18034584
CW
1392 if (ret) {
1393 i915_vma_unpin(vma);
1394 vma = ERR_PTR(ret);
1395 }
1396 }
058d88c4 1397 if (IS_ERR(vma)) {
bb6dc8d9 1398 ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
4f1959ee 1399 if (ret)
8bd81815 1400 goto out_rpm;
fe115628 1401 GEM_BUG_ON(!node.allocated);
4f1959ee 1402 }
935aaa69
DV
1403
1404 ret = i915_gem_object_set_to_gtt_domain(obj, true);
1405 if (ret)
1406 goto out_unpin;
1407
fe115628
CW
1408 mutex_unlock(&i915->drm.struct_mutex);
1409
b19482d7 1410 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
063e4e6b 1411
4f1959ee
AS
1412 user_data = u64_to_user_ptr(args->data_ptr);
1413 offset = args->offset;
1414 remain = args->size;
1415 while (remain) {
673a394b
EA
1416 /* Operation in this page
1417 *
0839ccb8
KP
1418 * page_base = page offset within aperture
1419 * page_offset = offset within page
1420 * page_length = bytes to copy for this page
673a394b 1421 */
4f1959ee 1422 u32 page_base = node.start;
bb6dc8d9
CW
1423 unsigned int page_offset = offset_in_page(offset);
1424 unsigned int page_length = PAGE_SIZE - page_offset;
4f1959ee
AS
1425 page_length = remain < page_length ? remain : page_length;
1426 if (node.allocated) {
1427 wmb(); /* flush the write before we modify the GGTT */
82ad6443
CW
1428 ggtt->vm.insert_page(&ggtt->vm,
1429 i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
1430 node.start, I915_CACHE_NONE, 0);
4f1959ee
AS
1431 wmb(); /* flush modifications to the GGTT (insert_page) */
1432 } else {
1433 page_base += offset & PAGE_MASK;
1434 }
0839ccb8 1435 /* If we get a fault while copying data, then (presumably) our
3de09aa3
EA
1436 * source page isn't available. Return the error and we'll
1437 * retry in the slow path.
b50a5371
AS
1438 * If the object is non-shmem backed, we retry again with the
1439 * path that handles page fault.
0839ccb8 1440 */
73ebd503 1441 if (ggtt_write(&ggtt->iomap, page_base, page_offset,
fe115628
CW
1442 user_data, page_length)) {
1443 ret = -EFAULT;
1444 break;
935aaa69 1445 }
673a394b 1446
0839ccb8
KP
1447 remain -= page_length;
1448 user_data += page_length;
1449 offset += page_length;
673a394b 1450 }
d59b21ec 1451 intel_fb_obj_flush(obj, ORIGIN_CPU);
fe115628
CW
1452
1453 mutex_lock(&i915->drm.struct_mutex);
935aaa69 1454out_unpin:
4f1959ee
AS
1455 if (node.allocated) {
1456 wmb();
82ad6443 1457 ggtt->vm.clear_range(&ggtt->vm, node.start, node.size);
4f1959ee
AS
1458 remove_mappable_node(&node);
1459 } else {
058d88c4 1460 i915_vma_unpin(vma);
4f1959ee 1461 }
8bd81815 1462out_rpm:
9c870d03 1463 intel_runtime_pm_put(i915);
8bd81815 1464out_unlock:
fe115628 1465 mutex_unlock(&i915->drm.struct_mutex);
3de09aa3 1466 return ret;
673a394b
EA
1467}
1468
3043c60c 1469static int
fe115628 1470shmem_pwrite_slow(struct page *page, int offset, int length,
d174bd64
DV
1471 char __user *user_data,
1472 bool page_do_bit17_swizzling,
1473 bool needs_clflush_before,
1474 bool needs_clflush_after)
673a394b 1475{
d174bd64
DV
1476 char *vaddr;
1477 int ret;
e5281ccd 1478
d174bd64 1479 vaddr = kmap(page);
e7e58eb5 1480 if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
fe115628 1481 shmem_clflush_swizzled_range(vaddr + offset, length,
23c18c71 1482 page_do_bit17_swizzling);
d174bd64 1483 if (page_do_bit17_swizzling)
fe115628
CW
1484 ret = __copy_from_user_swizzled(vaddr, offset, user_data,
1485 length);
d174bd64 1486 else
fe115628 1487 ret = __copy_from_user(vaddr + offset, user_data, length);
d174bd64 1488 if (needs_clflush_after)
fe115628 1489 shmem_clflush_swizzled_range(vaddr + offset, length,
23c18c71 1490 page_do_bit17_swizzling);
d174bd64 1491 kunmap(page);
40123c1f 1492
755d2218 1493 return ret ? -EFAULT : 0;
40123c1f
EA
1494}
1495
fe115628
CW
1496/* Per-page copy function for the shmem pwrite fastpath.
1497 * Flushes invalid cachelines before writing to the target if
1498 * needs_clflush_before is set and flushes out any written cachelines after
1499 * writing if needs_clflush is set.
1500 */
40123c1f 1501static int
fe115628
CW
1502shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
1503 bool page_do_bit17_swizzling,
1504 bool needs_clflush_before,
1505 bool needs_clflush_after)
40123c1f 1506{
fe115628
CW
1507 int ret;
1508
1509 ret = -ENODEV;
1510 if (!page_do_bit17_swizzling) {
1511 char *vaddr = kmap_atomic(page);
1512
1513 if (needs_clflush_before)
1514 drm_clflush_virt_range(vaddr + offset, len);
1515 ret = __copy_from_user_inatomic(vaddr + offset, user_data, len);
1516 if (needs_clflush_after)
1517 drm_clflush_virt_range(vaddr + offset, len);
1518
1519 kunmap_atomic(vaddr);
1520 }
1521 if (ret == 0)
1522 return ret;
1523
1524 return shmem_pwrite_slow(page, offset, len, user_data,
1525 page_do_bit17_swizzling,
1526 needs_clflush_before,
1527 needs_clflush_after);
1528}
1529
1530static int
1531i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
1532 const struct drm_i915_gem_pwrite *args)
1533{
1534 struct drm_i915_private *i915 = to_i915(obj->base.dev);
1535 void __user *user_data;
1536 u64 remain;
1537 unsigned int obj_do_bit17_swizzling;
1538 unsigned int partial_cacheline_write;
43394c7d 1539 unsigned int needs_clflush;
fe115628
CW
1540 unsigned int offset, idx;
1541 int ret;
40123c1f 1542
fe115628 1543 ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
755d2218
CW
1544 if (ret)
1545 return ret;
1546
fe115628
CW
1547 ret = i915_gem_obj_prepare_shmem_write(obj, &needs_clflush);
1548 mutex_unlock(&i915->drm.struct_mutex);
1549 if (ret)
1550 return ret;
673a394b 1551
fe115628
CW
1552 obj_do_bit17_swizzling = 0;
1553 if (i915_gem_object_needs_bit17_swizzle(obj))
1554 obj_do_bit17_swizzling = BIT(17);
e5281ccd 1555
fe115628
CW
1556 /* If we don't overwrite a cacheline completely we need to be
1557 * careful to have up-to-date data by first clflushing. Don't
1558 * overcomplicate things and flush the entire patch.
1559 */
1560 partial_cacheline_write = 0;
1561 if (needs_clflush & CLFLUSH_BEFORE)
1562 partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
9da3da66 1563
fe115628
CW
1564 user_data = u64_to_user_ptr(args->data_ptr);
1565 remain = args->size;
1566 offset = offset_in_page(args->offset);
1567 for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
1568 struct page *page = i915_gem_object_get_page(obj, idx);
1569 int length;
40123c1f 1570
fe115628
CW
1571 length = remain;
1572 if (offset + length > PAGE_SIZE)
1573 length = PAGE_SIZE - offset;
755d2218 1574
fe115628
CW
1575 ret = shmem_pwrite(page, offset, length, user_data,
1576 page_to_phys(page) & obj_do_bit17_swizzling,
1577 (offset | length) & partial_cacheline_write,
1578 needs_clflush & CLFLUSH_AFTER);
755d2218 1579 if (ret)
fe115628 1580 break;
755d2218 1581
fe115628
CW
1582 remain -= length;
1583 user_data += length;
1584 offset = 0;
8c59967c 1585 }
673a394b 1586
d59b21ec 1587 intel_fb_obj_flush(obj, ORIGIN_CPU);
fe115628 1588 i915_gem_obj_finish_shmem_access(obj);
40123c1f 1589 return ret;
673a394b
EA
1590}
1591
1592/**
1593 * Writes data to the object referenced by handle.
14bb2c11
TU
1594 * @dev: drm device
1595 * @data: ioctl data blob
1596 * @file: drm file
673a394b
EA
1597 *
1598 * On error, the contents of the buffer that were to be modified are undefined.
1599 */
1600int
1601i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
fbd5a26d 1602 struct drm_file *file)
673a394b
EA
1603{
1604 struct drm_i915_gem_pwrite *args = data;
05394f39 1605 struct drm_i915_gem_object *obj;
51311d0a
CW
1606 int ret;
1607
1608 if (args->size == 0)
1609 return 0;
1610
1611 if (!access_ok(VERIFY_READ,
3ed605bc 1612 u64_to_user_ptr(args->data_ptr),
51311d0a
CW
1613 args->size))
1614 return -EFAULT;
1615
03ac0642 1616 obj = i915_gem_object_lookup(file, args->handle);
258a5ede
CW
1617 if (!obj)
1618 return -ENOENT;
673a394b 1619
7dcd2499 1620 /* Bounds check destination. */
966d5bf5 1621 if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
ce9d419d 1622 ret = -EINVAL;
258a5ede 1623 goto err;
ce9d419d
CW
1624 }
1625
db53a302
CW
1626 trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1627
7c55e2c5
CW
1628 ret = -ENODEV;
1629 if (obj->ops->pwrite)
1630 ret = obj->ops->pwrite(obj, args);
1631 if (ret != -ENODEV)
1632 goto err;
1633
e95433c7
CW
1634 ret = i915_gem_object_wait(obj,
1635 I915_WAIT_INTERRUPTIBLE |
1636 I915_WAIT_ALL,
1637 MAX_SCHEDULE_TIMEOUT,
1638 to_rps_client(file));
258a5ede
CW
1639 if (ret)
1640 goto err;
1641
fe115628 1642 ret = i915_gem_object_pin_pages(obj);
258a5ede 1643 if (ret)
fe115628 1644 goto err;
258a5ede 1645
935aaa69 1646 ret = -EFAULT;
673a394b
EA
1647 /* We can only do the GTT pwrite on untiled buffers, as otherwise
1648 * it would end up going through the fenced access, and we'll get
1649 * different detiling behavior between reading and writing.
1650 * pread/pwrite currently are reading and writing from the CPU
1651 * perspective, requiring manual detiling by the client.
1652 */
6eae0059 1653 if (!i915_gem_object_has_struct_page(obj) ||
9c870d03 1654 cpu_write_needs_clflush(obj))
935aaa69
DV
1655 /* Note that the gtt paths might fail with non-page-backed user
1656 * pointers (e.g. gtt mappings when moving data between
9c870d03
CW
1657 * textures). Fallback to the shmem path in that case.
1658 */
fe115628 1659 ret = i915_gem_gtt_pwrite_fast(obj, args);
673a394b 1660
d1054ee4 1661 if (ret == -EFAULT || ret == -ENOSPC) {
6a2c4232
CW
1662 if (obj->phys_handle)
1663 ret = i915_gem_phys_pwrite(obj, args, file);
b50a5371 1664 else
fe115628 1665 ret = i915_gem_shmem_pwrite(obj, args);
6a2c4232 1666 }
5c0480f2 1667
fe115628 1668 i915_gem_object_unpin_pages(obj);
258a5ede 1669err:
f0cd5182 1670 i915_gem_object_put(obj);
258a5ede 1671 return ret;
673a394b
EA
1672}
1673
40e62d5d
CW
1674static void i915_gem_object_bump_inactive_ggtt(struct drm_i915_gem_object *obj)
1675{
1676 struct drm_i915_private *i915;
1677 struct list_head *list;
1678 struct i915_vma *vma;
1679
f2123818
CW
1680 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
1681
e2189dd0 1682 for_each_ggtt_vma(vma, obj) {
40e62d5d
CW
1683 if (i915_vma_is_active(vma))
1684 continue;
1685
1686 if (!drm_mm_node_allocated(&vma->node))
1687 continue;
1688
1689 list_move_tail(&vma->vm_link, &vma->vm->inactive_list);
1690 }
1691
1692 i915 = to_i915(obj->base.dev);
f2123818 1693 spin_lock(&i915->mm.obj_lock);
40e62d5d 1694 list = obj->bind_count ? &i915->mm.bound_list : &i915->mm.unbound_list;
f2123818
CW
1695 list_move_tail(&obj->mm.link, list);
1696 spin_unlock(&i915->mm.obj_lock);
40e62d5d
CW
1697}
1698
673a394b 1699/**
2ef7eeaa
EA
1700 * Called when user space prepares to use an object with the CPU, either
1701 * through the mmap ioctl's mapping or a GTT mapping.
14bb2c11
TU
1702 * @dev: drm device
1703 * @data: ioctl data blob
1704 * @file: drm file
673a394b
EA
1705 */
1706int
1707i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
05394f39 1708 struct drm_file *file)
673a394b
EA
1709{
1710 struct drm_i915_gem_set_domain *args = data;
05394f39 1711 struct drm_i915_gem_object *obj;
2ef7eeaa
EA
1712 uint32_t read_domains = args->read_domains;
1713 uint32_t write_domain = args->write_domain;
40e62d5d 1714 int err;
673a394b 1715
2ef7eeaa 1716 /* Only handle setting domains to types used by the CPU. */
b8f9096d 1717 if ((write_domain | read_domains) & I915_GEM_GPU_DOMAINS)
2ef7eeaa
EA
1718 return -EINVAL;
1719
1720 /* Having something in the write domain implies it's in the read
1721 * domain, and only that read domain. Enforce that in the request.
1722 */
1723 if (write_domain != 0 && read_domains != write_domain)
1724 return -EINVAL;
1725
03ac0642 1726 obj = i915_gem_object_lookup(file, args->handle);
b8f9096d
CW
1727 if (!obj)
1728 return -ENOENT;
673a394b 1729
3236f57a
CW
1730 /* Try to flush the object off the GPU without holding the lock.
1731 * We will repeat the flush holding the lock in the normal manner
1732 * to catch cases where we are gazumped.
1733 */
40e62d5d 1734 err = i915_gem_object_wait(obj,
e95433c7
CW
1735 I915_WAIT_INTERRUPTIBLE |
1736 (write_domain ? I915_WAIT_ALL : 0),
1737 MAX_SCHEDULE_TIMEOUT,
1738 to_rps_client(file));
40e62d5d 1739 if (err)
f0cd5182 1740 goto out;
b8f9096d 1741
a03f395a
TZ
1742 /*
1743 * Proxy objects do not control access to the backing storage, ergo
1744 * they cannot be used as a means to manipulate the cache domain
1745 * tracking for that backing storage. The proxy object is always
1746 * considered to be outside of any cache domain.
1747 */
1748 if (i915_gem_object_is_proxy(obj)) {
1749 err = -ENXIO;
1750 goto out;
1751 }
1752
1753 /*
1754 * Flush and acquire obj->pages so that we are coherent through
40e62d5d
CW
1755 * direct access in memory with previous cached writes through
1756 * shmemfs and that our cache domain tracking remains valid.
1757 * For example, if the obj->filp was moved to swap without us
1758 * being notified and releasing the pages, we would mistakenly
1759 * continue to assume that the obj remained out of the CPU cached
1760 * domain.
1761 */
1762 err = i915_gem_object_pin_pages(obj);
1763 if (err)
f0cd5182 1764 goto out;
40e62d5d
CW
1765
1766 err = i915_mutex_lock_interruptible(dev);
1767 if (err)
f0cd5182 1768 goto out_unpin;
3236f57a 1769
e22d8e3c
CW
1770 if (read_domains & I915_GEM_DOMAIN_WC)
1771 err = i915_gem_object_set_to_wc_domain(obj, write_domain);
1772 else if (read_domains & I915_GEM_DOMAIN_GTT)
1773 err = i915_gem_object_set_to_gtt_domain(obj, write_domain);
43566ded 1774 else
e22d8e3c 1775 err = i915_gem_object_set_to_cpu_domain(obj, write_domain);
2ef7eeaa 1776
40e62d5d
CW
1777 /* And bump the LRU for this access */
1778 i915_gem_object_bump_inactive_ggtt(obj);
031b698a 1779
673a394b 1780 mutex_unlock(&dev->struct_mutex);
b8f9096d 1781
40e62d5d 1782 if (write_domain != 0)
ef74921b
CW
1783 intel_fb_obj_invalidate(obj,
1784 fb_write_origin(obj, write_domain));
40e62d5d 1785
f0cd5182 1786out_unpin:
40e62d5d 1787 i915_gem_object_unpin_pages(obj);
f0cd5182
CW
1788out:
1789 i915_gem_object_put(obj);
40e62d5d 1790 return err;
673a394b
EA
1791}
1792
1793/**
1794 * Called when user space has done writes to this buffer
14bb2c11
TU
1795 * @dev: drm device
1796 * @data: ioctl data blob
1797 * @file: drm file
673a394b
EA
1798 */
1799int
1800i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
05394f39 1801 struct drm_file *file)
673a394b
EA
1802{
1803 struct drm_i915_gem_sw_finish *args = data;
05394f39 1804 struct drm_i915_gem_object *obj;
1d7cfea1 1805
03ac0642 1806 obj = i915_gem_object_lookup(file, args->handle);
c21724cc
CW
1807 if (!obj)
1808 return -ENOENT;
673a394b 1809
a03f395a
TZ
1810 /*
1811 * Proxy objects are barred from CPU access, so there is no
1812 * need to ban sw_finish as it is a nop.
1813 */
1814
673a394b 1815 /* Pinned buffers may be scanout, so flush the cache */
5a97bcc6 1816 i915_gem_object_flush_if_display(obj);
f0cd5182 1817 i915_gem_object_put(obj);
5a97bcc6
CW
1818
1819 return 0;
673a394b
EA
1820}
1821
1822/**
14bb2c11
TU
1823 * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
1824 * it is mapped to.
1825 * @dev: drm device
1826 * @data: ioctl data blob
1827 * @file: drm file
673a394b
EA
1828 *
1829 * While the mapping holds a reference on the contents of the object, it doesn't
1830 * imply a ref on the object itself.
34367381
DV
1831 *
1832 * IMPORTANT:
1833 *
1834 * DRM driver writers who look a this function as an example for how to do GEM
1835 * mmap support, please don't implement mmap support like here. The modern way
1836 * to implement DRM mmap support is with an mmap offset ioctl (like
1837 * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1838 * That way debug tooling like valgrind will understand what's going on, hiding
1839 * the mmap call in a driver private ioctl will break that. The i915 driver only
1840 * does cpu mmaps this way because we didn't know better.
673a394b
EA
1841 */
1842int
1843i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
05394f39 1844 struct drm_file *file)
673a394b
EA
1845{
1846 struct drm_i915_gem_mmap *args = data;
03ac0642 1847 struct drm_i915_gem_object *obj;
673a394b
EA
1848 unsigned long addr;
1849
1816f923
AG
1850 if (args->flags & ~(I915_MMAP_WC))
1851 return -EINVAL;
1852
568a58e5 1853 if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
1816f923
AG
1854 return -ENODEV;
1855
03ac0642
CW
1856 obj = i915_gem_object_lookup(file, args->handle);
1857 if (!obj)
bf79cb91 1858 return -ENOENT;
673a394b 1859
1286ff73
DV
1860 /* prime objects have no backing filp to GEM mmap
1861 * pages from.
1862 */
03ac0642 1863 if (!obj->base.filp) {
f0cd5182 1864 i915_gem_object_put(obj);
274b2462 1865 return -ENXIO;
1286ff73
DV
1866 }
1867
03ac0642 1868 addr = vm_mmap(obj->base.filp, 0, args->size,
673a394b
EA
1869 PROT_READ | PROT_WRITE, MAP_SHARED,
1870 args->offset);
1816f923
AG
1871 if (args->flags & I915_MMAP_WC) {
1872 struct mm_struct *mm = current->mm;
1873 struct vm_area_struct *vma;
1874
80a89a5e 1875 if (down_write_killable(&mm->mmap_sem)) {
f0cd5182 1876 i915_gem_object_put(obj);
80a89a5e
MH
1877 return -EINTR;
1878 }
1816f923
AG
1879 vma = find_vma(mm, addr);
1880 if (vma)
1881 vma->vm_page_prot =
1882 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1883 else
1884 addr = -ENOMEM;
1885 up_write(&mm->mmap_sem);
aeecc969
CW
1886
1887 /* This may race, but that's ok, it only gets set */
50349247 1888 WRITE_ONCE(obj->frontbuffer_ggtt_origin, ORIGIN_CPU);
1816f923 1889 }
f0cd5182 1890 i915_gem_object_put(obj);
673a394b
EA
1891 if (IS_ERR((void *)addr))
1892 return addr;
1893
1894 args->addr_ptr = (uint64_t) addr;
1895
1896 return 0;
1897}
1898
03af84fe
CW
1899static unsigned int tile_row_pages(struct drm_i915_gem_object *obj)
1900{
6649a0b6 1901 return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
03af84fe
CW
1902}
1903
4cc69075
CW
1904/**
1905 * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
1906 *
1907 * A history of the GTT mmap interface:
1908 *
1909 * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
1910 * aligned and suitable for fencing, and still fit into the available
1911 * mappable space left by the pinned display objects. A classic problem
1912 * we called the page-fault-of-doom where we would ping-pong between
1913 * two objects that could not fit inside the GTT and so the memcpy
1914 * would page one object in at the expense of the other between every
1915 * single byte.
1916 *
1917 * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
1918 * as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
1919 * object is too large for the available space (or simply too large
1920 * for the mappable aperture!), a view is created instead and faulted
1921 * into userspace. (This view is aligned and sized appropriately for
1922 * fenced access.)
1923 *
e22d8e3c
CW
1924 * 2 - Recognise WC as a separate cache domain so that we can flush the
1925 * delayed writes via GTT before performing direct access via WC.
1926 *
4cc69075
CW
1927 * Restrictions:
1928 *
1929 * * snoopable objects cannot be accessed via the GTT. It can cause machine
1930 * hangs on some architectures, corruption on others. An attempt to service
1931 * a GTT page fault from a snoopable object will generate a SIGBUS.
1932 *
1933 * * the object must be able to fit into RAM (physical memory, though no
1934 * limited to the mappable aperture).
1935 *
1936 *
1937 * Caveats:
1938 *
1939 * * a new GTT page fault will synchronize rendering from the GPU and flush
1940 * all data to system memory. Subsequent access will not be synchronized.
1941 *
1942 * * all mappings are revoked on runtime device suspend.
1943 *
1944 * * there are only 8, 16 or 32 fence registers to share between all users
1945 * (older machines require fence register for display and blitter access
1946 * as well). Contention of the fence registers will cause the previous users
1947 * to be unmapped and any new access will generate new page faults.
1948 *
1949 * * running out of memory while servicing a fault may generate a SIGBUS,
1950 * rather than the expected SIGSEGV.
1951 */
1952int i915_gem_mmap_gtt_version(void)
1953{
e22d8e3c 1954 return 2;
4cc69075
CW
1955}
1956
2d4281bb
CW
1957static inline struct i915_ggtt_view
1958compute_partial_view(struct drm_i915_gem_object *obj,
2d4281bb
CW
1959 pgoff_t page_offset,
1960 unsigned int chunk)
1961{
1962 struct i915_ggtt_view view;
1963
1964 if (i915_gem_object_is_tiled(obj))
1965 chunk = roundup(chunk, tile_row_pages(obj));
1966
2d4281bb 1967 view.type = I915_GGTT_VIEW_PARTIAL;
8bab1193
CW
1968 view.partial.offset = rounddown(page_offset, chunk);
1969 view.partial.size =
2d4281bb 1970 min_t(unsigned int, chunk,
8bab1193 1971 (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
2d4281bb
CW
1972
1973 /* If the partial covers the entire object, just create a normal VMA. */
1974 if (chunk >= obj->base.size >> PAGE_SHIFT)
1975 view.type = I915_GGTT_VIEW_NORMAL;
1976
1977 return view;
1978}
1979
de151cf6
JB
1980/**
1981 * i915_gem_fault - fault a page into the GTT
d9072a3e 1982 * @vmf: fault info
de151cf6
JB
1983 *
1984 * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
1985 * from userspace. The fault handler takes care of binding the object to
1986 * the GTT (if needed), allocating and programming a fence register (again,
1987 * only if needed based on whether the old reg is still valid or the object
1988 * is tiled) and inserting a new PTE into the faulting process.
1989 *
1990 * Note that the faulting process may involve evicting existing objects
1991 * from the GTT and/or fence registers to make room. So performance may
1992 * suffer if the GTT working set is large or there are few fence registers
1993 * left.
4cc69075
CW
1994 *
1995 * The current feature set supported by i915_gem_fault() and thus GTT mmaps
1996 * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
de151cf6 1997 */
52137010 1998vm_fault_t i915_gem_fault(struct vm_fault *vmf)
de151cf6 1999{
420980ca 2000#define MIN_CHUNK_PAGES (SZ_1M >> PAGE_SHIFT)
11bac800 2001 struct vm_area_struct *area = vmf->vma;
058d88c4 2002 struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
05394f39 2003 struct drm_device *dev = obj->base.dev;
72e96d64
JL
2004 struct drm_i915_private *dev_priv = to_i915(dev);
2005 struct i915_ggtt *ggtt = &dev_priv->ggtt;
b8f9096d 2006 bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
058d88c4 2007 struct i915_vma *vma;
de151cf6 2008 pgoff_t page_offset;
82118877 2009 unsigned int flags;
b8f9096d 2010 int ret;
f65c9168 2011
de151cf6 2012 /* We don't use vmf->pgoff since that has the fake offset */
1a29d85e 2013 page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
de151cf6 2014
db53a302
CW
2015 trace_i915_gem_object_fault(obj, page_offset, true, write);
2016
6e4930f6 2017 /* Try to flush the object off the GPU first without holding the lock.
b8f9096d 2018 * Upon acquiring the lock, we will perform our sanity checks and then
6e4930f6
CW
2019 * repeat the flush holding the lock in the normal manner to catch cases
2020 * where we are gazumped.
2021 */
e95433c7
CW
2022 ret = i915_gem_object_wait(obj,
2023 I915_WAIT_INTERRUPTIBLE,
2024 MAX_SCHEDULE_TIMEOUT,
2025 NULL);
6e4930f6 2026 if (ret)
b8f9096d
CW
2027 goto err;
2028
40e62d5d
CW
2029 ret = i915_gem_object_pin_pages(obj);
2030 if (ret)
2031 goto err;
2032
b8f9096d
CW
2033 intel_runtime_pm_get(dev_priv);
2034
2035 ret = i915_mutex_lock_interruptible(dev);
2036 if (ret)
2037 goto err_rpm;
6e4930f6 2038
eb119bd6 2039 /* Access to snoopable pages through the GTT is incoherent. */
0031fb96 2040 if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
ddeff6ee 2041 ret = -EFAULT;
b8f9096d 2042 goto err_unlock;
eb119bd6
CW
2043 }
2044
82118877
CW
2045 /* If the object is smaller than a couple of partial vma, it is
2046 * not worth only creating a single partial vma - we may as well
2047 * clear enough space for the full object.
2048 */
2049 flags = PIN_MAPPABLE;
2050 if (obj->base.size > 2 * MIN_CHUNK_PAGES << PAGE_SHIFT)
2051 flags |= PIN_NONBLOCK | PIN_NONFAULT;
2052
a61007a8 2053 /* Now pin it into the GTT as needed */
82118877 2054 vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, flags);
a61007a8 2055 if (IS_ERR(vma)) {
a61007a8 2056 /* Use a partial view if it is bigger than available space */
2d4281bb 2057 struct i915_ggtt_view view =
8201c1fa 2058 compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
aa136d9d 2059
50349247
CW
2060 /* Userspace is now writing through an untracked VMA, abandon
2061 * all hope that the hardware is able to track future writes.
2062 */
2063 obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
2064
a61007a8
CW
2065 vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
2066 }
058d88c4
CW
2067 if (IS_ERR(vma)) {
2068 ret = PTR_ERR(vma);
b8f9096d 2069 goto err_unlock;
058d88c4 2070 }
4a684a41 2071
c9839303
CW
2072 ret = i915_gem_object_set_to_gtt_domain(obj, write);
2073 if (ret)
b8f9096d 2074 goto err_unpin;
74898d7e 2075
3bd40735 2076 ret = i915_vma_pin_fence(vma);
d9e86c0e 2077 if (ret)
b8f9096d 2078 goto err_unpin;
7d1c4804 2079
b90b91d8 2080 /* Finally, remap it using the new GTT offset */
c58305af 2081 ret = remap_io_mapping(area,
8bab1193 2082 area->vm_start + (vma->ggtt_view.partial.offset << PAGE_SHIFT),
73ebd503 2083 (ggtt->gmadr.start + vma->node.start) >> PAGE_SHIFT,
c58305af 2084 min_t(u64, vma->size, area->vm_end - area->vm_start),
73ebd503 2085 &ggtt->iomap);
a65adaf8
CW
2086 if (ret)
2087 goto err_fence;
a61007a8 2088
a65adaf8
CW
2089 /* Mark as being mmapped into userspace for later revocation */
2090 assert_rpm_wakelock_held(dev_priv);
2091 if (!i915_vma_set_userfault(vma) && !obj->userfault_count++)
2092 list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
2093 GEM_BUG_ON(!obj->userfault_count);
2094
7125397b
CW
2095 i915_vma_set_ggtt_write(vma);
2096
a65adaf8 2097err_fence:
3bd40735 2098 i915_vma_unpin_fence(vma);
b8f9096d 2099err_unpin:
058d88c4 2100 __i915_vma_unpin(vma);
b8f9096d 2101err_unlock:
de151cf6 2102 mutex_unlock(&dev->struct_mutex);
b8f9096d
CW
2103err_rpm:
2104 intel_runtime_pm_put(dev_priv);
40e62d5d 2105 i915_gem_object_unpin_pages(obj);
b8f9096d 2106err:
de151cf6 2107 switch (ret) {
d9bc7e9f 2108 case -EIO:
2232f031
DV
2109 /*
2110 * We eat errors when the gpu is terminally wedged to avoid
2111 * userspace unduly crashing (gl has no provisions for mmaps to
2112 * fail). But any other -EIO isn't ours (e.g. swap in failure)
2113 * and so needs to be reported.
2114 */
52137010
CW
2115 if (!i915_terminally_wedged(&dev_priv->gpu_error))
2116 return VM_FAULT_SIGBUS;
045e769a 2117 case -EAGAIN:
571c608d
DV
2118 /*
2119 * EAGAIN means the gpu is hung and we'll wait for the error
2120 * handler to reset everything when re-faulting in
2121 * i915_mutex_lock_interruptible.
d9bc7e9f 2122 */
c715089f
CW
2123 case 0:
2124 case -ERESTARTSYS:
bed636ab 2125 case -EINTR:
e79e0fe3
DR
2126 case -EBUSY:
2127 /*
2128 * EBUSY is ok: this just means that another thread
2129 * already did the job.
2130 */
52137010 2131 return VM_FAULT_NOPAGE;
de151cf6 2132 case -ENOMEM:
52137010 2133 return VM_FAULT_OOM;
a7c2e1aa 2134 case -ENOSPC:
45d67817 2135 case -EFAULT:
52137010 2136 return VM_FAULT_SIGBUS;
de151cf6 2137 default:
a7c2e1aa 2138 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
52137010 2139 return VM_FAULT_SIGBUS;
de151cf6
JB
2140 }
2141}
2142
a65adaf8
CW
2143static void __i915_gem_object_release_mmap(struct drm_i915_gem_object *obj)
2144{
2145 struct i915_vma *vma;
2146
2147 GEM_BUG_ON(!obj->userfault_count);
2148
2149 obj->userfault_count = 0;
2150 list_del(&obj->userfault_link);
2151 drm_vma_node_unmap(&obj->base.vma_node,
2152 obj->base.dev->anon_inode->i_mapping);
2153
e2189dd0 2154 for_each_ggtt_vma(vma, obj)
a65adaf8 2155 i915_vma_unset_userfault(vma);
a65adaf8
CW
2156}
2157
901782b2
CW
2158/**
2159 * i915_gem_release_mmap - remove physical page mappings
2160 * @obj: obj in question
2161 *
af901ca1 2162 * Preserve the reservation of the mmapping with the DRM core code, but
901782b2
CW
2163 * relinquish ownership of the pages back to the system.
2164 *
2165 * It is vital that we remove the page mapping if we have mapped a tiled
2166 * object through the GTT and then lose the fence register due to
2167 * resource pressure. Similarly if the object has been moved out of the
2168 * aperture, than pages mapped into userspace must be revoked. Removing the
2169 * mapping will then trigger a page fault on the next user access, allowing
2170 * fixup by i915_gem_fault().
2171 */
d05ca301 2172void
05394f39 2173i915_gem_release_mmap(struct drm_i915_gem_object *obj)
901782b2 2174{
275f039d 2175 struct drm_i915_private *i915 = to_i915(obj->base.dev);
275f039d 2176
349f2ccf
CW
2177 /* Serialisation between user GTT access and our code depends upon
2178 * revoking the CPU's PTE whilst the mutex is held. The next user
2179 * pagefault then has to wait until we release the mutex.
9c870d03
CW
2180 *
2181 * Note that RPM complicates somewhat by adding an additional
2182 * requirement that operations to the GGTT be made holding the RPM
2183 * wakeref.
349f2ccf 2184 */
275f039d 2185 lockdep_assert_held(&i915->drm.struct_mutex);
9c870d03 2186 intel_runtime_pm_get(i915);
349f2ccf 2187
a65adaf8 2188 if (!obj->userfault_count)
9c870d03 2189 goto out;
901782b2 2190
a65adaf8 2191 __i915_gem_object_release_mmap(obj);
349f2ccf
CW
2192
2193 /* Ensure that the CPU's PTE are revoked and there are not outstanding
2194 * memory transactions from userspace before we return. The TLB
2195 * flushing implied above by changing the PTE above *should* be
2196 * sufficient, an extra barrier here just provides us with a bit
2197 * of paranoid documentation about our requirement to serialise
2198 * memory writes before touching registers / GSM.
2199 */
2200 wmb();
9c870d03
CW
2201
2202out:
2203 intel_runtime_pm_put(i915);
901782b2
CW
2204}
2205
7c108fd8 2206void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
eedd10f4 2207{
3594a3e2 2208 struct drm_i915_gem_object *obj, *on;
7c108fd8 2209 int i;
eedd10f4 2210
3594a3e2
CW
2211 /*
2212 * Only called during RPM suspend. All users of the userfault_list
2213 * must be holding an RPM wakeref to ensure that this can not
2214 * run concurrently with themselves (and use the struct_mutex for
2215 * protection between themselves).
2216 */
275f039d 2217
3594a3e2 2218 list_for_each_entry_safe(obj, on,
a65adaf8
CW
2219 &dev_priv->mm.userfault_list, userfault_link)
2220 __i915_gem_object_release_mmap(obj);
7c108fd8
CW
2221
2222 /* The fence will be lost when the device powers down. If any were
2223 * in use by hardware (i.e. they are pinned), we should not be powering
2224 * down! All other fences will be reacquired by the user upon waking.
2225 */
2226 for (i = 0; i < dev_priv->num_fence_regs; i++) {
2227 struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
2228
e0ec3ec6
CW
2229 /* Ideally we want to assert that the fence register is not
2230 * live at this point (i.e. that no piece of code will be
2231 * trying to write through fence + GTT, as that both violates
2232 * our tracking of activity and associated locking/barriers,
2233 * but also is illegal given that the hw is powered down).
2234 *
2235 * Previously we used reg->pin_count as a "liveness" indicator.
2236 * That is not sufficient, and we need a more fine-grained
2237 * tool if we want to have a sanity check here.
2238 */
7c108fd8
CW
2239
2240 if (!reg->vma)
2241 continue;
2242
a65adaf8 2243 GEM_BUG_ON(i915_vma_has_userfault(reg->vma));
7c108fd8
CW
2244 reg->dirty = true;
2245 }
eedd10f4
CW
2246}
2247
d8cb5086
CW
2248static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
2249{
fac5e23e 2250 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
f3f6184c 2251 int err;
da494d7c 2252
f3f6184c 2253 err = drm_gem_create_mmap_offset(&obj->base);
b42a13d9 2254 if (likely(!err))
f3f6184c 2255 return 0;
d8cb5086 2256
b42a13d9
CW
2257 /* Attempt to reap some mmap space from dead objects */
2258 do {
2259 err = i915_gem_wait_for_idle(dev_priv, I915_WAIT_INTERRUPTIBLE);
2260 if (err)
2261 break;
f3f6184c 2262
b42a13d9 2263 i915_gem_drain_freed_objects(dev_priv);
f3f6184c 2264 err = drm_gem_create_mmap_offset(&obj->base);
b42a13d9
CW
2265 if (!err)
2266 break;
2267
2268 } while (flush_delayed_work(&dev_priv->gt.retire_work));
da494d7c 2269
f3f6184c 2270 return err;
d8cb5086
CW
2271}
2272
2273static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2274{
d8cb5086
CW
2275 drm_gem_free_mmap_offset(&obj->base);
2276}
2277
da6b51d0 2278int
ff72145b
DA
2279i915_gem_mmap_gtt(struct drm_file *file,
2280 struct drm_device *dev,
da6b51d0 2281 uint32_t handle,
ff72145b 2282 uint64_t *offset)
de151cf6 2283{
05394f39 2284 struct drm_i915_gem_object *obj;
de151cf6
JB
2285 int ret;
2286
03ac0642 2287 obj = i915_gem_object_lookup(file, handle);
f3f6184c
CW
2288 if (!obj)
2289 return -ENOENT;
ab18282d 2290
d8cb5086 2291 ret = i915_gem_object_create_mmap_offset(obj);
f3f6184c
CW
2292 if (ret == 0)
2293 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
de151cf6 2294
f0cd5182 2295 i915_gem_object_put(obj);
1d7cfea1 2296 return ret;
de151cf6
JB
2297}
2298
ff72145b
DA
2299/**
2300 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2301 * @dev: DRM device
2302 * @data: GTT mapping ioctl data
2303 * @file: GEM object info
2304 *
2305 * Simply returns the fake offset to userspace so it can mmap it.
2306 * The mmap call will end up in drm_gem_mmap(), which will set things
2307 * up so we can get faults in the handler above.
2308 *
2309 * The fault handler will take care of binding the object into the GTT
2310 * (since it may have been evicted to make room for something), allocating
2311 * a fence register, and mapping the appropriate aperture address into
2312 * userspace.
2313 */
2314int
2315i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2316 struct drm_file *file)
2317{
2318 struct drm_i915_gem_mmap_gtt *args = data;
2319
da6b51d0 2320 return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
ff72145b
DA
2321}
2322
225067ee
DV
2323/* Immediately discard the backing storage */
2324static void
2325i915_gem_object_truncate(struct drm_i915_gem_object *obj)
e5281ccd 2326{
4d6294bf 2327 i915_gem_object_free_mmap_offset(obj);
1286ff73 2328
4d6294bf
CW
2329 if (obj->base.filp == NULL)
2330 return;
e5281ccd 2331
225067ee
DV
2332 /* Our goal here is to return as much of the memory as
2333 * is possible back to the system as we are called from OOM.
2334 * To do this we must instruct the shmfs to drop all of its
2335 * backing pages, *now*.
2336 */
5537252b 2337 shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
a4f5ea64 2338 obj->mm.madv = __I915_MADV_PURGED;
4e5462ee 2339 obj->mm.pages = ERR_PTR(-EFAULT);
225067ee 2340}
e5281ccd 2341
5537252b 2342/* Try to discard unwanted pages */
03ac84f1 2343void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
225067ee 2344{
5537252b
CW
2345 struct address_space *mapping;
2346
1233e2db 2347 lockdep_assert_held(&obj->mm.lock);
f1fa4f44 2348 GEM_BUG_ON(i915_gem_object_has_pages(obj));
1233e2db 2349
a4f5ea64 2350 switch (obj->mm.madv) {
5537252b
CW
2351 case I915_MADV_DONTNEED:
2352 i915_gem_object_truncate(obj);
2353 case __I915_MADV_PURGED:
2354 return;
2355 }
2356
2357 if (obj->base.filp == NULL)
2358 return;
2359
93c76a3d 2360 mapping = obj->base.filp->f_mapping,
5537252b 2361 invalidate_mapping_pages(mapping, 0, (loff_t)-1);
e5281ccd
CW
2362}
2363
5cdf5881 2364static void
03ac84f1
CW
2365i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
2366 struct sg_table *pages)
673a394b 2367{
85d1225e
DG
2368 struct sgt_iter sgt_iter;
2369 struct page *page;
1286ff73 2370
e5facdf9 2371 __i915_gem_object_release_shmem(obj, pages, true);
673a394b 2372
03ac84f1 2373 i915_gem_gtt_finish_pages(obj, pages);
e2273302 2374
6dacfd2f 2375 if (i915_gem_object_needs_bit17_swizzle(obj))
03ac84f1 2376 i915_gem_object_save_bit_17_swizzle(obj, pages);
280b713b 2377
03ac84f1 2378 for_each_sgt_page(page, sgt_iter, pages) {
a4f5ea64 2379 if (obj->mm.dirty)
9da3da66 2380 set_page_dirty(page);
3ef94daa 2381
a4f5ea64 2382 if (obj->mm.madv == I915_MADV_WILLNEED)
9da3da66 2383 mark_page_accessed(page);
3ef94daa 2384
09cbfeaf 2385 put_page(page);
3ef94daa 2386 }
a4f5ea64 2387 obj->mm.dirty = false;
673a394b 2388
03ac84f1
CW
2389 sg_free_table(pages);
2390 kfree(pages);
37e680a1 2391}
6c085a72 2392
96d77634
CW
2393static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
2394{
2395 struct radix_tree_iter iter;
c23aa71b 2396 void __rcu **slot;
96d77634 2397
bea6e987 2398 rcu_read_lock();
a4f5ea64
CW
2399 radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
2400 radix_tree_delete(&obj->mm.get_page.radix, iter.index);
bea6e987 2401 rcu_read_unlock();
96d77634
CW
2402}
2403
acd1c1e6
CW
2404static struct sg_table *
2405__i915_gem_object_unset_pages(struct drm_i915_gem_object *obj)
37e680a1 2406{
f2123818 2407 struct drm_i915_private *i915 = to_i915(obj->base.dev);
03ac84f1 2408 struct sg_table *pages;
37e680a1 2409
03ac84f1 2410 pages = fetch_and_zero(&obj->mm.pages);
acd1c1e6
CW
2411 if (!pages)
2412 return NULL;
a2165e31 2413
f2123818
CW
2414 spin_lock(&i915->mm.obj_lock);
2415 list_del(&obj->mm.link);
2416 spin_unlock(&i915->mm.obj_lock);
2417
a4f5ea64 2418 if (obj->mm.mapping) {
4b30cb23
CW
2419 void *ptr;
2420
0ce81788 2421 ptr = page_mask_bits(obj->mm.mapping);
4b30cb23
CW
2422 if (is_vmalloc_addr(ptr))
2423 vunmap(ptr);
fb8621d3 2424 else
4b30cb23
CW
2425 kunmap(kmap_to_page(ptr));
2426
a4f5ea64 2427 obj->mm.mapping = NULL;
0a798eb9
CW
2428 }
2429
96d77634 2430 __i915_gem_object_reset_page_iter(obj);
acd1c1e6
CW
2431 obj->mm.page_sizes.phys = obj->mm.page_sizes.sg = 0;
2432
2433 return pages;
2434}
96d77634 2435
acd1c1e6
CW
2436void __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
2437 enum i915_mm_subclass subclass)
2438{
2439 struct sg_table *pages;
2440
2441 if (i915_gem_object_has_pinned_pages(obj))
2442 return;
2443
2444 GEM_BUG_ON(obj->bind_count);
2445 if (!i915_gem_object_has_pages(obj))
2446 return;
2447
2448 /* May be called by shrinker from within get_pages() (on another bo) */
2449 mutex_lock_nested(&obj->mm.lock, subclass);
2450 if (unlikely(atomic_read(&obj->mm.pages_pin_count)))
2451 goto unlock;
2452
2453 /*
2454 * ->put_pages might need to allocate memory for the bit17 swizzle
2455 * array, hence protect them from being reaped by removing them from gtt
2456 * lists early.
2457 */
2458 pages = __i915_gem_object_unset_pages(obj);
4e5462ee
CW
2459 if (!IS_ERR(pages))
2460 obj->ops->put_pages(obj, pages);
2461
1233e2db
CW
2462unlock:
2463 mutex_unlock(&obj->mm.lock);
6c085a72
CW
2464}
2465
935a2f77 2466static bool i915_sg_trim(struct sg_table *orig_st)
0c40ce13
TU
2467{
2468 struct sg_table new_st;
2469 struct scatterlist *sg, *new_sg;
2470 unsigned int i;
2471
2472 if (orig_st->nents == orig_st->orig_nents)
935a2f77 2473 return false;
0c40ce13 2474
8bfc478f 2475 if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
935a2f77 2476 return false;
0c40ce13
TU
2477
2478 new_sg = new_st.sgl;
2479 for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
2480 sg_set_page(new_sg, sg_page(sg), sg->length, 0);
2481 /* called before being DMA mapped, no need to copy sg->dma_* */
2482 new_sg = sg_next(new_sg);
2483 }
c2dc6cc9 2484 GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
0c40ce13
TU
2485
2486 sg_free_table(orig_st);
2487
2488 *orig_st = new_st;
935a2f77 2489 return true;
0c40ce13
TU
2490}
2491
b91b09ee 2492static int i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
e5281ccd 2493{
fac5e23e 2494 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
d766ef53
CW
2495 const unsigned long page_count = obj->base.size / PAGE_SIZE;
2496 unsigned long i;
e5281ccd 2497 struct address_space *mapping;
9da3da66
CW
2498 struct sg_table *st;
2499 struct scatterlist *sg;
85d1225e 2500 struct sgt_iter sgt_iter;
e5281ccd 2501 struct page *page;
90797e6d 2502 unsigned long last_pfn = 0; /* suppress gcc warning */
5602452e 2503 unsigned int max_segment = i915_sg_segment_size();
84e8978e 2504 unsigned int sg_page_sizes;
4846bf0c 2505 gfp_t noreclaim;
e2273302 2506 int ret;
e5281ccd 2507
6c085a72
CW
2508 /* Assert that the object is not currently in any GPU domain. As it
2509 * wasn't in the GTT, there shouldn't be any way it could have been in
2510 * a GPU cache
2511 */
c0a51fd0
CK
2512 GEM_BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS);
2513 GEM_BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS);
6c085a72 2514
9da3da66
CW
2515 st = kmalloc(sizeof(*st), GFP_KERNEL);
2516 if (st == NULL)
b91b09ee 2517 return -ENOMEM;
9da3da66 2518
d766ef53 2519rebuild_st:
9da3da66 2520 if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
9da3da66 2521 kfree(st);
b91b09ee 2522 return -ENOMEM;
9da3da66 2523 }
e5281ccd 2524
9da3da66
CW
2525 /* Get the list of pages out of our struct file. They'll be pinned
2526 * at this point until we release them.
2527 *
2528 * Fail silently without starting the shrinker
2529 */
93c76a3d 2530 mapping = obj->base.filp->f_mapping;
0f6ab55d 2531 noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
4846bf0c
CW
2532 noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
2533
90797e6d
ID
2534 sg = st->sgl;
2535 st->nents = 0;
84e8978e 2536 sg_page_sizes = 0;
90797e6d 2537 for (i = 0; i < page_count; i++) {
4846bf0c
CW
2538 const unsigned int shrink[] = {
2539 I915_SHRINK_BOUND | I915_SHRINK_UNBOUND | I915_SHRINK_PURGEABLE,
2540 0,
2541 }, *s = shrink;
2542 gfp_t gfp = noreclaim;
2543
2544 do {
6c085a72 2545 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
4846bf0c
CW
2546 if (likely(!IS_ERR(page)))
2547 break;
2548
2549 if (!*s) {
2550 ret = PTR_ERR(page);
2551 goto err_sg;
2552 }
2553
912d572d 2554 i915_gem_shrink(dev_priv, 2 * page_count, NULL, *s++);
4846bf0c 2555 cond_resched();
24f8e00a 2556
6c085a72
CW
2557 /* We've tried hard to allocate the memory by reaping
2558 * our own buffer, now let the real VM do its job and
2559 * go down in flames if truly OOM.
24f8e00a
CW
2560 *
2561 * However, since graphics tend to be disposable,
2562 * defer the oom here by reporting the ENOMEM back
2563 * to userspace.
6c085a72 2564 */
4846bf0c
CW
2565 if (!*s) {
2566 /* reclaim and warn, but no oom */
2567 gfp = mapping_gfp_mask(mapping);
eaf41801
CW
2568
2569 /* Our bo are always dirty and so we require
2570 * kswapd to reclaim our pages (direct reclaim
2571 * does not effectively begin pageout of our
2572 * buffers on its own). However, direct reclaim
2573 * only waits for kswapd when under allocation
2574 * congestion. So as a result __GFP_RECLAIM is
2575 * unreliable and fails to actually reclaim our
2576 * dirty pages -- unless you try over and over
2577 * again with !__GFP_NORETRY. However, we still
2578 * want to fail this allocation rather than
2579 * trigger the out-of-memory killer and for
dbb32956 2580 * this we want __GFP_RETRY_MAYFAIL.
eaf41801 2581 */
dbb32956 2582 gfp |= __GFP_RETRY_MAYFAIL;
e2273302 2583 }
4846bf0c
CW
2584 } while (1);
2585
871dfbd6
CW
2586 if (!i ||
2587 sg->length >= max_segment ||
2588 page_to_pfn(page) != last_pfn + 1) {
a5c08166 2589 if (i) {
84e8978e 2590 sg_page_sizes |= sg->length;
90797e6d 2591 sg = sg_next(sg);
a5c08166 2592 }
90797e6d
ID
2593 st->nents++;
2594 sg_set_page(sg, page, PAGE_SIZE, 0);
2595 } else {
2596 sg->length += PAGE_SIZE;
2597 }
2598 last_pfn = page_to_pfn(page);
3bbbe706
DV
2599
2600 /* Check that the i965g/gm workaround works. */
2601 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
e5281ccd 2602 }
a5c08166 2603 if (sg) { /* loop terminated early; short sg table */
84e8978e 2604 sg_page_sizes |= sg->length;
426729dc 2605 sg_mark_end(sg);
a5c08166 2606 }
74ce6b6c 2607
0c40ce13
TU
2608 /* Trim unused sg entries to avoid wasting memory. */
2609 i915_sg_trim(st);
2610
03ac84f1 2611 ret = i915_gem_gtt_prepare_pages(obj, st);
d766ef53
CW
2612 if (ret) {
2613 /* DMA remapping failed? One possible cause is that
2614 * it could not reserve enough large entries, asking
2615 * for PAGE_SIZE chunks instead may be helpful.
2616 */
2617 if (max_segment > PAGE_SIZE) {
2618 for_each_sgt_page(page, sgt_iter, st)
2619 put_page(page);
2620 sg_free_table(st);
2621
2622 max_segment = PAGE_SIZE;
2623 goto rebuild_st;
2624 } else {
2625 dev_warn(&dev_priv->drm.pdev->dev,
2626 "Failed to DMA remap %lu pages\n",
2627 page_count);
2628 goto err_pages;
2629 }
2630 }
e2273302 2631
6dacfd2f 2632 if (i915_gem_object_needs_bit17_swizzle(obj))
03ac84f1 2633 i915_gem_object_do_bit_17_swizzle(obj, st);
e5281ccd 2634
84e8978e 2635 __i915_gem_object_set_pages(obj, st, sg_page_sizes);
b91b09ee
MA
2636
2637 return 0;
e5281ccd 2638
b17993b7 2639err_sg:
90797e6d 2640 sg_mark_end(sg);
b17993b7 2641err_pages:
85d1225e
DG
2642 for_each_sgt_page(page, sgt_iter, st)
2643 put_page(page);
9da3da66
CW
2644 sg_free_table(st);
2645 kfree(st);
0820baf3
CW
2646
2647 /* shmemfs first checks if there is enough memory to allocate the page
2648 * and reports ENOSPC should there be insufficient, along with the usual
2649 * ENOMEM for a genuine allocation failure.
2650 *
2651 * We use ENOSPC in our driver to mean that we have run out of aperture
2652 * space and so want to translate the error from shmemfs back to our
2653 * usual understanding of ENOMEM.
2654 */
e2273302
ID
2655 if (ret == -ENOSPC)
2656 ret = -ENOMEM;
2657
b91b09ee 2658 return ret;
03ac84f1
CW
2659}
2660
2661void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
a5c08166 2662 struct sg_table *pages,
84e8978e 2663 unsigned int sg_page_sizes)
03ac84f1 2664{
a5c08166
MA
2665 struct drm_i915_private *i915 = to_i915(obj->base.dev);
2666 unsigned long supported = INTEL_INFO(i915)->page_sizes;
2667 int i;
2668
1233e2db 2669 lockdep_assert_held(&obj->mm.lock);
03ac84f1
CW
2670
2671 obj->mm.get_page.sg_pos = pages->sgl;
2672 obj->mm.get_page.sg_idx = 0;
2673
2674 obj->mm.pages = pages;
2c3a3f44
CW
2675
2676 if (i915_gem_object_is_tiled(obj) &&
f2123818 2677 i915->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
2c3a3f44
CW
2678 GEM_BUG_ON(obj->mm.quirked);
2679 __i915_gem_object_pin_pages(obj);
2680 obj->mm.quirked = true;
2681 }
a5c08166 2682
84e8978e
MA
2683 GEM_BUG_ON(!sg_page_sizes);
2684 obj->mm.page_sizes.phys = sg_page_sizes;
a5c08166
MA
2685
2686 /*
84e8978e
MA
2687 * Calculate the supported page-sizes which fit into the given
2688 * sg_page_sizes. This will give us the page-sizes which we may be able
2689 * to use opportunistically when later inserting into the GTT. For
2690 * example if phys=2G, then in theory we should be able to use 1G, 2M,
2691 * 64K or 4K pages, although in practice this will depend on a number of
2692 * other factors.
a5c08166
MA
2693 */
2694 obj->mm.page_sizes.sg = 0;
2695 for_each_set_bit(i, &supported, ilog2(I915_GTT_MAX_PAGE_SIZE) + 1) {
2696 if (obj->mm.page_sizes.phys & ~0u << i)
2697 obj->mm.page_sizes.sg |= BIT(i);
2698 }
a5c08166 2699 GEM_BUG_ON(!HAS_PAGE_SIZES(i915, obj->mm.page_sizes.sg));
f2123818
CW
2700
2701 spin_lock(&i915->mm.obj_lock);
2702 list_add(&obj->mm.link, &i915->mm.unbound_list);
2703 spin_unlock(&i915->mm.obj_lock);
03ac84f1
CW
2704}
2705
2706static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2707{
b91b09ee 2708 int err;
03ac84f1
CW
2709
2710 if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
2711 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2712 return -EFAULT;
2713 }
2714
b91b09ee 2715 err = obj->ops->get_pages(obj);
b65a9b98 2716 GEM_BUG_ON(!err && !i915_gem_object_has_pages(obj));
03ac84f1 2717
b91b09ee 2718 return err;
673a394b
EA
2719}
2720
37e680a1 2721/* Ensure that the associated pages are gathered from the backing storage
1233e2db 2722 * and pinned into our object. i915_gem_object_pin_pages() may be called
37e680a1 2723 * multiple times before they are released by a single call to
1233e2db 2724 * i915_gem_object_unpin_pages() - once the pages are no longer referenced
37e680a1
CW
2725 * either as a result of memory pressure (reaping pages under the shrinker)
2726 * or as the object is itself released.
2727 */
a4f5ea64 2728int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
37e680a1 2729{
03ac84f1 2730 int err;
37e680a1 2731
1233e2db
CW
2732 err = mutex_lock_interruptible(&obj->mm.lock);
2733 if (err)
2734 return err;
4c7d62c6 2735
f1fa4f44 2736 if (unlikely(!i915_gem_object_has_pages(obj))) {
88c880bb
CW
2737 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2738
2c3a3f44
CW
2739 err = ____i915_gem_object_get_pages(obj);
2740 if (err)
2741 goto unlock;
37e680a1 2742
2c3a3f44
CW
2743 smp_mb__before_atomic();
2744 }
2745 atomic_inc(&obj->mm.pages_pin_count);
ee286370 2746
1233e2db
CW
2747unlock:
2748 mutex_unlock(&obj->mm.lock);
03ac84f1 2749 return err;
673a394b
EA
2750}
2751
dd6034c6 2752/* The 'mapping' part of i915_gem_object_pin_map() below */
d31d7cb1
CW
2753static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
2754 enum i915_map_type type)
dd6034c6
DG
2755{
2756 unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
a4f5ea64 2757 struct sg_table *sgt = obj->mm.pages;
85d1225e
DG
2758 struct sgt_iter sgt_iter;
2759 struct page *page;
b338fa47
DG
2760 struct page *stack_pages[32];
2761 struct page **pages = stack_pages;
dd6034c6 2762 unsigned long i = 0;
d31d7cb1 2763 pgprot_t pgprot;
dd6034c6
DG
2764 void *addr;
2765
2766 /* A single page can always be kmapped */
d31d7cb1 2767 if (n_pages == 1 && type == I915_MAP_WB)
dd6034c6
DG
2768 return kmap(sg_page(sgt->sgl));
2769
b338fa47
DG
2770 if (n_pages > ARRAY_SIZE(stack_pages)) {
2771 /* Too big for stack -- allocate temporary array instead */
0ee931c4 2772 pages = kvmalloc_array(n_pages, sizeof(*pages), GFP_KERNEL);
b338fa47
DG
2773 if (!pages)
2774 return NULL;
2775 }
dd6034c6 2776
85d1225e
DG
2777 for_each_sgt_page(page, sgt_iter, sgt)
2778 pages[i++] = page;
dd6034c6
DG
2779
2780 /* Check that we have the expected number of pages */
2781 GEM_BUG_ON(i != n_pages);
2782
d31d7cb1 2783 switch (type) {
a575c676
CW
2784 default:
2785 MISSING_CASE(type);
2786 /* fallthrough to use PAGE_KERNEL anyway */
d31d7cb1
CW
2787 case I915_MAP_WB:
2788 pgprot = PAGE_KERNEL;
2789 break;
2790 case I915_MAP_WC:
2791 pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
2792 break;
2793 }
2794 addr = vmap(pages, n_pages, 0, pgprot);
dd6034c6 2795
b338fa47 2796 if (pages != stack_pages)
2098105e 2797 kvfree(pages);
dd6034c6
DG
2798
2799 return addr;
2800}
2801
2802/* get, pin, and map the pages of the object into kernel space */
d31d7cb1
CW
2803void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
2804 enum i915_map_type type)
0a798eb9 2805{
d31d7cb1
CW
2806 enum i915_map_type has_type;
2807 bool pinned;
2808 void *ptr;
0a798eb9
CW
2809 int ret;
2810
a03f395a
TZ
2811 if (unlikely(!i915_gem_object_has_struct_page(obj)))
2812 return ERR_PTR(-ENXIO);
0a798eb9 2813
1233e2db 2814 ret = mutex_lock_interruptible(&obj->mm.lock);
0a798eb9
CW
2815 if (ret)
2816 return ERR_PTR(ret);
2817
a575c676
CW
2818 pinned = !(type & I915_MAP_OVERRIDE);
2819 type &= ~I915_MAP_OVERRIDE;
2820
1233e2db 2821 if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
f1fa4f44 2822 if (unlikely(!i915_gem_object_has_pages(obj))) {
88c880bb
CW
2823 GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
2824
2c3a3f44
CW
2825 ret = ____i915_gem_object_get_pages(obj);
2826 if (ret)
2827 goto err_unlock;
1233e2db 2828
2c3a3f44
CW
2829 smp_mb__before_atomic();
2830 }
2831 atomic_inc(&obj->mm.pages_pin_count);
1233e2db
CW
2832 pinned = false;
2833 }
f1fa4f44 2834 GEM_BUG_ON(!i915_gem_object_has_pages(obj));
0a798eb9 2835
0ce81788 2836 ptr = page_unpack_bits(obj->mm.mapping, &has_type);
d31d7cb1
CW
2837 if (ptr && has_type != type) {
2838 if (pinned) {
2839 ret = -EBUSY;
1233e2db 2840 goto err_unpin;
0a798eb9 2841 }
d31d7cb1
CW
2842
2843 if (is_vmalloc_addr(ptr))
2844 vunmap(ptr);
2845 else
2846 kunmap(kmap_to_page(ptr));
2847
a4f5ea64 2848 ptr = obj->mm.mapping = NULL;
0a798eb9
CW
2849 }
2850
d31d7cb1
CW
2851 if (!ptr) {
2852 ptr = i915_gem_object_map(obj, type);
2853 if (!ptr) {
2854 ret = -ENOMEM;
1233e2db 2855 goto err_unpin;
d31d7cb1
CW
2856 }
2857
0ce81788 2858 obj->mm.mapping = page_pack_bits(ptr, type);
d31d7cb1
CW
2859 }
2860
1233e2db
CW
2861out_unlock:
2862 mutex_unlock(&obj->mm.lock);
d31d7cb1
CW
2863 return ptr;
2864
1233e2db
CW
2865err_unpin:
2866 atomic_dec(&obj->mm.pages_pin_count);
2867err_unlock:
2868 ptr = ERR_PTR(ret);
2869 goto out_unlock;
0a798eb9
CW
2870}
2871
7c55e2c5
CW
2872static int
2873i915_gem_object_pwrite_gtt(struct drm_i915_gem_object *obj,
2874 const struct drm_i915_gem_pwrite *arg)
2875{
2876 struct address_space *mapping = obj->base.filp->f_mapping;
2877 char __user *user_data = u64_to_user_ptr(arg->data_ptr);
2878 u64 remain, offset;
2879 unsigned int pg;
2880
2881 /* Before we instantiate/pin the backing store for our use, we
2882 * can prepopulate the shmemfs filp efficiently using a write into
2883 * the pagecache. We avoid the penalty of instantiating all the
2884 * pages, important if the user is just writing to a few and never
2885 * uses the object on the GPU, and using a direct write into shmemfs
2886 * allows it to avoid the cost of retrieving a page (either swapin
2887 * or clearing-before-use) before it is overwritten.
2888 */
f1fa4f44 2889 if (i915_gem_object_has_pages(obj))
7c55e2c5
CW
2890 return -ENODEV;
2891
a6d65e45
CW
2892 if (obj->mm.madv != I915_MADV_WILLNEED)
2893 return -EFAULT;
2894
7c55e2c5
CW
2895 /* Before the pages are instantiated the object is treated as being
2896 * in the CPU domain. The pages will be clflushed as required before
2897 * use, and we can freely write into the pages directly. If userspace
2898 * races pwrite with any other operation; corruption will ensue -
2899 * that is userspace's prerogative!
2900 */
2901
2902 remain = arg->size;
2903 offset = arg->offset;
2904 pg = offset_in_page(offset);
2905
2906 do {
2907 unsigned int len, unwritten;
2908 struct page *page;
2909 void *data, *vaddr;
2910 int err;
2911
2912 len = PAGE_SIZE - pg;
2913 if (len > remain)
2914 len = remain;
2915
2916 err = pagecache_write_begin(obj->base.filp, mapping,
2917 offset, len, 0,
2918 &page, &data);
2919 if (err < 0)
2920 return err;
2921
2922 vaddr = kmap(page);
2923 unwritten = copy_from_user(vaddr + pg, user_data, len);
2924 kunmap(page);
2925
2926 err = pagecache_write_end(obj->base.filp, mapping,
2927 offset, len, len - unwritten,
2928 page, data);
2929 if (err < 0)
2930 return err;
2931
2932 if (unwritten)
2933 return -EFAULT;
2934
2935 remain -= len;
2936 user_data += len;
2937 offset += len;
2938 pg = 0;
2939 } while (remain);
2940
2941 return 0;
2942}
2943
e5e1fc47 2944static void i915_gem_context_mark_guilty(struct i915_gem_context *ctx)
aa60c664 2945{
77b25a97 2946 bool banned;
b083a087 2947
77b25a97 2948 atomic_inc(&ctx->guilty_count);
b083a087 2949
24eae08d
CW
2950 banned = false;
2951 if (i915_gem_context_is_bannable(ctx)) {
2952 unsigned int score;
2953
2954 score = atomic_add_return(CONTEXT_SCORE_GUILTY,
2955 &ctx->ban_score);
2956 banned = score >= CONTEXT_SCORE_BAN_THRESHOLD;
2957
2958 DRM_DEBUG_DRIVER("context %s marked guilty (score %d) banned? %s\n",
2959 ctx->name, score, yesno(banned));
2960 }
77b25a97 2961 if (!banned)
b083a087
MK
2962 return;
2963
77b25a97
CW
2964 i915_gem_context_set_banned(ctx);
2965 if (!IS_ERR_OR_NULL(ctx->file_priv)) {
2966 atomic_inc(&ctx->file_priv->context_bans);
2967 DRM_DEBUG_DRIVER("client %s has had %d context banned\n",
2968 ctx->name, atomic_read(&ctx->file_priv->context_bans));
2969 }
e5e1fc47
MK
2970}
2971
2972static void i915_gem_context_mark_innocent(struct i915_gem_context *ctx)
2973{
77b25a97 2974 atomic_inc(&ctx->active_count);
aa60c664
MK
2975}
2976
e61e0f51 2977struct i915_request *
0bc40be8 2978i915_gem_find_active_request(struct intel_engine_cs *engine)
9375e446 2979{
e61e0f51 2980 struct i915_request *request, *active = NULL;
754c9fd5 2981 unsigned long flags;
4db080f9 2982
cc7cc534
CW
2983 /*
2984 * We are called by the error capture, reset and to dump engine
2985 * state at random points in time. In particular, note that neither is
2986 * crucially ordered with an interrupt. After a hang, the GPU is dead
2987 * and we assume that no more writes can happen (we waited long enough
2988 * for all writes that were in transaction to be flushed) - adding an
f69a02c9
CW
2989 * extra delay for a recent interrupt is pointless. Hence, we do
2990 * not need an engine->irq_seqno_barrier() before the seqno reads.
cc7cc534
CW
2991 * At all other times, we must assume the GPU is still running, but
2992 * we only care about the snapshot of this moment.
f69a02c9 2993 */
a89d1f92
CW
2994 spin_lock_irqsave(&engine->timeline.lock, flags);
2995 list_for_each_entry(request, &engine->timeline.requests, link) {
e61e0f51 2996 if (__i915_request_completed(request, request->global_seqno))
4db080f9 2997 continue;
aa60c664 2998
754c9fd5
CW
2999 active = request;
3000 break;
4db080f9 3001 }
a89d1f92 3002 spin_unlock_irqrestore(&engine->timeline.lock, flags);
b6b0fac0 3003
754c9fd5 3004 return active;
b6b0fac0
MK
3005}
3006
a1ef70e1
MT
3007/*
3008 * Ensure irq handler finishes, and not run again.
3009 * Also return the active request so that we only search for it once.
3010 */
e61e0f51 3011struct i915_request *
a1ef70e1
MT
3012i915_gem_reset_prepare_engine(struct intel_engine_cs *engine)
3013{
5adfb772 3014 struct i915_request *request;
a1ef70e1 3015
1749d90f
CW
3016 /*
3017 * During the reset sequence, we must prevent the engine from
3018 * entering RC6. As the context state is undefined until we restart
3019 * the engine, if it does enter RC6 during the reset, the state
3020 * written to the powercontext is undefined and so we may lose
3021 * GPU state upon resume, i.e. fail to restart after a reset.
3022 */
3023 intel_uncore_forcewake_get(engine->i915, FORCEWAKE_ALL);
3024
5adfb772 3025 request = engine->reset.prepare(engine);
d1d1ebf4
CW
3026 if (request && request->fence.error == -EIO)
3027 request = ERR_PTR(-EIO); /* Previous reset failed! */
a1ef70e1
MT
3028
3029 return request;
3030}
3031
0e178aef 3032int i915_gem_reset_prepare(struct drm_i915_private *dev_priv)
4c965543
CW
3033{
3034 struct intel_engine_cs *engine;
e61e0f51 3035 struct i915_request *request;
4c965543 3036 enum intel_engine_id id;
0e178aef 3037 int err = 0;
4c965543 3038
0e178aef 3039 for_each_engine(engine, dev_priv, id) {
a1ef70e1
MT
3040 request = i915_gem_reset_prepare_engine(engine);
3041 if (IS_ERR(request)) {
3042 err = PTR_ERR(request);
3043 continue;
0e178aef 3044 }
c64992e0
MT
3045
3046 engine->hangcheck.active_request = request;
0e178aef
CW
3047 }
3048
4c965543 3049 i915_gem_revoke_fences(dev_priv);
c37d5728 3050 intel_uc_sanitize(dev_priv);
0e178aef
CW
3051
3052 return err;
4c965543
CW
3053}
3054
e61e0f51 3055static void skip_request(struct i915_request *request)
821ed7df
CW
3056{
3057 void *vaddr = request->ring->vaddr;
3058 u32 head;
3059
3060 /* As this request likely depends on state from the lost
3061 * context, clear out all the user operations leaving the
3062 * breadcrumb at the end (so we get the fence notifications).
3063 */
3064 head = request->head;
3065 if (request->postfix < head) {
3066 memset(vaddr + head, 0, request->ring->size - head);
3067 head = 0;
3068 }
3069 memset(vaddr + head, 0, request->postfix - head);
c0d5f32c
CW
3070
3071 dma_fence_set_error(&request->fence, -EIO);
821ed7df
CW
3072}
3073
e61e0f51 3074static void engine_skip_context(struct i915_request *request)
36193acd
MK
3075{
3076 struct intel_engine_cs *engine = request->engine;
4e0d64db 3077 struct i915_gem_context *hung_ctx = request->gem_context;
a89d1f92 3078 struct i915_timeline *timeline = request->timeline;
36193acd
MK
3079 unsigned long flags;
3080
a89d1f92 3081 GEM_BUG_ON(timeline == &engine->timeline);
36193acd 3082
a89d1f92 3083 spin_lock_irqsave(&engine->timeline.lock, flags);
0c591a40 3084 spin_lock_nested(&timeline->lock, SINGLE_DEPTH_NESTING);
36193acd 3085
a89d1f92 3086 list_for_each_entry_continue(request, &engine->timeline.requests, link)
4e0d64db 3087 if (request->gem_context == hung_ctx)
36193acd
MK
3088 skip_request(request);
3089
3090 list_for_each_entry(request, &timeline->requests, link)
3091 skip_request(request);
3092
3093 spin_unlock(&timeline->lock);
a89d1f92 3094 spin_unlock_irqrestore(&engine->timeline.lock, flags);
36193acd
MK
3095}
3096
d1d1ebf4 3097/* Returns the request if it was guilty of the hang */
e61e0f51 3098static struct i915_request *
d1d1ebf4 3099i915_gem_reset_request(struct intel_engine_cs *engine,
bba0869b
CW
3100 struct i915_request *request,
3101 bool stalled)
61da5362 3102{
71895a08
MK
3103 /* The guilty request will get skipped on a hung engine.
3104 *
3105 * Users of client default contexts do not rely on logical
3106 * state preserved between batches so it is safe to execute
3107 * queued requests following the hang. Non default contexts
3108 * rely on preserved state, so skipping a batch loses the
3109 * evolution of the state and it needs to be considered corrupted.
3110 * Executing more queued batches on top of corrupted state is
3111 * risky. But we take the risk by trying to advance through
3112 * the queued requests in order to make the client behaviour
3113 * more predictable around resets, by not throwing away random
3114 * amount of batches it has prepared for execution. Sophisticated
3115 * clients can use gem_reset_stats_ioctl and dma fence status
3116 * (exported via sync_file info ioctl on explicit fences) to observe
3117 * when it loses the context state and should rebuild accordingly.
3118 *
3119 * The context ban, and ultimately the client ban, mechanism are safety
3120 * valves if client submission ends up resulting in nothing more than
3121 * subsequent hangs.
3122 */
3123
bba0869b
CW
3124 if (i915_request_completed(request)) {
3125 GEM_TRACE("%s pardoned global=%d (fence %llx:%d), current %d\n",
3126 engine->name, request->global_seqno,
3127 request->fence.context, request->fence.seqno,
3128 intel_engine_get_seqno(engine));
3129 stalled = false;
3130 }
3131
3132 if (stalled) {
4e0d64db 3133 i915_gem_context_mark_guilty(request->gem_context);
61da5362 3134 skip_request(request);
d1d1ebf4
CW
3135
3136 /* If this context is now banned, skip all pending requests. */
4e0d64db 3137 if (i915_gem_context_is_banned(request->gem_context))
d1d1ebf4 3138 engine_skip_context(request);
61da5362 3139 } else {
d1d1ebf4
CW
3140 /*
3141 * Since this is not the hung engine, it may have advanced
3142 * since the hang declaration. Double check by refinding
3143 * the active request at the time of the reset.
3144 */
3145 request = i915_gem_find_active_request(engine);
3146 if (request) {
4e0d64db 3147 i915_gem_context_mark_innocent(request->gem_context);
d1d1ebf4
CW
3148 dma_fence_set_error(&request->fence, -EAGAIN);
3149
3150 /* Rewind the engine to replay the incomplete rq */
a89d1f92 3151 spin_lock_irq(&engine->timeline.lock);
d1d1ebf4 3152 request = list_prev_entry(request, link);
a89d1f92 3153 if (&request->link == &engine->timeline.requests)
d1d1ebf4 3154 request = NULL;
a89d1f92 3155 spin_unlock_irq(&engine->timeline.lock);
d1d1ebf4 3156 }
61da5362
MK
3157 }
3158
d1d1ebf4 3159 return request;
61da5362
MK
3160}
3161
a1ef70e1 3162void i915_gem_reset_engine(struct intel_engine_cs *engine,
bba0869b
CW
3163 struct i915_request *request,
3164 bool stalled)
b6b0fac0 3165{
fcb1de54
CW
3166 /*
3167 * Make sure this write is visible before we re-enable the interrupt
3168 * handlers on another CPU, as tasklet_enable() resolves to just
3169 * a compiler barrier which is insufficient for our purpose here.
3170 */
3171 smp_store_mb(engine->irq_posted, 0);
ed454f2c 3172
d1d1ebf4 3173 if (request)
bba0869b 3174 request = i915_gem_reset_request(engine, request, stalled);
d1d1ebf4 3175
821ed7df 3176 /* Setup the CS to resume from the breadcrumb of the hung request */
5adfb772 3177 engine->reset.reset(engine, request);
4db080f9 3178}
aa60c664 3179
d0667e9c
CW
3180void i915_gem_reset(struct drm_i915_private *dev_priv,
3181 unsigned int stalled_mask)
4db080f9 3182{
821ed7df 3183 struct intel_engine_cs *engine;
3b3f1650 3184 enum intel_engine_id id;
608c1a52 3185
4c7d62c6
CW
3186 lockdep_assert_held(&dev_priv->drm.struct_mutex);
3187
e61e0f51 3188 i915_retire_requests(dev_priv);
821ed7df 3189
2ae55738 3190 for_each_engine(engine, dev_priv, id) {
1fc44d9b 3191 struct intel_context *ce;
2ae55738 3192
bba0869b
CW
3193 i915_gem_reset_engine(engine,
3194 engine->hangcheck.active_request,
d0667e9c 3195 stalled_mask & ENGINE_MASK(id));
1fc44d9b
CW
3196 ce = fetch_and_zero(&engine->last_retired_context);
3197 if (ce)
3198 intel_context_unpin(ce);
7b6da818
CW
3199
3200 /*
3201 * Ostensibily, we always want a context loaded for powersaving,
3202 * so if the engine is idle after the reset, send a request
3203 * to load our scratch kernel_context.
3204 *
3205 * More mysteriously, if we leave the engine idle after a reset,
3206 * the next userspace batch may hang, with what appears to be
3207 * an incoherent read by the CS (presumably stale TLB). An
3208 * empty request appears sufficient to paper over the glitch.
3209 */
01b8fdc5 3210 if (intel_engine_is_idle(engine)) {
e61e0f51 3211 struct i915_request *rq;
7b6da818 3212
e61e0f51
CW
3213 rq = i915_request_alloc(engine,
3214 dev_priv->kernel_context);
7b6da818 3215 if (!IS_ERR(rq))
e61e0f51 3216 __i915_request_add(rq, false);
7b6da818 3217 }
2ae55738 3218 }
821ed7df 3219
4362f4f6 3220 i915_gem_restore_fences(dev_priv);
821ed7df
CW
3221}
3222
a1ef70e1
MT
3223void i915_gem_reset_finish_engine(struct intel_engine_cs *engine)
3224{
5adfb772
CW
3225 engine->reset.finish(engine);
3226
1749d90f 3227 intel_uncore_forcewake_put(engine->i915, FORCEWAKE_ALL);
a1ef70e1
MT
3228}
3229
d8027093
CW
3230void i915_gem_reset_finish(struct drm_i915_private *dev_priv)
3231{
1f7b847d
CW
3232 struct intel_engine_cs *engine;
3233 enum intel_engine_id id;
3234
d8027093 3235 lockdep_assert_held(&dev_priv->drm.struct_mutex);
1f7b847d 3236
fe3288b5 3237 for_each_engine(engine, dev_priv, id) {
c64992e0 3238 engine->hangcheck.active_request = NULL;
a1ef70e1 3239 i915_gem_reset_finish_engine(engine);
fe3288b5 3240 }
d8027093
CW
3241}
3242
e61e0f51 3243static void nop_submit_request(struct i915_request *request)
af7a8ffa 3244{
d9b13c4d
CW
3245 GEM_TRACE("%s fence %llx:%d -> -EIO\n",
3246 request->engine->name,
3247 request->fence.context, request->fence.seqno);
af7a8ffa
DV
3248 dma_fence_set_error(&request->fence, -EIO);
3249
e61e0f51 3250 i915_request_submit(request);
af7a8ffa
DV
3251}
3252
e61e0f51 3253static void nop_complete_submit_request(struct i915_request *request)
821ed7df 3254{
8d550824
CW
3255 unsigned long flags;
3256
d9b13c4d
CW
3257 GEM_TRACE("%s fence %llx:%d -> -EIO\n",
3258 request->engine->name,
3259 request->fence.context, request->fence.seqno);
3cd9442f 3260 dma_fence_set_error(&request->fence, -EIO);
8d550824 3261
a89d1f92 3262 spin_lock_irqsave(&request->engine->timeline.lock, flags);
e61e0f51 3263 __i915_request_submit(request);
3dcf93f7 3264 intel_engine_init_global_seqno(request->engine, request->global_seqno);
a89d1f92 3265 spin_unlock_irqrestore(&request->engine->timeline.lock, flags);
821ed7df
CW
3266}
3267
af7a8ffa 3268void i915_gem_set_wedged(struct drm_i915_private *i915)
821ed7df 3269{
af7a8ffa
DV
3270 struct intel_engine_cs *engine;
3271 enum intel_engine_id id;
3272
d9b13c4d
CW
3273 GEM_TRACE("start\n");
3274
7f961d79 3275 if (GEM_SHOW_DEBUG()) {
559e040f
CW
3276 struct drm_printer p = drm_debug_printer(__func__);
3277
3278 for_each_engine(engine, i915, id)
3279 intel_engine_dump(engine, &p, "%s\n", engine->name);
3280 }
3281
0d73e7a0
CW
3282 set_bit(I915_WEDGED, &i915->gpu_error.flags);
3283 smp_mb__after_atomic();
3284
af7a8ffa
DV
3285 /*
3286 * First, stop submission to hw, but do not yet complete requests by
3287 * rolling the global seqno forward (since this would complete requests
3288 * for which we haven't set the fence error to EIO yet).
3289 */
963ddd63
CW
3290 for_each_engine(engine, i915, id) {
3291 i915_gem_reset_prepare_engine(engine);
47650db0 3292
af7a8ffa 3293 engine->submit_request = nop_submit_request;
47650db0 3294 engine->schedule = NULL;
963ddd63 3295 }
47650db0 3296 i915->caps.scheduler = 0;
af7a8ffa 3297
ac697ae8
CW
3298 /* Even if the GPU reset fails, it should still stop the engines */
3299 intel_gpu_reset(i915, ALL_ENGINES);
3300
af7a8ffa
DV
3301 /*
3302 * Make sure no one is running the old callback before we proceed with
3303 * cancelling requests and resetting the completion tracking. Otherwise
3304 * we might submit a request to the hardware which never completes.
20e4933c 3305 */
af7a8ffa 3306 synchronize_rcu();
70c2a24d 3307
af7a8ffa
DV
3308 for_each_engine(engine, i915, id) {
3309 /* Mark all executing requests as skipped */
3310 engine->cancel_requests(engine);
5e32d748 3311
af7a8ffa
DV
3312 /*
3313 * Only once we've force-cancelled all in-flight requests can we
3314 * start to complete all requests.
3315 */
3316 engine->submit_request = nop_complete_submit_request;
3317 }
3318
3319 /*
3320 * Make sure no request can slip through without getting completed by
3321 * either this call here to intel_engine_init_global_seqno, or the one
3322 * in nop_complete_submit_request.
5e32d748 3323 */
af7a8ffa 3324 synchronize_rcu();
673a394b 3325
af7a8ffa
DV
3326 for_each_engine(engine, i915, id) {
3327 unsigned long flags;
673a394b 3328
0d73e7a0
CW
3329 /*
3330 * Mark all pending requests as complete so that any concurrent
af7a8ffa
DV
3331 * (lockless) lookup doesn't try and wait upon the request as we
3332 * reset it.
3333 */
a89d1f92 3334 spin_lock_irqsave(&engine->timeline.lock, flags);
af7a8ffa
DV
3335 intel_engine_init_global_seqno(engine,
3336 intel_engine_last_submit(engine));
a89d1f92 3337 spin_unlock_irqrestore(&engine->timeline.lock, flags);
963ddd63
CW
3338
3339 i915_gem_reset_finish_engine(engine);
af7a8ffa 3340 }
20e4933c 3341
d9b13c4d
CW
3342 GEM_TRACE("end\n");
3343
3d7adbbf 3344 wake_up_all(&i915->gpu_error.reset_queue);
673a394b
EA
3345}
3346
2e8f9d32
CW
3347bool i915_gem_unset_wedged(struct drm_i915_private *i915)
3348{
a89d1f92 3349 struct i915_timeline *tl;
2e8f9d32
CW
3350
3351 lockdep_assert_held(&i915->drm.struct_mutex);
3352 if (!test_bit(I915_WEDGED, &i915->gpu_error.flags))
3353 return true;
3354
d9b13c4d
CW
3355 GEM_TRACE("start\n");
3356
2d4ecace
CW
3357 /*
3358 * Before unwedging, make sure that all pending operations
2e8f9d32
CW
3359 * are flushed and errored out - we may have requests waiting upon
3360 * third party fences. We marked all inflight requests as EIO, and
3361 * every execbuf since returned EIO, for consistency we want all
3362 * the currently pending requests to also be marked as EIO, which
3363 * is done inside our nop_submit_request - and so we must wait.
3364 *
3365 * No more can be submitted until we reset the wedged bit.
3366 */
3367 list_for_each_entry(tl, &i915->gt.timelines, link) {
a89d1f92 3368 struct i915_request *rq;
2e8f9d32 3369
a89d1f92
CW
3370 rq = i915_gem_active_peek(&tl->last_request,
3371 &i915->drm.struct_mutex);
3372 if (!rq)
3373 continue;
2e8f9d32 3374
a89d1f92
CW
3375 /*
3376 * We can't use our normal waiter as we want to
3377 * avoid recursively trying to handle the current
3378 * reset. The basic dma_fence_default_wait() installs
3379 * a callback for dma_fence_signal(), which is
3380 * triggered by our nop handler (indirectly, the
3381 * callback enables the signaler thread which is
3382 * woken by the nop_submit_request() advancing the seqno
3383 * and when the seqno passes the fence, the signaler
3384 * then signals the fence waking us up).
3385 */
3386 if (dma_fence_default_wait(&rq->fence, true,
3387 MAX_SCHEDULE_TIMEOUT) < 0)
3388 return false;
2e8f9d32 3389 }
2d4ecace
CW
3390 i915_retire_requests(i915);
3391 GEM_BUG_ON(i915->gt.active_requests);
2e8f9d32 3392
2d4ecace
CW
3393 /*
3394 * Undo nop_submit_request. We prevent all new i915 requests from
2e8f9d32
CW
3395 * being queued (by disallowing execbuf whilst wedged) so having
3396 * waited for all active requests above, we know the system is idle
3397 * and do not have to worry about a thread being inside
3398 * engine->submit_request() as we swap over. So unlike installing
3399 * the nop_submit_request on reset, we can do this from normal
3400 * context and do not require stop_machine().
3401 */
3402 intel_engines_reset_default_submission(i915);
36703e79 3403 i915_gem_contexts_lost(i915);
2e8f9d32 3404
d9b13c4d
CW
3405 GEM_TRACE("end\n");
3406
2e8f9d32
CW
3407 smp_mb__before_atomic(); /* complete takeover before enabling execbuf */
3408 clear_bit(I915_WEDGED, &i915->gpu_error.flags);
3409
3410 return true;
3411}
3412
75ef9da2 3413static void
673a394b
EA
3414i915_gem_retire_work_handler(struct work_struct *work)
3415{
b29c19b6 3416 struct drm_i915_private *dev_priv =
67d97da3 3417 container_of(work, typeof(*dev_priv), gt.retire_work.work);
91c8a326 3418 struct drm_device *dev = &dev_priv->drm;
673a394b 3419
891b48cf 3420 /* Come back later if the device is busy... */
b29c19b6 3421 if (mutex_trylock(&dev->struct_mutex)) {
e61e0f51 3422 i915_retire_requests(dev_priv);
b29c19b6 3423 mutex_unlock(&dev->struct_mutex);
673a394b 3424 }
67d97da3 3425
88923048
CW
3426 /*
3427 * Keep the retire handler running until we are finally idle.
67d97da3
CW
3428 * We do not need to do this test under locking as in the worst-case
3429 * we queue the retire worker once too often.
3430 */
88923048 3431 if (READ_ONCE(dev_priv->gt.awake))
67d97da3
CW
3432 queue_delayed_work(dev_priv->wq,
3433 &dev_priv->gt.retire_work,
bcb45086 3434 round_jiffies_up_relative(HZ));
b29c19b6 3435}
0a58705b 3436
84a10749
CW
3437static void shrink_caches(struct drm_i915_private *i915)
3438{
3439 /*
3440 * kmem_cache_shrink() discards empty slabs and reorders partially
3441 * filled slabs to prioritise allocating from the mostly full slabs,
3442 * with the aim of reducing fragmentation.
3443 */
3444 kmem_cache_shrink(i915->priorities);
3445 kmem_cache_shrink(i915->dependencies);
3446 kmem_cache_shrink(i915->requests);
3447 kmem_cache_shrink(i915->luts);
3448 kmem_cache_shrink(i915->vmas);
3449 kmem_cache_shrink(i915->objects);
3450}
3451
3452struct sleep_rcu_work {
3453 union {
3454 struct rcu_head rcu;
3455 struct work_struct work;
3456 };
3457 struct drm_i915_private *i915;
3458 unsigned int epoch;
3459};
3460
3461static inline bool
3462same_epoch(struct drm_i915_private *i915, unsigned int epoch)
3463{
3464 /*
3465 * There is a small chance that the epoch wrapped since we started
3466 * sleeping. If we assume that epoch is at least a u32, then it will
3467 * take at least 2^32 * 100ms for it to wrap, or about 326 years.
3468 */
3469 return epoch == READ_ONCE(i915->gt.epoch);
3470}
3471
3472static void __sleep_work(struct work_struct *work)
3473{
3474 struct sleep_rcu_work *s = container_of(work, typeof(*s), work);
3475 struct drm_i915_private *i915 = s->i915;
3476 unsigned int epoch = s->epoch;
3477
3478 kfree(s);
3479 if (same_epoch(i915, epoch))
3480 shrink_caches(i915);
3481}
3482
3483static void __sleep_rcu(struct rcu_head *rcu)
3484{
3485 struct sleep_rcu_work *s = container_of(rcu, typeof(*s), rcu);
3486 struct drm_i915_private *i915 = s->i915;
3487
3488 if (same_epoch(i915, s->epoch)) {
3489 INIT_WORK(&s->work, __sleep_work);
3490 queue_work(i915->wq, &s->work);
3491 } else {
3492 kfree(s);
3493 }
3494}
3495
5427f207
CW
3496static inline bool
3497new_requests_since_last_retire(const struct drm_i915_private *i915)
3498{
3499 return (READ_ONCE(i915->gt.active_requests) ||
3500 work_pending(&i915->gt.idle_work.work));
3501}
3502
1934f5de
CW
3503static void assert_kernel_context_is_current(struct drm_i915_private *i915)
3504{
3505 struct intel_engine_cs *engine;
3506 enum intel_engine_id id;
3507
3508 if (i915_terminally_wedged(&i915->gpu_error))
3509 return;
3510
3511 GEM_BUG_ON(i915->gt.active_requests);
3512 for_each_engine(engine, i915, id) {
3513 GEM_BUG_ON(__i915_gem_active_peek(&engine->timeline.last_request));
3514 GEM_BUG_ON(engine->last_retired_context !=
3515 to_intel_context(i915->kernel_context, engine));
3516 }
3517}
3518
b29c19b6
CW
3519static void
3520i915_gem_idle_work_handler(struct work_struct *work)
3521{
3522 struct drm_i915_private *dev_priv =
67d97da3 3523 container_of(work, typeof(*dev_priv), gt.idle_work.work);
84a10749 3524 unsigned int epoch = I915_EPOCH_INVALID;
67d97da3
CW
3525 bool rearm_hangcheck;
3526
3527 if (!READ_ONCE(dev_priv->gt.awake))
3528 return;
3529
4dfacb0b
CW
3530 if (READ_ONCE(dev_priv->gt.active_requests))
3531 return;
3532
3533 /*
3534 * Flush out the last user context, leaving only the pinned
3535 * kernel context resident. When we are idling on the kernel_context,
3536 * no more new requests (with a context switch) are emitted and we
3537 * can finally rest. A consequence is that the idle work handler is
3538 * always called at least twice before idling (and if the system is
3539 * idle that implies a round trip through the retire worker).
3540 */
3541 mutex_lock(&dev_priv->drm.struct_mutex);
3542 i915_gem_switch_to_kernel_context(dev_priv);
3543 mutex_unlock(&dev_priv->drm.struct_mutex);
3544
3545 GEM_TRACE("active_requests=%d (after switch-to-kernel-context)\n",
3546 READ_ONCE(dev_priv->gt.active_requests));
3547
0cb5670b
ID
3548 /*
3549 * Wait for last execlists context complete, but bail out in case a
ffed7bd2
CW
3550 * new request is submitted. As we don't trust the hardware, we
3551 * continue on if the wait times out. This is necessary to allow
3552 * the machine to suspend even if the hardware dies, and we will
3553 * try to recover in resume (after depriving the hardware of power,
3554 * it may be in a better mmod).
0cb5670b 3555 */
ffed7bd2
CW
3556 __wait_for(if (new_requests_since_last_retire(dev_priv)) return,
3557 intel_engines_are_idle(dev_priv),
3558 I915_IDLE_ENGINES_TIMEOUT * 1000,
3559 10, 500);
67d97da3
CW
3560
3561 rearm_hangcheck =
3562 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
3563
5427f207 3564 if (!mutex_trylock(&dev_priv->drm.struct_mutex)) {
67d97da3
CW
3565 /* Currently busy, come back later */
3566 mod_delayed_work(dev_priv->wq,
3567 &dev_priv->gt.idle_work,
3568 msecs_to_jiffies(50));
3569 goto out_rearm;
3570 }
3571
93c97dc1
ID
3572 /*
3573 * New request retired after this work handler started, extend active
3574 * period until next instance of the work.
3575 */
5427f207 3576 if (new_requests_since_last_retire(dev_priv))
67d97da3 3577 goto out_unlock;
b29c19b6 3578
e4d2006f 3579 epoch = __i915_gem_park(dev_priv);
35c94185 3580
1934f5de
CW
3581 assert_kernel_context_is_current(dev_priv);
3582
67d97da3 3583 rearm_hangcheck = false;
67d97da3 3584out_unlock:
5427f207 3585 mutex_unlock(&dev_priv->drm.struct_mutex);
b29c19b6 3586
67d97da3
CW
3587out_rearm:
3588 if (rearm_hangcheck) {
3589 GEM_BUG_ON(!dev_priv->gt.awake);
3590 i915_queue_hangcheck(dev_priv);
35c94185 3591 }
84a10749
CW
3592
3593 /*
3594 * When we are idle, it is an opportune time to reap our caches.
3595 * However, we have many objects that utilise RCU and the ordered
3596 * i915->wq that this work is executing on. To try and flush any
3597 * pending frees now we are idle, we first wait for an RCU grace
3598 * period, and then queue a task (that will run last on the wq) to
3599 * shrink and re-optimize the caches.
3600 */
3601 if (same_epoch(dev_priv, epoch)) {
3602 struct sleep_rcu_work *s = kmalloc(sizeof(*s), GFP_KERNEL);
3603 if (s) {
3604 s->i915 = dev_priv;
3605 s->epoch = epoch;
3606 call_rcu(&s->rcu, __sleep_rcu);
3607 }
3608 }
673a394b
EA
3609}
3610
b1f788c6
CW
3611void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
3612{
d1b48c1e 3613 struct drm_i915_private *i915 = to_i915(gem->dev);
b1f788c6
CW
3614 struct drm_i915_gem_object *obj = to_intel_bo(gem);
3615 struct drm_i915_file_private *fpriv = file->driver_priv;
d1b48c1e 3616 struct i915_lut_handle *lut, *ln;
b1f788c6 3617
d1b48c1e
CW
3618 mutex_lock(&i915->drm.struct_mutex);
3619
3620 list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
3621 struct i915_gem_context *ctx = lut->ctx;
3622 struct i915_vma *vma;
3623
432295d7 3624 GEM_BUG_ON(ctx->file_priv == ERR_PTR(-EBADF));
d1b48c1e
CW
3625 if (ctx->file_priv != fpriv)
3626 continue;
3627
3628 vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
3ffff017
CW
3629 GEM_BUG_ON(vma->obj != obj);
3630
3631 /* We allow the process to have multiple handles to the same
3632 * vma, in the same fd namespace, by virtue of flink/open.
3633 */
3634 GEM_BUG_ON(!vma->open_count);
3635 if (!--vma->open_count && !i915_vma_is_ggtt(vma))
b1f788c6 3636 i915_vma_close(vma);
f8a7fde4 3637
d1b48c1e
CW
3638 list_del(&lut->obj_link);
3639 list_del(&lut->ctx_link);
4ff4b44c 3640
d1b48c1e
CW
3641 kmem_cache_free(i915->luts, lut);
3642 __i915_gem_object_release_unless_active(obj);
f8a7fde4 3643 }
d1b48c1e
CW
3644
3645 mutex_unlock(&i915->drm.struct_mutex);
b1f788c6
CW
3646}
3647
e95433c7
CW
3648static unsigned long to_wait_timeout(s64 timeout_ns)
3649{
3650 if (timeout_ns < 0)
3651 return MAX_SCHEDULE_TIMEOUT;
3652
3653 if (timeout_ns == 0)
3654 return 0;
3655
3656 return nsecs_to_jiffies_timeout(timeout_ns);
3657}
3658
23ba4fd0
BW
3659/**
3660 * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
14bb2c11
TU
3661 * @dev: drm device pointer
3662 * @data: ioctl data blob
3663 * @file: drm file pointer
23ba4fd0
BW
3664 *
3665 * Returns 0 if successful, else an error is returned with the remaining time in
3666 * the timeout parameter.
3667 * -ETIME: object is still busy after timeout
3668 * -ERESTARTSYS: signal interrupted the wait
3669 * -ENONENT: object doesn't exist
3670 * Also possible, but rare:
b8050148 3671 * -EAGAIN: incomplete, restart syscall
23ba4fd0
BW
3672 * -ENOMEM: damn
3673 * -ENODEV: Internal IRQ fail
3674 * -E?: The add request failed
3675 *
3676 * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
3677 * non-zero timeout parameter the wait ioctl will wait for the given number of
3678 * nanoseconds on an object becoming unbusy. Since the wait itself does so
3679 * without holding struct_mutex the object may become re-busied before this
3680 * function completes. A similar but shorter * race condition exists in the busy
3681 * ioctl
3682 */
3683int
3684i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3685{
3686 struct drm_i915_gem_wait *args = data;
3687 struct drm_i915_gem_object *obj;
e95433c7
CW
3688 ktime_t start;
3689 long ret;
23ba4fd0 3690
11b5d511
DV
3691 if (args->flags != 0)
3692 return -EINVAL;
3693
03ac0642 3694 obj = i915_gem_object_lookup(file, args->bo_handle);
033d549b 3695 if (!obj)
23ba4fd0 3696 return -ENOENT;
23ba4fd0 3697
e95433c7
CW
3698 start = ktime_get();
3699
3700 ret = i915_gem_object_wait(obj,
3701 I915_WAIT_INTERRUPTIBLE | I915_WAIT_ALL,
3702 to_wait_timeout(args->timeout_ns),
3703 to_rps_client(file));
3704
3705 if (args->timeout_ns > 0) {
3706 args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
3707 if (args->timeout_ns < 0)
3708 args->timeout_ns = 0;
c1d2061b
CW
3709
3710 /*
3711 * Apparently ktime isn't accurate enough and occasionally has a
3712 * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
3713 * things up to make the test happy. We allow up to 1 jiffy.
3714 *
3715 * This is a regression from the timespec->ktime conversion.
3716 */
3717 if (ret == -ETIME && !nsecs_to_jiffies(args->timeout_ns))
3718 args->timeout_ns = 0;
b8050148
CW
3719
3720 /* Asked to wait beyond the jiffie/scheduler precision? */
3721 if (ret == -ETIME && args->timeout_ns)
3722 ret = -EAGAIN;
b4716185
CW
3723 }
3724
f0cd5182 3725 i915_gem_object_put(obj);
ff865885 3726 return ret;
23ba4fd0
BW
3727}
3728
a89d1f92 3729static int wait_for_timeline(struct i915_timeline *tl, unsigned int flags)
4df2faf4 3730{
0606035f
CW
3731 struct i915_request *rq;
3732 long ret;
3733
3734 rq = i915_gem_active_get_unlocked(&tl->last_request);
3735 if (!rq)
3736 return 0;
3737
3738 /*
3739 * "Race-to-idle".
3740 *
3741 * Switching to the kernel context is often used a synchronous
3742 * step prior to idling, e.g. in suspend for flushing all
3743 * current operations to memory before sleeping. These we
3744 * want to complete as quickly as possible to avoid prolonged
3745 * stalls, so allow the gpu to boost to maximum clocks.
3746 */
3747 if (flags & I915_WAIT_FOR_IDLE_BOOST)
3748 gen6_rps_boost(rq, NULL);
3749
3750 ret = i915_request_wait(rq, flags, MAX_SCHEDULE_TIMEOUT);
3751 i915_request_put(rq);
3752
3753 return ret < 0 ? ret : 0;
73cb9701
CW
3754}
3755
25112b64
CW
3756static int wait_for_engines(struct drm_i915_private *i915)
3757{
ee42c00e 3758 if (wait_for(intel_engines_are_idle(i915), I915_IDLE_ENGINES_TIMEOUT)) {
59e4b19d
CW
3759 dev_err(i915->drm.dev,
3760 "Failed to idle engines, declaring wedged!\n");
629820fc 3761 GEM_TRACE_DUMP();
cad9946c
CW
3762 i915_gem_set_wedged(i915);
3763 return -EIO;
25112b64
CW
3764 }
3765
3766 return 0;
3767}
3768
73cb9701
CW
3769int i915_gem_wait_for_idle(struct drm_i915_private *i915, unsigned int flags)
3770{
09a4c02e
CW
3771 GEM_TRACE("flags=%x (%s)\n",
3772 flags, flags & I915_WAIT_LOCKED ? "locked" : "unlocked");
3773
863e9fde
CW
3774 /* If the device is asleep, we have no requests outstanding */
3775 if (!READ_ONCE(i915->gt.awake))
3776 return 0;
3777
9caa34aa 3778 if (flags & I915_WAIT_LOCKED) {
a89d1f92
CW
3779 struct i915_timeline *tl;
3780 int err;
9caa34aa
CW
3781
3782 lockdep_assert_held(&i915->drm.struct_mutex);
3783
3784 list_for_each_entry(tl, &i915->gt.timelines, link) {
a89d1f92
CW
3785 err = wait_for_timeline(tl, flags);
3786 if (err)
3787 return err;
9caa34aa 3788 }
e61e0f51 3789 i915_retire_requests(i915);
09a4c02e 3790 GEM_BUG_ON(i915->gt.active_requests);
25112b64 3791
a89d1f92 3792 return wait_for_engines(i915);
9caa34aa 3793 } else {
a89d1f92
CW
3794 struct intel_engine_cs *engine;
3795 enum intel_engine_id id;
3796 int err;
4df2faf4 3797
a89d1f92
CW
3798 for_each_engine(engine, i915, id) {
3799 err = wait_for_timeline(&engine->timeline, flags);
3800 if (err)
3801 return err;
3802 }
3803
3804 return 0;
3805 }
4df2faf4
DV
3806}
3807
5a97bcc6
CW
3808static void __i915_gem_object_flush_for_display(struct drm_i915_gem_object *obj)
3809{
e27ab73d
CW
3810 /*
3811 * We manually flush the CPU domain so that we can override and
3812 * force the flush for the display, and perform it asyncrhonously.
3813 */
3814 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
3815 if (obj->cache_dirty)
3816 i915_gem_clflush_object(obj, I915_CLFLUSH_FORCE);
c0a51fd0 3817 obj->write_domain = 0;
5a97bcc6
CW
3818}
3819
3820void i915_gem_object_flush_if_display(struct drm_i915_gem_object *obj)
3821{
bd3d2252 3822 if (!READ_ONCE(obj->pin_global))
5a97bcc6
CW
3823 return;
3824
3825 mutex_lock(&obj->base.dev->struct_mutex);
3826 __i915_gem_object_flush_for_display(obj);
3827 mutex_unlock(&obj->base.dev->struct_mutex);
3828}
3829
e22d8e3c
CW
3830/**
3831 * Moves a single object to the WC read, and possibly write domain.
3832 * @obj: object to act on
3833 * @write: ask for write access or read only
3834 *
3835 * This function returns when the move is complete, including waiting on
3836 * flushes to occur.
3837 */
3838int
3839i915_gem_object_set_to_wc_domain(struct drm_i915_gem_object *obj, bool write)
3840{
3841 int ret;
3842
3843 lockdep_assert_held(&obj->base.dev->struct_mutex);
3844
3845 ret = i915_gem_object_wait(obj,
3846 I915_WAIT_INTERRUPTIBLE |
3847 I915_WAIT_LOCKED |
3848 (write ? I915_WAIT_ALL : 0),
3849 MAX_SCHEDULE_TIMEOUT,
3850 NULL);
3851 if (ret)
3852 return ret;
3853
c0a51fd0 3854 if (obj->write_domain == I915_GEM_DOMAIN_WC)
e22d8e3c
CW
3855 return 0;
3856
3857 /* Flush and acquire obj->pages so that we are coherent through
3858 * direct access in memory with previous cached writes through
3859 * shmemfs and that our cache domain tracking remains valid.
3860 * For example, if the obj->filp was moved to swap without us
3861 * being notified and releasing the pages, we would mistakenly
3862 * continue to assume that the obj remained out of the CPU cached
3863 * domain.
3864 */
3865 ret = i915_gem_object_pin_pages(obj);
3866 if (ret)
3867 return ret;
3868
3869 flush_write_domain(obj, ~I915_GEM_DOMAIN_WC);
3870
3871 /* Serialise direct access to this object with the barriers for
3872 * coherent writes from the GPU, by effectively invalidating the
3873 * WC domain upon first access.
3874 */
c0a51fd0 3875 if ((obj->read_domains & I915_GEM_DOMAIN_WC) == 0)
e22d8e3c
CW
3876 mb();
3877
3878 /* It should now be out of any other write domains, and we can update
3879 * the domain values for our changes.
3880 */
c0a51fd0
CK
3881 GEM_BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_WC) != 0);
3882 obj->read_domains |= I915_GEM_DOMAIN_WC;
e22d8e3c 3883 if (write) {
c0a51fd0
CK
3884 obj->read_domains = I915_GEM_DOMAIN_WC;
3885 obj->write_domain = I915_GEM_DOMAIN_WC;
e22d8e3c
CW
3886 obj->mm.dirty = true;
3887 }
3888
3889 i915_gem_object_unpin_pages(obj);
3890 return 0;
3891}
3892
2ef7eeaa
EA
3893/**
3894 * Moves a single object to the GTT read, and possibly write domain.
14bb2c11
TU
3895 * @obj: object to act on
3896 * @write: ask for write access or read only
2ef7eeaa
EA
3897 *
3898 * This function returns when the move is complete, including waiting on
3899 * flushes to occur.
3900 */
79e53945 3901int
2021746e 3902i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
2ef7eeaa 3903{
e47c68e9 3904 int ret;
2ef7eeaa 3905
e95433c7 3906 lockdep_assert_held(&obj->base.dev->struct_mutex);
4c7d62c6 3907
e95433c7
CW
3908 ret = i915_gem_object_wait(obj,
3909 I915_WAIT_INTERRUPTIBLE |
3910 I915_WAIT_LOCKED |
3911 (write ? I915_WAIT_ALL : 0),
3912 MAX_SCHEDULE_TIMEOUT,
3913 NULL);
88241785
CW
3914 if (ret)
3915 return ret;
3916
c0a51fd0 3917 if (obj->write_domain == I915_GEM_DOMAIN_GTT)
c13d87ea
CW
3918 return 0;
3919
43566ded
CW
3920 /* Flush and acquire obj->pages so that we are coherent through
3921 * direct access in memory with previous cached writes through
3922 * shmemfs and that our cache domain tracking remains valid.
3923 * For example, if the obj->filp was moved to swap without us
3924 * being notified and releasing the pages, we would mistakenly
3925 * continue to assume that the obj remained out of the CPU cached
3926 * domain.
3927 */
a4f5ea64 3928 ret = i915_gem_object_pin_pages(obj);
43566ded
CW
3929 if (ret)
3930 return ret;
3931
ef74921b 3932 flush_write_domain(obj, ~I915_GEM_DOMAIN_GTT);
1c5d22f7 3933
d0a57789
CW
3934 /* Serialise direct access to this object with the barriers for
3935 * coherent writes from the GPU, by effectively invalidating the
3936 * GTT domain upon first access.
3937 */
c0a51fd0 3938 if ((obj->read_domains & I915_GEM_DOMAIN_GTT) == 0)
d0a57789
CW
3939 mb();
3940
e47c68e9
EA
3941 /* It should now be out of any other write domains, and we can update
3942 * the domain values for our changes.
3943 */
c0a51fd0
CK
3944 GEM_BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
3945 obj->read_domains |= I915_GEM_DOMAIN_GTT;
e47c68e9 3946 if (write) {
c0a51fd0
CK
3947 obj->read_domains = I915_GEM_DOMAIN_GTT;
3948 obj->write_domain = I915_GEM_DOMAIN_GTT;
a4f5ea64 3949 obj->mm.dirty = true;
2ef7eeaa
EA
3950 }
3951
a4f5ea64 3952 i915_gem_object_unpin_pages(obj);
e47c68e9
EA
3953 return 0;
3954}
3955
ef55f92a
CW
3956/**
3957 * Changes the cache-level of an object across all VMA.
14bb2c11
TU
3958 * @obj: object to act on
3959 * @cache_level: new cache level to set for the object
ef55f92a
CW
3960 *
3961 * After this function returns, the object will be in the new cache-level
3962 * across all GTT and the contents of the backing storage will be coherent,
3963 * with respect to the new cache-level. In order to keep the backing storage
3964 * coherent for all users, we only allow a single cache level to be set
3965 * globally on the object and prevent it from being changed whilst the
3966 * hardware is reading from the object. That is if the object is currently
3967 * on the scanout it will be set to uncached (or equivalent display
3968 * cache coherency) and all non-MOCS GPU access will also be uncached so
3969 * that all direct access to the scanout remains coherent.
3970 */
e4ffd173
CW
3971int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
3972 enum i915_cache_level cache_level)
3973{
aa653a68 3974 struct i915_vma *vma;
a6a7cc4b 3975 int ret;
e4ffd173 3976
4c7d62c6
CW
3977 lockdep_assert_held(&obj->base.dev->struct_mutex);
3978
e4ffd173 3979 if (obj->cache_level == cache_level)
a6a7cc4b 3980 return 0;
e4ffd173 3981
ef55f92a
CW
3982 /* Inspect the list of currently bound VMA and unbind any that would
3983 * be invalid given the new cache-level. This is principally to
3984 * catch the issue of the CS prefetch crossing page boundaries and
3985 * reading an invalid PTE on older architectures.
3986 */
aa653a68
CW
3987restart:
3988 list_for_each_entry(vma, &obj->vma_list, obj_link) {
ef55f92a
CW
3989 if (!drm_mm_node_allocated(&vma->node))
3990 continue;
3991
20dfbde4 3992 if (i915_vma_is_pinned(vma)) {
ef55f92a
CW
3993 DRM_DEBUG("can not change the cache level of pinned objects\n");
3994 return -EBUSY;
3995 }
3996
010e3e68
CW
3997 if (!i915_vma_is_closed(vma) &&
3998 i915_gem_valid_gtt_space(vma, cache_level))
aa653a68
CW
3999 continue;
4000
4001 ret = i915_vma_unbind(vma);
4002 if (ret)
4003 return ret;
4004
4005 /* As unbinding may affect other elements in the
4006 * obj->vma_list (due to side-effects from retiring
4007 * an active vma), play safe and restart the iterator.
4008 */
4009 goto restart;
42d6ab48
CW
4010 }
4011
ef55f92a
CW
4012 /* We can reuse the existing drm_mm nodes but need to change the
4013 * cache-level on the PTE. We could simply unbind them all and
4014 * rebind with the correct cache-level on next use. However since
4015 * we already have a valid slot, dma mapping, pages etc, we may as
4016 * rewrite the PTE in the belief that doing so tramples upon less
4017 * state and so involves less work.
4018 */
15717de2 4019 if (obj->bind_count) {
ef55f92a
CW
4020 /* Before we change the PTE, the GPU must not be accessing it.
4021 * If we wait upon the object, we know that all the bound
4022 * VMA are no longer active.
4023 */
e95433c7
CW
4024 ret = i915_gem_object_wait(obj,
4025 I915_WAIT_INTERRUPTIBLE |
4026 I915_WAIT_LOCKED |
4027 I915_WAIT_ALL,
4028 MAX_SCHEDULE_TIMEOUT,
4029 NULL);
e4ffd173
CW
4030 if (ret)
4031 return ret;
4032
0031fb96
TU
4033 if (!HAS_LLC(to_i915(obj->base.dev)) &&
4034 cache_level != I915_CACHE_NONE) {
ef55f92a
CW
4035 /* Access to snoopable pages through the GTT is
4036 * incoherent and on some machines causes a hard
4037 * lockup. Relinquish the CPU mmaping to force
4038 * userspace to refault in the pages and we can
4039 * then double check if the GTT mapping is still
4040 * valid for that pointer access.
4041 */
4042 i915_gem_release_mmap(obj);
4043
4044 /* As we no longer need a fence for GTT access,
4045 * we can relinquish it now (and so prevent having
4046 * to steal a fence from someone else on the next
4047 * fence request). Note GPU activity would have
4048 * dropped the fence as all snoopable access is
4049 * supposed to be linear.
4050 */
e2189dd0 4051 for_each_ggtt_vma(vma, obj) {
49ef5294
CW
4052 ret = i915_vma_put_fence(vma);
4053 if (ret)
4054 return ret;
4055 }
ef55f92a
CW
4056 } else {
4057 /* We either have incoherent backing store and
4058 * so no GTT access or the architecture is fully
4059 * coherent. In such cases, existing GTT mmaps
4060 * ignore the cache bit in the PTE and we can
4061 * rewrite it without confusing the GPU or having
4062 * to force userspace to fault back in its mmaps.
4063 */
e4ffd173
CW
4064 }
4065
1c7f4bca 4066 list_for_each_entry(vma, &obj->vma_list, obj_link) {
ef55f92a
CW
4067 if (!drm_mm_node_allocated(&vma->node))
4068 continue;
4069
4070 ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
4071 if (ret)
4072 return ret;
4073 }
e4ffd173
CW
4074 }
4075
1c7f4bca 4076 list_for_each_entry(vma, &obj->vma_list, obj_link)
2c22569b 4077 vma->node.color = cache_level;
b8f55be6 4078 i915_gem_object_set_cache_coherency(obj, cache_level);
e27ab73d 4079 obj->cache_dirty = true; /* Always invalidate stale cachelines */
2c22569b 4080
e4ffd173
CW
4081 return 0;
4082}
4083
199adf40
BW
4084int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
4085 struct drm_file *file)
e6994aee 4086{
199adf40 4087 struct drm_i915_gem_caching *args = data;
e6994aee 4088 struct drm_i915_gem_object *obj;
fbbd37b3 4089 int err = 0;
e6994aee 4090
fbbd37b3
CW
4091 rcu_read_lock();
4092 obj = i915_gem_object_lookup_rcu(file, args->handle);
4093 if (!obj) {
4094 err = -ENOENT;
4095 goto out;
4096 }
e6994aee 4097
651d794f
CW
4098 switch (obj->cache_level) {
4099 case I915_CACHE_LLC:
4100 case I915_CACHE_L3_LLC:
4101 args->caching = I915_CACHING_CACHED;
4102 break;
4103
4257d3ba
CW
4104 case I915_CACHE_WT:
4105 args->caching = I915_CACHING_DISPLAY;
4106 break;
4107
651d794f
CW
4108 default:
4109 args->caching = I915_CACHING_NONE;
4110 break;
4111 }
fbbd37b3
CW
4112out:
4113 rcu_read_unlock();
4114 return err;
e6994aee
CW
4115}
4116
199adf40
BW
4117int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
4118 struct drm_file *file)
e6994aee 4119{
9c870d03 4120 struct drm_i915_private *i915 = to_i915(dev);
199adf40 4121 struct drm_i915_gem_caching *args = data;
e6994aee
CW
4122 struct drm_i915_gem_object *obj;
4123 enum i915_cache_level level;
d65415df 4124 int ret = 0;
e6994aee 4125
199adf40
BW
4126 switch (args->caching) {
4127 case I915_CACHING_NONE:
e6994aee
CW
4128 level = I915_CACHE_NONE;
4129 break;
199adf40 4130 case I915_CACHING_CACHED:
e5756c10
ID
4131 /*
4132 * Due to a HW issue on BXT A stepping, GPU stores via a
4133 * snooped mapping may leave stale data in a corresponding CPU
4134 * cacheline, whereas normally such cachelines would get
4135 * invalidated.
4136 */
9c870d03 4137 if (!HAS_LLC(i915) && !HAS_SNOOP(i915))
e5756c10
ID
4138 return -ENODEV;
4139
e6994aee
CW
4140 level = I915_CACHE_LLC;
4141 break;
4257d3ba 4142 case I915_CACHING_DISPLAY:
9c870d03 4143 level = HAS_WT(i915) ? I915_CACHE_WT : I915_CACHE_NONE;
4257d3ba 4144 break;
e6994aee
CW
4145 default:
4146 return -EINVAL;
4147 }
4148
d65415df
CW
4149 obj = i915_gem_object_lookup(file, args->handle);
4150 if (!obj)
4151 return -ENOENT;
4152
a03f395a
TZ
4153 /*
4154 * The caching mode of proxy object is handled by its generator, and
4155 * not allowed to be changed by userspace.
4156 */
4157 if (i915_gem_object_is_proxy(obj)) {
4158 ret = -ENXIO;
4159 goto out;
4160 }
4161
d65415df
CW
4162 if (obj->cache_level == level)
4163 goto out;
4164
4165 ret = i915_gem_object_wait(obj,
4166 I915_WAIT_INTERRUPTIBLE,
4167 MAX_SCHEDULE_TIMEOUT,
4168 to_rps_client(file));
3bc2913e 4169 if (ret)
d65415df 4170 goto out;
3bc2913e 4171
d65415df
CW
4172 ret = i915_mutex_lock_interruptible(dev);
4173 if (ret)
4174 goto out;
e6994aee
CW
4175
4176 ret = i915_gem_object_set_cache_level(obj, level);
e6994aee 4177 mutex_unlock(&dev->struct_mutex);
d65415df
CW
4178
4179out:
4180 i915_gem_object_put(obj);
e6994aee
CW
4181 return ret;
4182}
4183
b9241ea3 4184/*
07bcd99b
DP
4185 * Prepare buffer for display plane (scanout, cursors, etc). Can be called from
4186 * an uninterruptible phase (modesetting) and allows any flushes to be pipelined
4187 * (for pageflips). We only flush the caches while preparing the buffer for
4188 * display, the callers are responsible for frontbuffer flush.
b9241ea3 4189 */
058d88c4 4190struct i915_vma *
2da3b9b9
CW
4191i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
4192 u32 alignment,
5935485f
CW
4193 const struct i915_ggtt_view *view,
4194 unsigned int flags)
b9241ea3 4195{
058d88c4 4196 struct i915_vma *vma;
b9241ea3
ZW
4197 int ret;
4198
4c7d62c6
CW
4199 lockdep_assert_held(&obj->base.dev->struct_mutex);
4200
bd3d2252 4201 /* Mark the global pin early so that we account for the
cc98b413
CW
4202 * display coherency whilst setting up the cache domains.
4203 */
bd3d2252 4204 obj->pin_global++;
cc98b413 4205
a7ef0640
EA
4206 /* The display engine is not coherent with the LLC cache on gen6. As
4207 * a result, we make sure that the pinning that is about to occur is
4208 * done with uncached PTEs. This is lowest common denominator for all
4209 * chipsets.
4210 *
4211 * However for gen6+, we could do better by using the GFDT bit instead
4212 * of uncaching, which would allow us to flush all the LLC-cached data
4213 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
4214 */
651d794f 4215 ret = i915_gem_object_set_cache_level(obj,
8652744b
TU
4216 HAS_WT(to_i915(obj->base.dev)) ?
4217 I915_CACHE_WT : I915_CACHE_NONE);
058d88c4
CW
4218 if (ret) {
4219 vma = ERR_PTR(ret);
bd3d2252 4220 goto err_unpin_global;
058d88c4 4221 }
a7ef0640 4222
2da3b9b9
CW
4223 /* As the user may map the buffer once pinned in the display plane
4224 * (e.g. libkms for the bootup splash), we have to ensure that we
2efb813d
CW
4225 * always use map_and_fenceable for all scanout buffers. However,
4226 * it may simply be too big to fit into mappable, in which case
4227 * put it anyway and hope that userspace can cope (but always first
4228 * try to preserve the existing ABI).
2da3b9b9 4229 */
2efb813d 4230 vma = ERR_PTR(-ENOSPC);
5935485f
CW
4231 if ((flags & PIN_MAPPABLE) == 0 &&
4232 (!view || view->type == I915_GGTT_VIEW_NORMAL))
2efb813d 4233 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment,
5935485f
CW
4234 flags |
4235 PIN_MAPPABLE |
4236 PIN_NONBLOCK);
4237 if (IS_ERR(vma))
767a222e 4238 vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment, flags);
058d88c4 4239 if (IS_ERR(vma))
bd3d2252 4240 goto err_unpin_global;
2da3b9b9 4241
d8923dcf
CW
4242 vma->display_alignment = max_t(u64, vma->display_alignment, alignment);
4243
5a97bcc6 4244 __i915_gem_object_flush_for_display(obj);
b118c1e3 4245
2da3b9b9
CW
4246 /* It should now be out of any other write domains, and we can update
4247 * the domain values for our changes.
4248 */
c0a51fd0 4249 obj->read_domains |= I915_GEM_DOMAIN_GTT;
b9241ea3 4250
058d88c4 4251 return vma;
cc98b413 4252
bd3d2252
CW
4253err_unpin_global:
4254 obj->pin_global--;
058d88c4 4255 return vma;
cc98b413
CW
4256}
4257
4258void
058d88c4 4259i915_gem_object_unpin_from_display_plane(struct i915_vma *vma)
cc98b413 4260{
49d73912 4261 lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
4c7d62c6 4262
bd3d2252 4263 if (WARN_ON(vma->obj->pin_global == 0))
8a0c39b1
TU
4264 return;
4265
bd3d2252 4266 if (--vma->obj->pin_global == 0)
f51455d4 4267 vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
e6617330 4268
383d5823 4269 /* Bump the LRU to try and avoid premature eviction whilst flipping */
befedbb7 4270 i915_gem_object_bump_inactive_ggtt(vma->obj);
383d5823 4271
058d88c4 4272 i915_vma_unpin(vma);
b9241ea3
ZW
4273}
4274
e47c68e9
EA
4275/**
4276 * Moves a single object to the CPU read, and possibly write domain.
14bb2c11
TU
4277 * @obj: object to act on
4278 * @write: requesting write or read-only access
e47c68e9
EA
4279 *
4280 * This function returns when the move is complete, including waiting on
4281 * flushes to occur.
4282 */
dabdfe02 4283int
919926ae 4284i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
e47c68e9 4285{
e47c68e9
EA
4286 int ret;
4287
e95433c7 4288 lockdep_assert_held(&obj->base.dev->struct_mutex);
4c7d62c6 4289
e95433c7
CW
4290 ret = i915_gem_object_wait(obj,
4291 I915_WAIT_INTERRUPTIBLE |
4292 I915_WAIT_LOCKED |
4293 (write ? I915_WAIT_ALL : 0),
4294 MAX_SCHEDULE_TIMEOUT,
4295 NULL);
88241785
CW
4296 if (ret)
4297 return ret;
4298
ef74921b 4299 flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
2ef7eeaa 4300
e47c68e9 4301 /* Flush the CPU cache if it's still invalid. */
c0a51fd0 4302 if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
57822dc6 4303 i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
c0a51fd0 4304 obj->read_domains |= I915_GEM_DOMAIN_CPU;
2ef7eeaa
EA
4305 }
4306
4307 /* It should now be out of any other write domains, and we can update
4308 * the domain values for our changes.
4309 */
c0a51fd0 4310 GEM_BUG_ON(obj->write_domain & ~I915_GEM_DOMAIN_CPU);
e47c68e9
EA
4311
4312 /* If we're writing through the CPU, then the GPU read domains will
4313 * need to be invalidated at next use.
4314 */
e27ab73d
CW
4315 if (write)
4316 __start_cpu_write(obj);
2ef7eeaa
EA
4317
4318 return 0;
4319}
4320
673a394b
EA
4321/* Throttle our rendering by waiting until the ring has completed our requests
4322 * emitted over 20 msec ago.
4323 *
b962442e
EA
4324 * Note that if we were to use the current jiffies each time around the loop,
4325 * we wouldn't escape the function with any frames outstanding if the time to
4326 * render a frame was over 20ms.
4327 *
673a394b
EA
4328 * This should get us reasonable parallelism between CPU and GPU but also
4329 * relatively low latency when blocking on a particular request to finish.
4330 */
40a5f0de 4331static int
f787a5f5 4332i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
40a5f0de 4333{
fac5e23e 4334 struct drm_i915_private *dev_priv = to_i915(dev);
f787a5f5 4335 struct drm_i915_file_private *file_priv = file->driver_priv;
d0bc54f2 4336 unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
e61e0f51 4337 struct i915_request *request, *target = NULL;
e95433c7 4338 long ret;
93533c29 4339
f4457ae7
CW
4340 /* ABI: return -EIO if already wedged */
4341 if (i915_terminally_wedged(&dev_priv->gpu_error))
4342 return -EIO;
e110e8d6 4343
1c25595f 4344 spin_lock(&file_priv->mm.lock);
c8659efa 4345 list_for_each_entry(request, &file_priv->mm.request_list, client_link) {
b962442e
EA
4346 if (time_after_eq(request->emitted_jiffies, recent_enough))
4347 break;
40a5f0de 4348
c8659efa
CW
4349 if (target) {
4350 list_del(&target->client_link);
4351 target->file_priv = NULL;
4352 }
fcfa423c 4353
54fb2411 4354 target = request;
b962442e 4355 }
ff865885 4356 if (target)
e61e0f51 4357 i915_request_get(target);
1c25595f 4358 spin_unlock(&file_priv->mm.lock);
40a5f0de 4359
54fb2411 4360 if (target == NULL)
f787a5f5 4361 return 0;
2bc43b5c 4362
e61e0f51 4363 ret = i915_request_wait(target,
e95433c7
CW
4364 I915_WAIT_INTERRUPTIBLE,
4365 MAX_SCHEDULE_TIMEOUT);
e61e0f51 4366 i915_request_put(target);
ff865885 4367
e95433c7 4368 return ret < 0 ? ret : 0;
40a5f0de
EA
4369}
4370
058d88c4 4371struct i915_vma *
ec7adb6e
JL
4372i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
4373 const struct i915_ggtt_view *view,
91b2db6f 4374 u64 size,
2ffffd0f
CW
4375 u64 alignment,
4376 u64 flags)
ec7adb6e 4377{
ad16d2ed 4378 struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
82ad6443 4379 struct i915_address_space *vm = &dev_priv->ggtt.vm;
59bfa124
CW
4380 struct i915_vma *vma;
4381 int ret;
72e96d64 4382
4c7d62c6
CW
4383 lockdep_assert_held(&obj->base.dev->struct_mutex);
4384
ac87a6fd
CW
4385 if (flags & PIN_MAPPABLE &&
4386 (!view || view->type == I915_GGTT_VIEW_NORMAL)) {
43ae70d9
CW
4387 /* If the required space is larger than the available
4388 * aperture, we will not able to find a slot for the
4389 * object and unbinding the object now will be in
4390 * vain. Worse, doing so may cause us to ping-pong
4391 * the object in and out of the Global GTT and
4392 * waste a lot of cycles under the mutex.
4393 */
4394 if (obj->base.size > dev_priv->ggtt.mappable_end)
4395 return ERR_PTR(-E2BIG);
4396
4397 /* If NONBLOCK is set the caller is optimistically
4398 * trying to cache the full object within the mappable
4399 * aperture, and *must* have a fallback in place for
4400 * situations where we cannot bind the object. We
4401 * can be a little more lax here and use the fallback
4402 * more often to avoid costly migrations of ourselves
4403 * and other objects within the aperture.
4404 *
4405 * Half-the-aperture is used as a simple heuristic.
4406 * More interesting would to do search for a free
4407 * block prior to making the commitment to unbind.
4408 * That caters for the self-harm case, and with a
4409 * little more heuristics (e.g. NOFAULT, NOEVICT)
4410 * we could try to minimise harm to others.
4411 */
4412 if (flags & PIN_NONBLOCK &&
4413 obj->base.size > dev_priv->ggtt.mappable_end / 2)
4414 return ERR_PTR(-ENOSPC);
4415 }
4416
718659a6 4417 vma = i915_vma_instance(obj, vm, view);
e0216b76 4418 if (unlikely(IS_ERR(vma)))
058d88c4 4419 return vma;
59bfa124
CW
4420
4421 if (i915_vma_misplaced(vma, size, alignment, flags)) {
43ae70d9
CW
4422 if (flags & PIN_NONBLOCK) {
4423 if (i915_vma_is_pinned(vma) || i915_vma_is_active(vma))
4424 return ERR_PTR(-ENOSPC);
59bfa124 4425
43ae70d9 4426 if (flags & PIN_MAPPABLE &&
944397f0 4427 vma->fence_size > dev_priv->ggtt.mappable_end / 2)
ad16d2ed
CW
4428 return ERR_PTR(-ENOSPC);
4429 }
4430
59bfa124
CW
4431 WARN(i915_vma_is_pinned(vma),
4432 "bo is already pinned in ggtt with incorrect alignment:"
05a20d09
CW
4433 " offset=%08x, req.alignment=%llx,"
4434 " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
4435 i915_ggtt_offset(vma), alignment,
59bfa124 4436 !!(flags & PIN_MAPPABLE),
05a20d09 4437 i915_vma_is_map_and_fenceable(vma));
59bfa124
CW
4438 ret = i915_vma_unbind(vma);
4439 if (ret)
058d88c4 4440 return ERR_PTR(ret);
59bfa124
CW
4441 }
4442
058d88c4
CW
4443 ret = i915_vma_pin(vma, size, alignment, flags | PIN_GLOBAL);
4444 if (ret)
4445 return ERR_PTR(ret);
ec7adb6e 4446
058d88c4 4447 return vma;
673a394b
EA
4448}
4449
edf6b76f 4450static __always_inline unsigned int __busy_read_flag(unsigned int id)
3fdc13c7
CW
4451{
4452 /* Note that we could alias engines in the execbuf API, but
4453 * that would be very unwise as it prevents userspace from
4454 * fine control over engine selection. Ahem.
4455 *
4456 * This should be something like EXEC_MAX_ENGINE instead of
4457 * I915_NUM_ENGINES.
4458 */
4459 BUILD_BUG_ON(I915_NUM_ENGINES > 16);
4460 return 0x10000 << id;
4461}
4462
4463static __always_inline unsigned int __busy_write_id(unsigned int id)
4464{
70cb472c
CW
4465 /* The uABI guarantees an active writer is also amongst the read
4466 * engines. This would be true if we accessed the activity tracking
4467 * under the lock, but as we perform the lookup of the object and
4468 * its activity locklessly we can not guarantee that the last_write
4469 * being active implies that we have set the same engine flag from
4470 * last_read - hence we always set both read and write busy for
4471 * last_write.
4472 */
4473 return id | __busy_read_flag(id);
3fdc13c7
CW
4474}
4475
edf6b76f 4476static __always_inline unsigned int
d07f0e59 4477__busy_set_if_active(const struct dma_fence *fence,
3fdc13c7
CW
4478 unsigned int (*flag)(unsigned int id))
4479{
e61e0f51 4480 struct i915_request *rq;
3fdc13c7 4481
d07f0e59
CW
4482 /* We have to check the current hw status of the fence as the uABI
4483 * guarantees forward progress. We could rely on the idle worker
4484 * to eventually flush us, but to minimise latency just ask the
4485 * hardware.
1255501d 4486 *
d07f0e59 4487 * Note we only report on the status of native fences.
1255501d 4488 */
d07f0e59
CW
4489 if (!dma_fence_is_i915(fence))
4490 return 0;
4491
4492 /* opencode to_request() in order to avoid const warnings */
e61e0f51
CW
4493 rq = container_of(fence, struct i915_request, fence);
4494 if (i915_request_completed(rq))
d07f0e59
CW
4495 return 0;
4496
1d39f281 4497 return flag(rq->engine->uabi_id);
3fdc13c7
CW
4498}
4499
edf6b76f 4500static __always_inline unsigned int
d07f0e59 4501busy_check_reader(const struct dma_fence *fence)
3fdc13c7 4502{
d07f0e59 4503 return __busy_set_if_active(fence, __busy_read_flag);
3fdc13c7
CW
4504}
4505
edf6b76f 4506static __always_inline unsigned int
d07f0e59 4507busy_check_writer(const struct dma_fence *fence)
3fdc13c7 4508{
d07f0e59
CW
4509 if (!fence)
4510 return 0;
4511
4512 return __busy_set_if_active(fence, __busy_write_id);
3fdc13c7
CW
4513}
4514
673a394b
EA
4515int
4516i915_gem_busy_ioctl(struct drm_device *dev, void *data,
05394f39 4517 struct drm_file *file)
673a394b
EA
4518{
4519 struct drm_i915_gem_busy *args = data;
05394f39 4520 struct drm_i915_gem_object *obj;
d07f0e59
CW
4521 struct reservation_object_list *list;
4522 unsigned int seq;
fbbd37b3 4523 int err;
673a394b 4524
d07f0e59 4525 err = -ENOENT;
fbbd37b3
CW
4526 rcu_read_lock();
4527 obj = i915_gem_object_lookup_rcu(file, args->handle);
d07f0e59 4528 if (!obj)
fbbd37b3 4529 goto out;
d1b851fc 4530
d07f0e59
CW
4531 /* A discrepancy here is that we do not report the status of
4532 * non-i915 fences, i.e. even though we may report the object as idle,
4533 * a call to set-domain may still stall waiting for foreign rendering.
4534 * This also means that wait-ioctl may report an object as busy,
4535 * where busy-ioctl considers it idle.
4536 *
4537 * We trade the ability to warn of foreign fences to report on which
4538 * i915 engines are active for the object.
4539 *
4540 * Alternatively, we can trade that extra information on read/write
4541 * activity with
4542 * args->busy =
4543 * !reservation_object_test_signaled_rcu(obj->resv, true);
4544 * to report the overall busyness. This is what the wait-ioctl does.
4545 *
4546 */
4547retry:
4548 seq = raw_read_seqcount(&obj->resv->seq);
426960be 4549
d07f0e59
CW
4550 /* Translate the exclusive fence to the READ *and* WRITE engine */
4551 args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
3fdc13c7 4552
d07f0e59
CW
4553 /* Translate shared fences to READ set of engines */
4554 list = rcu_dereference(obj->resv->fence);
4555 if (list) {
4556 unsigned int shared_count = list->shared_count, i;
3fdc13c7 4557
d07f0e59
CW
4558 for (i = 0; i < shared_count; ++i) {
4559 struct dma_fence *fence =
4560 rcu_dereference(list->shared[i]);
4561
4562 args->busy |= busy_check_reader(fence);
4563 }
426960be 4564 }
673a394b 4565
d07f0e59
CW
4566 if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
4567 goto retry;
4568
4569 err = 0;
fbbd37b3
CW
4570out:
4571 rcu_read_unlock();
4572 return err;
673a394b
EA
4573}
4574
4575int
4576i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4577 struct drm_file *file_priv)
4578{
0206e353 4579 return i915_gem_ring_throttle(dev, file_priv);
673a394b
EA
4580}
4581
3ef94daa
CW
4582int
4583i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4584 struct drm_file *file_priv)
4585{
fac5e23e 4586 struct drm_i915_private *dev_priv = to_i915(dev);
3ef94daa 4587 struct drm_i915_gem_madvise *args = data;
05394f39 4588 struct drm_i915_gem_object *obj;
1233e2db 4589 int err;
3ef94daa
CW
4590
4591 switch (args->madv) {
4592 case I915_MADV_DONTNEED:
4593 case I915_MADV_WILLNEED:
4594 break;
4595 default:
4596 return -EINVAL;
4597 }
4598
03ac0642 4599 obj = i915_gem_object_lookup(file_priv, args->handle);
1233e2db
CW
4600 if (!obj)
4601 return -ENOENT;
4602
4603 err = mutex_lock_interruptible(&obj->mm.lock);
4604 if (err)
4605 goto out;
3ef94daa 4606
f1fa4f44 4607 if (i915_gem_object_has_pages(obj) &&
3e510a8e 4608 i915_gem_object_is_tiled(obj) &&
656bfa3a 4609 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
bc0629a7
CW
4610 if (obj->mm.madv == I915_MADV_WILLNEED) {
4611 GEM_BUG_ON(!obj->mm.quirked);
a4f5ea64 4612 __i915_gem_object_unpin_pages(obj);
bc0629a7
CW
4613 obj->mm.quirked = false;
4614 }
4615 if (args->madv == I915_MADV_WILLNEED) {
2c3a3f44 4616 GEM_BUG_ON(obj->mm.quirked);
a4f5ea64 4617 __i915_gem_object_pin_pages(obj);
bc0629a7
CW
4618 obj->mm.quirked = true;
4619 }
656bfa3a
DV
4620 }
4621
a4f5ea64
CW
4622 if (obj->mm.madv != __I915_MADV_PURGED)
4623 obj->mm.madv = args->madv;
3ef94daa 4624
6c085a72 4625 /* if the object is no longer attached, discard its backing storage */
f1fa4f44
CW
4626 if (obj->mm.madv == I915_MADV_DONTNEED &&
4627 !i915_gem_object_has_pages(obj))
2d7ef395
CW
4628 i915_gem_object_truncate(obj);
4629
a4f5ea64 4630 args->retained = obj->mm.madv != __I915_MADV_PURGED;
1233e2db 4631 mutex_unlock(&obj->mm.lock);
bb6baf76 4632
1233e2db 4633out:
f8c417cd 4634 i915_gem_object_put(obj);
1233e2db 4635 return err;
3ef94daa
CW
4636}
4637
5b8c8aec 4638static void
e61e0f51 4639frontbuffer_retire(struct i915_gem_active *active, struct i915_request *request)
5b8c8aec
CW
4640{
4641 struct drm_i915_gem_object *obj =
4642 container_of(active, typeof(*obj), frontbuffer_write);
4643
d59b21ec 4644 intel_fb_obj_flush(obj, ORIGIN_CS);
5b8c8aec
CW
4645}
4646
37e680a1
CW
4647void i915_gem_object_init(struct drm_i915_gem_object *obj,
4648 const struct drm_i915_gem_object_ops *ops)
0327d6ba 4649{
1233e2db
CW
4650 mutex_init(&obj->mm.lock);
4651
2f633156 4652 INIT_LIST_HEAD(&obj->vma_list);
d1b48c1e 4653 INIT_LIST_HEAD(&obj->lut_list);
8d9d5744 4654 INIT_LIST_HEAD(&obj->batch_pool_link);
0327d6ba 4655
37e680a1
CW
4656 obj->ops = ops;
4657
d07f0e59
CW
4658 reservation_object_init(&obj->__builtin_resv);
4659 obj->resv = &obj->__builtin_resv;
4660
50349247 4661 obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
5b8c8aec 4662 init_request_active(&obj->frontbuffer_write, frontbuffer_retire);
a4f5ea64
CW
4663
4664 obj->mm.madv = I915_MADV_WILLNEED;
4665 INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
4666 mutex_init(&obj->mm.get_page.lock);
0327d6ba 4667
f19ec8cb 4668 i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
0327d6ba
CW
4669}
4670
37e680a1 4671static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
3599a91c
TU
4672 .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
4673 I915_GEM_OBJECT_IS_SHRINKABLE,
7c55e2c5 4674
37e680a1
CW
4675 .get_pages = i915_gem_object_get_pages_gtt,
4676 .put_pages = i915_gem_object_put_pages_gtt,
7c55e2c5
CW
4677
4678 .pwrite = i915_gem_object_pwrite_gtt,
37e680a1
CW
4679};
4680
465c403c
MA
4681static int i915_gem_object_create_shmem(struct drm_device *dev,
4682 struct drm_gem_object *obj,
4683 size_t size)
4684{
4685 struct drm_i915_private *i915 = to_i915(dev);
4686 unsigned long flags = VM_NORESERVE;
4687 struct file *filp;
4688
4689 drm_gem_private_object_init(dev, obj, size);
4690
4691 if (i915->mm.gemfs)
4692 filp = shmem_file_setup_with_mnt(i915->mm.gemfs, "i915", size,
4693 flags);
4694 else
4695 filp = shmem_file_setup("i915", size, flags);
4696
4697 if (IS_ERR(filp))
4698 return PTR_ERR(filp);
4699
4700 obj->filp = filp;
4701
4702 return 0;
4703}
4704
b4bcbe2a 4705struct drm_i915_gem_object *
12d79d78 4706i915_gem_object_create(struct drm_i915_private *dev_priv, u64 size)
ac52bc56 4707{
c397b908 4708 struct drm_i915_gem_object *obj;
5949eac4 4709 struct address_space *mapping;
b8f55be6 4710 unsigned int cache_level;
1a240d4d 4711 gfp_t mask;
fe3db79b 4712 int ret;
ac52bc56 4713
b4bcbe2a
CW
4714 /* There is a prevalence of the assumption that we fit the object's
4715 * page count inside a 32bit _signed_ variable. Let's document this and
4716 * catch if we ever need to fix it. In the meantime, if you do spot
4717 * such a local variable, please consider fixing!
4718 */
7a3ee5de 4719 if (size >> PAGE_SHIFT > INT_MAX)
b4bcbe2a
CW
4720 return ERR_PTR(-E2BIG);
4721
4722 if (overflows_type(size, obj->base.size))
4723 return ERR_PTR(-E2BIG);
4724
187685cb 4725 obj = i915_gem_object_alloc(dev_priv);
c397b908 4726 if (obj == NULL)
fe3db79b 4727 return ERR_PTR(-ENOMEM);
673a394b 4728
465c403c 4729 ret = i915_gem_object_create_shmem(&dev_priv->drm, &obj->base, size);
fe3db79b
CW
4730 if (ret)
4731 goto fail;
673a394b 4732
bed1ea95 4733 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
c0f86832 4734 if (IS_I965GM(dev_priv) || IS_I965G(dev_priv)) {
bed1ea95
CW
4735 /* 965gm cannot relocate objects above 4GiB. */
4736 mask &= ~__GFP_HIGHMEM;
4737 mask |= __GFP_DMA32;
4738 }
4739
93c76a3d 4740 mapping = obj->base.filp->f_mapping;
bed1ea95 4741 mapping_set_gfp_mask(mapping, mask);
4846bf0c 4742 GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
5949eac4 4743
37e680a1 4744 i915_gem_object_init(obj, &i915_gem_object_ops);
73aa808f 4745
c0a51fd0
CK
4746 obj->write_domain = I915_GEM_DOMAIN_CPU;
4747 obj->read_domains = I915_GEM_DOMAIN_CPU;
673a394b 4748
b8f55be6 4749 if (HAS_LLC(dev_priv))
3d29b842 4750 /* On some devices, we can have the GPU use the LLC (the CPU
a1871112
EA
4751 * cache) for about a 10% performance improvement
4752 * compared to uncached. Graphics requests other than
4753 * display scanout are coherent with the CPU in
4754 * accessing this cache. This means in this mode we
4755 * don't need to clflush on the CPU side, and on the
4756 * GPU side we only need to flush internal caches to
4757 * get data visible to the CPU.
4758 *
4759 * However, we maintain the display planes as UC, and so
4760 * need to rebind when first used as such.
4761 */
b8f55be6
CW
4762 cache_level = I915_CACHE_LLC;
4763 else
4764 cache_level = I915_CACHE_NONE;
a1871112 4765
b8f55be6 4766 i915_gem_object_set_cache_coherency(obj, cache_level);
e27ab73d 4767
d861e338
DV
4768 trace_i915_gem_object_create(obj);
4769
05394f39 4770 return obj;
fe3db79b
CW
4771
4772fail:
4773 i915_gem_object_free(obj);
fe3db79b 4774 return ERR_PTR(ret);
c397b908
DV
4775}
4776
340fbd8c
CW
4777static bool discard_backing_storage(struct drm_i915_gem_object *obj)
4778{
4779 /* If we are the last user of the backing storage (be it shmemfs
4780 * pages or stolen etc), we know that the pages are going to be
4781 * immediately released. In this case, we can then skip copying
4782 * back the contents from the GPU.
4783 */
4784
a4f5ea64 4785 if (obj->mm.madv != I915_MADV_WILLNEED)
340fbd8c
CW
4786 return false;
4787
4788 if (obj->base.filp == NULL)
4789 return true;
4790
4791 /* At first glance, this looks racy, but then again so would be
4792 * userspace racing mmap against close. However, the first external
4793 * reference to the filp can only be obtained through the
4794 * i915_gem_mmap_ioctl() which safeguards us against the user
4795 * acquiring such a reference whilst we are in the middle of
4796 * freeing the object.
4797 */
4798 return atomic_long_read(&obj->base.filp->f_count) == 1;
4799}
4800
fbbd37b3
CW
4801static void __i915_gem_free_objects(struct drm_i915_private *i915,
4802 struct llist_node *freed)
673a394b 4803{
fbbd37b3 4804 struct drm_i915_gem_object *obj, *on;
673a394b 4805
fbbd37b3 4806 intel_runtime_pm_get(i915);
cc731f5a 4807 llist_for_each_entry_safe(obj, on, freed, freed) {
fbbd37b3
CW
4808 struct i915_vma *vma, *vn;
4809
4810 trace_i915_gem_object_destroy(obj);
4811
cc731f5a
CW
4812 mutex_lock(&i915->drm.struct_mutex);
4813
fbbd37b3
CW
4814 GEM_BUG_ON(i915_gem_object_is_active(obj));
4815 list_for_each_entry_safe(vma, vn,
4816 &obj->vma_list, obj_link) {
fbbd37b3
CW
4817 GEM_BUG_ON(i915_vma_is_active(vma));
4818 vma->flags &= ~I915_VMA_PIN_MASK;
3365e226 4819 i915_vma_destroy(vma);
fbbd37b3 4820 }
db6c2b41
CW
4821 GEM_BUG_ON(!list_empty(&obj->vma_list));
4822 GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma_tree));
fbbd37b3 4823
f2123818
CW
4824 /* This serializes freeing with the shrinker. Since the free
4825 * is delayed, first by RCU then by the workqueue, we want the
4826 * shrinker to be able to free pages of unreferenced objects,
4827 * or else we may oom whilst there are plenty of deferred
4828 * freed objects.
4829 */
4830 if (i915_gem_object_has_pages(obj)) {
4831 spin_lock(&i915->mm.obj_lock);
4832 list_del_init(&obj->mm.link);
4833 spin_unlock(&i915->mm.obj_lock);
4834 }
4835
cc731f5a 4836 mutex_unlock(&i915->drm.struct_mutex);
fbbd37b3 4837
fbbd37b3 4838 GEM_BUG_ON(obj->bind_count);
a65adaf8 4839 GEM_BUG_ON(obj->userfault_count);
fbbd37b3 4840 GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
67b48040 4841 GEM_BUG_ON(!list_empty(&obj->lut_list));
fbbd37b3
CW
4842
4843 if (obj->ops->release)
4844 obj->ops->release(obj);
f65c9168 4845
fbbd37b3
CW
4846 if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
4847 atomic_set(&obj->mm.pages_pin_count, 0);
548625ee 4848 __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
f1fa4f44 4849 GEM_BUG_ON(i915_gem_object_has_pages(obj));
fbbd37b3
CW
4850
4851 if (obj->base.import_attach)
4852 drm_prime_gem_destroy(&obj->base, NULL);
4853
d07f0e59 4854 reservation_object_fini(&obj->__builtin_resv);
fbbd37b3
CW
4855 drm_gem_object_release(&obj->base);
4856 i915_gem_info_remove_obj(i915, obj->base.size);
4857
4858 kfree(obj->bit_17);
4859 i915_gem_object_free(obj);
cc731f5a 4860
c9c70471
CW
4861 GEM_BUG_ON(!atomic_read(&i915->mm.free_count));
4862 atomic_dec(&i915->mm.free_count);
4863
cc731f5a
CW
4864 if (on)
4865 cond_resched();
fbbd37b3 4866 }
cc731f5a 4867 intel_runtime_pm_put(i915);
fbbd37b3
CW
4868}
4869
4870static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
4871{
4872 struct llist_node *freed;
4873
87701b4b
CW
4874 /* Free the oldest, most stale object to keep the free_list short */
4875 freed = NULL;
4876 if (!llist_empty(&i915->mm.free_list)) { /* quick test for hotpath */
4877 /* Only one consumer of llist_del_first() allowed */
4878 spin_lock(&i915->mm.free_lock);
4879 freed = llist_del_first(&i915->mm.free_list);
4880 spin_unlock(&i915->mm.free_lock);
4881 }
4882 if (unlikely(freed)) {
4883 freed->next = NULL;
fbbd37b3 4884 __i915_gem_free_objects(i915, freed);
87701b4b 4885 }
fbbd37b3
CW
4886}
4887
4888static void __i915_gem_free_work(struct work_struct *work)
4889{
4890 struct drm_i915_private *i915 =
4891 container_of(work, struct drm_i915_private, mm.free_work);
4892 struct llist_node *freed;
26e12f89 4893
2ef1e729
CW
4894 /*
4895 * All file-owned VMA should have been released by this point through
b1f788c6
CW
4896 * i915_gem_close_object(), or earlier by i915_gem_context_close().
4897 * However, the object may also be bound into the global GTT (e.g.
4898 * older GPUs without per-process support, or for direct access through
4899 * the GTT either for the user or for scanout). Those VMA still need to
4900 * unbound now.
4901 */
1488fc08 4902
f991c492 4903 spin_lock(&i915->mm.free_lock);
5ad08be7 4904 while ((freed = llist_del_all(&i915->mm.free_list))) {
f991c492
CW
4905 spin_unlock(&i915->mm.free_lock);
4906
fbbd37b3 4907 __i915_gem_free_objects(i915, freed);
5ad08be7 4908 if (need_resched())
f991c492
CW
4909 return;
4910
4911 spin_lock(&i915->mm.free_lock);
5ad08be7 4912 }
f991c492 4913 spin_unlock(&i915->mm.free_lock);
fbbd37b3 4914}
a071fa00 4915
fbbd37b3
CW
4916static void __i915_gem_free_object_rcu(struct rcu_head *head)
4917{
4918 struct drm_i915_gem_object *obj =
4919 container_of(head, typeof(*obj), rcu);
4920 struct drm_i915_private *i915 = to_i915(obj->base.dev);
4921
2ef1e729
CW
4922 /*
4923 * Since we require blocking on struct_mutex to unbind the freed
4924 * object from the GPU before releasing resources back to the
4925 * system, we can not do that directly from the RCU callback (which may
4926 * be a softirq context), but must instead then defer that work onto a
4927 * kthread. We use the RCU callback rather than move the freed object
4928 * directly onto the work queue so that we can mix between using the
4929 * worker and performing frees directly from subsequent allocations for
4930 * crude but effective memory throttling.
fbbd37b3
CW
4931 */
4932 if (llist_add(&obj->freed, &i915->mm.free_list))
beacbd16 4933 queue_work(i915->wq, &i915->mm.free_work);
fbbd37b3 4934}
656bfa3a 4935
fbbd37b3
CW
4936void i915_gem_free_object(struct drm_gem_object *gem_obj)
4937{
4938 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
a4f5ea64 4939
bc0629a7
CW
4940 if (obj->mm.quirked)
4941 __i915_gem_object_unpin_pages(obj);
4942
340fbd8c 4943 if (discard_backing_storage(obj))
a4f5ea64 4944 obj->mm.madv = I915_MADV_DONTNEED;
de151cf6 4945
2ef1e729
CW
4946 /*
4947 * Before we free the object, make sure any pure RCU-only
fbbd37b3
CW
4948 * read-side critical sections are complete, e.g.
4949 * i915_gem_busy_ioctl(). For the corresponding synchronized
4950 * lookup see i915_gem_object_lookup_rcu().
4951 */
c9c70471 4952 atomic_inc(&to_i915(obj->base.dev)->mm.free_count);
fbbd37b3 4953 call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
673a394b
EA
4954}
4955
f8a7fde4
CW
4956void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
4957{
4958 lockdep_assert_held(&obj->base.dev->struct_mutex);
4959
d1b48c1e
CW
4960 if (!i915_gem_object_has_active_reference(obj) &&
4961 i915_gem_object_is_active(obj))
f8a7fde4
CW
4962 i915_gem_object_set_active_reference(obj);
4963 else
4964 i915_gem_object_put(obj);
4965}
4966
24145517
CW
4967void i915_gem_sanitize(struct drm_i915_private *i915)
4968{
c3160da9
CW
4969 struct intel_engine_cs *engine;
4970 enum intel_engine_id id;
4971
4972 GEM_TRACE("\n");
4973
4dfacb0b 4974 mutex_lock(&i915->drm.struct_mutex);
c3160da9
CW
4975
4976 intel_runtime_pm_get(i915);
4977 intel_uncore_forcewake_get(i915, FORCEWAKE_ALL);
4978
4979 /*
4980 * As we have just resumed the machine and woken the device up from
4981 * deep PCI sleep (presumably D3_cold), assume the HW has been reset
4982 * back to defaults, recovering from whatever wedged state we left it
4983 * in and so worth trying to use the device once more.
4984 */
4dfacb0b 4985 if (i915_terminally_wedged(&i915->gpu_error))
f36325f3 4986 i915_gem_unset_wedged(i915);
f36325f3 4987
24145517
CW
4988 /*
4989 * If we inherit context state from the BIOS or earlier occupants
4990 * of the GPU, the GPU may be in an inconsistent state when we
4991 * try to take over. The only way to remove the earlier state
4992 * is by resetting. However, resetting on earlier gen is tricky as
4993 * it may impact the display and we are uncertain about the stability
ea117b8d 4994 * of the reset, so this could be applied to even earlier gen.
24145517 4995 */
ce1599a4
DCS
4996 if (INTEL_GEN(i915) >= 5 && intel_has_gpu_reset(i915))
4997 WARN_ON(intel_gpu_reset(i915, ALL_ENGINES));
4dfacb0b 4998
c3160da9
CW
4999 /* Reset the submission backend after resume as well as the GPU reset */
5000 for_each_engine(engine, i915, id) {
5001 if (engine->reset.reset)
5002 engine->reset.reset(engine, NULL);
5003 }
5004
5005 intel_uncore_forcewake_put(i915, FORCEWAKE_ALL);
5006 intel_runtime_pm_put(i915);
5007
4dfacb0b
CW
5008 i915_gem_contexts_lost(i915);
5009 mutex_unlock(&i915->drm.struct_mutex);
24145517
CW
5010}
5011
bf9e8429 5012int i915_gem_suspend(struct drm_i915_private *dev_priv)
29105ccc 5013{
bf9e8429 5014 struct drm_device *dev = &dev_priv->drm;
dcff85c8 5015 int ret;
28dfe52a 5016
09a4c02e
CW
5017 GEM_TRACE("\n");
5018
c998e8a0 5019 intel_runtime_pm_get(dev_priv);
54b4f68f
CW
5020 intel_suspend_gt_powersave(dev_priv);
5021
45c5f202 5022 mutex_lock(&dev->struct_mutex);
5ab57c70
CW
5023
5024 /* We have to flush all the executing contexts to main memory so
5025 * that they can saved in the hibernation image. To ensure the last
5026 * context image is coherent, we have to switch away from it. That
5027 * leaves the dev_priv->kernel_context still active when
5028 * we actually suspend, and its image in memory may not match the GPU
5029 * state. Fortunately, the kernel_context is disposable and we do
5030 * not rely on its state.
5031 */
ecf73eb2
CW
5032 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
5033 ret = i915_gem_switch_to_kernel_context(dev_priv);
5034 if (ret)
5035 goto err_unlock;
5ab57c70 5036
ecf73eb2
CW
5037 ret = i915_gem_wait_for_idle(dev_priv,
5038 I915_WAIT_INTERRUPTIBLE |
0606035f
CW
5039 I915_WAIT_LOCKED |
5040 I915_WAIT_FOR_IDLE_BOOST);
ecf73eb2
CW
5041 if (ret && ret != -EIO)
5042 goto err_unlock;
f7403347 5043
ecf73eb2
CW
5044 assert_kernel_context_is_current(dev_priv);
5045 }
45c5f202
CW
5046 mutex_unlock(&dev->struct_mutex);
5047
7cfca4af 5048 intel_uc_suspend(dev_priv);
63987bfe 5049
737b1506 5050 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
67d97da3 5051 cancel_delayed_work_sync(&dev_priv->gt.retire_work);
bdeb9785
CW
5052
5053 /* As the idle_work is rearming if it detects a race, play safe and
5054 * repeat the flush until it is definitely idle.
5055 */
7c26240e 5056 drain_delayed_work(&dev_priv->gt.idle_work);
bdeb9785 5057
bdcf120b
CW
5058 /* Assert that we sucessfully flushed all the work and
5059 * reset the GPU back to its idle, low power state.
5060 */
67d97da3 5061 WARN_ON(dev_priv->gt.awake);
fc692bd3
CW
5062 if (WARN_ON(!intel_engines_are_idle(dev_priv)))
5063 i915_gem_set_wedged(dev_priv); /* no hope, discard everything */
bdcf120b 5064
ec92ad00
CW
5065 intel_runtime_pm_put(dev_priv);
5066 return 0;
5067
5068err_unlock:
5069 mutex_unlock(&dev->struct_mutex);
5070 intel_runtime_pm_put(dev_priv);
5071 return ret;
5072}
5073
5074void i915_gem_suspend_late(struct drm_i915_private *i915)
5075{
9776f472
CW
5076 struct drm_i915_gem_object *obj;
5077 struct list_head *phases[] = {
5078 &i915->mm.unbound_list,
5079 &i915->mm.bound_list,
5080 NULL
5081 }, **phase;
5082
1c777c5d
ID
5083 /*
5084 * Neither the BIOS, ourselves or any other kernel
5085 * expects the system to be in execlists mode on startup,
5086 * so we need to reset the GPU back to legacy mode. And the only
5087 * known way to disable logical contexts is through a GPU reset.
5088 *
5089 * So in order to leave the system in a known default configuration,
5090 * always reset the GPU upon unload and suspend. Afterwards we then
5091 * clean up the GEM state tracking, flushing off the requests and
5092 * leaving the system in a known idle state.
5093 *
5094 * Note that is of the upmost importance that the GPU is idle and
5095 * all stray writes are flushed *before* we dismantle the backing
5096 * storage for the pinned objects.
5097 *
5098 * However, since we are uncertain that resetting the GPU on older
5099 * machines is a good idea, we don't - just in case it leaves the
5100 * machine in an unusable condition.
5101 */
1c777c5d 5102
9776f472
CW
5103 mutex_lock(&i915->drm.struct_mutex);
5104 for (phase = phases; *phase; phase++) {
5105 list_for_each_entry(obj, *phase, mm.link)
5106 WARN_ON(i915_gem_object_set_to_gtt_domain(obj, false));
5107 }
5108 mutex_unlock(&i915->drm.struct_mutex);
5109
ec92ad00
CW
5110 intel_uc_sanitize(i915);
5111 i915_gem_sanitize(i915);
673a394b
EA
5112}
5113
37cd3300 5114void i915_gem_resume(struct drm_i915_private *i915)
5ab57c70 5115{
4dfacb0b
CW
5116 GEM_TRACE("\n");
5117
37cd3300 5118 WARN_ON(i915->gt.awake);
5ab57c70 5119
37cd3300
CW
5120 mutex_lock(&i915->drm.struct_mutex);
5121 intel_uncore_forcewake_get(i915, FORCEWAKE_ALL);
31ab49ab 5122
37cd3300
CW
5123 i915_gem_restore_gtt_mappings(i915);
5124 i915_gem_restore_fences(i915);
5ab57c70 5125
6ca9a2be
CW
5126 /*
5127 * As we didn't flush the kernel context before suspend, we cannot
5ab57c70
CW
5128 * guarantee that the context image is complete. So let's just reset
5129 * it and start again.
5130 */
37cd3300 5131 i915->gt.resume(i915);
5ab57c70 5132
37cd3300
CW
5133 if (i915_gem_init_hw(i915))
5134 goto err_wedged;
5135
7cfca4af 5136 intel_uc_resume(i915);
7469c62c 5137
37cd3300
CW
5138 /* Always reload a context for powersaving. */
5139 if (i915_gem_switch_to_kernel_context(i915))
5140 goto err_wedged;
5141
5142out_unlock:
5143 intel_uncore_forcewake_put(i915, FORCEWAKE_ALL);
5144 mutex_unlock(&i915->drm.struct_mutex);
5145 return;
5146
5147err_wedged:
6ca9a2be
CW
5148 if (!i915_terminally_wedged(&i915->gpu_error)) {
5149 DRM_ERROR("failed to re-initialize GPU, declaring wedged!\n");
5150 i915_gem_set_wedged(i915);
5151 }
37cd3300 5152 goto out_unlock;
5ab57c70
CW
5153}
5154
c6be607a 5155void i915_gem_init_swizzling(struct drm_i915_private *dev_priv)
f691e2f4 5156{
c6be607a 5157 if (INTEL_GEN(dev_priv) < 5 ||
f691e2f4
DV
5158 dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
5159 return;
5160
5161 I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
5162 DISP_TILE_SURFACE_SWIZZLING);
5163
5db94019 5164 if (IS_GEN5(dev_priv))
11782b02
DV
5165 return;
5166
f691e2f4 5167 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
5db94019 5168 if (IS_GEN6(dev_priv))
6b26c86d 5169 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
5db94019 5170 else if (IS_GEN7(dev_priv))
6b26c86d 5171 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
5db94019 5172 else if (IS_GEN8(dev_priv))
31a5336e 5173 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
8782e26c
BW
5174 else
5175 BUG();
f691e2f4 5176}
e21af88d 5177
50a0bc90 5178static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
81e7f200 5179{
81e7f200
VS
5180 I915_WRITE(RING_CTL(base), 0);
5181 I915_WRITE(RING_HEAD(base), 0);
5182 I915_WRITE(RING_TAIL(base), 0);
5183 I915_WRITE(RING_START(base), 0);
5184}
5185
50a0bc90 5186static void init_unused_rings(struct drm_i915_private *dev_priv)
81e7f200 5187{
50a0bc90
TU
5188 if (IS_I830(dev_priv)) {
5189 init_unused_ring(dev_priv, PRB1_BASE);
5190 init_unused_ring(dev_priv, SRB0_BASE);
5191 init_unused_ring(dev_priv, SRB1_BASE);
5192 init_unused_ring(dev_priv, SRB2_BASE);
5193 init_unused_ring(dev_priv, SRB3_BASE);
5194 } else if (IS_GEN2(dev_priv)) {
5195 init_unused_ring(dev_priv, SRB0_BASE);
5196 init_unused_ring(dev_priv, SRB1_BASE);
5197 } else if (IS_GEN3(dev_priv)) {
5198 init_unused_ring(dev_priv, PRB1_BASE);
5199 init_unused_ring(dev_priv, PRB2_BASE);
81e7f200
VS
5200 }
5201}
5202
20a8a74a 5203static int __i915_gem_restart_engines(void *data)
4fc7c971 5204{
20a8a74a 5205 struct drm_i915_private *i915 = data;
e2f80391 5206 struct intel_engine_cs *engine;
3b3f1650 5207 enum intel_engine_id id;
20a8a74a
CW
5208 int err;
5209
5210 for_each_engine(engine, i915, id) {
5211 err = engine->init_hw(engine);
8177e112
CW
5212 if (err) {
5213 DRM_ERROR("Failed to restart %s (%d)\n",
5214 engine->name, err);
20a8a74a 5215 return err;
8177e112 5216 }
20a8a74a
CW
5217 }
5218
5219 return 0;
5220}
5221
5222int i915_gem_init_hw(struct drm_i915_private *dev_priv)
5223{
d200cda6 5224 int ret;
4fc7c971 5225
de867c20
CW
5226 dev_priv->gt.last_init_time = ktime_get();
5227
5e4f5189
CW
5228 /* Double layer security blanket, see i915_gem_init() */
5229 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
5230
0031fb96 5231 if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
05e21cc4 5232 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
4fc7c971 5233
772c2a51 5234 if (IS_HASWELL(dev_priv))
50a0bc90 5235 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
0bf21347 5236 LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
9435373e 5237
6e266956 5238 if (HAS_PCH_NOP(dev_priv)) {
fd6b8f43 5239 if (IS_IVYBRIDGE(dev_priv)) {
6ba844b0
DV
5240 u32 temp = I915_READ(GEN7_MSG_CTL);
5241 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
5242 I915_WRITE(GEN7_MSG_CTL, temp);
c6be607a 5243 } else if (INTEL_GEN(dev_priv) >= 7) {
6ba844b0
DV
5244 u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
5245 temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
5246 I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
5247 }
88a2b2a3
BW
5248 }
5249
59b449d5
OM
5250 intel_gt_workarounds_apply(dev_priv);
5251
c6be607a 5252 i915_gem_init_swizzling(dev_priv);
4fc7c971 5253
d5abdfda
DV
5254 /*
5255 * At least 830 can leave some of the unused rings
5256 * "active" (ie. head != tail) after resume which
5257 * will prevent c3 entry. Makes sure all unused rings
5258 * are totally idle.
5259 */
50a0bc90 5260 init_unused_rings(dev_priv);
d5abdfda 5261
ed54c1a1 5262 BUG_ON(!dev_priv->kernel_context);
6f74b36b
CW
5263 if (i915_terminally_wedged(&dev_priv->gpu_error)) {
5264 ret = -EIO;
5265 goto out;
5266 }
90638cc1 5267
c6be607a 5268 ret = i915_ppgtt_init_hw(dev_priv);
4ad2fd88 5269 if (ret) {
8177e112 5270 DRM_ERROR("Enabling PPGTT failed (%d)\n", ret);
4ad2fd88
JH
5271 goto out;
5272 }
5273
f08e2035
JL
5274 ret = intel_wopcm_init_hw(&dev_priv->wopcm);
5275 if (ret) {
5276 DRM_ERROR("Enabling WOPCM failed (%d)\n", ret);
5277 goto out;
5278 }
5279
9bdc3573
MW
5280 /* We can't enable contexts until all firmware is loaded */
5281 ret = intel_uc_init_hw(dev_priv);
8177e112
CW
5282 if (ret) {
5283 DRM_ERROR("Enabling uc failed (%d)\n", ret);
9bdc3573 5284 goto out;
8177e112 5285 }
9bdc3573 5286
bf9e8429 5287 intel_mocs_init_l3cc_table(dev_priv);
0ccdacf6 5288
136109c6
CW
5289 /* Only when the HW is re-initialised, can we replay the requests */
5290 ret = __i915_gem_restart_engines(dev_priv);
b96f6ebf
MW
5291 if (ret)
5292 goto cleanup_uc;
5e4f5189
CW
5293out:
5294 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2fa48d8d 5295 return ret;
b96f6ebf
MW
5296
5297cleanup_uc:
5298 intel_uc_fini_hw(dev_priv);
5299 goto out;
8187a2b7
ZN
5300}
5301
d2b4b979
CW
5302static int __intel_engines_record_defaults(struct drm_i915_private *i915)
5303{
5304 struct i915_gem_context *ctx;
5305 struct intel_engine_cs *engine;
5306 enum intel_engine_id id;
5307 int err;
5308
5309 /*
5310 * As we reset the gpu during very early sanitisation, the current
5311 * register state on the GPU should reflect its defaults values.
5312 * We load a context onto the hw (with restore-inhibit), then switch
5313 * over to a second context to save that default register state. We
5314 * can then prime every new context with that state so they all start
5315 * from the same default HW values.
5316 */
5317
5318 ctx = i915_gem_context_create_kernel(i915, 0);
5319 if (IS_ERR(ctx))
5320 return PTR_ERR(ctx);
5321
5322 for_each_engine(engine, i915, id) {
e61e0f51 5323 struct i915_request *rq;
d2b4b979 5324
e61e0f51 5325 rq = i915_request_alloc(engine, ctx);
d2b4b979
CW
5326 if (IS_ERR(rq)) {
5327 err = PTR_ERR(rq);
5328 goto out_ctx;
5329 }
5330
3fef5cda 5331 err = 0;
d2b4b979
CW
5332 if (engine->init_context)
5333 err = engine->init_context(rq);
5334
e61e0f51 5335 __i915_request_add(rq, true);
d2b4b979
CW
5336 if (err)
5337 goto err_active;
5338 }
5339
5340 err = i915_gem_switch_to_kernel_context(i915);
5341 if (err)
5342 goto err_active;
5343
5344 err = i915_gem_wait_for_idle(i915, I915_WAIT_LOCKED);
5345 if (err)
5346 goto err_active;
5347
5348 assert_kernel_context_is_current(i915);
5349
5350 for_each_engine(engine, i915, id) {
5351 struct i915_vma *state;
5352
ab82a063 5353 state = to_intel_context(ctx, engine)->state;
d2b4b979
CW
5354 if (!state)
5355 continue;
5356
5357 /*
5358 * As we will hold a reference to the logical state, it will
5359 * not be torn down with the context, and importantly the
5360 * object will hold onto its vma (making it possible for a
5361 * stray GTT write to corrupt our defaults). Unmap the vma
5362 * from the GTT to prevent such accidents and reclaim the
5363 * space.
5364 */
5365 err = i915_vma_unbind(state);
5366 if (err)
5367 goto err_active;
5368
5369 err = i915_gem_object_set_to_cpu_domain(state->obj, false);
5370 if (err)
5371 goto err_active;
5372
5373 engine->default_state = i915_gem_object_get(state->obj);
5374 }
5375
5376 if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)) {
5377 unsigned int found = intel_engines_has_context_isolation(i915);
5378
5379 /*
5380 * Make sure that classes with multiple engine instances all
5381 * share the same basic configuration.
5382 */
5383 for_each_engine(engine, i915, id) {
5384 unsigned int bit = BIT(engine->uabi_class);
5385 unsigned int expected = engine->default_state ? bit : 0;
5386
5387 if ((found & bit) != expected) {
5388 DRM_ERROR("mismatching default context state for class %d on engine %s\n",
5389 engine->uabi_class, engine->name);
5390 }
5391 }
5392 }
5393
5394out_ctx:
5395 i915_gem_context_set_closed(ctx);
5396 i915_gem_context_put(ctx);
5397 return err;
5398
5399err_active:
5400 /*
5401 * If we have to abandon now, we expect the engines to be idle
5402 * and ready to be torn-down. First try to flush any remaining
5403 * request, ensure we are pointing at the kernel context and
5404 * then remove it.
5405 */
5406 if (WARN_ON(i915_gem_switch_to_kernel_context(i915)))
5407 goto out_ctx;
5408
5409 if (WARN_ON(i915_gem_wait_for_idle(i915, I915_WAIT_LOCKED)))
5410 goto out_ctx;
5411
5412 i915_gem_contexts_lost(i915);
5413 goto out_ctx;
5414}
5415
bf9e8429 5416int i915_gem_init(struct drm_i915_private *dev_priv)
1070a42b 5417{
1070a42b
CW
5418 int ret;
5419
52b2416c
CD
5420 /* We need to fallback to 4K pages if host doesn't support huge gtt. */
5421 if (intel_vgpu_active(dev_priv) && !intel_vgpu_has_huge_gtt(dev_priv))
da9fe3f3
MA
5422 mkwrite_device_info(dev_priv)->page_sizes =
5423 I915_GTT_PAGE_SIZE_4K;
5424
94312828 5425 dev_priv->mm.unordered_timeline = dma_fence_context_alloc(1);
57822dc6 5426
fb5c551a 5427 if (HAS_LOGICAL_RING_CONTEXTS(dev_priv)) {
821ed7df 5428 dev_priv->gt.resume = intel_lr_context_resume;
117897f4 5429 dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
fb5c551a
CW
5430 } else {
5431 dev_priv->gt.resume = intel_legacy_submission_resume;
5432 dev_priv->gt.cleanup_engine = intel_engine_cleanup;
a83014d3
OM
5433 }
5434
ee48700d
CW
5435 ret = i915_gem_init_userptr(dev_priv);
5436 if (ret)
5437 return ret;
5438
6b0478fb
JL
5439 ret = intel_wopcm_init(&dev_priv->wopcm);
5440 if (ret)
5441 return ret;
5442
70deeadd 5443 ret = intel_uc_init_misc(dev_priv);
3176ff49
MW
5444 if (ret)
5445 return ret;
5446
5e4f5189
CW
5447 /* This is just a security blanket to placate dragons.
5448 * On some systems, we very sporadically observe that the first TLBs
5449 * used by the CS may be stale, despite us poking the TLB reset. If
5450 * we hold the forcewake during initialisation these problems
5451 * just magically go away.
5452 */
ee48700d 5453 mutex_lock(&dev_priv->drm.struct_mutex);
5e4f5189
CW
5454 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
5455
f6b9d5ca 5456 ret = i915_gem_init_ggtt(dev_priv);
6ca9a2be
CW
5457 if (ret) {
5458 GEM_BUG_ON(ret == -EIO);
5459 goto err_unlock;
5460 }
d62b4892 5461
829a0af2 5462 ret = i915_gem_contexts_init(dev_priv);
6ca9a2be
CW
5463 if (ret) {
5464 GEM_BUG_ON(ret == -EIO);
5465 goto err_ggtt;
5466 }
2fa48d8d 5467
bf9e8429 5468 ret = intel_engines_init(dev_priv);
6ca9a2be
CW
5469 if (ret) {
5470 GEM_BUG_ON(ret == -EIO);
5471 goto err_context;
5472 }
2fa48d8d 5473
f58d13d5
CW
5474 intel_init_gt_powersave(dev_priv);
5475
61b5c158 5476 ret = intel_uc_init(dev_priv);
cc6a818a 5477 if (ret)
6ca9a2be 5478 goto err_pm;
cc6a818a 5479
61b5c158
MW
5480 ret = i915_gem_init_hw(dev_priv);
5481 if (ret)
5482 goto err_uc_init;
5483
cc6a818a
CW
5484 /*
5485 * Despite its name intel_init_clock_gating applies both display
5486 * clock gating workarounds; GT mmio workarounds and the occasional
5487 * GT power context workaround. Worse, sometimes it includes a context
5488 * register workaround which we need to apply before we record the
5489 * default HW state for all contexts.
5490 *
5491 * FIXME: break up the workarounds and apply them at the right time!
5492 */
5493 intel_init_clock_gating(dev_priv);
5494
d2b4b979 5495 ret = __intel_engines_record_defaults(dev_priv);
6ca9a2be
CW
5496 if (ret)
5497 goto err_init_hw;
5498
5499 if (i915_inject_load_failure()) {
5500 ret = -ENODEV;
5501 goto err_init_hw;
5502 }
5503
5504 if (i915_inject_load_failure()) {
5505 ret = -EIO;
5506 goto err_init_hw;
5507 }
5508
5509 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5510 mutex_unlock(&dev_priv->drm.struct_mutex);
5511
5512 return 0;
5513
5514 /*
5515 * Unwinding is complicated by that we want to handle -EIO to mean
5516 * disable GPU submission but keep KMS alive. We want to mark the
5517 * HW as irrevisibly wedged, but keep enough state around that the
5518 * driver doesn't explode during runtime.
5519 */
5520err_init_hw:
8571a05a
CW
5521 mutex_unlock(&dev_priv->drm.struct_mutex);
5522
5523 WARN_ON(i915_gem_suspend(dev_priv));
5524 i915_gem_suspend_late(dev_priv);
5525
5526 mutex_lock(&dev_priv->drm.struct_mutex);
6ca9a2be 5527 intel_uc_fini_hw(dev_priv);
61b5c158
MW
5528err_uc_init:
5529 intel_uc_fini(dev_priv);
6ca9a2be
CW
5530err_pm:
5531 if (ret != -EIO) {
5532 intel_cleanup_gt_powersave(dev_priv);
5533 i915_gem_cleanup_engines(dev_priv);
5534 }
5535err_context:
5536 if (ret != -EIO)
5537 i915_gem_contexts_fini(dev_priv);
5538err_ggtt:
5539err_unlock:
5540 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5541 mutex_unlock(&dev_priv->drm.struct_mutex);
5542
70deeadd 5543 intel_uc_fini_misc(dev_priv);
da943b5a 5544
6ca9a2be
CW
5545 if (ret != -EIO)
5546 i915_gem_cleanup_userptr(dev_priv);
5547
60990320 5548 if (ret == -EIO) {
6ca9a2be
CW
5549 /*
5550 * Allow engine initialisation to fail by marking the GPU as
60990320
CW
5551 * wedged. But we only want to do this where the GPU is angry,
5552 * for all other failure, such as an allocation failure, bail.
5553 */
6f74b36b 5554 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
51c18bf7
CW
5555 i915_load_error(dev_priv,
5556 "Failed to initialize GPU, declaring it wedged!\n");
6f74b36b
CW
5557 i915_gem_set_wedged(dev_priv);
5558 }
60990320 5559 ret = 0;
1070a42b
CW
5560 }
5561
6ca9a2be 5562 i915_gem_drain_freed_objects(dev_priv);
60990320 5563 return ret;
1070a42b
CW
5564}
5565
8979187a
MW
5566void i915_gem_fini(struct drm_i915_private *dev_priv)
5567{
5568 i915_gem_suspend_late(dev_priv);
5569
5570 /* Flush any outstanding unpin_work. */
5571 i915_gem_drain_workqueue(dev_priv);
5572
5573 mutex_lock(&dev_priv->drm.struct_mutex);
5574 intel_uc_fini_hw(dev_priv);
5575 intel_uc_fini(dev_priv);
5576 i915_gem_cleanup_engines(dev_priv);
5577 i915_gem_contexts_fini(dev_priv);
5578 mutex_unlock(&dev_priv->drm.struct_mutex);
5579
5580 intel_uc_fini_misc(dev_priv);
5581 i915_gem_cleanup_userptr(dev_priv);
5582
5583 i915_gem_drain_freed_objects(dev_priv);
5584
5585 WARN_ON(!list_empty(&dev_priv->contexts.list));
5586}
5587
24145517
CW
5588void i915_gem_init_mmio(struct drm_i915_private *i915)
5589{
5590 i915_gem_sanitize(i915);
5591}
5592
8187a2b7 5593void
cb15d9f8 5594i915_gem_cleanup_engines(struct drm_i915_private *dev_priv)
8187a2b7 5595{
e2f80391 5596 struct intel_engine_cs *engine;
3b3f1650 5597 enum intel_engine_id id;
8187a2b7 5598
3b3f1650 5599 for_each_engine(engine, dev_priv, id)
117897f4 5600 dev_priv->gt.cleanup_engine(engine);
8187a2b7
ZN
5601}
5602
40ae4e16
ID
5603void
5604i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
5605{
49ef5294 5606 int i;
40ae4e16 5607
c56b89f1 5608 if (INTEL_GEN(dev_priv) >= 7 && !IS_VALLEYVIEW(dev_priv) &&
40ae4e16
ID
5609 !IS_CHERRYVIEW(dev_priv))
5610 dev_priv->num_fence_regs = 32;
c56b89f1 5611 else if (INTEL_GEN(dev_priv) >= 4 ||
73f67aa8
JN
5612 IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
5613 IS_G33(dev_priv) || IS_PINEVIEW(dev_priv))
40ae4e16
ID
5614 dev_priv->num_fence_regs = 16;
5615 else
5616 dev_priv->num_fence_regs = 8;
5617
c033666a 5618 if (intel_vgpu_active(dev_priv))
40ae4e16
ID
5619 dev_priv->num_fence_regs =
5620 I915_READ(vgtif_reg(avail_rs.fence_num));
5621
5622 /* Initialize fence registers to zero */
49ef5294
CW
5623 for (i = 0; i < dev_priv->num_fence_regs; i++) {
5624 struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
5625
5626 fence->i915 = dev_priv;
5627 fence->id = i;
5628 list_add_tail(&fence->link, &dev_priv->mm.fence_list);
5629 }
4362f4f6 5630 i915_gem_restore_fences(dev_priv);
40ae4e16 5631
4362f4f6 5632 i915_gem_detect_bit_6_swizzle(dev_priv);
40ae4e16
ID
5633}
5634
9c52d1c8
CW
5635static void i915_gem_init__mm(struct drm_i915_private *i915)
5636{
5637 spin_lock_init(&i915->mm.object_stat_lock);
5638 spin_lock_init(&i915->mm.obj_lock);
5639 spin_lock_init(&i915->mm.free_lock);
5640
5641 init_llist_head(&i915->mm.free_list);
5642
5643 INIT_LIST_HEAD(&i915->mm.unbound_list);
5644 INIT_LIST_HEAD(&i915->mm.bound_list);
5645 INIT_LIST_HEAD(&i915->mm.fence_list);
5646 INIT_LIST_HEAD(&i915->mm.userfault_list);
5647
5648 INIT_WORK(&i915->mm.free_work, __i915_gem_free_work);
5649}
5650
a0de908d 5651int i915_gem_init_early(struct drm_i915_private *dev_priv)
673a394b 5652{
a933568e 5653 int err = -ENOMEM;
42dcedd4 5654
a933568e
TU
5655 dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
5656 if (!dev_priv->objects)
73cb9701 5657 goto err_out;
73cb9701 5658
a933568e
TU
5659 dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
5660 if (!dev_priv->vmas)
73cb9701 5661 goto err_objects;
73cb9701 5662
d1b48c1e
CW
5663 dev_priv->luts = KMEM_CACHE(i915_lut_handle, 0);
5664 if (!dev_priv->luts)
5665 goto err_vmas;
5666
e61e0f51 5667 dev_priv->requests = KMEM_CACHE(i915_request,
a933568e
TU
5668 SLAB_HWCACHE_ALIGN |
5669 SLAB_RECLAIM_ACCOUNT |
5f0d5a3a 5670 SLAB_TYPESAFE_BY_RCU);
a933568e 5671 if (!dev_priv->requests)
d1b48c1e 5672 goto err_luts;
73cb9701 5673
52e54209
CW
5674 dev_priv->dependencies = KMEM_CACHE(i915_dependency,
5675 SLAB_HWCACHE_ALIGN |
5676 SLAB_RECLAIM_ACCOUNT);
5677 if (!dev_priv->dependencies)
5678 goto err_requests;
5679
c5cf9a91
CW
5680 dev_priv->priorities = KMEM_CACHE(i915_priolist, SLAB_HWCACHE_ALIGN);
5681 if (!dev_priv->priorities)
5682 goto err_dependencies;
5683
73cb9701 5684 INIT_LIST_HEAD(&dev_priv->gt.timelines);
643b450a 5685 INIT_LIST_HEAD(&dev_priv->gt.active_rings);
3365e226 5686 INIT_LIST_HEAD(&dev_priv->gt.closed_vma);
643b450a 5687
9c52d1c8 5688 i915_gem_init__mm(dev_priv);
f2123818 5689
67d97da3 5690 INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
673a394b 5691 i915_gem_retire_work_handler);
67d97da3 5692 INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
b29c19b6 5693 i915_gem_idle_work_handler);
1f15b76f 5694 init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
1f83fee0 5695 init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
31169714 5696
6f633402
JL
5697 atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
5698
b5add959 5699 spin_lock_init(&dev_priv->fb_tracking.lock);
73cb9701 5700
465c403c
MA
5701 err = i915_gemfs_init(dev_priv);
5702 if (err)
5703 DRM_NOTE("Unable to create a private tmpfs mount, hugepage support will be disabled(%d).\n", err);
5704
73cb9701
CW
5705 return 0;
5706
52e54209
CW
5707err_dependencies:
5708 kmem_cache_destroy(dev_priv->dependencies);
73cb9701
CW
5709err_requests:
5710 kmem_cache_destroy(dev_priv->requests);
d1b48c1e
CW
5711err_luts:
5712 kmem_cache_destroy(dev_priv->luts);
73cb9701
CW
5713err_vmas:
5714 kmem_cache_destroy(dev_priv->vmas);
5715err_objects:
5716 kmem_cache_destroy(dev_priv->objects);
5717err_out:
5718 return err;
673a394b 5719}
71acb5eb 5720
a0de908d 5721void i915_gem_cleanup_early(struct drm_i915_private *dev_priv)
d64aa096 5722{
c4d4c1c6 5723 i915_gem_drain_freed_objects(dev_priv);
c9c70471
CW
5724 GEM_BUG_ON(!llist_empty(&dev_priv->mm.free_list));
5725 GEM_BUG_ON(atomic_read(&dev_priv->mm.free_count));
c4d4c1c6 5726 WARN_ON(dev_priv->mm.object_count);
ea84aa77 5727 WARN_ON(!list_empty(&dev_priv->gt.timelines));
ea84aa77 5728
c5cf9a91 5729 kmem_cache_destroy(dev_priv->priorities);
52e54209 5730 kmem_cache_destroy(dev_priv->dependencies);
d64aa096 5731 kmem_cache_destroy(dev_priv->requests);
d1b48c1e 5732 kmem_cache_destroy(dev_priv->luts);
d64aa096
ID
5733 kmem_cache_destroy(dev_priv->vmas);
5734 kmem_cache_destroy(dev_priv->objects);
0eafec6d
CW
5735
5736 /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
5737 rcu_barrier();
465c403c
MA
5738
5739 i915_gemfs_fini(dev_priv);
d64aa096
ID
5740}
5741
6a800eab
CW
5742int i915_gem_freeze(struct drm_i915_private *dev_priv)
5743{
d0aa301a
CW
5744 /* Discard all purgeable objects, let userspace recover those as
5745 * required after resuming.
5746 */
6a800eab 5747 i915_gem_shrink_all(dev_priv);
6a800eab 5748
6a800eab
CW
5749 return 0;
5750}
5751
95c778da 5752int i915_gem_freeze_late(struct drm_i915_private *i915)
461fb99c
CW
5753{
5754 struct drm_i915_gem_object *obj;
7aab2d53 5755 struct list_head *phases[] = {
95c778da
CW
5756 &i915->mm.unbound_list,
5757 &i915->mm.bound_list,
7aab2d53 5758 NULL
95c778da 5759 }, **phase;
461fb99c 5760
95c778da
CW
5761 /*
5762 * Called just before we write the hibernation image.
461fb99c
CW
5763 *
5764 * We need to update the domain tracking to reflect that the CPU
5765 * will be accessing all the pages to create and restore from the
5766 * hibernation, and so upon restoration those pages will be in the
5767 * CPU domain.
5768 *
5769 * To make sure the hibernation image contains the latest state,
5770 * we update that state just before writing out the image.
7aab2d53
CW
5771 *
5772 * To try and reduce the hibernation image, we manually shrink
d0aa301a 5773 * the objects as well, see i915_gem_freeze()
461fb99c
CW
5774 */
5775
95c778da
CW
5776 i915_gem_shrink(i915, -1UL, NULL, I915_SHRINK_UNBOUND);
5777 i915_gem_drain_freed_objects(i915);
461fb99c 5778
95c778da
CW
5779 mutex_lock(&i915->drm.struct_mutex);
5780 for (phase = phases; *phase; phase++) {
5781 list_for_each_entry(obj, *phase, mm.link)
5782 WARN_ON(i915_gem_object_set_to_cpu_domain(obj, true));
461fb99c 5783 }
95c778da 5784 mutex_unlock(&i915->drm.struct_mutex);
461fb99c
CW
5785
5786 return 0;
5787}
5788
f787a5f5 5789void i915_gem_release(struct drm_device *dev, struct drm_file *file)
b962442e 5790{
f787a5f5 5791 struct drm_i915_file_private *file_priv = file->driver_priv;
e61e0f51 5792 struct i915_request *request;
b962442e
EA
5793
5794 /* Clean up our request list when the client is going away, so that
5795 * later retire_requests won't dereference our soon-to-be-gone
5796 * file_priv.
5797 */
1c25595f 5798 spin_lock(&file_priv->mm.lock);
c8659efa 5799 list_for_each_entry(request, &file_priv->mm.request_list, client_link)
f787a5f5 5800 request->file_priv = NULL;
1c25595f 5801 spin_unlock(&file_priv->mm.lock);
b29c19b6
CW
5802}
5803
829a0af2 5804int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
b29c19b6
CW
5805{
5806 struct drm_i915_file_private *file_priv;
e422b888 5807 int ret;
b29c19b6 5808
c4c29d7b 5809 DRM_DEBUG("\n");
b29c19b6
CW
5810
5811 file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
5812 if (!file_priv)
5813 return -ENOMEM;
5814
5815 file->driver_priv = file_priv;
829a0af2 5816 file_priv->dev_priv = i915;
ab0e7ff9 5817 file_priv->file = file;
b29c19b6
CW
5818
5819 spin_lock_init(&file_priv->mm.lock);
5820 INIT_LIST_HEAD(&file_priv->mm.request_list);
b29c19b6 5821
c80ff16e 5822 file_priv->bsd_engine = -1;
de1add36 5823
829a0af2 5824 ret = i915_gem_context_open(i915, file);
e422b888
BW
5825 if (ret)
5826 kfree(file_priv);
b29c19b6 5827
e422b888 5828 return ret;
b29c19b6
CW
5829}
5830
b680c37a
DV
5831/**
5832 * i915_gem_track_fb - update frontbuffer tracking
d9072a3e
GT
5833 * @old: current GEM buffer for the frontbuffer slots
5834 * @new: new GEM buffer for the frontbuffer slots
5835 * @frontbuffer_bits: bitmask of frontbuffer slots
b680c37a
DV
5836 *
5837 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
5838 * from @old and setting them in @new. Both @old and @new can be NULL.
5839 */
a071fa00
DV
5840void i915_gem_track_fb(struct drm_i915_gem_object *old,
5841 struct drm_i915_gem_object *new,
5842 unsigned frontbuffer_bits)
5843{
faf5bf0a
CW
5844 /* Control of individual bits within the mask are guarded by
5845 * the owning plane->mutex, i.e. we can never see concurrent
5846 * manipulation of individual bits. But since the bitfield as a whole
5847 * is updated using RMW, we need to use atomics in order to update
5848 * the bits.
5849 */
5850 BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
5851 sizeof(atomic_t) * BITS_PER_BYTE);
5852
a071fa00 5853 if (old) {
faf5bf0a
CW
5854 WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
5855 atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
a071fa00
DV
5856 }
5857
5858 if (new) {
faf5bf0a
CW
5859 WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
5860 atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
a071fa00
DV
5861 }
5862}
5863
ea70299d
DG
5864/* Allocate a new GEM object and fill it with the supplied data */
5865struct drm_i915_gem_object *
12d79d78 5866i915_gem_object_create_from_data(struct drm_i915_private *dev_priv,
ea70299d
DG
5867 const void *data, size_t size)
5868{
5869 struct drm_i915_gem_object *obj;
be062fa4
CW
5870 struct file *file;
5871 size_t offset;
5872 int err;
ea70299d 5873
12d79d78 5874 obj = i915_gem_object_create(dev_priv, round_up(size, PAGE_SIZE));
fe3db79b 5875 if (IS_ERR(obj))
ea70299d
DG
5876 return obj;
5877
c0a51fd0 5878 GEM_BUG_ON(obj->write_domain != I915_GEM_DOMAIN_CPU);
ea70299d 5879
be062fa4
CW
5880 file = obj->base.filp;
5881 offset = 0;
5882 do {
5883 unsigned int len = min_t(typeof(size), size, PAGE_SIZE);
5884 struct page *page;
5885 void *pgdata, *vaddr;
ea70299d 5886
be062fa4
CW
5887 err = pagecache_write_begin(file, file->f_mapping,
5888 offset, len, 0,
5889 &page, &pgdata);
5890 if (err < 0)
5891 goto fail;
ea70299d 5892
be062fa4
CW
5893 vaddr = kmap(page);
5894 memcpy(vaddr, data, len);
5895 kunmap(page);
5896
5897 err = pagecache_write_end(file, file->f_mapping,
5898 offset, len, len,
5899 page, pgdata);
5900 if (err < 0)
5901 goto fail;
5902
5903 size -= len;
5904 data += len;
5905 offset += len;
5906 } while (size);
ea70299d
DG
5907
5908 return obj;
5909
5910fail:
f8c417cd 5911 i915_gem_object_put(obj);
be062fa4 5912 return ERR_PTR(err);
ea70299d 5913}
96d77634
CW
5914
5915struct scatterlist *
5916i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
5917 unsigned int n,
5918 unsigned int *offset)
5919{
a4f5ea64 5920 struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
96d77634
CW
5921 struct scatterlist *sg;
5922 unsigned int idx, count;
5923
5924 might_sleep();
5925 GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
a4f5ea64 5926 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
96d77634
CW
5927
5928 /* As we iterate forward through the sg, we record each entry in a
5929 * radixtree for quick repeated (backwards) lookups. If we have seen
5930 * this index previously, we will have an entry for it.
5931 *
5932 * Initial lookup is O(N), but this is amortized to O(1) for
5933 * sequential page access (where each new request is consecutive
5934 * to the previous one). Repeated lookups are O(lg(obj->base.size)),
5935 * i.e. O(1) with a large constant!
5936 */
5937 if (n < READ_ONCE(iter->sg_idx))
5938 goto lookup;
5939
5940 mutex_lock(&iter->lock);
5941
5942 /* We prefer to reuse the last sg so that repeated lookup of this
5943 * (or the subsequent) sg are fast - comparing against the last
5944 * sg is faster than going through the radixtree.
5945 */
5946
5947 sg = iter->sg_pos;
5948 idx = iter->sg_idx;
5949 count = __sg_page_count(sg);
5950
5951 while (idx + count <= n) {
5952 unsigned long exception, i;
5953 int ret;
5954
5955 /* If we cannot allocate and insert this entry, or the
5956 * individual pages from this range, cancel updating the
5957 * sg_idx so that on this lookup we are forced to linearly
5958 * scan onwards, but on future lookups we will try the
5959 * insertion again (in which case we need to be careful of
5960 * the error return reporting that we have already inserted
5961 * this index).
5962 */
5963 ret = radix_tree_insert(&iter->radix, idx, sg);
5964 if (ret && ret != -EEXIST)
5965 goto scan;
5966
5967 exception =
5968 RADIX_TREE_EXCEPTIONAL_ENTRY |
5969 idx << RADIX_TREE_EXCEPTIONAL_SHIFT;
5970 for (i = 1; i < count; i++) {
5971 ret = radix_tree_insert(&iter->radix, idx + i,
5972 (void *)exception);
5973 if (ret && ret != -EEXIST)
5974 goto scan;
5975 }
5976
5977 idx += count;
5978 sg = ____sg_next(sg);
5979 count = __sg_page_count(sg);
5980 }
5981
5982scan:
5983 iter->sg_pos = sg;
5984 iter->sg_idx = idx;
5985
5986 mutex_unlock(&iter->lock);
5987
5988 if (unlikely(n < idx)) /* insertion completed by another thread */
5989 goto lookup;
5990
5991 /* In case we failed to insert the entry into the radixtree, we need
5992 * to look beyond the current sg.
5993 */
5994 while (idx + count <= n) {
5995 idx += count;
5996 sg = ____sg_next(sg);
5997 count = __sg_page_count(sg);
5998 }
5999
6000 *offset = n - idx;
6001 return sg;
6002
6003lookup:
6004 rcu_read_lock();
6005
6006 sg = radix_tree_lookup(&iter->radix, n);
6007 GEM_BUG_ON(!sg);
6008
6009 /* If this index is in the middle of multi-page sg entry,
6010 * the radixtree will contain an exceptional entry that points
6011 * to the start of that range. We will return the pointer to
6012 * the base page and the offset of this page within the
6013 * sg entry's range.
6014 */
6015 *offset = 0;
6016 if (unlikely(radix_tree_exception(sg))) {
6017 unsigned long base =
6018 (unsigned long)sg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
6019
6020 sg = radix_tree_lookup(&iter->radix, base);
6021 GEM_BUG_ON(!sg);
6022
6023 *offset = n - base;
6024 }
6025
6026 rcu_read_unlock();
6027
6028 return sg;
6029}
6030
6031struct page *
6032i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
6033{
6034 struct scatterlist *sg;
6035 unsigned int offset;
6036
6037 GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
6038
6039 sg = i915_gem_object_get_sg(obj, n, &offset);
6040 return nth_page(sg_page(sg), offset);
6041}
6042
6043/* Like i915_gem_object_get_page(), but mark the returned page dirty */
6044struct page *
6045i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
6046 unsigned int n)
6047{
6048 struct page *page;
6049
6050 page = i915_gem_object_get_page(obj, n);
a4f5ea64 6051 if (!obj->mm.dirty)
96d77634
CW
6052 set_page_dirty(page);
6053
6054 return page;
6055}
6056
6057dma_addr_t
6058i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
6059 unsigned long n)
6060{
6061 struct scatterlist *sg;
6062 unsigned int offset;
6063
6064 sg = i915_gem_object_get_sg(obj, n, &offset);
6065 return sg_dma_address(sg) + (offset << PAGE_SHIFT);
6066}
935a2f77 6067
8eeb7906
CW
6068int i915_gem_object_attach_phys(struct drm_i915_gem_object *obj, int align)
6069{
6070 struct sg_table *pages;
6071 int err;
6072
6073 if (align > obj->base.size)
6074 return -EINVAL;
6075
6076 if (obj->ops == &i915_gem_phys_ops)
6077 return 0;
6078
6079 if (obj->ops != &i915_gem_object_ops)
6080 return -EINVAL;
6081
6082 err = i915_gem_object_unbind(obj);
6083 if (err)
6084 return err;
6085
6086 mutex_lock(&obj->mm.lock);
6087
6088 if (obj->mm.madv != I915_MADV_WILLNEED) {
6089 err = -EFAULT;
6090 goto err_unlock;
6091 }
6092
6093 if (obj->mm.quirked) {
6094 err = -EFAULT;
6095 goto err_unlock;
6096 }
6097
6098 if (obj->mm.mapping) {
6099 err = -EBUSY;
6100 goto err_unlock;
6101 }
6102
acd1c1e6 6103 pages = __i915_gem_object_unset_pages(obj);
f2123818 6104
8eeb7906
CW
6105 obj->ops = &i915_gem_phys_ops;
6106
8fb6a5df 6107 err = ____i915_gem_object_get_pages(obj);
8eeb7906
CW
6108 if (err)
6109 goto err_xfer;
6110
6111 /* Perma-pin (until release) the physical set of pages */
6112 __i915_gem_object_pin_pages(obj);
6113
6114 if (!IS_ERR_OR_NULL(pages))
6115 i915_gem_object_ops.put_pages(obj, pages);
6116 mutex_unlock(&obj->mm.lock);
6117 return 0;
6118
6119err_xfer:
6120 obj->ops = &i915_gem_object_ops;
acd1c1e6
CW
6121 if (!IS_ERR_OR_NULL(pages)) {
6122 unsigned int sg_page_sizes = i915_sg_page_sizes(pages->sgl);
6123
6124 __i915_gem_object_set_pages(obj, pages, sg_page_sizes);
6125 }
8eeb7906
CW
6126err_unlock:
6127 mutex_unlock(&obj->mm.lock);
6128 return err;
6129}
6130
935a2f77
CW
6131#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
6132#include "selftests/scatterlist.c"
66d9cb5d 6133#include "selftests/mock_gem_device.c"
44653988 6134#include "selftests/huge_gem_object.c"
4049866f 6135#include "selftests/huge_pages.c"
8335fd65 6136#include "selftests/i915_gem_object.c"
17059450 6137#include "selftests/i915_gem_coherency.c"
935a2f77 6138#endif