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