slides intro embedded linux 3day color
TRANSCRIPT
Introduction to Embedded Linux
Student Guide
Revision 2.00 April 2013
Technical Training Organization
Important Notice
ii Introduction to Embedded Linux
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 TI’s 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 customer’s 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. TI’s publication of information regarding any third party’s products or services does not constitute TI’s 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
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 1
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.)
Module Topics
01 - 2 Introduction to Embedded Linux - Module 01: Booting Linux
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
Module Topics
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 3
Booting Linux from Pre-Built Binaries
01 - 4 Introduction to Embedded Linux - Module 01: Booting Linux
Booting Linux from Pre-Built Binaries
Linux in Three Parts
Flash
BootloaderProvides rudimentary h/w initCalls Linux kernel and passes boot arguments
KernelInitializes the system (and device)Manages system resourcesProvides services for user programs
FilesystemSingle filesystem (/ root)Stores all system filesAfter init, kernel looks to filesystem for “what’s next”bootarg tells linux where to find root filesystem
File System
Linux Kernel
Boot Loader
Linux Boot Process
U-Boot
Linux Kernel
Init Process
Login Prompt
Power On
ARM assembly codePasses args to Linux (bootargs)
Initialize hardware via static drivers
/sbin/init – 1st process exe by kernel
Login consoleUsually one of first prog’s to run
Mount root filesys
Booting Linux from Pre-Built Binaries
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 5
Where Do You Find …
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 JFFSAll components may be flashed using U-boot (initial load via MMC or bootp) or JTAG using flashing utility via Code Composer Studio
Where located: Flash Boot
1a. SBL, UBL or MLO n/a1b. Bootloader (U-Boot) Flash
2. Linux Kernel Flash
3. Filesystem Flash
Where Do You Find …
Multimedia Card (MMC) or Secure Digital card (SD) may be flashed using an MMC/SD programmer using a variety of utilitiesSimple, low cost method for booting Linux (or just U-boot) on a development board that has nothing pre-programmed (or for recovery.)
Where located: Flash Boot MMC Boot
1a. SBL, UBL or MLO n/a MMC1b. Bootloader (U-Boot) Flash MMC
2. Linux Kernel Flash MMC
3. Filesystem Flash MMC
Booting Linux from Pre-Built Binaries
01 - 6 Introduction to Embedded Linux - Module 01: Booting Linux
Device
Booting Linux – MMC/SD Boot
RBL MLO U-Boot Kernel
ROM Internal RAM DDR2 DDR2
MMC/SD
DDR3MLO
UBoot Linux Kernel
RBLMLO
UBoot LinuxKernel
The ROM bootloader cannot make assumptions about external memory, so it can only load to the device’s internal memoryuBoot with MMC driver is too large to fit into internal memory
OCMC (on-chip memory controller)Internal memory
Where Do You Find …
NFS boot is typically used for development but not production devicesAll components of the system are loaded from host server at each bootFilesystem changes on host are instantly reflectedUBL, U-boot and Linux Kernel changes are reflected on each rebootGood method to ensure uniformity across multiple development boards
Where located: Flash Boot MMC Boot NFS Boot
1a. SBL, UBL or MLO n/a MMC bootp / tftp1b. Bootloader (U-Boot) Flash MMC tftp
2. Linux Kernel Flash MMC tftp
3. Filesystem Flash MMC nfs
Booting Linux from Pre-Built Binaries
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 7
Step 1: Setup EZSDKSetup and Rebuild Linux EZSDKhost $ 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 variableConfigures 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 bitCreates setup.minicom script to configure u-boot for desired boot type (mmc or tftp/nfs).
Step 2: Boot Linux from MMCMMC BootAttach SD/MMC programmer with inserted Micro-SD adapterhost $ cd ti-sdk-am335x-evm-xx.xx.xx.xx/bin
host $ sudo ./create-sdcard.sh
MLO (i.e. x-loader)u-boot.imguImage (i.e. Kernel)
RootFilesystem
Partition 1(FAT32)
Partition 2(EXT3)
ROM bootloader will load a file named “MLO” from partition 1, which must be FAT32 filesystemMLO (per MMC default config) boots a file named “u-boot.bin” from partition 1 of FAT32 MMC
Linux root filesystem must be in its own partition.
Booting Linux from Pre-Built Binaries
01 - 8 Introduction to Embedded Linux - Module 01: Booting Linux
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 boot2. SPI Flash boot3. TFTP/NFS (network) boot
Linux Boot Arguments for MMC Bootmmc_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 rootwaitip=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.
Rebuilding and Modifying SDK Components
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 9
Rebuilding and Modifying SDK Components
Rebuilding EZSDK
Rebuild SDKhost $ make help
host $ make clean
host $ make all
Install rebuilt components to export directory (default ${HOME}/targetfs)host $ make install
make all rebuilds:U-bootLinux KernelOpenGL graphics Demos
Example ApplicationsWireless Driver Support
Device
Booting Linux – MMC/SD Boot
RBL MLO (x-loader) U-Boot Kernel
ROM Internal RAM DDR2 DDR2
MMC/SD
DDR3
MLO(x-loader)
UBoot Linux Kernel
RBLMLO
(x-loader)
UBoot LinuxKernel
The ROM bootloader cannot make assumptions about external memory, so it can only load to the device’s internal memoryuBoot with MMC driver is too large to fit into internal memory
OCMC (on-chip memory controller)Internal memory
Rebuilding and Modifying SDK Components
01 - 10 Introduction to Embedded Linux - Module 01: Booting Linux
MLO (U-boot_min) Build
host $ cd ti-sdk-am335x-evm-xxx/board_support/u-boot-xxx
host $ make distcleanhost $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- am335x_evm_config*
host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- MLO
MLO (x-loader) U-Boot Kernel
ROM Internal RAM DDR2 DDR2
RBL
* For available configs: host$ ls include/configs
U-Boot Build
host $ cd ti-sdk-am335x-evm-xxx/board_support/u-boot-xxx
host $ make distcleanhost $ 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
MLO (x-loader) U-Boot Kernel
ROM Internal RAM DDR2 DDR2
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 distcleanhost $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- am335x_evm
RBL
Rebuilding and Modifying SDK Components
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 11
Kernel Build
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
MLO (x-loader) U-Boot Kernel
ROM Internal RAM DDR2 DDR2
* For available ARCH: host$ ls arch/** For available configs: host$ ls arch/arm/configs
RBL
“make menuconfig” options
Rebuilding and Modifying SDK Components
01 - 12 Introduction to Embedded Linux - Module 01: Booting Linux
Kernel Object Modules
# insmod <mod_name>.ko [mod_properties]
Use insmod (short for insert module) command to dynamically add modules into the kernelKeep statically built kernel small (to reduce size or boot-up time), then add functionality later with insmodInsmod is also handy when developing kernel modules
Linux Kernel source code is broken into individual modulesOnly those parts of the kernel that are needed are built in
Kernel Module Examples:fbdev frame buffer devv4l2 video for linux 2nfsd network file server devdsp oss digital sound proc.audio alsa audio driver
1. Static(built-in)
2. Dynamic(insmod)
.ko = kernel object
Linux Kernel
v4l2
fbdev
dsp
oss
nfsd ext3
httpd
System Startup Details
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 13
System Startup Details
File System
Linux Kernel
Boot Loader
Linux Boot Process
U-Boot
Linux Kernel
Init Process
Login Prompt
Power On
ARM assembly codePasses args to Linux (bootargs)
Initialize hardware via static drivers
/sbin/init – 1st process exe by kernel
Login consoleUsually one of first prog’s to run
Mount root filesys
Linux Initialization ProcessThe initialization process is launched by the Linux Kernel after the root filesystem is mountedBy default it is located at /sbin/init, but it can be specified as a kernel boot argument
/etc/inittab /etc/init.d
/etc/rcX.d
bootmisc.sh syslog
mountnfs.sh telnetd
networking thttpd
S05networking S20syslog
S10telnetd S20thttpd
S20syslog S60mountnfs
/sbin/init
System Startup Details
01 - 14 Introduction to Embedded Linux - Module 01: Booting Linux
SysV Startup
Arago and most Linux distributions use the SysV(“System Five”) startup process/etc/init.d directory holds all scripts used for boot-up/etc/rcX.d (i.e. /etc/rc5.d) contains links to these scripts specifying which should run and in what order for a given run level 1-5 (5 is default)Sxx precedes the name of each link in rcX.d. “S” indicates it is run at startup, “xx” indicates the order
/etc/init.d
/etc/rcX.d
bootmisc.sh syslog
mountnfs.sh ...
S05networking S20syslog
S10telnetd ...
Beaglebone Arago Runlevel 5 Startup
S01psplash S10checkroot S37populate-volatile.sh S45mountnfs.shS02banner S12udev-cache S38devpts.sh S55bootmisc.shS03sysfs S20modutils.sh S39alsa-state S99finish.shS03udev S30ramdisk S40configureS06alignment S35mountall.sh S41networking
/etc/rcS.d
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)
S10dropbear S20syslog S70lighttpd S98storage-gadget-initS10telnetd S20thttpd S97matrix-gui-2.0 S99gplv3-noticeS20netperf S30pvr-init S98parse-ip S99rmnologin
/etc/rc5.d
System Startup Details
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 15
/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 scriptsl0:0:wait:/etc/init.d/rc 0l1:1:wait:/etc/init.d/rc 1l2:2:wait:/etc/init.d/rc 2l3:3:wait:/etc/init.d/rc 3l4:4:wait:/etc/init.d/rc 4l5:5:wait:/etc/init.d/rc 5# Other InitializationsS:2345:respawn:/sbin/getty 115200 ttyO0
Format:<id>:<runlevels>:<action>:<process>
/etc/fstab
# stock fstab - you probably want to override this with a machine specific one
rootfs / auto defaults 1 1proc /proc proc defaults 0 0devpts /dev/pts devpts mode=0620,gid=5 0 0usbfs /proc/bus/usb usbfs defaults 0 0tmpfs /var/volatile tmpfs defaults,size=16M 0 0tmpfs /dev/shm tmpfs mode=0777 0 0tmpfs /media/ram tmpfs defaults,size=16M 0 0
# uncomment this if your device has a SD/MMC/Transflash slot#/dev/mmcblk0p1 /media/card auto defaults,sync,noauto 0 0
Format:<device>:<mount point>:<filesys type>:<options>:<backup>:<check>
System Startup Details
01 - 16 Introduction to Embedded Linux - Module 01: Booting Linux
inetd/xinetduser@ubuntu:~$ ls /etc/xinetd.dchargen daytime discard echo tftp time
service tftp{protocol = udpport = 69socket_type = dgramwait = yesuser = nobodyserver = /usr/sbin/in.tftpdserver_args = /tftpbootdisable = 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
/etc/inittab
/sbin/init
/etc/init.d
/etc/rcX.d
bootmisc.sh syslog
mountnfs.sh ...
S05networking S20syslog
S10telnetd ...
/etc/fstab
Ultimately, the meaning of initialization scripts are driven completely by /sbin/initInitialization scripts and tables only have meaning for a given distribution if recognized by /sbin/init
Beaglebone Arago
Lab 1 Introduction
Introduction to Embedded Linux - Module 01: Booting Linux 01 - 17
Lab 1 Introduction
Lab 1: Booting Linux
A. Start and Configure Ubuntu VmwareB. Create Bootable SD CardC. 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 VmwareB. Create Bootable SD CardC. Boot Linux on Beaglebone
MLO (i.e. x-loader)u-boot.imguImage (i.e. Kernel)
RootFilesystem
Partition 1(FAT32)
Partition 2(EXT3)
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
Lab 1 Introduction
01 - 18 Introduction to Embedded Linux - Module 01: Booting Linux
Lab 1: Booting Linux
A. Start and Configure Ubuntu VmwareB. Create Bootable SD CardC. Boot Linux on Beaglebone
1. Map Serial-over-USB and Ethernet-over-USB to VM
2. Launch minicom serial terminal emulator
3. Manually load Ethernet-over-USB driver.
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 1
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.
Module Topics
02 - 2 Introduction to Embedded Linux - Module 02: Linux Distributions
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
(Short) Product Overview
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 3
(Short) Product Overview
TI Embedded Processors Portfolio
32-bitReal-time
32-bit ARM
ARMIndustry StdLow Power
<100 MHz
Flash64 KB to 1 MB
USB, ENET, ADC, PWM, SPI
Host Control
$2.00 to $8.00
16-bit
Microcontrollers
MSP430Ultra-Low
Power
Up to 25 MHz
Flash1 KB to 256 KB
Analog I/O, ADCLCD, USB, RF
Measurement,Sensing, General
Purpose
$0.49 to $9.00
DSP
C647x, C64x+, C674x, C55x
Leadership DSP Performance
24,000 MMACS
Up to 3 MBL2 Cache
1G EMAC, SRIO,DDR2, PCI-66
Comm, WiMAX, Industrial/
Medical Imaging
$4.00 to $99.00+
ARM+
ARM9Cortex A-8
Industry-Std Core,High-Perf GPP
Accelerators
MMU
USB, LCD,MMC, EMAC
Linux/WinCE User Apps
$8.00 to $35.00
DSP
C64x+ plusARM9/Cortex A-8Industry-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 + DSP
ARM-Based
C2000™Fixed &
Floating Point
Up to 300 MHz
Flash32 KB to 512 KB
PWM, ADC, CAN, SPI, I2C
Motor Control, Digital Power,
Lighting, Sensing
$1.50 to $20.00
ARM CPU Processor Cores
http://www.arm.com/products/processors/index.php
ARM11
ClassicARM Processors
ARM7Cortex-M3
Cortex-M4
Cortex-R4
Cortex-A8
EmbeddedCortex Processors
ApplicationCortex Processors
ARM9
Capability
Per
form
ance
, Fun
ctio
nalit
y
TI’s ARM core's supporting Linux...
(Short) Product Overview
02 - 4 Introduction to Embedded Linux - Module 02: Linux Distributions
TI ARM® investment and innovation
* TI licensed in July 2003, but publicly announced Oct 2005.
Newest DaVinci solution for
flexible, HD video
Two ARM Cortex-R4
cores for
automotive
TI Licenses
first ARM core
1995
1st single-chip digital baseband -
DSP/ARM multi-core
1st multi-core applications processor,
ARM9-based
2002 2005
*TI first licensee for ARM Cortex™- A8
Introduced DaVinci™ processors for
digital video – ARM9™-based SoCs
2006
1st ARM Cortex-A8
based silicon
2007
TI Licenses
ARM Cortex-A9
2009
TI Acquires Luminary
Micro
TI announces
31 new Stellaris®
andARM-based
MPUs
Stellaris®
Sandstorm Class
Stellaris®
Fury Class
2008
Stellaris®
DustDevil Class
Stellaris®
Tempest Class
StellarisMCUFixed/
Floating-Point ARM9 SoC
1993
TMS570FMCU
1st R4F-based floating-point, dual-core auto
MCU
DaVinci™
OMAP™
OMAP 3
OMAP™
OMAP1510
DaVinci™ TMS570MCU
OMAP™
OMAP-L138
2010 2011
Lead Licensee
on Cortex-
M4
Introduce ARM Cortex-A9
based siliconOMAP™
OMAP 4
Introduce ARM
Cortex-A15
based siliconOMAP™
OMAP 5
TI Licenses Cortex-A15
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 Licenses Cortex-A7
AM335x Cortex™-A8 based processorsBenefits• High performance Cortex-A8 at ARM9/11 prices• Rich peripheral integration reduces complexity and cost
Sample Applications
Software and development tools• 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: 2Q’12• Dev. Tools: Order open October 31, 2011• Prelim docs: available today• Packaging: 13x13, 0.65mm via channel array
15x15, 0.8mm
• 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
Availability of some features, derivatives, or packages may be delayed from initial silicon availability Peripheral limitations may apply among different packagesSome features may require third party supportAll 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
ARM®
Cortex-A8up to
720* MHz
L3/L4 Interconnect
Serial Interface
32K/32K L1 w/SED
256K L2 w/ECC
64K RAM64K
SharedRAM
Display24 bit LCD Ctrl (WXGA)
Touch Scr. Ctrl.**
Securityw/ crypto acc.
PRU SSPRU x2200 MHz
12K RAMw/SED
Peripherals8K P. w/SED8K D. w/SED
System
Memory InterfaceLPDDR1/DDR2/DDR3
NAND/NOR(16b ECC)
ParallelEDMA
Timers x8WDTRTC
eHRPWM x3eQEP x3eCAP x3
JTAG/ETBADC (8ch)
12-bit SAR**
UART x6SPI x2I2C x3
McASP x2(4ch)
CAN x2(2.0B)
MMC/SD/SDIO x3
GPIO
USB 2.0 OTG+ PHY x2
EMAC 2port10/100/1Gw/1588 &
switch (MII,RMII, RGMII)
GraphicsPowerVR
SGX 3D Gfx
(Short) Product Overview
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 5
Demos
Kit Contents
Documentation
• User and Demo guide, Releases: TI Wireless Connectivity Wiki• Module WL1271-Type TN Datasheet from Murata
COM6M WL1271 Adapter Boardis included in AM335x EVM Kit
AM335x/WL1271 Development Kit
Software
AM335x EVMavailable for purchase throughTI E-store: TMDXEVM3358
• QT based WLAN and Bluetooth® demoApplications integrated into SDK
• WPA Supplicant and HostApd GUIs for WiFi Station and Soft APsetup
• Profusion Bluetooh GUI with BMG (Scan, Pair, Connect), A2DP, FTP, OPP and SPPdemos
• TI AM335x EVM Kit includes AM3358 Microprocessor, 512 MB DDR2, TPS65910 Power management IC, 7” LCD, Software & Tools, WL1271 COM6M Adapter Card
• 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• TI’s 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
Applications• Mobile consumer devices• Industrial and home automation, metering• Portable data terminals• Video conferencing, video camera
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
www.ti.com/wl1271typetn
LBEE5ZSTNC-523
(Short) Product Overview
02 - 6 Introduction to Embedded Linux - Module 02: Linux Distributions
What is Pin Multiplexing?
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 layoutRead datasheet for final authority on how pins are muxedGraphical utility can assist with figuring out pin-muxing… Pin mux utility...
HPIuPP
Pin Mux Example
Pin Muxing Tools
Graphical Utilities For Determining which Peripherals can be Used SimultaneouslyProvides Pin Mux Register Configurationshttp://wiki.davincidsp.com/index.php?title=Pinmux_Utilities_for_Davinci_Processors
Linux Distributions
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 7
Linux Distributions
What Is a ‘Linux Distribution’A ‘Linux distribution’ is a combination of the components requiredto 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
2. BootloaderUboot is the standard bootloader for ARM Linux
3. Linux ‘file system’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 WindowsIt 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)
4. Development toolsCodeSourcery - GCC, GDBMV DevRocket, CCSv5 (beta), GHS Multi, etc.
O/S Choices
Choices
Linux Android(arowboat.org) WinCE
Commercial Community
Others …
• QNX• Nucleus• BIOS• Etc.
Build ItYourself
Linux Distributions
02 - 8 Introduction to Embedded Linux - Module 02: Linux Distributions
O/S Choices
Choices
Linux Android(arowboat.org) WinCE
Commercial Community
Others …
• QNX• Nucleus• BIOS• Etc.
Build ItYourself
LinuxMontaVistaTimeSysWind RiverMentorRidgerun
WinCEAdeneoMistralMPC DataBSQUARE
Commercial O/S Vendors
Linux Partner StrategyCommercial: provide support, off-the-shelf Linux distributions or GNU toolsConsultants: provide training, general embedded Linux development expertise, or specific expertise for developing drivers or particular embedded applicationshttp://www.tiexpressdsp.com/index.php/Linux_Consultants_and_Commercial_Linux_Providers
RTOSGreen HillsWind River (VxWorks)ELogic (ThreadX)QNXMentor (Nucleus)
Linux Distributions
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 9
O/S Choices
Choices
Linux Android(arowboat.org) WinCE
Commercial Community
Others …
• QNX• Nucleus• BIOS• Etc.
Build ItYourself
Arago Lineage
Open Embedded
Angstrom
Arago
ubootsource
Various GNU appskernel.org
Many DistributionsMany Platforms
One DistributionMany Platforms
One DistributionTI Platforms
Linux Distributions
02 - 10 Introduction to Embedded Linux - Module 02: Linux Distributions
Arago Feedback Loop
Open Embedded
Angstrom
Arago
ubootsource
Various GNU appskernel.org
TI-specific drivers and patches pushed back to community
O/S Choices
Choices
Linux Android(arowboat.org) WinCE
Commercial Community
Others …
• QNX• Nucleus• BIOS• Etc.
Build ItYourself
Linux Distributions
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 11
Open EmbeddedOpen Embedded is a Linux open-source project to provide a build system for building and maintaining a Linux DistributionThe 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 FileaDESCRIPTION = "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 }
Includes download instructions, build instructions and dependencies
http://www.openembedded.org/wiki/How_to_create_a_bitbake_recipe_for_dummies
Linux Distributions
02 - 12 Introduction to Embedded Linux - Module 02: Linux Distributions
Arago Project Downloads
Arago install and updates are distributed via gitArago install includes Bitbake, Open Embedded recipesA separate page contains pre-built binaries (snapshots)
Ångström : Narcissus
(http://www.angstrom-distribution.org/narcissus)
Linux Distributions
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 13
Using opkg to Add New Packages
To see the commands the opkg package manager supportshost$ opkg
To install an opkg-compliant packagehost$ opkg install <packagename>.ipkg
To download a package but not install ithost$ opkg download <packagename>
To find out which packages provides a given filehost$ opkg whatprovides <filename>
To list which packages are availablehost$ opkg list
To update the list of available packages and “whatprovides” searchhost$ opkg update
Using opkg to Trim Down a Filesystem
You can start by listing all packages that are installed on the systemhost$ opkg list-installed
If you find a package you don’t think you need, good idea to check what other packages depend on it before removing
host$ opkg whatdepends <packagename>
Assuming you don’t 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 don’t need, you can determine the package that installed it using
host$ opkg search <file>
Linux Distributions
02 - 14 Introduction to Embedded Linux - Module 02: Linux Distributions
Linux Distributions Options for TI
Ease of UseEasyTested
Experienced User Latest
Commercial Community Custom(Build it Yourself)
TimesysMontaVistaEtc.
TI SDK(PSP)
Ångström / Arago
Open Embedded
(OE)
Custom from
Sources
Binary(Update patches)
BinaryUpdated foreach SDKrelease
BinaryNarcissus(online tool)opkg
Bit-BakeRecipies
“GIT”from kernel.org, and others
MMU and Dynamic Libraries
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 15
MMU and Dynamic Libraries
FragmentationProblem:Over time, the system heap that is used to manage dynamic memory becomes fragmented.
Free Memory
Allocated Memory
FreeAllocated
Free
Allocated
FreeAllocated
Free
Allocated
mallocfreemallocfree…
Virtual MemorySolution:A Memory Management Unit (MMU) maps fragmented physical memory into “virtually contiguous” memory
FreeAllocated
Free
Allocated
FreeAllocated
Free
Allocated
Allocated Memory
Free Memory
MMU
MMU and Dynamic Libraries
02 - 16 Introduction to Embedded Linux - Module 02: Linux Distributions
Memory ProtectionThe memory management unit also provides memory protection by denying access to regions of physical memory that are not allocated to a given application
Application 1 Memory
(unused)
Application 2 Memory
(unused)
Application 1
Application 2
Physical Memory
MMU
Memory ProtectionWhen application 1 is executing, it’s application memory is mapped to a valid virtual address. Disallowed memory is assigned no virtual address and is therefore unreachable.
Application 1 Memory
(unused)
Application 2 Memory
(unused)
Application 1Physical Memory
MMU
Allowed
MMU and Dynamic Libraries
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 17
MMU Details
All user-mode applications access memory via the MMUKernel 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)
Application 1
MMU
Application 2
Common libraries are shared across applications and dynamically linked
Application 1 Memory
(unused)
Application 2 Memory
(unused)
Physical Memory
Static Libs
Static Libs
MMU and Dynamic Libraries
02 - 18 Introduction to Embedded Linux - Module 02: Linux Distributions
Dynamic Linking and .so Libraries
Physical Memory
Application 1Application 1 Memory(unused)
Shared Libraries
(unused)
Application 2 Memory
(unused)
MMU
Application 2
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 librarylibpthread.so – shared POSIX thread library
or the static libraries (archives)libm.a – staic math librarylibpthread.a – static POSIX thread library
Depending on which library appears first in the library search path.
Lab 2: Terminal Manipulation
Introduction to Embedded Linux - Module 02: Linux Distributions 02 - 19
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 cp pwd ls mkdir
mv rm rmdir touch
Concepts Covered:wildcard (*) home directory (~)autofill (<tab>) terminal history (arrow keys)text editor (gedit)
Lab 2: Terminal Manipulation
02 - 20 Introduction to Embedded Linux - Module 02: Linux Distributions
(Page intentionally left blank)
Introduction to Embedded Linux - Module 03: The git Tool 03 - 1
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.
Module Topics
03 - 2 Introduction to Embedded Linux - Module 03: The git Tool
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
git Overview
Introduction to Embedded Linux - Module 03: The git Tool 03 - 3
git Overview
git Branches
Creating a new git repositoryYou may create a new git repositoryhost$ 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 filesStep 2: use “git init” to initialize the directory with git metadataStep 3: add files to the projectStep 4: use “git add” to add files from the directory to the git repository
(just placing the file in the git directory hasn’t 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”
git Overview
03 - 4 Introduction to Embedded Linux - Module 03: The git Tool
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 because1. Automatically creates a local git repository2. Allows you to pull external changes (patches) from the
public repository and merge them into your copy3. Depending on configuration, allows you to push your
changes back to the public repository
git Commit and Branches
branch 2
commit
commit
commit
commit
commit
commit
commitbranch 3
• 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
master(branch 1)
commit
Adding Commits
Introduction to Embedded Linux - Module 03: The git Tool 03 - 5
Adding Commits
Creating a Repository
host$ mkdir ~/my_project
host$ git init
host$ cp ~/project_files/* ~/myproject
host$ git add *
host$ git commit –m “initial_version”
HEAD
The HEAD marker indicates your position within the branch/commit structure.By default git names the first branch “master,” although this can be overridden.
master(branch 1)
Making Commits
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
HEAD
master(branch 1)
Adding Commits
03 - 6 Introduction to Embedded Linux - Module 03: The git Tool
Making Commits
commit
(make changes to “file1” and “file2”…)
host$ git add file1
host$ git commit
host$ git add file2
host$ git commit
commitHEAD
master(branch 1)
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 <[email protected]>
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
Adding Commits
Introduction to Embedded Linux - Module 03: The git Tool 03 - 7
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 commit’s SHA1 sum
host$ git checkout myTag
Tracked and Staged Filesfile1
file2
Index Staging Area
host$ touch file1 file2
host$
New files in a git repository are not tracked until added
git repository
Adding Commits
03 - 8 Introduction to Embedded Linux - Module 03: The git Tool
Tracked and Staged Filesfile1
file2
file1
file2
file1
file2
Index Staging Area
host$ touch file1 file2
host$ git add *
“git add” moves files to Staging Area and adds them to index
git repository
Tracked and Staged Filesfile1
file2
file1
file2
Index Staging Area
host$ touch file1 file2
host$ git add *
host$ git commit
“git commit” clears the staging area
git repository
Adding Commits
Introduction to Embedded Linux - Module 03: The git Tool 03 - 9
Tracked and Staged Filesfile1
file2
file1
file2
file2
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”
git repository
Tracked and Staged Filesfile1
file2
file3
file1
file2
(file1)
(file2)
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)
git repository
Adding Commits
03 - 10 Introduction to Embedded Linux - Module 03: The git Tool
git statusfile1
file2
file3
file1
file2
file2
Index Staging Area
host$ git status
# On branch master
# Changes to be committed
# modified: file2
# Changes not staged for commit:
# modified: file1
# Untracked files:
# file3
“git status” reports status of index and staging area
git repository
Adding and Merging Branches
Introduction to Embedded Linux - Module 03: The git Tool 03 - 11
Adding and Merging Branches
Making a New Branch
host$ git branch branch2
Creating a branch does not change your current position (i.e. currently checked-out commit)
branch 2
commit
commitHEAD
master(branch 1)
Making a New Branch
host$ git branch branch2
(change file1)
host$ git commit -a
commit
commit
commit branch 2HEAD
master(branch 1)
Adding and Merging Branches
03 - 12 Introduction to Embedded Linux - Module 03: The git Tool
Making a New Branch
host$ git branch branch2
(change file1)
host$ git commit -a
host$ git checkout branch2
Use “git checkout” to move to new branch
branch 2
commit
commit
master(branch 1)
HEADcommit
Making a New Branch (Example 2)
host$ git branch branch2(change file1)host$ git commit -ahost$ git checkout branch2(create file2)host$ git add file2host$ git commit -a
branch 2
commit
commit
commit HEAD
master(branch 1)
commit
Adding and Merging Branches
Introduction to Embedded Linux - Module 03: The git Tool 03 - 13
Merging git Branches
branch 2
commit
commit
commit
HEAD
master(branch 1)
commit
commithost$ git checkout branch2host$ git merge masterhost$ git commit -a
U-boot Practical Example
commit
U-bootmaster
1. Ima Pro of Penguins, Inc. clones the Arago u-boot for AM335x EVM from arago-project.org
Adding and Merging Branches
03 - 14 Introduction to Embedded Linux - Module 03: The git Tool
U-boot Practical Example
commit
1. Ima Pro of Penguins, Inc. clones the Arago u-boot for AM335x EVM from arago-project.org
2. Ima ports U-boot to the Penguins, Inc. production board
penguin
commit
U-bootmaster
U-boot Practical Example
1. Ima Pro of Penguins, Inc. clones the Arago u-boot for AM335x EVM from arago-project.org
2. Ima ports U-boot to the Penguins, Inc. production board3. As U-boot is updated on Arago git, Ima merges patches
commit
commit
commit
penguin
commit
U-bootmaster
Adding and Merging Branches
Introduction to Embedded Linux - Module 03: The git Tool 03 - 15
U-boot Practical Example
commit penguin
commit
U-bootmaster
commit
commit
commit
commit
penguinpro 2e
commit
commit
commitcommit4. Ima gets promoted5. Ima takes up golf6. Ima retires in Tahiti
Lab 3: Using git
03 - 16 Introduction to Embedded Linux - Module 03: The git Tool
Lab 3: Using git
Lab 3: Exploring git
A. Exploring git’s own git repositoryB. 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.”
Introduction to Embedded Linux - Module 04: Application Debug 04 - 1
Module 04: Application Debug
Introduction Code Composer Studio version 5 is the current iteration of Texas Instrument’s integrated development environment. This IDE can be used to program any of TI’s processors from the low-cost, 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.
Module Topics
04 - 2 Introduction to Embedded Linux - Module 04: Application Debug
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
Intro to Makefiles
Introduction to Embedded Linux - Module 04: Application Debug 04 - 3
Intro to Makefiles
Build Overview
Build Tool
Build Instructions
Source Files“Dependencies”
app.capp.cfgapp.h
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)
app.x64Papp.xv5Tapp.x470MVapp.x86U
Executables “Targets”
app.oapp.lib
“D” “CMD” “T”
Solution: command line (e.g. cl6x, gcc) or scripting tool (gMake, etc.)
Command Line (Examples 1-2)
Example 1: create an object file (app.o) from an input file (app.c)
Might be more convenient to place commands in a script/batch file…makefile…
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
“Commands”
command flag dependency flag target
Command Line
“Dependencies”
app.capp.o
app.oapp.x86U
“Targets”
“D” “CMD” “T”
-c = compile only-g = build with debug enabled-o = output filename
Intro to Makefiles
04 - 4 Introduction to Embedded Linux - Module 04: Application Debug
Basic Makefile with Rules
gMake
“Dependencies”
app.capp.o
app.oapp.x86U
“Targets”
“D” “CMD” “T”
One of the more common “scripting” tools is GNU Make, aka gMake, aka Make…gMake uses “rules” to specify build commands, dependencies and targetsGenerically, a RULE looks like this:
Remember Example 2? Let’s make this into a simple Makefile rule:gcc –g app.o –o app.x86U
command flag dependency flag target
Makefile
TARGET : DEPENDENCY[TAB] COMMANDS…
app.x86U : app.o
gcc –g app.o –o app.x86U
Becomes….RULE
Creating Your First Makefile
gMake
“Dependencies”
app.capp.o
app.oapp.x86U
“Targets”
“D” “CMD” “T”
Makefile
gcc –c –g app.c –o app.o
gcc –g app.o –o app.x86U Command Lines
# Makefile for app.x86U (goal)
app.x86U : app.ogcc –g app.o –o app.x86U
app.o : app.cgcc –g –c app.c –o app.o
Makefile
Intro to Makefiles
Introduction to Embedded Linux - Module 04: Application Debug 04 - 5
User-Defined Variables & Include Files
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.
“D” “CMD” “T”
include path.mak
CC := $(CC_DIR)gcc
CFLAGS := -g
LINK_FLAGS := -o
app.x86U : app.o
$(CC) $(CFLAGS) $^ $(LINK_FLAGS) $@
CC_DIR := /usr/bin/
...# other paths go here…
Examples:
makefile path.mak
Using Built-in Variables“D” “CMD” “T”
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:
app.x86U: app.o
gcc –g app.o –o app.x86U
Original makefile…
app.x86U: app.o
gcc –g $^ –o $@
Becomes…
Intro to Makefiles
04 - 6 Introduction to Embedded Linux - Module 04: Application Debug
Templated Rules Using “%”Using pattern matching (or pattern substitution) can help simplify your makefile and help you remove explicit arguments. For example:
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 $@
Original Makefile
app.x86U : app.o main.o$(CC) $(CFLAGS) $^ -o $@
%.o : %.c$(CC) $(CFLAGS) -c $^ -o $@
Makefile Using Pattern Matching
The .x rule depends on the .o files being built – that’s what kicks off the .o rules% is a shortcut for $(patsubst …), e.g. $(patsubst .c, .o)
Code Composer Studio Overview
Introduction to Embedded Linux - Module 04: Application Debug 04 - 7
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 communityDrop in Eclipse plug-ins from other vendors or take TI tools and drop them into an existing Eclipse environmentCCSv5 runs on a Windows or Linux host
Integrate additional toolsOS application development tools (Linux, Android…)Code analysis, source control…
Low cost!
CCSv5 Environment
Tabbed editor windows
Tab data displays togetherto save space
Fast view windows don’t displayUntil you click on them
Perspectives contain separatewindow arrangements depending
on what you are doing.
Customize toolbars & menus
Code Composer Studio Overview
04 - 8 Introduction to Embedded Linux - Module 04: Application Debug
Eclipse ProjectsCCSv5 is PROJECT-centricEclipse uses managed makefiles as their build scripts – as opposed to pjt filesEclipse projects are folder based
“Adding file” copies it to folder“Linking file” references original fileProject explorer shows folder contents
Project explorer lists functions
make file
PerspectivesPerspectives – a set of windows, views andmenus that correspond to a specific set of tasksTwo default perspectives are provided with CCSv5:
C/C++• Code Dev’t Views• Project Contents• Editor
Debug• Debug Views• Watch/Memory• Graphs, etc.
Users can customize perspectives and save them:
Code Composer Studio Overview
Introduction to Embedded Linux - Module 04: Application Debug 04 - 9
Two Default Build ConfigurationsBuild 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 modify compiler/linker options via “Build Options”:
User can create theirown config if desired
18Many more details on compiler options in a later chapter…
User Mode DebuggingWhen 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
Kernel Mode DebugDebugging kernel code requires complete system access. You need KGDB (Ethernet) or scan-based (JTAG) debuggers for this.
Debugging & Debugger’s
A debugger lets you Pause a programExamine and change variablesStep through code
Code Composer Studio (CCSv5)Latest version of TI’s graphical software debugger (i.e. IDE)IDE – integrated development environment: which combines editing, building and debugging into a single toolBuilt on Eclipse platform; can install on top of standard EclipseAllows debugging via GDB (Ethernet/serial) or JTAG (scan-based)Free license for GDB debugging
Code Composer Studio Overview
04 - 10 Introduction to Embedded Linux - Module 04: Application Debug
LANGdbserver on target
RS232Putty,Teraterm,Hyperterminal, CCS Serial Terminal
Linux application debug setup
LANGdb via Code Composer Studio
Debug system (PC) Target system (Board)
• Physically the connections of a typical linux application debug system are shown below.
JTAG
Linux kernel and driver debug setup
Debug system (PC) Target system (Board)
• Physically the connections of a typical uboot, linux kernel or driver debug system are shown below.
Code Composer Studio Overview
Introduction to Embedded Linux - Module 04: Application Debug 04 - 11
Open source debugger that is often supplied with the toolchainIn this workshop, it’s included in the Code Sourcery packageGDB has a client/server nature:
GDB Server:First start gdbserver, specifying connection and app to be debuggedServer then runs your app, following gdb commands
GDB (i.e. debug client)Command-line oriented debuggerTelnet, Bash terminal, IDE
GDB : GNU Debugger
(gdb) target remote 192.168.1.122:10000(gdb) step(gdb) b 43 (gdb) run
EVM> gdbserver 192.168.1.122:10000 myAppListening on port 10000Remote debugging from host 192.168.1.1
Hello World
Tera Term
GDB ServerRuns your app for you, based on the GDB commands you send
Graphical Debug with GDBEclipse (CCSv5) and other IDE’s can translate actions to GDB cmds
Other than starting gdbserver, it means we don’t have to know GDB syntaxThe debug (host) system runs:
Its own OS (Linux, Windows, etc.)Debugger IDE (optional) and GdbTerminal app (Tera Term, putty, etc.) to control the target/evm environment
Host PCCCSv5 (Eclipse)
Target (EVM)RS-232
Terminal
Ethernet
CCSv5 (Eclipse)
The target system runs:Embedded OS Gdbserver that controls app’s execution
GDB
Embedded O/S (ie. Linux)
GDB Server
App
ControlsTarget
Code Composer Studio Overview
04 - 12 Introduction to Embedded Linux - Module 04: Application Debug
CCSv5 Licensing & Pricing
20
Item Description Price AnnualPlatinum Eval Tools Full tools with 120 day limit (all EMU) FREEPlatinum Bundle EVM, sim, XDS100 use FREE Platinum Node Lock Full tools tied to a machine $495 (1) $99Platinum Floating Full tools shared across machines $795 (1) $159Microcontroller Core MSP/C2000 code size limited FREEMicrocontroller Node Lock MSP/C2000 $445 $99
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)
- recommended option: purchase Dev Kit, use XDS100v1-2, & Free CCSv5
Setting up a CCS5 GDB Session
Introduction to Embedded Linux - Module 04: Application Debug 04 - 13
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
Setting up a CCS5 GDB Session
04 - 14 Introduction to Embedded Linux - Module 04: Application Debug
Remote System View – Files / Terminal
Setting Up CCSv5 Application DebugRun Debug Configurations New Launch Configuration
Use remote system explorer to launch remote gdbserver
Setting up a CCS5 GDB Session
Introduction to Embedded Linux - Module 04: Application Debug 04 - 15
Setting Up CCSv5 Application Debug
Specify version of Gnu Debugger to use
CCSv5 Attached Remote Debugger
Setting up a CCS5 JTAG Session
04 - 16 Introduction to Embedded Linux - Module 04: Application Debug
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)
“click”
Specify GEL script here
Advanced Tab
16More on GEL files...
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 debugenvironment including:
16
• Memory Map• DDR Configuration• PINMUX• PSC• PLL
The board manufacturer (e.g. SD or LogicPD) supplies GEL fileswith each board.To create a “stand-alone” or “bootable” system, the user mustwrite code to perform these actions (optional chapter covers these details)
Lab 4: Application Build and Debug
Introduction to Embedded Linux - Module 04: Application Debug 04 - 17
Lab 4: Application Build and Debug
Lab 4: Application Build and DebugA. Test Secure Shell (ssh) protocolB. Create ProjectC. Set up CCS Remote System Explorer ConnectionD. Set up CCS Debug Configuration
Lab 4: Application Build and Debug
04 - 18 Introduction to Embedded Linux - Module 04: Application Debug
(Page intentionally left blank)
Introduction to Embedded Linux - Module 05: Linux Files 05 - 1
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.
Module Topics
05 - 2 Introduction to Embedded Linux - Module 05: Linux Files
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
Module Topics
Introduction to Embedded Linux - Module 05: Linux Files 05 - 3
Driver Basics
Kernel vs User Space
Kernel SpaceThe Linux kernel manages the machine's hardware via driversDrivers provide hardware abstraction and protectionDrivers execute within the Linux kernel’s 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 directlyMake requests to kernel to access peripherals or storage media
User Process 1
User Process 3
User Process 2LinuxKernel
APIDriver
RAM Memory
Storage
Peripherals
File Sys
MMU
API
API
User Access to Kernel Space
Kernel Space
User Space
audio driver video driver
harddrive
ATA driver
buffer buffer
Memoryprocess
main(){
func1();
func2();
…
/dev/dsp /dev/video0
/mypath/myfile
/dev/hda1
filesystem
Block – random Character - sequential
‘mounted’ to root file system
Module Topics
05 - 4 Introduction to Embedded Linux - Module 05: Linux Files
Four Steps to Accessing Drivers
1. Load the driver’s 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
Kernel Object Modules
Linux Kernel source code is broken into individual modulesOnly those parts of the kernel that are needed are built in
Kernel Module Examples:fbdev frame buffer devv4l2 video for linux 2nfsd network file server devdsp oss digital sound proc.audio alsa audio driver
How to add modules to Linux Kernel:1. Static (built-in) Linux Kernel
v4l2
fbdev
dsp
audio
nfsd ext3
httpd
Change static configuration using...
Module Topics
Introduction to Embedded Linux - Module 05: Linux Files 05 - 5
Static Linux Kernel Configuration
#> make ARCH=arm CROSS_COMPILE=arm_v5t_le- menuconfig
Kernel Object Modules
# modprobe <mod_name>.ko [mod_properties]
Use modprobe command to dynamically add modules into the Linux kernelKeep statically built kernel small (to reduce size or boot-up time), then add functionality later with modprobemodprobe is also handy when developing kernel modules
Linux Kernel source code is broken into individual modulesOnly those parts of the kernel that are needed are built in
Kernel Module Examples:fbdev frame buffer devv4l2 video for linux 2nfsd network file server devdsp oss digital sound proc.audio alsa audio driver
How to add modules to Linux Kernel:1. Static (built-in)
2. Dynamic(modprobe)
.ko = kernel object
Linux Kernel
v4l2
fbdev
dsp
oss
nfsd ext3
httpd
Module Topics
05 - 6 Introduction to Embedded Linux - Module 05: Linux Files
Examining The Steps in More Detail…
1. Load the driver’s 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
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.
# mknod <name> <type> <major> <minor>
<name>: Node name (i.e. virtual file name)
<type>: b blockc character
<major>: Major number for the driver
<minor>: Minor number for the driver
Example: mknod /dev/fb/3 c 29 3
Useage: Fd = open("/dev/fb/3", O_RDWR);
Module Topics
Introduction to Embedded Linux - Module 05: Linux Files 05 - 7
Linux Device RegistrationLinux devices are registered in /dev directoryTwo ways to view registered devices:
cat /proc/devicesls –lsa command (as shown below) to list available drivers
/ # cd /dev
/dev # ls –lsa
0 brw-rw---- 1 root disk 0, 0 Jun 24 2004 /dev/hda
0 crw-rw---- 1 root uucp 4, 64 Mar 8 2004 /dev/ttyS0
0 crw------- 1 user root 14, 3 Jun 24 2004 /dev/dsp
0 crw------- 1 user root 29, 0 Jun 24 2004 /dev/fb/0
0 crw------- 1 user root 29, 1 Jun 24 2004 /dev/fb/1
block vs char
Permissions (user,group,all)
Major number
Minor number Name
/dev directory
1. Load the driver’s 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
Examining The Steps in More Detail…
Module Topics
05 - 8 Introduction to Embedded Linux - Module 05: Linux Files
Mounting Block Devices
Mounting a block driver into the filesystem gives access to the files on the device as a new directoryEasy manipulation of flash, hard drive, compact flash and other storage mediaUse mkfs.ext2, mkfs.jffs2, etc. to format a device with a given filesystem
/ # mkdir /media/part1
/ # ls /media/part1
user – Shell – Konsole
Initially empty
Mounting Block Devices
Unlike Windows, there is only one filesystem – therefore you must mount to a mount point (i.e. empty directory) in the root filesystemEasy manipulation of flash, hard drive, compact flash and other storage mediaUse mkfs.ext2, mkfs.jffs2, etc. to format a device with a given filesystemThe above example shows mounting an external harddrive into the root filesystem
user – Shell – Konsole
Now populated
Initially empty
* Try ls –l : adds linefeeds
$ mount –t vfat /dev/mmcblk0p1 /media/part1
$ ls /media/part1
MLO u-boot.bin uImage
$ mkdir /media/part1
$ ls /media/part1
Module Topics
Introduction to Embedded Linux - Module 05: Linux Files 05 - 9
Some Common Filesystem TypesHarddrive File systems:
ext2 Common general-purpose filesystemext3 Journaled filesystem -
Similar to ext2, but more robust against unexpected power-downvfat Windows “File Allocation Table” filesystem
Memory File systems:jffs2 Journaling flash filesystem (NOR flash)yaffs yet another flash filesystem (NAND flash)ramfs Filesystem for RAMcramfs Compressed RAM filesystem
Network File systems:nfs Share a remote linux filesystemsmbfs Share a remote Windows® filesystem
Examining The Steps in More Detail…
1. Load the driver’s 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
Module Topics
05 - 10 Introduction to Embedded Linux - Module 05: Linux Files
Accessing Files
Manipulating files from within user programs is as simple as…
myFileFd = fopen(“/mnt/harddrive/myfile”,”rw”);
fread ( aMyBuf, sizeof(int), len, myFileFd );
fwrite( aMyBuf, sizeof(int), len, myFileFd );
fclose( myFileFd );
Additionally, use fprintf and fscanf for more feature-rich file read and write capability
File descriptor / handle Directory previously mounted File to open… Permissions
File descriptor / handleArray to read into / write from # of itemssize of item
Module Topics
Introduction to Embedded Linux - Module 05: Linux Files 05 - 11
NAND Flash Driver
NAND Partitions
# cat /proc/mtd
dev: size erasesize name mtd0: 00020000 00020000 "SPL" mtd1: 00020000 00020000 "SPL.backup1" mtd2: 00020000 00020000 "SPL.backup2" mtd3: 00020000 00020000 "SPL.backup3" mtd4: 001e0000 00020000 "U-Boot" mtd5: 00020000 00020000 "U-Boot Env" mtd6: 00500000 00020000 "Kernel" mtd7: 0f880000 00020000 "File System"
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.
Examples of Using NAND
# flash_eraseall /dev/mtd4
Erase NAND partition 4
# nandwrite –p /dev/mtd4 u-boot.img
Write u-boot into NAND partition 4
# ubiformat /dev/mtd7 –f ubi.img –s 512 –O 2048
Write a UBI image into NAND partition 7
UBI images are created with mkfs.ubifs and ubinize commands. For more information:http://processors.wiki.ti.com/index.php/UBIFS_Support
Module Topics
05 - 12 Introduction to Embedded Linux - Module 05: Linux Files
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:YX device numberY Volume number (ubi0:0) or name (ubi0:rootfs)
Module Topics
Introduction to Embedded Linux - Module 05: Linux Files 05 - 13
GPIO
GPIO Driver (Terminal)
# echo 30 > /sys/class/gpio/export
1. Export GPIO pin for sysfs usage (Pin 30 in example)
# echo "out" > /sys/class/gpio/gpio30/direction
# echo "in" > /sys/class/gpio/gpio30/direction
2. Change the GPIO pin direction to in/out
# echo 1 > /sys/class/gpio/gpio30/value
# echo 0 > /sys/class/gpio/gpio30/value
# cat /sys/class/gpio/gpio30/value
3. Change the value (output) or read the value (input)
# echo 30 > /sys/class/gpio/unexport
4. Unexport GPIO pin (when no longer needed)
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);
Module Topics
05 - 14 Introduction to Embedded Linux - Module 05: Linux Files
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
# echo 1 > /sys/devices/platform/leds-gpio/leds/am335x\:EVM_SK\:usr0/brightness
1. Light the usr0 LED
In addition to standard (device-specific) GPIO driver,Arago provides the (platform-specific) leds-gpio driver:
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
# cat /sys/devices/platform/leds-gpio/leds/am335x\:EVM_SK\:heartbeat/triggernone nand-disk mmc0 mmc1 timer [heartbeat] rfkill0 phy0rx phy0tx phy0assoc phy0radio
# echo none > /sys/devices/platform/leds-gpio/leds/am335x\:EVM_SK\:heartbeat/trigger
To disable the heartbeat led
Setting up a trigger ties an LED to a kernel event
Brackets around [heartbeat] indicate this LED is configured to trigger on the system heartbeat event.
Lab 5: GPIO via Virtual Files
Introduction to Embedded Linux - Module 05: Linux Files 05 - 15
Lab 5: GPIO via Virtual Files
Lab 5: GPIO via Virtual Files
Boot board and test GPIO (terminal)A. Light LED from C applicationB. Blink LED from C application
solution_Astart
solution_B
lab05_git
solutionsmaster
HEAD
Lab 5: GPIO via Virtual Files
05 - 16 Introduction to Embedded Linux - Module 05: Linux Files
(Page intentionally left blank)
Introduction to Embedded Linux - Module 06: Linux Drivers 06 - 1
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.
Module Topics
06 - 2 Introduction to Embedded Linux - Module 06: Linux Drivers
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
Driver Basics
Introduction to Embedded Linux - Module 06: Linux Drivers 06 - 3
Driver Basics
Files and Virtual Files (Review)
Kernel Space
User Space
audio driver video driver
harddrive
ATA driver
buffer buffer
Memoryprocess
main(){
func1();
func2();
…
/dev/dsp /dev/video0
/mypath/myfile
/dev/hda1
filesystem
Block – random Character - sequential
‘mounted’ to root file system
Accessing Files (Review)
Manipulating files from within user programs is as simple as…
myFileFd = fopen(“/mnt/harddrive/myfile”,”rw”);
fread ( aMyBuf, sizeof(int), len, myFileFd );
fwrite( aMyBuf, sizeof(int), len, myFileFd );
fclose( myFileFd );
Additionally, use fprintf and fscanf for more feature-rich file read and write capability
File descriptor / handle Directory previously mounted File to open… Permissions
File descriptor / handleArray to read into / write from # of itemssize of item
Driver Basics
06 - 4 Introduction to Embedded Linux - Module 06: Linux Drivers
Using Character Device Drivers
ioctl( soundFd, SNDCTL_DSP_SETFMT, &format);
Notes:len field is always in bytesMore complex drivers, such as V4L2 and FBDEV video drivers, have special requirements and typically use ioctl commands to perfrom reads and writes
Additionally, drivers use I/O control (ioctl) commands to set driver characteristics
Simple drivers use the same format as files:
soundFd = open(“/dev/dsp”, O_RDWR);
read ( soundFd, aMyBuf, len );
write( soundFd, aMyBuf, len );
close( soundFd );
beaglebone$ lsmod
g_mass_storage
beaglebone$ rmmod g_mass_storage
beaglebone$ modprobe g_ether
Dynamic Driver Example – USB
connect_etherusb.sh
The connect_etherusb.sh script manually removes the mass storage USB gadget driver from the Beaglebone’srunning kernel and then dynamically inserts the Ethernet-over-USB gadget driver.
UART Driver
Introduction to Embedded Linux - Module 06: Linux Drivers 06 - 5
UART Driver
TTY Teletype Terminal
Name “teletype terminal” derives from historical hardware device that is rarely used todayAll Linux textual terminals (shell, uart, modem, etc.) use the TTY standardBasic open, read, write and close calls to useCommon practice is to use the <termios.h> library in place of direct ioctl control calls.
(Left) Early TTYs printed to paper.
(Right) screens were later added
Serial Port Configuration (Part 1)#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <fcntl.h>#include <termios.h>
// Simple function to configure a serial port to 1152008N1void configure_serial(int fd){
struct termios terminal_setting;
tcgetattr(fd, &terminal_setting);
// Set baud rate// Most drivers use input rate for bothcfsetispeed(&terminal_setting, B115200);cfsetospeed(&terminal_setting, B115200);
UART Driver
06 - 6 Introduction to Embedded Linux - Module 06: Linux Drivers
Serial Port Configuration (Part 2)
// clear number of bits fieldterminal_setting.c_cflag &= ~CSIZE;// set 8 bitsterminal_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 bitterminal_setting.c_cflag &= ~CSTOPB;
// send changes to terminal settings structure to kernel// TCSANOW flag forces immediate changetcsetattr(fd, TCSANOW, &terminal_setting);
}
Serial Driver “Hello World”int main( void ){
char hello[40]="hello world\n";int fd;
// Open serial devicefd = open("/dev/ttyO0", O_RDWR);
configure_serial(fd);
// Write a string (char array) to devicewrite( fd, hello, sizeof(hello));
// Close fd to allow other programs accessclose(fd);
return 0;}
Advanced Linux Sound Architecture (ALSA)
Introduction to Embedded Linux - Module 06: Linux Drivers 06 - 7
Advanced Linux Sound Architecture (ALSA)
ALSA Applications
The ALSA driver provides 3 Linux applications to exercise the driver. While not fancy, record/play app’s are useful for testing. The mixer is useful for choosing inputs/outputs.The three app’s are:
arecord Record audio from an ALSA device to a file
aplay Play recorded audio over an ALSA device
amixer Select input sources and adjust relative volume levels
ALSA Library APIInformation Interface /proc/asound
Status and settings for ALSA driver.
Control Interface /dev/snd/controlCXControl hardware of system (e.g. adc, dac).
Mixer Interface /dev/snd/mixerControls volume and routing of on systems with multiple lines.
PCM Interface /dev/snd/pcmCXDXManages digital audio capture and playback; most commonly used.
Raw MIDI Interface* /dev/snd/midiCXDXRaw support for MIDI interfaces; user responsible for protocol/timing.
Sequencer Interface* /dev/snd/seqHigher-level interface for MIDI programming.
Timer Interface /dev/snd/timerTiming hardware used for synchronizing sound events.
* Not implemented in current TI provided driver.
Advanced Linux Sound Architecture (ALSA)
06 - 8 Introduction to Embedded Linux - Module 06: Linux Drivers
ALSA Driver Structure
ALSA Library
ALSA Kernel APIControlPCM
snd_pcm_open() snd_pcm_read()
snd_pcm_hw_params() snd_pcm_writei()
Snd_pcm_close()
open() read() write()
close() ioctl()
ALSA driver supports standard open, read, write, close and ioctl, however most programmers use the ALSA user-space library calls (snd_pcm_xxx)
arecordaplayamixer
ALSA Driver StructureApplication
User SpaceKernel Space
ALSA Library
ALSA Kernel APIControl
ALSA Driver CoreH/W Codec
DriverMachine
DriverPlatform Driver
McBSP Driver
PCM
AM335xControl I/F
(I2C) System DMA McBSPAudio Codec
(TWL4030/AIC23)
ALSA app’s
Hardware
Advanced Linux Sound Architecture (ALSA)
Introduction to Embedded Linux - Module 06: Linux Drivers 06 - 9
Opening and Closing Devices
Devices:hw:i,j i = card number, j = device numberdefault 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(¶ms);
/* 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);
Advanced Linux Sound Architecture (ALSA)
06 - 10 Introduction to Embedded Linux - Module 06: Linux Drivers
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; /* 2 bytes/sample, 2 channels */
buffer = (char *) malloc(size);
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));
}
Signal Handling
Introduction to Embedded Linux - Module 06: Linux Drivers 06 - 11
Signal Handling
Linux SignalsA 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 signalMemory segment violationsFloating-point processor errorsIllegal instructionsUser generated at terminalSend from one process (program) to another
“Catch” indicates the receipt of a signalApplication programmers may register signal handling routinesIf no user signal handler is registered, a default signal handler is used
Signals defined in signal.h
* Note, this is not a complete list
Signal Handling
06 - 12 Introduction to Embedded Linux - Module 06: Linux Drivers
Signal Registration Exampleint 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;
} elseprintf("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
}
Lab 6: UART Driver
Introduction to Embedded Linux - Module 06: Linux Drivers 06 - 13
Lab 6: UART Driver
Lab 6: UART DriverBoot board and test sshRemove serial console
A. Simple UART DriverB. Variables over UARTC. UART Configuration (Examination)
Restore serial console
solution_Astart
lab06_git
solutionsmaster
HEAD
solution_C
solution_B
Lab 6: UART Driver
06 - 14 Introduction to Embedded Linux - Module 06: Linux Drivers
(Page intentionally left blank)
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 1
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.
Module Topics
07 - 2 Introduction to Embedded Linux - Module 07: Linux Scheduler
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
Linux Processes
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 3
Linux Processes
What is a Process?
main(){
func1();
func2();
…
Process AMemory
main(){
func3();
func4();
…
Process BMemory
main(){
func5();
func6();
…
Process CMemory
Process A
Process B
Process C
Physical Processor
Scheduling MethodologiesTime-Slicing Threads
Scheduler shares processor run time between all threads with greater time for higher priorityNo threads completely starveCorrects for non-”good citizen”threadsCan’t guarantee processor cycles even to highest priority threads.More context switching overhead
Realtime ThreadsLower priority threads won’t run unless higher priority threads block (i.e. pause)Requires “good citizen” threadsLow priority threads may starve
Lower priority threads never break high priority threadsLower context-switch overhead
Time-sliced threads have a “nieceness” value by which administrator may modify relative loadingLinux dynamically modifies processes’ time slice according to process behaviorWith realtime threads, the highest priority thread always runs until it blocks itself
Linux Processes
07 - 4 Introduction to Embedded Linux - Module 07: Linux Scheduler
The Usefulness of Processes
// audio_video.c// handles audio and video in// a single application
int main(int argc, char *argv[]){
while(condition == TRUE){callAudioFxn();callVideoFxn();
}}
Option 1:
// audio.c, handles audio only
int main(int argc, char *argv[]) {while(condition == TRUE)
callAudioFxn();}
Audio and Video in a single Process
Option 2: Audio and Video in separate Processes
// video.c, handles video only
int main(int argc, char *argv[]) {while(condition == TRUE)
callVideoFxn();}
Splitting into two processes is helpful if: 1. audio and video occur at different rates 2. audio and video should be prioritized differently3. multiple channels of audio or video might be required (modularity)4. memory protection between audio and video is desired
Terminal Commands for Processes
# ps Lists currently running user processes# ps -e Lists all processes
# top Ranks processes in order of CPU usage
# kill <pid> Ends a running process
# renice +5 –p <pid> Changes time-slice ranking of a process(range +/- 20)
Linux Processes
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 5
Launching a Process – Terminal
Side Topic – Creating New Processes in C
Splits one executing process into two
with same environment
New process replacesold but maintains
previous environment
Launch new processand keep previous
process
All processes are split-off from the original process created at startupWhen using fork, both processes run the same code; to prevent this, test if newly created process and run another program – or exec to another programTo review, a process consists of:
Context (memory space, file descriptors)One (or more) threads
fork exec fork + exec
Linux Threads
07 - 6 Introduction to Embedded Linux - Module 07: Linux Scheduler
Linux Threads
Processes and Threads
By default, each process contains one main thread of executionAdditional threads can be spawned within a process (pThreads)All threads within a process share global variables
Threads scheduled individually by priority – regardless of which process they reside withinNo thread isolation – a rogue pointer will probably bring down all threads in that process.
Process A Process B
Process A global vars
A1 M
ain w
/ loca
l var
s
A2 p
Thre
adw/
loca
l var
s
A3 p
Thre
adw/
loca
l var
s
B1 M
ain w
/ loca
l var
s
Process B global vars
Process Pipes
Threads vs Processes
Processes ThreadsMemory protectionEase of useStart-up cyclesContext switchShared globals no yesScheduled entity no yesEnvironment program function
Linux Threads
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 7
pThread Functions – Create & Exit
pthread_create(&video_thread, null, video_thread_fxn, …)
pthread_exit (NULL)
main
video_thread
What if there's nothing for main() to do?
#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);
pthread_create (&new,…)
pthread_exit (retval)
main blocked
new
Re-Joining Main
pthread_join (new)
pthread_create(&video_thread, null, video_thread_fxn, …)
pthread_exit (retval)
main
video_thread
Linux Threads
07 - 8 Introduction to Embedded Linux - Module 07: Linux Scheduler
Thread Synchronization
Thread Synchronization (Polling)void *threadA(void *env){int test;while(1){
while(test != TRUE) {test = (volatile int) env->driverComplete;
}doSomething(env->bufferPtr);
}}
Thread A’s doSomething( ) function should only run after the driver completes reading in a new bufferPolling 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.
Polling(spin loop)
Thread Synchronization (Polling)
Start pollingfor devComplete
devComplete = TRUE
thread A(higher priority)
driver
Process data
Wasted cycles whilethread A does nothing!(and thread B starves)
Process data
devComplete = TRUE
thread B
Linux Threads
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 9
Thread Synchronization (Blocking)
void *threadA(void *env){while(1){
read(env->audioFd, env->bufferPtr, env->bufsize); doSomethingNext(env->bufferPtr);
}
Instead of polling on a flag, the thread blocks execution as a result of the driver’s read call
More efficient than polling because thread A doesn’t waste cycles waiting on the driver to fill the buffer
Blocking(waits till
complete)
Thread Synchronization (Blocking)
Driver “read” call
devComplete = TRUE
thread A(higher priority)
driver
Process dataProcess data
devComplete = TRUE
(blocked)
Semaphores are used to block a thread’s execution until occurrence of an event or freeing of a resourceMuch more efficient system
thread B
Thread blocks until driver fills buffer.No wasted cycles!
(thread B gets to fill time)
Linux Threads
07 - 10 Introduction to Embedded Linux - Module 07: Linux Scheduler
Semaphores
#include <semaphore.h>void *threadA(void *env){sem_t mySem;sem_init(&mySem, 1, 0); // initial value of zerowhile(1){
sem_wait(&mySem);doSomethingNext(env->bufferPtr);
}}
A semaphore is the underlying mechanism of the read call that causes it to block
Blocking(waits till
complete)
Thread Synchronization (Semaphore)
sem_wait(…)
sem_post(…)
thread A(higher priority)
driver
Process dataProcess data
sem_post(…)
(blocked)
Semaphores are used to block a thread’s execution until occurrence of an event or freeing of a resourceMuch more efficient system
thread B
Thread blocks until driver fills buffer.No wasted cycles!
(thread B gets to fill time)
Linux Threads
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 11
Using Real-Time Threads
Time-Sliced A/V Application, >100% loadAudio 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 processingNiceness values may be reconfigured, but system unpredictability will often cause future problemsIn 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
All threads suffer, but not equally:Audio thread real-time failure is highly perceptibleVideo thread failure is slightly perceptibleControl 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
Audio Thread Audio thread completes 80% of samples
Video Thread Video thread drops 6 of 30 frames
Control Thread User response delayed 1mS
Linux Threads
07 - 12 Introduction to Embedded Linux - Module 07: Linux Scheduler
Real-time A/V Application, >100% load
Audio thread is guaranteed the bandwidth it needsVideo thread takes the restControl thread never runs!
Audio Thread(priority 99)
Video Thread(priority 98)
Control Thread(priority 70)
Time-Sliced A/V Application Analysis
Still a problem:Audio thread completes as desiredVideo thread failure is practically inperceptibleControl thread never runs – User input is locked out
Audio Thread Audio thread completes, no distortion
Video Thread Video thread drops 1 of 30 frames
Control Thread No user response
Linux Threads
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 13
Hybrid A/V Application, >100% load
Audio thread is guaranteed the bandwidth it needsVideo thread takes most of remaining bandwidthControl thread gets a small portion of remaining bandwidth
Audio Thread(priority 99)
Video Thread(pri 0, nice -5)
Control Thread(pri 0, nice +5)
Hybrid A/V Application Analysis
A good compromise:Audio thread completes as desiredVideo thread failure is barely perceptibleControl thread delayed response is acceptibleBottom Line: We have designed the system so that it
degrades gracefully
Video Thread Video thread drops 2 of 30 frames
Control Thread User response delayed 100ms
Audio Thread Audio thread completes, no distortion
Linux Threads
07 - 14 Introduction to Embedded Linux - Module 07: Linux Scheduler
Default Thread Scheduling
pThread attributes: NULL / default value:
stacksize PTHREAD_STACK_MIN… …
detachedstate PTHREAD_CREATE_JOINABLEschedpolicy SCHED_OTHER (time slicing)inheritsched PTHREAD_INHERIT_SCHEDschedparam.sched_priority 0
#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_create()
pthread_create: Creates a new thread and makes it executable. It can be called anynumber 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.
pthread_create (&thread, attr, start_routine, arg)
Linux Threads
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 15
Scheduling Policy OptionsSCHED_OTHER SCHED_RR SCHED_FIFO
Sched Method Time Slicing Real-Time (RT)RT priority 0 1 to 99 1 to 99
Min niceness +20 n/a n/a
Max niceness -20 n/a n/a
Scope root or user root 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 threadsRT threads scheduled at the same priority are defined by their policy:
SCHED_FIFO: When it begins running, it will continue until it blocksSCHED_RR: "Round-Robin" will share with other threads at it’s
priority based on a deterministic time quantum
Real-time Thread Creation Procedure// Initialize the pthread_attr_t structure audioThreadAttrspthread_attr_init(&audioThreadAttrs);
// Set the inheritance value in audioThreadAttrs structurepthread_attr_setinheritsched(&audioThreadAttrs,
PTHREAD_EXPLICIT_SCHED);
// Set the scheduling policy for audioThreadAttrs structurepthread_attr_setschedpolicy(&audioThreadAttrs, SCHED_RR);
// Set the scheduler priority via audioThreadParams structaudioThreadParams.sched_priority = 99;pthread_attr_setschedparam(&audioThreadAttrs,
&audioThreadParams);
// Create the new thread using thread attributespthread_create(&audioThread, &audioThreadAttrs,
audio_thread_fxn, (void *) &audio_env);
Create attribute structure
Set attribute to real-time priority 99
Create thread with given attributes
Linux Threads
07 - 16 Introduction to Embedded Linux - Module 07: Linux Scheduler
Linking the pthread Librarypthread stands for POSIX threadPOSIX 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 don’t completely adhere to it.
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.
# gcc –D_REENTRANT myProg.c –o myprog.o –lpthread
#include <pthread.h>#include C compiler pre-processor statementpthread.h Function declarations for the posix thread library
Lab 7: Linux Scheduler
Introduction to Embedded Linux - Module 07: Linux Scheduler 07 - 17
Lab 7: Linux Scheduler
Lab 7: Linux Scheduler
A. Creating a POSIX threadB. Using Realtime threadsC. Using Semaphores
solution_Astart
lab07_git
solutionsmaster
HEAD
solution_C
solution_B
Lab 7A: Timeslice Thread
A. Creating a POSIX threadB. Using Realtime threadsC. Using Semaphores
Linux scheduler shares CPU between timesliced threads, so each thread gets a turn to run.
Lab 7: Linux Scheduler
07 - 18 Introduction to Embedded Linux - Module 07: Linux Scheduler
Lab 7B: Realtime Thread
A. Creating a POSIX threadB. Using Realtime threadsC. 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 threadB. Using Realtime threadsC. Using Semaphores
while(1){
sem_wait();
…
sem_post();
}
while(1){
sem_wait();
…
sem_post();
}
thread1 thread2
Introduction to Embedded Linux - Module 08: Networking 08 - 1
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.
Module Topics
08 - 2 Introduction to Embedded Linux - Module 08: Networking
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
Ethernet Basics
Introduction to Embedded Linux - Module 08: Networking 08 - 3
Ethernet Basics
Networking References
FF.FF.FF.FF.FF.FF
255.255.255.255
Media Access Controller address is unique to a physical device
www.ti.com
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 addressesDomain Name Service (DNS) resolves IP addresses from host and domain name
Sub-networks
FF.FF.FF.FF.FF.FF
255.255.255.255
2^48 MAC Addresses>>
2^32 IP Addresses
WAN
LAN
WAN = Wide Area Network“the cloud.” WAN addresses are unique (but may be dynamic)
LAN = Local Area Network (subnet.)IP addresses are not unique
Ethernet Basics
08 - 4 Introduction to Embedded Linux - Module 08: Networking
Sub-networks
WAN
LAN
If <Dest> & Netmask = <Source> & Netmask thensource and destination are on the same subnet.
Else, destination packet is forwarded to the WAN.
Sub-networks are formed using a netmask
255.255.255.255
Sub-network Example
203.114.28.8192.168.1.1
192.168.1.7 192.168.1.3192.168.1.5
WAN
LAN
Computer A sends a packet to IP address 192.168.1.7Computer A (192.168.1.5) & 255.255.255.0 = 192.168.1.0Destination & 255.255.255.0 = 192.168.1.0
This is a transmission within the subnet, packet is sent directly to destination.
netmask255.255.255.0
A B C
D
Ethernet Basics
Introduction to Embedded Linux - Module 08: Networking 08 - 5
Sub-network Example
203.114.28.8192.168.1.1
192.168.1.7 192.168.1.3192.168.1.5
WAN
LAN
Computer A sends a packet to IP address 116.97.23.47Computer A (192.168.1.5) & 255.255.255.0 = 192.168.1.0Destination & 255.255.255.0 = 116.97.23.0
Packet is forwarded to the Gateway to be sent to the wide area network.
netmask255.255.255.0
A B C
D (Gateway)
Server/Client Protocols
08 - 6 Introduction to Embedded Linux - Module 08: Networking
Server/Client Protocols
IP PortsService Portecho 7ftp 20/21ssh 22telnet 23nameserver 42http 80
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.
Client/Server modelServer is a static background (daemon)
process, usually initiated at startup, that listens for requests from one or more clients.
Network Address Translation
203.114.28.8:1000
:1002 :1003:1001
WAN
LAN
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
A B C
D (Gateway)
Server/Client Protocols
Introduction to Embedded Linux - Module 08: Networking 08 - 7
Dynamic Host Configuration Protocol (DHCP)
DHCP server issues IP address, netmask, gateway, dns to DHCP clients.
Server installation (Ubuntu)# apt-get install dhcp3-serverServer configuration file/etc/dhcp3/dhcpd.conf
Domain Name ServiceDomains and subdomains are not required to correlate to subnetwork boundaries (although they often do.)
Server installation (Ubuntu)# apt-get install bind9Configuration files/etc/named.conf/var/bind/*.zone
Server/Client Protocols
08 - 8 Introduction to Embedded Linux - Module 08: Networking
inetd/xinetduser@ubuntu:~$ ls /etc/xinetd.dchargen daytime discard echo tftp time
service tftp{protocol = udpport = 69socket_type = dgramwait = yesuser = nobodyserver = /usr/sbin/in.tftpdserver_args = /tftpbootdisable = 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.)
Berkeley Sockets
Introduction to Embedded Linux - Module 08: Networking 08 - 9
Berkeley Sockets
Berkeley Sockets Basic Procedure
sFD = socket(…);
connect(sFD, addr, …);// do reads and writesshutdown(sFD,…);close(sFD);
sFD = socket(…);bind(sFD, addr, …);listen(sFD, …);while(1){
cFD = accept(sFD,…);// do reads and writesshutdown(cFD,…);close(cFD);
}Client Server
Socket Types
sFD = socket(AF_UNIX, SOCK_STREAM, 0);Local Socket
sFD = socket(AF_INET, SOCK_STREAM, 0);TCP/IP Socket
sFD = socket(AF_INET, SOCK_DGRAM, 0);UDP/IP Socket
Final parameter to socket function is protocol. Protocol is typically determined completely by first two parameters, so that “0” (default) is usually passed.
Berkeley Sockets
08 - 10 Introduction to Embedded Linux - Module 08: Networking
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);
connect(SocketFD, (struct sockaddr *)&stSockAddr,sizeof(stSockAddr));
Client
bind(SocketFD,(struct sockaddr *)&stSockAddr,sizeof(stSockAddr))
Server
Server Detailslisten(int sFD, int backlog);
listen creates an incoming connection queuesocketFD is the file descriptorbacklog 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_RDWRpossible to call with SHUT_RD followed by SHUT_WRshutdown 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.
Lab 8: Berkeley Sockets
Introduction to Embedded Linux - Module 08: Networking 08 - 11
Lab 8: Berkeley Sockets
Lab 8: Berkeley SocketsA. Network Configuration FilesB. Berkeley Socket ClientC. Build and Launch Host ServerD. Server Application
solution_Astart
lab08_git
solutionsmaster
solution_Astart
lab08_x86_server
solutionsmaster
Lab 8: Berkeley Sockets
08 - 12 Introduction to Embedded Linux - Module 08: Networking
(Page intentionally left blank)
Introduction to Embedded Linux - Module 09: Video and Graphics Drivers 09 - 1
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.
Module Topics
09 - 2 Introduction to Embedded Linux - Module 09: Video and Graphics Drivers
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
Module Topics
Introduction to Embedded Linux - Module 09: Video and Graphics Drivers 09 - 3
Linux v4L2 Video Driver v4l2 Driver Overview
v4l2 is a standard Linux video driver used in many linux systemsSupports video input and output
In this workshop we use it for video input only
Device node Node name: /dev/video0Uses major number 81
v4l2 spec: http://bytesex.org/v4lDriver source location:…/lsp/ti-davinci/drivers/media/davinci_vpfe.c
v4l2 Driver Queue Structureincoming (empty) queue
outgoing (full) queue
v4l2
driv
erow
ns b
uffe
r
appl
icat
ion
owns
buf
fer
Application takes ownership of a full video buffer from the outgoing driver queue using the VIDIOC_DQBUF ioctlAfter using the buffer, application returns ownership of the buffer to the driver by using VIDIOC_QBUF ioctl to place it on the incoming queue
Module Topics
09 - 4 Introduction to Embedded Linux - Module 09: Video and Graphics Drivers
v4l2 Enqueue and Dequeue
App
DQ
OQ
IQv4l2 driver
Buffers typically exist in driver’s memory spaceThe dequeue call makes the data available to the app
v4l2 Enqueue and Dequeue
App
DQ
OQ
IQ
(empty)
v4l2 driver
Buffers typically exist in driver’s memory spaceThe dequeue call makes the buffer available to the app Even after DQ, buffers still exist in the driver’s memory space but not the application’s
1234…
Module Topics
Introduction to Embedded Linux - Module 09: Video and Graphics Drivers 09 - 5
v4l2 Enqueue and Dequeue
1234…
Appread1234…OQ
IQ
(empty)
v4l2 driver
Buffers typically exist in driver’s memory spaceThe dequeue call makes the buffer available to the app Even after DQ, buffers still exist in the driver’s memory space but not the application’s
read and write operations copy buffers from driver’s memory space to app’s or vice-versa
v4l2 Enqueue and Dequeue
1234…
App
OQ
IQ
(empty)
EQv4l2 driver
Buffers typically exist in driver’s memory spaceThese buffers exist in the driver’s memory space but not the application’s read and write operations copy buffers from driver’s memory space to app’s or vice-versa
Is there a better method than "read"?
1234…
Module Topics
09 - 6 Introduction to Embedded Linux - Module 09: Video and Graphics Drivers
Using mmap
mmap – A Better Way
1234…
IQ
App
AppdriverStandard read and write copy data from driver buffer to a new buffer in application process’s memory space
Use mmap to expand the application process’s memory space to include the driver bufferReturns a pointer to the location in the app’s memory space
read
1234…
1234…
(mmap)
OQ
IQ
OQ
DQ
EQ
driverEQ
1234…
DQ
v4l2 Queue Synchronization
App
DQ
OQ
IQ
X
XDriver fills IQ bufand places on OQ
v4l2 driver
The VIDIOC_DQBUF ioctl blocks the thread’s execution waits if until a buffer is available on the output queueWhen driver adds a new, full buffer to the output queue, the application process is releasedDequeue call completes and application resumes with the following set of commands
(empty)
Module Topics
Introduction to Embedded Linux - Module 09: Video and Graphics Drivers 09 - 7
v4l2 Queue Synchronization
App
DQ
OQ
IQ
X
XDriver fills IQ bufand places on OQ
v4l2 driver
The VIDIOC_DQBUF ioctl blocks the thread’s execution waits if until a buffer is available on the output queueWhen driver adds a new, full buffer to the output queue, the application process is releasedDequeue call completes and application resumes with the following set of commands
v4l2 Queue Synchronization
App
DQ
OQ
IQv4l2 driver
The VIDIOC_DQBUF ioctl blocks the thread’s execution waits if until a buffer is available on the output queueWhen driver adds a new, full buffer to the output queue, the application process is releasedDequeue call completes and application resumes with the following set of commands
Module Topics
09 - 8 Introduction to Embedded Linux - Module 09: Video and Graphics Drivers
v4l2 Synchronization
App
OQ
IQ
(empty)
v4l2 driver5678…
5678…
DQ
The VIDIOC_DQBUF ioctl blocks the thread’s execution waits if until a buffer is available on the output queueWhen driver adds a new, full buffer to the output queue, the application process is releasedDequeue call completes and application resumes with the following set of commands
(Optional) v4L2 Coding
Commonly Used v4l2 ioctl’sData Structures
struct v4l2_requestbuffers req;req.count; // how many buffers to requestreq.type; // capture, output, overlayreq.memory; // mmap, userptr, overlay
struct v4l2_buffer buf;buf.index; // which driver bufferbuf.type; // matches req.typebuf.memory; // matches req.memorybuf.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);
Module Topics
Introduction to Embedded Linux - Module 09: Video and Graphics Drivers 09 - 9
v4l2 Buffer Passing Procedure
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 driver’s queueMore efficient code would map each driver buffer once during initialization, instead of mapping and unmapping within the loopAlternatively, later versions of the driver allow you to create the buffer in ‘user’ space and pass it to the driver
while(cond){ioctl(v4l2_input_fd, VIDIOC_DQBUF, &buf); bufPtr = mmap(NULL, // “start” address (ususally 0)
buf.length, // lengthPROT_READ | PROT_WRITE, // allowed use for map’d memoryMAP_SHARED, // allow sharing of mapped bufsv4l2_input_fd, // driver/file descriptorbuf.m.offset); // offset requested from “start”
doSomething(bufPtr, buf.length, ...);munmap(bufPtr, buf.length);ioctl(v4l2_input_fd, VIDIOC_QBUF, &buf);
}
Module Topics
09 - 10 Introduction to Embedded Linux - Module 09: Video and Graphics Drivers
Linux FBdev Display Driver FBdev Driver Overview
FBdev is a standard Linux video output driver used in many linux systemsCan be used to map the frame buffer of a display device into user spaceDevice nodes have major number 29Device nodes have a minor number x Uses /dev/fb/x node naming convention
Multiple Video/OSD Windows
Source: DirectFBOverview.pdf
Module Topics
Introduction to Embedded Linux - Module 09: Video and Graphics Drivers 09 - 11
Allows Pixel by Pixel Blending of OSD and Video WindowsUses an 8-bit, Attribute (Alpha Blending) Value
FF 0020406080A0D0
32-bit Color Format
8-bit Attribute
8-bit Red
8-bit Green
8-bit Blue
8-bit blending0x00: 00.0%, 100% Video0x20: 12.5%, 87.5% Video0x40: 25.0%, 75.0% Video
…0xA0: 75.0%, 25.0% Video0xFF: 100%, 00.0% Video
32-bit ARGB Pixel Value
For Each /dev/fb/x Video Plane
Named FBdev because it gives direct access to the display device’s frame bufferFBIOPAN_DISPLAY allows users to pan the active display region within a virtual display buffer
yoffset
xoffset
xres
yres
xres_virtual
yres_virtual
Module Topics
09 - 12 Introduction to Embedded Linux - Module 09: Video and Graphics Drivers
Ping-pong Buffers with FBdev
FBdev has no video buffer queue (provides direct access to the display device’s frame buffer)Use FBIOPAN_DISPLAY to switch between 2 or more buffers in the virtual buffer spaceUse FBIO_WAITFORVSYNC to block process until current buffer scan completes, then switch.
xres_virtual
yres_virtual
buffer0 (ping)
buffer1(pong)
offset = (0,0)
offset = (yres,0)
In our case...
Ping-pong Buffers with FBdev
FBdev has no video buffer queue (provides direct access to the display device’s frame buffer)Use FBIOPAN_DISPLAY to switch between 2 or more buffers in the virtual buffer spaceUse FBIO_WAITFORVSYNC to block process until current buffer scan completes, then switch.
xres_virtual
yres_virtual
buffer0 (ping)
buffer1(pong)
offset = (0,0)
offset = (yres,0)
Module Topics
Introduction to Embedded Linux - Module 09: Video and Graphics Drivers 09 - 13
Buffer SynchronizationpVirtualBuf = mmap(NULL,display_size * NUM_BUFS,
PROT_READ | PROT_WRITE,MAP_SHARED,FbdevFd, 0);
while(cond){// map next frame from virtual bufferdisplay_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 frameioctl(pFbdevFd, FBIOPAN_DISPLAY, &vinfo);
// wait for current frame to completeioctl(pFbdevFd, FBIO_WAITFORVSYNC, NULL);
}
yresbuffer 0 (ping)
xres
buffer 1 (pong)
Blocking on select()
Reasons to use select():Can block on multiple eventsAllows specification of a timeout value for blocking
int wait_for_frame(int fd) {struct timeval tv; // timeout valuefd_set fds; // set of file descriptors to wait on
FD_ZERO(&fds); // using a file descriptor set of only one FD_SET(fd, &fds); // value – passed in as function parameter
tv.tv_sec = 2; // timeout after 2 seconds if no new frame
// Use select to wait for next filled frameret = select(fd + 1, // largest file descr value to test
&fds, // set of fd’s to wait on “read”NULL, NULL, // fd’s to wait on write or error&tv); // timeout value
… }
Module Topics
09 - 14 Introduction to Embedded Linux - Module 09: Video and Graphics Drivers
Commonly Used FBdev ioctlData Structures
struct fb_fix_screeninfo myFixScreenInfo;myFixScreenInfo.smem_len; // length of framebuffer
struct fb_var_screeninfo myVarScreenInfo;myVarScreenInfo.xres; // visible pic resolutionmyVarScreenInfo.xres_virtual; // virtual pic resolutionmyVarScreenInfo.xoffset; // from virtual to vis
Get or put variable screen informationioctl(fd, FBIOGET_VSCREENINFO, &myVarScreenInfo);ioctl(fd, FBIOPUT_VSCREENINFO, &myVarScreenInfo);
Get fixed screen informationioctl(fd, FBIOGET_FSCREENINFO, &myFixScreenInfo);
We use Pan to switch output buffersioctl(fd, FBIOPAN_DISPLAY, &myVarScreenInfo);
After writing buffer and pan_display, wait for current to finishioctl(fd, FBIO_WAITFORVSYNC, NULL); // arg 3 is not used
Introduction to Embedded Linux - Module 10: Qtopia GUI Development 10 - 1
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. .
Module Topics
10 - 2 Introduction to Embedded Linux - Module 10: Qtopia GUI Development
Module Topics Module 10: Qtopia GUI Development .................................................................................................... 10-1
Module Topics ........................................................................................................................................ 10-2
Graphics Software Layers ...................................................................................................................... 10-3
Qtopia .................................................................................................................................................... 10-6
Graphics Software Layers
Introduction to Embedded Linux - Module 10: Qtopia GUI Development 10 - 3
Graphics Software Layers Terminal vs. Desktop
A terminal is a text-based interface to Linux O/SCommands 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 displayMost 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 managersDesktop 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 ManagerGnome display manager is “just another client” to x11A display manager isn’t required to run Linuxx11 isn’t required to run Linux, though it is required by many graphical applications
Graphics Software Layers
10 - 4 Introduction to Embedded Linux - Module 10: Qtopia GUI Development
x11 Without Desktop
Session Manager XSM(x11 session manager)
Display Manager XDM(x11 Display Manager)
Window Manager x11 window manager
Display Server X server
Driver LinuxFBDEV framebuffer driver
Device AM335x
Gnome Desktop Environment
Desktop Environment
Session Manager
Display Manager
Window Manager x11 window manager
Display Server X server
Driver LinuxFBDEV framebuffer driver
Device AM335x
GDM(Gnome Display Manager)
Gnome Session Manager
Gnome Desktop
KDE ... as a quick comparison
Graphics Software Layers
Introduction to Embedded Linux - Module 10: Qtopia GUI Development 10 - 5
Gnome Desktop EnvironmentDesktop 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 EnvironmentKDE
(K Desktop Environment)KDE
(K Desktop Environment)
ksmserver(session mgr)
ksmserver(session mgr)
KDM(KDE Display manager)
KDM(KDE Display manager)
kwm(K window mgr)
kwm(K window mgr)
QT embedded (QT / e) QT over x11 (QT / x11)
(No Display Server, direct framebufferaccess via widget lib) X server
Linux FBDEV Framebuffer Driver
Linux FBDEV Framebuffer Driver
AM335x AM335x
Qtopia
10 - 6 Introduction to Embedded Linux - Module 10: Qtopia GUI Development
Qtopia
» Qt is cross-platform application and UI
framework.
» Qt provides a well defined API that can make
development quick and easy.
» 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
» Multithreading support
» Network connectivity» Advanced GUI development
Qt SDK
Qt development toolsQt modular class library
GUIWebKit
Graphics ViewOpenGL
Multimedia
Core
XMLScriptingDatabaseNetwork UI Tests
BenchmarkingFont Engine
Cross-platform support
Qt Designer
Forms Builder
qmakeCross-Platform
Build Tool
Qt Linguist
I18N Tools
Qt Assistant
Help reader
Qt CreatorCross-platform IDE
Linux/X11
Embedded Linux
Windows CEWindows
QT Framework
9
Example Qtopia Apps and UIs
Qtopia
Introduction to Embedded Linux - Module 10: Qtopia GUI Development 10 - 7
Sitara Linux Stack
Matrix Application Launcher
Qt Embedded
QWidgetQGLWidget
OpenGL ES
ARM Benchmarks
Power Manager
Web Browser
System Information
Sitara ARM Processor
Target Board
FBDEV
DSS2
McSPI Touchscreen EthernetV4L2 ALSA VISA
UARTI2C USB McBSP MMC
3D Graphics
Gstreamer/FFMPEG
MPEG4, H.264, MPEG2, AAC, …
Wifi BlueZ
USB Profiler WLAN GUI
“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();}
Qtopia
10 - 8 Introduction to Embedded Linux - Module 10: Qtopia GUI Development
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
Qtopia
Introduction to Embedded Linux - Module 10: Qtopia GUI Development 10 - 9
QT Creator – Drag and Drop Widgets (Forms)
QT Creator – Forms Stored via XML
The UI created on the previous slide is stored as .xmlQT Creator then generates the UI from this .xml file
Qtopia
10 - 10 Introduction to Embedded Linux - Module 10: Qtopia GUI Development
QT Creator – C++ Objects
Alternately, users may program using C++ object classes for each widget
WidgetsQt UI framework is based on widgetsWidgets respond to UI events (key presses/mouse movements), and update their screen areaEach widget has a parent, that affects its behavior, and is embedded into itMost Qt classes are derived from QWidgetRefer to online documentation at
http://doc.qt.nokia.com/4.6/qwidget.htmlTip – Documentation is arranged using class names.
Qtopia
Introduction to Embedded Linux - Module 10: Qtopia GUI Development 10 - 11
QWTPlotCurve QHBoxLayout QComboBoxQDoubleSpinBox
QPushButton QlabelQMainWindow QMessageBox
QSl ider
Widgets
Signals & SlotsSignals & 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.
SignalsEvents occur and cause a signal
Widgets contain a list of predefined signals, but you can subclass a widget to add your own signalExample – 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
Qtopia
10 - 12 Introduction to Embedded Linux - Module 10: Qtopia GUI Development
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.
Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot 11 - 1
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.
Module Topics
11 - 2 Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot
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
Acquiring Timing Information
Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot 11 - 3
Acquiring Timing Information
Method 1: Timestamp printk
Pros: Timestamped at message generation
Cons: Potentially requires kernel rebuild (but default for TI SDK)
Only timestamps kernel messagesRequires printk, which adds to boot time!
$ make ARCH=arm menuconfigKernel hackingShow timing information on printks
Timestamped printk ExampleU-Boot SPL 2011.09 (Jul 26 2012 - 17:18:20)Texas Instruments Revision detection unimplementedNo daughter card presentOMAP SD/MMC: 0reading 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 : 0x4dd074udhcpc (v1.13.2) startedSending discover...
Timer starts when kernel begins booting
SPL/U-boot not profiled
Significant portion of kernel boot instrumented
init (rcX.d) scripts not instrumented
Acquiring Timing Information
11 - 4 Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot
Method 2: Timestamp Serial Messages
Pros: Allows profiling of SBL/U-bootAllows benchmarking without printk overhead
Cons: Timestamps suffer serial buffering jitter
6
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_debugsaveenv
– 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 enableddmesg | grep initcall | sort -k8 -n
• If CONFIG_PRINTK_TIME is not enableddmesg | 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)
• Timing for certain kernel and process events– Oprofile
• System wide profiler– Bootchart
• Visualizes boot process
Kernel Boot Time Improvements
Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot 11 - 5
Kernel Boot Time Improvements
Step 1: Remove Unneeded Init ScriptsThe initialization process is launched by the Linux Kernel after the root filesystem is mountedBy default it is located at /sbin/init, but it can be specified as a kernel boot argument
/etc/inittab /etc/init.d
/etc/rcX.d
bootmisc.sh syslog
mountnfs.sh telnetd
networking thttpd
S05networking S20syslog
S10telnetd S20thttpd
S20syslog S60mountnfs
/sbin/init
Step 2: Remove Unneeded Kernel Modules
# insmod <mod_name>.ko [mod_properties]
Use insmod (short for insert module) command to dynamically add modules into the kernelKeep statically built kernel small (to reduce size or boot-up time), then add functionality later with insmodInsmod is also handy when developing kernel modules
Linux Kernel source code is broken into individual modulesOnly those parts of the kernel that are needed are built in
Kernel Module Examples:fbdev frame buffer devv4l2 video for linux 2nfsd network file server devdsp oss digital sound proc.audio alsa audio driver
1. Static(built-in)
2. Dynamic(insmod)
.ko = kernel object
Linux Kernel
v4l2
fbdev
dsp
oss
nfsd ext3
httpd
Kernel Boot Time Improvements
11 - 6 Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot
Kernel Build
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
MLO (x-loader) U-Boot Kernel
ROM Internal RAM DDR2 DDR2
* For available ARCH: host$ ls arch/** For available configs: host$ ls arch/arm/configs
RBL
Default Configurations
ubuntu$ make ARCH=arm am335x_evm_defconfig
ubuntu$ ls arch/arm/configsacs5k_defconfig fortunet_defconfig omap2plus_defconfigacs5k_tiny_defconfig g3evm_defconfig orion5x_defconfigafeb9260_defconfig g4evm_defconfig palmz72_defconfigag5evm_defconfig h3600_defconfig pcm027_defconfigam200epdkit_defconfig h5000_defconfig pcontrol_g20_defconfigam335x_evm_defconfig h7201_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.
Kernel Boot Time Improvements
Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot 11 - 7
Custom Configuration
Step 1: Start with an existing default configuration ubuntu$ make ARCH=arm am335x_evm_defconfig
Step 2: Modify the configurationubuntu$ make ARCH=arm menuconfig
Step 3: Save as a new default configurationubuntu$ 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
Kernel Boot Time Improvements
11 - 8 Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot
Other Boot OptimizationsChange Kernel Compile Flags Reduce filesystem sizeUse faster media to store kernel and filesystem
MMC/SD NAND FlashDefer module init calls
It is possibly to defer module init calls without having to build the modules dynamically. This requires kernel rebuildOnce the system booted the deferred calls can be executed by doing:
echo 1 > /proc/deferred_initcallsAdditional details at http://elinux.org/Deferred_Initcalls
Kernel Board Port
Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot 11 - 9
Kernel Board Port
16
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.
17
Machine and Platform Files
17
arch/arm/mach-omap2/Makefile:
obj-$(CONFIG_MACH_AM335XEVM) += board-am335xevm.o
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.
arch/arm/Makefile:
machine-$(CONFIG_ARCH_OMAP3) := omap2plat-$(CONFIG_ARCH_OMAP) := omap…machdirs := $(patsubst %,arch/arm/mach-%/,$(machine-y))platdirs := $(patsubst %,arch/arm/plat-%/,$(plat-y))
arch/arm/plat-omap/Makefile:
obj-$(CONFIG_ARCH_OMAP3) += omap_device.o
Board
Kernel Board Port
11 - 10 Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot
Machine and Platform DefinitionUbuntu$ more arch/arm/configs/am335x_evm_defconfig…CONFIG_ARCH_OMAP=y…CONFIG_ARCH_OMAP2PLUS=y…CONFIG_MACH_OMAP_GENERIC=y…CONFIG_ARCH_OMAP2PLUS_TYPICAL=y…CONFIG_ARCH_OMAP3=y…CONFIG_SOC_OMAPTI81XX=y…CONFIG_SOC_OMAPAM33XX=y…CONFIG_MACH_OMAP3_BEAGLE=y…CONFIG_MACH_TI8168EVM=yCONFIG_MACH_TI8148EVM=yCONFIG_MACH_AM335XEVM=yCONFIG_MACH_AM335XIAEVM=y
Platform
Machine,Device
Board
19
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.
Kernel Board Port
Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot 11 - 11
20
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.
21
Board Porting
21
Much of the board-specific configuration of the Linux kernel is handled by the Machine and Platform files.
Machine = Board SpecificPlatform = Device Specific
So generally you will want to define a new Machine for a new board, but don’t 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)
Kernel Board Port
11 - 12 Introduction to Embedded Linux - Customizing Linux Kernel for Fast Boot
Platform-Specific Driver SwitchesFor instance, searching on “CONFIG_ARCH_OMAP” locates (partial list:)
./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 TI-specific driver file. Sometimes there is simply a #define switch in a generic driver file.
ubuntu$ grep -R CONFIG_ARCH_OMAP .
Introduction to Embedded Linux - Optimizing and Customizing U-boot 12 - 1
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.
Module Topics
12 - 2 Introduction to Embedded Linux - Optimizing and Customizing U-boot
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
Kernel Boot Option Improvements
Introduction to Embedded Linux - Optimizing and Customizing U-boot 12 - 3
Kernel Boot Option Improvements
3
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 don’t 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
4
Reduce Linux Boot – Bootargs (2)
• Almost a second is spent verifying the kernel image checksum.– If your system doesn’t 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 promptu-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
Initial Ram Disk
12 - 4 Introduction to Embedded Linux - Optimizing and Customizing U-boot
Initial Ram Disk
6
Common Filesystems and Media
6
Media FilesystemMMC/SD EXT3 / EXT4 / FATHarddrive EXT3 / EXT4 / FATNAND / NOR Flash UBIFS / JFFS2 / YAFFSNetwork NFS / SMBFSDDR 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
7
INITRD Support Must be Enabled in Kernel
7
# # 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
<Kernel>/.config
Note: In addition to enabling initrd support, the blocksize and count must be configured to match the Ramdisk image.
Initial Ram Disk
Introduction to Embedded Linux - Optimizing and Customizing U-boot 12 - 5
8
Creating a Ramdisk Image
8
# Ramdisk ConstantsRDSIZE=4000BLKSIZE=1024
# Create an empty ramdisk imagesudo dd if=/dev/zero of=/tmp/ramdisk.img bs=$BLKSIZE count=$RDSIZE
# Make it an ext2 mountable file systemsudo /sbin/mke2fs -F -m 0 -b $BLKSIZE /tmp/ramdisk.img $RDSIZE
# Mount it so that we can populatesudo mount /tmp/ramdisk.img /mnt/initrd -t ext2 -o loop=/dev/loop0
### Fill image with filesystem ###
# Finish up...sudo umount /mnt/initrdsudo gzip -9 /tmp/ramdisk.imgsudo cp /tmp/ramdisk.img.gz .
9
Ramdisk Boot Arguments
9
uEnv.txtbootargs=MEM=124M console=ttyO0,115200n8 root=/dev/ram0 rwrootfstype=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}
MLOu-boot.imguImageuEnv.txtramdisk.img.gz
MMCPartition 1
MEM=124 M128M – 4M Ramdisk
initrd=0x87c00000,4M0x87c00000 = start of DDR3
+ 124M offset,4M = length of initrd
U-boot Rebuild
12 - 6 Introduction to Embedded Linux - Optimizing and Customizing U-boot
U-boot Rebuild
MLO (U-boot_min) Build
host $ cd ti-sdk-am335x-evm-xxx/board_support/u-boot-xxx
host $ make distcleanhost $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- am335x_evm_config
host $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- MLO
MLO (x-loader) U-Boot Kernel
ROM Internal RAM DDR2 DDR2
RBL
host$ make ARCH=<ARCH> CROSS_COMPILE=… <target>_config
<ARCH> and <Target> as defined in “boards.cfg”
U-Boot Build
host $ cd ti-sdk-am335x-evm-xxx/board_support/u-boot-xxx
host $ make distcleanhost $ 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
MLO (x-loader) U-Boot Kernel
ROM Internal RAM DDR2 DDR2
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 distcleanhost $ make ARCH=arm CROSS_COMPILE=arm-arago-linux-gnueabi- am335x_evm
RBL
host$ make ARCH=<ARCH> CROSS_COMPILE=… <target>
<ARCH> and <Target> as defined in “boards.cfg”
U-boot Rebuild
Introduction to Embedded Linux - Optimizing and Customizing U-boot 12 - 7
13
Translating Target into Source Directories
# Target ARCH CPU Board name Vendor SoC
##########################################################
davinci_dm355evm arm arm926ejs dm355evm davinci davinci
davinci_dm365evm arm arm926ejs dm365evm davinci davinci
davinci_dm6467evm arm arm926ejs dm6467evm davinci davinci
am3517_evm arm armv7 am3517evm logicpd omap3
am335x_evm arm armv7 am335x ti ti81xx
…
13
<U-boot>/boards.cfg
14
U-Boot Sources board/<Vendor>/<Board name>
arch/<ARCH>/include/asm/arch-<SoC>
include/configs/<Target>.h
<Vendor><Board><ARCH><SoC><Target>As definedIn “boards.cfg”
U-boot Rebuild
12 - 8 Introduction to Embedded Linux - Optimizing and Customizing U-boot
15
Configuration File Options – Boot Time
• 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
host$ gedit include/configs/<target>.h
16
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 pre-processor 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