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