0677ef900250b4cde1c0c46b338395eeb9aceb02
[libreriscv.git] / HDL_workflow.mdwn
1 # HDL workflow
2
3 This section describes the workflow and some best practices for developing
4 the Libre-SOC hardware. We use nmigen, yosys and symbiyosys, and this
5 page is intended not just to help you get set up, it is intended to
6 help advise you of some tricks and practices that will help you become
7 effective team contributors.
8
9 It is particularly important to bear in mind that we are not just
10 "developing code", here: we are creating a "lasting legacy educational
11 resource" for other people to learn from, and for businesses and students
12 alike to be able to use, learn from and augment for their own purposes.
13
14 It is also important to appreciate and respect that we are funded under
15 NLNet's Privacy and Enhanced Trust Programme <http://nlnet.nl/PET>. Full
16 transparency, readability, documentation, effective team communication
17 and formal mathematical proofs for all code at all levels is therefore
18 paramount.
19
20 Therefore, we need not only to be "self-sufficient" (absolutely
21 under no circumstances critically reliant on somebody else's servers
22 **or protocols**) we also need to ensure that everything (including
23 all communication such as the mailing list archives) are recorded,
24 replicable, and accessible in perpetuity. Use of slack or a "forum"
25 either actively prevents or makes that much harder.
26
27 # Collaboration resources
28
29 The main message here: **use the right tool for the right job**.
30
31 * mailing list: general communication and discussion.
32 * irc channel #libre-soc: real(ish)-time communication.
33 * bugtracker: task-orientated, goal-orientated *focussed* discussion.
34 * ikiwiki: document store, information store, and (editable) main website
35 * git repositories: code stores (**not binary or auto-generated output store**)
36 * ftp server (<https://ftp.libre-soc.org/>): large (temporary,
37 auto-generated) file store.
38
39 We will add an IRC channel at some point when there are enough people
40 to warrant having one (and it will be publicly archived)
41
42 Note also the lack of a "forum" in the above list. this is very
43 deliberate. forums are a serious distraction when it comes to technical
44 heavily goal-orientated development. recent internet users may enjoy
45 looking up the "AOL metoo postings" meme.
46
47 Note also the complete lack of "social platforms". if we wanted to tell
48 everybody how much better each of us are than anyone else in the team,
49 how many times we made a commit (look at me, look at me, i'm so clever),
50 and how many times we went to the bathroom, we would have installed a
51 social media based project "management" system.
52
53 ## Main contact method: mailing list
54
55 To respect the transparency requirements, conversations need to be
56 public and archived (i.e not skype, not telegram, not discord,
57 and anyone seriously suggesting slack will be thrown to the
58 lions). Therefore we have a mailing list. Everything goes through
59 there. <https://lists.libre-soc.org/mailman/listinfo/libre-soc-dev>
60 therefore please do google "mailing list etiquette" and at the very
61 minimum look up and understand the following:
62
63 * This is a technical mailing list with complex topics. Top posting
64 is completely inappropriate. Don't do it unless you have mitigating
65 circumstances, and even then please apologise and explain ("hello sorry
66 using phone at airport flight soon, v. quick reply: ....")
67 * Always trim context but do not cut excessively to the point where people
68 cannot follow the discussion. Especially do not cut the attribution
69 ("On monday xxx wrote") of something that you are actually replying
70 to.
71 * Use inline replies i.e. reply at the point in the relevant part of
72 the conversation, as if you were actually having a conversation.
73 * Follow standard IETF reply formatting, using ">" for cascaded
74 indentation of other people's replies. If using gmail, please: SWITCH
75 OFF RICH TEXT EDITING.
76 * Please for god's sake do not use "my replies are in a different
77 colour". Only old and highly regarded people still using AOL are allowed
78 to get away with that (such as Mitch).
79 * Start a new topic with a relevant subject line. If an existing
80 discussion changes direction, change the subject line to reflect the
81 new topic (or start a new conversation entirely, without using the
82 "reply" button)
83 * DMARC is a pain on the neck. Try to avoid GPG signed messages. sigh.
84 * Don't send massive attachments. Put them online (no, not on facebook or
85 google drive or anywhere else that demands privacy violations) and provide
86 the link. Which should not require any kind of login to access. ask the
87 listadmin if you don't have anywhere suitable: FTP access can be arranged.
88
89 ### Actionable items from mailing list
90
91 If discussions result in any actionable items, it is important not to
92 lose track of them. Create a bugreport, find the discussion in the
93 archives <https://lists.libre-soc.org/pipermail/libre-soc-dev/>,
94 and put the link actually in the bugtracker as one of the comments.
95
96 At some point in any discussion, the sudden realisation may dawn on one
97 or more people that this is an "actionable" discussion. at that point
98 it may become better to use <https://bugs.libre-soc.org/>
99 itself to continue the discussion rather than to keep on dropping copies
100 of links into the bugtracker. The bugtracker sends copies of comments
101 *to* the list however this is 'one-way' (note from lkcl: because this
102 involves running an automated perl script from email, on every email,
103 on the server, that is a high security risk, and i'm not doing it. sorry.)
104
105 ### Mailing list != editable document store
106
107 Also, please do not use the mailing list as an "information or document
108 store or poor-man's editor". We have the wiki for that. Edit a page and
109 tell people what you did (summarise rather than drop the entire contents
110 at the list) and include the link to the page.
111
112 Or, if it is more appropriate, commit a document (or source code)
113 into the relevant git repository then look up the link in the gitweb
114 source tree browser and post that (in the bugtracker or mailing list)
115 See <https://git.libre-soc.org/>
116
117 ### gmail "spam"ifying the list
118
119 See <https://blog.kittycooper.com/2014/05/keeping-my-mailing-list-emails-out-of-gmails-spam-folder/>
120
121 Basically it is possible to select any message from the list, create a
122 "filter" (under "More"), and, on the 2nd dialog box, click the "never
123 send this to Spam" option.
124
125 ## Bugtracker
126
127 bugzilla. old and highly effective. sign up in the usual way. any
128 problems, ask on the list.
129
130 Please do not ask for the project to be transferred to github or other
131 proprietary nonfree service "because it's soooo convenient", as the
132 lions are getting wind and gout from overfeeding on that one.
133
134 ## ikiwiki
135
136 Runs the main libre-soc.org site (including this page). effective,
137 stunningly light on resources, and uses a git repository not a database.
138 That means it can be edited offline.
139
140 Usual deal: register an account and you can start editing and contributing
141 straight away.
142
143 Hint: to create a new page, find a suitable page that would link to it,
144 first, then put the link in of the page you want to create, as if the
145 page already exists. Save that page, and you will find a question mark
146 next to the new link you created. click that link, and it will fire up a
147 "create new page" editor.
148
149 Wiki pages are formatted in [[markdown|ikiwiki/markdown]] syntax.
150
151 Hint again: the wiki is backed by a git repository. Don't go overboard
152 but at the same time do not be afraid that you might "damage" or "lose"
153 pages. Although it would be a minor pain, the pages can always be
154 reverted or edited by the sysadmins to restore things if you get in a tiz.
155
156 Assistance in creating a much better theme greatly appreciated. e.g.
157 <http://www.math.cmu.edu/~gautam/sj/blog/20140720-ikiwiki-navbar.html>
158
159 ## git
160
161 We use git. More on this below. We also use
162 [gitolite3](https://gitolite.com/gitolite/) running on a dedicated server.
163 again, it is extremely effective and low resource utilisation. Reminder:
164 lions are involved if github is mentioned.
165
166 [gitweb](https://git.wiki.kernel.org/index.php/Gitweb) is provided which
167 does a decent job. <https://git.libre-soc.org/>
168
169 [Git](https://en.wikipedia.org/wiki/Git) does version control, ie it
170 tracks changes to files so that previous versions can be got back or
171 compared.
172
173 ## ftp server
174
175 <https://ftp.libre-soc.org/> is available for storing large files
176 that do not belong in a git repository, if we have (or ever need)
177 any. Images (etc.) if small and appropriate should go into the
178 wiki, however .tgz archives (etc.) and, at some point, binaries,
179 should be on the ftp server.
180
181 Ask on the list if you have a file that belongs on the ftp server.
182
183 ## server
184
185 As an aside: all this is "old school" and run on a single core 512MB
186 VM with only a 20GB HDD allocation. it costs only 8 GBP per month from
187 mythic-beasts and means that the project is in no way dependent on anyone
188 else - not microsoft, not google, not facebook, not amazon.
189
190 We tried [gitlab](https://about.gitlab.com/). it didn't go well. please
191 don't ask to replace the above extremely resource-efficient services
192 with it.
193
194 # Hardware
195
196 RAM is the biggest requirement. Minimum 16GB, the more the better (32
197 or 64GB starts to reach "acceptable" levels. Disk space is not hugely
198 critical: 256GB SSD should be more than adequate. Simulations and
199 FPGA compilations however are where raw processing power is a must.
200 High end Graphics Cards are nonessential.
201
202 What is particularly useful is to have hi-res screens (curved is
203 *strongly* recommended if the LCD is over 24in wide, to avoid eyeballs
204 going "prism" through long term use), and to have several of them: the
205 more the better. Either a DisplayLink UD160A (or more modern variant)
206 or simply using a second machine (lower spec hardware because it will
207 run editors) is really effective.
208
209 Also it is really recommended to have a UHD monitor (4k - 3840x2160),
210 or at least 2560x1200. If given a choice, 4:3 aspect ratio is better
211 than 16:9 particularly when using several of them. However, caveat
212 (details below): please when editing do not assume that everyone will
213 have access to such high resolution screens.
214
215 # Operating System
216
217 First install and become familiar with
218 [Debian](https://www.debian.org/) ([Ubuntu](https://ubuntu.com/)
219 if you absolutely
220 must) for standardisation cross-team and so that toolchain installation
221 is greatly simplified. yosys in particular warns that trying to use
222 Windows, BSD or MacOS will get you into a world of pain.
223
224 Only a basic GUI desktop is necessary: fvwm2, xfce4, lxde are perfectly
225 sufficient (alongside wicd-gtk for network management). Other more
226 complex desktops can be used however may consume greater resources.
227
228 # editors and editing
229
230 Whilst this is often a personal choice, the fact that many editors are
231 GUI based and run full-screen with the entire right hand side *and* middle
232 *and* the majority of the left side of the hi-res screen entirely unused
233 and bereft of text leaves experienced developers both amused and puzzled.
234
235 At the point where such full-screen users commit code with line lengths
236 well over 160 characters, that amusement quickly evaporates.
237
238 Where the problems occur with full-screen editor usage is when a project
239 is split into dozens if not hundreds of small files (as this one is). At
240 that point it becomes pretty much essential to have as many as six to
241 eight files open *and on-screen* at once, without overlaps i.e. not in
242 hidden tabs, next to at least two if not three additional free and clear
243 terminals into which commands are regularly and routinely typed (make,
244 git commit, nosetests3 etc). Illustrated with the following 3840x2160
245 screenshot (click to view full image), where *every one* of those 80x70
246 xterm windows is *relevant to the task at hand*.
247
248 [[!img 2020-01-24_11-56.png size=640x ]]
249
250 (hint/tip: fvwm2 set up with "mouse-over to raise focus, rather than
251 additionally requiring a mouse click, can save a huge amount of cumulative
252 development time here, switching between editor terminal(s) and the
253 command terminals).
254
255 Once this becomes necessary, it it turn implies that having greater
256 than 80 chars per line - and running editors full-screen - is a severe
257 hinderance to an essential *and highly effective* workflow technique.
258
259 Additionally, care should be taken to respect that not everyone will have
260 200+ column editor windows and the eyesight of a hawk. They may only have
261 a 1280 x 800 laptop which barely fits two 80x53 xterms side by side.
262 Consequently, having excessively long functions is also a hindrance to
263 others, as such developers with limited screen resources would need to
264 continuously page-up and page-down to read the code even of a single
265 function, in full.
266
267 This helps explain in part, below, why compliance with
268 [pep8](https://pep8.org/) is enforced, including its 80 character limit.
269 In short: not everyone has the same "modern" GUI workflow or has access
270 to the same computing resources as you, so please do respect that.
271
272 More on this concept is
273 [here](https://www.linuxjournal.com/content/line-length-limits).
274 Note *very pointedly* that Linus Torvalds *specifically* states that
275 he does not want Linux kernel development to become the exclusive
276 domain of the "wealthy". That means **no** to assumptions about
277 access to ultra-high resolution screens.
278
279 # Software prerequisites
280
281 Whilst many resources online advocate "`sudo`" in front of all root-level
282 commands below, this quickly becomes tiresome. run "`sudo bash`", get a
283 root prompt, and save yourself some typing.
284
285 * sudo bash
286 * apt-get install vim exuberant-ctags
287 * apt-get install build-essential
288 * apt-get install git python3.7 python3.7-dev python-nosetest3
289 * apt-get install graphviz xdot gtkwave
290 * apt-get install python3-venv
291 * apt-get install python-virtualenv # this is an alternative to python3-venv
292 * apt-get install tcl-dev libreadline-dev bison flex libffi-dev iverilog
293 * return to user prompt (ctrl-d)
294
295 (The above assumes that you are running Debian.)
296
297 This will get you python3 and other tools that are
298 needed. [graphviz](https://graphviz.org/) is essential
299 for showing the interconnections between cells, and
300 [gtkwave](http://gtkwave.sourceforge.net/) is essential for debugging.
301
302 If you would like to save yourself a lot more typing, check out the
303 [dev-env-setup](https://git.libre-soc.org/?p=dev-env-setup.git;a=summary)
304 repository, examine the scripts there and use them to automate much of
305 the process below.
306
307 ## git
308
309 Look up good tutorials on how to use git effectively. There are so many
310 it is hard to recommend one. This is however essential. If you are not
311 comfortable with git, and you let things stay that way, it will seriously
312 impede development progress.
313
314 If working all day you should expect to be making at least two commits per
315 hour, so should become familiar with it very quickly. If you are *not*
316 doing around 2 commits per hour, something is wrong and you should read
317 the workflow instructions below more carefully, and also ask for advice
318 on the mailing list.
319
320 Worth noting: *this project does not use branches*. All code is committed
321 to master and we *require* that it be either zero-impact additions or that
322 relevant unit tests pass 100%. This ensures that people's work does not
323 get "lost" or isolated and out of touch due to major branch diversion,
324 and that people communicate and coordinate with each other.
325
326 ## yosys
327
328 Follow the source code (git clone) instructions here:
329 <http://www.clifford.at/yosys/download.html>
330
331 Or, alternatively, use the
332 [yosys-et-al](https://git.libre-soc.org/?p=dev-env-setup.git;a=blob;f=yosys-et-al;hb=HEAD)
333 script (which also installs symbiyosys and its dependencies)
334
335 Do not try to use a fixed revision of yosys (currently 0.9), nmigen is
336 evolving and frequently interacts with yosys.
337
338 [Yosys](http://www.clifford.at/yosys/) is a framework for Verilog RTL.
339 [Verilog](https://en.wikipedia.org/wiki/Verilog) is a hardware description
340 language.
341 RTL [Register Transfer
342 Level](https://en.wikipedia.org/wiki/Register-transfer_level)
343 models how data moves between
344 [registers](https://en.wikipedia.org/wiki/Hardware_register).
345
346 ## symbiyosys
347
348 To install follow the [instructions
349 here](https://symbiyosys.readthedocs.io/en/latest/install.html)
350 Once done look at [A simple BMC
351 example](https://symbiyosys.readthedocs.io/en/latest/quickstart.html)
352
353 You do not have to install all of those (avy, boolector can be left
354 out if desired) however the more that are installed the more effective
355 the formal proof scripts will be (less resource utilisation in certain
356 circumstances).
357
358 [SymbiYosys](https://symbiyosys.readthedocs.io/en/latest/) (sby) is a
359 front-end driver program for Yosys-based formal hardware verification
360 flows.
361
362 ## nmigen
363
364 [nmigen](https://m-labs.hk/gateware/nmigen/) may be installed as follows:
365
366 * mkdir ~/src
367 * cd !$
368 * git clone https://github.com/nmigen/nmigen.git
369 * cd nmigen
370 * sudo bash
371 * python3 setup.py develop
372 * ctrl-d
373
374 Testing can then be carried out with "python3 setup.py test"
375
376 nmigen is a Python toolbox for building complex digital hardware.
377
378 ## Softfloat and sfpy
379
380 These are a test suite dependency for the
381 [ieee754fpu](https://www.gaisler.com/index.php/products/ipcores/ieee754fpu)
382 library, and will be changed in the future to use Jacob's
383 [simple-soft-float](https://crates.io/crates/simple-soft-float) library.
384 In the meantime, sfpy can be built as follows:
385
386 git clone --recursive https://github.com/billzorn/sfpy.git
387 cd sfpy
388 cd SoftPosit
389 git apply ../softposit_sfpy_build.patch
390 git apply /path/to/ieee754fpu/SoftPosit.patch
391 cd ../berkely-softfloat-3
392 # Note: Do not apply the patch included in sfpy for berkely-softfloat,
393 # it contains the same changes as this one
394 git apply /path/to/ieee754fpu/berkeley-softfloat.patch
395 cd ..
396
397 # prepare a virtual environment for building
398 python3 -m venv .env
399
400 # or, if you prefer the old way:
401 # virtualenv -p python3 .env
402
403 # install dependencies
404 source .env/bin/activate
405 pip3 install --upgrade -r requirements.txt
406
407 # build
408 make lib -j$(nproc)
409 make cython
410 make inplace -j$(nproc)
411 make wheel
412
413 # install
414 deactivate # deactivates venv, optional
415 pip3 install dist/sfpy*.whl
416
417 You can test your installation by doing the following:
418
419 python3
420 >>> from sfpy import *
421 >>> Posit8(1.3)
422
423 It should print out `Posit8(1.3125)`
424
425 ## qemu, cross-compilers, gdb
426
427 As we are doing POWER ISA, POWER ISA compilers, toolchains and
428 emulators are required.
429
430 Install powerpc64 gcc:
431
432 apt-get install gcc-9-powerpc64-linux-gnu
433
434 Install qemu:
435
436 apt-get install qemu-system-ppc
437
438 Install gdb from source. Obtain the latest tarball, unpack it, then:
439
440 cd gdb-9.1 (or other location)
441 mkdir build
442 cd build
443 ../configure --srcdir=.. --host=x86_64-linux --target=powerpc64-linux-gnu
444 make -j$(nproc)
445 make install
446
447 [gdb](https://en.wikipedia.org/wiki/GNU_Debugger) lets you debug running
448 programs. [qemu](https://www.qemu.org/) emulates processors, you can
449 run programs under qemu.
450
451 ## power_instruction_analyzer (pia)
452
453 We have a custom tool built in rust by programmerjake to help analyze
454 the power instructions execution on *actual* hardware.
455
456 Note: a very recent version of pip3 is required for this to work.
457
458 Install rust:
459
460 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
461
462 Make sure we have the correct and up-to-date rust compiler (rustc):
463
464 rustup default stable
465 rustup update
466
467 Use rust's package manager *cargo* to install the rust-python build
468 tool maturin:
469
470 cargo install maturin
471
472 Install from git source by doing the following:
473
474 git clone https://salsa.debian.org/Kazan-team/power-instruction-analyzer.git pia
475 cd pia
476 maturin build --cargo-extra-args=--features=python-extension
477 python3 -m pip install --user target/wheels/*.whl
478
479 Note: an ongoing bug in maturin interferes with successful installation.
480 This can be worked around by explicitly installing only the `.whl`
481 files needed rather than installing everything (`\*.whl`).
482
483 ## Chips4Makers JTAG
484
485 As this is an actual ASIC, we do not rely on an FPGA's JTAG TAP
486 interface, instead require a full complete independent implementation
487 of JTAG. Staf Verhaegen has one, with a full test suite, and it is
488 superb and well-written. The Libre-SOC version includes DMI (Debug
489 Memory Interface):
490
491 git clone https://git.libre-soc.org/git/c4m-jtag.git/
492
493 Included is an IDCODE tap point, Wishbone Master (for direct memory read
494 and write, fully independent of the core), IOPad redirection and testing,
495 and general purpose shift register capability for any custom use.
496
497 We added a DMI to JTAG bridge in LibreSOC which is
498 directly connected to the core, to access registers and
499 to be able to start and stop the core and change the PC.
500 In combination with the JTAG Wishbone interface the test
501 [ASIC](https://en.wikipedia.org/wiki/Application-specific_integrated_circuit)
502 can have a bootloader uploaded directly into onboard
503 [SRAM](https://en.wikipedia.org/wiki/Static_random-access_memory) and
504 execution begun.
505
506 [Chips4Makers](https://chips4makers.io/) make it possible for makers
507 and hobbyists to make their own open source chips.
508
509 [JTAG](https://en.wikipedia.org/wiki/JTAG) (Joint Test Action Group) is
510 an industry standard for verifying designs and testing printed circuit
511 boards after manufacture.
512
513 The [Wishbone
514 bus](https://en.wikipedia.org/wiki/Wishbone_%28computer_bus%29) is an open
515 source hardware computer bus intended to let the parts of an integrated
516 circuit communicate with each other.
517
518 ## Coriolis2
519
520 See [[HDL_workflow/coriolis2]] page, for those people doing layout work.
521
522 # Registering for git repository access
523
524 After going through the onboarding process and having agreed to take
525 responsibility for certain tasks, ask on the mailing list for git
526 repository access, sending in a public key (`id_rsa.pub`). If you do
527 not have one then generate it with `ssh-keygen -t rsa`. You will find it
528 in `~/.ssh`
529
530 NEVER SEND ANYONE THE PRIVATE KEY. By contrast the public key, on
531 account of being public, is perfectly fine to make... err... public.
532
533 Create a file `~/.ssh/config` with the following lines:
534
535 Host git.libre-soc.org
536 Port 922
537
538 Wait for the Project Admin to confirm that the ssh key has been added
539 to the required repositories. Once confirmed, you can clone any of the
540 repos at https://git.libre-soc.org/:
541
542 git clone gitolite3@git.libre-soc.org:REPONAME.git
543
544 Alternatively, the .ssh/config can be skipped and this used:
545
546 git clone ssh://gitolite3@git.libre-soc.org:922/REPONAME.git
547
548 # git configuration
549
550 Although there are methods online which describe how (and why) these
551 settings are normally done, honestly it is simpler and easier to open
552 ~/.gitconfig and add them by hand.
553
554 core.autocrlf is a good idea to ensure that anyone adding DOS-formatted
555 files they don't become a pain. pull.rebase is something that is greatly
556 preferred for this project because it avoids the mess of "multiple
557 extra merge git tree entries", and branch.autosetuprebase=always will,
558 if you want it, always ensure that a new git checkout is set up with rebase.
559
560 [core]
561 autocrlf = input
562 [push]
563 default = simple
564 [pull]
565 rebase = true
566 [branch]
567 autosetuprebase = always
568
569 # Checking out the HDL repositories
570
571 Before running the following, install the
572 dependencies. This is easiest done with this script
573 <https://git.libre-soc.org/?p=dev-env-setup.git;a=blob;f=install-hdl-apt-reqs;hb=HEAD>
574
575 * mkdir ~/src
576 * cd !$
577 * git clone gitolite3@git.libre-soc.org:nmutil.git
578 * git clone gitolite3@git.libre-soc.org:ieee754fpu.git
579 * git clone gitolite3@git.libre-soc.org:nmigen-soc.git
580 * git clone gitolite3@git.libre-soc.org:soc.git
581
582 In each of these directories, in the order listed, track down the
583 `setup.py` file, then, as root (`sudo bash`), run the following:
584
585 * python3 setup.py develop
586
587 The reason for using "develop" mode is that the code may be edited
588 in-place yet still imported "globally". There are variants on this theme
589 for multi-user machine use however it is often just easier to get your
590 own machine these days.
591
592 The reason for the order is because soc depends on ieee754fpu, and
593 ieee754fpu depends on nmutil
594
595 If "`python3 setup.py install`" is used it is a pain: edit, then
596 install. edit, then install. It gets extremely tedious, hence why
597 "develop" was created.
598
599 # Development Rules
600
601 Team communication:
602
603 * new members, add yourself to the [[about_us]] page and create yourself a home page using someone else's page as a template.
604 * communicate on the mailing list or the bugtracker an intent to take
605 responsibility for a particular task.
606 * assign yourself as the bug's owner
607 * *keep in touch* about what you are doing, and why you are doing it.
608 * edit your home page regularly, particularly to track tasks so that
609 they can be paid by NLNet.
610 * if you cannot do something that you have taken responsibility for,
611 then unless it is a dire personal emergency please say so, on-list. we
612 won't mind. we'll help sort it out.
613
614 Regarding the above it is important that you read, understand, and agree
615 to the [[charter]] because the charter is about ensuring that we operate
616 as an effective organisation. It's *not* about "setting rules and meting
617 out punishment".
618
619 ## Coding
620
621 for actual code development
622
623 ### Plan unit tests
624
625 * plan in advance to write not just code but a full test suite for
626 that code. **this is not optional**. large python projects that do not
627 have unit tests **FAIL** (see separate section below).
628 * Prioritise writing formal proofs and a single clear unit test that is more
629 like a "worked example".
630 We receive NLNet funds for writing formal proofs, plus they
631 cover corner cases and take far less time to write
632
633 ### Commit tested or zero-dependent code
634
635 * only commit code that has been tested (or is presently unused). other
636 people will be depending on you, so do take care not to screw up.
637 not least because, as it says in the [[charter]] it will be your
638 responsibility to fix. that said, do not feel intimidated: ask for help
639 and advice, and you'll get it straight away.
640
641 ### Commit often
642
643 * commit often. several times a day, and "git push" it. this is
644 collaboration. if something is left even overnight uncommitted and not
645 pushed so that other people can see it, it is a red flag. if you find
646 yourself thinking "i'll commit it when it's finished" or "i don't want to
647 commit something that people might criticise" *this is not collaboration*,
648 it is making yourself a bottleneck. pair-programming is supposed to help
649 avoid this kind of thing however pair-programming is difficult to organise
650 for remote collaborative libre projects (suggestions welcomed here)
651
652 ### Enable editor auto-detection of file changes by external programs
653
654 This is important. "`git pull`" will merge in changes. If you then
655 arbitrarily save a file without re-loading it, you risk destroying
656 other people's work.
657
658 ### Absolutely no auto-generated output
659
660 * **do not commit autogenerated output**. write a shell script and commit
661 that, or add a `Makefile` to run the command that generates the output, but
662 **do not** add the actual output of **any** command to the repository.
663 ever. this is really important. even if it is a human-readable file
664 rather than a binary object file.
665 it is very common to add pdfs (the result of running `latex2pdf`) or
666 configure.in (the result of running `automake`), they are an absolute
667 nuisance and interfere hugely with git diffs, as well as waste hard
668 disk space *and* network bandwidth. don't do it.
669
670 ### Write commands that do tasks and commit those
671
672 * if the command needed to create any given autogenerated output is not
673 currently in the list of known project dependencies, first consult on
674 the list if it is okay to make that command become a hard dependency of
675 the project (hint: java, node.js php and .NET commands may cause delays
676 in response time due to other list participants laughing hysterically),
677 and after a decision is made, document the dependency and how its source
678 code is obtained and built (hence why it has to be discussed carefully)
679 * if you find yourself repeating commands regularly, chances are high
680 that someone else will need to run them, too. clearly this includes
681 yourself, therefore, to make everyone's lives easier including your own,
682 put them into a `.sh` shell script (and/or a `Makefile`), commit them to
683 the repository and document them at the very minimum in the README,
684 INSTALL.txt or somewhere in a docs folder as appropriate. if unsure,
685 ask on the mailing list for advice.
686
687 ### Keep commits single-purpose
688
689 * edit files making minimal *single purpose* modifications (even if
690 it involves multiple files. Good extreme example: globally changing
691 a function name across an entire codebase is one purpose, one commit,
692 yet hundreds of files. miss out one of those files, requiring multiple
693 commits, and it actually becomes a nuisance).
694
695 ### Run unit tests prior to commits
696
697 * prior to committing make sure that relevant unit tests pass, or that
698 the change is a zero-impact addition (no unit tests fail at the minimum)
699
700 ### Do not break existing code
701
702 * keep working code working **at all times**. find ways to ensure that
703 this is the case. examples include writing alternative classes that
704 replace existing functionality and adding runtime options to select
705 between old and new code.
706
707 ### Small commits with relevant commit message
708
709 * commit no more than around 5 to 10 lines at a time, with a CLEAR message
710 (no "added this" or "changed that").
711 * if as you write you find that the commit message involves a *list* of
712 changes or the word "and", then STOP. do not proceed: it is a "red flag"
713 that the commit has not been properly broken down into separate-purpose
714 commits. ask for advice on-list on how to proceed.
715
716 ### Exceptions to small commit: atomic single purpose commit
717
718 * if it is essential to commit large amounts of code, ensure that it
719 is **not** in use **anywhere** by any other code. then make a *small*
720 (single purpose) followup commit which actually puts that code into use.
721
722 This last rule is kinda flexible, because if you add the code *and* add
723 the unit test *and* added it into the main code *and* ran all relevant
724 unit tests on all cascade-impacted areas by that change, that's perfectly
725 fine too. however if it is the end of a day, and you need to stop and
726 do not have time to run the necessary unit tests, do *not* commit the
727 change which integrates untested code: just commit the new code (only)
728 and follow up the next day *after* running the full relevant unit tests.
729
730 ### Why such strict rules?
731
732 The reason for all the above is because python is a dynamically typed
733 language. make one tiny change at the base level of the class hierarchy
734 and the effect may be disastrous.
735
736 It is therefore worth reiterating: make absolutely certain that you *only*
737 commit working code or zero-impact code.
738
739 Therefore, if you are absolutely certain that a new addition (new file,
740 new class, new function) is not going to have any side-effects, committing
741 it (a large amount of code) is perfectly fine.
742
743 As a general rule, however, do not use this an an excuse to write code
744 first then write unit tests as an afterthought. write *less* code *in
745 conjunction* with its (more basic) unit tests, instead. then, folliw up with
746 additions and improvements.
747
748 The reason for separating out commits to single purpose only becomes
749 obvious (and regretted if not followed) when, months later, a mistake
750 has to be tracked down and reverted. if the commit does not have an
751 easy-to-find message, it cannot even be located, and once found, if the
752 commit confuses several unrelated changes, not only the diff is larger
753 than it should be, the reversion process becomes extremely painful.
754
755 ### PEP8 format
756
757 * all code needs to conform to pep8. use either pep8checker or better
758 run autopep8. however whenever committing whitespace changes, *make a
759 separate commit* with a commit message "whitespace" or "autopep8 cleanup".
760 * pep8 REQUIRES no more than 80 chars per line. this is non-negotiable. if
761 you think you need greater than 80 chars, it *fundamentally* indicates
762 poor code design. split the code down further into smaller classes
763 and functions.
764
765 ### Docstring checker
766
767 * TBD there is a docstring checker. at the minimum make sure to have
768 an SPD license header, module header docstring, class docstring and
769 function docstrings on at least non-obvious functions.
770
771 ### Clear code commenting and docstrings
772
773 * make liberal but not excessive use of comments. describe a group of
774 lines of code, with terse but useful comments describing the purpose,
775 documenting any side-effects, and anything that could trip you or other
776 developers up. unusual coding techniques should *definitely* contain
777 a warning.
778
779 ### Only one class per module (ish)
780
781 * unless they are very closely related, only have one module (one class)
782 per file. a file only 25 lines long including imports and docstrings
783 is perfectly fine however don't force yourself. again, if unsure,
784 ask on-list.
785
786 ### File and Directory hierarchy
787
788 * *keep files short and simple*. see below as to why
789 * create a decent directory hierarchy but do not go mad. ask for advice
790 if unsure
791
792 ### No import star!
793
794 * please do not use "from module import \*". it is extremely bad practice,
795 causes unnecessary resource utilisation, makes code readability and
796 tracking extremely difficult, and results in unintended side-effects.
797
798 Example: often you want to find the code from which a class was imported.
799 nirmally you go to the top of the file, check the imports, and you know
800 exactly which file has the class because of the import path. by using
801 wildcards, you have absolutely *no clue* which wildcard imported which
802 class or classes.
803
804 Example: sometimes you may accidentally have duplicate code maintained
805 in two or more places. editing one of them you find, puzzlingly, that
806 the code behaves in some files with the old behaviour, but in others it
807 works. after a massive amount of investigation, you find that the working
808 files happen to have a wildcard import of the newer accidental duplicate
809 class **after** the wildcard import of the older class with exactly the
810 same name. if you had used explicit imports, you would have spotted
811 the double import of the class from two separate locations, immediately.
812
813 Really. don't. use. wildcards.
814
815 ### Keep file and variables short but clear
816
817 * try to keep both filenames and variable names short but not ridiculously
818 obtuse. an interesting compromise on imports is "from ridiculousfilename
819 import longsillyname as lsn", and to assign variables as well: "comb =
820 m.d.comb" followed by multiple "comb += nmigen_stmt" lines is a good trick
821 that can reduce code indentation by 6 characters without reducing clarity.
822
823 Additionally, use comments just above an obtuse variable in order to
824 help explain what it is for. In combination with keeping the the module
825 itself short, other readers will not need to scroll back several pages
826 in order to understand the code.
827
828 Yes it is tempting to actually use the variables as
829 self-explanatory-comments and generally this can be extremely good
830 practice. the problem comes when the variable is so long that a function
831 with several parameters csn no longer fit on a single line, and takes
832 up five to ten lines rather than one or two. at that point, the length
833 of the code is adversely affected and thus so is readability by forcing
834 readers to scroll through reams of pages.
835
836 It is a tricky balance: basically use your common sense, or just ask
837 someone else, "can you understand this code?"
838
839 ### Reasons for code structure
840
841 Regarding code structure: we decided to go with small modules that are
842 both easy to analyse, as well as fit onto a single page and be readable
843 when displayed as a visual graph on a full UHD monitor. this is done
844 as follows:
845
846 * using the capability of nmigen (TODO crossref to example) output the
847 module to a yosys ilang (.il) file
848 * in a separate terminal window, run yosys
849 * at the yosys prompt type "read_ilang modulename.il"
850 * type "show top" and a graphviz window should appear. note that typing
851 show, then space, then pressing the tab key twice will give a full list
852 of submodules (one of which will be "top")
853
854 You can now fullsize the graphviz window and scroll around. if it looks
855 reasonably obvious at 100% zoom, i.e the connections can be clearly
856 related in your mind back to the actual code (by matching the graph names
857 against signals and modules in the original nmigen code) and the words are
858 not tiny when zoomed out, and connections are not total incomprehensible
859 spaghetti, then congratulations, you have well-designed code. If not,
860 then this indicates a need to split the code further into submodules
861 and do a bit more work.
862
863 The reasons for doing a proper modularisation job are several-fold:
864
865 * firstly, we will not be doing a full automated layout-and-hope
866 using alliance/coriolis2, we will be doing leaf-node thru tree node
867 half-automated half-manual layout, finally getting to the floorplan,
868 then revising and iteratively adjusting.
869 * secondly, examining modules at the gate level (or close to it) is just
870 good practice. poor design creeps in by *not* knowing what the tools
871 are actually doing (word to experienced developers: yes, we know that
872 the yosys graph != final netlist).
873 * thirdly, unit testing, particularly formal proofs, is far easier on
874 small sections of code, and complete in a reasonable time.
875
876 ## Special warning / alert to vim users!
877
878 Some time around the beginning of 2019 some bright spark decided that
879 an "auto-recommend-completion-of-stuff" option would be a nice, shiny
880 idea to enable by default from that point onwards.
881
882 This incredibly annoying "feature" results in tabs (or spaces) being
883 inserted "on your behalf" when you press return on one line, for your
884 "convenience" of not needing to type lots of spaces/tabs just to get
885 to the same indentation level.
886
887 Of course, this "feature", if you press return on one line in edit
888 mode and then press "escape", leaves a bundle-of-joy extraneous
889 whitespace **exactly** where you don't want it, and didn't ask for it,
890 pooped all over your file.
891
892 Therefore, *please*: **before** running "git commit", get into the
893 habit of always running "git diff", and at the very minimum
894 speed-skim the entire diff, looking for tell-tale "red squares"
895 (these show up under bash diff colour-syntax-highlighting) that
896 inform you that, without your knowledge or consent, vim has
897 "helpfully" inserted extraneous whitespace.
898
899 Remove them **before** git committing because they are not part
900 of the actual desired code-modifications, and committing them
901 is a major and constant distraction for reviewers about actual
902 important things like "the code that actually *usefully* was
903 modified for that commit"
904
905 This has the useful side-effect of ensuring that, right before
906 the commit, you've got the actual diff right in front of you
907 in the xterm window, on which you can base the "commit message".
908
909 ## Unit tests
910
911 For further reading, see the wikipedia page on
912 [Test-driven Development](https://en.wikipedia.org/wiki/Test-driven_development)
913
914 This deserves its own special section. It is extremely important to
915 appreciate that without unit tests, python projects are simply unviable.
916 Python itself has over 25,000 individual tests.
917
918 This can be quite overwhelming to a beginner developer, especially one
919 used to writing scripts of only 100 lines in length.
920
921 Thanks to Samuel Falvo we learned that writing unit tests as a formal
922 proof is not only shorter, it's also far more readable and also, if
923 written properly, provides 100% coverage of corner-cases that would
924 otherwise be overlooked or require tens to hundreds of thousands of
925 tests to be run.
926
927 No this is not a joke or even remotely hypothetical, this is an actual
928 real-world problem.
929
930 The ieee754fpu requires several hundreds of thousands of tests to be
931 run (currently needing several days to run them all), and even then we
932 cannot be absolutely certain that all possible combinations of input have
933 been tested. With 2^128 permutations to try with 2 64 bit FP numbers
934 it is simply impossible to even try.
935
936 This is where formal proofs come into play.
937
938 Samuel illustrated to us that "ordinary" unit tests can then be written
939 to *augment* the formal ones, serving the purpose of illustrating how
940 to use the module, more than anything.
941
942 However it is appreciated that writing formal proofs is a bit of a
943 black art. This is where team collaboration particularly kicks in,
944 so if you need help, ask on the mailing list.
945
946 ## Don't comment out unit tests: add them first (as failures) and fix code later
947
948 Unit tests serve an additional critical purpose of keeping track of code
949 that needs to be written. In many cases, you write the unit test *first*,
950 despite knowing full well that the code doesn't even exist or is completely
951 broken. The unit test then serves as a constant and important reminder
952 to actually fix (or write) the code.
953
954 Therefore, *do not* comment out unit tests just because they "don't work".
955 If you absolutely must stop a unit test from running, **do not delete it**.
956 Simply mark it with an appropriate
957 ["skip" decorator](https://docs.python.org/3/library/unittest.html#skipping-tests-and-expected-failures),
958 preferably with a link to a URL in the [bugtracker](https://bugs.libre-soc.org/)
959 with further details as to why the unit test should not be run.
960
961 # TODO Tutorials
962
963 Find appropriate tutorials for nmigen and yosys, as well as symbiyosys.
964
965 * Robert Baruch's nmigen tutorials look really good:
966 <https://github.com/RobertBaruch/nmigen-tutorial>
967 * Although a verilog example this is very useful to do
968 <https://symbiyosys.readthedocs.io/en/latest/quickstart.html#first-step-a-simple-bmc-example>
969 * This tutorial looks pretty good and will get you started
970 <http://blog.lambdaconcept.com/doku.php?id=nmigen:nmigen_install> and
971 walks not just through simulation, it takes you through using gtkwave
972 as well.
973 * There exist several nmigen examples which are also executable
974 <https://github.com/m-labs/nmigen/tree/master/examples/> exactly as
975 described in the above tutorial (python3 filename.py -h)
976