Using The NicheStack TCP-IP Stack - NIOS II Edition - TUTORIAL
Using The NicheStack TCP-IP Stack - NIOS II Edition - TUTORIAL
Tutorial
Subscribe
Copyright 2011 Altera Corporation. All rights reserved. Altera, The Programmable Solutions Company, the stylized Altera logo, and specific device designations
are trademarks and/or service marks of Altera Corporation in the U.S. and other countries. All other words and logos identified as trademarks and/or service marks
are the property of Altera Corporation or their respective owners. Altera products are protected under numerous U.S. and foreign patents and pending applications,
maskwork rights, and copyrights. Altera warrants performance of its semiconductor products to current specifications in accordance with Altera's standard
warranty, but reserves the right to make changes to any products and services at any time without notice. Altera assumes no responsibility or liability arising out of
the application or use of any information, product, or service described herein except as expressly agreed to in writing by Altera. Altera customers are advised to
obtain the latest version of device specifications before relying on any published information and before placing orders for products or services.
Contents
Additional Information
Document Revision History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Info1
How to Contact Altera . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Info1
Typographic Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Info1
June 2011
Altera Corporation
iv
Contents
This tutorial introduces you to the Nios II Software Build Tools (SBT) for Eclipse
using the MicroC/OS-II and NicheStack TCP/IP Stack development flow. It shows
you how to use the Nios II SBT for Eclipse to create a new Nios II project that
configures, builds, and runs a MicroC/OS-II and NicheStack TCP/IP Stack program
on an Altera development board.
Introduction
This tutorial familiarizes you with the NicheStack TCP/IP Stack Nios II Edition
(NicheStack TCP/IP Stack) software component. The tutorial covers the following
topics:
Using the Nios II SBT for Eclipse to develop programs with the NicheStack
TCP/IP Stack software component
The Nios II SBT for Eclipse offers software designers a rich development platform for
Nios II applications. The Nios II SBT for Eclipse contains the MicroC/OS-II RTOS and
the NicheStack TCP/IP Stack software component, providing designers with the
ability to quickly build networked embedded systems applications for the Nios II
processor. This tutorial provides step-by-step instructions for building a simple
program based on the MicroC/OS-II RTOS and NicheStack TCP/IP Stack networking
stack.
This tutorial describes C software files that demonstrate communication with a telnet
client on a development host PC. The telnet client offers a convenient way of issuing
commands over a TCP/IP socket to the Ethernet-connected NicheStack TCP/IP Stack
running on the Altera development board with a simple TCP/IP socket server
example. The socket server example receives commands sent over a TCP/IP
connection and turns LEDs on and off according to the commands. The example
consists of a socket server task that listens for commands on a TCP/IP port and
dispatches those commands to a set of LED management tasks.
1
The Nios II target system does not implement a full telnet server.
f For more information about MicroC/OS-II for the Nios II processor, refer to the
MicroC/OS-II Real-Time Operating System chapter of the Nios II Software Developers
Handbook.
f For more information about NicheStack TCP/IP Stack initialization and configuration
for the Nios II processor, refer to the Ethernet and the NicheStack TCP/IP Stack Nios II
Edition chapter of the Nios II Software Developer's Handbook.
June 2011
Altera Corporation
12
RJ-45 connected Ethernet cable on the same network as the PC development host
To complete this tutorial, you must install the Nios II SBT for Eclipse and you must
connect your Altera development board to a host PC on the Ethernet and USB/JTAG
ports. For hardware setup instructions, refer to Appendix A, Hardware Setup Details.
Tutorial Files
The files for this tutorial are available in two .zip files on the Altera website. One file
contains the hardware design example and the other contains the software program
files.
Software Files
The NicheStack tutorial software files .zip file (next to the link to this document on the
Literature: Nios II Processor page of the Altera website) contains the software
program files to use with this tutorial. Download and unzip the file in a directory of
your choosing. The tutorial uses <tutorial_files> to refer to this directory.
13
alt_eeprom.cContains utilities that read, write, dump, and fill the contents of the
EEPROM devices.
alt_eeprom.hDefines utilities that read, write, dump, and fill the contents of the
EEPROM devices.
June 2011
Altera Corporation
14
On Windows, on the Start menu, point to All Programs > Altera > Nios II EDS
<version>, and click Nios II <version> Software Build Tools for Eclipse.
On Linux, open a Nios II Command Shell and type eclipse-nios2 r.
2. On the File menu, point to New and click Nios II Application and BSP from
Template. The first page of the Nios II Application and BSP from Template
wizard appears.
3. Under Target hardware information, browse to and open the
<tutorial_files>\niosii_ethernet_standard_<board>\eth_std_main_system.sopcin
fo SOPC Information File (.sopcinfo). The SOPC Information File name box
contains the path to the .sopcinfo and the CPU name box contains the name of one
of the available Nios II processors as defined in SOPC Builder. The hardware
design of the tutorial contains a single processor, so the software automatically
selects the single processor.
4. In the Project name box, type niosII_simple_socket_server_0. The Project
location fills in for you automatically.
5. Verify Use default location is on.
15
7. Click Next. The second page of the Nios II Application and BSP from Template
wizard appears.
8. Select Select an existing BSP project from your workspace.
9. Click Create. The Nios II Board Support Package dialog box appears.
10. In the BSP name box, type niosII_simple_socket_server_0_bsp.
11. In the Operating system list, select Micrium MicroC/OS-II.
June 2011
Altera Corporation
16
12. Click Finish. The wizard creates a BSP project and closes the Nios II Board
Support Package dialog box.
13. Click Finish. The wizard creates an application project.
1
If the wizard prompts you to open the Nios II perspective, click Yes. If the
Finish button is grayed out, click Cancel to close the previous GUI. Repeat
Step 2 - 8, select niosII_simple_socket_server_0_bsp, and click Finish.
14. With a file management tool (such as Windows Explorer), drag and drop all the
Nios II Simple Socket Server source files and folders from the
<tutorial_files>\nichestack_tutorial folder to the niosII_simple_socket_server_0
folder in the Nios II SBT for Eclipse Project Explorer view.
15. Select Copy files and folders in the File and Folder Operation dialog box, and
click OK.
Figure 12 shows the application and BSP projects in the Project Explorer view at this
point in the tutorial.
Figure 12. New Projects in the Nios II Perspective
17
June 2011
Altera Corporation
18
3. On the Main tab (Settings tab in v9.1 and earlier), expand Advanced in the left
pane, and click ucosii. Settings for the MicroC/OS-II RTOS appear, as shown in
Figure 14.
Figure 14. MicroC/OS-II RTOS Options
The MicroC/OS-II kernel is highly configurable. The options that you set in this
dialog box determine which MicroC/OS-II options are included in the binary
image. Examine the configurable options by clicking each of the options categories
under ucosii in the left pane. For this tutorial, do not change any of the settings.
1
Although this example software design does not use all the MicroC/OS-II
system calls, the NicheStack TCP/IP Stack internally uses many more
MicroC/OS-II system calls, more than the Nios II Simple Socket Server
application itself uses. Do not disable any system calls unless you need to
be very conservative with your code size requirements. You must reenable
system calls that you try to disable if the link stage of the build fails with
unresolved symbols.
19
f For more information about the various MicroC/OS-II features, refer to the
MicroC/OS-II Real-Time Operating System chapter in the Nios II Software
Developer's Handbook.
4. On the Software Packages tab, turn on Enable for the altera_iniche software
package, as shown in Figure 15.
Figure 15. NicheStack TCP/IP Stack Options
June 2011
Altera Corporation
Take care when choosing your default IP and gateway addresses. Some
secure router configurations block DHCP request packets on local
subnetworks such as the 192.168.X.X subnetwork. If you do encounter
problems, try using 0.0.0.0 as your default IP and gateway addresses.
110
6. On the Linker Script tab, verify that the Linker Region Name is sdram for all
enabled Linker Section Names in the table under Linker Section Mappings, as
shown in Figure 16. If not, click each current Linker Region Name and select
sdram from the list that appears.
Figure 16. BSP Editor Linker Script Tab
7. Click Generate. When prompted to save your changes, click Yes, Save.
8. Click Exit on the File menu to close the BSP Editor and return to the Nios II SBT for
Eclipse.
9. In BSP project, you must add -DTSE_MY_SYSTEM to your defined symbols.
Right-click the niosII_simple_socket_server_0_bsp project and click Properties.
The Nios II BSP Properties page appears. On the left pane, click Nios II BSP
Properties. In the Defined symbols box, type -DTSE_MY_SYSTEM. Click Apply and
OK.
111
June 2011
Altera Corporation
112
1. Configure the FPGA on the development board by performing the following steps:
a. On the Nios II menu, click Quartus II Programmer.
b. In the Quartus II Programmer dialog box, on the File menu, click Open.
c. Browse to and open the <tutorial_files>\niosii_ethernet_standard_<board>\
niosii_ethernet_standard_<board>.sof SRAM Object File (.sof). Information
for the file appears in the Quartus II Programmer dialog box.
d. Verify Program/Configure is on, as shown in Figure 17.
Figure 17. Quartus II Programmer Dialog Box
f. On the File menu, click Exit to close the Quartus II Programmer and return to
the Nios II SBT for Eclipse. If you receive a message that asks if you want to
save the changes to the chain1.cdf file, click No.
2. In the Nios II SBT for Eclipse, select the niosII_simple_socket_server_0 project in
the Project Explorer view.
3. On the Run menu, point to Run As and click Nios II Hardware to build the
program, download it to the board, and run it.
113
If the Run Configurations dialog box appears, click the Target Connection
tab. Then click Refresh Connections and Apply until a board connection
establishes. After the board connection is established, click Run.
The build process takes several minutes. After the build process completes, the Nios II
SBT for Eclipse downloads the executable program to your development board.
f For additional information about using the Nios II SBT for Eclipse to build projects,
set up run configurations, and download programs to the board, refer to the Getting
Started with the Graphical User Interface chapter of the Nios II Software Developers
Handbook.
LED
LED0
D23
The Nios II Console view displays a message with the default IP address as
configured in niosII_simple_socket_server.h. If DHCP is enabled, the DHCP
server-supplied IP address displays a message that indicates the DHCP client for the
Ethernet interface acquires a DHCP IP address.
The message Nios II Simple Socket Server starting up displays when the
NicheStack TCP/IP Stack is ready to accept commands.
After the NicheStack TCP/IP Stack is ready, you can start a telnet session to interact
with the stack. To start a telnet session, follow these steps:
1. From your operating system, open a command shell.
1
2. Type the following command, specifying either the static IP address or the DHCP
server-provided IP address:
telnet <IP address> 30 r
June 2011
Altera Corporation
114
115
Figure 19 shows the corresponding output that appears in the Nios II Console view.
Figure 19. Nios II Console Output During Telnet Session
To test the functionality of the Nios II Simple Socket Server, enter the following
commands in the telnet session:
1. Type <n> r, where <n> is a number from one through nine, to change the blink rate
of the LED on your board.
2. Repeat step 1 several times, varying the number, to see the pulse rate change.
3. Type Q r to terminate the test. The socket connection on the development board
terminates and the telnet command exits.
June 2011
Altera Corporation
116
Name
SSS
LED
OS
117
Software Architecture
The onion diagram in Figure 110 shows the architectural layers of a Nios II
MicroC/OS-II software application.
Figure 110. Layered Software Model
Application
cific system initia
e
lizat
on-sp
ion
icati
l
p
Stack software
P
I
/
Ap
P
c om
TC
k
c
p
on
ta
MicroC/OS-II
en
eS
t
ch
i
N
HAL API
So
ftwar
e device driver
s
Nios II processor
system hardware
Software
Hardware
Each layer encapsulates the specific implementation details of that layer, abstracting
the data for the next outer layer. The following list describes each layer:
June 2011
Nios II processor system hardwareThe core of the onion diagram represents the
Nios II softcore processor and hardware peripherals implemented in the FPGA.
Software device driversThe software device drivers layer contains the software
functions that manipulate the Ethernet and hardware peripherals. These drivers
know the physical details of the peripheral devices, abstracting those details from
the outer layers.
MicroC/OS-IIThe MicroC/OS-II RTOS layer provides multitasking and intertask communication services to the NicheStack TCP/IP Networking Stack and the
Nios II Simple Socket Server.
Altera Corporation
118
Figure 111 shows the structure of the design example described in Introduction on
page 11. The sections following the figure describe the tasks in the figure.
Figure 111. Nios II Simple Socket Server Data Flow Diagram
LED
Nios II
Simple Socket
Server Task
OSQPost
OSQPend
Q 3 2 1
LED
Management
Task
OSMboxPost
OSMboxAccept
LED Blink
Task
NicheStack
Timer
Task
NicheStack
TCP/IP
Task
Monitor
PHY
Task
The figure shows the state of the system after initialization. When the NicheStack
TCP/IP Stack software component receives an Ethernet packet that contains an LED
command sent from a telnet client program, the NicheStack TCP/IP Stack processes
the incoming Ethernet packet with the TCP/IP protocol and presents the data packet
to the socket server task using the sockets API. The LED management tasks then
extract and post the LED command contained in the data packet to the LED command
queue for processing.
119
MicroC-OS/II Resources
This section describes the tasks, queue, event flag, and semaphores that implement
the Nios II Simple Socket Server application.
Tasks
Table 13 lists the MicroC/OS-II tasks that implement the Nios II Simple Socket
Server application.
Table 13. MicroC/OS-II Tasks for the Nios II Simple Socket Server
Task
Description
SSSInitialTask()
SSSNiosIISimpleSocketServerTask()
LEDManagementTask()
LEDBlinkTask()
SSSMonitorPhyTask()
Monitors the status of a single network PHY and maintains the network
connection.
The application creates the tasks listed in Table 13. The NicheStack TCP/IP
Networking Stack creates two additional software component layer tasks: a main task
that operates the networking stack, and a time-keeping task that the main task uses.
The application creates the NicheStack TCP/IP Stack main task (tk_netmain) in the
netmain() function with a priority of TK_NETMAIN_TPRIO. The application creates the
time-keeping task (tk_nettick) in the netmain() call with a priority level of
TK_NETTICK_TPRIO. For more information about these tasks, and how to set their
priorities and stack sizes, refer to Important NicheStack TCP/IP Stack Concepts on
page 122.
June 2011
Altera Corporation
120
SSSLEDCommandQ
SSSLEDCommandQ is a MicroC/OS-II message queue that sends commands from the
simple socket server task to the Altera development board LED control task,
LEDManagementTask().
SSSLEDFreqMailbox
SSSLEDFreqMailbox is the handle to the MicroC/OS-II LED pulse rate mailbox.
The mailbox passes an LED blink rate between the LED control task, named
LEDManagementTask(), and the LED task responsible for blinking the development
board LED, named LEDBlinkTask(). The LEDManagementTask() passes the pulse
rate in response to a command sent from SSSNiosIISimpleSocketServerTask()
when the blink the LED command comes over the TCP/IP socket.
You can use the task SSSInitialTask() in your own MicroC/OS-II and NicheStack
TCP/IP Stack networking application.
121
Calls OSTimeSet()
Calls alt_uCOSIIErrorHandler()
The Micriums MicroC/OS-II examples suggest using a single task to initialize the rest
of the application. This technique ensures that stack checking initializes enabled
features correctly. In this tutorial, the SSSInitialTask() task (located in iniche_init.c)
initializes the NicheStack TCP/IP Stack software, initializes the operating system data
structures, and starts any user-defined networking tasks and regular tasks. The
SSSInitialTask()task performs the following specific actions:
June 2011
Creates a socket to serve a TCP/IP connection, binds to the socket, and listens for
TCP/IP connection requests from a client.
Altera Corporation
122
LEDBlinkTask() blinks the LED based on the pulse rate the LEDManagementTask()
task sets in the MicroC/OS-II SSSLEDFreqMailbox mailbox.
Error Handling
A suite of error-handling functions defined in alt_error_handler() check error
handling of the Nios II Simple Socket Server application, NicheStack TCP/IP Stack,
and MicroC-OS/II system call error-codes. All system, socket, and application calls
check for error conditions whenever an error could exist.
Module Stack SizeIdentifies what MicroC/OS-II stack size the module should
use
f For more information about other NicheStack TCP/IP Stack options that can be
enabled at run-time, refer to the NicheStack TCP/IP Stack documentation in
NicheStackRef.zip located in the <Nios II EDS install
path>/components/altera_iniche/UCOSII/31src directory.
123
In the Nios II Simple Socket Server design example, only the minimum required
NicheStack TCP/IP Stack tasks have been configured to run. These tasks are as
follows:
For more information about these NicheStack TCP/IP Stack tasks, refer to Task
Priorities in the Nios II Simple Socket Server Design on page 125.
Creating Tasks that Use the NicheStack TCP/IP Stack Sockets Interface
You must use the function call TK_NEWTASK to create any tasks that use the NicheStack
networking services. You must create tasks that do not use networking services with
the MicroC/OS-II function OSTaskCreate().
The NicheStack Networking Stack uses the TK_NEWTASK (defined in osportco.c)
function to launch MicroC/OS-II tasks that use the networking services. TK_NEWTASK
accepts a single argument, struct inet_taskinfo * nettask (defined in osport.h),
which specifies the task name, the MicroC/OS-II thread priority, and the stack size.
You can locate these files in the <Nios II EDS install path>/components/
altera_iniche/UCOSII/src/nios2 directory. The struct inet_taskinfo structure is
defined as follows:
struct inet_taskinfo {
TK_OBJECT_PTR(tk_ptr);/* pointer to static task object */
char * name;/* name of task */
TK_ENTRY_PTR(entry); /* pointer to code that starts task*/
int priority; /* MicroC/OS-II priority of the task */
int stacksize;/* size (bytes) of tasks stack */
char* stackbase; /* base of tasks stack */
};
For every networking task you create in your application, you must declare a local
struct inet_taskinfo structure with the elements defined. These elements are listed
in the following bullets, along with a brief explanation of their function:
June 2011
Altera Corporation
124
In addition to declaring the struct inet_taskinfo structure, you must invoke two
macro definitions: TK_OBJECT and TK_ENTRY. These macros have the following uses:
To create your own application tasks that use the services offered by the NicheStack
TCP/IP Stack, follow these steps:
1. Invoke Task MacrosInclude the TK_OBJECT and TK_ENTRY macros, with
information about your task.
2. Define Task ParametersDefine your task application by filling in a local
inet_taskinfo structure in your code.
3. Wait for Stack InitializationBefore launching your task, wait until the external
variable iniche_net_ready is set to TRUE. This variable sets to FALSE at run time
and changes to TRUE when the NicheStack TCP/IP Networking Stack is
operational.
4. Launch TaskCall TK_NEWTASK while passing in a pointer to the inet_taskinfo
structure for your task.
Following is a code sample for creating your own application task:
// Declaration of SSSNiosIISimpleSocketServerTask
void SSSNiosIISimpleSocketServerTask(void){
// task specific code
}
// Creation of NicheStack networking task
TK_OBJECT(to_ssstask);
TK_ENTRY(SSSNiosIISimpleSocketServerTask);
struct inet_taskinfo ssstask = {
&to_ssstask,
"simple socket server",
SSSNiosIISimpleSocketServerTask,
TASK_PRIORITY,
APP_STACK_SIZE,
};
while (!iniche_net_ready)
TK_SLEEP(1);
/* Create the main simple socket server task. */
TK_NEWTASK(&ssstask);
Networking tasks can hand off large processing jobs that are independent of
networking to other tasks. This task load segmentation has the advantage of
increasing control over memory usage for task stacks, as well as greater control over
prioritization of jobs.
125
Be careful not to overutilize job distribution among several tasks at the same time, for
the following reasons:
Limited number of priorities. Each task must have its own unique priority in
MicroC/OS-II, and you do not want to run out of task priorities.
Configuration Mechanism
ucosii settings, located on the Main tab of the Nios II BSP Editor
NicheStack TCP/IP Stack internal tasks ipport.h, located in the iniche/src/h/nios2 directory of your BSP project
Networking initialization task
The following sections discuss the priorities of the tasks in the Nios II Simple Socket
Server design:
June 2011
Altera Corporation
126
127
f For more information about the _reent structure, refer to the The Newlib ANSI C
Standard Library and the Implementing MicroC/OS-II Projects for the Nios II
Processor sections of the MicroC/OS-II Real-Time Operating System chapter of the
Nios II Software Developers Handbook.
Where to Go Next
This example is easily expandable to handle multiple TCP connections on a single
port. The SSSNiosIISimpleSocketServerTask() task could be modified to create
separate socket connection instance tasks to handle multiple telnet connections.
There are many uses for an Ethernet connection in an embedded system. A
connection to the Internet can allow the addition of many powerful features for any
embedded product, such as remote configurability using a web browser, or remote
software upgrade for corrections or feature enhancements to a product already in the
field.
June 2011
Altera Corporation
128
Introduction
To complete this tutorial, you must have the Nios II SBT for Eclipse installed, and
your Altera development board must be connected to a host PC on both the Ethernet
and USB/JTAG ports.
f For information about download cables and drivers, refer to the Download Cables
page of the Altera website.
The Nios II Ethernet Standard hardware design examples for Altera development
boards include the Ethernet device required by this NicheStack tutorial. The Ethernet
device included in these design examples, along with the physical MAC/PHY on
your Altera development boards, is the Altera Triple Speed Ethernet MAC peripheral.
The Ethernet peripheral base address settings for the design examples are defined in
system.h.
Network Connection
If you are using a DHCP server to assign IP addresses, connect your Altera
development board to your Ethernet network.
If the Altera development board is connected directly to your PC with a crossover
Ethernet cable, or a DHCP server is not available, specify the IP addresses manually in
niosII_simple_socket_server.h.
The default IP addresses in niosII_simple_socket_server.h are set to all zeros so the
DHCP server packets can pass through secure routers. If you are not using a DHCP
server, specify valid static addresses, such as an IP address of 192.168.1.234, with a
gateway of 192.168.1.1 and a subnet mask of 255.255.255.0.
1
June 2011
Altera Corporation
A2
Additional Information
This chapter provides additional information about the document and Altera.
Version
June 2011
3.0
Changes
Revised for Quartus II Software 11.0 release.
May 2010
2.0
January 2007
1.0
Initial release.
Contact Method
Address
Website
www.altera.com/support
Website
www.altera.com/training
Website
www.altera.com/literature
(Software Licensing)
Note to Table:
(1) You can also contact your local Altera sales office or sales representative.
Typographic Conventions
The following table shows the typographic conventions this document uses.
Visual Cue
Meaning
Indicate command names, dialog box titles, dialog box options, and other GUI
labels. For example, Save As dialog box. For GUI elements, capitalization matches
the GUI.
bold type
Indicates directory names, project names, disk drive names, file names, file name
extensions, software utility names, and GUI labels. For example, \qdesigns
directory, d: drive, and chiptrip.gdf file.
italic type
June 2011
Variable names are enclosed in angle brackets (< >). For example, <file name> and
<project name>.pof file.
Altera Corporation
Info2
Additional Information
Typographic Conventions
Visual Cue
Meaning
Indicate keyboard keys and menu names. For example, the Delete key and the
Options menu.
Subheading Title
Courier type
Indicates command line commands and anything that must be typed exactly as it
appears. For example, c:\qdesigns\tutorial\chiptrip.gdf.
Also indicates sections of an actual file, such as a Report File, references to parts of
files (for example, the AHDL keyword SUBDESIGN), and logic function names (for
example, TRI).
Numbered steps indicate a list of items when the sequence of the items is important,
such as the steps listed in a procedure.
Bullets indicate a list of items when the sequence of the items is not important.
A question mark directs you to a software help system with related information.
The feet direct you to another document or website with related information.
A warning calls attention to a condition or possible situation that can cause you
injury.
The envelope links to the Email Subscription Management Center page on the Altera
website, where you can sign up to receive update notifications for Altera documents.