Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
223 changes: 160 additions & 63 deletions drivers/gpu/drm/asahi/g16/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,18 @@
//! ([`object::Objects::clients`]) as driver mappings at their fixed GVAs, and reserve
//! [`super::hw::client::CLIENT_APERTURE`], the pass-slot range and the PB page list
//! (`vm.install_driver_mappings`): user binds there fail (EINVAL);
//! - keep it unbound ([`IdleVm`]) until its client creates a queue.
//!
//! With the VM's first queue ([`lookup`]):
//!
//! - bind it to an exclusive TTBAT slot ([`mmu::Uat::bind`]) for as long as its [`VmState`]
//! lives; at most [`super::hw::sizes::MAX_VMS`] such VMs (ENOSPC beyond, checked before
//! binding so the slot allocator never blocks), shared between processes as the queues are
//! ([`crate::queue_share::Shares`]), since a process may open the device many times.
//!
//! Only a queue's jobs run in a VM's context, so a VM without one needs no slot: a Vulkan
//! client opens one such VM for its physical device beside the VM its logical device uses.
//!
//! The [`VmState`] of a VM is shared by the [`Registry`] (while the client's VM handle exists),
//! the VM's queues and its jobs. It cannot be owned by the [`mmu::Vm`] itself: the slot binding
//! holds a `Vm` reference. The registry drops its reference once the shared lifetime reports the
Expand All @@ -34,6 +41,7 @@ use kernel::{
drm::gem::BaseObject,
new_mutex,
prelude::*,
rbtree::{RBTree, RBTreeNode},
sync::{aref::ARef, Arc, Mutex, UniqueArc},
};

Expand Down Expand Up @@ -133,7 +141,7 @@ pub(crate) struct VmStateInner {
/// The VM: span checks, stream reads and job guards.
pub(crate) vm: mmu::Vm,
/// Private mappings are kept outside generic close's user GPUVA teardown.
context_mappings: KVec<mmu::KernelMapping>,
context_mappings: Option<Arc<KVec<mmu::KernelMapping>>>,
pub(crate) resources: Option<Arc<super::resources::Cache>>,
#[allow(dead_code)]
pub(crate) live: Arc<LiveToken>,
Expand All @@ -152,42 +160,70 @@ impl Drop for VmStateInner {
fn drop(&mut self) {
mod_pr_debug!("G16: VM {} releases context {}\n", self.id, self.slot);
drop(self.resources.take());
self.context_mappings.clear();
drop(self.context_mappings.take());
}
}

/// Count a VM until every deferred arena has unmapped and released its binding.
/// Count a bound VM until every deferred arena has unmapped and released its binding.
pub(crate) struct LiveToken {
registry: Arc<Registry>,
bind: Option<mmu::VmBind>,
file_id: u64,
_place: Arc<FilePlace>,
process: usize,
}
impl Drop for LiveToken {
fn drop(&mut self) {
drop(self.bind.take());
self.registry.release(self.file_id, self.process);
self.registry.release(self.process);
}
}

/// One of its file's VMs, counted until the VM is closed and, if it was bound, every deferred
/// arena has unmapped.
pub(crate) struct FilePlace {
registry: Arc<Registry>,
file_id: u64,
}
impl Drop for FilePlace {
fn drop(&mut self) {
self.registry.leave(self.file_id);
}
}

/// Live-VM accounting and the VMs whose client handle is open.
/// A VM whose client has created no queue yet. Nothing runs in its context, so it holds no TTBAT
/// slot; [`lookup`] binds it for its first queue.
struct IdleVm {
vm: mmu::Vm,
status: Arc<VmStatus>,
mappings: Arc<KVec<mmu::KernelMapping>>,
place: Arc<FilePlace>,
}

/// VM accounting and the VMs whose client handle is open.
#[pin_data]
pub(crate) struct Registry {
/// VMs whose client handle may still be open, oldest first.
/// Bound VMs whose client handle may still be open, oldest first.
#[pin]
vms: Mutex<KVec<Arc<VmState>>>,
/// VMs without a queue, by identifier. Its nodes are allocated before taking the lock,
/// which `fail_all()` takes under the device lock.
#[pin]
idle: Mutex<RBTree<u64, IdleVm>>,
/// Serializes the binding of VMs ([`lookup`]): a VM is bound once.
#[pin]
binding: Mutex<()>,
/// Live [`VmState`]s (each holds a TTBAT slot) plus reservations being created.
live: AtomicU32,
/// Includes deferred/retained bindings after the file handle closes.
/// The VMs of each file. Includes deferred/retained bindings after the file handle closes.
#[pin]
files: Mutex<KVec<(u64, u32)>>,
/// The live VMs counted per creating process; taken under `files`.
#[pin]
processes: Mutex<crate::queue_share::Shares>,
}

/// A reserved place among the live VMs, released unless a [`VmState`] takes it over.
struct Reservation<'a>(Option<&'a Registry>, u64, usize);
/// A reserved TTBAT slot among the live VMs, released unless a [`VmState`] takes it over.
struct Reservation<'a>(Option<&'a Registry>, usize);

impl Reservation<'_> {
fn into_state(mut self) {
Expand All @@ -198,7 +234,7 @@ impl Reservation<'_> {
impl Drop for Reservation<'_> {
fn drop(&mut self) {
if let Some(registry) = self.0 {
registry.release(self.1, self.2);
registry.release(self.1);
}
}
}
Expand All @@ -210,6 +246,8 @@ impl Registry {
Arc::pin_init(
pin_init!(Self {
vms <- new_mutex!(vms, "g16::Registry::vms"),
idle <- new_mutex!(RBTree::new(), "g16::Registry::idle"),
binding <- new_mutex!((), "g16::Registry::binding"),
live: AtomicU32::new(0),
files <- new_mutex!(files, "g16::Registry::files"),
processes <- new_mutex!(crate::queue_share::Shares::new(),
Expand All @@ -219,8 +257,40 @@ impl Registry {
)
}

/// Reserves a place for a new VM after dropping the registry's references to closed VMs.
fn reserve(&self, file_id: u64) -> Result<Reservation<'_>> {
/// Counts a new VM against its file.
fn admit(registry: &Arc<Self>, file_id: u64) -> Result<Arc<FilePlace>> {
// The place gives its count back when dropped, so allocate it before counting.
let place = UniqueArc::<FilePlace>::new_uninit(GFP_KERNEL)?;
{
let mut files = registry.files.lock();
match files.iter().position(|(id, _)| *id == file_id) {
Some(index) if files[index].1 >= MAX_VMS_PER_FILE => return Err(ENOSPC),
Some(index) => files[index].1 += 1,
None => files.push((file_id, 1), GFP_NOWAIT)?,
}
}
Ok(place
.write(FilePlace {
registry: registry.clone(),
file_id,
})
.into())
}

/// Takes a VM off its file's count.
fn leave(&self, file_id: u64) {
let mut files = self.files.lock();
if let Some(index) = files.iter().position(|(id, _)| *id == file_id) {
files[index].1 -= 1;
if files[index].1 == 0 {
let _ = files.remove(index);
}
}
}

/// Reserves a TTBAT slot for a VM's first queue after dropping the registry's references to
/// closed VMs.
fn reserve(&self) -> Result<Reservation<'_>> {
self.prune();
// The shared slot allocator hands out a single slot with robust isolation.
let limit = if module_parameters::robust_isolation.value() != 0 {
Expand All @@ -236,45 +306,18 @@ impl Registry {
let rollback = kernel::types::ScopeGuard::new(|| {
self.live.fetch_sub(1, Ordering::AcqRel);
});
let process = {
let mut files = self.files.lock();
let index = match files.iter().position(|(id, _)| *id == file_id) {
Some(index) if files[index].1 >= MAX_VMS_PER_FILE => return Err(ENOSPC),
Some(index) => index,
None => {
files.push((file_id, 0), GFP_NOWAIT)?;
files.len() - 1
}
};
match self.processes.lock().take_current(limit, GFP_NOWAIT) {
Ok(process) => {
files[index].1 += 1;
process
}
Err(error) => {
if files[index].1 == 0 {
let _ = files.remove(index);
}
// The share refusing is "no room"; a failed allocation stays ENOMEM.
return Err(if error == EBUSY { ENOSPC } else { error });
}
}
};
let process = self
.processes
.lock()
.take_current(limit, GFP_NOWAIT)
// The share refusing is "no room"; a failed allocation stays ENOMEM.
.map_err(|error| if error == EBUSY { ENOSPC } else { error })?;
rollback.dismiss();
Ok(Reservation(Some(self), file_id, process))
Ok(Reservation(Some(self), process))
}

fn release(&self, file_id: u64, process: usize) {
let gone = {
let mut files = self.files.lock();
if let Some(index) = files.iter().position(|(id, _)| *id == file_id) {
files[index].1 -= 1;
if files[index].1 == 0 {
let _ = files.remove(index);
}
}
self.processes.lock().give_back(process)
};
fn release(&self, process: usize) {
let gone = self.processes.lock().give_back(process);
// Drops the process's mm reference outside the registry locks.
drop(gone);
self.live.fetch_sub(1, Ordering::AcqRel);
Expand All @@ -283,6 +326,9 @@ impl Registry {
/// Drop the handle owner immediately, outside the registry lock. Other references
/// still protect jobs, both hardware units' last owners, and deferred destruction.
pub(crate) fn close(&self, id: u64) {
// A VM that never had a queue: its mappings go here, outside the registry locks.
let idle = self.idle.lock().remove_node(&id);
drop(idle);
let state = {
let mut vms = self.vms.lock();
let index = vms.iter().position(|state| state.id == id);
Expand Down Expand Up @@ -387,6 +433,9 @@ impl Registry {
/// Latches `error` on every VM whose client handle is open. The fail-stop path calls it under
/// the device lock.
pub(crate) fn fail_all(&self, error: Error) {
for idle in self.idle.lock().values() {
idle.status.record(error);
}
for state in self.vms.lock().iter() {
state.status.record(error);
}
Expand All @@ -399,7 +448,7 @@ pub(crate) fn reserved_ranges() -> [Range<u64>; 2] {
[0x1000000000..0x1000010000, 0x7000000000..0x7100000000]
}

/// Creates a user VM (`gpu::Gpu::new_vm`).
/// Creates a user VM (`gpu::Gpu::new_vm`), unbound until its first queue.
///
/// Kernel memory sized by the VM's client (its private arenas) is charged to `memory`.
pub(crate) fn new_vm(
Expand All @@ -414,13 +463,13 @@ pub(crate) fn new_vm(
// Reserve outside the device lock: reclaim may wait for a fence whose poller needs it.
let mut aliases = KVec::with_capacity(hw::sizes::MAX_CLIENT, GFP_KERNEL)?;
// Snapshot only references and metadata under the device lock; map after releasing it.
let (registry, factory) = {
let registry = {
let state = gpu.shared.state.lock();
let firmware = state.as_ref().ok_or(ENODEV)?;
ClientAlias::collect(&firmware.objects, &mut aliases)?;
(firmware.vms.clone(), firmware.private_factory.clone())
firmware.vms.clone()
};
let reservation = registry.reserve(file_id)?;
let place = Registry::admit(&registry, file_id)?;
let id = gpu.ids.vm.next();
let mut vm = gpu
.uat
Expand All @@ -430,7 +479,7 @@ pub(crate) fn new_vm(
vm = vm.with_memory_client(memory);
}
// Driver mappings retain their VM. Break that ownership if any later step fails,
// including binding/state allocation and registry insertion.
// including registry insertion.
let failed_vm = kernel::types::ScopeGuard::new_with_data(vm.clone(), |vm| {
if let Err(error) = vm.unmap_user_ranges(hw::USER_RANGE.clone(), kernel_range) {
pr_err!("G16: closing unpublished VM failed: {:?}\n", error);
Expand All @@ -440,7 +489,41 @@ pub(crate) fn new_vm(
let status = vm.status().ok_or(EINVAL)?.clone();
let (mappings, reserved) = Registry::driver_mappings(&vm, aliases)?;
vm.install_driver_mappings(KVec::new(), reserved)?;
// The context names the root only now: everything above is already visible to the walker.
let idle = IdleVm {
vm: vm.clone(),
status,
mappings: Arc::new(mappings, GFP_KERNEL)?,
place,
};
let node = RBTreeNode::new(id, idle, GFP_KERNEL)?;
// Identifiers are never reused, so nothing is replaced.
let replaced = registry.idle.lock().insert(node);
drop(replaced);
drop(failed_vm.dismiss());
Ok(vm)
}

/// Binds the idle VM `vm` to a TTBAT slot for its first queue. The caller holds
/// [`Registry::binding`]; a failure leaves the VM idle.
fn bind_idle(
gpu: &Gpu,
registry: &Arc<Registry>,
factory: object::Factory,
id: u64,
) -> Result<Arc<VmState>> {
let (vm, status, mappings, place) = {
let idle = registry.idle.lock();
let idle = idle.get(&id).ok_or(ENOENT)?;
(
idle.vm.clone(),
idle.status.clone(),
idle.mappings.clone(),
idle.place.clone(),
)
};
let reservation = registry.reserve()?;
// The context names the root only now: the driver mappings and everything the client mapped
// so far are already visible to the walker.
let bind = gpu.uat.bind(&vm)?;
let slot = bind.slot();
let generation = bind.generation();
Expand All @@ -451,8 +534,8 @@ pub(crate) fn new_vm(
.write(LiveToken {
registry: registry.clone(),
bind: Some(bind),
file_id,
process: reservation.2,
_place: place,
process: reservation.1,
})
.into();
reservation.into_state();
Expand All @@ -468,21 +551,35 @@ pub(crate) fn new_vm(
generation,
status,
vm: vm.clone(),
context_mappings: mappings,
context_mappings: Some(mappings),
resources: Some(resources),
live,
};
let state = Arc::new(VmState(crate::cleanup::Deferred::new(inner)?), GFP_KERNEL)?;
// Registry storage was bounded and preallocated at backend startup. NOWAIT also keeps
// an invariant failure from entering reclaim under a lock required by fail_all().
registry.vms.lock().push(state, GFP_NOWAIT)?;
drop(failed_vm.dismiss());
registry.vms.lock().push(state.clone(), GFP_NOWAIT)?;
let idle = registry.idle.lock().remove_node(&id);
drop(idle);
// A close that found neither: the VM was closed before its state was pushed.
if vm.is_closed() {
registry.close(id);
return Err(ENOENT);
}
mod_pr_debug!("G16: VM {} context {}\n", id, slot);
Ok(vm)
Ok(state)
}

/// The state of a VM for a new queue.
pub(crate) fn lookup(gpu: &Gpu, vm: &mmu::Vm) -> Result<Arc<VmState>> {
let registry = gpu.shared.state.lock().as_ref().ok_or(ENODEV)?.vms.clone();
registry.find(vm)
let (registry, factory) = {
let state = gpu.shared.state.lock();
let firmware = state.as_ref().ok_or(ENODEV)?;
(firmware.vms.clone(), firmware.private_factory.clone())
};
let _binding = registry.binding.lock();
match registry.find(vm) {
Err(error) if error == ENOENT => bind_idle(gpu, &registry, factory, vm.id()),
found => found,
}
}
Loading
Loading