CIRCT 24.0.0git
Loading...
Searching...
No Matches
esitester.cpp
Go to the documentation of this file.
1//===- esitester.cpp - ESI accelerator test/example tool ------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// DO NOT EDIT!
10// This file is distributed as part of an ESI runtime package. The source for
11// this file should always be modified within CIRCT
12// (lib/dialect/ESI/runtime/cpp/tools/esitester.cpp).
13//
14//===----------------------------------------------------------------------===//
15//
16// This application isn't a utility so much as a test driver for an ESI system.
17// It is also useful as an example of how to use the ESI C++ API. esiquery.cpp
18// is also useful as an example.
19//
20//===----------------------------------------------------------------------===//
21
22#include "esi/Accelerator.h"
23#include "esi/CLI.h"
24#include "esi/Manifest.h"
25#include "esi/Services.h"
26#include "esi/TypedPorts.h"
27
28#include <algorithm>
29#include <atomic>
30#include <chrono>
31#include <cstdlib>
32#include <cstring>
33#include <future>
34#include <iostream>
35#include <map>
36#include <memory>
37#include <mutex>
38#include <random>
39#include <span>
40#include <sstream>
41#include <stdexcept>
42#include <vector>
43
44using namespace esi;
45
46// Forward declarations of test functions.
48 uint32_t iterations);
50 const std::vector<uint32_t> &widths, bool write,
51 bool read);
53 uint32_t xferCount,
54 const std::vector<uint32_t> &widths, bool read,
55 bool write);
57 const std::vector<uint32_t> &widths, bool read, bool write);
59 const std::vector<uint32_t> &widths,
60 uint32_t xferCount, bool read, bool write,
61 bool checkData);
62static uint8_t esitesterDataByte(uint32_t index, size_t byte);
63static uint8_t enginePatternByte(uint32_t index, size_t byte, size_t bitWidth);
65 uint32_t iterations, bool pipeline);
67 Accelerator *, uint32_t width,
68 uint32_t xferCount, bool read,
69 bool write);
71 uint32_t addAmt, uint32_t numItems);
73 uint32_t addAmt, uint32_t numItems);
75 uint32_t xTrans, uint32_t yTrans,
76 uint32_t numCoords);
78 uint32_t xTrans, uint32_t yTrans,
79 uint32_t numCoords, size_t batchSizeLimit);
81 uint32_t xTrans, uint32_t yTrans,
82 uint32_t numCoords);
84 uint32_t iterations);
86
87// Default widths and default widths string for CLI help text.
88constexpr std::array<uint32_t, 8> defaultWidths = {24, 32, 64, 72,
89 128, 256, 512, 534};
90static std::string defaultWidthsStr() {
91 std::string s;
92 for (size_t i = 0; i < defaultWidths.size(); ++i) {
93 s += std::to_string(defaultWidths[i]);
94 if (i + 1 < defaultWidths.size())
95 s += ",";
96 }
97 return s;
98}
99
100// Helper to format bandwidth with appropriate units.
101static std::string formatBandwidth(double bytesPerSec) {
102 const char *unit = "B/s";
103 double value = bytesPerSec;
104 if (bytesPerSec >= 1e9) {
105 unit = "GB/s";
106 value = bytesPerSec / 1e9;
107 } else if (bytesPerSec >= 1e6) {
108 unit = "MB/s";
109 value = bytesPerSec / 1e6;
110 } else if (bytesPerSec >= 1e3) {
111 unit = "KB/s";
112 value = bytesPerSec / 1e3;
113 }
114 std::ostringstream oss;
115 oss.setf(std::ios::fixed);
116 oss.precision(2);
117 oss << value << " " << unit;
118 return oss.str();
119}
120
121// Human-readable size from bytes.
122static std::string humanBytes(uint64_t bytes) {
123 const char *units[] = {"B", "KB", "MB", "GB", "TB"};
124 double v = (double)bytes;
125 int u = 0;
126 while (v >= 1024.0 && u < 4) {
127 v /= 1024.0;
128 ++u;
129 }
130 std::ostringstream oss;
131 oss.setf(std::ios::fixed);
132 oss.precision(u == 0 ? 0 : 2);
133 oss << v << " " << units[u];
134 return oss.str();
135}
136
137// Human-readable time from microseconds.
138static std::string humanTimeUS(uint64_t us) {
139 if (us < 1000)
140 return std::to_string(us) + " us";
141 double ms = us / 1000.0;
142 if (ms < 1000.0) {
143 std::ostringstream oss;
144 oss.setf(std::ios::fixed);
145 oss.precision(ms < 10.0 ? 2 : (ms < 100.0 ? 1 : 0));
146 oss << ms << " ms";
147 return oss.str();
148 }
149 double sec = ms / 1000.0;
150 std::ostringstream oss;
151 oss.setf(std::ios::fixed);
152 oss.precision(sec < 10.0 ? 3 : 2);
153 oss << sec << " s";
154 return oss.str();
155}
156
157// MSVC does not implement std::aligned_malloc, even though it's part of the
158// C++17 standard. Provide a compatibility layer.
159static void *alignedAllocCompat(std::size_t alignment, std::size_t size) {
160#if defined(_MSC_VER)
161 void *ptr = _aligned_malloc(size, alignment);
162 if (!ptr)
163 throw std::bad_alloc();
164 return ptr;
165#else
166 void *ptr = std::aligned_alloc(alignment, size);
167 if (!ptr)
168 throw std::bad_alloc();
169 return ptr;
170#endif
171}
172
173static void alignedFreeCompat(void *ptr) {
174#if defined(_MSC_VER)
175 _aligned_free(ptr);
176#else
177 std::free(ptr);
178#endif
179}
180
181int main(int argc, const char *argv[]) {
182 CliParser cli("esitester");
183 cli.description("Test an ESI system running the ESI tester image.");
184 cli.require_subcommand(1);
185
186 CLI::App *callback_test =
187 cli.add_subcommand("callback", "initiate callback test");
188 uint32_t cb_iters = 1;
189 callback_test->add_option("-i,--iters", cb_iters,
190 "Number of iterations to run");
191
192 CLI::App *hostmemtestSub =
193 cli.add_subcommand("hostmem", "Run the host memory test");
194 bool hmRead = false;
195 bool hmWrite = false;
196 std::vector<uint32_t> hostmemWidths(defaultWidths.begin(),
197 defaultWidths.end());
198 hostmemtestSub->add_flag("-w,--write", hmWrite,
199 "Enable host memory write test");
200 hostmemtestSub->add_flag("-r,--read", hmRead, "Enable host memory read test");
201 hostmemtestSub->add_option(
202 "--widths", hostmemWidths,
203 "Hostmem test widths (default: " + defaultWidthsStr() + ")");
204
205 CLI::App *dmatestSub = cli.add_subcommand("dma", "Run the DMA test");
206 bool dmaRead = false;
207 bool dmaWrite = false;
208 std::vector<uint32_t> dmaWidths(defaultWidths.begin(), defaultWidths.end());
209 dmatestSub->add_flag("-w,--write", dmaWrite, "Enable dma write test");
210 dmatestSub->add_flag("-r,--read", dmaRead, "Enable dma read test");
211 dmatestSub->add_option("--widths", dmaWidths,
212 "DMA test widths (default: " + defaultWidthsStr() +
213 ")");
214
215 CLI::App *bandwidthSub =
216 cli.add_subcommand("bandwidth", "Run the bandwidth test");
217 uint32_t xferCount = 1000;
218 bandwidthSub->add_option("-c,--count", xferCount,
219 "Number of transfers to perform");
220 bool bandwidthRead = false;
221 bool bandwidthWrite = false;
222 bool bandwidthCheckData = false;
223 std::vector<uint32_t> bandwidthWidths(defaultWidths.begin(),
224 defaultWidths.end());
225 bandwidthSub->add_option("--widths", bandwidthWidths,
226 "Width of the transfers to perform (default: " +
227 defaultWidthsStr() + ")");
228 bandwidthSub->add_flag("-w,--write", bandwidthWrite,
229 "Enable bandwidth write");
230 bandwidthSub->add_flag("-r,--read", bandwidthRead, "Enable bandwidth read");
231 bandwidthSub->add_flag("--check-data", bandwidthCheckData,
232 "Verify every transferred payload byte");
233
234 CLI::App *hostmembwSub =
235 cli.add_subcommand("hostmembw", "Run the host memory bandwidth test");
236 uint32_t hmBwCount = 1000;
237 bool hmBwRead = false;
238 bool hmBwWrite = false;
239 std::vector<uint32_t> hmBwWidths(defaultWidths.begin(), defaultWidths.end());
240 hostmembwSub->add_option("-c,--count", hmBwCount,
241 "Number of hostmem transfers");
242 hostmembwSub->add_option(
243 "--widths", hmBwWidths,
244 "Hostmem bandwidth widths (default: " + defaultWidthsStr() + ")");
245 hostmembwSub->add_flag("-w,--write", hmBwWrite,
246 "Measure hostmem write bandwidth");
247 hostmembwSub->add_flag("-r,--read", hmBwRead,
248 "Measure hostmem read bandwidth");
249
250 CLI::App *loopbackSub =
251 cli.add_subcommand("loopback", "Test LoopbackInOutAdd function service");
252 uint32_t loopbackIters = 10;
253 bool loopbackPipeline = false;
254 loopbackSub->add_option("-i,--iters", loopbackIters,
255 "Number of function invocations (default 10)");
256 loopbackSub->add_flag("-p,--pipeline", loopbackPipeline,
257 "Pipeline all calls then collect results");
258
259 CLI::App *aggBwSub = cli.add_subcommand(
260 "aggbandwidth",
261 "Aggregate hostmem bandwidth across four units (readmem*, writemem*)");
262 uint32_t aggWidth = 512;
263 uint32_t aggCount = 1000;
264 bool aggRead = false;
265 bool aggWrite = false;
266 aggBwSub->add_option(
267 "--width", aggWidth,
268 "Bit width (default 512; other widths ignored if absent)");
269 aggBwSub->add_option("-c,--count", aggCount, "Flits per unit (default 1000)");
270 aggBwSub->add_flag("-r,--read", aggRead, "Include read units");
271 aggBwSub->add_flag("-w,--write", aggWrite, "Include write units");
272
273 CLI::App *streamingAddSub = cli.add_subcommand(
274 "streaming_add", "Test StreamingAdder function service with list input");
275 uint32_t streamingAddAmt = 5;
276 uint32_t streamingNumItems = 5;
277 bool streamingTranslate = false;
278 streamingAddSub->add_option("-a,--add", streamingAddAmt,
279 "Amount to add to each element (default 5)");
280 streamingAddSub->add_option("-n,--num-items", streamingNumItems,
281 "Number of random items in the list (default 5)");
282 streamingAddSub->add_flag("-t,--translate", streamingTranslate,
283 "Use message translation (list translation)");
284
285 CLI::App *coordTranslateSub = cli.add_subcommand(
286 "translate_coords",
287 "Test CoordTranslator function service with list of coordinates");
288 uint32_t coordXTrans = 10;
289 uint32_t coordYTrans = 20;
290 uint32_t coordNumItems = 5;
291 coordTranslateSub->add_option("-x,--x-translation", coordXTrans,
292 "X translation amount (default 10)");
293 coordTranslateSub->add_option("-y,--y-translation", coordYTrans,
294 "Y translation amount (default 20)");
295 coordTranslateSub->add_option("-n,--num-coords", coordNumItems,
296 "Number of random coordinates (default 5)");
297
298 CLI::App *serialCoordTranslateSub = cli.add_subcommand(
299 "serial_coords",
300 "Test SerialCoordTranslator function service with list of coordinates");
301 uint32_t serialBatchSize = 240;
302 serialCoordTranslateSub->add_option("-x,--x-translation", coordXTrans,
303 "X translation amount (default 10)");
304 serialCoordTranslateSub->add_option("-y,--y-translation", coordYTrans,
305 "Y translation amount (default 20)");
306 serialCoordTranslateSub->add_option(
307 "-n,--num-coords", coordNumItems,
308 "Number of random coordinates (default 5)");
309 serialCoordTranslateSub
310 ->add_option("-b,--batch-size", serialBatchSize,
311 "Coordinates per header (default 240, max 65535)")
312 ->check(CLI::Range(1u, 0xFFFFu));
313
314 CLI::App *autoSerialCoordTranslateSub = cli.add_subcommand(
315 "auto_serial_coords",
316 "Test AutoSerialCoordTranslator (uses ListWindowToParallel/Serial "
317 "converters under the hood)");
318 uint32_t autoCoordXTrans = 10;
319 uint32_t autoCoordYTrans = 20;
320 uint32_t autoCoordNumItems = 5;
321 autoSerialCoordTranslateSub->add_option("-x,--x-translation", autoCoordXTrans,
322 "X translation amount (default 10)");
323 autoSerialCoordTranslateSub->add_option("-y,--y-translation", autoCoordYTrans,
324 "Y translation amount (default 20)");
325 autoSerialCoordTranslateSub->add_option(
326 "-n,--num-coords", autoCoordNumItems,
327 "Number of random coordinates (default 5)");
328
329 CLI::App *channelTestSub = cli.add_subcommand(
330 "channel", "Test ChannelService to_host and from_host");
331 uint32_t channelIters = 10;
332 channelTestSub->add_option("-i,--iters", channelIters,
333 "Number of loopback iterations (default 10)");
334
335 CLI::App *resetSub = cli.add_subcommand(
336 "reset", "Test the design reset feature (telemetry clears after reset)");
337
338 if (int rc = cli.esiParse(argc, argv))
339 return rc;
340 if (!cli.get_help_ptr()->empty())
341 return 0;
342
343 Context &ctxt = cli.getContext();
344 AcceleratorConnection *acc = cli.connect();
345 try {
346 const auto &info = *acc->getService<services::SysInfo>();
347 ctxt.getLogger().info("esitester", "Connected to accelerator.");
348 Manifest manifest(ctxt, info.getJsonManifest());
349 Accelerator *accel = manifest.buildAccelerator(*acc);
350 ctxt.getLogger().info("esitester", "Built accelerator.");
351 acc->getServiceThread()->addPoll(*accel);
352
353 if (*callback_test) {
354 callbackTest(acc, accel, cb_iters);
355 } else if (*hostmemtestSub) {
356 hostmemTest(acc, accel, hostmemWidths, hmWrite, hmRead);
357 } else if (*loopbackSub) {
358 loopbackAddTest(acc, accel, loopbackIters, loopbackPipeline);
359 } else if (*dmatestSub) {
360 dmaTest(acc, accel, dmaWidths, dmaRead, dmaWrite);
361 } else if (*bandwidthSub) {
362 bandwidthTest(acc, accel, bandwidthWidths, xferCount, bandwidthRead,
363 bandwidthWrite, bandwidthCheckData);
364 } else if (*hostmembwSub) {
365 hostmemBandwidthTest(acc, accel, hmBwCount, hmBwWidths, hmBwRead,
366 hmBwWrite);
367 } else if (*aggBwSub) {
368 aggregateHostmemBandwidthTest(acc, accel, aggWidth, aggCount, aggRead,
369 aggWrite);
370 } else if (*streamingAddSub) {
371 if (streamingTranslate)
372 streamingAddTranslatedTest(acc, accel, streamingAddAmt,
373 streamingNumItems);
374 else
375 streamingAddTest(acc, accel, streamingAddAmt, streamingNumItems);
376 } else if (*coordTranslateSub) {
377 coordTranslateTest(acc, accel, coordXTrans, coordYTrans, coordNumItems);
378 } else if (*serialCoordTranslateSub) {
379 serialCoordTranslateTest(acc, accel, coordXTrans, coordYTrans,
380 coordNumItems, serialBatchSize);
381 } else if (*autoSerialCoordTranslateSub) {
382 autoSerialCoordTranslateTest(acc, accel, autoCoordXTrans, autoCoordYTrans,
383 autoCoordNumItems);
384 } else if (*channelTestSub) {
385 channelTest(acc, accel, channelIters);
386 } else if (*resetSub) {
387 resetTest(acc, accel);
388 }
389
390 acc->disconnect();
391 } catch (std::exception &e) {
392 ctxt.getLogger().error("esitester", e.what());
393 acc->disconnect();
394 return -1;
395 }
396 std::cout << "Exiting successfully\n";
397 return 0;
398}
399
401 uint32_t iterations) {
402 auto cb_test = accel->getChildren().find(AppID("cb_test"));
403 if (cb_test == accel->getChildren().end())
404 throw std::runtime_error("No cb_test child found in accelerator");
405 auto &ports = cb_test->second->getPorts();
406 auto cmd_port = ports.find(AppID("cmd"));
407 if (cmd_port == ports.end())
408 throw std::runtime_error("No cmd port found in cb_test child");
409 auto *cmdMMIO = cmd_port->second.getAs<services::MMIO::MMIORegion>();
410 if (!cmdMMIO)
411 throw std::runtime_error("cb_test cmd port is not MMIO");
412
413 auto f = ports.find(AppID("cb"));
414 if (f == ports.end())
415 throw std::runtime_error("No cb port found in accelerator");
416
417 auto *callPort = f->second.getAs<services::CallService::Callback>();
418 if (!callPort)
419 throw std::runtime_error("cb port is not a CallService::Callback");
420
421 std::atomic<uint32_t> callbackCount = 0;
422 callPort->connect(
423 [conn, &callbackCount](const MessageData &data) mutable -> MessageData {
424 conn->getLogger().debug(
425 [&](std::string &subsystem, std::string &msg,
426 std::unique_ptr<std::map<std::string, std::any>> &details) {
427 subsystem = "ESITESTER";
428 msg = "Received callback";
429 details = std::make_unique<std::map<std::string, std::any>>();
430 details->emplace("data", data);
431 });
432 std::cout << "callback: " << *data.as<uint64_t>() << std::endl;
433 callbackCount.fetch_add(1);
434 return MessageData();
435 },
436 true);
437
438 for (uint32_t i = 0; i < iterations; ++i) {
439 conn->getLogger().info("esitester", "Issuing callback command iteration " +
440 std::to_string(i) + "/" +
441 std::to_string(iterations));
442 cmdMMIO->write(0x10, i); // Command the callback
443 // Wait up to 1 second for the callback to be invoked.
444 for (uint32_t wait = 0; wait < 1000; ++wait) {
445 if (callbackCount.load() > i)
446 break;
447 std::this_thread::sleep_for(std::chrono::milliseconds(1));
448 }
449 if (callbackCount.load() <= i)
450 throw std::runtime_error("Callback test failed. No callback received");
451 }
452}
453
455 uint64_t address, uint64_t flits) {
456 struct RegisterExpectation {
457 uint32_t offset;
458 uint64_t expected;
459 const char *name;
460 };
461 const RegisterExpectation expectations[] = {
462 {0x00, 0, "flits_left"},
463 {0x08, address, "start_addr"},
464 {0x10, flits, "flits_total"},
465 };
466 for (const auto &[offset, expected, name] : expectations) {
467 uint64_t actual = mmio.read(offset);
468 if (actual != expected)
469 throw std::runtime_error("BurstCommand MMIO readback for " +
470 std::string(name) + " failed: expected " +
471 toHex(expected) + ", got " + toHex(actual));
472 }
473}
474
475/// Test the hostmem write functionality.
478 uint32_t width) {
479 std::cout << "Running hostmem WRITE test with width " << width << std::endl;
480 uint64_t *dataPtr = static_cast<uint64_t *>(region.getPtr());
481 auto check = [&](bool print) {
482 bool ret = true;
483 for (size_t i = 0; i < 9; ++i) {
484 if (print)
485 printf("[write] dataPtr[%zu] = 0x%016lx\n", i, dataPtr[i]);
486 if (i < (width + 63) / 64 && dataPtr[i] == 0xFFFFFFFFFFFFFFFFull)
487 ret = false;
488 }
489 return ret;
490 };
491
492 auto writeMemChildIter = acc->getChildren().find(AppID("writemem", width));
493 if (writeMemChildIter == acc->getChildren().end())
494 throw std::runtime_error(
495 "hostmem write test failed. No writemem child found");
496 auto &writeMemPorts = writeMemChildIter->second->getPorts();
497
498 // The MMIO command surface lives in a nested 'mmio[width]' submodule
499 // (BurstCommand -> MmioRegistry), exposing its 'cmd' port at
500 // writemem[width]/mmio[width]/cmd.
501 AppIDPath cmdPath;
502 BundlePort *cmdPortBundle = acc->resolvePort(
503 {AppID("writemem", width), AppID("mmio", width), AppID("cmd")}, cmdPath);
504 if (!cmdPortBundle)
505 throw std::runtime_error(
506 "hostmem write test failed. No mmio[width]/cmd MMIO port");
507 auto *cmdMMIO = cmdPortBundle->getAs<services::MMIO::MMIORegion>();
508 if (!cmdMMIO)
509 throw std::runtime_error(
510 "hostmem write test failed. mmio[width]/cmd port not MMIO");
511
512 auto issuedPortIter = writeMemPorts.find(AppID("addrCmdIssued"));
513 if (issuedPortIter == writeMemPorts.end())
514 throw std::runtime_error(
515 "hostmem write test failed. addrCmdIssued missing");
516 auto *addrCmdIssuedPort =
517 issuedPortIter->second.getAs<services::TelemetryService::Metric>();
518 if (!addrCmdIssuedPort)
519 throw std::runtime_error(
520 "hostmem write test failed. addrCmdIssued not telemetry");
521 addrCmdIssuedPort->connect();
522
523 auto responsesPortIter = writeMemPorts.find(AppID("addrCmdResponses"));
524 if (responsesPortIter == writeMemPorts.end())
525 throw std::runtime_error(
526 "hostmem write test failed. addrCmdResponses missing");
527 auto *addrCmdResponsesPort =
528 responsesPortIter->second.getAs<services::TelemetryService::Metric>();
529 if (!addrCmdResponsesPort)
530 throw std::runtime_error(
531 "hostmem write test failed. addrCmdResponses not telemetry");
532 addrCmdResponsesPort->connect();
533
534 for (size_t i = 0, e = 9; i < e; ++i)
535 dataPtr[i] = 0xFFFFFFFFFFFFFFFFull;
536 region.flush();
537 uint64_t devPtr = reinterpret_cast<uint64_t>(region.getDevicePtr());
538 cmdMMIO->write(0x08, devPtr);
539 cmdMMIO->write(0x10, 1);
540 checkBurstCommandRegisters(*cmdMMIO, devPtr, 1);
541 cmdMMIO->write(0x18, 1);
542 bool done = false;
543 for (int i = 0; i < 100; ++i) {
544 auto issued = addrCmdIssuedPort->readInt();
545 auto responses = addrCmdResponsesPort->readInt();
546 if (issued == 1 && responses == 1) {
547 done = true;
548 break;
549 }
550 std::this_thread::sleep_for(std::chrono::microseconds(100));
551 }
552 if (!done) {
553 check(true);
554 throw std::runtime_error("hostmem write test (" + std::to_string(width) +
555 " bits) timeout waiting for completion");
556 }
557 if (!check(true))
558 throw std::runtime_error("hostmem write test failed (" +
559 std::to_string(width) + " bits)");
560}
561
564 uint32_t width) {
565 std::cout << "Running hostmem READ test with width " << width << std::endl;
566 auto readMemChildIter = acc->getChildren().find(AppID("readmem", width));
567 if (readMemChildIter == acc->getChildren().end())
568 throw std::runtime_error(
569 "hostmem read test failed. No readmem child found");
570
571 auto &readMemPorts = readMemChildIter->second->getPorts();
572 // The MMIO command surface lives in a nested 'mmio[width]' submodule
573 // (BurstCommand -> MmioRegistry), exposing its 'cmd' port at
574 // readmem[width]/mmio[width]/cmd.
575 AppIDPath addrCmdPath;
576 BundlePort *addrCmdPortBundle = acc->resolvePort(
577 {AppID("readmem", width), AppID("mmio", width), AppID("cmd")},
578 addrCmdPath);
579 if (!addrCmdPortBundle)
580 throw std::runtime_error(
581 "hostmem read test failed. No mmio[width]/cmd MMIO port");
582 auto *addrCmdMMIO = addrCmdPortBundle->getAs<services::MMIO::MMIORegion>();
583 if (!addrCmdMMIO)
584 throw std::runtime_error(
585 "hostmem read test failed. mmio[width]/cmd port not MMIO");
586
587 auto lastReadPortIter = readMemPorts.find(AppID("lastReadLSB"));
588 if (lastReadPortIter == readMemPorts.end())
589 throw std::runtime_error("hostmem read test failed. lastReadLSB missing");
590 auto *lastReadPort =
591 lastReadPortIter->second.getAs<services::TelemetryService::Metric>();
592 if (!lastReadPort)
593 throw std::runtime_error(
594 "hostmem read test failed. lastReadLSB not telemetry");
595 lastReadPort->connect();
596
597 auto issuedPortIter = readMemPorts.find(AppID("addrCmdIssued"));
598 if (issuedPortIter == readMemPorts.end())
599 throw std::runtime_error("hostmem read test failed. addrCmdIssued missing");
600 auto *addrCmdIssuedPort =
601 issuedPortIter->second.getAs<services::TelemetryService::Metric>();
602 if (!addrCmdIssuedPort)
603 throw std::runtime_error(
604 "hostmem read test failed. addrCmdIssued not telemetry");
605 addrCmdIssuedPort->connect();
606
607 auto responsesPortIter = readMemPorts.find(AppID("addrCmdResponses"));
608 if (responsesPortIter == readMemPorts.end())
609 throw std::runtime_error(
610 "hostmem read test failed. addrCmdResponses missing");
611 auto *addrCmdResponsesPort =
612 responsesPortIter->second.getAs<services::TelemetryService::Metric>();
613 if (!addrCmdResponsesPort)
614 throw std::runtime_error(
615 "hostmem read test failed. addrCmdResponses not telemetry");
616 addrCmdResponsesPort->connect();
617
618 for (size_t i = 0; i < 8; ++i) {
619 auto *dataPtr = static_cast<uint64_t *>(region.getPtr());
620 dataPtr[0] = 0x12345678ull << i;
621 dataPtr[1] = 0xDEADBEEFull << i;
622 region.flush();
623 uint64_t devPtr = reinterpret_cast<uint64_t>(region.getDevicePtr());
624 addrCmdMMIO->write(0x08, devPtr);
625 addrCmdMMIO->write(0x10, 1);
626 checkBurstCommandRegisters(*addrCmdMMIO, devPtr, 1);
627 addrCmdMMIO->write(0x18, 1);
628 bool done = false;
629 for (int waitLoop = 0; waitLoop < 100; ++waitLoop) {
630 auto issued = addrCmdIssuedPort->readInt();
631 auto responses = addrCmdResponsesPort->readInt();
632 if (issued == 1 && responses == 1) {
633 done = true;
634 break;
635 }
636 std::this_thread::sleep_for(std::chrono::milliseconds(10));
637 }
638 if (!done)
639 throw std::runtime_error("hostmem read (" + std::to_string(width) +
640 " bits) timeout waiting for completion");
641 uint64_t captured = lastReadPort->readInt();
642 uint64_t expected = dataPtr[0];
643 if (width < 64)
644 expected &= ((1ull << width) - 1);
645 if (captured != expected)
646 throw std::runtime_error("hostmem read test (" + std::to_string(width) +
647 " bits) failed. Expected " +
648 esi::toHex(expected) + ", got " +
649 esi::toHex(captured));
650 }
651}
652
654 const std::vector<uint32_t> &widths, bool write,
655 bool read) {
656 // Enable the host memory service.
657 auto hostmem = conn->getService<services::HostMem>();
658 hostmem->start();
659 auto scratchRegion = hostmem->allocate(/*size(bytes)=*/1024 * 1024,
660 /*memOpts=*/{.writeable = true});
661 if (!scratchRegion)
662 throw std::runtime_error("hostmem test: failed to allocate host memory");
663 uint64_t *dataPtr = static_cast<uint64_t *>(scratchRegion->getPtr());
664 conn->getLogger().info("esitester",
665 "Running host memory test with region size " +
666 std::to_string(scratchRegion->getSize()) +
667 " bytes at 0x" + toHex(dataPtr));
668 for (size_t i = 0; i < scratchRegion->getSize() / 8; ++i)
669 dataPtr[i] = 0;
670 scratchRegion->flush();
671
672 bool passed = true;
673 for (size_t width : widths) {
674 try {
675 if (write)
676 hostmemWriteTest(acc, *scratchRegion, width);
677 if (read)
678 hostmemReadTest(acc, *scratchRegion, width);
679 } catch (std::exception &e) {
680 conn->getLogger().error("esitester", "Hostmem test failed for width " +
681 std::to_string(width) + ": " +
682 e.what());
683 passed = false;
684 }
685 }
686 if (!passed)
687 throw std::runtime_error("Hostmem test failed");
688 std::cout << "Hostmem test passed" << std::endl;
689}
690
692 size_t width) {
693 Logger &logger = conn->getLogger();
694 logger.info("esitester",
695 "== Running DMA read test with width " + std::to_string(width));
696 AppIDPath lastPath;
697 BundlePort *toHostMMIOPort =
698 acc->resolvePort({AppID("tohostdma", width), AppID("cmd")}, lastPath);
699 if (!toHostMMIOPort)
700 throw std::runtime_error("dma read test failed. No tohostdma[" +
701 std::to_string(width) + "] found");
702 auto *toHostMMIO = toHostMMIOPort->getAs<services::MMIO::MMIORegion>();
703 if (!toHostMMIO)
704 throw std::runtime_error("dma read test failed. MMIO port is not MMIO");
705 lastPath.clear();
706 BundlePort *outPortBundle =
707 acc->resolvePort({AppID("tohostdma", width), AppID("out")}, lastPath);
708 ReadChannelPort &outPort = outPortBundle->getRawRead("data");
709 outPort.connect();
710
711 size_t xferCount = 24;
712 MessageData data;
713 toHostMMIO->write(0, xferCount);
714 const size_t wireBytes = (width + 7) / 8;
715 for (size_t index = 0; index < xferCount; ++index) {
716 outPort.read(data);
717 if (data.getSize() != wireBytes)
718 throw std::runtime_error("dma read test failed. Expected " +
719 std::to_string(wireBytes) + " bytes, got " +
720 std::to_string(data.getSize()));
721 for (size_t byte = 0; byte < wireBytes; ++byte) {
722 uint8_t expected =
723 enginePatternByte(static_cast<uint32_t>(index), byte, width);
724 if (data.getBytes()[byte] != expected)
725 throw std::runtime_error(
726 "dma read test failed. Data mismatch at item " +
727 std::to_string(index) + " byte " + std::to_string(byte) +
728 ": expected " + toHex(expected) + ", got " +
729 toHex(data.getBytes()[byte]));
730 }
731 logger.debug("esitester",
732 "Payload [" + std::to_string(index) + "] = 0x" + data.toHex());
733 }
734 outPort.disconnect();
735 std::cout << " DMA read test for " << width << " bits passed" << std::endl;
736}
737
739 size_t width) {
740 Logger &logger = conn->getLogger();
741 logger.info("esitester",
742 "Running DMA write test with width " + std::to_string(width));
743 AppIDPath lastPath;
744 BundlePort *fromHostMMIOPort =
745 acc->resolvePort({AppID("fromhostdma", width), AppID("cmd")}, lastPath);
746 if (!fromHostMMIOPort)
747 throw std::runtime_error("dma read test for " + toString(width) +
748 " bits failed. No fromhostdma[" +
749 std::to_string(width) + "] found");
750 auto *fromHostMMIO = fromHostMMIOPort->getAs<services::MMIO::MMIORegion>();
751 if (!fromHostMMIO)
752 throw std::runtime_error("dma write test for " + toString(width) +
753 " bits failed. MMIO port is not MMIO");
754 lastPath.clear();
755 BundlePort *outPortBundle =
756 acc->resolvePort({AppID("fromhostdma", width), AppID("in")}, lastPath);
757 if (!outPortBundle)
758 throw std::runtime_error("dma write test for " + toString(width) +
759 " bits failed. No out port found");
760 WriteChannelPort &writePort = outPortBundle->getRawWrite("data");
761 writePort.connect();
762
763 size_t xferCount = 24;
764 std::vector<uint8_t> data((width + 7) / 8, 0);
765 fromHostMMIO->read(8);
766 fromHostMMIO->write(0, xferCount);
767 for (size_t i = 1; i < xferCount + 1; ++i) {
768 data[0] = i;
769 bool successWrite;
770 size_t attempts = 0;
771 do {
772 successWrite = writePort.tryWrite(MessageData(data.data(), data.size()));
773 if (!successWrite) {
774 std::this_thread::sleep_for(std::chrono::milliseconds(10));
775 }
776 } while (!successWrite && ++attempts < 100);
777 if (!successWrite)
778 throw std::runtime_error("dma write test for " + toString(width) +
779 " bits failed. Write failed");
780 uint64_t lastReadMMIO;
781 for (size_t a = 0; a < 20; ++a) {
782 lastReadMMIO = fromHostMMIO->read(8);
783 if (lastReadMMIO == i)
784 break;
785 std::this_thread::sleep_for(std::chrono::milliseconds(10));
786 if (a >= 19)
787 throw std::runtime_error("dma write for " + toString(width) +
788 " bits test failed. Read from MMIO failed");
789 }
790 }
791 writePort.disconnect();
792 std::cout << " DMA write test for " << width << " bits passed" << std::endl;
793}
794
796 const std::vector<uint32_t> &widths, bool read,
797 bool write) {
798 bool success = true;
799 if (write)
800 for (size_t width : widths)
801 try {
802 dmaWriteTest(conn, acc, width);
803 } catch (std::exception &e) {
804 success = false;
805 std::cerr << "DMA write test for " << width
806 << " bits failed: " << e.what() << std::endl;
807 }
808 if (read)
809 for (size_t width : widths)
810 dmaReadTest(conn, acc, width);
811 if (!success)
812 throw std::runtime_error("DMA test failed");
813 std::cout << "DMA test passed" << std::endl;
814}
815
816//
817// DMA bandwidth test
818
819static size_t engineWireBytes(size_t bitWidth) { return (bitWidth + 7) / 8; }
820
821static uint8_t enginePatternByte(uint32_t index, size_t byte, size_t bitWidth) {
822 uint8_t value = esitesterDataByte(index, byte);
823 const size_t tailBits = bitWidth % 8;
824 if (tailBits != 0 && byte + 1 == engineWireBytes(bitWidth))
825 value &= (uint8_t(1) << tailBits) - 1;
826 return value;
827}
828
829static std::vector<uint8_t> enginePatternBytes(uint32_t index,
830 size_t bitWidth) {
831 std::vector<uint8_t> bytes(engineWireBytes(bitWidth));
832 for (size_t byte = 0; byte < bytes.size(); ++byte)
833 bytes[byte] = enginePatternByte(index, byte, bitWidth);
834 return bytes;
835}
836
837static uint64_t enginePayloadFold(uint32_t index, size_t bitWidth) {
838 const size_t numChunks = (bitWidth + 63) / 64;
839 uint64_t fold = 0;
840 for (size_t chunkIndex = 0; chunkIndex < numChunks; ++chunkIndex) {
841 uint64_t chunk = 0;
842 for (size_t byteInChunk = 0; byteInChunk < 8; ++byteInChunk) {
843 const size_t byteIndex = chunkIndex * 8 + byteInChunk;
844 if (byteIndex < engineWireBytes(bitWidth))
845 chunk |= uint64_t(enginePatternByte(index, byteIndex, bitWidth))
846 << (8 * byteInChunk);
847 }
848 const unsigned rotate = (8 * chunkIndex) % 64;
849 fold ^= rotate ? ((chunk << rotate) | (chunk >> (64 - rotate))) : chunk;
850 }
851 return fold;
852}
853
855 size_t width, size_t xferCount, bool checkData) {
856
857 AppIDPath lastPath;
858 BundlePort *toHostMMIOPort =
859 acc->resolvePort({AppID("tohostdma", width), AppID("cmd")}, lastPath);
860 if (!toHostMMIOPort)
861 throw std::runtime_error("bandwidth test failed. No tohostdma[" +
862 std::to_string(width) + "] found");
863 auto *toHostMMIO = toHostMMIOPort->getAs<services::MMIO::MMIORegion>();
864 if (!toHostMMIO)
865 throw std::runtime_error("bandwidth test failed. MMIO port is not MMIO");
866 lastPath.clear();
867 BundlePort *outPortBundle =
868 acc->resolvePort({AppID("tohostdma", width), AppID("out")}, lastPath);
869 ReadChannelPort &outPort = outPortBundle->getRawRead("data");
870 outPort.connect();
871
872 Logger &logger = conn->getLogger();
873 logger.info("esitester", "Starting read bandwidth test with " +
874 std::to_string(xferCount) + " x " +
875 std::to_string(width) + " bit transfers");
876 MessageData data;
877 size_t sizeMismatches = 0;
878 size_t dataMismatches = 0;
879 size_t firstMismatchItem = 0;
880 size_t firstMismatchByte = 0;
881 uint8_t firstExpected = 0;
882 uint8_t firstActual = 0;
883 auto start = std::chrono::high_resolution_clock::now();
884 toHostMMIO->write(0, xferCount);
885 for (size_t index = 0; index < xferCount; ++index) {
886 outPort.read(data);
887 if (checkData) {
888 const size_t wireBytes = engineWireBytes(width);
889 if (data.getSize() != wireBytes) {
890 ++sizeMismatches;
891 } else {
892 for (size_t byte = 0; byte < wireBytes; ++byte) {
893 const uint8_t expected =
894 enginePatternByte(static_cast<uint32_t>(index), byte, width);
895 if (data.getBytes()[byte] != expected) {
896 if (dataMismatches == 0) {
897 firstMismatchItem = index;
898 firstMismatchByte = byte;
899 firstExpected = expected;
900 firstActual = data.getBytes()[byte];
901 }
902 ++dataMismatches;
903 }
904 }
905 }
906 }
907 logger.debug(
908 [index,
909 &data](std::string &subsystem, std::string &msg,
910 std::unique_ptr<std::map<std::string, std::any>> &details) {
911 subsystem = "esitester";
912 msg = "Payload [" + std::to_string(index) + "] = 0x" + data.toHex();
913 });
914 }
915 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
916 std::chrono::high_resolution_clock::now() - start);
917 outPort.disconnect();
918 if (checkData && sizeMismatches != 0)
919 throw std::runtime_error(
920 "bandwidth read data mismatch: " + std::to_string(sizeMismatches) +
921 " payload(s) had the wrong wire size");
922 if (checkData && dataMismatches != 0)
923 throw std::runtime_error(
924 "bandwidth read data mismatch: " + std::to_string(dataMismatches) +
925 " bytes wrong; first at item " + std::to_string(firstMismatchItem) +
926 " byte " + std::to_string(firstMismatchByte) + ": expected " +
927 toHex(firstExpected) + ", got " + toHex(firstActual));
928 double bytesPerSec =
929 (double)xferCount * (width / 8.0) * 1e6 / (double)duration.count();
930 logger.info("esitester",
931 " Bandwidth test: " + std::to_string(xferCount) + " x " +
932 std::to_string(width) + " bit transfers in " +
933 std::to_string(duration.count()) + " microseconds");
934 logger.info("esitester", " bandwidth: " + formatBandwidth(bytesPerSec));
935 if (checkData)
936 logger.info("esitester", " data integrity: passed");
937}
938
940 size_t width, size_t xferCount, bool checkData) {
941
942 AppIDPath lastPath;
943 BundlePort *fromHostMMIOPort =
944 acc->resolvePort({AppID("fromhostdma", width), AppID("cmd")}, lastPath);
945 if (!fromHostMMIOPort)
946 throw std::runtime_error("bandwidth test failed. No fromhostdma[" +
947 std::to_string(width) + "] found");
948 auto *fromHostMMIO = fromHostMMIOPort->getAs<services::MMIO::MMIORegion>();
949 if (!fromHostMMIO)
950 throw std::runtime_error("bandwidth test failed. MMIO port is not MMIO");
951 services::TelemetryService::Metric *checksumPort = nullptr;
952 if (checkData) {
953 auto fromHostChild = acc->getChildren().find(AppID("fromhostdma", width));
954 if (fromHostChild == acc->getChildren().end())
955 throw std::runtime_error("bandwidth test failed. No fromhostdma[" +
956 std::to_string(width) + "] found");
957 auto checksumIter =
958 fromHostChild->second->getPorts().find(AppID("fromHostChecksum"));
959 if (checksumIter == fromHostChild->second->getPorts().end())
960 throw std::runtime_error(
961 "bandwidth write data check failed. fromHostChecksum missing");
962 checksumPort =
963 checksumIter->second.getAs<services::TelemetryService::Metric>();
964 if (!checksumPort)
965 throw std::runtime_error("bandwidth write data check failed. "
966 "fromHostChecksum not telemetry");
967 checksumPort->connect();
968 }
969 lastPath.clear();
970 BundlePort *inPortBundle =
971 acc->resolvePort({AppID("fromhostdma", width), AppID("in")}, lastPath);
972 WriteChannelPort &outPort = inPortBundle->getRawWrite("data");
973 outPort.connect();
974
975 Logger &logger = conn->getLogger();
976 logger.info("esitester", "Starting write bandwidth test with " +
977 std::to_string(xferCount) + " x " +
978 std::to_string(width) + " bit transfers");
979 std::vector<uint8_t> dataVec(engineWireBytes(width));
980 for (size_t i = 0; i < dataVec.size(); ++i)
981 dataVec[i] = i;
982 MessageData data(dataVec);
983 uint64_t expectedChecksum = 0;
984 auto start = std::chrono::high_resolution_clock::now();
985 fromHostMMIO->read(8);
986 fromHostMMIO->write(0, xferCount);
987 for (size_t index = 0; index < xferCount; ++index) {
988 if (checkData) {
989 data =
990 MessageData(enginePatternBytes(static_cast<uint32_t>(index), width));
991 expectedChecksum ^=
992 enginePayloadFold(static_cast<uint32_t>(index), width);
993 }
994 outPort.write(data);
995 logger.debug(
996 [index,
997 &data](std::string &subsystem, std::string &msg,
998 std::unique_ptr<std::map<std::string, std::any>> &details) {
999 subsystem = "esitester";
1000 msg = "Payload [" + std::to_string(index) + "] = 0x" + data.toHex();
1001 });
1002 }
1003 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
1004 std::chrono::high_resolution_clock::now() - start);
1005 if (checkData) {
1006 std::vector<uint8_t> expectedLast;
1007 if (xferCount != 0)
1008 expectedLast =
1009 enginePatternBytes(static_cast<uint32_t>(xferCount - 1), width);
1010 uint64_t expectedLastValue = 0;
1011 if (!expectedLast.empty())
1012 std::memcpy(&expectedLastValue, expectedLast.data(),
1013 std::min(expectedLast.size(), sizeof(expectedLastValue)));
1014 bool complete = xferCount == 0;
1015 uint64_t lastReadValue = 0;
1016 for (size_t attempt = 0; !complete && attempt < 5000; ++attempt) {
1017 lastReadValue = fromHostMMIO->read(8);
1018 if (lastReadValue == expectedLastValue) {
1019 complete = true;
1020 break;
1021 }
1022 std::this_thread::sleep_for(std::chrono::milliseconds(1));
1023 }
1024 if (!complete)
1025 throw std::runtime_error(
1026 "bandwidth write data check timed out waiting for completion: "
1027 "expected final payload " +
1028 toHex(expectedLastValue) + ", got " + toHex(lastReadValue));
1029 const uint64_t actualChecksum = checksumPort->readInt();
1030 if (actualChecksum != expectedChecksum)
1031 throw std::runtime_error(
1032 "bandwidth write data mismatch: checksum expected " +
1033 toHex(expectedChecksum) + ", got " + toHex(actualChecksum));
1034 }
1035 if (checkData)
1036 outPort.disconnect();
1037 double bytesPerSec =
1038 (double)xferCount * (width / 8.0) * 1e6 / (double)duration.count();
1039 logger.info("esitester",
1040 " Bandwidth test: " + std::to_string(xferCount) + " x " +
1041 std::to_string(width) + " bit transfers in " +
1042 std::to_string(duration.count()) + " microseconds");
1043 logger.info("esitester", " bandwidth: " + formatBandwidth(bytesPerSec));
1044 if (checkData)
1045 logger.info("esitester", " data integrity: passed");
1046}
1047
1049 const std::vector<uint32_t> &widths,
1050 uint32_t xferCount, bool read, bool write,
1051 bool checkData) {
1052 if (read)
1053 for (uint32_t w : widths)
1054 bandwidthReadTest(conn, acc, w, xferCount, checkData);
1055 if (write)
1056 for (uint32_t w : widths)
1057 bandwidthWriteTest(conn, acc, w, xferCount, checkData);
1058}
1059
1060// Fixed 64-bit seed for the hostmem burst data pattern; must match
1061// _ESITESTER_SEQ_SEED in esiaccel/esitester.py.
1062static constexpr uint64_t kEsitesterSeqSeed = 0x5A5A5A5A5A5A5A5AULL;
1063
1064// Byte j of element i in the hostmem burst data pattern: tile (seed ^ i)
1065// across the element's bytes and XOR each byte with a distinct per-position
1066// mask so every byte is unique. Must match WriteMem/ReadMem in
1067// esiaccel/esitester.py.
1068static inline uint8_t esitesterDataByte(uint32_t i, size_t j) {
1069 uint64_t seq = (uint64_t)i ^ kEsitesterSeqSeed;
1070 return (uint8_t)(seq >> (8 * (j % 8))) ^ (uint8_t)(j * 0x9D);
1071}
1072
1073static size_t hostmemWireBytes(uint32_t width) { return (width + 7) / 8; }
1074
1075static uint8_t esitesterHostmemByte(uint32_t index, size_t byte,
1076 uint32_t width) {
1077 uint8_t value = esitesterDataByte(index, byte);
1078 const size_t tailBits = width % 8;
1079 if (tailBits != 0 && byte + 1 == hostmemWireBytes(width))
1080 value &= (uint8_t(1) << tailBits) - 1;
1081 return value;
1082}
1083
1084// Fold element i's `width` bits into its 64-bit readChecksum contribution:
1085// XOR each 64-bit chunk with a per-chunk rotate so word/byte misplacement
1086// doesn't cancel. Must match ReadMem's readChecksum in esiaccel/esitester.py.
1087static inline uint64_t esitesterElemFold(uint32_t i, uint32_t width) {
1088 size_t numBytes = hostmemWireBytes(width);
1089 size_t numChunks = (width + 63) / 64;
1090 uint64_t fold = 0;
1091 for (size_t c = 0; c < numChunks; ++c) {
1092 uint64_t chunk = 0;
1093 for (size_t b = 0; b < 8; ++b) {
1094 size_t j = 8 * c + b;
1095 if (j < numBytes)
1096 chunk |= (uint64_t)esitesterHostmemByte(i, j, width) << (8 * b);
1097 }
1098 unsigned r = (8 * c) % 64;
1099 fold ^= r ? ((chunk << r) | (chunk >> (64 - r))) : chunk;
1100 }
1101 return fold;
1102}
1103
1104//
1105// Hostmem bandwidth test
1106//
1107
1108static void
1111 uint32_t width, uint32_t xferCount) {
1112 Logger &logger = conn->getLogger();
1113 logger.info("esitester", "Starting hostmem WRITE bandwidth test: " +
1114 std::to_string(xferCount) + " x " +
1115 std::to_string(width) + " bits");
1116
1117 auto writeMemChildIter = acc->getChildren().find(AppID("writemem", width));
1118 if (writeMemChildIter == acc->getChildren().end())
1119 throw std::runtime_error("hostmem write bandwidth: writemem child missing");
1120 auto &writeMemPorts = writeMemChildIter->second->getPorts();
1121
1122 // MMIO command surface and cycle telemetry live in nested BurstCommand
1123 // submodules: MMIO at writemem[width]/mmio[width]/cmd and the active-cycle
1124 // metric at writemem[width]/addrCmdResp/cycles.
1125 AppIDPath cmdPath;
1126 BundlePort *cmdPortBundle = acc->resolvePort(
1127 {AppID("writemem", width), AppID("mmio", width), AppID("cmd")}, cmdPath);
1128 if (!cmdPortBundle)
1129 throw std::runtime_error("hostmem write bandwidth: cmd MMIO missing");
1130 auto *cmdMMIO = cmdPortBundle->getAs<services::MMIO::MMIORegion>();
1131 if (!cmdMMIO)
1132 throw std::runtime_error("hostmem write bandwidth: cmd not MMIO");
1133
1134 AppIDPath cyclePath;
1135 BundlePort *cyclePortBundle = acc->resolvePort(
1136 {AppID("writemem", width), AppID("addrCmdResp"), AppID("cycles")},
1137 cyclePath);
1138 auto issuedIter = writeMemPorts.find(AppID("addrCmdIssued"));
1139 auto respIter = writeMemPorts.find(AppID("addrCmdResponses"));
1140 if (issuedIter == writeMemPorts.end() || respIter == writeMemPorts.end() ||
1141 !cyclePortBundle)
1142 throw std::runtime_error("hostmem write bandwidth: telemetry missing");
1143 auto *issuedPort =
1144 issuedIter->second.getAs<services::TelemetryService::Metric>();
1145 auto *respPort = respIter->second.getAs<services::TelemetryService::Metric>();
1146 auto *cyclePort =
1147 cyclePortBundle->getAs<services::TelemetryService::Metric>();
1148 if (!issuedPort || !respPort || !cyclePort)
1149 throw std::runtime_error(
1150 "hostmem write bandwidth: telemetry type mismatch");
1151
1152 issuedPort->connect();
1153 respPort->connect();
1154 cyclePort->connect();
1155
1156 // Initialize pattern (optional).
1157 uint64_t *dataPtr = static_cast<uint64_t *>(region.getPtr());
1158 size_t words = region.getSize() / 8;
1159 for (size_t i = 0; i < words; ++i)
1160 dataPtr[i] = i + 0xA5A50000;
1161 region.flush();
1162
1163 auto start = std::chrono::high_resolution_clock::now();
1164 // Fire off xferCount write commands (one flit each).
1165 uint64_t devPtr = reinterpret_cast<uint64_t>(region.getDevicePtr());
1166 cmdMMIO->write(0x08, devPtr); // address
1167 cmdMMIO->write(0x10, xferCount); // flits
1168 cmdMMIO->write(0x18, 1); // start
1169
1170 // Wait for responses counter to reach target.
1171 bool completed = false;
1172 for (int wait = 0; wait < 100000; ++wait) {
1173 uint64_t respNow = respPort->readInt();
1174 if (respNow == xferCount) {
1175 completed = true;
1176 break;
1177 }
1178 std::this_thread::sleep_for(std::chrono::microseconds(50));
1179 }
1180 if (!completed)
1181 throw std::runtime_error("hostmem write bandwidth timeout");
1182 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
1183 std::chrono::high_resolution_clock::now() - start);
1184 double bytesPerSec =
1185 (double)xferCount * (width / 8.0) * 1e6 / (double)duration.count();
1186 uint64_t cycles = cyclePort->readInt();
1187 double bytesPerCycle = (double)xferCount * (width / 8.0) / (double)cycles;
1188 std::cout << "[WRITE] Hostmem bandwidth (" << std::to_string(width)
1189 << "): " << formatBandwidth(bytesPerSec) << " "
1190 << std::to_string(xferCount) << " flits in "
1191 << std::to_string(duration.count()) << " us, "
1192 << std::to_string(cycles) << " cycles, " << bytesPerCycle
1193 << " bytes/cycle" << std::endl;
1194
1195 // Data integrity: WriteMem wrote the byte-level pattern (esitesterDataByte)
1196 // into element i. The host-memory layout must be contiguous and backend-
1197 // width-independent, so element i occupies ceil(width/8) bytes at that
1198 // stride; verify every byte.
1199 uint8_t *bytePtr = static_cast<uint8_t *>(region.getPtr());
1200 size_t elemBytes = hostmemWireBytes(width);
1201 size_t mismatches = 0;
1202 uint32_t firstMismatch = 0;
1203 size_t firstByte = 0;
1204 uint8_t firstExpected = 0, firstActual = 0;
1205 for (uint32_t i = 0; i < xferCount; ++i) {
1206 for (size_t j = 0; j < elemBytes; ++j) {
1207 uint8_t expected = esitesterHostmemByte(i, j, width);
1208 uint8_t actual = bytePtr[(size_t)i * elemBytes + j];
1209 if (actual != expected) {
1210 if (mismatches == 0) {
1211 firstMismatch = i;
1212 firstByte = j;
1213 firstExpected = expected;
1214 firstActual = actual;
1215 }
1216 ++mismatches;
1217 }
1218 }
1219 }
1220 if (mismatches != 0) {
1221 char eb[8], gb[8];
1222 std::snprintf(eb, sizeof(eb), "0x%02x", firstExpected);
1223 std::snprintf(gb, sizeof(gb), "0x%02x", firstActual);
1224 throw std::runtime_error(
1225 "hostmem write bandwidth data mismatch: " + std::to_string(mismatches) +
1226 " bytes wrong; first at element " + std::to_string(firstMismatch) +
1227 " byte " + std::to_string(firstByte) + " expected=" + eb +
1228 " got=" + gb);
1229 }
1230}
1231
1232static void
1235 uint32_t width, uint32_t xferCount) {
1236 Logger &logger = conn->getLogger();
1237 logger.info("esitester", "Starting hostmem READ bandwidth test: " +
1238 std::to_string(xferCount) + " x " +
1239 std::to_string(width) + " bits");
1240
1241 auto readMemChildIter = acc->getChildren().find(AppID("readmem", width));
1242 if (readMemChildIter == acc->getChildren().end())
1243 throw std::runtime_error("hostmem read bandwidth: readmem child missing");
1244 auto &readMemPorts = readMemChildIter->second->getPorts();
1245
1246 // MMIO at readmem[width]/mmio[width]/cmd; active-cycle metric at
1247 // readmem[width]/addrCmdResp/cycles (nested BurstCommand submodules).
1248 AppIDPath cmdPath;
1249 BundlePort *cmdPortBundle = acc->resolvePort(
1250 {AppID("readmem", width), AppID("mmio", width), AppID("cmd")}, cmdPath);
1251 if (!cmdPortBundle)
1252 throw std::runtime_error("hostmem read bandwidth: cmd MMIO missing");
1253 auto *cmdMMIO = cmdPortBundle->getAs<services::MMIO::MMIORegion>();
1254 if (!cmdMMIO)
1255 throw std::runtime_error("hostmem read bandwidth: cmd not MMIO");
1256
1257 AppIDPath cyclePath;
1258 BundlePort *cyclePortBundle = acc->resolvePort(
1259 {AppID("readmem", width), AppID("addrCmdResp"), AppID("cycles")},
1260 cyclePath);
1261 auto issuedIter = readMemPorts.find(AppID("addrCmdIssued"));
1262 auto respIter = readMemPorts.find(AppID("addrCmdResponses"));
1263 auto checksumIter = readMemPorts.find(AppID("readChecksum"));
1264 if (issuedIter == readMemPorts.end() || respIter == readMemPorts.end() ||
1265 checksumIter == readMemPorts.end() || !cyclePortBundle)
1266 throw std::runtime_error("hostmem read bandwidth: telemetry missing");
1267 auto *issuedPort =
1268 issuedIter->second.getAs<services::TelemetryService::Metric>();
1269 auto *respPort = respIter->second.getAs<services::TelemetryService::Metric>();
1270 auto *checksumPort =
1271 checksumIter->second.getAs<services::TelemetryService::Metric>();
1272 auto *cycleCntPort =
1273 cyclePortBundle->getAs<services::TelemetryService::Metric>();
1274 if (!issuedPort || !respPort || !checksumPort || !cycleCntPort)
1275 throw std::runtime_error("hostmem read bandwidth: telemetry type mismatch");
1276 issuedPort->connect();
1277 respPort->connect();
1278 checksumPort->connect();
1279 cycleCntPort->connect();
1280
1281 // Lay out the read data contiguously (natural ceil(width/8)-byte stride)
1282 // using the byte-level pattern for every byte; ReadMem folds each received
1283 // element into readChecksum, which must match this host-side fold if the
1284 // read fetched the right bytes.
1285 uint8_t *bytePtr = static_cast<uint8_t *>(region.getPtr());
1286 size_t elemBytes = hostmemWireBytes(width);
1287 uint64_t expectedChecksum = 0;
1288 for (uint32_t i = 0; i < xferCount; ++i) {
1289 for (size_t j = 0; j < elemBytes; ++j)
1290 bytePtr[(size_t)i * elemBytes + j] = esitesterHostmemByte(i, j, width);
1291 expectedChecksum ^= esitesterElemFold(i, width);
1292 }
1293 region.flush();
1294 uint64_t devPtr = reinterpret_cast<uint64_t>(region.getDevicePtr());
1295 auto start = std::chrono::high_resolution_clock::now();
1296
1297 cmdMMIO->write(0x08, devPtr);
1298 cmdMMIO->write(0x10, xferCount);
1299 cmdMMIO->write(0x18, 1);
1300
1301 bool timeout = true;
1302 for (int wait = 0; wait < 100000; ++wait) {
1303 uint64_t respNow = respPort->readInt();
1304 if (respNow == xferCount) {
1305 timeout = false;
1306 break;
1307 }
1308 std::this_thread::sleep_for(std::chrono::microseconds(50));
1309 }
1310 if (timeout)
1311 throw std::runtime_error("hostmem read bandwidth timeout");
1312 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
1313 std::chrono::high_resolution_clock::now() - start);
1314 double bytesPerSec =
1315 (double)xferCount * (width / 8.0) * 1e6 / (double)duration.count();
1316 uint64_t cycles = cycleCntPort->readInt();
1317 double bytesPerCycle = (double)xferCount * (width / 8.0) / (double)cycles;
1318 std::cout << "[ READ] Hostmem bandwidth (" << width
1319 << "): " << formatBandwidth(bytesPerSec) << ", " << xferCount
1320 << " flits in " << duration.count() << " us, " << cycles
1321 << " cycles, " << bytesPerCycle << " bytes/cycle" << std::endl;
1322
1323 uint64_t gotChecksum = checksumPort->readInt();
1324 if (gotChecksum != expectedChecksum) {
1325 char eb[24], gb[24];
1326 std::snprintf(eb, sizeof(eb), "0x%016llx",
1327 (unsigned long long)expectedChecksum);
1328 std::snprintf(gb, sizeof(gb), "0x%016llx", (unsigned long long)gotChecksum);
1329 throw std::runtime_error(
1330 std::string(
1331 "hostmem read bandwidth data mismatch: checksum expected ") +
1332 eb + " got " + gb);
1333 }
1334}
1335
1337 uint32_t xferCount,
1338 const std::vector<uint32_t> &widths, bool read,
1339 bool write) {
1340 auto hostmemSvc = conn->getService<services::HostMem>();
1341 hostmemSvc->start();
1342 auto region = hostmemSvc->allocate(/*size(bytes)=*/1024 * 1024 * 1024,
1343 /*memOpts=*/{.writeable = true});
1344 if (!region)
1345 throw std::runtime_error(
1346 "hostmem bandwidth test: failed to allocate host memory");
1347 for (uint32_t w : widths) {
1348 if (write)
1349 hostmemWriteBandwidthTest(conn, acc, *region, w, xferCount);
1350 if (read)
1351 hostmemReadBandwidthTest(conn, acc, *region, w, xferCount);
1352 }
1353}
1354
1356 uint32_t iterations, bool pipeline) {
1357 Logger &logger = conn->getLogger();
1358 auto loopbackChild = accel->getChildren().find(AppID("loopback"));
1359 if (loopbackChild == accel->getChildren().end())
1360 throw std::runtime_error("Loopback test: no 'loopback' child");
1361 auto &ports = loopbackChild->second->getPorts();
1362 auto addIter = ports.find(AppID("add"));
1363 if (addIter == ports.end())
1364 throw std::runtime_error("Loopback test: no 'add' port");
1365
1366 // Use FuncService::Func instead of raw channels.
1367 auto *funcPort = addIter->second.getAs<services::FuncService::Function>();
1368 if (!funcPort)
1369 throw std::runtime_error(
1370 "Loopback test: 'add' port not a FuncService::Function");
1371 funcPort->connect();
1372 if (iterations == 0) {
1373 logger.info("esitester", "Loopback add test: 0 iterations (skipped)");
1374 return;
1375 }
1376 std::mt19937_64 rng(0xC0FFEE);
1377 std::uniform_int_distribution<uint32_t> dist(0, (1u << 24) - 1);
1378
1379 if (!pipeline) {
1380 auto start = std::chrono::high_resolution_clock::now();
1381 for (uint32_t i = 0; i < iterations; ++i) {
1382 uint32_t argVal = dist(rng);
1383 uint32_t expected = (argVal + 11) & 0xFFFF;
1384 uint8_t argBytes[3] = {
1385 static_cast<uint8_t>(argVal & 0xFF),
1386 static_cast<uint8_t>((argVal >> 8) & 0xFF),
1387 static_cast<uint8_t>((argVal >> 16) & 0xFF),
1388 };
1389 MessageData argMsg(argBytes, 3);
1390 MessageData resMsg = funcPort->call(argMsg).get();
1391 uint16_t got = *resMsg.as<uint16_t>();
1392 std::cout << "[loopback] i=" << i << " arg=0x" << esi::toHex(argVal)
1393 << " got=0x" << esi::toHex(got) << " exp=0x"
1394 << esi::toHex(expected) << std::endl;
1395 if (got != expected)
1396 throw std::runtime_error("Loopback mismatch (non-pipelined)");
1397 }
1398 auto end = std::chrono::high_resolution_clock::now();
1399 auto us = std::chrono::duration_cast<std::chrono::microseconds>(end - start)
1400 .count();
1401 double callsPerSec = (double)iterations * 1e6 / (double)us;
1402 logger.info("esitester", "Loopback add test passed (non-pipelined, " +
1403 std::to_string(iterations) + " calls, " +
1404 std::to_string(us) + " us, " +
1405 std::to_string(callsPerSec) + " calls/s)");
1406 } else {
1407 // Pipelined mode: launch all calls first, then collect.
1408 std::vector<std::future<MessageData>> futures;
1409 futures.reserve(iterations);
1410 std::vector<uint32_t> expectedVals;
1411 expectedVals.reserve(iterations);
1412
1413 auto issueStart = std::chrono::high_resolution_clock::now();
1414 for (uint32_t i = 0; i < iterations; ++i) {
1415 uint32_t argVal = dist(rng);
1416 uint32_t expected = (argVal + 11) & 0xFFFF;
1417 uint8_t argBytes[3] = {
1418 static_cast<uint8_t>(argVal & 0xFF),
1419 static_cast<uint8_t>((argVal >> 8) & 0xFF),
1420 static_cast<uint8_t>((argVal >> 16) & 0xFF),
1421 };
1422 futures.emplace_back(funcPort->call(MessageData(argBytes, 3)));
1423 expectedVals.emplace_back(expected);
1424 }
1425 auto issueEnd = std::chrono::high_resolution_clock::now();
1426
1427 for (uint32_t i = 0; i < iterations; ++i) {
1428 MessageData resMsg = futures[i].get();
1429 uint16_t got = *resMsg.as<uint16_t>();
1430 uint16_t exp = (uint16_t)expectedVals[i];
1431 std::cout << "[loopback-pipelined] i=" << i << " got=0x"
1432 << esi::toHex(got) << " exp=0x" << esi::toHex(exp) << std::endl;
1433 if (got != exp)
1434 throw std::runtime_error("Loopback mismatch (pipelined) idx=" +
1435 std::to_string(i));
1436 }
1437 auto collectEnd = std::chrono::high_resolution_clock::now();
1438
1439 auto issueUs = std::chrono::duration_cast<std::chrono::microseconds>(
1440 issueEnd - issueStart)
1441 .count();
1442 auto totalUs = std::chrono::duration_cast<std::chrono::microseconds>(
1443 collectEnd - issueStart)
1444 .count();
1445
1446 double issueRate = (double)iterations * 1e6 / (double)issueUs;
1447 double completionRate = (double)iterations * 1e6 / (double)totalUs;
1448
1449 logger.info("esitester", "Loopback add test passed (pipelined). Issued " +
1450 std::to_string(iterations) + " in " +
1451 std::to_string(issueUs) + " us (" +
1452 std::to_string(issueRate) +
1453 " calls/s), total " + std::to_string(totalUs) +
1454 " us (" + std::to_string(completionRate) +
1455 " calls/s effective)");
1456 }
1457}
1458
1459// Exercise the design reset feature using existing telemetry. Run a hostmem
1460// write operation on the 'writemem' module, which increments its
1461// 'addrCmdResponses' telemetry counter. Confirm the telemetry advanced,
1462// request a design reset, then confirm the telemetry has been cleared back to
1463// zero (the counters live in the user design which the reset clears).
1464static void resetTest(AcceleratorConnection *conn, Accelerator *accel) {
1465 Logger &logger = conn->getLogger();
1466 constexpr uint32_t width = 64;
1467
1468 // Run an existing test that increments telemetry. The hostmem write test
1469 // bumps the writemem module's 'addrCmdResponses' counter.
1470 hostmemTest(conn, accel, {width}, /*write=*/true, /*read=*/false);
1471
1472 // Grab the writemem module's response telemetry counter to observe the
1473 // reset.
1474 auto writeMemChildIter = accel->getChildren().find(AppID("writemem", width));
1475 if (writeMemChildIter == accel->getChildren().end())
1476 throw std::runtime_error("Reset test: no 'writemem' child");
1477 auto &ports = writeMemChildIter->second->getPorts();
1478 auto respIter = ports.find(AppID("addrCmdResponses"));
1479 if (respIter == ports.end())
1480 throw std::runtime_error(
1481 "Reset test: no 'addrCmdResponses' telemetry port");
1482 auto *respMetric =
1483 respIter->second.getAs<services::TelemetryService::Metric>();
1484 if (!respMetric)
1485 throw std::runtime_error("Reset test: 'addrCmdResponses' not telemetry");
1486 respMetric->connect();
1487
1488 uint64_t before = respMetric->readInt();
1489 std::cout << "[reset] telemetry addrCmdResponses before reset = " << before
1490 << std::endl;
1491 if (before == 0)
1492 throw std::runtime_error(
1493 "Reset test: telemetry was not incremented by the hostmem write");
1494
1495 // Request a design reset.
1496 logger.info("esitester", "Requesting design reset");
1497 if (!conn->reset())
1498 throw std::runtime_error("Reset test: reset() reported failure");
1499 std::cout << "[reset] reset requested" << std::endl;
1500
1501 // The reset is asserted a fixed number of cycles after the request (to let
1502 // in-flight transactions drain), so poll the telemetry until it clears.
1503 uint64_t after = before;
1504 constexpr int maxPolls = 1000000;
1505 for (int polls = 0; polls < maxPolls; ++polls) {
1506 after = respMetric->readInt();
1507 if (after == 0)
1508 break;
1509 std::this_thread::sleep_for(std::chrono::microseconds(1));
1510 }
1511 std::cout << "[reset] telemetry addrCmdResponses after reset = " << after
1512 << std::endl;
1513 if (after != 0)
1514 throw std::runtime_error(
1515 "Reset test: telemetry was not cleared by the reset (got " +
1516 std::to_string(after) + ")");
1517
1518 std::cout << "Reset test passed" << std::endl;
1519}
1520
1522 Accelerator *acc, uint32_t width,
1523 uint32_t xferCount, bool read,
1524 bool write) {
1525 Logger &logger = conn->getLogger();
1526 if (!read && !write) {
1527 std::cout << "aggbandwidth: nothing to do (enable --read and/or --write)\n";
1528 return;
1529 }
1530 logger.info(
1531 "esitester",
1532 "Aggregate hostmem bandwidth start width=" + std::to_string(width) +
1533 " count=" + std::to_string(xferCount) +
1534 " read=" + (read ? "Y" : "N") + " write=" + (write ? "Y" : "N"));
1535
1536 auto hostmemSvc = conn->getService<services::HostMem>();
1537 hostmemSvc->start();
1538
1539 struct Unit {
1540 std::string prefix;
1541 bool isRead = false;
1542 bool isWrite = false;
1543 std::unique_ptr<esi::services::HostMem::HostMemRegion> region;
1544 services::TelemetryService::Metric *resp = nullptr;
1545 services::TelemetryService::Metric *cycles = nullptr;
1546 services::MMIO::MMIORegion *cmd = nullptr;
1547 bool launched = false;
1548 bool done = false;
1549 uint64_t bytes = 0;
1550 uint64_t duration_us = 0;
1551 uint64_t cycleCount = 0;
1552 std::chrono::high_resolution_clock::time_point start;
1553 };
1554 std::vector<Unit> units;
1555 const std::vector<std::string> readPrefixes = {"readmem", "readmem_0",
1556 "readmem_1", "readmem_2"};
1557 const std::vector<std::string> writePrefixes = {"writemem", "writemem_0",
1558 "writemem_1", "writemem_2"};
1559
1560 // Size each unit's region to the actual transfer (min 1 MiB) rather than a
1561 // fixed 1 GiB, so aggregating many units stays memory-bounded.
1562 size_t strideBytes = ((width + 31) / 32) * 4;
1563 size_t neededBytes = static_cast<size_t>(xferCount) * strideBytes;
1564 size_t regionBytes = neededBytes < (1u << 20) ? (1u << 20) : neededBytes;
1565
1566 auto addUnits = [&](const std::vector<std::string> &pref, bool doRead,
1567 bool doWrite) {
1568 for (auto &p : pref) {
1569 AppID id(p, width);
1570 auto childIt = acc->getChildren().find(id);
1571 if (childIt == acc->getChildren().end())
1572 continue; // silently skip missing variants
1573 auto &ports = childIt->second->getPorts();
1574 auto respIt = ports.find(AppID("addrCmdResponses"));
1575 // MMIO ('cmd') and the cycle metric are nested inside BurstCommand
1576 // submodules: <unit>/mmio[width]/cmd and <unit>/addrCmdResp/cycles.
1577 AppIDPath cmdPath, cycPath;
1578 BundlePort *cmdBundle =
1579 acc->resolvePort({id, AppID("mmio", width), AppID("cmd")}, cmdPath);
1580 BundlePort *cycBundle = acc->resolvePort(
1581 {id, AppID("addrCmdResp"), AppID("cycles")}, cycPath);
1582 if (respIt == ports.end() || !cmdBundle || !cycBundle)
1583 continue;
1584 auto *cmd = cmdBundle->getAs<services::MMIO::MMIORegion>();
1585 auto *resp = respIt->second.getAs<services::TelemetryService::Metric>();
1586 auto *cyc = cycBundle->getAs<services::TelemetryService::Metric>();
1587 if (!cmd || !resp || !cyc)
1588 continue;
1589 resp->connect();
1590 cyc->connect();
1591 Unit u;
1592 u.prefix = p;
1593 u.isRead = doRead;
1594 u.isWrite = doWrite;
1595 u.region = hostmemSvc->allocate(regionBytes, {.writeable = true});
1596 if (!u.region)
1597 throw std::runtime_error(
1598 "hostmem bandwidth test: failed to allocate host memory");
1599 // Init pattern.
1600 uint64_t *ptr = static_cast<uint64_t *>(u.region->getPtr());
1601 size_t words = u.region->getSize() / 8;
1602 for (size_t i = 0; i < words; ++i)
1603 ptr[i] =
1604 (p[0] == 'w' ? (0xA5A500000000ull + i) : (0xCAFEBABE0000ull + i));
1605 u.region->flush();
1606 u.cmd = cmd;
1607 u.resp = resp;
1608 u.cycles = cyc;
1609 u.bytes = uint64_t(xferCount) * (width / 8);
1610 units.emplace_back(std::move(u));
1611 }
1612 };
1613 if (read)
1614 addUnits(readPrefixes, true, false);
1615 if (write)
1616 addUnits(writePrefixes, false, true);
1617 if (units.empty()) {
1618 std::cout << "aggbandwidth: no matching units present for width " << width
1619 << "\n";
1620 return;
1621 }
1622
1623 auto wallStart = std::chrono::high_resolution_clock::now();
1624 // Launch sequentially.
1625 for (auto &u : units) {
1626 uint64_t devPtr = reinterpret_cast<uint64_t>(u.region->getDevicePtr());
1627 u.cmd->write(0x08, devPtr);
1628 u.cmd->write(0x10, xferCount);
1629 u.cmd->write(0x18, 1);
1630 u.start = std::chrono::high_resolution_clock::now();
1631 u.launched = true;
1632 }
1633
1634 // Poll all until complete.
1635 const uint64_t timeoutLoops = 200000; // ~10s at 50us sleep
1636 uint64_t loops = 0;
1637 while (true) {
1638 bool allDone = true;
1639 for (auto &u : units) {
1640 if (u.done)
1641 continue;
1642 if (u.resp->readInt() == xferCount) {
1643 auto end = std::chrono::high_resolution_clock::now();
1644 u.duration_us =
1645 std::chrono::duration_cast<std::chrono::microseconds>(end - u.start)
1646 .count();
1647 u.cycleCount = u.cycles->readInt();
1648 u.done = true;
1649 } else {
1650 allDone = false;
1651 }
1652 }
1653 if (allDone)
1654 break;
1655 if (++loops >= timeoutLoops)
1656 throw std::runtime_error("aggbandwidth: timeout");
1657 std::this_thread::sleep_for(std::chrono::microseconds(50));
1658 }
1659 auto wallUs = std::chrono::duration_cast<std::chrono::microseconds>(
1660 std::chrono::high_resolution_clock::now() - wallStart)
1661 .count();
1662
1663 uint64_t totalBytes = 0;
1664 uint64_t totalReadBytes = 0;
1665 uint64_t totalWriteBytes = 0;
1666 for (auto &u : units) {
1667 totalBytes += u.bytes;
1668 if (u.isRead)
1669 totalReadBytes += u.bytes;
1670 if (u.isWrite)
1671 totalWriteBytes += u.bytes;
1672 double unitBps = (double)u.bytes * 1e6 / (double)u.duration_us;
1673 std::cout << "[agg-unit] " << u.prefix << "[" << width << "] "
1674 << (u.isRead ? "READ" : (u.isWrite ? "WRITE" : "UNK"))
1675 << " bytes=" << humanBytes(u.bytes) << " (" << u.bytes << " B)"
1676 << " time=" << humanTimeUS(u.duration_us) << " (" << u.duration_us
1677 << " us) cycles=" << u.cycleCount
1678 << " throughput=" << formatBandwidth(unitBps) << std::endl;
1679 }
1680 // Compute aggregate bandwidths as total size / total wall time (not sum of
1681 // unit throughputs).
1682 double aggReadBps =
1683 totalReadBytes ? (double)totalReadBytes * 1e6 / (double)wallUs : 0.0;
1684 double aggWriteBps =
1685 totalWriteBytes ? (double)totalWriteBytes * 1e6 / (double)wallUs : 0.0;
1686 double aggCombinedBps =
1687 totalBytes ? (double)totalBytes * 1e6 / (double)wallUs : 0.0;
1688
1689 std::cout << "[agg-total] units=" << units.size()
1690 << " read_bytes=" << humanBytes(totalReadBytes) << " ("
1691 << totalReadBytes << " B)"
1692 << " read_bw=" << formatBandwidth(aggReadBps)
1693 << " write_bytes=" << humanBytes(totalWriteBytes) << " ("
1694 << totalWriteBytes << " B)"
1695 << " write_bw=" << formatBandwidth(aggWriteBps)
1696 << " combined_bytes=" << humanBytes(totalBytes) << " ("
1697 << totalBytes << " B)"
1698 << " combined_bw=" << formatBandwidth(aggCombinedBps)
1699 << " wall_time=" << humanTimeUS(wallUs) << " (" << wallUs << " us)"
1700 << std::endl;
1701 logger.info("esitester", "Aggregate hostmem bandwidth test complete");
1702}
1703
1704/// Packed struct representing a parallel window argument for StreamingAdder.
1705/// Layout in SystemVerilog (so it must be reversed in C):
1706/// { add_amt: UInt(32), input: UInt(32), last: UInt(8) }
1707#pragma pack(push, 1)
1709 uint8_t last;
1710 uint32_t input;
1711 uint32_t addAmt;
1712};
1713#pragma pack(pop)
1714static_assert(sizeof(StreamingAddArg) == 9,
1715 "StreamingAddArg must be 9 bytes packed");
1716
1717/// Packed struct representing a parallel window result for StreamingAdder.
1718/// Layout in SystemVerilog (so it must be reversed in C):
1719/// { data: UInt(32), last: UInt(8) }
1720#pragma pack(push, 1)
1722 uint8_t last;
1723 uint32_t data;
1724};
1725#pragma pack(pop)
1726static_assert(sizeof(StreamingAddResult) == 5,
1727 "StreamingAddResult must be 5 bytes packed");
1728
1729/// Test the StreamingAdder module. This module takes a struct containing
1730/// an add_amt and a list of uint32s, adds add_amt to each element, and
1731/// returns the resulting list. The data is streamed using windowed types.
1733 uint32_t addAmt, uint32_t numItems) {
1734 Logger &logger = conn->getLogger();
1735 logger.info("esitester", "Starting streaming add test with add_amt=" +
1736 std::to_string(addAmt) +
1737 ", num_items=" + std::to_string(numItems));
1738
1739 // Generate random input data.
1740 std::mt19937 rng(0xDEADBEEF);
1741 std::uniform_int_distribution<uint32_t> dist(0, 1000000);
1742 std::vector<uint32_t> inputData;
1743 inputData.reserve(numItems);
1744 for (uint32_t i = 0; i < numItems; ++i)
1745 inputData.push_back(dist(rng));
1746
1747 // Find the streaming_adder child.
1748 auto streamingAdderChild =
1749 accel->getChildren().find(AppID("streaming_adder"));
1750 if (streamingAdderChild == accel->getChildren().end())
1751 throw std::runtime_error(
1752 "Streaming add test: no 'streaming_adder' child found");
1753
1754 auto &ports = streamingAdderChild->second->getPorts();
1755 auto addIter = ports.find(AppID("streaming_add"));
1756 if (addIter == ports.end())
1757 throw std::runtime_error(
1758 "Streaming add test: no 'streaming_add' port found");
1759
1760 // Get the raw read/write channel ports for the windowed function.
1761 // The argument channel expects parallel windowed data where each message
1762 // contains: struct { add_amt: UInt(32), input: UInt(32), last: bool }
1763 WriteChannelPort &argPort = addIter->second.getRawWrite("arg");
1764 ReadChannelPort &resultPort = addIter->second.getRawRead("result");
1765
1766 argPort.connect(ChannelPort::ConnectOptions(std::nullopt, false));
1767 resultPort.connect(ChannelPort::ConnectOptions(std::nullopt, false));
1768
1769 // Send each list element with add_amt repeated in every message.
1770 for (size_t i = 0; i < inputData.size(); ++i) {
1771 StreamingAddArg arg;
1772 arg.addAmt = addAmt;
1773 arg.input = inputData[i];
1774 arg.last = (i == inputData.size() - 1) ? 1 : 0;
1775 argPort.write(
1776 MessageData(reinterpret_cast<const uint8_t *>(&arg), sizeof(arg)));
1777 logger.debug("esitester", "Sent {add_amt=" + std::to_string(arg.addAmt) +
1778 ", input=" + std::to_string(arg.input) +
1779 ", last=" + (arg.last ? "true" : "false") +
1780 "}");
1781 }
1782
1783 // Read the result list (also windowed).
1784 std::vector<uint32_t> results;
1785 bool lastSeen = false;
1786 while (!lastSeen) {
1787 MessageData resMsg;
1788 resultPort.read(resMsg);
1789 if (resMsg.getSize() < sizeof(StreamingAddResult))
1790 throw std::runtime_error(
1791 "Streaming add test: unexpected result message size");
1792
1793 const auto *res =
1794 reinterpret_cast<const StreamingAddResult *>(resMsg.getBytes());
1795 lastSeen = res->last != 0;
1796 results.push_back(res->data);
1797 logger.debug("esitester", "Received result=" + std::to_string(res->data) +
1798 " (last=" + (lastSeen ? "true" : "false") +
1799 ")");
1800 }
1801
1802 // Verify results.
1803 if (results.size() != inputData.size())
1804 throw std::runtime_error(
1805 "Streaming add test: result size mismatch. Expected " +
1806 std::to_string(inputData.size()) + ", got " +
1807 std::to_string(results.size()));
1808
1809 bool passed = true;
1810 std::cout << "Streaming add test results:" << std::endl;
1811 for (size_t i = 0; i < inputData.size(); ++i) {
1812 uint32_t expected = inputData[i] + addAmt;
1813 std::cout << " input[" << i << "]=" << inputData[i] << " + " << addAmt
1814 << " = " << results[i] << " (expected " << expected << ")";
1815 if (results[i] != expected) {
1816 std::cout << " MISMATCH!";
1817 passed = false;
1818 }
1819 std::cout << std::endl;
1820 }
1821
1822 argPort.disconnect();
1823 resultPort.disconnect();
1824
1825 if (!passed)
1826 throw std::runtime_error("Streaming add test failed: result mismatch");
1827
1828 logger.info("esitester", "Streaming add test passed");
1829 std::cout << "Streaming add test passed" << std::endl;
1830}
1831
1832/// Test the StreamingAdder module using message translation.
1833/// This version uses the list translation support where the message format is:
1834/// Argument: { add_amt (4 bytes), input_length (8 bytes), input_data[] }
1835/// Result: { data_length (8 bytes), data[] }
1836/// The translation layer automatically converts between this format and the
1837/// parallel windowed frames used by the hardware.
1838
1839/// Translated argument struct for StreamingAdder.
1840/// Memory layout (standard C struct ordering, fields in declaration order):
1841/// ESI type: struct { add_amt: UInt(32), input: List<UInt(32)> }
1842/// becomes host struct:
1843/// { input_length (size_t, 8 bytes on 64-bit), add_amt (uint32_t),
1844/// input_data[] }
1845/// Note: The translation layer handles the conversion between this C struct
1846/// layout and the hardware's SystemVerilog frame format.
1847/// Note: size_t is used for list lengths, so this format is platform-dependent.
1848#pragma pack(push, 1)
1851 uint32_t addAmt;
1852 // Trailing array data follows immediately after the struct in memory.
1853 // Use inputData() accessor to access it.
1854
1855 /// Get pointer to trailing input data array.
1856 uint32_t *inputData() { return reinterpret_cast<uint32_t *>(this + 1); }
1857 const uint32_t *inputData() const {
1858 return reinterpret_cast<const uint32_t *>(this + 1);
1859 }
1860 /// Get span view of input data (requires inputLength to be set first).
1861 std::span<uint32_t> inputDataSpan() { return {inputData(), inputLength}; }
1862 std::span<const uint32_t> inputDataSpan() const {
1863 return {inputData(), inputLength};
1864 }
1865
1866 static size_t allocSize(size_t numItems) {
1867 return sizeof(StreamingAddTranslatedArg) + numItems * sizeof(uint32_t);
1868 }
1869};
1870#pragma pack(pop)
1871
1872/// Translated result struct for StreamingAdder.
1873/// Memory layout:
1874/// struct { data: List<UInt(32)> }
1875/// becomes:
1876/// { data_length (size_t, 8 bytes on 64-bit), data[] }
1877#pragma pack(push, 1)
1880 // Trailing array data follows immediately after the struct in memory.
1881
1882 /// Get pointer to trailing result data array.
1883 uint32_t *data() { return reinterpret_cast<uint32_t *>(this + 1); }
1884 const uint32_t *data() const {
1885 return reinterpret_cast<const uint32_t *>(this + 1);
1886 }
1887 /// Get span view of result data (requires dataLength to be set first).
1888 std::span<uint32_t> dataSpan() { return {data(), dataLength}; }
1889 std::span<const uint32_t> dataSpan() const { return {data(), dataLength}; }
1890
1891 static size_t allocSize(size_t numItems) {
1892 return sizeof(StreamingAddTranslatedResult) + numItems * sizeof(uint32_t);
1893 }
1894};
1895#pragma pack(pop)
1896
1898 Accelerator *accel, uint32_t addAmt,
1899 uint32_t numItems) {
1900 Logger &logger = conn->getLogger();
1901 logger.info("esitester",
1902 "Starting streaming add test (translated) with add_amt=" +
1903 std::to_string(addAmt) +
1904 ", num_items=" + std::to_string(numItems));
1905
1906 // Generate random input data.
1907 std::mt19937 rng(0xDEADBEEF);
1908 std::uniform_int_distribution<uint32_t> dist(0, 1000000);
1909 std::vector<uint32_t> inputData;
1910 inputData.reserve(numItems);
1911 for (uint32_t i = 0; i < numItems; ++i)
1912 inputData.push_back(dist(rng));
1913
1914 // Find the streaming_adder child.
1915 auto streamingAdderChild =
1916 accel->getChildren().find(AppID("streaming_adder"));
1917 if (streamingAdderChild == accel->getChildren().end())
1918 throw std::runtime_error(
1919 "Streaming add test: no 'streaming_adder' child found");
1920
1921 auto &ports = streamingAdderChild->second->getPorts();
1922 auto addIter = ports.find(AppID("streaming_add"));
1923 if (addIter == ports.end())
1924 throw std::runtime_error(
1925 "Streaming add test: no 'streaming_add' port found");
1926
1927 // Get the raw read/write channel ports with translation enabled (default).
1928 WriteChannelPort &argPort = addIter->second.getRawWrite("arg");
1929 ReadChannelPort &resultPort = addIter->second.getRawRead("result");
1930
1931 // Connect with translation enabled (the default).
1932 argPort.connect();
1933 resultPort.connect();
1934
1935 // Allocate the argument struct with proper alignment for the struct
1936 // members. We use aligned_alloc to ensure the buffer meets alignment
1937 // requirements.
1938 size_t argSize = StreamingAddTranslatedArg::allocSize(numItems);
1939 constexpr size_t alignment = alignof(StreamingAddTranslatedArg);
1940 // aligned_alloc requires size to be a multiple of alignment
1941 size_t allocSize = ((argSize + alignment - 1) / alignment) * alignment;
1942 void *argRaw = alignedAllocCompat(alignment, allocSize);
1943 if (!argRaw)
1944 throw std::bad_alloc();
1945 auto argDeleter = [](void *p) { alignedFreeCompat(p); };
1946 std::unique_ptr<void, decltype(argDeleter)> argBuffer(argRaw, argDeleter);
1947 auto *arg = static_cast<StreamingAddTranslatedArg *>(argRaw);
1948 arg->inputLength = numItems;
1949 arg->addAmt = addAmt;
1950 for (uint32_t i = 0; i < numItems; ++i)
1951 arg->inputData()[i] = inputData[i];
1952
1953 logger.debug("esitester",
1954 "Sending translated argument: " + std::to_string(argSize) +
1955 " bytes, list_length=" + std::to_string(arg->inputLength) +
1956 ", add_amt=" + std::to_string(arg->addAmt));
1957
1958 // Send the complete message - translation will split it into frames.
1959 argPort.write(MessageData(reinterpret_cast<const uint8_t *>(arg), argSize));
1960 // argBuffer automatically freed when it goes out of scope
1961
1962 // Read the translated result.
1963 MessageData resMsg;
1964 resultPort.read(resMsg);
1965
1966 logger.debug("esitester", "Received translated result: " +
1967 std::to_string(resMsg.getSize()) + " bytes");
1968
1969 if (resMsg.getSize() < sizeof(StreamingAddTranslatedResult))
1970 throw std::runtime_error(
1971 "Streaming add test (translated): result too small");
1972
1973 const auto *result =
1974 reinterpret_cast<const StreamingAddTranslatedResult *>(resMsg.getBytes());
1975
1976 if (resMsg.getSize() <
1977 StreamingAddTranslatedResult::allocSize(result->dataLength))
1978 throw std::runtime_error(
1979 "Streaming add test (translated): result data truncated");
1980
1981 // Verify results.
1982 if (result->dataLength != inputData.size())
1983 throw std::runtime_error(
1984 "Streaming add test (translated): result size mismatch. Expected " +
1985 std::to_string(inputData.size()) + ", got " +
1986 std::to_string(result->dataLength));
1987
1988 bool passed = true;
1989 std::cout << "Streaming add test results:" << std::endl;
1990 for (size_t i = 0; i < inputData.size(); ++i) {
1991 uint32_t expected = inputData[i] + addAmt;
1992 std::cout << " input[" << i << "]=" << inputData[i] << " + " << addAmt
1993 << " = " << result->data()[i] << " (expected " << expected << ")";
1994 if (result->data()[i] != expected) {
1995 std::cout << " MISMATCH!";
1996 passed = false;
1997 }
1998 std::cout << std::endl;
1999 }
2000
2001 argPort.disconnect();
2002 resultPort.disconnect();
2003
2004 if (!passed)
2005 throw std::runtime_error(
2006 "Streaming add test (translated) failed: result mismatch");
2007
2008 logger.info("esitester", "Streaming add test passed (translated)");
2009 std::cout << "Streaming add test passed" << std::endl;
2010}
2011
2012/// Test the CoordTranslator module using message translation.
2013/// This version uses the list translation support where the message format is:
2014/// Argument: { x_translation, y_translation, coords_length, coords[] }
2015/// Result: { coords_length, coords[] }
2016/// Each coord is a struct { x, y }.
2017
2018/// Coordinate struct for CoordTranslator.
2019/// SV ordering means y comes before x in memory.
2020#pragma pack(push, 1)
2021struct Coord {
2022 uint32_t y; // SV ordering: last declared field first in memory
2023 uint32_t x;
2024};
2025#pragma pack(pop)
2026static_assert(sizeof(Coord) == 8, "Coord must be 8 bytes packed");
2027
2028/// Translated argument struct for CoordTranslator.
2029/// Memory layout (standard C struct ordering):
2030/// ESI type: struct { x_translation: UInt(32), y_translation: UInt(32),
2031/// coords: List<struct{x, y}> }
2032/// becomes host struct:
2033/// { coords_length (size_t, 8 bytes on 64-bit), y_translation (uint32_t),
2034/// x_translation (uint32_t), coords[] }
2035/// Note: Fields are in reverse order due to SV struct ordering.
2036/// Note: size_t is used for list lengths, so this format is platform-dependent.
2037#pragma pack(push, 1)
2040 uint32_t yTranslation; // SV ordering: last declared field first in memory
2042 // Trailing array data follows immediately after the struct in memory.
2043
2044 /// Get pointer to trailing coords array.
2045 Coord *coords() { return reinterpret_cast<Coord *>(this + 1); }
2046 const Coord *coords() const {
2047 return reinterpret_cast<const Coord *>(this + 1);
2048 }
2049 /// Get span view of coords (requires coordsLength to be set first).
2050 std::span<Coord> coordsSpan() { return {coords(), coordsLength}; }
2051 std::span<const Coord> coordsSpan() const { return {coords(), coordsLength}; }
2052
2053 static size_t allocSize(size_t numCoords) {
2054 return sizeof(CoordTranslateArg) + numCoords * sizeof(Coord);
2055 }
2056};
2057#pragma pack(pop)
2058
2059/// Translated result struct for CoordTranslator.
2060/// Memory layout:
2061/// ESI type: List<struct{x, y}>
2062/// becomes host struct:
2063/// { coords_length (size_t, 8 bytes on 64-bit), coords[] }
2064#pragma pack(push, 1)
2067 // Trailing array data follows immediately after the struct in memory.
2068
2069 /// Get pointer to trailing coords array.
2070 Coord *coords() { return reinterpret_cast<Coord *>(this + 1); }
2071 const Coord *coords() const {
2072 return reinterpret_cast<const Coord *>(this + 1);
2073 }
2074 /// Get span view of coords (requires coordsLength to be set first).
2075 std::span<Coord> coordsSpan() { return {coords(), coordsLength}; }
2076 std::span<const Coord> coordsSpan() const { return {coords(), coordsLength}; }
2077
2078 static size_t allocSize(size_t numCoords) {
2079 return sizeof(CoordTranslateResult) + numCoords * sizeof(Coord);
2080 }
2081};
2082#pragma pack(pop)
2083
2085 uint32_t xTrans, uint32_t yTrans,
2086 uint32_t numCoords) {
2087 Logger &logger = conn->getLogger();
2088 logger.info("esitester", "Starting coord translate test with x_trans=" +
2089 std::to_string(xTrans) +
2090 ", y_trans=" + std::to_string(yTrans) +
2091 ", num_coords=" + std::to_string(numCoords));
2092
2093 // Generate random input coordinates.
2094 // Note: Coord struct has y before x due to SV ordering, but we generate
2095 // and display as (x, y) for human readability.
2096 std::mt19937 rng(0xDEADBEEF);
2097 std::uniform_int_distribution<uint32_t> dist(0, 1000000);
2098 std::vector<Coord> inputCoords;
2099 inputCoords.reserve(numCoords);
2100 for (uint32_t i = 0; i < numCoords; ++i) {
2101 Coord c;
2102 c.x = dist(rng);
2103 c.y = dist(rng);
2104 inputCoords.push_back(c);
2105 }
2106
2107 // Find the coord_translator child.
2108 auto coordTranslatorChild =
2109 accel->getChildren().find(AppID("coord_translator"));
2110 if (coordTranslatorChild == accel->getChildren().end())
2111 throw std::runtime_error(
2112 "Coord translate test: no 'coord_translator' child found");
2113
2114 auto &ports = coordTranslatorChild->second->getPorts();
2115 auto translateIter = ports.find(AppID("translate_coords"));
2116 if (translateIter == ports.end())
2117 throw std::runtime_error(
2118 "Coord translate test: no 'translate_coords' port found");
2119
2120 // Use FuncService::Function which handles connection and translation.
2121 auto *funcPort =
2122 translateIter->second.getAs<services::FuncService::Function>();
2123 if (!funcPort)
2124 throw std::runtime_error(
2125 "Coord translate test: 'translate_coords' port not a "
2126 "FuncService::Function");
2127 funcPort->connect();
2128
2129 // Allocate the argument struct with proper alignment for the struct
2130 // members.
2131 size_t argSize = CoordTranslateArg::allocSize(numCoords);
2132 constexpr size_t alignment = alignof(CoordTranslateArg);
2133 // aligned_alloc requires size to be a multiple of alignment
2134 size_t allocSize = ((argSize + alignment - 1) / alignment) * alignment;
2135 void *argRaw = alignedAllocCompat(alignment, allocSize);
2136 if (!argRaw)
2137 throw std::bad_alloc();
2138 auto argDeleter = [](void *p) { alignedFreeCompat(p); };
2139 std::unique_ptr<void, decltype(argDeleter)> argBuffer(argRaw, argDeleter);
2140 auto *arg = static_cast<CoordTranslateArg *>(argRaw);
2141 arg->coordsLength = numCoords;
2142 arg->xTranslation = xTrans;
2143 arg->yTranslation = yTrans;
2144 for (uint32_t i = 0; i < numCoords; ++i)
2145 arg->coords()[i] = inputCoords[i];
2146
2147 logger.debug(
2148 "esitester",
2149 "Sending coord translate argument: " + std::to_string(argSize) +
2150 " bytes, coords_length=" + std::to_string(arg->coordsLength) +
2151 ", x_trans=" + std::to_string(arg->xTranslation) +
2152 ", y_trans=" + std::to_string(arg->yTranslation));
2153
2154 // Call the function - translation happens automatically.
2155 MessageData resMsg =
2156 funcPort
2157 ->call(MessageData(reinterpret_cast<const uint8_t *>(arg), argSize))
2158 .get();
2159 // argBuffer automatically freed when it goes out of scope
2160
2161 logger.debug("esitester", "Received coord translate result: " +
2162 std::to_string(resMsg.getSize()) + " bytes");
2163
2164 if (resMsg.getSize() < sizeof(CoordTranslateResult))
2165 throw std::runtime_error("Coord translate test: result too small");
2166
2167 const auto *result =
2168 reinterpret_cast<const CoordTranslateResult *>(resMsg.getBytes());
2169
2170 if (resMsg.getSize() < CoordTranslateResult::allocSize(result->coordsLength))
2171 throw std::runtime_error("Coord translate test: result data truncated");
2172
2173 // Verify results.
2174 if (result->coordsLength != inputCoords.size())
2175 throw std::runtime_error(
2176 "Coord translate test: result size mismatch. Expected " +
2177 std::to_string(inputCoords.size()) + ", got " +
2178 std::to_string(result->coordsLength));
2179
2180 bool passed = true;
2181 std::cout << "Coord translate test results:" << std::endl;
2182 for (size_t i = 0; i < inputCoords.size(); ++i) {
2183 uint32_t expectedX = inputCoords[i].x + xTrans;
2184 uint32_t expectedY = inputCoords[i].y + yTrans;
2185 std::cout << " coord[" << i << "]=(" << inputCoords[i].x << ","
2186 << inputCoords[i].y << ") + (" << xTrans << "," << yTrans
2187 << ") = (" << result->coords()[i].x << ","
2188 << result->coords()[i].y << ")";
2189 if (result->coords()[i].x != expectedX ||
2190 result->coords()[i].y != expectedY) {
2191 std::cout << " MISMATCH! (expected (" << expectedX << "," << expectedY
2192 << "))";
2193 passed = false;
2194 }
2195 std::cout << std::endl;
2196 }
2197
2198 if (!passed)
2199 throw std::runtime_error("Coord translate test failed: result mismatch");
2200
2201 logger.info("esitester", "Coord translate test passed");
2202 std::cout << "Coord translate test passed" << std::endl;
2203}
2204
2205//
2206// SerialCoordTranslator test
2207//
2208
2209#pragma pack(push, 1)
2211 uint16_t coordsCount;
2214};
2215static_assert(sizeof(SerialCoordHeader) == 10, "Size mismatch");
2217 SerialCoordData(uint32_t x, uint32_t y) : y(y), x(x), _pad_tail(0) {}
2218 uint32_t y;
2219 uint32_t x;
2220 uint16_t _pad_tail;
2221};
2222static_assert(sizeof(SerialCoordData) == sizeof(SerialCoordHeader),
2223 "Size mismatch");
2224#pragma pack(pop)
2225
2226// Note: this application is intended to test hardware. As such, we need
2227// to be able to send batches. So this is not the typical way one would define
2228// a message struct. It's closer to a streaming style.
2230private:
2232 std::vector<SerialCoordData> coords;
2234
2235public:
2237 header.coordsCount = 0;
2238 header.xTranslation = 0;
2239 header.yTranslation = 0;
2240 // The footer is a count==0 header that terminates the list per the ESI
2241 // bulk-transfer serial encoding. Static fields are constant within a
2242 // list so the footer's translation values are irrelevant; zero them.
2243 footer.coordsCount = 0;
2244 footer.xTranslation = 0;
2245 footer.yTranslation = 0;
2246 }
2247 void yTranslation(uint32_t yTrans) { header.yTranslation = yTrans; }
2248 uint32_t yTranslation() const { return header.yTranslation; }
2249 void xTranslation(uint32_t xTrans) { header.xTranslation = xTrans; }
2250 uint32_t xTranslation() const { return header.xTranslation; }
2251 void appendCoord(uint32_t x, uint32_t y) {
2252 coords.emplace_back(x, y);
2253 header.coordsCount = (uint16_t)coords.size();
2254 }
2255 const std::vector<SerialCoordData> &getCoords() const { return coords; }
2256
2257 size_t numSegments() const override { return 3; }
2258 Segment segment(size_t idx) const override {
2259 if (idx == 0)
2260 return {reinterpret_cast<const uint8_t *>(&header), sizeof(header)};
2261 else if (idx == 1)
2262 return {reinterpret_cast<const uint8_t *>(coords.data()),
2263 coords.size() * sizeof(SerialCoordData)};
2264 else if (idx == 2)
2265 return {reinterpret_cast<const uint8_t *>(&footer), sizeof(footer)};
2266 else
2267 throw std::out_of_range("SerialCoordInput: invalid segment index");
2268 }
2269};
2270
2271// Like SerialCoordInput but without the trailing count==0 terminator. Used
2272// when streaming multiple bursts that together comprise a single logical
2273// list; the caller is responsible for sending a separate terminator burst
2274// (a SerialCoordBurst with count==0 and no data).
2276private:
2278 std::vector<SerialCoordData> coords;
2279
2280public:
2282 header.coordsCount = 0;
2283 header.xTranslation = 0;
2284 header.yTranslation = 0;
2285 }
2286 void yTranslation(uint32_t yTrans) { header.yTranslation = yTrans; }
2287 void xTranslation(uint32_t xTrans) { header.xTranslation = xTrans; }
2288 void appendCoord(uint32_t x, uint32_t y) {
2289 coords.emplace_back(x, y);
2290 header.coordsCount = (uint16_t)coords.size();
2291 }
2292
2293 size_t numSegments() const override { return 2; }
2294 Segment segment(size_t idx) const override {
2295 if (idx == 0)
2296 return {reinterpret_cast<const uint8_t *>(&header), sizeof(header)};
2297 else if (idx == 1)
2298 return {reinterpret_cast<const uint8_t *>(coords.data()),
2299 coords.size() * sizeof(SerialCoordData)};
2300 else
2301 throw std::out_of_range("SerialCoordBurst: invalid segment index");
2302 }
2303};
2304
2305#pragma pack(push, 1)
2307 uint16_t coordsCount;
2308 uint8_t _pad[6];
2309};
2311 uint32_t y;
2312 uint32_t x;
2313};
2318#pragma pack(pop)
2319static_assert(sizeof(SerialCoordOutputFrame) == 8, "Size mismatch");
2320
2321/// Deserialized result batch from the serial coord translator. The
2322/// TypeDeserializer accumulates header+data frame sequences until the
2323/// zero-count footer header, then emits the complete coordinate list.
2325 std::vector<Coord> coords;
2326
2328 : public QueuedDecodeTypeDeserializer<SerialCoordOutputBatch> {
2329 public:
2333
2335 : Base(std::move(output)) {}
2336
2337 private:
2338 DecodedOutputs decode(std::unique_ptr<SegmentedMessageData> &msg) override {
2339 DecodedOutputs decoded;
2340
2341 MessageData scratch;
2342 const MessageData &flat = msg->asMessageData(scratch);
2343 const uint8_t *bytes = flat.getBytes();
2344 size_t size = flat.getSize();
2345 constexpr size_t frameSize = sizeof(SerialCoordOutputFrame);
2346
2347 size_t offset = 0;
2348 while (offset < size) {
2349 size_t needed = frameSize - partialFrameBytes.size();
2350 size_t chunkSize = std::min(needed, size - offset);
2351 partialFrameBytes.insert(partialFrameBytes.end(), bytes + offset,
2352 bytes + offset + chunkSize);
2353 offset += chunkSize;
2354
2355 if (partialFrameBytes.size() != frameSize)
2356 break;
2357
2359 std::memcpy(&frame, partialFrameBytes.data(), frameSize);
2360 partialFrameBytes.clear();
2361
2362 if (remainingCoords == 0) {
2363 // Header frame.
2364 uint16_t batchCount = frame.header.coordsCount;
2365 if (batchCount == 0) {
2366 // Footer: end of list. Emit accumulated coordinates.
2367 auto batch = std::make_unique<SerialCoordOutputBatch>();
2368 batch->coords = std::move(accumulated);
2369 accumulated.clear();
2370 decoded.push_back(std::move(batch));
2371 msg.reset();
2372 return decoded;
2373 }
2374 remainingCoords = batchCount;
2375 continue;
2376 }
2377 // Data frame.
2378 accumulated.push_back({frame.data.y, frame.data.x});
2380 }
2381
2382 msg.reset();
2383 return decoded;
2384 }
2385
2386 std::vector<Coord> accumulated;
2387 std::vector<uint8_t> partialFrameBytes;
2389 };
2390};
2391
2393 Accelerator *accel, uint32_t xTrans,
2394 uint32_t yTrans, uint32_t numCoords,
2395 size_t batchSizeLimit) {
2396 Logger &logger = conn->getLogger();
2397 logger.info("esitester", "Starting Serial coord translate test");
2398
2399 // Generate random coordinates.
2400 std::mt19937 rng(0xDEADBEEF);
2401 std::uniform_int_distribution<uint32_t> dist(0, 1000000);
2402 std::vector<Coord> inputCoords;
2403 inputCoords.reserve(numCoords);
2404 for (uint32_t i = 0; i < numCoords; ++i)
2405 inputCoords.push_back({dist(rng), dist(rng)});
2406
2407 auto child = accel->getChildren().find(AppID("coord_translator_serial"));
2408 if (child == accel->getChildren().end())
2409 throw std::runtime_error("Serial coord translate test: no "
2410 "'coord_translator_serial' child found");
2411
2412 auto &ports = child->second->getPorts();
2413 auto portIter = ports.find(AppID("translate_coords_serial"));
2414 if (portIter == ports.end())
2415 throw std::runtime_error("Serial coord translate test: no "
2416 "'translate_coords_serial' port found");
2417
2418 TypedWritePort<SerialCoordBurst, /*SkipTypeCheck=*/true> argPort(
2419 portIter->second.getRawWrite("arg"));
2420 // Use the raw read port so we can verify the multi-burst output framing
2421 // explicitly rather than relying on the typed deserializer to accumulate
2422 // frames until the terminator.
2423 ReadChannelPort &resultRaw = portIter->second.getRawRead("result");
2424
2425 argPort.connect(ChannelPort::ConnectOptions(std::nullopt, false));
2426 // Use an unlimited read queue so the device output isn't stalled by a full
2427 // queue while we're still writing. With raw reads (translateMessage=false),
2428 // each output frame becomes its own queued message, so the default 32-msg
2429 // limit can be hit easily on a multi-burst run.
2430 resultRaw.connect(ChannelPort::ConnectOptions(/*bufferSize=*/0,
2431 /*translateMessage=*/false));
2432
2433 size_t sent = 0;
2434 while (sent < numCoords) {
2435 size_t batchSize = std::min(batchSizeLimit, numCoords - sent);
2436
2437 // Send Header. Only the first header needs the translation values, test
2438 // the subsequent ones with zero translation to verify that the hardware
2439 // correctly applies the first header's translation to the whole list.
2440 auto batch = std::make_unique<SerialCoordBurst>();
2441 batch->xTranslation(sent == 0 ? xTrans : 0);
2442 batch->yTranslation(sent == 0 ? yTrans : 0);
2443 // Send Data
2444 for (size_t i = 0; i < batchSize; ++i) {
2445 batch->appendCoord(inputCoords[sent + i].x, inputCoords[sent + i].y);
2446 }
2447 argPort.write(batch);
2448 sent += batchSize;
2449 }
2450 // Send final header with count=0 to signal end of input.
2451 auto footerBurst = std::make_unique<SerialCoordBurst>();
2452 argPort.write(footerBurst);
2453
2454 // Read raw output frames, walking the bulk-transfer wire format: zero or
2455 // more (HDR(N) + N data frames) sequences followed by a single HDR(0)
2456 // terminator. Each `read()` returns whatever the transport layer has
2457 // available, which is not guaranteed to align with frame boundaries
2458 // (e.g., DMA channel engines may coalesce or split across frames). So
2459 // we accumulate bytes into a buffer and only consume whole frames.
2460 constexpr size_t frameSize = sizeof(SerialCoordOutputFrame);
2461 std::vector<uint8_t> rxBuf;
2462 auto readFrame = [&](SerialCoordOutputFrame &out) {
2463 while (rxBuf.size() < frameSize) {
2464 MessageData data;
2465 resultRaw.read(data);
2466 rxBuf.insert(rxBuf.end(), data.getBytes(),
2467 data.getBytes() + data.getSize());
2468 }
2469 std::memcpy(&out, rxBuf.data(), frameSize);
2470 rxBuf.erase(rxBuf.begin(), rxBuf.begin() + frameSize);
2471 };
2472
2473 std::vector<Coord> results;
2474 results.reserve(numCoords);
2475 while (true) {
2477 readFrame(hdr);
2478 uint16_t batchCount = hdr.header.coordsCount;
2479 if (batchCount == 0)
2480 break;
2481 for (uint16_t i = 0; i < batchCount; ++i) {
2482 SerialCoordOutputFrame frame{};
2483 readFrame(frame);
2484 results.push_back({frame.data.y, frame.data.x});
2485 }
2486 }
2487
2488 // Verify
2489 bool passed = true;
2490 std::cout << "Serial coord translate test results:" << std::endl;
2491 if (results.size() != inputCoords.size()) {
2492 std::cout << "Result size mismatch. Expected " << inputCoords.size()
2493 << ", got " << results.size() << std::endl;
2494 passed = false;
2495 }
2496 for (size_t i = 0; i < std::min(inputCoords.size(), results.size()); ++i) {
2497 uint32_t expX = inputCoords[i].x + xTrans;
2498 uint32_t expY = inputCoords[i].y + yTrans;
2499 std::cout << " coord[" << i << "]=(" << inputCoords[i].x << ","
2500 << inputCoords[i].y << ") + (" << xTrans << "," << yTrans
2501 << ") = (" << results[i].x << "," << results[i].y
2502 << ") (expected (" << expX << "," << expY << "))";
2503 if (results[i].x != expX || results[i].y != expY) {
2504 std::cout << " MISMATCH!";
2505 passed = false;
2506 }
2507 std::cout << std::endl;
2508 }
2509
2510 argPort.disconnect();
2511 resultRaw.disconnect();
2512
2513 if (!passed)
2514 throw std::runtime_error("Serial coord translate test failed");
2515
2516 logger.info("esitester", "Serial coord translate test passed");
2517 std::cout << "Serial coord translate test passed" << std::endl;
2518}
2519
2520//
2521// AutoSerialCoordTranslator test
2522//
2523// The hardware module pipes the input through ListWindowToParallel ->
2524// per-coordinate translation -> ListWindowToSerial. The conversion modules
2525// emit one or more bulk transfers per call (each `header(count>0)` followed
2526// by `count` data frames) terminated by a `header(count==0)` footer per the
2527// ESI WindowField serial-encoding spec. This test:
2528// * Sends exactly one input batch: header(numCoords) + numCoords data
2529// frames + header(0) footer.
2530// * Reads back: a sequence of one-or-more `header(count>0) + count data`
2531// bursts terminated by `header(0)`. Use raw frame reads since the
2532// canonical `SerialCoordOutputBatch` deserializer hasn't been wired in
2533// for the converter pair.
2534//
2536 Accelerator *accel, uint32_t xTrans,
2537 uint32_t yTrans, uint32_t numCoords) {
2538 Logger &logger = conn->getLogger();
2539 logger.info("esitester", "Starting Auto serial coord translate test");
2540
2541 // Generate random coordinates.
2542 std::mt19937 rng(0xDEADBEEF);
2543 std::uniform_int_distribution<uint32_t> dist(0, 1000000);
2544 std::vector<Coord> inputCoords;
2545 inputCoords.reserve(numCoords);
2546 for (uint32_t i = 0; i < numCoords; ++i)
2547 inputCoords.push_back({dist(rng), dist(rng)});
2548
2549 auto child = accel->getChildren().find(AppID("coord_translator_auto_serial"));
2550 if (child == accel->getChildren().end())
2551 throw std::runtime_error("Auto serial coord translate test: no "
2552 "'coord_translator_auto_serial' child found");
2553
2554 auto &ports = child->second->getPorts();
2555 auto portIter = ports.find(AppID("translate_coords_auto_serial"));
2556 if (portIter == ports.end())
2557 throw std::runtime_error("Auto serial coord translate test: no "
2558 "'translate_coords_auto_serial' port found");
2559
2560 // Reuse SerialCoordInput: the input wire format is identical (header with
2561 // x/y_translation+count, followed by data frames each carrying one coord).
2562 TypedWritePort<SerialCoordInput, /*SkipTypeCheck=*/true> argPort(
2563 portIter->second.getRawWrite("arg"));
2564 argPort.connect(ChannelPort::ConnectOptions(std::nullopt, false));
2565
2566 // Use the raw read port for results: read one header frame then numCoords
2567 // data frames as raw `SerialCoordOutputFrame`-shaped messages. Disable
2568 // window-message translation so we get one frame per `read()` instead of
2569 // assembled higher-level messages.
2570 ReadChannelPort &resultRaw = portIter->second.getRawRead("result");
2571 // Use an unlimited read queue so the device output isn't stalled by a full
2572 // queue while we're still writing. With raw reads (translateMessage=false),
2573 // each output frame becomes its own queued message, so the default 32-msg
2574 // limit can be hit easily on a multi-frame run.
2575 resultRaw.connect(ChannelPort::ConnectOptions(/*bufferSize=*/0,
2576 /*translateMessage=*/false));
2577
2578 // Send a single header+data burst.
2579 auto batch = std::make_unique<SerialCoordInput>();
2580 batch->xTranslation(xTrans);
2581 batch->yTranslation(yTrans);
2582 for (uint32_t i = 0; i < numCoords; ++i)
2583 batch->appendCoord(inputCoords[i].x, inputCoords[i].y);
2584 argPort.write(batch);
2585
2586 // Helper: read one raw frame, accumulating bytes across `read()` calls
2587 // since transports such as DMA channel engines do not guarantee that
2588 // each `read()` returns exactly one frame.
2589 constexpr size_t frameSize = sizeof(SerialCoordOutputFrame);
2590 std::vector<uint8_t> rxBuf;
2591 auto readFrame = [&](SerialCoordOutputFrame &out) {
2592 while (rxBuf.size() < frameSize) {
2593 MessageData data;
2594 resultRaw.read(data);
2595 rxBuf.insert(rxBuf.end(), data.getBytes(),
2596 data.getBytes() + data.getSize());
2597 }
2598 std::memcpy(&out, rxBuf.data(), frameSize);
2599 rxBuf.erase(rxBuf.begin(), rxBuf.begin() + frameSize);
2600 };
2601
2602 // Read a sequence of one-or-more `header(count>0) + count data` bursts
2603 // followed by a `header(count==0)` terminator footer. Total data items
2604 // received across all bursts must equal numCoords.
2605 std::vector<Coord> results;
2606 results.reserve(numCoords);
2607 while (true) {
2609 readFrame(hdr);
2610 uint16_t burstCount = hdr.header.coordsCount;
2611 if (burstCount == 0)
2612 break;
2613 if (results.size() + burstCount > numCoords)
2614 throw std::runtime_error("Auto serial coord translate test: bursts "
2615 "overflow expected total " +
2616 std::to_string(numCoords));
2617 for (uint32_t i = 0; i < burstCount; ++i) {
2618 SerialCoordOutputFrame frame{};
2619 readFrame(frame);
2620 results.push_back({frame.data.y, frame.data.x});
2621 }
2622 }
2623 if (results.size() != numCoords)
2624 throw std::runtime_error("Auto serial coord translate test: got " +
2625 std::to_string(results.size()) +
2626 " coords across all bursts " + "(expected " +
2627 std::to_string(numCoords) + ")");
2628
2629 argPort.disconnect();
2630 resultRaw.disconnect();
2631
2632 bool passed = true;
2633 std::cout << "Auto serial coord translate test results:" << std::endl;
2634 for (size_t i = 0; i < inputCoords.size(); ++i) {
2635 uint32_t expX = inputCoords[i].x + xTrans;
2636 uint32_t expY = inputCoords[i].y + yTrans;
2637 std::cout << " coord[" << i << "]=(" << inputCoords[i].x << ","
2638 << inputCoords[i].y << ") + (" << xTrans << "," << yTrans
2639 << ") = (" << results[i].x << "," << results[i].y
2640 << ") (expected (" << expX << "," << expY << "))";
2641 if (results[i].x != expX || results[i].y != expY) {
2642 std::cout << " MISMATCH!";
2643 passed = false;
2644 }
2645 std::cout << std::endl;
2646 }
2647
2648 if (!passed)
2649 throw std::runtime_error("Auto serial coord translate test failed");
2650
2651 logger.info("esitester", "Auto serial coord translate test passed");
2652 std::cout << "Auto serial coord translate test passed" << std::endl;
2653}
2654
2656 uint32_t iterations) {
2657 Logger &logger = conn->getLogger();
2658
2659 auto channelChild = accel->getChildren().find(AppID("channel_test"));
2660 if (channelChild == accel->getChildren().end())
2661 throw std::runtime_error("Channel test: no 'channel_test' child");
2662 auto &ports = channelChild->second->getPorts();
2663
2664 // --- Get the MMIO port to trigger the producer ---
2665 auto cmdIter = ports.find(AppID("cmd"));
2666 if (cmdIter == ports.end())
2667 throw std::runtime_error("Channel test: no 'cmd' port");
2668 auto *cmdMMIO = cmdIter->second.getAs<services::MMIO::MMIORegion>();
2669 if (!cmdMMIO)
2670 throw std::runtime_error("Channel test: 'cmd' is not MMIO");
2671
2672 // --- Get the producer to_host port ---
2673 auto producerIter = ports.find(AppID("producer"));
2674 if (producerIter == ports.end())
2675 throw std::runtime_error("Channel test: no 'producer' port");
2676 auto *producerPort =
2677 producerIter->second.getAs<services::ChannelService::ToHost>();
2678 if (!producerPort)
2679 throw std::runtime_error(
2680 "Channel test: 'producer' is not a ChannelService::ToHost");
2681 producerPort->connect();
2682
2683 // --- Test to_host: MMIO-triggered incrementing values ---
2684 // Write the number of values to send at offset 0x0.
2685 cmdMMIO->write(0x0, iterations);
2686
2687 for (uint32_t i = 0; i < iterations; ++i) {
2688 MessageData recvData = producerPort->read().get();
2689 uint32_t got = *recvData.as<uint32_t>();
2690 std::cout << "[channel] producer i=" << i << " got=" << got << std::endl;
2691 if (got != i)
2692 throw std::runtime_error("Channel producer: expected " +
2693 std::to_string(i) + ", got " +
2694 std::to_string(got));
2695 }
2696 logger.info("esitester", "Channel test: producer passed (" +
2697 std::to_string(iterations) +
2698 " incrementing values)");
2699
2700 // --- Test from_host -> to_host loopback ---
2701 auto loopbackInIter = ports.find(AppID("loopback_in"));
2702 if (loopbackInIter == ports.end())
2703 throw std::runtime_error("Channel test: no 'loopback_in' port");
2704 auto *fromHostPort =
2705 loopbackInIter->second.getAs<services::ChannelService::FromHost>();
2706 if (!fromHostPort)
2707 throw std::runtime_error(
2708 "Channel test: 'loopback_in' is not a ChannelService::FromHost");
2709 fromHostPort->connect();
2710
2711 auto loopbackOutIter = ports.find(AppID("loopback_out"));
2712 if (loopbackOutIter == ports.end())
2713 throw std::runtime_error("Channel test: no 'loopback_out' port");
2714 auto *loopbackOutPort =
2715 loopbackOutIter->second.getAs<services::ChannelService::ToHost>();
2716 if (!loopbackOutPort)
2717 throw std::runtime_error(
2718 "Channel test: 'loopback_out' is not a ChannelService::ToHost");
2719 loopbackOutPort->connect();
2720
2721 std::mt19937_64 rng(0xDEADBEEF);
2722 std::uniform_int_distribution<uint32_t> dist(0, UINT32_MAX);
2723
2724 for (uint32_t i = 0; i < iterations; ++i) {
2725 uint32_t sendVal = dist(rng);
2726 fromHostPort->write(MessageData::from(sendVal));
2727 MessageData recvData = loopbackOutPort->read().get();
2728 uint32_t recvVal = *recvData.as<uint32_t>();
2729 std::cout << "[channel] loopback i=" << i << " sent=0x"
2730 << esi::toHex(sendVal) << " recv=0x" << esi::toHex(recvVal)
2731 << std::endl;
2732 if (recvVal != sendVal)
2733 throw std::runtime_error("Channel loopback mismatch at i=" +
2734 std::to_string(i));
2735 }
2736
2737 logger.info("esitester", "Channel test: loopback passed (" +
2738 std::to_string(iterations) + " iterations)");
2739
2740 // --- Test from_host in callback mode ---
2741 // The port fetches each message once the channel can accept it. A small
2742 // in-flight limit makes the writes wait on the hardware consuming them.
2743 WriteChannelPort &rawFromHost = fromHostPort->getRawWrite("data");
2744 rawFromHost.disconnect();
2745 std::mutex fetchMutex;
2746 std::vector<uint32_t> toSend;
2747 size_t nextToSend = 0;
2748 std::exception_ptr writeError;
2750 writeOpts.bufferSize = 2;
2751 // Empty messages, which have no frames and so send nothing, are interleaved
2752 // to check that they don't stop the rest being fetched.
2753 bool sendEmpty = true;
2754 // The callbacks use the locals above, so disconnect before they're
2755 // destroyed, however this scope exits.
2756 struct DisconnectOnExit {
2757 WriteChannelPort &port;
2758 ~DisconnectOnExit() { port.disconnect(); }
2759 } disconnectOnExit{rawFromHost};
2760 rawFromHost.connect(
2761 [&]() -> std::unique_ptr<SegmentedMessageData> {
2762 std::lock_guard<std::mutex> lock(fetchMutex);
2763 if (nextToSend == toSend.size())
2764 return nullptr;
2765 if ((sendEmpty = !sendEmpty))
2766 return std::make_unique<MessageData>();
2767 return std::make_unique<MessageData>(
2768 MessageData::from(toSend[nextToSend++]));
2769 },
2770 [&](std::exception_ptr e) {
2771 std::lock_guard<std::mutex> lock(fetchMutex);
2772 if (!writeError)
2773 writeError = e;
2774 },
2775 writeOpts);
2776 uint32_t callbackIters = 16 * iterations;
2777 for (uint32_t i = 0; i < callbackIters; ++i) {
2778 {
2779 std::lock_guard<std::mutex> lock(fetchMutex);
2780 toSend.push_back(dist(rng));
2781 }
2782 rawFromHost.notifyAsyncDataAvailable();
2783 }
2784 for (uint32_t i = 0; i < callbackIters; ++i) {
2785 std::future<MessageData> recv = loopbackOutPort->read();
2786 if (recv.wait_for(std::chrono::seconds(30)) != std::future_status::ready)
2787 throw std::runtime_error("Channel callback loopback: timed out at i=" +
2788 std::to_string(i));
2789 uint32_t recvVal = *recv.get().as<uint32_t>();
2790 uint32_t sendVal;
2791 {
2792 std::lock_guard<std::mutex> lock(fetchMutex);
2793 sendVal = toSend[i];
2794 }
2795 if (recvVal != sendVal)
2796 throw std::runtime_error("Channel callback loopback mismatch at i=" +
2797 std::to_string(i));
2798 }
2799 rawFromHost.disconnect();
2800 if (writeError)
2801 std::rethrow_exception(writeError);
2802 std::cout << "[channel] callback loopback passed (" << callbackIters
2803 << " messages)" << std::endl;
2804
2805 std::cout << "Channel test passed" << std::endl;
2806}
static void print(TypedAttr val, llvm::raw_ostream &os)
return success()
QueuedDecodeTypeDeserializer< SerialCoordOutputBatch > Base
DecodedOutputs decode(std::unique_ptr< SegmentedMessageData > &msg) override
Decode one raw message into zero or more typed outputs.
Abstract class representing a connection to an accelerator.
Top level accelerator class.
Definition Accelerator.h:85
T * getAs() const
Cast this Bundle port to a subclass which is actually useful.
Definition Ports.h:781
Common options and code for ESI runtime tools.
Definition CLI.h:29
Context & getContext()
Get the context.
Definition CLI.h:69
AcceleratorConnection * connect()
Connect to the accelerator using the specified backend and connection.
Definition CLI.h:66
int esiParse(int argc, const char **argv)
Run the parser.
Definition CLI.h:52
AcceleratorConnections, Accelerators, and Manifests must all share a context.
Definition Context.h:34
Logger & getLogger()
Definition Context.h:69
const std::map< AppID, Instance * > & getChildren() const
Access the module's children by ID.
Definition Design.h:71
virtual void error(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an error.
Definition Logging.h:64
virtual void info(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an informational message.
Definition Logging.h:75
void debug(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a debug message.
Definition Logging.h:83
Class to parse a manifest.
Definition Manifest.h:39
Accelerator * buildAccelerator(AcceleratorConnection &acc) const
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
const uint8_t * getBytes() const
Definition Common.h:216
const T * as() const
Cast to a type.
Definition Common.h:240
size_t getSize() const
Get the size of the data in bytes.
Definition Common.h:230
static MessageData from(T &t)
Cast from a type to its raw bytes.
Definition Common.h:250
detail::TypedReadOwnedCallback< SerialCoordOutputBatch > OutputCallback
Definition TypedPorts.h:232
std::vector< std::unique_ptr< SerialCoordOutputBatch > > DecodedOutputs
Definition TypedPorts.h:233
A ChannelPort which reads data from the accelerator.
Definition Ports.h:595
virtual void connect(ReadCallback callback, const ConnectOptions &options={})
Definition Ports.cpp:143
virtual void disconnect() override
Disconnect the channel.
Definition Ports.cpp:71
virtual void read(MessageData &outData)
Specify a buffer to read into.
Definition Ports.h:659
Abstract multi-segment message.
Definition Common.h:151
const MessageData & asMessageData(MessageData &scratch) const
Return this message as a MessageData without copying if it already is one.
Definition Common.cpp:62
void connect(const ChannelPort::ConnectOptions &opts={std::nullopt, false})
Definition TypedPorts.h:610
void write(const T &data)
Definition TypedPorts.h:660
A ChannelPort which sends data to the accelerator.
Definition Ports.h:315
virtual void disconnect() override
Disconnect the port.
Definition Ports.cpp:902
virtual void notifyAsyncDataAvailable()
Notify the port that the DataFetchCallback has data again.
Definition Ports.cpp:938
void write(const MessageData &data)
A very basic blocking write API.
Definition Ports.h:356
virtual void connect(const ConnectOptions &options={}) override
Connect in sync mode. Throws if connected in callback mode.
Definition Ports.cpp:867
bool tryWrite(const MessageData &data)
A basic non-blocking write API.
Definition Ports.h:379
A function call which gets attached to a service port.
Definition Services.h:437
A port which writes data to the accelerator (from_host).
Definition Services.h:347
A port which reads data from the accelerator (to_host).
Definition Services.h:323
A function call which gets attached to a service port.
Definition Services.h:385
virtual void start()
In cases where necessary, enable host memory services.
Definition Services.h:292
services::HostMemRegion HostMemRegion
RAII memory region for host memory. See services::HostMemRegion.
Definition Services.h:289
A "slice" of some parent MMIO space.
Definition Services.h:187
virtual uint64_t read(uint32_t addr) const
Read a 64-bit value from this region, not the global address space.
Definition Services.cpp:132
Information about the Accelerator system.
Definition Services.h:113
A telemetry port which gets attached to a service port.
Definition Services.h:502
void connect()
Connect to a particular telemetry port. Offset should be non-nullopt.
Definition Services.cpp:481
int main()
static void * alignedAllocCompat(std::size_t alignment, std::size_t size)
static void bandwidthReadTest(AcceleratorConnection *conn, Accelerator *acc, size_t width, size_t xferCount, bool checkData)
static void hostmemWriteTest(Accelerator *acc, esi::services::HostMem::HostMemRegion &region, uint32_t width)
Test the hostmem write functionality.
static void aggregateHostmemBandwidthTest(AcceleratorConnection *, Accelerator *, uint32_t width, uint32_t xferCount, bool read, bool write)
static void dmaTest(AcceleratorConnection *, Accelerator *, const std::vector< uint32_t > &widths, bool read, bool write)
static void hostmemBandwidthTest(AcceleratorConnection *conn, Accelerator *acc, uint32_t xferCount, const std::vector< uint32_t > &widths, bool read, bool write)
static void callbackTest(AcceleratorConnection *, Accelerator *, uint32_t iterations)
static uint64_t enginePayloadFold(uint32_t index, size_t bitWidth)
static void serialCoordTranslateTest(AcceleratorConnection *, Accelerator *, uint32_t xTrans, uint32_t yTrans, uint32_t numCoords, size_t batchSizeLimit)
static void bandwidthTest(AcceleratorConnection *, Accelerator *, const std::vector< uint32_t > &widths, uint32_t xferCount, bool read, bool write, bool checkData)
static std::vector< uint8_t > enginePatternBytes(uint32_t index, size_t bitWidth)
static void hostmemReadBandwidthTest(AcceleratorConnection *conn, Accelerator *acc, esi::services::HostMem::HostMemRegion &region, uint32_t width, uint32_t xferCount)
static void channelTest(AcceleratorConnection *, Accelerator *, uint32_t iterations)
static std::string formatBandwidth(double bytesPerSec)
static void autoSerialCoordTranslateTest(AcceleratorConnection *, Accelerator *, uint32_t xTrans, uint32_t yTrans, uint32_t numCoords)
static void hostmemWriteBandwidthTest(AcceleratorConnection *conn, Accelerator *acc, esi::services::HostMem::HostMemRegion &region, uint32_t width, uint32_t xferCount)
static void alignedFreeCompat(void *ptr)
static void dmaWriteTest(AcceleratorConnection *conn, Accelerator *acc, size_t width)
static uint8_t esitesterHostmemByte(uint32_t index, size_t byte, uint32_t width)
static void bandwidthWriteTest(AcceleratorConnection *conn, Accelerator *acc, size_t width, size_t xferCount, bool checkData)
static size_t hostmemWireBytes(uint32_t width)
static std::string humanBytes(uint64_t bytes)
static void checkBurstCommandRegisters(services::MMIO::MMIORegion &mmio, uint64_t address, uint64_t flits)
static uint8_t esitesterDataByte(uint32_t index, size_t byte)
static uint64_t esitesterElemFold(uint32_t i, uint32_t width)
static void streamingAddTest(AcceleratorConnection *, Accelerator *, uint32_t addAmt, uint32_t numItems)
Test the StreamingAdder module.
static void loopbackAddTest(AcceleratorConnection *, Accelerator *, uint32_t iterations, bool pipeline)
static void dmaReadTest(AcceleratorConnection *conn, Accelerator *acc, size_t width)
static void streamingAddTranslatedTest(AcceleratorConnection *, Accelerator *, uint32_t addAmt, uint32_t numItems)
static void hostmemTest(AcceleratorConnection *, Accelerator *, const std::vector< uint32_t > &widths, bool write, bool read)
static std::string humanTimeUS(uint64_t us)
static void coordTranslateTest(AcceleratorConnection *, Accelerator *, uint32_t xTrans, uint32_t yTrans, uint32_t numCoords)
static void resetTest(AcceleratorConnection *, Accelerator *)
constexpr std::array< uint32_t, 8 > defaultWidths
Definition esitester.cpp:88
static uint8_t enginePatternByte(uint32_t index, size_t byte, size_t bitWidth)
static size_t engineWireBytes(size_t bitWidth)
static std::string defaultWidthsStr()
Definition esitester.cpp:90
static constexpr uint64_t kEsitesterSeqSeed
static void hostmemReadTest(Accelerator *acc, esi::services::HostMem::HostMemRegion &region, uint32_t width)
Definition esi.py:1
std::string toString(const std::any &a)
'Stringify' a std::any. This is used to log std::any values by some loggers.
Definition Logging.cpp:132
std::string toHex(void *val)
Definition Common.cpp:38
Definition seq.py:1
Translated argument struct for CoordTranslator.
std::span< const Coord > coordsSpan() const
const Coord * coords() const
static size_t allocSize(size_t numCoords)
Coord * coords()
Get pointer to trailing coords array.
std::span< Coord > coordsSpan()
Get span view of coords (requires coordsLength to be set first).
Translated result struct for CoordTranslator.
static size_t allocSize(size_t numCoords)
std::span< Coord > coordsSpan()
Get span view of coords (requires coordsLength to be set first).
const Coord * coords() const
Coord * coords()
Get pointer to trailing coords array.
std::span< const Coord > coordsSpan() const
Test the CoordTranslator module using message translation.
uint32_t x
uint32_t y
void yTranslation(uint32_t yTrans)
void appendCoord(uint32_t x, uint32_t y)
std::vector< SerialCoordData > coords
void xTranslation(uint32_t xTrans)
SerialCoordHeader header
Segment segment(size_t idx) const override
Get a segment by index. Throws if the segment has been take()n.
size_t numSegments() const override
Number of segments in the message.
SerialCoordData(uint32_t x, uint32_t y)
size_t numSegments() const override
Number of segments in the message.
void appendCoord(uint32_t x, uint32_t y)
uint32_t yTranslation() const
SerialCoordHeader header
void yTranslation(uint32_t yTrans)
SerialCoordHeader footer
uint32_t xTranslation() const
Segment segment(size_t idx) const override
Get a segment by index. Throws if the segment has been take()n.
const std::vector< SerialCoordData > & getCoords() const
void xTranslation(uint32_t xTrans)
std::vector< SerialCoordData > coords
Deserialized result batch from the serial coord translator.
std::vector< Coord > coords
Packed struct representing a parallel window argument for StreamingAdder.
Packed struct representing a parallel window result for StreamingAdder.
Test the StreamingAdder module using message translation.
uint32_t * inputData()
Get pointer to trailing input data array.
static size_t allocSize(size_t numItems)
std::span< uint32_t > inputDataSpan()
Get span view of input data (requires inputLength to be set first).
std::span< const uint32_t > inputDataSpan() const
const uint32_t * inputData() const
Translated result struct for StreamingAdder.
uint32_t * data()
Get pointer to trailing result data array.
std::span< uint32_t > dataSpan()
Get span view of result data (requires dataLength to be set first).
static size_t allocSize(size_t numItems)
std::span< const uint32_t > dataSpan() const
const uint32_t * data() const
std::optional< unsigned > bufferSize
The buffer size is optional and should be considered merely a hint.
Definition Ports.h:128
A contiguous, non-owning view of bytes within a SegmentedMessageData.
Definition Common.h:122
virtual std::size_t getSize() const =0
virtual void * getPtr() const =0
Get a pointer to the host memory.
virtual void flush()
Flush the memory region to ensure that the device sees the latest contents.
Definition Services.h:256
virtual void * getDevicePtr() const
Sometimes the pointer the device sees is different from the pointer the host sees.
Definition Services.h:243
SerialCoordOutputData data
SerialCoordOutputHeader header