diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index b17f3d47a3e06..33ea620b9ac44 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -8,4 +8,4 @@ aurora-$(CONFIG_DRM_ASAHI_G15) += g15/glue.o aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o -aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o +aurora-y += retain.o cpu_capacity.o g17/mesh_tvb_floor.o rtkit_dump.o diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b970691651032..ccddb7e8c7efc 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -27,6 +27,9 @@ mod g18; #[cfg(CONFIG_DRM_ASAHI_M5)] mod m5; mod gpu; +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +mod j413; + mod hw; mod initdata; mod m3; @@ -176,6 +179,254 @@ module! { default: 1, description: "G13/G14: publish ready in-order jobs from SUBMIT (0: off)", }, + t8112_telemetry_ro: bool { + default: false, + description: "J413 startup trial: expose the shared telemetry window read-only", + }, + t8112_dashboard_ram: bool { + default: false, + description: "J413 idle-policy trial: back the dashboard update slot with isolated RAM", + }, + t8112_rgx_ram_pages: u32 { + default: 255, + description: "J413 RGX scratch trial: one bit per 16 KiB RAM page", + }, + t8112_ram_slots: u64 { + default: 0, + description: "J413 idle trial: isolated RAM substitutes, bit per descriptor (0, 1, 3, 8, 10, 12, 17, 33, 40, 44)", + }, + t8112_cre: bool { + default: false, + description: "J413 power trial: enable CRE during firmware initialization", + }, + t8112_power_filter: bool { + default: false, + description: "J413 26B123: seed the calibrated cold power controllers", + }, + t8112_power_curve: bool { + default: false, + description: "J413 indexed wake: populate the calibrated operating-point power curve", + }, + t8112_alarm_fields: u32 { + default: 0, + description: "J413 indexed wake: number of additional stock alarm fields to publish", + }, + t8112_calibrated_sensors: u64 { + default: 0, + description: "J413 trial: sensor inventory from this unit's PMGR calibration records", + }, + t8112_fast_die_fields: u32 { + default: 0, + description: "J413 metrology trial: cumulative fast-die release temperature, mask, integral and proportional gains (0-4)", + }, + t8112_firmware_log: bool { + default: false, + description: "J413 diagnostic: open the firmware log publication gate in the directory", + }, + t8112_service_stage: bool { + default: true, + description: "J413 26B123: also require powered stage 2 before the first engine entry", + }, + t8112_command_notifier: u32 { + default: 0, + description: "J413 first command: command offset of the per-command notifier pointer (0 none; firmware reads +0xc)", + }, + t8112_drain_statistics: bool { + default: false, + description: "J413 26B123: consume the firmware statistics ring while polling", + }, + t8112_client_counter: bool { + default: false, + description: "J413 first command: place the signal counter at a context-0 client VA", + }, + t8112_priority_row: u32 { + default: 255, + description: "J413 first command: legacy priority row and matching submission group (0-3), 255 for the stock priority fields in group 0", + }, + t8112_stock_header: bool { + default: false, + description: "J413 first command: type-9 prefix (data master at +0x18) and a tracking slot with its retirement cursor", + }, + t8112_completion_record: bool { + default: false, + description: "J413 first command: completion destination at command +0x30", + }, + t8112_job_context: u32 { + default: 0, + description: "J413 26B123: client context of the kernel-owned job (0 kernel context, 1-63 a clone of it)", + }, + t8112_provider_object: u32 { + default: 0, + description: "J413 26B123 compute job: provider-wide object named by start/finish (0 directory +0x264, 1 directory +0x26c)", + }, + t8112_tail_probe: u32 { + default: 0, + description: "J413 26B123 compute job diagnostic: poison or fill command tail words", + }, + t8112_start_probe: u32 { + default: 0, + description: "J413 26B123 compute job diagnostic: poison start-record operands (1 provider, 2 channel, 3 command-relative)", + }, + t8112_job_wait_ms: u32 { + default: 3000, + description: "J413 26B123: how long to wait for the held command to retire", + }, + t8112_power_zones: u32 { + default: 1, + description: "J413 26B123: average-power zone count seeded in the controller (stock J413 has 0)", + }, + t8112_rekick_ms: u32 { + default: 0, + description: "J413 26B123: repeat the engine kick this long after submission (0 never)", + }, + t8112_dashboard_real: bool { + default: false, + description: "J413 26B123: map the real push-telemetry dashboard page writable for the firmware instead of private RAM", + }, + t8112_state_cap: u32 { + default: 0, + description: "J413 26B123: upper performance-state cap in hundredths at shared configuration +0x98 (0 = ceiling)", + }, + t8112_firmware_trace: bool { + default: false, + description: "J413 26B123 diagnostic: set the firmware debug bit that enables its trace ring", + }, + t8112_trace_bits: u32 { + default: 2, + description: "J413 26B123 diagnostic: firmware debug category bits used with t8112_firmware_trace", + }, + t8112_trace_show: u32 { + default: 160, + description: "J413 26B123 diagnostic: number of trace records to print", + }, + t8112_hw_legacy: u64 { + default: 0, + description: "J413 26B123: carry legacy HwDataB configuration words to the inline hardware block (1 num_frags, 2 unk_504, 4 unk_4c0, 8 unk_534, 0x10 unk_524, 0x20 flag/clock group)", + }, + t8112_forced_stop: u32 { + default: 0, + description: "J413 trial: RTKit acknowledged power-off before teardown (1 if still running, 2 always)", + }, + t8112_queue_lane: u32 { + default: 0, + description: "J413 trial queue +0x48: 0 as the priority row writes it, 1 all-ones sentinel, n+2 lane n", + }, + t8112_task_configuration: u32 { + default: 0, + description: "J413 trial scheduler context +0x26: 0 untouched, n+1 task-configuration byte n", + }, + t8112_context_id_field: bool { + default: false, + description: "J413 trial client context: identifier in bits 63:48 of both table entries", + }, + t8112_private_scan: u32 { + default: 0, + description: "J413 trial, read-only firmware data log: 1 words around pointers to the job's host objects while parked, 2 non-zero rows of the queue-record areas, 4 both after the wait ends", + }, + t8112_drm: bool { + default: false, + description: "J413 27.2: keep the firmware running after the boot compute job and register a compute-only DRM device", + }, + t8112_drm_ring_skew: bool { + default: false, + description: "J413 27.2 diagnostic: publish one empty submission entry at take-over", + }, + t8112_queue_capacity: u32 { + default: 0x500, + description: "J413 27.2: queue capacity at position block +0x50 (16 x channel count, at most 0x800)", + }, + t8112_job_order: u32 { + default: 0, + description: "J413 26B123 compute job: 0 alone as the first command, 1 as the second command after the retiring signal, 2 first with the signal published behind it", + }, + t8112_compute_job: bool { + default: false, + description: "J413 26B123: submit a kernel-owned type-3 compute job (terminate-only CDM stream) in place of the signal", + }, + t8112_command_service: bool { + default: false, + description: "J413 26B123: request command-handler installation in the firmware data and wait for it", + }, + t8112_ring_start: u32 { + default: 0, + description: "J413 diagnostic: index of the trial ring's first entry (the ring starts empty there; 255 makes the first client command wrap)", + }, + t8112_first_publication: bool { + default: true, + description: "J413 first command: first-publication byte of the submission entry", + }, + t8112_queue_owner: u32 { + default: 0xffffffff, + description: "J413 first command: owning process word of the work queue", + }, + t8112_class_opcode: u32 { + default: 0x1b, + description: "J413 first command: device-control opcode of the engine-class registrations", + }, + t8112_opening_opcode: u32 { + default: 0x15, + description: "J413 first command: device-control opcode of the opening record (0x15 on the 27.x line, 0x16 on J613 26.6.2)", + }, + t8112_command_engine: u32 { + default: 2, + description: "J413 first command: data master of the signal (0 tiler, 1 fragment, 2 compute)", + }, + t8112_command_type: u32 { + default: 9, + description: "J413 first command: channel-command type word of the kernel-owned signal", + }, + t8112_engine_classes: u32 { + default: 0, + description: "J413 first command: 0 none, 1 stage the extended opening control record, 2 also register two engine classes per data master", + }, + t8112_active_followup: u32 { + default: 0, + description: "J413 acknowledged wake: 0 observe, 1 release, 2 complete a held fence then release", + }, + t8112_post_power_job: bool { + default: false, + description: "J413 power trial: publish one completion after both real-core idle commands retire", + }, + t8112_mtr_sensors: bool { + default: false, + description: "J413 stock power trial: use the G14G board sensor mask in the secure metrology controller", + }, + t8112_sgx_open: bool { + default: false, + description: "J413 power trial: open the SGX synchronization window with inherited platform selection", + }, + t8112_gpc_irq_bit: u32 { + default: 0, + description: "J413 stock power trial: enable one GPC interrupt bit (1 or 2)", + }, + t8112_event_completion: bool { + default: false, + description: "J413 power trial: select event-assisted operating-point completion", + }, + t8112_base_request: bool { + default: false, + description: "J413 power trial: initialize the wake operand from the board base operating point", + }, + t8112_performance_control: bool { + default: false, + description: "J413 power trial: request firmware-managed operating points", + }, + t8112_pmp_vote: bool { + default: false, + description: "J413 power trial: acquire the linked PMP AGX device before ASC start", + }, + t8112_fender_gating: u32 { + default: 0, + description: "J413 idle trial: Fender gating at power-on (0 inherited, 1 hold, 2 automatic)", + }, + t8112_idle_policy: bool { + default: false, + description: "J413 idle trial: request and release GPU power through the idle policy", + }, + t8112_handshake: u32 { + default: 0, + description: "J413 GPU trial: 1 UAT, 2 legacy InitData, 3-6 neighbouring ABI controls, 7 G14G root, 9/10 extended channel construction, 11 J413 stopped construction, 12 J413 startup with writable MMIO limited to SGX, 13 one kernel-owned compute fence, 14 matching idle control", + }, legacy_rx_fastpath: u32 { default: 1, description: "G13/G14: drain GPU events on a dedicated receive worker (0: off)", diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index d55826375296b..020952b58babd 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -116,7 +116,7 @@ pub(crate) struct TileInfo { } /// A single scene, representing a render pass and its required buffers. -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct Scene { object: GpuObject, @@ -136,7 +136,7 @@ pub(crate) struct Scene { meta4_off: usize, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Scene::ver { /// Returns true if the buffer was bound to a fresh manager slot, and therefore needs an init /// command before a render. @@ -272,7 +272,7 @@ impl Scene::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Drop for Scene::ver { fn drop(&mut self) { let mut inner = self.object.buffer.inner.lock(); @@ -290,7 +290,7 @@ impl Drop for Scene::ver { } /// Inner data for a single TVB buffer object. -#[versions(AGX)] +#[versions(AGX_ROOT)] struct BufferInner { info: GpuObject, ualloc: Arc>, @@ -313,12 +313,12 @@ struct BufferInner { } /// Locked and reference counted TVB buffer. -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct Buffer { inner: Arc>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Buffer::ver { /// Create a new Buffer for a given VM, given the per-VM allocators. pub(crate) fn new<'drm>( @@ -729,7 +729,7 @@ impl Buffer::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Clone for Buffer::ver { fn clone(&self) -> Self { Buffer::ver { @@ -738,10 +738,10 @@ impl Clone for Buffer::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] struct BufferSlotInner(); -#[versions(AGX)] +#[versions(AGX_ROOT)] impl slotalloc::SlotItem for BufferSlotInner::ver { type Data = BufferManagerInner::ver; @@ -752,16 +752,16 @@ impl slotalloc::SlotItem for BufferSlotInner::ver { } /// Inner data for the buffer manager, to be protected by the SlotAllocator lock. -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct BufferManagerInner { owners: KVec>, } /// The GPU-global buffer manager, used to allocate and release buffer slots from the pool. -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct BufferManager(slotalloc::SlotAllocator); -#[versions(AGX)] +#[versions(AGX_ROOT)] impl BufferManager::ver { pub(crate) fn new() -> Result { let mut owners = KVec::new(); @@ -801,7 +801,7 @@ impl BufferManager::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Clone for BufferManager::ver { fn clone(&self) -> Self { BufferManager::ver(self.0.clone()) diff --git a/drivers/gpu/drm/asahi/channel.rs b/drivers/gpu/drm/asahi/channel.rs index dbb84f288087b..b1d847d3089cd 100644 --- a/drivers/gpu/drm/asahi/channel.rs +++ b/drivers/gpu/drm/asahi/channel.rs @@ -210,13 +210,13 @@ where } /// Device Control channel for global device management commands. -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct DeviceControlChannel { dev: AsahiDevRef, ch: TxChannel, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl DeviceControlChannel::ver { const COMMAND_TIMEOUT_MS: i64 = 1000; @@ -249,13 +249,13 @@ impl DeviceControlChannel::ver { } /// Pipe channel to submit WorkQueue execution requests. -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct PipeChannel { dev: AsahiDevRef, ch: TxChannel, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl PipeChannel::ver { /// Allocate a new Pipe submission channel. pub(crate) fn new( @@ -316,7 +316,7 @@ impl FwCtlChannel { /// Event channel, used to notify the driver of command completions, GPU faults and errors, and /// other events. -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct EventChannel { dev: AsahiDevRef, ch: RxChannel, @@ -325,7 +325,7 @@ pub(crate) struct EventChannel { gpu: Option>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl EventChannel::ver { /// Allocate a new Event channel. pub(crate) fn new( @@ -587,7 +587,7 @@ impl KTraceChannel { /// Debug-logs the messages and, when the `stats_export` module parameter /// is enabled, also updates the shared `StatsSnapshot` exported via /// `/sys/class/drm/card*/device/agx_stats`. -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct StatsChannel { dev: AsahiDevRef, ch: RxChannel, @@ -602,7 +602,7 @@ pub(crate) struct StatsChannel { busy: crate::stats_busy::BusyIntegrator, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl StatsChannel::ver { /// Allocate a new Statistics channel. pub(crate) fn new( diff --git a/drivers/gpu/drm/asahi/driver.rs b/drivers/gpu/drm/asahi/driver.rs index 77ffd32891cd2..a15744721d0e3 100644 --- a/drivers/gpu/drm/asahi/driver.rs +++ b/drivers/gpu/drm/asahi/driver.rs @@ -53,6 +53,9 @@ pub(crate) struct AsahiPlatformDriverData<'bound> { #[cfg(CONFIG_DRM_ASAHI_G16)] pub(crate) g16: Option>, m3: Option, + /// The J413 27.2 compute backend, whose firmware must be stopped on unbind. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: Option>, /// Raw `struct device *` of the platform device. Stored once at probe /// time so the `Drop` impl can find the sysfs file on unregister. raw_dev: *mut bindings::device, @@ -150,6 +153,7 @@ impl drm::driver::Driver for AsahiDrmDriver { /// Firmware interface selected by the hardware compatible. pub(crate) enum ProbeConfig { Legacy(&'static hw::HwConfig), + T8112Identify, G17(&'static g17::Config), /// M5 Pro, Max and Ultra: the ID registers select the configuration. G17M5, @@ -195,6 +199,10 @@ macro_rules! asahi_of_device_table { of::DeviceId::new(c"apple,agx-t8103"), ProbeConfig::Legacy(&hw::t8103::HWCONFIG) ), + ( + of::DeviceId::new(c"apple,agx-t8112-identify"), + ProbeConfig::T8112Identify + ), ( of::DeviceId::new(c"apple,agx-t8112"), ProbeConfig::Legacy(&hw::t8112::HWCONFIG) @@ -337,6 +345,10 @@ impl platform::Driver for AsahiPlatformDriver { if let Some(m3) = this.m3.as_ref() { m3.stop(); } + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + if let Some(j413) = this.j413.as_ref() { + j413.stop(); + } this.close_binding(); } @@ -354,6 +366,20 @@ impl platform::Driver for AsahiPlatformDriver { dev_info!(pdev.as_ref(), "Probing...\n"); let cfg = match info.ok_or(ENODEV)? { + ProbeConfig::T8112Identify => { + let node = pdev.as_ref().fwnode().ok_or(ENODEV)?; + let version: KVec = node + .property_read_array_vec(c"apple,firmware-version", 3)? + .required_by(pdev.as_ref())?; + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + if version.as_slice() == [27, 2, 0] && matches!(crate::module_parameters::t8112_handshake.value(), 1..=7 | 9..=14) { + if let Some(live) = crate::mmu::Uat::observe_t8112_peer(pdev)? { + return AsahiPlatformDriver::probe_j413(pdev, live); + } + } + dev_info!(pdev.as_ref(), "T8112 G14G, firmware {:?}: no matching initdata layout; startup disabled\n", version.as_slice()); + return Err(ENODEV); + } ProbeConfig::Legacy(cfg) => *cfg, ProbeConfig::G17(cfg) => { return AsahiPlatformDriver::probe_g17(pdev, regs::G17Resources::new(pdev)?, cfg) @@ -449,6 +475,8 @@ impl platform::Driver for AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev, @@ -461,6 +489,43 @@ impl platform::Driver for AsahiPlatformDriver { } impl AsahiPlatformDriver { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + /// J413 with firmware 27.2: register the compute-only DRM device on the firmware the + /// bring-up path left running. + fn probe_j413<'bound>( + pdev: &'bound platform::Device>, + live: crate::j413::Live<'bound>, + ) -> Result> { + let crate::j413::Live { peer, root, graph, pool, asc, drm, binding, resources } = live; + let backend = crate::j413::Backend::start(&drm, pdev.as_ref(), peer, root, graph, pool, asc)?; + let gpu = backend.clone() as Arc; + let data = try_pin_init!(AsahiDrmRegistrationData { gpu, resources }); + // SAFETY: The registration is stored in the platform data and unregistered when it is + // dropped, after the backend has stopped the firmware. + let reg = match unsafe { drm::Registration::new(pdev.as_ref(), drm, data, 0) } { + Ok(reg) => reg, + Err(error) => { + backend.stop(); + return Err(error); + } + }; + dev_info!(pdev.as_ref(), "J413: firmware 27.2 running; compute-only DRM device registered\n"); + Ok(AsahiPlatformDriverData { + binding, + _device: reg.device().into(), + _reg: reg, + g17: None, + #[cfg(CONFIG_DRM_ASAHI_G16)] + g16: None, + m3: None, + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: Some(backend), + raw_dev: core::ptr::null_mut(), + raw_stats: core::ptr::null_mut(), + stats: None, + }) + } + #[cfg(CONFIG_DRM_ASAHI_G15)] pub(crate) fn probe_g15<'bound>( pdev: &'bound platform::Device>, @@ -487,6 +552,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -529,6 +596,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: Some(backend), + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: None, raw_dev: core::ptr::null_mut(), raw_stats: core::ptr::null_mut(), stats: None, @@ -605,6 +674,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: Some(gpu), m3: None, + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev, @@ -652,6 +723,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -691,6 +764,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: None, g16: Some(gpu), raw_dev, raw_stats, @@ -747,6 +822,8 @@ impl AsahiPlatformDriver { _reg: reg, g17: None, m3: None, + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + j413: None, #[cfg(CONFIG_DRM_ASAHI_G16)] g16: None, raw_dev: core::ptr::null_mut(), @@ -780,5 +857,9 @@ impl Drop for AsahiPlatformDriverData<'_> { if let Some(m3) = self.m3.as_ref() { m3.stop(); } + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + if let Some(j413) = self.j413.as_ref() { + j413.stop(); + } } } diff --git a/drivers/gpu/drm/asahi/event.rs b/drivers/gpu/drm/asahi/event.rs index edd7d701e665c..7a84a6e5f6067 100644 --- a/drivers/gpu/drm/asahi/event.rs +++ b/drivers/gpu/drm/asahi/event.rs @@ -54,6 +54,10 @@ pub(crate) type Event = slotalloc::Guard; pub(crate) struct EventValue(u32); impl EventValue { + pub(crate) fn raw(self) -> u32 { + self.0 + } + /// Returns the `EventValue` that succeeds this one. pub(crate) fn next(&self) -> EventValue { EventValue(self.0.wrapping_add(0x100)) @@ -199,6 +203,11 @@ impl EventManager { Ok(ev) } + /// Reserve the normal stamp pair for a kernel queue that polls its own completion. + pub(crate) fn try_get_polled(&self) -> Result { + self.alloc.try_get(None) + } + /// Signals an event by slot, indicating completion (of one or more commands). pub(crate) fn signal(&self, slot: u32) { match self diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 6f9a89cc311b6..1117213a777eb 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -318,10 +318,12 @@ impl SyncItem { } anchor = Some(i as usize); } - vec.push( - Self::parse_one(file, sync, i >= in_count, allow_cumulative)?, - GFP_KERNEL, - )?; + let (kind, handle, value) = (sync.sync_type, sync.handle, sync.timeline_value); + let item = Self::parse_one(file, sync, i >= in_count, allow_cumulative).inspect_err(|e| { + pr_info!("asahi: sync {} of {} (in {}) type={} handle={} value={} rejected {:?}\n", + i, count, in_count, kind, handle, value, e); + })?; + vec.push(item, GFP_KERNEL)?; } if let Some(anchor) = anchor { let bundle = crate::g17::sync_output::SignalBundle::new( @@ -1649,6 +1651,26 @@ impl File { reg_data: &driver::AsahiDrmRegistrationData<'_>, data: &mut uapi::drm_asahi_queue_create, file: &DrmFile, + ) -> Result { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + let (vm, prio, usc, layouts, timeout) = (data.vm_id, data.priority, data.usc_exec_base, + data.render_scs_layout, data.compute_timeout_ms); + let result = Self::queue_create_inner(device, reg_data, data, file); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + if let Err(e) = result.as_ref() { + if reg_data.gpu.as_any().is::() { + dev_info!(device.as_ref(), "queue_create failed {:?}: vm={} priority={} usc={:#x} layouts={:x?} timeout={}\n", + e, vm, prio, usc, layouts, timeout); + } + } + result + } + + fn queue_create_inner( + device: &AsahiDrmDevice, + reg_data: &driver::AsahiDrmRegistrationData<'_>, + data: &mut uapi::drm_asahi_queue_create, + file: &DrmFile, ) -> Result { let file_id = file.inner().id; @@ -1774,6 +1796,24 @@ impl File { reg_data: &driver::AsahiDrmRegistrationData<'_>, data: &mut uapi::drm_asahi_submit, file: &DrmFile, + ) -> Result { + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + let fields = (data.flags, data.pad, data.queue_id, data.in_sync_count, data.out_sync_count, data.cmdbuf_size); + let result = Self::submit_inner(device, reg_data, data, file); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + if let Err(e) = result.as_ref() { + if *e != ERESTARTSYS && reg_data.gpu.as_any().is::() { + dev_info!(device.as_ref(), "J413 submit ioctl failed {:?}: flags/pad/queue/in/out/size={:?}\n", e, fields); + } + } + result + } + + fn submit_inner( + device: &AsahiDrmDevice, + reg_data: &driver::AsahiDrmRegistrationData<'_>, + data: &mut uapi::drm_asahi_submit, + file: &DrmFile, ) -> Result { debug::update_debug_flags(); diff --git a/drivers/gpu/drm/asahi/fw/buffer.rs b/drivers/gpu/drm/asahi/fw/buffer.rs index b1f4974fd0290..434b842eb2380 100644 --- a/drivers/gpu/drm/asahi/fw/buffer.rs +++ b/drivers/gpu/drm/asahi/fw/buffer.rs @@ -44,7 +44,7 @@ pub(crate) mod raw { pub(crate) __pad1: Pad<0x1c>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct Info<'a> { @@ -85,7 +85,7 @@ pub(crate) mod raw { pub(crate) unk_90: Array<0x30, u8>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct Scene<'a> { @@ -109,7 +109,7 @@ pub(crate) mod raw { pub(crate) unk_38: U64, // pad } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct InitBuffer<'a> { @@ -127,7 +127,7 @@ trivial_gpustruct!(BlockControl); trivial_gpustruct!(Counter); trivial_gpustruct!(Stats); -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct Info { pub(crate) block_ctl: GpuObject, @@ -136,7 +136,7 @@ pub(crate) struct Info { pub(crate) block_list: GpuArray, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for Info::ver { type Raw<'a> = raw::Info::ver<'a>; } @@ -146,7 +146,7 @@ pub(crate) struct ClusterBuffers { pub(crate) meta: GpuArray, } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct Scene { pub(crate) user_buffer: GpuArray, pub(crate) buffer: crate::buffer::Buffer::ver, @@ -159,26 +159,26 @@ pub(crate) struct Scene { pub(crate) control_word: GpuArray, } -#[versions(AGX)] +#[versions(AGX_ROOT)] no_debug!(Scene::ver); -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for Scene::ver { type Raw<'a> = raw::Scene::ver<'a>; } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct InitBuffer { pub(crate) scene: Arc, } -#[versions(AGX)] +#[versions(AGX_ROOT)] no_debug!(InitBuffer::ver); -#[versions(AGX)] +#[versions(AGX_ROOT)] impl workqueue::Command for InitBuffer::ver {} -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for InitBuffer::ver { type Raw<'a> = raw::InitBuffer::ver<'a>; } diff --git a/drivers/gpu/drm/asahi/fw/channels.rs b/drivers/gpu/drm/asahi/fw/channels.rs index c1a7ec82aad1e..80aaa02dcb51e 100644 --- a/drivers/gpu/drm/asahi/fw/channels.rs +++ b/drivers/gpu/drm/asahi/fw/channels.rs @@ -122,7 +122,7 @@ pub(crate) enum PipeType { Compute = 2, } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug, Copy, Clone, Default)] #[repr(C)] pub(crate) struct RunWorkQueueMsg { @@ -137,10 +137,10 @@ pub(crate) struct RunWorkQueueMsg { pub(crate) __pad: Pad<0x1b>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) type PipeMsg = RunWorkQueueMsg::ver; -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) const DEVICECONTROL_SZ: usize = { #[ver(V < V13_2 || G != G14)] { @@ -155,7 +155,7 @@ pub(crate) const DEVICECONTROL_SZ: usize = { // TODO: clean up when arbitrary_enum_discriminant is stable // https://github.com/rust-lang/rust/issues/60553 -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug, Copy, Clone)] #[repr(C, u32)] #[allow(dead_code)] @@ -225,10 +225,10 @@ pub(crate) enum DeviceControlMsg { Initialize(Pad), // Update RegionC } -#[versions(AGX)] +#[versions(AGX_ROOT)] static_assert!(core::mem::size_of::() == 4 + DEVICECONTROL_SZ::ver); -#[versions(AGX)] +#[versions(AGX_ROOT)] default_zeroed!(DeviceControlMsg::ver); #[derive(Copy, Clone, Default, Debug)] @@ -331,7 +331,7 @@ pub(crate) struct RawKTraceMsg { pub(crate) unk_flag: U64, } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) const STATS_SZ: usize = { #[ver(V < V13_0B4)] { @@ -343,7 +343,7 @@ pub(crate) const STATS_SZ: usize = { } }; -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug, Copy, Clone)] #[repr(C, u32)] #[allow(dead_code)] @@ -425,13 +425,13 @@ pub(crate) enum StatsMsg { }, // Max discriminant: 0xe } -#[versions(AGX)] +#[versions(AGX_ROOT)] static_assert!(core::mem::size_of::() == 4 + STATS_SZ::ver); -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) const STATS_MAX: u32 = 0xe; -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Copy, Clone)] #[repr(C)] pub(crate) union RawStatsMsg { @@ -439,5 +439,5 @@ pub(crate) union RawStatsMsg { pub(crate) msg: StatsMsg::ver, } -#[versions(AGX)] +#[versions(AGX_ROOT)] default_zeroed!(RawStatsMsg::ver); diff --git a/drivers/gpu/drm/asahi/fw/compute.rs b/drivers/gpu/drm/asahi/fw/compute.rs index f5f6ffa9d8d0d..ac83fd4b3cc4a 100644 --- a/drivers/gpu/drm/asahi/fw/compute.rs +++ b/drivers/gpu/drm/asahi/fw/compute.rs @@ -39,7 +39,7 @@ pub(crate) mod raw { pub(crate) __pad: Pad<0xfc>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct JobParameters2<'a> { @@ -55,7 +55,7 @@ pub(crate) mod raw { pub(crate) unk_5c: u32, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct RunCompute<'a> { @@ -100,7 +100,7 @@ pub(crate) mod raw { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct RunCompute { pub(crate) notifier: Arc>, @@ -111,10 +111,10 @@ pub(crate) struct RunCompute { pub(crate) user_timestamps: job::UserTimestamps, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for RunCompute::ver { type Raw<'a> = raw::RunCompute::ver<'a>; } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl workqueue::Command for RunCompute::ver {} diff --git a/drivers/gpu/drm/asahi/fw/event.rs b/drivers/gpu/drm/asahi/fw/event.rs index e26bc6ceb3448..b0176fb8358c5 100644 --- a/drivers/gpu/drm/asahi/fw/event.rs +++ b/drivers/gpu/drm/asahi/fw/event.rs @@ -27,7 +27,7 @@ pub(crate) mod raw { } default_zeroed!(NotifierList); - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug, Clone, Copy)] #[repr(C)] pub(crate) struct NotifierState { @@ -51,7 +51,7 @@ pub(crate) mod raw { pub(crate) unk_buf: Array<0x8, u8>, // Init to all-ff } - #[versions(AGX)] + #[versions(AGX_ROOT)] impl Default for NotifierState::ver { fn default() -> Self { #[allow(unused_mut)] @@ -77,7 +77,7 @@ pub(crate) mod raw { } } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct Notifier<'a> { @@ -92,13 +92,13 @@ pub(crate) mod raw { trivial_gpustruct!(Threshold); trivial_gpustruct!(NotifierList); -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct Notifier { pub(crate) threshold: GpuObject, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for Notifier::ver { type Raw<'a> = raw::Notifier::ver<'a>; } diff --git a/drivers/gpu/drm/asahi/fw/fragment.rs b/drivers/gpu/drm/asahi/fw/fragment.rs index 3daad1ae4db67..aa653c091a093 100644 --- a/drivers/gpu/drm/asahi/fw/fragment.rs +++ b/drivers/gpu/drm/asahi/fw/fragment.rs @@ -55,7 +55,7 @@ pub(crate) mod raw { pub(crate) unk_padding: U64, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug, Clone, Copy)] #[repr(C)] pub(crate) struct AuxFBInfo { @@ -68,7 +68,7 @@ pub(crate) mod raw { pub(crate) unk3: U64, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct JobParameters1<'a> { @@ -154,7 +154,7 @@ pub(crate) mod raw { pub(crate) __pad: Pad<0xac>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct JobParameters3 { @@ -204,7 +204,7 @@ pub(crate) mod raw { pub(crate) isp_zls_pixels: U64, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct RunFragment<'a> { @@ -275,7 +275,7 @@ pub(crate) mod raw { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct RunFragment { pub(crate) notifier: Arc>, @@ -287,10 +287,10 @@ pub(crate) struct RunFragment { pub(crate) user_timestamps: job::UserTimestamps, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for RunFragment::ver { type Raw<'a> = raw::RunFragment::ver<'a>; } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl workqueue::Command for RunFragment::ver {} diff --git a/drivers/gpu/drm/asahi/fw/initdata.rs b/drivers/gpu/drm/asahi/fw/initdata.rs index 7c7488e950ace..3711ecaad200b 100644 --- a/drivers/gpu/drm/asahi/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/fw/initdata.rs @@ -22,7 +22,7 @@ pub(crate) mod raw { pub(crate) ring: Option>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct PipeChannels { @@ -30,7 +30,7 @@ pub(crate) mod raw { pub(crate) frag: ChannelRing, pub(crate) comp: ChannelRing, } - #[versions(AGX)] + #[versions(AGX_ROOT)] default_zeroed!(PipeChannels::ver); #[derive(Debug, Default)] @@ -184,7 +184,7 @@ pub(crate) mod raw { } default_zeroed!(T81xxData); - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Default, Copy, Clone)] #[repr(C)] pub(crate) struct PowerZone { @@ -202,7 +202,7 @@ pub(crate) mod raw { pub(crate) pad: u32, } - #[versions(AGX)] + #[versions(AGX_ROOT)] const MAX_CORES_PER_CLUSTER: usize = { #[ver(G >= G14X)] { @@ -223,7 +223,7 @@ pub(crate) mod raw { pub(crate) cs_2: Array<2, F32>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[repr(C)] pub(crate) struct HwDataA { pub(crate) unk_0: u32, @@ -587,9 +587,9 @@ pub(crate) mod raw { pub(crate) unk_3d34: Array<0x38, u8>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] default_zeroed!(HwDataA::ver); - #[versions(AGX)] + #[versions(AGX_ROOT)] no_debug!(HwDataA::ver); #[derive(Debug, Default, Clone, Copy)] @@ -602,7 +602,7 @@ pub(crate) mod raw { pub(crate) readwrite: U64, } - #[versions(AGX)] + #[versions(AGX_ROOT)] const IO_MAPPING_COUNT: usize = { #[ver(V < V13_0B4)] { @@ -637,7 +637,7 @@ pub(crate) mod raw { pub(crate) afr_unkpad: u32, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct HwDataB { @@ -663,10 +663,15 @@ pub(crate) mod raw { pub(crate) yuv_matrices: Array<0x3f, Array<3, Array<4, i16>>>, pub(crate) pad_1c8: Pad<0x8>, + #[ver(V < V27_2)] pub(crate) io_mappings: Array, + #[ver(V >= V27_2)] + pub(crate) io_mappings: Array<60, crate::g17::fw::initdata::RegisterMapEntry>, #[ver(V >= V13_0B4)] pub(crate) sgx_sram_ptr: U64, + #[ver(V >= V27_2)] + pub(crate) coredump_copy_buffer_size: U64, pub(crate) chip_id: u32, pub(crate) unk_454: u32, @@ -835,7 +840,7 @@ pub(crate) mod raw { #[ver(V >= V13_0B4)] pub(crate) unk_c3c: u32, } - #[versions(AGX)] + #[versions(AGX_ROOT)] default_zeroed!(HwDataB::ver); #[derive(Debug)] @@ -846,7 +851,7 @@ pub(crate) mod raw { } default_zeroed!(GpuStatsVtx); - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct GpuStatsFrag { @@ -861,7 +866,7 @@ pub(crate) mod raw { pub(crate) unk3: Array<0x1000, u8>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] impl Default for GpuStatsFrag::ver { fn default() -> Self { Self { @@ -884,7 +889,7 @@ pub(crate) mod raw { } default_zeroed!(GpuGlobalStatsVtx); - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug, Default)] #[repr(C)] pub(crate) struct GpuGlobalStatsFrag { @@ -901,7 +906,7 @@ pub(crate) mod raw { } default_zeroed!(GpuStatsComp); - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct RuntimeScratch { @@ -942,10 +947,10 @@ pub(crate) mod raw { pub(crate) unk_6b38: u32, pub(crate) pad_6b3c: Pad<0x84>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] default_zeroed!(RuntimeScratch::ver); - #[versions(AGX)] + #[versions(AGX_ROOT)] #[repr(C)] pub(crate) struct RuntimePointers<'a> { pub(crate) pipes: Array<4, PipeChannels::ver>, @@ -984,7 +989,7 @@ pub(crate) mod raw { pub(crate) __pad1: Pad<0x5c>, pub(crate) gpu_scratch: RuntimeScratch::ver, } - #[versions(AGX)] + #[versions(AGX_ROOT)] no_debug!(RuntimePointers::ver<'_>); #[derive(Debug)] @@ -1016,7 +1021,7 @@ pub(crate) mod raw { } default_zeroed!(PowerZoneGlobal); - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct Globals { @@ -1226,7 +1231,7 @@ pub(crate) mod raw { #[ver(V >= V13_3)] pub(crate) unk_11f00: Array<0x280, u8>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] default_zeroed!(Globals::ver); #[derive(Debug, Default, Clone, Copy)] @@ -1243,7 +1248,7 @@ pub(crate) mod raw { pub(crate) index_mask: U64, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct InitData<'a> { @@ -1253,20 +1258,67 @@ pub(crate) mod raw { pub(crate) unk_buf: GpuPointer<'a, &'a [u8]>, pub(crate) unk_8: u32, pub(crate) unk_c: u32, + #[ver(V < V27_2)] pub(crate) runtime_pointers: GpuPointer<'a, super::RuntimePointers::ver>, + #[ver(V < V27_2)] pub(crate) globals: GpuPointer<'a, super::Globals::ver>, + #[ver(V < V27_2)] pub(crate) fw_status: GpuPointer<'a, super::FwStatus>, + // The newer single-role G15 root splits the old status pointer into two words. + // Opaque targets stay tied to their backing until their contents are qualified. + #[ver(V >= V27_2)] + pub(crate) runtime_pointers: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) globals: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) role: u32, + #[ver(V >= V27_2)] + pub(crate) host_mapped_fw_allocations: u32, pub(crate) uat_page_size: u16, pub(crate) uat_page_bits: u8, pub(crate) uat_num_levels: u8, pub(crate) uat_level_info: Array<0x3, UatLevelInfo>, pub(crate) __pad0: Pad<0x14>, + #[ver(V < V27_2)] pub(crate) host_mapped_fw_allocations: u32, + #[ver(V < V27_2)] pub(crate) unk_ac: u32, + #[ver(V < V27_2)] pub(crate) unk_b0: u32, + #[ver(V < V27_2)] pub(crate) unk_b4: u32, + #[ver(V < V27_2)] pub(crate) unk_b8: u32, + #[ver(V >= V27_2)] + pub(crate) status_record: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) control: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) power: GpuPointer<'a, &'a [u8]>, + #[ver(V >= V27_2)] + pub(crate) extra: GpuPointer<'a, &'a [u8]>, } + + // The candidate is deliberately limited to the root. These checks validate + // host encoding against the neighbouring profiles, independent of firmware admission. + const _: () = { + // T8112's older layout locates its optional SRAM pointer after 25 IO records. + assert!(core::mem::offset_of!(HwDataBG14V13_5, io_mappings) == 0x640); + assert!(core::mem::size_of::() == 0x20); + assert!(core::mem::offset_of!(HwDataBG14V13_5, sgx_sram_ptr) == 0x960); + assert!(core::mem::offset_of!(HwDataBG14V27_2, io_mappings) == 0x640); + assert!(core::mem::offset_of!(HwDataBG14V27_2, sgx_sram_ptr) == 0xfa0); + assert!(core::mem::offset_of!(HwDataBG14V27_2, coredump_copy_buffer_size) == 0xfa8); + assert!(core::mem::offset_of!(HwDataBG14V27_2, chip_id) == 0xfb0); + type Root = InitDataG14V27_2<'static>; + assert!(core::mem::offset_of!(Root, ver_info) == 0); + assert!(core::mem::offset_of!(Root, role) == 0x28); + assert!(core::mem::offset_of!(Root, host_mapped_fw_allocations) == 0x2c); + assert!(core::mem::offset_of!(Root, uat_level_info) == 0x34); + assert!(core::mem::offset_of!(Root, status_record) == 0xa8); + assert!(core::mem::offset_of!(Root, extra) == 0xc0); + assert!(core::mem::size_of::() == 0xc8); + }; } #[derive(Debug)] @@ -1292,17 +1344,17 @@ where trivial_gpustruct!(FwStatus); trivial_gpustruct!(GpuGlobalStatsVtx); -#[versions(AGX)] +#[versions(AGX_ROOT)] trivial_gpustruct!(GpuGlobalStatsFrag::ver); trivial_gpustruct!(GpuStatsComp); -#[versions(AGX)] +#[versions(AGX_ROOT)] trivial_gpustruct!(HwDataA::ver); -#[versions(AGX)] +#[versions(AGX_ROOT)] trivial_gpustruct!(HwDataB::ver); -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct Stats { pub(crate) vtx: GpuObject, @@ -1310,7 +1362,7 @@ pub(crate) struct Stats { pub(crate) comp: GpuObject, } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct RuntimePointers { pub(crate) stats: Stats::ver, @@ -1329,15 +1381,15 @@ pub(crate) struct RuntimePointers { pub(crate) buffer_mgr_ctl_high_mapping: Option, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for RuntimePointers::ver { type Raw<'a> = raw::RuntimePointers::ver<'a>; } -#[versions(AGX)] +#[versions(AGX_ROOT)] trivial_gpustruct!(Globals::ver); -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct InitData { pub(crate) unk_buf: GpuArray, @@ -1346,7 +1398,7 @@ pub(crate) struct InitData { pub(crate) fw_status: GpuObject, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for InitData::ver { type Raw<'a> = raw::InitData::ver<'a>; } diff --git a/drivers/gpu/drm/asahi/fw/microseq.rs b/drivers/gpu/drm/asahi/fw/microseq.rs index ff59deda6be61..fe6dedd80c0f5 100644 --- a/drivers/gpu/drm/asahi/fw/microseq.rs +++ b/drivers/gpu/drm/asahi/fw/microseq.rs @@ -147,7 +147,7 @@ pub(crate) struct RetireStamp { impl Operation for RetireStamp {} -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct Timestamp<'a> { @@ -166,10 +166,10 @@ pub(crate) struct Timestamp<'a> { pub(crate) unk_30_padding: u32, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl<'a> Operation for Timestamp::ver<'a> {} -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct StartVertex<'a> { @@ -206,10 +206,10 @@ pub(crate) struct StartVertex<'a> { pub(crate) unk_178: u32, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl<'a> Operation for StartVertex::ver<'a> {} -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct FinalizeVertex { @@ -243,10 +243,10 @@ pub(crate) struct FinalizeVertex { pub(crate) unk_74: Array<0x10, u8>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Operation for FinalizeVertex::ver {} -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct StartFragment<'a> { @@ -287,10 +287,10 @@ pub(crate) struct StartFragment<'a> { pub(crate) notifier_buf: GpuWeakPointer>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl<'a> Operation for StartFragment::ver<'a> {} -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct FinalizeFragment { @@ -329,10 +329,10 @@ pub(crate) struct FinalizeFragment { pub(crate) unk_9c: Array<0x10, u8>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Operation for FinalizeFragment::ver {} -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct StartCompute<'a> { @@ -364,10 +364,10 @@ pub(crate) struct StartCompute<'a> { pub(crate) notifier_buf: GpuWeakPointer>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl<'a> Operation for StartCompute::ver<'a> {} -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct FinalizeCompute<'a> { @@ -408,5 +408,5 @@ pub(crate) struct FinalizeCompute<'a> { pub(crate) unk_79: Array<0x7, u8>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl<'a> Operation for FinalizeCompute::ver<'a> {} diff --git a/drivers/gpu/drm/asahi/fw/vertex.rs b/drivers/gpu/drm/asahi/fw/vertex.rs index 07a0e05c72112..cb2637b396e84 100644 --- a/drivers/gpu/drm/asahi/fw/vertex.rs +++ b/drivers/gpu/drm/asahi/fw/vertex.rs @@ -38,7 +38,7 @@ pub(crate) mod raw { pub(crate) __pad: Pad<0x70>, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct JobParameters1<'a> { @@ -111,7 +111,7 @@ pub(crate) mod raw { pub(crate) unk_520: U64, } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct RunVertex<'a> { @@ -173,7 +173,7 @@ pub(crate) mod raw { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct RunVertex { pub(crate) notifier: Arc>, @@ -184,10 +184,10 @@ pub(crate) struct RunVertex { pub(crate) user_timestamps: job::UserTimestamps, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for RunVertex::ver { type Raw<'a> = raw::RunVertex::ver<'a>; } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl workqueue::Command for RunVertex::ver {} diff --git a/drivers/gpu/drm/asahi/fw/workqueue.rs b/drivers/gpu/drm/asahi/fw/workqueue.rs index 78ac6c676a6eb..5a2865e73c207 100644 --- a/drivers/gpu/drm/asahi/fw/workqueue.rs +++ b/drivers/gpu/drm/asahi/fw/workqueue.rs @@ -124,7 +124,7 @@ pub(crate) mod raw { } } - #[versions(AGX)] + #[versions(AGX_ROOT)] #[derive(Debug)] #[repr(C)] pub(crate) struct QueueInfo<'a> { @@ -175,7 +175,7 @@ impl GpuStruct for GpuContextData { /// /// The raw structure points to the queue's GPU context weakly. The `GpuContext` keeps these /// structures until it has been invalidated, and only then frees its own data. -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Debug)] pub(crate) struct QueueInfo { pub(crate) state: GpuObject, @@ -184,7 +184,7 @@ pub(crate) struct QueueInfo { pub(crate) notifier_list: Arc>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuStruct for QueueInfo::ver { type Raw<'a> = raw::QueueInfo::ver<'a>; } diff --git a/drivers/gpu/drm/asahi/g15/uat.rs b/drivers/gpu/drm/asahi/g15/uat.rs index 0f91f7c9f0610..8168f32abe01b 100644 --- a/drivers/gpu/drm/asahi/g15/uat.rs +++ b/drivers/gpu/drm/asahi/g15/uat.rs @@ -118,7 +118,7 @@ fn clean_entries(pa: u64, first: usize, count: usize) -> Result { } /// Cleans a whole RAM table page to the point of coherency. -fn clean_page(pa: u64) -> Result { +pub(crate) fn clean_page(pa: u64) -> Result { clean_entries(pa, 0, ENTRIES) } diff --git a/drivers/gpu/drm/asahi/g17/fw/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/initdata.rs index a70b5763eac4d..9c827c6d8c188 100644 --- a/drivers/gpu/drm/asahi/g17/fw/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/initdata.rs @@ -652,6 +652,7 @@ impl RegisterWindow { const RESERVED_SLOT_UNK_20: u32 = 2; /// One register-map slot of the hardware data. +#[derive(Debug)] #[repr(C)] pub(crate) struct RegisterMapEntry { /// Physical address of the window. diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index fa59271630930..b9e8f4aec4a7f 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -1827,7 +1827,7 @@ const COMMON26_POLICY_BOOT_TIMESTAMP: usize = 0x6c14; /// initPowerAndPerformanceData stores (the G18 backend's G18G_26A428_POLICY_BANDS). 26A428 /// inserts 0x680 bytes between the AON PTD pointer and the boot timestamp; the 25G76 words /// there have no place. -const COMMON26_POLICY_BANDS: &[LayoutBand] = &[ +pub(crate) const COMMON26_POLICY_BANDS: &[LayoutBand] = &[ band(0x0000, 0x009c, 0, Evidence::ProducerChecked), band(0x00a0, 0x0200, 0x10, Evidence::ProducerChecked), band(0x09b8, 0x295c, 0x10, Evidence::ProducerChecked), diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5..3afcf8c937924 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -375,6 +375,16 @@ enum CrashLogMap { FirmwareData(data_segment::DataSegmentLog), } +impl CrashLog { + /// Map only the range firmware requested within its loader-reserved data. + pub(crate) fn from_firmware(dev: &device::Device, iova: usize, size: usize) -> Result { + Ok(Self { + iova, + map: CrashLogMap::FirmwareData(data_segment::DataSegmentLog::map(dev, iova, size)?), + }) + } +} + impl rtkit::Buffer for CrashLog { fn iova(&self) -> Result { Ok(self.iova) @@ -483,14 +493,7 @@ impl rtkit::Operations for RoleOps { }); } // The firmware places its buffers in its data segment, at their physical address. - Ok(CrashLog { - iova, - map: CrashLogMap::FirmwareData(data_segment::DataSegmentLog::map( - &data.shared.dev, - iova, - size, - )?), - }) + CrashLog::from_firmware(&data.shared.dev, iova, size) } } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 588f95f087a49..01faa2fd6a84a 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -106,6 +106,20 @@ const EP_DOORBELL: u8 = 0x21; const MSG_INIT: u64 = 0x81 << 48; const INIT_DATA_MASK: u64 = (1 << 44) - 1; +pub(crate) const fn init_message(address: u64) -> u64 { + MSG_INIT | (address & INIT_DATA_MASK) +} + +/// The four 16-bit firmware version words of a packed version. +pub(crate) fn version_words(word: u64) -> fw::types::Array<4, u16> { + fw::types::Array::new(core::array::from_fn(|i| (word >> (16 * i)) as u16)) +} + +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +mod j413_root; +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +pub(crate) use j413_root::*; + const RX_WORK_PENDING: u32 = 1 << 0; const RX_WORK_RUNNING: u32 = 1 << 1; @@ -127,6 +141,7 @@ const DOORBELL_DEVCTRL: u64 = 0x11; // Upper kernel half VA address ranges. /// Private (cached) firmware structure VA range base. const IOVA_KERN_PRIV_RANGE: Range = 0xffffffa000000000..0xffffffa600000000; +const G14G_TIMESTAMP_RANGE: Range = 0xffffffa181400000..0xffffffa185400000; /// Private (cached) GPU-RO firmware structure VA range base. const IOVA_KERN_GPU_RO_RANGE: Range = 0xffffffa600000000..0xffffffa800000000; /// Shared (uncached) firmware structure VA range base. @@ -179,7 +194,7 @@ pub(crate) struct KernelAllocators { } /// Receive (GPU->driver) ring buffer channels. -#[versions(AGX)] +#[versions(AGX_ROOT)] #[pin_data] struct RxChannels { event: channel::EventChannel::ver, @@ -189,7 +204,7 @@ struct RxChannels { } /// GPU work submission pipe channels (driver->GPU). -#[versions(AGX)] +#[versions(AGX_ROOT)] struct PipeChannels { pub(crate) vtx: KVec>>>, pub(crate) frag: KVec>>>, @@ -197,7 +212,7 @@ struct PipeChannels { } /// Misc command transmit (driver->GPU) channels. -#[versions(AGX)] +#[versions(AGX_ROOT)] #[pin_data] struct TxChannels { pub(crate) device_control: channel::DeviceControlChannel::ver, @@ -262,7 +277,7 @@ struct FaultLogState { } /// Top-level GPU manager that owns all the global state relevant to the driver instance. -#[versions(AGX)] +#[versions(AGX_ROOT)] #[pin_data] pub(crate) struct GpuManager { dev: AsahiDevRef, @@ -300,7 +315,7 @@ pub(crate) struct GpuManager { fault_log: SpinLock, } -#[versions(AGX)] +#[versions(AGX_ROOT)] unsafe impl HasWork for GpuManager::ver { unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work { // SAFETY: The caller supplies a live GpuManager allocation. @@ -313,7 +328,7 @@ unsafe impl HasWork for GpuManager::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl WorkItem for GpuManager::ver { type Pointer = Arc; @@ -529,7 +544,7 @@ impl rtkit::Buffer for RtkitObject { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[vtable] impl rtkit::Operations for GpuManager::ver { type Data = Arc; @@ -598,7 +613,7 @@ impl rtkit::Operations for GpuManager::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuManager::ver { fn poll_rx_channels(&self) { let mut ch = self.rx_channels.lock(); @@ -653,13 +668,45 @@ impl GpuManager::ver { cfg: &'static hw::HwConfig, ) -> Result> { let uat = Self::make_uat(dev, cfg)?; + let mgr = Self::build_graph(dev, res, cfg, uat, true, None)?; + let rtkit = + rtkit::RtKit::::new(dev.as_ref().as_ref(), None, 0, mgr.clone())?; + + *mgr.rtkit.lock() = Some(rtkit); + + { + let mut rxc = mgr.rx_channels.lock(); + rxc.event.set_manager(mgr.clone()); + } + + Ok(mgr) + } + + // Build the owned records before attaching RTKit. A version-check trial can + // supply its own reserved UAT and withhold the MMIO aperture and all doorbells. + #[inline(never)] + pub(crate) fn build_graph( + dev: &AsahiDrmDevice, + res: ®s::Resources<'_>, + cfg: &'static hw::HwConfig, + uat: KBox, + map_registers: bool, + _trial_version: Option, + ) -> Result> { let dyncfg = Self::make_dyncfg(dev, res, cfg, &uat)?; + // The 26B123 timestamp aperture falls inside the legacy private range. + // Keep normal allocations below it in the J413 construction profile. + let private_end = if cfg.chip_id == 0x8112 && _trial_version == Some(0x0c8a_8342_8392_04c8) { + G14G_TIMESTAMP_RANGE.start + } else { + IOVA_KERN_PRIV_RANGE.end + }; let mut alloc = KernelAllocators { private: alloc::DefaultAllocator::new( dev, uat.kernel_vm(), - IOVA_KERN_PRIV_RANGE, + IOVA_KERN_PRIV_RANGE.start..private_end, 0x80, mmu::PROT_FW_PRIV_RW, 1024 * 1024, @@ -802,49 +849,54 @@ impl GpuManager::ver { } }); - for (i, map) in cfg.io_mappings.iter().enumerate() { - if let Some(map) = map.as_ref() { - Self::iomap(&mut mgr, cfg, i, map)?; + if map_registers { + for (i, map) in cfg.io_mappings.iter().enumerate() { + if let Some(map) = map.as_ref() { + Self::iomap(&mut mgr, cfg, i, map)?; + } } - } - #[ver(V >= V13_0B4)] - if let Some(base) = cfg.sram_base { - let size = cfg.sram_size.unwrap(); - let iova = mgr.as_mut().alloc_mmio_iova(size); - - let mapping = mgr.uat.kernel_vm().map_io( - dev.as_ref().as_ref(), - iova, - base, - size, - mmu::PROT_FW_SHARED_RW, - )?; + #[ver(V >= V13_0B4)] + if let Some(base) = cfg.sram_base { + let size = cfg.sram_size.unwrap(); + let iova = mgr.as_mut().alloc_mmio_iova(size); + + let mapping = mgr.uat.kernel_vm().map_io( + dev.as_ref().as_ref(), + iova, + base, + size, + mmu::PROT_FW_SHARED_RW, + )?; - mgr.as_mut() - .initdata_mut() - .runtime_pointers - .hwdata_b - .with_mut(|raw, _| { - raw.sgx_sram_ptr = U64(mapping.iova()); - }); + mgr.as_mut() + .initdata_mut() + .runtime_pointers + .hwdata_b + .with_mut(|raw, _| { + raw.sgx_sram_ptr = U64(mapping.iova()); + }); - mgr.as_mut().io_mappings_mut().push(mapping, GFP_KERNEL)?; + mgr.as_mut().io_mappings_mut().push(mapping, GFP_KERNEL)?; + } } - let mgr = Arc::from(mgr); + #[ver(V >= V13_0B4)] + if let Some(word) = _trial_version { + mgr.as_mut().initdata_mut().with_mut(|raw, _| raw.ver_info = version_words(word)); + } - let rtkit = - rtkit::RtKit::::new(dev.as_ref().as_ref(), None, 0, mgr.clone())?; + let mgr = Arc::from(mgr); - *mgr.rtkit.lock() = Some(rtkit); + Ok(mgr) + } - { - let mut rxc = mgr.rx_channels.lock(); - rxc.event.set_manager(mgr.clone()); - } + pub(crate) fn trial_root(&self) -> u64 { + self.initdata.gpu_va().get() + } - Ok(mgr) + pub(crate) fn trial_uat(&self) -> &mmu::Uat { + &self.uat } /// Return a mutable reference to the initdata member @@ -1257,6 +1309,10 @@ impl GpuManager::ver { } } + // The 27.2 hardware data carries register-map entries; its builder fills them. + #[ver(V >= V27_2)] + let _ = index; + #[ver(V < V27_2)] this.as_mut() .initdata_mut() .runtime_pointers @@ -1531,7 +1587,7 @@ extern "C" { fn asahi_min_cpu_capacity() -> u32; } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Gpu for GpuManager::ver { /// A light submission completes in tens of microseconds, so its submitter /// sleeps briefly between submissions and the CPU scheduler places and @@ -1588,7 +1644,7 @@ impl Gpu for GpuManager::ver { rtk.as_mut().start_endpoint(EP_FIRMWARE)?; rtk.as_mut().start_endpoint(EP_DOORBELL)?; rtk.as_mut() - .send_message(EP_FIRMWARE, MSG_INIT | (initdata & INIT_DATA_MASK))?; + .send_message(EP_FIRMWARE, init_message(initdata))?; rtk.as_mut() .send_message(EP_DOORBELL, MSG_TX_DOORBELL | DOORBELL_DEVCTRL)?; core::mem::drop(guard); @@ -1685,7 +1741,7 @@ impl Gpu for GpuManager::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuManager for GpuManager::ver { fn update_globals(&self) { let mut timeout: u32 = 2; @@ -2028,7 +2084,7 @@ impl GpuManager for GpuManager::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl GpuManagerPriv for GpuManager::ver { fn end_op(&self) { let val = self diff --git a/drivers/gpu/drm/asahi/gpu/j413_root.rs b/drivers/gpu/drm/asahi/gpu/j413_root.rs new file mode 100644 index 0000000000000..371936a3074f7 --- /dev/null +++ b/drivers/gpu/drm/asahi/gpu/j413_root.rs @@ -0,0 +1,2123 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! T8112 (G14G) with GPU firmware 27.2: the bring-up root, its queues and the command pool +//! that the compute DRM backend (`crate::j413`) publishes on. + +use super::*; + +/// An isolated root-layout comparison. The manager owns the calibrated G14 +/// records and channels. Every new pointer names a live allocation. +pub(crate) struct G14TrialRoot { + graph: Arc, + directory: Option>, + controller: Option>, + slot_ram: KVec, + _channels: KVec>, + _register_mappings: KVec, + startup_fence: Option, + globals: Option>, + boot_page: Option>, + status: fw::types::GpuArray, + control: fw::types::GpuArray, + power: fw::types::GpuArray, + extra: fw::types::GpuArray, +} + +/// Ordinary RAM only. The mapping drops before its backing. Both are retained +/// with the root through ASC shutdown, including the failed-shutdown path. +struct G14SlotRam { + mappings: KVec, + register_base: u64, + ram_pages: u32, + ram: mmu::ContiguousScratch, + initial: KVec, + slot: usize, +} + +impl G14SlotRam { + fn readback(slot: usize) -> bool { + matches!(slot, 1 | 10) + } + + fn protection(slot: usize) -> mmu::Prot { + if Self::readback(slot) { mmu::PROT_FW_SHARED_RO } else { mmu::PROT_FW_SHARED_RW } + } + + fn new(graph: &GpuManagerG14V13_5, slot: usize, span: usize, va: u64, register_base: u64) -> Result { + let mut initial = KVec::from_elem(0u8, span, GFP_KERNEL)?; + if matches!(slot, 9 | 10) { + // Slots 9 and 10 start from a snapshot of their live register pages, which the + // caller saves as a firmware file before loading the module. + let name = if slot == 10 { c"apple/t8112-gpu-slot10-seed.bin" } else { c"apple/t8112-gpu-slot9-seed.bin" }; + let seed = kernel::firmware::Firmware::request_nowarn( + name, graph.dev.as_ref().as_ref())?; + if seed.size() != span { return Err(EINVAL); } + initial.copy_from_slice(seed.data()); + } + if slot == 40 { + // G14G has one cluster. Preserve its board fuse mask in the Fender copy. + let [mask] = graph.dyncfg.id.core_masks.as_slice() else { return Err(EINVAL); }; + initial[0x1500..0x1504].copy_from_slice(&(*mask as u32).to_le_bytes()); + } + let ram = mmu::ContiguousScratch::zeroed(span)?; + for (index, chunk) in initial.chunks(kernel::page::PAGE_SIZE).enumerate() { + ram.with_cpu_page(index * kernel::page::PAGE_SIZE, |ptr| { + // SAFETY: the allocated page is exclusively host-owned before publication. + unsafe { core::ptr::copy_nonoverlapping(chunk.as_ptr(), ptr, chunk.len()) }; + crate::pgtable::clean_invalidate_poc(ptr, chunk.len()); + })?; + } + crate::pgtable::poc_barrier(); + let ram_pages = if slot == 17 { + let pages = crate::module_parameters::t8112_rgx_ram_pages.value(); + if pages > 255 || span != 8 * mmu::UAT_PGSZ || register_base != 0x204000000 { + return Err(EINVAL); + } + pages + } else { u32::MAX }; + let mut owner = Self { mappings: KVec::new(), register_base, ram_pages, ram, initial, slot }; + for offset in (0..span).step_by(mmu::UAT_PGSZ) { + let (physical, prot) = owner.backing(offset); + let map = graph.uat.kernel_vm().map_io(graph.dev.as_ref().as_ref(), va + offset as u64, + physical as usize, mmu::UAT_PGSZ, prot)?; + if map.translate_offset(0)? != physical { return Err(EFAULT); } + owner.mappings.push(map, GFP_KERNEL)?; + } + Ok(owner) + } + + fn backing(&self, offset: usize) -> (u64, mmu::Prot) { + if self.slot == 17 && self.ram_pages & (1 << (offset / mmu::UAT_PGSZ)) == 0 { + (self.register_base + offset as u64, mmu::PROT_FW_MMIO_RW) + } else { + (self.ram.physical() + offset as u64, Self::protection(self.slot)) + } + } + + fn report_stopped(&self, graph: &GpuManagerG14V13_5) -> Result { + let mut changed = 0; + for (index, chunk) in self.initial.chunks(kernel::page::PAGE_SIZE).enumerate() { + let base = index * kernel::page::PAGE_SIZE; + self.ram.with_cpu_page(base, |ptr| { + crate::pgtable::clean_invalidate_poc(ptr, chunk.len()); + crate::pgtable::poc_barrier(); + for (i, bytes) in chunk.chunks_exact(4).enumerate() { + let before = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + // SAFETY: the ASC is stopped; this aligned word is within the owned page. + let after = unsafe { ptr.cast::().add(i).read_volatile() }; + if after != before { + dev_info!(graph.dev.as_ref(), "G14G scratch slot={} offset={:#x} before={:#x} after={:#x}\n", + self.slot, base + 4*i, before, after); + changed += 1; + } + } + })?; + } + dev_info!(graph.dev.as_ref(), "G14G scratch slot={} changed={} words={}\n", + self.slot, changed, self.initial.len()/4); + Ok(()) + } +} + +impl fw::types::GpuStruct for G14TrialRoot { + type Raw<'a> = fw::initdata::raw::InitDataG14V27_2<'a>; +} + +#[derive(Copy, Clone)] +pub(crate) enum G14DirectoryHeader { + Zero, + PrivatePage, + J413 { sgx: u64, sgx_size: u64, interrupt: u64, copy_bytes: u32, live: bool, first_job: bool }, +} + +/// Single kernel-owned completion with no external notification destinations. +struct G14StartupFence { + queue: fw::types::GpuArray, + positions: fw::types::GpuArray, + counter: fw::types::GpuArray, + event: event::Event, + expected_stamp: u32, + /// Stamp value of the compute job published as the queue's second command. + second: Option, + _owners: KVec>, + /// Client-visible buffers of the kernel-owned compute job: mapping before backing. + _client: Option<(mmu::KernelMapping, gem::ObjectRef, fw::types::GpuArray)>, + /// Stream offsets that take the compute engine-state address once the directory exists. + stats_patch: KVec, + /// That address, for compute commands built after boot. + compute_state: u64, +} + +impl G14StartupFence { + fn new(alloc: &mut KernelAllocators, event: event::Event, uat: &mmu::Uat, dev: &AsahiDevice) -> Result { + let mut queue = alloc.private.array_empty::(0x2cc0)?; + let mut positions = alloc.shared.array_empty::(0x2860)?; + let mut pointers = alloc.private.array_empty::(0x2860)?; + let mut scheduler = alloc.private.array_empty::(0x40)?; + let mut timestamps = alloc.shared.array_empty::(0x18)?; + let mut command = alloc.private.array_empty::(0x400)?; + let mut stream = alloc.private.array_empty::(0x400)?; + // The counter is a client VA resolved through the stream's context. The + // kernel VM's lower half is context 0's client range (legacy GPU allocator). + let client = crate::module_parameters::t8112_client_counter.value(); + let counter = alloc.shared.array_empty::(8)?; + // The only context-0 client mapping the J413 graph owns is the low alias of the + // (idle) buffer-manager control page; borrow a cleared word near its end. + let counter_va = if client { IOVA_KERN_GPU_BUFMGR_LOW + 0x3f00 } else { counter.gpu_va().get() }; + // One command-buffer tracking slot (0x100 stride, 0xc8 maintained by firmware) + // whose first word names its own cleared u32 retirement cursor. + let stock = crate::module_parameters::t8112_stock_header.value(); + let mut notifier = alloc.private.array_empty::(0x100)?; + let cursor = alloc.shared.array_empty::(0x90)?; + if stock { + notifier.as_mut_slice()[..8].copy_from_slice(&cursor.gpu_va().get().to_le_bytes()); + crate::pgtable::clean_poc(notifier.as_slice().as_ptr(), 0x100); + } + + let ctx_task = |scheduler: &mut fw::types::GpuArray| { + let task = crate::module_parameters::t8112_task_configuration.value(); + if task != 0 { scheduler.as_mut_slice()[0x26] = (task - 1) as u8; } + }; + let timestamp_va = timestamps.gpu_va().get(); + timestamps.as_mut_slice()[8..16].copy_from_slice(×tamp_va.to_le_bytes()); + let ctx = scheduler.as_mut_slice(); + ctx[..2].copy_from_slice(&u16::MAX.to_le_bytes()); + ctx[5] = 1; + ctx[0x27] = 0xff; + let queue_va = queue.gpu_va().get(); + let q = queue.as_mut_slice(); + for (offset, value) in [(0, positions.gpu_va().get()), (8, pointers.gpu_va().get()), + (0x10, timestamp_va), (0x18, queue_va + 0x90), + (0x7c, scheduler.gpu_va().get())] { + q[offset..offset+8].copy_from_slice(&value.to_le_bytes()); + } + // The driver-owned queue has no owning process. + for offset in [0x2c, 0x48, 0x4c, 0x50] { + q[offset..offset+4].copy_from_slice(&u32::MAX.to_le_bytes()); + } + q[0x30..0x34].copy_from_slice(&4u32.to_le_bytes()); + q[0x4c..0x50].copy_from_slice(&crate::module_parameters::t8112_queue_owner.value().to_le_bytes()); + if crate::module_parameters::t8112_priority_row.value() == 16 { + // Context priority 1 / QoS 1: physical group 2. + q[0x30..0x34].copy_from_slice(&2u32.to_le_bytes()); + q[0x34..0x38].copy_from_slice(&2u32.to_le_bytes()); + q[0x38..0x40].copy_from_slice(&0xffff_0000_0000_0000u64.to_le_bytes()); + q[0x40..0x44].copy_from_slice(&0u32.to_le_bytes()); + q[0x44..0x48].copy_from_slice(&1u32.to_le_bytes()); + } + if let row @ 0..=3 = crate::module_parameters::t8112_priority_row.value() { + // Legacy J413 priority row (fw/workqueue.rs PRIORITY), as J613 extended writes row 2. + let legacy = crate::fw::workqueue::raw::PRIORITY[row as usize]; + q[0x30..0x34].copy_from_slice(&legacy.0.to_le_bytes()); + q[0x34..0x38].copy_from_slice(&legacy.1.to_le_bytes()); + q[0x38..0x40].copy_from_slice(&legacy.2.0.to_le_bytes()); + q[0x40..0x44].copy_from_slice(&legacy.3.to_le_bytes()); + q[0x44..0x48].copy_from_slice(&legacy.4.to_le_bytes()); + q[0x48..0x4c].copy_from_slice(&legacy.5.to_le_bytes()); + } + // Stock leaves the current lane at the all-ones sentinel and the + // firmware assigns it on first activation; the legacy row presets it. + match crate::module_parameters::t8112_queue_lane.value() { + 0 => {} + 1 => q[0x48..0x4c].copy_from_slice(&u32::MAX.to_le_bytes()), + lane => q[0x48..0x4c].copy_from_slice(&(lane - 2).to_le_bytes()), + } + // Host scheduler context +0x26 carries the task-configuration byte. + ctx_task(&mut scheduler); + positions.as_mut_slice()[0x50..0x54].copy_from_slice(&crate::module_parameters::t8112_queue_capacity.value().to_le_bytes()); + + // Keep the shared-event counter separate from the indexed completion stamp. + crate::pgtable::clean_poc(q.as_ptr(), q.len()); + let stamp = u64::from(event.stamp_pointer()); + let stamp_value = event.current().next().raw(); + let stamp_value2 = event.current().next().next().raw(); + // Job order 2: the compute job is the queue's first command and the signal follows. + let swap = crate::module_parameters::t8112_compute_job.value() + && crate::module_parameters::t8112_job_order.value() == 2; + let signal_value = if swap { stamp_value2 } else { stamp_value }; + let data = stream.as_mut_slice(); + data[..4].copy_from_slice(&14u32.to_le_bytes()); + for (offset, value) in [(8, 1u64), (0x10, 1), (0x18, 1), + (0x28, counter_va), (0x30, stamp)] { + data[offset..offset+8].copy_from_slice(&value.to_le_bytes()); + } + data[0x38..0x3c].copy_from_slice(&signal_value.to_le_bytes()); + data[0x4c..0x50].copy_from_slice(&crate::g15::fw::work::op::END.to_le_bytes()); + let cmd_va = command.gpu_va().get(); + let cmd = command.as_mut_slice(); + cmd[..4].copy_from_slice(&crate::module_parameters::t8112_command_type.value().to_le_bytes()); + // Hardware: the type-9 handler clears 0xc8 bytes through the packed u64 at +0xc. + let at = crate::module_parameters::t8112_command_notifier.value() as usize; + if at != 0 { + if at > 0x14 { return Err(EINVAL); } + cmd[at..at + 8].copy_from_slice(¬ifier.gpu_va().get().to_le_bytes()); + } + if stock { + // Type-9 prefix: sequence 0 at +4, context 0 at +0x14, data master at +0x18. + cmd[0x18..0x1c].copy_from_slice(&(G14TrialRoot::signal_engine() as u32).to_le_bytes()); + } + if crate::module_parameters::t8112_completion_record.value() { + // Hardware: retirement stores command +0x40 through the pointer at +0x30, i.e. a + // 0x20-byte acknowledgement record begins at command +0x30. + cmd[0x30..0x38].copy_from_slice(&stamp.to_le_bytes()); + } + cmd[0x1c..0x24].copy_from_slice(&stream.gpu_va().get().to_le_bytes()); + cmd[0x24..0x28].copy_from_slice(&0x80u32.to_le_bytes()); + cmd[0x38..0x40].copy_from_slice(&stamp.to_le_bytes()); + cmd[0x40..0x44].copy_from_slice(&signal_value.to_le_bytes()); + let mut client_job = None; + let mut stats_patch = KVec::new(); + // Optional second command on the same queue: the compute job follows the signal. + let second = crate::module_parameters::t8112_compute_job.value() + && crate::module_parameters::t8112_job_order.value() != 0; + let mut command2 = alloc.private.array_empty::(0x400)?; + let mut stream2 = alloc.private.array_empty::(0x400)?; + let mut tracking2 = alloc.private.array_empty::(0x100)?; + tracking2.as_mut_slice()[..8].copy_from_slice(&(cursor.gpu_va().get() + 4).to_le_bytes()); + let (command2_va, stream2_va, tracking2_va) = + (command2.gpu_va().get(), stream2.gpu_va().get(), tracking2.gpu_va().get()); + if crate::module_parameters::t8112_compute_job.value() { + // Kernel-owned compute job in context 0. Layout: legacy G14G V13_5 RunCompute and + // StartCompute/Timestamp/FinalizeCompute payloads (fw/compute.rs, fw/microseq.rs, + // queue/compute.rs) inside the 26.x wrapper as G15G 26.6.2 carries it + // (m3_compute_layout.rs, m3_compute_sequence.rs encode_extended), at the anchors. + const PREEMPT: usize = 0x10000; // hw/t8112.rs compute_preempt1_size + const CLIENT_VA: u64 = IOVA_KERN_GPU_BUFMGR_LOW + 0x10_0000; + let mut object = gem::new_kernel_object(dev, PREEMPT + 0x4000)?; + let size = object.size(); + use kernel::io::Io; + let map = object.vmap()?; + for off in (0..size).step_by(8) { map.try_write64(0, off)?; } + // CDM control stream: one Stream Terminate block (block type 2 in bits 31:29). + let cdm = PREEMPT + 0x2000; + map.try_write32(0x4000_0000, cdm)?; + let mapping = object.map_at(uat.kernel_lower_vm(), CLIENT_VA, mmu::PROT_GPU_SHARED_RW, false)?; + let queue_va = queue.gpu_va().get(); + let fw_stamp = u64::from(event.fw_stamp_pointer()); + let slot = event.slot(); + let timestamps_va = { + let ts = alloc.shared.array_empty::(0x80)?; + let va = ts.gpu_va().get(); + client_job = Some((object, mapping, ts)); + va + }; + let (cmd, cmd_va, stream_va, tracking_va, stamp_value) = if second { + (command2.as_mut_slice(), command2_va, stream2_va, tracking2_va, if swap { stamp_value } else { stamp_value2 }) + } else { + (&mut *cmd, cmd_va, stream.gpu_va().get(), notifier.gpu_va().get(), stamp_value) + }; + cmd.fill(0); + let put32 = |b: &mut [u8], at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + let put64 = |b: &mut [u8], at: usize, v: u64| b[at..at + 8].copy_from_slice(&v.to_le_bytes()); + let context = crate::module_parameters::t8112_job_context.value(); + put32(cmd, 0, 3); + put64(cmd, 4, u64::from(second)); + put32(cmd, 0xc, context); + put64(cmd, 0x10, tracking_va); + // First register image (+0x18, 0x50 bytes): zero, as the 13.5 G14G path sends it. + // Second image at +0x68 (= 13.5 JobParameters1). + for (at, v) in [(0x00, CLIENT_VA), (0x08, CLIENT_VA + cdm as u64), + (0x10, CLIENT_VA + PREEMPT as u64), (0x18, CLIENT_VA + PREEMPT as u64 + 8), + (0x20, CLIENT_VA + PREEMPT as u64 + 16), (0x28, CLIENT_VA + PREEMPT as u64 + 24), + (0x30, 0x11_0000_0000), (0x38, 0x8c60), (0x58, 1)] { + put64(cmd, 0x68 + at, v); + } + put64(cmd, 0x1e8, stream_va); + put32(cmd, 0x1f0, 0x2c0); + // Auxiliary block: 13.5 JobParameters2 preempt/CDM end in vector B, + // EncoderParams mask in the last control word. + put64(cmd, 0x220, CLIENT_VA); + put64(cmd, 0x228, CLIENT_VA + cdm as u64 + 8); + put32(cmd, 0x270, u32::MAX); + put64(cmd, 0x298, stamp); + put64(cmd, 0x2a0, fw_stamp); + put32(cmd, 0x2a8, stamp_value); + put32(cmd, 0x2b0, slot); + // Tail: timestamp slots B/C name the start/end words. + put64(cmd, 0x2cc, timestamps_va); + put64(cmd, 0x2d4, timestamps_va + 8); + put32(cmd, 0x33c, 1); + match crate::module_parameters::t8112_tail_probe.value() { + // Diagnostic: distinct unmapped addresses in the zero tail words. + 1 => { put64(cmd, 0x2b8, 0xffff_ffa7_0000_2000); put64(cmd, 0x2c4, 0xffff_ffa7_0000_1000); + put64(cmd, 0x2dc, 0xffff_ffa7_0000_3000); put64(cmd, 0x2ec, 0xffff_ffa7_0000_4000); + put64(cmd, 0x304, 0xffff_ffa7_0000_5000); put64(cmd, 0x314, 0xffff_ffa7_0000_6000); } + 2 => for at in [0x18usize, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x60, 0xa8, 0xb0, 0xb8, + 0x200, 0x208, 0x210, 0x218, 0x230, 0x240, 0x250, 0x284, 0x28c, + 0x2e4, 0x2f4, 0x2fc, 0x31c, 0x324, 0x32c, 0x334] { + put64(cmd, at, 0xffff_ffa7_0000_0000 + ((at as u64) << 16)); + }, + // Hardware: the handler clears 0x10 bytes through command +0x334. + 3 => put64(cmd, 0x334, timestamps_va + 0x20), + 4 => { put64(cmd, 0x334, timestamps_va + 0x20); put32(cmd, 0x33c, 0); } + // Seed the dependency latch so the companion lookup is bypassed. + 5 => { put64(cmd, 0x334, timestamps_va + 0x20); put32(cmd, 0x340, 1); } + // Canonical disabled form: +0x33c/+0x334/+0x324/+0x340 all zero. + 6 => put32(cmd, 0x33c, 0), + _ => {} + } + + let data = if second { stream2.as_mut_slice() } else { stream.as_mut_slice() }; + data.fill(0); + put32(data, 0, 11); + put64(data, 0x160, u64::from(second)); + put64(data, 0x04, cmd_va + 0x18); + put64(data, 0x0c, cmd_va + 0x68); + stats_patch.push(0x14, GFP_KERNEL)?; + put64(data, 0x1c, queue_va); + put32(data, 0x24, context); + put32(data, 0x34, slot); + put64(data, 0x3c, cmd_va + 0x1f4); + put64(data, 0x158, cmd_va + 0x340); + for (at, op, selected) in [(0x16c, 0x8000_0003u32, 0x2ccu64), (0x1bc, 3, 0x2d4)] { + put32(data, at, op); + put64(data, at + 0x04, cmd_va + 0x2c4); + put64(data, at + 0x0c, cmd_va + 0x2cc); + put64(data, at + 0x14, cmd_va + selected); + put64(data, at + 0x1c, queue_va); + put64(data, at + 0x2c, cmd_va + 0x314); + put64(data, at + 0x34, cmd_va + 0x264); + } + match crate::module_parameters::t8112_start_probe.value() { + // Diagnostics: unmapped addresses in the start record's private operands. + 1 => { stats_patch.clear(); put64(data, 0x14, 0xffff_ffa7_0014_0000); } + 2 => put64(data, 0x1c, 0xffff_ffa7_001c_0000), + // Legacy StartCompute values the table leaves as descriptor scalars: + // unk_28 = 1, event_generation = queue id, uuid. + 4 => put32(data, 0x28, 1), + 5 => { put32(data, 0x28, 1); put32(data, 0x2c, 1); put32(data, 0x30, 1); } + 3 => { put64(data, 0x04, 0xffff_ffa7_0004_0000); put64(data, 0x0c, 0xffff_ffa7_000c_0000); + put64(data, 0x3c, 0xffff_ffa7_003c_0000); put64(data, 0x158, 0xffff_ffa7_0158_0000); } + _ => {} + } + put32(data, 0x1b8, 0x0080_0000); + let finish = 0x208; + put32(data, finish, 12); + stats_patch.push(finish + 4, GFP_KERNEL)?; + put64(data, finish + 0x0c, queue_va); + put32(data, finish + 0x14, context); + put64(data, finish + 0x18, cmd_va + 0x1f4); + put64(data, finish + 0x2c, fw_stamp); + put32(data, finish + 0x34, stamp_value); + put32(data, finish + 0x5c, (-(finish as i32)) as u32); + put64(data, finish + 0x71, cmd_va + 0x340); + put64(data, finish + 0x79, cmd_va + 0x304); + put32(data, finish + 0x84, 0x4000_0002); + } + crate::pgtable::clean_poc(stream.as_slice().as_ptr(), stream.as_slice().len()); + crate::pgtable::clean_poc(cmd.as_ptr(), cmd.len()); + crate::pgtable::poc_barrier(); + pointers.as_mut_slice()[..8].copy_from_slice(&command.gpu_va().get().to_le_bytes()); + if swap { + pointers.as_mut_slice()[..8].copy_from_slice(&command2_va.to_le_bytes()); + } + if second { + for owner in [&command2, &stream2, &tracking2] { + crate::pgtable::clean_poc(owner.as_slice().as_ptr(), owner.as_slice().len()); + } + crate::pgtable::poc_barrier(); + let next = if swap { command.gpu_va().get() } else { command2_va }; + pointers.as_mut_slice()[8..16].copy_from_slice(&next.to_le_bytes()); + } + + // These allocations are private to this fresh graph. Walk its owned RAM + // tables before publishing anything to the ASC, including both edge pages + // of each suballocation. G14G's upper root takes a 39-bit input. + let root = uat.kernel_window_root(); + let check = |address: u64, len: usize, expected: mmu::Prot| -> Result { + let end = address.checked_add(len as u64 - 1).ok_or(EOVERFLOW)?; + let mut page = address & !(mmu::UAT_PGMSK as u64); + while page <= end { + let entry = crate::g15::uat::read_leaf(root, page & ((1u64 << 39) - 1))? + .ok_or(EFAULT)?; + if entry & 3 != 3 || mmu::Prot::from_pte(entry).leaf_bits() != expected.leaf_bits() { + return Err(EFAULT); + } + page = page.checked_add(mmu::UAT_PGSZ as u64).ok_or(EOVERFLOW)?; + } + Ok(()) + }; + for owner in [&queue, &pointers, &scheduler, &stream, &command] { + check(owner.gpu_va().get(), owner.as_slice().len(), mmu::PROT_FW_PRIV_RW)?; + } + for owner in [&positions, ×tamps] { + check(owner.gpu_va().get(), owner.as_slice().len(), mmu::PROT_FW_SHARED_RW)?; + } + if client { + // The context-0 client tree must already translate the counter page. + let va = counter_va; + let leaf = crate::g15::uat::read_leaf(uat.kernel_lower_root(), va)?.ok_or(ENOENT)?; + if leaf & 3 != 3 { return Err(ENXIO); } + } else { + check(counter.gpu_va().get(), 8, mmu::PROT_FW_SHARED_RW)?; + } + check(stamp, 4, mmu::PROT_FW_SHARED_RW)?; + + let mut owners = KVec::new(); + for owner in [×tamps, &pointers, &scheduler] { + crate::pgtable::clean_poc(owner.as_slice().as_ptr(), owner.as_slice().len()); + } + for owner in [timestamps, pointers, scheduler, command, stream, notifier, cursor, command2, stream2, tracking2] { + owners.push(owner, GFP_KERNEL)?; + } + let _client = client_job.map(|(object, mapping, ts)| (mapping, object, ts)); + Ok(Self { queue, positions, counter, event, expected_stamp: stamp_value, second: second.then_some(stamp_value2), _owners: owners, _client, stats_patch, compute_state: 0 }) + } +} + +/// Command slots for compute work published after boot (the DRM device). They are allocated +/// with the trial queue, before the firmware window's tables are mirrored for the ASC, so every +/// slot lies in a table the firmware already translates. Slots are reused in order. +pub(crate) const J413_POOL: usize = 48; + +pub(crate) struct J413Pool { + commands: fw::types::GpuArray, + streams: fw::types::GpuArray, + tracking: fw::types::GpuArray, + cursors: fw::types::GpuArray, + stamps: fw::types::GpuArray, +} + +/// One compute command from a client, as the 26.x front end hands it over. +pub(crate) struct J413Compute { + pub(crate) context: u32, + pub(crate) sequence: u64, + pub(crate) cdm_base: u64, + pub(crate) cdm_end: u64, + pub(crate) usc_base: u64, + /// Client VA of a 0x10020-byte preemption buffer in the same context (13.5 layout: + /// buffer 1 at +0, buffers 2 to 5 at +0x10000 + 8n). + pub(crate) preempt: u64, +} + +/// Firmware-visible facts of the trial queue that every runtime command names. +#[derive(Copy, Clone)] +pub(crate) struct J413Queue { + pub(crate) queue: u64, + pub(crate) slot: u32, + pub(crate) stamp: u64, + pub(crate) fw_stamp: u64, + pub(crate) compute_state: u64, +} + +impl J413Pool { + pub(crate) fn new(alloc: &mut KernelAllocators) -> Result { + let commands = alloc.private.array_empty::(J413_POOL * 0x400)?; + let streams = alloc.private.array_empty::(J413_POOL * 0x400)?; + let mut tracking = alloc.private.array_empty::(J413_POOL * 0x100)?; + // One 64-byte line per retirement cursor, so no firmware write can reach a neighbour. + let cursors = alloc.shared.array_empty::(J413_POOL * 0x40)?; + let stamps = alloc.shared.array_empty::(J413_POOL * 0x80)?; + // Each tracking slot's first word names its own cleared retirement cursor. + let base = cursors.gpu_va().get(); + for (i, chunk) in tracking.as_mut_slice().chunks_mut(0x100).enumerate() { + chunk[..8].copy_from_slice(&(base + 0x40 * i as u64).to_le_bytes()); + } + crate::pgtable::clean_poc(tracking.as_slice().as_ptr(), tracking.as_slice().len()); + Ok(Self { commands, streams, tracking, cursors, stamps }) + } + + /// Builds slot `i` as the boot compute job is built (26B123 layout with the 13.5 G14G + /// JobParameters payload) and returns the command's firmware VA. + pub(crate) fn encode(&mut self, i: usize, q: &J413Queue, stamp_value: u32, job: &J413Compute) -> Result { + if i >= J413_POOL { return Err(EINVAL); } + let cmd_va = self.commands.gpu_va().get() + (i * 0x400) as u64; + let stream_va = self.streams.gpu_va().get() + (i * 0x400) as u64; + let tracking_va = self.tracking.gpu_va().get() + (i * 0x100) as u64; + let timestamps_va = self.stamps.gpu_va().get() + (i * 0x80) as u64; + // The firmware maintains 0xc8 bytes of the tracking slot; start each use cleared. + let tracking = &mut self.tracking.as_mut_slice()[i * 0x100..(i + 1) * 0x100]; + tracking[8..].fill(0); + crate::pgtable::clean_poc(tracking.as_ptr(), tracking.len()); + + self.stamps.as_mut_slice()[i * 0x80..(i + 1) * 0x80].fill(0); + crate::pgtable::clean_poc(self.stamps.as_slice()[i * 0x80..].as_ptr(), 0x80); + let put32 = |b: &mut [u8], at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + let put64 = |b: &mut [u8], at: usize, v: u64| b[at..at + 8].copy_from_slice(&v.to_le_bytes()); + let cmd = &mut self.commands.as_mut_slice()[i * 0x400..(i + 1) * 0x400]; + cmd.fill(0); + put32(cmd, 0, 3); + put64(cmd, 4, job.sequence); + put32(cmd, 0xc, job.context); + put64(cmd, 0x10, tracking_va); + // 13.5 JobParameters1 at +0x68 (queue/compute.rs values; preempt offsets per 13.5). + let p2 = job.preempt + 0x10000; + for (at, v) in [(0x00, job.preempt), (0x08, job.cdm_base), (0x10, p2), (0x18, p2 + 8), + (0x20, p2 + 16), (0x28, p2 + 24), (0x30, job.usc_base), (0x38, 0x8c60), (0x58, 1)] { + put64(cmd, 0x68 + at, v); + } + put64(cmd, 0x1e8, stream_va); + put32(cmd, 0x1f0, 0x2c0); + // 13.5 JobParameters2: preemption buffer and CDM end; EncoderParams mask. + put64(cmd, 0x220, job.preempt); + put64(cmd, 0x228, job.cdm_end); + put32(cmd, 0x270, u32::MAX); + put64(cmd, 0x298, q.stamp); + put64(cmd, 0x2a0, q.fw_stamp); + put32(cmd, 0x2a8, stamp_value); + put32(cmd, 0x2b0, q.slot); + put64(cmd, 0x2cc, timestamps_va); + put64(cmd, 0x2d4, timestamps_va + 8); + // The baseline's command-local latch object (enabled form, seed 0). + put32(cmd, 0x33c, 1); + put64(cmd, 0x334, timestamps_va + 0x20); + let data = &mut self.streams.as_mut_slice()[i * 0x400..(i + 1) * 0x400]; + data.fill(0); + put32(data, 0, 11); + put64(data, 0x160, job.sequence); + put64(data, 0x04, cmd_va + 0x18); + put64(data, 0x0c, cmd_va + 0x68); + put64(data, 0x14, q.compute_state); + put64(data, 0x1c, q.queue); + put32(data, 0x24, job.context); + put32(data, 0x34, q.slot); + put64(data, 0x3c, cmd_va + 0x1f4); + put64(data, 0x158, cmd_va + 0x340); + for (at, op, selected) in [(0x16c, 0x8000_0003u32, 0x2ccu64), (0x1bc, 3, 0x2d4)] { + put32(data, at, op); + put64(data, at + 0x04, cmd_va + 0x2c4); + put64(data, at + 0x0c, cmd_va + 0x2cc); + put64(data, at + 0x14, cmd_va + selected); + put64(data, at + 0x1c, q.queue); + put64(data, at + 0x2c, cmd_va + 0x314); + put64(data, at + 0x34, cmd_va + 0x264); + } + put32(data, 0x1b8, 0x0080_0000); + let finish = 0x208; + put32(data, finish, 12); + put64(data, finish + 4, q.compute_state); + put64(data, finish + 0x0c, q.queue); + put32(data, finish + 0x14, job.context); + put64(data, finish + 0x18, cmd_va + 0x1f4); + put64(data, finish + 0x2c, q.fw_stamp); + put32(data, finish + 0x34, stamp_value); + put32(data, finish + 0x5c, (-(finish as i32)) as u32); + put64(data, finish + 0x71, cmd_va + 0x340); + put64(data, finish + 0x79, cmd_va + 0x304); + put32(data, finish + 0x84, 0x4000_0002); + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + crate::pgtable::clean_poc(self.commands.as_slice()[i * 0x400..].as_ptr(), 0x400); + crate::pgtable::poc_barrier(); + Ok(cmd_va) + } +} + +impl J413Pool { + /// Retirement: advance slot `i`'s cursor to the expected value the firmware recorded + /// at tracking +0xc, so its retirement scan unlinks the slot from the queue's list. + pub(crate) fn retire(&self, i: usize) -> Result { + if i >= J413_POOL { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::poc_barrier(); + let expected = self.tracking.shared_index(i * 0x100 + 0xc)?.load(Ordering::Acquire); + self.cursors.shared_index(i * 0x40)?.store(expected, Ordering::Release); + crate::pgtable::clean_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); + crate::pgtable::poc_barrier(); + Ok(expected) + } + + /// Whether the firmware still holds slot `i` in a queue's tracking list (+0x94). + pub(crate) fn registered(&self, i: usize) -> Result { + if i >= J413_POOL { return Err(EINVAL); } + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::poc_barrier(); + Ok(self.tracking.shared_index(i * 0x100 + 0x94)?.load(Ordering::Acquire) != 0) + } + + /// Logs slot `i`'s tracking slot, cursor, command head and stream start. + pub(crate) fn dump(&self, dev: &kernel::device::Device, i: usize) { + let w = |a: &fw::types::GpuArray, at: usize| a.shared_index(at).map(|x| x.load(Ordering::Acquire)).unwrap_or(u32::MAX); + crate::pgtable::clean_invalidate_poc(self.tracking.as_slice()[i * 0x100..].as_ptr(), 0x100); + crate::pgtable::clean_invalidate_poc(self.cursors.as_slice()[i * 0x40..].as_ptr(), 0x40); + crate::pgtable::poc_barrier(); + let mut t = [0u32; 0x32]; + for (k, x) in t.iter_mut().enumerate() { *x = w(&self.tracking, i * 0x100 + 4 * k); } + dev_info!(dev, "J413 slot {} cursor={:#x} tracking={:x?}\n", i, w(&self.cursors, i * 0x40), t); + let mut c = [0u32; 8]; + for (k, x) in c.iter_mut().enumerate() { *x = w(&self.commands, i * 0x400 + 4 * k); } + let mut st = [0u32; 8]; + for (k, x) in st.iter_mut().enumerate() { *x = w(&self.streams, i * 0x400 + 4 * k); } + dev_info!(dev, "J413 slot {} command={:x?} stream={:x?} stamp+0x2a8={:#x}\n", i, c, st, w(&self.commands, i * 0x400 + 0x2a8)); + } +} + +impl G14TrialRoot { + /// Logs the queue's work record for `ordinal`. + pub(crate) fn j413_record(&self, ordinal: usize) { + if let Some(job) = &self.startup_fence { + let at = 0x90 + (ordinal & 0x7f) * 0x58; + let q = job.queue.as_slice(); + crate::pgtable::clean_invalidate_poc(q[at..].as_ptr(), 0x58); + crate::pgtable::poc_barrier(); + let mut r = [0u32; 0x16]; + for (k, x) in r.iter_mut().enumerate() { *x = u32::from_le_bytes([q[at+4*k], q[at+4*k+1], q[at+4*k+2], q[at+4*k+3]]); } + dev_info!(self.graph.dev.as_ref(), "J413 work record ordinal {} +{:#x}: {:x?}\n", ordinal & 0x7f, at, r); + } + } + + /// The trial queue's identity for runtime commands, and the stamp value it last reached. + pub(crate) fn j413_queue(&self) -> Result<(J413Queue, event::EventValue)> { + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + if job.compute_state == 0 { return Err(EINVAL); } + Ok((J413Queue { + queue: job.queue.gpu_va().get(), + slot: job.event.slot(), + stamp: u64::from(job.event.stamp_pointer()), + fw_stamp: u64::from(job.event.fw_stamp_pointer()), + compute_state: job.compute_state, + }, job.event.current())) + } + + /// The queue's capacity (position block +0x50). + pub(crate) fn j413_capacity(&self) -> Result { + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + Ok(job.positions.shared_index(0x50)?.load(Ordering::Acquire)) + } + + /// Current queue head, the firmware's retired position and the stamp value. + pub(crate) fn j413_progress(&self) -> Result<(u32, u32, event::EventValue)> { + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + let positions = job.positions.as_slice(); + crate::pgtable::clean_invalidate_poc(positions.as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + Ok((job.positions.shared_index(0x40)?.load(Ordering::Acquire), + job.positions.shared_index(0)?.load(Ordering::Acquire), job.event.current())) + } + + /// Publishes `command` as the queue's next command: pointer, queue head, then the compute + /// submission entry and its producer, as m3_config::submit_queue does on the same ring. + pub(crate) fn j413_publish(&self, command: u64) -> Result { + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + let pointers = &job._owners[1]; + let head = job.positions.shared_index(0x40)?; + let old = head.load(Ordering::Acquire); + let capacity = job.positions.shared_index(0x50)?.load(Ordering::Acquire); + if capacity == 0 || (old % capacity) as usize * 8 + 8 > pointers.as_slice().len() { return Err(EINVAL); } + let at = (old % capacity) as usize * 8; + pointers.shared_index(at)?.store(command as u32, Ordering::Relaxed); + pointers.shared_index(at + 4)?.store((command >> 32) as u32, Ordering::Relaxed); + crate::pgtable::clean_poc(pointers.as_slice()[at..].as_ptr(), 8); + crate::pgtable::poc_barrier(); + let new = (old + 1) % capacity; + head.store(new, Ordering::Release); + crate::pgtable::clean_poc(job.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + let state = &self._channels[2 * Self::signal_ring()]; + let ring = &self._channels[2 * Self::signal_ring() + 1]; + let w = state.shared_index(0x20)?.load(Ordering::Acquire); + if w >= crate::m3::m3_channel_format::SLOTS { return Err(EIO); } + let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(Self::signal_engine() as u32, job.queue.gpu_va().get(), + u16::try_from(new).map_err(|_| EINVAL)?, slot, false).map_err(|_| EINVAL)?; + let base = w as usize * entry.len(); + for (k, word) in entry.chunks(4).enumerate() { + ring.shared_index(base + 4 * k)?.store(u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + } + crate::pgtable::clean_poc(ring.as_slice()[base..].as_ptr(), entry.len()); + crate::pgtable::poc_barrier(); + state.shared_index(0x20)?.store((w + 1) % crate::m3::m3_channel_format::SLOTS, Ordering::Release); + crate::pgtable::clean_poc(state.as_slice().as_ptr(), 0x30); + crate::pgtable::poc_barrier(); + Ok(new) + } + + /// Logs the compute submission ring's index words, its last entries and the position block. + pub(crate) fn j413_rings(&self) -> Result { + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + let state = &self._channels[2 * Self::signal_ring()]; + let ring = &self._channels[2 * Self::signal_ring() + 1]; + let w = |a: &fw::types::GpuArray, at: usize| a.shared_index(at).map(|x| x.load(Ordering::Acquire)).unwrap_or(u32::MAX); + let idx: [u32; 12] = core::array::from_fn(|i| w(state, 4 * i)); + let pos: [u32; 24] = core::array::from_fn(|i| w(&job.positions, 4 * i)); + dev_info!(self.graph.dev.as_ref(), "J413 ring index={:x?} positions={:x?}\n", idx, pos); + for e in [254usize, 255, 0, 1] { + let words: [u32; 6] = core::array::from_fn(|i| w(ring, e * 0x18 + 4 * i)); + dev_info!(self.graph.dev.as_ref(), "J413 ring entry {} {:x?}\n", e, words); + } + Ok(()) + } + + /// Logs the last `count` firmware trace records (already consumed or not). + pub(crate) fn j413_trace_tail(&self, count: u32) -> Result { + let state = &self._channels[2 * 15]; + let ring = &self._channels[2 * 15 + 1]; + let write = state.shared_index(0x20)?.load(Ordering::Acquire); + if write >= 512 { return Err(EIO); } + for k in (1..=count.min(511)).rev() { + let at = (write + 512 - k) % 512; + let mut words = [0u32; 12]; + for (i, word) in words.iter_mut().enumerate() { + *word = ring.shared_index(at as usize * 0x48 + 4 * i)?.load(Ordering::Acquire); + } + dev_info!(self.graph.dev.as_ref(), "J413 trace[{}] {:x?}\n", at, words); + } + Ok(()) + } + + /// Diagnostic: one submission entry naming the current queue head (no new command). + pub(crate) fn j413_publish_entry(&self) -> Result { + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + let head = job.positions.shared_index(0x40)?.load(Ordering::Acquire); + let state = &self._channels[2 * Self::signal_ring()]; + let ring = &self._channels[2 * Self::signal_ring() + 1]; + let w = state.shared_index(0x20)?.load(Ordering::Acquire); + if w >= crate::m3::m3_channel_format::SLOTS { return Err(EIO); } + let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; + let entry = crate::m3::submission_entry(Self::signal_engine() as u32, job.queue.gpu_va().get(), + u16::try_from(head).map_err(|_| EINVAL)?, slot, false).map_err(|_| EINVAL)?; + let base = w as usize * entry.len(); + for (k, word) in entry.chunks(4).enumerate() { + ring.shared_index(base + 4 * k)?.store(u32::from_le_bytes([word[0], word[1], word[2], word[3]]), Ordering::Relaxed); + } + crate::pgtable::clean_poc(ring.as_slice()[base..].as_ptr(), entry.len()); + crate::pgtable::poc_barrier(); + state.shared_index(0x20)?.store((w + 1) % crate::m3::m3_channel_format::SLOTS, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// Kick message for the trial queue's submission ring. + pub(crate) fn j413_kick() -> u64 { + (0x83u64 << 48) | (4 * Self::signal_group() + Self::signal_engine()) as u64 + } + + pub(crate) fn publish_startup_fence(&self, operating_point: u32) -> Result { + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + // This trial ring starts empty. Generation one holds power and generation + // two permits idle again. Verify the hold before publishing either index. + let index = operating_point & 0xf; + if operating_point & 0x10 != 0 || index == 0 || index > self.graph.dyncfg.pwr.perf_max_pstate + || self.idle_progress()? != [Self::control_base() + 1; 3] + || self.idle_acknowledgement()? != self.globals.as_ref().ok_or(EINVAL)?.shared_index(0xe40)?.load(Ordering::Acquire) { + return Err(EAGAIN); + } + let service = self.command_service()?; + if crate::module_parameters::t8112_command_service.value() && service.1 != 0 + || crate::module_parameters::t8112_service_stage.value() && service.0 != 2 { + return Err(EAGAIN); + } + let producer = self._channels[2 * Self::signal_ring()].shared_index(0x20)?; + let head = job.positions.shared_index(0x40)?; + if self.status.shared_index(0x14)?.load(Ordering::Acquire) != 1 || + producer.load(Ordering::Acquire) != Self::ring_index(0) || head.load(Ordering::Acquire) != 0 { + return Err(EAGAIN); + } + crate::pgtable::poc_barrier(); + head.store(1, Ordering::Release); + crate::pgtable::poc_barrier(); + producer.store(Self::ring_index(1), Ordering::Release); + crate::pgtable::poc_barrier(); + Ok(()) + } + + /// Publish the queue's second command (the compute job) after the signal has retired. + pub(crate) fn publish_second(&self) -> Result { + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + if job.second.is_none() { return Err(EINVAL); } + let producer = self._channels[2 * Self::signal_ring()].shared_index(0x20)?; + let head = job.positions.shared_index(0x40)?; + if producer.load(Ordering::Acquire) != Self::ring_index(1) || head.load(Ordering::Acquire) != 1 { return Err(EAGAIN); } + crate::pgtable::poc_barrier(); + head.store(2, Ordering::Release); + crate::pgtable::poc_barrier(); + producer.store(Self::ring_index(2), Ordering::Release); + crate::pgtable::poc_barrier(); + Ok(()) + } + + pub(crate) fn second_complete(&self) -> Result { + self.drain_statistics()?; + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + Ok(job.positions.shared_index(0)?.load(Ordering::Acquire) == 2 + && Some(job.event.current().raw()) == job.second) + } + + pub(crate) fn startup_fence_complete(&self) -> Result { + self.drain_statistics()?; + let job = self.startup_fence.as_ref().ok_or(EINVAL)?; + Ok(self._channels[2 * Self::signal_ring()].shared_index(0)?.load(Ordering::Acquire) == Self::ring_index(1) + && job.positions.shared_index(0x30)?.load(Ordering::Acquire) == 1 + && job.positions.shared_index(0)?.load(Ordering::Acquire) == 1 + && (crate::module_parameters::t8112_client_counter.value() + || (crate::module_parameters::t8112_compute_job.value() + && (job.second.is_none() || crate::module_parameters::t8112_job_order.value() == 2)) + || job.counter.shared_index(0)?.load(Ordering::Acquire) == 1) + && job.event.current().raw() == job.expected_stamp) + } + + /// Consume everything the firmware has published on the statistics ring, as the + /// J613 drain does, so its producer never waits for space. Records are not kept. + pub(crate) fn drain_statistics(&self) -> Result { + if !crate::module_parameters::t8112_drain_statistics.value() || self._channels.len() < 34 { return Ok(()); } + let state = &self._channels[2 * 16]; + let write = state.shared_index(0x20)?.load(Ordering::Acquire); + let read = state.shared_index(0)?; + if write < 256 && read.load(Ordering::Acquire) != write { + read.store(write, Ordering::Release); + crate::pgtable::poc_barrier(); + } + // Firmware-to-host event ring (256 records of 0x38 bytes): the firmware waits for space when it is + // full, and host consumer advancement is the acknowledgement. Completion is followed + // through the queues' position blocks, so the records are only counted and the + // first few logged. + static EVENTS: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); + let state = &self._channels[2 * 13]; + let ring = &self._channels[2 * 13 + 1]; + let write = state.shared_index(0x20)?.load(Ordering::Acquire); + let read = state.shared_index(0)?; + let mut at = read.load(Ordering::Acquire); + if write < 256 && at < 256 && at != write { + while at != write { + if EVENTS.fetch_add(1, Ordering::Relaxed) < 4 { + let words: [u32; 6] = core::array::from_fn(|i| + ring.shared_index(at as usize * 0x38 + 4 * i).map(|w| w.load(Ordering::Acquire)).unwrap_or(u32::MAX)); + dev_info!(self.graph.dev.as_ref(), "G14G event[{}] {:x?}\n", at, words); + } + at = (at + 1) % 256; + } + read.store(at, Ordering::Release); + crate::pgtable::poc_barrier(); + } + // Firmware log rings (one 256-record ring per log thread, state blocks 0x30 apart): + // consumed the same way so they cannot fill on a long-running device. + let state = &self._channels[2 * 14]; + for thread in 0..crate::m3::m3_init_26::LOG_THREADS { + let (Ok(write), Ok(read)) = (state.shared_index(thread * 0x30 + 0x20), state.shared_index(thread * 0x30)) + else { break }; + let write = write.load(Ordering::Acquire); + if write < 256 && read.load(Ordering::Acquire) != write { + read.store(write, Ordering::Release); + crate::pgtable::poc_barrier(); + } + } + // Firmware trace ring. Hardware uses the J613 geometry (512 records of 0x48 bytes), + // not 256 x 0x90. Consume in order; print the first records. + static SHOWN: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); + let state = &self._channels[2 * 15]; + let ring = &self._channels[2 * 15 + 1]; + let write = state.shared_index(0x20)?.load(Ordering::Acquire); + let read = state.shared_index(0)?; + let mut at = read.load(Ordering::Acquire); + if write < 512 && at < 512 { + while at != write { + if SHOWN.fetch_add(1, Ordering::Relaxed) < crate::module_parameters::t8112_trace_show.value() { + let mut words = [0u32; 12]; + for (i, word) in words.iter_mut().enumerate() { + *word = ring.shared_index(at as usize * 0x48 + 4 * i)?.load(Ordering::Acquire); + } + dev_info!(self.graph.dev.as_ref(), "G14G trace[{}] {:x?}\n", at, words); + } + at = (at + 1) % 512; + } + read.store(at, Ordering::Release); + crate::pgtable::poc_barrier(); + } + Ok(()) + } + + /// Shared status +0x10: non-zero while the firmware reports itself powered/running. + pub(crate) fn firmware_running(&self) -> Result { + Ok(self.status.shared_index(0x10)?.load(Ordering::Acquire)) + } + + /// Command-service state: (powered stage, pending installation request). + /// Engine entries may be published only at (2, 0). + pub(crate) fn command_service(&self) -> Result<(u32, u32)> { + Ok((self.control.shared_index(0x4c00)?.load(Ordering::Acquire), + self.control.shared_index(0x4c24)?.load(Ordering::Acquire))) + } + + pub(crate) fn idle_acknowledgement(&self) -> Result { + Ok(self.control.shared_index(0xe838)?.load(Ordering::Acquire)) + } + + pub(crate) fn idle_progress(&self) -> Result<[u32; 3]> { + self.drain_statistics()?; + let ring = &self._channels[2 * crate::m3::DEVICE_CONTROL]; + let read = |offset| ring.shared_index(offset).map(|v| v.load(Ordering::Acquire)); + Ok([read(0)?, read(0x10)?, read(0x20)?]) + } + + /// Data master of the kernel-owned signal at priority zero: tiler, fragment or compute. + pub(crate) fn signal_engine() -> usize { + crate::module_parameters::t8112_command_engine.value().min(2) as usize + } + + /// Priority group of the signal. The stock layout leaves the group to the configured priority; the + /// legacy J413 and J613 queues submit in the group their priority row names. + pub(crate) fn signal_group() -> usize { + match crate::module_parameters::t8112_priority_row.value() { p @ 0..=3 => p as usize, 16 => 2, _ => 0 } + } + + /// First entry of the trial ring (diagnostic; 0 is the stock empty ring). + pub(crate) fn ring_start() -> u32 { + crate::module_parameters::t8112_ring_start.value() % crate::m3::m3_channel_format::SLOTS + } + + /// Ring index `n` publications after the start. + pub(crate) fn ring_index(n: u32) -> u32 { + (Self::ring_start() + n) % crate::m3::m3_channel_format::SLOTS + } + + /// Index of the signal's submission descriptor among the twelve. + pub(crate) fn signal_ring() -> usize { + 3 * Self::signal_group() + Self::signal_engine() + } + + /// Control records that precede the two idle-policy records on the trial ring: + /// the J613 extended opening record, then its six engine-class registrations. + pub(crate) fn control_base() -> u32 { + match crate::module_parameters::t8112_engine_classes.value() { + 0 => 0, + 1 => 1, + _ => 1 + crate::m3::ENGINE_CLASSES, + } + } + + /// Publish the next pre-encoded engine-class registration. The opening record + /// and every earlier registration must already have retired. + pub(crate) fn publish_engine_class(&self, ordinal: u32) -> Result { + if ordinal >= crate::m3::ENGINE_CLASSES || Self::control_base() != 1 + crate::m3::ENGINE_CLASSES { + return Err(EINVAL); + } + let producer = self._channels[2 * crate::m3::DEVICE_CONTROL].shared_index(0x20)?; + if self.status.shared_index(0x14)?.load(Ordering::Acquire) != 1 || + crate::m3::idle_cursor(self.idle_progress()?).map_err(|_| EBUSY)? != 1 + ordinal { + return Err(EAGAIN); + } + crate::pgtable::poc_barrier(); + producer.store(ordinal + 2, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok(ordinal + 2) + } + + /// Publish one of two pre-encoded policy records on a fresh idle trial ring. + /// Returns the ring cursor and the counted generation the firmware acknowledges. + /// As in the J613 extended control path, the generation follows the larger of + /// the host's last publication and the firmware's consumed count. + pub(crate) fn publish_idle_policy(&self, allow_off: bool) -> Result<(u32, u32)> { + let cursor = Self::control_base() + u32::from(allow_off); + let host = self.globals.as_ref().ok_or(EINVAL)?.shared_index(0xe40)?; + let firmware = self.idle_acknowledgement()?; + let producer = self._channels[2 * crate::m3::DEVICE_CONTROL].shared_index(0x20)?; + if self.status.shared_index(0x14)?.load(Ordering::Acquire) != 1 || + crate::m3::idle_cursor(self.idle_progress()?).map_err(|_| EBUSY)? != cursor { + return Err(EAGAIN); + } + let action = crate::m3::Action::Idle { enabled: allow_off }; + let generation = action.generation(host.load(Ordering::Acquire), firmware).map_err(|_| EOVERFLOW)?; + host.store(generation, Ordering::Release); + crate::pgtable::poc_barrier(); + producer.store(cursor + 1, Ordering::Release); + crate::pgtable::poc_barrier(); + Ok((cursor + 1, generation)) + } + + /// After the ASC has stopped: receive-ring cursors, the first records of each + /// ring and the firmware's own log text. Layout shared with the J613 drain. + pub(crate) fn report_stopped_receive(&self) { + use crate::m3::m3_init_26 as extended; + let dev = self.graph.dev.as_ref(); + if self._channels.len() < 34 { return; } + // The payload owner follows other retained owners: find it by its directory address. + let payload = self.directory.as_ref().and_then(|dir| dir.as_slice().get(0x200..0x208)) + .and_then(|b| <[u8; 8]>::try_from(b).ok()).map(u64::from_le_bytes) + .and_then(|va| self._channels.iter().find(|a| a.gpu_va().get() == va)); + let word = |b: &[u8], at: usize| u32::from_le_bytes([b[at], b[at+1], b[at+2], b[at+3]]); + for (name, channel, capacity, threads) in [("event", 13usize, 256usize, 1usize), + ("log", 14, 256, extended::LOG_THREADS), ("trace", 15, 512, 1), ("stats", 16, 256, 1)] { + let state = self._channels[2 * channel].as_slice(); + let ring = self._channels[2 * channel + 1].as_slice(); + for thread in 0..threads { + let write = word(state, thread * 0x30 + 0x20) as usize; + if write == 0 || write >= capacity { continue; } + dev_info!(dev, "G14G receive {}[{}] read={} target={} write={}\n", name, thread, + word(state, thread * 0x30), word(state, thread * 0x30 + 0x10), write); + for index in 0..write.min(if channel == 14 { 24 } else { 6 }) { + let at = (thread * capacity + index) * extended::RX_BYTES; + let Some(record) = ring.get(at..at + extended::RX_BYTES) else { continue; }; + if channel == 14 { + let slot = word(record, 8); + dev_info!(dev, "G14G receive log record {}: {:02x?}\n", index, &record[..0x20]); + let Ok(offset) = crate::m3::payload_offset(thread, slot) else { continue; }; + let Some(text) = payload.and_then(|p| p.as_slice().get(offset + 0x10..offset + 0xd8)) + else { continue; }; + let len = text.iter().position(|v| *v == 0).unwrap_or(text.len()); + dev_info!(dev, "G14G firmware log[{}]: {}\n", thread, + core::str::from_utf8(&text[..len]).unwrap_or("")); + } else { + dev_info!(dev, "G14G receive {} record {}: {:02x?}\n", name, index, record); + } + } + } + } + } + + /// Only the shared ring and the hardware register are sampled while the ASC runs. + pub(crate) fn report_power_progress(&self, stage: &str, operating_point: u32) -> Result { + let globals = self.globals.as_ref().ok_or(EINVAL)?; + let ring = &self._channels[2 * crate::m3::DEVICE_CONTROL]; + let read = |a: &fw::types::GpuArray, offset| { + a.shared_index(offset).map(|v| v.load(Ordering::Acquire)) + }; + dev_info!(self.graph.dev.as_ref(), + "G14G {} Fender={:#x} request_pending={} index={} ready={} requested={} assertions host={} fw={} control consumer={} target={} producer={}\n", + stage, operating_point, (operating_point >> 4) & 1, operating_point & 0xf, + read(&self.status, 0x14)?, read(&self.status, 0x18)?, + read(globals, 0xe40)?, read(&self.control, 0xe838)?, + read(ring, 0)?, read(ring, 0x10)?, read(ring, 0x20)?); + dev_info!(self.graph.dev.as_ref(), "G14G {} command service (stage, request)={:?} neighbours={:x?}\n", + stage, self.command_service()?, + [read(&self.control, 0x4bf8)?, read(&self.control, 0x4bfc)?, read(&self.control, 0x4c04)?, + read(&self.control, 0x4c08)?, read(&self.control, 0x4c20)?, read(&self.control, 0x4c28)?]); + Ok(()) + } + + /// Audit immutable host inputs after the firmware has published ready. The caller + /// checks the context-0 upper root and supplies the walk of its installed window. + pub(crate) fn audit_power_inputs(&self, leaf: impl Fn(u64) -> Result, pa_mask: u64) -> Result { + use crate::m3::m3_mmio_26::{TABLE_OFFSET, RECORD_BYTES}; + use crate::g17::fw::m5::initdata as abi; + let word = |a: &fw::types::GpuArray, n| a.shared_index(n).map(|v| v.load(Ordering::Acquire)); + let pair = |a: &fw::types::GpuArray, n| -> Result { + Ok(u64::from(word(a, n)?) | (u64::from(word(a, n + 4)?) << 32)) + }; + let dir = self.directory.as_ref().ok_or(EINVAL)?; + let address = pair(dir, 0)?; + let hw = self._channels.iter().find(|a| a.gpu_va().get() == address).ok_or(EFAULT)?; + let list = self.boot_page.as_ref().ok_or(EINVAL)?; + dev_info!(self.graph.dev.as_ref(), + "G14G power path perf={} cre={} init_list_first_type={}\n", + word(hw, 0xfc0)?, word(hw, 0x26b8)?, word(list, 0x10)?); + dev_info!(self.graph.dev.as_ref(), "G14G slow={} event_completion={} cre_companion={}\n", + word(hw, 0xfc8)?, word(hw, 0x1054)?, word(hw, 0x26bc)?); + let audit_owner = |owner: &fw::types::GpuArray| -> Result { + let va = owner.gpu_va().get(); + let end = va + owner.as_slice().len() as u64 - 1; + let mut page = va & !(mmu::UAT_PGMSK as u64); + while page <= end { + let installed = leaf(page)?; + let expected = crate::g15::uat::read_leaf(self.graph.uat.kernel_window_root(), + page & ((1 << 39) - 1))?.ok_or(EFAULT)?; + if installed != expected || installed & 3 != 3 { return Err(EFAULT); } + page += mmu::UAT_PGSZ as u64; + } + Ok(()) + }; + audit_owner(dir)?; + audit_owner(hw)?; + if crate::module_parameters::t8112_power_filter.value() { + let controller = self.controller.as_ref().ok_or(EINVAL)?; + // The directory's immutable controller pointer is packed at an odd offset. + let target = dir.as_slice().get(0x485..0x48d).ok_or(EINVAL)?; + if u64::from_le_bytes(target.try_into().map_err(|_| EINVAL)?) != controller.gpu_va().get() { + return Err(EFAULT); + } + audit_owner(controller)?; + let sample_ticks = word(controller, 4)?; + let reference_ticks = word(controller, 8)?; + let samples = word(controller, 0xad8)?; + let filter_ticks = pair(controller, 0xae0)?; + let pwr = &self.graph.dyncfg.pwr; + if sample_ticks == 0 || sample_ticks != pwr.pwr_sample_period_aic_clks || + reference_ticks != sample_ticks || samples == 0 || + filter_ticks != u64::from(reference_ticks) * u64::from(samples) { + return Err(EINVAL); + } + dev_info!(self.graph.dev.as_ref(), + "G14G sampling controller bytes={:#x} period={} reference={} filter_samples={} filter_ticks={} counter_mode={}\n", + controller.as_slice().len(), sample_ticks, reference_ticks, samples, + filter_ticks, word(controller, 0x6ac8)?); + // These are firmware statistics outputs. Verify the published pointers and every + // backing page independently of whether the firmware has produced any records. + for (at, size) in [(0x1f0, 0x30), (0x1f8, 0x4800)] { + let va = pair(dir, at)?; + let owner = self._channels.iter().find(|a| a.gpu_va().get() == va).ok_or(EFAULT)?; + if owner.as_slice().len() != size { return Err(EINVAL); } + audit_owner(owner)?; + dev_info!(self.graph.dev.as_ref(), + "G14G statistics directory={:#x} bytes={:#x} mapping verified\n", at, size); + } + } + for slot in 0..60 { + let at = TABLE_OFFSET + RECORD_BYTES * slot; + let physical = pair(hw, at)?; + let va = pair(hw, at + 8)?; + let bytes = word(hw, at + 16)?; + let scratch = self.slot_ram.iter().find(|ram| ram.slot == slot); + if let Some(ram) = scratch { + if physical != ram.ram.physical() || va != ram.mappings[0].iova() + || (bytes as usize).next_multiple_of(mmu::UAT_PGSZ) != ram.initial.len() + || word(hw, at + 20)? != bytes || pair(hw, at + 32)? != (if G14SlotRam::readback(slot) { 0 } else { 2 }) { + return Err(EFAULT); + } + } + if va == 0 && bytes == 0 && physical == 0 { + if [0,1,3,8,9,10,12,17,31,32,33,34,37,40,44].contains(&slot) { + dev_info!(self.graph.dev.as_ref(), "G14G audit slot={} absent\n", slot); + } + continue; + } + if bytes == 0 || va == 0 { return Err(EINVAL); } + dev_info!(self.graph.dev.as_ref(), "G14G audit slot={} descriptor_pa={:#x} va={:#x} bytes={:#x} requested={:#x} mode={}\n", + slot, physical, va, bytes, word(hw, at + 20)?, pair(hw, at + 32)?); + let mut page = va & !(mmu::UAT_PGMSK as u64); + let end = va.checked_add(bytes.into()).ok_or(EOVERFLOW)?; + while page < end { + let pte = leaf(page)?; + let bits = mmu::Prot::from_pte(pte).leaf_bits(); + if let Some(ram) = scratch { + let (expected, prot) = ram.backing((page - va) as usize); + if pte & 3 != 3 || pte & pa_mask != expected || bits != prot.leaf_bits() { + return Err(EFAULT); + } + } + let access = if pte & 3 != 3 { "invalid" } + else if bits == mmu::PROT_FW_MMIO_RW.leaf_bits() { "RW" } + else if bits == mmu::PROT_FW_MMIO_RO.leaf_bits() { "RO" } + else if bits == mmu::PROT_FW_SHARED_RW.leaf_bits() { "RAM-RW" } + else if bits == mmu::PROT_FW_SHARED_RO.leaf_bits() { "RAM-RO" } + else { "other" }; + dev_info!(self.graph.dev.as_ref(), "G14G audit leaf slot={} page={:#x} pte={:#x} pa={:#x} access={}\n", + slot, page, pte, pte & pa_mask, access); + page += mmu::UAT_PGSZ as u64; + } + } + dev_info!(self.graph.dev.as_ref(), "G14G audit OPP ceiling={} hardware={:#x}\n", word(hw,0x10e0)?, address); + if crate::module_parameters::t8112_power_curve.value() { + let mut bits = [0u32; 16]; + for (i, value) in bits.iter_mut().enumerate() { + *value = word(hw, abi::COMMON26_HW_PERF_RELATIVE_A + 4*i)?; + } + let ceiling = word(hw, 0x10e0)? as usize; + if !(1..16).contains(&ceiling) || bits[0] != 0 || + bits[ceiling] != 100.0f32.to_bits() || + bits[..=ceiling].windows(2).any(|s| s[0] >= s[1]) || + bits[ceiling+1..].iter().any(|&x| x != 0) { return Err(EINVAL); } + dev_info!(self.graph.dev.as_ref(), "G14G calibrated power curve h={} words={:x?} alarm_fields={}\n", + ceiling, bits, crate::module_parameters::t8112_alarm_fields.value()); + } + if crate::module_parameters::t8112_power_filter.value() { + let pwr = &self.graph.dyncfg.pwr; + let base = pwr.perf_base_pstate as usize; + let top = pwr.perf_max_pstate as usize; + let mut frequency = [0u32; 16]; + for (i, value) in frequency.iter_mut().enumerate() { + *value = word(hw, abi::COMMON26_HW_PERF_RELATIVE_B + 4*i)?; + } + if top >= frequency.len() || base >= top + || frequency[..=base].iter().any(|&bits| bits != 0) + || frequency[base..=top].windows(2).any(|v| v[0] >= v[1]) + || frequency[top] != 100.0f32.to_bits() + || frequency[top+1..].iter().any(|&bits| bits != 0) { + return Err(EINVAL); + } + dev_info!(self.graph.dev.as_ref(), "G14G calibrated frequency curve base={} top={} bits={:x?}\n", + base, top, frequency); + } + for i in 0..abi::COMMON26_HW_PERF_ROWS { + let row = i * abi::COMMON26_HW_PERF_ROW_STRIDE; + let core = abi::COMMON26_HW_PERF_CORE_VOLTAGE + row; + let sram = abi::COMMON26_HW_PERF_SRAM_VOLTAGE + row; + let mv = word(hw,core)?; + let sv = word(hw,sram)?; + let mut equal = true; + for lane in 1..abi::COMMON26_HW_PERF_LANES { + equal &= word(hw, core+4*lane)? == mv && word(hw, sram+4*lane)? == sv; + } + dev_info!(self.graph.dev.as_ref(), "G14G audit OPP row={} MHz={} mV={} SRAM_mV={} lanes_equal={}\n", + i, word(hw, abi::COMMON26_HW_PERF_FREQUENCY + 4*i)?, mv, sv, equal); + } + Ok(()) + } + + /// The ASC has stopped and the host has not modified these records since publication. + pub(crate) fn report_stopped_power(&self) -> Result { + for ram in &self.slot_ram { + ram.report_stopped(&self.graph)?; + } + let directory = self.directory.as_ref().ok_or(EINVAL)?; + let controller = self.controller.as_ref().ok_or(EINVAL)?; + let read = |a: &fw::types::GpuArray, offset| -> Result { + let word = a.shared_index(offset)?; + crate::pgtable::clean_invalidate_poc(word.as_ptr().cast(), 4); + crate::pgtable::poc_barrier(); + Ok(word.load(Ordering::Acquire)) + }; + dev_info!(self.graph.dev.as_ref(), + "G14G stopped power request_marker={} source_states=[{},{}] selector={} current={} input={} power_up_count={}\n", + read(directory, 0x330)?, read(controller, 0x2c)?, read(controller, 0x30)?, + read(controller, 0x34)?, read(controller, 0x38)?, read(controller, 0xa4)?, + read(controller, 0x6bd4)?); + if crate::module_parameters::t8112_power_filter.value() { + dev_info!(self.graph.dev.as_ref(), + "G14G stopped controller sample={} budget={} peak_state={} average_state={} effective={}\n", + read(controller, 0x218)?, read(controller, 0xacc)?, read(controller, 0xb00)?, + read(controller, 0x2a64)?, read(controller, 0x50)?); + dev_info!(self.graph.dev.as_ref(), + "G14G thermal at stop active={} temperature_cc={} target_cc={} effort_scale_bits={:#x} request={}\n", + read(controller, 0x2270)?, read(controller, 0x2274)?, read(controller, 0x22d4)?, + read(controller, 0x22b0)?, read(controller, 0x2308)?); + dev_info!(self.graph.dev.as_ref(), + "G14G stopped demand deadline={} perf={} se={} pmu_limit={}\n", + read(controller, 0x2220)?, read(controller, 0xbd0)?, read(controller, 0x2bf4)?, + read(controller, 0x2cb0)?); + } + Ok(()) + } + + /// Discriminators for a parked job. Safe while the ASC runs: host cache + /// lines are refreshed before each read and nothing is written. + /// Firmware-visible addresses of the trial job's host objects, for the private scan. + pub(crate) fn job_anchors(&self) -> KVec<(u64, &'static str)> { + let mut v = KVec::new(); + if let Some(job) = &self.startup_fence { + let q = job.queue.gpu_va().get(); + for item in [(q, "queue"), (q + 0x90, "records"), (q + 0xe8, "record1"), + (job._owners[2].gpu_va().get(), "scheduler"), + (job._owners[3].gpu_va().get(), "command")] { + let _ = v.push(item, GFP_KERNEL); + } + } + v + } + + pub(crate) fn report_job_gates(&self, stage: &str) -> Result { + let dev = self.graph.dev.as_ref(); + let read = |a: &fw::types::GpuArray, offset: usize| -> Result { + let word = a.shared_index(offset)?; + crate::pgtable::clean_invalidate_poc(word.as_ptr().cast(), 4); + crate::pgtable::poc_barrier(); + Ok(word.load(Ordering::Acquire)) + }; + if let Some(job) = self.startup_fence.as_ref() { + for record in [0x90usize, 0xe8, 0x140] { + let q = &job.queue; + dev_info!(dev, "G14G {} work record +{:#x}: state={} flags={:#x} command={:#x}{:08x} cursor={:#x}{:08x} mask={:#x} token={:#x}{:08x}/{:#x}\n", + stage, record, read(q, record)?, read(q, record + 4)?, + read(q, record + 0x14)?, read(q, record + 0x10)?, + read(q, record + 0x34)?, read(q, record + 0x30)?, read(q, record + 0x40)?, + read(q, record + 0x4c)?, read(q, record + 0x48)?, read(q, record + 0x50)?); + } + if let Some((_, _, ts)) = job._client.as_ref() { + dev_info!(dev, "G14G {} latch=[{}, {}, {:#x}, {:#x}] queue group={}/{} sub={} lane={:#x}\n", stage, + read(ts, 0x20)?, read(ts, 0x24)?, read(ts, 0x28)?, read(ts, 0x2c)?, + read(&job.queue, 0x30)?, read(&job.queue, 0x34)?, read(&job.queue, 0x44)?, read(&job.queue, 0x48)?); + } + } + if let Some(c) = self.controller.as_ref() { + dev_info!(dev, "G14G {} controller achieved={} effective={} sample={} zones={} average={} ticks={} hist=[{:#x}, {:#x}] override={} S.zones={} S.pending={}\n", + stage, read(c, 0x38)?, read(c, 0x50)?, read(c, 0x218)?, read(c, 0x28e8)?, read(c, 0x2a64)?, + read(c, 0x2a2c)?, read(c, 0x2a58)?, read(c, 0x2a5c)?, read(c, 0x2a68)?, + read(&self.power, 0x0c)?, read(&self.power, 0x08)?); + let stats = &self._channels[2 * 16]; + dev_info!(dev, "G14G {} live temperature_cc={} power_ups={} stats read={} write={} events write={}\n", + stage, read(c, 0x2274)?, read(c, 0x6bd4)?, read(stats, 0)?, read(stats, 0x20)?, + read(&self._channels[2 * 13], 0x20)?); + } + Ok(()) + } + + pub(crate) fn report_stopped_fence(&self) { + if let Some(job) = &self.startup_fence { + let read = |buf: &fw::types::GpuArray, at: usize| { + let b = buf.as_slice(); + u32::from_le_bytes([b[at], b[at+1], b[at+2], b[at+3]]) + }; + let q = job.queue.as_slice(); + crate::pgtable::clean_invalidate_poc(q.as_ptr(), 0x90); + crate::pgtable::poc_barrier(); + dev_info!(self.graph.dev.as_ref(), "G14G queue mapping check passed; stamp slot={} TX producer={} queue producer={} accepted={} first={} retired={}\n", + job.event.slot(), read(&self._channels[2 * Self::signal_ring()], 0x20), read(&job.positions, 0x40), + read(&job.queue, 0x28), read(&job.queue, 0x58), read(&job.positions, 0)); + dev_info!(self.graph.dev.as_ref(), "G14G first fence channel read={} queue read={} counter={} stamp={} events={}\n", + read(&self._channels[2 * Self::signal_ring()], 0), read(&job.positions, 0x30), + u64::from(read(&job.counter, 0)) | (u64::from(read(&job.counter, 4)) << 32), + job.event.current().raw(), + read(&self._channels[26], 0x20)); + if read(&self._channels[26], 0x20) != 0 { + let event = &self._channels[27].as_slice()[..0x48]; + dev_info!(self.graph.dev.as_ref(), "G14G first firmware event {:02x?}\n", event); + } + // Exact bytes sent, and the queue state as the stopped firmware left it. + // Owners are [timestamps, pointers, scheduler, command, stream]. + let dev = self.graph.dev.as_ref(); + let dump = |name: &str, va: u64, bytes: &[u8]| { + for (row, chunk) in bytes.chunks(32).enumerate() { + if chunk.iter().any(|v| *v != 0) { + dev_info!(dev, "G14G sent {} {:#x}+{:#05x}: {:02x?}\n", name, va, row * 32, chunk); + } + } + }; + for owner in job._owners.iter() { + crate::pgtable::clean_invalidate_poc(owner.as_slice().as_ptr(), owner.as_slice().len()); + } + crate::pgtable::clean_invalidate_poc(q.as_ptr(), 0x400); + crate::pgtable::poc_barrier(); + let ring = &self._channels[2 * Self::signal_ring() + 1]; + dump("submission", ring.gpu_va().get(), &ring.as_slice()[..0x18]); + dump("command", job._owners[3].gpu_va().get(), &job._owners[3].as_slice()[..0x360]); + if let Some((_, _, ts)) = job._client.as_ref() { dump("jobtime", ts.gpu_va().get(), ts.as_slice()); } + if let Some(dir) = self.directory.as_ref() { + for at in [0x264usize, 0x26c] { + let va = u64::from_le_bytes(dir.as_slice()[at..at + 8].try_into().unwrap_or([0; 8])); + if let Some(owner) = self._channels.iter().find(|a| a.gpu_va().get() == va) { + crate::pgtable::clean_invalidate_poc(owner.as_slice().as_ptr(), owner.as_slice().len()); + dump(if at == 0x264 { "compute-state" } else { "scheduler-state" }, va, owner.as_slice()); + } + } + } + dump("stream", job._owners[4].gpu_va().get(), job._owners[4].as_slice()); + dump("pointers", job._owners[1].gpu_va().get(), &job._owners[1].as_slice()[..0x20]); + dump("scheduler", job._owners[2].gpu_va().get(), job._owners[2].as_slice()); + dump("timestamps", job._owners[0].gpu_va().get(), job._owners[0].as_slice()); + dump("positions", job.positions.gpu_va().get(), &job.positions.as_slice()[..0x60]); + dump("queue", job.queue.gpu_va().get(), &q[..0x400]); + dump("tracking", job._owners[5].gpu_va().get(), job._owners[5].as_slice()); + dump("cursor", job._owners[6].gpu_va().get(), job._owners[6].as_slice()); + } + } + + /// Read the uncached shared status after the ASC has stopped. + pub(crate) fn stopped_status(&self) -> (u32, u32, u32) { + let data = self.status.as_slice(); + let word = |i: usize| u32::from_le_bytes([data[i], data[i+1], data[i+2], data[i+3]]); + (word(4), word(0x10), word(0x14)) + } + + pub(crate) fn build( + graph: &Arc, + word: u64, + directory_layout: Option, + ) -> Result> { + use crate::m3::m3_init_26 as extended; + let mut alloc = graph.alloc(); + let mut startup_fence = if matches!(directory_layout, Some(G14DirectoryHeader::J413 { first_job: true, .. })) { + Some(G14StartupFence::new(&mut alloc, graph.event_manager.try_get_polled()?, graph.trial_uat(), &graph.dev)?) + } else { + None + }; + let mut channels = KVec::new(); + let mut controller = None; + let mut slot_ram = KVec::new(); + let mut register_mappings = KVec::new(); + let board = matches!(directory_layout, Some(G14DirectoryHeader::J413 { .. })); + let power_filter = crate::module_parameters::t8112_power_filter.value(); + let pwr = &graph.dyncfg.pwr; + if power_filter && (!board || !crate::module_parameters::t8112_power_curve.value() + || crate::module_parameters::t8112_alarm_fields.value() != 13 + || !pwr.power_zones.is_empty() || pwr.max_power_mw == 0 + || pwr.perf_states.last().map(|s| s.pwr_mw) != Some(pwr.max_power_mw) + || pwr.max_power_mw > i32::MAX as u32 || pwr.power_sample_period == 0 + || pwr.ppm_filter_time_constant_ms < pwr.power_sample_period + || pwr.avg_power_filter_tc_ms < pwr.power_sample_period + || pwr.avg_power_target_filter_tc == 0) { + return Err(EINVAL); + } + // On G14G the 0x60-byte root child and the eight-byte temperature + // generation occupy consecutive, 64-byte-aligned shared suballocations. + let board_extra = if board { + Some(alloc.shared.array_empty::(0x80 + 8)?) + } else { + None + }; + let directory = if let Some(header) = directory_layout { + let mut addresses = [0; 34]; + for (index, address) in addresses.iter_mut().enumerate() { + let size = extended::allocation(index).map_err(|_| EINVAL)?.size; + let owner = if board && index < 26 && index % 2 == 1 { + alloc.private.array_empty::(size)? + } else { + alloc.shared.array_empty::(size)? + }; + *address = owner.gpu_va().get(); + channels.push(owner, GFP_KERNEL)?; + } + if let Some(job) = startup_fence.as_ref() { + // Compute at priority zero uses the third TX descriptor. + let slot = u8::try_from(job.event.slot()).map_err(|_| EINVAL)?; + let engine = Self::signal_engine(); + let entry = crate::m3::submission_entry(engine as u32, job.queue.gpu_va().get(), 1, slot, + crate::module_parameters::t8112_first_publication.value()) + .map_err(|_| EINVAL)?; + // The ring starts empty at index R (consumer = intermediate = producer = R). + let r = Self::ring_start() as usize; + let n = entry.len(); + let ring = channels[2 * Self::signal_ring() + 1].as_mut_slice(); + ring[r * n..(r + 1) * n].copy_from_slice(&entry); + if job.second.is_some() { + let next = crate::m3::submission_entry(engine as u32, job.queue.gpu_va().get(), 2, slot, false) + .map_err(|_| EINVAL)?; + let r2 = (r + 1) % crate::m3::m3_channel_format::SLOTS as usize; + ring[r2 * n..(r2 + 1) * n].copy_from_slice(&next); + } + crate::pgtable::clean_poc(ring.as_ptr(), ring.len()); + let state = channels[2 * Self::signal_ring()].as_mut_slice(); + for at in [0usize, 0x10, 0x20] { + state[at..at + 4].copy_from_slice(&(r as u32).to_le_bytes()); + } + crate::pgtable::clean_poc(state.as_ptr(), state.len()); + } + if startup_fence.is_some() && crate::module_parameters::t8112_handshake.value() == 14 + && crate::module_parameters::t8112_idle_policy.value() { + // Reuse the J613 extended order: opening record, two engine classes + // per data master, then the counted idle-policy records. + let base = Self::control_base() as usize; + let records = &mut channels[2 * crate::m3::DEVICE_CONTROL + 1].as_mut_slice() + [..(base + 2) * crate::m3::CONTROL_BYTES]; + for (index, record) in records.chunks_exact_mut(crate::m3::CONTROL_BYTES).enumerate() { + let action = if index >= base { + crate::m3::Action::Idle { enabled: index == base + 1 } + } else if index == 0 { + crate::m3::Action::Initialize + } else { + let ordinal = index as u32 - 1; + crate::m3::Action::Register { pipe: ordinal / 2, engine: ordinal % 2 + 1 } + }; + action.encode(record).map_err(|_| EINVAL)?; + if index != 0 && index < base { + record[..4].copy_from_slice( + &crate::module_parameters::t8112_class_opcode.value().to_le_bytes()); + } + if index == 0 && index < base { + // The 27.x firmware line renumbered the opening handler (G18G 26A428 + // moved it from 0x16 to 0x15): the record body is unchanged. + record[..4].copy_from_slice( + &crate::module_parameters::t8112_opening_opcode.value().to_le_bytes()); + } + } + crate::pgtable::clean_poc(records.as_ptr(), records.len()); + if base != 0 { + // As on J613, the opening record is pending when the root becomes + // visible and retires through InitData consumption without a kick. + let state = channels[2 * crate::m3::DEVICE_CONTROL].as_mut_slice(); + state[0x20..0x24].copy_from_slice(&1u32.to_le_bytes()); + crate::pgtable::clean_poc(state.as_ptr(), state.len()); + } + } + let mut directory = if board { &mut alloc.private } else { &mut alloc.shared } + .array_empty::(0x4c8)?; + let bytes = directory.as_mut_slice(); + extended::write_channels(bytes, &addresses).map_err(|_| EINVAL)?; + let base = &graph.initdata.runtime_pointers; + bytes[..8].copy_from_slice(&base.hwdata_b.gpu_va().get().to_le_bytes()); + bytes[0x10..0x18].copy_from_slice(&base.unkptr_190.gpu_va().get().to_le_bytes()); + if let G14DirectoryHeader::J413 { sgx, sgx_size, interrupt, copy_bytes, live, .. } = header { + use crate::m3::m3_mmio_26::{write_record, RECORD_BYTES, TABLE_OFFSET}; + use fw::initdata::raw::HwDataBG14V27_2 as Hw; + let mut hardware = alloc.private.array_empty::(0x2788)?; + let hw = hardware.as_mut_slice(); + let scratch_pa = sgx + 0xe10000; + let mut io_va = IOVA_KERN_MMIO_RANGE.start; + let sgx_end = sgx.checked_add(sgx_size).ok_or(EOVERFLOW)?; + // Some disabled records retain their mode even with no backing. + let telemetry_ro = live && crate::module_parameters::t8112_telemetry_ro.value(); + // Stock maps the real 0x1000-byte push-telemetry window RW. The PMP + // takes the GPU's performance-state reports from it. + let real_dashboard = live && crate::module_parameters::t8112_dashboard_real.value(); + let ram_mask = crate::module_parameters::t8112_ram_slots.value(); + let trial_mask = (1 << 0) | (1 << 1) | (1 << 3) | (1 << 8) | (1 << 10) + | (1 << 12) | (1 << 17) | (1 << 33) | (1 << 40) | (1 << 44); + if ram_mask & !trial_mask != 0 { return Err(EINVAL); } + let slot_mode = |slot: usize| -> u64 { + match slot { + 9 if telemetry_ro && !real_dashboard => 0, + 0 | 2 | 3 | 5..=9 | 12 | 17 | 25..=27 | 31..=40 | + 42..=48 | 52..=55 | 58 => 2, + _ => 0, + } + }; + for slot in 0..60 { + let offset = TABLE_OFFSET + RECORD_BYTES * slot; + write_record(&mut hw[offset..], 0, 0, 0, 0, 0, slot_mode(slot)) + .map_err(|_| EINVAL)?; + } + for (slot, physical, size, relative) in [ + (0, interrupt & !0x3fff, 0x4000, 0), + (1, 0x23b2c0000, 0x1000, 0), + (3, 0x200f04000, 0x18000, 0), + (8, 0x27d050000, 0x4000, 0), + (9, 0x23b3d0000, 0x1000, 0), + (10, 0x23b3c0000, 0x1000, 0), + (12, 0x26b45c000, 0x4000, 0), + (17, sgx, 0x20000, 0), + (31, sgx + 0xd04000, 0xc000, 0xd04000), + (32, sgx + 0xd61000, 0x1000, 0xd61000), + (33, sgx + 0xe0c000, 0x4000, 0xe0c000), + (34, sgx + 0xd10000, 0x4000, 0xd10000), + (37, scratch_pa, 0x1000, 0xe10000), + (40, sgx + 0xd00000, 0x4000, 0xd00000), + (44, sgx + 0xd80000, 0x8000, 0), + ] { + let replace = ram_mask & (1u64 << slot) != 0; + let dashboard = slot == 9 && crate::module_parameters::t8112_dashboard_ram.value() && !real_dashboard; + if live && (replace || dashboard) { + if !telemetry_ro || crate::module_parameters::t8112_handshake.value() != 14 { + return Err(EINVAL); + } + // Independent trial VAs leave every existing register VA unchanged. + // The real update aperture and external MMIO are never installed here. + let span = (size as usize).next_multiple_of(mmu::UAT_PGSZ); + let offset = if dashboard { 0x10_0000 } else { 0x20_0000 + slot as u64 * 0x2_0000 }; + let va = if matches!(slot, 1 | 10 | 17 | 33 | 40 | 44) { + let original = io_va; + io_va = io_va.checked_add(span as u64).ok_or(EOVERFLOW)?; + original + } else { + IOVA_KERN_MMIO_RANGE.start + offset + }; + let ram = G14SlotRam::new(graph, slot, span, va, physical)?; + write_record(&mut hw[TABLE_OFFSET + RECORD_BYTES * slot..], + ram.ram.physical(), ram.mappings[0].iova(), size, size, relative, if G14SlotRam::readback(slot) { 0 } else { 2 }) + .map_err(|_| EINVAL)?; + slot_ram.push(ram, GFP_KERNEL)?; + dev_info!(graph.dev.as_ref(), "G14G scratch slot={} installed={} logical={}\n", slot, span, size); + continue; + } + let subpage = physical as usize & mmu::UAT_PGMSK; + let span = (subpage + size as usize + mmu::UAT_PGMSK) & !mmu::UAT_PGMSK; + let writable = slot_mode(slot) == 2; + let page_start = physical - subpage as u64; + let page_end = page_start.checked_add(span as u64).ok_or(EOVERFLOW)?; + // The admission-only profile can describe shared SoC registers. + // On live bring-up give write access only to full pages owned by SGX. + if live && writable && (page_start < sgx || page_end > sgx_end) && !(real_dashboard && slot == 9) { + continue; + } + // Place the optional read-only mapping after the fixed SGX register set + // so every other register keeps the same VA as the control. + let separate = telemetry_ro && slot == 9; + let va = if separate { + IOVA_KERN_MMIO_RANGE.start + 0x10_0000 + } else { + io_va + }; + let page = graph.uat.kernel_vm().map_io( + graph.dev.as_ref().as_ref(), va, page_start as usize, span, + if writable { mmu::PROT_FW_MMIO_RW } else { mmu::PROT_FW_MMIO_RO }, + )?; + if page.translate_offset(subpage)? != physical + || page.translate_offset(subpage + size as usize - 1)? != physical + u64::from(size) - 1 { + return Err(EINVAL); + } + write_record(&mut hw[TABLE_OFFSET + RECORD_BYTES * slot..], physical, + page.iova() + subpage as u64, size, size, relative, + slot_mode(slot)).map_err(|_| EINVAL)?; + if !separate { + io_va = io_va.checked_add(span as u64).ok_or(EOVERFLOW)?; + } + register_mappings.push(page, GFP_KERNEL)?; + } + let dump = core::mem::offset_of!(Hw, coredump_copy_buffer_size); + hw[dump..dump+8].copy_from_slice(&u64::from(copy_bytes).to_le_bytes()); + base.hwdata_b.with(|old, _| { + for (offset, value) in [ + (0x00, old.unk_8.0), (0x08, old.unk_18.0), + (0x10, 0x11_00000000), (0x18, 0x11_00000000), + (0x20, 0x6f_ffff8000), (0x28, G14G_TIMESTAMP_RANGE.start), + (0x10cc, old.uat_ttb_base.0), + ] { + hw[offset..offset+8].copy_from_slice(&value.to_le_bytes()); + } + for (offset, value) in [(0x10d4, old.gpu_core_id), (0x10d8, old.gpu_rev_id), + (0x10dc, graph.dyncfg.id.total_active_cores), (0x10e0, old.max_pstate)] { + hw[offset..offset+4].copy_from_slice(&value.to_le_bytes()); + } + // Legacy J413 HwDataB configuration carried to the 26B123 inline block. The + // chip words (legacy +0x450 -> +0xfb0) and the two words already confirmed on + // hardware (+0x460 -> +0xfc0, +0x4f4 -> +0x1054) give a shift of 0xb60; the + // firmware's own read list places unk_534 and num_frags at +0x109c/+0x10a4. + let legacy = crate::module_parameters::t8112_hw_legacy.value(); + let mut carry = |bit: u64, offset: usize, value: u32| { + if legacy & bit != 0 { hw[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); } + }; + carry(1, 0x10a4, old.num_frags); + carry(2, 0x1064, old.unk_504); + carry(4, 0x1020, old.unk_4c0); + carry(8, 0x109c, old.unk_534); + carry(0x10, 0x1084, old.unk_524); + for (offset, value) in [(0xfc4, old.unk_464), (0xfdc, old.unk_47c), (0xfe4, old.unk_484), + (0xfec, old.unk_48c), (0xff0, old.base_clock_khz), + (0xff4, old.power_sample_period), (0xffc, old.unk_49c), + (0x1000, old.unk_4a0), (0x1004, old.unk_4a4)] { + carry(0x20, offset, value); + } + // Inline words whose stock J413 value the host producer fixes. + // These replace the legacy-shift guesses for the same offsets. + for (offset, value) in [(0xfc8u32, 0u32), (0xfd8, 1), (0xfec, 24000), (0xff0, 1), + (0xffc, 1), (0x2724, 1), (0x2754, 1)] { + carry(0x40, offset as usize, value); + } + // Capability words {8,10,11,18,24,25,53} for a gpu,t8112 + // node without model-slow. They replace the legacy carry at the same offsets. + for (offset, value) in [(0xfc4u32, 1u32), (0xfdc, 1), (0xfe0, 0), (0x1028, 0), + (0x109c, 0), (0x1064, 0), (0x2728, 0)] { + carry(0x80, offset as usize, value); + } + // Compute resource mask, one low bit per configured core. + // The firmware imports it and seeds the compute engine's population from it. + let cores = graph.dyncfg.id.total_active_cores; + carry(0x100, 0x2670, if cores < 32 { (1u32 << cores) - 1 } else { u32::MAX }); + let chip = core::mem::offset_of!(Hw, chip_id); + for (i, word) in [old.chip_id, old.unk_454, old.unk_458, old.unk_45c] + .into_iter().enumerate() { + let offset = chip + 4 * i; + hw[offset..offset + 4].copy_from_slice(&word.to_le_bytes()); + } + }); + // G15G 26.6.2 and the common newer profile agree on the first table: + // 16 lanes of voltage per state and frequencies expressed in MHz. + use crate::g17::fw::m5::initdata as abi; + let mut sram_table = None; + let mut found_sgx = false; + let chosen = kernel::of::chosen().ok_or(ENODEV)?; + for parent in chosen.children() { + let name = parent.get_opt_property::>(c"name")?; + if name.as_deref() != Some(b"aurora-gpu-resources\0") && + name.as_deref() != Some(b"aurora-gpu-resources") { + continue; + } + for child in parent.children() { + let name = child.get_opt_property::>(c"name")?; + if name.as_deref() == Some(b"sgx\0") || name.as_deref() == Some(b"sgx") { + found_sgx = true; + sram_table = child.get_opt_property::>(c"adt-perf-states-sram")?; + } + } + } + let perf = crate::module_parameters::t8112_performance_control.value(); + let cre = crate::module_parameters::t8112_cre.value(); + let event = crate::module_parameters::t8112_event_completion.value(); + let base_request = crate::module_parameters::t8112_base_request.value(); + let curve = crate::module_parameters::t8112_power_curve.value(); + if perf || cre || event || base_request { + if !live || !telemetry_ro || ram_mask & !(1 << 17) != 0 || + crate::module_parameters::t8112_handshake.value() != 14 || + !(curve || crate::module_parameters::t8112_idle_policy.value()) { return Err(EINVAL); } + if (event || base_request) && !(perf && cre) { return Err(EINVAL); } + for (offset, enabled) in [(0xfc0, perf), (0x26b8, cre), (0x1054, event)] { + hw[offset..offset+4].copy_from_slice(&u32::from(enabled).to_le_bytes()); + } + } + let id = &graph.dyncfg.id; + let [mask] = id.core_masks.as_slice() else { return Err(EINVAL); }; + if mask.count_ones() != id.total_active_cores || id.total_active_cores == 0 { + return Err(EINVAL); + } + hw[0x267c..0x2684].copy_from_slice(&u64::from(*mask).to_le_bytes()); + hw[0x2684..0x2688].copy_from_slice(&id.total_active_cores.to_le_bytes()); + let states = &graph.dyncfg.pwr.perf_states; + if !found_sgx || states.is_empty() || states.len() > abi::COMMON26_HW_PERF_ROWS || + sram_table.as_ref().is_some_and(|table| table.len() != states.len()*8) { + return Err(EINVAL); + } + let alarm_fields = crate::module_parameters::t8112_alarm_fields.value() as usize; + let inventory = crate::module_parameters::t8112_calibrated_sensors.value(); + let fast_selection = graph.cfg.fast_sensor_mask[0]; + if curve { + if !base_request || !(2..=16).contains(&states.len()) || + !crate::module_parameters::t8112_dashboard_ram.value() || + !crate::module_parameters::t8112_mtr_sensors.value() || + inventory & fast_selection != fast_selection || inventory >> 32 != 0 || + states.windows(2).any(|pair| pair[1].pwr_mw <= pair[0].pwr_mw) { + return Err(EINVAL); + } + let ceiling = u32::from_le_bytes(hw[0x10e0..0x10e4].try_into().map_err(|_| EINVAL)?); + if ceiling as usize != states.len()-1 { return Err(EINVAL); } + let baseline = states[0].pwr_mw; + let span = crate::float::F32::from(states[ceiling as usize].pwr_mw - baseline); + for (i, state) in states.iter().enumerate() { + let percentage = crate::float::F32::from(state.pwr_mw - baseline) * + crate::f32!(100.0) / span; + let at = abi::COMMON26_HW_PERF_RELATIVE_A + i * 4; + hw[at..at+4].copy_from_slice(&percentage.to_bits().to_le_bytes()); + } + } + if power_filter { + // Performance and SE interpolate frequency above base, not absolute power. + // Same normalization as the common26 frequency table on the M5 profile. + let base_idx = pwr.perf_base_pstate as usize; + let base_hz = states.get(base_idx).ok_or(EINVAL)?.freq_hz; + let top_hz = states.last().ok_or(EINVAL)?.freq_hz; + if top_hz <= base_hz || states.windows(2).any(|v| v[0].freq_hz >= v[1].freq_hz) { + return Err(EINVAL); + } + let span = crate::float::F32::from(top_hz - base_hz); + for (i, state) in states.iter().enumerate().skip(base_idx + 1) { + let at = abi::COMMON26_HW_PERF_RELATIVE_B + 4 * i; + let relative = crate::float::F32::from(state.freq_hz - base_hz) + * crate::f32!(100.0) / span; + hw[at..at+4].copy_from_slice(&relative.to_bits().to_le_bytes()); + } + } + if alarm_fields > 13 || (alarm_fields != 0 && !curve) { return Err(EINVAL); } + for (i,state) in states.iter().enumerate() { + let [mv] = state.volt_mv.as_slice() else { return Err(EINVAL); }; + let sram_mv = if let Some(table) = &sram_table { + let (freq, voltage) = table[i*8..i*8+8].split_at(4); + if u32::from_le_bytes(freq.try_into().map_err(|_| EINVAL)?) != state.freq_hz { + return Err(EINVAL); + } + let value = u32::from_le_bytes(voltage.try_into().map_err(|_| EINVAL)?); + if value < *mv || value > 1100 { return Err(EINVAL); } + value + } else { + (*mv).max(850) + }; + let mhz = (state.freq_hz / 1_000_000).to_le_bytes(); + for series in [abi::COMMON26_HW_PERF_FREQUENCY, 0x1924] { + let freq = series + i * 4; + hw[freq..freq+4].copy_from_slice(&mhz); + } + for lane in 0..abi::COMMON26_HW_PERF_LANES { + let row = i*abi::COMMON26_HW_PERF_ROW_STRIDE + lane*4; + let core = abi::COMMON26_HW_PERF_CORE_VOLTAGE + row; + let sram = abi::COMMON26_HW_PERF_SRAM_VOLTAGE + row; + hw[core..core+4].copy_from_slice(&mv.to_le_bytes()); + hw[sram..sram+4].copy_from_slice(&sram_mv.to_le_bytes()); + } + } + dev_info!(graph.dev.as_ref(), "G14G {} checked MMIO translations; {} operating points, boot SRAM table={}\n", + register_mappings.len(), states.len(), sram_table.is_some()); + crate::pgtable::clean_poc(hw.as_ptr(), hw.len()); + bytes[..8].copy_from_slice(&hardware.gpu_va().get().to_le_bytes()); + channels.push(hardware, GFP_KERNEL)?; + for (offset, size) in [(0x10,0x88),(0x254,0x678),(0x25c,0x760), + (0x264,0x6d0),(0x26c,0x60),(0x485,0x6c48)] { + let mut owner = alloc.private.array_empty::(size)?; + if offset == 0x485 { + let pwr = &graph.dyncfg.pwr; + let policy = owner.as_mut_slice(); + let max_state = (pwr.perf_states.len() as u32 - 1) * 100; + for offset in [0x222c, 0x2880] { + policy[offset..offset + 4].copy_from_slice(&max_state.to_le_bytes()); + } + let extra = board_extra.as_ref().ok_or(EINVAL)?; + let generation = extra.gpu_va().get() + 0x80; + if generation & 0x3f != 0 || extra.as_slice()[0x80..] != [0; 8] { + return Err(EINVAL); + } + policy[0x3b98..0x3ba0].copy_from_slice(&generation.to_le_bytes()); + let fast_die_fields = crate::module_parameters::t8112_fast_die_fields.value() as usize; + if alarm_fields != 0 && fast_die_fields != 4 { return Err(EINVAL); } + if fast_die_fields > 4 || (fast_die_fields != 0 && !crate::module_parameters::t8112_mtr_sensors.value()) { + return Err(EINVAL); + } + if crate::module_parameters::t8112_mtr_sensors.value() { + if !(base_request && event && crate::module_parameters::t8112_dashboard_ram.value()) + || ram_mask != 0 { return Err(EINVAL); } + // J413's old ABI uses the board alarm mask as its alternate sensor mask. + // The newer secure controller accepts a 64-bit sensor set at +0x3ba0. + let sensors = if curve { inventory } else { graph.cfg.fast_sensor_mask_alt[0] }; + if sensors == 0 || sensors >> 32 != 0 { return Err(EINVAL); } + policy[0x3ba0..0x3ba8].copy_from_slice(&sensors.to_le_bytes()); + dev_info!(graph.dev.as_ref(), "G14G secure metrology sensors={:#x}\n", sensors); + // Keep the J413 13.5 producer and its board-specific units. These four + // J613 sources share a checked relocation band with both J413 OPP anchors. + let (release, mask, integral, proportional) = base.hwdata_a.with(|old, _| + (old.fast_die0_release_temp_cc, old.fast_die0_sensor_mask.0, + old.fast_die0_ki_dt.to_bits(), old.fast_die0_kp.to_bits())); + let fields = [ + (0x2270, u64::from(release), 4), + (0x2268, mask, 8), + (0x2294, u64::from(integral), 4), + (0x22a4, u64::from(proportional), 4), + ]; + for &(source, value, width) in &fields[..fast_die_fields] { + let at = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source).ok_or(EINVAL)?; + policy.get_mut(at..at + width).ok_or(EINVAL)? + .copy_from_slice(&value.to_le_bytes()[..width]); + dev_info!(graph.dev.as_ref(), "G14G J413 fast-die policy offset={:#x} bytes={} value={:#x}\n", + at, width, value); + } + } + // Each step adds one stock controller field to the same matched profile. + // Install thresholds and correction tables before selecting the SoC-hot alarm. + let settings: &[(usize, u32)] = &[(0x22d4, 11000), (0x2284, 900), (0x2288, 4), + (0x229c, crate::f32!(1.0).to_bits()), (0x2f30, 125), (0x2f34, 1)]; + for &(at, value) in settings.iter().take(alarm_fields) { + policy[at..at+4].copy_from_slice(&value.to_le_bytes()); + } + for &at in [0x2320, 0x2420, 0x2f38, 0x3038].iter().take(alarm_fields.saturating_sub(6)) { + for sid in 0..64 { + if fast_selection & (1u64 << sid) != 0 { + let field = at + 4 * sid; + policy[field..field+4].copy_from_slice(&crate::f32!(5.3).to_bits().to_le_bytes()); + } + } + } + if alarm_fields >= 11 { + policy[0x2f28..0x2f30].copy_from_slice(&(inventory & fast_selection).to_le_bytes()); + } + if alarm_fields >= 12 { + policy[0x3ba8..0x3bac].copy_from_slice(&1u32.to_le_bytes()); + } + if alarm_fields >= 13 { + if graph.cfg.shared3_tab.len() != 16 { return Err(EINVAL); } + for (word, value) in policy[0x62b8..0x62f8].chunks_exact_mut(4).zip(graph.cfg.shared3_tab) { + word.copy_from_slice(&value.to_le_bytes()); + } + let mask_at = |at: usize| -> Result { + Ok(u64::from_le_bytes(policy[at..at+8].try_into().map_err(|_| EINVAL)?)) + }; + dev_info!(graph.dev.as_ref(), + "G14G prepared thermal masks inventory={:#x} fast_die={:#x} soc_hot={:#x}\n", + mask_at(0x3ba0)?, mask_at(0x2278)?, mask_at(0x2f28)?); + } + // Controlled cold-wake operand, distinct from the observed current index. + if base_request { + if pwr.perf_base_pstate == 0 || pwr.perf_base_pstate as usize >= pwr.perf_states.len() { + return Err(EINVAL); + } + policy[0xa4..0xa8].copy_from_slice(&pwr.perf_base_pstate.to_le_bytes()); + } + for (source, bits) in [ + (4, pwr.pwr_sample_period_aic_clks), + (8, pwr.pwr_sample_period_aic_clks), + // The common 26-series controller has two initial state sources. + // The current state at +0x38 belongs to firmware. + (0x2c, pwr.perf_base_pstate), + (0x30, pwr.perf_base_pstate), + (0x9f0, pwr.pwr_min_duty_cycle), + (0xb5c, pwr.perf_integral_gain.to_bits()), + (0xb60, pwr.perf_integral_gain2.to_bits()), + (0xb6c, pwr.perf_proportional_gain.to_bits()), + (0xb70, pwr.perf_proportional_gain2.to_bits()), + ] { + let target = abi::relocate_by_bands(abi::COMMON26_POLICY_BANDS, source) + .ok_or(EINVAL)?; + policy.get_mut(target..target + 4).ok_or(EINVAL)? + .copy_from_slice(&bits.to_le_bytes()); + } + if power_filter { + // The 26B123 controller uses the same calibrated values as J413's + // typed producer. Only the layout and the peak length unit differ. + let samples = pwr.ppm_filter_time_constant_ms / pwr.power_sample_period; + let fields = base.hwdata_a.with(|a, _| [ + (0x50, 100), (0xa80, a.ppm_filter_tc_periods_x4), + (0xa8c, a.ppm_filter_a_neg.to_bits()), (0xa94, a.ppm_filter_a.to_bits()), + (0xa9c, a.ppm_ki_dt.to_bits()), (0xaa8, a.unk_6fc.to_bits()), + (0xaac, a.ppm_kp.to_bits()), (0xab8, a.pwr_min_duty_cycle), + (0xabc, a.max_pstate_scaled_4), (0xacc, a.max_power_3), + (0xad8, samples), (0x2200, a.unk_6fc.to_bits()), + (0xa48, max_state), + (0xb38, a.perf_tgt_utilization), (0xb40, a.perf_boost_min_util), + (0xb44, a.perf_boost_ce_step), (0xb58, a.perf_filter_drop_threshold), + (0xb5c, a.perf_filter_a_neg.to_bits()), (0xb60, a.perf_filter_a2_neg.to_bits()), + (0xb64, a.perf_filter_a.to_bits()), (0xb68, a.perf_filter_a2.to_bits()), + (0xb74, a.perf_integral_min_clamp.to_bits()), (0xb78, a.unk_79c.to_bits()), + (0xb84, a.boost_state_unk_k.to_bits()), (0xb88, a.base_pstate_scaled_2), + (0xb8c, a.max_pstate_scaled_5), (0xb90, a.base_pstate_scaled_3), + (0xb9c, a.perf_tgt_utilization_2), (0xbd0, a.base_pstate_scaled_4), + (0x2204, a.pwr_min_duty_cycle_2.to_bits()), (0x2208, a.max_pstate_scaled_6.to_bits()), + (0x220c, pwr.max_freq_mhz), + (0x22b0, a.unk_8a8.to_bits()), (0x22c0, a.pwr_min_duty_cycle_4), + (0x22c4, a.max_pstate_scaled_8), (0x22c8, a.max_pstate_scaled_9), + (0x2308, a.max_pstate_scaled_10), + (0x28e8, crate::module_parameters::t8112_power_zones.value()), (0x28f0, a.max_power_4), + (0x28f4, a.max_power_5), (0x28f8, a.max_power_6), + (0x2904, a.avg_power_target_filter_a_neg.to_bits()), + (0x2908, a.avg_power_target_filter_a.to_bits()), + (0x29f0, a.avg_power_filter_a_neg.to_bits()), + (0x29f8, a.avg_power_filter_a.to_bits()), + (0x2a00, a.avg_power_ki_dt.to_bits()), (0x2a10, a.avg_power_kp.to_bits()), + (0x2a0c, a.unk_d20.to_bits()), (0x2a1c, a.avg_power_min_duty_cycle), + (0x2a20, a.max_pstate_scaled_12), (0x2a2c, a.max_power_7.to_bits()), + (0x2a30, a.max_power_8), + (0x2b80, a.unk_e10_0.gpu_se_filter_a_neg.to_bits()), + (0x2b84, a.unk_e10_0.gpu_se_filter_1_a_neg.to_bits()), + (0x2b88, a.unk_e10_0.gpu_se_filter_a.to_bits()), + (0x2b8c, a.unk_e10_0.gpu_se_filter_1_a.to_bits()), + (0x2b90, a.unk_e10_0.gpu_se_ki_dt.to_bits()), + (0x2b94, a.unk_e10_0.gpu_se_ki_1_dt.to_bits()), + (0x2b9c, a.unk_e10_0.unk_7c.to_bits()), + (0x2ba0, a.unk_e10_0.gpu_se_kp.to_bits()), + (0x2ba4, a.unk_e10_0.gpu_se_kp_1.to_bits()), + (0x2bac, a.unk_e10_0.unk_8c), (0x2bb0, a.unk_e10_0.max_pstate_scaled_1), + (0x2c10, a.unk_e10_0.unk_3c), (0x2c14, a.unk_e10_0.unk_38), + (0x2c28, a.unk_e10_0.gpu_se_reset_criteria), + (0x6ac8, 1), + ]); + for (at, value) in fields { + policy[at..at+4].copy_from_slice(&value.to_le_bytes()); + } + let ticks = u64::from(samples) * u64::from(pwr.pwr_sample_period_aic_clks); + policy[0xae0..0xae8].copy_from_slice(&ticks.to_le_bytes()); + dev_info!(graph.dev.as_ref(), + "G14G cold power policy target={} peak samples={} ticks={} ceiling={}\n", + pwr.max_power_mw, samples, ticks, max_state); + } + crate::pgtable::clean_poc(policy.as_ptr(), policy.len()); + } + let address = owner.gpu_va().get().to_le_bytes(); + dev_info!(graph.dev.as_ref(), "G14G directory +{:#x} owner va={:#x} bytes={:#x}\n", + offset, owner.gpu_va().get(), size); + bytes[offset..offset+8].copy_from_slice(&address); + if offset == 0x10 { + bytes[8..16].copy_from_slice(&address); + } + if offset == (if crate::module_parameters::t8112_provider_object.value() == 1 { 0x26c } else { 0x264 }) { + if let Some(job) = startup_fence.as_mut() { + // Compute engine state: legacy StartCompute/FinalizeCompute "stats". + let patch: KVec = core::mem::take(&mut job.stats_patch); + job.compute_state = owner.gpu_va().get(); + let stream = job._owners[if job.second.is_some() { 8 } else { 4 }].as_mut_slice(); + for at in patch.iter().copied() { + stream[at..at + 8].copy_from_slice(&address); + } + crate::pgtable::clean_poc(stream.as_ptr(), stream.len()); + } + } + if offset == 0x485 { + controller = Some(owner); + } else { + channels.push(owner, GFP_KERNEL)?; + } + } + let ids = alloc.private.array_empty::(0x134c)?; + for (slot, offset) in [(0x2c8, 0), (0x2d0, 0x1000), (0x2d8, 0x1300)] { + bytes[slot..slot+8].copy_from_slice(&(ids.gpu_va().get() + offset).to_le_bytes()); + } + channels.push(ids, GFP_KERNEL)?; + let low = base.buffer_mgr_ctl_low_mapping.as_ref().ok_or(EINVAL)?; + let high = base.buffer_mgr_ctl_high_mapping.as_ref().ok_or(EINVAL)?; + if low.translate_offset(0)? != high.translate_offset(0)? { return Err(EINVAL); } + bytes[0x2e0..0x2e8].copy_from_slice(&low.iova().to_le_bytes()); + bytes[0x2e8..0x2f0].copy_from_slice(&high.iova().to_le_bytes()); + bytes[0x3e4] = 0xff; + } + if matches!(header, G14DirectoryHeader::PrivatePage) { + // T6040's main.unk_18 names a zeroed, private RAM page. + // Keep a page-aligned allocation alive for the whole firmware session. + let size = mmu::UAT_PGSZ; + let storage = alloc.private.alloc_generic::(size, size, None)?; + let page = fw::types::GpuArray::::empty(storage, size)?; + if page.gpu_va().get() % size as u64 != 0 { + return Err(EINVAL); + } + crate::pgtable::clean_poc(page.as_slice().as_ptr(), size); + bytes[0x18..0x20].copy_from_slice(&page.gpu_va().get().to_le_bytes()); + channels.push(page, GFP_KERNEL)?; + } + let payload = alloc.shared.array_empty::( + extended::LOG_THREADS * 256 * extended::LOG_PAYLOAD_BYTES)?; + bytes[0x200..0x208].copy_from_slice(&payload.gpu_va().get().to_le_bytes()); + channels.push(payload, GFP_KERNEL)?; + if board && crate::module_parameters::t8112_firmware_log.value() { + // J613's extended runtime opens this gate; stock J413 leaves it clear. + bytes[0x250..0x254].copy_from_slice(&1u32.to_le_bytes()); + } + crate::pgtable::clean_poc(bytes.as_ptr(), bytes.len()); + Some(directory) + } else { + None + }; + let mut status = alloc.shared.array_empty::(0x20)?; + if board && crate::module_parameters::t8112_firmware_trace.value() { + // Debug bit 1 in the status word, set before the root message. + status.as_mut_slice()[..4].copy_from_slice(&crate::module_parameters::t8112_trace_bits.value().to_le_bytes()); + } + let boot_page = if board { + let page = alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)?; + Some(fw::types::GpuArray::empty(page, mmu::UAT_PGSZ)?) + } else { + None + }; + let globals = if board { + let mut globals = alloc.shared_ro.array_empty::(0xe48)?; + let data = globals.as_mut_slice(); + for (offset, value) in [(0x58, 0xffffu16), (0x5a, 0x28), (0x5c, 0xffff)] { + data[offset..offset+2].copy_from_slice(&value.to_le_bytes()); + } + if power_filter { + let ceiling = pwr.perf_max_pstate * 100; + // An upper cap of 100 at +0x98 keeps the first job at the + // base state, with no operating-point change around submission. + let cap = match crate::module_parameters::t8112_state_cap.value() { 0 => ceiling, cap => cap }; + for (at, value) in [(0x84, pwr.max_power_mw), (0x88, ceiling), + (0x8c, ceiling), (0x98, cap)] { + data[at..at+4].copy_from_slice(&value.to_le_bytes()); + } + } + // Hardware configuration +0xff0 is zero in this profile. + data[0x6e..0x72].copy_from_slice(&1u32.to_le_bytes()); + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + Some(globals) + } else { + None + }; + let mut control = alloc.shared.array_empty(if board { 0xe850 } else { 0xeaf0 })?; + if board { + // One shared backing: 0x20 bytes of indices, followed at +0x40 + // by 256 cache-flush requests. An empty ring still needs both VAs. + let flush = alloc.shared.array_empty::(0x40 + 256 * 0x18)?; + let state = flush.gpu_va().get(); + extended::write_flush_ring(control.as_mut_slice(), 0x4be0, state, state + 0x40) + .map_err(|_| EINVAL)?; + if crate::module_parameters::t8112_command_service.value() { + // Request command-handler installation during powered initialization. + control.as_mut_slice()[0x4c24..0x4c28].copy_from_slice(&1u32.to_le_bytes()); + } + channels.push(flush, GFP_KERNEL)?; + dev_info!(graph.dev.as_ref(), "G14G 26B123 shared temperature and cache-flush allocations ready; GPTBAT={:#x}\n", + graph.dyncfg.uat_ttb_base); + } + let mut power = alloc.shared.array_empty(if board { 0x6a0 } else if directory_layout.is_some() { 0x698 } else { 0x670 })?; + if power_filter { + // Cold mirrors only. A runtime update must also publish its filter length. + let gains = graph.initdata.runtime_pointers.hwdata_a.with(|a, _| + (a.ppm_kp.to_bits(), a.ppm_ki_dt.to_bits())); + let data = power.as_mut_slice(); + for (at, value) in [(0x12c, pwr.max_power_mw), (0x130, gains.0), (0x134, gains.1)] { + data[at..at+4].copy_from_slice(&value.to_le_bytes()); + } + // The SGX cold runtime mirrors use the same temperature units and gains + // as the controller. Leave its update flag and overrides at their cold values. + let initial = controller.as_ref().ok_or(EINVAL)?.as_slice(); + for (dst, src) in [(0xc8, 0x22d4), (0xcc, 0x2280), (0xd0, 0x2284), + (0xd4, 0x22cc), (0xd8, 0x22b4), (0xdc, 0x22a4)] { + data[dst..dst+4].copy_from_slice(&initial[src..src+4]); + } + crate::pgtable::clean_poc(data.as_ptr(), data.len()); + } + let extra = match board_extra { + Some(extra) => extra, + None => alloc.shared.array_empty(0x4000)?, + }; + let (page_size, page_bits, levels, descriptors) = graph.initdata.with(|r, _| + (r.uat_page_size, r.uat_page_bits, r.uat_num_levels, r.uat_level_info)); + let root = if board { + alloc.shared_ro.alloc_generic::(mmu::UAT_PGSZ, mmu::UAT_PGSZ, None)? + } else { + alloc.private.alloc_object::()? + }; + fw::types::GpuObject::::new_init_prealloc(root, + |_| try_init!(Self { graph: graph.clone(), directory, controller, slot_ram, _channels: channels, _register_mappings: register_mappings, startup_fence, globals, boot_page, status, control, power, extra }), + |owners, _| { + let base = &owners.graph.initdata; + try_init!(fw::initdata::raw::InitDataG14V27_2 { + ver_info: version_words(word), + unk_buf: owners.boot_page.as_ref().unwrap_or(&base.unk_buf).gpu_pointer(), + unk_8: 0, + unk_c: 0, + runtime_pointers: match &owners.directory { + Some(directory) => directory.gpu_pointer(), + None => base.runtime_pointers.gpu_bytes(), + }, + globals: match &owners.globals { Some(g) => g.gpu_pointer(), None => base.globals.gpu_bytes() }, + role: 0, + host_mapped_fw_allocations: 1, + uat_page_size: page_size, + uat_page_bits: page_bits, + uat_num_levels: levels, + uat_level_info: descriptors, + __pad0: Default::default(), + status_record: owners.status.gpu_pointer(), + control: owners.control.gpu_pointer(), + power: owners.power.gpu_pointer(), + extra: owners.extra.gpu_pointer(), + }) + }, + ) + } +} diff --git a/drivers/gpu/drm/asahi/initdata.rs b/drivers/gpu/drm/asahi/initdata.rs index 75cbb1c03c6b1..25e4890e1c546 100644 --- a/drivers/gpu/drm/asahi/initdata.rs +++ b/drivers/gpu/drm/asahi/initdata.rs @@ -37,7 +37,7 @@ use ::pin_init; use ::pin_init::Init; /// Builder helper for the global GPU InitData. -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct InitDataBuilder<'a> { dev: &'a AsahiDrmDevice, alloc: &'a mut gpu::KernelAllocators, @@ -45,7 +45,7 @@ pub(crate) struct InitDataBuilder<'a> { dyncfg: &'a hw::DynConfig, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl<'a> InitDataBuilder::ver<'a> { /// Create a new InitData builder pub(crate) fn new( @@ -995,9 +995,15 @@ impl<'a> InitDataBuilder::ver<'a> { } } + /// Build the top-level InitData object. #[inline(never)] pub(crate) fn build(&mut self) -> Result>> { + // The 27.2 root is built by the J413 root builder in gpu.rs, not from this graph. + #[ver(V >= V27_2)] + return Err(ENOSYS); + #[ver(V < V27_2)] + { let runtime_pointers = self.runtime_pointers()?; let globals = self.globals()?; let fw_status = self.fw_status()?; @@ -1041,5 +1047,6 @@ impl<'a> InitDataBuilder::ver<'a> { }, )?; Ok(KBox::new(obj, GFP_KERNEL)?) + } } } diff --git a/drivers/gpu/drm/asahi/j413.rs b/drivers/gpu/drm/asahi/j413.rs new file mode 100644 index 0000000000000..201671ba94bb3 --- /dev/null +++ b/drivers/gpu/drm/asahi/j413.rs @@ -0,0 +1,585 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! J413 (T8112, G14G) with GPU firmware 27.2: a compute-only DRM backend. +//! +//! The 27.2 firmware is brought up by the J413 bring-up path in `mmu.rs` +//! (`Uat::observe_t8112_peer`), which builds the 26B123 root from the 13.5 G14G graph and runs +//! one kernel-owned compute job. With `asahi.t8112_drm=1` that path hands the running firmware +//! over instead of stopping it. Clients reach it through the 26.x submission front end of the +//! M3 backend (`m3_submit`), whose compute commands are re-encoded here in the 26B123 G14G +//! layout and published, in order, on the bring-up queue. + +use core::ops::Range; +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +use kernel::{ + device, + drm::sched, + new_delayed_work, new_mutex, + prelude::*, + sync::{Arc, Mutex}, + time::{msecs_to_jiffies, Delta, Instant, Monotonic}, + sync::aref::ARef, + uapi, + workqueue::{self, impl_has_delayed_work, DelayedWork, WorkItem}, +}; + +use crate::{ + alloc, event, gem, gpu, gpu::GpuManagerG14V13_5, mmu, queue, + gpu::{G14TrialRoot, J413Compute, J413Pool, J413Queue, J413_POOL}, + m3::m3_submit::{Command, Packet}, +}; + +/// The ASC control page, kept mapped until the firmware is stopped. +pub(crate) struct AscControl(*mut u8); +// SAFETY: a device register page; accesses are single 32-bit MMIO operations. +unsafe impl Send for AscControl {} +// SAFETY: as above. +unsafe impl Sync for AscControl {} + +impl AscControl { + /// Maps the ASC control page at `phys`. + pub(crate) fn new(phys: u64) -> Result { + // SAFETY: `phys` is the ASC register window of this platform device. + let ptr = unsafe { kernel::bindings::ioremap(phys, 0x4000) }; + if ptr.is_null() { return Err(ENOMEM); } + Ok(Self(ptr.cast())) + } + fn read(&self, at: usize) -> u32 { + // SAFETY: `at` is a register offset inside the mapped page. + unsafe { kernel::bindings::readl(self.0.add(at).cast()) } + } + fn write(&self, at: usize, value: u32) { + // SAFETY: as above. + unsafe { kernel::bindings::writel(value, self.0.add(at).cast()) } + } +} + +impl Drop for AscControl { + fn drop(&mut self) { + // SAFETY: mapped in `new`, unmapped once. + unsafe { kernel::bindings::iounmap(self.0.cast()) } + } +} + +/// What the bring-up path hands over when it keeps the firmware running. +pub(crate) struct Live<'a> { + pub(crate) peer: Pin>>, + pub(crate) root: crate::fw::types::GpuObject, + pub(crate) graph: Arc, + pub(crate) pool: J413Pool, + pub(crate) asc: AscControl, + pub(crate) drm: kernel::drm::UnregisteredDevice, + pub(crate) binding: crate::binding::Owner, + pub(crate) resources: crate::regs::Resources<'a>, +} + +struct Inflight { + packet: Arc, + last: bool, + stamp: event::EventValue, + slot: usize, + /// Queue publications up to and including this command, counted from take-over. + ordinal: u64, + started: Instant, + _bind: mmu::VmBind, +} + +struct State { + peer: Pin>>, + root: crate::fw::types::GpuObject, + pool: J413Pool, + asc: AscControl, + queue: J413Queue, + last: event::EventValue, + sequence: u64, + next_slot: usize, + waiting_unlink: bool, + /// Publications and retirements counted on the queue's position block, which the + /// firmware advances in order (the shared stamp can be written out of order). + published: u64, + retired_total: u64, + retired_raw: u32, + capacity: u32, + inflight: KVec, + pending: KVec<(Arc, usize)>, + submitted: u64, + retired: u64, +} + +/// Commands slower than this are a hang; the firmware state is then not trusted. +const COMMAND_TIMEOUT_MS: i64 = 5000; +/// Idle polling keeps the firmware's statistics ring drained and bounds completion latency. +const IDLE_POLL_MS: u64 = 20; + +#[pin_data(PinnedDrop)] +pub(crate) struct Runtime { + dev: ARef, + graph: Arc, + healthy: AtomicBool, + /// Poll work queued or running; `stop` waits for zero so no work outlives the module. + queued: AtomicU32, + #[pin] + state: Mutex>, + #[pin] + poll: DelayedWork, +} + +impl_has_delayed_work! { + impl HasDelayedWork for Runtime { self.poll } +} + +impl WorkItem for Runtime { + type Pointer = Arc; + fn run(this: Arc) { + let busy = this.service(); + if this.healthy.load(Ordering::Acquire) { + this.schedule(if busy { 1 } else { IDLE_POLL_MS }); + } + this.queued.fetch_sub(1, Ordering::AcqRel); + } +} + +#[pinned_drop] +impl PinnedDrop for Runtime { + fn drop(self: Pin<&mut Self>) { + // The poll work holds a reference while scheduled, so this runs only once the + // runtime is idle; stop the firmware first if no one has. + if self.state.lock().is_some() { self.stop(); } + } +} + +impl Runtime { + fn schedule(self: &Arc, ms: u64) { + if !self.healthy() { return; } + self.queued.fetch_add(1, Ordering::AcqRel); + if workqueue::system_highpri() + .enqueue_delayed::, 0>(self.clone(), msecs_to_jiffies(ms as u32)).is_err() { + // Already queued: that run accounts for itself. + self.queued.fetch_sub(1, Ordering::AcqRel); + } + } + + pub(crate) fn healthy(&self) -> bool { self.healthy.load(Ordering::Acquire) } + + /// Queue a packet; the poll work publishes and retires it. + pub(crate) fn submit(self: &Arc, packet: Arc) -> Result { + if !self.healthy() { return Err(EIO); } + if packet.commands.is_empty() { + return Err(ENOTSUPP); + } + { + let mut guard = self.state.lock(); + let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; + state.pending.push((packet, 0), GFP_KERNEL)?; + self.pump(state); + } + self.schedule(1); + Ok(()) + } + + /// Withdraw a packet's unpublished commands; published ones retire normally. + pub(crate) fn withdraw(&self, packet: &Arc) { + let mut guard = self.state.lock(); + if let Some(state) = Option::as_mut(&mut *guard) { + if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { + let _ = state.pending.remove(i); + } + if !state.inflight.iter().any(|f| Arc::ptr_eq(&f.packet, packet)) { + packet.release_guard(); + } + } + } + + fn fail_all(&self, state: &mut State, error: Error) { + self.healthy.store(false, Ordering::Release); + for (packet, _) in state.pending.drain(..) { + packet.release_guard(); + packet.finish(Err(error)); + } + // Published work stays owned: the firmware may still read it. + for f in state.inflight.iter() { + if let Some(status) = f.packet.vm.status() { status.record(error); } + f.packet.finish(Err(error)); + } + } + + /// Publish pending commands while pool slots are free. + fn pump(&self, state: &mut State) { + while state.inflight.len() < J413_POOL - 1 && !state.pending.is_empty() { + // A slot is reused only once the firmware has unlinked it (tracking list). + match state.pool.registered(state.next_slot) { + Ok(false) => {} + Ok(true) => { + if !state.waiting_unlink { + state.waiting_unlink = true; + dev_info!(self.dev, "J413: slot {} still in the firmware's tracking list; waiting\n", state.next_slot); + state.pool.dump(&self.dev, state.next_slot); + // Wake the firmware's service so its retirement scan runs. + let _ = state.peer.as_mut().send_message(0x21, G14TrialRoot::j413_kick()); + } + return; + } + Err(e) => { self.fail_all(state, e); return; } + } + state.waiting_unlink = false; + 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)); + continue; + }; + let result = (|| -> Result<(mmu::VmBind, event::EventValue)> { + let bind = self.graph.trial_uat().bind(&packet.vm)?; + let preempt = packet.j413_preempt.as_ref().ok_or(EINVAL)?.gpu_va().get(); + let stamp = state.last.next(); + let job = J413Compute { + context: bind.slot(), + sequence: state.sequence, + cdm_base: control.base, + cdm_end: control.end, + usc_base: control.usc_base, + preempt, + }; + let command = state.pool.encode(state.next_slot, &state.queue, stamp.raw(), &job)?; + packet.mark_published(); + state.root.j413_publish(command)?; + state.peer.as_mut().send_message(0x21, G14TrialRoot::j413_kick())?; + Ok((bind, stamp)) + })(); + match result { + Ok((bind, stamp)) => { + state.last = stamp; + state.sequence += 1; + let slot = state.next_slot; + state.published += 1; + let ordinal = state.published; + state.next_slot = (state.next_slot + 1) % J413_POOL; + 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); + return; + } + if last { let _ = state.pending.remove(0); } else { state.pending[0].1 += 1; } + } + Err(e) => { + dev_err!(self.dev, "J413: compute publication failed {:?}\n", e); + let _ = state.pending.remove(0); + if packet.may_be_published() && index != 0 { + // Earlier commands of this packet are in flight; fail it when they retire. + packet.finish(Err(e)); + } else { + packet.release_guard(); + packet.finish(Err(e)); + } + } + } + } + } + + /// Retire completed commands, publish more, keep the firmware's rings drained. + /// Returns whether work remains. + fn service(&self) -> bool { + let mut guard = self.state.lock(); + let Some(state) = Option::as_mut(&mut *guard) else { return false; }; + let _ = state.root.drain_statistics(); + if state.peer.is_crashed() { + dev_err!(self.dev, "J413: GPU firmware crashed; failing {} pending and {} published commands\n", + state.pending.len(), state.inflight.len()); + self.fail_all(state, EIO); + return false; + } + let (current, raw) = match state.root.j413_progress() { + Ok((_, raw, current)) => (current, raw), + Err(e) => { self.fail_all(state, e); return false; } + }; + if state.capacity != 0 && raw < state.capacity { + let delta = (raw + state.capacity - state.retired_raw) % state.capacity; + state.retired_total += u64::from(delta); + state.retired_raw = raw; + } + while !state.inflight.is_empty() { + let front = &state.inflight[0]; + if state.retired_total >= front.ordinal { + let done = state.inflight.remove(0).ok(); + if let Some(done) = done { + if let Err(e) = state.pool.retire(done.slot) { + dev_err!(self.dev, "J413: tracking retirement failed {:?}\n", e); + } + state.retired += 1; + if done.last { + done.packet.retired(); + } + } + continue; + } + if front.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + let (head, retired, _) = state.root.j413_progress().unwrap_or((0, 0, current)); + dev_err!(self.dev, "J413: compute command timed out: stamp={:#x} expected={:#x} head={} retired={} submitted={} completed={}\n", + current.raw(), front.stamp.raw(), head, retired, state.submitted, state.retired); + // Diagnostics, all read-only: work records, MMU fault latch, private scheduler words. + let _ = state.root.report_job_gates("drm-timeout"); + fault_latch(&self.dev); + let _ = crate::mmu::t8112_private_scan(&self.dev, &state.root.job_anchors(), 3); + let _ = state.root.j413_trace_tail(48); + let _ = state.root.j413_rings(); + let stuck = state.inflight[0].slot; + state.root.j413_record((state.inflight[0].stamp.raw() >> 8) as usize); + state.root.j413_record((state.inflight[0].stamp.raw() >> 8) as usize - 1); + state.pool.dump(&self.dev, stuck); + state.pool.dump(&self.dev, 0); + state.pool.dump(&self.dev, (stuck + 1) % J413_POOL); + self.fail_all(state, ETIMEDOUT); + return false; + } + break; + } + if self.healthy() { self.pump(state); } + !state.inflight.is_empty() || !state.pending.is_empty() + } + + /// Stop the firmware: retire or fail outstanding work, allow power-off, then halt the ASC + /// with every mapping still in place (normal stop, forced stop as fallback). + pub(crate) fn stop(&self) { + let start = Instant::::now(); + while start.elapsed() < Delta::from_millis(2000) { + if !self.service() { break; } + kernel::time::delay::fsleep(Delta::from_millis(1)); + } + self.healthy.store(false, Ordering::Release); + // No poll work may remain queued or running once this returns. + let start = Instant::::now(); + while self.queued.load(Ordering::Acquire) != 0 && start.elapsed() < Delta::from_millis(2000) { + kernel::time::delay::fsleep(Delta::from_millis(5)); + } + // Let a run that just accounted for itself return out of this module. + kernel::time::delay::fsleep(Delta::from_millis(20)); + let mut guard = self.state.lock(); + let Some(mut state) = guard.take() else { return; }; + self.fail_all(&mut state, ENODEV); + let root = &state.root; + let allowed = (|| -> Result { + let (target, generation) = root.publish_idle_policy(true)?; + state.peer.as_mut().send_message(0x21, 0x0084_0000_0000_0011)?; + let start = Instant::::now(); + while root.idle_progress()? != [target; 3] || root.idle_acknowledgement()? != generation { + if start.elapsed() >= Delta::from_millis(500) { return Err(ETIMEDOUT); } + let _ = root.drain_statistics(); + kernel::time::delay::fsleep(Delta::from_millis(1)); + } + Ok(()) + })(); + let start = Instant::::now(); + while root.firmware_running() != Ok(0) && start.elapsed() < Delta::from_millis(500) { + let _ = root.drain_statistics(); + kernel::time::delay::fsleep(Delta::from_millis(1)); + } + let running = root.firmware_running(); + let forced = if running != Ok(0) { + // SAFETY: the RTKit instance is live and owned here. + Some(kernel::error::to_result(unsafe { + kernel::bindings::apple_rtkit_poweroff(state.peer.as_raw()) + })) + } else { + None + }; + state.asc.write(0x44, state.asc.read(0x44) & !0x10); + dev_info!(self.dev, "J413: GPU stopped: allow-off={:?} status+0x10={:?} forced={:?} ASC={:#x} submitted={} completed={}\n", + allowed, running, forced, state.asc.read(0x44), state.submitted, state.retired); + // Keep everything the firmware could reach for the rest of the boot, halted or not: its + // page tables still name these pages, and a bring-up leak is cheaper than a stray write. + core::mem::forget(state); + core::mem::forget(self.graph.clone()); + if running != Ok(0) && forced != Some(Ok(())) { + dev_err!(self.dev, "J413: firmware did not stop; memory retained, a reset is required\n"); + } + } +} + +/// Logs the G14 MMU fault latch (read-only). +fn fault_latch(dev: &device::Device) { + // SAFETY: SGX register page holding the G14 MMU fault latch, read once. + let latch = unsafe { + let p = kernel::bindings::ioremap(0x204000000 + 0x17000, 0x1000); + if p.is_null() { u64::MAX } else { + let lo = kernel::bindings::readl(p.cast::().add(0x30).cast()) as u64; + let hi = kernel::bindings::readl(p.cast::().add(0x34).cast()) as u64; + kernel::bindings::iounmap(p); + lo | hi << 32 + } + }; + dev_err!(dev, "J413: fault latch={:#x} valid={} reason={} client={} address={:#x}\n", + latch, latch & 1, (latch >> 1) & 7, (latch >> 9) & 0xff, (latch >> 24) & !0x3f); +} + +/// Halts firmware that no runtime owns yet (allow-off, then RTKit power-off, then the ASC run +/// bit), and retains every object it could reach. +fn halt_unowned( + dev: &device::Device, + mut peer: Pin>>, + root: crate::fw::types::GpuObject, + asc: AscControl, +) { + let allowed = (|| -> Result { + let (target, generation) = root.publish_idle_policy(true)?; + peer.as_mut().send_message(0x21, 0x0084_0000_0000_0011)?; + let start = Instant::::now(); + while root.idle_progress()? != [target; 3] || root.idle_acknowledgement()? != generation { + if start.elapsed() >= Delta::from_millis(500) { return Err(ETIMEDOUT); } + kernel::time::delay::fsleep(Delta::from_millis(1)); + } + Ok(()) + })(); + // SAFETY: the RTKit instance is live and owned here. + let forced = kernel::error::to_result(unsafe { kernel::bindings::apple_rtkit_poweroff(peer.as_raw()) }); + asc.write(0x44, asc.read(0x44) & !0x10); + dev_err!(dev, "J413: firmware halted after a failed take-over: allow-off={:?} power-off={:?} ASC={:#x}\n", + allowed, forced, asc.read(0x44)); + core::mem::forget(peer); + core::mem::forget(root); + core::mem::forget(asc); +} + +pub(crate) struct Backend { + graph: Arc, + runtime: Arc, + scheduler: Arc>, + ids: gpu::SequenceIDs, +} + +impl Backend { + /// Takes over the running firmware from the bring-up path. + pub(crate) fn start( + drm: &crate::driver::AsahiDrmDevice, + dev: &device::Device, + peer: Pin>>, + root: crate::fw::types::GpuObject, + graph: Arc, + pool: J413Pool, + asc: AscControl, + ) -> Result> { + // The runtime is created empty first, so no allocation failure can drop firmware-visible + // state. Every failure after the state is moved in goes through Runtime::stop, which halts + // the firmware and retains all of its memory. + let runtime_graph = graph.clone(); + let runtime = match Arc::pin_init(try_pin_init!(Runtime { + dev: dev.into(), + graph: runtime_graph, + healthy: AtomicBool::new(true), + queued: AtomicU32::new(0), + state <- new_mutex!(None, "j413::Runtime::state"), + poll <- new_delayed_work!("j413::Runtime::poll"), + }), GFP_KERNEL) { + Ok(runtime) => runtime, + Err(e) => { + dev_err!(dev, "J413: runtime allocation failed {:?}; halting the firmware\n", e); + halt_unowned(dev, peer, root, asc); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + }; + let checked = (|| -> Result<(J413Queue, event::EventValue, u32, u32)> { + let (queue, last) = root.j413_queue()?; + let (head, retired, _) = root.j413_progress()?; + if head != retired { return Err(EBUSY); } + Ok((queue, last, head, root.j413_capacity()?)) + })(); + let (queue, last, head, capacity) = match checked { + Ok(v) => v, + Err(e) => { + dev_err!(dev, "J413: take-over refused {:?}; halting the firmware\n", e); + halt_unowned(dev, peer, root, asc); + core::mem::forget(pool); + core::mem::forget(graph); + return Err(e); + } + }; + dev_info!(dev, "J413: taking over the running firmware: queue={:#x} head={} stamp={:#x}\n", + queue.queue, head, last.raw()); + *runtime.state.lock() = Some(State { + peer, root, pool, asc, queue, last, + sequence: u64::from(head), + next_slot: 0, + waiting_unlink: false, + published: 0, + retired_total: 0, + retired_raw: head, + capacity, + inflight: KVec::new(), + pending: KVec::new(), + submitted: 0, + retired: 0, + }); + if crate::module_parameters::t8112_drm_ring_skew.value() { + // Diagnostic: offset the submission ring by one entry against the stamps. + let mut guard = runtime.state.lock(); + if let Some(state) = Option::as_mut(&mut *guard) { + let r = state.root.j413_publish_entry() + .and_then(|_| state.peer.as_mut().send_message(0x21, G14TrialRoot::j413_kick())); + dev_info!(dev, "J413: ring skew entry {:?}\n", r); + } + } + runtime.schedule(IDLE_POLL_MS); + let scheduler = match sched::Scheduler::new(drm.as_ref().as_ref(), 4, J413_POOL as u32 - 1, 0, 10000, + c"asahi_j413_sched").and_then(|s| Arc::new(s, GFP_KERNEL).map_err(Into::into)) { + Ok(scheduler) => scheduler, + Err(e) => { + dev_err!(dev, "J413: scheduler setup failed {:?}; stopping the firmware\n", e); + runtime.stop(); + return Err(e); + } + }; + match Arc::new(Self { graph, runtime: runtime.clone(), scheduler, ids: gpu::SequenceIDs::default() }, GFP_KERNEL) { + Ok(backend) => Ok(backend), + Err(e) => { runtime.stop(); Err(e.into()) } + } + } + + pub(crate) fn stop(&self) { self.runtime.stop(); } +} + +impl Drop for Backend { + fn drop(&mut self) { self.runtime.stop(); } +} + +impl gpu::Gpu for Backend { + fn stats_snapshot(&self) -> Option> { None } + fn as_any(&self) -> &dyn core::any::Any { self } + fn arc_as_any(self: Arc) -> Arc { self as Arc } + fn manager(&self) -> Option<&dyn gpu::GpuManager> { None } + fn init(&self) -> Result { if self.runtime.healthy() { Ok(()) } else { Err(ENODEV) } } + fn ids(&self) -> &gpu::SequenceIDs { &self.ids } + fn is_crashed(&self) -> bool { !self.runtime.healthy() } + fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result { + ::get_params(&self.graph, params)?; + params.max_commands_per_submission = crate::m3::agx_uapi::UAPI_MAX_HARDWARE_COMMANDS; + params.max_attachments = crate::m3::agx_uapi::UAPI_MAX_ATTACHMENTS as u32; + Ok(()) + } + fn supports_vm_status(&self) -> bool { true } + fn feature_flags(&self) -> u64 { + uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_VM_STATUS as u64 + | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_SCHEDULED_QUEUES as u64 + } + fn tracked_submission(&self) -> bool { true } + fn base_clock_hz(&self) -> u32 { ::base_clock_hz(&self.graph) } + fn uat_geometry(&self) -> mmu::UatGeometry { ::uat_geometry(&self.graph) } + fn new_vm(&self, range: Range) -> Result { + self.graph.trial_uat().new_vm(self.ids.vm.next(), range)?.with_tracked_status() + } + fn new_queue(&self, vm: mmu::Vm, _ualloc: Arc>, + ualloc_priv: Arc>, priority: u32, + usc_exec_base: u64, _usage: Arc) -> Result> { + Ok(KBox::new(crate::m3::m3_submit::Queue::new_j413(self.runtime.clone(), self.scheduler.clone(), + vm, priority, usc_exec_base, ualloc_priv)?, GFP_KERNEL)?) + } + fn map_timestamp_buffer(&self, _bo: gem::ObjectRef, _range: Range) -> Result { + // Timestamp buffers would need new tables in the firmware window after boot. + Err(ENOTSUPP) + } +} diff --git a/drivers/gpu/drm/asahi/m3/m3_channel_format.rs b/drivers/gpu/drm/asahi/m3/m3_channel_format.rs index 45eebda112b73..d3cc240e898cb 100644 --- a/drivers/gpu/drm/asahi/m3/m3_channel_format.rs +++ b/drivers/gpu/drm/asahi/m3/m3_channel_format.rs @@ -7,6 +7,27 @@ use super::m3_init_layout::Error; pub(crate) const CONTROL_BYTES: usize = 64; pub(crate) const RECEIVE_BYTES: usize = 72; pub(crate) const SLOTS: u32 = 256; +pub(crate) const SUBMISSION_BYTES: usize = 0x18; +/// Two firmware engine classes for each of the three data masters. +pub(crate) const ENGINE_CLASSES: u32 = 6; + +/// Wire entry shared by G15G 26.6.2 and G14G 26B123. The caller owns the queue +/// and publishes its contents before advancing the channel's shared write index. +pub(crate) fn submission_entry( + selector: u32, queue: u64, position: u16, stamp: u8, first: bool, +) -> Result<[u8; SUBMISSION_BYTES], Error> { + if selector > 2 { + return Err(Error::Bounds); + } + let mut entry = [0; SUBMISSION_BYTES]; + entry[8..16].copy_from_slice(&queue.to_le_bytes()); + entry[16..20].copy_from_slice(&selector.to_le_bytes()); + entry[20..22].copy_from_slice(&position.to_le_bytes()); + entry[22] = stamp; + entry[23] = u8::from(first); + Ok(entry) +} + #[derive(Clone, Copy, Debug)] pub(crate) enum Action { @@ -163,6 +184,18 @@ mod tests { assert!(payload_offset(9, 0).is_err()); } + #[test] + fn first_and_reused_compute_entries_match_the_26b123_wire_format() { + let expected = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0x40, 0x12, 0x34, 0xa0, 0xff, 0xff, + 0xff, 2, 0, 0, 0, 0x23, 1, 7, 1]; + let queue = 0xffff_ffa0_3412_4000; + assert_eq!(submission_entry(2, queue, 0x123, 7, true).unwrap(), expected); + let reused = submission_entry(2, queue, 0x123, 7, false).unwrap(); + assert_eq!(&reused[..23], &expected[..23]); + assert_eq!(reused[23], 0); + assert!(submission_entry(3, queue, 0, 0, true).is_err()); + } + #[test] fn release_uses_the_packed_owned_pointer() { let action = Action::Release { diff --git a/drivers/gpu/drm/asahi/m3/m3_config.rs b/drivers/gpu/drm/asahi/m3/m3_config.rs index 02b847e210dc9..3d3550909399b 100644 --- a/drivers/gpu/drm/asahi/m3/m3_config.rs +++ b/drivers/gpu/drm/asahi/m3/m3_config.rs @@ -305,12 +305,9 @@ impl Config { let state=kind*2;let ring=state+1; let w=self.objects[state].read_u32(0x20)?; if w>=256 || self.objects[state].read_u32(0)?!=w { return Err(EBUSY); } - let mut message=[0u8;0x18]; - message[8..16].copy_from_slice(&queue.to_le_bytes()); - message[16..20].copy_from_slice(&(kind as u32).to_le_bytes()); - message[20..22].copy_from_slice(&head.to_le_bytes()); - message[22]=event;message[23]=u8::from(new); // New queue; caller selected the event slot. - self.objects[ring].write(w as usize*0x18,&message)?; + let message = super::m3_channel_format::submission_entry(kind as u32, queue, head, event, new) + .map_err(|_| EINVAL)?; + self.objects[ring].write(w as usize * message.len(), &message)?; agx_memory::publish(); self.objects[state].u32(0x20,(w+1)%256)?; agx_memory::publish(); diff --git a/drivers/gpu/drm/asahi/m3/m3_init_26.rs b/drivers/gpu/drm/asahi/m3/m3_init_26.rs index a86432b2bbe2b..0c71ddc8bc71a 100644 --- a/drivers/gpu/drm/asahi/m3/m3_init_26.rs +++ b/drivers/gpu/drm/asahi/m3/m3_init_26.rs @@ -19,11 +19,24 @@ pub(crate) const LOG_THREADS: usize = 9; pub(crate) const RX_BYTES: usize = 0x48; pub(crate) const LOG_PAYLOAD_BYTES: usize = 0xd8; +/// The shared cache-flush ring has separate index and entry addresses on the wire. +pub(crate) fn write_flush_ring( + bytes: &mut [u8], offset: usize, state: u64, entries: u64, +) -> Result<(), Error> { + if state == 0 || entries == 0 || (state | entries) & 0x3f != 0 { + return Err(Error::Address); + } + let pair = bytes.get_mut(offset..).and_then(|s| s.get_mut(..16)).ok_or(Error::Size)?; + pair[..8].copy_from_slice(&state.to_le_bytes()); + pair[8..].copy_from_slice(&entries.to_le_bytes()); + Ok(()) +} + /// Extend the existing M3 owner indices instead of introducing another owner graph. pub(crate) fn allocation(index: usize) -> Result { let size = match index { 0..=23 if index % 2 == 0 => 0x30, - 0..=23 => 0x1800, + 0..=23 => super::m3_channel_format::SLOTS as usize * super::m3_channel_format::SUBMISSION_BYTES, 24 | 26 | 30 | 32 => 0x30, 25 => 0x4000, 27 | 33 => 0x4800, @@ -65,6 +78,30 @@ pub(crate) fn cached(index: usize) -> bool { matches!(index, 39 | PERFORMANCE_CONTROL) } +/// Thirteen TX descriptors and four RX state/ring pairs. Both the extended +/// M3 profile and the adjacent G14G profile use these directory offsets. +/// The caller owns all 34 buffers through firmware stop. +pub(crate) fn write_channels(bytes: &mut [u8], addresses: &[u64; 34]) -> Result<(), Error> { + if bytes.len() < 0x200 || addresses.contains(&0) { + return Err(Error::Bounds); + } + let pointer = |bytes: &mut [u8], offset, value: u64| { + bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); + }; + for channel in 0..13 { + let offset = 0x20 + channel * 0x20; + let state = addresses[channel * 2]; + pointer(bytes, offset, state); + pointer(bytes, offset + 8, state + 0x10); + pointer(bytes, offset + 16, state + 0x20); + pointer(bytes, offset + 24, addresses[channel * 2 + 1]); + } + for (index, &address) in addresses[26..].iter().enumerate() { + pointer(bytes, 0x1c0 + index * 8, address); + } + Ok(()) +} + pub(crate) struct PointerGraph<'a> { pub(crate) owners: &'a [Region; COUNT], pub(crate) scratch: Region, @@ -155,14 +192,6 @@ impl PointerGraph<'_> { for (offset, owner) in [ (0, storage::HARDWARE_DATA), (0x10, storage::UNKNOWN_PAIR), - (0x1c0, 26), - (0x1c8, 27), - (0x1d0, 28), - (0x1d8, 29), - (0x1e0, 30), - (0x1e8, 31), - (0x1f0, 32), - (0x1f8, 33), (0x200, storage::FWLOG_PAYLOAD), (0x254, storage::UNKNOWN_C0), (0x25c, storage::UNKNOWN_C1), @@ -174,14 +203,7 @@ impl PointerGraph<'_> { ] { pointer(bytes, offset, addresses[owner]); } - for channel in 0..13 { - let offset = 0x20 + channel * 0x20; - let state = addresses[channel * 2]; - pointer(bytes, offset, state); - pointer(bytes, offset + 8, state + 0x10); - pointer(bytes, offset + 16, state + 0x20); - pointer(bytes, offset + 24, addresses[channel * 2 + 1]); - } + write_channels(bytes, addresses[..34].try_into().map_err(|_| Error::Bounds)?)?; Ok(()) } @@ -191,8 +213,8 @@ impl PointerGraph<'_> { .get_mut(..allocation(storage::CONTROL_REGION)?.size) .ok_or(Error::Size)?; bytes.fill(0); - bytes[0x4f88..0x4f90].copy_from_slice(&addresses[storage::FW_CONTROL_STATE].to_le_bytes()); - bytes[0x4f90..0x4f98].copy_from_slice(&addresses[storage::FW_CONTROL_RING].to_le_bytes()); + write_flush_ring(bytes, 0x4f88, addresses[storage::FW_CONTROL_STATE], + addresses[storage::FW_CONTROL_RING])?; bytes[0x4fd4..0x4fd8].copy_from_slice(&1u32.to_le_bytes()); Ok(()) } @@ -202,6 +224,17 @@ impl PointerGraph<'_> { mod tests { use super::*; + #[test] + fn j413_empty_flush_ring_publishes_both_views() { + let mut control = [0u8; 0x4bf8]; + let base = 0xffff_ffa8_0010_0000; + write_flush_ring(&mut control, 0x4be0, base, base + 0x40).unwrap(); + assert_eq!(&control[0x4be0..0x4be8], &base.to_le_bytes()); + assert_eq!(&control[0x4be8..0x4bf0], &(base + 0x40).to_le_bytes()); + assert_eq!(&control[0x4bf0..], &[0; 8]); + assert!(write_flush_ring(&mut control[..0x4be8], 0x4be0, base, base + 0x40).is_err()); + } + fn owners(delta: u64) -> [Region; COUNT] { core::array::from_fn(|index| { let item = allocation(index).unwrap(); diff --git a/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs b/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs index a17bc0ee399c3..31e463f6cd1ec 100644 --- a/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs +++ b/drivers/gpu/drm/asahi/m3/m3_mmio_26.rs @@ -142,6 +142,12 @@ pub(crate) fn encode( } _ => return Err(Error::Address), }; + write_record(output, physical, va, bytes, requested, register, mode) +} + +/// Common 0x28-byte record used by the single-role G14G and G15G interfaces. +pub(crate) fn write_record(output: &mut [u8], physical: u64, va: u64, bytes: u32, + requested: u32, register: u64, mode: u64) -> Result<(), Error> { let bytes_out = output.get_mut(..RECORD_BYTES).ok_or(Error::Size)?; bytes_out.fill(0); bytes_out[0..8].copy_from_slice(&physical.to_le_bytes()); diff --git a/drivers/gpu/drm/asahi/m3/m3_runtime.rs b/drivers/gpu/drm/asahi/m3/m3_runtime.rs index 762c8bc26e75b..1ffe3c1c7ddfc 100644 --- a/drivers/gpu/drm/asahi/m3/m3_runtime.rs +++ b/drivers/gpu/drm/asahi/m3/m3_runtime.rs @@ -1304,7 +1304,7 @@ impl Runtime { self.retire_extended_control(first)?; self.inner.boot_step = BootStep::DeviceControl; // Each data master registers its two firmware engine classes. - for ordinal in 0..6 { + for ordinal in 0..super::m3_channel_format::ENGINE_CLASSES { let action = Action::Register { pipe: ordinal / 2, engine: ordinal % 2 + 1 }; self.send_extended_control(action)?; } diff --git a/drivers/gpu/drm/asahi/m3/m3_submit.rs b/drivers/gpu/drm/asahi/m3/m3_submit.rs index 155bda714e9d9..307acf9ac5bda 100644 --- a/drivers/gpu/drm/asahi/m3/m3_submit.rs +++ b/drivers/gpu/drm/asahi/m3/m3_submit.rs @@ -2,6 +2,7 @@ //! Bounded M3 compute and graphics submissions through the common DRM scheduler/syncobjs. use kernel::{c_str,dma_fence::*,drm::sched,prelude::*,sync::{Arc,Mutex},new_mutex,xarray}; use crate::{file,m3::agx_uapi,mmu,queue,m3::m3_drm::Shared}; +use crate::alloc::Allocator as _; use core::sync::atomic::{AtomicBool, Ordering}; #[derive(Default)] pub(crate) struct Completion; @@ -53,7 +54,12 @@ pub(crate) struct Packet { /// Who submitted the packet, for the failure log only. pub(crate) owner:Owner, vm_job:Pin>>>, + /// J413 27.2: the compute preemption buffer in the packet's VM, kept until retirement. + pub(crate) j413_preempt:Option>, } +/// The runtime a queue's packets go to: the M3 runtime or the J413 27.2 compute runtime. +#[derive(Clone)] +pub(crate) enum Sink { M3(Shared), J413(Arc) } /// The process and thread that submitted a packet, recorded in the submit ioctl. Only logged: /// a renamed task leaves a stale name, which is harmless. #[derive(Copy,Clone)] @@ -118,9 +124,9 @@ impl Packet { } } } -pub(crate) struct Job {shared:Shared,packet:Arc} +pub(crate) struct Job {shared:Sink,packet:Arc} /// Timeout state of a [`Job`], owned by the scheduler's timeout worker. -pub(crate) struct JobTimeout {shared:Shared,packet:Arc} +pub(crate) struct JobTimeout {shared:Sink,packet:Arc} impl sched::JobImpl for Job { type TimeoutData = JobTimeout; fn timeout_data(&self)->JobTimeout { @@ -129,7 +135,11 @@ impl sched::JobImpl for Job { fn run(job:&mut Self)->Result> { // Queue the packet and return its fence; the completion worker publishes and retires // it, so the scheduler can hand over further ready jobs meanwhile. - if let Err(e)=crate::m3::m3_runtime::Runtime::submit(&job.shared,job.packet.clone()) { + let submitted=match &job.shared { + Sink::M3(shared)=>crate::m3::m3_runtime::Runtime::submit(shared,job.packet.clone()), + Sink::J413(runtime)=>runtime.submit(job.packet.clone()), + }; + if let Err(e)=submitted { pr_err!("M3 scheduler: submission failed {:?}\n",e); // submit() failed before this packet could be published. job.packet.release_guard();job.packet.finish(Err(e)); @@ -137,13 +147,23 @@ impl sched::JobImpl for Job { Ok(Some(Fence::from_fence(&job.packet.completion))) } fn timed_out(job:&mut JobTimeout,_finished:bool)->sched::Status { + let shared=match &job.shared { + Sink::M3(shared)=>shared.clone(), + Sink::J413(runtime)=>{ + // The runtime's own command timeout fails a hung GPU; a healthy one is late. + if runtime.healthy() {return sched::Status::NoHang;} + runtime.withdraw(&job.packet); + job.packet.finish(Err(EIO)); + return sched::Status::NoDevice; + } + }; // Retain the publishing branch's explicit diagnostic override. if !crate::m3::m3_params::timeout_nohang() { - if let Some(r)=Option::as_mut(&mut *job.shared.lock()) {r.health().mark_failed();} - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + if let Some(r)=Option::as_mut(&mut *shared.lock()) {r.health().mark_failed();} + crate::m3::m3_runtime::Runtime::withdraw(&shared,&job.packet); job.packet.finish(Err(ETIMEDOUT));return sched::Status::NoDevice; } - let guard=job.shared.lock(); + let guard=shared.lock(); let Some(runtime)=guard.as_ref() else { job.packet.finish(Err(ENODEV)); return sched::Status::NoDevice; @@ -154,12 +174,15 @@ impl sched::JobImpl for Job { // device loss or corrupting an already signaled fence. if runtime.health().healthy() { return sched::Status::NoHang; } drop(guard); - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + crate::m3::m3_runtime::Runtime::withdraw(&shared,&job.packet); job.packet.finish(Err(EIO)); sched::Status::NoDevice } fn cancel(job:&mut Self) { - crate::m3::m3_runtime::Runtime::withdraw(&job.shared,&job.packet); + match &job.shared { + Sink::M3(shared)=>{crate::m3::m3_runtime::Runtime::withdraw(shared,&job.packet);} + Sink::J413(runtime)=>runtime.withdraw(&job.packet), + } job.packet.finish(Err(ECANCELED)); } } @@ -175,7 +198,9 @@ impl agx_uapi::GpuAddressSpace for AddressSpace<'_> { } pub(crate) struct Queue { entity:sched::Entity,_scheduler:Arc>, - shared:Shared,vm:mmu::Vm,usc:u64,fences:FenceContexts, + shared:Sink,vm:mmu::Vm,usc:u64,fences:FenceContexts, + /// J413: the VM's private allocator, for per-packet preemption buffers. + j413_alloc:Option>>, /// Whether the SoC advertises early tiling (`m3_soc::Features::fragment_dependency`). early_tiling:bool, wide_visibility:bool, @@ -190,8 +215,19 @@ impl Queue { let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, - shared,vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, - early_tiling,wide_visibility,urgency}) + shared:Sink::M3(shared),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_m3_queue"),kernel::static_lock_class!())?, + early_tiling,wide_visibility,urgency,j413_alloc:None}) + } + /// A J413 27.2 compute queue: the same front end, published by the J413 runtime. + pub(crate) fn new_j413(runtime:Arc,scheduler:Arc>,vm:mmu::Vm,priority:u32,usc:u64, + ualloc_priv:Arc>)->Result { + agx_uapi::QueueUscWindow{base:usc,user_start:0x4000,user_end:(1u64<<42)-0x8000}.validate().map_err(|_|EINVAL)?; + let urgency=3u8.saturating_sub(priority.min(3) as u8); + let priority=match priority {3=>sched::Priority::Low,2=>sched::Priority::Normal, + 1=>sched::Priority::High,0=>sched::Priority::Kernel,_=>return Err(EINVAL)}; + Ok(Self {entity:sched::Entity::new(&scheduler,priority)?,_scheduler:scheduler, + shared:Sink::J413(runtime),vm,usc,fences:FenceContexts::new(1,c_str!("asahi_j413_queue"),kernel::static_lock_class!())?, + early_tiling:false,wide_visibility:false,urgency,j413_alloc:Some(ualloc_priv)}) } } impl queue::Queue for Queue { @@ -199,13 +235,15 @@ impl queue::Queue for Queue { raw:&[u8],objects:Pin<&xarray::XArray>>)->Result { let vm_job=self.vm.retain_job()?; let mut parser=agx_uapi::UapiCommandParser::new(raw);let mut commands=KVec::new();let mut timestamps=KVec::new();let mut flushes=KVec::new();let mut visibility=KVec::new();let mut render_attachments=KVec::new(); - while let Some(command)=parser.next_hardware().map_err(|_|EINVAL)? { + while let Some(command)=parser.next_hardware().map_err(|e|{pr_err!("asahi submit: command parse rejected {:?} (cmdbuf {} bytes)\n",e,raw.len());EINVAL})? { if let agx_uapi::ParsedHardwareCommand::Render{payload,vertex_attachments,fragment_attachments,..}=command { + // The J413 27.2 backend is compute-only. + if self.j413_alloc.is_some() {return Err(EINVAL);} if let Err(e)=validate_render(payload,self.usc,&AddressSpace(&self.vm),self.early_tiling) { pr_err!("M3 render rejected {:?}: flags={:#x} size={}x{} layers={} samples={} utile={}x{} sample_size={} depth={:#x} stencil={:#x} zls={:#x} samplers={} heap={:#x}\n",e,payload.flags,payload.width,payload.height,payload.layers,payload.samples,payload.utile_width,payload.utile_height,payload.sample_size,payload.depth.base,payload.stencil.base,payload.zls_control,payload.sampler_count,payload.sampler_heap); return Err(e); } - agx_uapi::validate_attachments(&AddressSpace(&self.vm),&vertex_attachments).map_err(|_|EINVAL)?; + agx_uapi::validate_attachments(&AddressSpace(&self.vm),&vertex_attachments).map_err(|e|{pr_err!("asahi submit: attachments rejected {:?}\n",e);EINVAL})?; agx_uapi::validate_attachments(&AddressSpace(&self.vm),&fragment_attachments).map_err(|_|EINVAL)?; commands.push(Command::Render{command:payload,usc:self.usc},GFP_KERNEL)?; timestamps.push([Destination::resolve(objects,payload.vertex_timestamps.start)?, @@ -237,13 +275,22 @@ impl queue::Queue for Queue { pr_err!("M3 compute translation rejected {:?}: stream={:#x}..{:#x} helper={:?}\n",e,payload.control_stream_base,payload.control_stream_end,payload.helper); EINVAL })?; - crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; + // The launch check decodes the 26.x G15 CDM launch format; G14 (J413) streams differ. + if self.j413_alloc.is_none() { + crate::m3::m3_client::check_compute_launches(&self.vm,&AddressSpace(&self.vm),c.control_stream_base,c.control_stream_end)?; + } timestamps.push([Destination::resolve(objects,payload.timestamps.start)?, Destination::resolve(objects,payload.timestamps.end)?,None,None],GFP_KERNEL)?; commands.push(Command::Compute(crate::m3::agx_compute::Control{base:c.control_stream_base,end:c.control_stream_end,usc_base:self.usc}),GFP_KERNEL)?; } - parser.finish().map_err(|_|EINVAL)?; - let packet=Arc::new(Packet{vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, + parser.finish().map_err(|e|{pr_err!("asahi submit: command buffer trailer rejected {:?}\n",e);EINVAL})?; + // 13.5 compute preemption buffer: buffer 1 of compute_preempt1_size, then four words. + let j413_preempt=match &self.j413_alloc { + Some(alloc) if commands.iter().any(|c| matches!(c, Command::Compute(_))) => + Some(alloc.lock().array_empty::(crate::hw::t8112::HWCONFIG.compute_preempt1_size + 0x20)?), + _ => None, + }; + let packet=Arc::new(Packet{j413_preempt,vm:self.vm.clone(),commands,timestamps,attachments:flushes,wide_visibility:visibility,render_attachments, completion:self.fences.new_fence(0,Completion)?.into(), finish_claimed:AtomicBool::new(false),published:AtomicBool::new(false),urgency:self.urgency,owner:Owner::current(), vm_job:KBox::pin_init(new_mutex!(Some(vm_job)),GFP_KERNEL)?},GFP_KERNEL)?; diff --git a/drivers/gpu/drm/asahi/m3/mod.rs b/drivers/gpu/drm/asahi/m3/mod.rs index eafd5732bceac..a1fc96609c3ef 100644 --- a/drivers/gpu/drm/asahi/m3/mod.rs +++ b/drivers/gpu/drm/asahi/m3/mod.rs @@ -81,7 +81,7 @@ mod agx_resources; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod agx_status; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod agx_uapi; +pub(crate) mod agx_uapi; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod g15_raw; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] @@ -125,7 +125,7 @@ mod m3_rtkit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_runtime; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] -mod m3_submit; +pub(crate) mod m3_submit; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_thermal; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] @@ -162,6 +162,7 @@ mod m3_scene_layout; mod m3_shared_layout; mod m3_state_layout; +pub(crate) use m3_state_layout::EXTENDED_NOTIFIER_SIZE; mod m3_sync_layout; @@ -201,11 +202,13 @@ pub(crate) mod m3_soc; mod t8122_hwdata; -mod m3_init_26; +pub(crate) mod m3_init_26; mod m3_profile; -mod m3_mmio_26; +pub(crate) mod m3_mmio_26; #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] mod m3_power_26; -mod m3_channel_format; +pub(crate) mod m3_channel_format; +pub(crate) use m3_channel_format::{idle_cursor, payload_offset, submission_entry, Action, CONTROL_BYTES, ENGINE_CLASSES}; +pub(crate) use m3_init_storage::DEVICE_CONTROL; diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 4337024993025..8d3e7209596e8 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -123,6 +123,8 @@ mod m3; mod residency; mod shared; mod sparse_tile; +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +pub(crate) use sparse_tile::SparseTile as ContiguousScratch; mod table; #[cfg(CONFIG_DRM_ASAHI_G18)] mod t8152; @@ -269,6 +271,73 @@ const fn binding_wire_generation(incarnation: u64) -> u8 { /// Upper word of an application TTBAT slot. M4 exposes firmware upper mappings only in /// context 0; the existing G15 handoff shares them with user contexts. +/// Read-only diagnostic for the parked J413 job: find the firmware's private records by +/// their pointers to the host queue objects and log the words around each one. The region +/// is the firmware data segment the trial already maps its crash log from. +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +pub(crate) fn t8112_private_scan(dev: &device::Device, anchors: &[(u64, &str)], mode: u32) -> Result { + let node = dev.of_node().ok_or(EINVAL)?; + let res = node.reserved_mem_region_to_resource_byname(c_str!("fw-data"))?; + // The crash-log region sits directly above the firmware's private data segment + // (stock gfx-data: 0x9c000 bytes ending where the shared read-only segment begins). + let bytes: usize = 0x9c000; + let log: u64 = res.start().try_into()?; + let base = log.checked_sub(bytes as u64).ok_or(EINVAL)?; + // SAFETY: loader-reserved firmware RAM, outside Linux's memory map, mapped for reading only. + let map = unsafe { kernel::bindings::memremap(base, bytes, kernel::bindings::MEMREMAP_WB as _) }; + if map.is_null() { return Err(ENOMEM); } + struct Unmap(*mut core::ffi::c_void); + impl Drop for Unmap { + // SAFETY: the pointer came from memremap above and is unmapped once. + fn drop(&mut self) { unsafe { kernel::bindings::memunmap(self.0) } } + } + let _unmap = Unmap(map); + let p = map as *const u8; + // SAFETY: every offset read below is checked against the mapped size. + let rd = |o: usize| unsafe { core::ptr::read_unaligned(p.add(o) as *const u64) }; + dev_info!(dev, "G14G private scan region PA={:#x} bytes={:#x}\n", base, bytes); + let rd32 = |o: usize| (rd(o) & 0xffff_ffff) as u32; + // Named words: imported compute mask, selector word, compute engine marker, + // allocated and reference populations, per-group last-selected slots. + dev_info!(dev, "G14G private named import+0x99404={:#x} selector+0x993f0={:#x} engine+0x49158={:#x} busy+0x491ac={:#x} reference+0x491bc={:#x} last+0x49224={:#x} idle+0x48758={:#x}\n", + rd32(0x99404), rd32(0x993f0), rd32(0x49158), rd32(0x491ac), rd32(0x491bc), rd32(0x49224), rd(0x48758)); + if mode & 2 != 0 { + // Non-zero rows of the two areas the queue records and their stack references lie in. + for (start, end) in [(0x48000usize, 0x49800usize), (0x55000, 0x55c00)] { + let mut w = start; + while w < end { + let row = [rd(w), rd(w + 8), rd(w + 16), rd(w + 24)]; + if row != [0; 4] { + dev_info!(dev, "G14G private area +{:#x}: {:#x} {:#x} {:#x} {:#x}\n", w, row[0], row[1], row[2], row[3]); + } + w += 0x20; + } + } + } + let mut hits = 0usize; + let mut o = 0usize; + while o + 8 <= bytes { + let v = rd(o); + for (needle, name) in anchors { + if v != *needle { continue; } + hits += 1; + if hits > 40 { return Ok(hits); } + if mode & 1 == 0 { continue; } + dev_info!(dev, "G14G private hit {} at +{:#x}\n", name, o); + let start = o.saturating_sub(0xc0) & !7; + let end = core::cmp::min(o + 0xc0, bytes - 0x20); + let mut w = start; + while w < end { + dev_info!(dev, "G14G private +{:#x}: {:#x} {:#x} {:#x} {:#x}\n", + w, rd(w), rd(w + 8), rd(w + 16), rd(w + 24)); + w += 0x20; + } + } + o += 4; + } + Ok(hits) +} + const fn application_ttb1(root: u64, asid: usize, map_kernel_to_user: bool) -> u64 { if map_kernel_to_user { root | TTBR_VALID | (asid as u64) << TTBR_ASID_SHIFT @@ -3487,6 +3556,51 @@ pub(crate) struct AdoptedRegions { pub(crate) kernel_root: PhysicalAddr, } +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +pub(crate) struct T8112Peer; + +#[cfg(CONFIG_DRM_ASAHI_M3_T8122)] +#[vtable] +impl kernel::soc::apple::rtkit::Operations for T8112Peer { + type Data = Arc>; + type Buffer = crate::g17::CrashLog; + + const COPROC_PLACES_BUFFERS: bool = true; + + fn shmem_map( + dev: kernel::sync::ArcBorrow<'_, ARef>, + iova: usize, + size: usize, + ) -> Result { + let buffer = crate::g17::CrashLog::from_firmware(&dev, iova, size)?; + dev_info!(&**dev, "G14G mapped RTKit log PA={:#x} bytes={:#x}\n", iova, size); + Ok(buffer) + } + + fn crashed(dev: kernel::sync::ArcBorrow<'_, ARef>, log: Option<&[u8]>) { + unsafe extern "C" { + fn asahi_save_rtkit_dump(dev: *mut kernel::bindings::device, data: *const u8, size: usize); + } + if let Some(log) = log { + // SAFETY: RTKit and the device remain live throughout this synchronous copy. + unsafe { asahi_save_rtkit_dump(dev.as_raw(), log.as_ptr(), log.len()) }; + } + } + + fn recv_message( + dev: kernel::sync::ArcBorrow<'_, ARef>, + ep: u8, + message: u64, + ) { + // Receive doorbells repeat once the firmware is opened: log the first few. + static SEEN: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); + let seen = SEEN.fetch_add(1, Ordering::Relaxed); + if seen < 8 || seen.is_power_of_two() { + dev_info!(&**dev, "G14G firmware ep={:#x} message={:#018x} count={}\n", ep, message, seen + 1); + } + } +} + impl Uat { /// Common AP and firmware exclusion for G16's reserved-table window. Acquire /// immutable root addresses before this guard, preserving binding -> UAT lock order. @@ -3686,6 +3800,659 @@ impl Uat { } /// Map a bootloader-preallocated memory region + /// Boot only as far as the legacy PPL handshake. No host tables or queues are published. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + pub(crate) fn observe_t8112_peer<'a>(pdev: &'a kernel::platform::Device>) -> Result>> { + use kernel::io::{Io, IoBase}; + let phase = module_parameters::t8112_handshake.value(); + let followup = module_parameters::t8112_active_followup.value(); + if followup > 2 || (followup != 0 && (phase != 14 + || !module_parameters::t8112_power_filter.value() || !module_parameters::t8112_idle_policy.value() + || module_parameters::t8112_post_power_job.value() || module_parameters::t8112_ram_slots.value() != 0)) { + return Err(EINVAL); + } + if module_parameters::t8112_command_engine.value() > 2 { return Err(EINVAL); } + let classes = module_parameters::t8112_engine_classes.value(); + if classes > 2 || (classes != 0 && (phase != 14 || !module_parameters::t8112_idle_policy.value())) { + return Err(EINVAL); + } + let region = Self::map_region(pdev.as_ref(), c"handoff", HANDOFF_SIZE, true)?; + // SAFETY: map_region checked the size of the dedicated UAT reservation. + // Only the aligned shared atomic fields in its protocol header are used. + let h = unsafe { &*region.map.ptr().cast::() }; + let req = pdev.io_request_by_name(c"asc").ok_or(EINVAL)?; + let mapping = req.iomap_sized::<{ crate::regs::ASC_CTL_SIZE }>()?; + let asc = mapping.as_view(); + let ctl = asc.read32(0x44); + let ap = h.magic_ap.load(Ordering::Acquire); + let fw = h.magic_fw.load(Ordering::Acquire); + dev_info!(pdev.as_ref(), "G14G pre-init: ASC control={:#x} handoff AP={:#x} FW={:#x}\n", ctl, ap, fw); + if ctl & 0x10 != 0 || ap != 0 || fw != 0 || + h.lock_ap.load(Ordering::Acquire) != 0 || h.lock_fw.load(Ordering::Acquire) != 0 { + return Err(EBUSY); + } + // The 26B123 firmware advertised this word to the v2 host. + const G14G_26B123_MAGIC: u64 = 0x4b1d000000000003; + let device: &device::Device = pdev.as_ref(); + let peer = kernel::soc::apple::rtkit::RtKit::::new( + pdev.as_ref(), None, 0, Arc::new(ARef::from(device), GFP_KERNEL)?, + )?; + let ttbs = Self::map_region(device, c"ttbs", UAT_PGSZ, true)?; + let tables = Self::map_region(device, c"pagetables", UAT_PGSZ, true)?; + let sgx = crate::regs::Resources::new(pdev)?; + let shared_l2 = Self::map_region(device, c"shared-l2", UAT_PGSZ, true)?; + let l2_state = || { + // SAFETY: shared-l2 is one loader-reserved 16 KiB table. + let l2 = unsafe { &*shared_l2.map.ptr().cast::<[AtomicU64; UAT_PGSZ / 8]>() }; + let mut first = None; + let mut used = 0; + for (index, entry) in l2.iter().enumerate() { + let value = entry.load(Ordering::Acquire); + if value != 0 { + first.get_or_insert((index, value)); + used += 1; + } + } + (used, first) + }; + let snapshot = |region: &UatRegion| { + // SAFETY: Both reservations cover a full aligned page. Sample the shared + // table words without interpreting them as CPU pointers. + let words = unsafe { &*region.map.ptr().cast::<[AtomicU64; 4]>() }; + words.each_ref().map(|v| v.load(Ordering::Acquire)) + }; + dev_info!(device, "G14G stopped TTBAT={:x?} root={:x?}\n", snapshot(&ttbs), snapshot(&tables)); + dev_info!(device, "G14G stopped shared-L2 PA={:#x} entries={:x?}\n", shared_l2.base, l2_state()); + // Qualify the G15 host window without giving the firmware an InitData pointer. + // Install while the ASC is stopped. The isolated leaf maps only a zeroed, + // read-only host-owned page and is retained until the ASC stops again. + let cfg = &crate::hw::t8112::HWCONFIG; + let geometry = UatGeometry { ias: cfg.uat_ias, oas: cfg.uat_oas }; + let va = geometry.kernel_range().start; + let page = kernel::page::Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; + let mut shadow = UatPageTable::new(geometry.ias, geometry.oas)?; + shadow.enable_clean_poc()?; + let range = va..va + UAT_PGSZ as u64; + shadow.alloc_pages(range.clone())?; + shadow.map_pages(range, page.phys(), PROT_FW_SHARED_RO, false)?; + if shadow.translate_iova(va)? != page.phys() || l2_state().0 != 0 { + return Err(EINVAL); + } + let mask = ((1u64 << geometry.oas) - 1) & !(UAT_PGMSK as u64); + // SAFETY: This exclusively owned shadow and all its page-table pages outlive this + // walk. Each intermediate address is extracted from our own table. + let leaf_table = unsafe { + let upper = pgtable::with_root_entries(None, shadow.ttb(), 3, + |words| words[2].load(Ordering::Acquire))?; + if upper & 3 != 3 { return Err(EINVAL); } + pgtable::with_root_entries(None, upper & mask, 1, + |words| words[0].load(Ordering::Acquire))? + }; + if leaf_table & 3 != 3 { return Err(EINVAL); } + // SAFETY: This aligned word is in the ADT shared-L2 reservation. + let slot = unsafe { &*shared_l2.map.ptr().cast::() }; + let want_graph = phase >= 2; + // The extended G15G and primary T6050 profile words are controls. + let version = match phase { + 3 | 5 => Some(0x0c89_c357_8392_04b8), + 4 | 6 => Some(0x0c8e_4339_8728_04c0), + // Published T8112 host submission, Stela #170, build 26B123. + 7 | 9..=14 => Some(0x0c8a_8342_8392_04c8), + _ => None, + }; + let mut modern = None; + let mut init_va = 0; + let mut graph: Option> = None; + let mut binding: Option = None; + let mut drm_keep = None; + let mut pool: Option = None; + let mut entries = KVec::from_elem(0u64, UAT_PGSZ / 8, GFP_KERNEL)?; + entries[0] = leaf_table; + let mut lower_root = 0; + if want_graph { + #[cfg(not(CONFIG_DRM_ASAHI_G15))] + return Err(EOPNOTSUPP); + #[cfg(CONFIG_DRM_ASAHI_G15)] + { + use kernel::dma::{Device as _, DmaMask}; + // SAFETY: The mask is the real T8112 UAT's physical width. + unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(geometry.oas)?)? }; + let drm = kernel::drm::UnregisteredDevice::::new(pdev, Ok(()))?; + // SAFETY: The unregistered DRM instance is private to this bound probe. + // The local owner closes on all returns. + binding = Some(unsafe { crate::binding::Owner::new(pdev.as_ref(), &drm)? }); + let regions = AdoptedRegions { + handoff: region.base..region.base + UAT_PGSZ as u64, + ttbs: ttbs.base..ttbs.base + UAT_PGSZ as u64, + kernel_root: tables.base, + }; + let uat = Self::new_adopted(&drm, geometry, ®ions)?; + let control = crate::gpu::GpuManagerG14V13_5::build_graph( + &drm, &sgx, cfg, KBox::new(uat, GFP_KERNEL)?, false, version, + )?; + init_va = if phase >= 5 { + let header = match phase { + 11..=14 => { + let node = device.fwnode().ok_or(ENODEV)?; + let sgx = pdev.resource_by_name(c"sgx").ok_or(EINVAL)?; + let copy_bytes: u32 = node.property_read(c"apple,coredump-copy-buffer").required_by(device)?; + let interrupt: u64 = node.property_read(c"apple,meta-sw-interrupt").required_by(device)?; + if sgx.start() != 0x204000000 || sgx.size() < 0xe14000 || + copy_bytes != 0x8000 || interrupt & !0x3fff != 0x23b0c4000 { + return Err(EINVAL); + } + Some(crate::gpu::G14DirectoryHeader::J413 { sgx: sgx.start(), sgx_size: sgx.size() as u64, interrupt, copy_bytes, live: phase >= 12, first_job: phase >= 13 }) + } + 9 => Some(crate::gpu::G14DirectoryHeader::Zero), + 10 => Some(crate::gpu::G14DirectoryHeader::PrivatePage), + _ => None, + }; + let candidate = crate::gpu::G14TrialRoot::build( + &control, version.ok_or(EINVAL)?, header, + )?; + if module_parameters::t8112_drm.value() { + // Runtime command slots, before the window's tables are mirrored. + let mut alloc = crate::gpu::GpuManager::alloc(&*control); + pool = Some(crate::gpu::J413Pool::new(&mut alloc)?); + } + candidate.with(|r, _| { + let word = r.ver_info.iter().enumerate() + .fold(0u64, |v, (i, &w)| v | (u64::from(w) << (16*i))); + dev_info!(device, "G14G encoded root word={:#018x} runtime={:?} status={:?}\n", + word, r.runtime_pointers, r.status_record); + pgtable::clean_poc(core::ptr::from_ref(r).cast(), core::mem::size_of_val(r)); + }); + let address = candidate.gpu_va().get(); + modern = Some(candidate); + address + } else { + control.trial_root() + }; + let root = control.trial_uat().kernel_window_root(); + // SAFETY: The private control graph owns both table levels. + unsafe { + let upper = pgtable::with_root_entries(None, root, 3, + |w| w[2].load(Ordering::Acquire))?; + if upper & 3 != 3 { return Err(EINVAL); } + pgtable::with_root_entries(None, upper & mask, entries.len(), |w| { + for (entry, word) in entries.iter_mut().zip(w) { + *entry = word.load(Ordering::Acquire); + } + })?; + } + // The window's final 4 GiB is reserved for MMIO. The trial graph + // has one MMIO subtree only for the stopped 26B123 board construction. + let first_io = (0xf_0000_0000u64 >> 25) as usize; + let mmio_tables = entries[first_io..].iter().filter(|w| **w != 0).count(); + if mmio_tables != usize::from(matches!(phase, 11..=14)) { return Err(EINVAL); } + for &w in entries.iter().filter(|w| **w != 0) { + if w & 3 != 3 { return Err(EINVAL); } + crate::g15::uat::clean_page(w & mask)?; + } + crate::g15::uat::clean_lower(control.trial_uat())?; + lower_root = control.trial_uat().kernel_lower_root(); + dev_info!(device, "G14G InitData phase={} word={:#018x} root={:#x} RAM tables={} MMIO tables={}\n", + phase, version.unwrap_or(0x00b0_0601_1f28_6ba0), init_va, entries[..first_io].iter().filter(|w| **w != 0).count(), mmio_tables); + graph = Some(control); + drm_keep = Some(drm); + } + } + // Construction-only profiles must return before touching the live UAT. + if matches!(phase, 9..=11) { + dev_info!(device, "G14G directory construction verified with ASC stopped\n"); + drop(modern); + drop(graph); + drop(binding); + return Ok(None); + } + // SAFETY: These are aligned words of two dedicated one-page reservations. + let shared = unsafe { &*shared_l2.map.ptr().cast::<[AtomicU64; UAT_PGSZ / 8]>() }; + let context = unsafe { &*ttbs.map.ptr().cast::() }; + if l2_state().0 != 0 || snapshot(&ttbs) != [0; 4] { return Err(EBUSY); } + let gate_mask = crate::regs::G17_GATING_DISABLE; + let previous_gating = match module_parameters::t8112_fender_gating.value() { + 0 => None, + mode @ (1 | 2) if phase == 14 && module_parameters::t8112_idle_policy.value() + && module_parameters::t8112_ram_slots.value() == 0 => { + let (clear, set) = if mode == 1 { (0, crate::regs::G17_GATING_HOLD) } else { (gate_mask, 0) }; + Some(sgx.t8112_fender_gating(clear, set)? & gate_mask) + } + _ => return Err(EINVAL), + }; + let open_guard = if module_parameters::t8112_sgx_open.value() { + if phase != 14 || !module_parameters::t8112_idle_policy.value() + || !module_parameters::t8112_event_completion.value() { return Err(EINVAL); } + let (before, after) = sgx.t8112_sgx_open(true); + let regs = &sgx; + let guard = kernel::types::ScopeGuard::new(move || { + regs.t8112_sgx_open(before & 1 != 0); + }); + if after & 1 == 0 { return Err(EIO); } + Some(guard) + } else { None }; + let irq_bit = module_parameters::t8112_gpc_irq_bit.value(); + let irq_guard = if irq_bit == 0 { + None + } else { + if !matches!(irq_bit, 1 | 2) || phase != 14 || !module_parameters::t8112_idle_policy.value() + || !module_parameters::t8112_event_completion.value() { return Err(EINVAL); } + let was_set = sgx.t8112_gpc_irq_enable() & irq_bit != 0; + let regs = &sgx; + let guard = kernel::types::ScopeGuard::new(move || { + regs.t8112_update_gpc_irq(irq_bit, was_set); + }); + if sgx.t8112_update_gpc_irq(irq_bit, true) & irq_bit == 0 { return Err(EIO); } + Some(guard) + }; + let pmp_vote = module_parameters::t8112_pmp_vote.value(); + if pmp_vote { + if phase != 14 || !module_parameters::t8112_idle_policy.value() || + module_parameters::t8112_ram_slots.value() != 0 { return Err(EINVAL); } + #[cfg(not(CONFIG_DRM_ASAHI_M3_T8122))] + return Err(ENOTSUPP); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + { + // SAFETY: the live GPU consumer links to its declared PMP supplier. The + // bridge waits for the report and serializes the untagged endpoint reply. + kernel::error::to_result(unsafe { kernel::bindings::apple_pmp_link_device(device.as_raw()) })?; + let result = unsafe { kernel::bindings::apple_pmp_set_device_power(0x0f, 5, 1) }; + dev_info!(device, "G14G PMP AGX device 5 acquire result={}\n", result); + kernel::error::to_result(result)?; + } + } + for (word, value) in shared.iter().zip(entries.iter()) { + if *value != 0 { word.store(*value, Ordering::Release); } + } + if want_graph { + context.ttb0.store(lower_root | TTBR_VALID, Ordering::Release); + context.ttb1.store(tables.base | TTBR_VALID, Ordering::Release); + pgtable::clean_poc(ttbs.map.ptr(), 16); + let job = module_parameters::t8112_job_context.value() as usize; + if job != 0 { + if job >= UAT_NUM_CTX { return Err(EINVAL); } + // A client context for the kernel-owned job: the same two trees as context 0. + // SAFETY: the slot lies inside the mapped, size-checked TTBAT reservation. + let client = unsafe { &*ttbs.map.ptr().cast::().add(job) }; + // As Vm::bind writes it for other firmware: both entries + // carry the context identifier in bits 63:48. + let id = if module_parameters::t8112_context_id_field.value() { + (job as u64) << TTBR_ASID_SHIFT + } else { 0 }; + client.ttb0.store(lower_root | TTBR_VALID | id, Ordering::Release); + client.ttb1.store(tables.base | TTBR_VALID | id, Ordering::Release); + pgtable::clean_poc(ttbs.map.ptr(), (job + 1) * 16); + } + } + pgtable::clean_poc(shared_l2.map.ptr(), UAT_PGSZ); + pgtable::poc_barrier(); + dev_info!(device, "G14G preboot host window VA={:#x} first entry={:#x}\n", va, entries[0]); + let mut peer_box = KBox::pin(peer, GFP_KERNEL)?; + let mut peer = peer_box.as_mut(); + h.magic_ap.store(G14G_26B123_MAGIC, Ordering::Release); + fence(Ordering::SeqCst); + asc.write32(ctl | 0x10, 0x44); + let run = asc.read32(0x44); + let start = Instant::::now(); + while start.elapsed() < Delta::from_millis(1000) && h.magic_fw.load(Ordering::Acquire) != G14G_26B123_MAGIC { + fsleep(Delta::from_millis(1)); + } + let observed = h.magic_fw.load(Ordering::Acquire); + if observed == G14G_26B123_MAGIC { + let result = peer.as_mut().boot(); + dev_info!(pdev.as_ref(), "G14G RTKit boot={:?} firmware_ep={} doorbell_ep={}\n", result, peer.as_mut().has_endpoint(0x20), peer.as_mut().has_endpoint(0x21)); + if result.is_ok() { + dev_info!(device, "G14G running shared-L2 PA={:#x} entries={:x?}\n", shared_l2.base, l2_state()); + match sgx.get_gpu_id() { + Ok(id) => dev_info!(device, "G14G register identity {:?}{:?} {:?}, clusters={} active_cores={} mask={:x?}\n", + id.gpu_gen, id.gpu_variant, id.gpu_rev, id.num_clusters, + id.total_active_cores, id.core_masks), + Err(e) => dev_warn!(device, "G14G register identity error {:?}\n", e), + } + let cmd = peer.as_mut().start_endpoint(0x20); + let doorbell = peer.as_mut().start_endpoint(0x21); + if graph.is_some() { + if cmd.is_ok() && doorbell.is_ok() && snapshot(&tables)[2] & mask == shared_l2.base + && context.ttb0.load(Ordering::Acquire) == lower_root | TTBR_VALID + && context.ttb1.load(Ordering::Acquire) == tables.base | TTBR_VALID { + let power_sample = |stage: &str| { + if phase == 14 { + if let Some(root) = modern.as_ref() { + if let Err(e) = root.report_power_progress(stage, sgx.t8112_operating_point()) { + dev_warn!(device, "G14G {} power sample failed {:?}\n", stage, e); + } + } + } + }; + let kick_fence = |peer: &mut core::pin::Pin<&mut kernel::soc::apple::rtkit::RtKit>| -> Result { + let root = modern.as_ref().ok_or(EINVAL)?; + let start = Instant::::now(); + while module_parameters::t8112_command_service.value() + && root.command_service()? != (2, 0) + && start.elapsed() < Delta::from_millis(500) { + fsleep(Delta::from_millis(1)); + } + dev_info!(device, "G14G command service (stage, request)={:?}\n", root.command_service()); + root.publish_startup_fence(sgx.t8112_operating_point())?; + let kick = peer.as_mut().send_message(0x21, (0x83u64 << 48) | (4 * crate::gpu::G14TrialRoot::signal_group() + crate::gpu::G14TrialRoot::signal_engine()) as u64); + dev_info!(device, "G14G first compute fence kick={:?}\n", kick); + kick + }; + let mut power_cycled = false; + power_sample("before-init"); + let sent = peer.as_mut().send_message(0x20, crate::gpu::init_message(init_va)); + dev_info!(device, "G14G InitData-only post phase={} result={:?}\n", phase, sent); + // Keep the statistics consumer moving through every wait. + let nap = |ms: i64| { + let start = Instant::::now(); + while start.elapsed() < Delta::from_millis(ms) { + if let Some(root) = modern.as_ref() { let _ = root.drain_statistics(); } + fsleep(Delta::from_millis(1)); + } + }; + nap(1000); + if matches!(phase, 13 | 14) && sent.is_ok() { + dev_info!(device, "G14G before publication: GPC interrupt enable={:#x}\n", + sgx.t8112_gpc_irq_enable()); + } + if phase == 14 && sent.is_ok() { + power_sample("after-init"); + let policy = module_parameters::t8112_idle_policy.value(); + let scratch = module_parameters::t8112_ram_slots.value() != 0 || + module_parameters::t8112_dashboard_ram.value(); + let mut verified = false; + let audit = scratch || module_parameters::t8112_performance_control.value() + || module_parameters::t8112_cre.value(); + if !policy || audit { + if let Some(root) = modern.as_ref() { + let walk = |va: u64| -> Result { + let va = va & ((1u64 << 39) - 1); + let i = ((va >> 25) & 2047) as usize; + if va >> 36 != 2 || context.ttb1.load(Ordering::Acquire) != tables.base | TTBR_VALID || + snapshot(&tables)[2] & (mask | 3) != shared_l2.base | 3 { return Err(EFAULT); } + let l3 = shared[i].load(Ordering::Acquire); + // Only follow the L3 page retained by this graph at this index. + if l3 & 3 != 3 || l3 != entries[i] { return Err(EFAULT); } + let j = ((va >> 14) & 2047) as usize; + // SAFETY: this entry names the live, driver-owned RAM table checked above. + unsafe { pgtable::with_root_entries(None, l3 & mask, j+1, + |words| words[j].load(Ordering::Acquire)) } + }; + let result = root.audit_power_inputs(walk, mask); + verified = result.is_ok(); + dev_info!(device, "G14G audit upper={:#x} shared_l2={:#x} result={:?}\n", + context.ttb1.load(Ordering::Acquire), shared_l2.base, result); + } + } + // Same owners and observation interval as the first fence, + // with both producer indices still zero and no queue kick. + if policy && (!audit || verified) { + if let Some(root) = modern.as_ref() { + let set_policy = |peer: &mut core::pin::Pin<&mut kernel::soc::apple::rtkit::RtKit>, allow_off| -> Result { + let (target, generation) = root.publish_idle_policy(allow_off)?; + peer.as_mut().send_message(0x21, 0x0084_0000_0000_0011)?; + let start = Instant::::now(); + let mut last = None; + loop { + let state = (root.idle_progress()?, sgx.t8112_operating_point()); + if last != Some(state) { + power_sample(if allow_off { "allow-off" } else { "keep-powered" }); + last = Some(state); + } + if state.0 == [target; 3] && root.idle_acknowledgement()? == generation { + return Ok(()); + } + if start.elapsed() >= Delta::from_millis(500) { + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + }; + // J613 extended order: the opening record retires with + // InitData, then each engine class retires on its own kick. + let base = crate::gpu::G14TrialRoot::control_base(); + let mut opened = base == 0 || root.idle_progress() == Ok([1; 3]); + if base != 0 { + dev_info!(device, "G14G opening control retired={} progress={:?}\n", + opened, root.idle_progress()); + } + for ordinal in 0..base.saturating_sub(1) { + if !opened { break; } + let class = (|| -> Result { + let target = root.publish_engine_class(ordinal)?; + peer.as_mut().send_message(0x21, 0x0084_0000_0000_0011)?; + let start = Instant::::now(); + while root.idle_progress()? != [target; 3] { + if start.elapsed() >= Delta::from_millis(500) { return Err(ETIMEDOUT); } + fsleep(Delta::from_millis(1)); + } + Ok(()) + })(); + dev_info!(device, "G14G engine class pipe={} engine={} retired={:?} progress={:?}\n", + ordinal / 2, ordinal % 2 + 1, class, root.idle_progress()); + opened = class.is_ok(); + } + for allow_off in [false, true] { + if !opened { break; } + let policy = set_policy(&mut peer, allow_off); + dev_info!(device, "G14G idle policy allow_off={} retired={:?}\n", allow_off, policy); + if policy.is_err() { break; } + power_cycled = allow_off; + if !allow_off && followup == 2 { + let held_job = (|| -> Result { + kick_fence(&mut peer)?; + let start = Instant::::now(); + let mut sampled = 0; + let mut rekick = module_parameters::t8112_rekick_ms.value(); + while !root.startup_fence_complete()? { + if rekick != 0 && start.elapsed() >= Delta::from_millis(rekick as i64) { + rekick = 0; + let again = peer.as_mut().send_message(0x21, (0x83u64 << 48) + | (4 * crate::gpu::G14TrialRoot::signal_group() + crate::gpu::G14TrialRoot::signal_engine()) as u64); + dev_info!(device, "G14G repeat kick={:?}\n", again); + } + if module_parameters::t8112_compute_job.value() + && start.elapsed() >= Delta::from_millis(1000 + 200 * sampled) + && sampled < 2 { + sampled += 1; + root.report_job_gates("parked")?; + if sampled == 1 && module_parameters::t8112_private_scan.value() & 3 != 0 { + let found = t8112_private_scan(device, &root.job_anchors(), module_parameters::t8112_private_scan.value()); + dev_info!(device, "G14G private scan={:?}\n", found); + } + } + if start.elapsed() >= Delta::from_millis(module_parameters::t8112_job_wait_ms.value() as i64) { return Err(ETIMEDOUT); } + fsleep(Delta::from_millis(1)); + } + Ok(()) + })(); + dev_info!(device, "G14G held fence completion={:?}\n", held_job); + if module_parameters::t8112_drm.value() && held_job.is_ok() + && modern.is_some() && graph.is_some() && pool.is_some() + && drm_keep.is_some() && binding.is_some() { + // Hand the running firmware to the DRM backend instead of stopping it. + let asc_phys = pdev.resource_by_name(c"asc").ok_or(EINVAL)?.start(); + let asc_ctl = crate::j413::AscControl::new(asc_phys)?; + let (Some(root), Some(control), Some(slots), Some(drm), Some(owner)) = + (modern.take(), graph.take(), pool.take(), drm_keep.take(), binding.take()) + else { return Err(EINVAL); }; + drop(irq_guard); + drop(open_guard); + // The firmware keeps using these until it is stopped; their + // mappings stay for the life of the boot. + core::mem::forget(region); + core::mem::forget(ttbs); + core::mem::forget(tables); + core::mem::forget(shared_l2); + core::mem::forget(page); + core::mem::forget(shadow); + core::mem::forget(mapping); + dev_info!(device, "G14G handing the running firmware to the DRM backend\n"); + return Ok(Some(crate::j413::Live { + peer: peer_box, root, graph: control, pool: slots, asc: asc_ctl, + drm, binding: owner, resources: sgx, + })); + } + if module_parameters::t8112_private_scan.value() & 4 != 0 { + let found = t8112_private_scan(device, &root.job_anchors(), 3); + dev_info!(device, "G14G private scan after wait={:?}\n", found); + } + if ((held_job.is_ok() && module_parameters::t8112_job_order.value() == 1) + || module_parameters::t8112_job_order.value() == 2) + && module_parameters::t8112_compute_job.value() { + let second = (|| -> Result { + root.publish_second()?; + peer.as_mut().send_message(0x21, (0x83u64 << 48) + | (4 * crate::gpu::G14TrialRoot::signal_group() + crate::gpu::G14TrialRoot::signal_engine()) as u64)?; + let start = Instant::::now(); + let mut sampled = 0; + while !root.second_complete()? { + if start.elapsed() >= Delta::from_millis(500 + 200 * sampled) && sampled < 2 { + sampled += 1; + root.report_job_gates("second")?; + } + if start.elapsed() >= Delta::from_millis(3000) { return Err(ETIMEDOUT); } + fsleep(Delta::from_millis(1)); + } + Ok(()) + })(); + dev_info!(device, "G14G second command (compute) completion={:?}\n", second); + if second.is_err() { break; } + } + if held_job.is_err() { break; } + } + if allow_off || followup == 0 { + fsleep(Delta::from_millis(100)); + } + power_sample(if allow_off { "released" } else { "held" }); + } + } + } + nap(1000); + } + if module_parameters::t8112_compute_job.value() && sgx.t8112_operating_point() & 0xf != 0 { + let latch = sgx.t8112_fault_latch(); + dev_info!(device, "G14G core fault latch={:#x} valid={} reason={} client={} address={:#x}\n", + latch, latch & 1, (latch >> 1) & 7, (latch >> 9) & 0xff, (latch >> 24) & !0x3f); + } + // After the allow-off control retires, the firmware + // publishes power-off by clearing shared status +0x10. + if power_cycled { + if let Some(root) = modern.as_ref() { + let start = Instant::::now(); + while root.firmware_running() != Ok(0) && start.elapsed() < Delta::from_millis(500) { + let _ = root.drain_statistics(); + fsleep(Delta::from_millis(1)); + } + dev_info!(device, "G14G stop acknowledgement status+0x10={:?} after {} ms\n", + root.firmware_running(), start.elapsed().as_millis()); + } + } + // With work still parked the allow-off control cannot + // complete. Ask RTKit for acknowledged power-off of both sides while + // every mapping is still in place, before the ASC run bit is cleared. + let forced = module_parameters::t8112_forced_stop.value(); + if forced != 0 { + if let Some(root) = modern.as_ref() { + let before = root.firmware_running(); + if forced == 2 || before != Ok(0) { + let start = Instant::::now(); + // SAFETY: the RTKit instance is live and owned by this probe. + let off = kernel::error::to_result(unsafe { + kernel::bindings::apple_rtkit_poweroff(peer.as_raw()) + }); + dev_info!(device, "G14G forced stop status+0x10 before={:?} power-off={:?} after {} ms status+0x10={:?} ASC={:#x}\n", + before, off, start.elapsed().as_millis(), root.firmware_running(), asc.read32(0x44)); + } + } + } + power_sample("before-stop"); + let post_power_job = power_cycled && module_parameters::t8112_post_power_job.value() + && module_parameters::t8112_ram_slots.value() == 0; + if (phase == 13 || post_power_job) && sent.is_ok() { + match kick_fence(&mut peer) { + Ok(()) => fsleep(Delta::from_millis(1000)), + Err(e) => dev_info!(device, "G14G compute fence submission failed {:?}\n", e), + } + } + } + } + fsleep(Delta::from_millis(50)); + dev_info!(device, "G14G start endpoints command={:?} doorbell={:?} TTBAT={:x?} root={:x?} lock_fw={} turn={} slot={}\n", + cmd, doorbell, snapshot(&ttbs), snapshot(&tables), + h.lock_fw.load(Ordering::Acquire), h.turn.load(Ordering::Acquire), h.cur_slot.load(Ordering::Acquire)); + } + } + asc.write32(asc.read32(0x44) & !0x10, 0x44); + let stopped = asc.read32(0x44); + dev_info!(pdev.as_ref(), "G14G pre-init: ASC started={:#x} FW={:#x} stopped={:#x}\n", run, observed, stopped); + if stopped & 0x10 != 0 { + shadow.retain(); + core::mem::forget(page); + core::mem::forget(modern); + core::mem::forget(graph); + return Err(EBUSY); + } + if phase >= 12 { + if let Some(root) = modern.as_ref() { + if phase == 14 { + if let Err(e) = root.report_stopped_power() { + dev_warn!(device, "G14G stopped power sample failed {:?}\n", e); + } + } + dev_info!(device, "G14G stopped command service (stage, request)={:?}\n", root.command_service()); + root.report_stopped_fence(); + root.report_stopped_receive(); + let (cold, started, ready) = root.stopped_status(); + dev_info!(device, "G14G final shared status cold={} started={} ready={}\n", + cold, started, ready); + } + } + pgtable::clean_invalidate_poc(shared_l2.map.ptr(), UAT_PGSZ); + pgtable::poc_barrier(); + let final_entry = slot.load(Ordering::Acquire); + dev_info!(device, "G14G stopped host window slot={:#x} expected={:#x}\n", final_entry, entries[0]); + if shared.iter().zip(entries.iter()).any(|(w,e)| { + let value = w.load(Ordering::Acquire); + value != 0 && value != *e + }) { + shadow.retain(); + core::mem::forget(page); + core::mem::forget(modern); + core::mem::forget(graph); + return Err(EBUSY); + } + if want_graph { + context.ttb0.store(0, Ordering::Release); + context.ttb1.store(0, Ordering::Release); + pgtable::clean_poc(ttbs.map.ptr(), 16); + } + for (word, value) in shared.iter().zip(entries.iter()) { + if *value != 0 { word.store(0, Ordering::Release); } + } + pgtable::clean_poc(shared_l2.map.ptr(), UAT_PGSZ); + pgtable::poc_barrier(); + mem::tlbi_all(); + mem::sync(); + h.magic_ap.store(ap, Ordering::Release); + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + if pmp_vote { + // SAFETY: the ASC was stopped and its UAT mappings withdrawn while power was held. + let result = unsafe { kernel::bindings::apple_pmp_set_device_power(0x0f, 5, 0) }; + dev_info!(device, "G14G PMP AGX device 5 release result={}\n", result); + kernel::error::to_result(result)?; + } + drop(irq_guard); + drop(open_guard); + if let Some(previous) = previous_gating { + sgx.t8112_fender_gating(gate_mask, previous)?; + } + drop(modern); + drop(graph); + drop(binding); + if observed != G14G_26B123_MAGIC { return Err(ETIMEDOUT); } + Ok(None) + } + fn map_region( dev: &device::Device, name: &CStr, @@ -3861,6 +4628,13 @@ impl Uat { uat_inner.owned_user_roots[idx] = ttb; binding.generation = binding_wire_generation(incarnation); uat_inner.publish_slot(idx); + if self.inner.clean_poc && !uat_inner.quirks.clean_tables { + // A walker that does not snoop the CPU caches (the adopted J413 27.2 UAT) + // must also see the new TTBAT words, not only the new tables. + let slot = core::ptr::from_ref(&uat_inner.ttbs()[idx]).cast::(); + pgtable::clean_poc(slot, size_of::()); + pgtable::poc_barrier(); + } drop(transaction); // Make sure all TLB entries from the previous owner of this ASID are gone diff --git a/drivers/gpu/drm/asahi/mmu/sparse_tile.rs b/drivers/gpu/drm/asahi/mmu/sparse_tile.rs index dc4a5459eff10..ea53b285d8e5d 100644 --- a/drivers/gpu/drm/asahi/mmu/sparse_tile.rs +++ b/drivers/gpu/drm/asahi/mmu/sparse_tile.rs @@ -7,9 +7,10 @@ use kernel::{prelude::*, sync::Arc}; /// A zeroed, physically contiguous kernel allocation. The page tables repeat /// its first page across a filled range, as a SINGLE_PAGE bind repeats its /// GEM's first page. -pub(super) struct SparseTile { +pub(crate) struct SparseTile { page: *mut kernel::bindings::page, physical: u64, + order: u32, } // SAFETY: The pages are exclusively owned until Drop; only their physical @@ -19,32 +20,42 @@ unsafe impl Send for SparseTile {} unsafe impl Sync for SparseTile {} impl SparseTile { - /// One UAT page, the only part the page tables read: the order of the kernel pages that - /// make up a UAT page, naturally aligned to it. - const ORDER: u32 = (crate::pgtable::UAT_PGSZ / kernel::page::PAGE_SIZE).trailing_zeros(); - pub(super) fn new() -> Result> { + Ok(Arc::new(Self::zeroed(crate::pgtable::UAT_PGSZ)?, GFP_KERNEL)?) + } + + /// Allocate a naturally aligned contiguous block covering the requested bytes. + pub(crate) fn zeroed(bytes: usize) -> Result { + if bytes == 0 { return Err(EINVAL); } + let pages = bytes.div_ceil(kernel::page::PAGE_SIZE); + let order = pages.checked_next_power_of_two().ok_or(EOVERFLOW)?.trailing_zeros(); // SAFETY: A plain zeroed higher-order page allocation. let page = unsafe { kernel::bindings::alloc_pages( - kernel::bindings::GFP_KERNEL | kernel::bindings::__GFP_ZERO, Self::ORDER) }; + kernel::bindings::GFP_KERNEL | kernel::bindings::__GFP_ZERO, order) }; if page.is_null() { return Err(ENOMEM); } // SAFETY: page is a live allocation returned above. let physical = unsafe { kernel::bindings::page_to_phys(page) } as u64; - let tile = Arc::new(Self { page, physical }, GFP_KERNEL); - if tile.is_err() { - // SAFETY: The allocation above was not published anywhere. - unsafe { kernel::bindings::__free_pages(page, Self::ORDER) }; - } - Ok(tile?) + Ok(Self { page, physical, order }) } - pub(super) fn physical(&self) -> u64 { self.physical } + pub(crate) fn physical(&self) -> u64 { self.physical } + + pub(crate) fn with_cpu_page(&self, offset: usize, f: impl FnOnce(*mut u8) -> R) -> Result { + let size = kernel::page::PAGE_SIZE; + if offset % size != 0 || offset / size >= 1usize << self.order { + return Err(EINVAL); + } + let pa = self.physical + offset as u64; + // SAFETY: The complete physical allocation stays live across this scoped mapping. + let page = unsafe { kernel::page::Page::borrow_phys(&pa) }.ok_or(EFAULT)?; + Ok(page.with_page_mapped(f)) + } } impl Drop for SparseTile { fn drop(&mut self) { // SAFETY: The VM that maps the tile owns it and drops it after its // page tables. - unsafe { kernel::bindings::__free_pages(self.page, Self::ORDER) }; + unsafe { kernel::bindings::__free_pages(self.page, self.order) }; } } diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index 0c9e6f62b5bbe..8c2fc2191009a 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -431,6 +431,11 @@ impl> GpuObject { GpuPointer(self.gpu_ptr.0, PhantomData) } + /// Borrow the backing of an object used as an opaque firmware record. + pub(crate) fn gpu_bytes(&self) -> GpuPointer<'_, &'_ [u8]> { + GpuPointer(self.gpu_ptr.0, PhantomData) + } + /// Returns a weak GPU pointer to this object, with no lifetime. pub(crate) fn weak_pointer(&self) -> GpuWeakPointer { GpuWeakPointer(self.gpu_ptr.0, PhantomData) @@ -697,6 +702,22 @@ impl> GpuArray { } } +impl> GpuArray { + /// Aligned index in a shared firmware ring, accessed without borrowing its payload. + pub(crate) fn shared_index(&self, offset: usize) -> Result<&core::sync::atomic::AtomicU32> { + if offset.checked_add(4).is_none_or(|end| end > self.len) { + return Err(EINVAL); + } + let ptr = self.raw.wrapping_add(offset).cast::(); + if !ptr.is_aligned() { + return Err(EINVAL); + } + // SAFETY: bounds and alignment checked; the shared ring ABI accesses + // this word only in aligned 32-bit transactions while the ring is live. + Ok(unsafe { core::sync::atomic::AtomicU32::from_ptr(ptr) }) + } +} + impl> Deref for GpuArray { type Target = GpuOnlyArray; diff --git a/drivers/gpu/drm/asahi/queue/compute.rs b/drivers/gpu/drm/asahi/queue/compute.rs index a89fcaf0b8dcb..99893619c9b33 100644 --- a/drivers/gpu/drm/asahi/queue/compute.rs +++ b/drivers/gpu/drm/asahi/queue/compute.rs @@ -32,7 +32,7 @@ use kernel::xarray; const DEBUG_CLASS: DebugFlags = DebugFlags::Compute; -#[versions(AGX)] +#[versions(AGX_ROOT)] impl super::QueueInner::ver { /// Submit work to a compute queue. #[expect( diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index a37bb48fa613f..352ec6a52448d 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -99,12 +99,12 @@ pub(crate) trait Queue: Send + Sync { fn drain(&mut self) {} } -#[versions(AGX)] +#[versions(AGX_ROOT)] struct SubQueue { wq: Arc, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl SubQueue::ver { fn new_job(&mut self, fence: dma_fence::Fence) -> SubQueueJob::ver { SubQueueJob::ver { @@ -115,14 +115,14 @@ impl SubQueue::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] struct SubQueueJob { wq: Arc, job: Option, fence: Option, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl SubQueueJob::ver { fn get(&mut self) -> Result<&mut workqueue::Job::ver> { if self.job.is_none() { @@ -149,7 +149,7 @@ impl SubQueueJob::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct Queue { dev: AsahiDevRef, _sched: sched::Scheduler, @@ -165,7 +165,7 @@ pub(crate) struct Queue { last_out: Option, } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct QueueInner { dev: AsahiDevRef, ualloc: Arc>, @@ -180,7 +180,7 @@ pub(crate) struct QueueInner { counter: AtomicU64, } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Default)] pub(crate) struct JobFence { id: u64, @@ -188,7 +188,7 @@ pub(crate) struct JobFence { stats: Option>, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl JobFence::ver { fn add_command(self: &FenceObject) { self.pending.fetch_add(1, Ordering::Relaxed); @@ -211,7 +211,7 @@ impl JobFence::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[vtable] impl dma_fence::FenceOps for JobFence::ver { fn get_driver_name<'a>(self: &'a FenceObject) -> &'a CStr { @@ -222,7 +222,7 @@ impl dma_fence::FenceOps for JobFence::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct QueueJob { dev: AsahiDevRef, vm_bind: mmu::VmBind, @@ -244,7 +244,7 @@ pub(crate) struct QueueTimeout { id: u64, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl QueueJob::ver { fn get_vtx(&mut self) -> Result<&mut workqueue::Job::ver> { self.sj_vtx @@ -300,7 +300,7 @@ impl QueueJob::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl sched::JobImpl for QueueJob::ver { type TimeoutData = QueueTimeout; const MODULE: Option<&'static kernel::ThisModule> = @@ -507,7 +507,7 @@ impl sched::JobImpl for QueueJob::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Drop for QueueJob::ver { fn drop(&mut self) { mod_dev_dbg!(self.dev, "QueueJob {}: Dropping\n", self.id); @@ -517,7 +517,7 @@ impl Drop for QueueJob::ver { static QUEUE_NAME: &CStr = c_str!("aurora_fence"); static QUEUE_CLASS_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Queue::ver { /// Create a new user queue. #[allow(clippy::too_many_arguments)] @@ -727,7 +727,7 @@ fn build_attachments(reader: &mut Reader<'_>, size: usize) -> Result { .expect("64-bit read failed!") } + /// Fender operating-point request and readback, sampled with GFX powered. + /// G14 first MMU fault latch. Read only while the core is held at a positive state. + pub(crate) fn t8112_fault_latch(&self) -> u64 { + self.sgx_read64::() + } + + pub(crate) fn t8112_operating_point(&self) -> u32 { + self.sgx_read32::<0xd01000>() + } + + /// Apply the shared Fender gate controls and return their observed word. + pub(crate) fn t8112_fender_gating(&self, clear: u32, set: u32) -> Result { + let sgx = self.sgx.as_view(); + let before = sgx.read32(G17_GATING_CONTROL); + let value = (before & !clear) | set; + sgx.write32(value, G17_GATING_CONTROL); + let after = sgx.read32(G17_GATING_CONTROL); + dev_info!(self.dev.as_ref(), "G14G Fender gating before={:#x} after={:#x} requested={:#x}\n", before, after, value); + if (after ^ value) & G17_GATING_DISABLE != 0 { return Err(EIO); } + Ok(before) + } + + /// Keep the platform selection and spare bits intact when opening SGX. + #[cfg(CONFIG_DRM_ASAHI_M3_T8122)] + pub(crate) fn t8112_sgx_open(&self, enabled: bool) -> (u32, u32) { + use crate::g15::regs::SGX_OPEN; + let reg = self.sgx.as_view(); + let before = reg.read32(SGX_OPEN); + let target = (before & !1) | u32::from(enabled); + if target != before { reg.write32(target, SGX_OPEN); } + let after = reg.read32(SGX_OPEN); + dev_info!(self.dev.as_ref(), "G14G SGX open before={:#x} after={:#x}\n", before, after); + (before, after) + } + + /// Change only the selected GPC interrupt bit and read back the GPU-owned register. + pub(crate) fn t8112_update_gpc_irq(&self, bit: u32, set: bool) -> u32 { + let reg = self.sgx.as_view(); + let previous = self.t8112_gpc_irq_enable(); + reg.write32(if set { previous | bit } else { previous & !bit }, 0xd01010); + let after = self.t8112_gpc_irq_enable(); + dev_info!(self.dev.as_ref(), "G14G GPC IRQ bit={:#x} before={:#x} after={:#x}\n", + bit, previous, after); + after + } + + /// Read the two host interrupt selectors on T8112 without changing their masks. + pub(crate) fn t8112_gpc_irq_enable(&self) -> u32 { + self.sgx_read32::<0xd01010>() + } + /// Initialize the MMIO registers for the GPU. pub(crate) fn init_mmio(&self) -> Result { // Nothing to do for now... diff --git a/drivers/gpu/drm/asahi/rtkit_dump.c b/drivers/gpu/drm/asahi/rtkit_dump.c new file mode 100644 index 0000000000000..c7b147c35a286 --- /dev/null +++ b/drivers/gpu/drm/asahi/rtkit_dump.c @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +#include +#include + +void asahi_save_rtkit_dump(struct device *dev, const void *data, size_t size); + +/* RTKit owns its immutable shadow only during the crash callback. */ +void asahi_save_rtkit_dump(struct device *dev, const void *data, size_t size) +{ + void *copy; + + if (!size) + return; + copy = vmalloc(size); + if (copy) { + memcpy(copy, data, size); + dev_coredumpv(dev, copy, size, GFP_KERNEL); + } +} diff --git a/drivers/gpu/drm/asahi/workqueue.rs b/drivers/gpu/drm/asahi/workqueue.rs index 81262edc87e2a..0add98b28cf22 100644 --- a/drivers/gpu/drm/asahi/workqueue.rs +++ b/drivers/gpu/drm/asahi/workqueue.rs @@ -284,7 +284,7 @@ impl) + Send + Sync> GenSubm } /// Inner data for managing a single work queue. -#[versions(AGX)] +#[versions(AGX_ROOT)] struct WorkQueueInner { dev: driver::AsahiDevice, event_manager: Arc, @@ -317,7 +317,7 @@ struct WorkQueueInner { } /// An instance of a work queue. -#[versions(AGX)] +#[versions(AGX_ROOT)] #[pin_data] pub(crate) struct WorkQueue { info_pointer: GpuWeakPointer, @@ -325,7 +325,7 @@ pub(crate) struct WorkQueue { inner: Mutex, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl WorkQueueInner::ver { fn info(&self) -> &GpuObject { self.info @@ -348,7 +348,7 @@ impl WorkQueueInner::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] #[derive(Copy, Clone)] pub(crate) struct QueueEventInfo { pub(crate) stamp_pointer: GpuWeakPointer, @@ -360,7 +360,7 @@ pub(crate) struct QueueEventInfo { pub(crate) info_ptr: GpuWeakPointer, } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct Job { wq: Arc, event_info: QueueEventInfo::ver, @@ -372,7 +372,7 @@ pub(crate) struct Job { fence: dma_fence::Fence, } -#[versions(AGX)] +#[versions(AGX_ROOT)] pub(crate) struct JobSubmission<'a> { inner: Option>, wptr: u32, @@ -380,7 +380,7 @@ pub(crate) struct JobSubmission<'a> { command_count: usize, } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Job::ver { pub(crate) fn event_info(&self) -> QueueEventInfo::ver { let mut info = self.event_info; @@ -597,7 +597,7 @@ impl Job::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl<'a> JobSubmission::ver<'a> { pub(crate) fn run(mut self, channel: &mut channel::PipeChannel::ver) { let command_count = self.command_count; @@ -639,7 +639,7 @@ impl<'a> JobSubmission::ver<'a> { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Drop for Job::ver { fn drop(&mut self) { mod_pr_debug!("WorkQueue: Dropping Job\n"); @@ -684,7 +684,7 @@ impl Drop for Job::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl<'a> Drop for JobSubmission::ver<'a> { fn drop(&mut self) { let inner = self.inner.as_mut().expect("No inner?"); @@ -712,7 +712,7 @@ impl<'a> Drop for JobSubmission::ver<'a> { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl Drop for WorkQueueInner::ver { fn drop(&mut self) { // Release any command held back for the firmware's completion tail. The queue is being torn @@ -734,7 +734,7 @@ impl Drop for WorkQueueInner::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl WorkQueueInner::ver { /// Return the number of free entries in the workqueue pub(crate) fn free_space(&self) -> usize { @@ -755,7 +755,7 @@ impl WorkQueueInner::ver { } } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl WorkQueue::ver { /// Create a new WorkQueue of a given type and priority. #[allow(clippy::too_many_arguments)] @@ -988,7 +988,7 @@ pub(crate) trait WorkQueue { fn fail_all(&self, error: WorkError); } -#[versions(AGX)] +#[versions(AGX_ROOT)] impl WorkQueue for WorkQueue::ver { fn as_any(&self) -> &dyn Any { self diff --git a/rust/macros/versions.rs b/rust/macros/versions.rs index b13a5d55c0e17..79d3a91eba16b 100644 --- a/rust/macros/versions.rs +++ b/rust/macros/versions.rs @@ -93,7 +93,7 @@ static AGX_VERSIONS: VersionConfig = VersionConfig { fields: &["G", "V"], enums: &[ &["G13", "G14", "G14X"], - &["V12_3", "V12_4", "V13_0B4", "V13_2", "V13_3", "V13_5"], + &["V12_3", "V12_4", "V13_0B4", "V13_2", "V13_3", "V13_5", "V27_2"], ], versions: &[ &["G13", "V12_3"], @@ -276,8 +276,10 @@ fn filter_versions( } pub(crate) fn versions(attr: TokenStream, item: TokenStream) -> TokenStream { - let config = match attr.to_string().as_str() { - "AGX" => &AGX_VERSIONS, + // AGX_ROOT is AGX plus G14/V27_2, which only the T8112 27.2 bring-up types instantiate. + let group = attr.to_string(); + let config = match group.as_str() { + "AGX" | "AGX_ROOT" => &AGX_VERSIONS, _ => panic!("Unknown version group {}", attr), }; @@ -321,7 +323,8 @@ pub(crate) fn versions(attr: TokenStream, item: TokenStream) -> TokenStream { body.extend(it); - for ver in config.versions { + let candidate = (group == "AGX_ROOT").then_some(&["G14", "V27_2"][..]); + for ver in config.versions.iter().copied().chain(candidate) { let tag = ver.join(""); let mut ver_num = Vec::::new(); for (i, comp) in ver.iter().enumerate() { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py index 485241a564463..08a06e25ac76f 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py @@ -42,7 +42,7 @@ def body(source,marker): struct Quirks{handoff_lock:bool,clean_tables:bool} struct SlotTTBS{ttb0:AtomicU64,ttb1:AtomicU64}struct UatShared{handoff:Handoff,ttbs:[SlotTTBS;64],map_kernel_to_user:bool,kernel_ttb1:u64,binding_generations:[u64;64],binding_published:[bool;64],owned_user_roots:[u64;64],quirks:Quirks} impl UatShared{fn handoff(&self)->&Handoff{&self.handoff}fn ttbs(&self)->&[SlotTTBS;64]{&self.ttbs}} -struct UatInner{firmware:UatFirmware,m4_adopted:bool,failed:AtomicBool,shared:Mutex} +struct UatInner{firmware:UatFirmware,m4_adopted:bool,clean_poc:bool,failed:AtomicBool,shared:Mutex} ''' mid=mid.replace('impl UatShared{','impl UatShared{'+''.join(body(mm,m) for m in ['fn handoff_lock(', 'fn handoff_unlock(', 'fn publish_slot('])) raii='#[path="'+str(ROOT/'drivers/gpu/drm/asahi/mmu/ppl.rs')+'"]mod ppl;\n'+'\n'.join(body(mm,m) for m in [ @@ -51,7 +51,7 @@ def body(source,marker): ]) inner='impl UatInner{\n'+'\n'.join(body(mm,m) for m in ['fn lock(&self) -> Guard', 'fn check_m4(', 'fn lock_handoff(', 'fn lock_m4_upper('])+'\n}\n' models=r''' -fn uat(m4:bool,firmware:UatFirmware)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],quirks:Quirks{handoff_lock:true,clean_tables:false}})})} +fn uat(m4:bool,firmware:UatFirmware)->Rc{Rc::new(UatInner{firmware,m4_adopted:m4,clean_poc:false,failed:AtomicBool::new(false),shared:Mutex::new(UatShared{handoff:Handoff::new(),ttbs:std::array::from_fn(|_|SlotTTBS{ttb0:AtomicU64::new(0),ttb1:AtomicU64::new(0)}),map_kernel_to_user:!m4,kernel_ttb1:0x800000000,binding_generations:[0;64],binding_published:[false;64],owned_user_roots:[0;64],quirks:Quirks{handoff_lock:true,clean_tables:false}})})} #[derive(Clone,Copy)]struct Prot{cached:bool}impl Prot{fn is_cached_noncoherent(&self)->bool{self.cached}} struct Mutation;impl Drop for Mutation{fn drop(&mut self){MUTATIONS.fetch_sub(1,Ordering::Relaxed);}} struct MapTable{fail:bool}impl MapTable{fn unmap_pages(&mut self,_r:Range)->Result{LEAF_CLEARS.fetch_add(1,Ordering::Relaxed);if self.fail{Err(EIO)}else{Ok(())}}}