upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/acphal.cpp
diff options
context:
space:
mode:
authorDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-24 21:09:02 +0100
committerDadaCap <167002618+DadaCap@users.noreply.github.com>2026-11-24 21:09:02 +0100
commitbc245e5046124941bbdc7bb5c3bd7c739da4e03e (patch)
tree5b780fbcbc1dd131ee635980dfe3e996ac72928f /runtime/shims/acphal.cpp
parent30450e0e96e1df700bbfa9505433c9b9940e8694 (diff)
parent58be9cdf8df9a31bc7f6c068991f1aed381f7f4d (diff)
Merge remote-tracking branch 'origin/main' into vcc-tuple-resync
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/shims/acphal.cpp')
-rw-r--r--runtime/shims/acphal.cpp873
1 files changed, 769 insertions, 104 deletions
diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp
index 5ead016d6..f1c33ddd9 100644
--- a/runtime/shims/acphal.cpp
+++ b/runtime/shims/acphal.cpp
@@ -1,10 +1,12 @@
1// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine 1// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine
2// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series. 2// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series.
3// 3//
4// On a PC there is no SHAPE/ACP hardware and APU physical memory does not exist. 4// Provides:
5// This shim creates the APU heap from process memory and manages allocations within it. 5// - A VirtualAlloc-backed APU heap (cached + non-cached) with 32-bit device addresses;
6// The SHAPE context arrays are allocated on the process heap; the ACP interface 6// - SHAPE context arrays sized to the documented GDK strides;
7// accepts and acknowledges commands to allow audio bring-up to proceed cleanly. 7// - The IAcpHal command and message queue (registration, completion, disconnect,
8// flowgraph acknowledgement, and APU notification word writes);
9// - A background XMA2 decoder pumping enabled SHAPE_XMA_CONTEXT output rings.
8// 10//
9// Signatures from the public GDK reference (devdocs.xbox.com): 11// Signatures from the public GDK reference (devdocs.xbox.com):
10// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS. 12// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS.
@@ -14,21 +16,37 @@
14 16
15#include <windows.h> 17#include <windows.h>
16 18
17#include <atomic> 19#include <algorithm>
18#include <array> 20#include <array>
21#include <atomic>
22#include <chrono>
23#include <climits>
24#include <condition_variable>
19#include <cstddef> 25#include <cstddef>
20#include <cstdint> 26#include <cstdint>
21#include <cstdio> 27#include <cstdio>
22#include <cstdlib> 28#include <cstdlib>
23#include <cstring> 29#include <cstring>
30#include <deque>
24#include <map> 31#include <map>
32#include <memory>
25#include <mutex> 33#include <mutex>
34#include <new>
35#include <optional>
26#include <set> 36#include <set>
37#include <shared_mutex>
38#include <stop_token>
27#include <string> 39#include <string>
40#include <string_view>
41#include <system_error>
42#include <thread>
28#include <vector> 43#include <vector>
29 44
30#include "shims.h" 45#include "shims.h"
31#include "startup_trace.h" 46#include "startup_trace.h"
47#if defined(LEONIDA_HAVE_XMA2_DECODER)
48#include "leonida_xma2_decoder.h"
49#endif
32 50
33namespace { 51namespace {
34 52
@@ -124,24 +142,7 @@ struct SHAPE_DMA_CONTEXT {
124static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK"); 142static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK");
125 143
126struct SHAPE_XMA_CONTEXT { 144struct SHAPE_XMA_CONTEXT {
127 uint32_t sizeRead0 : 12; 145 uint32_t words[16]; // See the shared word layout above the XMA engine.
128 uint32_t numLoops : 8;
129 uint32_t validBuffer : 2;
130 uint32_t sizeWrite : 5;
131 uint32_t offsetWrite : 5;
132 uint32_t sizeRead1 : 12;
133 uint32_t sequenceNumber : 12;
134 uint32_t stopSampleAddress : 8;
135 uint32_t subframeOffset : 4;
136 uint32_t reserved0 : 1;
137 uint32_t isLooping : 1;
138 uint32_t subframeSkip : 2;
139 uint32_t packetMetadata : 16;
140 uint32_t currentByteOffset : 26;
141 uint32_t reserved1 : 6;
142 uint32_t loopStartOffset : 26;
143 uint32_t loopEndOffset : 6;
144 uint32_t reserved[11]; // the GDK's 64-byte context: the published field list leaves one trailing word
145}; 146};
146static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK"); 147static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK");
147 148
@@ -194,21 +195,28 @@ static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38,
194 195
195// ---- Startup trace helper ---- 196// ---- Startup trace helper ----
196 197
197void trace_call(const char* api, const std::string& detail) { 198void trace_call(const char* api, std::string_view detail = {}) noexcept try {
198 if (!rt::startup_trace::enabled()) return; 199 if (!rt::startup_trace::enabled()) return;
199 static std::mutex mutex; 200 static std::mutex mutex;
200 static std::set<std::string> seen; 201 static std::set<std::string> seen;
201 { 202 {
202 const std::lock_guard lock(mutex); 203 const std::lock_guard lock(mutex);
203 if (!seen.insert(std::string(api) + detail).second) return; 204 if (!seen.insert(std::string(api).append(detail)).second) return;
204 } 205 }
205 rt::startup_trace::event("acphal", 206 rt::startup_trace::event("acphal",
206 std::string("\"api\":\"") + api + "\"" + detail); 207 (std::string("\"api\":\"") + api + "\"").append(detail));
208} catch (...) {
209 // Tracing cannot change the result of a guest-facing call.
207} 210}
208 211
209// ---- Genuine APU Heap Implementation ---- 212// ---- Genuine APU Heap Implementation ----
210 213
211constexpr uint32_t kApuBaseAddress = 0x40000000u; 214constexpr uint32_t kApuBaseAddress = 0x40000000u;
215constexpr uint64_t kApuRegionAlignment = 0x10000u;
216
217uint64_t align_apu_region(uint64_t size) {
218 return (size + kApuRegionAlignment - 1) & ~(kApuRegionAlignment - 1);
219}
212 220
213struct ApuRegion { 221struct ApuRegion {
214 void* base = nullptr; 222 void* base = nullptr;
@@ -241,6 +249,13 @@ struct ApuRegion {
241 return static_cast<uint8_t*>(base) + offset; 249 return static_cast<uint8_t*>(base) + offset;
242 } 250 }
243 251
252 uint8_t* span_from_offset(uint32_t offset, std::size_t len) const {
253 if (!base || len == 0 || offset >= size) return nullptr;
254 const uint64_t remaining = size - offset;
255 if (len > remaining) return nullptr;
256 return static_cast<uint8_t*>(base) + offset;
257 }
258
244 void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) { 259 void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) {
245 if (alloc_size == 0 || alignment == 0) return nullptr; 260 if (alloc_size == 0 || alignment == 0) return nullptr;
246 uint64_t at = 0; 261 uint64_t at = 0;
@@ -281,48 +296,667 @@ ApuRegion g_cached_heap;
281ApuRegion g_noncached_heap; 296ApuRegion g_noncached_heap;
282 297
283// Tracked SHAPE context arrays 298// Tracked SHAPE context arrays
284std::vector<void*> g_active_shape_arrays; 299struct ShapeArrayFree {
300 void operator()(void* array) const noexcept { std::free(array); }
301};
302
303using ShapeAllocation = std::array<std::unique_ptr<void, ShapeArrayFree>, 6>;
304
305std::mutex g_shape_mutex;
306std::vector<ShapeAllocation> g_shape_allocations;
307
308// Resolves a contiguous [apu, apu + len) byte range inside the APU heap.
309uint8_t* apu_span(uint32_t apu, std::size_t len) {
310 if (apu < kApuBaseAddress || len == 0) return nullptr;
311 std::lock_guard lock(g_apu_mutex);
312 const uint32_t offset = apu - kApuBaseAddress;
313 if (g_cached_heap.base && offset < g_cached_heap.size) {
314 return g_cached_heap.span_from_offset(offset, len);
315 }
316 if (g_noncached_heap.base) {
317 const uint64_t cached_span = align_apu_region(g_cached_heap.size);
318 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
319 return g_noncached_heap.span_from_offset(
320 static_cast<uint32_t>(offset - cached_span), len);
321 }
322 }
323 return nullptr;
324}
325
326// ---- ACP Command / Message Protocol Constants ----
327
328constexpr uint32_t kCmdLoadFlowgraph = 1;
329constexpr uint32_t kCmdRegisterMessages = 2;
330constexpr uint32_t kCmdUnregisterMessages = 3;
331constexpr uint32_t kCmdEnableXma = 5;
332constexpr uint32_t kCmdEnableXmas = 6;
333constexpr uint32_t kCmdDisableXma = 7;
334constexpr uint32_t kCmdDisableXmas = 8;
335constexpr uint32_t kCmdAdvanceXmaRead = 18;
336
337constexpr uint32_t kMsgFlowgraphCompleted = 0x02u;
338constexpr uint32_t kMsgCommandCompleted = 0x10u;
339constexpr uint32_t kMsgDisconnected = 0x80u;
340
341// 128 samples per audio frame at 48 kHz = 375 audio frames/second.
342constexpr uint64_t kAudioFramesPerSecond = 375;
343
344// ---- XMA2 Hardware Context Decoder Engine ----
345//
346// Each 64-byte SHAPE_XMA_CONTEXT holds 16 32-bit words shared with the title:
347// Word 0: input 0 packets (0..11), loop count (12..19, 255 = forever),
348// valid input bits (20..21), output ring blocks (22..26), write block (27..31).
349// Word 1: input 1 packets (0..11), loop end subframe (12..13), loop start skip subframes
350// (17..19), initial skip subframes (24..26), rate index (27..28: 24/32/44.1/48 kHz),
351// stereo (29), output writable (31).
352// Word 2: read bit offset (0..25), error status (26..30), error flag (31).
353// Word 3: loop start bit offset (0..25).
354// Word 4: loop end bit offset (0..25), current input buffer index (31).
355// Word 5: input 0 APU address.
356// Word 6: input 1 APU address.
357// Word 7: output ring APU address.
358// Word 8: overlap buffer APU address.
359// Word 9: output read block index (0..4).
360//
361// Packets are decoded by the Rust decoder in runtime/xma_decoder when CMake found cargo (LEONIDA_HAVE_XMA2_DECODER);
362// otherwise each packet becomes silence for its frame count. The read offset (word 2) and the loop points (words 3
363// and 4) are used per 2048-byte packet, so the loop-end subframe (word 1 bits 12..13) is not applied.
364
365constexpr std::size_t kXmaBlockBytes = 256;
366constexpr std::size_t kXmaSamplesPerBlock = kXmaBlockBytes / 2;
367constexpr std::size_t kXmaPacketBytes = 2048;
368constexpr std::size_t kXmaPacketBits = kXmaPacketBytes * 8;
369constexpr std::size_t kXmaSubframeSamples = 128;
370constexpr std::size_t kXmaFrameSamples = 512;
371constexpr uint32_t kXmaErrorInputInvalid = 4;
372
373#if defined(LEONIDA_HAVE_XMA2_DECODER)
374constexpr uint32_t kXmaRates[4] = {24000, 32000, 44100, 48000};
375struct Xma2DecoderFree {
376 void operator()(LeonidaXma2Decoder* d) const noexcept { leonida_xma2_decoder_destroy(d); }
377};
378struct Xma2PcmFree {
379 void operator()(LeonidaXma2PcmBlock* b) const noexcept { leonida_xma2_pcm_destroy(b); }
380};
381#endif
382
383struct XmaContextView {
384 uint32_t* words = nullptr;
385
386 uint32_t get(std::size_t index) const { return std::atomic_ref(words[index]).load(); }
387
388 uint32_t field(std::size_t index, uint32_t shift, uint32_t bits) const {
389 const uint32_t mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
390 return (get(index) >> shift) & mask;
391 }
392
393 uint32_t set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const {
394 const uint32_t raw_mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
395 const uint32_t mask = raw_mask << shift;
396 const uint32_t field_value = (value << shift) & mask;
397 std::atomic_ref word(words[index]);
398 uint32_t previous = word.load();
399 while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {}
400 return previous;
401 }
402
403};
404
405struct XmaVoice {
406 explicit XmaVoice(uint32_t format_bits) : pcm(0), format(format_bits) {}
407 std::size_t channels() const { return 1u + (format >> 2); }
408 std::size_t queued_samples() const { return pcm.size() - pcm_read; }
409
410#if defined(LEONIDA_HAVE_XMA2_DECODER)
411 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder;
412#endif
413 std::vector<int16_t> pcm;
414 std::size_t pcm_read = 0;
415 std::size_t loop_skip = 0; // samples per channel to drop after a rewind
416 uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout
417 bool ended = false;
418};
419
420struct XmaVoiceSlot {
421 std::mutex mutex;
422 std::optional<XmaVoice> voice;
423};
424
425class XmaEngine {
426public:
427 ~XmaEngine() { unbind(); }
428
429 void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) {
430 // Construct with a size so MSVC's Debug iterator allocations can also fail
431 // through this call instead of the noexcept default constructor.
432 std::vector<std::unique_ptr<XmaVoiceSlot>> slots(count);
433 for (auto& slot : slots) slot = std::make_unique<XmaVoiceSlot>();
434 unbind();
435 std::unique_lock lock(table_mutex_);
436 array_ = array;
437 voices_.swap(slots);
438 }
439
440 void unbind() {
441 {
442 std::unique_lock lock(table_mutex_);
443 array_ = nullptr;
444 voices_.clear();
445 active_count_.store(0, std::memory_order_relaxed);
446 }
447 // Once detached, commands cannot start a worker for this table.
448 stop_worker();
449 }
450
451 bool handle_command(uint32_t command, const void* config) {
452 auto read_word = [config](std::size_t index) -> uint32_t {
453 if (!config) return 0u;
454 uint32_t value = 0;
455 std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t),
456 sizeof(uint32_t));
457 return value;
458 };
459
460 switch (command) {
461 case kCmdEnableXma:
462 if (config) enable(read_word(0));
463 return true;
464 case kCmdDisableXma:
465 if (config) disable(read_word(0));
466 return true;
467 case kCmdEnableXmas:
468 case kCmdDisableXmas: {
469 std::shared_lock lock(table_mutex_);
470 const std::size_t count = voices_.size();
471 lock.unlock();
472 if (!config) return true;
473 for (std::size_t i = 0; i < count; ++i) {
474 const uint32_t bits = read_word(i / 32);
475 if ((bits & (1u << (i % 32))) != 0) {
476 if (command == kCmdEnableXmas) {
477 enable(static_cast<uint32_t>(i));
478 } else {
479 disable(static_cast<uint32_t>(i));
480 }
481 }
482 }
483 return true;
484 }
485 case kCmdAdvanceXmaRead:
486 if (config) advance_read(read_word(0), read_word(1));
487 return true;
488 default:
489 return false;
490 }
491 }
492
493 void enable(uint32_t index) {
494 std::shared_lock table_lock(table_mutex_);
495 XmaContextView ctx = context_locked(index);
496 if (!ctx.words) return;
497
498 {
499 std::lock_guard slot_lock(voices_[index]->mutex);
500 auto& voice = voices_[index]->voice;
501 const uint32_t format = ctx.field(1, 27, 3);
502 // The worker cannot access the voice until the slot is unlocked.
503 ensure_worker_and_wake();
504 if (!voice) {
505 voice.emplace(format);
506 active_count_.fetch_add(1, std::memory_order_relaxed);
507 } else if (voice->format != format) {
508 voice->pcm.clear();
509 voice->pcm_read = 0;
510 voice->loop_skip = 0;
511 voice->format = format;
512#if defined(LEONIDA_HAVE_XMA2_DECODER)
513 voice->decoder.reset();
514#endif
515 }
516 voice->ended = false;
517 ctx.set_field(2, 26, 6, 0);
518 }
519 }
520
521 void disable(uint32_t index) {
522 std::shared_lock table_lock(table_mutex_);
523 if (index >= voices_.size()) return;
524 std::lock_guard slot_lock(voices_[index]->mutex);
525 if (voices_[index]->voice.has_value()) {
526 voices_[index]->voice.reset();
527 active_count_.fetch_sub(1, std::memory_order_relaxed);
528 }
529 }
530
531 void advance_read(uint32_t index, uint32_t blocks) {
532 std::shared_lock table_lock(table_mutex_);
533 XmaContextView ctx = context_locked(index);
534 if (!ctx.words) return;
535
536 bool wake = false;
537 {
538 std::lock_guard slot_lock(voices_[index]->mutex);
539 const uint32_t size = ctx.field(0, 22, 5);
540 if (size == 0) return;
541 const uint32_t read = (ctx.field(9, 0, 5) + blocks % size) % size;
542 ctx.set_field(9, 0, 5, read);
543 if (blocks > 0) {
544 ctx.set_field(1, 31, 1, 1);
545 }
546 wake = voices_[index]->voice.has_value();
547 }
548 if (wake) ensure_worker_and_wake();
549 }
550
551private:
552 XmaContextView context_locked(uint32_t index) const {
553 if (!array_ || index >= voices_.size()) return {};
554 return XmaContextView{array_[index].words};
555 }
556
557 // Appends interleaved s16 for one 2048-byte packet. Without the Rust decoder, or when it
558 // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds.
559 static void decode_packet(XmaVoice& voice, const uint8_t* bytes) {
560 const std::size_t channels = voice.channels();
561#if defined(LEONIDA_HAVE_XMA2_DECODER)
562 if (!voice.decoder) {
563 LeonidaXma2Decoder* raw = nullptr;
564 if (leonida_xma2_decoder_create_hardware(kXmaRates[voice.format & 3u],
565 static_cast<uint32_t>(channels), &raw) == LEONIDA_XMA2_OK) {
566 voice.decoder.reset(raw);
567 }
568 }
569 if (voice.decoder) {
570 LeonidaXma2PcmBlock* raw = nullptr;
571 if (leonida_xma2_decode_buffer(voice.decoder.get(), bytes, kXmaPacketBytes, &raw) == LEONIDA_XMA2_OK) {
572 const std::unique_ptr<LeonidaXma2PcmBlock, Xma2PcmFree> block(raw);
573 const int16_t* samples = leonida_xma2_pcm_data(block.get());
574 const std::size_t count = leonida_xma2_pcm_sample_count(block.get());
575 if (count != 0) voice.pcm.insert(voice.pcm.end(), samples, samples + count);
576 return;
577 }
578 voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence.
579 }
580#endif
581 voice.pcm.resize(voice.pcm.size() + static_cast<std::size_t>(bytes[0] >> 2) * kXmaFrameSamples * channels);
582 }
583
584 // Decodes the packet at the read offset of the current input buffer and queues its PCM.
585 // Offsets and loop points are used per packet: a loop plays its end packet in full and
586 // restarts at the start of the packet holding the loop start.
587 static bool decode_one_packet(XmaContextView ctx, XmaVoice& voice) {
588 if (voice.ended) return false;
589
590 const std::size_t channels = voice.channels();
591 uint32_t current = ctx.field(4, 31, 1);
592 const uint32_t valid = ctx.field(0, 20, 2);
593
594 if (valid == 0) {
595 voice.ended = true;
596 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
597 return voice.queued_samples() != 0;
598 }
599 if ((valid & (1u << current)) == 0) {
600 current ^= 1u;
601 ctx.set_field(4, 31, 1, current);
602 }
603
604 const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6);
605 const std::size_t packets = (current == 0) ? ctx.field(0, 0, 12) : ctx.field(1, 0, 12);
606 const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits;
607 const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes);
608 if (!data || packet >= packets) {
609 finish_input(ctx, current, packet >= packets ? packet - packets : 0);
610 return true;
611 }
612
613 const uint8_t* packet_data = data + packet * kXmaPacketBytes;
614 const uint8_t packet_skip = packet_data[3];
615 // Decoding is only requested when less than a ring block remains. Keep that
616 // tail and reuse the packet storage as the voice consumes subsequent packets.
617 voice.pcm.erase(voice.pcm.begin(), voice.pcm.begin() + static_cast<std::ptrdiff_t>(voice.pcm_read));
618 voice.pcm_read = 0;
619 const std::size_t packet_start = voice.pcm.size();
620 decode_packet(voice, packet_data);
621 const std::size_t packet_samples = voice.pcm.size() - packet_start;
622 const std::size_t subframe_samples = kXmaSubframeSamples * channels;
623 const std::size_t initial_skip = ctx.field(1, 24, 3);
624 const std::size_t skipped_subframes = std::min(initial_skip, packet_samples / subframe_samples);
625 const std::size_t initial_samples = skipped_subframes * subframe_samples;
626 const std::size_t loop_samples = std::min(voice.loop_skip * channels, packet_samples - initial_samples);
627 const std::size_t skip_samples = initial_samples + loop_samples;
628 if (skip_samples != 0) {
629 const auto first = voice.pcm.begin() + static_cast<std::ptrdiff_t>(packet_start);
630 voice.pcm.erase(first, first + static_cast<std::ptrdiff_t>(skip_samples));
631 }
632 // Update the context only after the PCM append succeeds.
633 if (skipped_subframes != 0) {
634 ctx.set_field(1, 24, 3, static_cast<uint32_t>(initial_skip - skipped_subframes));
635 }
636 voice.loop_skip -= loop_samples / channels;
637
638 // XMA2 packet headers link packets from the same stream; 0xff ends the chain.
639 std::size_t next = packet_skip == 0xFFu ? packets : packet + 1 + packet_skip;
640 const uint32_t loops = ctx.field(0, 12, 8);
641 const std::size_t loop_end = ctx.field(4, 0, 26);
642 if (loops > 0 && loop_end != 0 && packet == loop_end / kXmaPacketBits) {
643 next = ctx.field(3, 0, 26) / kXmaPacketBits;
644 voice.loop_skip = static_cast<std::size_t>(ctx.field(1, 17, 3)) * kXmaSubframeSamples;
645#if defined(LEONIDA_HAVE_XMA2_DECODER)
646 // A frame spilling out of the loop-end packet does not continue in the loop-start packet:
647 // start a fresh decoder there rather than decode the spliced bits.
648 voice.decoder.reset();
649#endif
650 if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u);
651 }
652 if (next >= packets) {
653 finish_input(ctx, current, next - packets);
654 } else {
655 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next * kXmaPacketBits));
656 }
657 return true;
658 }
659
660 static void finish_input(XmaContextView ctx, uint32_t current,
661 std::size_t skip_packets) {
662 // Publish the next offset before telling the title it can refill this input.
663 ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits));
664 const uint32_t other = 1u - current;
665 const uint32_t retired = ctx.set_field(0, 20 + current, 1, 0);
666 // Take the other input if it was queued at retirement. Otherwise a double
667 // refill of the empty pair starts at input 0. A lone input can still run.
668 ctx.set_field(4, 31, 1, (retired & (1u << (20 + other))) != 0 ? other : 0u);
669 }
670
671 static void pump_voice(XmaContextView ctx, XmaVoice& voice) {
672 const uint32_t size = ctx.field(0, 22, 5);
673 if (size == 0 || ctx.field(1, 31, 1) == 0) return;
674 auto* ring = apu_span(ctx.get(7), size * kXmaBlockBytes);
675 if (!ring) return;
676
677 for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) {
678 int decode_guard = 0;
679 while (voice.queued_samples() < kXmaSamplesPerBlock && decode_guard++ < 16) {
680 if (!decode_one_packet(ctx, voice)) break;
681 }
682 if (voice.queued_samples() == 0) return;
683
684 const uint32_t write = ctx.field(0, 27, 5) % size;
685 uint8_t* out = ring + write * kXmaBlockBytes;
686
687 for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) {
688 int16_t sample = 0;
689 if (voice.pcm_read != voice.pcm.size()) {
690 sample = voice.pcm[voice.pcm_read++];
691 }
692 const uint16_t raw = static_cast<uint16_t>(sample);
693 out[2 * i] = static_cast<uint8_t>(raw & 0xFFu);
694 out[2 * i + 1] = static_cast<uint8_t>((raw >> 8) & 0xFFu);
695 }
696
697 const uint32_t next_write = (write + 1u) % size;
698 ctx.set_field(0, 27, 5, next_write);
699 if (next_write == ctx.field(9, 0, 5) % size) {
700 ctx.set_field(1, 31, 1, 0);
701 }
702 }
703 }
704
705 void pump_all() {
706 std::shared_lock table_lock(table_mutex_);
707 if (!array_) return;
708 for (std::size_t i = 0; i < voices_.size(); ++i) {
709 std::lock_guard slot_lock(voices_[i]->mutex);
710 auto& voice = voices_[i]->voice;
711 if (!voice) continue;
712 auto ctx = context_locked(static_cast<uint32_t>(i));
713 try {
714 pump_voice(ctx, *voice);
715 } catch (const std::bad_alloc&) {
716 // Only this voice failed. Retire it and allow the title to enable it again.
717 voice.reset();
718 active_count_.fetch_sub(1, std::memory_order_relaxed);
719 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
720 }
721 }
722 }
723
724 void ensure_worker_and_wake() {
725 std::lock_guard lock(worker_mutex_);
726 if (!worker_.joinable()) {
727 worker_ = std::jthread([this](std::stop_token stop) { worker_loop(stop); });
728 }
729 wake_requested_ = true;
730 worker_cv_.notify_one();
731 }
732
733 // Each worker owns its stop_token, so a stop only ever reaches the thread it was
734 // sent to; a worker started after this call is unaffected by it.
735 void stop_worker() {
736 std::jthread to_join;
737 {
738 std::lock_guard lock(worker_mutex_);
739 if (!worker_.joinable()) return;
740 worker_.request_stop();
741 worker_cv_.notify_all();
742 to_join = std::move(worker_);
743 }
744 if (to_join.joinable()) to_join.join();
745 }
746
747 void worker_loop(std::stop_token stop) {
748 for (;;) {
749 {
750 std::unique_lock lock(worker_mutex_);
751 if (stop.stop_requested()) return;
752 if (active_count_.load(std::memory_order_relaxed) == 0 && !wake_requested_) {
753 worker_cv_.wait(lock, stop, [this]() { return wake_requested_; });
754 if (stop.stop_requested()) return;
755 }
756 wake_requested_ = false;
757 }
758
759 pump_all();
760
761 std::unique_lock lock(worker_mutex_);
762 if (stop.stop_requested()) return;
763 if (!wake_requested_ && active_count_.load(std::memory_order_relaxed) > 0) {
764 // One 256-byte output block lasts ~2.67 ms at 48 kHz mono.
765 worker_cv_.wait_for(lock, stop, std::chrono::milliseconds(2),
766 [this]() { return wake_requested_; });
767 }
768 }
769 }
770
771 mutable std::shared_mutex table_mutex_;
772 SHAPE_XMA_CONTEXT* array_ = nullptr;
773 std::vector<std::unique_ptr<XmaVoiceSlot>> voices_;
774 std::atomic<uint32_t> active_count_{0};
775
776 std::mutex worker_mutex_;
777 std::condition_variable_any worker_cv_;
778 std::jthread worker_;
779 bool wake_requested_ = false;
780};
781
782XmaEngine g_xma_engine;
285 783
286// ---- IAcpHal Interface Implementation ---- 784// ---- IAcpHal Interface Implementation ----
287 785
288struct AcpHalImpl { 786#pragma pack(push, 1)
787struct AcpMessage {
788 uint32_t kind = 0;
789 uint32_t dropped = 0;
790 uint32_t usec = 0;
791 uint8_t data[16]{};
792};
793#pragma pack(pop)
794static_assert(sizeof(AcpMessage) == 28, "AcpMessage is 28 bytes");
795
796void write_u32_le(uint8_t* dst, uint32_t value) {
797 dst[0] = static_cast<uint8_t>(value & 0xFFu);
798 dst[1] = static_cast<uint8_t>((value >> 8) & 0xFFu);
799 dst[2] = static_cast<uint8_t>((value >> 16) & 0xFFu);
800 dst[3] = static_cast<uint8_t>((value >> 24) & 0xFFu);
801}
802
803void write_u64_le(uint8_t* dst, uint64_t value) {
804 write_u32_le(dst, static_cast<uint32_t>(value & 0xFFFFFFFFu));
805 write_u32_le(dst + 4, static_cast<uint32_t>(value >> 32));
806}
807
808struct IAcpHal {
809 virtual HRESULT __stdcall connect(uint32_t commands, uint32_t messages) = 0;
810 virtual HRESULT __stdcall disconnect() = 0;
811 virtual HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
812 const void* config, uint32_t notification) = 0;
813 virtual uint32_t __stdcall pop_message(void* out) = 0;
814 virtual uint32_t __stdcall get_num_messages() = 0;
815 virtual HRESULT __stdcall release() = 0;
816};
817
818struct AcpHalImpl final : IAcpHal {
819 std::mutex mutex_;
820 bool connected_ = false;
821 uint32_t mask_ = 0;
822 std::deque<AcpMessage> messages_;
823 std::size_t capacity_ = 0;
824 uint32_t dropped_ = 0;
825 std::chrono::steady_clock::time_point since_ = std::chrono::steady_clock::now();
826
827 uint64_t elapsed_usec_locked() const {
828 const auto dt = std::chrono::steady_clock::now() - since_;
829 return static_cast<uint64_t>(
830 std::chrono::duration_cast<std::chrono::microseconds>(dt).count());
831 }
832
833 uint32_t audio_frame_locked() const {
834 return static_cast<uint32_t>((elapsed_usec_locked() * kAudioFramesPerSecond) / 1000000ull);
835 }
836
837 void post_locked(uint32_t kind, const uint8_t* payload, std::size_t len) {
838 if ((mask_ & kind) == 0) return;
839 if (messages_.size() >= capacity_) {
840 if (dropped_ < UINT32_MAX) ++dropped_;
841 return;
842 }
843 AcpMessage msg{};
844 msg.kind = kind;
845 msg.dropped = dropped_;
846 msg.usec = static_cast<uint32_t>(elapsed_usec_locked());
847 if (payload && len > 0) {
848 std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data)));
849 }
850 try {
851 messages_.push_back(msg);
852 dropped_ = 0;
853 } catch (const std::bad_alloc&) {
854 if (dropped_ < UINT32_MAX) ++dropped_;
855 }
856 }
857
289 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) 858 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked)
290 virtual HRESULT __stdcall connect(uint32_t, uint32_t) { 859 HRESULT __stdcall connect(uint32_t commands, uint32_t messages) override {
291 trace_call("AcpHal::Connect", ""); 860 trace_call("AcpHal::Connect", "");
861 if (commands == 0) return E_INVALIDARG;
862 std::lock_guard lock(mutex_);
863 connected_ = true;
864 capacity_ = messages;
292 return S_OK; 865 return S_OK;
293 } 866 }
294 867
295 // Slot 1: Disconnect (called at shutdown) 868 // Slot 1: Disconnect (called at shutdown)
296 virtual HRESULT __stdcall disconnect() { 869 HRESULT __stdcall disconnect() override {
297 trace_call("AcpHal::Disconnect", ""); 870 trace_call("AcpHal::Disconnect", "");
871 std::lock_guard lock(mutex_);
872 if (!connected_) return E_FAIL;
873 post_locked(kMsgDisconnected, nullptr, 0);
874 connected_ = false;
298 return S_OK; 875 return S_OK;
299 } 876 }
300 877
301 // Slot 2: SubmitCommand 878 // Slot 2: SubmitCommand
302 // Critical: The title calls slot 2 as (2, 0xf0f0f0f0, -1, config, 0) and 879 // Acknowledges command completion, updates registered message masks, dispatches
303 // a negative result triggers a fatal int3 kernel panic (+0x43ad94e). 880 // XMA voice commands, and writes any requested APU notification word.
304 virtual HRESULT __stdcall submit_command(uint32_t cmd, uint32_t d1, uint32_t d2, 881 HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
305 const void* config, uint32_t d3) { 882 const void* config, uint32_t notification) override try {
306 (void)cmd; 883 (void)frame;
307 (void)d1; 884 auto read_word = [config](std::size_t index) -> uint32_t {
308 (void)d2; 885 if (!config) return 0u;
309 (void)config; 886 uint32_t value = 0;
310 (void)d3; 887 std::memcpy(&value, static_cast<const uint8_t*>(config) + index * sizeof(uint32_t),
311 static std::atomic<bool> warned{false}; 888 sizeof(uint32_t));
312 if (!warned.exchange(true, std::memory_order_relaxed)) { 889 return value;
313 std::fprintf(stderr, 890 };
314 "[rt] acphal: command accepted and dropped: no audio DSP hardware on PC\n"); 891
892 const bool handled_xma = g_xma_engine.handle_command(cmd, config);
893 {
894 std::lock_guard lock(mutex_);
895 if (!handled_xma) {
896 switch (cmd) {
897 case kCmdRegisterMessages:
898 mask_ |= read_word(0);
899 break;
900 case kCmdUnregisterMessages:
901 mask_ &= ~read_word(0);
902 break;
903 case kCmdLoadFlowgraph: {
904 uint8_t payload[4];
905 write_u32_le(payload, read_word(1));
906 post_locked(kMsgFlowgraphCompleted, payload, sizeof(payload));
907 break;
908 }
909 default:
910 break;
911 }
912 }
913 if (id != 0) {
914 uint8_t done[16];
915 write_u32_le(done, cmd);
916 write_u64_le(done + 4, id);
917 write_u32_le(done + 12, audio_frame_locked());
918 post_locked(kMsgCommandCompleted, done, sizeof(done));
919 }
920 }
921
922 if (notification != 0) {
923 if (uint8_t* word_bytes = apu_span(notification, sizeof(uint32_t))) {
924 if ((reinterpret_cast<uintptr_t>(word_bytes) & 3u) == 0) {
925 *reinterpret_cast<volatile uint32_t*>(word_bytes) = 1u;
926 } else {
927 static constexpr uint8_t kOneLe[4] = {1, 0, 0, 0};
928 volatile uint8_t* dst = word_bytes;
929 for (std::size_t i = 0; i < 4; ++i) dst[i] = kOneLe[i];
930 }
931 }
315 } 932 }
933
316 trace_call("AcpHal::SubmitCommand", ""); 934 trace_call("AcpHal::SubmitCommand", "");
317 return S_OK; 935 return S_OK;
936 } catch (const std::bad_alloc&) {
937 return E_OUTOFMEMORY;
938 } catch (const std::system_error&) {
939 return E_FAIL;
318 } 940 }
319 941
320 // Slots 3 and 4: PopMessage and GetNumMessages (message polling, not called by title) 942 // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty.
321 virtual uint32_t __stdcall pop_message() { return 0; } 943 uint32_t __stdcall pop_message(void* out) override {
322 virtual uint32_t __stdcall get_num_messages() { return 0; } 944 std::lock_guard lock(mutex_);
945 if (messages_.empty()) return 0u;
946 const AcpMessage msg = messages_.front();
947 messages_.pop_front();
948 if (out) std::memcpy(out, &msg, sizeof(msg));
949 return 1u;
950 }
951
952 // Slot 4: GetNumMessages
953 uint32_t __stdcall get_num_messages() override {
954 std::lock_guard lock(mutex_);
955 return static_cast<uint32_t>(messages_.size());
956 }
323 957
324 // Slot 5: Release 958 // Slot 5: Release
325 virtual HRESULT __stdcall release() { 959 HRESULT __stdcall release() override {
326 trace_call("AcpHal::Release", ""); 960 trace_call("AcpHal::Release", "");
327 delete this; 961 delete this;
328 return S_OK; 962 return S_OK;
@@ -333,7 +967,12 @@ struct AcpHalImpl {
333 967
334HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { 968HRESULT __stdcall AcpHalCreate(void** ppAcpHal) {
335 if (!ppAcpHal) return E_POINTER; 969 if (!ppAcpHal) return E_POINTER;
336 *ppAcpHal = new AcpHalImpl(); 970 *ppAcpHal = nullptr;
971 try {
972 *ppAcpHal = new AcpHalImpl();
973 } catch (const std::bad_alloc&) {
974 return E_OUTOFMEMORY;
975 }
337 trace_call("AcpHalCreate", ""); 976 trace_call("AcpHalCreate", "");
338 return S_OK; 977 return S_OK;
339} 978}
@@ -343,63 +982,79 @@ HRESULT __stdcall AcpHalCreate(void** ppAcpHal) {
343HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { 982HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
344 if (!ctx) return E_POINTER; 983 if (!ctx) return E_POINTER;
345 984
346 std::lock_guard lock(g_apu_mutex); 985 std::lock_guard lock(g_shape_mutex);
347 986
348 auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { 987 ShapeAllocation pending{};
988 std::size_t array_index = 0;
989 auto alloc_array = [&](uint32_t count, size_t elem_size) -> void* {
349 if (count == 0) return nullptr; 990 if (count == 0) return nullptr;
350 void* ptr = std::calloc(count, elem_size); 991 void* ptr = std::calloc(count, elem_size);
351 if (ptr) g_active_shape_arrays.push_back(ptr); 992 if (!ptr) throw std::bad_alloc();
993 pending[array_index++].reset(ptr);
352 return ptr; 994 return ptr;
353 }; 995 };
354 996
355 ctx->srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>( 997 SHAPE_CONTEXTS result{};
356 alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); 998 result.numSrcContexts = ctx->numSrcContexts;
357 ctx->eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>( 999 result.numEqCompContexts = ctx->numEqCompContexts;
358 alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); 1000 result.numFiltVolContexts = ctx->numFiltVolContexts;
359 ctx->filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>( 1001 result.numDmaContexts = ctx->numDmaContexts;
360 alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); 1002 result.numXmaContexts = ctx->numXmaContexts;
361 ctx->dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>( 1003 result.numPcmContexts = ctx->numPcmContexts;
362 alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); 1004 try {
363 ctx->xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>( 1005 result.srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>(
364 alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); 1006 alloc_array(result.numSrcContexts, sizeof(SHAPE_SRC_CONTEXT)));
365 ctx->pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>( 1007 result.eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>(
366 alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); 1008 alloc_array(result.numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT)));
367 1009 result.filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>(
368 // On PC there is no physical APU address translation for host context arrays; 1010 alloc_array(result.numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT)));
369 // assign unique synthetic addresses from the APU base. 1011 result.dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>(
370 ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0}; 1012 alloc_array(result.numDmaContexts, sizeof(SHAPE_DMA_CONTEXT)));
371 ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; 1013 result.xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>(
372 ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; 1014 alloc_array(result.numXmaContexts, sizeof(SHAPE_XMA_CONTEXT)));
373 ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; 1015 result.pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>(
374 ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; 1016 alloc_array(result.numPcmContexts, sizeof(SHAPE_PCM_CONTEXT)));
375 ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; 1017
376 1018 // Assign synthetic APU addresses to the host-side context arrays.
377 trace_call("AcpHalAllocateShapeContexts", 1019 result.apuSrcContextArray = {result.srcContextArray ? kApuBaseAddress : 0};
378 ",\"src\":" + std::to_string(ctx->numSrcContexts) + 1020 result.apuEqCompContextArray = {result.eqCompContextArray ? kApuBaseAddress + 0x1000 : 0};
379 ",\"xma\":" + std::to_string(ctx->numXmaContexts) + 1021 result.apuFiltVolContextArray = {result.filtVolContextArray ? kApuBaseAddress + 0x2000 : 0};
380 ",\"pcm\":" + std::to_string(ctx->numPcmContexts)); 1022 result.apuDmaContextArray = {result.dmaContextArray ? kApuBaseAddress + 0x3000 : 0};
1023 result.apuXmaContextArray = {result.xmaContextArray ? kApuBaseAddress + 0x4000 : 0};
1024 result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0};
1025
1026 g_shape_allocations.reserve(g_shape_allocations.size() + 1);
1027 if (result.xmaContextArray) g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts);
1028 } catch (const std::bad_alloc&) {
1029 return E_OUTOFMEMORY;
1030 }
1031
1032 // Both the backing arrays and the engine's slots are now fully allocated.
1033 g_shape_allocations.push_back(std::move(pending));
1034 *ctx = result;
1035 if (rt::startup_trace::enabled()) {
1036 try {
1037 trace_call("AcpHalAllocateShapeContexts",
1038 ",\"src\":" + std::to_string(result.numSrcContexts) +
1039 ",\"xma\":" + std::to_string(result.numXmaContexts) +
1040 ",\"pcm\":" + std::to_string(result.numPcmContexts));
1041 } catch (const std::bad_alloc&) {
1042 // The allocation succeeded. A missing diagnostic does not invalidate it.
1043 }
1044 }
381 return S_OK; 1045 return S_OK;
382} 1046}
383 1047
384// ---- AcpHalReleaseShapeContexts ---- 1048// ---- AcpHalReleaseShapeContexts ----
385 1049
386HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { 1050HRESULT __stdcall AcpHalReleaseShapeContexts(void* /*hal*/) {
387 std::lock_guard lock(g_apu_mutex); 1051 std::lock_guard lock(g_shape_mutex);
388 1052 // Stop and detach the XMA worker before freeing backing arrays.
389 // Free all recorded context allocations 1053 g_xma_engine.unbind();
390 for (void* p : g_active_shape_arrays) {
391 if (p) std::free(p);
392 }
393 g_active_shape_arrays.clear();
394 1054
395 if (ctx) { 1055 // The export releases the process-wide SHAPE arrays. The argument is an
396 ctx->srcContextArray = nullptr; 1056 // opaque HAL handle, and allocation descriptors are owned by the caller.
397 ctx->eqCompContextArray = nullptr; 1057 g_shape_allocations.clear();
398 ctx->filtVolContextArray = nullptr;
399 ctx->dmaContextArray = nullptr;
400 ctx->xmaContextArray = nullptr;
401 ctx->pcmContextArray = nullptr;
402 }
403 1058
404 trace_call("AcpHalReleaseShapeContexts", ""); 1059 trace_call("AcpHalReleaseShapeContexts", "");
405 return S_OK; 1060 return S_OK;
@@ -411,6 +1066,9 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
411 uint32_t nonCachedSizeInBytes) { 1066 uint32_t nonCachedSizeInBytes) {
412 std::lock_guard lock(g_apu_mutex); 1067 std::lock_guard lock(g_apu_mutex);
413 if (g_apu_heap_created) return E_FAIL; 1068 if (g_apu_heap_created) return E_FAIL;
1069 const uint64_t address_bytes = (nonCachedSizeInBytes ? align_apu_region(cachedSizeInBytes)
1070 : cachedSizeInBytes) + nonCachedSizeInBytes;
1071 if (address_bytes > static_cast<uint64_t>(UINT32_MAX) + 1 - kApuBaseAddress) return E_INVALIDARG;
414 1072
415 if (cachedSizeInBytes > 0) { 1073 if (cachedSizeInBytes > 0) {
416 g_cached_heap.base = VirtualAlloc( 1074 g_cached_heap.base = VirtualAlloc(
@@ -430,17 +1088,23 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
430 } 1088 }
431 1089
432 g_apu_heap_created = true; 1090 g_apu_heap_created = true;
433 trace_call("ApuCreateHeap", 1091 if (rt::startup_trace::enabled()) {
434 ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + 1092 try {
435 ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); 1093 trace_call("ApuCreateHeap",
1094 ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) +
1095 ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes));
1096 } catch (const std::bad_alloc&) {
1097 // The heap is ready even if its diagnostic cannot be built.
1098 }
1099 }
436 return S_OK; 1100 return S_OK;
437} 1101}
438 1102
439// ---- ApuAlloc ---- 1103// ---- ApuAlloc ----
440 1104
441HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, 1105HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
442 uint32_t sizeInBytes, uint32_t alignmentInBytes, 1106 uint32_t sizeInBytes, uint32_t alignmentInBytes,
443 uint32_t flags) { 1107 uint32_t flags) try {
444 if (!virtualAddress) return E_POINTER; 1108 if (!virtualAddress) return E_POINTER;
445 *virtualAddress = nullptr; 1109 *virtualAddress = nullptr;
446 if (physicalAddress) *physicalAddress = 0; 1110 if (physicalAddress) *physicalAddress = 0;
@@ -459,6 +1123,7 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
459 1123
460 if (!target->base) { 1124 if (!target->base) {
461 if (!prefer_noncached) { 1125 if (!prefer_noncached) {
1126 if (g_apu_heap_created) return E_OUTOFMEMORY;
462 // Lazy default cached heap if ApuCreateHeap wasn't called yet 1127 // Lazy default cached heap if ApuCreateHeap wasn't called yet
463 constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024; 1128 constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024;
464 target->base = VirtualAlloc(nullptr, kDefaultHeapSize, 1129 target->base = VirtualAlloc(nullptr, kDefaultHeapSize,
@@ -485,17 +1150,17 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
485 1150
486 *virtualAddress = ptr; 1151 *virtualAddress = ptr;
487 if (physicalAddress) { 1152 if (physicalAddress) {
488 // Disjoint APU address ranges: 1153 // Leave alignment padding between the two synthetic address ranges.
489 // cached: 0x40000000 .. 0x40000000 + cached_size - 1
490 // non-cached: 0x40000000 + cached_size .. 0x40000000 + cached_size + noncached_size - 1
491 uint32_t apu = kApuBaseAddress + offset; 1154 uint32_t apu = kApuBaseAddress + offset;
492 if (target == &g_noncached_heap) { 1155 if (target == &g_noncached_heap) {
493 apu += static_cast<uint32_t>(g_cached_heap.size); 1156 apu += static_cast<uint32_t>(align_apu_region(g_cached_heap.size));
494 } 1157 }
495 *physicalAddress = apu; 1158 *physicalAddress = apu;
496 } 1159 }
497 1160
498 return S_OK; 1161 return S_OK;
1162} catch (const std::bad_alloc&) {
1163 return E_OUTOFMEMORY;
499} 1164}
500 1165
501// ---- ApuFree ---- 1166// ---- ApuFree ----
@@ -530,7 +1195,7 @@ void* __stdcall ApuMapApuAddress(uint32_t apu) {
530 return g_cached_heap.from_offset(offset); 1195 return g_cached_heap.from_offset(offset);
531 } 1196 }
532 if (g_noncached_heap.base) { 1197 if (g_noncached_heap.base) {
533 const uint32_t cached_span = static_cast<uint32_t>(g_cached_heap.size); 1198 const uint32_t cached_span = static_cast<uint32_t>(align_apu_region(g_cached_heap.size));
534 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { 1199 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
535 return g_noncached_heap.from_offset(offset - cached_span); 1200 return g_noncached_heap.from_offset(offset - cached_span);
536 } 1201 }
@@ -547,7 +1212,7 @@ uint32_t __stdcall ApuMapVirtualAddress(void* virtualAddress) {
547 return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress); 1212 return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress);
548 } 1213 }
549 if (g_noncached_heap.contains(virtualAddress)) { 1214 if (g_noncached_heap.contains(virtualAddress)) {
550 return kApuBaseAddress + static_cast<uint32_t>(g_cached_heap.size) + 1215 return kApuBaseAddress + static_cast<uint32_t>(align_apu_region(g_cached_heap.size)) +
551 g_noncached_heap.to_offset(virtualAddress); 1216 g_noncached_heap.to_offset(virtualAddress);
552 } 1217 }
553 return 0; 1218 return 0;