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