xref: /linux/drivers/gpu/drm/panthor/panthor_mmu.c (revision 09b1704f5b02c18dd02b21343530463fcfc92c54)
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 		/* Two VMAs can be needed for an unmap, as an unmap can happen
1179 		 * in the middle of a drm_gpuva, requiring a remap with both
1180 		 * prev & next VA. Or an unmap can span more than one drm_gpuva
1181 		 * where the first and last ones are covered partially, requring
1182 		 * a remap for the first with a prev VA and remap for the last
1183 		 * with a next VA.
1184 		 */
1185 		vma_count = 2;
1186 		break;
1187 
1188 	default:
1189 		return 0;
1190 	}
1191 
1192 	for (u32 i = 0; i < vma_count; i++) {
1193 		struct panthor_vma *vma = kzalloc(sizeof(*vma), GFP_KERNEL);
1194 
1195 		if (!vma)
1196 			return -ENOMEM;
1197 
1198 		op_ctx->preallocated_vmas[i] = vma;
1199 	}
1200 
1201 	return 0;
1202 }
1203 
1204 #define PANTHOR_VM_BIND_OP_MAP_FLAGS \
1205 	(DRM_PANTHOR_VM_BIND_OP_MAP_READONLY | \
1206 	 DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC | \
1207 	 DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED | \
1208 	 DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
1209 
1210 static int panthor_vm_prepare_map_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1211 					 struct panthor_vm *vm,
1212 					 struct panthor_gem_object *bo,
1213 					 u64 offset,
1214 					 u64 size, u64 va,
1215 					 u32 flags)
1216 {
1217 	struct drm_gpuvm_bo *preallocated_vm_bo;
1218 	struct sg_table *sgt = NULL;
1219 	u64 pt_count;
1220 	int ret;
1221 
1222 	if (!bo)
1223 		return -EINVAL;
1224 
1225 	if ((flags & ~PANTHOR_VM_BIND_OP_MAP_FLAGS) ||
1226 	    (flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK) != DRM_PANTHOR_VM_BIND_OP_TYPE_MAP)
1227 		return -EINVAL;
1228 
1229 	/* Make sure the VA and size are in-bounds. */
1230 	if (size > bo->base.base.size || offset > bo->base.base.size - size)
1231 		return -EINVAL;
1232 
1233 	/* If the BO has an exclusive VM attached, it can't be mapped to other VMs. */
1234 	if (bo->exclusive_vm_root_gem &&
1235 	    bo->exclusive_vm_root_gem != panthor_vm_root_gem(vm))
1236 		return -EINVAL;
1237 
1238 	memset(op_ctx, 0, sizeof(*op_ctx));
1239 	INIT_LIST_HEAD(&op_ctx->returned_vmas);
1240 	op_ctx->flags = flags;
1241 	op_ctx->va.range = size;
1242 	op_ctx->va.addr = va;
1243 
1244 	ret = panthor_vm_op_ctx_prealloc_vmas(op_ctx);
1245 	if (ret)
1246 		goto err_cleanup;
1247 
1248 	if (!drm_gem_is_imported(&bo->base.base)) {
1249 		/* Pre-reserve the BO pages, so the map operation doesn't have to
1250 		 * allocate.
1251 		 */
1252 		ret = drm_gem_shmem_pin(&bo->base);
1253 		if (ret)
1254 			goto err_cleanup;
1255 	}
1256 
1257 	sgt = drm_gem_shmem_get_pages_sgt(&bo->base);
1258 	if (IS_ERR(sgt)) {
1259 		if (!drm_gem_is_imported(&bo->base.base))
1260 			drm_gem_shmem_unpin(&bo->base);
1261 
1262 		ret = PTR_ERR(sgt);
1263 		goto err_cleanup;
1264 	}
1265 
1266 	op_ctx->map.sgt = sgt;
1267 
1268 	preallocated_vm_bo = drm_gpuvm_bo_create(&vm->base, &bo->base.base);
1269 	if (!preallocated_vm_bo) {
1270 		if (!drm_gem_is_imported(&bo->base.base))
1271 			drm_gem_shmem_unpin(&bo->base);
1272 
1273 		ret = -ENOMEM;
1274 		goto err_cleanup;
1275 	}
1276 
1277 	/* drm_gpuvm_bo_obtain_prealloc() will call drm_gpuvm_bo_put() on our
1278 	 * pre-allocated BO if the <BO,VM> association exists. Given we
1279 	 * only have one ref on preallocated_vm_bo, drm_gpuvm_bo_destroy() will
1280 	 * be called immediately, and we have to hold the VM resv lock when
1281 	 * calling this function.
1282 	 */
1283 	dma_resv_lock(panthor_vm_resv(vm), NULL);
1284 	mutex_lock(&bo->base.base.gpuva.lock);
1285 	op_ctx->map.vm_bo = drm_gpuvm_bo_obtain_prealloc(preallocated_vm_bo);
1286 	mutex_unlock(&bo->base.base.gpuva.lock);
1287 	dma_resv_unlock(panthor_vm_resv(vm));
1288 
1289 	/* If the a vm_bo for this <VM,BO> combination exists, it already
1290 	 * retains a pin ref, and we can release the one we took earlier.
1291 	 *
1292 	 * If our pre-allocated vm_bo is picked, it now retains the pin ref,
1293 	 * which will be released in panthor_vm_bo_put().
1294 	 */
1295 	if (preallocated_vm_bo != op_ctx->map.vm_bo &&
1296 	    !drm_gem_is_imported(&bo->base.base))
1297 		drm_gem_shmem_unpin(&bo->base);
1298 
1299 	op_ctx->map.bo_offset = offset;
1300 
1301 	/* L1, L2 and L3 page tables.
1302 	 * We could optimize L3 allocation by iterating over the sgt and merging
1303 	 * 2M contiguous blocks, but it's simpler to over-provision and return
1304 	 * the pages if they're not used.
1305 	 */
1306 	pt_count = ((ALIGN(va + size, 1ull << 39) - ALIGN_DOWN(va, 1ull << 39)) >> 39) +
1307 		   ((ALIGN(va + size, 1ull << 30) - ALIGN_DOWN(va, 1ull << 30)) >> 30) +
1308 		   ((ALIGN(va + size, 1ull << 21) - ALIGN_DOWN(va, 1ull << 21)) >> 21);
1309 
1310 	op_ctx->rsvd_page_tables.pages = kcalloc(pt_count,
1311 						 sizeof(*op_ctx->rsvd_page_tables.pages),
1312 						 GFP_KERNEL);
1313 	if (!op_ctx->rsvd_page_tables.pages) {
1314 		ret = -ENOMEM;
1315 		goto err_cleanup;
1316 	}
1317 
1318 	ret = kmem_cache_alloc_bulk(pt_cache, GFP_KERNEL, pt_count,
1319 				    op_ctx->rsvd_page_tables.pages);
1320 	op_ctx->rsvd_page_tables.count = ret;
1321 	if (ret != pt_count) {
1322 		ret = -ENOMEM;
1323 		goto err_cleanup;
1324 	}
1325 
1326 	/* Insert BO into the extobj list last, when we know nothing can fail. */
1327 	dma_resv_lock(panthor_vm_resv(vm), NULL);
1328 	drm_gpuvm_bo_extobj_add(op_ctx->map.vm_bo);
1329 	dma_resv_unlock(panthor_vm_resv(vm));
1330 
1331 	return 0;
1332 
1333 err_cleanup:
1334 	panthor_vm_cleanup_op_ctx(op_ctx, vm);
1335 	return ret;
1336 }
1337 
1338 static int panthor_vm_prepare_unmap_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1339 					   struct panthor_vm *vm,
1340 					   u64 va, u64 size)
1341 {
1342 	u32 pt_count = 0;
1343 	int ret;
1344 
1345 	memset(op_ctx, 0, sizeof(*op_ctx));
1346 	INIT_LIST_HEAD(&op_ctx->returned_vmas);
1347 	op_ctx->va.range = size;
1348 	op_ctx->va.addr = va;
1349 	op_ctx->flags = DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP;
1350 
1351 	/* Pre-allocate L3 page tables to account for the split-2M-block
1352 	 * situation on unmap.
1353 	 */
1354 	if (va != ALIGN(va, SZ_2M))
1355 		pt_count++;
1356 
1357 	if (va + size != ALIGN(va + size, SZ_2M) &&
1358 	    ALIGN(va + size, SZ_2M) != ALIGN(va, SZ_2M))
1359 		pt_count++;
1360 
1361 	ret = panthor_vm_op_ctx_prealloc_vmas(op_ctx);
1362 	if (ret)
1363 		goto err_cleanup;
1364 
1365 	if (pt_count) {
1366 		op_ctx->rsvd_page_tables.pages = kcalloc(pt_count,
1367 							 sizeof(*op_ctx->rsvd_page_tables.pages),
1368 							 GFP_KERNEL);
1369 		if (!op_ctx->rsvd_page_tables.pages) {
1370 			ret = -ENOMEM;
1371 			goto err_cleanup;
1372 		}
1373 
1374 		ret = kmem_cache_alloc_bulk(pt_cache, GFP_KERNEL, pt_count,
1375 					    op_ctx->rsvd_page_tables.pages);
1376 		if (ret != pt_count) {
1377 			ret = -ENOMEM;
1378 			goto err_cleanup;
1379 		}
1380 		op_ctx->rsvd_page_tables.count = pt_count;
1381 	}
1382 
1383 	return 0;
1384 
1385 err_cleanup:
1386 	panthor_vm_cleanup_op_ctx(op_ctx, vm);
1387 	return ret;
1388 }
1389 
1390 static void panthor_vm_prepare_sync_only_op_ctx(struct panthor_vm_op_ctx *op_ctx,
1391 						struct panthor_vm *vm)
1392 {
1393 	memset(op_ctx, 0, sizeof(*op_ctx));
1394 	INIT_LIST_HEAD(&op_ctx->returned_vmas);
1395 	op_ctx->flags = DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY;
1396 }
1397 
1398 /**
1399  * panthor_vm_get_bo_for_va() - Get the GEM object mapped at a virtual address
1400  * @vm: VM to look into.
1401  * @va: Virtual address to search for.
1402  * @bo_offset: Offset of the GEM object mapped at this virtual address.
1403  * Only valid on success.
1404  *
1405  * The object returned by this function might no longer be mapped when the
1406  * function returns. It's the caller responsibility to ensure there's no
1407  * concurrent map/unmap operations making the returned value invalid, or
1408  * make sure it doesn't matter if the object is no longer mapped.
1409  *
1410  * Return: A valid pointer on success, an ERR_PTR() otherwise.
1411  */
1412 struct panthor_gem_object *
1413 panthor_vm_get_bo_for_va(struct panthor_vm *vm, u64 va, u64 *bo_offset)
1414 {
1415 	struct panthor_gem_object *bo = ERR_PTR(-ENOENT);
1416 	struct drm_gpuva *gpuva;
1417 	struct panthor_vma *vma;
1418 
1419 	/* Take the VM lock to prevent concurrent map/unmap operations. */
1420 	mutex_lock(&vm->op_lock);
1421 	gpuva = drm_gpuva_find_first(&vm->base, va, 1);
1422 	vma = gpuva ? container_of(gpuva, struct panthor_vma, base) : NULL;
1423 	if (vma && vma->base.gem.obj) {
1424 		drm_gem_object_get(vma->base.gem.obj);
1425 		bo = to_panthor_bo(vma->base.gem.obj);
1426 		*bo_offset = vma->base.gem.offset + (va - vma->base.va.addr);
1427 	}
1428 	mutex_unlock(&vm->op_lock);
1429 
1430 	return bo;
1431 }
1432 
1433 #define PANTHOR_VM_MIN_KERNEL_VA_SIZE	SZ_256M
1434 
1435 static u64
1436 panthor_vm_create_get_user_va_range(const struct drm_panthor_vm_create *args,
1437 				    u64 full_va_range)
1438 {
1439 	u64 user_va_range;
1440 
1441 	/* Make sure we have a minimum amount of VA space for kernel objects. */
1442 	if (full_va_range < PANTHOR_VM_MIN_KERNEL_VA_SIZE)
1443 		return 0;
1444 
1445 	if (args->user_va_range) {
1446 		/* Use the user provided value if != 0. */
1447 		user_va_range = args->user_va_range;
1448 	} else if (TASK_SIZE_OF(current) < full_va_range) {
1449 		/* If the task VM size is smaller than the GPU VA range, pick this
1450 		 * as our default user VA range, so userspace can CPU/GPU map buffers
1451 		 * at the same address.
1452 		 */
1453 		user_va_range = TASK_SIZE_OF(current);
1454 	} else {
1455 		/* If the GPU VA range is smaller than the task VM size, we
1456 		 * just have to live with the fact we won't be able to map
1457 		 * all buffers at the same GPU/CPU address.
1458 		 *
1459 		 * If the GPU VA range is bigger than 4G (more than 32-bit of
1460 		 * VA), we split the range in two, and assign half of it to
1461 		 * the user and the other half to the kernel, if it's not, we
1462 		 * keep the kernel VA space as small as possible.
1463 		 */
1464 		user_va_range = full_va_range > SZ_4G ?
1465 				full_va_range / 2 :
1466 				full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE;
1467 	}
1468 
1469 	if (full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE < user_va_range)
1470 		user_va_range = full_va_range - PANTHOR_VM_MIN_KERNEL_VA_SIZE;
1471 
1472 	return user_va_range;
1473 }
1474 
1475 #define PANTHOR_VM_CREATE_FLAGS		0
1476 
1477 static int
1478 panthor_vm_create_check_args(const struct panthor_device *ptdev,
1479 			     const struct drm_panthor_vm_create *args,
1480 			     u64 *kernel_va_start, u64 *kernel_va_range)
1481 {
1482 	u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
1483 	u64 full_va_range = 1ull << va_bits;
1484 	u64 user_va_range;
1485 
1486 	if (args->flags & ~PANTHOR_VM_CREATE_FLAGS)
1487 		return -EINVAL;
1488 
1489 	user_va_range = panthor_vm_create_get_user_va_range(args, full_va_range);
1490 	if (!user_va_range || (args->user_va_range && args->user_va_range > user_va_range))
1491 		return -EINVAL;
1492 
1493 	/* Pick a kernel VA range that's a power of two, to have a clear split. */
1494 	*kernel_va_range = rounddown_pow_of_two(full_va_range - user_va_range);
1495 	*kernel_va_start = full_va_range - *kernel_va_range;
1496 	return 0;
1497 }
1498 
1499 /*
1500  * Only 32 VMs per open file. If that becomes a limiting factor, we can
1501  * increase this number.
1502  */
1503 #define PANTHOR_MAX_VMS_PER_FILE	32
1504 
1505 /**
1506  * panthor_vm_pool_create_vm() - Create a VM
1507  * @ptdev: The panthor device
1508  * @pool: The VM to create this VM on.
1509  * @args: VM creation args.
1510  *
1511  * Return: a positive VM ID on success, a negative error code otherwise.
1512  */
1513 int panthor_vm_pool_create_vm(struct panthor_device *ptdev,
1514 			      struct panthor_vm_pool *pool,
1515 			      struct drm_panthor_vm_create *args)
1516 {
1517 	u64 kernel_va_start, kernel_va_range;
1518 	struct panthor_vm *vm;
1519 	int ret;
1520 	u32 id;
1521 
1522 	ret = panthor_vm_create_check_args(ptdev, args, &kernel_va_start, &kernel_va_range);
1523 	if (ret)
1524 		return ret;
1525 
1526 	vm = panthor_vm_create(ptdev, false, kernel_va_start, kernel_va_range,
1527 			       kernel_va_start, kernel_va_range);
1528 	if (IS_ERR(vm))
1529 		return PTR_ERR(vm);
1530 
1531 	ret = xa_alloc(&pool->xa, &id, vm,
1532 		       XA_LIMIT(1, PANTHOR_MAX_VMS_PER_FILE), GFP_KERNEL);
1533 
1534 	if (ret) {
1535 		panthor_vm_put(vm);
1536 		return ret;
1537 	}
1538 
1539 	args->user_va_range = kernel_va_start;
1540 	return id;
1541 }
1542 
1543 static void panthor_vm_destroy(struct panthor_vm *vm)
1544 {
1545 	if (!vm)
1546 		return;
1547 
1548 	vm->destroyed = true;
1549 
1550 	mutex_lock(&vm->heaps.lock);
1551 	panthor_heap_pool_destroy(vm->heaps.pool);
1552 	vm->heaps.pool = NULL;
1553 	mutex_unlock(&vm->heaps.lock);
1554 
1555 	drm_WARN_ON(&vm->ptdev->base,
1556 		    panthor_vm_unmap_range(vm, vm->base.mm_start, vm->base.mm_range));
1557 	panthor_vm_put(vm);
1558 }
1559 
1560 /**
1561  * panthor_vm_pool_destroy_vm() - Destroy a VM.
1562  * @pool: VM pool.
1563  * @handle: VM handle.
1564  *
1565  * This function doesn't free the VM object or its resources, it just kills
1566  * all mappings, and makes sure nothing can be mapped after that point.
1567  *
1568  * If there was any active jobs at the time this function is called, these
1569  * jobs should experience page faults and be killed as a result.
1570  *
1571  * The VM resources are freed when the last reference on the VM object is
1572  * dropped.
1573  *
1574  * Return: %0 for success, negative errno value for failure
1575  */
1576 int panthor_vm_pool_destroy_vm(struct panthor_vm_pool *pool, u32 handle)
1577 {
1578 	struct panthor_vm *vm;
1579 
1580 	vm = xa_erase(&pool->xa, handle);
1581 
1582 	panthor_vm_destroy(vm);
1583 
1584 	return vm ? 0 : -EINVAL;
1585 }
1586 
1587 /**
1588  * panthor_vm_pool_get_vm() - Retrieve VM object bound to a VM handle
1589  * @pool: VM pool to check.
1590  * @handle: Handle of the VM to retrieve.
1591  *
1592  * Return: A valid pointer if the VM exists, NULL otherwise.
1593  */
1594 struct panthor_vm *
1595 panthor_vm_pool_get_vm(struct panthor_vm_pool *pool, u32 handle)
1596 {
1597 	struct panthor_vm *vm;
1598 
1599 	xa_lock(&pool->xa);
1600 	vm = panthor_vm_get(xa_load(&pool->xa, handle));
1601 	xa_unlock(&pool->xa);
1602 
1603 	return vm;
1604 }
1605 
1606 /**
1607  * panthor_vm_pool_destroy() - Destroy a VM pool.
1608  * @pfile: File.
1609  *
1610  * Destroy all VMs in the pool, and release the pool resources.
1611  *
1612  * Note that VMs can outlive the pool they were created from if other
1613  * objects hold a reference to there VMs.
1614  */
1615 void panthor_vm_pool_destroy(struct panthor_file *pfile)
1616 {
1617 	struct panthor_vm *vm;
1618 	unsigned long i;
1619 
1620 	if (!pfile->vms)
1621 		return;
1622 
1623 	xa_for_each(&pfile->vms->xa, i, vm)
1624 		panthor_vm_destroy(vm);
1625 
1626 	xa_destroy(&pfile->vms->xa);
1627 	kfree(pfile->vms);
1628 }
1629 
1630 /**
1631  * panthor_vm_pool_create() - Create a VM pool
1632  * @pfile: File.
1633  *
1634  * Return: 0 on success, a negative error code otherwise.
1635  */
1636 int panthor_vm_pool_create(struct panthor_file *pfile)
1637 {
1638 	pfile->vms = kzalloc(sizeof(*pfile->vms), GFP_KERNEL);
1639 	if (!pfile->vms)
1640 		return -ENOMEM;
1641 
1642 	xa_init_flags(&pfile->vms->xa, XA_FLAGS_ALLOC1);
1643 	return 0;
1644 }
1645 
1646 /* dummy TLB ops, the real TLB flush happens in panthor_vm_flush_range() */
1647 static void mmu_tlb_flush_all(void *cookie)
1648 {
1649 }
1650 
1651 static void mmu_tlb_flush_walk(unsigned long iova, size_t size, size_t granule, void *cookie)
1652 {
1653 }
1654 
1655 static const struct iommu_flush_ops mmu_tlb_ops = {
1656 	.tlb_flush_all = mmu_tlb_flush_all,
1657 	.tlb_flush_walk = mmu_tlb_flush_walk,
1658 };
1659 
1660 static const char *access_type_name(struct panthor_device *ptdev,
1661 				    u32 fault_status)
1662 {
1663 	switch (fault_status & AS_FAULTSTATUS_ACCESS_TYPE_MASK) {
1664 	case AS_FAULTSTATUS_ACCESS_TYPE_ATOMIC:
1665 		return "ATOMIC";
1666 	case AS_FAULTSTATUS_ACCESS_TYPE_READ:
1667 		return "READ";
1668 	case AS_FAULTSTATUS_ACCESS_TYPE_WRITE:
1669 		return "WRITE";
1670 	case AS_FAULTSTATUS_ACCESS_TYPE_EX:
1671 		return "EXECUTE";
1672 	default:
1673 		drm_WARN_ON(&ptdev->base, 1);
1674 		return NULL;
1675 	}
1676 }
1677 
1678 static void panthor_mmu_irq_handler(struct panthor_device *ptdev, u32 status)
1679 {
1680 	bool has_unhandled_faults = false;
1681 
1682 	status = panthor_mmu_fault_mask(ptdev, status);
1683 	while (status) {
1684 		u32 as = ffs(status | (status >> 16)) - 1;
1685 		u32 mask = panthor_mmu_as_fault_mask(ptdev, as);
1686 		u32 new_int_mask;
1687 		u64 addr;
1688 		u32 fault_status;
1689 		u32 exception_type;
1690 		u32 access_type;
1691 		u32 source_id;
1692 
1693 		fault_status = gpu_read(ptdev, AS_FAULTSTATUS(as));
1694 		addr = gpu_read64(ptdev, AS_FAULTADDRESS(as));
1695 
1696 		/* decode the fault status */
1697 		exception_type = fault_status & 0xFF;
1698 		access_type = (fault_status >> 8) & 0x3;
1699 		source_id = (fault_status >> 16);
1700 
1701 		mutex_lock(&ptdev->mmu->as.slots_lock);
1702 
1703 		ptdev->mmu->as.faulty_mask |= mask;
1704 		new_int_mask =
1705 			panthor_mmu_fault_mask(ptdev, ~ptdev->mmu->as.faulty_mask);
1706 
1707 		/* terminal fault, print info about the fault */
1708 		drm_err(&ptdev->base,
1709 			"Unhandled Page fault in AS%d at VA 0x%016llX\n"
1710 			"raw fault status: 0x%X\n"
1711 			"decoded fault status: %s\n"
1712 			"exception type 0x%X: %s\n"
1713 			"access type 0x%X: %s\n"
1714 			"source id 0x%X\n",
1715 			as, addr,
1716 			fault_status,
1717 			(fault_status & (1 << 10) ? "DECODER FAULT" : "SLAVE FAULT"),
1718 			exception_type, panthor_exception_name(ptdev, exception_type),
1719 			access_type, access_type_name(ptdev, fault_status),
1720 			source_id);
1721 
1722 		/* We don't handle VM faults at the moment, so let's just clear the
1723 		 * interrupt and let the writer/reader crash.
1724 		 * Note that COMPLETED irqs are never cleared, but this is fine
1725 		 * because they are always masked.
1726 		 */
1727 		gpu_write(ptdev, MMU_INT_CLEAR, mask);
1728 
1729 		/* Ignore MMU interrupts on this AS until it's been
1730 		 * re-enabled.
1731 		 */
1732 		ptdev->mmu->irq.mask = new_int_mask;
1733 
1734 		if (ptdev->mmu->as.slots[as].vm)
1735 			ptdev->mmu->as.slots[as].vm->unhandled_fault = true;
1736 
1737 		/* Disable the MMU to kill jobs on this AS. */
1738 		panthor_mmu_as_disable(ptdev, as);
1739 		mutex_unlock(&ptdev->mmu->as.slots_lock);
1740 
1741 		status &= ~mask;
1742 		has_unhandled_faults = true;
1743 	}
1744 
1745 	if (has_unhandled_faults)
1746 		panthor_sched_report_mmu_fault(ptdev);
1747 }
1748 PANTHOR_IRQ_HANDLER(mmu, MMU, panthor_mmu_irq_handler);
1749 
1750 /**
1751  * panthor_mmu_suspend() - Suspend the MMU logic
1752  * @ptdev: Device.
1753  *
1754  * All we do here is de-assign the AS slots on all active VMs, so things
1755  * get flushed to the main memory, and no further access to these VMs are
1756  * possible.
1757  *
1758  * We also suspend the MMU IRQ.
1759  */
1760 void panthor_mmu_suspend(struct panthor_device *ptdev)
1761 {
1762 	mutex_lock(&ptdev->mmu->as.slots_lock);
1763 	for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
1764 		struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
1765 
1766 		if (vm) {
1767 			drm_WARN_ON(&ptdev->base, panthor_mmu_as_disable(ptdev, i));
1768 			panthor_vm_release_as_locked(vm);
1769 		}
1770 	}
1771 	mutex_unlock(&ptdev->mmu->as.slots_lock);
1772 
1773 	panthor_mmu_irq_suspend(&ptdev->mmu->irq);
1774 }
1775 
1776 /**
1777  * panthor_mmu_resume() - Resume the MMU logic
1778  * @ptdev: Device.
1779  *
1780  * Resume the IRQ.
1781  *
1782  * We don't re-enable previously active VMs. We assume other parts of the
1783  * driver will call panthor_vm_active() on the VMs they intend to use.
1784  */
1785 void panthor_mmu_resume(struct panthor_device *ptdev)
1786 {
1787 	mutex_lock(&ptdev->mmu->as.slots_lock);
1788 	ptdev->mmu->as.alloc_mask = 0;
1789 	ptdev->mmu->as.faulty_mask = 0;
1790 	mutex_unlock(&ptdev->mmu->as.slots_lock);
1791 
1792 	panthor_mmu_irq_resume(&ptdev->mmu->irq, panthor_mmu_fault_mask(ptdev, ~0));
1793 }
1794 
1795 /**
1796  * panthor_mmu_pre_reset() - Prepare for a reset
1797  * @ptdev: Device.
1798  *
1799  * Suspend the IRQ, and make sure all VM_BIND queues are stopped, so we
1800  * don't get asked to do a VM operation while the GPU is down.
1801  *
1802  * We don't cleanly shutdown the AS slots here, because the reset might
1803  * come from an AS_ACTIVE_BIT stuck situation.
1804  */
1805 void panthor_mmu_pre_reset(struct panthor_device *ptdev)
1806 {
1807 	struct panthor_vm *vm;
1808 
1809 	panthor_mmu_irq_suspend(&ptdev->mmu->irq);
1810 
1811 	mutex_lock(&ptdev->mmu->vm.lock);
1812 	ptdev->mmu->vm.reset_in_progress = true;
1813 	list_for_each_entry(vm, &ptdev->mmu->vm.list, node)
1814 		panthor_vm_stop(vm);
1815 	mutex_unlock(&ptdev->mmu->vm.lock);
1816 }
1817 
1818 /**
1819  * panthor_mmu_post_reset() - Restore things after a reset
1820  * @ptdev: Device.
1821  *
1822  * Put the MMU logic back in action after a reset. That implies resuming the
1823  * IRQ and re-enabling the VM_BIND queues.
1824  */
1825 void panthor_mmu_post_reset(struct panthor_device *ptdev)
1826 {
1827 	struct panthor_vm *vm;
1828 
1829 	mutex_lock(&ptdev->mmu->as.slots_lock);
1830 
1831 	/* Now that the reset is effective, we can assume that none of the
1832 	 * AS slots are setup, and clear the faulty flags too.
1833 	 */
1834 	ptdev->mmu->as.alloc_mask = 0;
1835 	ptdev->mmu->as.faulty_mask = 0;
1836 
1837 	for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
1838 		struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
1839 
1840 		if (vm)
1841 			panthor_vm_release_as_locked(vm);
1842 	}
1843 
1844 	mutex_unlock(&ptdev->mmu->as.slots_lock);
1845 
1846 	panthor_mmu_irq_resume(&ptdev->mmu->irq, panthor_mmu_fault_mask(ptdev, ~0));
1847 
1848 	/* Restart the VM_BIND queues. */
1849 	mutex_lock(&ptdev->mmu->vm.lock);
1850 	list_for_each_entry(vm, &ptdev->mmu->vm.list, node) {
1851 		panthor_vm_start(vm);
1852 	}
1853 	ptdev->mmu->vm.reset_in_progress = false;
1854 	mutex_unlock(&ptdev->mmu->vm.lock);
1855 }
1856 
1857 static void panthor_vm_free(struct drm_gpuvm *gpuvm)
1858 {
1859 	struct panthor_vm *vm = container_of(gpuvm, struct panthor_vm, base);
1860 	struct panthor_device *ptdev = vm->ptdev;
1861 
1862 	mutex_lock(&vm->heaps.lock);
1863 	if (drm_WARN_ON(&ptdev->base, vm->heaps.pool))
1864 		panthor_heap_pool_destroy(vm->heaps.pool);
1865 	mutex_unlock(&vm->heaps.lock);
1866 	mutex_destroy(&vm->heaps.lock);
1867 
1868 	mutex_lock(&ptdev->mmu->vm.lock);
1869 	list_del(&vm->node);
1870 	/* Restore the scheduler state so we can call drm_sched_entity_destroy()
1871 	 * and drm_sched_fini(). If get there, that means we have no job left
1872 	 * and no new jobs can be queued, so we can start the scheduler without
1873 	 * risking interfering with the reset.
1874 	 */
1875 	if (ptdev->mmu->vm.reset_in_progress)
1876 		panthor_vm_start(vm);
1877 	mutex_unlock(&ptdev->mmu->vm.lock);
1878 
1879 	drm_sched_entity_destroy(&vm->entity);
1880 	drm_sched_fini(&vm->sched);
1881 
1882 	mutex_lock(&ptdev->mmu->as.slots_lock);
1883 	if (vm->as.id >= 0) {
1884 		int cookie;
1885 
1886 		if (drm_dev_enter(&ptdev->base, &cookie)) {
1887 			panthor_mmu_as_disable(ptdev, vm->as.id);
1888 			drm_dev_exit(cookie);
1889 		}
1890 
1891 		ptdev->mmu->as.slots[vm->as.id].vm = NULL;
1892 		clear_bit(vm->as.id, &ptdev->mmu->as.alloc_mask);
1893 		list_del(&vm->as.lru_node);
1894 	}
1895 	mutex_unlock(&ptdev->mmu->as.slots_lock);
1896 
1897 	free_io_pgtable_ops(vm->pgtbl_ops);
1898 
1899 	drm_mm_takedown(&vm->mm);
1900 	kfree(vm);
1901 }
1902 
1903 /**
1904  * panthor_vm_put() - Release a reference on a VM
1905  * @vm: VM to release the reference on. Can be NULL.
1906  */
1907 void panthor_vm_put(struct panthor_vm *vm)
1908 {
1909 	drm_gpuvm_put(vm ? &vm->base : NULL);
1910 }
1911 
1912 /**
1913  * panthor_vm_get() - Get a VM reference
1914  * @vm: VM to get the reference on. Can be NULL.
1915  *
1916  * Return: @vm value.
1917  */
1918 struct panthor_vm *panthor_vm_get(struct panthor_vm *vm)
1919 {
1920 	if (vm)
1921 		drm_gpuvm_get(&vm->base);
1922 
1923 	return vm;
1924 }
1925 
1926 /**
1927  * panthor_vm_get_heap_pool() - Get the heap pool attached to a VM
1928  * @vm: VM to query the heap pool on.
1929  * @create: True if the heap pool should be created when it doesn't exist.
1930  *
1931  * Heap pools are per-VM. This function allows one to retrieve the heap pool
1932  * attached to a VM.
1933  *
1934  * If no heap pool exists yet, and @create is true, we create one.
1935  *
1936  * The returned panthor_heap_pool should be released with panthor_heap_pool_put().
1937  *
1938  * Return: A valid pointer on success, an ERR_PTR() otherwise.
1939  */
1940 struct panthor_heap_pool *panthor_vm_get_heap_pool(struct panthor_vm *vm, bool create)
1941 {
1942 	struct panthor_heap_pool *pool;
1943 
1944 	mutex_lock(&vm->heaps.lock);
1945 	if (!vm->heaps.pool && create) {
1946 		if (vm->destroyed)
1947 			pool = ERR_PTR(-EINVAL);
1948 		else
1949 			pool = panthor_heap_pool_create(vm->ptdev, vm);
1950 
1951 		if (!IS_ERR(pool))
1952 			vm->heaps.pool = panthor_heap_pool_get(pool);
1953 	} else {
1954 		pool = panthor_heap_pool_get(vm->heaps.pool);
1955 		if (!pool)
1956 			pool = ERR_PTR(-ENOENT);
1957 	}
1958 	mutex_unlock(&vm->heaps.lock);
1959 
1960 	return pool;
1961 }
1962 
1963 /**
1964  * panthor_vm_heaps_sizes() - Calculate size of all heap chunks across all
1965  * heaps over all the heap pools in a VM
1966  * @pfile: File.
1967  * @stats: Memory stats to be updated.
1968  *
1969  * Calculate all heap chunk sizes in all heap pools bound to a VM. If the VM
1970  * is active, record the size as active as well.
1971  */
1972 void panthor_vm_heaps_sizes(struct panthor_file *pfile, struct drm_memory_stats *stats)
1973 {
1974 	struct panthor_vm *vm;
1975 	unsigned long i;
1976 
1977 	if (!pfile->vms)
1978 		return;
1979 
1980 	xa_lock(&pfile->vms->xa);
1981 	xa_for_each(&pfile->vms->xa, i, vm) {
1982 		size_t size = panthor_heap_pool_size(vm->heaps.pool);
1983 		stats->resident += size;
1984 		if (vm->as.id >= 0)
1985 			stats->active += size;
1986 	}
1987 	xa_unlock(&pfile->vms->xa);
1988 }
1989 
1990 static u64 mair_to_memattr(u64 mair, bool coherent)
1991 {
1992 	u64 memattr = 0;
1993 	u32 i;
1994 
1995 	for (i = 0; i < 8; i++) {
1996 		u8 in_attr = mair >> (8 * i), out_attr;
1997 		u8 outer = in_attr >> 4, inner = in_attr & 0xf;
1998 
1999 		/* For caching to be enabled, inner and outer caching policy
2000 		 * have to be both write-back, if one of them is write-through
2001 		 * or non-cacheable, we just choose non-cacheable. Device
2002 		 * memory is also translated to non-cacheable.
2003 		 */
2004 		if (!(outer & 3) || !(outer & 4) || !(inner & 4)) {
2005 			out_attr = AS_MEMATTR_AARCH64_INNER_OUTER_NC |
2006 				   AS_MEMATTR_AARCH64_SH_MIDGARD_INNER |
2007 				   AS_MEMATTR_AARCH64_INNER_ALLOC_EXPL(false, false);
2008 		} else {
2009 			out_attr = AS_MEMATTR_AARCH64_INNER_OUTER_WB |
2010 				   AS_MEMATTR_AARCH64_INNER_ALLOC_EXPL(inner & 1, inner & 2);
2011 			/* Use SH_MIDGARD_INNER mode when device isn't coherent,
2012 			 * so SH_IS, which is used when IOMMU_CACHE is set, maps
2013 			 * to Mali's internal-shareable mode. As per the Mali
2014 			 * Spec, inner and outer-shareable modes aren't allowed
2015 			 * for WB memory when coherency is disabled.
2016 			 * Use SH_CPU_INNER mode when coherency is enabled, so
2017 			 * that SH_IS actually maps to the standard definition of
2018 			 * inner-shareable.
2019 			 */
2020 			if (!coherent)
2021 				out_attr |= AS_MEMATTR_AARCH64_SH_MIDGARD_INNER;
2022 			else
2023 				out_attr |= AS_MEMATTR_AARCH64_SH_CPU_INNER;
2024 		}
2025 
2026 		memattr |= (u64)out_attr << (8 * i);
2027 	}
2028 
2029 	return memattr;
2030 }
2031 
2032 static void panthor_vma_link(struct panthor_vm *vm,
2033 			     struct panthor_vma *vma,
2034 			     struct drm_gpuvm_bo *vm_bo)
2035 {
2036 	struct panthor_gem_object *bo = to_panthor_bo(vma->base.gem.obj);
2037 
2038 	mutex_lock(&bo->base.base.gpuva.lock);
2039 	drm_gpuva_link(&vma->base, vm_bo);
2040 	drm_WARN_ON(&vm->ptdev->base, drm_gpuvm_bo_put(vm_bo));
2041 	mutex_unlock(&bo->base.base.gpuva.lock);
2042 }
2043 
2044 static void panthor_vma_unlink(struct panthor_vm *vm,
2045 			       struct panthor_vma *vma)
2046 {
2047 	struct panthor_gem_object *bo = to_panthor_bo(vma->base.gem.obj);
2048 	struct drm_gpuvm_bo *vm_bo = drm_gpuvm_bo_get(vma->base.vm_bo);
2049 
2050 	mutex_lock(&bo->base.base.gpuva.lock);
2051 	drm_gpuva_unlink(&vma->base);
2052 	mutex_unlock(&bo->base.base.gpuva.lock);
2053 
2054 	/* drm_gpuva_unlink() release the vm_bo, but we manually retained it
2055 	 * when entering this function, so we can implement deferred VMA
2056 	 * destruction. Re-assign it here.
2057 	 */
2058 	vma->base.vm_bo = vm_bo;
2059 	list_add_tail(&vma->node, &vm->op_ctx->returned_vmas);
2060 }
2061 
2062 static void panthor_vma_init(struct panthor_vma *vma, u32 flags)
2063 {
2064 	INIT_LIST_HEAD(&vma->node);
2065 	vma->flags = flags;
2066 }
2067 
2068 #define PANTHOR_VM_MAP_FLAGS \
2069 	(DRM_PANTHOR_VM_BIND_OP_MAP_READONLY | \
2070 	 DRM_PANTHOR_VM_BIND_OP_MAP_NOEXEC | \
2071 	 DRM_PANTHOR_VM_BIND_OP_MAP_UNCACHED)
2072 
2073 static int panthor_gpuva_sm_step_map(struct drm_gpuva_op *op, void *priv)
2074 {
2075 	struct panthor_vm *vm = priv;
2076 	struct panthor_vm_op_ctx *op_ctx = vm->op_ctx;
2077 	struct panthor_vma *vma = panthor_vm_op_ctx_get_vma(op_ctx);
2078 	int ret;
2079 
2080 	if (!vma)
2081 		return -EINVAL;
2082 
2083 	panthor_vma_init(vma, op_ctx->flags & PANTHOR_VM_MAP_FLAGS);
2084 
2085 	ret = panthor_vm_map_pages(vm, op->map.va.addr, flags_to_prot(vma->flags),
2086 				   op_ctx->map.sgt, op->map.gem.offset,
2087 				   op->map.va.range);
2088 	if (ret)
2089 		return ret;
2090 
2091 	/* Ref owned by the mapping now, clear the obj field so we don't release the
2092 	 * pinning/obj ref behind GPUVA's back.
2093 	 */
2094 	drm_gpuva_map(&vm->base, &vma->base, &op->map);
2095 	panthor_vma_link(vm, vma, op_ctx->map.vm_bo);
2096 	op_ctx->map.vm_bo = NULL;
2097 	return 0;
2098 }
2099 
2100 static int panthor_gpuva_sm_step_remap(struct drm_gpuva_op *op,
2101 				       void *priv)
2102 {
2103 	struct panthor_vma *unmap_vma = container_of(op->remap.unmap->va, struct panthor_vma, base);
2104 	struct panthor_vm *vm = priv;
2105 	struct panthor_vm_op_ctx *op_ctx = vm->op_ctx;
2106 	struct panthor_vma *prev_vma = NULL, *next_vma = NULL;
2107 	u64 unmap_start, unmap_range;
2108 	int ret;
2109 
2110 	drm_gpuva_op_remap_to_unmap_range(&op->remap, &unmap_start, &unmap_range);
2111 	ret = panthor_vm_unmap_pages(vm, unmap_start, unmap_range);
2112 	if (ret)
2113 		return ret;
2114 
2115 	if (op->remap.prev) {
2116 		prev_vma = panthor_vm_op_ctx_get_vma(op_ctx);
2117 		panthor_vma_init(prev_vma, unmap_vma->flags);
2118 	}
2119 
2120 	if (op->remap.next) {
2121 		next_vma = panthor_vm_op_ctx_get_vma(op_ctx);
2122 		panthor_vma_init(next_vma, unmap_vma->flags);
2123 	}
2124 
2125 	drm_gpuva_remap(prev_vma ? &prev_vma->base : NULL,
2126 			next_vma ? &next_vma->base : NULL,
2127 			&op->remap);
2128 
2129 	if (prev_vma) {
2130 		/* panthor_vma_link() transfers the vm_bo ownership to
2131 		 * the VMA object. Since the vm_bo we're passing is still
2132 		 * owned by the old mapping which will be released when this
2133 		 * mapping is destroyed, we need to grab a ref here.
2134 		 */
2135 		panthor_vma_link(vm, prev_vma,
2136 				 drm_gpuvm_bo_get(op->remap.unmap->va->vm_bo));
2137 	}
2138 
2139 	if (next_vma) {
2140 		panthor_vma_link(vm, next_vma,
2141 				 drm_gpuvm_bo_get(op->remap.unmap->va->vm_bo));
2142 	}
2143 
2144 	panthor_vma_unlink(vm, unmap_vma);
2145 	return 0;
2146 }
2147 
2148 static int panthor_gpuva_sm_step_unmap(struct drm_gpuva_op *op,
2149 				       void *priv)
2150 {
2151 	struct panthor_vma *unmap_vma = container_of(op->unmap.va, struct panthor_vma, base);
2152 	struct panthor_vm *vm = priv;
2153 	int ret;
2154 
2155 	ret = panthor_vm_unmap_pages(vm, unmap_vma->base.va.addr,
2156 				     unmap_vma->base.va.range);
2157 	if (drm_WARN_ON(&vm->ptdev->base, ret))
2158 		return ret;
2159 
2160 	drm_gpuva_unmap(&op->unmap);
2161 	panthor_vma_unlink(vm, unmap_vma);
2162 	return 0;
2163 }
2164 
2165 static const struct drm_gpuvm_ops panthor_gpuvm_ops = {
2166 	.vm_free = panthor_vm_free,
2167 	.sm_step_map = panthor_gpuva_sm_step_map,
2168 	.sm_step_remap = panthor_gpuva_sm_step_remap,
2169 	.sm_step_unmap = panthor_gpuva_sm_step_unmap,
2170 };
2171 
2172 /**
2173  * panthor_vm_resv() - Get the dma_resv object attached to a VM.
2174  * @vm: VM to get the dma_resv of.
2175  *
2176  * Return: A dma_resv object.
2177  */
2178 struct dma_resv *panthor_vm_resv(struct panthor_vm *vm)
2179 {
2180 	return drm_gpuvm_resv(&vm->base);
2181 }
2182 
2183 struct drm_gem_object *panthor_vm_root_gem(struct panthor_vm *vm)
2184 {
2185 	if (!vm)
2186 		return NULL;
2187 
2188 	return vm->base.r_obj;
2189 }
2190 
2191 static int
2192 panthor_vm_exec_op(struct panthor_vm *vm, struct panthor_vm_op_ctx *op,
2193 		   bool flag_vm_unusable_on_failure)
2194 {
2195 	u32 op_type = op->flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK;
2196 	int ret;
2197 
2198 	if (op_type == DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY)
2199 		return 0;
2200 
2201 	mutex_lock(&vm->op_lock);
2202 	vm->op_ctx = op;
2203 	switch (op_type) {
2204 	case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP: {
2205 		const struct drm_gpuvm_map_req map_req = {
2206 			.map.va.addr = op->va.addr,
2207 			.map.va.range = op->va.range,
2208 			.map.gem.obj = op->map.vm_bo->obj,
2209 			.map.gem.offset = op->map.bo_offset,
2210 		};
2211 
2212 		if (vm->unusable) {
2213 			ret = -EINVAL;
2214 			break;
2215 		}
2216 
2217 		ret = drm_gpuvm_sm_map(&vm->base, vm, &map_req);
2218 		break;
2219 	}
2220 
2221 	case DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP:
2222 		ret = drm_gpuvm_sm_unmap(&vm->base, vm, op->va.addr, op->va.range);
2223 		break;
2224 
2225 	default:
2226 		ret = -EINVAL;
2227 		break;
2228 	}
2229 
2230 	if (ret && flag_vm_unusable_on_failure)
2231 		vm->unusable = true;
2232 
2233 	vm->op_ctx = NULL;
2234 	mutex_unlock(&vm->op_lock);
2235 
2236 	return ret;
2237 }
2238 
2239 static struct dma_fence *
2240 panthor_vm_bind_run_job(struct drm_sched_job *sched_job)
2241 {
2242 	struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2243 	bool cookie;
2244 	int ret;
2245 
2246 	/* Not only we report an error whose result is propagated to the
2247 	 * drm_sched finished fence, but we also flag the VM as unusable, because
2248 	 * a failure in the async VM_BIND results in an inconsistent state. VM needs
2249 	 * to be destroyed and recreated.
2250 	 */
2251 	cookie = dma_fence_begin_signalling();
2252 	ret = panthor_vm_exec_op(job->vm, &job->ctx, true);
2253 	dma_fence_end_signalling(cookie);
2254 
2255 	return ret ? ERR_PTR(ret) : NULL;
2256 }
2257 
2258 static void panthor_vm_bind_job_release(struct kref *kref)
2259 {
2260 	struct panthor_vm_bind_job *job = container_of(kref, struct panthor_vm_bind_job, refcount);
2261 
2262 	if (job->base.s_fence)
2263 		drm_sched_job_cleanup(&job->base);
2264 
2265 	panthor_vm_cleanup_op_ctx(&job->ctx, job->vm);
2266 	panthor_vm_put(job->vm);
2267 	kfree(job);
2268 }
2269 
2270 /**
2271  * panthor_vm_bind_job_put() - Release a VM_BIND job reference
2272  * @sched_job: Job to release the reference on.
2273  */
2274 void panthor_vm_bind_job_put(struct drm_sched_job *sched_job)
2275 {
2276 	struct panthor_vm_bind_job *job =
2277 		container_of(sched_job, struct panthor_vm_bind_job, base);
2278 
2279 	if (sched_job)
2280 		kref_put(&job->refcount, panthor_vm_bind_job_release);
2281 }
2282 
2283 static void
2284 panthor_vm_bind_free_job(struct drm_sched_job *sched_job)
2285 {
2286 	struct panthor_vm_bind_job *job =
2287 		container_of(sched_job, struct panthor_vm_bind_job, base);
2288 
2289 	drm_sched_job_cleanup(sched_job);
2290 
2291 	/* Do the heavy cleanups asynchronously, so we're out of the
2292 	 * dma-signaling path and can acquire dma-resv locks safely.
2293 	 */
2294 	queue_work(panthor_cleanup_wq, &job->cleanup_op_ctx_work);
2295 }
2296 
2297 static enum drm_gpu_sched_stat
2298 panthor_vm_bind_timedout_job(struct drm_sched_job *sched_job)
2299 {
2300 	WARN(1, "VM_BIND ops are synchronous for now, there should be no timeout!");
2301 	return DRM_GPU_SCHED_STAT_RESET;
2302 }
2303 
2304 static const struct drm_sched_backend_ops panthor_vm_bind_ops = {
2305 	.run_job = panthor_vm_bind_run_job,
2306 	.free_job = panthor_vm_bind_free_job,
2307 	.timedout_job = panthor_vm_bind_timedout_job,
2308 };
2309 
2310 /**
2311  * panthor_vm_create() - Create a VM
2312  * @ptdev: Device.
2313  * @for_mcu: True if this is the FW MCU VM.
2314  * @kernel_va_start: Start of the range reserved for kernel BO mapping.
2315  * @kernel_va_size: Size of the range reserved for kernel BO mapping.
2316  * @auto_kernel_va_start: Start of the auto-VA kernel range.
2317  * @auto_kernel_va_size: Size of the auto-VA kernel range.
2318  *
2319  * Return: A valid pointer on success, an ERR_PTR() otherwise.
2320  */
2321 struct panthor_vm *
2322 panthor_vm_create(struct panthor_device *ptdev, bool for_mcu,
2323 		  u64 kernel_va_start, u64 kernel_va_size,
2324 		  u64 auto_kernel_va_start, u64 auto_kernel_va_size)
2325 {
2326 	u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
2327 	u32 pa_bits = GPU_MMU_FEATURES_PA_BITS(ptdev->gpu_info.mmu_features);
2328 	u64 full_va_range = 1ull << va_bits;
2329 	struct drm_gem_object *dummy_gem;
2330 	struct drm_gpu_scheduler *sched;
2331 	const struct drm_sched_init_args sched_args = {
2332 		.ops = &panthor_vm_bind_ops,
2333 		.submit_wq = ptdev->mmu->vm.wq,
2334 		.num_rqs = 1,
2335 		.credit_limit = 1,
2336 		/* Bind operations are synchronous for now, no timeout needed. */
2337 		.timeout = MAX_SCHEDULE_TIMEOUT,
2338 		.name = "panthor-vm-bind",
2339 		.dev = ptdev->base.dev,
2340 	};
2341 	struct io_pgtable_cfg pgtbl_cfg;
2342 	u64 mair, min_va, va_range;
2343 	struct panthor_vm *vm;
2344 	int ret;
2345 
2346 	vm = kzalloc(sizeof(*vm), GFP_KERNEL);
2347 	if (!vm)
2348 		return ERR_PTR(-ENOMEM);
2349 
2350 	/* We allocate a dummy GEM for the VM. */
2351 	dummy_gem = drm_gpuvm_resv_object_alloc(&ptdev->base);
2352 	if (!dummy_gem) {
2353 		ret = -ENOMEM;
2354 		goto err_free_vm;
2355 	}
2356 
2357 	mutex_init(&vm->heaps.lock);
2358 	vm->for_mcu = for_mcu;
2359 	vm->ptdev = ptdev;
2360 	mutex_init(&vm->op_lock);
2361 
2362 	if (for_mcu) {
2363 		/* CSF MCU is a cortex M7, and can only address 4G */
2364 		min_va = 0;
2365 		va_range = SZ_4G;
2366 	} else {
2367 		min_va = 0;
2368 		va_range = full_va_range;
2369 	}
2370 
2371 	mutex_init(&vm->mm_lock);
2372 	drm_mm_init(&vm->mm, kernel_va_start, kernel_va_size);
2373 	vm->kernel_auto_va.start = auto_kernel_va_start;
2374 	vm->kernel_auto_va.end = vm->kernel_auto_va.start + auto_kernel_va_size - 1;
2375 
2376 	INIT_LIST_HEAD(&vm->node);
2377 	INIT_LIST_HEAD(&vm->as.lru_node);
2378 	vm->as.id = -1;
2379 	refcount_set(&vm->as.active_cnt, 0);
2380 
2381 	pgtbl_cfg = (struct io_pgtable_cfg) {
2382 		.pgsize_bitmap	= SZ_4K | SZ_2M,
2383 		.ias		= va_bits,
2384 		.oas		= pa_bits,
2385 		.coherent_walk	= ptdev->coherent,
2386 		.tlb		= &mmu_tlb_ops,
2387 		.iommu_dev	= ptdev->base.dev,
2388 		.alloc		= alloc_pt,
2389 		.free		= free_pt,
2390 	};
2391 
2392 	vm->pgtbl_ops = alloc_io_pgtable_ops(ARM_64_LPAE_S1, &pgtbl_cfg, vm);
2393 	if (!vm->pgtbl_ops) {
2394 		ret = -EINVAL;
2395 		goto err_mm_takedown;
2396 	}
2397 
2398 	ret = drm_sched_init(&vm->sched, &sched_args);
2399 	if (ret)
2400 		goto err_free_io_pgtable;
2401 
2402 	sched = &vm->sched;
2403 	ret = drm_sched_entity_init(&vm->entity, 0, &sched, 1, NULL);
2404 	if (ret)
2405 		goto err_sched_fini;
2406 
2407 	mair = io_pgtable_ops_to_pgtable(vm->pgtbl_ops)->cfg.arm_lpae_s1_cfg.mair;
2408 	vm->memattr = mair_to_memattr(mair, ptdev->coherent);
2409 
2410 	mutex_lock(&ptdev->mmu->vm.lock);
2411 	list_add_tail(&vm->node, &ptdev->mmu->vm.list);
2412 
2413 	/* If a reset is in progress, stop the scheduler. */
2414 	if (ptdev->mmu->vm.reset_in_progress)
2415 		panthor_vm_stop(vm);
2416 	mutex_unlock(&ptdev->mmu->vm.lock);
2417 
2418 	/* We intentionally leave the reserved range to zero, because we want kernel VMAs
2419 	 * to be handled the same way user VMAs are.
2420 	 */
2421 	drm_gpuvm_init(&vm->base, for_mcu ? "panthor-MCU-VM" : "panthor-GPU-VM",
2422 		       DRM_GPUVM_RESV_PROTECTED | DRM_GPUVM_IMMEDIATE_MODE,
2423 		       &ptdev->base, dummy_gem, min_va, va_range, 0, 0,
2424 		       &panthor_gpuvm_ops);
2425 	drm_gem_object_put(dummy_gem);
2426 	return vm;
2427 
2428 err_sched_fini:
2429 	drm_sched_fini(&vm->sched);
2430 
2431 err_free_io_pgtable:
2432 	free_io_pgtable_ops(vm->pgtbl_ops);
2433 
2434 err_mm_takedown:
2435 	drm_mm_takedown(&vm->mm);
2436 	drm_gem_object_put(dummy_gem);
2437 
2438 err_free_vm:
2439 	kfree(vm);
2440 	return ERR_PTR(ret);
2441 }
2442 
2443 static int
2444 panthor_vm_bind_prepare_op_ctx(struct drm_file *file,
2445 			       struct panthor_vm *vm,
2446 			       const struct drm_panthor_vm_bind_op *op,
2447 			       struct panthor_vm_op_ctx *op_ctx)
2448 {
2449 	ssize_t vm_pgsz = panthor_vm_page_size(vm);
2450 	struct drm_gem_object *gem;
2451 	int ret;
2452 
2453 	/* Aligned on page size. */
2454 	if (!IS_ALIGNED(op->va | op->size | op->bo_offset, vm_pgsz))
2455 		return -EINVAL;
2456 
2457 	switch (op->flags & DRM_PANTHOR_VM_BIND_OP_TYPE_MASK) {
2458 	case DRM_PANTHOR_VM_BIND_OP_TYPE_MAP:
2459 		gem = drm_gem_object_lookup(file, op->bo_handle);
2460 		ret = panthor_vm_prepare_map_op_ctx(op_ctx, vm,
2461 						    gem ? to_panthor_bo(gem) : NULL,
2462 						    op->bo_offset,
2463 						    op->size,
2464 						    op->va,
2465 						    op->flags);
2466 		drm_gem_object_put(gem);
2467 		return ret;
2468 
2469 	case DRM_PANTHOR_VM_BIND_OP_TYPE_UNMAP:
2470 		if (op->flags & ~DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
2471 			return -EINVAL;
2472 
2473 		if (op->bo_handle || op->bo_offset)
2474 			return -EINVAL;
2475 
2476 		return panthor_vm_prepare_unmap_op_ctx(op_ctx, vm, op->va, op->size);
2477 
2478 	case DRM_PANTHOR_VM_BIND_OP_TYPE_SYNC_ONLY:
2479 		if (op->flags & ~DRM_PANTHOR_VM_BIND_OP_TYPE_MASK)
2480 			return -EINVAL;
2481 
2482 		if (op->bo_handle || op->bo_offset)
2483 			return -EINVAL;
2484 
2485 		if (op->va || op->size)
2486 			return -EINVAL;
2487 
2488 		if (!op->syncs.count)
2489 			return -EINVAL;
2490 
2491 		panthor_vm_prepare_sync_only_op_ctx(op_ctx, vm);
2492 		return 0;
2493 
2494 	default:
2495 		return -EINVAL;
2496 	}
2497 }
2498 
2499 static void panthor_vm_bind_job_cleanup_op_ctx_work(struct work_struct *work)
2500 {
2501 	struct panthor_vm_bind_job *job =
2502 		container_of(work, struct panthor_vm_bind_job, cleanup_op_ctx_work);
2503 
2504 	panthor_vm_bind_job_put(&job->base);
2505 }
2506 
2507 /**
2508  * panthor_vm_bind_job_create() - Create a VM_BIND job
2509  * @file: File.
2510  * @vm: VM targeted by the VM_BIND job.
2511  * @op: VM operation data.
2512  *
2513  * Return: A valid pointer on success, an ERR_PTR() otherwise.
2514  */
2515 struct drm_sched_job *
2516 panthor_vm_bind_job_create(struct drm_file *file,
2517 			   struct panthor_vm *vm,
2518 			   const struct drm_panthor_vm_bind_op *op)
2519 {
2520 	struct panthor_vm_bind_job *job;
2521 	int ret;
2522 
2523 	if (!vm)
2524 		return ERR_PTR(-EINVAL);
2525 
2526 	if (vm->destroyed || vm->unusable)
2527 		return ERR_PTR(-EINVAL);
2528 
2529 	job = kzalloc(sizeof(*job), GFP_KERNEL);
2530 	if (!job)
2531 		return ERR_PTR(-ENOMEM);
2532 
2533 	ret = panthor_vm_bind_prepare_op_ctx(file, vm, op, &job->ctx);
2534 	if (ret) {
2535 		kfree(job);
2536 		return ERR_PTR(ret);
2537 	}
2538 
2539 	INIT_WORK(&job->cleanup_op_ctx_work, panthor_vm_bind_job_cleanup_op_ctx_work);
2540 	kref_init(&job->refcount);
2541 	job->vm = panthor_vm_get(vm);
2542 
2543 	ret = drm_sched_job_init(&job->base, &vm->entity, 1, vm, file->client_id);
2544 	if (ret)
2545 		goto err_put_job;
2546 
2547 	return &job->base;
2548 
2549 err_put_job:
2550 	panthor_vm_bind_job_put(&job->base);
2551 	return ERR_PTR(ret);
2552 }
2553 
2554 /**
2555  * panthor_vm_bind_job_prepare_resvs() - Prepare VM_BIND job dma_resvs
2556  * @exec: The locking/preparation context.
2557  * @sched_job: The job to prepare resvs on.
2558  *
2559  * Locks and prepare the VM resv.
2560  *
2561  * If this is a map operation, locks and prepares the GEM resv.
2562  *
2563  * Return: 0 on success, a negative error code otherwise.
2564  */
2565 int panthor_vm_bind_job_prepare_resvs(struct drm_exec *exec,
2566 				      struct drm_sched_job *sched_job)
2567 {
2568 	struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2569 	int ret;
2570 
2571 	/* Acquire the VM lock an reserve a slot for this VM bind job. */
2572 	ret = drm_gpuvm_prepare_vm(&job->vm->base, exec, 1);
2573 	if (ret)
2574 		return ret;
2575 
2576 	if (job->ctx.map.vm_bo) {
2577 		/* Lock/prepare the GEM being mapped. */
2578 		ret = drm_exec_prepare_obj(exec, job->ctx.map.vm_bo->obj, 1);
2579 		if (ret)
2580 			return ret;
2581 	}
2582 
2583 	return 0;
2584 }
2585 
2586 /**
2587  * panthor_vm_bind_job_update_resvs() - Update the resv objects touched by a job
2588  * @exec: drm_exec context.
2589  * @sched_job: Job to update the resvs on.
2590  */
2591 void panthor_vm_bind_job_update_resvs(struct drm_exec *exec,
2592 				      struct drm_sched_job *sched_job)
2593 {
2594 	struct panthor_vm_bind_job *job = container_of(sched_job, struct panthor_vm_bind_job, base);
2595 
2596 	/* Explicit sync => we just register our job finished fence as bookkeep. */
2597 	drm_gpuvm_resv_add_fence(&job->vm->base, exec,
2598 				 &sched_job->s_fence->finished,
2599 				 DMA_RESV_USAGE_BOOKKEEP,
2600 				 DMA_RESV_USAGE_BOOKKEEP);
2601 }
2602 
2603 void panthor_vm_update_resvs(struct panthor_vm *vm, struct drm_exec *exec,
2604 			     struct dma_fence *fence,
2605 			     enum dma_resv_usage private_usage,
2606 			     enum dma_resv_usage extobj_usage)
2607 {
2608 	drm_gpuvm_resv_add_fence(&vm->base, exec, fence, private_usage, extobj_usage);
2609 }
2610 
2611 /**
2612  * panthor_vm_bind_exec_sync_op() - Execute a VM_BIND operation synchronously.
2613  * @file: File.
2614  * @vm: VM targeted by the VM operation.
2615  * @op: Data describing the VM operation.
2616  *
2617  * Return: 0 on success, a negative error code otherwise.
2618  */
2619 int panthor_vm_bind_exec_sync_op(struct drm_file *file,
2620 				 struct panthor_vm *vm,
2621 				 struct drm_panthor_vm_bind_op *op)
2622 {
2623 	struct panthor_vm_op_ctx op_ctx;
2624 	int ret;
2625 
2626 	/* No sync objects allowed on synchronous operations. */
2627 	if (op->syncs.count)
2628 		return -EINVAL;
2629 
2630 	if (!op->size)
2631 		return 0;
2632 
2633 	ret = panthor_vm_bind_prepare_op_ctx(file, vm, op, &op_ctx);
2634 	if (ret)
2635 		return ret;
2636 
2637 	ret = panthor_vm_exec_op(vm, &op_ctx, false);
2638 	panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2639 
2640 	return ret;
2641 }
2642 
2643 /**
2644  * panthor_vm_map_bo_range() - Map a GEM object range to a VM
2645  * @vm: VM to map the GEM to.
2646  * @bo: GEM object to map.
2647  * @offset: Offset in the GEM object.
2648  * @size: Size to map.
2649  * @va: Virtual address to map the object to.
2650  * @flags: Combination of drm_panthor_vm_bind_op_flags flags.
2651  * Only map-related flags are valid.
2652  *
2653  * Internal use only. For userspace requests, use
2654  * panthor_vm_bind_exec_sync_op() instead.
2655  *
2656  * Return: 0 on success, a negative error code otherwise.
2657  */
2658 int panthor_vm_map_bo_range(struct panthor_vm *vm, struct panthor_gem_object *bo,
2659 			    u64 offset, u64 size, u64 va, u32 flags)
2660 {
2661 	struct panthor_vm_op_ctx op_ctx;
2662 	int ret;
2663 
2664 	ret = panthor_vm_prepare_map_op_ctx(&op_ctx, vm, bo, offset, size, va, flags);
2665 	if (ret)
2666 		return ret;
2667 
2668 	ret = panthor_vm_exec_op(vm, &op_ctx, false);
2669 	panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2670 
2671 	return ret;
2672 }
2673 
2674 /**
2675  * panthor_vm_unmap_range() - Unmap a portion of the VA space
2676  * @vm: VM to unmap the region from.
2677  * @va: Virtual address to unmap. Must be 4k aligned.
2678  * @size: Size of the region to unmap. Must be 4k aligned.
2679  *
2680  * Internal use only. For userspace requests, use
2681  * panthor_vm_bind_exec_sync_op() instead.
2682  *
2683  * Return: 0 on success, a negative error code otherwise.
2684  */
2685 int panthor_vm_unmap_range(struct panthor_vm *vm, u64 va, u64 size)
2686 {
2687 	struct panthor_vm_op_ctx op_ctx;
2688 	int ret;
2689 
2690 	ret = panthor_vm_prepare_unmap_op_ctx(&op_ctx, vm, va, size);
2691 	if (ret)
2692 		return ret;
2693 
2694 	ret = panthor_vm_exec_op(vm, &op_ctx, false);
2695 	panthor_vm_cleanup_op_ctx(&op_ctx, vm);
2696 
2697 	return ret;
2698 }
2699 
2700 /**
2701  * panthor_vm_prepare_mapped_bos_resvs() - Prepare resvs on VM BOs.
2702  * @exec: Locking/preparation context.
2703  * @vm: VM targeted by the GPU job.
2704  * @slot_count: Number of slots to reserve.
2705  *
2706  * GPU jobs assume all BOs bound to the VM at the time the job is submitted
2707  * are available when the job is executed. In order to guarantee that, we
2708  * need to reserve a slot on all BOs mapped to a VM and update this slot with
2709  * the job fence after its submission.
2710  *
2711  * Return: 0 on success, a negative error code otherwise.
2712  */
2713 int panthor_vm_prepare_mapped_bos_resvs(struct drm_exec *exec, struct panthor_vm *vm,
2714 					u32 slot_count)
2715 {
2716 	int ret;
2717 
2718 	/* Acquire the VM lock and reserve a slot for this GPU job. */
2719 	ret = drm_gpuvm_prepare_vm(&vm->base, exec, slot_count);
2720 	if (ret)
2721 		return ret;
2722 
2723 	return drm_gpuvm_prepare_objects(&vm->base, exec, slot_count);
2724 }
2725 
2726 /**
2727  * panthor_mmu_unplug() - Unplug the MMU logic
2728  * @ptdev: Device.
2729  *
2730  * No access to the MMU regs should be done after this function is called.
2731  * We suspend the IRQ and disable all VMs to guarantee that.
2732  */
2733 void panthor_mmu_unplug(struct panthor_device *ptdev)
2734 {
2735 	if (!IS_ENABLED(CONFIG_PM) || pm_runtime_active(ptdev->base.dev))
2736 		panthor_mmu_irq_suspend(&ptdev->mmu->irq);
2737 
2738 	mutex_lock(&ptdev->mmu->as.slots_lock);
2739 	for (u32 i = 0; i < ARRAY_SIZE(ptdev->mmu->as.slots); i++) {
2740 		struct panthor_vm *vm = ptdev->mmu->as.slots[i].vm;
2741 
2742 		if (vm) {
2743 			drm_WARN_ON(&ptdev->base, panthor_mmu_as_disable(ptdev, i));
2744 			panthor_vm_release_as_locked(vm);
2745 		}
2746 	}
2747 	mutex_unlock(&ptdev->mmu->as.slots_lock);
2748 }
2749 
2750 static void panthor_mmu_release_wq(struct drm_device *ddev, void *res)
2751 {
2752 	destroy_workqueue(res);
2753 }
2754 
2755 /**
2756  * panthor_mmu_init() - Initialize the MMU logic.
2757  * @ptdev: Device.
2758  *
2759  * Return: 0 on success, a negative error code otherwise.
2760  */
2761 int panthor_mmu_init(struct panthor_device *ptdev)
2762 {
2763 	u32 va_bits = GPU_MMU_FEATURES_VA_BITS(ptdev->gpu_info.mmu_features);
2764 	struct panthor_mmu *mmu;
2765 	int ret, irq;
2766 
2767 	mmu = drmm_kzalloc(&ptdev->base, sizeof(*mmu), GFP_KERNEL);
2768 	if (!mmu)
2769 		return -ENOMEM;
2770 
2771 	INIT_LIST_HEAD(&mmu->as.lru_list);
2772 
2773 	ret = drmm_mutex_init(&ptdev->base, &mmu->as.slots_lock);
2774 	if (ret)
2775 		return ret;
2776 
2777 	INIT_LIST_HEAD(&mmu->vm.list);
2778 	ret = drmm_mutex_init(&ptdev->base, &mmu->vm.lock);
2779 	if (ret)
2780 		return ret;
2781 
2782 	ptdev->mmu = mmu;
2783 
2784 	irq = platform_get_irq_byname(to_platform_device(ptdev->base.dev), "mmu");
2785 	if (irq <= 0)
2786 		return -ENODEV;
2787 
2788 	ret = panthor_request_mmu_irq(ptdev, &mmu->irq, irq,
2789 				      panthor_mmu_fault_mask(ptdev, ~0));
2790 	if (ret)
2791 		return ret;
2792 
2793 	mmu->vm.wq = alloc_workqueue("panthor-vm-bind", WQ_UNBOUND, 0);
2794 	if (!mmu->vm.wq)
2795 		return -ENOMEM;
2796 
2797 	/* On 32-bit kernels, the VA space is limited by the io_pgtable_ops abstraction,
2798 	 * which passes iova as an unsigned long. Patch the mmu_features to reflect this
2799 	 * limitation.
2800 	 */
2801 	if (va_bits > BITS_PER_LONG) {
2802 		ptdev->gpu_info.mmu_features &= ~GENMASK(7, 0);
2803 		ptdev->gpu_info.mmu_features |= BITS_PER_LONG;
2804 	}
2805 
2806 	return drmm_add_action_or_reset(&ptdev->base, panthor_mmu_release_wq, mmu->vm.wq);
2807 }
2808 
2809 #ifdef CONFIG_DEBUG_FS
2810 static int show_vm_gpuvas(struct panthor_vm *vm, struct seq_file *m)
2811 {
2812 	int ret;
2813 
2814 	mutex_lock(&vm->op_lock);
2815 	ret = drm_debugfs_gpuva_info(m, &vm->base);
2816 	mutex_unlock(&vm->op_lock);
2817 
2818 	return ret;
2819 }
2820 
2821 static int show_each_vm(struct seq_file *m, void *arg)
2822 {
2823 	struct drm_info_node *node = (struct drm_info_node *)m->private;
2824 	struct drm_device *ddev = node->minor->dev;
2825 	struct panthor_device *ptdev = container_of(ddev, struct panthor_device, base);
2826 	int (*show)(struct panthor_vm *, struct seq_file *) = node->info_ent->data;
2827 	struct panthor_vm *vm;
2828 	int ret = 0;
2829 
2830 	mutex_lock(&ptdev->mmu->vm.lock);
2831 	list_for_each_entry(vm, &ptdev->mmu->vm.list, node) {
2832 		ret = show(vm, m);
2833 		if (ret < 0)
2834 			break;
2835 
2836 		seq_puts(m, "\n");
2837 	}
2838 	mutex_unlock(&ptdev->mmu->vm.lock);
2839 
2840 	return ret;
2841 }
2842 
2843 static struct drm_info_list panthor_mmu_debugfs_list[] = {
2844 	DRM_DEBUGFS_GPUVA_INFO(show_each_vm, show_vm_gpuvas),
2845 };
2846 
2847 /**
2848  * panthor_mmu_debugfs_init() - Initialize MMU debugfs entries
2849  * @minor: Minor.
2850  */
2851 void panthor_mmu_debugfs_init(struct drm_minor *minor)
2852 {
2853 	drm_debugfs_create_files(panthor_mmu_debugfs_list,
2854 				 ARRAY_SIZE(panthor_mmu_debugfs_list),
2855 				 minor->debugfs_root, minor);
2856 }
2857 #endif /* CONFIG_DEBUG_FS */
2858 
2859 /**
2860  * panthor_mmu_pt_cache_init() - Initialize the page table cache.
2861  *
2862  * Return: 0 on success, a negative error code otherwise.
2863  */
2864 int panthor_mmu_pt_cache_init(void)
2865 {
2866 	pt_cache = kmem_cache_create("panthor-mmu-pt", SZ_4K, SZ_4K, 0, NULL);
2867 	if (!pt_cache)
2868 		return -ENOMEM;
2869 
2870 	return 0;
2871 }
2872 
2873 /**
2874  * panthor_mmu_pt_cache_fini() - Destroy the page table cache.
2875  */
2876 void panthor_mmu_pt_cache_fini(void)
2877 {
2878 	kmem_cache_destroy(pt_cache);
2879 }
2880