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
40 changes: 21 additions & 19 deletions drivers/gpu/drm/asahi/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ impl drm::driver::Driver for AsahiDrmDriver {
/// Firmware interface selected by the hardware compatible.
pub(crate) enum ProbeConfig {
Legacy(&'static hw::HwConfig),
LegacyWithG14Handoff(&'static hw::HwConfig),
G17(&'static g17::Config),
/// M5 Pro, Max and Ultra: the ID registers select the configuration.
G17M5,
Expand Down Expand Up @@ -200,7 +201,7 @@ macro_rules! asahi_of_device_table {
),
(
of::DeviceId::new(c"apple,agx-t8112"),
ProbeConfig::Legacy(&hw::t8112::HWCONFIG)
ProbeConfig::LegacyWithG14Handoff(&hw::t8112::HWCONFIG)
),
(
of::DeviceId::new(c"apple,agx-t6000"),
Expand Down Expand Up @@ -376,8 +377,9 @@ impl platform::Driver for AsahiPlatformDriver {

dev_info!(pdev.as_ref(), "Probing...\n");

let cfg = match info.ok_or(ENODEV)? {
ProbeConfig::Legacy(cfg) => *cfg,
let (cfg, has_g14_handoff) = match info.ok_or(ENODEV)? {
ProbeConfig::Legacy(cfg) => (*cfg, false),
ProbeConfig::LegacyWithG14Handoff(cfg) => (*cfg, true),
ProbeConfig::G17(cfg) => {
return AsahiPlatformDriver::probe_g17(pdev, regs::G17Resources::new(pdev)?, cfg)
}
Expand All @@ -391,16 +393,19 @@ impl platform::Driver for AsahiPlatformDriver {
ProbeConfig::M5 => return Err(ENODEV),
};

// G14 with firmware 27.2 has its own root and start sequence (g14_v27_2.rs).
if (cfg.gpu_gen, cfg.gpu_variant) == (hw::GpuGen::G14, hw::GpuVariant::G) {
let version: Option<KVec<u32>> = pdev.as_ref().fwnode().ok_or(EIO)?
.property_read_array_vec(c"apple,firmware-version", 3)?.optional();
if version.as_deref() == Some(&[27, 2, 0]) {
#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))]
return AsahiPlatformDriver::probe_g14_v27_2(pdev, cfg);
#[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))]
return Err(ENODEV);
}
let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?;
let compat: KVec<u32> = fwnode
.property_read_array_vec(c"apple,firmware-compat", 3)?
.required_by(pdev.as_ref())?;

// The loader advertises the supported wire layout independently of the image version.
if has_g14_handoff && compat.as_slice() == [27, 2, 0] {
#[cfg(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122))]
return AsahiPlatformDriver::probe_g14_v27_2(
pdev, cfg, hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2,
);
#[cfg(not(all(CONFIG_DRM_ASAHI_G15, CONFIG_DRM_ASAHI_M3_T8122)))]
return Err(ENODEV);
}

// SAFETY: The selected SoC's UAT output width bounds all device DMA.
Expand All @@ -414,11 +419,6 @@ impl platform::Driver for AsahiPlatformDriver {
// Start the coprocessor CPU, so UAT can initialize the handoff
regs::Resources::start_cpu(pdev)?;

let fwnode = pdev.as_ref().fwnode().ok_or(EIO)?;
let compat: KVec<u32> = fwnode
.property_read_array_vec(c"apple,firmware-compat", 3)?
.required_by(pdev.as_ref())?;

let drm = drm::UnregisteredDevice::<AsahiDrmDriver>::new(pdev, Ok(()))?;
// SAFETY: Every adapter calls close_binding in unbind before devres;
// probe errors drop this local owner while the bound callback is live.
Expand Down Expand Up @@ -503,9 +503,11 @@ impl AsahiPlatformDriver {
fn probe_g14_v27_2<'bound>(
pdev: &'bound platform::Device<Core<'_>>,
cfg: &'static hw::HwConfig,
registers: &'static [hw::RegisterV27_2],
writable: u64,
) -> Result<AsahiPlatformDriverData<'bound>> {
let crate::g14_v27_2::Started { backend, drm, binding, resources } =
crate::g14_v27_2::start(pdev, cfg)?;
crate::g14_v27_2::start(pdev, cfg, registers, writable)?;
let gpu = backend.clone() as Arc<dyn gpu::Gpu>;
let data = try_pin_init!(AsahiDrmRegistrationData { gpu, resources });
// SAFETY: The registration is stored in the platform data and unregistered when it is
Expand Down
118 changes: 75 additions & 43 deletions drivers/gpu/drm/asahi/g14_v27_2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use kernel::{
platform,
prelude::*,
soc::apple::rtkit,
sync::{aref::ARef, Arc, ArcBorrow, CondVar, Mutex, SpinLock},
sync::{aref::ARef, Arc, ArcBorrow, CondVar, CondVarTimeoutResult, Mutex, SpinLock},
time::{delay::fsleep, msecs_to_jiffies, Delta, Instant, Monotonic},
uapi,
workqueue::{impl_has_work, OwnedQueue, Work, WorkItem},
Expand Down Expand Up @@ -211,14 +211,14 @@ pub(crate) struct Started<'a> {
}

/// Starts the firmware and retires the boot job.
pub(crate) fn start<'a>(pdev: &'a platform::Device<device::Core<'_>>, cfg: &'static hw::HwConfig)
-> Result<Started<'a>> {
pub(crate) fn start<'a>(
pdev: &'a platform::Device<device::Core<'_>>,
cfg: &'static hw::HwConfig,
registers: &'static [hw::RegisterV27_2],
writable: u64,
) -> Result<Started<'a>> {
use kernel::dma::{Device as _, DmaMask};
let dev: &device::Device = pdev.as_ref();
let (registers, writable) = match cfg.chip_id {
0x8112 => (hw::t8112::REGISTERS_V27_2, hw::t8112::WRITABLE_V27_2),
_ => return Err(ENODEV),
};
let geometry = mmu::UatGeometry { ias: cfg.uat_ias, oas: cfg.uat_oas };
let mut window = mmu::FirmwareWindow::reserve(dev, geometry)?;
let asc = AscControl::new(pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start())?;
Expand Down Expand Up @@ -299,6 +299,7 @@ pub(crate) fn start<'a>(pdev: &'a platform::Device<device::Core<'_>>, cfg: &'sta
struct Inflight {
packet: Arc<Packet>,
last: bool,
publication_error: Option<Error>,
stamp: event::EventValue,
slot: usize,
/// Queue publications up to and including this command, counted from take-over.
Expand Down Expand Up @@ -335,10 +336,26 @@ struct State {
capacity: u32,
inflight: KVec<Inflight>,
pending: KVec<(Arc<Packet>, usize)>,
accepting: bool,
submitted: u64,
retired: u64,
}

impl State {
/// Stop publishing this packet. Report failure only once any published prefix retires.
fn fail_publication(&mut self, packet: &Arc<Packet>, err: Error) {
let _ = self.pending.remove(0);
if let Some(last) = self.inflight.iter_mut().rev()
.find(|flight| Arc::ptr_eq(&flight.packet, packet))
{
last.publication_error = Some(err);
} else {
packet.release_guard();
packet.finish(Err(err));
}
}
}

#[pin_data(PinnedDrop)]
pub(crate) struct Runtime {
dev: ARef<device::Device>,
Expand Down Expand Up @@ -395,6 +412,8 @@ impl Runtime {
}
let mut guard = self.state.lock();
let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?;
if !self.healthy() { return Err(EIO); }
if !state.accepting { return Err(ENODEV); }
state.pending.push((packet, 0), GFP_KERNEL)?;
self.pump(state);
Ok(())
Expand All @@ -417,7 +436,9 @@ impl Runtime {
self.healthy.store(false, Ordering::Release);
self.idle.notify_all();
for (packet, _) in state.pending.drain(..) {
packet.release_guard();
if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &packet)) {
packet.release_guard();
}
packet.finish(Err(error));
}
// Published work stays owned: the firmware may still read it.
Expand Down Expand Up @@ -447,7 +468,7 @@ impl Runtime {
/// Publishes pending commands while pool slots are free.
fn pump(&self, state: &mut State) {
self.acknowledge(state);
if self.asleep.load(Ordering::Acquire) { return; }
if !self.healthy() || self.asleep.load(Ordering::Acquire) { return; }
while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() {
// A slot is reused only once the firmware has unlinked it from its tracking list
// (+0x94), which its retirement scan does after the slot's cursor is advanced.
Expand Down Expand Up @@ -480,15 +501,16 @@ impl Runtime {
let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1);
let Command::Compute(control) = packet.commands[index] else {
// Queues of this backend accept only compute commands (Queue::submit).
let _ = state.pending.remove(0);
if !(packet.may_be_published() && index != 0) { packet.release_guard(); }
packet.finish(Err(EINVAL));
state.fail_publication(&packet, EINVAL);
continue;
};
let result = (|| -> Result<(mmu::VmBind, event::EventValue)> {
let slot = state.next_slot;
let stamp = state.last.next();
let ordinal = state.published + 1;
let last = index + 1 == packet.commands.len();
let result = (|| -> Result {
let bind = self.graph.kernel_uat().bind(&packet.vm)?;
let preempt = packet.preempt.as_ref().ok_or(EINVAL)?.gpu_va().get();
let stamp = state.last.next();
let job = ComputeJob {
context: bind.slot(),
sequence: state.sequence,
Expand All @@ -497,38 +519,32 @@ impl Runtime {
usc_base: control.usc_base,
preempt,
};
let command = state.pool.encode(state.next_slot, &state.queue, stamp.raw(), &job)?;
let command = state.pool.encode(slot, &state.queue, stamp.raw(), &job)?;
let publication = state.root.stage_compute(command)?;
state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal,
publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?;
packet.mark_published();
state.root.publish(command)?;
state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK)?;
Ok((bind, stamp))
publication.commit();
Ok(())
})();
match result {
Ok((bind, stamp)) => {
Ok(()) => {
state.last = stamp;
state.sequence += 1;
let slot = state.next_slot;
state.busy |= 1 << slot;
state.published += 1;
let ordinal = state.published;
state.next_slot = (state.next_slot + 1) % POOL_SLOTS;
state.published = ordinal;
state.next_slot = (slot + 1) % POOL_SLOTS;
state.submitted += 1;
let last = index + 1 == packet.commands.len();
if state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal,
started: Instant::now(), _bind: bind }, GFP_KERNEL).is_err() {
self.fail_all(state, ENOMEM);
if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; }
if let Err(err) = state.peer.as_mut().send_message(EP_DOORBELL, gpu::COMPUTE_KICK) {
self.fail_all(state, err);
return;
}
if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; }
}
Err(EBUSY) if !state.inflight.is_empty() => return,
Err(e) => {
dev_err!(self.dev, "GPU: compute publication failed {:?}\n", e);
let _ = state.pending.remove(0);
// Earlier commands of a published packet fail it when they retire.
if !(packet.may_be_published() && index != 0) {
packet.release_guard();
}
packet.finish(Err(e));
state.fail_publication(&packet, e);
}
}
}
Expand All @@ -550,7 +566,11 @@ impl Runtime {
let mut guard = self.state.lock();
let Some(state) = Option::as_mut(&mut *guard) else { return; };
self.service_locked(state);
if state.inflight.is_empty() && state.pending.is_empty() { self.idle.notify_all(); }
if state.inflight.is_empty()
&& (state.pending.is_empty() || self.asleep.load(Ordering::Acquire))
{
self.idle.notify_all();
}
}

fn service_locked(&self, state: &mut State) {
Expand Down Expand Up @@ -592,8 +612,15 @@ impl Runtime {
}
state.busy &= !(1 << done.slot);
state.retired += 1;
if done.last {
if let Some(err) = done.publication_error {
done.packet.release_guard();
done.packet.finish(Err(err));
} else if done.last {
done.packet.retired();
} else if !state.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, &done.packet))
&& !state.pending.iter().any(|(packet, _)| Arc::ptr_eq(packet, &done.packet))
{
done.packet.release_guard();
}
}
continue;
Expand Down Expand Up @@ -624,7 +651,7 @@ impl Runtime {
// Hold publications first, then let what is published retire. User space is frozen by
// now; only the scheduler's queued jobs can still arrive, and they wait in `pending`.
self.asleep.store(true, Ordering::Release);
let start = Instant::<Monotonic>::now();
let mut remaining = msecs_to_jiffies(STOP_DRAIN_MS);
loop {
let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); };
if !self.healthy() { return Ok(()); }
Expand All @@ -633,15 +660,16 @@ impl Runtime {
state.submitted, state.retired, state.pending.len());
return Ok(());
}
if start.elapsed() >= Delta::from_millis(STOP_DRAIN_MS.into()) {
if remaining == 0 {
dev_err!(self.dev, "GPU: sleep refused, {} commands still running\n", state.inflight.len());
self.asleep.store(false, Ordering::Release);
self.pump(state);
return Err(EBUSY);
}
// The service retires on notifications; `idle` is signalled only when nothing at all
// is left, so look again every 50 ms.
let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(50));
remaining = match self.idle.wait_timeout(&mut guard, remaining) {
CondVarTimeoutResult::Woken { jiffies } => jiffies,
_ => 0,
};
}
}

Expand All @@ -658,17 +686,20 @@ impl Runtime {
/// Stops the firmware: retire or fail outstanding work, allow power-off, then halt the ASC
/// with every mapping still in place (RTKit power-off if the firmware does not stop).
pub(crate) fn stop(&self) {
// Let published work retire; the service signals `idle` when nothing is left.
// Close admission while the service retires work already accepted.
{
let mut guard = self.state.lock();
let Some(state) = Option::as_mut(&mut *guard) else { return; };
state.accepting = false;
let start = Instant::<Monotonic>::now();
while self.healthy() && start.elapsed() < Delta::from_millis(STOP_DRAIN_MS.into()) {
let Some(state) = guard.as_ref() else { break; };
if state.inflight.is_empty() && state.pending.is_empty() { break; }
let _ = self.idle.wait_timeout(&mut guard, msecs_to_jiffies(STOP_DRAIN_MS));
}
// Serialize the last permitted publication with the transition to shutdown.
self.healthy.store(false, Ordering::Release);
}
self.healthy.store(false, Ordering::Release);
// Nothing queues service work after the detach, and none is queued or running once the
// drain returns, so no work outlives the module.
drop(self.notify.detach());
Expand Down Expand Up @@ -782,6 +813,7 @@ impl Backend {
capacity,
inflight: KVec::new(),
pending: KVec::new(),
accepting: true,
submitted: 0,
retired: 0,
});
Expand Down
Loading