i915_gem.c revision 1.36 1 /* $NetBSD: i915_gem.c,v 1.36 2018/08/27 04:58:23 riastradh Exp $ */
2
3 /*
4 * Copyright 2008-2015 Intel Corporation
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 * IN THE SOFTWARE.
24 *
25 * Authors:
26 * Eric Anholt <eric (at) anholt.net>
27 *
28 */
29
30 #include <sys/cdefs.h>
31 __KERNEL_RCSID(0, "$NetBSD: i915_gem.c,v 1.36 2018/08/27 04:58:23 riastradh Exp $");
32
33 #ifdef __NetBSD__
34 #if 0 /* XXX uvmhist option? */
35 #include "opt_uvmhist.h"
36 #endif
37
38 #include <sys/types.h>
39 #include <sys/param.h>
40
41 #include <uvm/uvm.h>
42 #include <uvm/uvm_extern.h>
43 #include <uvm/uvm_fault.h>
44 #include <uvm/uvm_page.h>
45 #include <uvm/uvm_pmap.h>
46 #include <uvm/uvm_prot.h>
47
48 #include <drm/bus_dma_hacks.h>
49 #endif
50
51 #include <drm/drmP.h>
52 #include <drm/drm_vma_manager.h>
53 #include <drm/i915_drm.h>
54 #include "i915_drv.h"
55 #include "i915_vgpu.h"
56 #include "i915_trace.h"
57 #include "intel_drv.h"
58 #include <linux/shmem_fs.h>
59 #include <linux/slab.h>
60 #include <linux/swap.h>
61 #include <linux/pci.h>
62 #include <linux/dma-buf.h>
63 #include <linux/errno.h>
64 #include <linux/time.h>
65 #include <linux/err.h>
66 #include <linux/bitops.h>
67 #include <linux/printk.h>
68 #include <asm/param.h>
69 #include <asm/page.h>
70
71 #define RQ_BUG_ON(expr)
72
73 static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
74 static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj);
75 static void
76 i915_gem_object_retire__write(struct drm_i915_gem_object *obj);
77 static void
78 i915_gem_object_retire__read(struct drm_i915_gem_object *obj, int ring);
79
80 static bool cpu_cache_is_coherent(struct drm_device *dev,
81 enum i915_cache_level level)
82 {
83 return HAS_LLC(dev) || level != I915_CACHE_NONE;
84 }
85
86 static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
87 {
88 if (!cpu_cache_is_coherent(obj->base.dev, obj->cache_level))
89 return true;
90
91 return obj->pin_display;
92 }
93
94 /* some bookkeeping */
95 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
96 size_t size)
97 {
98 spin_lock(&dev_priv->mm.object_stat_lock);
99 dev_priv->mm.object_count++;
100 dev_priv->mm.object_memory += size;
101 spin_unlock(&dev_priv->mm.object_stat_lock);
102 }
103
104 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
105 size_t size)
106 {
107 spin_lock(&dev_priv->mm.object_stat_lock);
108 dev_priv->mm.object_count--;
109 dev_priv->mm.object_memory -= size;
110 spin_unlock(&dev_priv->mm.object_stat_lock);
111 }
112
113 static int
114 i915_gem_wait_for_error(struct i915_gpu_error *error)
115 {
116 int ret;
117
118 #define EXIT_COND (!i915_reset_in_progress(error) || \
119 i915_terminally_wedged(error))
120 if (EXIT_COND)
121 return 0;
122
123 /*
124 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
125 * userspace. If it takes that long something really bad is going on and
126 * we should simply try to bail out and fail as gracefully as possible.
127 */
128 #ifdef __NetBSD__
129 spin_lock(&error->reset_lock);
130 DRM_SPIN_TIMED_WAIT_UNTIL(ret, &error->reset_queue, &error->reset_lock,
131 10*HZ, EXIT_COND);
132 spin_unlock(&error->reset_lock);
133 #else
134 ret = wait_event_interruptible_timeout(error->reset_queue,
135 EXIT_COND,
136 10*HZ);
137 #endif
138 if (ret == 0) {
139 DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
140 return -EIO;
141 } else if (ret < 0) {
142 return ret;
143 }
144 #undef EXIT_COND
145
146 return 0;
147 }
148
149 int i915_mutex_lock_interruptible(struct drm_device *dev)
150 {
151 struct drm_i915_private *dev_priv = dev->dev_private;
152 int ret;
153
154 ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
155 if (ret)
156 return ret;
157
158 ret = mutex_lock_interruptible(&dev->struct_mutex);
159 if (ret)
160 return ret;
161
162 WARN_ON(i915_verify_lists(dev));
163 return 0;
164 }
165
166 int
167 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
168 struct drm_file *file)
169 {
170 struct drm_i915_private *dev_priv = dev->dev_private;
171 struct drm_i915_gem_get_aperture *args = data;
172 struct i915_gtt *ggtt = &dev_priv->gtt;
173 struct i915_vma *vma;
174 size_t pinned;
175
176 pinned = 0;
177 mutex_lock(&dev->struct_mutex);
178 list_for_each_entry(vma, &ggtt->base.active_list, mm_list)
179 if (vma->pin_count)
180 pinned += vma->node.size;
181 list_for_each_entry(vma, &ggtt->base.inactive_list, mm_list)
182 if (vma->pin_count)
183 pinned += vma->node.size;
184 mutex_unlock(&dev->struct_mutex);
185
186 args->aper_size = dev_priv->gtt.base.total;
187 args->aper_available_size = args->aper_size - pinned;
188
189 return 0;
190 }
191
192 static int
193 i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
194 {
195 #ifndef __NetBSD__
196 struct address_space *mapping = file_inode(obj->base.filp)->i_mapping;
197 #endif
198 char *vaddr = obj->phys_handle->vaddr;
199 #ifndef __NetBSD__
200 struct sg_table *st;
201 struct scatterlist *sg;
202 #endif
203 int i;
204
205 if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
206 return -EINVAL;
207
208 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
209 struct page *page;
210 char *src;
211
212 #ifdef __NetBSD__
213 struct pglist pages = TAILQ_HEAD_INITIALIZER(pages);
214 int ret;
215 /* XXX errno NetBSD->Linux */
216 ret = -uvm_obj_wirepages(obj->base.gemo_shm_uao,
217 i*PAGE_SIZE, (i + 1)*PAGE_SIZE, &pages);
218 if (ret)
219 return ret;
220 page = container_of(TAILQ_FIRST(&pages), struct page, p_vmp);
221 #else
222 page = shmem_read_mapping_page(mapping, i);
223 if (IS_ERR(page))
224 return PTR_ERR(page);
225 #endif
226
227 src = kmap_atomic(page);
228 memcpy(vaddr, src, PAGE_SIZE);
229 drm_clflush_virt_range(vaddr, PAGE_SIZE);
230 kunmap_atomic(src);
231
232 #ifdef __NetBSD__
233 uvm_obj_unwirepages(obj->base.gemo_shm_uao,
234 i*PAGE_SIZE, (i + 1)*PAGE_SIZE);
235 #else
236 page_cache_release(page);
237 #endif
238 vaddr += PAGE_SIZE;
239 }
240
241 i915_gem_chipset_flush(obj->base.dev);
242
243 #ifdef __NetBSD__
244 /*
245 * We don't need to store anything here -- the phys handle is
246 * enough. But obj->pages can't be null while the pages are
247 * mapped.
248 */
249 obj->pages = (void *)1;
250 #else
251 st = kmalloc(sizeof(*st), GFP_KERNEL);
252 if (st == NULL)
253 return -ENOMEM;
254
255 if (sg_alloc_table(st, 1, GFP_KERNEL)) {
256 kfree(st);
257 return -ENOMEM;
258 }
259
260 sg = st->sgl;
261 sg->offset = 0;
262 sg->length = obj->base.size;
263
264 sg_dma_address(sg) = obj->phys_handle->busaddr;
265 sg_dma_len(sg) = obj->base.size;
266
267 obj->pages = st;
268 #endif
269 return 0;
270 }
271
272 static void
273 i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj)
274 {
275 int ret;
276
277 BUG_ON(obj->madv == __I915_MADV_PURGED);
278
279 ret = i915_gem_object_set_to_cpu_domain(obj, true);
280 if (ret) {
281 /* In the event of a disaster, abandon all caches and
282 * hope for the best.
283 */
284 WARN_ON(ret != -EIO);
285 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
286 }
287
288 if (obj->madv == I915_MADV_DONTNEED)
289 obj->dirty = 0;
290
291 if (obj->dirty) {
292 #ifndef __NetBSD__
293 struct address_space *mapping = file_inode(obj->base.filp)->i_mapping;
294 #endif
295 const char *vaddr = obj->phys_handle->vaddr;
296 int i;
297
298 for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
299 struct page *page;
300 char *dst;
301
302 #ifdef __NetBSD__
303 struct pglist pages = TAILQ_HEAD_INITIALIZER(pages);
304 int ret;
305 /* XXX errno NetBSD->Linux */
306 ret = -uvm_obj_wirepages(obj->base.gemo_shm_uao,
307 i*PAGE_SIZE, (i + 1)*PAGE_SIZE, &pages);
308 if (ret)
309 continue;
310 page = container_of(TAILQ_FIRST(&pages), struct page,
311 p_vmp);
312 #endif
313
314 dst = kmap_atomic(page);
315 drm_clflush_virt_range(vaddr, PAGE_SIZE);
316 memcpy(dst, vaddr, PAGE_SIZE);
317 kunmap_atomic(dst);
318
319 #ifdef __NetBSD__
320 vm_page->flags &= ~PG_CLEAN;
321 /* XXX mark page accessed */
322 uvm_obj_unwirepages(obj->base.gemo_shm_uao,
323 i*PAGE_SIZE, (i+1)*PAGE_SIZE);
324 #else
325 set_page_dirty(page);
326 if (obj->madv == I915_MADV_WILLNEED)
327 mark_page_accessed(page);
328 page_cache_release(page);
329 #endif
330 vaddr += PAGE_SIZE;
331 }
332 obj->dirty = 0;
333 }
334
335 sg_free_table(obj->pages);
336 kfree(obj->pages);
337 }
338
339 static void
340 i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
341 {
342 drm_pci_free(obj->base.dev, obj->phys_handle);
343 }
344
345 static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
346 .get_pages = i915_gem_object_get_pages_phys,
347 .put_pages = i915_gem_object_put_pages_phys,
348 .release = i915_gem_object_release_phys,
349 };
350
351 static int
352 drop_pages(struct drm_i915_gem_object *obj)
353 {
354 struct i915_vma *vma, *next;
355 int ret;
356
357 drm_gem_object_reference(&obj->base);
358 list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link)
359 if (i915_vma_unbind(vma))
360 break;
361
362 ret = i915_gem_object_put_pages(obj);
363 drm_gem_object_unreference(&obj->base);
364
365 return ret;
366 }
367
368 int
369 i915_gem_object_attach_phys(struct drm_i915_gem_object *obj,
370 int align)
371 {
372 drm_dma_handle_t *phys;
373 int ret;
374
375 if (obj->phys_handle) {
376 if ((unsigned long)obj->phys_handle->vaddr & (align -1))
377 return -EBUSY;
378
379 return 0;
380 }
381
382 if (obj->madv != I915_MADV_WILLNEED)
383 return -EFAULT;
384
385 #ifdef __NetBSD__
386 if (obj->base.gemo_shm_uao == NULL)
387 return -EINVAL;
388 #else
389 if (obj->base.filp == NULL)
390 return -EINVAL;
391 #endif
392
393 ret = drop_pages(obj);
394 if (ret)
395 return ret;
396
397 /* create a new object */
398 phys = drm_pci_alloc(obj->base.dev, obj->base.size, align);
399 if (!phys)
400 return -ENOMEM;
401
402 obj->phys_handle = phys;
403 obj->ops = &i915_gem_phys_ops;
404
405 return i915_gem_object_get_pages(obj);
406 }
407
408 static int
409 i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
410 struct drm_i915_gem_pwrite *args,
411 struct drm_file *file_priv)
412 {
413 struct drm_device *dev = obj->base.dev;
414 void *vaddr = (char *)obj->phys_handle->vaddr + args->offset;
415 char __user *user_data = to_user_ptr(args->data_ptr);
416 int ret = 0;
417
418 /* We manually control the domain here and pretend that it
419 * remains coherent i.e. in the GTT domain, like shmem_pwrite.
420 */
421 ret = i915_gem_object_wait_rendering(obj, false);
422 if (ret)
423 return ret;
424
425 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
426 if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
427 unsigned long unwritten;
428
429 /* The physical object once assigned is fixed for the lifetime
430 * of the obj, so we can safely drop the lock and continue
431 * to access vaddr.
432 */
433 mutex_unlock(&dev->struct_mutex);
434 unwritten = copy_from_user(vaddr, user_data, args->size);
435 mutex_lock(&dev->struct_mutex);
436 if (unwritten) {
437 ret = -EFAULT;
438 goto out;
439 }
440 }
441
442 drm_clflush_virt_range(vaddr, args->size);
443 i915_gem_chipset_flush(dev);
444
445 out:
446 intel_fb_obj_flush(obj, false, ORIGIN_CPU);
447 return ret;
448 }
449
450 void *i915_gem_object_alloc(struct drm_device *dev)
451 {
452 struct drm_i915_private *dev_priv = dev->dev_private;
453 return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
454 }
455
456 void i915_gem_object_free(struct drm_i915_gem_object *obj)
457 {
458 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
459 kmem_cache_free(dev_priv->objects, obj);
460 }
461
462 static int
463 i915_gem_create(struct drm_file *file,
464 struct drm_device *dev,
465 uint64_t size,
466 uint32_t *handle_p)
467 {
468 struct drm_i915_gem_object *obj;
469 int ret;
470 u32 handle;
471
472 size = roundup(size, PAGE_SIZE);
473 if (size == 0)
474 return -EINVAL;
475
476 /* Allocate the new object */
477 obj = i915_gem_alloc_object(dev, size);
478 if (obj == NULL)
479 return -ENOMEM;
480
481 ret = drm_gem_handle_create(file, &obj->base, &handle);
482 /* drop reference from allocate - handle holds it now */
483 drm_gem_object_unreference_unlocked(&obj->base);
484 if (ret)
485 return ret;
486
487 *handle_p = handle;
488 return 0;
489 }
490
491 int
492 i915_gem_dumb_create(struct drm_file *file,
493 struct drm_device *dev,
494 struct drm_mode_create_dumb *args)
495 {
496 /* have to work out size/pitch and return them */
497 #ifdef __NetBSD__ /* ALIGN means something else. */
498 args->pitch = round_up(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
499 #else
500 args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
501 #endif
502 args->size = args->pitch * args->height;
503 return i915_gem_create(file, dev,
504 args->size, &args->handle);
505 }
506
507 /**
508 * Creates a new mm object and returns a handle to it.
509 */
510 int
511 i915_gem_create_ioctl(struct drm_device *dev, void *data,
512 struct drm_file *file)
513 {
514 struct drm_i915_gem_create *args = data;
515
516 return i915_gem_create(file, dev,
517 args->size, &args->handle);
518 }
519
520 static inline int
521 __copy_to_user_swizzled(char __user *cpu_vaddr,
522 const char *gpu_vaddr, int gpu_offset,
523 int length)
524 {
525 int ret, cpu_offset = 0;
526
527 while (length > 0) {
528 #ifdef __NetBSD__ /* XXX ALIGN means something else. */
529 int cacheline_end = round_up(gpu_offset + 1, 64);
530 #else
531 int cacheline_end = ALIGN(gpu_offset + 1, 64);
532 #endif
533 int this_length = min(cacheline_end - gpu_offset, length);
534 int swizzled_gpu_offset = gpu_offset ^ 64;
535
536 ret = __copy_to_user(cpu_vaddr + cpu_offset,
537 gpu_vaddr + swizzled_gpu_offset,
538 this_length);
539 if (ret)
540 return ret + length;
541
542 cpu_offset += this_length;
543 gpu_offset += this_length;
544 length -= this_length;
545 }
546
547 return 0;
548 }
549
550 static inline int
551 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
552 const char __user *cpu_vaddr,
553 int length)
554 {
555 int ret, cpu_offset = 0;
556
557 while (length > 0) {
558 #ifdef __NetBSD__ /* XXX ALIGN means something else. */
559 int cacheline_end = round_up(gpu_offset + 1, 64);
560 #else
561 int cacheline_end = ALIGN(gpu_offset + 1, 64);
562 #endif
563 int this_length = min(cacheline_end - gpu_offset, length);
564 int swizzled_gpu_offset = gpu_offset ^ 64;
565
566 ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
567 cpu_vaddr + cpu_offset,
568 this_length);
569 if (ret)
570 return ret + length;
571
572 cpu_offset += this_length;
573 gpu_offset += this_length;
574 length -= this_length;
575 }
576
577 return 0;
578 }
579
580 /*
581 * Pins the specified object's pages and synchronizes the object with
582 * GPU accesses. Sets needs_clflush to non-zero if the caller should
583 * flush the object from the CPU cache.
584 */
585 int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
586 int *needs_clflush)
587 {
588 int ret;
589
590 *needs_clflush = 0;
591
592 #ifdef __NetBSD__
593 if (obj->base.gemo_shm_uao == NULL)
594 return -EINVAL;
595 #else
596 if (!obj->base.filp)
597 return -EINVAL;
598 #endif
599
600 if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU)) {
601 /* If we're not in the cpu read domain, set ourself into the gtt
602 * read domain and manually flush cachelines (if required). This
603 * optimizes for the case when the gpu will dirty the data
604 * anyway again before the next pread happens. */
605 *needs_clflush = !cpu_cache_is_coherent(obj->base.dev,
606 obj->cache_level);
607 ret = i915_gem_object_wait_rendering(obj, true);
608 if (ret)
609 return ret;
610 }
611
612 ret = i915_gem_object_get_pages(obj);
613 if (ret)
614 return ret;
615
616 i915_gem_object_pin_pages(obj);
617
618 return ret;
619 }
620
621 /* Per-page copy function for the shmem pread fastpath.
622 * Flushes invalid cachelines before reading the target if
623 * needs_clflush is set. */
624 static int
625 shmem_pread_fast(struct page *page, int shmem_page_offset, int page_length,
626 char __user *user_data,
627 bool page_do_bit17_swizzling, bool needs_clflush)
628 {
629 #ifdef __NetBSD__ /* XXX atomic shmem fast path */
630 return -EFAULT;
631 #else
632 char *vaddr;
633 int ret;
634
635 if (unlikely(page_do_bit17_swizzling))
636 return -EINVAL;
637
638 vaddr = kmap_atomic(page);
639 if (needs_clflush)
640 drm_clflush_virt_range(vaddr + shmem_page_offset,
641 page_length);
642 ret = __copy_to_user_inatomic(user_data,
643 vaddr + shmem_page_offset,
644 page_length);
645 kunmap_atomic(vaddr);
646
647 return ret ? -EFAULT : 0;
648 #endif
649 }
650
651 static void
652 shmem_clflush_swizzled_range(char *addr, unsigned long length,
653 bool swizzled)
654 {
655 if (unlikely(swizzled)) {
656 unsigned long start = (unsigned long) addr;
657 unsigned long end = (unsigned long) addr + length;
658
659 /* For swizzling simply ensure that we always flush both
660 * channels. Lame, but simple and it works. Swizzled
661 * pwrite/pread is far from a hotpath - current userspace
662 * doesn't use it at all. */
663 start = round_down(start, 128);
664 end = round_up(end, 128);
665
666 drm_clflush_virt_range((void *)start, end - start);
667 } else {
668 drm_clflush_virt_range(addr, length);
669 }
670
671 }
672
673 /* Only difference to the fast-path function is that this can handle bit17
674 * and uses non-atomic copy and kmap functions. */
675 static int
676 shmem_pread_slow(struct page *page, int shmem_page_offset, int page_length,
677 char __user *user_data,
678 bool page_do_bit17_swizzling, bool needs_clflush)
679 {
680 char *vaddr;
681 int ret;
682
683 vaddr = kmap(page);
684 if (needs_clflush)
685 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
686 page_length,
687 page_do_bit17_swizzling);
688
689 if (page_do_bit17_swizzling)
690 ret = __copy_to_user_swizzled(user_data,
691 vaddr, shmem_page_offset,
692 page_length);
693 else
694 ret = __copy_to_user(user_data,
695 vaddr + shmem_page_offset,
696 page_length);
697 kunmap(page);
698
699 return ret ? - EFAULT : 0;
700 }
701
702 static int
703 i915_gem_shmem_pread(struct drm_device *dev,
704 struct drm_i915_gem_object *obj,
705 struct drm_i915_gem_pread *args,
706 struct drm_file *file)
707 {
708 char __user *user_data;
709 ssize_t remain;
710 loff_t offset;
711 int shmem_page_offset, page_length, ret = 0;
712 int obj_do_bit17_swizzling, page_do_bit17_swizzling;
713 #ifndef __NetBSD__ /* XXX */
714 int prefaulted = 0;
715 #endif
716 int needs_clflush = 0;
717 #ifndef __NetBSD__
718 struct sg_page_iter sg_iter;
719 #endif
720
721 user_data = to_user_ptr(args->data_ptr);
722 remain = args->size;
723
724 obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
725
726 ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
727 if (ret)
728 return ret;
729
730 offset = args->offset;
731
732 #ifdef __NetBSD__
733 while (0 < remain)
734 #else
735 for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents,
736 offset >> PAGE_SHIFT)
737 #endif
738 {
739 #ifdef __NetBSD__
740 struct page *const page = i915_gem_object_get_page(obj,
741 atop(offset));
742 #else
743 struct page *page = sg_page_iter_page(&sg_iter);
744
745 if (remain <= 0)
746 break;
747 #endif
748
749 /* Operation in this page
750 *
751 * shmem_page_offset = offset within page in shmem file
752 * page_length = bytes to copy for this page
753 */
754 shmem_page_offset = offset_in_page(offset);
755 page_length = remain;
756 if ((shmem_page_offset + page_length) > PAGE_SIZE)
757 page_length = PAGE_SIZE - shmem_page_offset;
758
759 page_do_bit17_swizzling = obj_do_bit17_swizzling &&
760 (page_to_phys(page) & (1 << 17)) != 0;
761
762 ret = shmem_pread_fast(page, shmem_page_offset, page_length,
763 user_data, page_do_bit17_swizzling,
764 needs_clflush);
765 if (ret == 0)
766 goto next_page;
767
768 mutex_unlock(&dev->struct_mutex);
769 #ifndef __NetBSD__
770 if (likely(!i915.prefault_disable) && !prefaulted) {
771 ret = fault_in_multipages_writeable(user_data, remain);
772 /* Userspace is tricking us, but we've already clobbered
773 * its pages with the prefault and promised to write the
774 * data up to the first fault. Hence ignore any errors
775 * and just continue. */
776 (void)ret;
777 prefaulted = 1;
778 }
779 #endif
780 ret = shmem_pread_slow(page, shmem_page_offset, page_length,
781 user_data, page_do_bit17_swizzling,
782 needs_clflush);
783
784 mutex_lock(&dev->struct_mutex);
785
786 if (ret)
787 goto out;
788
789 next_page:
790 remain -= page_length;
791 user_data += page_length;
792 offset += page_length;
793 }
794
795 out:
796 i915_gem_object_unpin_pages(obj);
797
798 return ret;
799 }
800
801 /**
802 * Reads data from the object referenced by handle.
803 *
804 * On error, the contents of *data are undefined.
805 */
806 int
807 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
808 struct drm_file *file)
809 {
810 struct drm_i915_gem_pread *args = data;
811 struct drm_gem_object *gobj;
812 struct drm_i915_gem_object *obj;
813 int ret = 0;
814
815 if (args->size == 0)
816 return 0;
817
818 if (!access_ok(VERIFY_WRITE,
819 to_user_ptr(args->data_ptr),
820 args->size))
821 return -EFAULT;
822
823 ret = i915_mutex_lock_interruptible(dev);
824 if (ret)
825 return ret;
826
827 gobj = drm_gem_object_lookup(dev, file, args->handle);
828 if (gobj == NULL) {
829 ret = -ENOENT;
830 goto unlock;
831 }
832 obj = to_intel_bo(gobj);
833
834 /* Bounds check source. */
835 if (args->offset > obj->base.size ||
836 args->size > obj->base.size - args->offset) {
837 ret = -EINVAL;
838 goto out;
839 }
840
841 /* prime objects have no backing filp to GEM pread/pwrite
842 * pages from.
843 */
844 #ifdef __NetBSD__
845 /* Also stolen objects. */
846 if (obj->base.gemo_shm_uao == NULL) {
847 ret = -EINVAL;
848 goto out;
849 }
850 #else
851 if (!obj->base.filp) {
852 ret = -EINVAL;
853 goto out;
854 }
855 #endif
856
857 trace_i915_gem_object_pread(obj, args->offset, args->size);
858
859 ret = i915_gem_shmem_pread(dev, obj, args, file);
860
861 out:
862 drm_gem_object_unreference(&obj->base);
863 unlock:
864 mutex_unlock(&dev->struct_mutex);
865 return ret;
866 }
867
868 /* This is the fast write path which cannot handle
869 * page faults in the source data
870 */
871
872 static inline int
873 fast_user_write(struct io_mapping *mapping,
874 loff_t page_base, int page_offset,
875 char __user *user_data,
876 int length)
877 {
878 #ifdef __NetBSD__ /* XXX atomic shmem fast path */
879 return -EFAULT;
880 #else
881 void __iomem *vaddr_atomic;
882 void *vaddr;
883 unsigned long unwritten;
884
885 vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
886 /* We can use the cpu mem copy function because this is X86. */
887 vaddr = (void __force*)vaddr_atomic + page_offset;
888 unwritten = __copy_from_user_inatomic_nocache(vaddr,
889 user_data, length);
890 io_mapping_unmap_atomic(vaddr_atomic);
891 return unwritten;
892 #endif
893 }
894
895 /**
896 * This is the fast pwrite path, where we copy the data directly from the
897 * user into the GTT, uncached.
898 */
899 static int
900 i915_gem_gtt_pwrite_fast(struct drm_device *dev,
901 struct drm_i915_gem_object *obj,
902 struct drm_i915_gem_pwrite *args,
903 struct drm_file *file)
904 {
905 struct drm_i915_private *dev_priv = dev->dev_private;
906 ssize_t remain;
907 loff_t offset, page_base;
908 char __user *user_data;
909 int page_offset, page_length, ret;
910
911 ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_MAPPABLE | PIN_NONBLOCK);
912 if (ret)
913 goto out;
914
915 ret = i915_gem_object_set_to_gtt_domain(obj, true);
916 if (ret)
917 goto out_unpin;
918
919 ret = i915_gem_object_put_fence(obj);
920 if (ret)
921 goto out_unpin;
922
923 user_data = to_user_ptr(args->data_ptr);
924 remain = args->size;
925
926 offset = i915_gem_obj_ggtt_offset(obj) + args->offset;
927
928 intel_fb_obj_invalidate(obj, ORIGIN_GTT);
929
930 while (remain > 0) {
931 /* Operation in this page
932 *
933 * page_base = page offset within aperture
934 * page_offset = offset within page
935 * page_length = bytes to copy for this page
936 */
937 page_base = offset & PAGE_MASK;
938 page_offset = offset_in_page(offset);
939 page_length = remain;
940 if ((page_offset + remain) > PAGE_SIZE)
941 page_length = PAGE_SIZE - page_offset;
942
943 /* If we get a fault while copying data, then (presumably) our
944 * source page isn't available. Return the error and we'll
945 * retry in the slow path.
946 */
947 if (fast_user_write(dev_priv->gtt.mappable, page_base,
948 page_offset, user_data, page_length)) {
949 ret = -EFAULT;
950 goto out_flush;
951 }
952
953 remain -= page_length;
954 user_data += page_length;
955 offset += page_length;
956 }
957
958 out_flush:
959 intel_fb_obj_flush(obj, false, ORIGIN_GTT);
960 out_unpin:
961 i915_gem_object_ggtt_unpin(obj);
962 out:
963 return ret;
964 }
965
966 /* Per-page copy function for the shmem pwrite fastpath.
967 * Flushes invalid cachelines before writing to the target if
968 * needs_clflush_before is set and flushes out any written cachelines after
969 * writing if needs_clflush is set. */
970 static int
971 shmem_pwrite_fast(struct page *page, int shmem_page_offset, int page_length,
972 char __user *user_data,
973 bool page_do_bit17_swizzling,
974 bool needs_clflush_before,
975 bool needs_clflush_after)
976 {
977 #ifdef __NetBSD__
978 return -EFAULT;
979 #else
980 char *vaddr;
981 int ret;
982
983 if (unlikely(page_do_bit17_swizzling))
984 return -EINVAL;
985
986 vaddr = kmap_atomic(page);
987 if (needs_clflush_before)
988 drm_clflush_virt_range(vaddr + shmem_page_offset,
989 page_length);
990 ret = __copy_from_user_inatomic(vaddr + shmem_page_offset,
991 user_data, page_length);
992 if (needs_clflush_after)
993 drm_clflush_virt_range(vaddr + shmem_page_offset,
994 page_length);
995 kunmap_atomic(vaddr);
996
997 return ret ? -EFAULT : 0;
998 #endif
999 }
1000
1001 /* Only difference to the fast-path function is that this can handle bit17
1002 * and uses non-atomic copy and kmap functions. */
1003 static int
1004 shmem_pwrite_slow(struct page *page, int shmem_page_offset, int page_length,
1005 char __user *user_data,
1006 bool page_do_bit17_swizzling,
1007 bool needs_clflush_before,
1008 bool needs_clflush_after)
1009 {
1010 char *vaddr;
1011 int ret;
1012
1013 vaddr = kmap(page);
1014 if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
1015 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
1016 page_length,
1017 page_do_bit17_swizzling);
1018 if (page_do_bit17_swizzling)
1019 ret = __copy_from_user_swizzled(vaddr, shmem_page_offset,
1020 user_data,
1021 page_length);
1022 else
1023 ret = __copy_from_user(vaddr + shmem_page_offset,
1024 user_data,
1025 page_length);
1026 if (needs_clflush_after)
1027 shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
1028 page_length,
1029 page_do_bit17_swizzling);
1030 kunmap(page);
1031
1032 return ret ? -EFAULT : 0;
1033 }
1034
1035 static int
1036 i915_gem_shmem_pwrite(struct drm_device *dev,
1037 struct drm_i915_gem_object *obj,
1038 struct drm_i915_gem_pwrite *args,
1039 struct drm_file *file)
1040 {
1041 ssize_t remain;
1042 loff_t offset;
1043 char __user *user_data;
1044 int shmem_page_offset, page_length, ret = 0;
1045 int obj_do_bit17_swizzling, page_do_bit17_swizzling;
1046 int hit_slowpath = 0;
1047 int needs_clflush_after = 0;
1048 int needs_clflush_before = 0;
1049 #ifndef __NetBSD__
1050 struct sg_page_iter sg_iter;
1051 int flush_mask = boot_cpu_data.x86_clflush_size - 1;
1052 #else
1053 int flush_mask = cpu_info_primary.ci_cflush_lsize - 1;
1054 #endif
1055
1056 user_data = to_user_ptr(args->data_ptr);
1057 remain = args->size;
1058
1059 obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
1060
1061 if (obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
1062 /* If we're not in the cpu write domain, set ourself into the gtt
1063 * write domain and manually flush cachelines (if required). This
1064 * optimizes for the case when the gpu will use the data
1065 * right away and we therefore have to clflush anyway. */
1066 needs_clflush_after = cpu_write_needs_clflush(obj);
1067 ret = i915_gem_object_wait_rendering(obj, false);
1068 if (ret)
1069 return ret;
1070 }
1071 /* Same trick applies to invalidate partially written cachelines read
1072 * before writing. */
1073 if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0)
1074 needs_clflush_before =
1075 !cpu_cache_is_coherent(dev, obj->cache_level);
1076
1077 ret = i915_gem_object_get_pages(obj);
1078 if (ret)
1079 return ret;
1080
1081 intel_fb_obj_invalidate(obj, ORIGIN_CPU);
1082
1083 i915_gem_object_pin_pages(obj);
1084
1085 offset = args->offset;
1086 obj->dirty = 1;
1087
1088 #ifdef __NetBSD__
1089 while (0 < remain)
1090 #else
1091 for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents,
1092 offset >> PAGE_SHIFT)
1093 #endif
1094 {
1095 #ifdef __NetBSD__
1096 struct page *const page = i915_gem_object_get_page(obj,
1097 atop(offset));
1098 #else
1099 struct page *page = sg_page_iter_page(&sg_iter);
1100 #endif
1101
1102 if (remain <= 0)
1103 break;
1104
1105 /* Operation in this page
1106 *
1107 * shmem_page_offset = offset within page in shmem file
1108 * page_length = bytes to copy for this page
1109 */
1110 shmem_page_offset = offset_in_page(offset);
1111
1112 page_length = remain;
1113 if ((shmem_page_offset + page_length) > PAGE_SIZE)
1114 page_length = PAGE_SIZE - shmem_page_offset;
1115
1116 /* If we don't overwrite a cacheline completely we need to be
1117 * careful to have up-to-date data by first clflushing. Don't
1118 * overcomplicate things and flush the entire patch. */
1119 const int partial_cacheline_write = needs_clflush_before &&
1120 ((shmem_page_offset | page_length) & flush_mask);
1121
1122 page_do_bit17_swizzling = obj_do_bit17_swizzling &&
1123 (page_to_phys(page) & (1 << 17)) != 0;
1124
1125 ret = shmem_pwrite_fast(page, shmem_page_offset, page_length,
1126 user_data, page_do_bit17_swizzling,
1127 partial_cacheline_write,
1128 needs_clflush_after);
1129 if (ret == 0)
1130 goto next_page;
1131
1132 hit_slowpath = 1;
1133 mutex_unlock(&dev->struct_mutex);
1134 ret = shmem_pwrite_slow(page, shmem_page_offset, page_length,
1135 user_data, page_do_bit17_swizzling,
1136 partial_cacheline_write,
1137 needs_clflush_after);
1138
1139 mutex_lock(&dev->struct_mutex);
1140
1141 if (ret)
1142 goto out;
1143
1144 next_page:
1145 remain -= page_length;
1146 user_data += page_length;
1147 offset += page_length;
1148 }
1149
1150 out:
1151 i915_gem_object_unpin_pages(obj);
1152
1153 if (hit_slowpath) {
1154 /*
1155 * Fixup: Flush cpu caches in case we didn't flush the dirty
1156 * cachelines in-line while writing and the object moved
1157 * out of the cpu write domain while we've dropped the lock.
1158 */
1159 if (!needs_clflush_after &&
1160 obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
1161 if (i915_gem_clflush_object(obj, obj->pin_display))
1162 needs_clflush_after = true;
1163 }
1164 }
1165
1166 if (needs_clflush_after)
1167 i915_gem_chipset_flush(dev);
1168 else
1169 obj->cache_dirty = true;
1170
1171 intel_fb_obj_flush(obj, false, ORIGIN_CPU);
1172 return ret;
1173 }
1174
1175 /**
1176 * Writes data to the object referenced by handle.
1177 *
1178 * On error, the contents of the buffer that were to be modified are undefined.
1179 */
1180 int
1181 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
1182 struct drm_file *file)
1183 {
1184 struct drm_i915_private *dev_priv = dev->dev_private;
1185 struct drm_i915_gem_pwrite *args = data;
1186 struct drm_gem_object *gobj;
1187 struct drm_i915_gem_object *obj;
1188 int ret;
1189
1190 if (args->size == 0)
1191 return 0;
1192
1193 if (!access_ok(VERIFY_READ,
1194 to_user_ptr(args->data_ptr),
1195 args->size))
1196 return -EFAULT;
1197
1198 #ifndef __NetBSD__ /* XXX prefault */
1199 if (likely(!i915.prefault_disable)) {
1200 ret = fault_in_multipages_readable(to_user_ptr(args->data_ptr),
1201 args->size);
1202 if (ret)
1203 return -EFAULT;
1204 }
1205 #endif
1206
1207 intel_runtime_pm_get(dev_priv);
1208
1209 ret = i915_mutex_lock_interruptible(dev);
1210 if (ret)
1211 goto put_rpm;
1212
1213 gobj = drm_gem_object_lookup(dev, file, args->handle);
1214 if (gobj == NULL) {
1215 ret = -ENOENT;
1216 goto unlock;
1217 }
1218 obj = to_intel_bo(gobj);
1219
1220 /* Bounds check destination. */
1221 if (args->offset > obj->base.size ||
1222 args->size > obj->base.size - args->offset) {
1223 ret = -EINVAL;
1224 goto out;
1225 }
1226
1227 /* prime objects have no backing filp to GEM pread/pwrite
1228 * pages from.
1229 */
1230 #ifdef __NetBSD__
1231 /* Also stolen objects. */
1232 if (obj->base.gemo_shm_uao == NULL) {
1233 ret = -EINVAL;
1234 goto out;
1235 }
1236 #else
1237 if (!obj->base.filp) {
1238 ret = -EINVAL;
1239 goto out;
1240 }
1241 #endif
1242
1243 trace_i915_gem_object_pwrite(obj, args->offset, args->size);
1244
1245 ret = -EFAULT;
1246 /* We can only do the GTT pwrite on untiled buffers, as otherwise
1247 * it would end up going through the fenced access, and we'll get
1248 * different detiling behavior between reading and writing.
1249 * pread/pwrite currently are reading and writing from the CPU
1250 * perspective, requiring manual detiling by the client.
1251 */
1252 if (obj->tiling_mode == I915_TILING_NONE &&
1253 obj->base.write_domain != I915_GEM_DOMAIN_CPU &&
1254 cpu_write_needs_clflush(obj)) {
1255 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
1256 /* Note that the gtt paths might fail with non-page-backed user
1257 * pointers (e.g. gtt mappings when moving data between
1258 * textures). Fallback to the shmem path in that case. */
1259 }
1260
1261 if (ret == -EFAULT || ret == -ENOSPC) {
1262 if (obj->phys_handle)
1263 ret = i915_gem_phys_pwrite(obj, args, file);
1264 else
1265 ret = i915_gem_shmem_pwrite(dev, obj, args, file);
1266 }
1267
1268 out:
1269 drm_gem_object_unreference(&obj->base);
1270 unlock:
1271 mutex_unlock(&dev->struct_mutex);
1272 put_rpm:
1273 intel_runtime_pm_put(dev_priv);
1274
1275 return ret;
1276 }
1277
1278 int
1279 i915_gem_check_wedge(struct i915_gpu_error *error,
1280 bool interruptible)
1281 {
1282 if (i915_reset_in_progress(error)) {
1283 /* Non-interruptible callers can't handle -EAGAIN, hence return
1284 * -EIO unconditionally for these. */
1285 if (!interruptible)
1286 return -EIO;
1287
1288 /* Recovery complete, but the reset failed ... */
1289 if (i915_terminally_wedged(error))
1290 return -EIO;
1291
1292 /*
1293 * Check if GPU Reset is in progress - we need intel_ring_begin
1294 * to work properly to reinit the hw state while the gpu is
1295 * still marked as reset-in-progress. Handle this with a flag.
1296 */
1297 if (!error->reload_in_reset)
1298 return -EAGAIN;
1299 }
1300
1301 return 0;
1302 }
1303
1304 #ifndef __NetBSD__
1305 static void fake_irq(unsigned long data)
1306 {
1307 wake_up_process((struct task_struct *)data);
1308 }
1309 #endif
1310
1311 static bool missed_irq(struct drm_i915_private *dev_priv,
1312 struct intel_engine_cs *ring)
1313 {
1314 return test_bit(ring->id, &dev_priv->gpu_error.missed_irq_rings);
1315 }
1316
1317 static unsigned long local_clock_us(unsigned *cpu)
1318 {
1319 unsigned long t;
1320
1321 /* Cheaply and approximately convert from nanoseconds to microseconds.
1322 * The result and subsequent calculations are also defined in the same
1323 * approximate microseconds units. The principal source of timing
1324 * error here is from the simple truncation.
1325 *
1326 * Note that local_clock() is only defined wrt to the current CPU;
1327 * the comparisons are no longer valid if we switch CPUs. Instead of
1328 * blocking preemption for the entire busywait, we can detect the CPU
1329 * switch and use that as indicator of system load and a reason to
1330 * stop busywaiting, see busywait_stop().
1331 */
1332 *cpu = get_cpu();
1333 t = local_clock() >> 10;
1334 put_cpu();
1335
1336 return t;
1337 }
1338
1339 static bool busywait_stop(unsigned long timeout, unsigned cpu)
1340 {
1341 unsigned this_cpu;
1342
1343 if (time_after(local_clock_us(&this_cpu), timeout))
1344 return true;
1345
1346 return this_cpu != cpu;
1347 }
1348
1349 static int __i915_spin_request(struct drm_i915_gem_request *req, int state)
1350 {
1351 #ifndef __NetBSD__
1352 unsigned long timeout;
1353 unsigned cpu;
1354 #endif
1355
1356 /* When waiting for high frequency requests, e.g. during synchronous
1357 * rendering split between the CPU and GPU, the finite amount of time
1358 * required to set up the irq and wait upon it limits the response
1359 * rate. By busywaiting on the request completion for a short while we
1360 * can service the high frequency waits as quick as possible. However,
1361 * if it is a slow request, we want to sleep as quickly as possible.
1362 * The tradeoff between waiting and sleeping is roughly the time it
1363 * takes to sleep on a request, on the order of a microsecond.
1364 */
1365
1366 if (req->ring->irq_refcount)
1367 return -EBUSY;
1368
1369 /* Only spin if we know the GPU is processing this request */
1370 if (!i915_gem_request_started(req, true))
1371 return -EAGAIN;
1372
1373 #ifndef __NetBSD__ /* XXX No local clock in usec. */
1374 timeout = local_clock_us(&cpu) + 5;
1375 while (!need_resched()) {
1376 if (i915_gem_request_completed(req, true))
1377 return 0;
1378
1379 if (signal_pending_state(state, current))
1380 break;
1381
1382 if (busywait_stop(timeout, cpu))
1383 break;
1384
1385 cpu_relax_lowlatency();
1386 }
1387 #endif
1388
1389 if (i915_gem_request_completed(req, false))
1390 return 0;
1391
1392 return -EAGAIN;
1393 }
1394
1395 /**
1396 * __i915_wait_request - wait until execution of request has finished
1397 * @req: duh!
1398 * @reset_counter: reset sequence associated with the given request
1399 * @interruptible: do an interruptible wait (normally yes)
1400 * @timeout: in - how long to wait (NULL forever); out - how much time remaining
1401 *
1402 * Note: It is of utmost importance that the passed in seqno and reset_counter
1403 * values have been read by the caller in an smp safe manner. Where read-side
1404 * locks are involved, it is sufficient to read the reset_counter before
1405 * unlocking the lock that protects the seqno. For lockless tricks, the
1406 * reset_counter _must_ be read before, and an appropriate smp_rmb must be
1407 * inserted.
1408 *
1409 * Returns 0 if the request was found within the alloted time. Else returns the
1410 * errno with remaining time filled in timeout argument.
1411 */
1412 int __i915_wait_request(struct drm_i915_gem_request *req,
1413 unsigned reset_counter,
1414 bool interruptible,
1415 s64 *timeout,
1416 struct intel_rps_client *rps)
1417 {
1418 struct intel_engine_cs *ring = i915_gem_request_get_ring(req);
1419 struct drm_device *dev = ring->dev;
1420 struct drm_i915_private *dev_priv = dev->dev_private;
1421 const bool irq_test_in_progress =
1422 ACCESS_ONCE(dev_priv->gpu_error.test_irq_rings) & intel_ring_flag(ring);
1423 int state = interruptible ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1424 #ifndef __NetBSD__
1425 DEFINE_WAIT(wait);
1426 #endif
1427 unsigned long timeout_expire;
1428 s64 before, now;
1429 int ret;
1430
1431 WARN(!intel_irqs_enabled(dev_priv), "IRQs disabled");
1432
1433 if (list_empty(&req->list))
1434 return 0;
1435
1436 if (i915_gem_request_completed(req, true))
1437 return 0;
1438
1439 timeout_expire = 0;
1440 if (timeout) {
1441 if (WARN_ON(*timeout < 0))
1442 return -EINVAL;
1443
1444 if (*timeout == 0)
1445 return -ETIME;
1446
1447 timeout_expire = jiffies + nsecs_to_jiffies_timeout(*timeout);
1448 }
1449
1450 if (INTEL_INFO(dev_priv)->gen >= 6)
1451 gen6_rps_boost(dev_priv, rps, req->emitted_jiffies);
1452
1453 /* Record current time in case interrupted by signal, or wedged */
1454 trace_i915_gem_request_wait_begin(req);
1455 before = ktime_get_raw_ns();
1456
1457 /* Optimistic spin for the next jiffie before touching IRQs */
1458 ret = __i915_spin_request(req, state);
1459 if (ret == 0)
1460 goto out;
1461
1462 if (!irq_test_in_progress && WARN_ON(!ring->irq_get(ring))) {
1463 ret = -ENODEV;
1464 goto out;
1465 }
1466
1467 #ifdef __NetBSD__
1468 # define EXIT_COND \
1469 ((wedged = (reset_counter != \
1470 atomic_read(&dev_priv->gpu_error.reset_counter))) || \
1471 i915_request_completed(req, false))
1472 if (timeout) {
1473 int ticks = nsecs_to_jiffies_timeout(*timeout);
1474 if (interruptible) {
1475 DRM_SPIN_TIMED_WAIT_UNTIL(ret, &ring->irq_queue,
1476 &dev_priv->irq_lock, ticks, EXIT_COND);
1477 } else {
1478 DRM_SPIN_TIMED_WAIT_NOINTR_UNTIL(ret, &ring->irq_queue,
1479 &dev_priv->irq_lock, ticks, EXIT_COND);
1480 }
1481 if (ret < 0) /* Failure: return negative error as is. */
1482 ;
1483 else if (ret == 0) /* Timed out: return -ETIME. */
1484 ret = -ETIME;
1485 else /* Succeeded (ret > 0): return 0. */
1486 ret = 0;
1487 } else {
1488 if (interruptible) {
1489 DRM_SPIN_WAIT_UNTIL(ret, &ring->irq_queue,
1490 &dev_priv->irq_lock, EXIT_COND);
1491 } else {
1492 DRM_SPIN_WAIT_NOINTR_UNTIL(ret, &ring->irq_queue,
1493 &dev_priv->irq_lock, EXIT_COND);
1494 }
1495 /* ret is negative on failure or zero on success. */
1496 }
1497 #else
1498 for (;;) {
1499 struct timer_list timer;
1500
1501 prepare_to_wait(&ring->irq_queue, &wait, state);
1502
1503 /* We need to check whether any gpu reset happened in between
1504 * the caller grabbing the seqno and now ... */
1505 if (reset_counter != atomic_read(&dev_priv->gpu_error.reset_counter)) {
1506 /* ... but upgrade the -EAGAIN to an -EIO if the gpu
1507 * is truely gone. */
1508 ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
1509 if (ret == 0)
1510 ret = -EAGAIN;
1511 break;
1512 }
1513
1514 if (i915_gem_request_completed(req, false)) {
1515 ret = 0;
1516 break;
1517 }
1518
1519 if (signal_pending_state(state, current)) {
1520 ret = -ERESTARTSYS;
1521 break;
1522 }
1523
1524 if (timeout && time_after_eq(jiffies, timeout_expire)) {
1525 ret = -ETIME;
1526 break;
1527 }
1528
1529 timer.function = NULL;
1530 if (timeout || missed_irq(dev_priv, ring)) {
1531 unsigned long expire;
1532
1533 setup_timer_on_stack(&timer, fake_irq, (unsigned long)current);
1534 expire = missed_irq(dev_priv, ring) ? jiffies + 1 : timeout_expire;
1535 mod_timer(&timer, expire);
1536 }
1537
1538 io_schedule();
1539
1540 if (timer.function) {
1541 del_singleshot_timer_sync(&timer);
1542 destroy_timer_on_stack(&timer);
1543 }
1544 }
1545 #endif
1546 if (!irq_test_in_progress)
1547 ring->irq_put(ring);
1548
1549 #ifndef __NetBSD__
1550 finish_wait(&ring->irq_queue, &wait);
1551 #endif
1552
1553 out:
1554 now = ktime_get_raw_ns();
1555 trace_i915_gem_request_wait_end(req);
1556
1557 if (timeout) {
1558 s64 tres = *timeout - (now - before);
1559
1560 *timeout = tres < 0 ? 0 : tres;
1561
1562 /*
1563 * Apparently ktime isn't accurate enough and occasionally has a
1564 * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
1565 * things up to make the test happy. We allow up to 1 jiffy.
1566 *
1567 * This is a regrssion from the timespec->ktime conversion.
1568 */
1569 if (ret == -ETIME && *timeout < jiffies_to_usecs(1)*1000)
1570 *timeout = 0;
1571 }
1572
1573 return ret;
1574 }
1575
1576 int i915_gem_request_add_to_client(struct drm_i915_gem_request *req,
1577 struct drm_file *file)
1578 {
1579 struct drm_i915_private *dev_private;
1580 struct drm_i915_file_private *file_priv;
1581
1582 WARN_ON(!req || !file || req->file_priv);
1583
1584 if (!req || !file)
1585 return -EINVAL;
1586
1587 if (req->file_priv)
1588 return -EINVAL;
1589
1590 dev_private = req->ring->dev->dev_private;
1591 file_priv = file->driver_priv;
1592
1593 spin_lock(&file_priv->mm.lock);
1594 req->file_priv = file_priv;
1595 list_add_tail(&req->client_list, &file_priv->mm.request_list);
1596 spin_unlock(&file_priv->mm.lock);
1597
1598 req->pid = get_pid(task_pid(current));
1599
1600 return 0;
1601 }
1602
1603 static inline void
1604 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
1605 {
1606 struct drm_i915_file_private *file_priv = request->file_priv;
1607
1608 if (!file_priv)
1609 return;
1610
1611 spin_lock(&file_priv->mm.lock);
1612 list_del(&request->client_list);
1613 request->file_priv = NULL;
1614 spin_unlock(&file_priv->mm.lock);
1615
1616 put_pid(request->pid);
1617 request->pid = NULL;
1618 }
1619
1620 static void i915_gem_request_retire(struct drm_i915_gem_request *request)
1621 {
1622 trace_i915_gem_request_retire(request);
1623
1624 /* We know the GPU must have read the request to have
1625 * sent us the seqno + interrupt, so use the position
1626 * of tail of the request to update the last known position
1627 * of the GPU head.
1628 *
1629 * Note this requires that we are always called in request
1630 * completion order.
1631 */
1632 request->ringbuf->last_retired_head = request->postfix;
1633
1634 list_del_init(&request->list);
1635 i915_gem_request_remove_from_client(request);
1636
1637 i915_gem_request_unreference(request);
1638 }
1639
1640 static void
1641 __i915_gem_request_retire__upto(struct drm_i915_gem_request *req)
1642 {
1643 struct intel_engine_cs *engine = req->ring;
1644 struct drm_i915_gem_request *tmp;
1645
1646 lockdep_assert_held(&engine->dev->struct_mutex);
1647
1648 if (list_empty(&req->list))
1649 return;
1650
1651 do {
1652 tmp = list_first_entry(&engine->request_list,
1653 typeof(*tmp), list);
1654
1655 i915_gem_request_retire(tmp);
1656 } while (tmp != req);
1657
1658 WARN_ON(i915_verify_lists(engine->dev));
1659 }
1660
1661 /**
1662 * Waits for a request to be signaled, and cleans up the
1663 * request and object lists appropriately for that event.
1664 */
1665 int
1666 i915_wait_request(struct drm_i915_gem_request *req)
1667 {
1668 struct drm_device *dev;
1669 struct drm_i915_private *dev_priv;
1670 bool interruptible;
1671 int ret;
1672
1673 BUG_ON(req == NULL);
1674
1675 dev = req->ring->dev;
1676 dev_priv = dev->dev_private;
1677 interruptible = dev_priv->mm.interruptible;
1678
1679 BUG_ON(!mutex_is_locked(&dev->struct_mutex));
1680
1681 ret = i915_gem_check_wedge(&dev_priv->gpu_error, interruptible);
1682 if (ret)
1683 return ret;
1684
1685 ret = __i915_wait_request(req,
1686 atomic_read(&dev_priv->gpu_error.reset_counter),
1687 interruptible, NULL, NULL);
1688 if (ret)
1689 return ret;
1690
1691 __i915_gem_request_retire__upto(req);
1692 return 0;
1693 }
1694
1695 /**
1696 * Ensures that all rendering to the object has completed and the object is
1697 * safe to unbind from the GTT or access from the CPU.
1698 */
1699 int
1700 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
1701 bool readonly)
1702 {
1703 int ret, i;
1704
1705 if (!obj->active)
1706 return 0;
1707
1708 if (readonly) {
1709 if (obj->last_write_req != NULL) {
1710 ret = i915_wait_request(obj->last_write_req);
1711 if (ret)
1712 return ret;
1713
1714 i = obj->last_write_req->ring->id;
1715 if (obj->last_read_req[i] == obj->last_write_req)
1716 i915_gem_object_retire__read(obj, i);
1717 else
1718 i915_gem_object_retire__write(obj);
1719 }
1720 } else {
1721 for (i = 0; i < I915_NUM_RINGS; i++) {
1722 if (obj->last_read_req[i] == NULL)
1723 continue;
1724
1725 ret = i915_wait_request(obj->last_read_req[i]);
1726 if (ret)
1727 return ret;
1728
1729 i915_gem_object_retire__read(obj, i);
1730 }
1731 RQ_BUG_ON(obj->active);
1732 }
1733
1734 return 0;
1735 }
1736
1737 static void
1738 i915_gem_object_retire_request(struct drm_i915_gem_object *obj,
1739 struct drm_i915_gem_request *req)
1740 {
1741 int ring = req->ring->id;
1742
1743 if (obj->last_read_req[ring] == req)
1744 i915_gem_object_retire__read(obj, ring);
1745 else if (obj->last_write_req == req)
1746 i915_gem_object_retire__write(obj);
1747
1748 __i915_gem_request_retire__upto(req);
1749 }
1750
1751 /* A nonblocking variant of the above wait. This is a highly dangerous routine
1752 * as the object state may change during this call.
1753 */
1754 static __must_check int
1755 i915_gem_object_wait_rendering__nonblocking(struct drm_i915_gem_object *obj,
1756 struct intel_rps_client *rps,
1757 bool readonly)
1758 {
1759 struct drm_device *dev = obj->base.dev;
1760 struct drm_i915_private *dev_priv = dev->dev_private;
1761 struct drm_i915_gem_request *requests[I915_NUM_RINGS];
1762 unsigned reset_counter;
1763 int ret, i, n = 0;
1764
1765 BUG_ON(!mutex_is_locked(&dev->struct_mutex));
1766 BUG_ON(!dev_priv->mm.interruptible);
1767
1768 if (!obj->active)
1769 return 0;
1770
1771 ret = i915_gem_check_wedge(&dev_priv->gpu_error, true);
1772 if (ret)
1773 return ret;
1774
1775 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
1776
1777 if (readonly) {
1778 struct drm_i915_gem_request *req;
1779
1780 req = obj->last_write_req;
1781 if (req == NULL)
1782 return 0;
1783
1784 requests[n++] = i915_gem_request_reference(req);
1785 } else {
1786 for (i = 0; i < I915_NUM_RINGS; i++) {
1787 struct drm_i915_gem_request *req;
1788
1789 req = obj->last_read_req[i];
1790 if (req == NULL)
1791 continue;
1792
1793 requests[n++] = i915_gem_request_reference(req);
1794 }
1795 }
1796
1797 mutex_unlock(&dev->struct_mutex);
1798 for (i = 0; ret == 0 && i < n; i++)
1799 ret = __i915_wait_request(requests[i], reset_counter, true,
1800 NULL, rps);
1801 mutex_lock(&dev->struct_mutex);
1802
1803 for (i = 0; i < n; i++) {
1804 if (ret == 0)
1805 i915_gem_object_retire_request(obj, requests[i]);
1806 i915_gem_request_unreference(requests[i]);
1807 }
1808
1809 return ret;
1810 }
1811
1812 static struct intel_rps_client *to_rps_client(struct drm_file *file)
1813 {
1814 struct drm_i915_file_private *fpriv = file->driver_priv;
1815 return &fpriv->rps;
1816 }
1817
1818 /**
1819 * Called when user space prepares to use an object with the CPU, either
1820 * through the mmap ioctl's mapping or a GTT mapping.
1821 */
1822 int
1823 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
1824 struct drm_file *file)
1825 {
1826 struct drm_i915_gem_set_domain *args = data;
1827 struct drm_gem_object *gobj;
1828 struct drm_i915_gem_object *obj;
1829 uint32_t read_domains = args->read_domains;
1830 uint32_t write_domain = args->write_domain;
1831 int ret;
1832
1833 /* Only handle setting domains to types used by the CPU. */
1834 if (write_domain & I915_GEM_GPU_DOMAINS)
1835 return -EINVAL;
1836
1837 if (read_domains & I915_GEM_GPU_DOMAINS)
1838 return -EINVAL;
1839
1840 /* Having something in the write domain implies it's in the read
1841 * domain, and only that read domain. Enforce that in the request.
1842 */
1843 if (write_domain != 0 && read_domains != write_domain)
1844 return -EINVAL;
1845
1846 ret = i915_mutex_lock_interruptible(dev);
1847 if (ret)
1848 return ret;
1849
1850 gobj = drm_gem_object_lookup(dev, file, args->handle);
1851 if (gobj == NULL) {
1852 ret = -ENOENT;
1853 goto unlock;
1854 }
1855 obj = to_intel_bo(gobj);
1856
1857 /* Try to flush the object off the GPU without holding the lock.
1858 * We will repeat the flush holding the lock in the normal manner
1859 * to catch cases where we are gazumped.
1860 */
1861 ret = i915_gem_object_wait_rendering__nonblocking(obj,
1862 to_rps_client(file),
1863 !write_domain);
1864 if (ret)
1865 goto unref;
1866
1867 if (read_domains & I915_GEM_DOMAIN_GTT)
1868 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
1869 else
1870 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
1871
1872 if (write_domain != 0)
1873 intel_fb_obj_invalidate(obj,
1874 write_domain == I915_GEM_DOMAIN_GTT ?
1875 ORIGIN_GTT : ORIGIN_CPU);
1876
1877 unref:
1878 drm_gem_object_unreference(&obj->base);
1879 unlock:
1880 mutex_unlock(&dev->struct_mutex);
1881 return ret;
1882 }
1883
1884 /**
1885 * Called when user space has done writes to this buffer
1886 */
1887 int
1888 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
1889 struct drm_file *file)
1890 {
1891 struct drm_i915_gem_sw_finish *args = data;
1892 struct drm_gem_object *gobj;
1893 struct drm_i915_gem_object *obj;
1894 int ret = 0;
1895
1896 ret = i915_mutex_lock_interruptible(dev);
1897 if (ret)
1898 return ret;
1899
1900 gobj = drm_gem_object_lookup(dev, file, args->handle);
1901 if (gobj == NULL) {
1902 ret = -ENOENT;
1903 goto unlock;
1904 }
1905 obj = to_intel_bo(gobj);
1906
1907 /* Pinned buffers may be scanout, so flush the cache */
1908 if (obj->pin_display)
1909 i915_gem_object_flush_cpu_write_domain(obj);
1910
1911 drm_gem_object_unreference(&obj->base);
1912 unlock:
1913 mutex_unlock(&dev->struct_mutex);
1914 return ret;
1915 }
1916
1917 /**
1918 * Maps the contents of an object, returning the address it is mapped
1919 * into.
1920 *
1921 * While the mapping holds a reference on the contents of the object, it doesn't
1922 * imply a ref on the object itself.
1923 *
1924 * IMPORTANT:
1925 *
1926 * DRM driver writers who look a this function as an example for how to do GEM
1927 * mmap support, please don't implement mmap support like here. The modern way
1928 * to implement DRM mmap support is with an mmap offset ioctl (like
1929 * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
1930 * That way debug tooling like valgrind will understand what's going on, hiding
1931 * the mmap call in a driver private ioctl will break that. The i915 driver only
1932 * does cpu mmaps this way because we didn't know better.
1933 */
1934 int
1935 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
1936 struct drm_file *file)
1937 {
1938 struct drm_i915_gem_mmap *args = data;
1939 struct drm_gem_object *obj;
1940 unsigned long addr;
1941 #ifdef __NetBSD__
1942 int ret;
1943 #endif
1944
1945 if (args->flags & ~(I915_MMAP_WC))
1946 return -EINVAL;
1947
1948 if (args->flags & I915_MMAP_WC && !cpu_has_pat)
1949 return -ENODEV;
1950
1951 obj = drm_gem_object_lookup(dev, file, args->handle);
1952 if (obj == NULL)
1953 return -ENOENT;
1954
1955 /* prime objects have no backing filp to GEM mmap
1956 * pages from.
1957 */
1958 #ifdef __NetBSD__
1959 /* Also stolen objects (XXX can we get them here?) */
1960 if (obj->gemo_shm_uao == NULL) {
1961 drm_gem_object_unreference_unlocked(obj);
1962 return -EINVAL;
1963 }
1964 #else
1965 if (!obj->filp) {
1966 drm_gem_object_unreference_unlocked(obj);
1967 return -EINVAL;
1968 }
1969 #endif
1970
1971 #ifdef __NetBSD__
1972 addr = (*curproc->p_emul->e_vm_default_addr)(curproc,
1973 (vaddr_t)curproc->p_vmspace->vm_daddr, args->size,
1974 curproc->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN);
1975 /* XXX errno NetBSD->Linux */
1976 ret = -uvm_map(&curproc->p_vmspace->vm_map, &addr, args->size,
1977 obj->gemo_shm_uao, args->offset, 0,
1978 UVM_MAPFLAG((VM_PROT_READ | VM_PROT_WRITE),
1979 (VM_PROT_READ | VM_PROT_WRITE), UVM_INH_COPY, UVM_ADV_NORMAL,
1980 0));
1981 if (ret) {
1982 drm_gem_object_unreference_unlocked(obj);
1983 return ret;
1984 }
1985 uao_reference(obj->gemo_shm_uao);
1986 drm_gem_object_unreference_unlocked(obj);
1987 #else
1988 addr = vm_mmap(obj->filp, 0, args->size,
1989 PROT_READ | PROT_WRITE, MAP_SHARED,
1990 args->offset);
1991 if (args->flags & I915_MMAP_WC) {
1992 struct mm_struct *mm = current->mm;
1993 struct vm_area_struct *vma;
1994
1995 down_write(&mm->mmap_sem);
1996 vma = find_vma(mm, addr);
1997 if (vma)
1998 vma->vm_page_prot =
1999 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
2000 else
2001 addr = -ENOMEM;
2002 up_write(&mm->mmap_sem);
2003 }
2004 drm_gem_object_unreference_unlocked(obj);
2005 if (IS_ERR((void *)addr))
2006 return addr;
2007 #endif
2008
2009 args->addr_ptr = (uint64_t) addr;
2010
2011 return 0;
2012 }
2013
2014 #ifdef __NetBSD__ /* XXX gem gtt fault */
2015 static int i915_udv_fault(struct uvm_faultinfo *, vaddr_t,
2016 struct vm_page **, int, int, vm_prot_t, int, paddr_t);
2017
2018 int
2019 i915_gem_fault(struct uvm_faultinfo *ufi, vaddr_t vaddr, struct vm_page **pps,
2020 int npages, int centeridx, vm_prot_t access_type, int flags)
2021 {
2022 struct uvm_object *uobj = ufi->entry->object.uvm_obj;
2023 struct drm_gem_object *gem_obj =
2024 container_of(uobj, struct drm_gem_object, gemo_uvmobj);
2025 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
2026 struct drm_device *dev = obj->base.dev;
2027 struct drm_i915_private *dev_priv = dev->dev_private;
2028 voff_t byte_offset;
2029 pgoff_t page_offset;
2030 int ret = 0;
2031 bool write = ISSET(access_type, VM_PROT_WRITE)? 1 : 0;
2032
2033 byte_offset = (ufi->entry->offset + (vaddr - ufi->entry->start));
2034 KASSERT(byte_offset <= obj->base.size);
2035 page_offset = (byte_offset >> PAGE_SHIFT);
2036
2037 intel_runtime_pm_get(dev_priv);
2038
2039 /* Thanks, uvm, but we don't need this lock. */
2040 mutex_exit(uobj->vmobjlock);
2041
2042 ret = i915_mutex_lock_interruptible(dev);
2043 if (ret)
2044 goto out;
2045
2046 trace_i915_gem_object_fault(obj, page_offset, true, write);
2047
2048 ret = i915_gem_object_wait_rendering__nonblocking(obj, NULL, !write);
2049 if (ret)
2050 goto unlock;
2051
2052 if ((obj->cache_level != I915_CACHE_NONE) && !HAS_LLC(dev)) {
2053 ret = -EINVAL;
2054 goto unlock;
2055 }
2056
2057 ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_MAPPABLE);
2058 if (ret)
2059 goto unlock;
2060
2061 ret = i915_gem_object_set_to_gtt_domain(obj, write);
2062 if (ret)
2063 goto unpin;
2064
2065 ret = i915_gem_object_get_fence(obj);
2066 if (ret)
2067 goto unpin;
2068
2069 obj->fault_mappable = true;
2070
2071 /* XXX errno NetBSD->Linux */
2072 ret = -i915_udv_fault(ufi, vaddr, pps, npages, centeridx, access_type,
2073 flags,
2074 (dev_priv->gtt.mappable_base + i915_gem_obj_ggtt_offset(obj)));
2075 unpin:
2076 i915_gem_object_ggtt_unpin(obj);
2077 unlock:
2078 mutex_unlock(&dev->struct_mutex);
2079 out:
2080 mutex_enter(uobj->vmobjlock);
2081 uvmfault_unlockall(ufi, ufi->entry->aref.ar_amap, uobj);
2082 if (ret == -ERESTART)
2083 uvm_wait("i915flt");
2084
2085 /*
2086 * Remap EINTR to success, so that we return to userland.
2087 * On the way out, we'll deliver the signal, and if the signal
2088 * is not fatal then the user code which faulted will most likely
2089 * fault again, and we'll come back here for another try.
2090 */
2091 if (ret == -EINTR)
2092 ret = 0;
2093 /* XXX Deal with GPU hangs here... */
2094 intel_runtime_pm_put(dev_priv);
2095 /* XXX errno Linux->NetBSD */
2096 return -ret;
2097 }
2098
2099 /*
2100 * XXX i915_udv_fault is copypasta of udv_fault from uvm_device.c.
2101 *
2102 * XXX pmap_enter_default instead of pmap_enter because of a problem
2103 * with using weak aliases in kernel modules or something.
2104 */
2105 int pmap_enter_default(pmap_t, vaddr_t, paddr_t, vm_prot_t, unsigned);
2106
2107 static int
2108 i915_udv_fault(struct uvm_faultinfo *ufi, vaddr_t vaddr, struct vm_page **pps,
2109 int npages, int centeridx, vm_prot_t access_type, int flags,
2110 paddr_t gtt_paddr)
2111 {
2112 struct vm_map_entry *entry = ufi->entry;
2113 vaddr_t curr_va;
2114 off_t curr_offset;
2115 paddr_t paddr;
2116 u_int mmapflags;
2117 int lcv, retval;
2118 vm_prot_t mapprot;
2119 UVMHIST_FUNC("i915_udv_fault"); UVMHIST_CALLED(maphist);
2120 UVMHIST_LOG(maphist," flags=%jd", flags,0,0,0);
2121
2122 /*
2123 * we do not allow device mappings to be mapped copy-on-write
2124 * so we kill any attempt to do so here.
2125 */
2126
2127 if (UVM_ET_ISCOPYONWRITE(entry)) {
2128 UVMHIST_LOG(maphist, "<- failed -- COW entry (etype=0x%jx)",
2129 entry->etype, 0,0,0);
2130 return(EIO);
2131 }
2132
2133 /*
2134 * now we must determine the offset in udv to use and the VA to
2135 * use for pmap_enter. note that we always use orig_map's pmap
2136 * for pmap_enter (even if we have a submap). since virtual
2137 * addresses in a submap must match the main map, this is ok.
2138 */
2139
2140 /* udv offset = (offset from start of entry) + entry's offset */
2141 curr_offset = entry->offset + (vaddr - entry->start);
2142 /* pmap va = vaddr (virtual address of pps[0]) */
2143 curr_va = vaddr;
2144
2145 /*
2146 * loop over the page range entering in as needed
2147 */
2148
2149 retval = 0;
2150 for (lcv = 0 ; lcv < npages ; lcv++, curr_offset += PAGE_SIZE,
2151 curr_va += PAGE_SIZE) {
2152 if ((flags & PGO_ALLPAGES) == 0 && lcv != centeridx)
2153 continue;
2154
2155 if (pps[lcv] == PGO_DONTCARE)
2156 continue;
2157
2158 paddr = (gtt_paddr + curr_offset);
2159 mmapflags = 0;
2160 mapprot = ufi->entry->protection;
2161 UVMHIST_LOG(maphist,
2162 " MAPPING: device: pm=0x%#jx, va=0x%jx, pa=0x%jx, at=%jd",
2163 (uintptr_t)ufi->orig_map->pmap, curr_va, paddr, mapprot);
2164 if (pmap_enter_default(ufi->orig_map->pmap, curr_va, paddr, mapprot,
2165 PMAP_CANFAIL | mapprot | mmapflags) != 0) {
2166 /*
2167 * pmap_enter() didn't have the resource to
2168 * enter this mapping. Unlock everything,
2169 * wait for the pagedaemon to free up some
2170 * pages, and then tell uvm_fault() to start
2171 * the fault again.
2172 *
2173 * XXX Needs some rethinking for the PGO_ALLPAGES
2174 * XXX case.
2175 */
2176 pmap_update(ufi->orig_map->pmap); /* sync what we have so far */
2177 return (ERESTART);
2178 }
2179 }
2180
2181 pmap_update(ufi->orig_map->pmap);
2182 return (retval);
2183 }
2184 #else
2185 /**
2186 * i915_gem_fault - fault a page into the GTT
2187 * @vma: VMA in question
2188 * @vmf: fault info
2189 *
2190 * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
2191 * from userspace. The fault handler takes care of binding the object to
2192 * the GTT (if needed), allocating and programming a fence register (again,
2193 * only if needed based on whether the old reg is still valid or the object
2194 * is tiled) and inserting a new PTE into the faulting process.
2195 *
2196 * Note that the faulting process may involve evicting existing objects
2197 * from the GTT and/or fence registers to make room. So performance may
2198 * suffer if the GTT working set is large or there are few fence registers
2199 * left.
2200 */
2201 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2202 {
2203 struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
2204 struct drm_device *dev = obj->base.dev;
2205 struct drm_i915_private *dev_priv = dev->dev_private;
2206 struct i915_ggtt_view view = i915_ggtt_view_normal;
2207 pgoff_t page_offset;
2208 unsigned long pfn;
2209 int ret = 0;
2210 bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
2211
2212 intel_runtime_pm_get(dev_priv);
2213
2214 /* We don't use vmf->pgoff since that has the fake offset */
2215 page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
2216 PAGE_SHIFT;
2217
2218 ret = i915_mutex_lock_interruptible(dev);
2219 if (ret)
2220 goto out;
2221
2222 trace_i915_gem_object_fault(obj, page_offset, true, write);
2223
2224 /* Try to flush the object off the GPU first without holding the lock.
2225 * Upon reacquiring the lock, we will perform our sanity checks and then
2226 * repeat the flush holding the lock in the normal manner to catch cases
2227 * where we are gazumped.
2228 */
2229 ret = i915_gem_object_wait_rendering__nonblocking(obj, NULL, !write);
2230 if (ret)
2231 goto unlock;
2232
2233 /* Access to snoopable pages through the GTT is incoherent. */
2234 if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev)) {
2235 ret = -EFAULT;
2236 goto unlock;
2237 }
2238
2239 /* Use a partial view if the object is bigger than the aperture. */
2240 if (obj->base.size >= dev_priv->gtt.mappable_end &&
2241 obj->tiling_mode == I915_TILING_NONE) {
2242 static const unsigned int chunk_size = 256; // 1 MiB
2243
2244 memset(&view, 0, sizeof(view));
2245 view.type = I915_GGTT_VIEW_PARTIAL;
2246 view.params.partial.offset = rounddown(page_offset, chunk_size);
2247 view.params.partial.size =
2248 min_t(unsigned int,
2249 chunk_size,
2250 (vma->vm_end - vma->vm_start)/PAGE_SIZE -
2251 view.params.partial.offset);
2252 }
2253
2254 /* Now pin it into the GTT if needed */
2255 ret = i915_gem_object_ggtt_pin(obj, &view, 0, PIN_MAPPABLE);
2256 if (ret)
2257 goto unlock;
2258
2259 ret = i915_gem_object_set_to_gtt_domain(obj, write);
2260 if (ret)
2261 goto unpin;
2262
2263 ret = i915_gem_object_get_fence(obj);
2264 if (ret)
2265 goto unpin;
2266
2267 /* Finally, remap it using the new GTT offset */
2268 pfn = dev_priv->gtt.mappable_base +
2269 i915_gem_obj_ggtt_offset_view(obj, &view);
2270 pfn >>= PAGE_SHIFT;
2271
2272 if (unlikely(view.type == I915_GGTT_VIEW_PARTIAL)) {
2273 /* Overriding existing pages in partial view does not cause
2274 * us any trouble as TLBs are still valid because the fault
2275 * is due to userspace losing part of the mapping or never
2276 * having accessed it before (at this partials' range).
2277 */
2278 unsigned long base = vma->vm_start +
2279 (view.params.partial.offset << PAGE_SHIFT);
2280 unsigned int i;
2281
2282 for (i = 0; i < view.params.partial.size; i++) {
2283 ret = vm_insert_pfn(vma, base + i * PAGE_SIZE, pfn + i);
2284 if (ret)
2285 break;
2286 }
2287
2288 obj->fault_mappable = true;
2289 } else {
2290 if (!obj->fault_mappable) {
2291 unsigned long size = min_t(unsigned long,
2292 vma->vm_end - vma->vm_start,
2293 obj->base.size);
2294 int i;
2295
2296 for (i = 0; i < size >> PAGE_SHIFT; i++) {
2297 ret = vm_insert_pfn(vma,
2298 (unsigned long)vma->vm_start + i * PAGE_SIZE,
2299 pfn + i);
2300 if (ret)
2301 break;
2302 }
2303
2304 obj->fault_mappable = true;
2305 } else
2306 ret = vm_insert_pfn(vma,
2307 (unsigned long)vmf->virtual_address,
2308 pfn + page_offset);
2309 }
2310 unpin:
2311 i915_gem_object_ggtt_unpin_view(obj, &view);
2312 unlock:
2313 mutex_unlock(&dev->struct_mutex);
2314 out:
2315 switch (ret) {
2316 case -EIO:
2317 /*
2318 * We eat errors when the gpu is terminally wedged to avoid
2319 * userspace unduly crashing (gl has no provisions for mmaps to
2320 * fail). But any other -EIO isn't ours (e.g. swap in failure)
2321 * and so needs to be reported.
2322 */
2323 if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
2324 ret = VM_FAULT_SIGBUS;
2325 break;
2326 }
2327 case -EAGAIN:
2328 /*
2329 * EAGAIN means the gpu is hung and we'll wait for the error
2330 * handler to reset everything when re-faulting in
2331 * i915_mutex_lock_interruptible.
2332 */
2333 case 0:
2334 case -ERESTARTSYS:
2335 case -EINTR:
2336 case -EBUSY:
2337 /*
2338 * EBUSY is ok: this just means that another thread
2339 * already did the job.
2340 */
2341 ret = VM_FAULT_NOPAGE;
2342 break;
2343 case -ENOMEM:
2344 ret = VM_FAULT_OOM;
2345 break;
2346 case -ENOSPC:
2347 case -EFAULT:
2348 ret = VM_FAULT_SIGBUS;
2349 break;
2350 default:
2351 WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
2352 ret = VM_FAULT_SIGBUS;
2353 break;
2354 }
2355
2356 intel_runtime_pm_put(dev_priv);
2357 return ret;
2358 }
2359 #endif
2360
2361 /**
2362 * i915_gem_release_mmap - remove physical page mappings
2363 * @obj: obj in question
2364 *
2365 * Preserve the reservation of the mmapping with the DRM core code, but
2366 * relinquish ownership of the pages back to the system.
2367 *
2368 * It is vital that we remove the page mapping if we have mapped a tiled
2369 * object through the GTT and then lose the fence register due to
2370 * resource pressure. Similarly if the object has been moved out of the
2371 * aperture, than pages mapped into userspace must be revoked. Removing the
2372 * mapping will then trigger a page fault on the next user access, allowing
2373 * fixup by i915_gem_fault().
2374 */
2375 void
2376 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
2377 {
2378 if (!obj->fault_mappable)
2379 return;
2380
2381 #ifdef __NetBSD__ /* XXX gem gtt fault */
2382 {
2383 struct drm_device *const dev = obj->base.dev;
2384 struct drm_i915_private *const dev_priv = dev->dev_private;
2385 const paddr_t start = dev_priv->gtt.mappable_base +
2386 i915_gem_obj_ggtt_offset(obj);
2387 const size_t size = obj->base.size;
2388 const paddr_t end = start + size;
2389 paddr_t pa;
2390
2391 KASSERT((start & (PAGE_SIZE - 1)) == 0);
2392 KASSERT((size & (PAGE_SIZE - 1)) == 0);
2393
2394 for (pa = start; pa < end; pa += PAGE_SIZE)
2395 pmap_pv_protect(pa, VM_PROT_NONE);
2396 }
2397 #else
2398 drm_vma_node_unmap(&obj->base.vma_node,
2399 obj->base.dev->anon_inode->i_mapping);
2400 #endif
2401 obj->fault_mappable = false;
2402 }
2403
2404 void
2405 i915_gem_release_all_mmaps(struct drm_i915_private *dev_priv)
2406 {
2407 struct drm_i915_gem_object *obj;
2408
2409 list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list)
2410 i915_gem_release_mmap(obj);
2411 }
2412
2413 uint32_t
2414 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
2415 {
2416 uint32_t gtt_size;
2417
2418 if (INTEL_INFO(dev)->gen >= 4 ||
2419 tiling_mode == I915_TILING_NONE)
2420 return size;
2421
2422 /* Previous chips need a power-of-two fence region when tiling */
2423 if (INTEL_INFO(dev)->gen == 3)
2424 gtt_size = 1024*1024;
2425 else
2426 gtt_size = 512*1024;
2427
2428 while (gtt_size < size)
2429 gtt_size <<= 1;
2430
2431 return gtt_size;
2432 }
2433
2434 /**
2435 * i915_gem_get_gtt_alignment - return required GTT alignment for an object
2436 * @obj: object to check
2437 *
2438 * Return the required GTT alignment for an object, taking into account
2439 * potential fence register mapping.
2440 */
2441 uint32_t
2442 i915_gem_get_gtt_alignment(struct drm_device *dev, uint32_t size,
2443 int tiling_mode, bool fenced)
2444 {
2445 /*
2446 * Minimum alignment is 4k (GTT page size), but might be greater
2447 * if a fence register is needed for the object.
2448 */
2449 if (INTEL_INFO(dev)->gen >= 4 || (!fenced && IS_G33(dev)) ||
2450 tiling_mode == I915_TILING_NONE)
2451 return 4096;
2452
2453 /*
2454 * Previous chips need to be aligned to the size of the smallest
2455 * fence register that can contain the object.
2456 */
2457 return i915_gem_get_gtt_size(dev, size, tiling_mode);
2458 }
2459
2460 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
2461 {
2462 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2463 int ret;
2464
2465 if (drm_vma_node_has_offset(&obj->base.vma_node))
2466 return 0;
2467
2468 dev_priv->mm.shrinker_no_lock_stealing = true;
2469
2470 ret = drm_gem_create_mmap_offset(&obj->base);
2471 if (ret != -ENOSPC)
2472 goto out;
2473
2474 /* Badly fragmented mmap space? The only way we can recover
2475 * space is by destroying unwanted objects. We can't randomly release
2476 * mmap_offsets as userspace expects them to be persistent for the
2477 * lifetime of the objects. The closest we can is to release the
2478 * offsets on purgeable objects by truncating it and marking it purged,
2479 * which prevents userspace from ever using that object again.
2480 */
2481 i915_gem_shrink(dev_priv,
2482 obj->base.size >> PAGE_SHIFT,
2483 I915_SHRINK_BOUND |
2484 I915_SHRINK_UNBOUND |
2485 I915_SHRINK_PURGEABLE);
2486 ret = drm_gem_create_mmap_offset(&obj->base);
2487 if (ret != -ENOSPC)
2488 goto out;
2489
2490 i915_gem_shrink_all(dev_priv);
2491 ret = drm_gem_create_mmap_offset(&obj->base);
2492 out:
2493 dev_priv->mm.shrinker_no_lock_stealing = false;
2494
2495 return ret;
2496 }
2497
2498 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
2499 {
2500 drm_gem_free_mmap_offset(&obj->base);
2501 }
2502
2503 int
2504 i915_gem_mmap_gtt(struct drm_file *file,
2505 struct drm_device *dev,
2506 uint32_t handle,
2507 uint64_t *offset)
2508 {
2509 struct drm_gem_object *gobj;
2510 struct drm_i915_gem_object *obj;
2511 int ret;
2512
2513 ret = i915_mutex_lock_interruptible(dev);
2514 if (ret)
2515 return ret;
2516
2517 gobj = drm_gem_object_lookup(dev, file, handle);
2518 if (gobj == NULL) {
2519 ret = -ENOENT;
2520 goto unlock;
2521 }
2522 obj = to_intel_bo(gobj);
2523
2524 if (obj->madv != I915_MADV_WILLNEED) {
2525 DRM_DEBUG("Attempting to mmap a purgeable buffer\n");
2526 ret = -EFAULT;
2527 goto out;
2528 }
2529
2530 ret = i915_gem_object_create_mmap_offset(obj);
2531 if (ret)
2532 goto out;
2533
2534 *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
2535
2536 out:
2537 drm_gem_object_unreference(&obj->base);
2538 unlock:
2539 mutex_unlock(&dev->struct_mutex);
2540 return ret;
2541 }
2542
2543 /**
2544 * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
2545 * @dev: DRM device
2546 * @data: GTT mapping ioctl data
2547 * @file: GEM object info
2548 *
2549 * Simply returns the fake offset to userspace so it can mmap it.
2550 * The mmap call will end up in drm_gem_mmap(), which will set things
2551 * up so we can get faults in the handler above.
2552 *
2553 * The fault handler will take care of binding the object into the GTT
2554 * (since it may have been evicted to make room for something), allocating
2555 * a fence register, and mapping the appropriate aperture address into
2556 * userspace.
2557 */
2558 int
2559 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
2560 struct drm_file *file)
2561 {
2562 struct drm_i915_gem_mmap_gtt *args = data;
2563
2564 return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
2565 }
2566
2567 /* Immediately discard the backing storage */
2568 static void
2569 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
2570 {
2571 i915_gem_object_free_mmap_offset(obj);
2572
2573 #ifdef __NetBSD__
2574 if (obj->base.gemo_shm_uao == NULL)
2575 return;
2576
2577 {
2578 struct uvm_object *const uobj = obj->base.gemo_shm_uao;
2579
2580 if (uobj != NULL) {
2581 /* XXX Calling pgo_put like this is bogus. */
2582 mutex_enter(uobj->vmobjlock);
2583 (*uobj->pgops->pgo_put)(uobj, 0, obj->base.size,
2584 (PGO_ALLPAGES | PGO_FREE));
2585 }
2586 }
2587 #else
2588 if (obj->base.filp == NULL)
2589 return;
2590
2591 /* Our goal here is to return as much of the memory as
2592 * is possible back to the system as we are called from OOM.
2593 * To do this we must instruct the shmfs to drop all of its
2594 * backing pages, *now*.
2595 */
2596 shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
2597 #endif
2598 obj->madv = __I915_MADV_PURGED;
2599 }
2600
2601 /* Try to discard unwanted pages */
2602 static void
2603 i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
2604 {
2605 struct address_space *mapping;
2606
2607 switch (obj->madv) {
2608 case I915_MADV_DONTNEED:
2609 i915_gem_object_truncate(obj);
2610 case __I915_MADV_PURGED:
2611 return;
2612 }
2613
2614 if (obj->base.filp == NULL)
2615 return;
2616
2617 mapping = file_inode(obj->base.filp)->i_mapping,
2618 invalidate_mapping_pages(mapping, 0, (loff_t)-1);
2619 }
2620
2621 #ifdef __NetBSD__
2622 static void
2623 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
2624 {
2625 struct drm_device *const dev = obj->base.dev;
2626 struct vm_page *page;
2627 int ret;
2628
2629 /* XXX Cargo-culted from the Linux code. */
2630 BUG_ON(obj->madv == __I915_MADV_PURGED);
2631
2632 ret = i915_gem_object_set_to_cpu_domain(obj, true);
2633 if (ret) {
2634 WARN_ON(ret != -EIO);
2635 i915_gem_clflush_object(obj, true);
2636 obj->base.read_domains = obj->base.write_domain =
2637 I915_GEM_DOMAIN_CPU;
2638 }
2639
2640 if (i915_gem_object_needs_bit17_swizzle(obj))
2641 i915_gem_object_save_bit_17_swizzle(obj);
2642
2643 if (obj->madv == I915_MADV_DONTNEED)
2644 obj->dirty = 0;
2645
2646 if (obj->dirty) {
2647 TAILQ_FOREACH(page, &obj->igo_pageq, pageq.queue) {
2648 page->flags &= ~PG_CLEAN;
2649 /* XXX mark page accessed */
2650 }
2651 }
2652
2653 bus_dmamap_destroy(dev->dmat, obj->igo_dmamap);
2654 bus_dmamem_unwire_uvm_object(dev->dmat, obj->base.gemo_shm_uao, 0,
2655 obj->base.size, obj->pages, obj->igo_nsegs);
2656
2657 kfree(obj->pages);
2658 }
2659 #else
2660 static void
2661 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
2662 {
2663 struct sg_page_iter sg_iter;
2664 int ret;
2665
2666 BUG_ON(obj->madv == __I915_MADV_PURGED);
2667
2668 ret = i915_gem_object_set_to_cpu_domain(obj, true);
2669 if (ret) {
2670 /* In the event of a disaster, abandon all caches and
2671 * hope for the best.
2672 */
2673 WARN_ON(ret != -EIO);
2674 i915_gem_clflush_object(obj, true);
2675 obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
2676 }
2677
2678 i915_gem_gtt_finish_object(obj);
2679
2680 if (i915_gem_object_needs_bit17_swizzle(obj))
2681 i915_gem_object_save_bit_17_swizzle(obj);
2682
2683 if (obj->madv == I915_MADV_DONTNEED)
2684 obj->dirty = 0;
2685
2686 for_each_sg_page(obj->pages->sgl, &sg_iter, obj->pages->nents, 0) {
2687 struct page *page = sg_page_iter_page(&sg_iter);
2688
2689 if (obj->dirty)
2690 set_page_dirty(page);
2691
2692 if (obj->madv == I915_MADV_WILLNEED)
2693 mark_page_accessed(page);
2694
2695 page_cache_release(page);
2696 }
2697 obj->dirty = 0;
2698
2699 sg_free_table(obj->pages);
2700 kfree(obj->pages);
2701 }
2702 #endif
2703
2704 int
2705 i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
2706 {
2707 const struct drm_i915_gem_object_ops *ops = obj->ops;
2708
2709 if (obj->pages == NULL)
2710 return 0;
2711
2712 if (obj->pages_pin_count)
2713 return -EBUSY;
2714
2715 BUG_ON(i915_gem_obj_bound_any(obj));
2716
2717 /* ->put_pages might need to allocate memory for the bit17 swizzle
2718 * array, hence protect them from being reaped by removing them from gtt
2719 * lists early. */
2720 list_del(&obj->global_list);
2721
2722 ops->put_pages(obj);
2723 obj->pages = NULL;
2724
2725 i915_gem_object_invalidate(obj);
2726
2727 return 0;
2728 }
2729
2730 #ifdef __NetBSD__
2731 static int
2732 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2733 {
2734 struct drm_device *const dev = obj->base.dev;
2735 struct vm_page *page;
2736 int error;
2737
2738 /* XXX Cargo-culted from the Linux code. */
2739 BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2740 BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2741
2742 KASSERT(obj->pages == NULL);
2743 TAILQ_INIT(&obj->igo_pageq);
2744 obj->pages = kcalloc((obj->base.size / PAGE_SIZE),
2745 sizeof(obj->pages[0]), GFP_KERNEL);
2746 if (obj->pages == NULL) {
2747 error = -ENOMEM;
2748 goto fail0;
2749 }
2750
2751 /* XXX errno NetBSD->Linux */
2752 error = -bus_dmamem_wire_uvm_object(dev->dmat, obj->base.gemo_shm_uao,
2753 0, obj->base.size, &obj->igo_pageq, PAGE_SIZE, 0, obj->pages,
2754 (obj->base.size / PAGE_SIZE), &obj->igo_nsegs, BUS_DMA_NOWAIT);
2755 if (error)
2756 /* XXX Try i915_gem_purge, i915_gem_shrink_all. */
2757 goto fail1;
2758 KASSERT(0 < obj->igo_nsegs);
2759 KASSERT(obj->igo_nsegs <= (obj->base.size / PAGE_SIZE));
2760
2761 /*
2762 * Check that the paddrs will fit in 40 bits, or 32 bits on i965.
2763 *
2764 * XXX This is wrong; we ought to pass this constraint to
2765 * bus_dmamem_wire_uvm_object instead.
2766 */
2767 TAILQ_FOREACH(page, &obj->igo_pageq, pageq.queue) {
2768 const uint64_t mask =
2769 (IS_BROADWATER(dev) || IS_CRESTLINE(dev)?
2770 0xffffffffULL : 0xffffffffffULL);
2771 if (VM_PAGE_TO_PHYS(page) & ~mask) {
2772 DRM_ERROR("GEM physical address exceeds %u bits"
2773 ": %"PRIxMAX"\n",
2774 popcount64(mask),
2775 (uintmax_t)VM_PAGE_TO_PHYS(page));
2776 error = -EIO;
2777 goto fail2;
2778 }
2779 }
2780
2781 /* XXX Should create the DMA map when creating the object. */
2782
2783 /* XXX errno NetBSD->Linux */
2784 error = -bus_dmamap_create(dev->dmat, obj->base.size, obj->igo_nsegs,
2785 PAGE_SIZE, 0, BUS_DMA_NOWAIT, &obj->igo_dmamap);
2786 if (error)
2787 goto fail2;
2788
2789 /* XXX Cargo-culted from the Linux code. */
2790 if (i915_gem_object_needs_bit17_swizzle(obj))
2791 i915_gem_object_do_bit_17_swizzle(obj);
2792
2793 /* Success! */
2794 return 0;
2795
2796 fail2: bus_dmamem_unwire_uvm_object(dev->dmat, obj->base.gemo_shm_uao, 0,
2797 obj->base.size, obj->pages, (obj->base.size / PAGE_SIZE));
2798 fail1: kfree(obj->pages);
2799 obj->pages = NULL;
2800 fail0: KASSERT(error);
2801 return error;
2802 }
2803 #else
2804 static int
2805 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
2806 {
2807 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2808 int page_count, i;
2809 struct address_space *mapping;
2810 struct sg_table *st;
2811 struct scatterlist *sg;
2812 struct sg_page_iter sg_iter;
2813 struct page *page;
2814 unsigned long last_pfn = 0; /* suppress gcc warning */
2815 int ret;
2816 gfp_t gfp;
2817
2818 /* Assert that the object is not currently in any GPU domain. As it
2819 * wasn't in the GTT, there shouldn't be any way it could have been in
2820 * a GPU cache
2821 */
2822 BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
2823 BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
2824
2825 st = kmalloc(sizeof(*st), GFP_KERNEL);
2826 if (st == NULL)
2827 return -ENOMEM;
2828
2829 page_count = obj->base.size / PAGE_SIZE;
2830 if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
2831 kfree(st);
2832 return -ENOMEM;
2833 }
2834
2835 /* Get the list of pages out of our struct file. They'll be pinned
2836 * at this point until we release them.
2837 *
2838 * Fail silently without starting the shrinker
2839 */
2840 mapping = file_inode(obj->base.filp)->i_mapping;
2841 gfp = mapping_gfp_constraint(mapping, ~(__GFP_IO | __GFP_RECLAIM));
2842 gfp |= __GFP_NORETRY | __GFP_NOWARN;
2843 sg = st->sgl;
2844 st->nents = 0;
2845 for (i = 0; i < page_count; i++) {
2846 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2847 if (IS_ERR(page)) {
2848 i915_gem_shrink(dev_priv,
2849 page_count,
2850 I915_SHRINK_BOUND |
2851 I915_SHRINK_UNBOUND |
2852 I915_SHRINK_PURGEABLE);
2853 page = shmem_read_mapping_page_gfp(mapping, i, gfp);
2854 }
2855 if (IS_ERR(page)) {
2856 /* We've tried hard to allocate the memory by reaping
2857 * our own buffer, now let the real VM do its job and
2858 * go down in flames if truly OOM.
2859 */
2860 i915_gem_shrink_all(dev_priv);
2861 page = shmem_read_mapping_page(mapping, i);
2862 if (IS_ERR(page)) {
2863 ret = PTR_ERR(page);
2864 goto err_pages;
2865 }
2866 }
2867 #ifdef CONFIG_SWIOTLB
2868 if (swiotlb_nr_tbl()) {
2869 st->nents++;
2870 sg_set_page(sg, page, PAGE_SIZE, 0);
2871 sg = sg_next(sg);
2872 continue;
2873 }
2874 #endif
2875 if (!i || page_to_pfn(page) != last_pfn + 1) {
2876 if (i)
2877 sg = sg_next(sg);
2878 st->nents++;
2879 sg_set_page(sg, page, PAGE_SIZE, 0);
2880 } else {
2881 sg->length += PAGE_SIZE;
2882 }
2883 last_pfn = page_to_pfn(page);
2884
2885 /* Check that the i965g/gm workaround works. */
2886 WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
2887 }
2888 #ifdef CONFIG_SWIOTLB
2889 if (!swiotlb_nr_tbl())
2890 #endif
2891 sg_mark_end(sg);
2892 obj->pages = st;
2893
2894 ret = i915_gem_gtt_prepare_object(obj);
2895 if (ret)
2896 goto err_pages;
2897
2898 if (i915_gem_object_needs_bit17_swizzle(obj))
2899 i915_gem_object_do_bit_17_swizzle(obj);
2900
2901 if (obj->tiling_mode != I915_TILING_NONE &&
2902 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES)
2903 i915_gem_object_pin_pages(obj);
2904
2905 return 0;
2906
2907 err_pages:
2908 sg_mark_end(sg);
2909 for_each_sg_page(st->sgl, &sg_iter, st->nents, 0)
2910 page_cache_release(sg_page_iter_page(&sg_iter));
2911 sg_free_table(st);
2912 kfree(st);
2913
2914 /* shmemfs first checks if there is enough memory to allocate the page
2915 * and reports ENOSPC should there be insufficient, along with the usual
2916 * ENOMEM for a genuine allocation failure.
2917 *
2918 * We use ENOSPC in our driver to mean that we have run out of aperture
2919 * space and so want to translate the error from shmemfs back to our
2920 * usual understanding of ENOMEM.
2921 */
2922 if (ret == -ENOSPC)
2923 ret = -ENOMEM;
2924
2925 return ret;
2926 }
2927 #endif
2928
2929 /* Ensure that the associated pages are gathered from the backing storage
2930 * and pinned into our object. i915_gem_object_get_pages() may be called
2931 * multiple times before they are released by a single call to
2932 * i915_gem_object_put_pages() - once the pages are no longer referenced
2933 * either as a result of memory pressure (reaping pages under the shrinker)
2934 * or as the object is itself released.
2935 */
2936 int
2937 i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
2938 {
2939 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
2940 const struct drm_i915_gem_object_ops *ops = obj->ops;
2941 int ret;
2942
2943 if (obj->pages)
2944 return 0;
2945
2946 if (obj->madv != I915_MADV_WILLNEED) {
2947 DRM_DEBUG("Attempting to obtain a purgeable object\n");
2948 return -EFAULT;
2949 }
2950
2951 BUG_ON(obj->pages_pin_count);
2952
2953 ret = ops->get_pages(obj);
2954 if (ret)
2955 return ret;
2956
2957 list_add_tail(&obj->global_list, &dev_priv->mm.unbound_list);
2958
2959 obj->get_page.sg = obj->pages->sgl;
2960 obj->get_page.last = 0;
2961
2962 return 0;
2963 }
2964
2965 void i915_vma_move_to_active(struct i915_vma *vma,
2966 struct drm_i915_gem_request *req)
2967 {
2968 struct drm_i915_gem_object *obj = vma->obj;
2969 struct intel_engine_cs *ring;
2970
2971 ring = i915_gem_request_get_ring(req);
2972
2973 /* Add a reference if we're newly entering the active list. */
2974 if (obj->active == 0)
2975 drm_gem_object_reference(&obj->base);
2976 obj->active |= intel_ring_flag(ring);
2977
2978 list_move_tail(&obj->ring_list[ring->id], &ring->active_list);
2979 i915_gem_request_assign(&obj->last_read_req[ring->id], req);
2980
2981 list_move_tail(&vma->mm_list, &vma->vm->active_list);
2982 }
2983
2984 static void
2985 i915_gem_object_retire__write(struct drm_i915_gem_object *obj)
2986 {
2987 RQ_BUG_ON(obj->last_write_req == NULL);
2988 RQ_BUG_ON(!(obj->active & intel_ring_flag(obj->last_write_req->ring)));
2989
2990 i915_gem_request_assign(&obj->last_write_req, NULL);
2991 intel_fb_obj_flush(obj, true, ORIGIN_CS);
2992 }
2993
2994 static void
2995 i915_gem_object_retire__read(struct drm_i915_gem_object *obj, int ring)
2996 {
2997 struct i915_vma *vma;
2998
2999 RQ_BUG_ON(obj->last_read_req[ring] == NULL);
3000 RQ_BUG_ON(!(obj->active & (1 << ring)));
3001
3002 list_del_init(&obj->ring_list[ring]);
3003 i915_gem_request_assign(&obj->last_read_req[ring], NULL);
3004
3005 if (obj->last_write_req && obj->last_write_req->ring->id == ring)
3006 i915_gem_object_retire__write(obj);
3007
3008 obj->active &= ~(1 << ring);
3009 if (obj->active)
3010 return;
3011
3012 /* Bump our place on the bound list to keep it roughly in LRU order
3013 * so that we don't steal from recently used but inactive objects
3014 * (unless we are forced to ofc!)
3015 */
3016 list_move_tail(&obj->global_list,
3017 &to_i915(obj->base.dev)->mm.bound_list);
3018
3019 list_for_each_entry(vma, &obj->vma_list, vma_link) {
3020 if (!list_empty(&vma->mm_list))
3021 list_move_tail(&vma->mm_list, &vma->vm->inactive_list);
3022 }
3023
3024 i915_gem_request_assign(&obj->last_fenced_req, NULL);
3025 drm_gem_object_unreference(&obj->base);
3026 }
3027
3028 static int
3029 i915_gem_init_seqno(struct drm_device *dev, u32 seqno)
3030 {
3031 struct drm_i915_private *dev_priv = dev->dev_private;
3032 struct intel_engine_cs *ring;
3033 int ret, i, j;
3034
3035 /* Carefully retire all requests without writing to the rings */
3036 for_each_ring(ring, dev_priv, i) {
3037 ret = intel_ring_idle(ring);
3038 if (ret)
3039 return ret;
3040 }
3041 i915_gem_retire_requests(dev);
3042
3043 /* Finally reset hw state */
3044 for_each_ring(ring, dev_priv, i) {
3045 intel_ring_init_seqno(ring, seqno);
3046
3047 for (j = 0; j < ARRAY_SIZE(ring->semaphore.sync_seqno); j++)
3048 ring->semaphore.sync_seqno[j] = 0;
3049 }
3050
3051 return 0;
3052 }
3053
3054 int i915_gem_set_seqno(struct drm_device *dev, u32 seqno)
3055 {
3056 struct drm_i915_private *dev_priv = dev->dev_private;
3057 int ret;
3058
3059 if (seqno == 0)
3060 return -EINVAL;
3061
3062 /* HWS page needs to be set less than what we
3063 * will inject to ring
3064 */
3065 ret = i915_gem_init_seqno(dev, seqno - 1);
3066 if (ret)
3067 return ret;
3068
3069 /* Carefully set the last_seqno value so that wrap
3070 * detection still works
3071 */
3072 dev_priv->next_seqno = seqno;
3073 dev_priv->last_seqno = seqno - 1;
3074 if (dev_priv->last_seqno == 0)
3075 dev_priv->last_seqno--;
3076
3077 return 0;
3078 }
3079
3080 int
3081 i915_gem_get_seqno(struct drm_device *dev, u32 *seqno)
3082 {
3083 struct drm_i915_private *dev_priv = dev->dev_private;
3084
3085 /* reserve 0 for non-seqno */
3086 if (dev_priv->next_seqno == 0) {
3087 int ret = i915_gem_init_seqno(dev, 0);
3088 if (ret)
3089 return ret;
3090
3091 dev_priv->next_seqno = 1;
3092 }
3093
3094 *seqno = dev_priv->last_seqno = dev_priv->next_seqno++;
3095 return 0;
3096 }
3097
3098 /*
3099 * NB: This function is not allowed to fail. Doing so would mean the the
3100 * request is not being tracked for completion but the work itself is
3101 * going to happen on the hardware. This would be a Bad Thing(tm).
3102 */
3103 void __i915_add_request(struct drm_i915_gem_request *request,
3104 struct drm_i915_gem_object *obj,
3105 bool flush_caches)
3106 {
3107 struct intel_engine_cs *ring;
3108 struct drm_i915_private *dev_priv;
3109 struct intel_ringbuffer *ringbuf;
3110 u32 request_start;
3111 int ret;
3112
3113 if (WARN_ON(request == NULL))
3114 return;
3115
3116 ring = request->ring;
3117 dev_priv = ring->dev->dev_private;
3118 ringbuf = request->ringbuf;
3119
3120 /*
3121 * To ensure that this call will not fail, space for its emissions
3122 * should already have been reserved in the ring buffer. Let the ring
3123 * know that it is time to use that space up.
3124 */
3125 intel_ring_reserved_space_use(ringbuf);
3126
3127 request_start = intel_ring_get_tail(ringbuf);
3128 /*
3129 * Emit any outstanding flushes - execbuf can fail to emit the flush
3130 * after having emitted the batchbuffer command. Hence we need to fix
3131 * things up similar to emitting the lazy request. The difference here
3132 * is that the flush _must_ happen before the next request, no matter
3133 * what.
3134 */
3135 if (flush_caches) {
3136 if (i915.enable_execlists)
3137 ret = logical_ring_flush_all_caches(request);
3138 else
3139 ret = intel_ring_flush_all_caches(request);
3140 /* Not allowed to fail! */
3141 WARN(ret, "*_ring_flush_all_caches failed: %d!\n", ret);
3142 }
3143
3144 /* Record the position of the start of the request so that
3145 * should we detect the updated seqno part-way through the
3146 * GPU processing the request, we never over-estimate the
3147 * position of the head.
3148 */
3149 request->postfix = intel_ring_get_tail(ringbuf);
3150
3151 if (i915.enable_execlists)
3152 ret = ring->emit_request(request);
3153 else {
3154 ret = ring->add_request(request);
3155
3156 request->tail = intel_ring_get_tail(ringbuf);
3157 }
3158 /* Not allowed to fail! */
3159 WARN(ret, "emit|add_request failed: %d!\n", ret);
3160
3161 request->head = request_start;
3162
3163 /* Whilst this request exists, batch_obj will be on the
3164 * active_list, and so will hold the active reference. Only when this
3165 * request is retired will the the batch_obj be moved onto the
3166 * inactive_list and lose its active reference. Hence we do not need
3167 * to explicitly hold another reference here.
3168 */
3169 request->batch_obj = obj;
3170
3171 request->emitted_jiffies = jiffies;
3172 request->previous_seqno = ring->last_submitted_seqno;
3173 ring->last_submitted_seqno = request->seqno;
3174 list_add_tail(&request->list, &ring->request_list);
3175
3176 trace_i915_gem_request_add(request);
3177
3178 i915_queue_hangcheck(ring->dev);
3179
3180 queue_delayed_work(dev_priv->wq,
3181 &dev_priv->mm.retire_work,
3182 round_jiffies_up_relative(HZ));
3183 intel_mark_busy(dev_priv->dev);
3184
3185 /* Sanity check that the reserved size was large enough. */
3186 intel_ring_reserved_space_end(ringbuf);
3187 }
3188
3189 static bool i915_context_is_banned(struct drm_i915_private *dev_priv,
3190 const struct intel_context *ctx)
3191 {
3192 unsigned long elapsed;
3193
3194 elapsed = get_seconds() - ctx->hang_stats.guilty_ts;
3195
3196 if (ctx->hang_stats.banned)
3197 return true;
3198
3199 if (ctx->hang_stats.ban_period_seconds &&
3200 elapsed <= ctx->hang_stats.ban_period_seconds) {
3201 if (!i915_gem_context_is_default(ctx)) {
3202 DRM_DEBUG("context hanging too fast, banning!\n");
3203 return true;
3204 } else if (i915_stop_ring_allow_ban(dev_priv)) {
3205 if (i915_stop_ring_allow_warn(dev_priv))
3206 DRM_ERROR("gpu hanging too fast, banning!\n");
3207 return true;
3208 }
3209 }
3210
3211 return false;
3212 }
3213
3214 static void i915_set_reset_status(struct drm_i915_private *dev_priv,
3215 struct intel_context *ctx,
3216 const bool guilty)
3217 {
3218 struct i915_ctx_hang_stats *hs;
3219
3220 if (WARN_ON(!ctx))
3221 return;
3222
3223 hs = &ctx->hang_stats;
3224
3225 if (guilty) {
3226 hs->banned = i915_context_is_banned(dev_priv, ctx);
3227 hs->batch_active++;
3228 hs->guilty_ts = get_seconds();
3229 } else {
3230 hs->batch_pending++;
3231 }
3232 }
3233
3234 void i915_gem_request_free(struct kref *req_ref)
3235 {
3236 struct drm_i915_gem_request *req = container_of(req_ref,
3237 typeof(*req), ref);
3238 struct intel_context *ctx = req->ctx;
3239
3240 if (req->file_priv)
3241 i915_gem_request_remove_from_client(req);
3242
3243 if (ctx) {
3244 if (i915.enable_execlists) {
3245 if (ctx != req->ring->default_context)
3246 intel_lr_context_unpin(req);
3247 }
3248
3249 i915_gem_context_unreference(ctx);
3250 }
3251
3252 kmem_cache_free(req->i915->requests, req);
3253 }
3254
3255 int i915_gem_request_alloc(struct intel_engine_cs *ring,
3256 struct intel_context *ctx,
3257 struct drm_i915_gem_request **req_out)
3258 {
3259 struct drm_i915_private *dev_priv = to_i915(ring->dev);
3260 struct drm_i915_gem_request *req;
3261 int ret;
3262
3263 if (!req_out)
3264 return -EINVAL;
3265
3266 *req_out = NULL;
3267
3268 req = kmem_cache_zalloc(dev_priv->requests, GFP_KERNEL);
3269 if (req == NULL)
3270 return -ENOMEM;
3271
3272 ret = i915_gem_get_seqno(ring->dev, &req->seqno);
3273 if (ret)
3274 goto err;
3275
3276 kref_init(&req->ref);
3277 req->i915 = dev_priv;
3278 req->ring = ring;
3279 req->ctx = ctx;
3280 i915_gem_context_reference(req->ctx);
3281
3282 if (i915.enable_execlists)
3283 ret = intel_logical_ring_alloc_request_extras(req);
3284 else
3285 ret = intel_ring_alloc_request_extras(req);
3286 if (ret) {
3287 i915_gem_context_unreference(req->ctx);
3288 goto err;
3289 }
3290
3291 /*
3292 * Reserve space in the ring buffer for all the commands required to
3293 * eventually emit this request. This is to guarantee that the
3294 * i915_add_request() call can't fail. Note that the reserve may need
3295 * to be redone if the request is not actually submitted straight
3296 * away, e.g. because a GPU scheduler has deferred it.
3297 */
3298 if (i915.enable_execlists)
3299 ret = intel_logical_ring_reserve_space(req);
3300 else
3301 ret = intel_ring_reserve_space(req);
3302 if (ret) {
3303 /*
3304 * At this point, the request is fully allocated even if not
3305 * fully prepared. Thus it can be cleaned up using the proper
3306 * free code.
3307 */
3308 i915_gem_request_cancel(req);
3309 return ret;
3310 }
3311
3312 *req_out = req;
3313 return 0;
3314
3315 err:
3316 kmem_cache_free(dev_priv->requests, req);
3317 return ret;
3318 }
3319
3320 void i915_gem_request_cancel(struct drm_i915_gem_request *req)
3321 {
3322 intel_ring_reserved_space_cancel(req->ringbuf);
3323
3324 i915_gem_request_unreference(req);
3325 }
3326
3327 struct drm_i915_gem_request *
3328 i915_gem_find_active_request(struct intel_engine_cs *ring)
3329 {
3330 struct drm_i915_gem_request *request;
3331
3332 list_for_each_entry(request, &ring->request_list, list) {
3333 if (i915_gem_request_completed(request, false))
3334 continue;
3335
3336 return request;
3337 }
3338
3339 return NULL;
3340 }
3341
3342 static void i915_gem_reset_ring_status(struct drm_i915_private *dev_priv,
3343 struct intel_engine_cs *ring)
3344 {
3345 struct drm_i915_gem_request *request;
3346 bool ring_hung;
3347
3348 request = i915_gem_find_active_request(ring);
3349
3350 if (request == NULL)
3351 return;
3352
3353 ring_hung = ring->hangcheck.score >= HANGCHECK_SCORE_RING_HUNG;
3354
3355 i915_set_reset_status(dev_priv, request->ctx, ring_hung);
3356
3357 list_for_each_entry_continue(request, &ring->request_list, list)
3358 i915_set_reset_status(dev_priv, request->ctx, false);
3359 }
3360
3361 static void i915_gem_reset_ring_cleanup(struct drm_i915_private *dev_priv,
3362 struct intel_engine_cs *ring)
3363 {
3364 while (!list_empty(&ring->active_list)) {
3365 struct drm_i915_gem_object *obj;
3366
3367 obj = list_first_entry(&ring->active_list,
3368 struct drm_i915_gem_object,
3369 ring_list[ring->id]);
3370
3371 i915_gem_object_retire__read(obj, ring->id);
3372 }
3373
3374 /*
3375 * Clear the execlists queue up before freeing the requests, as those
3376 * are the ones that keep the context and ringbuffer backing objects
3377 * pinned in place.
3378 */
3379 while (!list_empty(&ring->execlist_queue)) {
3380 struct drm_i915_gem_request *submit_req;
3381
3382 submit_req = list_first_entry(&ring->execlist_queue,
3383 struct drm_i915_gem_request,
3384 execlist_link);
3385 list_del(&submit_req->execlist_link);
3386
3387 if (submit_req->ctx != ring->default_context)
3388 intel_lr_context_unpin(submit_req);
3389
3390 i915_gem_request_unreference(submit_req);
3391 }
3392
3393 /*
3394 * We must free the requests after all the corresponding objects have
3395 * been moved off active lists. Which is the same order as the normal
3396 * retire_requests function does. This is important if object hold
3397 * implicit references on things like e.g. ppgtt address spaces through
3398 * the request.
3399 */
3400 while (!list_empty(&ring->request_list)) {
3401 struct drm_i915_gem_request *request;
3402
3403 request = list_first_entry(&ring->request_list,
3404 struct drm_i915_gem_request,
3405 list);
3406
3407 i915_gem_request_retire(request);
3408 }
3409 }
3410
3411 void i915_gem_reset(struct drm_device *dev)
3412 {
3413 struct drm_i915_private *dev_priv = dev->dev_private;
3414 struct intel_engine_cs *ring;
3415 int i;
3416
3417 /*
3418 * Before we free the objects from the requests, we need to inspect
3419 * them for finding the guilty party. As the requests only borrow
3420 * their reference to the objects, the inspection must be done first.
3421 */
3422 for_each_ring(ring, dev_priv, i)
3423 i915_gem_reset_ring_status(dev_priv, ring);
3424
3425 for_each_ring(ring, dev_priv, i)
3426 i915_gem_reset_ring_cleanup(dev_priv, ring);
3427
3428 i915_gem_context_reset(dev);
3429
3430 i915_gem_restore_fences(dev);
3431
3432 WARN_ON(i915_verify_lists(dev));
3433 }
3434
3435 /**
3436 * This function clears the request list as sequence numbers are passed.
3437 */
3438 void
3439 i915_gem_retire_requests_ring(struct intel_engine_cs *ring)
3440 {
3441 WARN_ON(i915_verify_lists(ring->dev));
3442
3443 /* Retire requests first as we use it above for the early return.
3444 * If we retire requests last, we may use a later seqno and so clear
3445 * the requests lists without clearing the active list, leading to
3446 * confusion.
3447 */
3448 while (!list_empty(&ring->request_list)) {
3449 struct drm_i915_gem_request *request;
3450
3451 request = list_first_entry(&ring->request_list,
3452 struct drm_i915_gem_request,
3453 list);
3454
3455 if (!i915_gem_request_completed(request, true))
3456 break;
3457
3458 i915_gem_request_retire(request);
3459 }
3460
3461 /* Move any buffers on the active list that are no longer referenced
3462 * by the ringbuffer to the flushing/inactive lists as appropriate,
3463 * before we free the context associated with the requests.
3464 */
3465 while (!list_empty(&ring->active_list)) {
3466 struct drm_i915_gem_object *obj;
3467
3468 obj = list_first_entry(&ring->active_list,
3469 struct drm_i915_gem_object,
3470 ring_list[ring->id]);
3471
3472 if (!list_empty(&obj->last_read_req[ring->id]->list))
3473 break;
3474
3475 i915_gem_object_retire__read(obj, ring->id);
3476 }
3477
3478 if (unlikely(ring->trace_irq_req &&
3479 i915_gem_request_completed(ring->trace_irq_req, true))) {
3480 ring->irq_put(ring);
3481 i915_gem_request_assign(&ring->trace_irq_req, NULL);
3482 }
3483
3484 WARN_ON(i915_verify_lists(ring->dev));
3485 }
3486
3487 bool
3488 i915_gem_retire_requests(struct drm_device *dev)
3489 {
3490 struct drm_i915_private *dev_priv = dev->dev_private;
3491 struct intel_engine_cs *ring;
3492 bool idle = true;
3493 int i;
3494
3495 for_each_ring(ring, dev_priv, i) {
3496 i915_gem_retire_requests_ring(ring);
3497 idle &= list_empty(&ring->request_list);
3498 if (i915.enable_execlists) {
3499 unsigned long flags;
3500
3501 spin_lock_irqsave(&ring->execlist_lock, flags);
3502 idle &= list_empty(&ring->execlist_queue);
3503 spin_unlock_irqrestore(&ring->execlist_lock, flags);
3504
3505 intel_execlists_retire_requests(ring);
3506 }
3507 }
3508
3509 if (idle)
3510 mod_delayed_work(dev_priv->wq,
3511 &dev_priv->mm.idle_work,
3512 msecs_to_jiffies(100));
3513
3514 return idle;
3515 }
3516
3517 static void
3518 i915_gem_retire_work_handler(struct work_struct *work)
3519 {
3520 struct drm_i915_private *dev_priv =
3521 container_of(work, typeof(*dev_priv), mm.retire_work.work);
3522 struct drm_device *dev = dev_priv->dev;
3523 bool idle;
3524
3525 /* Come back later if the device is busy... */
3526 idle = false;
3527 if (mutex_trylock(&dev->struct_mutex)) {
3528 idle = i915_gem_retire_requests(dev);
3529 mutex_unlock(&dev->struct_mutex);
3530 }
3531 if (!idle)
3532 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
3533 round_jiffies_up_relative(HZ));
3534 }
3535
3536 static void
3537 i915_gem_idle_work_handler(struct work_struct *work)
3538 {
3539 struct drm_i915_private *dev_priv =
3540 container_of(work, typeof(*dev_priv), mm.idle_work.work);
3541 struct drm_device *dev = dev_priv->dev;
3542 struct intel_engine_cs *ring;
3543 int i;
3544
3545 for_each_ring(ring, dev_priv, i)
3546 if (!list_empty(&ring->request_list))
3547 return;
3548
3549 intel_mark_idle(dev);
3550
3551 if (mutex_trylock(&dev->struct_mutex)) {
3552 struct intel_engine_cs *ring;
3553 int i;
3554
3555 for_each_ring(ring, dev_priv, i)
3556 i915_gem_batch_pool_fini(&ring->batch_pool);
3557
3558 mutex_unlock(&dev->struct_mutex);
3559 }
3560 }
3561
3562 /**
3563 * Ensures that an object will eventually get non-busy by flushing any required
3564 * write domains, emitting any outstanding lazy request and retiring and
3565 * completed requests.
3566 */
3567 static int
3568 i915_gem_object_flush_active(struct drm_i915_gem_object *obj)
3569 {
3570 int i;
3571
3572 if (!obj->active)
3573 return 0;
3574
3575 for (i = 0; i < I915_NUM_RINGS; i++) {
3576 struct drm_i915_gem_request *req;
3577
3578 req = obj->last_read_req[i];
3579 if (req == NULL)
3580 continue;
3581
3582 if (list_empty(&req->list))
3583 goto retire;
3584
3585 if (i915_gem_request_completed(req, true)) {
3586 __i915_gem_request_retire__upto(req);
3587 retire:
3588 i915_gem_object_retire__read(obj, i);
3589 }
3590 }
3591
3592 return 0;
3593 }
3594
3595 /**
3596 * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
3597 * @DRM_IOCTL_ARGS: standard ioctl arguments
3598 *
3599 * Returns 0 if successful, else an error is returned with the remaining time in
3600 * the timeout parameter.
3601 * -ETIME: object is still busy after timeout
3602 * -ERESTARTSYS: signal interrupted the wait
3603 * -ENONENT: object doesn't exist
3604 * Also possible, but rare:
3605 * -EAGAIN: GPU wedged
3606 * -ENOMEM: damn
3607 * -ENODEV: Internal IRQ fail
3608 * -E?: The add request failed
3609 *
3610 * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
3611 * non-zero timeout parameter the wait ioctl will wait for the given number of
3612 * nanoseconds on an object becoming unbusy. Since the wait itself does so
3613 * without holding struct_mutex the object may become re-busied before this
3614 * function completes. A similar but shorter * race condition exists in the busy
3615 * ioctl
3616 */
3617 int
3618 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
3619 {
3620 struct drm_i915_private *dev_priv = dev->dev_private;
3621 struct drm_i915_gem_wait *args = data;
3622 struct drm_gem_object *gobj;
3623 struct drm_i915_gem_object *obj;
3624 struct drm_i915_gem_request *req[I915_NUM_RINGS];
3625 unsigned reset_counter;
3626 int i, n = 0;
3627 int ret;
3628
3629 if (args->flags != 0)
3630 return -EINVAL;
3631
3632 ret = i915_mutex_lock_interruptible(dev);
3633 if (ret)
3634 return ret;
3635
3636 gobj = drm_gem_object_lookup(dev, file, args->bo_handle);
3637 if (gobj == NULL) {
3638 mutex_unlock(&dev->struct_mutex);
3639 return -ENOENT;
3640 }
3641 obj = to_intel_bo(gobj);
3642
3643 /* Need to make sure the object gets inactive eventually. */
3644 ret = i915_gem_object_flush_active(obj);
3645 if (ret)
3646 goto out;
3647
3648 if (!obj->active)
3649 goto out;
3650
3651 /* Do this after OLR check to make sure we make forward progress polling
3652 * on this IOCTL with a timeout == 0 (like busy ioctl)
3653 */
3654 if (args->timeout_ns == 0) {
3655 ret = -ETIME;
3656 goto out;
3657 }
3658
3659 drm_gem_object_unreference(&obj->base);
3660 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
3661
3662 for (i = 0; i < I915_NUM_RINGS; i++) {
3663 if (obj->last_read_req[i] == NULL)
3664 continue;
3665
3666 req[n++] = i915_gem_request_reference(obj->last_read_req[i]);
3667 }
3668
3669 mutex_unlock(&dev->struct_mutex);
3670
3671 for (i = 0; i < n; i++) {
3672 if (ret == 0)
3673 ret = __i915_wait_request(req[i], reset_counter, true,
3674 args->timeout_ns > 0 ? &args->timeout_ns : NULL,
3675 file->driver_priv);
3676 i915_gem_request_unreference__unlocked(req[i]);
3677 }
3678 return ret;
3679
3680 out:
3681 drm_gem_object_unreference(&obj->base);
3682 mutex_unlock(&dev->struct_mutex);
3683 return ret;
3684 }
3685
3686 static int
3687 __i915_gem_object_sync(struct drm_i915_gem_object *obj,
3688 struct intel_engine_cs *to,
3689 struct drm_i915_gem_request *from_req,
3690 struct drm_i915_gem_request **to_req)
3691 {
3692 struct intel_engine_cs *from;
3693 int ret;
3694
3695 from = i915_gem_request_get_ring(from_req);
3696 if (to == from)
3697 return 0;
3698
3699 if (i915_gem_request_completed(from_req, true))
3700 return 0;
3701
3702 if (!i915_semaphore_is_enabled(obj->base.dev)) {
3703 struct drm_i915_private *i915 = to_i915(obj->base.dev);
3704 ret = __i915_wait_request(from_req,
3705 atomic_read(&i915->gpu_error.reset_counter),
3706 i915->mm.interruptible,
3707 NULL,
3708 &i915->rps.semaphores);
3709 if (ret)
3710 return ret;
3711
3712 i915_gem_object_retire_request(obj, from_req);
3713 } else {
3714 int idx = intel_ring_sync_index(from, to);
3715 u32 seqno = i915_gem_request_get_seqno(from_req);
3716
3717 WARN_ON(!to_req);
3718
3719 if (seqno <= from->semaphore.sync_seqno[idx])
3720 return 0;
3721
3722 if (*to_req == NULL) {
3723 ret = i915_gem_request_alloc(to, to->default_context, to_req);
3724 if (ret)
3725 return ret;
3726 }
3727
3728 trace_i915_gem_ring_sync_to(*to_req, from, from_req);
3729 ret = to->semaphore.sync_to(*to_req, from, seqno);
3730 if (ret)
3731 return ret;
3732
3733 /* We use last_read_req because sync_to()
3734 * might have just caused seqno wrap under
3735 * the radar.
3736 */
3737 from->semaphore.sync_seqno[idx] =
3738 i915_gem_request_get_seqno(obj->last_read_req[from->id]);
3739 }
3740
3741 return 0;
3742 }
3743
3744 /**
3745 * i915_gem_object_sync - sync an object to a ring.
3746 *
3747 * @obj: object which may be in use on another ring.
3748 * @to: ring we wish to use the object on. May be NULL.
3749 * @to_req: request we wish to use the object for. See below.
3750 * This will be allocated and returned if a request is
3751 * required but not passed in.
3752 *
3753 * This code is meant to abstract object synchronization with the GPU.
3754 * Calling with NULL implies synchronizing the object with the CPU
3755 * rather than a particular GPU ring. Conceptually we serialise writes
3756 * between engines inside the GPU. We only allow one engine to write
3757 * into a buffer at any time, but multiple readers. To ensure each has
3758 * a coherent view of memory, we must:
3759 *
3760 * - If there is an outstanding write request to the object, the new
3761 * request must wait for it to complete (either CPU or in hw, requests
3762 * on the same ring will be naturally ordered).
3763 *
3764 * - If we are a write request (pending_write_domain is set), the new
3765 * request must wait for outstanding read requests to complete.
3766 *
3767 * For CPU synchronisation (NULL to) no request is required. For syncing with
3768 * rings to_req must be non-NULL. However, a request does not have to be
3769 * pre-allocated. If *to_req is NULL and sync commands will be emitted then a
3770 * request will be allocated automatically and returned through *to_req. Note
3771 * that it is not guaranteed that commands will be emitted (because the system
3772 * might already be idle). Hence there is no need to create a request that
3773 * might never have any work submitted. Note further that if a request is
3774 * returned in *to_req, it is the responsibility of the caller to submit
3775 * that request (after potentially adding more work to it).
3776 *
3777 * Returns 0 if successful, else propagates up the lower layer error.
3778 */
3779 int
3780 i915_gem_object_sync(struct drm_i915_gem_object *obj,
3781 struct intel_engine_cs *to,
3782 struct drm_i915_gem_request **to_req)
3783 {
3784 const bool readonly = obj->base.pending_write_domain == 0;
3785 struct drm_i915_gem_request *req[I915_NUM_RINGS];
3786 int ret, i, n;
3787
3788 if (!obj->active)
3789 return 0;
3790
3791 if (to == NULL)
3792 return i915_gem_object_wait_rendering(obj, readonly);
3793
3794 n = 0;
3795 if (readonly) {
3796 if (obj->last_write_req)
3797 req[n++] = obj->last_write_req;
3798 } else {
3799 for (i = 0; i < I915_NUM_RINGS; i++)
3800 if (obj->last_read_req[i])
3801 req[n++] = obj->last_read_req[i];
3802 }
3803 for (i = 0; i < n; i++) {
3804 ret = __i915_gem_object_sync(obj, to, req[i], to_req);
3805 if (ret)
3806 return ret;
3807 }
3808
3809 return 0;
3810 }
3811
3812 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
3813 {
3814 u32 old_write_domain, old_read_domains;
3815
3816 /* Force a pagefault for domain tracking on next user access */
3817 i915_gem_release_mmap(obj);
3818
3819 if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
3820 return;
3821
3822 /* Wait for any direct GTT access to complete */
3823 mb();
3824
3825 old_read_domains = obj->base.read_domains;
3826 old_write_domain = obj->base.write_domain;
3827
3828 obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
3829 obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
3830
3831 trace_i915_gem_object_change_domain(obj,
3832 old_read_domains,
3833 old_write_domain);
3834 }
3835
3836 static int __i915_vma_unbind(struct i915_vma *vma, bool wait)
3837 {
3838 struct drm_i915_gem_object *obj = vma->obj;
3839 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
3840 int ret;
3841
3842 if (list_empty(&vma->vma_link))
3843 return 0;
3844
3845 if (!drm_mm_node_allocated(&vma->node)) {
3846 i915_gem_vma_destroy(vma);
3847 return 0;
3848 }
3849
3850 if (vma->pin_count)
3851 return -EBUSY;
3852
3853 BUG_ON(obj->pages == NULL);
3854
3855 if (wait) {
3856 ret = i915_gem_object_wait_rendering(obj, false);
3857 if (ret)
3858 return ret;
3859 }
3860
3861 if (i915_is_ggtt(vma->vm) &&
3862 vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL) {
3863 i915_gem_object_finish_gtt(obj);
3864
3865 /* release the fence reg _after_ flushing */
3866 ret = i915_gem_object_put_fence(obj);
3867 if (ret)
3868 return ret;
3869 }
3870
3871 trace_i915_vma_unbind(vma);
3872
3873 vma->vm->unbind_vma(vma);
3874 vma->bound = 0;
3875
3876 list_del_init(&vma->mm_list);
3877 if (i915_is_ggtt(vma->vm)) {
3878 if (vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL) {
3879 obj->map_and_fenceable = false;
3880 } else if (vma->ggtt_view.pages) {
3881 sg_free_table(vma->ggtt_view.pages);
3882 kfree(vma->ggtt_view.pages);
3883 }
3884 vma->ggtt_view.pages = NULL;
3885 }
3886
3887 drm_mm_remove_node(&vma->node);
3888 i915_gem_vma_destroy(vma);
3889
3890 /* Since the unbound list is global, only move to that list if
3891 * no more VMAs exist. */
3892 if (list_empty(&obj->vma_list))
3893 list_move_tail(&obj->global_list, &dev_priv->mm.unbound_list);
3894
3895 /* And finally now the object is completely decoupled from this vma,
3896 * we can drop its hold on the backing storage and allow it to be
3897 * reaped by the shrinker.
3898 */
3899 i915_gem_object_unpin_pages(obj);
3900
3901 return 0;
3902 }
3903
3904 int i915_vma_unbind(struct i915_vma *vma)
3905 {
3906 return __i915_vma_unbind(vma, true);
3907 }
3908
3909 int __i915_vma_unbind_no_wait(struct i915_vma *vma)
3910 {
3911 return __i915_vma_unbind(vma, false);
3912 }
3913
3914 int i915_gpu_idle(struct drm_device *dev)
3915 {
3916 struct drm_i915_private *dev_priv = dev->dev_private;
3917 struct intel_engine_cs *ring;
3918 int ret, i;
3919
3920 /* Flush everything onto the inactive list. */
3921 for_each_ring(ring, dev_priv, i) {
3922 if (!i915.enable_execlists) {
3923 struct drm_i915_gem_request *req;
3924
3925 ret = i915_gem_request_alloc(ring, ring->default_context, &req);
3926 if (ret)
3927 return ret;
3928
3929 ret = i915_switch_context(req);
3930 if (ret) {
3931 i915_gem_request_cancel(req);
3932 return ret;
3933 }
3934
3935 i915_add_request_no_flush(req);
3936 }
3937
3938 ret = intel_ring_idle(ring);
3939 if (ret)
3940 return ret;
3941 }
3942
3943 WARN_ON(i915_verify_lists(dev));
3944 return 0;
3945 }
3946
3947 static bool i915_gem_valid_gtt_space(struct i915_vma *vma,
3948 unsigned long cache_level)
3949 {
3950 struct drm_mm_node *gtt_space = &vma->node;
3951 struct drm_mm_node *other;
3952
3953 /*
3954 * On some machines we have to be careful when putting differing types
3955 * of snoopable memory together to avoid the prefetcher crossing memory
3956 * domains and dying. During vm initialisation, we decide whether or not
3957 * these constraints apply and set the drm_mm.color_adjust
3958 * appropriately.
3959 */
3960 if (vma->vm->mm.color_adjust == NULL)
3961 return true;
3962
3963 if (!drm_mm_node_allocated(gtt_space))
3964 return true;
3965
3966 if (list_empty(>t_space->node_list))
3967 return true;
3968
3969 other = list_entry(gtt_space->node_list.prev, struct drm_mm_node, node_list);
3970 if (other->allocated && !other->hole_follows && other->color != cache_level)
3971 return false;
3972
3973 other = list_entry(gtt_space->node_list.next, struct drm_mm_node, node_list);
3974 if (other->allocated && !gtt_space->hole_follows && other->color != cache_level)
3975 return false;
3976
3977 return true;
3978 }
3979
3980 /**
3981 * Finds free space in the GTT aperture and binds the object or a view of it
3982 * there.
3983 */
3984 static struct i915_vma *
3985 i915_gem_object_bind_to_vm(struct drm_i915_gem_object *obj,
3986 struct i915_address_space *vm,
3987 const struct i915_ggtt_view *ggtt_view,
3988 unsigned alignment,
3989 uint64_t flags)
3990 {
3991 struct drm_device *dev = obj->base.dev;
3992 struct drm_i915_private *dev_priv = dev->dev_private;
3993 u32 fence_alignment, unfenced_alignment;
3994 u32 search_flag, alloc_flag;
3995 u64 start, end;
3996 u64 size, fence_size;
3997 struct i915_vma *vma;
3998 int ret;
3999
4000 if (i915_is_ggtt(vm)) {
4001 u32 view_size;
4002
4003 if (WARN_ON(!ggtt_view))
4004 return ERR_PTR(-EINVAL);
4005
4006 view_size = i915_ggtt_view_size(obj, ggtt_view);
4007
4008 fence_size = i915_gem_get_gtt_size(dev,
4009 view_size,
4010 obj->tiling_mode);
4011 fence_alignment = i915_gem_get_gtt_alignment(dev,
4012 view_size,
4013 obj->tiling_mode,
4014 true);
4015 unfenced_alignment = i915_gem_get_gtt_alignment(dev,
4016 view_size,
4017 obj->tiling_mode,
4018 false);
4019 size = flags & PIN_MAPPABLE ? fence_size : view_size;
4020 } else {
4021 fence_size = i915_gem_get_gtt_size(dev,
4022 obj->base.size,
4023 obj->tiling_mode);
4024 fence_alignment = i915_gem_get_gtt_alignment(dev,
4025 obj->base.size,
4026 obj->tiling_mode,
4027 true);
4028 unfenced_alignment =
4029 i915_gem_get_gtt_alignment(dev,
4030 obj->base.size,
4031 obj->tiling_mode,
4032 false);
4033 size = flags & PIN_MAPPABLE ? fence_size : obj->base.size;
4034 }
4035
4036 start = flags & PIN_OFFSET_BIAS ? flags & PIN_OFFSET_MASK : 0;
4037 end = vm->total;
4038 if (flags & PIN_MAPPABLE)
4039 end = min_t(u64, end, dev_priv->gtt.mappable_end);
4040 if (flags & PIN_ZONE_4G)
4041 end = min_t(u64, end, (1ULL << 32));
4042
4043 if (alignment == 0)
4044 alignment = flags & PIN_MAPPABLE ? fence_alignment :
4045 unfenced_alignment;
4046 if (flags & PIN_MAPPABLE && alignment & (fence_alignment - 1)) {
4047 DRM_DEBUG("Invalid object (view type=%u) alignment requested %u\n",
4048 ggtt_view ? ggtt_view->type : 0,
4049 alignment);
4050 return ERR_PTR(-EINVAL);
4051 }
4052
4053 /* If binding the object/GGTT view requires more space than the entire
4054 * aperture has, reject it early before evicting everything in a vain
4055 * attempt to find space.
4056 */
4057 if (size > end) {
4058 DRM_DEBUG("Attempting to bind an object (view type=%u) larger than the aperture: size=%llu > %s aperture=%llu\n",
4059 ggtt_view ? ggtt_view->type : 0,
4060 size,
4061 flags & PIN_MAPPABLE ? "mappable" : "total",
4062 end);
4063 return ERR_PTR(-E2BIG);
4064 }
4065
4066 ret = i915_gem_object_get_pages(obj);
4067 if (ret)
4068 return ERR_PTR(ret);
4069
4070 i915_gem_object_pin_pages(obj);
4071
4072 vma = ggtt_view ? i915_gem_obj_lookup_or_create_ggtt_vma(obj, ggtt_view) :
4073 i915_gem_obj_lookup_or_create_vma(obj, vm);
4074
4075 if (IS_ERR(vma))
4076 goto err_unpin;
4077
4078 if (flags & PIN_HIGH) {
4079 search_flag = DRM_MM_SEARCH_BELOW;
4080 alloc_flag = DRM_MM_CREATE_TOP;
4081 } else {
4082 search_flag = DRM_MM_SEARCH_DEFAULT;
4083 alloc_flag = DRM_MM_CREATE_DEFAULT;
4084 }
4085
4086 search_free:
4087 ret = drm_mm_insert_node_in_range_generic(&vm->mm, &vma->node,
4088 size, alignment,
4089 obj->cache_level,
4090 start, end,
4091 search_flag,
4092 alloc_flag);
4093 if (ret) {
4094 ret = i915_gem_evict_something(dev, vm, size, alignment,
4095 obj->cache_level,
4096 start, end,
4097 flags);
4098 if (ret == 0)
4099 goto search_free;
4100
4101 goto err_free_vma;
4102 }
4103 if (WARN_ON(!i915_gem_valid_gtt_space(vma, obj->cache_level))) {
4104 ret = -EINVAL;
4105 goto err_remove_node;
4106 }
4107
4108 trace_i915_vma_bind(vma, flags);
4109 ret = i915_vma_bind(vma, obj->cache_level, flags);
4110 if (ret)
4111 goto err_remove_node;
4112
4113 list_move_tail(&obj->global_list, &dev_priv->mm.bound_list);
4114 list_add_tail(&vma->mm_list, &vm->inactive_list);
4115
4116 return vma;
4117
4118 err_remove_node:
4119 drm_mm_remove_node(&vma->node);
4120 err_free_vma:
4121 i915_gem_vma_destroy(vma);
4122 vma = ERR_PTR(ret);
4123 err_unpin:
4124 i915_gem_object_unpin_pages(obj);
4125 return vma;
4126 }
4127
4128 bool
4129 i915_gem_clflush_object(struct drm_i915_gem_object *obj,
4130 bool force)
4131 {
4132 /* If we don't have a page list set up, then we're not pinned
4133 * to GPU, and we can ignore the cache flush because it'll happen
4134 * again at bind time.
4135 */
4136 if (obj->pages == NULL)
4137 return false;
4138
4139 /*
4140 * Stolen memory is always coherent with the GPU as it is explicitly
4141 * marked as wc by the system, or the system is cache-coherent.
4142 */
4143 if (obj->stolen || obj->phys_handle)
4144 return false;
4145
4146 /* If the GPU is snooping the contents of the CPU cache,
4147 * we do not need to manually clear the CPU cache lines. However,
4148 * the caches are only snooped when the render cache is
4149 * flushed/invalidated. As we always have to emit invalidations
4150 * and flushes when moving into and out of the RENDER domain, correct
4151 * snooping behaviour occurs naturally as the result of our domain
4152 * tracking.
4153 */
4154 if (!force && cpu_cache_is_coherent(obj->base.dev, obj->cache_level)) {
4155 obj->cache_dirty = true;
4156 return false;
4157 }
4158
4159 trace_i915_gem_object_clflush(obj);
4160 #ifdef __NetBSD__
4161 drm_clflush_pglist(&obj->igo_pageq);
4162 #else
4163 drm_clflush_sg(obj->pages);
4164 #endif
4165 obj->cache_dirty = false;
4166
4167 return true;
4168 }
4169
4170 /** Flushes the GTT write domain for the object if it's dirty. */
4171 static void
4172 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
4173 {
4174 uint32_t old_write_domain;
4175
4176 if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
4177 return;
4178
4179 /* No actual flushing is required for the GTT write domain. Writes
4180 * to it immediately go to main memory as far as we know, so there's
4181 * no chipset flush. It also doesn't land in render cache.
4182 *
4183 * However, we do have to enforce the order so that all writes through
4184 * the GTT land before any writes to the device, such as updates to
4185 * the GATT itself.
4186 */
4187 wmb();
4188
4189 old_write_domain = obj->base.write_domain;
4190 obj->base.write_domain = 0;
4191
4192 intel_fb_obj_flush(obj, false, ORIGIN_GTT);
4193
4194 trace_i915_gem_object_change_domain(obj,
4195 obj->base.read_domains,
4196 old_write_domain);
4197 }
4198
4199 /** Flushes the CPU write domain for the object if it's dirty. */
4200 static void
4201 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
4202 {
4203 uint32_t old_write_domain;
4204
4205 if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
4206 return;
4207
4208 if (i915_gem_clflush_object(obj, obj->pin_display))
4209 i915_gem_chipset_flush(obj->base.dev);
4210
4211 old_write_domain = obj->base.write_domain;
4212 obj->base.write_domain = 0;
4213
4214 intel_fb_obj_flush(obj, false, ORIGIN_CPU);
4215
4216 trace_i915_gem_object_change_domain(obj,
4217 obj->base.read_domains,
4218 old_write_domain);
4219 }
4220
4221 /**
4222 * Moves a single object to the GTT read, and possibly write domain.
4223 *
4224 * This function returns when the move is complete, including waiting on
4225 * flushes to occur.
4226 */
4227 int
4228 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
4229 {
4230 uint32_t old_write_domain, old_read_domains;
4231 struct i915_vma *vma;
4232 int ret;
4233
4234 if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
4235 return 0;
4236
4237 ret = i915_gem_object_wait_rendering(obj, !write);
4238 if (ret)
4239 return ret;
4240
4241 /* Flush and acquire obj->pages so that we are coherent through
4242 * direct access in memory with previous cached writes through
4243 * shmemfs and that our cache domain tracking remains valid.
4244 * For example, if the obj->filp was moved to swap without us
4245 * being notified and releasing the pages, we would mistakenly
4246 * continue to assume that the obj remained out of the CPU cached
4247 * domain.
4248 */
4249 ret = i915_gem_object_get_pages(obj);
4250 if (ret)
4251 return ret;
4252
4253 i915_gem_object_flush_cpu_write_domain(obj);
4254
4255 /* Serialise direct access to this object with the barriers for
4256 * coherent writes from the GPU, by effectively invalidating the
4257 * GTT domain upon first access.
4258 */
4259 if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
4260 mb();
4261
4262 old_write_domain = obj->base.write_domain;
4263 old_read_domains = obj->base.read_domains;
4264
4265 /* It should now be out of any other write domains, and we can update
4266 * the domain values for our changes.
4267 */
4268 BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
4269 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
4270 if (write) {
4271 obj->base.read_domains = I915_GEM_DOMAIN_GTT;
4272 obj->base.write_domain = I915_GEM_DOMAIN_GTT;
4273 obj->dirty = 1;
4274 }
4275
4276 trace_i915_gem_object_change_domain(obj,
4277 old_read_domains,
4278 old_write_domain);
4279
4280 /* And bump the LRU for this access */
4281 vma = i915_gem_obj_to_ggtt(obj);
4282 if (vma && drm_mm_node_allocated(&vma->node) && !obj->active)
4283 list_move_tail(&vma->mm_list,
4284 &to_i915(obj->base.dev)->gtt.base.inactive_list);
4285
4286 return 0;
4287 }
4288
4289 /**
4290 * Changes the cache-level of an object across all VMA.
4291 *
4292 * After this function returns, the object will be in the new cache-level
4293 * across all GTT and the contents of the backing storage will be coherent,
4294 * with respect to the new cache-level. In order to keep the backing storage
4295 * coherent for all users, we only allow a single cache level to be set
4296 * globally on the object and prevent it from being changed whilst the
4297 * hardware is reading from the object. That is if the object is currently
4298 * on the scanout it will be set to uncached (or equivalent display
4299 * cache coherency) and all non-MOCS GPU access will also be uncached so
4300 * that all direct access to the scanout remains coherent.
4301 */
4302 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
4303 enum i915_cache_level cache_level)
4304 {
4305 struct drm_device *dev = obj->base.dev;
4306 struct i915_vma *vma, *next;
4307 bool bound = false;
4308 int ret = 0;
4309
4310 if (obj->cache_level == cache_level)
4311 goto out;
4312
4313 /* Inspect the list of currently bound VMA and unbind any that would
4314 * be invalid given the new cache-level. This is principally to
4315 * catch the issue of the CS prefetch crossing page boundaries and
4316 * reading an invalid PTE on older architectures.
4317 */
4318 list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link) {
4319 if (!drm_mm_node_allocated(&vma->node))
4320 continue;
4321
4322 if (vma->pin_count) {
4323 DRM_DEBUG("can not change the cache level of pinned objects\n");
4324 return -EBUSY;
4325 }
4326
4327 if (!i915_gem_valid_gtt_space(vma, cache_level)) {
4328 ret = i915_vma_unbind(vma);
4329 if (ret)
4330 return ret;
4331 } else
4332 bound = true;
4333 }
4334
4335 /* We can reuse the existing drm_mm nodes but need to change the
4336 * cache-level on the PTE. We could simply unbind them all and
4337 * rebind with the correct cache-level on next use. However since
4338 * we already have a valid slot, dma mapping, pages etc, we may as
4339 * rewrite the PTE in the belief that doing so tramples upon less
4340 * state and so involves less work.
4341 */
4342 if (bound) {
4343 /* Before we change the PTE, the GPU must not be accessing it.
4344 * If we wait upon the object, we know that all the bound
4345 * VMA are no longer active.
4346 */
4347 ret = i915_gem_object_wait_rendering(obj, false);
4348 if (ret)
4349 return ret;
4350
4351 if (!HAS_LLC(dev) && cache_level != I915_CACHE_NONE) {
4352 /* Access to snoopable pages through the GTT is
4353 * incoherent and on some machines causes a hard
4354 * lockup. Relinquish the CPU mmaping to force
4355 * userspace to refault in the pages and we can
4356 * then double check if the GTT mapping is still
4357 * valid for that pointer access.
4358 */
4359 i915_gem_release_mmap(obj);
4360
4361 /* As we no longer need a fence for GTT access,
4362 * we can relinquish it now (and so prevent having
4363 * to steal a fence from someone else on the next
4364 * fence request). Note GPU activity would have
4365 * dropped the fence as all snoopable access is
4366 * supposed to be linear.
4367 */
4368 ret = i915_gem_object_put_fence(obj);
4369 if (ret)
4370 return ret;
4371 } else {
4372 /* We either have incoherent backing store and
4373 * so no GTT access or the architecture is fully
4374 * coherent. In such cases, existing GTT mmaps
4375 * ignore the cache bit in the PTE and we can
4376 * rewrite it without confusing the GPU or having
4377 * to force userspace to fault back in its mmaps.
4378 */
4379 }
4380
4381 list_for_each_entry(vma, &obj->vma_list, vma_link) {
4382 if (!drm_mm_node_allocated(&vma->node))
4383 continue;
4384
4385 ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
4386 if (ret)
4387 return ret;
4388 }
4389 }
4390
4391 list_for_each_entry(vma, &obj->vma_list, vma_link)
4392 vma->node.color = cache_level;
4393 obj->cache_level = cache_level;
4394
4395 out:
4396 /* Flush the dirty CPU caches to the backing storage so that the
4397 * object is now coherent at its new cache level (with respect
4398 * to the access domain).
4399 */
4400 if (obj->cache_dirty &&
4401 obj->base.write_domain != I915_GEM_DOMAIN_CPU &&
4402 cpu_write_needs_clflush(obj)) {
4403 if (i915_gem_clflush_object(obj, true))
4404 i915_gem_chipset_flush(obj->base.dev);
4405 }
4406
4407 return 0;
4408 }
4409
4410 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
4411 struct drm_file *file)
4412 {
4413 struct drm_i915_gem_caching *args = data;
4414 struct drm_gem_object *gobj;
4415 struct drm_i915_gem_object *obj;
4416
4417 gobj = drm_gem_object_lookup(dev, file, args->handle);
4418 if (gobj == NULL)
4419 return -ENOENT;
4420 obj = to_intel_bo(gobj);
4421
4422 switch (obj->cache_level) {
4423 case I915_CACHE_LLC:
4424 case I915_CACHE_L3_LLC:
4425 args->caching = I915_CACHING_CACHED;
4426 break;
4427
4428 case I915_CACHE_WT:
4429 args->caching = I915_CACHING_DISPLAY;
4430 break;
4431
4432 default:
4433 args->caching = I915_CACHING_NONE;
4434 break;
4435 }
4436
4437 drm_gem_object_unreference_unlocked(&obj->base);
4438 return 0;
4439 }
4440
4441 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
4442 struct drm_file *file)
4443 {
4444 struct drm_i915_private *dev_priv = dev->dev_private;
4445 struct drm_i915_gem_caching *args = data;
4446 struct drm_gem_object *gobj;
4447 struct drm_i915_gem_object *obj;
4448 enum i915_cache_level level;
4449 int ret;
4450
4451 switch (args->caching) {
4452 case I915_CACHING_NONE:
4453 level = I915_CACHE_NONE;
4454 break;
4455 case I915_CACHING_CACHED:
4456 /*
4457 * Due to a HW issue on BXT A stepping, GPU stores via a
4458 * snooped mapping may leave stale data in a corresponding CPU
4459 * cacheline, whereas normally such cachelines would get
4460 * invalidated.
4461 */
4462 if (IS_BROXTON(dev) && INTEL_REVID(dev) < BXT_REVID_B0)
4463 return -ENODEV;
4464
4465 level = I915_CACHE_LLC;
4466 break;
4467 case I915_CACHING_DISPLAY:
4468 level = HAS_WT(dev) ? I915_CACHE_WT : I915_CACHE_NONE;
4469 break;
4470 default:
4471 return -EINVAL;
4472 }
4473
4474 intel_runtime_pm_get(dev_priv);
4475
4476 ret = i915_mutex_lock_interruptible(dev);
4477 if (ret)
4478 goto rpm_put;
4479
4480 gobj = drm_gem_object_lookup(dev, file, args->handle);
4481 if (gobj == NULL) {
4482 ret = -ENOENT;
4483 goto unlock;
4484 }
4485 obj = to_intel_bo(gobj);
4486
4487 ret = i915_gem_object_set_cache_level(obj, level);
4488
4489 drm_gem_object_unreference(&obj->base);
4490 unlock:
4491 mutex_unlock(&dev->struct_mutex);
4492 rpm_put:
4493 intel_runtime_pm_put(dev_priv);
4494
4495 /*
4496 * Prepare buffer for display plane (scanout, cursors, etc).
4497 * Can be called from an uninterruptible phase (modesetting) and allows
4498 * any flushes to be pipelined (for pageflips).
4499 */
4500 int
4501 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
4502 u32 alignment,
4503 struct intel_engine_cs *pipelined,
4504 struct drm_i915_gem_request **pipelined_request,
4505 const struct i915_ggtt_view *view)
4506 {
4507 u32 old_read_domains, old_write_domain;
4508 int ret;
4509
4510 ret = i915_gem_object_sync(obj, pipelined, pipelined_request);
4511 if (ret)
4512 return ret;
4513
4514 /* Mark the pin_display early so that we account for the
4515 * display coherency whilst setting up the cache domains.
4516 */
4517 obj->pin_display++;
4518
4519 /* The display engine is not coherent with the LLC cache on gen6. As
4520 * a result, we make sure that the pinning that is about to occur is
4521 * done with uncached PTEs. This is lowest common denominator for all
4522 * chipsets.
4523 *
4524 * However for gen6+, we could do better by using the GFDT bit instead
4525 * of uncaching, which would allow us to flush all the LLC-cached data
4526 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
4527 */
4528 ret = i915_gem_object_set_cache_level(obj,
4529 HAS_WT(obj->base.dev) ? I915_CACHE_WT : I915_CACHE_NONE);
4530 if (ret)
4531 goto err_unpin_display;
4532
4533 /* As the user may map the buffer once pinned in the display plane
4534 * (e.g. libkms for the bootup splash), we have to ensure that we
4535 * always use map_and_fenceable for all scanout buffers.
4536 */
4537 ret = i915_gem_object_ggtt_pin(obj, view, alignment,
4538 view->type == I915_GGTT_VIEW_NORMAL ?
4539 PIN_MAPPABLE : 0);
4540 if (ret)
4541 goto err_unpin_display;
4542
4543 i915_gem_object_flush_cpu_write_domain(obj);
4544
4545 old_write_domain = obj->base.write_domain;
4546 old_read_domains = obj->base.read_domains;
4547
4548 /* It should now be out of any other write domains, and we can update
4549 * the domain values for our changes.
4550 */
4551 obj->base.write_domain = 0;
4552 obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
4553
4554 trace_i915_gem_object_change_domain(obj,
4555 old_read_domains,
4556 old_write_domain);
4557
4558 return 0;
4559
4560 err_unpin_display:
4561 obj->pin_display--;
4562 return ret;
4563 }
4564
4565 void
4566 i915_gem_object_unpin_from_display_plane(struct drm_i915_gem_object *obj,
4567 const struct i915_ggtt_view *view)
4568 {
4569 if (WARN_ON(obj->pin_display == 0))
4570 return;
4571
4572 i915_gem_object_ggtt_unpin_view(obj, view);
4573
4574 obj->pin_display--;
4575 }
4576
4577 /**
4578 * Moves a single object to the CPU read, and possibly write domain.
4579 *
4580 * This function returns when the move is complete, including waiting on
4581 * flushes to occur.
4582 */
4583 int
4584 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
4585 {
4586 uint32_t old_write_domain, old_read_domains;
4587 int ret;
4588
4589 if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
4590 return 0;
4591
4592 ret = i915_gem_object_wait_rendering(obj, !write);
4593 if (ret)
4594 return ret;
4595
4596 i915_gem_object_flush_gtt_write_domain(obj);
4597
4598 old_write_domain = obj->base.write_domain;
4599 old_read_domains = obj->base.read_domains;
4600
4601 /* Flush the CPU cache if it's still invalid. */
4602 if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
4603 i915_gem_clflush_object(obj, false);
4604
4605 obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
4606 }
4607
4608 /* It should now be out of any other write domains, and we can update
4609 * the domain values for our changes.
4610 */
4611 BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
4612
4613 /* If we're writing through the CPU, then the GPU read domains will
4614 * need to be invalidated at next use.
4615 */
4616 if (write) {
4617 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
4618 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
4619 }
4620
4621 trace_i915_gem_object_change_domain(obj,
4622 old_read_domains,
4623 old_write_domain);
4624
4625 return 0;
4626 }
4627
4628 /* Throttle our rendering by waiting until the ring has completed our requests
4629 * emitted over 20 msec ago.
4630 *
4631 * Note that if we were to use the current jiffies each time around the loop,
4632 * we wouldn't escape the function with any frames outstanding if the time to
4633 * render a frame was over 20ms.
4634 *
4635 * This should get us reasonable parallelism between CPU and GPU but also
4636 * relatively low latency when blocking on a particular request to finish.
4637 */
4638 static int
4639 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
4640 {
4641 struct drm_i915_private *dev_priv = dev->dev_private;
4642 struct drm_i915_file_private *file_priv = file->driver_priv;
4643 unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
4644 struct drm_i915_gem_request *request, *target = NULL;
4645 unsigned reset_counter;
4646 int ret;
4647
4648 ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
4649 if (ret)
4650 return ret;
4651
4652 ret = i915_gem_check_wedge(&dev_priv->gpu_error, false);
4653 if (ret)
4654 return ret;
4655
4656 spin_lock(&file_priv->mm.lock);
4657 list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
4658 if (time_after_eq(request->emitted_jiffies, recent_enough))
4659 break;
4660
4661 /*
4662 * Note that the request might not have been submitted yet.
4663 * In which case emitted_jiffies will be zero.
4664 */
4665 if (!request->emitted_jiffies)
4666 continue;
4667
4668 target = request;
4669 }
4670 reset_counter = atomic_read(&dev_priv->gpu_error.reset_counter);
4671 if (target)
4672 i915_gem_request_reference(target);
4673 spin_unlock(&file_priv->mm.lock);
4674
4675 if (target == NULL)
4676 return 0;
4677
4678 ret = __i915_wait_request(target, reset_counter, true, NULL, NULL);
4679 if (ret == 0)
4680 queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
4681
4682 i915_gem_request_unreference__unlocked(target);
4683
4684 return ret;
4685 }
4686
4687 static bool
4688 i915_vma_misplaced(struct i915_vma *vma, uint32_t alignment, uint64_t flags)
4689 {
4690 struct drm_i915_gem_object *obj = vma->obj;
4691
4692 if (alignment &&
4693 vma->node.start & (alignment - 1))
4694 return true;
4695
4696 if (flags & PIN_MAPPABLE && !obj->map_and_fenceable)
4697 return true;
4698
4699 if (flags & PIN_OFFSET_BIAS &&
4700 vma->node.start < (flags & PIN_OFFSET_MASK))
4701 return true;
4702
4703 return false;
4704 }
4705
4706 void __i915_vma_set_map_and_fenceable(struct i915_vma *vma)
4707 {
4708 struct drm_i915_gem_object *obj = vma->obj;
4709 bool mappable, fenceable;
4710 u32 fence_size, fence_alignment;
4711
4712 fence_size = i915_gem_get_gtt_size(obj->base.dev,
4713 obj->base.size,
4714 obj->tiling_mode);
4715 fence_alignment = i915_gem_get_gtt_alignment(obj->base.dev,
4716 obj->base.size,
4717 obj->tiling_mode,
4718 true);
4719
4720 fenceable = (vma->node.size == fence_size &&
4721 (vma->node.start & (fence_alignment - 1)) == 0);
4722
4723 mappable = (vma->node.start + fence_size <=
4724 to_i915(obj->base.dev)->gtt.mappable_end);
4725
4726 obj->map_and_fenceable = mappable && fenceable;
4727 }
4728
4729 static int
4730 i915_gem_object_do_pin(struct drm_i915_gem_object *obj,
4731 struct i915_address_space *vm,
4732 const struct i915_ggtt_view *ggtt_view,
4733 uint32_t alignment,
4734 uint64_t flags)
4735 {
4736 struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
4737 struct i915_vma *vma;
4738 unsigned bound;
4739 int ret;
4740
4741 if (WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base))
4742 return -ENODEV;
4743
4744 if (WARN_ON(flags & (PIN_GLOBAL | PIN_MAPPABLE) && !i915_is_ggtt(vm)))
4745 return -EINVAL;
4746
4747 if (WARN_ON((flags & (PIN_MAPPABLE | PIN_GLOBAL)) == PIN_MAPPABLE))
4748 return -EINVAL;
4749
4750 if (WARN_ON(i915_is_ggtt(vm) != !!ggtt_view))
4751 return -EINVAL;
4752
4753 vma = ggtt_view ? i915_gem_obj_to_ggtt_view(obj, ggtt_view) :
4754 i915_gem_obj_to_vma(obj, vm);
4755
4756 if (IS_ERR(vma))
4757 return PTR_ERR(vma);
4758
4759 if (vma) {
4760 if (WARN_ON(vma->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT))
4761 return -EBUSY;
4762
4763 if (i915_vma_misplaced(vma, alignment, flags)) {
4764 WARN(vma->pin_count,
4765 "bo is already pinned in %s with incorrect alignment:"
4766 " offset=%08x %08x, req.alignment=%x, req.map_and_fenceable=%d,"
4767 " obj->map_and_fenceable=%d\n",
4768 ggtt_view ? "ggtt" : "ppgtt",
4769 upper_32_bits(vma->node.start),
4770 lower_32_bits(vma->node.start),
4771 alignment,
4772 !!(flags & PIN_MAPPABLE),
4773 obj->map_and_fenceable);
4774 ret = i915_vma_unbind(vma);
4775 if (ret)
4776 return ret;
4777
4778 vma = NULL;
4779 }
4780 }
4781
4782 bound = vma ? vma->bound : 0;
4783 if (vma == NULL || !drm_mm_node_allocated(&vma->node)) {
4784 vma = i915_gem_object_bind_to_vm(obj, vm, ggtt_view, alignment,
4785 flags);
4786 if (IS_ERR(vma))
4787 return PTR_ERR(vma);
4788 } else {
4789 ret = i915_vma_bind(vma, obj->cache_level, flags);
4790 if (ret)
4791 return ret;
4792 }
4793
4794 if (ggtt_view && ggtt_view->type == I915_GGTT_VIEW_NORMAL &&
4795 (bound ^ vma->bound) & GLOBAL_BIND) {
4796 __i915_vma_set_map_and_fenceable(vma);
4797 WARN_ON(flags & PIN_MAPPABLE && !obj->map_and_fenceable);
4798 }
4799
4800 vma->pin_count++;
4801 return 0;
4802 }
4803
4804 int
4805 i915_gem_object_pin(struct drm_i915_gem_object *obj,
4806 struct i915_address_space *vm,
4807 uint32_t alignment,
4808 uint64_t flags)
4809 {
4810 return i915_gem_object_do_pin(obj, vm,
4811 i915_is_ggtt(vm) ? &i915_ggtt_view_normal : NULL,
4812 alignment, flags);
4813 }
4814
4815 int
4816 i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
4817 const struct i915_ggtt_view *view,
4818 uint32_t alignment,
4819 uint64_t flags)
4820 {
4821 if (WARN_ONCE(!view, "no view specified"))
4822 return -EINVAL;
4823
4824 return i915_gem_object_do_pin(obj, i915_obj_to_ggtt(obj), view,
4825 alignment, flags | PIN_GLOBAL);
4826 }
4827
4828 void
4829 i915_gem_object_ggtt_unpin_view(struct drm_i915_gem_object *obj,
4830 const struct i915_ggtt_view *view)
4831 {
4832 struct i915_vma *vma = i915_gem_obj_to_ggtt_view(obj, view);
4833
4834 BUG_ON(!vma);
4835 WARN_ON(vma->pin_count == 0);
4836 WARN_ON(!i915_gem_obj_ggtt_bound_view(obj, view));
4837
4838 --vma->pin_count;
4839 }
4840
4841 int
4842 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
4843 struct drm_file *file)
4844 {
4845 struct drm_i915_gem_busy *args = data;
4846 struct drm_gem_object *gobj;
4847 struct drm_i915_gem_object *obj;
4848 int ret;
4849
4850 ret = i915_mutex_lock_interruptible(dev);
4851 if (ret)
4852 return ret;
4853
4854 gobj = drm_gem_object_lookup(dev, file, args->handle);
4855 if (gobj == NULL) {
4856 ret = -ENOENT;
4857 goto unlock;
4858 }
4859 obj = to_intel_bo(gobj);
4860
4861 /* Count all active objects as busy, even if they are currently not used
4862 * by the gpu. Users of this interface expect objects to eventually
4863 * become non-busy without any further actions, therefore emit any
4864 * necessary flushes here.
4865 */
4866 ret = i915_gem_object_flush_active(obj);
4867 if (ret)
4868 goto unref;
4869
4870 BUILD_BUG_ON(I915_NUM_RINGS > 16);
4871 args->busy = obj->active << 16;
4872 if (obj->last_write_req)
4873 args->busy |= obj->last_write_req->ring->id;
4874
4875 unref:
4876 drm_gem_object_unreference(&obj->base);
4877 unlock:
4878 mutex_unlock(&dev->struct_mutex);
4879 return ret;
4880 }
4881
4882 int
4883 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
4884 struct drm_file *file_priv)
4885 {
4886 return i915_gem_ring_throttle(dev, file_priv);
4887 }
4888
4889 int
4890 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
4891 struct drm_file *file_priv)
4892 {
4893 struct drm_i915_private *dev_priv = dev->dev_private;
4894 struct drm_i915_gem_madvise *args = data;
4895 struct drm_gem_object *gobj;
4896 struct drm_i915_gem_object *obj;
4897 int ret;
4898
4899 switch (args->madv) {
4900 case I915_MADV_DONTNEED:
4901 case I915_MADV_WILLNEED:
4902 break;
4903 default:
4904 return -EINVAL;
4905 }
4906
4907 ret = i915_mutex_lock_interruptible(dev);
4908 if (ret)
4909 return ret;
4910
4911 gobj = drm_gem_object_lookup(dev, file_priv, args->handle);
4912 if (gobj == NULL) {
4913 ret = -ENOENT;
4914 goto unlock;
4915 }
4916 obj = to_intel_bo(gobj);
4917
4918 if (i915_gem_obj_is_pinned(obj)) {
4919 ret = -EINVAL;
4920 goto out;
4921 }
4922
4923 if (obj->pages &&
4924 obj->tiling_mode != I915_TILING_NONE &&
4925 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
4926 if (obj->madv == I915_MADV_WILLNEED)
4927 i915_gem_object_unpin_pages(obj);
4928 if (args->madv == I915_MADV_WILLNEED)
4929 i915_gem_object_pin_pages(obj);
4930 }
4931
4932 if (obj->madv != __I915_MADV_PURGED)
4933 obj->madv = args->madv;
4934
4935 /* if the object is no longer attached, discard its backing storage */
4936 if (obj->madv == I915_MADV_DONTNEED && obj->pages == NULL)
4937 i915_gem_object_truncate(obj);
4938
4939 args->retained = obj->madv != __I915_MADV_PURGED;
4940
4941 out:
4942 drm_gem_object_unreference(&obj->base);
4943 unlock:
4944 mutex_unlock(&dev->struct_mutex);
4945 return ret;
4946 }
4947
4948 void i915_gem_object_init(struct drm_i915_gem_object *obj,
4949 const struct drm_i915_gem_object_ops *ops)
4950 {
4951 int i;
4952
4953 INIT_LIST_HEAD(&obj->global_list);
4954 for (i = 0; i < I915_NUM_RINGS; i++)
4955 INIT_LIST_HEAD(&obj->ring_list[i]);
4956 INIT_LIST_HEAD(&obj->obj_exec_link);
4957 INIT_LIST_HEAD(&obj->vma_list);
4958 INIT_LIST_HEAD(&obj->batch_pool_link);
4959
4960 obj->ops = ops;
4961
4962 obj->fence_reg = I915_FENCE_REG_NONE;
4963 obj->madv = I915_MADV_WILLNEED;
4964
4965 i915_gem_info_add_obj(obj->base.dev->dev_private, obj->base.size);
4966 }
4967
4968 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
4969 .get_pages = i915_gem_object_get_pages_gtt,
4970 .put_pages = i915_gem_object_put_pages_gtt,
4971 };
4972
4973 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
4974 size_t size)
4975 {
4976 #ifdef __NetBSD__
4977 struct drm_i915_private *const dev_priv = dev->dev_private;
4978 #endif
4979 struct drm_i915_gem_object *obj;
4980 #ifndef __NetBSD__
4981 struct address_space *mapping;
4982 gfp_t mask;
4983 #endif
4984
4985 obj = i915_gem_object_alloc(dev);
4986 if (obj == NULL)
4987 return NULL;
4988
4989 if (drm_gem_object_init(dev, &obj->base, size) != 0) {
4990 i915_gem_object_free(obj);
4991 return NULL;
4992 }
4993
4994 #ifdef __NetBSD__
4995 uao_set_pgfl(obj->base.gemo_shm_uao, dev_priv->gtt.pgfl);
4996 #else
4997 mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
4998 if (IS_CRESTLINE(dev) || IS_BROADWATER(dev)) {
4999 /* 965gm cannot relocate objects above 4GiB. */
5000 mask &= ~__GFP_HIGHMEM;
5001 mask |= __GFP_DMA32;
5002 }
5003
5004 mapping = file_inode(obj->base.filp)->i_mapping;
5005 mapping_set_gfp_mask(mapping, mask);
5006 #endif
5007
5008 i915_gem_object_init(obj, &i915_gem_object_ops);
5009
5010 obj->base.write_domain = I915_GEM_DOMAIN_CPU;
5011 obj->base.read_domains = I915_GEM_DOMAIN_CPU;
5012
5013 if (HAS_LLC(dev)) {
5014 /* On some devices, we can have the GPU use the LLC (the CPU
5015 * cache) for about a 10% performance improvement
5016 * compared to uncached. Graphics requests other than
5017 * display scanout are coherent with the CPU in
5018 * accessing this cache. This means in this mode we
5019 * don't need to clflush on the CPU side, and on the
5020 * GPU side we only need to flush internal caches to
5021 * get data visible to the CPU.
5022 *
5023 * However, we maintain the display planes as UC, and so
5024 * need to rebind when first used as such.
5025 */
5026 obj->cache_level = I915_CACHE_LLC;
5027 } else
5028 obj->cache_level = I915_CACHE_NONE;
5029
5030 trace_i915_gem_object_create(obj);
5031
5032 return obj;
5033 }
5034
5035 static bool discard_backing_storage(struct drm_i915_gem_object *obj)
5036 {
5037 /* If we are the last user of the backing storage (be it shmemfs
5038 * pages or stolen etc), we know that the pages are going to be
5039 * immediately released. In this case, we can then skip copying
5040 * back the contents from the GPU.
5041 */
5042
5043 if (obj->madv != I915_MADV_WILLNEED)
5044 return false;
5045
5046 if (obj->base.filp == NULL)
5047 return true;
5048
5049 /* At first glance, this looks racy, but then again so would be
5050 * userspace racing mmap against close. However, the first external
5051 * reference to the filp can only be obtained through the
5052 * i915_gem_mmap_ioctl() which safeguards us against the user
5053 * acquiring such a reference whilst we are in the middle of
5054 * freeing the object.
5055 */
5056 return atomic_long_read(&obj->base.filp->f_count) == 1;
5057 }
5058
5059 void i915_gem_free_object(struct drm_gem_object *gem_obj)
5060 {
5061 struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
5062 struct drm_device *dev = obj->base.dev;
5063 struct drm_i915_private *dev_priv = dev->dev_private;
5064 struct i915_vma *vma, *next;
5065
5066 intel_runtime_pm_get(dev_priv);
5067
5068 trace_i915_gem_object_destroy(obj);
5069
5070 list_for_each_entry_safe(vma, next, &obj->vma_list, vma_link) {
5071 int ret;
5072
5073 vma->pin_count = 0;
5074 ret = i915_vma_unbind(vma);
5075 if (WARN_ON(ret == -ERESTARTSYS)) {
5076 bool was_interruptible;
5077
5078 was_interruptible = dev_priv->mm.interruptible;
5079 dev_priv->mm.interruptible = false;
5080
5081 WARN_ON(i915_vma_unbind(vma));
5082
5083 dev_priv->mm.interruptible = was_interruptible;
5084 }
5085 }
5086
5087 /* Stolen objects don't hold a ref, but do hold pin count. Fix that up
5088 * before progressing. */
5089 if (obj->stolen)
5090 i915_gem_object_unpin_pages(obj);
5091
5092 WARN_ON(obj->frontbuffer_bits);
5093
5094 if (obj->pages && obj->madv == I915_MADV_WILLNEED &&
5095 dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES &&
5096 obj->tiling_mode != I915_TILING_NONE)
5097 i915_gem_object_unpin_pages(obj);
5098
5099 if (WARN_ON(obj->pages_pin_count))
5100 obj->pages_pin_count = 0;
5101 if (discard_backing_storage(obj))
5102 obj->madv = I915_MADV_DONTNEED;
5103 i915_gem_object_put_pages(obj);
5104 i915_gem_object_free_mmap_offset(obj);
5105
5106 BUG_ON(obj->pages);
5107
5108 #ifndef __NetBSD__ /* XXX drm prime */
5109 if (obj->base.import_attach)
5110 drm_prime_gem_destroy(&obj->base, NULL);
5111 #endif
5112
5113 if (obj->ops->release)
5114 obj->ops->release(obj);
5115
5116 drm_gem_object_release(&obj->base);
5117 i915_gem_info_remove_obj(dev_priv, obj->base.size);
5118
5119 kfree(obj->bit_17);
5120 i915_gem_object_free(obj);
5121
5122 intel_runtime_pm_put(dev_priv);
5123 }
5124
5125 struct i915_vma *i915_gem_obj_to_vma(struct drm_i915_gem_object *obj,
5126 struct i915_address_space *vm)
5127 {
5128 struct i915_vma *vma;
5129 list_for_each_entry(vma, &obj->vma_list, vma_link) {
5130 if (i915_is_ggtt(vma->vm) &&
5131 vma->ggtt_view.type != I915_GGTT_VIEW_NORMAL)
5132 continue;
5133 if (vma->vm == vm)
5134 return vma;
5135 }
5136 return NULL;
5137 }
5138
5139 struct i915_vma *i915_gem_obj_to_ggtt_view(struct drm_i915_gem_object *obj,
5140 const struct i915_ggtt_view *view)
5141 {
5142 struct i915_address_space *ggtt = i915_obj_to_ggtt(obj);
5143 struct i915_vma *vma;
5144
5145 if (WARN_ONCE(!view, "no view specified"))
5146 return ERR_PTR(-EINVAL);
5147
5148 list_for_each_entry(vma, &obj->vma_list, vma_link)
5149 if (vma->vm == ggtt &&
5150 i915_ggtt_view_equal(&vma->ggtt_view, view))
5151 return vma;
5152 return NULL;
5153 }
5154
5155 void i915_gem_vma_destroy(struct i915_vma *vma)
5156 {
5157 struct i915_address_space *vm = NULL;
5158 WARN_ON(vma->node.allocated);
5159
5160 /* Keep the vma as a placeholder in the execbuffer reservation lists */
5161 if (!list_empty(&vma->exec_list))
5162 return;
5163
5164 vm = vma->vm;
5165
5166 if (!i915_is_ggtt(vm))
5167 i915_ppgtt_put(i915_vm_to_ppgtt(vm));
5168
5169 list_del(&vma->vma_link);
5170
5171 kmem_cache_free(to_i915(vma->obj->base.dev)->vmas, vma);
5172 }
5173
5174 static void
5175 i915_gem_stop_ringbuffers(struct drm_device *dev)
5176 {
5177 struct drm_i915_private *dev_priv = dev->dev_private;
5178 struct intel_engine_cs *ring;
5179 int i;
5180
5181 for_each_ring(ring, dev_priv, i)
5182 dev_priv->gt.stop_ring(ring);
5183 }
5184
5185 int
5186 i915_gem_suspend(struct drm_device *dev)
5187 {
5188 struct drm_i915_private *dev_priv = dev->dev_private;
5189 int ret = 0;
5190
5191 mutex_lock(&dev->struct_mutex);
5192 ret = i915_gpu_idle(dev);
5193 if (ret)
5194 goto err;
5195
5196 i915_gem_retire_requests(dev);
5197
5198 i915_gem_stop_ringbuffers(dev);
5199 mutex_unlock(&dev->struct_mutex);
5200
5201 cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
5202 cancel_delayed_work_sync(&dev_priv->mm.retire_work);
5203 flush_delayed_work(&dev_priv->mm.idle_work);
5204
5205 /* Assert that we sucessfully flushed all the work and
5206 * reset the GPU back to its idle, low power state.
5207 */
5208 WARN_ON(dev_priv->mm.busy);
5209
5210 return 0;
5211
5212 err:
5213 mutex_unlock(&dev->struct_mutex);
5214 return ret;
5215 }
5216
5217 int i915_gem_l3_remap(struct drm_i915_gem_request *req, int slice)
5218 {
5219 struct intel_engine_cs *ring = req->ring;
5220 struct drm_device *dev = ring->dev;
5221 struct drm_i915_private *dev_priv = dev->dev_private;
5222 u32 reg_base = GEN7_L3LOG_BASE + (slice * 0x200);
5223 u32 *remap_info = dev_priv->l3_parity.remap_info[slice];
5224 int i, ret;
5225
5226 if (!HAS_L3_DPF(dev) || !remap_info)
5227 return 0;
5228
5229 ret = intel_ring_begin(req, GEN7_L3LOG_SIZE / 4 * 3);
5230 if (ret)
5231 return ret;
5232
5233 /*
5234 * Note: We do not worry about the concurrent register cacheline hang
5235 * here because no other code should access these registers other than
5236 * at initialization time.
5237 */
5238 for (i = 0; i < GEN7_L3LOG_SIZE; i += 4) {
5239 intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
5240 intel_ring_emit(ring, reg_base + i);
5241 intel_ring_emit(ring, remap_info[i/4]);
5242 }
5243
5244 intel_ring_advance(ring);
5245
5246 return ret;
5247 }
5248
5249 void i915_gem_init_swizzling(struct drm_device *dev)
5250 {
5251 struct drm_i915_private *dev_priv = dev->dev_private;
5252
5253 if (INTEL_INFO(dev)->gen < 5 ||
5254 dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
5255 return;
5256
5257 I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
5258 DISP_TILE_SURFACE_SWIZZLING);
5259
5260 if (IS_GEN5(dev))
5261 return;
5262
5263 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
5264 if (IS_GEN6(dev))
5265 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
5266 else if (IS_GEN7(dev))
5267 I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
5268 else if (IS_GEN8(dev))
5269 I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
5270 else
5271 BUG();
5272 }
5273
5274 static void init_unused_ring(struct drm_device *dev, u32 base)
5275 {
5276 struct drm_i915_private *dev_priv = dev->dev_private;
5277
5278 I915_WRITE(RING_CTL(base), 0);
5279 I915_WRITE(RING_HEAD(base), 0);
5280 I915_WRITE(RING_TAIL(base), 0);
5281 I915_WRITE(RING_START(base), 0);
5282 }
5283
5284 static void init_unused_rings(struct drm_device *dev)
5285 {
5286 if (IS_I830(dev)) {
5287 init_unused_ring(dev, PRB1_BASE);
5288 init_unused_ring(dev, SRB0_BASE);
5289 init_unused_ring(dev, SRB1_BASE);
5290 init_unused_ring(dev, SRB2_BASE);
5291 init_unused_ring(dev, SRB3_BASE);
5292 } else if (IS_GEN2(dev)) {
5293 init_unused_ring(dev, SRB0_BASE);
5294 init_unused_ring(dev, SRB1_BASE);
5295 } else if (IS_GEN3(dev)) {
5296 init_unused_ring(dev, PRB1_BASE);
5297 init_unused_ring(dev, PRB2_BASE);
5298 }
5299 }
5300
5301 int i915_gem_init_rings(struct drm_device *dev)
5302 {
5303 struct drm_i915_private *dev_priv = dev->dev_private;
5304 int ret;
5305
5306 ret = intel_init_render_ring_buffer(dev);
5307 if (ret)
5308 return ret;
5309
5310 if (HAS_BSD(dev)) {
5311 ret = intel_init_bsd_ring_buffer(dev);
5312 if (ret)
5313 goto cleanup_render_ring;
5314 }
5315
5316 if (HAS_BLT(dev)) {
5317 ret = intel_init_blt_ring_buffer(dev);
5318 if (ret)
5319 goto cleanup_bsd_ring;
5320 }
5321
5322 if (HAS_VEBOX(dev)) {
5323 ret = intel_init_vebox_ring_buffer(dev);
5324 if (ret)
5325 goto cleanup_blt_ring;
5326 }
5327
5328 if (HAS_BSD2(dev)) {
5329 ret = intel_init_bsd2_ring_buffer(dev);
5330 if (ret)
5331 goto cleanup_vebox_ring;
5332 }
5333
5334 return 0;
5335
5336 cleanup_vebox_ring:
5337 intel_cleanup_ring_buffer(&dev_priv->ring[VECS]);
5338 cleanup_blt_ring:
5339 intel_cleanup_ring_buffer(&dev_priv->ring[BCS]);
5340 cleanup_bsd_ring:
5341 intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
5342 cleanup_render_ring:
5343 intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
5344
5345 return ret;
5346 }
5347
5348 int
5349 i915_gem_init_hw(struct drm_device *dev)
5350 {
5351 struct drm_i915_private *dev_priv = dev->dev_private;
5352 struct intel_engine_cs *ring;
5353 int ret, i, j;
5354
5355 if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
5356 return -EIO;
5357
5358 /* Double layer security blanket, see i915_gem_init() */
5359 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
5360
5361 if (dev_priv->ellc_size)
5362 I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
5363
5364 if (IS_HASWELL(dev))
5365 I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev) ?
5366 LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
5367
5368 if (HAS_PCH_NOP(dev)) {
5369 if (IS_IVYBRIDGE(dev)) {
5370 u32 temp = I915_READ(GEN7_MSG_CTL);
5371 temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
5372 I915_WRITE(GEN7_MSG_CTL, temp);
5373 } else if (INTEL_INFO(dev)->gen >= 7) {
5374 u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
5375 temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
5376 I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
5377 }
5378 }
5379
5380 i915_gem_init_swizzling(dev);
5381
5382 /*
5383 * At least 830 can leave some of the unused rings
5384 * "active" (ie. head != tail) after resume which
5385 * will prevent c3 entry. Makes sure all unused rings
5386 * are totally idle.
5387 */
5388 init_unused_rings(dev);
5389
5390 BUG_ON(!dev_priv->ring[RCS].default_context);
5391
5392 ret = i915_ppgtt_init_hw(dev);
5393 if (ret) {
5394 DRM_ERROR("PPGTT enable HW failed %d\n", ret);
5395 goto out;
5396 }
5397
5398 /* Need to do basic initialisation of all rings first: */
5399 for_each_ring(ring, dev_priv, i) {
5400 ret = ring->init_hw(ring);
5401 if (ret)
5402 goto out;
5403 }
5404
5405 /* We can't enable contexts until all firmware is loaded */
5406 if (HAS_GUC_UCODE(dev)) {
5407 ret = intel_guc_ucode_load(dev);
5408 if (ret) {
5409 /*
5410 * If we got an error and GuC submission is enabled, map
5411 * the error to -EIO so the GPU will be declared wedged.
5412 * OTOH, if we didn't intend to use the GuC anyway, just
5413 * discard the error and carry on.
5414 */
5415 DRM_ERROR("Failed to initialize GuC, error %d%s\n", ret,
5416 i915.enable_guc_submission ? "" :
5417 " (ignored)");
5418 ret = i915.enable_guc_submission ? -EIO : 0;
5419 if (ret)
5420 goto out;
5421 }
5422 }
5423
5424 /*
5425 * Increment the next seqno by 0x100 so we have a visible break
5426 * on re-initialisation
5427 */
5428 ret = i915_gem_set_seqno(dev, dev_priv->next_seqno+0x100);
5429 if (ret)
5430 goto out;
5431
5432 /* Now it is safe to go back round and do everything else: */
5433 for_each_ring(ring, dev_priv, i) {
5434 struct drm_i915_gem_request *req;
5435
5436 WARN_ON(!ring->default_context);
5437
5438 ret = i915_gem_request_alloc(ring, ring->default_context, &req);
5439 if (ret) {
5440 i915_gem_cleanup_ringbuffer(dev);
5441 goto out;
5442 }
5443
5444 if (ring->id == RCS) {
5445 for (j = 0; j < NUM_L3_SLICES(dev); j++)
5446 i915_gem_l3_remap(req, j);
5447 }
5448
5449 ret = i915_ppgtt_init_ring(req);
5450 if (ret && ret != -EIO) {
5451 DRM_ERROR("PPGTT enable ring #%d failed %d\n", i, ret);
5452 i915_gem_request_cancel(req);
5453 i915_gem_cleanup_ringbuffer(dev);
5454 goto out;
5455 }
5456
5457 ret = i915_gem_context_enable(req);
5458 if (ret && ret != -EIO) {
5459 DRM_ERROR("Context enable ring #%d failed %d\n", i, ret);
5460 i915_gem_request_cancel(req);
5461 i915_gem_cleanup_ringbuffer(dev);
5462 goto out;
5463 }
5464
5465 i915_add_request_no_flush(req);
5466 }
5467
5468 out:
5469 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5470 return ret;
5471 }
5472
5473 int i915_gem_init(struct drm_device *dev)
5474 {
5475 struct drm_i915_private *dev_priv = dev->dev_private;
5476 int ret;
5477
5478 i915.enable_execlists = intel_sanitize_enable_execlists(dev,
5479 i915.enable_execlists);
5480
5481 mutex_lock(&dev->struct_mutex);
5482
5483 if (IS_VALLEYVIEW(dev)) {
5484 /* VLVA0 (potential hack), BIOS isn't actually waking us */
5485 I915_WRITE(VLV_GTLC_WAKE_CTRL, VLV_GTLC_ALLOWWAKEREQ);
5486 if (wait_for((I915_READ(VLV_GTLC_PW_STATUS) &
5487 VLV_GTLC_ALLOWWAKEACK), 10))
5488 DRM_DEBUG_DRIVER("allow wake ack timed out\n");
5489 }
5490
5491 if (!i915.enable_execlists) {
5492 dev_priv->gt.execbuf_submit = i915_gem_ringbuffer_submission;
5493 dev_priv->gt.init_rings = i915_gem_init_rings;
5494 dev_priv->gt.cleanup_ring = intel_cleanup_ring_buffer;
5495 dev_priv->gt.stop_ring = intel_stop_ring_buffer;
5496 } else {
5497 dev_priv->gt.execbuf_submit = intel_execlists_submission;
5498 dev_priv->gt.init_rings = intel_logical_rings_init;
5499 dev_priv->gt.cleanup_ring = intel_logical_ring_cleanup;
5500 dev_priv->gt.stop_ring = intel_logical_ring_stop;
5501 }
5502
5503 /* This is just a security blanket to placate dragons.
5504 * On some systems, we very sporadically observe that the first TLBs
5505 * used by the CS may be stale, despite us poking the TLB reset. If
5506 * we hold the forcewake during initialisation these problems
5507 * just magically go away.
5508 */
5509 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
5510
5511 ret = i915_gem_init_userptr(dev);
5512 if (ret)
5513 goto out_unlock;
5514
5515 i915_gem_init_global_gtt(dev);
5516
5517 ret = i915_gem_context_init(dev);
5518 if (ret)
5519 goto out_unlock;
5520
5521 ret = dev_priv->gt.init_rings(dev);
5522 if (ret)
5523 goto out_unlock;
5524
5525 ret = i915_gem_init_hw(dev);
5526 if (ret == -EIO) {
5527 /* Allow ring initialisation to fail by marking the GPU as
5528 * wedged. But we only want to do this where the GPU is angry,
5529 * for all other failure, such as an allocation failure, bail.
5530 */
5531 DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
5532 atomic_or(I915_WEDGED, &dev_priv->gpu_error.reset_counter);
5533 ret = 0;
5534 }
5535
5536 out_unlock:
5537 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
5538 mutex_unlock(&dev->struct_mutex);
5539
5540 return ret;
5541 }
5542
5543 void
5544 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
5545 {
5546 struct drm_i915_private *dev_priv = dev->dev_private;
5547 struct intel_engine_cs *ring;
5548 int i;
5549
5550 for_each_ring(ring, dev_priv, i)
5551 dev_priv->gt.cleanup_ring(ring);
5552
5553 if (i915.enable_execlists)
5554 /*
5555 * Neither the BIOS, ourselves or any other kernel
5556 * expects the system to be in execlists mode on startup,
5557 * so we need to reset the GPU back to legacy mode.
5558 */
5559 intel_gpu_reset(dev);
5560 }
5561
5562 static void
5563 init_ring_lists(struct intel_engine_cs *ring)
5564 {
5565 INIT_LIST_HEAD(&ring->active_list);
5566 INIT_LIST_HEAD(&ring->request_list);
5567 }
5568
5569 void
5570 i915_gem_load(struct drm_device *dev)
5571 {
5572 struct drm_i915_private *dev_priv = dev->dev_private;
5573 int i;
5574
5575 dev_priv->objects =
5576 kmem_cache_create("i915_gem_object",
5577 sizeof(struct drm_i915_gem_object), 0,
5578 SLAB_HWCACHE_ALIGN,
5579 NULL);
5580 dev_priv->vmas =
5581 kmem_cache_create("i915_gem_vma",
5582 sizeof(struct i915_vma), 0,
5583 SLAB_HWCACHE_ALIGN,
5584 NULL);
5585 dev_priv->requests =
5586 kmem_cache_create("i915_gem_request",
5587 sizeof(struct drm_i915_gem_request), 0,
5588 SLAB_HWCACHE_ALIGN,
5589 NULL);
5590
5591 INIT_LIST_HEAD(&dev_priv->vm_list);
5592 INIT_LIST_HEAD(&dev_priv->context_list);
5593 INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
5594 INIT_LIST_HEAD(&dev_priv->mm.bound_list);
5595 INIT_LIST_HEAD(&dev_priv->mm.fence_list);
5596 for (i = 0; i < I915_NUM_RINGS; i++)
5597 init_ring_lists(&dev_priv->ring[i]);
5598 for (i = 0; i < I915_MAX_NUM_FENCES; i++)
5599 INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
5600 INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
5601 i915_gem_retire_work_handler);
5602 INIT_DELAYED_WORK(&dev_priv->mm.idle_work,
5603 i915_gem_idle_work_handler);
5604 #ifdef __NetBSD__
5605 spin_lock_init(&dev_priv->gpu_error.reset_lock);
5606 DRM_INIT_WAITQUEUE(&dev_priv->gpu_error.reset_queue, "i915errst");
5607 #else
5608 init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
5609 #endif
5610
5611 dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
5612
5613 if (INTEL_INFO(dev)->gen >= 7 && !IS_VALLEYVIEW(dev))
5614 dev_priv->num_fence_regs = 32;
5615 else if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
5616 dev_priv->num_fence_regs = 16;
5617 else
5618 dev_priv->num_fence_regs = 8;
5619
5620 if (intel_vgpu_active(dev))
5621 dev_priv->num_fence_regs =
5622 I915_READ(vgtif_reg(avail_rs.fence_num));
5623
5624 /*
5625 * Set initial sequence number for requests.
5626 * Using this number allows the wraparound to happen early,
5627 * catching any obvious problems.
5628 */
5629 dev_priv->next_seqno = ((u32)~0 - 0x1100);
5630 dev_priv->last_seqno = ((u32)~0 - 0x1101);
5631
5632 /* Initialize fence registers to zero */
5633 INIT_LIST_HEAD(&dev_priv->mm.fence_list);
5634 i915_gem_restore_fences(dev);
5635
5636 i915_gem_detect_bit_6_swizzle(dev);
5637 #ifdef __NetBSD__
5638 DRM_INIT_WAITQUEUE(&dev_priv->pending_flip_queue, "i915flip");
5639 spin_lock_init(&dev_priv->pending_flip_lock);
5640 #else
5641 init_waitqueue_head(&dev_priv->pending_flip_queue);
5642 #endif
5643
5644 dev_priv->mm.interruptible = true;
5645
5646 i915_gem_shrinker_init(dev_priv);
5647
5648 mutex_init(&dev_priv->fb_tracking.lock);
5649 }
5650
5651 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
5652 {
5653 struct drm_i915_file_private *file_priv = file->driver_priv;
5654
5655 /* Clean up our request list when the client is going away, so that
5656 * later retire_requests won't dereference our soon-to-be-gone
5657 * file_priv.
5658 */
5659 spin_lock(&file_priv->mm.lock);
5660 while (!list_empty(&file_priv->mm.request_list)) {
5661 struct drm_i915_gem_request *request;
5662
5663 request = list_first_entry(&file_priv->mm.request_list,
5664 struct drm_i915_gem_request,
5665 client_list);
5666 list_del(&request->client_list);
5667 request->file_priv = NULL;
5668 }
5669 spin_unlock(&file_priv->mm.lock);
5670
5671 if (!list_empty(&file_priv->rps.link)) {
5672 spin_lock(&to_i915(dev)->rps.client_lock);
5673 list_del(&file_priv->rps.link);
5674 spin_unlock(&to_i915(dev)->rps.client_lock);
5675 }
5676 }
5677
5678 int i915_gem_open(struct drm_device *dev, struct drm_file *file)
5679 {
5680 struct drm_i915_file_private *file_priv;
5681 int ret;
5682
5683 DRM_DEBUG_DRIVER("\n");
5684
5685 file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
5686 if (!file_priv)
5687 return -ENOMEM;
5688
5689 file->driver_priv = file_priv;
5690 file_priv->dev_priv = dev->dev_private;
5691 file_priv->file = file;
5692 INIT_LIST_HEAD(&file_priv->rps.link);
5693
5694 spin_lock_init(&file_priv->mm.lock);
5695 INIT_LIST_HEAD(&file_priv->mm.request_list);
5696
5697 ret = i915_gem_context_open(dev, file);
5698 if (ret)
5699 kfree(file_priv);
5700
5701 return ret;
5702 }
5703
5704 /**
5705 * i915_gem_track_fb - update frontbuffer tracking
5706 * @old: current GEM buffer for the frontbuffer slots
5707 * @new: new GEM buffer for the frontbuffer slots
5708 * @frontbuffer_bits: bitmask of frontbuffer slots
5709 *
5710 * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
5711 * from @old and setting them in @new. Both @old and @new can be NULL.
5712 */
5713 void i915_gem_track_fb(struct drm_i915_gem_object *old,
5714 struct drm_i915_gem_object *new,
5715 unsigned frontbuffer_bits)
5716 {
5717 if (old) {
5718 WARN_ON(!mutex_is_locked(&old->base.dev->struct_mutex));
5719 WARN_ON(!(old->frontbuffer_bits & frontbuffer_bits));
5720 old->frontbuffer_bits &= ~frontbuffer_bits;
5721 }
5722
5723 if (new) {
5724 WARN_ON(!mutex_is_locked(&new->base.dev->struct_mutex));
5725 WARN_ON(new->frontbuffer_bits & frontbuffer_bits);
5726 new->frontbuffer_bits |= frontbuffer_bits;
5727 }
5728 }
5729 #endif
5730
5731 /* All the new VM stuff */
5732 u64 i915_gem_obj_offset(struct drm_i915_gem_object *o,
5733 struct i915_address_space *vm)
5734 {
5735 struct drm_i915_private *dev_priv = o->base.dev->dev_private;
5736 struct i915_vma *vma;
5737
5738 WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base);
5739
5740 list_for_each_entry(vma, &o->vma_list, vma_link) {
5741 if (i915_is_ggtt(vma->vm) &&
5742 vma->ggtt_view.type != I915_GGTT_VIEW_NORMAL)
5743 continue;
5744 if (vma->vm == vm)
5745 return vma->node.start;
5746 }
5747
5748 WARN(1, "%s vma for this object not found.\n",
5749 i915_is_ggtt(vm) ? "global" : "ppgtt");
5750 return -1;
5751 }
5752
5753 u64 i915_gem_obj_ggtt_offset_view(struct drm_i915_gem_object *o,
5754 const struct i915_ggtt_view *view)
5755 {
5756 struct i915_address_space *ggtt = i915_obj_to_ggtt(o);
5757 struct i915_vma *vma;
5758
5759 list_for_each_entry(vma, &o->vma_list, vma_link)
5760 if (vma->vm == ggtt &&
5761 i915_ggtt_view_equal(&vma->ggtt_view, view))
5762 return vma->node.start;
5763
5764 WARN(1, "global vma for this object not found. (view=%u)\n", view->type);
5765 return -1;
5766 }
5767
5768 bool i915_gem_obj_bound(struct drm_i915_gem_object *o,
5769 struct i915_address_space *vm)
5770 {
5771 struct i915_vma *vma;
5772
5773 list_for_each_entry(vma, &o->vma_list, vma_link) {
5774 if (i915_is_ggtt(vma->vm) &&
5775 vma->ggtt_view.type != I915_GGTT_VIEW_NORMAL)
5776 continue;
5777 if (vma->vm == vm && drm_mm_node_allocated(&vma->node))
5778 return true;
5779 }
5780
5781 return false;
5782 }
5783
5784 bool i915_gem_obj_ggtt_bound_view(struct drm_i915_gem_object *o,
5785 const struct i915_ggtt_view *view)
5786 {
5787 struct i915_address_space *ggtt = i915_obj_to_ggtt(o);
5788 struct i915_vma *vma;
5789
5790 list_for_each_entry(vma, &o->vma_list, vma_link)
5791 if (vma->vm == ggtt &&
5792 i915_ggtt_view_equal(&vma->ggtt_view, view) &&
5793 drm_mm_node_allocated(&vma->node))
5794 return true;
5795
5796 return false;
5797 }
5798
5799 bool i915_gem_obj_bound_any(struct drm_i915_gem_object *o)
5800 {
5801 struct i915_vma *vma;
5802
5803 list_for_each_entry(vma, &o->vma_list, vma_link)
5804 if (drm_mm_node_allocated(&vma->node))
5805 return true;
5806
5807 return false;
5808 }
5809
5810 unsigned long i915_gem_obj_size(struct drm_i915_gem_object *o,
5811 struct i915_address_space *vm)
5812 {
5813 struct drm_i915_private *dev_priv = o->base.dev->dev_private;
5814 struct i915_vma *vma;
5815
5816 WARN_ON(vm == &dev_priv->mm.aliasing_ppgtt->base);
5817
5818 BUG_ON(list_empty(&o->vma_list));
5819
5820 list_for_each_entry(vma, &o->vma_list, vma_link) {
5821 if (i915_is_ggtt(vma->vm) &&
5822 vma->ggtt_view.type != I915_GGTT_VIEW_NORMAL)
5823 continue;
5824 if (vma->vm == vm)
5825 return vma->node.size;
5826 }
5827 return 0;
5828 }
5829
5830 bool i915_gem_obj_is_pinned(struct drm_i915_gem_object *obj)
5831 {
5832 struct i915_vma *vma;
5833 list_for_each_entry(vma, &obj->vma_list, vma_link)
5834 if (vma->pin_count > 0)
5835 return true;
5836
5837 return false;
5838 }
5839
5840 /* Allocate a new GEM object and fill it with the supplied data */
5841 struct drm_i915_gem_object *
5842 i915_gem_object_create_from_data(struct drm_device *dev,
5843 const void *data, size_t size)
5844 {
5845 struct drm_i915_gem_object *obj;
5846 struct sg_table *sg;
5847 size_t bytes;
5848 int ret;
5849
5850 obj = i915_gem_alloc_object(dev, round_up(size, PAGE_SIZE));
5851 if (IS_ERR_OR_NULL(obj))
5852 return obj;
5853
5854 ret = i915_gem_object_set_to_cpu_domain(obj, true);
5855 if (ret)
5856 goto fail;
5857
5858 ret = i915_gem_object_get_pages(obj);
5859 if (ret)
5860 goto fail;
5861
5862 i915_gem_object_pin_pages(obj);
5863 sg = obj->pages;
5864 bytes = sg_copy_from_buffer(sg->sgl, sg->nents, (void *)data, size);
5865 i915_gem_object_unpin_pages(obj);
5866
5867 if (WARN_ON(bytes != size)) {
5868 DRM_ERROR("Incomplete copy, wrote %zu of %zu", bytes, size);
5869 ret = -EFAULT;
5870 goto fail;
5871 }
5872
5873 return obj;
5874
5875 fail:
5876 drm_gem_object_unreference(&obj->base);
5877 return ERR_PTR(ret);
5878 }
5879