Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [High] drm/tyr: partial 2 MiB block PTE unmap at 4 KiB in
  sm_step_remap()
- [Medium] drm/tyr: unbounded KVec kmalloc growth before vm_id check in
  vm_bind()
- [Medium] drm/tyr: failed VM operations in exec_op() do not mark the VM
  unusable
- [Medium] drm/tyr: unclamped va_bits in new_for_user() exceeds 32-bit
  usize limit
--

commit 6e66301fc3b3ee2268d9c61dcd5d0c01cc14673d
Author: Alvin Sun <[email protected]>

drm/tyr: add VM-related ioctls

This commit implements the PANTHOR_VM_CREATE, PANTHOR_VM_DESTROY,
PANTHOR_VM_BIND, and PANTHOR_VM_GET_STATE ioctls for the Tyr DRM driver.

> diff --git a/drivers/gpu/drm/tyr/file.rs b/drivers/gpu/drm/tyr/file.rs
> index 933a365cb016e..901c0fb951adf 100644
> --- a/drivers/gpu/drm/tyr/file.rs
> +++ b/drivers/gpu/drm/tyr/file.rs
[ ... ]
> @@ -65,4 +86,260 @@ pub(crate) fn dev_query(
[ ... ]
> +    pub(crate) fn vm_bind(
> +        ddev: &TyrDrmDevice<Registered>,
> +        _reg_data: &TyrDrmRegistrationData<'_>,
> +        vmbind: &mut uapi::drm_panthor_vm_bind,
> +        file: &TyrDrmFile,
> +    ) -> Result<u32> {
[ ... ]
> +        let total_len = 
> size_of::<VmBindOp>().checked_mul(count).ok_or_else(|| {
> +            dev_dbg!(ddev.as_ref(), "VM_BIND ops length overflow\n");
> +            EINVAL
> +        })?;
> +        let mut reader =
> +            UserSlice::new(UserPtr::from_addr(vmbind.ops.array as usize), 
> total_len).reader();
> +        let mut ops = KVec::new();
> +        for _ in 0..count {
> +            ops.push(reader.read::<VmBindOp>()?, GFP_KERNEL)?;
> +        }
> +
> +        let ret: Result<u32, Error> = file.inner_with(|pfile| {
> +            let vm = pfile.vm_pool.get(vmbind.vm_id).ok_or_else(|| {
> +                dev_dbg!(ddev.as_ref(), "Invalid VM_BIND vm_id: {}\n", 
> vmbind.vm_id);
> +                EINVAL
> +            })?;

[Severity: Medium]
Can pushing a user-controlled count into an unreserved KVec trigger a warning
in ___kmalloc_large_node() before vmbind.vm_id is validated?

Because VmBindOp is 48 bytes and KVec::push() doubles its kmalloc-backed
capacity on growth, any render-node call with vmbind.ops.count >= 65537
attempts a 6 MiB physically contiguous allocation exceeding KMALLOC_MAX_SIZE
without __GFP_NOWARN, hitting WARN_ON_ONCE_GFP(size > KMALLOC_MAX_SIZE, flags)
instead of falling back to vmalloc.  Validating vmbind.vm_id first and
pre-allocating with KVVec::with_capacity() would avoid unauthenticated work
and fall back to vmalloc for large batches.

[ ... ]

> +fn vm_bind_exec_op(vm: &Vm<'_>, file: &TyrDrmFile, op: &VmBindOp) -> Result {
[ ... ]
> +    match VmBindOpType::try_from(op.flags) {
> +        Ok(VmBindOpType::Map) => {
[ ... ]
> +            vm.map_bo_range(&bo, op.bo_offset, op.size, op.va, map_flags)
> +        }
> +        Ok(VmBindOpType::Unmap) => {
> +            // Unmap must not carry map-specific flags or BO references.
> +            if op.flags & !VmBindOpType::MASK != 0 || op.bo_handle != 0 || 
> op.bo_offset != 0 {
> +                dev_dbg!(
> +                    vm.dev(),
> +                    "VM_BIND UNMAP carries flags/BO refs: flags={:#x} 
> bo_handle={} bo_offset={}\n",
> +                    op.flags,
> +                    op.bo_handle,
> +                    op.bo_offset
> +                );
> +                return Err(EINVAL);
> +            }
> +            vm.unmap_range(op.va, op.size)
> +        }

[Severity: High]
What happens when vm_bind_exec_op() partially unmaps or overwrites an
existing 2 MiB block mapping at 4 KiB granularity?

pt_map() creates SZ_2M block mappings when the IOVA, physical address, and
remaining size are 2 MiB-aligned, but GpuVmData::sm_step_remap() passes only
the unmapped sub-range to pt_unmap():

drivers/gpu/drm/tyr/vm.rs:GpuVmData::sm_step_remap() {
    ...
        if unmap_length > 0 {
            let region = unmap_start..(unmap_start + unmap_length);
            pt_unmap(context.dev, context.pt, region.clone()).inspect_err(|e| {
    ...
}

When that sub-range is not 2 MiB-aligned, get_pgsize() selects SZ_4K and
__arm_lpae_unmap() triggers WARN_ONCE(true, "Unmap of a partial large IOPTE
is not allowed") and returns 0, aborting sm_step_remap() with EINVAL before
op.remap() updates the GpuVm tree and leaving the hardware page tables out of
sync with GpuVm if earlier pages were already unmapped.  Like C panthor's
unmap_hugepage_align(), sm_step_remap() needs to widen the unmap range to
2 MiB block boundaries and remap the surviving 4 KiB portions of prev and
next.

> diff --git a/drivers/gpu/drm/tyr/vm.rs b/drivers/gpu/drm/tyr/vm.rs
> index 029a08051a87e..45e42e210de29 100644
> --- a/drivers/gpu/drm/tyr/vm.rs
> +++ b/drivers/gpu/drm/tyr/vm.rs
[ ... ]
> @@ -446,7 +484,6 @@ pub(crate) fn new_for_fw(
>      }
>  
>      /// Creates a user VM, splitting the GPU VA range per `user_va`.
> -    #[expect(dead_code)]
>      pub(crate) fn new_for_user(
>          dev: &'drm Device<Bound>,
>          ddev: &TyrDrmDevice,

[Severity: Medium]
On 32-bit ARM builds, does Vm::new_for_user() compute a 64-bit VA layout that
cannot be mapped by pt_map() and pt_unmap()?

drivers/gpu/drm/tyr/vm.rs:Vm::new_for_user() {
        let mmu_features = MMU_FEATURES::from_raw(gpu_info.mmu_features);
        let va_bits = mmu_features.va_bits().get();
        let range = 0..(1u64 << va_bits);
    ...
}

Because va_bits from MMU_FEATURES (e.g. 48) is not clamped to usize::BITS as
in C panthor_mmu_init(), VmLayout::compute() splits 1u64 << va_bits against a
32-bit task_size, placing the kernel VA region and user_va_range above
u32::MAX where pt_map() and pt_unmap() fail with EOVERFLOW when converting the
64-bit IOVA to a 32-bit usize.

[ ... ]

> @@ -656,16 +712,24 @@ pub(crate) fn map_bo_range(
> -        let mut resources = VmOpResources {
> -            preallocated_gpuvas: [
> -                Some(GpuVaAlloc::<GpuVmData<'drm>>::new(GFP_KERNEL)?),
> -                Some(GpuVaAlloc::<GpuVmData<'drm>>::new(GFP_KERNEL)?),
> -                Some(GpuVaAlloc::<GpuVmData<'drm>>::new(GFP_KERNEL)?),
> -            ],
> -        };
>          let result = {
>              let mut gpuvm_unique = self.gpuvm_unique.lock();
> -            self.exec_op(gpuvm_unique.as_mut().get_mut(), req, &mut 
> resources)
> +            // Check under the GPUVM lock, which the kill path also takes to
> +            // unmap, so this serializes against a concurrent teardown.
> +            if self.is_unusable() {
> +                dev_err!(
> +                    self.dev,
> +                    "Failed to map VA {:#x}..{:#x}: VM is unusable\n",
> +                    req.region.start,
> +                    req.region.end
> +                );
> +                // Drop the vm_bo reference before the deferred cleanup
> +                // below runs; otherwise the vm_bo would leak.
> +                drop(req);
> +                Err(EINVAL)
> +            } else {
> +                self.exec_op(gpuvm_unique.as_mut().get_mut(), req, &mut 
> resources)
> +            }
>          };

[Severity: Medium]
Should Vm::exec_op() call self.mark_unusable() when an operation fails?

Currently mark_unusable() is only called from Vm::kill() after the VM is
removed from VmPool.  If exec_op() fails partway through map_bo_range() or
unmap_range() (for example, if pt_map() hits ENOMEM after sm_map() has already
unmapped or split overlapping mappings), the VM is left partially modified in
the pool while vm_get_state() still reports DRM_PANTHOR_VM_STATE_USABLE and
subsequent map operations are not rejected.

-- 
Sashiko AI review ยท 
https://sashiko.dev/#/patchset/[email protected]?part=7

Reply via email to