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