rk: ion: resolve build err
[firefly-linux-kernel-4.4.55.git] / drivers / gpu / arm / t6xx / kbase / src / common / mali_kbase_mmu.c
1 /*
2  *
3  * (C) COPYRIGHT ARM Limited. All rights reserved.
4  *
5  * This program is free software and is provided to you under the terms of the
6  * GNU General Public License version 2 as published by the Free Software
7  * Foundation, and any use by you of this program is subject to the terms
8  * of such GNU licence.
9  *
10  * A copy of the licence is included with the program, and can also be obtained
11  * from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
12  * Boston, MA  02110-1301, USA.
13  *
14  */
15
16
17
18
19
20 /**
21  * @file mali_kbase_mmu.c
22  * Base kernel MMU management.
23  */
24
25 /* #define DEBUG    1 */
26 #include <kbase/src/common/mali_kbase.h>
27 #include <kbase/src/common/mali_midg_regmap.h>
28 #include <kbase/src/common/mali_kbase_gator.h>
29
30 #define beenthere(f, a...)  KBASE_DEBUG_PRINT_INFO(KBASE_MMU, "%s:" f, __func__, ##a)
31
32 #include <kbase/src/common/mali_kbase_defs.h>
33 #include <kbase/src/common/mali_kbase_hw.h>
34
35 #define KBASE_MMU_PAGE_ENTRIES 512
36
37 /*
38  * Definitions:
39  * - PGD: Page Directory.
40  * - PTE: Page Table Entry. A 64bit value pointing to the next
41  *        level of translation
42  * - ATE: Address Transation Entry. A 64bit value pointing to
43  *        a 4kB physical page.
44  */
45
46 static void kbase_mmu_report_fault_and_kill(kbase_context *kctx, kbase_as *as);
47 static u64 lock_region(kbase_device *kbdev, u64 pfn, size_t num_pages);
48
49 /* Helper Function to perform assignment of page table entries, to ensure the use of
50  * strd, which is required on LPAE systems.
51  */
52
53 static inline void page_table_entry_set( kbase_device * kbdev, u64 * pte, u64 phy )
54 {
55 #ifdef CONFIG_64BIT
56         *pte = phy;
57 #elif defined(CONFIG_ARM)
58         /*
59          *
60          * In order to prevent the compiler keeping cached copies of memory, we have to explicitly
61          * say that we have updated memory.
62          *
63          * Note: We could manually move the data ourselves into R0 and R1 by specifying
64          * register variables that are explicitly given registers assignments, the down side of
65          * this is that we have to assume cpu endianess.  To avoid this we can use the ldrd to read the
66          * data from memory into R0 and R1 which will respect the cpu endianess, we then use strd to
67          * make the 64 bit assignment to the page table entry.
68          *
69          */
70
71         asm     volatile("ldrd r0, r1, [%[ptemp]]\n\t"
72                                 "strd r0, r1, [%[pte]]\n\t"
73                                 : "=m" (*pte)
74                                 : [ptemp] "r" (&phy), [pte] "r" (pte), "m" (phy)
75                                 : "r0", "r1" );
76 #else
77 #error "64-bit atomic write must be implemented for your architecture"
78 #endif
79 }
80
81 static void ksync_kern_vrange_gpu(phys_addr_t paddr, void *vaddr, size_t size)
82 {
83         kbase_sync_to_memory(paddr, vaddr, size);
84 }
85
86 static size_t make_multiple(size_t minimum, size_t multiple)
87 {
88         size_t remainder = minimum % multiple;
89         if (remainder == 0)
90                 return minimum;
91         else
92                 return minimum + multiple - remainder;
93 }
94
95 static void mmu_mask_reenable(kbase_device *kbdev, kbase_context *kctx, kbase_as *as)
96 {
97         unsigned long flags;
98         u32 mask;
99         spin_lock_irqsave(&kbdev->mmu_mask_change, flags);
100         mask = kbase_reg_read(kbdev, MMU_REG(MMU_IRQ_MASK), kctx);
101         mask |= ((1UL << as->number) | (1UL << (MMU_REGS_BUS_ERROR_FLAG(as->number))));
102         kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_MASK), mask, kctx);
103         spin_unlock_irqrestore(&kbdev->mmu_mask_change, flags);
104 }
105
106 static void page_fault_worker(struct work_struct *data)
107 {
108         u64 fault_pfn;
109         size_t new_pages;
110         size_t fault_rel_pfn;
111         kbase_as *faulting_as;
112         int as_no;
113         kbase_context *kctx;
114         kbase_device *kbdev;
115         kbase_va_region *region;
116         mali_error err;
117
118         faulting_as = container_of(data, kbase_as, work_pagefault);
119         fault_pfn = faulting_as->fault_addr >> PAGE_SHIFT;
120         as_no = faulting_as->number;
121
122         kbdev = container_of(faulting_as, kbase_device, as[as_no]);
123
124         /* Grab the context that was already refcounted in kbase_mmu_interrupt().
125          * Therefore, it cannot be scheduled out of this AS until we explicitly release it
126          *
127          * NOTE: NULL can be returned here if we're gracefully handling a spurious interrupt */
128         kctx = kbasep_js_runpool_lookup_ctx_noretain(kbdev, as_no);
129
130         if (kctx == NULL) {
131                 /* Only handle this if not already suspended */
132                 if ( !kbase_pm_context_active_handle_suspend(kbdev, KBASE_PM_SUSPEND_HANDLER_DONT_REACTIVATE)) {
133                         /* Address space has no context, terminate the work */
134                         u32 reg;
135
136                         /* AS transaction begin */
137                         mutex_lock(&faulting_as->transaction_mutex);
138                         reg = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), NULL);
139                         reg = (reg & (~(u32) MMU_TRANSTAB_ADRMODE_MASK)) | ASn_TRANSTAB_ADRMODE_UNMAPPED;
140                         kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), reg, NULL);
141                         kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_UPDATE, NULL);
142                         mutex_unlock(&faulting_as->transaction_mutex);
143                         /* AS transaction end */
144
145                         mmu_mask_reenable(kbdev, NULL, faulting_as);
146                         kbase_pm_context_idle(kbdev);
147                 }
148                 return;
149         }
150
151         KBASE_DEBUG_ASSERT(kctx->kbdev == kbdev);
152
153         kbase_gpu_vm_lock(kctx);
154
155         /* find the region object for this VA */
156         region = kbase_region_tracker_find_region_enclosing_address(kctx, faulting_as->fault_addr);
157         if (NULL == region || (GROWABLE_FLAGS_REQUIRED != (region->flags & GROWABLE_FLAGS_MASK))) {
158                 kbase_gpu_vm_unlock(kctx);
159                 /* failed to find the region or mismatch of the flags */
160                 kbase_mmu_report_fault_and_kill(kctx, faulting_as);
161                 goto fault_done;
162         }
163
164         if ((((faulting_as->fault_status & ASn_FAULTSTATUS_ACCESS_TYPE_MASK) == ASn_FAULTSTATUS_ACCESS_TYPE_READ) && !(region->flags & KBASE_REG_GPU_RD)) || (((faulting_as->fault_status & ASn_FAULTSTATUS_ACCESS_TYPE_MASK) == ASn_FAULTSTATUS_ACCESS_TYPE_WRITE) && !(region->flags & KBASE_REG_GPU_WR)) || (((faulting_as->fault_status & ASn_FAULTSTATUS_ACCESS_TYPE_MASK) == ASn_FAULTSTATUS_ACCESS_TYPE_EX) && (region->flags & KBASE_REG_GPU_NX))) {
165                 KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Access permissions don't match: region->flags=0x%lx", region->flags);
166                 kbase_gpu_vm_unlock(kctx);
167                 kbase_mmu_report_fault_and_kill(kctx, faulting_as);
168                 goto fault_done;
169         }
170
171         /* find the size we need to grow it by */
172         /* we know the result fit in a size_t due to kbase_region_tracker_find_region_enclosing_address
173          * validating the fault_adress to be within a size_t from the start_pfn */
174         fault_rel_pfn = fault_pfn - region->start_pfn;
175
176         if (fault_rel_pfn < kbase_reg_current_backed_size(region)) {
177                 KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Page fault in allocated region of growable TMEM: Ignoring");
178                 mmu_mask_reenable(kbdev, kctx, faulting_as);
179                 kbase_gpu_vm_unlock(kctx);
180                 goto fault_done;
181         }
182
183         new_pages = make_multiple(fault_rel_pfn - kbase_reg_current_backed_size(region) + 1, region->extent);
184         if (new_pages + kbase_reg_current_backed_size(region) > region->nr_pages) {
185                 /* cap to max vsize */
186                 new_pages = region->nr_pages - kbase_reg_current_backed_size(region);
187         }
188
189         if (0 == new_pages) {
190                 /* Duplicate of a fault we've already handled, nothing to do */
191                 mmu_mask_reenable(kbdev, kctx, faulting_as);
192                 kbase_gpu_vm_unlock(kctx);
193                 goto fault_done;
194         }
195
196         if (MALI_ERROR_NONE == kbase_alloc_phy_pages_helper(region->alloc, new_pages)) {
197                 /* alloc success */
198                 mali_addr64 lock_addr;
199                 KBASE_DEBUG_ASSERT(kbase_reg_current_backed_size(region) <= region->nr_pages);
200
201                 /* AS transaction begin */
202                 mutex_lock(&faulting_as->transaction_mutex);
203
204                 /* Lock the VA region we're about to update */
205                 lock_addr = lock_region(kbdev, faulting_as->fault_addr >> PAGE_SHIFT, new_pages);
206                 kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_LOCKADDR_LO), lock_addr & 0xFFFFFFFFUL, kctx);
207                 kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_LOCKADDR_HI), lock_addr >> 32, kctx);
208                 kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_LOCK, kctx);
209                 if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_T76X_3285)) {
210                         kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_CLEAR), (1UL << as_no), NULL);
211                         kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_LOCK, kctx);
212                 }
213
214                 /* set up the new pages */
215                 err = kbase_mmu_insert_pages(kctx, region->start_pfn + kbase_reg_current_backed_size(region) - new_pages, &kbase_get_phy_pages(region)[kbase_reg_current_backed_size(region) - new_pages], new_pages, region->flags);
216                 if (MALI_ERROR_NONE != err) {
217                         /* failed to insert pages, handle as a normal PF */
218                         mutex_unlock(&faulting_as->transaction_mutex);
219                         kbase_gpu_vm_unlock(kctx);
220                         kbase_free_phy_pages_helper(region->alloc, new_pages);
221                         /* The locked VA region will be unlocked and the cache invalidated in here */
222                         kbase_mmu_report_fault_and_kill(kctx, faulting_as);
223                         goto fault_done;
224                 }
225 #ifdef CONFIG_MALI_GATOR_SUPPORT
226                 kbase_trace_mali_page_fault_insert_pages(as_no, new_pages);
227 #endif                          /* CONFIG_MALI_GATOR_SUPPORT */
228
229                 /* flush L2 and unlock the VA (resumes the MMU) */
230                 if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_6367))
231                         kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_FLUSH, kctx);
232                 else
233                         kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_FLUSH_PT, kctx);
234
235                 /* wait for the flush to complete */
236                 while (kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_STATUS), kctx) & 1)
237                         ;
238
239                 if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_9630)) {
240                         /* Issue an UNLOCK command to ensure that valid page tables are re-read by the GPU after an update.
241                            Note that, the FLUSH command should perform all the actions necessary, however the bus logs show
242                            that if multiple page faults occur within an 8 page region the MMU does not always re-read the
243                            updated page table entries for later faults or is only partially read, it subsequently raises the
244                            page fault IRQ for the same addresses, the unlock ensures that the MMU cache is flushed, so updates
245                            can be re-read.  As the region is now unlocked we need to issue 2 UNLOCK commands in order to flush the
246                            MMU/uTLB, see PRLAM-8812.
247                          */
248                         kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_UNLOCK, kctx);
249                         kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_UNLOCK, kctx);
250                 }
251
252                 mutex_unlock(&faulting_as->transaction_mutex);
253                 /* AS transaction end */
254
255                 /* reenable this in the mask */
256                 mmu_mask_reenable(kbdev, kctx, faulting_as);
257                 kbase_gpu_vm_unlock(kctx);
258         } else {
259                 /* failed to extend, handle as a normal PF */
260                 kbase_gpu_vm_unlock(kctx);
261                 kbase_mmu_report_fault_and_kill(kctx, faulting_as);
262         }
263
264  fault_done:
265         /* By this point, the fault was handled in some way, so release the ctx refcount */
266         kbasep_js_runpool_release_ctx(kbdev, kctx);
267 }
268
269 phys_addr_t kbase_mmu_alloc_pgd(kbase_context *kctx)
270 {
271         phys_addr_t pgd;
272         u64 *page;
273         int i;
274
275         KBASE_DEBUG_ASSERT(NULL != kctx);
276         if (MALI_ERROR_NONE != kbase_mem_usage_request_pages(&kctx->usage, 1))
277                 return 0;
278
279         if (MALI_ERROR_NONE != kbase_mem_usage_request_pages(&kctx->kbdev->memdev.usage, 1))
280         {
281                 kbase_mem_usage_release_pages(&kctx->usage, 1);
282                 return 0;
283         }
284         if (MALI_ERROR_NONE != kbase_mem_allocator_alloc(kctx->pgd_allocator, 1, &pgd)){
285                 kbase_mem_usage_release_pages(&kctx->usage, 1);
286                 kbase_mem_usage_release_pages(&kctx->kbdev->memdev.usage, 1);
287                 return 0;
288         }
289
290         page = kmap(pfn_to_page(PFN_DOWN(pgd)));
291         if (NULL == page) {
292                 kbase_mem_allocator_free(kctx->pgd_allocator, 1, &pgd, MALI_FALSE);
293                 kbase_mem_usage_release_pages(&kctx->usage, 1);
294                 kbase_mem_usage_release_pages(&kctx->kbdev->memdev.usage, 1);
295                 return 0;
296         }
297
298         kbase_process_page_usage_inc(kctx, 1);
299
300         for (i = 0; i < KBASE_MMU_PAGE_ENTRIES; i++)
301                 page_table_entry_set( kctx->kbdev, &page[i], ENTRY_IS_INVAL );
302
303         /* Clean the full page */
304         ksync_kern_vrange_gpu(pgd, page, KBASE_MMU_PAGE_ENTRIES * sizeof(u64));
305         kunmap(pfn_to_page(PFN_DOWN(pgd)));
306         return pgd;
307 }
308
309 KBASE_EXPORT_TEST_API(kbase_mmu_alloc_pgd)
310
311 static phys_addr_t mmu_pte_to_phy_addr(u64 entry)
312 {
313         if (!(entry & 1))
314                 return 0;
315
316         return entry & ~0xFFF;
317 }
318
319 static u64 mmu_phyaddr_to_pte(phys_addr_t phy)
320 {
321         return (phy & ~0xFFF) | ENTRY_IS_PTE;
322 }
323
324 static u64 mmu_phyaddr_to_ate(phys_addr_t phy, u64 flags)
325 {
326         return (phy & ~0xFFF) | (flags & ENTRY_FLAGS_MASK) | ENTRY_IS_ATE;
327 }
328
329 /* Given PGD PFN for level N, return PGD PFN for level N+1 */
330 static phys_addr_t mmu_get_next_pgd(kbase_context *kctx, phys_addr_t pgd, u64 vpfn, int level)
331 {
332         u64 *page;
333         phys_addr_t target_pgd;
334
335         KBASE_DEBUG_ASSERT(pgd);
336         KBASE_DEBUG_ASSERT(NULL != kctx);
337
338         lockdep_assert_held(&kctx->reg_lock);
339
340         /*
341          * Architecture spec defines level-0 as being the top-most.
342          * This is a bit unfortunate here, but we keep the same convention.
343          */
344         vpfn >>= (3 - level) * 9;
345         vpfn &= 0x1FF;
346
347         page = kmap(pfn_to_page(PFN_DOWN(pgd)));
348         if (NULL == page) {
349                 KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "mmu_get_next_pgd: kmap failure\n");
350                 return 0;
351         }
352
353         target_pgd = mmu_pte_to_phy_addr(page[vpfn]);
354
355         if (!target_pgd) {
356                 target_pgd = kbase_mmu_alloc_pgd(kctx);
357                 if (!target_pgd) {
358                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "mmu_get_next_pgd: kbase_mmu_alloc_pgd failure\n");
359                         kunmap(pfn_to_page(PFN_DOWN(pgd)));
360                         return 0;
361                 }
362
363                 page_table_entry_set( kctx->kbdev, &page[vpfn], mmu_phyaddr_to_pte(target_pgd) );
364
365                 ksync_kern_vrange_gpu(pgd + (vpfn * sizeof(u64)), page + vpfn, sizeof(u64));
366                 /* Rely on the caller to update the address space flags. */
367         }
368
369         kunmap(pfn_to_page(PFN_DOWN(pgd)));
370         return target_pgd;
371 }
372
373 static phys_addr_t mmu_get_bottom_pgd(kbase_context *kctx, u64 vpfn)
374 {
375         phys_addr_t pgd;
376         int l;
377
378         pgd = kctx->pgd;
379
380         for (l = MIDGARD_MMU_TOPLEVEL; l < 3; l++) {
381                 pgd = mmu_get_next_pgd(kctx, pgd, vpfn, l);
382                 /* Handle failure condition */
383                 if (!pgd) {
384                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "mmu_get_bottom_pgd: mmu_get_next_pgd failure\n");
385                         return 0;
386                 }
387         }
388
389         return pgd;
390 }
391
392 static phys_addr_t mmu_insert_pages_recover_get_next_pgd(kbase_context *kctx, phys_addr_t pgd, u64 vpfn, int level)
393 {
394         u64 *page;
395         phys_addr_t target_pgd;
396
397         KBASE_DEBUG_ASSERT(pgd);
398         KBASE_DEBUG_ASSERT(NULL != kctx);
399
400         lockdep_assert_held(&kctx->reg_lock);
401
402         /*
403          * Architecture spec defines level-0 as being the top-most.
404          * This is a bit unfortunate here, but we keep the same convention.
405          */
406         vpfn >>= (3 - level) * 9;
407         vpfn &= 0x1FF;
408
409         page = kmap_atomic(pfn_to_page(PFN_DOWN(pgd)));
410         /* kmap_atomic should NEVER fail */
411         KBASE_DEBUG_ASSERT(NULL != page);
412
413         target_pgd = mmu_pte_to_phy_addr(page[vpfn]);
414         /* As we are recovering from what has already been set up, we should have a target_pgd */
415         KBASE_DEBUG_ASSERT(0 != target_pgd);
416
417         kunmap_atomic(page);
418         return target_pgd;
419 }
420
421 static phys_addr_t mmu_insert_pages_recover_get_bottom_pgd(kbase_context *kctx, u64 vpfn)
422 {
423         phys_addr_t pgd;
424         int l;
425
426         pgd = kctx->pgd;
427
428         for (l = MIDGARD_MMU_TOPLEVEL; l < 3; l++) {
429                 pgd = mmu_insert_pages_recover_get_next_pgd(kctx, pgd, vpfn, l);
430                 /* Should never fail */
431                 KBASE_DEBUG_ASSERT(0 != pgd);
432         }
433
434         return pgd;
435 }
436
437 static void mmu_insert_pages_failure_recovery(kbase_context *kctx, u64 vpfn, phys_addr_t *phys, size_t nr)
438 {
439         phys_addr_t pgd;
440         u64 *pgd_page;
441
442         KBASE_DEBUG_ASSERT(NULL != kctx);
443         KBASE_DEBUG_ASSERT(0 != vpfn);
444         KBASE_DEBUG_ASSERT(vpfn <= (UINT64_MAX / PAGE_SIZE));   /* 64-bit address range is the max */
445
446         lockdep_assert_held(&kctx->reg_lock);
447
448         while (nr) {
449                 unsigned int i;
450                 unsigned int index = vpfn & 0x1FF;
451                 unsigned int count = KBASE_MMU_PAGE_ENTRIES - index;
452
453                 if (count > nr)
454                         count = nr;
455
456                 pgd = mmu_insert_pages_recover_get_bottom_pgd(kctx, vpfn);
457                 KBASE_DEBUG_ASSERT(0 != pgd);
458
459                 pgd_page = kmap_atomic(pfn_to_page(PFN_DOWN(pgd)));
460                 KBASE_DEBUG_ASSERT(NULL != pgd_page);
461
462                 /* Invalidate the entries we added */
463                 for (i = 0; i < count; i++)
464                         page_table_entry_set( kctx->kbdev, &pgd_page[index + i], ENTRY_IS_INVAL );
465
466                 phys += count;
467                 vpfn += count;
468                 nr -= count;
469
470                 ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)), pgd_page + index, count * sizeof(u64));
471
472                 kunmap_atomic(pgd_page);
473         }
474 }
475
476 /**
477  * Map KBASE_REG flags to MMU flags
478  */
479 static u64 kbase_mmu_get_mmu_flags(unsigned long flags)
480 {
481         u64 mmu_flags = 0;
482
483         mmu_flags |= (flags & KBASE_REG_GPU_WR) ? ENTRY_WR_BIT : 0;     /* write perm if requested */
484         mmu_flags |= (flags & KBASE_REG_GPU_RD) ? ENTRY_RD_BIT : 0;     /* read perm if requested */
485         mmu_flags |= (flags & KBASE_REG_GPU_NX) ? ENTRY_NX_BIT : 0;     /* nx if requested */
486
487         if (flags & KBASE_REG_SHARE_BOTH) {
488                 /* inner and outer shareable */
489                 mmu_flags |= SHARE_BOTH_BITS;
490         } else if (flags & KBASE_REG_SHARE_IN) {
491                 /* inner shareable coherency */
492                 mmu_flags |= SHARE_INNER_BITS;
493         }
494
495         return mmu_flags;
496 }
497 /*
498  * Map 'nr' pages pointed to by 'phys' at GPU PFN 'vpfn'
499  */
500 mali_error kbase_mmu_insert_pages(kbase_context *kctx, u64 vpfn, phys_addr_t *phys, size_t nr, unsigned long flags)
501 {
502         phys_addr_t pgd;
503         u64 *pgd_page;
504         u64 mmu_flags = 0;
505         /* In case the insert_pages only partially completes we need to be able to recover */
506         mali_bool recover_required = MALI_FALSE;
507         u64 recover_vpfn = vpfn;
508         phys_addr_t *recover_phys = phys;
509         size_t recover_count = 0;
510
511         KBASE_DEBUG_ASSERT(NULL != kctx);
512         KBASE_DEBUG_ASSERT(0 != vpfn);
513         KBASE_DEBUG_ASSERT((flags & ~((1 << KBASE_REG_FLAGS_NR_BITS) - 1)) == 0);
514         KBASE_DEBUG_ASSERT(vpfn <= (UINT64_MAX / PAGE_SIZE));   /* 64-bit address range is the max */
515
516         lockdep_assert_held(&kctx->reg_lock);
517
518         mmu_flags = kbase_mmu_get_mmu_flags(flags);
519
520         while (nr) {
521                 unsigned int i;
522                 unsigned int index = vpfn & 0x1FF;
523                 unsigned int count = KBASE_MMU_PAGE_ENTRIES - index;
524
525                 if (count > nr)
526                         count = nr;
527
528                 /*
529                  * Repeatedly calling mmu_get_bottom_pte() is clearly
530                  * suboptimal. We don't have to re-parse the whole tree
531                  * each time (just cache the l0-l2 sequence).
532                  * On the other hand, it's only a gain when we map more than
533                  * 256 pages at once (on average). Do we really care?
534                  */
535                 pgd = mmu_get_bottom_pgd(kctx, vpfn);
536                 if (!pgd) {
537                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kbase_mmu_insert_pages: mmu_get_bottom_pgd failure\n");
538                         if (recover_required) {
539                                 /* Invalidate the pages we have partially completed */
540                                 mmu_insert_pages_failure_recovery(kctx, recover_vpfn, recover_phys, recover_count);
541                         }
542                         return MALI_ERROR_FUNCTION_FAILED;
543                 }
544
545                 pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
546                 if (!pgd_page) {
547                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kbase_mmu_insert_pages: kmap failure\n");
548                         if (recover_required) {
549                                 /* Invalidate the pages we have partially completed */
550                                 mmu_insert_pages_failure_recovery(kctx, recover_vpfn, recover_phys, recover_count);
551                         }
552                         return MALI_ERROR_OUT_OF_MEMORY;
553                 }
554
555                 for (i = 0; i < count; i++) {
556                         unsigned int ofs = index + i;
557                         KBASE_DEBUG_ASSERT(0 == (pgd_page[ofs] & 1UL));
558                         page_table_entry_set( kctx->kbdev, &pgd_page[ofs], mmu_phyaddr_to_ate(phys[i], mmu_flags) );
559                 }
560
561                 phys += count;
562                 vpfn += count;
563                 nr -= count;
564
565                 ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)), pgd_page + index, count * sizeof(u64));
566
567                 kunmap(pfn_to_page(PFN_DOWN(pgd)));
568                 /* We have started modifying the page table. If further pages need inserting and fail we need to
569                  * undo what has already taken place */
570                 recover_required = MALI_TRUE;
571                 recover_count += count;
572         }
573         return MALI_ERROR_NONE;
574 }
575
576 KBASE_EXPORT_TEST_API(kbase_mmu_insert_pages)
577
578 /**
579  * This function is responsible for validating the MMU PTs
580  * triggering reguired flushes.
581  *
582  * * IMPORTANT: This uses kbasep_js_runpool_release_ctx() when the context is
583  * currently scheduled into the runpool, and so potentially uses a lot of locks.
584  * These locks must be taken in the correct order with respect to others
585  * already held by the caller. Refer to kbasep_js_runpool_release_ctx() for more
586  * information.
587  */
588 static void kbase_mmu_flush(kbase_context *kctx, u64 vpfn, size_t nr)
589 {
590         kbase_device *kbdev;
591         mali_bool ctx_is_in_runpool;
592
593         KBASE_DEBUG_ASSERT(NULL != kctx);
594
595         kbdev = kctx->kbdev;
596
597         /* We must flush if we're currently running jobs. At the very least, we need to retain the
598          * context to ensure it doesn't schedule out whilst we're trying to flush it */
599         ctx_is_in_runpool = kbasep_js_runpool_retain_ctx(kbdev, kctx);
600
601         if (ctx_is_in_runpool) {
602                 KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID);
603
604                 /* Second level check is to try to only do this when jobs are running. The refcount is
605                  * a heuristic for this. */
606                 if (kbdev->js_data.runpool_irq.per_as_data[kctx->as_nr].as_busy_refcount >= 2) {
607                         /* Lock the VA region we're about to update */
608                         u64 lock_addr = lock_region(kbdev, vpfn, nr);
609                         unsigned int max_loops = KBASE_AS_FLUSH_MAX_LOOPS;
610
611                         /* AS transaction begin */
612                         mutex_lock(&kbdev->as[kctx->as_nr].transaction_mutex);
613                         kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_LOCKADDR_LO), lock_addr & 0xFFFFFFFFUL, kctx);
614                         kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_LOCKADDR_HI), lock_addr >> 32, kctx);
615                         kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_LOCK, kctx);
616
617                         /* flush L2 and unlock the VA */
618                         if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_6367))
619                                 kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_FLUSH, kctx);
620                         else
621                                 kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_FLUSH_MEM, kctx);
622
623                         /* wait for the flush to complete */
624                         while (--max_loops && kbase_reg_read(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_STATUS), kctx) & ASn_STATUS_FLUSH_ACTIVE)
625                                 ;
626
627                         if (!max_loops) {
628                                 /* Flush failed to complete, assume the GPU has hung and perform a reset to recover */
629                                 KBASE_DEBUG_PRINT_ERROR(KBASE_MMU, "Flush for GPU page table update did not complete. Issueing GPU soft-reset to recover\n");
630                                 if (kbase_prepare_to_reset_gpu(kbdev))
631                                         kbase_reset_gpu(kbdev);
632                         }
633
634                         if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_9630)) {
635                                 /* Issue an UNLOCK command to ensure that valid page tables are re-read by the GPU after an update.
636                                    Note that, the FLUSH command should perform all the actions necessary, however the bus logs show
637                                    that if multiple page faults occur within an 8 page region the MMU does not always re-read the
638                                    updated page table entries for later faults or is only partially read, it subsequently raises the
639                                    page fault IRQ for the same addresses, the unlock ensures that the MMU cache is flushed, so updates
640                                    can be re-read.  As the region is now unlocked we need to issue 2 UNLOCK commands in order to flush the
641                                    MMU/uTLB, see PRLAM-8812.
642                                  */
643                                 kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_UNLOCK, kctx);
644                                 kbase_reg_write(kctx->kbdev, MMU_AS_REG(kctx->as_nr, ASn_COMMAND), ASn_COMMAND_UNLOCK, kctx);
645                         }
646
647                         mutex_unlock(&kbdev->as[kctx->as_nr].transaction_mutex);
648                         /* AS transaction end */
649                 }
650                 kbasep_js_runpool_release_ctx(kbdev, kctx);
651         }
652 }
653
654 /*
655  * We actually only discard the ATE, and not the page table
656  * pages. There is a potential DoS here, as we'll leak memory by
657  * having PTEs that are potentially unused.  Will require physical
658  * page accounting, so MMU pages are part of the process allocation.
659  *
660  * IMPORTANT: This uses kbasep_js_runpool_release_ctx() when the context is
661  * currently scheduled into the runpool, and so potentially uses a lot of locks.
662  * These locks must be taken in the correct order with respect to others
663  * already held by the caller. Refer to kbasep_js_runpool_release_ctx() for more
664  * information.
665  */
666 mali_error kbase_mmu_teardown_pages(kbase_context *kctx, u64 vpfn, size_t nr)
667 {
668         phys_addr_t pgd;
669         u64 *pgd_page;
670         kbase_device *kbdev;
671         size_t requested_nr = nr;
672
673         beenthere("kctx %p vpfn %lx nr %d", (void *)kctx, (unsigned long)vpfn, nr);
674
675         KBASE_DEBUG_ASSERT(NULL != kctx);
676
677         lockdep_assert_held(&kctx->reg_lock);
678
679         if (0 == nr) {
680                 /* early out if nothing to do */
681                 return MALI_ERROR_NONE;
682         }
683
684         kbdev = kctx->kbdev;
685
686         while (nr) {
687                 unsigned int i;
688                 unsigned int index = vpfn & 0x1FF;
689                 unsigned int count = KBASE_MMU_PAGE_ENTRIES - index;
690                 if (count > nr)
691                         count = nr;
692
693                 pgd = mmu_get_bottom_pgd(kctx, vpfn);
694                 if (!pgd) {
695                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kbase_mmu_teardown_pages: mmu_get_bottom_pgd failure\n");
696                         return MALI_ERROR_FUNCTION_FAILED;
697                 }
698
699                 pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
700                 if (!pgd_page) {
701                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kbase_mmu_teardown_pages: kmap failure\n");
702                         return MALI_ERROR_OUT_OF_MEMORY;
703                 }
704
705                 for (i = 0; i < count; i++) {
706                         page_table_entry_set( kctx->kbdev, &pgd_page[index + i], ENTRY_IS_INVAL );
707                 }
708
709                 vpfn += count;
710                 nr -= count;
711
712                 ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)), pgd_page + index, count * sizeof(u64));
713
714                 kunmap(pfn_to_page(PFN_DOWN(pgd)));
715         }
716
717         kbase_mmu_flush(kctx,vpfn,requested_nr);
718         return MALI_ERROR_NONE;
719 }
720
721 KBASE_EXPORT_TEST_API(kbase_mmu_teardown_pages)
722
723 /**
724  * Update the entries for specified number of pages pointed to by 'phys' at GPU PFN 'vpfn'.
725  * This call is being triggered as a response to the changes of the mem attributes
726  *
727  * @pre : The caller is responsible for validating the memory attributes
728  *
729  * IMPORTANT: This uses kbasep_js_runpool_release_ctx() when the context is
730  * currently scheduled into the runpool, and so potentially uses a lot of locks.
731  * These locks must be taken in the correct order with respect to others
732  * already held by the caller. Refer to kbasep_js_runpool_release_ctx() for more
733  * information.
734  */
735 mali_error kbase_mmu_update_pages(kbase_context* kctx, u64 vpfn, phys_addr_t* phys, size_t nr, unsigned long flags)
736 {
737         phys_addr_t pgd;
738         u64* pgd_page;
739         u64 mmu_flags = 0;
740         size_t requested_nr = nr;
741
742         KBASE_DEBUG_ASSERT(NULL != kctx);
743         KBASE_DEBUG_ASSERT(0 != vpfn);
744         KBASE_DEBUG_ASSERT(vpfn <= (UINT64_MAX / PAGE_SIZE));
745
746         lockdep_assert_held(&kctx->reg_lock);
747
748         mmu_flags = kbase_mmu_get_mmu_flags(flags);
749
750         dev_warn( kctx->kbdev->osdev.dev, "kbase_mmu_update_pages(): updating page share flags "\
751                         "on GPU PFN 0x%llx from phys %p, %zu pages", 
752                         vpfn, phys, nr);
753
754
755         while(nr)
756         {
757                 unsigned int i;
758                 unsigned int index = vpfn & 0x1FF;
759                 size_t count = KBASE_MMU_PAGE_ENTRIES - index;
760                 if (count > nr)
761                         count = nr;
762
763                 pgd = mmu_get_bottom_pgd(kctx, vpfn);
764                 if (!pgd) {
765                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "mmu_get_bottom_pgd failure\n");
766                         return MALI_ERROR_FUNCTION_FAILED;
767                 }
768
769                 pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
770                 if (!pgd_page) {
771                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kmap failure\n");
772                         return MALI_ERROR_OUT_OF_MEMORY;
773                 }
774
775                 for (i = 0; i < count; i++) {
776                         page_table_entry_set( kctx->kbdev, &pgd_page[index + i],  mmu_phyaddr_to_ate(phys[i], mmu_flags)  );
777                 }
778
779                 phys += count;
780                 vpfn += count;
781                 nr -= count;
782
783                 ksync_kern_vrange_gpu(pgd + (index * sizeof(u64)), pgd_page + index, count * sizeof(u64));
784
785                 kunmap(pfn_to_page(PFN_DOWN(pgd)));
786         }
787
788         kbase_mmu_flush(kctx,vpfn,requested_nr);
789
790         return MALI_ERROR_NONE;
791 }
792
793 static int mmu_pte_is_valid(u64 pte)
794 {
795         return ((pte & 3) == ENTRY_IS_ATE);
796 }
797
798 /* This is a debug feature only */
799 static void mmu_check_unused(kbase_context *kctx, phys_addr_t pgd)
800 {
801         u64 *page;
802         int i;
803         CSTD_UNUSED(kctx);
804
805         page = kmap_atomic(pfn_to_page(PFN_DOWN(pgd)));
806         /* kmap_atomic should NEVER fail. */
807         KBASE_DEBUG_ASSERT(NULL != page);
808
809         for (i = 0; i < KBASE_MMU_PAGE_ENTRIES; i++) {
810                 if (mmu_pte_is_valid(page[i]))
811                         beenthere("live pte %016lx", (unsigned long)page[i]);
812         }
813         kunmap_atomic(page);
814 }
815
816 static void mmu_teardown_level(kbase_context *kctx, phys_addr_t pgd, int level, int zap, u64 *pgd_page_buffer)
817 {
818         phys_addr_t target_pgd;
819         u64 *pgd_page;
820         int i;
821
822         KBASE_DEBUG_ASSERT(NULL != kctx);
823         lockdep_assert_held(&kctx->reg_lock);
824
825         pgd_page = kmap_atomic(pfn_to_page(PFN_DOWN(pgd)));
826         /* kmap_atomic should NEVER fail. */
827         KBASE_DEBUG_ASSERT(NULL != pgd_page);
828         /* Copy the page to our preallocated buffer so that we can minimize kmap_atomic usage */
829         memcpy(pgd_page_buffer, pgd_page, PAGE_SIZE);
830         kunmap_atomic(pgd_page);
831         pgd_page = pgd_page_buffer;
832
833         for (i = 0; i < KBASE_MMU_PAGE_ENTRIES; i++) {
834                 target_pgd = mmu_pte_to_phy_addr(pgd_page[i]);
835
836                 if (target_pgd) {
837                         if (level < 2) {
838                                 mmu_teardown_level(kctx, target_pgd, level + 1, zap, pgd_page_buffer + (PAGE_SIZE / sizeof(u64)));
839                         } else {
840                                 /*
841                                  * So target_pte is a level-3 page.
842                                  * As a leaf, it is safe to free it.
843                                  * Unless we have live pages attached to it!
844                                  */
845                                 mmu_check_unused(kctx, target_pgd);
846                         }
847
848                         beenthere("pte %lx level %d", (unsigned long)target_pgd, level + 1);
849                         if (zap) {
850                                 kbase_mem_allocator_free(kctx->pgd_allocator, 1, &target_pgd, MALI_TRUE);
851                                 kbase_process_page_usage_dec(kctx, 1 );
852                                 kbase_mem_usage_release_pages(&kctx->usage, 1);
853                                 kbase_mem_usage_release_pages(&kctx->kbdev->memdev.usage, 1);
854                         }
855                 }
856         }
857 }
858
859 mali_error kbase_mmu_init(kbase_context *kctx)
860 {
861         KBASE_DEBUG_ASSERT(NULL != kctx);
862         KBASE_DEBUG_ASSERT(NULL == kctx->mmu_teardown_pages);
863
864         /* Preallocate MMU depth of four pages for mmu_teardown_level to use */
865         kctx->mmu_teardown_pages = kmalloc(PAGE_SIZE * 4, GFP_KERNEL);
866
867         if (NULL == kctx->mmu_teardown_pages)
868                 return MALI_ERROR_OUT_OF_MEMORY;
869
870         return MALI_ERROR_NONE;
871 }
872
873 void kbase_mmu_term(kbase_context *kctx)
874 {
875         KBASE_DEBUG_ASSERT(NULL != kctx);
876         KBASE_DEBUG_ASSERT(NULL != kctx->mmu_teardown_pages);
877
878         kfree(kctx->mmu_teardown_pages);
879         kctx->mmu_teardown_pages = NULL;
880 }
881
882 void kbase_mmu_free_pgd(kbase_context *kctx)
883 {
884         KBASE_DEBUG_ASSERT(NULL != kctx);
885         KBASE_DEBUG_ASSERT(NULL != kctx->mmu_teardown_pages);
886
887         lockdep_assert_held(&kctx->reg_lock);
888
889         mmu_teardown_level(kctx, kctx->pgd, MIDGARD_MMU_TOPLEVEL, 1, kctx->mmu_teardown_pages);
890
891         beenthere("pgd %lx", (unsigned long)kctx->pgd);
892         kbase_mem_allocator_free(kctx->pgd_allocator, 1, &kctx->pgd, MALI_TRUE);
893         kbase_process_page_usage_dec(kctx, 1 );
894         kbase_mem_usage_release_pages(&kctx->usage, 1);
895         kbase_mem_usage_release_pages(&kctx->kbdev->memdev.usage, 1);
896 }
897
898 KBASE_EXPORT_TEST_API(kbase_mmu_free_pgd)
899
900 static size_t kbasep_mmu_dump_level(kbase_context *kctx, phys_addr_t pgd, int level, char ** const buffer, size_t *size_left)
901 {
902         phys_addr_t target_pgd;
903         u64 *pgd_page;
904         int i;
905         size_t size = KBASE_MMU_PAGE_ENTRIES * sizeof(u64) + sizeof(u64);
906         size_t dump_size;
907
908         KBASE_DEBUG_ASSERT(NULL != kctx);
909         lockdep_assert_held(&kctx->reg_lock);
910
911         pgd_page = kmap(pfn_to_page(PFN_DOWN(pgd)));
912         if (!pgd_page) {
913                 KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "kbasep_mmu_dump_level: kmap failure\n");
914                 return 0;
915         }
916
917         if (*size_left >= size) {
918                 /* A modified physical address that contains the page table level */
919                 u64 m_pgd = pgd | level;
920
921                 /* Put the modified physical address in the output buffer */
922                 memcpy(*buffer, &m_pgd, sizeof(m_pgd));
923                 *buffer += sizeof(m_pgd);
924
925                 /* Followed by the page table itself */
926                 memcpy(*buffer, pgd_page, sizeof(u64) * KBASE_MMU_PAGE_ENTRIES);
927                 *buffer += sizeof(u64) * KBASE_MMU_PAGE_ENTRIES;
928
929                 *size_left -= size;
930         }
931
932         for (i = 0; i < KBASE_MMU_PAGE_ENTRIES; i++) {
933                 if ((pgd_page[i] & ENTRY_IS_PTE) == ENTRY_IS_PTE) {
934                         target_pgd = mmu_pte_to_phy_addr(pgd_page[i]);
935
936                         dump_size = kbasep_mmu_dump_level(kctx, target_pgd, level + 1, buffer, size_left);
937                         if (!dump_size) {
938                                 kunmap(pfn_to_page(PFN_DOWN(pgd)));
939                                 return 0;
940                         }
941                         size += dump_size;
942                 }
943         }
944
945         kunmap(pfn_to_page(PFN_DOWN(pgd)));
946
947         return size;
948 }
949
950 void *kbase_mmu_dump(kbase_context *kctx, int nr_pages)
951 {
952         void *kaddr;
953         size_t size_left;
954
955         KBASE_DEBUG_ASSERT(kctx);
956
957         lockdep_assert_held(&kctx->reg_lock);
958
959         if (0 == nr_pages) {
960                 /* can't find in a 0 sized buffer, early out */
961                 return NULL;
962         }
963
964         size_left = nr_pages * PAGE_SIZE;
965
966         KBASE_DEBUG_ASSERT(0 != size_left);
967         kaddr = vmalloc_user(size_left);
968
969         if (kaddr) {
970                 u64 end_marker = 0xFFULL;
971                 char *buffer = (char *)kaddr;
972
973                 size_t size = kbasep_mmu_dump_level(kctx, kctx->pgd, MIDGARD_MMU_TOPLEVEL, &buffer, &size_left);
974                 if (!size) {
975                         vfree(kaddr);
976                         return NULL;
977                 }
978
979                 /* Add on the size for the end marker */
980                 size += sizeof(u64);
981
982                 if (size > nr_pages * PAGE_SIZE || size_left < sizeof(u64)) {
983                         /* The buffer isn't big enough - free the memory and return failure */
984                         vfree(kaddr);
985                         return NULL;
986                 }
987
988                 /* Add the end marker */
989                 memcpy(buffer, &end_marker, sizeof(u64));
990         }
991
992         return kaddr;
993 }
994 KBASE_EXPORT_TEST_API(kbase_mmu_dump)
995
996 static u64 lock_region(kbase_device *kbdev, u64 pfn, size_t num_pages)
997 {
998         u64 region;
999
1000         /* can't lock a zero sized range */
1001         KBASE_DEBUG_ASSERT(num_pages);
1002
1003         region = pfn << PAGE_SHIFT;
1004         /*
1005          * fls returns (given the ASSERT above):
1006          * 32-bit: 1 .. 32
1007          * 64-bit: 1 .. 32
1008          *
1009          * 32-bit: 10 + fls(num_pages)
1010          * results in the range (11 .. 42)
1011          * 64-bit: 10 + fls(num_pages)
1012          * results in the range (11 .. 42)
1013          */
1014
1015         /* gracefully handle num_pages being zero */
1016         if (0 == num_pages) {
1017                 region |= 11;
1018         } else {
1019                 u8 region_width;
1020                 region_width = 10 + fls(num_pages);
1021                 if (num_pages != (1ul << (region_width - 11))) {
1022                         /* not pow2, so must go up to the next pow2 */
1023                         region_width += 1;
1024                 }
1025                 KBASE_DEBUG_ASSERT(region_width <= KBASE_LOCK_REGION_MAX_SIZE);
1026                 KBASE_DEBUG_ASSERT(region_width >= KBASE_LOCK_REGION_MIN_SIZE);
1027                 region |= region_width;
1028         }
1029
1030         return region;
1031 }
1032
1033 static void bus_fault_worker(struct work_struct *data)
1034 {
1035         kbase_as *faulting_as;
1036         int as_no;
1037         kbase_context *kctx;
1038         kbase_device *kbdev;
1039         u32 reg;
1040         mali_bool reset_status = MALI_FALSE;
1041
1042         faulting_as = container_of(data, kbase_as, work_busfault);
1043         as_no = faulting_as->number;
1044
1045         kbdev = container_of(faulting_as, kbase_device, as[as_no]);
1046
1047         /* Grab the context that was already refcounted in kbase_mmu_interrupt().
1048          * Therefore, it cannot be scheduled out of this AS until we explicitly release it
1049          *
1050          * NOTE: NULL can be returned here if we're gracefully handling a spurious interrupt */
1051         kctx = kbasep_js_runpool_lookup_ctx_noretain(kbdev, as_no);
1052
1053         if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8245)) {
1054                 /* Due to H/W issue 8245 we need to reset the GPU after using UNMAPPED mode.
1055                  * We start the reset before switching to UNMAPPED to ensure that unrelated jobs
1056                  * are evicted from the GPU before the switch.
1057                  */
1058                 KBASE_DEBUG_PRINT_ERROR(KBASE_MMU, "GPU bus error occurred. For this GPU version we now soft-reset as part of bus error recovery\n");
1059                 reset_status = kbase_prepare_to_reset_gpu(kbdev);
1060         }
1061
1062         /* NOTE: If GPU already powered off for suspend, we don't need to switch to unmapped */
1063         if (!kbase_pm_context_active_handle_suspend(kbdev, KBASE_PM_SUSPEND_HANDLER_DONT_REACTIVATE)) {
1064                 /* switch to UNMAPPED mode, will abort all jobs and stop any hw counter dumping */
1065                 /* AS transaction begin */
1066                 mutex_lock(&kbdev->as[as_no].transaction_mutex);
1067
1068                 reg = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), kctx);
1069                 reg &= ~3;
1070                 kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), reg, kctx);
1071                 kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_UPDATE, kctx);
1072                 
1073                 mutex_unlock(&kbdev->as[as_no].transaction_mutex);
1074                 /* AS transaction end */
1075
1076                 mmu_mask_reenable(kbdev, kctx, faulting_as);
1077                 kbase_pm_context_idle(kbdev);
1078         }
1079
1080         if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8245) && reset_status)
1081                 kbase_reset_gpu(kbdev);
1082
1083         /* By this point, the fault was handled in some way, so release the ctx refcount */
1084         if (kctx != NULL)
1085                 kbasep_js_runpool_release_ctx(kbdev, kctx);
1086 }
1087
1088 void kbase_mmu_interrupt(kbase_device *kbdev, u32 irq_stat)
1089 {
1090         unsigned long flags;
1091         const int num_as = 16;
1092         const int busfault_shift = 16;
1093         const int pf_shift = 0;
1094         const unsigned long mask = (1UL << num_as) - 1;
1095         kbasep_js_device_data *js_devdata;
1096         u32 new_mask;
1097         u32 tmp;
1098         u32 bf_bits = (irq_stat >> busfault_shift) & mask;      /* bus faults */
1099         /* Ignore ASes with both pf and bf */
1100         u32 pf_bits = ((irq_stat >> pf_shift) & mask) & ~bf_bits;       /* page faults */
1101
1102         KBASE_DEBUG_ASSERT(NULL != kbdev);
1103
1104         js_devdata = &kbdev->js_data;
1105
1106         /* remember current mask */
1107         spin_lock_irqsave(&kbdev->mmu_mask_change, flags);
1108         new_mask = kbase_reg_read(kbdev, MMU_REG(MMU_IRQ_MASK), NULL);
1109         /* mask interrupts for now */
1110         kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_MASK), 0, NULL);
1111         spin_unlock_irqrestore(&kbdev->mmu_mask_change, flags);
1112
1113         while (bf_bits) {
1114                 /* the while logic ensures we have a bit set, no need to check for not-found here */
1115                 int as_no = ffs(bf_bits) - 1;
1116                 kbase_as *as = &kbdev->as[as_no];
1117                 kbase_context *kctx;
1118
1119                 /* Refcount the kctx ASAP - it shouldn't disappear anyway, since Bus/Page faults
1120                  * _should_ only occur whilst jobs are running, and a job causing the Bus/Page fault
1121                  * shouldn't complete until the MMU is updated */
1122                 kctx = kbasep_js_runpool_lookup_ctx(kbdev, as_no);
1123
1124                 /* mark as handled */
1125                 bf_bits &= ~(1UL << as_no);
1126
1127                 /* find faulting address & status */
1128                 as->fault_addr = ((u64)kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTADDRESS_HI), kctx) << 32) |
1129                                        kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTADDRESS_LO), kctx);
1130                 as->fault_status = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTSTATUS), kctx);
1131
1132                 /* Clear the internal JM mask first before clearing the internal MMU mask */
1133                 kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_CLEAR), 1UL << MMU_REGS_BUS_ERROR_FLAG(as_no), kctx);
1134
1135                 if (kctx) {
1136                         /* hw counters dumping in progress, signal the other thread that it failed */
1137                         if ((kbdev->hwcnt.kctx == kctx) && (kbdev->hwcnt.state == KBASE_INSTR_STATE_DUMPING))
1138                                 kbdev->hwcnt.state = KBASE_INSTR_STATE_FAULT;
1139
1140                         /* Stop the kctx from submitting more jobs and cause it to be scheduled
1141                          * out/rescheduled when all references to it are released */
1142                         spin_lock_irqsave(&js_devdata->runpool_irq.lock, flags);
1143                         kbasep_js_clear_submit_allowed(js_devdata, kctx);
1144                         spin_unlock_irqrestore(&js_devdata->runpool_irq.lock, flags);
1145
1146                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Bus error in AS%d at 0x%016llx\n", as_no, as->fault_addr);
1147                 } else {
1148                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Bus error in AS%d at 0x%016llx with no context present! " "Suprious IRQ or SW Design Error?\n", as_no, as->fault_addr);
1149                 }
1150
1151                 /* remove the queued BFs from the mask */
1152                 new_mask &= ~(1UL << (as_no + num_as));
1153
1154                 /* We need to switch to UNMAPPED mode - but we do this in a worker so that we can sleep */
1155                 KBASE_DEBUG_ASSERT(0 == object_is_on_stack(&as->work_busfault));
1156                 INIT_WORK(&as->work_busfault, bus_fault_worker);
1157                 queue_work(as->pf_wq, &as->work_busfault);
1158         }
1159
1160         /*
1161          * pf_bits is non-zero if we have at least one AS with a page fault and no bus fault.
1162          * Handle the PFs in our worker thread.
1163          */
1164         while (pf_bits) {
1165                 /* the while logic ensures we have a bit set, no need to check for not-found here */
1166                 int as_no = ffs(pf_bits) - 1;
1167                 kbase_as *as = &kbdev->as[as_no];
1168                 kbase_context *kctx;
1169
1170                 /* Refcount the kctx ASAP - it shouldn't disappear anyway, since Bus/Page faults
1171                  * _should_ only occur whilst jobs are running, and a job causing the Bus/Page fault
1172                  * shouldn't complete until the MMU is updated */
1173                 kctx = kbasep_js_runpool_lookup_ctx(kbdev, as_no);
1174
1175                 /* mark as handled */
1176                 pf_bits &= ~(1UL << as_no);
1177
1178                 /* find faulting address & status */
1179                 as->fault_addr = ((u64)kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTADDRESS_HI), kctx) << 32) |
1180                                        kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTADDRESS_LO), kctx);
1181                 as->fault_status = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_FAULTSTATUS), kctx);
1182
1183                 /* Clear the internal JM mask first before clearing the internal MMU mask */
1184                 kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_CLEAR), 1UL << MMU_REGS_PAGE_FAULT_FLAG(as_no), kctx);
1185
1186                 if (kctx == NULL)
1187                         KBASE_DEBUG_PRINT_WARN(KBASE_MMU, "Page fault in AS%d at 0x%016llx with no context present! " "Suprious IRQ or SW Design Error?\n", as_no, as->fault_addr);
1188
1189                 /* remove the queued PFs from the mask */
1190                 new_mask &= ~((1UL << as_no) | (1UL << (as_no + num_as)));
1191
1192                 /* queue work pending for this AS */
1193                 KBASE_DEBUG_ASSERT(0 == object_is_on_stack(&as->work_pagefault));
1194                 INIT_WORK(&as->work_pagefault, page_fault_worker);
1195                 queue_work(as->pf_wq, &as->work_pagefault);
1196         }
1197
1198         /* reenable interrupts */
1199         spin_lock_irqsave(&kbdev->mmu_mask_change, flags);
1200         tmp = kbase_reg_read(kbdev, MMU_REG(MMU_IRQ_MASK), NULL);
1201         new_mask |= tmp;
1202         kbase_reg_write(kbdev, MMU_REG(MMU_IRQ_MASK), new_mask, NULL);
1203         spin_unlock_irqrestore(&kbdev->mmu_mask_change, flags);
1204 }
1205
1206 KBASE_EXPORT_TEST_API(kbase_mmu_interrupt)
1207
1208 const char *kbase_exception_name(u32 exception_code)
1209 {
1210         const char *e;
1211
1212         switch (exception_code) {
1213                 /* Non-Fault Status code */
1214         case 0x00:
1215                 e = "NOT_STARTED/IDLE/OK";
1216                 break;
1217         case 0x01:
1218                 e = "DONE";
1219                 break;
1220         case 0x02:
1221                 e = "INTERRUPTED";
1222                 break;
1223         case 0x03:
1224                 e = "STOPPED";
1225                 break;
1226         case 0x04:
1227                 e = "TERMINATED";
1228                 break;
1229         case 0x08:
1230                 e = "ACTIVE";
1231                 break;
1232                 /* Job exceptions */
1233         case 0x40:
1234                 e = "JOB_CONFIG_FAULT";
1235                 break;
1236         case 0x41:
1237                 e = "JOB_POWER_FAULT";
1238                 break;
1239         case 0x42:
1240                 e = "JOB_READ_FAULT";
1241                 break;
1242         case 0x43:
1243                 e = "JOB_WRITE_FAULT";
1244                 break;
1245         case 0x44:
1246                 e = "JOB_AFFINITY_FAULT";
1247                 break;
1248         case 0x48:
1249                 e = "JOB_BUS_FAULT";
1250                 break;
1251         case 0x50:
1252                 e = "INSTR_INVALID_PC";
1253                 break;
1254         case 0x51:
1255                 e = "INSTR_INVALID_ENC";
1256                 break;
1257         case 0x52:
1258                 e = "INSTR_TYPE_MISMATCH";
1259                 break;
1260         case 0x53:
1261                 e = "INSTR_OPERAND_FAULT";
1262                 break;
1263         case 0x54:
1264                 e = "INSTR_TLS_FAULT";
1265                 break;
1266         case 0x55:
1267                 e = "INSTR_BARRIER_FAULT";
1268                 break;
1269         case 0x56:
1270                 e = "INSTR_ALIGN_FAULT";
1271                 break;
1272         case 0x58:
1273                 e = "DATA_INVALID_FAULT";
1274                 break;
1275         case 0x59:
1276                 e = "TILE_RANGE_FAULT";
1277                 break;
1278         case 0x5A:
1279                 e = "ADDR_RANGE_FAULT";
1280                 break;
1281         case 0x60:
1282                 e = "OUT_OF_MEMORY";
1283                 break;
1284                 /* GPU exceptions */
1285         case 0x80:
1286                 e = "DELAYED_BUS_FAULT";
1287                 break;
1288         case 0x81:
1289                 e = "SHAREABILITY_FAULT";
1290                 break;
1291                 /* MMU exceptions */
1292         case 0xC0:
1293         case 0xC1:
1294         case 0xC2:
1295         case 0xC3:
1296         case 0xC4:
1297         case 0xC5:
1298         case 0xC6:
1299         case 0xC7:
1300                 e = "TRANSLATION_FAULT";
1301                 break;
1302         case 0xC8:
1303                 e = "PERMISSION_FAULT";
1304                 break;
1305         case 0xD0:
1306         case 0xD1:
1307         case 0xD2:
1308         case 0xD3:
1309         case 0xD4:
1310         case 0xD5:
1311         case 0xD6:
1312         case 0xD7:
1313                 e = "TRANSTAB_BUS_FAULT";
1314                 break;
1315         case 0xD8:
1316                 e = "ACCESS_FLAG";
1317                 break;
1318         default:
1319                 e = "UNKNOWN";
1320                 break;
1321         };
1322
1323         return e;
1324 }
1325
1326 /**
1327  * The caller must ensure it's retained the ctx to prevent it from being scheduled out whilst it's being worked on.
1328  */
1329 static void kbase_mmu_report_fault_and_kill(kbase_context *kctx, kbase_as *as)
1330 {
1331         unsigned long flags;
1332         u32 reg;
1333         int exception_type;
1334         int access_type;
1335         int source_id;
1336         int as_no;
1337         kbase_device *kbdev;
1338         kbasep_js_device_data *js_devdata;
1339         mali_bool reset_status = MALI_FALSE;
1340         static const char * const access_type_names[] = { "RESERVED", "EXECUTE", "READ", "WRITE" };
1341
1342         KBASE_DEBUG_ASSERT(as);
1343         KBASE_DEBUG_ASSERT(kctx);
1344
1345         as_no = as->number;
1346         kbdev = kctx->kbdev;
1347         js_devdata = &kbdev->js_data;
1348
1349         /* ASSERT that the context won't leave the runpool */
1350         KBASE_DEBUG_ASSERT(kbasep_js_debug_check_ctx_refcount(kbdev, kctx) > 0);
1351
1352         /* decode the fault status */
1353         exception_type = as->fault_status & 0xFF;
1354         access_type = (as->fault_status >> 8) & 0x3;
1355         source_id = (as->fault_status >> 16);
1356
1357         /* terminal fault, print info about the fault */
1358         KBASE_DEBUG_PRINT_ERROR(KBASE_MMU, "Unhandled Page fault in AS%d at VA 0x%016llX\n"
1359                                            "raw fault status 0x%X\n"
1360                                            "decoded fault status: %s\n"
1361                                            "exception type 0x%X: %s\n"
1362                                            "access type 0x%X: %s\n"
1363                                            "source id 0x%X\n",
1364                                            as_no, as->fault_addr,
1365                                            as->fault_status,
1366                                            (as->fault_status & (1 << 10) ? "DECODER FAULT" : "SLAVE FAULT"),
1367                                            exception_type, kbase_exception_name(exception_type),
1368                                            access_type, access_type_names[access_type],
1369                                            source_id);
1370
1371         /* hardware counters dump fault handling */
1372         if ((kbdev->hwcnt.kctx) && (kbdev->hwcnt.kctx->as_nr == as_no) && (kbdev->hwcnt.state == KBASE_INSTR_STATE_DUMPING)) {
1373                 unsigned int num_core_groups = kbdev->gpu_props.num_core_groups;
1374                 if ((as->fault_addr >= kbdev->hwcnt.addr) && (as->fault_addr < (kbdev->hwcnt.addr + (num_core_groups * 2048))))
1375                         kbdev->hwcnt.state = KBASE_INSTR_STATE_FAULT;
1376         }
1377
1378         /* Stop the kctx from submitting more jobs and cause it to be scheduled
1379          * out/rescheduled - this will occur on releasing the context's refcount */
1380         spin_lock_irqsave(&js_devdata->runpool_irq.lock, flags);
1381         kbasep_js_clear_submit_allowed(js_devdata, kctx);
1382         spin_unlock_irqrestore(&js_devdata->runpool_irq.lock, flags);
1383
1384         /* Kill any running jobs from the context. Submit is disallowed, so no more jobs from this
1385          * context can appear in the job slots from this point on */
1386         kbase_job_kill_jobs_from_context(kctx);
1387         /* AS transaction begin */
1388         mutex_lock(&as->transaction_mutex);
1389
1390         if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8245)) {
1391                 /* Due to H/W issue 8245 we need to reset the GPU after using UNMAPPED mode.
1392                  * We start the reset before switching to UNMAPPED to ensure that unrelated jobs
1393                  * are evicted from the GPU before the switch.
1394                  */
1395                 KBASE_DEBUG_PRINT_ERROR(KBASE_MMU, "Unhandled page fault. For this GPU version we now soft-reset the GPU as part of page fault recovery.");
1396                 reset_status = kbase_prepare_to_reset_gpu(kbdev);
1397         }
1398
1399         /* switch to UNMAPPED mode, will abort all jobs and stop any hw counter dumping */
1400         reg = kbase_reg_read(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), kctx);
1401         reg &= ~3;
1402         kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_TRANSTAB_LO), reg, kctx);
1403         kbase_reg_write(kbdev, MMU_AS_REG(as_no, ASn_COMMAND), ASn_COMMAND_UPDATE, kctx);
1404
1405         mutex_unlock(&as->transaction_mutex);
1406         /* AS transaction end */
1407         mmu_mask_reenable(kbdev, kctx, as);
1408
1409         if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8245) && reset_status)
1410                 kbase_reset_gpu(kbdev);
1411 }
1412
1413 void kbasep_as_do_poke(struct work_struct *work)
1414 {
1415         kbase_as *as;
1416         kbase_device *kbdev;
1417         unsigned long flags;
1418
1419         KBASE_DEBUG_ASSERT(work);
1420         as = container_of(work, kbase_as, poke_work);
1421         kbdev = container_of(as, kbase_device, as[as->number]);
1422         KBASE_DEBUG_ASSERT(as->poke_state & KBASE_AS_POKE_STATE_IN_FLIGHT);
1423
1424         /* GPU power will already be active by virtue of the caller holding a JS
1425          * reference on the address space, and will not release it until this worker
1426          * has finished */
1427
1428         /* AS transaction begin */
1429         mutex_lock(&as->transaction_mutex);
1430         /* Force a uTLB invalidate */
1431         kbase_reg_write(kbdev, MMU_AS_REG(as->number, ASn_COMMAND), ASn_COMMAND_UNLOCK, NULL);
1432         mutex_unlock(&as->transaction_mutex);
1433         /* AS transaction end */
1434
1435         spin_lock_irqsave(&kbdev->js_data.runpool_irq.lock, flags);
1436         if (as->poke_refcount &&
1437                 !(as->poke_state & KBASE_AS_POKE_STATE_KILLING_POKE)) {
1438                 /* Only queue up the timer if we need it, and we're not trying to kill it */
1439                 hrtimer_start(&as->poke_timer, HR_TIMER_DELAY_MSEC(5), HRTIMER_MODE_REL);
1440         }
1441         spin_unlock_irqrestore(&kbdev->js_data.runpool_irq.lock, flags);
1442
1443 }
1444
1445 enum hrtimer_restart kbasep_as_poke_timer_callback(struct hrtimer *timer)
1446 {
1447         kbase_as *as;
1448         int queue_work_ret;
1449
1450         KBASE_DEBUG_ASSERT(NULL != timer);
1451         as = container_of(timer, kbase_as, poke_timer);
1452         KBASE_DEBUG_ASSERT(as->poke_state & KBASE_AS_POKE_STATE_IN_FLIGHT);
1453
1454         queue_work_ret = queue_work(as->poke_wq, &as->poke_work);
1455         KBASE_DEBUG_ASSERT(queue_work_ret);
1456         return HRTIMER_NORESTART;
1457 }
1458
1459 /**
1460  * Retain the poking timer on an atom's context (if the atom hasn't already
1461  * done so), and start the timer (if it's not already started).
1462  *
1463  * This must only be called on a context that's scheduled in, and an atom
1464  * that's running on the GPU.
1465  *
1466  * The caller must hold kbasep_js_device_data::runpool_irq::lock
1467  *
1468  * This can be called safely from atomic context
1469  */
1470 void kbase_as_poking_timer_retain_atom(kbase_device *kbdev, kbase_context *kctx, kbase_jd_atom *katom)
1471 {
1472         kbase_as *as;
1473         KBASE_DEBUG_ASSERT(kbdev);
1474         KBASE_DEBUG_ASSERT(kctx);
1475         KBASE_DEBUG_ASSERT(katom);
1476         KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID);
1477         lockdep_assert_held(&kbdev->js_data.runpool_irq.lock);
1478
1479         if (katom->poking)
1480                 return;
1481
1482         katom->poking = 1;
1483
1484         /* It's safe to work on the as/as_nr without an explicit reference,
1485          * because the caller holds the runpool_irq lock, and the atom itself
1486          * was also running and had already taken a reference  */
1487         as = &kbdev->as[kctx->as_nr];
1488
1489         if (++(as->poke_refcount) == 1) {
1490                 /* First refcount for poke needed: check if not already in flight */
1491                 if (!as->poke_state) {
1492                         /* need to start poking */
1493                         as->poke_state |= KBASE_AS_POKE_STATE_IN_FLIGHT;
1494                         queue_work(as->poke_wq, &as->poke_work);
1495                 }
1496         }
1497 }
1498
1499 /**
1500  * If an atom holds a poking timer, release it and wait for it to finish
1501  *
1502  * This must only be called on a context that's scheduled in, and an atom
1503  * that still has a JS reference on the context
1504  *
1505  * This must \b not be called from atomic context, since it can sleep.
1506  */
1507 void kbase_as_poking_timer_release_atom(kbase_device *kbdev, kbase_context *kctx, kbase_jd_atom *katom)
1508 {
1509         kbase_as *as;
1510         unsigned long flags;
1511
1512         KBASE_DEBUG_ASSERT(kbdev);
1513         KBASE_DEBUG_ASSERT(kctx);
1514         KBASE_DEBUG_ASSERT(katom);
1515         KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID);
1516
1517         if (!katom->poking)
1518                 return;
1519
1520         as = &kbdev->as[kctx->as_nr];
1521
1522         spin_lock_irqsave(&kbdev->js_data.runpool_irq.lock, flags);
1523         KBASE_DEBUG_ASSERT(as->poke_refcount > 0);
1524         KBASE_DEBUG_ASSERT(as->poke_state & KBASE_AS_POKE_STATE_IN_FLIGHT);
1525
1526         if (--(as->poke_refcount) == 0) {
1527                 as->poke_state |= KBASE_AS_POKE_STATE_KILLING_POKE;
1528                 spin_unlock_irqrestore(&kbdev->js_data.runpool_irq.lock, flags);
1529
1530                 hrtimer_cancel(&as->poke_timer);
1531                 flush_workqueue(as->poke_wq);
1532
1533                 spin_lock_irqsave(&kbdev->js_data.runpool_irq.lock, flags);
1534
1535                 /* Re-check whether it's still needed */
1536                 if (as->poke_refcount) {
1537                         int queue_work_ret;
1538                         /* Poking still needed:
1539                          * - Another retain will not be starting the timer or queueing work,
1540                          * because it's still marked as in-flight
1541                          * - The hrtimer has finished, and has not started a new timer or
1542                          * queued work because it's been marked as killing
1543                          *
1544                          * So whatever happens now, just queue the work again */
1545                         as->poke_state &= ~((kbase_as_poke_state)KBASE_AS_POKE_STATE_KILLING_POKE);
1546                         queue_work_ret = queue_work(as->poke_wq, &as->poke_work);
1547                         KBASE_DEBUG_ASSERT(queue_work_ret);
1548                 } else {
1549                         /* It isn't - so mark it as not in flight, and not killing */
1550                         as->poke_state = 0u;
1551
1552                         /* The poke associated with the atom has now finished. If this is
1553                          * also the last atom on the context, then we can guarentee no more
1554                          * pokes (and thus no more poking register accesses) will occur on
1555                          * the context until new atoms are run */
1556                 }
1557         }
1558         spin_unlock_irqrestore(&kbdev->js_data.runpool_irq.lock, flags);
1559
1560         katom->poking = 0;
1561 }