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