drm/i915: Update to Linux commit b224c4dc70cdd5f42d24a7057148c6ace90e4f4e
[dragonfly.git] / sys / dev / drm / i915 / i915_gem_gtt.c
1 /*
2  * Copyright © 2010 Daniel Vetter
3  * Copyright © 2011-2014 Intel Corporation
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  *
24  */
25
26 #include <linux/seq_file.h>
27 #include <linux/stop_machine.h>
28 #include <drm/drmP.h>
29 #include <drm/i915_drm.h>
30 #include "i915_drv.h"
31 #include "i915_vgpu.h"
32 #include "i915_trace.h"
33 #include "intel_drv.h"
34
35 #include <linux/bitmap.h>
36
37 #include <sys/mplock2.h>
38
39 /**
40  * DOC: Global GTT views
41  *
42  * Background and previous state
43  *
44  * Historically objects could exists (be bound) in global GTT space only as
45  * singular instances with a view representing all of the object's backing pages
46  * in a linear fashion. This view will be called a normal view.
47  *
48  * To support multiple views of the same object, where the number of mapped
49  * pages is not equal to the backing store, or where the layout of the pages
50  * is not linear, concept of a GGTT view was added.
51  *
52  * One example of an alternative view is a stereo display driven by a single
53  * image. In this case we would have a framebuffer looking like this
54  * (2x2 pages):
55  *
56  *    12
57  *    34
58  *
59  * Above would represent a normal GGTT view as normally mapped for GPU or CPU
60  * rendering. In contrast, fed to the display engine would be an alternative
61  * view which could look something like this:
62  *
63  *   1212
64  *   3434
65  *
66  * In this example both the size and layout of pages in the alternative view is
67  * different from the normal view.
68  *
69  * Implementation and usage
70  *
71  * GGTT views are implemented using VMAs and are distinguished via enum
72  * i915_ggtt_view_type and struct i915_ggtt_view.
73  *
74  * A new flavour of core GEM functions which work with GGTT bound objects were
75  * added with the _ggtt_ infix, and sometimes with _view postfix to avoid
76  * renaming  in large amounts of code. They take the struct i915_ggtt_view
77  * parameter encapsulating all metadata required to implement a view.
78  *
79  * As a helper for callers which are only interested in the normal view,
80  * globally const i915_ggtt_view_normal singleton instance exists. All old core
81  * GEM API functions, the ones not taking the view parameter, are operating on,
82  * or with the normal GGTT view.
83  *
84  * Code wanting to add or use a new GGTT view needs to:
85  *
86  * 1. Add a new enum with a suitable name.
87  * 2. Extend the metadata in the i915_ggtt_view structure if required.
88  * 3. Add support to i915_get_vma_pages().
89  *
90  * New views are required to build a scatter-gather table from within the
91  * i915_get_vma_pages function. This table is stored in the vma.ggtt_view and
92  * exists for the lifetime of an VMA.
93  *
94  * Core API is designed to have copy semantics which means that passed in
95  * struct i915_ggtt_view does not need to be persistent (left around after
96  * calling the core API functions).
97  *
98  */
99
100 static inline struct i915_ggtt *
101 i915_vm_to_ggtt(struct i915_address_space *vm)
102 {
103         GEM_BUG_ON(!i915_is_ggtt(vm));
104         return container_of(vm, struct i915_ggtt, base);
105 }
106
107 static int
108 i915_get_ggtt_vma_pages(struct i915_vma *vma);
109
110 const struct i915_ggtt_view i915_ggtt_view_normal = {
111         .type = I915_GGTT_VIEW_NORMAL,
112 };
113 const struct i915_ggtt_view i915_ggtt_view_rotated = {
114         .type = I915_GGTT_VIEW_ROTATED,
115 };
116
117 int intel_sanitize_enable_ppgtt(struct drm_i915_private *dev_priv,
118                                 int enable_ppgtt)
119 {
120         bool has_aliasing_ppgtt;
121         bool has_full_ppgtt;
122         bool has_full_48bit_ppgtt;
123
124         has_aliasing_ppgtt = INTEL_GEN(dev_priv) >= 6;
125         has_full_ppgtt = INTEL_GEN(dev_priv) >= 7;
126         has_full_48bit_ppgtt =
127                 IS_BROADWELL(dev_priv) || INTEL_GEN(dev_priv) >= 9;
128
129         if (intel_vgpu_active(dev_priv))
130                 has_full_ppgtt = false; /* emulation is too hard */
131
132         if (!has_aliasing_ppgtt)
133                 return 0;
134
135         /*
136          * We don't allow disabling PPGTT for gen9+ as it's a requirement for
137          * execlists, the sole mechanism available to submit work.
138          */
139         if (enable_ppgtt == 0 && INTEL_GEN(dev_priv) < 9)
140                 return 0;
141
142         if (enable_ppgtt == 1)
143                 return 1;
144
145         if (enable_ppgtt == 2 && has_full_ppgtt)
146                 return 2;
147
148         if (enable_ppgtt == 3 && has_full_48bit_ppgtt)
149                 return 3;
150
151 #ifdef CONFIG_INTEL_IOMMU
152         /* Disable ppgtt on SNB if VT-d is on. */
153         if (IS_GEN6(dev_priv) && intel_iommu_gfx_mapped) {
154                 DRM_INFO("Disabling PPGTT because VT-d is on\n");
155                 return 0;
156         }
157 #endif
158
159         /* Early VLV doesn't have this */
160         if (IS_VALLEYVIEW(dev_priv) && dev_priv->drm.pdev->revision < 0xb) {
161                 DRM_DEBUG_DRIVER("disabling PPGTT on pre-B3 step VLV\n");
162                 return 0;
163         }
164
165         if (INTEL_GEN(dev_priv) >= 8 && i915.enable_execlists)
166                 return has_full_48bit_ppgtt ? 3 : 2;
167         else
168                 return has_aliasing_ppgtt ? 1 : 0;
169 }
170
171 static int ppgtt_bind_vma(struct i915_vma *vma,
172                           enum i915_cache_level cache_level,
173                           u32 unused)
174 {
175         u32 pte_flags = 0;
176
177         /* Currently applicable only to VLV */
178         if (vma->obj->gt_ro)
179                 pte_flags |= PTE_READ_ONLY;
180
181         vma->vm->insert_entries(vma->vm, vma->obj->pages, vma->node.start,
182                                 cache_level, pte_flags);
183
184         return 0;
185 }
186
187 static void ppgtt_unbind_vma(struct i915_vma *vma)
188 {
189         vma->vm->clear_range(vma->vm,
190                              vma->node.start,
191                              vma->obj->base.size,
192                              true);
193 }
194
195 static gen8_pte_t gen8_pte_encode(dma_addr_t addr,
196                                   enum i915_cache_level level,
197                                   bool valid)
198 {
199         gen8_pte_t pte = valid ? _PAGE_PRESENT | _PAGE_RW : 0;
200         pte |= addr;
201
202         switch (level) {
203         case I915_CACHE_NONE:
204                 pte |= PPAT_UNCACHED_INDEX;
205                 break;
206         case I915_CACHE_WT:
207                 pte |= PPAT_DISPLAY_ELLC_INDEX;
208                 break;
209         default:
210                 pte |= PPAT_CACHED_INDEX;
211                 break;
212         }
213
214         return pte;
215 }
216
217 static gen8_pde_t gen8_pde_encode(const dma_addr_t addr,
218                                   const enum i915_cache_level level)
219 {
220         gen8_pde_t pde = _PAGE_PRESENT | _PAGE_RW;
221         pde |= addr;
222         if (level != I915_CACHE_NONE)
223                 pde |= PPAT_CACHED_PDE_INDEX;
224         else
225                 pde |= PPAT_UNCACHED_INDEX;
226         return pde;
227 }
228
229 #define gen8_pdpe_encode gen8_pde_encode
230 #define gen8_pml4e_encode gen8_pde_encode
231
232 static gen6_pte_t snb_pte_encode(dma_addr_t addr,
233                                  enum i915_cache_level level,
234                                  bool valid, u32 unused)
235 {
236         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
237         pte |= GEN6_PTE_ADDR_ENCODE(addr);
238
239         switch (level) {
240         case I915_CACHE_L3_LLC:
241         case I915_CACHE_LLC:
242                 pte |= GEN6_PTE_CACHE_LLC;
243                 break;
244         case I915_CACHE_NONE:
245                 pte |= GEN6_PTE_UNCACHED;
246                 break;
247         default:
248                 MISSING_CASE(level);
249         }
250
251         return pte;
252 }
253
254 static gen6_pte_t ivb_pte_encode(dma_addr_t addr,
255                                  enum i915_cache_level level,
256                                  bool valid, u32 unused)
257 {
258         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
259         pte |= GEN6_PTE_ADDR_ENCODE(addr);
260
261         switch (level) {
262         case I915_CACHE_L3_LLC:
263                 pte |= GEN7_PTE_CACHE_L3_LLC;
264                 break;
265         case I915_CACHE_LLC:
266                 pte |= GEN6_PTE_CACHE_LLC;
267                 break;
268         case I915_CACHE_NONE:
269                 pte |= GEN6_PTE_UNCACHED;
270                 break;
271         default:
272                 MISSING_CASE(level);
273         }
274
275         return pte;
276 }
277
278 static gen6_pte_t byt_pte_encode(dma_addr_t addr,
279                                  enum i915_cache_level level,
280                                  bool valid, u32 flags)
281 {
282         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
283         pte |= GEN6_PTE_ADDR_ENCODE(addr);
284
285         if (!(flags & PTE_READ_ONLY))
286                 pte |= BYT_PTE_WRITEABLE;
287
288         if (level != I915_CACHE_NONE)
289                 pte |= BYT_PTE_SNOOPED_BY_CPU_CACHES;
290
291         return pte;
292 }
293
294 static gen6_pte_t hsw_pte_encode(dma_addr_t addr,
295                                  enum i915_cache_level level,
296                                  bool valid, u32 unused)
297 {
298         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
299         pte |= HSW_PTE_ADDR_ENCODE(addr);
300
301         if (level != I915_CACHE_NONE)
302                 pte |= HSW_WB_LLC_AGE3;
303
304         return pte;
305 }
306
307 static gen6_pte_t iris_pte_encode(dma_addr_t addr,
308                                   enum i915_cache_level level,
309                                   bool valid, u32 unused)
310 {
311         gen6_pte_t pte = valid ? GEN6_PTE_VALID : 0;
312         pte |= HSW_PTE_ADDR_ENCODE(addr);
313
314         switch (level) {
315         case I915_CACHE_NONE:
316                 break;
317         case I915_CACHE_WT:
318                 pte |= HSW_WT_ELLC_LLC_AGE3;
319                 break;
320         default:
321                 pte |= HSW_WB_ELLC_LLC_AGE3;
322                 break;
323         }
324
325         return pte;
326 }
327
328 static int __setup_page_dma(struct drm_device *dev,
329                             struct i915_page_dma *p, gfp_t flags)
330 {
331         struct device *device = &dev->pdev->dev;
332
333         p->page = alloc_page(flags);
334         if (!p->page)
335                 return -ENOMEM;
336
337         p->daddr = dma_map_page(device,
338                                 p->page, 0, 4096, PCI_DMA_BIDIRECTIONAL);
339
340         if (dma_mapping_error(device, p->daddr)) {
341                 __free_page(p->page);
342                 return -EINVAL;
343         }
344
345         return 0;
346 }
347
348 static int setup_page_dma(struct drm_device *dev, struct i915_page_dma *p)
349 {
350         return __setup_page_dma(dev, p, GFP_KERNEL);
351 }
352
353 static void cleanup_page_dma(struct drm_device *dev, struct i915_page_dma *p)
354 {
355         if (WARN_ON(!p->page))
356                 return;
357
358         dma_unmap_page(&dev->pdev->dev, p->daddr, 4096, PCI_DMA_BIDIRECTIONAL);
359         __free_page(p->page);
360         memset(p, 0, sizeof(*p));
361 }
362
363 static void *kmap_page_dma(struct i915_page_dma *p)
364 {
365         return kmap_atomic(p->page);
366 }
367
368 /* We use the flushing unmap only with ppgtt structures:
369  * page directories, page tables and scratch pages.
370  */
371 static void kunmap_page_dma(struct drm_device *dev, void *vaddr)
372 {
373         /* There are only few exceptions for gen >=6. chv and bxt.
374          * And we are not sure about the latter so play safe for now.
375          */
376         if (IS_CHERRYVIEW(dev) || IS_BROXTON(dev))
377                 drm_clflush_virt_range(vaddr, PAGE_SIZE);
378
379         kunmap_atomic(vaddr);
380 }
381
382 #define kmap_px(px) kmap_page_dma(px_base(px))
383 #define kunmap_px(ppgtt, vaddr) kunmap_page_dma((ppgtt)->base.dev, (vaddr))
384
385 #define setup_px(dev, px) setup_page_dma((dev), px_base(px))
386 #define cleanup_px(dev, px) cleanup_page_dma((dev), px_base(px))
387 #define fill_px(dev, px, v) fill_page_dma((dev), px_base(px), (v))
388 #define fill32_px(dev, px, v) fill_page_dma_32((dev), px_base(px), (v))
389
390 static void fill_page_dma(struct drm_device *dev, struct i915_page_dma *p,
391                           const uint64_t val)
392 {
393         int i;
394         uint64_t * const vaddr = kmap_page_dma(p);
395
396         for (i = 0; i < 512; i++)
397                 vaddr[i] = val;
398
399         kunmap_page_dma(dev, vaddr);
400 }
401
402 static void fill_page_dma_32(struct drm_device *dev, struct i915_page_dma *p,
403                              const uint32_t val32)
404 {
405         uint64_t v = val32;
406
407         v = v << 32 | val32;
408
409         fill_page_dma(dev, p, v);
410 }
411
412 static struct i915_page_scratch *alloc_scratch_page(struct drm_device *dev)
413 {
414         struct i915_page_scratch *sp;
415         int ret;
416
417         sp = kzalloc(sizeof(*sp), GFP_KERNEL);
418         if (sp == NULL)
419                 return ERR_PTR(-ENOMEM);
420
421         ret = __setup_page_dma(dev, px_base(sp), GFP_DMA32 | __GFP_ZERO);
422         if (ret) {
423                 kfree(sp);
424                 return ERR_PTR(ret);
425         }
426
427         set_pages_uc(px_page(sp), 1);
428
429         return sp;
430 }
431
432 static void free_scratch_page(struct drm_device *dev,
433                               struct i915_page_scratch *sp)
434 {
435         set_pages_wb(px_page(sp), 1);
436
437         cleanup_px(dev, sp);
438         kfree(sp);
439 }
440
441 static struct i915_page_table *alloc_pt(struct drm_device *dev)
442 {
443         struct i915_page_table *pt;
444         const size_t count = INTEL_INFO(dev)->gen >= 8 ?
445                 GEN8_PTES : GEN6_PTES;
446         int ret = -ENOMEM;
447
448         pt = kzalloc(sizeof(*pt), GFP_KERNEL);
449         if (!pt)
450                 return ERR_PTR(-ENOMEM);
451
452         pt->used_ptes = kcalloc(BITS_TO_LONGS(count), sizeof(*pt->used_ptes),
453                                 GFP_KERNEL);
454
455         if (!pt->used_ptes)
456                 goto fail_bitmap;
457
458         ret = setup_px(dev, pt);
459         if (ret)
460                 goto fail_page_m;
461
462         return pt;
463
464 fail_page_m:
465         kfree(pt->used_ptes);
466 fail_bitmap:
467         kfree(pt);
468
469         return ERR_PTR(ret);
470 }
471
472 static void free_pt(struct drm_device *dev, struct i915_page_table *pt)
473 {
474         cleanup_px(dev, pt);
475         kfree(pt->used_ptes);
476         kfree(pt);
477 }
478
479 static void gen8_initialize_pt(struct i915_address_space *vm,
480                                struct i915_page_table *pt)
481 {
482         gen8_pte_t scratch_pte;
483
484         scratch_pte = gen8_pte_encode(px_dma(vm->scratch_page),
485                                       I915_CACHE_LLC, true);
486
487         fill_px(vm->dev, pt, scratch_pte);
488 }
489
490 static void gen6_initialize_pt(struct i915_address_space *vm,
491                                struct i915_page_table *pt)
492 {
493         gen6_pte_t scratch_pte;
494
495         WARN_ON(px_dma(vm->scratch_page) == 0);
496
497         scratch_pte = vm->pte_encode(px_dma(vm->scratch_page),
498                                      I915_CACHE_LLC, true, 0);
499
500         fill32_px(vm->dev, pt, scratch_pte);
501 }
502
503 static struct i915_page_directory *alloc_pd(struct drm_device *dev)
504 {
505         struct i915_page_directory *pd;
506         int ret = -ENOMEM;
507
508         pd = kzalloc(sizeof(*pd), GFP_KERNEL);
509         if (!pd)
510                 return ERR_PTR(-ENOMEM);
511
512         pd->used_pdes = kcalloc(BITS_TO_LONGS(I915_PDES),
513                                 sizeof(*pd->used_pdes), GFP_KERNEL);
514         if (!pd->used_pdes)
515                 goto fail_bitmap;
516
517         ret = setup_px(dev, pd);
518         if (ret)
519                 goto fail_page_m;
520
521         return pd;
522
523 fail_page_m:
524         kfree(pd->used_pdes);
525 fail_bitmap:
526         kfree(pd);
527
528         return ERR_PTR(ret);
529 }
530
531 static void free_pd(struct drm_device *dev, struct i915_page_directory *pd)
532 {
533         if (px_page(pd)) {
534                 cleanup_px(dev, pd);
535                 kfree(pd->used_pdes);
536                 kfree(pd);
537         }
538 }
539
540 static void gen8_initialize_pd(struct i915_address_space *vm,
541                                struct i915_page_directory *pd)
542 {
543         gen8_pde_t scratch_pde;
544
545         scratch_pde = gen8_pde_encode(px_dma(vm->scratch_pt), I915_CACHE_LLC);
546
547         fill_px(vm->dev, pd, scratch_pde);
548 }
549
550 static int __pdp_init(struct drm_device *dev,
551                       struct i915_page_directory_pointer *pdp)
552 {
553         size_t pdpes = I915_PDPES_PER_PDP(dev);
554
555         pdp->used_pdpes = kcalloc(BITS_TO_LONGS(pdpes),
556                                   sizeof(unsigned long),
557                                   GFP_KERNEL);
558         if (!pdp->used_pdpes)
559                 return -ENOMEM;
560
561         pdp->page_directory = kcalloc(pdpes, sizeof(*pdp->page_directory),
562                                       GFP_KERNEL);
563         if (!pdp->page_directory) {
564                 kfree(pdp->used_pdpes);
565                 /* the PDP might be the statically allocated top level. Keep it
566                  * as clean as possible */
567                 pdp->used_pdpes = NULL;
568                 return -ENOMEM;
569         }
570
571         return 0;
572 }
573
574 static void __pdp_fini(struct i915_page_directory_pointer *pdp)
575 {
576         kfree(pdp->used_pdpes);
577         kfree(pdp->page_directory);
578         pdp->page_directory = NULL;
579 }
580
581 static struct
582 i915_page_directory_pointer *alloc_pdp(struct drm_device *dev)
583 {
584         struct i915_page_directory_pointer *pdp;
585         int ret = -ENOMEM;
586
587         WARN_ON(!USES_FULL_48BIT_PPGTT(dev));
588
589         pdp = kzalloc(sizeof(*pdp), GFP_KERNEL);
590         if (!pdp)
591                 return ERR_PTR(-ENOMEM);
592
593         ret = __pdp_init(dev, pdp);
594         if (ret)
595                 goto fail_bitmap;
596
597         ret = setup_px(dev, pdp);
598         if (ret)
599                 goto fail_page_m;
600
601         return pdp;
602
603 fail_page_m:
604         __pdp_fini(pdp);
605 fail_bitmap:
606         kfree(pdp);
607
608         return ERR_PTR(ret);
609 }
610
611 static void free_pdp(struct drm_device *dev,
612                      struct i915_page_directory_pointer *pdp)
613 {
614         __pdp_fini(pdp);
615         if (USES_FULL_48BIT_PPGTT(dev)) {
616                 cleanup_px(dev, pdp);
617                 kfree(pdp);
618         }
619 }
620
621 static void gen8_initialize_pdp(struct i915_address_space *vm,
622                                 struct i915_page_directory_pointer *pdp)
623 {
624         gen8_ppgtt_pdpe_t scratch_pdpe;
625
626         scratch_pdpe = gen8_pdpe_encode(px_dma(vm->scratch_pd), I915_CACHE_LLC);
627
628         fill_px(vm->dev, pdp, scratch_pdpe);
629 }
630
631 static void gen8_initialize_pml4(struct i915_address_space *vm,
632                                  struct i915_pml4 *pml4)
633 {
634         gen8_ppgtt_pml4e_t scratch_pml4e;
635
636         scratch_pml4e = gen8_pml4e_encode(px_dma(vm->scratch_pdp),
637                                           I915_CACHE_LLC);
638
639         fill_px(vm->dev, pml4, scratch_pml4e);
640 }
641
642 static void
643 gen8_setup_page_directory(struct i915_hw_ppgtt *ppgtt,
644                           struct i915_page_directory_pointer *pdp,
645                           struct i915_page_directory *pd,
646                           int index)
647 {
648         gen8_ppgtt_pdpe_t *page_directorypo;
649
650         if (!USES_FULL_48BIT_PPGTT(ppgtt->base.dev))
651                 return;
652
653         page_directorypo = kmap_px(pdp);
654         page_directorypo[index] = gen8_pdpe_encode(px_dma(pd), I915_CACHE_LLC);
655         kunmap_px(ppgtt, page_directorypo);
656 }
657
658 static void
659 gen8_setup_page_directory_pointer(struct i915_hw_ppgtt *ppgtt,
660                                   struct i915_pml4 *pml4,
661                                   struct i915_page_directory_pointer *pdp,
662                                   int index)
663 {
664         gen8_ppgtt_pml4e_t *pagemap = kmap_px(pml4);
665
666         WARN_ON(!USES_FULL_48BIT_PPGTT(ppgtt->base.dev));
667         pagemap[index] = gen8_pml4e_encode(px_dma(pdp), I915_CACHE_LLC);
668         kunmap_px(ppgtt, pagemap);
669 }
670
671 /* Broadwell Page Directory Pointer Descriptors */
672 static int gen8_write_pdp(struct drm_i915_gem_request *req,
673                           unsigned entry,
674                           dma_addr_t addr)
675 {
676         struct intel_engine_cs *engine = req->engine;
677         int ret;
678
679         BUG_ON(entry >= 4);
680
681         ret = intel_ring_begin(req, 6);
682         if (ret)
683                 return ret;
684
685         intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
686         intel_ring_emit_reg(engine, GEN8_RING_PDP_UDW(engine, entry));
687         intel_ring_emit(engine, upper_32_bits(addr));
688         intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(1));
689         intel_ring_emit_reg(engine, GEN8_RING_PDP_LDW(engine, entry));
690         intel_ring_emit(engine, lower_32_bits(addr));
691         intel_ring_advance(engine);
692
693         return 0;
694 }
695
696 static int gen8_legacy_mm_switch(struct i915_hw_ppgtt *ppgtt,
697                                  struct drm_i915_gem_request *req)
698 {
699         int i, ret;
700
701         for (i = GEN8_LEGACY_PDPES - 1; i >= 0; i--) {
702                 const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
703
704                 ret = gen8_write_pdp(req, i, pd_daddr);
705                 if (ret)
706                         return ret;
707         }
708
709         return 0;
710 }
711
712 static int gen8_48b_mm_switch(struct i915_hw_ppgtt *ppgtt,
713                               struct drm_i915_gem_request *req)
714 {
715         return gen8_write_pdp(req, 0, px_dma(&ppgtt->pml4));
716 }
717
718 static void gen8_ppgtt_clear_pte_range(struct i915_address_space *vm,
719                                        struct i915_page_directory_pointer *pdp,
720                                        uint64_t start,
721                                        uint64_t length,
722                                        gen8_pte_t scratch_pte)
723 {
724         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
725         gen8_pte_t *pt_vaddr;
726         unsigned pdpe = gen8_pdpe_index(start);
727         unsigned pde = gen8_pde_index(start);
728         unsigned pte = gen8_pte_index(start);
729         unsigned num_entries = length >> PAGE_SHIFT;
730         unsigned last_pte, i;
731
732         if (WARN_ON(!pdp))
733                 return;
734
735         while (num_entries) {
736                 struct i915_page_directory *pd;
737                 struct i915_page_table *pt;
738
739                 if (WARN_ON(!pdp->page_directory[pdpe]))
740                         break;
741
742                 pd = pdp->page_directory[pdpe];
743
744                 if (WARN_ON(!pd->page_table[pde]))
745                         break;
746
747                 pt = pd->page_table[pde];
748
749                 if (WARN_ON(!px_page(pt)))
750                         break;
751
752                 last_pte = pte + num_entries;
753                 if (last_pte > GEN8_PTES)
754                         last_pte = GEN8_PTES;
755
756                 pt_vaddr = kmap_px(pt);
757
758                 for (i = pte; i < last_pte; i++) {
759                         pt_vaddr[i] = scratch_pte;
760                         num_entries--;
761                 }
762
763                 kunmap_px(ppgtt, pt_vaddr);
764
765                 pte = 0;
766                 if (++pde == I915_PDES) {
767                         if (++pdpe == I915_PDPES_PER_PDP(vm->dev))
768                                 break;
769                         pde = 0;
770                 }
771         }
772 }
773
774 static void gen8_ppgtt_clear_range(struct i915_address_space *vm,
775                                    uint64_t start,
776                                    uint64_t length,
777                                    bool use_scratch)
778 {
779         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
780         gen8_pte_t scratch_pte = gen8_pte_encode(px_dma(vm->scratch_page),
781                                                  I915_CACHE_LLC, use_scratch);
782
783         if (!USES_FULL_48BIT_PPGTT(vm->dev)) {
784                 gen8_ppgtt_clear_pte_range(vm, &ppgtt->pdp, start, length,
785                                            scratch_pte);
786         } else {
787                 uint64_t pml4e;
788                 struct i915_page_directory_pointer *pdp;
789
790                 gen8_for_each_pml4e(pdp, &ppgtt->pml4, start, length, pml4e) {
791                         gen8_ppgtt_clear_pte_range(vm, pdp, start, length,
792                                                    scratch_pte);
793                 }
794         }
795 }
796
797 static void
798 gen8_ppgtt_insert_pte_entries(struct i915_address_space *vm,
799                               struct i915_page_directory_pointer *pdp,
800                               struct sg_page_iter *sg_iter,
801                               uint64_t start,
802                               enum i915_cache_level cache_level)
803 {
804         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
805         gen8_pte_t *pt_vaddr;
806         unsigned pdpe = gen8_pdpe_index(start);
807         unsigned pde = gen8_pde_index(start);
808         unsigned pte = gen8_pte_index(start);
809
810         pt_vaddr = NULL;
811
812         while (__sg_page_iter_next(sg_iter)) {
813                 if (pt_vaddr == NULL) {
814                         struct i915_page_directory *pd = pdp->page_directory[pdpe];
815                         struct i915_page_table *pt = pd->page_table[pde];
816                         pt_vaddr = kmap_px(pt);
817                 }
818
819                 pt_vaddr[pte] =
820                         gen8_pte_encode(sg_page_iter_dma_address(sg_iter),
821                                         cache_level, true);
822                 if (++pte == GEN8_PTES) {
823                         kunmap_px(ppgtt, pt_vaddr);
824                         pt_vaddr = NULL;
825                         if (++pde == I915_PDES) {
826                                 if (++pdpe == I915_PDPES_PER_PDP(vm->dev))
827                                         break;
828                                 pde = 0;
829                         }
830                         pte = 0;
831                 }
832         }
833
834         if (pt_vaddr)
835                 kunmap_px(ppgtt, pt_vaddr);
836 }
837
838 static void gen8_ppgtt_insert_entries(struct i915_address_space *vm,
839                                       struct sg_table *pages,
840                                       uint64_t start,
841                                       enum i915_cache_level cache_level,
842                                       u32 unused)
843 {
844         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
845         struct sg_page_iter sg_iter;
846
847         __sg_page_iter_start(&sg_iter, pages->sgl, sg_nents(pages->sgl), 0);
848
849         if (!USES_FULL_48BIT_PPGTT(vm->dev)) {
850                 gen8_ppgtt_insert_pte_entries(vm, &ppgtt->pdp, &sg_iter, start,
851                                               cache_level);
852         } else {
853                 struct i915_page_directory_pointer *pdp;
854                 uint64_t pml4e;
855                 uint64_t length = (uint64_t)pages->orig_nents << PAGE_SHIFT;
856
857                 gen8_for_each_pml4e(pdp, &ppgtt->pml4, start, length, pml4e) {
858                         gen8_ppgtt_insert_pte_entries(vm, pdp, &sg_iter,
859                                                       start, cache_level);
860                 }
861         }
862 }
863
864 static void gen8_free_page_tables(struct drm_device *dev,
865                                   struct i915_page_directory *pd)
866 {
867         int i;
868
869         if (!px_page(pd))
870                 return;
871
872         for_each_set_bit(i, pd->used_pdes, I915_PDES) {
873                 if (WARN_ON(!pd->page_table[i]))
874                         continue;
875
876                 free_pt(dev, pd->page_table[i]);
877                 pd->page_table[i] = NULL;
878         }
879 }
880
881 static int gen8_init_scratch(struct i915_address_space *vm)
882 {
883         struct drm_device *dev = vm->dev;
884         int ret;
885
886         vm->scratch_page = alloc_scratch_page(dev);
887         if (IS_ERR(vm->scratch_page))
888                 return PTR_ERR(vm->scratch_page);
889
890         vm->scratch_pt = alloc_pt(dev);
891         if (IS_ERR(vm->scratch_pt)) {
892                 ret = PTR_ERR(vm->scratch_pt);
893                 goto free_scratch_page;
894         }
895
896         vm->scratch_pd = alloc_pd(dev);
897         if (IS_ERR(vm->scratch_pd)) {
898                 ret = PTR_ERR(vm->scratch_pd);
899                 goto free_pt;
900         }
901
902         if (USES_FULL_48BIT_PPGTT(dev)) {
903                 vm->scratch_pdp = alloc_pdp(dev);
904                 if (IS_ERR(vm->scratch_pdp)) {
905                         ret = PTR_ERR(vm->scratch_pdp);
906                         goto free_pd;
907                 }
908         }
909
910         gen8_initialize_pt(vm, vm->scratch_pt);
911         gen8_initialize_pd(vm, vm->scratch_pd);
912         if (USES_FULL_48BIT_PPGTT(dev))
913                 gen8_initialize_pdp(vm, vm->scratch_pdp);
914
915         return 0;
916
917 free_pd:
918         free_pd(dev, vm->scratch_pd);
919 free_pt:
920         free_pt(dev, vm->scratch_pt);
921 free_scratch_page:
922         free_scratch_page(dev, vm->scratch_page);
923
924         return ret;
925 }
926
927 static int gen8_ppgtt_notify_vgt(struct i915_hw_ppgtt *ppgtt, bool create)
928 {
929         enum vgt_g2v_type msg;
930         struct drm_i915_private *dev_priv = to_i915(ppgtt->base.dev);
931         int i;
932
933         if (USES_FULL_48BIT_PPGTT(dev_priv)) {
934                 u64 daddr = px_dma(&ppgtt->pml4);
935
936                 I915_WRITE(vgtif_reg(pdp[0].lo), lower_32_bits(daddr));
937                 I915_WRITE(vgtif_reg(pdp[0].hi), upper_32_bits(daddr));
938
939                 msg = (create ? VGT_G2V_PPGTT_L4_PAGE_TABLE_CREATE :
940                                 VGT_G2V_PPGTT_L4_PAGE_TABLE_DESTROY);
941         } else {
942                 for (i = 0; i < GEN8_LEGACY_PDPES; i++) {
943                         u64 daddr = i915_page_dir_dma_addr(ppgtt, i);
944
945                         I915_WRITE(vgtif_reg(pdp[i].lo), lower_32_bits(daddr));
946                         I915_WRITE(vgtif_reg(pdp[i].hi), upper_32_bits(daddr));
947                 }
948
949                 msg = (create ? VGT_G2V_PPGTT_L3_PAGE_TABLE_CREATE :
950                                 VGT_G2V_PPGTT_L3_PAGE_TABLE_DESTROY);
951         }
952
953         I915_WRITE(vgtif_reg(g2v_notify), msg);
954
955         return 0;
956 }
957
958 static void gen8_free_scratch(struct i915_address_space *vm)
959 {
960         struct drm_device *dev = vm->dev;
961
962         if (USES_FULL_48BIT_PPGTT(dev))
963                 free_pdp(dev, vm->scratch_pdp);
964         free_pd(dev, vm->scratch_pd);
965         free_pt(dev, vm->scratch_pt);
966         free_scratch_page(dev, vm->scratch_page);
967 }
968
969 static void gen8_ppgtt_cleanup_3lvl(struct drm_device *dev,
970                                     struct i915_page_directory_pointer *pdp)
971 {
972         int i;
973
974         for_each_set_bit(i, pdp->used_pdpes, I915_PDPES_PER_PDP(dev)) {
975                 if (WARN_ON(!pdp->page_directory[i]))
976                         continue;
977
978                 gen8_free_page_tables(dev, pdp->page_directory[i]);
979                 free_pd(dev, pdp->page_directory[i]);
980         }
981
982         free_pdp(dev, pdp);
983 }
984
985 static void gen8_ppgtt_cleanup_4lvl(struct i915_hw_ppgtt *ppgtt)
986 {
987         int i;
988
989         for_each_set_bit(i, ppgtt->pml4.used_pml4es, GEN8_PML4ES_PER_PML4) {
990                 if (WARN_ON(!ppgtt->pml4.pdps[i]))
991                         continue;
992
993                 gen8_ppgtt_cleanup_3lvl(ppgtt->base.dev, ppgtt->pml4.pdps[i]);
994         }
995
996         cleanup_px(ppgtt->base.dev, &ppgtt->pml4);
997 }
998
999 static void gen8_ppgtt_cleanup(struct i915_address_space *vm)
1000 {
1001         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1002
1003         if (intel_vgpu_active(to_i915(vm->dev)))
1004                 gen8_ppgtt_notify_vgt(ppgtt, false);
1005
1006         if (!USES_FULL_48BIT_PPGTT(ppgtt->base.dev))
1007                 gen8_ppgtt_cleanup_3lvl(ppgtt->base.dev, &ppgtt->pdp);
1008         else
1009                 gen8_ppgtt_cleanup_4lvl(ppgtt);
1010
1011         gen8_free_scratch(vm);
1012 }
1013
1014 /**
1015  * gen8_ppgtt_alloc_pagetabs() - Allocate page tables for VA range.
1016  * @vm: Master vm structure.
1017  * @pd: Page directory for this address range.
1018  * @start:      Starting virtual address to begin allocations.
1019  * @length:     Size of the allocations.
1020  * @new_pts:    Bitmap set by function with new allocations. Likely used by the
1021  *              caller to free on error.
1022  *
1023  * Allocate the required number of page tables. Extremely similar to
1024  * gen8_ppgtt_alloc_page_directories(). The main difference is here we are limited by
1025  * the page directory boundary (instead of the page directory pointer). That
1026  * boundary is 1GB virtual. Therefore, unlike gen8_ppgtt_alloc_page_directories(), it is
1027  * possible, and likely that the caller will need to use multiple calls of this
1028  * function to achieve the appropriate allocation.
1029  *
1030  * Return: 0 if success; negative error code otherwise.
1031  */
1032 static int gen8_ppgtt_alloc_pagetabs(struct i915_address_space *vm,
1033                                      struct i915_page_directory *pd,
1034                                      uint64_t start,
1035                                      uint64_t length,
1036                                      unsigned long *new_pts)
1037 {
1038         struct drm_device *dev = vm->dev;
1039         struct i915_page_table *pt;
1040         uint32_t pde;
1041
1042         gen8_for_each_pde(pt, pd, start, length, pde) {
1043                 /* Don't reallocate page tables */
1044                 if (test_bit(pde, pd->used_pdes)) {
1045                         /* Scratch is never allocated this way */
1046                         WARN_ON(pt == vm->scratch_pt);
1047                         continue;
1048                 }
1049
1050                 pt = alloc_pt(dev);
1051                 if (IS_ERR(pt))
1052                         goto unwind_out;
1053
1054                 gen8_initialize_pt(vm, pt);
1055                 pd->page_table[pde] = pt;
1056                 __set_bit(pde, new_pts);
1057                 trace_i915_page_table_entry_alloc(vm, pde, start, GEN8_PDE_SHIFT);
1058         }
1059
1060         return 0;
1061
1062 unwind_out:
1063         for_each_set_bit(pde, new_pts, I915_PDES)
1064                 free_pt(dev, pd->page_table[pde]);
1065
1066         return -ENOMEM;
1067 }
1068
1069 /**
1070  * gen8_ppgtt_alloc_page_directories() - Allocate page directories for VA range.
1071  * @vm: Master vm structure.
1072  * @pdp:        Page directory pointer for this address range.
1073  * @start:      Starting virtual address to begin allocations.
1074  * @length:     Size of the allocations.
1075  * @new_pds:    Bitmap set by function with new allocations. Likely used by the
1076  *              caller to free on error.
1077  *
1078  * Allocate the required number of page directories starting at the pde index of
1079  * @start, and ending at the pde index @start + @length. This function will skip
1080  * over already allocated page directories within the range, and only allocate
1081  * new ones, setting the appropriate pointer within the pdp as well as the
1082  * correct position in the bitmap @new_pds.
1083  *
1084  * The function will only allocate the pages within the range for a give page
1085  * directory pointer. In other words, if @start + @length straddles a virtually
1086  * addressed PDP boundary (512GB for 4k pages), there will be more allocations
1087  * required by the caller, This is not currently possible, and the BUG in the
1088  * code will prevent it.
1089  *
1090  * Return: 0 if success; negative error code otherwise.
1091  */
1092 static int
1093 gen8_ppgtt_alloc_page_directories(struct i915_address_space *vm,
1094                                   struct i915_page_directory_pointer *pdp,
1095                                   uint64_t start,
1096                                   uint64_t length,
1097                                   unsigned long *new_pds)
1098 {
1099         struct drm_device *dev = vm->dev;
1100         struct i915_page_directory *pd;
1101         uint32_t pdpe;
1102         uint32_t pdpes = I915_PDPES_PER_PDP(dev);
1103
1104         WARN_ON(!bitmap_empty(new_pds, pdpes));
1105
1106         gen8_for_each_pdpe(pd, pdp, start, length, pdpe) {
1107                 if (test_bit(pdpe, pdp->used_pdpes))
1108                         continue;
1109
1110                 pd = alloc_pd(dev);
1111                 if (IS_ERR(pd))
1112                         goto unwind_out;
1113
1114                 gen8_initialize_pd(vm, pd);
1115                 pdp->page_directory[pdpe] = pd;
1116                 __set_bit(pdpe, new_pds);
1117                 trace_i915_page_directory_entry_alloc(vm, pdpe, start, GEN8_PDPE_SHIFT);
1118         }
1119
1120         return 0;
1121
1122 unwind_out:
1123         for_each_set_bit(pdpe, new_pds, pdpes)
1124                 free_pd(dev, pdp->page_directory[pdpe]);
1125
1126         return -ENOMEM;
1127 }
1128
1129 /**
1130  * gen8_ppgtt_alloc_page_dirpointers() - Allocate pdps for VA range.
1131  * @vm: Master vm structure.
1132  * @pml4:       Page map level 4 for this address range.
1133  * @start:      Starting virtual address to begin allocations.
1134  * @length:     Size of the allocations.
1135  * @new_pdps:   Bitmap set by function with new allocations. Likely used by the
1136  *              caller to free on error.
1137  *
1138  * Allocate the required number of page directory pointers. Extremely similar to
1139  * gen8_ppgtt_alloc_page_directories() and gen8_ppgtt_alloc_pagetabs().
1140  * The main difference is here we are limited by the pml4 boundary (instead of
1141  * the page directory pointer).
1142  *
1143  * Return: 0 if success; negative error code otherwise.
1144  */
1145 static int
1146 gen8_ppgtt_alloc_page_dirpointers(struct i915_address_space *vm,
1147                                   struct i915_pml4 *pml4,
1148                                   uint64_t start,
1149                                   uint64_t length,
1150                                   unsigned long *new_pdps)
1151 {
1152         struct drm_device *dev = vm->dev;
1153         struct i915_page_directory_pointer *pdp;
1154         uint32_t pml4e;
1155
1156         WARN_ON(!bitmap_empty(new_pdps, GEN8_PML4ES_PER_PML4));
1157
1158         gen8_for_each_pml4e(pdp, pml4, start, length, pml4e) {
1159                 if (!test_bit(pml4e, pml4->used_pml4es)) {
1160                         pdp = alloc_pdp(dev);
1161                         if (IS_ERR(pdp))
1162                                 goto unwind_out;
1163
1164                         gen8_initialize_pdp(vm, pdp);
1165                         pml4->pdps[pml4e] = pdp;
1166                         __set_bit(pml4e, new_pdps);
1167                         trace_i915_page_directory_pointer_entry_alloc(vm,
1168                                                                       pml4e,
1169                                                                       start,
1170                                                                       GEN8_PML4E_SHIFT);
1171                 }
1172         }
1173
1174         return 0;
1175
1176 unwind_out:
1177         for_each_set_bit(pml4e, new_pdps, GEN8_PML4ES_PER_PML4)
1178                 free_pdp(dev, pml4->pdps[pml4e]);
1179
1180         return -ENOMEM;
1181 }
1182
1183 static void
1184 free_gen8_temp_bitmaps(unsigned long *new_pds, unsigned long *new_pts)
1185 {
1186         kfree(new_pts);
1187         kfree(new_pds);
1188 }
1189
1190 /* Fills in the page directory bitmap, and the array of page tables bitmap. Both
1191  * of these are based on the number of PDPEs in the system.
1192  */
1193 static
1194 int __must_check alloc_gen8_temp_bitmaps(unsigned long **new_pds,
1195                                          unsigned long **new_pts,
1196                                          uint32_t pdpes)
1197 {
1198         unsigned long *pds;
1199         unsigned long *pts;
1200
1201         pds = kcalloc(BITS_TO_LONGS(pdpes), sizeof(unsigned long), GFP_TEMPORARY);
1202         if (!pds)
1203                 return -ENOMEM;
1204
1205         pts = kcalloc(pdpes, BITS_TO_LONGS(I915_PDES) * sizeof(unsigned long),
1206                       GFP_TEMPORARY);
1207         if (!pts)
1208                 goto err_out;
1209
1210         *new_pds = pds;
1211         *new_pts = pts;
1212
1213         return 0;
1214
1215 err_out:
1216         free_gen8_temp_bitmaps(pds, pts);
1217         return -ENOMEM;
1218 }
1219
1220 /* PDE TLBs are a pain to invalidate on GEN8+. When we modify
1221  * the page table structures, we mark them dirty so that
1222  * context switching/execlist queuing code takes extra steps
1223  * to ensure that tlbs are flushed.
1224  */
1225 static void mark_tlbs_dirty(struct i915_hw_ppgtt *ppgtt)
1226 {
1227         ppgtt->pd_dirty_rings = INTEL_INFO(ppgtt->base.dev)->ring_mask;
1228 }
1229
1230 static int gen8_alloc_va_range_3lvl(struct i915_address_space *vm,
1231                                     struct i915_page_directory_pointer *pdp,
1232                                     uint64_t start,
1233                                     uint64_t length)
1234 {
1235         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1236         unsigned long *new_page_dirs, *new_page_tables;
1237         struct drm_device *dev = vm->dev;
1238         struct i915_page_directory *pd;
1239         const uint64_t orig_start = start;
1240         const uint64_t orig_length = length;
1241         uint32_t pdpe;
1242         uint32_t pdpes = I915_PDPES_PER_PDP(dev);
1243         int ret;
1244
1245         /* Wrap is never okay since we can only represent 48b, and we don't
1246          * actually use the other side of the canonical address space.
1247          */
1248         if (WARN_ON(start + length < start))
1249                 return -ENODEV;
1250
1251         if (WARN_ON(start + length > vm->total))
1252                 return -ENODEV;
1253
1254         ret = alloc_gen8_temp_bitmaps(&new_page_dirs, &new_page_tables, pdpes);
1255         if (ret)
1256                 return ret;
1257
1258         /* Do the allocations first so we can easily bail out */
1259         ret = gen8_ppgtt_alloc_page_directories(vm, pdp, start, length,
1260                                                 new_page_dirs);
1261         if (ret) {
1262                 free_gen8_temp_bitmaps(new_page_dirs, new_page_tables);
1263                 return ret;
1264         }
1265
1266         /* For every page directory referenced, allocate page tables */
1267         gen8_for_each_pdpe(pd, pdp, start, length, pdpe) {
1268                 ret = gen8_ppgtt_alloc_pagetabs(vm, pd, start, length,
1269                                                 new_page_tables + pdpe * BITS_TO_LONGS(I915_PDES));
1270                 if (ret)
1271                         goto err_out;
1272         }
1273
1274         start = orig_start;
1275         length = orig_length;
1276
1277         /* Allocations have completed successfully, so set the bitmaps, and do
1278          * the mappings. */
1279         gen8_for_each_pdpe(pd, pdp, start, length, pdpe) {
1280                 gen8_pde_t *const page_directory = kmap_px(pd);
1281                 struct i915_page_table *pt;
1282                 uint64_t pd_len = length;
1283                 uint64_t pd_start = start;
1284                 uint32_t pde;
1285
1286                 /* Every pd should be allocated, we just did that above. */
1287                 WARN_ON(!pd);
1288
1289                 gen8_for_each_pde(pt, pd, pd_start, pd_len, pde) {
1290                         /* Same reasoning as pd */
1291                         WARN_ON(!pt);
1292                         WARN_ON(!pd_len);
1293                         WARN_ON(!gen8_pte_count(pd_start, pd_len));
1294
1295                         /* Set our used ptes within the page table */
1296                         bitmap_set(pt->used_ptes,
1297                                    gen8_pte_index(pd_start),
1298                                    gen8_pte_count(pd_start, pd_len));
1299
1300                         /* Our pde is now pointing to the pagetable, pt */
1301                         __set_bit(pde, pd->used_pdes);
1302
1303                         /* Map the PDE to the page table */
1304                         page_directory[pde] = gen8_pde_encode(px_dma(pt),
1305                                                               I915_CACHE_LLC);
1306                         trace_i915_page_table_entry_map(&ppgtt->base, pde, pt,
1307                                                         gen8_pte_index(start),
1308                                                         gen8_pte_count(start, length),
1309                                                         GEN8_PTES);
1310
1311                         /* NB: We haven't yet mapped ptes to pages. At this
1312                          * point we're still relying on insert_entries() */
1313                 }
1314
1315                 kunmap_px(ppgtt, page_directory);
1316                 __set_bit(pdpe, pdp->used_pdpes);
1317                 gen8_setup_page_directory(ppgtt, pdp, pd, pdpe);
1318         }
1319
1320         free_gen8_temp_bitmaps(new_page_dirs, new_page_tables);
1321         mark_tlbs_dirty(ppgtt);
1322         return 0;
1323
1324 err_out:
1325         while (pdpe--) {
1326                 unsigned long temp;
1327
1328                 for_each_set_bit(temp, new_page_tables + pdpe *
1329                                 BITS_TO_LONGS(I915_PDES), I915_PDES)
1330                         free_pt(dev, pdp->page_directory[pdpe]->page_table[temp]);
1331         }
1332
1333         for_each_set_bit(pdpe, new_page_dirs, pdpes)
1334                 free_pd(dev, pdp->page_directory[pdpe]);
1335
1336         free_gen8_temp_bitmaps(new_page_dirs, new_page_tables);
1337         mark_tlbs_dirty(ppgtt);
1338         return ret;
1339 }
1340
1341 static int gen8_alloc_va_range_4lvl(struct i915_address_space *vm,
1342                                     struct i915_pml4 *pml4,
1343                                     uint64_t start,
1344                                     uint64_t length)
1345 {
1346         DECLARE_BITMAP(new_pdps, GEN8_PML4ES_PER_PML4);
1347         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1348         struct i915_page_directory_pointer *pdp;
1349         uint64_t pml4e;
1350         int ret = 0;
1351
1352         /* Do the pml4 allocations first, so we don't need to track the newly
1353          * allocated tables below the pdp */
1354         bitmap_zero(new_pdps, GEN8_PML4ES_PER_PML4);
1355
1356         /* The pagedirectory and pagetable allocations are done in the shared 3
1357          * and 4 level code. Just allocate the pdps.
1358          */
1359         ret = gen8_ppgtt_alloc_page_dirpointers(vm, pml4, start, length,
1360                                                 new_pdps);
1361         if (ret)
1362                 return ret;
1363
1364         WARN(bitmap_weight(new_pdps, GEN8_PML4ES_PER_PML4) > 2,
1365              "The allocation has spanned more than 512GB. "
1366              "It is highly likely this is incorrect.");
1367
1368         gen8_for_each_pml4e(pdp, pml4, start, length, pml4e) {
1369                 WARN_ON(!pdp);
1370
1371                 ret = gen8_alloc_va_range_3lvl(vm, pdp, start, length);
1372                 if (ret)
1373                         goto err_out;
1374
1375                 gen8_setup_page_directory_pointer(ppgtt, pml4, pdp, pml4e);
1376         }
1377
1378         bitmap_or(pml4->used_pml4es, new_pdps, pml4->used_pml4es,
1379                   GEN8_PML4ES_PER_PML4);
1380
1381         return 0;
1382
1383 err_out:
1384         for_each_set_bit(pml4e, new_pdps, GEN8_PML4ES_PER_PML4)
1385                 gen8_ppgtt_cleanup_3lvl(vm->dev, pml4->pdps[pml4e]);
1386
1387         return ret;
1388 }
1389
1390 static int gen8_alloc_va_range(struct i915_address_space *vm,
1391                                uint64_t start, uint64_t length)
1392 {
1393         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1394
1395         if (USES_FULL_48BIT_PPGTT(vm->dev))
1396                 return gen8_alloc_va_range_4lvl(vm, &ppgtt->pml4, start, length);
1397         else
1398                 return gen8_alloc_va_range_3lvl(vm, &ppgtt->pdp, start, length);
1399 }
1400
1401 static void gen8_dump_pdp(struct i915_page_directory_pointer *pdp,
1402                           uint64_t start, uint64_t length,
1403                           gen8_pte_t scratch_pte,
1404                           struct seq_file *m)
1405 {
1406         struct i915_page_directory *pd;
1407         uint32_t pdpe;
1408
1409         gen8_for_each_pdpe(pd, pdp, start, length, pdpe) {
1410                 struct i915_page_table *pt;
1411                 uint64_t pd_len = length;
1412                 uint64_t pd_start = start;
1413                 uint32_t pde;
1414
1415                 if (!test_bit(pdpe, pdp->used_pdpes))
1416                         continue;
1417
1418                 seq_printf(m, "\tPDPE #%d\n", pdpe);
1419                 gen8_for_each_pde(pt, pd, pd_start, pd_len, pde) {
1420                         uint32_t  pte;
1421                         gen8_pte_t *pt_vaddr;
1422
1423                         if (!test_bit(pde, pd->used_pdes))
1424                                 continue;
1425
1426                         pt_vaddr = kmap_px(pt);
1427                         for (pte = 0; pte < GEN8_PTES; pte += 4) {
1428                                 uint64_t va =
1429                                         (pdpe << GEN8_PDPE_SHIFT) |
1430                                         (pde << GEN8_PDE_SHIFT) |
1431                                         (pte << GEN8_PTE_SHIFT);
1432                                 int i;
1433                                 bool found = false;
1434
1435                                 for (i = 0; i < 4; i++)
1436                                         if (pt_vaddr[pte + i] != scratch_pte)
1437                                                 found = true;
1438                                 if (!found)
1439                                         continue;
1440
1441                                 seq_printf(m, "\t\t0x%lx [%03d,%03d,%04d]: =", va, pdpe, pde, pte);
1442                                 for (i = 0; i < 4; i++) {
1443                                         if (pt_vaddr[pte + i] != scratch_pte)
1444                                                 seq_printf(m, " %lx", pt_vaddr[pte + i]);
1445                                         else
1446                                                 seq_puts(m, "  SCRATCH ");
1447                                 }
1448                                 seq_puts(m, "\n");
1449                         }
1450                         /* don't use kunmap_px, it could trigger
1451                          * an unnecessary flush.
1452                          */
1453                         kunmap_atomic(pt_vaddr);
1454                 }
1455         }
1456 }
1457
1458 static void gen8_dump_ppgtt(struct i915_hw_ppgtt *ppgtt, struct seq_file *m)
1459 {
1460         struct i915_address_space *vm = &ppgtt->base;
1461         uint64_t start = ppgtt->base.start;
1462         uint64_t length = ppgtt->base.total;
1463         gen8_pte_t scratch_pte = gen8_pte_encode(px_dma(vm->scratch_page),
1464                                                  I915_CACHE_LLC, true);
1465
1466         if (!USES_FULL_48BIT_PPGTT(vm->dev)) {
1467                 gen8_dump_pdp(&ppgtt->pdp, start, length, scratch_pte, m);
1468         } else {
1469                 uint64_t pml4e;
1470                 struct i915_pml4 *pml4 = &ppgtt->pml4;
1471                 struct i915_page_directory_pointer *pdp;
1472
1473                 gen8_for_each_pml4e(pdp, pml4, start, length, pml4e) {
1474                         if (!test_bit(pml4e, pml4->used_pml4es))
1475                                 continue;
1476
1477                         seq_printf(m, "    PML4E #%lu\n", pml4e);
1478                         gen8_dump_pdp(pdp, start, length, scratch_pte, m);
1479                 }
1480         }
1481 }
1482
1483 static int gen8_preallocate_top_level_pdps(struct i915_hw_ppgtt *ppgtt)
1484 {
1485         unsigned long *new_page_dirs, *new_page_tables;
1486         uint32_t pdpes = I915_PDPES_PER_PDP(dev);
1487         int ret;
1488
1489         /* We allocate temp bitmap for page tables for no gain
1490          * but as this is for init only, lets keep the things simple
1491          */
1492         ret = alloc_gen8_temp_bitmaps(&new_page_dirs, &new_page_tables, pdpes);
1493         if (ret)
1494                 return ret;
1495
1496         /* Allocate for all pdps regardless of how the ppgtt
1497          * was defined.
1498          */
1499         ret = gen8_ppgtt_alloc_page_directories(&ppgtt->base, &ppgtt->pdp,
1500                                                 0, 1ULL << 32,
1501                                                 new_page_dirs);
1502         if (!ret)
1503                 *ppgtt->pdp.used_pdpes = *new_page_dirs;
1504
1505         free_gen8_temp_bitmaps(new_page_dirs, new_page_tables);
1506
1507         return ret;
1508 }
1509
1510 /*
1511  * GEN8 legacy ppgtt programming is accomplished through a max 4 PDP registers
1512  * with a net effect resembling a 2-level page table in normal x86 terms. Each
1513  * PDP represents 1GB of memory 4 * 512 * 512 * 4096 = 4GB legacy 32b address
1514  * space.
1515  *
1516  */
1517 static int gen8_ppgtt_init(struct i915_hw_ppgtt *ppgtt)
1518 {
1519         int ret;
1520
1521         ret = gen8_init_scratch(&ppgtt->base);
1522         if (ret)
1523                 return ret;
1524
1525         ppgtt->base.start = 0;
1526         ppgtt->base.cleanup = gen8_ppgtt_cleanup;
1527         ppgtt->base.allocate_va_range = gen8_alloc_va_range;
1528         ppgtt->base.insert_entries = gen8_ppgtt_insert_entries;
1529         ppgtt->base.clear_range = gen8_ppgtt_clear_range;
1530         ppgtt->base.unbind_vma = ppgtt_unbind_vma;
1531         ppgtt->base.bind_vma = ppgtt_bind_vma;
1532         ppgtt->debug_dump = gen8_dump_ppgtt;
1533
1534         if (USES_FULL_48BIT_PPGTT(ppgtt->base.dev)) {
1535                 ret = setup_px(ppgtt->base.dev, &ppgtt->pml4);
1536                 if (ret)
1537                         goto free_scratch;
1538
1539                 gen8_initialize_pml4(&ppgtt->base, &ppgtt->pml4);
1540
1541                 ppgtt->base.total = 1ULL << 48;
1542                 ppgtt->switch_mm = gen8_48b_mm_switch;
1543         } else {
1544                 ret = __pdp_init(ppgtt->base.dev, &ppgtt->pdp);
1545                 if (ret)
1546                         goto free_scratch;
1547
1548                 ppgtt->base.total = 1ULL << 32;
1549                 ppgtt->switch_mm = gen8_legacy_mm_switch;
1550                 trace_i915_page_directory_pointer_entry_alloc(&ppgtt->base,
1551                                                               0, 0,
1552                                                               GEN8_PML4E_SHIFT);
1553
1554                 if (intel_vgpu_active(to_i915(ppgtt->base.dev))) {
1555                         ret = gen8_preallocate_top_level_pdps(ppgtt);
1556                         if (ret)
1557                                 goto free_scratch;
1558                 }
1559         }
1560
1561         if (intel_vgpu_active(to_i915(ppgtt->base.dev)))
1562                 gen8_ppgtt_notify_vgt(ppgtt, true);
1563
1564         return 0;
1565
1566 free_scratch:
1567         gen8_free_scratch(&ppgtt->base);
1568         return ret;
1569 }
1570
1571 static void gen6_dump_ppgtt(struct i915_hw_ppgtt *ppgtt, struct seq_file *m)
1572 {
1573         struct i915_address_space *vm = &ppgtt->base;
1574         struct i915_page_table *unused;
1575         gen6_pte_t scratch_pte;
1576         uint32_t pd_entry;
1577         uint32_t  pte, pde;
1578         uint32_t start = ppgtt->base.start, length = ppgtt->base.total;
1579
1580         scratch_pte = vm->pte_encode(px_dma(vm->scratch_page),
1581                                      I915_CACHE_LLC, true, 0);
1582
1583         gen6_for_each_pde(unused, &ppgtt->pd, start, length, pde) {
1584                 u32 expected;
1585                 gen6_pte_t *pt_vaddr;
1586                 const dma_addr_t pt_addr = px_dma(ppgtt->pd.page_table[pde]);
1587                 pd_entry = readl(ppgtt->pd_addr + pde);
1588                 expected = (GEN6_PDE_ADDR_ENCODE(pt_addr) | GEN6_PDE_VALID);
1589
1590                 if (pd_entry != expected)
1591                         seq_printf(m, "\tPDE #%d mismatch: Actual PDE: %x Expected PDE: %x\n",
1592                                    pde,
1593                                    pd_entry,
1594                                    expected);
1595                 seq_printf(m, "\tPDE: %x\n", pd_entry);
1596
1597                 pt_vaddr = kmap_px(ppgtt->pd.page_table[pde]);
1598
1599                 for (pte = 0; pte < GEN6_PTES; pte+=4) {
1600                         unsigned long va =
1601                                 (pde * PAGE_SIZE * GEN6_PTES) +
1602                                 (pte * PAGE_SIZE);
1603                         int i;
1604                         bool found = false;
1605                         for (i = 0; i < 4; i++)
1606                                 if (pt_vaddr[pte + i] != scratch_pte)
1607                                         found = true;
1608                         if (!found)
1609                                 continue;
1610
1611                         seq_printf(m, "\t\t0x%lx [%03d,%04d]: =", va, pde, pte);
1612                         for (i = 0; i < 4; i++) {
1613                                 if (pt_vaddr[pte + i] != scratch_pte)
1614                                         seq_printf(m, " %08x", pt_vaddr[pte + i]);
1615                                 else
1616                                         seq_puts(m, "  SCRATCH ");
1617                         }
1618                         seq_puts(m, "\n");
1619                 }
1620                 kunmap_px(ppgtt, pt_vaddr);
1621         }
1622 }
1623
1624 /* Write pde (index) from the page directory @pd to the page table @pt */
1625 static void gen6_write_pde(struct i915_page_directory *pd,
1626                             const int pde, struct i915_page_table *pt)
1627 {
1628         /* Caller needs to make sure the write completes if necessary */
1629         struct i915_hw_ppgtt *ppgtt =
1630                 container_of(pd, struct i915_hw_ppgtt, pd);
1631         u32 pd_entry;
1632
1633         pd_entry = GEN6_PDE_ADDR_ENCODE(px_dma(pt));
1634         pd_entry |= GEN6_PDE_VALID;
1635
1636         writel(pd_entry, ppgtt->pd_addr + pde);
1637 }
1638
1639 /* Write all the page tables found in the ppgtt structure to incrementing page
1640  * directories. */
1641 static void gen6_write_page_range(struct drm_i915_private *dev_priv,
1642                                   struct i915_page_directory *pd,
1643                                   uint32_t start, uint32_t length)
1644 {
1645         struct i915_ggtt *ggtt = &dev_priv->ggtt;
1646         struct i915_page_table *pt;
1647         uint32_t pde;
1648
1649         gen6_for_each_pde(pt, pd, start, length, pde)
1650                 gen6_write_pde(pd, pde, pt);
1651
1652         /* Make sure write is complete before other code can use this page
1653          * table. Also require for WC mapped PTEs */
1654         readl(ggtt->gsm);
1655 }
1656
1657 static uint32_t get_pd_offset(struct i915_hw_ppgtt *ppgtt)
1658 {
1659         BUG_ON(ppgtt->pd.base.ggtt_offset & 0x3f);
1660
1661         return (ppgtt->pd.base.ggtt_offset / 64) << 16;
1662 }
1663
1664 static int hsw_mm_switch(struct i915_hw_ppgtt *ppgtt,
1665                          struct drm_i915_gem_request *req)
1666 {
1667         struct intel_engine_cs *engine = req->engine;
1668         int ret;
1669
1670         /* NB: TLBs must be flushed and invalidated before a switch */
1671         ret = engine->flush(req, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
1672         if (ret)
1673                 return ret;
1674
1675         ret = intel_ring_begin(req, 6);
1676         if (ret)
1677                 return ret;
1678
1679         intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(2));
1680         intel_ring_emit_reg(engine, RING_PP_DIR_DCLV(engine));
1681         intel_ring_emit(engine, PP_DIR_DCLV_2G);
1682         intel_ring_emit_reg(engine, RING_PP_DIR_BASE(engine));
1683         intel_ring_emit(engine, get_pd_offset(ppgtt));
1684         intel_ring_emit(engine, MI_NOOP);
1685         intel_ring_advance(engine);
1686
1687         return 0;
1688 }
1689
1690 static int gen7_mm_switch(struct i915_hw_ppgtt *ppgtt,
1691                           struct drm_i915_gem_request *req)
1692 {
1693         struct intel_engine_cs *engine = req->engine;
1694         int ret;
1695
1696         /* NB: TLBs must be flushed and invalidated before a switch */
1697         ret = engine->flush(req, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
1698         if (ret)
1699                 return ret;
1700
1701         ret = intel_ring_begin(req, 6);
1702         if (ret)
1703                 return ret;
1704
1705         intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(2));
1706         intel_ring_emit_reg(engine, RING_PP_DIR_DCLV(engine));
1707         intel_ring_emit(engine, PP_DIR_DCLV_2G);
1708         intel_ring_emit_reg(engine, RING_PP_DIR_BASE(engine));
1709         intel_ring_emit(engine, get_pd_offset(ppgtt));
1710         intel_ring_emit(engine, MI_NOOP);
1711         intel_ring_advance(engine);
1712
1713         /* XXX: RCS is the only one to auto invalidate the TLBs? */
1714         if (engine->id != RCS) {
1715                 ret = engine->flush(req, I915_GEM_GPU_DOMAINS, I915_GEM_GPU_DOMAINS);
1716                 if (ret)
1717                         return ret;
1718         }
1719
1720         return 0;
1721 }
1722
1723 static int gen6_mm_switch(struct i915_hw_ppgtt *ppgtt,
1724                           struct drm_i915_gem_request *req)
1725 {
1726         struct intel_engine_cs *engine = req->engine;
1727         struct drm_i915_private *dev_priv = req->i915;
1728
1729         I915_WRITE(RING_PP_DIR_DCLV(engine), PP_DIR_DCLV_2G);
1730         I915_WRITE(RING_PP_DIR_BASE(engine), get_pd_offset(ppgtt));
1731         return 0;
1732 }
1733
1734 static void gen8_ppgtt_enable(struct drm_device *dev)
1735 {
1736         struct drm_i915_private *dev_priv = to_i915(dev);
1737         struct intel_engine_cs *engine;
1738
1739         for_each_engine(engine, dev_priv) {
1740                 u32 four_level = USES_FULL_48BIT_PPGTT(dev) ? GEN8_GFX_PPGTT_48B : 0;
1741                 I915_WRITE(RING_MODE_GEN7(engine),
1742                            _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE | four_level));
1743         }
1744 }
1745
1746 static void gen7_ppgtt_enable(struct drm_device *dev)
1747 {
1748         struct drm_i915_private *dev_priv = to_i915(dev);
1749         struct intel_engine_cs *engine;
1750         uint32_t ecochk, ecobits;
1751
1752         ecobits = I915_READ(GAC_ECO_BITS);
1753         I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_PPGTT_CACHE64B);
1754
1755         ecochk = I915_READ(GAM_ECOCHK);
1756         if (IS_HASWELL(dev)) {
1757                 ecochk |= ECOCHK_PPGTT_WB_HSW;
1758         } else {
1759                 ecochk |= ECOCHK_PPGTT_LLC_IVB;
1760                 ecochk &= ~ECOCHK_PPGTT_GFDT_IVB;
1761         }
1762         I915_WRITE(GAM_ECOCHK, ecochk);
1763
1764         for_each_engine(engine, dev_priv) {
1765                 /* GFX_MODE is per-ring on gen7+ */
1766                 I915_WRITE(RING_MODE_GEN7(engine),
1767                            _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1768         }
1769 }
1770
1771 static void gen6_ppgtt_enable(struct drm_device *dev)
1772 {
1773         struct drm_i915_private *dev_priv = to_i915(dev);
1774         uint32_t ecochk, gab_ctl, ecobits;
1775
1776         ecobits = I915_READ(GAC_ECO_BITS);
1777         I915_WRITE(GAC_ECO_BITS, ecobits | ECOBITS_SNB_BIT |
1778                    ECOBITS_PPGTT_CACHE64B);
1779
1780         gab_ctl = I915_READ(GAB_CTL);
1781         I915_WRITE(GAB_CTL, gab_ctl | GAB_CTL_CONT_AFTER_PAGEFAULT);
1782
1783         ecochk = I915_READ(GAM_ECOCHK);
1784         I915_WRITE(GAM_ECOCHK, ecochk | ECOCHK_SNB_BIT | ECOCHK_PPGTT_CACHE64B);
1785
1786         I915_WRITE(GFX_MODE, _MASKED_BIT_ENABLE(GFX_PPGTT_ENABLE));
1787 }
1788
1789 /* PPGTT support for Sandybdrige/Gen6 and later */
1790 static void gen6_ppgtt_clear_range(struct i915_address_space *vm,
1791                                    uint64_t start,
1792                                    uint64_t length,
1793                                    bool use_scratch)
1794 {
1795         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1796         gen6_pte_t *pt_vaddr, scratch_pte;
1797         unsigned first_entry = start >> PAGE_SHIFT;
1798         unsigned num_entries = length >> PAGE_SHIFT;
1799         unsigned act_pt = first_entry / GEN6_PTES;
1800         unsigned first_pte = first_entry % GEN6_PTES;
1801         unsigned last_pte, i;
1802
1803         scratch_pte = vm->pte_encode(px_dma(vm->scratch_page),
1804                                      I915_CACHE_LLC, true, 0);
1805
1806         while (num_entries) {
1807                 last_pte = first_pte + num_entries;
1808                 if (last_pte > GEN6_PTES)
1809                         last_pte = GEN6_PTES;
1810
1811                 pt_vaddr = kmap_px(ppgtt->pd.page_table[act_pt]);
1812
1813                 for (i = first_pte; i < last_pte; i++)
1814                         pt_vaddr[i] = scratch_pte;
1815
1816                 kunmap_px(ppgtt, pt_vaddr);
1817
1818                 num_entries -= last_pte - first_pte;
1819                 first_pte = 0;
1820                 act_pt++;
1821         }
1822 }
1823
1824 static void gen6_ppgtt_insert_entries(struct i915_address_space *vm,
1825                                       struct sg_table *pages,
1826                                       uint64_t start,
1827                                       enum i915_cache_level cache_level, u32 flags)
1828 {
1829         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1830         unsigned first_entry = start >> PAGE_SHIFT;
1831         unsigned act_pt = first_entry / GEN6_PTES;
1832         unsigned act_pte = first_entry % GEN6_PTES;
1833         gen6_pte_t *pt_vaddr = NULL;
1834         struct sgt_iter sgt_iter;
1835         dma_addr_t addr;
1836
1837         for_each_sgt_dma(addr, sgt_iter, pages) {
1838                 if (pt_vaddr == NULL)
1839                         pt_vaddr = kmap_px(ppgtt->pd.page_table[act_pt]);
1840
1841                 pt_vaddr[act_pte] =
1842                         vm->pte_encode(addr, cache_level, true, flags);
1843
1844                 if (++act_pte == GEN6_PTES) {
1845                         kunmap_px(ppgtt, pt_vaddr);
1846                         pt_vaddr = NULL;
1847                         act_pt++;
1848                         act_pte = 0;
1849                 }
1850         }
1851
1852         if (pt_vaddr)
1853                 kunmap_px(ppgtt, pt_vaddr);
1854 }
1855
1856 static int gen6_alloc_va_range(struct i915_address_space *vm,
1857                                uint64_t start_in, uint64_t length_in)
1858 {
1859         DECLARE_BITMAP(new_page_tables, I915_PDES);
1860         struct drm_device *dev = vm->dev;
1861         struct drm_i915_private *dev_priv = to_i915(dev);
1862         struct i915_ggtt *ggtt = &dev_priv->ggtt;
1863         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1864         struct i915_page_table *pt;
1865         uint32_t start, length, start_save, length_save;
1866         uint32_t pde;
1867         int ret;
1868
1869         if (WARN_ON(start_in + length_in > ppgtt->base.total))
1870                 return -ENODEV;
1871
1872         start = start_save = start_in;
1873         length = length_save = length_in;
1874
1875         bitmap_zero(new_page_tables, I915_PDES);
1876
1877         /* The allocation is done in two stages so that we can bail out with
1878          * minimal amount of pain. The first stage finds new page tables that
1879          * need allocation. The second stage marks use ptes within the page
1880          * tables.
1881          */
1882         gen6_for_each_pde(pt, &ppgtt->pd, start, length, pde) {
1883                 if (pt != vm->scratch_pt) {
1884                         WARN_ON(bitmap_empty(pt->used_ptes, GEN6_PTES));
1885                         continue;
1886                 }
1887
1888                 /* We've already allocated a page table */
1889                 WARN_ON(!bitmap_empty(pt->used_ptes, GEN6_PTES));
1890
1891                 pt = alloc_pt(dev);
1892                 if (IS_ERR(pt)) {
1893                         ret = PTR_ERR(pt);
1894                         goto unwind_out;
1895                 }
1896
1897                 gen6_initialize_pt(vm, pt);
1898
1899                 ppgtt->pd.page_table[pde] = pt;
1900                 __set_bit(pde, new_page_tables);
1901                 trace_i915_page_table_entry_alloc(vm, pde, start, GEN6_PDE_SHIFT);
1902         }
1903
1904         start = start_save;
1905         length = length_save;
1906
1907         gen6_for_each_pde(pt, &ppgtt->pd, start, length, pde) {
1908                 DECLARE_BITMAP(tmp_bitmap, GEN6_PTES);
1909
1910                 bitmap_zero(tmp_bitmap, GEN6_PTES);
1911                 bitmap_set(tmp_bitmap, gen6_pte_index(start),
1912                            gen6_pte_count(start, length));
1913
1914                 if (__test_and_clear_bit(pde, new_page_tables))
1915                         gen6_write_pde(&ppgtt->pd, pde, pt);
1916
1917                 trace_i915_page_table_entry_map(vm, pde, pt,
1918                                          gen6_pte_index(start),
1919                                          gen6_pte_count(start, length),
1920                                          GEN6_PTES);
1921                 bitmap_or(pt->used_ptes, tmp_bitmap, pt->used_ptes,
1922                                 GEN6_PTES);
1923         }
1924
1925         WARN_ON(!bitmap_empty(new_page_tables, I915_PDES));
1926
1927         /* Make sure write is complete before other code can use this page
1928          * table. Also require for WC mapped PTEs */
1929         readl(ggtt->gsm);
1930
1931         mark_tlbs_dirty(ppgtt);
1932         return 0;
1933
1934 unwind_out:
1935         for_each_set_bit(pde, new_page_tables, I915_PDES) {
1936                 struct i915_page_table *pt = ppgtt->pd.page_table[pde];
1937
1938                 ppgtt->pd.page_table[pde] = vm->scratch_pt;
1939                 free_pt(vm->dev, pt);
1940         }
1941
1942         mark_tlbs_dirty(ppgtt);
1943         return ret;
1944 }
1945
1946 static int gen6_init_scratch(struct i915_address_space *vm)
1947 {
1948         struct drm_device *dev = vm->dev;
1949
1950         vm->scratch_page = alloc_scratch_page(dev);
1951         if (IS_ERR(vm->scratch_page))
1952                 return PTR_ERR(vm->scratch_page);
1953
1954         vm->scratch_pt = alloc_pt(dev);
1955         if (IS_ERR(vm->scratch_pt)) {
1956                 free_scratch_page(dev, vm->scratch_page);
1957                 return PTR_ERR(vm->scratch_pt);
1958         }
1959
1960         gen6_initialize_pt(vm, vm->scratch_pt);
1961
1962         return 0;
1963 }
1964
1965 static void gen6_free_scratch(struct i915_address_space *vm)
1966 {
1967         struct drm_device *dev = vm->dev;
1968
1969         free_pt(dev, vm->scratch_pt);
1970         free_scratch_page(dev, vm->scratch_page);
1971 }
1972
1973 static void gen6_ppgtt_cleanup(struct i915_address_space *vm)
1974 {
1975         struct i915_hw_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1976         struct i915_page_directory *pd = &ppgtt->pd;
1977         struct drm_device *dev = vm->dev;
1978         struct i915_page_table *pt;
1979         uint32_t pde;
1980
1981         drm_mm_remove_node(&ppgtt->node);
1982
1983         gen6_for_all_pdes(pt, pd, pde)
1984                 if (pt != vm->scratch_pt)
1985                         free_pt(dev, pt);
1986
1987         gen6_free_scratch(vm);
1988 }
1989
1990 static int gen6_ppgtt_allocate_page_directories(struct i915_hw_ppgtt *ppgtt)
1991 {
1992         struct i915_address_space *vm = &ppgtt->base;
1993         struct drm_device *dev = ppgtt->base.dev;
1994         struct drm_i915_private *dev_priv = to_i915(dev);
1995         struct i915_ggtt *ggtt = &dev_priv->ggtt;
1996         bool retried = false;
1997         int ret;
1998
1999         /* PPGTT PDEs reside in the GGTT and consists of 512 entries. The
2000          * allocator works in address space sizes, so it's multiplied by page
2001          * size. We allocate at the top of the GTT to avoid fragmentation.
2002          */
2003         BUG_ON(!drm_mm_initialized(&ggtt->base.mm));
2004
2005         ret = gen6_init_scratch(vm);
2006         if (ret)
2007                 return ret;
2008
2009 alloc:
2010         ret = drm_mm_insert_node_in_range_generic(&ggtt->base.mm,
2011                                                   &ppgtt->node, GEN6_PD_SIZE,
2012                                                   GEN6_PD_ALIGN, 0,
2013                                                   0, ggtt->base.total,
2014                                                   DRM_MM_TOPDOWN);
2015         if (ret == -ENOSPC && !retried) {
2016                 ret = i915_gem_evict_something(dev, &ggtt->base,
2017                                                GEN6_PD_SIZE, GEN6_PD_ALIGN,
2018                                                I915_CACHE_NONE,
2019                                                0, ggtt->base.total,
2020                                                0);
2021                 if (ret)
2022                         goto err_out;
2023
2024                 retried = true;
2025                 goto alloc;
2026         }
2027
2028         if (ret)
2029                 goto err_out;
2030
2031
2032         if (ppgtt->node.start < ggtt->mappable_end)
2033                 DRM_DEBUG("Forced to use aperture for PDEs\n");
2034
2035         return 0;
2036
2037 err_out:
2038         gen6_free_scratch(vm);
2039         return ret;
2040 }
2041
2042 static int gen6_ppgtt_alloc(struct i915_hw_ppgtt *ppgtt)
2043 {
2044         return gen6_ppgtt_allocate_page_directories(ppgtt);
2045 }
2046
2047 static void gen6_scratch_va_range(struct i915_hw_ppgtt *ppgtt,
2048                                   uint64_t start, uint64_t length)
2049 {
2050         struct i915_page_table *unused;
2051         uint32_t pde;
2052
2053         gen6_for_each_pde(unused, &ppgtt->pd, start, length, pde)
2054                 ppgtt->pd.page_table[pde] = ppgtt->base.scratch_pt;
2055 }
2056
2057 static int gen6_ppgtt_init(struct i915_hw_ppgtt *ppgtt)
2058 {
2059         struct drm_device *dev = ppgtt->base.dev;
2060         struct drm_i915_private *dev_priv = to_i915(dev);
2061         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2062         int ret;
2063
2064         ppgtt->base.pte_encode = ggtt->base.pte_encode;
2065         if (intel_vgpu_active(dev_priv) || IS_GEN6(dev))
2066                 ppgtt->switch_mm = gen6_mm_switch;
2067         else if (IS_HASWELL(dev))
2068                 ppgtt->switch_mm = hsw_mm_switch;
2069         else if (IS_GEN7(dev))
2070                 ppgtt->switch_mm = gen7_mm_switch;
2071         else
2072                 BUG();
2073
2074         ret = gen6_ppgtt_alloc(ppgtt);
2075         if (ret)
2076                 return ret;
2077
2078         ppgtt->base.allocate_va_range = gen6_alloc_va_range;
2079         ppgtt->base.clear_range = gen6_ppgtt_clear_range;
2080         ppgtt->base.insert_entries = gen6_ppgtt_insert_entries;
2081         ppgtt->base.unbind_vma = ppgtt_unbind_vma;
2082         ppgtt->base.bind_vma = ppgtt_bind_vma;
2083         ppgtt->base.cleanup = gen6_ppgtt_cleanup;
2084         ppgtt->base.start = 0;
2085         ppgtt->base.total = I915_PDES * GEN6_PTES * PAGE_SIZE;
2086         ppgtt->debug_dump = gen6_dump_ppgtt;
2087
2088         ppgtt->pd.base.ggtt_offset =
2089                 ppgtt->node.start / PAGE_SIZE * sizeof(gen6_pte_t);
2090
2091         ppgtt->pd_addr = (gen6_pte_t __iomem *)ggtt->gsm +
2092                 ppgtt->pd.base.ggtt_offset / sizeof(gen6_pte_t);
2093
2094         gen6_scratch_va_range(ppgtt, 0, ppgtt->base.total);
2095
2096         gen6_write_page_range(dev_priv, &ppgtt->pd, 0, ppgtt->base.total);
2097
2098         DRM_DEBUG_DRIVER("Allocated pde space (%lldM) at GTT entry: %llx\n",
2099                          ppgtt->node.size >> 20,
2100                          ppgtt->node.start / PAGE_SIZE);
2101
2102         DRM_DEBUG("Adding PPGTT at offset %x\n",
2103                   ppgtt->pd.base.ggtt_offset << 10);
2104
2105         return 0;
2106 }
2107
2108 static int __hw_ppgtt_init(struct drm_device *dev, struct i915_hw_ppgtt *ppgtt)
2109 {
2110         ppgtt->base.dev = dev;
2111
2112         if (INTEL_INFO(dev)->gen < 8)
2113                 return gen6_ppgtt_init(ppgtt);
2114         else
2115                 return gen8_ppgtt_init(ppgtt);
2116 }
2117
2118 static void i915_address_space_init(struct i915_address_space *vm,
2119                                     struct drm_i915_private *dev_priv)
2120 {
2121         drm_mm_init(&vm->mm, vm->start, vm->total);
2122         vm->dev = &dev_priv->drm;
2123         INIT_LIST_HEAD(&vm->active_list);
2124         INIT_LIST_HEAD(&vm->inactive_list);
2125         list_add_tail(&vm->global_link, &dev_priv->vm_list);
2126 }
2127
2128 static void gtt_write_workarounds(struct drm_device *dev)
2129 {
2130         struct drm_i915_private *dev_priv = to_i915(dev);
2131
2132         /* This function is for gtt related workarounds. This function is
2133          * called on driver load and after a GPU reset, so you can place
2134          * workarounds here even if they get overwritten by GPU reset.
2135          */
2136         /* WaIncreaseDefaultTLBEntries:chv,bdw,skl,bxt */
2137         if (IS_BROADWELL(dev))
2138                 I915_WRITE(GEN8_L3_LRA_1_GPGPU, GEN8_L3_LRA_1_GPGPU_DEFAULT_VALUE_BDW);
2139         else if (IS_CHERRYVIEW(dev))
2140                 I915_WRITE(GEN8_L3_LRA_1_GPGPU, GEN8_L3_LRA_1_GPGPU_DEFAULT_VALUE_CHV);
2141         else if (IS_SKYLAKE(dev))
2142                 I915_WRITE(GEN8_L3_LRA_1_GPGPU, GEN9_L3_LRA_1_GPGPU_DEFAULT_VALUE_SKL);
2143         else if (IS_BROXTON(dev))
2144                 I915_WRITE(GEN8_L3_LRA_1_GPGPU, GEN9_L3_LRA_1_GPGPU_DEFAULT_VALUE_BXT);
2145 }
2146
2147 static int i915_ppgtt_init(struct drm_device *dev, struct i915_hw_ppgtt *ppgtt)
2148 {
2149         struct drm_i915_private *dev_priv = to_i915(dev);
2150         int ret = 0;
2151
2152         ret = __hw_ppgtt_init(dev, ppgtt);
2153         if (ret == 0) {
2154                 kref_init(&ppgtt->ref);
2155                 i915_address_space_init(&ppgtt->base, dev_priv);
2156         }
2157
2158         return ret;
2159 }
2160
2161 int i915_ppgtt_init_hw(struct drm_device *dev)
2162 {
2163         gtt_write_workarounds(dev);
2164
2165         /* In the case of execlists, PPGTT is enabled by the context descriptor
2166          * and the PDPs are contained within the context itself.  We don't
2167          * need to do anything here. */
2168         if (i915.enable_execlists)
2169                 return 0;
2170
2171         if (!USES_PPGTT(dev))
2172                 return 0;
2173
2174         if (IS_GEN6(dev))
2175                 gen6_ppgtt_enable(dev);
2176         else if (IS_GEN7(dev))
2177                 gen7_ppgtt_enable(dev);
2178         else if (INTEL_INFO(dev)->gen >= 8)
2179                 gen8_ppgtt_enable(dev);
2180         else
2181                 MISSING_CASE(INTEL_INFO(dev)->gen);
2182
2183         return 0;
2184 }
2185
2186 struct i915_hw_ppgtt *
2187 i915_ppgtt_create(struct drm_device *dev, struct drm_i915_file_private *fpriv)
2188 {
2189         struct i915_hw_ppgtt *ppgtt;
2190         int ret;
2191
2192         ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
2193         if (!ppgtt)
2194                 return ERR_PTR(-ENOMEM);
2195
2196         ret = i915_ppgtt_init(dev, ppgtt);
2197         if (ret) {
2198                 kfree(ppgtt);
2199                 return ERR_PTR(ret);
2200         }
2201
2202         ppgtt->file_priv = fpriv;
2203
2204         trace_i915_ppgtt_create(&ppgtt->base);
2205
2206         return ppgtt;
2207 }
2208
2209 void  i915_ppgtt_release(struct kref *kref)
2210 {
2211         struct i915_hw_ppgtt *ppgtt =
2212                 container_of(kref, struct i915_hw_ppgtt, ref);
2213
2214         trace_i915_ppgtt_release(&ppgtt->base);
2215
2216         /* vmas should already be unbound */
2217         WARN_ON(!list_empty(&ppgtt->base.active_list));
2218         WARN_ON(!list_empty(&ppgtt->base.inactive_list));
2219
2220         list_del(&ppgtt->base.global_link);
2221         drm_mm_takedown(&ppgtt->base.mm);
2222
2223         ppgtt->base.cleanup(&ppgtt->base);
2224         kfree(ppgtt);
2225 }
2226
2227 extern int intel_iommu_gfx_mapped;
2228 /* Certain Gen5 chipsets require require idling the GPU before
2229  * unmapping anything from the GTT when VT-d is enabled.
2230  */
2231 static bool needs_idle_maps(struct drm_device *dev)
2232 {
2233 #ifdef CONFIG_INTEL_IOMMU
2234         /* Query intel_iommu to see if we need the workaround. Presumably that
2235          * was loaded first.
2236          */
2237         if (IS_GEN5(dev) && IS_MOBILE(dev) && intel_iommu_gfx_mapped)
2238                 return true;
2239 #endif
2240         return false;
2241 }
2242
2243 static bool do_idling(struct drm_i915_private *dev_priv)
2244 {
2245         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2246         bool ret = dev_priv->mm.interruptible;
2247
2248         if (unlikely(ggtt->do_idle_maps)) {
2249                 dev_priv->mm.interruptible = false;
2250                 if (i915_gem_wait_for_idle(dev_priv)) {
2251                         DRM_ERROR("Failed to wait for idle; VT'd may hang.\n");
2252                         /* Wait a bit, in hopes it avoids the hang */
2253                         udelay(10);
2254                 }
2255         }
2256
2257         return ret;
2258 }
2259
2260 static void undo_idling(struct drm_i915_private *dev_priv, bool interruptible)
2261 {
2262         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2263
2264         if (unlikely(ggtt->do_idle_maps))
2265                 dev_priv->mm.interruptible = interruptible;
2266 }
2267
2268 void i915_check_and_clear_faults(struct drm_i915_private *dev_priv)
2269 {
2270         struct intel_engine_cs *engine;
2271
2272         if (INTEL_INFO(dev_priv)->gen < 6)
2273                 return;
2274
2275         for_each_engine(engine, dev_priv) {
2276                 u32 fault_reg;
2277                 fault_reg = I915_READ(RING_FAULT_REG(engine));
2278                 if (fault_reg & RING_FAULT_VALID) {
2279                         DRM_DEBUG_DRIVER("Unexpected fault\n"
2280                                          "\tAddr: 0x%08ux\n"
2281                                          "\tAddress space: %s\n"
2282                                          "\tSource ID: %d\n"
2283                                          "\tType: %d\n",
2284                                          fault_reg & LINUX_PAGE_MASK,
2285                                          fault_reg & RING_FAULT_GTTSEL_MASK ? "GGTT" : "PPGTT",
2286                                          RING_FAULT_SRCID(fault_reg),
2287                                          RING_FAULT_FAULT_TYPE(fault_reg));
2288                         I915_WRITE(RING_FAULT_REG(engine),
2289                                    fault_reg & ~RING_FAULT_VALID);
2290                 }
2291         }
2292         POSTING_READ(RING_FAULT_REG(&dev_priv->engine[RCS]));
2293 }
2294
2295 static void i915_ggtt_flush(struct drm_i915_private *dev_priv)
2296 {
2297         if (INTEL_INFO(dev_priv)->gen < 6) {
2298                 intel_gtt_chipset_flush();
2299         } else {
2300                 I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
2301                 POSTING_READ(GFX_FLSH_CNTL_GEN6);
2302         }
2303 }
2304
2305 void i915_gem_suspend_gtt_mappings(struct drm_device *dev)
2306 {
2307         struct drm_i915_private *dev_priv = to_i915(dev);
2308         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2309
2310         /* Don't bother messing with faults pre GEN6 as we have little
2311          * documentation supporting that it's a good idea.
2312          */
2313         if (INTEL_INFO(dev)->gen < 6)
2314                 return;
2315
2316         i915_check_and_clear_faults(dev_priv);
2317
2318         ggtt->base.clear_range(&ggtt->base, ggtt->base.start, ggtt->base.total,
2319                              true);
2320
2321         i915_ggtt_flush(dev_priv);
2322 }
2323
2324 int i915_gem_gtt_prepare_object(struct drm_i915_gem_object *obj)
2325 {
2326         if (!dma_map_sg(&obj->base.dev->pdev->dev,
2327                         obj->pages->sgl, obj->pages->nents,
2328                         PCI_DMA_BIDIRECTIONAL))
2329                 return -ENOSPC;
2330
2331         return 0;
2332 }
2333
2334 static void gen8_set_pte(void __iomem *addr, gen8_pte_t pte)
2335 {
2336 #ifdef writeq
2337         writeq(pte, addr);
2338 #else
2339         iowrite32((u32)pte, addr);
2340         iowrite32(pte >> 32, addr + 4);
2341 #endif
2342 }
2343
2344 static void gen8_ggtt_insert_page(struct i915_address_space *vm,
2345                                   dma_addr_t addr,
2346                                   uint64_t offset,
2347                                   enum i915_cache_level level,
2348                                   u32 unused)
2349 {
2350         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2351         gen8_pte_t __iomem *pte =
2352                 (gen8_pte_t __iomem *)dev_priv->ggtt.gsm +
2353                 (offset >> PAGE_SHIFT);
2354         int rpm_atomic_seq;
2355
2356         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2357
2358         gen8_set_pte(pte, gen8_pte_encode(addr, level, true));
2359
2360         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
2361         POSTING_READ(GFX_FLSH_CNTL_GEN6);
2362
2363         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2364 }
2365
2366 static void gen8_ggtt_insert_entries(struct i915_address_space *vm,
2367                                      struct sg_table *st,
2368                                      uint64_t start,
2369                                      enum i915_cache_level level, u32 unused)
2370 {
2371         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2372         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2373         struct sgt_iter sgt_iter;
2374         gen8_pte_t __iomem *gtt_entries;
2375         gen8_pte_t gtt_entry;
2376         dma_addr_t addr;
2377         int rpm_atomic_seq;
2378         int i = 0;
2379
2380         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2381
2382         gtt_entries = (gen8_pte_t __iomem *)ggtt->gsm + (start >> PAGE_SHIFT);
2383
2384         for_each_sgt_dma(addr, sgt_iter, st) {
2385                 gtt_entry = gen8_pte_encode(addr, level, true);
2386                 gen8_set_pte(&gtt_entries[i++], gtt_entry);
2387         }
2388
2389         /*
2390          * XXX: This serves as a posting read to make sure that the PTE has
2391          * actually been updated. There is some concern that even though
2392          * registers and PTEs are within the same BAR that they are potentially
2393          * of NUMA access patterns. Therefore, even with the way we assume
2394          * hardware should work, we must keep this posting read for paranoia.
2395          */
2396         if (i != 0)
2397                 WARN_ON(readq(&gtt_entries[i-1]) != gtt_entry);
2398
2399         /* This next bit makes the above posting read even more important. We
2400          * want to flush the TLBs only after we're certain all the PTE updates
2401          * have finished.
2402          */
2403         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
2404         POSTING_READ(GFX_FLSH_CNTL_GEN6);
2405
2406         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2407 }
2408
2409 struct insert_entries {
2410         struct i915_address_space *vm;
2411         struct sg_table *st;
2412         uint64_t start;
2413         enum i915_cache_level level;
2414         u32 flags;
2415 };
2416
2417 static int gen8_ggtt_insert_entries__cb(void *_arg)
2418 {
2419         struct insert_entries *arg = _arg;
2420         gen8_ggtt_insert_entries(arg->vm, arg->st,
2421                                  arg->start, arg->level, arg->flags);
2422         return 0;
2423 }
2424
2425 static void gen8_ggtt_insert_entries__BKL(struct i915_address_space *vm,
2426                                           struct sg_table *st,
2427                                           uint64_t start,
2428                                           enum i915_cache_level level,
2429                                           u32 flags)
2430 {
2431         struct insert_entries arg = { vm, st, start, level, flags };
2432 #ifndef __DragonFly__
2433         stop_machine(gen8_ggtt_insert_entries__cb, &arg, NULL);
2434 #else
2435         /* XXX: is this enough ?
2436          * See Linux commit 5bab6f60cb4d1417ad7c599166bcfec87529c1a2 */
2437         get_mplock();
2438         gen8_ggtt_insert_entries__cb(&arg);
2439         rel_mplock();
2440 #endif
2441 }
2442
2443 static void gen6_ggtt_insert_page(struct i915_address_space *vm,
2444                                   dma_addr_t addr,
2445                                   uint64_t offset,
2446                                   enum i915_cache_level level,
2447                                   u32 flags)
2448 {
2449         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2450         gen6_pte_t __iomem *pte =
2451                 (gen6_pte_t __iomem *)dev_priv->ggtt.gsm +
2452                 (offset >> PAGE_SHIFT);
2453         int rpm_atomic_seq;
2454
2455         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2456
2457         iowrite32(vm->pte_encode(addr, level, true, flags), pte);
2458
2459         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
2460         POSTING_READ(GFX_FLSH_CNTL_GEN6);
2461
2462         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2463 }
2464
2465 /*
2466  * Binds an object into the global gtt with the specified cache level. The object
2467  * will be accessible to the GPU via commands whose operands reference offsets
2468  * within the global GTT as well as accessible by the GPU through the GMADR
2469  * mapped BAR (dev_priv->mm.gtt->gtt).
2470  */
2471 static void gen6_ggtt_insert_entries(struct i915_address_space *vm,
2472                                      struct sg_table *st,
2473                                      uint64_t start,
2474                                      enum i915_cache_level level, u32 flags)
2475 {
2476         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2477         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2478         struct sgt_iter sgt_iter;
2479         gen6_pte_t __iomem *gtt_entries;
2480         gen6_pte_t gtt_entry;
2481         dma_addr_t addr;
2482         int rpm_atomic_seq;
2483         int i = 0;
2484
2485         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2486
2487         gtt_entries = (gen6_pte_t __iomem *)ggtt->gsm + (start >> PAGE_SHIFT);
2488
2489         for_each_sgt_dma(addr, sgt_iter, st) {
2490                 gtt_entry = vm->pte_encode(addr, level, true, flags);
2491                 iowrite32(gtt_entry, &gtt_entries[i++]);
2492         }
2493
2494         /* XXX: This serves as a posting read to make sure that the PTE has
2495          * actually been updated. There is some concern that even though
2496          * registers and PTEs are within the same BAR that they are potentially
2497          * of NUMA access patterns. Therefore, even with the way we assume
2498          * hardware should work, we must keep this posting read for paranoia.
2499          */
2500         if (i != 0)
2501                 WARN_ON(readl(&gtt_entries[i-1]) != gtt_entry);
2502
2503         /* This next bit makes the above posting read even more important. We
2504          * want to flush the TLBs only after we're certain all the PTE updates
2505          * have finished.
2506          */
2507         I915_WRITE(GFX_FLSH_CNTL_GEN6, GFX_FLSH_CNTL_EN);
2508         POSTING_READ(GFX_FLSH_CNTL_GEN6);
2509
2510         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2511 }
2512
2513 static void nop_clear_range(struct i915_address_space *vm,
2514                             uint64_t start,
2515                             uint64_t length,
2516                             bool use_scratch)
2517 {
2518 }
2519
2520 static void gen8_ggtt_clear_range(struct i915_address_space *vm,
2521                                   uint64_t start,
2522                                   uint64_t length,
2523                                   bool use_scratch)
2524 {
2525         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2526         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2527         unsigned first_entry = start >> PAGE_SHIFT;
2528         unsigned num_entries = length >> PAGE_SHIFT;
2529         gen8_pte_t scratch_pte, __iomem *gtt_base =
2530                 (gen8_pte_t __iomem *)ggtt->gsm + first_entry;
2531         const int max_entries = ggtt_total_entries(ggtt) - first_entry;
2532         int i;
2533         int rpm_atomic_seq;
2534
2535         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2536
2537         if (WARN(num_entries > max_entries,
2538                  "First entry = %d; Num entries = %d (max=%d)\n",
2539                  first_entry, num_entries, max_entries))
2540                 num_entries = max_entries;
2541
2542         scratch_pte = gen8_pte_encode(px_dma(vm->scratch_page),
2543                                       I915_CACHE_LLC,
2544                                       use_scratch);
2545         for (i = 0; i < num_entries; i++)
2546                 gen8_set_pte(&gtt_base[i], scratch_pte);
2547         readl(gtt_base);
2548
2549         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2550 }
2551
2552 static void gen6_ggtt_clear_range(struct i915_address_space *vm,
2553                                   uint64_t start,
2554                                   uint64_t length,
2555                                   bool use_scratch)
2556 {
2557         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2558         struct i915_ggtt *ggtt = i915_vm_to_ggtt(vm);
2559         unsigned first_entry = start >> PAGE_SHIFT;
2560         unsigned num_entries = length >> PAGE_SHIFT;
2561         gen6_pte_t scratch_pte, __iomem *gtt_base =
2562                 (gen6_pte_t __iomem *)ggtt->gsm + first_entry;
2563         const int max_entries = ggtt_total_entries(ggtt) - first_entry;
2564         int i;
2565         int rpm_atomic_seq;
2566
2567         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2568
2569         if (WARN(num_entries > max_entries,
2570                  "First entry = %d; Num entries = %d (max=%d)\n",
2571                  first_entry, num_entries, max_entries))
2572                 num_entries = max_entries;
2573
2574         scratch_pte = vm->pte_encode(px_dma(vm->scratch_page),
2575                                      I915_CACHE_LLC, use_scratch, 0);
2576
2577         for (i = 0; i < num_entries; i++)
2578                 iowrite32(scratch_pte, &gtt_base[i]);
2579         readl(gtt_base);
2580
2581         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2582 }
2583
2584 static void i915_ggtt_insert_page(struct i915_address_space *vm,
2585                                   dma_addr_t addr,
2586                                   uint64_t offset,
2587                                   enum i915_cache_level cache_level,
2588                                   u32 unused)
2589 {
2590         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2591         unsigned int flags = (cache_level == I915_CACHE_NONE) ?
2592                 AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
2593         int rpm_atomic_seq;
2594
2595         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2596
2597         intel_gtt_insert_page(addr, offset >> PAGE_SHIFT, flags);
2598
2599         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2600 }
2601
2602 static void i915_ggtt_insert_entries(struct i915_address_space *vm,
2603                                      struct sg_table *pages,
2604                                      uint64_t start,
2605                                      enum i915_cache_level cache_level, u32 unused)
2606 {
2607         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2608         unsigned int flags = (cache_level == I915_CACHE_NONE) ?
2609                 AGP_USER_MEMORY : AGP_USER_CACHED_MEMORY;
2610         int rpm_atomic_seq;
2611
2612         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2613
2614         intel_gtt_insert_sg_entries(pages, start >> PAGE_SHIFT, flags);
2615
2616         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2617
2618 }
2619
2620 static void i915_ggtt_clear_range(struct i915_address_space *vm,
2621                                   uint64_t start,
2622                                   uint64_t length,
2623                                   bool unused)
2624 {
2625         struct drm_i915_private *dev_priv = to_i915(vm->dev);
2626         unsigned first_entry = start >> PAGE_SHIFT;
2627         unsigned num_entries = length >> PAGE_SHIFT;
2628         int rpm_atomic_seq;
2629
2630         rpm_atomic_seq = assert_rpm_atomic_begin(dev_priv);
2631
2632         intel_gtt_clear_range(first_entry, num_entries);
2633
2634         assert_rpm_atomic_end(dev_priv, rpm_atomic_seq);
2635 }
2636
2637 static int ggtt_bind_vma(struct i915_vma *vma,
2638                          enum i915_cache_level cache_level,
2639                          u32 flags)
2640 {
2641         struct drm_i915_gem_object *obj = vma->obj;
2642         u32 pte_flags = 0;
2643         int ret;
2644
2645         ret = i915_get_ggtt_vma_pages(vma);
2646         if (ret)
2647                 return ret;
2648
2649         /* Currently applicable only to VLV */
2650         if (obj->gt_ro)
2651                 pte_flags |= PTE_READ_ONLY;
2652
2653         vma->vm->insert_entries(vma->vm, vma->ggtt_view.pages,
2654                                 vma->node.start,
2655                                 cache_level, pte_flags);
2656
2657         /*
2658          * Without aliasing PPGTT there's no difference between
2659          * GLOBAL/LOCAL_BIND, it's all the same ptes. Hence unconditionally
2660          * upgrade to both bound if we bind either to avoid double-binding.
2661          */
2662         vma->bound |= GLOBAL_BIND | LOCAL_BIND;
2663
2664         return 0;
2665 }
2666
2667 static int aliasing_gtt_bind_vma(struct i915_vma *vma,
2668                                  enum i915_cache_level cache_level,
2669                                  u32 flags)
2670 {
2671         u32 pte_flags;
2672         int ret;
2673
2674         ret = i915_get_ggtt_vma_pages(vma);
2675         if (ret)
2676                 return ret;
2677
2678         /* Currently applicable only to VLV */
2679         pte_flags = 0;
2680         if (vma->obj->gt_ro)
2681                 pte_flags |= PTE_READ_ONLY;
2682
2683
2684         if (flags & GLOBAL_BIND) {
2685                 vma->vm->insert_entries(vma->vm,
2686                                         vma->ggtt_view.pages,
2687                                         vma->node.start,
2688                                         cache_level, pte_flags);
2689         }
2690
2691         if (flags & LOCAL_BIND) {
2692                 struct i915_hw_ppgtt *appgtt =
2693                         to_i915(vma->vm->dev)->mm.aliasing_ppgtt;
2694                 appgtt->base.insert_entries(&appgtt->base,
2695                                             vma->ggtt_view.pages,
2696                                             vma->node.start,
2697                                             cache_level, pte_flags);
2698         }
2699
2700         return 0;
2701 }
2702
2703 static void ggtt_unbind_vma(struct i915_vma *vma)
2704 {
2705         struct drm_device *dev = vma->vm->dev;
2706         struct drm_i915_private *dev_priv = to_i915(dev);
2707         struct drm_i915_gem_object *obj = vma->obj;
2708         const uint64_t size = min_t(uint64_t,
2709                                     obj->base.size,
2710                                     vma->node.size);
2711
2712         if (vma->bound & GLOBAL_BIND) {
2713                 vma->vm->clear_range(vma->vm,
2714                                      vma->node.start,
2715                                      size,
2716                                      true);
2717         }
2718
2719         if (dev_priv->mm.aliasing_ppgtt && vma->bound & LOCAL_BIND) {
2720                 struct i915_hw_ppgtt *appgtt = dev_priv->mm.aliasing_ppgtt;
2721
2722                 appgtt->base.clear_range(&appgtt->base,
2723                                          vma->node.start,
2724                                          size,
2725                                          true);
2726         }
2727 }
2728
2729 void i915_gem_gtt_finish_object(struct drm_i915_gem_object *obj)
2730 {
2731         struct drm_device *dev = obj->base.dev;
2732         struct drm_i915_private *dev_priv = to_i915(dev);
2733         bool interruptible;
2734
2735         interruptible = do_idling(dev_priv);
2736
2737         dma_unmap_sg(&dev->pdev->dev, obj->pages->sgl, obj->pages->nents,
2738                      PCI_DMA_BIDIRECTIONAL);
2739
2740         undo_idling(dev_priv, interruptible);
2741 }
2742
2743 static void i915_gtt_color_adjust(struct drm_mm_node *node,
2744                                   unsigned long color,
2745                                   u64 *start,
2746                                   u64 *end)
2747 {
2748         if (node->color != color)
2749                 *start += 4096;
2750
2751         if (!list_empty(&node->node_list)) {
2752                 node = list_entry(node->node_list.next,
2753                                   struct drm_mm_node,
2754                                   node_list);
2755                 if (node->allocated && node->color != color)
2756                         *end -= 4096;
2757         }
2758 }
2759
2760 static int i915_gem_setup_global_gtt(struct drm_device *dev,
2761                                      u64 start,
2762                                      u64 mappable_end,
2763                                      u64 end)
2764 {
2765         /* Let GEM Manage all of the aperture.
2766          *
2767          * However, leave one page at the end still bound to the scratch page.
2768          * There are a number of places where the hardware apparently prefetches
2769          * past the end of the object, and we've seen multiple hangs with the
2770          * GPU head pointer stuck in a batchbuffer bound at the last page of the
2771          * aperture.  One page should be enough to keep any prefetching inside
2772          * of the aperture.
2773          */
2774         struct drm_i915_private *dev_priv = to_i915(dev);
2775         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2776         struct drm_mm_node *entry;
2777         struct drm_i915_gem_object *obj;
2778         unsigned long hole_start, hole_end;
2779         int ret;
2780         unsigned long mappable;
2781         int error;
2782
2783         mappable = min(end, mappable_end) - start;
2784         BUG_ON(mappable_end > end);
2785
2786         ggtt->base.start = start;
2787
2788         /* Subtract the guard page before address space initialization to
2789          * shrink the range used by drm_mm */
2790         ggtt->base.total = end - start - PAGE_SIZE;
2791         i915_address_space_init(&ggtt->base, dev_priv);
2792         ggtt->base.total += PAGE_SIZE;
2793
2794         ret = intel_vgt_balloon(dev_priv);
2795         if (ret)
2796                 return ret;
2797
2798         if (!HAS_LLC(dev))
2799                 ggtt->base.mm.color_adjust = i915_gtt_color_adjust;
2800
2801         /* Mark any preallocated objects as occupied */
2802         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
2803                 struct i915_vma *vma = i915_gem_obj_to_vma(obj, &ggtt->base);
2804
2805                 DRM_DEBUG_KMS("reserving preallocated space: %llx + %zx\n",
2806                               i915_gem_obj_ggtt_offset(obj), obj->base.size);
2807
2808                 WARN_ON(i915_gem_obj_ggtt_bound(obj));
2809                 ret = drm_mm_reserve_node(&ggtt->base.mm, &vma->node);
2810                 if (ret) {
2811                         DRM_DEBUG_KMS("Reservation failed: %i\n", ret);
2812                         return ret;
2813                 }
2814                 vma->bound |= GLOBAL_BIND;
2815                 __i915_vma_set_map_and_fenceable(vma);
2816                 list_add_tail(&vma->vm_link, &ggtt->base.inactive_list);
2817         }
2818
2819         /* Clear any non-preallocated blocks */
2820         drm_mm_for_each_hole(entry, &ggtt->base.mm, hole_start, hole_end) {
2821                 DRM_DEBUG_KMS("clearing unused GTT space: [%lx, %lx]\n",
2822                               hole_start, hole_end);
2823                 ggtt->base.clear_range(&ggtt->base, hole_start,
2824                                      hole_end - hole_start, true);
2825         }
2826
2827 #ifdef __DragonFly__
2828         device_printf(dev->dev->bsddev,
2829             "taking over the fictitious range 0x%llx-0x%llx\n",
2830             dev_priv->ggtt.mappable_base + start, dev_priv->ggtt.mappable_base + start + mappable);
2831         error = -vm_phys_fictitious_reg_range(dev_priv->ggtt.mappable_base + start,
2832             dev_priv->ggtt.mappable_base + start + mappable, VM_MEMATTR_WRITE_COMBINING);
2833 #endif
2834
2835         /* And finally clear the reserved guard page */
2836         ggtt->base.clear_range(&ggtt->base, end - PAGE_SIZE, PAGE_SIZE, true);
2837
2838         if (USES_PPGTT(dev) && !USES_FULL_PPGTT(dev)) {
2839                 struct i915_hw_ppgtt *ppgtt;
2840
2841                 ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL);
2842                 if (!ppgtt)
2843                         return -ENOMEM;
2844
2845                 ret = __hw_ppgtt_init(dev, ppgtt);
2846                 if (ret) {
2847                         ppgtt->base.cleanup(&ppgtt->base);
2848                         kfree(ppgtt);
2849                         return ret;
2850                 }
2851
2852                 if (ppgtt->base.allocate_va_range)
2853                         ret = ppgtt->base.allocate_va_range(&ppgtt->base, 0,
2854                                                             ppgtt->base.total);
2855                 if (ret) {
2856                         ppgtt->base.cleanup(&ppgtt->base);
2857                         kfree(ppgtt);
2858                         return ret;
2859                 }
2860
2861                 ppgtt->base.clear_range(&ppgtt->base,
2862                                         ppgtt->base.start,
2863                                         ppgtt->base.total,
2864                                         true);
2865
2866                 dev_priv->mm.aliasing_ppgtt = ppgtt;
2867                 WARN_ON(ggtt->base.bind_vma != ggtt_bind_vma);
2868                 ggtt->base.bind_vma = aliasing_gtt_bind_vma;
2869         }
2870
2871         return 0;
2872 }
2873
2874 /**
2875  * i915_gem_init_ggtt - Initialize GEM for Global GTT
2876  * @dev: DRM device
2877  */
2878 void i915_gem_init_ggtt(struct drm_device *dev)
2879 {
2880         struct drm_i915_private *dev_priv = to_i915(dev);
2881         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2882
2883         i915_gem_setup_global_gtt(dev, 0, ggtt->mappable_end, ggtt->base.total);
2884 }
2885
2886 /**
2887  * i915_ggtt_cleanup_hw - Clean up GGTT hardware initialization
2888  * @dev: DRM device
2889  */
2890 void i915_ggtt_cleanup_hw(struct drm_device *dev)
2891 {
2892         struct drm_i915_private *dev_priv = to_i915(dev);
2893         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2894
2895         if (dev_priv->mm.aliasing_ppgtt) {
2896                 struct i915_hw_ppgtt *ppgtt = dev_priv->mm.aliasing_ppgtt;
2897
2898                 ppgtt->base.cleanup(&ppgtt->base);
2899                 kfree(ppgtt);
2900         }
2901
2902         i915_gem_cleanup_stolen(dev);
2903
2904         if (drm_mm_initialized(&ggtt->base.mm)) {
2905                 intel_vgt_deballoon(dev_priv);
2906
2907                 drm_mm_takedown(&ggtt->base.mm);
2908                 list_del(&ggtt->base.global_link);
2909         }
2910
2911         ggtt->base.cleanup(&ggtt->base);
2912 }
2913
2914 static unsigned int gen6_get_total_gtt_size(u16 snb_gmch_ctl)
2915 {
2916         snb_gmch_ctl >>= SNB_GMCH_GGMS_SHIFT;
2917         snb_gmch_ctl &= SNB_GMCH_GGMS_MASK;
2918         return snb_gmch_ctl << 20;
2919 }
2920
2921 static unsigned int gen8_get_total_gtt_size(u16 bdw_gmch_ctl)
2922 {
2923         bdw_gmch_ctl >>= BDW_GMCH_GGMS_SHIFT;
2924         bdw_gmch_ctl &= BDW_GMCH_GGMS_MASK;
2925         if (bdw_gmch_ctl)
2926                 bdw_gmch_ctl = 1 << bdw_gmch_ctl;
2927
2928 #ifdef CONFIG_X86_32
2929         /* Limit 32b platforms to a 2GB GGTT: 4 << 20 / pte size * PAGE_SIZE */
2930         if (bdw_gmch_ctl > 4)
2931                 bdw_gmch_ctl = 4;
2932 #endif
2933
2934         return bdw_gmch_ctl << 20;
2935 }
2936
2937 static unsigned int chv_get_total_gtt_size(u16 gmch_ctrl)
2938 {
2939         gmch_ctrl >>= SNB_GMCH_GGMS_SHIFT;
2940         gmch_ctrl &= SNB_GMCH_GGMS_MASK;
2941
2942         if (gmch_ctrl)
2943                 return 1 << (20 + gmch_ctrl);
2944
2945         return 0;
2946 }
2947
2948 static size_t gen6_get_stolen_size(u16 snb_gmch_ctl)
2949 {
2950         snb_gmch_ctl >>= SNB_GMCH_GMS_SHIFT;
2951         snb_gmch_ctl &= SNB_GMCH_GMS_MASK;
2952         return snb_gmch_ctl << 25; /* 32 MB units */
2953 }
2954
2955 static size_t gen8_get_stolen_size(u16 bdw_gmch_ctl)
2956 {
2957         bdw_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
2958         bdw_gmch_ctl &= BDW_GMCH_GMS_MASK;
2959         return bdw_gmch_ctl << 25; /* 32 MB units */
2960 }
2961
2962 static size_t chv_get_stolen_size(u16 gmch_ctrl)
2963 {
2964         gmch_ctrl >>= SNB_GMCH_GMS_SHIFT;
2965         gmch_ctrl &= SNB_GMCH_GMS_MASK;
2966
2967         /*
2968          * 0x0  to 0x10: 32MB increments starting at 0MB
2969          * 0x11 to 0x16: 4MB increments starting at 8MB
2970          * 0x17 to 0x1d: 4MB increments start at 36MB
2971          */
2972         if (gmch_ctrl < 0x11)
2973                 return gmch_ctrl << 25;
2974         else if (gmch_ctrl < 0x17)
2975                 return (gmch_ctrl - 0x11 + 2) << 22;
2976         else
2977                 return (gmch_ctrl - 0x17 + 9) << 22;
2978 }
2979
2980 static size_t gen9_get_stolen_size(u16 gen9_gmch_ctl)
2981 {
2982         gen9_gmch_ctl >>= BDW_GMCH_GMS_SHIFT;
2983         gen9_gmch_ctl &= BDW_GMCH_GMS_MASK;
2984
2985         if (gen9_gmch_ctl < 0xf0)
2986                 return gen9_gmch_ctl << 25; /* 32 MB units */
2987         else
2988                 /* 4MB increments starting at 0xf0 for 4MB */
2989                 return (gen9_gmch_ctl - 0xf0 + 1) << 22;
2990 }
2991
2992 static int ggtt_probe_common(struct drm_device *dev,
2993                              size_t gtt_size)
2994 {
2995         struct drm_i915_private *dev_priv = to_i915(dev);
2996         struct i915_ggtt *ggtt = &dev_priv->ggtt;
2997         struct i915_page_scratch *scratch_page;
2998         phys_addr_t ggtt_phys_addr;
2999
3000         /* For Modern GENs the PTEs and register space are split in the BAR */
3001         ggtt_phys_addr = pci_resource_start(dev->pdev, 0) +
3002                          (pci_resource_len(dev->pdev, 0) / 2);
3003
3004         /*
3005          * On BXT writes larger than 64 bit to the GTT pagetable range will be
3006          * dropped. For WC mappings in general we have 64 byte burst writes
3007          * when the WC buffer is flushed, so we can't use it, but have to
3008          * resort to an uncached mapping. The WC issue is easily caught by the
3009          * readback check when writing GTT PTE entries.
3010          */
3011         if (IS_BROXTON(dev))
3012                 ggtt->gsm = ioremap_nocache(ggtt_phys_addr, gtt_size);
3013         else
3014                 ggtt->gsm = ioremap_wc(ggtt_phys_addr, gtt_size);
3015         if (!ggtt->gsm) {
3016                 DRM_ERROR("Failed to map the gtt page table\n");
3017                 return -ENOMEM;
3018         }
3019
3020         scratch_page = alloc_scratch_page(dev);
3021         if (IS_ERR(scratch_page)) {
3022                 DRM_ERROR("Scratch setup failed\n");
3023                 /* iounmap will also get called at remove, but meh */
3024                 iounmap(ggtt->gsm);
3025                 return PTR_ERR(scratch_page);
3026         }
3027
3028         ggtt->base.scratch_page = scratch_page;
3029
3030         return 0;
3031 }
3032
3033 /* The GGTT and PPGTT need a private PPAT setup in order to handle cacheability
3034  * bits. When using advanced contexts each context stores its own PAT, but
3035  * writing this data shouldn't be harmful even in those cases. */
3036 static void bdw_setup_private_ppat(struct drm_i915_private *dev_priv)
3037 {
3038         uint64_t pat;
3039
3040         pat = GEN8_PPAT(0, GEN8_PPAT_WB | GEN8_PPAT_LLC)     | /* for normal objects, no eLLC */
3041               GEN8_PPAT(1, GEN8_PPAT_WC | GEN8_PPAT_LLCELLC) | /* for something pointing to ptes? */
3042               GEN8_PPAT(2, GEN8_PPAT_WT | GEN8_PPAT_LLCELLC) | /* for scanout with eLLC */
3043               GEN8_PPAT(3, GEN8_PPAT_UC)                     | /* Uncached objects, mostly for scanout */
3044               GEN8_PPAT(4, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(0)) |
3045               GEN8_PPAT(5, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(1)) |
3046               GEN8_PPAT(6, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(2)) |
3047               GEN8_PPAT(7, GEN8_PPAT_WB | GEN8_PPAT_LLCELLC | GEN8_PPAT_AGE(3));
3048
3049         if (!USES_PPGTT(dev_priv))
3050                 /* Spec: "For GGTT, there is NO pat_sel[2:0] from the entry,
3051                  * so RTL will always use the value corresponding to
3052                  * pat_sel = 000".
3053                  * So let's disable cache for GGTT to avoid screen corruptions.
3054                  * MOCS still can be used though.
3055                  * - System agent ggtt writes (i.e. cpu gtt mmaps) already work
3056                  * before this patch, i.e. the same uncached + snooping access
3057                  * like on gen6/7 seems to be in effect.
3058                  * - So this just fixes blitter/render access. Again it looks
3059                  * like it's not just uncached access, but uncached + snooping.
3060                  * So we can still hold onto all our assumptions wrt cpu
3061                  * clflushing on LLC machines.
3062                  */
3063                 pat = GEN8_PPAT(0, GEN8_PPAT_UC);
3064
3065         /* XXX: spec defines this as 2 distinct registers. It's unclear if a 64b
3066          * write would work. */
3067         I915_WRITE(GEN8_PRIVATE_PAT_LO, pat);
3068         I915_WRITE(GEN8_PRIVATE_PAT_HI, pat >> 32);
3069 }
3070
3071 static void chv_setup_private_ppat(struct drm_i915_private *dev_priv)
3072 {
3073         uint64_t pat;
3074
3075         /*
3076          * Map WB on BDW to snooped on CHV.
3077          *
3078          * Only the snoop bit has meaning for CHV, the rest is
3079          * ignored.
3080          *
3081          * The hardware will never snoop for certain types of accesses:
3082          * - CPU GTT (GMADR->GGTT->no snoop->memory)
3083          * - PPGTT page tables
3084          * - some other special cycles
3085          *
3086          * As with BDW, we also need to consider the following for GT accesses:
3087          * "For GGTT, there is NO pat_sel[2:0] from the entry,
3088          * so RTL will always use the value corresponding to
3089          * pat_sel = 000".
3090          * Which means we must set the snoop bit in PAT entry 0
3091          * in order to keep the global status page working.
3092          */
3093         pat = GEN8_PPAT(0, CHV_PPAT_SNOOP) |
3094               GEN8_PPAT(1, 0) |
3095               GEN8_PPAT(2, 0) |
3096               GEN8_PPAT(3, 0) |
3097               GEN8_PPAT(4, CHV_PPAT_SNOOP) |
3098               GEN8_PPAT(5, CHV_PPAT_SNOOP) |
3099               GEN8_PPAT(6, CHV_PPAT_SNOOP) |
3100               GEN8_PPAT(7, CHV_PPAT_SNOOP);
3101
3102         I915_WRITE(GEN8_PRIVATE_PAT_LO, pat);
3103         I915_WRITE(GEN8_PRIVATE_PAT_HI, pat >> 32);
3104 }
3105
3106 static int gen8_gmch_probe(struct i915_ggtt *ggtt)
3107 {
3108         struct drm_device *dev = ggtt->base.dev;
3109         struct drm_i915_private *dev_priv = to_i915(dev);
3110         u16 snb_gmch_ctl;
3111         int ret;
3112
3113         /* TODO: We're not aware of mappable constraints on gen8 yet */
3114         ggtt->mappable_base = pci_resource_start(dev->pdev, 2);
3115         ggtt->mappable_end = pci_resource_len(dev->pdev, 2);
3116
3117 #if 0
3118         if (!pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(39)))
3119                 pci_set_consistent_dma_mask(dev->pdev, DMA_BIT_MASK(39));
3120 #endif
3121
3122         pci_read_config_word(dev->pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
3123
3124         if (INTEL_INFO(dev)->gen >= 9) {
3125                 ggtt->stolen_size = gen9_get_stolen_size(snb_gmch_ctl);
3126                 ggtt->size = gen8_get_total_gtt_size(snb_gmch_ctl);
3127         } else if (IS_CHERRYVIEW(dev)) {
3128                 ggtt->stolen_size = chv_get_stolen_size(snb_gmch_ctl);
3129                 ggtt->size = chv_get_total_gtt_size(snb_gmch_ctl);
3130         } else {
3131                 ggtt->stolen_size = gen8_get_stolen_size(snb_gmch_ctl);
3132                 ggtt->size = gen8_get_total_gtt_size(snb_gmch_ctl);
3133         }
3134
3135         ggtt->base.total = (ggtt->size / sizeof(gen8_pte_t)) << PAGE_SHIFT;
3136
3137         if (IS_CHERRYVIEW(dev) || IS_BROXTON(dev))
3138                 chv_setup_private_ppat(dev_priv);
3139         else
3140                 bdw_setup_private_ppat(dev_priv);
3141
3142         ret = ggtt_probe_common(dev, ggtt->size);
3143
3144         ggtt->base.bind_vma = ggtt_bind_vma;
3145         ggtt->base.unbind_vma = ggtt_unbind_vma;
3146         ggtt->base.insert_page = gen8_ggtt_insert_page;
3147         ggtt->base.clear_range = nop_clear_range;
3148         if (!USES_FULL_PPGTT(dev_priv) || intel_scanout_needs_vtd_wa(dev_priv))
3149                 ggtt->base.clear_range = gen8_ggtt_clear_range;
3150
3151         ggtt->base.insert_entries = gen8_ggtt_insert_entries;
3152         if (IS_CHERRYVIEW(dev_priv))
3153                 ggtt->base.insert_entries = gen8_ggtt_insert_entries__BKL;
3154
3155         return ret;
3156 }
3157
3158 static int gen6_gmch_probe(struct i915_ggtt *ggtt)
3159 {
3160         struct drm_device *dev = ggtt->base.dev;
3161         u16 snb_gmch_ctl;
3162         int ret;
3163
3164         ggtt->mappable_base = pci_resource_start(dev->pdev, 2);
3165         ggtt->mappable_end = pci_resource_len(dev->pdev, 2);
3166
3167         /* 64/512MB is the current min/max we actually know of, but this is just
3168          * a coarse sanity check.
3169          */
3170         if ((ggtt->mappable_end < (64<<20) || (ggtt->mappable_end > (512<<20)))) {
3171                 DRM_ERROR("Unknown GMADR size (%llx)\n", ggtt->mappable_end);
3172                 return -ENXIO;
3173         }
3174
3175 #if 0
3176         if (!pci_set_dma_mask(dev->pdev, DMA_BIT_MASK(40)))
3177                 pci_set_consistent_dma_mask(dev->pdev, DMA_BIT_MASK(40));
3178 #endif
3179         pci_read_config_word(dev->pdev, SNB_GMCH_CTRL, &snb_gmch_ctl);
3180
3181         ggtt->stolen_size = gen6_get_stolen_size(snb_gmch_ctl);
3182         ggtt->size = gen6_get_total_gtt_size(snb_gmch_ctl);
3183         ggtt->base.total = (ggtt->size / sizeof(gen6_pte_t)) << PAGE_SHIFT;
3184
3185         ret = ggtt_probe_common(dev, ggtt->size);
3186
3187         ggtt->base.clear_range = gen6_ggtt_clear_range;
3188         ggtt->base.insert_page = gen6_ggtt_insert_page;
3189         ggtt->base.insert_entries = gen6_ggtt_insert_entries;
3190         ggtt->base.bind_vma = ggtt_bind_vma;
3191         ggtt->base.unbind_vma = ggtt_unbind_vma;
3192
3193         return ret;
3194 }
3195
3196 static void gen6_gmch_remove(struct i915_address_space *vm)
3197 {
3198         struct i915_ggtt *ggtt = container_of(vm, struct i915_ggtt, base);
3199
3200         iounmap(ggtt->gsm);
3201         free_scratch_page(vm->dev, vm->scratch_page);
3202 }
3203
3204 static int i915_gmch_probe(struct i915_ggtt *ggtt)
3205 {
3206         struct drm_device *dev = ggtt->base.dev;
3207         struct drm_i915_private *dev_priv = to_i915(dev);
3208 #if 0
3209         int ret;
3210
3211         ret = intel_gmch_probe(dev_priv->bridge_dev, dev_priv->drm.pdev, NULL);
3212         if (!ret) {
3213                 DRM_ERROR("failed to set up gmch\n");
3214                 return -EIO;
3215         }
3216 #endif
3217
3218         intel_gtt_get(&ggtt->base.total, &ggtt->stolen_size,
3219                       &ggtt->mappable_base, &ggtt->mappable_end);
3220
3221         ggtt->do_idle_maps = needs_idle_maps(&dev_priv->drm);
3222         ggtt->base.insert_page = i915_ggtt_insert_page;
3223         ggtt->base.insert_entries = i915_ggtt_insert_entries;
3224         ggtt->base.clear_range = i915_ggtt_clear_range;
3225         ggtt->base.bind_vma = ggtt_bind_vma;
3226         ggtt->base.unbind_vma = ggtt_unbind_vma;
3227
3228         if (unlikely(ggtt->do_idle_maps))
3229                 DRM_INFO("applying Ironlake quirks for intel_iommu\n");
3230
3231         return 0;
3232 }
3233
3234 static void i915_gmch_remove(struct i915_address_space *vm)
3235 {
3236         intel_gmch_remove();
3237 }
3238
3239 /**
3240  * i915_ggtt_init_hw - Initialize GGTT hardware
3241  * @dev: DRM device
3242  */
3243 int i915_ggtt_init_hw(struct drm_device *dev)
3244 {
3245         struct drm_i915_private *dev_priv = to_i915(dev);
3246         struct i915_ggtt *ggtt = &dev_priv->ggtt;
3247         int ret;
3248
3249         if (INTEL_INFO(dev)->gen <= 5) {
3250                 ggtt->probe = i915_gmch_probe;
3251                 ggtt->base.cleanup = i915_gmch_remove;
3252         } else if (INTEL_INFO(dev)->gen < 8) {
3253                 ggtt->probe = gen6_gmch_probe;
3254                 ggtt->base.cleanup = gen6_gmch_remove;
3255
3256                 if (HAS_EDRAM(dev))
3257                         ggtt->base.pte_encode = iris_pte_encode;
3258                 else if (IS_HASWELL(dev))
3259                         ggtt->base.pte_encode = hsw_pte_encode;
3260                 else if (IS_VALLEYVIEW(dev))
3261                         ggtt->base.pte_encode = byt_pte_encode;
3262                 else if (INTEL_INFO(dev)->gen >= 7)
3263                         ggtt->base.pte_encode = ivb_pte_encode;
3264                 else
3265                         ggtt->base.pte_encode = snb_pte_encode;
3266         } else {
3267                 ggtt->probe = gen8_gmch_probe;
3268                 ggtt->base.cleanup = gen6_gmch_remove;
3269         }
3270
3271         ggtt->base.dev = dev;
3272         ggtt->base.is_ggtt = true;
3273
3274         ret = ggtt->probe(ggtt);
3275         if (ret)
3276                 return ret;
3277
3278         if ((ggtt->base.total - 1) >> 32) {
3279                 DRM_ERROR("We never expected a Global GTT with more than 32bits"
3280                           "of address space! Found %lldM!\n",
3281                           ggtt->base.total >> 20);
3282                 ggtt->base.total = 1ULL << 32;
3283                 ggtt->mappable_end = min(ggtt->mappable_end, ggtt->base.total);
3284         }
3285
3286         /*
3287          * Initialise stolen early so that we may reserve preallocated
3288          * objects for the BIOS to KMS transition.
3289          */
3290         ret = i915_gem_init_stolen(dev);
3291         if (ret)
3292                 goto out_gtt_cleanup;
3293
3294         /* GMADR is the PCI mmio aperture into the global GTT. */
3295         DRM_INFO("Memory usable by graphics device = %lluM\n",
3296                  ggtt->base.total >> 20);
3297         DRM_DEBUG_DRIVER("GMADR size = %lldM\n", ggtt->mappable_end >> 20);
3298         DRM_DEBUG_DRIVER("GTT stolen size = %zdM\n", ggtt->stolen_size >> 20);
3299 #ifdef CONFIG_INTEL_IOMMU
3300         if (intel_iommu_gfx_mapped)
3301                 DRM_INFO("VT-d active for gfx access\n");
3302 #endif
3303
3304         return 0;
3305
3306 out_gtt_cleanup:
3307         ggtt->base.cleanup(&ggtt->base);
3308
3309         return ret;
3310 }
3311
3312 int i915_ggtt_enable_hw(struct drm_device *dev)
3313 {
3314         if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
3315                 return -EIO;
3316
3317         return 0;
3318 }
3319
3320 void i915_gem_restore_gtt_mappings(struct drm_device *dev)
3321 {
3322         struct drm_i915_private *dev_priv = to_i915(dev);
3323         struct i915_ggtt *ggtt = &dev_priv->ggtt;
3324         struct drm_i915_gem_object *obj;
3325         struct i915_vma *vma;
3326
3327         i915_check_and_clear_faults(dev_priv);
3328
3329         /* First fill our portion of the GTT with scratch pages */
3330         ggtt->base.clear_range(&ggtt->base, ggtt->base.start, ggtt->base.total,
3331                                true);
3332
3333         /* Cache flush objects bound into GGTT and rebind them. */
3334         list_for_each_entry(obj, &dev_priv->mm.bound_list, global_list) {
3335                 list_for_each_entry(vma, &obj->vma_list, obj_link) {
3336                         if (vma->vm != &ggtt->base)
3337                                 continue;
3338
3339                         WARN_ON(i915_vma_bind(vma, obj->cache_level,
3340                                               PIN_UPDATE));
3341                 }
3342
3343                 if (obj->pin_display)
3344                         WARN_ON(i915_gem_object_set_to_gtt_domain(obj, false));
3345         }
3346
3347         if (INTEL_INFO(dev)->gen >= 8) {
3348                 if (IS_CHERRYVIEW(dev) || IS_BROXTON(dev))
3349                         chv_setup_private_ppat(dev_priv);
3350                 else
3351                         bdw_setup_private_ppat(dev_priv);
3352
3353                 return;
3354         }
3355
3356         if (USES_PPGTT(dev)) {
3357                 struct i915_address_space *vm;
3358
3359                 list_for_each_entry(vm, &dev_priv->vm_list, global_link) {
3360                         /* TODO: Perhaps it shouldn't be gen6 specific */
3361
3362                         struct i915_hw_ppgtt *ppgtt;
3363
3364                         if (vm->is_ggtt)
3365                                 ppgtt = dev_priv->mm.aliasing_ppgtt;
3366                         else
3367                                 ppgtt = i915_vm_to_ppgtt(vm);
3368
3369                         gen6_write_page_range(dev_priv, &ppgtt->pd,
3370                                               0, ppgtt->base.total);
3371                 }
3372         }
3373
3374         i915_ggtt_flush(dev_priv);
3375 }
3376
3377 static struct i915_vma *
3378 __i915_gem_vma_create(struct drm_i915_gem_object *obj,
3379                       struct i915_address_space *vm,
3380                       const struct i915_ggtt_view *ggtt_view)
3381 {
3382         struct i915_vma *vma;
3383
3384         if (WARN_ON(i915_is_ggtt(vm) != !!ggtt_view))
3385                 return ERR_PTR(-EINVAL);
3386
3387         vma = kzalloc(sizeof(*vma), GFP_KERNEL);
3388         if (vma == NULL)
3389                 return ERR_PTR(-ENOMEM);
3390
3391         INIT_LIST_HEAD(&vma->vm_link);
3392         INIT_LIST_HEAD(&vma->obj_link);
3393         INIT_LIST_HEAD(&vma->exec_list);
3394         vma->vm = vm;
3395         vma->obj = obj;
3396         vma->is_ggtt = i915_is_ggtt(vm);
3397
3398         if (i915_is_ggtt(vm))
3399                 vma->ggtt_view = *ggtt_view;
3400         else
3401                 i915_ppgtt_get(i915_vm_to_ppgtt(vm));
3402
3403         list_add_tail(&vma->obj_link, &obj->vma_list);
3404
3405         return vma;
3406 }
3407
3408 struct i915_vma *
3409 i915_gem_obj_lookup_or_create_vma(struct drm_i915_gem_object *obj,
3410                                   struct i915_address_space *vm)
3411 {
3412         struct i915_vma *vma;
3413
3414         vma = i915_gem_obj_to_vma(obj, vm);
3415         if (!vma)
3416                 vma = __i915_gem_vma_create(obj, vm,
3417                                             i915_is_ggtt(vm) ? &i915_ggtt_view_normal : NULL);
3418
3419         return vma;
3420 }
3421
3422 struct i915_vma *
3423 i915_gem_obj_lookup_or_create_ggtt_vma(struct drm_i915_gem_object *obj,
3424                                        const struct i915_ggtt_view *view)
3425 {
3426         struct drm_device *dev = obj->base.dev;
3427         struct drm_i915_private *dev_priv = to_i915(dev);
3428         struct i915_ggtt *ggtt = &dev_priv->ggtt;
3429         struct i915_vma *vma = i915_gem_obj_to_ggtt_view(obj, view);
3430
3431         if (!vma)
3432                 vma = __i915_gem_vma_create(obj, &ggtt->base, view);
3433
3434         return vma;
3435
3436 }
3437
3438 static struct scatterlist *
3439 rotate_pages(const dma_addr_t *in, unsigned int offset,
3440              unsigned int width, unsigned int height,
3441              unsigned int stride,
3442              struct sg_table *st, struct scatterlist *sg)
3443 {
3444         unsigned int column, row;
3445         unsigned int src_idx;
3446
3447         for (column = 0; column < width; column++) {
3448                 src_idx = stride * (height - 1) + column;
3449                 for (row = 0; row < height; row++) {
3450                         st->nents++;
3451                         /* We don't need the pages, but need to initialize
3452                          * the entries so the sg list can be happily traversed.
3453                          * The only thing we need are DMA addresses.
3454                          */
3455                         sg_set_page(sg, NULL, PAGE_SIZE, 0);
3456                         sg_dma_address(sg) = in[offset + src_idx];
3457                         sg_dma_len(sg) = PAGE_SIZE;
3458                         sg = sg_next(sg);
3459                         src_idx -= stride;
3460                 }
3461         }
3462
3463         return sg;
3464 }
3465
3466 static struct sg_table *
3467 intel_rotate_fb_obj_pages(struct intel_rotation_info *rot_info,
3468                           struct drm_i915_gem_object *obj)
3469 {
3470         unsigned int size_pages = rot_info->plane[0].width * rot_info->plane[0].height;
3471         unsigned int size_pages_uv;
3472         struct sgt_iter sgt_iter;
3473         dma_addr_t dma_addr;
3474         unsigned long i;
3475         dma_addr_t *page_addr_list;
3476         struct sg_table *st;
3477         unsigned int uv_start_page;
3478         struct scatterlist *sg;
3479         int ret = -ENOMEM;
3480
3481         /* Allocate a temporary list of source pages for random access. */
3482         page_addr_list = drm_malloc_ab(obj->base.size / PAGE_SIZE,
3483                                        sizeof(dma_addr_t));
3484         if (!page_addr_list)
3485                 return ERR_PTR(ret);
3486
3487         /* Account for UV plane with NV12. */
3488         if (rot_info->pixel_format == DRM_FORMAT_NV12)
3489                 size_pages_uv = rot_info->plane[1].width * rot_info->plane[1].height;
3490         else
3491                 size_pages_uv = 0;
3492
3493         /* Allocate target SG list. */
3494         st = kmalloc(sizeof(*st), M_DRM, M_WAITOK);
3495         if (!st)
3496                 goto err_st_alloc;
3497
3498         ret = sg_alloc_table(st, size_pages + size_pages_uv, GFP_KERNEL);
3499         if (ret)
3500                 goto err_sg_alloc;
3501
3502         /* Populate source page list from the object. */
3503         i = 0;
3504         for_each_sgt_dma(dma_addr, sgt_iter, obj->pages)
3505                 page_addr_list[i++] = dma_addr;
3506
3507         GEM_BUG_ON(i != n_pages);
3508         st->nents = 0;
3509         sg = st->sgl;
3510
3511         /* Rotate the pages. */
3512         sg = rotate_pages(page_addr_list, 0,
3513                           rot_info->plane[0].width, rot_info->plane[0].height,
3514                           rot_info->plane[0].width,
3515                           st, sg);
3516
3517         /* Append the UV plane if NV12. */
3518         if (rot_info->pixel_format == DRM_FORMAT_NV12) {
3519                 uv_start_page = size_pages;
3520
3521                 /* Check for tile-row un-alignment. */
3522                 if (offset_in_page(rot_info->uv_offset))
3523                         uv_start_page--;
3524
3525                 rot_info->uv_start_page = uv_start_page;
3526
3527                 sg = rotate_pages(page_addr_list, rot_info->uv_start_page,
3528                                   rot_info->plane[1].width, rot_info->plane[1].height,
3529                                   rot_info->plane[1].width,
3530                                   st, sg);
3531         }
3532
3533         DRM_DEBUG_KMS("Created rotated page mapping for object size %zu (%ux%u tiles, %u pages (%u plane 0)).\n",
3534                       obj->base.size, rot_info->plane[0].width,
3535                       rot_info->plane[0].height, size_pages + size_pages_uv,
3536                       size_pages);
3537
3538         drm_free_large(page_addr_list);
3539
3540         return st;
3541
3542 err_sg_alloc:
3543         kfree(st);
3544 err_st_alloc:
3545         drm_free_large(page_addr_list);
3546
3547         DRM_DEBUG_KMS("Failed to create rotated mapping for object size %zu! (%d) (%ux%u tiles, %u pages (%u plane 0))\n",
3548                       obj->base.size, ret, rot_info->plane[0].width,
3549                       rot_info->plane[0].height, size_pages + size_pages_uv,
3550                       size_pages);
3551         return ERR_PTR(ret);
3552 }
3553
3554 static struct sg_table *
3555 intel_partial_pages(const struct i915_ggtt_view *view,
3556                     struct drm_i915_gem_object *obj)
3557 {
3558         struct sg_table *st;
3559         struct scatterlist *sg;
3560         struct sg_page_iter obj_sg_iter;
3561         int ret = -ENOMEM;
3562
3563         st = kmalloc(sizeof(*st), M_DRM, M_WAITOK);
3564         if (!st)
3565                 goto err_st_alloc;
3566
3567         ret = sg_alloc_table(st, view->params.partial.size, GFP_KERNEL);
3568         if (ret)
3569                 goto err_sg_alloc;
3570
3571         sg = st->sgl;
3572         st->nents = 0;
3573         for_each_sg_page(obj->pages->sgl, &obj_sg_iter, obj->pages->nents,
3574                 view->params.partial.offset)
3575         {
3576                 if (st->nents >= view->params.partial.size)
3577                         break;
3578
3579                 sg_set_page(sg, NULL, PAGE_SIZE, 0);
3580                 sg_dma_address(sg) = sg_page_iter_dma_address(&obj_sg_iter);
3581                 sg_dma_len(sg) = PAGE_SIZE;
3582
3583                 sg = sg_next(sg);
3584                 st->nents++;
3585         }
3586
3587         return st;
3588
3589 err_sg_alloc:
3590         kfree(st);
3591 err_st_alloc:
3592         return ERR_PTR(ret);
3593 }
3594
3595 static int
3596 i915_get_ggtt_vma_pages(struct i915_vma *vma)
3597 {
3598         int ret = 0;
3599
3600         if (vma->ggtt_view.pages)
3601                 return 0;
3602
3603         if (vma->ggtt_view.type == I915_GGTT_VIEW_NORMAL)
3604                 vma->ggtt_view.pages = vma->obj->pages;
3605         else if (vma->ggtt_view.type == I915_GGTT_VIEW_ROTATED)
3606                 vma->ggtt_view.pages =
3607                         intel_rotate_fb_obj_pages(&vma->ggtt_view.params.rotated, vma->obj);
3608         else if (vma->ggtt_view.type == I915_GGTT_VIEW_PARTIAL)
3609                 vma->ggtt_view.pages =
3610                         intel_partial_pages(&vma->ggtt_view, vma->obj);
3611         else
3612                 WARN_ONCE(1, "GGTT view %u not implemented!\n",
3613                           vma->ggtt_view.type);
3614
3615         if (!vma->ggtt_view.pages) {
3616                 DRM_ERROR("Failed to get pages for GGTT view type %u!\n",
3617                           vma->ggtt_view.type);
3618                 ret = -EINVAL;
3619         } else if (IS_ERR(vma->ggtt_view.pages)) {
3620                 ret = PTR_ERR(vma->ggtt_view.pages);
3621                 vma->ggtt_view.pages = NULL;
3622                 DRM_ERROR("Failed to get pages for VMA view type %u (%d)!\n",
3623                           vma->ggtt_view.type, ret);
3624         }
3625
3626         return ret;
3627 }
3628
3629 /**
3630  * i915_vma_bind - Sets up PTEs for an VMA in it's corresponding address space.
3631  * @vma: VMA to map
3632  * @cache_level: mapping cache level
3633  * @flags: flags like global or local mapping
3634  *
3635  * DMA addresses are taken from the scatter-gather table of this object (or of
3636  * this VMA in case of non-default GGTT views) and PTE entries set up.
3637  * Note that DMA addresses are also the only part of the SG table we care about.
3638  */
3639 int i915_vma_bind(struct i915_vma *vma, enum i915_cache_level cache_level,
3640                   u32 flags)
3641 {
3642         int ret;
3643         u32 bind_flags;
3644
3645         if (WARN_ON(flags == 0))
3646                 return -EINVAL;
3647
3648         bind_flags = 0;
3649         if (flags & PIN_GLOBAL)
3650                 bind_flags |= GLOBAL_BIND;
3651         if (flags & PIN_USER)
3652                 bind_flags |= LOCAL_BIND;
3653
3654         if (flags & PIN_UPDATE)
3655                 bind_flags |= vma->bound;
3656         else
3657                 bind_flags &= ~vma->bound;
3658
3659         if (bind_flags == 0)
3660                 return 0;
3661
3662         if (vma->bound == 0 && vma->vm->allocate_va_range) {
3663                 /* XXX: i915_vma_pin() will fix this +- hack */
3664                 vma->pin_count++;
3665                 trace_i915_va_alloc(vma);
3666                 ret = vma->vm->allocate_va_range(vma->vm,
3667                                                  vma->node.start,
3668                                                  vma->node.size);
3669                 vma->pin_count--;
3670                 if (ret)
3671                         return ret;
3672         }
3673
3674         ret = vma->vm->bind_vma(vma, cache_level, bind_flags);
3675         if (ret)
3676                 return ret;
3677
3678         vma->bound |= bind_flags;
3679
3680         return 0;
3681 }
3682
3683 /**
3684  * i915_ggtt_view_size - Get the size of a GGTT view.
3685  * @obj: Object the view is of.
3686  * @view: The view in question.
3687  *
3688  * @return The size of the GGTT view in bytes.
3689  */
3690 size_t
3691 i915_ggtt_view_size(struct drm_i915_gem_object *obj,
3692                     const struct i915_ggtt_view *view)
3693 {
3694         if (view->type == I915_GGTT_VIEW_NORMAL) {
3695                 return obj->base.size;
3696         } else if (view->type == I915_GGTT_VIEW_ROTATED) {
3697                 return intel_rotation_info_size(&view->params.rotated) << PAGE_SHIFT;
3698         } else if (view->type == I915_GGTT_VIEW_PARTIAL) {
3699                 return view->params.partial.size << PAGE_SHIFT;
3700         } else {
3701                 WARN_ONCE(1, "GGTT view %u not implemented!\n", view->type);
3702                 return obj->base.size;
3703         }
3704 }
3705
3706 void __iomem *i915_vma_pin_iomap(struct i915_vma *vma)
3707 {
3708         void __iomem *ptr;
3709
3710         lockdep_assert_held(&vma->vm->dev->struct_mutex);
3711         if (WARN_ON(!vma->obj->map_and_fenceable))
3712                 return ERR_PTR(-ENODEV);
3713
3714         GEM_BUG_ON(!vma->is_ggtt);
3715         GEM_BUG_ON((vma->bound & GLOBAL_BIND) == 0);
3716
3717         ptr = vma->iomap;
3718         if (ptr == NULL) {
3719                 ptr = io_mapping_map_wc(i915_vm_to_ggtt(vma->vm)->mappable,
3720                                         vma->node.start,
3721                                         vma->node.size);
3722                 if (ptr == NULL)
3723                         return ERR_PTR(-ENOMEM);
3724
3725                 vma->iomap = ptr;
3726         }
3727
3728         vma->pin_count++;
3729         return ptr;
3730 }