Debian Codegraph @

legacy/tiled_fuzzer.py

raw symbols SCIP
1 import re
2 import os
3 import sys
4 import copy
5 import tempfile
6 import subprocess
7 from pathlib import Path
8 from collections import deque, Counter, namedtuple
9 from itertools import chain, count, zip_longest
10 from functools import reduce
11 from random import shuffle, seed
12 from warnings import warn
13 from math import factorial
14 from multiprocessing.dummy import Pool
15 import pickle
16 from shutil import copytree
17
18 from apycula import codegen
19 from apycula import bslib
20 from apycula import pindef
21 from apycula import fse_parser
22 from apycula import wirenames as wnames
23 from apycula import dat_parser
24 from apycula import tm_parser
25 from apycula import chipdb
26 from apycula import attrids
27
28 gowinhome = os.getenv("GOWINHOME")
29 if not gowinhome:
30 raise Exception("GOWINHOME not set")
31 gowin_debug = os.getenv("GOWIN_DEBUG")
32
33 # device = os.getenv("DEVICE")
34 device = sys.argv[1]
35 params = {
36 "GW1NS-4": {
37 "package": "QFN48P",
38 "device": "GW1NSR-4C",
39 "partnumber": "GW1NSR-LV4CQN48PC7/I6",
40 },
41 "GW1N-9": {
42 "package": "PBGA256",
43 "device": "GW1N-9",
44 "partnumber": "GW1N-LV9PG256C6/I5",
45 },
46 "GW1N-9C": {
47 "package": "QFN88P",
48 "device": "GW1NR-9C",
49 "partnumber": "GW1NR-LV9QN88PC6/I5",
50 },
51 "GW1N-4": {
52 "package": "PBGA256",
53 "device": "GW1N-4",
54 "partnumber": "GW1N-LV4PG256C6/I5",
55 },
56 "GW1N-1P5C": {
57 "package": "QFN48XF",
58 "device": "GW1N-1P5C",
59 "partnumber": "GW1N-UV1P5QN48XFC7/I6",
60 },
61 "GW1N-1": {
62 "package": "LQFP144",
63 "device": "GW1N-1",
64 "partnumber": "GW1N-LV1LQ144C6/I5",
65 },
66 "GW1NZ-1": {
67 "package": "QFN48",
68 "device": "GW1NZ-1",
69 "partnumber": "GW1NZ-LV1QN48C6/I5",
70 },
71 "GW2A-18": {
72 "package": "PBGA256",
73 "device": "GW2A-18",
74 "partnumber": "GW2A-LV18PG256C8/I7",
75 },
76 "GW2A-18C": {
77 "package": "PBGA256S",
78 "device": "GW2A-18C",
79 "partnumber": "GW2A-LV18PG256SC8/I7", #"GW2AR-LV18PG256SC8/I7", "GW2AR-LV18QN88C8/I7"
80 },
81 "GW5A-25A": {
82 "package": "MBGA121N",
83 "device": "GW5A-25A",
84 "partnumber": "GW5A-LV25MG121NES",
85 },
86 "GW5AST-138C": {
87 "package": "PBGA484A",
88 "device": "GW5AST-138C",
89 "partnumber": "GW5AST-LV138PG484AC1/I0",
90 },
91 }[device]
92
93 # utils
94 name_idx = 0
95 def make_name(bel, typ):
96 global name_idx
97 name_idx += 1
98 return f"inst{name_idx}_{bel}_{typ}"
99
100 def tbrl2rc(fse, side, num):
101 if side == 'T':
102 row = 0
103 col = int(num) - 1
104 elif side == 'B':
105 row = len(fse['header']['grid'][61])-1
106 col = int(num) - 1
107 elif side == 'L':
108 row = int(num) - 1
109 col = 0
110 elif side == 'R':
111 row = int(num) - 1
112 col = len(fse['header']['grid'][61][0])-1
113 return (row, col)
114
115 def rc2tbrl(db, row, col, num):
116 idx = col
117 if row == 1:
118 edge = 'T'
119 elif row == db.rows:
120 edge = 'B'
121 elif col == 1:
122 edge = 'L'
123 idx = row
124 elif col == db.cols:
125 edge = 'R'
126 idx = row
127 return f"IO{edge}{idx}{num}"
128
129 # Read the packer vendor log to identify problem with primitives/attributes
130 # returns dictionary {(primitive name, error code) : [full error text]}
131 _err_parser = re.compile(r"(\w+) +\(([\w\d]+)\).*'(inst[^\']+)\'.*")
132 def read_err_log(fname):
133 errs = {}
134 with open(fname, 'r') as f:
135 for line in f:
136 res = _err_parser.match(line)
137 if res:
138 line_type, code, name = res.groups()
139 text = res.group(0)
140 if line_type in ["Warning", "Error"]:
141 errs.setdefault((name, code), []).append(text)
142 return errs
143
144 # Result of the vendor router-packer run
145 PnrResult = namedtuple('PnrResult', [
146 'bitmap', 'hdr', 'ftr', 'extra_slots',
147 'constrs', # constraints
148 'config', # device config
149 'attrs', # port attributes
150 'errs', # parsed log file
151 'version', # IDE version
152 ])
153
154 def run_pnr(mod, constr, config):
155 cfg = codegen.DeviceConfig({
156 "use_jtag_as_gpio" : config.get('jtag', "1"),
157 "use_sspi_as_gpio" : config.get('sspi', "1"),
158 "use_mspi_as_gpio" : config.get('mspi', "1"),
159 "use_ready_as_gpio" : config.get('ready', "1"),
160 "use_done_as_gpio" : config.get('done', "1"),
161 "use_reconfign_as_gpio" : config.get('reconfig', "1"),
162 "use_mode_as_gpio" : config.get('mode', "1"),
163 "use_i2c_as_gpio" : config.get('i2c', "1"),
164 "bit_crc_check" : "1",
165 "bit_compress" : "1",
166 "bit_encrypt" : "0",
167 "bit_security" : "1",
168 "bit_incl_bsram_init" : "0",
169 #"loading_rate" : "250/100",
170 "spi_flash_addr" : "0x00FFF000",
171 "bit_format" : "txt",
172 "bg_programming" : "off",
173 "secure_mode" : "0"})
174
175 opt = codegen.PnrOptions({
176 "gen_posp" : "1",
177 "gen_io_cst" : "1",
178 "gen_ibis" : "1",
179 "ireg_in_iob" : "0",
180 "oreg_in_iob" : "0",
181 "ioreg_in_iob" : "0",
182 "timing_driven" : "0",
183 "cst_warn_to_error" : "0"})
184 #"show_all_warn" : "1",
185
186 pnr = codegen.Pnr()
187 pnr.device = params['device']
188 pnr.partnumber = params['partnumber']
189 pnr.opt = opt
190 pnr.cfg = cfg
191
192 with tempfile.TemporaryDirectory() as tmpdir:
193 with open(tmpdir+"/top.v", "w") as f:
194 mod.write(f)
195 pnr.netlist = tmpdir+"/top.v"
196 with open(tmpdir+"/top.cst", "w") as f:
197 constr.write(f)
198 pnr.cst = tmpdir+"/top.cst"
199 with open(tmpdir+"/run.tcl", "w") as f:
200 pnr.write(f)
201
202 print(["/usr/bin/env", "LD_PRELOAD=" + gowinhome + "/Programmer/bin/libfontconfig.so.1", gowinhome + "/IDE/bin/gw_sh", tmpdir+"/run.tcl"])
203 subprocess.run(["/usr/bin/env", "LD_PRELOAD=" + gowinhome + "/Programmer/bin/libfontconfig.so.1", gowinhome + "/IDE/bin/gw_sh", tmpdir+"/run.tcl"], cwd = tmpdir)
204 #print(tmpdir); input()
205 try:
206 return PnrResult(
207 *bslib.read_bitstream(tmpdir+"/impl/pnr/top.fs"),
208 constr,
209 config, constr.attrs,
210 read_err_log(tmpdir+"/impl/pnr/top.log"),
211 bslib.read_bitstream_version(tmpdir+"/impl/pnr/top.fs"))
212 except FileNotFoundError:
213 print('ERROR', tmpdir)
214 #input()
215 return None
216
217 _tbrlre = re.compile(r"IO([TBRL])(\d+)")
218 def fse_iob(fse, db, diff_cap_info, locations):
219 iob_bels = {}
220 is_true_lvds = False
221 is_positive = False
222 for ttyp in fse.keys():
223 if ttyp == 'header' or 'longval' not in fse[ttyp]:
224 continue
225 # for ttyp, tiles in pin_locations.items():
226 # crieate all IO bels
227 bel_cnt = 0
228 for idx, fuse_table_n in {'A':23, 'B':24, 'C':40, 'D':41, 'E':42, 'F':43, 'G':44, 'H':45, 'I':46, 'J':47}.items():
229 if fuse_table_n in fse[ttyp]['longval']:
230 bel_cnt += 1
231 iob_bels.setdefault(ttyp, {}).setdefault(f'IOB{idx}', chipdb.Bel())
232 if bel_cnt > 2:
233 for bel in iob_bels[ttyp].values():
234 bel.simplified_iob = True
235 for ttyp, bels in iob_bels.items():
236 first_cell = True
237 for row, col in locations[ttyp]:
238 if first_cell:
239 for bel_name, bel in bels.items():
240 name = rc2tbrl(db, row + 1, col + 1, bel_name[-1])
241 if name in diff_cap_info.keys():
242 is_diff, is_true_lvds, is_positive, adc_bus = diff_cap_info[name]
243 bel.is_diff = is_diff
244 bel.is_true_lvds = is_true_lvds
245 bel.is_diff_p = is_positive
246 first_cell = False
247
248 #print(f"type:{ttyp} [{row}][{col}], {name}, diff:{bel.is_diff}, true lvds:{bel.is_true_lvds}, p:{bel.is_diff_p}")
249 db.grid[row][col].bels.update(iob_bels[ttyp])
250
251 # adc bus
252 for pin, desc in diff_cap_info.items():
253 _, _, _, adc_bus = desc
254 if adc_bus:
255 side, num = _tbrlre.match(pin).groups()
256 row, col = tbrl2rc(fse, side, num)
257 extra = db.extra_func.setdefault((row, col), {})
258 extra.setdefault('adcio', {})['bus'] = adc_bus
259
260 if device in {'GW5A-25A'}:
261 # fix IOR3AB
262 db.grid[2][db.cols - 1].bels['IOBA'].is_diff = False
263 db.grid[2][db.cols - 1].bels['IOBA'].is_true_lvds = False
264 db.grid[2][db.cols - 1].bels['IOBB'] = copy.deepcopy(db.grid[2][db.cols - 1].bels['IOBA'])
265
266 # generate bitstream footer
267 def gen_ftr():
268 # first line with CRC(?) at the end
269 line = bytearray(b'\xff'*20)
270 line[-2] = 0x34
271 line[-1] = 0x73
272 ftr = [line]
273 # bitmap CRC, filled in gowin_pack
274 ftr.append(bytearray(b'\x0a\x00\x00\x00\x00\x00\x00\x00'))
275 # noop
276 ftr.append(bytearray(b'\xff'*8))
277 # write done
278 ftr.append(bytearray(b'\x08\x00\x00\x00'))
279 # noop
280 ftr.append(bytearray(b'\xff'*8))
281 ftr.append(bytearray(b'\xff'*2))
282
283 return ftr
284
285 # borrowed from https://github.com/trabucayre/openFPGALoader/blob/master/src/fsparser.cpp
286 _chip_id = {
287 'GW1N-1' : b'\x06\x00\x00\x00\x09\x00\x28\x1b',
288 'GW1NZ-1' : b'\x06\x00\x00\x00\x01\x00\x68\x1b',
289 'GW1NS-2' : b'\x06\x00\x00\x00\x03\x00\x08\x1b',
290 'GW1N-4' : b'\x06\x00\x00\x00\x01\x00\x38\x1b',
291 'GW1NS-4' : b'\x06\x00\x00\x00\x01\x00\x98\x1b',
292 'GW1N-9' : b'\x06\x00\x00\x00\x11\x00\x58\x1b',
293 'GW1N-9C' : b'\x06\x00\x00\x00\x11\x00\x48\x1b',
294 'GW2A-18' : b'\x06\x00\x00\x00\x00\x00\x08\x1b',
295 'GW2A-18C' : b'\x06\x00\x00\x00\x00\x00\x08\x1b',
296 'GW5A-25A' : b'\x06\x00\x00\x00\x00\x01\x28\x1b',
297 'GW5AST-138C' : b'\x06\x00\x00\x00\x00\x01\x08\x1b',
298 }
299
300 # generate bitsream header
301 def gen_hdr():
302 hdr = [bytearray(b'\xff'*20)]
303 hdr.append(bytearray(b'\xff'*2))
304 # magic
305 hdr.append(bytearray(b'\xa5\xc3'))
306 # chip id
307 hdr.append(bytearray(_chip_id[device]))
308 # flags?
309 hdr.append(bytearray(b'\x10\x00\x00\x00\x00\xae\x00\x00'))
310 if params['device'] in {'GW5A-25A'}:
311 hdr.append(bytearray(b'\x62\x00\x00\x00\x00\x00\x00\x40'))
312 # compression keys
313 hdr.append(bytearray(b'\x51\x00\xff\xff\xff\xff\xff\xff'))
314 # something about the Security Bit
315 hdr.append(bytearray(b'\x0b\x00\x00\x00'))
316 # SPI address = 0
317 hdr.append(bytearray(b'\xd2\x00\xff\xff\x00\x00\x00\x00'))
318 # unknown
319 hdr.append(bytearray(b'\x12\x00\x00\x00'))
320 # number of rows, is filled in gowin_pack
321 hdr.append(bytearray(b'\x3b\x80\x00\x00'))
322
323 return hdr
324
325 if __name__ == "__main__":
326 with open(f"{gowinhome}/IDE/share/device/{params['device']}/{params['device']}.fse", 'rb') as f:
327 fse = fse_parser.readFse(f, device)
328
329 dat = dat19.Datfile(Path(f"{gowinhome}/IDE/share/device/{params['device']}/{params['device']}.dat"))
330
331 if gowin_debug:
332 with open(f"{device}-dat.pickle", 'wb') as f:
333 pickle.dump(dat, f)
334
335 with open(f"{gowinhome}/IDE/share/device/{params['device']}/{params['device']}.tm", 'rb') as f:
336 tm = tm_h4x.read_tm(f, device)
337
338 db = chipdb.from_fse(device, fse, dat)
339 chipdb.set_banks(fse, dat, db)
340 db.timing = tm
341 chipdb.fse_wire_delays(db, params['device'])
342 db.packages, db.pinout, _ = chipdb.json_pinout(device)
343
344 corners = [
345 (0, 0, fse['header']['grid'][61][0][0]),
346 (0, db.cols-1, fse['header']['grid'][61][0][-1]),
347 (db.rows-1, db.cols-1, fse['header']['grid'][61][-1][-1]),
348 (db.rows-1, 0, fse['header']['grid'][61][-1][0]),
349 ]
350
351 locations = {}
352 for row, row_dat in enumerate(fse['header']['grid'][61]):
353 for col, typ in enumerate(row_dat):
354 locations.setdefault(typ, []).append((row, col))
355
356 pin_names = pindef.get_locs(params['device'], params['package'], True)
357 edges = {'T': fse['header']['grid'][61][0],
358 'B': fse['header']['grid'][61][-1],
359 'L': [row[0] for row in fse['header']['grid'][61]],
360 'R': [row[-1] for row in fse['header']['grid'][61]]}
361 pin_locations = {}
362 pin_re = re.compile(r"IO([TBRL])(\d+)\[?([A-Z])\]?")
363 for name in pin_names:
364 side, num, pin = pin_re.match(name).groups()
365 ttyp = edges[side][int(num)-1]
366 ttyp_pins = pin_locations.setdefault(ttyp, {})
367 ttyp_pins.setdefault(name[:-1], set()).add(name)
368
369 # fill header/footer by hand
370 db.cmd_hdr = gen_hdr()
371 db.cmd_ftr = gen_ftr()
372
373 # IOB
374 diff_cap_info = pindef.get_diff_adc_cap_info(params['device'], params['package'], True)
375 fse_iob(fse, db, diff_cap_info, locations);
376 if chipdb.is_GW5_family(device):
377 chipdb.fill_GW5A_io_bels(db)
378 chipdb.dat_fill_io_cfgs(db, dat, db.pinout[params['device']][params['package']])
379
380 pad_locs = pindef.get_pll_pads_locs(params['device'], params['package'])
381 chipdb.pll_pads(db, device, pad_locs)
382
383 chipdb.dat_portmap(dat, db, device)
384 chipdb.add_hclk_bels(dat, db, device)
385
386
387 # XXX GW1NR-9 has interesting IOBA pins on the bottom side
388 if device == 'GW1N-9' :
389 loc = locations[52][0]
390 bel = db.grid[loc[0]][loc[1]].bels['IOBA']
391 bel.portmap['GW9_ALWAYS_LOW0'] = wnames.wirenames[dat.portmap['IologicAIn'][40]]
392 bel.portmap['GW9_ALWAYS_LOW1'] = wnames.wirenames[dat.portmap['IologicAIn'][42]]
393
394 # GSR
395 if device in {'GW2A-18', 'GW2A-18C'}:
396 db.grid[27][50].bels.setdefault('GSR', chipdb.Bel()).portmap['GSRI'] = 'C4';
397 elif device in {'GW5A-25A'}:
398 db.grid[27][88].bels.setdefault('GSR', chipdb.Bel()).portmap['GSRI'] = 'LSR0';
399 elif device in {'GW5AST-138C'}:
400 db.grid[108][165].bels.setdefault('GSR', chipdb.Bel()).portmap['GSRI'] = 'D7';
401 elif device in {'GW1N-1', 'GW1N-4', 'GW1NS-4', 'GW1N-9', 'GW1N-9C', 'GW1NS-2', 'GW1NZ-1'}:
402 db.grid[0][0].bels.setdefault('GSR', chipdb.Bel()).portmap['GSRI'] = 'C4';
403 elif device in {'GW1N-1P5C'}:
404 db.grid[0][1].bels.setdefault('GSR', chipdb.Bel()).portmap['GSRI'] = 'C4';
405 else:
406 raise Exception(f"No GSR for {device}")
407
408
409 #TODO proper serialization format
410 with open(f"{device}_stage1.pickle", 'wb') as f:
411 pickle.dump(db, f)