1 // SPDX-License-Identifier: GPL-2.0 or MIT
3 /* Copyright 2023 Collabora ltd. */
5 #include <drm/drm_debugfs.h>
6 #include <drm/drm_drv.h>
7 #include <drm/drm_exec.h>
8 #include <drm/drm_gpuvm.h>
9 #include <drm/drm_managed.h>
10 #include <drm/gpu_scheduler.h>
11 #include <drm/panthor_drm.h>
13 #include <linux/atomic.h>
14 #include <linux/bitfield.h>
15 #include <linux/delay.h>
16 #include <linux/dma-mapping.h>
17 #include <linux/interrupt.h>
19 #include <linux/iopoll.h>
20 #include <linux/io-pgtable.h>
21 #include <linux/iommu.h>
22 #include <linux/kmemleak.h>
23 #include <linux/platform_device.h>
24 #include <linux/pm_runtime.h>
25 #include <linux/rwsem.h>
26 #include <linux/sched.h>
27 #include <linux/shmem_fs.h>
28 #include <linux/sizes.h>
30 #include "panthor_device.h"
31 #include "panthor_gem.h"
32 #include "panthor_heap.h"
33 #include "panthor_mmu.h"
34 #include "panthor_regs.h"
35 #include "panthor_sched.h"
37 #define MAX_AS_SLOTS 32
42 * struct panthor_as_slot - Address space slot
44 struct panthor_as_slot {
45 /** @vm: VM bound to this slot. NULL is no VM is bound. */
46 struct panthor_vm *vm;
50 * struct panthor_mmu - MMU related data
53 /** @irq: The MMU irq. */
54 struct panthor_irq irq;
56 /** @as: Address space related fields.
58 * The GPU has a limited number of address spaces (AS) slots, forcing
59 * us to re-assign them to re-assign slots on-demand.
62 /** @slots_lock: Lock protecting access to all other AS fields. */
63 struct mutex slots_lock;
65 /** @alloc_mask: Bitmask encoding the allocated slots. */
66 unsigned long alloc_mask;
68 /** @faulty_mask: Bitmask encoding the faulty slots. */
69 unsigned long faulty_mask;
71 /** @slots: VMs currently bound to the AS slots. */
72 struct panthor_as_slot slots[MAX_AS_SLOTS];
75 * @lru_list: List of least recently used VMs.
77 * We use this list to pick a VM to evict when all slots are
80 * There should be no more active VMs than there are AS slots,
81 * so this LRU is just here to keep VMs bound until there's
82 * a need to release a slot, thus avoid unnecessary TLB/cache
85 struct list_head lru_list;
88 /** @vm: VMs management fields */
90 /** @lock: Lock protecting access to list. */
93 /** @list: List containing all VMs. */
94 struct list_head list;
96 /** @reset_in_progress: True if a reset is in progress. */
97 bool reset_in_progress;
99 /** @wq: Workqueue used for the VM_BIND queues. */
100 struct workqueue_struct *wq;
105 * struct panthor_vm_pool - VM pool object
107 struct panthor_vm_pool {
108 /** @xa: Array used for VM handle tracking. */
113 * struct panthor_vma - GPU mapping object
115 * This is used to track GEM mappings in GPU space.
118 /** @base: Inherits from drm_gpuva. */
119 struct drm_gpuva base;
121 /** @node: Used to implement deferred release of VMAs. */
122 struct list_head node;
125 * @flags: Combination of drm_panthor_vm_bind_op_flags.
127 * Only map related flags are accepted.
133 * struct panthor_vm_op_ctx - VM operation context
135 * With VM operations potentially taking place in a dma-signaling path, we
136 * need to make sure everything that might require resource allocation is
137 * pre-allocated upfront. This is what this operation context is far.
139 * We also collect resources that have been freed, so we can release them
140 * asynchronously, and let the VM_BIND scheduler process the next VM_BIND
143 struct panthor_vm_op_ctx {
144 /** @rsvd_page_tables: Pages reserved for the MMU page table update. */
146 /** @count: Number of pages reserved. */
149 /** @ptr: Point to the first unused page in the @pages table. */
153 * @page: Array of pages that can be used for an MMU page table update.
155 * After an VM operation, there might be free pages left in this array.
156 * They should be returned to the pt_cache as part of the op_ctx cleanup.
162 * @preallocated_vmas: Pre-allocated VMAs to handle the remap case.
164 * Partial unmap requests or map requests overlapping existing mappings will
165 * trigger a remap call, which need to register up to three panthor_vma objects
166 * (one for the new mapping, and two for the previous and next mappings).
168 struct panthor_vma *preallocated_vmas[3];
170 /** @flags: Combination of drm_panthor_vm_bind_op_flags. */
173 /** @va: Virtual range targeted by the VM operation. */
175 /** @addr: Start address. */
178 /** @range: Range size. */
183 * @returned_vmas: List of panthor_vma objects returned after a VM operation.
185 * For unmap operations, this will contain all VMAs that were covered by the
186 * specified VA range.
188 * For map operations, this will contain all VMAs that previously mapped to
189 * the specified VA range.
191 * Those VMAs, and the resources they point to will be released as part of
192 * the op_ctx cleanup operation.
194 struct list_head returned_vmas;
196 /** @map: Fields specific to a map operation. */
198 /** @vm_bo: Buffer object to map. */
199 struct drm_gpuvm_bo *vm_bo;
201 /** @bo_offset: Offset in the buffer object. */
205 * @sgt: sg-table pointing to pages backing the GEM object.
207 * This is gathered at job creation time, such that we don't have
208 * to allocate in ::run_job().
210 struct sg_table *sgt;
213 * @new_vma: The new VMA object that will be inserted to the VA tree.
215 struct panthor_vma *new_vma;
220 * struct panthor_vm - VM object
222 * A VM is an object representing a GPU (or MCU) virtual address space.
223 * It embeds the MMU page table for this address space, a tree containing
224 * all the virtual mappings of GEM objects, and other things needed to manage
227 * Except for the MCU VM, which is managed by the kernel, all other VMs are
228 * created by userspace and mostly managed by userspace, using the
229 * %DRM_IOCTL_PANTHOR_VM_BIND ioctl.
231 * A portion of the virtual address space is reserved for kernel objects,
232 * like heap chunks, and userspace gets to decide how much of the virtual
233 * address space is left to the kernel (half of the virtual address space
238 * @base: Inherit from drm_gpuvm.
240 * We delegate all the VA management to the common drm_gpuvm framework
241 * and only implement hooks to update the MMU page table.
243 struct drm_gpuvm base;
246 * @sched: Scheduler used for asynchronous VM_BIND request.
248 * We use a 1:1 scheduler here.
250 struct drm_gpu_scheduler sched;
253 * @entity: Scheduling entity representing the VM_BIND queue.
255 * There's currently one bind queue per VM. It doesn't make sense to
256 * allow more given the VM operations are serialized anyway.
258 struct drm_sched_entity entity;
260 /** @ptdev: Device. */
261 struct panthor_device *ptdev;
263 /** @memattr: Value to program to the AS_MEMATTR register. */
266 /** @pgtbl_ops: Page table operations. */
267 struct io_pgtable_ops *pgtbl_ops;
269 /** @root_page_table: Stores the root page table pointer. */
270 void *root_page_table;
273 * @op_lock: Lock used to serialize operations on a VM.
275 * The serialization of jobs queued to the VM_BIND queue is already
276 * taken care of by drm_sched, but we need to serialize synchronous
277 * and asynchronous VM_BIND request. This is what this lock is for.
279 struct mutex op_lock;
282 * @op_ctx: The context attached to the currently executing VM operation.
284 * NULL when no operation is in progress.
286 struct panthor_vm_op_ctx *op_ctx;
289 * @mm: Memory management object representing the auto-VA/kernel-VA.
291 * Used to auto-allocate VA space for kernel-managed objects (tiler
294 * For the MCU VM, this is managing the VA range that's used to map
295 * all shared interfaces.
297 * For user VMs, the range is specified by userspace, and must not
298 * exceed half of the VA space addressable.
302 /** @mm_lock: Lock protecting the @mm field. */
303 struct mutex mm_lock;
305 /** @kernel_auto_va: Automatic VA-range for kernel BOs. */
307 /** @start: Start of the automatic VA-range for kernel BOs. */
310 /** @size: Size of the automatic VA-range for kernel BOs. */
314 /** @as: Address space related fields. */
317 * @id: ID of the address space this VM is bound to.
319 * A value of -1 means the VM is inactive/not bound.
323 /** @active_cnt: Number of active users of this VM. */
324 refcount_t active_cnt;
327 * @lru_node: Used to instead the VM in the panthor_mmu::as::lru_list.
329 * Active VMs should not be inserted in the LRU list.
331 struct list_head lru_node;
335 * @heaps: Tiler heap related fields.
339 * @pool: The heap pool attached to this VM.
341 * Will stay NULL until someone creates a heap context on this VM.
343 struct panthor_heap_pool *pool;
345 /** @lock: Lock used to protect access to @pool. */
349 /** @node: Used to insert the VM in the panthor_mmu::vm::list. */
350 struct list_head node;
352 /** @for_mcu: True if this is the MCU VM. */
356 * @destroyed: True if the VM was destroyed.
358 * No further bind requests should be queued to a destroyed VM.
363 * @unusable: True if the VM has turned unusable because something
364 * bad happened during an asynchronous request.
366 * We don't try to recover from such failures, because this implies
367 * informing userspace about the specific operation that failed, and
368 * hoping the userspace driver can replay things from there. This all
369 * sounds very complicated for little gain.
371 * Instead, we should just flag the VM as unusable, and fail any
372 * further request targeting this VM.
374 * We also provide a way to query a VM state, so userspace can destroy
375 * it and create a new one.
377 * As an analogy, this would be mapped to a VK_ERROR_DEVICE_LOST
378 * situation, where the logical device needs to be re-created.
383 * @unhandled_fault: Unhandled fault happened.
385 * This should be reported to the scheduler, and the queue/group be
386 * flagged as faulty as a result.
388 bool unhandled_fault;
392 * struct panthor_vm_bind_job - VM bind job
394 struct panthor_vm_bind_job {
395 /** @base: Inherit from drm_sched_job. */
396 struct drm_sched_job base;
398 /** @refcount: Reference count. */
399 struct kref refcount;
401 /** @cleanup_op_ctx_work: Work used to cleanup the VM operation context. */
402 struct work_struct cleanup_op_ctx_work;
404 /** @vm: VM targeted by the VM operation. */
405 struct panthor_vm *vm;
407 /** @ctx: Operation context. */
408 struct panthor_vm_op_ctx ctx;
412 * @pt_cache: Cache used to allocate MMU page tables.
414 * The pre-allocation pattern forces us to over-allocate to plan for
415 * the worst case scenario, and return the pages we didn't use.
417 * Having a kmem_cache allows us to speed allocations.
419 static struct kmem_cache *pt_cache;
422 * alloc_pt() - Custom page table allocator
423 * @cookie: Cookie passed at page table allocation time.
424 * @size: Size of the page table. This size should be fixed,
425 * and determined at creation time based on the granule size.
428 * We want a custom allocator so we can use a cache for page table
429 * allocations and amortize the cost of the over-reservation that's
430 * done to allow asynchronous VM operations.
432 * Return: non-NULL on success, NULL if the allocation failed for any
435 static void *alloc_pt(void *cookie, size_t size, gfp_t gfp)
437 struct panthor_vm *vm = cookie;
440 /* Allocation of the root page table happening during init. */
441 if (unlikely(!vm->root_page_table)) {
444 drm_WARN_ON(&vm->ptdev->base, vm->op_ctx);
445 p = alloc_pages_node(dev_to_node(vm->ptdev->base.dev),
446 gfp | __GFP_ZERO, get_order(size));
447 page = p ? page_address(p) : NULL;
448 vm->root_page_table = page;
452 /* We're not supposed to have anything bigger than 4k here, because we picked a
453 * 4k granule size at init time.
455 if (drm_WARN_ON(&vm->ptdev->base, size != SZ_4K))
458 /* We must have some op_ctx attached to the VM and it must have at least one
461 if (drm_WARN_ON(&vm->ptdev->base, !vm->op_ctx) ||
462 drm_WARN_ON(&vm->ptdev->base,
463 vm->op_ctx->rsvd_page_tables.ptr >= vm->op_ctx->rsvd_page_tables.count))
466 page = vm->op_ctx->rsvd_page_tables.pages[vm->op_ctx->rsvd_page_tables.ptr++];
467 memset(page, 0, SZ_4K);
469 /* Page table entries don't use virtual addresses, which trips out
470 * kmemleak. kmemleak_alloc_phys() might work, but physical addresses
471 * are mixed with other fields, and I fear kmemleak won't detect that
474 * Let's just ignore memory passed to the page-table driver for now.
476 kmemleak_ignore(page);
481 * @free_pt() - Custom page table free function
482 * @cookie: Cookie passed at page table allocation time.
483 * @data: Page table to free.
484 * @size: Size of the page table. This size should be fixed,
485 * and determined at creation time based on the granule size.
487 static void free_pt(void *cookie, void *data, size_t size)
489 struct panthor_vm *vm = cookie;
491 if (unlikely(vm->root_page_table == data)) {
492 free_pages((unsigned long)data, get_order(size));
493 vm->root_page_table = NULL;
497 if (drm_WARN_ON(&vm->ptdev->base, size != SZ_4K))
500 /* Return the page to the pt_cache. */
501 kmem_cache_free(pt_cache, data);
504 static int wait_ready(struct panthor_device *ptdev, u32 as_nr)
509 /* Wait for the MMU status to indicate there is no active command, in
510 * case one is pending.
512 ret = readl_relaxed_poll_timeout_atomic(ptdev->iomem + AS_STATUS(as_nr),
513 val, !(val & AS_STATUS_AS_ACTIVE),
517 panthor_device_schedule_reset(ptdev);
518 drm_err(&ptdev->base, "AS_ACTIVE bit stuck\n");
524 static int write_cmd(struct panthor_device *ptdev, u32 as_nr, u32 cmd)
528 /* write AS_COMMAND when MMU is ready to accept another command */
529 status = wait_ready(ptdev, as_nr);
531 gpu_write(ptdev, AS_COMMAND(as_nr), cmd);
536 static void lock_region(struct panthor_device *ptdev, u32 as_nr,
537 u64 region_start, u64 size)
541 u64 region_end = region_start + size;
547 * The locked region is a naturally aligned power of 2 block encoded as
549 * Calculate the desired start/end and look for the highest bit which
550 * differs. The smallest naturally aligned block must include this bit
551 * change, the desired region starts with this bit (and subsequent bits)
552 * zeroed and ends with the bit (and subsequent bits) set to one.
554 region_width = max(fls64(region_start ^ (region_end - 1)),
555 const_ilog2(AS_LOCK_REGION_MIN_SIZE)) - 1;
558 * Mask off the low bits of region_start (which would be ignored by
559 * the hardware anyway)
561 region_start &= GENMASK_ULL(63, region_width);
563 region = region_width | region_start;
565 /* Lock the region that needs to be updated */
566 gpu_write(ptdev, AS_LOCKADDR_LO(as_nr), lower_32_bits(region));
567 gpu_write(ptdev, AS_LOCKADDR_HI(as_nr), upper_32_bits(region));
568 write_cmd(ptdev, as_nr, AS_COMMAND_LOCK);
571 static int mmu_hw_do_operation_locked(struct panthor_device *ptdev, int as_nr,
572 u64 iova, u64 size, u32 op)
574 lockdep_assert_held(&ptdev->mmu->as.slots_lock);
580 * If the AS number is greater than zero, then we can be sure
581 * the device is up and running, so we don't need to explicitly
585 if (op != AS_COMMAND_UNLOCK)
586 lock_region(ptdev, as_nr, iova, size);
588 /* Run the MMU operation */
589 write_cmd(ptdev, as_nr, op);
591 /* Wait for the flush to complete */
592 return wait_ready(ptdev, as_nr);
595 static int mmu_hw_do_operation(struct panthor_vm *vm,
596 u64 iova, u64 size, u32 op)
598 struct panthor_device *ptdev = vm->ptdev;
601 mutex_lock(&ptdev->mmu->as.slots_lock);
602 ret = mmu_hw_do_operation_locked(ptdev, vm->as.id, iova, size, op);
603 mutex_unlock(&ptdev->mmu->as.slots_lock);
608 static int panthor_mmu_as_enable(struct panthor_device *ptdev, u32 as_nr,
609 u64 transtab, u64 transcfg, u64 memattr)
613 ret = mmu_hw_do_operation_locked(ptdev, as_nr, 0, ~0ULL, AS_COMMAND_FLUSH_MEM);
617 gpu_write(ptdev, AS_TRANSTAB_LO(as_nr), lower_32_bits(transtab));
618 gpu_write(ptdev, AS_TRANSTAB_HI(as_nr), upper_32_bits(transtab));
620 gpu_write(ptdev, AS_MEMATTR_LO(as_nr), lower_32_bits(memattr));
621 gpu_write(ptdev, AS_MEMATTR_HI(as_nr), upper_32_bits(memattr));
623 gpu_write(ptdev, AS_TRANSCFG_LO(as_nr), lower_32_bits(transcfg));
624 gpu_write(ptdev, AS_TRANSCFG_HI(as_nr), upper_32_bits(transcfg));
626 return write_cmd(ptdev, as_nr, AS_COMMAND_UPDATE);
629 static int panthor_mmu_as_disable(struct panthor_device *ptdev, u32 as_nr)
633 ret = mmu_hw_do_operation_locked(ptdev, as_nr, 0, ~0ULL, AS_COMMAND_FLUSH_MEM);
637 gpu_write(ptdev, AS_TRANSTAB_LO(as_nr), 0);
638 gpu_write(ptdev, AS_TRANSTAB_HI(as_nr), 0);
640 gpu_write(ptdev, AS_MEMATTR_LO(as_nr), 0);
641 gpu_write(ptdev, AS_MEMATTR_HI(as_nr), 0);
643 gpu_write(ptdev, AS_TRANSCFG_LO(as_nr), AS_TRANSCFG_ADRMODE_UNMAPPED);
644 gpu_write(ptdev, AS_TRANSCFG_HI(as_nr), 0);
646 return write_cmd(ptdev, as_nr, AS_COMMAND_UPDATE);
649 static u32 panthor_mmu_fault_mask(struct panthor_device *ptdev, u32 value)
651 /* Bits 16 to 31 mean REQ_COMPLETE. */
652 return value & GENMASK(15, 0);
655 static u32 panthor_mmu_as_fault_mask(struct panthor_device *ptdev, u32 as)
661 * panthor_vm_has_unhandled_faults() - Check if a VM has unhandled faults
664 * Return: true if the VM has unhandled faults, false otherwise.
666 bool panthor_vm_has_unhandled_faults(struct panthor_vm *vm)
668 return vm->unhandled_fault;
672 * panthor_vm_is_unusable() - Check if the VM is still usable
675 * Return: true if the VM is unusable, false otherwise.
677 bool panthor_vm_is_unusable(struct panthor_vm *vm)
682 static void panthor_vm_release_as_locked(struct panthor_vm *vm)
684 struct panthor_device *ptdev = vm->ptdev;
686 lockdep_assert_held(&ptdev->mmu->as.slots_lock);
688 if (drm_WARN_ON(&ptdev->base, vm->as.id < 0))
691 ptdev->mmu->as.slots[vm->as.id].vm = NULL;
692 clear_bit(vm->as.id, &ptdev->mmu->as.alloc_mask);
693 refcount_set(&vm->as.active_cnt, 0);
694 list_del_init(&vm->as.lru_node);
699 * panthor_vm_active() - Flag a VM as active
700 * @VM: VM to flag as active.
702 * Assigns an address space to a VM so it can be used by the GPU/MCU.
704 * Return: 0 on success, a negative error code otherwise.
706 int panthor_vm_active(struct panthor_vm *vm)
708 struct panthor_device *ptdev = vm->ptdev;
709 u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
710 struct io_pgtable_cfg *cfg = &io_pgtable_ops_to_pgtable(vm->pgtbl_ops)->cfg;
711 int ret = 0, as, cookie;
712 u64 transtab, transcfg;
714 if (!drm_dev_enter(&ptdev->base, &cookie))
717 if (refcount_inc_not_zero(&vm->as.active_cnt))
720 mutex_lock(&ptdev->mmu->as.slots_lock);
722 if (refcount_inc_not_zero(&vm->as.active_cnt))
727 /* Unhandled pagefault on this AS, the MMU was disabled. We need to
728 * re-enable the MMU after clearing+unmasking the AS interrupts.
730 if (ptdev->mmu->as.faulty_mask & panthor_mmu_as_fault_mask(ptdev, as))
733 goto out_make_active;
736 /* Check for a free AS */
738 drm_WARN_ON(&ptdev->base, ptdev->mmu->as.alloc_mask & BIT(0));
741 as = ffz(ptdev->mmu->as.alloc_mask | BIT(0));
744 if (!(BIT(as) & ptdev->gpu_info.as_present)) {
745 struct panthor_vm *lru_vm;
747 lru_vm = list_first_entry_or_null(&ptdev->mmu->as.lru_list,
750 if (drm_WARN_ON(&ptdev->base, !lru_vm)) {
755 drm_WARN_ON(&ptdev->base, refcount_read(&lru_vm->as.active_cnt));
757 panthor_vm_release_as_locked(lru_vm);
760 /* Assign the free or reclaimed AS to the FD */
762 set_bit(as, &ptdev->mmu->as.alloc_mask);
763 ptdev->mmu->as.slots[as].vm = vm;
766 transtab = cfg->arm_lpae_s1_cfg.ttbr;
767 transcfg = AS_TRANSCFG_PTW_MEMATTR_WB |
769 AS_TRANSCFG_ADRMODE_AARCH64_4K |
770 AS_TRANSCFG_INA_BITS(55 - va_bits);
772 transcfg |= AS_TRANSCFG_PTW_SH_OS;
774 /* If the VM is re-activated, we clear the fault. */
775 vm->unhandled_fault = false;
777 /* Unhandled pagefault on this AS, clear the fault and re-enable interrupts
778 * before enabling the AS.
780 if (ptdev->mmu->as.faulty_mask & panthor_mmu_as_fault_mask(ptdev, as)) {
781 gpu_write(ptdev, MMU_INT_CLEAR, panthor_mmu_as_fault_mask(ptdev, as));
782 ptdev->mmu->as.faulty_mask &= ~panthor_mmu_as_fault_mask(ptdev, as);
783 gpu_write(ptdev, MMU_INT_MASK, ~ptdev->mmu->as.faulty_mask);
786 ret = panthor_mmu_as_enable(vm->ptdev, vm->as.id, transtab, transcfg, vm->memattr);
790 refcount_set(&vm->as.active_cnt, 1);
791 list_del_init(&vm->as.lru_node);
795 mutex_unlock(&ptdev->mmu->as.slots_lock);
798 drm_dev_exit(cookie);
803 * panthor_vm_idle() - Flag a VM idle
804 * @VM: VM to flag as idle.
806 * When we know the GPU is done with the VM (no more jobs to process),
807 * we can relinquish the AS slot attached to this VM, if any.
809 * We don't release the slot immediately, but instead place the VM in
810 * the LRU list, so it can be evicted if another VM needs an AS slot.
811 * This way, VMs keep attached to the AS they were given until we run
812 * out of free slot, limiting the number of MMU operations (TLB flush
813 * and other AS updates).
815 void panthor_vm_idle(struct panthor_vm *vm)
817 struct panthor_device *ptdev = vm->ptdev;
819 if (!refcount_dec_and_mutex_lock(&vm->as.active_cnt, &ptdev->mmu->as.slots_lock))
822 if (!drm_WARN_ON(&ptdev->base, vm->as.id == -1 || !list_empty(&vm->as.lru_node)))
823 list_add_tail(&vm->as.lru_node, &ptdev->mmu->as.lru_list);
825 refcount_set(&vm->as.active_cnt, 0);
826 mutex_unlock(&ptdev->mmu->as.slots_lock);
829 u32 panthor_vm_page_size(struct panthor_vm *vm)
831 const struct io_pgtable *pgt = io_pgtable_ops_to_pgtable(vm->pgtbl_ops);
832 u32 pg_shift = ffs(pgt->cfg.pgsize_bitmap) - 1;
834 return 1u << pg_shift;
837 static void panthor_vm_stop(struct panthor_vm *vm)
839 drm_sched_stop(&vm->sched, NULL);
842 static void panthor_vm_start(struct panthor_vm *vm)
844 drm_sched_start(&vm->sched, 0);
848 * panthor_vm_as() - Get the AS slot attached to a VM
849 * @vm: VM to get the AS slot of.
851 * Return: -1 if the VM is not assigned an AS slot yet, >= 0 otherwise.
853 int panthor_vm_as(struct panthor_vm *vm)
858 static size_t get_pgsize(u64 addr, size_t size, size_t *count)
861 * io-pgtable only operates on multiple pages within a single table
862 * entry, so we need to split at boundaries of the table size, i.e.
863 * the next block size up. The distance from address A to the next
864 * boundary of block size B is logically B - A % B, but in unsigned
865 * two's complement where B is a power of two we get the equivalence
866 * B - A % B == (B - A) % B == (n * B - A) % B, and choose n = 0 :)
868 size_t blk_offset = -addr % SZ_2M;
870 if (blk_offset || size < SZ_2M) {
871 *count = min_not_zero(blk_offset, size) / SZ_4K;
874 blk_offset = -addr % SZ_1G ?: SZ_1G;
875 *count = min(blk_offset, size) / SZ_2M;
879 static int panthor_vm_flush_range(struct panthor_vm *vm, u64 iova, u64 size)
881 struct panthor_device *ptdev = vm->ptdev;
887 /* If the device is unplugged, we just silently skip the flush. */
888 if (!drm_dev_enter(&ptdev->base, &cookie))
891 ret = mmu_hw_do_operation(vm, iova, size, AS_COMMAND_FLUSH_PT);
893 drm_dev_exit(cookie);
898 * panthor_vm_flush_all() - Flush L2 caches for the entirety of a VM's AS
899 * @vm: VM whose cache to flush
901 * Return: 0 on success, a negative error code if flush failed.
903 int panthor_vm_flush_all(struct panthor_vm *vm)
905 return panthor_vm_flush_range(vm, vm->base.mm_start, vm->base.mm_range);
908 static int panthor_vm_unmap_pages(struct panthor_vm *vm, u64 iova, u64 size)
910 struct panthor_device *ptdev = vm->ptdev;
911 struct io_pgtable_ops *ops = vm->pgtbl_ops;
914 drm_dbg(&ptdev->base, "unmap: as=%d, iova=%llx, len=%llx", vm->as.id, iova, size);
916 while (offset < size) {
917 size_t unmapped_sz = 0, pgcount;
918 size_t pgsize = get_pgsize(iova + offset, size - offset, &pgcount);
920 unmapped_sz = ops->unmap_pages(ops, iova + offset, pgsize, pgcount, NULL);
922 if (drm_WARN_ON(&ptdev->base, unmapped_sz != pgsize * pgcount)) {
923 drm_err(&ptdev->base, "failed to unmap range %llx-%llx (requested range %llx-%llx)\n",
924 iova + offset + unmapped_sz,
925 iova + offset + pgsize * pgcount,
927 panthor_vm_flush_range(vm, iova, offset + unmapped_sz);
930 offset += unmapped_sz;
933 return panthor_vm_flush_range(vm, iova, size);
937 panthor_vm_map_pages(struct panthor_vm *vm, u64 iova, int prot,
938 struct sg_table *sgt, u64 offset, u64 size)
940 struct panthor_device *ptdev = vm->ptdev;
942 struct scatterlist *sgl;
943 struct io_pgtable_ops *ops = vm->pgtbl_ops;
944 u64 start_iova = iova;
950 for_each_sgtable_dma_sg(sgt, sgl, count) {
951 dma_addr_t paddr = sg_dma_address(sgl);
952 size_t len = sg_dma_len(sgl);
961 len = min_t(size_t, len, size);
964 drm_dbg(&ptdev->base, "map: as=%d, iova=%llx, paddr=%pad, len=%zx",
965 vm->as.id, iova, &paddr, len);
968 size_t pgcount, mapped = 0;
969 size_t pgsize = get_pgsize(iova | paddr, len, &pgcount);
971 ret = ops->map_pages(ops, iova, paddr, pgsize, pgcount, prot,
972 GFP_KERNEL, &mapped);
977 if (drm_WARN_ON(&ptdev->base, !ret && !mapped))
981 /* If something failed, unmap what we've already mapped before
982 * returning. The unmap call is not supposed to fail.
984 drm_WARN_ON(&ptdev->base,
985 panthor_vm_unmap_pages(vm, start_iova,
997 return panthor_vm_flush_range(vm, start_iova, iova - start_iova);
1000 static int flags_to_prot(u32 flags)
1004 if (flags & DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC)
1005 prot |= IOMMU_NOEXEC;
1007 if (!(flags & DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED))
1008 prot |= IOMMU_CACHE;
1010 if (flags & DRM_PANTHOR_VM_BIND_OP_MAP_READONLY)
1013 prot |= IOMMU_READ | IOMMU_WRITE;
1019 * panthor_vm_alloc_va() - Allocate a region in the auto-va space
1020 * @VM: VM to allocate a region on.
1021 * @va: start of the VA range. Can be PANTHOR_VM_KERNEL_AUTO_VA if the user
1022 * wants the VA to be automatically allocated from the auto-VA range.
1023 * @size: size of the VA range.
1024 * @va_node: drm_mm_node to initialize. Must be zero-initialized.
1026 * Some GPU objects, like heap chunks, are fully managed by the kernel and
1027 * need to be mapped to the userspace VM, in the region reserved for kernel
1030 * This function takes care of allocating a region in the kernel auto-VA space.
1032 * Return: 0 on success, an error code otherwise.
1035 panthor_vm_alloc_va(struct panthor_vm *vm, u64 va, u64 size,
1036 struct drm_mm_node *va_node)
1038 ssize_t vm_pgsz = panthor_vm_page_size(vm);
1041 if (!size || !IS_ALIGNED(size, vm_pgsz))
1044 if (va != PANTHOR_VM_KERNEL_AUTO_VA && !IS_ALIGNED(va, vm_pgsz))
1047 mutex_lock(&vm->mm_lock);
1048 if (va != PANTHOR_VM_KERNEL_AUTO_VA) {
1049 va_node->start = va;
1050 va_node->size = size;
1051 ret = drm_mm_reserve_node(&vm->mm, va_node);
1053 ret = drm_mm_insert_node_in_range(&vm->mm, va_node, size,
1054 size >= SZ_2M ? SZ_2M : SZ_4K,
1055 0, vm->kernel_auto_va.start,
1056 vm->kernel_auto_va.end,
1057 DRM_MM_INSERT_BEST);
1059 mutex_unlock(&vm->mm_lock);
1065 * panthor_vm_free_va() - Free a region allocated with panthor_vm_alloc_va()
1066 * @VM: VM to free the region on.
1067 * @va_node: Memory node representing the region to free.
1069 void panthor_vm_free_va(struct panthor_vm *vm, struct drm_mm_node *va_node)
1071 mutex_lock(&vm->mm_lock);
1072 drm_mm_remove_node(va_node);
1073 mutex_unlock(&vm->mm_lock);
1076 static void panthor_vm_bo_put(struct drm_gpuvm_bo *vm_bo)
1078 struct panthor_gem_object *bo = to_panthor_bo(vm_bo->obj);
1079 struct drm_gpuvm *vm = vm_bo->vm;
1082 /* We must retain the GEM before calling drm_gpuvm_bo_put(),
1083 * otherwise the mutex might be destroyed while we hold it.
1084 * Same goes for the VM, since we take the VM resv lock.
1086 drm_gem_object_get(&bo->base.base);
1089 /* We take the resv lock to protect against concurrent accesses to the
1090 * gpuvm evicted/extobj lists that are modified in
1091 * drm_gpuvm_bo_destroy(), which is called if drm_gpuvm_bo_put()
1092 * releases sthe last vm_bo reference.
1093 * We take the BO GPUVA list lock to protect the vm_bo removal from the
1096 dma_resv_lock(drm_gpuvm_resv(vm), NULL);
1097 mutex_lock(&bo->gpuva_list_lock);
1098 unpin = drm_gpuvm_bo_put(vm_bo);
1099 mutex_unlock(&bo->gpuva_list_lock);
1100 dma_resv_unlock(drm_gpuvm_resv(vm));
1102 /* If the vm_bo object was destroyed, release the pin reference that
1103 * was hold by this object.
1105 if (unpin && !bo->base.base.import_attach)
1106 drm_gem_shmem_unpin(&bo->base);
1109 drm_gem_object_put(&bo->base.base);
1112 static void panthor_vm_cleanup_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1113 struct panthor_vm *vm)
1115 struct panthor_vma *vma, *tmp_vma;
1117 u32 remaining_pt_count = op_ctx->rsvd_page_tables.count -
1118 op_ctx->rsvd_page_tables.ptr;
1120 if (remaining_pt_count) {
1121 kmem_cache_free_bulk(pt_cache, remaining_pt_count,
1122 op_ctx->rsvd_page_tables.pages +
1123 op_ctx->rsvd_page_tables.ptr);
1126 kfree(op_ctx->rsvd_page_tables.pages);
1128 if (op_ctx->map.vm_bo)
1129 panthor_vm_bo_put(op_ctx->map.vm_bo);
1131 for (u32 i = 0; i < ARRAY_SIZE(op_ctx->preallocated_vmas); i++)
1132 kfree(op_ctx->preallocated_vmas[i]);
1134 list_for_each_entry_safe(vma, tmp_vma, &op_ctx->returned_vmas, node) {
1135 list_del(&vma->node);
1136 panthor_vm_bo_put(vma->base.vm_bo);
1141 static struct panthor_vma *
1142 panthor_vm_op_ctx_get_vma(struct panthor_vm_op_ctx *op_ctx)
1144 for (u32 i = 0; i < ARRAY_SIZE(op_ctx->preallocated_vmas); i++) {
1145 struct panthor_vma *vma = op_ctx->preallocated_vmas[i];
1148 op_ctx->preallocated_vmas[i] = NULL;
1157 panthor_vm_op_ctx_prealloc_vmas(struct panthor_vm_op_ctx *op_ctx)
1161 switch (op_ctx->flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK) {
1162 case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP:
1163 /* One VMA for the new mapping, and two more VMAs for the remap case
1164 * which might contain both a prev and next VA.
1169 case DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP:
1170 /* Partial unmaps might trigger a remap with either a prev or a next VA,
1180 for (u32 i = 0; i < vma_count; i++) {
1181 struct panthor_vma *vma = kzalloc(sizeof(*vma), GFP_KERNEL);
1186 op_ctx->preallocated_vmas[i] = vma;
1192 #define PANTHOR_VM_BIND_OP_MAP_FLAGS \
1193 (DRM_PANTHOR_VM_BIND_OP_MAP_READONLY | \
1194 DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC | \
1195 DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED | \
1196 DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
1198 static int panthor_vm_prepare_map_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1199 struct panthor_vm *vm,
1200 struct panthor_gem_object *bo,
1205 struct drm_gpuvm_bo *preallocated_vm_bo;
1206 struct sg_table *sgt = NULL;
1213 if ((flags & ~PANTHOR_VM_BIND_OP_MAP_FLAGS) ||
1214 (flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK) != DRM_PANTHOR_VM_BIND_OP_TYPE_MAP)
1217 /* Make sure the VA and size are aligned and in-bounds. */
1218 if (size > bo->base.base.size || offset > bo->base.base.size - size)
1221 /* If the BO has an exclusive VM attached, it can't be mapped to other VMs. */
1222 if (bo->exclusive_vm_root_gem &&
1223 bo->exclusive_vm_root_gem != panthor_vm_root_gem(vm))
1226 memset(op_ctx, 0, sizeof(*op_ctx));
1227 INIT_LIST_HEAD(&op_ctx->returned_vmas);
1228 op_ctx->flags = flags;
1229 op_ctx->va.range = size;
1230 op_ctx->va.addr = va;
1232 ret = panthor_vm_op_ctx_prealloc_vmas(op_ctx);
1236 if (!bo->base.base.import_attach) {
1237 /* Pre-reserve the BO pages, so the map operation doesn't have to
1240 ret = drm_gem_shmem_pin(&bo->base);
1245 sgt = drm_gem_shmem_get_pages_sgt(&bo->base);
1247 if (!bo->base.base.import_attach)
1248 drm_gem_shmem_unpin(&bo->base);
1254 op_ctx->map.sgt = sgt;
1256 preallocated_vm_bo = drm_gpuvm_bo_create(&vm->base, &bo->base.base);
1257 if (!preallocated_vm_bo) {
1258 if (!bo->base.base.import_attach)
1259 drm_gem_shmem_unpin(&bo->base);
1265 /* drm_gpuvm_bo_obtain_prealloc() will call drm_gpuvm_bo_put() on our
1266 * pre-allocated BO if the <BO,VM> association exists. Given we
1267 * only have one ref on preallocated_vm_bo, drm_gpuvm_bo_destroy() will
1268 * be called immediately, and we have to hold the VM resv lock when
1269 * calling this function.
1271 dma_resv_lock(panthor_vm_resv(vm), NULL);
1272 mutex_lock(&bo->gpuva_list_lock);
1273 op_ctx->map.vm_bo = drm_gpuvm_bo_obtain_prealloc(preallocated_vm_bo);
1274 mutex_unlock(&bo->gpuva_list_lock);
1275 dma_resv_unlock(panthor_vm_resv(vm));
1277 /* If the a vm_bo for this <VM,BO> combination exists, it already
1278 * retains a pin ref, and we can release the one we took earlier.
1280 * If our pre-allocated vm_bo is picked, it now retains the pin ref,
1281 * which will be released in panthor_vm_bo_put().
1283 if (preallocated_vm_bo != op_ctx->map.vm_bo &&
1284 !bo->base.base.import_attach)
1285 drm_gem_shmem_unpin(&bo->base);
1287 op_ctx->map.bo_offset = offset;
1289 /* L1, L2 and L3 page tables.
1290 * We could optimize L3 allocation by iterating over the sgt and merging
1291 * 2M contiguous blocks, but it's simpler to over-provision and return
1292 * the pages if they're not used.
1294 pt_count = ((ALIGN(va + size, 1ull << 39) - ALIGN_DOWN(va, 1ull << 39)) >> 39) +
1295 ((ALIGN(va + size, 1ull << 30) - ALIGN_DOWN(va, 1ull << 30)) >> 30) +
1296 ((ALIGN(va + size, 1ull << 21) - ALIGN_DOWN(va, 1ull << 21)) >> 21);
1298 op_ctx->rsvd_page_tables.pages = kcalloc(pt_count,
1299 sizeof(*op_ctx->rsvd_page_tables.pages),
1301 if (!op_ctx->rsvd_page_tables.pages) {
1306 ret = kmem_cache_alloc_bulk(pt_cache, GFP_KERNEL, pt_count,
1307 op_ctx->rsvd_page_tables.pages);
1308 op_ctx->rsvd_page_tables.count = ret;
1309 if (ret != pt_count) {
1314 /* Insert BO into the extobj list last, when we know nothing can fail. */
1315 dma_resv_lock(panthor_vm_resv(vm), NULL);
1316 drm_gpuvm_bo_extobj_add(op_ctx->map.vm_bo);
1317 dma_resv_unlock(panthor_vm_resv(vm));
1322 panthor_vm_cleanup_op_ctx(op_ctx, vm);
1326 static int panthor_vm_prepare_unmap_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1327 struct panthor_vm *vm,
1333 memset(op_ctx, 0, sizeof(*op_ctx));
1334 INIT_LIST_HEAD(&op_ctx->returned_vmas);
1335 op_ctx->va.range = size;
1336 op_ctx->va.addr = va;
1337 op_ctx->flags = DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP;
1339 /* Pre-allocate L3 page tables to account for the split-2M-block
1340 * situation on unmap.
1342 if (va != ALIGN(va, SZ_2M))
1345 if (va + size != ALIGN(va + size, SZ_2M) &&
1346 ALIGN(va + size, SZ_2M) != ALIGN(va, SZ_2M))
1349 ret = panthor_vm_op_ctx_prealloc_vmas(op_ctx);
1354 op_ctx->rsvd_page_tables.pages = kcalloc(pt_count,
1355 sizeof(*op_ctx->rsvd_page_tables.pages),
1357 if (!op_ctx->rsvd_page_tables.pages) {
1362 ret = kmem_cache_alloc_bulk(pt_cache, GFP_KERNEL, pt_count,
1363 op_ctx->rsvd_page_tables.pages);
1364 if (ret != pt_count) {
1368 op_ctx->rsvd_page_tables.count = pt_count;
1374 panthor_vm_cleanup_op_ctx(op_ctx, vm);
1378 static void panthor_vm_prepare_sync_only_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1379 struct panthor_vm *vm)
1381 memset(op_ctx, 0, sizeof(*op_ctx));
1382 INIT_LIST_HEAD(&op_ctx->returned_vmas);
1383 op_ctx->flags = DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY;
1387 * panthor_vm_get_bo_for_va() - Get the GEM object mapped at a virtual address
1388 * @vm: VM to look into.
1389 * @va: Virtual address to search for.
1390 * @bo_offset: Offset of the GEM object mapped at this virtual address.
1391 * Only valid on success.
1393 * The object returned by this function might no longer be mapped when the
1394 * function returns. It's the caller responsibility to ensure there's no
1395 * concurrent map/unmap operations making the returned value invalid, or
1396 * make sure it doesn't matter if the object is no longer mapped.
1398 * Return: A valid pointer on success, an ERR_PTR() otherwise.
1400 struct panthor_gem_object *
1401 panthor_vm_get_bo_for_va(struct panthor_vm *vm, u64 va, u64 *bo_offset)
1403 struct panthor_gem_object *bo = ERR_PTR(-ENOENT);
1404 struct drm_gpuva *gpuva;
1405 struct panthor_vma *vma;
1407 /* Take the VM lock to prevent concurrent map/unmap operations. */
1408 mutex_lock(&vm->op_lock);
1409 gpuva = drm_gpuva_find_first(&vm->base, va, 1);
1410 vma = gpuva ? container_of(gpuva, struct panthor_vma, base) : NULL;
1411 if (vma && vma->base.gem.obj) {
1412 drm_gem_object_get(vma->base.gem.obj);
1413 bo = to_panthor_bo(vma->base.gem.obj);
1414 *bo_offset = vma->base.gem.offset + (va - vma->base.va.addr);
1416 mutex_unlock(&vm->op_lock);
1421 #define PANTHOR_VM_MIN_KERNEL_VA_SIZE SZ_256M
1424 panthor_vm_create_get_user_va_range(const struct drm_panthor_vm_create *args,
1429 /* Make sure we have a minimum amount of VA space for kernel objects. */
1430 if (full_va_range < PANTHOR_VM_MIN_KERNEL_VA_SIZE)
1433 if (args->user_va_range) {
1434 /* Use the user provided value if != 0. */
1435 user_va_range = args->user_va_range;
1436 } else if (TASK_SIZE_OF(current) < full_va_range) {
1437 /* If the task VM size is smaller than the GPU VA range, pick this
1438 * as our default user VA range, so userspace can CPU/GPU map buffers
1439 * at the same address.
1441 user_va_range = TASK_SIZE_OF(current);
1443 /* If the GPU VA range is smaller than the task VM size, we
1444 * just have to live with the fact we won't be able to map
1445 * all buffers at the same GPU/CPU address.
1447 * If the GPU VA range is bigger than 4G (more than 32-bit of
1448 * VA), we split the range in two, and assign half of it to
1449 * the user and the other half to the kernel, if it's not, we
1450 * keep the kernel VA space as small as possible.
1452 user_va_range = full_va_range > SZ_4G ?
1454 full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE;
1457 if (full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE < user_va_range)
1458 user_va_range = full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE;
1460 return user_va_range;
1463 #define PANTHOR_VM_CREATE_FLAGS 0
1466 panthor_vm_create_check_args(const struct panthor_device *ptdev,
1467 const struct drm_panthor_vm_create *args,
1468 u64 *kernel_va_start, u64 *kernel_va_range)
1470 u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
1471 u64 full_va_range = 1ull << va_bits;
1474 if (args->flags & ~PANTHOR_VM_CREATE_FLAGS)
1477 user_va_range = panthor_vm_create_get_user_va_range(args, full_va_range);
1478 if (!user_va_range || (args->user_va_range && args->user_va_range > user_va_range))
1481 /* Pick a kernel VA range that's a power of two, to have a clear split. */
1482 *kernel_va_range = rounddown_pow_of_two(full_va_range - user_va_range);
1483 *kernel_va_start = full_va_range - *kernel_va_range;
1488 * Only 32 VMs per open file. If that becomes a limiting factor, we can
1489 * increase this number.
1491 #define PANTHOR_MAX_VMS_PER_FILE 32
1494 * panthor_vm_pool_create_vm() - Create a VM
1495 * @pool: The VM to create this VM on.
1496 * @kernel_va_start: Start of the region reserved for kernel objects.
1497 * @kernel_va_range: Size of the region reserved for kernel objects.
1499 * Return: a positive VM ID on success, a negative error code otherwise.
1501 int panthor_vm_pool_create_vm(struct panthor_device *ptdev,
1502 struct panthor_vm_pool *pool,
1503 struct drm_panthor_vm_create *args)
1505 u64 kernel_va_start, kernel_va_range;
1506 struct panthor_vm *vm;
1510 ret = panthor_vm_create_check_args(ptdev, args, &kernel_va_start, &kernel_va_range);
1514 vm = panthor_vm_create(ptdev, false, kernel_va_start, kernel_va_range,
1515 kernel_va_start, kernel_va_range);
1519 ret = xa_alloc(&pool->xa, &id, vm,
1520 XA_LIMIT(1, PANTHOR_MAX_VMS_PER_FILE), GFP_KERNEL);
1527 args->user_va_range = kernel_va_start;
1531 static void panthor_vm_destroy(struct panthor_vm *vm)
1536 vm->destroyed = true;
1538 mutex_lock(&vm->heaps.lock);
1539 panthor_heap_pool_destroy(vm->heaps.pool);
1540 vm->heaps.pool = NULL;
1541 mutex_unlock(&vm->heaps.lock);
1543 drm_WARN_ON(&vm->ptdev->base,
1544 panthor_vm_unmap_range(vm, vm->base.mm_start, vm->base.mm_range));
1549 * panthor_vm_pool_destroy_vm() - Destroy a VM.
1551 * @handle: VM handle.
1553 * This function doesn't free the VM object or its resources, it just kills
1554 * all mappings, and makes sure nothing can be mapped after that point.
1556 * If there was any active jobs at the time this function is called, these
1557 * jobs should experience page faults and be killed as a result.
1559 * The VM resources are freed when the last reference on the VM object is
1562 int panthor_vm_pool_destroy_vm(struct panthor_vm_pool *pool, u32 handle)
1564 struct panthor_vm *vm;
1566 vm = xa_erase(&pool->xa, handle);
1568 panthor_vm_destroy(vm);
1570 return vm ? 0 : -EINVAL;
1574 * panthor_vm_pool_get_vm() - Retrieve VM object bound to a VM handle
1575 * @pool: VM pool to check.
1576 * @handle: Handle of the VM to retrieve.
1578 * Return: A valid pointer if the VM exists, NULL otherwise.
1581 panthor_vm_pool_get_vm(struct panthor_vm_pool *pool, u32 handle)
1583 struct panthor_vm *vm;
1586 vm = panthor_vm_get(xa_load(&pool->xa, handle));
1587 xa_unlock(&pool->xa);
1593 * panthor_vm_pool_destroy() - Destroy a VM pool.
1596 * Destroy all VMs in the pool, and release the pool resources.
1598 * Note that VMs can outlive the pool they were created from if other
1599 * objects hold a reference to there VMs.
1601 void panthor_vm_pool_destroy(struct panthor_file *pfile)
1603 struct panthor_vm *vm;
1609 xa_for_each(&pfile->vms->xa, i, vm)
1610 panthor_vm_destroy(vm);
1612 xa_destroy(&pfile->vms->xa);
1617 * panthor_vm_pool_create() - Create a VM pool
1620 * Return: 0 on success, a negative error code otherwise.
1622 int panthor_vm_pool_create(struct panthor_file *pfile)
1624 pfile->vms = kzalloc(sizeof(*pfile->vms), GFP_KERNEL);
1628 xa_init_flags(&pfile->vms->xa, XA_FLAGS_ALLOC1);
1632 /* dummy TLB ops, the real TLB flush happens in panthor_vm_flush_range() */
1633 static void mmu_tlb_flush_all(void *cookie)
1637 static void mmu_tlb_flush_walk(unsigned long iova, size_t size, size_t granule, void *cookie)
1641 static const struct iommu_flush_ops mmu_tlb_ops = {
1642 .tlb_flush_all = mmu_tlb_flush_all,
1643 .tlb_flush_walk = mmu_tlb_flush_walk,
1646 static const char *access_type_name(struct panthor_device *ptdev,
1649 switch (fault_status & AS_FAULTSTATUS_ACCESS_TYPE_MASK) {
1650 case AS_FAULTSTATUS_ACCESS_TYPE_ATOMIC:
1652 case AS_FAULTSTATUS_ACCESS_TYPE_READ:
1654 case AS_FAULTSTATUS_ACCESS_TYPE_WRITE:
1656 case AS_FAULTSTATUS_ACCESS_TYPE_EX:
1659 drm_WARN_ON(&ptdev->base, 1);
1664 static void panthor_mmu_irq_handler(struct panthor_device *ptdev, u32 status)
1666 bool has_unhandled_faults = false;
1668 status = panthor_mmu_fault_mask(ptdev, status);
1670 u32 as = ffs(status | (status >> 16)) - 1;
1671 u32 mask = panthor_mmu_as_fault_mask(ptdev, as);
1679 fault_status = gpu_read(ptdev, AS_FAULTSTATUS(as));
1680 addr = gpu_read(ptdev, AS_FAULTADDRESS_LO(as));
1681 addr |= (u64)gpu_read(ptdev, AS_FAULTADDRESS_HI(as)) << 32;
1683 /* decode the fault status */
1684 exception_type = fault_status & 0xFF;
1685 access_type = (fault_status >> 8) & 0x3;
1686 source_id = (fault_status >> 16);
1688 mutex_lock(&ptdev->mmu->as.slots_lock);
1690 ptdev->mmu->as.faulty_mask |= mask;
1692 panthor_mmu_fault_mask(ptdev, ~ptdev->mmu->as.faulty_mask);
1694 /* terminal fault, print info about the fault */
1695 drm_err(&ptdev->base,
1696 "Unhandled Page fault in AS%d at VA 0x%016llX\n"
1697 "raw fault status: 0x%X\n"
1698 "decoded fault status: %s\n"
1699 "exception type 0x%X: %s\n"
1700 "access type 0x%X: %s\n"
1704 (fault_status & (1 << 10) ? "DECODER FAULT" : "SLAVE FAULT"),
1705 exception_type, panthor_exception_name(ptdev, exception_type),
1706 access_type, access_type_name(ptdev, fault_status),
1709 /* Ignore MMU interrupts on this AS until it's been
1712 ptdev->mmu->irq.mask = new_int_mask;
1713 gpu_write(ptdev, MMU_INT_MASK, new_int_mask);
1715 if (ptdev->mmu->as.slots[as].vm)
1716 ptdev->mmu->as.slots[as].vm->unhandled_fault = true;
1718 /* Disable the MMU to kill jobs on this AS. */
1719 panthor_mmu_as_disable(ptdev, as);
1720 mutex_unlock(&ptdev->mmu->as.slots_lock);
1723 has_unhandled_faults = true;
1726 if (has_unhandled_faults)
1727 panthor_sched_report_mmu_fault(ptdev);
1729 PANTHOR_IRQ_HANDLER(mmu, MMU, panthor_mmu_irq_handler);
1732 * panthor_mmu_suspend() - Suspend the MMU logic
1735 * All we do here is de-assign the AS slots on all active VMs, so things
1736 * get flushed to the main memory, and no further access to these VMs are
1739 * We also suspend the MMU IRQ.
1741 void panthor_mmu_suspend(struct panthor_device *ptdev)
1743 mutex_lock(&ptdev->mmu->as.slots_lock);
1744 for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
1745 struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
1748 drm_WARN_ON(&ptdev->base, panthor_mmu_as_disable(ptdev, i));
1749 panthor_vm_release_as_locked(vm);
1752 mutex_unlock(&ptdev->mmu->as.slots_lock);
1754 panthor_mmu_irq_suspend(&ptdev->mmu->irq);
1758 * panthor_mmu_resume() - Resume the MMU logic
1763 * We don't re-enable previously active VMs. We assume other parts of the
1764 * driver will call panthor_vm_active() on the VMs they intend to use.
1766 void panthor_mmu_resume(struct panthor_device *ptdev)
1768 mutex_lock(&ptdev->mmu->as.slots_lock);
1769 ptdev->mmu->as.alloc_mask = 0;
1770 ptdev->mmu->as.faulty_mask = 0;
1771 mutex_unlock(&ptdev->mmu->as.slots_lock);
1773 panthor_mmu_irq_resume(&ptdev->mmu->irq, panthor_mmu_fault_mask(ptdev, ~0));
1777 * panthor_mmu_pre_reset() - Prepare for a reset
1780 * Suspend the IRQ, and make sure all VM_BIND queues are stopped, so we
1781 * don't get asked to do a VM operation while the GPU is down.
1783 * We don't cleanly shutdown the AS slots here, because the reset might
1784 * come from an AS_ACTIVE_BIT stuck situation.
1786 void panthor_mmu_pre_reset(struct panthor_device *ptdev)
1788 struct panthor_vm *vm;
1790 panthor_mmu_irq_suspend(&ptdev->mmu->irq);
1792 mutex_lock(&ptdev->mmu->vm.lock);
1793 ptdev->mmu->vm.reset_in_progress = true;
1794 list_for_each_entry(vm, &ptdev->mmu->vm.list, node)
1795 panthor_vm_stop(vm);
1796 mutex_unlock(&ptdev->mmu->vm.lock);
1800 * panthor_mmu_post_reset() - Restore things after a reset
1803 * Put the MMU logic back in action after a reset. That implies resuming the
1804 * IRQ and re-enabling the VM_BIND queues.
1806 void panthor_mmu_post_reset(struct panthor_device *ptdev)
1808 struct panthor_vm *vm;
1810 mutex_lock(&ptdev->mmu->as.slots_lock);
1812 /* Now that the reset is effective, we can assume that none of the
1813 * AS slots are setup, and clear the faulty flags too.
1815 ptdev->mmu->as.alloc_mask = 0;
1816 ptdev->mmu->as.faulty_mask = 0;
1818 for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
1819 struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
1822 panthor_vm_release_as_locked(vm);
1825 mutex_unlock(&ptdev->mmu->as.slots_lock);
1827 panthor_mmu_irq_resume(&ptdev->mmu->irq, panthor_mmu_fault_mask(ptdev, ~0));
1829 /* Restart the VM_BIND queues. */
1830 mutex_lock(&ptdev->mmu->vm.lock);
1831 list_for_each_entry(vm, &ptdev->mmu->vm.list, node) {
1832 panthor_vm_start(vm);
1834 ptdev->mmu->vm.reset_in_progress = false;
1835 mutex_unlock(&ptdev->mmu->vm.lock);
1838 static void panthor_vm_free(struct drm_gpuvm *gpuvm)
1840 struct panthor_vm *vm = container_of(gpuvm, struct panthor_vm, base);
1841 struct panthor_device *ptdev = vm->ptdev;
1843 mutex_lock(&vm->heaps.lock);
1844 if (drm_WARN_ON(&ptdev->base, vm->heaps.pool))
1845 panthor_heap_pool_destroy(vm->heaps.pool);
1846 mutex_unlock(&vm->heaps.lock);
1847 mutex_destroy(&vm->heaps.lock);
1849 mutex_lock(&ptdev->mmu->vm.lock);
1850 list_del(&vm->node);
1851 /* Restore the scheduler state so we can call drm_sched_entity_destroy()
1852 * and drm_sched_fini(). If get there, that means we have no job left
1853 * and no new jobs can be queued, so we can start the scheduler without
1854 * risking interfering with the reset.
1856 if (ptdev->mmu->vm.reset_in_progress)
1857 panthor_vm_start(vm);
1858 mutex_unlock(&ptdev->mmu->vm.lock);
1860 drm_sched_entity_destroy(&vm->entity);
1861 drm_sched_fini(&vm->sched);
1863 mutex_lock(&ptdev->mmu->as.slots_lock);
1864 if (vm->as.id >= 0) {
1867 if (drm_dev_enter(&ptdev->base, &cookie)) {
1868 panthor_mmu_as_disable(ptdev, vm->as.id);
1869 drm_dev_exit(cookie);
1872 ptdev->mmu->as.slots[vm->as.id].vm = NULL;
1873 clear_bit(vm->as.id, &ptdev->mmu->as.alloc_mask);
1874 list_del(&vm->as.lru_node);
1876 mutex_unlock(&ptdev->mmu->as.slots_lock);
1878 free_io_pgtable_ops(vm->pgtbl_ops);
1880 drm_mm_takedown(&vm->mm);
1885 * panthor_vm_put() - Release a reference on a VM
1886 * @vm: VM to release the reference on. Can be NULL.
1888 void panthor_vm_put(struct panthor_vm *vm)
1890 drm_gpuvm_put(vm ? &vm->base : NULL);
1894 * panthor_vm_get() - Get a VM reference
1895 * @vm: VM to get the reference on. Can be NULL.
1897 * Return: @vm value.
1899 struct panthor_vm *panthor_vm_get(struct panthor_vm *vm)
1902 drm_gpuvm_get(&vm->base);
1908 * panthor_vm_get_heap_pool() - Get the heap pool attached to a VM
1909 * @vm: VM to query the heap pool on.
1910 * @create: True if the heap pool should be created when it doesn't exist.
1912 * Heap pools are per-VM. This function allows one to retrieve the heap pool
1915 * If no heap pool exists yet, and @create is true, we create one.
1917 * The returned panthor_heap_pool should be released with panthor_heap_pool_put().
1919 * Return: A valid pointer on success, an ERR_PTR() otherwise.
1921 struct panthor_heap_pool *panthor_vm_get_heap_pool(struct panthor_vm *vm, bool create)
1923 struct panthor_heap_pool *pool;
1925 mutex_lock(&vm->heaps.lock);
1926 if (!vm->heaps.pool && create) {
1928 pool = ERR_PTR(-EINVAL);
1930 pool = panthor_heap_pool_create(vm->ptdev, vm);
1933 vm->heaps.pool = panthor_heap_pool_get(pool);
1935 pool = panthor_heap_pool_get(vm->heaps.pool);
1937 pool = ERR_PTR(-ENOENT);
1939 mutex_unlock(&vm->heaps.lock);
1944 static u64 mair_to_memattr(u64 mair, bool coherent)
1949 for (i = 0; i < 8; i++) {
1950 u8 in_attr = mair >> (8 * i), out_attr;
1951 u8 outer = in_attr >> 4, inner = in_attr & 0xf;
1953 /* For caching to be enabled, inner and outer caching policy
1954 * have to be both write-back, if one of them is write-through
1955 * or non-cacheable, we just choose non-cacheable. Device
1956 * memory is also translated to non-cacheable.
1958 if (!(outer & 3) || !(outer & 4) || !(inner & 4)) {
1959 out_attr = AS_MEMATTR_AARCH64_INNER_OUTER_NC |
1960 AS_MEMATTR_AARCH64_SH_MIDGARD_INNER |
1961 AS_MEMATTR_AARCH64_INNER_ALLOC_EXPL(false, false);
1963 out_attr = AS_MEMATTR_AARCH64_INNER_OUTER_WB |
1964 AS_MEMATTR_AARCH64_INNER_ALLOC_EXPL(inner & 1, inner & 2);
1965 /* Use SH_MIDGARD_INNER mode when device isn't coherent,
1966 * so SH_IS, which is used when IOMMU_CACHE is set, maps
1967 * to Mali's internal-shareable mode. As per the Mali
1968 * Spec, inner and outer-shareable modes aren't allowed
1969 * for WB memory when coherency is disabled.
1970 * Use SH_CPU_INNER mode when coherency is enabled, so
1971 * that SH_IS actually maps to the standard definition of
1975 out_attr |= AS_MEMATTR_AARCH64_SH_MIDGARD_INNER;
1977 out_attr |= AS_MEMATTR_AARCH64_SH_CPU_INNER;
1980 memattr |= (u64)out_attr << (8 * i);
1986 static void panthor_vma_link(struct panthor_vm *vm,
1987 struct panthor_vma *vma,
1988 struct drm_gpuvm_bo *vm_bo)
1990 struct panthor_gem_object *bo = to_panthor_bo(vma->base.gem.obj);
1992 mutex_lock(&bo->gpuva_list_lock);
1993 drm_gpuva_link(&vma->base, vm_bo);
1994 drm_WARN_ON(&vm->ptdev->base, drm_gpuvm_bo_put(vm_bo));
1995 mutex_unlock(&bo->gpuva_list_lock);
1998 static void panthor_vma_unlink(struct panthor_vm *vm,
1999 struct panthor_vma *vma)
2001 struct panthor_gem_object *bo = to_panthor_bo(vma->base.gem.obj);
2002 struct drm_gpuvm_bo *vm_bo = drm_gpuvm_bo_get(vma->base.vm_bo);
2004 mutex_lock(&bo->gpuva_list_lock);
2005 drm_gpuva_unlink(&vma->base);
2006 mutex_unlock(&bo->gpuva_list_lock);
2008 /* drm_gpuva_unlink() release the vm_bo, but we manually retained it
2009 * when entering this function, so we can implement deferred VMA
2010 * destruction. Re-assign it here.
2012 vma->base.vm_bo = vm_bo;
2013 list_add_tail(&vma->node, &vm->op_ctx->returned_vmas);
2016 static void panthor_vma_init(struct panthor_vma *vma, u32 flags)
2018 INIT_LIST_HEAD(&vma->node);
2022 #define PANTHOR_VM_MAP_FLAGS \
2023 (DRM_PANTHOR_VM_BIND_OP_MAP_READONLY | \
2024 DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC | \
2025 DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED)
2027 static int panthor_gpuva_sm_step_map(struct drm_gpuva_op *op, void *priv)
2029 struct panthor_vm *vm = priv;
2030 struct panthor_vm_op_ctx *op_ctx = vm->op_ctx;
2031 struct panthor_vma *vma = panthor_vm_op_ctx_get_vma(op_ctx);
2037 panthor_vma_init(vma, op_ctx->flags & PANTHOR_VM_MAP_FLAGS);
2039 ret = panthor_vm_map_pages(vm, op->map.va.addr, flags_to_prot(vma->flags),
2040 op_ctx->map.sgt, op->map.gem.offset,
2045 /* Ref owned by the mapping now, clear the obj field so we don't release the
2046 * pinning/obj ref behind GPUVA's back.
2048 drm_gpuva_map(&vm->base, &vma->base, &op->map);
2049 panthor_vma_link(vm, vma, op_ctx->map.vm_bo);
2050 op_ctx->map.vm_bo = NULL;
2054 static int panthor_gpuva_sm_step_remap(struct drm_gpuva_op *op,
2057 struct panthor_vma *unmap_vma = container_of(op->remap.unmap->va, struct panthor_vma, base);
2058 struct panthor_vm *vm = priv;
2059 struct panthor_vm_op_ctx *op_ctx = vm->op_ctx;
2060 struct panthor_vma *prev_vma = NULL, *next_vma = NULL;
2061 u64 unmap_start, unmap_range;
2064 drm_gpuva_op_remap_to_unmap_range(&op->remap, &unmap_start, &unmap_range);
2065 ret = panthor_vm_unmap_pages(vm, unmap_start, unmap_range);
2069 if (op->remap.prev) {
2070 prev_vma = panthor_vm_op_ctx_get_vma(op_ctx);
2071 panthor_vma_init(prev_vma, unmap_vma->flags);
2074 if (op->remap.next) {
2075 next_vma = panthor_vm_op_ctx_get_vma(op_ctx);
2076 panthor_vma_init(next_vma, unmap_vma->flags);
2079 drm_gpuva_remap(prev_vma ? &prev_vma->base : NULL,
2080 next_vma ? &next_vma->base : NULL,
2084 /* panthor_vma_link() transfers the vm_bo ownership to
2085 * the VMA object. Since the vm_bo we're passing is still
2086 * owned by the old mapping which will be released when this
2087 * mapping is destroyed, we need to grab a ref here.
2089 panthor_vma_link(vm, prev_vma,
2090 drm_gpuvm_bo_get(op->remap.unmap->va->vm_bo));
2094 panthor_vma_link(vm, next_vma,
2095 drm_gpuvm_bo_get(op->remap.unmap->va->vm_bo));
2098 panthor_vma_unlink(vm, unmap_vma);
2102 static int panthor_gpuva_sm_step_unmap(struct drm_gpuva_op *op,
2105 struct panthor_vma *unmap_vma = container_of(op->unmap.va, struct panthor_vma, base);
2106 struct panthor_vm *vm = priv;
2109 ret = panthor_vm_unmap_pages(vm, unmap_vma->base.va.addr,
2110 unmap_vma->base.va.range);
2111 if (drm_WARN_ON(&vm->ptdev->base, ret))
2114 drm_gpuva_unmap(&op->unmap);
2115 panthor_vma_unlink(vm, unmap_vma);
2119 static const struct drm_gpuvm_ops panthor_gpuvm_ops = {
2120 .vm_free = panthor_vm_free,
2121 .sm_step_map = panthor_gpuva_sm_step_map,
2122 .sm_step_remap = panthor_gpuva_sm_step_remap,
2123 .sm_step_unmap = panthor_gpuva_sm_step_unmap,
2127 * panthor_vm_resv() - Get the dma_resv object attached to a VM.
2128 * @vm: VM to get the dma_resv of.
2130 * Return: A dma_resv object.
2132 struct dma_resv *panthor_vm_resv(struct panthor_vm *vm)
2134 return drm_gpuvm_resv(&vm->base);
2137 struct drm_gem_object *panthor_vm_root_gem(struct panthor_vm *vm)
2142 return vm->base.r_obj;
2146 panthor_vm_exec_op(struct panthor_vm *vm, struct panthor_vm_op_ctx *op,
2147 bool flag_vm_unusable_on_failure)
2149 u32 op_type = op->flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK;
2152 if (op_type == DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY)
2155 mutex_lock(&vm->op_lock);
2158 case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP:
2164 ret = drm_gpuvm_sm_map(&vm->base, vm, op->va.addr, op->va.range,
2165 op->map.vm_bo->obj, op->map.bo_offset);
2168 case DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP:
2169 ret = drm_gpuvm_sm_unmap(&vm->base, vm, op->va.addr, op->va.range);
2177 if (ret && flag_vm_unusable_on_failure)
2178 vm->unusable = true;
2181 mutex_unlock(&vm->op_lock);
2186 static struct dma_fence *
2187 panthor_vm_bind_run_job(struct drm_sched_job *sched_job)
2189 struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2193 /* Not only we report an error whose result is propagated to the
2194 * drm_sched finished fence, but we also flag the VM as unusable, because
2195 * a failure in the async VM_BIND results in an inconsistent state. VM needs
2196 * to be destroyed and recreated.
2198 cookie = dma_fence_begin_signalling();
2199 ret = panthor_vm_exec_op(job->vm, &job->ctx, true);
2200 dma_fence_end_signalling(cookie);
2202 return ret ? ERR_PTR(ret) : NULL;
2205 static void panthor_vm_bind_job_release(struct kref *kref)
2207 struct panthor_vm_bind_job *job = container_of(kref, struct panthor_vm_bind_job, refcount);
2209 if (job->base.s_fence)
2210 drm_sched_job_cleanup(&job->base);
2212 panthor_vm_cleanup_op_ctx(&job->ctx, job->vm);
2213 panthor_vm_put(job->vm);
2218 * panthor_vm_bind_job_put() - Release a VM_BIND job reference
2219 * @sched_job: Job to release the reference on.
2221 void panthor_vm_bind_job_put(struct drm_sched_job *sched_job)
2223 struct panthor_vm_bind_job *job =
2224 container_of(sched_job, struct panthor_vm_bind_job, base);
2227 kref_put(&job->refcount, panthor_vm_bind_job_release);
2231 panthor_vm_bind_free_job(struct drm_sched_job *sched_job)
2233 struct panthor_vm_bind_job *job =
2234 container_of(sched_job, struct panthor_vm_bind_job, base);
2236 drm_sched_job_cleanup(sched_job);
2238 /* Do the heavy cleanups asynchronously, so we're out of the
2239 * dma-signaling path and can acquire dma-resv locks safely.
2241 queue_work(panthor_cleanup_wq, &job->cleanup_op_ctx_work);
2244 static enum drm_gpu_sched_stat
2245 panthor_vm_bind_timedout_job(struct drm_sched_job *sched_job)
2247 WARN(1, "VM_BIND ops are synchronous for now, there should be no timeout!");
2248 return DRM_GPU_SCHED_STAT_NOMINAL;
2251 static const struct drm_sched_backend_ops panthor_vm_bind_ops = {
2252 .run_job = panthor_vm_bind_run_job,
2253 .free_job = panthor_vm_bind_free_job,
2254 .timedout_job = panthor_vm_bind_timedout_job,
2258 * panthor_vm_create() - Create a VM
2260 * @for_mcu: True if this is the FW MCU VM.
2261 * @kernel_va_start: Start of the range reserved for kernel BO mapping.
2262 * @kernel_va_size: Size of the range reserved for kernel BO mapping.
2263 * @auto_kernel_va_start: Start of the auto-VA kernel range.
2264 * @auto_kernel_va_size: Size of the auto-VA kernel range.
2266 * Return: A valid pointer on success, an ERR_PTR() otherwise.
2269 panthor_vm_create(struct panthor_device *ptdev, bool for_mcu,
2270 u64 kernel_va_start, u64 kernel_va_size,
2271 u64 auto_kernel_va_start, u64 auto_kernel_va_size)
2273 u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
2274 u32 pa_bits = GPU_MMU_FEATURES_PA_BITS(ptdev->gpu_info.mmu_features);
2275 u64 full_va_range = 1ull << va_bits;
2276 struct drm_gem_object *dummy_gem;
2277 struct drm_gpu_scheduler *sched;
2278 struct io_pgtable_cfg pgtbl_cfg;
2279 u64 mair, min_va, va_range;
2280 struct panthor_vm *vm;
2283 vm = kzalloc(sizeof(*vm), GFP_KERNEL);
2285 return ERR_PTR(-ENOMEM);
2287 /* We allocate a dummy GEM for the VM. */
2288 dummy_gem = drm_gpuvm_resv_object_alloc(&ptdev->base);
2294 mutex_init(&vm->heaps.lock);
2295 vm->for_mcu = for_mcu;
2297 mutex_init(&vm->op_lock);
2300 /* CSF MCU is a cortex M7, and can only address 4G */
2305 va_range = full_va_range;
2308 mutex_init(&vm->mm_lock);
2309 drm_mm_init(&vm->mm, kernel_va_start, kernel_va_size);
2310 vm->kernel_auto_va.start = auto_kernel_va_start;
2311 vm->kernel_auto_va.end = vm->kernel_auto_va.start + auto_kernel_va_size - 1;
2313 INIT_LIST_HEAD(&vm->node);
2314 INIT_LIST_HEAD(&vm->as.lru_node);
2316 refcount_set(&vm->as.active_cnt, 0);
2318 pgtbl_cfg = (struct io_pgtable_cfg) {
2319 .pgsize_bitmap = SZ_4K | SZ_2M,
2322 .coherent_walk = ptdev->coherent,
2323 .tlb = &mmu_tlb_ops,
2324 .iommu_dev = ptdev->base.dev,
2329 vm->pgtbl_ops = alloc_io_pgtable_ops(ARM_64_LPAE_S1, &pgtbl_cfg, vm);
2330 if (!vm->pgtbl_ops) {
2332 goto err_mm_takedown;
2335 /* Bind operations are synchronous for now, no timeout needed. */
2336 ret = drm_sched_init(&vm->sched, &panthor_vm_bind_ops, ptdev->mmu->vm.wq,
2338 MAX_SCHEDULE_TIMEOUT, NULL, NULL,
2339 "panthor-vm-bind", ptdev->base.dev);
2341 goto err_free_io_pgtable;
2344 ret = drm_sched_entity_init(&vm->entity, 0, &sched, 1, NULL);
2346 goto err_sched_fini;
2348 mair = io_pgtable_ops_to_pgtable(vm->pgtbl_ops)->cfg.arm_lpae_s1_cfg.mair;
2349 vm->memattr = mair_to_memattr(mair, ptdev->coherent);
2351 mutex_lock(&ptdev->mmu->vm.lock);
2352 list_add_tail(&vm->node, &ptdev->mmu->vm.list);
2354 /* If a reset is in progress, stop the scheduler. */
2355 if (ptdev->mmu->vm.reset_in_progress)
2356 panthor_vm_stop(vm);
2357 mutex_unlock(&ptdev->mmu->vm.lock);
2359 /* We intentionally leave the reserved range to zero, because we want kernel VMAs
2360 * to be handled the same way user VMAs are.
2362 drm_gpuvm_init(&vm->base, for_mcu ? "panthor-MCU-VM" : "panthor-GPU-VM",
2363 DRM_GPUVM_RESV_PROTECTED, &ptdev->base, dummy_gem,
2364 min_va, va_range, 0, 0, &panthor_gpuvm_ops);
2365 drm_gem_object_put(dummy_gem);
2369 drm_sched_fini(&vm->sched);
2371 err_free_io_pgtable:
2372 free_io_pgtable_ops(vm->pgtbl_ops);
2375 drm_mm_takedown(&vm->mm);
2376 drm_gem_object_put(dummy_gem);
2380 return ERR_PTR(ret);
2384 panthor_vm_bind_prepare_op_ctx(struct drm_file *file,
2385 struct panthor_vm *vm,
2386 const struct drm_panthor_vm_bind_op *op,
2387 struct panthor_vm_op_ctx *op_ctx)
2389 ssize_t vm_pgsz = panthor_vm_page_size(vm);
2390 struct drm_gem_object *gem;
2393 /* Aligned on page size. */
2394 if (!IS_ALIGNED(op->va | op->size, vm_pgsz))
2397 switch (op->flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK) {
2398 case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP:
2399 gem = drm_gem_object_lookup(file, op->bo_handle);
2400 ret = panthor_vm_prepare_map_op_ctx(op_ctx, vm,
2401 gem ? to_panthor_bo(gem) : NULL,
2406 drm_gem_object_put(gem);
2409 case DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP:
2410 if (op->flags & ~DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
2413 if (op->bo_handle || op->bo_offset)
2416 return panthor_vm_prepare_unmap_op_ctx(op_ctx, vm, op->va, op->size);
2418 case DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY:
2419 if (op->flags & ~DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
2422 if (op->bo_handle || op->bo_offset)
2425 if (op->va || op->size)
2428 if (!op->syncs.count)
2431 panthor_vm_prepare_sync_only_op_ctx(op_ctx, vm);
2439 static void panthor_vm_bind_job_cleanup_op_ctx_work(struct work_struct *work)
2441 struct panthor_vm_bind_job *job =
2442 container_of(work, struct panthor_vm_bind_job, cleanup_op_ctx_work);
2444 panthor_vm_bind_job_put(&job->base);
2448 * panthor_vm_bind_job_create() - Create a VM_BIND job
2450 * @vm: VM targeted by the VM_BIND job.
2451 * @op: VM operation data.
2453 * Return: A valid pointer on success, an ERR_PTR() otherwise.
2455 struct drm_sched_job *
2456 panthor_vm_bind_job_create(struct drm_file *file,
2457 struct panthor_vm *vm,
2458 const struct drm_panthor_vm_bind_op *op)
2460 struct panthor_vm_bind_job *job;
2464 return ERR_PTR(-EINVAL);
2466 if (vm->destroyed || vm->unusable)
2467 return ERR_PTR(-EINVAL);
2469 job = kzalloc(sizeof(*job), GFP_KERNEL);
2471 return ERR_PTR(-ENOMEM);
2473 ret = panthor_vm_bind_prepare_op_ctx(file, vm, op, &job->ctx);
2476 return ERR_PTR(ret);
2479 INIT_WORK(&job->cleanup_op_ctx_work, panthor_vm_bind_job_cleanup_op_ctx_work);
2480 kref_init(&job->refcount);
2481 job->vm = panthor_vm_get(vm);
2483 ret = drm_sched_job_init(&job->base, &vm->entity, 1, vm);
2490 panthor_vm_bind_job_put(&job->base);
2491 return ERR_PTR(ret);
2495 * panthor_vm_bind_job_prepare_resvs() - Prepare VM_BIND job dma_resvs
2496 * @exec: The locking/preparation context.
2497 * @sched_job: The job to prepare resvs on.
2499 * Locks and prepare the VM resv.
2501 * If this is a map operation, locks and prepares the GEM resv.
2503 * Return: 0 on success, a negative error code otherwise.
2505 int panthor_vm_bind_job_prepare_resvs(struct drm_exec *exec,
2506 struct drm_sched_job *sched_job)
2508 struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2511 /* Acquire the VM lock an reserve a slot for this VM bind job. */
2512 ret = drm_gpuvm_prepare_vm(&job->vm->base, exec, 1);
2516 if (job->ctx.map.vm_bo) {
2517 /* Lock/prepare the GEM being mapped. */
2518 ret = drm_exec_prepare_obj(exec, job->ctx.map.vm_bo->obj, 1);
2527 * panthor_vm_bind_job_update_resvs() - Update the resv objects touched by a job
2528 * @exec: drm_exec context.
2529 * @sched_job: Job to update the resvs on.
2531 void panthor_vm_bind_job_update_resvs(struct drm_exec *exec,
2532 struct drm_sched_job *sched_job)
2534 struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2536 /* Explicit sync => we just register our job finished fence as bookkeep. */
2537 drm_gpuvm_resv_add_fence(&job->vm->base, exec,
2538 &sched_job->s_fence->finished,
2539 DMA_RESV_USAGE_BOOKKEEP,
2540 DMA_RESV_USAGE_BOOKKEEP);
2543 void panthor_vm_update_resvs(struct panthor_vm *vm, struct drm_exec *exec,
2544 struct dma_fence *fence,
2545 enum dma_resv_usage private_usage,
2546 enum dma_resv_usage extobj_usage)
2548 drm_gpuvm_resv_add_fence(&vm->base, exec, fence, private_usage, extobj_usage);
2552 * panthor_vm_bind_exec_sync_op() - Execute a VM_BIND operation synchronously.
2554 * @vm: VM targeted by the VM operation.
2555 * @op: Data describing the VM operation.
2557 * Return: 0 on success, a negative error code otherwise.
2559 int panthor_vm_bind_exec_sync_op(struct drm_file *file,
2560 struct panthor_vm *vm,
2561 struct drm_panthor_vm_bind_op *op)
2563 struct panthor_vm_op_ctx op_ctx;
2566 /* No sync objects allowed on synchronous operations. */
2567 if (op->syncs.count)
2573 ret = panthor_vm_bind_prepare_op_ctx(file, vm, op, &op_ctx);
2577 ret = panthor_vm_exec_op(vm, &op_ctx, false);
2578 panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2584 * panthor_vm_map_bo_range() - Map a GEM object range to a VM
2585 * @vm: VM to map the GEM to.
2586 * @bo: GEM object to map.
2587 * @offset: Offset in the GEM object.
2588 * @size: Size to map.
2589 * @va: Virtual address to map the object to.
2590 * @flags: Combination of drm_panthor_vm_bind_op_flags flags.
2591 * Only map-related flags are valid.
2593 * Internal use only. For userspace requests, use
2594 * panthor_vm_bind_exec_sync_op() instead.
2596 * Return: 0 on success, a negative error code otherwise.
2598 int panthor_vm_map_bo_range(struct panthor_vm *vm, struct panthor_gem_object *bo,
2599 u64 offset, u64 size, u64 va, u32 flags)
2601 struct panthor_vm_op_ctx op_ctx;
2604 ret = panthor_vm_prepare_map_op_ctx(&op_ctx, vm, bo, offset, size, va, flags);
2608 ret = panthor_vm_exec_op(vm, &op_ctx, false);
2609 panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2615 * panthor_vm_unmap_range() - Unmap a portion of the VA space
2616 * @vm: VM to unmap the region from.
2617 * @va: Virtual address to unmap. Must be 4k aligned.
2618 * @size: Size of the region to unmap. Must be 4k aligned.
2620 * Internal use only. For userspace requests, use
2621 * panthor_vm_bind_exec_sync_op() instead.
2623 * Return: 0 on success, a negative error code otherwise.
2625 int panthor_vm_unmap_range(struct panthor_vm *vm, u64 va, u64 size)
2627 struct panthor_vm_op_ctx op_ctx;
2630 ret = panthor_vm_prepare_unmap_op_ctx(&op_ctx, vm, va, size);
2634 ret = panthor_vm_exec_op(vm, &op_ctx, false);
2635 panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2641 * panthor_vm_prepare_mapped_bos_resvs() - Prepare resvs on VM BOs.
2642 * @exec: Locking/preparation context.
2643 * @vm: VM targeted by the GPU job.
2644 * @slot_count: Number of slots to reserve.
2646 * GPU jobs assume all BOs bound to the VM at the time the job is submitted
2647 * are available when the job is executed. In order to guarantee that, we
2648 * need to reserve a slot on all BOs mapped to a VM and update this slot with
2649 * the job fence after its submission.
2651 * Return: 0 on success, a negative error code otherwise.
2653 int panthor_vm_prepare_mapped_bos_resvs(struct drm_exec *exec, struct panthor_vm *vm,
2658 /* Acquire the VM lock and reserve a slot for this GPU job. */
2659 ret = drm_gpuvm_prepare_vm(&vm->base, exec, slot_count);
2663 return drm_gpuvm_prepare_objects(&vm->base, exec, slot_count);
2667 * panthor_mmu_unplug() - Unplug the MMU logic
2670 * No access to the MMU regs should be done after this function is called.
2671 * We suspend the IRQ and disable all VMs to guarantee that.
2673 void panthor_mmu_unplug(struct panthor_device *ptdev)
2675 if (!IS_ENABLED(CONFIG_PM) || pm_runtime_active(ptdev->base.dev))
2676 panthor_mmu_irq_suspend(&ptdev->mmu->irq);
2678 mutex_lock(&ptdev->mmu->as.slots_lock);
2679 for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
2680 struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
2683 drm_WARN_ON(&ptdev->base, panthor_mmu_as_disable(ptdev, i));
2684 panthor_vm_release_as_locked(vm);
2687 mutex_unlock(&ptdev->mmu->as.slots_lock);
2690 static void panthor_mmu_release_wq(struct drm_device *ddev, void *res)
2692 destroy_workqueue(res);
2696 * panthor_mmu_init() - Initialize the MMU logic.
2699 * Return: 0 on success, a negative error code otherwise.
2701 int panthor_mmu_init(struct panthor_device *ptdev)
2703 u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
2704 struct panthor_mmu *mmu;
2707 mmu = drmm_kzalloc(&ptdev->base, sizeof(*mmu), GFP_KERNEL);
2711 INIT_LIST_HEAD(&mmu->as.lru_list);
2713 ret = drmm_mutex_init(&ptdev->base, &mmu->as.slots_lock);
2717 INIT_LIST_HEAD(&mmu->vm.list);
2718 ret = drmm_mutex_init(&ptdev->base, &mmu->vm.lock);
2724 irq = platform_get_irq_byname(to_platform_device(ptdev->base.dev), "mmu");
2728 ret = panthor_request_mmu_irq(ptdev, &mmu->irq, irq,
2729 panthor_mmu_fault_mask(ptdev, ~0));
2733 mmu->vm.wq = alloc_workqueue("panthor-vm-bind", WQ_UNBOUND, 0);
2737 /* On 32-bit kernels, the VA space is limited by the io_pgtable_ops abstraction,
2738 * which passes iova as an unsigned long. Patch the mmu_features to reflect this
2741 if (va_bits > BITS_PER_LONG) {
2742 ptdev->gpu_info.mmu_features &= ~GENMASK(7, 0);
2743 ptdev->gpu_info.mmu_features |= BITS_PER_LONG;
2746 return drmm_add_action_or_reset(&ptdev->base, panthor_mmu_release_wq, mmu->vm.wq);
2749 #ifdef CONFIG_DEBUG_FS
2750 static int show_vm_gpuvas(struct panthor_vm *vm, struct seq_file *m)
2754 mutex_lock(&vm->op_lock);
2755 ret = drm_debugfs_gpuva_info(m, &vm->base);
2756 mutex_unlock(&vm->op_lock);
2761 static int show_each_vm(struct seq_file *m, void *arg)
2763 struct drm_info_node *node = (struct drm_info_node *)m->private;
2764 struct drm_device *ddev = node->minor->dev;
2765 struct panthor_device *ptdev = container_of(ddev, struct panthor_device, base);
2766 int (*show)(struct panthor_vm *, struct seq_file *) = node->info_ent->data;
2767 struct panthor_vm *vm;
2770 mutex_lock(&ptdev->mmu->vm.lock);
2771 list_for_each_entry(vm, &ptdev->mmu->vm.list, node) {
2778 mutex_unlock(&ptdev->mmu->vm.lock);
2783 static struct drm_info_list panthor_mmu_debugfs_list[] = {
2784 DRM_DEBUGFS_GPUVA_INFO(show_each_vm, show_vm_gpuvas),
2788 * panthor_mmu_debugfs_init() - Initialize MMU debugfs entries
2791 void panthor_mmu_debugfs_init(struct drm_minor *minor)
2793 drm_debugfs_create_files(panthor_mmu_debugfs_list,
2794 ARRAY_SIZE(panthor_mmu_debugfs_list),
2795 minor->debugfs_root, minor);
2797 #endif /* CONFIG_DEBUG_FS */
2800 * panthor_mmu_pt_cache_init() - Initialize the page table cache.
2802 * Return: 0 on success, a negative error code otherwise.
2804 int panthor_mmu_pt_cache_init(void)
2806 pt_cache = kmem_cache_create("panthor-mmu-pt", SZ_4K, SZ_4K, 0, NULL);
2814 * panthor_mmu_pt_cache_fini() - Destroy the page table cache.
2816 void panthor_mmu_pt_cache_fini(void)
2818 kmem_cache_destroy(pt_cache);