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