thesis.tex 176 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073
  1. % Copyright (C) 2014-2020 by Thomas Auzinger <thomas@auzinger.name>
  2. \documentclass[draft,final]{vutinfth} % Remove option 'final' to obtain debug information.
  3. % Load packages to allow in- and output of non-ASCII characters.
  4. \usepackage{lmodern} % Use an extension of the original Computer Modern font to minimize the use of bitmapped letters.
  5. \usepackage[T1]{fontenc} % Determines font encoding of the output. Font packages have to be included before this line.
  6. \usepackage[utf8]{inputenc} % Determines encoding of the input. All input files have to use UTF8 encoding.
  7. % Extended LaTeX functionality is enables by including packages with \usepackage{...}.
  8. \usepackage{amsmath} % Extended typesetting of mathematical expression.
  9. \usepackage{amssymb} % Provides a multitude of mathematical symbols.
  10. \usepackage{mathtools} % Further extensions of mathematical typesetting.
  11. \usepackage{microtype} % Small-scale typographic enhancements.
  12. \usepackage[inline]{enumitem} % User control over the layout of lists (itemize, enumerate, description).
  13. \usepackage{multirow} % Allows table elements to span several rows.
  14. \usepackage{booktabs} % Improves the typesettings of tables.
  15. \usepackage{subcaption} % Allows the use of subfigures and enables their referencing.
  16. \usepackage[ruled,linesnumbered,algochapter]{algorithm2e} % Enables the writing of pseudo code.
  17. \usepackage[usenames,dvipsnames,table]{xcolor} % Allows the definition and use of colors. This package has to be included before tikz.
  18. \usepackage{nag} % Issues warnings when best practices in writing LaTeX documents are violated.
  19. \usepackage{todonotes} % Provides tooltip-like todo notes.
  20. \usepackage{hyperref} % Enables cross linking in the electronic document version. This package has to be included second to last.
  21. \usepackage[acronym,toc]{glossaries} % Enables the generation of glossaries and lists fo acronyms. This package has to be included last.
  22. \usepackage{float} % Control positioning more fine-grained
  23. \usepackage{listings}
  24. \usepackage{minted}
  25. \usepackage{xurl}
  26. \usepackage{placeins}
  27. \usemintedstyle{manni}
  28. % Define convenience functions to use the author name and the thesis title in the PDF document properties.
  29. \newcommand{\authorname}{Norbert Cornelius Tremurici} % The author name without titles.
  30. \newcommand{\thesistitle}{Exploring extensions for a basic RISC-V pipeline implementation to support the execution of an operating system} % The title of the thesis. The English version should be used, if it exists.
  31. % color macros
  32. \newcommand{\catSN}[0]{\textcolor{BrickRed}{SN} }
  33. \newcommand{\catEX}[0]{\textcolor{OliveGreen}{E} }
  34. \newcommand{\catPE}[0]{\textcolor{RoyalBlue}{PE} }
  35. \newcommand{\catCO}[0]{\textcolor{MidnightBlue}{C} }
  36. % Set PDF document properties
  37. \hypersetup{
  38. pdfpagelayout = TwoPageRight, % How the document is shown in PDF viewers (optional).
  39. linkbordercolor = {Melon}, % The color of the borders of boxes around crosslinks (optional).
  40. pdfauthor = {\authorname}, % The author's name in the document properties (optional).
  41. pdftitle = {\thesistitle}, % The document's title in the document properties (optional).
  42. pdfsubject = {Subject}, % The document's subject in the document properties (optional).
  43. pdfkeywords = {a, list, of, keywords} % The document's keywords in the document properties (optional).
  44. }
  45. \setpnumwidth{2.5em} % Avoid overfull hboxes in the table of contents (see memoir manual).
  46. \setsecnumdepth{subsection} % Enumerate subsections.
  47. \nonzeroparskip % Create space between paragraphs (optional).
  48. \setlength{\parindent}{0pt} % Remove paragraph identation (optional).
  49. \makeindex % Use an optional index.
  50. \makeglossaries % Use an optional glossary.
  51. %\glstocfalse % Remove the glossaries from the table of contents.
  52. % Set persons with 4 arguments:
  53. % {title before name}{name}{title after name}{gender}
  54. % where both titles are optional (i.e. can be given as empty brackets {}).
  55. \setauthor{}{\authorname}{}{male}
  56. \setadvisor{Ao.Univ.Prof. Dipl.-Ing. Dr.techn.}{Andreas Steininger}{}{male}
  57. % For bachelor and master theses:
  58. \setfirstassistant{Projektass. Dipl.-Inform.}{Florian Kriebel}{}{male}
  59. %\setsecondassistant{Pretitle}{Forename Surname}{Posttitle}{male}
  60. %\setthirdassistant{Pretitle}{Forename Surname}{Posttitle}{male}
  61. % For dissertations:
  62. %\setfirstreviewer{Pretitle}{Forename Surname}{Posttitle}{male}
  63. %\setsecondreviewer{Pretitle}{Forename Surname}{Posttitle}{male}
  64. % For dissertations at the PhD School and optionally for dissertations:
  65. %\setsecondadvisor{Pretitle}{Forename Surname}{Posttitle}{male} % Comment to remove.
  66. % Required data.
  67. \setregnumber{11907086}
  68. \setdate{16}{08}{2023} % Set date with 3 arguments: {day}{month}{year}.
  69. \settitle{\thesistitle}{Exploring extensions for a basic RISC-V pipeline implementation to support the execution of an operating system} % Sets English and German version of the title (both can be English or German). If your title contains commas, enclose it with additional curvy brackets (i.e., {{your title}}) or define it as a macro as done with \thesistitle.
  70. %\setsubtitle{Optional Subtitle of the Thesis}{Optionaler Untertitel der Arbeit} % Sets English and German version of the subtitle (both can be English or German).
  71. % Select the thesis type: bachelor / master / doctor / phd-school.
  72. % Bachelor:
  73. \setthesis{bachelor}
  74. %
  75. % Master:
  76. %\setthesis{master}
  77. %\setmasterdegree{dipl.} % dipl. / rer.nat. / rer.soc.oec. / master
  78. %
  79. % Doctor:
  80. %\setthesis{doctor}
  81. %\setdoctordegree{rer.soc.oec.}% rer.nat. / techn. / rer.soc.oec.
  82. %
  83. % Doctor at the PhD School
  84. %\setthesis{phd-school} % Deactivate non-English title pages (see below)
  85. % For bachelor and master:
  86. \setcurriculum{Computer Engineering}{Technische Informatik} % Sets the English and German name of the curriculum.
  87. % For dissertations at the PhD School:
  88. \setfirstreviewerdata{Affiliation, Country}
  89. \setsecondreviewerdata{Affiliation, Country}
  90. \begin{document}
  91. \frontmatter % Switches to roman numbering.
  92. % The structure of the thesis has to conform to the guidelines at
  93. % https://informatics.tuwien.ac.at/study-services
  94. \addtitlepage{naustrian} % German title page (not for dissertations at the PhD School).
  95. \addtitlepage{english} % English title page.
  96. \addstatementpage
  97. %\begin{danksagung*}
  98. %\todo{Ihr Text hier.}
  99. %\end{danksagung*}
  100. %\begin{acknowledgements*}
  101. %\todo{Enter your text here.}
  102. %\end{acknowledgements*}
  103. \begin{kurzfassung}
  104. In den letzten Jahren hat der open-source RISC-V Befehlssatz (ISA) und das dazugehörige Ökosystem an Sichtbarkeit in den industriellen und akademischen Sektoren gewonnen.
  105. Es wird auch breitflächig genutzt um Grundlagen der Technischen Informatik zu lehren, vorallem in einem Befehlssatzdesign- und Pipeliningkontext.
  106. Als solches spielt Praxiserfahrung (wie etwa eine Implementierung der Pipeline eines Prozessorkerns) eine entscheidende Rolle in der Erforschung der mit Pipelining verbundenen Probleme.
  107. Während eine grundlegende Pipelineimplementierung es erlaubt, Bare-Metal-Applikationen mit vertretbarem Implementierungs- und Infrastrukturaufwand auszuführen, bleibt das Erweitern eines solchen Systems um die Ausführung komplexerer Applikationen oder gar Betriebssysteme zu erlauben (etwa durch eine komplexere Speicherhierarchie oder fortgeschrittener I/O Möglichkeiten) eine unzumutbare Aufgabe für eine zum Bachelor gehörige Rechnerstrukturlehrveranstaltung.
  108. Obwohl eine breite Vielfalt an kommerziellen und akademischen RISC-V Implementierungen und Projekten existiert, welche zum Teil aufgezählte Funktionen unterstützen, sind diese oft entweder zu kompliziert, erfordern einen zusätzlichen Implementierungsaufwand für mehrere Erweiterungen, oder erfüllen nicht die Anforderungen und Vorgaben für das Interface, die Infrastruktur, die Hardwareplattform oder die Hardwarebeschreibungssprache.
  109. Daher ist das Ziel dieser Arbeit eine potenzielle, minimale und/oder realisierbare Menge an notwendigen Erweiterungen für eine existierende, einfache 5-stufige RISC-V Pipelineimplementierung zu finden um die Ausführung eines Betriebssystems zu unterstützen.
  110. Impliziert ist das Auffinden verfügbarer Betriebssyteme für diese Implementierung, ein Vergleich hinsichtlich Funktionalität sowie derer Vor- und Nachteile, eine Analyse der Trade-offs, eine Abschätzung des dazugehörigen Entwicklungs- und Implementierungsaufwandes hinsichtlich der notwendigen Hardware- und Softwareerweiterungen und zu guter Letzt, eine passende Wahl.
  111. Als Ergebnis dieser Untersuchung wird eine Analyse des aktuellen Zustandes von RISC-V Betriebssytemen bereitgestellt, so wie Prototypimplementierungen einer \textit{Exception}, \textit{Interrupt} und \textit{Trap} Architektur, RISC-V M und Zicsr Erweiterungen und ein einfacher 2-bit Branch Predictor.
  112. Diese Erweiterungen wurden entweder als notwendige oder leistungssteigendere Komponenten für die Unterstützung eines ausgewählten Betriebssystems, FreeRTOS, aufgesetzt in einer einfachen Konfiguration um eine 2-thread Applikation auszuführen, identifiziert.
  113. \end{kurzfassung}
  114. \begin{abstract}
  115. In recent years, the open-source RISC-V Instruction Set Architecture and the corresponding ecosystem gained increasing visibility in the industry and academic sectors.
  116. It is also widely used for teaching computer architecture fundamentals, especially in the context of ISA design and pipelining.
  117. In this regard, hands-on experience (i.e., implementing the core processor pipeline) plays an important role to explore and understand the problems associated with pipelining.
  118. While such a basic pipeline implementation allows running bare metal applications with a manageable implementation and infrastructure overhead, extending this basic system with more sophisticated functionality (e.g., being able to execute more complex applications or even an operating system), a more complex memory hierarchy or advanced I/O is typically not feasible for an undergraduate computer architecture course.
  119. Although a wide variety of commercial and academic RISC-V implementations and projects offering (parts of) the above-mentioned features exist, they often are either too complex, require several extensions to be implemented, or do not meet interface, infrastructure, hardware platform or hardware description language requirements.
  120. Therefore, the goal of this work is to explore the potential and a minimal and/or feasible set of required extensions for an existing basic 5-stage RISC-V pipeline implementation to be able to support the execution of an operating system.
  121. This implies discovering existing operating system options for this implementation, comparing them with respect to their features and advantages/disadvantages, analyzing trade-offs and estimating the corresponding development and implementation effort for required hardware and software extensions and finally selecting an appropriate option.
  122. As a result of this exploration, an analysis of operating systems supporting RISC-V is provided, as well as prototype implementations of an exception, interrupt and trap architecture, RISC-V M and Zicsr extensions and a simple 2-bit branch predictor.
  123. These extensions were identified either as necessary or performance enhancing components to support the execution of an operating system of choice, FreeRTOS, set up in a simple configuration to run a two-threaded application.
  124. \end{abstract}
  125. % Select the language of the thesis, e.g., english or naustrian.
  126. \selectlanguage{english}
  127. % Add a table of contents (toc).
  128. \tableofcontents % Starred version, i.e., \tableofcontents*, removes the self-entry.
  129. % Switch to arabic numbering and start the enumeration of chapters in the table of content.
  130. \mainmatter
  131. % CHAPTER
  132. \chapter{Introduction}
  133. \label{chapter:introduction}
  134. \section{Motivation}
  135. The motivation of this bachelor thesis is to explore the RISC-V hardware and software ecosystem, such that a clear and concise picture of available software and its actual hardware requirements emerges.
  136. This undertaking is intended to enhance an existing relatively basic pipelined RISC-V processor implementation supporting the 32-bit base integer instruction set (RV32I) by studying available implementation paths and providing required new functionality.
  137. Students of the undergraduate level Computer Engineering study program take this task on to complete a digital design and computer architecture lab course, with teams of two students each producing their own implementation of the so-called MiRiV processor.
  138. MiRiV serves to show students the basics of pipelining and its related concepts.
  139. Usually students end the course with an actual and functional pipelined RV32I implementation.
  140. The end result, already large in scope for a lab course, is however still limited in its support for the execution of more complex applications.
  141. Students get to implement a basic processor almost from the ground up, being provided an environment in which to develop their designs and test their implementation.
  142. But going beyond a bare-metal execution of simple programs remains a difficult challenge.
  143. Real world computers and microcontrollers consist of more than the bare-metal execution of simple programs.
  144. Thus, there exists a great opportunity to extend this existing environment such that students can see their own implementation perform tasks more reminiscent of actual workloads found in the real world.
  145. With the support of a real-time operating system, FreeRTOS, this desired situation has been realized.
  146. \section{Outline}
  147. In Section~\ref{section:riscv-manual}, we will take a quick look at the official RISC-V specifications.
  148. The extent of the MiRiV processor in its entirety, together with a description of the platform (target devices and software environment) it runs on is discussed in Section~\ref{section:miriv}.
  149. Running operating systems on RISC-V architectures will be discussed in Section~\ref{section:support-exec-os}.
  150. Considerations about whether to use existing RISC-V processor implementations with openly available source code will be laid out in Section~\ref{section:utilizing-existing-implementations} while available options will be explored in \ref{section:some-existing-implementations}.
  151. Chapter~\ref{chapter:overview} will explore RISC-V standard ISA extensions in Section~\ref{section:overview-ext} and several available operating systems in Section~\ref{section:overview-os}.
  152. In this second chapter the state of the current software ecosystem is examined and on this basis an implementation path is chosen.
  153. We will consider real-time operating systems and embedded Linux based operating systems in more detail.
  154. The findings will be concluded in Section~\ref{section:overview-conclusion}.
  155. %We will consider real-time operating systems in more detail in Section~\ref{section:overview-rtos} and Linux based operating systems in \ref{section:overview-linux}.
  156. Afterwards, in Chapter~\ref{chapter:architecture} a few selected extensions will be illustrated by way of providing architectural considerations and their design for the final implementation.
  157. These include the exception, interrupt and trap architecture (section \ref{section:exc-int-trap-arch}), as well as considerations for the implementation of the M (section \ref{section:m-arch}), A (section \ref{section:a-arch}), Zifencei (section \ref{section:zifencei-arch}) and Zicsr (section \ref{section:zicsr-arch}) extensions and a branch predictor (section \ref{section:bp-arch}).
  158. Finally, implementation details are outlined in Chapter~\ref{chapter:implementation}.
  159. Section~\ref{section:preparing-miriv} will explain modifications made to the basic MiRiV processor implementation, giving a short overview of all architectural changes.
  160. More elaborate implementation details are also provided in Sections \ref{section:exc-int-trap-implementation} (exceptions, interrupts and traps), \ref{section:m-ext-implementation} (M extension) and \ref{section:bp-implementation} (modified branch predictor).
  161. Section~\ref{section:preparing-freertos} will show how FreeRTOS is incorporated into the already existing suite of software tests, what options it offers, how it can be configured and how it is intended to run on the extended MiRiV processor and in Section~\ref{section:freertos-demo} we will discuss the demo application based on FreeRTOS that has been implemented.
  162. The results are reflected on in Chapter~\ref{chapter:conclusion}, where Section~\ref{section:future-work} details possible future trajectories of the extended MiRiV processor and Section~\ref{section:conclusion} gives a summary of this entire effort.
  163. \section{Note on RISC-V Specifications}
  164. \label{section:riscv-manual}
  165. Throughout this document we will refer to both RISC-V specifications that are part of the RISC-V Instruction Set Manual.
  166. Volume 1 is the RISC-V unprivileged specification \cite{riscv-isa-vol-1} and Volume 2 is the RISC-V privileged specification \cite{riscv-isa-vol-2}.
  167. Both try to keep implementation details as undetermined as possible, to support a wide variety of implementations while still ensuring enough similarity between processors implementing the RISC-V specifications where it is necessary, for example to avoid excessive fragmentation.
  168. The RISC-V privileged specification describes different privilege modes for a privileged architecture, to support all kinds of execution environments.
  169. A configuration could include privilege modes for the machine, a hypervisor, a supervisor and the user.
  170. The RISC-V unprivileged specification includes all base instructions, \textit{unprivileged} instructions, that can be used in all privilege modes.
  171. It also contains optional ISA extensions that supply additional hardware functionality.
  172. \section{The MiRiV Processor}
  173. \label{section:miriv}
  174. MiRiV is a minimal RISC-V implementation that covers the RV32I base integer instruction set.
  175. We will now look at the design of its pipeline, as well as the hardware and software environments it runs in.
  176. \subsection{Pipeline Design}
  177. The implementation is pipelined and the pipeline design is the basic and canonical RISC-V pipeline as outlined in the definitive book by David A. Patterson and John L. Hennessy \cite{comporg2020}.
  178. The five stages of this pipeline are the instruction fetch stage, the instruction decode stage, the execute stage, the memory stage and finally the write-back stage.
  179. Figure~\ref{fig:miriv-pipeline} serves to show the individual components of this implementation.
  180. \begin{figure}[h]
  181. \centering
  182. \includegraphics[width=\textwidth]{miriv-pipeline.png}
  183. \caption{The base MiRiV pipeline \cite{ddca2021}. For the final, modified pipeline with all necessary extensions refer to Figure~\ref{fig:miriv-new-pipeline}.}
  184. \label{fig:miriv-pipeline}
  185. \end{figure}
  186. In addition to the pipeline itself, a control unit that stalls and flushes the pipeline accordingly in order to properly detect and handle hazards is implemented.
  187. Forwarding from the memory and write-back stages is also implemented, for writes that aren't yet reflected by reads from the register file in the decode stage.
  188. Finally, caches are implemented, ranging from a direct-mapped cache up to 2-way or 4-way set associative caches.
  189. Implementing a cache makes the processor more realistic and viable.
  190. For the students it also serves to relax memory assumptions (such as instructions or data being available at the next clock cycle) and illustrate associated challenges.
  191. It is important to also discuss what is \textit{not} part of the processor implementation, to begin to understand its limitations.
  192. There is no interrupt unit and there are no trap handlers to handle exceptions and interrupts.
  193. Exceptions are implemented as signals within respective design units, to capture decode exceptions and load and store exceptions.
  194. But so far they exist only as unused signals that can be probed inside a simulation.
  195. Furthermore, none of the extensions of the RISC-V unprivileged \cite{riscv-isa-vol-1} or privileged \cite{riscv-isa-vol-2} specifications are implemented.
  196. Notably, this means that Zicsr, counters (except for a simple 32-bit memory-mapped counter mentioned in Section~\ref{subsection:software-environment}) and timers aren't implemented, so there are no control and status registers (CSRs) or support for instructions manipulating them.
  197. Other extensions like the multiplication, atomic or floating-point extensions are also currently not supported.
  198. Memory is confined to embedded memory on the FPGA chip and there is no support for virtual memory, as the implementation lacks a memory-management unit (MMU).
  199. Both the instruction and data memories are limited to 16 KiB each.
  200. There is also no support for different privilege modes.
  201. This is fine for a basic pipeline implementation that exists for learning purposes, but as we will see some extensions and changes are required in order to run an operating system.
  202. \subsection{Target Device}
  203. As the purpose of the lab course is the development and implementation of the MiRiV processor, the target devices consist of field-programmable gate arrays (FPGAs).
  204. The hardware description language (HDL) used is VHDL.
  205. Two specific boards are targeted, the Terasic Altera DE2-115 board as well as the Terasic Altera DE0-Nano board (both hosting FPGAs from the Cyclone IV E family of FPGAs).
  206. These FPGA boards provide many on-board peripherals, although not many are used for this processor.
  207. Instruction and data memory are instantiated as embedded memory on the FPGA chip itself.
  208. No peripheral memory components, such as SDRAM for example, are used in the basic MiRiV implementation.
  209. Once a MiRiV design is synthesized and fitted, it is flashed onto the FPGA.
  210. The bootloader consists of script utilities that use the USB serial programmer (on-board Altera USB-Blaster) to program regions of the instruction and data memories and set the state of the processor accordingly such that it starts reading and executing the right instruction.
  211. \subsection{The Software Environment}
  212. \label{subsection:software-environment}
  213. Of course such an undertaking would not be as instructive if there was no testing.
  214. There are simulations of individual units as well as simulations that simulate the entire pipeline as a whole.
  215. But the goal is not only to build a processor that runs in simulations, it's also to build a processor that can execute programs on hardware.
  216. Currently, the only interfacing I/O of the MiRiV processor, once programmed onto the target device, is a USB serial connection to communicate with the host via UART.
  217. This allows for simple textual output that showcases correct execution of the processor.
  218. Using this UART interface is made possible by using a custom, very lightweight implementation of a small C library implementing only 10 functions.
  219. Those functions include string comparison and string length, a time function that returns a tick counter value with a granularity of microseconds, as well as simple functions to read from and write to UART.
  220. This environment already offers great testing capabilities, but any complex tasks, particularly multi-tasking, prove to be a challenge.
  221. Due to such limitations, students are restricted to either writing simple monolithic programs or invest unrealistic efforts into understanding the system well enough to design and implement more comprehensive capabilities.
  222. As previously outlined, because the MiRiV processor is a platform for students to learn, providing a more complete and sophisticated environment where even an operating system is supported would make the entire platform more accessible for those who want to go beyond simple bare-metal applications.
  223. \section{Supporting the Execution of an Operating System}
  224. \label{section:support-exec-os}
  225. Currently there are a few supplied example programs and students can write their own test programs.
  226. But because of the limited support for sophisticated library features these programs are invariably limited in scope.
  227. An operating system is usually built against a C standard library implementing functionality of the C standard for the C programming language, as is a lot of other code.
  228. A motivated student longing to see his freshly implemented processor do actual work will quickly realize that there is a mountain of work to be scaled as they will have to implement all required features of the C standard, port an existing C standard library or write a lot of their own code, all of which would be hard to test and debug.
  229. One of the most inspiring test cases for a processor implementation of a student would arguably be an operating system, which is an application that illustrates well the complexities of running more elaborate software.
  230. Offering them an opportunity to test out an operating system would perhaps even inspire them to join the effort and make further extensions, which constitutes a clear-cut path to increasing the scope of MiRiV as a project.
  231. Any student wondering how they can make the transition from their RV32I implementation to a system that does everything an operating system requires will be faced with similar questions like the ones this work will be concerned with.
  232. So one additional goal is to serve as a reference and fairly comprehensive overview for anyone looking to get into this difficult space.
  233. It is not that difficult to find an unconstrained set of extensions needed to run an operating system.
  234. There are several RISC-V implementations that can run operating systems that list in their specifications what they have implemented, but it is difficult currently to find out what \emph{minimal} set of extensions are necessary for any given operating system.
  235. The question of implementing a minimal set of extensions would be relevant to any interested students because after completing the lab course, they will have implemented for themselves only the 32-bit base integer instruction set.
  236. Targeting the minimal set of extensions does not only constrain the scale of the implementation effort and lead to a working example quicker, but also reduces complexity and thereby makes the task at hand easier.
  237. \section{Utilizing Existing Implementations}
  238. \label{section:utilizing-existing-implementations}
  239. Several RISC-V processor implementations that support the execution of even operating systems like Linux with many of its features already exist \cite{web-riscv-boards-exchange}.
  240. By nature of the RISC-V ecosystem, open-source implementations can even be found with ease and freely used, re-used, even extended or contributed to.
  241. It is fair to ask whether there isn't already an implementation that can serve the purpose outlined in the motivation.
  242. Several factors come into play, such as complexity, extension support and whether they meet all other requirements.
  243. Such requirements include interface, infrastructure, hardware platform or hardware description language (HDL) requirements.
  244. The author is not aware of a single existing RISC-V processor implementation that can readily and easily be adapted to fit for this use case.
  245. For one, if they are too complex, they pose too great a leap from the MiRiV implementation in the hands of students.
  246. Some implement and depend on too many extensions, which in turn raises their complexity.
  247. Common performance features such as out-of-order execution, superscalar design, superpipelined design or sophisticated branch prediction have a considerably higher barrier to entry for students who want to improve on their own humble implementation.
  248. An implementation is usually bound to a hardware platform and makes extensive use of an infrastructure developed as part of the implementation effort.
  249. In adapting an implementation, constraints like supported hardware platforms are inherited and existing infrastructure can make for a challenging integration effort.
  250. One particularly important consideration is the memory organization and by extension, support for memory interfaces.
  251. Even if an implementation turns out to be compatible, they might still be based on different HDLs.
  252. This will more easily enable students to integrate their solution.
  253. There are many ways to modularize, extend and implement units in different HDLs.
  254. Because of this, the issue of packaging a set of extensions so that a student can integrate them effortlessly becomes intricate.
  255. The first goal is to keep a common base with the extended MiRiV implementation.
  256. The second is to use isolated modules and precompiled modules that rely as little as possible on the parts of MiRiV that will be variable due to student implementation variance.
  257. The assignment itself has fixed interfaces, making unknown implementations more predictable.
  258. If some of these factors cannot be completely accounted for, it is also possible to make it the task of students to perform basic implementation tasks in order to make their implementation compatible.
  259. \section{Some Existing Implementations}
  260. \label{section:some-existing-implementations}
  261. We do still want to mention other existing implementations, as it gives a good overview of features that can be implemented.
  262. There is a wealth of open source RISC-V designs and the designs range from basic CPU implementations, entire Systems-on-Chip (SoC) to boards containing peripheral devices.
  263. Some of them are meant to be taped out on actual integrated circuits to be put on actual boards, while others exist purely as soft-core implementations meant for FPGA devices.
  264. Designs may even support both approaches.
  265. One of the earliest proponents of RISC-V were SiFive, who have brought to market development boards meant to offer RISC-V platforms with many capabilities.
  266. Their CPU designs are modular and actual specifications can be tweaked to one's requirements.
  267. The HiFive Unmatched board \cite{web-hifive-unmatched}, which is their current flagship device, supports on-board 16 GB 64-bit DDR4 @ 1866 MT/s, on-board 32 MB QSPI NOR flash, an optional microSD card, an optional solid-state drive via NVMe SSD M.2 Key M for their memory options \cite{web-hifive-unmatched-datasheet}.
  268. Then there is Ethernet (10/100/1000 Mbps) and optional Wi-Fi and BLE support for networking options.
  269. There are also many connectors, too many to be listed here.
  270. Their processor is the SiFive FU740-C000 operating at 1.2 GHz.
  271. It has a dual-issue in-order 64-bit execution pipeline, four 64-bit SiFive U74 cores supporting RV64IMAFDC (or RV64GC for short) with 32KB instruction and data cache per core and a shared 2 MB coherent banked L2-Cache.
  272. On the side of the soft-core implementations, there is the LiteX VexRiscv and the NEORV32.
  273. The LiteX VexRiscv is an FPGA friendly 32-bit RISC-V CPU soft-core processor \cite{web-vexriscv}.
  274. It can be used in a minimal configuration targeting RV32I in a no MMU (nommu) fashion, up to much more sophisticated configurations targeting RV32IMAFDC (RV32GC) with an MMU.
  275. There are also debugging features and interrupt and exception handling with machine mode (M-mode) and optionally supervisor mode (S-mode) and user mode (U-mode).
  276. Depending on the configuration and FPGA resources, its frequency can go as high 243 MHz.
  277. Another soft-core implementation is the NEORV32, which is another FPGA friendly 32-bit RISC-V CPU implementation \cite{web-neorv32}.
  278. Similarly to the LiteX VexRiscv it supports a range of different configurations.
  279. It can run implementing only RV32I or RV32E, or extended to implement most extensions currently available, in addition to exception and interrupt handling.
  280. Out of the RISC-V privileged specification it implements M-mode and U-mode.
  281. Using RV32IMC with Zicsr and the Counters extension on an Intel Cyclone IV FPGA its maximum frequency is 128 MHz.
  282. Both can come only as processor cores or in the package of an entire SoC.
  283. %This flexibility is a useful property when considering how to get an operating system running by adding minimal extensions to the existing MiRiV implementation.
  284. None of these existing implementations are trivial to adapt in order to extract a set of processor extensions that students can use for their MiRiV implementation to get an operating system running.
  285. The challenge lies in the complexity of these projects, with many features being offered that are tightly integrated into the structure of the processor.
  286. The NEORV32 for example is not a traditional pipelined processor but uses a multi-cycle architecture, while the LiteX VexRiscv uses a configurable pipeline with two to five stages, but is implemented using a Scala-based HDL called SpinalHDL.
  287. %On the basis of this exploration, a decision was made to extend the MiRiV processor instead of using any existing implementation.
  288. % CHAPTER
  289. \chapter{Overview and analysis of the RISC-V ecosystem}
  290. \label{chapter:overview}
  291. As the centerpiece of this work is to connect the worlds of a basic RV32I hardware implementation and an operating system, two different aspects need to be considered simultaneously.
  292. Which operating systems exist and what are their requirements?
  293. Subsequently, which requirements are already implemented and which need to be implemented?
  294. This malleable task where both the hardware architecture as well as the operating system and its configuration can be extended proves a difficult design challenge.
  295. Designing the hardware to support the execution of an operating system is a bottom-up task where one needs to work at least initially towards a basic set of features beyond the already existing ones.
  296. On the other hand, choosing and configuring the operating system is a top-down task where one works towards a reasonable configuration that offers sufficient capabilities together with a clear path towards building the hardware for it.
  297. To avoid making a haphazard decision, we use a systematic approach towards comparing operating systems, their precise requirements and possible hardware extensions.
  298. Our methodology for choosing an implementation path is to first consider RISC-V hardware extensions as they are standardized, in order to acquire an understanding of the complexity of different extensions that will be helpful during a subsequent analysis of the operating systems.
  299. Afterwards, we analyze which operating systems are available to make a decision as to what operating system to use for our task.
  300. To do this, we filter choices in two rounds.
  301. In the first round, we roughly scan for operating systems with RISC-V support and what level of support is being offered, by using sources such as documentation.
  302. This is done to gauge how large of an architectural change or porting effort would be necessary either in the MiRiV implementation or the operating system.
  303. One such example is operating system support for 64-bit RISC-V processors only, which would incur larger architectural changes or porting efforts compared to a different operating system supporting 32-bit RISC-V processors.
  304. After a preliminary choice of contenders for the second round, we analyze their minimal requirements by building the operating systems and looking at which extensions can be done without by configuring the build process.
  305. In general, there are many possible extensions to make.
  306. Within the scope of this thesis, they can be considered either strictly necessary, convenient, performance enhancing or expendable.
  307. This categorization scheme will be elaborated upon in Section~\ref{section:categorization-scheme}.
  308. Section~\ref{section:overview-ext} will describe in detail what (stable) RISC-V standard ISA extensions currently exist as part of the RISC-V specifications.
  309. Section~\ref{section:overview-os} will outline possible operating system choices, configurations and which extensions they require.
  310. Because there are too many operating systems for a more precise comparison, as part of the first round our preliminary choice of operating systems will be based on data gathered from documentation and similar sources and the decision process will be discussed in Section~\ref{section:making-a-choice}.
  311. Finally in Section~\ref{section:os-ext-analysis} we will put everything together in an analysis of operating systems of choice as part of the second round, by classifying extension requirements in the above-mentioned categorization scheme.
  312. To conclude this entire chapter, we will summarize our insights and single out an operating system that will be used as a target for the final implementation in Section~\ref{section:overview-conclusion}.
  313. \section{Hardware Extension Categorization Scheme}
  314. \label{section:categorization-scheme}
  315. As we will need to decide which of the RISC-V standard ISA extensions and other hardware features to implement, it is necessary to understand what purpose they are meant to serve.
  316. In general, extensions to the MiRiV processor can be either implementations for RISC-V standard ISA extensions, or hardware features that aren't explicitly specified but still necessary or otherwise beneficial to support the execution of an operating system.
  317. Any extension can be said to fall within one of four categories:
  318. \begin{itemize}
  319. \item \textbf{strictly necessary}
  320. Some hardware features such as support for exceptions, interrupts and trap handlers, in addition to several control and status registers specified in the unprivileged ISA extension Zicsr are likely unavoidable.
  321. \item \textbf{convenient}
  322. The hardware can be extended to implement conventional features like a memory-management unit (MMU) that are sometimes assumed by operating systems as a prerequisite but can be avoided with some effort (the MMU example is briefly touched upon in Section~\ref{subsection:memory-hierarchies}).
  323. \item \textbf{performance enhancing}
  324. Other extensions still can serve to improve various aspects of system performance.
  325. The RISC-V C extension for instance can potentially greatly reduce code size, thereby relaxing not only memory constraints but perhaps even increasing instruction cache performance.
  326. Other more complex features, such as out-of-order, superscalar and superpipelined execution can greatly increase processor performance, but aren't strictly necessary for supporting an operating system and would go against the goal of preserving the core pipeline as it is.
  327. Hosting multiple cores also fits this class.
  328. All of these are features that offer great opportunities for future work.
  329. \item \textbf{expendable}
  330. On the other hand, a floating-point unit (FPU) can be critical for some applications but expendable for others.
  331. Several embedded systems forsake an FPU to drive down costs, which is entirely reasonable in case floating-point arithmetic can be avoided entirely.
  332. In case floating-point operations cannot be done without, they can also be emulated in software\footnote{In the RISC-V GNU toolchain, the ABI \texttt{ilp32} assumes 32-bit software emulated floating-point operations (called soft-floats), while \texttt{ilp32f} and \texttt{ilp32d} are for 32-bit single-precision hard-float and 32-bit hard-float respectively.}.
  333. \end{itemize}
  334. \section{Overview of RISC-V extensions}
  335. \label{section:overview-ext}
  336. Capabilities of RISC-V processors which go beyond the base insteger instruction set are specified in both the RISC-V unprivileged \cite{riscv-isa-vol-1} and privileged \cite{riscv-isa-vol-2} specifications using individual and mostly decoupled extensions.
  337. Many of these extensions are common features of modern processors, but often skipped in an educational context.
  338. Every extension has trade-offs that are made quite deliberately and it is instructive to consider these extensions and their trade-offs in more detail.
  339. \subsection{Zifencei Extension \cite[ch. 3]{riscv-isa-vol-1}}
  340. \label{subsection:overview-zifencei-ext}
  341. The base integer instruction set already includes a rudimentary fence instruction (\texttt{FENCE}).
  342. As it is used to order I/O and memory accesses between different hardware threads, which becomes relevant when load and store operations are re-ordered, it is useful in a multi-core context, but also for single-core systems implementing interrupts.
  343. The RISC-V unprivileged specification \cite[ch. 1]{riscv-isa-vol-1} introduces the term \textit{hart} to refer to a hardware thread, which is defined to be an abstract execution resource in the context of an execution environment and its relationship to a \textit{core} is such that a core might support one or more harts.
  344. This extension serves to add another fence instruction (\texttt{FENCE.I}) with the following purpose:
  345. It is a fence instruction that explicitly synchronizes writes to instruction memory and instruction fetches on the same hart.
  346. According to the RISC-V unprivileged specification \cite{riscv-isa-vol-1}, "RISC-V does not guarantee that stores to instruction memory will be made visible to instruction fetches on a RISC-V hart until that hart executes a FENCE.I instruction."
  347. %It is an general instruction applicable in many contexts, with fields for a source register, destination register and immediate bits, all of which are currently unused.
  348. %These are reserved for possible future use in more specialized fence instructions.
  349. \subsection{M Extension \cite[ch. 7]{riscv-isa-vol-1}}
  350. \label{subsection:overview-m-ext}
  351. The M extension adds new instructions to support integer multiplication and division.
  352. The added multiplication instructions (\texttt{MUL} and \texttt{MULH[[S]U]}) have variations for signed and unsigned integer multiplication and also lower and higher result bits.
  353. Signed and unsigned integer multiplication is necessary by virtue of RISC-V supporting both types of storing numbers and supported are signed $\times$ signed, unsigned $\times$ unsigned and signed $\times$ unsigned multiplications.
  354. For integer multiplication, the resulting bits can exceed the source register size to double that amount, so instruction variations exist where the target register stores either the low or high 32 bits of the 64 bits resulting from the computation.
  355. As for the division instructions, there are instructions for storing the quotient and remainder (\texttt{DIV[U]} and \texttt{REM[U]}), both using either signed or unsigned values.
  356. Special care is needed to handle division by zero and in the case of signed divisions, an overflowing quotient when dividing the most-negative integer ($-2^{31}$) by $-1$.
  357. One benefit of implementing the M extension is reduction in code size, as the compiler can simplify the code.
  358. Without M extension support, the compiler has to resort to multiple addition and shift operations that are usually unrolled loops.
  359. For more complex calculations (like modulo operators) the compiler might even insert auxiliary function calls.
  360. \subsection{A Extension \cite[ch. 8]{riscv-isa-vol-1}}
  361. \label{subsection:overview-a-ext}
  362. The A extension adds new instructions to support atomic operations.
  363. Atomic operations are meant to keep the data consistent when multiple processes read or change state.
  364. For multi-core systems this is important because multiple cores could interact in an undesired fashion.
  365. A classic example would be multiple cores accessing the same data, where non-atomicity could cause race conditions.
  366. On single-core systems this issue might still arise in systems with preemption and multiple tasks.
  367. For single instruction operations, there is no issue, but when atomicity needs to be ensured for multiple instructions interrupts could cause a context switch and lead to consistency issues.
  368. Making multiple operations atomic in RISC-V is done by adding Load-Reserved/Store-Conditional (\texttt{LR.W} and \texttt{SC.W}) and atomic memory operation (AMO) instructions (\texttt{AMO(SWAP|ADD|AND|OR|XOR|MAX[U]|MIN[U]).W}).
  369. Load-Reserved and Store-Conditional are instructions that can work in conjunction to ensure atomicity, thereby offering a way to synchronize hardware threads (harts) or ensure consistency on single-core systems.
  370. Load-Reserved has a single source register and a destination register and reserves the memory address stored in \texttt{rs1}.
  371. Store-Conditional has two source registers and a destination register and checks whether the reservation (at the memory address stored in \texttt{rs1}) is still held and stores the contents of \texttt{rs2}.
  372. Depending on the value stored in the destination register after the Store-Conditional operation, the hart can check whether the atomic operation was successful.
  373. The AMO instructions use a similar format, but with different semantics.
  374. They atomically load a value from the address stored in \texttt{rs1}, placing the value into register \texttt{rd} in addition to applying a binary operator to the loaded value and the value stored in \texttt{rs2} and finally storing the result back to address the address in \texttt{rs1}.
  375. These binary operators are a swap operation, integer add, bit-wise operations (\texttt{AND}, \texttt{OR}, \texttt{XOR}) and signed/unsigned integer maximum and minimum.
  376. \subsection{Zicsr Extension \cite[ch. 9]{riscv-isa-vol-1}}
  377. \label{subsection:overview-zicsr-ext}
  378. The Zicsr extension serves to add an address space of 4096 control and status registers (CSRs) and a set of instructions that operate on these CSRs.
  379. To be precise, there is a 12-bit encoding space to support up to 4096 CSRs.
  380. Their addresses, encoding, purpose and convention is described extensively in the RISC-V privileged specification \cite{riscv-isa-vol-2}.
  381. To give a quick overview, there are unprivileged and user-level CSRs, supervisor-level CSRs, hypervisor and VS (virtual supervisor) CSRs, machine-level CSRs, unprivileged floating-point CSRs and finally, unprivileged counters and timers.
  382. The Zicsr extension itself does not necessarily concern itself with the assignment of CSRs but solely how instructions can interact with them.
  383. There are six instructions added as part of the Zicsr extension, alongside seven pseudo-instructions, six pseudo-instructions related to counters and nine additional pseudo-instructions related to floating-point registers.
  384. The six instructions semantically consist of three instructions, with source register and immediate variants.
  385. In essence, the instructions atomically read the value of a CSR.
  386. Additionally, they write it to the destination register and write new contents into the CSR, although CSRs can be set up to be read/write or read-only.
  387. The first two instructions (\texttt{CSRRW[I]}) are meant to transfer the value of a source register (or an immediate value) to a CSR, while writing the previously held value of the the CSR to the destination register.
  388. The next two instructions (\texttt{CSRRS[I]}) similarly read the value of the CSR and update the CSR, but they use the value in the source register (or an immediate value) as a bit mask instead.
  389. Masked bits are set high in the CSR, while the previously held CSR value is written to the destination register.
  390. The final two instructions (\texttt{CSRRC[I]}) have the same semantics, but they clear bits instead.
  391. Depending on whether the zero register is used as a source or destination register, reads and writes might explicitly not occur.
  392. Because there are many different possible operations, many pseudo-instructions based on these six instructions are offered.
  393. \subsection{Counters Extension \cite[ch. 10]{riscv-isa-vol-1}}
  394. \label{subsection:overview-counters-ext}
  395. The Counters extension (sometimes, but not officially, referred to as Zicntr) is meant to encapsulate all that is necessary to support the operation of hardware performance counters and timers.
  396. Compared to the other extensions, this extension is not actually ratified yet and is subject to change.
  397. It does not actually add any new instructions, but instead offers three pseudo-instructions based on Zicsr (\texttt{RDCYCLE[H]}, \texttt{RDTIME[H]} and \texttt{RDINSTRET[H]}, all based on \texttt{CSRRS}).
  398. This is the case because the performance counters and timers themselves are implemented as read-only CSRs.
  399. For purposes of supporting a higher level of precision, counters and timers are 64-bit CSRs, even on 32-bit architectures.
  400. This is made possible by splitting up the 64-bit values into two separate CSRs.
  401. The pseudo-instructions that have an \texttt[H] suffix read bits 63 to 32.
  402. The \texttt{RDCYCLE[H]} pseudo-instruction reads the CSR \texttt{cycle} which holds a count of the number of clock cycles executed by the processor core on which the hart is running.
  403. The \texttt{RDTIME[H]} pseudo-instruction reads the CSR \texttt{time} which holds the wall-clock real time.
  404. The \texttt{RDINSTRET[H]} pseudo-instruction reads the amount of instructions that were retired by a hart from the CSR \texttt{instret}.
  405. All of these counters count from some arbitrary point in the past.
  406. This conflicts slightly with the RISC-V privileged specification \cite{riscv-isa-vol-2}, which does not specify \texttt{time} as a CSR, but rather two 64-bit memory-mapped registers \texttt{mtime} and \texttt{mtimecmp}.
  407. Additional CSR space is available for hardware performance counters, which can be used for profiling by counting platform-specific events.
  408. They have similar semantics.
  409. \subsection{F, D and Q Extension \cite[ch. 11-13]{riscv-isa-vol-1}}
  410. \label{subsection:overview-fdq-ext}
  411. There exist three separate extensions, all meant to incorporate IEEE 754-2008 floating-point support.
  412. The F extension is meant for single-precision floating-point support, while the D extension targets double-precision and the Q extension quad-precision.
  413. They are set up in a way that implicitly assumes implementation of Zicsr and one another, with the F extension requiring the Zicsr extension, the D extension requiring the F extension and the Q extension requiring the D extension.
  414. The F extension adds a new set of 32 floating-point registers and a CSR that collects accrued exceptions and the rounding mode.
  415. There are plenty of new instructions added to support all kinds of floating-point operations, going well beyond the arithmetic operations of the base integer instruction set.
  416. \subsection{C Extension \cite[ch. 16]{riscv-isa-vol-1}}
  417. \label{subsection:overview-c-ext}
  418. The C extension is meant to add compressed instructions to reduce static and dynamic code size.
  419. This is achieved by trimming common operations to 16-bit instructions.
  420. As such, instructions can now start on any 16-bit boundary.
  421. Many short hand versions of pre-existing instructions are added.
  422. \subsection{Machine-Mode (M-mode) \cite[ch. 3]{riscv-isa-vol-2}}
  423. \label{subsection:overview-m-mode-ext}
  424. This is the first extension listed here that is not part of the RISC-V unprivileged specification, but rather the RISC-V privileged specification, which describes different privilege modes with their respective specified functionality.
  425. It adds several machine-level CSRs as well as Trap-Return and Interrupt-Management instructions.
  426. For M-mode, these instructions are a \texttt{MRET} (M-mode trap return) and \texttt{WFI} (wait for interrupt) respectively.
  427. The CSRs which are added range from read-only CSRs that supply system information to others that control processor behavior.
  428. Examples for this are the \texttt{misa} register, which encodes what parts of the modular RISC-V ISA are implemented and supported by the processor.
  429. Other important CSRs are \texttt{mie} (interrupt-enable register), \texttt{mip} (interrupt pending register) \texttt{mtvec} (trap-handler base address register), \texttt{mstatus} (machine status register), \texttt{mepc} (exception program counter register) and \texttt{mcause} (trap cause register), to list a few.
  430. Not every CSR listed has to be implemented and this applies to all privilege modes.
  431. This is because operating systems do not necessarily make use of all of them.
  432. For some of them, the operating system can still operate without them being implemented if they return default values.
  433. \subsection{Supervisor-Mode (S-mode) \cite[ch. 4]{riscv-isa-vol-2}}
  434. \label{subsection:overview-s-mode-ext}
  435. This extension serves to add optional supervisor-level counterparts of the M-mode extension for the lower S-mode privilege level.
  436. We have seen embedded Linux using glibc make use of this extension.
  437. In general, S-mode is meant for operating systems, while M-mode offers low-level access to the hardware platform.
  438. More instructions are added, which are not only variations of M-mode counterparts.
  439. There is an analogous \texttt{SRET} instruction, but supervisor-level variations of the fence instructions are also added (\texttt{SFENCE.VMA}, \texttt{SINVAL.VMA}, \texttt{SFENCE.W.INVAL} and \break\texttt{SFENCE.INVAL.IR}).
  440. One would need to implement S-mode to support paging.
  441. \subsection{User-Mode (U-mode)}
  442. \label{subsection:overview-u-mode-ext}
  443. The U-mode privilege level is mentioned throughout the RISC-V privileged specification \cite{riscv-isa-vol-2}, but is not as extensively specified as M-mode and S-mode.
  444. This makes sense, because U-mode is intended as the \emph{least privileged} mode and serves to create a boundary to the next privilege mode in order to protect the system from application code.
  445. Valid systems adhering to the privileged specification must have at least M-mode implemented, but it is optional whether to also implement S-mode or U-mode.
  446. As a result, possible configurations are \texttt{M} (simple embedded systems), \texttt{M + U} (secure embedded systems) and \texttt{M + S + U} (systems running Unix-like operating systems), as listed in Table 1.2 of \cite{riscv-isa-vol-2}.
  447. \subsection{Hypervisor-Mode (H-mode) \cite[ch. 8]{riscv-isa-vol-2}}
  448. \label{subsection:overview-h-mode-ext}
  449. This extension implements another privilege level in addition to the other privilege levels.
  450. It is meant for execution environments in which a hypervisor or virtual supervisor is used.
  451. \subsection{Memory Management Unit (MMU)}
  452. \label{subsection:overview-mmu-ext}
  453. Also to be considered a hardware extension is the memory management unit.
  454. This differs from the other hardware extensions in that the MMU is not defined in either of the RISC-V specifications.
  455. But for certain operating systems, having an MMU is required.
  456. We will consider the details in a later part after getting an idea of operating systems, in Section~\ref{subsection:memory-hierarchies}.
  457. \section{Overview of Operating Systems}
  458. \label{section:overview-os}
  459. In order to realize the goal of supporting an operating system, having a precise set of requirements is necessary.
  460. Without comprehensively looking at available options and making an initial choice, it is not possible to focus on this goal.
  461. What follows in this section is an overview that will list operating system choices for RISC-V, details what they offer and require and finally we will make a choice about which one to pick.
  462. As the goal is to offer students something to tinker with for their own understanding, the more features can be offered the better, although this has to be contrasted against operating system complexity to keep the implementation effort feasible.
  463. %\subsection{Available Operating Systems}
  464. RISC-V has certainly gained traction since its inception as a research and teaching ISA.
  465. One proof of this is the wide range of operating systems that do in some way support it.
  466. We will take a quick look at the current state of available operating systems.
  467. There are roughly three classes of operating systems that are available right now for RISC-V processors.
  468. Sometimes software running on RISC-V processors is classified into bare-metal, real-time operating systems and rich operating systems \cite{web-riscv-supporting-an-os}.
  469. Bare-metal software might not qualify as an operating system, but as a category it captures low-level software that does not fall under any of the other two categories and is often a primary target or prerequisite for prototypes due to its relative simplicity.
  470. Although operating systems themselves would qualify as bare-metal software, this term is still used to refer to software which directly takes control of the underlying hardware and does not introduce an additional abstraction layer that fulfills the purposes of an operating system.
  471. A rich operating system is geared more towards enabling many different kinds of purposes without focusing too much on a particular aspect.
  472. For example, they might be used in a lightweight laptop, a powerful desktop workstation or a server, each with their own sets of typical software applications.
  473. Real-time operating systems on the other hand might be considered restricted operating systems, with the specific purpose of fulfilling real-time constraints.
  474. Other special purpose serving operating systems exist, like for example seL4 \cite{web-sel4}, a security-driven but fast microkernel platform.
  475. These other special purpose serving operating systems do not see themselves as a traditional real-time operating system (but might still be real-time, like SAFERTOS \cite{web-riscv-supporting-an-os}) and will be considered separately.
  476. \subsection{Real-Time Operating Systems (RTOSs)}
  477. This class of operating systems is often used to run on microcontrollers that are small, resource-constrained but sometimes mission-critical.
  478. They strike a delicate balance of supporting enough to serve their purpose and keep necessary guarantees but little enough to drive costs low.
  479. Several RTOSs that have been ported to RISC-V devices exist, but their software ecosystems have varying degrees of support for the RISC-V platform as a whole.
  480. To the best of our knowledge, the two best supported RTOSs for RISC-V right now, particularly for the given constraints, are FreeRTOS \cite{web-freertos} and Zephyr RTOS \cite{web-zephyr}.
  481. They don't only offer ports for specific RISC-V processors, but provide comprehensive documentation on how to utilize and adapt them for new ones as well.
  482. FreeRTOS has a dedicated page, among other entries, detailing the steps to get FreeRTOS on a RISC-V platform \cite{web-freertos-riscv}.
  483. Another advantage is that FreeRTOS is configurable enough to support the operation of RISC-V processors with varying extension support.
  484. There are even features to configure it out of the box for processors with different exception and interrupt unit architectures, like for example a SiFive core local interruptor (CLINT)~\cite{sifive-interrupt-cookbook}, and architectures lacking hardware timers.
  485. A lack of hardware timers refers to not implementing \texttt{mtime} and \texttt{mtimecmp} out of the RISC-V privileged specification \cite{riscv-isa-vol-2}.
  486. The other contender is Zephyr RTOS, which is a Linux Foundation project that serves as a software platform for many different microcontrollers.
  487. There is a wide array of actual hardware boards that are supported (18 as of yet!) \cite{web-zephyr-riscv-boards}.
  488. Previously mentioned RISC-V processors, namely the SiFive FU740-C000, LiteX VexRiscv and NEORV32, are supported for example.
  489. There are two more RTOSs that have ports for RISC-V, but lack documentation and only support the operation of highly specific RISC-V processor configurations, none of which are minimal.
  490. This is reasonable, because they target boards that offer a certain minimum of features, but they are hard to deal with for the purposes of this work.
  491. These RTOSs are Huawei LiteOS \cite{web-huawei-liteos} and Apache Mynewt \cite{web-apache-mynewt} respectively.
  492. FreeRTOS and Zephyr RTOS, currently offer much richer flexibility, support and documentation.
  493. \subsection{Rich Operating Systems}
  494. Another class of operating systems exists that has a wider range of available features and customizability.
  495. It encompasses all kinds of use cases, from a desktop computer all the way to a high-performance computing context, with many distributions existing to target a specific set of constraints but otherwise offering a general solution.
  496. Several popular operating systems belong to this class, but don't currently offer any \mbox{RISC-V} support.
  497. Linux however, by way of its open ecosystem as well as active community, does offer support.
  498. For this reason, but also for interoperability and accessibility, we will restrict our analysis of rich operating systems and what it takes to support them to Linux.
  499. There are many ways to utilize Linux as an operating system.
  500. Linux by itself is only a limited component in what constitutes a whole operating system and is usually complemented by additional software.
  501. Because there are so many ways in which Linux can be used, we want to look at Linux configurability and differentiate between full-fledged Linux distributions and embedded Linux.
  502. \subsubsection{Minimal Linux Configuration}
  503. \label{subsubsection:linux-configurations}
  504. Linux is an operating system that serves many different purposes.
  505. It comes in many different forms and each has its own advantages and disadvantages.
  506. By virtue of its completely free and accessible nature, anyone can adopt Linux to fit their needs and many of the distributions we have looked at exist as adaptations.
  507. %Usually Linux is used in a server or desktop configuration by making use of readily available Linux distributions which not only build and distribute Linux, but also offer vast package repositories, automation, documentation, and guidance.
  508. %This is typically very useful when adopting Linux for such platforms, but for embedded platforms the situation is quite different.
  509. %Some of the goals of server or desktop Linux run contrary to the goals of embedded Linux.
  510. %Instead of prepackaging as many programs and features that a user might need, the distribution needs to be kept as small and compact as possible.
  511. %User-friendliness is also not as important.
  512. %All of these different use cases for an operating system like Linux and many more are supported in some way.
  513. %Users of Linux have made sure that it runs on a breathtaking amount of platforms, bridging what seems like deal-breaking differences.
  514. %One such example is support for many different ISAs and microarchitectures, RISC-V and some of its live hardware implementations on actual boards included.
  515. %The most sophisticated server platforms offer complex SIMD instruction support, advanced virtualization features and other performance and security innovations.
  516. %By contrast, Linux runs on those platforms, just like it does on others that don't even offer virtual memory support by lack of an MMU.
  517. A minimal Linux configuration is hard to achieve.
  518. In the first place, it is not clear what the lowest possible requirements really are.
  519. Additionally, some configurations have more support available, with respect to build tools, hardware platforms and general software support.
  520. In theory Linux can support any system, but the question is always at what cost.
  521. The most prevalent uses for Linux have led to an ecosystem in which using Linux for precisely such purposes is easy.
  522. The most obscure uses suffer from their prerequisites to dig deeper, tinker around and making far reaching customizations.
  523. Configuration has to be differentiated between kernel configuration and user space configuration.
  524. \subsubsection{Linux Auxiliary Software}
  525. \label{subsubsection:linux-aux-software}
  526. Linux is only a kernel.
  527. To transform Linux into an operating system that doesn't only perform the operations of a kernel, some sort of user space must be added.
  528. If code is executed only by the kernel it is said to live in kernel space.
  529. Likewise, code that is executed by a user process is said to live in user space.
  530. This separation exists for memory and hardware protection purposes and comes from the fact that code inside virtual memory can be considered to belong to only one of these two spaces.
  531. Besides using Linux as a kernel, different options exist for the user space.
  532. It is primarily provided by way of the C standard library and the applications that come with the operating system itself.
  533. Auxiliary software refers to these additional components of a Linux based operating system
  534. Historically there have been projects that attempt to bring down the size and requirements of Linux, like uClibc \cite{web-uclibc} (the recent version being uClibc-ng), musl \cite{web-musl}, busybox \cite{web-busybox} and buildroot \cite{web-buildroot} to list a few.
  535. uClibc represents a basic C standard library for more minimal purposes than that of the de facto standard for Linux distributions \cite{web-linux-standard-clib}, glibc, developed by the Free Software Foundation.
  536. The other C standard library that is an alternative to glibc is musl, which has the goals of being lightweight, fast, simple, free and correct.
  537. The busybox user space is an alternative to the more resource-intensive GNU user space.
  538. Finally, buildroot serves as a convenient tool to generate embedded Linux systems through cross-compilation.
  539. The projects uClibc, busybox and buildroot are projects that have been developed in conjunction, as they complement each other.
  540. As an example, a Linux system can use uClibc with a busybox user space, built using the buildroot build system.
  541. We will compare configurations using different C standard library implementations and their support, as well as configurations that do or do not use an MMU.
  542. To refer to the lack of an MMU, we will use the term nommu.
  543. \subsubsection{Full-fledged Linux Distributions}
  544. \label{subsubsection:full-fledged-linux}
  545. Several of the major Linux distribution projects have opted to support RISC-V, with varying levels of support.
  546. One of the major distributors of Linux is the Debian project \cite{web-debian}, which not only makes a wealth of Linux distributions for all kinds of targets, but whose work is reflected downstream in other distributions which base themselves on it.
  547. One such distribution is Ubuntu \cite{web-ubuntu}.
  548. Debian has begun working on the RISC-V port many years back and its support has matured by now for several available devices \cite{web-debian-riscv}.
  549. Besides the more low level and lightweight embedded Linux systems we will discuss in a brief moment, Debian is the only full-fledged Linux distribution that has any support for 32-bit RISC-V.
  550. Ubuntu also supports RISC-V, but it is more experimental and limited to 64-bit RISC-V \cite{web-ubuntu-riscv}.
  551. Another family of Linux distributions (the families itself are determined by how software made available to users of the distribution is packaged) is Fedora Linux \cite{web-fedora}.
  552. Its derivatives include Red Hat Enterprise Linux and CentOS.
  553. Fedora also has support for 32-bit RISC-V and some available devices \cite{web-fedora-riscv}.
  554. Yet another distribution supporting 32-bit RISC-V is OpenSUSE \cite{web-opensuse}.
  555. While it does offer support, as of yet its support is largely experimental \cite{web-opensuse-riscv}.
  556. There is also Alpine Linux \cite{web-alpine}, which considers itself a small, simple and secure Linux distribution.
  557. It makes extensive use of more lightweight alternatives to common software packages and thus enables more limited hardware platforms to perform well.
  558. This makes it a good base for containerized applications, as containers strive to run on a base system that is as minimal as possible.
  559. It would also be a great fit for the use case of this project and the RISC-V platform in general.
  560. But although some work was already put into porting it to and supporting RISC-V, none of it has been finalized and there is no official documentation besides experience reports of a few users \cite{web-alpine-riscv}.
  561. \subsubsection{Embedded Linux Distributions}
  562. \label{subsubsection:embedded-linux}
  563. Besides full-fledged Linux distributions, there exist also smaller projects meant to target more specific embedded architectures.
  564. Users are always free to build their entirely own Linux distribution for their device, gaining complete customizability but also inheriting the workload associated with it.
  565. Because this is not productive if everyone repeats such efforts, certain projects have attempted to streamline the process of building an embedded Linux distribution by offering sophisticated build systems.
  566. An important difference between these projects and aforementioned Linux distributions is that they are not themselves Linux distributions, but build systems that can generate Linux distributions for many different embedded devices.
  567. One such build system is buildroot \cite{web-buildroot}, which offers multiple ways for users to configure all aspects of the resulting Linux system.
  568. Buildroot itself has support for RISC-V in several different configurations.
  569. Extension support can be toggled, different ABIs can be targeted, target architecture size can be configured, MMU support (in general buildroot tries not to assume whether a system supports virtual memory) can be disabled and more \cite{web-buildroot-riscv}.
  570. Another build system is the Yocto Project \cite{web-yocto}.
  571. It exists for many of the same reasons and is sometimes compared directly against buildroot \cite{web-buildroot-vs-yocto}.
  572. The Yocto Project uses a more modular approach and users can supplement their own compatibility layers.
  573. These layers define all necessary configurations and recipes for users to build their own system.
  574. Through one of these layers, the Yocto Project supports RISC-V \cite{web-yocto-riscv}.
  575. \subsection{Special Purpose Operating Systems}
  576. These systems form the last class of operating systems.
  577. They are neither real-time operating systems (which are well established as a class of their own), nor one of the rich operating systems.
  578. They don't base themselves on any of the pre-existing rich operating systems, having been built from the ground up to satisfy certain constraints to the best of their ability.
  579. Such constraints might be code size, performance or security.
  580. But they also serve as experimental platforms to test unique innovations on.
  581. Because of their reduced scope, they are often simpler and thus more easily ported to new architectures.
  582. Three such operating systems are the seL4 Microkernel \cite{web-sel4}, Harvey OS \cite{web-harveyos}, as well as HelenOS \cite{web-helenos}.
  583. Each of them has seen efforts to extend their support to RISC-V, but with varying degrees of success.
  584. The seL4 Microkernel as a selling point offers functional correctness proofs for hardware architectures it supports, but this has only been done for a single device that hosts a 64-bit RISC-V processor \cite{web-sel4-riscv}.
  585. Harvey OS also has new configuration options to support RISC-V, but the full extent of its support is unclear \cite{web-harveyos-riscv}.
  586. Lastly, HelenOS has also been ported to RISC-V, but as of yet there is no official documentation to go by \cite{web-helenos-riscv}.
  587. \section{Making a Choice}
  588. \label{section:making-a-choice}
  589. An ever-present theme with many of these operating systems and their support for RISC-V is their varying degree of quality with respect to their documentation and device support.
  590. This is only natural, as RISC-V is still relatively new and the platform as a whole is not yet mature.
  591. While there is now quite a range of actual hardware available, RISC-V itself strives to be modular and support as many hardware configurations as possible.
  592. This is one of the strengths, but simultaneously a weakness, as it fragments the ecosystem and makes supporting the RISC-V architectures more difficult for maintainers of software.
  593. At this stage, much of the support for RISC-V by operating systems is experimental and exists to serve as a proof of concept.
  594. Some of it is relatively mature however, particularly those projects that have invested more effort and started sooner.
  595. For the scope of this thesis we cannot take a close look at all of these operating systems, so there is a choice to be made even before beginning to adapt and possibly extend an operating system insofar as necessary.
  596. This choice also needs to align with the goals stated in Chapter~\ref{chapter:introduction}.
  597. Looking at the real-time operating systems, out of all the choices, only two of them are at a state appropriate for use on RISC-V, FreeRTOS and Zephyr RTOS.
  598. The other options have not yet matured.
  599. Both FreeRTOS and Zephyr RTOS on the other hand can feasibly be ported to run on the MiRiV processor.
  600. Although rich operating systems would be best suited for rich demonstrations of processor capabilities, they are more geared towards platforms that have support for common RISC-V extensions such as the multiplication, atomics, and floating-point extensions, more sophisticated memory hierarchies and additional performance enhancing extensions.
  601. Particularly with full-fledged Linux distributions, for reasons of modernity and practicability, a 64-bit architecture is often assumed.
  602. This stands in direct contrast with what is currently available with the MiRiV processor, so these operating systems will not be considered further.
  603. As for the embedded Linux distributions, their flexibility allows them to cater to a great wealth of hardware platforms and utilizing them for the MiRiV processor is more feasible.
  604. Between buildroot and Yocto Project, buildroot currently has more accessible documentation and is by itself more accessible because of its focus on simplicity \cite{web-buildroot-vs-yocto}.
  605. Yocto Project, designed as a powerful tool to support powerful abstractions, comes at the price of understanding its abstractions and the tools it relies on.
  606. Buildroot on the other hand re-uses common development tools for its build system and is constrained in complexity, making it easier to use and easier to get familiarized with.
  607. For our purposes it is not necessary to streamline the entire process of creating elaborate Linux distributions, packaging a lot of software and enabling complex release cycles where only parts can be exchanged, which would all be possible with Yocto Project.
  608. Because buildroot supports some of these features but in a simpler fashion, not much is lost in choosing buildroot.
  609. As a result, we will restrict our analysis to Linux generated by the buildroot build system only.
  610. The last class of operating systems, special purpose operating systems, would typically offer a good opportunity for processor designs like MiRiV.
  611. Their relative obscurity and lack of extensive documentation make porting them difficult however.
  612. They also do not exhibit as big and vibrant of an ecosystem as specifically Linux does and are more limited in their uses.
  613. While it would be interesting to analyze them further, they will not be considered for the purposes of this thesis.
  614. The operating systems that will thus be examined more closely are FreeRTOS, Zephyr RTOS and embedded Linux (generated using the buildroot build system).
  615. All of them can target 32-bit platforms, like the MiRiV processor, and they will be used as such.
  616. This is not coincidental of course, the choices were deliberately made to support the existing 32-bit design.
  617. While a change of the design to 64-bit would be possible, the end result would not fit our purposes well, as these extensions are intended for a lab course in which 32-bit designs have to be implemented.
  618. %For both FreeRTOS, Zephyr RTOS and embedded Linux, we will take a closer look at their extension requirements in Section~\ref{section:os-ext-analysis}. But before we do, we will take a closer look at Linux configurations and auxiliary software.
  619. \section{Analyzing Operating System Requirements}
  620. \label{section:os-ext-analysis}
  621. To implement only what is necessary, we will need to have a clear picture of the extension requirements of all the operating systems of choice.
  622. This is not exactly as trivial as looking at requirement lists, because the operating systems themselves support many different configurations and could be adapted still to require fewer or more extensions.
  623. We will first make builds of each operating system to get actual binaries that will later have to run on the target device.
  624. These builds can be examined more closely using a disassembler to see which instructions are contained and thus find out the extension requirements.
  625. \subsection{Memory Hierarchies}
  626. \label{subsection:memory-hierarchies}
  627. Before looking at operating system builds however we will make a quick excursion to memory hierarchies.
  628. Advanced processors have advanced memory hierarchies, supporting multiple layers of memory.
  629. Beyond the cache lies actual memory, but because memory layers that lie outside the processor often have multitudes of higher memory latencies, sophisticated systems were invented to lessen the resulting performance penalty.
  630. Aspects other than performance are also important, such as memory protection and code relocation.
  631. A memory hierarchy consisting of multiple layers of caches, together with a virtual memory system on top, is found in many different commercially available processors.
  632. Virtual memory has many different advantages and disadvantages.
  633. In essence, it serves to create virtual memory regions (memory pages) that are addressed using virtual addresses.
  634. These virtual memory regions map to physical memory regions, but require a system for address translation.
  635. This system comes in the form of a memory management unit.
  636. Modern operating systems run on modern processors and thus make extensive use of these capabilities.
  637. But besides interrupt and exception handling to process events (such as page faults, which occur when a memory page is not currently loaded in main memory), virtual memory support requires dedicated address translation hardware and setting up an entire memory hierarchy.
  638. Even embedded Linux configurations (such as buildroot 2022.08 build we will soon take a look at) make use of virtual memory, as MMU support by processors becomes ever more ubiquitous.
  639. But some microcontrollers do not contain an MMU and for this reason, some operating systems still target systems without virtual memory.
  640. All RTOSs as well as the nommu embedded Linux configuration (using a forked buildroot 2022.05) we will look at run on systems without an MMU.
  641. Without an MMU, code organization becomes more difficult:
  642. In Linux, programs are usually compiled into the ELF binary format, which is a format used to store position-independent code.
  643. When executing ELF executables, process-specific virtual memory is created, executable code and data sections are copied and the program counter is set to the entry point address.
  644. Without virtual memory support, an application has to be loaded at fixed respective memory addresses because parts of it will expect that code to be there.
  645. RTOSs circumvent this issue by taking all kernel and user space code and compiling them together into a single binary, organized in a way where no such issues can arise.
  646. The embedded Linux build uses uClibc, which supports a different binary format, the binary flat (bFLT) format \cite{web-uclibc-bflt}.
  647. This format is a descendant of the a.out format.
  648. The original uClibc project supplies a tool called elf2flt that converts ELF to bFLT for nommu Linux targets \cite{web-uclibc-elf2flt}.
  649. This is done by relocating sections and changing references to absolute addresses.
  650. Implementing an MMU is not a small effort.
  651. For this reason we are more interested in trying to run basic operating systems without having to implement an MMU and the rest of virtual memory.
  652. \subsection{Build Systems}
  653. The builds themselves have to be made using a RISC-V toolchain like the RISC-V GNU toolchain \cite{web-riscv-gnu-toolchain}.
  654. This includes software tools like the GCC, the GNU Compiler Collection, configured to target RISC-V.
  655. The disassembler itself is also already part of this toolchain.
  656. Because RISC-V as an ISA has a modular design, this toolchain can be configured to target different target architectures with varying degrees of support for extensions.
  657. Of course a compiler that already only targets the base integer instruction set won't generate any of the instructions that are part of any additional extension (with the exception of extensions like Zicsr).
  658. But because the operating systems' build processes themselves sometimes assume special toolchain configurations, the builds will be created using as minimal a toolchain configuration as is possible.
  659. The result will then be examined to see which extensions, if any, are actually required.
  660. Furthermore, to examine a more lightweight embedded Linux configuration, we will make use of unofficial buildroot patches.
  661. At the time of writing, buildroot (version 2022.08) only supports a limited set of embedded Linux configurations targeting RISC-V.
  662. Going lower with the requirements would require patching buildroot and Linux, which is not a trivial effort.
  663. Others have done this and as such, we will also consider an embedded Linux system produced by a forked buildroot that enables us to use uClibc in a nommu configuration.
  664. One buildroot fork by Damien Le Moal has enabled buildroot to target a nommu configuration for 64-bit RISC-V embedded Linux \cite{web-buildroot-fork-damien-lemoal}.
  665. GitHub user regymm has extended this effort to support 32-bit systems \cite{web-buildroot-fork-regymm}.
  666. It is this second fork that targets 32-bit systems we will be using.
  667. FreeRTOS is straightforward when it comes to build systems.
  668. The operating system is offered as a set of sources and sample projects that can be adopted with their respective build systems, which often use Makefiles.
  669. One could adopt the sources and integrate them into an existing build process, which makes FreeRTOS attractive for the purpose of running it on the MiRiV processor.
  670. Zephyr RTOS is intended to be used in conjunction with its sophisticated build system which makes extensive use of CMake and a meta tool called West.
  671. Getting Zephyr RTOS to support the MiRiV processor would also require creating respective hardware definitions in the format of DeviceTree sources.
  672. Because such additional integrations are not necessarily a straightforward task and go against the previously stated goal of getting to a state where an operating system can be run on the MiRiV processor within the scope of a bachelor thesis, FreeRTOS will be preferred over Zephyr RTOS.
  673. Thankfully due to existing support to similarly equipped RISC-V processors, we can still at least include Zephyr RTOS in our analysis.
  674. Consequently, the operating systems in consideration are FreeRTOS, Zephyr RTOS and embedded Linux (the first configuration built using buildroot version 2022.08, the second using the buildroot fork version 2022.05 with the nommu patch).
  675. In the embedded Linux systems, a busybox shell session is executed as the root process (no change in preconfigured default behavior when building embedded Linux using buildroot).
  676. FreeRTOS is set up to make use of the pre-existing MiRiV UART software infrastructure, executing two threads that output to UART periodically.
  677. Zephyr RTOS is set up to use the NEORV32 board configuration (mentioned earlier), which is itself a minimalistic soft-core 32-bit RISC-V SoC, with the same application as on FreeRTOS tweaked to use Zephyr RTOS libraries \cite{web-neorv32}.
  678. This is acceptable for comparison purposes because of the way Zephyr RTOS is set up to produce a final build.
  679. The DeviceTree specifications exist in order to be able to include code for features for peripherals, like for example UART or SPI.
  680. When such features are used, code is included that is specific to the targeted hardware specification.
  681. In the application running on FreeRTOS and Zephyr RTOS, only threading features to run two threads on a single core are used, the pre-existing MiRiV UART interface and library are re-used, thus not resulting in the inclusion of any NEORV32 specific code.
  682. \subsection{Analysis Results}
  683. \label{subsection:os-analysis-results}
  684. To achieve the results that follow in this section, the four operating systems were built in configurations described in the previous section on build systems and the resulting binary files disassembled using \texttt{objdump} of the RISC-V GNU toolchain \cite{web-riscv-gnu-toolchain} to extract instruction counts and other relevant data.
  685. \begin{table}[ht]
  686. \centering
  687. \begin{tabularx}{\textwidth}{r|cccc}
  688. & \multicolumn{4}{c}{OS configuration} \\
  689. \hline
  690. & & & buildroot 2022.08 & buildroot 2022.05 \\
  691. standard & FreeRTOS & Zephyr RTOS & Linux 5.17 & Linux 5.18 \\
  692. extensions & & & (glibc + busybox) & (uClibc + busybox) \\
  693. \hline
  694. M & \catPE & \catPE & \catPE & \catSN \\
  695. A & \catEX & \catEX & \catSN & \catSN \\
  696. Zifencei & \catEX & \catEX & \catSN & \catSN \\
  697. Zicsr & \catSN & \catSN & \catSN & \catSN \\
  698. Counters & \catEX & \catEX & \catSN & \catEX \\
  699. F, D, Q & \catEX & \catEX & \catSN & \catPE \\
  700. C & \catPE & \catPE & \catPE & \catPE \\
  701. \end{tabularx}
  702. \caption{\label{table:rv-unpriv-classification}Classification of RISC-V unprivileged ISA standard extensions \cite{riscv-isa-vol-1} with respect to different operating systems (Legend: \catSN = strictly necessary, \catPE = performance enhancing, \catEX = expendable)}
  703. \vspace{1ex}
  704. \end{table}
  705. Table~\ref{table:rv-unpriv-classification} displays all sampled requirements of all the given operating systems in terms of RISC-V unprivileged specification ISA extensions.
  706. Only stable ISA extensions were considered, as other extensions are currently in the process of being standardized and have yet to reach a stable state.
  707. The aforementioned categorization scheme (Section~\ref{section:categorization-scheme}) using four categories is used to delineate each of the extensions that can be made and what category they fall under.
  708. Likewise, Table~\ref{table:rv-priv-classification} shows whether auxiliary units such as an MMU or any of the RISC-V privileged specification ISA extensions are necessary.
  709. \begin{table}[ht]
  710. \centering
  711. \begin{tabularx}{\textwidth}{r|cccc}
  712. & \multicolumn{4}{c}{OS configuration} \\
  713. \hline
  714. & & & buildroot 2022.08 & buildroot 2022.05 \\
  715. privilege & FreeRTOS & Zephyr RTOS & Linux 5.17 & Linux 5.18 \\
  716. modes & & & (glibc + busybox) & (uClibc + busybox) \\
  717. \hline
  718. M-mode & \catSN & \catSN & \catSN & \catSN \\
  719. S-mode & \catEX & \catEX & \catSN & \catCO \\
  720. U-mode & \catEX & \catEX & \catEX & \catEX \\
  721. H-mode & \catEX & \catEX & \catEX & \catEX \\
  722. \hline
  723. MMU & \catEX & \catEX & \catSN & \catCO \\
  724. \end{tabularx}
  725. \caption{\label{table:rv-priv-classification}Classification of RISC-V privileged ISA privilege modes and whether they require an MMU \cite{riscv-isa-vol-2} with respect to different operating systems (Legend: MMU = memory management unit, M-mode = machine mode, S-mode = supervisor mode, H-mode = hypervisor mode, \catCO = convenient, \catSN = strictly necessary, \catEX = expendable)}
  726. \vspace{1ex}
  727. \end{table}
  728. \begin{figure}[ht]
  729. \centering
  730. \includegraphics[width=.95\textwidth]{os-base-histogram.png}
  731. \caption{Base integer ISA instructions across systems grouped by respective subcategories.}
  732. \label{fig:os-base-histogram}
  733. \end{figure}
  734. \begin{figure}[H]
  735. \centering
  736. \includegraphics[width=.95\textwidth]{os-ext-histogram.png}
  737. \caption{Instructions compared across systems grouped by their classification in the RISC-V unprivileged and privileged specifications, excluding base integer ISA instructions grouped in Figure~\ref{fig:os-base-histogram}.}
  738. \label{fig:os-ext-histogram}
  739. \end{figure}
  740. Figure~\ref{fig:os-base-histogram} is a comparison between all considered operating systems and their base integer instruction distribution within the disassembled linked binary.
  741. Not only is the total count of base integer instructions displayed, but they are also grouped by different categories.
  742. The scale was chosen to be logarithmic for the categories to be comparable to one another.
  743. The category for arithmetic instruction include those that operate on three registers, as well as their immediate instruction form counterparts.
  744. Branch and jump instructions are in two separate categories.
  745. The U format (\texttt{LUI}, \texttt{AUIPC}) instructions were included in the category for jump instructions, as they are commonly used for subsequent jumps.
  746. Load and store instructions are also in their own category.
  747. Finally, there is a category for system instructions, which groups together those which are part of the base integer instruction set but do not belong in any of the aforementioned categories (\texttt{ECALL}, \texttt{EBREAK}, \texttt{FENCE}).
  748. Figure~\ref{fig:os-ext-histogram} does not look at any of the base integer instructions, but instead considers all instructions which are part of some extension.
  749. The Counters extension doesn't introduce any new instructions, but re-uses CSR instructions introduced by the Zicsr extension.
  750. Still, it is possible to detect their use or label them using their respective pseudo-instructions (\texttt{rdinstret[h]}, \texttt{rdcycle[h]}, \texttt{rdtime[h]}).
  751. As can be seen, the real-time operating systems compare favorably against embedded Linux configurations in terms of code size and required complexity by having a much smaller footprint and requiring markedly less extension support.
  752. These are desirable properties to have when not all the complex features of the extendable instruction set can be implemented.
  753. The embedded Linux systems practically assume the A extension, but profit from an implementation of other extensions.
  754. When targeting a system with an MMU, S-mode (supervisor mode) instructions are necessary as well.
  755. Not surprisingly, none of these lightweight systems contain any H-mode (hypervisor mode) instructions.
  756. The Zicsr extension is strictly necessary for all operating systems.
  757. FreeRTOS uses the least amount of distinct CSRs (mcause, mepc, mhartid, mie, mstatus and mtvec).
  758. Zephyr RTOS makes use of the same CSRs, but uses additional ones as well (mcountinhibit, mcycle, mcycleh, minstret, minstreth and mtval).
  759. As for Linux (glibc + busybox), it doesn't make use of any of the M-mode CSRs, but instead uses S-mode CSR counterparts (satp, scause, sepc, sie, sip, sscratch, sstatus, stval and stvec).
  760. This is because normally, M-mode (being the highest privilege level) is reserved for system firmware.
  761. Linux (uClibc + busybox) nommu on the other hand uses the same CSRs as FreeRTOS, with some additional ones (marchid, mimpid, mip, mscratch, mtval, mvendorid, pmpaddr0 and pmpcfg0).
  762. It is important to note that for the RTOSs, the M extension is optional and only inserted, if a compiler that targets the M extension is used.
  763. For the sake of our analysis, we have enabled the M extension.
  764. \subsection{Eliminating Requirements}
  765. These requirements are samples of what needs to be implemented with currently available software.
  766. In theory, many of these requirements can be eliminated by patching these software tools and the operating systems themselves to run without them.
  767. Doing so necessitates a considerable amount of changes to be made just to support the modified operating systems.
  768. Any programs that are intended to be run on the deployed operating system could require such changes as well.
  769. Whether it is more worthwhile to implement these extensions instead of intervening to make such an effort unnecessary by software adaptations is an interesting question.
  770. For some of these extensions and operating systems, like the A extension for embedded Linux, eliminating their requirement is uneconomical.
  771. In the case of the A extension for embedded Linux: The distributions were generated using buildroot, which compiles a custom toolchain that is then used to cross-compile the Linux kernel and busybox.
  772. This entire process makes certain assumptions during compile time, where support for the A extension is one of them.
  773. Thus, to eliminate the A extension requirement for embedded Linux, which might not by itself be hard to meet, one would have to adapt this process not to assume the A extension.
  774. As an alternative, correct execution of instructions introduced by the A extension could be emulated by trapping on illegal instruction exceptions and then decoding and executing them in software.
  775. But the extent of this effort is difficult to gauge and dependencies that might surface are not at first transparent.
  776. \pagebreak
  777. \section{Conclusion}
  778. \label{section:overview-conclusion}
  779. To provide a compact overview, in the following section the main insights with respect to RISC-V ISA extensions presented in this chapter are summarized.
  780. \subsection{Unprivileged ISA Extensions}
  781. \textbf{M Extension }
  782. While support for the M extension does increase performance, build tools do not necessarily explicitly require M extension support.
  783. %As we will see, support for the M extension is not too big of a task, so it is up to us to decide whether to equip the MiRiV processor with M extension support.
  784. \textbf{A Extension }
  785. For RTOSs and our simple two-task UART application, A extension support is not necessary.
  786. For any Linux based operating system, such as both embedded Linux configurations we have looked at, this extension is strictly necessary.
  787. \textbf{Zifencei Extension }
  788. The conclusion we have reached for the A extension also applies here.
  789. \textbf{Zicsr Extension }
  790. All operating systems we have looked at require Zicsr.
  791. This is not too surprising considering that besides being vital for managing the state and correct execution of each core, it is strictly necessary to support any kind of exception, interrupt and trap handling.
  792. Although it is possible to roll one's own system to support interrupts for example, using the already defined CSRs provides a fairly standardized way for hardware and software to interact with the common goal of managing exceptions, interrupts and traps.
  793. But CSRs that serve quite different purposes exist too.
  794. \textbf{Counters Extension }
  795. This extension is only explicitly used by the embedded Linux (glibc) configuration.
  796. \textbf{F, D, Q Extensions }
  797. For some applications, floating-point support is vital.
  798. For others, it might not be necessary (we marked it as expendable in our OS analysis) and going without it saves many hardware resources and implementation efforts.
  799. Operating systems also support processors that don't have floating-point support, so the implementation of these three extensions is optional.
  800. \textbf{C Extension}
  801. While it can offer a respectable improvement in code sizes and even performance (by virtue of relieving the instruction cache slightly), it is optional and implementing it takes effort.
  802. There are not only many instruction variations added, but because 16-bit and 32-bit instructions are intermixed, instructions can now start on any 16-bit boundary, complicating the fetch and decode stages.
  803. \subsection{Privileged ISA Extensions}
  804. \textbf{M-mode }
  805. The most basic execution environment for all operating systems includes at least M-mode instructions.
  806. As such, implementing M-mode is unavoidable.
  807. There is not too much additional specific M-mode functionality to be implemented to support it, because there is an overlap with other unprivileged ISA extensions, such as Zicsr for example.
  808. \textbf{S-mode }
  809. For standard Linux systems, such as the embedded Linux (glibc) configuration we have looked at, S-mode is a requirement.
  810. This is because an execution environment with separated machine and supervisor levels is assumed.
  811. For the implementation of embedded Linux (glibc) supporting at least a subset of the S-mode extension is unavoidable.
  812. \textbf{H-mode }
  813. If we were to support operating systems with even more powerful features, systems that make use of a hypervisor for example, we would need to implement the H-mode extension.
  814. Because it is a complex extension with many additions, while at the same time not being used at all by considered operating systems, we will not take a closer look at this extension.
  815. \subsection{The Next MiRiV Processor}
  816. Out of all possibilities of our preliminary choices and our analysis thus far, it is clear that supporting the execution of an operating system necessitates the implementation of a system for trap handling, at the very least.
  817. It is also clear that embedded Linux has strictly greater set of requirements than the RTOSs in consideration, making it imperative to support RTOSs first.
  818. Thus it was determined that the first step would be to support an RTOS.
  819. Out of FreeRTOS and Zephyr RTOS, FreeRTOS was chosen for its simplicity, maturity, unopinionated build system, RISC-V support and clear implementation path.
  820. %These reasons have already been outlined but are reiterated here as a reminder.
  821. To support FreeRTOS, we will need to implement the Zicsr extension and a system for trap handling, at the privilege level of M-mode.
  822. It was deemed appropriate to also include the M extension and a branch predictor, because this effort could be completed in a concerted effort with a colleague for whom it is also beneficial to include these extensions.
  823. The effort required to go from an implementation that supports FreeRTOS to an implementation that supports embedded Linux is not entirely predictable, but was found to be high (due to necessary architectural additions and/or porting effort) and beyond the scope of this work.
  824. % CHAPTER
  825. \chapter{Architectural Considerations}
  826. \label{chapter:architecture}
  827. In Chapter~\ref{chapter:overview} we have examined available RISC-V ISA extensions, different operating systems and their precise requirements.
  828. %In this chapter we want to take a quick tour of how an extension might be implemented and what costs and benefits such an implementation would entail.
  829. In this chapter we want to take a quick tour of what properties an extension implementation needs to fulfill and what costs and benefits its implementation would entail, by examining which components, registers and instructions need to be added.
  830. We want to constrain ourselves only to extensions that have proven to be strictly necessary for RTOSs and those that are used in the simpler of the two embedded Linux cases (using uClibc).
  831. In addition, we will consider the M extensions and a non-ISA related microarchitectural extension that is (for our purposes) completely separate of any operating system and can serve to greatly improve system performance, namely branch prediction.
  832. These two extensions, even though they are considered performance enhancing, are included because an implementation for them was developed in conjunction with a colleague.
  833. These considerations are not necessarily related to the final implementation, which is further outlined in more detail in the next chapter.
  834. Rather, this chapter serves to show briefly which design decisions can be made and what their respective trade-offs are.
  835. \section{Exception, Interrupt and Trap Architecture}
  836. \label{section:exc-int-trap-arch}
  837. An operating system managing different tasks, such as external events triggered by peripherals, let alone its own events if they can occur simultaneously, assumes interrupts and exceptions to be supported.
  838. Almost no modern processor runs without some kind of interrupt architecture.
  839. The RISC-V specification defines the term \textit{exception} to refer to events caused internally by usual or unusual conditions associated with an instruction being executed, \textit{interrupt} to refer to externally caused events and \textit{trap} to refer to the transfer of control to a trap handler caused by either of the two \cite{riscv-isa-vol-1}.
  840. They might be differentiated by categorizing exceptions as synchronous and interrupts as asynchronous, as the former is associated with the well-defined execution of a hardware thread (hart), while the latter can be triggered at any time externally.
  841. There are different interrupt controller designs to support exceptions, interrupts and traps.
  842. Many designs are possible, but we want to restrict ourselves to designs that are relatively standardized and thus predictable for operating system developers.
  843. SiFive has thankfully already tackled this problem and produced a cookbook that lists three different architectures \cite{sifive-interrupt-cookbook}.
  844. We will consider their interrupt controller designs first.
  845. The most basic design is the Core Local Interruptor (CLINT), which has a fixed priority scheme and implements software, timer and external interrupts.
  846. Then there is the Core Local Interrupt Controller (CLIC), which sports a more flexible configuration compared to the CLINT, at the cost of being a more complex design.
  847. Advantages are reverse compatibility and programmable interrupt levels and priorities, among others.
  848. Both CLIC and CLINT, as the name implies, are core local units and thus meant for single hart systems.
  849. Going beyond this constraint is the Platform Local Interrupt Controller (PLIC), which is a more advanced design that may dispatch interrupts to more than one hart.
  850. This makes it a global interrupt controller.
  851. It has the highest amount of complexity, but also the highest amount of flexibility.
  852. Because the CLINT is the best fit for our application, we will consider it in more detail.
  853. \subsubsection{Core Local Interruptor (CLINT)}
  854. The CLINT can be best understood by examining what CSRs it depends on and what functionality these CSRs are meant to add to the processor as a whole.
  855. To start off, there are interrupt related CSRs (\texttt{mstatus}, \texttt{mcause}, \texttt{mie}, \texttt{mip}, \texttt{mtvec}, \texttt{mtvt}, \texttt{msip}).
  856. Early in the boot flow, the CSR \texttt{mtvec} (M-mode trap vector) needs to be set up, in particular for exception handling in case any early errors occur, because it determines where the hart will jump to in order to handle the trap.
  857. Its first two bits are set up to contain the mode \texttt{mtvec.mode = mtvec[1:0]}, while the higher order bits contain the trap vector base-address \texttt{mtvec.base = mtvec[31:2]}.
  858. The two modes currently specified are the direct mode and vectored mode.
  859. This can also be seen in Figure~\ref{fig:mtvec-register}.
  860. \begin{figure}[h]
  861. \centering
  862. \includegraphics[width=\textwidth]{mtvec-register.png}
  863. \caption{Register layout for \texttt{mtvec} as can be found in \cite[Fig.~3.9]{riscv-isa-vol-2}.}
  864. \label{fig:mtvec-register}
  865. \end{figure}
  866. Direct mode (\texttt{mtvec.mode = 0}) traps all exceptions and interrupts to the same handler with no vector table, thus incurring an additional software cost to determine where to continue execution.
  867. Vectored mode (\texttt{mtvec.mode = 1}) introduces a vector table that stores addresses of the trap handlers, which lowers latency.
  868. The precise mechanism to address the correct handler is to use the base address \texttt{mtvec.base} stored in CSR \texttt{mtvec} with an added offset stored in CSR \texttt{mcause} (multiplied by a factor of four).
  869. Each time an exception or interrupt occurs, the CSR \texttt{mcause} will be populated according to what has caused the transfer of control flow.
  870. The highest bit denotes whether the source is an interrupt or an exception, while the lower bits contain the code associated with respective causes.
  871. For direct mode, when jumping to \texttt{mtvec.base} the hart encounters a software defined method that determines what to do next.
  872. In vectored mode, there is a contiguous memory region of jump instructions for all the different interrupt handlers at \texttt{mtvec.base} and the hart jumps to \texttt{mtvec.base} $+$ (\texttt{mcause.code} $\times 4$).
  873. The jump instruction that lies at each interrupt handler offset stores the address of the actual interrupt handler.
  874. \section{M Extension}
  875. \label{section:m-arch}
  876. The M extension adds multiplications and divisions.
  877. To support this, a multiplication and division (muldiv) unit could be implemented in conjunction with additions to the decode pipeline stage to decode the new instructions.
  878. All instructions use the R-type instruction format and have two source registers and a destination register, together with an opcode and a funct3 section that specifies the operation.
  879. Figure~\ref{fig:m-ext-instructions} shows their layout.
  880. For multiplications, the sources can be interpreted either as signed or unsigned integers.
  881. \begin{figure}[h]
  882. \centering
  883. \includegraphics[width=\textwidth]{m-ext-instructions.png}
  884. \caption{M extension multiplication, division and remainder instruction layout as can be found in \cite[Ch.~7]{riscv-isa-vol-1}.}
  885. \label{fig:m-ext-instructions}
  886. \end{figure}
  887. Multiplication and division can be costly in terms of hardware resources, but division more so in particular.
  888. Because of this, an extension called Zmmul is in the process of being specified which adopts only multiplication instructions of the M extension.
  889. These instructions are analogous to other arithmetic instructions, so the muldiv unit can be incorporated into the execute stage right alongside the ALU.
  890. Whereas the ALU completes in a single cycle however, it is to be expected that muldiv will take multiple cycles.
  891. This brings a requirement for the control unit to handle subsequent stages of the pipeline while waiting for muldiv to complete its operation.
  892. \section{A Extension}
  893. \label{section:a-arch}
  894. As we have seen, for this extension we would need to implement Load-Reserved/Store-Conditional (\texttt{LR.W} and \texttt{SC.W}) and atomic memory operation (AMO) instructions (\texttt{AMO(SWAP|ADD|AND|OR|XOR|MAX[U]|MIN[U]).W}), all of which use the R-type instruction format, but with the highest seven bits allocated as \textit{funct5}, \textit{aq} (acquire), \textit{rl} (release) fields.
  895. This is further illustrated in Figure~\ref{fig:a-ext-instructions}.
  896. For multi-core systems, implementing this extension is not at all trivial.
  897. With our single-core system, atomics are easier to support however.
  898. \begin{figure}[h]
  899. \centering
  900. \includegraphics[width=\textwidth]{a-ext-instructions.png}
  901. \caption{A extension Load-Reserved/Store-Conditional and atomic memory operation instruction layout as can be found in \cite[Ch.~8]{riscv-isa-vol-1}.}
  902. \label{fig:a-ext-instructions}
  903. \end{figure}
  904. These instructions serve not only as synchronization mechanisms, but they keep data consistent from irregular control flow.
  905. If interrupts are implemented, special care needs to be taken that interrupts do not interfere with a sequence of instructions that are supposed to be atomic.
  906. For single instruction operations, there is no problem, because they are inherently atomic in our single-core system.
  907. Store-Conditional instructions use a return code to specify operation success or failure, used to retry on failure.
  908. Using a Load-Reserved/Store-Conditional sequence is specified to eventually succeed, under certain pre-existing conditions.
  909. For this reason inside a Load-Reserved/Store-Conditional sequence certain instructions are not allowed, the most recent Load-Reserved and Store-Conditional addresses must align and have the same data size, and other additional conditions.
  910. This category of forbidden instructions also includes \texttt{JALR}, \texttt{FENCE} and \texttt{SYSTEM} (\texttt{(ECALL|EBREAK)}) instructions, loads, stores, backward jumps, taken backward branches, but also those of all other extensions (except for compressed versions of allowed instructions) \cite{riscv-isa-vol-1}.
  911. For an implementation of this extension, we would thus need to ensure that under these conditions there is in fact eventual success of an appropriate Store-Conditional instruction.
  912. The AMO instructions are not so simple:
  913. "These AMO instructions atomically load a data value from the address in \textit{rs1}, place the value into register \textit{rd}, apply a binary operator to the loaded value and the original value in \textit{rs2}, then store the result back to the address in \textit{rs1}." \cite{riscv-isa-vol-1}
  914. Because of these complicated semantics, they are not a small addition even to MiRiV (5-stage pipelined single-core implementation).
  915. If we wanted to re-use all existing pipeline stages and their components we would run into a problem:
  916. The value that is loaded would be read only in the memory stage and written back in the write-back stage, but the loaded value needs to be available already in the execute stage (where the ALU that would already support addition and binary logic resides) to apply the binary operator.
  917. One way to implement these semantics is to disable interrupts and emit a sequence of base integer instruction set instructions that emulates the behavior of these atomic instructions.
  918. Another would be to support all binary operators in the memory stage by immediately using the read value in combinatorial logic, possibly extending the critical path and bringing overall performance down.
  919. Finally, for systems supporting trap handling an uninterruptible trap could provide an implementation for all the AMO instructions.
  920. \section{Zifencei Extension}
  921. \label{section:zifencei-arch}
  922. The Zifencei extension serves as a mechanism of synchronizing data and instruction streams, typically because instruction memory needs to be reloaded because it was pre-fetched but modified in the meantime.
  923. A simple pipelined implementation could ensure that it reads the updated value by flushing the pipeline and forcing the fetch stage to load all upcoming instructions again.
  924. In our pipeline, another option would be to emulate the behavior of a branch, jumping to the following instructions unconditionally on an instruction fence and causing a pipeline flush.
  925. The pipeline flush would be caused after all writes have been completed.
  926. However, in our pipeline the instruction and data memories are separate and the instruction memory is not writable by the pipeline.
  927. In order to comply with the Zifencei extension, we would first need to enable instruction memory writes, a feature that is not required anyway.
  928. %This actually makes any compliance with the Zifencei extension impossible, without first enabling instruction memory writes.
  929. \section{Zicsr Extension}
  930. \label{section:zicsr-arch}
  931. We have already outlined most characteristics of the Zicsr extension in Section~\ref{subsection:overview-zicsr-ext}.
  932. To support operating on at least some CSRs using software, they are specified as memory-mapped registers to be operated upon using special instructions.
  933. In the specification, entire address ranges are allocated, but not all addresses are populated yet.
  934. Some CSRs are set up to store and set system information and they can do so using individual bits of the CSR register.
  935. For example, the \texttt{mstatus} register is set up to contain 17 different fields (and four more reserved for future use), the layout of which is illustrated in Figure~\ref{fig:mstatus-register}.
  936. Individual bits can be read-only.
  937. Besides special use CSR addresses with their CSRs having their own unique semantics, there are also address ranges reserved for custom use.
  938. \begin{figure}[h]
  939. \centering
  940. \includegraphics[width=\textwidth]{mstatus-register.png}
  941. \caption{Register layout for \texttt{mstatus} as can be found in \cite[Fig.~3.6]{riscv-isa-vol-2}.}
  942. \label{fig:mstatus-register}
  943. \end{figure}
  944. The entirety of all 4096 CSRs could be implemented as a RAM, but this has several practical disadvantages.
  945. As we have established in Section~\ref{subsection:os-analysis-results}, only few CSRs are used in practice.
  946. The semantics of individual CSRs can also differ, with some CSRs having individual read-only bits and some CSRs being exclusively managed by hardware components, further complicating the implementation as a RAM.
  947. A more appropriate solution is to multiplex register access using the address to denote the register while implementing and thus supporting only a small selection of CSRs.
  948. Zicsr can be implemented by adding a CSR unit that contains all supported CSRs, takes control signals such as the CSR operation (if any), an address and a register or immediate value.
  949. Because this information either has to be decoded on the fly or passed on by the decode stage of the pipeline, the CSR unit can either operate in the decode or execute stage.
  950. Data that is read back from the CSRs, if used, needs to be forwarded in case of data dependencies or the pipeline has to be stalled.
  951. If the CSR unit is included in the execute stage, it can function like an alternative output data source alongside the ALU (and possibly a multiplication and division unit).
  952. When getting a request for data to be written and read, the CSR unit can do so in a single-cycle.
  953. Either the data supplied in the request is written, or it is used to mask (setting or resetting bits) previously held bits, in the next cycle, while at the same time data is read.
  954. \section{Branch Prediction}
  955. \label{section:bp-arch}
  956. There already exists a primitive form of branch prediction in the current MiRiV pipeline implementation.
  957. We want to consider branch prediction to see whether there are any significant performance gains to be had by way of relatively simple improvements, although we will not provide a detailed analysis of relative performance improvements.
  958. \subsection{Pre-existing Predictor}
  959. The MiRiV processor is designed not to stall whenever branch decisions come up, continuing execution on the basis of a branch prediction and determining the actual result of the branch instruction only later.
  960. Complications like branch target calculation and the like can be avoided by following a simple strategy:
  961. always assume there will be no change in control flow and continue execution.
  962. This is akin to always predicting that a branch will not be taken, making the current implementation a static branch predictor.
  963. If the result of the branch instruction later turns out to be a taken branch, then incorrectly fetched instructions within the pipeline are flushed.
  964. That is to say, all instructions in the pipeline that were queued as a result of an incorrect static prediction are discarded.
  965. The result of the branch instruction is determined in the fourth stage, the memory stage.
  966. Currently a VHDL type containing the operations \texttt{BR\_NOP} (no branch instruction), \texttt{BR\_BR} (jump instructions), \texttt{BR\_CND} and \texttt{BR\_CNDI} (conditional and conditional inverted branch instructions) is passed down up to the memory stage, where the new branch target is determined and a signal to the fetch stage is asserted if the PC is to be taken from the memory stage, causing a flush of the pipeline.
  967. Even for unconditional branches (jumps), the pipeline is only flushed later.
  968. The conditional branches are determined using the zero flag of the ALU passed to the memory stage.
  969. \subsection{Simple 2-bit Predictor}
  970. To improve the prediction, a simple 2-bit predictor unit can be implemented.
  971. A 2-bit predictor keeps a history of the last two branch results and predicts the next branch result based on that history.
  972. There are many ways to implement such a unit, it can for example be placed inside the fetch stage, where it produces the next PCs while accepting prediction results from the memory stage.
  973. Having the branch predictor as part of the fetch stage has the disadvantage of requiring additional hardware to decode incoming instructions.
  974. If the branch predictor were part of a later stage it could make use of the computation in the decode stage, but placing the branch predictor at any later stage in the pipeline inevitably either causes delays or requires static predictions like those of the pre-existing predictor.
  975. The price of additional hardware to decode incoming instructions for the branch predictor in the fetch stage is a small price to pay, although if these additions lie on the critical path the maximum operating frequency could be lowered as a consequence.
  976. \begin{figure}[H]
  977. \centering
  978. \includegraphics[width=.5\textwidth]{2-bit-predictor.pdf}
  979. \caption{2-bit prediction state machine, highlighting the four possible states.}
  980. \label{fig:2-bit-predictor}
  981. \end{figure}
  982. To realize the 2-bit prediction, a state machine (as can be seen in Figure~\ref{fig:2-bit-predictor}) with four states can be implemented: two taken and not taken states, with weak and strong prediction respectively.
  983. This state machine exhibits a kind of hysteresis, where two mispredictions are required for the branch predictor to change its prediction.
  984. The branch predictor uses its current prediction to determine the PC for the fetch stage, but in case of mispredictions the memory stage has to issue a new PC and flush the pipeline.
  985. Another aspect that can be improved upon compared to the pre-existing predictor is the prediction result of jump instructions.
  986. When the branch predictor recognizes a jump instruction (\texttt{JAL}), it can immediately return the correct PC.
  987. In case of jump register instructions (\texttt{JALR}), no such improvement can be made, because information of later pipeline stages is required.
  988. To deal with this, the memory stage can still issue a new PC and flush the pipeline.
  989. % CHAPTER
  990. \chapter{Implementation}
  991. \label{chapter:implementation}
  992. We now want to discuss the details of our implementation.
  993. This will be done by illustrating all the design decisions for the extensions of the MiRiV processor and by giving an overview of how FreeRTOS was included as an application to the pre-existing suite of software test applications.
  994. \section{Extending MiRiV}
  995. \label{section:preparing-miriv}
  996. With all aforementioned changes made to the original MiRiV pipeline (Figure~\ref{fig:miriv-pipeline}), we end up with our new pipeline as shown in Figure~\ref{fig:miriv-new-pipeline}.
  997. This again shows all the individual components of the MiRiV pipeline implementation.
  998. Components newly added to the pipeline have been highlighted in light red color.
  999. \begin{figure}[h]
  1000. \centering
  1001. \includegraphics[width=\textwidth]{miriv-new-pipeline.pdf}
  1002. \caption{The modified MiRiV pipeline, with new extensions highlighted in light red. For the original MiRiV pipeline refer to Figure~\ref{fig:miriv-pipeline}.}
  1003. \label{fig:miriv-new-pipeline}
  1004. \end{figure}
  1005. The most important extension to the pipeline is the exception, interrupt and trap architecture, in conjunction with the Zicsr extension.
  1006. For the exception, interrupt and trap architecture, we have already discussed design options that were made available by SiFive, with a particular focus on the core local interruptor (CLINT) \cite{sifive-interrupt-cookbook}.
  1007. The modified MiRiV pipeline makes use of the semantics and specifications of the CLINT and integrates its use with an implementation of the Zicsr extension in the form of a CSR unit.
  1008. Further, an auxiliary trap unit was added to the pipeline to facilitate correct changes in control flow and correct interoperation with the new CSR unit.
  1009. We will look at these architectural additions and changes in more detail now.
  1010. Because the CLINT, CSR and trap units all work in conjunction to enable more sophisticated control flows, their implementation is documented together in Section~\ref{section:exc-int-trap-implementation}.
  1011. Afterwards, we will consider implementation details for the other two pipeline extensions, the muldiv unit implementing the M extension in Section~\ref{section:m-ext-implementation} and the modified branch predictor in Section~\ref{section:bp-implementation}.
  1012. \section{Implementation of Exceptions, Interrupts and Traps}
  1013. \label{section:exc-int-trap-implementation}
  1014. To keep the implementation simple and avoid handling of relatively complex edge cases, interrupts and exceptions are designed to function in a way similar to normal instructions.
  1015. Normal instructions in the MiRiV pipeline are straightforward: after being loaded in the fetch stage, they flow through all the other stages of the pipeline, being handled by functional units in each stage in progressive fashion accordingly to fulfill their function.
  1016. This approach has the benefit of simplifying design by avoiding complex inter-dependencies, as each stage simply pushes their data forward to the next.
  1017. Some orchestration by a control unit is necessary, but the responsibilities of the control unit are kept small.
  1018. This leads to a natural implementation of interrupts and exceptions.
  1019. Software interrupts are caused by an instruction, so they already flow through the pipeline.
  1020. External interrupts can be seen as events that are signaled to the processor from some outside unit.
  1021. Even though this is the case, for our implementation they can still be analogous to software interrupts, by having the fetch stage receive these interrupt signals and passing them on like instruction data.
  1022. Exceptions on the other hand are entirely internal events that appear only mid-execution.
  1023. In the case of our implementation this refers to the decode stage, where an illegal instruction can make decoding impossible, and the memory stage, where a misaligned load and store can occur.
  1024. In the case of the two special software exceptions, those raised by instructions \texttt{ECALL} and \texttt{EBREAK}, they are detected in the decode stage and flow through the pipeline like any other instruction.
  1025. Each of these events requires treatment via a jump to an interrupt or exception handler, a so-called trap.
  1026. Specifically for the MiRiV pipeline, this irregular control flow is similar to the process of correcting a wrongly predicted branch result.
  1027. Only in later stages of the pipeline can it be ascertained that the branch was correct, which means that the instruction is pushed all the way to the memory stage until the processor can intervene to correct a possible misprediction.
  1028. This is accomplished by having the control unit flush respective pipeline stages, while the fetch stage assumes the corrected program counter signaled back to the fetch stage from the memory stage.
  1029. This already pre-existing mechanism to update the program counter in the case of a (perhaps not so) irregular event can be expanded to handle interrupts and exceptions as well.
  1030. Interrupts and exceptions can be passed down in the pipeline from stage to stage, until they reach the memory stage, where the irregular control flow event is then signaled to the control unit and the fetch stage, making interrupts and exceptions appear like any other misprediction.
  1031. Another reason that makes this implementation natural is the critical role of the CSR unit.
  1032. The CSR unit holds and controls all CSRs, which are essential parts of interrupt and exception handling.
  1033. We will describe all relevant CSRs and their role in this sort of irregular control flow before long.
  1034. The CSR unit does not only keep track of processor state, but it exposes processor state in the form of memory-mapped registers that can only be interacted with using special CSR instructions.
  1035. %This means it is necessary in a pipelined implementation to consider forward data dependencies for this software exposed side of the CSR unit.
  1036. It is not sufficient to track and manage processor state in a unit that is decoupled from individual pipeline stages.
  1037. Arguably, to uphold this principle of having only forward data dependencies, it is a good idea to place functional units as early in the pipeline as possible, but not earlier.
  1038. For example, if a functional unit required decoding the instruction first, then if the functional unit were placed in the stage that follows the decode stage, it can directly make use of the results of the decode stage.
  1039. In this example, the functional unit could still be placed earlier in the pipeline, but then it might require duplication of decoding hardware.
  1040. This is one reason to place the CSR unit in the execute stage of the MiRiV pipeline, which can then neatly make use of data prepared in the decode stage.
  1041. Upon handling a CSR instruction, none of the other functional units of the execute stage are busy and if any data is read via a CSR instruction, the output of the CSR unit is only a single 32-bit value, just like with the ALU, or the muldiv unit.
  1042. If interrupts and exceptions are handled only in the memory stage, like previously discussed, this placement of the CSR unit in the execute stage has another elegant property:
  1043. data that is required to decide whether to trap and where to trap to can be passed on forward by the CSR unit in the execute stage to the memory stage.
  1044. \subsection{Control and Status Registers (CSR Unit)}
  1045. \label{subsection:csr-unit}
  1046. The CSR unit was implemented to fulfill two functions:
  1047. read/write CSRs and pass on processor state information to the trap unit.
  1048. Unlike other functional units that don't require a clock, reset and stall signal, the CSR unit does, because it also contains the CSRs themselves.
  1049. To fulfill the first function, the CSR unit has been designed to take \texttt{op}, \texttt{csraddr}, \texttt{csrread}, \texttt{readdata}, \texttt{csrwrite} and \texttt{writedata} signals.
  1050. The operation is specified by \texttt{op} and the CSR is selected by \texttt{csraddr}.
  1051. In the case of a read, \texttt{csrread} is set to high by the decode stage and \texttt{readdata} is filled with the value contained in the selected CSR.
  1052. In the case of a write, \texttt{csrwrite} is set to high by the decode stage and \texttt{writedata} is populated either with a register or an immediate value.
  1053. Towards its second purpose, the CSR unit takes a \texttt{trapop} signal that contains all relevant information for the trap unit, populates it with CSR values and passes it on to the memory stage where the trap unit resides.
  1054. Now we will get into a description of CSRs that are necessary and how they are used.
  1055. \subsubsection{mstatus}
  1056. This CSR serves to store general processor state that is particularly relevant to correct handling of nested traps and correct execution in the presence of multiple privilege modes.
  1057. There is only one bit that is currently relevant to the MiRiV processor, the \texttt{mstatus.MIE} bit, which denotes whether or not interrupts are enabled globally (targeting only interrupts, not any of the exceptions).
  1058. This bit can be interacted with programmatically, but the pipeline also sets and clears it when certain events take place.
  1059. Notably, to disable nested interrupts (interrupts inside traps), this bit is set during a trap and cleared by an \texttt{MRET} instruction.
  1060. This instruction signifies that the trap handler has finished and normal execution can be resumed.
  1061. A short discussion on nested traps in general and why it is okay for our purposes to disable them is provided in the discussion of the trap unit in the next section.
  1062. Nested interrupts are already disabled by a separate mechanism that we will discuss soon, but it is still important to toggle this bit during a trap to expose this state information to software.
  1063. \subsubsection{mie}
  1064. This CSR serves to store whether interrupts are enabled, for each individual interrupt type.
  1065. Do note that, like the related CSR \texttt{mip}, this CSR is only concerned with interrupts, not any exceptions.
  1066. In general this CSR can toggle different interrupt types for different privilege modes, but in our case only M-mode interrupts are relevant.
  1067. There are only three bits relevant to our implementation, \texttt{mie.MEIE} (external interrupts enabled), \texttt{mie.MTIE} (timer interrupts enabled) and \texttt{mie.MSIE} (software interrupts enabled).
  1068. \subsubsection{mip}
  1069. This CSR is functionally equivalent to CSR \texttt{mie}, except for one difference: instead of storing whether an individual interrupt type is enabled, it stores whether an individual interrupt type is pending.
  1070. Pending interrupts are those that occur and can not immediately be handled.
  1071. One such instance would be an interrupt type that is currently disabled.
  1072. Information about pending interrupts is always stored, even when they are disabled.
  1073. When execution of pending interrupts becomes possible again and no conditions prevent a pending interrupt from taking place, the value of this CSR will cause an interrupt when passed to the trap unit similar to how an interrupt would normally be caused and additionally clear the pending bit.
  1074. In the case of multiple pending interrupts, we could either use a simple prioritization scheme that always chooses certain interrupts over others, or we could use some kind of arbitration.
  1075. Interesting arbitration schemes that could serve to prevent starvation would be a round-robin scheme, or a scheme that keeps a simple counter for each pending interrupt type and chooses those that were chosen least.
  1076. In the case of a prioritization scheme, the priorities could also be made configurable.
  1077. For now, a simple unconfigurable prioritization scheme has been chosen for the MiRiV processor with the following order of descending priority:
  1078. software interrupts, external interrupts and timer interrupts.
  1079. This ordering has been chosen, to prioritize program flow and instructions placed for debugging purposes over external requests that can be delayed without issue as well as timer interrupts that are expected to happen more frequently.
  1080. For a different system or application a different ordering might be desirable.
  1081. Like with the CSR \texttt{mie}, only the following bits are relevant: \texttt{mip.MEIP} (external interrupt pending), \texttt{mip.MTIP} (timer interrupt pending) and \texttt{mip.MSIP} (software interrupt pending).
  1082. \subsubsection{mtvec}
  1083. This CSR stores either the direct address of a generic trap handler, or the base address of the trap vector.
  1084. The lowest two bits (which for an address would be unavailable anyway to ensure correct alignment) denote how this CSR is set up.
  1085. Setting the mode to direct mode ($\text{MODE} = 0$) sets all interrupts and exceptions to jump directly to the stored address.
  1086. In vectored mode ($\text{MODE} = 1$), all interrupts and exceptions are set to jump to the base address with some offset denoted by the CSR \texttt{mcause} ($\text{BASE} + 4 \times \text{cause}$).
  1087. The CSR can contain a read-only value, but it can also be writable.
  1088. In general it is exposed to software at least for reads.
  1089. In a real context this CSR can be expected not to change too often, but because it can change if it is writable, its value has to be loaded and passed on.
  1090. Because the CSR unit is located in the execute stage, its value can be loaded and passed on to the memory stage, where information about the correct jump target is necessary.
  1091. \subsubsection{mepc}
  1092. This CSR is used to keep track of where execution was stopped before trapping.
  1093. One advantage of the design choice to have all exceptions and interrupts flow to the memory stage, is that the value of this CSR can easily be determined.
  1094. Because exceptions and interrupts, when they do take place and cause a change in control-flow and flush of the pipeline, accompany an instruction up until the memory stage, these exceptions and interrupts can be said to hijack the execution of the instruction they accompany.
  1095. The program counter that needs to be stored in the CSR \texttt{mepc} is always the instruction that is currently in the memory stage.
  1096. It will be necessary however to make sure that the correct program counter is retained and usable if a trap were to be caused during a pipeline flush.
  1097. This could be easily circumvented by delaying traps, such that a flush can never have an adverse effect on which program counter is chosen.
  1098. Upon encountering an \texttt{MRET} instruction, the value stored in this CSR is used to jump back to where normal execution was interrupted.
  1099. \subsubsection{mcause}
  1100. This CSR has an elementary purpose, to keep track of what has caused a change in control-flow.
  1101. When CSR \texttt{mtvec} is in direct mode, the cause can be used by software to determine the appropriate course of action.
  1102. In vectored mode, it is also used to directly compute the correct jump target.
  1103. When multiple interrupts or exceptions occur, it is set to the interrupt or exception of the highest priority.
  1104. Exceptions are prioritized over interrupts.
  1105. For multiple simultaneous exceptions, the RISC-V privileged specification specifies how they should be prioritized.
  1106. In the case of MiRiV, because exceptions have to be carried all the way to the memory stage by the originating instruction, as long as there are no instructions that can cause exceptions in multiple pipeline stages, there are no simultaneously occurring exceptions.
  1107. \begin{table}[H]
  1108. \centering
  1109. \begin{tabular}{r|r|r|l}
  1110. Interrupt & Exception Code & Value & Description \\
  1111. \hline
  1112. 0 & 2 & 2 & Illegal instruction \\
  1113. 0 & 3 & 3 & Breakpoint (\texttt{EBREAK}) \\
  1114. 0 & 4 & 4 & Load misaligned \\
  1115. 0 & 6 & 6 & Store misaligned \\
  1116. 0 & 11 & 11 & Environment call from M-mode (\texttt{ECALL}) \\
  1117. 1 & 3 & 2147483651 & Machine software interrupt \\
  1118. 1 & 11 & 2147483659 & Machine external interrupt \\
  1119. 1 & 7 & 2147483655 & Machine timer interrupt \\
  1120. \end{tabular}
  1121. \caption{\label{table:exc-int-listing}Listing of implemented exception and interrupt causes and their \texttt{mcause} values (adapted from Table~3.6 of the RISC-V privileged specification \cite{riscv-isa-vol-2}). Priorities are fixed and correspond to the order of occurrence in the table. The interrupt field corresponds to the unsigned value of \texttt{mcause[31]} and the exception code field to the unsigned value of \texttt{mcause[30:0]}, while the value field shows the unsigned value of the entire register.}
  1122. \vspace{1ex}
  1123. \end{table}
  1124. Table~\ref{table:exc-int-listing} shows which exceptions and interrupts are implemented in the modified MiRiV pipeline, what their \texttt{mcause} values are and in which order they are prioritized.
  1125. Do note that the CSR \texttt{misa} is also implemented but not relevant to interrupt and exception handling.
  1126. Also note that exceptions that happen for instructions which are executed as part of a mispredicted branch get flushed as well when the branch is corrected, which is necessary to avoid handling exceptions for instructions that were not meant to be executed.
  1127. When a trap is executed and earlier stages are flushed, their exception vectors are also flushed.
  1128. Interrupts on the other hand do not get flushed, but in the case that a trap is taken for another exception/interrupt, the pending bit is set to delay handling of the interrupt until appropriate.
  1129. \subsection{Trap Generation (Trap Unit)}
  1130. \label{subsection:trap-unit}
  1131. Like previously mentioned, the memory stage determines whether a branch prediction was correct and if it wasn't, the misprediction is signaled to the control unit and the corrected jump target is transmitted to the fetch stage, causing a pipeline flush and change in control flow.
  1132. This mechanism can be re-used for traps, by making the memory stage change the control flow in the additional case of a trap (or a return from a trap).
  1133. For this purpose, a new functional unit has been added that has the purpose of deciding whether to trap, calculating the correct jump target and writing back to the CSRs.
  1134. The trap unit takes as inputs an enable signal, the program counter of the memory stage and a trap operation data structure \texttt{trapop}, which is a record containing all information necessary to determine whether or not to raise a trap, calculate the correct jump target and new values for the CSRs.
  1135. Inside a \texttt{trapop} are current values for CSRs \texttt{mstatus}, \texttt{mie}, \texttt{mip} and \texttt{mtvec} supplied by the CSR unit in the execute stage, a signal for \texttt{MRET} and two signal vectors for accumulated exceptions and interrupts that have passed through the pipeline.
  1136. These vectors accumulate exceptions and interrupts, because they are simply passed on through individual pipeline stages, with respective bits going high if an interrupt or exception is issued in any one of the pipeline stages.
  1137. This approach is essential for exceptions, because it keeps them consistent in the order in which they appear, so that no instruction that causes an exception in an earlier pipeline stage can raise an exception before its predecessing instructions that cause one only in a later stage.
  1138. A detailed explanation of this approach can also be found in \cite[Appendix C., Ch. 4]{comparch2019}.
  1139. Out of this, the trap unit determines the correct course of action and generates the aforementioned information.
  1140. The memory stage uses this information to update the control flow if necessary and writes back new values for the CSRs to the CSR unit, similar to how writes to the register file are handled.
  1141. Just like writes to the register file, if necessary the updated CSR values can be forwarded.
  1142. The trap unit is kept stateless.
  1143. This has the advantage of simplifying implementation and verification of the unit.
  1144. To ensure correctness, additional registers \texttt{cooldown} and \texttt{trapped} were added to the memory stage instead.
  1145. How they are used will be explained shortly.
  1146. The only relevant information from the perspective of the trap unit is whether or not it would be acceptable to generate a trap.
  1147. In the implementation of the MiRiV processor, there are two cases where trap generation needs to be delayed:
  1148. traps during pipeline flushes and during execution of other traps.
  1149. The first case is problematic because it complicates calculation of the correct program counter for the CSR \texttt{mepc} in the case of exceptions and interrupts.
  1150. As for the second case, raising any trap during execution of any other trap is explicitly forbidden, due to possible state inconsistencies.
  1151. Except for the case of exceptions raised during the execution of an interrupt handler, nested traps are not as useful, as we can see by looking at possible cases:
  1152. Interrupts are disabled during other interrupts regardless, because all implemented interrupts are part of the same privilege mode.
  1153. During traps caused by exceptions, it is acceptable to simply delay interrupts.
  1154. In all other cases, i.e. exceptions within an exception/interrupt handler, the exception would prove fatal if not handled specifically by the application, because the correct control flow information, such as the value of the CSR \texttt{mepc}, are lost.
  1155. Because the target application does not handle these special cases, nested traps are unsupported.
  1156. The \texttt{cooldown} and \texttt{trapped} registers are used to delay the generation of traps by disabling the trap unit for three clock cycles after a pipeline flush (representing pipeline bubbles) and while in a trapped state respectively.
  1157. The processor is in a trapped state after a trap has been raised and until an \texttt{MRET} instruction has reached the memory stage.
  1158. A cooldown after pipeline flushes ensures that no trap with an invalid program counter value can be generated, as well as no exceptions caused by invalid instructions from regions of memory that are not supposed to be executed.
  1159. This cooldown mechanism could be replaced by keeping track of the last valid program counter value for CSR \texttt{mepc} updates, as well as annotating instruction packets with a valid field to disregard exceptions of invalid instructions.
  1160. Instead, this simpler mechanism was chosen for simplicity, as the worst case scenario would only delay interrupts by three clock cycles.
  1161. Do note that because it is not needed for our use case, the \texttt{WFI} (wait for interrupt) instruction is implemented as a \texttt{NOP}.
  1162. \subsection{Core Local Interruptor (CLINT Unit)}
  1163. \label{subsection:clint-unit}
  1164. The final component of this interrupt and exception scheme is the interruptor itself.
  1165. The interruptor is a unit that collects information from outside the processor and issues interrupt service requests.
  1166. Software interrupts are issued when writing an appropriate value to the CSR \texttt{mip} and as such, software interrupt requests are already contained within the MiRiV processor with the addition of the CSR and trap units.
  1167. But the core itself does not generate any timer interrupt requests and external interrupt requests.
  1168. These other interrupt requests can only be signaled from outside the processor core.
  1169. There are several considerations as to what the signal source and specification should be.
  1170. The signals coming from outside the processor core can be asynchronous or synchronous, but need to stay high for at least an entire (synchronous) clock cycle.
  1171. The CLINT unit then scans for rising edges using a simple state machine, where each rising edge of the interrupt signal lines causes an interrupt request pulse that flows through the pipeline in the form of the accumulated interrupt vector.
  1172. The exact signal specifications are illustrated in Figure~\ref{fig:clint-waveform}.
  1173. Signals \texttt{exti} and \texttt{timi} represent interrupt lines coming from outside the processor core, while signals \texttt{ext\_irq} and \texttt{tim\_irq} represent core internal interrupt request pulses that flow through the pipeline.
  1174. This way, a wide range of signals can be supported as valid external interrupts and in particular, the signal produced by the FPGA's on-board button can be used without adding a dedicated unit.
  1175. \begin{figure}[h]
  1176. \centering
  1177. \includegraphics[width=0.8\textwidth]{clint-waveform.pdf}
  1178. \caption{External and timer interrupt request waveforms.}
  1179. \label{fig:clint-waveform}
  1180. \end{figure}
  1181. \subsubsection{External Interrupt Requests}
  1182. \label{subsubsection:ext-irq}
  1183. For simplicity, the external interrupt was implemented using one of the on-board buttons.
  1184. These buttons offer an already debounced signal, simplifying implementation.
  1185. This is the only external interrupt source present as of now.
  1186. Even with multiple sources, they could all map to the same interrupt for which there would be only one interrupt handler.
  1187. To support more external interrupts, separate sources could be bound to unused bits of the interrupt vector.
  1188. One could also expose different devices using memory-mapped registers, have them all cause the same interrupt (a collective external interrupt) and use these registers in software to differentiate between the different sources.
  1189. \subsubsection{Timer Interrupt Requests}
  1190. \label{subsubsection:tim-irq}
  1191. Timer interrupts on the other hand are not entirely external but need to be programmable.
  1192. The RISC-V privileged specification \cite{riscv-isa-vol-2} has a section on \texttt{mtime}, describing the addition of two 64-bit memory-mapped registers and their semantics.
  1193. More specifically, it outlines the addition of a 64-bit memory-mapped register called \texttt{mtime}, and another one called \texttt{mtimecmp}.
  1194. Even for 32-bit architectures, these registers need to be 64 bits wide to support a high enough clock granularity without worrying about overflows, for a clock running at a constant frequency.
  1195. The \texttt{mtime} register is set automatically by hardware and encodes a strictly increasing unsigned integer value representing the current tick, starting from some arbitrary point in time.
  1196. The timer interrupt is then programmed by setting the \texttt{mtimecmp} to some point in the future, by adding an appropriate value to the current tick.
  1197. For this to work, according to the specification, the platform must provide a mechanism for determining the period of a tick.
  1198. Once the \texttt{mtime} register value has reached or exceeded the \texttt{mtimecmp} register value, the interrupt goes high and remains high until that is no longer the case.
  1199. Special care needs to be taken in a software implementation using \texttt{mtimecmp}, in order not to cause invalid transient interrupts with incorrect write sequences, as only 32-bits can be written atomically.
  1200. One such correct write sequence suggested in \cite[Fig.~3.29]{riscv-isa-vol-2} is illustrated in Figure~\ref{fig:mtimecmp-write-sequence}.
  1201. For the implementation, the registers are exposed to software as four memory-mapped registers \texttt{mtimelo}, \texttt{mtimehi}, \texttt{mtimecmplo} and \texttt{mtimecmphi}, at addresses \texttt{0xFFFF8000}, \texttt{0xFFFF8004}, \texttt{0xFFFF8008}, \texttt{0xFFFF800C} respectively.
  1202. \begin{figure}[h]
  1203. \centering
  1204. \includegraphics[width=\textwidth]{mtimecmp-write-sequence.png}
  1205. \caption{Correct write sequence for \texttt{mtimecmp} as can be found in \cite[Fig.~3.29]{riscv-isa-vol-2}.}
  1206. \label{fig:mtimecmp-write-sequence}
  1207. \end{figure}
  1208. These memory-mapped registers are not part of the processor core itself, but are instead contained in and exposed by a device in a separate address space.
  1209. \section{M Extension Implementation}
  1210. \label{section:m-ext-implementation}
  1211. The M Extension Implementation is described in Section~\ref{section:m-arch}.
  1212. It is implemented as a multicycle component that can cause pipeline stalls until its operation is completed.
  1213. Besides the small additions to the decode stage to support the new instructions, a unit called the muldiv unit has been added to the execute stage of the pipeline.
  1214. This unit functions analogously to the ALU, in that it takes an operation and two operands to output a single result, although without a zero flag or any other flags.
  1215. Two implementations for the muldiv unit are provided, which can be toggled using generics.
  1216. The first implementation is a naive one that is simple but assumes a fixed delay of 32 additional clock cycles to complete any operation.
  1217. The second is an improvement over the first one in that it stalls for only two clock cycles when multiplying, although it still stalls for up to 35 clock cycles when dividing (and only a single cycle for trivial cases such as division by one).
  1218. We will consider both separately.
  1219. \subsection{Naive Implementation}
  1220. The naive implementation is a simple implementation that mostly lets the FPGA development tools infer and generate multiplication and division functions.
  1221. As such, binary multiplication and division themselves don't have to be implemented, although their use still has to be integrated into the pipeline and reconciled with the semantics of the M extension specification.
  1222. However, in the context of FPGA development (using Intel Quartus with the Cyclone IV E family of FPGAs), to meet timing requirements the development tool has to be informed that these circuits are expected to take multiple cycles in order to keep the maximum frequency as high as possible.
  1223. This is done using multicycle path constraints.
  1224. Particularly for multiplication, on-chip DSP functions with low latencies can be used to avoid having to use multiple cycles for multiplication.
  1225. With division however, such a delay is unavoidable.
  1226. But because both multiplication and division set the result bit vector on which the timing constraint is placed, they both stall the pipeline for 32 clock cycles.
  1227. \subsection{Custom Implementation}
  1228. In general, the guiding principle for this custom implementation is to make the common case fast.
  1229. As application writers are aware that division is more costly than multiplication, division is already avoided wherever possible.
  1230. Our analysis in Chapter~\ref{chapter:overview} also shows that the frequency of M extension instructions themselves is not too high, compared to more prominent instructions.
  1231. The custom implementation still uses on-chip DSP blocks with low latencies for multiplication.
  1232. This enables binary multiplication to be done in a single clock cycle, although the state machine managing the logistics of the muldiv unit makes it necessary to stall for two clock cycles.
  1233. To avoid having multiplication be involved in the critical path, when multiplication itself is not so common (as we have seen), this is considered acceptable.
  1234. Division however is not implemented as an inferred operation, but using a custom intdiv unit that uses a simple shift-based binary integer division algorithm.
  1235. A state machine listens for incoming requests, idling until a division operation (\texttt{DIV[U]} and \texttt{REM[U]}) appears.
  1236. If the operation is a trivial case, the result of which can be determined in a single clock cycle, then the result is immediately produced and the unit stalls only for a single clock cycle.
  1237. These trivial cases are division by zero, one and negative one, for which the RISC-V unprivileged specification \cite{riscv-isa-vol-1} defines appropriate return values which can be seen in Figure~\ref{fig:m-div-special}.
  1238. \begin{figure}[h]
  1239. \centering
  1240. \includegraphics[width=\textwidth]{m-div-special.png}
  1241. \caption{Semantics for division by zero and division overflow with $L=32$ for MiRiV, as illustrated in \cite[Tab.~7.1]{riscv-isa-vol-1}.}
  1242. \label{fig:m-div-special}
  1243. \end{figure}
  1244. Any other set of division operands begins a process in which the result is calculated in a series of subtraction and shift operations.
  1245. At the end of these 32 cycles worth of subtraction and shift operations, both the quotient and remainder have been determined.
  1246. Finally an intermediate state determines the correct sign and then the result is returned to the muldiv unit.
  1247. Besides making the common case fast, this implementation can also be inspected and understood in comparison to the generated and opaque result of the FPGA tooling.
  1248. %It would also be simpler to use this custom implementation when not targeting an FPGA-based platform.
  1249. For these reasons this custom implementation is preferred over the naive one, although the naive one is left available as a choice for completeness.
  1250. \section{Modified Branch Predictor Implementation}
  1251. \label{section:bp-implementation}
  1252. The modified branch predictor is implemented as a simple 2-bit predictor exactly as specified in Section~\ref{section:bp-arch}.
  1253. Although its performance has not been extensively benchmarked, it has been compared to the pre-existing branch predictor using assembly test programs that were already part of MiRiV, where it has shown a definite improvement.
  1254. The modified branch predictor is also vital for this implementation for another reason.
  1255. Because the trap unit is disabled after a pipeline flush, pipeline flushes could lead to starvation of interrupts when the program enters an infinite loop that continually flushes the pipeline.
  1256. But because the branch predictor learns the correct course of action quickly in such a case, no mispredictions can cause pipeline flushes and the pipeline is guaranteed to reach a state where it can trap.
  1257. If this type of behavior is undesired, as can be expected for example for any program that enters an infinite loop after some setup to service interrupt request while in this idle state, the modified branch predictor should be used.
  1258. A better solution would be not to rely on the branch predictor, but for simplicity this solution was adopted.
  1259. \section{Preparing FreeRTOS}
  1260. \label{section:preparing-freertos}
  1261. FreeRTOS has been chosen as the operating system of choice to implement a demo with for our extended MiRiV processor.
  1262. But how does one use FreeRTOS?
  1263. In the remainder of this chapter we will discuss FreeRTOS, its integration into the suite of software test programs for the MiRiV processor and some interesting tensions between the hardware and software sides.
  1264. \subsection{FreeRTOS Overview}
  1265. As an RTOS, FreeRTOS is a kernel that will offer features only if required, in the spirit of providing only what is strictly necessary for an application and no more.
  1266. This is of course aligned with the usual goal of microcontroller development, where costs have to be driven low.
  1267. FreeRTOS resembles a highly configurable library where it is possible to optimize for code size reductions and speed, although only where it is possible without compromising important safety guarantees.
  1268. Because of this structure, FreeRTOS as an operating system is used by integrating it with the actual target application.
  1269. This makes FreeRTOS an explicit dependency where library features are used directly, as compared to exposing a POSIX-like API in the form of a standard library or similar approaches reminiscent of other operating systems.
  1270. \subsection{FreeRTOS Software Integration}
  1271. The base MiRiV processor already provided a suite of software tests, using simple and self-contained RISC-V Assembly and C programs.
  1272. They are converted into a set of target files that can then be loaded into the processor's memory using Makefiles.
  1273. This is achieved by taking a set of source files (\texttt{*.c, *.h, *.S}) and converting them to a set of target files (\texttt{*.imem.mif, *.dmem.mif}).
  1274. The detailed compilation flow (using the RISC-V GNU toolchain \cite{web-riscv-gnu-toolchain}) is illustrated in Figure~\ref{fig:compilation-flow}.
  1275. \begin{figure}[h]
  1276. \centering
  1277. \includegraphics[width=\textwidth]{compilation-flow.pdf}
  1278. \caption{Compilation flow, from source files (\texttt{*.c, *.h, *.S}) to target files (\texttt{*.imem.mif, *.dmem.mif}).}
  1279. \label{fig:compilation-flow}
  1280. \end{figure}
  1281. The target files are used to directly program the FPGA's on-chip memory, writing to separate instruction and data memory regions to initialize the MiRiV processor allowing it to run from a clean state.
  1282. Currently, both the base and extended MiRiV processor implementations use an address width of 14 (byte-addresses) inside the processor core, leading to a limitation of 16 KiB for both the data and instruction memories.
  1283. The (byte) address space is \texttt{0x0000} to \texttt{0x3FFF} for the data memory, and \texttt{0x4000} to \texttt{7FFF} for the instruction memory.
  1284. Because the target files consist of one hexadecimal word per line, one can easily check if either the instruction or data memory is too small by verifying whether their respective target files exceed 4096 lines.
  1285. Code size can be and is currently kept low by compiling the application in a way that optimizes for code size (GCC's \texttt{-Os} flag).
  1286. Of course a kernel with all the safety guarantees, functionality and performance that FreeRTOS offers is not so simple to implement and if many components are used, the resulting program quickly grows too large to respect these size limitations.
  1287. To give a rough overview of some of its features, FreeRTOS offers support for tasks and co-routines, queues, binary semaphores, counting semaphores, mutexes, recursive mutexes, task notifications (inter-process communication), stream and message buffers and several software timers.
  1288. When incorporating FreeRTOS into a project, one can choose which of these features to make use of and which to relinquish, as is often done to fit FreeRTOS code usage to the requirements of an application and no more.
  1289. In order for FreeRTOS to be useful, at the very least tasks have to be used, while most other features can be seen as optional dependencies.
  1290. The pre-existing build infrastructure was extended to link against a recent and stable version of the FreeRTOS kernel (version 10.4.6).
  1291. The only dependency pulled in, out of the above listed features, is support for tasks (\texttt{tasks.h} + \texttt{tasks.c}).
  1292. This inherently requires use of FreeRTOS's own list implementation (\texttt{list.c} + \texttt{list.h}).
  1293. FreeRTOS maintains several ports for different processor architectures, one of which is a port for RISC-V.
  1294. Thus, port-related code is also necessary (\texttt{port.c} + \texttt{port.h}, \texttt{portASM.S}).
  1295. Initially it was considered to also make use of software timers to avoid having to implement hardware timers, but code size constraints have made it easier to opt for a hardware solution.
  1296. More about this is mentioned in the next section.
  1297. Besides FreeRTOS related code and the application itself, the pre-existing basic libc implementation of the MiRiV suite of software programs (\texttt{util.c} + \texttt{util.h}) was re-used and extended appropriately as required.
  1298. \subsection{Connecting MiRiV and FreeRTOS}
  1299. Usually, the task of porting FreeRTOS to a new board is not so trivial.
  1300. To avoid having to implement any kernel code, which would be a long-winded process if it had to be tested, code re-use for existing RISC-V FreeRTOS ports has been a top priority.
  1301. As previously mentioned, the RISC-V FreeRTOS port can automatically install a trap handler and all other necessary utilities.
  1302. These work in a tried and tested way, if one adheres to the SiFive CLINT design.
  1303. This was one of the motivations behind the implementation of the SiFive CLINT design and it has proven to be a good choice.
  1304. While testing the main application and fixing bugs has been a challenging process, no RISC-V port specific code had to be extended or changed.
  1305. Because software timers could not be used, it was necessary however to offer hardware timers and configure them appropriately in the FreeRTOS configuration.
  1306. When using hardware timers, the RISC-V FreeRTOS port assumes memory-mapped registers \texttt{mtime} and \texttt{mtimecmp} to be present.
  1307. The base MiRiV platform already offered a hardware timer with the semantics required, but this hardware timer did not conform to the RISC-V privileged specification \cite{riscv-isa-vol-2}.
  1308. The changes made to support hardware timers are mentioned in Section~\ref{subsubsection:tim-irq}.
  1309. This hardware timer runs at a constant frequency of 1 MHz, the rate at which the value of \texttt{mtime} is incremented per second.
  1310. One should note that usually \texttt{mtime} would be writable, but to preserve backward compatibility with the old hardware timer and applications that have made use of it, \texttt{mtime} is kept read-only and only \texttt{mtimecmp} can be read and written.
  1311. \subsection{Configuring FreeRTOS}
  1312. FreeRTOS supports many different configurations, as it finds use with many real-world applications.
  1313. For this reason, there is a long list of configuration options that can be set to parameterize the specific board FreeRTOS runs on and how its features should be used.
  1314. \subsubsection{Timers}
  1315. In this configuration, addresses of memory-mapped registers such as \texttt{mtime} have to be specified.
  1316. One also has to configure the timebase of the hardware timers and the rate of ticks per second.
  1317. FreeRTOS supports features like time slicing, which is realized by making scheduling decisions during the so-called tick interrupt.
  1318. The tick interrupt is a timer interrupt that is raised at a constant rate and it counts how many ticks have passed, which FreeRTOS can use to make decisions about whether a blocked task has waited long enough.
  1319. There are several ways to block a task, the most common of which is to delay a task, either for a fixed time or until a certain point in the future.
  1320. The fixed task delay in ticks for example can be calculated by taking the total time in milliseconds and dividing it by the tick period in milliseconds.
  1321. \subsubsection{Debugging Options}
  1322. Another important configuration option, for debugging purposes, is to configure assertions.
  1323. FreeRTOS has several sanity checks in different places, which can call a user-provided function when one of these assertions fails.
  1324. It is possible for example, to use a function that prints to the UART serial console at runtime for which file and line number the assertion has failed, by using GCC related primitives.
  1325. There are also other facilities for debugging within FreeRTOS, like hooks (callbacks) as well as additional logging and trace features.
  1326. \subsubsection{Task-Specific Stack Memory}
  1327. What also has to be configured is the amount of memory that tasks have allocated for their task-specific stacks.
  1328. There is a main stack used by the whole application overall, but to ensure correct execution, FreeRTOS takes care to keep this data separate from what happens inside a task.
  1329. This memory has to be allocated somewhere and to realize this, FreeRTOS offers several options.
  1330. The most important distinction is dynamic and static allocation.
  1331. Tasks are not necessarily meant to but can be dynamic, as tasks can be paused, resumed, stopped, killed and re-created.
  1332. If dynamic task features are used, FreeRTOS needs to pull in another dependency for a heap implementation and the heap has to be configured appropriately.
  1333. To avoid this additional dependency to respect aforementioned code size constraints, dynamic tasks are not used.
  1334. Because the intended demo application only uses two tasks that continually block to wait and are then resumed again, both of which are created during initialization and run endlessly, we can get away with using only static tasks.
  1335. Static tasks don't use a heap implementation but instead require the application to provide static memory during initialization.
  1336. When using static tasks, one also has to take care of the initialization of the idle task.
  1337. Whenever no task is running, FreeRTOS executes the idle task, which requires its own stack.
  1338. In the RISC-V FreeRTOS port there is also a specific stack for the trap handler.
  1339. Lastly, there are stack protection features available in FreeRTOS.
  1340. Using no stack protection is the most performant option.
  1341. The most aggressive stack protection initializes task-specific stack memory with a magic value and watermarks the region of memory at the end, so as to be able to check if anything other than the task itself has modified this memory.
  1342. A compromise between aggressive stack protection and no stack protection is using just the watermark, which can also be configured.
  1343. FreeRTOS does not guarantee to detect stack corruption even with the aggressive stack protection feature enabled.
  1344. \subsubsection{Additional Hooks}
  1345. There is also the option of providing additional hooks to be called by FreeRTOS.
  1346. One such hook is the stack overflow hook, which is called when FreeRTOS manages to detect a stack overflow.
  1347. The FreeRTOS developer documentation suggests that fatal exceptions might be raised on some processors in response to stack corruption before the kernel overflow check can occur, which has been observed during testing with our implementation. \cite{web-freertos-stack-usage}
  1348. Then there are the tick hook, which is called at the end of every tick (timer interrupt) and the idle hook called towards the end of the idle task.
  1349. Currently the demo application does not support idle hooks, as there is an unresolved task-switching bug when using idle hooks.
  1350. \begin{figure}[htbp]
  1351. \centering
  1352. \includegraphics[width=\textwidth]{de2-115-execution.jpg}
  1353. \caption{Terasic Altera DE2-115 board running the FreeRTOS demo application, with board and terminal output visible.}
  1354. \label{fig:de2-115-execution}
  1355. \end{figure}
  1356. \newpage
  1357. \section{FreeRTOS Demo Application}
  1358. \label{section:freertos-demo}
  1359. In Section~\ref{section:preparing-freertos} we have set up the FreeRTOS application that was used for analysis of required extensions in Chapter~\ref{chapter:overview}.
  1360. Now we want to briefly look at the results and see what is happening on the processor during execution on the actual boards and in a simulation.
  1361. An example execution is illustrated in Listing~\ref{listing:demo}, where we can see terminal output transmitted by the extended MiRiV implementation over UART.
  1362. Figure~\ref{fig:de2-115-execution} illustrates this terminal output in a picture with the Terasic Altera DE2-115 board and Figure~\ref{fig:de0-nano-execution} with the Terasic Altera DE0-Nano board.
  1363. In this execution, FreeRTOS first sets up two static tasks \texttt{task1} and \texttt{task2}.
  1364. Because the tasks are created in a pending state, the scheduler immediately schedules the execution of both tasks and then transitions into an idle state to wait until further task executions have to be serviced.
  1365. These two tasks alternate, with \texttt{task1} set up to execute once every second and \texttt{task2} once every two seconds.
  1366. \begin{figure}[htbp]
  1367. \centering
  1368. \includegraphics[width=\textwidth]{de0-nano-execution.jpg}
  1369. \caption{Terasic Altera DE0-Nano running the FreeRTOS demo application, with board and terminal output visible.}
  1370. \label{fig:de0-nano-execution}
  1371. \end{figure}
  1372. \begin{listing}[htbp]
  1373. \begin{minted}{text}
  1374. Welcome to minicom 2.6.2
  1375. OPTIONS: I18n
  1376. Compiled on Jun 10 2014, 03:20:53.
  1377. Port /dev/ttyUSB0, 08:41:49
  1378. Press CTRL-A Z for help on special keys
  1379. creating task 1
  1380. task 1 created successfully
  1381. creating task 2
  1382. task 2 created successfully
  1383. starting scheduler
  1384. task1 counter: 0
  1385. task2 counter: 0
  1386. task1 counter: 1
  1387. task1 counter: 2
  1388. task2 counter: 1
  1389. task1 counter: 3
  1390. \end{minted}
  1391. \caption{Serial console UART output of the extended MiRiV implementation executing the FreeRTOS task switching demo application, with \texttt{task1} set up to execute twice as often as \texttt{task2}.}
  1392. \label{listing:demo}
  1393. \end{listing}
  1394. %\begin{lstlisting}[caption={\label{listing:demo} UART output of the extended MiRiV implementation executing the FreeRTOS task switching demo application, with \texttt{task1} set up to execute twice as often as \texttt{task2}.}]
  1395. When \texttt{task2} becomes pending, \texttt{task1} becomes pending too.
  1396. Because the tasks have fixed priorities assigned, the task execution order remains deterministic.
  1397. Listings~\ref{listing:code-main}~and~\ref{listing:code-tasks} show the C source code of the \texttt{main} (executed upon boot), \texttt{task1} and \texttt{task2} functions.
  1398. The function \texttt{main} attempts to initialize both tasks, writing to UART via function \texttt{putstring} (wrapped in a \texttt{TRACE} macro that enables/disables output for easier visibility in simulations) and a notification that the scheduler is about to start.
  1399. Do note that there would be additional output after the scheduler returns, but it is not supposed to ever return.
  1400. \begin{listing}[htbp]
  1401. \begin{minted}{c}
  1402. int main(void) {
  1403. TaskHandle_t task1_handle, task2_handle;
  1404. TRACE(putstring("creating task 1\r\n"));
  1405. task1_handle = xTaskCreateStatic(
  1406. task1, // function name
  1407. "task 1", // task name
  1408. TASK_STACK_SIZE, // stack size
  1409. NULL, // task parameters
  1410. 3, // priority (high number = high priority)
  1411. task1_stack, // stack array
  1412. &task1_buffer // task buffer
  1413. );
  1414. if (task1_handle) {
  1415. TRACE(putstring("task 1 created successfully\r\n"));
  1416. } else {
  1417. TRACE(putstring("error creating task 1\r\n"));
  1418. return 1;
  1419. }
  1420. TRACE(putstring("creating task 2\r\n"));
  1421. task2_handle = xTaskCreateStatic(
  1422. task2, // function name
  1423. "task 2", // task name
  1424. TASK_STACK_SIZE, // stack size
  1425. NULL, // task parameters
  1426. 2, // priority (high number = high priority)
  1427. task2_stack, // stack array
  1428. &task2_buffer // task buffer
  1429. );
  1430. if (task2_handle) {
  1431. TRACE(putstring("task 2 created successfully\r\n"));
  1432. } else {
  1433. TRACE(putstring("error creating task 2\r\n"));
  1434. return 1;
  1435. }
  1436. TRACE(putstring("starting scheduler\r\n"));
  1437. vTaskStartScheduler();
  1438. // this segment shouldn't be reached!
  1439. TRACE(putstring("this line should never be printed\r\n"));
  1440. return 0;
  1441. }
  1442. \end{minted}
  1443. \caption{C definition of \texttt{main}}
  1444. \label{listing:code-main}
  1445. \end{listing}
  1446. %\begin{lstlisting}[language=C, caption={\label{listing:code-main} C definition of \texttt{main}}]
  1447. In the task definitions, we set up a counter and then enter an infinite loop where the counter value is printed via UART before incrementing it and blocking the task for the duration of the delay.
  1448. Other ways of blocking periodic tasks as these ones exist, but \texttt{vTaskDelay} was chosen for simplicity.
  1449. \begin{listing}[htbp]
  1450. \begin{minted}{c}
  1451. void task1(void * parameters) {
  1452. // x ticks (delay) = y ms / portTICK_PERIOD_MS ms
  1453. const TickType_t delay = 1000 / portTICK_PERIOD_MS;
  1454. unsigned int counter = 0;
  1455. for (;;) {
  1456. TRACE(putstring("task1 counter: "));
  1457. TRACE(putnumber(counter));
  1458. TRACE(putstring("\r\n"));
  1459. counter++;
  1460. vTaskDelay(delay);
  1461. }
  1462. }
  1463. void task2(void * parameters) {
  1464. // x ticks (delay) = y ms / portTICK_PERIOD_MS ms
  1465. const TickType_t delay = 2000 / portTICK_PERIOD_MS;
  1466. unsigned int counter = 0;
  1467. for (;;) {
  1468. TRACE(putstring("task2 counter: "));
  1469. TRACE(putnumber(counter));
  1470. TRACE(putstring("\r\n"));
  1471. counter++;
  1472. vTaskDelay(delay);
  1473. }
  1474. }
  1475. \end{minted}
  1476. \caption{C definitions of \texttt{task1} and \texttt{task2}}
  1477. \label{listing:code-tasks}
  1478. \end{listing}
  1479. %\begin{lstlisting}[language=C, caption={\label{listing:code-tasks} C definitions of \texttt{task1} and \texttt{task2}}]
  1480. \FloatBarrier
  1481. To understand the way FreeRTOS operates we will look at a few ModelSim simulation traces.
  1482. The way FreeRTOS initializes once at the start, goes idle once everything is set up and wakes up again to execute pending tasks can be seen in Figure~\ref{fig:freertos-demo-full}.
  1483. The internal \texttt{mtime} counter frequency and task delay have been changed to make results more visible in the ModelSim simulation traces.
  1484. In the trace we can see a lengthier initialization section, the execution of \texttt{task1}, then \texttt{task1} and \texttt{task2} together and finally \texttt{task1} again, with periods of inactivity in between.
  1485. \begin{figure}[h]
  1486. \centering
  1487. \includegraphics[width=\textwidth]{wave-freertos-demo-full.png}
  1488. \caption{ModelSim simulation trace of the extended MiRiV implementation executing the FreeRTOS demo application, with initialization and two tick interrupts visible. Section 1 denotes the initialization section, sections 2 and 4 denote the execution of \texttt{task1} alone and section 3 denotes the execution of both \texttt{task1}.}
  1489. \label{fig:freertos-demo-full}
  1490. \end{figure}
  1491. FreeRTOS is only woken up when a timer interrupt or an external interrupt occur.
  1492. To react correctly to these events, FreeRTOS configures the trap handler and regular timer interrupts in the initialization section of the execution of FreeRTOS.
  1493. These regular timer interrupts cause the execution of the automatically installed trap handler, which determines the interrupt cause and proceeds executing the scheduler.
  1494. With this mechanism FreeRTOS also enables pre-emption as well as other possibly desired features and the precise semantics for such interactions can be configured.
  1495. Figure~\ref{fig:freertos-demo-init} highlights the initialization section, where the two tasks are created.
  1496. The stack protection feature causes two calls to \texttt{memset} to be made to initialize the task-specific stacks with internally pre-defined values.
  1497. Not all traps are caused by timer interrupts, the other type of trap that can be seen in these traces are \texttt{ECALL} (environment call from M-mode) exceptions, which are used in the RISC-V FreeRTOS port for control flow purposes.
  1498. \begin{figure}[h]
  1499. \centering
  1500. \includegraphics[width=\textwidth]{wave-freertos-demo-init.png}
  1501. \caption{ModelSim simulation trace of the extended MiRiV implementation executing the FreeRTOS demo application, with only initialization visible. Sections 1 to 4 denote the calls to \texttt{memset} to initialize the task-specific stacks of \texttt{task1}, \texttt{task2}, idle task and interrupt handler. Section 5 denotes the tail of initialization during which the scheduler is started, the first pending tasks executed and the timer configured for the next execution of a task.}
  1502. \label{fig:freertos-demo-init}
  1503. \end{figure}
  1504. Figure~\ref{fig:freertos-demo-single-task} highlights the first tick interrupt with the first execution of \texttt{task1} as it becomes pending.
  1505. A timer interrupt is caused just as \texttt{task1} becomes pending and the scheduler switches to the execution of \texttt{task1}.
  1506. In the trace we can see by looking at \texttt{trapped\_reg} that the timer interrupt completes after a while, the processor returns using the \texttt{MRET} instruction, executes the task and invokes \texttt{ECALL} before going to sleep again.
  1507. The \texttt{ECALL} instruction is invoked when the task calls the delay function, at which point the kernel tries to determine whether there is another task pending or whether it should go into an idle state.
  1508. \begin{figure}[h]
  1509. \centering
  1510. \includegraphics[width=\textwidth]{wave-freertos-demo-single-task.png}
  1511. \caption{ModelSim simulation trace of the extended MiRiV implementation executing a single pending task in a tick interrupt. Section 1 denotes the timer interrupt waking up the scheduler, section 2 denotes the execution of \texttt{task1} and section 3 denotes a transfer of control back to the scheduler.}
  1512. \label{fig:freertos-demo-single-task}
  1513. \end{figure}
  1514. Figure~\ref{fig:freertos-demo-double-task} shows the second tick interrupt where both \texttt{task1} and \texttt{task2} become pending.
  1515. Similarly to before, the timer interrupt initiates the scheduler, \texttt{task1} is executed and returns control to the kernel.
  1516. But at this point the kernel also executes \texttt{task2} before going idle because \texttt{task2} is still pending.
  1517. \begin{figure}[h]
  1518. \centering
  1519. \includegraphics[width=\textwidth]{wave-freertos-demo-double-task.png}
  1520. \caption{ModelSim simulation trace of the extended MiRiV implementation executing two pending tasks back to back in a tick interrupt. Section 1 denotes the timer interrupt waking up the scheduler, sections 2 and 4 denote execution of \texttt{task1} and \texttt{task2} respectively and sections 3 and 4 denote transfers of control back to the scheduler.}
  1521. \label{fig:freertos-demo-double-task}
  1522. \end{figure}
  1523. The demo was chosen in a way that highlights the correct operation of basic FreeRTOS features.
  1524. Going further, tasks could be extended to implement more complex application, perhaps to find out how much can be accomplished within the limits of schedulability and code size on the extended MiRiV processor.
  1525. But exploring the space of possibilities is left as a task for future implementation, perhaps as part of continuative work.
  1526. \chapter{Outlook and Conclusion}
  1527. \label{chapter:conclusion}
  1528. \section{Conclusion}
  1529. \label{section:conclusion}
  1530. Looking back, we have surveyed the landscape of available operating systems, giving an idea of the rough state of the RISC-V ecosystem and its support.
  1531. We have also taken a look at RISC-V extensions and other important parts of the specification, identifying exactly which parts are necessary for the execution of an operating system.
  1532. Finally we have detailed an implementation, following a strategy of making appropriate changes from both the hardware and software side of the existing MiRiV processor.
  1533. It is not a surprising result that supporting the execution of an operating system is no trivial matter.
  1534. The operating system implemented in the form of a simple demo application is FreeRTOS, showing the new MiRiV processor capabilities for context switching by running two tasks that print their own counter values to the UART serial console at precise and fixed intervals in time.
  1535. For a RISC-V processor running the 32-bit base integer instruction set (RV32I), such as the base MiRiV implementation, real-time operating systems (RTOSs) represent a reasonable goal when trying to identify, implement and verify all extensions necessary for their execution.
  1536. They also have more straightforward pathways towards an implementation, compared to embedded Linux.
  1537. As for the hardware extensions, an implementation for an exception, interrupt and trap architecture, the Zicsr extension, M extension and a new branch predictor (simple 2-bit branch predictor) were detailed.
  1538. By way of RISC-V's identification scheme, this makes the new MiRiV processor an RV32IMZicsr processor.
  1539. While many RISC-V extensions retain a neat modularity, it is interesting to note that the interrupt, exception and trap architecture cannot be decoupled from the Zicsr extension and both the RISC-V unprivileged \cite{riscv-isa-vol-1} and privileged \cite{riscv-isa-vol-2} specifications have to be consulted at various points to create a processor that is then actually capable enough for more complex behavior.
  1540. There are similar such interdependencies for other extensions.
  1541. With appropriate refactoring, the original goal of providing a set of extensions that students can plug in to use their own processor core and run FreeRTOS on it is achieved.
  1542. Students who want to tinker with FreeRTOS itself and implement more complex use-cases than our simple demo application can now do so.
  1543. However, they are limited in what they can do with the current implementation without further extending the processor.
  1544. With current instruction and data memory size limitations, FreeRTOS on the extended MiRiV processor is better suited at implementing static multi-tasking with few auxiliary library features used and it might be necessary to optimize for code size reductions and lower data memory usage.
  1545. \section{Future Work}
  1546. \label{section:future-work}
  1547. Before concluding our work, we want to look at several areas of the extended MiRiV processor and FreeRTOS demo application implementation that could be built on or improved in the future.
  1548. While the extended MiRiV processor can run FreeRTOS with the demo application, it is limited in the sense that the application for which FreeRTOS is used cannot be easily extended without violating instruction memory size constraints and depending on the application, perhaps even data memory constraints.
  1549. This is an obvious area in need of improvement.
  1550. Changing the size of the instruction and data memories is not a particularly complex change, but definitions, constants and addresses have to be updated at several points in the implementation of the hardware and software.
  1551. The address spaces of the on-chip RAMs for the instruction and data memory have to be updated, but depending on the change also those of the memory-mapped devices (UART and the hardware timer) and the JTAG bridge with which the FPGA on-chip RAMs are programmed from the host computer.
  1552. An effort was made to increase the size of the instruction and data memories, but because the FPGA's on-chip RAM resources are limited, this effort was not completed.
  1553. An idea for a more powerful test application that is feasible without adding any additional devices to the processor would be a simple shell, implementing the \texttt{fork/exec -> exit} flow.
  1554. This would require mature support for FreeRTOS tasks with dynamic memory allocation, which is also an area that could be improved upon.
  1555. Currently the extended MiRiV processor is equipped with the following devices: a pre-programmed button on the FPGA for external interrupts, a UART serial connection and a single hardware timer.
  1556. If they are not enough, additional devices could be implemented.
  1557. One could for instance support any number of buttons, switches, seven-segment displays or other hardware that is already made available by the FPGA board.
  1558. FreeRTOS can also run as a networked application, so one could imagine support for an Ethernet connection.
  1559. Another relatively self-contained addition to this list of devices would be support for graphics.
  1560. Support for graphics is quite well aligned with the capabilities of FreeRTOS, because the concurrency features of FreeRTOS can be used to realize simple games and other such use cases.
  1561. Other FPGA resources, such as the SDRAM, could be used for a future application.
  1562. This would greatly increase the size of available memory, to the point where it would even be feasible to run embedded Linux in the configurations we have discussed on the MiRiV processor.
  1563. One could also realize the Zephyr RTOS demo on the extended MiRiV processor.
  1564. A demo was included for our comparison between operating systems, but only FreeRTOS has been configured and tested to the point where the demo application runs on the extended MiRiV processor.
  1565. The most ambitious goal would be to extend the processor further to run embedded Linux (or as an even more ambitious follow-up, full-fledged Linux distributions).
  1566. Besides the already mentioned code size requirements, making it unavoidable to change the memory architecture, one would also need to implement support for several other unprivileged extensions or their emulation using exceptions, S-mode and an MMU.
  1567. The processor itself could also be improved in generic ways.
  1568. The branch predictor is an obvious area to target for further increases in performance.
  1569. %The caches could be tweaked.
  1570. %Support for more CSRs could be added.
  1571. The interrupt architecture could be extended to be more powerful and programmable (for instance, a SiFive CLIC could be added to replace the CLINT).
  1572. The processor could also be adapted to support multiple cores, although it would be a considerable effort.
  1573. \backmatter
  1574. % Use an optional list of figures.
  1575. \listoffigures % Starred version, i.e., \listoffigures*, removes the toc entry.
  1576. % Use an optional list of tables.
  1577. \cleardoublepage % Start list of tables on the next empty right hand page.
  1578. \listoftables % Starred version, i.e., \listoftables*, removes the toc entry.
  1579. % Use an optional list of alogrithms.
  1580. %\listofalgorithms
  1581. %\addcontentsline{toc}{chapter}{List of Algorithms}
  1582. % Add an index.
  1583. \printindex
  1584. % Add a glossary.
  1585. \printglossaries
  1586. % Add a bibliography.
  1587. \bibliographystyle{alpha}
  1588. \bibliography{thesis}
  1589. \end{document}