SLIDES Intro Embedded Linux 3day Color
SLIDES Intro Embedded Linux 3day Color
Student Guide
Important Notice
Important Notice
Texas Instruments and its subsidiaries (TI) reserve the right to make changes to their products or to discontinue any product or service without notice, and advise customers to obtain the latest version of relevant information to verify, before placing orders, that information being relied on is current and complete. All products are sold subject to the terms and conditions of sale supplied at the time of order acknowledgment, including those pertaining to warranty, patent infringement, and limitation of liability. TI warrants performance of its semiconductor products to the specifications applicable at the time of sale in accordance with TIs standard warranty. Testing and other quality control techniques are utilized to the extent TI deems necessary to support this warranty. Specific testing of all parameters of each device is not necessarily performed, except those mandated by government requirements. Customers are responsible for their applications using TI components. In order to minimize risks associated with the customers applications, adequate design and operating safeguards must be provided by the customer to minimize inherent or procedural hazards. TI assumes no liability for applications assistance or customer product design. TI does not warrant or represent that any license, either express or implied, is granted under any patent right, copyright, mask work right, or other intellectual property right of TI covering or relating to any combination, machine, or process in which such semiconductor products or services might be or are used. TIs publication of information regarding any third partys products or services does not constitute TIs approval, warranty or endorsement thereof.
Revision History
August 2012 Revision 1.0
Mailing Address
Texas Instruments Training Technical Organization 6550 Chase Oaks Blvd Building 2 Plano, TX 75023
ii
01 - 1
Module Topics
Module Topics
Module 01: Booting Linux .........................................................................................................................1-1 Module Topics..........................................................................................................................................1-2 Booting Linux from Pre-Built Binaries ....................................................................................................1-4 Rebuilding and Modifying SDK Components ..........................................................................................1-9 System Startup Details ...........................................................................................................................1-13 Lab 1 Introduction .................................................................................................................................1-17
01 - 2
Module Topics
01 - 3
Provides rudimentary h/w init Calls Linux kernel and passes boot arguments
Flash
o Kernel
Initializes the system (and device) Manages system resources Provides services for user programs
p Filesystem
Single filesystem (/ root) Stores all system files After init, kernel looks to filesystem for whats next bootarg tells linux where to find root filesystem
01 - 4
ROM bootloader supports NAND, NOR or SPI-flash boot (determined by BOOTM pins high/low at device powerup) Linux supports flash-based filesystems such as YAFFS and JFFS All components may be flashed using U-boot (initial load via MMC or bootp) or JTAG using flashing utility via Code Composer Studio
Multimedia Card (MMC) or Secure Digital card (SD) may be flashed using an MMC/SD programmer using a variety of utilities Simple, low cost method for booting Linux (or just U-boot) on a development board that has nothing pre-programmed (or for recovery.)
01 - 5
MLO
U-Boot
DDR2
Kernel
DDR2
Internal RAM
Device
RBL MLO
OCMC (on-chip memory controller) Internal memory
n o p
MLO UBoot
MMC/SD
Linux Kernel
DDR3
UBoot Linux Kernel
The ROM bootloader cannot make assumptions about external memory, so it can only load to the devices internal memory uBoot with MMC driver is too large to fit into internal memory
NFS boot is typically used for development but not production devices All components of the system are loaded from host server at each boot Filesystem changes on host are instantly reflected UBL, U-boot and Linux Kernel changes are reflected on each reboot Good method to ensure uniformity across multiple development boards
01 - 6
Installs tftp server, nfs server , minicom and packages needed to rebuild u-boot and kernel (using Aptitude package manager) Extracts AM335x Linux filesystem to specified location (default ${HOME}/targetfs), exports it via nfs server, and updates Rules.mak EXEC_DIR variable Configures tftp server with specified read directory (default /tftpboot) and copies in prebuilt Linux kernel Configures minicom for TTYS0 serial device for 115,200 Baud, 8-bit, no parity, 1 stop bit Creates setup.minicom script to configure u-boot for desired boot type (mmc or tftp/nfs).
Partition 1
(FAT32)
MLO (i.e. x-loader) u-boot.img (per MMC default config) uImage (i.e. Kernel) MLO boots a file named u-boot.bin
Partition 2
(EXT3)
Root Filesystem
Linux root filesystem must be in its own partition.
01 - 7
Other Boot Options (Macros in Default U-boot Environment) 1. NOR Flash boot 2. SPI Flash boot 3. TFTP/NFS (network) boot
01 - 8
Rebuilding EZSDK
Rebuild SDK
host $ make help host $ make clean host $ make all
make all rebuilds: U-boot Linux Kernel OpenGL graphics Demos Example Applications Wireless Driver Support
MLO
U-Boot
DDR2
Kernel
DDR2
Device
n o p
MMC/SD
Linux Kernel
DDR3
UBoot Linux Kernel
The ROM bootloader cannot make assumptions about external memory, so it can only load to the devices internal memory uBoot with MMC driver is too large to fit into internal memory
01 - 9
MLO
U-Boot
DDR2
Kernel
DDR2
host $ cd ti-sdk-am335x-evm-xxx/board_support/u-boot-xxx host $ make distclean host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- am335x_evm_config* host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- MLO
host$
ls include/configs
U-Boot Build
n
RBL
ROM
MLO
U-Boot
DDR2
Kernel
DDR2
host $ cd ti-sdk-am335x-evm-xxx/board_support/u-boot-xxx host $ make distclean host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- am335x_evm_config host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- u-boot.img
01 - 10
Kernel Build
n
RBL
ROM
MLO
U-Boot
DDR2
Kernel
DDR2
host$ cd ti-sdk-am35x-evm_xxx/board_support/linux-xxx-psp-xxx host$ make mrproper host$ make ARCH=arm* am335x_evm_defconfig** host$ make ARCH=arm menuconfig host$ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- uImage host$ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- modules host$ make INSTALL_MOD_PATH=${HOME}/targetfs modules_install
host$ host$
ls arch/ ls arch/arm/configs
01 - 11
Kernel Module Examples: fbdev frame buffer dev v4l2 video for linux 2 nfsd network file server dev dsp oss digital sound proc. audio alsa audio driver
Linux Kernel source code is broken into individual modules Only those parts of the kernel that are needed are built in
2. Dynamic (insmod)
Use insmod (short for insert module) command to dynamically add modules into the kernel Keep statically built kernel small (to reduce size or boot-up time), then add functionality later with insmod Insmod is also handy when developing kernel modules
01 - 12
/etc/rcX.d
01 - 13
SysV Startup
/etc/init.d /etc/rcX.d
bootmisc.sh mountnfs.sh syslog ...
Arago and most Linux distributions use the SysV (System Five) startup process /etc/init.d directory holds all scripts used for boot-up /etc/rcX.d (i.e. /etc/rc5.d) contains links to these scripts specifying which should run and in what order for a given run level 1-5 (5 is default) Sxx precedes the name of each link in rcX.d. S indicates it is run at startup, xx indicates the order
/etc/rc5.d
S10dropbear S10telnetd S20netperf S20syslog S20thttpd S30pvr-init S70lighttpd S97matrix-gui-2.0 S98parse-ip S98storage-gadget-init S99gplv3-notice S99rmnologin
Sxx scripts are executed when entering a runlevel, according to the order of xx (01 first) Kxx scripts are executed when exiting a runlevel, according to reverse order of xx (99 first)
01 - 14
/etc/inittab
# The default runlevel. id:5:initdefault: # Boot-time system configuration/initialization script. # This is run first except when booting in emergency (-b) mode. si::sysinit:/etc/init.d/rcS # Run-level configuration/initialziation scripts l0:0:wait:/etc/init.d/rc 0 l1:1:wait:/etc/init.d/rc 1 l2:2:wait:/etc/init.d/rc 2 l3:3:wait:/etc/init.d/rc 3 l4:4:wait:/etc/init.d/rc 4 l5:5:wait:/etc/init.d/rc 5 # Other Initializations S:2345:respawn:/sbin/getty 115200 ttyO0
Format: <id>:<runlevels>:<action>:<process>
/etc/fstab
Format: <device>:<mount point>:<filesys type>:<options>:<backup>:<check>
# stock fstab - you probably want to override this with a machine specific one rootfs proc devpts usbfs tmpfs tmpfs tmpfs / /proc /dev/pts /var/volatile /dev/shm /media/ram auto proc defaults defaults defaults 1 1 0 0 0 0 0 0
/proc/bus/usb usbfs
# uncomment this if your device has a SD/MMC/Transflash slot #/dev/mmcblk0p1 /media/card auto defaults,sync,noauto 0 0
01 - 15
inetd/xinetd
user@ubuntu:~$ ls /etc/xinetd.d chargen daytime discard echo tftp time service tftp { protocol = udp port = 69 socket_type = dgram wait = yes user = nobody server = /usr/sbin/in.tftpd server_args = /tftpboot disable = no }
Beaglebone Arago distribution does not use xinetd Many desktop distributions do, including Ubuntu Ubuntu launches xinetd from /etc/rc5.d/S20xinetd
xinetd is a replacement for inetd, the internet services daemon. It listens for requests and forwards to appropriate service according to port number.
/sbin/init vs distribution
/sbin/init /etc/inittab /etc/init.d /etc/rcX.d /etc/fstab Ultimately, the meaning of initialization scripts are driven completely by /sbin/init Initialization scripts and tables only have meaning for a given distribution if recognized by /sbin/init Beaglebone Arago
bootmisc.sh mountnfs.sh syslog ...
01 - 16
Lab 1 Introduction
Lab 1 Introduction
1. Use mkcard.txt script to format and partition card 2. Mount micro-SD partitions into root filesystem (Discussed in Module 5) 3. Copy MLO, u-boot and uImage into partition 1 4. De-archive filesystem into partition 2
Partition 1
(FAT32)
Root Filesystem
Partition 2
(EXT3)
01 - 17
Lab 1 Introduction
1. Map Serial-over-USB and Ethernet-over-USB to VM 2. Launch minicom serial terminal emulator 3. Manually load Ethernetover-USB driver.
01 - 18
02 - 1
Module Topics
Module Topics
Module 02: Linux Distributions ................................................................................................................2-1 Module Topics..........................................................................................................................................2-2 (Short) Product Overview ........................................................................................................................2-3 Linux Distributions ..................................................................................................................................2-7 MMU and Dynamic Libraries ................................................................................................................2-15 Lab 2: Terminal Manipulation ...............................................................................................................2-19
02 - 2
ARM-Based
32-bit ARM
ARM Industry Std Low Power <100 MHz Flash 64 KB to 1 MB USB, ENET, ADC, PWM, SPI Host Control $2.00 to $8.00
DSP
ARM + DSP DSP
C647x, C64x+, C674x, C55x Leadership DSP Performance 24,000 MMACS Up to 3 MB L2 Cache 1G EMAC, SRIO, DDR2, PCI-66 Comm, WiMAX, Industrial/ Medical Imaging $4.00 to $99.00+
32-bit Real-time
C2000 Fixed & Floating Point Up to 300 MHz Flash 32 KB to 512 KB PWM, ADC, CAN, SPI, I2C Motor Control, Digital Power, Lighting, Sensing $1.50 to $20.00
ARM+
ARM9 Cortex A-8 Industry-Std Core, High-Perf GPP Accelerators MMU USB, LCD, MMC, EMAC Linux/WinCE User Apps $8.00 to $35.00
C64x+ plus ARM9/Cortex A-8 Industry-Std Core + DSP for Signal Proc. 4800 MMACs/ 1.07 DMIPS/MHz MMU, Cache VPSS, USB, EMAC, MMC Linux/Win + Video, Imaging, Multimedia $12.00 to $65.00
Embedded
Cortex Processors
Application
Cortex Processors
Performance, Functionality
ARM11 ARM9
http://www.arm.com/products/processors/index.php
02 - 3
1993
1995
2002
2005
2006
2007
2008
Stellaris Tempest Class
2009
2010
2011
TI Licenses Cortex-A15 TI announces Sandstorm 1st R4F-based 1st ARM 31 new Introduce ARM Class floating-point, Cortex-A8 Cortex-A9 Newest DaVinci dual-core auto Stellaris based silicon based silicon and solution for MCU ARM-based OMAP OMAP flexible, TI MPUs OMAP 4 OMAP 3 TMS570F HD video Licenses MCU Cortex-A7 Stellaris
DaVinci
TI has shipped over 6 billion ARM-based products and continues to invest in a large portfolio of scalable platforms from $1 to >1GHz
* TI licensed in July 2003, but publicly announced Oct 2005.
Sample Applications
Home automation Home networking Gaming peripherals Consumer medical appliances Printers Building automation Smart toll systems Weighing scales Educational consoles Advanced toys Customer premise equipment Connected vending machines
ARM Cortex-A8 up to
720* MHz
256K L2 w/ECC 64K RAM 32K/32K L1 w/SED
PRU SS PRU x2 200 MHz 8K P. w/SED 8K D. w/SED 12K RAM w/SED Peripherals
L3/L4 Interconnect
Serial Interface UART x6 SPI x2 I2C x3 McASP x2 (4ch) CAN x2 (2.0B) System EDMA Timers x8 WDT RTC eHRPWM x3 eQEP x3 eCAP x3 JTAG/ETB ADC (8ch) 12-bit SAR** Parallel MMC/SD/ SDIO x3 GPIO USB 2.0 OTG + PHY x2 EMAC 2port 10/100/1G w/1588 & switch (MII,RMII, RGMII)
Linux, Android, WinCE and drivers direct from TI StarterWare enables quick and simple programming of and migration among TI embedded processors RTOS (QNX, Wind River, Mentor, etc) from partners Full featured and low cost development board options
Power Estimates
Total Power: 600mW-1000mW Standby Power: ~25mW Deep Sleep Power: ~5-7mW
Samples: October 31, 2011; Production: 2Q12 Dev. Tools: Order open October 31, 2011 Prelim docs: available today Packaging: 13x13, 0.65mm via channel array 15x15, 0.8mm
Availability of some features, derivatives, or packages may be delayed from initial silicon availability Peripheral limitations may apply among different packages Some features may require third party support All speeds shown are for commercial temperature range only
* 720 MHz only available on 15x15 package. 13x13 is planned for 500 MHz. ** Use of TSC will limit available ADC channels. SED: single error detection/parity
02 - 4
Kit Contents TI AM335x EVM Kit includes AM3358 Microprocessor, 512 MB DDR2, TPS65910 Power management IC, 7 LCD, Software & Tools, WL1271 COM6M Adapter Card Demos QT based WLAN and Bluetooth demo Applications integrated into SDK WPA Supplicant and Host Apd GUIs for WiFi Station and Soft AP setup Profusion Bluetooh GUI with BMG (Scan, Pair, Connect), A2DP, FTP, OPP and SPP demos Software
User and Demo guide, Releases: TI Wireless Connectivity Wiki Module WL1271-Type TN Datasheet from Murata Documentation
Open Source Linux 3.2 drivers Pre-Integrated with TI Linux SDK mac80211 Open Source WLAN Driver BlueZ Open Source Bluetooth stack BlueZ OpenObex Profiles
WL1271-TypeTN (Murata)
WLAN 802.11 b/g/n and Bluetooth v4.0 BLE Module Features
IEEE 802.11 b/g/n compliant Bluetooth 4.0 with Bluetooth Low Energy Wi-Fi Direct TIs proven 6th generation Wi-Fi and Bluetooth solution Pre-integration with high performance Cortex-A8 based AM335x processor platform Open-source compliant Wi-Fi and Bluetooth drivers FCC Certified, ETSI & EMC Tested WL1271 module Sample applications and demos LBEE5ZSTNC-523
Benefits
Seamless, direct and high throughput Wi-Fi connectivity between devices (no external access points needed) High throughput, reliable signal integrity, best in class coexistence, enhanced low power Simplified and reduced hardware and software integration effort, get started quickly Platform enables high performance processing and increased level of integration at value-line pricing Open-source compliant Wi-Fi and Bluetooth drivers Certified modules lowers manufacturing and operating costs, saves board space and minimizes RF expertise required
Applications
Mobile consumer devices Industrial and home automation, metering Portable data terminals Video conferencing, video camera
www.ti.com/wl1271typetn
02 - 5
HPI uPP
How many pins is on your device? How many pins would all your peripheral require? Pin Multiplexing is the answer only so many peripherals can be used at the same time in other words, to reduce costs, peripherals must share available pins Which ones can you use simultaneously?
Designers examine app use cases when deciding best muxing layout Read datasheet for final authority on how pins are muxed Graphical utility can assist with figuring out pin-muxing
Graphical Utilities For Determining which Peripherals can be Used Simultaneously Provides Pin Mux Register Configurations http://wiki.davincidsp.com/index.php?title=Pinmux_Utilities_for_Davinci_Processors
02 - 6
Linux Distributions
Linux Distributions
A TI LSP or Linux PSP is a Linux kernel port to a device, not just a set of device drivers Uboot is the standard bootloader for ARM Linux This does NOT mean a specific type of file system like FAT file system or flash file system rather, it more like the C:\ drive in Windows It refers to all the user mode software that an application needs such as graphics libraries, network applications, C run-time library (glibc, uclibc), codec engine, dynamically-loaded kernel modules (CMEM, DSPLINK) CodeSourcery - GCC, GDB MV DevRocket, CCSv5 (beta), GHS Multi, etc.
2. 3.
Bootloader
4.
Development tools
O/S Choices
Choices
Linux
Android
(arowboat.org)
WinCE
Others
QNX
Commercial
Community
Build It Yourself
02 - 7
Linux Distributions
O/S Choices
Choices
Linux
Android
(arowboat.org)
WinCE
Others
QNX
Commercial
Community
Build It Yourself
Linux
MontaVista TimeSys Wind River Mentor Ridgerun Adeneo Mistral MPC Data BSQUARE
WinCE
RTOS
Green Hills Wind River (VxWorks) ELogic (ThreadX) QNX Mentor (Nucleus)
Commercial: provide support, off-the-shelf Linux distributions or GNU tools Consultants: provide training, general embedded Linux development expertise, or specific expertise for developing drivers or particular embedded applications http://www.tiexpressdsp.com/index.php/Linux_Consultants_and_Commercial_Linux_Providers
02 - 8
Linux Distributions
O/S Choices
Choices
Linux
Android
(arowboat.org)
WinCE
Others
QNX
Commercial
Community
Build It Yourself
Arago Lineage
kernel.org uboot source Open Embedded Angstrom Arago Various GNU apps
Many Distributions Many Platforms One Distribution Many Platforms One Distribution TI Platforms
02 - 9
Linux Distributions
O/S Choices
Choices
Linux
Android
(arowboat.org)
WinCE
Others
QNX
Commercial
Community
Build It Yourself
02 - 10
Linux Distributions
Open Embedded
Open Embedded is a Linux open-source project to provide a build system for building and maintaining a Linux Distribution The Open Embedded project contains contributions from many different Distribution maintainers (such as Angstrom and Arago) Most OE Distributions are aimed at Embedded Applications (but this is not a requirement.) Open Embedded uses a build system called Bitbake which builds a distribution from recipe files. OE Users may build community distributions from provided recipes or modify existing recipes to create a custom distribution.
http://www.openembedded.org/wiki/How_to_create_a_bitbake_recipe_for_dummies
02 - 11
Linux Distributions
Arago install and updates are distributed via git Arago install includes Bitbake, Open Embedded recipes A separate page contains pre-built binaries (snapshots)
ngstrm : Narcissus
(http://www.angstrom-distribution.org/narcissus)
02 - 12
Linux Distributions
02 - 13
Linux Distributions
Community
TI SDK (PSP)
Custom
(Build it Yourself) Open Embedded (OE)
Binary
(Update patches)
(online tool)
Bit-Bake Recipies
GIT
Ease of Use
Easy Tested
02 - 14
Fragmentation
Problem: Over time, the system heap that is used to manage dynamic memory becomes fragmented.
Free
malloc
Free Memory
Allocated Memory
Allocated
Virtual Memory
Solution: A Memory Management Unit (MMU) maps fragmented physical memory into virtually contiguous memory
Free Allocated Free Allocated Free Allocated Free Allocated Free Memory
MMU
Allocated Memory
02 - 15
Memory Protection
The memory management unit also provides memory protection by denying access to regions of physical memory that are not allocated to a given application Physical Memory Application 1 MMU Application 2
Application 1 Memory (unused) Application 2 Memory (unused)
Memory Protection
When application 1 is executing, its application memory is mapped to a valid virtual address. Disallowed memory is assigned no virtual address and is therefore unreachable. Physical Memory Application 1 Allowed
Application 1 Memory (unused) Application 2 Memory (unused)
MMU
02 - 16
MMU Details
All user-mode applications access memory via the MMU Kernel and drivers bypass the MMU and access memory via physical addresses. In desktop systems (not commonly in embedded), virtual memory is used to extend ram by virtualizing storage media such as a hard disk (swap space/demand paging.)
Libs
(unused)
Static Libs
(unused)
02 - 17
Application 2
02 - 18
Concepts Covered: wildcard (*) autofill (<tab>) text editor (gedit) home directory (~) terminal history (arrow keys)
02 - 19
02 - 20
03 - 1
Module Topics
Module Topics
Module 03: The git Tool.............................................................................................................................3-1 Module Topics..........................................................................................................................................3-2 git Overview .............................................................................................................................................3-3 Adding Commits .......................................................................................................................................3-5 Adding and Merging Branches ..............................................................................................................3-11 Lab 3: Using git .....................................................................................................................................3-16
03 - 2
git Overview
git Overview
git Branches
Step 1: make a directory to hold your project files Step 2: use git init to initialize the directory with git metadata Step 3: add files to the project Step 4: use git add to add files from the directory to the git repository (just placing the file in the git directory hasnt added them to get yet!) Step 5: use git commit to commit the current state of the git repository, with the reference tag initial_version
03 - 3
git Overview
Cloning is better than simply copying source files because 1. Automatically creates a local git repository 2. Allows you to pull external changes (patches) from the public repository and merge them into your copy 3. Depending on configuration, allows you to push your changes back to the public repository
Branch 1 is by default named master Branch 2 is derived from master, branch 3 is derived from a branch 2 commit Each commit is a diff (difference operation) from the previous commit
03 - 4
Adding Commits
Adding Commits
Creating a Repository
HEAD
master (branch 1)
host$ mkdir ~/my_project host$ git init host$ cp ~/project_files/* ~/myproject host$ git add * host$ git commit m initial_version
The HEAD marker indicates your position within the branch/commit structure. By default git names the first branch master, although this can be overridden.
Making Commits
master (branch 1)
HEAD
commit
(make changes to file1 and file2) host$ git add file1 host$ git commit
Only files that have been git add-ed since last commit will be committed, regardless of which files have been changed. As a shortcut, you can commit all files that have been previously added to the index with git add using: host$ git commit -a
03 - 5
Adding Commits
Making Commits
master (branch 1)
(make changes to file1 and file2) host$ git add file1 host$ git commit host$ git add file2 host$ git commit
A commit can be retrieved using the checkout command with its SHA1 sum
host$ git checkout b87bd642de3c1d6a47cde7bfa9305a29606c7781
03 - 6
Adding Commits
git tags
Checking out commits by their SHA1 sum is tedious and the SHA1 sum is not particularly informative. Instead, one may create a tag to reference the commit
host$ git tag a myTag m message b87bd642de3c1d6a47cde7bfa9305a29606c7781
git repository
Index
Staging Area
03 - 7
Adding Commits
git repository
Index
Staging Area
git add moves files to Staging Area and adds them to index
git repository
Index
Staging Area
host$ touch file1 file2 host$ git add * host$ git commit
03 - 8
Adding Commits
git repository
Index
Staging Area
host$ touch file1 file2 host$ git add * host$ git commit host$ git add file2 host$ git commit
git repository
Index
Staging Area
host$ touch file1 file2 host$ git add * host$ git commit host$ git add file2 host$ git commit host$ touch file3 host$ git commit -a
03 - 9
Adding Commits
git status
file1 file2 file3 file1 file2 file2
git repository
host$ git status
Index
Staging Area
# On branch master # Changes to be committed # # # modified: modified: file3 file2 file1 # Changes not staged for commit: # Untracked files:
03 - 10
Creating a branch does not change your current position (i.e. currently checked-out commit)
03 - 11
branch 2
HEAD
03 - 12
commit
HEAD
commit
1.
Ima Pro of Penguins, Inc. clones the Arago u-boot for AM335x EVM from arago-project.org
03 - 13
1. 2.
Ima Pro of Penguins, Inc. clones the Arago u-boot for AM335x EVM from arago-project.org Ima ports U-boot to the Penguins, Inc. production board
03 - 14
03 - 15
A. Use git branch, git tag and git log to get the lay of the land from a real-world git repository and then use git checkout to rebuild a specific version B. Use git init to create a new repository and then git commit and git tag to save files in various states and explore the effects of git checkout and git merge.
03 - 16
04 - 1
Module Topics
Module Topics
Module 04: Application Debug..................................................................................................................4-1 Module Topics..........................................................................................................................................4-2 Intro to Makefiles .....................................................................................................................................4-3 Code Composer Studio Overview ............................................................................................................4-7 Setting up a CCS5 GDB Session ............................................................................................................4-13 Setting up a CCS5 JTAG Session ...........................................................................................................4-16 Lab 4: Application Build and Debug .....................................................................................................4-17
04 - 2
Intro to Makefiles
Intro to Makefiles
Build Overview
Source Files Dependencies Build Instructions Executables Targets app.x64P app.xv5T app.x470MV app.x86U app.o app.lib T
Build Tool
CMD
Build Tool Goals: 1. Build executable (target) from input files (dependencies) using build instructions (commands)
2.
Solution: command line (e.g. cl6x, gcc) or scripting tool (gMake, etc.)
Example 1: create an object file (app.o) from an input file (app.c) gcc g c app.c o app.o Example 2: create an executable (app.x86U) from an object file (app.o) gcc g app.o o app.x86U
command flag dependency flag target -c = compile only -g = build with debug enabled -o = output filename
04 - 3
Intro to Makefiles
Makefile
gMake CMD
One of the more common scripting tools is GNU Make, aka gMake, aka Make gMake uses rules to specify build commands, dependencies and targets Generically, a RULE looks like this:
TARGET : DEPENDENCY [TAB] COMMANDS
Remember Example 2? Lets make this into a simple Makefile rule: gcc g app.o o app.x86U
command flag dependency flag target
Becomes. app.x86U
app.x86U
RULE
gMake CMD
Command Lines
gcc c g app.c o app.o gcc g app.o o app.x86U # Makefile for app.x86U (goal)
Makefile
app.x86U : app.o gcc g app.o o app.x86U app.o : app.c gcc g c app.c o app.o
04 - 4
Intro to Makefiles
CMD
User-defined variables simplify your makefile and make it more readable. Include files can contain, for example, path statements for build tools. We use this method to place absolute paths into one file. If -include path.mak is used, the - tells gMake to keep going if errors exist. Examples: makefile
include path.mak CC := $(CC_DIR)gcc CFLAGS := -g LINK_FLAGS := -o
path.mak
CC_DIR := /usr/bin/ ... # other paths go here
CMD
$@
04 - 5
Intro to Makefiles
Using pattern matching (or pattern substitution) can help simplify your makefile and help you remove explicit arguments. For example:
Original Makefile app.x86U : app.o main.o $(CC) $(CFLAGS) $^ -o $@ app.o : app.c $(CC) $(CFLAGS) -c $^ -o $@ main.o : main.c $(CC) $(CFLAGS) -c $^ -o $@ Makefile Using Pattern Matching app.x86U : app.o main.o $(CC) $(CFLAGS) $^ -o $@ %.o : %.c $(CC) $(CFLAGS) -c $^ -o $@
The .x rule depends on the .o files being built thats what kicks off the .o rules % is a shortcut for $(patsubst ), e.g. $(patsubst .c, .o)
04 - 6
Integrated development environment for TI embedded processors Includes debugger, compiler, editor, simulator, OS CCSv5 is based on off the shelf Eclipse TI contributes changes directly to the open source community Drop in Eclipse plug-ins from other vendors or take TI tools and drop them into an existing Eclipse environment CCSv5 runs on a Windows or Linux host Integrate additional tools OS application development tools (Linux, Android) Code analysis, source control Low cost!
CCSv5 Environment
Customize toolbars & menus Perspectives contain separate window arrangements depending on what you are doing.
04 - 7
Eclipse Projects
CCSv5 is PROJECT-centric Eclipse uses managed makefiles as their build scripts as opposed to pjt files Eclipse projects are folder based
Adding file copies it to folder Linking file references original file Project explorer shows folder contents
make file
Perspectives
Perspectives
a set of windows, views and menus that correspond to a specific set of tasks Debug C/C++
Users
04 - 8
Build Configuration a set of build options for the compiler and linker (e.g. optimization levels, include DIRs, debug symbols, etc.) CCSv5 comes standard with two DEFAULT build configs: Debug & Release:
User can create their own config if desired
18
When debugging user mode programs, you often only want to debug hence stop one thread or program. GDB (GNU Debugger) works well for this. (GDB discussed on next slide) Connection is usually Ethernet or serial-port Debugging kernel code requires complete system access. You need KGDB (Ethernet) or scan-based (JTAG) debuggers for this.
04 - 9
JTAG
04 - 10
Open source debugger that is often supplied with the toolchain In this workshop, its included in the Code Sourcery package GDB has a client/server nature: GDB Server GDB Server: Runs your app for you, First start gdbserver, specifying connection and app based on the GDB to be debugged commands you send Server then runs your app, following gdb commands
Tera Term
EVM> gdbserver 192.168.1.122:10000 myApp Listening on port 10000 Remote debugging from host 192.168.1.1 Hello World
GDB (i.e. debug client) Command-line oriented debugger Telnet, Bash terminal, IDE
Other than starting gdbserver, it means we dont have to know GDB syntax The debug (host) system runs:
Its own OS (Linux, Windows, etc.) Debugger IDE (optional) and Gdb Terminal app (Tera Term, putty, etc.) to control the target/evm environment
Host PC
Terminal
RS-232
Controls Target
Target (EVM)
Embedded O/S (ie. Linux)
Ethernet
04 - 11
Licensing
Wide variety of options (node locked, floating, time based) All versions (full, DSK, free tools) use same image Updates readily available via the internet
Pricing
Reasonable pricing includes FREE options noted below Annual subscription $99 ($149 for floating)
Item
Platinum Eval Tools Platinum Bundle Platinum Node Lock Platinum Floating Microcontroller Core Microcontroller Node Lock
Description
Full tools with 120 day limit (all EMU) EVM, sim, XDS100 use Full tools tied to a machine Full tools shared across machines MSP/C2000 code size limited MSP/C2000
Price
FREE FREE $495 (1) $795 (1) FREE $445
Annual
$99 $159 $99
- - recommended option: purchase Dev Kit, use XDS100v1-2, & Free CCSv5
20
04 - 12
Processes: tells CCS how to view and manipulate remote processes (applications)
04 - 13
04 - 14
04 - 15
Target Configuration defines your target i.e. emulator/device used, GEL scripts (replaces the old CCS Setup) Create user-defined configurations (select based on chosen board)
Advanced Tab
click
A GEL file is basically a batch file that sets up the CCS debug environment including: Memory Map DDR Configuration PINMUX PSC PLL
The board manufacturer (e.g. SD or LogicPD) supplies GEL files with each board. To create a stand-alone or bootable system, the user must write code to perform these actions (optional chapter covers these details)
16
04 - 16
04 - 17
04 - 18
05 - 1
Module Topics
Module Topics
Module 05: Linux Files ..............................................................................................................................5-1 Module Topics..........................................................................................................................................5-2 Driver Basics ...............................................................................................................................................5-3 NAND Flash Driver ..................................................................................................................................5-11 GPIO..........................................................................................................................................................5-13 Lab 5: GPIO via Virtual Files ...............................................................................................................5-15
05 - 2
Module Topics
Driver Basics
Kernel vs User Space
Peripherals Storage RAM Memory Driver File Sys MMU Linux Kernel API API API User Process 1 User Process 2 User Process 3
Kernel Space The Linux kernel manages the machine's hardware via drivers Drivers provide hardware abstraction and protection Drivers execute within the Linux kernels context, and are inserted into the running Linux kernel or statically linked in when kernel is built User Space(Applications) Cannot access peripherals or memory directly Make requests to kernel to access peripherals or storage media
/mypath/myfile
mounted to root file system
Kernel Space
ATA driver harddrive
Block random
Character - sequential
05 - 3
Module Topics
fbdev dsp
httpd ext3
nfsd
Kernel Module Examples: fbdev frame buffer dev v4l2 video for linux 2 nfsd network file server dev dsp oss digital sound proc. audio alsa audio driver
Linux Kernel source code is broken into individual modules Only those parts of the kernel that are needed are built in
05 - 4
Module Topics
Linux Kernel source code is broken into individual modules Only those parts of the kernel that are needed are built in
2. Dynamic (modprobe)
Use modprobe command to dynamically add modules into the Linux kernel Keep statically built kernel small (to reduce size or boot-up time), then add functionality later with modprobe modprobe is also handy when developing kernel modules
05 - 5
Module Topics
1. Load the drivers code into the kernel (insmod or static) 2. Create a virtual file to reference the driver using mknod 3. Mount block drivers using a filesystem (block drivers only) 4. Access resources using open, read, write and close
Major number for the driver Minor number for the driver mknod /dev/fb/3 c 29 3
Fd = open("/dev/fb/3", O_RDWR);
Register new drivers with mknod (i.e. Make Node) command. Major number determines which driver is used (the name does not affect which driver is used). Most devices have number assigned by Linux community. Minor number is significant for some drivers; it could denote instance of given driver, or in our example, it refers to a specific buffer in the FBdev driver.
05 - 6
Module Topics
Linux devices are registered in /dev directory Two ways to view registered devices:
cat /proc/devices ls lsa command (as shown below) to list available drivers
/ #
cd /dev ls lsa 1 root disk 1 root uucp 0, 0 Jun 24 8 3 Jun 24 0 Jun 24 1 Jun 24 2004 /dev/hda 2004 /dev/ttyS0 2004 /dev/dsp 2004 /dev/fb/0 2004 /dev/fb/1 4, 64 Mar
/dev #
1. Load the drivers code into the kernel (insmod or static) 2. Create a virtual file to reference the driver using mknod 3. Mount block drivers using a filesystem (block drivers only) 4. Access resources using open, read, write and close
05 - 7
Module Topics
/ # / #
Initially empty
Mounting a block driver into the filesystem gives access to the files on the device as a new directory Easy manipulation of flash, hard drive, compact flash and other storage media Use mkfs.ext2, mkfs.jffs2, etc. to format a device with a given filesystem
$ $ $ $
mkdir /media/part1 ls /media/part1 mount t vfat /dev/mmcblk0p1 /media/part1 ls /media/part1 MLO u-boot.bin uImage
Unlike Windows, there is only one filesystem therefore you must mount to a mount point (i.e. empty directory) in the root filesystem Easy manipulation of flash, hard drive, compact flash and other storage media Use mkfs.ext2, mkfs.jffs2, etc. to format a device with a given filesystem The above example shows mounting an external harddrive into the root filesystem
05 - 8
Module Topics
1. Load the drivers code into the kernel (insmod or static) 2. Create a virtual file to reference the driver using mknod 3. Mount block drivers using a filesystem (block drivers only) 4. Access resources using open, read, write and close
05 - 9
Module Topics
Accessing Files
Manipulating files from within user programs is as simple as
File descriptor / handle Directory previously mounted File to open Permissions
myFileFd = fopen(/mnt/harddrive/myfile,rw); fread ( aMyBuf, sizeof(int), len, myFileFd ); fwrite( aMyBuf, sizeof(int), len, myFileFd ); fclose( myFileFd );
Array to read into / write from size of item # of items File descriptor / handle
Additionally, use fprintf and fscanf for more feature-rich file read and write capability
05 - 10
Module Topics
# cat /proc/mtd dev: mtd0: mtd1: mtd2: mtd3: mtd4: mtd5: mtd6: mtd7: size 00020000 00020000 00020000 00020000 001e0000 00020000 00500000 0f880000 erasesize name 00020000 "SPL" 00020000 "SPL.backup1" 00020000 "SPL.backup2" 00020000 "SPL.backup3" 00020000 "U-Boot" 00020000 "U-Boot Env" 00020000 "Kernel" 00020000 "File System"
05 - 11
Module Topics
ubiattach attaches mtd partition 7 to UBI -O 2048 indicates NAND flash block size UBI volumes are specified ubiX:Y X device number Y Volume number (ubi0:0) or name (ubi0:rootfs)
05 - 12
Module Topics
GPIO
GPIO Driver (Terminal)
1. Export GPIO pin for sysfs usage (Pin 30 in example)
# echo 30 > /sys/class/gpio/export
05 - 13
Module Topics
leds-gpio driver
In addition to standard (device-specific) GPIO driver, Arago provides the (platform-specific) leds-gpio driver:
/sys/devices/platform/leds-gpio/leds/am335x:EVM_SK:heartbeat /sys/devices/platform/leds-gpio/leds/am335x:EVM_SK:mmc0 /sys/devices/platform/leds-gpio/leds/am335x:EVM_SK:usr0 /sys/devices/platform/leds-gpio/leds/am335x:EVM_SK:usr1
led Triggering
Setting up a trigger ties an LED to a kernel event
# cat /sys/devices/platform/leds-gpio/leds/am335x\:EVM_SK\:heartbeat/trigger none nand-disk mmc0 mmc1 timer [heartbeat] rfkill0 phy0rx phy0tx phy0assoc phy0radio
Brackets around [heartbeat] indicate this LED is configured to trigger on the system heartbeat event.
05 - 14
HEAD
start
solution_A solution_B
05 - 15
05 - 16
06 - 1
Module Topics
Module Topics
Module 06: Linux Drivers .........................................................................................................................6-1 Module Topics..........................................................................................................................................6-2 Driver Basics ...........................................................................................................................................6-3 UART Driver ............................................................................................................................................6-5 Advanced Linux Sound Architecture (ALSA) ...........................................................................................6-7 Signal Handling .....................................................................................................................................6-11 Lab 6: UART Driver ..............................................................................................................................6-13
06 - 2
Driver Basics
Driver Basics
Files and Virtual Files (Review)
User Space
process Memory main(){ func1(); func2();
/mypath/myfile
mounted to root file system
Kernel Space
ATA driver harddrive
Block random
Character - sequential
myFileFd = fopen(/mnt/harddrive/myfile,rw); fread ( aMyBuf, sizeof(int), len, myFileFd ); fwrite( aMyBuf, sizeof(int), len, myFileFd ); fclose( myFileFd );
Array to read into / write from size of item # of items File descriptor / handle
Additionally, use fprintf and fscanf for more feature-rich file read and write capability
06 - 3
Driver Basics
Additionally, drivers use I/O control (ioctl) commands to set driver characteristics
ioctl( soundFd, SNDCTL_DSP_SETFMT, &format); Notes: len field is always in bytes More complex drivers, such as V4L2 and FBDEV video drivers, have special requirements and typically use ioctl commands to perfrom reads and writes
connect_etherusb.sh
The connect_etherusb.sh script manually removes the mass storage USB gadget driver from the Beaglebones running kernel and then dynamically inserts the Ethernet-over-USB gadget driver.
06 - 4
UART Driver
UART Driver
TTY Teletype Terminal
(Left) Early TTYs printed to paper. (Right) screens were later added
Name teletype terminal derives from historical hardware device that is rarely used today All Linux textual terminals (shell, uart, modem, etc.) use the TTY standard Basic open, read, write and close calls to use Common practice is to use the <termios.h> library in place of direct ioctl control calls.
// Simple function to configure a serial port to 1152008N1 void configure_serial(int fd) { struct termios terminal_setting; tcgetattr(fd, &terminal_setting); // Set baud rate // Most drivers use input rate for both cfsetispeed(&terminal_setting, B115200); cfsetospeed(&terminal_setting, B115200);
06 - 5
UART Driver
06 - 6
The ALSA driver provides 3 Linux applications to exercise the driver. While not fancy, record/play apps are useful for testing. The mixer is useful for choosing inputs/outputs. The three apps are: arecord aplay amixer Record audio from an ALSA device to a file Play recorded audio over an ALSA device Select input sources and adjust relative volume levels
/dev/snd/pcmCXDX Manages digital audio capture and playback; most commonly used. /dev/snd/midiCXDX Raw support for MIDI interfaces; user responsible for protocol/timing.
Higher-level interface for MIDI programming. Timing hardware used for synchronizing sound events.
/dev/snd/seq /dev/snd/timer
06 - 7
ALSA Library
PCM Control
open() close()
read() ioctl()
write()
ALSA driver supports standard open, read, write, close and ioctl, however most programmers use the ALSA user-space library calls (snd_pcm_xxx)
ALSA Library
PCM Control
Hardware
AM335x
System DMA
06 - 8
/ Open the device */ rc = sound_pcm_open( &handle, default, SND_PCM_STREAM_PLAYBACK, 0); /* Close the device */ /* Drain call blocks until last data plays */ snd_pcm_drain(handle); snd_pcm_close(handle);
06 - 9
06 - 10
Signal Handling
Signal Handling
Linux Signals
A signal is an event generated by Linux in response to some condition, which may cause a process to take some action when it receives the signal.
Raise indicates the generation of a signal Memory segment violations Floating-point processor errors Illegal instructions User generated at terminal Send from one process (program) to another Catch indicates the receipt of a signal
Application programmers may register signal handling routines If no user signal handler is registered, a default signal handler is used
06 - 11
Signal Handling
/* Callback called when SIGINT is sent to the process (Ctrl-C). */ void signal_handler(int sig) { DBG("Ctrl-C pressed, cleaning up and exiting..\n"); audio_env.quit = 1; // used as while loop condition }
06 - 12
HEAD
start
06 - 13
06 - 14
07 - 1
Module Topics
Module Topics
Module 07: Linux Scheduler .....................................................................................................................7-1 Module Topics..........................................................................................................................................7-2 Linux Processes .......................................................................................................................................7-3 Linux Threads ..........................................................................................................................................7-6 Thread Synchronization ............................................................................................................................7-8 Using Real-Time Threads ........................................................................................................................7-11 Lab 7: Linux Scheduler ..........................................................................................................................7-17
07 - 2
Linux Processes
Linux Processes
What is a Process?
Process A Process B Process C
Physical Processor Process A Memory main(){ func1(); func2(); Process B Memory main(){ func3(); func4(); Process C Memory main(){ func5(); func6();
Scheduling Methodologies
Time-Slicing Threads
Scheduler shares processor run time between all threads with greater time for higher priority 9 No threads completely starve 9 Corrects for non-good citizen threads 8 Cant guarantee processor cycles even to highest priority threads. 8 More context switching overhead
Realtime Threads
Lower priority threads wont run unless higher priority threads block (i.e. pause) 8 Requires good citizen threads 8 Low priority threads may starve 9 Lower priority threads never break high priority threads 9 Lower context-switch overhead
Time-sliced threads have a nieceness value by which administrator may modify relative loading Linux dynamically modifies processes time slice according to process behavior With realtime threads, the highest priority thread always runs until it blocks itself
07 - 3
Linux Processes
Option 2: Audio and Video in separate Processes // audio.c, handles audio only int main(int argc, char *argv[]) { while(condition == TRUE) callAudioFxn(); } // video.c, handles video only int main(int argc, char *argv[]) { while(condition == TRUE) callVideoFxn(); }
audio and video occur at different rates audio and video should be prioritized differently multiple channels of audio or video might be required (modularity) memory protection between audio and video is desired
07 - 4
Linux Processes
All processes are split-off from the original process created at startup When using fork, both processes run the same code; to prevent this, test if newly created process and run another program or exec to another program To review, a process consists of: Context (memory space, file descriptors) One (or more) threads
07 - 5
Linux Threads
Linux Threads
Processes and Threads
Process A Process A global vars
A2 pThread w/ local vars
Threads scheduled individually by priority regardless of which process they reside within No thread isolation a rogue pointer will probably bring down all threads in that process.
Additional threads can be spawned within a process (pThreads) All threads within a process share global variables
Threads vs Processes
Processes 9 9 8 8 no no program Threads 8 8 9 9 yes yes function
Memory protection Ease of use Start-up cycles Context switch Shared globals Scheduled entity Environment
07 - 6
Process Pipes
Linux Threads
#include <pthread.h> int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); pthread_join(pthread_t thread, void **retval); pthread_exit(void *retval);
Re-Joining Main
video_thread main pthread_create(&video_thread, null, video_thread_fxn, ) pthread_exit (retval)
pthread_exit (retval)
07 - 7
Linux Threads
Thread Synchronization
Thread Synchronization (Polling)
void *threadA(void *env){ int test; while(1){ while(test != TRUE) { test = (volatile int) env->driverComplete; } doSomething(env->bufferPtr); } }
Polling
(spin loop)
Thread As doSomething( ) function should only run after the driver completes reading in a new buffer Polling can be used to halt the thread in a spin loop until the driverComplete flag is thrown. But polling is inefficient because it wastes CPU cycles while the thread does nothing.
devComplete = TRUE
Process data
Process data
thread B
07 - 8
Linux Threads
Instead of polling on a flag, the thread blocks execution as a result of the drivers read call More efficient than polling because thread A doesnt waste cycles waiting on the driver to fill the buffer
devComplete = TRUE
Process data
Process data
thread B Thread blocks until driver fills buffer. No wasted cycles! (thread B gets to fill time)
Semaphores are used to block a threads execution until occurrence of an event or freeing of a resource Much more efficient system
07 - 9
Linux Threads
Semaphores
#include <semaphore.h> void *threadA(void *env){ sem_t mySem; sem_init(&mySem, 1, 0); // initial value of zero while(1){ sem_wait(&mySem); doSomethingNext(env->bufferPtr); } }
Blocking
(waits till complete)
A semaphore is the underlying mechanism of the read call that causes it to block
sem_post()
Process data
sem_wait()
Process data
thread B Thread blocks until driver fills buffer. No wasted cycles! (thread B gets to fill time)
Semaphores are used to block a threads execution until occurrence of an event or freeing of a resource Much more efficient system
07 - 10
Linux Threads
Adding a new thread of the highest niceness (smallest time slice) may disrupt lower niceness threads (higher time slices) All threads share the pain of overloading, no thread has time to complete all of its processing Niceness values may be reconfigured, but system unpredictability will often cause future problems In general, what happens when your system reaches 100% loading? Will it degrade in a well planned way? What can you do about it?
Audio thread real-time failure is highly perceptible Video thread failure is slightly perceptible Control thread failure is not remotely perceptible
Note: Time-slicing may also cause real-time failure in systems that are <100% loaded due to increased thread latency
07 - 11
Linux Threads
Audio thread is guaranteed the bandwidth it needs Video thread takes the rest Control thread never runs!
Still a problem:
Audio thread completes as desired Video thread failure is practically inperceptible Control thread never runs User input is locked out
07 - 12
Linux Threads
Audio thread is guaranteed the bandwidth it needs Video thread takes most of remaining bandwidth Control thread gets a small portion of remaining bandwidth
A good compromise:
Audio thread completes as desired Video thread failure is barely perceptible Control thread delayed response is acceptible Bottom Line: We have designed the system so that it degrades gracefully
07 - 13
Linux Threads
Setting the second argument to NULL means the pthread is created with default attributes
pThread attributes: stacksize detachedstate schedpolicy inheritsched schedparam.sched_priority NULL / default value: PTHREAD_STACK_MIN PTHREAD_CREATE_JOINABLE SCHED_OTHER (time slicing) PTHREAD_INHERIT_SCHED 0
pthread_create()
pthread_create (&thread, attr, start_routine, arg)
pthread_create: Creates a new thread and makes it executable. It can be called any number of times from anywhere within your code. pthread_create arguments: thread: A unique identifier (i.e. handle) for the new thread. It is filled-in and returned by pthread_create(). attr: An attribute object that for setting thread attributes. Pass NULL to use default values. start_routine: The C function to be executed once the new thread is created. arg: A single argument passed to start_routine. It must be passed by reference as a void pointer. Use NULL if no argument is to be passed (though that is not the case for our lab exercise).
Once created, threads are peers, and may create other threads.
07 - 14
Linux Threads
SCHED_RR
SCHED_FIFO
Time Sliced scheduling is specified with SCHED_OTHER: Niceness determines how much time slice a thread receives, where higher niceness value means less time slice Threads that block frequently are rewarded by Linux with lower niceness Real-time threads use preemptive (i.e. priority-based) scheduling Higher priority threads always preempt lower priority threads RT threads scheduled at the same priority are defined by their policy: SCHED_FIFO: When it begins running, it will continue until it blocks SCHED_RR: "Round-Robin" will share with other threads at its priority based on a deterministic time quantum
07 - 15
Linux Threads
pthread stands for POSIX thread POSIX threads were introduced to Linux in 1996, but are not widely used because of the (relatively) low overhead of using processes. What does POSIX mean? IEEE POSIX committee defined POSIX 1003.1c standard for threads. Linux threads are modeled after this standard, though dont completely adhere to it. #include <pthread.h> #include pthread.h C compiler pre-processor statement Function declarations for the posix thread library
# gcc D_REENTRANT myProg.c o myprog.o lpthread gcc GNU compiler collection. Invokes compiler, assembler and linker as necessary for specified source files. -D_REENTRANT Defines the _REENTRANT symbol, which forces all included libraries to use reentrant functions. -lpthread Link in the pthread (POSIX thread) library.
07 - 16
HEAD
start
Linux scheduler shares CPU between timesliced threads, so each thread gets a turn to run.
07 - 17
The first realtime thread to run will lock out the second thread. Because delay function uses a for loop instead of sleep (blocking)
thread1
thread2
07 - 18
08 - 1
Module Topics
Module Topics
Module 08: Networking .............................................................................................................................8-1 Module Topics..........................................................................................................................................8-2 Ethernet Basics ........................................................................................................................................8-3 Server/Client Protocols ............................................................................................................................8-6 Berkeley Sockets.......................................................................................................................................8-9 Lab 8: Berkeley Sockets .........................................................................................................................8-11
08 - 2
Ethernet Basics
Ethernet Basics
Networking References
FF.FF.FF.FF.FF.FF 255.255.255.255 www.ti.com Media Access Controller address is unique to a physical device IP address is assigned by network or network administrator Host name and domain name are resolved by domain name servers
Address Resolution Protocol (ARP) resolves MAC addresses from IP addresses Domain Name Service (DNS) resolves IP addresses from host and domain name
Sub-networks
FF.FF.FF.FF.FF.FF 255.255.255.255 WAN LAN 2^48 MAC Addresses >> 2^32 IP Addresses WAN = Wide Area Network
the cloud. WAN addresses are unique (but may be dynamic)
08 - 3
Ethernet Basics
Sub-networks
WAN LAN 255.255.255.255
Sub-networks are formed using a netmask
If <Dest> & Netmask = <Source> & Netmask then source and destination are on the same subnet. Else, destination packet is forwarded to the WAN.
Sub-network Example
WAN
203.114.28.8
255.255.255.0
netmask
LAN
192.168.1.5
192.168.1.1
D
192.168.1.3
192.168.1.7
A B C Computer A sends a packet to IP address 192.168.1.7 Computer A (192.168.1.5) & 255.255.255.0 = 192.168.1.0 Destination & 255.255.255.0 = 192.168.1.0 This is a transmission within the subnet, packet is sent directly to destination.
08 - 4
Ethernet Basics
Sub-network Example
WAN
203.114.28.8
255.255.255.0
netmask
LAN
192.168.1.5
192.168.1.1
D (Gateway)
192.168.1.3
192.168.1.7
A B C Computer A sends a packet to IP address 116.97.23.47 Computer A (192.168.1.5) & 255.255.255.0 = 192.168.1.0 Destination & 255.255.255.0 = 116.97.23.0 Packet is forwarded to the Gateway to be sent to the wide area network.
08 - 5
Server/Client Protocols
Server/Client Protocols
IP Ports
In addition to an IP address, connection requests may specify a port number. Ports are generally used in order to route connection requests to the appropriate server.
Service echo ftp ssh telnet nameserver http Port 7 20/21 22 23 42 80
Client/Server model Server is a static background (daemon) process, usually initiated at startup, that listens for requests from one or more clients.
LAN
:1001
:1000
D (Gateway)
:1003
:1002
The Network Address Translation (NAT) protocol allows the gateway to assign port numbers to individual endpoints within the subnet. In this example, Computer A, port 22 (ssh) is mapped by the gateway to 203.114.28.8:1001
08 - 6
Server/Client Protocols
08 - 7
Server/Client Protocols
inetd/xinetd
user@ubuntu:~$ ls /etc/xinetd.d chargen daytime discard echo tftp time service tftp { protocol = udp port = 69 socket_type = dgram wait = yes user = nobody server = /usr/sbin/in.tftpd server_args = /tftpboot disable = no }
Beaglebone Arago distribution does not use xinetd Many desktop distributions do, including Ubuntu Ubuntu launches xinetd from /etc/rc5.d/S20xinetd
xinetd is a single server (daemon process) that launches various IP services (as opposed to having each service running independent servers.)
08 - 8
Berkeley Sockets
Berkeley Sockets
Berkeley Sockets Basic Procedure
sFD = socket(); sFD = socket();
connect(sFD, addr, );
// do reads and writes
shutdown(sFD,); close(sFD);
}
Socket Types
Local Socket sFD = socket(AF_UNIX, SOCK_STREAM, 0); TCP/IP Socket sFD = socket(AF_INET, SOCK_STREAM, 0); UDP/IP Socket sFD = socket(AF_INET, SOCK_DGRAM, 0);
Final parameter to socket function is protocol. Protocol is typically determined completely by first two parameters, so that 0 (default) is usually passed.
08 - 9
Berkeley Sockets
Client
connect(SocketFD, (struct sockaddr *)&stSockAddr, sizeof(stSockAddr));
Server
bind(SocketFD,(struct sockaddr *)&stSockAddr, sizeof(stSockAddr))
Server Details
listen(int sFD, int backlog); listen creates an incoming connection queue socketFD is the file descriptor backlog is the maximum number of connection requests to hold in the queue accept(int sFD, sockaddr *address, size_t *len); address and len (of address struct) are used to return the address of the connecting client. If this is not of interest, NULL may be passed. shutdown(int sFD, int how); how may be SHUT_RD, SHUT_WR, SHUT_RDWR possible to call with SHUT_RD followed by SHUT_WR shutdown informs TCP/IP stack to terminate session, but does not close file descriptor. Many systems implement shutdown automatically in close, but best to always call.
08 - 10
start
solution_A
lab08_x86_server
master
solutions
start
solution_A
08 - 11
08 - 12
09 - 1
Module Topics
Module Topics
Module 09: Video and Graphics Drivers..................................................................................................9-1 Module Topics..........................................................................................................................................9-2 Linux v4L2 Video Driver ...........................................................................................................................9-3 Using mmap.........................................................................................................................................9-6 (Optional) v4L2 Coding ......................................................................................................................9-8 Linux FBdev Display Driver ...................................................................................................................9-10
09 - 2
Module Topics
v4l2 is a standard Linux video driver used in many linux systems Supports video input and output
Device node
v4l2 spec:
owns buffer
Application takes ownership of a full video buffer from the outgoing driver queue using the VIDIOC_DQBUF ioctl After using the buffer, application returns ownership of the buffer to the driver by using VIDIOC_QBUF ioctl to place it on the incoming queue
owns buffer
v4l2 driver
application
09 - 3
Module Topics
App
Buffers typically exist in drivers memory space The dequeue call makes the data available to the app
1 2 3 4
App
Buffers typically exist in drivers memory space The dequeue call makes the buffer available to the app Even after DQ, buffers still exist in the drivers memory space but not the applications
09 - 4
Module Topics
Buffers typically exist in drivers memory space The dequeue call makes the buffer available to the app Even after DQ, buffers still exist in the drivers memory space but not the applications read and write operations copy buffers from drivers memory space to apps or vice-versa
Buffers typically exist in drivers memory space These buffers exist in the drivers memory space but not the applications read and write operations copy buffers from drivers memory space to apps or vice-versa
09 - 5
Module Topics
Using mmap
Standard read and write copy data from driver buffer to a new buffer in application processs memory space
driver IQ OQ DQ EQ
1 read 2 3 4
App 1 2 3 4
(mmap) 1 2 3 4 App 1 2 3 4
Use mmap to expand the application processs memory space to include the driver buffer Returns a pointer to the location in the apps memory space
driver IQ OQ
DQ
App
The VIDIOC_DQBUF ioctl blocks the threads execution waits if until a buffer is available on the output queue When driver adds a new, full buffer to the output queue, the application process is released Dequeue call completes and application resumes with the following set of commands
09 - 6
Module Topics
App
The VIDIOC_DQBUF ioctl blocks the threads execution waits if until a buffer is available on the output queue When driver adds a new, full buffer to the output queue, the application process is released Dequeue call completes and application resumes with the following set of commands
App
The VIDIOC_DQBUF ioctl blocks the threads execution waits if until a buffer is available on the output queue When driver adds a new, full buffer to the output queue, the application process is released Dequeue call completes and application resumes with the following set of commands
09 - 7
Module Topics
v4l2 Synchronization
v4l2 driver IQ OQ (empty) DQ
5 6 7 8
App 5 6 7 8
The VIDIOC_DQBUF ioctl blocks the threads execution waits if until a buffer is available on the output queue When driver adds a new, full buffer to the output queue, the application process is released Dequeue call completes and application resumes with the following set of commands
Request the driver allocate a new buffer ioctl(fd, VIDIOC_REQBUFS, &req); Get information on a driver buffer ioctl(fd, VIDIOC_QUERYBUF, &buf); Enqueue and Dequeue buffers to/from driver ioctl(fd, VIDIOC_QBUF, &buf); Ioctl(fd, VIDIOC_DQBUF, &buf);
09 - 8
Module Topics
// start address (ususally 0) // length // allowed use for mapd memory // allow sharing of mapped bufs // driver/file descriptor // offset requested from start
A simple flow would be: (1) DQBUF the buffer, (2) map it into user space, (3) use the buffer, (4) unmap it, (5) put it back on the drivers queue More efficient code would map each driver buffer once during initialization, instead of mapping and unmapping within the loop Alternatively, later versions of the driver allow you to create the buffer in user space and pass it to the driver
09 - 9
Module Topics
FBdev is a standard Linux video output driver used in many linux systems Can be used to map the frame buffer of a display device into user space Device nodes have major number 29 Device nodes have a minor number x Uses /dev/fb/x node naming convention
Source: DirectFBOverview.pdf
09 - 10
Module Topics
Allows Pixel by Pixel Blending of OSD and Video Windows Uses an 8-bit, Attribute (Alpha Blending) Value
32-bit ARGB Pixel Value 8-bit Attribute 8-bit Red
FF
8-bit Green
D0 A0 80
8-bit Blue
60 40 20 00
8-bit blending
0x00: 00.0%, 100% Video 0x20: 12.5%, 87.5% Video 0x40: 25.0%, 75.0% Video 0xA0: 75.0%, 25.0% Video 0xFF: 100%, 00.0% Video
xoffset yres
yres_virtual
xres xres_virtual
Named FBdev because it gives direct access to the display devices frame buffer FBIOPAN_DISPLAY allows users to pan the active display region within a virtual display buffer
09 - 11
Module Topics
offset = (yres,0)
buffer1 (pong)
yres_virtual
xres_virtual
FBdev has no video buffer queue (provides direct access to the display devices frame buffer) Use FBIOPAN_DISPLAY to switch between 2 or more buffers in the virtual buffer space Use FBIO_WAITFORVSYNC to block process until current buffer scan completes, then switch. In our case...
offset = (yres,0)
buffer1 (pong)
yres_virtual
xres_virtual
FBdev has no video buffer queue (provides direct access to the display devices frame buffer) Use FBIOPAN_DISPLAY to switch between 2 or more buffers in the virtual buffer space Use FBIO_WAITFORVSYNC to block process until current buffer scan completes, then switch.
09 - 12
Module Topics
Buffer Synchronization
yres pVirtualBuf = mmap(NULL,display_size * NUM_BUFS, PROT_READ | PROT_WRITE, MAP_SHARED, FbdevFd, 0); while(cond){ // map next frame from virtual buffer display_index = (display_index +1) % NUM_BUFS; ioctl(pFbdevFd, FBIOGET_VSCREENINFO, &vinfo); vinfo.yoffset = vinfo.yres * display_index; // write pixels into next video frame genPicture(); // switch to next frame ioctl(pFbdevFd, FBIOPAN_DISPLAY, &vinfo); // wait for current frame to complete ioctl(pFbdevFd, FBIO_WAITFORVSYNC, NULL); }
Blocking on select()
int wait_for_frame(int fd) { struct timeval tv; fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); tv.tv_sec = 2; // Use select to wait for next filled frame ret = select(fd + 1, &fds, NULL, NULL, &tv); } // timeout value // set of file descriptors to wait on // using a file descriptor set of only one // value passed in as function parameter // timeout after 2 seconds if no new frame // largest file descr value to test // set of fds to wait on read // fds to wait on write or error // timeout value
Reasons to use select(): Can block on multiple events Allows specification of a timeout value for blocking
09 - 13
Module Topics
ioctl(fd, FBIOGET_VSCREENINFO, &myVarScreenInfo); ioctl(fd, FBIOPUT_VSCREENINFO, &myVarScreenInfo); ioctl(fd, FBIOGET_FSCREENINFO, &myFixScreenInfo); ioctl(fd, FBIOPAN_DISPLAY, &myVarScreenInfo); ioctl(fd, FBIO_WAITFORVSYNC, NULL);
09 - 14
10 - 1
Module Topics
Module Topics
Module 10: Qtopia GUI Development ....................................................................................................10-1 Module Topics........................................................................................................................................10-2 Graphics Software Layers......................................................................................................................10-3 Qtopia ....................................................................................................................................................10-6
10 - 2
A terminal is a text-based interface to Linux O/S Commands are interpreted by a shell program (such as BASH) A terminal may connect via RS-232, Ethernet, etc. xterm is a terminal which connects via the X window server, i.e. receives input via x11 HID and outputs to x11 display Most applications which can be launched from the Desktop (i.e. a drop-down menu) can be equivalently launched by typing a command into a Linux terminal
Desktop Managers
Gnome and KDE are two of many Linux display managers Desktop managers provide a Desktop or similar environment (i.e. for handheld device) Applications (such as mplayer or xterm) typically interface directly to x11 and are therefore independent of the Display Manager Gnome display manager is just another client to x11 A display manager isnt required to run Linux x11 isnt required to run Linux, though it is required by many graphical applications
10 - 3
XSM (x11 session manager) XDM (x11 Display Manager) x11 window manager X server Linux FBDEV framebuffer driver
Device
AM335x
Gnome Desktop Gnome Session Manager GDM (Gnome Display Manager) x11 window manager X server Linux FBDEV framebuffer driver
Device
AM335x
KDE ... as a quick comparison
10 - 4
K Desktop Environment
KDE (K Desktop Environment) ksmserver (session mgr) KDM (KDE Display manager) kwm (K window mgr) QT embedded (QT / e)
(No Display Server, direct framebuffer access via widget lib)
KDE (K Desktop Environment) ksmserver (session mgr) KDM (KDE Display manager) kwm (K window mgr) QT over x11 (QT / x11) X server Linux FBDEV Framebuffer Driver
AM335x
AM335x
10 - 5
Qtopia
Qtopia
QT Framework
Qt provides a well defined API that can make development quick and easy.
Qt SDK
Qt modular class library
GUI WebKit Graphics View OpenGL Multimedia Core XML Scripting Database Network UI Tests Benchmarking Font Engine Qt development tools
Qt Creator Cross-platform IDE
Qt Designer Forms Builder Qt Assistant Help reader
Webkit
Well accepted open source web browser Rapidly create real-time web content and services Use HTML and Java Script integrated in native code
Cross-platform support
Windows Linux/X11 Embedded Linux Windows CE
10 - 6
Qtopia
Qt Embedded QGLWidget QWidget Gstreamer/FFMPEG Wifi MPEG4, H.264, MPEG2, AAC, BlueZ
OpenGL ES
FBDEV DSS2
V4L2
ALSA I2C
VISA USB
McSPI McBSP
Ethernet
UART
Hello World!
#include <QApplication> #include <QLabel> int main(int argc, char **argv) { QApplication app(argc, argv); QLabel label("Hello World!"); label.show(); return app.exec(); }
10 - 7
Qtopia
Run make to build the application make Application is built and ready in debug/ directory. Copy executable to your filesystem on your target and run.
10 - 8
Qtopia
The UI created on the previous slide is stored as .xml QT Creator then generates the UI from this .xml file
10 - 9
Qtopia
Alternately, users may program using C++ object classes for each widget
Widgets
Qt UI framework is based on widgets Widgets respond to UI events (key presses/mouse movements), and update their screen area Each widget has a parent, that affects its behavior, and is embedded into it Most Qt classes are derived from QWidget Refer to online documentation at http://doc.qt.nokia.com/4 .6/qwidget.html Tip Documentation is arranged using class names.
10 - 10
Qtopia
Widgets
QWTPlotCurve QHBoxLayout QComboBox QDoubleSpinBox
Q S l i d e r
QMainWindow
QMessageBox
QPushButton
Qlabel
Signals & Slots Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from the features provided by other frameworks. Signals Events occur and cause a signal Widgets contain a list of predefined signals, but you can subclass a widget to add your own signal Example button press, or Process complete Slots are the functions which are assigned to handle a signal. Widgets contain a list of predefined slots. You can subclass a widget and add your own slots
10 - 11
Qtopia
The signal sliderMoved(int) is generated whenever the horizontal slider is moved By adding this signal to the lcdNumber display(int) slot, the LCD will display the value of the horizontal slider when it is moved.
Here a GUI object signal is tied directly to another GUI object slot; however, programmers can also write C++ functions to interface to signals and slots, thus connecting their interface to back-end functionality.
10 - 12
11 - 1
Module Topics
Module Topics
Customizing Linux Kernel for Fast Boot ...............................................................................................11-1 Module Topics........................................................................................................................................11-2 Acquiring Timing Information ...............................................................................................................11-3 Kernel Boot Time Improvements............................................................................................................11-5 Kernel Board Port..................................................................................................................................11-9
11 - 2
Timer starts when kernel begins booting Significant portion of kernel boot instrumented
11 - 3
It is possible to graphically view these initcall times using the bootgraph script in the Linux kernel sources. This requires CONFIG_PRINTK_TIME to be enabled
cat <bootlog> | perl <kernel source dir>/scripts/bootgraph.pl > boot.svg
Additionaly you can use other tools to help you analyze the Linux kernel such as:
Linux Trace Toolkit (LTTng) Oprofile
System wide profiler Visualizes boot process Timing for certain kernel and process events
Bootchart
11 - 4
/etc/rcX.d
Kernel Module Examples: fbdev frame buffer dev v4l2 video for linux 2 nfsd network file server dev dsp oss digital sound proc. audio alsa audio driver
Linux Kernel source code is broken into individual modules Only those parts of the kernel that are needed are built in
2. Dynamic (insmod)
Use insmod (short for insert module) command to dynamically add modules into the kernel Keep statically built kernel small (to reduce size or boot-up time), then add functionality later with insmod Insmod is also handy when developing kernel modules
11 - 5
Kernel Build
n
RBL
ROM
MLO
U-Boot
DDR2
Kernel
DDR2
host$ cd ti-sdk-am35x-evm_xxx/board_support/linux-xxx-psp-xxx host$ make mrproper host$ make ARCH=arm* am335x_evm_defconfig** host$ make ARCH=arm menuconfig host$ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- uImage host$ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- modules host$ make INSTALL_MOD_PATH=${HOME}/targetfs modules_install
host$ host$
ls arch/ ls arch/arm/configs
Default Configurations
ubuntu$ make ARCH=arm am335x_evm_defconfig
ubuntu$ ls arch/arm/configs acs5k_defconfig fortunet_defconfig acs5k_tiny_defconfig g3evm_defconfig afeb9260_defconfig g4evm_defconfig ag5evm_defconfig h3600_defconfig am200epdkit_defconfig h5000_defconfig am335x_evm_defconfig h7201_defconfig
Note: these filenames must end in _defconfig to be recognized as default configurations. The default configuration file is used to generate a hidden file named .config at the top level of the kernel build directory.
11 - 6
Custom Configuration
Step 1: Start with an existing default configuration ubuntu$ make ARCH=arm am335x_evm_defconfig Step 2: Modify the configuration ubuntu$ make ARCH=arm menuconfig Step 3: Save as a new default configuration ubuntu$ copy .config arch/arm/am335x_fastboot_defconfig
Though not required, it is a good idea to save your custom configuration as a new kernel default configuration in case you need to modify later.
11 - 7
Kernel Compile Flags Reduce filesystem size Use faster media to store kernel and filesystem
MMC/SD
NAND Flash
Defer
It
is possibly to defer module init calls without having to build the modules dynamically. This requires kernel rebuild Once the system booted the deferred calls can be executed by doing:
echo 1 > /proc/deferred_initcalls
Additional
details at http://elinux.org/Deferred_Initcalls
11 - 8
16
Board
The Makefiles create variables named platform-y, machine-y, and obj-y, that define the directories and ultimately files to be added into the kernel binary. 17
17
11 - 9
19
11 - 10
20
Board Porting
Much of the board-specific configuration of the Linux kernel is handled by the Machine and Platform files. Machine = Board Specific Platform = Device Specific So generally you will want to define a new Machine for a new board, but dont need a new Platform. Note, however, that in some cases the CONFIG_ARCH_xxx switches may be referenced in Linux drivers and other common code. (See next slide)
21
21
11 - 11
Sometimes there is a TIspecific driver file. Sometimes there is simply a #define switch in a generic driver file.
11 - 12
12 - 1
Module Topics
Module Topics
Optimizing and Customizing U-boot ......................................................................................................12-1 Module Topics........................................................................................................................................12-2 Kernel Boot Option Improvements.........................................................................................................12-3 Initial Ram Disk .....................................................................................................................................12-4 U-boot Rebuild .......................................................................................................................................12-6
12 - 2
Use the quiet bootargs option to disable routine status printfs to console Remove the console altogether
Remove console=ttyO0,115200n8 from bootargs
12 - 3
EXT3 / EXT4 / FAT EXT3 / EXT4 / FAT UBIFS / JFFS2 / YAFFS NFS / SMBFS RAMFS / CRAMFS
Your choice of root filesystem type and storage media may has a significant impact on the time required to boot. -- Initialization of memory interface -- Filesystem mount time -- Read/Write speed
12 - 4
12 - 5
U-boot Rebuild
U-boot Rebuild
MLO (U-boot_min) Build
n
RBL
ROM
MLO
U-Boot
DDR2
Kernel
DDR2
host $ cd ti-sdk-am335x-evm-xxx/board_support/u-boot-xxx host $ make distclean host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- am335x_evm_config host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- MLO
host$ make ARCH=<ARCH> CROSS_COMPILE= <target>_config <ARCH> and <Target> as defined in boards.cfg
U-Boot Build
n
RBL
ROM
MLO
U-Boot
DDR2
Kernel
DDR2
host $ cd ti-sdk-am335x-evm-xxx/board_support/u-boot-xxx host $ make distclean host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- am335x_evm_config host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- u-boot.img
host$ make ARCH=<ARCH> CROSS_COMPILE= <target> <ARCH> and <Target> as defined in boards.cfg
12 - 6
U-boot Rebuild
# Target
ARCH
CPU
Board name
Vendor
SoC
########################################################## davinci_dm355evm davinci_dm365evm davinci_dm6467evm am3517_evm am335x_evm arm arm926ejs dm355evm davinci davinci davinci davinci davinci omap3 ti81xx
arm arm926ejs dm6467evm davinci arm arm armv7 armv7 am3517evm logicpd am335x ti
13
13
U-Boot Sources
board/<Vendor>/<Board name>
arch/<ARCH>/include/asm/arch-<SoC>
include/configs/<Target>.h
14
12 - 7
U-boot Rebuild
Reduce environment size so that less data is read into memory CONFIG_ENV_SIZE Remove Unnecessary Console Print Statements CONFIG_SILENT_CONSOLE 1 Set bootdelay to 0 Disable un-used peripherals #undef CONFIG_USB_* #undef CONFIG_NAND #undef CONFIG_MMC #undef CONFIG_SPI #undef CONFIG_FLASH_* Avoid long help text for the u-boot commands to save space #undef CONFIG_SYS_LONGHELP Use simple parser - instead of hush #undef CONFIG_SYS_HUSH_PARSER
15
16
12 - 8