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