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