Vous êtes sur la page 1sur 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
C stom Peripherals

Custom Instructions
M lti M t
Multi-Masters
and
d Direct
Di t M
Memory A
Access (DMA)
Configuring the Development Board

Copyright 2005 Altera Corporation

Nios II Hardware
Development
Copyright 2005 Altera Corporation

What is Nios II?

Alteras Second Generation Soft-Core 32 Bit RISC Microprocessor

Debug

On Chip
On-Chip
ROM
On-Chip
RAM

FPGA
4

Copyright 2005 Altera Corporation

Avalon Sw
witch Fabric

Nios II
CPU

Cache

- Nios
Developed
By Altera
II Plus Internally
All Peripherals
Written In HDL
- Can
Harvard
Architecture
Be Targeted
For All Altera FPGAs
- Synthesis
Royalty-Free
Using Quartus II Integrated Synthesis
UART
GPIO
Timer
SPI
SDRAM
Controller

Problem: Reduce Cost, Complexity & Power

Flash

I/O
CPU

SDRAM

I/O
I/O

I/O

I/O

I/O

FPGA
G
CPU

DSP

DSP

Solution: Replace External Devices


with Programmable Logic
5

Copyright 2005 Altera Corporation

Problem:On
Reduce
Cost, Complexity
& Power
System
A Programmable
Chip
(SOPC)

Flash

FPGA
SDRAM

CPU is a Critical
Function
Solution:
ReplaceControl
External
Devices
Required
forProgrammable
System Level Logic
System-Level
Integration
with
6

Copyright 2005 Altera Corporation

FPGA Hardware Design Flow


with Quartus II and SOPC Builder

Create FPGA project in Quartus II


Build embedded sub
sub--system in SOPC Builder
Integrate subsub-system in Quartus II
Compile and generate a programming file
7

Copyright 2005 Altera Corporation

.sof / .pof file

Development Kits, Stratix & Cyclone Edition


Serial RS-232
Connectors

Download /JTAG
Debug Connector
Power Connector

10/100 Ethernet
MAC/PHY &
RJ-45 Connector
Expansion
Prototype
Connectors

CPU Reset
8 MB Flash

(40 I/O pins each)

16 MB SDRAM
1MB SRAM

Compact Flash
(Connector Mounted on Back)

Buttons

Copyright 2005 Altera Corporation

LEDs

7 Segment

Configuration
g
Controller
(MAX 7128AE)
Configuration Control

Standard Design Block Diagram


Ethernet
MAC/PHY

1MB
SRAM

8MB
FLASH

16MB Compact
FLASH

32MB
SDRAM

Tri-State
Bridge

Address (32)
Read
Write
Data In ((32))
Data Out (32)

IRQ
Q
IRQ #(6)

On-Chip

Off-Chip

Copyright 2005 Altera Corporation

Avalo
on Switch Fa
abric

32-Bit
Nios II
Processor

Tri-State
Bridge

Compactt
C
Flash
PIOs

SDRAM
Controller

UART

General
Purpose
Timer

Periodic
Timer

LED PIO

LCD PIO

7-Segment
LED PIO

Button PIO

8 LEDs

Expansion
Header
J12

2 Digit
Display

4
Momentary
buttons

ROM
(with Monitor)

Reconfig
PIO

Le
evel Shifter

Nios II Processor

Nios II System Architecture


Instr.
Nios II
CPU

Address
Decoder

D t
Data

On-Chip
g Core
Debug

Interrupt
Controller

Avalon
Master/
Slave
P t
Port
Interfaces

UART 0

Timer 0

SPI 0
Wait State
Generation
GPIO 0

Off-Chip
Software Trace
Memory

Data
D
t iin
Multiplexer
Master
Arbitration
Dynamic
Bus Sizing

Avalon Switch Fabric


10

Copyright 2005 Altera Corporation

DMA 0

UART n

Timer n

SPI n

GPIO n

DMA n

Memory
Interface Memory
Interface
User-Defined
InterfaceUser-Defined
Interface

Nios II Block Diagram


Nios II Processor Core
reset
clock
l k
JTAG interface
to Software
Debugger

HardwareAssisted
Debug Module

Program
Controller
&
Address
Generation

General
Purpose
Registers
r0 to r31

Instruction
Master
Port
Instruction
Cache

Exception
Controller
Interrupt
Controller

irq[31..0]

Custom
I/O Signals

11

C stom
Custom
Instruction
Logic

Copyright 2005 Altera Corporation

Control
Registers
ctl0
tl0 to
t ctl4
tl4

Arithmetic
A
ith ti
Logic Unit

Data
Cache

Data
Master
Port

Nios II Processor Architecture


Classic

Pipelined RISC Machine

32 G
Generall P
Purpose R
Registers
i t
3 Instruction Formats
32-Bit
Bit Instructions
32
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

12

Copyright 2005 Altera Corporation

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
S f
Code is Binary Compatible
z

13

No Changes Required When CPU is Changed

Copyright 2005 Altera Corporation

Binary Compatibility / Flexible Performance


Nios II /f
Fast

Nios II /s
Standard

Nios II /e
Economy

Pipeline

6 Stage

5 Stage

None

H/W Multiplier &


Barrel Shifter

1 Cycle

3 Cycle

Emulated
In Software

Branch Prediction

Dynamic

Static

None

Instruction Cache

Configurable

Configurable

None

Data Cache

Configurable

None

None

1400 - 1800

1200 1400

600 700

Logic
L
i Usage
U
(Logic Elements)
Custom
Instructions

14

Copyright 2005 Altera Corporation

Up to 256

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

15

250

Standard
MUL in Stratix

Fast
MUL in Stratix

Copyright 2005 Altera Corporation

Licensing

Nios II Delivered As Encrypted Megacore

Licensed Via Feature Line In Existing Quartus II License File


Consistent
C
i t t With General
G
l Altera
Alt
Megacore
M
Delivery
D li
M
Mechanism
h i
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
S
License

Available Upon Request On Case-By-Case Basis


Included With Purchase Of Nios II ASIC License

16

Copyright 2005 Altera Corporation

Requirements for Nios II Designs

Quartus II 4.0 SP1 or higher


Note:
N t Q
Quartus
t II now 4.2
4 2 available
il bl
Required for Nios II 1.1

No spaces in Quartus II project pathname


Nios II license or a p
programming
g
g cable
tethered to PC to run the OpenCore Plus
version of Nios II

17

Copyright 2005 Altera Corporation

Nios II: Hard Numbers


Nios II/f
Stratix II

Stratix

Cyclone

Nios II/s

Nios II/e

200 DMIPS @ 175MHz


1180 LEs
1 of 8 DSP
4K Icache, 2K Dcache
Stratix 2S10
2S10-C5
C5
150 DMIPS @ 135MHz
1800 LEs
1 of 8 DSP
4K IIcache,
h 2K D
Dcache
h
Stratix 1S10-C5
100 DMIPS @ 125MHz
1800 LEs

90 DMIPS @ 175MHz
800 LEs

28 DMIPS @ 190MHz
400 LEs

4K Icache, No Dcache
Stratix 2S10
2S10-C5
C5
67 DMIPS @ 135MHz
1200 LEs

No Icache, No Dcache
Stratix 2S10
2S10-C5
C5
22 DMIPS @ 150MHz
550 LEs

4K IIcache,
h N
No D
Dcache
h
Stratix 1S10-C5
62 DMIPS @ 125MHz
1200 LEs

No IIcache,
N
h N
No D
Dcache
h
Stratix 1S10-C5
20 DMIPS @ 140MHz
550 LEs

4K Icache, 1K Dcache
Cyclone 1C4-C6

2K Icache, No Dcache
Cyclone 1C4-C6

No Icache, No Dcache
Cyclone 1C4-C6

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

18

Copyright 2005 Altera Corporation

SOPC Builder System Contents Page

Over 60
Cores Available
Today
y

19

Copyright 2005 Altera Corporation

Altera, Partner & User


Cores
Processors
Memory Interfaces
Peripherals
Bridges
Hardware Accelerators
Import User Logic
(ie. custom peripherals)

Web-Based IP Deployment

Clock-Domain Crossing

Auto-Insertion of Clock-Domain Crossing Logic


FIFO Where
Wh
Posted-Reads
P t dR d A
Are S
Supported
t d
Simple Metastability-Hardening Otherwise

Unlimited Number of Clock Domains


Added, Named & Managed Through GUI

20

New in
4.2

Copyright 2005 Altera Corporation

Nios II CPU Configured in SOPC Builder

21

Hardware designer selects which Nios II version to use when


creating system

Copyright 2005 Altera Corporation

Selecting JTAG Debug Core

22

Configuration is chosen when hardware designer selects


appropriate Nios II processor core

Copyright 2005 Altera Corporation

SOPC Builder More cpu Settings Page

23

Copyright 2005 Altera Corporation

SOPC Builder System Generation Page

24

Copyright 2005 Altera Corporation

SOPC Builder Produces a .PTF File

25

Text file that records SOPC Builder edits


Describes Nios II System
Used by software development tools

Copyright 2005 Altera Corporation

Integrate SOPC Builder O/P in Quartus II

26

Integrate SOPC Builder block symbol to Quartus II schematic


(as shown below) and compile design
O instantiate
Or,
i t ti t top
t module
d l into
i t your HDL d
design
i and
d compile
il

Copyright 2005 Altera Corporation

New Peripherals for Nios II

System ID Peripheral

EPCS Serial Flash


Controller
On-Chip

Used to Ensure Hardware/


Software Version Synchronization
Simple 2 read-only register
peripheral containing hardware ID
tags.
z
z

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

27

Copyright 2005 Altera Corporation

Memory Interfaces

RAM, ROM

Off-Chip
z
z

SRAM
CFI Flash

LCD Display

New Peripherals for Nios II

JTAG UART
Single JTAG
Connection For:
z
z
z
z
z

Device Configuration
Fl h P
Flash
Programming
i
Code Download
Debug
T
Target
t STDIO (printing)
( i ti )

Compact Flash Interface


Mass Storage
g Support
z
z

True IDE Mode


Compact Flash Mode

Software Supports
pp
z
z
z

Low-Level API
MicroC/OS-II File System
Support
CLinux File System
Support

Supported through
www.niosforum.com

28

Copyright 2005 Altera Corporation

Project Directories

Hardware
HDL Source & Netlist
db - Quartus project
database

Software
Application source code
Library files

Simulation
Testbench
Automatically generated
test memory and vectors

29

Copyright 2005 Altera Corporation

Exercise 1
A Basic Nios II Design
g
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


Peripherals, IP

IP Modules
M d l

Hardware Development

Software Development
Nios II IDE

Connect Blocks

HDL Source Files

Testbench

Synthesis &
Fitter

User Design

Other IP Blocks

Quartus II

32

Copyright 2005 Altera Corporation

Generate
H d
Hardware
Configuration
File

Executable
E
t bl
Code

Verification
& Debug
JTAG
JTAG,
Serial, or
Ethernet

Altera
FPGA

On-Chip
Debug
Software Trace
Hard Breakpoints
SignalTap II

C Header files

Custom Library

Peripheral Drivers

Compiler,
Linker, Debugger

User Code

Libraries

RTOS

GNU Tools

Nios II Software Design Process

Deliverables Required to Start


Software Development:

Software Development
Nios II IDE

.ptf file from SOPC Builder


(defines hardware for the Nios II IDE)

.soff (or
( .pof)
f) fil
file ffrom Q
Quartus
t II
(used to program the FPGA on the board)

Thats ALL you need to start


to run with the Nios II IDE

Executable
E
t bl
Code

C Header files

Custom Library

Peripheral Drivers

Compiler,
Linker, Debugger

User Code

Libraries

RTOS

GNU Tools
33

Copyright 2005 Altera Corporation

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


34

Copyright 2005 Altera Corporation

Opening the Nios II IDE


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

35

Copyright 2005 Altera Corporation

Nios II IDE

File Viewer
do
Window

List of Open
Projects

(for C code,
C++, and
assembly*)

Terminal
window

Note: C++ files must have extension .cpp


In-line assembly code offset by asm();
36

Copyright 2005 Altera Corporation

Nios II IDE C/C++ Projects/Navigator

37

Lists all
open
projects

Displays
p y
source files
associated
with project

Copyright 2005 Altera Corporation

List all
open and
closed
projects

Allows you
to drag and
drop new
files into
existing
projects

Creating a C/C++ Application


File > New > Project

38

Copyright 2005 Altera Corporation

Creating a C/C++ Application


Link to a System Library
- Select a pre-existing
pre existing library
- Or create a new library

39

Copyright 2005 Altera Corporation

This Creates Two Software Projects


- Application and System Library Project
Application Project
- contains application
source code

System Library Project


- contains system
y
header file, etc.

Drivers Directory
- contains all device drivers
DO NOT DELETE !

40

Copyright 2005 Altera Corporation

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
p
RTOS ((MicroC/OS-II))
Optional software components (Lightweight
TCP/IP stack, Read Only Zip File System)

41

Copyright 2005 Altera Corporation

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
g Library
y Project
j
Facilitates software library
development
Enables you to associate precompiled code into an Application
Project
Tool writes makefile for included files

42

Copyright 2005 Altera Corporation

Importing Projects into the IDE

43

Copyright 2005 Altera Corporation

Project Properties

44

Both Application and System Library have


Properties pages

Copyright 2005 Altera Corporation

System Library Options


Select
Specify
stdio
devicesmap
Partition
theRTOS
memory

45

Copyright 2005 Altera Corporation

Software Compilation

46

To compile a software application, highlight your project


and select Build Project from the Projects menu

Copyright 2005 Altera Corporation

Directory Structure After Compilation

47

Application Project

Copyright 2005 Altera Corporation

System Library Project

Nios II Host Platform Support

Windows XP
Linux
Li
H
Hostt S
Supportt (R
(RedHat
dH t 7
7.3,
3 8
8.0,
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

48

Copyright 2005 Altera Corporation

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:

49

device drivers
initialization software
file system
stdio, stderr

Copyright 2005 Altera Corporation

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
z
z
z

50

ANSI C (through the Newlib library)


UNIX style interface (i.e. POSIX like)
Altera extensions where standards dont exist or were
inappropriate (watch for the alt_* extension)

Copyright 2005 Altera Corporation

Hardware Abstraction Layer

Key features of the HAL


Uses standard interfaces where appropriate
Close integration with the Newlib ANSI C library
z http://sources.redhat.com/newlib/
Device drivers automatically configured to match the PTF
Drivers initialised before main()
Scalable (i.e. packs down small)
Clear
C
distinction between system and application software
f

51

Copyright 2005 Altera Corporation

Nios II HAL: Runtime Library


The HAL UNIX Style Functions are the glue
between the C libraryy and the device drivers

HAL API

User Program

C Standard Library

HAL API
Device
D
i
Driver

Device
D
i
Driver

Device
D
i
Driver

Nios II Processor System Hardware

52

Copyright 2005 Altera Corporation

_exit()
close()
closedir()
fstat()
getpid()
gettimeofday()
ioctl()
isatty()
kill()
lseek()

open()
opendir
read()
readdir()
rewinddir()
sbrk()
settimeofday()
stat()
usleep()
wait()
write()

HAL File System


/

/dev

/dev/jtag_uart0

/mnt

/dev/lcd0

/mnt/rozipfs

/mnt/rozipfs/myfile1
p
y

Device names match those set in SOPC


builder.
Can
C only
l access nodes,
d
nott di
directories.
t i
All paths must be absolute (no current
directory)

53

Copyright 2005 Altera Corporation

/mnt/rozips/myfile21

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));

N lib also
Newlib
l supports C
C++ streams:

ofstream ofp(/dev/lcd0, ios::out); ofp << msg;

Existing code (outside the Nios world) uses


these interfaces. Porting is now much
easier.
easier
Use of existing standards means theres
nothing new to learn
learn.
54

Copyright 2005 Altera Corporation

HAL System Header File


SOPC Builder System Contents

system.h

System Library Settings


55

Copyright 2005 Altera Corporation

system.h

Contains macro definitions for system parameters,


including peripheral configuration, for instance:

Hardware configuration of the peripheral


Base address
IRQ p
priority
y ((if any)
y)
Symbolic name for peripheral

Does not include: static information, function


prototypes or device structures (unlike the old
prototypes,
excalibur.h)
Located in the syslib project directory
Rarely necessary to include it explicitly in your
application code, which improves rebuild time

56

Copyright 2005 Altera Corporation

system.h - example

Defines system settings and peripheral configurations:


Replaces excalibur.h (from Nios)

/*
* system configuration
*
*/

.
.
.

#define ALT_SYSTEM_NAME "std_1s10ES"


#define ALT_CPU_NAME "cpu"
#define ALT_CPU_ARCHITECTURE "altera_nios2"
#define ALT_DEVICE_FAMILY
ALT DEVICE FAMILY "STRATIX"
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

.
.
.
57

Copyright 2005 Altera Corporation

/
/*
* 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
BUTTON_PIO_HAS_TRI
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

HAL References

58

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

Copyright 2005 Altera Corporation

Reading/Writing Hardware in Nios

Nios Classic used volatile pointers to


access hardware e.g.
eg
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

59

Copyright 2005 Altera Corporation

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
IORD(BASE, REGNUM)
z Reads value at register
REGNUM offset from base
address
dd
BASE

BASE

REGNUM = 0
REGNUM = 1

BASE+2

REGNUM = 2
REGNUM = 3

IOWR(BASE,REGNUM,DATA)
z Writes DATA to register
REGNUM offset from base
address BASE
60

Copyright 2005 Altera Corporation

BASE+4

REGNUM = 4

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)

61

Copyright 2005 Altera Corporation

#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)

Data Cache

Memory space is mirrored (e.g. 2GB


addressable space)
Upper half is uncacheable
Lower
L
h
half
lf iis cacheable
h bl

All data variables are cached by default


This can cause memory coherency issues if
you are using a DMA controller in your design.

62

Copyright 2005 Altera Corporation

Data Cache

63

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

Interrupts

HAL API for ISRs - Functions


alt_irq_register()
lt i
i t ()
z

Associates interrupt with your ISR function.

alt_irq_disable_all()
alt irq disable all()
z

Disables all IRQs

alt_irq_enable_all()
z

Enables all IRQs

alt_irq_interruptible()
z

Used in ISR function body


body. Allows ISR to be interrupted by
higher priority IRQs.

alt_irq_non_interruptible()
z

64

U d tto make
Used
k ISR
ISRs uninterruptible
i t
tibl (d
(default
f lt b
behavior).
h i )

Copyright 2005 Altera Corporation

HAL API for ISRs - Useful Info


sample_isr ( void* context, alt_u32 id);

Write your ISR


(Follow prototype)

id == irq number (0 to 31)


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


Using alt_irq_register()

65

Copyright 2005 Altera Corporation

Sa p e Usage:
Sample
Usage
alt_irq_register ( 3, &some_data,
sample_isr);

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()

66

Keep it simple.
Use ISR to trigger execution of slow processing tasks outside of
p context
interrupt
Do NOT perform these tasks within ISR

References:
Exception Handling Chapter in Nios II Software Developers
Handbook

Copyright 2005 Altera Corporation

Nios II OS / RTOS Support


Product

Provider

Source
Code

Standards

TCP/IP
Stack

File
System

Other

RTCA/DO-178B

Opt.

Opt.

GUI
Flash

* MicroC/OS-II

Micrium

Yes

* Lightweight IP
TCP/IP Stack

Open Source

Yes

** Nucleus Plus

ATI/Mentor

Yes

CLinux

Open
p Source
(GPL)

Yes

KROS

KROS
Technologies

Yes

OSEK
ITRON

POSIX

<continued on next slide>


* Included in Nios II Development Kits
** Evaluation Version Included in Nios II Development Kits
67

Copyright 2005 Altera Corporation

C/OS-II
Support

Sockets API
IP, ICMP, UDP,
TCP
Opt.

Opt.

GUI, SNMP
RMON,
SPAN

Incl.

Many,
y,
inc.
FAT
and
JFFS2

Extensive
drivers and
middlewear,
inc USB,
IPSec, etc.

Opt.

Opt.

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

Th
ThreadX
dX

E
Express
Logic
L i

Y
Yes

O t
Opt.

O t
Opt.

USB

eCos

Open Source
(GPL with
excpetion)

Yes

Incl.

FAT,
JFFS2,
ROMFS
ROMFS,
RAMFS

Extensive
drivers and
middleware
, inc. USB,
IPSec, etc.

* Included in Nios II Development Kits


** Evaluation Version Included in Nios II Development Kits
68

Copyright 2005 Altera Corporation

POSIZ, uITRON,
EL/IX

Nios II MicroC/OS-II

69

Single-seat developers license included for free with


Nios II kits
Licensing fee reqd when you productize your system
Full source code included
Preemptive operating system
Small footprint
p
Code Size (min 5KB, max 20KB)
Data Space (min 1KB, max 5KB)
Supports Semaphores, and Mailboxes for task
synchronization

Copyright 2005 Altera Corporation

Nios II MicroC/OS-II

70

Copyright 2005 Altera Corporation

Lightweight IP for MicroC/OS-II

Plugs is being replaced with the


Lightweight
g
g 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
g
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

71

Copyright 2005 Altera Corporation

LWIP - Instantiation

72

Available as a Software Component

Copyright 2005 Altera Corporation

LWIP Configuration

73

Copyright 2005 Altera Corporation

Nios to Nios II Conversion

Hardware Must be Ported


Add Nios
Ni II processor and
d connections
ti
in
i
SOPC Builder

Software can be Used in Legacy SDK


Mode or Ported to HAL
See AN350 for full details

74

Copyright 2005 Altera Corporation

Nios to Nios II Conversion

Legacy Software Support


Minimal
Mi i l if any C
Code
d Ch
Changes R
Required
i d
No Access to Nios II IDE
Only
O l supported
t d for
f Standard
St d d and
d Economy
E
cores
New
N
peripherals
i h l (CFI flflash,
h sysid,
id etc)
t
) nott
supported
New software components (uC/OSII
(uC/OSII, LWIP)
not supported

75

Copyright 2005 Altera Corporation

Nios to Nios II Conversion

Full Port from Nios to Nios II


Requires
R
i
C code
d changes
h
No GERMS support
Provides
P id access HAL
HAL, uC/OSII,
C/OSII LWIP

76

Copyright 2005 Altera Corporation

Nios to Nios II Conversion

Porting Process:
Replace header files
z

Example: system.h for excalibur.h

Change
g API calls from SDK to HAL syntax
y
z

Example: nr_delay() is replaced with usleep()

Replace data types (int, char, etc..) with Nios II data


types (alt_u32,
(alt u32 alt
alt_u8,
u8 etc
etc))
Replace hardware access pointers with macros
z

Example:
p my
y_p
pio->data = 1 is replaced
p
with
IOWR_ALTERA_AVALON_PIO_DATA(PIO_BASE,1)

Take into account that *volatile pointers no longer


prevent data from being cached
77

Copyright 2005 Altera Corporation

Software Run & Debug

Copyright 2005 Altera Corporation

Software Run and Debug

Nios II Run
Nios
Ni II IDE JTAG D
Debugger
b
Nios II ISS
Nios II Console
Third Party tools

79

Copyright 2005 Altera Corporation

Running Code On A Target

80

Nios II IDE can be used to download code to target board

Copyright 2005 Altera Corporation

Running Code On A Target

81

Download messages, stdout and stdin appear in console


window

Copyright 2005 Altera Corporation

Nios II IDE Run Options

82

Nios II IDE > Run > Run

Copyright 2005 Altera Corporation

System ID Peripheral Revisited

When downloading code to a target, Nios II IDE computes


y
ID peripheral values from PTF file
expected System
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

83

Copyright 2005 Altera Corporation

Nios II IDE JTAG Debugger

Requirements
Must have JTAG
Debug Core enabled
in CPU

84

Copyright 2005 Altera Corporation

Nios II IDE Debug Perspective

Basic Debug
Run Controls
Stack View
Active Debug
Sessions

Double-click to
Doubleadd breakpoints

Memory View
Variables
Registers
Signals

85

Copyright 2005 Altera Corporation

Nios II IDE Debugger


Step Return
Step Over
Step Into
Step with Filters

Disconnect
sco ect
Terminate
Suspend
Resume
Resume
Run last Configuration
D b llastt C
Debug
Configuration
fi
ti

86

Copyright 2005 Altera Corporation

Nios II IDE Debugger

Standard debug
windows

87

memory
g
registers
Variables
breakpoints
expressions
signals

Copyright 2005 Altera Corporation

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


88

Copyright 2005 Altera Corporation

Nios II IDE: Debugger

89

Debug each CPU by selecting its program thread

Copyright 2005 Altera Corporation

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
unavailable.
Provides limited models of a few hardware
peripherals.
peripherals
z Timer
z UART
U
z Memory

90

(flash, SDRAM, on-chip, etc)

Copyright 2005 Altera Corporation

Nios II Instruction Set Simulator

91

Launch an ISS Debug session from the


Run Menu

Copyright 2005 Altera Corporation

Nios II Instruction Set Simulator

Targets .elf file to ISS and opens debugger


Application can then be debugged as normal

92

Copyright 2005 Altera Corporation

Customizing Views in the IDE GUI

93

You can turn windows on or off in either the


Run or Debug Perspective

Copyright 2005 Altera Corporation

Nios II SDK Shell

SDK shell is still provided with Nios II


Used to support legacy SDK flow (eg
(eg.. n2b,
n2b n2c) as
well as other general commands
Can launch terminal to interface to JTAG UARTs
nios2-terminal
And compile code
nios2-elf-gcc

94

Copyright 2005 Altera Corporation

Nios II / FS2 Console

95

Command line debugger

Copyright 2005 Altera Corporation

Nios II Console Launch

96

FS2 Console Launches then minimizes

Copyright 2005 Altera Corporation

Nios II Console

Allows for hardware


breakpoints and trace data
2 HWBPs and 16 Frames of OnChip Trace Included

97

Displays C Source,
A
Assembly,
bl Mi
Mixed
d

Copyright 2005 Altera Corporation

Nios II Debug Solutions


Product

Provider

Description

* Nios II IDE

Altera

IDE / Debugger
gg
JTAG Target
g 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
98

Copyright 2005 Altera Corporation

Features

Upgrades from FS2


(see www.fs2.com for details)
Feature

Nios II IDE

FS2 S/W
Upgrade

FS2 H/W
Upgrade

Hardware Execution
Breakpoints

Data Triggers

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)

Included

See FS2

See FS2

Trace (PC)

Cost

99

Copyright 2005 Altera Corporation

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

100

Copyright 2005 Altera Corporation

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


103

Copyright 2005 Altera Corporation

Simulation TestBench
Ethernet
MAC/PHY

Dev board
SRAM

Dev board
FLASH

Compact FLASH

SDRAM

Nios II Processor

Write
Data In ((32))
Data Out (32)

IRQ

Avalon S
Switch Fabric
c

Read

32-Bit
Nios II
Processor

IRQ #(6)

Clock

104

Reset

Copyright 2005 Altera Corporation

Tri-State
Bridge

Tri-State
Bridge

Compactt
C
Flash
PIOs

On Chip
ROM)

On Chip
RAM

Custom
Instruction

SDRAM
Controller

UART

User
Defined
Peripheral

User
Defined
Interface

User Device

User
Peripheral

I l d d
Included
Not Included

User Device

Address (32)

User Additions to Nios II TestBench

105

Copyright 2005 Altera Corporation

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 regenerate the Nios II
system

Running an RTL Simulation

Modify Nios II IDE System Library For Simulation:


Specify
p
y Program
g
Memory
y
Set Up As Simulation Only

106

Copyright 2005 Altera Corporation

Running an RTL Simulation

Checking the ModelSim only, no hardware support


button:
Leaves
L
caches
h uninitialized
i iti li d
Does not initialize the .bss section

107

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

Running an RTL Simulation

Launch ModelSim from Nios II IDE:


Highlight Software Project In C/C
C/C++ Projects panel
Right click
Run As Nios II ModelSim

108

Copyright 2005 Altera Corporation

Running an RTL Simulation

109

Copyright 2005 Altera Corporation

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
setup sim do
Simulation Scripts
s Compiles HDL source code and loads design
c Rebuilds memory contents based on software code
z

w
l
h
110

Includes changes since Nios II generation

Opens Wave
O
W
window
i d
with
ith useful
f l signals
i
l
Opens List window with useful signals
Displays help message describing scripts

Copyright 2005 Altera Corporation

Memory Device Simulation Models

Applies To The Following Nios II Memories


On Chip Memory (ROM or RAM)
SRAM
Flash Memoryy and now SDRAM

Include SDRAM Model


for Simulation

111

Copyright 2005 Altera Corporation

Memory Device Simulation Models

You can no longer initialize memories in the


SOPC Builder.
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

112

Copyright 2005 Altera Corporation

UART Simulation

Text is transmitted to
UART during simulation
Creates and saves txt file
containing UART tx
stream
t
Creates window to input
t t att simulation
text
i l ti run time
ti

Note: ModelSim Options are mutually exclusive

113

Copyright 2005 Altera Corporation

UART Simulation

114

Input is interactive or predefined


Output is shown and saved independently for
multiple UARTs

Copyright 2005 Altera Corporation

JTAG_UART Simulation

Note: ModelSim Options are mutually exclusive

115

Copyright 2005 Altera Corporation

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

Wave Window

116

Adds UART and CPU signals by default

Copyright 2005 Altera Corporation

SignalTap II Logic Analyzer

Up to 200 MHz
Multi-Analyzer
y
Support
pp
1,024 Channels
128K Samples
10 T
Trigger
i
L
Levels
l
No Probes!
Can be used
simultaneously with the
Nios II IDE debugger and
the FS2 console!

Capture the state of internal nodes


I
In-system,
t
att ffull
ll system
t
speeds
d
117

Copyright 2005 Altera Corporation

SignalTap II Logic Analyzer

118

Copyright 2005 Altera Corporation

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
g
Simplicity
Synchronous operation

Transfer Types

121

Slave Transfers
Master Transfers
Streaming Transfers
Latency-Aware Transfers
Burst Transfers

Copyright 2005 Altera Corporation

Switch
PIO

Address (32)

32-Bit
Nios II
Processor

Read
Write
Data In (32)
Data Out (32)

IRQ
IRQ #(6)

ROM
(with Monitor)

UART

Ti
Timer

Ava
alon Switch Fabric

Nios II Processor

LED PIO

7-Segment
LED PIO

PIO-32
UserDefined
Interface

Avalon Switch Fabric

Custom-Generated for Peripherals


Contingencies
g
are on a Per-Peripheral
p
Basis
System is Not Burdened by Bus Complexity

SOPC Builder Automatically Generates

122

Arbitration
Address Decoding
Data Path Multiplexing
Bus Sizing
Wait-State Generation
Interrupts

Copyright 2005 Altera Corporation

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

123

Copyright 2005 Altera Corporation

Avalon Slave Ports

Respond to Transfer Requests from Avalon


Switch Fabric
Transfer Types
Fundamental Read
Fundamental Write

Transfer Properties

124

Wait States
Latency
Streaming
g
Burst

Copyright 2005 Altera Corporation

Slave Read Transfer

0 Setup
Cycles
y
0 Wait Cycles

clk

address,be_n

address, be_n

readn
chipselect
readdata

125

Copyright 2005 Altera Corporation

readdata

Slave Read Transfer with Wait States

1 Setup Cycle
1 Wait Cycle

B C

clk
address,be_n

address, be_n

chipselect
Tsu
readn
readdata

126

Copyright 2005 Altera Corporation

readdata

Slave Write Transfer

0 Setup
Cycles
y
0 Wait Cycles
0 Hold Cycles

clk
address,be_n
writedata
writen
chipselect

127

Copyright 2005 Altera Corporation

address, be_n
writedata

Slave Write Transfer with Wait States

1 Setup Cycle
0 Wait Cycles
1 Hold Cycle

B C

clk
address,be_n
writedata
writen
chipselect

128

Copyright 2005 Altera Corporation

address, be_n
writedata

Multiple Clock Domains Supported


Master
Clock Domain 1

Master
Clock Domain 2

Master
Clock Domain 1

Avalon Switch Fabric

CDX
CDX
Arbiter

Avalon Switch Fabric


Slave
Clock Domain 2

Slave
Clock Domain 2

Slave
Clock Domain 2

Slave
Clock Domain 2

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


129

Copyright 2005 Altera Corporation

Multi-Clock Domain Support


Master
Clock
Domain 2

Master
Clock
Domain 1

CDX

CDX

Master
Clock
Domain 1

Arbiter

CDX

Arbiter

Avalon Switch Fabric

Slave
Clock Domain 3

CDX = Clock Domain Crossing Logic


130

Copyright 2005 Altera Corporation

Master
Clock
Domain 1

Avalon Switch Fabric

Slave
S
a e
Clock Domain 2

User-Defined Custom Peripherals

What if I need to add a peripheral not included with the


y
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

131

Copyright 2005 Altera Corporation

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
User
A bit
Arbiters
G
Generated
t d for
f You
Y
Logic

Concentrate Effort on
Peripheral Functionality!
132

Copyright 2005 Altera Corporation

New Component Editor

133

Copyright 2005 Altera Corporation

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
CPU

Nios II
CPU

I/O

Nios II System
Module

134

Copyright 2005 Altera Corporation

I/O
I/O

I/O
Interface
to User
Logic

/O
I/O
Avalon

Avalon

I/O

External
User
Peripheral

Nios II System
Module

Internal
User
Peripheral

Create External Component Interface

135

To communicate with
off-chip
off
chip peripherals
Base interface type
on data sheet

Copyright 2005 Altera Corporation

AMD29LV065AD CFI Flash Chip

Or Add HDL Files

136

For peripheral that has been encoded for FPGA

Copyright 2005 Altera Corporation

Tri-State Peripherals

Require Tri-State Bridge

Interface
e to
User Lo
ogic

Tri-Sta
ate
Bridge
e

Nios II
Processor

Avalon

Available as an SOPC Builder component


p
Off Chip
Peripheral

FPGA

137

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

Define Component Signals

Automatically populates port


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

138

Copyright 2005 Altera Corporation

Define Interface for Each Signal Type

Choose interface type


Register Slave uses native
alignment Memory Slave uses
alignment,
dynamic alignment

Control Read and Write Timing


Add
dd wait
ata
and
d hold
o d states View
e
waveforms

139

Copyright 2005 Altera Corporation

Address Alignment Narrow Slave


Peripheral Registers

140

32

Av
valon

32-Bit
Nios II
Processor

8 Bit
Peripheral

Base

aa

Base + 0x1

bb

Base + 0x2

cc

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


LD from Base + 0x0:
LD from Base + 0x4:
LD from Base + 0x8:

Copyright 2005 Altera Corporation

(set as Avalon Register Slave)


uu uu uu aa
uu uu uu bb
uu uu uu cc

Address Alignment Narrow Master

141

Memory Contents

32

Av
valon

32-Bit
Nios II
Processor

64

64 Bit
Memory

Base

77 66 55 44 33 22 11 00

Base + 0x8

ff ee dd cc bb aa 99 88

Base + 0x16

?? ?? ?? ?? ?? ?? ?? ??

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

Add Software Files

142

ie. Header files and drivers

Copyright 2005 Altera Corporation

Add Software Files

143

Header file and drivers can also be added directly to


Application Project

Copyright 2005 Altera Corporation

Create Component Wizard

Publish and create a wizard for your component

144

Copyright 2005 Altera Corporation

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

Add Component to SOPC System

145

Default location is the User Logic folder

Copyright 2005 Altera Corporation

Intel PXA255 Example

146

Copyright 2005 Altera Corporation

VLIO as an Avalon Master Port VLIO

147

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

Relevant Verilog Code to Relevant Verilog


C d to
Code
t Implement
I
l
t

148

Copyright 2005 Altera Corporation

Lab 4
Adding
g A User Peripheral
p
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

Dramaticallyy Boost Processing


g Performance
With no Increase in fMAX required

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

151

Copyright 2005 Altera Corporation

Custom Instructions

Augment Nios II Instruction Set


Mux User Logic
g Into ALU Path of Processor Pipeline
p

152

Copyright 2005 Altera Corporation

Several Levels of Customization


Optional Interface to FIFO, Memory, Other Logic

dataa
datab

32

result

Combinatorial
32

clk

32

clk_en

Multi-Cycle

reset

done

start
n

Extended
8

readra

5
5

153

Copyright 2005 Altera Corporation

Internal
R i t Fil
Register
File

readrb
writerc

Custom Instructions

Integrated Into Nios II Development Tools


SOPC Builder design tool handles op-code
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

154

Copyright 2005 Altera Corporation

Custom Instructions Tab

155

Enabled from the Custom Instructions tab in the


Nios II CPU settings
g in SOPC Builder

Copyright 2005 Altera Corporation

Custom Instructions Tab

Import logic for the custom instruction


Custom Instruction module can be of following
formats:

156

VHDL
Verilog HDL
EDIF
Quartus Block Diagram (.bdf)

Copyright 2005 Altera Corporation

Combinatorial Custom Instructions

Port list
All Custom Instruction Modules need these ports
z

157

Port names must match exactly

Copyright 2005 Altera Corporation

Multi-Cycle Custom Instructions

Port list for Multi-Cycle Custom Instructions


Must have all of these ports with exact names

158

Copyright 2005 Altera Corporation

Extended Custom Instructions

159

Uses n[7..0] port to select an operation to perform.

Copyright 2005 Altera Corporation

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]

reada

Custom
Logic

writec
c[4..0]

a[4..0]

160

Copyright 2005 Altera Corporation

Software Interface - C

NIOS II IDE generates macros automatically during build process

Macros defined in system.h


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;
}

161

Copyright 2005 Altera Corporation

Assembly Language Interface

Assembler syntax for the custom instruction:


custom N
N, rC
rC, rA
rA, rB

Custom
instruction
opcode
number

Destination
register
for result

Operand 2

Two Examples:
custom 0, r6, r7, r8
custom 3, c1, r2, c4

162

Operand 1

Copyright 2005 Altera Corporation

r = Nios II processor
register
c = Custom instruction
internal register

Why Custom Instruction?

Reduce Complex Sequence of Instructions to One Instruction


Example: Floating Point Multiply
float a
a, b
b, result
result_slow,
slow result
result_fast;
fast;
result_slow = a * b;
/* Takes 266 clock cycles */
result_fast = ALT_CI_fpmult(a,b); /* Takes 6 clock cycles*/

Significantly Faster!

Typical Flow
Profile Code
Identify Critical Inner Loop
Create Custom Instruction Logic
z

Replace One or All Instructions in Inner Loop

Import Custom Instruction Logic into Design


Call Custom Instruction from C or Assembly

163

Copyright 2005 Altera Corporation

Custom Instruction vs Peripheral

Custom Instruction can execute in a single cycle


No overhead for call to custom Hardware
L0
L1

Custom
Instruction

L0

Access to same hardware as peripheral takes


multiple cycles
Write DataA, then write DataB, and finally read Result
Peripheral memory map
0x408
0x404
0x400
L0
L1

164

Copyright 2005 Altera Corporation

Result
DataB
DataA

Custom
Peripheral

L0

Multi-Cycle Custom Instructions


Processor stalls while awaiting result

Niios Clock C
Cycles

Clock
Cl k cycles
l =3

custom

DataA

DataB

REG

----Next Instr

REG

Result

165

Copyright 2005 Altera Corporation

Cu
ustom Insttruction

Pipelined Custom Instructions


Result not always needed for each input
Clock
Cl k C
Cycles
l =1
Route start sig to reg clk_en

Nios C
Clock Cycle
es

custom

DataA

DataB

REG

custom
t
custom
custom

REG

custom
Next Instr
Result

166

Copyright 2005 Altera Corporation

Cu
ustom Insttruction

Accelerating CRC

Implementing the shift and XOR for each


bit takes many clock cycles ~50
Software algorithms tend to use look up
t bl tto pre-compute
tables
t each
h byte
b t
Parallel Hardware is fastest

167

Copyright 2005 Altera Corporation

xor/shifft

in(0)

xor/shifft

reg

in(14)

xor/shifft

in(15)

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 crc
ALT_CI_CRC(0xFFFF,1);
// run crc
ALT_CI_CRC(word,0);

Control
D A(31 0)
DataA(31-0)

Copyright 2005 Altera Corporation

Data in
CRC Reg

DataB(0)

168

CRC
Custom Instruction

Init / nRun

Result(15-0)

Multi-Masters and Direct


Memory Access (DMA)

Copyright 2005 Altera Corporation

Traditional Multi-Masters

Direct Memory Access (DMA)


Processor
P
Waits
W it For
F Bus
B During
D i DMA
Masters

Control
C
t l
direction

System CPU
(Master 1)

System
B l
Bottleneck
k

100Base-T
(Master 2)

Arbiter Determines
Which Master Has
Access To Shared
Bus

DMA
Bus
B Arbitor
Arbiter
A bit
DMA

System Bus

Slaves

170

Program
Memory
y

Copyright 2005 Altera Corporation

I/O
1

I/O
2

Data
Memory
y

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
M lti l M
Master
t T
Transactions
ti
C
Can O
Operate
t Si
Simultaneously
lt
l
z

As long as they dont access the same slave in the same bus bycle

I/O Devices Can be Grouped Based on Bandwidth Requirement

T d Off
Trade-Off
Hardware Resource Usage Increases

Uses Fairness
Arbitration

automatically
generated by
SOPC Builder

CPU 0

Masters

DMA

CPU 1

System
Switch
Fabric
Arbiter

Slaves

171

Program
M
Memory
0

I/O

Copyright 2005 Altera Corporation

Data
M
Memory
0

Arbiter
Display
C t l
Control

Data
M
Memory
1

Custom
F
Function
ti

Program
M
Memory
1

DMA Peripheral

Provides Bus Master Capability to Any Nios II


p
Peripheral
FIFO Depth = 2
DMA Peripheral
Master Port
1

FIFO

Start Addr

Start Addr

# Bytes

# Bytes

Addr Incr

Addr Incr
Direction
Control Port

172

Master Port
2

Copyright 2005 Altera Corporation

Data Flow with DMA Peripheral


Master 2
DMA

Master 1
(Nios II CPU)
I

Avalon

Avalon

Arbiter

Program
Memory

173

I/O
1

I/O
2

Copyright 2005 Altera Corporation

Data
Memory
1

SPI

Accelerate Software Execution

Use custom hardware peripheral with DMA

Avalon
Switch
Fabric

Program
Memory

174

Copyright 2005 Altera Corporation

Accelerator

DMA

Processor

DMA

Processor & Accelerator Run Concurrently


More Work Per Clock
Lower fMAX, Power, Cost

Arbiter

Arbiter

Data
Memory

Data
Memory

Accelerate Software Execution

Example: CRC Algorithm (64 Kbytes)


25,000,000

Cllock Cycles

20,000,000
,
,
15,000,000

27
Times
Faster

10,000,000
5,000,000

530
Times
Faster

0
Software Only

175

Copyright 2005 Altera Corporation

Custom
Instruction

Hardware
Accelerator

Custom Streaming Slave Peripherals

For using DMA with other slow peripherals


Example:
E
l UART

Adds up to three outputs to Avalon Slave


dataavailable
readyfordata
endofpacket

adress
control

Custom
Streaming
Sla e
Slave
Peripheral

writedata
readdata
dataavailable
Readyfordata
endofpacket

176

Copyright 2005 Altera Corporation

Av
Avalon

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
p
Usage not defined
DMA can be optionally set to end transfer

177

Copyright 2005 Altera Corporation

Custom Master Peripherals

Can integrate DMA function


Eg.
Eg VGA that takes data from memory directly

Simpler than Slave peripherals


Assert outputs
p
until waitrequest
q
is low

Transaction are between Master and Avalon,


not Slave
address

Custom
Master
Peripheral

writedata
readdata
waitrequest

178

Copyright 2005 Altera Corporation

Avalo
on

control

Master Read Transfer

Assert addr, be, read


Wait
W it for
f waitrequest
it
t = 0
Read in Data
End of transfer

179

Copyright 2005 Altera Corporation

Master Write Transfer

Assert addr, be, read


Assert
A
t Write
W it Data
D t
Wait for waitrequest = 0
End of transfer

180

Copyright 2005 Altera Corporation

Avalon Master-Slave Connections

181

View => Show Master Connections


Observe and configure Avalon connections

Copyright 2005 Altera Corporation

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
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

182

Copyright 2005 Altera Corporation

PCI DMA
2 shares

Set Arbitration Priority

183

View => Show Arbitration Priorities

Copyright 2005 Altera Corporation

Avalon Arbitration Behavior


Master A Shares = 4
Master A

Master B

Master B Shares = 2
Arbiter
Slave

Arbiter (continuous accesses)

Master A
Master B

184

Copyright 2005 Altera Corporation

L b5
Lab
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


g
used byy yyour design
There is a connection between FPGA and MAX device to
force reconfiguration
Active
A ti low,
l
pulled
ll d hi
high
h

187

Assignments -> Device


For Stratix devices, be sure to set Dual Purpose pins to
Use as Regular IO

Copyright 2005 Altera Corporation

Clock Distribution

SDRAM

Nios II

PLL

Zero Skew
w
Buffer

CLK in
((50 MHz))

Zerro Skew
Buffer
B

FPGA

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

188

See board schematic and ref design

Copyright 2005 Altera Corporation

Hardware Configuration Process


8 MB Flash

Flash Configuration
o FPGA
G images
ages
Two
z

0x600000

MAX Device Loads User Image into FPGA


If Thi
This Fails
F il MAX Device
D i Loads
L d Safe
S f Image
I
Failure includes no user image present

Upon press of Safe Config


z
189

MAX Device Loads Safe Image into FPGA

Copyright 2005 Altera Corporation

Stratix

User FPGA
Image

MAX EPM7128 Configures FPGA from


Flash
Upon power up or press of Reset Config
z

Data

Addrress

Safe Image
User Image

0x700000

Safe FPGA
Image

MAX

Flash Memory Configuration


8 MB Flash
0x700000

0x600000

Safe FPGA
Image & S/W
User FPGA
Image

Data

Stratix

0x500000

Addres
ss

0x400000

SRAM
0x300000

0x200000

0x100000

0x000000
190

Copyright 2005 Altera Corporation

User
Software

Configuration of FPGA From Flash


0x1000000

Data
0xE00000

8 MB RAM

0xC00000

Stratix

0xA00000

Nios II

0x800000

0x600000

Safe FPGA Image


& S/W
User FPGA Image

8 MB Flash

0x400000

0x200000

Application
Application
Code
Code
Start--up Code
Start

Boot Copier
191

0x000000
Copyright 2005 Altera Corporation

Controller

Loading RAM
0x1000000

Data
0xE00000

8 MB RAM

Dynamic
Memory

0xC00000

0xA00000

0x800000

0x600000

Stratix
Application
pp
Code
Start--up Code
Start
Safe FPGA Image
& S/W
User FPGA Image

8 MB Flash

0x400000

0x200000

Application
Code
Start--up Code
Start

Boot Copier
192

0x000000
Copyright 2005 Altera Corporation

Nios II

Boot Copier
Use

Flash for Program


Storage

Running from Flash is slow

Data

Nios

For Custom Boards:


((see again
g
Nios II Flash
Programmer User Guide)

Must create your own flash


programmer design to transport data
to the flash on yyour board

193

Copyright 2005 Altera Corporation

Addrress

II IDE Automatically
Prepends Boot Copier to
Program Code

if Reset Address is in Flash and


Program Memory is in RAM

Stratix

User
Software

SRAM

8 MB Flash

Boot Copier
p
my_sw.elf

my_sw.flash
fl h

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:


Two-step
Send Flash Programmer Design
Send Flash Content
Flash Content

194

Copyright 2005 Altera Corporation

Nios II Flash Programmer

Flash Programmer Design contains

Nios II CPU
JTAG UART
Active serial memory interface
Tri state bridge
Tri-state
CFI-compatible flash interface
System ID peripheral on-chip memory for firmware and buffers

Flash Content can include:


FPGA hardware configuration image
Software
S ft
content
t t
Arbitrary content

195

Copyright 2005 Altera Corporation

Nios II Flash Programmer

Can program Flash from Nios II IDE or command line


Nios II IDE is recommended method

196

Copyright 2005 Altera Corporation

Nios II Flash Programmer

Command Line Utilities


elf2flash
sof2flash
Bin2flash
elf2hex
nios2-flash-programmer
p g

(see Nios
Nios II Flash Programmer User Guide
Guide for details)
197

Copyright 2005 Altera Corporation

Instantiating Flash in Target System

198

Must set target board to appropriate development kit

Need CFI ((Common Flash Interface)) Flash Memory


y

EPCS Serial Flash Controller reqd if booting from EPCS device

Copyright 2005 Altera Corporation

Flash Programmer Design

What if I Have a Custom Board?


Import board settings into the SOPC Builder using
mk_target_board script
z

Specify flash devices and designator numbers

Clock frequency

Device family

C
Create fflash programming design in SOPC
SO C Builder
based on .PTF generated from above script
Generate .SOF
SOF file for flash design

199

See Nios II Flash Programmer User Guide for details

Copyright 2005 Altera Corporation

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


p
./restore_my_flash

200

Follow the scripts instructions

Copyright 2005 Altera Corporation

Lab 6
The Flash Programmer
10 mins
Copyright 2005 Altera Corporation

Thank You

Copyright 2005 Altera Corporation