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