esiaccel 0.1.5.dev147__cp311-cp311-win_amd64.whl → 0.1.5.dev164__cp311-cp311-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of esiaccel might be problematic. Click here for more details.

esiaccel/CosimBackend.dll CHANGED
Binary file
Binary file
Binary file
esiaccel/MtiPli.dll CHANGED
Binary file
@@ -9,6 +9,8 @@
9
9
  // Package: Cosim_DpiPkg
10
10
  //
11
11
  // Main cosim <--> dpi bridge module.
12
+
13
+
12
14
  //
13
15
  //===----------------------------------------------------------------------===//
14
16
 
@@ -118,9 +120,8 @@ module Cosim_Endpoint_FromHost
118
120
  $error("Cosim endpoint (%s) register failed: %d", ENDPOINT_ID, rc);
119
121
  end
120
122
 
121
- /// *******************
122
- /// Data out management.
123
- ///
123
+ /// ***********************
124
+ /// Useful constants.
124
125
 
125
126
  localparam int FROM_HOST_SIZE_BYTES = int'((FROM_HOST_SIZE_BITS+7)/8);
126
127
  // The number of bits over a byte.
@@ -129,13 +130,30 @@ module Cosim_Endpoint_FromHost
129
130
  localparam int FROM_HOST_SIZE_BYTES_FLOOR_IN_BITS
130
131
  = FROM_HOST_SIZE_BYTES_FLOOR * 8;
131
132
 
133
+ // Buffer to hold incoming data directly from the DPI calls.
132
134
  byte unsigned DataOutBuffer[FROM_HOST_SIZE_BYTES-1:0];
135
+
136
+ // Pipeline interface signals for buffering DataOut.
137
+ // DataOut_a_valid is asserted when a complete message is available in
138
+ // DataOut_a buffer and waiting to be accepted by the skid buffer.
139
+ logic DataOut_a_valid;
140
+ // Packed representation of the byte buffer to feed the skid input.
141
+ logic [FROM_HOST_SIZE_BITS-1:0] DataOut_a;
142
+ // Ready/valid wires between this module and the skid buffer.
143
+ wire DataOut_a_ready;
144
+ wire DataOut_x_valid;
145
+ wire [FROM_HOST_SIZE_BITS-1:0] DataOut_x;
146
+
133
147
  always @(posedge clk) begin
134
148
  if (~rst) begin
135
- if (DataOutValid && DataOutReady) // A transfer occurred.
136
- DataOutValid <= 1'b0;
137
-
138
- if (!DataOutValid || DataOutReady) begin
149
+ // If the skid buffer accepted the input token this cycle, clear the
150
+ // internal valid that indicates we have buffered data.
151
+ if (DataOut_a_valid && DataOut_a_ready)
152
+ DataOut_a_valid <= 1'b0;
153
+
154
+ // Only attempt to fetch data from the host when the skid buffer can
155
+ // accept it (DataOut_a_ready).
156
+ if (!DataOut_a_valid && DataOut_a_ready) begin
139
157
  int data_limit;
140
158
  int rc;
141
159
 
@@ -149,7 +167,7 @@ module Cosim_Endpoint_FromHost
149
167
  ENDPOINT_ID, FROM_HOST_SIZE_BYTES, data_limit, rc);
150
168
  end else if (rc == 0) begin
151
169
  if (data_limit == FROM_HOST_SIZE_BYTES)
152
- DataOutValid <= 1'b1;
170
+ DataOut_a_valid <= 1'b1;
153
171
  else if (data_limit == 0)
154
172
  begin end // No message.
155
173
  else
@@ -159,24 +177,53 @@ module Cosim_Endpoint_FromHost
159
177
  end
160
178
  end
161
179
  end else begin
162
- DataOutValid <= 1'b0;
180
+ DataOut_a_valid <= 1'b0;
163
181
  end
164
182
  end
165
183
 
166
- // Assign packed output bit array from unpacked byte array.
184
+ // Pack the byte array into a single vector that will be handed to the
185
+ // skid buffer as its input payload.
167
186
  genvar iOut;
168
187
  generate
169
188
  for (iOut=0; iOut<FROM_HOST_SIZE_BYTES_FLOOR; iOut++)
170
- assign DataOut[((iOut+1)*8)-1:iOut*8] = DataOutBuffer[iOut];
189
+ assign DataOut_a[((iOut+1)*8)-1:iOut*8] = DataOutBuffer[iOut];
171
190
  if (FROM_HOST_SIZE_BITS_DIFF != 0)
172
- // If the type is not a multiple of 8, we've got to copy the extra bits.
173
- assign DataOut[(FROM_HOST_SIZE_BYTES_FLOOR_IN_BITS +
174
- FROM_HOST_SIZE_BITS_DIFF - 1) :
175
- FROM_HOST_SIZE_BYTES_FLOOR_IN_BITS]
191
+ // If the type is not a multiple of 8, copy the extra bits.
192
+ assign DataOut_a[(FROM_HOST_SIZE_BYTES_FLOOR_IN_BITS +
193
+ FROM_HOST_SIZE_BITS_DIFF - 1) :
194
+ FROM_HOST_SIZE_BYTES_FLOOR_IN_BITS]
176
195
  = DataOutBuffer[FROM_HOST_SIZE_BYTES - 1]
177
196
  [FROM_HOST_SIZE_BITS_DIFF - 1 : 0];
178
197
  endgenerate
179
198
 
199
+ /// *******************
200
+ /// Data out management.
201
+ ///
202
+ /// It has been observed that some simulators (verilator) does not handle
203
+ /// combinational driving from DPI well (resulting in non-determinism wrt
204
+ /// some of the combinational outputs being dropped/replicated). Questa does
205
+ /// not show this behavior.
206
+ /// A mitigation is to add a skid buffer to decouple the DPI interface
207
+ /// from the output interface.
208
+
209
+ // Instantiate a single-stage pipeline to buffer tokens that arrive from
210
+ // the host and present them to the module's output with proper
211
+ // ready/valid handshaking.
212
+ ESI_PipelineStage #(.WIDTH(FROM_HOST_SIZE_BITS)) out_pipe (
213
+ .clk(clk),
214
+ .rst(rst),
215
+ .a_valid(DataOut_a_valid),
216
+ .a(DataOut_a),
217
+ .a_ready(DataOut_a_ready),
218
+ .x_valid(DataOut_x_valid),
219
+ .x(DataOut_x),
220
+ .x_ready(DataOutReady)
221
+ );
222
+
223
+ // Drive the module's outward-facing signals from the pipeline output.
224
+ assign DataOutValid = DataOut_x_valid;
225
+ assign DataOut = DataOut_x;
226
+
180
227
  initial begin
181
228
  $display("FROM_HOST_SIZE_BITS: %d", FROM_HOST_SIZE_BITS);
182
229
  $display("FROM_HOST_SIZE_BYTES: %d", FROM_HOST_SIZE_BYTES);
@@ -0,0 +1,78 @@
1
+ # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2
+ # See https://llvm.org/LICENSE.txt for license information.
3
+ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import List
8
+
9
+ from .simulator import CosimCollateralDir, Simulator
10
+
11
+
12
+ class Questa(Simulator):
13
+ """Run and compile funcs for Questasim."""
14
+
15
+ DefaultDriver = CosimCollateralDir / "driver.sv"
16
+
17
+ # Questa doesn't use stderr for error messages. Everything goes to stdout.
18
+ UsesStderr = False
19
+
20
+ def internal_compile_commands(self) -> List[str]:
21
+ cmds = [
22
+ "onerror { quit -f -code 1 }",
23
+ ]
24
+ sources = self.sources.rtl_sources
25
+ sources.append(Questa.DefaultDriver)
26
+ for src in sources:
27
+ cmds.append(f"vlog -incr +acc -sv +define+TOP_MODULE={self.sources.top}"
28
+ f" +define+SIMULATION {str(src)}")
29
+ cmds.append(f"vopt -incr driver -o driver_opt +acc")
30
+ return cmds
31
+
32
+ def compile_commands(self) -> List[List[str]]:
33
+ with open("compile.do", "w") as f:
34
+ for cmd in self.internal_compile_commands():
35
+ f.write(cmd)
36
+ f.write("\n")
37
+ f.write("quit\n")
38
+ return [
39
+ ["vsim", "-batch", "-do", "compile.do"],
40
+ ]
41
+
42
+ def run_command(self, gui: bool) -> List[str]:
43
+ vsim = "vsim"
44
+ # Note: vsim exit codes say nothing about the test run's pass/fail even
45
+ # if $fatal is encountered in the simulation.
46
+ if gui:
47
+ cmd = [
48
+ vsim,
49
+ "driver_opt",
50
+ ]
51
+ else:
52
+ cmd = [
53
+ vsim,
54
+ "driver_opt",
55
+ "-batch",
56
+ "-do",
57
+ "run -all",
58
+ ]
59
+ for lib in self.sources.dpi_so_paths():
60
+ svLib = os.path.splitext(lib)[0]
61
+ cmd.append("-sv_lib")
62
+ cmd.append(svLib)
63
+ return cmd
64
+
65
+ def run(self,
66
+ inner_command: str,
67
+ gui: bool = False,
68
+ server_only: bool = False) -> int:
69
+ """Override the Simulator.run() to add a soft link in the run directory (to
70
+ the work directory) before running vsim the usual way."""
71
+
72
+ # Create a soft link to the work directory.
73
+ workDir = self.run_dir / "work"
74
+ if not workDir.exists():
75
+ os.symlink(Path(os.getcwd()) / "work", workDir)
76
+
77
+ # Run the simulation.
78
+ return super().run(inner_command, gui, server_only=server_only)
@@ -0,0 +1,228 @@
1
+ # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2
+ # See https://llvm.org/LICENSE.txt for license information.
3
+ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
+
5
+ import os
6
+ import re
7
+ import signal
8
+ import socket
9
+ import subprocess
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Dict, List
13
+
14
+ _thisdir = Path(__file__).parent
15
+ CosimCollateralDir = _thisdir
16
+
17
+
18
+ def is_port_open(port) -> bool:
19
+ """Check if a TCP port is open locally."""
20
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
21
+ result = sock.connect_ex(('127.0.0.1', port))
22
+ sock.close()
23
+ return True if result == 0 else False
24
+
25
+
26
+ class SourceFiles:
27
+
28
+ def __init__(self, top: str) -> None:
29
+ # User source files.
30
+ self.user: List[Path] = []
31
+ # DPI shared objects.
32
+ self.dpi_so: List[str] = ["EsiCosimDpiServer"]
33
+ # DPI SV files.
34
+ self.dpi_sv: List[Path] = [
35
+ CosimCollateralDir / "Cosim_DpiPkg.sv",
36
+ CosimCollateralDir / "Cosim_Endpoint.sv",
37
+ CosimCollateralDir / "Cosim_Manifest.sv",
38
+ ]
39
+ # Name of the top module.
40
+ self.top = top
41
+
42
+ def add_dir(self, dir: Path):
43
+ """Add all the RTL files in a directory to the source list."""
44
+ for file in sorted(dir.iterdir()):
45
+ if file.is_file() and (file.suffix == ".sv" or file.suffix == ".v"):
46
+ self.user.append(file)
47
+ elif file.is_dir():
48
+ self.add_dir(file)
49
+
50
+ def dpi_so_paths(self) -> List[Path]:
51
+ """Return a list of all the DPI shared object files."""
52
+
53
+ def find_so(name: str) -> Path:
54
+ for path in Simulator.get_env().get("LD_LIBRARY_PATH", "").split(":"):
55
+ if os.name == "nt":
56
+ so = Path(path) / f"{name}.dll"
57
+ else:
58
+ so = Path(path) / f"lib{name}.so"
59
+ if so.exists():
60
+ return so
61
+ raise FileNotFoundError(f"Could not find {name}.so in LD_LIBRARY_PATH")
62
+
63
+ return [find_so(name) for name in self.dpi_so]
64
+
65
+ @property
66
+ def rtl_sources(self) -> List[Path]:
67
+ """Return a list of all the RTL source files."""
68
+ return self.dpi_sv + self.user
69
+
70
+
71
+ class SimProcess:
72
+
73
+ def __init__(self, proc: subprocess.Popen, port: int):
74
+ self.proc = proc
75
+ self.port = port
76
+
77
+ def force_stop(self):
78
+ """Make sure to stop the simulation no matter what."""
79
+ if self.proc:
80
+ os.killpg(os.getpgid(self.proc.pid), signal.SIGINT)
81
+ # Allow the simulation time to flush its outputs.
82
+ try:
83
+ self.proc.wait(timeout=1.0)
84
+ except subprocess.TimeoutExpired:
85
+ # If the simulation doesn't exit of its own free will, kill it.
86
+ self.proc.kill()
87
+
88
+
89
+ class Simulator:
90
+
91
+ # Some RTL simulators don't use stderr for error messages. Everything goes to
92
+ # stdout. Boo! They should feel bad about this. Also, they can specify that
93
+ # broken behavior by overriding this.
94
+ UsesStderr = True
95
+
96
+ def __init__(self, sources: SourceFiles, run_dir: Path, debug: bool):
97
+ self.sources = sources
98
+ self.run_dir = run_dir
99
+ self.debug = debug
100
+
101
+ @staticmethod
102
+ def get_env() -> Dict[str, str]:
103
+ """Get the environment variables to locate shared objects."""
104
+
105
+ env = os.environ.copy()
106
+ env["LIBRARY_PATH"] = env.get("LIBRARY_PATH", "") + ":" + str(
107
+ _thisdir.parent / "lib")
108
+ env["LD_LIBRARY_PATH"] = env.get("LD_LIBRARY_PATH", "") + ":" + str(
109
+ _thisdir.parent / "lib")
110
+ return env
111
+
112
+ def compile_commands(self) -> List[List[str]]:
113
+ """Compile the sources. Returns the exit code of the simulation compiler."""
114
+ assert False, "Must be implemented by subclass"
115
+
116
+ def compile(self) -> int:
117
+ cmds = self.compile_commands()
118
+ self.run_dir.mkdir(parents=True, exist_ok=True)
119
+ with (self.run_dir / "compile_stdout.log").open("w") as stdout, (
120
+ self.run_dir / "compile_stderr.log").open("w") as stderr:
121
+ for cmd in cmds:
122
+ stderr.write(" ".join(cmd) + "\n")
123
+ cp = subprocess.run(cmd,
124
+ env=Simulator.get_env(),
125
+ capture_output=True,
126
+ text=True)
127
+ stdout.write(cp.stdout)
128
+ stderr.write(cp.stderr)
129
+ if cp.returncode != 0:
130
+ print("====== Compilation failure:")
131
+ if self.UsesStderr:
132
+ print(cp.stderr)
133
+ else:
134
+ print(cp.stdout)
135
+ return cp.returncode
136
+ return 0
137
+
138
+ def run_command(self, gui: bool) -> List[str]:
139
+ """Return the command to run the simulation."""
140
+ assert False, "Must be implemented by subclass"
141
+
142
+ def run_proc(self, gui: bool = False) -> SimProcess:
143
+ """Run the simulation process. Returns the Popen object and the port which
144
+ the simulation is listening on."""
145
+ # Open log files
146
+ self.run_dir.mkdir(parents=True, exist_ok=True)
147
+ simStdout = open(self.run_dir / "sim_stdout.log", "w")
148
+ simStderr = open(self.run_dir / "sim_stderr.log", "w")
149
+
150
+ # Erase the config file if it exists. We don't want to read
151
+ # an old config.
152
+ portFileName = self.run_dir / "cosim.cfg"
153
+ if os.path.exists(portFileName):
154
+ os.remove(portFileName)
155
+
156
+ # Run the simulation.
157
+ simEnv = Simulator.get_env()
158
+ if self.debug:
159
+ simEnv["COSIM_DEBUG_FILE"] = "cosim_debug.log"
160
+ if "DEBUG_PERIOD" not in simEnv:
161
+ # Slow the simulation down to one tick per millisecond.
162
+ simEnv["DEBUG_PERIOD"] = "1"
163
+ rcmd = self.run_command(gui)
164
+ simProc = subprocess.Popen(self.run_command(gui),
165
+ stdout=simStdout,
166
+ stderr=simStderr,
167
+ env=simEnv,
168
+ cwd=self.run_dir,
169
+ preexec_fn=os.setsid)
170
+ simStderr.close()
171
+ simStdout.close()
172
+
173
+ # Get the port which the simulation RPC selected.
174
+ checkCount = 0
175
+ while (not os.path.exists(portFileName)) and \
176
+ simProc.poll() is None:
177
+ time.sleep(0.1)
178
+ checkCount += 1
179
+ if checkCount > 500 and not gui:
180
+ raise Exception(f"Cosim never wrote cfg file: {portFileName}")
181
+ port = -1
182
+ while port < 0:
183
+ portFile = open(portFileName, "r")
184
+ for line in portFile.readlines():
185
+ m = re.match("port: (\\d+)", line)
186
+ if m is not None:
187
+ port = int(m.group(1))
188
+ portFile.close()
189
+
190
+ # Wait for the simulation to start accepting RPC connections.
191
+ checkCount = 0
192
+ while not is_port_open(port):
193
+ checkCount += 1
194
+ if checkCount > 200:
195
+ raise Exception(f"Cosim RPC port ({port}) never opened")
196
+ if simProc.poll() is not None:
197
+ raise Exception("Simulation exited early")
198
+ time.sleep(0.05)
199
+ return SimProcess(proc=simProc, port=port)
200
+
201
+ def run(self,
202
+ inner_command: str,
203
+ gui: bool = False,
204
+ server_only: bool = False) -> int:
205
+ """Start the simulation then run the command specified. Kill the simulation
206
+ when the command exits."""
207
+
208
+ # 'simProc' is accessed in the finally block. Declare it here to avoid
209
+ # syntax errors in that block.
210
+ simProc = None
211
+ try:
212
+ simProc = self.run_proc(gui=gui)
213
+ if server_only:
214
+ # wait for user input to kill the server
215
+ input(
216
+ f"Running in server-only mode on port {simProc.port} - Press anything to kill the server..."
217
+ )
218
+ return 0
219
+ else:
220
+ # Run the inner command, passing the connection info via environment vars.
221
+ testEnv = os.environ.copy()
222
+ testEnv["ESI_COSIM_PORT"] = str(simProc.port)
223
+ testEnv["ESI_COSIM_HOST"] = "localhost"
224
+ return subprocess.run(inner_command, cwd=os.getcwd(),
225
+ env=testEnv).returncode
226
+ finally:
227
+ if simProc:
228
+ simProc.force_stop()
@@ -0,0 +1,61 @@
1
+ # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2
+ # See https://llvm.org/LICENSE.txt for license information.
3
+ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from typing import List
8
+
9
+ from .simulator import CosimCollateralDir, Simulator, SourceFiles
10
+
11
+
12
+ class Verilator(Simulator):
13
+ """Run and compile funcs for Verilator."""
14
+
15
+ DefaultDriver = CosimCollateralDir / "driver.cpp"
16
+
17
+ def __init__(self, sources: SourceFiles, run_dir: Path, debug: bool):
18
+ super().__init__(sources, run_dir, debug)
19
+
20
+ self.verilator = "verilator"
21
+ if "VERILATOR_PATH" in os.environ:
22
+ self.verilator = os.environ["VERILATOR_PATH"]
23
+
24
+ def compile_commands(self) -> List[List[str]]:
25
+ cmd: List[str] = [
26
+ self.verilator,
27
+ "--cc",
28
+ "--top-module",
29
+ self.sources.top,
30
+ "-DSIMULATION",
31
+ "-Wno-TIMESCALEMOD",
32
+ "-Wno-fatal",
33
+ "-sv",
34
+ "--exe",
35
+ "--build",
36
+ "-j",
37
+ "0",
38
+ "--output-split",
39
+ "--assert",
40
+ str(Verilator.DefaultDriver),
41
+ ]
42
+ cflags = [
43
+ "-DTOP_MODULE=" + self.sources.top,
44
+ ]
45
+ if self.debug:
46
+ cmd += [
47
+ "--trace", "--trace-params", "--trace-structs", "--trace-underscore"
48
+ ]
49
+ cflags.append("-DTRACE")
50
+ if len(cflags) > 0:
51
+ cmd += ["-CFLAGS", " ".join(cflags)]
52
+ if len(self.sources.dpi_so) > 0:
53
+ cmd += ["-LDFLAGS", " ".join(["-l" + so for so in self.sources.dpi_so])]
54
+ cmd += [str(p) for p in self.sources.rtl_sources]
55
+ return [cmd]
56
+
57
+ def run_command(self, gui: bool):
58
+ if gui:
59
+ raise RuntimeError("Verilator does not support GUI mode.")
60
+ exe = Path.cwd() / "obj_dir" / ("V" + self.sources.top)
61
+ return [str(exe)]
esiaccel/esi-cosim.py CHANGED
@@ -14,350 +14,14 @@
14
14
  # ===----------------------------------------------------------------------===//
15
15
 
16
16
  import argparse
17
- import os
18
17
  from pathlib import Path
19
- import re
20
- import signal
21
- import socket
22
- import subprocess
23
18
  import sys
24
19
  import textwrap
25
- import time
26
20
  from typing import Dict, List
27
21
 
28
- _thisdir = Path(__file__).parent
29
- CosimCollateralDir = _thisdir.parent / "cosim"
30
-
31
-
32
- def is_port_open(port) -> bool:
33
- """Check if a TCP port is open locally."""
34
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
35
- result = sock.connect_ex(('127.0.0.1', port))
36
- sock.close()
37
- return True if result == 0 else False
38
-
39
-
40
- class SourceFiles:
41
-
42
- def __init__(self, top: str) -> None:
43
- # User source files.
44
- self.user: List[Path] = []
45
- # DPI shared objects.
46
- self.dpi_so: List[str] = ["EsiCosimDpiServer"]
47
- # DPI SV files.
48
- self.dpi_sv: List[Path] = [
49
- CosimCollateralDir / "Cosim_DpiPkg.sv",
50
- CosimCollateralDir / "Cosim_Endpoint.sv",
51
- CosimCollateralDir / "Cosim_Manifest.sv",
52
- ]
53
- # Name of the top module.
54
- self.top = top
55
-
56
- def add_dir(self, dir: Path):
57
- """Add all the RTL files in a directory to the source list."""
58
- for file in sorted(dir.iterdir()):
59
- if file.is_file() and (file.suffix == ".sv" or file.suffix == ".v"):
60
- self.user.append(file)
61
- elif file.is_dir():
62
- self.add_dir(file)
63
-
64
- def dpi_so_paths(self) -> List[Path]:
65
- """Return a list of all the DPI shared object files."""
66
-
67
- def find_so(name: str) -> Path:
68
- for path in Simulator.get_env().get("LD_LIBRARY_PATH", "").split(":"):
69
- if os.name == "nt":
70
- so = Path(path) / f"{name}.dll"
71
- else:
72
- so = Path(path) / f"lib{name}.so"
73
- if so.exists():
74
- return so
75
- raise FileNotFoundError(f"Could not find {name}.so in LD_LIBRARY_PATH")
76
-
77
- return [find_so(name) for name in self.dpi_so]
78
-
79
- @property
80
- def rtl_sources(self) -> List[Path]:
81
- """Return a list of all the RTL source files."""
82
- return self.dpi_sv + self.user
83
-
84
-
85
- class SimProcess:
86
-
87
- def __init__(self, proc: subprocess.Popen, port: int):
88
- self.proc = proc
89
- self.port = port
90
-
91
- def force_stop(self):
92
- """Make sure to stop the simulation no matter what."""
93
- if self.proc:
94
- os.killpg(os.getpgid(self.proc.pid), signal.SIGINT)
95
- # Allow the simulation time to flush its outputs.
96
- try:
97
- self.proc.wait(timeout=1.0)
98
- except subprocess.TimeoutExpired:
99
- # If the simulation doesn't exit of its own free will, kill it.
100
- self.proc.kill()
101
-
102
-
103
- class Simulator:
104
-
105
- # Some RTL simulators don't use stderr for error messages. Everything goes to
106
- # stdout. Boo! They should feel bad about this. Also, they can specify that
107
- # broken behavior by overriding this.
108
- UsesStderr = True
109
-
110
- def __init__(self, sources: SourceFiles, run_dir: Path, debug: bool):
111
- self.sources = sources
112
- self.run_dir = run_dir
113
- self.debug = debug
114
-
115
- @staticmethod
116
- def get_env() -> Dict[str, str]:
117
- """Get the environment variables to locate shared objects."""
118
-
119
- env = os.environ.copy()
120
- env["LIBRARY_PATH"] = env.get("LIBRARY_PATH", "") + ":" + str(
121
- _thisdir.parent / "lib")
122
- env["LD_LIBRARY_PATH"] = env.get("LD_LIBRARY_PATH", "") + ":" + str(
123
- _thisdir.parent / "lib")
124
- return env
125
-
126
- def compile_commands(self) -> List[List[str]]:
127
- """Compile the sources. Returns the exit code of the simulation compiler."""
128
- assert False, "Must be implemented by subclass"
129
-
130
- def compile(self) -> int:
131
- cmds = self.compile_commands()
132
- self.run_dir.mkdir(parents=True, exist_ok=True)
133
- with (self.run_dir / "compile_stdout.log").open("w") as stdout, (
134
- self.run_dir / "compile_stderr.log").open("w") as stderr:
135
- for cmd in cmds:
136
- stderr.write(" ".join(cmd) + "\n")
137
- cp = subprocess.run(cmd,
138
- env=Simulator.get_env(),
139
- capture_output=True,
140
- text=True)
141
- stdout.write(cp.stdout)
142
- stderr.write(cp.stderr)
143
- if cp.returncode != 0:
144
- print("====== Compilation failure:")
145
- if self.UsesStderr:
146
- print(cp.stderr)
147
- else:
148
- print(cp.stdout)
149
- return cp.returncode
150
- return 0
151
-
152
- def run_command(self, gui: bool) -> List[str]:
153
- """Return the command to run the simulation."""
154
- assert False, "Must be implemented by subclass"
155
-
156
- def run_proc(self, gui: bool = False) -> SimProcess:
157
- """Run the simulation process. Returns the Popen object and the port which
158
- the simulation is listening on."""
159
- # Open log files
160
- self.run_dir.mkdir(parents=True, exist_ok=True)
161
- simStdout = open(self.run_dir / "sim_stdout.log", "w")
162
- simStderr = open(self.run_dir / "sim_stderr.log", "w")
163
-
164
- # Erase the config file if it exists. We don't want to read
165
- # an old config.
166
- portFileName = self.run_dir / "cosim.cfg"
167
- if os.path.exists(portFileName):
168
- os.remove(portFileName)
169
-
170
- # Run the simulation.
171
- simEnv = Simulator.get_env()
172
- if self.debug:
173
- simEnv["COSIM_DEBUG_FILE"] = "cosim_debug.log"
174
- if "DEBUG_PERIOD" not in simEnv:
175
- # Slow the simulation down to one tick per millisecond.
176
- simEnv["DEBUG_PERIOD"] = "1"
177
- rcmd = self.run_command(gui)
178
- simProc = subprocess.Popen(self.run_command(gui),
179
- stdout=simStdout,
180
- stderr=simStderr,
181
- env=simEnv,
182
- cwd=self.run_dir,
183
- preexec_fn=os.setsid)
184
- simStderr.close()
185
- simStdout.close()
186
-
187
- # Get the port which the simulation RPC selected.
188
- checkCount = 0
189
- while (not os.path.exists(portFileName)) and \
190
- simProc.poll() is None:
191
- time.sleep(0.1)
192
- checkCount += 1
193
- if checkCount > 500 and not gui:
194
- raise Exception(f"Cosim never wrote cfg file: {portFileName}")
195
- port = -1
196
- while port < 0:
197
- portFile = open(portFileName, "r")
198
- for line in portFile.readlines():
199
- m = re.match("port: (\\d+)", line)
200
- if m is not None:
201
- port = int(m.group(1))
202
- portFile.close()
203
-
204
- # Wait for the simulation to start accepting RPC connections.
205
- checkCount = 0
206
- while not is_port_open(port):
207
- checkCount += 1
208
- if checkCount > 200:
209
- raise Exception(f"Cosim RPC port ({port}) never opened")
210
- if simProc.poll() is not None:
211
- raise Exception("Simulation exited early")
212
- time.sleep(0.05)
213
- return SimProcess(proc=simProc, port=port)
214
-
215
- def run(self,
216
- inner_command: str,
217
- gui: bool = False,
218
- server_only: bool = False) -> int:
219
- """Start the simulation then run the command specified. Kill the simulation
220
- when the command exits."""
221
-
222
- # 'simProc' is accessed in the finally block. Declare it here to avoid
223
- # syntax errors in that block.
224
- simProc = None
225
- try:
226
- simProc = self.run_proc(gui=gui)
227
- if server_only:
228
- # wait for user input to kill the server
229
- input(
230
- f"Running in server-only mode on port {simProc.port} - Press anything to kill the server..."
231
- )
232
- return 0
233
- else:
234
- # Run the inner command, passing the connection info via environment vars.
235
- testEnv = os.environ.copy()
236
- testEnv["ESI_COSIM_PORT"] = str(simProc.port)
237
- testEnv["ESI_COSIM_HOST"] = "localhost"
238
- return subprocess.run(inner_command, cwd=os.getcwd(),
239
- env=testEnv).returncode
240
- finally:
241
- if simProc:
242
- simProc.force_stop()
243
-
244
-
245
- class Verilator(Simulator):
246
- """Run and compile funcs for Verilator."""
247
-
248
- DefaultDriver = CosimCollateralDir / "driver.cpp"
249
-
250
- def __init__(self, sources: SourceFiles, run_dir: Path, debug: bool):
251
- super().__init__(sources, run_dir, debug)
252
-
253
- self.verilator = "verilator"
254
- if "VERILATOR_PATH" in os.environ:
255
- self.verilator = os.environ["VERILATOR_PATH"]
256
-
257
- def compile_commands(self) -> List[List[str]]:
258
- cmd: List[str] = [
259
- self.verilator,
260
- "--cc",
261
- "--top-module",
262
- self.sources.top,
263
- "-DSIMULATION",
264
- "-Wno-TIMESCALEMOD",
265
- "-Wno-fatal",
266
- "-sv",
267
- "--build",
268
- "--exe",
269
- "--assert",
270
- str(Verilator.DefaultDriver),
271
- ]
272
- cflags = [
273
- "-DTOP_MODULE=" + self.sources.top,
274
- ]
275
- if self.debug:
276
- cmd += [
277
- "--trace", "--trace-params", "--trace-structs", "--trace-underscore"
278
- ]
279
- cflags.append("-DTRACE")
280
- if len(cflags) > 0:
281
- cmd += ["-CFLAGS", " ".join(cflags)]
282
- if len(self.sources.dpi_so) > 0:
283
- cmd += ["-LDFLAGS", " ".join(["-l" + so for so in self.sources.dpi_so])]
284
- cmd += [str(p) for p in self.sources.rtl_sources]
285
- return [cmd]
286
-
287
- def run_command(self, gui: bool):
288
- if gui:
289
- raise RuntimeError("Verilator does not support GUI mode.")
290
- exe = Path.cwd() / "obj_dir" / ("V" + self.sources.top)
291
- return [str(exe)]
292
-
293
-
294
- class Questa(Simulator):
295
- """Run and compile funcs for Questasim."""
296
-
297
- DefaultDriver = CosimCollateralDir / "driver.sv"
298
-
299
- # Questa doesn't use stderr for error messages. Everything goes to stdout.
300
- UsesStderr = False
301
-
302
- def internal_compile_commands(self) -> List[str]:
303
- cmds = [
304
- "onerror { quit -f -code 1 }",
305
- ]
306
- sources = self.sources.rtl_sources
307
- sources.append(Questa.DefaultDriver)
308
- for src in sources:
309
- cmds.append(f"vlog -incr +acc -sv +define+TOP_MODULE={self.sources.top}"
310
- f" +define+SIMULATION {str(src)}")
311
- cmds.append(f"vopt -incr driver -o driver_opt +acc")
312
- return cmds
313
-
314
- def compile_commands(self) -> List[List[str]]:
315
- with open("compile.do", "w") as f:
316
- for cmd in self.internal_compile_commands():
317
- f.write(cmd)
318
- f.write("\n")
319
- f.write("quit\n")
320
- return [
321
- ["vsim", "-batch", "-do", "compile.do"],
322
- ]
323
-
324
- def run_command(self, gui: bool) -> List[str]:
325
- vsim = "vsim"
326
- # Note: vsim exit codes say nothing about the test run's pass/fail even
327
- # if $fatal is encountered in the simulation.
328
- if gui:
329
- cmd = [
330
- vsim,
331
- "driver_opt",
332
- ]
333
- else:
334
- cmd = [
335
- vsim,
336
- "driver_opt",
337
- "-batch",
338
- "-do",
339
- "run -all",
340
- ]
341
- for lib in self.sources.dpi_so_paths():
342
- svLib = os.path.splitext(lib)[0]
343
- cmd.append("-sv_lib")
344
- cmd.append(svLib)
345
- return cmd
346
-
347
- def run(self,
348
- inner_command: str,
349
- gui: bool = False,
350
- server_only: bool = False) -> int:
351
- """Override the Simulator.run() to add a soft link in the run directory (to
352
- the work directory) before running vsim the usual way."""
353
-
354
- # Create a soft link to the work directory.
355
- workDir = self.run_dir / "work"
356
- if not workDir.exists():
357
- os.symlink(Path(os.getcwd()) / "work", workDir)
358
-
359
- # Run the simulation.
360
- return super().run(inner_command, gui, server_only=server_only)
22
+ from esiaccel.cosim.questa import Questa
23
+ from esiaccel.cosim.verilator import Verilator
24
+ from esiaccel.cosim.simulator import SourceFiles
361
25
 
362
26
 
363
27
  def __main__(args):
Binary file
esiaccel/esiquery.exe CHANGED
Binary file
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: esiaccel
3
- Version: 0.1.5.dev147
3
+ Version: 0.1.5.dev164
4
4
  Summary: ESI accelerators runtime
5
5
  Author-email: John Demme <John.Demme@microsoft.com>
6
6
  License: ==============================================================================
@@ -1,25 +1,28 @@
1
- esiaccel/CosimBackend.dll,sha256=IL1XoD-Z8zQ1ZjK7X8XBP42rHowpxIa2xRKYf-R7I8k,7152128
1
+ esiaccel/CosimBackend.dll,sha256=pVZhWoNUMgZNnY8LCShcT1Sqst9nQRyizrb2i2fjq14,7152128
2
2
  esiaccel/CosimBackend.lib,sha256=UjflmgR93Kl22Du0lTqGhXWQqWEF-V8VwcqUuFo8GNk,4992924
3
- esiaccel/ESICppRuntime.dll,sha256=cnbfx7k4jo8RHd_1uGRfeauE5xLD1fcrKCLM5JYTDxI,4078592
3
+ esiaccel/ESICppRuntime.dll,sha256=w_UDjb258Zl0TU1mEBnTGRkr6bdhYSMu1-FUReTn0uQ,4078592
4
4
  esiaccel/ESICppRuntime.lib,sha256=iGJtktQywYhQCody90jvprSYC7kB9LWt3LEX5yIGEkM,15154004
5
- esiaccel/EsiCosimDpiServer.dll,sha256=Fj2803pwpUP9-WYlAR5yE6936dXdR50gNcJgMlPocxo,159744
5
+ esiaccel/EsiCosimDpiServer.dll,sha256=xktLQ4-xOA688Du5D07q6BrAEr7wqpW60z7Stjfn2Wk,159744
6
6
  esiaccel/EsiCosimDpiServer.lib,sha256=bYBigD0RtRRSEiDxf4_gvpasLjD8fcUmC0CjRgQiQ0s,604164
7
- esiaccel/MtiPli.dll,sha256=cOA9Yf66yJvYF5NigtBAj8YvcMeOjWSy3c-A1XJvdso,14848
7
+ esiaccel/MtiPli.dll,sha256=gQnnnRHOA7_70UeRxqrjeXuH-w1ppBV82D05JmQnOv0,14848
8
8
  esiaccel/MtiPli.lib,sha256=X0PcXwheCUvBMgQ5BAawePxbXQSLNk5M1FFn6V56ydo,14570
9
9
  esiaccel/__init__.py,sha256=65xXWHwJwRePsyhWk837NpzuN0qsNhoAX29TOiSYKGc,905
10
10
  esiaccel/accelerator.py,sha256=BcXPsUqcQV3YsVVyYbz9P6JnZLlcnuageFbJwID9_3s,3318
11
11
  esiaccel/codegen.py,sha256=uoYELtnIabVvgLeCABj-mWras0BvmSKABPH-cd9nDFk,6560
12
- esiaccel/esi-cosim.py,sha256=JHPgS6jjC655afz7pNBh47cAjyRTiqMKRM3tCsszYM4,14796
13
- esiaccel/esiCppAccel.cp311-win_amd64.pyd,sha256=2yMe1ow3wydK8BqZgc8gDtorgIteCc0oap1jt8J98SE,502272
14
- esiaccel/esiquery.exe,sha256=mQ2O-o3mOEFhCCpzp7XUt7-Kd8fhrl6O3YodRPO8nyk,441856
12
+ esiaccel/esi-cosim.py,sha256=P7n3SBgKPnXynwghY5zK1FmpqZkbC_YxfVIvNNQNl6Q,3817
13
+ esiaccel/esiCppAccel.cp311-win_amd64.pyd,sha256=EBeBmtCdIUKEVjq9YKLDSxZytsKoGdKLKlhUdqQ90-E,502272
14
+ esiaccel/esiquery.exe,sha256=l46J-YKhec1EfdEpuVbQ74KMj-kpdxEMGd8OQFh1FXM,441856
15
15
  esiaccel/types.py,sha256=LFLzUCvtYF6FLsmKet6eJTMq2ija2Z5kxd5Ks6tkS4U,19044
16
16
  esiaccel/utils.py,sha256=q-8fmgJ9tUvmBsIvqZiZ7u845IJhOjvjYTQLhhrNYl0,1515
17
17
  esiaccel/cmake/esiaccelConfig.cmake,sha256=u2aW99k1lEcmYTG1P3BTJqtmDrj53wUUaBz_jzw8kYY,565
18
18
  esiaccel/cosim/Cosim_DpiPkg.sv,sha256=9qGn1VyAVrzBP5At1thV6xrovg0WghICD01Zz9J221E,3458
19
- esiaccel/cosim/Cosim_Endpoint.sv,sha256=ri1fHdkiphe8S2-vm6Ru16rBGYiDiS1c8qeCAsl1diU,6498
19
+ esiaccel/cosim/Cosim_Endpoint.sv,sha256=2F7UQYWavUlWx7Iqi_6iawn5geZRPG96H8rDBBDRAQ0,8391
20
20
  esiaccel/cosim/Cosim_Manifest.sv,sha256=vl9b6XieEkP880IBw1ferekBnDJwFanZZggJJGertXM,1123
21
21
  esiaccel/cosim/driver.cpp,sha256=DrEKkSN7Y_Hu7wcaUulH5mbC2L4yB9xLClRMeRUpzHM,3842
22
22
  esiaccel/cosim/driver.sv,sha256=ro-j9GM164A1W0MDPkqYfEn3TUKHSqVvgjO31fnloQI,1428
23
+ esiaccel/cosim/questa.py,sha256=d6PnjzRxQpu47Zpez6hmzTc_aMQdrmQRSmnpOXSPFVU,2386
24
+ esiaccel/cosim/simulator.py,sha256=Yv5PeWDmhsgATDEy-P3drFgXNEaALOlMInsFvsiGy4c,7864
25
+ esiaccel/cosim/verilator.py,sha256=BwCJWLlMOPD_JZyjOoLGUW48-IIndtbj55D2kRvL1l4,1834
23
26
  esiaccel/include/esi/Accelerator.h,sha256=RhkZ2HeMZ0iHc5BkHdDWXoeg9J9lyPQciH5bWq5Qc_w,9772
24
27
  esiaccel/include/esi/CLI.h,sha256=Nn8tHn_xtEfkrD7USE2tao6ktYOJ6xcbnhZkS9-ox0A,2540
25
28
  esiaccel/include/esi/Common.h,sha256=IGJvAU72dlearXFbSmlXFFriy8aomirp7opEBjgewek,5775
@@ -35,9 +38,9 @@ esiaccel/include/esi/Utils.h,sha256=KPd75GajIFeTBVJocXBjwsJqhbZg-ShWZCIe3oQdBss,
35
38
  esiaccel/include/esi/backends/Cosim.h,sha256=s7vYd0ra6m1nvk-n37MjvBoGVI-CCUKBt0DU4PKlaHM,2838
36
39
  esiaccel/include/esi/backends/RpcServer.h,sha256=WMwnhwU2qnrcglGNeiKg9QQHpkDx1QE1JydKYDK4jqE,1856
37
40
  esiaccel/include/esi/backends/Trace.h,sha256=kx4wwLH3a0ndmRUdaDyYGZ1SP83zlpFrk30Nw8ZrJJA,3286
38
- esiaccel-0.1.5.dev147.dist-info/licenses/LICENSE,sha256=vtnVnB8_lN1yPYcA5MeT56R8UsQtBhyzZLBvu_KMf7I,13468
39
- esiaccel-0.1.5.dev147.dist-info/METADATA,sha256=oxZUJ15Qr6eLJeMDWCKVnCncAT1a9lAyqNFBrqKtzys,16148
40
- esiaccel-0.1.5.dev147.dist-info/WHEEL,sha256=JLOMsP7F5qtkAkINx5UnzbFguf8CqZeraV8o04b0I8I,101
41
- esiaccel-0.1.5.dev147.dist-info/entry_points.txt,sha256=_CuNLV0fyTURxRREFwpzGycifZW_-7-MyuJNEwKK9J8,137
42
- esiaccel-0.1.5.dev147.dist-info/top_level.txt,sha256=fYWTWMDK4PDu4ePQ9NtcFHas2k8-d1kWhTs2avPpgB4,9
43
- esiaccel-0.1.5.dev147.dist-info/RECORD,,
41
+ esiaccel-0.1.5.dev164.dist-info/licenses/LICENSE,sha256=vtnVnB8_lN1yPYcA5MeT56R8UsQtBhyzZLBvu_KMf7I,13468
42
+ esiaccel-0.1.5.dev164.dist-info/METADATA,sha256=5jOaDY4vSlfnWCgt5XqVyfrY_S1jfzgoyO6pRfl6fq8,16148
43
+ esiaccel-0.1.5.dev164.dist-info/WHEEL,sha256=JLOMsP7F5qtkAkINx5UnzbFguf8CqZeraV8o04b0I8I,101
44
+ esiaccel-0.1.5.dev164.dist-info/entry_points.txt,sha256=_CuNLV0fyTURxRREFwpzGycifZW_-7-MyuJNEwKK9J8,137
45
+ esiaccel-0.1.5.dev164.dist-info/top_level.txt,sha256=fYWTWMDK4PDu4ePQ9NtcFHas2k8-d1kWhTs2avPpgB4,9
46
+ esiaccel-0.1.5.dev164.dist-info/RECORD,,