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