forked from schoeberl/chisel-book
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathchisel-book.tex
3776 lines (2900 loc) · 164 KB
/
chisel-book.tex
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[%draft,
10pt,
headinclude, footexclude,
% twoside, % this produces strange margins!
openright, % for new chapters
notitlepage,
cleardoubleempty,
headsepline,
pointlessnumbers,
bibtotoc, idxtotoc,
]{scrbook}
% iPad Air 2 resolution: 1536 x 2048
% 1.3333 ratio (4:3)
% LeeSeshia is 15,73 ? 20,96 cm, ratio 1.332
%\setlength{\paperwidth}{15.73cm} \setlength{\paperheight}{20.96cm}
\setlength{\paperwidth}{15.72cm} \setlength{\paperheight}{20.95cm}
%\typearea{calc} % without BCOR results to a DIV of 8 for 11pt
\typearea[1cm]{18} % TODO: check if 1 cm is the correct number
\usepackage{scrlayer-scrpage}
\setkomafont{pagehead}{\scshape\small}
\setkomafont{pagenumber}{\scshape\small}
\newif\ifbook
%\booktrue % comment out for the eBook version
\ifbook
\else
\cfoot{\hyperlink{contents}{{\textnormal{Contents}}}}
\fi
\usepackage{pslatex} % -- times instead of computer modern, especially for the plain article class
\usepackage[colorlinks=true,bookmarks=false]{hyperref}
\usepackage{booktabs}
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{multirow}
\usepackage{cite}
\usepackage{dirtree}
\usepackage{pdfpages}
% For alignment on tables
\usepackage{dcolumn}
\newcommand{\cc}[1]{\multicolumn{1}{c}{#1}}
\newcommand{\code}[1]{{\small{\texttt{#1}}}}
\newcommand{\codefoot}[1]{{\footnotesize{\texttt{#1}}}}
% fatter TT font
\renewcommand*\ttdefault{txtt}
% another TT, suggested by Alex
% \usepackage{inconsolata}
% \usepackage[T1]{fontenc} % needed as well?
\usepackage[procnames]{listings}
\ifbook
\hypersetup{
linkcolor = black,
citecolor = black,
urlcolor = black,
colorlinks = black,
bookmarks=false,
}
\else
\hypersetup{
linkcolor = blue,
citecolor = blue,
urlcolor = blue,
colorlinks = true,
bookmarks=true,
}
\fi
% not really used
\newenvironment{comment}
{ \vspace{-0.1in}
\begin{quotation}
\noindent
\small \em
\rule{\linewidth}{0.5pt}\\
}
{
\\
\rule{\linewidth}{0.5pt}
\end{quotation}
}
\newcommand{\scale}{0.7}
\input{shared/chisel.tex}
\newcommand{\todo}[1]{{\emph{TODO: #1}}}
\newcommand{\martin}[1]{{\color{blue} Martin: #1}}
\newcommand{\myref}[2]{\href{#1}{#2}}
\ifbook
\renewcommand{\myref}[2]{{#2}{\footnote{\url{#1}}}}
\fi
% uncomment following for final submission
\renewcommand{\todo}[1]{}
\renewcommand{\martin}[1]{}
\begin{document}
\ifbook
\else
\includepdf{chisel-cover.pdf}
\newpage
\thispagestyle{empty}
~
\newpage
\fi
\begin{flushleft}
\pagestyle{empty}
\ \\
\vspace{1cm}
{\usekomafont{title}\mdseries\huge Digital Design with Chisel}
\cleardoublepage
\end{flushleft}
\newpage
\begin{flushleft}
\pagestyle{empty}
\ \\
\vspace{1cm}
{\usekomafont{title}\Huge Digital Design with Chisel\\
\bigskip
\bigskip
\bigskip
\bigskip
\bigskip
%{\large\itshape Beta Edition}\\
\bigskip
{\usekomafont{title}\huge Martin Schoeberl}
\medskip\\
%{\large\itshape martin@jopdesign.com}
}
%\vspace{10cm} \emph{Version: \today}
\newpage
\end{flushleft}
\thispagestyle{empty}
\begin{flushleft}
{\small
%\lowertitleback{
Copyright \copyright{} 2016--2019 Martin Schoeberl
\medskip\\
\begin{tabular}{lp{.8\textwidth}}
\raisebox{-12pt}{\includegraphics[height=18pt]{figures/cc_by_sa}} &
This work is licensed under a Creative Commons Attribution-ShareAlike
4.0 International License.
\url{http://creativecommons.org/licenses/by-sa/4.0/}\\
\end{tabular}
%}
\medskip
Email: \url{martin@jopdesign.com}\\
Visit the source at \url{https://github.com/schoeberl/chisel-book}
\medskip
Published 2019 by Kindle Direct Publishing,\\
\url{https://kdp.amazon.com/}
\medskip
\medskip
\textbf{Library of Congress Cataloging-in-Publication Data}
\medskip
Schoeberl, Martin
\begin{quote}
Digital Design with Chisel\\
Martin Schoeberl\\
Includes bibliographical references.\\ \todo{and index. \\}
ISBN 9781689336031
\end{quote}
\bigskip
Manufactured in the United States of America.
Typeset by Martin Schoeberl.}
\end{flushleft}
\frontmatter
\phantomsection
\hypertarget{contents}{}
\tableofcontents
\begingroup
\let\cleardoublepage\clearpage
\listoffigures
\listoftables
\lstlistoflistings
\endgroup
%\chapter*{Foreword}
%
%Here comes the text.
%
%\bigskip
%
%Jonathan Bachrach, designer of Chisel
\chapter{Preface}
% This text goes on the backside of the book, and in Amazon description
This book is an introduction to digital design with the focus on using the hardware construction language Chisel. Chisel brings advances from software engineering, such as object-orientated and functional languages, into digital design.
This book addresses hardware designers and software engineers. Hardware designers, with knowledge of Verilog or VHDL, can upgrade their productivity with a modern language for their next ASIC or FPGA design. Software engineers, with knowledge of object-oriented and functional programming, can leverage their knowledge to program hardware, for example, FPGA accelerators executing in the cloud.
The approach of this book is to present small to medium-sized typical hardware components to explore digital design with Chisel.
% about me, backside
%Martin Schoeberl is Associate Professor at the Technical University of Denmark, where he is teaching digital electronics and computer architecture. His research interest is on hard real-time systems, time-predictable computer architecture, and real-time Java. He has more than 100 publications in peer reviewed journals, conferences, and books.
%Martin has been four times at UC Berkeley on research stays, where he has picked up Chisel and was in close contact with the developers of Chisel. He lead the research project T-CREST where most of the components have been written in Chisel.
\section*{Acknowledgements}
I want to thank everyone who has worked on Chisel for creating such
a cool hardware construction language. Chisel is so joyful to use and
therefore worth writing a book about.
I am thankful to the whole Chisel community, which is so welcoming and friendly
and never tired to answer questions on Chisel.
I would also like to thank my students in the last years of an advanced computer
architecture course where most of them picked up Chisel for the final project.
Thank you for moving out of your comfort zone and taking up the journey of
learning and using a bleeding-edge hardware description language.
Many of your questions have helped to shape this book.
\mainmatter
\chapter{Introduction}
\label{sec:intro}
This book is an introduction to digital system design using a modern hardware
construction language, \myref{https://chisel.eecs.berkeley.edu/}{Chisel}~\cite{chisel:dac2012}.
In this book, we focus on a higher abstraction level than usual in digital design books,
to enable you to build more complex, interacting digital systems in a shorter time.
This book and Chisel are targeting two groups of developers:
(1) hardware designers and (2) software programmers.
Hardware designers who are fluid in VHDL or Verilog and using other languages such as Python,
Java, or Tcl to generate hardware can move to a single hardware construction language
where hardware generation is part of the language and
Software programmers may become interested in hardware design,
e.g., as future chips from Intel will include programmable hardware to speed up programs.
It is perfectly fine to use Chisel as your first hardware description language.
Chisel brings advances in software engineering, such as object-orientated
and functional languages, into digital design.
Chisel does not only allow to express hardware at the register-transfer level
but allows you to write hardware generators.
Hardware is now commonly described with a hardware description language.
The time of drawing hardware components, even with CAD tools, is
over. Some high-level schematics can give an overview of the system but are
not intended to describe the system.
The two most common hardware description languages are Verilog and VHDL.
Both languages are old, contain many legacies, and have a moving line of what
constructs of the language are synthesizable to hardware.
Do not get me wrong: VHDL and Verilog are perfectly able to describe a hardware
block that can be synthesized into an
\myref{https://en.wikipedia.org/wiki/Application-specific_integrated_circuit}{ASIC}.
For hardware design in Chisel, Verilog serves as an intermediate language
for testing and synthesis.
This book is not a general introduction to hardware design and the fundamentals of it.
For an introduction of the basics in digital design, such as how to build a gate out of
CMOS transistors, refer to other digital design books.
However, this book intends to teach digital design at an abstraction level that is
current practice to describe ASICs or designs targeting
\myref{https://en.wikipedia.org/wiki/Field-programmable_gate_array}{FPGA}s.\footnote{As the author is more familiar with FPGAs
than ASICs as target technology, some design optimizations shown in this book are
targeting FPGA technology.}
As prerequisites for this book, we assume basic knowledge of
\myref{https://en.wikipedia.org/wiki/Boolean_algebra}{Boolean algebra} and the
\myref{https://en.wikipedia.org/wiki/Binary_number}{binary number system}.
Furthermore, some programming experience in any programming language
is assumed. No knowledge of Verilog or VHDL is needed.
Chisel can be your first programming language to describe digital hardware.
As the build process in the examples is based on \code{sbt} and \code{make}
basic knowledge of the command-line interface (CLI, also called terminal or
Unix shell) will be helpful.
Chisel itself is not a big language. The basic constructs fit on
\myref{https://chisel.eecs.berkeley.edu/doc/chisel-cheatsheet3.pdf}{one page}
and can be learned within a few days.
Therefore, this book is not a big book, as well.
Chisel is for sure smaller than VHDL and Verilog, which carry many legacies.
The power of Chisel comes from the embedding of Chisel within
\myref{https://www.scala-lang.org/}{Scala}, which itself in an expressive language.
Chisel inherits the feature from Scala being ``a language that grows on you''~\cite{Scala}.
However, Scala is not the topic of this book.
% We provide a short section on Scala for hardware designers, but
%A general introduction to Scala is better served by
The textbook by Odersky et al.~\cite{Scala} provides a general introduction
to Scala.
This book is a tutorial in digital design and the Chisel language; it is not
a Chisel language reference, nor is it a book on complete chip design.
All code examples shown in this book are extracted from complete programs
that have been compiled and tested. Therefore, the code shall not contain
any syntax errors. The code examples are available from the
\myref{https://github.com/schoeberl/chisel-book}{GitHub repository}
of this book.
Besides showing Chisel code, we have also tried to show useful designs and
principles of good hardware description style.
This book is optimized for reading on a laptop or tablet (e.g., an iPad).
We include links to further reading in the running text, mostly to
\myref{https://en.wikipedia.org/}{Wikipedia} articles.
\section{Installing Chisel and FPGA Tools}
Chisel is a Scala library, and the easiest way to install Chisel and Scala is
with \code{sbt}, the Scala build tool. Scala itself depends on the installation
of the \myref{https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html}{Java JDK 1.8}.
On Mac OS X, with the packet manager \myref{https://brew.sh/}{Homebrew},
\code{sbt} is installed with:
\begin{verbatim}
$ brew install sbt
\end{verbatim}
\noindent For Ubuntu, which is based on Debian, programs are usually installed from a
Debian file (.deb). However, as of the time of this writing \code{sbt} is not
available as a ready to install package. Therefore, the installation process
is a little bit more involved:
\begin{verbatim}
echo "deb https://dl.bintray.com/sbt/debian /" | \
sudo tee -a /etc/apt/sources.list.d/sbt.list
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 \
--recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823
sudo apt-get update
sudo apt-get install sbt
\end{verbatim}
Chisel and Scala can also be installed and used under Windows.
\code{sbt} can be installed with a Windows installer, see:
\myref{https://www.scala-sbt.org/1.x/docs/Installing-sbt-on-Windows.html}{Installing sbt on Windows}.
To build hardware for an FPGA, you need a synthesize tool. The two major
FPGA vendors, Intel\footnote{former Altera} and Xilinx, provide free versions of
their tools that cover small to medium-sized FPGAs. Those medium-sized
FPGAs are large enough to build multicore RISC style processors.
Intel provides the \myref{https://www.altera.com/products/design-software/fpga-design/quartus-prime/download.html}{Quartus Prime Lite Edition} and Xilinx the
\myref{https://www.xilinx.com/products/design-tools/vivado/vivado-webpack.html}{Vivado Design Suite, WebPACK Edition}.
\section{Hello World}
Each book on a programming language shall start with a minimal example,
called the \emph{Hello World} example. Following code is the first approach:
\shortlist{src/main/scala/HelloScala.scala}
\noindent Compiling and executing this short program with \code{sbt}
\begin{chisel}
$ sbt "runMain HelloScala"
\end{chisel}
\noindent leads to the expected output of a Hello World program:
\begin{chisel}
[info] Running HelloScala
Hello Chisel World!
\end{chisel}
\noindent However, is this Chisel? Is this hardware generated to print a string?
No, this is plain Scala code and not a representative Hello World
program for a hardware design.
\section{Chisel Hello World}
What is then the equivalent of a Hello World program for a hardware design?
The minimal useful and visible design? A blinking LED is the hardware (or even
embedded software) version of Hello World. If a LED blinks, we are ready to
solve bigger problems!
\longlist{code/hello.txt}{A hardware Hello World in Chisel}{lst:chisel:hello}
Listing~\ref{lst:chisel:hello} shows a blinking LED, described in Chisel.
It is not important that you understand the details of this code example.
We will cover those in the following chapters. Just note that the circuit is
usually clocked with a high frequency, e.g., 50 MHz, and we need a counter
to derive timing in the Hz range to achieve a visible blinking. In the above
example, we count from 0 up to 25000000-1 and then toggle the blinking signal
(\code{blkReg := \textasciitilde blkReg}) and restart the counter (\code{cntReg := 0.U}).
That hardware then blinks the LED at 1~Hz.
\section{An IDE for Chisel}
This book makes no assumptions about your programming environment or editor to use.
Learning of the basics should be easy with just using \code{sbt} at the command line
and an editor of your choice. In the tradition of other books, all commands that you
shall type in a shell/terminal/CLI are preceded by a \code{\$} character, which you
shall not type in. As an example, here is the Unix \code{ls} command, which lists files in
the current folder:
\begin{verbatim}
$ ls
\end{verbatim}
That said, an integrated development environment (IDE), where a compiler is running in
the background, can speed up coding. As Chisel is a Scala library, all IDEs
that support Scala are also good IDEs for Chisel.
It is possible in \myref{https://www.eclipse.org/}{Eclipse} and
\myref{https://www.jetbrains.com/help/idea/discover-intellij-idea-for-scala.html}{IntelliJ}
to generate a project from the sbt project configuration in \code{build.sbt}.
You can create an Eclipse project via
\begin{verbatim}
$ sbt eclipse
\end{verbatim}
and import that project into Eclipse.\footnote{This function needs the Eclipse plugin for sbt.}
In IntelliJ you can create a new project from existing sources and then select from \code{build.sbt}.
\myref{https://code.visualstudio.com/}{Visual Studio Code} with
\myref{https://marketplace.visualstudio.com/items?itemName=scalameta.metals/}{Scala Metals} requires
no setup beyond installing Visual Studio Code and the Scala Metals plugin. Scala Metals knows how to
set up everything including but not limited to code completion, Chisel source code download and
building based on \code{build.sbt}.
\section{Source Access and eBook Features}
This book is open source and hosted at GitHub: \myref{https://github.com/schoeberl/chisel-book}{chisel-book}.
All Chisel code examples, shown in this book, are included in the repository.
The code compiles with a recent version of Chisel, and many examples also include a test bench.
We collect larger Chisel examples in the accompanying repository \myref{https://github.com/schoeberl/chisel-examples}{chisel-examples}. If you find an error or typo in the book, a GitHub pull request is the most convenient way to incorporate your improvement.
You can also provide feedback or comments for improvements by filing an issue on GitHub
or sending a plain, old school email.
This book is freely available as a PDF eBook and in classical printed form.
The eBook version features links to further resources
and \myref{https://www.wikipedia.org/}{Wikipedia} entries.
We use Wikipedia entries for background information (e.g., binary number system)
that does not directly fit into this book.
We optimized the format of the eBook for reading on a tablet, such as an iPad.
\section{Further Reading}
Here a list of further reading for digital design and Chisel:
\begin{itemize}
\item \myref{http://www.cambridge.org/es/academic/subjects/engineering/circuits-and-systems/digital-design-systems-approach}{Digital Design: A Systems Approach}, by William J. Dally and R. Curtis Harting,
is a modern textbook on digital design. It is available in two versions: using Verilog or VHDL as a hardware description language.
\end{itemize}
The official Chisel documentation and further documents are available online:
\begin{itemize}
\item The \myref{https://chisel.eecs.berkeley.edu/}{Chisel} home page is the official starting point to
download and learn Chisel.
\item The \myref{https://github.com/ucb-bar/chisel-tutorial}{Chisel Tutorial} provides a ready setup
project containing small exercises with testers and solutions.
\item The \myref{https://github.com/freechipsproject/chisel3/wiki}{Chisel Wiki} contains
a short users guide to Chisel and links to further information.
\item The \myref{https://github.com/freechipsproject/chisel-testers}{Chisel Testers} are in
their repository that contains a Wiki documentation.
\item The \myref{https://github.com/ucb-bar/generator-bootcamp}{Generator Bootcamp} is
a Chisel course focusing on hardware generators, as a Jupyter notebook
\item A \myref{https://github.com/ccelio/chisel-style-guide}{Chisel Style Guide} by Christopher Celio.
\end{itemize}
\section{Exercise}
Each chapter ends with a hands-on exercise. For the introduction exercise, we will use an
FPGA board to get one \myref{https://en.wikipedia.org/wiki/Light-emitting_diode}{LED} blinking.
As a first step clone (or fork) the \myref{https://github.com/schoeberl/chisel-examples}{chisel-examples}
repository from GitHub.
The Hello World example is in the folder \code{hello-world}, set up as
a minimal project. You can explore the Chisel code of the blinking LED
in \code{src/main/scala/Hello.scala}.
Compile the blinking LED with the following steps:
\begin{chisel}
$ git clone https://github.com/schoeberl/chisel-examples.git
$ cd chisel-examples/hello-world/
$ make
\end{chisel}
After some initial downloading of Chisel components, this will produce the Verilog file \code{Hello.v}.
Explore this Verilog file. You will see that it contains two inputs \code{clock} and \code{reset}
and one output \code{io\_led}. When you compare this Verilog file with the Chisel module,
you will notice that the Chisel module does not contain \code{clock} or \code{reset}.
Those signals are implicitly generated, and in most designs, it is convenient not to need to
deal with these low-level details. Chisel provides register components, and those
are connected automatically to \code{clock} and \code{reset} (if needed).
The next step is to set up an FPGA project file for the synthesize tool, assign the pins,
and compile\footnote{The real process is more elaborated with following steps: synthesizing the logic,
performing place and route, performing timing analysis, and generating a bitfile.
However, for the purpose of this introduction example we simply call it ``compile''
your code.} the Verilog code, and configure the FPGA with the resulting bitfile.
We cannot provide the details of these steps. Please consult the manual of
your Intel Quartus or Xilinx Vivado tool.
However, the examples repository contains some ready to use Quartus
projects in folder \code{quartus} for several popular FPGA boards (e.g., DE2-115).
If the repository contains support for your board, start Quartus, open the project,
compile it by pressing the \emph{Play} button, and configure the FPGA board
with the \emph{Programmer} button and one of the LEDs should blink.
{\bf Gratulation! You managed to get your first design in Chisel running in an FPGA!}
If the LED is not blinking, check the status of reset. On the DE2-115 configuration,
the reset input is connected to SW0.
Now change the blinking frequency to a slower or a faster value and
rerun the build process. Blinking frequencies and also blinking patterns
communicate different ``emotions''. E.g., a slow blinking LED signals that
everything is ok, a fast blinking LED signals an alarm state.
Explore which frequencies express best those two different emotions.
As a more challenging extension to the exercise, generate the following blinking pattern:
the LED shall be on for 200~ms every second. For this pattern, you might
decouple the change of the LED blinking from the counter reset.
You will need a second constant where you change the state of the
\code{blkReg} register. What kind of emotion does this pattern produce?
Is it alarming or more like a sign-of-live signal?
\chapter{Basic Components}
In this section, we introduce the basic components for digital design:
combinational circuits and flip-flops.
These essential elements can be combined to build larger, more interesting circuits.
\section{Signal Types and Constants}
Chisel provides three data types to describe signals, combinational logic, and registers:
\code{Bits}, \code{UInt}, and \code{SInt}. \code{UInt} and \code{SInt} extend \code{Bits},
and all three types represent a vector of bits. \code{UInt} gives this vector of
bits the meaning of an unsigned integer and \code{SInt} of a signed
integer.\footnote{The type \codefoot{Bits} in the current version of Chisel is missing operations and
therefore not very useful for user code.}
Chisel uses \myref{https://en.wikipedia.org/wiki/Two\%27s\_complement}{two's complement}
as signed integer representation.
Here is the definition for different types, an 8-bit \code{Bits}, an 8-bit unsigned integer, and a 10-bit
signed integer:
\shortlist{code/types.txt}
\noindent The width of a vector of bits is defined by a Chisel width type (\code{Width}).
The following expression casts the Scala integer \code{n} to a Chisel \code{width},
which is used for the definition of the \code{Bits} vector:
\shortlist{code/n_w.txt}
\noindent Constants can be defined by using a Scala integer and converting it to a Chisel type:
\shortlist{code/constants.txt}
\noindent Constants can also be defined with a width, by using the Chisel width type:
\shortlist{code/const_width.txt}
\noindent If you find the notion of 8.U and 4.W a little bit funny, consider it as a variant of an integer
constant with a type. This notation is similar to 8L, representing a long integer constant in C, Java, and Scala.
Chisel benefits from Scala's type inference and in many places type information can be left out.
The same is also valid for bit widths. In many cases, Chisel will automatically infer the correct width.
Therefore, a Chisel description of hardware is more concise and better readable than VHDL or
Verilog.
For constants defined in other bases than decimal, the constant is defined in a string with
a preceding \code{h} for hexadecimal (base 16), \code{o} for octal (base 8), and \code{b}
for binary (base 2). The following example shows the definition of constant 255 in different
bases. In this example we omit the bit width and Chisel infers the minimum width to fit
the constants in, in this case 8 bits.
\shortlist{code/const_base.txt}
\noindent The above code shows how to use an underscore to group digits in the
string that represents a constant. The underscore is ignored.
To represent logic values, Chisel defines the type \code{Bool}.
\code{Bool} can represent a \emph{true} or \emph{false} value.
The following code shows the definition of type \code{Bool} and the definition of
\code{Bool} constants, by converting the Scala Boolean constants \code{true}
and \code{false} to Chisel \code{Bool} constants.
\shortlist{code/bool.txt}
\section{Combinational Circuits}
Chisel uses \myref{https://en.wikipedia.org/wiki/Boolean_algebra}{Boolean algebra} operators,
as they are defined in C, Java, Scala, and several other programming languages,
to described combinational circuits: \code{\&} is the AND operator and \code{|} is
the OR operator.
Following line of code defines a circuit that combines signals \code{a} and \code{b} with \emph{and}
gates and combines the result with signal \code{c} with \emph{or} gates.
\shortlist{code/logic.txt}
\begin{figure}
\centering
\includegraphics[scale=\scale]{figures/logic}
\caption{Logic for the expression \code{(a \& b) | c}.
The wires can be a single bit or multiple bits. The Chisel expression, and the schematics are the same.}
\label{fig:logic}
\end{figure}
Figure~\ref{fig:logic} shows the schematic of this combinatorial expression.
Note that this circuit may be for a vector of bits and not only single wires
that are combined with the AND and OR circuits.
In this example, we do not define the type nor the width of signal \code{logic}.
Both are inferred from the type and width of the expression.
The standard logic operations in Chisel are:
\shortlist{code/bool_ops.txt}
\noindent The arithmetic operations use the standard operators:
\shortlist{code/arith_ops.txt}
\noindent The resulting width of the operation is the maximum width of the operators for
addition and subtraction, the sum of the two widths for the multiplication, and usually
the width of the numerator for divide and modulo operations.\footnote{The exact
details are available in the \myref{https://github.com/freechipsproject/firrtl/blob/master/spec/spec.pdf}{FIRRTL specification}.}
A signal can also first be defined as a \code{Wire} of some type. Afterward, we can assign a
value to the wire with the \code{:=} update operator.
\shortlist{code/wire.txt}
A single bit can be extracted as follows:
\shortlist{code/single_bit.txt}
\noindent A subfield can be extracted from end to start position:
\shortlist{code/sub_field.txt}
\noindent Bit fields are concatenated with \code{Cat}.
\shortlist{code/concat.txt}
Table~\ref{tab:operators} shows the full list of operators
(see also \myref{https://github.com/freechipsproject/chisel3/wiki/Builtin-Operators}{builtin operators}).
The Chisel operator precedence is determined by the evaluation order of the circuit,
which follows the \myref{https://docs.scala-lang.org/tour/operators.html}{Scala operator precedence}.
If in doubt, it is always a good praxis to use parentheses.\footnote{The operator precedence in
Chisel is a side effect of the hardware elaboration when the tree of hardware nodes
is created by executing the Scala operators. The Scala operator precedence is similar but
not identical to Java/C. Verilog has the same operator precedence as C, but VHDL
has a different one. Verilog has precedence ordering for logic operations, but in VHDL
those operators have the same precedence and are evaluated from left to right.}
Table~\ref{tab:functions} shows various functions defined on and for Chisel data types.
\begin{table}
\centering
\label{tab:operators}
\begin{tabular}{lll}
\toprule
Operator & Description & Data types \\
\midrule
\code{* / \%} & multiplication, division, modulus & UInt, SInt \\
\code{+ -} & addition, subtraction & UInt, SInt \\
\code{=== =/=} & equal, not equal & UInt, SInt, returns Bool \\
\code{> >= < <=} & comparison & UInt, SInt, returns Bool \\
\code{<< >>} & shift left, shift right (sign extend on SInt) & UInt, SInt \\
\code{\~} & NOT & UInt, SInt, Bool \\
\code{\& | \^} & AND, OR, XOR & UInt, SInt, Bool \\
\code{!} & logical NOT & Bool \\
\code{\&\& ||} & logical AND, OR & Bool \\
\bottomrule
\end{tabular}
\caption{Chisel defined hardware operators.}
\end{table}
\begin{table}
\centering
\label{tab:functions}
\begin{tabular}{lll}
\toprule
Function & Description & Data types \\
\midrule
\code{v.andR v.orR v.xorR} & AND, OR, XOR reduction & UInt, SInt, returns Bool \\
\code{v(n)} & extraction of a single bit & UInt, SInt \\
\code{v(end, start)} & bitfield extraction & UInt, SInt \\
\code{Fill(n, v)} & bitstring replication, n times & UInt, SInt \\
\code{Cat(a, b, ...)} & bit field concatenation & UInt, SInt \\
\bottomrule
\end{tabular}
\caption{Chisel defined hardware functions, invoked on \code{v}.}
\end{table}
\subsection{Multiplexer}
A \myref{https://en.wikipedia.org/wiki/Multiplexer}{multiplexer} is a circuit that selects between alternatives.
In the most basic form, it selects between two alternatives. Figure~\ref{fig:mux} shows
such a 2:1 multiplexer, or mux for short. Depending on the value of the
select signal (\code{sel}) signal \code{y} will represent signal \code{a} or
signal \code{b}.
\begin{figure}
\centering
\includegraphics[scale=\scale]{figures/mux}
\caption{A basic 2:1 multiplexer.}
\label{fig:mux}
\end{figure}
A multiplexer can be built from logic.
However, as multiplexing is such a standard operation, Chisel provides a multiplexer,
\shortlist{code/mux.txt}
\noindent where \code{a} is selected when the \code{sel} is \code{true.B}, otherwise \code{b}
is selected. The type of \code{sel} is a Chisel \code{Bool}; the inputs \code{a} and \code{b}
can be any Chisel base type or aggregate (bundles or vectors) as long as they are the same
type.
With logical and arithmetical operations and a multiplexer, every combinational
circuit can be described. However, Chisel provides further components and control abstractions
for a more elegant description of a combinational circuit, which are described in
a later chapter.
The second basic component needed to describe a digital circuit is a state element,
also called register, which is described next.
\section{Registers}
Chisel provides a register, which is a collection of
\myref{https://en.wikipedia.org/wiki/Flip-flop\_(electronics)\#D\_flip-flop}{D flip-flops}.
The register is implicitly connected to a global clock and is updated on the rising edge.
When an initialization value is provided at the declaration of the register,
it uses a synchronous reset connected to a global reset signal.
A register can be any Chisel type that can be represented as a collection of bits.
Following code defines an 8-bit register, initialized with 0 at reset:
\shortlist{code/register.txt}
\noindent An input is connected to the register with the \code{:=} update operator and
the output of the register can be used just with the name in an expression:
\shortlist{code/reg_con.txt}
\noindent A register can also be connected to its input at the definition:
\shortlist{code/reg_next.txt}
\noindent A register can also be connected to its input and a constant as
initial value at the definition:
\shortlist{code/reg_both.txt}
\noindent To distinguish between signals representing combinational logic and registers,
a common practice is to postfix register names with \code{Reg}.
Another common practice, coming from Java and Scala, is to use
\myref{https://en.wikipedia.org/wiki/Camel_case}{camelCase} for
identifier consisting of several words. The convention is to start
functions and variables with a lower case and classes (types) with
an upper case.
\subsection{Counting}
Counting is a fundamental operation in digital systems. On might count events.
However, more often counting is used to define a time interval. Counting the
clock cycles and triggering an action when the time interval has expired.
A simple approach is counting up to a value. However, in computer science,
and digital design, counting starts at 0. Therefore, if we want to count till
10, we count from 0 to 9. The following code shows such a counter that counts
till 9 and wraps around to 0 when reaching 9.
\shortlist{code/counter.txt}
\section{Structure with Bundle and Vec}
Chisel provides two constructs to group related signals: (1) a \code{Bundle} to group
signals of different types and (2) a \code{Vec} to represent an indexable collection of signals
of the same type.
\code{Bundle}s and \code{Vec}s can be arbitrarily nested.
A Chisel bundle groups several signals. The entire bundle can be referenced
as a whole, or individual fields can be accessed by their name.
We can define a bundle (collection of signals) by defining a class that
extends \code{Bundle} and list the fields as \code{val}s within the constructor block.
\shortlist{code/bundle.txt}
\noindent To use a bundle, we create it with \code{new} and wrap it into a \code{Wire}.
The fields are accessed with the dot notation:
\shortlist{code/bundle_use.txt}
Dot notation is common in object-oriented languages, where \code{x.y} means
\code{x} is a reference to an object and \code{y} is a field of that object.
As Chisel is object-oriented, we use dot notation to access fields in a bundle.
A bundle is similar to a \code{struct} in C, a \code{record} in VHDL, or a
\code{struct} in SystemVerilog.
A bundle can also be referenced as a whole:
\shortlist{code/bundle_ref.txt}
A Chisel \code{Vec} represents a collection of signals of the same type (a vector).
Each element can be accessed by an index. A Chisel \code{Vec} is similar
to array data structures in other programing languages.\footnote{The name \codefoot{Array}
is already used in Scala.}
A \code{Vec} is created by calling the constructor with two parameters: the
number of elements and the type of the elements. A combinational \code{Vec}
needs to be wrapped into a \code{Wire}
\shortlist{code/vec.txt}
\noindent Individual elements are accessed with \code{(index)}.
\shortlist{code/vec_access.txt}
A vector wrapped into a \code{Wire} is a multiplexer.
We can also wrap a vector into a register to define an array of registers.
Following example defines a register file for a processor; 32 registers
each 32-bits wide, as for a classic 32-bit
\myref{https://en.wikipedia.org/wiki/Reduced_instruction_set_computer}{RISC}
processor, like the 32-bit version of \myref{https://en.wikipedia.org/wiki/RISC-V}{RISC-V}.
\shortlist{code/reg_file.txt}
\noindent An element of that register file is accessed with an index and used as a normal register.
\shortlist{code/reg_file_access.txt}
We can freely mix bundles and vectors. When creating a vector with a bundle
type, we need to pass a prototype for the vector fields. Using our
\code{Channel}, which we defined above, we can create a vector of channels with:
\shortlist{code/vec_bundle.txt}
\noindent A bundle may as well contain a vector:
\shortlist{code/bundle_vec.txt}
When we want a register of a bundle type that needs a reset value,
we first create a \code{Wire} of that bundle, set the individual fields
as needed, and then passing this bundle to a \code{RegInit}:
\shortlist{code/bundle_reg_init.txt}
With combinations of \code{Bundle}s and \code{Vec}s we can define our own data
structures, which are powerful abstractions.
\section{Chisel Generates Hardware}
After seeing some initial Chisel code, it might look similar to classic programming
languages such as Java or C. However, Chisel (or any other hardware description
language) does define hardware components. While in a software program one
line of code after the other is executed, in hardware all lines of code
\emph{execute in parallel}.
It is essential to keep in mind that Chisel code does generate hardware.
Try to imagine, or draw on a sheet of paper, the individual blocks that
are generated by your Chisel circuit description.
Each creation of a component adds hardware; each assignment statement
generates gates and/or flip-flops.
More technically, when Chisel executes your code it runs as a Scala program, and
by executing the Chisel statements, it \emph{collects} the hardware components
and connects those nodes. This network of hardware nodes is the hardware,
which can spill out Verilog code for ASIC or FPGA synthesis or can be
tested with a Chisel tester.
The network of hardware nodes is what is executed in fully parallel.
For a software engineer imagine this immense parallelism that you can
create in hardware without needing to partition your application into threads
and getting the locking correct for the communication.
\section{Exercise}
In the introduction you implemented a blinking LED on an FPGA board
(from \myref{https://github.com/schoeberl/chisel-examples}{chisel-examples}), which is a reasonable
hardware \emph{Hello World} example. It used only internal state, a single LED output, and no input.
Copy that project into a new folder and extend it by adding some inputs to the \code{io} \code{Bundle}
with \code{val sw = Input(UInt(2.W))}.
\shortlist{code/basic_exercise.txt}
\noindent For those switches, you also need to assign the pin names for the FPGA board.
You can find examples of pin assignments in the Quartus project files of the ALU project
(e.g., for the \myref{https://github.com/schoeberl/chisel-examples/blob/master/quartus/altde2-115/alu.qsf}{DE2-115
FPGA board}).
When you have defined those inputs and the pin assignment, start with a simple test:
drop all blinking logic from the design and connect one switch to the LED output;
compile and configure the FPGA device. Can you switch the LED on an off with the switch?
If yes, you have now inputs available. If not, you need to debug your FPGA configuration.
The pin assignment can also be done with the GUI version of the tool.
Now use two switches and implement one of the basic combinational functions,
e.g., AND two switches and show the result on the LED. Change the function.
The next step involves three input switches to implement a multiplexer: one acts as
a select signal, and the other two are the two inputs for the 2:1 multiplexer.
Now you have been able to implement simple combinational functions and test them
in real hardware in an FPGA. As a next step, we will take a first look at how the build
process works to generate an FPGA configuration. Furthermore, we will also
explore a simple testing framework from Chisel, which allows you to test circuits
without configuring an FPGA and toggle switches.
\chapter{Build Process and Testing}
To get started with more interesting Chisel code we first need to learn how to compile
Chisel programs, how to generate Verilog code for execution in an FPGA, and how
to write tests for debugging and to verify that our circuits are correct.
Chisel is written in Scala, so any build process that supports Scala is possible
with a Chisel project. One popular build tool for Scala is \myref{https://www.scala-sbt.org/}{sbt},
which stands for the Scala interactive build tool.
Besides driving the build and test process, \code{sbt} also downloads the correct
version of Scala and the Chisel libraries.
\section{Building your Project with sbt}
The Scala library that represents Chisel and the Chisel testers are automatically
downloaded during the build process from a Maven repository.
The libraries are referenced by \code{build.sbt}. It is possible to configure \code{build.sbt}
with \code{latest.release} to always use the most actual version of Chisel.
However, this means on each build the version is looked up from the Maven
repository. This lookup needs an Internet connection for the build to succeed.
Better use a dedicated version of Chisel and all other Scala libraries in your \code{build.sbt}.
Maybe sometimes it is also good to be able to write hardware code and test it without an Internet connection.
For example, it is cool to do hardware design on a plane.
\subsection{Source Organization}
\code{sbt} inherits the source convention from the \myref{https://maven.apache.org/}{Maven}
build automation tool. Maven also organizes repositories of open-source Java libraries.\footnote{That is
also the place where you downloaded the Chisel library on your first build:
\url{https://mvnrepository.com/artifact/edu.berkeley.cs/chisel3}.}
\begin{figure}
\dirtree{%
.1 project.
.2 src.
.3 main.
.4 scala.
.5 package.
.6 sub-package.
.3 test.
.4 scala.
.5 package.
.2 target.
.2 generated.
}
\caption{Source tree of a Chisel project (using \code{sbt})}
\label{fig:folders}
\end{figure}
Figure~\ref{fig:folders} shows the organization of the source tree of a typical Chisel project.
The root of the project is the project home, which contains \code{build.sbt}.
It may also include a \code{Makefile} for the build process, a README, and a LICENSE file.
Folder \code{src} contains all source code. From there it is split between \code{main},
containing the hardware sources and \code{test} containing testers.
Chisel inherits from Scala, which inherits from Java the organization of source
in \myref{https://en.wikipedia.org/wiki/Java_package}{packages}.
Packages organize your Chisel code into namespaces. Packages can also contain
sub-packages.
The folder \code{target} contains the class files and other generated files.
I recommend to also use a folder for generated Verilog files, which is usually
call \code{generated}.
To use the facility of namespaces in Chisel, you need to declare that a class/module
is defined in a package, in this example in \code{mypacket}:
\shortlist{code/packet.txt}
\noindent Note that in this example we see the import of the \code{chisel3} packet