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