Sunteți pe pagina 1din 202

Designing with Nios II

and SOPC Builder

Copyright © 2005 Altera Corporation


Agenda
 Nios II® Hardware Development
 Nios II Software Development
 Nios II Software Debug
 RTL Simulation
 Avalon Switch Fabric
 Custom Peripherals
 Custom Instructions
 Multi-Masters and Direct Memory Access (DMA)
 Configuring the Development Board

Copyright © 2005 Altera Corporation


2
Nios II Hardware
Development

Copyright © 2005 Altera Corporation


What is Nios II?
 Altera’s Second Generation Soft-Core 32 Bit RISC Microprocessor
- Nios
Developed
II Plus Internally By Altera
All Peripherals Written In HDL
- Can
Harvard Architecture
Be Targeted For All Altera FPGAs
- Synthesis
Royalty-Free
Using Quartus II Integrated Synthesis

Nios II UART

Cache

Avalon Switch Fabric


CPU
Debug GPIO

On-Chip Timer
ROM
SPI
On-Chip SDRAM
RAM Controller

FPGA

Copyright © 2005 Altera Corporation


4
Problem: Reduce Cost, Complexity & Power

I/O Flash
CPU
SDRAM
I/O
I/O I/O I/O

DSP
I/O FPGA
CPU DSP

Solution: Replace External Devices


with Programmable Logic
Copyright © 2005 Altera Corporation
5
Problem:On
System Reduce Cost, Complexity
A Programmable Chip& Power
(SOPC)

Flash
FPGA
SDRAM

CPU is a Critical
Solution: ReplaceControl Function
External Devices
Required forProgrammable
with System-Level Logic
Integration
Copyright © 2005 Altera Corporation
6
FPGA Hardware Design Flow
with Quartus II and SOPC Builder

• Create FPGA project in Quartus II


• Build embedded sub-system in SOPC Builder
• Integrate sub-system in Quartus II .sof / .pof file
• Compile and generate a programming file

Copyright © 2005 Altera Corporation


7
Development Kits, Stratix & Cyclone Edition
Download /JTAG
Debug Connector
Serial RS-232 Power Connector
Connectors

10/100 Ethernet
MAC/PHY &
RJ-45 Connector
CPU Reset Expansion
Prototype
8 MB Flash Connectors
(40 I/O pins each)

16 MB SDRAM

1MB SRAM

Configuration Controller
Compact Flash Buttons LEDs 7 Segment (MAX 7128AE)
(Connector Mounted on Back)
Configuration Control
Copyright © 2005 Altera Corporation
8
Standard Design Block Diagram
Ethernet 1MB 8MB 16MB Compact 32MB
MAC/PHY SRAM FLASH FLASH SDRAM

Nios II Processor
Compact
Address (32) Tri-State Tri-State SDRAM
Flash

Level Shifter
Bridge Bridge Controller
Read PIOs
32-Bit
Avalon Switch Fabric

Write
Nios II
Processor Data In (32) UART
General
Data Out (32) ROM Periodic
Purpose
(with Monitor) Timer
Timer
Reconfig
PIO
IRQ

IRQ #(6) 7-Segment


LED PIO LCD PIO Button PIO
LED PIO

Expansion 4
2 Digit
On-Chip Off-Chip 8 LEDs Header Momentary
Display
J12 buttons

Copyright © 2005 Altera Corporation


9
Nios II System Architecture
Address Avalon UART 0
Instr. UART n
Decoder Master/
Nios II Slave
CPU Data Port Timer 0
Interrupt Interfaces Timer n
Controller
On-Chip
Debug Core SPI 0
SPI n
Wait State
Generation
GPIO 0
GPIO n
Data in
Off-Chip
Multiplexer
Software Trace DMA 0
Memory DMA n
Master
Arbitration Memory
Interface Memory
Interface
Dynamic
Bus Sizing User-Defined
InterfaceUser-Defined
Interface
Avalon Switch Fabric
Copyright © 2005 Altera Corporation
10
Nios II Block Diagram
Nios II Processor Core
reset
Program Instruction
clock Master
Controller General
& Port
JTAG interface Hardware- Purpose Instruction
Assisted Address Registers
to Software Generation Cache
Debugger Debug Module r0 to r31

Exception
Controller
Control
Interrupt Registers
irq[31..0] Controller ctl0 to ctl4
Data
Master
Port
Data
Custom Arithmetic Cache
Custom Instruction Logic Unit
I/O Signals Logic

Copyright © 2005 Altera Corporation


11
Nios II Processor Architecture

 Classic Pipelined RISC Machine


 32 General Purpose Registers
 3 Instruction Formats
 32-Bit Instructions
 32-Bit Data Path
 Flat Register File
 Separate Instruction and Data Cache (configurable sizes)
 Branch Prediction
 32 Prioritized Interrupts
 Custom Instructions
 JTAG-Based Hardware Debug Unit

Copyright © 2005 Altera Corporation


12
Nios II Versions
 Nios II Processor Comes In Three ISA Compatible
Versions

 FAST: Optimized for Speed

 STANDARD: Balanced for Speed and Size

 ECONOMY: Optimized for Size

 Software
 Code is Binary Compatible
 No Changes Required When CPU is Changed

Copyright © 2005 Altera Corporation


13
Binary Compatibility / Flexible Performance
Nios II /f Nios II /s Nios II /e
Fast Standard Economy
Pipeline 6 Stage 5 Stage None
H/W Multiplier & Emulated
Barrel Shifter 1 Cycle 3 Cycle In Software

Branch Prediction Dynamic Static None

Instruction Cache Configurable Configurable None

Data Cache Configurable None None

Logic Usage
1400 - 1800 1200 – 1400 600 – 700
(Logic Elements)
Custom
Instructions Up to 256

Copyright © 2005 Altera Corporation


14
Hardware Multiplier Acceleration
 Nios II Economy version - No Multiply Hardware
 Uses GNUPro Math Library to Implement Multiplier
 Nios II Standard - Full Hardware Multiplier
 32 x 32  32 in 3 Clock Cycles if DSP block present, else uses software
only multiplier
 Nios II Fast - Full Hardware Multiplier
 32 x 32  32 in 1 Clock Cycles if DSP block present, else uses software
only multiplier
Acceleration Clock Cycles
Hardware (32 x 32  32)
None 250
Standard
3
MUL in Stratix
Fast
1
MUL in Stratix

Copyright © 2005 Altera Corporation


15
Licensing
 Nios II Delivered As Encrypted Megacore
 Licensed Via Feature Line In Existing Quartus II License File
 Consistent With General Altera Megacore Delivery Mechanism
 Enables Detection Of Nios II In Customer Designs (Talkback)
 No Nios II Feature Line (OpenCore Plus Mode)
 System Runs If Tethered To Host PC
 System Times Out If Disconnected from PC After ~ 1 hr
 Nios II Feature Line (Active Subscriber)
 Subscription and New Dev Kit Customers Obtain Licenses From
www.altera.com
 Nios II CPU RTL Remains Encrypted
 Nios II Source License
 Available Upon Request On Case-By-Case Basis
 Included With Purchase Of Nios II ASIC License

Copyright © 2005 Altera Corporation


16
Requirements for Nios II Designs
 Quartus II 4.0 SP1 or higher
 Note: Quartus II now 4.2 available
 Required for Nios II 1.1
 No spaces in Quartus II project pathname
 Nios II license or a programming cable
tethered to PC to run the OpenCore Plus
version of Nios II

Copyright © 2005 Altera Corporation


17
Nios II: Hard Numbers
Nios II/f Nios II/s Nios II/e
200 DMIPS @ 175MHz 90 DMIPS @ 175MHz 28 DMIPS @ 190MHz
Stratix II
1180 LEs 800 LEs 400 LEs
1 of 8 DSP
4K Icache, 2K Dcache 4K Icache, No Dcache No Icache, No Dcache
Stratix 2S10-C5 Stratix 2S10-C5 Stratix 2S10-C5
150 DMIPS @ 135MHz 67 DMIPS @ 135MHz 22 DMIPS @ 150MHz
Stratix
1800 LEs 1200 LEs 550 LEs
1 of 8 DSP
4K Icache, 2K Dcache 4K Icache, No Dcache No Icache, No Dcache
Stratix 1S10-C5 Stratix 1S10-C5 Stratix 1S10-C5
100 DMIPS @ 125MHz 62 DMIPS @ 125MHz 20 DMIPS @ 140MHz
Cyclone
1800 LEs 1200 LEs 550 LEs

4K Icache, 1K Dcache 2K Icache, No Dcache No Icache, No Dcache


Cyclone 1C4-C6 Cyclone 1C4-C6 Cyclone 1C4-C6
* FMax Numbers Based Reference Design Running From On-Chip Memory (Nios II/f 1.15 DMIPS / MHz)

Copyright © 2005 Altera Corporation


18
SOPC Builder – System Contents Page

 Altera, Partner & User


Cores
 Processors
 Memory Interfaces
 Peripherals
Over 60
 Bridges
Cores Available
 Hardware Accelerators
Today
 Import User Logic
(ie. custom peripherals)
 Web-Based IP Deployment

Copyright © 2005 Altera Corporation


19
Clock-Domain Crossing New in
4.2

 Auto-Insertion of Clock-Domain Crossing Logic


 FIFO Where Posted-Reads Are Supported
 Simple Metastability-Hardening Otherwise
 Unlimited Number of Clock Domains
 Added, Named & Managed Through GUI

Copyright © 2005 Altera Corporation


20
Nios II CPU Configured in SOPC Builder
 Hardware designer selects which Nios II version to use when
creating system

Copyright © 2005 Altera Corporation


21
Selecting JTAG Debug Core
 Configuration is chosen when hardware designer selects
appropriate Nios II processor core

Copyright © 2005 Altera Corporation


22
SOPC Builder – More “cpu” Settings Page

Copyright © 2005 Altera Corporation


23
SOPC Builder – System Generation Page

Copyright © 2005 Altera Corporation


24
SOPC Builder Produces a .PTF File
 Text file that records SOPC Builder edits
 Describes Nios II System
 Used by software development tools

Copyright © 2005 Altera Corporation


25
Integrate SOPC Builder O/P in Quartus II
 Integrate SOPC Builder block symbol to Quartus II schematic
(as shown below) and compile design
 Or, instantiate top module into your HDL design and compile

Copyright © 2005 Altera Corporation


26
New Peripherals for Nios II
 System ID Peripheral  Memory Interfaces
 Used to Ensure Hardware/  EPCS Serial Flash
Software Version Synchronization Controller
 Simple 2 read-only register  On-Chip
peripheral containing hardware ID  RAM, ROM
tags.  Off-Chip
 Register 1 contains random  SRAM
number  CFI Flash
 Register 2 contains time and date
when system was generated in
SOPC Builder  LCD Display
 Can be checked at runtime to
ensure that the software to be
downloaded matches the
hardware image

Copyright © 2005 Altera Corporation


27
New Peripherals for Nios II
 JTAG UART  Compact Flash Interface
 Single JTAG  Mass Storage Support
 True IDE Mode
Connection For:  Compact Flash Mode
 Device Configuration
 Software Supports
 Flash Programming
 Low-Level API
 Code Download
 MicroC/OS-II File System
 Debug
Support
 Target STDIO (printing)  µCLinux File System
Support

Supported through
www.niosforum.com

Copyright © 2005 Altera Corporation


28
Project Directories
 Hardware
 HDL Source & Netlist
 db - Quartus project
database
 Software
 Application source code
 Library files
 Simulation
 Testbench
 Automatically generated
test memory and vectors

Copyright © 2005 Altera Corporation


29
Exercise 1
A Basic Nios II Design
35 mins

Copyright © 2005 Altera Corporation


Nios II Software
Development

Copyright © 2005 Altera Corporation


Nios II System Design Flow
SOPC Builder GUI
Processor Library Configure Processor Custom Instructions

Peripheral Library Select & Configure IP Modules


Peripherals, IP
Hardware Development Software Development
Connect Blocks Nios II IDE
 HDL Source Files  C Header files
 Testbench  Custom Library
Generate
 Peripheral Drivers

Hardware Executable
Configuration Code
Synthesis & Compiler,
File
Fitter Verification Linker, Debugger
& Debug
JTAG,
Serial, or
 User Design Ethernet
 User Code
 Other IP Blocks  Libraries
On-Chip
Altera Debug  RTOS
Quartus II FPGA Software Trace
Hard Breakpoints GNU Tools
SignalTap® II

Copyright © 2005 Altera Corporation


32
Nios II Software Design Process

Deliverables Required to Start Software Development


Software Development: Nios II IDE
 C Header files
• .ptf file from SOPC Builder  Custom Library
(defines hardware for the Nios II IDE)  Peripheral Drivers

• .sof (or .pof) file from Quartus II Executable


Code
Compiler,
(used to program the FPGA on the board) Linker, Debugger

That’s ALL you need to start User Code


 Libraries
to run with the Nios II IDE  RTOS

GNU Tools

Copyright © 2005 Altera Corporation


33
Nios II IDE (Integrated Development Environment)*

 Leading Edge Software


Development Tool
 Target Connections
 Hardware (JTAG)
 Instruction Set Simulator
 ModelSim®-Altera Software
 Advanced Hardware
Debug Features
 Software and Hardware
Break Points, Data Triggers,
Trace
 Flash Memory
Programming Support

* Based on Eclipse Project

Copyright © 2005 Altera Corporation


34
Opening the Nios II IDE
Launch the Nios II IDE from
the SOPC Builder or from
the Windows Start menu

Copyright © 2005 Altera Corporation


35
Nios II IDE

File Viewer
List of Open Window
Projects
(for C code,
C++, and
assembly*)

Terminal
window

•Note: C++ files must have extension .cpp


In-line assembly code offset by asm();
Copyright © 2005 Altera Corporation
36
Nios II IDE C/C++ Projects/Navigator
 Lists all  List all
open open and
projects closed
projects
 Displays
source files  Allows you
associated to drag and
with project drop new
files into
existing
projects

Copyright © 2005 Altera Corporation


37
Creating a C/C++ Application
File > New > Project

Copyright © 2005 Altera Corporation


38
Creating a C/C++ Application

Link to a System Library


- Select a pre-existing library
- Or create a new library

Copyright © 2005 Altera Corporation


39
This Creates Two Software Projects
- Application and System Library Project

Application Project
- contains application
source code

System Library Project


- contains system
header file, etc.

Drivers Directory
- contains all device
drivers – DO NOT
DELETE !

Copyright © 2005 Altera Corporation


40
Application and System Library Projects

 Application Projects build executables


 System Library Projects contain interface to the
hardware
 Nios II device drivers (Hardware Abstraction
Layer)
 Optional RTOS (MicroC/OS-II)
 Optional software components (Lightweight
TCP/IP stack, Read Only Zip File System)

Copyright © 2005 Altera Corporation


41
Other New Project Options
 System Library
 Only creates system library project
 Build C applications upon this later
 Advanced C/C++ Project
 Disable automatic tool features like
makefile and linker script generation
 User defines own instead
 Managed Library Project
 Facilitates software library development
 Enables you to associate pre-compiled
code into an Application Project
 Tool writes makefile for included files

Copyright © 2005 Altera Corporation


42
Importing Projects into the IDE

Copyright © 2005 Altera Corporation


43
Project Properties
 Both Application and System Library have
Properties pages

Copyright © 2005 Altera Corporation


44
System Library Options
Select
Specify
Partition theRTOS
stdio devicesmap
memory

Copyright © 2005 Altera Corporation


45
Software Compilation
 To compile a software application, highlight your project
and select Build Project from the Projects menu

Copyright © 2005 Altera Corporation


46
Directory Structure After Compilation

 Application Project  System Library Project

Copyright © 2005 Altera Corporation


47
Nios II Host Platform Support
 Windows XP
 Linux Host Support (RedHat 7.3, 8.0,
Enterprise 3)
 Nios II GNU Toolchain (Compiler, Binary Utilities)
 Nios II Instruction Set Simulator
 Nios II Debugger
 Nios II IDE
 USB Blaster Linux driver

Copyright © 2005 Altera Corporation


48
Hardware Abstraction Layer
 A lightweight runtime environment for Nios II software
 Provides a level of abstraction between application code and
low level hardware
 HAL libraries are generated by Nios II IDE
 A HAL contains:
 device drivers
 initialization software
 file system
 stdio, stderr

Copyright © 2005 Altera Corporation


49
Hardware Abstraction Layer
 Provides generic device models for classes of
peripherals common in embedded systems
 eg. timers, I/O peripherals, etc.
 Gives a consistent POSIX-like API, regardless of
underlying hardware
 Make programming as familiar as possible to
software engineers who may not be familiar with the
specific peripheral architectures
 ANSI C (through the Newlib library)
 UNIX style interface (i.e. POSIX like)
 Altera extensions where standards don’t exist or were
inappropriate (watch for the alt_* extension)

Copyright © 2005 Altera Corporation


50
Hardware Abstraction Layer
 Key features of the HAL
 Uses standard interfaces where appropriate
 Close integration with the Newlib ANSI C library
 http://sources.redhat.com/newlib/

 Device drivers automatically configured to match the PTF


 Drivers initialised before main()
 Scalable (i.e. packs down small)
 Clear distinction between system and application software

Copyright © 2005 Altera Corporation


51
Nios II HAL: Runtime Library
The HAL ‘UNIX Style’ Functions are the glue
between the C library and the device drivers

User Program HAL API


_exit() open()
close() opendir
C
C Standard
Standard Library
Library closedir() read()
fstat() readdir()
getpid() rewinddir()
HAL API gettimeofday() sbrk()
ioctl() settimeofday(
Device Device Device isatty() )
Driver Driver … Driver kill() stat()
lseek() usleep()
wait()
Nios II Processor System Hardware write()

Copyright © 2005 Altera Corporation


52
HAL File System

/dev /mnt

/dev/jtag_uart0 /dev/lcd0 /mnt/rozipfs

/mnt/rozipfs/myfile1

• Device names match those set in SOPC /mnt/rozips/myfile21


builder.
• Can only access nodes, not directories.
• All paths must be absolute (no current
directory)

Copyright © 2005 Altera Corporation


53
Familiar File/Device Access
 ANSI C:
fp = fopen (“/dev/lcd0”, “w”); fprintf (fp, “%s”, msg);
 UNIX Style:
fd = open (“/dev/lcd0”, O_WRONLY); write (fd, msg, strlen(msg));

 Newlib also supports C++ streams:


ofstream ofp(“/dev/lcd0”, ios::out); ofp << msg;
 Existing code (outside the Nios world) uses
these interfaces. Porting is now much
easier.
 Use of existing standards means there’s
nothing new to learn.
Copyright © 2005 Altera Corporation
54
HAL System Header File
SOPC Builder System Contents

system.h

System Library Settings


Copyright © 2005 Altera Corporation
55
system.h
 Contains macro definitions for system parameters,
including peripheral configuration, for instance:
 Hardware configuration of the peripheral
 Base address
 IRQ priority (if any)
 Symbolic name for peripheral
 Does not include: static information, function
prototypes, or device structures (unlike the old
excalibur.h)
 Located in the syslib project directory
 Rarely necessary to include it explicitly in your
application code, which improves rebuild time

Copyright © 2005 Altera Corporation


56
system.h - example
 Defines system settings and peripheral configurations:
 Replaces excalibur.h (from Nios)
/* .
* system configuration
.
*
.
*/
/*
* button_pio configuration
#define ALT_SYSTEM_NAME "std_1s10ES"
*
#define ALT_CPU_NAME "cpu"
*/
#define ALT_CPU_ARCHITECTURE "altera_nios2"
#define ALT_DEVICE_FAMILY "STRATIX"
#define BUTTON_PIO_NAME "/dev/button_pio"
#define ALTERA_NIOS_DEV_BOARD_STRATIX_1S10_ES
#define BUTTON_PIO_TYPE "altera_avalon_pio"
#define ALT_STDIN "/dev/jtag_uart"
#define BUTTON_PIO_BASE 0x00920830
#define ALT_STDOUT "/dev/jtag_uart"
#define BUTTON_PIO_IRQ 2
#define ALT_STDERR "/dev/jtag_uart"
#define BUTTON_PIO_HAS_TRI 0
#define ALT_CPU_FREQ 50000000
#define BUTTON_PIO_HAS_OUT 0
#define ALT_CPP_CONSTRUCTORS
#define BUTTON_PIO_HAS_IN 1
#define ALT_IRQ_BASE NULL
#define BUTTON_PIO_CAPTURE 1
.
#define BUTTON_PIO_EDGE_TYPE "ANY"
. #define BUTTON_PIO_IRQ_TYPE "EDGE"
. #define BUTTON_PIO_FREQ 50000000

Copyright © 2005 Altera Corporation


57
HAL References
 Each HAL project references library routines and drivers for the
components included in your Nios II system

Copyright © 2005 Altera Corporation


58
Reading/Writing Hardware in Nios
 Nios Classic used volatile pointers to
access hardware e.g.
 volatile *my_led_pointer = (int *) LED_BASE;

 Volatiles will no longer provide access to


hardware registers in Nios II
 They are still used to tell the compiler not to
optimize code
 No longer disable cache access

Copyright © 2005 Altera Corporation


59
Reading/Writing Hardware in Nios II

 Instead use I/O macros to access hardware


 I/O macros bypass the cache for hardware accesses
 They set bit 31 of address bus high (ie. control bit)
 IORD(BASE, REGNUM)
 Reads value at register BASE REGNUM = 0

REGNUM offset from base REGNUM = 1


address BASE BASE+2 REGNUM = 2
REGNUM = 3
 IOWR(BASE,REGNUM,DATA) BASE+4 REGNUM = 4
 Writes DATA to register
REGNUM offset from base
address BASE

Copyright © 2005 Altera Corporation


60
Header Files for Nios II Peripherals
 Each Nios II peripheral has specific read/write
macros for each register
 Example: UART (altera_avalon_uart_regs.h)

#define IORD_ALTERA_AVALON_UART_RXDATA(base) IORD(base, 0)


#define IOWR_ALTERA_AVALON_UART_RXDATA(base, data) IOWR(base, 0, data)

#define IORD_ALTERA_AVALON_UART_TXDATA(base) IORD(base, 1)


#define IOWR_ALTERA_AVALON_UART_TXDATA(base, data) IOWR(base, 1, data)

#define IORD_ALTERA_AVALON_UART_STATUS(base) IORD(base, 2)


#define IOWR_ALTERA_AVALON_UART_STATUS(base, data) IOWR(base, 2, data)

Copyright © 2005 Altera Corporation


61
Data Cache
 Memory space is mirrored (e.g. 2GB
addressable space)
 Upper half is uncacheable
 Lower half is cacheable
 All data variables are cached by default
 This can cause memory coherency issues if you
are using a DMA controller in your design.

Copyright © 2005 Altera Corporation


62
Data Cache
 To bypass the cache and maintain coherency…
 Flush before any DMA transfers using
alt_dcache_flush()
 Allocate uncacheable regions on the heap
using alt_uncached_malloc()
 Remap an existing area of memory using
alt_remap_uncached()
 Use ldio or stio instructions in assembly

Copyright © 2005 Altera Corporation


63
Interrupts
 HAL API for ISRs - Functions
 alt_irq_register()
 Associates interrupt with your ISR function.
 alt_irq_disable_all()
 Disables all IRQs
 alt_irq_enable_all()
 Enables all IRQs
 alt_irq_interruptible()
 Used in ISR function body. Allows ISR to be interrupted by
higher priority IRQs.
 alt_irq_non_interruptible()
 Used to make ISRs uninterruptible (default behavior).

Copyright © 2005 Altera Corporation


64
HAL API for ISRs - Useful Info
sample_isr ( void* context, alt_u32 id);
Write your ISR
id == irq number (0 to 31)
(Follow prototype) context == void pointer to data produced by or
consumed by ISR.

alt_irq_register ( alt_u32 id, void* context,


void (*irq_handler) (void*, alt_u32));
Register your ISR Sample Usage:
Using alt_irq_register() alt_irq_register ( 3, &some_data,
sample_isr);

Copyright © 2005 Altera Corporation


65
HAL API for ISRs - Useful Info
 Creating interruptible code blocks in ISR
 Use alt_irq_interruptible() & alt_irq_non_interruptible()
 Do not use standard C library or RTOS software functions inside
ISR that may pend for any reason
 Eg. printf()
 Keep it simple….
 Use ISR to trigger execution of slow processing tasks outside of
interrupt context
 Do NOT perform these tasks within ISR

 References:
 Exception Handling Chapter in “Nios II Software Developer’s
Handbook”

Copyright © 2005 Altera Corporation


66
Nios II OS / RTOS Support
Product Provider Source Standards TCP/IP File Other
Stack System
Code
* MicroC/OS-II Micrium Yes RTCA/DO-178B Opt. Opt. GUI
Flash

* Lightweight Open Source Yes Sockets API µC/OS-II


IP Support
IP, ICMP, UDP,
TCP/IP Stack TCP
** Nucleus Plus ATI/Mentor Yes OSEK Opt. Opt. GUI, SNMP
µITRON RMON,
SPAN
µCLinux Open Source Yes Incl. Many, Extensive
(GPL) inc. drivers and
middlewear,
FAT
inc USB,
and IPSec, etc.
JFFS2
KROS KROS Yes POSIX Opt. Opt.
Technologies

<continued on next slide>


* Included in Nios II Development Kits
** Evaluation Version Included in Nios II Development Kits
Copyright © 2005 Altera Corporation
67
Nios II OS / RTOS Support (cont)
Product Provider Source Standards TCP/IP File Other
Stack System
Code
NORTi MiSPO Yes µITRON Opt. Opt. PPP,
SNMP,
HTTP
PrKERNELv4 eSOL Yes µITRON Opt. Opt. USB, Mail
HTTP

ThreadX Express Logic Yes Opt. Opt. USB

eCos Open Source Yes POSIZ, uITRON, Incl. FAT, Extensive


(GPL with EL/IX JFFS2, drivers and
middleware
excpetion) ROMFS,
, inc. USB,
RAMFS IPSec, etc.

* Included in Nios II Development Kits


** Evaluation Version Included in Nios II Development Kits
Copyright © 2005 Altera Corporation
68
Nios II MicroC/OS-II
 Single-seat developers license included for free with
Nios II kits
 Licensing fee req’d when you productize your system
 Full source code included
 Preemptive operating system
 Small footprint
 Code Size (min 5KB, max 20KB)
 Data Space (min 1KB, max 5KB)
 Supports Semaphores, and Mailboxes for task
synchronization

Copyright © 2005 Altera Corporation


69
Nios II MicroC/OS-II

Copyright © 2005 Altera Corporation


70
Lightweight IP for MicroC/OS-II
 Plugs is being replaced with the
Lightweight IP TCP/IP stack in Nios II
 Open source TCP/IP Stack
 Supports TCP, UDP, IP, DHCP and ARP
 Optimised for size (Very simple web server < 500k)
 LWIP supports IPv4 and IPv6, but we support IPv4 ONLY
 Based on version 0.6.3
 Integrated into Nios II IDE
 Used in conjunction with uC/OS-II
 Sockets API available
 Free Licensing
 Modified BSD License, must keep the copyright notice and display it in the
product documentation

Copyright © 2005 Altera Corporation


71
LWIP - Instantiation
 Available as a Software Component

Copyright © 2005 Altera Corporation


72
LWIP – Configuration

Copyright © 2005 Altera Corporation


73
Nios to Nios II Conversion
 Hardware Must be Ported
 Add Nios II processor and connections in
SOPC Builder

 Software can be Used in Legacy SDK


Mode or Ported to HAL

See AN350 for full details

Copyright © 2005 Altera Corporation


74
Nios to Nios II Conversion
 Legacy Software Support
 Minimal if any Code Changes Required
 No Access to Nios II IDE
 Only supported for Standard and Economy
cores
 New peripherals (CFI flash, sysid, etc…) not
supported
 New software components (uC/OSII, LWIP)
not supported

Copyright © 2005 Altera Corporation


75
Nios to Nios II Conversion
 Full Port from Nios to Nios II
 Requires C code changes
 No GERMS support
 Provides access HAL, uC/OSII, LWIP

Copyright © 2005 Altera Corporation


76
Nios to Nios II Conversion
 Porting Process:
 Replace header files
 Example: system.h for excalibur.h
 Change API calls from SDK to HAL syntax
 Example: nr_delay() is replaced with usleep()
 Replace data types (int, char, etc..) with Nios II data
types (alt_u32, alt_u8, etc…)
 Replace hardware access pointers with macros
 Example: my_pio->data = 1 is replaced with
IOWR_ALTERA_AVALON_PIO_DATA(PIO_BASE,1)
 Take into account that *volatile pointers no longer
prevent data from being cached

Copyright © 2005 Altera Corporation


77
Software Run & Debug

Copyright © 2005 Altera Corporation


Software Run and Debug
 Nios II Run
 Nios II IDE JTAG Debugger
 Nios II ISS
 Nios II Console
 Third Party tools

Copyright © 2005 Altera Corporation


79
Running Code On A Target
 Nios II IDE can be used to download code to target board

Copyright © 2005 Altera Corporation


80
Running Code On A Target
 Download messages, stdout and stdin appear in console
window

Copyright © 2005 Altera Corporation


81
Nios II IDE Run Options
 Nios II IDE > Run > Run…

Copyright © 2005 Altera Corporation


82
System ID Peripheral Revisited
 When downloading code to a target, Nios II IDE computes
expected System ID peripheral values from PTF file
 If computed ID values do not match System ID variables stored on
the target board then an error is flagged
 Generally, to fix this you should recompile your hardware

Copyright © 2005 Altera Corporation


83
Nios II IDE JTAG Debugger
 Requirements
 Must have JTAG
Debug Core enabled
in CPU

Copyright © 2005 Altera Corporation


84
Nios II IDE Debug Perspective

Basic Debug
• Run Controls
• Stack View
• Active Debug
Sessions

Double-click to
add breakpoints

Memory View
•Variables
•Registers
•Signals

Copyright © 2005 Altera Corporation


85
Nios II IDE Debugger

Step Return
Step Over
Step Into
Step with Filters

Disconnect
Terminate
Suspend
Resume

Run last Configuration


Debug last Configuration

Copyright © 2005 Altera Corporation


86
Nios II IDE Debugger
 Standard debug
windows
 memory
 registers
 Variables
 breakpoints
 expressions
 signals

Copyright © 2005 Altera Corporation


87
Nios II IDE – Multi-Processor Launch
 Mechanism to Quickly Launch Multiple Debuggers and
Connect Them to Multiple Nios II Processors
 Run > Debug… > Nios II Multiprocessor Collection

Accelerates Debug Cycle for Multi-Processor Systems


Copyright © 2005 Altera Corporation
88
Nios II IDE: Debugger
 Debug each CPU by selecting it’s program thread

Copyright © 2005 Altera Corporation


89
Nios II Instruction Set Simulator
 Instruction Set Simulators are software
models of an Instruction Set Architecture
 Generally used to debug code if a target board
is unavailable.
 Provides limited models of a few hardware
peripherals.
 Timer
 UART
 Memory (flash, SDRAM, on-chip, etc…)

Copyright © 2005 Altera Corporation


90
Nios II Instruction Set Simulator
 Launch an ISS Debug session from the
Run Menu

Copyright © 2005 Altera Corporation


91
Nios II Instruction Set Simulator
 Targets .elf file to ISS and opens debugger
 Application can then be debugged as normal

Copyright © 2005 Altera Corporation


92
Customizing Views in the IDE GUI
 You can turn windows on or off in either the
Run or Debug Perspective

Copyright © 2005 Altera Corporation


93
Nios II SDK Shell
 SDK shell is still provided with Nios II
 Used to support legacy SDK flow (eg.. n2b, n2c) as
well as other general commands
 Can launch terminal to interface to JTAG UART’s
 nios2-terminal
 And compile code
 nios2-elf-gcc

Copyright © 2005 Altera Corporation


94
Nios II / FS2 Console
 Command line debugger

Copyright © 2005 Altera Corporation


95
Nios II Console Launch
 FS2 Console Launches then minimizes

Copyright © 2005 Altera Corporation


96
Nios II Console
 Allows for hardware
breakpoints and trace data
 2 HWBP’s and 16 Frames of On-
Chip Trace Included
 Displays C Source,
Assembly, Mixed

Copyright © 2005 Altera Corporation


97
Nios II Debug Solutions
Product Provider Description Features

* Nios II IDE Altera IDE / Debugger JTAG Target Connection, H/W


Breakpoints, Data Triggers,
On-Chip Trace, FS2 Trace
Probe

** code|lab ATI Mentor IDE / Debugger JTAG Target Connection, H/W


Breakpoints, Data Triggers,
On-Chip Trace , FS2 Trace
Probe

Watchpoint Sophia Debugger Supports FS2 ISA-Nios/T


Systems

ISA-Nios/T First Silicon JTAG Trace External Trace Capture,


Solution Probe Timestamp, Complex Data
(FS2) Triggers

* Included in Nios II Development Kits


** Evaluation Version Included in Nios II Development Kits
Copyright © 2005 Altera Corporation
98
Upgrades from FS2
(see www.fs2.com for details)
Feature Nios II IDE FS2 S/W FS2 H/W
Upgrade Upgrade
Hardware Execution 2 4 4
Breakpoints
Data Triggers 2 4 4

Trace (PC) On-Chip On-Chip Off-Chip


16 Frames 128 Frames 128K Frames
Trace (Load / Store) No Yes Yes
Trace (Timestamp) No No Yes
Target Connection Altera Altera FS2 Black Box
USB/B Blaster USB/B Blaster (USB, Ethernet)
Cost Included See FS2 See FS2

Copyright © 2005 Altera Corporation


99
FS2 System Analyzer Upgrade
 ISA-Nios II System Analyzer
 10-pin JTAG Target Connection
 Unlimited Software Breakpoints
 2 Hardware Breakpoints (upgradable to 4)
 Supports On-Chip Trace (upgrades available for
deeper trace)

 ISA-Nios II/T System Analyzer


 38-pin Mictor Connection
 Blackbox probe
 Supports 128k frames Off-Chip Trace
in addition to Unlimited On-Chip Trace

Copyright © 2005 Altera Corporation


100
Lab 2
Software Flow
45 mins

Copyright © 2005 Altera Corporation


RTL Simulation

Copyright © 2005 Altera Corporation


RTL Simulation
 Nios II SOPC Builder Automatically Creates
Simulation Models Plus:
 ModelSim Project
 Testbench
 Simulation Scripts

Set Simulation Option


Copyright © 2005 Altera Corporation
103
Simulation TestBench
Ethernet Dev board Dev board
Compact FLASH SDRAM
MAC/PHY SRAM FLASH

Nios II Processor
Compact
Address (32) Tri-State Tri-State SDRAM
Flash
Bridge Bridge Controller
Avalon Switch Fabric
Read PIOs
32-Bit
Write
Nios II
Processor Data In (32)
On Chip On Chip Custom

User Device
Data Out (32)
ROM) RAM Instruction
UART

IRQ
User User
IRQ #(6) Defined Defined
Peripheral Interface

User Device
User Included
Clock Reset Peripheral
Not Included
Copyright © 2005 Altera Corporation
104
User Additions to Nios II TestBench

 SOPC Builder creates


testbench embedded in
top level file eg NiosII.v

 Sections within this file


are reserved to add user
files and code

 These sections are


preserved if the SOPC
builder is used to re-
generate the Nios II
system

Copyright © 2005 Altera Corporation


105
Running an RTL Simulation
 Modify Nios II IDE System Library For Simulation:
 Specify Program Memory
 Set Up As Simulation Only

Copyright © 2005 Altera Corporation


106
Running an RTL Simulation

 Checking the “ModelSim only, no hardware support”


button:
 Leaves caches uninitialized
 Does not initialize the .bss section

 As a result simulation speeds are increased

 You can still simulate with this button unchecked but


simulation time will be much longer

Copyright © 2005 Altera Corporation


107
Running an RTL Simulation
 Launch ModelSim from Nios II IDE:
 Highlight Software Project In C/C++ Projects panel
 Right click
 Run As Nios II ModelSim

Copyright © 2005 Altera Corporation


108
Running an RTL Simulation

Copyright © 2005 Altera Corporation


109
Simulation Scripts
 When ModelSim is started from the Nios II IDE a set-up
script is run automatically which creates aliases for
simulation scripts
 The set up script can also be run independently as follows:
 do setup_sim.do
 Simulation Scripts
 s Compiles HDL source code and loads design
 c Rebuilds memory contents based on software code
 Includes changes since Nios II generation
 w Opens Wave window with “useful” signals
 l Opens List window with “useful” signals
 h Displays help message describing scripts

Copyright © 2005 Altera Corporation


110
Memory Device Simulation Models
 Applies To The Following Nios II Memories
 On Chip Memory (ROM or RAM)
 SRAM
 Flash Memory and now SDRAM

Include SDRAM Model


for Simulation

Copyright © 2005 Altera Corporation


111
Memory Device Simulation Models
 You can no longer initialize memories in the
SOPC Builder.
 Memory init file are created by the Nios II IDE.

 ext_ram will be initialized for simulation


with the ext_ram.dat file
 You must compile your software in the
Nios II IDE to generate this file
 Onchip memories are initialized with
<component_name>.hex
 Onchip memory init files can be created
by an editor or by the Nios II IDE

Copyright © 2005 Altera Corporation


112
UART Simulation
 Text is transmitted to
UART during simulation
 Creates and saves txt file
containing UART tx
stream
 Creates window to input
text at simulation run time

Note: ModelSim Options are mutually exclusive

Copyright © 2005 Altera Corporation


113
UART Simulation
 Input is interactive or predefined
 Output is shown and saved independently for
multiple UARTs

Copyright © 2005 Altera Corporation


114
JTAG_UART Simulation New

 Text is transmitted to the


new JTAG_UART
peripheral during
simulation
 Creates and saves txt file
containing UART tx
stream
 Creates window to input
text at simulation run time

Note: ModelSim Options are mutually exclusive

Copyright © 2005 Altera Corporation


115
Wave Window
 Adds UART and CPU signals by default

Copyright © 2005 Altera Corporation


116
SignalTap™ II Logic Analyzer
 Up to 200 MHz
 Multi-Analyzer Support
 1,024 Channels
 128K Samples
 10 Trigger Levels
 No Probes!
 Can be used
simultaneously with the
Nios II IDE debugger and
the FS2 console!

Capture the state of internal nodes


In-system, at full system speeds
Copyright © 2005 Altera Corporation
117
SignalTap™ II Logic Analyzer

Copyright © 2005 Altera Corporation


118
Lab 3
RTL Simulation
30 mins

Copyright © 2005 Altera Corporation


Avalon Switch Fabric

Copyright © 2005 Altera Corporation


Avalon Switch Fabric
 Proprietary interconnect specification used with Nios II

 Principal design goals


 Low resource utilization for
bus logic
Nios II Processor
 Simplicity Address (32)
Switch
PIO
 Synchronous operation 32-Bit
Read

Avalon Switch Fabric


Write
Nios II LED PIO
Processor Data In (32)
 Transfer Types Data Out (32)

 Slave Transfers 7-Segment


LED PIO
 Master Transfers IRQ
 Streaming Transfers IRQ #(6)
PIO-32
 Latency-Aware Transfers
User-
 Burst Transfers ROM
(with Monitor)
UART Timer Defined
Interface

Copyright © 2005 Altera Corporation


121
Avalon Switch Fabric
 Custom-Generated for Peripherals
 Contingencies are on a Per-Peripheral Basis
 System is Not Burdened by Bus Complexity
 SOPC Builder Automatically Generates
 Arbitration
 Address Decoding
 Data Path Multiplexing
 Bus Sizing
 Wait-State Generation
 Interrupts

Copyright © 2005 Altera Corporation


122
Avalon Master Ports
 Initiate Transfers with Avalon Switch Fabric
 Transfer Types
 Fundamental Read
 Fundamental Write
 All Avalon Masters Must Honor a waitrequest
signal
 Transfer Properties
 Latency
 Streaming
 Burst

Copyright © 2005 Altera Corporation


123
Avalon Slave Ports
 Respond to Transfer Requests from Avalon
Switch Fabric
 Transfer Types
 Fundamental Read
 Fundamental Write
 Transfer Properties
 Wait States
 Latency
 Streaming
 Burst

Copyright © 2005 Altera Corporation


124
Slave Read Transfer
 0 Setup
Cycles
 0 Wait Cycles

A B C D E
clk

address,be_n address, be_n


readn
chipselect
readdata readdata

Copyright © 2005 Altera Corporation


125
Slave Read Transfer with Wait States
 1 Setup Cycle
 1 Wait Cycle

A B C D E F G H
clk

address,be_n address, be_n


chipselect

Tsu

readn

readdata readdata

Copyright © 2005 Altera Corporation


126
Slave Write Transfer
 0 Setup
Cycles
 0 Wait Cycles
 0 Hold Cycles

A B C D
clk
address,be_n address, be_n
writedata writedata

writen

chipselect

Copyright © 2005 Altera Corporation


127
Slave Write Transfer with Wait States
 1 Setup Cycle
 0 Wait Cycles
 1 Hold Cycle

A B C D E F G
clk
address,be_n address, be_n
writedata writedata
writen
chipselect

Copyright © 2005 Altera Corporation


128
Multiple Clock Domains Supported

Master Master
Master Clock Domain 1
Clock Domain 2
Clock Domain 1

Avalon Switch Fabric

CDX
CDX
Arbiter
Arbiter

Avalon Switch Fabric

Slave Slave Slave


Clock Domain 2 Clock Domain 2 Clock Domain 2 Slave
Clock Domain 2

CDX = Clock Domain Crossing Logic (inserted automatically by SOPC Builder)

Copyright © 2005 Altera Corporation


129
Multi-Clock Domain Support

Master Master Master Master


Clock Clock Clock Clock
Domain 2 Domain 1 Domain 1 Domain 1

CDX CDX Arbiter


Arbiter

Arbiter
Arbiter CDX

Avalon Switch Fabric Avalon Switch Fabric

Slave Slave
Clock Domain 3 Clock Domain 2

CDX = Clock Domain Crossing Logic

Copyright © 2005 Altera Corporation


130
User-Defined Custom Peripherals
 What if I need to add a peripheral not included with the
Nios II system?
 user wants to add own peripheral to perform some kind of
proprietary function or perhaps a standard function that is
not yet included as part of the Nios kit
 Expand or accelerate system capabilities

 We are now going learn how to connect our own design


directly to the Nios II system via Avalon
 As many peripherals contain registers we could also have
chosen to connect to a PIO rather than directly to the bus

Copyright © 2005 Altera Corporation


131
Creating Avalon Slave
 No Need to Worry about Bus Interface
 Implement Only Signals Needed
 Peripherals Adapted to by Avalon Switch Fabric
Avalon Switch Fabric
 Timing Handled Automatically
Register File
 Fabric Created for You
 Arbiters Generated for You User
Logic

Concentrate Effort on
Peripheral Functionality!
Copyright © 2005 Altera Corporation
132
New Component Editor

Copyright © 2005 Altera Corporation


133
Creates Interface
 Connect to Existing HDL or board component
 Map into Nios II Memory Space
 Can be “Inside” or “Outside” Nios II System

I/O I/O
Nios II Nios II
CPU I/O CPU I/O

Avalon
Avalon

I/O I/O

I/O I/O

Interface External Internal


to User User User
Nios II System Nios II System
Logic Peripheral Peripheral
Module Module

Copyright © 2005 Altera Corporation


134
Create External Component Interface
 To communicate with AMD29LV065AD CFI Flash Chip

off-chip peripherals
 Base interface type
on data sheet

Copyright © 2005 Altera Corporation


135
Or Add HDL Files
 For peripheral that has been encoded for FPGA

Copyright © 2005 Altera Corporation


136
Tri-State Peripherals
 Require Tri-State Bridge
 Available as an SOPC Builder component

Interface to
User Logic
Off Chip

Tri-State
Avalon

Bridge
Nios II Peripheral
Processor

FPGA

 Tri-State peripheral is defined by the presence of


a bi-direction data port
 Off-chip peripherals do not have to be tri-state

Copyright © 2005 Altera Corporation


137
Define Component Signals

Automatically populates port


table from design files
Enter port type here
Can also define ports manually

Copyright © 2005 Altera Corporation


138
Define Interface for Each Signal Type

Choose interface type


Register Slave uses native
alignment, Memory Slave uses
dynamic alignment
Control Read and Write Timing
Add wait and hold states View
waveforms

Copyright © 2005 Altera Corporation


139
Address Alignment – Narrow Slave
Peripheral Registers
32-Bit 32
Nios II Base aa

Avalon
Processor Base + 0x1 bb
8 Base + 0x2 cc
8 Bit
Peripheral Base + 0x3 dd
Base + 0x4 ee

 Dynamic Address Alignment (set as Memory Slave)


 LD from Base + 0x0: dd cc bb aa
 LD from Base + 0x4: uu uu uu ee

 Native Address Alignment (set as Avalon Register Slave)


 LD from Base + 0x0: uu uu uu aa
 LD from Base + 0x4: uu uu uu bb
 LD from Base + 0x8: uu uu uu cc
Copyright © 2005 Altera Corporation
140
Address Alignment – Narrow Master
32-Bit 32 Memory Contents
Nios II
Base 77 66 55 44 33 22 11 00

Avalon
Processor
Base + 0x8
64
64 Bit
Base + 0x16 ff ee dd cc bb aa 99 88
Memory
?? ?? ?? ?? ?? ?? ?? ??

 Dynamic Address Alignment


 LD from Base + 0x0: 33 22 11 00
 LD from Base + 0x4: 77 66 55 44
 LD from Base + 0x8: bb aa 99 88
 Native Address Alignment
 LD from Base + 0x0: 33 22 11 00
 LD from Base + 0x4: bb aa 99 88
 LD from Base + 0x8: ?? ?? ?? ??
 High bytes are unobtainable – warning issued
Copyright © 2005 Altera Corporation
141
Add Software Files
 ie. Header files and drivers

Copyright © 2005 Altera Corporation


142
Add Software Files
 Header file and drivers can also be added directly to
Application Project

Copyright © 2005 Altera Corporation


143
Create Component Wizard
 Publish and create a wizard for your component

 Fill in fields
 Add component to
SOPC Builder portfolio
 Can add parameterizing
capability to component

Copyright © 2005 Altera Corporation


144
Add Component to SOPC System
 Default location is the User Logic folder

Copyright © 2005 Altera Corporation


145
Intel PXA255 Example

Copyright © 2005 Altera Corporation


146
VLIO as an Avalon Master Port VLIO
 Intel PXA255 Variable Latency I/O (VLIO) Uses a Bi-Directional Data Path, RDY Signal to
Add Wait States
 Interface Separates DATA into Read Data & Write Data Paths

Copyright © 2005 Altera Corporation


147
Relevant Verilog Code to Relevant Verilog
Code to Implement

Copyright © 2005 Altera Corporation


148
Lab 4
Adding A User Peripheral
30 mins

Copyright © 2005 Altera Corporation


Custom Instructions

Copyright © 2005 Altera Corporation


Custom Instructions
 Add custom functionality to the Nios II design
 To take full advantage of the flexibility of FPGA

 Dramatically Boost Processing Performance


 With no Increase in fMAX required

 Application Examples
 Data Stream Processing (eg. Network Applications)
 Application Specific Processing (eg. MP3 Audio Decode)
 Software Inner Loop Optimization

Copyright © 2005 Altera Corporation


151
Custom Instructions
 Augment Nios II Instruction Set
 Mux User Logic Into ALU Path of Processor Pipeline

Copyright © 2005 Altera Corporation


152
Several Levels of Customization
Optional Interface to FIFO, Memory, Other Logic

dataa
result
datab 32 Combinatorial
32
32
clk
clk_en
Multi-Cycle done
reset
start

n
Extended
8
a readra
b 5 Internal readrb
5 Register File writerc
c
5
Copyright © 2005 Altera Corporation
153
Custom Instructions
 Integrated Into Nios II Development Tools
 SOPC Builder design tool handles op-code assignment
 Generates C and assembly-language macros

 Similar to Nios Custom Instructions Except


 Up to 256 different custom instructions possible
 Multi-cycle instructions can have variable duration
 Parameterization of custom instructions has changed

Copyright © 2005 Altera Corporation


154
Custom Instructions Tab
 Enabled from the Custom Instructions tab in the
Nios II CPU settings in SOPC Builder

Copyright © 2005 Altera Corporation


155
Custom Instructions Tab
 Import logic for the custom instruction
 Custom Instruction module can be of following
formats:
 VHDL
 Verilog HDL
 EDIF
 Quartus Block Diagram (.bdf)

Copyright © 2005 Altera Corporation


156
Combinatorial Custom Instructions

 Port list
 All Custom Instruction Modules need these ports
 Port names must match exactly

Copyright © 2005 Altera Corporation


157
Multi-Cycle Custom Instructions

 Port list for Multi-Cycle Custom Instructions


 Must have all of these ports with exact names

Copyright © 2005 Altera Corporation


158
Extended Custom Instructions
 Uses n[7..0] port to select an operation to perform.

Copyright © 2005 Altera Corporation


159
Register File Custom Instructions
 Custom instructions can select inputs from internal
registers or dataa, datab ports
 Custom instructions can write results to an internal
register file

dataa[31..0]
result[31..0]
Custom
reada Logic writec

c[4..0]
a[4..0]

Copyright © 2005 Altera Corporation


160
Software Interface - C
 NIOS II IDE generates macros automatically during build process

 Macros defined in system.h file


#define ALT_CI_<your instruction_name>(instruction arguments)

 Example of user C-code that references Bitswap custom instruction:


#include "system.h"
int main (void)
{
int a = 0x12345678;
int a_swap = 0;

a_swap = ALT_CI_BSWAP(a);
return 0;
}

Copyright © 2005 Altera Corporation


161
Assembly Language Interface
 Assembler syntax for the custom instruction:
custom N, rC, rA, rB

Custom Destination Operand 1 Operand 2


instruction register
opcode for result
number

 Two Examples:
r = Nios II processor
custom 0, r6, r7, r8
register
custom 3, c1, r2, c4
c = Custom instruction
internal register

Copyright © 2005 Altera Corporation


162
Why Custom Instruction?
 Reduce Complex Sequence of Instructions to One Instruction
 Example: Floating Point Multiply
float
float a,
a, b,
b, result_slow,
result_slow, result_fast;
result_fast;

result_slow
result_slow == aa ** b;
b; /*
/* Takes
Takes 266
266 clock
clock cycles
cycles */*/
result_fast
result_fast == ALT_CI_fpmult(a,b);
ALT_CI_fpmult(a,b); /*
/* Takes
Takes 66 clock
clock cycles*/
cycles*/

Significantly
SignificantlyFaster!
Faster!
 Typical Flow
 Profile Code
 Identify Critical Inner Loop
 Create Custom Instruction Logic
 Replace One or All Instructions in Inner Loop
 Import Custom Instruction Logic into Design
 Call Custom Instruction from C or Assembly

Copyright © 2005 Altera Corporation


163
Custom Instruction vs Peripheral
 Custom Instruction can execute in a single cycle
 No overhead for call to custom Hardware
L0 Custom L0
L1 Instruction

 Access to same hardware as peripheral takes


multiple cycles
 Write DataA, then write DataB, and finally read Result
Peripheral memory map

0x408
Result
DataB
0x404
DataA
0x400

L0 Custom L0
L1 Peripheral

Copyright © 2005 Altera Corporation


164
Multi-Cycle Custom Instructions
 Processor stalls while awaiting result
 Clock cycles = 3 DataA DataB

Custom Instruction
Nios Clock Cycles

custom REG

---

---
REG
Next Instr

Result

Copyright © 2005 Altera Corporation


165
Pipelined Custom Instructions
 Result not always needed for each input
 Clock Cycles = 1 DataA DataB
 Route start sig to reg clk_en

Custom Instruction
custom REG
Nios Clock Cycles

custom

custom
REG
custom

custom

Next Instr
Result

Copyright © 2005 Altera Corporation


166
Accelerating CRC
 Implementing the shift and XOR for each
bit takes many clock cycles ~50
 Software algorithms tend to use look up
tables to pre-compute each byte
 Parallel Hardware is fastest
in(15) in(14) in(0)
xor/shift

xor/shift

xor/shift
reg

Copyright © 2005 Altera Corporation


167
CRC Custom Instruction
 CRC16-CCITT needs to be preset to 0xFFFF at
the start of each computation
 Can use the Data B input to select between run
and load
 Use of prefix would waste a clock cycle

////reset
resetcrc
crc CRC
Control
Custom Instruction
ALT_CI_CRC(0xFFFF,1);
ALT_CI_CRC(0xFFFF,1);
DataA(31-0) Data in
////run crc
run crc CRC Reg Result(15-0)
ALT_CI_CRC(word,0);
ALT_CI_CRC(word,0);
DataB(0) Init / nRun

Copyright © 2005 Altera Corporation


168
Multi-Masters and Direct
Memory Access (DMA)

Copyright © 2005 Altera Corporation


Traditional Multi-Masters
 Direct Memory Access (DMA)
 Processor Waits For Bus During DMA
Masters System CPU 100Base-T
(Master 1) (Master 2)

System
Arbiter Determines
Control Bottleneck DMA Bus
DMA Arbiter
Arbitor Which Master Has
direction Access To Shared
Bus
System Bus

I/O I/O
Program Data
1 2
Slaves Memory Memory

Copyright © 2005 Altera Corporation


170
Avalon Simultaneous Multi-Mastering Bus
 Has Benefits of a Switch Fabric and Slave-Side Arbitration
 Shared Bus & Share Arbiter are No Longer the Bottleneck
 Multiple Master Transactions Can Operate Simultaneously
 As long as they don’t access the same slave in the same bus bycle
 I/O Devices Can be Grouped Based on Bandwidth Requirement
 Trade-Off
 Hardware Resource Usage Increases Uses Fairness
automatically
generated by
Arbitration
SOPC Builder

Masters CPU 0 DMA CPU 1

System
Switch
Fabric
Arbiter Arbiter

Program Data Display Data Custom Program


Slaves I/O
Memory 0 Memory 0 Control Memory 1 Function Memory 1

Copyright © 2005 Altera Corporation


171
DMA Peripheral
 Provides Bus Master Capability to Any Nios II
Peripheral
 FIFO Depth = 2
DMA Peripheral

Master Port FIFO Master Port


1 2

Start Addr Start Addr

# Bytes # Bytes

Addr Incr Addr Incr

Direction

Control Port

Copyright © 2005 Altera Corporation


172
Data Flow with DMA Peripheral
Master 1 Master 2
SPI
(Nios II CPU) DMA
I D

Avalon Avalon

Arbiter

I/O I/O
1 2 Data
Program
Memory
Memory
1

Copyright © 2005 Altera Corporation


173
Accelerate Software Execution
 Use custom hardware peripheral with DMA
 Processor & Accelerator Run Concurrently
 More Work Per Clock
 Lower fMAX, Power, Cost

DMA

DMA
Processor Accelerator

Avalon
Switch
Fabric Arbiter
Arbiter Arbiter
Arbiter

Program Data Data


Memory Memory Memory

Copyright © 2005 Altera Corporation


174
Accelerate Software Execution
 Example: CRC Algorithm (64 Kbytes)

25,000,000

20,000,000
Clock Cycles

15,000,000

10,000,000 27 530
Times Times
Faster Faster
5,000,000

0
Software Only Custom Hardware
Instruction Accelerator

Copyright © 2005 Altera Corporation


175
Custom Streaming Slave Peripherals
 For using DMA with other slow peripherals
 Example: UART
 Adds up to three outputs to Avalon Slave
 dataavailable
 readyfordata adress

control

 endofpacket Custom writedata

Avalon
Streaming readdata

Slave
dataavailable
Peripheral
Readyfordata

endofpacket

Copyright © 2005 Altera Corporation


176
Streaming Slave Peripheral Signals
 dataavailable
 Indicates that the peripheral has data available to be read
by DMA or other master
 ie, there is data in the rx buffer or register
 readyfordata
 Indicates that the peripheral is able to receive data written
by DMA or other master
 Ie. the tx buffer or register is not full
 endofpacket
 Usage not defined
 DMA can be optionally set to end transfer

Copyright © 2005 Altera Corporation


177
Custom Master Peripherals
 Can integrate DMA function
 Eg. VGA that takes data from memory directly
 Simpler than Slave peripherals
 Assert outputs until waitrequest is low
 Transaction are between Master and Avalon,
not Slave
address

control
Custom

Avalon
writedata
Master
Peripheral readdata

waitrequest

Copyright © 2005 Altera Corporation


178
Master Read Transfer
 Assert addr, be, read
 Wait for waitrequest = ‘0’
 Read in Data
 End of transfer

Copyright © 2005 Altera Corporation


179
Master Write Transfer
 Assert addr, be, read
 Assert Write Data
 Wait for waitrequest = ‘0’
 End of transfer

Copyright © 2005 Altera Corporation


180
Avalon Master-Slave Connections
 View => Show Master Connections
 Observe and configure Avalon connections

Copyright © 2005 Altera Corporation


181
Master Arbitration Scheme
 Nios II Multi-Master Avalon Switch Fabric Utilises
Fairness Arbitration Scheme
 Each Master/Slave pair is assign an integer “shares”
 Upon conflict Master with most shares takes bus until all
shares are used
 Master with least shares then takes bus until all shares are
used
 Assuming all Masters continuously request the bus, they will
each be granted the bus for a percentage of time equal to the
percentage of total master shares that they own
CPU
7 Shares

SPI DMA
1 share
PCI DMA
2 shares
Copyright © 2005 Altera Corporation
182
Set Arbitration Priority
 View => Show Arbitration Priorities

Copyright © 2005 Altera Corporation


183
Avalon Arbitration Behavior

Master A Shares = 4
Master A Master B
Master B Shares = 2

Arbiter

Slave

Arbiter (continuous accesses)

Master A

Master B

Copyright © 2005 Altera Corporation


184
Lab 5
Custom Instruction and
(optional) DMA Controller
45 mins
Copyright © 2005 Altera Corporation
Working with the
Development Board

Copyright © 2005 Altera Corporation


Ensure Unused I/O are Tri-State
 The FPGA may connect to components on the board not
used by your design
 There is a connection between FPGA and MAX device to
force reconfiguration
 Active low, pulled high
 Assignments -> Device …
 For Stratix devices, be sure to set Dual Purpose pins to
“Use as Regular IO”

Copyright © 2005 Altera Corporation


187
Clock Distribution
FPGA Nios II SDRAM

Zero Skew
Buffer
Zero Skew
Buffer PLL
CLK in
(50 MHz)

 PLL required to meet SDRAM I/O timing


 Introduces -60° phase shift relative to Nios II
 CLK in is socket crystal or external input
 Resistor changes required for external
 See board schematic and ref design
Copyright © 2005 Altera Corporation
188
Hardware Configuration Process
8 MB Flash
 Flash Configuration Safe FPGA Data

 Two FPGA images 0x700000


Image
Stratix
User FPGA
 Safe Image
Image
0x600000
 User Image

Address
 MAX® EPM7128 Configures FPGA from MAX

Flash
 Upon power up or press of Reset Config
 MAX Device Loads User Image into FPGA
 If This Fails MAX Device Loads Safe Image
 Failure includes no user image present
 Upon press of Safe Config
 MAX Device Loads Safe Image into FPGA
Copyright © 2005 Altera Corporation
189
Flash Memory Configuration
8 MB Flash
Safe FPGA
Image & S/W
0x700000
User FPGA Data
Image
0x600000
Stratix

0x500000

Address
0x400000

SRAM
0x300000 User
Software
0x200000

0x100000

0x000000
Copyright © 2005 Altera Corporation
190
Configuration of FPGA From Flash
0x1000000

Data
0xE00000

0xC00000
8 MB RAM Stratix

0xA00000
Nios II

0x800000

Safe FPGA Image


& S/W
0x600000
User FPGA
Controller
Image
8 MB Flash 0x400000
Application
Application
Code
Code
0x200000
Start-up Code
Boot Copier
0x000000
Copyright © 2005 Altera Corporation
191
Loading RAM
0x1000000

Data
0xE00000 Dynamic
Memory
0xC00000
8 MB RAM Stratix
Application
0xA00000 Code
Nios II
Start-up Code
0x800000

Safe FPGA Image


& S/W
0x600000
User FPGA
Image
8 MB Flash 0x400000
Application
Code
0x200000
Start-up Code
Boot Copier
0x000000
Copyright © 2005 Altera Corporation
192
Boot Copier
 Use Flash for Program Data
Storage
User Stratix
 Running from Flash is slow Software

 Nios II IDE Automatically

Address
Prepends Boot Copier to
Program Code SRAM
 if Reset Address is in Flash and 8 MB Flash
Program Memory is in RAM

 For Custom Boards:


Boot Copier
(see again “Nios II Flash my_sw.flash
Programmer User Guide”) my_sw.elf
 Must create your own flash
programmer design to transport data
to the flash on your board

Copyright © 2005 Altera Corporation


193
Nios II Flash Programmer
 Downloads flash content to CFI flash device
 Communication is over JTAG interface
 Can also download to any Altera EPCS Serial Configuration
Device connected to FPGA
 Two-step process:
 Send Flash Programmer Design
 Send Flash Content

Flash Content

Copyright © 2005 Altera Corporation


194
Nios II Flash Programmer
 Flash Programmer Design contains
 Nios II CPU
 JTAG UART
 Active serial memory interface
 Tri-state bridge
 CFI-compatible flash interface
 System ID peripheral on-chip memory for firmware and buffers

 Flash Content can include:


 FPGA hardware configuration image
 Software content
 Arbitrary content

Copyright © 2005 Altera Corporation


195
Nios II Flash Programmer
 Can program Flash from Nios II IDE or command line
 Nios II IDE is recommended method

Copyright © 2005 Altera Corporation


196
Nios II Flash Programmer
 Command Line Utilities
 elf2flash

 sof2flash

 Bin2flash

 elf2hex

 nios2-flash-programmer

(see “Nios II Flash Programmer User Guide” for details)

Copyright © 2005 Altera Corporation


197
Instantiating Flash in Target System
 Must set target board to appropriate development kit
 Need CFI (Common Flash Interface) Flash Memory
 EPCS Serial Flash Controller req’d if booting from EPCS device

Copyright © 2005 Altera Corporation


198
Flash Programmer Design
 What if I Have a Custom Board?
 Import board settings into the SOPC Builder using
mk_target_board script
 Specify flash devices and designator numbers
 Clock frequency
 Device family

 Create flash programming design in SOPC Builder


based on .PTF generated from above script
 Generate .SOF file for flash design
 See Nios II Flash Programmer User Guide for details

Copyright © 2005 Altera Corporation


199
What If Safe Flash Image Overwritten?
 Open Nios II SDK Shell
 Start > Programs > Altera > Nios II Development Kit
<installed version> > Nios II SDKShell
 Change to factory-recovery directory for your
development kit
 cd examples/factory_recovery/niosII_cyclone_1c20
 Run flash-restoration script
 ./restore_my_flash
 Follow the script’s instructions

Copyright © 2005 Altera Corporation


200
Lab 6
The Flash Programmer
10 mins

Copyright © 2005 Altera Corporation


Thank You

Copyright © 2005 Altera Corporation

S-ar putea să vă placă și