Вы находитесь на странице: 1из 180

Introduction to Embedded Linux

Student Guide

Revision 2.00 April 2013

Technical Training Organization

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.

Copyright 2012 Texas Instruments Incorporated

Revision History
August 2012 Revision 1.0

Mailing Address
Texas Instruments Training Technical Organization 6550 Chase Oaks Blvd Building 2 Plano, TX 75023

ii

Introduction to Embedded Linux

Module 01: Booting Linux


Introduction
This module begins by showing how a Linux distribution may be booted using a provided u-boot bootloader, Linux kernel and Linux filesystem. Next it shows how those same three elements may be rebuilt from source code and possibly reconfigured. Finally, the module covers some details of the System five (sys-V) initialization standard that is used to specify the startup configuration of many Linux distributions, including Arago (Beaglebone distribution) and Ubuntu (x86 Distribution.)

Introduction to Embedded Linux - Module 01: Booting Linux

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

Introduction to Embedded Linux - Module 01: Booting Linux

Module Topics

Introduction to Embedded Linux - Module 01: Booting Linux

01 - 3

Booting Linux from Pre-Built Binaries

Booting Linux from Pre-Built Binaries


n Bootloader

Linux in Three Parts

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

Linux Boot Process


Power On

Boot Loader Linux Kernel

U-Boot Linux Kernel Mount root filesys Init Process

ARM assembly code Passes args to Linux (bootargs)

Initialize hardware via static drivers

/sbin/init 1st process exe by kernel


File System Login Prompt

Login console Usually one of first progs to run

01 - 4

Introduction to Embedded Linux - Module 01: Booting Linux

Booting Linux from Pre-Built Binaries

Where Do You Find


Where located:
1a.

Flash Boot n/a Flash Flash Flash

SBL, UBL or MLO

1b. Bootloader (U-Boot) 2. 3.

Linux Kernel Filesystem

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

Where Do You Find


Where located:
1a.

Flash Boot n/a Flash Flash Flash

MMC Boot MMC MMC MMC MMC

SBL, UBL or MLO

1b. Bootloader (U-Boot) 2. 3.

Linux Kernel Filesystem

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

Introduction to Embedded Linux - Module 01: Booting Linux

01 - 5

Booting Linux from Pre-Built Binaries

Booting Linux MMC/SD Boot


n
RBL
ROM

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

Where Do You Find


Where located:
1a.

Flash Boot n/a Flash Flash Flash

MMC Boot MMC MMC MMC MMC

NFS Boot bootp / tftp tftp tftp nfs

SBL, UBL or MLO

1b. Bootloader (U-Boot) 2. 3.

Linux Kernel Filesystem

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

Introduction to Embedded Linux - Module 01: Booting Linux

Booting Linux from Pre-Built Binaries

Step 1: Setup EZSDK


Setup and Rebuild Linux EZSDK
host $ sudo apt-get update host $ cd ti-sdk-am335x-evm-xx.xx.xx.xx host $ sudo ./setup.sh

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

Step 2: Boot Linux from MMC


MMC Boot
Attach SD/MMC programmer with inserted Micro-SD adapter host $ cd ti-sdk-am335x-evm-xx.xx.xx.xx/bin host $ sudo ./create-sdcard.sh ROM bootloader will load a file named MLO from partition 1, which must be FAT32 filesystem from partition 1 of FAT32 MMC

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.

Introduction to Embedded Linux - Module 01: Booting Linux

01 - 7

Booting Linux from Pre-Built Binaries

U-boot Default Scripting


Detect MMC? Attempt to load uEnv.txt Boot from NAND Attempt to run uenvcmd Attempt boot from MMC

Other Boot Options (Macros in Default U-boot Environment) 1. NOR Flash boot 2. SPI Flash boot 3. TFTP/NFS (network) boot

Linux Boot Arguments for MMC Boot


mmc_load_uimage= fatload mmc 0 0x80007fc0 uImage
uBoot will attempt to load Linux kernel binary with filename uImage from mmc/sd partition 0, which must be fat32 formatted. Kernel image will be loaded into physical address 0x80007fc0, an offset into DDR3. Subsequent call of bootm will boot the kernel from DDR3.

bootargs= console=ttyO0,115200n8 bootdelay=3 root=/dev/mmcblk0p2 rw rootfstype=ext3 rootwait ip=none


Linux boot arguments set up a serial console for login and specify the root filesystem location as mmc/sd device 0 partition 2, which must be ext3 formatted. ip=none allows boot scripts in filesystem to define ip settings (/etc/network/interfaces). bootdelay and rootwait provide delays for mmc.

01 - 8

Introduction to Embedded Linux - Module 01: Booting Linux

Rebuilding and Modifying SDK Components

Rebuilding and Modifying SDK Components

Rebuilding EZSDK
Rebuild SDK
host $ make help host $ make clean host $ make all

Install rebuilt components to export directory (default ${HOME}/targetfs)


host $ make install

make all rebuilds: U-boot Linux Kernel OpenGL graphics Demos Example Applications Wireless Driver Support

Booting Linux MMC/SD Boot


n
RBL
ROM

(x-loader) Internal RAM

MLO

U-Boot
DDR2

Kernel
DDR2

Device

RBL MLO (x-loader)


OCMC (on-chip memory controller) Internal memory

n o p

MLO (x-loader) 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

Introduction to Embedded Linux - Module 01: Booting Linux

01 - 9

Rebuilding and Modifying SDK Components

MLO (U-boot_min) Build


n
RBL
ROM

(x-loader) Internal RAM

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

* For available configs:

host$

ls include/configs

U-Boot Build
n
RBL
ROM

(x-loader) Internal RAM

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

Both MLO and u-boot.img may be built simultaneously using


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

01 - 10

Introduction to Embedded Linux - Module 01: Booting Linux

Rebuilding and Modifying SDK Components

Kernel Build
n
RBL
ROM

(x-loader) Internal RAM

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

* For available ARCH: ** For available configs:

host$ host$

ls arch/ ls arch/arm/configs

make menuconfig options

Introduction to Embedded Linux - Module 01: Booting Linux

01 - 11

Rebuilding and Modifying SDK Components

Kernel Object Modules


1. Static (built-in) oss v4l2

Linux Kernel fbdev nfsd dsp httpd ext3

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)

# insmod <mod_name>.ko [mod_properties]


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

.ko = kernel object

01 - 12

Introduction to Embedded Linux - Module 01: Booting Linux

System Startup Details

System Startup Details

Linux Boot Process


Power On

Boot Loader Linux Kernel

U-Boot Linux Kernel Mount root filesys Init Process

ARM assembly code Passes args to Linux (bootargs)

Initialize hardware via static drivers

/sbin/init 1st process exe by kernel


File System Login Prompt

Login console Usually one of first progs to run

Linux Initialization Process


The initialization process is launched by the Linux Kernel after the root filesystem is mounted By default it is located at /sbin/init, but it can be specified as a kernel boot argument /sbin/init /etc/inittab /etc/init.d
bootmisc.sh mountnfs.sh networking syslog telnetd thttpd

/etc/rcX.d

S05networking S20syslog S10telnetd S20syslog S20thttpd S60mountnfs

Introduction to Embedded Linux - Module 01: Booting Linux

01 - 13

System Startup Details

SysV Startup
/etc/init.d /etc/rcX.d

bootmisc.sh mountnfs.sh syslog ...

S05networking S20syslog S10telnetd ...

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

Beaglebone Arago Runlevel 5 Startup


/etc/rcS.d
S01psplash S02banner S03sysfs S03udev S06alignment S10checkroot S12udev-cache S20modutils.sh S30ramdisk S35mountall.sh S37populate-volatile.sh S38devpts.sh S39alsa-state S40configure S41networking S45mountnfs.sh S55bootmisc.sh S99finish.sh

/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

Introduction to Embedded Linux - Module 01: Booting Linux

System Startup Details

/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

devpts mode=0620,gid=5 0 0 tmpfs defaults,size=16M 0 0 tmpfs mode=0777 tmpfs defaults,size=16M 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

Introduction to Embedded Linux - Module 01: Booting Linux

01 - 15

System Startup Details

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

S05networking S20syslog S10telnetd ...

01 - 16

Introduction to Embedded Linux - Module 01: Booting Linux

Lab 1 Introduction

Lab 1 Introduction

Lab 1: Booting Linux


A. Start and Configure Ubuntu Vmware B. Create Bootable SD Card C. Boot Linux on Beaglebone Vmware: Software emulated Computer within a computer. Allows us to run Ubuntu Linux on a Windows machine Ubuntu: Very popular desktop distribution of Linux Completely Free

Lab 1: Booting Linux


A. Start and Configure Ubuntu Vmware B. Create Bootable SD Card C. Boot Linux on Beaglebone

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

MLO (i.e. x-loader) u-boot.img uImage (i.e. Kernel)

Partition 1

(FAT32)

Root Filesystem

Partition 2

(EXT3)

Introduction to Embedded Linux - Module 01: Booting Linux

01 - 17

Lab 1 Introduction

Lab 1: Booting Linux


A. Start and Configure Ubuntu Vmware B. Create Bootable SD Card C. Boot Linux on Beaglebone

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

Introduction to Embedded Linux - Module 01: Booting Linux

Module 02: Linux Distributions


Introduction
A Linux distribution is the entire collection of software necessary to run Linux on a given platform. At the minimum, this is a bootloader, a Linux kernel and a Linux filesystem. Additionally, some distributions incorporate various tooling for configuring or debugging the distribution. This module will discuss distributions genericly, then focus on the Arago distribution, which is the distribution that is tested and maintained by Texas Instruments for use on TI platforms.

Introduction to Embedded Linux - Module 02: Linux Distributions

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

Introduction to Embedded Linux - Module 02: Linux Distributions

(Short) Product Overview

(Short) Product Overview


TI Embedded Processors Portfolio
Microcontrollers
16-bit
MSP430 Ultra-Low Power Up to 25 MHz Flash 1 KB to 256 KB Analog I/O, ADC LCD, USB, RF Measurement, Sensing, General Purpose $0.49 to $9.00

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

ARM CPU Processor Cores


Classic
ARM Processors

Embedded
Cortex Processors

Application
Cortex Processors

Performance, Functionality

Cortex-A8 Cortex-R4 Cortex-M4 Cortex-M3 ARM7


Capability

ARM11 ARM9

http://www.arm.com/products/processors/index.php

TIs ARM core's supporting Linux...

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 3

(Short) Product Overview

TI ARM investment and innovation


1st single-chip digital baseband DSP/ARM multi-core TI Licenses first ARM core Introduce Stellaris ARM MCU Lead CortexFixed/ FloatingLicensee A15 Point based on TI Introduced DaVinci Two ARM Stellaris Stellaris ARM9 silicon Acquires CortexCortex-R4 processors for DustDevil SoC Fury M4 OMAP cores digital video Class OMAP Luminary Class TI OMAP 5 Micro for ARM9-based SoCs Licenses OMAP-L138 automotive ARM *TI first licensee for Cortex-A9 ARM Cortex- A8
DaVinci TMS570 MCU

1993

1995

2002

2005

2006

2007

2008
Stellaris Tempest Class

2009

2010

2011

1st multi-core applications processor, ARM9-based


OMAP
OMAP1510

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.

AM335x Cortex-A8 based processors


Benefits
High performance Cortex-A8 at ARM9/11 prices Rich peripheral integration reduces complexity and cost

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

Graphics PowerVR SGX 3D Gfx

Display 24 bit LCD Ctrl (WXGA) Touch Scr. Ctrl.**

Security w/ crypto acc. 64K Shared RAM

PRU SS PRU x2 200 MHz 8K P. w/SED 8K D. w/SED 12K RAM w/SED Peripherals

Software and development tools

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

Schedule and packaging


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

Memory Interface LPDDR1/DDR2/DDR3 NAND/NOR (16b ECC)

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

Introduction to Embedded Linux - Module 02: Linux Distributions

(Short) Product Overview

AM335x/WL1271 Development Kit


AM335x EVM available for purchase through TI E-store: TMDXEVM3358

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

COM6M WL1271 Adapter Board is included in AM335x EVM Kit

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

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 5

(Short) Product Overview

What is Pin Multiplexing?


Pin Mux Example

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

Pin mux utility...

Pin Muxing Tools

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

Introduction to Embedded Linux - Module 02: Linux Distributions

Linux Distributions

Linux Distributions

What Is a Linux Distribution


A Linux distribution is a combination of the components required to provide a working Linux environment for a particular platform: 1. Linux kernel port

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

Linux file system


4.

Development tools

O/S Choices
Choices

Linux

Android
(arowboat.org)

WinCE

Others

QNX

Commercial

Community

Build It Yourself

Nucleus BIOS Etc.

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 7

Linux Distributions

O/S Choices
Choices

Linux

Android
(arowboat.org)

WinCE

Others

QNX

Commercial

Community

Build It Yourself

Nucleus BIOS Etc.

Commercial O/S Vendors

Linux

MontaVista TimeSys Wind River Mentor Ridgerun Adeneo Mistral MPC Data BSQUARE

WinCE

RTOS

Green Hills Wind River (VxWorks) ELogic (ThreadX) QNX Mentor (Nucleus)

Linux Partner Strategy


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

Introduction to Embedded Linux - Module 02: Linux Distributions

Linux Distributions

O/S Choices
Choices

Linux

Android
(arowboat.org)

WinCE

Others

QNX

Commercial

Community

Build It Yourself

Nucleus BIOS Etc.

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

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 9

Linux Distributions

Arago Feedback Loop


kernel.org uboot source Open Embedded Angstrom Arago TI-specific drivers and patches pushed back to community Various GNU apps

O/S Choices
Choices

Linux

Android
(arowboat.org)

WinCE

Others

QNX

Commercial

Community

Build It Yourself

Nucleus BIOS Etc.

02 - 10

Introduction to Embedded Linux - Module 02: Linux Distributions

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.

Bitbake Recipe File


aDESCRIPTION = "nodeJS Evented I/O for V8 JavaScript HOMEPAGE = "http://nodejs.org" LICENSE = "MIT" DEPENDS = "openssl" SRC_URI = " http://nodejs.org/dist/node-v${PV}.tar.gz file://libev-cross-cc.patch file://node-cross-cc.patch " SRC_URI[md5sum] = "c6051dd216817bf0f95bea80c42cf262 " S = "${WORKDIR}/node-v${PV}" do_configure () { ./configure --prefix=${prefix} --without-snapshot } do_compile () { make } do_install () { DESTDIR=${D} oe_runmake install }

http://www.openembedded.org/wiki/How_to_create_a_bitbake_recipe_for_dummies

Includes download instructions, build instructions and dependencies

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 11

Linux Distributions

Arago Project Downloads

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

Introduction to Embedded Linux - Module 02: Linux Distributions

Linux Distributions

Using opkg to Add New Packages


To see the commands the opkg package manager supports host$ opkg To install an opkg-compliant package host$ opkg install <packagename>.ipkg To download a package but not install it host$ opkg download <packagename> To find out which packages provides a given file host$ opkg whatprovides <filename> To list which packages are available host$ opkg list To update the list of available packages and whatprovides search host$ opkg update

Using opkg to Trim Down a Filesystem


You can start by listing all packages that are installed on the system host$ opkg list-installed If you find a package you dont think you need, good idea to check what other packages depend on it before removing host$ opkg whatdepends <packagename> Assuming you dont need any of the packages that depend on this one, you can remove it and all dependent packages host$ opkg remove <packagename> \ --force-removal-of-dependent-packages If you suspect a file is part of a package you dont need, you can determine the package that installed it using host$ opkg search <file>

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 13

Linux Distributions

Linux Distributions Options for TI


Commercial

Community
TI SDK (PSP)

Custom
(Build it Yourself) Open Embedded (OE)

Timesys MontaVista Etc. Binary

ngstrm / Arago Binary Narcissus opkg

Custom from Sources

Binary

(Update patches)

Updated for each SDK release

(online tool)

Bit-Bake Recipies

GIT

from kernel.org, and others

Ease of Use

Easy Tested

Experienced User Latest

02 - 14

Introduction to Embedded Linux - Module 02: Linux Distributions

MMU and Dynamic Libraries

MMU and Dynamic Libraries

Fragmentation
Problem: Over time, the system heap that is used to manage dynamic memory becomes fragmented.
Free

malloc
Free Memory

Allocated Free Allocated Free Allocated Free

free malloc free

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

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 15

MMU and Dynamic Libraries

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

Introduction to Embedded Linux - Module 02: Linux Distributions

MMU and Dynamic Libraries

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

Static Linking and .a Libraries (Archives)


Physical Memory Application 1 MMU Application 2
Application 2 Memory Application 1 Memory Static

Libs

(unused)

Static Libs

(unused)

Common libraries are shared across applications and dynamically linked

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 17

MMU and Dynamic Libraries

Dynamic Linking and .so Libraries


Physical Memory Application 1 MMU
(unused) Application 1 Memory (unused) Shared Libraries

Application 2

Application 2 Memory (unused)

Common libraries are shared across applications and dynamically linked

Linking Linux Libraries


# gcc myfile.c lm -lpthread This links the dynamic libraries: libm.so shared math library libpthread.so shared POSIX thread library or the static libraries (archives) libm.a staic math library libpthread.a static POSIX thread library Depending on which library appears first in the library search path.

02 - 18

Introduction to Embedded Linux - Module 02: Linux Distributions

Lab 2: Terminal Manipulation

Lab 2: Terminal Manipulation

Lab 2 Beginner and Advanced Tracks


Beginner (beginner) Basic Terminal Manipulation (beginner) Basic File Manipulation Advanced (advanced) Linux Redirection (advanced) Linux Scripting You may not have time to complete both tracks, so choose wisely!

Should I take the Beginner Track?


Commands Covered: cat cd mv rm cp pwd ls mkdir rmdir touch

Concepts Covered: wildcard (*) autofill (<tab>) text editor (gedit) home directory (~) terminal history (arrow keys)

Introduction to Embedded Linux - Module 02: Linux Distributions

02 - 19

Lab 2: Terminal Manipulation

(Page intentionally left blank)

02 - 20

Introduction to Embedded Linux - Module 02: Linux Distributions

Module 03: The git Tool


Introduction
The git tool is an open-source software package used for managing different versions of software. git is used throughout the Linux community, and is the version management tool used by the developers of the Linux kernel itself. Furthermore, Arago, the free, open-source distribution that is tested and maintained by Texas Instruments, uses git as its versioning software. By learning the git tool, you will be able to apply updates and patches from the Arago distribution with far less effort than would be required to do the same task manually. Furthermore, git has a plugin to Code Composer studio that will be discussed in the next chapter. This plugin allows you to use git to seamlessly manage any CCS project.

Introduction to Embedded Linux - Module 03: The git Tool

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

Introduction to Embedded Linux - Module 03: The git Tool

git Overview

git Overview
git Branches

Creating a new git repository


You may create a new git repository
host$ mkdir ~/git/my_project host$ cd ~/git/myproject host$ git init host$ cp ~/project_files/* ~/myproject host$ git add * host$ git commit m initial_version

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

Introduction to Embedded Linux - Module 03: The git Tool

03 - 3

git Overview

Cloning an Existing git Repository


By cloning a public repository, you create a local copy that can be accessed without internet connectivity.
host$ mkdir ~/git host$ cd ~/git host$ git clone git://git.kernel.org/pub/scm/git/git.git

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

git Commit and Branches


master (branch 1)

branch 2 commit commit commit

commit commit commit commit branch 3 commit

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

Introduction to Embedded Linux - Module 03: The git Tool

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

Introduction to Embedded Linux - Module 03: The git Tool

03 - 5

Adding Commits

Making Commits
master (branch 1)

commit HEAD commit

(make changes to file1 and file2) host$ git add file1 host$ git commit host$ git add file2 host$ git commit

Commits and SHA1 sums


Each time a commit is made, an SHA1 hash operation is used to assign the commit a unique identifier.
host$ git log commit b87bd642de3c1d6a47cde7bfa9305a29606c7781 Author: user <user@workshop.net> Date: Wed Aug 1 11:49:53 2012 -0700 initial commit

A commit can be retrieved using the checkout command with its SHA1 sum
host$ git checkout b87bd642de3c1d6a47cde7bfa9305a29606c7781

03 - 6

Introduction to Embedded Linux - Module 03: The git Tool

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

This tag is now an alias for the commits SHA1 sum


host$ git checkout myTag

Tracked and Staged Files


file1 file2

git repository

Index

Staging Area

host$ touch file1 file2 host$

New files in a git repository are not tracked until added

Introduction to Embedded Linux - Module 03: The git Tool

03 - 7

Adding Commits

Tracked and Staged Files


file1 file2 file1 file2 file1 file2

git repository

Index

Staging Area

host$ touch file1 file2 host$ git add *

git add moves files to Staging Area and adds them to index

Tracked and Staged Files


file1 file2 file1 file2

git repository

Index

Staging Area

host$ touch file1 file2 host$ git add * host$ git commit

git commit clears the staging area

03 - 8

Introduction to Embedded Linux - Module 03: The git Tool

Adding Commits

Tracked and Staged Files


file1 file2 file1 file2 file2

git repository

Index

Staging Area

host$ touch file1 file2 host$ git add * host$ git commit host$ git add file2 host$ git commit

Only files in Staging Area are committed by git commit

Tracked and Staged Files


file1 file2 file3 file1 file2 (file1) (file2)

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

git commit -a commits all files in the index (not repository)

Introduction to Embedded Linux - Module 03: The git Tool

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:

git status reports status of index and staging area

03 - 10

Introduction to Embedded Linux - Module 03: The git Tool

Adding and Merging Branches

Adding and Merging Branches


Making a New Branch
master (branch 1)

commit HEAD commit branch 2


host$ git branch branch2

Creating a branch does not change your current position (i.e. currently checked-out commit)

Making a New Branch


master (branch 1)

commit commit HEAD commit branch 2

host$ git branch branch2 (change file1) host$ git commit -a

Introduction to Embedded Linux - Module 03: The git Tool

03 - 11

Adding and Merging Branches

Making a New Branch


master (branch 1)

commit commit commit


host$ git branch branch2 (change file1) host$ git commit -a host$ git checkout branch2

branch 2

HEAD

Use git checkout to move to new branch

Making a New Branch (Example 2)


master (branch 1)

commit commit commit


host$ git branch branch2 (change file1) host$ git commit -a host$ git checkout branch2 (create file2) host$ git add file2 host$ git commit -a

branch 2 commit HEAD

03 - 12

Introduction to Embedded Linux - Module 03: The git Tool

Adding and Merging Branches

Merging git Branches


master (branch 1)

commit commit commit branch 2 commit


host$ git checkout branch2 host$ git merge master host$ git commit -a

commit

HEAD

U-boot Practical Example


U-boot master

commit

1.

Ima Pro of Penguins, Inc. clones the Arago u-boot for AM335x EVM from arago-project.org

Introduction to Embedded Linux - Module 03: The git Tool

03 - 13

Adding and Merging Branches

U-boot Practical Example


U-boot master

commit penguin commit

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

U-boot Practical Example


U-boot master

commit commit penguin commit commit


1. 2. 3. 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 As U-boot is updated on Arago git, Ima merges patches

03 - 14

Introduction to Embedded Linux - Module 03: The git Tool

Adding and Merging Branches

U-boot Practical Example


U-boot master

commit commit commit commit


4. Ima gets promoted 5. Ima takes up golf 6. Ima retires in Tahiti

penguin commit commit commit commit penguin pro 2e commit commit

Introduction to Embedded Linux - Module 03: The git Tool

03 - 15

Lab 3: Using git

Lab 3: Using git


Lab 3: Exploring git
A. Exploring gits own git repository B. Create a new git repository

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

Introduction to Embedded Linux - Module 03: The git Tool

Module 04: Application Debug


Introduction
Code Composer Studio version 5 is the current iteration of Texas Instruments integrated development environment. This IDE can be used to program any of TIs processors from the lowcost, ultra-low-power MSP430 all the way up to the ultra-performance Arm Cortex-A8 devices such as the AM335x. CCSv5 is based on eclipse, an open-source IDE. This provides many advantages. Firstly, customers who are familiar with other eclipse-based IDEs will have less learning curve, and those who are not are likely to run into eclipse-based IDEs in the future. Secondly, there is a large community of eclipse plugins that can be used with CCSv5. Also, eclipse runs on both Windows and Linux host machines. This module will introduce the basic features of CCSv5 and provide details on setting up a debugging environment.

Introduction to Embedded Linux - Module 04: Application Debug

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

Introduction to Embedded Linux - Module 04: Application Debug

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

app.c app.cfg app.h D

Build Tool

CMD

Build Tool Goals: 1. Build executable (target) from input files (dependencies) using build instructions (commands)
2.

Build for multiple targets at once (e.g. ARM, X86, DSP)

Solution: command line (e.g. cl6x, gcc) or scripting tool (gMake, etc.)

Command Line (Examples 1-2)


Dependencies app.c app.o D

Commands Command Line CMD

Targets app.o app.x86U T

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

Might be more convenient to place commands in a script/batch filemakefile

Introduction to Embedded Linux - Module 04: Application Debug

04 - 3

Intro to Makefiles

Basic Makefile with Rules


Dependencies app.c app.o D

Makefile

Targets app.o app.x86U T

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.o gcc g app.o

app.x86U

RULE

Creating Your First Makefile


Dependencies app.c app.o D Makefile Targets app.o app.x86U T

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

Introduction to Embedded Linux - Module 04: Application Debug

Intro to Makefiles

User-Defined Variables & Include Files


D

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

app.x86U : app.o $(CC) $(CFLAGS) $^ $(LINK_FLAGS) $@

Using Built-in Variables


D

CMD

Simplify your makefile by using these built-in gMake variables:


$@ = Target $^ = All Dependencies $< = 1st Dependency Only

Scope of variables used is the current rule only. Example:


Original makefile app.x86U: app.o gcc g app.o o app.x86U Becomes app.x86U: app.o gcc g $^

$@

Introduction to Embedded Linux - Module 04: Application Debug

04 - 5

Intro to Makefiles

Templated Rules Using %

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

Introduction to Embedded Linux - Module 04: Application Debug

Code Composer Studio Overview

Code Composer Studio Overview


What is Code Composer Studio?

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.

Tabbed editor windows

Tab data displays together to save space

Fast view windows dont display Until you click on them

Introduction to Embedded Linux - Module 04: Application Debug

04 - 7

Code Composer Studio Overview

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

Project explorer lists functions

make file

Perspectives
Perspectives

a set of windows, views and menus that correspond to a specific set of tasks Debug C/C++

Two default perspectives are provided with CCSv5:


Debug Views Watch/Memory Graphs, etc. Code Devt Views Project Contents Editor

Users

can customize perspectives and save them:

04 - 8

Introduction to Embedded Linux - Module 04: Application Debug

Code Composer Studio Overview

Two Default Build Configurations

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

User can modify compiler/linker options via Build Options:

Many more details on compiler options in a later chapter

18

Debugging & Debuggers

User Mode Debugging


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.

Kernel Mode Debug


A debugger lets you


Pause a program Examine and change variables Step through code


Latest version of TIs graphical software debugger (i.e. IDE) IDE integrated development environment: which combines editing, building and debugging into a single tool Built on Eclipse platform; can install on top of standard Eclipse Allows debugging via GDB (Ethernet/serial) or JTAG (scan-based) Free license for GDB debugging

Code Composer Studio (CCSv5)


Introduction to Embedded Linux - Module 04: Application Debug

04 - 9

Code Composer Studio Overview

Linux application debug setup


Physically the connections of a typical linux application debug system are shown below.

Debug system (PC)


RS232 Putty, Teraterm, Hyperterminal, CCS Serial Terminal

Target system (Board)

LAN Gdb via Code Composer Studio

LAN Gdbserver on target

Linux kernel and driver debug setup


Physically the connections of a typical uboot, linux kernel or driver debug system are shown below.

Debug system (PC)

Target system (Board)

JTAG

04 - 10

Introduction to Embedded Linux - Module 04: Application Debug

Code Composer Studio Overview

GDB : GNU Debugger


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

(gdb) target remote 192.168.1.122:10000 (gdb) step (gdb) b 43 (gdb) run

Graphical Debug with GDB


Eclipse (CCSv5) and other IDEs can translate actions to GDB cmds

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

CCSv5 (Eclipse) CCSv5 (Eclipse)


GDB

RS-232

Controls Target

Target (EVM)
Embedded O/S (ie. Linux)

Ethernet

The target system runs:


Embedded OS Gdbserver that controls apps execution

GDB Server App

Introduction to Embedded Linux - Module 04: Application Debug

04 - 11

Code Composer Studio Overview

CCSv5 Licensing & Pricing

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

Introduction to Embedded Linux - Module 04: Application Debug

Setting up a CCS5 GDB Session

Setting up a CCS5 GDB Session


Remote Systems View (1)
Window Show View Other Remote Systems Remote Systems

Remote Systems View (2)


Files: tells CCS how to view remote files on and transfer files to remote system

Processes: tells CCS how to view and manipulate remote processes (applications)

Shells: tells CCS how to launch remote applications for debugging

Introduction to Embedded Linux - Module 04: Application Debug

04 - 13

Setting up a CCS5 GDB Session

Remote System View Files / Terminal

Setting Up CCSv5 Application Debug


Run Debug Configurations New Launch Configuration

Use remote system explorer to launch remote gdbserver

04 - 14

Introduction to Embedded Linux - Module 04: Application Debug

Setting up a CCS5 GDB Session

Setting Up CCSv5 Application Debug


Specify version of Gnu Debugger to use

CCSv5 Attached Remote Debugger

Introduction to Embedded Linux - Module 04: Application Debug

04 - 15

Setting up a CCS5 JTAG Session

Setting up a CCS5 JTAG Session


Creating a New Target Config File (.ccxml)

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

Specify GEL script here


More on GEL files...
16

What is a GEL File ?


GEL General Extension Language

(not much help, but there you go)

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

Introduction to Embedded Linux - Module 04: Application Debug

Lab 4: Application Build and Debug

Lab 4: Application Build and Debug


Lab 4: Application Build and Debug
A. Test Secure Shell (ssh) protocol B. Create Project C. Set up CCS Remote System Explorer Connection D. Set up CCS Debug Configuration

Introduction to Embedded Linux - Module 04: Application Debug

04 - 17

Lab 4: Application Build and Debug

(Page intentionally left blank)

04 - 18

Introduction to Embedded Linux - Module 04: Application Debug

Module 05: Linux Files


Introduction
The Linux operating system has a wide range of filesystem support for many different block storage devices. The ability to store and manipulate files on NAND and NOR flash, multimedia and secure digital cards, hard disk drives and other media is important for many systems. This section begins with an overview of Linux drivers that is applicable both to storage media drivers and device drivers. This module then continues to two case studys: the Arago NAND flash driver and GPIO driver. Though GPIO is a peripheral, the Arago GPIO driver is manipulated via virtual files and programming GPIO is therefore more akin to file manipulation than standard device driver manipulation. The next chapter will then focus on device drivers.

Introduction to Embedded Linux - Module 05: Linux Files

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

Introduction to Embedded Linux - Module 05: Linux Files

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

User Access to Kernel Space


User Space
process Memory main(){ func1(); func2();

/mypath/myfile
mounted to root file system

filesystem /dev/hda1 /dev/dsp /dev/video0

Kernel Space
ATA driver harddrive
Block random

audio driver buffer

video driver buffer

Character - sequential

Introduction to Embedded Linux - Module 05: Linux Files

05 - 3

Module Topics

Four Steps to Accessing Drivers


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

How to add modules to Linux Kernel: 1. Static (built-in)

Kernel Object Modules


Linux Kernel audio v4l2

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

Change static configuration using...

05 - 4

Introduction to Embedded Linux - Module 05: Linux Files

Module Topics

Static Linux Kernel Configuration

#> make ARCH=arm CROSS_COMPILE=arm_v5t_le- menuconfig

How to add modules to Linux Kernel: 1. Static (built-in) oss v4l2


Kernel Object Modules


Linux Kernel fbdev nfsd dsp httpd ext3
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 (modprobe)

# modprobe <mod_name>.ko [mod_properties]


.ko = kernel object

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

Introduction to Embedded Linux - Module 05: Linux Files

05 - 5

Module Topics

Examining The Steps in More Detail

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

Linux Driver Registration


# mknod <name> <type> <major> <minor> <name>: <type>: <major>: <minor>: Example: Useage:

Node name (i.e. virtual file name) b c block character

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

Introduction to Embedded Linux - Module 05: Linux Files

Module Topics

Linux Device Registration


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 #

0 brw-rw---0 crw-rw---0 crw------0 crw------0 crw-------

1 user root 14, 1 user root 29, 1 user root 29,

Permissions (user,group,all) block vs char

Minor number Major number

Name /dev directory

Examining The Steps in More Detail

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

Introduction to Embedded Linux - Module 05: Linux Files

05 - 7

Module Topics

Mounting Block Devices


user Shell Konsole

/ # / #

mkdir /media/part1 ls /media/part1

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

Mounting Block Devices


user Shell Konsole

$ $ $ $

mkdir /media/part1 ls /media/part1 mount t vfat /dev/mmcblk0p1 /media/part1 ls /media/part1 MLO u-boot.bin uImage

Initially empty Now populated

* Try ls l : adds linefeeds

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

Introduction to Embedded Linux - Module 05: Linux Files

Module Topics

Some Common Filesystem Types


Harddrive File systems:
ext2 ext3 vfat Common general-purpose filesystem Journaled filesystem Similar to ext2, but more robust against unexpected power-down Windows File Allocation Table filesystem

Memory File systems:


jffs2 yaffs ramfs cramfs Journaling flash filesystem (NOR flash) yet another flash filesystem (NAND flash) Filesystem for RAM Compressed RAM filesystem

Network File systems:


nfs smbfs Share a remote linux filesystem Share a remote Windows filesystem

Examining The Steps in More Detail

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

Introduction to Embedded Linux - Module 05: Linux Files

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

Introduction to Embedded Linux - Module 05: Linux Files

Module Topics

NAND Flash Driver


NAND Partitions
The Memory Technology Device (mtd) driver defines seven fixed partitions of NAND. Unlike most block devices, these partitions cannot be changed without modifying and rebuilding the driver source.

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

Examples of Using NAND


Erase NAND partition 4
# flash_eraseall /dev/mtd4

Write u-boot into NAND partition 4


# nandwrite p /dev/mtd4 u-boot.img

Write a UBI image into NAND partition 7


# ubiformat /dev/mtd7 f ubi.img s 512 O 2048 UBI images are created with mkfs.ubifs and ubinize commands. For more information: http://processors.wiki.ti.com/index.php/UBIFS_Support

Introduction to Embedded Linux - Module 05: Linux Files

05 - 11

Module Topics

Mounting a UBI Volume


# ubinfo # mtdinfo # mkdir /mnt/ubifs # ubiattach /dev/ubi_ctrl m 7 O 2048 # mount t ubifs ubi0:rootfs /mnt/ubifs

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

Introduction to Embedded Linux - Module 05: Linux Files

Module Topics

GPIO
GPIO Driver (Terminal)
1. Export GPIO pin for sysfs usage (Pin 30 in example)
# echo 30 > /sys/class/gpio/export

2. Change the GPIO pin direction to in/out


# echo "out" > /sys/class/gpio/gpio30/direction # echo "in" > /sys/class/gpio/gpio30/direction

3. Change the value (output) or read the value (input)


# echo 1 > /sys/class/gpio/gpio30/value # echo 0 > /sys/class/gpio/gpio30/value # cat /sys/class/gpio/gpio30/value

4. Unexport GPIO pin (when no longer needed)


# echo 30 > /sys/class/gpio/unexport

GPIO Driver (C code)


sysfs virtual files can be manipulated from C code in same manner as regular files
// echo "out" > /sys/class/gpio/gpio30/direction pFile = fopen(/sys/class/gpio/gpio30/direction, w); fwrite(out, 1, sizeof(out), pFile); fclose(pFile); // echo 1 > /sys/class/gpio/gpio30/value pFile = fopen(/sys/class/gpio/gpio30/value, w); fwrite(1, 1, 1, pFile); // cat /sys/class/gpio/gpio30/value fread(myArray, 1, 1, pFile); fclose(pFile);

Introduction to Embedded Linux - Module 05: Linux Files

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

1. Light the usr0 LED


# echo 1 > /sys/devices/platform/leds-gpio/leds/am335x\:EVM_SK\:usr0/brightness
Note that \: is used to designate : in the Linux terminal because : is a special character. \ is called the escape character because it can be prepended to special characters to designate they are simple text.

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.

To disable the heartbeat led


# echo none > /sys/devices/platform/leds-gpio/leds/am335x\:EVM_SK\:heartbeat/trigger

05 - 14

Introduction to Embedded Linux - Module 05: Linux Files

Lab 5: GPIO via Virtual Files

Lab 5: GPIO via Virtual Files


Lab 5: GPIO via Virtual Files
Boot board and test GPIO (terminal) A. Light LED from C application B. Blink LED from C application

lab05_git master solutions

HEAD

start

solution_A solution_B

Introduction to Embedded Linux - Module 05: Linux Files

05 - 15

Lab 5: GPIO via Virtual Files

(Page intentionally left blank)

05 - 16

Introduction to Embedded Linux - Module 05: Linux Files

Module 06: Linux Drivers


Introduction
A basic feature of nearly any modern operating system is the abstraction of peripherals via device drivers. Linux provides a basic open-read-write-close interface to peripheral drivers that is a close parallel to the file manipulation interface described in the previous module. This module provides a brief discussion on the differences between the basic driver model and the file I/O model then delves into two case studies: the UART driver and the audio driver (ALSA). The module wraps up with a related side topic: Linux signal handling.

Introduction to Embedded Linux - Module 06: Linux Drivers

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

Introduction to Embedded Linux - Module 06: Linux Drivers

Driver Basics

Driver Basics
Files and Virtual Files (Review)
User Space
process Memory main(){ func1(); func2();

/mypath/myfile
mounted to root file system

filesystem /dev/hda1 /dev/dsp /dev/video0

Kernel Space
ATA driver harddrive
Block random

audio driver buffer

video driver buffer

Character - sequential

Accessing Files (Review)


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

Introduction to Embedded Linux - Module 06: Linux Drivers

06 - 3

Driver Basics

Using Character Device Drivers


Simple drivers use the same format as files:
soundFd = open(/dev/dsp, O_RDWR); read ( soundFd, aMyBuf, len ); write( soundFd, aMyBuf, len ); close( soundFd );

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

Dynamic Driver Example USB


beaglebone$ lsmod g_mass_storage beaglebone$ rmmod g_mass_storage beaglebone$ modprobe g_ether

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

Introduction to Embedded Linux - Module 06: Linux Drivers

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.

Serial Port Configuration (Part 1)


#include #include #include #include #include #include <stdio.h> <stdlib.h> <unistd.h> <string.h> <fcntl.h> <termios.h>

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

Introduction to Embedded Linux - Module 06: Linux Drivers

06 - 5

UART Driver

Serial Port Configuration (Part 2)


// clear number of bits field terminal_setting.c_cflag &= ~CSIZE; // set 8 bits terminal_setting.c_cflag |= CS8; // clear parity bit in flag (no parity) terminal_setting.c_cflag &= ~PARENB; // clear the CSTOPB flag in the mask // CSTOPB = 1 : 2 stop bits // CSTOPB = 0 : 1 stop bit terminal_setting.c_cflag &= ~CSTOPB; // send changes to terminal settings structure to kernel // TCSANOW flag forces immediate change tcsetattr(fd, TCSANOW, &terminal_setting); }

Serial Driver Hello World


int main( void ) { char hello[40]="hello world\n"; int fd; // Open serial device fd = open("/dev/ttyO0", O_RDWR); configure_serial(fd); // Write a string (char array) to device write( fd, hello, sizeof(hello)); // Close fd to allow other programs access close(fd); return 0; }

06 - 6

Introduction to Embedded Linux - Module 06: Linux Drivers

Advanced Linux Sound Architecture (ALSA)

Advanced Linux Sound Architecture (ALSA)


ALSA Applications

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

ALSA Library API


Information Interface Control Interface Mixer Interface PCM Interface
Status and settings for ALSA driver. Control hardware of system (e.g. adc, dac).

/proc/asound /dev/snd/controlCX /dev/snd/mixer

Controls volume and routing of on systems with multiple lines.

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

Raw MIDI Interface*

Sequencer Interface* Timer Interface

/dev/snd/seq /dev/snd/timer

* Not implemented in current TI provided driver.

Introduction to Embedded Linux - Module 06: Linux Drivers

06 - 7

Advanced Linux Sound Architecture (ALSA)

ALSA Driver Structure


snd_pcm_open() snd_pcm_hw_params() Snd_pcm_close() snd_pcm_read() snd_pcm_writei()

ALSA Library
PCM Control

ALSA Kernel API

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


Application ALSA apps
arecord aplay amixer

ALSA Library
PCM Control

User Space Kernel Space

ALSA Kernel API

ALSA Driver Core


H/W Codec Driver Machine Driver Platform Driver McBSP Driver

Hardware

AM335x

Control I/F (I2C)

System DMA

McBSP Audio Codec (TWL4030/AIC23)

06 - 8

Introduction to Embedded Linux - Module 06: Linux Drivers

Advanced Linux Sound Architecture (ALSA)

Opening and Closing Devices


Devices: hw:i,j default i = card number, j = device number alias for hw:0,0

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

ALSA Configuration Example


/* Allocate a hardware parameters object. */ snd_pcm_hw_params_allocate(&params); /* Fill it in with default values. */ snd_pcm_hw_params_any(handle, params); /* Set the desired hardware parameters. */ /* Interleaved mode */ snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED); /* Signed 16-bit little-endian format */ snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE); /* Two channels (stereo) */ snd_pcm_hw_params_set_channels(handle, params, 2); /* 44100 bits/second sampling rate (CD quality) */ val = 44100; snd_pcm_hw_params_set_rate_near(handle, params, &val, &dir); /* Write the parameters to the driver */ rc = snd_pcm_hw_params(handle, params);

Introduction to Embedded Linux - Module 06: Linux Drivers

06 - 9

Advanced Linux Sound Architecture (ALSA)

ALSA Read/Write Example


/* Use a buffer large enough to hold one period */ snd_pcm_hw_params_get_period_size(params, &frames, &dir); size = frames * 4; while (loops-- > 0) { rc = read(0, buffer, size); if (rc < size) { fprintf(stderr, "end of file on input\n"); break; } rc = snd_pcm_writei(handle, buffer, frames); if (rc < 0) fprintf(stderr, "error from writei: %s\n", snd_strerror(rc)); } /* 2 bytes/sample, 2 channels */ buffer = (char *) malloc(size);

06 - 10

Introduction to Embedded Linux - Module 06: Linux Drivers

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

Signals defined in signal.h

* Note, this is not a complete list

Introduction to Embedded Linux - Module 06: Linux Drivers

06 - 11

Signal Handling

Signal Registration Example


int main(int argc, char *argv[ ]) { int status = EXIT_SUCCESS; void *audioThreadReturn; /* Set the signal callback for Ctrl-C */ signal(SIGINT, signal_handler); /* Call audio thread function */ audioThreadReturn = audio_thread_fxn((void *) &audio_env); if( audioThreadReturn == AUDIO_THREAD_FAILURE ){ printf("audio thread exited with FAILURE status\n"); status = EXIT_FAILURE; } else printf("audio thread exited with SUCCESS status\n"); } exit(status);

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

Introduction to Embedded Linux - Module 06: Linux Drivers

Lab 6: UART Driver

Lab 6: UART Driver


Lab 6: UART Driver
Boot board and test ssh Remove serial console A. Simple UART Driver B. Variables over UART C. UART Configuration (Examination) Restore serial console

lab06_git master solutions

HEAD

start

solution_A solution_B solution_C

Introduction to Embedded Linux - Module 06: Linux Drivers

06 - 13

Lab 6: UART Driver

(Page intentionally left blank)

06 - 14

Introduction to Embedded Linux - Module 06: Linux Drivers

Module 07: Linux Scheduler


Introduction
Another common feature of nearly any operating system is the ability to run multiple tasks concurrently, often referred to as multi-threading. The Linux operating system has two primary features used for concurrent tasks. The first is a memory management feature via the Memory Management Unit (MMU) in which separate memory spaces are created for each process, i.e. application. The second feature is the sharing of CPU cycles across different applications via separation into POSIX threads. The Linux scheduler also manages the context switching between different threads of execution, including saving and restoring the system stack, saving and restoring CPU registers and reprogramming of the memory management unit if necessary. This module begins with an overview of processes and threads, then discusses thread synchronization using semaphore objects. The module wraps up with a discussion of the usage of the two primary scheduling methodologies for threads: realtime and timeslicing.

Introduction to Embedded Linux - Module 07: Linux Scheduler

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

Introduction to Embedded Linux - Module 07: Linux Scheduler

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

Introduction to Embedded Linux - Module 07: Linux Scheduler

07 - 3

Linux Processes

The Usefulness of Processes


Option 1: Audio and Video in a single Process // audio_video.c // handles audio and video in // a single application int main(int argc, char *argv[]) { while(condition == TRUE){ callAudioFxn(); callVideoFxn(); } }
1. 2. 3. 4.

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

Splitting into two processes is helpful if:

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

Terminal Commands for Processes


# ps # ps -e # top # kill <pid> # renice +5 p <pid> Lists currently running user processes Lists all processes Ranks processes in order of CPU usage Ends a running process Changes time-slice ranking of a process
(range +/- 20)

07 - 4

Introduction to Embedded Linux - Module 07: Linux Scheduler

Linux Processes

Launching a Process Terminal

Side Topic Creating New Processes in C


fork exec fork + exec

Splits one executing process into two with same environment


New process replaces old but maintains previous environment

Launch new process and keep previous process

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

Introduction to Embedded Linux - Module 07: Linux Scheduler

07 - 5

Linux Threads

Linux Threads
Processes and Threads
Process A Process A global vars
A2 pThread w/ local vars

Process B Process B global vars


B1 Main w/ local vars

By default, each process contains one main thread of execution


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.

A1 Main w/ local vars

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

A3 pThread w/ local vars

Process Pipes

Introduction to Embedded Linux - Module 07: Linux Scheduler

Linux Threads

pThread Functions Create & Exit


video_thread main pthread_create(&video_thread, null, video_thread_fxn, ) pthread_exit (NULL)

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

What if there's nothing for main() to do?

Re-Joining Main
video_thread main pthread_create(&video_thread, null, video_thread_fxn, ) pthread_exit (retval)

new main blocked

pthread_exit (retval)

pthread_create (&new,) pthread_join (new)

Introduction to Embedded Linux - Module 07: Linux Scheduler

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.

Thread Synchronization (Polling)


devComplete = TRUE driver thread A
(higher priority)

devComplete = TRUE

Process data

Start polling for devComplete

Process data

thread B

Wasted cycles while thread A does nothing! (and thread B starves)

07 - 8

Introduction to Embedded Linux - Module 07: Linux Scheduler

Linux Threads

Thread Synchronization (Blocking)


void *threadA(void *env){ while(1){ read(env->audioFd, env->bufferPtr, env->bufsize); doSomethingNext(env->bufferPtr); } Blocking
(waits till complete)

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

Thread Synchronization (Blocking)


devComplete = TRUE driver thread A
(higher priority) (blocked)

devComplete = TRUE

Process data

Driver read call

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

Introduction to Embedded Linux - Module 07: Linux Scheduler

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

Thread Synchronization (Semaphore)


sem_post() driver thread A
(higher priority) (blocked)

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

Introduction to Embedded Linux - Module 07: Linux Scheduler

Linux Threads

Using Real-Time Threads


Time-Sliced A/V Application, >100% load
Audio Thread Video Thread Control Thread

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?

Time-Sliced A/V Application Analysis


Audio Thread Video Thread Control Thread Audio thread completes 80% of samples Video thread drops 6 of 30 frames User response delayed 1mS

All threads suffer, but not equally:


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

Introduction to Embedded Linux - Module 07: Linux Scheduler

07 - 11

Linux Threads

Real-time A/V Application, >100% load


Audio Thread (priority 99) Video Thread (priority 98) Control Thread (priority 70)

Audio thread is guaranteed the bandwidth it needs Video thread takes the rest Control thread never runs!

Time-Sliced A/V Application Analysis


Audio Thread Video Thread Control Thread Audio thread completes, no distortion Video thread drops 1 of 30 frames No user response

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

Introduction to Embedded Linux - Module 07: Linux Scheduler

Linux Threads

Hybrid A/V Application, >100% load


Audio Thread (priority 99) Video Thread (pri 0, nice -5) Control Thread (pri 0, nice +5)

Audio thread is guaranteed the bandwidth it needs Video thread takes most of remaining bandwidth Control thread gets a small portion of remaining bandwidth

Hybrid A/V Application Analysis


Audio Thread Video Thread Control Thread Audio thread completes, no distortion Video thread drops 2 of 30 frames User response delayed 100ms

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

Introduction to Embedded Linux - Module 07: Linux Scheduler

07 - 13

Linux Threads

Default Thread Scheduling


#include <pthread.h> pthread_create(&myThread, NULL, my_fxn, (void *) &audio_env);

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

Introduction to Embedded Linux - Module 07: Linux Scheduler

Linux Threads

Scheduling Policy Options


SCHED_OTHER Sched Method RT priority Min niceness Max niceness Scope

SCHED_RR

SCHED_FIFO

Time Slicing 0 +20 -20 root or user

Real-Time (RT) 1 to 99 1 to 99 n/a n/a root n/a n/a root

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

Real-time Thread Creation Procedure


Create attribute structure // Initialize the pthread_attr_t structure audioThreadAttrs pthread_attr_init(&audioThreadAttrs); // Set the inheritance value in audioThreadAttrs structure pthread_attr_setinheritsched(&audioThreadAttrs, PTHREAD_EXPLICIT_SCHED); Set attribute to real-time priority 99 // Set the scheduling policy for audioThreadAttrs structure pthread_attr_setschedpolicy(&audioThreadAttrs, SCHED_RR); // Set the scheduler priority via audioThreadParams struct audioThreadParams.sched_priority = 99; pthread_attr_setschedparam(&audioThreadAttrs, &audioThreadParams); // Create the new thread using thread attributes pthread_create(&audioThread, &audioThreadAttrs, audio_thread_fxn, (void *) &audio_env);

Create thread with given attributes

Introduction to Embedded Linux - Module 07: Linux Scheduler

07 - 15

Linux Threads

Linking the pthread Library


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

Introduction to Embedded Linux - Module 07: Linux Scheduler

Lab 7: Linux Scheduler

Lab 7: Linux Scheduler


Lab 7: Linux Scheduler
A. Creating a POSIX thread B. Using Realtime threads C. Using Semaphores

lab07_git master solutions

HEAD

start

solution_A solution_B solution_C

Lab 7A: Timeslice Thread


A. Creating a POSIX thread B. Using Realtime threads C. Using Semaphores

Linux scheduler shares CPU between timesliced threads, so each thread gets a turn to run.

Introduction to Embedded Linux - Module 07: Linux Scheduler

07 - 17

Lab 7: Linux Scheduler

Lab 7B: Realtime Thread


A. Creating a POSIX thread B. Using Realtime threads C. Using Semaphores

The first realtime thread to run will lock out the second thread. Because delay function uses a for loop instead of sleep (blocking)

Lab 7C: Realtime + Semaphore


A. Creating a POSIX thread B. Using Realtime threads C. Using Semaphores

while(1){ sem_wait(); sem_post(); }

while(1){ sem_wait(); sem_post(); }

thread1

thread2

07 - 18

Introduction to Embedded Linux - Module 07: Linux Scheduler

Module 08: Networking


Introduction
Networking connectivity is a common requirement for many applications. Linux on the AM335x provides strong support for both wired and wireless IP communication. This module begins with a short review of basic networking concepts and then proceeds into in a discussion of various commonly used server/client protocols such as secure shell (ssh), telnet, file transfer protocol (ftp), dynamic host configuration protocol (dhcp) and dynamic domain name servers (ddns.) The module ends with an-indepth study of the underlying protocol common to all of these server/client systems in a Linux environment: Berkeley sockets. Programming examples are shown for opening and closing Berkeley sockets on both the server and client.

Introduction to Embedded Linux - Module 08: Networking

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

Introduction to Embedded Linux - Module 08: Networking

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)

LAN = Local Area Network (subnet.)


IP addresses are not unique

Introduction to Embedded Linux - Module 08: Networking

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

Introduction to Embedded Linux - Module 08: Networking

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.

Introduction to Embedded Linux - Module 08: Networking

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.

Network Address Translation


WAN
203.114.28.8

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

Introduction to Embedded Linux - Module 08: Networking

Server/Client Protocols

Dynamic Host Configuration Protocol (DHCP)


DHCP server issues IP address, netmask, gateway, dns to DHCP clients.
Server installation (Ubuntu) # apt-get install dhcp3-server Server configuration file /etc/dhcp3/dhcpd.conf

Domain Name Service


Domains and subdomains are not required to correlate to subnetwork boundaries (although they often do.)
Server installation (Ubuntu) # apt-get install bind9 Configuration files /etc/named.conf /var/bind/*.zone

Introduction to Embedded Linux - Module 08: Networking

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

Introduction to Embedded Linux - Module 08: Networking

Berkeley Sockets

Berkeley Sockets
Berkeley Sockets Basic Procedure
sFD = socket(); sFD = socket();

bind(sFD, addr, ); listen(sFD, );


while(1){

connect(sFD, addr, );
// do reads and writes

cFD = accept(sFD,); // do reads and writes

shutdown(sFD,); close(sFD);
}

shutdown(cFD,); close(cFD); Client Server

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.

Introduction to Embedded Linux - Module 08: Networking

08 - 9

Berkeley Sockets

Specifying Address and Port


struct sockaddr_in stSockAddr; memset(&stSockAddr, 0, sizeof(stSockAddr)); stSockAddr.sin_family = AF_INET; stSockAddr.sin_addr.s_addr = inet_addr("192.168.1.1"); stSockAddr.sin_port = htons(1100);

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

Introduction to Embedded Linux - Module 08: Networking

Lab 8: Berkeley Sockets

Lab 8: Berkeley Sockets


Lab 8: Berkeley Sockets
A. Network Configuration Files B. Berkeley Socket Client C. Build and Launch Host Server D. Server Application

lab08_git master solutions

start

solution_A
lab08_x86_server

master

solutions

start

solution_A

Introduction to Embedded Linux - Module 08: Networking

08 - 11

Lab 8: Berkeley Sockets

(Page intentionally left blank)

08 - 12

Introduction to Embedded Linux - Module 08: Networking

Module 09: Video and Graphics Drivers


Introduction
Linux developers commonly use two drivers for handling video and graphics. The first of these drivers is named Video For Linux, 2 (V4L2) and is commonly used to capture or display moving video. The second is called the Framebuffer Device driver (FBDEV) and is commonly used to display graphics such as a graphical user interface or desktop environment, although it is possible to use FBDEV to display moving video as well. This module will cover functionality overviews as well as application programming details of using the V4L2 and FBDEV drivers.

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

Module Topics

Linux v4L2 Video Driver


v4l2 Driver Overview

v4l2 is a standard Linux video driver used in many linux systems Supports video input and output

In this workshop we use it for video input only

Device node

Node name: /dev/video0 Uses major number 81


http://bytesex.org/v4l

v4l2 spec:

Driver source location:


/lsp/ti-davinci/drivers/media/davinci_vpfe.c

v4l2 Driver Queue Structure


incoming (empty) queue

owns buffer

outgoing (full) queue

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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

owns buffer

v4l2 driver

application

09 - 3

Module Topics

v4l2 Enqueue and Dequeue


v4l2 driver IQ OQ DQ

App

Buffers typically exist in drivers memory space The dequeue call makes the data available to the app

v4l2 Enqueue and Dequeue


v4l2 driver IQ OQ (empty) DQ

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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

Module Topics

v4l2 Enqueue and Dequeue


v4l2 driver IQ OQ (empty) 1 read 2 3 4 App 1 2 3 4

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

v4l2 Enqueue and Dequeue


EQ v4l2 driver IQ OQ (empty) 1 2 3 4 App 1 2 3 4

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

Is there a better method than "read"?

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

09 - 5

Module Topics

Using mmap

mmap A Better Way


EQ

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

v4l2 Queue Synchronization


v4l2 driver Driver fills IQ buf and places on OQ IQ OQ (empty) 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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

Module Topics

v4l2 Queue Synchronization


v4l2 driver Driver fills IQ buf and places on OQ 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

v4l2 Queue Synchronization


v4l2 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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

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

(Optional) v4L2 Coding

Commonly Used v4l2 ioctls


Data Structures struct v4l2_requestbuffers req; req.count; // how many buffers to request req.type; // capture, output, overlay req.memory; // mmap, userptr, overlay
struct v4l2_buffer buf; buf.index; // which driver buffer buf.type; // matches req.type buf.memory; // matches req.memory buf.m.offset; // location of buffer in driver mem

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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

Module Topics

v4l2 Buffer Passing Procedure


while(cond){ ioctl(v4l2_input_fd, VIDIOC_DQBUF, &buf); bufPtr = mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, v4l2_input_fd, buf.m.offset); doSomething(bufPtr, buf.length, ...); munmap(bufPtr, buf.length); ioctl(v4l2_input_fd, VIDIOC_QBUF, &buf); }

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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

09 - 9

Module Topics

Linux FBdev Display Driver


FBdev Driver Overview

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

Multiple Video/OSD Windows

Source: DirectFBOverview.pdf

09 - 10

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

Module Topics

32-bit Color Format

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

For Each /dev/fb/x Video Plane


yoffset

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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

09 - 11

Module Topics

Ping-pong Buffers with FBdev


offset = (0,0)
buffer0 (ping)

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

Ping-pong Buffers with FBdev


offset = (0,0)
buffer0 (ping)

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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

Module Topics

buffer 0 (ping) buffer 1 (pong) xres

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

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

09 - 13

Module Topics

Commonly Used FBdev ioctl


Data Structures
struct fb_fix_screeninfo myFixScreenInfo; myFixScreenInfo.smem_len; // length of framebuffer struct fb_var_screeninfo myVarScreenInfo; myVarScreenInfo.xres; // visible pic resolution myVarScreenInfo.xres_virtual; // virtual pic resolution myVarScreenInfo.xoffset; // from virtual to vis

Get or put variable screen information Get fixed screen information

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

We use Pan to switch output buffers

After writing buffer and pan_display, wait for current to finish


// arg 3 is not used

09 - 14

Introduction to Embedded Linux - Module 09: Video and Graphics Drivers

Module 10: Qtopia GUI Development


Introduction
The previous module introduced FBDEV, the Linux device driver that is commonly used for the display of graphics. This driver, however, is very low level, with the display being specified in the form of a bitmap. Typically a developer would prefer to have additional tools such as fonts for displaying text and an abstraction of various common GUI components such as text and input boxes. There are many packages in Linux that may be used for the development of a graphical user interface. One of these packages that is commonly used in the embedded space is called Qtopia (or qt for short.) Qtopia provides abstractions for many commonly used GUI components (termed widgets) as well as providing font support and human interface device (HID) support to integrate mouse and keyboard inputs as well as touch-screen inputs. Furthermore, Qtopia has a feature-rich and easy to use development environment called QT creator. .

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

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

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

Graphics Software Layers

Graphics Software Layers

Terminal vs. Desktop

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

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

10 - 3

Graphics Software Layers

x11 Without Desktop

Session Manager Display Manager Window Manager Display Server Driver

XSM (x11 session manager) XDM (x11 Display Manager) x11 window manager X server Linux FBDEV framebuffer driver

Device

AM335x

Gnome Desktop Environment


Desktop Environment Session Manager Display Manager Window Manager Display Server Driver

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

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

Graphics Software Layers

Gnome Desktop Environment


Desktop Environment Presents a desktop environment. Session Manager Manages a login session to a Window Manager. Allows a user to maintain the settings and state of a windowing environment. Display Manager Manages one or more local and/or remote Display servers (usually via window managers) for a login session. Window Manager Exposes independent, resizable virtual displays (windows) to applications. Display Server Network-transparent interface to display driver. Driver Exposes a bitmap-type interface (framebuffer) to the display hardware.

Looking at Gnome graphically ...

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

Linux FBDEV Framebuffer Driver

AM335x

AM335x

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

10 - 5

Qtopia

Qtopia
QT Framework

Qt is cross-platform application and UI 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

3D Graphics with OpenGL and OpenGL ES


Easily incorporate 3D Graphics in your applications Get maximum graphics performance

Qt Linguist I18N Tools

qmake Cross-Platform Build Tool

Cross-platform support
Windows Linux/X11 Embedded Linux Windows CE

Multithreading support Network connectivity

Advanced GUI development


9

Example Qtopia Apps and UIs

10 - 6

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

Qtopia

Sitara Linux Stack


Matrix Application Launcher ARM Benchmarks 3D Graphics USB Profiler Power Manager Web Browser System Information WLAN GUI

Qt Embedded QGLWidget QWidget Gstreamer/FFMPEG Wifi MPEG4, H.264, MPEG2, AAC, BlueZ

OpenGL ES

FBDEV DSS2

V4L2

ALSA I2C

VISA USB

McSPI McBSP

Touch screen MMC

Ethernet

UART

Sitara ARM Processor Target Board

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

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

10 - 7

Qtopia

Running Hello World!


Run qmake inside the helloworld directory to create a project file qmake project

Run qmake again to create a Makefile from helloworld.pro qmake

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.

QT Creator Development tools


Downloading and setting up: http://processors.wiki.ti.com/index.php/Qt_Creator_Embedded_Debugging_Setup

10 - 8

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

Qtopia

QT Creator Drag and Drop Widgets (Forms)

QT Creator Forms Stored via XML

The UI created on the previous slide is stored as .xml QT Creator then generates the UI from this .xml file

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

10 - 9

Qtopia

QT Creator C++ Objects

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

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

Qtopia

Widgets
QWTPlotCurve QHBoxLayout QComboBox QDoubleSpinBox

Q S l i d e r

QMainWindow

QMessageBox

QPushButton

Qlabel

Signals & Slots

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

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

10 - 11

Qtopia

Simple Signal/Slot Example

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.

Simple Signal/Slot Example

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

Introduction to Embedded Linux - Module 10: Qtopia GUI Development

Customizing Linux Kernel for Fast Boot


Introduction
A common concern with developers using the Linux operating system is the boot time that is required to start the system from reset. The boot time for the system we have used in the class so far is about 40 seconds; however, this is an unoptimized system that has a large number of components and features enabled, many of which may not be needed. There are a couple of techniques for reducing boot time. Two of the most important are removing features and components that will never be required and deferring the loading of those components that are not required for booting. This module will show you how to create a custom kernel configuration, which is useful both for configuring a fast boot and for board porting. Techniques for improving boot time will then be shown, and finally, an overview of the Linux kernel source code is presented from the standpoint of Kernel porting, though this final topic is a high-level overview and much further knowledge is required to complete this extensive task.

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

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

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

Acquiring Timing Information

Acquiring Timing Information

Method 1: Timestamp printk


Pros: Cons: Timestamped at message generation Potentially requires kernel rebuild (but default for TI SDK) Only timestamps kernel messages Requires printk, which adds to boot time! $ make ARCH=arm menuconfig Kernel hacking Show timing information on printks

Timestamped printk Example


SPL/U-boot not profiled U-Boot SPL 2011.09 (Jul 26 2012 - 17:18:20) Texas Instruments Revision detection unimplemented No daughter card present OMAP SD/MMC: 0 reading u-boot.img Starting kernel ... Uncompressing Linux... done, booting the kernel. [ 0.000000] Linux version 3.2.0 (jenkins@sdit-build01) ... [ 5.432098] kjournald starting. Commit interval 5 seconds [ 6.153228] EXT3-fs (mmcblk0p2): using internal journal [ 6.158721] EXT3-fs (mmcblk0p2): recovery complete [ 6.167755] EXT3-fs (mmcblk0p2): mounted filesystem [ 6.174987] VFS: Mounted root (ext3 filesystem) on device 179:2. [ 6.181640] Freeing init memory: 248K ... ALSA: Restoring mixer settings... Configuring network interfaces... [ 12.417053] net eth0: CPSW phy found : id is : 0x4dd074 udhcpc (v1.13.2) started Sending discover...

Timer starts when kernel begins booting Significant portion of kernel boot instrumented

init (rcX.d) scripts not instrumented

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

11 - 3

Acquiring Timing Information

Method 2: Timestamp Serial Messages


Pros: Cons: Allows profiling of SBL/U-boot Allows benchmarking without printk overhead Timestamps suffer serial buffering jitter

Profiling the Linux Kernel - Cont


Instrument kernel initialization. This will help you find which static drivers in the kernel are taking the most time to initialize
Add initcall_debug to the bootargs in u-boot. With recent u-boots this can usually be done using: setenv optargs initcall_debug saveenv When the Linux system is booted you can view these initcall lines using dmesg | grep initcall [ xxxxx] initcall <init function> [<module>] returned 0 after <time> usecs These lines can be sorted using the commands below to help find the modules with the largest init times
If CONFIG_PRINTK_TIME is enabled dmesg | grep initcall | sort -k8 -n If CONFIG_PRINTK_TIME is not enabled dmesg | grep initcall | sort -k6 -n

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

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

Kernel Boot Time Improvements

Kernel Boot Time Improvements

Step 1: Remove Unneeded Init Scripts


The initialization process is launched by the Linux Kernel after the root filesystem is mounted By default it is located at /sbin/init, but it can be specified as a kernel boot argument /sbin/init /etc/inittab /etc/init.d
bootmisc.sh mountnfs.sh networking syslog telnetd thttpd

/etc/rcX.d

S05networking S20syslog S10telnetd S20syslog S20thttpd S60mountnfs

Step 2: Remove Unneeded Kernel Modules


1. Static (built-in) oss v4l2

Linux Kernel fbdev nfsd dsp httpd ext3

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)

# insmod <mod_name>.ko [mod_properties]


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

.ko = kernel object

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

11 - 5

Kernel Boot Time Improvements

Kernel Build
n
RBL
ROM

(x-loader) Internal RAM

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

* For available ARCH: ** For available configs:

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

omap2plus_defconfig orion5x_defconfig palmz72_defconfig pcm027_defconfig pcontrol_g20_defconfig pleb_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

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

Kernel Boot Time Improvements

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.

make menuconfig options

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

11 - 7

Kernel Boot Time Improvements

Other Boot Optimizations


Change

Kernel Compile Flags Reduce filesystem size Use faster media to store kernel and filesystem
MMC/SD

NAND Flash

Defer
It

module init calls

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

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

Kernel Board Port

Kernel Board Port


The Target Port Starts with a Board File
Defines the Machine Name Declares Initialization Data for Peripherals being used Declare Pin Mux initialization Data Defines Initialization functions Provides required Machine Initialization functions Calls Common Initialization functions Summary is that this file defines several required elements required to boot a Linux kernel, one of several bricks in the wall so to speak.

16

Machine and Platform Files


arch/arm/Makefile: machine-$(CONFIG_ARCH_OMAP3) := omap2 plat-$(CONFIG_ARCH_OMAP) := omap machdirs := $(patsubst %,arch/arm/mach-%/,$(machine-y)) platdirs := $(patsubst %,arch/arm/plat-%/,$(plat-y)) arch/arm/mach-omap2/Makefile: obj-$(CONFIG_MACH_AM335XEVM) arch/arm/plat-omap/Makefile: obj-$(CONFIG_ARCH_OMAP3) += omap_device.o += board-am335xevm.o

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

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

11 - 9

Kernel Board Port

Machine and Platform Definition


Ubuntu$ more arch/arm/configs/am335x_evm_defconfig CONFIG_ARCH_OMAP=y Platform CONFIG_ARCH_OMAP2PLUS=y CONFIG_MACH_OMAP_GENERIC=y CONFIG_ARCH_OMAP2PLUS_TYPICAL=y CONFIG_ARCH_OMAP3=y Machine, CONFIG_SOC_OMAPTI81XX=y Device CONFIG_SOC_OMAPAM33XX=y CONFIG_MACH_OMAP3_BEAGLE=y CONFIG_MACH_TI8168EVM=y CONFIG_MACH_TI8148EVM=y CONFIG_MACH_AM335XEVM=y Board CONFIG_MACH_AM335XIAEVM=y

How the Board File fits in the stack


Board Developer will spend most of their time in the Board file. The Board file makes use of the machine shared common code The underlying port to the ARM Architecture Shared common code is already done and does not need to be looked at Finally everything rests on the Linux Kernel Shared Common Code. The lower in the stack you go the less direct interaction the board developer will or need to have.

19

11 - 10

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

Kernel Board Port

OMAP2+ Machine Shared Common Code


There are several board files in the mach-omap2 directory. These board files typical use the support functions defined within this directory. Below is a sampling of some of the supporting common code, not all are mentioned here.

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

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

11 - 11

Kernel Board Port

Platform-Specific Driver Switches


For instance, searching on CONFIG_ARCH_OMAP locates (partial list:) ubuntu$ grep -R CONFIG_ARCH_OMAP . ./sound/soc/omap/omap-mcbsp.h ./include/linux/usb/musb.h ./include/linux/omapfb.h ./drivers/tty/serial/8250.c ./drivers/usb/musb/musb_core.c ./drivers/usb/host/ohci-hcd.c ./drivers/usb/host/ohci-omap.c ./drivers/usb/host/ohci-omap.c ./drivers/input/keyboard/omap-keypad.c ./drivers/mfd/twl-core.c ./drivers/mfd/twl-core.c ./drivers/video/omap/omapfb.h ./drivers/video/omap/omapfb_main.c ./drivers/gpio/gpio-omap.c ./drivers/mtd/onenand/omap2.c ./drivers/net/ethernet/smsc/smc911x.h ./drivers/i2c/busses/i2c-omap.c

Sometimes there is a TIspecific driver file. Sometimes there is simply a #define switch in a generic driver file.

11 - 12

Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot

Optimizing and Customizing U-boot


Introduction
By modifying the Linux kernel and filesystem you can make significant reductions in boot time. In order to reach the optimal boot time, however, you will also need to modify U-boot and the boot arguments (bootargs) U-boot provides to the kernel. This module will begin with a few simple bootargs changes that can shave a second or two off of boot time, then progresses to the concept of the initial RAM disk, which in some cases (such as booting from MMC/SD card) can remove three or four seconds from your boot time, and finally shows how to rebuild U-boot itself with configuration options that will reduce the size of U-boot and the MLO as well as reducing boot time.

Introduction to Embedded Linux - Optimizing and Customizing U-boot

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

Introduction to Embedded Linux - Optimizing and Customizing U-boot

Kernel Boot Option Improvements

Kernel Boot Option Improvements


Reduce Linux Boot Bootargs (1)
Pre-set loops per jiffy
You just need to measure this once Find lpj value in kernel boot messages
Calibrating delay loop 718.02 BogoMIPS (lpj=3590144)

Add the lpj=3590144 to the bootargs

Use Static IP addressing where possible


If you dont need networking then disable it altogether If you want networking capability but not NFS then be sure to set ip=off on the kernel command line.

Set memory limit with mem= option


Use only as much memory as needed to avoid DDR initialization time

Reduce Linux Boot Bootargs (2)


Almost a second is spent verifying the kernel image checksum.
If your system doesnt do anything about a bad image, why verify it? This verification can be disabled by setting the verify u-boot parameter to n at the u-boot command prompt u-boot# setenv verify n

Use the quiet bootargs option to disable routine status printfs to console Remove the console altogether
Remove console=ttyO0,115200n8 from bootargs

Introduction to Embedded Linux - Optimizing and Customizing U-boot

12 - 3

Initial Ram Disk

Initial Ram Disk


Common Filesystems and Media
Media Filesystem

MMC/SD Harddrive NAND / NOR Flash Network DDR

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

INITRD Support Must be Enabled in Kernel


<Kernel>/.config # # General setup # ... CONFIG_BLK_DEV_INITRD=y CONFIG_INITRAMFS_SOURCE="" ... # # UBI - Unsorted block images # ... CONFIG_BLK_DEV_RAM=y CONFIG_BLK_DEV_RAM_COUNT=1 CONFIG_BLK_DEV_RAM_SIZE=4000 CONFIG_BLK_DEV_RAM_BLOCKSIZE=1024 Note: In addition to enabling initrd support, the blocksize and count must be configured to match the Ramdisk image.

12 - 4

Introduction to Embedded Linux - Optimizing and Customizing U-boot

Initial Ram Disk

Creating a Ramdisk Image


# Ramdisk Constants RDSIZE=4000 BLKSIZE=1024 # Create an empty ramdisk image sudo dd if=/dev/zero of=/tmp/ramdisk.img bs=$BLKSIZE count=$RDSIZE # Make it an ext2 mountable file system sudo /sbin/mke2fs -F -m 0 -b $BLKSIZE /tmp/ramdisk.img $RDSIZE # Mount it so that we can populate sudo mount /tmp/ramdisk.img /mnt/initrd -t ext2 -o loop=/dev/loop0 ### Fill image with filesystem ### # Finish up... sudo umount /mnt/initrd sudo gzip -9 /tmp/ramdisk.img sudo cp /tmp/ramdisk.img.gz . 8
8

Ramdisk Boot Arguments


uEnv.txt bootargs=MEM=124M console=ttyO0,115200n8 root=/dev/ram0 rw rootfstype=ext2 initrd=0x87c00000,4M ip=none quiet lpj=3590144 init=/linuxrc silent=true uenvcmd=run mmc_load_uimage;fatload mmc 0 0x87c00000 ramdisk.img.gz 0x400000; bootm ${kloadaddr} MEM=124 M 128M 4M Ramdisk initrd=0x87c00000,4M 0x87c00000 = start of DDR3 + 124M offset ,4M = length of initrd MMC Partition 1

MLO u-boot.img uImage uEnv.txt ramdisk.img.gz

Introduction to Embedded Linux - Optimizing and Customizing U-boot

12 - 5

U-boot Rebuild

U-boot Rebuild
MLO (U-boot_min) Build
n
RBL
ROM

(x-loader) Internal RAM

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

(x-loader) Internal RAM

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

Both MLO and u-boot.img may be built simultaneously using


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

host$ make ARCH=<ARCH> CROSS_COMPILE= <target> <ARCH> and <Target> as defined in boards.cfg

12 - 6

Introduction to Embedded Linux - Optimizing and Customizing U-boot

U-boot Rebuild

Translating Target into Source Directories


<U-boot>/boards.cfg

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

arm arm926ejs dm6467evm davinci arm arm armv7 armv7 am3517evm logicpd am335x ti

13

13

U-Boot Sources

board/<Vendor>/<Board name>

<Vendor> <Board> <ARCH> <SoC> <Target> As defined In boards.cfg

arch/<ARCH>/include/asm/arch-<SoC>

include/configs/<Target>.h
14

Introduction to Embedded Linux - Optimizing and Customizing U-boot

12 - 7

U-boot Rebuild

Configuration File Options Boot Time


host$ gedit include/configs/<target>.h

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

U-Boot Board File


Defines Required interface functions for SPL and U-Boot One source file contains the code for both SPL and U-Boot and are separated by preprocessor flags SPL handles the initialization of clocks, DDR, Serial Port and PMIC Some functions are defined twice in both an SPL context and then again in a U-Boot context (s_init & board_init) The board file is where the developer will spend most of their effort for a port

16

12 - 8

Introduction to Embedded Linux - Optimizing and Customizing U-boot

Вам также может понравиться