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