scieee AI-readable full text Open interactive document viewer

Porting of LTZVisor to the Zynq Ultrascale+ MPSoC ZCU102 Board

Albuquerque, Francisco Coelho Petrucci

Abstract

Presently, computing technology is expanding towards realms that seemed unrealistic at the stages of its emergence, shifting from traditional single-purpose designs to modern generalpurpose appliances centred around connectivity, ubiquity, and security. With this constant reshaping of metrics, it is important to devise new solutions from the onset, taking into account the system’s features at the architecture level. In fact, many manufacturers are motivated in improving nowadays’ devices to wield powerful services in their hardware, liberating software to expand on general-purpose applications. With the rise of virtualization, it is possible to apply the functionalities of physically absent components on a single processor, leading to the employment of fewer devices but requiring more powerful processing units. In systems with real-time requirements, this increase in overhead is prejudicial as it overloads execution with too many operations. By designing devices from the onset with those functions in mind, software ceases to handle such complex and time-consuming roles, which are guaranteed by the platform’s architectural features instead. Thus, hardwareassisted virtualization technologies balance out the total system workload between the software and hardware domains. This dissertation presents the porting process of a TrustZone-assisted virtualization solution (LTZVisor) through ARM’s latest high-performance architectures. This change in architecture entails a transfer to newer embedded platforms, like the state-of-the-art heterogeneous Zynq Ultrascale+ MPSoC from Xilinx adopted as the target board for this project. It is mentioned how the emergent architecture capabilities can be handled to implement virtualized scenarios with low overhead, suggesting methods to apply them in a secure and lightweight execution environment. These approaches were validated through the integration and evaluation of real-time virtual machines with distinct privileges, where the performance sensitive guests thrived without interfering with one another.

Full text

Francisco Coelho Petrucci Albuquerque Porting of LTZVisor to the Zynq Ultrascale+ MPSoC ZCU102 Board Julho de 2019 Francisco Coelho Petrucci Albuquerque Porting of LTZVisor to the Zynq Ultrascale+ MPSoC ZCU102 Board Dissertação de Mestrado Mestrado Integrado em Engenharia Eletrónica Industrial e Computadores Sistemas Embebidos Trabalho efectuado sob a orientação do Professor Sandro Pinto Julho de 2019 Declaração do Autor Nome: Francisco Coelho Petrucci Albuquerque Correio Eletrónico: [email protected] Cartão de Cidadão: 14236133 Titulo da dissertação: Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 Board Ano de conclusão: 2019 Orientador: Professor Doutor Sandro Pinto Designação do Mestrado: Ciclo de Estudos Integrados Conducentes ao Grau de Mestre em Engenharia Eletrónica Industrial e Computadores Área de Especialização: Sistemas Embebidos e Computadores Escola de Engenharia Departamento de Eletrónica Industrial De acordo com a legislação em vigor, não é permitida a reprodução de qualquer parte desta dissertação. Universidade do Minho, 10/07/2019 Assinatura: Francisco Coelho Petrucci Albuquerque iv Despacho RT - 31 /2019 - Anexo 3 Declaração a incluir na Tese de Doutoramento (ou equivalente) ou no trabalho de Mestrado DIREITOS DE AUTOR E CONDIÇÕES DE UTILIZAÇÃO DO TRABALHO POR TERCEIROS Este é um trabalho académico que pode ser utilizado por terceiros desde que respeitadas as regras e boas práticas internacionalmente aceites, no que concerne aos direitos de autor e direitos conexos. Assim, o presente trabalho pode ser utilizado nos termos previstos na licença abaixo indicada. Caso o utilizador necessite de permissão para poder fazer um uso do trabalho em condições não previstas no licenciamento indicado, deverá contactar o autor, através do RepositóriUM da Universidade do Minho. Licença concedida aos utilizadores deste trabalho Atribuição CC BY https://creativecommons.org/licenses/by/4.0/ Acknowledgements ”A man must go forth from where he stands. He cannot jump to the absolute; he must evolve towards it”. It is with this dissertation that I complete a journey lasting 18 continuous years of being a student. This uphill walk culminates in a similarly challenging finale, which would not be possible without the aid and accompaniment of family, friends, and academic colleagues. Foremost, I thank my advisor, Sandro Pinto, whose own investigation was the parent of this dissertation’s theme, thus representing the main root from which this project blossomed. He served as the main counselor when crucial decision-making was required while infecting his advisees with a relaxed and productive work mood. This lab environment was also possible thanks to ESRG’s current Ph.D. students, whose maturity depicted a source of inspiration and pertinent suggestions for the progression of this project. I cannot proceed without acknowledging the efforts of my lab colleagues — Ailton Lopes, Ângelo Oliveira, Hugo Araújo, José Ribeiro, José Silva, Nuno Silva, Pedro Machado, Ricardo Roriz and Sérgio Pereira — who cooperated mutually with me to solve the surging issues and surpassing our own engineering and personal skills as a team. Concurrently, the interaction with other colleagues of my degree, — mainly André Teixeira, António Dias, and Nuno Pereira — fed my curiosity with trivial and scientific domains beyond embedded systems development. A big shout-out to the members of Onysus — André Lopes, André Pacheco, Daniel Rodrigues, and Pedro Coelho — whose constant creativity stimulus and synergistic activities deepened my soft skills and sparked unique points of view. Not to forget the daily attendance of my causal but noteworthy friends, who occasionally tempted me into tasks of leisure, refreshing my often deep and stagnant thoughts which allowed me to take one step back and two leaps forward. Last but certainly not least, my sincerest gratitude to all the family members whom I have the absolute gratefulness of getting to know and love throughout all my life. It is with their continuous support that I have thrived into an individual and engineer that makes them proud to have watched grow. vi Despacho RT - 31 /2019 - Anexo 4 Declaração a incluir na Tese de Doutoramento (ou equivalente) ou no trabalho de Mestrado STATEMENT OF INTEGRITY I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. Porting do LTZVisor para a Zynq Ultrascale+MPSoC ZCU102 Atualmente, a tecnologia computacional está a expandir-se para áreas que pareciam inalcançáveis nas suas etapas primordiais, substituindo os tradicionais modelos de propósito único por aplicações modernas de propósito geral focadas em conectividade, ubiquidade e segurança. Devido a esta constante remodelação de métricas, é importante desenhar novas soluções desde as fases iniciais de desenvolvimento, tendo em conta as características do sistema a nível arquitectural. De facto, muitos fabricantes estão determinados a melhorar os dispositivos dos dias de hoje de modo a providenciarem vários serviços através do seu hardware, libertando o software para se dedicar a aplicações de propósito geral. Com o crescimento da virtualização, é possível aplicar funcionalidades de componentes fisicamente absentes num único processador, resultando na utilização de menos dispositivos mas também de unidades de processamento mais potentes. Em sistemas de tempo-real, este aumento de funcionalidades torna-se prejudicial visto que sobrecarrega a execução com demasiadas operações. Ao se projetar dispositivos desde as primeiras fases com estas considerações, é possível fazer com que estes cargos deixem de ser encarregues a software, sendo portanto garantidos pelas capacidades arquiteturais das plataformas. Deste modo, a virtualização assistida por hardware consegue equilibrar toda a carga de um sistema entre os domínios do software e do hardware. Esta dissertação apresenta o processo de ”porting” de uma solução de virtualização assistida por TrustZone (LTZVisor) pelas últimas arquiteturas de alto desempenho da ARM. Esta migração entre arquiteturas implica uma alteração de plataforma, como a surgente e heterogénea Zynq Ultrascale+MPSoC da Xilinx, adotada como placa de desenvolvimento deste projeto. É indicado como as capacidades da arquitetura emergente podem ser manuseadas de modo a implementar cenários de virtualização com pouca carga, sugerindo métodos para as aplicar em ambientes de execução leves e seguros. Estas abordagens foram validadas através da integração e avaliação de máquinas virtuais de tempo-real com privilégios distintos, onde os hóspedes prosperaram sem interferirem um com o outro. Palavras-Chave: Arquitetura ARM, LTZVisor, Zynq Ultrascale+ viii Porting of LTZVisor to the Zynq Ultrascale+ MPSoC ZCU102 Presently, computing technology is expanding towards realms that seemed unrealistic at the stages of its emergence, shifting from traditional single-purpose designs to modern generalpurpose appliances centred around connectivity, ubiquity, and security. With this constant reshaping of metrics, it is important to devise new solutions from the onset, taking into account the system’s features at the architecture level. In fact, many manufacturers are motivated in improving nowadays’ devices to wield powerful services in their hardware, liberating software to expand on general-purpose applications. With the rise of virtualization, it is possible to apply the functionalities of physically absent components on a single processor, leading to the employment of fewer devices but requiring more powerful processing units. In systems with real-time requirements, this increase in overhead is prejudicial as it overloads execution with too many operations. By designing devices from the onset with those functions in mind, software ceases to handle such complex and time-consuming roles, which are guaranteed by the platform’s architectural features instead. Thus, hardwareassisted virtualization technologies balance out the total system workload between the software and hardware domains. This dissertation presents the porting process of a TrustZone-assisted virtualization solution (LTZVisor) through ARM’s latest high-performance architectures. This change in architecture entails a transfer to newer embedded platforms, like the state-of-the-art heterogeneous Zynq Ultrascale+MPSoC from Xilinx adopted as the target board for this project. It is mentioned how the emergent architecture capabilities can be handled to implement virtualized scenarios with low overhead, suggesting methods to apply them in a secure and lightweight execution environment. These approaches were validated through the integration and evaluation of real-time virtual machines with distinct privileges, where the performance sensitive guests thrived without interfering with one another. Keywords: ARM Architecture, LTZVisor, Zynq Ultrascale+ ix Glossary µRTZVisor Microkernel-like Real-Time TrustZone-assisted Hypervisor 3DIC Three Dimensional Integrated Circuit ACP Accelerator Coherency Port ACTLR Auxiliary Control Register ADC Analog-Digital Converter AP All Programmable API Application Programming Interface APSR Application Program Status Register APU Application Processing Unit AXI Advanced eXtensible Interface BPD Battery Power Domain BSP Board Support Package CAN Controller Area Network CCI Cache Coherent Interconnect CPSR Current Program Status Register CPU Central Processing Unit CTR Cache Type Register DAC Digital-Analog Converter DDR Double Data Rate DDRC Dynamic Memory Controller DMA Direct Memory Access DRAM Dynamic Random Access Memory DSP Digital Signal Processing ECC Error Correcting Code xvi EL Exception Level ELR Exception Link Register EMIO Extended Multiplexed I/O eMMC Embebbed Multi-Media Controller ESRG Embebbed Systems Research Group FinFET Fin Field Effect Transistor FIQ Fast Interrupt reQuest FPD Full Power Domain FPEXC Floating-Point Exception Register FPGA Field Programmable Gate Array FPSCR Floating-Point Status and Control Register GEM Gigabit Ethernet MAC GIC General Interrupt Controller GNU GNU Not Unix GPIO General-Purpose Input/Output GPOS General-Purpose Operating System GPU Graphics Processing Unit HCR Hypervisor Configuration Register HDMI High-Definition Multimedia Interface HMI Human-Machine Interface HP High Performance HVBAR Hypervisor Vector Base Address Register HVC Hypervisor Call I/O Input/Output I2C Inter-Integrated Circuit IoT Internet of Things IRQ Interrupt ReQuest ISA Instruction Set Architecture KVM Kernel-based Virtual Machine LPD Low Power Domain LPDDR Low Power Double Data Rate xvii LR Link Register LTZVisor Lightweight TrustZone-assisted Hypervisor MIDR Main ID Register MIO Multi-use I/O MMU Memory Management Unit MPCore Multi-Processing Core MPIDR Multiprocessor Affinity Register MPSoC Multi-Processor System-on-Chip MVBAR Monitor Vector Base Address Register MVFR Media and VFP Feature Register NSACR Non-Secure Access Control Register OCM On-Chip Memory OS Operating System PC Program Counter PCIe Peripheral Component Interconnect Express PL Programmable Logic PMU Power Management Unit PS Processing System PSR Program Status Register RAM Random-Access Memory RFSoC Radio-Frequency System-on-Chip RISC Reduced Instruction Set Computer ROM Read-Only Memory RPU Real-Time Processing Unit RTOS Real-Time Operating System RTZVisor Real-Time TrustZone-assisted Hypervisor SATA Serial Advanced Technology Attachment SCR Secure Configuration Register SCTLR System Control Register SD Secure Digital SD-FEC Soft Decision Forward Error Correction xviii SDIO Secure Digital Input Output SError System Error SIMD Single Instruction, Multiple Data SMC Secure Monitor Call SoC System-on-Chip SP Stack Pointer SPI Serial Peripheral Interface SPSel Stack Pointer Selection SPSR Saved Program Status Register SRAM Static Random Access Memory SVC Supervisor Call SVM Secure Virtual Machine SWDT Software WatchDog Timer TCB Trusted Computing Base TCM Tightly-Coupled Memory TLB Translation Lookaside Buffer TSMC Taiwan Semiconductor Manufacturer Company TTC Triple Timer Counter TZASC TrustZone Address Space Controller TZMA TrustZone Memory Adapter TZPC TrustZone Protection Controller UART Universal Asynchronous Receiver-Transceiver USB Universal Serial Bus VBAR Vector Base Address Register VM Virtual Machine VMCB Virtual Machine Control Block VMM Virtual Machine Monitor VMSA Virtual Memory System Architecture VOSYS Virtual Open Systems VT Virtualization Technology XMPU Xilinx Memory Protection Unit XPPU Xilinx Peripheral Protection Unit XSDK Xilinx Software Development Kit xix 1. Introduction 1.1 Motivation From the second half of the 20th century onwards, technology instituted a way for physical procedures to unfold without the need for human interference or heavy mechanical efforts, introducing the concept of electricity-powered machines. Initially arranged with simple designs directly constrained by the physical limitations of electrical equipment, those machines were innovated into much more powerful digital devices. By introducing a binary format, they were able to extend the applications of electronics into information storages, efficient controllers of physical tools, and smart decision-making devices, marking the birth of computers. In current days, it is a scarce thought to think about the non-existence of computing devices alongside the quotidian of modern society, stretching out to most, if not all, professional and personal activities. Due to this omnipresence, the modern world started to demand a huge trade of information throughout the globe, leading to the emergence of connectivity as one of the core metrics in the design of computing systems. With that goal in mind, a way to connect all devices between themselves while exchanging information was conceived, originating the concept behind the Internet-of-Things (IoT). While the Internet serves as an interface for users to connect to each other via a global network, IoT invests on establishing a similar scenario of mutual connectivity between everyday objects [1; 2]. As they become smarter, these devices evolved to be capable of sensing factors from their environment without human aid [2]. By assembling many of these devices into clusters, fully smart environments are created, where those devices process the information gathered through sensors and decide on the best course of action to take in order to achieve the smart environment’s goal. However, providing ubiquitous connectivity is not enough to make a reliable network. As increasingly more devices and information are globally linked and shared, it is crucial to administer the equivalent privacy to that data, which may comprise not only trivial details but also valuable and confidential information of customers, enterprises, and even governmental entities [1]. Thus, security increased exponentially as a fundamental requirement in IoT systems’ design, which shall be included not only at the later stages of development but during the whole process, interfering with software and hardware implementations [3]. 1 Chapter 1. Introduction 2 One widely used approach to provide security through separation relies on the use of virtualization technology. Virtualization enables the execution of multiple mutually isolated Virtual Machines (VMs) on the same hardware platform, which are managed by a software abstraction layer, the Virtual Machine Monitor (VMM) [4; 5]. Among embedded systems, hosting numerous mixed-criticality applications as VMs ensures that the damage in one partition does not compromise the whole system. In this context, the VMM — or underlying Hypervisor — must be more secure than the guest Operating Systems (OS), as the hypervisor’s malfunctioning invalidates the proper management of its guest VMs, compromising its integrity. This innate security causes high levels of overhead issued by the careful handling of the hosted VMs, colliding with the real-time requirements demanded in embedded systems [6; 7]. This compromise between security and performance has generated the need to develop efficient embedded virtualization solutions [8]. Hence, many Commercial Off-The-Shelf (COTS) technologies were developed to fulfill this premise, such as Intel’s Virtualization Technology (VT) [9], AMD Secure Virtual Machine (SVM) [10], ARM Virtualization Extensions (VE) [11] and ARM TrustZone [12]. The latter is an hardware-based solution that, although designed to improve a system’s security, is employed by many hypervisors to establish the separation of VMs, including LTZVisor. The TrustZone technology divides the processor into two worlds, the Secure (trusted) and Normal (non-trusted) worlds, which subdivide hardware resources and software applications [13; 12]. A processor supporting TrustZone can execute in two states, secure and non-secure, while memory regions, bus accesses, and peripherals can also be assigned to either world [14]. The normal world, being less privileged than the secure, cannot access secure resources, while the opposite is allowed. The TrustZone technology is currently supported in 19 processors with the ARMv7- A, ARMv8-A and ARMv8-M architectures. Among the Cortex-A series, only the Cortex-A5 CPU lacks TrustZone support between the 17 existing processors, meaning this technology is present in roughly 94% of Cortex-A devices [15]. In addiction, a third of the Cortex-M processors are equipped with TrustZone. Although this technology was not designed to be used as a virtualization tool, the development of TrustZone-assisted hypervisors emerged, as this hardware-based implementation could satisfy the requirements for virtualizing real-time environments [16]. The Lightweight TrustZone-assisted Hypervisor (LTZVisor) [16; 17; 18] is an open-source project developed in-house that takes advantage of TrustZone’s features to better isolate partitions, running in a tradition dual-OS configuration — Real-Time Operating System (RTOS) in the secure world and General-Purpose Operating System (GPOS) in the normal world. LTZVisor was originally developed on Xilinx Zynq-7000 devices, which include the ARM Cortex-A9 processor featured with the 32-bit ARMv7-A architecture [19]. This thesis aims to fill this gap by scaling LTZVisor to the 64-bit ARMv8-A architecture. The Chapter 1. Introduction 3 selected device for this porting was Xilinx’s Zynq UltraScale+MPSoC ZCU102 since it resembles the already supported platforms — Xilinx Zynq-7000 devices — while also enclosing an ARM Cortex-A53 processor built upon the required ARMv8-A architecture [20]. The board is a heterogeneous platform that comes with 3 processing units: an ARM Cortex-A53 quad-core Application Processing Unit (APU), an ARM Cortex-R5 dual-core Real-time Processing Unit (RPU), and an ARM Mali-400MP2 Graphics Processing Unit (GPU). This approach merges the flexibility of the three distinct processors with the reconfigurable acceleration provided by programmable logic. 1.2 Goals With this thesis, it is primarily intended to successfully port LTZVisor to the ARMv8-A architecture, scaling the hypervisor to 64-bit machines. To achieve it, a thorough study of both architectures is required, understanding deeply ARMv7-A and ARMv8-A’s features, such as instruction sets, available registers, interrupts and exception handling, approaches to access memory, and usage of the TrustZone technology. It is also crucial to be able to apply these architectural changes while maintaining — or, if possible, improving — the hypervisor’s behavior, without compromising its core structure. The porting will allow the hypervisor to be supported on most systems with integrated Trust- Zone, especially ones which include the ARMv7-A and ARMv8-A architectures. A change in architecture also implies a necessity to adapt the hypervisor to a new platform. The successful adaptation of LTZVisor’s hardware interfaces to the Zynq Ultrascale+MPSoC ZCU102 board and its components is also an important step towards completing the porting. 1.3 Document Organization This thesis is organized in six chapters. It starts by mentioning the motivation behind its theme in Chapter 1, going through the proposed goals. Chapter 2 introduces some background concepts necessary to enter into the technical details of this thesis, describing the characteristics of both the ARMv7-A and ARMv8-A architectures. Afterwards, it details some hypervisors with similar features to LTZVisor, namely the use of TrustZone in its core, having support for the ARMv8- A architecture, and the partitioning of the platform’s components. On Chapter 3, LTZVisor is presented and specified, along with its original development platform, Xilinx’s Zynq-7000, and the target platform for this thesis, the Zynq Ultrascale+MPSoC. Further ahead, Chapter 4 enters into the implementation process of porting LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 board, describing all the steps taken and the subsequent results. Chapter 5 starts a discussion about the results of the new 64-bit LTZVisor which are evaluated and compared with the results of the original version. At last, Chapter 6 presents the conclusions obtained from this thesis, mainly Chapter 1. Introduction 4 the improvements of the 64-bit LTZVisor over the original 32-bit version, its shortcomings, and future additions that may correct those faults. 2. Background & State of the Art The realm of virtualized embedded systems belongs to a complex field of technological development and investigation, brimming with precise concepts and elaborate ideas. As such, it demands an objective and thorough clarification of the technologies involved and the nomenclatures used. This chapter is devoted to explaining the fundamental concepts required to conceptualize the theme of this dissertation. Additionally, it covers some similar state of the art projects that resemble this thesis’ work. It starts by describing the evolution of virtualization, grasping its usage on embedded systems, and continues by introducing ARM architecture’s main features and relevant technologies like ARM TrustZone, ending with a contextualization of the chosen development platform’s history. The ”Related Work” section showcases several hypervisors with support for ARMv8-A, whilst also exploiting ARM TrustZone technology or partitioning the platform’s hardware components. 2.1 Fundamental Concepts 2.1.1 Virtualization Virtualization technologies surged to improve system requirements that were difficult to assess in the 1960s’ computational solutions, mainly the isolation, consolidation, and migration of software workloads [21; 4; 22]. Broadly speaking, virtualization strives to establish an abstracted execution environment which recreates software models as if they were running directly on a physical platform. This environment is carefully monitored to ensure the software model behaves as intended while being abstracted of all system resources it accesses. Traditionally, the software running on the abstracted environment is named Virtual Machine (VM), while the monitoring activity is done by the Virtual Machine Monitor (VMM), also known as hypervisor. An additional feature of virtualization is the ability to run more than one VM on a single platform, reducing the number of devices necessary for multi-functional solutions, as portrayed in Figure 2.1. Similarly, since the VMs are concealed on an abstraction environment, they are isolated from each other, preventing faults in one VM to compromise other VMs or even the whole system’s integrity. 5 Chapter 2. Background & State of the Art 6 Device 2 Device 1 Device 3 Operating System Braking System Data Processing User Interface Motor Control (a) Non-Virtualized Automotive System with multiple Devices. Device 1 Operating System Virtual Machine Monitor Braking System Motor Control Data Processing User Interface (b) Virtualized Automotive System on a single Device. Figure 2.1: Addition of Virtualization in an Automotive System. Generally, specific devices were employed for each application (2.1a). Virtualization allows for distinct functions to operate over the same platform, while maintaining isolation between each VM (2.1b). It is thanks to these traits that virtualization technologies entered the investigation scene around the world of computation. As physical devices reached a peak of performance that could not be fully satisfied by the adopted applications, there was a switch to the investment on a higher number of functionalities rather than higher levels of performance on a single device [4; 5]. However, increasing the number of applications running on a single platform clogged solutions with vulnerabilities that could jeopardize the whole device. Thus, the abstraction approach of virtualization proved to be a fitting answer, worthy of being applied in server consolidation [22; 23], utility computing [24; 25], network applications [26] or in the multi-operability of operating systems via hypervisors [27; 28; 29]. Chapter 2. Background & State of the Art 13 Figure 2.3: Cumulative features of the latest ARM architectures (taken from [40]). As new architectures were introduced, the features of previous architectures were kept throughout their evolution. a crucial trait for the type of hypervisors this thesis is based on. I will now begin to delve into the central architectures for the porting of LTZVisor, mainly the original ARMv7-A and the target ARMv8-A, concluding with an specification of the TrustZone technology. 2.1.3.1 ARMv7-A ARMv7 is a 32-bit architecture that follows ARM’s legacy in the development of processors. This architecture was a huge contributor to widen ARM’s horizons in its products by introducing the architecture profiles: Application (A), Real-Time (R), and Microcontroller (M). This thesis’ project focuses solely on the Application profile, which is aimed at high-performance processors and supports a VMSA based on a MMU [38]. ARMv7-A inherits both the ARM (A32) and Thumb (T32) instruction sets (along with the ability to interwork between them), DSP extensions, and multiprocessing instructions from previous architectures, while also introducing new features such as NEON technology. Finally, ARMv7-A incorporates the first versions of the General Interrupt Controller (GIC), which was designed to manage interrupts in a system. 2.1.3.1.1 Processor Modes An ARMv7-A CPU can execute in 9 different modes, which represent various states of execution. These modes are: User (USR), System (SYS), Supervisor (SVC), Abort (ABT), Undefined (UND), FIQ (FIQ), IRQ (IRQ), Hypervisor (HYP) and Monitor (MON) [38]. The hypervisor mode is only available in devices that integrate ARM’s Virtualization Extensions, while the monitor mode Chapter 2. Background & State of the Art 14 USR mode USR mode SVC, ABT, IRQ, FIQ, UND, SYS modes HYP mode Non-Secure Secure PL0 PL2 PL1 SVC, ABT, IRQ, FIQ, UND, SYS modes MON mode Figure 2.4: ARMv7 processor modes and the corresponding Privilege Levels. The concept of orthogonality between processor modes and execution states can be verified, as most processor modes exist on both the secure and normal worlds, except the hypervisor mode that is always non-secure and the monitor mode which is always secure. only exists when the TrustZone security extensions are implemented. The monitor mode is always secure, while the Hypervisor mode only exists in the normal world. These processor modes are linked with the Privilege Levels (PLs), which indicate the permission status of each processor mode. Figure 2.4 showcases how the nine processor modes fit into the three PLs available in ARMv7-A. Non-secure execution is always considered less privileged than secure execution, independently of privilege level, as some registers and instructions can only be accessed and performed by secure execution. Thus, even if the hypervisor mode belongs in the highest PL, it is considered to be less privileged than the processor modes located in secure PL1. The privilege levels have the following properties: •PL0 - With the fewest amount of permissions, it is associated with user-level execution, encompassing solely the user (usr) mode. It is considered the unprivileged mode which cannot access system configuration registers or privileged memory. •PL1 - In this level, execution can access basically all features from the architecture, except for the ones added by PL2. This PL includes 7 processor modes: system, supervisor, abort, IRQ, FIQ, undefined and monitor (secure world only). Software executing at those modes is considered to be privileged and is able to access both unprivileged and privileged resources. •PL2 - It is only associated with the hypervisor mode, which is also a privileged mode. PL2 and the hypervisor mode were added to the ARMv7-A architecture as part of ARM’s Virtualization Extensions with the intuit of isolating the configuration the virtualization extensions’ Chapter 2. Background & State of the Art 15 features in a single higher privilege mode. Execution can switch between modes whenever an exception or interrupt occurs and it’s trapped on the respective mode. However, it is also possible to manually switch to another processor mode by using one of three special instructions: the Supervisor Call (SVC), Hypervisor Call (HVC), and Secure Monitor Call (SMC). Each of this instructions is trapped to the supervisor, hypervisor, and/or monitor modes respectively, and can only be issued when the execution is running on the same PL as the destination mode or on the immediately lower PL. Therefore, SVC and SMC can be used on all modes except the hypervisor mode, which is in PL2. On the other hand, HVC can be used on all modes located in PL1, but not on the User mode located in PL0, as doing so would issue a jump from PL0 to PL2, which is not directly allowed in ARMv7-A. The HVC requires a special setup as it only works properly if issued on the normal world (SCR.NS bit must be active) and when the instruction is activated by setting the SCR.HCE bit, which is cleared on system reset. 2.1.3.1.2 Registers ARMv7-A includes thirteen 32-bit general-purpose registers (R0 to R12), a Stack Pointer (SP), a Link Register (LR), and a Program Counter (PC), which are defined as R13, R14, and R15 respectively. These last three registers are designated special-purpose registers that, such as the Saved Program Status Register (SPSR), have distinct copies for each of the processor modes as Figure 2.5 showcases. These copies are denoted as banked copies, implying that using the common register token . Registers that follow this behaviour are called banked registers, and can have copies for every processor mode . The System mode has access to the same registers as the User mode but from PL1 instead of PL0. Along with the hypervisor mode, these three modes share the same LR, while the hypervisor mode adds the Exception Link Register (ELR_hyp) to indicate the returning address when leaving PL2 via the ERET instruction. When switching processor modes, the Program Status Registers are modified as they save the execution status. ARMv7-A provides an application and a system view of these registers, namely the Application Program Status Register (APSR) and the Current Program Status Register (CPSR). Both of them have the same purpose, although the CPSR adds extra system level information (Figure 2.6). The SPSRs represent asynchronous copies of the CPSR that are saved whenever an exception occurs to the respective mode. As Figure 2.5 shows, there is a SPSR for each processor mode except the User mode (which can’t handle exceptions as it belongs to the unprivileged PL0), and the System mode (which is never a target for an exception). Apart from the core registers, ARMv7-A has a large bundle of system control registers, designed to configure system-level settings, such as TrustZone, cache, vector table, and VMSA configurations. Not all of these registers exist in every version of ARMv7-A, depending on whether it Chapter 2. Background & State of the Art 16 includes Security and/or Virtualization Extensions. System control registers cannot be read/written by PL0 execution since that is only possible by accessing the CP15 and CP14 coprocessors. In a device with Security Extensions, system control registers can have different behaviours: •Banked registers, which have two separate copies, one for the secure world and another for the normal world. Just a few of the CP15 registers can be banked (e.g. ACTLR, SCTLR, VBAR). •Restricted access registers, which are only present in the secure world. Attempts to access these registers from the normal world are not permitted (e.g. SCR, NSACR, MVBAR). •Configurable access registers, which can be configured by secure software to be accessed by both worlds or only by the secure world. The NSACR is the register responsible for such configuration (e.g. FPSCR, FPEXC, MVFRs). •PL2-mode registers, which are intended to be used in PL2. They can be banked CP15 read/write or write-only and shared CP15, responsible for configuring the Hypervisor mode interfaces and execute PL2-related operations. ARMv8 Registers ARM DEN0024A Copyright © 2015 ARM. All rights reserved. 4-14 ID050815 Non-Confidential Figure 4-7 The ARMv7 register set showing banked registers Banking is used in ARMv7 to reduce the latency for exceptions. However, this also means that of a considerable number of possible registers, fewer than half can be used at any one time. In contrast, the AArch64 execution state has 31 × 64-bit general-purpose registers accessible at all times and in all Exception levels. A change in execution state between AArch64 and AArch32 means that the AArch64 registers must necessarily map onto the AArch32 (ARMv7) register set. This mapping is shown in Figure 4-8 on page 4-15. The upper 32 bits of the AArch64 registers are inaccessible when executing in AArch32. If the processor is operating in AArch32 state, it uses the 32-bit W registers, which are equivalent to the 32-bit ARMv7 registers. AArch32 maps the banked registers to AArch64 registers that would otherwise be inaccessible. (A/C)PSR User FIQ IRQ ABT SVC UND R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13 (sp) R14 (lr) R15 (pc) R0 R1 R2 R3 R4 R5 R6 R7 R8_fiq R9_fiq R10_fiq R11_fiq R12_fiq SP_fiq LR_fiq R15 (pc) R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 SP_irq LR_irq R15 (pc) R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 SP_abt LR_abt R15 (pc) R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 SP_svc LR_svc R15 (pc) R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 SP_und LR_und R15 (pc) SPSR_fiq CPSR SPSR_irq CPSR SPSR_abt CPSR SPSR_svc CPSR SPSR_und CPSR Banked CPSR R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13 (sp) R14 (lr) R15 (pc) Sys MON HYP R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 SP_mon LR_mon R15 (pc) R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 SP_hyp LR_hyp R15 (pc) SPSR_mon CPSR SPSR_hyp CPSR ELR_hyp Figure 2.5: Core Registers of the ARMv7-A Architecture (taken from [40]). They are mapped through the processor modes, whereas the FIQ mode has extra banked registers to allow for faster and easier interrupt handling. Chapter 2. Background & State of the Art 17 Figure 2.6: ARMv7-A APSR, CPSR and SPSR formats (adapted from [38]). The CPSR and SPSR contain more detailed info, such as the processor mode (M[4.0])and exceptions mask flags for Aborts (A), IRQs (I), and FIQs (F). •Common registers, which belong to both Secure and normal worlds, maintaining its values during a domain switch. Some CP15 registers fall in this category (e.g. MIDR, CTR, MPIDR) along with all CP14 registers (debug, trace and execution environment control registers). Accessing the CP15 and CP14 coprocessors may also issue some system control operations, which are not part of the supported instruction set. 2.1.3.1.3 Instruction Sets ARMv7-A supports two instruction sets, the 32-bit ARM instruction set (A32) and the 16-bit or 32-bit Thumb instruction set (T32). Thumb also provides 16-bit instructions, which can provide more efficient execution than 32-bit instructions, especially if the required operations have lowcomplexity [38]. Both instruction sets are compatible with each other, so software can interwork between the ARM and Thumb instruction sets at any time with no overhead when swapping between the two. It is possible to change from one state to another using the BX, BLX, LDR or LDM instructions, which are available in both sets. The A32 instruction set contains additional instructions to swap to the Thumb-based execution. Overall, ARMv7-A offers instructions capable of performing arithmetic, logical and other dataprocessing operations on the core registers. There are three ways to access the coprocessors and activate their features: initiating a coprocessor data-processing operation (CDP and CDP2 instructions), moving core registers to and from the coprocessor registers (MRC and MCR types of instructions) and by loading or storing the values of the coprocessor registers (LDC and STC instructions). Most coprocessors have vendor-specific features (CP0-7) or were reserved for future use by ARM (CP8, CP9, CP12, and CP13). Excluding those, the CP10 and CP11 can be used to issue floating-point and Advanced SIMD operations and CP14 to handle debug, trace and Thumb Execution Environment operations. That leaves the CP15 coprocessor which is the one with the most varied functionalities. Table 2.2 indicates the features that each primary coprocessor offers Chapter 2. Background & State of the Art 18 Table 2.2: Organization of CP15 registers and available operations (adapted from [38]). The CP15 is organized in 16 primary coprocessor registers (CRn), which can have different functions according to 2 opcodes (opc1 and opc2) and a secondary coprocessor register (CRm). CRn opc1 CRm opc2 Function c0 0-2 c0-c7 0-7 ID registers c1 0,4 c0,c1 0-7 System Control registers c2 0,4 c0,c1 0-2 Memory Protection and Control registers c3 0 c0 0 Memory Protection and Control registers c4 - - - Not used c5 0,4 c0,c1 0,1 Memory System Fault registers c6 0,4 c0 0,2,4 Memory System Fault registers c7 0,4 Various Various Cache Maintenance, Address Translations c8 0,4 Various Various TLB Maintenance Operations c9 0-7 Various 0-7 Performance Monitors and Maintenance c10 0-7 Various 0-7 Memory Mapping and TLB Operations c11 0-7 c0-c8,c15 0-7 DMA Operations for TCM access c12 0,4 c0,c1 0,1 Security Extensions (if implemented) c13 0,4 c0 0-4 Process, Context and Thread ID registers c14 0-7 c0-c15 0-7 Generic Timer registers (if implemented) c15 0-7 c0-c15 0-7 IMPLEMENTATION DEFINED to the architecture, including control and configuration operations on system-level functionalities, confirming the importance of CP15 on an embedded design like LTZVisor. The functionalities of the CP15 coprocessor operations may vary according to the implementation of each ARMv7-A processor. Thus, further specification of the CP15 coprocessor operations can be found in the target CPU’s technical reference manual (p.e. Cortex-A9 [42]). Proceeding with ARMv7-A instructions, it is known that ARM’s architecture traditionally applies load/store mechanisms to transfer register data from and to memory (see Section 2.1.3). Those load/store mechanisms are supported by various instructions that differ from each other on the size of each transferred element and their number, including the load/store multiple instructions (LDM and STM). Loading and storing can be used with the SP as the destination register, acting as PUSH or POP stack management instructions, which can also write and read multiple registers with a single PUSH or POP instruction. Additionally, ARMv7-A provides flexible conditional execution by offering a bunch of branching instructions with many scenarios in mind. The B instruction is the most basic branch, which jumps to the indicated address, with a range of ±256 bytes when using 16-bit Thumb branching or ±1MB when using A32 or 32-bit Thumb branch instructions. Branching can also be done by writing an address directly to the PC. Every branch can be assisted by four conditional flags — Zero (Z), Carry (C), Negative (N) and Overflow (V) — that indicate the conditional state of execution Chapter 2. Background & State of the Art 19 Table 2.3: ARMv7-A available conditions and conditional flag combinations (adapted from [38]). By analysing the binary state of the four conditional flags, an ARMv7-A processor is able to determine a specific conditional scenario of execution. Condition Meaning Flags 0000 (EQ) Equal Z==1 0001 (NE) Not Equal Z==0 0010 (CS) Carry Set C==1 0011 (CC) Carry Clear C==0 0100 (MI) Minus, Negative N==1 0101 (PL) Plus, Positive or Zero N==0 0110 (VS) Overflow V==1 0111 (VC) No Overflow V==0 1000 (HI) Unsigned Higher C==1 and Z==0 1001 (LS) Unsigned Lower or Same C==0 and Z==1 1010 (GE) Signed Greater Than or Equal N==V 1011 (LT) Signed Less Than N!=V 1100 (GT) Signed Greater Than Z==0 and N==V 1101 (LE) Signed Less Than or Equal Z==1 or N!=V 1110 (None) Always (unconditional) Any through binary combinations, as seen in Table 2.3. These flags are altered when comparative instructions (CMN and CMP) or certain data processing instructions ending with the character ”S” (MOVS, ADDS and SUBS) are executed. Furthermore, the conditional mnemonics shown can be suffixed to another instruction (for example, ”ADDNE”) to indicate that the typed instruction is only executed if the specified condition is true, providing flexible and responsive conditional behaviours. Furthermore, ARMv7-A offers system barrier instructions, that order and synchronize accesses to memory (ISB, DSB, and DMB), processor hints (YIELD and DBG) and exception handling instructions, either to generate exceptions (SVC, HVC, and SMC) or to return from them (ERET). 2.1.3.1.4 Exception Handling ARMv7-A has five types of exceptions: reset, interrupts, memory system aborts, undefined instructions, and system calls [38]. These types can be broken up into nine exceptions: •Reset goes back to the starting point of execution after stopping it beforehand. Upon reset, the processor starts in secure Supervisor mode (PL1). The starting point of execution can be at the low or high reset vector address (0x00000000 or 0xFFFF0000 respectively), depending on the reset value of the SCTLR.V bit; Chapter 2. Background & State of the Art 20 •IRQ, triggered by an IRQ interrupt, executes the handler of the respective interrupt. Whenever an IRQ exception is taken, the processor traps, by default, into the IRQ mode (PL1), but can also trap to the hypervisor (PL2) or monitor (PL1) modes depending on system configurations; •FIQ, which occurs once a FIQ interrupt is triggered. It traps execution to the FIQ mode (PL1) in order to execute the handler of the respective FIQ interrupt. Similarly to the IRQ exceptions, the processor may trap to the hypervisor (PL2) or monitor (PL1) modes depending on system configurations; •Data Abort exceptions are prompted when erroneous memory accesses are performed, whether in data reads or writes, instruction fetches or translation table accesses. They are handled in abort mode (PL1) but can be configured to be handled in hypervisor (PL2) or monitor mode (PL1). •Prefetch Abort happens when a fetched instruction is located on memory that is inaccessible by current execution, therefore the fetch is aborted and the exception triggers. It is handled on the abort mode (PL1) but can be configured to be handled in hypervisor (PL2) or monitor mode (PL1). •Undefined Instruction occurs whenever an instruction with undefined or invalid behaviour is attempted to be executed, such as disabled coprocessor operations or unimplemented instructions. The handler to these exceptions runs in undefined mode (PL1), but can also be handled in the hypervisor mode (PL2); •Supervisor Call is triggered via the SVC instruction, which is used to enter the supervisor mode (PL1), normally from the user mode (PL0); •Hypervisor Call requests functionalities unique to the Hypervisor mode (PL2), normally related to the reconfiguration of virtualization extensions’ functionalities. This exception is triggered by issuing the HVC instruction when the virtualization extensions are implemented and from a processor mode with PL1 privilege running in the non-secure state; •Secure Monitor Call is an exception triggered by the SMC instruction that is handled in monitor mode (PL1). It is frequently used to request operations that are only permitted from the secure monitor layer, such as transitioning from one execution state to the other. The handlers of these exceptions are named exception vectors and are located in unique addresses. They are arranged in sets of 8 entries, where each set is known as a vector table. There are four vector tables: one for the hypervisor mode, one for the monitor mode, and one for each of the PL1 worlds, the secure and the normal. Table 2.4 shows the contents of those Chapter 2. Background & State of the Art 21 Table 2.4: Arrangement of Exception Vector Tables in ARMv7-A (adapted from [38]). The entries have 4 bytes of memory between themselves, having room for solely a single instruction. Offset Hypervisor Monitor Secure Non-Secure 0x00 - - Reset - 0x04 Undefined - Undefined Undefined 0x08 HVC SMC SVC SVC 0x0C Prefetch Abort Prefetch Abort Prefetch Abort Prefetch Abort 0x10 Data Abort Data Abort Data Abort Data Abort 0x14 Hyp Trap - - - 0x18 IRQ IRQ IRQ IRQ 0x1C FIQ FIQ FIQ FIQ vector tables and how they’re arranged. It can be seen that each handler has room for a single instruction before the offset of the next handler, almost obligating the use of subroutine branches on the vector table’s memory space. The base address of each of the vector tables is contained on the following system registers: HVBAR for the hypervisor, MVBAR for the monitor and VBAR for both the secure and non-secure vector tables. The later being a banked register, it contains the address of the vector table related to the current execution domain and swaps its value whenever there is a world-switch. It can also be confirmed in Table 2.4 that the program reset starts in the Secure PL1 and that the monitor mode has permission to execute any instruction, lacking an Undefined Instruction handler. The Hyp trap exception indicates the entry point of the Hypervisor mode. 2.1.3.2 ARMv8-A ARMv8-A is the most recent ARM architecture, introducing its processors to the 64-bit realm. It presents major changes to the traditional ARM features while maintaining a high level of consistency with its previous versions [37]. While all variants of this architecture include TrustZone, there are extensions to the ARMv8-A architecture that bring even more features, such as allowing the Exception Level 2 (EL2) to exist on the Secure World (available in ARMv8.4-A) [37]. Since the CPU enclosed in this project’s development platform supports the ARMv8.0 version of the architecture, it does not include any of those extensions. Hence, they will not be further described as they do not belong in the range of this dissertation’s investigation. The most interesting feature in ARMv8-A is the introduction of two distinct execution states: •AArch32, which envisions to mimic the 32-bit ARMv7-A environment, allowing for ARMv7- A compatible software to be compiled and run even in systems supporting ARMv8-A; •AArch64, bringing the innovative features of the ARMv8-A architecture, such as a 64-bit instruction set, a re-design of the existing privilege levels and a new register file. Chapter 2. Background & State of the Art 22 Although both execution states adopt different register sets, all ARMv8-A registers are 64- bit wide. As AArch32 mimics the ARMv7-A architecture, it only takes into account the lower 32 bits of the accessed registers. When swapping between execution states, it is important that the values of some registers are maintained, like the first general-purpose registers. Therefore, the registers in AArch64 are mapped to the register set in AArch32. The same occurs with some special-purpose and system control registers, where the mapped registers normally have similar functions and names on each of the execution states. An ARMv8-A processor can boot from either AArch32 or AArch64, and can also switch between them during execution. To do so, at least the highest privileged level of execution must be running on AArch64. This is necessary because privileged AArch32 software cannot handle less privileged execution in AArch64. Hence, in order for both states of execution to be present, the highest privilege code must run on AArch64. The following specification of the architecture will focus mostly on the innovative ARMv8-A features, specifically on the unique characteristics of the AArch64 execution state. 2.1.3.2.1 Exception Levels One of the most relevant changes in the AArch64 execution state was the re-design of the levels of privilege, introducing the Exception Levels (ELs) [37]. The ELs are organized similarly to ARMv7-A’s Privilege Levels, but are no longer related to the processor modes, which are obsolete on the AArch64 execution state. The ELs are separated into four levels: •EL0, indicating an unprivileged state, intended to run user applications; •EL1, indicating the privileged execution of an OS or kernel; •EL2, indicating the privileged monitoring layer of a hypervisor; •EL3, indicating the privileges of the Secure Monitor, the most privileged level in ARMv8-A. In comparison to ARMv7-A’s PLs, the arrangement of ELs only differs on the isolation of the monitor mode to a whole new level of privilege — EL3 — as depicted in Figure 2.7. Since managing the world-switches requires access to important system registers, it is essential that other modes do not access those registers and change architectural configurations. Hence, the monitor mode in ARMv7-A was promoted to EL3 in the ARMv8-A architecture, becoming the only mode with permission to access all system registers. Since EL3 only contains the monitor mode, it is an always secure EL. When a CPU supporting the ARMv8-A architecture boots or is reset, it starts running on EL3. To decrease the privilege of execution it is necessary to issue the ERET instruction, which changes execution to a lower EL according to the M[3:0] bits of the SPSRs. Likewise, the ERET instruction can return to the currently running EL too. It is also possible to indicate the execution state which the ERET Chapter 2. Background & State of the Art 29 Table 2.6: Vector table structure in ARMv8-A (adapted from [40]). Exceptions are distinguished in four types: synchronous, IRQs, FIQs, and SErrors. Each of these types has a separate vector table entry depending on four distinct scenarios, granting a total of 16 entries per vector table, each of them with room for 32 instructions. Offset Exception Type Description 0x000 Synchronous Current EL with SP_EL0 0x080 IRQ/vIRQ 0x100 FIQ/vFIQ 0x180 SError/vSError 0x200 Synchronous Current EL with SP_ELx 0x280 IRQ/vIRQ 0x300 FIQ/vFIQ 0x380 SError/vSError 0x400 Synchronous Lower EL using AArch64 0x480 IRQ/vIRQ 0x500 FIQ/vFIQ 0x580 SError/vSError 0x600 Synchronous Lower EL using AArch32 0x680 IRQ/vIRQ 0x700 FIQ/vFIQ 0x780 SError/vSError (SVC, HVC, and SMC) and instructions to return from them (ERET). 2.1.3.2.4 Exception Handling With the introduction of ELs, ARMv8-A implements a new exception handling system, where each EL (apart from EL0 that does not have permission to handle exceptions) has a vector table of its own. The role of exceptions remains the same: to trap unprivileged activity to privileged execution. The exception handling system can also be used to intentionally trap execution to a higher EL. ARMv8-A exceptions can be categorized in IRQ and FIQ interrupts, aborts, system calls, reset exception and system errors (SErrors) [40]. However, the vector table provided by the architecture only has four exception entries: synchronous exceptions, IRQs, FIQs, and SErrors. AArch64 presents two major types of exceptions, synchronous and asynchronous. Synchronous exceptions are caused by the execution itself, such as issuing system calls, instruction aborts or SP and PC misalignment. Asynchronous exceptions originate from sources disconnected with current execution, including interrupt requests and SErrors. The latter encompass aborts that are not directly related to the execution, like for example, when a write-back of dirty data from a cache line to external memory is performed [40]. A vector table in ARMv8-A has the format shown in Table 2.6, with a total of 16 entries. The four available scenarios were provided Chapter 2. Background & State of the Art 30 to assist in identifying the execution environment’s status when an exception occurs, allowing for more detailed exception handling mechanisms. Combining the 4 exception types with the 4 scenarios, ARMv8-A vector tables provide up to 16 entries of exception handling. Each of these entries is separated by 128 bytes, fitting 32 instructions in each handler. The asynchronous exceptions - IRQs, FIQs, and SErrors - have virtual counterparts, that work alongside the virtualization extensions to allow virtualized guests to handle some of those exceptions in a more secure and isolated fashion. 2.1.3.3 ARM’s GIC Architecture Since the surge of the ARMv7 architecture, ARM has designed a specified controller to interface interrupts with the CPU. The General Interrupt Controller (GIC) offers a kit of interrupt-based configurations taking into account the TrustZone security extensions. As newer ARM architectures surged, the GIC was improved to comply with the adjustments made, including a total of 4 established versions. This section details the first two versions of the GIC architecture, as those are the relevant versions for the porting process of LTZVisor. GICv1 is present on Zynq-7000 devices while the ZCU102 board supports the GICv2 version of the architecture. Overall, the GIC is capable of managing the system’s interrupt sources, determine their origin and route them to the specified processors [43; 44]. When examining Figure 2.11 it can be seen that the GIC is partitioned in 2 blocks, the distributor and the CPU interfaces. The interrupt signals are received by the distributor, that identifies them and performs first-stage prioritization. Then, the received interrupts are distributed to one of the 8 available CPU interfaces, which acknowledge the signal and perform a second-stage prioritization on the processor level. Furthermore, the CPU can also interact with the GIC by accessing its registers to configure its behaviour and control the status of the interrupts, as well as trigger their own interrupts, named software-generated interrupts (SGI). The GIC’s configuration and control registers are mapped to the device’s memory. The GIC employs TrustZone’s world partition, allowing each interrupt to be configured as secure or non-secure. It provides two different types of exception requests for handling interrupts, the IRQs and the FIQs. While a non-secure interrupt can only signal an IRQ interrupt request to the target processor, a secure interrupt can signal both IRQ and FIQ interrupt requests. A CPU interface can be configured to receive only secure, only non-secure, or both types of interrupts. Since there are different exception handlers for the IRQ and FIQ interrupt requests, it is possible to have different handling routines for non-secure and secure interrupts. In GICv2, these principles are kept, while some slight improvements are introduced. The most relevant changes are the addition of virtualization support, interrupt grouping, and upgrades to the controller’s power efficiency [44]. GIC’s virtualization extensions allow hypervisor-level (EL2 or PL2) software to route physical interrupts to its guests or to generate virtual interrupts and redirect them towards the guests. Virtual interrupts are signals sent to a VM which are perceived as triggers Chapter 2. Background & State of the Art 31 of a physical interrupt. They are sent by a virtual CPU interface which, just like a physical CPU interface, can be configured to send IRQ or FIQ requests to the VMs. These interfaces are typically configured from EL2/PL2 and serve as a stronger abstraction mechanism between the guest VMs and the physical components of the system, namely the interrupt sources. Interrupt grouping creates two groups of interrupts: group 0 for the secure interrupts and group 1 for the non-secure. By default, all interrupts belong to group 0 and signal a processor via the IRQ interrupt request. However, any interrupt can be configured to belong to either group and the CPU interfaces can be set up to perform either IRQ or FIQ requests on group 0 interrupts. Nonsecure or group 1 interrupts always cause IRQ interrupt requests. This allows for more isolated prioritization strategies since all group 0 interrupts have higher priority than group 1 interrupts. General Interrupt Controller Interface Interrupt Sources Processor 7 Processor 0 Processor 1 Interface Interface Interface FIQ, IRQ FIQ, IRQ FIQ, IRQ CPU Interface 0 Distributor CPU Interface 1 CPU Interface 7 Figure 2.11: GICv1 distributor and CPU interface blocks (adapted from [43]). Interrupt signals enter the distributor which routes them to the correct CPU. Then the CPU Interface adapts that interrupt signal into a FIQ or IRQ and secure or non-secure request, which is then sent towards the respective processor. Chapter 2. Background & State of the Art 32 Table 2.7: Distribution of the TrustZone Technology among ARM’s CPUs. Among the 19 total CPUs with TrustZone technology, 5 of those were designed with ARMv7-A (26,3%), 11 with ARMv8-A (57,9%) and 3 with ARMv8-M (15,8%). Cortex-R processors do not incorporate this technology. ARM TrustZone-enabled CPUs Percentage Architectures (Total: 19) (%) ARMv7-A A7; A8; A9; A15; A17 26,3% ARMv8-A A32; A35; A53; A57; A64AE 57,9% A72; A73; A75; A76; A76AE ARMv8-M M23; M33; M35P 15,8% 2.1.3.4 ARM TrustZone ARM’s security extensions, or TrustZone, were first included on the ARMv6 architecture, namely on the ARM1176JZ(F)-S processor [12], becoming a feature on the processors shown in Table 2.7, which were designed with the ARMv7-A, ARMv8-A, and ARMv8-M profiles [15]. TrustZone provides hardware security extensions for ARM’s processors, encompassing system components like memory, buses, peripherals, and interrupts. It splits hardware, software, and data in two worlds: the Secure and the Non-Secure [8; 13]. This separation is achieved by virtualizing the physical core into two virtual cores, one for each world, allowing the processor to execute in two distinct execution domains. Figure 2.12 showcases how this world division is applied to most components of a platform, creating a complete subdivision of both software and hardware environments into both unprivileged and trusted worlds. Due to a new processor bit — the Non-Secure (NS) bit located in the System Configuration Register (SCR) — it is possible to identify which domain is currently executing. Likewise, memory regions, buses, and peripherals also added a 33rd bit meant to indicate the world which those components belong to. Secure resources can only be accessed from the secure execution domain, while non-secure resources can be accessed from both worlds. TrustZone also allows for specific instructions to be executable solely on the secure world, being trapped when an attempt to execute them occurs from the non-secure domain, like when accessing the CP15 coprocessors [13; 12]. The execution domains can be switched at any time while software is running. To supervise the switches between worlds, a new processor mode named monitor mode was created. This mode is responsible for managing critical resources during a change of execution domain. Similar to the context switch between tasks of an OS, world-switching demands that the data of the world being left is correctly saved and the resources of the target world are properly restored. The monitor mode is by predefinition a secure mode, implying it can only run while on the secure world. However, it is possible to enter this mode from non-secure execution, either through a hardware exception, an interrupt being trapped to the monitor mode itself, or via the SMC instruction. Entering into the monitor mode from the secure world can also happen from any Chapter 2. Background & State of the Art 33 TrustZone-based Platform Non Secure Secure SoC Memory Secure Non Secure Non-Secure Execution GIC Non-Secure Device Non-Secure Peripheral Secure Peripheral Secure Device Secure Execution ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? Secure Bus Non-Secure Bus Figure 2.12: Structure of an ARM TrustZone-based Platform. A TrustZone-based SoC is granted 2 domains of execution — one for trusted environments (secure) and the other for non-critical applications (non-secure). Similarly, memory regions, peripherals, buses’ accesses and interrupt requests are also partitioned into the secure or nonsecure worlds. of the aforementioned reasons. However, ARMv7-A provides a simpler method to do so, which involves writing to the Mode bits (M[4:0]) of the CPSR, when done from another processor mode within PL1. TrustZone also divides memory, buses, and peripherals into the 2 worlds. These resources are assigned to one of those worlds by a specific controller. In terms of memory: DRAM, ROM, SRAM and even caches and MMU suffer from the world partitioning. DRAM is configured by the TrustZone Address Space Controller (TZASC), while off-chip ROM and SRAM by the TrustZone Memory Adapter (TZMA). These controllers traditionally permit the configuration of their respective memories in personalized regions. However, some implementations of these controllers only allow the assignment of fixed memory regions as secure or non-secure [45; 14]. Processor caches include a tag on their entries which indicates the domain of the memory being accessed and the MMU is partitioned into 2 distinct interfaces, one for each world, to provide separate memory address translation tables to each world. Peripherals and system buses are configured via the TrustZone Protection Controller (TZPC), establishing any peripheral or bus as secure or non-secure. Finally, TrustZone is also applied to interrupt management, causing a distinction between secure and non-secure interrupt sources. Secure interrupts can be selected to have priority over non-secure interrupts via the GIC, which allows for several interrupt models. One of the most traditional models is to assign Fast Interrupt reQuests (FIQs) as secure and Interrupt ReQuests (IRQs) as non-secure interrupt sources. Chapter 2. Background & State of the Art 34 2.2 Related Work Section 2.1.2 introduces how the different paradigms of virtualization technologies were applied in the design of hypervisors over the years. It refers some of the most renown hypervisors that were released on the upsurge of virtualization and are up-to-date with the actual technological trends [27; 29; 28]. Newer technologies emerged to better integrate virtualization on the embedded systems realm [6], such as Intel’s VT [9] and AMD’s SVM [10]. ARM followed this trend by also establishing its own virtualization extensions, asserting the use of virtualization in embedded systems even more. Although ARM’s TrustZone technology was designed to improve security and not to assist virtualization, it ended up being used as a stepping stone towards a new paradigm of hypervisors based around TrustZone’s world partitioning. This section will focus on these hypervisors, further specifying those with features that were of use to the ARMv8-A version of LTZVisor developed in this dissertation. As aforementioned, TrustZone segments an ARM-based system into two worlds, subdividing the processor, memory, buses, peripherals and interrupts. This full-system division satisfies the time and space isolation of VMs demanded in virtualized environments, justifying the use of TrustZone as a core hardware-based technology in the design of hypervisors. The first TrustZoneassisted virtualization solution was developed in 2008 by Cereia et al. [46], which presented an asymmetric virtualization approach that hosts two guests with different levels of criticality, an RTOS on the secure world and a GPOS on the normal world. This solution proved that the realtime requirements of the RTOS were met while both guests were virtually executing on the same platform. This was due to the higher scheduling priority of the RTOS over the GPOS, provided by the asymmetric virtualization approach. Later, TOPPERS designed the SafeG hypervisor [47], which applied the fundamentals of Cereia’s et al. hypervisor and enhanced them by improving the scheduling of the GPOS’ soft real-time tasks and interrupts, implementing basic device sharing mechanisms without overhead, and adding support for the RTOS to health-monitor the GPOS. As an active open-source project, the current SafeG replaced the idle scheduling policy with an integrated scheduler and contains support for multicore platforms. Simultaneously, single-guest TrustZone-assisted virtualization approaches were being developed by Douglas [48] and Frenzel et al. [49], where the hypervisor simply provides low-overhead monitoring and isolation of the VM. In this single-guest setting, the guest runs on the normal world as it is monitored by the hypervisor on the secure world. Frenzel’s et al. hosted a Linux OS as the non-secure VM and evaluated its performance overhead in the TrustZone-assisted virtualization environment under various workloads, obtaining positive results when compared to para-virtualization approaches [49]. On the other hand, Douglas’ thin hypervisor hosted a single FreeRTOS instance [48]. In both of these approaches, the hypervisor was responsible of booting the system, assigning each hardware component as secure or non-secure. Chapter 2. Background & State of the Art 35 In 2012, Sierraware introduced the concept of multi-guest virtualization on TrustZone-assisted hypervisors with SierraVisor from the Open Virtualization Project [50]. It creates two instances of the hypervisor, one for each world, whereas the secure instance monitors the secure guests and the non-secure instance manages the non-secure guests. Although secure guests are protected from non-secure ones by TrustZone’s design, harmful non-secure activity in one guest can threaten the other non-secure guests as they share the non-secure address space. This vulnerability is enough to threaten the hypervisor’s integrity, specially when compared with the space isolation of dual-guest hypervisors that is reinforced by TrustZone’s world division. Later, Pinto et al. improved the multi-guest paradigm with RTZVisor in 2016. They propose saving the context of inactive guests in the secure world, while the currently executing guest is running on the normal world. With this implementation, context-switching between guests needs to reconfigure the address space of the guest being suspended from the non-secure to the secure world, and vice-versa for the guest that is about to be executed. The same is required when concerning the state of devices, as secure devices belong to the inactive guests and non-secure devices are accessed by the active guest. This implementation provides strong spatial isolation between guests, but may suffer in performance overhead, specially in scenarios with high rate of context-switching between guests. RTZVisor was subsequently enhanced by Martins et al. with µRTZVisor [51], a solution based on a microkernel architecture and with object-oriented implementation. Beyond the features of RTZVisor, µRTZVisor strengthened the time isolation of guests with a scheduler based on time domains that adopts a preemptive, round-robin scheme. Simultaneously, it is able to host nearly unmodified guest OSes, which is rare in microkernel-based hypervisors, and provides enhanced flexibility and configurability of functionalities. With the main goal of porting LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 board — namely to the ARMv8-A architecture — the . The hypervisors further specified are Baryshnikov’s et al. Jailhouse [52], which focuses on hardware resource partitioning on many platforms such as the ZCU102 board, and Lucas’ et al. VOSYSmonitor [53], a native TrustZone-assisted ARMv8-A solution. 2.2.1 Jailhouse In 2013, Jailhouse was announced as a solution to the predicament of security-based virtualization in embedded systems. This hypervisor takes a completely different approach than the primordial hypervisors like Xen and KVM, focusing more on resource partitioning rather than virtualization techniques [52]. This means that the hypervisor avoids applying too much overhead on managing virtualized partitions, and instead focuses on providing security by isolation. In fact, Jailhouse is an open-source hypervisor without scheduling mechanisms and capable of supporting real-time and fully functional guests simultaneously. Chapter 2. Background & State of the Art 36 Hardware Jailhouse Device A Core 0 Device B Core 1 Core 2 Device C Core 3 Linux Bare-metal or RTOS Root Cell Non-root Cell Figure 2.13: Jailhouse’s System Overview (adapted from [54]. After the root cell launches Jailhouse, it lets the hypervisor partition the system’s resources, supplying them to other cells. As more non-root cells exist simultaneously, fewer resources are available for the root cell. Jailhouse is Linux-based, implying it is executed under a Linux environment. Actually, Jailhouse is loaded from a regular Linux system, which boots normally by initializing all of its components. Thereafter, the Linux launches Jailhouse, giving it full control of the system’s resources and becoming one of its guests. Jailhouse’s guests are entitled cells and derive from this Linux partition, known as the root cell. Jailhouse relies on the root cell to perform control operations over the other cells and to borrow some extra Linux-based functionalities. Once a new cell is created — designated as non-root cell — the root cell offers some of its cores and devices to execute the other partition, as indicated by Figure 2.13. This justifies the lack of scheduling policies by the hypervisor, as each partition is executed simultaneously on each core in an Asynchronous Multi-Processing (AMP) scheme. With a completely distinct structure from traditional hypervisors, Jailhouse is capable of creating a guest multiplexing environment more centred around hardware configurations than virtualization mechanisms. Although it highly differs from LTZVisor, it was also developed with lightweight properties in mind, thus relying on hardware partition to guarantee the isolation between cells. Besides, it is supported on a plethora of platforms which include the Zynq Ultrascale+ MPSoC. This proves that the ZCU102 board has highly configurable components capable of being Chapter 2. Background & State of the Art 37 isolated from each other. Therefore, as most core mechanics of Jailhouse can be overlooked, its scalable hardware interfaces and extensive interactions with a Linux OS are important segments to stimulate further development of the ARMv8-A version of LTZVisor. 2.2.2 VOSYSmonitor Unlike the dissimilar Jailhouse, Virtual Open Systems (VOSYS) present a virtualized monitor layer with similar features to LTZVisor. The VOSYSmonitor is also based on the ARM TrustZone technology, entailing a dual-OS configuration with a secure RTOS alongside a non-secure GPOS [53]. This mixed-criticality monitor was developed mainly on ARMv8-A systems, including on Zynq Ultrascale+MPSoCs, hence becoming one of the references for this dissertation. The VOSYSmonitor’s development took the inverse course of LTZVisor’s, as it was first developed on the ARMv8-A architecture and was only later supported in ARMv7-A platforms. Plus, it currently only supports one board featuring the ARMv7-A architecture, the Resesas RZ/N1D which contains a dual-core Cortex-A7 CPU [55], different from the Cortex-A9 that LTZVisor natively supports. Still, being a hypervisor natively developed to the ARMv8-A platform serves as an example, since its structure and functionalities were not constrained by other architecture’s constraints. Figure 2.14 shows that VOSYSmonitor is a firmware that oversees 2 virtualized guest OSes, a safety-critical RTOS plus a full-fledged GPOS. As anticipated, the hypervisor runs on EL3, the most privileged level of execution in ARMv8-A, allowing EL2 to be exploited by the non-secure guest to hold a hypervisor of its own, admitting a higher number of non-secure VMs. This configuration sets up a scenario capable of hosting a Linux-KVM as the non-secure guest, exploiting the most out of ARM’s virtualization extensions. The context-switching between guests is akin to LTZVisor’s. SMCs are used to transition from the secure to the non-secure guest and FIQs trigger the scheduling of the secure guest, which has priority over the non-critical GPOS. Where VOSYSmonitor starts to differ from LTZVisor is on the booting process. While LTZVisor is responsible for the whole boot sequence, VOSYSmonitor is only executed after a succession of bootloaders, which are responsible for authenticating the guests’ and hypervisor’s binaries while also initializing elemental or critical peripherals. Concurrently there are also included standard interfaces in order to extend the hypervisor’s functionalities, as portrayed in Figure 2.15. Because of this, VOSYSmonitor provides improved support for fully featured VMs such as a complex modular GPOS like Linux. In fact, this is the characteristic that defines it the most. While LTZVisor takes a lightweight approach with minimal TCB and memory footprint, VOSYSmonitor bets on a more powerful framework capable of providing low overhead in context-switches and boot sequence, hence fulfilling the harmony of complex and exigent mixed-criticality systems. For this reason, VOSYSmonitor serves as a standing ground for introducing extra features to LTZVisor, which could make it support better-equipped OSes. However, in order to keep the hypervisor’s lightweight character, adding these features needs to be done carefully and in order Chapter 2. Background & State of the Art 38 ARM multi-core platform VOSYSmonitor ASIL C Hypervisor (optional) Infotainment OS Rich OS 2 Safety Critical OS Native OSGuest (optional)Non Critical OS Secure World Normal World ASIL C No ASIL No ASIL Figure 2.14: VOSYSmonitor System Overview (adapted from [55]). Structured similarly to LTZVisor, VOSYSmonitor features mixed criticality guests, with a secure real-time VM and full-fledged software on the unprivileged world. PSCI service layer Safety features Inter-world custom layer configuration Drivers Watchdog Interrupt controller UART Platform API EL3 Monitor Layer SMC framework Interrupt framework Secure world service table Secure OS Service Layer (SOSSL) VOSYSmonitor Figure 2.15: VOSYSmonitor Software Architecture (adapted from [55]). VOSYSmonitor applies many software services to improve its ability to support its guests’ functionalities. These services include interactions with the monitor layer, drivers to the platform’s components, and inter-world interfaces. to minimize their memory and performance footprints. Since this thesis focuses on porting the hypervisor as it is, the main focus is to implement it in the simplest ways, thus making it more secure. Chapter 3. Platform and Tools 45 Zynq UltraScale+ Device TRM 25 UG1085 (v1.7) December 22, 2017 www.xilinx.com Chapter 1: Introduction X-Ref Target - Figure 1-1 Figure 1-1: AXI Interconnect Diagram M     Each input to all output ports CCI Coherency And Bypass RPU GIC TCMs                     OCM Switch USB0 w/DMA USB1 w/DMA LPD DMA PS SYSMON eFUSE LPD SLCRs IPI /3'6ODYHV RTC IOP Inbound IOP Outbound OCM Memory 6 DAP Controller $3% $3% S6 CSU Processor PMU Processor $;, Quad-SPI GEM x4 NAND SDIO x2 ,23ZLWK0DVWHUV ,23XQLWV UART x2 SPI x2 CAN x2 I2C x2 ,236ODYHRQO\ S S TBU2 Programmable Logic 2XWVWDQGLQJ5HDG:ULWH%XIIHU'HSWK 6  FPD SLCRs FPD slaves DDR Memory Controller SMMU TCU AIB AIB AIB AIB AIB AIB ''54R6DQG491 ;338 ;038V $30V 6 66  AIB  AIB  APU MPCore DisplayPort FPD DMA TBU3 TBU4 TBU5 TBU0TBU1 CoreSight 6 6 6 '900 0 0 6 6 PCIe SATA AXI Stream $7% GPU PPs $7% AIB $;,7LPHRXW%ORFN $;,,VRODWLRQ%ORFN ADB ADB ADB $;,'RPDLQ%ULGJH TBUx 60087UDQVODWLRQ%XIIHU8QLW )3' /3' ''5 )3' /3' 3/3' AIB IOP Outbound $7% $7% LPD Inbound $7% AIB AIB S SM 128-bit Block RAM (slave) M_AXI_HPM0_LPD S_AXI_LPD S_AXI_HP3_FPD S_AXI_HP2_FPD S_AXI_HP1_FPD S_AXI_HP0_FPD S_AXI_ACP_FPD S_AXI_ACE_FPD S_AXI_HPC0_FPD S_AXI_HPC1_FPD M_AXI_HPM0_FPD M_AXI_HPM1_FPD Non-Coherent Master I/O Coherent Master 2-way Cache Coherent Master $7% $3% AIB AIB AIB AIB GPU cfg [afifs0] [afifs1] [afifs2] [fpd_main] [ocms] [fpd_lpdibs] [lpd_ddr] [usb0s], [usb1s] [rpus0], [rpus1] [rpum0], rpum1] [ocms] LPD Main Switch RPU Switch Full crossbar. Each input to all output ports. Full crossbar. 7RDOORXWSXWSRUWV GPIO x78 SM 64-bit SM 32-bit AIB AIB FPD Main Switch I/O I/O 2-way I/O I/O $GYDQFHG4R65HJXODWRUV 'DWD%XV:LGWK M M AXI Stream RPU $3% QVN X19932-100917 Send FeedbackSend Feedback Figure 3.3: Zynq Ultrascale+MPSoC system interconnect diagram. Due to its heterogeneous and TrustZonebased design, the Ultrascale+MPSoCs provide a robust interconnect arrangement, where most buses pass through hardware modules that verify the data’s authenticity before reaching its target system components. 3.1.2.1.2 Memory Subsystem The memory subsystem of a Zynq Ultrascale+MPSoC device is spread across various controllers for distinct types of memory. It includes local dynamic DDR RAM and OCM, while providing controllers for external NAND and Quad-SPI flash memories, and SD/SDIO/eMMC cards. The board has a DDR interface, the DDRC, which provides either a 32 or 64-bit interface for DDR4, DDR3, DDR3L, and LPDDR3 memories, and a 32-bit interface for LPDDR4. Both the 32-bit and 64-bit interfaces incorporate Error-Correcting Code (ECC) memory support. The controller can achieve data rates of 2400Mb/s in DDR4 operation and can manage a total of 32GB of DRAM [20]. The DDRC accesses the DRAM through a DDR PHY interface and is connected to the rest of the Zynq Ultrascale+MPSoC platform through six AXI data interfaces and one AXI control interface. According to [45] and Figure 3.3, the data ports are organized as follows: Chapter 3. Platform and Tools 46 •Two 128-bit AXI ports connected to the cache coherent interconnect (CCI), which grants access from the APU, RPU, GPU, high-speed peripherals, and from igh-performance ports (HP0 and HP1) located in the PL; •One 64-bit AXI port connected directly to the RPU; •One 128-bit AXI port connected to the DisplayPort and HP2 port from the PL; •One 128-bit AXI port connected to the HP3 and HP4 ports from the PL; •One 128-bit AXI port connected to the DMA and HP2 port from the PL. The OCM is a 256KB RAM block with 64-bit ECC connected via a 128-bit AXI slave interface port [45]. It has a clock running at 600MHz and supports 256-bit read and write accesses by implementing a double-width memory. As Figure 3.3 and Figure 3.2 show, it belongs to the LPD and is closely attached to the RPU, providing low latency accesses from it. The 256KB of RAM are subdivided in four independent 64KB banks, each with an individual power island monitored by the PMU. For external static memory interfaces, the MPSoC supplies controllers for NAND, Quad-SPI, and SD/SDIO/eMMC flash memories. The NAND controller can handle devices with a maximum capacity of 512Gb and can achieve a maximal throughput of 24.3MB/s in asynchronous single data rate mode and 112MB/s in synchronous NV-DDR mode. There are 2 Quad-SPI controllers available. One of them is a legacy controller with the standard linear interface, while the other is a generic controller that provides I/O, DMA, and SPI mode interfacing. Similarly, there is a pair of SD/SDIO/eMMC controllers which have the same features as the Quad-SPI ones, communicating with SD memory cards, SDIO devices, and eMMC cards with up to eight data lines. Xilinx provides a specified controller that applies TrustZone’s world separation into the memory subsystem and manages its accesses. The Xilinx Memory Protection Unit (XMPU) interfaces the interconnect buses that connect each system component with the physical memories present on the board: DDR via the DDRC and OCM (Figure 3.3). The purpose of this unit is to act as a TZASC, assigning memory regions as secure or non-secure and controlling the accesses to those regions, permitting or denying them. The XMPU interfaces the FPD with the DDRC and OCM, while containing six modules connected to the DDRC [45]. Each XMPU module can configure a total of 16 memory regions (numbered from 0 to 15) with personalized start and end addresses, which are 1MB-aligned for the DDR modules and 4KB- aligned for the OCM and FPD modules. The XMPU is capable of configuring those regions as secure or non-secure, permitting write or read operations, and enabling those regions as a whole. Furthermore, it is also possible to completely isolate both worlds by forbidding secure execution to access non-secure memory, contrasting with TrustZone legacy implementation. Each of these regions is assigned to one or more masters that are granted the permission to access them. Chapter 3. Platform and Tools 47 Different XMPU configurations can cause certain memory regions to overlap each other. In these cases, the configuration of memory regions with the higher ID number have priority over the configurations of lower memory regions. 3.1.2.1.3 Peripherals The ZCU102 board contains various general-purpose and high-speed peripheral interfaces distributed through the PS and PL. On the PS, there can be found GEM3 Ethernet, UART, SPI, USB 2.0, GPIO, CAN 2.0A/B, HDMI, and I2C interfaces, all of them belonging to the LPD. As showcased previously in Figure 3.2, these interfaces connect to external devices through a physical layer of 78 MIO pins, which can be assigned in groups to provide the respective physical connection with the external device. Similar to the memory subsystem, the peripheral interfaces also adopt TrustZone’s world division. More specifically, any connected device can be assigned as secure or non-secure, having the same access permissions as secure and non-secure memory. Consequently, there is also a component responsible for managing the accesses and configuration of these devices, the Xilinx Peripheral Protection Unit (XPPU). Similarly to the XMPU, the XPPU attributes a security state and a master mask to an aperture, that can only be accessed by valid masters with the proper TrustZone privilege. Apertures represent peripheral address space in blocks, just as the memory regions managed by the XMPU. In total, up to 400 programmable apertures are supported by ZCU102’s XPPU. There are four possible kinds of apertures distinguished by the size and type of the accessed peripheral: •128 x 32B for inter-processor interrupt (IPI) message buffers; •256 x 64KB for peripheral slave ports; •16 x 1MB for peripheral slave ports; •1 x 512MB for Quad-SPI memory controller; As all of the PS peripheral interfaces are located on the LPD, XPPU has a single instance positioned on the bus between the LPD Inbound and the I/O Peripherals (IOP) Switch (Figure 3.3). 3.1.2.2 Programmable Logic Built over TSMC’s 16nm FinFET+technology, the Zynq Ultrascale+MPSoCs’ PL offers enhanced performance/watt when compared to the Zynq-7000 series. Apart from an increase on the quantity of look-up tables (LUTs), configurable logic blocks (CLBs), flip-flops, and DSP blocks, the Ultrascale+FPGA also contains new high-performance peripheral interfaces, such as 100G Chapter 3. Platform and Tools 48 Ethernet, Interlaken and Gen3/4 PCIe. Additionally, it also introduces UltraRAM, designed as synchronous dual-port high-density memory blocks capable of being cascaded to achieve capacities from 288Kb to 36Mb [20; 45]. However, as an evaluation board, the ZCU102’s PL does not contain all of these elements, lacking PCIe, Interlaken, and Ethernet 100G interfaces and UltraRAM blocks. Nonetheless, the EMIO feature of Zynq-7000 platforms is still available on the ZCU102 board and can thus be used to provide additional configurable interfaces on the board’s PL pins. 3.2 Lightweight TrustZone-assisted Hypervisor This section introduces the Lightweight TrustZone-assisted Hypervisor (LTZVisor), which is the focal point of this thesis. Being built on top of the TrustZone framework, it manipulates ARM’s security extensions to improve the space and time isolation between VMs by design, offloading much of the security effort from the processor. Although it was originally developed on the Xilinx ZC702, Zedboard and ZYBO boards, it is currently being modified to run on other platforms and architectures, as this thesis presents. Additional porting projects include adapting LTZVisor to the i.MX6-Quad platform using ARMv7-A, and to the Musca-A board equipped with a Cortex- M33 processor that supports ARMv8-M. Furthermore, the hypervisor’s response to critical system failures is also currently being improved. 3.2.1 LTZVisor Overview LTZVisor is a hypervisor that exploits ARM TrustZone’s features to better deploy the isolation between guest partitions, assisting virtualization in a security-oriented fashion [16]. As TrustZone separates the processor and hardware resources in two domains — the privileged secure and unprivileged non-secure — there is a layer of security that is provided by design which is employed to reduce effort on the CPU, hence the Lightweight keyword. There are three fundamental principles that LTZVisor abides by: •Minimal Implementation: by relying the most on the security extensions of TrustZone to assist virtualization, some hypervisor mechanisms can be offloaded from software to hardware, reducing the trusted computing base and thus disrupt attacks that threaten the system; •Least Privilege: access to system resources must only be permitted when they are entirely necessary. Thanks to TrustZone’s world partition, non-secure units cannot access secure components, providing some of the intended isolation to the hardware resources, and also to the real-time and general-purpose VMs; Chapter 3. Platform and Tools 49 User mode LTZVisor Apps Apps Normal Apps Non-Secure VM (GPOS) Apps Apps RT Apps Secure VM (RTOS) Supervisor mode Monitor mode ARM TrustZone-enabled SoC Figure 3.4: LTZVisor general architecture. Running in the highest privileged mode, LTZVisor is a bare-metal hypervisor that hosts two isolated guests with distinct levels of criticality. •Asymmetric Scheduling: compromising the timing requirements of a real-time environment with the extra overhead issued by the management of virtualized resources is a demanding effort. Applying an asymmetric scheduling policy ensures that the real-time functions are not misguided or delayed by non-real-time activity. With these principles in mind, LTZVisor was implemented on a traditional dual-OS configuration: secure RTOS and non-secure GPOS. Considering ARM’s latest architectures, the hypervisor runs in monitor mode, which is the most privileged level of execution with full access to system registers and peripherals. The permission to manage those resources is required since LTZVisor has to guarantee inter-guest isolation and abstraction of the hardware platform. Figure 3.4 shows the adopted virtualization architecture. The secure VM runs on the Supervisor mode and has permission to view and access the non-secure domain and its resources. Hence, the secure guest needs to be slightly modified in order to be properly isolated from the non-secure guest and not access its resources. With that slight increase in the guest’s TCB, an OS with a small memory footprint is required. Thus, a RTOS proves to be the ideal solution, taking advantage of the privileged execution of the secure world to comply with its real-time requirements. Similarly, the non-secure VM also runs on the Supervisor mode, however with unprivileged non-secure permissions. As the non-secure domain is completely isolated from outer components — like the secure world that includes the hypervisor running on monitor mode — it is an adequate environment to host a complex guest like a GPOS. Unable to intrude on more privileged resources, Chapter 3. Platform and Tools 50 a GPOS can employ many applications, ranging from internet-based services to HMIs, without tampering with confidential and privileged system property. 3.2.2 Virtual CPU As already mentioned in section 2.1.3.4 (ARM TrustZone), a CPU encompassing TrustZone technology is segmented in two execution domains: the privileged secure world, and the unprivileged non-secure world. Therefore, almost all system registers are banked to each domain. The only registers that avoid this mechanism are the core registers and the PSRs in ARMv7-A, implying they need to be handled on every world-switch and when first setting up the non-secure guest. Consequently, these registers belong to the virtual machine control block (VMCB), which contains the registers whose state needs to be preserved and restored when switching between worlds. Each VM contains a corresponding VMCB, which is represented in Figure 3.5. The secure VMCB holds a total of 16 registers, while the non-secure includes 25. All of the saved/restored registers are general-purpose registers, since most of the system control-registers are banked between the secure and non-secure worlds in ARMv7-A. However, some guests are required to boot with certain architectural configurations that can only be enabled using those registers. Hence, LTZVisor needs to take those configurations into account and apply them before the guest starts executing. Due to the banking of system registers, this set up only needs to be done once, since Secure VMCB R0 R1 R2 . . . R11 R12 SP_sys LR_sys SPSR_sys Non-Secure VMCB R0 R1 R2 . . . R11 R12 SP_svc SP_sys LR_svc SPSR_svc LR_sys SPSR_sys SP_abt SP_usr LR_abt SPSR_abt LR_usr SPSR_usr Figure 3.5: VMCBs of LTZVisor’s guest VMs. Due to the banking of system registers, only the general-purpose core (R0-R12) and special registers (SP, LR, and SPSR) need to reside in the guest’s VMCB. The non-secure VMCB encompasses the states of three additional processor modes to hold more details about the full-fledged and intricate environment of the hosted GPOS. Chapter 3. Platform and Tools 51 the configurations of each guest will be automatically loaded when switching between the secure and non-secure worlds. 3.2.3 Scheduler Each OS has its own scheduling policies involving tasks or processes. However, when they are hosted by a hypervisor, the CPU must deal with the scheduling of its guests on top of their own inner scheduling mechanisms. To solve this matter, LTZVisor adopts an asymmetric scheduling policy, which is demonstrated in Figure 3.6. The non-secure guest only runs when the secure OS enters idle execution. On the other hand, the non-secure VM is preempted by the secure guest when the latter is recovering from its idle activity. Since the secure OS is usually more critical than the non-secure, it has a higher scheduling priority and is thus able to interrupt non-secure execution when resuming itself. In fact, the whole asymmetric scheduling policy uses the secure guest as its main agent while LTZVisor behaves passively. Still, LTZVisor keeps its high privilege status over the secure VM, managing system resources and monitoring the world switches when necessary. 3.2.4 Memory Partition As a virtualization solution, LTZVisor relies on the MMU to achieve different stages of memory partition, one for the virtualized guests and another for the hypervisor. It must be included on a SMC ERET Secure Guest S –EL1 S –EL3 LTZVisor (SMC Handler) NS –EL1 Non-Secure Guest FIQ ERET Non-Secure Guest NS –EL1 S –EL3 LTZVisor (Context Switch) S –EL1 Secure Guest (FIQ Handler) Figure 3.6: World-Switch scenarios of LTZVisor’s asymmetric scheduling policy. As the secure guest has higher criticality (and thus priority of execution) than the non-secure guest, its tick is the trigger of context-switching. Whenever it occurs via a FIQ interrupt, the secure guest is scheduled passing through the hypervisor. Once it enters an idle state, a SMC is issued, hinting LTZVisor to schedule the non-secure guest. Chapter 3. Platform and Tools 52 platform containing a MMU that supports 2-level address translation, which maps guest-virtual to guest-physical addresses at one stage and guest-physical to host-physical at another. This MMU feature allows LTZVisor to host unmodified OSes. Therefore, the hypervisor reserves a memory region for each guest, partitioning the memory subsystem in secure and non-secure regions which are used by the secure and non-secure VMs respectively as if they were directly accessing it. This memory segregation is possible in a device supporting TrustZone thanks to the TZASC, which is the controller responsible for assigning memory regions as secure or non-secure. Traditionally, LTZVisor employs the memory subdivisions showcased in Figure 3.7. It reserves the first 960MB of memory to the non-secure GPOS and 64MB to the secure RTOS and the hypervisor itself. This is the default arrangement for a device with 1GB of DDR3 memory, such as the original development platform ZC702 [16]. However, it can be altered in a way that adapts to the available memory capacity, as it happens to the ZEDBOARD and ZYBO boards which contain only 512MB of DDR3 memory. In these devices, the secure memory size remains the same as on larger platforms — since it is the minimal granularity of the TZASC in the Zynq-7000 boards — and the non-secure section is reduced to 448MB. The secure and non-secure memory regions must be selected and configured at design time so that LTZVisor can assign them during the boot process. Non-Secure Secure 0x3BFF_FFFF 0x3FFF_FFFF 0x0000_0000 64MB 960MB 0x3C00_0000 Figure 3.7: LTZVisor memory arrangement. Most of the used addresses are occupied by the non-secure GPOS, which is placed on the first regions of memory. The following region is occupied by the secure guest and LTZVisor, which don’t need as much address space because of their low memory footprint relative to the rich GPOS. Chapter 3. Platform and Tools 53 3.2.5 Device Partition Similarly to the memory subsystem, LTZVisor also employs world isolation to the platform’s peripheral devices. Using the TZPC, it is possible to assign each available peripheral as secure or non-secure, which are then used solely by the guest OS of the corresponding world. This configuration prohibits the simultaneous usage of the same device by both VMs. The peripherals used by each guest are selected at design time and configured during LTZVisor’s boot process, similarly to memory partitioning. The devices that can be involved in this partition are peripherals, external interfaces and interconnect buses. 3.2.6 Interrupt Management LTZVisor’s interrupt system is supported by ARM’s GIC, which applies the features of Trust- Zone into interrupt management on TrustZone-enabled SoCs. Apart from configuring interrupts as secure and non-secure, the GIC can also designate whether an interrupt signal is represented through an IRQ or a FIQ request. A typical model is to entrust FIQs as secure interrupts and IRQs as non-secure, which is the model adopted by LTZVisor. Therefore, FIQs represent secure interrupts, which are to be handled by the secure RTOS, and IRQs non-secure interrupts, managed by the non-secure GPOS. This setting brings out the best of both interrupt mechanisms since the FIQ higher performance complies with the timing requirements of a RTOS. Consequently, there are four possible interrupt handling scenarios. When a secure interrupt (FIQ) is taken during privileged execution, it is directly handled by the secure VM, without passing through the hypervisor. The same occurs when a non-secure interrupt (IRQ) is triggered during the non-secure VM’s execution. However, if a secure interrupt (FIQ) arises while the non-secure VM is running, execution changes to the secure world and the interrupt is handled by the hypervisor, which reroutes it directly to the RTOS. On the other hand, IRQs which occur during secure execution are put on hold, and are only handled when the RTOS enters idle activity and gives the execution to the GPOS. These scenarios enforce the higher privilege of secure interrupts over non-secure requests, holding true to the fundamentals of TrustZone. 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 In order to properly port LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 board, it was required to understand the differences between the native platform and the ZCU102 board. Since the discrepancies between both the ARMv7-A and ARMv8-A architectures have been specified, as well as the differences between both platforms, it is now possible to properly apply them under the context of LTZVisor. This chapter describes the implementation process of porting LTZVisor to the ZCU102 board, indicating the modifications done to set up the platform and prepare LTZVisor to run on ARMv8-A’s 64-bit environment. 4.1 Overview The process adopted for porting LTZVisor to a new platform can be subdivided into four phases. Initially, the board was configured to run a single core bare-metal application on its APU, enabling only essential peripherals like the UART for communication and a Triple Timer Counter (TTC) timer to provide the secure guest scheduling tick. Afterwards, LTZVisor’s hardware interfaces were complemented with support for the ZCU102, including the TTC timers and UART peripherals, but also other core components such as the GIC, XMPU, and XPPU. Once LTZVisor has been fully equipped with the required interfaces, the following phase focused on adapting its core mechanics to the ARMv8-A architecture, maintaining the hypervisor’s original functionalities whenever possible. At last, the guest VMs were included, starting with simple bare-metal guests on each world and adding the RTOS and GPOS one at a time to identify necessary privileged configurations (which are usually done by bootloaders) for each OS. The following sections will describe these steps, indicating the main challenges faced during this process as well as the methodology adopted to approach and solve them. 54 Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 61 these two sections on LTZVisor’s linker script for the ZCU102 board, along with the endianness and architecture specifications. 4.3.3 Exception Levels When booting, LTZVisor starts running in monitor mode, which is the most privileged level of execution. In ARMv7-A, this mode is present in PL1, but on ARMv8-A it is detached from Level 1 privilege and is placed on its own privileged level, EL3. Figure 4.3 depicts the distribution of the hypervisor and the two VMs across ARMv8-A’s exception levels. LTZVisor remains on the most privileged level of execution, while the guest OSes execute on EL1 as they supervise their own applications running in EL0. The hypervisor level of privilege, EL2, is not taken into account in this porting, as EL3 surpasses it on system permissions and using it would deviate from LTZVisor’s original implementation. Throughout the porting process, EL2 didn’t ascertain itself as a necessary element, although it was observed that it could be useful in future upgrades of the hypervisor, as mentioned later in Section 6.1 (Future Work). Due to the dismissal of processor modes, exception handling is treated differently on ARMv8- A. When an exception occurs, it is handled on the current EL or on an EL with higher privilege. The exceptional case is when occurring in EL0, where it is always handled on any of the other ELs. This means that a maximum of three vector tables can exist simultaneously, one for EL1, EL2, and EL3. As verified in Section 2.1.3.2.4 (Exception Handling), each vector table has 16 entries, where each entry has an offset of 32 instructions from each other. This results in a single vector table occupying 16 ∗32 ∗4 = 2048 bytes of memory, much more than the size of an ARMv7-A vector table, which has 8 entries of a single instruction each, featuring 8∗4 = 32 bytes. However, each entry can hold more code, reducing the necessity for the exception handling routines to occupy sporadic memory addresses. As the aforementioned Table 2.4 indicates, the exception handling scenarios in ARMv7-A match most of the processor modes, suggesting the treatment of an exception is executed at OUTPUT_FORMAT("elf64 -littleaarch64", "elf64 -littleaarch64", "elf64 - littleaarch64") OUTPUT_ARCH("aarch64") ENTRY(_reset_handler) MEMORY { DDR_NS (rwx) : ORIGIN = 0x00000000 , LENGTH = 0x1C000000 DDR_S (rwx) : ORIGIN = 0x1C000000 , LENGTH = 0x04000000 } Listing 4.5: LTZVisor’s memory section configuration in linker script. Along with the endianness and architecture specification, the memory sections must also be specified. Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 62 the respective processor mode. This no longer happens in ARMv8-A since the processor modes are not present anymore, and thus different exception scenarios are available, as shown in Table 2.6. Since the original LTZVisor doesn’t have a full-fledged exception handling mechanism, it was simpler to adapt it into the ARMv8-A model. The legacy LTZVisor only provides specialized handling of synchronous aborts — namely the SMC system call that can trigger a context-switch from the secure to the non-secure guest —, and of FIQ interrupts — which can generate a world-switch from the non-secure to the secure guest. Hence, the first case was easily embedded unto the synchronous aborts from lower ELs exception, as it is the entry point of a SMC instruction issued from EL1 or EL0. The context-switch via a FIQ interrupt is performed whenever the non-secure guest is running, hence it is attributed to the AArch64 from lower ELs case. The remaining exception entries either block execution in an endless loop or immediately issue an eret instruction to resume execution, depending on the exception’s criticality. In ARMv7-A, each processor mode responsible for exception handling has its own stack so that it was possible to save and restore exception information. Without the processor modes in Zynq Ultrascale+ MPSoC EL0 (user) EL1 (supervisor) EL2 (hypervisor) EL3 (monitor) Non Secure Secure Cortex-A53 SoC LTZVisor Apps Apps Normal Apps Non-Secure VM (GPOS) Unused Apps Apps RT Apps Secure VM (RTOS) Figure 4.3: LTZVisor’s architecture on a Zynq Ultrascale+MPSoC platform. The hypervisor remains on the Monitor mode, which is now isolated from Level 1 privilege of execution. The VMs are also kept at EL1 and EL0, while EL2’s virtual extensions are not used. Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 63 ARMv8-A, these seven stacks cease to exist, being replaced by four stacks, one for each ELs. Similarly, there are some registers that are banked to each processor mode in ARMv7-A (SPs, LRs, and SPSRs). However, these registers are not banked in ARMv8-A according to each EL, creating the need to manage these registers when switching between ELs. Instead, these registers have copies of themselves in each EL, as mentioned previously in Section 2.1.3.2.2 (Registers). Therefore, it is possible for higher ELs to access the copies of these registers from lower ELs, facilitating configuration of the less privileged ELs from the hypervisor. Still, the same non-banking problem occurs relatively to the TrustZone security states. On ARMv7-A, some registers had banked copies for each world, allowing for world-switches supported by the hardware itself. On ARMv8-A though, the banked registers have been dismissed, increasing the number of registers required to be saved and restored during context-switching between guests. Thus, it was required to increase the VMCB of each guest. A thorough analysis of which registers need to be maintained to preserve each guest’s state was done. This resulted in the VMCBs used for the ARMv8-A LTZVisor’s guests being composed of the following registers: •The 31 general-purpose registers, which are more than double the number of ARMv7-A’s 13 general-purpose registers; •The SPSRs of EL1 and EL3, which indicate the execution state of the guest and code executing at EL0; Secure VMCB Non-Secure VMCB R0 R1 R2 R3 . . . R27 R28 R29 R30 ELR_EL1 ELR_EL3 SP_EL0 SP_EL1 SPSEL SPSR_EL1 SPSR_EL3 SCTLR_EL1 SCTLR_EL3 CPACR_EL1 SCR_EL3 VBAR_EL1 R0 R1 R2 R3 . . . R27 R28 R29 R30 ELR_EL1 ELR_EL3 SP_EL0 SP_EL1 SPSEL SPSR_EL1 SPSR_EL3 SCTLR_EL1 SCTLR_EL3 CPACR_EL1 SCR_EL3 VBAR_EL1 Figure 4.4: LTZVisor’s architecture on a Zynq Ultrascale+MPSoC platform. The hypervisor remains on the Monitor mode, which is now isolated from Level 1 privilege of execution. The VMs are also kept at EL1 and EL0, while EL2’s virtual extensions are not used. Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 64 •The ELRs of EL1 and EL3, that are used to store the return addresses of the guest and of its own exception handling mechanisms; •The SCTLRs of EL1 and EL3, which hold cache, MMU and TLB configurations; •The SCR_EL3 register, that appoints to which EL exceptions are trapped; •The VBAR_EL1 register, which holds the address of the guest’s vector table; •The SPSel register and the stack pointers SP1 and SP0. The VMCB in ARMv8-A is shown in Figure 4.4, which amounts to a total of 45 registers on both the secure and non-secure states. This number can be compared to the 27 registers that belong to the VMCB in ARMv7-A, as specified in Figure 3.5. However, in ARMv7-A it is necessary to cycle through some processor modes in order to store their registers, which is no longer necessary in ARMv8-A as all registers are accessible from the hypervisor running in EL3. 4.3.4 A32 to A64 As described before in Section 2.1.3.2.2 (Registers), registers have a different naming scheme in ARMv8-A than in previous architectures. Here, the general-purpose registers can be named Xn or Wn if they’re being used as their 64-bit or 32-bit variants respectively. Since this dissertation’s main goal is to implement 64-bit support in LTZVisor, and since some instructions only accept general-purpose registers in their 64-bit states, most register accesses involved their 64-bit counterparts (X0-X31). The 32-bit variants (W0-W31) were only used when accessing 32-bit wide memory-mapped registers, since accessing them through the Xn is not allowed by the compiler. Listing 4.6 indicates one example where the Wn were used to access GIC registers to acknowledge a FIQ interrupt. In ARMv7-A, system control registers were accessed through the CP15 coprocessors, which no longer exist in ARMv8-A. Instead, ARMv8-A provides the MRS and MSR instructions to access system control registers. Since these instructions are very similar to the MRC and MCR instructions in ARMv7-A, it was easy to identify and replace such operations. Nonetheless, accessing the CP15 coprocessors does not always result in an access to a system control register in ARMv7-A, as they 1/* ACK FIQ */ 2mov x0, #MPIC_BASE 3ldr w1,[x0,#_ASM_GIC_INT_ID] 4ldr w2,=interrupt 5str x1,[x2] 6ldr w0,[x0,#0x0C] Listing 4.6: Usage of Wn when acknowleging FIQs. Since acknowledging an interrupt requires the write operation to a 32-bit GIC register, the general-purpose register used in that write has to be represented by its 32-bit variant. Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 65 were also used to perform cache, MMU and TLB maintenance operations. These operations can be performed in ARMv8-A via the DC,IC, and TLBI instructions. In order to properly replace the CP15 accesses with the respective instructions, the CP15 operations were consulted at [63] and modified to the related ARMv8-A instructions described in [37]. Some A64 instructions remained the same from A32, mainly the data processing operations. On most of these cases, it was only required to change the general-purpose registers. However, there were cases where some data processing instructions were no longer required. For example, after some stack management operations, the stack pointer was adjusted with subtractions. It was verified that those adjustments were no longer necessary since the SP could already be correctly manipulated through the load/store instructions by using the indexation mechanisms provided by the architecture. Due to the SP having an alignment of 128 bit (16 bytes), the SP handling operations are more constrained in ARMv8-A when compared to the ones in ARMv7-A, which only require a SP with an alignment of 4 bytes. Hence, if the load/store instructions do not align the SP properly, execution will be halted by an exception, avoiding the misuse of these operations. Therefore, in order to reduce the memory footprint and occupy all 16 bytes (128 bits), each load/store operation must involve two 64-bit registers or four 32-bit registers. Depending on the amount and width of the registers to be stored, there are many ways to occupy the 16-bytes. Figure 4.5 presents some approaches for storing values on the stack while maintaining an aligned SP. Thus, the approaches taken into account were: •Approach (b), which stores a 32-bit register, occupying 4 bytes and leaving a gap of 12 bytes; ?? ?? ?? ?? ?? ?? ?? SP 0x????_0018 0x????_0014 0x????_0010 0x????_000C 0x????_0008 0x????_0004 0x????_0000 (a) Initial State ?? ?? ?? ?? ?? w1 ?? SP 0x????_0018 0x????_0014 0x????_0010 0x????_000C 0x????_0008 0x????_0004 0x????_0000 (b) str w1,[sp,#-16]! ?? ?? ?? ?? w3 w2 ?? SP 0x????_0018 0x????_0014 0x????_0010 0x????_000C 0x????_0008 0x????_0004 0x????_0000 (c) stp w2,w3,[sp,#-16]! ?? ?? ?? ?? x1 ?? SP 0x????_0018 0x????_0014 0x????_0010 0x????_000C 0x????_0008 0x????_0004 0x????_0000 (d) str x1,[sp,#-16]! ?? ?? x2 x1 ?? SP 0x????_0018 0x????_0014 0x????_0010 0x????_000C 0x????_0008 0x????_0004 0x????_0000 (e) stp x1,x2,[sp,#-16]! ?? ?? w4 w3 w2 w1 ?? SP 0x????_0018 0x????_0014 0x????_0010 0x????_000C 0x????_0008 0x????_0004 0x????_0000 (f) stp w1,w2,[sp,#-16]! stp w3,w4,[sp,#8] Figure 4.5: Stack management approaches on A64. Similarly to Figure 2.10, it is presented a stack in an initial state (a) that has data from registers stored on it according to the instructions indicated in the respective captions. Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 66 •Approach (c), which stores two 32-bit registers, occupying 8-bytes and leaving an 8-byte long gap; •Approach (d), which stores a 64-bit register, occupying 8-bytes and leaving an 8-byte long gap; •Approach (e), which stores two 64-bit registers, occupying all of the 16-bytes; •Approach (f), which stores four 32-bit registers, occupying all the 16-bytes, but requiring a total of two instructions. While analysing all of these approaches, it can be noted that the ones with higher memory efficiency are (e) and (f), which occupy the whole 16 bytes. However, (f) has a performance disadvantage since it requires two load/store pair instructions. This can be a critical factor in LTZVisor, since many memory and stack accesses are done during context-switching, which must be performed as fast as possible. Likewise, it was already mentioned that the 32-bit representation of general-purpose registers is only required when accessing memory space reserved for peripheral configuration. So, and in order to keep consistency throughout LTZVisor’s code, only the approaches which involve 64-bit registers ((d) and (e)) were used. In most occasions, more than one register is stored at a time, allowing for the most efficient method to be used more often. Nonetheless, there were still cases that required a single register to be accessed. Upon further analysis, it was experienced that this approach could be slightly improved if replaced by the instruction stp x1,xzr,[sp#-16]!. The difference between this instruction and approach (d) is that, instead of leaving the last 8-bytes untouched, using this instruction actually clears them. This ended up being the preferable approach for both loading and storing single registers, since write operations on the XZR register are ignored. The most common stack operation on LTZVisor is when loading/storing all 31 general-purpose registers. In ARMv7-A, it can be done in a single load/store multiple instruction (LDM/STM). However, since A64 no longer supports them, the maximum amount of data per instruction is two 64-bit registers via the load/store pair instructions (LDP/STP). Since there is an odd number of general-purpose registers (31), loading/storing them all requires executing 16 LDP/STP instructions, where the last one includes the XZR register to clean the unused 8-bytes. Thus, there is higher overhead in ARMv8-A when performing that operation. Another issue encountered while porting LTZVisor was the differences in conditional execution. Although the conditional flags remain the same in both the ARMv7-A and ARMv8-A architectures, A32 allowed conditional mnemonics to be suffixed to almost any instruction, providing more flexible conditional execution. In ARMv8-A, this feature is only present in conditional branch instructions. To rectify the lack of this feature, A64 includes extra instructions with specialized conditional behaviour. However, these instructions do not provide the same versatility as the Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 67 previous mechanism since they only operate on handling general-purpose registers, unlike the A32 method that could be applied to any instruction. Although A64’s conditional mechanisms are less flexible, they do not interfere much on LTZVisor’s performance, since the hypervisor contains few occurrences of conditional behaviour in its code. The worst case is during cache cleaning operations, where a register (R5/X5) determines whether a cache is to be only invalidated or invalidated and cleaned. These two similar yet distinct operations require separate accesses to the CP15 coprocessors in A32 or different instructions in A64 to be executed. Figure 4.6 depicts the desired execution flow, which is adopted by A32 using the code in Listing 4.7, and by A64 using the code in Listing 4.8. In A32, the whole process is performed in four instructions that are always executed, featuring high determinism of execution. Meanwhile, A64 requires six instructions, including branches to labels, which provide lower determinism. Due to the branches, this operation can take a minimum of four instructions to complete, only adding up to five in case it follows the most prejudicial route. Since this is the worst conditional case in LTZVisor, even if A64 provides less conditional flexibility, it does not R5 == 1 Invalidate Clean & Invalidate R9 = R9 - 1 Start End True False Figure 4.6: LTZVisor’s Conditional Algorithm. Due to the existing differences between both architectures’ conditional mechanics, this simple algorithm is applied differently on each of them. 1cmp r5, #1 2mcreq p15, 0, r11, c7, c6, 2 3mcrne p15, 0, r11, c7, c14 , 2 4subs r9, r9, #1 5 6 Listing 4.7: Conditional Code in A32, using the suffixation of conditional flags on CP15 access instructions. 1cmp x5, #1 2b.ne 3f 3dc isw, x11 4b4f 53:dc cisw, x11 64:subs x9, x9, #1 Listing 4.8: Conditional Code in A64, relying on labels to apply the conditional behaviour represented above. Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 68 degrade the hypervisor’s mechanisms in a significant order of magnitude. At last, the return mechanisms were also adjusted. In A32, an exclusive branch to the LR (”bx lr”) is used, which A64 converts into the ret instruction. This A64 instruction replaces other A32 return methods, such as ”pop pc” and ”mov pc, lr”. 4.3.5 Interrupts One very important element for the hypervisor’s proper functionality is the interrupt system, which is responsible for supplying the tick for the secure guest. The two types of supported interrupt requests (FIQs and IRQs) can be thoroughly configured via the Cortex-A53’s GIC. In Cortex-A9’s GICv1, it was possible to directly establish FIQs or IRQs as secure or non-secure. However, in GICv2, this implementation can only be achieved by configuring the interrupt groups. As indicated in Section 2.1.3.3 (ARM’s GIC Architecture), only group 0 interrupts can cause FIQ requests. This matches with the hypervisor’s intention of having FIQs as privileged requests routed to the secure guest and IRQs as less priority requests handled only by the non-secure guest. Thus, secure interrupts belong to group 0 which offers FIQs, while non-secure interrupts belong to group 1 through IRQs. There are few differences between the GICv1 and GICv2 architectures. Their interfaces contain a lot of similar configuration registers, differing only on the interrupt grouping, GIC virtualization extensions (which are irrelevant since EL2 is not used in this project), and the number of interrupt sources available on the board. A Zynq Ultrascale+MPSoC platform has a total of 187 sources of interrupts, around twice as many as the Zynq-7000’s 96 existing interrupts. This is due to the higher amount of components present on the board and to its heterogeneous nature, which also offers interrupt sources from other processing units. Therefore, the original interrupt vector table was expanded and its contents updated. Since there are more interrupts, it is likely that the same interrupt has distinct IDs on different platforms. This is verified on the TTC interrupts, that on Zynq-7000 platforms occupy the 45th-47th and 69th-71st positions ([58]) while on the ZCU102 board they are numbered 68 through 79 ([45]). LTZVisor by itself only requires one interrupt, which is a TTC tick that schedules the secure guest. All the remaining FIQ and IRQ requests are free to be used by the secure and non-secure guests respectively. Following what is said in Section 3.2.3 (Scheduler), IRQs are only enabled during execution of the non-secure VM, while FIQs are active on both VMs but not while LTZVisor is running. A secure interrupt that occurs during the privileged guest’s execution is directly managed by its interrupt handling mechanisms. When it occurs during non-secure execution, it needs to be routed to the secure VM. This routing process requires a context-switch, so it is done by LTZVisor, which treats the FIQ interrupt in its handler without acknowledging it, allowing that interrupt to remain active until the secure guest handles it. Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 69 4.3.6 Guests LTZVisor acts as a first stage boot loader for its guests, performing maintenance operations and setting up the architecture. Then, it proceeds to platform-specific initializations and to importing the guest VMs. Once all of the virtualization environment is ready, it boots the secure-guest, which performs its own set of initializations. Once it goes into the idle state, a context-switch is performed, booting the non-secure guest. LTZVisor has two methods of including guest VMs: •Including them on the hypervisor source files and compiling them together with it; •Building them externally and converting them to a separate binary file (.bin) which is merged later in the same full binary. The first approach has the VM on the same workspace as the hypervisor, allowing the hypervisor to access some of the VM’s resources easily. This can improve the performance of context-switching and interrupt handling operations since LTZVisor can directly access some of the VM’s elements. The second approach provides a more scalable solution where LTZVisor is not linked to the VM’s code, allowing the inclusion of more complex guests such as a GPOS. However, it requires more effort in configuring the VM, which must be compatible with LTZVisor’s settings, such as the used toolchain, compilation flags, memory partition, and interrupt configuration. The second method was applied to most guests as it requires less effort to include more complex VMs. The first one was only used on the secure bare-metal guest since it was already implemented in the original LTZVisor, and to provide an example of its implementation if eventually needed for future development. In an initial phase, only a secure bare-metal VM was used in order to test LTZVisor’s core mechanisms, making sure that all components were well initialized before the guests started to run. Afterwards, a non-secure VM was included in order to verify the hypervisor’s scheduling process, mainly the context-switching between guests and interrupt handling. With two simultaneous VMs, it was also possible to validate TrustZone-defined configurations by trying to access secure components from the normal world. In accordance with the original LTZVisor, these bare-metal guests would be replaced by guest OSes, namely a RTOS on the secure world and a GPOS on the normal world. In the short development time of this thesis, it was not possible to completely provide support for a functional GPOS to run as the non-secure VM. Instead, two RTOS were used, maintaining the traditional time-sensitive RTOS on the secure world while another one resides on the normal world as the non-critical and non-secure VM. This configuration still emulates a mixed-criticality system, running both hard and soft real-time guests concurrently. The next sections will go through the required changes when implementing each of these VMs, starting with bare-metal secure and non-secure VMs, and then going through the FreeRTOS. Additionally, the steps done towards Chapter 4. Porting of LTZVisor to the Zynq Ultrascale+MPSoC ZCU102 70 attempting to support an Embedded Linux as the non-secure VM are also enumerated, providing some guidelines for LTZVisor’s future development. 4.3.6.1 Bare-Metal VMs The bare-metal guests consist of custom software with minimal initializations, used with the purpose of validating the hypervisor’s functionalities before adopting full-fledged guest OSes. Furthermore, they are also employed to prove that any application-specific software can be a guest in LTZVisor. In this case, both bare-metal VMs confine simple functionalities since their main goal is to verify the core mechanics of LTZVisor before integrating the guest OSes. Both of the adopted bare-metal guests are 64-bit VMs. The secure bare-metal guest consists of a printing loop, where it prints a message and then issues a SMC for LTZVisor to schedule the non-secure guest. Once the SMC is issued, the secure guest will resume its execution just as its system tick triggers, which is represented by a secure FIQ interrupt. Therefore, the bare-metal VM is responsible for initializing its own tick by configuring the selected TTC timer and the respective interrupt. The UART port used to send the message is not configured by this guest as it is the same port as LTZVisor (UART1), which is initialized by the hypervisor beforehand. As already mentioned, the SMC is issued when the secure guest has nothing else to do until the next tick. Hence, the SMC is issued immediately after the message has been printed. The non-secure bare-metal guest does not diverge much from the secure VM’s flow. It also starts by performing trivial initializations and then enters a loop which prints a message at a certain frequency. The initializations are written in assembly code as they focus solely on setting up the guest’s stack and exception vector table. It was also created a stub IRQ handler, meant to validate the non-secure guest’s IRQ handling mechanisms by providing essential operations, such as acknowledging and clearing the taken interrupts. When both of these guests were running simultaneously, many aspects of LTZVisor’s functionalities were validated. It was possible to confirm which registers must be included in the VMCB to guarantee each guest’s data is not compromised or lost in context-switching. It was also possible to verify if the interrupt masking was done properly throughout each guest’s execution. Both FIQ and IRQ interrupts must be disabled while the hypervisor is executing. Meanwhile, the secure guest may only handle FIQs, while the non-secure guest should only handle IRQs, although it has both FIQs and IRQs enabled. When a FIQ interrupt is triggered while the non-secure guest is running, it will be handled by LTZVisor. Enabling or disabling interrupts is done by modifying the DAIF flags located on PSTATE and the SPSRs. Chapter 5. Evaluation and Discussion 77 Table 5.1: Memory footprints of LTZVisor and variants of FreeRTOS (in bytes). LTZVisor presents a size of almost 15KB, much less than any of the instances of FreeRTOS which round 203KB. This OS was measured natively running in EL3 (FreeRTOS IRQ), with its tick represented by a FIQ request instead of IRQ (FreeRTOS FIQ) and in its virtualized form that runs in secure EL1 (vFreeRTOS (FIQ)). Software Memory Footprint .text .data .bss Total LTZVisor 7068 0 8200 15268 FreeRTOS IRQ (v9.0.1) 41884 2360 21520 65764 FreeRTOS FIQ (v9.0.1) 41884 2360 21520 65764 vFreeRTOS FIQ (v9.0.1) 41588 2360 21520 65468 the total memory allocated to the hypervisor and its guests (512MB), and 0,02% of the secure memory region (64MB), as shown in Figure 4.1. This is a sliver of the 512MB chosen as the worst-case scenario for the memory partitioning in LTZVisor, meaning that the hypervisor will have no problems in being integrated on every 64-bit platform. In fact, even if the minimal memory partitioning size (1MB for DDR memory) is taken as reference, the hypervisor core mechanics only occupy 1,456%, leaving more than enough room for a plethora of support for additional platforms, components, guests, and extensions. The FreeRTOS has a much larger footprint, although it is enough to fit the 63MB allocated to it, occupying around 0,099% in its virtualized instance. What is most relevant in this measurement is not the total size of the OS, but the differences between each of the instances’ memory footprints. The non-virtualized instances are launched in EL3, while the virtualized FreeRTOS boots in EL1. Meanwhile, only the first instance uses IRQs to represent its interrupts, including system tick, while the others employ FIQs to do so. Briefly, these instances will be respectively named IRQ, FIQ, and vFIQ for convenience. Therefore, from the IRQ to the FIQ instances it can be noted no change in memory footprint. This is due to the absolute replacement of the interrupt handling mechanisms from IRQ to FIQ requests, without adding or removing any extra code or data. On the other hand, from the FIQ instance to the vFIQ there is a slight reduction of 296 bytes, around 0,45% of the native instance’s size. This reduction is caused by the higher quantity of registers to configure and manage while running in EL3. When booting in its virtualized instance in EL1, the FreeRTOS has less maintenance to perform to convey the required functionalities properly. 5.1.2 Performance Overhead The performance overhead is calculated using two different benchmarks for two separate scenarios. One of them is to evaluate LTZVisor’s overhead in context-switching (measured using the Performance Monitoring Unit), and the other is to assess the overhead of different instances of the FreeRTOS while performing distinct tasks (measured using Thread-Metric benchmarks). The first scenario was chosen since it will indicate if LTZVisor’s guest handling mechanisms are Chapter 5. Evaluation and Discussion 78 fast enough to not interfere with the guests’ operability, especially the secure guest’s real-time constraints. The second scenario was employed to verify the performance variations of distinct instances of the included FreeRTOS, which are the same as the ones used on the memory footprint tests. Both of these tests were each performed 1000 times, and the singular values indicated below portray the average of all the carried out measurements. To gauge LTZVisor’s performance during its context-switching operations, I resorted to the Performance Monitoring Unit. This component counts the occurrence of processor or memory system events like interrupts, memory reads/writes, taken branches, caches hits/misses, between others. In this case, it is gauged the number of processor cycles during each operation. The results are shown in Table 5.2, which portrays the performance overhead in six operations: 1. (1) SMC handling. This operation is the first to be executed once the secure guest enters idle execution and gives up its execution, starting the world-switch to the non-secure guest. In here, LTZVisor verifies if the synchronous exception taken is a SMC and if that SMC contains the hint to perform the context-switch; 2. (2) Save secure guest’s context. Once the SMC has been recognized, the contextswitch itself starts by saving the secure guest’s context, storing its VMCB in memory; 3. (3) Restore non-secure guest’s context. Once the secure guest’s context is properly conserved, the registers are actualized with the non-secure guest’s VMCB. After this operation, the non-secure guest is executed until the secure guest tick occurs and signals another world-switch to the secure guest. The time when the non-secure guest is executing is not taken into account in these measurements since its execution is not constrained by real-time requirements; Table 5.2: Performance overhead of LTZVisor’s context-switching. The performance monitoring unit was used to measure the amount of cycles each of the shown operations took to complete, where xis the average and s the standard deviation. Then, taking into account the processor clock of 1,2GHz, the time each of these operations last is calculated. World Switch Operation Performance Time xs @1,2GHz Switch to NS world (1) SMC Handling 405 59,0 337ns (2) Save S guest context 921 80,5 767ns (3) Restore NS guest context 3523 150,6 2936ns Switch to S world (4) Save NS guest context 635 74,3 529ns (5) Restores S guest context 4259 154,5 3549ns RTOS Scheduler (6) Asymmetric Policy 1876 82,0 1563ns Chapter 5. Evaluation and Discussion 79 4. (4) Save non-secure guest’s context. Once the FIQ interrupt representing the secure guest’s tick is acknowledged, LTZVisor starts the world-switch to the secure world by saving the non-secure guest’s state into memory; 5. (5) Restore secure guest’s context. As the evident follower, the secure guest’s context is restored to prepare its execution; 6. (6) RTOS scheduling. This operation mentions the time the secure guest takes to resume execution, verify if it has any pending tasks to run, and enter idle activity, re-signalling LTZVisor to restart the non-secure guest. It is being measured since the RTOS tasks are not immediately handled as it resumes. Any real-time response to an interrupt is only executed once the RTOS scheduler finishes its scheduling process. In a practical scenario, the idle task should not be taken into account in this measurement, as the interrupt service routine is meant to execute instead. However, due to the minimal overhead of the idle task, it can be included to give an estimate of the RTOS’ interrupt handling duration. Immediately looking at the results, it can be verified that all operations are faster than the RTOS’ scheduling except for operations (3) and (5), which correspond to restoring the guests’ VMCBs from memory. In fact, it is noted that these operations take much longer than the save counterparts, which perform almost the same number of instructions, differing in the use of load and store instructions for restoring and saving the guests’ contexts respectively. In an attempt to justify this contrast, a secondary test was made to evaluate the performance of solely store and load instructions. It was confirmed that load operations take around double the time to be performed than store operations. Further experiments to find the source of this behaviour were not done since it would involve dwelling deeper into the memory controller design and the board’s data transfer mechanisms in the micro-architectural level, which were left for future work. Due to this behaviour, the context-switches take an average of 4849 cycles when entering the non-secure world ((1) + (2) + (3)) and 4894 cycles when entering the secure ((4) + (5)), which translate to around 4µs. Jumping to the evaluation of the FreeRTOS, the same instances as the memory footprint analysis were used — native FreeRTOS using IRQs (IRQ), native FreeRTOS using FIQs (FIQ), and virtualized FreeRTOS using FIQs (vFIQ). This time, the Thread-Metric benchmarks were used, which contain a bunch of specific applications that evaluate individual properties of a RTOS. These applications have periodic behaviours, repeating themselves many times. The number of times each application occurs is the measure taken to evaluate the performance of the RTOS (thus the higher the value, the higher the performance). In this case, the benchmarks employed were: •Cooperative Scheduling (CS), where five threads with the same priority are executed with a round-robin scheduling policy; Chapter 5. Evaluation and Discussion 80 0 10000000 20000000 30000000 40000000 50000000 60000000 70000000 80000000 90000000 CS PS IP PIP SP MP MA Number of Occurrences Secure RTOS Absolute Performance Measures using Thread-Metric Native (IRQ) Native (FIQ) Virtualized (vFIQ) Figure 5.1: Secure RTOS absolute performance measures using Thread-Metric. Different types of software were tested, where each of them was repeated the measured amount of times during a constant interval of 30 seconds. •Preemptive Scheduling (PS), where five threads with distinct priorities are executed in an ascending scheduling policy, as each thread resumes the subsequent higher-priority thread starting with the lowest-priority one; •Interrupt Processing (IP), where a single thread causes an interrupt that gives a semaphore which is taken by the running thread; •Preemptive Interrupt Processing (PIP), where two threads with distinct priorities are executed. The lowest-priority thread triggers an interrupt that gives a semaphore which is taken by the highest-priority thread; •Synchronization Processing (SP), where a single thread gives a semaphore that is immediately taken by the same thread; •Message Processing (MP), where a single thread sends a 16-byte message to a queue and then retrieves that same message; •Memory Allocation (MA), where a single thread allocates 128-bytes of memory and immediately releases them. Each thread or interrupt of these applications contains a counter that is incremented every time it executes. At the end of a predefined real-time duration, the number of occurrences of the whole application is measured. If all counters don’t have the same value at that moment, the test will be considered a failure and show no measurements. Figure 5.1 shows the results of the Thread-Metric benchmarks with the standard duration of 30 seconds between each measure. It can be remarked that the applications’ number of occurrences goes from 13M on the PIP benchmark and reaches 85M on the CS benchmark. However, the absolute quantity of occurrences is not the main focus of this test. The intended purpose is to assess how each instance of the FreeRTOS behaves under the different workloads. Chapter 5. Evaluation and Discussion 81 85593152.25 17334980.35 35178926.8 13457423.2 35671222.45 32056417.35 26543908.8 50 60 70 80 90 100 110 120 130 CS PS IP PIP SP MP MA Relative Performance (%) Secure RTOS Relative Performance Measures using Thread-Metric Native (IRQ) Native (FIQ) Virtualized (vFIQ) Figure 5.2: Secure RTOS relative performance measures using Thread-Metric. Taking the native FreeRTOS using IRQs as the basis for comparison, it can be verified that the (FIQ) and (vFIQ) instances have little variation from the legacy performance. Looking at Figure 5.1 does not provide enough detail on this metric, as most applications have little divergence between the FreeRTOS’ instances. So, a relative chart is provided in Figure 5.2. Certainly, it is possible to verify that the (FIQ) and (vFIQ) instances of FreeRTOS deviate very little, achieving a gap of about 1% in the worst cases. This indicates that the native FreeRTOS’s performance is almost fully maintained when employing FIQ requests instead of IRQs, or even when virtualizing it under the jurisdiction of LTZVisor. It is important to note that the virtualized instance of FreeRTOS was not issuing the SMC on its idle task, running alone and uninterrupted while avoiding being scheduled. 5.1.3 Interrupt Latency Gauging the latency of LTZVisor’s interrupt handling consists of measuring the duration between the moment the interrupt trigger occurs and the moment it starts to get handled. This assessment was only performed using FIQ interrupts that are routed to the secure guest. This is due to the IRQ requests that are routed to the non-secure guest lacking real-time constraints. In order to have minimal development effort, the selected interrupt was the one responsible for the secure guest’s tick, which is triggered by the TTC1 timer 1. The way to measure the interrupt latency was to check the timer’s counter value at the start of the interrupt handler, which would indicate how much cycles have passed since the interrupt was triggered. This test was done in two scenarios. The first provided an optimistic approach, where the tick would be triggered before the secure world issued the SMC, resulting on the fastest interrupt handling, as the interrupt would immediately be routed to the secure guest. The second one was exactly the opposite, triggering the tick interrupt as soon as the secure world issued the SMC and LTZVisor started context-switching to the non-secure world. This approach would indicate the worst possible interrupt latency, as the interrupt would only be recognized once the non-secure Chapter 5. Evaluation and Discussion 82 guest was running (since interrupts are disabled during LTZVisor’s execution) and LTZVisor would perform both context-switches to the non-secure and secure worlds. Once 1000 tests for each scenario have been carried out, it was verified that the interrupt latency ranged from 0,35µs to 5,85µs in the optimistic and pessimistic scenarios respectively. However, it is important to note that the pessimist case is a very sporadic event that has a very unlikely chance to occur, while the optimistic approach is a much likelier occurrence. Thus, the real interrupt latency is more convergent towards the optimistic approach than the pessimistic one. Nonetheless, it is important to know the worst case scenario and even design the FreeRTOS around it, removing the possibility of a longer than intended interrupt handling jeopardizing the system’s integrity. 5.2 Comparison with the 32-bit LTZVisor One of the goals of this dissertation was to guarantee the 64-bit LTZVisor maintained — or, if possible, improved — the legacy hypervisor’s core structure while fulfilling its design metrics. This section focuses on comparing the evaluations of the legacy LTZVisor and of the one developed in this dissertation, analysing the improvements, the features that maintained and the aspects that worsened. 5.2.1 Memory Footprint The comparison between both LTZVisors’ memory footprint can be seen in Figure 5.3. It can immediately be noted that the ARMv8 versions are much heavier than the ones supporting ARMv7. Taking each case into account, LTZVisor’s increase in memory footprint occurs due to the expansion of many architectural features. In fact, ARMv8 provides a higher quantity of registers, both for general-purpose use and for system configuration and control operations. As LTZVisor has the responsibility of acting as a bootloader to its guests, the increase in architectural features also implies the extension of system initializations. Consequently, ARMv8-A’s exception vector tables are capable of encompassing 64 more instructions than the ones available in ARMv7. Last but not least, the lack of banked system registers leads to an increase on the guests’ VMCBs, resulting on the allocation of more static memory to store them and on longer routines that perform the world-switch operations, which are also stored in memory. Thus, it is not just the 64-bit data formats that increase the memory footprint of an application when designed for ARMv8-A instead of for ARMv7-A. Focusing on the instances of FreeRTOS, the increase in memory footprints from the 32-bit architecture to the 64-bit is not solely caused by the change in data formats. To begin with, both versions of the RTOS are different (the legacy LTZVisor employed the FreeRTOS v7.0.2 while the Chapter 5. Evaluation and Discussion 83 2.88 18.882 18.898 18.918 15.268 65.764 65.764 65.468 0 10 20 30 40 50 60 70 80 LTZVisor FreeRTOS (IRQ) FreeRTOS (FIQ) vFreeRTOS (vFIQ) KBytes Memory Footprints of the ARMv7 and ARMv8 LTZVisors ARMv7-A ARMv8-A Figure 5.3: Memory footprints of the ARMv7 and ARMv8 LTZVisors and FreeRTOS. LTZVisor memory footprint increases by about 562%, while the 64-bit FreeRTOSes occupy 1000% more than their 32-bit versions. 64-bit LTZVisor hosts the FreeRTOS v9.0.1). This aspect is an important factor to take into account, as it is very likely that the whole OS had to be restructured in order to meet with state-of-the- art solutions, such as more advanced hardware technologies like 64-bit architectures. However, it is possible to go further and refer another disparity between both the employed RTOSes. While the FreeRTOS used in the original LTZVisor was obtained directly from the FreeRTOS’ source code, the ARMv8-A version was provided by XSDK. Since this framework is meant to provide software support for Xilinx’ devices, it is safe to assume that the provided FreeRTOS is designed with the appropriate interfaces to be executed on the target platform — in this case, the Zynq Ultrascale+MPSoC ZCU102 board. In fact, a BSP project was automatically generated as the OS was created. Therefore, the FreeRTOS employed on this thesis contained support for most of the board’s peripherals and components, which would certainly enlarge its memory footprint over a non-dedicated RTOS. Conclusively, the differences in memory footprint between each version of the FreeRTOS should not be directly compared, as both OSes have distinct features and sources. 5.2.2 Performance Overhead LTZVisor’s context-switching is a crucial operation that needs to be toned down as much as possible so that the secure guest handles its interrupts with haste, fulfilling the imposed real-time deadlines. Figure 5.4 indicates the evolution of the hypervisor’s context-switching concerning its duration. As indicated in Section 5.1.2, the ARMv8 LTZVisor suffers from huge overhead when restoring the guests’ VMCB from memory, which is a fact that needs to be further investigated in Chapter 5. Evaluation and Discussion 84 571 422 949 982 243 405 921 3523 635 4259 0 500 1000 1500 2000 2500 3000 3500 4000 4500 SMC Handling Save Secure Restore Non-Secure Save Non-Secure Restore Secure Processor Cycles Performance Overhead in ARMv7 and ARMv8 LTZVisors' Context-Switching ARMv7-A ARMv8-A Figure 5.4: Performance overhead in ARMv7 and ARMv8 LTZVisors’ context-switching. Due to a larger VMCB, the 64-bit LTZVisor takes longer to switch between worlds, especially during restore operations. On the other hand, it can be noted an improvement in the FreeRTOS’ scheduling mechanisms. the future. If the extraordinary lengthy restore operations are not taken into account, it can actually be noted that the 64-bit LTZVisor fares well against the original, which comes as a surprise due to the overall larger VMCBs in ARMv8-A. Dwelling further, to save the secure guest’s context there is an increase of 118,25%, which can be seen as a slight improvement taking into account the 43/16 = 187,5% augment of the secure guest’s VMCB from the original to the 64-bit LTZVisor. On the other hand, when saving the non-secure guest’s context, there is a decrease in overhead of 35,34%, which is surprising due to the VMCB’s expansion of 72%. This upswing against the expected results is most likely due to the sub-architectural features of the employed CPUs, which could also be the source of the decelerated restore process. The decline in the RTOS’ scheduling duration to 24,87% of the legacy implementation partly balances out the lengthy context-switch operation. Cumulatively, the world-switch’s duration in both the original ARMv7 hypervisor and the developed ARMv8 LTZVisor are shown in Table 5.3. The hypervisor’s context-switching activity has generally decreased, only manifesting positive results when the RTOS’ overhead is also considered. Without the RTOS, world-switching in ARMv8 has thrice the performance overhead than Table 5.3: Cumulative comparison of both LTZVisors’ context-switching durations. Due to the Cortex-A53 CPU having a faster clock (1,2GHz) than the Cortex-A9 (666MHz), the higher overhead of the ARMv8 design has less impact in the time domain. ARMv7 ARMv8 Percentage (%) with RTOS Cycles 10709 11619 108,5% Time (ns) 16080 9681 60,2% without RTOS Cycles 3167 9743 307,6% Time (ns) 4755 8118 170,7% Chapter 5. Evaluation and Discussion 85 0 1000000 2000000 3000000 4000000 5000000 CS PS IP PIP SP MP MA Number of Occurrences Secure RTOS Absolute Performance Measures in ARMv7 and ARMv8 Native (IRQ) ARMv8-A Native (IRQ) ARMv7-A 10000000 30000000 50000000 70000000 90000000 Figure 5.5: Secure RTOS absolute performance measures in ARMv7 and ARMv8. The ARMv8-A native FreeRTOS can reach about 10x better performances than the ARMv7-A native FreeRTOS. in ARMv7, translating to a 70% increase on the time domain. With the RTOS’ scheduling time taken into account, the ARMv8 LTZVisor actually outperforms the original while context-switching between guests, even with 8,5% more overhead on the CPU. Analysing the performance overhead of the previously gauged RTOS’ scheduler, it is possible to predict that the FreeRTOS version hosted by the 64-bit LTZVisor achieves better results in terms of performance when compared to the version originally adopted by LTZVisor. Figure 5.5 reflects that forecast, showcasing that the native 64-bit FreeRTOS is capable of executing the same application roughly 15 times more than the native 32-bit FreeRTOS. This phenomenon is most likely due to the FreeRTOS’ restructuring and to the platform’s modernized architectural features and components. It can also be verified that each benchmark application weights about the same on either one of the FreeRTOSes, as the ratio between each of them is roughly kept on both versions of the FreeRTOS. Relative to the performance variation between the different instances of the FreeRTOS tested (IRQ, FIQ, and vFIQ), Figure 5.6 shows how the 32-bit and 64-bit FreeRTOSes fared. The newer version of the FreeRTOS provides more deterministic results, as the FIQ and vFIQ instances differ from the native one by a maximal margin of 1,3%. In contrast, the ARMv7 FreeRTOS contains variations that reach relative amounts of 30%. Once again, due to the dissimilarities of both versions of FreeRTOS, pinpointing the exact source of such deterministic behaviours is a delicate matter. Since the FreeRTOS’ implementation does not belong in the research standpoint of this dissertation, I can only conclude that the normalized results come from an improved real-time infra-structure provided by the 64-bit version of FreeRTOS. Furthermore, the platform’s Chapter 5. Evaluation and Discussion 86 S. Pinto, J. Pereira, T. Gomes, A. Tavares, and J. Cabral 4:13 50 60 70 80 90 100 110 120 130 N_IRQ N_FIQ TZ_FIQ N_IRQ N_FIQ TZ_FIQ N_IRQ N_FIQ TZ_FIQ N_IRQ N_FIQ TZ_FIQ N_IRQ N_FIQ TZ_FIQ N_IRQ N_FIQ TZ_FIQ N_IRQ N_FIQ TZ_FIQ CS PS IP IPP SP MP MA Relative Performance (%) Relative Performance (%) 5119573 1155546 1915753 943882 2452514 2309552 1735713 (a) Relative performance 0.9998 0.99985 0.9999 0.99995 1 1.00005 1.0001 1.00015 30 90 150 210 270 330 390 450 510 570 630 690 750 810 870 930 990 1050 1110 1170 1230 1290 1350 1410 1470 Time (seconds) Native FreeRTOS (IRQ) CS PCS IP IPP (b) Variation: Native (IRQ) 0.9998 0.99985 0.9999 0.99995 1 1.00005 1.0001 1.00015 30 90 150 210 270 330 390 450 510 570 630 690 750 810 870 930 990 1050 1110 1170 1230 1290 1350 1410 1470 Time (seconds) Native FreeRTOS (FIQ) CS PCS IP IPP (c) Variation: Native (FIQ) 0.9998 0.99985 0.9999 0.99995 1 1.00005 1.0001 1.00015 30 90 150 210 270 330 390 450 510 570 630 690 750 810 870 930 990 1050 1110 1170 1230 1290 1350 1410 1470 Time (seconds) Virtualized FreeRTOS (FIQ) CS PCS IP IPP (d) Variation: Virtualized (FIQ) Figure 4 Thread-Metric benchmarks results. (atomic execution). Thus, the modification of FreeRTOS for handling interrupts as FIQs should include the modification of the context-switch function to set the FIQ bit, instead of the IRQ bit. The problem is in the ARMv7-A specification, this bit is implementation defined. In the case of Xilinx Zynq, for security reasons, this bit is read-only, and only changes when triggered by hardware (e.g. when a FIQ happens). For this reason, we were forced to change the yield function to use an SGI (FIQ) instead of the SVC exception. The SGI has a higher latency than the SVC, which, on yield-intensive tests (i.e., the case of CS, PS, IP and IPP), this translates in a decrease of performance. It should be noted this is platform- and worlkload-specific problem that does not necessarily mean it can occur in other platforms and be noticeable in real application scenarios. In fact, the overhead introduced by LTZVisor is null, as demonstrated by the comparison of the N_FIQ and TZ_FIQ versions. This is perfectly understandable because, once FreeRTOS starts running real-time tasks, it will never be interrupted by the hypervisor. Regarding the variation, Figure 4b, Figure 4c and Figure 4d present the normalized variation of the collected results over time for the native, modified and virtualized versions of FreeRTOS, respectively. It is clear that the use of FIQ for handling interrupt sources slightly reduces the variation of results, and variation in the virtualized system is also in the same order of magnitude as the modified version, which means the virtualized system remains as deterministic as the (modified) native one. In sum, the asymmetric scheduling policy gives the RTOS a higher execution privilege, so it can preserve its real-time characteristics. Furthermore, the necessity of handling interrupts as FIQs promotes a deterministic execution, and most of the cases can either increase performance. Interrupt latency is the measurement of system’s response-time to an interrupt, which corresponds to the elapsed time between interrupt assertion and the instant when a response happens. Equation 1 expresses the system latency: τH is the hardware dependent time which depends on the interrupt controller, on the board, as well as the type of the interrupt; τOS is ECRTS 2017 (a) Secure RTOS relative performance measures in ARMv7. 85593152.25 17334980.35 35178926.8 13457423.2 35671222.45 32056417.35 26543908.8 50 60 70 80 90 100 110 120 130 CS PS IP PIP SP MP MA Relative Performance (%) Secure RTOS Relative Performance Measures using Thread-Metric Native (IRQ) Native (FIQ) Virtualized (vFIQ) (b) Secure RTOS relative performance measures in ARMv8. Figure 5.6: Secure RTOS Relative performance measures in ARMv7 and ARMv8. The native instances using IRQs of the FreeRTOSes correspond to 100%, while the other instances’ performances vary around that base value. architectural characteristics highly differ from the legacy boards’, completely altering whether one application improves or worsens between each FreeRTOS instance. 5.2.3 Interrupt Latency It was just verified that the platform’s components a have great impact on the performance of a system. Indeed, the same can be said about its interrupt handling. Figure 5.7 shows the latency of both LTZVisors’ interrupt handling mechanisms in the best-case and worst-case scenarios mentioned in Section 5.1.3. It is confirmed that the ARMv8-A LTZVisor outperforms the original hypervisor whenever an optimistic situation ensues. These results agree with the previous comparisons, as the interrupt handling in this scenario relies solely on the overhead induced by the hardware architecture and the FreeRTOS’ mechanisms, both of which were proven to be superior in ARMv8. However, on the pessimistic approach, the hypervisors’ context-switching overhead is fully taken into account. In this case, the ARMv7-A implementation achieves lower interrupt latency, mainly due to the fact that the context-switching mechanisms of the 64-bit LTZVisor are REFERENCES 93 [25] S. Marston, Z. Li, S. Bandyopadhyay, J. Zhang, and A. Ghalsasi, “Cloud Computing — The Business Perspective,” Decision Support Systems, vol. 51, no. 1, pp. 176 – 189, 2011. [26] N. M. M. K. Chowdhury and R. Boutaba, “A Survey of Network Virtualization,” Computer Networks, vol. 54, no. 5, pp. 862 – 876, 2010. [27] P. Barham, B. Dragovic, K. Fraser, S. Hand, T. Harris, A. Ho, R. Neugebauer, I. Pratt, and A. Warfield, “Xen and the Art of Virtualization,” Proceedings of the nineteenth ACM symposium on Operating systems principles - SOSP ’03, p. 164, 2003. [28] VMWare, “Understanding Full Virtualization, Paravirtualization, and Hardware Assist,” tech. rep., 2007. [29] I. Habib, “Virtualization with KVM,” Linux Journal, vol. 2008, February 2008. [30] U. Steinberg and B. Kauer, “NOVA: A Microhypervisor-based Secure Virtualization Architecture,” in Proceedings of the 5th European Conference on Computer Systems, EuroSys ’10, (New York, NY, USA), pp. 209–222, ACM, 2010. [31] B. D. Payne, M. Carbone, M. Sharif, and W. Lee, “Lares: An Architecture for Secure Active Monitoring Using Virtualization,” in 2008 IEEE Symposium on Security and Privacy, pp. 233–247, May 2008. [32] M. Ben-Yehuda, M. D. Day, Z. Dubitzky, M. Factor, N. Har’El, A. Gordon, A. Liguori, O. Wasserman, and B.-A. Yassour, “The Turtles Project: Design and Implementation of Nested Virtualization,” in 9th USENIX Symposium on Operating Systems Design and Implementation (OSDI 10), (Vancouver, BC), USENIX Association, 2010. [33] C. Dall and J. Nieh, “KVM/ARM: The Design and Implementation of the Linux ARM Hypervisor,” vol. 49, pp. 333–348, 02 2014. [34] C.-T. Liu, K.-C. Chen, and C.-H. Chen, “CASL Hypervisor and its Virtualization Platform,” pp. 1224–1227, 05 2013. [35] ARM, ARM Architecture Reference Manual. ARM, DDI 0100I ed., July 2005. [36] A. N. Sloss, D. Symes, and C. Wright, ARM System Developer’s Guide: Designing and Optimizing System Software. Morgan Kaufmann, 2004. [37] ARM, ARM Architecture Reference Manual ARMv8, for ARMv8-A architecture profile. ARM, DDI 0487D.a (ID103018) ed., October 2018. [38] ARM, ARM Architecture Reference Manual, ARMv7-A and ARMv7-R edition. ARM, DDI 0406C.c (ID051414) ed., May 2014. REFERENCES 94 [39] S. Pinto, H. Araujo, D. Oliveira, J. Martins, and A. Tavares, “Virtualization on trustzoneenabled microcontrollers? voilà!,” 04 2019. [40] ARM, ARM Cortex-A Series, Programmer’s Guide for ARMv8-A. ARM, DEN0024A (ID050815) ed., March 2015. [41] ARM, “”Technologies - ARM” [Online]. Available: https://www.arm.com/why-arm/ technologies.,” 2019. [42] ARM, Cortex-A9 Technical Reference Manual. ARM, Revision r2p2, DDI 0388F (ID050110) ed., April 2010. [43] ARM, ARM® Generic Interrupt Controller Architecture Specification, Architecture version 1.0. ARM, IHI 0048A ed., September 2008. [44] ARM, ARM® Generic Interrupt Controller Architecture Specification, Architecture version 2.0. ARM, IHI 0048B.b (ID072613) ed., July 2013. [45] Xilinx, Zynq UltraScale+ Device Technical Reference Manual. Xilinx, UG1085 (v1.9) ed., January 2019. [46] M. Cereia and I. C. Bertolotti, “Asymmetric virtualisation for real-time systems,” in 2008 IEEE International Symposium on Industrial Electronics, pp. 1680–1685, June 2008. [47] D. Sangorrín, S. Honda, and H. Takada, “Dual Operating System Architecture for Real-Time Embedded Systems,” Journal of Chemical Information and Modeling, vol. 53, no. 9, pp. 6– 15, 2013. [48] H. Douglas, Thin Hypervisor-based Security Architectures for Embedded Platforms. Trita- ICT-EX, Skolan för informations- och kommunikationsteknik, Kungliga Tekniska högskolan, 2010. [49] T. Frenzel, A. Lackorzynskyi, A. Warg, and H. Härtig, “ARM TrustZone as a Virtualization Technique in Embedded Systems,” October 2010. [50] Sierraware, “”Open Virtualization - ARM TrustZone and ARM Hypervisor Open Source Software” [Online]. Available: http://www.openvirtualization.org/.,” 2013. [51] J. Martins, J. Alves, J. Cabral, A. Tavares, and S. Pinto, “µRTZVisor: A Secure and Safe Real-Time Hypervisor,” Electronics, vol. 6, no. 4, p. 93, 2017. [52] R. Ramsauer, J. Kiszka, D. Lohmann, and W. Mauerer, “Look Mum, no VM Exits! (Almost),” CoRR, vol. abs/1705.06932, 2017. REFERENCES 95 [53] P. Lucas, K. Chappuis, M. Paolino, N. Dagieu, and D. Raho, “VOSYSmonitor, a Low Latency Monitor Layer for Mixed-Criticality Systems on ARMv8-A,” in 29th Euromicro Conference on Real-Time Systems, ECRTS 2017, June 27-30, 2017, Dubrovnik, Croatia, pp. 6:1–6:18, 2017. [54] Siemens Corporate Technology, “Hard Partitioning for Linux : The Jailhouse Hypervisor,” August 2015. [55] Virtual Open Systems SAS, “”Low latency TrustZone monitor layer to enable mixed-critical automotive systems” [Online]. Available: http://www.virtualopensystems.com/ en/products/vosysmonitor/.,” 2019. [56] AVNET, ZedBoard (Zynq™ Evaluation and Development Hardware User’s Guide). AVNET, Version 2.2 ed., January 2014. [57] Digilent, ZYBO™ FPGA Board Reference Manual. Digilent, DOC: 502-279 ed., April 2016. [58] Xilinx, Zynq-7000 SoC Technical Reference Manual. Xilinx, UG585 v1.12.2 ed., July 2018. [59] Xilinx, “”Zynq Ultrascale+ MPSoC Register Reference” [Online]. Available: https://www.xilinx.com/html_docs/registers/ug1087/ ug1087-zynq-ultrascale-registers.html.,” 2019. [60] Xilinx, Zynq Migration Guide, Zynq-7000 AP SoC to Zynq UltraScale+ MPSoC Devices. Xilinx, UG1213 (v2.0) ed., November 2016. [61] Free Software Foundation, “Using the GNU Compiler Collection (GCC),” 2019. [62] S. Chamberlain, “The GNU linker,” January 1994. [63] ARM, “”ARM Information Center” [Online]. Available: http://infocenter.arm.com/ help/index.jsp?topic=/com.arm.doc.ddi0388f/CIHCBHFB.html.,” 2010. [64] AWS, “”FreeRTOS - Market leading RTOS (Real Time Operating System) for embedded systems with Internet of Things extensions” [Online]. Available: https://www.freertos. org/.,” 2019. [65] Real Time Engineers, “The Free RTOS™ Reference Manual,” 2016. [66] R. Barry, “Mastering the FreeRTOS™ Real Time Kernel,” 2016. [67] Yocto Project, “”Yocto Project | Open Source embedded Linux build system, package metadata and SDK generator” [Online] Available at: https://www.yoctoproject.org/.,” 2019. Julho de 2019