-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlteraDownload.java
More file actions
568 lines (523 loc) · 21.6 KB
/
AlteraDownload.java
File metadata and controls
568 lines (523 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/*
* Logisim-evolution - digital logic design tool and simulator
* Copyright by the Logisim-evolution developers
*
* https://github.com/logisim-evolution/
*
* This is free software released under GNU GPLv3 license
*/
package com.cburch.logisim.fpga.download;
import static com.cburch.logisim.fpga.Strings.S;
import com.cburch.logisim.fpga.data.BoardInformation;
import com.cburch.logisim.fpga.data.MappableResourcesContainer;
import com.cburch.logisim.fpga.data.PullBehaviors;
import com.cburch.logisim.fpga.designrulecheck.Netlist;
import com.cburch.logisim.fpga.file.FileWriter;
import com.cburch.logisim.fpga.gui.Reporter;
import com.cburch.logisim.fpga.hdlgenerator.HdlGeneratorFactory;
import com.cburch.logisim.fpga.hdlgenerator.TickComponentHdlGeneratorFactory;
import com.cburch.logisim.fpga.hdlgenerator.ToplevelHdlGeneratorFactory;
import com.cburch.logisim.fpga.settings.VendorSoftware;
import com.cburch.logisim.util.LineBuffer;
import com.cburch.logisim.util.XmlUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class AlteraDownload implements VendorDownload {
private final VendorSoftware alteraVendor = VendorSoftware.getSoftware(VendorSoftware.VENDOR_ALTERA);
private final String scriptPath;
private final String projectPath;
private final String sandboxPath;
private final Netlist rootNetList;
private MappableResourcesContainer mapInfo;
private final BoardInformation boardInfo;
private final List<String> entities;
private final List<String> architectures;
private final String hdlType;
private String cablename;
private final boolean writeToFlash;
private static final String alteraTclFile = "AlteraDownload.tcl";
private static final String AlteraCofFile = "AlteraFlash.cof";
public AlteraDownload(
String projectPath,
Netlist rootNetList,
BoardInformation boardInfo,
List<String> entities,
List<String> architectures,
String hdlType,
boolean writeToFlash) {
this.projectPath = projectPath;
this.sandboxPath = DownloadBase.getDirectoryLocation(projectPath, DownloadBase.SANDBOX_PATH);
this.scriptPath = DownloadBase.getDirectoryLocation(projectPath, DownloadBase.SCRIPT_PATH);
this.rootNetList = rootNetList;
this.boardInfo = boardInfo;
this.entities = entities;
this.architectures = architectures;
this.hdlType = hdlType;
this.writeToFlash = writeToFlash;
cablename = "";
}
@Override
public void setMapableResources(MappableResourcesContainer resources) {
mapInfo = resources;
}
@Override
public int getNumberOfStages() {
return 3;
}
@Override
public String getStageMessage(int stage) {
return switch (stage) {
case 0 -> S.get("AlteraProject");
case 1 -> S.get("AlteraOptimize");
case 2 -> S.get("AlteraSyntPRBit");
default -> "Unknown, bizare";
};
}
@Override
public ProcessBuilder performStep(int stage) {
return switch (stage) {
case 0 -> stage0Project();
case 1 -> stage1Optimize();
case 2 -> stage2SprBit();
default -> null;
};
}
@Override
public boolean readyForDownload() {
final var SofFile = new File(sandboxPath + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".sof").exists();
final var PofFile = new File(sandboxPath + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".pof").exists();
return SofFile || PofFile;
}
@Override
public ProcessBuilder downloadToBoard() {
if (writeToFlash && !doFlashing()) return null;
final var command = new ArrayList<String>();
command.add(alteraVendor.getBinaryPath(1));
command.add("-c");
command.add(cablename);
command.add("-m");
command.add("jtag");
command.add("-o");
// [Fixed] If both .sof and .pof are present, let the user choose.
final var SofFile = new File(sandboxPath + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".sof").exists();
final var PofFile = new File(sandboxPath + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".pof").exists();
// If both a .sof and a .pof file exist, the user chooses
int choice = 0;
if (SofFile && PofFile) {
// Define the options as an array of strings.
String[] options = {"SOF (SRAM Object File)", "POF (Programmer Object File)"};
// Use the JOptionPane to bring up a selection pane.
choice = JOptionPane.showOptionDialog(
null, // Parent component (displayed in the center of the screen if null)
"Select the programming file to download:", // Message
"Select an option", // Window Title
JOptionPane.DEFAULT_OPTION, // Option types
JOptionPane.INFORMATION_MESSAGE, // Message types
null, // Icon (uses default icon if set to null)
options, // Array of options to select
options[0]); // Default selection (set to options[0])
// choice: 0(SOF), 1(POF), other (if you closed the window without selecting anything)
if (choice != 1) choice = 0; // If you closed the window without selecting anything, select SOF
}
else if (SofFile) { // If you only have a .sof file
choice = 0;
}
else { // If you only have a .pof file
choice = 1;
}
if (choice == 0) {
command.add("P;" + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".sof"
+ "@" + boardInfo.fpga.getFpgaJTAGChainPosition());
} else {
command.add("P;" + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".pof"
+ "@" + boardInfo.fpga.getFpgaJTAGChainPosition());
}
final var down = new ProcessBuilder(command);
down.directory(new File(sandboxPath));
return down;
}
private ProcessBuilder stage0Project() {
final var command = new ArrayList<String>();
command.add(alteraVendor.getBinaryPath(0));
command.add("-t");
command.add(scriptPath.replace(projectPath, ".." + File.separator) + alteraTclFile);
final var stage0 = new ProcessBuilder(command);
stage0.directory(new File(sandboxPath));
return stage0;
}
private ProcessBuilder stage1Optimize() {
final var command = new ArrayList<String>();
command.add(alteraVendor.getBinaryPath(2));
command.add(ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME);
command.add("--optimize=area");
final var stage1 = new ProcessBuilder(command);
stage1.directory(new File(sandboxPath));
return stage1;
}
private ProcessBuilder stage2SprBit() {
var command = new ArrayList<String>();
command.add(alteraVendor.getBinaryPath(0));
command.add("--flow");
command.add("compile");
command.add(ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME);
final var stage2 = new ProcessBuilder(command);
stage2.directory(new File(sandboxPath));
return stage2;
}
@Override
public boolean createDownloadScripts() {
var scriptFile = FileWriter.getFilePointer(scriptPath, alteraTclFile);
if (scriptFile == null) {
scriptFile = new File(scriptPath + alteraTclFile);
return scriptFile.exists();
}
final var fileType = hdlType.equals(HdlGeneratorFactory.VHDL) ? "VHDL_FILE" : "VERILOG_FILE";
final var contents = LineBuffer.getBuffer();
contents
.pair("topLevelName", ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME)
.pair("fileType", fileType)
.pair("clock", TickComponentHdlGeneratorFactory.FPGA_CLOCK);
contents
.add("""
# Load Quartus II Tcl Project package
package require ::quartus::project
set need_to_close_project 0
set make_assignments 1
# Check that the right project is open
if {[is_project_open]} {
if {[string compare $quartus(project) "{{topLevelName}}"]} {
puts "Project {{topLevelName}} is not open"
set make_assignments 0
}
} else {
# Only open if not already open
if {[project_exists {{topLevelName}}]} {
project_open -revision {{topLevelName}} {{topLevelName}}
} else {
project_new -revision {{topLevelName}} {{topLevelName}}
}
set need_to_close_project 1
}
# Make assignments
if {$make_assignments} {
""")
.add(getAlteraAssignments(boardInfo))
.add("""
# Include all entities and gates
""");
for (var entity : entities) {
contents.add(" set_global_assignment -name {{fileType}} \"{{1}}\"", entity);
}
for (var architecture : architectures) {
contents.add(" set_global_assignment -name {{fileType}} \"{{1}}\"", architecture);
}
contents.add("");
contents.add(" # Map fpga_clk and ionets to fpga pins");
if (rootNetList.numberOfClockTrees() > 0 || rootNetList.requiresGlobalClockConnection()) {
contents.add(" set_location_assignment {{1}} -to {{clock}}", boardInfo.fpga.getClockPinLocation());
}
contents
.add(getPinLocStrings())
.add("""
# Commit assignments
export_assignments
# Close project
if {$need_to_close_project} {
project_close
}
}
""");
return FileWriter.writeContents(scriptFile, contents.get());
}
private List<String> getPinLocStrings() {
final var contents = LineBuffer.getBuffer();
for (final var key : mapInfo.getMappableResources().keySet()) {
final var map = mapInfo.getMappableResources().get(key);
for (var i = 0; i < map.getNrOfPins(); i++) {
if (map.isMapped(i) && !map.isOpenMapped(i) && !map.isConstantMapped(i) && !map.isInternalMapped(i)) {
final var pairs = new LineBuffer.Pairs()
.pair("pinLoc", map.getPinLocation(i))
.pair("inv", map.isExternalInverted(i) ? "n_" : "")
.pair("hdlStr", map.getHdlString(i));
contents.add("set_location_assignment {{pinLoc}} -to {{inv}}{{hdlStr}}", pairs);
if (map.requiresPullup(i))
contents.add("set_instance_assignment -name WEAK_PULL_UP_RESISTOR ON -to {{inv}}{{hdlStr}}", pairs);
}
}
}
final var ledArrayMap = DownloadBase.getScanningMaps(mapInfo, rootNetList, boardInfo);
for (final var key : ledArrayMap.keySet())
contents.add("set_location_assignment {{1}} -to {{2}}", ledArrayMap.get(key), key);
return contents.getWithIndent(4);
}
private static List<String> getAlteraAssignments(BoardInformation currentBoard) {
final var pkg = currentBoard.fpga.getPackage().split(" ");
final var currentBehavior = currentBoard.fpga.getUnusedPinsBehavior();
final var behavior = switch (currentBehavior) {
case PullBehaviors.PULL_UP -> "PULLUP";
case PullBehaviors.PULL_DOWN -> "PULLDOWN";
case PullBehaviors.FLOAT -> "TRI-STATED";
default -> throw new IllegalStateException("Unexpected value: " + currentBehavior);
};
return LineBuffer.getBuffer()
.pair("assignName", "set_global_assignment -name")
.add("{{assignName}} FAMILY \"{{1}}\"", currentBoard.fpga.getTechnology())
.add("{{assignName}} DEVICE {{1}}", currentBoard.fpga.getPart())
.add("{{assignName}} DEVICE_FILTER_PACKAGE {{1}}", pkg[0])
.add("{{assignName}} DEVICE_FILTER_PIN_COUNT {{1}}", pkg[1])
// Modified to treat unused pins as inputs
// .add("{{assignName}} RESERVE_ALL_UNUSED_PINS \"AS INPUT {{1}}\"", behavior) // [Previoius]
.add("{{assignName}} RESERVE_ALL_UNUSED_PINS_WEAK_PULLUP \"AS INPUT {{1}}\"", behavior) // [Fixed]
.add("{{assignName}} FMAX_REQUIREMENT \"{{1}}\"", Download.getClockFrequencyString(currentBoard))
.add("{{assignName}} RESERVE_NCEO_AFTER_CONFIGURATION \"USE AS REGULAR IO\"")
.add("{{assignName}} CYCLONEII_RESERVE_NCEO_AFTER_CONFIGURATION \"USE AS REGULAR IO\"")
.getWithIndent();
}
@Override
public boolean isBoardConnected() {
var command = new ArrayList<String>();
command.add(alteraVendor.getBinaryPath(1));
command.add("--list");
final var detect = new ProcessBuilder(command);
detect.directory(new File(sandboxPath));
var response = new ArrayList<String>();
try {
Reporter.report.print("");
Reporter.report.print("===");
Reporter.report.print("===> " + S.get("AlteraDetectDevice"));
Reporter.report.print("===");
if (Download.execute(detect, response) != null) return false;
} catch (IOException | InterruptedException e) {
return false;
}
var devices = getDevices(response);
if (devices == null) return false;
if (devices.size() == 1) {
cablename = devices.get(0);
return true;
}
var selection = Download.chooseBoard(devices);
if (selection == null) return false;
cablename = selection;
return true;
}
private List<String> getDevices(ArrayList<String> lines) {
final var dev = new ArrayList<String>();
for (var line : lines) {
var n = dev.size() + 1;
if (!line.matches("^" + n + "\\) .*")) continue;
line = line.replaceAll("^" + n + "\\) ", "");
dev.add(line.trim());
}
return (dev.isEmpty()) ? null : dev;
}
private boolean doFlashing() {
if (!createCofFile()) {
Reporter.report.addError(S.get("AlteraFlashError"));
return false;
}
if (!createJicFile()) {
Reporter.report.addError(S.get("AlteraFlashError"));
return false;
}
if (!loadProgrammerSoftware()) {
Reporter.report.addError(S.get("AlteraFlashError"));
return false;
}
if (!flashDevice()) {
Reporter.report.addError(S.get("AlteraFlashError"));
return false;
}
return true;
}
private boolean flashDevice() {
final var jicFile = ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".jic";
Reporter.report.print("==>");
Reporter.report.print("==> " + S.get("AlteraFlash"));
Reporter.report.print("==>");
if (!new File(sandboxPath + jicFile).exists()) {
Reporter.report.addError(S.get("AlteraFlashError", jicFile));
return false;
}
final var command = LineBuffer.getBuffer();
command
.add(alteraVendor.getBinaryPath(1))
.add("-c")
.add(cablename)
.add("-m")
.add("jtag")
.add("-o")
.add("P;{{1}}", jicFile);
final var prog = new ProcessBuilder(command.get());
prog.directory(new File(sandboxPath));
try {
final var result = Download.execute(prog, null);
if (result != null) {
Reporter.report.addFatalError(S.get("AlteraFlashFailure"));
return false;
}
} catch (IOException | InterruptedException e) {
Reporter.report.addFatalError(S.get("AlteraFlashFailure"));
return false;
}
return true;
}
private boolean loadProgrammerSoftware() {
final var FpgaDevice = stripPackageSpeedSuffix();
final var ProgrammerSofFile = new File(VendorSoftware.getToolPath(VendorSoftware.VENDOR_ALTERA)).getParent()
+ File.separator
+ "common"
+ File.separator
+ "devinfo"
+ File.separator
+ "programmer"
+ File.separator
+ "sfl_"
+ FpgaDevice.toLowerCase()
+ ".sof";
Reporter.report.print("==>");
Reporter.report.print("==> " + S.get("AlteraProgSof"));
Reporter.report.print("==>");
if (!new File(ProgrammerSofFile).exists()) {
Reporter.report.addError(S.get("AlteraProgSofError", ProgrammerSofFile));
return false;
}
final var command = LineBuffer.getBuffer();
command.add(alteraVendor.getBinaryPath(1))
.add("-c")
.add(cablename)
.add("-m")
.add("jtag")
.add("-o")
.add("P;{{1}}", ProgrammerSofFile);
final var prog = new ProcessBuilder(command.get());
prog.directory(new File(sandboxPath));
try {
final var result = Download.execute(prog, null);
if (result != null) {
Reporter.report.addFatalError(S.get("AlteraProgSofFailure"));
return false;
}
} catch (IOException | InterruptedException e) {
Reporter.report.addFatalError(S.get("AlteraProgSofFailure"));
return false;
}
return true;
}
private String stripPackageSpeedSuffix() {
/* For the Cyclone IV devices the name used for Syntesis is in form
* EP4CE15F23C8. For the programmer sof-file (for flash writing) we need to strip
* the part F23C8. For future supported devices this should be checked.
*/
final var FpgaDevice = boardInfo.fpga.getPart();
final var index = FpgaDevice.indexOf("F");
return FpgaDevice.substring(0, index);
}
private boolean createJicFile() {
if (!new File(scriptPath + AlteraCofFile).exists()) {
Reporter.report.addError(S.get("AlteraNoCof"));
return false;
}
Reporter.report.print("==>");
Reporter.report.print("==> " + S.get("AlteraJicFile"));
Reporter.report.print("==>");
var command = new ArrayList<String>();
command.add(alteraVendor.getBinaryPath(3));
command.add("-c");
command.add((scriptPath + AlteraCofFile).replace(projectPath, "../"));
final var jic = new ProcessBuilder(command);
jic.directory(new File(sandboxPath));
try {
final var result = Download.execute(jic, null);
if (result != null) {
Reporter.report.addFatalError(S.get("AlteraJicFileError"));
return false;
}
} catch (IOException | InterruptedException e) {
Reporter.report.addFatalError(S.get("AlteraJicFileError"));
return false;
}
return true;
}
private boolean createCofFile() {
if (!new File(sandboxPath + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".sof").exists()) {
Reporter.report.addFatalError(S.get("AlteraNoSofFile"));
return false;
}
Reporter.report.print("==>");
Reporter.report.print("==> " + S.get("AlteraCofFile"));
Reporter.report.print("==>");
try {
final var docFactory = XmlUtil.getHardenedBuilderFactory();
final var docBuilder = docFactory.newDocumentBuilder();
final var cofFile = docBuilder.newDocument();
cofFile.setXmlStandalone(true);
final var rootElement = cofFile.createElement("cof");
cofFile.appendChild(rootElement);
addElement("eprom_name", boardInfo.fpga.getFlashName(), rootElement, cofFile);
addElement("flash_loader_device", stripPackageSpeedSuffix(), rootElement, cofFile);
addElement("output_filename",
sandboxPath + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".jic",
rootElement,
cofFile);
addElement("n_pages", "1", rootElement, cofFile);
addElement("width", "1", rootElement, cofFile);
addElement("mode", "7", rootElement, cofFile);
final var sofData = cofFile.createElement("sof_data");
rootElement.appendChild(sofData);
addElement("user_name", "Page_0", sofData, cofFile);
addElement("page_flags", "1", sofData, cofFile);
final var bitFile = cofFile.createElement("bit0");
sofData.appendChild(bitFile);
addElement("sof_filename",
sandboxPath + ToplevelHdlGeneratorFactory.FPGA_TOP_LEVEL_NAME + ".sof",
bitFile,
cofFile);
addElement("version", "10", rootElement, cofFile);
addElement("create_cvp_file", "0", rootElement, cofFile);
addElement("create_hps_iocsr", "0", rootElement, cofFile);
addElement("auto_create_rpd", "0", rootElement, cofFile);
addElement("rpd_little_endian", "1", rootElement, cofFile);
final var options = cofFile.createElement("options");
rootElement.appendChild(options);
addElement("map_file", "0", options, cofFile);
final var advancedOptions = cofFile.createElement("advanced_options");
rootElement.appendChild(advancedOptions);
addElement("ignore_epcs_id_check", "2", advancedOptions, cofFile);
addElement("ignore_condone_check", "2", advancedOptions, cofFile);
addElement("plc_adjustment", "0", advancedOptions, cofFile);
addElement("post_chain_bitstream_pad_bytes", "-1", advancedOptions, cofFile);
addElement("post_device_bitstream_pad_bytes", "-1", advancedOptions, cofFile);
addElement("bitslice_pre_padding", "1", advancedOptions, cofFile);
final var transformerFac = TransformerFactory.newInstance();
final var transformer = transformerFac.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
final var source = new DOMSource(cofFile);
final var result = new StreamResult(new File(scriptPath + AlteraCofFile));
transformer.transform(source, result);
} catch (ParserConfigurationException | TransformerException e) {
Reporter.report.addError(S.get("AlteraErrorCof"));
return false;
}
return true;
}
private void addElement(String elementName, String elementValue, Element root, Document doc) {
final var namedElement = doc.createElement(elementName);
namedElement.appendChild(doc.createTextNode(elementValue));
root.appendChild(namedElement);
}
}