scieee AI-readable full text Open interactive document viewer

HAL-ASOS - hardware assisted Linux for application specific operating system

Silva, Vítor Alberto Teixeira

Abstract

O ecossistema de sistemas embebidos de hoje tornou-se enorme, cobrindo vários e diferentes sistemas, exigindo desempenho e mobilidade completa enquanto atingem autonomias de bateria cada vez maiores. Mas a crescente frequência de relógio que resultou em dispositivos cada vez mais rápidos começou a estagnar antes dos transístores pararem de encolher. Plataformas Field Programmable Gate Array (FPGA) são uma solução alternativa para a implementação de sistemas completos e reconfiguráveis. Fornecem desempenho e eficiência computacional para satisfazer requisitos da aplicação e do sistema embebido. Vários Sistemas Operativos (SO) assistidos por FPGA foram propostos, mas ao estreitar seu foco na síntese do datapath do acelerador de hardware, a grande maioria ignora a integração semântica destes no SO. Ambientes de síntese de alto nível (HLS) elevaram a abstração além da linguagem de transferência de registo (RTL), seguindo uma abordagem específica de domínio enquanto misturam software e abstrações de hardware ad hoc, que dificultam as otimizações. Além disso, os modelos de programação para software e hardware reconfigurável carecem de semelhanças, o que com o tempo dificultará a Exploração do Ambiente de Design (DSE) e diminuirá o potencial de reutilização de código. Para responder a estas necessidades, propomos HAL-ASOS, uma ferramenta para implementar sistemas embebidos baseados em Linux que fornece (1) elasticidade no design em conformidade com a natureza evolutiva deste SO, (2) integração semântica profunda de tarefas de hardware nos modelos de programação do Linux, (3) facilidade na gestão de complexidade através de metodologia e ferramentas para apoiar o design, verificação e implementação, (4) orientada por princípios de design híbridos e eficiência no sistema. Para avaliar as funcionalidades da ferramenta, foi implementado um aplicativo criptográfico que demonstra alcance de desempenho enquanto se emprega a metodologia de design. Novos níveis de desempenho são atingidos numa aplicação de Visão por Computador que explora recursos de programação assíncrona-síncrona. Os resultados demonstram uma abordagem flexível na reconfiguração entre hardware e software, e desempenho que aumenta consistentemente com acréscimo de recursos ou frequência de relógio.

Full text

Universidade do Minho Escola de Engenharia Vitor Alberto Teixeira da Silva HAL-ASOS Hardware Assisted Linux for Application Specific Operating Systems Fevereiro de 2022 UMinho | 2022 Vitor Alberto Teixeira da Silva HAL-ASOS - Hardware Assisted Linux for Application Specific Operating Systems Vitor Alberto Teixeira da Silva HAL-ASOS Hardware Assisted Linux for Application Specific Operating Systems Tese de Doutoramento Programa Doutoral em Engenharia Eletrónica e de Computadores (PDEEC) Especialidade de Informática Industrial e Sistemas Embebidos Trabalho efetuado sob a orientação do Professor Doutor Adriano José da Conceição Tavares e do Professor Doutor Francisco Carlos Afonso Universidade do Minho Escola de Engenharia Fevereiro de 2022 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-NãoComercial-SemDerivações CC BY-NC-ND https://creativecommons.org/licenses/by-nc-nd/4.0/ ii Acknowledgements I would like to express my deepest gratitude to Professor Adriano Tavares for the guidance throughout this thesis. His knowledge and expertise were of utmost importance to the achievements in this work. I also would like to thank to Professors João Monteiro and Jorge Cabral for their support helping me to overcome the major obstacles faced during this thesis. I am also grateful to centro ALGORITMI for providing the necessary conditions that made this thesis possible. On a personal note, I would like to thank to my family for every sacrifice made, so that I could pursue my dreams in the world of science. Lastly I would like to acknowledge the financial support received from Portuguese Foundation for Science and Technology (FCT) with the PhD grant SFRH/BD/82732/2011. iii 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. iv Resumo HAL-ASOS - Linux com Aceleração em Hardware para Sistemas Operativos dedicados à Aplicação. O ecossistema de sistemas embebidos de hoje tornou-se enorme, cobrindo vários e diferentes sistemas, exigindo desempenho e mobilidade completa enquanto atingem autonomias de bateria cada vez maiores. Mas a crescente frequência de relógio que resultou em dispositivos cada vez mais rápidos começou a estagnar antes dos transístores pararem de encolher. Plataformas Field Programmable Gate Array (FPGA) são uma solução alternativa para a implementação de sistemas completos e reconfiguráveis. Fornecem desempenho e eficiência computacional para satisfazer requisitos da aplicação e do sistema embebido. Vários Sistemas Operativos (SO) assistidos por FPGA foram propostos, mas ao estreitar seu foco na síntese do datapath do acelerador de hardware, a grande maioria ignora a integração semântica destes no SO. Ambientes de síntese de alto nível (HLS) elevaram a abstração além da linguagem de transferência de registo (RTL), seguindo uma abordagem específica de domínio enquanto misturam software e abstrações de hardware ad hoc , que dificultam as otimizações. Além disso, os modelos de programação para software e hardware reconfigurável carecem de semelhanças, o que com o tempo dificultará a Exploração do Ambiente de Design (DSE) e diminuirá o potencial de reutilização de código. Para responder a estas necessidades, propomos HAL-ASOS, uma ferramenta para implementar sistemas embebidos baseados em Linux que fornece (1) elasticidade no design em conformidade com a natureza evolutiva deste SO, (2) integração semântica profunda de tarefas de hardware nos modelos de programação do Linux, (3) facilidade na gestão de complexidade através de metodologia e ferramentas para apoiar o design, verificação e implementação, (4) orientada por princípios de design híbridos e eficiência no sistema. Para avaliar as funcionalidades da ferramenta, foi implementado um aplicativo criptográfico que demonstra alcance de desempenho enquanto se emprega a metodologia de design. Novos níveis de desempenho são atingidos numa aplicação de Visão por Computador que explora recursos de programação assíncrona-síncrona. Os resultados demonstram uma abordagem flexível na reconfiguração entre hardware e software, e desempenho que aumenta consistentemente com acréscimo de recursos ou frequência de relógio. palavras chave: FPGA, Linux, Elasticidade Evolutiva, Microcódigo, Aceleração em Hardware. v Abstract HAL-ASOS - Hardware Assisted Linux for Application Specific Operating System Today’s embedded systems ecosystem became huge while covering several and different computer-based systems, demanding for performance and complete mobility while experiencing longer battery lives. But the rampant frequency that resulted in faster devices began hitting a wall even before transistors stopped shrinking. Field Programmable Gate Array (FPGA) platforms are an alternative solution towards implementing complete reconfigurable systems. They provide computational power, efficiency, in a lightweight solution to serve the application requirements and increase performance in the overall system. Several FPGA-assisted Operating Systems (OS) have been proposed, but by narrowing their focus on datapath synthesis of the hardware accelerator, they completely ignore the deep semantic integration of these accelerators into the OS. State-of-the-art High-Level Synthesis (HLS) environments have raised the level of abstraction beyond Register Transfer Language (RTL) by following a domain-specific approach while mixing ad hoc software and hardware abstractions, making harder for performance optimizations. Furthermore, the programming models for software and reconfigurable hardware lack commonalities, which in time will hinder the Design Space Exploration (DSE) and lower the potential for code reuse. To overcome these issues, we propose HAL-ASOS, a framework to implement Linux-based Embedded systems which provides (1) elasticity by design to comply with the evolutive nature of Linux, (2) deep semantic integration of the hardware tasks in the Linux programming models, (3) easy complexity management using methodology and tools to fully support design, verification and deployment, (4) hybrid and efficiency-oriented design principles. To evaluate the framework functionalities, a cryptographic application was implemented and demonstrates performance achievements while using the promoted application-driven design methodology. To demonstrate new levels of performance that can be achieved, a Computer Vision application explores several mixed asynchronous-synchronous programming features. Experiments demonstrate a flexible design approach in terms of hardware and software reconfiguration, and significant performance that increases consistently with the rising in processing resources or clock frequencies. Keywords: FPGA, Linux, Evolutive elasticity, Microcode, Hardware Acceleration. vi Table of Contents Resumo vi Abstract vii List of Listings xi 1 Introduction 1 1.1 Research questions and Methodology . . . . . . . . . . . . . . . . . . . . . . . . 5 1.2 Scope ....................................... 6 1.3 StateoftheArt ................................... 6 1.3.1 Native FPGA Acceleration . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.3.2 Operating systems for FPGA . . . . . . . . . . . . . . . . . . . . . . . . 7 1.3.3 Application-specific operating systems . . . . . . . . . . . . . . . . . . . 12 1.3.4 Microcode-level customizations . . . . . . . . . . . . . . . . . . . . . . . 12 1.4 Conclusions .................................... 13 1.5 ThesisStructure .................................. 14 2 Design Methodology 15 2.1 Designflow..................................... 15 2.2 Programmingmodel ................................ 18 2.3 Application Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.4 Softwarerefactoring................................. 23 2.4.1 The File reader task . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.4.2 TheEncryptortask............................. 25 2.4.3 TheUploadertask ............................. 26 2.4.4 Functional validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 vii PL Programmable Logic. PLB Processor Local Bus. POSIX Portable Operating System Interface. PS Processing System. RAM Random-access memory. RTL Register Transfer Language. SDK Software Development Kit. SIMD Single Instruction Multiple Data. SoC System on a Chip. SPUFS Synergistic Processor Units File System. stdout standard output descriptor. TLP Thread Level Parallelism. UHD Ultra High Definition. UML Unified Modelling Language. VFS Virtual File System. VLIW Very Long Instruction Word. VM Virtual Machine. XML Extensible Markup Language. xiv List of Figures 2.1 The HAL-ASOS design flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.2 Simplified UML diagram of template class Task . ................... 19 2.3 Overview of the AES-128-bit algorithm. . . . . . . . . . . . . . . . . . . . . . . . . 21 2.4 Machine 1application - task graphical representation. . . . . . . . . . . . . . . . . 22 2.5 The Machine 1application - SW task version source code. . . . . . . . . . . . . . . 23 2.6 File reader task - simplified run() member....................... 24 2.7 Encryptor task - simplified run() member. ...................... 25 2.8 Uploader task - simplified ’run()’ member (full listing:C.3) . . . . . . . . . . . . . . 26 2.9 Machine 1 - SW-only application output for one million digits. . . . . . . . . . . . . . 27 2.10 Machine 2- Server application Output. . . . . . . . . . . . . . . . . . . . . . . . 27 2.11 Machine 2- contents of plain data file after decryption. . . . . . . . . . . . . . . . . 28 2.12 Machine 2- contents of encrypted file received. . . . . . . . . . . . . . . . . . . . 28 2.13 Profile results of the Machine 1application. ..................... 31 2.14 HAL-ASOS Accelerator model integrated into Host platform. . . . . . . . . . . . . . 32 2.15 Hardware Kernel simplified model. . . . . . . . . . . . . . . . . . . . . . . . . . 33 2.16 Hardware Task simplified model. . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.17 HAL-ASOS file system structure on Linux. . . . . . . . . . . . . . . . . . . . . . . 36 2.18 Accelerator Model Emulator - Simplified UML class diagram. . . . . . . . . . . . . . 39 2.19 HW Encryptor Task - Simplified Datapath . . . . . . . . . . . . . . . . . . . . . . 41 2.20 HW Encryptor Task - Simplified Control unit Finite State Machine (FSM) . . . . . . . . 42 2.21 Machine 1: emulated HW Encryptor software changes . . . . . . . . . . . . . . . . 44 2.22 Machine 1: Hardware Task emulator . . . . . . . . . . . . . . . . . . . . . . . . . 45 2.23 Machine 1- HW encryptor using emulator . . . . . . . . . . . . . . . . . . . . . . 46 2.24 Encryptor - simplified control path. . . . . . . . . . . . . . . . . . . . . . . . . . . 48 2.25 Encryptor SA - simplified control path. . . . . . . . . . . . . . . . . . . . . . . . . 50 xv 2.26 HAL-ASOS simplified Co-Simulation model . . . . . . . . . . . . . . . . . . . . . . 51 2.27 Machine 1- software changes for Co-Simulation using the HW Encryptor task. . . . . 52 2.28 Co-Simulation - HW Encryptor Accelerator settings . . . . . . . . . . . . . . . . . . 53 2.29 Co-Simulation - HW Encryptor application output . . . . . . . . . . . . . . . . . . . 54 2.30 Co-Simulation - HW Encryptor handshake messages . . . . . . . . . . . . . . . . . 55 2.31 Co-Simulation - HW Encryptor wave plot using Vivado simulator . . . . . . . . . . . . 57 2.32 Machine 1- Co-Simulation Standalone HW Encryptor Task . . . . . . . . . . . . . . 58 2.33 Co-Simulation - HW Encryptor SA application output. . . . . . . . . . . . . . . . . . 59 2.34 Machine 1- HW Encryptor SA handshake messages using ModelSim . . . . . . . . . 59 2.35 Co-Simulation - HW Encryptor SA wave plot using ModelSim. . . . . . . . . . . . . . 60 2.36 Machine 1 -Simplified block design using ZC702 platform. . . . . . . . . . . . . . . 63 2.37 Programmable Logic - device tree source two accelerators. . . . . . . . . . . . . . . 64 2.38 HAL-ASOS Full simulation Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 2.39 Full Simulation - HW Encryptors block design . . . . . . . . . . . . . . . . . . . . 67 2.40 Full Simulation - hal_asos_link simulation parameters . . . . . . . . . . . . . . . . 68 2.41 Full Simulation - QEMU and Vivado handshake log . . . . . . . . . . . . . . . . . . 69 2.42 Full Simulation - running Linux image on QEMU . . . . . . . . . . . . . . . . . . . 70 2.43 Full Simulation - Machine 1 application using HW Encryptor task........... 71 2.44 Full Simulation - HW Encryptor simulation waveform. . . . . . . . . . . . . . . . . . 72 2.45 Full Simulation - Standalone HW Encryptor design . . . . . . . . . . . . . . . . . . 73 2.46 Full Simulation - Stand-Alone HW Encryptor simulation waveform. . . . . . . . . . . 74 2.47 Machine 1 - Software-only application version running on ZC702 board. . . . . . . . . 75 2.48 Zynq ZC702 - Application performance of the machine 1application. . . . . . . . . . 78 2.49 Zynq ZC702 - Application performance of the hardware accelerated designs. . . . . . 78 3.1 Accelerator Model - and overview of the provided services. . . . . . . . . . . . . . . 80 3.2 Hardware system call - wait event sequence diagram. . . . . . . . . . . . . . . . . 81 3.3 Hardware system call - mutex lock sequence diagram. . . . . . . . . . . . . . . . . 82 3.4 Kernel Core internal structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 3.5 Authenticator device architecture . . . . . . . . . . . . . . . . . . . . . . . . . . 84 3.6 Authenticator wave diagram: control operation for HW-Task restart. . . . . . . . . . . 85 3.7 Kernel Core - Control Unit Overview . . . . . . . . . . . . . . . . . . . . . . . . . 86 xvi 3.8 Kernel Core - FSM state diagram . . . . . . . . . . . . . . . . . . . . . . . . . . 87 3.9 Kernel Core - control unit wave diagram. . . . . . . . . . . . . . . . . . . . . . . . 89 3.10 Kernel Core - system-level datapath and microprogram interaction. . . . . . . . . . . 90 3.11 HW-Kernel package - system call types, entry and exit records . . . . . . . . . . . . 91 3.12 Microprogram - opcode format example in mutex lock step two. . . . . . . . . . . . . 97 3.13 Microprogram - ROM-based internal architecture. . . . . . . . . . . . . . . . . . . . 99 3.14 Time Event unit - simplified architecture diagram. . . . . . . . . . . . . . . . . . . 101 3.15 Time Event unit - control logic state diagram. . . . . . . . . . . . . . . . . . . . . 102 3.16 Time Event unit - Wait for a signal event using a 6-clock timeout. . . . . . . . . . . . 103 3.17 System-Level datapath - system call signals and target resource. . . . . . . . . . . . 104 3.18 System-Level datapath - Time event parameters and return signals. . . . . . . . . . . 106 3.19 System-Level datapath - Local-BUS and MBUS fields of system call. . . . . . . . . . . 107 3.20 Kernel Core - status register signals. . . . . . . . . . . . . . . . . . . . . . . . . . 108 3.21 System-Level datapath - Index management service. . . . . . . . . . . . . . . . . . 109 3.22 Kernel Core - execution progress service. . . . . . . . . . . . . . . . . . . . . . . 111 3.23 Kernel Core - input and output interface types using VHDL records. . . . . . . . . . . 112 3.24 Kernel Core - execution runtime overview from the HW-Task perspective. . . . . . . . 114 3.25 Kernel package procedures - wait signal event descriptions. . . . . . . . . . . . . . 115 3.26 Kernel package procedures - read local-RAM in burst format descriptions. . . . . . . . 116 3.27 Hardware Task - simplified example architecture. . . . . . . . . . . . . . . . . . . . 118 3.28 Task Model - concurrent user procedure description example. . . . . . . . . . . . . 119 3.29 HW-Task Model - Sequential units descriptions using VHDL. . . . . . . . . . . . . . 121 3.30 User package procedures - scheduling concurrent system calls. . . . . . . . . . . . 122 3.31 User package - VHDL procedure to burst read the sysram memory. . . . . . . . . . . 124 3.32 Hardware descriptor - record composition and specialized types. . . . . . . . . . . . 126 3.33 Kernel package - VHDL excerpt of the file and socket descriptor records. . . . . . . . 127 3.34 Kernel-level internal message hierarchy. . . . . . . . . . . . . . . . . . . . . . . . 128 3.35 Query message - file descriptor query sequence diagram. . . . . . . . . . . . . . . 129 3.36 User package - procedure to query for a file HW-based descriptor. . . . . . . . . . . 130 3.37 Data transfer message - file descriptor write sequence diagram. . . . . . . . . . . . 132 3.38 Remote call message - file descriptor write data sequence diagram. . . . . . . . . . . 133 xvii 3.39 Kernel Package - Kernel-level communication tokens. . . . . . . . . . . . . . . . . . 134 3.40 Generic Interface Master-Slave model . . . . . . . . . . . . . . . . . . . . . . . . 135 3.41 Synchronizer for the generic interface . . . . . . . . . . . . . . . . . . . . . . . . 138 3.42 Generic Bus component - The top level and schedule policies . . . . . . . . . . . . . 140 3.43 Generic Bus Arbiter - internal architecture . . . . . . . . . . . . . . . . . . . . . . 141 3.44 Generic Bus Arbiter - internal architecture . . . . . . . . . . . . . . . . . . . . . . 142 3.45 Generic Bus component - internal architecture . . . . . . . . . . . . . . . . . . . . 144 3.46 Generic Bus wave plot - timing simulation using A and B interfaces. . . . . . . . . . 145 3.47 Slave decoder componentinternal architecture. . . . . . . . . . . . . . . . . . . . 147 3.48 S01 interface - multi-master connectivity. . . . . . . . . . . . . . . . . . . . . . . 151 3.49 M00 interface - multi-master connectivity. . . . . . . . . . . . . . . . . . . . . . . 153 3.50 M00 interface - Read four words in SYSRAM using burst format. . . . . . . . . . . . 156 4.1 Local-BUS mapping - Low- and High-memory regions. . . . . . . . . . . . . . . . . 158 4.2 Local-BUS architecture - slave interfaces and address decoding. . . . . . . . . . . . 159 4.3 Local-BUS - Resource usage for final design in Zynq ZC702. . . . . . . . . . . . . . 160 4.4 HW-Mutex design architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 4.5 HW-Mutex control unit state diagram. . . . . . . . . . . . . . . . . . . . . . . . . 162 4.6 HW-Mutex wave diagram: concurrency scenarios. . . . . . . . . . . . . . . . . . . 164 4.7 Local RAM - internal architecture for 32-bit accelerator design. . . . . . . . . . . . . 165 4.8 Local-Ram wave diagram: burst read system call. . . . . . . . . . . . . . . . . . . 166 4.9 HW FIFO[1:3] - architecture using 3 and 8 configured parameters. . . . . . . . . . . 168 4.10 HW FIFO[1:3] - architecture using 3 and 8 configured parameters. . . . . . . . . . . 169 4.11 HW-FIFO [1:3] - Wave plot simulation diagram using Vivado. . . . . . . . . . . . . . 170 4.12 Local Interrupt Controller - control and status register. . . . . . . . . . . . . . . . . 171 4.13 Local Interrupt Controller - internal architecture diagram. . . . . . . . . . . . . . . . 172 4.14 ZeroCopy unit - Connectivity in the accelerator model. . . . . . . . . . . . . . . . . 174 4.15 ZeroCopy unit - architectural design. . . . . . . . . . . . . . . . . . . . . . . . . . 176 4.16 ZeroCopy unit - Lock unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 4.17 ZeroCopy unit - Write enable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 4.18 ZeroCopy unit - Control unit FSM. . . . . . . . . . . . . . . . . . . . . . . . . . . 178 xviii 4.19 ZeroCopy unit wave diagram - Read the S01 interface and write to the system memory usingburstformat. ................................. 180 4.20 Performance Counter - architecture simplified block diagram. . . . . . . . . . . . . . 183 4.21 Performance counter wave diagram - Blocked counter metrics using example HW-Task . 184 4.22 HW kernel - architecture configurations for b and f variants. . . . . . . . . . . . . . 188 4.23 HAL-ASOS accelerator - architecture components and configuration clause. . . . . . . 189 5.1 Object Detector application block diagram. . . . . . . . . . . . . . . . . . . . . . . 191 5.2 Object Detector application test. . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 5.3 Image mapping to Bresenham circle example. . . . . . . . . . . . . . . . . . . . . 193 5.4 Block Diagram for the Software Full dataset test. . . . . . . . . . . . . . . . . . . . 196 5.5 Block Diagram for the Software Non-maximum suppression. . . . . . . . . . . . . . 197 5.6 Hardware accelerated feature detection application using HAL-ASOS framework. . . . 198 5.7 Software-only feature detection: application performances when using input and output files and time command on the target platform Xilinx ZC-702. . . . . . . . . . . . . 199 5.8 Software-Only feature detection performances using 1080p test images. . . . . . . . 200 5.9 An abstract overview of synchronous (a) versus asynchronous (b) pipeline in the Classifilter blockdesign. ................................. 202 5.10 Hardware Accelerated Feature detection feature datapath. . . . . . . . . . . . . . . 203 5.11 Simplified synchronous control unit for HW feature detection. . . . . . . . . . . . . . 204 5.12 Extended features for the multi-threaded HW-Task that targets LRAM resource when using the V4_00_B accelerator. . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 5.13 Excerpt of the multi-threaded application source that targets the LRAM resource using theV4_00_Baccelerator............................... 207 5.14 Performances for the multi-threaded HW accelerated feature detention using V4_00_B and V4_00_F accelerators at 50 MHz and 8 kB and 2 kB block sizes. . . . . . . . . 208 5.15 Application performances between software and synchronous HW accelerated feature detection....................................... 209 5.16 Performances for the multi-threaded HW accelerated feature detention using accelerator versions V4_00_B/F at 142 MHz and 32 kB and 2 kB block sizes. . . . . . . . . . . 210 5.17 Excerpt from the source to implement standalone application using synchronous design and the V4_00_F accelerator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 xix 5.18 Extended features for the standalone HW-Task that targets SYSRAM resource when using theV4_00_Faccelerator............................... 213 5.19 Performances for the stand-alone synchronous control using V4_00_B/F accelerators at 50 MHz and 8 kB and 2 kB block sizes. . . . . . . . . . . . . . . . . . . . . . . 213 5.20 Performance comparison of the synchronous design HW-accelerated applications using 8 kB block and 50 MHz clock frequency. . . . . . . . . . . . . . . . . . . . . . . . 214 5.21 Performance of the standalone synchronous application using the V4_00_F accelerator and 90,000 corners and varying the input block size and design frequency. . . . . . . 215 5.22 Dual task hardware accelerated feature detection block diagram. . . . . . . . . . . . 216 5.23 Asynchronous control for hardware accelerated feature detection. . . . . . . . . . . . 218 5.24 Extended Features design-level for the HW-Task MFastSA that targets the SYSRAM resource and uses de V4_00_F accelerator version . . . . . . . . . . . . . . . . . . 220 5.25 Performance of asynchronous designs using V4_00_B and V4_00_F accelerators. . . 221 5.26 Performance of the interrupt latency of V4_00_B and V4_00_F accelerators. . . . . . 222 5.27 Performance of the interrupt latency of V4_00_F accelerators. . . . . . . . . . . . . 223 5.28 Logic Analyzer using interrupt as trigger in the V4_00_F accelerator. . . . . . . . . . 224 5.29 Performances of asynchronous V4_00_A and V4_00_F/B accelerators. . . . . . . . 226 5.30 Performances for the asynchronous designs varying the input file. . . . . . . . . . . 227 5.31 Performances using dual-task V4_00_F accelerators and 90,000 corners. . . . . . . 228 5.32 Full frame-rate operation using 100 MHz clock and 32 kB input block size. . . . . . . 229 5.33 Hardware accelerated object detection application results. . . . . . . . . . . . . . . 232 5.34 Software accelerated object detection application results. . . . . . . . . . . . . . . . 233 A.1 S00 interface - Two-level address decoding design. . . . . . . . . . . . . . . . . . . 240 A.2 S00 interface - Two-level address resource usage in Zynq7000. . . . . . . . . . . . . 240 A.3 S00 interface - Single-level address resource usage in Zynq7000. . . . . . . . . . . . 241 A.4 S00 Interface - Two-level address resource usage in Virtex 5 family. . . . . . . . . . . 242 A.5 Slave decoder internal architecture block diagram. . . . . . . . . . . . . . . . . . . 243 A.6 S00 interface - Resource usage for tri-state datapath design in Zynq7000. . . . . . . 243 A.7 S00 interface - Resource usage for MUX datapath design in Zynq ZC702. . . . . . . . 244 A.8 Slave decoder internal architecture block diagram. . . . . . . . . . . . . . . . . . . 245 A.9 Page decoder component - internal architecture. . . . . . . . . . . . . . . . . . . . 246 xx A.10 S00 interface - Resource usage final design using ZC702 platform. . . . . . . . . . . 246 B.1 Flip-Flop D time constraints setup, hold and propagation delay . . . . . . . . . . . . 249 B.2 Flip-Flop D time constraints violation . . . . . . . . . . . . . . . . . . . . . . . . . 250 B.3 Multi-Flop D synchronizer circuit . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 B.4 Multi-Flop D pulse synchronizer circuit . . . . . . . . . . . . . . . . . . . . . . . . 251 B.5 Synchronizer Generic: single clock ACK-based handshake circuit. . . . . . . . . . . . 252 D.1 Platform Deployment - Machine 1 block design using ZC702 board (Back to Figure 2.36). 304 D.2 Co-Simulation - Standalone HW Encryptor signals using Vivado simulator (back to Figure2.35)...................................... 305 D.3 Time Event unit - Wait for a signal event using 6 as timeout parameter, not exhausted. 306 D.4 Time Event unit - Wait for a signal event using no timeout. . . . . . . . . . . . . . . 306 D.5 ZeroCopy unit wave diagram - Read system memory and write S01 interface in burst format........................................ 307 D.6 Kernel Core - FSM state diagram for the RAM-based microprogram. . . . . . . . . . . 308 D.7 Kernel Core - Control and status registers for the RAM-based microprogram. . . . . . 308 D.8 Kernel Core - system-level datapath and microprogram interaction for the RAM-based microprogram. ................................... 308 D.9 Microprogram - RAM-based internal architecture. . . . . . . . . . . . . . . . . . . . 309 D.10 Feature detection test images dataset. . . . . . . . . . . . . . . . . . . . . . . . . 309 D.11 Synchronous control unit for the multithread-based HW-Task design. . . . . . . . . . 310 D.12 Synchronous control unit for the FastSA HW-Task. . . . . . . . . . . . . . . . . . . 311 D.13 Block design for the Dual-Task Asynchronous design targeting ZC702 platform. . . . . 312 D.14 Asynchronous control unit for the single Task feature detection. . . . . . . . . . . . . 313 E.1 The AES block interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 E.2 The AES-128 algorithmic structure. . . . . . . . . . . . . . . . . . . . . . . . . . 319 E.3 The AES block cipher matrix - The state Smatrix. .................. 320 E.4 The AES parallel SubBytes blockdiagram....................... 321 E.5 The sbox function internal blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . 321 E.6 The software SubBytes function using C language. . . . . . . . . . . . . . . . . . . 323 E.7 The software InvSubBytes function using C language. . . . . . . . . . . . . . . . . 323 xxi E.8 The hardware SubBytes step using VHDL language. . . . . . . . . . . . . . . . . . 323 E.9 The ShiftRows stepintheAES. ........................... 324 E.10 The software ShiftRows function using C language. . . . . . . . . . . . . . . . . . . 325 E.11 The software inverse of ShiftRows function using C language. . . . . . . . . . . . . . 325 E.12 The hardware ShiftRows function using VHDL. . . . . . . . . . . . . . . . . . . . . 326 E.13 The MixWord (or MixColumn ) block in the AES MixColumns step. . . . . . . . . . . . 328 E.14 The AES MixColumns - software implementation using C language. . . . . . . . . . . 329 E.15 The AES InvMixWord - software source using C language. . . . . . . . . . . . . . . . 330 E.16 The AES MixWord - hardware description using VHDL. . . . . . . . . . . . . . . . . 330 E.17 The AES AddRoundKey step block diagram. . . . . . . . . . . . . . . . . . . . . . 331 E.18 The AES AddRoundKey step - software implementation using C language. . . . . . . . 332 E.19 The AES AddRoundKey step - hardware implementation using VHDL. . . . . . . . . . 333 E.20 The AES Key Schedule Algorithmpipeline-based block diagram. . . . . . . . . . . . 333 E.21 The AES Key Expansion - software C sequential implementation. . . . . . . . . . . . 335 E.22 The AES Key Expansion - hardware sequential-based description using VHDL. . . . . . 336 E.23 The AES software encrypt process - sequential implementation. . . . . . . . . . . . 338 E.24 The AES software decrypt process - sequential implementation. . . . . . . . . . . . 339 E.25 The hardware AES - sequential design. . . . . . . . . . . . . . . . . . . . . . . . . 340 E.26 The hardware AES - pipeline design. . . . . . . . . . . . . . . . . . . . . . . . . . 342 F.1 HW-Fast or HW-NMS parameter registers. . . . . . . . . . . . . . . . . . . . . . . 356 F.2 Hardware Feature detection datapath. . . . . . . . . . . . . . . . . . . . . . . . . 358 F.3 Address controller hardware block diagram. . . . . . . . . . . . . . . . . . . . . . 359 F.4 Classifier filter hardware block diagram. . . . . . . . . . . . . . . . . . . . . . . . 361 F.5 Contiguity check hardware block diagram. . . . . . . . . . . . . . . . . . . . . . . 362 F.6 Scoring hardware block diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . 363 F.7 Feature detection final score. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 F.8 Non-Maximum suppression datapath. . . . . . . . . . . . . . . . . . . . . . . . . 364 F.9 Suppression hardware block diagram. . . . . . . . . . . . . . . . . . . . . . . . . 365 F.10 Feature Detection co-simulation - Block design using Vivado. . . . . . . . . . . . . . 366 F.11 Feature Detection co-simulation - Single corner input file. . . . . . . . . . . . . . . . 367 F.12 Feature Detection co-simulation - Wave plot of the FAST datapath. . . . . . . . . . . 369 xxii F.13 Feature Detection co-simulation - Wave plot of the FAST+NMS datapaths. . . . . . . . 370 F.14 Feature Detection co-simulation output logs. . . . . . . . . . . . . . . . . . . . . . 371 List of Tables 1.1 Gap Analysis considering the literature solutions revised in the section. . . . . . . . . 13 3.1 Kernel Core - HW system call summary description . . . . . . . . . . . . . . . . . 93 3.2 Microprogram - Binary excerpt from the Microprogram. . . . . . . . . . . . . . . . . 98 3.3 The S00 interface - Page 0 internal register mapping. . . . . . . . . . . . . . . . . 148 3.4 The S00 interface - Page 1 internal register mapping. . . . . . . . . . . . . . . . . 149 3.5 Performance Counter internal register offsets. . . . . . . . . . . . . . . . . . . . . 150 3.6 The M00 interface - signal description and generic interface mapping. . . . . . . . . 154 4.1 HAL-ASOS accelerator versions V3 and V4 features. . . . . . . . . . . . . . . . . . 186 5.1 Hardware Accelerated Feature detection designs comparison. . . . . . . . . . . . . 230 5.2 HW-Accelerated FAST using HAL-ASOS (a) compared to the literature. . . . . . . . . . 231 List of Equations 5.1 Fast algorithm Bright comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 5.2 Fast algorithm Bright comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 5.3 Fast algorithm Scoring function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 xxiii 2 Chapter 1. Introduction Level Parallelism (ILP) are the root drivers of performance in the system, the performance of the manycore demands for scalability, as the system utilization will only be exacerbated by a proper and efficient parallelization. Another consideration is the fact that distinct CPU architectures will map more efficiently into specific types or sections inside an application. The control dominated or event-bounded sections are generally composed by independent code sections and can be efficiently executed in more traditional out-of-order execution processor. Other sections can be more data-centric or processor-bounded, such as image or signal processing, and can also executed in the same machine, but it will experience great performances in a more complex CPU architecture such as Single Instruction Multiple Data (SIMD) or Very Long Instruction Word (VLIW) processors. The struggle to serve the different application needs pushed chip manufactures into designing systems that mix core architectures and dynamically adjust performance to the computational needs. ARM has been developing the big.LITTLE heterogeneous processing Architecture since 2011. The design uses two classes of processors and in the latest design specifications, the Big processor cluster can include four Cortex-A73, while the Little processor cluster can also include four Cortex-A53. Apple launched the A13 Bionic chip, an ARM-based System on a Chip (SoC) design that includes a 64-bit hexa-core processor with two 2.65 GHz Lightning cores for high-performance processing, and four 1.8GHz Thunder cores for power efficient processing. Intel announced the Hybrid x86 CPU designed with power efficiency in mind, with one x86 Sunny Cove core (big CPU) and four smaller design x86 CPU cores (small CPUs). However, different core architectures can introduce Instruction Set Architecture (ISA) and Application Binary Interface (ABI) incompatibilities, different memory hierarchies, cache organization or coherence algorithms. Currently, specific OSes are used to deal with these issues, by abstracting the computing platform into a single Virtual Machine (VM), where system calls represent the standard set of operations for each specific machine while providing the designer an established way for structuring its applications. The assumption that such set of virtual operations will be available across different platform distributions, provides the means for portability and consequently guide industry acceptance. Although a valid solution, the specific OSes usually restrict the available application software base and target specific software tools that can raise development effort. Consequently, new design projects are featured by growing software complexity and engineering effort. Generic purpose OSes usually provide fast application prototyping with eased use, high software integration, increased hardware support, and extended debugging features that are not usual in target specific Chapter 1. Introduction 3 OSes. But despite of the expected overhead and performance metrics degradation, most of the ’wellaccepted’ operating systems, were never created to abstract such a level of heterogeneity into a unified VM model. They are built into the premise of some internal homogeneity and so, they are now struggling with the hardware level asymmetries at many levels of implementation, raising considerable issues to programming and increased computational overhead to conform with the system. The risen in silicon logic densities, pushed the Field Programmable Gate Array (FPGA) from being applied as glue logic and prototyping towards implementing complete reconfigurable systems. Today’s FPGA platforms provide large density fabrics and include the latest multi-core CPU architectures. They represent the desired architecture for most embedded devices and motivated designers to use them not only as development platforms but also as final products. Offloading computation to specialized hardware circuitry is not new as it has been successfully used in the past. The mix of fast CPU cores and fine-grained reconfigurable logic allows to map both sequential or control-dominated code and highly parallel datacentric computations into a single platform. They can provide computational power, efficiency, in a lightweight solution to serve the application requirements, increasing performance, and they can also be considered as complementary to complex heterogenic processor architectures. However, the programming models for software and reconfigurable hardware lack commonalities, which in time will hinder the Design Space Exploration (DSE) and lower the potential for code reuse. Traditional design techniques were not able to kept with these risen in system complexity. Generally, they do not consider any efficiencies on the purposed programming models. Also, the existing design techniques for these types of reconfigurable devices evolved from the Application Specific Integrated Circuit (ASIC) design and tend to view the specialized hardware as passive processing units in the system. A new design methodology is demanded for dealing with aforementioned new systems requirements and constraints of multiple functionalities, programmability, heterogeneity, smartness, real-time performance, power consumption and security due to connectivity, that all together have been compounding the design complexity. Essentially, it must raise the abstraction level to design, allowing the user to quickly envision, develop and deploy the application. Specifically, it must be one that: (1) promotes the reconfigurable hardware to first-class computing unit, being able to synchronize, communicate and notify other computing units in the system; (2) provides seamless hardware integration through an automated DSE, guided by an improved metric-driven approach and encompassing an integrated system emulator with multilevel simulation; (3) encourages creativity, exploring the hardware and software synergies, and thus expanding 4 Chapter 1. Introduction the scope of electronic design beyond its original boundaries. In spite of the panoply of existing Electronic Design Automation (EDA) tools, supporting capabilities such as high-level synthesis, system profiling, simulation and emulation as well as Standard Structure for Packaging, Integrating, and Reusing Intellectual Property (IP) (IP-XACT) [3] design and overlay architecture for FPGAs, only to mention a few, none of them can efficiently handle such demand for nowadays systems requirements and constraints. A toolset is in need to leverage IP evaluation, quality assurance and mostly a snap-in integration. Most of the existing IPs, are blacked boxed with few or none visibility into, neither software to support for validation and assist in device-driver development, thus forcing the integration task to a level of development effort. To gain the insight to what such a tool needs to address it is better to start by answering what is the today’s system realization. Traditionally, most systems are developed from the bottom up starting with the hardware. The OS already exists and is generally pre-selected and the applications are developed within the limitations of the pre-determined hardware and software stacks. Typically, the application development is largely abstracted from the hardware, and in the absence of a virtual emulator, the application will not be completed until the target hardware is fully available. The system integration and debugging will occur later in the development cycle, and it will usually face schedule delays and quality issues that, ultimately resulted in quality degradation. Applications are pre-sentenced to the underlying hardware and software layers, and must conform to any constraint limitations imposed. Any potential glitch that simultaneously involves the application, OS, and hardware layers is extremely difficult to fix and demands for very timeconsuming effort with a lot of iteration and debugging. To support the narrow range of application needs and still being able to tackle performance and efficient design metrics, one must ditch the hardware-first paradigm and follow a different approach. One that starts by quickly envisioning the application, allowing designers to feel the application needs and then choose the right platform, resources and the software layers. For an effective performance, the hardware and software must to be developed concurrently to better promote efficiency in a resource-aware design approach that fits the solution with just the right needs. Chapter 1. Introduction 5 1.1 Research questions and Methodology We believe that extracting the performance benefits from computational offload to FPGA reconfigurable devices, requires an agnostic approach to the software. One that follows an application-centric design methodology, where the application is driving the system requirements instead of system capabilities driving the application. One that raises the abstraction level to programming and provides transparent reconfigurable hardware devices integration. For these reasons, this thesis tries to answer to the following questions: 1. How can we transparently and dynamically extend the Linux programming models with reconfigurable hardware devices? 2. How can we lower programmability gap between the hardware and software? 3. Can we provide and automated design flow that mitigates the system complexity, keeps track on development and ensures compliance with the design metrics, while leveraging better computing and resource efficiency? We address the questions above by applying the following methodology that is anchored to (1) elasticity by design, (2) deep semantic integration, (3) easy complexity management, (4) hybrid and efficiency-oriented design principles, to implement Hardware Assisted Linux for Application Specific Operating Systems (HALASOS): 1. Run a parallelization tuning cycle using profilers and based on several workloads to identify critical Linux kernel- and user-level subsystems that should be tuned for scalability; 2. Propose a high-level programming abstraction at the same level of software task to express hardware translated tasks from Linux, application and middleware components by making reconfigurable hardware first-class computing entities; 3. Leveraging computing and resource efficiency by applying mixed asynchronous–synchronous design, event-driven, microcode dynamicity and laziness approaches; 4. Support system designer in the creation of the full platform solutions, including Board Support Package (BSP), OS, device drivers, middleware and applications software; 6 Chapter 1. Introduction 5. Provide an integrated solution that automates the development of the software on which the user application will be built by exploring the capabilities of the application-tailored SoC. HAL-ASOS targets the design of Embedded systems, tailored to the application requirements, which are implemented using CPU+FPGA platforms. 1.2 Scope The scope of this thesis falls within the development of software and reconfigurable hardware devices, but it is constrained to the hardware accelerated Linux-based embedded systems on CPU+FPGA platforms. It also falls into the scope of design methodologies to ensure an efficient design and ease the programmability gap between software and hardware, while providing the designer with a complete solution for developing reconfigurable systems that, benefit from the synergy among software, hardware and services, and deliver powerful computation solutions that can be built with just the right resources. 1.3 State of the Art The state-of-the-art for this thesis falls into four areas that will be discussed in the paragraphs below: (1) Native or ad hoc FPGA acceleration (2) operating systems for FPGA; (3) Application-Specific Operating Systems (ASOS); and (4) microcode-level customization and update: 1.3.1 Native FPGA Acceleration Many native FPGA-based acceleration solutions exist, which are hand-optimized for one specific application and FPGA platform, hindering the productivity by demanding for complete rewriting or time-consuming porting. HThreads [4] provided a unified multi-threaded programming model for architectures with reconfigurable components, by delivering mechanisms that implement transparent integration of hardware threads into a heterogenous system. Such mechanisms, implement basic scheduling, synchronization and interrupt handling for the hardware threads. A Hardware Thread Interface (HWTI) abstracts a platformindependent compilation target, for hardware-resident computations. It enables the use of standard thread communication and synchronization across the software/hardware boundary. The system is designed from C code language sources, which are compiled using the HybridThreads compiler (HTC) to create Chapter 1. Introduction 7 VHDL code that is integrated into the HThreads synthesis process. A runtime support implementing a hardware-based microkernel provides OS backend to the components in the system. It enables the design of heterogeneous systems using Portable Operating System Interface (POSIX) programming abstractions. From the designer perspective, it provides a multi-threaded programming model where a parent thread creates any number of children threads that will execute transparently on the underlying computational resources. Despite the novelty in this research, the use of dedicated compiler from C to Register Transfer Language (RTL) to implement hardware threads in the application, is very limiting in terms of portability and maintenance. Luca Pezzarossa et al. [5] evaluated the potential benefits of using Dynamic Partial Reconfiguration (DPR) to implement hardware accelerators in real-time systems by driving the main focus towards: (1) trade-offs between hardware utilization, worst-case performance, and speed-up over a pure software solution and (2) the trade-offs between the use of multiple specialized accelerators combined with DPR instead of the use of a more general accelerator, and the memory footprint of the partial-bit streams. The interaction between software and hardware is based on the control registers of each accelerator and specific shared memory regions. For testing, it implemented a passive coprocessor model where the software is responsible for activating accelerators when input data is ready for processing. The results compare performance of the software using softcore processor over the hardware accelerators in combination with the DPR feature of the FPGAs. The use of DPR can lead to significant reduction in the hardware size when the reconfigured tasks are computationally intensive, and maintain performances gains ranging from 1.2 to 4.1 times over the software execution. Solutions described above narrow their focus on datapath synthesis of the hardware accelerator, completely ignoring the deep semantic integration of these into operating system, or high-level synthesis (High-Level Synthesis (HLS)) environments as well as DPR-enabled elasticity. In the absence of and OS environment, applications fail to handle reliable software operation as well as the legacy software execution and well-established programming models. 1.3.2 Operating systems for FPGA There have been many proposals for building operating systems for FPGA, mainly due to the risen in silicon logic densities alongside the differentiating capabilities of FPGAs. Offloading computation to specialized hardware circuitry has been used to provide computational power, efficiency, in a light-weight solution to 8 Chapter 1. Introduction serve the application requirements and increasing performance, while it can also be considered as complementary to complex heterogenic processor architectures. To reduce development time and to ease a complex design implementation, HLS environments have raised the level of abstraction beyond RTL (i.e., by using high-level languages such C/C++ or OpenCL) and following a domain-specific approach, while mixing ad hoc software and hardware abstractions, making harder performance optimizations. Furthermore, design portability is strongly impacted when changing from one HLS environment to another, due to their specific dependencies on custom data type, hardware support IPs, and compiler-specific ”pragmas” [6]. BORPH [7] implements an operating system level support for FPGA-based reconfigurable computers. It introduces the concept of hardware process which is the same as normal UNIX process, but execution is handled by hardware circuits on FPGA. Under BORPH, hardware and software share the same familiar UNIX interface and the same level of support from the OS kernel. An application using BORPH is composed of a collection of files, to implement a predetermined number of processes, that can be software or equivalent hardware processes. The framework is composed of a kernel module and a user Application Programming Interface (API) that provides the set of system calls to interact with the computing resources. The kernel module is responsible for the request handling that mainly correspond to the allocation and configuration of the hardware resources. The API includes a series of system calls that implement a message passing interface allowing a hardware process to access data files or to communicate with other processes using pipes. In design terms, a hardware process is a BORPH executable binary file (BOF), that contains information about the resources. By extending the standard Linux kernel to accommodate the hardware process, it conflicts with its evolutive nature, demanding for a continuous updated patching of the Linux source. No hardware interface is established and the communication is based on passive hardware regions that are populated into the Linux procfs , under the process identification (pid) folder. In doing so, a new folder is created with any new execution, thus creating different virtual file locations that are unpredictable to the application. FUSE [8] implements a framework to abstract HW accelerators and design PetaLinux-based embedded systems. It provides a POSIX compliant thread model that can be implemented using software or hardware resources. To abstract the accelerator model to the software application, it relies on the Top-Level FUSE Component (TLFC) and the Low-Level FUSE Component (LLFC), that operate at Linux user and kernel spaces, respectively. The TLFC is as software library that provides thread creation, initialization, Chapter 1. Introduction 9 scheduling and destruction. It also implements a set of functions to interact at the LLFC using the OS interface. The LLFC is a kernel module that acts as low-level abstraction and is responsible for the communication, synchronization and monitoring of the hardware tasks. Each hardware task is coupled with an accelerator interface that is orchestrated by the LLFC module. For every such interface, a loadable kernel module is created dynamically at runtime and LLFC maps each hardware interface as peripheral I/O devices. Communication is implemented on the software side, exchanging data using operating system services and thus forcing the hardware task design to a passive coprocessor model. FOSFOR [9] is a framework that implements a transparent abstraction layer for applications following the Synchronous Data Flow model, deployed on System on Chip architectures. The underlying platform is composed by a combination of reconfigurable hardware regions (RR) and the required number of general purpose processors (GPP)s. It considers a Synchronous Data Flow model description and an architectural mapping to describe associations between processing units and actors. The implementation is based on C/C++ language for the software, and VHDL descriptions for the hardware-based components. The resulting synthesis is a hardware design used to configure the FPGA and perform the actual computation. It implements the concept of hardware threads, that are composed of a static component responsible for the communication, providing local resources and associated control interfaces. A dynamic part is used to implement the application related design. For this, Flexible OS was selected as hardware operating system and RTEMS was chosen for the management of the software parts. A middleware layer implemented using hardware and software parts establishes a single programming interface. It abstracts both implementation and mapping, and offers some mechanisms like the accesses to OS services and the inter-process communication. Focusing on the synchronous data flow model, system portability increases, but communication efficiency becomes a system performance bottleneck. SPREAD [10] provides a point-to-point streaming oriented programming environment, for architectures with reconfigurable components. It is a thread-based approach where hardware tasks are encapsulated into threads that resemble the POSIX programming interface. It considers three basic operations performed by each thread, in getting the application-related data, the computation itself, and then providing the processing results to the next thread. To facilitate switching between hardware and software, a software delegate is created, and is responsible for the monitoring of the hardware thread on the software side. A Hardware Thread Interface (HTI) abstracts the hardware thread design and enables communication between hardware and software as well as between hardware threads. Streaming channels can be 10 Chapter 1. Introduction dynamically interconnected at runtime, to provide inter-thread communication. Depending on whether the execution resource is hardware or software it provides three distinct communication channels. When both threads are implemented in software, the communication is implemented using memcopy function. When implemented on hardware, they communicate directly using FIFOs that are synchronized by the HTI. Lastly, when a software and hardware threads need to communicate, they use a Direct Memory Access (DMA) point-to-point connection. A hardware thread manager is also provided to handle hardware threads and is responsible for their creation and termination. Unlike previous frameworks, SPREAD is an integrated solution specifically developed for streaming application design. It does not allow “one-to-many” and “many-to-one” streaming interconnections, which are more common but not so easy automate. The hardware task programming interface is centered around the passive coprocessor model, where control unit blocks waiting for input data, executes processing upon arrival, and concludes producing results on the local resources and signaling the software execution. ReconOS [11] implements an operating system that extends the software multi-threaded programming model to reconfigurable hardware. From the programmability point of view, it provides an API close to the POSIX programming model where threads can be executed either on CPU or in reconfigurable hardware. Software threads can be implemented using the POSIX library and synchronized using semaphores, mutexes, condition variables and mailboxes. Hardware threads are abstracted by the OS interface (OSIF) that implements synchronization and communication mechanisms. An indexing scheme is also used to implement resource sharing. The software-level inter-thread communication is implemented using shared memory, while communication between hardware and software uses a message-based exchange model. Thread memories are shared leaving consistency and coherence hazards to be handled by the programmer. Such constraint penalizes the performance in the overall system by the increased use of interrupt events and consequent latency involved. Zongwei Zhu et al. [12] proposes a task scheduling framework on the DPR-based platform that exploits the hardware task cycle accuracy and task preemption overhead to improve scheduling efficiency. The framework is based on general OS and takes the full consideration of the preemption overhead, the reconfiguration time and hardware tasks’ cycle accuracy. The scheduling method is based on the predictable execution time of hardware tasks in DPR to improve scheduling efficiency of the whole system. The hardware task participates in the scheduling of the OS through the associated delegate thread and optimizes the task scheduling model, thereby reducing both the number and the overhead of task context switch. Chapter 1. Introduction 11 FOS [13] provides an OS that adopts a modular FPGA development flow, to allow each system component to be changed and be agnostic to the heterogeneity of EDA tool versions, hardware and software layers. It dynamically maximizes the utilization transparently from the users by using resource-elastic scheduling to arbitrate the FPGA resources in both the time and spatial domain for any type of accelerators. Moreover, FOS can switch between different accelerator implementations on the fly in order to balance resource allocation for the best performance and load scenarios. It provides an application-centric view to the developers by hiding most of the complexity encountered when using a heterogeneous CPU-FPGA acceleration system with a Linux backend. A user level daemon is responsible for managing FPGA resources and initiate scheduling operations. Updating individual components includes the latency of the partial reconfiguration that ranges from 3.8 to 6.8 milliseconds to replace one hardware accelerator, or 20.7 to 98.4 milliseconds to replace the entire FPGA shell. It abstracts the software design perspective but disregards the efforts required to semantically integrate the hardware accelerators in the application, mapping them by its hardware regions and considering accelerators as passive coprocessors. A design methodology is also proposed but it lacks co-simulation or full-simulation supports to validate the accelerator nodes in the application. Hoang-Gia Vu et al. [6] propose a hardware task migration scheme assisted by (1) a checkpointing architecture for FPGAs that flattens the structure of nested modules at the hardware description language (HDL) level, (2) a static analysis of the original HDL source code to reduce the cost of hardware and (3) Python-based tool to generate the checkpointing architecture at the HDL level. In the hardware task migration scheme the checkpoint procedures overlap data transfers to minimize downtime to 1.251 milliseconds in the worst-case scenario. When compared to the original design, clock degradations observed vary from 9.73% to 0.15% averaging at 1.66%. The design is limited to a single-clock domain and yet to be ported across different FPGA vendors. Coyote [14] is a configurable FPGA “OS” for hybrid compute servers, designed mainly for reflecting on the performance and efficiency benefits of importing OS abstractions wholesale to FPGAs. It goes beyond ReconOS’s deep semantic integration by supporting secure spatial and temporal multiplexing of the FPGA between tenants, virtual memory, communication, and memory management inside a uniform execution environment. The overhead of Coyote is small and the performance benefit is significant, but more importantly it allows us to reflect on whether importing OS abstractions wholesale to FPGAs is the best 18 Chapter 2. Design Methodology The platform selection is the last phase in the design flow and it occurs when all software and hardware components are fully developed and well consolidated, closing the development phase and sentencing the application to the underlying hardware. To assist in this design stage, the tool provides a Full simulation model that being based on the previous co-simulation principles, it considers the full hardware and software layers in the system. For that, it selected a platform emulator such as QEMU [23], and extended the QEMU functionalities to the surrounding simulation tools. The full simulation model will provide the user with a clear view of the application deployed to the target platform, and it will assist this development stage in addressing any potential glitch that can simultaneously conflict with the Application, the OS and the underlying hardware units. It will allow the user to strip down the several levels of implementation in the system and debug each one as an integrated part, as opposed to the efforts of reproducing a failure in isolated test fixture. For completeness, the platform binaries are also validated and usually the Buildroot [24] tool is used to provide the host with the necessary software packages. The target validation will proceed beyond this design flow and the designer will confront the developed solution with the initial design expectations. At this stage, any significant change to the system usually represents a costly decision, that will ultimately result in quality degradation. The main concern of this design methodology was to mitigate the technological gap between the hardware and software concepts, ease the programmability to explore the synergies between the hardware and software concepts, and provide the designer with the means to quickly integrate the implemented hardware units with the application, but also, care was taken to provide the user with the necessary level information that will allow anticipation of potential problems in the early stages of design where they are properly addressed. 2.2 Programming model In this thesis, an object-oriented multithreading programming model is proposed for HAL-ASOS framework. One that integrates software threads and hardware accelerators in a unified and customized design, that will assist the development in partitioning the application and offloading the critical workload functionality to the accelerator model. The purposed programming model follows the standard of Multithread Programming Models for C/C++ applications on Linux OS, where the elementary processing units are implemented by the software threads. Chapter 2. Design Methodology 19 A software thread usually represents a precise flow of execution inside an application, and is commonly delimited by the smallest sequence of programmed instructions that can be managed independently. In the majority of cases, this flow explores the code cyclic use and for that reason the execution is restricted within an application dependent loop. They can be seen as an integrant part of a process that executes concurrently with other threads in the same application and share memory resources. A multitude of threads in the same application can implement a parallel model that aims to promote the efficient use among the many sources of computation in the system. The purposed model is centered around the class Task that symbolizes the thread in the traditional programming model. The Task can be semantically interpreted as software task that maps to the traditional thread, or as hardware task that is deployed into the accelerator model. Figure 2.2 shows a simplified UML of the class Task . It can be seen that the implementation is based in the C++ templates metaprogramming and by using specialization we address the configurability inside the application model. The class template qualifiers range between a predefined and a variable template pack that allows the user to configure and extend qualifiers to the application needs. The template parameter pack will be evaluated and matched to the available class implementations during the compilation phase. TaskConfig_t +Subscription: TopicConfig_t ... +TaskTag: std::string +Publication: TopicConfig_t +Resources: ControlResources_t Task <Type,Config,Args...> -p_Topic: dds::Topic -run():void +start():bool -Native: std::thread -p_Subscription: dds::Subscription ... -unconditional_shutdown():bool ... TaskType_t Type TaskConfig_t Config Semantics_t Semantics CommProfile_t Profile CommProfile_t enum UserIO StandardIO Semantics_t enum Shared TaskType_t enum HwTask SwTask +join():bool SharedResources ZeroCopy CoSimulation Emulator Restricted Figure 2.2: Simplified UML diagram of template class Task . Any instance of the class Task demands a specialized run() member and a unique configuration that links to the class parameters (i.e., TaskConfig_t ). This configuration includes a string Tag used for identification and log messages, a Topic and a Subscription setting, and a predefined set of members that address resource allocation inside class members. 20 Chapter 2. Design Methodology The use of the SwTask as Task qualifier will match the class with an implementation that assigns the Native thread execution to a specializable run() member. The alternate HwTask qualifier will select an implementation that assigns the Native thread to the class internal services, as result of computation offload to the accelerator model. These services mostly include the boundary crossings between the software and hardware specialized circuitry while exchanging data between the class instance and the accelerator model, and to connect the accelerator with the Linux OS services. The Semantics qualifier establishes data exchange semantics between Shared or Restricted models. A shared model will allow multiple references for the task data while sharing results with other existing Tasks . The restricted model will enforce a unique instance of data that can only be collected by one Task instance despite being shared with any definable number of Tasks . The Profile qualifier will be matched in the HwTask specialized instances of the class Task and establishes the communication model with the hardware resources. The use of this qualifier affects the critical path and latency observed at the processing boundary crossings and it is limited to the predefined set. As an example, the qualifier StandardIO which is the default parameter will bind the class resource handling with the traditional set of Linux system calls and exchange data by use of the high and low memory regions. Alternately, the UserIO qualifier will reduce the usage of the system calls and map the hardware resources into the application address space. Throughout the application development several crossed configurations can occur. The multitude of qualifiers combines specialized implementations at different layers of functionality. It is fair to say that for a specific application scenario the correct configuration might not exist. Instead, an optimized solution that explores the distinct trade-off(s) between different class implementations will be achieved. One that during the design space exploration is found to be the best solution for the desired performance metrics within the specificity of the application requirements. 2.3 Application Development When creating applications, designers usually start with an idea in mind, a solution to a problem, an identified market need, or a technological vision to improve existing solutions. Generally, at this early stage of development, there is no reasonable expectation of what the application will be. To maximize creativity, designers should start by a quick prototype development, to rapidly envision the application and Chapter 2. Design Methodology 21 what the outcome results need to be, before facing any restrictions imposed by the commitment to the hardware and software stacks. When we observe of most today’s common computer applications, we realize they are internet-aware, and use the internet to exchange data, by using cloud services or any form of private servers. But within the Internet connectivity, applications are facing a growing need for security, leading developers to rely on complex cryptographic algorithms, that target specific requirements not suited for implementation in the most generic embedded devices. Traditionally, designers use standard encryption algorithms to cope with security needs and a common example is the use of the Advanced Encryption Standard (AES). The AES is a well-established algorithm that operates on blocks of 128-bit plain data, and is available in three different cipher lengths: 128, 192 and 256-bit [25]. It is classified as symmetric-key algorithm which means that the same cipher is used for both operations, encrypting and decrypting the source data. Each of the 128-bit blocks represents a 4x4 bytes matrix, also designated by state Si, where iis the consecutive block number in {1, ..., n}blocks of data. Figure 2.3 helps to illustrate conceptual implementation of the AES-128 algorithm. Plain data Ciphered data Cipher key Round keys 1 - 9 Round key 10 Final Round Shift rows Substitute bytes S(i,j) Add round key [i,j] Round 9 Shift rows Mix columns .C(x) Substitute bytes S(i,j) Add round key [i,j] Initial Add Add round key Rijndael key schedule Figure 2.3: Overview of the AES-128-bit algorithm. Using the Rijndael key schedule, the input cypher will be expanded into ten additional ciphers and used in the successive rounds that establish the encryption/decryption algorithm. As so, the encryption of a state Sican be summarized to one initial adding operation, using the input cipher, and ten subsequent rounds using one of ten expanded ciphers. The rounds one to nine are identical and include four stages, namely: substituting bytes; shifting rows; mixing columns; and adding the round cipher. The state Si encryption concludes with the tenth round, similar to the previous nine but skipping the mix columns stage. Implementation details about the AES-128 can be consulted in the Appendix E. 22 Chapter 2. Design Methodology We will consider the example of an application that needs to upload files through the internet and selects the 128-bit AES algorithm to enforce security. The example will target a generic embedded device here referenced as Machine 1. The simplified architecture for the Machine 1application can be decomposed into three processing threads: a ’File reader’, that polls on the OS file system for files, reads the file contents and fragments data into adequate size before submitting to the application internal structures; an ’Encryptor’ thread that implements the AES-128 algorithm, collects the fragmented plain data and converts them into ciphered data; and an ’Uploader’ thread that regroups the ciphered fragments and synchronizes the file transfers through the internet. Figure 2.4 depicts this organization. Publish(data) Publish(data) Plaint data 16 Bytes 16 Bytes MailBox MailBox 16 Bytes 16 Bytes 16 Bytes 16 Bytes Linux Userspace 16 Bytes 16 Bytes 1024 Bytes AES 128-Bit Network Data Distribution System (DDS) Thread: Uploader Thread: Encryptor Thread:File reader read(buffer,1024) Filesystem fragmentation regrouping write(bufffer,1024) Cipher key Subscribe(FileReader) Subscribe(Encryptor) 10110 111001 [4x4][4x4] [4x4][4x4] 16 Bytes 16 Bytes 16 Bytes 16 Bytes 16 Bytes 16 Bytes ciphered data State_t State_t Figure 2.4: Machine 1application - task graphical representation. This example gravitates near the data-centric class of applications, where data is the main concern to the system and they tend to view data manipulation as the most important part of the work. Consequently, threads will need an efficient way to exchange data and for that we will use a Data Distribution System (DDS) provided as part of the HAL-ASOS framework. The DDS will link threads through an exchange model based on Publish-Subscribe, where the ’FileReader’ will create a topic that is subscribed by the ’Encryptor’ thread and consequently, this thread creates another topic that is subscribed by the ’Uploader’ thread. The DDS implementation follows a low-memory footprint model, where the multiple attempts on creating the same topic will result on copied references of the same object. If a multitude of subscribers exist in Chapter 2. Design Methodology 23 one topic, they will receive memory references of the same ’const’ data. The memory resources involved are allocated by any of the topic publishers, and later released when a subscriber attempts to destroy the last memory reference. 2.4 Software refactoring For the Machine 1application, the thread ’File reader’ will create a topic named FileReader using the DDS services. Continuing with processing, all the thread results will be published in that topic. The thread ’Encryptor’ will subscribe the FileReader topic and will periodically receive any published data to that topic. Similarly, the ’Encryptor’ thread will create a topic named Encrypted that is subscribed by the ’Uploader’ thread. The ’create topic’ and ’subscribe topic’ operations consider a numeric tag for identification that is created from hashing the TopicConfig_t members. The application code for the Machine 1is presented in Figure 2.5. #include "hal_asos.h" 9 #define HLEN (sizeof(state_t))//16 10 ... const hal_asos::TaskConfig_t TFRead = { "FileReader", //TaskTag 12 { "PlainData",HLEN,1,1 },//Topic 13 { "",0 }// No Subscription 14 }; 15 const hal_asos::TaskConfig_t TEncrypt = { "Encryptor", 16 { "CipheredData", HLEN,1,1 }, 17 { "PlainData",HLEN,1,1 } 18 }; 19 const hal_asos::TaskConfig_t TUpload = { "Uploader", 20 { "",0 }, 21 { "CipheredData",HLEN,1,1 } 22 }; 23 ... void hal_asos_demo::test_aes128_file_sw_threads(void) { 205 using namespace hal_asos; 206 207 Task<SwTask, TFRead> T0; 208 Task<SwTask, TEncrypt>T1; 209 Task<SwTask, TUpload>T2; 210 211 T0.start(); 212 T1.start(); 213 T2.start(); 214 T0.join(); 215 T1.join(); 216 T2.join(); 217 } 218 Figure 2.5: The Machine 1application - SW task version source code. Three TaskConfig_t structures were specified for each of the Tasks (lines 12 to 23). The ’File Reader’ and the ’Encryptor’ tasks will create the ’PlainData’ and ’CypheredData’ topics respectively, and use the same topic length specified by the ’HLEN’ macro. Each class instance will link with the TaskConfig_t 24 Chapter 2. Design Methodology structure by template parameter (lines 208 to 210). Using the SwTask qualifier, all class instances were parametrized for software resource as result of initial development iteration. Not all qualifiers and configuration parameters were specified and default values predefined by the framework will be used. The task start() member will assign the native OS thread execution to the class specialized run() member. The execution will join() threads until completion of all operations and terminates releasing the allocated resources. 2.4.1 The File reader task The algorithm for the ’File reader’ task consists of: reading blocks of plain data from the input file; fragment these into adequate size of 128-bit (16 bytes); and publish the resulting fragments in the DDS topic (line 59 to 66). The specialized run() member for the class ’File reader’ can be consulted in Figure 2.6. For simplicity, some lines were omitted and the full listing can be consulted on the Attached Listing:C.2. #define HLEN (sizeof(state_t)) 10 #define BLOCK_LEN 1024 11 ... template <> 26 void hal_asos::Task <hal_asos::SwTask, TFRead>::run(void) { 27 std::ifstream input_file; 28 std::shared_ptr<char[HLEN]> p_buff; 29 char* p_local_buff; 30 int InputFileSize, read_len, i, count = 0; 31 ... input_file.open(target_file.c_str(),ios::in|ifstream::binary); 33 ... input_file.read(p_local_buff+sizeof(int),(BLOCK_LEN-sizeof(int))); 53 ... while (this->StatusRunning && Read_len > 0) { 56 for (i = 0; i < Read_len; i += HLEN) { 57 p_buff = std::shared_ptr<char[HLEN]>(new char[HLEN]); 58 copy_len = mmin(HLEN, (int)(Read_len - i)); 59 std::copy_n(p_local_buff + i, copy_len, p_buff.get()); 60 this->p_Topic->publish(p_buff); 61 count++; 62 } 63 input_file.read(p_local_buff, BLOCK_LEN); 64 Read_len = (long)input_file.gcount(); 65 } 66 input_file.close(); 67 this->p_Topic->close_topic(); 68 LOG_MSG << this->TaskTag << "finished...(" << count << ")\n"; 69 delete[] p_local_buff; 70 } 71 Figure 2.6: File reader task - simplified run() member. An input file containing one million digits of pi (“3.”+1.000.000 digits) was selected as source of data and is open for read in line 33. Once in the “main” loop, the thread will read successive blocks of 1024 bytes from the source file, fragment each block into smaller 16-byte blocks and publish the resulting data in Chapter 2. Design Methodology 25 the DDS topic (lines 58 to 61). After reading all source file content, the thread will exit the main loop by failing the condition at line 56 ( Read_len > 0 ) and close the file and the DDS topic (lines 67,68). A closed topic will allow the subscribers to consume the remaining publications. The thread concludes issuing a log message that prints the number of blocks processed and releases all the allocated resources (line 67 to 70). 2.4.2 The Encryptor task The simplified code for the ’Encryptor’ task run() member is presented in Figure 2.7. Similarly, the full listing can be consulted attached in Listing C.1. template <> 81 void hal_asos::Task <hal_asos::SwTask, TEncrypt>::run(void) { 82 std::shared_ptr<dds::Publication> pLocal; 83 std::shared_ptr<char[HLEN]> p_cyphered; 84 std::shared_ptr<const char[]> p_plain; 85 ... set_cypher_key(key); 90 key_expansion(); 91 92 while (this->StatusRunning && ret > 0) { 93 ret = this->p_Subscription->take_publication(pLocal); 94 if (ret) { 95 ... p_current_state = (state_t*)p_cyphered.get(); 101 add_round_key(0); 102 for (round = 1; round < NROUNDS; ++round){ 103 subst_bytes(); 104 shift_rows(); 105 mix_columns(); 106 add_round_key(round); 107 } 108 subst_bytes(); 109 shift_rows(); 110 add_round_key(NROUNDS); 111 ret = this->p_Topic->publish(p_cyphered); 112 } 113 } 114 ... this->p_Topic->close_topic(); 116 this->p_Subscription->terminate_subscription(); 117 LOG_MSG << this->TaskTag << "finished.(" << pcount << ")\n"; 118 } 119 Figure 2.7: Encryptor task - simplified run() member. The input cipher is set and the key expansion schedule is executed (lines 90 and 91). Once in the main loop, the thread will collect 4x4 bytes (Si) of plain data from the DDS subscription (line 94). The ten rounds that complete the AES-128 algorithm will encipher the received plain data, and the iteration of Siconcludes with publishing the resulting data (ciphered data) in the DDS topic (lines 102 to 112). A negative return or a null ’ pLocal ’ pointer in the take_publication call (line 94), will force the execution to 26 Chapter 2. Design Methodology break the main loop (line 93). The thread concludes closing the topic, terminating the subscription and issuing a log message that prints the number of blocks processed (lines 116 to 118). 2.4.3 The Uploader task The simplified code for the specialized run() member of the task ’Uploader’ is presented in Figure 2.8. The task uses the name space networking from HAL-ASOS framework that provides eased access to the OS network subsystem. An instance of CSocket<Client> will be used to establish a connection with a network server for uploading files. A successful connection will allow the thread to proceed into the main loop (lines 157-171). The main loop consists of receiving ciphered fragments from the DDS subscription template <> 134 void hal_asos::Task <hal_asos::SwTask, TUpload>::run(void) { 135 using namespace hal_asos::networking; 136 int ret = 1, count = 0, index=0; 137 char* p_local_buff; 138 std::shared_ptr<const char[]> p_buff; 139 std::shared_ptr<dds::Publication> pLocal; 140 CSocket<Client> Soc; 141 ... this->StatusRunning = Soc.open_connection(); 157 while (this->StatusRunning && ret > 0) { 158 while (index < BLOCK_LEN && ret > 0) { 159 ret = this->p_Subscription->take_publication(pLocal); 160 if (ret) { 161 p_buff = pLocal->get_reference(); 162 std::copy_n(p_buff.get(),pLocal->get_len(), p_local_buff + index); 163 index += pLocal->get_len(); 164 count++; 165 } 166 } 167 if (index > 0) { 168 ret = Soc.safe_write(p_local_buff, index); 169 index = 0; 170 } 171 } 172 Soc.close_connection(); 173 this->p_Subscription->close_subscription(); 174 delete[] p_local_buff; 175 LOG_MSG<<this->TaskTag<<"finished...("<<count<<")\n"; 176 } 177 Figure 2.8: Uploader task - simplified ’run()’ member (full listing:C.3) and regrouping data into a network-adequate block size by using local_buffer (lines 159-167). Once local_buffer is complete the results are transferred over the network (line 169). A negative return on take_publication or a network communication error, will break the main loop by failing the condition ’ret > 0’ on line 157. The thread concludes closing the network connection, terminating the subscription and issuing a log message that prints the output results (lines 173-176). Chapter 2. Design Methodology 27 2.4.4 Functional validation The application for Machine 1was selected for compilation at Host environment using Linux OS. Similarly, a second machine, Machine 2, was configured with a server application to provide a connection and receive the encrypted data. Details of the Machine 2 application are out of discussion in this thesis but. Machine 1, using the network subsystem with IP 192.168.1.11 , connects with the Server application on Machine 2for uploading the encrypted file 1M_digits_of_pi.txt . The output results of this test are presented in Figure 2.9. The log messages from the three Tasks , in Figure 2.9, indicate that 62,501 Figure 2.9: Machine 1 - SW-only application output for one million digits. blocks were processed and resulted in a file length of 1,000,016 bytes. The input file 1M_digits_of_pi.txt contains 1,000,002 bytes and the output exceeds this value in 14 bytes, as result of including a minimal header that indicates the file length and some padding to align the number of fragments with the state matrix length. At Machine 2, using IP 192.168.1.200 , a connection was accepted and the file was received successfully. The application log from this test can be consulted in Figure 2.10. The received data resulted in an Figure 2.10: Machine 2- Server application Output. encrypted file containing 1,000,016 bytes that was stored in the encrypted_file.dat file. The Inverse 34 Chapter 2. Design Methodology Core implementation results in a static unit that is independent of the HW-Task implementation and can be configured or changed by applying microcode updates. A service-level datapath includes (1) a dual-port and bi-directional message-queue used for messaging control information within the host system services, (2) a dual-port bi-directional data-FIFO available for HW-Task generic use (3) a Local Interrupt Controller (LINTC) that allows synchronization with the Linux OS, (4) a true dual-port generic purpose Local RAM (LRAM) for data exchange and temporary storage, and (5) two dual channel HW-Mutexes that implement mutual exclusion with the accelerator model. The latter are directly coupled with the LRAM and a system memory region allocated at boot-time. At kernel-side, dedicated interfaces are used to manage each of the HW-FIFO , while the remainder of the functional units are accessed through custom Local-Bus . The M00_System interface is used to access a kernel-specific region in the host system memory. S00_Control and S01_Data offer the control- and data-oriented transfer interfaces for host system accesses to the HW-Kernel functional units. The S01_Data implements a byte-oriented bidirectional interface used exclusively to access the LRAM. The reminder of the functional units, link to the S00_Control in a bidirectional register type interface. The complete set of units that integrate the HW-Kernel model are also parametrizable and are made available to the host system through the Linux integration model. 2.6.2 Hardware Task model The Hardware Task model provided by the HAL-ASOS accelerator follows traditional architecture modelling techniques. The design can be partitioned in a Control Unit and a collection of user-defined functional units that compose the Datapath. Figure 2.16 presents a simplified model of the HW-Task . The Control synchronizes the task internal implementation while the Datapath implements the task algorithm. Using the HAL-ASOS VHDL packages, the Control can also synchronize externally with the other tasks in the system. Mainly, these packages provide a set of services that are divided into user- and kernel-levels. The user-level implementation, considers the task-related functionality and only uses local resources, while the kernel-level considers a more service-related implementation, where it is allowed to talk to the local hardware or system resources, including the Linux OS. Both the user and kernel services are manly implemented using VHDL procedures and the HW-Task will link the datapath to each procedure implementation. A VHDL procedure, denotes a subprogram description that is implemented in zero simulation time. It differs from the VHDL functions, in the sense that, it Chapter 2. Design Methodology 35 HW Task kernel-level packages M01_TaskS01_Kernel user-level packages ALU start s1 done Datapath system call entry system call return parameters return parm. ret. data in data out Control Unit Start Error Done S1 S2 call return ret. syscall block kernel_response kernel_call Extended Features Figure 2.16: Hardware Task simplified model. can receive parameters as input and output, and using signal driver capabilities, manipulate values that exist outside the subprogram. To accommodate the complexity of each procedure, the kernel provides generic FSMs for each of the RTL layers being concurrently executed. In doing so, the task description scales, implementing procedures from the user or kernel packages. At user package, each procedure is implemented using functionality-based procedures from the kernel package. While executing, the kernel_call interface will be updated by the procedure RTL and the kernel will execute HW system calls accordingly. Generically, once the HW-Task control-path implements a procedure call, the Control unit is blocked and the synchronization is transferred to the Kernel Core control. The procedure will execute in a predetermined number of clocks that depends on each distinct implementation and value of the passed parameters. These parameters will be copied or forwarded to the procedure circuitry accordingly, and at completion, an exit path will ultimately enable back the task Control Unit. The kernel package uses the kernel_call and kernel_response registers, that link to the HW-Kernel system call infrastructure using M00_Task and S00_Kernel interfaces. A template for the HW-Task design is provided, and it includes a minimal control FSM with blocking functionality. The designer will then extend the FSM states to accommodate the HW-Task algorithm description. The implementation details of the HW-Task , the RTL packages or the HW-Kernel will be best discussed in Chapter 3. 36 Chapter 2. Design Methodology 2.6.3 Linux Integration The HAL-ASOS Accelerator model integrates with the target platform OS at user- and kernel-levels. Due to the myriad of functional units in the model, a proper OS support requires a collection of device-drivers that efficiently export each functionality into the Linux user-space. Such a collection of drivers is best organized through a customized File System(FS). Figure 2.17 presents the HAL-ASOS FS structure. \hal-asos Accelerator_0 Accelerator_1 hal_asos_resources interrupts kernel performance counters local-ram message-queue-size message-queue-space lram-mutex sysram sysram-mutex message-queue data-fifo-space data-fifo-size data-fifo lintc local_interrupt_0 local_interrupt_1 local_interrupt_2 local_interrupt_7 user_interrupt_0 user_interrupt_22 local-kernel transfers-shared-mem transfers-zero-copy mcode.bin ... … 101101 110011 000010 Figure 2.17: HAL-ASOS file system structure on Linux. The HAL-ASOS file system mounts during Linux start-up and it can be found at the root of the Linux file system in the hal-asos folder. Any existing accelerators will be extracted from the device tree information that results from the deployment phase, and mapped into individual Accelerator_x folders. The folder name results from a configurable name tag in the accelerator listing, and a sequence number that counts the instances using the same tag. Inside the accelerator folder, the structure is organized in a kernel folder, an interrupt folder and a sub-set of virtual files that map the remainder of functional units in the Accelerator model. These include: the LRAM and the local-mutex (LMUTEX); the system memory region (i.e., sysram ) Chapter 2. Design Methodology 37 and associated hardware mutex ( sysram-mutex ); the HW-Kernel message-queue with read-only size and space files; and similarly, the data-fifo with the size and space files. The interrupt folder contains the virtual files that provide the synchronization between the software threads in the system and the accelerator. The lintc file represents the local interrupt controller and it uses seven native interrupts that are mapped to the local_* files. Since a configurable number of user definable interrupts is also available, up until twenty-four user_* files can be present in this directory. Some of the FS functionality demand proper registration by using the local-kernel file in the kernel directory. The registration is based on exclusive ownership model and the local-kernel initializes a private structure containing a 32-bit key automatically hashed. The transfer_* files map distinct profile interfaces between the software framework and the accelerator model, and the mcode.bin file is used to update the Kernel Core microprogram. These features will require validation using the previously generated key or otherwise will be denied. A performance counters folder will be found if the accelerator model is active for performance metrics. Generally, these follow a hardware event counter model, coupled with synchronous clock timer model, that register the number of events and associated latency across the HW-Kernel functionality. One file for each active performance counter will be found in that directory, and reading them or using a ’ cat ’ command from the Linux bash, will output the current performance results in a conveniently formatted text message. The Performance functionality will be best discussed in Chapters 4 and 5. At the application-level, to efficiently handle the exported model, the software framework provides the class Proxy that maps the FS functionality into a resource-oriented set of operations. A Proxy member will be found in all class Task instances that were specialized for HwTask . The transfer profiles are differentiated using distinct Proxy implementations that explore the different interfaces provided by the FS. The HAL-ASOS file system is a Linux functionality provided by the framework and exists only in the target generated platform binaries, mostly because of its hardware and device tree dependencies. For that reason, it will only be available on the System implementation phase, or alternately, when applying the Full simulation model to the platform binaries, in the deployment phase. When compiling the application for the development host, an emulated version of the file system is implemented by the Emulator model. 38 Chapter 2. Design Methodology 2.6.4 Emulator Model The Emulator model is a framework feature that assists in mapping the pre-selected candidates to computational offloading into the HW-Task structure. By using a software development perspective, it promotes a more flexible environment that exposes the task algorithm requirements and consolidates HW-Task interoperability in the application. This stage establishes a design iteration that aims to create a control algorithm that fits the application requirements and it is close to the RTL specification. The Emulator Model is composed by a set of function-oriented entities that can be divided in two implementation layers: (1) the HW emulation layer, that includes the Accelerator described above; and (2) the software layer that emulates the Linux integration in the HAL-ASOS file system. This model follows a design approach that took the effort in describing the implementation details and available interfaces on each functional unit, and can ultimately be considered as a software description of the HW counterpart. The Emulator model is a C/C++ functionality implemented by the ’ hal_asos::emulator ’ namespace , and considers a unified implementation with purposed programming model. Figure 2.18 shows a simplified UML class diagram for the first layer. In that figure, it can be seen that the AcceleratorModel class integrates the HwTaskModel class and the HwKernelModel class, and the three altogether form a template model qualified by the accelerator configuration. For simplicity, the following section will refer the Emulator model entities by the name of their representative hardware counterparts. The user packages are private members of the class HW-Task and a similar implementation can be found in the HW-Kernel , with respect to the kernel packages. A C++ Friend definition will allow the HW-Task to access the private parts of the HW-Kernel and talk directly with the kernel packages. The HW-Task plays the central role in the emulator as it stimulates the model using its Native thread member. Among other internal code, the thread loops using the run_iteration member, that considers the processing in an equivalent clock cycle of the HW-Task . The successive calling of this member will iteratively progress the task algorithm code. The designer will provide a specialized run_iteration member that contains the task algorithm implementation, and since it is using the same configuration as template qualifier, it will be linked to the class unique code. A call to any of the user package members will ultimately result in a kernel HW system call, and the execution proceeds by copying the parameters to the member KernellCall that binds the two classes. When executing the HW-Kernel member execute_sys_call , it will transfer execution to the kernel model and the system call will be implemented. Any data exchange or control updates in the kernel set of Chapter 2. Design Methodology 39 AcceleratorModel<Conf> ->PlatformDevice -LocalKernel:HwKernelModel -Task: HwTaskModel ... Platformdevice HwTaskModel <Conf> -safe_read_lram(...):int +device_init(void):int +device_write_word32(...):int ... HwKernelModel <Conf> AccConfig_t Conf +execute_sys_call(void): void -Lintc: HwIntcModel AccConfig_t Conf ... -LMutex: HwMutexModel -LocalRam[]: char -safe_read_write(...):int -task_run_iteration(void):void -Native: thread ... task_init(void): void -kmutex_lock(void): void -klram_read_word(...): void +p_Syscall: KernelCall* +SysRet: KernellReturn ... +Syscall: KernelCall +p_Sysret: KernellReturn* ... AccConfig_t Conf -TaskState: state_t Figure 2.18: Accelerator Model Emulator - Simplified UML class diagram. functional units will be performed. At conclusion, the resulting data will be found in the KernelReturn member and the execution returns to the HW-Task At the Host system, the Accelerator is accessed via PlatformDevice . This structure encapsulates the model representation in a common form, and similarly to the Linux device model, interfaces the Accelerator via read or write set of operations that is used by SW Layer of the Emulator. 2.7 Computational offloading In this design stage we leverage the computation offload by applying a two-step HW description. We begin with the specialization of the HW Encryptor task that includes the selected candidates from the profiling phase. We then apply the Emulator model to ease the HW partitioning and gain perception about the new task implications, and once completed, we apply the Accelerator model and proceed to the hardware description stage. At completion, we verify the design by applying the Co-Simulation model and establish a unified simulation environment, where this new application snapshot will be validated. In a real design scenario, multiple attempts to map application functionality are most likely to occur, and can result from metric-driven improvements or control algorithm refinements. But to reduce the design iteration on this example application, we anticipate two decisions before proceeding into the computation offload phase. First, using a behavioral modelling style, we will describe the HW-Task and map the 40 Chapter 2. Design Methodology pre-selected candidates with minimal application refactoring. The task control unit will also be described following a close to emulator description style. Then, the resulting accelerator will be functionally validated using the co-simulation model. And finally, to conveniently explore the interaction between the Accelerator model and Host system, we will execute another design iteration and offload the file and network socket functionalities into a unified HW-Task design, that assumes the role of a standalone (SA) task in the application. These two functional units will be confined to specific accelerator implementations that will proceed in the design flow until the System implementation phase, where they will be evaluated and compared. To distinguish the HW from the SW counterparts we will be referring these tasks as the HW Encryptor and HW Encryptor SA. 2.7.1 Hardware specification When we look at the source code of the Encryptor task in Figure 2.7, we realize that generically, the thread is polling for data using the DDS subscription and, at arrival of such data, it will be encrypted and published back to the DDS topic. As soon as the subscription expires, the thread will break the loop and terminate the execution. To map this outline into the Accelerator model, the best use of resources demands that we use the Accelerator data channel to exchange data with the DDS subsystem. This exchange is implemented by a combination of service request, that use the HW system calls in the accelerator and the Linux kernel system calls, to synchronize the HW-Task with the application functionality. To minimize the resulting computation overhead on the Host side, we maximize the transfer length involved, thus lowering the number of requests per-file and consequently lowering the synchronization events at the Linux kernel. The first design decision will be to properly handle data in blocks of 1024 bytes that will be stored in the Accelerator’s Local-RAM. To extract individual fragments of 128-bit (16 bytes) of plain data, we will specify the first loop of the HW-Task and name it encrypt loop. We will call this the inner-loop. Numerous block transfer requests may be necessary until the file is exhausted, as so, we will use a second loop and call it exchange loop. Since the file contents might not conform with the block alignment, at every request iteration we will check how many bytes were effectively transferred, and proceed in the exchange loop with a new target value. For now, we decide to use a target length counter, and to comply with the task final message informing the processing results, we will include another counter here referred as total counter. If we elaborate the set of identified requirements into a block diagram, we obtain the HW Encryptor datapath. Such diagram can be seen in Figure 2.19 and includes the connection with the Control unit. Chapter 2. Design Methodology 41 From that figure it can be seen that the input of the data-path is the return data from the HW system call and that similarly, the output data will be forward via HW system call. The two blue functional blocks represent the synchronous registry for local storage and we add a comparison unit to signal when the target and count contents match. The light red blocks represent the combinational units that are kept steady value using the synchronous registry. The white labelled blocks are mere representation of data that exists in those registers. AES128 RUN DONE key_expand plain_data cipher_key ciphered_data Target_len Count_len C_PLAIN_LEN + = Cipher Control Unit Kernel Call Kernel Response Datapath select select HW Sys.call HW Sys.call 1 Total_len + Figure 2.19: HW Encryptor Task - Simplified Datapath The AES-128 functionality can ultimately be accomplished by integrating any existing functional unit and to serve the purpose of simplicity we will resume the AES description to a top-level functional description. The conceptual implementation was extracted from the diagram depicted in Figure 2.3, and the data inputs and output can be observed here matching the signals in this top-level. The control signals of the AES-128 unit are: the key_expand , to expand the cipher in ten additional keys; and the run signal that triggers the unit execution. A done signal will inform control that the ciphered data is ready to be collected at the output. The AES design follows a twelve-clock pipeline design strategy but to simplify the task specification, this continuous mode of operation will not be explored. Details about HW description of the AES-128 can be consulted in the Appendix C. The Control Unit for the HW Encryptor can be implemented using an FSM-based design, integrating eleven states that sequence the necessary operations, in the true parallel nature of the HW implementation. Such 42 Chapter 2. Design Methodology design can be consulted in Figure 2.20. 0 #1 trans_from_dds #0 ready #2 eval_transfer #3 safe_lram_read #4 trigger_aes #5 wait_event #6 safe_write_lram #7 trans_to_dds #8 write_message #9 write_std_io #10 task_exit aes_done_i/ target_len > 0 Exchange loop Encrypt loop Figure 2.20: HW Encryptor Task - Simplified Control unit FSM The state zero is a mandatory state for synchronizing the HW-Task with the application and the Accelerator enters a sleep state when steady in state zero for more time that a parametrizable time constant. As soon as Control receives the run signal from the HW-Kernel , the task will issue the first request, demanding a transfer of 1024 bytes from the DDS subscription. The second state will evaluate the transfer result into a new target value and proceed to the encrypt loop. Any processing error would result in a negative or null target value that redirects the next state to the write message, thus concluding prematurely. The target length is accomplished with the state three to state six sequenced loop while the Control Unit is using the user package to: synchronously read blocks of 16-bytes (128-bit) of plain data, here referenced as parametrizable constant C_PLAIN_LEN, and after being submitted to the AES encryption; write the resulting ciphered data to the same address of the Local-RAM. One must say that the fragmenting and regrouping performed by the FileReader and the Uploader tasks are by now redundant. In the state four we trigger the AES execution and move to state five where Control issues a wait event system call. Similarly, the clock enable will be cleared and the designer needs to tackle this condition since it needs to keep the AES unit working. The Control unit will reach the seventh state with the counter value matching the target from the encrypt loop iteration, and it will conclude by issuing a request to transfer the block of 1024 bytes of ciphered data to the DDS topic, thus restarting the exchange loop. The state nine is achieved after failing the target value evaluation in s2, and preparing the message in the standard output format at the Local-RAM on state s8. The Control will issue a request to forward this Chapter 2. Design Methodology 43 message and concludes in the state ten, issuing a task_exit call from the user package. Beyond this call, the Control unit will not be available until a software reset is issued using local-kernel file in the HAL-ASOS file system. 2.7.2 Emulating Hardware Accelerators When modelling the behavior of the Encryptor using C/C++ languages and applying the Emulator model provided by the framework, one must take into account that the sequential statements of the C language will be implemented concurrently if modelling the hardware using HDL. With this idea in mind, care must be taken to avoid the use of temporary data that results from the current flow of execution. For the Emulator model, one clock cycle is implemented by the run_iteration call, and one execution of this function will produce results that can only be used in the next cycle. To develop an emulated Encryptor task we start by defining the configuration structure where we specify the accelerator parameterizable resources, namely: the size in number of words of the Local-RAM; the space in number of words in the control FIFOs; the number of parallel words exchanged between HW- Kernel , H W-Task and HW-FIFOs ; the number of user-defined interrupts; and the accelerator name or task tag. At the software-side of the application, the Task class needs to be reconfigured by the HwTask qualifier combined with the Emulator profile, and one accelerator entity needs to be instanced. Figure 2.21 shows the necessary changes to the application when using the Emulator model. The emulated accelerator is instanced in line 208 and uses the configuration as template qualifier. We extend the T1 template pack with the desired profile (line 213) and add one Virtual File System(VFS) instance with the purpose of listing the available accelerators when executing the application (lines 209-210). The specialized run_interarion member is presented in Figure 2.22 and is identified by the compiler using the HwEncrypter configuration as template qualifier. The majority of local variables need to be static to preserve data between successive calls that resemble the HW clock cycles. To abstract design from the AES-128 implementation details, we have included this functionality in C++ class (line 43). The FSM implementation uses a switch case block to re-evaluate the TaskState member at the beginning of each cycle. Every case entry will conclude by redefining the TaskStateNext value and the task iteration concludes with the assignment of the TaskState with this new value (not represented). In state s1 the Control transfers 1024 bytes to the Local-RAM address ’0h’ and stores the return value in the target length variable. In state s2 this new target determines the next state and, in state s3 the Control 50 Chapter 2. Design Methodology hal_asos_link_to_kernel(kernel_response,kernel_call); 117 case task_state is 118 ... when s1_query_file=> 123 pooled_fstream_query(kernel_call,kernel_response,ifile_q, ifile_d); 124 task_state_next <= s2_query_socket; 125 when s2_query_socket=> 126 pooled_socket_query(kernel_call,kernel_response,tsocket_q,tsocket_d); 127 task_state_next<= s3_open_file; 128 when s3_open_file=> 129 pooled_fstream_open(kernel_call,kernel_response,ifile_q,ifile_d); 130 status_ret_d <= cast_return_to_transaction_ret(kernel_response); 131 task_state_next <= s4_evaluate_file; 132 if(status_ret_q < 0)then 133 task_state_next <= s17_write_string_lram; 134 end if; 135 when s4_evaluate_file=> 136 pooled_fstream_read_len(kernel_call,kernel_response,ifile_q,file_len_d); 137 p_current_d(0) <= std_logic_vector(to_unsigned(file_len_q,32)); 138 task_state_next <= s16_close_file; 139 if(file_len_d >0) then 140 task_state_next <= s5_set_word_len; 141 end if; 142 when s5_set_word_len=> 143 safe_write_lram_word32(kernel_call, kernel_response, p_current_q,1,0); 144 inc_index <= '1'; 145 task_state_next<= s6_open_socket; 146 when s6_open_socket=> 147 pooled_socket_open(kernel_call,kernel_response,tsocket_q,tsocket_d); 148 status_ret_d <= cast_return_to_transaction_ret(kernel_response); 149 task_state_next <= s7_read_file; 150 if(status_ret_q < 0)then 151 task_state_next <= s15_close_socket; 152 end if 153 ... when s14_write_socket=> 184 clr_index<= '1'; 185 pooled_socket_write_word32(kernel_call, kernel_response, tsocket_q,index_q,0); 186 task_state_next <= s7_read_file; 187 when s15_close_socket=> 188 pooled_socket_close(kernel_call, kernel_response, tsocket_q,tsocket_d); 189 task_state_next <= s16_close_file; 190 when s16_close_file=> 191 pooled_fstream_close(kernel_call, kernel_response, ifile_q,ifile_d); 192 task_state_next<= s17_write_string_lram; 193 ... end process FSM_DPATH; 207 -------------------------------------------------------------------------------------- 208 Figure 2.25: Encryptor SA - simplified control path. as Vivado. Further details that concern the Accelerator model and some of the package provided features used in this section will be best discussed in Chapter 3 and Chapter 4. 2.7.4 Co-Simulation model From this point in the design flow, the two HW-Task descriptions that where implemented are ready for functional validation. An efficient and proper design validation should consider the application as a unified solution. Since this application will be running on the host development system, and the elaborated designs will exist solely in the simulation tool, we apply the co-simulation model that links the application Chapter 2. Design Methodology 51 functionality with the simulation tool. The outcome of this model is a unified simulation environment that simplifies the need for complex test benches that closely emulate the application by applying the real application stimulus to the accelerator model. At the software side, the framework will use the CoSimulation profile that specializes the task’s Proxy member and implements the conceptual resource-based set of operations, by using two network channels, and establishing connection with each individual accelerator. Figure 2.26 helps to illustrate the Co-Simulation model in the HAL-ASOS framework. A primary transfer channel will enqueue all of the Task class requests and the secondary channel will provide the interrupt related synchronism. The pending operations from the primary channel will be forwarded to the secondary channel for synchronism, before re-attempting the primary channel again. HAL-ASOS Accelerator Interrupt pin Control channel Data channel System channel HW Task HW Kernel Slave Interface Slave Interface Master Interface Task<HwTask, CoSimulation,…> transfer channel synch. channel run() start() … shutdow() … Proxy<CoSimulation > send_data() receive_data() … wait_interrupt() … Software application HDL simulation (C/C++) Figure 2.26: HAL-ASOS simplified Co-Simulation model The Accelerator model interfaces the communication channels using similar network features that provide a bus-abstraction to the original design. This feature is implemented using a mixed topology that combines the RTL description with: (1) VHDL Foreign Language Interface (FLI), establishing a programming interface that provides means to access data in the VHDL elaborated and simulated models; (2) or SystemVerilog Direct Programming Interface (DPI), interfacing the hardware description to foreign languages, namely C/C++ and System-C, by directly calling functions implemented in the foreign language. The choice is simulation-tool dependent since FLI support is, up until now, only available in the ModelSim tool. In either of the Model distinct implementations, the foreign language used was C/C++. Running a test-bench on the accelerator will allow the network channels to listen and accept connections. The software application can then start, and after a quick handshake, it will be running simultaneously at both sides of the implemented design. 52 Chapter 2. Design Methodology 2.7.5 Encryptor co-simulation In this section, the Machine 1 application will be executed on the host’s development environment using the co-simulation model. The co-simulation model involves the simulation of the software application, containing the Task class reconfigured for HwTask and using the CoSimulation profile, and the developed HW Encryptor , interacting with the accelerator model by using an RTL simulation tool. Figure 2.27 shows the Machine 1application, containing the necessary modifications to perform the functional validation in the co-simulation environment. When we observe the lines in that figure, we can see that the Task T1 declaration is using the THwEncrypter configuration, the HwTask qualifier and extends the template package with the CoSimulation profile. void hal_asos_demo::test_aes128_file_hw_cosim_thread_cypher_3(void) { 249 using namespace hal_asos; 250 251 Task<SwTask, TFRead> T0; 252 Task<HwTask, THwEncrypter,profile<proxy::CoSimulation>> T1; 253 Task<SwTask, TUpload> T2; 254 255 T0.start(); 256 T1.start(); 257 T2.start(); 258 T0.join(); 259 T1.join(); 260 T2.join(); 261 } 262 Figure 2.27: Machine 1- software changes for Co-Simulation using the HW Encryptor task. On the RTL side, we integrate the HW-Task in the application using the accelerator component, that can be identified by the suffixes ’ _c ’ for co-simulation and ’ _v ’ for bus abstraction based on SystemVerilog. In Figure 2.28a it can be seen the block design used for the co-simulation of the HW Encryptor task using a Vivado design project. The upper block represents the accelerator model, where it receives stimuli at clock and reset inputs, and responds with interrupt and heart-bit signals. These outputs are intended for their graphical representations in the tool’s wave window, since the interrupt signal is sensed internally by the bus abstraction model, and the heart-bit signal is an interface-based signal that denotes the accelerator operability. The lower block represents the HW-Task that was described in the previous section. This block design is then instantiated as a component, and submitted to a test-bench using an RTL file provided with the accelerator. The source listing of this test-bench can be consulted in the attached Listing C.10. The framework provides distinct implementations of the accelerator model which include Extensible Markup Chapter 2. Design Methodology 53 (a) HW Encryptor accelerator connections (b) Accelerator v4.00.c.v parameters Figure 2.28: Co-Simulation - HW Encryptor Accelerator settings Language (XML) descriptions in the IP-XACT format, to simplify the block design step by promoting the assisted connection with rule verification features. It also abstracts each group of the top-level logical signals to single interface connections. In the same image, Figure 2.28b, it is also possible to see the graphical interface used to configure the accelerator. This accelerator uses the host network service and so, it needs parameters that configure the network location where it will register its existence. The IP address and port number are used to connect with the Machine 1application, and the identification is mostly dependent of the name tag that matches the configuration member used in the class Task . When both, the application binary and the elaborated design are ready, the application and the simulation can be started without any particular order. In Figure 2.29 it can be seen message log that took place on the software side of the application. For this purpose, a smaller file containing 252 bytes (file small_pi.txt) was used, thus reducing the simulation and exposing the task algorithm to less cycles than the specified block size to complete the encryption, and to a file length that is not aligned with the accelerator word size. The HAL-ASOS network management service starts when the first registration attempt is received and issues a message in the application log. Upon receiving the accelerator registration, it will assign new port number used for handshake activities. The Task class will also register its particular interest about an 54 Chapter 2. Design Methodology accelerator that fits the provided parameters, and when found, it will receive back its IP address and the new port number for the handshake activities that starts right away. The remaining log messages demonstrate the application expected behavior and include the processing results sent by the HwEncrypter0 accelerator, which can be identified by the prefix from the template qualifiers HwTask and CoSimulation . Each individual task message shows a total of sixteen processed fragments and the application concludes as expected. Figure 2.29: Co-Simulation - HW Encryptor application output Back on the RTL side, the simulation was started and the accelerator waits for the task handshake. Figure 2.30 shows the log that results from this simulation in the Vivado’s TCL console. It can be seen the list of configuration parameters in use, here referred as Generics , and three log messages that encompass the accelerator registration. All the displayed messages lines contain prefixes based on: the name of the accelerator that sends the message; followed by the name of the internal operation that is being executed; and the current simulation time in nanoseconds. The handshake is triggered by the internal connect function at 295 nanoseconds of simulation time. After a successful handshake, the Proxy member in the class Task initializes the accelerator using local provided resources that include a system memory region. The operation started at 385 nanoseconds and completed at 615 nanoseconds. The next two message lines, report interrupts received from the HW-Kernel and the simulation concludes with the final two lines that result from the software application disconnection. From the performed simulation, a wave diagram is also displayed where it’s possible to examine the contents in the registers of the elaborated design. Figure 2.31 combines a view of the simulation at the top of the image, and an enlargement aligned with some FSM states at the bottom. At the top of the figure, it can be seen the exchange loop iteration, encompassed between the states s1 and s8, and sixteen encrypt loop iterations, delimited by the markers at 5.235 microseconds and the at 14.845 microseconds. Chapter 2. Design Methodology 55 Figure 2.30: Co-Simulation - HW Encryptor handshake messages Through the lower part of the figure, we can observe the behavior across the encrypt loop, where reading a fragment from Local-RAM takes twelve clock cycles, marker at 14,245.00 microseconds, in a two clock per word rate, that includes the four words read, and two more words for locking and unlocking the LMutex . The words used in the HW mutexes are equal and composed from a combination between configuration parameters and hardware signatures from the used mutex channel. When we observe the block_task signal, we realize that it remains active for the majority of the simulation time, which demonstrates an intensive use of functionalities under the kernel control. The behavior in the AES-128 top-level signals can also be examined, namely: run and done control signals, and plain_data and ciphered_data ports. At the 14,465.00 microseconds marker, the FSM triggers the AES run signal and proceeds to the wait_aes state, where it blocks in the HW system call. The AES uses a twelve-stage pipeline to encrypt the input plain_data and then releases the done signal. The kernel event subsystem will acknowledge a steady high value in the done signal, and the task returns from the system 56 Chapter 2. Design Methodology call in an additional four clocks. The AES connection differentiates blocking by using the kernel sleep control signal, and keep its clock active while the task is blocked in the above system calls. The same twelve clocks are used to write-back the cyphered data to the Local-RAM and the encrypt loop restarts, or moves to state s7 and attempts a new exchange loop iteration. The number of clocks used in the states s1 and s7 are mostly dependent of the network activity and does not reflect the four clocks used in the HW system call implementation. Two clocks are spent writing a 64-bit message in the kernel message-queue, and upon receiving, two more clocks are spent reading the response. Similar to other transactions in the kernel set of functional units, one clock pulse is used during data exchanging, and another clock pulse is used for reading the signals that acknowledge the operation. The FSM completes the exchange loop with the count_len matching the target_len and the total_len_q register indicating sixteen processed fragments, where it proceeds to state s8 . Once in s8, the control writes the final results in the Local-RAM, and the operation completes in the state s90 with the request to transfer the message to the stdout . At the 22,505.00 microseconds marker, the FSM achieves the last state and the execution concludes. The task_exit procedure notifies the Task class and puts the Kernel Core in a dead state. It also suspends all the HW-Task activities with both, the block_task and sleep signals active, until a hardware reset or a new initialization procedure is received. A functional validation of the Machine 1was performed, using the HW Encryptor description and the accelerator model for co-simulation. At the software side, minimal reconfiguration was performed by selecting the HwTask specialized class, that using the CoSimuation profile connects with the hardware part of the application for a unified simulation environment. For convenience, a smaller file was used thus producing a reduced number of cycles that ease the representation in the wave windows and allow for a comprehensive description about the HW-Task behavior. We now proceed with the Machine 1application using the HW Encryptor SA task in the co-simulation environment. For completeness, we will be using the ModelSim tool to simulate the accelerator’s RTL behavior. Chapter 2. Design Methodology 57 Figure 2.31: Co-Simulation - HW Encryptor wave plot using Vivado simulator 58 Chapter 2. Design Methodology 2.7.6 Encryptor SA co-simulation To address the roles of reading from the input file and writing to the network socket using the standalone HW-Task , first the designer needs to create the local references of this objects in the software application. For that it will use a framework software abstraction that encapsulates the implementation details of each specific object in the software class VirtualObject . The abstraction reduces the interaction to a message-based communication model, using internal message format that can be sent or received by the accelerator. The template specializations of this class include the most commonly used Linux device models. Figure 2.32 demonstrates the use of this feature in abstracting the input file stream and the network socket for the Machine 1application. void hal_asos_demo::test_aes128_file_hw_cosim_thread_cypher_sa(void) { 367 using namespace hal_asos; 368 hal_asos::networking::CSocket<hal_asos::networking::Client> Soc; 369 CFstream<std::ifstream> Input_file(target_file.c_str()); 370 371 Task<HwTask, THwEncrypterSA, profile<proxy::CoSimulation>> T1; 372 373 Input_file.set_flags(std::ios::in | std::ifstream::binary); 374 Soc.set_ip_address(ip); 375 Soc.set_sock_family(AF_INET); 376 Soc.set_sock_type(SOCK_STREAM); 377 Soc.set_sock_port(PORT_NO); 378 379 T1.submit_to_pool(Input_file); 380 T1.submit_to_pool(Soc); 381 382 T1.start(); 383 T1.join(); 384 } 385 Figure 2.32: Machine 1- Co-Simulation Standalone HW Encryptor Task Such instances are declared in lines 369 and 370 of the same figure, and after some configurations, they are submitted to the task T1 internal structures in lines 380 and 381. The file and the network socket are kept closed until submission, but alternatively, they could have been opened. The T1 Task instance uses the same qualifiers as in previous validation but a new configuration that matches this new accelerator descriptions is used. The newly reconfigured application was once more compiled and executed at host environment, and after connecting with the accelerator model, the output results were captured and can be observed in Figure 2.33. Similar output from the HAL-ASOS network manager is reported and it can be noticed only one task result message. Chapter 2. Design Methodology 59 Figure 2.33: Co-Simulation - HW Encryptor SA application output. At the ModelSim console, the configured settings were reported and upon receiving connection from the software task, the simulation proceeded in a continuous mode until receiving disconnection. In Figure 2.34 it can be seen the console log from this simulation. Figure 2.34: Machine 1- HW Encryptor SA handshake messages using ModelSim A wave plot describing the register contents throughout the performed simulation is depicted in Figure 2.35. In a similar manner, the image is divided in two subplots where we can observe the overall path of the states implemented by the FSM, and a magnified view of the encrypt loop. At the bottom of the topmost subplot, we can observe the first marker indicating the open file operation at time 1,940.00 nanoseconds, and consecutively the socket is opened at time 3,150.00 nanoseconds (i.e., S3_Open_file and S6_Open_sock markers respectively). The hardware file descriptors updated with the current state on the software side and it can be seen that the two virtual objects are kept closed until each specific open state is reached. The complete file encryption starts at the 8,960.00 nanoseconds and finishes at 18,710.00 nanoseconds in a total of sixteen processed fragments, (i.e., S9_load_plain and S13_update_in markers respectively). 66 Chapter 2. Design Methodology network channels. As for the RTL simulation, the model assumes once again two implementation variants, using VHDL FLI- or SystemVerilog DPI-based implementations in the ModelSim tool or SystemVerilog DPI- based implementation in the Vivado simulation tool. On the RTL side, the model stimulates the design and allows the user to explore how the accelerators relate to the system bus, or how they synchronize with the application on the Host side, here considered QEMU guest. The hal_asos_link component initiates the connection with QEMU side, and in the handshake phase, exchange the tool and accelerators intrinsic details. These include the tool name and address range, and accelerator parameters namely, the task tag, base address and address range, and the interrupt offset. Each device is then registered accordingly to map the corresponding accelerator in the QEMU machine virtual representation. On QEMU side, at the top of the hierarchy, stands the bus where the devices are attached. For every device, there is a memory region and a file operation structure that uses each device specific code. Once in service, and as consequence of the software execution, whenever QEMU needs to access the memory region where the device is mapped, it launches the execution of the read or write functions from the registered object. These implementations evaluate the address and the size of the request and forward and appropriate message to the RTL simulation. On the RTL side, the receiving requests from the network channel are forwarded to the Master Model. Such model implements the procedures that exchange data with the HW-Kernel resources using the accelerator differentiated interfaces, i.e., the S00_Control and S01_Data . Whenever an interrupt line is triggered, or an accelerator accesses the system’s memory, the hal_asos_link component intermediates such request by using the Slave Model, and proceeds by forwarding an appropriate message to the QEMU side. Upon receiving such message, the bus_link on QEMU side uses native API to interact with the memory or interrupt subsystems and complete the received request. Despite presenting a wider validation chain, this model can replace the Co-simulation model and reduce the number of iterations in the design flow. For this reason, once achieving the deployment phase, the design flow does not iterate back to the Co-Simulation phase, assuming that it can validate the application in full simulation environment. Care must be taken when dealing with design refinements in this stage and appropriate planning is required. Chapter 2. Design Methodology 67 2.8.3 Full system simulation To apply the Full simulation model to the Machine 1application the designer needs to provide the means for connecting the accelerators that exist in the simulation tool with the virtual device representation on QEMU. For that, it will replace the processing system in the block design of Figure 2.36, by the hal_asos_link component that fit the SystemVerilog implemented version. Alternatively, it can create a new block design and keep both designs in the Vivado project, to be used them in the subsequent design iterations. Figure 2.39 depicts the block design for Full simulation of the Machine 1application using Vivado. To highlight the connections, the accelerator interface lines where manually colored in: light purple for the accelerators’ master interfaces; light orange for the control-oriented slave interfaces; and light blue for data-oriented slave interfaces. Figure 2.39: Full Simulation - HW Encryptors block design Similarly, as in the co-simulation model, the hal_asos_link component requires parametrizable settings that configure the network connection. Figure 2.40 depicts the Vivado component generated interface, and includes the parameters used in this simulation. Such block design requires one interrupt for accelerator and two accelerators are in the block design. We use the same IP address as in the Co-Simulation but a different port that depends in the tool specific implementation. 68 Chapter 2. Design Methodology Figure 2.40: Full Simulation - hal_asos_link simulation parameters On the QEMU side a custom implementation for Vivado tool was compiled as dynamic library and during the QEMU machine initialization, the HAL-ASOS extension will load all the .so files that can be found in the libraries path. In this example, a vivado.so dynamic library is loaded, and QEMU will wait for a parametrizable time until receives connection from the simulation tool, before proceeds with the handshake. Figure 2.41 depicts the handshake log messages at both sides of the simulation. In Figure 2.41a, a cat command exposes the used boot settings. We have selected the QEMU pre-defined machine xilinz_zynq_a9 and the compressed Linux generic image, zImage will be used. The rootfs.ext2 file will be mounted as SD device and the append switch specifies the kernel boot command. After loading the symbols in the vivado.so library the open_connection of the bus_link was executed. Upon receiving connection, the details about the simulation tool and the existing accelerators were exchanged. At concluding the handshake, the simulation parameters were used to register two devices using the device model extension, and once all hardware devices where initialized, the QEMU proceeded by booting the Linux image. In the Figure 2.41b we can see the handshake log messages in the Vivado TCL console. The first lines list the accelerator parameters and result from SystemVerilog registry functions. At 265 nanoseconds of simulation time, the hal_asos_link successfully established connection with QEMU. A continuous run command was issued, and the simulation proceeds until the designer decides to manually stop the simulation, or issues a shutdown on the Linux console of the guest machine and closes the QEMU execution. The testbench source used in this simulation is a generic example provided by the HAL-ASOS framework and can be consulted in the attached Figure C.11. Chapter 2. Design Methodology 69 (a) QEMU handshake log (b) Vivado Simulator handshake log Figure 2.41: Full Simulation - QEMU and Vivado handshake log Once QEMU booted the Linux image, a set of commands were executed with the purpose of confirming the correct state of the system, and the results can be seen in Figure 2.42a. A ’ uname ’ command displays information about the system: a Linux 4.9.0 preemptible kernel for SMP architectures is in use and is based on ARMv7l machines. A ’ ls ’ command lists the available accelerators in the HAL-ASOS file system. Two directories with the accelerator’s names are found, and contain the virtual files that export the accelerator model to the Linux user-space. Entering the QEMU monitor console, an ’ info qtree ’ command lists the devices in the system and it can be seen the accelerators that were registered in the handshake phase. On Figure 2.42b it can be seen a console formatted message, from the local-kernel virtual file read that lists the current accelerator status. It includes information such as: the accelerator name; the base address and combined address range; the configured design parameters; some Linux kernel assigned resources; internal statistics and status of the local-kernel registry; but is also displayed the overall status of the HW-Kernel functional units being simulated in the RTL side. Considering that the Linux image was successfully booted, the handshake established a connection between the emulated hardware in QEMU and the RTL simulation on Vivado, we now proceed with the 70 Chapter 2. Design Methodology (a) QEMU - Survey HAL-ASOS file system and monitor (b) QEMU - File system query to accelerator kernel Figure 2.42: Full Simulation - running Linux image on QEMU functional validation of the Machine 1. For this stage, the Machine 1application was once more compiled, but this time using the host cross-compilation toolchain. To address the different application variants, the main function was updated to receive parameters form the command line that specify both, the application variant and the input source. The attached Figure C.12 lists these software changes. The Machine 1application was reconfigured to use the HwTask qualifier and recompiled with debug symbols. The attached Figure C.13 lists the corresponding source. Figure 2.43 depicts the output log from the Machine 1functional that selects the use the HW Encryptor task. A ’ ls ’ command lists the files in the home directory and two text files that contain 1,000,002 bytes and 252 bytes are listed. The file hw_encryptor file is the application binary in the elf format. The log that results from the execution, demonstrates similar results as in the Co-Simulation stage, and we can observe the HwTask as prefix of the Encryptor task log. Since the task is configured to use the StandardIO profile no qualifier is printed. On the RTL side, a simulation waveform was plotted and once more the image is divided in wide and magnified views. Figure 2.44 at top, depicts the overall execution time of the Encryptor task. At time 1,813.235 microseconds the HW-Kernel received the control information to start the HW-Task and 151.38 Chapter 2. Design Methodology 71 Figure 2.43: Full Simulation - Machine 1 application using HW Encryptor task microseconds later, the task enters the state s3 to read the first word from the Local-RAM. The encryption of the 256 bytes completes 9.61 microseconds later and after 943.504 microseconds the task completes the transfer to the DDS topic. The execution concludes 20.775 microseconds later. We can observe that due to the multiple implementation levels, the HW-Task spends most of the time waiting on the interaction with the simulation on QEMU. The light blue strips, indicate activity in the accelerator bus interfaces. The S00_AXI is connected with the control-oriented channel and the S01_AXI is connected with the data-oriented channel of the Accelerator model. At the bottom of Figure 2.44, we zoom in to see the details of the activity on those signals. The purple blocks represent read transactions, and the shaded red blocks represent write transactions. The read , write , read pattern is used to lock the Local-RAM mutex with the transaction ID 0x5, and the ’1’ value on the o_status [31] bit, indicates a locked mutex . Consecutive write transactions are performed in the S01_AXI interface, to transfer the plain data from the DDS subscription to the Local-RAM. The first word 0xfc is the control field and indicates an effective file length of 252 bytes. Three clock cycles per word are used to write the S01_AXI interface and an interval of eight clocks is used in the internal operation of the hal_asos_link component. Similarly, the HW Encryptor SA task was also validated and Figure 2.45 shows the application log in the Linux command line at QEMU. The attached Figure C.14 lists the used source with the necessary changes. A ’ uname ’ command lists the information about that system before running the application, and a ’ ls ’ command repeats the list of contents in the directory. The application is launched with argument ’2’, which selects the standalone version of the Machine 1, and the same file was used. As expected, we can observe that only one task is in execution, where 16 fragments of plain data where successfully ciphered and consequently uploaded to the Machine 2. The simulation waveform of this execution can be seen in Figure 2.46. 72 Chapter 2. Design Methodology Figure 2.44: Full Simulation - HW Encryptor simulation waveform. Chapter 2. Design Methodology 73 Figure 2.45: Full Simulation - Standalone HW Encryptor design At top we can see that the application received the run signal at 5,042.705 microseconds and 191.00 microseconds later, the received plain data was ciphered and is ready to be transferred over the network. At time 6,179.695 microseconds, such transfer was completed and 9.95 microseconds later the task concluded. The worst case in the task FSM is once again the network transfer with 916 microseconds duration. It’s fair to say that due to the emulated nature of QEMU, the Full-Simulation environment involves a great deal of overhead in the network subsystem, which includes the host development environment, the QEMU network back-end, and the target Linux OS in QEMU. Analogous bus activity can be observed in the accelerator interfaces. The bottom of Figure 2.46 depicts the last transactions used to read the 64 words of ciphered data from the Local-RAM. Four clocks are spent to read data in a total of eleven clocks per word transaction. The Local-RAM mutex remains locked until the transaction completes and once more, the read, write, read pattern appears at the S00_AXI interface to unlock the HW mutex . The o_status [31] bit is cleared indicating the mutex is free and the last owner ID was 0x13. When compared to the results of the Machine 1Co-Simulation, the Full Simulation requires more clocks per task iteration and it consumes more simulation time. For this reason, the major application design refinements should be addressed during the Co-Simulation phase. The Full simulation provides a powerful simulation environment that is capable of dealing with any potential glitches involving the tree major system components: the Software; the hardware; and the Linux OS. But it also requires a good strategy in applying debug iterations while addressing such faults. In this section, the binary files that implement the system were cross-compiled to the target hardware and the overall system files were validated. Usually in this phase, we use compilation with debug symbols and as so the binary files might need to be once more re-compiled. We will proceed with the system implementation using the ZC702 board, where the trifecta of application versions will be evaluated. 74 Chapter 2. Design Methodology Figure 2.46: Full Simulation - Stand-Alone HW Encryptor simulation waveform. Chapter 2. Design Methodology 75 2.9 System Implementation In this section, we implement the system in the selected board and evaluate the application in the three implementation variants: the software-only, the software and hardware Encryptor and the hardware Encryptor as standalone. The target system is using the binary files that resulted from the previous section where the bitstream includes the two implemented accelerators using 100 MHz bus clock In similar manner to the Full simulation tests, the Machine 1 mounts the HAL-ASOS file system at boottime and two accelerator folders can be found in the hal-asos directory, at the root of the Linux file system. The Machine 2was set to receive the resulting ciphered files and both applications were simultaneously executed. Figure 2.47 shows the results of the Machine 1running on the ZC702 board. The tests were executed using the ’ time ’ command that displays an output message with timing statistics about the execution. # uname -a Linux buildroot 4.9.0-xilinx #1 SMP PREEMPT Wed Jul 17 14:19:13 WEST 2020 armv7l GNU/Linux # ls 100M_digits_pi.txt 1M_digits_pi.txt stress_test.sh 10M_digits_pi.txt machine_1_app # time ./machine_1_app 0 1M_digits_pi.txt [FileReader<SwTask>]finished...(62501) [Encryptor<SwTask>]finished...(62501) [Uploader<SwTask>]finished...(62501) real 0m 6.42s user 0m 8.13s sys 0m 1.56s # Figure 2.47: Machine 1 - Software-only application version running on ZC702 board. The output results demonstrate similar log messages from the application. The timing statistics are displayed after the application log and include: (1) the real time between the invocation and the termination, (2) the CPU time spent in the application running the user code and (3) the CPU time spent in the system running the Linux kernel code. The SW-only real time results demonstrate 6.42 seconds spent using one million digits of pi as input. The subsequent lines demonstrate that 8.13 seconds were spent running the application code and 1.56 seconds running the system code. The total time value overcomes the real time value and the differences result from the existing parallelism in the application and scheduling the execution using two CPU cores to simultaneously execute the application. Similar messages describe the 82 Chapter 3. First-class Hardware Components locked HW-Task Kernel Core LMutex mutex_lock(LMutex) write(TaskID) read() locked (‘10’ &HostID) (blocked) locked read() (‘11’ &TaskID) locked write(TaskID) Host System concurrent lock Figure 3.3: Hardware system call - mutex lock sequence diagram. In the next sections, we discuss the implementation of the Kernel Core in the HW-Task concept. We then proceed with details of connectivity between the Kernel Core and the HW-Task , and the available resources in the Kernel Core . In section 3.2 we discuss the HW-Task template design where we show some application-level operations. We conclude in section 3.3 describing the host system connection with the accelerator model. 3.1 Kernel Core The Kernel Core manages the HW resources in the accelerator model and promotes the integration of the HW-Task in the host platform, namely in the interaction with the operating system and the application memory segment. Conceptually, the Kernel Core acts like any kernel that can be found in the most elementary OS, by providing a set of services that interact with local resources through system call invocation. In the HAL-ASOS design, these are called HW system calls to distinguish themselves from the similar software-based implementation. To operate at kernel level, the HW-Task implements system calls using procedures described in the kernel HDL package. Alternatively, for more complex operations the user HDL procedures can implement consecutive system calls that involve more than one local resource. Procedures can receive input and output parameters that link to resources from the HW-Task design. These Chapter 3. First-class Hardware Components 83 in turn will allow the system call to access these resources and ultimately update them with execution results. Figure 3.4 shows a simplified diagram that describes the internal organization of this component. The Control Unit determines the status of the accelerator, and it can be triggered by the active bits in the control register. These in turn can be handled by the host system to address the application functional requirements. Due to the critical nature of these operations, the content of this register is updated under the supervision of the Authenticator device, which validates the received word before authorizing the operation. Kernel Core Time Events Index Counter Schedule Cntr. Error Counter Authenticator LOCAL BUSFIFO IN FIFO OUTS00 Control M00 System Kernel Call Kernel Response Microprogram Control Unit Control Reg. Status Reg. System Datapath Figure 3.4: Kernel Core internal structure Once active, the Control unit operates through the system-level datapath, establishing connectivity between the micro-programmable unit and the kernel Call and Response interfaces. These interfaces match directly to the S00_Task and M00_Kernel signals in the accelerator top-level, and allow the HW-Task to trigger the system calls present in the micro-programmable unit. In turn, system calls give rise to a pre-programmed set of control actions, which operate at the system level to handle adequate data manipulation using the existing local resources. When the HW-Task design needs a wait event within the duration of a predetermined number of clock cycles, or to wait for an HW signal restricted to a maximum timeout interval, a system call can interact with the Time Event device to provide this service. In addition, three parametrizable counters are included in the kernel datapath and used internally when scheduling multiple and concurrent system calls, manipulating data through indexes and to account for any errors that may occur as result of the execution. 84 Chapter 3. First-class Hardware Components Once running, the micro-programmable unit suspends the clock signal at strategic points of the HW-Task design for all system calls. In doing so, the HW-Task context remains suspended while it interacts at kernel level. Pre-programmed control signals are then generated to forward the received parameters using the system-level datapath. At the same time, status information is generated that indicates whether the system call performs a write or read operation, or if it stays blocked waiting for available resources involved. In the final active clock cycle that completes the system call execution, the microprogram re-establishes the context on the HW-Task , allowing this entity to proceed with its processing. 3.1.1 Authentication In the Kernel Core design, the Authenticator acts as a shield for the control register. All data write transactions that target this register are forward via the Authenticator device that, after validating the received word, determines whether or not such contents can be written. In Figure 3.5 we can see a simplified diagram that describes the internal design of the Authenticator device. Q[5:0] D[5:0] increment clear load Counter (6-bit) reset clock 100000 50 [5] [4] clock [5] reset compare match ALU [15:0] [15:0] A1 user_id Auth_reg CE reset D[N:0] Q[N:0] i_data WR_CE_i reset DQ clk CMASTER_KEY Clock clock Control.run Control.sw_reset Control.run_for_iteration Control.restart auth_key Control.auth_key Q[5:0] D[5:0] increment clear load Counter (6-bit) reset clock 100000 50 [5] [4] clock [5] reset master_id valid_id [15:0] [28] [29] [30] [31] compare match ALU [15:0] [15:0] A0 CUSER_KEY master_id user_id Control.sw_reset Control.restart RESET auth_key C0 C1 FF0 FF1 [30] clear_i Authenticator reset clock CS(0) txdata S00_Control control o_sw_reset o_sw_restart * - control_offset = 0 ce WR_CE clear_i Figure 3.5: Authenticator device architecture On the left side of the figure, we see the S00_Control interface, which is the source of control-oriented data, used by the host system. In this interface, the CS(0) line is active when the address matches the control register offset, and the interface specifies a write transaction using the WR_CE signal. The logical combination of both signals and logic ’0’ in the FF0 register, enables the clock (CE) in FF1 for one period. The next active clock transition stores the contents of i_data in the internal register Auth_reg . During this clock cycle, the Authenticator makes the word available at the control output, while comparing the auth_key field with parameter keys in A0 and A1 inputs. The logical combination of user_id and Chapter 3. First-class Hardware Components 85 negated control.sw_reset will activate the output valid_id , while at the same time, the input WR_CE assumes the logical zero, which activates the clear_i internal signal. The subsequent clock cycle will use the valid_id signal to store the control output in the Kernel Core register, while the clear signal discards the contents in the Auth_reg . Figure 3.6 shows a wave plot that results from the functional validation of the authenticator device, where the S00_Control interface writes in the control register of this unit. Figure 3.6: Authenticator wave diagram: control operation for HW-Task restart. At the 125 nanoseconds marker, the control word 0x1000ace1 sets the restart_hwtask bit, that combined with the user_id flag , loads the counter C0. In the next clock cycle, the active 5th bit in Q[5:0] links with the output o_sw_restart , and the same bit starts C0 counting. When the count value reaches “110000”, the 4th bit clears C0, and at the 305 nanoseconds marker the output Q assumes the value of “000000” that completes the restart operation. The authentication key CUSER_KEY gives the host privileges to change all fields in the control register except for sw_reset bit. Due to such critical condition and to avoid erroneous data re-use, this operation can only be triggered by the use of distinct CMASTER_KEY . In a similar way, when the authenticator receives the CMASTER_KEY with the logical value high in the sw_reset bit, the combination of this bit with the master_id flag loads C1. The output of this counter triggers the SW demanded reset operation for a pre-determined number of clock cycles. The value of both keys, as well as the count intervals of the C0 and C1, are parameters of the Authenticator. These 86 Chapter 3. First-class Hardware Components values are defined in the hal_asos_configs package that can be adjusted to better suit the design timing constraints. Some of the contents in this package will be discussed in this section. 3.1.2 Control Unit The Control Unit is responsible for the status of the Kernel Core , and reacts to the active bits in the control register and the task status bits. From the host’s point of view, this unit establishes synchronism between the OS and the accelerator model. As from the accelerator’s point of view, it synchronizes the HW-Task with the target application. Figure 3.7 1 describes the top-level signals of this unit, and it also shows the control register implementation and the HW-Task status bits dead and done (i.e., task_dead_i and task_done_i ). CE reset DQ clk Control.run Control.run_for_iteration Control.restart [28] [29] [31] control CE reset DQ clk Kernel_Call task_done_i CE reset DQ clk Status.Dead task_sleep task_run task _restart 31 29 28 15 0 Control Register Control.auth_key [15:0] CE reset DQ clk core_state sw_reset reset clear_run_i restart_hwtask_i run_i RUN_IT task _restart reset_i reset_i clear_task_rst_i [31] [29] [15:0] valid_id reset_i reset_i task_dead_i RUN SW_RST 30 RUN_IT RESTART AUTH_KEY - Control Unit clock reset_i clk reset clock Kernel_Response FF2 FF3 FF1 FF0 [28] task_done to Datapath sw_restart Time_Event.timeout Time_Event.core_sleep timeout_i CE Figure 3.7: Kernel Core - Control Unit Overview The main source of information for this unit is the control register implemented using FF0 to FF3 logical elements (LEs). When the RUN bit is active, the control enables the accelerator to a continuous run, that can be quantifiable in HW-Task iterations or processing rounds. When this bit value switches to logical zero, the control remains active until the HW-Task completes the current round, and signals completion through the task_done bit. Similarly, the combination between RUN and RUN_IT bits, activates the control unit to run for one HW-Task round. At completion, the task_done signal is used to set clear_run_i and the next active clock transition will clear the RUN bit (FF0) in the control register. In response, the control suspends the task_run output, which prevents the HW-Task from starting a new round. The HW-Task rounds are comprised between the clock cycle in which the control activates the task_run output until the clock cycle in which it receives the task_done signal. Chapter 3. First-class Hardware Components 87 The implementation of the control unit follows a state logic that can be consulted in Figure 3.8. States #0, #1 and #2 are referred to as online states since control is available to interact with the host system, although from the HW-Task perspective, in #2, the internal context is suspended. In the remaining states, the accelerator is considered offline, either because it is in the dead state or because a restart operation has been triggered and it waits in #3 for the HW-Task to be ready for execution. 0 #0 ready #1 processing #2 sleeping #4 dead #3 restarting_task timeout_i/ status.dead task_done_i/ run_i/ run_i/ restart_hwtask_i wait_event_timeout(run_i, CKERNEL_TIME_TILL_SLEEP) wait_signal_... /task_run sys_call_yield sys_call_none /task_restart run_i/ On-line states restart_hwtask_i /task_sleep Figure 3.8: Kernel Core - FSM state diagram The Control unit assumes the initial state ready after a system restart or a host demanded SW reset. During this state, it is not possible to predict when the host system will be available to interact with the accelerator, and thus the control initiates the HW system call waint_event_timeout . This system call receives the run_i signal and the integer CKERNEL_TIME_TILL_SLEEP as input parameters. The numeric value expresses the timeout value in clock cycles during which the execution will remain waiting for a high value on the run_i signal. If the run_i input is not received before the counting expires, the control returns from executing the system call with the timeout bit high, and transitions to #2. In #2, the Control unit activates the task_sleep output to enable the sleep condition on the HW-Task design. At the same time, it selects a similar system call but now using the logical combination of the run_i or restart_hwtask_i as input signal and no timeout value. In doing so, this system call will wait indefinitely for a high value in the input signal parameter. A zero value in the timeout parameter activates the core_sleep signal that is output in the Time Event unit, and using this signal, strategic points of the Kernel Core are kept with the clock signals disabled. If the input signal is detected, the Time Event unit 88 Chapter 3. First-class Hardware Components disables the sleep signal and the Control unit transitions to the next state accordingly. Slightly modified control unit is used to address microprogram updates and can be seen attached in Figure D.6. Once in #1, the Control unit connects the system-level datapath and the micro-programmable unit to the kernel Call and Response interfaces, so that it can answer to HW-Task requests. At the same time, the task_run output is kept active, signaling the HW-Task to proceed with its execution. The HW-Task can now execute any of the system calls that the Kernel makes available, until the host system decides to disable the run bit. Alternatively, the HW-Task can terminate the execution using the task_yield system call. This will activate the Dead flag in the Status register and the Control unit reacts with the transition to #4. Once in #4, the clocks for all strategic points in the Kernel Core and HW-Task designs are once again deactivated. The Control unit does not return from this state unless a software reset operation is initiated by the host system, or the target platform is restarted. In Figure 3.9 we can see a wave diagram of a short simulation of this Control unit, including relevant signals that relate to the Kernel Core design. After an initial reset the control assumes the st0_ready and remains in this state, while waiting for the host to intervene in the control register. At time 1,300.00 nanoseconds, the status register indicates that the HW-Task is ready but blocked waiting for the run signal. From the contents of the sys_call_id signal, we can see that the microprogram is executing a wait event system call, which a few clock cycles later, gives rise to a timeout signal in the Time Event unit. In response to a timeout, the Control unit advances to the st2_sleep state, suspending the clock signal in the HW-Task design. Simultaneously, it repeats the execution of the system call, using the logical combination of the run and restart signals, and zero timeout clock cycles as parameters. Five clock cycles later, the Time Event unit activates the core_sleep signal that suspends the clock sources in strategic points the Kernel Core design. Under this condition, the Control unit enters into suspension mode, where it remains until host system intervention. At time 1,630.00 nanoseconds, the control register is updated with the user key and the active bits run and restart. One of these two active signals would be enough to trigger the Time Event device, which in response, disables the core_sleep signal. With the clock sources enabled, the Control unit recognizes the flags that gave rise to the event and advances to st4_restart , where the context of the HW-Task is restarted. After ten clock cycles, the restart concludes and the control switches to the st1_processing and activates the task_run signal. Chapter 3. First-class Hardware Components 89 Figure 3.9: Kernel Core - control unit wave diagram. 90 Chapter 3. First-class Hardware Components Once active, the HW-Task executes the system call that reads the control-oriented data FIFO, and when completed, it decides to abort the execution by issuing the task_yield system call. The control switches the st3_dead where it remains blocked with the clock signals suspended once again. A few cycles later, the main reset signal restores the accelerator to its initial state. During these states, the status register is updated with the information from the HW-Task , where its operating status is visible, as well as the indication of blocking, dead, sleep and restart, by the use of the corresponding flags. In Figure 3.10 we can see a functional block diagram depicts the connectivity between the kernel Call and Response interfaces, the micro-programmable unit and the system-level datapath. In M0, the source of parameters for the microprogram and the system-level datapath are determined by the state register of the Control unit. Similarly, using M1, the kernel response interface will receive the outputs from the system wait_event_timeout() Kernel_Call sys_call_i core_state core_state Kernel_Response ready processing sleeping dead restarting syscall_none() return_dead() return_blocked() return_sleeping() ready processing sleeping restarting dead cinput_bus[N:0] sys_call sleep coutput_bus[M:0] cresponse block_task validthis_call Microprogram (microcode) core_sleep_i return_i parameters[X:0] return_arg[X:0] System-Level Datapath cresponse control_inputs control_ouputs syscall_yield() wait_event() M0 M1 X –(C_MESSAGE_WIDTH-1) := 63 N –(C_MICROPROGRAM_INPUT_WIDHT-1) := 31 M –(C_MICROPROGRAM_OUTPUT_WITDH -1) := 15 Figure 3.10: Kernel Core - system-level datapath and microprogram interaction. call execution, or otherwise it will be clamped to constant signals. In the processing state, the HW-Task is the source and destination of these signals, whereas in the remaining states, M0 disconnects the HW-Task from the microprogram and system-level datapath, and M1 reinforces the blocking signals. Details about the microprogram and the system-level datapath will be discussed in the following subsections, after the introduction of the HW system calls. 3.1.3 Hardware System Calls An HW system call is a sequence of control operations that use a predetermined number of steps, to provide services related to the local resources in the accelerator model. In similarity with the concept applied to the OS environments, the HW system calls virtualize the accelerator through a specific set of features, that allows the designer to structure an HW-Task . They are the Kernel Core fundamental Chapter 3. First-class Hardware Components 91 interface, to handle the local resources and abstract away the complexity that the accelerator model represents. Such level of abstraction, in turn, promotes the design reuse allowing it to be implemented on different platforms, as long as the HW system calls have appropriate implementation. In doing so, we organize the Kernel Core design trough an incremental set of programmable features. For simplicity, in this section we will refer to the HW system calls as system calls and to the Kernel Core as kernel. To implement a system call, the HW-Task uses procedures in the kernel package that establish the functionality, the involved parameters and the connectivity between these and the kernel microprogram and system-level datapath units. For this, the kernel provides entry and exit points in its interface that establish the required signals. In Figure 3.11, we can see an excerpt of the kernel package that defines the system call interface. Starting at lines 163, 206 and 213, the kernel package defines the sys_call_t type as the subset of system calls that the kernel supports and are used in the input and output records to establish the system call interface. ... library hal_asos_v4_00_a; 6 use hal_asos_v4_00_a.hal_asos_configs_pkg.all; 7 use hal_asos_v4_00_a.hal_asos_utils_pkg.all; 8 ... type sys_call_t is (SYS_CALL_NONE, SYS_CALL_WAIT_EVENT_TIMEOUT, SYS_CALL_READ_LFIFO, 163 SYS_CALL_WRITE_LFIFO, SYS_CALL_READ_MESSAGE, SYS_CALL_WRITE_MESSAGE, SYS_CALL_READ_LBUS, 164 SYS_CALL_WRITE_LBUS, SYS_CALL_MUTEX_LOCK, SYS_CALL_MUTEX_TRY_LOCK, SYS_CALL_MUTEX_UNLOCK, 165 SYS_CALL_READ_MBUS, SYS_CALL_WRITE_MBUS, SYS_CALL_READ_LBUS_BURST, 166 SYS_CALL_WRITE_LBUS_BURST, SYS_CALL_READ_MBUS_BURST, SYS_CALL_WRITE_MBUS_BURST, 167 SYS_CALL_YIELD); 168 ... type sys_call_input_t is 206 record 207 this_call: std_ulogic;-- trigger sys_call 208 sys_call_id :sys_call_t; 209 parameters : std_logic_vector(C_MESSAGE_WIDTH-1 downto 0); --field for syscall parameters 210 end record; 211 212 type sys_call_output_t is 213 record 214 valid: std_logic; 215 block_task: std_logic; 216 sys_call_id : sys_call_t; 217 return_arg : std_logic_vector (C_MESSAGE_WIDTH-1 downto 0); -- return sys_call data 218 end record; 219 ... Figure 3.11: HW-Kernel package - system call types, entry and exit records When executing system calls, each procedure specifies its arguments according to the desired feature in line 209, and links them to the input parameters according to line 210. It then activates the this_call flag to signal the kernel for valid inputs and to proceed with the system call. In response, the microprogram activates the block_task signal and transfers the received type of system call to the syscall_id member according to line 216 and line 217, respectively. Over the course of execution, the kernel updates the 98 Chapter 3. First-class Hardware Components Table 3.2: Microprogram - Binary excerpt from the Microprogram. Sys Call ID Step Input NSF Output Valid Block ... ... ... ... ... ... ... 00 01100 00 0111 0 1 01 11111 10 0110 0 1 10 01010 00 0111 0 1 SYS_CALL_MUTEX_LOCK 0x08 11 11110 00 0000 1 0 00 01100 11 0000 0 1 01 11111 10 0110 0 1 10 01010 11 0111 0 1 SYS...MUTEX_TRY_LOCK 0x09 11 11110 00 0000 1 0 ... ... ... ... ... ... ... success, the microprogram reaches step three by incrementing the counter, or otherwise jumps to address 0x20 and repeats the system call. In step three, it activates the output to indicate valid data in the return register and releases the HW-Task by disabling the Block output. At completion, the microprogram needs to jump to step zero in the counter register, so that a new system call can start. Although the increment of the counter gives rise to the similar behavior, the design applies a dummy test of a false input to favor regularity, and jump back in the last step of each system call. The following lines in the same table describe the implementation of the system call for the try-lock mode. As described in subsection 3.1.3, it differs from the previous one in steps zero and two, where in the first case it proceeds to the last step if the resource is locked, avoiding contention. In the step two, it proceeds to the next step even though it might have lost the dispute for the resource, thus avoiding the repetition of the system call. In this case, both test results lead to step three and a distinction is made at the system-level datapath, which turns the denied Locked B flag into an error and a false logical value for the system call return. Although some system calls use fewer steps, a set of four microinstructions establish a state in the microprogram. In the fewer steps case, the unused locations were filled with just-in-case corrections, implementing jumps to the beginning of the system call where they are inserted. For this reason, only the blocking output is set to active, the false input is used for testing and the NSF field defines ”00” as the next step. Up until now, 18 system calls are mapped in the program memory that requires 72 memory locations. For this purpose, we implement a 128 x 13-bit ROM with an overall usage of 56% of the capacity and exhibiting 12% of memory footprint with self-corrections. Chapter 3. First-class Hardware Components 99 Figure 3.13 describes the ROM-based microprogram architecture using a simplified block diagram where U0 represents the combinational ROM, addressed using the 7-bit program counter (PC). For this signal, the design uses the inputted i_sys_call as address prefix and to convert a system call element to an equivalent number, it employs the VHDL position attribute. In doing so, it considers the logical description in the signal by the enumeration value it represents. Then, we concatenate this number with the 2-bit output Q of the counter C0 to form the absolute address used in U0. In order to synchronize the microprogram execution with the system-level datapath, the absolute address is also forwarded to this unit using the output control . Input select Next step false Output select Valid Block ROM word addr PC[N-1:0] i_sys_call o_block o_valid test input enable output 1 no output o_levm_trigger i_levm_ready i_levm_signal 0 1 2 OW+1OW+2OW+3OW+4 IW+OW+3 LEN:= 128 , Input Width (IW) :=5 , Output Width (OW):=4 Microprogram (ROM-based) Parameters: mutex_locked_B_i mutex_nlocked_A_i mutex_nlocked_B_i 0 1 10 11 12 o_lbus_wr_ce o_lbus_rd_ce 0 1 6 7 15 31 …… …… true (‘1’) M0 M1 U0 i_this_call N := SYS_CALL_WIDTH +2 reset FF0 L0 1 clock this_call_i I2 I0 I1 … LUT3 (8:1) Out X0 X1 X2 X3 … X7 0 i_sleep Counter Q[1:0] EN inc load D[1:0] reset clock C0 clk CE reset DQ clk reset [N-1:2] [1:0] o_cresponse cinput_bus coutput_bus …… … … Figure 3.13: Microprogram - ROM-based internal architecture. The C0 counter is updated in the clock active transitions by incrementing whenever the output in M0 is a logic ’1’, or loading the value in input D when the same is a logic ’0’. For a change in its output, the counter must have the EN input active, which enables the clock signal in the output register Q. The EN signal is connected to the output of the logic expression in L0 that evaluates the i_this_call input, this signal in the previous cycle, and the sleep input. The combination of logic ’0’ at the input I2 and ’1’ at I1 or I0, establishes a logic ’1’ at the output. The use of FF0 provides an additional clock pulse in C0, ensuring that, on completion, the microprogram proceeds with step zero of the idle system call. To implement this, L0 receives an 8-bit logic function ’X’ as parameter, that contains ’1’ in the positions 1, 2 and 3, and ’0’ in the remaining positions. This is an alternative representation of the logical expression after it has been implemented in the FPGA configurable logic blocks (CLBs). Figure C.18 attached to this document, 100 Chapter 3. First-class Hardware Components shows an excerpt from the HDL descriptions of the microprogram unit that include the U0 ROM, the PC and the L0 logic. The sleep signal is activated by the Time Event unit operation during step one of the wait system call (line 1 of Table 3.1). In this step, the inputs i_sys_call and i_this_call cannot change since the HW-Task is already blocked, and by disabling the clock in C0 and FF0, the microprogram is considered suspended. Within a signal detection or timeout events, the sleep signal is revoked, allowing for the next active clock to update the C0 output. In doing so, the PC receives the absolute address for step two and the microprogram resumes the execution. Specific points in the accelerator model that use this hibernation signal include the HW-Task control, the kernel control and the sequential logic in the kernel’s datapath. The descriptions about each design unit will include the sleep feature. In the next subsection, we shall discuss the Time Event unit operation using a wave plot that includes the microprogram signals, while implementing the wait system call. Alternative RAM-based microprogram architecture uses true dual-port RAM in U0 to allow filesystem-based updates in the microcode contents can be consulted attached in Figure D.9. The binary code is loaded by the HAL-ASOS file system at start-up, and the storage resource is mapped by the S00 interface at supplementary page 8 offset. 3.1.5 Time Events In the proposed accelerator model, the time wait and event detection features are implemented using the Time Event unit, which provides parametrized services using the wait system call (line 1 of Table 3.1). Through this unit, the kernel provides synchronization services to the control of the HW-Task , being based on internal events that it expects to receive. Such events may result from known and synchronous sources, or asynchronous change in the logical signals that this entity receives from its design. Ultimately, waiting for an asynchronous event has a degree of unpredictability, which can be complemented with a timeout parameter in clock cycles. With this unit, the accelerator model seeks to enclose waiting events in a single resource to avoid consequent replication of counters. At the same time, it seeks to mitigate the energy waste associated with these waiting cycles, by providing a sleep feature that disables the clock at strategic points in the HW-Task and Kernel Core designs. In doing so, whenever the HW-Task enters a sleep state, the kernel will act in accordance, disabling the clock sources of the functional units in its datapath. On the other hand, if the Chapter 3. First-class Hardware Components 101 accelerator is not running, the kernel control uses this service to disable the same functional units, while waiting for the host system to intervene in the control register. Figure 3.14 describes the design of the Time Event unit through a simplified block diagram. The central element in the datapath is the C0 that implements clock cycle counting until it achieves a timeout value that receives on its input. For appropriate semantics, this timeout is converted using two’s complement in A1, and in doing so, the count value starts from that result to zero. 1result ADD ALU TWO’S COMPLEMENT Counter Q[M-1:0] EN reset clock inc load D[M-1:0] OV i_timeout_val timeout_i o_remaining_time increment_counter_i load_counter_i reset clock FF3* o_timeout clock Control Unit i_event ALU match no_time_i compare 0 1result ADD ALU TWO’S COMPLEMENT i_trigger reset D Q clk reset D Q clk reset D Q clk o_event_signal o_ready o_sleep FF2 FF1 FF0 C0 A0 A1 A2 Time Event clock reset reset reset reset reset M :16-BIT (CEVENT_TIMEOUT_WIDTH) enable_i reset D Q clk timeout_i i_event sleep_i CE CE CE sleep_i clock clock sleep_i clock sleep_i ready_i ev…signal_i Figure 3.14: Time Event unit - simplified architecture diagram. Once in service, counting can be interrupted by detecting the event input, or ultimately by exhausting the counter, which is signaled by the internal timeout. At completion, the remaining count is converted back in A2 and returned to the HW-Task using the remaining time output. The overall design of the datapath is equivalent to a down-counting circuit that can load absolute count intervals. The resource management is supervised by the control unit that loads, activates and stops the C0 counter. At the same time, the control is sensitive to the event and trigger inputs while establishing the ready , sleep and event signals on the outputs. The event input is connected to the HW-Task sourced signal by means of the system-level datapath in the Kernel Core , and the trigger signal is activated by the microprogram to start counting. For this, the ready output is used, informing the microprogram about the resource state. If the timeout value is null at the input, the internal signal no_time_i is set to logical ’1’. The control unit reacts by disabling the enable_i signal that suspends the C0 counter. At the same time, it will enable the sleep output and wait 102 Chapter 3. First-class Hardware Components indefinitely for a signal rise at the input event . The sleep output is distributed by the accelerator design to disable clock sources, and internally, this signal is directly applied to the logic elements FF1, FF2 and FF3. Finally, the output that results from the event detection, is sent back to the microprogram so that it can complete the system call. Figure 3.15 describes the control of the Time Event unit using a logic state diagram. After an initial reset signal the control logic reaches #0, where it activates the ready output and waits for a trigger signal to initiate a new event. Once at #1, the control enables the clock in C0 using the internal enable signal and together with load , enables the write of the timeout value received in its input. #3 Sleeping /sleep_i #2 Counting /incr.._counter_i /enable_i i_trigger/ #0 Ready /ready_i #1 Load /load_counter_i /enable_i #4 Signal /event_signal no_time_i i_event i_event V timeout_i i_trigger/ Figure 3.15: Time Event unit - control logic state diagram. With a non-zero timeout, the control advances to #2, where it keeps the clock active and starts counting, by activating the increment signal. The reception of a logic ’1’ in the event input, or the occurrence of a timeout in the counter, completes the counting state and the control advances to #4. If the timeout value at the input is null in #1, the control advances to #3, where it waits indefinitely for the event input while keeping the sleep output active. With a logic ’1’ in the event input, the sleep state concludes and control advances to #4. Once in #4, the unit activates the event output and synchronizes the operating mode, waiting for the trigger input to be disabled. Upon disable, the control unit returns to #0 and signals that it is ready for a new processing round. Figure 3.16 shows a wave plot that results from the simulation of the Time Event unit using Vivado, in the context of the accelerator design where it is implemented. For this purpose, the HW-Task implements a system call to wait for an event and considers a timeout of 6 clock cycles. At the bottom of this diagram, it can be seen the parameters in use, as well as the microprogram control signals. The system call starts at Chapter 3. First-class Hardware Components 103 10,505.00 nanoseconds and in step 0, the microprogram evaluates the operationality of the Time Event unit. A clock cycle later, the microprogram reaches step 1 and activates the trigger signal, staying in this step until event detection. Figure 3.16: Time Event unit - Wait for a signal event using a 6-clock timeout. The control of the Time Event unit responds to the trigger signal stimulus and advances to state 1, loading the counter with 6, and one clock cycle later, when state 2 is reached, it starts counting. After 6 clock cycles, counter time is exhausted and the internal timeout signal is asserted. The control unit advances to state 4 and signals the event detection through its output o_event_signal . Upon receiving this signal, the microprogram proceeds to step 2 and releases the context of the HW-Task . At the same time, the systemlevel datapath transfers the timeout result and the remaining count value to the return register. In the context of the HW-Task , the system call concludes with a false boolean extracted from the return_arg register at position 62 (PARAM_TIMEOUT_STATUS). And in the position range [15:0] (PARAM_TIMEOUT_VAL’ range) this unit can check for a remaining time value. For completeness, similar plot using event detection can be consulted in Figure D.3 and Figure D.4 shows the same simulation using a zero-timeout parameter. 3.1.6 System-Level Datapath The system-level datapath establishes correspondence between the system call interface, the microprogram and the resources in the accelerator model. For this, it selects one of three interfaces that provide 104 Chapter 3. First-class Hardware Components access to local resources as it was shown in Figure 3.4. Among these interfaces we can find the HW-FIFOs input and output interfaces, the Local-BUS, and the M00-BUS. Alternatively, the system-level datapath can select the TimeEvent internal peripheral while providing timing services. The design is predominantly combinational and operates in conjunction with the microprogram, to exchange data between individual resources and the members of the system call. In Figure 3.17 we can see the system-level datapath architecture, described using a simplified diagram. Local-BUS Time Event M00_BUS 1100101100100 0001001001001 0110010001001 0000110010101 1100101100100 0001001001001 0110010001001 0000110010101 pop_msg push_msg message_t message_t parameters return_arg Message Queue …… S00_Control i_event evm_trigger i_timeout event_signal sleep o_remaining_time o_timeout_signal addr lbus_rd_ce txdata lbus_wr_ce be cs burst_target maddr mbus_rd_req mtxdata mbus_wr_req mbe burst_target lbus_rd_ack lbus_wr_ack rxdata mblen Cmd_ack Cmplt mrxdata BurstDone cresponse.sys_call_i cresponse.sys_call_i Kernel_Call.parameters Kernel_Response.return_arg SYS..WRITE_MESSAGE SYS..READ_MESSAGE SYS..WAIT.._TIMEOUT SYS..WAIT.._TIMEOUT SYS.._READ_LBUS SYS.._WRITE_LBUS SYS.._R..LBUS_BURST SYS.._W..LBUS_BURST SYS.._READ_LBUS SYS.._WRITE_LBUS SYS.._R..LBUS_BURST SYS.._W..LBUS_BURST SYS.._READ_MBUS SYS.._WRITE_MBUS SYS.._R..MBUS_BURST SYS.._W..MBUS_BURST SYS.._READ_MBUS SYS.._WRITE_MBUS SYS.._R..MBUS_BURST SYS.._W..MBUS_BURST SYS.._MUTEX..LOCK SYS.._MUTEX..TLOCK SYS.._MUTEX..UNLOCK SYS.._MUTEX..LOCK SYS.._MUTEX..TLOCK SYS.._MUTEX..UNLOCK CE reset DQ clk FF4 SYS_CALL_IDLE valid clock reset Microprogram control signals Datapath signals Sleep signal M2 M3 data_ready data_valid ready_for_data ack_data evm_ready Figure 3.17: System-Level datapath - system call signals and target resource. At the top of the figure, we can see the system call interface signals that connect with this design, after being selected by the kernel control state, as it was seen in Figure 3.10. Input parameters are received at the M2 demultiplexer, which operates according to the type it receives from the microprogram control output. As such, it extracts predetermined fields from a system call to connect with one of the four logical elements visible in the center of the figure. Conversely, the signals received from each logic element are inputs to the M3 multiplexer, which are selected by the same type as in M2 and concatenated to form the fields in the return of the system call. To handle clock cycle transactions, the return member fields are sent directly from M3 to the kernel output. At completion of each system call, these are stored in FF4, Chapter 3. First-class Hardware Components 105 so that they are available beyond execution. For that, the microprogram must reach an idle state (i.e., SYS_CALL_IDLE), or otherwise a new system call will update these registers with new data. The interface that the kernel provides with the HW-FIFOs, is used to submit or retrieve control words, that the accelerator model distinguishes between committed to kernel or to the HW-Task . In these components, the design is aligned with the transfer rate of a clock cycle and takes advantage of parallelism to exchange data above the word length. Figure 3.17 shows a Message Queue used to exchange kernel messages, which is implemented using two HW-FIFOs. In this logical element, the length of the data is specified by the predefined type message_t , which in the standard configuration is using two words (64 bits). Whenever the microprogram executes one of the two system calls that exchange messages, the receiving parameters and return members are connected with the input or output of the Message Queue. Similar resource is the Data-FIFO logical element that despite using the same design, it does not have a pre-defined type. Instead, the length of data is based on a predefined number of words that can be changed at the top-level of each accelerator. In doing so, different lengths between different accelerators can be used in the same design, or even be different between sent and received in the same design. For this reason, only the control signals are provided by the microprogram, and the datapath is not included in the kernel design, being connected directly to the HW-Task . With respect to control signals, three are used in each logical direction of transfer, one being input and two outputs, as can be seen in the same figure. Depending on the direction, the first output signal indicates to the microprogram that each device is ready to receive, or to provide available data. The input signal triggers the exchange and is produced by the microprogram outputs, and the last control signal is used as a handshake, indicating that the data has been received, or should be read at the output. Implementation details will be discussed in section 4.4, and the type of messages that can be exchanged will be discussed in section 3.2. Figure 3.17 also shows the connection with the Time Event unit. Since it is a local resource, none of the previous interfaces is used while executing the wait system call. For this purpose, three control signals connect with the microprogram, and seventeen bits from the parameters and return members in the system call records, connect with the inputs and outputs of the Time Event unit. In the parameters member, sixteen bits specify the timeout value and the position of one bit is used to establish the connectivity between the received event and the input event in the device. In the return member, the same 16-bit position is used to send back the remaining time, and one bit is used to indicate the occurrence of timeout. Once 106 Chapter 3. First-class Hardware Components in execution, the microprogram waits for the ready signal before starting a new event. The new event is set using the trigger signal which gives rise to the sleep output that suspends the microprogram execution and strategic points across the accelerator model. Upon receiving an active input event, or an exhausted timeout signal, the sleep output is cleared and the microprogram resumes the execution. Figure 3.18, shows excerpts of two files containing Time Event related descriptions, used by the systemlevel datapath. These are part of the configuration package, lines 12 to 47, and the kernel package, lines 10 to 95. It is also possible to observe excerpt descriptions of the system-level datapath in the Kernel Core design, lines 562 to 576. In the configuration package, we find two redefinable constants that set the timeout bit width and the time interval before the kernel sleep state, as mentioned earlier in subsection 3.1.2. package hal_asos_configs_pkg is 12 ... constant C_EVENT_TIMEOUT_WIDTH :natural :=16; 46 constant C_KERNEL_TIME_TILL_SLEEP: 47 std_logic_vector(C_EVENT_TIMEOUT_WIDTH-1downto0):= x"C0DE"; ... package hal_kernel_pkg is 10 ... subtype PARAM_TIMEOUT_VAL IS std_logic_vector(C_EVENT_TIMEOUT_WIDTH-1 downto 0);--[15:0] 93 constant PARAM_SIGNAL_SOURCE: natural:= (C_MESSAGE_WIDTH-1); 94 constant PARAM_TIMEOUT_STATUS: natural:= (C_MESSAGE_WIDTH-2); 95 ... architecture Behavioral of kernel_core is 126 ... case cresponse_i.sys_call_id is 562 when SYS_CALL_WAIT_EVENT_TIMEOUT => 563 time_event_selected_timeout <= sys_call_i.parameters(PARAM_TIMEOUT_VAL'RANGE);--[15:0] 564 time_event_selected_event <= sys_call_i.parameters(PARAM_SIGNAL_SOURCE);--[63] 565 dresponse_i.return_arg(PARAM_TIMEOUT_VAL'RANGE)<=time_event_remaining;--[15:0] 566 dresponse_i.return_arg(PARAM_TIMEOUT_STATUS)<=time_event_timeout_signal;--[62] 567 ... Figure 3.18: System-Level datapath - Time event parameters and return signals. In the kernel package, we find positions for the parameters used in the system call members. The timeout received and returned parameters use the least significant bits (e.g., 15 down to 0) defined by the subtype of line 93. The signal event position is defined in line 94 and the timeout status flag position in line 95. Such positions are then used in Kernel Core descriptions to establish connectivity with the Time Event unit. Lines 564 and 566 use the timeout bit range in the assignment, and lines 565 and 567 assign the event status and the timeout flag using the above positions. The assignments are active when the system call ID matches the value specified in line 562. Similarly, Figure 3.19 shows excerpt descriptions of the same design, but this time focusing the connections of two system calls that use the burst format, to exchange data across the Local-BUS and the Chapter 3. First-class Hardware Components 107 M00-BUS interfaces. In this format, a consecutive number of words is exchanged, starting from an initial offset and until a parameter number is achieved. These two resources follow a generic interface model that aims to promote data exchange to a single format, and in doing so, similar descriptions are used to implement the system-level datapath connections. Details about this generic interface will be discussed in section 3.3. architecture Behavioral of kernel_core is 126 ... case cresponse_i.sys_call_id is 608 ... when SYS_CALL_WRITE_LBUS_BURST=> 712 task_status <= TASK_WRITING; 713 lbus_burst_syscall_i <= '1'; 714 o_lbus_cs <= '1'; 715 o_lbus_addr<= sys_call_i.parameters(PARAM_LBUS_OFFSET'RANGE);--[53:36] 716 o_lbus_be <= sys_call_i.parameters(PARAM_LBUS_BE'RANGE);--[35:32] 717 o_lbus_dout<= sys_call_i.parameters(PARAM_LBUS_WORD'RANGE); --[31:0] 718 target_i(target_i'high-1 downto 0) 719 <=signed(sys_call_i.parameters(PARAM_LBUS_BURST_LEN'RANGE)); --[63:54] dresponse_i.return_arg(C_LBUS_DATA_WIDTH-1 downto 0) <= i_lbus_din; --[31:0] 720 dresponse_i.return_arg(PARAM_LBUS_BURST_LEN'range) 721 <= std_logic_vector(to_unsigned(cresponse_i.index,PARAM_LBUS_BURST_LEN'length)); error_source <= not(i_lbus_wr_ack); 722 when SYS_CALL_READ_MBUS_BURST=> 723 task_status <= TASK_READING; 724 o_kernel2_mbus_addr(31 downto C_MBUS_OFFSET_WIDTH) 725 <= sys_ram_addr_reg(31 downto C_MBUS_OFFSET_WIDTH);--[31:20] o_kernel2_mbus_addr(C_MBUS_OFFSET_WIDTH-1 downto C_PAGE_SHIFT)<= std_logic_vector ( 726 UNSIGNED(sys_call_i.parameters(PARAM_MBUS_PAGE_PREFIX'RANGE)) + UNSIGNED(sys_ram_addr_reg(C_MBUS_OFFSET_WIDTH-1 downto C_PAGE_SHIFT)) ); o_kernel2_mbus_addr(C_PAGE_SHIFT-1 downto 0) 727 <= sys_call_i.parameters(PARAM_MBUS_PAGE_OFFSET'RANGE) & "00";--[11:0]<-[45:36] o_kernel2_mbus_tlen <= sys_call_i.parameters(PARAM_MBUS_BURST_LEN'RANGE) ; --[63:54] 728 target_i(target_i'high-1 downto 0) 729 <= signed(sys_call_i.parameters(PARAM_MBUS_BURST_LEN'RANGE))-1; dresponse_i.return_arg(PARAM_MBUS_WORD'RANGE) <= i_mbus2_kernel_data; 730 dresponse_i.return_arg(PARAM_MBUS_BURST_LEN'RANGE) 731 <= std_logic_vector(to_unsigned(cresponse_i.index,PARAM_LBUS_BURST_LEN'length)); error_source <= i_mbus2_kernel_cmd_error or sys_ram_addr_reg(31); 732 ... Figure 3.19: System-Level datapath - Local-BUS and MBUS fields of system call. As in the previous peripheral, the implementation is based on the settings that the configuration and kernel packages establish, and can be consulted in Listing C.19 attached to this document. For this, the system-level datapath implements connectivity with the inputs signals: word, offset, byte enable (BE) and transfer length, and the system call parameters member. In the opposite direction, the output signals: word and the effective number of words transferred, are connected with the return member. The latter signal is part of the kernel index service which allows the HW-Task to manipulate data using array logical structures at kernel-level, and it will be discussed in the next subsection. In summary, the least significant 32-bit of the parameters and return members are used to exchange one word in both directions (lines 718, 720 and 730). The most significant 32-bit are split into 18 bits to specify 114 Chapter 3. First-class Hardware Components example of the HW-Task design. It can also be seen the top-level interfaces M00_TAS K and M00_KERNEL discussed in the previous section. HW-Task Control Unit system-call procedure (wait_event) system-call procedure (mutex_lock) system-call procedure (write_reg) S00_KERNEL M00_TASK M00_KERNEL S00_TASK HW-Kernel Kernel Core Kernel Call Kernel Response Microprogram System-level Datapath Kernel Call task_state_2 task_state_4 task_state_7 task_state_n system-call procedure (mutex_unlock) system-call procedure (write_lram_burst) system-call procedure (mutex_lock) operation-oriented procedure Kernel Response Index Scheduler Status sleep block run Figure 3.24: Kernel Core - execution runtime overview from the HW-Task perspective. The control unit of the HW-Task is responsible to activate concurrent system call procedures in its datapath, while it receives control signals to synchronize with the kernel execution. The moment a system call starts, the control unit suspends, keeping the procedure active until completion of the microprogram execution. Once active, the inputs and outputs of the procedure are updated by the execution of the microprogram and the system-level datapath, and in this sense, it is considered that these signals are controlled by the context of the kernel. To that extent, the procedure circuitry is seen as an HW extension of the Kernel Core . In the same figure, it can also be seen a user package procedure that is composed of three concurrent kernel procedures. Similarly, only one user procedure can be used in each state of the HW-Task control, and that particular state is repeated for each system call consecutive execution. For that, the user procedure relies on the kernel scheduling service to select each procedure accordingly. The HW-Task design is accountable for the additional logic inside a user procedure, to interconnect each kernel procedure with the kernel interfaces. In that sense, the interconnect logic is considered an extension of the HW-Task ’s datapath. In Figure 3.25 it can be seen the descriptions of the wait_event procedure in the kernel package. Such procedure, interfaces the wait system call and can be used to put the HW-Task into a sleep state while Chapter 3. First-class Hardware Components 115 waiting for a signal event in its design. For this, the HW-Task must connect the target signal with the event input, and when required, specify a timeout value using the timeout_val parameter. Alternatively, it can connect a logic ’0’ in the event input for using this service as time-based event. The descriptions in this procedure specify the system call ID on line 1152, and provide the received timeout value, on line 1153. In line 1154, it establishes a connection between the target signal and the system call parameter, and at line 1155, the this_call signal is set, triggering the microprogram execution. package hal_kernel_pkg is 10 ... ----------------------------------------------------------------------------------------------- 1144 procedure wait_signal_event(signal i_call : out kernel_input_t; 1145 signal o_response : in kernel_output_t; 1146 signal i_event : in std_logic; 1147 signal is_event : out boolean; 1148 constant timeout_val: in integer :=0) is 1149 ------------------------------------------------------------------------------------------------ 1150 begin 1151 i_call.sys_call_id <= SYS_CALL_WAIT_EVENT_TIMEOUT; 1152 i_call.parameters(PARAM_TIMEOUT_VAL'RANGE) 1153 <= std_logic_vector( to_unsigned(timeout_val,C_EVENT_TIMEOUT_WIDTH)); i_call.parameters(PARAM_SIGNAL_SOURCE) <= i_event; 1154 i_call.this_call <= '1'; 1155 is_event <= to_boolean(not(o_response.return_arg(PARAM_TIMEOUT_STATUS))); 1156 end procedure wait_signal_event; 1157 ------------------------------------------------------------------------------------------------ 1158 Figure 3.25: Kernel package procedures - wait signal event descriptions. To exchange parameters, the procedure descriptions make use of the kernel’s input interface, that connects with the output in this procedure, line 1145, using the HW-Task design. Likewise, the kernel output interface connects to the corresponding procedure input in line 1146. In this case, the timeout occurrence signal is used to stimulate the boolean output is_event , on line 1156. The procedure implementation remains active until the microprogram completes its execution and releases control of the HW-Task . In these descriptions, we can see that it completes without returning the remaining time value. As result, the HW- Task receives the boolean parameter that indicates the event occurrence, and if desired, the remaining time can be consulted using the return_arg member after the execution has completed. A simulation wave plot that includes this procedure descriptions was discussed in subsection 3.1.5 and can be seen in Figure 3.16. In Figure 3.26 we can see a snippet from the kernel package, that describes a procedure which reads from the local memory using the burst format. In the parameters of this procedure, we can also find the kernel input and output interfaces, followed by input parameters, such as transfer length and offset in the LRAM, and output data in the length of a word. In lines 1414 and 1415 the procedure specifies the system call and triggers the execution in the microprogram. The descriptions forward the input parameters to the 116 Chapter 3. First-class Hardware Components corresponding signals on the kernel Call interface, in lines 1416 to 1418, and in the opposite direction, in line 1419, it forwards the received word to the output parameter data . package hal_kernel_pkg is 10 ... ------------------------------------------------------------------------------------------------ 1405 procedure lram_read_word_burst (signal i_call : out kernel_input_t; 1406 signal o_response: in kernel_output_t; 1407 transfer_len:in natural; 1408 lram_offset: in natural range 0 to (2**CLRAM_AWWIDTH)-1; 1409 data: out std_logic_vector(31 downto 0))is 1410 ------------------------------------------------------------------------------------------------ 1411 begin 1412 1413 i_call.sys_call_id <= SYS_CALL_READ_LBUS_BURST; 1414 i_call.this_call <= '1'; 1415 i_call.parameters(PARAM_LBUS_BE'RANGE) <= "0000"; 1416 i_call.parameters(PARAM_LBUS_ADDR'RANGE) 1417 <= '1'& std_logic_vector(to_unsigned(lram_offset,CLRAM_AWWIDTH)); i_call.parameters(PARAM_LBUS_BURST_LEN'RANGE) 1418 <= std_logic_vector(to_unsigned(transfer_len,PARAM_LBUS_BURST_LEN'LENGTH)); data := o_response.return_arg(PARAM_LBUS_WORD'RANGE); 1419 1420 end procedure lram_read_word_burst ; 1421 ------------------------------------------------------------------------------------------------ 1422 ... 1 Figure 3.26: Kernel package procedures - read local-RAM in burst format descriptions. Once in execution, the system call will use the system-level datapath in the Kernel Core , to activate the index service and the microprogram will repeat the step two until it receives a burst done signal from the index service. In doing so, a different word is sourced at the data output parameter, and the HW-Task is responsible for implementing the path that consecutively distributes the received words by the distinct destination registers. In this case the index_d1 field of the kernel interface will be used to select the target register. Once again, the descriptions in this procedure can be translated into wires between the kernel interfaces and the datapath of the HW-Task . The kernel package includes more procedures beyond those that were seen until now. Due to the extensive descriptions that these require, we’ve decided to include procedures that relate to the accelerator model internal features. Other procedures target the synchronization and manipulation of software features in the Linux OS or the target application. We shall discuss some of these in the following section. 3.2 HW-Task In the HAL-ASOS accelerator model, the HW-Task represents an execution flow that is part of a Linux application and was implemented using equivalent logic circuits that counterparts to a software-based computation. In this way, the base concept of a Linux application is retransformed to a combination of Chapter 3. First-class Hardware Components 117 hardware and software execution flows, dictated by the system requirements. When offloading software computations via HW-Task (s), an application can benefit from the intrinsic parallel nature in the hardware circuits, which were designed according to the system’s requirements and use just the right resources. On the other hand, the boundary crossing between the HW and the SW implementations can overcome the benefits in the mixed design architecture. To avoid multiple and consecutive design iterations, the candidates to computation offload must be identified using the OProfile tool in the design methodology, followed by a functional Co-Simulation as covered in Chapter 2. In this section, we describe the HW-Task design and introduce the HAL-ASOS programming model through examples. We then describe the HW-Task interaction with the Linux software application and the OS services. 3.2.1 Programming Model The HW-Task is the processing entity in the HAL-ASOS programming model that integrates FPGA-based computation into Linux software applications. To ease development, the framework provides a template design for the HW-Task that is independent from the HW-Kernel . It includes RTL descriptions with: (1) a state machine structure for the control unit that is synchronized with the Kernel Core system calls; (2) the sleep infrastructure where all sequential units subject to this state will be instantiated; and (3) the connectivity between the HW-Task design and the kernel interfaces to and from the top-level signals in this component. Figure 3.27 shows an example of the HW-Task template model and to better illustrate the design and the internal connectivity of this component, two black boxed IPs were added to the datapath. To comply with the traditional design of the logic circuits, such design is divided into a control unit and a datapath. Here, the control unit implements the state logic that establishes the behavior of the HW-Task by sensing specific signals from the datapath. Additionally, some of the HW-Kernel interface signals are also considered, namely the task_run and the task_error . The first signal triggers the HW-Task activity for the required processing rounds, and the latter signals a system call error that can be used to trigger handling states at the HW-Task level. In this model, the FF0 register establishes the current state of the control logic, where each state determines the set of active control signals and the value of the next state in M0. When a state requires a procedure to implement a system call, the value of the next state can be set concurrently, as if it was a one clock-cycle state. Once reaching such state, the control unit will activate the chosen procedure and 118 Chapter 3. First-class Hardware Components 0 1 CE reset DQ clk state block_task next_state switch_state Control Unit HW-Task Combinational state logic task_run error_flag S00_Kernel M00_Task FF0 M0 task_restart resetn reset_i user procedure Kernel Call Kernel Call Kernel Response select state parameters return_args sys_call_id index index_d1 valid sched_progress this_call sys_call_id enable_scheduler enable_index increment_index reschedule clock clock user procedure params_0 params_1 (import) (export) params_0 Black Box IP run done reset params_1 CE reset_i CE G0 F0 M1XF1 UP0 UP1 U1 FF2 FF3 Datapath Extended features task_sleep clock task_sleep reset_i Black Box IP run done reset U0 CE FF1 clock task_sleep error_u1 results_u0 ref_u0 results_u1 Figure 3.27: Hardware Task - simplified example architecture. in response, the HW-Kernel interface will raise the block_task signal. In doing so, the current state will be maintained for the necessary number clock-cycles, thus allowing the procedure to complete. Upon completion, HW-Kernel lowers the block_task signal, enabling back the clock in FF0 and in the next active clock transition the state register is updated with the next state value. In its turn, the datapath provides the necessary resources for computing the set of data it receives as input. Generally, a datapath consists of specific design logic functions to compute data and sequential logic for storing results. Depending on the data-level parallelism, a datapath can achieve a fixed length expressed in clock-cycles, usually referred as processing stages. Such stages are intended to promote the throughput of the datapath by maximizing the usage of the logical units that it implements, following a design structure usually referred as the execution pipeline. In the datapath of Figure 3.27, the two IPs U0 and U1 are the implementation of this combinational logic and the registers FF1, FF2 and FF3 are the sequential units that establish the progress of the data across the datapath. Chapter 3. First-class Hardware Components 119 The proposed programming model implements an extended layer with application-based functionality, that uses a mix of control and datapath signals. In this new design level, the kernel or user package procedures are implemented concurrently and are primarily scheduled selecting each Kernel_Call at the M1XF1 inputs, by use of the state register. Conversely, each procedure receives a connection with the Kernel_Response in parallel with other procedures in the same level. For this, logic function F0 translates signals from S00_Kernel to the Kernel_Response interface, and similarly, M1XF1 is composed of a logic function that translates the selected Kernel_Call to the M00_Task interface. For this example, we have included two user procedures, UP0 and UP1, where the topmost procedure outputs the received data to FF1 which is input to the datapath, whereas the bottommost procedure receives data as arguments using FF3 which is output from the datapath. As such, the simplified HW-Task example is using the two concurrent procedures to exchange application data using the accelerator model. For a better understanding, Figure 3.28 shows an excerpt from the HW-Task that describes this implementation. import_kernel_response( s00_kernel_sys_call_id, s00_kernel_return, s00_kernel_valid, 209 s00_kernel_syscall_progress, s00_kernel_sched_progress, 210 s00_kernel_index,s00_kernel_delayed_index, s00_kernel_block_task, 211 s00_kernel_sleep_task, s00_kernel_error_flag, kernel_response); 212 213 export_kernel_call(kernel_call, m00_task_sys_call_id, m00_task_parameters, 214 m00_task_this_call,m00_task_enable_scheduler, m00_task_reschedule, 215 m00_task_enable_index,m00_task_increment_index); 216 --------------------------------------------------------------------------------------------------- 217 EXTENDED:process(state,params_u0_q, params_u1_q, kernel_response, local_offset_q, 218 sys_offset_q) --------------------------------------------------------------------------------------------------- 219 begin 220 params_u0_i <= params_u0_q; 221 hal_asos_link_to_kernel(kernel_response,kernel_call); 222 case state is 223 when st1_read_data=> 224 safe_read_lram_word32_burst(kernel_call,kernel_response,params_u0_i,4, local_offset_q); 225 when st4_write_data=> 226 safe_write_sysram_word32_burst(kernel_call,kernel_response,params_u1_q,8, sys_offset_q); 227 when others=> null; 228 end case; 229 end process EXTENDED; 230 --------------------------------------------------------------------------------------------------- 231 Figure 3.28: Task Model - concurrent user procedure description example. To connect the top-level interfaces with the implemented user procedures, lines 209 and 214 implement two concurrent kernel procedures. The first procedure receives as input the HW-Kernel slave top-level signals and outputs the kernel_response record, which is the output of the Kernel Core ’s defined interface. In the opposite direction, the second procedure receives the kernel_call record as input and provides the output signals that connect with the HW-Task master interface. The two procedure implementations use only connect logic with the purpose of providing the Kernel Core interfaces locally. To implement the extended features level, a combinational process in line 218, uses the state register in the sensitivity list, 120 Chapter 3. First-class Hardware Components together with kernel_response record and the parameters that each procedure requires as input. In these parameters, we can find the signals that connect with the datapath’s logic units (i.e., params_u0_q and params_u1_q), and two address registers used in each procedure. A case statement will activate the user procedures in lines 225 or 227, when the control logic reaches the st1 or st4 states, respectively. In doing so, the kernel_call will be updated with signals from a specific procedure implementation, while it senses the kernel_response received as argument. For as long as the control unit remains in one of these logic states, the corresponding procedure will be set to active to update the correspondent outputs according to the changes in the input parameters that it receives. In response, it will generate the appropriate outputs using the kernel_response or the params_u0_i signals. When the control logic is implementing the remaining states that are not considered in the enclosed cases, a kernel procedure at the line 222 will keep the connectivity between the HW-Task and the kernel interface in a consistent state, using the default logic signals. Similarly, the params_u0_i will be tied to the last received results that were stored in the FF1 register, using in a self-closed loop design (line 221). Figure 3.29 shows an excerpt with descriptions for implementing the sequential logic in the datapath and control unit of the HW-Task example. In these, a logic function is used to establish the internal reset of such logic, using the target platform or the kernel software reset sources (line 161). In the line 163, a process describes the FF0 state register that is set to the initial state by the active rise in the clock signal and a logic ’1’ in the internal reset (in line 168). If otherwise such reset is low, a logic ’0’ in block_task signal will store the next state in the logic sequence. Using this description style, the blocking signal will be source to the clock enable pin of this logic element by using the necessary logic function. In doing so, the clock will be disable when executing kernel procedures, thus providing the necessary clock cycles before storing the next state value and proceed in the state logic. A similar style is used to describe the sequential elements in the datapath using the process at the line 175. The sleep task signal in the kernel interface is used to enable the clock in these logic elements. In this way, the clock will be active while executing kernel procedures thus allowing the output arguments to be stored in these elements. Once in sleep condition, the clock source is disabled in the logic described by both processes and since such condition is the result of the wait system call, it also ensures a block condition until the input event is detected. Nevertheless, a distinction must be made according to the necessary instance in time where the provided source is available. A block condition will cease in the last step of the system call execution, whereas the sleep condition will be completed in the next state in the Chapter 3. First-class Hardware Components 121 1 reset_i <= s00_kernel_swrst or not(resetn); 161 ------------------------------------------------------------------------------------------------ 162 ff0:process(clock) 163 ------------------------------------------------------------------------------------------------ 164 begin 165 if rising_edge(clock) then 166 if reset_i = '1' then 167 state <= st0_ready; 168 elsif kernel_response.block_task = '0' then 169 state <= next_state; 170 end if; 171 end if; 172 end process ff0; 173 ------------------------------------------------------------------------------------------------ 174 dpath_seq:process(clock) 175 ------------------------------------------------------------------------------------------------ 176 begin 177 if rising_edge(clock) then 178 if reset_i = '1' then 179 params_u0_q <= (others=>(others=>'0')); --reset ff1 180 result_u0_q <= (others=>(others=>'0')); --reset ff2 181 params_u0_q <= (others=>(others=>'0')); --reset ff3 high 182 u1_error_q <= (others=>(others=>'0')); --reset ff3 low 183 elsif kernel_response.sleep_task = '0' then 184 params_u0_q <= params_u0_i; --ff1 185 result_u0_q <= result_u0_o; --ff2 186 params_u1_q <= params_u1_o; --ff3 high 187 u1_error_q <= u1_error_i; --ff3 low 188 end if; 189 end if; 190 end process dpath_seq; 191 ------------------------------------------------------------------------------------------------ 192 Figure 3.29: HW-Task Model - Sequential units descriptions using VHDL. logic sequence after implementing the wait procedure. 3.2.2 User Procedures User package procedures, or user procedures, are a subset of low-level operations, wrapped inside a VHDL language procedure that can be instantiated when developing HW-Task s for the HAL-ASOS accelerator model. Such procedures operate at the extended level in HW-Task and can be seen as an auxiliary subprogram, similar to a library used in software-based applications. In its essence, a user procedure provides means to implement a specific feature that is based on more than one HW system call. Thus, they establish interface with the required input and output parameters while implementing the correspondence with the required system call procedures. In addition, user procedures are also distinguished by providing advanced data formats, such as unconstrained arrays or multiple words, or user-defined types that are not supported at kernel-level, and a semantic abstraction of the Linux programming interface. Figure 3.30 shows a typical architecture of a user procedure that implements concurrent system calls from the kernel package, and uses the scheduler service in the Kernel Core to ensure a proper execution. 122 Chapter 3. First-class Hardware Components The scheduling service divides the procedure into nsteps, and establishes a sequence in the concurrent system calls, by sensing the reschedule signal that is provided internally. In doing so, the procedure descriptions implement M0 that ensures an exclusive connection between the Kernel_Call interface and the subset of outputs from each system call, where all inputs connect with the Kernel_Response and receive input parameters in parallel. Index_d1 system-call procedure system-call procedure system-call procedure … 0 1 N-1 Kernel_Response Kernel_Call enable_scheduler reschedule User-level procedure compare match ALU A1 target_1 enable_index sched_progress parameters parameters parameters return_args return_args return_args … Index service (optional) Parameter_0 Parameter_1 Parameter_2 word_out Index_d1 sel 1:M valid reschedule M0 M1 offset Figure 3.30: User package procedures - scheduling concurrent system calls. From the bottom of the same figure, it can also be seen that the user procedure receives inputs and provides outputs with the HW-Task context. Here, two inputs and one output parameters are used (i.e., Parameter_0 , Parameter_1 and Parameter_2 , respectively), where together the input parameters are read-only signals and the output parameter represents HW-Task resources, handled by the execution in the user procedure. A constant offset is also provided internally and connects with the top- and bottommost system calls. These two system calls are a common example of the mutual exclusion invocation, using the HW-Mutex lock and unlock procedures in the kernel package. The input parameters provided by the HW-Task context, are connected to the system call used in step 1, and is a typical example of a multiple word read that expects an address offset and transfer length as input, and where a consecutive number of words can be provided as output. In such case, the system call implements a burst format transfer and the target length is used at kernel-level to repeat the word exchange in the required number of times. If otherwise the involved resources do not allow such format, Chapter 3. First-class Hardware Components 123 an alternative single word exchange system call can be selected to implement an equivalent operation. For this reason, the target parameter will be used at the HW-Task level to implement repeated executions of the same step, until the transfer length is completed. Optionally, to control the repetition process, ALU A1 is used to compare the index register with the received target length. To establish the desired scheduling, in step 0, the Valid flag is used to trigger the first scheduling operation. Similarly, in step 1, the same flag can be used if the system call provides burst format, or alternatively, if a system call repeat is in use, the reschedule signal can result from the match signal in A1. Considering that an array of data is provided as output of the user procedure, a demultiplexer M1 is implemented locally to connect each of the 32-bit words to the corresponding position in the array. Such component, uses the index register in the delay of one clock cycle, to select the appropriate position of each word of data that is received from the system call. In the last step, the scheduler service is deactivated, resulting in the HW-Task context release with the completion of the system call, and therefore, the conclusion of the user procedure. For completeness, Figure 3.31 shows a user procedure description that implements similar architecture to the diagram of Figure 3.30. Such procedure allows to safely read a consecutive number of words from the SYSRAM memory region in the host system. For this, in steps 0 and 2, it invokes the system calls to lock and unlock the required HW-Mutex, making use of the internal offset as parameter in each procedure (e.g., lines 1775 and 1783, CSYSMUTEX_WOFFSET , defined externally in the configuration package). In step 1 starting at line 1775, the procedure invokes the system call to read a consecutive number of words, expressed by the input parameter word_len and starting at the specified input parameter offset , while using the burst transfer format. In doing so, it requires the use of the index_d1 value to index the correct position in the pbuff array, as shown in line 1779. To ensure a proper memory address that is aligned with the host system, the received word-based offset is multiplied by four or by eight according to the parameter C_HOST_ARCH defined in the configuration package. The resulting logic are simple wires implementing a misaligned connection between input parameter offset and the variable param_woffs at line 1760, which in turn is an input parameter of the system call at line 1778. An if clause is used at line 1764 to prevent the procedure from running with transfer length zero. It immediately disables the scheduler and releases the HW-Task , preventing any connection with the i_call interface. If otherwise the word_len is greater than zero, the scheduler service is activated in line 1769, blocking the HW-Task for multiple system calls. Once reaching step 2 starting at line 1781, the service 226 Chapter 5. Experimental Results of 50 MHz, for the two equivalent designs. The left side of Figure 5.29a, shows the tests carried out on the single-task asynchronous control that uses the accelerator version V4_00_A. Although the control task is heavily conditioned by concurrent data reading and writing operations, the test performed records a total time of 50 milliseconds in each execution, and the done performance counter records a total of 2,161,332 clock cycles for the best HW-Task execution. Linux buildroot 4.9.0-xilinx #9 SMP PREEMPT Wed Jul 22 16:08:43 WEST 2020 armv7l GNU/Linux # ls /hal-asos/ FastDetectorSA2 hal_asos_resources # time ./feature_detector e 1080p/1920_1080_table_i.pgm 8192 [FastDetectorSA2<HwTask>]:finished...(254,4622) real 0m 0.05s user 0m 0.03s sys 0m 0.02s # time ./feature_detector e 1080p/1920_1080_table_i.pgm 8192 [FastDetectorSA2<HwTask>]:finished...(254,4622) real 0m 0.05s user 0m 0.01s sys 0m 0.04s # cat /hal-asos/FastDetectorSA2/performance-counters/done_counter ------------------------------------------------------------ - Performance Counter: done_counter Results ------------------------------------------------------------ Control Register:0x0 Number of events: 02 Counter value: 02161332 Maxim event duration:02169054 [BusClks] Minimum event duration:02161332 [BusClks] Total events duration:0004330386 [BusClks] # (a) Tests using V4_00_A accelerator at 50 MHz. # ls /hal-asos/ MFastSA0 NonmaxSA0 hal_asos_resources # time ./feature_detector f 1080p/1920_1080_table_i.pgm 8192 [MFastSA0<HwTask>]:finished...(254,2073600) [NonmaxSA0<HwTask>]:finished...(4862) real 0m 0.05s user 0m 0.02s sys 0m 0.04s # time ./feature_detector f 1080p/1920_1080_table_i.pgm 8192 [MFastSA0<HwTask>]:finished...(254,2073600) [NonmaxSA0<HwTask>]:finished...(4862) real 0m 0.05s user 0m 0.01s sys 0m 0.05s # cat /hal-asos/MFastSA0/performance-counters/done_counter ------------------------------------------------------------ - Performance Counter: done_counter Results ------------------------------------------------------------ Control Register:0x0 Number of events: 02 Counter value: 02167760 Maxim event duration:02171980 [BusClks] Minimum event duration:02167760 [BusClks] Total events duration:0004339740 [BusClks] # (b) Tests using V4_00_F/B accelerators at 50 MHz. Figure 5.29: Performances of asynchronous V4_00_A and V4_00_F/B accelerators. On the right side, Figure 5.29b shows the tests performed to the design that uses the two accelerators V4_00_F and V4_00_B. In equivalent way, such design reads the input file using the SYSRAM storage, and writes the output file using the LRAM. The same datapath is in use but it was split between the two HW-Tasks , as in the previous asynchronous designs. In the two consecutive tests the application executed in 50 milliseconds and the done performance counter shows the best execution for the MFastSA0 of 2,167,760 clock cycles. 5.9 Performance Comparison To better distinguish between the four asynchronous designs, Figure 5.30 plots the average performance of the application, when the file is varied to increase the number of corners detected. In the same graph, it is possible to see the performance results of the application when using the software accelerated algorithms. Compared to HW accelerators in asynchronous design, all accelerators outperform software-only versions using 50 MHz clock frequency and input block size limited to 8 kB. Chapter 5. Experimental Results 227 A comparison between the four asynchronous versions confirms a dependence of the detection algorithm for the final performance of the application. When raising the number of corners, the designs that use the V4_00_B accelerators show a slight performance degradation. The design that uses two accelerators V4_00_F have a dedicated system memory interface for each accelerator to minimize bus transaction delays. For that reason, the application’s overall performance remains stable with increasing corners in the output file. For completeness, Figure D.13 shows detailed block diagram connections of the design that targets the Zynq7000 on the ZC702 platform, when using V4_00_F version accelerators. 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0 4.6k 33.7k 61.7k 90k Execution Time [seconds] Corners per Frame OpenCV (0.16) (0.21) (0.31) (0.44) (0.85) E.Rosten-C (0.08) (0.12) (0.17) (0.27) (0.59) DTask-4.00.b (0.08) (0.08) (0.09) (0.10) (0.11) Sin.Task-4.00.a (0.05) (0.05) (0.06) (0.06) (0.07) DTask-4.00.f (0.05) (0.05) (0.05) (0.05) (0.05) Application performances: using 8 kB transfers [1080P][50MHz] Figure 5.30: Performances for the asynchronous designs varying the input file. To assess the effects of input block size and frequency applied to the design, Figures 5.31 plots the performance results for the fastest design, (i.e., Dual-Task based on V4_00_F accelerators) using four frequencies while varying the input block size. In all tests, the file with the largest number of corners was used, i.e., jean.pgm file with 90,000 corners. With a clock frequency of 25 MHz, the application performance drops to 100 milliseconds and it is not influenced by the increase in block size. For frequencies beyond 50 MHz, the overall application performance raises with the input block size, and the frequency increase has an effect on the overall performance for block sizes larger than 8 kB. Tests performed at 142 MHz did not reflect a performance increase when compared to the previous 100 MHz mark, and the 16 kB block size was sufficient to maintain the performance level. Table 5.1 summarizes the distinct hardware accelerators discussed in this chapter, categorized by asynchronous and synchronous design strategy. It considers the target platform ZC702 from Xilinx at 100 MHz as target frequency and 16 kB as optimized block sizes for transferring input pixels. The first column 228 Chapter 5. Experimental Results 0 0.02 0.04 0.06 0.08 0.1 2kB 4kB 8kB 16 kB 32 kB Execution Time [seconds] Data block size DTask-4.00.f:25MHz (0.10) (0.10) (0.10) (0.10) (0.10) DTask-4.00.f:50MHz (0.08) (0.06) (0.05) (0.05) (0.05) DTask-4.00.f:100MHz (0.08) (0.06) (0.05) (0.04) (0.04) DTask-4.00.f:142MHz (0.08) (0.06) (0.05) (0.04) (0.04) Application performances Dual-task 4.00.f:block rising 90k Corners [1080P] Figure 5.31: Performances using dual-task V4_00_F accelerators and 90,000 corners. identifies the accelerator by the HW-Task name and the second column shows the accelerator version to which it was connected to. The third and fourth columns show the performance obtained and establish the order between the accelerators placing, the fastest ones at the top. At top stand the designs that rely on the SYSRAM memory region to read the input file. Compared to the LRAM based design (line 4), the performance difference is marginal (i.e., 10 milliseconds) when both designs are stimulated at 100 MHz. Due to a low, or null number of interrupt events in the system, the FastDetectorSA2 design is the most interesting and it also consumes the least logical resources. On the other hand, this is the most complex design and thus more difficult to update, maintain and functionally verify. In terms of resource usage, we can say that consumption does not increases drastically when the design scales using two accelerators. From the two topmost rows (right side of the table) it can be seen that the consumption of LUTS and FFS goes up 6.6% and 4.6% respectively. In contrast, the required RAM and BRAM logic goes down by 2.6% and 8.2% respectively. Is fair to say that the second accelerator logic overhead is neglectable when compared to the resource consumed by the overall single accelerator design. To distinguish the two control strategies discussed, we can say that the application performance improves about 30% with the asynchronous strategy. Beyond this point, the asynchronous model is more beneficial to the system because it reduces the number of interrupt events to less than half, or completely as in line Chapter 5. Experimental Results 229 2. Compared to synchronous examples, the difference between the two fastest designs is 33%, but in contrast, the synchronous design is simpler, faster to develop and verify, and can be implemented using half of the memory resources. For the above reasons we can say that the design that is best positioned to integrate the final application is the asynchronous dual-task using two accelerators in version V4_00_F. Lastly, the software and hardware accelerated application versions were compared in similar scenarios that can be found in the literature. Usually, these evaluate performance on a frame-per-second (FPS) rate using resolutions of 512x512, or 640x480, connected with digital cameras at the input of the datapath. An alternative test consists of reproducing this frame rate in numerous frames, by converting the files from the test dataset into the two above resolutions and replicated them in two input files. The files containing the lowest and highest number of corners were selected. Figure 5.32 shows results of tests performed using these two files. On the left side, Figure 5.32a shows the tests carried out using the table.pgm file converted to the 640x480 resolution and replicated 245 times in the input file. For this frame length, the software application lasted 4.32 seconds which is equivalent to 56 FPS. The application using the MFastSA0 and MNonmaxSA0 accelerators, an input block size of 32 kB and a design frequency of 142 MHz, takes 1 second to process the same input, which is equivalent to 245 FPS. The done performance counter shows that the execution of the MFastSA0 accelerator lasted 993.63 milliseconds. # ls /hal-asos/ MFastSA0 MNonmaxSA0 hal_asos_resources # time ./feature_detector e 640_480_table_if245.pgm [EdRosten-C]:finished!...(75264000, 475055) real 0m 4.34s user 0m 4.17s sys 0m 0.17s # time ./feature_detector b 640_480_table_if245.pgm [MNonmaxSA0<HwTask>]:finished...(390277) [MFastSA0<HwTask>]:finished...(2297,75264000) real 0m 1.00s user 0m 0.28s sys 0m 0.86s # cat /hal-asos/MFastSA0/performance-counters/done_counter ------------------------------------------------------------ - Performance Counter: done_counter Results ------------------------------------------------------------ Control Register:0x0 Number of events: 01 Counter value: 0141094839 Maxim event duration:0141094839 [BusClks] Minimum event duration:0141094839 [BusClks] Total events duration:000141094839 [BusClks] # (a) Tests using V4_00_F accelerators and 640x480 resolution. # ls /hal-asos/ MFastSA0 MNonmaxSA0 hal_asos_resources # time ./feature_detector e 512_512_jeanf270.pgm [EdRosten-C]:finished!...(70778880, 3353940) real 0m 36.04s user 0m 35.13s sys 0m 0.91s # time ./feature_detector b 512_512_jeanf270.pgm [MFastSA0<HwTask>]:finished...(2160,70778880) [MNonmaxSA0<HwTask>]:finished...(2229600) real 0m 0.99s user 0m 0.26s sys 0m 1.39s # cat /hal-asos/MFastSA0/performance-counters/done_counter ------------------------------------------------------------ - Performance Counter: done_counter Results ------------------------------------------------------------ Control Register:0x0 Number of events: 01 Counter value: 0141605982 Maxim event duration:0141605982 [BusClks] Minimum event duration:0141605982 [BusClks] Total events duration:000141605982 [BusClks] # (b) Tests using V4_00_F accelerators and 512x512 resolution. Figure 5.32: Full frame-rate operation using 100 MHz clock and 32 kB input block size. On the right side, Figure 5.32b shows the test based on the jean.pgm file, with a resolution of 512x512 in and input file containing 270 frames. For this frame-rate the software-based application lasted 38.04 seconds which equates to 7 FPS. The same hardware accelerated application lasted 0.99 seconds which 230 Chapter 5. Experimental Results HW-Task(s) Accelerator Time AVG LINTC RAM LRAM LUTs LUTRAMs FFs BRAM (version) (ms) (Clocks) (Evts.) (kB) (kB) cnt. (%) cnt. (%) cnt. (%) cnt. (%) Asynchronous design 100 MHz 16 kB block transfers Zynq7000-Soc (Xilinx ZC702 platform) MFastSA0 V4_00_F 40 2978000 1 64 1 12113 (22.77) 804 (4.62) 12564 (11.81) 10 (7.14) MNonmaxSA0 V4_00_F 2954773 9 4 1 FastDetectorSA2 V4_00_A 40 3255000 0 64 64 8160 (16.18) 1262 (7.25) 8027 (7.54) 21.50 (15.36) MFastSA0 V4_00_F 40 3311000 1 64 1 11804 (22.19) 834 (4.79) 12576 (11.86) 10 (7.14) NonmaxSA0 V4_00_B 2878388 73 - 4 FastSA0 V4_00_B 50 4015000 1 - 64 10982 (20.64) 784 (4.51) 12010 (11.29) 24 (17.14) NonmaxSA0 V4_00_B 3782638 37 - 64 Synchronous design 100 MHz 16 kB block transfers Zynq7000-Soc (Xilinx ZC702 platform) FastDetectorSA1 V4_00_F 60 5437404 136 64 1 7786 (14.64) 722 (4.15) 7783 (7.40) 7.50 (5.36) MxFastDetectorSA1 V4_00_F 70 5817009 136 64 1 7708 (14.49) 722 (4.15) 7856 (7.38) 7.50 (5.36) FastDetectorSA0 V4_00_B 70 6203700 135 - 64 7255 (13.64) 720 (4.14) 7642 (7.18) 21.50 (15.36) MxFastDetectorSA0 V4_00_B 80 7151521 133 - 64 7269 (13.66) 712 (4.09) 7559 (7.10) 21.50 (15.36) Table 5.1: Hardware Accelerated Feature detection designs comparison. Chapter 5. Experimental Results 231 equates to 270 FPS, and the result of the performance counter shows a duration of 997.23 milliseconds for the MFastSA0. While in previous tests, the hardware accelerated designs achieved a processing rate of one pixel per clock, this level of performance cannot be permanent when operating in an OS environment such as Linux. This OS has a base scheduling policy that ensures a fair distribution of the CPU resource to the other tasks in the system. From the tests carried out on the hardware, we can say that the design on the FPGA allows a frame-rate of 460 FPS for a resolution of 640x480, and a frame-rate of 541 FPS for a resolution of 515x512. In the Linux environment, such performance can only be achieved by providing a video stream locally, using a digital camera connected at the input of its datapath. Example of such connectivity is the DCMI parallel interface from STMicroelectronics [33] used in some digital cameras with this resolution ranges. To the best of our knowledge no tests have been found in the literature that consider the Linux OS and achieve the experimental performances of our designs. In most cases, the target image is already available in the design local storage consuming all RAM-based logic in the FPGA and do not consider the transfer time. Table 5.2 lists publications that can be compared to this design. SOA Target Frame fps f Platform FFs LUTs BRAMs resource size MHz [34] FPGA 512x512 500 130 XC3S200-4 1547 2638 12 [35] FPGA 515x512 310 100 XC72K325T 112166 80472 35 [36] FPGA 640x480 55 100 Zynq-7000 3187 4257 576 512x512 541 FPGA 640x480 460 142 (a) 1080p 68 Zynq-7000 12564 12935 10 CPU+FPGA 512x512 270 (ZC-702) (Linux OS) 640x480 245 142 1080p 36 Table 5.2: HW-Accelerated FAST using HAL-ASOS (a) compared to the literature. Finally, to integrate the Feature Detection stage in the application, the MNonmaxSA0 was refactored to handle network TCP sockets instead of the output binary files. Changes to extended features are minimal since both resources arise from Linux virtual file model. Required changes can be seen in the attached Listing C.54. The application was also refactored and changes can be seen in the attached Listing C.55. Performed tests demonstrated a consistent total execution time of 40 milliseconds using 142 MHz, a 232 Chapter 5. Experimental Results threshold parameter of 20 and an input block size of 32 kB. Experimental results can be seen in Figure 5.33. In similar conditions, the application using software Ed.Rosten-C was adapted to upload data using the network subsystem. Changes to the software application can be seen attached in Listing C.56 and Listing C.57. For the same conditions the software-only application achieved a total execution time of 140 milliseconds. Experimental results can be found in Figure 5.34. The software accelerated version is 3.5 times the duration of the hardware accelerated version. Qualitatively speaking, the difference between both is imperceptible. Both applications shown similar erroneous matches that are result of the same Brute-Force algorithm in use. A distinction can be made in terms of the number of successful matches which is higher when using the hardware accelerator. MFastSA0 MNonmaxNet0 hal_asos_resources # time ./feature_detector n table_i1080p.pgm 32768 20 192.168.1.71 [MNonmaxNet0<HwTask>]:finished...(9980) [MFastSA0<HwTask>]:finished...(64,2073600) real 0m 0.04s user 0m 0.02s sys 0m 0.02s # time ./feature_detector n table_i1080p.pgm 32768 20 192.168.1.71 [MFastSA0<HwTask>]:finished...(64,2073600) [MNonmaxNet0<HwTask>]:finished...(9980) real 0m 0.04s user 0m 0.01s sys 0m 0.03s # cat /hal-asos/MFastSA0/performance-counters/done_counter ------------------------------------------------------------ - Performance Counter: done_counter Results ------------------------------------------------------------ Control Register:0x0 Number of events: 02 Counter value: 04269257 Maxim event duration:04281926 [BusClks] Minimum event duration:04269257 [BusClks] Total events duration:0008551183 [BusClks] # Figure 5.33: Hardware accelerated object detection application results. Chapter 5. Experimental Results 233 # uname -a Linux buildroot 4.9.0-xilinx #9 SMP PREEMPT Wed Jul 22 16:08:43 WEST 2020 armv7l GNU/Linux # time ./feature_detector t table_i1080p.pgm 32768 20 192.168.1.71 [EdRosten-C Network]:finished!...(2073600, 9803) real 0m 0.14s user 0m 0.12s sys 0m 0.02s # time ./feature_detector t table_i1080p.pgm 32768 20 192.168.1.71 [EdRosten-C Network]:finished!...(2073600, 9803) real 0m 0.14s user 0m 0.11s sys 0m 0.03s # time ./feature_detector t table_i1080p.pgm 32768 20 192.168.1.71 [EdRosten-C Network]:finished!...(2073600, 9803) real 0m 0.14s user 0m 0.12s sys 0m 0.02s # Figure 5.34: Software accelerated object detection application results. Chapter 6 Conclusions and Future work This thesis proposes the HAL-ASOS framework and its accelerator model to ease the development of Linux based embedded systems using hardware acceleration in CPU+FPGA platforms. Throughout this document we have demonstrated how the HAL-ASOS framework is positioned as an integrated design solution that provides means to design systems that fit in the requirements of the target application. By use of its design methodology, the framework promotes the reuse of legacy software, where strategic pieces can be offloaded to FPGA computation. In a controlled way, the advance in the methodology stages, promotes design scalability guided by the achievement of the system performance metrics. The proposed accelerator model integrates the Linux OS and its programming models into a unified design that was usually and independently split between hardware and software layers. At the same time, this model benefits from the existing computational resources, placing the CPU of the target platform and the FPGA resource at the service of the application. In Chapter 2 we have applied the design methodology to a case study application that deals with file encryption using the 128-bit AES algorithm. It was possible to modify the application, guided by a performance achievement that was based on the CPU workloads, observed in its original software-only format. This chapter demonstrates the applicability as well as each of the development stages when using the HAL-ASOS framework. In Chapter 3 the main components in the accelerator model were discussed. We introduced some of the features implemented by the microprogram and the Kernel Core design that ultimately support the proposed programming model. The Extended Layer in the HW-Task concept and the HAL-ASOS programming model were also discussed. Using the HDL procedure packages and the corresponding hardware system calls, it was possible to extend the Linux programming models to the HW-Task design. The chapter ends 234 Chapter 6. Conclusions and Future work 235 describing the fundamental interfaces provided to the surrounding hardware. With a single format in data exchange proposed by the Generic Bus, the design becomes more flexible, partitioned into multiple clock domains that connected through a bidirectional handshake protocol. From the design discussed in this chapter resulted a journal publication entitled: HAL-ASOS accelerator model: evolutive elasticity by design . In chapter 4, singularities of the accelerator model that specialize the design in the different existing versions were discussed. The indispensable components that sustain the local storage and the synchronism in the proposed model were also evaluated. Other optional components, such as the performance counters and the ZeroCopy units were also discussed. The chapter concludes by distinguishing the specific versions of the accelerator model, implemented from a single description and using HDL configurations to instruct the synthesis and implementation phases of each design. In chapter 5, we put the different versions of the accelerator to a test, using a case study that falls within the scope of computer vision applications. In this chapter, we were able to summarize the different characteristics and application details that target each accelerator version. The design was explored to its limit in the application performance when targeting the Xilinx Zynq-7000 SoC in the ZC702 platform. Following a synchronous design topology for FPGA-based circuits, the application was implemented and tested on the target platform. The performance results were compared with algorithms that use softwarebased acceleration and can be found in the literature. Subsequently, the asynchronous programming paradigm supported by the HAL-ASOS accelerator model was applied. This design change improved performance results, dropping the execution times by 33% to 45% within the different accelerator versions used. On the other hand, it also proved the ability to mitigate the number of interrupt events launched by each accelerator, turning its behavior into a purely asynchronous entity. In turn, the final design was compared with designs that can be found in the literature under the similar test conditions. We considered that the performance gains were significant when compared to state-of-the-art implementations and due to its uniqueness in the application of asynchronous circuits, this chapter results in a publication that is under revision. When compared to other accelerator models in the literature, the HAL-ASOS model provides an easy and complete integration of the design in the Linux operating system, promoting the accelerator to a first-class computation entity, in which Linux is the target operating system of this model. No other accelerator allows 242 Appendix A. Resource Addressing Figure A.4: S00 Interface - Two-level address resource usage in Virtex 5 family. Appendix A. Resource Addressing 243 denoted as ’Z’. To apply this approach in the slave decoder, the design evolves to the simplified architecture that can be seen in Figure A.5. In that figure, the LUTs that implement the two level-address decode and the resulting select lines are visible using blue color. For simplicity only the pages 0 and 7 are represented, and we can see 16 words attached to each page decoder. These words are purely figurative and are intended to describe the association in parallel using arrays of tri-state buffers, ATR0 to ATR127, of 32 lines each. Word 0 Word 1 Word 15 Page 0 decoder word_select[0:15] 0 1 15 … … … RXDATA[31:0] LUT 5:32 LUT 4:16 ADDR[8:2] CS A5:A2 page_select[0:7] 07 L0 L1 ATR0 Slave Decoder A8:A6 [31:0] [31:0] [31:0] ATR7 Word 0 Word 1 Word 15 Page 7 decoder word_select[0:15] 0 1 15 … … LUT 5:32 L8 ATR120 [31:0] [31:0] [31:0] ATR127 A5:A2 [31:0] Figure A.5: Slave decoder internal architecture block diagram. Similar excerpt from the resource usage of this design can be seen in Figure A.6. It must be said that since the 128 words are not part of the design, the tri-state buffers were connected to top-level inputs of the slave decoder. In doing so, we expect to see an additional use of 4096 input buffers (IBUF) that will not be part of the final design. Figure A.6: S00 interface - Resource usage for tri-state datapath design in Zynq7000. An analysis of the report cell usage shows that this design does not qualifies for implementation using FPGA devices. The parallel word associations have been transformed into equivalent LUT-based circuits, and we can notice that only 32 tri-state buffers (OBUFT) are in use. This transformation resulted in a dispersion 244 Appendix A. Resource Addressing in the number of LUT inputs, with a predominance in LUT6 and LUT2. In summary, it can negatively impact the quality factor of the design, since the use of LUT1 to LUT4 are implemented by reusing LUT5 or LUT6 available in each slice. As a result, the use of resources reaches a total consumption of 3176 slices, which represents 5.97% of the available resources. A viable alternative is to apply multiplexing and take advantage of the MUX (F7 and F8) that can be found in each slice. Applying the same principle of the two-level addressing, the page-level can multiplex the 16 words into a 32-bit output. The decoder-level can multiplex the 8 inputs from each page, to give rise to the 32-bit RXDATA of the slave interface. To ease design mapping, each 32-bit word is connected using a parallel of 4 MUX with 16 inputs of 8 bits, and each page word is connected to a parallel of 4 MUX with 8 inputs of 8 bits. In Figure A.7 we can see the resource usage for this alternative. Figure A.7: S00 interface - Resource usage for MUX datapath design in Zynq ZC702. From the report cell usage, we can conclude that the design is using the desired logical elements. The use of LUTs is significantly lower and is influenced by the slice level organization. Here, each MUXF7 allows an 8:1 multiplexing function but it receives bits from LUT6 or LUT5 in its inputs. In turn, the outputs of these are connected to the MUXF8 inputs which together allow a 16:1 multiplexing function. The final result of the design translates into a total use of 2.17% of the available slices. To implement the first level of address decoding, the HAL-ASOS design uses the Slave decoder component, that follows the above design considerations. To promote design reuse, this component allows a parameterized number of pages and words per page. In Figure A.8 we can see a block diagram that describes its internal architecture. On the left side, the component implements the generic interface and is usually connected to top-level signals. On the right side, the component implements the page-level signals that may vary in number and Appendix A. Resource Addressing 245 Look-UP Table (LUT) 4:16 A8 A7 EN I2 I3 O0 O1 O7 WR_ACK_7 WR_ACK_1 WR_ACK_0 0 1 … 7 N_WORDS= 16 I1 A6 … … Rd_ACK_7 RD_ACK_1 RD_ACK_0 … page_select[0:7] page0_rxdata[31:0] ADDR[8:2] CS TXDATA[31:0] page1_rxdata[31:0] page7_rxdata[31:0] page_addr[5:2] WR_ACK RD_ACK page_wr_ack[0:7] page_rd_ack[0:7] SLAVE_DECODER N_PAGES= 8 WR_CE RD_CE page_wr_ce RXDATA[31:0] page_rd_ce page_txdata[31:0] … A8 76 L0 M0 AG0 AG1 Figure A.8: Slave decoder internal architecture block diagram. length, as a result of the chosen parameters. This degree of variability was implemented using advanced types of unconstrained number of elements, where we apply mathematical functions that are based on the received parameters, to establish the appropriate number of input and output signals in the design. For better organization, the component extends the remaining signals from the generic interface to the page-level using appropriate nomenclature. Since each data exchange demands two handshake signals, the decoder expects to receive two page-level acknowledge buses. These signals are combined internally using logic OR gates that give rise to the WR_ACK and RD_ACK signals. For completeness, the VHDL description of this component can be seen in Listing A.1 and in Listing A.2 we’ve included the VHDL description for its architecture. In the second level of the address decoding, the HAL-ASOS design implements the page decoder component. Here, we follow the same approach as in the previous level but using page-level inputs and word-level outputs. In Figure 3.47 we can see a diagram that describes its internal design. The main difference lies in the connection at the M0 control inputs being closed by the address bus, instead of being extended in sub-levels. As result of the single parameter, the implementation uses twice as many resources when comparing the 16 inputs with the first level of decoding. To address the local resources in the S00 interface, the design of the accelerator implements a hierarchy of one slave decoder to eight page decoder components. The resource consumption of the final version in the synthesis stage can be seen in Figure A.10. It is worth noting that, in order to assess this level of 246 Appendix A. Resource Addressing Look-UP Table (LUT) 5:32 word_select[0:15] rxword_0[31:0] page_address[5:2] page_select A5 A4 EN I2 I3 O0 O1 O15 page_txdata[31:0] rxword_1[31:0] rxword_15[31:0] page_wr_ack page_rd_ack wr_ack_bus[0:15] rd_ack_bus[0:15] WR_ACK_15 WR_ACK_1 WR_ACK_0 0 1 … 15 PAGE_DECODER N_WORDS= 16 page_wr_ce page_rd_ce word_wr_ce page_rxdata[31:0] word_rd_ce txword[31:0] I1 I0 A3 A2 … … Rd_ACK_15 RD_ACK_1 RD_ACK_0 … L0 M0 AG0 AG1 Figure A.9: Page decoder component - internal architecture. detail, the design of the interface decoder was isolated from the remaining accelerator circuits. With the insertion of OR logic in both components, the implementation slightly increases the consumption of LUT6 and LUT3. Figure A.10: S00 interface - Resource usage final design using ZC702 platform. The Slice Logic utilization shows a total consumption of 2.27% of available slices, and by this number, we can consider this two-level addressing is suitable for mapping in FPGAs. This value is an indicator of preliminary consumption that may vary in the final stages of implementation, being affected by the time constraints that the accelerator model faces. These can lead to the merging of combinational logic that aims to decrease the critical path, or to reuse partial resources in other slices closer in the design. Appendix A. Resource Addressing 247 Alternatives to this addressing model could include the use of FPGA memory blocks, programmed with a binary address map. This can be particularly advantageous in asymmetric memory layouts, where the decoder aims to accommodate the distinct address ranges of the target resources. Listing A.1: Page decoder component - entity declaration using VHDL. library IEEE; 20 use IEEE.STD_LOGIC_1164.ALL; 21 use IEEE.NUMERIC_STD.ALL; 22 library hal_asos_v4_00_a; 23 use hal_asos_v4_00_a.hal_asos_configs_pkg.C_MACHINE_WIDTH; 24 use hal_asos_v4_00_a.hal_asos_utils_pkg.t_array_slv_32; 25 use hal_asos_v4_00_a.hal_asos_utils_pkg.POW2; 26 use hal_asos_v4_00_a.MUX32; 27 28 entity SLAVE_DECODER is 29 GENERIC( N_PAGES: natural:=8; 30 N_WORDS: natural:=16); 31 Port ( CS : in STD_LOGIC; 32 WR_CE : in STD_LOGIC; 33 RD_CE : in STD_LOGIC; 34 ADDR : in STD_LOGIC_VECTOR ((POW2(N_PAGES)+ POW2(N_WORDS)+2-1 downto 2); 35 RXDATA : in STD_LOGIC_VECTOR (C_MACHINE_WIDTH-1 downto 0); 36 TXDATA : out STD_LOGIC_VECTOR (C_MACHINE_WIDTH-1 downto 0); 37 WR_ACK: out STD_LOGIC; 38 RD_ACK: out STD_LOGIC; 39 PAGE_SELECT : out STD_LOGIC_VECTOR (0 to N_PAGES-1); 40 PAGE_WR_CE : out STD_LOGIC; 41 PAGE_RD_CE : out STD_LOGIC; 42 PAGE_ADDR: out STD_LOGIC_VECTOR(POW2(N_WORDS)+2-1 DOWNTO 2); 43 PAGE_TXDATA : out STD_LOGIC_VECTOR (C_MACHINE_WIDTH-1 downto 0); 44 PAGE_RXDATA: in t_array_slv_32 (0 to N_PAGES-1); 45 PAGE_WR_ACK: in STD_LOGIC_VECTOR(0 to N_PAGES-1); 46 PAGE_RD_ACK: in STD_LOGIC_VECTOR(0 to N_PAGES-1); 47 end SLAVE_DECODER; 48 248 Appendix A. Resource Addressing Listing A.2: Slave decoder component - architecture description using VHDL. architecture Behavioral of SLAVE_DECODER is 49 CONSTANT ADDR_WIDTH: NATURAL:= POW2(N_PAGES) + POW2(N_WORDS)+2; 50 signal page_address : std_logic_vector (ADDR_WIDTH-1 downto POW2(N_WORDS)+2); 51 signal page_cs_i : std_logic_vector (0 to N_PAGES-1); 52 signal page_wr_ack_i: std_logic_vector (0 TO N_PAGES-1); 53 signal page_rd_ack_i: std_logic_vector (0 TO N_PAGES-1); 54 55 begin 56 PAGE_WR_CE <= WR_CE; 57 PAGE_RD_CE <= RD_CE; 58 PAGE_TXDATA <= RXDATA; 59 page_address <= ADDR(ADDR_WIDTH-1 downto POW2(N_WORDS)+2); 60 -------------------------------------------------------------------------------------------- 61 PG_CS:process(page_address,CS) 62 -------------------------------------------------------------------------------------------- 63 variable index: natural; 64 begin 65 index := to_integer(unsigned(page_address)); 66 page_cs_i<= (others=>'0'); 67 if (cs = '1') then 68 page_cs_i(index)<= '1'; 69 end if; 70 end process PG_CS; 71 -------------------------------------------------------------------------------------------- 72 PAGE_SELECT <= page_cs_i; 73 PAGE_ADDR <= addr(POW2(N_WORDS)+2-1 downto 2); 74 -------------------------------------------------------------- 75 MUX: entity MUX32 76 -------------------------------------------------------------- 77 GENERIC MAP(N_INPUTS=>N_PAGES) 78 Port MAP( ADDR=> page_address, 79 DIN=> PAGE_RXDATA, 80 DOUT=>TXDATA); 81 -------------------------------------------------------------- 82 RD_ACK <= page_rd_ack_i(0); 83 WR_ACK <= page_wr_ack_i(0); 84 ----------------------------------------------------------- 85 GEN_OR:FOR I IN 0 TO N_PAGES-2 GENERATE 86 ----------------------------------------------------------- 87 BEGIN 88 page_rd_ack_i(I) <= PAGE_RD_ACK(I) OR page_rd_ack_i(I+1); 89 page_wr_ack_i(I) <= PAGE_WR_ACK(I) OR page_wr_ack_i(I+1); 90 END GENERATE; 91 ----------------------------------------------------------- 92 page_rd_ack_i(N_PAGES-1) <= PAGE_RD_ACK(N_PAGES-1); 93 page_wr_ack_i(N_PAGES-1) <= PAGE_WR_ACK(N_PAGES-1); 94 ----------------------------------------------------------- 95 end Behavioral; 96 Appendix B Clock Synchronizers Fundamentally, all flip-flops with a clock signal have time constraints such as the setup time (tsu) and hold time (th), dictating that the input signal must remain stable in order to produce a stable output, after an expected time interval (tdq in the case of D flip-flop). Figure B.1 describes, in the form of a time diagram, a satisfactory input for this flip-flop. Here, the input signal at D, remains stable for the time constraints and thus produce a stable output at Q after the tdq interval. D Q clk clk T D Q 𝑡𝑠𝑢 𝑡ℎ 𝑡𝑑𝑞 Figure B.1: Flip-Flop D time constraints setup, hold and propagation delay The violation of time constraints produces failures in the signal capture, which can lead to: (1) the metastability of the flip-flop, or (2) the signal loss or data inconsistency when using vector signals. Figure B.2 describes in the form of a time diagram, an occurrence of meta-stability and two common examples of data loss or data inconsistency. In the temporal diagram on the left of the image, it is possible to observe that the input D violates the configuration constraint and this violation gave rise to an oscillating output. This condition is maintained for an undetermined time interval tosc, also known as metastable signal time (tmeta). If propagated to the other logical units of a design, this state of oscillation may trigger undetermined control states or excessive current consumption in the design. 249 250 Appendix B. Clock Synchronizers T D Q 𝑡𝑠𝑢 𝑡ℎ 𝑡𝑑𝑞 clk T𝑡𝑠𝑢 𝑡ℎ D Q clk Lost update Metastable 𝑡𝑑𝑞 𝑡𝑜𝑠𝑐 Figure B.2: Flip-Flop D time constraints violation On the right side we can observe two phenomena of lost update, or lost data, in which the two events at input D result in loss either due to the occurrence between the active transitions of the clock, or because it has violated the hold time. In the latter case, the result of output Q evolves to the previous value and when this failure occurs in vector-type signals, different bits may have different tmeta durations and unpredictably evolve to the input or to their previous values. Altogether, these failures can become intermittent, difficult to debug or reproduce, which often only occurs on the final hardware, being pointed out as the second biggest cause of product respin. The synchronizer variants found in the community can be distinguished in two types of functionality: (1) the conventional multi-flop synchronizer and (2) a toggle synchronizer variant. Figure B.3 describes the implementation of the conventional multi-flop synchronizer, where the transmitter and receiver are marked by the letters A and Y, and only the clock and reset signals from the receiver circuit are used. Synchronizer (Comb) reset DQ clk reset D Q clk clock_rcvr reset_rcvr FF1 FF0 Metastability region META_REGION = 1 i_Sig_sndr o_Sig_rcvr A Y Figure B.3: Multi-Flop D synchronizer circuit The input i_Sig_sndr receives the control signal sent from A to Y, and the output o_Sig_rcvr produces the signal captured by this component. The metastable state of the captured signal can occur at output Q of FF0, being contained by the input D of FF1 until the next active clock transition, time that it is allowed to stabilize. The probability of a meta-stable signal at the output of FF1 is very low or practically zero, but Appendix B. Clock Synchronizers 251 even so, for extreme high frequency scenarios, it is possible to scale the meta-stability region with more flip-flops using the META_REGION parameter. For signals with the duration of a transmitter’s clock pulse, we cannot use the conventional synchronizer for the reasons already mentioned in the lost data example. Instead, the pulse synchronizer (2) is applied since this circuit is not dependent on the duration of the event, but on the active transitions of the signal. Figure B.4 describes the implementation of this synchronizer where the clock and reset signals from both circuits are used. reset DQ clk reset D Q clk clock_rcvr reset_rcvr reset_sndr clock_sndr reset D Q clk FF1 FF2 Reset_A Clock_A Clock_Y reset DQ clk FF0 FF3 SynchronizerDual (pulse) Reset_y Metastability region i_Pulse_sndr o_Pulse_rcvr Y A META_REGION = 1 Figure B.4: Multi-Flop D pulse synchronizer circuit The active transition of the pulse in the input sets the value of output Q in FF0 to its complementary value (toggle). This signal keeps the logic value stable until the next active transition of the input. Two Y clock cycles allow to deal with metastability using the conventional multi-flop scheme, which reproduces the stable value at the output of FF2. Then, a logical combination between this output and FF3 produces a high logic value at the output during a Y clock pulse. It should be noted that this synchronization can only be applied to clock pulse signals, and in situations where the meta-region signals evolved to its previous value, this pulse can suffer an additional clock cycle Y delay. For signals active for more than one clock cycle, the design of the accelerator employs a decomposition in set and clear pulses, which occur in the upward and downward transitions of the original signal. 258 Appendix C. Source Listings Listing C.6: Encryptor SA - control path (1/2):(back to Figure 2.25). ---------------------------------------------------------------------------------------- 94 FSM_CONTROL:process(task_state,s00_kernel_run,status_ret_q,file_len_d,buff_len_q, 95 count_blocks_q, index_q, reset_i, kernel_response, ciphered_data_i, file_len_q, ifile_q, 96 done_i, tsocket_q, target_read, p_current_q,p_result_q,kernel_call) 97 ---------------------------------------------------------------------------------------- 98 begin 99 task_state_next <= task_state; 100 inc_index <= '0'; 101 inc_count_blocks <='0'; 102 clr_index <= '0'; 103 trigger_aes_i <= '0'; 104 status_ret_d <= status_ret_q; 105 p_current_d <= p_current_q; 106 p_result_d <= p_result_q; 107 ifile_d <= ifile_q; 108 tsocket_d <= tsocket_q; 109 file_len_d <= file_len_q; 110 buff_len_d <= buff_len_q; 111 task_done_i <= '0'; 112 113 if reset_i = '1' then 114 reset_sys_call(kernel_call); 115 else 116 hal_asos_link_to_kernel(kernel_response,kernel_call); 117 case task_state is 118 when s0_ready=> 119 if s00_kernel_run = '1' then 120 task_state_next <= s1_query_file; 121 end if; 122 when s1_query_file=> 123 pooled_fstream_query(kernel_call,kernel_response,ifile_q, ifile_d); 124 task_state_next <= s2_query_socket; 125 when s2_query_socket=> 126 pooled_socket_query(kernel_call,kernel_response,tsocket_q,tsocket_d); 127 task_state_next<= s3_open_file; 128 when s3_open_file=> 129 pooled_fstream_open(kernel_call,kernel_response,ifile_q,ifile_d); 130 status_ret_d <= cast_return_to_transaction_ret(kernel_response); 131 task_state_next <= s4_evaluate_file; 132 if(status_ret_q < 0)then 133 task_state_next <= s17_write_string_lram; 134 end if; 135 when s4_evaluate_file=> 136 pooled_fstream_read_len(kernel_call,kernel_response,ifile_q,file_len_d); 137 p_current_d(0) <= std_logic_vector(to_unsigned(file_len_q,32)); 138 task_state_next <= s16_close_file; 139 if(file_len_d >0) then 140 task_state_next <= s5_set_word_len; 141 end if; 142 when s5_set_word_len=> 143 safe_write_lram_word32(kernel_call, kernel_response, p_current_q,1,0); 144 inc_index <= '1'; 145 task_state_next<= s6_open_socket; 146 when s6_open_socket=> 147 pooled_socket_open(kernel_call,kernel_response,tsocket_q,tsocket_d); 148 status_ret_d <= cast_return_to_transaction_ret(kernel_response); 149 task_state_next <= s7_read_file; 150 if(status_ret_q < 0)then 151 task_state_next <= s15_close_socket; 152 end if 153 94 Appendix C. Source Listings 259 when s7_read_file=> 154 pooled_fstream_read_word32(kernel_call,kernel_response, ifile_q,target_read,index_q); 155 buff_len_d <= cast_return_to_transfer_len(kernel_response); 156 clr_index <= '1'; 157 task_state_next <= s8_evaluate_read; 158 when s8_evaluate_read=> 159 task_state_next <= s15_close_socket; 160 if(buff_len_q > 0) then 161 task_state_next <= s9_load_plain; 162 end if; 163 when s9_load_plain=> 164 safe_read_lram_word32(kernel_call, kernel_response, p_current_d,4,index_q); 165 task_state_next <= s10_trigger_encrypt; 166 when s10_trigger_encrypt=> 167 trigger_aes_i <='1'; 168 task_state_next <= s11_wait_done; 169 when s11_wait_done=> 170 wait_signal_event(kernel_call, kernel_response,done_i,event_done_d); 171 p_result_d <= slv_to_array_32(ciphered_data_i); 172 task_state_next <= s12_update_lram; 173 when s12_update_lram=> 174 inc_count_blocks<= '1'; 175 inc_index <= '1'; 176 safe_write_lram_word32(kernel_call, kernel_response, p_result_q,4,index_q); 177 task_state_next <= s13_update_index; 178 when s13_update_index=> 179 task_state_next<=s14_write_socket; 180 if(index_q < buff_len_q) then 181 task_state_next <= s9_load_plain; 182 end if; 183 when s14_write_socket=> 184 clr_index<= '1'; 185 pooled_socket_write_word32(kernel_call, kernel_response, tsocket_q,index_q,0); 186 task_state_next <= s7_read_file; 187 when s15_close_socket=> 188 pooled_socket_close(kernel_call, kernel_response, tsocket_q,tsocket_d); 189 task_state_next <= s16_close_file; 190 when s16_close_file=> 191 pooled_fstream_close(kernel_call, kernel_response, ifile_q,ifile_d); 192 task_state_next<= s17_write_string_lram; 193 when s17_write_string_lram=> 194 safe_write_lram(kernel_call,kernel_response,fmessage, 195 std_logic_vector(to_unsigned(count_blocks_q,32)),128); task_state_next <= s90_print_stdio; 196 when s90_print_stdio=> 197 write_stdio(kernel_call, kernel_response,fmessage'high,m_len,128); 198 task_state_next <= s99_exit; 199 when s99_exit=> 200 task_done_i <= '1'; 201 task_exit(kernel_call, kernel_response); 202 task_state_next <=s99_exit; 203 when others=> null; 204 end case; 205 end if; 206 end process FSM_CONTROL; 207 ---------------------------------------------------------------------------------------- 208 Listing C.7: Encryptor SA - control path (2/2):(back to Figure 2.25). 260 Appendix C. Source Listings Listing C.8: Encryptor SA - synchronous control path:(Figure 2.25). target_read <= INIT_WBLOCK_LEN when initial_it = '1' else WBLOCK_LEN; 209 increment_val <= 1 when initial_index else 4; 210 -------------------------------------------------------------------------- 211 process(index_q,increment_val) 212 -------------------------------------------------------------------------- 213 begin 214 next_index <= index_q + increment_val; 215 end process; 216 -------------------------------------------------------------------------- 217 FSM_SYNC:process(clock) 218 -------------------------------------------------------------------------- 219 begin 220 if rising_edge(clock) then 221 222 if reset_i = '1' then 223 p_current_q <= (others=>(others=>'0')); 224 p_result_q <= (others=>(others=>'0')); 225 file_len_q <= 0; 226 event_done_q <= false; 227 228 buff_len_q <= 0; 229 status_ret_q <=0; 230 ifile_q <=(fstream_obj,(others=>'0'),0,false); 231 tsocket_q <=(net_obj,(others=>'0'),1,false); 232 task_state <= s0_ready; 233 234 else 235 if kernel_response.sleep_task = '0' then 236 p_current_q <= p_current_d; 237 p_result_q <= p_result_d; 238 file_len_q <= file_len_d; 239 event_done_q <= event_done_d; 240 end if; 241 242 if kernel_response.block_task = '0' then 243 task_state <= s0_ready; 244 buff_len_q <= buff_len_d; 245 status_ret_q <=status_ret_d; 246 ifile_q <= ifile_d; 247 tsocket_q <= tsocket_d; 248 end if; 249 end if; 250 end if; 251 end process FSM_SYNC; 252 -------------------------------------------------------------------------- 253 Appendix C. Source Listings 261 Listing C.9: Encryptor SA - synchronous datapath:(Figure 2.25). -------------------------------------------------------------------------- 254 plain_data_i <= array_32_to_slv(p_current_q); 255 -------------------------------------------------------------------------- 256 ip_aes: entity aes128 257 -------------------------------------------------------------------------- 258 port map (clock => clock, 259 reset => reset_i, 260 i_run => trigger_aes_i, 261 i_sleep => kernel_response.sleep_task, 262 i_key_expand => initial_it, 263 o_done => done_i, 264 i_plain_data => plain_data_i, 265 i_cipher_key => ciper_key_i, 266 o_ciphered_data => ciphered_data_i); 267 ------------------------------------------------------------------------ 268 p_result_d <= slv_to_array_32(ciphered_data_i); 269 ------------------------------------------------------------------------ 270 TASK_DPATH: process(clock) 271 ------------------------------------------------------------------------ 272 begin 273 if rising_edge(clock) then 274 if reset_i = '1' then 275 initial_it <= '1'; 276 initial_index <= true; 277 count_blocks_q <= 0; 278 else 279 if clr_index = '1' and kernel_response.block_task= '0' then 280 initial_index <= false; 281 end if; 282 283 if done_i = '0' and kernel_response.sleep_task = '0' then 284 initial_it <= '0'; 285 end if; 286 287 if inc_count_blocks = '1' and kernel_response.block_task = '0' then 288 count_blocks_q <= count_blocks_q + 1; 289 end if; 290 291 end if; 292 end if; 293 end process TASK_DPATH; 294 -------------------------------------------------------------------------- 295 counter_index: process(clock) 296 -------------------------------------------------------------------------- 297 begin 298 if rising_edge(clock) then 299 if (clr_index = '1' and kernel_response.block_task = '0') or reset_i = '1' then 300 index_q <= 0; 301 elsif inc_index = '1' and kernel_response.block_task = '0' then 302 index_q <= next_index; 303 end if; 304 end if; 305 end process counter_index; 306 -------------------------------------------------------------------------- 307 end encrypter_sa_level; 308 262 Appendix C. Source Listings Listing C.10: Co-Simulation Encryptor - SystemVerilog test-bench file:(sec. 2.7.5). `timescale 1ns / 1ps 1 2 module tb_design(); 3 4 logic interrupt_pin_0; 5 logic o_heart_bit_0; 6 logic s00_axi_aclk_0=0; 7 logic s00_axi_aresetn_0=0; 8 9 always #5ns s00_axi_aclk_0=~s00_axi_aclk_0; 10 11 design_1_wrapper DUT( 12 .s00_axi_aclk_0(s00_axi_aclk_0), 13 .s00_axi_aresetn_0(s00_axi_aresetn_0), 14 .o_heart_bit_0(o_heart_bit_0), 15 .interrupt_pin_0(interrupt_pin_0)); 16 17 //-------------------------------------------------------------- 18 initial 19 //-------------------------------------------------------------- 20 begin 21 s00_axi_aresetn_0=0; 22 #100ns; 23 s00_axi_aresetn_0=1; 24 #200ns; 25 DUT.design_1_i.hal_asos_accelerator_0.u0.ubus.start_proxy(); 26 #100ns; 27 end 28 //------------------- 29 endmodule 30 Appendix C. Source Listings 263 Listing C.11: Full Simulation - SystemVerilog testbench for QEMU. `timescale 1ns / 1ps 1 2 import hal_asos_sv_pkg::*; 3 module tb_qemu( ); 4 5 const int C_BASE_ADDRESS = 32'h043C00000; 6 AcceleratorInfo acc0 = { "HwEncrypter0" ,C_BASE_ADDRESS,32'h20000,0}; 7 AcceleratorInfo acc1 = { "HwEncrypterSA0" ,C_BASE_ADDRESS + 32'h20000,32'h20000,1}; 8 simulation_status_t status= DEAD_SIM; 9 logic clock = 0; 10 logic resetn = 0; 11 12 always #5ns clock=~clock; 13 14 //------------------------------------------------ 15 task timestamp(output int x); 16 //------------------------------------------------ 17 x = $time; 18 endtask; 19 20 //------------------------------------------------ 21 task delay(input int x); 22 //------------------------------------------------ 23 int count = x; 24 while(count > 0)begin 25 #10 count--; 26 end 27 endtask; 28 //----------------------------------------------- 29 export "DPI-C" task delay; 30 export "DPI-C" task timestamp; 31 32 design_2_wrapper DUT( 33 .m00_axi_aclk_0(clock), 34 .m00_axi_aresetn_0(resetn)); 35 //-------------------------------------------------------------- 36 initial 37 //-------------------------------------------------------------- 38 begin 39 resetn=0; 40 #200ns; 41 resetn=1; 42 #50ns 43 DUT.design_2_i.hal_asos_link_cv_0.inst.u0.register_accelerator(acc0); 44 #10ns 45 DUT.design_2_i.hal_asos_link_cv_0.inst.u0.register_accelerator(acc1); 46 #10ns 47 DUT.design_2_i.hal_asos_link_cv_0.inst.u0.start_simulation(status); 48 49 // #20ns; 50 //DUT.design_1_i.Host_0.inst.u0.read_bus_w32(C_BASE_ADDRESS + 51 MQUEUE_IN_SPACE_REG_OFFSET,data); 52 ; 53 54 end 55 endmodule 56 264 Appendix C. Source Listings Listing C.12: Machine 1 Application - receive parameters from command line. #include <iostream> 1 #include "aes_128_client_code/client_machine.h" 2 3 extern std::string target_file; 4 int main(int argc, char** argv){ 5 6 char select = -1; 7 if (argc > 2) { 8 select = *argv[1]; 9 target_file = std::string(argv[2]); 10 } 11 12 switch (select) { 13 case '0': 14 hal_asos_demo::test_aes128_file_sw_threads(); 15 break; 16 case '1': 17 hal_asos_demo::test_aes128_file_hw_thread_cypher_3(); 18 break; 19 case '2': 20 hal_asos_demo::test_aes128_file_hw_thread_cypher_sa(); 21 break; 22 case '3': 23 hal_asos_demo::test_aes128_file_hw_thread_cypher_3_user_io(); 24 break; 25 case '4': 26 hal_asos_demo::test_aes128_file_hw_thread_cypher_sa_uio(); 27 break; 28 default: 29 break; 30 } 31 return 0; 32 } 33 Listing C.13: Machine 1Application - HW Encryptor software refactoring. void hal_asos_demo::test_aes128_file_hw_thread_cypher_3(void) { 226 using namespace hal_asos; 227 228 Task<SwTask, TFRead> T0; 229 Task<HwTask, THwEncrypter, semantic<dds::Restricted>> T1; 230 Task<SwTask, TUpload> T2; 231 232 T0.start(); 233 T1.start(); 234 T2.start(); 235 236 T0.join(); 237 T1.join(); 238 T2.join(); 239 }240 Appendix C. Source Listings 265 Listing C.14: Machine 1Application - HW Encryptor SA software refactoring. 336 void hal_asos_demo::test_aes128_file_hw_thread_cypher_sa(void) { 336 using namespace hal_asos; 337 338 Task<HwTask, THwEncrypterSA> T1; 339 hal_asos::networking::CSocket<hal_asos::networking::Client> Soc; 340 341 CFstream<std::ifstream> Input_file(target_file.c_str()); 342 Input_file.set_flags(std::ios::in | std::ifstream::binary); 343 344 Input_file.open_file(); 345 Input_file.get_file_len(); 346 347 348 Soc.set_ip_address(ip); 349 Soc.set_sock_family(AF_INET); 350 Soc.set_sock_type(SOCK_STREAM); 351 Soc.set_sock_port(PORT_NO); 352 353 T1.submit_to_pool(Input_file); 354 T1.submit_to_pool(Soc); 355 356 T1.start(); 357 T1.join(); 358 } 359 266 Appendix C. Source Listings Listing C.15: Kernel Package - LBUS register and LRAM write procedures. library IEEE; 2 use IEEE.STD_LOGIC_1164.ALL; 3 use IEEE.NUMERIC_STD.ALL; 4 library hal_asos_v4_00_a; 5 use hal_asos_v4_00_a.hal_asos_configs_pkg.all; 6 7 8 package hal_kernel_pkg is9 ... ------------------------------------------------------------------------------------------ 1356 procedure lbus_write_reg (signal i_call : out kernel_input_t; 1357 signal o_response: in kernel_output_t; 1358 reg_offset: in natural range 0 to (2**CLBUS_REG_WIDTH)-1; 1359 data: in std_logic_vector(31 downto 0)) is 1360 ------------------------------------------------------------------------------------------ 1361 begin 1362 i_call.sys_call_id <= SYS_CALL_WRITE_LBUS; 1363 i_call.this_call <= '1'; 1364 i_call.parameters(PARAM_LBUS_WORD'RANGE)<=data; 1365 i_call.parameters(PARAM_LBUS_BE'RANGE) <= "1111"; 1366 i_call.parameters(PARAM_LBUS_ADDR'RANGE)1367 <=std_logic_vector(to_unsigned(reg_offset,CLBUS_AWWIDTH)); end procedure lbus_write_reg; 1368 ------------------------------------------------------------------------------------------ 1369 ... ------------------------------------------------------------------------------------------ 1389 procedure lram_write_word (signal i_call : out kernel_input_t; 1390 signal o_response: in kernel_output_t; 1391 lram_address: in natural range 0 to (2**CLRAM_AWWIDTH)-1; 1392 data: in std_logic_vector(31 downto 0))is 1393 ------------------------------------------------------------------------------------------ 1394 begin 1395 i_call.sys_call_id <= SYS_CALL_WRITE_LBUS; 1396 i_call.this_call <= '1'; 1397 i_call.parameters(PARAM_LBUS_BURTS_LEN'RANGE)1398 <=std_logic_vector(to_unsigned(1, PARAM_LBUS_BURTS_LEN'length)); i_call.parameters(PARAM_LBUS_WORD'RANGE)<=data; 1399 i_call.parameters(PARAM_LBUS_BE'RANGE) <= "1111"; 1400 i_call.parameters(PARAM_LBUS_ADDR'RANGE) 1401 <= '1'& std_logic_vector(to_unsigned(lram_address,CLRAM_AWWIDTH)); 1402 end procedure lram_write_word; 1403 ------------------------------------------------------------------------------------------ 1404 => back to Figure 4.2 Appendix C. Source Listings 267 Listing C.16: Microprogram - VHDL description for the test input MUX. -------------------------------------------------------------------------------------------- 92 --INPUT_MUX_SEL 93 -------------------------------------------------------------------------------------------- 94 CONSTANT LEV_EVM_READY_SEL :natural:=0;--00000 95 CONSTANT LEV_EVM_SIGNAL_SEL :natural:=1;--00001 96 CONSTANT LFIFO_DATA_READY_SEL :natural:=2;--00010 97 CONSTANT LFIFO_DATA_VALID_SEL :natural:=3;--00011 98 CONSTANT LFIFO_READY_FOR_DATA_SEL :natural:=4;--00100 99 CONSTANT LFIFO_ACK_DATA_SEL :natural:=5;--00101 100 CONSTANT MQ_LINK_DATA_READY_SEL :natural:=6;--00110 101 CONSTANT MQ_LINK_DATA_VALID_SEL :natural:=7;--00111 102 CONSTANT MQ_LINK_READY_FOR_DATA_SEL:natural:=8;--01000 103 CONSTANT MQ_LINK_ACK_DATA_SEL :natural:=9;--01001 104 CONSTANT MUTEX_STATUS_B_LOCKED_SEL :natural:=10;--01010 105 CONSTANT MUTEX_STATUS_B_LOCKED_NOT_SEL:natural:=11;--01011 106 CONSTANT MUTEX_STATUS_A_LOCKED_NOT_SEL:natural:=12;--01100 107 CONSTANT LBUS_WR_ACK_SEL :natural:=13;--01101 108 CONSTANT LBUS_RD_ACK_SEL :natural:=14;--01110 109 CONSTANT MBUS2_KERNEL_CMD_ACK_SEL :natural:=15;--01111 110 CONSTANT MBUS2_KERNEL_CMD_CMPLT_SEL :natural:=16;--10000 111 CONSTANT SYSRAM_ADDRESS_OK_SEL :natural:=17;--10001 112 CONSTANT BURST_MODE_ACTIVE_SEL :natural:=18;--10010 113 CONSTANT BURST_DONE_SEL :natural:=19;--10011 114 CONSTANT MBUS2_KERNEL_CMD_BURST_COMPLT:natural:=20;--10100 115 CONSTANT MBUS2_KERNEL_CMD_BURST_DONE :natural:=21;--10101 116 CONSTANT MBUS2_KERNEL_CMD_BURST_READY:natural:=22;--10110 117 -- 118 CONSTANT FALSE_SEL :natural:=2**(input_sel_t'LENGTH)-2;--(32-2)--11110 119 CONSTANT TRUE_SEL :natural:=2**(input_sel_t'LENGTH)-1;--(32-1)--11111 120 ----------------------------------------------------------------------------- 121 ---------------------------------------------------- 298 INPUT_MUX: process( input_sel, i_time_event_ready,i_time_event_signal, 299 ... i_mbus2_kernel_burst_done, i_mbus2_kernel_burst_mode) 322 ---------------------------------------------------- 323 begin 324 inc_load_not <= '0'; 325 case to_integer(unsigned(input_sel)) is 326 when LEV_EVM_READY_SEL =>inc_load_not <= i_time_event_ready; 327 when LEV_EVM_SIGNAL_SEL =>inc_load_not <= i_time_event_signal; 328 when LFIFO_DATA_READY_SEL =>inc_load_not <=i_lfifo_data_ready; 329 when LFIFO_DATA_VALID_SEL =>inc_load_not <=i_lfifo_data_valid; 330 when LFIFO_READY_FOR_DATA_SEL =>inc_load_not <=i_lfifo_ready_for_data; 331 when LFIFO_ACK_DATA_SEL =>inc_load_not <=i_lfifo_ack_data; 332 when MQ_LINK_DATA_READY_SEL =>inc_load_not <=i_msg_queue_data_ready; 333 when MQ_LINK_DATA_VALID_SEL =>inc_load_not <=i_msg_queue_data_valid; 334 when MQ_LINK_READY_FOR_DATA_SEL=>inc_load_not<=i_msg_queue_ready_for_data; 335 when MQ_LINK_ACK_DATA_SEL =>inc_load_not <=i_msg_queue_ack_data; 336 when MUTEX_STATUS_B_LOCKED_SEL =>inc_load_not <=mutex_chb_locked; 337 when MUTEX_STATUS_B_LOCKED_NOT_SEL=>inc_load_not <= mutex_chb_locked_not; 338 when MUTEX_STATUS_A_LOCKED_NOT_SEL=>inc_load_not <= mutex_cha_locked_not; 339 when LBUS_WR_ACK_SEL =>inc_load_not <=i_lbus_wr_ack; 340 when LBUS_RD_ACK_SEL =>inc_load_not <=i_lbus_rd_ack; 341 when MBUS2_KERNEL_CMD_ACK_SEL =>inc_load_not <=i_mbus2_kernel_cmd_ack; 342 when MBUS2_KERNEL_CMD_CMPLT_SEL =>inc_load_not <=i_mbus2_kernel_cmd_cmplt; 343 when SYSRAM_ADDRESS_OK_SEL =>inc_load_not <=i_sysram_buffer_address_ok 344 when BURST_MODE_ACTIVE_SEL => inc_load_not<=i_burst_mode; 345 when MBUS2_KERNEL_CMD_BURST_COMPLT => inc_load_not <=i_mbus2_kernel_burst_complt; 346 when MBUS2_KERNEL_CMD_BURST_DONE => inc_load_not <=i_mbus2_kernel_burst_done; 347 when MBUS2_KERNEL_CMD_BURST_READY => 348 inc_load_not <= i_mbus2_kernel_burst_mode AND i_sysram_buffer_address_ok; -- 349 when BURST_DONE_SEL =>INC_LOAD_NOT <= i_burst_done; 350 when FALSE_SEL =>inc_load_not <='0'; 351 when TRUE_SEL =>inc_load_not <='1'; 352 when others => null; 353 end case; 354 end process INPUT_MUX; 355 ---------------------------------------------------- 356 274 Appendix C. Source Listings Listing C.23: Kernel Package - VHDL procedures declaration (part 3/3). ... procedure byte_to_lbus_word( signal data: in std_logic_vector(7 downto 0); 755 signal be: in std_logic_vector(3 downto 0); 756 signal lbus_data: out std_logic_vector(31 downto 0)); 757 758 procedure byte_from_lbus_word( signal lbus_data: in std_logic_vector(31 downto 0); 759 signal be: in std_logic_vector(3 downto 0); 760 signal data: out std_logic_vector(7 downto 0)); 761 762 procedure sysram_get_virt_address ( signal i_call : out kernel_input_t; 763 signal o_response: in kernel_output_t; 764 signal sysram_address: out unsigned(31 downto 0)); 765 766 procedure mst_bus_read_word (signal i_call : out kernel_input_t; 767 signal o_response: in kernel_output_t; 768 bus_address: in std_logic_vector(31 downto 0); 769 data: out std_logic_vector(31 downto 0)); 770 771 procedure mst_bus_write_word (signal i_call : out kernel_input_t; 772 signal o_response: in kernel_output_t; 773 bus_address: in std_logic_vector(31 downto 0); 774 data: in std_logic_vector(31 downto 0)); 775 776 procedure mst_bus_read_word_burst (signal i_call : out kernel_input_t; 777 signal o_response: in kernel_output_t; 778 burst_len:in natural; --len-1 779 bus_address: in std_logic_vector(31 downto 0); 780 data: out std_logic_vector(31 downto 0)); 781 782 procedure mst_bus_write_word_burst ( signal i_call : out kernel_input_t; 783 signal o_response: in kernel_output_t; 784 burst_len:in natural; --len-1 785 bus_address: in std_logic_vector(31 downto 0); 786 data: in std_logic_vector(31 downto 0)); 787 788 procedure task_yield( signal i_call : out kernel_input_t; 789 signal o_response: in kernel_output_t); 790 791 procedure sys_call_return( signal kernel_response: in kernel_output_t; 792 signal ret: out boolean); 793 ... 794 Appendix C. Source Listings 275 Listing C.24: User Package - VHDL procedures declaration (part 1/6). package hal_asos_user_pkg is 11 -------------------------------------------------------------- 12 procedure reset_pooled_object(signal umutex: out pooled_mutex_t ); 13 14 procedure reset_pooled_object(signal usem: out pooled_semaphore_t ); 15 16 procedure reset_pooled_object(signal ucond: out pooled_condition_t ); 17 18 procedure reset_pooled_object(signal ubuff: out pooled_array_t); 19 20 procedure reset_pooled_object(signal udev: out pooled_device_t ); 21 22 procedure reset_pooled_object(signal ufile: out pooled_file_t ); 23 24 procedure reset_pooled_object(signal uobj: out pooled_object_t ); 25 -------------------------------------------------------------- 26 procedure pooled_mutex_query( signal i_call : out kernel_input_t; 27 signal o_response: in kernel_output_t; 28 signal umutex_q: in pooled_mutex_t; 29 signal umutex_d: out pooled_mutex_t); 30 -------------------------------------------------------------- 31 procedure pooled_semaphore_query(signal i_call : out kernel_input_t; 32 signal o_response : in kernel_output_t; 33 signal usem_q: in pooled_semaphore_t; 34 signal usem_d: out pooled_semaphore_t); 35 -------------------------------------------------------------- 36 procedure pooled_condition_query(signal i_call : out kernel_input_t; 37 signal o_response : in kernel_output_t; 38 signal ucond_q: in pooled_condition_t; 39 signal ucond_d: out pooled_condition_t); 40 -------------------------------------------------------------- 41 procedure pooled_buffer_query(signal i_call : out kernel_input_t; 42 signal o_response : in kernel_output_t; 43 signal pbuff_q: in pooled_array_t; 44 signal pbuff_d: out pooled_array_t); 45 -------------------------------------------------------------- 46 procedure pooled_file_query(signal i_call : out kernel_input_t; 47 signal o_response : in kernel_output_t; 48 signal ufile_q: in pooled_file_t; 49 signal ufile_d: out pooled_file_t); 50 -------------------------------------------------------------- 51 procedure pooled_device_query(signal i_call : out kernel_input_t; 52 signal o_response : in kernel_output_t; 53 signal udev_d: in pooled_device_t; 54 signal udev_q: out pooled_device_t); 55 -------------------------------------------------------------- 56 procedure pooled_mutex_lock(signal i_call : out kernel_input_t; 57 signal o_response: in kernel_output_t; 58 signal umutex_d: in pooled_mutex_t; 59 signal umutex_q: out pooled_mutex_t); 60 -------------------------------------------------------------- 61 procedure pooled_fstream_query(signal i_call : out kernel_input_t; 62 signal o_response : in kernel_output_t; 63 signal ustream_q: in pooled_fstream_t; 64 signal ustream_d: out pooled_fstream_t); 65 -------------------------------------------------------------- 66 procedure pooled_socket_query( signal i_call : out kernel_input_t; 67 signal o_response : in kernel_output_t; 68 signal usock_q: in pooled_socket_t; 69 signal usock_d: out pooled_socket_t); 70 -------------------------------------------------------------- 71 procedure pooled_mutex_unlock( signal i_call : out kernel_input_t; 72 signal o_response: in kernel_output_t; 73 signal umutex_d: in pooled_mutex_t; 74 signal umutex_q: out pooled_mutex_t) 75 276 Appendix C. Source Listings Listing C.25: User Package - VHDL procedures declaration (part 2/6). -------------------------------------------------------------- 76 procedure pooled_semaphore_wait(signal i_call : out kernel_input_t; 77 signal o_response: in kernel_output_t; 78 signal usem_d: in pooled_semaphore_t; 79 signal usem_q: out pooled_semaphore_t); 80 -------------------------------------------------------------- 81 procedure pooled_semaphore_post(signal i_call : out kernel_input_t; 82 signal o_response: in kernel_output_t; 83 signal usem_q: in pooled_semaphore_t; 84 signal usem_d: out pooled_semaphore_t); 85 -------------------------------------------------------------- 86 procedure pooled_condition_signal(signal i_call : out kernel_input_t; 87 signal o_response: in kernel_output_t; 88 signal ucond_q: in pooled_condition_t; 89 signal ucond_d: out pooled_condition_t); 90 -------------------------------------------------------------- 91 procedure pooled_condition_wait(signal i_call : out kernel_input_t; 92 signal o_response: in kernel_output_t; 93 signal ucond_q: in pooled_condition_t; 94 signal ucond_d: out pooled_condition_t); 95 -------------------------------------------------------------- 96 procedure transfer_control_to_dds ( signal i_call : out kernel_input_t; 97 signal o_response: in kernel_output_t; 98 constant len: in natural); 99 -------------------------------------------------------------- 100 procedure transfer_control_from_dds(signal i_call : out kernel_input_t; 101 signal o_response: in kernel_output_t; 102 constant len: in natural ); 103 -------------------------------------------------------------- 104 procedure transfer_data_to_dds( signal i_call : out kernel_input_t; 105 signal o_response: in kernel_output_t; 106 constant lram_address:in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1); 107 constant len: in natural); 108 -------------------------------------------------------------- 109 procedure transfer_data_from_dds(signal i_call : out kernel_input_t; 110 signal o_response: in kernel_output_t; 111 constant lram_address:in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1); 112 constant len: in natural ); 113 -------------------------------------------------------------- 114 procedure transfer_to_host_swfifo( signal i_call : out kernel_input_t; 115 signal o_response: in kernel_output_t; 116 constant len: in natural); 117 -------------------------------------------------------------- 118 procedure transfer_from_host_swfifo(signal i_call : out kernel_input_t; 119 signal o_response: in kernel_output_t; 120 constant len: in natural); 121 -------------------------------------------------------------- 122 procedure safe_write_lram_word32 ( signal i_call : out kernel_input_t; 123 signal o_response: in kernel_output_t; 124 signal pbuff: in t_array_slv_32; 125 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 126 constant lram_address: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 127 -------------------------------------------------------------- 128 procedure safe_read_lram_word32 ( signal i_call : out kernel_input_t; 129 signal o_response: in kernel_output_t; 130 signal pbuff: out t_array_slv_32; 131 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 132 constant lram_address: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 133 -------------------------------------------------------------- 134 procedure safe_write_lram_word32_burst (signal i_call : out kernel_input_t; 135 signal o_response: in kernel_output_t; 136 signal pbuff: in t_array_slv_32; 137 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 138 constant lram_address: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 139 Appendix C. Source Listings 277 Listing C.26: User Package - VHDL procedures declaration (part 3/6). -------------------------------------------------------------- 140 procedure safe_read_lram_word32_burst ( signal i_call : out kernel_input_t; 141 signal o_response: in kernel_output_t; 142 signal pbuff: out t_array_slv_32; 143 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 144 constant lram_address: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 145 -------------------------------------------------------------- 146 procedure unsafe_read_lram_word32_burst (signal i_call : out kernel_input_t; 147 signal o_response: in kernel_output_t; 148 signal pbuff: out t_array_slv_32; 149 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 150 constant lram_address: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 151 -------------------------------------------------------------- 152 procedure safe_write_sysram_word32 (signal i_call : out kernel_input_t; 153 signal o_response: in kernel_output_t; 154 signal pbuff: in t_array_slv_32; 155 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 156 constant lram_address: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 157 -------------------------------------------------------------- 158 procedure safe_read_sysram_word32 (signal i_call : out kernel_input_t; 159 signal o_response: in kernel_output_t; 160 signal pbuff: out t_array_slv_32; 161 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 162 constant lram_address: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 163 -------------------------------------------------------------- 164 procedure safe_write_lram ( signal i_call : out kernel_input_t; 165 signal o_response: in kernel_output_t; 166 signal pbuff: in t_array_slv_8; 167 constant len: in natural range 1 to 2**(CLRAM_AWWIDTH+2)-1; 168 constant lram_address: in natural range 0 to 2**(CLRAM_AWWIDTH+2)-1); 169 -------------------------------------------------------------- 170 procedure safe_read_lram (signal i_call : out kernel_input_t; 171 signal o_response: in kernel_output_t; 172 signal pbuff: out t_array_slv_8; 173 constant len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)-1); 174 constant lram_address: in natural range 0 to 2**(CLRAM_AWWIDTH+2)-1); 175 -------------------------------------------------------------- 176 procedure safe_write_lram ( signal i_call : out kernel_input_t; 177 signal o_response: in kernel_output_t; 178 constant fmessage: in string; 179 constant parameters: in std_logic_vector; 180 constant lram_address: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 181 -------------------------------------------------------------- 182 procedure safe_write_sysram_word32_burst (signal i_call : out kernel_input_t; 183 signal o_response: in kernel_output_t; 184 signal pbuff: in t_array_slv_32; 185 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 186 constant offset: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 187 -------------------------------------------------------------- 188 procedure safe_read_sysram_word32_burst (signal i_call : out kernel_input_t; 189 signal o_response: in kernel_output_t; 190 signal pbuff: out t_array_slv_32; 191 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 192 constant offset: in natural range 0 to (2**CLRAM_AWWIDTH)-1); 193 -------------------------------------------------------------- 194 procedure pooled_buffer_write (signal i_call : out kernel_input_t; 195 signal o_response: in kernel_output_t; 196 signal shd_buff: in pooled_array_t; 197 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 198 constant buff_offset: in natural range 0 to 65535; 199 constant lram_address:in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 200 278 Appendix C. Source Listings Listing C.27: User Package - VHDL procedures declaration (part 4/6). -------------------------------------------------------------- 201 procedure pooled_buffer_read( signal i_call : out kernel_input_t; 202 signal o_response: in kernel_output_t; 203 signal shd_buff: in pooled_array_t; 204 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 205 constant buff_offset: in natural range 0 to 65535; 206 constant lram_address:in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 207 -------------------------------------------------------------- 208 procedure pooled_file_write (signal i_call : out kernel_input_t; 209 signal o_response: in kernel_output_t; 210 signal ufile: in pooled_file_t; 211 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 212 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 213 -------------------------------------------------------------- 214 procedure pooled_file_read( signal i_call : out kernel_input_t; 215 signal o_response: in kernel_output_t; 216 signal ufile: in pooled_file_t; 217 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 218 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 219 -------------------------------------------------------------- 220 procedure pooled_device_write (signal i_call : out kernel_input_t; 221 signal o_response: in kernel_output_t; 222 signal udevice: in pooled_device_t; 223 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 224 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 225 -------------------------------------------------------------- 226 procedure pooled_device_read( signal i_call : out kernel_input_t; 227 signal o_response: in kernel_output_t; 228 signal udevice: in pooled_device_t; 229 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 230 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 231 -------------------------------------------------------------- 232 procedure pooled_file_close( signal i_call : out kernel_input_t; 233 signal o_response : in kernel_output_t; 234 signal ufile: inout pooled_file_t); 235 -------------------------------------------------------------- 236 procedure pooled_file_open( signal i_call : out kernel_input_t; 237 signal o_response : in kernel_output_t; 238 signal ufile: inout pooled_file_t); 239 --------------------------------------------------------------- 240 procedure pooled_fstream_open(signal i_call : out kernel_input_t; 241 signal o_response : in kernel_output_t; 242 signal ufstream_q: in pooled_fstream_t; 243 signal ufstream_d: out pooled_fstream_t); 244 -------------------------------------------------------------- 245 procedure pooled_fstream_close(signal i_call : out kernel_input_t; 246 signal o_response : in kernel_output_t; 247 signal ufstream_q: in pooled_fstream_t; 248 signal ufstream_d: out pooled_fstream_t); 249 -------------------------------------------------------------- 250 procedure pooled_fstream_write (signal i_call : out kernel_input_t; 251 signal o_response: in kernel_output_t; 252 signal ustream: in pooled_fstream_t; 253 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 254 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 255 -------------------------------------------------------------- 256 procedure pooled_fstream_read(signal i_call : out kernel_input_t; 257 signal o_response: in kernel_output_t; 258 signal ustream: in pooled_fstream_t; 259 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 260 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 261 Appendix C. Source Listings 279 Listing C.28: User Package - VHDL procedures declaration (part 5/6). -------------------------------------------------------------- 268 procedure pooled_fstream_write_word32 (signal i_call : out kernel_input_t; 269 signal o_response: in kernel_output_t; 270 signal ustream: in pooled_fstream_t; 271 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 272 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 273 -------------------------------------------------------------- 274 procedure pooled_fstream_read_word32(signal i_call : out kernel_input_t; 275 signal o_response: in kernel_output_t; 276 signal ustream: in pooled_fstream_t; 277 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 278 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 279 -------------------------------------------------------------- 280 procedure pooled_fstream_read_len(signal i_call : out kernel_input_t; 281 signal o_response: in kernel_output_t; 282 signal ustream: in pooled_fstream_t; 283 signal flen:out integer); 284 -------------------------------------------------------------- 285 procedure pooled_socket_open( signal i_call : out kernel_input_t; 286 signal o_response : in kernel_output_t; 287 signal usock_q: in pooled_socket_t; 288 signal usock_d: out pooled_socket_t); 289 -------------------------------------------------------------- 290 procedure pooled_socket_close( signal i_call : out kernel_input_t; 291 signal o_response : in kernel_output_t; 292 signal usock_q: in pooled_socket_t; 293 signal usock_d: out pooled_socket_t); 294 -------------------------------------------------------------- 295 procedure pooled_socket_write ( signal i_call : out kernel_input_t; 296 signal o_response: in kernel_output_t; 297 signal usocket: in pooled_socket_t; 298 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 299 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 300 -------------------------------------------------------------- 301 procedure pooled_socket_read( signal i_call : out kernel_input_t; 302 signal o_response: in kernel_output_t; 303 signal usocket: in pooled_socket_t; 304 constant byte_len: in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 305 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 306 -------------------------------------------------------------- 307 procedure pooled_socket_write_word32 (signal i_call : out kernel_input_t; 308 signal o_response: in kernel_output_t; 309 signal usocket: in pooled_socket_t; 310 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 311 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 312 -------------------------------------------------------------- 313 procedure pooled_socket_read_word32( signal i_call : out kernel_input_t; 314 signal o_response: in kernel_output_t; 315 signal usocket: in pooled_socket_t; 316 constant word_len: in natural range 1 to (2**CLRAM_AWWIDTH); 317 constant source_laddress: in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 318 -------------------------------------------------------------- 319 procedure pooled_device_close( signal i_call : out kernel_input_t; 320 signal o_response : in kernel_output_t; 321 signal udev: inout pooled_device_t); 322 -------------------------------------------------------------- 323 procedure pooled_device_open( signal i_call : out kernel_input_t; 324 signal o_response : in kernel_output_t; 325 signal udev: inout pooled_device_t); 326 280 Appendix C. Source Listings Listing C.29: User Package - VHDL procedures declaration (part 6/6). -------------------------------------------------------------- 327 procedure write_stdio( signal i_call : out kernel_input_t; 328 signal o_response : in kernel_output_t; 329 constant slen:in natural range 1 to (2**(CLRAM_AWWIDTH+2)); 330 constant mlen:in natural range 0 to (2**(CLRAM_AWWIDTH+2)); 331 constant lram_address:in natural range 0 to (2**(CLRAM_AWWIDTH+2)-1)); 332 -------------------------------------------------------------- 333 procedure task_exit(signal i_call : out kernel_input_t; 334 signal o_response: in kernel_output_t); 335 -------------------------------------------------------------- 336 Listing C.30: User package - VHDL procedure to read the sysram memory. package hal_asos_user_pkg is 11 ... ------------------------------------------------------------------------------------------ 1641 procedure safe_read_sysram_word32 (signal i_call : out kernel_input_t; 1642 signal o_response: in kernel_output_t; 1643 signal pbuff: out t_array_slv_32; 1644 constant word_len: in natural; 1645 constant offset: in natural)is 1646 ------------------------------------------------------------------------------------------ 1647 constant ALNMNT: natural:=POW2(C_MACHINE_WIDTH/8); 1648 variable waddr: natural :=offset + o_response.index; 1649 variable param_woffs: unsigned(C_MACHINE_WIDTH-1 downto 0) 1650 := to_unsigned(waddr, C_MACHINE_WIDTH) rol ALNMNT; variable word: std_logic_vector(31 downto 0); 1651 begin 1652 if word_len = 0 then 1653 i_call.enable_scheduler <= '0'; 1654 i_call.reschedule <= '0'; 1655 else 1656 i_call.enable_scheduler <= '1'; 1657 i_call.reschedule <= '1'; 1658 1659 case o_response.sched_progress is 1660 when 0=> 1661 mutex_lock(i_call,o_response,CSYSMUTEX_WOFFSET); 1662 when 1=> 1663 i_call.enable_index <= '1'; 1664 i_call.increment_index<= '1'; 1665 i_call.reschedule<= '0'; 1666 mst_bus_read_word(i_call, 1667 o_response,std_logic_vector(param_woffs),word); pbuff(o_response.index) <= word; 1668 if o_response.index = word_len-1 then 1669 i_call.reschedule<= '1'; 1670 i_call.increment_index<= '0'; 1671 end if; 1672 when 2=> 1673 mutex_unlock(i_call,o_response,CSYSMUTEX_WOFFSET); 1674 i_call.enable_scheduler <= '0'; 1675 when others=>null; 1676 end case; 1677 end if; 1678 end procedure; 1679 ------------------------------------------------------------------------------------------ 1680 back to Figure 3.31. Appendix C. Source Listings 281 Listing C.31: Data transfer message - file descriptor write sequence diagram. package hal_asos_user_pkg is 11 ... ------------------------------------------------------------------------------------------ 3215 procedure pooled_file_async_write (signal i_call : out kernel_input_t; 3216 signal o_response: in kernel_output_t; 3217 signal ufile_q: in file_descriptor_t; 3218 constant byte_len: in natural range 1 to (2**(C_LRAM_AWWIDTH+2)); 3219 constant source_laddress: in natural range 0 to (2**(C_LRAM_AWWIDTH+2)- 3220 1))is 3221 ------------------------------------------------------------------------------------------ 3222 variable dmsg: kdata_transfer_m; 3223 begin 3224 dmsg.xcode := std_logic_vector(to_unsigned(exec_code_t'pos(TRANSFER_TO_POOLED),8)); 3225 dmsg.index := std_logic_vector(to_signed(ufile_q.index,8)); 3226 dmsg.transfer_len:= std_logic_vector(to_unsigned(byte_len,dmsg.transfer_len'length)); 3227 dmsg.receiver_offset:= (others=>'0'); 3228 dmsg.sender_offset 3229 := std_logic_vector(to_unsigned(source_laddress,dmsg.sender_offset'length)); send_message(i_call,o_response,dmsg); 3230 end procedure; 3231 ------------------------------------------------------------------------------------------ 3232 3233 ------------------------------------------------------------------------------------------ 3234 procedure pooled_file_async_write_complete (signal i_call : out kernel_input_t; 3235 signal o_response: in kernel_output_t; 3236 signal ufile_q: in file_descriptor_t; 3237 signal byte_len: out natural range 1 to (2**(C_LRAM_AWWIDTH+2)); 3238 signal source_laddress: out natural range 0 to (2**(C_LRAM_AWWIDTH+2)-1))is 3239 ------------------------------------------------------------------------------------------ 3240 variable dmsg : kdata_transfer_m; 3241 variable received_index: integer range -128 to 127; 3242 begin 3243 3244 receive_message(i_call,o_response); 3245 dmsg := cast_return_to_kdata_transfer_message(o_response); 3246 received_index:=to_integer(signed(dmsg.index)); 3247 3248 byte_len <= 0; 3249 source_laddress<= 0; 3250 if received_index = ufile_q.index then 3251 byte_len <= to_integer(unsigned(dmsg.transfer_len)); 3252 source_laddress<= to_integer(unsigned(dmsg.sender_offset)); 3253 end if; 3254 end procedure; 3255 ------------------------------------------------------------------------------------------ 3256 back to Figure 3.37. 282 Appendix C. Source Listings Listing C.32: HAL-ASOS Accelerator - HW-Kernel configurations for the a, c, d and e variants. architecture hwkernel of hal_kernel is 157 ... 158 end hwkernel 1635 1636 configuration hal_kernel_v4_00_a_config of hal_kernel is 1637 for hwkernel 1638 for XS00:xsync_gen 1639 use entity hal_asos_v4_00_A.sync_gen(blank); 1640 end for; 1641 for XS01:xsgen_bus 1642 use entity hal_asos_v4_00_A.gen_bus(single_clock); 1643 end for; 1644 for XM00: xmgen_bus 1645 use entity hal_asos_v4_00_a.gen_bus(single_clock); 1646 end for; 1647 end for; 1648 end configuration hal_kernel_v4_00_a_config; 1649 ... 1664 configuration hal_kernel_v4_00_c_config of hal_kernel is 1665 for hwkernel 1666 for XS00:xsync_gen 1667 use entity hal_asos_v4_00_A.sync_gen(blank); 1668 end for; 1669 for XS01:xsgen_bus 1670 use entity hal_asos_v4_00_A.gen_bus(single_clock); 1671 end for; 1672 for XM00: xmgen_bus 1673 use entity hal_asos_v4_00_a.gen_bus(single_clock); 1674 end for; 1675 end for; 1676 end configuration hal_kernel_v4_00_c_config; 1677 1678 configuration hal_kernel_v4_00_d_config of hal_kernel is 1679 for hwkernel 1680 for XS00:xsync_gen 1681 use entity hal_asos_v4_00_A.sync_gen(dual_clock); 1682 end for; 1683 for XS01:xsgen_bus 1684 use entity hal_asos_v4_00_A.gen_bus(single_clock); 1685 end for; 1686 for XM00: xmgen_bus 1687 use entity hal_asos_v4_00_a.gen_bus(single_clock); 1688 end for; 1689 end for; 1690 end configuration hal_kernel_v4_00_d_config; 1691 1692 configuration hal_kernel_v4_00_e_config of hal_kernel is 1693 for hwkernel 1694 for XS00:xsync_gen 1695 use entity hal_asos_v4_00_A.sync_gen(dual_clock); 1696 end for; 1697 for XS01:xsgen_bus 1698 use entity hal_asos_v4_00_A.gen_bus(mxclock_a_is_y); 1699 end for; 1700 for XM00: xmgen_bus 1701 use entity hal_asos_v4_00_a.gen_bus(single_clock); 1702 end for; 1703 end for; 1704 end configuration hal_kernel_v4_00_e_config; 1705 ... back to Figure 4.22. Appendix C. Source Listings 283 Listing C.33: File reader software Task run member. hal_asos::TaskConfig_t 41 TFileRead = { "FileReader", //TaskTag 42 { "Imagelines",BLOCK_LEN,1,1 },//Topic 43 { "",0 }// No Subscription 44 }; 45 ... hal_asos::Task<>* p_Detector_Task; 151 template<> 152 void hal_asos::Task <hal_asos::SwTask, TFileRead> ::run(void) { 153 std::ifstream input_file; std::string s; std::stringstream ss; 154 std::string header0 = ""; std::string header1= ""; std::string header2= ""; 155 std::string version, width, height; 156 std::shared_ptr<char[BLOCK_LEN]> p_line; 157 std::shared_ptr<StreamData> Conf = std::make_shared<StreamData>(16); 158 detector::config_words *p_config = (detector::config_words*)Conf.get(); 159 int file_length, Read_len=0, count = 0, pixel_len = 0; 160 input_file.open(hal_asos_demo::feature_detector::scene_img.c_str(), std::ios::in | 161 std::ifstream::binary); if (!input_file.is_open()) { 162 LOG_MSG << this->TaskTag << ":error opening input file!\n"; 163 this->shutdown_unconditional(); 164 return; 165 }// First line : version 166 getline(input_file, header0); 167 if (delimiter.compare("P5") != 0) { 168 LOG_MSG << "Wrong file format or version\n"; 169 this->shutdown_unconditional(); 170 return; 171 } 172 // secondline: wxh 173 getline(input_file, header1); 174 ss.str(header1); 175 ss >> p_config->image_width >> p_config->image_height; 176 if (p_config->image_width > BLOCK_LEN) { 177 this->StatusRunning = false; 178 LOG_MSG <<this->TaskTag<< "Topiclen is smaller than image width\n"; 179 this->shutdown_unconditional(); 180 return; 181 } 182 //third line 183 getline(input_file, header2); 184 p_config->threshould = hal_asos_demo::feature_detector::th; 185 file_length = p_config->image_width * p_config->image_height; 186 Read_len = p_config->image_width; 187 if (p_Detector_Task) { 188 p_config->block_len = hal_asos_demo::feature_detector::block_size; 189 p_Detector_Task->submit_data(Conf); 190 } 191 while (this->StatusRunning && Read_len > 0) { 192 p_line = std::shared_ptr<char[BLOCK_LEN]>(new char[p_config->image_width], [](char* p) 193 { delete[] p; }); input_file.read(p_line.get(), p_config->image_width); 194 Read_len = (int)input_file.gcount(); 195 if (Read_len) { 196 file_length -= Read_len;pixel_len += Read_len; 197 this->p_Topic->publish(p_line, Read_len); count++; 198 p_line = nullptr; 199 } 200 else p_line = nullptr; 201 } 202 input_file.close(); 203 this->p_Topic->close_topic(); 204 LOG_MSG << this->TaskTag << "finished...(" << count << "," << " " << pixel_len << ")\n"; 205 } 206 back Figure 5.6. 290 Appendix C. Source Listings Listing C.40: Extended features synchronous Control unit for the HW accelerated feature detection using the LRAM(1/2). ---------------------------------------------------------------------------------------- 441 EXTENEDED_FEATURES: process(task_state, resetn_i, kernel_response, 442 line0_in_burst_q,block_len,count_crnr_bytes_q,pixel_block_counter,pixels_target_q, 443 index_read_q,index_write_q,fifo_out_burst_last_q,fifo_out_burst_q, 444 count_crnrs_q,corners_word_i,trfr_len_q,data_in_i) 445 ------------------------------------------------------------------------------------------ 446 variable RAM_DATA:STD_LOGIC_VECTOR(31 DOWNTO 0); 447 begin 448 RAM_DATA:=(OTHERS=>'0'); pixels_target_d <= pixels_target_q; 449 config_d<= (others=>(others=>'0'));OFFSET_i<= (others=>'0'); 450 pixels_word_d <= (OTHERS=>'0');pop_crnrs_i <= '0';trfr_len_d <= trfr_len_q; 451 inc_windex_i <='0';write_pixel_word <= '0'; 452 if resetn_i = '0' then 453 reset_sys_call(kernel_call); 454 else 455 hal_asos_link_to_kernel(kernel_response,kernel_call); 456 case task_state is 457 when s1_read_config=> 458 transfer_from_host_swfifo(kernel_call,kernel_response,C_CONF_LEN); 459 when s2_write_config=> 460 kernel_call.enable_index <= '1'; 461 kernel_call.increment_index <= '1'; 462 config_d(0)<=data_in_i(0); 463 config_d(1)<=data_in_i(1); 464 config_d(2)<=data_in_i(2); 465 OFFSET_i<= std_logic_vector(to_unsigned(kernel_response.index,3)); 466 if kernel_response.index = (C_CONF_LEN/4)-1 then 467 kernel_call.increment_index <= '0'; 468 end if; 469 when s3_config_run=> 470 config_d(0)<= x"00000080"; 471 OFFSET_i<= std_logic_vector(to_unsigned(CONTROL_OFFSET,OFFSET_i'length)); 472 when s4_read_block=> 473 transfer_data_from_dds(kernel_call,kernel_response,0, block_len); 474 pixels_target_d <= cast_return_to_transfer_len(kernel_response); 475 when s7_write_pixel=> 476 lram_read_word(kernel_call, kernel_response,index_read_q,RAM_DATA); 477 write_pixel_word <= cast_return_to_push_data(kernel_response); 478 pixels_word_d<=RAM_DATA; 479 when s7_write_pixels=> 480 lram_read_word_burst(kernel_call,kernel_response, 481 line0_in_burst_q,index_read_q,RAM_DATA); write_pixel_word <= cast_return_to_push_data(kernel_response); 482 pixels_word_d<=RAM_DATA; 483 when st10_lock_rsrc_mutex=> 484 mutex_lock(kernel_call,kernel_response,CLMUTEX_WOFFSET); 485 when s11_read_crnrs=> 486 lram_write_word_burst(kernel_call, kernel_response, fifo_out_burst_q, 487 index_write_q,corners_word_i); pop_crnrs_i<=kernel_response.block_task; 488 inc_windex_i<=kernel_response.block_task; 489 when s12_unlock_rsrc_mutex=> 490 mutex_unlock(kernel_call,kernel_response,CLMUTEX_WOFFSET); 491 when s14_write_block=> 492 transfer_data_to_dds(kernel_call, kernel_response,32768/4, count_crnr_bytes_q); 493 trfr_len_d <= cast_return_to_transfer_len(kernel_response); 494 when s18_lock_rsrc_mutex_last=> 495 mutex_lock(kernel_call,kernel_response,CLMUTEX_WOFFSET); 496 when s19_read_corner_last=> 497 lram_write_word(kernel_call, kernel_response,index_write_q,corners_word_i); 498 pop_crnrs_i<=kernel_response.block_task; 499 inc_windex_i <= kernel_response.block_task; 500 back to Figure 5.12. [Document text truncated for crawler view.]