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:
authorandretuta <andreviniciusmerlia@gmail.com>2026-11-24 06:21:32 -0300
committerandretuta <andreviniciusmerlia@gmail.com>2026-11-24 06:21:32 -0300
commit4e9407a409641b644393a66b41d35e431f1c5ddb (patch)
tree4fd9f237b0074c1eec460011556350358cddca1c /runtime/shims/acphal.cpp
parent0fe9c0bdfb844678209c0d0ffdd37d2533d1f57e (diff)
acphal: isolate voice failures and keep input transitions ordered
Diffstat (limited to 'runtime/shims/acphal.cpp')
-rw-r--r--runtime/shims/acphal.cpp162
1 files changed, 96 insertions, 66 deletions
diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp
index d273aaa85..4b516cf8f 100644
--- a/runtime/shims/acphal.cpp
+++ b/runtime/shims/acphal.cpp
@@ -37,6 +37,8 @@
37#include <shared_mutex> 37#include <shared_mutex>
38#include <stop_token> 38#include <stop_token>
39#include <string> 39#include <string>
40#include <string_view>
41#include <system_error>
40#include <thread> 42#include <thread>
41#include <vector> 43#include <vector>
42 44
@@ -193,21 +195,28 @@ static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38,
193 195
194// ---- Startup trace helper ---- 196// ---- Startup trace helper ----
195 197
196void trace_call(const char* api, const std::string& detail) { 198void trace_call(const char* api, std::string_view detail = {}) noexcept try {
197 if (!rt::startup_trace::enabled()) return; 199 if (!rt::startup_trace::enabled()) return;
198 static std::mutex mutex; 200 static std::mutex mutex;
199 static std::set<std::string> seen; 201 static std::set<std::string> seen;
200 { 202 {
201 const std::lock_guard lock(mutex); 203 const std::lock_guard lock(mutex);
202 if (!seen.insert(std::string(api) + detail).second) return; 204 if (!seen.insert(std::string(api).append(detail)).second) return;
203 } 205 }
204 rt::startup_trace::event("acphal", 206 rt::startup_trace::event("acphal",
205 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.
206} 210}
207 211
208// ---- Genuine APU Heap Implementation ---- 212// ---- Genuine APU Heap Implementation ----
209 213
210constexpr 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}
211 220
212struct ApuRegion { 221struct ApuRegion {
213 void* base = nullptr; 222 void* base = nullptr;
@@ -291,10 +300,7 @@ struct ShapeArrayFree {
291 void operator()(void* array) const noexcept { std::free(array); } 300 void operator()(void* array) const noexcept { std::free(array); }
292}; 301};
293 302
294struct ShapeAllocation { 303using ShapeAllocation = std::array<std::unique_ptr<void, ShapeArrayFree>, 6>;
295 SHAPE_CONTEXTS* caller;
296 std::array<std::unique_ptr<void, ShapeArrayFree>, 6> arrays;
297};
298 304
299std::mutex g_shape_mutex; 305std::mutex g_shape_mutex;
300std::vector<ShapeAllocation> g_shape_allocations; 306std::vector<ShapeAllocation> g_shape_allocations;
@@ -308,7 +314,7 @@ uint8_t* apu_span(uint32_t apu, std::size_t len) {
308 return g_cached_heap.span_from_offset(offset, len); 314 return g_cached_heap.span_from_offset(offset, len);
309 } 315 }
310 if (g_noncached_heap.base) { 316 if (g_noncached_heap.base) {
311 const uint64_t cached_span = g_cached_heap.size; 317 const uint64_t cached_span = align_apu_region(g_cached_heap.size);
312 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { 318 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
313 return g_noncached_heap.span_from_offset( 319 return g_noncached_heap.span_from_offset(
314 static_cast<uint32_t>(offset - cached_span), len); 320 static_cast<uint32_t>(offset - cached_span), len);
@@ -393,16 +399,18 @@ struct XmaContextView {
393 while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {} 399 while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {}
394 } 400 }
395 401
396 std::size_t channels() const { return 1u + static_cast<std::size_t>(field(1, 29, 1)); }
397}; 402};
398 403
399struct XmaVoice { 404struct XmaVoice {
405 explicit XmaVoice(uint32_t format_bits) : format(format_bits) {}
406 std::size_t channels() const { return 1u + (format >> 2); }
407
400#if defined(LEONIDA_HAVE_XMA2_DECODER) 408#if defined(LEONIDA_HAVE_XMA2_DECODER)
401 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder; 409 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder;
402#endif 410#endif
403 std::deque<int16_t> pcm; 411 std::deque<int16_t> pcm;
404 std::size_t loop_skip = 0; // samples per channel to drop after a rewind 412 std::size_t loop_skip = 0; // samples per channel to drop after a rewind
405 std::optional<uint32_t> exhausted_input; 413 uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout
406 bool ended = false; 414 bool ended = false;
407}; 415};
408 416
@@ -487,16 +495,23 @@ public:
487 { 495 {
488 std::lock_guard slot_lock(voices_[index]->mutex); 496 std::lock_guard slot_lock(voices_[index]->mutex);
489 auto& voice = voices_[index]->voice; 497 auto& voice = voices_[index]->voice;
490 // Clear error_status (26..30) and error flag (31). 498 const uint32_t format = ctx.field(1, 27, 3);
491 ctx.set_field(2, 26, 6, 0); 499 // The worker cannot access the voice until the slot is unlocked.
492 500 ensure_worker_and_wake();
493 if (!voice) { 501 if (!voice) {
494 voice.emplace(); 502 voice.emplace(format);
495 active_count_.fetch_add(1, std::memory_order_relaxed); 503 active_count_.fetch_add(1, std::memory_order_relaxed);
504 } else if (voice->format != format) {
505 voice->pcm.clear();
506 voice->loop_skip = 0;
507 voice->format = format;
508#if defined(LEONIDA_HAVE_XMA2_DECODER)
509 voice->decoder.reset();
510#endif
496 } 511 }
497 voice->ended = false; 512 voice->ended = false;
513 ctx.set_field(2, 26, 6, 0);
498 } 514 }
499 ensure_worker_and_wake();
500 } 515 }
501 516
502 void disable(uint32_t index) { 517 void disable(uint32_t index) {
@@ -537,13 +552,13 @@ private:
537 552
538 // Fills `pcm` (interleaved s16) for one 2048-byte packet. Without the Rust decoder, or when it 553 // Fills `pcm` (interleaved s16) for one 2048-byte packet. Without the Rust decoder, or when it
539 // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds. 554 // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds.
540 static void decode_packet(XmaContextView ctx, XmaVoice& voice, const uint8_t* bytes, 555 static void decode_packet(XmaVoice& voice, const uint8_t* bytes,
541 std::vector<int16_t>& pcm) { 556 std::vector<int16_t>& pcm) {
542 const std::size_t channels = ctx.channels(); 557 const std::size_t channels = voice.channels();
543#if defined(LEONIDA_HAVE_XMA2_DECODER) 558#if defined(LEONIDA_HAVE_XMA2_DECODER)
544 if (!voice.decoder) { 559 if (!voice.decoder) {
545 LeonidaXma2Decoder* raw = nullptr; 560 LeonidaXma2Decoder* raw = nullptr;
546 if (leonida_xma2_decoder_create_hardware(kXmaRates[ctx.field(1, 27, 2) & 3u], 561 if (leonida_xma2_decoder_create_hardware(kXmaRates[voice.format & 3u],
547 static_cast<uint32_t>(channels), &raw) == LEONIDA_XMA2_OK) { 562 static_cast<uint32_t>(channels), &raw) == LEONIDA_XMA2_OK) {
548 voice.decoder.reset(raw); 563 voice.decoder.reset(raw);
549 } 564 }
@@ -559,8 +574,6 @@ private:
559 } 574 }
560 voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence. 575 voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence.
561 } 576 }
562#else
563 (void)voice;
564#endif 577#endif
565 pcm.assign(static_cast<std::size_t>(bytes[0] >> 2) * kXmaFrameSamples * channels, 0); 578 pcm.assign(static_cast<std::size_t>(bytes[0] >> 2) * kXmaFrameSamples * channels, 0);
566 } 579 }
@@ -571,7 +584,7 @@ private:
571 static bool decode_one_packet(XmaContextView ctx, XmaVoice& voice) { 584 static bool decode_one_packet(XmaContextView ctx, XmaVoice& voice) {
572 if (voice.ended) return false; 585 if (voice.ended) return false;
573 586
574 const std::size_t channels = ctx.channels(); 587 const std::size_t channels = voice.channels();
575 uint32_t current = ctx.field(4, 31, 1); 588 uint32_t current = ctx.field(4, 31, 1);
576 const uint32_t valid = ctx.field(0, 20, 2); 589 const uint32_t valid = ctx.field(0, 20, 2);
577 590
@@ -580,11 +593,8 @@ private:
580 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u); 593 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
581 return !voice.pcm.empty(); 594 return !voice.pcm.empty();
582 } 595 }
583 const uint32_t other = 1u - current; 596 if ((valid & (1u << current)) == 0) {
584 const bool current_valid = (valid & (1u << current)) != 0; 597 current ^= 1u;
585 const bool other_valid = (valid & (1u << other)) != 0;
586 if (!current_valid || (voice.exhausted_input == current && other_valid)) {
587 current = other;
588 ctx.set_field(4, 31, 1, current); 598 ctx.set_field(4, 31, 1, current);
589 } 599 }
590 600
@@ -593,15 +603,15 @@ private:
593 const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits; 603 const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits;
594 const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes); 604 const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes);
595 if (!data || packet >= packets) { 605 if (!data || packet >= packets) {
596 finish_input(ctx, voice, current, packet >= packets ? packet - packets : 0); 606 finish_input(ctx, current, packet >= packets ? packet - packets : 0);
597 return true; 607 return true;
598 } 608 }
599 voice.exhausted_input.reset();
600 609
601 const uint8_t* packet_data = data + packet * kXmaPacketBytes; 610 const uint8_t* packet_data = data + packet * kXmaPacketBytes;
602 const uint8_t packet_skip = packet_data[3]; 611 const uint8_t packet_skip = packet_data[3];
603 std::vector<int16_t> pcm; 612 // The sized constructor can propagate even an MSVC Debug allocation failure.
604 decode_packet(ctx, voice, packet_data, pcm); 613 std::vector<int16_t> pcm(0);
614 decode_packet(voice, packet_data, pcm);
605 const std::size_t subframe_samples = kXmaSubframeSamples * channels; 615 const std::size_t subframe_samples = kXmaSubframeSamples * channels;
606 const std::size_t initial_skip = ctx.field(1, 24, 3); 616 const std::size_t initial_skip = ctx.field(1, 24, 3);
607 const std::size_t skipped_subframes = std::min(initial_skip, pcm.size() / subframe_samples); 617 const std::size_t skipped_subframes = std::min(initial_skip, pcm.size() / subframe_samples);
@@ -629,18 +639,19 @@ private:
629 if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u); 639 if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u);
630 } 640 }
631 if (next >= packets) { 641 if (next >= packets) {
632 finish_input(ctx, voice, current, next - packets); 642 finish_input(ctx, current, next - packets);
633 } else { 643 } else {
634 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next * kXmaPacketBits)); 644 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next * kXmaPacketBits));
635 } 645 }
636 return true; 646 return true;
637 } 647 }
638 648
639 static void finish_input(XmaContextView ctx, XmaVoice& voice, uint32_t current, 649 static void finish_input(XmaContextView ctx, uint32_t current,
640 std::size_t skip_packets) { 650 std::size_t skip_packets) {
641 voice.exhausted_input = current;
642 // Publish the next offset before telling the title it can refill this input. 651 // Publish the next offset before telling the title it can refill this input.
643 ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits)); 652 ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits));
653 const uint32_t other = 1u - current;
654 if (ctx.field(0, 20 + other, 1) != 0) ctx.set_field(4, 31, 1, other);
644 ctx.set_field(0, 20 + current, 1, 0); 655 ctx.set_field(0, 20 + current, 1, 0);
645 } 656 }
646 657
@@ -684,8 +695,16 @@ private:
684 if (!array_) return; 695 if (!array_) return;
685 for (std::size_t i = 0; i < voices_.size(); ++i) { 696 for (std::size_t i = 0; i < voices_.size(); ++i) {
686 std::lock_guard slot_lock(voices_[i]->mutex); 697 std::lock_guard slot_lock(voices_[i]->mutex);
687 if (voices_[i]->voice.has_value()) { 698 auto& voice = voices_[i]->voice;
688 pump_voice(context_locked(static_cast<uint32_t>(i)), *voices_[i]->voice); 699 if (!voice) continue;
700 auto ctx = context_locked(static_cast<uint32_t>(i));
701 try {
702 pump_voice(ctx, *voice);
703 } catch (const std::bad_alloc&) {
704 // Only this voice failed. Retire it and allow the title to enable it again.
705 voice.reset();
706 active_count_.fetch_sub(1, std::memory_order_relaxed);
707 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
689 } 708 }
690 } 709 }
691 } 710 }
@@ -812,12 +831,16 @@ struct AcpHalImpl final : IAcpHal {
812 AcpMessage msg{}; 831 AcpMessage msg{};
813 msg.kind = kind; 832 msg.kind = kind;
814 msg.dropped = dropped_; 833 msg.dropped = dropped_;
815 dropped_ = 0;
816 msg.usec = static_cast<uint32_t>(elapsed_usec_locked()); 834 msg.usec = static_cast<uint32_t>(elapsed_usec_locked());
817 if (payload && len > 0) { 835 if (payload && len > 0) {
818 std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data))); 836 std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data)));
819 } 837 }
820 messages_.push_back(msg); 838 try {
839 messages_.push_back(msg);
840 dropped_ = 0;
841 } catch (const std::bad_alloc&) {
842 if (dropped_ < UINT32_MAX) ++dropped_;
843 }
821 } 844 }
822 845
823 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) 846 // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked)
@@ -844,7 +867,7 @@ struct AcpHalImpl final : IAcpHal {
844 // Acknowledges command completion, updates registered message masks, dispatches 867 // Acknowledges command completion, updates registered message masks, dispatches
845 // XMA voice commands, and writes any requested APU notification word. 868 // XMA voice commands, and writes any requested APU notification word.
846 HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame, 869 HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame,
847 const void* config, uint32_t notification) override { 870 const void* config, uint32_t notification) override try {
848 (void)frame; 871 (void)frame;
849 auto read_word = [config](std::size_t index) -> uint32_t { 872 auto read_word = [config](std::size_t index) -> uint32_t {
850 if (!config) return 0u; 873 if (!config) return 0u;
@@ -898,6 +921,10 @@ struct AcpHalImpl final : IAcpHal {
898 921
899 trace_call("AcpHal::SubmitCommand", ""); 922 trace_call("AcpHal::SubmitCommand", "");
900 return S_OK; 923 return S_OK;
924 } catch (const std::bad_alloc&) {
925 return E_OUTOFMEMORY;
926 } catch (const std::system_error&) {
927 return E_FAIL;
901 } 928 }
902 929
903 // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty. 930 // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty.
@@ -928,7 +955,12 @@ struct AcpHalImpl final : IAcpHal {
928 955
929HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { 956HRESULT __stdcall AcpHalCreate(void** ppAcpHal) {
930 if (!ppAcpHal) return E_POINTER; 957 if (!ppAcpHal) return E_POINTER;
931 *ppAcpHal = new AcpHalImpl(); 958 *ppAcpHal = nullptr;
959 try {
960 *ppAcpHal = new AcpHalImpl();
961 } catch (const std::bad_alloc&) {
962 return E_OUTOFMEMORY;
963 }
932 trace_call("AcpHalCreate", ""); 964 trace_call("AcpHalCreate", "");
933 return S_OK; 965 return S_OK;
934} 966}
@@ -940,13 +972,13 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
940 972
941 std::lock_guard lock(g_shape_mutex); 973 std::lock_guard lock(g_shape_mutex);
942 974
943 ShapeAllocation pending{ctx, {}}; 975 ShapeAllocation pending{};
944 std::size_t array_index = 0; 976 std::size_t array_index = 0;
945 auto alloc_array = [&](uint32_t count, size_t elem_size) -> void* { 977 auto alloc_array = [&](uint32_t count, size_t elem_size) -> void* {
946 if (count == 0) return nullptr; 978 if (count == 0) return nullptr;
947 void* ptr = std::calloc(count, elem_size); 979 void* ptr = std::calloc(count, elem_size);
948 if (!ptr) throw std::bad_alloc(); 980 if (!ptr) throw std::bad_alloc();
949 pending.arrays[array_index++].reset(ptr); 981 pending[array_index++].reset(ptr);
950 return ptr; 982 return ptr;
951 }; 983 };
952 984
@@ -980,7 +1012,7 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
980 result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; 1012 result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0};
981 1013
982 g_shape_allocations.reserve(g_shape_allocations.size() + 1); 1014 g_shape_allocations.reserve(g_shape_allocations.size() + 1);
983 g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts); 1015 if (result.xmaContextArray) g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts);
984 } catch (const std::bad_alloc&) { 1016 } catch (const std::bad_alloc&) {
985 return E_OUTOFMEMORY; 1017 return E_OUTOFMEMORY;
986 } 1018 }
@@ -1003,24 +1035,13 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
1003 1035
1004// ---- AcpHalReleaseShapeContexts ---- 1036// ---- AcpHalReleaseShapeContexts ----
1005 1037
1006HRESULT __stdcall AcpHalReleaseShapeContexts(void* argument = nullptr) { 1038HRESULT __stdcall AcpHalReleaseShapeContexts(void* /*hal*/) {
1007 std::lock_guard lock(g_shape_mutex); 1039 std::lock_guard lock(g_shape_mutex);
1008 // Stop and detach the XMA worker before freeing backing arrays. 1040 // Stop and detach the XMA worker before freeing backing arrays.
1009 g_xma_engine.unbind(); 1041 g_xma_engine.unbind();
1010 1042
1011 // Retail passes its IAcpHal handle. Only a pointer previously supplied to 1043 // The export releases the process-wide SHAPE arrays. The argument is an
1012 // AllocateShapeContexts can safely be treated as a SHAPE_CONTEXTS output. 1044 // opaque HAL handle, and allocation descriptors are owned by the caller.
1013 const auto allocation = std::find_if(g_shape_allocations.begin(), g_shape_allocations.end(),
1014 [argument](const ShapeAllocation& entry) { return entry.caller == argument; });
1015 if (allocation != g_shape_allocations.end()) {
1016 auto* ctx = allocation->caller;
1017 ctx->srcContextArray = nullptr;
1018 ctx->eqCompContextArray = nullptr;
1019 ctx->filtVolContextArray = nullptr;
1020 ctx->dmaContextArray = nullptr;
1021 ctx->xmaContextArray = nullptr;
1022 ctx->pcmContextArray = nullptr;
1023 }
1024 g_shape_allocations.clear(); 1045 g_shape_allocations.clear();
1025 1046
1026 trace_call("AcpHalReleaseShapeContexts", ""); 1047 trace_call("AcpHalReleaseShapeContexts", "");
@@ -1033,6 +1054,9 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
1033 uint32_t nonCachedSizeInBytes) { 1054 uint32_t nonCachedSizeInBytes) {
1034 std::lock_guard lock(g_apu_mutex); 1055 std::lock_guard lock(g_apu_mutex);
1035 if (g_apu_heap_created) return E_FAIL; 1056 if (g_apu_heap_created) return E_FAIL;
1057 const uint64_t address_bytes = (nonCachedSizeInBytes ? align_apu_region(cachedSizeInBytes)
1058 : cachedSizeInBytes) + nonCachedSizeInBytes;
1059 if (address_bytes > static_cast<uint64_t>(UINT32_MAX) + 1 - kApuBaseAddress) return E_INVALIDARG;
1036 1060
1037 if (cachedSizeInBytes > 0) { 1061 if (cachedSizeInBytes > 0) {
1038 g_cached_heap.base = VirtualAlloc( 1062 g_cached_heap.base = VirtualAlloc(
@@ -1052,9 +1076,15 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
1052 } 1076 }
1053 1077
1054 g_apu_heap_created = true; 1078 g_apu_heap_created = true;
1055 trace_call("ApuCreateHeap", 1079 if (rt::startup_trace::enabled()) {
1056 ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + 1080 try {
1057 ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); 1081 trace_call("ApuCreateHeap",
1082 ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) +
1083 ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes));
1084 } catch (const std::bad_alloc&) {
1085 // The heap is ready even if its diagnostic cannot be built.
1086 }
1087 }
1058 return S_OK; 1088 return S_OK;
1059} 1089}
1060 1090
@@ -1062,7 +1092,7 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes,
1062 1092
1063HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, 1093HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
1064 uint32_t sizeInBytes, uint32_t alignmentInBytes, 1094 uint32_t sizeInBytes, uint32_t alignmentInBytes,
1065 uint32_t flags) { 1095 uint32_t flags) try {
1066 if (!virtualAddress) return E_POINTER; 1096 if (!virtualAddress) return E_POINTER;
1067 *virtualAddress = nullptr; 1097 *virtualAddress = nullptr;
1068 if (physicalAddress) *physicalAddress = 0; 1098 if (physicalAddress) *physicalAddress = 0;
@@ -1107,17 +1137,17 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
1107 1137
1108 *virtualAddress = ptr; 1138 *virtualAddress = ptr;
1109 if (physicalAddress) { 1139 if (physicalAddress) {
1110 // Disjoint APU address ranges: 1140 // Leave alignment padding between the two synthetic address ranges.
1111 // cached: 0x40000000 .. 0x40000000 + cached_size - 1
1112 // non-cached: 0x40000000 + cached_size .. 0x40000000 + cached_size + noncached_size - 1
1113 uint32_t apu = kApuBaseAddress + offset; 1141 uint32_t apu = kApuBaseAddress + offset;
1114 if (target == &g_noncached_heap) { 1142 if (target == &g_noncached_heap) {
1115 apu += static_cast<uint32_t>(g_cached_heap.size); 1143 apu += static_cast<uint32_t>(align_apu_region(g_cached_heap.size));
1116 } 1144 }
1117 *physicalAddress = apu; 1145 *physicalAddress = apu;
1118 } 1146 }
1119 1147
1120 return S_OK; 1148 return S_OK;
1149} catch (const std::bad_alloc&) {
1150 return E_OUTOFMEMORY;
1121} 1151}
1122 1152
1123// ---- ApuFree ---- 1153// ---- ApuFree ----
@@ -1152,7 +1182,7 @@ void* __stdcall ApuMapApuAddress(uint32_t apu) {
1152 return g_cached_heap.from_offset(offset); 1182 return g_cached_heap.from_offset(offset);
1153 } 1183 }
1154 if (g_noncached_heap.base) { 1184 if (g_noncached_heap.base) {
1155 const uint32_t cached_span = static_cast<uint32_t>(g_cached_heap.size); 1185 const uint32_t cached_span = static_cast<uint32_t>(align_apu_region(g_cached_heap.size));
1156 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { 1186 if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) {
1157 return g_noncached_heap.from_offset(offset - cached_span); 1187 return g_noncached_heap.from_offset(offset - cached_span);
1158 } 1188 }
@@ -1169,7 +1199,7 @@ uint32_t __stdcall ApuMapVirtualAddress(void* virtualAddress) {
1169 return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress); 1199 return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress);
1170 } 1200 }
1171 if (g_noncached_heap.contains(virtualAddress)) { 1201 if (g_noncached_heap.contains(virtualAddress)) {
1172 return kApuBaseAddress + static_cast<uint32_t>(g_cached_heap.size) + 1202 return kApuBaseAddress + static_cast<uint32_t>(align_apu_region(g_cached_heap.size)) +
1173 g_noncached_heap.to_offset(virtualAddress); 1203 g_noncached_heap.to_offset(virtualAddress);
1174 } 1204 }
1175 return 0; 1205 return 0;