niosii sopcbuilder class 011804
TRANSCRIPT
Copyright © 2005 Altera Corporation
Designing with Nios II and SOPC BuilderDesigning with Nios II and SOPC Builder
2Copyright © 2005 Altera Corporation
AgendaAgenda
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
Nios II Hardware DevelopmentNios II Hardware Development
4Copyright © 2005 Altera Corporation
What is Nios II?What is Nios II?
Altera’s Second Generation Soft-Core 32 Bit RISC Microprocessor Developed Internally By Altera Harvard Architecture Royalty-Free
FPGA
- Nios II Plus All Peripherals Written In HDL
- Can Be Targeted For All Altera FPGAs
- Synthesis Using Quartus II Integrated Synthesis
Av
alo
n S
wit
ch
Fa
bri
c UART
GPIO
Timer
SPI
SDRAMController
On-ChipROM
On-ChipRAM
Nios IICPUDebug
Cac
he
5Copyright © 2005 Altera Corporation
Problem: Reduce Cost, Complexity & PowerProblem: Reduce Cost, Complexity & Power
Flash
SDRAM
CPU
DSP
I/O
I/O
I/O FPGA
I/O I/O I/O
CPU DSP
Solution: Replace External Devices with Programmable Logic
FPGA
6Copyright © 2005 Altera Corporation
Problem: Reduce Cost, Complexity & PowerProblem: Reduce Cost, Complexity & Power
Flash
SDRAM
Solution: Replace External Devices with Programmable Logic
CPU is a Critical Control Function Required for System-Level Integration
System On A Programmable Chip (SOPC)System On A Programmable Chip (SOPC)
FPGA
7Copyright © 2005 Altera Corporation
FPGA Hardware Design Flow with Quartus II and SOPC BuilderFPGA Hardware Design Flow with Quartus II and SOPC Builder
• Create FPGA project in Quartus IICreate FPGA project in Quartus II
• Build embedded sub-system in SOPC BuilderBuild embedded sub-system in SOPC Builder
• Integrate sub-system in Quartus IIIntegrate sub-system in Quartus II
• Compile and generate a programming fileCompile and generate a programming file
.sof / .pof file.sof / .pof file
8Copyright © 2005 Altera Corporation
Development Kits, Stratix & Cyclone EditionDevelopment Kits, Stratix & Cyclone Edition
8 MB Flash
Configuration Controller (MAX 7128AE)
10/100 Ethernet MAC/PHY & RJ-45 Connector
Compact Flash(Connector Mounted on Back)
16 MB SDRAM
Power Connector
Download /JTAG Debug Connector
Serial RS-232 Connectors
1MB SRAM
Buttons LEDs 7 Segment
Expansion Prototype Connectors(40 I/O pins each)
Configuration Control
CPU Reset
9Copyright © 2005 Altera Corporation
32-BitNios II
ProcessorROM
(with Monitor)
On-Chip Off-Chip
Address (32)
Read
Write
Data In (32)
Data Out (32)
IRQ
IRQ #(6)
Avalo
n S
witch
Fab
ric
Nios II Processor
Standard Design Block DiagramStandard Design Block Diagram
Tri-StateBridge
Le
ve
l S
hif
ter
16MB Compact FLASH
SDRAMController
8MB FLASH
1MB SRAM
Ethernet MAC/PHY
32MB SDRAM
Tri-StateBridge
Compact Flash PIOs
Button PIO7-SegmentLED PIO
LCD PIOLED PIO
General Purpose
Timer
Periodic Timer
UART
8 LEDsExpansion
Header J12
2 Digit Display
4 Momentary
buttons
Reconfig PIO
10Copyright © 2005 Altera Corporation
User-DefinedInterface
MemoryInterface
On-ChipDebug Core
Off-ChipSoftware Trace
Memory
UART n
Timer n
SPI n
GPIO n
DMA n
Avalon Switch Fabric
Instr.
Data
AddressDecoder
InterruptController
Wait StateGeneration
Data inMultiplexer
DynamicBus Sizing
AvalonMaster/SlavePort
Interfaces
MasterArbitration
Nios II System ArchitectureNios II System ArchitectureUART 0
Timer 0
SPI 0
GPIO 0
DMA 0
MemoryInterface
User-DefinedInterface
Nios IICPU
11Copyright © 2005 Altera Corporation
Nios II Block DiagramNios II Block Diagram
ProgramController
&Address
Generation Instruction
Cache
clock
reset
irq[31..0]
ControlRegistersctl0 to ctl4
ArithmeticLogic Unit
Hardware-Assisted
Debug Module
InterruptController
JTAG interface to Software Debugger
Custom Instruction
Logic
ExceptionController
InstructionMasterPort
DataCache
DataMasterPort
General PurposeRegistersr0 to r31
CustomI/O Signals
Nios II Processor Core
12Copyright © 2005 Altera Corporation
Nios II Processor ArchitectureNios 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
13Copyright © 2005 Altera Corporation
Nios II VersionsNios II VersionsNios II Processor Comes In Three ISA Compatible
Versions
Software Code is Binary Compatible
No Changes Required When CPU is Changed
FAST: Optimized for Speed
STANDARD: Balanced for Speed and Size
ECONOMY: Optimized for Size
14Copyright © 2005 Altera Corporation
Binary Compatibility / Flexible PerformanceBinary Compatibility / Flexible Performance
Nios II /fFast
Nios II /sStandard
Nios II /eEconomy
Pipeline 6 Stage 5 Stage None
H/W Multiplier & Barrel Shifter 1 Cycle 3 Cycle
EmulatedIn Software
Branch Prediction Dynamic Static None
Instruction Cache Configurable Configurable None
Data Cache Configurable None None
Logic Usage (Logic Elements)
1400 - 1800 1200 – 1400 600 – 700
CustomInstructions Up to 256
15Copyright © 2005 Altera Corporation
Hardware Multiplier AccelerationHardware 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
Hardware
Clock Cycles
(32 x 32 32)
None 250
Standard
MUL in Stratix3
Fast
MUL in Stratix1
16Copyright © 2005 Altera Corporation
LicensingLicensing
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
17Copyright © 2005 Altera Corporation
Requirements for Nios II DesignsRequirements 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
18Copyright © 2005 Altera Corporation
Nios II: Hard NumbersNios II: Hard Numbers
Nios II/f Nios II/s Nios II/e
Stratix II 200 DMIPS @ 175MHz1180 LEs1 of 8 DSP4K Icache, 2K DcacheStratix 2S10-C5
90 DMIPS @ 175MHz800 LEs
4K Icache, No DcacheStratix 2S10-C5
28 DMIPS @ 190MHz400 LEs
No Icache, No DcacheStratix 2S10-C5
Stratix 150 DMIPS @ 135MHz1800 LEs1 of 8 DSP4K Icache, 2K DcacheStratix 1S10-C5
67 DMIPS @ 135MHz1200 LEs
4K Icache, No DcacheStratix 1S10-C5
22 DMIPS @ 150MHz550 LEs
No Icache, No DcacheStratix 1S10-C5
Cyclone 100 DMIPS @ 125MHz1800 LEs
4K Icache, 1K DcacheCyclone 1C4-C6
62 DMIPS @ 125MHz1200 LEs
2K Icache, No DcacheCyclone 1C4-C6
20 DMIPS @ 140MHz550 LEs
No Icache, No DcacheCyclone 1C4-C6
* FMax Numbers Based Reference Design Running From On-Chip Memory (Nios II/f 1.15 DMIPS / MHz)
19Copyright © 2005 Altera Corporation
SOPC BuilderSOPC Builder
Altera, Partner & User Cores Processors Memory Interfaces Peripherals Bridges Hardware Accelerators Import User Logic
(ie. custom peripherals) Web-Based IP Deployment
Over 60 Cores Available
Today
– System Contents Page
20Copyright © 2005 Altera Corporation
Clock-Domain CrossingClock-Domain Crossing
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
New in4.2
21Copyright © 2005 Altera Corporation
Hardware designer selects which Nios II version to use when creating system
Nios II CPU Configured in SOPC BuilderNios II CPU Configured in SOPC Builder
22Copyright © 2005 Altera Corporation
Selecting JTAG Debug CoreSelecting JTAG Debug Core
Configuration is chosen when hardware designer selects appropriate Nios II processor core
23Copyright © 2005 Altera Corporation
SOPC BuilderSOPC Builder – More “cpu” Settings Page
24Copyright © 2005 Altera Corporation
SOPC Builder – System Generation PageSOPC Builder – System Generation Page
25Copyright © 2005 Altera Corporation
SOPC Builder Produces a .PTF FileSOPC Builder Produces a .PTF File
Text file that records SOPC Builder edits Describes Nios II System Used by software development tools
26Copyright © 2005 Altera Corporation
Integrate SOPC Builder O/P in Quartus IIIntegrate 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
27Copyright © 2005 Altera Corporation
Memory Interfaces EPCS Serial Flash
Controller On-Chip
RAM, ROM
Off-Chip SRAM CFI Flash
LCD Display
New Peripherals for Nios II New Peripherals for Nios II
System ID Peripheral Used to Ensure Hardware/
Software Version Synchronization Simple 2 read-only register
peripheral containing hardware ID tags.
Register 1 contains random number
Register 2 contains time and date when system was generated in SOPC Builder
Can be checked at runtime to ensure that the software to be downloaded matches the hardware image
28Copyright © 2005 Altera Corporation
JTAG UART Single JTAG
Connection For: Device Configuration Flash Programming Code Download Debug Target STDIO (printing)
New Peripherals for Nios II New Peripherals for Nios II
Compact Flash Interface Mass Storage Support
True IDE Mode Compact Flash Mode
Software Supports Low-Level API MicroC/OS-II File System
Support µCLinux File System
Support
Supported through www.niosforum.com
29Copyright © 2005 Altera Corporation
Project DirectoriesProject 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
Exercise 1A Basic Nios II DesignExercise 1A Basic Nios II Design
35 mins35 mins
Copyright © 2005 Altera Corporation
Nios II Software DevelopmentNios II Software Development
32Copyright © 2005 Altera Corporation
Nios II System Design FlowNios II System Design Flow
Connect Blocks
Processor Library Custom Instructions
Peripheral Library Select & Configure Peripherals, IP
IP Modules
Configure Processor
C Header files
Custom Library
Peripheral Drivers
Compiler, Linker, Debugger
Software Development
User Code
Libraries
RTOS
GNU Tools
Generate
SOPC Builder GUI
HDL Source Files
Testbench
Synthesis &Fitter
User Design
Other IP Blocks
Hardware Development
Quartus II
On-ChipDebug
Software TraceHard Breakpoints
SignalTap® II
Altera FPGA
JTAG,Serial, orEthernet
ExecutableCode
HardwareConfiguration
FileVerification
& Debug
Nios II IDENios II IDE
33Copyright © 2005 Altera Corporation
Deliverables Required to Start Deliverables Required to Start Software Development:Software Development:
• .ptf file from SOPC Builder.ptf file from SOPC Builder
(defines hardware for the Nios II IDE)(defines hardware for the Nios II IDE)
• .sof (or .pof) file from Quartus II.sof (or .pof) file from Quartus II
(used to program the FPGA on the board)(used to program the FPGA on the board)
Nios II Software Design ProcessNios II Software Design Process
ExecutableCode
C Header files
Custom Library
Peripheral Drivers
Compiler, Linker, Debugger
Software Development
User Code
Libraries
RTOS
GNU Tools
Nios II IDENios II IDE
That’s ALL you need to start That’s ALL you need to start to run with the Nios II IDEto run with the Nios II IDE
34Copyright © 2005 Altera Corporation
Nios II IDE (Integrated Development Environment)*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
35Copyright © 2005 Altera Corporation
Opening the Nios II IDEOpening the Nios II IDE
Launch the Nios II IDE from Launch the Nios II IDE from the SOPC Builder or from the SOPC Builder or from the Windows Start menuthe Windows Start menu
36Copyright © 2005 Altera Corporation
Nios II IDENios II IDE
List of Open Projects
Terminal window
File Viewer Window
(for C code, C++, and assembly*)
•Note: C++ files must have extension .cpp In-line assembly code offset by asm();
37Copyright © 2005 Altera Corporation
Nios II IDE C/C++ Projects/NavigatorNios II IDE C/C++ Projects/Navigator
Lists all open projects
Displays source files associated with project
List all open and closed projects
Allows you to drag and drop new files into existing projects
38Copyright © 2005 Altera Corporation
Creating a C/C++ ApplicationCreating a C/C++ Application
File > New > Project
39Copyright © 2005 Altera Corporation
Creating a C/C++ ApplicationCreating a C/C++ Application
Link to a System Library- Select a pre-existing library- Or create a new library
40Copyright © 2005 Altera Corporation
This Creates Two Software Projects- Application and System Library ProjectThis Creates Two Software Projects- Application and System Library Project
System Library Project
- contains system
header file, etc.
Application Project
- contains application source code
Drivers Directory
- contains all device drivers – DO NOT DELETE !
41Copyright © 2005 Altera Corporation
Application and System Library ProjectsApplication 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)
42Copyright © 2005 Altera Corporation
Other New Project OptionsOther 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
43Copyright © 2005 Altera Corporation
Importing Projects into the IDEImporting Projects into the IDE
44Copyright © 2005 Altera Corporation
Project Properties Project Properties Both Application and System Library have
Properties pages
45Copyright © 2005 Altera Corporation
System Library OptionsSystem Library OptionsSelect RTOSSpecify stdio devicesPartition the memory map
46Copyright © 2005 Altera Corporation
Software CompilationSoftware Compilation
To compile a software application, highlight your project and select Build Project from the Projects menu
47Copyright © 2005 Altera Corporation
Directory Structure After CompilationDirectory Structure After Compilation
Application Project System Library Project
48Copyright © 2005 Altera Corporation
Nios II Host Platform SupportNios 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
49Copyright © 2005 Altera Corporation
Hardware Abstraction LayerHardware 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
50Copyright © 2005 Altera Corporation
Hardware Abstraction LayerHardware 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)
51Copyright © 2005 Altera Corporation
Hardware Abstraction LayerHardware 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
52Copyright © 2005 Altera Corporation
Nios II Processor System Hardware
DeviceDriver
DeviceDriver
DeviceDriver…
Nios II HAL: Runtime LibraryNios II HAL: Runtime Library
_exit()close()closedir()fstat()getpid()gettimeofday()ioctl()isatty()kill()lseek()
open()opendirread()readdir()rewinddir()sbrk()settimeofday()stat()usleep()wait()write()
HAL API
HAL API
C Standard LibraryC Standard Library
User Program
The HAL ‘UNIX Style’ Functions are the glue between the C library and the device drivers
53Copyright © 2005 Altera Corporation
HAL File SystemHAL File System
/
/dev /mnt
/dev/jtag_uart0 /dev/lcd0 /mnt/rozipfs
/mnt/rozipfs/myfile1
/mnt/rozips/myfile21• Device names match those set in SOPC builder.• Can only access nodes, not directories.• All paths must be absolute (no current directory)
54Copyright © 2005 Altera Corporation
Familiar File/Device AccessFamiliar 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.
55Copyright © 2005 Altera Corporation
HAL System Header FileHAL System Header File
system.hsystem.h
SOPCSOPC Builder System ContentsBuilder System Contents
System Library SettingsSystem Library Settings
56Copyright © 2005 Altera Corporation
system.hsystem.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
57Copyright © 2005 Altera Corporation
system.h - examplesystem.h - example
.
.
./*
* button_pio configuration
*
*/
#define BUTTON_PIO_NAME "/dev/button_pio"
#define BUTTON_PIO_TYPE "altera_avalon_pio"
#define BUTTON_PIO_BASE 0x00920830
#define BUTTON_PIO_IRQ 2
#define BUTTON_PIO_HAS_TRI 0
#define BUTTON_PIO_HAS_OUT 0
#define BUTTON_PIO_HAS_IN 1
#define BUTTON_PIO_CAPTURE 1
#define BUTTON_PIO_EDGE_TYPE "ANY"
#define BUTTON_PIO_IRQ_TYPE "EDGE"
#define BUTTON_PIO_FREQ 50000000
/*
* system configuration
*
*/
#define ALT_SYSTEM_NAME "std_1s10ES"
#define ALT_CPU_NAME "cpu"
#define ALT_CPU_ARCHITECTURE "altera_nios2"
#define ALT_DEVICE_FAMILY "STRATIX"
#define ALTERA_NIOS_DEV_BOARD_STRATIX_1S10_ES
#define ALT_STDIN "/dev/jtag_uart"
#define ALT_STDOUT "/dev/jtag_uart"
#define ALT_STDERR "/dev/jtag_uart"
#define ALT_CPU_FREQ 50000000
#define ALT_CPP_CONSTRUCTORS
#define ALT_IRQ_BASE NULL
.
.
.
Defines system settings and peripheral configurations: Replaces excalibur.h (from Nios)
58Copyright © 2005 Altera Corporation
HAL ReferencesHAL References
Each HAL project references library routines and drivers for the components included in your Nios II system
59Copyright © 2005 Altera Corporation
Reading/Writing Hardware in NiosReading/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
60Copyright © 2005 Altera Corporation
Reading/Writing Hardware in Nios IIReading/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
REGNUM offset from base address BASE
IOWR(BASE,REGNUM,DATA)Writes DATA to register
REGNUM offset from base address BASE
REGNUM = 0REGNUM = 0
REGNUM = 1REGNUM = 1
REGNUM = 2REGNUM = 2
REGNUM = 3REGNUM = 3
REGNUM = 4REGNUM = 4
BASE+2BASE+2
BASEBASE
BASE+4BASE+4
61Copyright © 2005 Altera Corporation
Header Files for Nios II PeripheralsHeader 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)
62Copyright © 2005 Altera Corporation
Data CacheData 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.
63Copyright © 2005 Altera Corporation
Data CacheData 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
64Copyright © 2005 Altera Corporation
InterruptsInterrupts
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).
65Copyright © 2005 Altera Corporation
Write your ISR(Follow prototype)
Register your ISRUsing alt_irq_register()
alt_irq_register ( alt_u32 id, void* context,
void (*irq_handler) (void*, alt_u32));
Sample Usage:alt_irq_register ( 3, &some_data, sample_isr);
sample_isr ( void* context, alt_u32 id);
id == irq number (0 to 31)context == void pointer to data produced by or consumed by ISR.
HAL API for ISRs - Useful InfoHAL API for ISRs - Useful Info
66Copyright © 2005 Altera Corporation
HAL API for ISRs - Useful InfoHAL 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”
67Copyright © 2005 Altera Corporation
Nios II OS / RTOS SupportNios II OS / RTOS SupportProduct Provider Source
Code
Standards TCP/IP
Stack
File
System
Other
* MicroC/OS-II Micrium Yes RTCA/DO-178B Opt. Opt. GUI
Flash
* Lightweight IP
TCP/IP Stack
Open Source Yes Sockets API
IP, ICMP, UDP, TCP
µC/OS-II Support
** Nucleus Plus ATI/Mentor Yes OSEK
µITRON
Opt. Opt. GUI, SNMP
RMON, SPAN
µCLinux Open Source (GPL)
Yes Incl. Many, inc. FAT and
JFFS2
Extensive drivers and middlewear,
inc USB, IPSec, etc.
KROS KROS
Technologies
Yes POSIX Opt. Opt.
* Included in Nios II Development Kits** Evaluation Version Included in Nios II Development Kits
<continued on next slide>
68Copyright © 2005 Altera Corporation
Nios II OS / RTOS Support (cont)Nios II OS / RTOS Support (cont)Product Provider Source
Code
Standards TCP/IP
Stack
File
System
Other
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 (GPL with excpetion)
Yes POSIZ, uITRON, EL/IX
Incl. FAT, JFFS2,
ROMFS, RAMFS
Extensive drivers and middleware, inc. USB, IPSec, etc.
* Included in Nios II Development Kits** Evaluation Version Included in Nios II Development Kits
69Copyright © 2005 Altera Corporation
Nios II MicroC/OS-II 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
70Copyright © 2005 Altera Corporation
Nios II MicroC/OS-II Nios II MicroC/OS-II
71Copyright © 2005 Altera Corporation
Lightweight IP for MicroC/OS-IILightweight 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
72Copyright © 2005 Altera Corporation
LWIP - InstantiationLWIP - Instantiation
Available as a Software Component
73Copyright © 2005 Altera Corporation
LWIP – ConfigurationLWIP – Configuration
74Copyright © 2005 Altera Corporation
Nios to Nios II ConversionNios 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
75Copyright © 2005 Altera Corporation
Nios to Nios II ConversionNios 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
76Copyright © 2005 Altera Corporation
Nios to Nios II ConversionNios to Nios II Conversion
Full Port from Nios to Nios II Requires C code changes No GERMS support Provides access HAL, uC/OSII, LWIP
77Copyright © 2005 Altera Corporation
Nios to Nios II ConversionNios 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
Software Run & DebugSoftware Run & Debug
79Copyright © 2005 Altera Corporation
Software Run and DebugSoftware Run and Debug
Nios II Run Nios II IDE JTAG Debugger Nios II ISS Nios II Console Third Party tools
80Copyright © 2005 Altera Corporation
Running Code On A TargetRunning Code On A Target
Nios II IDE can be used to download code to target board
81Copyright © 2005 Altera Corporation
Running Code On A TargetRunning Code On A Target
Download messages, stdout and stdin appear in console window
82Copyright © 2005 Altera Corporation
Nios II IDE Run OptionsNios II IDE Run Options
Nios II IDE > Run > Run…
83Copyright © 2005 Altera Corporation
System ID Peripheral RevisitedSystem 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
84Copyright © 2005 Altera Corporation
Nios II IDE JTAG DebuggerNios II IDE JTAG Debugger
Requirements Must have JTAG
Debug Core enabled in CPU
85Copyright © 2005 Altera Corporation
Nios II IDE Debug PerspectiveNios II IDE Debug Perspective
Double-click to Double-click to add breakpointsadd breakpoints
Basic Debug
• Run Controls
• Stack View
• Active Debug Sessions
•Variables
•Registers
•Signals
Memory View
86Copyright © 2005 Altera Corporation
Nios II IDE DebuggerNios II IDE Debugger
Step ReturnStep Return
Step OverStep Over
Step IntoStep Into
Step with FiltersStep with Filters
DisconnectDisconnect
TerminateTerminate
SuspendSuspend
ResumeResume
Run last ConfigurationRun last Configuration
Debug last ConfigurationDebug last Configuration
87Copyright © 2005 Altera Corporation
Nios II IDE DebuggerNios II IDE Debugger
Standard debug windows memory registers Variables breakpoints expressions signals
88Copyright © 2005 Altera Corporation
Nios II IDE – Multi-Processor LaunchNios 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
89Copyright © 2005 Altera Corporation
Nios II IDE: Debugger Nios II IDE: Debugger
Debug each CPU by selecting it’s program thread
90Copyright © 2005 Altera Corporation
Nios II Instruction Set SimulatorNios 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.TimerUARTMemory (flash, SDRAM, on-chip, etc…)
91Copyright © 2005 Altera Corporation
Nios II Instruction Set SimulatorNios II Instruction Set Simulator
Launch an ISS Debug session from the Run Menu
92Copyright © 2005 Altera Corporation
Nios II Instruction Set SimulatorNios II Instruction Set Simulator Targets .elf file to ISS and opens debugger
Application can then be debugged as normal
93Copyright © 2005 Altera Corporation
Customizing Views in the IDE GUICustomizing Views in the IDE GUI
You can turn windows on or off in either the Run or Debug Perspective
94Copyright © 2005 Altera Corporation
Nios II SDK ShellNios 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
95Copyright © 2005 Altera Corporation
Nios II / FS2 ConsoleNios II / FS2 Console
Command line debugger
96Copyright © 2005 Altera Corporation
Nios II Console LaunchNios II Console Launch
FS2 Console Launches then minimizes
97Copyright © 2005 Altera Corporation
Nios II ConsoleNios 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
98Copyright © 2005 Altera Corporation
Nios II Debug SolutionsNios II Debug SolutionsProduct 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 Systems
Debugger Supports FS2 ISA-Nios/T
ISA-Nios/T First Silicon Solution (FS2)
JTAG Trace Probe
External Trace Capture, Timestamp, Complex Data Triggers
* Included in Nios II Development Kits
** Evaluation Version Included in Nios II Development Kits
99Copyright © 2005 Altera Corporation
Upgrades from FS2Upgrades from FS2(see www.fs2.com for details)
Feature Nios II IDE FS2 S/W Upgrade
FS2 H/W Upgrade
Hardware Execution Breakpoints
2 4 4
Data Triggers 2 4 4
Trace (PC) On-Chip
16 Frames
On-Chip
128 Frames
Off-Chip
128K Frames
Trace (Load / Store) No Yes Yes
Trace (Timestamp) No No Yes
Target Connection Altera
USB/B Blaster
Altera
USB/B Blaster
FS2 Black Box
(USB, Ethernet)
Cost Included See FS2 See FS2
100Copyright © 2005 Altera Corporation
FS2 System Analyzer UpgradeFS2 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
Lab 2Software FlowLab 2Software Flow
45 mins45 mins
Copyright © 2005 Altera Corporation
RTL SimulationRTL Simulation
103Copyright © 2005 Altera Corporation
RTL SimulationRTL Simulation
Nios II SOPC Builder Automatically Creates Simulation Models Plus: ModelSim Project Testbench Simulation Scripts
Set Simulation Option
104Copyright © 2005 Altera Corporation
SDRAMDev board
SRAMDev board
FLASH
32-BitNios II
ProcessorOn Chip
ROM)
Clock Reset
Address (32)
Read
Write
Data In (32)
Data Out (32)
IRQ
IRQ #(6)
Avalo
n S
witch
Fab
ric
Nios II Processor
Simulation TestBenchSimulation TestBench
Tri-StateBridge
Us
er
De
vic
e
Compact FLASH
SDRAMController
Ethernet MAC/PHY
Tri-StateBridge
Compact Flash PIOs
User Defined Interface
User Defined
Peripheral
On Chip RAM
Custom Instruction
UART
User DeviceUser
PeripheralIncluded
Not Included
105Copyright © 2005 Altera Corporation
User Additions to Nios II TestBenchUser 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
106Copyright © 2005 Altera Corporation
Running an RTL SimulationRunning an RTL Simulation
Modify Nios II IDE System Library For Simulation: Specify Program Memory Set Up As Simulation Only
107Copyright © 2005 Altera Corporation
Running an RTL SimulationRunning 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
108Copyright © 2005 Altera Corporation
Running an RTL SimulationRunning an RTL Simulation
Launch ModelSim from Nios II IDE: Highlight Software Project In C/C++ Projects panel Right click Run As Nios II ModelSim
109Copyright © 2005 Altera Corporation
Running an RTL SimulationRunning an RTL Simulation
110Copyright © 2005 Altera Corporation
Simulation ScriptsSimulation 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
111Copyright © 2005 Altera Corporation
Memory Device Simulation ModelsMemory 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
112Copyright © 2005 Altera Corporation
Memory Device Simulation ModelsMemory 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
113Copyright © 2005 Altera Corporation
UART SimulationUART 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
114Copyright © 2005 Altera Corporation
UART SimulationUART Simulation
Input is interactive or predefined Output is shown and saved independently for
multiple UARTs
115Copyright © 2005 Altera Corporation
JTAG_UART Simulation JTAG_UART Simulation
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
New
116Copyright © 2005 Altera Corporation
Wave WindowWave Window
Adds UART and CPU signals by default
117Copyright © 2005 Altera Corporation
Capture the state of internal nodesIn-system, at full system speeds
SignalTap™ II Logic AnalyzerSignalTap™ 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!
118Copyright © 2005 Altera Corporation
SignalTap™ II Logic AnalyzerSignalTap™ II Logic Analyzer
Copyright © 2005 Altera Corporation
Lab 3RTL SimulationLab 3RTL Simulation
30 mins30 mins
Copyright © 2005 Altera Corporation
Avalon Switch FabricAvalon Switch Fabric
121Copyright © 2005 Altera Corporation
Avalon Switch FabricAvalon Switch Fabric
Proprietary interconnect specification used with Nios II
Principal design goals Low resource utilization for bus logic Simplicity Synchronous operation
Transfer Types Slave Transfers Master Transfers Streaming Transfers Latency-Aware Transfers Burst Transfers
32-BitNios II
Processor
Switch PIO
LED PIO
7-SegmentLED PIO
PIO-32
User-Defined Interface
ROM(with Monitor)
UART Timer
Address (32)
Read
Write
Data In (32)
Data Out (32)
IRQ
IRQ #(6)
Avalo
n S
witch
Fab
ric
Nios II Processor
122Copyright © 2005 Altera Corporation
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
Avalon Switch FabricAvalon Switch Fabric
123Copyright © 2005 Altera Corporation
Avalon Master PortsAvalon 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
124Copyright © 2005 Altera Corporation
Avalon Slave PortsAvalon Slave Ports
Respond to Transfer Requests from Avalon Switch Fabric
Transfer Types Fundamental Read Fundamental Write
Transfer Properties Wait States Latency Streaming Burst
125Copyright © 2005 Altera Corporation
Slave Read TransferSlave Read Transfer
0 Setup Cycles
0 Wait Cycles
clk
address,be_n
readn
chipselect
readdata
address, be_n
readdata
A C D EB
126Copyright © 2005 Altera Corporation
clk
address,be_n
chipselect
readn
readdata
address, be_n
readdata
Tsu
A B C D E F G H
Slave Read Transfer with Wait StatesSlave Read Transfer with Wait States
1 Setup Cycle 1 Wait Cycle
127Copyright © 2005 Altera Corporation
clk
address,be_n
writedata
writen
chipselect
address, be_n
writedata
A B C D
Slave Write TransferSlave Write Transfer
0 Setup Cycles
0 Wait Cycles 0 Hold Cycles
128Copyright © 2005 Altera Corporation
clk
address,be_n
writedata
writen
chipselect
address, be_n
writedata
B C D E FA G
Slave Write Transfer with Wait StatesSlave Write Transfer with Wait States
1 Setup Cycle 0 Wait Cycles 1 Hold Cycle
129Copyright © 2005 Altera Corporation
Multiple Clock Domains SupportedMultiple Clock Domains Supported
CDX = Clock Domain Crossing Logic (inserted automatically by SOPC Builder)
MasterClock Domain 1
Slave Clock Domain 2
Slave Clock Domain 2
CDXCDX
Avalon Switch Fabric
CDXCDX
Avalon Switch Fabric
ArbiterArbiter
MasterClock Domain 1
MasterClock Domain 2
Slave Clock Domain 2
Slave Clock Domain 2
Slave Clock Domain 2
Slave Clock Domain 2
Slave Clock Domain 2
Slave Clock Domain 2
130Copyright © 2005 Altera Corporation
Multi-Clock Domain SupportMulti-Clock Domain Support
CDX = Clock Domain Crossing Logic
MasterClock
Domain 1
Slave Clock Domain 3
Slave Clock Domain 3
MasterClock
Domain 2
CDXCDX
Avalon Switch Fabric
ArbiterArbiter
CDXCDX
MasterClock
Domain 1
SlaveClock Domain 2
SlaveClock Domain 2
MasterClock
Domain 1
Avalon Switch Fabric
CDXCDX
ArbiterArbiter
131Copyright © 2005 Altera Corporation
User-Defined Custom PeripheralsUser-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
132Copyright © 2005 Altera Corporation
No Need to Worry about Bus Interface Implement Only Signals Needed Peripherals Adapted to by
Avalon Switch Fabric Timing Handled Automatically Fabric Created for You Arbiters Generated for You
Creating Avalon SlaveCreating Avalon Slave
Concentrate Effort onPeripheral Functionality!
User Logic
Avalon Switch Fabric
Register File
133Copyright © 2005 Altera Corporation
New Component EditorNew Component Editor
134Copyright © 2005 Altera Corporation
Creates InterfaceCreates Interface
Connect to Existing HDL or board component Map into Nios II Memory Space Can be “Inside” or “Outside” Nios II System
Nios II
CPU
Ava
lon
Interface
to User
LogicNios II System
Module
External
User
Peripheral
I/O
I/O
I/O
I/O
Nios II
CPU
Ava
lon
Internal
User
PeripheralNios II System
Module
I/O
I/O
I/O
I/O
135Copyright © 2005 Altera Corporation
Create External Component InterfaceCreate External Component Interface
To communicate with off-chip peripherals
Base interface type on data sheet
AMD29LV065AD CFI Flash Chip
136Copyright © 2005 Altera Corporation
Or Add HDL FilesOr Add HDL Files
For peripheral that has been encoded for FPGA
137Copyright © 2005 Altera Corporation
Tri-State PeripheralsTri-State Peripherals
Require Tri-State Bridge Available as an SOPC Builder component
Tri-State peripheral is defined by the presence of a bi-direction data port
Off-chip peripherals do not have to be tri-state
Nios IIProcessor
Ava
lon
Tri-
Sta
te
Brid
ge
Inte
rfac
e to
U
ser
Logi
c
Off Chip Off Chip PeripheralPeripheral
FPGA
138Copyright © 2005 Altera Corporation
Define Component SignalsDefine Component Signals
Automatically populates port table from design files
Enter port type here
Can also define ports manually
139Copyright © 2005 Altera Corporation
Define Interface for Each Signal TypeDefine 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
140Copyright © 2005 Altera Corporation
Address Alignment – Narrow SlaveAddress Alignment – Narrow Slave
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
32-BitNios II
Processor
8 Bit Peripheral
Avalo
n
32
8
Peripheral Registers
Base
Base + 0x1
Base + 0x2
Base + 0x3
Base + 0x4
aa
bb
cc
dd
ee
141Copyright © 2005 Altera Corporation
Address Alignment – Narrow MasterAddress Alignment – Narrow Master
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
64 Bit Memory
Avalo
n
32
64
Memory Contents
Base
Base + 0x8
Base + 0x16
77 66 55 44 33 22 11 00
ff ee dd cc bb aa 99 88
?? ?? ?? ?? ?? ?? ?? ??
32-BitNios II
Processor
142Copyright © 2005 Altera Corporation
Add Software FilesAdd Software Files
ie. Header files and drivers
143Copyright © 2005 Altera Corporation
Add Software FilesAdd Software Files Header file and drivers can also be added directly to
Application Project
144Copyright © 2005 Altera Corporation
Fill in fields Add component to
SOPC Builder portfolio Can add parameterizing
capability to component
Create Component WizardCreate Component Wizard
Publish and create a wizard for your component
145Copyright © 2005 Altera Corporation
Add Component to SOPC SystemAdd Component to SOPC System
Default location is the User Logic folder
146Copyright © 2005 Altera Corporation
Intel PXA255 ExampleIntel PXA255 Example
147Copyright © 2005 Altera Corporation
VLIO as an Avalon Master Port VLIOVLIO 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
148Copyright © 2005 Altera Corporation
Relevant Verilog Code to Relevant Verilog Code to ImplementRelevant Verilog Code to Relevant Verilog Code to Implement
Copyright © 2005 Altera Corporation
Lab 4Adding A User PeripheralLab 4Adding A User Peripheral
30 mins30 mins
Copyright © 2005 Altera Corporation
Custom InstructionsCustom Instructions
151Copyright © 2005 Altera Corporation
Custom InstructionsCustom 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
152Copyright © 2005 Altera Corporation
Custom InstructionsCustom Instructions
Augment Nios II Instruction Set Mux User Logic Into ALU Path of Processor Pipeline
153Copyright © 2005 Altera Corporation
Several Levels of CustomizationSeveral Levels of CustomizationOptional Interface to FIFO, Memory, Other Logic
Internal
Register File
a
5
b 5
5
c
readra
readrb
writerc
n
8Extended
clk
clk_en
reset
start
Multi-Cycle done
dataa
32datab
32
Combinatorialresult
32
154Copyright © 2005 Altera Corporation
Custom InstructionsCustom 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
155Copyright © 2005 Altera Corporation
Custom Instructions TabCustom Instructions Tab
Enabled from the Custom Instructions tab in the Nios II CPU settings in SOPC Builder
156Copyright © 2005 Altera Corporation
Custom Instructions TabCustom Instructions Tab
Import logic for the custom instruction Custom Instruction module can be of following
formats: VHDL Verilog HDL EDIF Quartus Block Diagram (.bdf)
157Copyright © 2005 Altera Corporation
Combinatorial Custom InstructionsCombinatorial Custom Instructions
Port list All Custom Instruction Modules need these ports
Port names must match exactly
158Copyright © 2005 Altera Corporation
Multi-Cycle Custom InstructionsMulti-Cycle Custom Instructions
Port list for Multi-Cycle Custom Instructions Must have all of these ports with exact names
159Copyright © 2005 Altera Corporation
Extended Custom InstructionsExtended Custom Instructions
Uses n[7..0] port to select an operation to perform.
160Copyright © 2005 Altera Corporation
Register File Custom InstructionsRegister File Custom Instructions
Custom
Logic
dataa[31..0]
reada
a[4..0]
result[31..0]
writec
c[4..0]
Custom instructions can select inputs from internal registers or dataa, datab ports
Custom instructions can write results to an internal register file
161Copyright © 2005 Altera Corporation
Software Interface - CSoftware 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; }
162Copyright © 2005 Altera Corporation
Assembly Language Interface Assembly Language Interface
Assembler syntax for the custom instruction:
custom N, rC, rA, rB
Two Examples:
custom 0, r6, r7, r8
custom 3, c1, r2, c4
Custom Custom instruction instruction
opcode opcode numbernumber
Destination Destination register register for resultfor result
Operand 1Operand 1 Operand 2Operand 2
r = Nios II processor r = Nios II processor registerregister
c = Custom instruction c = Custom instruction internal registerinternal register
163Copyright © 2005 Altera Corporation
Why Custom Instruction?Why Custom Instruction? Reduce Complex Sequence of Instructions to One Instruction Example: Floating Point Multiply
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
float a, b, result_slow, result_fast;
result_slow = a * b; /* Takes 266 clock cycles */result_fast = ALT_CI_fpmult(a,b); /* Takes 6 clock cycles*/
Significantly Faster!
float a, b, result_slow, result_fast;
result_slow = a * b; /* Takes 266 clock cycles */result_fast = ALT_CI_fpmult(a,b); /* Takes 6 clock cycles*/
Significantly Faster!
164Copyright © 2005 Altera Corporation
Custom Instruction vs PeripheralCustom Instruction vs Peripheral
Custom Instruction can execute in a single cycle No overhead for call to custom Hardware
Access to same hardware as peripheral takes multiple cycles Write DataA, then write DataB, and finally read Result
ResultDataBDataA
0x400
0x404
0x408
Custom Custom InstructionInstructionL1
L0L0
Custom Custom PeripheralPeripheralL1
L0L0
Peripheral memory map
165Copyright © 2005 Altera Corporation
Multi-Cycle Custom InstructionsMulti-Cycle Custom Instructions
Processor stalls while awaiting result Clock cycles = 3
DataA DataB
REGREG
REGREG
Result
Cus
tom
Ins
truc
tion
custom
---
---
Next InstrNio
s C
lock
Cyc
les
166Copyright © 2005 Altera Corporation
Result not always needed for each input Clock Cycles = 1 Route start sig to reg clk_en
Pipelined Custom InstructionsPipelined Custom Instructions
DataA DataB
REGREG
REGREG
Result
Cus
tom
Ins
truc
tion
custom
Next Instr
Nio
s C
lock
Cyc
les
custom
custom
custom
custom
167Copyright © 2005 Altera Corporation
Accelerating CRCAccelerating 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
reg
xor/
shift
xor/
shift
xor/
shift
in(15) in(14) in(0)
168Copyright © 2005 Altera Corporation
CRC Custom InstructionCRC 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
CRC
Custom Instruction
DataA(31-0)
DataB(0)
// reset crc ALT_CI_CRC(0xFFFF,1);
// run crc ALT_CI_CRC(word,0);
// reset crc ALT_CI_CRC(0xFFFF,1);
// run crc ALT_CI_CRC(word,0);
Data in
Init / nRun
CRC Reg Result(15-0)
Control
Copyright © 2005 Altera Corporation
Multi-Masters and Direct Memory Access (DMA)Multi-Masters and Direct Memory Access (DMA)
170Copyright © 2005 Altera Corporation
Direct Memory Access (DMA) Processor Waits For Bus During DMA
System CPU(Master 1)
DMA Arbitor
100Base-T(Master 2)
System Bus
I/O1
I/O2 Data
Memory
DMA Bus ArbiterDMA Bus Arbiter Arbiter Determines Which Master Has Access To Shared
Bus
ProgramMemory
Masters
Slaves
Traditional Multi-MastersTraditional Multi-Masters
Control direction
SystemBottleneck
SystemBottleneck
171Copyright © 2005 Altera Corporation
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
DisplayControlDisplayControl
CPU 0CPU 0 DMADMA
Program Memory 0Program Memory 0 I/OI/O Custom
FunctionCustomFunction
Data Memory 1
Data Memory 1
System Switch Fabric
Program Memory 1Program Memory 1
Data Memory 0
Data Memory 0
ArbiterArbiter
Masters
Slaves
Uses Fairness Arbitration
Avalon Simultaneous Multi-Mastering BusAvalon Simultaneous Multi-Mastering Bus
automatically automatically generated by generated by SOPC BuilderSOPC Builder
CPU 1CPU 1
ArbiterArbiter
172Copyright © 2005 Altera Corporation
Provides Bus Master Capability to Any Nios II Peripheral FIFO Depth = 2
DMA Peripheral
Control Port
Direction
Master Port
1
Start Addr
# Bytes
Addr Incr
Master Port
2
Start Addr
# Bytes
Addr Incr
FIFO
DMA PeripheralDMA Peripheral
173Copyright © 2005 Altera Corporation
Master 1(Nios II CPU)
I/O1Program
Memory
Arbiter
DataMemory
1
SPI
I D
I/O2
Avalon Avalon
Master 2DMA
Data Flow with DMA PeripheralData Flow with DMA Peripheral
174Copyright © 2005 Altera Corporation
Use custom hardware peripheral with DMA Processor & Accelerator Run Concurrently More Work Per Clock Lower fMAX, Power, Cost
Accelerate Software ExecutionAccelerate Software Execution
ProgramMemory
Processor
DataMemory
ArbiterArbiter
DataMemory
ArbiterArbiter
AvalonSwitch Fabric
DM
AD
MA
DM
AD
MA
Accelerator
175Copyright © 2005 Altera Corporation
Example: CRC Algorithm (64 Kbytes)
HardwareAccelerator
0
5,000,000
10,000,000
15,000,000
20,000,000
25,000,000
Clo
ck C
ycle
s
Software Only CustomInstruction
530 TimesFaster
27 TimesFaster
Accelerate Software ExecutionAccelerate Software Execution
176Copyright © 2005 Altera Corporation
Custom Streaming Slave PeripheralsCustom Streaming Slave Peripherals
For using DMA with other slow peripherals Example: UART
Adds up to three outputs to Avalon Slave dataavailable readyfordata endofpacket
Ava
lonCustom Custom
StreamingStreaming
Slave Slave PeripheralPeripheral
readdata
writedata
control
adress
endofpacket
Readyfordata
dataavailable
177Copyright © 2005 Altera Corporation
Streaming Slave Peripheral SignalsStreaming 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
178Copyright © 2005 Altera Corporation
Custom Master PeripheralsCustom 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
Ava
lonCustom Custom
Master Master PeripheralPeripheral
waitrequest
readdata
writedata
control
address
179Copyright © 2005 Altera Corporation
Master Read TransferMaster Read Transfer
Assert addr, be, read Wait for waitrequest = ‘0’ Read in Data End of transfer
180Copyright © 2005 Altera Corporation
Master Write TransferMaster Write Transfer
Assert addr, be, read Assert Write Data Wait for waitrequest = ‘0’ End of transfer
181Copyright © 2005 Altera Corporation
Avalon Master-Slave ConnectionsAvalon Master-Slave Connections
View => Show Master Connections Observe and configure Avalon connections
182Copyright © 2005 Altera Corporation
Master Arbitration SchemeMaster 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
PCI DMA 2 shares
SPI DMA 1 share
CPU 7 Shares
183Copyright © 2005 Altera Corporation
Set Arbitration PrioritySet Arbitration Priority
View => Show Arbitration Priorities
184Copyright © 2005 Altera Corporation
Avalon Arbitration BehaviorAvalon Arbitration Behavior
Master A Shares = 4
Master B Shares = 2
Arbiter (continuous accesses)
Master A Master B
Arbiter
Slave
Master B
Master A
Copyright © 2005 Altera Corporation
Lab 5Custom Instruction and (optional) DMA Controller
Lab 5Custom Instruction and (optional) DMA Controller
45 mins45 mins
Copyright © 2005 Altera Corporation
Working with the Development BoardWorking with the Development Board
187Copyright © 2005 Altera Corporation
Ensure Unused I/O are Tri-StateEnsure 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”
188Copyright © 2005 Altera Corporation
Clock DistributionClock Distribution
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
FPGA Nios IINios II
PLLPLL
Zer
o S
kew
B
uffe
r
SDRAMSDRAM
Zer
o S
kew
B
uffe
rCLK in
(50 MHz)
189Copyright © 2005 Altera Corporation
Flash Configuration Two FPGA images
Safe Image User Image
MAX® EPM7128 Configures FPGA from 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
Hardware Configuration ProcessHardware Configuration Process
MAX
Data
Ad
dre
ss
8 MB Flash
Stratix
Safe FPGA Safe FPGA ImageImage
User FPGA Image
0x600000
0x700000
190Copyright © 2005 Altera Corporation
SRAM
Data
Ad
dre
ss
8 MB Flash
Stratix
Flash Memory ConfigurationFlash Memory Configuration
Safe FPGA Safe FPGA Image & S/WImage & S/W
User FPGA Image
0x000000
0x100000
0x200000
0x300000
0x400000
0x500000
0x600000
0x700000
User User SoftwareSoftware
191Copyright © 2005 Altera Corporation
Controller
Data
8 MB Flash
Stratix
Configuration of FPGA From FlashConfiguration of FPGA From Flash
Safe FPGA Image Safe FPGA Image & S/W& S/W
User FPGA Image
0x000000
0x200000
0x400000
0x600000
0x800000
0xA00000
0xC00000
0xE00000
ApplicationApplication
CodeCode
8 MB RAM
0x1000000
Nios II
ApplicationApplication
CodeCode
Start-up CodeStart-up Code
Boot CopierBoot Copier
192Copyright © 2005 Altera Corporation
Data
8 MB Flash
Stratix
Loading RAMLoading RAM
Safe FPGA Image Safe FPGA Image & S/W& S/W
User FPGA Image
0x000000
0x200000
0x400000
0x600000
0x800000
0xA00000
0xC00000
0xE00000
ApplicationApplication
CodeCode
Boot CopierBoot Copier
8 MB RAM
0x1000000
Nios II
Application Application CodeCode
Dynamic Dynamic MemoryMemory
Start-upStart-up CodeCode
Start-up CodeStart-up Code
193Copyright © 2005 Altera Corporation
Use Flash for Program Storage Running from Flash is slow
Nios II IDE Automatically Prepends Boot Copier to Program Code if Reset Address is in Flash and
Program Memory is in RAM
For Custom Boards:(see again “Nios II Flash Programmer User Guide”) Must create your own flash
programmer design to transport data to the flash on your board
my_sw.elf
Boot Copier
SRAM
Data
Ad
dre
ss
8 MB Flash
Stratix User Software
Boot CopierBoot Copier
my_sw.flash
194Copyright © 2005 Altera Corporation
Nios II Flash ProgrammerNios 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 ContentFlash Content
195Copyright © 2005 Altera Corporation
Nios II Flash ProgrammerNios 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
196Copyright © 2005 Altera Corporation
Nios II Flash ProgrammerNios II Flash Programmer Can program Flash from Nios II IDE or command line
Nios II IDE is recommended method
197Copyright © 2005 Altera Corporation
Nios II Flash ProgrammerNios II Flash Programmer Command Line Utilities
elf2flash
sof2flash
Bin2flash
elf2hex
nios2-flash-programmer
(see “Nios II Flash Programmer User Guide” for details)
198Copyright © 2005 Altera Corporation
Instantiating Flash in Target SystemInstantiating 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
199Copyright © 2005 Altera Corporation
Flash Programmer DesignFlash 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
200Copyright © 2005 Altera Corporation
What If Safe Flash Image Overwritten?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
Lab 6The Flash ProgrammerLab 6The Flash Programmer
10 mins10 mins
Copyright © 2005 Altera Corporation
Thank YouThank You