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