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