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