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