f6fe5cb014382b42996c63daf27072ac3b9bf981
[linux-2.6-microblaze.git] / drivers / gpu / drm / i915 / gem / i915_gem_mman.c
1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2014-2016 Intel Corporation
5  */
6
7 #include <linux/anon_inodes.h>
8 #include <linux/mman.h>
9 #include <linux/pfn_t.h>
10 #include <linux/sizes.h>
11
12 #include "gt/intel_gt.h"
13 #include "gt/intel_gt_requests.h"
14
15 #include "i915_drv.h"
16 #include "i915_gem_gtt.h"
17 #include "i915_gem_ioctls.h"
18 #include "i915_gem_object.h"
19 #include "i915_gem_mman.h"
20 #include "i915_trace.h"
21 #include "i915_user_extensions.h"
22 #include "i915_vma.h"
23
24 static inline bool
25 __vma_matches(struct vm_area_struct *vma, struct file *filp,
26               unsigned long addr, unsigned long size)
27 {
28         if (vma->vm_file != filp)
29                 return false;
30
31         return vma->vm_start == addr &&
32                (vma->vm_end - vma->vm_start) == PAGE_ALIGN(size);
33 }
34
35 /**
36  * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
37  *                       it is mapped to.
38  * @dev: drm device
39  * @data: ioctl data blob
40  * @file: drm file
41  *
42  * While the mapping holds a reference on the contents of the object, it doesn't
43  * imply a ref on the object itself.
44  *
45  * IMPORTANT:
46  *
47  * DRM driver writers who look a this function as an example for how to do GEM
48  * mmap support, please don't implement mmap support like here. The modern way
49  * to implement DRM mmap support is with an mmap offset ioctl (like
50  * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
51  * That way debug tooling like valgrind will understand what's going on, hiding
52  * the mmap call in a driver private ioctl will break that. The i915 driver only
53  * does cpu mmaps this way because we didn't know better.
54  */
55 int
56 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
57                     struct drm_file *file)
58 {
59         struct drm_i915_gem_mmap *args = data;
60         struct drm_i915_gem_object *obj;
61         unsigned long addr;
62
63         if (args->flags & ~(I915_MMAP_WC))
64                 return -EINVAL;
65
66         if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
67                 return -ENODEV;
68
69         obj = i915_gem_object_lookup(file, args->handle);
70         if (!obj)
71                 return -ENOENT;
72
73         /* prime objects have no backing filp to GEM mmap
74          * pages from.
75          */
76         if (!obj->base.filp) {
77                 addr = -ENXIO;
78                 goto err;
79         }
80
81         if (range_overflows(args->offset, args->size, (u64)obj->base.size)) {
82                 addr = -EINVAL;
83                 goto err;
84         }
85
86         addr = vm_mmap(obj->base.filp, 0, args->size,
87                        PROT_READ | PROT_WRITE, MAP_SHARED,
88                        args->offset);
89         if (IS_ERR_VALUE(addr))
90                 goto err;
91
92         if (args->flags & I915_MMAP_WC) {
93                 struct mm_struct *mm = current->mm;
94                 struct vm_area_struct *vma;
95
96                 if (mmap_write_lock_killable(mm)) {
97                         addr = -EINTR;
98                         goto err;
99                 }
100                 vma = find_vma(mm, addr);
101                 if (vma && __vma_matches(vma, obj->base.filp, addr, args->size))
102                         vma->vm_page_prot =
103                                 pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
104                 else
105                         addr = -ENOMEM;
106                 mmap_write_unlock(mm);
107                 if (IS_ERR_VALUE(addr))
108                         goto err;
109         }
110         i915_gem_object_put(obj);
111
112         args->addr_ptr = (u64)addr;
113         return 0;
114
115 err:
116         i915_gem_object_put(obj);
117         return addr;
118 }
119
120 static unsigned int tile_row_pages(const struct drm_i915_gem_object *obj)
121 {
122         return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
123 }
124
125 /**
126  * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
127  *
128  * A history of the GTT mmap interface:
129  *
130  * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
131  *     aligned and suitable for fencing, and still fit into the available
132  *     mappable space left by the pinned display objects. A classic problem
133  *     we called the page-fault-of-doom where we would ping-pong between
134  *     two objects that could not fit inside the GTT and so the memcpy
135  *     would page one object in at the expense of the other between every
136  *     single byte.
137  *
138  * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
139  *     as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
140  *     object is too large for the available space (or simply too large
141  *     for the mappable aperture!), a view is created instead and faulted
142  *     into userspace. (This view is aligned and sized appropriately for
143  *     fenced access.)
144  *
145  * 2 - Recognise WC as a separate cache domain so that we can flush the
146  *     delayed writes via GTT before performing direct access via WC.
147  *
148  * 3 - Remove implicit set-domain(GTT) and synchronisation on initial
149  *     pagefault; swapin remains transparent.
150  *
151  * 4 - Support multiple fault handlers per object depending on object's
152  *     backing storage (a.k.a. MMAP_OFFSET).
153  *
154  * Restrictions:
155  *
156  *  * snoopable objects cannot be accessed via the GTT. It can cause machine
157  *    hangs on some architectures, corruption on others. An attempt to service
158  *    a GTT page fault from a snoopable object will generate a SIGBUS.
159  *
160  *  * the object must be able to fit into RAM (physical memory, though no
161  *    limited to the mappable aperture).
162  *
163  *
164  * Caveats:
165  *
166  *  * a new GTT page fault will synchronize rendering from the GPU and flush
167  *    all data to system memory. Subsequent access will not be synchronized.
168  *
169  *  * all mappings are revoked on runtime device suspend.
170  *
171  *  * there are only 8, 16 or 32 fence registers to share between all users
172  *    (older machines require fence register for display and blitter access
173  *    as well). Contention of the fence registers will cause the previous users
174  *    to be unmapped and any new access will generate new page faults.
175  *
176  *  * running out of memory while servicing a fault may generate a SIGBUS,
177  *    rather than the expected SIGSEGV.
178  */
179 int i915_gem_mmap_gtt_version(void)
180 {
181         return 4;
182 }
183
184 static inline struct i915_ggtt_view
185 compute_partial_view(const struct drm_i915_gem_object *obj,
186                      pgoff_t page_offset,
187                      unsigned int chunk)
188 {
189         struct i915_ggtt_view view;
190
191         if (i915_gem_object_is_tiled(obj))
192                 chunk = roundup(chunk, tile_row_pages(obj) ?: 1);
193
194         view.type = I915_GGTT_VIEW_PARTIAL;
195         view.partial.offset = rounddown(page_offset, chunk);
196         view.partial.size =
197                 min_t(unsigned int, chunk,
198                       (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
199
200         /* If the partial covers the entire object, just create a normal VMA. */
201         if (chunk >= obj->base.size >> PAGE_SHIFT)
202                 view.type = I915_GGTT_VIEW_NORMAL;
203
204         return view;
205 }
206
207 static vm_fault_t i915_error_to_vmf_fault(int err)
208 {
209         switch (err) {
210         default:
211                 WARN_ONCE(err, "unhandled error in %s: %i\n", __func__, err);
212                 fallthrough;
213         case -EIO: /* shmemfs failure from swap device */
214         case -EFAULT: /* purged object */
215         case -ENODEV: /* bad object, how did you get here! */
216         case -ENXIO: /* unable to access backing store (on device) */
217                 return VM_FAULT_SIGBUS;
218
219         case -ENOMEM: /* our allocation failure */
220                 return VM_FAULT_OOM;
221
222         case 0:
223         case -EAGAIN:
224         case -ENOSPC: /* transient failure to evict? */
225         case -ERESTARTSYS:
226         case -EINTR:
227         case -EBUSY:
228                 /*
229                  * EBUSY is ok: this just means that another thread
230                  * already did the job.
231                  */
232                 return VM_FAULT_NOPAGE;
233         }
234 }
235
236 static vm_fault_t vm_fault_cpu(struct vm_fault *vmf)
237 {
238         struct vm_area_struct *area = vmf->vma;
239         struct i915_mmap_offset *mmo = area->vm_private_data;
240         struct drm_i915_gem_object *obj = mmo->obj;
241         resource_size_t iomap;
242         int err;
243
244         /* Sanity check that we allow writing into this object */
245         if (unlikely(i915_gem_object_is_readonly(obj) &&
246                      area->vm_flags & VM_WRITE))
247                 return VM_FAULT_SIGBUS;
248
249         if (i915_gem_object_lock_interruptible(obj, NULL))
250                 return VM_FAULT_NOPAGE;
251
252         err = i915_gem_object_pin_pages(obj);
253         if (err)
254                 goto out;
255
256         iomap = -1;
257         if (!i915_gem_object_has_struct_page(obj)) {
258                 iomap = obj->mm.region->iomap.base;
259                 iomap -= obj->mm.region->region.start;
260         }
261
262         /* PTEs are revoked in obj->ops->put_pages() */
263         err = remap_io_sg(area,
264                           area->vm_start, area->vm_end - area->vm_start,
265                           obj->mm.pages->sgl, iomap);
266
267         if (area->vm_flags & VM_WRITE) {
268                 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
269                 obj->mm.dirty = true;
270         }
271
272         i915_gem_object_unpin_pages(obj);
273
274 out:
275         i915_gem_object_unlock(obj);
276         return i915_error_to_vmf_fault(err);
277 }
278
279 static vm_fault_t vm_fault_gtt(struct vm_fault *vmf)
280 {
281 #define MIN_CHUNK_PAGES (SZ_1M >> PAGE_SHIFT)
282         struct vm_area_struct *area = vmf->vma;
283         struct i915_mmap_offset *mmo = area->vm_private_data;
284         struct drm_i915_gem_object *obj = mmo->obj;
285         struct drm_device *dev = obj->base.dev;
286         struct drm_i915_private *i915 = to_i915(dev);
287         struct intel_runtime_pm *rpm = &i915->runtime_pm;
288         struct i915_ggtt *ggtt = &i915->ggtt;
289         bool write = area->vm_flags & VM_WRITE;
290         struct i915_gem_ww_ctx ww;
291         intel_wakeref_t wakeref;
292         struct i915_vma *vma;
293         pgoff_t page_offset;
294         int srcu;
295         int ret;
296
297         /* We don't use vmf->pgoff since that has the fake offset */
298         page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
299
300         trace_i915_gem_object_fault(obj, page_offset, true, write);
301
302         wakeref = intel_runtime_pm_get(rpm);
303
304         i915_gem_ww_ctx_init(&ww, true);
305 retry:
306         ret = i915_gem_object_lock(obj, &ww);
307         if (ret)
308                 goto err_rpm;
309
310         /* Sanity check that we allow writing into this object */
311         if (i915_gem_object_is_readonly(obj) && write) {
312                 ret = -EFAULT;
313                 goto err_rpm;
314         }
315
316         ret = i915_gem_object_pin_pages(obj);
317         if (ret)
318                 goto err_rpm;
319
320         ret = intel_gt_reset_trylock(ggtt->vm.gt, &srcu);
321         if (ret)
322                 goto err_pages;
323
324         /* Now pin it into the GTT as needed */
325         vma = i915_gem_object_ggtt_pin_ww(obj, &ww, NULL, 0, 0,
326                                           PIN_MAPPABLE |
327                                           PIN_NONBLOCK /* NOWARN */ |
328                                           PIN_NOEVICT);
329         if (IS_ERR(vma) && vma != ERR_PTR(-EDEADLK)) {
330                 /* Use a partial view if it is bigger than available space */
331                 struct i915_ggtt_view view =
332                         compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
333                 unsigned int flags;
334
335                 flags = PIN_MAPPABLE | PIN_NOSEARCH;
336                 if (view.type == I915_GGTT_VIEW_NORMAL)
337                         flags |= PIN_NONBLOCK; /* avoid warnings for pinned */
338
339                 /*
340                  * Userspace is now writing through an untracked VMA, abandon
341                  * all hope that the hardware is able to track future writes.
342                  */
343
344                 vma = i915_gem_object_ggtt_pin_ww(obj, &ww, &view, 0, 0, flags);
345                 if (IS_ERR(vma) && vma != ERR_PTR(-EDEADLK)) {
346                         flags = PIN_MAPPABLE;
347                         view.type = I915_GGTT_VIEW_PARTIAL;
348                         vma = i915_gem_object_ggtt_pin_ww(obj, &ww, &view, 0, 0, flags);
349                 }
350
351                 /* The entire mappable GGTT is pinned? Unexpected! */
352                 GEM_BUG_ON(vma == ERR_PTR(-ENOSPC));
353         }
354         if (IS_ERR(vma)) {
355                 ret = PTR_ERR(vma);
356                 goto err_reset;
357         }
358
359         /* Access to snoopable pages through the GTT is incoherent. */
360         if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(i915)) {
361                 ret = -EFAULT;
362                 goto err_unpin;
363         }
364
365         ret = i915_vma_pin_fence(vma);
366         if (ret)
367                 goto err_unpin;
368
369         /* Finally, remap it using the new GTT offset */
370         ret = io_mapping_map_user(&ggtt->iomap, area, area->vm_start +
371                         (vma->ggtt_view.partial.offset << PAGE_SHIFT),
372                         (ggtt->gmadr.start + vma->node.start) >> PAGE_SHIFT,
373                         min_t(u64, vma->size, area->vm_end - area->vm_start));
374         if (ret)
375                 goto err_fence;
376
377         assert_rpm_wakelock_held(rpm);
378
379         /* Mark as being mmapped into userspace for later revocation */
380         mutex_lock(&i915->ggtt.vm.mutex);
381         if (!i915_vma_set_userfault(vma) && !obj->userfault_count++)
382                 list_add(&obj->userfault_link, &i915->ggtt.userfault_list);
383         mutex_unlock(&i915->ggtt.vm.mutex);
384
385         /* Track the mmo associated with the fenced vma */
386         vma->mmo = mmo;
387
388         if (IS_ACTIVE(CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND))
389                 intel_wakeref_auto(&i915->ggtt.userfault_wakeref,
390                                    msecs_to_jiffies_timeout(CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND));
391
392         if (write) {
393                 GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
394                 i915_vma_set_ggtt_write(vma);
395                 obj->mm.dirty = true;
396         }
397
398 err_fence:
399         i915_vma_unpin_fence(vma);
400 err_unpin:
401         __i915_vma_unpin(vma);
402 err_reset:
403         intel_gt_reset_unlock(ggtt->vm.gt, srcu);
404 err_pages:
405         i915_gem_object_unpin_pages(obj);
406 err_rpm:
407         if (ret == -EDEADLK) {
408                 ret = i915_gem_ww_ctx_backoff(&ww);
409                 if (!ret)
410                         goto retry;
411         }
412         i915_gem_ww_ctx_fini(&ww);
413         intel_runtime_pm_put(rpm, wakeref);
414         return i915_error_to_vmf_fault(ret);
415 }
416
417 static int
418 vm_access(struct vm_area_struct *area, unsigned long addr,
419           void *buf, int len, int write)
420 {
421         struct i915_mmap_offset *mmo = area->vm_private_data;
422         struct drm_i915_gem_object *obj = mmo->obj;
423         struct i915_gem_ww_ctx ww;
424         void *vaddr;
425         int err = 0;
426
427         if (i915_gem_object_is_readonly(obj) && write)
428                 return -EACCES;
429
430         addr -= area->vm_start;
431         if (addr >= obj->base.size)
432                 return -EINVAL;
433
434         i915_gem_ww_ctx_init(&ww, true);
435 retry:
436         err = i915_gem_object_lock(obj, &ww);
437         if (err)
438                 goto out;
439
440         /* As this is primarily for debugging, let's focus on simplicity */
441         vaddr = i915_gem_object_pin_map(obj, I915_MAP_FORCE_WC);
442         if (IS_ERR(vaddr)) {
443                 err = PTR_ERR(vaddr);
444                 goto out;
445         }
446
447         if (write) {
448                 memcpy(vaddr + addr, buf, len);
449                 __i915_gem_object_flush_map(obj, addr, len);
450         } else {
451                 memcpy(buf, vaddr + addr, len);
452         }
453
454         i915_gem_object_unpin_map(obj);
455 out:
456         if (err == -EDEADLK) {
457                 err = i915_gem_ww_ctx_backoff(&ww);
458                 if (!err)
459                         goto retry;
460         }
461         i915_gem_ww_ctx_fini(&ww);
462
463         if (err)
464                 return err;
465
466         return len;
467 }
468
469 void __i915_gem_object_release_mmap_gtt(struct drm_i915_gem_object *obj)
470 {
471         struct i915_vma *vma;
472
473         GEM_BUG_ON(!obj->userfault_count);
474
475         for_each_ggtt_vma(vma, obj)
476                 i915_vma_revoke_mmap(vma);
477
478         GEM_BUG_ON(obj->userfault_count);
479 }
480
481 /*
482  * It is vital that we remove the page mapping if we have mapped a tiled
483  * object through the GTT and then lose the fence register due to
484  * resource pressure. Similarly if the object has been moved out of the
485  * aperture, than pages mapped into userspace must be revoked. Removing the
486  * mapping will then trigger a page fault on the next user access, allowing
487  * fixup by vm_fault_gtt().
488  */
489 void i915_gem_object_release_mmap_gtt(struct drm_i915_gem_object *obj)
490 {
491         struct drm_i915_private *i915 = to_i915(obj->base.dev);
492         intel_wakeref_t wakeref;
493
494         /*
495          * Serialisation between user GTT access and our code depends upon
496          * revoking the CPU's PTE whilst the mutex is held. The next user
497          * pagefault then has to wait until we release the mutex.
498          *
499          * Note that RPM complicates somewhat by adding an additional
500          * requirement that operations to the GGTT be made holding the RPM
501          * wakeref.
502          */
503         wakeref = intel_runtime_pm_get(&i915->runtime_pm);
504         mutex_lock(&i915->ggtt.vm.mutex);
505
506         if (!obj->userfault_count)
507                 goto out;
508
509         __i915_gem_object_release_mmap_gtt(obj);
510
511         /*
512          * Ensure that the CPU's PTE are revoked and there are not outstanding
513          * memory transactions from userspace before we return. The TLB
514          * flushing implied above by changing the PTE above *should* be
515          * sufficient, an extra barrier here just provides us with a bit
516          * of paranoid documentation about our requirement to serialise
517          * memory writes before touching registers / GSM.
518          */
519         wmb();
520
521 out:
522         mutex_unlock(&i915->ggtt.vm.mutex);
523         intel_runtime_pm_put(&i915->runtime_pm, wakeref);
524 }
525
526 void i915_gem_object_release_mmap_offset(struct drm_i915_gem_object *obj)
527 {
528         struct i915_mmap_offset *mmo, *mn;
529
530         spin_lock(&obj->mmo.lock);
531         rbtree_postorder_for_each_entry_safe(mmo, mn,
532                                              &obj->mmo.offsets, offset) {
533                 /*
534                  * vma_node_unmap for GTT mmaps handled already in
535                  * __i915_gem_object_release_mmap_gtt
536                  */
537                 if (mmo->mmap_type == I915_MMAP_TYPE_GTT)
538                         continue;
539
540                 spin_unlock(&obj->mmo.lock);
541                 drm_vma_node_unmap(&mmo->vma_node,
542                                    obj->base.dev->anon_inode->i_mapping);
543                 spin_lock(&obj->mmo.lock);
544         }
545         spin_unlock(&obj->mmo.lock);
546 }
547
548 static struct i915_mmap_offset *
549 lookup_mmo(struct drm_i915_gem_object *obj,
550            enum i915_mmap_type mmap_type)
551 {
552         struct rb_node *rb;
553
554         spin_lock(&obj->mmo.lock);
555         rb = obj->mmo.offsets.rb_node;
556         while (rb) {
557                 struct i915_mmap_offset *mmo =
558                         rb_entry(rb, typeof(*mmo), offset);
559
560                 if (mmo->mmap_type == mmap_type) {
561                         spin_unlock(&obj->mmo.lock);
562                         return mmo;
563                 }
564
565                 if (mmo->mmap_type < mmap_type)
566                         rb = rb->rb_right;
567                 else
568                         rb = rb->rb_left;
569         }
570         spin_unlock(&obj->mmo.lock);
571
572         return NULL;
573 }
574
575 static struct i915_mmap_offset *
576 insert_mmo(struct drm_i915_gem_object *obj, struct i915_mmap_offset *mmo)
577 {
578         struct rb_node *rb, **p;
579
580         spin_lock(&obj->mmo.lock);
581         rb = NULL;
582         p = &obj->mmo.offsets.rb_node;
583         while (*p) {
584                 struct i915_mmap_offset *pos;
585
586                 rb = *p;
587                 pos = rb_entry(rb, typeof(*pos), offset);
588
589                 if (pos->mmap_type == mmo->mmap_type) {
590                         spin_unlock(&obj->mmo.lock);
591                         drm_vma_offset_remove(obj->base.dev->vma_offset_manager,
592                                               &mmo->vma_node);
593                         kfree(mmo);
594                         return pos;
595                 }
596
597                 if (pos->mmap_type < mmo->mmap_type)
598                         p = &rb->rb_right;
599                 else
600                         p = &rb->rb_left;
601         }
602         rb_link_node(&mmo->offset, rb, p);
603         rb_insert_color(&mmo->offset, &obj->mmo.offsets);
604         spin_unlock(&obj->mmo.lock);
605
606         return mmo;
607 }
608
609 static struct i915_mmap_offset *
610 mmap_offset_attach(struct drm_i915_gem_object *obj,
611                    enum i915_mmap_type mmap_type,
612                    struct drm_file *file)
613 {
614         struct drm_i915_private *i915 = to_i915(obj->base.dev);
615         struct i915_mmap_offset *mmo;
616         int err;
617
618         mmo = lookup_mmo(obj, mmap_type);
619         if (mmo)
620                 goto out;
621
622         mmo = kmalloc(sizeof(*mmo), GFP_KERNEL);
623         if (!mmo)
624                 return ERR_PTR(-ENOMEM);
625
626         mmo->obj = obj;
627         mmo->mmap_type = mmap_type;
628         drm_vma_node_reset(&mmo->vma_node);
629
630         err = drm_vma_offset_add(obj->base.dev->vma_offset_manager,
631                                  &mmo->vma_node, obj->base.size / PAGE_SIZE);
632         if (likely(!err))
633                 goto insert;
634
635         /* Attempt to reap some mmap space from dead objects */
636         err = intel_gt_retire_requests_timeout(&i915->gt, MAX_SCHEDULE_TIMEOUT);
637         if (err)
638                 goto err;
639
640         i915_gem_drain_freed_objects(i915);
641         err = drm_vma_offset_add(obj->base.dev->vma_offset_manager,
642                                  &mmo->vma_node, obj->base.size / PAGE_SIZE);
643         if (err)
644                 goto err;
645
646 insert:
647         mmo = insert_mmo(obj, mmo);
648         GEM_BUG_ON(lookup_mmo(obj, mmap_type) != mmo);
649 out:
650         if (file)
651                 drm_vma_node_allow(&mmo->vma_node, file);
652         return mmo;
653
654 err:
655         kfree(mmo);
656         return ERR_PTR(err);
657 }
658
659 static int
660 __assign_mmap_offset(struct drm_file *file,
661                      u32 handle,
662                      enum i915_mmap_type mmap_type,
663                      u64 *offset)
664 {
665         struct drm_i915_gem_object *obj;
666         struct i915_mmap_offset *mmo;
667         int err;
668
669         obj = i915_gem_object_lookup(file, handle);
670         if (!obj)
671                 return -ENOENT;
672
673         if (i915_gem_object_never_mmap(obj)) {
674                 err = -ENODEV;
675                 goto out;
676         }
677
678         if (mmap_type != I915_MMAP_TYPE_GTT &&
679             !i915_gem_object_has_struct_page(obj) &&
680             !i915_gem_object_type_has(obj, I915_GEM_OBJECT_HAS_IOMEM)) {
681                 err = -ENODEV;
682                 goto out;
683         }
684
685         mmo = mmap_offset_attach(obj, mmap_type, file);
686         if (IS_ERR(mmo)) {
687                 err = PTR_ERR(mmo);
688                 goto out;
689         }
690
691         *offset = drm_vma_node_offset_addr(&mmo->vma_node);
692         err = 0;
693 out:
694         i915_gem_object_put(obj);
695         return err;
696 }
697
698 int
699 i915_gem_dumb_mmap_offset(struct drm_file *file,
700                           struct drm_device *dev,
701                           u32 handle,
702                           u64 *offset)
703 {
704         enum i915_mmap_type mmap_type;
705
706         if (boot_cpu_has(X86_FEATURE_PAT))
707                 mmap_type = I915_MMAP_TYPE_WC;
708         else if (!i915_ggtt_has_aperture(&to_i915(dev)->ggtt))
709                 return -ENODEV;
710         else
711                 mmap_type = I915_MMAP_TYPE_GTT;
712
713         return __assign_mmap_offset(file, handle, mmap_type, offset);
714 }
715
716 /**
717  * i915_gem_mmap_offset_ioctl - prepare an object for GTT mmap'ing
718  * @dev: DRM device
719  * @data: GTT mapping ioctl data
720  * @file: GEM object info
721  *
722  * Simply returns the fake offset to userspace so it can mmap it.
723  * The mmap call will end up in drm_gem_mmap(), which will set things
724  * up so we can get faults in the handler above.
725  *
726  * The fault handler will take care of binding the object into the GTT
727  * (since it may have been evicted to make room for something), allocating
728  * a fence register, and mapping the appropriate aperture address into
729  * userspace.
730  */
731 int
732 i915_gem_mmap_offset_ioctl(struct drm_device *dev, void *data,
733                            struct drm_file *file)
734 {
735         struct drm_i915_private *i915 = to_i915(dev);
736         struct drm_i915_gem_mmap_offset *args = data;
737         enum i915_mmap_type type;
738         int err;
739
740         /*
741          * Historically we failed to check args.pad and args.offset
742          * and so we cannot use those fields for user input and we cannot
743          * add -EINVAL for them as the ABI is fixed, i.e. old userspace
744          * may be feeding in garbage in those fields.
745          *
746          * if (args->pad) return -EINVAL; is verbotten!
747          */
748
749         err = i915_user_extensions(u64_to_user_ptr(args->extensions),
750                                    NULL, 0, NULL);
751         if (err)
752                 return err;
753
754         switch (args->flags) {
755         case I915_MMAP_OFFSET_GTT:
756                 if (!i915_ggtt_has_aperture(&i915->ggtt))
757                         return -ENODEV;
758                 type = I915_MMAP_TYPE_GTT;
759                 break;
760
761         case I915_MMAP_OFFSET_WC:
762                 if (!boot_cpu_has(X86_FEATURE_PAT))
763                         return -ENODEV;
764                 type = I915_MMAP_TYPE_WC;
765                 break;
766
767         case I915_MMAP_OFFSET_WB:
768                 type = I915_MMAP_TYPE_WB;
769                 break;
770
771         case I915_MMAP_OFFSET_UC:
772                 if (!boot_cpu_has(X86_FEATURE_PAT))
773                         return -ENODEV;
774                 type = I915_MMAP_TYPE_UC;
775                 break;
776
777         default:
778                 return -EINVAL;
779         }
780
781         return __assign_mmap_offset(file, args->handle, type, &args->offset);
782 }
783
784 static void vm_open(struct vm_area_struct *vma)
785 {
786         struct i915_mmap_offset *mmo = vma->vm_private_data;
787         struct drm_i915_gem_object *obj = mmo->obj;
788
789         GEM_BUG_ON(!obj);
790         i915_gem_object_get(obj);
791 }
792
793 static void vm_close(struct vm_area_struct *vma)
794 {
795         struct i915_mmap_offset *mmo = vma->vm_private_data;
796         struct drm_i915_gem_object *obj = mmo->obj;
797
798         GEM_BUG_ON(!obj);
799         i915_gem_object_put(obj);
800 }
801
802 static const struct vm_operations_struct vm_ops_gtt = {
803         .fault = vm_fault_gtt,
804         .access = vm_access,
805         .open = vm_open,
806         .close = vm_close,
807 };
808
809 static const struct vm_operations_struct vm_ops_cpu = {
810         .fault = vm_fault_cpu,
811         .access = vm_access,
812         .open = vm_open,
813         .close = vm_close,
814 };
815
816 static int singleton_release(struct inode *inode, struct file *file)
817 {
818         struct drm_i915_private *i915 = file->private_data;
819
820         cmpxchg(&i915->gem.mmap_singleton, file, NULL);
821         drm_dev_put(&i915->drm);
822
823         return 0;
824 }
825
826 static const struct file_operations singleton_fops = {
827         .owner = THIS_MODULE,
828         .release = singleton_release,
829 };
830
831 static struct file *mmap_singleton(struct drm_i915_private *i915)
832 {
833         struct file *file;
834
835         rcu_read_lock();
836         file = READ_ONCE(i915->gem.mmap_singleton);
837         if (file && !get_file_rcu(file))
838                 file = NULL;
839         rcu_read_unlock();
840         if (file)
841                 return file;
842
843         file = anon_inode_getfile("i915.gem", &singleton_fops, i915, O_RDWR);
844         if (IS_ERR(file))
845                 return file;
846
847         /* Everyone shares a single global address space */
848         file->f_mapping = i915->drm.anon_inode->i_mapping;
849
850         smp_store_mb(i915->gem.mmap_singleton, file);
851         drm_dev_get(&i915->drm);
852
853         return file;
854 }
855
856 /*
857  * This overcomes the limitation in drm_gem_mmap's assignment of a
858  * drm_gem_object as the vma->vm_private_data. Since we need to
859  * be able to resolve multiple mmap offsets which could be tied
860  * to a single gem object.
861  */
862 int i915_gem_mmap(struct file *filp, struct vm_area_struct *vma)
863 {
864         struct drm_vma_offset_node *node;
865         struct drm_file *priv = filp->private_data;
866         struct drm_device *dev = priv->minor->dev;
867         struct drm_i915_gem_object *obj = NULL;
868         struct i915_mmap_offset *mmo = NULL;
869         struct file *anon;
870
871         if (drm_dev_is_unplugged(dev))
872                 return -ENODEV;
873
874         rcu_read_lock();
875         drm_vma_offset_lock_lookup(dev->vma_offset_manager);
876         node = drm_vma_offset_exact_lookup_locked(dev->vma_offset_manager,
877                                                   vma->vm_pgoff,
878                                                   vma_pages(vma));
879         if (node && drm_vma_node_is_allowed(node, priv)) {
880                 /*
881                  * Skip 0-refcnted objects as it is in the process of being
882                  * destroyed and will be invalid when the vma manager lock
883                  * is released.
884                  */
885                 mmo = container_of(node, struct i915_mmap_offset, vma_node);
886                 obj = i915_gem_object_get_rcu(mmo->obj);
887         }
888         drm_vma_offset_unlock_lookup(dev->vma_offset_manager);
889         rcu_read_unlock();
890         if (!obj)
891                 return node ? -EACCES : -EINVAL;
892
893         if (i915_gem_object_is_readonly(obj)) {
894                 if (vma->vm_flags & VM_WRITE) {
895                         i915_gem_object_put(obj);
896                         return -EINVAL;
897                 }
898                 vma->vm_flags &= ~VM_MAYWRITE;
899         }
900
901         anon = mmap_singleton(to_i915(dev));
902         if (IS_ERR(anon)) {
903                 i915_gem_object_put(obj);
904                 return PTR_ERR(anon);
905         }
906
907         vma->vm_flags |= VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
908         vma->vm_private_data = mmo;
909
910         /*
911          * We keep the ref on mmo->obj, not vm_file, but we require
912          * vma->vm_file->f_mapping, see vma_link(), for later revocation.
913          * Our userspace is accustomed to having per-file resource cleanup
914          * (i.e. contexts, objects and requests) on their close(fd), which
915          * requires avoiding extraneous references to their filp, hence why
916          * we prefer to use an anonymous file for their mmaps.
917          */
918         vma_set_file(vma, anon);
919         /* Drop the initial creation reference, the vma is now holding one. */
920         fput(anon);
921
922         switch (mmo->mmap_type) {
923         case I915_MMAP_TYPE_WC:
924                 vma->vm_page_prot =
925                         pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
926                 vma->vm_ops = &vm_ops_cpu;
927                 break;
928
929         case I915_MMAP_TYPE_WB:
930                 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
931                 vma->vm_ops = &vm_ops_cpu;
932                 break;
933
934         case I915_MMAP_TYPE_UC:
935                 vma->vm_page_prot =
936                         pgprot_noncached(vm_get_page_prot(vma->vm_flags));
937                 vma->vm_ops = &vm_ops_cpu;
938                 break;
939
940         case I915_MMAP_TYPE_GTT:
941                 vma->vm_page_prot =
942                         pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
943                 vma->vm_ops = &vm_ops_gtt;
944                 break;
945         }
946         vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot);
947
948         return 0;
949 }
950
951 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
952 #include "selftests/i915_gem_mman.c"
953 #endif