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