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