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
2 changes: 1 addition & 1 deletion drivers/gpu/drm/asahi/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,7 @@ impl File {
let gpu = &reg_data.gpu;
let file_id = file.inner().id;
let vm = gpu
.new_vm_for_file(kernel_range.clone(), file_id)?
.new_vm_for_file(kernel_range.clone(), file_id, &file.inner().mem)?
.with_memory_client(file.inner().mem.clone());
// G16 registers a retained backend owner before returning this VM. Any later
// allocation can fail before file::Vm exists to run its normal close path.
Expand Down
11 changes: 8 additions & 3 deletions drivers/gpu/drm/asahi/g16/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -913,10 +913,15 @@ impl gpu::Gpu for Gpu {
}

fn new_vm(&self, kernel_range: Range<u64>) -> Result<mmu::Vm> {
vm::new_vm(self, kernel_range, 0)
vm::new_vm(self, kernel_range, 0, None)
}
fn new_vm_for_file(&self, kernel_range: Range<u64>, file_id: u64) -> Result<mmu::Vm> {
vm::new_vm(self, kernel_range, file_id)
fn new_vm_for_file(
&self,
kernel_range: Range<u64>,
file_id: u64,
memory: &Arc<crate::memacct::Client>,
) -> Result<mmu::Vm> {
vm::new_vm(self, kernel_range, file_id, Some(memory.clone()))
}
fn vm_closed(&self, vm: &mmu::Vm) {
self.vms.close(vm.id());
Expand Down
30 changes: 30 additions & 0 deletions drivers/gpu/drm/asahi/g16/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,7 @@ impl Factory {
mappings: KVec::new(),
error: None,
pages: 0,
charges: KVec::new(),
}
}

Expand All @@ -441,6 +442,7 @@ impl Factory {
mappings: KVec::new(),
error: None,
pages: 0,
charges: KVec::new(),
}
}

Expand All @@ -466,6 +468,7 @@ impl Factory {
mappings: KVec::new(),
error: None,
pages: 0,
charges: KVec::new(),
}
}

Expand Down Expand Up @@ -517,6 +520,8 @@ pub(crate) struct Objects {
error: Option<Error>,
/// Host-window pages backed by objects.
pages: usize,
/// The charges of private objects sized by the VM's client, held as long as their backing.
charges: KVec<crate::memacct::Charge>,
}

impl Objects {
Expand All @@ -539,6 +544,7 @@ impl Objects {
mappings: KVec::new(),
error: None,
pages: 0,
charges: KVec::new(),
})
}

Expand Down Expand Up @@ -628,8 +634,25 @@ impl Objects {
// A firmware-cached record needs a cacheable host view of the same pages (the host and
// firmware caches are coherent, as for G13-G15 private objects); every other private
// class keeps its write-combined view.
// A client VM's arena is client memory: admitted against, and counted for, its client
// instead of the device's kernel total.
let client = self
.private
.as_ref()
.and_then(|private| private.vm.as_ref())
.and_then(|vm| vm.memory_client());
let charge = match client {
Some(client) => {
self.charges.reserve(1, GFP_KERNEL)?;
let commit = crate::memacct::LEDGER.admit(client, bytes as u64)?;
Some(crate::memacct::Charge::user(commit, None))
}
None => None,
};
let mut backing = if req.class == Class::FwCoherent {
gem::new_kernel_object(&self.dev, bytes)?
} else if charge.is_some() {
gem::new_kernel_object_wc_user_charged(&self.dev, bytes)?
} else {
gem::new_kernel_object_wc(&self.dev, bytes)?
};
Expand Down Expand Up @@ -743,6 +766,13 @@ impl Objects {
cached_cpu,
}));
let _ = self.retained.push_within_capacity(object.clone());
// Held only once nothing can fail any more: an earlier error frees the backing, and a
// held charge left behind in a container that lives on would count memory that is gone.
// `charges` has room reserved; a charge that could not be kept uncharges on drop.
if let Some(charge) = charge {
charge.set_held(true);
let _ = self.charges.push_within_capacity(charge);
}
self.pages += bytes / hw::PAGE as usize;
Ok(object)
}
Expand Down
80 changes: 58 additions & 22 deletions drivers/gpu/drm/asahi/g16/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
//! (`vm.install_driver_mappings`): user binds there fail (EINVAL);
//! - 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).
//! 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.
//!
//! 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
Expand Down Expand Up @@ -174,11 +175,12 @@ pub(crate) struct LiveToken {
registry: Arc<Registry>,
bind: Option<mmu::VmBind>,
file_id: u64,
process: usize,
}
impl Drop for LiveToken {
fn drop(&mut self) {
drop(self.bind.take());
self.registry.release(self.file_id);
self.registry.release(self.file_id, self.process);
}
}

Expand All @@ -193,10 +195,13 @@ pub(crate) struct Registry {
/// 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);
struct Reservation<'a>(Option<&'a Registry>, u64, usize);

impl Reservation<'_> {
fn into_state(mut self) {
Expand All @@ -207,7 +212,7 @@ impl Reservation<'_> {
impl Drop for Reservation<'_> {
fn drop(&mut self) {
if let Some(registry) = self.0 {
registry.release(self.1);
registry.release(self.1, self.2);
}
}
}
Expand All @@ -221,6 +226,8 @@ impl Registry {
vms <- new_mutex!(vms, "g16::Registry::vms"),
live: AtomicU32::new(0),
files <- new_mutex!(files, "g16::Registry::files"),
processes <- new_mutex!(crate::queue_share::Shares::new(),
"g16::Registry::processes"),
}),
GFP_KERNEL,
)
Expand All @@ -243,29 +250,47 @@ impl Registry {
let rollback = kernel::types::ScopeGuard::new(|| {
self.live.fetch_sub(1, Ordering::AcqRel);
});
{
let process = {
let mut files = self.files.lock();
if let Some((_, count)) = files.iter_mut().find(|(id, _)| *id == file_id) {
if *count >= MAX_VMS_PER_FILE {
return Err(ENOSPC);
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 });
}
*count += 1;
} else {
files.push((file_id, 1), GFP_NOWAIT)?;
}
}
};
rollback.dismiss();
Ok(Reservation(Some(self), file_id))
Ok(Reservation(Some(self), file_id, process))
}

fn release(&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);
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)
};
// Drops the process's mm reference outside the registry locks.
drop(gone);
self.live.fetch_sub(1, Ordering::AcqRel);
}

Expand Down Expand Up @@ -389,7 +414,14 @@ pub(crate) fn reserved_ranges() -> [Range<u64>; 2] {
}

/// Creates a user VM (`gpu::Gpu::new_vm`).
pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range<u64>, file_id: u64) -> Result<mmu::Vm> {
///
/// Kernel memory sized by the VM's client (its private arenas) is charged to `memory`.
pub(crate) fn new_vm(
gpu: &Gpu,
kernel_range: Range<u64>,
file_id: u64,
memory: Option<Arc<crate::memacct::Client>>,
) -> Result<mmu::Vm> {
if gpu.shared.crashed.load(Ordering::Acquire) {
return Err(EIO);
}
Expand All @@ -404,10 +436,13 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range<u64>, file_id: u64) -> Resul
};
let reservation = registry.reserve(file_id)?;
let id = gpu.ids.vm.next();
let vm = gpu
let mut vm = gpu
.uat
.new_vm(id, kernel_range.clone())?
.with_tracked_status()?;
if let Some(memory) = memory {
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.
let failed_vm = kernel::types::ScopeGuard::new_with_data(vm.clone(), |vm| {
Expand All @@ -431,6 +466,7 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range<u64>, file_id: u64) -> Resul
registry: registry.clone(),
bind: Some(bind),
file_id,
process: reservation.2,
})
.into();
reservation.into_state();
Expand Down
10 changes: 8 additions & 2 deletions drivers/gpu/drm/asahi/gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,8 +508,14 @@ pub(crate) trait Gpu: Send + Sync {
}
/// Create a new `Vm` with the given range reserved for kernel-managed objects.
fn new_vm(&self, kernel_range: Range<u64>) -> Result<mmu::Vm>;
/// Create a VM charged to a DRM file when the backend bounds retained bindings.
fn new_vm_for_file(&self, kernel_range: Range<u64>, _file_id: u64) -> Result<mmu::Vm> {
/// Create a VM charged to a DRM file when the backend bounds retained bindings; kernel
/// memory the backend sizes by the VM's client is charged to `_memory`.
fn new_vm_for_file(
&self,
kernel_range: Range<u64>,
_file_id: u64,
_memory: &Arc<crate::memacct::Client>,
) -> Result<mmu::Vm> {
self.new_vm(kernel_range)
}
/// Release the backend's handle owner after closing user mapping admission.
Expand Down
73 changes: 69 additions & 4 deletions drivers/gpu/drm/asahi/queue_share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,31 @@ fn may_take(held: u32, total: u32, max: u32) -> bool {
held < max / 2 || held == total || max.saturating_sub(total.saturating_add(1)) >= reserve(max)
}

/// [`may_take`] for a resource a process keeps until it closes it (a G16 VM's TTBAT slot):
/// even a process alone leaves [`reserve`] free, or one client started before the compositor
/// would hold every slot until it exits.
fn may_take_held(held: u32, total: u32, max: u32) -> bool {
held < max / 2 || max.saturating_sub(total.saturating_add(1)) >= reserve(max)
}

/// Counts a new queue against the process `key`; EBUSY when [`may_take`] refuses it.
fn take(processes: &mut KVec<Process>, key: usize, mm: Option<ARef<Mm>>, max: u32) -> Result {
take_with(processes, key, mm, max, GFP_KERNEL, may_take)
}

fn take_with(processes: &mut KVec<Process>, key: usize, mm: Option<ARef<Mm>>, max: u32,
flags: kernel::alloc::Flags, allowed: fn(u32, u32, u32) -> bool) -> Result {
let total = processes.iter().map(|process| process.held).sum::<u32>();
let index = processes.iter().position(|process| process.key == key);
let held = index.map_or(0, |index| processes[index].held);
if !may_take(held, total, max) {
if !allowed(held, total, max) {
return Err(EBUSY);
}
match index {
Some(index) => processes[index].held += 1,
None => {
let (tgid, comm) = current_name();
processes.push(Process { key, _mm: mm, held: 1, tgid, comm }, GFP_KERNEL)?
processes.push(Process { key, _mm: mm, held: 1, tgid, comm }, flags)?
}
}
Ok(())
Expand Down Expand Up @@ -114,6 +126,36 @@ fn give_back(processes: &mut KVec<Process>, key: usize) -> Option<Process> {
(processes[index].held == 0).then(|| processes.swap_remove(index))
}

/// The current process's key and an `mm` reference that keeps it from being reused.
fn current_key() -> (usize, Option<ARef<Mm>>) {
let mm = kernel::current!().mm().map(|mm| ARef::from(&**mm));
(mm.as_ref().map_or(0, |mm| mm.as_raw() as usize), mm)
}

/// Another device-wide resource shared between processes, under its owner's lock: by the
/// queues' rule, except that a process alone also leaves the reserve ([`may_take_held`]).
pub(crate) struct Shares(KVec<Process>);

impl Shares {
pub(crate) const fn new() -> Self {
Self(KVec::new())
}

/// Counts one more of the `max` against the current process and returns its key; EBUSY
/// when [`may_take_held`] refuses it.
pub(crate) fn take_current(&mut self, max: u32, flags: kernel::alloc::Flags) -> Result<usize> {
let (key, mm) = current_key();
take_with(&mut self.0, key, mm, max, flags, may_take_held)?;
Ok(key)
}

/// Gives one back of the process `key`; returns the process once it holds none, to drop
/// outside the owner's lock.
pub(crate) fn give_back(&mut self, key: usize) -> Option<Process> {
give_back(&mut self.0, key)
}
}

/// One queue counted against the process that created it; dropping it gives the queue back.
pub(crate) struct Share {
key: usize,
Expand All @@ -122,8 +164,7 @@ pub(crate) struct Share {
impl Share {
/// Counts a new queue against the current process, of the device's `max` queues.
pub(crate) fn take_current(max: u32) -> Result<Self> {
let mm = kernel::current!().mm().map(|mm| ARef::from(&**mm));
let key = mm.as_ref().map_or(0, |mm| mm.as_raw() as usize);
let (key, mm) = current_key();
take(&mut PROCESSES.lock(), key, mm, max)?;
Ok(Self { key })
}
Expand Down Expand Up @@ -160,6 +201,30 @@ mod tests {
assert!(may_take(28, 57, 58));
}

#[test]
fn a_lone_vm_holder_still_leaves_the_reserve() -> Result {
// 63 G16 VM slots keep 7 free. A process alone stops at 56: the compositor started
// after it still gets a slot.
assert_eq!(reserve(63), 7);
assert!(may_take_held(55, 55, 63));
assert!(!may_take_held(56, 56, 63));
// Below half its share a process may still take from the reserve.
assert!(may_take_held(3, 60, 63));
let mut processes = KVec::new();
for _ in 0..56 {
take_with(&mut processes, 1, None, 63, GFP_KERNEL, may_take_held)?;
}
assert_eq!(
take_with(&mut processes, 1, None, 63, GFP_KERNEL, may_take_held),
Err(EBUSY)
);
// A second process (the compositor) gets one of the slots that were held back.
take_with(&mut processes, 2, None, 63, GFP_KERNEL, may_take_held)?;
// The same lone process may take every queue: queues are not held until close.
assert!(may_take(56, 56, 63));
Ok(())
}

#[test]
fn a_lone_process_with_two_files_reaches_the_full_budget() -> Result {
let mut processes = KVec::new();
Expand Down
Loading
Loading