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