xref: /linux/drivers/gpu/drm/panthor/panthor_mmu.c (revision 955abe0a1b41de5ba61fe4cd614ebc123084d499)
1 // SPDX-License-Identifier: GPL-2.0 or MIT
2 /* Copyright 2019 Linaro, Ltd, Rob Herring <robh@kernel.org> */
3 /* Copyright 2023 Collabora ltd. */
4 
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>
12 
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>
18 #include <linux/io.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>
29 
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"
36 
37 #define MAX_AS_SLOTS			32
38 
39 struct panthor_vm;
40 
41 /**
42  * struct panthor_as_slot - Address space slot
43  */
44 struct panthor_as_slot {
45 	/** @vm: VM bound to this slot. NULL is no VM is bound. */
46 	struct panthor_vm *vm;
47 };
48 
49 /**
50  * struct panthor_mmu - MMU related data
51  */
52 struct panthor_mmu {
53 	/** @irq: The MMU irq. */
54 	struct panthor_irq irq;
55 
56 	/** @as: Address space related fields.
57 	 *
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.
60 	 */
61 	struct {
62 		/** @slots_lock: Lock protecting access to all other AS fields. */
63 		struct mutex slots_lock;
64 
65 		/** @alloc_mask: Bitmask encoding the allocated slots. */
66 		unsigned long alloc_mask;
67 
68 		/** @faulty_mask: Bitmask encoding the faulty slots. */
69 		unsigned long faulty_mask;
70 
71 		/** @slots: VMs currently bound to the AS slots. */
72 		struct panthor_as_slot slots[MAX_AS_SLOTS];
73 
74 		/**
75 		 * @lru_list: List of least recently used VMs.
76 		 *
77 		 * We use this list to pick a VM to evict when all slots are
78 		 * used.
79 		 *
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
83 		 * flushes.
84 		 */
85 		struct list_head lru_list;
86 	} as;
87 
88 	/** @vm: VMs management fields */
89 	struct {
90 		/** @lock: Lock protecting access to list. */
91 		struct mutex lock;
92 
93 		/** @list: List containing all VMs. */
94 		struct list_head list;
95 
96 		/** @reset_in_progress: True if a reset is in progress. */
97 		bool reset_in_progress;
98 
99 		/** @wq: Workqueue used for the VM_BIND queues. */
100 		struct workqueue_struct *wq;
101 	} vm;
102 };
103 
104 /**
105  * struct panthor_vm_pool - VM pool object
106  */
107 struct panthor_vm_pool {
108 	/** @xa: Array used for VM handle tracking. */
109 	struct xarray xa;
110 };
111 
112 /**
113  * struct panthor_vma - GPU mapping object
114  *
115  * This is used to track GEM mappings in GPU space.
116  */
117 struct panthor_vma {
118 	/** @base: Inherits from drm_gpuva. */
119 	struct drm_gpuva base;
120 
121 	/** @node: Used to implement deferred release of VMAs. */
122 	struct list_head node;
123 
124 	/**
125 	 * @flags: Combination of drm_panthor_vm_bind_op_flags.
126 	 *
127 	 * Only map related flags are accepted.
128 	 */
129 	u32 flags;
130 };
131 
132 /**
133  * struct panthor_vm_op_ctx - VM operation context
134  *
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.
138  *
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
141  * request.
142  */
143 struct panthor_vm_op_ctx {
144 	/** @rsvd_page_tables: Pages reserved for the MMU page table update. */
145 	struct {
146 		/** @count: Number of pages reserved. */
147 		u32 count;
148 
149 		/** @ptr: Point to the first unused page in the @pages table. */
150 		u32 ptr;
151 
152 		/**
153 		 * @page: Array of pages that can be used for an MMU page table update.
154 		 *
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.
157 		 */
158 		void **pages;
159 	} rsvd_page_tables;
160 
161 	/**
162 	 * @preallocated_vmas: Pre-allocated VMAs to handle the remap case.
163 	 *
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).
167 	 */
168 	struct panthor_vma *preallocated_vmas[3];
169 
170 	/** @flags: Combination of drm_panthor_vm_bind_op_flags. */
171 	u32 flags;
172 
173 	/** @va: Virtual range targeted by the VM operation. */
174 	struct {
175 		/** @addr: Start address. */
176 		u64 addr;
177 
178 		/** @range: Range size. */
179 		u64 range;
180 	} va;
181 
182 	/**
183 	 * @returned_vmas: List of panthor_vma objects returned after a VM operation.
184 	 *
185 	 * For unmap operations, this will contain all VMAs that were covered by the
186 	 * specified VA range.
187 	 *
188 	 * For map operations, this will contain all VMAs that previously mapped to
189 	 * the specified VA range.
190 	 *
191 	 * Those VMAs, and the resources they point to will be released as part of
192 	 * the op_ctx cleanup operation.
193 	 */
194 	struct list_head returned_vmas;
195 
196 	/** @map: Fields specific to a map operation. */
197 	struct {
198 		/** @vm_bo: Buffer object to map. */
199 		struct drm_gpuvm_bo *vm_bo;
200 
201 		/** @bo_offset: Offset in the buffer object. */
202 		u64 bo_offset;
203 
204 		/**
205 		 * @sgt: sg-table pointing to pages backing the GEM object.
206 		 *
207 		 * This is gathered at job creation time, such that we don't have
208 		 * to allocate in ::run_job().
209 		 */
210 		struct sg_table *sgt;
211 
212 		/**
213 		 * @new_vma: The new VMA object that will be inserted to the VA tree.
214 		 */
215 		struct panthor_vma *new_vma;
216 	} map;
217 };
218 
219 /**
220  * struct panthor_vm - VM object
221  *
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
225  * the VM.
226  *
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.
230  *
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
234  * by default).
235  */
236 struct panthor_vm {
237 	/**
238 	 * @base: Inherit from drm_gpuvm.
239 	 *
240 	 * We delegate all the VA management to the common drm_gpuvm framework
241 	 * and only implement hooks to update the MMU page table.
242 	 */
243 	struct drm_gpuvm base;
244 
245 	/**
246 	 * @sched: Scheduler used for asynchronous VM_BIND request.
247 	 *
248 	 * We use a 1:1 scheduler here.
249 	 */
250 	struct drm_gpu_scheduler sched;
251 
252 	/**
253 	 * @entity: Scheduling entity representing the VM_BIND queue.
254 	 *
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.
257 	 */
258 	struct drm_sched_entity entity;
259 
260 	/** @ptdev: Device. */
261 	struct panthor_device *ptdev;
262 
263 	/** @memattr: Value to program to the AS_MEMATTR register. */
264 	u64 memattr;
265 
266 	/** @pgtbl_ops: Page table operations. */
267 	struct io_pgtable_ops *pgtbl_ops;
268 
269 	/** @root_page_table: Stores the root page table pointer. */
270 	void *root_page_table;
271 
272 	/**
273 	 * @op_lock: Lock used to serialize operations on a VM.
274 	 *
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.
278 	 */
279 	struct mutex op_lock;
280 
281 	/**
282 	 * @op_ctx: The context attached to the currently executing VM operation.
283 	 *
284 	 * NULL when no operation is in progress.
285 	 */
286 	struct panthor_vm_op_ctx *op_ctx;
287 
288 	/**
289 	 * @mm: Memory management object representing the auto-VA/kernel-VA.
290 	 *
291 	 * Used to auto-allocate VA space for kernel-managed objects (tiler
292 	 * heaps, ...).
293 	 *
294 	 * For the MCU VM, this is managing the VA range that's used to map
295 	 * all shared interfaces.
296 	 *
297 	 * For user VMs, the range is specified by userspace, and must not
298 	 * exceed half of the VA space addressable.
299 	 */
300 	struct drm_mm mm;
301 
302 	/** @mm_lock: Lock protecting the @mm field. */
303 	struct mutex mm_lock;
304 
305 	/** @kernel_auto_va: Automatic VA-range for kernel BOs. */
306 	struct {
307 		/** @start: Start of the automatic VA-range for kernel BOs. */
308 		u64 start;
309 
310 		/** @size: Size of the automatic VA-range for kernel BOs. */
311 		u64 end;
312 	} kernel_auto_va;
313 
314 	/** @as: Address space related fields. */
315 	struct {
316 		/**
317 		 * @id: ID of the address space this VM is bound to.
318 		 *
319 		 * A value of -1 means the VM is inactive/not bound.
320 		 */
321 		int id;
322 
323 		/** @active_cnt: Number of active users of this VM. */
324 		refcount_t active_cnt;
325 
326 		/**
327 		 * @lru_node: Used to instead the VM in the panthor_mmu::as::lru_list.
328 		 *
329 		 * Active VMs should not be inserted in the LRU list.
330 		 */
331 		struct list_head lru_node;
332 	} as;
333 
334 	/**
335 	 * @heaps: Tiler heap related fields.
336 	 */
337 	struct {
338 		/**
339 		 * @pool: The heap pool attached to this VM.
340 		 *
341 		 * Will stay NULL until someone creates a heap context on this VM.
342 		 */
343 		struct panthor_heap_pool *pool;
344 
345 		/** @lock: Lock used to protect access to @pool. */
346 		struct mutex lock;
347 	} heaps;
348 
349 	/** @node: Used to insert the VM in the panthor_mmu::vm::list. */
350 	struct list_head node;
351 
352 	/** @for_mcu: True if this is the MCU VM. */
353 	bool for_mcu;
354 
355 	/**
356 	 * @destroyed: True if the VM was destroyed.
357 	 *
358 	 * No further bind requests should be queued to a destroyed VM.
359 	 */
360 	bool destroyed;
361 
362 	/**
363 	 * @unusable: True if the VM has turned unusable because something
364 	 * bad happened during an asynchronous request.
365 	 *
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.
370 	 *
371 	 * Instead, we should just flag the VM as unusable, and fail any
372 	 * further request targeting this VM.
373 	 *
374 	 * We also provide a way to query a VM state, so userspace can destroy
375 	 * it and create a new one.
376 	 *
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.
379 	 */
380 	bool unusable;
381 
382 	/**
383 	 * @unhandled_fault: Unhandled fault happened.
384 	 *
385 	 * This should be reported to the scheduler, and the queue/group be
386 	 * flagged as faulty as a result.
387 	 */
388 	bool unhandled_fault;
389 };
390 
391 /**
392  * struct panthor_vm_bind_job - VM bind job
393  */
394 struct panthor_vm_bind_job {
395 	/** @base: Inherit from drm_sched_job. */
396 	struct drm_sched_job base;
397 
398 	/** @refcount: Reference count. */
399 	struct kref refcount;
400 
401 	/** @cleanup_op_ctx_work: Work used to cleanup the VM operation context. */
402 	struct work_struct cleanup_op_ctx_work;
403 
404 	/** @vm: VM targeted by the VM operation. */
405 	struct panthor_vm *vm;
406 
407 	/** @ctx: Operation context. */
408 	struct panthor_vm_op_ctx ctx;
409 };
410 
411 /**
412  * @pt_cache: Cache used to allocate MMU page tables.
413  *
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.
416  *
417  * Having a kmem_cache allows us to speed allocations.
418  */
419 static struct kmem_cache *pt_cache;
420 
421 /**
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.
426  * @gfp: GFP flags.
427  *
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.
431  *
432  * Return: non-NULL on success, NULL if the allocation failed for any
433  * reason.
434  */
435 static void *alloc_pt(void *cookie, size_t size, gfp_t gfp)
436 {
437 	struct panthor_vm *vm = cookie;
438 	void *page;
439 
440 	/* Allocation of the root page table happening during init. */
441 	if (unlikely(!vm->root_page_table)) {
442 		struct page *p;
443 
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;
449 		return page;
450 	}
451 
452 	/* We're not supposed to have anything bigger than 4k here, because we picked a
453 	 * 4k granule size at init time.
454 	 */
455 	if (drm_WARN_ON(&vm->ptdev->base, size != SZ_4K))
456 		return NULL;
457 
458 	/* We must have some op_ctx attached to the VM and it must have at least one
459 	 * free page.
460 	 */
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))
464 		return NULL;
465 
466 	page = vm->op_ctx->rsvd_page_tables.pages[vm->op_ctx->rsvd_page_tables.ptr++];
467 	memset(page, 0, SZ_4K);
468 
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
472 	 * either.
473 	 *
474 	 * Let's just ignore memory passed to the page-table driver for now.
475 	 */
476 	kmemleak_ignore(page);
477 	return page;
478 }
479 
480 /**
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.
486  */
487 static void free_pt(void *cookie, void *data, size_t size)
488 {
489 	struct panthor_vm *vm = cookie;
490 
491 	if (unlikely(vm->root_page_table == data)) {
492 		free_pages((unsigned long)data, get_order(size));
493 		vm->root_page_table = NULL;
494 		return;
495 	}
496 
497 	if (drm_WARN_ON(&vm->ptdev->base, size != SZ_4K))
498 		return;
499 
500 	/* Return the page to the pt_cache. */
501 	kmem_cache_free(pt_cache, data);
502 }
503 
504 static int wait_ready(struct panthor_device *ptdev, u32 as_nr)
505 {
506 	int ret;
507 	u32 val;
508 
509 	/* Wait for the MMU status to indicate there is no active command, in
510 	 * case one is pending.
511 	 */
512 	ret = readl_relaxed_poll_timeout_atomic(ptdev->iomem + AS_STATUS(as_nr),
513 						val, !(val & AS_STATUS_AS_ACTIVE),
514 						10, 100000);
515 
516 	if (ret) {
517 		panthor_device_schedule_reset(ptdev);
518 		drm_err(&ptdev->base, "AS_ACTIVE bit stuck\n");
519 	}
520 
521 	return ret;
522 }
523 
524 static int write_cmd(struct panthor_device *ptdev, u32 as_nr, u32 cmd)
525 {
526 	int status;
527 
528 	/* write AS_COMMAND when MMU is ready to accept another command */
529 	status = wait_ready(ptdev, as_nr);
530 	if (!status)
531 		gpu_write(ptdev, AS_COMMAND(as_nr), cmd);
532 
533 	return status;
534 }
535 
536 static void lock_region(struct panthor_device *ptdev, u32 as_nr,
537 			u64 region_start, u64 size)
538 {
539 	u8 region_width;
540 	u64 region;
541 	u64 region_end = region_start + size;
542 
543 	if (!size)
544 		return;
545 
546 	/*
547 	 * The locked region is a naturally aligned power of 2 block encoded as
548 	 * log2 minus(1).
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.
553 	 */
554 	region_width = max(fls64(region_start ^ (region_end - 1)),
555 			   const_ilog2(AS_LOCK_REGION_MIN_SIZE)) - 1;
556 
557 	/*
558 	 * Mask off the low bits of region_start (which would be ignored by
559 	 * the hardware anyway)
560 	 */
561 	region_start &= GENMASK_ULL(63, region_width);
562 
563 	region = region_width | region_start;
564 
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);
569 }
570 
571 static int mmu_hw_do_operation_locked(struct panthor_device *ptdev, int as_nr,
572 				      u64 iova, u64 size, u32 op)
573 {
574 	lockdep_assert_held(&ptdev->mmu->as.slots_lock);
575 
576 	if (as_nr < 0)
577 		return 0;
578 
579 	if (op != AS_COMMAND_UNLOCK)
580 		lock_region(ptdev, as_nr, iova, size);
581 
582 	/* Run the MMU operation */
583 	write_cmd(ptdev, as_nr, op);
584 
585 	/* Wait for the flush to complete */
586 	return wait_ready(ptdev, as_nr);
587 }
588 
589 static int mmu_hw_do_operation(struct panthor_vm *vm,
590 			       u64 iova, u64 size, u32 op)
591 {
592 	struct panthor_device *ptdev = vm->ptdev;
593 	int ret;
594 
595 	mutex_lock(&ptdev->mmu->as.slots_lock);
596 	ret = mmu_hw_do_operation_locked(ptdev, vm->as.id, iova, size, op);
597 	mutex_unlock(&ptdev->mmu->as.slots_lock);
598 
599 	return ret;
600 }
601 
602 static int panthor_mmu_as_enable(struct panthor_device *ptdev, u32 as_nr,
603 				 u64 transtab, u64 transcfg, u64 memattr)
604 {
605 	int ret;
606 
607 	ret = mmu_hw_do_operation_locked(ptdev, as_nr, 0, ~0ULL, AS_COMMAND_FLUSH_MEM);
608 	if (ret)
609 		return ret;
610 
611 	gpu_write(ptdev, AS_TRANSTAB_LO(as_nr), lower_32_bits(transtab));
612 	gpu_write(ptdev, AS_TRANSTAB_HI(as_nr), upper_32_bits(transtab));
613 
614 	gpu_write(ptdev, AS_MEMATTR_LO(as_nr), lower_32_bits(memattr));
615 	gpu_write(ptdev, AS_MEMATTR_HI(as_nr), upper_32_bits(memattr));
616 
617 	gpu_write(ptdev, AS_TRANSCFG_LO(as_nr), lower_32_bits(transcfg));
618 	gpu_write(ptdev, AS_TRANSCFG_HI(as_nr), upper_32_bits(transcfg));
619 
620 	return write_cmd(ptdev, as_nr, AS_COMMAND_UPDATE);
621 }
622 
623 static int panthor_mmu_as_disable(struct panthor_device *ptdev, u32 as_nr)
624 {
625 	int ret;
626 
627 	ret = mmu_hw_do_operation_locked(ptdev, as_nr, 0, ~0ULL, AS_COMMAND_FLUSH_MEM);
628 	if (ret)
629 		return ret;
630 
631 	gpu_write(ptdev, AS_TRANSTAB_LO(as_nr), 0);
632 	gpu_write(ptdev, AS_TRANSTAB_HI(as_nr), 0);
633 
634 	gpu_write(ptdev, AS_MEMATTR_LO(as_nr), 0);
635 	gpu_write(ptdev, AS_MEMATTR_HI(as_nr), 0);
636 
637 	gpu_write(ptdev, AS_TRANSCFG_LO(as_nr), AS_TRANSCFG_ADRMODE_UNMAPPED);
638 	gpu_write(ptdev, AS_TRANSCFG_HI(as_nr), 0);
639 
640 	return write_cmd(ptdev, as_nr, AS_COMMAND_UPDATE);
641 }
642 
643 static u32 panthor_mmu_fault_mask(struct panthor_device *ptdev, u32 value)
644 {
645 	/* Bits 16 to 31 mean REQ_COMPLETE. */
646 	return value & GENMASK(15, 0);
647 }
648 
649 static u32 panthor_mmu_as_fault_mask(struct panthor_device *ptdev, u32 as)
650 {
651 	return BIT(as);
652 }
653 
654 /**
655  * panthor_vm_has_unhandled_faults() - Check if a VM has unhandled faults
656  * @vm: VM to check.
657  *
658  * Return: true if the VM has unhandled faults, false otherwise.
659  */
660 bool panthor_vm_has_unhandled_faults(struct panthor_vm *vm)
661 {
662 	return vm->unhandled_fault;
663 }
664 
665 /**
666  * panthor_vm_is_unusable() - Check if the VM is still usable
667  * @vm: VM to check.
668  *
669  * Return: true if the VM is unusable, false otherwise.
670  */
671 bool panthor_vm_is_unusable(struct panthor_vm *vm)
672 {
673 	return vm->unusable;
674 }
675 
676 static void panthor_vm_release_as_locked(struct panthor_vm *vm)
677 {
678 	struct panthor_device *ptdev = vm->ptdev;
679 
680 	lockdep_assert_held(&ptdev->mmu->as.slots_lock);
681 
682 	if (drm_WARN_ON(&ptdev->base, vm->as.id < 0))
683 		return;
684 
685 	ptdev->mmu->as.slots[vm->as.id].vm = NULL;
686 	clear_bit(vm->as.id, &ptdev->mmu->as.alloc_mask);
687 	refcount_set(&vm->as.active_cnt, 0);
688 	list_del_init(&vm->as.lru_node);
689 	vm->as.id = -1;
690 }
691 
692 /**
693  * panthor_vm_active() - Flag a VM as active
694  * @VM: VM to flag as active.
695  *
696  * Assigns an address space to a VM so it can be used by the GPU/MCU.
697  *
698  * Return: 0 on success, a negative error code otherwise.
699  */
700 int panthor_vm_active(struct panthor_vm *vm)
701 {
702 	struct panthor_device *ptdev = vm->ptdev;
703 	u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
704 	struct io_pgtable_cfg *cfg = &io_pgtable_ops_to_pgtable(vm->pgtbl_ops)->cfg;
705 	int ret = 0, as, cookie;
706 	u64 transtab, transcfg;
707 
708 	if (!drm_dev_enter(&ptdev->base, &cookie))
709 		return -ENODEV;
710 
711 	if (refcount_inc_not_zero(&vm->as.active_cnt))
712 		goto out_dev_exit;
713 
714 	mutex_lock(&ptdev->mmu->as.slots_lock);
715 
716 	if (refcount_inc_not_zero(&vm->as.active_cnt))
717 		goto out_unlock;
718 
719 	as = vm->as.id;
720 	if (as >= 0) {
721 		/* Unhandled pagefault on this AS, the MMU was disabled. We need to
722 		 * re-enable the MMU after clearing+unmasking the AS interrupts.
723 		 */
724 		if (ptdev->mmu->as.faulty_mask & panthor_mmu_as_fault_mask(ptdev, as))
725 			goto out_enable_as;
726 
727 		goto out_make_active;
728 	}
729 
730 	/* Check for a free AS */
731 	if (vm->for_mcu) {
732 		drm_WARN_ON(&ptdev->base, ptdev->mmu->as.alloc_mask & BIT(0));
733 		as = 0;
734 	} else {
735 		as = ffz(ptdev->mmu->as.alloc_mask | BIT(0));
736 	}
737 
738 	if (!(BIT(as) & ptdev->gpu_info.as_present)) {
739 		struct panthor_vm *lru_vm;
740 
741 		lru_vm = list_first_entry_or_null(&ptdev->mmu->as.lru_list,
742 						  struct panthor_vm,
743 						  as.lru_node);
744 		if (drm_WARN_ON(&ptdev->base, !lru_vm)) {
745 			ret = -EBUSY;
746 			goto out_unlock;
747 		}
748 
749 		drm_WARN_ON(&ptdev->base, refcount_read(&lru_vm->as.active_cnt));
750 		as = lru_vm->as.id;
751 		panthor_vm_release_as_locked(lru_vm);
752 	}
753 
754 	/* Assign the free or reclaimed AS to the FD */
755 	vm->as.id = as;
756 	set_bit(as, &ptdev->mmu->as.alloc_mask);
757 	ptdev->mmu->as.slots[as].vm = vm;
758 
759 out_enable_as:
760 	transtab = cfg->arm_lpae_s1_cfg.ttbr;
761 	transcfg = AS_TRANSCFG_PTW_MEMATTR_WB |
762 		   AS_TRANSCFG_PTW_RA |
763 		   AS_TRANSCFG_ADRMODE_AARCH64_4K |
764 		   AS_TRANSCFG_INA_BITS(55 - va_bits);
765 	if (ptdev->coherent)
766 		transcfg |= AS_TRANSCFG_PTW_SH_OS;
767 
768 	/* If the VM is re-activated, we clear the fault. */
769 	vm->unhandled_fault = false;
770 
771 	/* Unhandled pagefault on this AS, clear the fault and re-enable interrupts
772 	 * before enabling the AS.
773 	 */
774 	if (ptdev->mmu->as.faulty_mask & panthor_mmu_as_fault_mask(ptdev, as)) {
775 		gpu_write(ptdev, MMU_INT_CLEAR, panthor_mmu_as_fault_mask(ptdev, as));
776 		ptdev->mmu->as.faulty_mask &= ~panthor_mmu_as_fault_mask(ptdev, as);
777 		gpu_write(ptdev, MMU_INT_MASK, ~ptdev->mmu->as.faulty_mask);
778 	}
779 
780 	ret = panthor_mmu_as_enable(vm->ptdev, vm->as.id, transtab, transcfg, vm->memattr);
781 
782 out_make_active:
783 	if (!ret) {
784 		refcount_set(&vm->as.active_cnt, 1);
785 		list_del_init(&vm->as.lru_node);
786 	}
787 
788 out_unlock:
789 	mutex_unlock(&ptdev->mmu->as.slots_lock);
790 
791 out_dev_exit:
792 	drm_dev_exit(cookie);
793 	return ret;
794 }
795 
796 /**
797  * panthor_vm_idle() - Flag a VM idle
798  * @VM: VM to flag as idle.
799  *
800  * When we know the GPU is done with the VM (no more jobs to process),
801  * we can relinquish the AS slot attached to this VM, if any.
802  *
803  * We don't release the slot immediately, but instead place the VM in
804  * the LRU list, so it can be evicted if another VM needs an AS slot.
805  * This way, VMs keep attached to the AS they were given until we run
806  * out of free slot, limiting the number of MMU operations (TLB flush
807  * and other AS updates).
808  */
809 void panthor_vm_idle(struct panthor_vm *vm)
810 {
811 	struct panthor_device *ptdev = vm->ptdev;
812 
813 	if (!refcount_dec_and_mutex_lock(&vm->as.active_cnt, &ptdev->mmu->as.slots_lock))
814 		return;
815 
816 	if (!drm_WARN_ON(&ptdev->base, vm->as.id == -1 || !list_empty(&vm->as.lru_node)))
817 		list_add_tail(&vm->as.lru_node, &ptdev->mmu->as.lru_list);
818 
819 	refcount_set(&vm->as.active_cnt, 0);
820 	mutex_unlock(&ptdev->mmu->as.slots_lock);
821 }
822 
823 static void panthor_vm_stop(struct panthor_vm *vm)
824 {
825 	drm_sched_stop(&vm->sched, NULL);
826 }
827 
828 static void panthor_vm_start(struct panthor_vm *vm)
829 {
830 	drm_sched_start(&vm->sched, true);
831 }
832 
833 /**
834  * panthor_vm_as() - Get the AS slot attached to a VM
835  * @vm: VM to get the AS slot of.
836  *
837  * Return: -1 if the VM is not assigned an AS slot yet, >= 0 otherwise.
838  */
839 int panthor_vm_as(struct panthor_vm *vm)
840 {
841 	return vm->as.id;
842 }
843 
844 static size_t get_pgsize(u64 addr, size_t size, size_t *count)
845 {
846 	/*
847 	 * io-pgtable only operates on multiple pages within a single table
848 	 * entry, so we need to split at boundaries of the table size, i.e.
849 	 * the next block size up. The distance from address A to the next
850 	 * boundary of block size B is logically B - A % B, but in unsigned
851 	 * two's complement where B is a power of two we get the equivalence
852 	 * B - A % B == (B - A) % B == (n * B - A) % B, and choose n = 0 :)
853 	 */
854 	size_t blk_offset = -addr % SZ_2M;
855 
856 	if (blk_offset || size < SZ_2M) {
857 		*count = min_not_zero(blk_offset, size) / SZ_4K;
858 		return SZ_4K;
859 	}
860 	blk_offset = -addr % SZ_1G ?: SZ_1G;
861 	*count = min(blk_offset, size) / SZ_2M;
862 	return SZ_2M;
863 }
864 
865 static int panthor_vm_flush_range(struct panthor_vm *vm, u64 iova, u64 size)
866 {
867 	struct panthor_device *ptdev = vm->ptdev;
868 	int ret = 0, cookie;
869 
870 	if (vm->as.id < 0)
871 		return 0;
872 
873 	/* If the device is unplugged, we just silently skip the flush. */
874 	if (!drm_dev_enter(&ptdev->base, &cookie))
875 		return 0;
876 
877 	/* Flush the PTs only if we're already awake */
878 	if (pm_runtime_active(ptdev->base.dev))
879 		ret = mmu_hw_do_operation(vm, iova, size, AS_COMMAND_FLUSH_PT);
880 
881 	drm_dev_exit(cookie);
882 	return ret;
883 }
884 
885 static int panthor_vm_unmap_pages(struct panthor_vm *vm, u64 iova, u64 size)
886 {
887 	struct panthor_device *ptdev = vm->ptdev;
888 	struct io_pgtable_ops *ops = vm->pgtbl_ops;
889 	u64 offset = 0;
890 
891 	drm_dbg(&ptdev->base, "unmap: as=%d, iova=%llx, len=%llx", vm->as.id, iova, size);
892 
893 	while (offset < size) {
894 		size_t unmapped_sz = 0, pgcount;
895 		size_t pgsize = get_pgsize(iova + offset, size - offset, &pgcount);
896 
897 		unmapped_sz = ops->unmap_pages(ops, iova + offset, pgsize, pgcount, NULL);
898 
899 		if (drm_WARN_ON(&ptdev->base, unmapped_sz != pgsize * pgcount)) {
900 			drm_err(&ptdev->base, "failed to unmap range %llx-%llx (requested range %llx-%llx)\n",
901 				iova + offset + unmapped_sz,
902 				iova + offset + pgsize * pgcount,
903 				iova, iova + size);
904 			panthor_vm_flush_range(vm, iova, offset + unmapped_sz);
905 			return  -EINVAL;
906 		}
907 		offset += unmapped_sz;
908 	}
909 
910 	return panthor_vm_flush_range(vm, iova, size);
911 }
912 
913 static int
914 panthor_vm_map_pages(struct panthor_vm *vm, u64 iova, int prot,
915 		     struct sg_table *sgt, u64 offset, u64 size)
916 {
917 	struct panthor_device *ptdev = vm->ptdev;
918 	unsigned int count;
919 	struct scatterlist *sgl;
920 	struct io_pgtable_ops *ops = vm->pgtbl_ops;
921 	u64 start_iova = iova;
922 	int ret;
923 
924 	if (!size)
925 		return 0;
926 
927 	for_each_sgtable_dma_sg(sgt, sgl, count) {
928 		dma_addr_t paddr = sg_dma_address(sgl);
929 		size_t len = sg_dma_len(sgl);
930 
931 		if (len <= offset) {
932 			offset -= len;
933 			continue;
934 		}
935 
936 		paddr += offset;
937 		len -= offset;
938 		len = min_t(size_t, len, size);
939 		size -= len;
940 
941 		drm_dbg(&ptdev->base, "map: as=%d, iova=%llx, paddr=%pad, len=%zx",
942 			vm->as.id, iova, &paddr, len);
943 
944 		while (len) {
945 			size_t pgcount, mapped = 0;
946 			size_t pgsize = get_pgsize(iova | paddr, len, &pgcount);
947 
948 			ret = ops->map_pages(ops, iova, paddr, pgsize, pgcount, prot,
949 					     GFP_KERNEL, &mapped);
950 			iova += mapped;
951 			paddr += mapped;
952 			len -= mapped;
953 
954 			if (drm_WARN_ON(&ptdev->base, !ret && !mapped))
955 				ret = -ENOMEM;
956 
957 			if (ret) {
958 				/* If something failed, unmap what we've already mapped before
959 				 * returning. The unmap call is not supposed to fail.
960 				 */
961 				drm_WARN_ON(&ptdev->base,
962 					    panthor_vm_unmap_pages(vm, start_iova,
963 								   iova - start_iova));
964 				return ret;
965 			}
966 		}
967 
968 		if (!size)
969 			break;
970 	}
971 
972 	return panthor_vm_flush_range(vm, start_iova, iova - start_iova);
973 }
974 
975 static int flags_to_prot(u32 flags)
976 {
977 	int prot = 0;
978 
979 	if (flags & DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC)
980 		prot |= IOMMU_NOEXEC;
981 
982 	if (!(flags & DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED))
983 		prot |= IOMMU_CACHE;
984 
985 	if (flags & DRM_PANTHOR_VM_BIND_OP_MAP_READONLY)
986 		prot |= IOMMU_READ;
987 	else
988 		prot |= IOMMU_READ | IOMMU_WRITE;
989 
990 	return prot;
991 }
992 
993 /**
994  * panthor_vm_alloc_va() - Allocate a region in the auto-va space
995  * @VM: VM to allocate a region on.
996  * @va: start of the VA range. Can be PANTHOR_VM_KERNEL_AUTO_VA if the user
997  * wants the VA to be automatically allocated from the auto-VA range.
998  * @size: size of the VA range.
999  * @va_node: drm_mm_node to initialize. Must be zero-initialized.
1000  *
1001  * Some GPU objects, like heap chunks, are fully managed by the kernel and
1002  * need to be mapped to the userspace VM, in the region reserved for kernel
1003  * objects.
1004  *
1005  * This function takes care of allocating a region in the kernel auto-VA space.
1006  *
1007  * Return: 0 on success, an error code otherwise.
1008  */
1009 int
1010 panthor_vm_alloc_va(struct panthor_vm *vm, u64 va, u64 size,
1011 		    struct drm_mm_node *va_node)
1012 {
1013 	int ret;
1014 
1015 	if (!size || (size & ~PAGE_MASK))
1016 		return -EINVAL;
1017 
1018 	if (va != PANTHOR_VM_KERNEL_AUTO_VA && (va & ~PAGE_MASK))
1019 		return -EINVAL;
1020 
1021 	mutex_lock(&vm->mm_lock);
1022 	if (va != PANTHOR_VM_KERNEL_AUTO_VA) {
1023 		va_node->start = va;
1024 		va_node->size = size;
1025 		ret = drm_mm_reserve_node(&vm->mm, va_node);
1026 	} else {
1027 		ret = drm_mm_insert_node_in_range(&vm->mm, va_node, size,
1028 						  size >= SZ_2M ? SZ_2M : SZ_4K,
1029 						  0, vm->kernel_auto_va.start,
1030 						  vm->kernel_auto_va.end,
1031 						  DRM_MM_INSERT_BEST);
1032 	}
1033 	mutex_unlock(&vm->mm_lock);
1034 
1035 	return ret;
1036 }
1037 
1038 /**
1039  * panthor_vm_free_va() - Free a region allocated with panthor_vm_alloc_va()
1040  * @VM: VM to free the region on.
1041  * @va_node: Memory node representing the region to free.
1042  */
1043 void panthor_vm_free_va(struct panthor_vm *vm, struct drm_mm_node *va_node)
1044 {
1045 	mutex_lock(&vm->mm_lock);
1046 	drm_mm_remove_node(va_node);
1047 	mutex_unlock(&vm->mm_lock);
1048 }
1049 
1050 static void panthor_vm_bo_put(struct drm_gpuvm_bo *vm_bo)
1051 {
1052 	struct panthor_gem_object *bo = to_panthor_bo(vm_bo->obj);
1053 	struct drm_gpuvm *vm = vm_bo->vm;
1054 	bool unpin;
1055 
1056 	/* We must retain the GEM before calling drm_gpuvm_bo_put(),
1057 	 * otherwise the mutex might be destroyed while we hold it.
1058 	 * Same goes for the VM, since we take the VM resv lock.
1059 	 */
1060 	drm_gem_object_get(&bo->base.base);
1061 	drm_gpuvm_get(vm);
1062 
1063 	/* We take the resv lock to protect against concurrent accesses to the
1064 	 * gpuvm evicted/extobj lists that are modified in
1065 	 * drm_gpuvm_bo_destroy(), which is called if drm_gpuvm_bo_put()
1066 	 * releases sthe last vm_bo reference.
1067 	 * We take the BO GPUVA list lock to protect the vm_bo removal from the
1068 	 * GEM vm_bo list.
1069 	 */
1070 	dma_resv_lock(drm_gpuvm_resv(vm), NULL);
1071 	mutex_lock(&bo->gpuva_list_lock);
1072 	unpin = drm_gpuvm_bo_put(vm_bo);
1073 	mutex_unlock(&bo->gpuva_list_lock);
1074 	dma_resv_unlock(drm_gpuvm_resv(vm));
1075 
1076 	/* If the vm_bo object was destroyed, release the pin reference that
1077 	 * was hold by this object.
1078 	 */
1079 	if (unpin && !bo->base.base.import_attach)
1080 		drm_gem_shmem_unpin(&bo->base);
1081 
1082 	drm_gpuvm_put(vm);
1083 	drm_gem_object_put(&bo->base.base);
1084 }
1085 
1086 static void panthor_vm_cleanup_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1087 				      struct panthor_vm *vm)
1088 {
1089 	struct panthor_vma *vma, *tmp_vma;
1090 
1091 	u32 remaining_pt_count = op_ctx->rsvd_page_tables.count -
1092 				 op_ctx->rsvd_page_tables.ptr;
1093 
1094 	if (remaining_pt_count) {
1095 		kmem_cache_free_bulk(pt_cache, remaining_pt_count,
1096 				     op_ctx->rsvd_page_tables.pages +
1097 				     op_ctx->rsvd_page_tables.ptr);
1098 	}
1099 
1100 	kfree(op_ctx->rsvd_page_tables.pages);
1101 
1102 	if (op_ctx->map.vm_bo)
1103 		panthor_vm_bo_put(op_ctx->map.vm_bo);
1104 
1105 	for (u32 i = 0; i < ARRAY_SIZE(op_ctx->preallocated_vmas); i++)
1106 		kfree(op_ctx->preallocated_vmas[i]);
1107 
1108 	list_for_each_entry_safe(vma, tmp_vma, &op_ctx->returned_vmas, node) {
1109 		list_del(&vma->node);
1110 		panthor_vm_bo_put(vma->base.vm_bo);
1111 		kfree(vma);
1112 	}
1113 }
1114 
1115 static struct panthor_vma *
1116 panthor_vm_op_ctx_get_vma(struct panthor_vm_op_ctx *op_ctx)
1117 {
1118 	for (u32 i = 0; i < ARRAY_SIZE(op_ctx->preallocated_vmas); i++) {
1119 		struct panthor_vma *vma = op_ctx->preallocated_vmas[i];
1120 
1121 		if (vma) {
1122 			op_ctx->preallocated_vmas[i] = NULL;
1123 			return vma;
1124 		}
1125 	}
1126 
1127 	return NULL;
1128 }
1129 
1130 static int
1131 panthor_vm_op_ctx_prealloc_vmas(struct panthor_vm_op_ctx *op_ctx)
1132 {
1133 	u32 vma_count;
1134 
1135 	switch (op_ctx->flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK) {
1136 	case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP:
1137 		/* One VMA for the new mapping, and two more VMAs for the remap case
1138 		 * which might contain both a prev and next VA.
1139 		 */
1140 		vma_count = 3;
1141 		break;
1142 
1143 	case DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP:
1144 		/* Partial unmaps might trigger a remap with either a prev or a next VA,
1145 		 * but not both.
1146 		 */
1147 		vma_count = 1;
1148 		break;
1149 
1150 	default:
1151 		return 0;
1152 	}
1153 
1154 	for (u32 i = 0; i < vma_count; i++) {
1155 		struct panthor_vma *vma = kzalloc(sizeof(*vma), GFP_KERNEL);
1156 
1157 		if (!vma)
1158 			return -ENOMEM;
1159 
1160 		op_ctx->preallocated_vmas[i] = vma;
1161 	}
1162 
1163 	return 0;
1164 }
1165 
1166 #define PANTHOR_VM_BIND_OP_MAP_FLAGS \
1167 	(DRM_PANTHOR_VM_BIND_OP_MAP_READONLY | \
1168 	 DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC | \
1169 	 DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED | \
1170 	 DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
1171 
1172 static int panthor_vm_prepare_map_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1173 					 struct panthor_vm *vm,
1174 					 struct panthor_gem_object *bo,
1175 					 u64 offset,
1176 					 u64 size, u64 va,
1177 					 u32 flags)
1178 {
1179 	struct drm_gpuvm_bo *preallocated_vm_bo;
1180 	struct sg_table *sgt = NULL;
1181 	u64 pt_count;
1182 	int ret;
1183 
1184 	if (!bo)
1185 		return -EINVAL;
1186 
1187 	if ((flags & ~PANTHOR_VM_BIND_OP_MAP_FLAGS) ||
1188 	    (flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK) != DRM_PANTHOR_VM_BIND_OP_TYPE_MAP)
1189 		return -EINVAL;
1190 
1191 	/* Make sure the VA and size are aligned and in-bounds. */
1192 	if (size > bo->base.base.size || offset > bo->base.base.size - size)
1193 		return -EINVAL;
1194 
1195 	/* If the BO has an exclusive VM attached, it can't be mapped to other VMs. */
1196 	if (bo->exclusive_vm_root_gem &&
1197 	    bo->exclusive_vm_root_gem != panthor_vm_root_gem(vm))
1198 		return -EINVAL;
1199 
1200 	memset(op_ctx, 0, sizeof(*op_ctx));
1201 	INIT_LIST_HEAD(&op_ctx->returned_vmas);
1202 	op_ctx->flags = flags;
1203 	op_ctx->va.range = size;
1204 	op_ctx->va.addr = va;
1205 
1206 	ret = panthor_vm_op_ctx_prealloc_vmas(op_ctx);
1207 	if (ret)
1208 		goto err_cleanup;
1209 
1210 	if (!bo->base.base.import_attach) {
1211 		/* Pre-reserve the BO pages, so the map operation doesn't have to
1212 		 * allocate.
1213 		 */
1214 		ret = drm_gem_shmem_pin(&bo->base);
1215 		if (ret)
1216 			goto err_cleanup;
1217 	}
1218 
1219 	sgt = drm_gem_shmem_get_pages_sgt(&bo->base);
1220 	if (IS_ERR(sgt)) {
1221 		if (!bo->base.base.import_attach)
1222 			drm_gem_shmem_unpin(&bo->base);
1223 
1224 		ret = PTR_ERR(sgt);
1225 		goto err_cleanup;
1226 	}
1227 
1228 	op_ctx->map.sgt = sgt;
1229 
1230 	preallocated_vm_bo = drm_gpuvm_bo_create(&vm->base, &bo->base.base);
1231 	if (!preallocated_vm_bo) {
1232 		if (!bo->base.base.import_attach)
1233 			drm_gem_shmem_unpin(&bo->base);
1234 
1235 		ret = -ENOMEM;
1236 		goto err_cleanup;
1237 	}
1238 
1239 	mutex_lock(&bo->gpuva_list_lock);
1240 	op_ctx->map.vm_bo = drm_gpuvm_bo_obtain_prealloc(preallocated_vm_bo);
1241 	mutex_unlock(&bo->gpuva_list_lock);
1242 
1243 	/* If the a vm_bo for this <VM,BO> combination exists, it already
1244 	 * retains a pin ref, and we can release the one we took earlier.
1245 	 *
1246 	 * If our pre-allocated vm_bo is picked, it now retains the pin ref,
1247 	 * which will be released in panthor_vm_bo_put().
1248 	 */
1249 	if (preallocated_vm_bo != op_ctx->map.vm_bo &&
1250 	    !bo->base.base.import_attach)
1251 		drm_gem_shmem_unpin(&bo->base);
1252 
1253 	op_ctx->map.bo_offset = offset;
1254 
1255 	/* L1, L2 and L3 page tables.
1256 	 * We could optimize L3 allocation by iterating over the sgt and merging
1257 	 * 2M contiguous blocks, but it's simpler to over-provision and return
1258 	 * the pages if they're not used.
1259 	 */
1260 	pt_count = ((ALIGN(va + size, 1ull << 39) - ALIGN_DOWN(va, 1ull << 39)) >> 39) +
1261 		   ((ALIGN(va + size, 1ull << 30) - ALIGN_DOWN(va, 1ull << 30)) >> 30) +
1262 		   ((ALIGN(va + size, 1ull << 21) - ALIGN_DOWN(va, 1ull << 21)) >> 21);
1263 
1264 	op_ctx->rsvd_page_tables.pages = kcalloc(pt_count,
1265 						 sizeof(*op_ctx->rsvd_page_tables.pages),
1266 						 GFP_KERNEL);
1267 	if (!op_ctx->rsvd_page_tables.pages) {
1268 		ret = -ENOMEM;
1269 		goto err_cleanup;
1270 	}
1271 
1272 	ret = kmem_cache_alloc_bulk(pt_cache, GFP_KERNEL, pt_count,
1273 				    op_ctx->rsvd_page_tables.pages);
1274 	op_ctx->rsvd_page_tables.count = ret;
1275 	if (ret != pt_count) {
1276 		ret = -ENOMEM;
1277 		goto err_cleanup;
1278 	}
1279 
1280 	/* Insert BO into the extobj list last, when we know nothing can fail. */
1281 	dma_resv_lock(panthor_vm_resv(vm), NULL);
1282 	drm_gpuvm_bo_extobj_add(op_ctx->map.vm_bo);
1283 	dma_resv_unlock(panthor_vm_resv(vm));
1284 
1285 	return 0;
1286 
1287 err_cleanup:
1288 	panthor_vm_cleanup_op_ctx(op_ctx, vm);
1289 	return ret;
1290 }
1291 
1292 static int panthor_vm_prepare_unmap_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1293 					   struct panthor_vm *vm,
1294 					   u64 va, u64 size)
1295 {
1296 	u32 pt_count = 0;
1297 	int ret;
1298 
1299 	memset(op_ctx, 0, sizeof(*op_ctx));
1300 	INIT_LIST_HEAD(&op_ctx->returned_vmas);
1301 	op_ctx->va.range = size;
1302 	op_ctx->va.addr = va;
1303 	op_ctx->flags = DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP;
1304 
1305 	/* Pre-allocate L3 page tables to account for the split-2M-block
1306 	 * situation on unmap.
1307 	 */
1308 	if (va != ALIGN(va, SZ_2M))
1309 		pt_count++;
1310 
1311 	if (va + size != ALIGN(va + size, SZ_2M) &&
1312 	    ALIGN(va + size, SZ_2M) != ALIGN(va, SZ_2M))
1313 		pt_count++;
1314 
1315 	ret = panthor_vm_op_ctx_prealloc_vmas(op_ctx);
1316 	if (ret)
1317 		goto err_cleanup;
1318 
1319 	if (pt_count) {
1320 		op_ctx->rsvd_page_tables.pages = kcalloc(pt_count,
1321 							 sizeof(*op_ctx->rsvd_page_tables.pages),
1322 							 GFP_KERNEL);
1323 		if (!op_ctx->rsvd_page_tables.pages) {
1324 			ret = -ENOMEM;
1325 			goto err_cleanup;
1326 		}
1327 
1328 		ret = kmem_cache_alloc_bulk(pt_cache, GFP_KERNEL, pt_count,
1329 					    op_ctx->rsvd_page_tables.pages);
1330 		if (ret != pt_count) {
1331 			ret = -ENOMEM;
1332 			goto err_cleanup;
1333 		}
1334 		op_ctx->rsvd_page_tables.count = pt_count;
1335 	}
1336 
1337 	return 0;
1338 
1339 err_cleanup:
1340 	panthor_vm_cleanup_op_ctx(op_ctx, vm);
1341 	return ret;
1342 }
1343 
1344 static void panthor_vm_prepare_sync_only_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1345 						struct panthor_vm *vm)
1346 {
1347 	memset(op_ctx, 0, sizeof(*op_ctx));
1348 	INIT_LIST_HEAD(&op_ctx->returned_vmas);
1349 	op_ctx->flags = DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY;
1350 }
1351 
1352 /**
1353  * panthor_vm_get_bo_for_va() - Get the GEM object mapped at a virtual address
1354  * @vm: VM to look into.
1355  * @va: Virtual address to search for.
1356  * @bo_offset: Offset of the GEM object mapped at this virtual address.
1357  * Only valid on success.
1358  *
1359  * The object returned by this function might no longer be mapped when the
1360  * function returns. It's the caller responsibility to ensure there's no
1361  * concurrent map/unmap operations making the returned value invalid, or
1362  * make sure it doesn't matter if the object is no longer mapped.
1363  *
1364  * Return: A valid pointer on success, an ERR_PTR() otherwise.
1365  */
1366 struct panthor_gem_object *
1367 panthor_vm_get_bo_for_va(struct panthor_vm *vm, u64 va, u64 *bo_offset)
1368 {
1369 	struct panthor_gem_object *bo = ERR_PTR(-ENOENT);
1370 	struct drm_gpuva *gpuva;
1371 	struct panthor_vma *vma;
1372 
1373 	/* Take the VM lock to prevent concurrent map/unmap operations. */
1374 	mutex_lock(&vm->op_lock);
1375 	gpuva = drm_gpuva_find_first(&vm->base, va, 1);
1376 	vma = gpuva ? container_of(gpuva, struct panthor_vma, base) : NULL;
1377 	if (vma && vma->base.gem.obj) {
1378 		drm_gem_object_get(vma->base.gem.obj);
1379 		bo = to_panthor_bo(vma->base.gem.obj);
1380 		*bo_offset = vma->base.gem.offset + (va - vma->base.va.addr);
1381 	}
1382 	mutex_unlock(&vm->op_lock);
1383 
1384 	return bo;
1385 }
1386 
1387 #define PANTHOR_VM_MIN_KERNEL_VA_SIZE	SZ_256M
1388 
1389 static u64
1390 panthor_vm_create_get_user_va_range(const struct drm_panthor_vm_create *args,
1391 				    u64 full_va_range)
1392 {
1393 	u64 user_va_range;
1394 
1395 	/* Make sure we have a minimum amount of VA space for kernel objects. */
1396 	if (full_va_range < PANTHOR_VM_MIN_KERNEL_VA_SIZE)
1397 		return 0;
1398 
1399 	if (args->user_va_range) {
1400 		/* Use the user provided value if != 0. */
1401 		user_va_range = args->user_va_range;
1402 	} else if (TASK_SIZE_OF(current) < full_va_range) {
1403 		/* If the task VM size is smaller than the GPU VA range, pick this
1404 		 * as our default user VA range, so userspace can CPU/GPU map buffers
1405 		 * at the same address.
1406 		 */
1407 		user_va_range = TASK_SIZE_OF(current);
1408 	} else {
1409 		/* If the GPU VA range is smaller than the task VM size, we
1410 		 * just have to live with the fact we won't be able to map
1411 		 * all buffers at the same GPU/CPU address.
1412 		 *
1413 		 * If the GPU VA range is bigger than 4G (more than 32-bit of
1414 		 * VA), we split the range in two, and assign half of it to
1415 		 * the user and the other half to the kernel, if it's not, we
1416 		 * keep the kernel VA space as small as possible.
1417 		 */
1418 		user_va_range = full_va_range > SZ_4G ?
1419 				full_va_range / 2 :
1420 				full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE;
1421 	}
1422 
1423 	if (full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE < user_va_range)
1424 		user_va_range = full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE;
1425 
1426 	return user_va_range;
1427 }
1428 
1429 #define PANTHOR_VM_CREATE_FLAGS		0
1430 
1431 static int
1432 panthor_vm_create_check_args(const struct panthor_device *ptdev,
1433 			     const struct drm_panthor_vm_create *args,
1434 			     u64 *kernel_va_start, u64 *kernel_va_range)
1435 {
1436 	u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
1437 	u64 full_va_range = 1ull << va_bits;
1438 	u64 user_va_range;
1439 
1440 	if (args->flags & ~PANTHOR_VM_CREATE_FLAGS)
1441 		return -EINVAL;
1442 
1443 	user_va_range = panthor_vm_create_get_user_va_range(args, full_va_range);
1444 	if (!user_va_range || (args->user_va_range && args->user_va_range > user_va_range))
1445 		return -EINVAL;
1446 
1447 	/* Pick a kernel VA range that's a power of two, to have a clear split. */
1448 	*kernel_va_range = rounddown_pow_of_two(full_va_range - user_va_range);
1449 	*kernel_va_start = full_va_range - *kernel_va_range;
1450 	return 0;
1451 }
1452 
1453 /*
1454  * Only 32 VMs per open file. If that becomes a limiting factor, we can
1455  * increase this number.
1456  */
1457 #define PANTHOR_MAX_VMS_PER_FILE	32
1458 
1459 /**
1460  * panthor_vm_pool_create_vm() - Create a VM
1461  * @pool: The VM to create this VM on.
1462  * @kernel_va_start: Start of the region reserved for kernel objects.
1463  * @kernel_va_range: Size of the region reserved for kernel objects.
1464  *
1465  * Return: a positive VM ID on success, a negative error code otherwise.
1466  */
1467 int panthor_vm_pool_create_vm(struct panthor_device *ptdev,
1468 			      struct panthor_vm_pool *pool,
1469 			      struct drm_panthor_vm_create *args)
1470 {
1471 	u64 kernel_va_start, kernel_va_range;
1472 	struct panthor_vm *vm;
1473 	int ret;
1474 	u32 id;
1475 
1476 	ret = panthor_vm_create_check_args(ptdev, args, &kernel_va_start, &kernel_va_range);
1477 	if (ret)
1478 		return ret;
1479 
1480 	vm = panthor_vm_create(ptdev, false, kernel_va_start, kernel_va_range,
1481 			       kernel_va_start, kernel_va_range);
1482 	if (IS_ERR(vm))
1483 		return PTR_ERR(vm);
1484 
1485 	ret = xa_alloc(&pool->xa, &id, vm,
1486 		       XA_LIMIT(1, PANTHOR_MAX_VMS_PER_FILE), GFP_KERNEL);
1487 
1488 	if (ret) {
1489 		panthor_vm_put(vm);
1490 		return ret;
1491 	}
1492 
1493 	args->user_va_range = kernel_va_start;
1494 	return id;
1495 }
1496 
1497 static void panthor_vm_destroy(struct panthor_vm *vm)
1498 {
1499 	if (!vm)
1500 		return;
1501 
1502 	vm->destroyed = true;
1503 
1504 	mutex_lock(&vm->heaps.lock);
1505 	panthor_heap_pool_destroy(vm->heaps.pool);
1506 	vm->heaps.pool = NULL;
1507 	mutex_unlock(&vm->heaps.lock);
1508 
1509 	drm_WARN_ON(&vm->ptdev->base,
1510 		    panthor_vm_unmap_range(vm, vm->base.mm_start, vm->base.mm_range));
1511 	panthor_vm_put(vm);
1512 }
1513 
1514 /**
1515  * panthor_vm_pool_destroy_vm() - Destroy a VM.
1516  * @pool: VM pool.
1517  * @handle: VM handle.
1518  *
1519  * This function doesn't free the VM object or its resources, it just kills
1520  * all mappings, and makes sure nothing can be mapped after that point.
1521  *
1522  * If there was any active jobs at the time this function is called, these
1523  * jobs should experience page faults and be killed as a result.
1524  *
1525  * The VM resources are freed when the last reference on the VM object is
1526  * dropped.
1527  */
1528 int panthor_vm_pool_destroy_vm(struct panthor_vm_pool *pool, u32 handle)
1529 {
1530 	struct panthor_vm *vm;
1531 
1532 	vm = xa_erase(&pool->xa, handle);
1533 
1534 	panthor_vm_destroy(vm);
1535 
1536 	return vm ? 0 : -EINVAL;
1537 }
1538 
1539 /**
1540  * panthor_vm_pool_get_vm() - Retrieve VM object bound to a VM handle
1541  * @pool: VM pool to check.
1542  * @handle: Handle of the VM to retrieve.
1543  *
1544  * Return: A valid pointer if the VM exists, NULL otherwise.
1545  */
1546 struct panthor_vm *
1547 panthor_vm_pool_get_vm(struct panthor_vm_pool *pool, u32 handle)
1548 {
1549 	struct panthor_vm *vm;
1550 
1551 	vm = panthor_vm_get(xa_load(&pool->xa, handle));
1552 
1553 	return vm;
1554 }
1555 
1556 /**
1557  * panthor_vm_pool_destroy() - Destroy a VM pool.
1558  * @pfile: File.
1559  *
1560  * Destroy all VMs in the pool, and release the pool resources.
1561  *
1562  * Note that VMs can outlive the pool they were created from if other
1563  * objects hold a reference to there VMs.
1564  */
1565 void panthor_vm_pool_destroy(struct panthor_file *pfile)
1566 {
1567 	struct panthor_vm *vm;
1568 	unsigned long i;
1569 
1570 	if (!pfile->vms)
1571 		return;
1572 
1573 	xa_for_each(&pfile->vms->xa, i, vm)
1574 		panthor_vm_destroy(vm);
1575 
1576 	xa_destroy(&pfile->vms->xa);
1577 	kfree(pfile->vms);
1578 }
1579 
1580 /**
1581  * panthor_vm_pool_create() - Create a VM pool
1582  * @pfile: File.
1583  *
1584  * Return: 0 on success, a negative error code otherwise.
1585  */
1586 int panthor_vm_pool_create(struct panthor_file *pfile)
1587 {
1588 	pfile->vms = kzalloc(sizeof(*pfile->vms), GFP_KERNEL);
1589 	if (!pfile->vms)
1590 		return -ENOMEM;
1591 
1592 	xa_init_flags(&pfile->vms->xa, XA_FLAGS_ALLOC1);
1593 	return 0;
1594 }
1595 
1596 /* dummy TLB ops, the real TLB flush happens in panthor_vm_flush_range() */
1597 static void mmu_tlb_flush_all(void *cookie)
1598 {
1599 }
1600 
1601 static void mmu_tlb_flush_walk(unsigned long iova, size_t size, size_t granule, void *cookie)
1602 {
1603 }
1604 
1605 static const struct iommu_flush_ops mmu_tlb_ops = {
1606 	.tlb_flush_all = mmu_tlb_flush_all,
1607 	.tlb_flush_walk = mmu_tlb_flush_walk,
1608 };
1609 
1610 static const char *access_type_name(struct panthor_device *ptdev,
1611 				    u32 fault_status)
1612 {
1613 	switch (fault_status & AS_FAULTSTATUS_ACCESS_TYPE_MASK) {
1614 	case AS_FAULTSTATUS_ACCESS_TYPE_ATOMIC:
1615 		return "ATOMIC";
1616 	case AS_FAULTSTATUS_ACCESS_TYPE_READ:
1617 		return "READ";
1618 	case AS_FAULTSTATUS_ACCESS_TYPE_WRITE:
1619 		return "WRITE";
1620 	case AS_FAULTSTATUS_ACCESS_TYPE_EX:
1621 		return "EXECUTE";
1622 	default:
1623 		drm_WARN_ON(&ptdev->base, 1);
1624 		return NULL;
1625 	}
1626 }
1627 
1628 static void panthor_mmu_irq_handler(struct panthor_device *ptdev, u32 status)
1629 {
1630 	bool has_unhandled_faults = false;
1631 
1632 	status = panthor_mmu_fault_mask(ptdev, status);
1633 	while (status) {
1634 		u32 as = ffs(status | (status >> 16)) - 1;
1635 		u32 mask = panthor_mmu_as_fault_mask(ptdev, as);
1636 		u32 new_int_mask;
1637 		u64 addr;
1638 		u32 fault_status;
1639 		u32 exception_type;
1640 		u32 access_type;
1641 		u32 source_id;
1642 
1643 		fault_status = gpu_read(ptdev, AS_FAULTSTATUS(as));
1644 		addr = gpu_read(ptdev, AS_FAULTADDRESS_LO(as));
1645 		addr |= (u64)gpu_read(ptdev, AS_FAULTADDRESS_HI(as)) << 32;
1646 
1647 		/* decode the fault status */
1648 		exception_type = fault_status & 0xFF;
1649 		access_type = (fault_status >> 8) & 0x3;
1650 		source_id = (fault_status >> 16);
1651 
1652 		mutex_lock(&ptdev->mmu->as.slots_lock);
1653 
1654 		ptdev->mmu->as.faulty_mask |= mask;
1655 		new_int_mask =
1656 			panthor_mmu_fault_mask(ptdev, ~ptdev->mmu->as.faulty_mask);
1657 
1658 		/* terminal fault, print info about the fault */
1659 		drm_err(&ptdev->base,
1660 			"Unhandled Page fault in AS%d at VA 0x%016llX\n"
1661 			"raw fault status: 0x%X\n"
1662 			"decoded fault status: %s\n"
1663 			"exception type 0x%X: %s\n"
1664 			"access type 0x%X: %s\n"
1665 			"source id 0x%X\n",
1666 			as, addr,
1667 			fault_status,
1668 			(fault_status & (1 << 10) ? "DECODER FAULT" : "SLAVE FAULT"),
1669 			exception_type, panthor_exception_name(ptdev, exception_type),
1670 			access_type, access_type_name(ptdev, fault_status),
1671 			source_id);
1672 
1673 		/* Ignore MMU interrupts on this AS until it's been
1674 		 * re-enabled.
1675 		 */
1676 		ptdev->mmu->irq.mask = new_int_mask;
1677 		gpu_write(ptdev, MMU_INT_MASK, new_int_mask);
1678 
1679 		if (ptdev->mmu->as.slots[as].vm)
1680 			ptdev->mmu->as.slots[as].vm->unhandled_fault = true;
1681 
1682 		/* Disable the MMU to kill jobs on this AS. */
1683 		panthor_mmu_as_disable(ptdev, as);
1684 		mutex_unlock(&ptdev->mmu->as.slots_lock);
1685 
1686 		status &= ~mask;
1687 		has_unhandled_faults = true;
1688 	}
1689 
1690 	if (has_unhandled_faults)
1691 		panthor_sched_report_mmu_fault(ptdev);
1692 }
1693 PANTHOR_IRQ_HANDLER(mmu, MMU, panthor_mmu_irq_handler);
1694 
1695 /**
1696  * panthor_mmu_suspend() - Suspend the MMU logic
1697  * @ptdev: Device.
1698  *
1699  * All we do here is de-assign the AS slots on all active VMs, so things
1700  * get flushed to the main memory, and no further access to these VMs are
1701  * possible.
1702  *
1703  * We also suspend the MMU IRQ.
1704  */
1705 void panthor_mmu_suspend(struct panthor_device *ptdev)
1706 {
1707 	mutex_lock(&ptdev->mmu->as.slots_lock);
1708 	for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
1709 		struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
1710 
1711 		if (vm) {
1712 			drm_WARN_ON(&ptdev->base, panthor_mmu_as_disable(ptdev, i));
1713 			panthor_vm_release_as_locked(vm);
1714 		}
1715 	}
1716 	mutex_unlock(&ptdev->mmu->as.slots_lock);
1717 
1718 	panthor_mmu_irq_suspend(&ptdev->mmu->irq);
1719 }
1720 
1721 /**
1722  * panthor_mmu_resume() - Resume the MMU logic
1723  * @ptdev: Device.
1724  *
1725  * Resume the IRQ.
1726  *
1727  * We don't re-enable previously active VMs. We assume other parts of the
1728  * driver will call panthor_vm_active() on the VMs they intend to use.
1729  */
1730 void panthor_mmu_resume(struct panthor_device *ptdev)
1731 {
1732 	mutex_lock(&ptdev->mmu->as.slots_lock);
1733 	ptdev->mmu->as.alloc_mask = 0;
1734 	ptdev->mmu->as.faulty_mask = 0;
1735 	mutex_unlock(&ptdev->mmu->as.slots_lock);
1736 
1737 	panthor_mmu_irq_resume(&ptdev->mmu->irq, panthor_mmu_fault_mask(ptdev, ~0));
1738 }
1739 
1740 /**
1741  * panthor_mmu_pre_reset() - Prepare for a reset
1742  * @ptdev: Device.
1743  *
1744  * Suspend the IRQ, and make sure all VM_BIND queues are stopped, so we
1745  * don't get asked to do a VM operation while the GPU is down.
1746  *
1747  * We don't cleanly shutdown the AS slots here, because the reset might
1748  * come from an AS_ACTIVE_BIT stuck situation.
1749  */
1750 void panthor_mmu_pre_reset(struct panthor_device *ptdev)
1751 {
1752 	struct panthor_vm *vm;
1753 
1754 	panthor_mmu_irq_suspend(&ptdev->mmu->irq);
1755 
1756 	mutex_lock(&ptdev->mmu->vm.lock);
1757 	ptdev->mmu->vm.reset_in_progress = true;
1758 	list_for_each_entry(vm, &ptdev->mmu->vm.list, node)
1759 		panthor_vm_stop(vm);
1760 	mutex_unlock(&ptdev->mmu->vm.lock);
1761 }
1762 
1763 /**
1764  * panthor_mmu_post_reset() - Restore things after a reset
1765  * @ptdev: Device.
1766  *
1767  * Put the MMU logic back in action after a reset. That implies resuming the
1768  * IRQ and re-enabling the VM_BIND queues.
1769  */
1770 void panthor_mmu_post_reset(struct panthor_device *ptdev)
1771 {
1772 	struct panthor_vm *vm;
1773 
1774 	mutex_lock(&ptdev->mmu->as.slots_lock);
1775 
1776 	/* Now that the reset is effective, we can assume that none of the
1777 	 * AS slots are setup, and clear the faulty flags too.
1778 	 */
1779 	ptdev->mmu->as.alloc_mask = 0;
1780 	ptdev->mmu->as.faulty_mask = 0;
1781 
1782 	for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
1783 		struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
1784 
1785 		if (vm)
1786 			panthor_vm_release_as_locked(vm);
1787 	}
1788 
1789 	mutex_unlock(&ptdev->mmu->as.slots_lock);
1790 
1791 	panthor_mmu_irq_resume(&ptdev->mmu->irq, panthor_mmu_fault_mask(ptdev, ~0));
1792 
1793 	/* Restart the VM_BIND queues. */
1794 	mutex_lock(&ptdev->mmu->vm.lock);
1795 	list_for_each_entry(vm, &ptdev->mmu->vm.list, node) {
1796 		panthor_vm_start(vm);
1797 	}
1798 	ptdev->mmu->vm.reset_in_progress = false;
1799 	mutex_unlock(&ptdev->mmu->vm.lock);
1800 }
1801 
1802 static void panthor_vm_free(struct drm_gpuvm *gpuvm)
1803 {
1804 	struct panthor_vm *vm = container_of(gpuvm, struct panthor_vm, base);
1805 	struct panthor_device *ptdev = vm->ptdev;
1806 
1807 	mutex_lock(&vm->heaps.lock);
1808 	if (drm_WARN_ON(&ptdev->base, vm->heaps.pool))
1809 		panthor_heap_pool_destroy(vm->heaps.pool);
1810 	mutex_unlock(&vm->heaps.lock);
1811 	mutex_destroy(&vm->heaps.lock);
1812 
1813 	mutex_lock(&ptdev->mmu->vm.lock);
1814 	list_del(&vm->node);
1815 	/* Restore the scheduler state so we can call drm_sched_entity_destroy()
1816 	 * and drm_sched_fini(). If get there, that means we have no job left
1817 	 * and no new jobs can be queued, so we can start the scheduler without
1818 	 * risking interfering with the reset.
1819 	 */
1820 	if (ptdev->mmu->vm.reset_in_progress)
1821 		panthor_vm_start(vm);
1822 	mutex_unlock(&ptdev->mmu->vm.lock);
1823 
1824 	drm_sched_entity_destroy(&vm->entity);
1825 	drm_sched_fini(&vm->sched);
1826 
1827 	mutex_lock(&ptdev->mmu->as.slots_lock);
1828 	if (vm->as.id >= 0) {
1829 		int cookie;
1830 
1831 		if (drm_dev_enter(&ptdev->base, &cookie)) {
1832 			panthor_mmu_as_disable(ptdev, vm->as.id);
1833 			drm_dev_exit(cookie);
1834 		}
1835 
1836 		ptdev->mmu->as.slots[vm->as.id].vm = NULL;
1837 		clear_bit(vm->as.id, &ptdev->mmu->as.alloc_mask);
1838 		list_del(&vm->as.lru_node);
1839 	}
1840 	mutex_unlock(&ptdev->mmu->as.slots_lock);
1841 
1842 	free_io_pgtable_ops(vm->pgtbl_ops);
1843 
1844 	drm_mm_takedown(&vm->mm);
1845 	kfree(vm);
1846 }
1847 
1848 /**
1849  * panthor_vm_put() - Release a reference on a VM
1850  * @vm: VM to release the reference on. Can be NULL.
1851  */
1852 void panthor_vm_put(struct panthor_vm *vm)
1853 {
1854 	drm_gpuvm_put(vm ? &vm->base : NULL);
1855 }
1856 
1857 /**
1858  * panthor_vm_get() - Get a VM reference
1859  * @vm: VM to get the reference on. Can be NULL.
1860  *
1861  * Return: @vm value.
1862  */
1863 struct panthor_vm *panthor_vm_get(struct panthor_vm *vm)
1864 {
1865 	if (vm)
1866 		drm_gpuvm_get(&vm->base);
1867 
1868 	return vm;
1869 }
1870 
1871 /**
1872  * panthor_vm_get_heap_pool() - Get the heap pool attached to a VM
1873  * @vm: VM to query the heap pool on.
1874  * @create: True if the heap pool should be created when it doesn't exist.
1875  *
1876  * Heap pools are per-VM. This function allows one to retrieve the heap pool
1877  * attached to a VM.
1878  *
1879  * If no heap pool exists yet, and @create is true, we create one.
1880  *
1881  * The returned panthor_heap_pool should be released with panthor_heap_pool_put().
1882  *
1883  * Return: A valid pointer on success, an ERR_PTR() otherwise.
1884  */
1885 struct panthor_heap_pool *panthor_vm_get_heap_pool(struct panthor_vm *vm, bool create)
1886 {
1887 	struct panthor_heap_pool *pool;
1888 
1889 	mutex_lock(&vm->heaps.lock);
1890 	if (!vm->heaps.pool && create) {
1891 		if (vm->destroyed)
1892 			pool = ERR_PTR(-EINVAL);
1893 		else
1894 			pool = panthor_heap_pool_create(vm->ptdev, vm);
1895 
1896 		if (!IS_ERR(pool))
1897 			vm->heaps.pool = panthor_heap_pool_get(pool);
1898 	} else {
1899 		pool = panthor_heap_pool_get(vm->heaps.pool);
1900 		if (!pool)
1901 			pool = ERR_PTR(-ENOENT);
1902 	}
1903 	mutex_unlock(&vm->heaps.lock);
1904 
1905 	return pool;
1906 }
1907 
1908 static u64 mair_to_memattr(u64 mair)
1909 {
1910 	u64 memattr = 0;
1911 	u32 i;
1912 
1913 	for (i = 0; i < 8; i++) {
1914 		u8 in_attr = mair >> (8 * i), out_attr;
1915 		u8 outer = in_attr >> 4, inner = in_attr & 0xf;
1916 
1917 		/* For caching to be enabled, inner and outer caching policy
1918 		 * have to be both write-back, if one of them is write-through
1919 		 * or non-cacheable, we just choose non-cacheable. Device
1920 		 * memory is also translated to non-cacheable.
1921 		 */
1922 		if (!(outer & 3) || !(outer & 4) || !(inner & 4)) {
1923 			out_attr = AS_MEMATTR_AARCH64_INNER_OUTER_NC |
1924 				   AS_MEMATTR_AARCH64_SH_MIDGARD_INNER |
1925 				   AS_MEMATTR_AARCH64_INNER_ALLOC_EXPL(false, false);
1926 		} else {
1927 			/* Use SH_CPU_INNER mode so SH_IS, which is used when
1928 			 * IOMMU_CACHE is set, actually maps to the standard
1929 			 * definition of inner-shareable and not Mali's
1930 			 * internal-shareable mode.
1931 			 */
1932 			out_attr = AS_MEMATTR_AARCH64_INNER_OUTER_WB |
1933 				   AS_MEMATTR_AARCH64_SH_CPU_INNER |
1934 				   AS_MEMATTR_AARCH64_INNER_ALLOC_EXPL(inner & 1, inner & 2);
1935 		}
1936 
1937 		memattr |= (u64)out_attr << (8 * i);
1938 	}
1939 
1940 	return memattr;
1941 }
1942 
1943 static void panthor_vma_link(struct panthor_vm *vm,
1944 			     struct panthor_vma *vma,
1945 			     struct drm_gpuvm_bo *vm_bo)
1946 {
1947 	struct panthor_gem_object *bo = to_panthor_bo(vma->base.gem.obj);
1948 
1949 	mutex_lock(&bo->gpuva_list_lock);
1950 	drm_gpuva_link(&vma->base, vm_bo);
1951 	drm_WARN_ON(&vm->ptdev->base, drm_gpuvm_bo_put(vm_bo));
1952 	mutex_unlock(&bo->gpuva_list_lock);
1953 }
1954 
1955 static void panthor_vma_unlink(struct panthor_vm *vm,
1956 			       struct panthor_vma *vma)
1957 {
1958 	struct panthor_gem_object *bo = to_panthor_bo(vma->base.gem.obj);
1959 	struct drm_gpuvm_bo *vm_bo = drm_gpuvm_bo_get(vma->base.vm_bo);
1960 
1961 	mutex_lock(&bo->gpuva_list_lock);
1962 	drm_gpuva_unlink(&vma->base);
1963 	mutex_unlock(&bo->gpuva_list_lock);
1964 
1965 	/* drm_gpuva_unlink() release the vm_bo, but we manually retained it
1966 	 * when entering this function, so we can implement deferred VMA
1967 	 * destruction. Re-assign it here.
1968 	 */
1969 	vma->base.vm_bo = vm_bo;
1970 	list_add_tail(&vma->node, &vm->op_ctx->returned_vmas);
1971 }
1972 
1973 static void panthor_vma_init(struct panthor_vma *vma, u32 flags)
1974 {
1975 	INIT_LIST_HEAD(&vma->node);
1976 	vma->flags = flags;
1977 }
1978 
1979 #define PANTHOR_VM_MAP_FLAGS \
1980 	(DRM_PANTHOR_VM_BIND_OP_MAP_READONLY | \
1981 	 DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC | \
1982 	 DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED)
1983 
1984 static int panthor_gpuva_sm_step_map(struct drm_gpuva_op *op, void *priv)
1985 {
1986 	struct panthor_vm *vm = priv;
1987 	struct panthor_vm_op_ctx *op_ctx = vm->op_ctx;
1988 	struct panthor_vma *vma = panthor_vm_op_ctx_get_vma(op_ctx);
1989 	int ret;
1990 
1991 	if (!vma)
1992 		return -EINVAL;
1993 
1994 	panthor_vma_init(vma, op_ctx->flags & PANTHOR_VM_MAP_FLAGS);
1995 
1996 	ret = panthor_vm_map_pages(vm, op->map.va.addr, flags_to_prot(vma->flags),
1997 				   op_ctx->map.sgt, op->map.gem.offset,
1998 				   op->map.va.range);
1999 	if (ret)
2000 		return ret;
2001 
2002 	/* Ref owned by the mapping now, clear the obj field so we don't release the
2003 	 * pinning/obj ref behind GPUVA's back.
2004 	 */
2005 	drm_gpuva_map(&vm->base, &vma->base, &op->map);
2006 	panthor_vma_link(vm, vma, op_ctx->map.vm_bo);
2007 	op_ctx->map.vm_bo = NULL;
2008 	return 0;
2009 }
2010 
2011 static int panthor_gpuva_sm_step_remap(struct drm_gpuva_op *op,
2012 				       void *priv)
2013 {
2014 	struct panthor_vma *unmap_vma = container_of(op->remap.unmap->va, struct panthor_vma, base);
2015 	struct panthor_vm *vm = priv;
2016 	struct panthor_vm_op_ctx *op_ctx = vm->op_ctx;
2017 	struct panthor_vma *prev_vma = NULL, *next_vma = NULL;
2018 	u64 unmap_start, unmap_range;
2019 	int ret;
2020 
2021 	drm_gpuva_op_remap_to_unmap_range(&op->remap, &unmap_start, &unmap_range);
2022 	ret = panthor_vm_unmap_pages(vm, unmap_start, unmap_range);
2023 	if (ret)
2024 		return ret;
2025 
2026 	if (op->remap.prev) {
2027 		prev_vma = panthor_vm_op_ctx_get_vma(op_ctx);
2028 		panthor_vma_init(prev_vma, unmap_vma->flags);
2029 	}
2030 
2031 	if (op->remap.next) {
2032 		next_vma = panthor_vm_op_ctx_get_vma(op_ctx);
2033 		panthor_vma_init(next_vma, unmap_vma->flags);
2034 	}
2035 
2036 	drm_gpuva_remap(prev_vma ? &prev_vma->base : NULL,
2037 			next_vma ? &next_vma->base : NULL,
2038 			&op->remap);
2039 
2040 	if (prev_vma) {
2041 		/* panthor_vma_link() transfers the vm_bo ownership to
2042 		 * the VMA object. Since the vm_bo we're passing is still
2043 		 * owned by the old mapping which will be released when this
2044 		 * mapping is destroyed, we need to grab a ref here.
2045 		 */
2046 		panthor_vma_link(vm, prev_vma,
2047 				 drm_gpuvm_bo_get(op->remap.unmap->va->vm_bo));
2048 	}
2049 
2050 	if (next_vma) {
2051 		panthor_vma_link(vm, next_vma,
2052 				 drm_gpuvm_bo_get(op->remap.unmap->va->vm_bo));
2053 	}
2054 
2055 	panthor_vma_unlink(vm, unmap_vma);
2056 	return 0;
2057 }
2058 
2059 static int panthor_gpuva_sm_step_unmap(struct drm_gpuva_op *op,
2060 				       void *priv)
2061 {
2062 	struct panthor_vma *unmap_vma = container_of(op->unmap.va, struct panthor_vma, base);
2063 	struct panthor_vm *vm = priv;
2064 	int ret;
2065 
2066 	ret = panthor_vm_unmap_pages(vm, unmap_vma->base.va.addr,
2067 				     unmap_vma->base.va.range);
2068 	if (drm_WARN_ON(&vm->ptdev->base, ret))
2069 		return ret;
2070 
2071 	drm_gpuva_unmap(&op->unmap);
2072 	panthor_vma_unlink(vm, unmap_vma);
2073 	return 0;
2074 }
2075 
2076 static const struct drm_gpuvm_ops panthor_gpuvm_ops = {
2077 	.vm_free = panthor_vm_free,
2078 	.sm_step_map = panthor_gpuva_sm_step_map,
2079 	.sm_step_remap = panthor_gpuva_sm_step_remap,
2080 	.sm_step_unmap = panthor_gpuva_sm_step_unmap,
2081 };
2082 
2083 /**
2084  * panthor_vm_resv() - Get the dma_resv object attached to a VM.
2085  * @vm: VM to get the dma_resv of.
2086  *
2087  * Return: A dma_resv object.
2088  */
2089 struct dma_resv *panthor_vm_resv(struct panthor_vm *vm)
2090 {
2091 	return drm_gpuvm_resv(&vm->base);
2092 }
2093 
2094 struct drm_gem_object *panthor_vm_root_gem(struct panthor_vm *vm)
2095 {
2096 	if (!vm)
2097 		return NULL;
2098 
2099 	return vm->base.r_obj;
2100 }
2101 
2102 static int
2103 panthor_vm_exec_op(struct panthor_vm *vm, struct panthor_vm_op_ctx *op,
2104 		   bool flag_vm_unusable_on_failure)
2105 {
2106 	u32 op_type = op->flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK;
2107 	int ret;
2108 
2109 	if (op_type == DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY)
2110 		return 0;
2111 
2112 	mutex_lock(&vm->op_lock);
2113 	vm->op_ctx = op;
2114 	switch (op_type) {
2115 	case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP:
2116 		if (vm->unusable) {
2117 			ret = -EINVAL;
2118 			break;
2119 		}
2120 
2121 		ret = drm_gpuvm_sm_map(&vm->base, vm, op->va.addr, op->va.range,
2122 				       op->map.vm_bo->obj, op->map.bo_offset);
2123 		break;
2124 
2125 	case DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP:
2126 		ret = drm_gpuvm_sm_unmap(&vm->base, vm, op->va.addr, op->va.range);
2127 		break;
2128 
2129 	default:
2130 		ret = -EINVAL;
2131 		break;
2132 	}
2133 
2134 	if (ret && flag_vm_unusable_on_failure)
2135 		vm->unusable = true;
2136 
2137 	vm->op_ctx = NULL;
2138 	mutex_unlock(&vm->op_lock);
2139 
2140 	return ret;
2141 }
2142 
2143 static struct dma_fence *
2144 panthor_vm_bind_run_job(struct drm_sched_job *sched_job)
2145 {
2146 	struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2147 	bool cookie;
2148 	int ret;
2149 
2150 	/* Not only we report an error whose result is propagated to the
2151 	 * drm_sched finished fence, but we also flag the VM as unusable, because
2152 	 * a failure in the async VM_BIND results in an inconsistent state. VM needs
2153 	 * to be destroyed and recreated.
2154 	 */
2155 	cookie = dma_fence_begin_signalling();
2156 	ret = panthor_vm_exec_op(job->vm, &job->ctx, true);
2157 	dma_fence_end_signalling(cookie);
2158 
2159 	return ret ? ERR_PTR(ret) : NULL;
2160 }
2161 
2162 static void panthor_vm_bind_job_release(struct kref *kref)
2163 {
2164 	struct panthor_vm_bind_job *job = container_of(kref, struct panthor_vm_bind_job, refcount);
2165 
2166 	if (job->base.s_fence)
2167 		drm_sched_job_cleanup(&job->base);
2168 
2169 	panthor_vm_cleanup_op_ctx(&job->ctx, job->vm);
2170 	panthor_vm_put(job->vm);
2171 	kfree(job);
2172 }
2173 
2174 /**
2175  * panthor_vm_bind_job_put() - Release a VM_BIND job reference
2176  * @sched_job: Job to release the reference on.
2177  */
2178 void panthor_vm_bind_job_put(struct drm_sched_job *sched_job)
2179 {
2180 	struct panthor_vm_bind_job *job =
2181 		container_of(sched_job, struct panthor_vm_bind_job, base);
2182 
2183 	if (sched_job)
2184 		kref_put(&job->refcount, panthor_vm_bind_job_release);
2185 }
2186 
2187 static void
2188 panthor_vm_bind_free_job(struct drm_sched_job *sched_job)
2189 {
2190 	struct panthor_vm_bind_job *job =
2191 		container_of(sched_job, struct panthor_vm_bind_job, base);
2192 
2193 	drm_sched_job_cleanup(sched_job);
2194 
2195 	/* Do the heavy cleanups asynchronously, so we're out of the
2196 	 * dma-signaling path and can acquire dma-resv locks safely.
2197 	 */
2198 	queue_work(panthor_cleanup_wq, &job->cleanup_op_ctx_work);
2199 }
2200 
2201 static enum drm_gpu_sched_stat
2202 panthor_vm_bind_timedout_job(struct drm_sched_job *sched_job)
2203 {
2204 	WARN(1, "VM_BIND ops are synchronous for now, there should be no timeout!");
2205 	return DRM_GPU_SCHED_STAT_NOMINAL;
2206 }
2207 
2208 static const struct drm_sched_backend_ops panthor_vm_bind_ops = {
2209 	.run_job = panthor_vm_bind_run_job,
2210 	.free_job = panthor_vm_bind_free_job,
2211 	.timedout_job = panthor_vm_bind_timedout_job,
2212 };
2213 
2214 /**
2215  * panthor_vm_create() - Create a VM
2216  * @ptdev: Device.
2217  * @for_mcu: True if this is the FW MCU VM.
2218  * @kernel_va_start: Start of the range reserved for kernel BO mapping.
2219  * @kernel_va_size: Size of the range reserved for kernel BO mapping.
2220  * @auto_kernel_va_start: Start of the auto-VA kernel range.
2221  * @auto_kernel_va_size: Size of the auto-VA kernel range.
2222  *
2223  * Return: A valid pointer on success, an ERR_PTR() otherwise.
2224  */
2225 struct panthor_vm *
2226 panthor_vm_create(struct panthor_device *ptdev, bool for_mcu,
2227 		  u64 kernel_va_start, u64 kernel_va_size,
2228 		  u64 auto_kernel_va_start, u64 auto_kernel_va_size)
2229 {
2230 	u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
2231 	u32 pa_bits = GPU_MMU_FEATURES_PA_BITS(ptdev->gpu_info.mmu_features);
2232 	u64 full_va_range = 1ull << va_bits;
2233 	struct drm_gem_object *dummy_gem;
2234 	struct drm_gpu_scheduler *sched;
2235 	struct io_pgtable_cfg pgtbl_cfg;
2236 	u64 mair, min_va, va_range;
2237 	struct panthor_vm *vm;
2238 	int ret;
2239 
2240 	vm = kzalloc(sizeof(*vm), GFP_KERNEL);
2241 	if (!vm)
2242 		return ERR_PTR(-ENOMEM);
2243 
2244 	/* We allocate a dummy GEM for the VM. */
2245 	dummy_gem = drm_gpuvm_resv_object_alloc(&ptdev->base);
2246 	if (!dummy_gem) {
2247 		ret = -ENOMEM;
2248 		goto err_free_vm;
2249 	}
2250 
2251 	mutex_init(&vm->heaps.lock);
2252 	vm->for_mcu = for_mcu;
2253 	vm->ptdev = ptdev;
2254 	mutex_init(&vm->op_lock);
2255 
2256 	if (for_mcu) {
2257 		/* CSF MCU is a cortex M7, and can only address 4G */
2258 		min_va = 0;
2259 		va_range = SZ_4G;
2260 	} else {
2261 		min_va = 0;
2262 		va_range = full_va_range;
2263 	}
2264 
2265 	mutex_init(&vm->mm_lock);
2266 	drm_mm_init(&vm->mm, kernel_va_start, kernel_va_size);
2267 	vm->kernel_auto_va.start = auto_kernel_va_start;
2268 	vm->kernel_auto_va.end = vm->kernel_auto_va.start + auto_kernel_va_size - 1;
2269 
2270 	INIT_LIST_HEAD(&vm->node);
2271 	INIT_LIST_HEAD(&vm->as.lru_node);
2272 	vm->as.id = -1;
2273 	refcount_set(&vm->as.active_cnt, 0);
2274 
2275 	pgtbl_cfg = (struct io_pgtable_cfg) {
2276 		.pgsize_bitmap	= SZ_4K | SZ_2M,
2277 		.ias		= va_bits,
2278 		.oas		= pa_bits,
2279 		.coherent_walk	= ptdev->coherent,
2280 		.tlb		= &mmu_tlb_ops,
2281 		.iommu_dev	= ptdev->base.dev,
2282 		.alloc		= alloc_pt,
2283 		.free		= free_pt,
2284 	};
2285 
2286 	vm->pgtbl_ops = alloc_io_pgtable_ops(ARM_64_LPAE_S1, &pgtbl_cfg, vm);
2287 	if (!vm->pgtbl_ops) {
2288 		ret = -EINVAL;
2289 		goto err_mm_takedown;
2290 	}
2291 
2292 	/* Bind operations are synchronous for now, no timeout needed. */
2293 	ret = drm_sched_init(&vm->sched, &panthor_vm_bind_ops, ptdev->mmu->vm.wq,
2294 			     1, 1, 0,
2295 			     MAX_SCHEDULE_TIMEOUT, NULL, NULL,
2296 			     "panthor-vm-bind", ptdev->base.dev);
2297 	if (ret)
2298 		goto err_free_io_pgtable;
2299 
2300 	sched = &vm->sched;
2301 	ret = drm_sched_entity_init(&vm->entity, 0, &sched, 1, NULL);
2302 	if (ret)
2303 		goto err_sched_fini;
2304 
2305 	mair = io_pgtable_ops_to_pgtable(vm->pgtbl_ops)->cfg.arm_lpae_s1_cfg.mair;
2306 	vm->memattr = mair_to_memattr(mair);
2307 
2308 	mutex_lock(&ptdev->mmu->vm.lock);
2309 	list_add_tail(&vm->node, &ptdev->mmu->vm.list);
2310 
2311 	/* If a reset is in progress, stop the scheduler. */
2312 	if (ptdev->mmu->vm.reset_in_progress)
2313 		panthor_vm_stop(vm);
2314 	mutex_unlock(&ptdev->mmu->vm.lock);
2315 
2316 	/* We intentionally leave the reserved range to zero, because we want kernel VMAs
2317 	 * to be handled the same way user VMAs are.
2318 	 */
2319 	drm_gpuvm_init(&vm->base, for_mcu ? "panthor-MCU-VM" : "panthor-GPU-VM",
2320 		       DRM_GPUVM_RESV_PROTECTED, &ptdev->base, dummy_gem,
2321 		       min_va, va_range, 0, 0, &panthor_gpuvm_ops);
2322 	drm_gem_object_put(dummy_gem);
2323 	return vm;
2324 
2325 err_sched_fini:
2326 	drm_sched_fini(&vm->sched);
2327 
2328 err_free_io_pgtable:
2329 	free_io_pgtable_ops(vm->pgtbl_ops);
2330 
2331 err_mm_takedown:
2332 	drm_mm_takedown(&vm->mm);
2333 	drm_gem_object_put(dummy_gem);
2334 
2335 err_free_vm:
2336 	kfree(vm);
2337 	return ERR_PTR(ret);
2338 }
2339 
2340 static int
2341 panthor_vm_bind_prepare_op_ctx(struct drm_file *file,
2342 			       struct panthor_vm *vm,
2343 			       const struct drm_panthor_vm_bind_op *op,
2344 			       struct panthor_vm_op_ctx *op_ctx)
2345 {
2346 	struct drm_gem_object *gem;
2347 	int ret;
2348 
2349 	/* Aligned on page size. */
2350 	if ((op->va | op->size) & ~PAGE_MASK)
2351 		return -EINVAL;
2352 
2353 	switch (op->flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK) {
2354 	case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP:
2355 		gem = drm_gem_object_lookup(file, op->bo_handle);
2356 		ret = panthor_vm_prepare_map_op_ctx(op_ctx, vm,
2357 						    gem ? to_panthor_bo(gem) : NULL,
2358 						    op->bo_offset,
2359 						    op->size,
2360 						    op->va,
2361 						    op->flags);
2362 		drm_gem_object_put(gem);
2363 		return ret;
2364 
2365 	case DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP:
2366 		if (op->flags & ~DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
2367 			return -EINVAL;
2368 
2369 		if (op->bo_handle || op->bo_offset)
2370 			return -EINVAL;
2371 
2372 		return panthor_vm_prepare_unmap_op_ctx(op_ctx, vm, op->va, op->size);
2373 
2374 	case DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY:
2375 		if (op->flags & ~DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
2376 			return -EINVAL;
2377 
2378 		if (op->bo_handle || op->bo_offset)
2379 			return -EINVAL;
2380 
2381 		if (op->va || op->size)
2382 			return -EINVAL;
2383 
2384 		if (!op->syncs.count)
2385 			return -EINVAL;
2386 
2387 		panthor_vm_prepare_sync_only_op_ctx(op_ctx, vm);
2388 		return 0;
2389 
2390 	default:
2391 		return -EINVAL;
2392 	}
2393 }
2394 
2395 static void panthor_vm_bind_job_cleanup_op_ctx_work(struct work_struct *work)
2396 {
2397 	struct panthor_vm_bind_job *job =
2398 		container_of(work, struct panthor_vm_bind_job, cleanup_op_ctx_work);
2399 
2400 	panthor_vm_bind_job_put(&job->base);
2401 }
2402 
2403 /**
2404  * panthor_vm_bind_job_create() - Create a VM_BIND job
2405  * @file: File.
2406  * @vm: VM targeted by the VM_BIND job.
2407  * @op: VM operation data.
2408  *
2409  * Return: A valid pointer on success, an ERR_PTR() otherwise.
2410  */
2411 struct drm_sched_job *
2412 panthor_vm_bind_job_create(struct drm_file *file,
2413 			   struct panthor_vm *vm,
2414 			   const struct drm_panthor_vm_bind_op *op)
2415 {
2416 	struct panthor_vm_bind_job *job;
2417 	int ret;
2418 
2419 	if (!vm)
2420 		return ERR_PTR(-EINVAL);
2421 
2422 	if (vm->destroyed || vm->unusable)
2423 		return ERR_PTR(-EINVAL);
2424 
2425 	job = kzalloc(sizeof(*job), GFP_KERNEL);
2426 	if (!job)
2427 		return ERR_PTR(-ENOMEM);
2428 
2429 	ret = panthor_vm_bind_prepare_op_ctx(file, vm, op, &job->ctx);
2430 	if (ret) {
2431 		kfree(job);
2432 		return ERR_PTR(ret);
2433 	}
2434 
2435 	INIT_WORK(&job->cleanup_op_ctx_work, panthor_vm_bind_job_cleanup_op_ctx_work);
2436 	kref_init(&job->refcount);
2437 	job->vm = panthor_vm_get(vm);
2438 
2439 	ret = drm_sched_job_init(&job->base, &vm->entity, 1, vm);
2440 	if (ret)
2441 		goto err_put_job;
2442 
2443 	return &job->base;
2444 
2445 err_put_job:
2446 	panthor_vm_bind_job_put(&job->base);
2447 	return ERR_PTR(ret);
2448 }
2449 
2450 /**
2451  * panthor_vm_bind_job_prepare_resvs() - Prepare VM_BIND job dma_resvs
2452  * @exec: The locking/preparation context.
2453  * @sched_job: The job to prepare resvs on.
2454  *
2455  * Locks and prepare the VM resv.
2456  *
2457  * If this is a map operation, locks and prepares the GEM resv.
2458  *
2459  * Return: 0 on success, a negative error code otherwise.
2460  */
2461 int panthor_vm_bind_job_prepare_resvs(struct drm_exec *exec,
2462 				      struct drm_sched_job *sched_job)
2463 {
2464 	struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2465 	int ret;
2466 
2467 	/* Acquire the VM lock an reserve a slot for this VM bind job. */
2468 	ret = drm_gpuvm_prepare_vm(&job->vm->base, exec, 1);
2469 	if (ret)
2470 		return ret;
2471 
2472 	if (job->ctx.map.vm_bo) {
2473 		/* Lock/prepare the GEM being mapped. */
2474 		ret = drm_exec_prepare_obj(exec, job->ctx.map.vm_bo->obj, 1);
2475 		if (ret)
2476 			return ret;
2477 	}
2478 
2479 	return 0;
2480 }
2481 
2482 /**
2483  * panthor_vm_bind_job_update_resvs() - Update the resv objects touched by a job
2484  * @exec: drm_exec context.
2485  * @sched_job: Job to update the resvs on.
2486  */
2487 void panthor_vm_bind_job_update_resvs(struct drm_exec *exec,
2488 				      struct drm_sched_job *sched_job)
2489 {
2490 	struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2491 
2492 	/* Explicit sync => we just register our job finished fence as bookkeep. */
2493 	drm_gpuvm_resv_add_fence(&job->vm->base, exec,
2494 				 &sched_job->s_fence->finished,
2495 				 DMA_RESV_USAGE_BOOKKEEP,
2496 				 DMA_RESV_USAGE_BOOKKEEP);
2497 }
2498 
2499 void panthor_vm_update_resvs(struct panthor_vm *vm, struct drm_exec *exec,
2500 			     struct dma_fence *fence,
2501 			     enum dma_resv_usage private_usage,
2502 			     enum dma_resv_usage extobj_usage)
2503 {
2504 	drm_gpuvm_resv_add_fence(&vm->base, exec, fence, private_usage, extobj_usage);
2505 }
2506 
2507 /**
2508  * panthor_vm_bind_exec_sync_op() - Execute a VM_BIND operation synchronously.
2509  * @file: File.
2510  * @vm: VM targeted by the VM operation.
2511  * @op: Data describing the VM operation.
2512  *
2513  * Return: 0 on success, a negative error code otherwise.
2514  */
2515 int panthor_vm_bind_exec_sync_op(struct drm_file *file,
2516 				 struct panthor_vm *vm,
2517 				 struct drm_panthor_vm_bind_op *op)
2518 {
2519 	struct panthor_vm_op_ctx op_ctx;
2520 	int ret;
2521 
2522 	/* No sync objects allowed on synchronous operations. */
2523 	if (op->syncs.count)
2524 		return -EINVAL;
2525 
2526 	if (!op->size)
2527 		return 0;
2528 
2529 	ret = panthor_vm_bind_prepare_op_ctx(file, vm, op, &op_ctx);
2530 	if (ret)
2531 		return ret;
2532 
2533 	ret = panthor_vm_exec_op(vm, &op_ctx, false);
2534 	panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2535 
2536 	return ret;
2537 }
2538 
2539 /**
2540  * panthor_vm_map_bo_range() - Map a GEM object range to a VM
2541  * @vm: VM to map the GEM to.
2542  * @bo: GEM object to map.
2543  * @offset: Offset in the GEM object.
2544  * @size: Size to map.
2545  * @va: Virtual address to map the object to.
2546  * @flags: Combination of drm_panthor_vm_bind_op_flags flags.
2547  * Only map-related flags are valid.
2548  *
2549  * Internal use only. For userspace requests, use
2550  * panthor_vm_bind_exec_sync_op() instead.
2551  *
2552  * Return: 0 on success, a negative error code otherwise.
2553  */
2554 int panthor_vm_map_bo_range(struct panthor_vm *vm, struct panthor_gem_object *bo,
2555 			    u64 offset, u64 size, u64 va, u32 flags)
2556 {
2557 	struct panthor_vm_op_ctx op_ctx;
2558 	int ret;
2559 
2560 	ret = panthor_vm_prepare_map_op_ctx(&op_ctx, vm, bo, offset, size, va, flags);
2561 	if (ret)
2562 		return ret;
2563 
2564 	ret = panthor_vm_exec_op(vm, &op_ctx, false);
2565 	panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2566 
2567 	return ret;
2568 }
2569 
2570 /**
2571  * panthor_vm_unmap_range() - Unmap a portion of the VA space
2572  * @vm: VM to unmap the region from.
2573  * @va: Virtual address to unmap. Must be 4k aligned.
2574  * @size: Size of the region to unmap. Must be 4k aligned.
2575  *
2576  * Internal use only. For userspace requests, use
2577  * panthor_vm_bind_exec_sync_op() instead.
2578  *
2579  * Return: 0 on success, a negative error code otherwise.
2580  */
2581 int panthor_vm_unmap_range(struct panthor_vm *vm, u64 va, u64 size)
2582 {
2583 	struct panthor_vm_op_ctx op_ctx;
2584 	int ret;
2585 
2586 	ret = panthor_vm_prepare_unmap_op_ctx(&op_ctx, vm, va, size);
2587 	if (ret)
2588 		return ret;
2589 
2590 	ret = panthor_vm_exec_op(vm, &op_ctx, false);
2591 	panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2592 
2593 	return ret;
2594 }
2595 
2596 /**
2597  * panthor_vm_prepare_mapped_bos_resvs() - Prepare resvs on VM BOs.
2598  * @exec: Locking/preparation context.
2599  * @vm: VM targeted by the GPU job.
2600  * @slot_count: Number of slots to reserve.
2601  *
2602  * GPU jobs assume all BOs bound to the VM at the time the job is submitted
2603  * are available when the job is executed. In order to guarantee that, we
2604  * need to reserve a slot on all BOs mapped to a VM and update this slot with
2605  * the job fence after its submission.
2606  *
2607  * Return: 0 on success, a negative error code otherwise.
2608  */
2609 int panthor_vm_prepare_mapped_bos_resvs(struct drm_exec *exec, struct panthor_vm *vm,
2610 					u32 slot_count)
2611 {
2612 	int ret;
2613 
2614 	/* Acquire the VM lock and reserve a slot for this GPU job. */
2615 	ret = drm_gpuvm_prepare_vm(&vm->base, exec, slot_count);
2616 	if (ret)
2617 		return ret;
2618 
2619 	return drm_gpuvm_prepare_objects(&vm->base, exec, slot_count);
2620 }
2621 
2622 /**
2623  * panthor_mmu_unplug() - Unplug the MMU logic
2624  * @ptdev: Device.
2625  *
2626  * No access to the MMU regs should be done after this function is called.
2627  * We suspend the IRQ and disable all VMs to guarantee that.
2628  */
2629 void panthor_mmu_unplug(struct panthor_device *ptdev)
2630 {
2631 	panthor_mmu_irq_suspend(&ptdev->mmu->irq);
2632 
2633 	mutex_lock(&ptdev->mmu->as.slots_lock);
2634 	for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
2635 		struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
2636 
2637 		if (vm) {
2638 			drm_WARN_ON(&ptdev->base, panthor_mmu_as_disable(ptdev, i));
2639 			panthor_vm_release_as_locked(vm);
2640 		}
2641 	}
2642 	mutex_unlock(&ptdev->mmu->as.slots_lock);
2643 }
2644 
2645 static void panthor_mmu_release_wq(struct drm_device *ddev, void *res)
2646 {
2647 	destroy_workqueue(res);
2648 }
2649 
2650 /**
2651  * panthor_mmu_init() - Initialize the MMU logic.
2652  * @ptdev: Device.
2653  *
2654  * Return: 0 on success, a negative error code otherwise.
2655  */
2656 int panthor_mmu_init(struct panthor_device *ptdev)
2657 {
2658 	u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
2659 	struct panthor_mmu *mmu;
2660 	int ret, irq;
2661 
2662 	mmu = drmm_kzalloc(&ptdev->base, sizeof(*mmu), GFP_KERNEL);
2663 	if (!mmu)
2664 		return -ENOMEM;
2665 
2666 	INIT_LIST_HEAD(&mmu->as.lru_list);
2667 
2668 	ret = drmm_mutex_init(&ptdev->base, &mmu->as.slots_lock);
2669 	if (ret)
2670 		return ret;
2671 
2672 	INIT_LIST_HEAD(&mmu->vm.list);
2673 	ret = drmm_mutex_init(&ptdev->base, &mmu->vm.lock);
2674 	if (ret)
2675 		return ret;
2676 
2677 	ptdev->mmu = mmu;
2678 
2679 	irq = platform_get_irq_byname(to_platform_device(ptdev->base.dev), "mmu");
2680 	if (irq <= 0)
2681 		return -ENODEV;
2682 
2683 	ret = panthor_request_mmu_irq(ptdev, &mmu->irq, irq,
2684 				      panthor_mmu_fault_mask(ptdev, ~0));
2685 	if (ret)
2686 		return ret;
2687 
2688 	mmu->vm.wq = alloc_workqueue("panthor-vm-bind", WQ_UNBOUND, 0);
2689 	if (!mmu->vm.wq)
2690 		return -ENOMEM;
2691 
2692 	/* On 32-bit kernels, the VA space is limited by the io_pgtable_ops abstraction,
2693 	 * which passes iova as an unsigned long. Patch the mmu_features to reflect this
2694 	 * limitation.
2695 	 */
2696 	if (sizeof(unsigned long) * 8 < va_bits) {
2697 		ptdev->gpu_info.mmu_features &= ~GENMASK(7, 0);
2698 		ptdev->gpu_info.mmu_features |= sizeof(unsigned long) * 8;
2699 	}
2700 
2701 	return drmm_add_action_or_reset(&ptdev->base, panthor_mmu_release_wq, mmu->vm.wq);
2702 }
2703 
2704 #ifdef CONFIG_DEBUG_FS
2705 static int show_vm_gpuvas(struct panthor_vm *vm, struct seq_file *m)
2706 {
2707 	int ret;
2708 
2709 	mutex_lock(&vm->op_lock);
2710 	ret = drm_debugfs_gpuva_info(m, &vm->base);
2711 	mutex_unlock(&vm->op_lock);
2712 
2713 	return ret;
2714 }
2715 
2716 static int show_each_vm(struct seq_file *m, void *arg)
2717 {
2718 	struct drm_info_node *node = (struct drm_info_node *)m->private;
2719 	struct drm_device *ddev = node->minor->dev;
2720 	struct panthor_device *ptdev = container_of(ddev, struct panthor_device, base);
2721 	int (*show)(struct panthor_vm *, struct seq_file *) = node->info_ent->data;
2722 	struct panthor_vm *vm;
2723 	int ret = 0;
2724 
2725 	mutex_lock(&ptdev->mmu->vm.lock);
2726 	list_for_each_entry(vm, &ptdev->mmu->vm.list, node) {
2727 		ret = show(vm, m);
2728 		if (ret < 0)
2729 			break;
2730 
2731 		seq_puts(m, "\n");
2732 	}
2733 	mutex_unlock(&ptdev->mmu->vm.lock);
2734 
2735 	return ret;
2736 }
2737 
2738 static struct drm_info_list panthor_mmu_debugfs_list[] = {
2739 	DRM_DEBUGFS_GPUVA_INFO(show_each_vm, show_vm_gpuvas),
2740 };
2741 
2742 /**
2743  * panthor_mmu_debugfs_init() - Initialize MMU debugfs entries
2744  * @minor: Minor.
2745  */
2746 void panthor_mmu_debugfs_init(struct drm_minor *minor)
2747 {
2748 	drm_debugfs_create_files(panthor_mmu_debugfs_list,
2749 				 ARRAY_SIZE(panthor_mmu_debugfs_list),
2750 				 minor->debugfs_root, minor);
2751 }
2752 #endif /* CONFIG_DEBUG_FS */
2753 
2754 /**
2755  * panthor_mmu_pt_cache_init() - Initialize the page table cache.
2756  *
2757  * Return: 0 on success, a negative error code otherwise.
2758  */
2759 int panthor_mmu_pt_cache_init(void)
2760 {
2761 	pt_cache = kmem_cache_create("panthor-mmu-pt", SZ_4K, SZ_4K, 0, NULL);
2762 	if (!pt_cache)
2763 		return -ENOMEM;
2764 
2765 	return 0;
2766 }
2767 
2768 /**
2769  * panthor_mmu_pt_cache_fini() - Destroy the page table cache.
2770  */
2771 void panthor_mmu_pt_cache_fini(void)
2772 {
2773 	kmem_cache_destroy(pt_cache);
2774 }
2775