dri-devel Archive on lore.kernel.org
 help / color / mirror / Atom feed
From: sashiko-bot@kernel.org
To: "Philipp Stanner" <phasta@kernel.org>
Cc: dri-devel@lists.freedesktop.org, media-ci@linuxtv.org,
	ojeda@kernel.org, gary@garyguo.net
Subject: Re: [PATCH v3 8/9] rust: drm: Add JobQueue
Date: Wed, 02 Dec 2026 12:04:48 +0000	[thread overview]
Message-ID: <sashiko-outbox-245661@kernel.org> (raw)
In-Reply-To: <20261202113914.1660411-10-phasta@kernel.org>

Thank you for your contribution! Sashiko AI review found 11 potential
issues to consider:
- [High] rust: dma_fence: payload destructor skipped in
  DriverFence::drop()
- [High] rust: drm: missing Signed-off-by trailer for Co-developed-by
  author
- [High] rust: drm: unsound lifetime transmute, aliasing, and teardown
  in JobQueue
- [High] rust: drm: fence signaling and job drop under SpinLockIrq in
  JobQueue
- [Medium] rust: drm: unscheduled DropWorker in RunWorker::run() on
  completion race
- [Medium] rust: drm: unsignaled waiting_jobs and serial RCU waits in
  JobQueue::drop()
- [Medium] rust: drm: RunWorker::run() does not re-check parked inside
  job loop
- [Medium] rust: drm: missing Release-Acquire ordering on nr_of_deps in
  job_queue
- [Medium] rust: drm: signed i64 cast of u64 capacity in
  RunWorker::run()
- [Low] rust: drm: spurious and missed worker wakeups in JobQueue
  completion
- [Low] rust: drm: broken rustdoc links and missing #[inline] in
  job_queue.rs
--

commit e74c12be9636b8996c8f70b342962e1ee1b25813
Author: Philipp Stanner <phasta@kernel.org>

> rust: drm: Add JobQueue
>
> JobQueue is a pure Rust component that handles job submissions for GPUs
> with firmware scheduling, i.e., GPUs that support one exclusive ring per
> execution context.
>
> JobQueue's primary task is dependency handling, where the user can set
> dependencies, each in the form of a `dma_buf::Fence`, on a job and then
> submit it to the queue.
>
> Jobs are being executed in FIFO order. Only jobs whose dependencies are
> all fulfilled get executed, otherwise the JobQueue pauses.
>
> A core design principle, just like with DmaFence, is to avoid all
> allocations in job submission paths, since this runs danger of
> deadlocking. For the same reason JobQueue's run_job workqueue is
> reclaim-safe.
>
> Another design principle, new when compared to the older drafts, is the
> ownership relationship with fences:
>
>   1. The JobQueue owns the FenceContext exclusively.
>   2. Jobs are created on the JobQueue, ensuring correct fence sequence
>      number ordering.
>   3. Jobs own the respective DriverFence.
>   4. Jobs are owned by the JobQueue.
>
> Consequently, a driver can only interact with fences and FenceContext
> indirectly through the JobQueue, and can also only complete jobs (and,
> hence, signal fences) through the JobQueue.
>
> Like drm_sched, JobQueue currently does not take errors set on job
> dependency fences into account. The reasons are that only all
> dependencies being signaled is decisive for memory safety, and that we
> would first have to establish what the semantic meaning of fence errors
> actually is. That's especially difficult when you consider that fences
> can be shared across drivers. Nevertheless, it would be doable to inform
> drivers through their run_job callback that this particular jobs has
> failed (but signaled) dependencies, and then allow the driver to make a
> decision on how to proceed (i.e., ignore or kill JQ).
>
> When a job shall be run, both its JobQueue::data and Job::data get
> borrowed back to the driver, together with the sequence number of this
> job, so that it can perform the appropriate interaction with the
> hardware.
>
> The RunWorker runs all ready jobs based on a credit count system, so
> that run_job() is infallible. A separate worker drops jobs (and
> their fences) that are already completed, but only if the user's payload
> data actually requires Drop. Otherwise, jobs are dropped by the
> RunWorker directly.
>
> Data left over by the workers drops together with JobQueue. For this
> reason, and because a JobQueue owns a FenceContext, it must only ever
> be dropped in process context.
>
> Signed-off-by: Philipp Stanner <phasta@kernel.org>
> Co-developed-by: Gary Guo <gary@garyguo.net>
>
> (^ waiting for Gary to sign-off)

[Severity: High]
Co-developed-by: Gary Guo is missing a matching Signed-off-by: trailer right
after it, the submitter's Signed-off-by: trailer should come last, and the
draft note at the bottom is still present.

> diff --git a/rust/kernel/drm/job_queue.rs b/rust/kernel/drm/job_queue.rs
> new file mode 100644
> index 0000000000000..063a04d684b14
> --- /dev/null
> +++ b/rust/kernel/drm/job_queue.rs
[ ... ]
> +impl<'b, T: JobQueueOps + Send + Sync> FenceCallback for DependencyWaker<'b, '_, T> {
> +    fn on_signal(&mut self, _res: Result) {
> +        // Last dependency kicks the worker. This cannot cause UAF on JQ if the
> +        // associated job was forgotten because only submitted jobs can reach 0.
> +        if self.nr_of_deps.fetch_sub(1, Relaxed) == 1 {
> +            // The drop-order of JobQueue ensures that all DependencyWakers are
> +            // cancelled before the JobQueue itself is dropped.
> +            self.jq.check_start_run_worker();
> +        }
> +    }
> +}

[Severity: Medium]
Can RunWorker::run() invoke T::run_job() on weakly-ordered architectures
before memory writes from dependency fence completions are visible?

DependencyWaker::on_signal() and Job::submit() decrement nr_of_deps with
Relaxed ordering, and RunWorker::run() loads nr_of_deps with Relaxed ordering
before dropping the spinlock and calling T::run_job().  If RunWorker::run()
is already looping when the last dependency signals, or if a dependency
signals before Job::submit() performs the final decrement to 0, nothing
establishes a happens-before relationship between the fence completion and
T::run_job().  Using Release on the fetch_sub() calls paired with Acquire on
the load in RunWorker::run() would synchronize all dependency completions.

[ ... ]
> +impl<T: JobQueueOps + Send + Sync> ScopedWorkItem for RunWorker<'_, '_, T> {
> +    fn run(work: &ScopedWork<Self>) {
> +        // Synchronize against revocation in `JobQueue::drop`.
> +        let _lock_guard = work.srcu.read_lock();
> +        if work.parked.load(Relaxed) {
> +            return;
> +        }
> +
> +        let mut jq = work.inner.lock();
> +
> +        while let Some(job) = jq.waiting_jobs.pop_front() {

[Severity: Medium]
If JobQueue::park() or JobQueue::drop() runs while T::run_job() is executing
unlocked inside this loop, doesn't RunWorker::run() keep submitting the
remaining ready jobs in waiting_jobs?  work.parked is only checked once
before the loop, while the SRCU read lock is held across all iterations.

> +            // While we didn't hold the lock below for `run_job()`, it could be
> +            // that a new job entered the waiting list which has an unfulfilled
> +            // dependency.
> +            if job.nr_of_deps.load(Relaxed) > 0 {
> +                jq.waiting_jobs.push_front(job);
> +                break;
> +            }
> +            let new_capacity = jq.capacity as i64 - i64::from(job.cost);
> +            if new_capacity < 0 {
> +                jq.waiting_jobs.push_front(job);
> +                break;
> +            }
> +            *jq.as_mut().project().capacity = new_capacity as u64;

[Severity: Medium]
Can casting jq.capacity to i64 wrap negative or underflow when JobQueue::new()
is given a capacity above i64::MAX as u64?  Using
jq.capacity.checked_sub(u64::from(job.cost)) avoids the signed conversion.

> +
> +            let fence = job.fence.as_ref().expect("fence not present");
> +            let seqno = fence.as_fence().seqno();
> +            let runnable_job = JobRunnable {
> +                seqno,
> +                data: fence.deref(),
> +            };
> +
> +            drop(jq); // Release lock.
> +            T::run_job(work.fctx, runnable_job);
> +            jq = work.inner.lock(); // Retake lock.
> +
> +            // run_job() above needs to be called without lock protection. Thus,
> +            // it is possible that the driver instructed completion right before
> +            // we could re-take the lock.
> +            if jq.last_completed >= seqno {
> +                *jq.as_mut().project().capacity += u64::from(job.cost);
> +                fence.signal(Ok(()));
> +
> +                // Drop here directly if possible. Otherwise, let the DropWorker
> +                // take care of it.
> +                if core::mem::needs_drop::<T::JobDataType>() {
> +                    jq.drop_list.push_back(job);
> +                }
> +            } else {
> +                jq.running_jobs.push_back(job);
> +            }
> +        }
> +    }
> +}

[Severity: Medium]
As reported by Younes Akhouayri on v1 [1], when a job completes while
T::run_job() is running unlocked, does pushing it onto jq.drop_list here leave
the job and its resources stranded until a later completion or queue teardown?

RunWorker                          <irq> / DropWorker
T::run_job()
                                   complete_jobs_up_to_seqno(seqno)
                                     *jq.last_completed = seqno
                                     check_start_drop_worker()
                                   DropWorker::run()
                                     pop_front() -> None
jq = work.inner.lock()
if jq.last_completed >= seqno
  jq.drop_list.push_back(job)      <-- drop_worker never re-scheduled

> +
> +struct DropWorker<'a, 'fctx, T: JobQueueOps + Send + Sync> {
> +    inner: &'a SpinLockIrq<JobQueueInner<'fctx, T>>,
> +}
> +
> +impl<T: JobQueueOps + Send + Sync> ScopedWorkItem for DropWorker<'_, '_, T> {
> +    fn run(work: &ScopedWork<Self>) {
> +        let mut jq_locked = work.inner.lock();
> +
> +        while let Some(job) = jq_locked.drop_list.pop_front() {
> +            drop(jq_locked);
> +            drop(job);
> +            jq_locked = work.inner.lock();
> +        }
> +    }
> +}

[Severity: High]
When DropWorker::run() or JobQueue::drop() drops a job, does T::JobDataType's
destructor ever run?

JobQueue::new_job() places the payload in DriverFenceData::data via
FenceContext::new_fence_allocation(), so dropping the job relies on
DriverFence::drop() introduced in commit "rust: DmaFence: Replace call_rcu()
with RcuState":

rust/kernel/dma_buf/dma_fence.rs:DriverFence::drop() {
    ...
        // SAFETY: Valid because `self` is valid. RCU above ensures that all
        // accessors are gone.
        unsafe { drop_in_place(&raw mut self.data) };

        // SAFETY: Valid because `self` is valid. This is the initial reference
        // from when this `DriverFence` was created.
        unsafe { bindings::dma_fence_put(self.as_raw()) };
}

self.data in DriverFence is a NonNull<DriverFenceData<'a, T>> pointer wrapper
rather than (*self.data.as_ptr()).data, so drop_in_place(&raw mut self.data)
is a no-op and dma_fence_put() frees the backing memory without running the
payload's Drop implementation.

[ ... ]
> +    /// Give the unique identifier for this JobQueue.
> +    ///
> +    /// This corresponds to the JobQueue's underlying [`FenceContext`].
> +    /// It is unique for all JobQueues in the entire system.
> +    pub fn id(&self) -> u64 {
> +        self.fctx.id()
> +    }
[ ... ]
> +    /// Prevent the JobQueue from further calling [`JobQueueOps::run_job()`].
> +    ///
> +    /// The JobQueue will not call [`JobQueueOps::run_job()`] anymore after this
> +    /// function returned, until you call [`JobQueue:unpark()`].

[Severity: Low]
This doc comment has a broken single-colon intra-doc link
([`JobQueue:unpark()`]), and the [`dma_buf::DriverFence`] and
[`dma_buf::Fence`] links earlier in this file do not resolve because dma_buf
is not in scope.  Also, small wrapper and accessor functions in the kernel
crate (JobQueue::id, JobQueue::deref, JobQueue::set_error, DriverDataWrapper's
methods, and UniqueList's methods) should be marked #[inline].

[ ... ]
> +    pub fn complete_jobs_up_to_seqno(&self, seqno: u64) {
> +        self.with_inner(|inner| {
> +            let needs_drop = core::mem::needs_drop::<T::JobDataType>();
> +            let mut jq_locked = inner.lock();
> +            let mut jq = jq_locked.as_mut().project();
> +
> +            if seqno < *jq.last_completed {
> +                return;
> +            }
> +
> +            while let Some(mut job) = jq.running_jobs.pop_front() {
> +                if job
> +                    .as_mut()
> +                    .project()
> +                    .fence
> +                    .as_mut()
> +                    .expect("fence not present")
> +                    .as_fence()
> +                    .seqno()
> +                    > seqno
> +                {
> +                    jq.running_jobs.push_front(job);
> +                    break;
> +                }
> +
> +                *jq.capacity += u64::from(job.cost);
> +
> +                let fence = job.fence.as_ref().expect("fence not present");
> +                fence.signal(Ok(()));
> +
> +                if needs_drop {
> +                    jq.drop_list.push_back(job);
> +                }
> +                // Otherwise, job is dropped here directly. Its fence won't
> +                // perform an RCU grace period wait.
> +            }

[Severity: High]
Can calling fence.signal(Ok(())) under inner.lock() (and in RunWorker::run())
deadlock if a fence callback submits or completes a job?

complete_jobs_up_to_seqno()
  jq_locked = inner.lock()
  fence.signal(Ok(()))
    dma_fence_signal_locked()
      FenceCallback::on_signal()
        Job::submit()
          inner.lock()  <-- spins forever

Even across different queues, signaling a fence under inner.lock() nests
dma_fence->lock inside JobQueue::inner's lockdep class, while a fence callback
calling Job::submit() or complete_jobs_up_to_seqno() acquires JobQueue::inner
under dma_fence->lock.  When !needs_drop, dropping job at the end of the loop
body also runs under SpinLockIrq, acquiring each dependency fence's lock via
dma_fence_remove_callback() and freeing the job and dependency allocations
with interrupts disabled.

> +
> +            // This enables the RunWorker to complete a job that is not yet
> +            // in 'running_jobs', in case of a race against the lock.
> +            *jq.last_completed = seqno;
> +            drop(jq_locked);
> +
> +            self.check_start_run_worker();
> +            if needs_drop {
> +                self.check_start_drop_worker();
> +            }
> +        })
> +    }

[Severity: Low]
As reported by Younes Akhouayri on v1 [2], if seqno == *jq.last_completed (or
when no jobs in running_jobs had a sequence number <= seqno), this does not
return early and unconditionally schedules both run_worker and drop_worker,
while the raced completion path in RunWorker::run() pushes to jq.drop_list
without calling check_start_drop_worker().  In addition, RunWorker::run()
keeps job.dependencies populated after nr_of_deps reaches 0, holding the
Dependency allocations and upstream fence references until the job finishes on
hardware.

> +
> +    /// Set the error with which this JobQueue will signal all running jobs'
> +    /// fences. (The jobs on the waiting_list will all complete with ECANCELED
> +    /// as their error)
> +    pub fn set_error(mut self: Pin<&mut Self>, error: Error) {
> +        *self.as_mut().project().err = error;
> +    }
> +}
> +
> +#[pinned_drop]
> +impl<T: JobQueueOps + Send + Sync> PinnedDrop for JobQueue<T> {
> +    fn drop(self: Pin<&mut Self>) {
> +        // Prevent the RunWorker from moving more jobs to `running_jobs`.
> +        self.park();
> +        self.with_inner(|inner| {
> +            let mut inner_locked = inner.lock();
> +            let drop_list = core::mem::take(&mut inner_locked.drop_list);
> +            let waiting_jobs = core::mem::take(&mut inner_locked.waiting_jobs);
> +            let mut running_jobs = core::mem::take(&mut inner_locked.running_jobs);
> +
> +            drop(inner_locked);
> +
> +            while let Some(job) = running_jobs.pop_front() {
> +                let fence = job.fence.as_ref().expect("fence not present");
> +                fence.signal(Err(self.err));
> +            }
> +
> +            drop(drop_list);
> +            drop(waiting_jobs);
> +            drop(running_jobs);
> +        })
> +    }
> +}

[Severity: High]
Does JobQueue::drop() guarantee that all transmuted &JobQueue<T> and
&FenceContext references in jobs are gone before JobQueue's fields are
destroyed?

CPU0                                     CPU1 (DropWorker)
DropWorker::run()
                                           job = jq_locked.drop_list.pop_front()
                                           drop(jq_locked)
JobQueue::drop()
  self.park()
  take(&mut inner_locked.drop_list)
  ...
  // struct fields drop:
  // drop_queue dropped before drop_worker
  // fctx dropped
                                           drop(job)  <-- accesses dangling fctx/jq

There are three related lifetime and teardown issues here:

1. In struct JobQueue, drop_queue and run_queue (OwnedQueue) are declared
   before drop_worker and run_worker (ScopedWork), so the workqueues are
   destroyed before the ScopedWork items that run on them are cancelled and
   dropped (and #[uses('_: invariant, 'parked: invariant, 'srcu: invariant)]
   is attached to drop_worker instead of run_worker).

2. Because Job::submit() erases the shared borrow of JobQueue, set_error() and
   PinnedDrop::drop() take Pin<&mut Self> while DependencyWaker callbacks in
   waiting_jobs still hold &JobQueue<T>; a dependency fence signaling before
   drop(waiting_jobs) dereferences self.jq concurrently with Pin<&mut Self>
   and calls check_start_run_worker() after self.park() has returned.

3. If a caller forgets an unsubmitted Job after Job::add_dependency(),
   fctx.nr_of_unsignaled_fences was never incremented (new_fence() is only
   called in submit()), so dropping JobQueue leaves the leaked
   DependencyWaker registered with a dangling &JobQueue<T>.

[Severity: Medium]
Are waiting_jobs' fences ever signaled with Err(ECANCELED) before
drop(waiting_jobs)?

Job::submit() already creates each job's DriverFence before pushing it to
waiting_jobs, so dropping waiting_jobs without signaling them triggers
DriverFence::drop()'s unsignaled error path (logging "DriverFence drops
unsignaled. Danger of memory corruption!" and calling an unconditional
synchronize_rcu() for every waiting job).  Also, in the running_jobs loop
above, each popped job is dropped at the end of the loop body right after
fence.signal(Err(self.err)), which waits for a full RCU grace period per
running job sequentially instead of signaling all fences before dropping the
jobs.

[1] https://lore.kernel.org/r/kw-1794059738.215694434-299782-0@younes.io
[2] https://lore.kernel.org/r/kw-1794059738.215694434-299782-0@younes.io

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261202113914.1660411-2-phasta@kernel.org?part=8

  reply	other threads:[~2026-12-02 12:05 UTC|newest]

Thread overview: 14+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-02 11:39 [PATCH v3 0/9] rust: Add drm::JobQueue Philipp Stanner
2026-12-02 11:39 ` [PATCH v3 1/9] rust: rcu: Add RcuState Philipp Stanner
2026-12-02 11:47   ` sashiko-bot
2026-12-02 11:39 ` [PATCH v3 2/9] rust: DmaFence: Implement Deref for FenceContext Philipp Stanner
2026-12-02 11:39 ` [PATCH v3 3/9] rust: DmaFence: Add ID accessor " Philipp Stanner
2026-12-02 11:39 ` [PATCH v3 4/9] rust: DmaFence: Don't drop on signal Philipp Stanner
2026-12-02 11:39 ` [PATCH v3 5/9] rust: DmaFence: Replace call_rcu() with RcuState Philipp Stanner
2026-12-02 11:49   ` sashiko-bot
2026-12-02 11:39 ` [PATCH v3 6/9] rust: DmaFence: Replace is_signaled() with status() Philipp Stanner
2026-12-02 11:54   ` sashiko-bot
2026-12-02 11:39 ` [PATCH v3 7/9] rust: DmaFence: Pass result in callbacks Philipp Stanner
2026-12-02 11:39 ` [PATCH v3 8/9] rust: drm: Add JobQueue Philipp Stanner
2026-12-02 12:04   ` sashiko-bot [this message]
2026-12-02 11:39 ` [PATCH v3 9/9] MAINTAINERS: Add drm::JobQueue to drm_sched's entry Philipp Stanner

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=sashiko-outbox-245661@kernel.org \
    --to=sashiko-bot@kernel.org \
    --cc=dri-devel@lists.freedesktop.org \
    --cc=gary@garyguo.net \
    --cc=media-ci@linuxtv.org \
    --cc=ojeda@kernel.org \
    --cc=phasta@kernel.org \
    --cc=sashiko-reviews@lists.linux.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox