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