Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion tests/startup_host_cpu_debug_check.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Run the startup debugger with X2W_HOST_CPU=1 on a source-built probe that executes SHA-extension
and RDPID instructions (tests/startup_host_cpu_probe.cpp).
and RDPID instructions (tests/startup_host_cpu_probe.cpp), including RDPID sites that eight threads
reach at the same time: every thread that faulted before a site was rewritten has to continue.

On a host that has the instructions the probe just runs. On a host that lacks them the debugger
has to perform them, and the same run without the switch must stop at an illegal instruction.
Expand Down Expand Up @@ -35,6 +36,7 @@ def main(probe):
out, printed = run(probe, work, "with", True)
assert "process exited with 0x00000000" in out, out
assert expected in printed and "rdpid agrees with rdtscp" in printed, printed
assert "rdpid threads 8 of 8" in printed, printed # threads that faulted on the site together
summary = next((line for line in out.splitlines() if "host-cpu sites rewritten" in line), "")
plain, plain_printed = run(probe, work, "without", False)
if summary:
Expand All @@ -44,6 +46,9 @@ def main(probe):
count = int(summary.split("sha (per hit) x")[1].split(",")[0].split()[0])
assert count == 56, summary # 32 SHA256RNDS2, 12 SHA256MSG1 and 12 SHA256MSG2 for one block
case = "performed by the debugger: " + summary.split("rewritten:")[1].strip()
resumed = next((line for line in out.splitlines() if "host-cpu threads resumed" in line), "")
if resumed:
case += "; threads resumed after another thread's rewrite: " + resumed.rsplit(":", 1)[1].strip()
else:
assert "process exited with 0x00000000" in plain and expected in plain_printed, plain
case = "host has the instructions, nothing rewritten"
Expand Down
44 changes: 43 additions & 1 deletion tests/startup_host_cpu_probe.cpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
// Input for tests/startup_host_cpu_debug_check.py: a program that executes SHA-extension and RDPID
// instructions, which a host processor may lack. It prints the SHA-256 digest of "abc" computed
// with SHA256RNDS2, SHA256MSG1 and SHA256MSG2, and whether two RDPID reads agree with RDTSCP.
// with SHA256RNDS2, SHA256MSG1 and SHA256MSG2, how many threads read RDPID when released together,
// and whether two RDPID reads agree with RDTSCP.
#include <immintrin.h>
#include <intrin.h>

#include <array>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <thread>
#include <utility>
#include <vector>

#if defined(__clang__)
#define HOST_CPU_TARGET __attribute__((target("sha,sse4.1,ssse3,rdpid")))
Expand Down Expand Up @@ -56,6 +62,41 @@ HOST_CPU_TARGET __declspec(noinline) unsigned read_processor_id()
{
return _rdpid_u32();
}

// Separate RDPID sites (the added constant keeps the linker from folding them into one function).
template <unsigned N>
HOST_CPU_TARGET __declspec(noinline) unsigned processor_id_site()
{
return _rdpid_u32() + N;
}

template <unsigned... N>
constexpr std::array<unsigned (*)(), sizeof...(N)> make_sites(std::integer_sequence<unsigned, N...>)
{
return {processor_id_site<N>...};
}
constexpr auto sites = make_sites(std::make_integer_sequence<unsigned, 32>{});

// Several threads reach each site together, before it has run anywhere: on a host without RDPID they
// fault at the same time, and every one has to continue after the debugger replaces the instruction.
// Returns how many threads passed every site.
int race_sites(int thread_count)
{
std::atomic<int> arrived[sites.size()] = {};
std::atomic<int> finished{0};
std::vector<std::thread> threads;
for (int i = 0; i < thread_count; ++i)
threads.emplace_back([&] {
for (std::size_t site = 0; site < sites.size(); ++site) {
arrived[site].fetch_add(1);
while (arrived[site].load() < thread_count) _mm_pause();
sites[site]();
}
finished.fetch_add(1);
});
for (auto& thread : threads) thread.join();
return finished.load();
}
} // namespace

int main()
Expand All @@ -65,6 +106,7 @@ int main()
std::printf("sha256 abc ");
for (std::uint32_t word : digest) std::printf("%08x", word);
std::printf("\n");
std::printf("rdpid threads %d of 8\n", race_sites(8));
// A thread can move between processors, so RDPID is compared with RDTSCP on both sides.
bool agrees = false;
for (int attempt = 0; attempt < 8 && !agrees; ++attempt) {
Expand Down
14 changes: 13 additions & 1 deletion tools/startup/debug_launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ def print(*args, **kwargs):
# X2W_HOST_CPU=1: rewrite main-image instructions the host processor lacks (host_cpu.py).
host_cpu_on = os.environ.get("X2W_HOST_CPU") == "1"
host_cpu_sites = {}
host_cpu_rewritten = set() # sites replaced in place; a thread may still fault on one (see the handler)
host_cpu_resumed = set() # (site, thread) pairs continued once for that reason
flushopt_missing = [False] # set when a CLFLUSHOPT faults: CLWB then becomes a NOP instead
stub_area = [0, 0] # next free address and end of the block the stubs go to
os.makedirs(logdir, exist_ok=True)
Expand Down Expand Up @@ -602,8 +604,16 @@ def poll_watches():
if (ex_code == 0xC000001D and first and host_cpu_on and not stop_first and main_base
and main_base <= ex_addr < main_base + 0x10000000):
name = rewrite_for_host(ex_addr)
if not name and sha_for_host(tid, ex_addr):
if name:
host_cpu_rewritten.add(ex_addr)
elif sha_for_host(tid, ex_addr):
name = "sha (per hit)"
elif ex_addr in host_cpu_rewritten and (ex_addr, tid) not in host_cpu_resumed:
# Another thread ran the old instruction before the rewrite and its fault arrived after:
# continued, it runs the replacement. Once per thread, so a fault that stays is reported.
host_cpu_resumed.add((ex_addr, tid))
k32.ContinueDebugEvent(pid, tid, DBG_CONTINUE)
continue
if name:
host_cpu_sites[name] = host_cpu_sites.get(name, 0) + 1
if sum(host_cpu_sites.values()) <= 40:
Expand Down Expand Up @@ -733,6 +743,8 @@ class MBI(ctypes.Structure):
print(" asserts continued: " + ", ".join(f"{where(a)} x{n}" for a, n in asserts_seen.items()))
if host_cpu_sites:
print(" host-cpu sites rewritten: " + ", ".join(f"{name} x{n}" for name, n in sorted(host_cpu_sites.items())))
if host_cpu_resumed:
print(f" host-cpu threads resumed at a site another thread had rewritten: {len(host_cpu_resumed)}")
bink_report()
if os.environ.get("X2W_COUNT"):
print(" hit counts: " + ", ".join(f"+{item} x{hit_counts.get('+' + item, 0)}"
Expand Down
Loading