diff --git a/drivers/gpu/drm/asahi/g18/address_map.rs b/drivers/gpu/drm/asahi/g18/address_map.rs index 1a73e894dd4a1..6052bd67a57e4 100644 --- a/drivers/gpu/drm/asahi/g18/address_map.rs +++ b/drivers/gpu/drm/asahi/g18/address_map.rs @@ -60,7 +60,9 @@ pub(crate) const GRAPHICS_IDEAL_BLOCKS: u64 = 0x70_2000_0000; pub(crate) const GRAPHICS_TARGET_OFFSET: u64 = 0x0100_0000; pub(crate) const GRAPHICS_TARGET_BYTES: usize = 0x0100_0000; pub(crate) const GRAPHICS_PB_OFFSET: u64 = 0x0200_0000; -pub(crate) const GRAPHICS_PB_COMPACT_BYTES: usize = 0x0100_0000; +// PB blocks grow to render_policy::PB_MAX_BLOCKS. The biased half stays +// inside the COMPACT_BIAS + [32 MiB, 2 GiB) that Mesa leaves to the kernel. +pub(crate) const GRAPHICS_PB_COMPACT_BYTES: usize = 0x3400_0000; pub(crate) const PB_GRAPH: u64 = GRAPHICS_PB_HIGH + 0x4000; pub(crate) const PB_PAGE_LIST_HIGH: u64 = GRAPHICS_PB_HIGH + 0x10000; pub(crate) const PB_PAGE_LIST_LOW: u64 = GRAPHICS_PB_OFFSET; @@ -194,7 +196,8 @@ pub(crate) const PB_REGIONS: &[Region] = &[ r("pb-metrics-high", PB_METRICS_HIGH, PAGE), r("pb-page-list-low", PB_PAGE_LIST_LOW, PB_PAGE_LIST_BYTES as u64), r("pb-metrics-low", PB_METRICS_LOW, PAGE), r("pb-scene-scratch", PB_SCENE_SCRATCH, PAGE), - r("pb-discard", PB_DISCARD, 0x8000), r("pb-blocks", PB_BLOCKS, 8 * 0x80000), + r("pb-discard", PB_DISCARD, 0x8000), + r("pb-blocks", PB_BLOCKS, crate::g18::uapi::render_policy::PB_MAX_BLOCKS as u64 * 0x80000), ]; const _: () = assert!(nonoverlapping(PB_REGIONS)); diff --git a/drivers/gpu/drm/asahi/g18/boot/mod.rs b/drivers/gpu/drm/asahi/g18/boot/mod.rs index d7b33d64f3864..e939846e52be8 100644 --- a/drivers/gpu/drm/asahi/g18/boot/mod.rs +++ b/drivers/gpu/drm/asahi/g18/boot/mod.rs @@ -61,7 +61,7 @@ use crate::{ driver::AsahiDrmDevice, g18::probe::{G18Runtime, T8152Probe}, - g18::initdata::G18FirmwareMemory, + g18::initdata::{G18FirmwareMemory, G18TvbGrowRequest}, g18::runtime::compute::G18PreparedComputeCommand, g18::buffer::pool::G18UmaPoolBinding, g18::queue::probe::{G18QueueProbe, QUEUE_ID}, @@ -198,6 +198,9 @@ const INITDATA_ACK: u64 = 0x0009_0000_0000_0000; /// EP 0x21 device-control doorbell for the idle-policy wake (M5 value, /// unchanged in the 26A428 EP 0x21 handler 0x254cc-0x25610). const IDLE_POLICY_WAKE: u64 = 0x0084_0000_0000_0011; +/// The same doorbell after any other primary control record (g17 +/// MSG_CONTROL_NOTIFY). +const CONTROL_NOTIFY: u64 = IDLE_POLICY_WAKE; const ACK_POLLS: u32 = 200; // x 10 ms const CONTROL_POLLS: u32 = 1000; // x 1 ms @@ -1082,12 +1085,45 @@ impl G18Session { } /// Drain the report rings once the graph exists. Returns whether a - /// recovery (type 4) event was seen. + /// recovery (type 4) event was seen. Answers TVB grow requests. fn drain(&mut self) -> Result { - match self.memory.as_mut() { - Some(memory) => memory.drain_reports(&self.dev), - None => Ok(false), + let Some(memory) = self.memory.as_mut() else { return Ok(false) }; + let recovery = memory.drain_reports(&self.dev)?; + while let Some(request) = self.memory.as_mut().ok_or(EIO)?.take_tvb_grow() { + self.answer_tvb_grow(request)?; + } + Ok(recovery) + } + + /// Grow the PB that a firmware TVB grow request names and reply, so the + /// waiting tiler continues; "not grown" when that fails or the PB is at + /// its limit. A request from before the current recovery epoch is + /// stale and gets no reply, as on M5. + fn answer_tvb_grow(&mut self, request: G18TvbGrowRequest) -> Result { + let epoch = self.memory.as_mut().ok_or(EIO)?.recovery_word()?.epoch; + if request.halt_count != epoch { + dev_warn!(self.device(), "G18_TVB_GROW stale {:?} epoch={}\n", request, epoch); + return Ok(()); } + let grown = match self.application_job.as_mut() { + Some(job) => job.grow_parameter_buffer(&self.dev, request.buffer_slot, request.vm_slot), + None => Err(ENOENT), + }; + let grew = match grown { + Ok(0) => { + dev_warn!(self.device(), "G18_TVB_GROW {:?} not grown: PB at its limit\n", request); + false + } + Ok(_) => true, + Err(error) => { + dev_warn!(self.device(), "G18_TVB_GROW {:?} not grown: {:?}\n", request, error); + false + } + }; + self.memory.as_mut().ok_or(EIO)?.reply_tvb_grow(request, grew)?; + Pin::new(&mut self.roles[G18Role::Gfx.index()].rtkit) + .send_message(EP_GFX_INTERRUPTS, CONTROL_NOTIFY)?; + Ok(()) } /// Fault check used by every wait loop. diff --git a/drivers/gpu/drm/asahi/g18/buffer/object.rs b/drivers/gpu/drm/asahi/g18/buffer/object.rs index 6697a5b3fa105..2a824398406b5 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/object.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/object.rs @@ -105,6 +105,30 @@ impl MappedObject { }) } + /// As [`Self::new_wc_at`], for memory whose owner holds a user charge for + /// it ([`crate::memacct::Charge::user`]) instead of counting it as kernel + /// memory. + pub(crate) fn new_wc_at_user_charged( + dev: &AsahiDrmDevice, + vm: &mmu::Vm, + address: u64, + size: usize, + prot: mmu::Prot, + ) -> Result { + let mut object = gem::new_kernel_object_wc_user_charged(dev, size)?; + zero_object(&mut object)?; + let mapping = object.map_at(vm, address, prot, false)?; + let iova = mapping.iova(); + Ok(Self { + mapping: Some(mapping), + object, + iova, + object_offset: 0, + logical_size: size, + cpu_wc: true, + }) + } + /// Replace this object's backing with a larger one at the SAME address. /// /// The replacement is allocated and zeroed before the old aperture is diff --git a/drivers/gpu/drm/asahi/g18/initdata/application.rs b/drivers/gpu/drm/asahi/g18/initdata/application.rs index 6a2be9da27f43..7ecb6397ae7af 100644 --- a/drivers/gpu/drm/asahi/g18/initdata/application.rs +++ b/drivers/gpu/drm/asahi/g18/initdata/application.rs @@ -37,7 +37,7 @@ impl G18FirmwareMemory { /// Graphics and compute share this outer ring but have independent inner /// sequences. Only publish from a fully retired observed outer position. pub(crate) fn publish_application_records(&mut self, records: &[[u8;24]]) -> Result { - if records.is_empty() || records.len()>2 || self.control_counters()?!=[[2;3],[1;3]] { + if records.is_empty() || records.len()>2 || self.control_counters()?!=self.control_retired() { return Err(EINVAL); } let counters=self.compute_outer_counters()?;let before=counters[0]; diff --git a/drivers/gpu/drm/asahi/g18/initdata/mod.rs b/drivers/gpu/drm/asahi/g18/initdata/mod.rs index 7a032eb17a876..689ab336bdb55 100644 --- a/drivers/gpu/drm/asahi/g18/initdata/mod.rs +++ b/drivers/gpu/drm/asahi/g18/initdata/mod.rs @@ -102,6 +102,13 @@ const TRACE_PRINT_BUDGET: [u32; 2] = [512, 16]; const TRACE_JOURNAL_CAPACITY: usize = 32768; /// b000 0x7de8 constructs type4 with counter at +4 and stamp index at +12. const EVENT_TYPE_RECOVERY: u32 = 4; +/// Parameter-buffer (TVB) grow request in the 25G76 TvbGrowEventRecord +/// layout (g17::fw::channels). The tiler waits for the reply. +const EVENT_TYPE_TVB_GROW: u32 = 6; +/// Device-control TvbGrowReply (g17 DeviceControlOp::TvbGrowReply). +const DEVICE_CONTROL_OPCODE_TVB_GROW_REPLY: u32 = 0x08; +/// Grow requests held between a drain and the session answering them. +const TVB_GROW_QUEUE: usize = 4; /// `halLoadUMADesc` device words (accelerator+0x11af8..0x11b10) as native /// `halInitSMAEnableMask` 0xfffffe0008c41bdc derives them on J873. @@ -166,6 +173,10 @@ pub(crate) struct G18FirmwareMemory { trace_printed: [u32; 2], trace_journal: [KVVec; 2], trace_dropped: [u32; 2], + /// TVB grow requests drained but not yet answered, oldest first. + tvb_grow: KVec, + /// Primary device-control records published after the idle wake. + control_published: u32, uat: Arc, /// InitData layouts of the firmware build the loader admitted. layouts: &'static init::G18GLayouts, @@ -183,6 +194,18 @@ pub(crate) struct G18StatusLinks { pub(crate) status_config_pointer: u64, } +/// A firmware TVB grow request (event 6): vm_slot +4, buffer_slot +8, +/// counter +0xc, subpipe +0x10, u64 halt count (the recovery epoch) +0x14. +/// The reply echoes every field. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) struct G18TvbGrowRequest { + pub(crate) vm_slot: u32, + pub(crate) buffer_slot: u32, + pub(crate) counter: u32, + pub(crate) subpipe: u32, + pub(crate) halt_count: u64, +} + /// The status-B recovery handshake words. #[derive(Debug, Copy, Clone, Default)] pub(crate) struct G18RecoveryWord { @@ -238,6 +261,7 @@ impl G18FirmwareMemory { KVVec::with_capacity(TRACE_JOURNAL_CAPACITY, GFP_KERNEL)?, KVVec::with_capacity(TRACE_JOURNAL_CAPACITY, GFP_KERNEL)?, ]; + let tvb_grow = KVec::with_capacity(TVB_GROW_QUEUE, GFP_KERNEL)?; let mut registers = KVec::new(); for window in init::G18G_26A428_REGISTER_WINDOWS { let (physical, virtual_address, span) = window.mapped_pages().map_err(|_| EINVAL)?; @@ -418,7 +442,7 @@ impl G18FirmwareMemory { application_compute: None, completions, aliases, registers, report_counts: [[0; 2]; 2], completion_masks: [0; 2], trace_printed: [0; 2], uat, - trace_journal, trace_dropped: [0; 2], layouts, + trace_journal, trace_dropped: [0; 2], tvb_grow, control_published: 0, layouts, }), GFP_KERNEL) } @@ -886,6 +910,13 @@ impl G18FirmwareMemory { crate::g18_event_info!(role == 0 && word(0) == 1, dev.as_ref(), "G18_EVENT role={} ordinal={} type={} payload={:x?}\n", role, count, word(0), [qword(4), qword(12), qword(20), qword(28), qword(36)]); recovery |= word(0) == EVENT_TYPE_RECOVERY; + if word(0) == EVENT_TYPE_TVB_GROW { + // The session grows the PB and replies after the drain. + self.tvb_grow.push_within_capacity(G18TvbGrowRequest { + vm_slot: word(4), buffer_slot: word(8), counter: word(0xc), + subpipe: word(0x10), halt_count: qword(0x14), + }).map_err(|_| EBUSY)?; + } if role == 0 && word(0) == 1 { // Original G18 b000 233a8..233d4 uses this exact // type-1 prefix. Copy/validate before releasing the @@ -911,6 +942,52 @@ impl G18FirmwareMemory { Ok(recovery) } + /// The oldest drained TVB grow request not yet answered. + pub(crate) fn take_tvb_grow(&mut self) -> Option { + if self.tvb_grow.is_empty() { None } else { self.tvb_grow.remove(0).ok() } + } + + /// Publish the TvbGrowReply for `request` on the primary device-control + /// ring (g17 TvbGrowReply: opcode, grew, buffer_slot, vm_slot, counter, + /// subpipe, halt_count). The caller rings the EP 0x21 control doorbell. + pub(crate) fn reply_tvb_grow(&mut self, request: G18TvbGrowRequest, grew: bool) -> Result { + let [consumer, _, producer] = self.control_counters()?[0]; + if consumer > init::CONTROL_RING_INDEX_MASK || producer > init::CONTROL_RING_INDEX_MASK { + return Err(EIO); + } + let next = (producer + 1) & init::CONTROL_RING_INDEX_MASK; + if next == consumer { + return Err(EBUSY); + } + let record = self.layouts.shared.control_ring[0] + producer as usize * init::CONTROL_RECORD_SIZE; + self.shared.with_bytes_mut(|out| { + let record = out.get_mut(record..record + init::CONTROL_RECORD_SIZE).ok_or(EINVAL)?; + init::encode_device_control_record(DEVICE_CONTROL_OPCODE_TVB_GROW_REPLY, u32::from(grew), record) + .map_err(|_| EINVAL)?; + let r = request; + for (offset, value) in [(0x08, r.buffer_slot), (0x0c, r.vm_slot), (0x10, r.counter), + (0x14, r.subpipe), (0x18, r.halt_count as u32), + (0x1c, (r.halt_count >> 32) as u32)] { + record[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + Ok(()) + })?; + fence(Ordering::SeqCst); + let producer_offset = init::G18G_26A428_PRIVATE_STATE_GRIDS[0] + + init::WORK_STATE_GRID_OFFSETS[init::CONTROL_CHANNEL_INDEX] + + init::CHANNEL_STATE_PRODUCER * init::CHANNEL_STATE_SPACING; + self.private.write_u32(PRIVATE_BASE + producer_offset as u64, next)?; + fence(Ordering::SeqCst); + self.control_published = self.control_published.wrapping_add(1); + Ok(()) + } + + /// Device-control counters of both roles once every record published + /// after boot retired: the idle wake left the primary ring at 2. + pub(crate) fn control_retired(&self) -> [[u32; 3]; 2] { + [[(2 + self.control_published) & init::CONTROL_RING_INDEX_MASK; 3], [1; 3]] + } + /// Report-record totals per role and channel since construction. pub(crate) fn report_counts(&self) -> [[u32; 2]; 2] { self.report_counts diff --git a/drivers/gpu/drm/asahi/g18/probe.rs b/drivers/gpu/drm/asahi/g18/probe.rs index a99f40d89d0ca..26534683e1ed5 100644 --- a/drivers/gpu/drm/asahi/g18/probe.rs +++ b/drivers/gpu/drm/asahi/g18/probe.rs @@ -64,6 +64,9 @@ impl platform::Driver for Driver { info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { let soc = *info.ok_or(ENODEV)?; + // The memory limits the parameter buffer's growth is admitted + // against (memacct), as the other generations' probe sets them. + crate::memacct::LEDGER.configure(); AsahiPlatformDriver::probe_g18(pdev, soc) } diff --git a/drivers/gpu/drm/asahi/g18/queue/graphics.rs b/drivers/gpu/drm/asahi/g18/queue/graphics.rs index 8bbd515854cfc..d3eb503fb032c 100644 --- a/drivers/gpu/drm/asahi/g18/queue/graphics.rs +++ b/drivers/gpu/drm/asahi/g18/queue/graphics.rs @@ -625,10 +625,17 @@ impl G18GraphicsQueues { use crate::g18::fw::parameter_buffer::*; const PM_GRAPH_BYTES: usize = 0x8000; +// The block table holds an entry for each of the PB_CAPACITY ring slots the +// firmware is given. It stays at the start of the graph (behind the scene +// records, at +0x8000 of a larger graph, the first frame faulted); the shared +// header, the counter and the scene records follow it. const BLOCK_TABLE: usize = 0; -const SHARED: usize = 0x800; -const COUNTER: usize = 0x900; -const SCENES: usize = 0x1000; +const SHARED: usize = 0x3400; +const COUNTER: usize = 0x3500; +const SCENES: usize = 0x4000; +const _: () = assert!( + BLOCK_TABLE + crate::g18::uapi::render_policy::PB_CAPACITY as usize * 8 <= SHARED +); const SCENE_BYTES: usize = 0x80; fn pb_put32(out: &mut [u8], offset: usize, value: u32) { @@ -723,6 +730,8 @@ pub(crate) struct G18ParameterBuffer { metrics: MappedObject, scene_scratch: MappedObject, blocks: KVec, + /// The user charges of the grown blocks ([`Self::grow`]). + charges: KVec, discard: MappedObject, addresses: G18PbAddresses, policy: G18PbPolicy, @@ -810,7 +819,8 @@ impl G18ParameterBuffer { }; let mut owner = Self { window_aliases: KVec::new(), low_aliases, state, graph, page_list, metrics, - scene_scratch, blocks, discard, addresses: a, policy, inputs, row: None, + scene_scratch, blocks, charges: KVec::new(), discard, addresses: a, policy, + inputs, row: None, }; owner.encode()?; dev_info!(dev.as_ref(), diff --git a/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs b/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs index 623b98d506fee..6420db7232025 100644 --- a/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs +++ b/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs @@ -4,81 +4,200 @@ use super::*; use crate::g18::uapi::application_runtime::Frame; impl G18GraphicsQueues { - pub(crate) fn prepare_application_pass(&mut self, dev: &AsahiDrmDevice, - pass: &G18QueuedPass, frame: Frame) -> Result { + pub(crate) fn prepare_application_pass( + &mut self, + dev: &AsahiDrmDevice, + pass: &G18QueuedPass, + frame: Frame, + ) -> Result { let before = frame.inner_before(); - if self.counters()? != [[before;3];2] - || self.step != if frame.generation == 1 {3} else {5} - || self.completion_list()? != [0,self.job_list()] {return Err(EBUSY);} - let status=self.firmware_status()?; - if !Self::installed(&status,&self.addresses) || !self.scheduler_bound(&status) {return Err(EIO);} - let pb=pass.parameter_buffer.ok_or(EINVAL)?; - let (pool,slot)=self.pool_and_pb_status(pass.uma.slot,pb.slot)?; - if pool != [pass.uma.state,pass.uma.generation.ok_or(EINVAL)?,(2u64<<32)|3,0x600,0] - || slot != [pb.state,pb.generation,u64::from(pass.context_id),0x200,0,0x400] {return Err(EIO);} - for stage in [1,0] { - let state=G18KickQueueState {current_stamp:u64::from(frame.generation), - previous_stamp:if frame.generation==1 {None} else {Some(u64::from(frame.generation-1))}, - base:1,submitted_kicks:(frame.generation-1) as u16}; - let (entry,kick)=g18_stage_kick(stage,pass,state,self.queue_address(stage)).map_err(|_|EINVAL)?; - let config=g18_stage_config(stage,3,(self.addresses.entry_low[stage],self.addresses.entry_high[stage]),pass); + if self.counters()? != [[before; 3]; 2] + || self.step != if frame.generation == 1 { 3 } else { 5 } + || self.completion_list()? != [0, self.job_list()] + { + return Err(EBUSY); + } + let status = self.firmware_status()?; + if !Self::installed(&status, &self.addresses) || !self.scheduler_bound(&status) { + return Err(EIO); + } + let pb = pass.parameter_buffer.ok_or(EINVAL)?; + let (pool, slot) = self.pool_and_pb_status(pass.uma.slot, pb.slot)?; + if pool + != [ + pass.uma.state, + pass.uma.generation.ok_or(EINVAL)?, + (2u64 << 32) | 3, + 0x600, + 0, + ] + || slot + != [ + pb.state, + pb.generation, + u64::from(pass.context_id), + 0x200, + 0, + 0x400, + ] + { + return Err(EIO); + } + for stage in [1, 0] { + let state = G18KickQueueState { + current_stamp: u64::from(frame.generation), + previous_stamp: if frame.generation == 1 { + None + } else { + Some(u64::from(frame.generation - 1)) + }, + base: 1, + submitted_kicks: (frame.generation - 1) as u16, + }; + let (entry, kick) = g18_stage_kick(stage, pass, state, self.queue_address(stage)) + .map_err(|_| EINVAL)?; + let config = g18_stage_config( + stage, + 3, + ( + self.addresses.entry_low[stage], + self.addresses.entry_high[stage], + ), + pass, + ); self.entries[stage].with_bytes_mut(|out| { - let slot=out.get_mut(entry.offset as usize..entry.offset as usize+entry.bytes.len()).ok_or(EINVAL)?; + let slot = out + .get_mut(entry.offset as usize..entry.offset as usize + entry.bytes.len()) + .ok_or(EINVAL)?; slot.copy_from_slice(&entry.bytes); - if slot!=entry.bytes {return Err(EIO);} Ok(()) + if slot != entry.bytes { + return Err(EIO); + } + Ok(()) })?; - let a=self.addresses.graph;let at=CONFIGS[stage]+0x300; + let a = self.addresses.graph; + let at = CONFIGS[stage] + 0x300; self.graph.with_bytes_mut(|out| { - out[at..at+G18_CHANNEL_CONFIG_BYTES].copy_from_slice(&config); - out[KICKS[stage]..KICKS[stage]+G18_KICK_BYTES].copy_from_slice(&kick); - for (i,address) in [pass.command_high[stage],a+at as u64,a+KICKS[stage] as u64].into_iter().enumerate() { - put64(out,ITEMS[stage]+((before as usize+i)%CAPACITY as usize)*8,address); + out[at..at + G18_CHANNEL_CONFIG_BYTES].copy_from_slice(&config); + out[KICKS[stage]..KICKS[stage] + G18_KICK_BYTES].copy_from_slice(&kick); + for (i, address) in [ + pass.command_high[stage], + a + at as u64, + a + KICKS[stage] as u64, + ] + .into_iter() + .enumerate() + { + put64( + out, + ITEMS[stage] + ((before as usize + i) % CAPACITY as usize) * 8, + address, + ); } - if out[at..at+G18_CHANNEL_CONFIG_BYTES]!=config - || out[KICKS[stage]..KICKS[stage]+G18_KICK_BYTES]!=kick {return Err(EIO);} Ok(()) + if out[at..at + G18_CHANNEL_CONFIG_BYTES] != config + || out[KICKS[stage]..KICKS[stage] + G18_KICK_BYTES] != kick + { + return Err(EIO); + } + Ok(()) })?; - if frame.generation<=3 { - for (name,bytes) in [("sksm",entry.bytes.as_slice()),("kick",kick.as_slice()),("tag15",config.as_slice())] { - dev_info!(dev.as_ref(),"G18_APP_DIGEST frame={} stage={} name={} fnv={:#018x}\n", - frame.generation,stage,name,crate::g18::fw::graphics_payload::fnv64(bytes)); + if frame.generation <= 3 { + for (name, bytes) in [ + ("sksm", entry.bytes.as_slice()), + ("kick", kick.as_slice()), + ("tag15", config.as_slice()), + ] { + dev_info!( + dev.as_ref(), + "G18_APP_DIGEST frame={} stage={} name={} fnv={:#018x}\n", + frame.generation, + stage, + name, + crate::g18::fw::graphics_payload::fnv64(bytes) + ); } } } - fence(Ordering::SeqCst);self.step=4;Ok(()) + fence(Ordering::SeqCst); + self.step = 4; + Ok(()) } /// The first firmware-owned precondition of the next frame's /// [`Self::prepare_application_pass`] that does not hold after `frame` /// retired, if any. A firmware recovery can reset queue state. - pub(crate) fn render_unready(&mut self, pass: &G18QueuedPass, frame: Frame) -> Result> { - let status=self.firmware_status()?; - let pb=pass.parameter_buffer.ok_or(EINVAL)?; - let (pool,slot)=self.pool_and_pb_status(pass.uma.slot,pb.slot)?; - Ok(if self.counters()? != [[frame.inner_after();3];2] {Some("counters")} - else if self.completion_list()? != [0,self.job_list()] {Some("completion-list")} - else if !Self::installed(&status,&self.addresses) {Some("installed")} - else if !self.scheduler_bound(&status) {Some("scheduler")} - else if pool != [pass.uma.state,pass.uma.generation.ok_or(EINVAL)?,(2u64<<32)|3,0x600,0] {Some("pool")} - else if slot != [pb.state,pb.generation,u64::from(pass.context_id),0x200,0,0x400] {Some("parameter-buffer")} - else {None}) + pub(crate) fn render_unready( + &mut self, + pass: &G18QueuedPass, + frame: Frame, + ) -> Result> { + let status = self.firmware_status()?; + let pb = pass.parameter_buffer.ok_or(EINVAL)?; + let (pool, slot) = self.pool_and_pb_status(pass.uma.slot, pb.slot)?; + Ok(if self.counters()? != [[frame.inner_after(); 3]; 2] { + Some("counters") + } else if self.completion_list()? != [0, self.job_list()] { + Some("completion-list") + } else if !Self::installed(&status, &self.addresses) { + Some("installed") + } else if !self.scheduler_bound(&status) { + Some("scheduler") + } else if pool + != [ + pass.uma.state, + pass.uma.generation.ok_or(EINVAL)?, + (2u64 << 32) | 3, + 0x600, + 0, + ] + { + Some("pool") + } else if slot + != [ + pb.state, + pb.generation, + u64::from(pass.context_id), + 0x200, + 0, + 0x400, + ] + { + Some("parameter-buffer") + } else { + None + }) } /// Every firmware word [`Self::render_unready`] reads, for the kernel log. - pub(crate) fn render_state(&mut self, pass: &G18QueuedPass) -> Result<(G18GraphicsFirmwareStatus, [u64;5], [u64;6])> { - let pb=pass.parameter_buffer.ok_or(EINVAL)?; - let (pool,slot)=self.pool_and_pb_status(pass.uma.slot,pb.slot)?; - Ok((self.firmware_status()?,pool,slot)) + pub(crate) fn render_state( + &mut self, + pass: &G18QueuedPass, + ) -> Result<(G18GraphicsFirmwareStatus, [u64; 5], [u64; 6])> { + let pb = pass.parameter_buffer.ok_or(EINVAL)?; + let (pool, slot) = self.pool_and_pb_status(pass.uma.slot, pb.slot)?; + Ok((self.firmware_status()?, pool, slot)) } - pub(crate) fn publish_application_pass(&mut self, frame: Frame) -> Result<[[u8;24];2]> { - if self.step!=4 || self.counters()?!=[[frame.inner_before();3];2] {return Err(EBUSY);} - let mut records=[[0;24];2]; + pub(crate) fn publish_application_pass(&mut self, frame: Frame) -> Result<[[u8; 24]; 2]> { + if self.step != 4 || self.counters()? != [[frame.inner_before(); 3]; 2] { + return Err(EBUSY); + } + let mut records = [[0; 24]; 2]; fence(Ordering::SeqCst); - for stage in [1,0] { - self.graph.write_u32(self.addresses.graph+POINTERS[stage] as u64+0x40,frame.inner_after())?; - records[stage]=encode_g18_outer_record(self.queue_address(stage),G18_GRAPHICS_QUEUE_IDS[stage],frame.inner_after() as u16); + for stage in [1, 0] { + self.graph.write_u32( + self.addresses.graph + POINTERS[stage] as u64 + 0x40, + frame.inner_after(), + )?; + records[stage] = encode_g18_outer_record( + self.queue_address(stage), + G18_GRAPHICS_QUEUE_IDS[stage], + frame.inner_after() as u16, + ); } - fence(Ordering::SeqCst);self.step=5;Ok([records[1],records[0]]) + fence(Ordering::SeqCst); + self.step = 5; + Ok([records[1], records[0]]) } } @@ -86,60 +205,265 @@ impl G18ParameterBuffer { /// Keep the PB resident in its hardware slot across VM handoffs. Every /// alias uses the addresses selected by the PB owner, including row VA. pub(crate) fn application_aliases(&mut self, vm: &mmu::Vm) -> Result> { - let a=self.addresses;let bias=crate::g18::address_map::COMPACT_BIAS; - let mut aliases=KVec::new(); - for (object,low) in [(&mut self.page_list,a.page_list_low),(&mut self.metrics,a.metrics_low), - (&mut self.scene_scratch,a.scene_scratch_low),(&mut self.discard,a.discard_low)] { - for address in [low,low+bias] {aliases.push(object.map_alias_at(vm,address,mmu::PROT_GPU_SHARED_RW)?,GFP_KERNEL)?;} + let a = self.addresses; + let bias = crate::g18::address_map::COMPACT_BIAS; + let mut aliases = KVec::new(); + for (object, low) in [ + (&mut self.page_list, a.page_list_low), + (&mut self.metrics, a.metrics_low), + (&mut self.scene_scratch, a.scene_scratch_low), + (&mut self.discard, a.discard_low), + ] { + for address in [low, low + bias] { + aliases.push( + object.map_alias_at(vm, address, mmu::PROT_GPU_SHARED_RW)?, + GFP_KERNEL, + )?; + } } - if a.page_list_row!=a.page_list_low && a.page_list_row!=a.page_list_low+bias { - aliases.push(self.page_list.map_alias_at(vm,a.page_list_row,mmu::PROT_GPU_SHARED_RW)?,GFP_KERNEL)?; + if a.page_list_row != a.page_list_low && a.page_list_row != a.page_list_low + bias { + aliases.push( + self.page_list + .map_alias_at(vm, a.page_list_row, mmu::PROT_GPU_SHARED_RW)?, + GFP_KERNEL, + )?; } - for (index,block) in self.blocks.iter_mut().enumerate() { - let low=a.blocks_low+index as u64*G18_PB_BLOCK_BYTES; - for address in [low,low+bias] {aliases.push(block.map_alias_at(vm,address,mmu::PROT_GPU_SHARED_RW)?,GFP_KERNEL)?;} + // Each block object is homed at its own low address; a grown one + // spans several blocks. + for block in self.blocks.iter_mut() { + let low = block.iova(); + for address in [low, low + bias] { + aliases.push( + block.map_alias_at(vm, address, mmu::PROT_GPU_SHARED_RW)?, + GFP_KERNEL, + )?; + } } Ok(aliases) } + /// Blocks backed so far: the initial ones plus every growth. + fn backed_blocks(&self) -> Result { + let bytes: usize = self.blocks.iter().map(|block| block.logical_size).sum(); + Ok(u32::try_from(bytes / G18_PB_BLOCK_BYTES as usize)?) + } + + /// Answer a firmware TVB grow request (event 6) while the tiler waits: + /// back up to `add` more blocks after the existing ones, append them to + /// the block ring and advance its total and committed cursors. This is + /// the M5 firmware-request growth (g17 Manager::commit_growth without a + /// descriptor): the firmware builds the page-list entries itself. The + /// new blocks are one object, homed in `storage` like the initial ones + /// and aliased into the running client `vm`; the caller retains those + /// aliases with the client's other PB aliases. The blocks are the memory + /// of `client`, the client whose render asked: they are admitted against + /// its limit and the device's first, and ENOMEM refuses the growth, which + /// fails only that render; so does a render with no client to charge. + /// Returns the number of blocks added (0: at the limit). + pub(crate) fn grow( + &mut self, + dev: &AsahiDrmDevice, + storage: &mmu::Vm, + vm: &mmu::Vm, + client: Option<&kernel::sync::Arc>, + add: u32, + max: u32, + ) -> Result<(u32, KVec)> { + let a = self.addresses; + let bias = crate::g18::address_map::COMPACT_BIAS; + let capacity = self.policy.capacity; + let blocks = self.backed_blocks()?; + let added = max.saturating_sub(blocks).min(add); + if added == 0 { + return Ok((0, KVec::new())); + } + let cursor = |pb: &mut Self, offset: usize| { + pb.graph.read_u32(a.graph_high + (SHARED + offset) as u64) + }; + let (total, committed, read) = (cursor(self, 0)?, cursor(self, 4)?, cursor(self, 8)?); + if total != committed || total >= capacity || read >= capacity { + return Err(EIO); + } + let retained = (total + capacity - read) % capacity; + // The ring keeps one slot empty; the block table ends at SHARED. + if retained + added >= capacity || (total + added) as usize * 8 > SHARED - BLOCK_TABLE { + return Err(ENOSPC); + } + let address = a.blocks_low + u64::from(blocks) * G18_PB_BLOCK_BYTES; + let bytes = added as usize * G18_PB_BLOCK_BYTES as usize; + // As g17 admits its pools: the PB outlives the client, so its growth + // would otherwise be kernel memory no limit stops. A render with no + // client to charge is refused rather than growing unadmitted. + let client = client.ok_or(ENOMEM)?; + let charge = + crate::memacct::Charge::user(crate::memacct::LEDGER.admit(client, bytes as u64)?, None); + let mut object = MappedObject::new_wc_at_user_charged( + dev, + storage, + address, + bytes, + mmu::PROT_GPU_SHARED_RW, + )?; + let window = object.map_alias_at(storage, address + bias, mmu::PROT_GPU_SHARED_RW)?; + let mut aliases = KVec::with_capacity(2, GFP_KERNEL)?; + for at in [address, address + bias] { + aliases.push( + object.map_alias_at(vm, at, mmu::PROT_GPU_SHARED_RW)?, + GFP_KERNEL, + )?; + } + let first = + u32::try_from(address.wrapping_add(a.user_view_delta) >> 15).map_err(|_| ERANGE)?; + let last = first + added * G18_PB_PAGES_PER_BLOCK - 1; + if last >> 25 != 0 { + return Err(ERANGE); + } + // Firmware owns the blocks once published: nothing below may fail + // and drop them, so the owner vectors grow first. + self.blocks.reserve(1, GFP_KERNEL)?; + self.charges.reserve(1, GFP_KERNEL)?; + self.window_aliases.reserve(1, GFP_KERNEL)?; + for index in 0..added { + let slot = ((total + index) % capacity) as usize; + let base = first + index * G18_PB_PAGES_PER_BLOCK; + self.graph + .write_u32(a.graph_high + (BLOCK_TABLE + slot * 8) as u64, base)?; + self.graph + .write_u32(a.graph_high + (BLOCK_TABLE + slot * 8 + 4) as u64, 0)?; + } + let target = (total + added) % capacity; + fence(Ordering::SeqCst); + self.graph.write_u32(a.graph_high + SHARED as u64, target)?; + fence(Ordering::SeqCst); + self.graph + .write_u32(a.graph_high + (SHARED + 4) as u64, target)?; + fence(Ordering::SeqCst); + let _ = self.blocks.push_within_capacity(object); + charge.set_held(true); + let _ = self.charges.push_within_capacity(charge); + let _ = self.window_aliases.push_within_capacity(window); + dev_info!( + dev.as_ref(), + "G18_PB_GROW blocks={}->{} ring total={}->{} read={}\n", + blocks, + blocks + added, + total, + target, + read + ); + Ok((added, aliases)) + } + /// The PB words a recovery can leave behind: the firmware-visible state /// (ring cursors, free list, the +0x1c flag firmware sets when a recovery /// flushes a render using this PB, b000 0xfd58-0xfd9c), the active scene /// record, the submitted-render counter and the scene index. - pub(crate) fn recovery_words(&mut self) -> Result<([u32;G18_PB_STATE_FIRMWARE_BYTES/4],[u32;SCENE_BYTES/4],u32,u32)> { - let state: [u8;G18_PB_STATE_FIRMWARE_BYTES]=self.state.with_bytes_mut(|out|out[..G18_PB_STATE_FIRMWARE_BYTES].try_into().map_err(|_|EINVAL))?; - let start=SCENES+self.policy.scene as usize*SCENE_BYTES; - let scene: [u8;SCENE_BYTES]=self.graph.with_bytes_mut(|out|out[start..start+SCENE_BYTES].try_into().map_err(|_|EINVAL))?; - let word=|b:&[u8],i:usize|u32::from_le_bytes(b[i*4..i*4+4].try_into().unwrap_or([0;4])); - let counter=self.graph.read_u32(self.addresses.graph_high+COUNTER as u64)?; - Ok((core::array::from_fn(|i|word(&state,i)),core::array::from_fn(|i|word(&scene,i)),counter,self.policy.scene)) + pub(crate) fn recovery_words( + &mut self, + ) -> Result<( + [u32; G18_PB_STATE_FIRMWARE_BYTES / 4], + [u32; SCENE_BYTES / 4], + u32, + u32, + )> { + let state: [u8; G18_PB_STATE_FIRMWARE_BYTES] = self.state.with_bytes_mut(|out| { + out[..G18_PB_STATE_FIRMWARE_BYTES] + .try_into() + .map_err(|_| EINVAL) + })?; + let start = SCENES + self.policy.scene as usize * SCENE_BYTES; + let scene: [u8; SCENE_BYTES] = self.graph.with_bytes_mut(|out| { + out[start..start + SCENE_BYTES] + .try_into() + .map_err(|_| EINVAL) + })?; + let word = |b: &[u8], i: usize| { + u32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().unwrap_or([0; 4])) + }; + let counter = self + .graph + .read_u32(self.addresses.graph_high + COUNTER as u64)?; + Ok(( + core::array::from_fn(|i| word(&state, i)), + core::array::from_fn(|i| word(&scene, i)), + counter, + self.policy.scene, + )) } - - pub(crate) fn application_scene(&mut self, template: Option<&[u8;SCENE_BYTES]>) -> Result<[u8;SCENE_BYTES]> { - let start=SCENES+self.policy.scene as usize*SCENE_BYTES; + pub(crate) fn application_scene( + &mut self, + template: Option<&[u8; SCENE_BYTES]>, + ) -> Result<[u8; SCENE_BYTES]> { + let start = SCENES + self.policy.scene as usize * SCENE_BYTES; self.graph.with_bytes_mut(|out| { - if let Some(bytes)=template {out[start..start+SCENE_BYTES].copy_from_slice(bytes);} - out[start..start+SCENE_BYTES].try_into().map_err(|_|EINVAL) + if let Some(bytes) = template { + out[start..start + SCENE_BYTES].copy_from_slice(bytes); + } + out[start..start + SCENE_BYTES] + .try_into() + .map_err(|_| EINVAL) }) } /// Hardware owns the ring cursors and free-list ordering after a render. /// Do not re-encode them. Check the stable address/capacity and state owner. - pub(crate) fn verify_resident(&mut self, table: &mut MappedObject, context: u32, - generation: u32) -> Result { - if generation==1 {return self.verify_before_kick(table);} - let offset=self.policy.slot as usize*G18_PB_ROW_BYTES; - let row: [u8;G18_PB_ROW_BYTES]=table.with_bytes_mut(|out|out[offset..offset+G18_PB_ROW_BYTES].try_into().map_err(|_|EINVAL))?; - let word=|i:usize|u32::from_le_bytes(row[i..i+4].try_into().unwrap()); - if g18_pb_row_decoded_address(&row)!=Some(self.inputs.page_list_gpu) - || (word(4)&0x3f_ffff)!=(self.row.ok_or(EINVAL)?[4..8].try_into().map(u32::from_le_bytes).map_err(|_|EINVAL)?&0x3f_ffff) - || word(8)&0x3f_ffff>=self.policy.capacity*G18_PB_PAGES_PER_BLOCK - || word(12)&0x3f_ffff>=self.policy.capacity*G18_PB_PAGES_PER_BLOCK {return Err(EIO);} - let state: [u8;G18_PB_STATE_FIRMWARE_BYTES]=self.state.with_bytes_mut(|out|out[..G18_PB_STATE_FIRMWARE_BYTES].try_into().map_err(|_|EINVAL))?; - if u32::from_le_bytes(state[8..12].try_into().map_err(|_|EINVAL)?)!=context {return Err(EIO);} - let counter=self.graph.read_u32(self.addresses.graph_high+COUNTER as u64)?; - if counter!=generation {return Err(EIO);} - Ok(G18PbReadback {row,state,counter}) + pub(crate) fn verify_resident( + &mut self, + table: &mut MappedObject, + context: u32, + generation: u32, + ) -> Result { + if generation == 1 { + return self.verify_before_kick(table); + } + let offset = self.policy.slot as usize * G18_PB_ROW_BYTES; + let row: [u8; G18_PB_ROW_BYTES] = table.with_bytes_mut(|out| { + out[offset..offset + G18_PB_ROW_BYTES] + .try_into() + .map_err(|_| EINVAL) + })?; + let word = |i: usize| u32::from_le_bytes(row[i..i + 4].try_into().unwrap()); + // The page count grows with firmware-requested PB growth, never + // beyond the backed blocks. + let pages = self.policy.blocks * G18_PB_PAGES_PER_BLOCK + ..=self.backed_blocks()? * G18_PB_PAGES_PER_BLOCK; + if g18_pb_row_decoded_address(&row) != Some(self.inputs.page_list_gpu) + || (word(4) & 0xffc0_0000) + != (self.row.ok_or(EINVAL)?[4..8] + .try_into() + .map(u32::from_le_bytes) + .map_err(|_| EINVAL)? + & 0xffc0_0000) + || !pages.contains(&(word(4) & 0x3f_ffff)) + || word(8) & 0x3f_ffff >= self.policy.capacity * G18_PB_PAGES_PER_BLOCK + || word(12) & 0x3f_ffff >= self.policy.capacity * G18_PB_PAGES_PER_BLOCK + { + pr_err!( + "G18 PB row {:x?} refused: pages {:?}\n", + [word(0), word(4), word(8), word(12)], + pages + ); + return Err(EIO); + } + let state: [u8; G18_PB_STATE_FIRMWARE_BYTES] = self.state.with_bytes_mut(|out| { + out[..G18_PB_STATE_FIRMWARE_BYTES] + .try_into() + .map_err(|_| EINVAL) + })?; + if u32::from_le_bytes(state[8..12].try_into().map_err(|_| EINVAL)?) != context { + return Err(EIO); + } + let counter = self + .graph + .read_u32(self.addresses.graph_high + COUNTER as u64)?; + if counter != generation { + return Err(EIO); + } + Ok(G18PbReadback { + row, + state, + counter, + }) } } diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs index dd3eb2837c9c8..d897ef52749de 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job.rs @@ -105,7 +105,7 @@ impl G18GraphicsJob { metrics_high: va::PB_METRICS_HIGH, metrics_low: va::PB_METRICS_LOW, scene_scratch_low: va::PB_SCENE_SCRATCH, blocks_low: va::PB_BLOCKS, discard_low: va::PB_DISCARD, user_view_delta: 0, - }, G18PbPolicy { blocks: 8, capacity: 1650, pm_154: 550, pm_15c: 1650, + }, G18PbPolicy { blocks: crate::g18::uapi::render_policy::PB_BLOCKS, capacity: crate::g18::uapi::render_policy::PB_CAPACITY, pm_154: 550, pm_15c: 1650, pm_1d4: 0, scene_count: 80, scene: 1, slot: 0, generation: 1 })?; parameter_buffer.alias_low_window(program.vm(), program.vm(), va::COMPACT_BIAS)?; p.cycle = parameter_buffer.scene_cycle(); @@ -363,7 +363,7 @@ impl G18GraphicsJob { ("pb-metrics", va::PB_METRICS_LOW, 0x4000, self.context_id()), ("pb-scene-scratch", va::PB_SCENE_SCRATCH, 0x4000, self.context_id()), ("pb-discard", va::PB_DISCARD, 0x8000, self.context_id()), - ("pb-blocks", va::PB_BLOCKS, 8*0x80000, self.context_id()), + ("pb-blocks", va::PB_BLOCKS, crate::g18::uapi::render_policy::PB_BLOCKS as usize*0x80000, self.context_id()), ("uma-state", va::GRAPHICS_UMA_STATE, 0xa0, 0), ("uma-counter", va::GRAPHICS_UMA_COUNTER, 8, 0), ("uma-list", va::GRAPHICS_UMA_LIST, 0x2000, 0), diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs index 546d7e91877f8..9b02605388369 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs @@ -30,6 +30,22 @@ impl ApplicationJob { guard:None,scene,generation:0,retired:true,client_frames:0,scratch:None},GFP_KERNEL)?) } pub(crate) fn frame(&self) -> Frame {Frame::new(self.generation).expect("admitted frame")} + /// Grow the PB of the frame in flight for a firmware TVB grow request + /// naming its slot and context. The client aliases join the client's + /// other PB aliases; a later client maps every block afresh. + pub(crate) fn grow_parameter_buffer(&mut self, dev: &AsahiDrmDevice, buffer_slot: u32, + vm_slot: u32) -> Result { + use crate::g18::uapi::render_policy::{PB_GROW_BLOCKS,PB_MAX_BLOCKS}; + if self.retired || buffer_slot!=self.job.parameter_buffer.command_fields().pb_slot + || vm_slot!=u32::from(self.job.context_id()) {return Err(ENOENT);} + self.user_aliases.reserve(2,GFP_KERNEL)?; + let vm=self.job.vm().clone(); + let client=vm.memory_client().cloned(); + let (added,aliases)=self.job.parameter_buffer.grow(dev,&self.storage,&vm,client.as_ref(), + PB_GROW_BLOCKS,PB_MAX_BLOCKS)?; + for alias in aliases {let _=self.user_aliases.push_within_capacity(alias);} + Ok(added) + } /// The last frame kicked to both graphics queues (0 before the first). pub(crate) fn submitted_generation(&self) -> u32 {self.generation} pub(crate) fn quarantine(&mut self) { diff --git a/drivers/gpu/drm/asahi/g18/uapi/render_policy.rs b/drivers/gpu/drm/asahi/g18/uapi/render_policy.rs index c10b4098fca9f..54c7719173c7d 100644 --- a/drivers/gpu/drm/asahi/g18/uapi/render_policy.rs +++ b/drivers/gpu/drm/asahi/g18/uapi/render_policy.rs @@ -4,7 +4,15 @@ use crate::{g18::fw::render_params::G17pRenderParameters, g18::address_map as va, g18::fw::render::G18RenderControls, g18::fw::render_command::*, g18::fw::render_assembly as g18_render_assembly}; -pub(crate) const PB_BLOCKS: u32 = 8; // plan: overprovision >=8; no PB growth. +/// PB blocks backed before the first render (the native initial size). +pub(crate) const PB_BLOCKS: u32 = 8; +/// Blocks added per firmware TVB grow request (event 6), up to +/// PB_MAX_BLOCKS: the ring the firmware is given holds PB_CAPACITY slots and +/// one stays empty, so a full ring is told from an empty one. A request +/// refused below what the firmware was given leaves the tiler waiting until +/// the job watchdog. +pub(crate) const PB_GROW_BLOCKS: u32 = 16; +pub(crate) const PB_MAX_BLOCKS: u32 = PB_CAPACITY - 1; pub(crate) const PB_CAPACITY: u32 = 1650; pub(crate) const UMA_BLOCKS: u32 = 24; // 24 MiB > sum of both M5 budgets. pub(crate) const USC_REQUIRED: [u64; 2] = [0x7d4000, 0x934000]; // M5 DRM hardware path.