Add OPCODE_NEGATED_MUL_ADD/OPCODE_NEGATED_MUL_SUB

Proper handling of nans for VMX max/min on x64 (minps/maxps has special behavior depending on the operand order that vmx does not have for vminfp/vmaxfp)
Add extremely unintrusive guest code profiler utilizing KUSER_SHARED systemtime. This profiler is disabled on platforms other than windows, and on windows is disabled by default by a cvar
Repurpose GUEST_SCRATCH64 stack offset to instead be for storing guest function profile times, define GUEST_SCRATCH as 0 instead, since thats already meant to be a scratch area
Fix xenia silently closing on config errors/other fatal errors by setting has_console_attached_'s default to false
Add alternative code path for guest clock that uses kusershared systemtime instead of QueryPerformanceCounter. This is way faster and I have tested it and found it to be working, but i have disabled it because i do not know how well it works on wine or on processors other than mine
Significantly reduce log spam by setting XELOGAPU and XELOGGPU to be LogLevel::Debug
Changed some LOGI to LOGD in places to reduce log spam
Mark VdSwap as kHighFrequency, it was spamming up logs
Make logging calls less intrusive for the caller by forcing the test of log level inline and moving the format/AppendLogLine stuff to an outlined cold function
Add swcache namespace for software cache operations like prefetches, streaming stores and streaming loads.
Add XE_MSVC_REORDER_BARRIER for preventing msvc from propagating a value too close to its store or from its load
Add xe_unlikely_mutex for locks we know have very little contention
add XE_HOST_CACHE_LINE_SIZE and XE_RESTRICT to platform.h
Microoptimization: Changed most uses of size_t to ring_size_t in RingBuffer, this reduces the size of the inlined ringbuffer operations slightly by eliminating rex prefixes, depending on register allocation
Add BeginPrefetchedRead to ringbuffer, which prefetches the second range if there is one according to the provided PrefetchTag
added inline_loadclock cvar, which will directly use the value of the guest clock from clock.cc in jitted guest code. off by default
change uses of GUEST_SCRATCH64 to GUEST_SCRATCH
Add fast vectorized xenos_half_to_float/xenos_float_to_half (currently resides in x64_seq_vector, move to gpu code maybe at some point)
Add fast x64 codegen for PackFloat16_4/UnpackFloat16_4. Same code can be used for Float16_2 in future commit. This should speed up some games that use these functions heavily
Remove cvar for toggling old float16 behavior
Add VRSAVE register, support mfspr/mtspr vrsave
Add cvar for toggling off codegen for trap instructions and set it to true by default.
Add specialized methods to CommandProcessor: WriteRegistersFromMem, WriteRegisterRangeFromRing, and WriteOneRegisterFromRing. These reduce the overall cost of WriteRegister
Use a fixed size vmem vector for upload ranges, realloc/memsetting on resize  in the inner loop of requestranges was showing up on the profiler (the search in requestranges itself needs work)
Rename fixed_vmem_vector to better fit xenia's naming convention
Only log unknown register writes in WriteRegister if DEBUG :/. We're stuck on MSVC with c++17 so we have no way of influencing the branch ordering for that function without profile guided optimization
Remove binding stride assert in shader_translator.cc, triangle told me its leftover ogl stuff
Mark xe::FatalError as noreturn
If a controller is not connected, delay by 1.1 seconds before checking if it has been reconnected. Asking Xinput about a controller slot that is unused is extremely slow, and XinputGetState/SetState were taking up
an enormous amount of time in profiles. this may have caused a bit of input lag
Protect accesses to input_system with a lock
Add proper handling for user_index>= 4 in XamInputGetState/SetState, properly return zeroed state in GetState
Add missing argument to NtQueryVirtualMemory_entry
Fixed RtlCompareMemoryUlong_entry, it actually does not care if the source is misaligned, and for length it aligns down
Fixed RtlUpperChar and RtlLowerChar, added a table that has their correct return values precomputed
This commit is contained in:
chss95cs@gmail.com
2022-08-20 11:40:19 -07:00
parent 7cc364dcb8
commit 457296850e
54 changed files with 1441 additions and 615 deletions

View File

@@ -50,14 +50,8 @@ uint64_t last_guest_tick_count_ = 0;
// Last sampled host tick count.
uint64_t last_host_tick_count_ = Clock::QueryHostTickCount();
struct null_lock {
public:
static void lock() {}
static void unlock() {}
static bool try_lock() { return true; }
};
using tick_mutex_type = null_lock; // xe::xe_mutex;
using tick_mutex_type = xe_unlikely_mutex;
// Mutex to ensure last_host_tick_count_ and last_guest_tick_count_ are in sync
// std::mutex tick_mutex_;
@@ -176,6 +170,7 @@ uint64_t Clock::QueryGuestTickCount() {
return guest_tick_count;
}
uint64_t* Clock::GetGuestTickCountPointer() { return &last_guest_tick_count_; }
uint64_t Clock::QueryGuestSystemTime() {
if (cvars::clock_no_scaling) {
return Clock::QueryHostSystemTime();

View File

@@ -74,6 +74,8 @@ class Clock {
// Queries the current guest tick count, accounting for frequency adjustment
// and scaling.
static uint64_t QueryGuestTickCount();
static uint64_t* GetGuestTickCountPointer();
// Queries the guest time, in FILETIME format, accounting for scaling.
static uint64_t QueryGuestSystemTime();
// Queries the milliseconds since the guest began, accounting for scaling.

View File

@@ -12,18 +12,17 @@
#include "xenia/base/platform_win.h"
namespace xe {
#if XE_USE_KUSER_SHARED==1
#if XE_USE_KUSER_SHARED == 1
uint64_t Clock::host_tick_frequency_platform() { return 10000000ULL; }
uint64_t Clock::host_tick_count_platform() {
return *reinterpret_cast<volatile uint64_t*>(&KUserShared()->SystemTime);
return *reinterpret_cast<volatile uint64_t*>(GetKUserSharedSystemTime());
}
uint64_t Clock::QueryHostSystemTime() {
return *reinterpret_cast<volatile uint64_t*>(&KUserShared()->SystemTime);
return *reinterpret_cast<volatile uint64_t*>(GetKUserSharedSystemTime());
}
#else
#else
uint64_t Clock::host_tick_frequency_platform() {
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
@@ -44,13 +43,9 @@ uint64_t Clock::QueryHostSystemTime() {
return (uint64_t(t.dwHighDateTime) << 32) | t.dwLowDateTime;
}
uint64_t Clock::QueryHostUptimeMillis() {
return host_tick_count_platform() * 1000 / host_tick_frequency_platform();
}
#endif
uint64_t Clock::QueryHostUptimeMillis() {
return host_tick_count_platform() * 1000 / host_tick_frequency_platform();
}
} // namespace xe

View File

@@ -19,7 +19,7 @@ namespace xe {
// TODO(Triang3l): Set the default depending on the actual subsystem. Currently
// it inhibits message boxes.
static bool has_console_attached_ = true;
static bool has_console_attached_ = false;
bool has_console_attached() { return has_console_attached_; }

View File

@@ -78,17 +78,25 @@ std::pair<char*, size_t> GetThreadBuffer();
void AppendLogLine(LogLevel log_level, const char prefix_char, size_t written);
} // namespace internal
// Appends a line to the log with {fmt}-style formatting.
template <typename... Args>
void AppendLogLineFormat(LogLevel log_level, const char prefix_char,
XE_NOINLINE XE_COLD static void AppendLogLineFormat_Impl(LogLevel log_level,
const char prefix_char,
const char* format,
const Args&... args) {
auto target = internal::GetThreadBuffer();
auto result = fmt::format_to_n(target.first, target.second, format, args...);
internal::AppendLogLine(log_level, prefix_char, result.size);
}
// Appends a line to the log with {fmt}-style formatting.
//chrispy: inline the initial check, outline the append. the append should happen rarely for end users
template <typename... Args>
XE_FORCEINLINE static void AppendLogLineFormat(LogLevel log_level, const char prefix_char,
const char* format, const Args&... args) {
if (!internal::ShouldLog(log_level)) {
return;
}
auto target = internal::GetThreadBuffer();
auto result = fmt::format_to_n(target.first, target.second, format, args...);
internal::AppendLogLine(log_level, prefix_char, result.size);
AppendLogLineFormat_Impl(log_level, prefix_char, format, args...);
}
// Appends a line to the log.
@@ -98,18 +106,19 @@ void AppendLogLine(LogLevel log_level, const char prefix_char,
} // namespace logging
// Logs a fatal error and aborts the program.
void FatalError(const std::string_view str);
[[noreturn]] void FatalError(const std::string_view str);
} // namespace xe
#if XE_OPTION_ENABLE_LOGGING
template <typename... Args>
void XELOGE(const char* format, const Args&... args) {
XE_COLD void XELOGE(const char* format, const Args&... args) {
xe::logging::AppendLogLineFormat(xe::LogLevel::Error, '!', format, args...);
}
template <typename... Args>
XE_COLD
void XELOGW(const char* format, const Args&... args) {
xe::logging::AppendLogLineFormat(xe::LogLevel::Warning, 'w', format, args...);
}
@@ -131,12 +140,12 @@ void XELOGCPU(const char* format, const Args&... args) {
template <typename... Args>
void XELOGAPU(const char* format, const Args&... args) {
xe::logging::AppendLogLineFormat(xe::LogLevel::Info, 'A', format, args...);
xe::logging::AppendLogLineFormat(xe::LogLevel::Debug, 'A', format, args...);
}
template <typename... Args>
void XELOGGPU(const char* format, const Args&... args) {
xe::logging::AppendLogLineFormat(xe::LogLevel::Info, 'G', format, args...);
xe::logging::AppendLogLineFormat(xe::LogLevel::Debug, 'G', format, args...);
}
template <typename... Args>

View File

@@ -466,9 +466,11 @@ constexpr inline fourcc_t make_fourcc(const std::string_view fourcc) {
}
return make_fourcc(fourcc[0], fourcc[1], fourcc[2], fourcc[3]);
}
//chrispy::todo:use for command stream vector, resize happens a ton and has to call memset
// chrispy::todo:use for command stream vector, resize happens a ton and has to
// call memset
template <size_t sz>
class fixed_vmem_vector {
class FixedVMemVector {
static_assert((sz & 65535) == 0,
"Always give fixed_vmem_vector a size divisible by 65536 to "
"avoid wasting memory on windows");
@@ -477,12 +479,12 @@ class fixed_vmem_vector {
size_t nbytes_;
public:
fixed_vmem_vector()
FixedVMemVector()
: data_((uint8_t*)memory::AllocFixed(
nullptr, sz, memory::AllocationType::kReserveCommit,
memory::PageAccess::kReadWrite)),
nbytes_(0) {}
~fixed_vmem_vector() {
~FixedVMemVector() {
if (data_) {
memory::DeallocFixed(data_, sz, memory::DeallocationType::kRelease);
data_ = nullptr;
@@ -503,13 +505,221 @@ class fixed_vmem_vector {
resize(0); // todo:maybe zero out
}
void reserve(size_t size) { xenia_assert(size < sz); }
};
// software prefetches/cache operations
namespace swcache {
/*
warning, prefetchw's current behavior is not consistent across msvc and
clang, for clang it will only compile to prefetchw if the set architecture
supports it, for msvc however it will unconditionally compile to prefetchw!
so prefetchw support is still in process
only use these if you're absolutely certain you know what you're doing;
you can easily tank performance through misuse CPUS have excellent automatic
prefetchers that can predict patterns, but in situations where memory
accesses are super unpredictable and follow no pattern you can make use of
them
another scenario where it can be handy is when crossing page boundaries,
as many automatic prefetchers do not allow their streams to cross pages (no
idea what this means for huge pages)
I believe software prefetches do not kick off an automatic prefetcher
stream, so you can't just prefetch one line of the data you're about to
access and be fine, you need to go all the way
prefetchnta is implementation dependent, and that makes its use a bit
limited. For intel cpus, i believe it only prefetches the line into one way
of the L3
for amd cpus, it marks the line as requiring immediate eviction, the
next time an entry is needed in the set it resides in it will be evicted. ms
does dumb shit for memcpy, like looping over the contents of the source
buffer and doing prefetchnta on them, likely evicting some of the data they
just prefetched by the end of the buffer, and probably messing up data that
was already in the cache
another warning for these: this bypasses what i think is called
"critical word load", the data will always become available starting from the
very beginning of the line instead of from the piece that is needed
L1I cache is not prefetchable, however likely all cpus can fulfill
requests for the L1I from L2, so prefetchL2 on instructions should be fine
todo: clwb, clflush
*/
#if XE_COMPILER_HAS_GNU_EXTENSIONS == 1
XE_FORCEINLINE
static void PrefetchW(const void* addr) { __builtin_prefetch(addr, 1, 0); }
XE_FORCEINLINE
static void PrefetchNTA(const void* addr) { __builtin_prefetch(addr, 0, 0); }
XE_FORCEINLINE
static void PrefetchL3(const void* addr) { __builtin_prefetch(addr, 0, 1); }
XE_FORCEINLINE
static void PrefetchL2(const void* addr) { __builtin_prefetch(addr, 0, 2); }
XE_FORCEINLINE
static void PrefetchL1(const void* addr) { __builtin_prefetch(addr, 0, 3); }
#elif XE_ARCH_AMD64 == 1 && XE_COMPILER_MSVC == 1
XE_FORCEINLINE
static void PrefetchW(const void* addr) { _m_prefetchw(addr); }
XE_FORCEINLINE
static void PrefetchNTA(const void* addr) {
_mm_prefetch((const char*)addr, _MM_HINT_NTA);
}
XE_FORCEINLINE
static void PrefetchL3(const void* addr) {
_mm_prefetch((const char*)addr, _MM_HINT_T2);
}
XE_FORCEINLINE
static void PrefetchL2(const void* addr) {
_mm_prefetch((const char*)addr, _MM_HINT_T1);
}
XE_FORCEINLINE
static void PrefetchL1(const void* addr) {
_mm_prefetch((const char*)addr, _MM_HINT_T0);
}
#else
XE_FORCEINLINE
static void PrefetchW(const void* addr) {}
XE_FORCEINLINE
static void PrefetchNTA(const void* addr) {}
XE_FORCEINLINE
static void PrefetchL3(const void* addr) {}
XE_FORCEINLINE
static void PrefetchL2(const void* addr) {}
XE_FORCEINLINE
static void PrefetchL1(const void* addr) {}
#endif
enum class PrefetchTag { Write, Nontemporal, Level3, Level2, Level1 };
template <PrefetchTag tag>
static void Prefetch(const void* addr) {
static_assert(false, "Unknown tag");
}
template <>
static void Prefetch<PrefetchTag::Write>(const void* addr) {
PrefetchW(addr);
}
template <>
static void Prefetch<PrefetchTag::Nontemporal>(const void* addr) {
PrefetchNTA(addr);
}
template <>
static void Prefetch<PrefetchTag::Level3>(const void* addr) {
PrefetchL3(addr);
}
template <>
static void Prefetch<PrefetchTag::Level2>(const void* addr) {
PrefetchL2(addr);
}
template <>
static void Prefetch<PrefetchTag::Level1>(const void* addr) {
PrefetchL1(addr);
}
// todo: does aarch64 have streaming stores/loads?
/*
non-temporal stores/loads
the stores allow cacheable memory to behave like write-combining memory.
on the first nt store to a line, an intermediate buffer will be
allocated by the cpu for stores that come after. once the entire contents of
the line have been written the intermediate buffer will be transmitted to
memory
the written line will not be cached and if it is in the cache it will be
invalidated from all levels of the hierarchy
the cpu in this case does not have to read line from memory when we
first write to it if it is not anywhere in the cache, so we use half the
memory bandwidth using these stores
non-temporal loads are... loads, but they dont use the cache. you need
to manually insert memory barriers (_ReadWriteBarrier, ReadBarrier, etc, do
not use any barriers that generate actual code) if on msvc to prevent it from
moving the load of the data to just before the use of the data (immediately
requiring the memory to be available = big stall)
*/
#if XE_COMPILER_MSVC == 1 && XE_COMPILER_CLANG_CL == 0
#define XE_MSVC_REORDER_BARRIER _ReadWriteBarrier
#else
// if the compiler actually has pipelining for instructions we dont need a
// barrier
#define XE_MSVC_REORDER_BARRIER() static_cast<void>(0)
#endif
#if XE_ARCH_AMD64 == 1
XE_FORCEINLINE
static void WriteLineNT(void* destination, const void* source) {
assert((reinterpret_cast<uintptr_t>(destination) & 63ULL) == 0);
__m256i low = _mm256_loadu_si256((const __m256i*)source);
__m256i high = _mm256_loadu_si256(&((const __m256i*)source)[1]);
XE_MSVC_REORDER_BARRIER();
_mm256_stream_si256((__m256i*)destination, low);
_mm256_stream_si256(&((__m256i*)destination)[1], high);
}
XE_FORCEINLINE
static void ReadLineNT(void* destination, const void* source) {
assert((reinterpret_cast<uintptr_t>(source) & 63ULL) == 0);
__m256i low = _mm256_stream_load_si256((const __m256i*)source);
__m256i high = _mm256_stream_load_si256(&((const __m256i*)source)[1]);
XE_MSVC_REORDER_BARRIER();
_mm256_storeu_si256((__m256i*)destination, low);
_mm256_storeu_si256(&((__m256i*)destination)[1], high);
}
XE_FORCEINLINE
static void WriteFence() { _mm_sfence(); }
XE_FORCEINLINE
static void ReadFence() { _mm_lfence(); }
XE_FORCEINLINE
static void ReadWriteFence() { _mm_mfence(); }
#else
XE_FORCEINLINE
static void WriteLineNT(void* destination, const void* source) {
assert((reinterpret_cast<uintptr_t>(destination) & 63ULL) == 0);
memcpy(destination, source, 64);
}
XE_FORCEINLINE
static void ReadLineNT(void* destination, const void* source) {
assert((reinterpret_cast<uintptr_t>(source) & 63ULL) == 0);
memcpy(destination, source, 64);
}
XE_FORCEINLINE
static void WriteFence() {}
XE_FORCEINLINE
static void ReadFence() {}
XE_FORCEINLINE
static void ReadWriteFence() {}
#endif
} // namespace swcache
} // namespace xe
#endif // XENIA_BASE_MEMORY_H_

View File

@@ -12,12 +12,14 @@
#include "xenia/base/platform_win.h"
#endif
namespace xe {
#if XE_PLATFORM_WIN32 == 1 &&XE_ENABLE_FAST_WIN32_MUTEX == 1
//default spincount for entercriticalsection is insane on windows, 0x20007D0i64 (33556432 times!!)
//when a lock is highly contended performance degrades sharply on some processors
#define XE_CRIT_SPINCOUNT 128
#if XE_PLATFORM_WIN32 == 1 && XE_ENABLE_FAST_WIN32_MUTEX == 1
// default spincount for entercriticalsection is insane on windows, 0x20007D0i64
// (33556432 times!!) when a lock is highly contended performance degrades
// sharply on some processors todo: perhaps we should have a set of optional
// jobs that processors can do instead of spinning, for instance, sorting a list
// so we have better locality later or something
#define XE_CRIT_SPINCOUNT 128
/*
chrispy: todo, if a thread exits before releasing the global mutex we need to
check this and release the mutex one way to do this is by using FlsAlloc and
@@ -30,8 +32,8 @@ static CRITICAL_SECTION* global_critical_section(xe_global_mutex* mutex) {
}
xe_global_mutex::xe_global_mutex() {
InitializeCriticalSectionAndSpinCount(global_critical_section(this),
XE_CRIT_SPINCOUNT);
InitializeCriticalSectionEx(global_critical_section(this), XE_CRIT_SPINCOUNT,
CRITICAL_SECTION_NO_DEBUG_INFO);
}
xe_global_mutex ::~xe_global_mutex() {
DeleteCriticalSection(global_critical_section(this));
@@ -65,7 +67,8 @@ CRITICAL_SECTION* fast_crit(xe_fast_mutex* mutex) {
return reinterpret_cast<CRITICAL_SECTION*>(mutex);
}
xe_fast_mutex::xe_fast_mutex() {
InitializeCriticalSectionAndSpinCount(fast_crit(this), XE_CRIT_SPINCOUNT);
InitializeCriticalSectionEx(fast_crit(this), XE_CRIT_SPINCOUNT,
CRITICAL_SECTION_NO_DEBUG_INFO);
}
xe_fast_mutex::~xe_fast_mutex() { DeleteCriticalSection(fast_crit(this)); }

View File

@@ -12,10 +12,10 @@
#include <mutex>
#include "platform.h"
#define XE_ENABLE_FAST_WIN32_MUTEX 1
#define XE_ENABLE_FAST_WIN32_MUTEX 1
namespace xe {
#if XE_PLATFORM_WIN32 == 1 && XE_ENABLE_FAST_WIN32_MUTEX==1
#if XE_PLATFORM_WIN32 == 1 && XE_ENABLE_FAST_WIN32_MUTEX == 1
/*
must conform to
BasicLockable:https://en.cppreference.com/w/cpp/named_req/BasicLockable as
@@ -23,7 +23,8 @@ namespace xe {
this emulates a recursive mutex, except with far less overhead
*/
class alignas(64) xe_global_mutex {
class alignas(4096) xe_global_mutex {
char detail[64];
public:
@@ -47,11 +48,50 @@ class alignas(64) xe_fast_mutex {
void unlock();
bool try_lock();
};
// a mutex that is extremely unlikely to ever be locked
// use for race conditions that have extremely remote odds of happening
class xe_unlikely_mutex {
std::atomic<uint32_t> mut;
bool _tryget() {
uint32_t lock_expected = 0;
return mut.compare_exchange_strong(lock_expected, 1);
}
public:
xe_unlikely_mutex() : mut(0) {}
~xe_unlikely_mutex() { mut = 0; }
void lock() {
uint32_t lock_expected = 0;
if (XE_LIKELY(_tryget())) {
return;
} else {
do {
// chrispy: warning, if no SMT, mm_pause does nothing...
#if XE_ARCH_AMD64 == 1
_mm_pause();
#endif
} while (!_tryget());
}
}
void unlock() { mut.exchange(0); }
bool try_lock() { return _tryget(); }
};
using xe_mutex = xe_fast_mutex;
#else
using global_mutex_type = std::recursive_mutex;
using xe_mutex = std::mutex;
using xe_unlikely_mutex = std::mutex;
#endif
struct null_mutex {
public:
static void lock() {}
static void unlock() {}
static bool try_lock() { return true; }
};
using global_unique_lock_type = std::unique_lock<global_mutex_type>;
// The global critical region mutex singleton.
// This must guard any operation that may suspend threads or be sensitive to

View File

@@ -122,6 +122,7 @@
#define XE_COLD __attribute__((cold))
#define XE_LIKELY(...) __builtin_expect(!!(__VA_ARGS__), true)
#define XE_UNLIKELY(...) __builtin_expect(!!(__VA_ARGS__), false)
#else
#define XE_FORCEINLINE inline
#define XE_NOINLINE
@@ -129,6 +130,24 @@
#define XE_LIKELY(...) (!!(__VA_ARGS__))
#define XE_UNLIKELY(...) (!!(__VA_ARGS__))
#endif
// only use __restrict if MSVC, for clang/gcc we can use -fstrict-aliasing which
// acts as __restrict across the board todo: __restrict is part of the type
// system, we might actually have to still emit it on clang and gcc
#if XE_COMPILER_CLANG_CL == 0 && XE_COMPILER_MSVC == 1
#define XE_RESTRICT __restrict
#else
#define XE_RESTRICT
#endif
#if XE_ARCH_AMD64 == 1
#define XE_HOST_CACHE_LINE_SIZE 64
#elif XE_ARCH_ARM64 == 1
#define XE_HOST_CACHE_LINE_SIZE 64
#else
#error unknown cache line size for unknown architecture!
#endif
namespace xe {

View File

@@ -35,7 +35,9 @@
#undef GetFirstChild
#define XE_USE_NTDLL_FUNCTIONS 1
#define XE_USE_KUSER_SHARED 1
//chrispy: disabling this for now, more research needs to be done imo, although it does work very well on my machine
//
#define XE_USE_KUSER_SHARED 0
#if XE_USE_NTDLL_FUNCTIONS == 1
/*
ntdll versions of functions often skip through a lot of extra garbage in
@@ -61,142 +63,19 @@
#define XE_NTDLL_IMPORT(name, cls, clsvar) static constexpr bool clsvar = false
#endif
#if XE_USE_KUSER_SHARED==1
// KUSER_SHARED
struct __declspec(align(4)) _KSYSTEM_TIME {
unsigned int LowPart;
int High1Time;
int High2Time;
};
enum _NT_PRODUCT_TYPE {
NtProductWinNt = 0x1,
NtProductLanManNt = 0x2,
NtProductServer = 0x3,
};
enum _ALTERNATIVE_ARCHITECTURE_TYPE {
StandardDesign = 0x0,
NEC98x86 = 0x1,
EndAlternatives = 0x2,
};
#pragma pack(push, 1)
struct $3D940D5D03EF7F98CEE6737EDE752E57 {
__int8 _bf_0;
};
union $DA7A7E727E24E4DD62317E27558CCADA {
unsigned __int8 MitigationPolicies;
$3D940D5D03EF7F98CEE6737EDE752E57 __s1;
};
struct __declspec(align(4)) $4BF4056B39611650D41923F164DAFA52 {
__int32 _bf_0;
};
union __declspec(align(4)) $BB68545E345A5F8046EF3BC0FE928142 {
unsigned int SharedDataFlags;
$4BF4056B39611650D41923F164DAFA52 __s1;
};
union $5031D289C483414B89DA3F368D1FE62C {
volatile _KSYSTEM_TIME TickCount;
volatile unsigned __int64 TickCountQuad;
unsigned int ReservedTickCountOverlay[3];
};
struct $F91ACE6F13277DFC9425B9B8BBCB30F7 {
volatile unsigned __int8 QpcBypassEnabled;
unsigned __int8 QpcShift;
};
union __declspec(align(2)) $3C927F8BB7EAEE13CF0CFC3E60EDC8A9 {
unsigned __int16 QpcData;
$F91ACE6F13277DFC9425B9B8BBCB30F7 __s1;
};
struct __declspec(align(8)) _KUSER_SHARED_DATA {
unsigned int TickCountLowDeprecated;
unsigned int TickCountMultiplier;
volatile _KSYSTEM_TIME InterruptTime;
volatile _KSYSTEM_TIME SystemTime;
volatile _KSYSTEM_TIME TimeZoneBias;
unsigned __int16 ImageNumberLow;
unsigned __int16 ImageNumberHigh;
wchar_t NtSystemRoot[260];
unsigned int MaxStackTraceDepth;
unsigned int CryptoExponent;
unsigned int TimeZoneId;
unsigned int LargePageMinimum;
unsigned int AitSamplingValue;
unsigned int AppCompatFlag;
unsigned __int64 RNGSeedVersion;
unsigned int GlobalValidationRunlevel;
volatile int TimeZoneBiasStamp;
unsigned int NtBuildNumber;
_NT_PRODUCT_TYPE NtProductType;
unsigned __int8 ProductTypeIsValid;
unsigned __int8 Reserved0[1];
unsigned __int16 NativeProcessorArchitecture;
unsigned int NtMajorVersion;
unsigned int NtMinorVersion;
unsigned __int8 ProcessorFeatures[64];
unsigned int Reserved1;
unsigned int Reserved3;
volatile unsigned int TimeSlip;
_ALTERNATIVE_ARCHITECTURE_TYPE AlternativeArchitecture;
unsigned int BootId;
_LARGE_INTEGER SystemExpirationDate;
unsigned int SuiteMask;
unsigned __int8 KdDebuggerEnabled;
$DA7A7E727E24E4DD62317E27558CCADA ___u33;
unsigned __int8 Reserved6[2];
volatile unsigned int ActiveConsoleId;
volatile unsigned int DismountCount;
unsigned int ComPlusPackage;
unsigned int LastSystemRITEventTickCount;
unsigned int NumberOfPhysicalPages;
unsigned __int8 SafeBootMode;
unsigned __int8 VirtualizationFlags;
unsigned __int8 Reserved12[2];
$BB68545E345A5F8046EF3BC0FE928142 ___u43;
unsigned int DataFlagsPad[1];
unsigned __int64 TestRetInstruction;
__int64 QpcFrequency;
unsigned int SystemCall;
unsigned int SystemCallPad0;
unsigned __int64 SystemCallPad[2];
$5031D289C483414B89DA3F368D1FE62C ___u50;
unsigned int TickCountPad[1];
unsigned int Cookie;
unsigned int CookiePad[1];
__int64 ConsoleSessionForegroundProcessId;
unsigned __int64 TimeUpdateLock;
unsigned __int64 BaselineSystemTimeQpc;
unsigned __int64 BaselineInterruptTimeQpc;
unsigned __int64 QpcSystemTimeIncrement;
unsigned __int64 QpcInterruptTimeIncrement;
unsigned __int8 QpcSystemTimeIncrementShift;
unsigned __int8 QpcInterruptTimeIncrementShift;
unsigned __int16 UnparkedProcessorCount;
unsigned int EnclaveFeatureMask[4];
unsigned int TelemetryCoverageRound;
unsigned __int16 UserModeGlobalLogger[16];
unsigned int ImageFileExecutionOptions;
unsigned int LangGenerationCount;
unsigned __int64 Reserved4;
volatile unsigned __int64 InterruptTimeBias;
volatile unsigned __int64 QpcBias;
unsigned int ActiveProcessorCount;
volatile unsigned __int8 ActiveGroupCount;
unsigned __int8 Reserved9;
$3C927F8BB7EAEE13CF0CFC3E60EDC8A9 ___u74;
_LARGE_INTEGER TimeZoneBiasEffectiveStart;
_LARGE_INTEGER TimeZoneBiasEffectiveEnd;
_XSTATE_CONFIGURATION XState;
};
static constexpr unsigned KUSER_SIZE = sizeof(_KUSER_SHARED_DATA);
static_assert(KUSER_SIZE == 1808, "yay");
#pragma pack(pop)
static _KUSER_SHARED_DATA* KUserShared() {
return (_KUSER_SHARED_DATA*)0x7FFE0000;
static constexpr size_t KSUER_SHARED_SYSTEMTIME_OFFSET = 0x14;
static unsigned char* KUserShared() { return (unsigned char*)0x7FFE0000ULL; }
static volatile _KSYSTEM_TIME* GetKUserSharedSystemTime() {
return reinterpret_cast<volatile _KSYSTEM_TIME*>(
KUserShared() + KSUER_SHARED_SYSTEMTIME_OFFSET);
}
#endif
#endif // XENIA_BASE_PLATFORM_WIN_H_

View File

@@ -8,46 +8,52 @@
*/
#include "xenia/base/ring_buffer.h"
#include <algorithm>
#include <cstring>
namespace xe {
RingBuffer::RingBuffer(uint8_t* buffer, size_t capacity)
: buffer_(buffer), capacity_(capacity) {}
: buffer_(buffer),
capacity_(static_cast<ring_size_t>(capacity)),
read_offset_(0),
write_offset_(0) {}
void RingBuffer::AdvanceRead(size_t count) {
void RingBuffer::AdvanceRead(size_t _count) {
ring_size_t count = static_cast<ring_size_t>(_count);
if (read_offset_ + count < capacity_) {
read_offset_ += count;
} else {
size_t left_half = capacity_ - read_offset_;
size_t right_half = count - left_half;
ring_size_t left_half = capacity_ - read_offset_;
ring_size_t right_half = count - left_half;
read_offset_ = right_half;
}
}
void RingBuffer::AdvanceWrite(size_t count) {
void RingBuffer::AdvanceWrite(size_t _count) {
ring_size_t count = static_cast<ring_size_t>(_count);
if (write_offset_ + count < capacity_) {
write_offset_ += count;
} else {
size_t left_half = capacity_ - write_offset_;
size_t right_half = count - left_half;
ring_size_t left_half = capacity_ - write_offset_;
ring_size_t right_half = count - left_half;
write_offset_ = right_half;
}
}
RingBuffer::ReadRange RingBuffer::BeginRead(size_t count) {
count = std::min(count, capacity_);
RingBuffer::ReadRange RingBuffer::BeginRead(size_t _count) {
ring_size_t count =
std::min<ring_size_t>(static_cast<ring_size_t>(_count), capacity_);
if (!count) {
return {0};
}
if (read_offset_ + count < capacity_) {
return {buffer_ + read_offset_, count, nullptr, 0};
return {buffer_ + read_offset_, nullptr, count, 0};
} else {
size_t left_half = capacity_ - read_offset_;
size_t right_half = count - left_half;
return {buffer_ + read_offset_, left_half, buffer_, right_half};
ring_size_t left_half = capacity_ - read_offset_;
ring_size_t right_half = count - left_half;
return {buffer_ + read_offset_, buffer_, left_half, right_half};
}
}
@@ -59,7 +65,8 @@ void RingBuffer::EndRead(ReadRange read_range) {
}
}
size_t RingBuffer::Read(uint8_t* buffer, size_t count) {
size_t RingBuffer::Read(uint8_t* buffer, size_t _count) {
ring_size_t count = static_cast<ring_size_t>(_count);
count = std::min(count, capacity_);
if (!count) {
return 0;
@@ -69,7 +76,7 @@ size_t RingBuffer::Read(uint8_t* buffer, size_t count) {
if (read_offset_ < write_offset_) {
assert_true(read_offset_ + count <= write_offset_);
} else if (read_offset_ + count >= capacity_) {
size_t left_half = capacity_ - read_offset_;
ring_size_t left_half = capacity_ - read_offset_;
assert_true(count - left_half <= write_offset_);
}
@@ -77,8 +84,8 @@ size_t RingBuffer::Read(uint8_t* buffer, size_t count) {
std::memcpy(buffer, buffer_ + read_offset_, count);
read_offset_ += count;
} else {
size_t left_half = capacity_ - read_offset_;
size_t right_half = count - left_half;
ring_size_t left_half = capacity_ - read_offset_;
ring_size_t right_half = count - left_half;
std::memcpy(buffer, buffer_ + read_offset_, left_half);
std::memcpy(buffer + left_half, buffer_, right_half);
read_offset_ = right_half;
@@ -87,7 +94,8 @@ size_t RingBuffer::Read(uint8_t* buffer, size_t count) {
return count;
}
size_t RingBuffer::Write(const uint8_t* buffer, size_t count) {
size_t RingBuffer::Write(const uint8_t* buffer, size_t _count) {
ring_size_t count = static_cast<ring_size_t>(_count);
count = std::min(count, capacity_);
if (!count) {
return 0;
@@ -105,8 +113,8 @@ size_t RingBuffer::Write(const uint8_t* buffer, size_t count) {
std::memcpy(buffer_ + write_offset_, buffer, count);
write_offset_ += count;
} else {
size_t left_half = capacity_ - write_offset_;
size_t right_half = count - left_half;
ring_size_t left_half = capacity_ - write_offset_;
ring_size_t right_half = count - left_half;
std::memcpy(buffer_ + write_offset_, buffer, left_half);
std::memcpy(buffer_, buffer + left_half, right_half);
write_offset_ = right_half;

View File

@@ -17,6 +17,8 @@
#include "xenia/base/assert.h"
#include "xenia/base/byte_order.h"
#include "xenia/base/math.h"
#include "xenia/base/memory.h"
namespace xe {
/*
@@ -39,18 +41,24 @@ namespace xe {
that the registers no longer need the rex prefix, shrinking the generated
code a bit.. like i said, every bit helps in this class
*/
using ring_size_t = uint32_t;
class RingBuffer {
public:
RingBuffer(uint8_t* buffer, size_t capacity);
uint8_t* buffer() const { return buffer_; }
size_t capacity() const { return capacity_; }
ring_size_t capacity() const { return capacity_; }
bool empty() const { return read_offset_ == write_offset_; }
size_t read_offset() const { return read_offset_; }
uintptr_t read_ptr() const { return uintptr_t(buffer_) + read_offset_; }
ring_size_t read_offset() const { return read_offset_; }
uintptr_t read_ptr() const {
return uintptr_t(buffer_) + static_cast<uintptr_t>(read_offset_);
}
// todo: offset/ capacity_ is probably always 1 when its over, just check and
// subtract instead
void set_read_offset(size_t offset) { read_offset_ = offset % capacity_; }
size_t read_count() const {
ring_size_t read_count() const {
// chrispy: these branches are unpredictable
#if 0
if (read_offset_ == write_offset_) {
@@ -61,14 +69,14 @@ class RingBuffer {
return (capacity_ - read_offset_) + write_offset_;
}
#else
size_t read_offs = read_offset_;
size_t write_offs = write_offset_;
size_t cap = capacity_;
ring_size_t read_offs = read_offset_;
ring_size_t write_offs = write_offset_;
ring_size_t cap = capacity_;
size_t offset_delta = write_offs - read_offs;
size_t wrap_read_count = (cap - read_offs) + write_offs;
ring_size_t offset_delta = write_offs - read_offs;
ring_size_t wrap_read_count = (cap - read_offs) + write_offs;
size_t comparison_value = read_offs <= write_offs;
ring_size_t comparison_value = read_offs <= write_offs;
#if 0
size_t selector =
static_cast<size_t>(-static_cast<ptrdiff_t>(comparison_value));
@@ -89,10 +97,12 @@ class RingBuffer {
#endif
}
size_t write_offset() const { return write_offset_; }
ring_size_t write_offset() const { return write_offset_; }
uintptr_t write_ptr() const { return uintptr_t(buffer_) + write_offset_; }
void set_write_offset(size_t offset) { write_offset_ = offset % capacity_; }
size_t write_count() const {
void set_write_offset(size_t offset) {
write_offset_ = static_cast<ring_size_t>(offset) % capacity_;
}
ring_size_t write_count() const {
if (read_offset_ == write_offset_) {
return capacity_;
} else if (write_offset_ < read_offset_) {
@@ -107,13 +117,35 @@ class RingBuffer {
struct ReadRange {
const uint8_t* first;
size_t first_length;
const uint8_t* second;
size_t second_length;
ring_size_t first_length;
ring_size_t second_length;
};
ReadRange BeginRead(size_t count);
void EndRead(ReadRange read_range);
/*
BeginRead, but if there is a second Range it will prefetch all lines of it
this does not prefetch the first range, because software prefetching can do that faster than we can
*/
template <swcache::PrefetchTag tag>
XE_FORCEINLINE ReadRange BeginPrefetchedRead(size_t count) {
ReadRange range = BeginRead(count);
if (range.second) {
ring_size_t numlines =
xe::align<ring_size_t>(range.second_length, XE_HOST_CACHE_LINE_SIZE) /
XE_HOST_CACHE_LINE_SIZE;
//chrispy: maybe unroll?
for (ring_size_t i = 0; i < numlines; ++i) {
swcache::Prefetch<tag>(range.second + (i * XE_HOST_CACHE_LINE_SIZE));
}
}
return range;
}
size_t Read(uint8_t* buffer, size_t count);
template <typename T>
size_t Read(T* buffer, size_t count) {
@@ -156,29 +188,29 @@ class RingBuffer {
private:
uint8_t* buffer_ = nullptr;
size_t capacity_ = 0;
size_t read_offset_ = 0;
size_t write_offset_ = 0;
ring_size_t capacity_ = 0;
ring_size_t read_offset_ = 0;
ring_size_t write_offset_ = 0;
};
template <>
inline uint32_t RingBuffer::ReadAndSwap<uint32_t>() {
size_t read_offset = this->read_offset_;
ring_size_t read_offset = this->read_offset_;
xenia_assert(this->capacity_ >= 4);
size_t next_read_offset = read_offset + 4;
#if 0
ring_size_t next_read_offset = read_offset + 4;
#if 0
size_t zerotest = next_read_offset - this->capacity_;
// unpredictable branch, use bit arith instead
// todo: it would be faster to use lzcnt, but we need to figure out if all
// machines we support support it
next_read_offset &= -static_cast<ptrdiff_t>(!!zerotest);
#else
#else
if (XE_UNLIKELY(next_read_offset == this->capacity_)) {
next_read_offset = 0;
//todo: maybe prefetch next? or should that happen much earlier?
// todo: maybe prefetch next? or should that happen much earlier?
}
#endif
#endif
this->read_offset_ = next_read_offset;
unsigned int ring_value = *(uint32_t*)&this->buffer_[read_offset];
return xe::byte_swap(ring_value);