embedded linux system development ... - dsi.fceia.unr.edu.ar · nacimiento del software libre i...

263
Embedded Linux system development Embedded Linux system development Free Electrons Copyright 2004-2018, Free Electrons. Creative Commons BY-SA 3.0 license. Latest update: March 14, 2018. Document updates and sources: http://free- electrons.com/doc/training/embedded- linux Corrections, suggestions, contributions and translations are welcome! Embedded Linux Developers DSI DSI - FCEIA http://dsi.fceia.unr.edu.ar 1/263

Upload: lehanh

Post on 27-May-2019

214 views

Category:

Documents


0 download

TRANSCRIPT

Embedded Linux system development

Embedded Linux systemdevelopment

Free Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Latest update: March 14, 2018.Document updates and sources:http://free-electrons.com/doc/training/embedded-linux

Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 1/263

Derechos de copia

© Copyright 2018, Luciano DiamandLicencia: Creative Commons Attribution - Share Alike 3.0http://creativecommons.org/licenses/by-sa/3.0/legalcode

Ud es libre de:

I copiar, distribuir, mostrar y realizar el trabajo

I hacer trabajos derivados

I hacer uso comercial del trabajo

Bajo las siguientes condiciones:

I Atribucion. Debes darle el credito al autor original.

I Compartir por igual. Si altera, transforma o construye sobre este trabajo, ustedpuede distribuir el trabajo resultante solamente bajo una licencia identica a esta.

I Para cualquier reutilizacion o distribucion, debe dejar claro a otros los terminosde la licencia de este trabajo.

I Se puede renunciar a cualquiera de estas condiciones si usted consigue elpermiso del titular de los derechos de autor.

El uso justo y otros derechos no se ven afectados por lo anterior.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 2/263

Hipervınculos en el documento

Hay muchos hipervınculos en el documento

I Hipervıncluos regulares:http://kernel.org/

I Enlaces a la documentacion del Kernel:Documentation/kmemcheck.txt

I Enlaces a los archivos fuente y directorios del kernel:drivers/input

include/linux/fb.h

I Enlaces a declaraciones, definiciones e instancias de lossimbolos del kernel (funciones, tipos, datos, estructuras):platform_get_irq()

GFP_KERNEL

struct file_operations

DSI - FCEIA http://dsi.fceia.unr.edu.ar 3/263

Introduccion a Linux Embebido

Introduccion aLinux EmbebidoFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 4/263

Nacimiento del software libre

I 1983, Richard Stallman, proyecto GNU y el concepto desoftware libre. Comienza el desarrollo de gcc, gdb, glibc yotras herramientas importantes

I 1991, Linus Torvalds, proyecto Linux kernel, un nucleo desistema operativo similar a Unix. Junto con el software GNU yotros componentes de codigo abierto: forman un sistemaoperativo completo GNU/Linux

I 1995, Linux es mas popular en sistemas servidor

I 2000, Linux es mas popular en sistemas embebidos

I 2008, Linux es mas popular en dispositivos moviles

I 2010, Linux es mas popular en telefonos

DSI - FCEIA http://dsi.fceia.unr.edu.ar 5/263

¿Software libre?

I Un programa es considerado libre cuando su licencia ofrece atodos sus usuarios las siguientes cuatro libertades

I Libertad de ejecutar el Sofrware para cualquier propositoI Libertad de estudiar el Software y modificarloI Liberatd de redistribuir copiasI Libertad de distribuir copias de versiones modificadas

I Estas libertades estan concedidas para uso tanto comercialcomo no-comercial

I Implican la disponibilidad del codigo fuente, el Software puedeser modificado y distribuido a los clientes

I Una opcion interesante para los sistemas embebidos!

DSI - FCEIA http://dsi.fceia.unr.edu.ar 6/263

¿Que es Linux embebido?

Linux embebido es el uso del kernelde Linux y varios componentes

open-source en sistemas embebidos

DSI - FCEIA http://dsi.fceia.unr.edu.ar 7/263

Introduccion a Linux Embebido

Ventajas de Linux y open-source parasistemas embebidos

DSI - FCEIA http://dsi.fceia.unr.edu.ar 8/263

Reutilizacion de componentes

I La principal ventaja de Linux y open-source en sistemasembebidos es la habilidad de reutilizar componentes

I El ecosistema de open-source ya provee de varioscomponentes para caracterısticas estandares, desde soporte deHardware hasta protocolos, pasando por multimedia, graficos,bibliotecas criptograficas, etc.

I Tan pronto como un dispositivo Hardware, o un protocolo, ouna caracterıstica se torna conocida, existen varias chances detener un componente open-source que lo soporte.

I Permite disenar de forma rapida y desarrollar productoscomplejos, basados en componentes existentes.

I No es necesario redesarrollar otro kernel de sistema operativo,una pila TCP/IP, una pila USB u otra biblioteca grafica.

I Permite enfocarce en el valor agregado del producto.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 9/263

Bajo costo

I El Software libre puede ser duplicado en la cantidad dedispositivos que se quiera, libre de cargos.

I Si su sistema embebido utiliza solo Software libre, se puedereducir los costos de licencias de Software a cero. Incluso, lasherramients de desarrollo son libres, a menos que se elija unaversion de Linux embebido comercial.

I Permite tener un mayor presupuesto para el Hardware opara incrementar las habilidades y conocimiento de lacompanıa

DSI - FCEIA http://dsi.fceia.unr.edu.ar 10/263

Control total

I Con codigo abierto, disponemos del codigo fuente de todos loscomponentes del sistema

I Permite modificaciones ilimitadas, cambios, ajustes,depuracion, optimizacion, por un perıodo de tiempo ilimitado

I Sin una dependencia ”bloqueante” de un vendedor externoI Componentes que no sean de codigo abierto se deben evitar

cuando el sistema se disena y desarrolla

I Permite tener un control total sobre el Software queforma parte del sistema

DSI - FCEIA http://dsi.fceia.unr.edu.ar 11/263

Calidad

I Varios componentes de codigo abierto son ampliamenteutilizados en millones de sistemas

I Generalmente son de mayor calidad que los desarrollosin-house o incluso de los vendedores propietarios

I Por supuesto, no todos los componentes de codigo abierto sonde buena calidad, pero los mas ampliamente utilizados los son.

I Permite disenar su sistema con componentesfundacionales de alta calidad

DSI - FCEIA http://dsi.fceia.unr.edu.ar 12/263

Facilita la prueba de nuevas caracteristicas

I Dado la disponibilidad del codigo abierto, es simple obteneruna copia del Software para evaluarlo

I Permite de forma simple estudiar las opciones mientras se estadecidiendo

I Mucho mas simple que la compra y procesos de demostracionnecesitan con la mayorıa de los productos propietarios

I Permiten explorar de forma simple nuevas posibilidades ysoluciones

DSI - FCEIA http://dsi.fceia.unr.edu.ar 13/263

Soporte de la comunidad

I Los componentes de Software de codigo abierto sondesarrollados por comunidades de desarrolladores y usuarios

I Esta comunidad puede proveer soporte de alta calidad: sepuede contactar directamente a los desarrolladores principalesdel componente que se esta usando. La probabilidad deobtener una respuesta no depende de la companıa para la quetrabajemos.

I En general mejor que el soporte tradicional, pero es necesarioentender como funciona la comunidad para hacer un usocorrecto de las posibilidades de soporte

I Permite acelerar la resolucion de problemas cuando seeste desarrollando el sistema

DSI - FCEIA http://dsi.fceia.unr.edu.ar 14/263

Formando parte de la comunidad

I La posibilidad de formar parte de la comunidad de desarrollode algunos de los componentes utilizados en sistemasembebidos: reporte de fallas, prueba de nuevas versiones ycaracterısticas, parches que corrigen errores o agregan nuevascaracterısticas, etc.

I La mayorıa del tiempo, los componentes de codigo abierto noson el nucleo de valor del producto: es interes de todoscontribuir al mismo

I Para los ingenieros: una forma muy motivante de serreconocido fuera de la companıa, comunicarse con otros en elmismo campo, la oportunidad de nuevas posibilidades, etc.

I Para los gerentes: factor de motivacion para los ingenieros,permite a la companıa ser reconocida en la comunidad decodigo abierto y por lo tanto obtener soporte de forma massimple y ser mas atractivo para los desarrolladores de codigoabierto

DSI - FCEIA http://dsi.fceia.unr.edu.ar 15/263

Introduccion a Linux Embebido

Algunos ejemplos de sistemasembebidos ejecutando Linux

DSI - FCEIA http://dsi.fceia.unr.edu.ar 16/263

Ruters personales

DSI - FCEIA http://dsi.fceia.unr.edu.ar 17/263

Television

DSI - FCEIA http://dsi.fceia.unr.edu.ar 18/263

Terminales de punto de venta

DSI - FCEIA http://dsi.fceia.unr.edu.ar 19/263

Maquinas de corte Laser

DSI - FCEIA http://dsi.fceia.unr.edu.ar 20/263

Maquina de Viticultura

DSI - FCEIA http://dsi.fceia.unr.edu.ar 21/263

Introduccion a Linux Embebido

Hardware para sistemas embebidos enLinux

DSI - FCEIA http://dsi.fceia.unr.edu.ar 22/263

Procesador y arquitectura (1)

I El kernel de Linux y la mayorıa de otros componentesdependientes de la arquitectura soportan un amplio rango dearquitecturas de 32 y 64 bits

I x86 y x86-64, como se encuentran en plataformas PC, perotambien sistemas embebidos (multimedia, industrial)

I ARM, con miles de diferentes SoC (multimedia, industrial)I PowerPC (principalmente aplicaciones en tiempo real e

industriales)I MIPS (principalmente para aplicaciones de red)I SuperH (principalmente aplicaciones multimedia)I Blackfin (arquitectura DSP)I Microblaze (soft-core para FGPA de Xilinx)I Coldfire, SCore, Tile, Xtensa, Cris, FRV, AVR32, M32R

DSI - FCEIA http://dsi.fceia.unr.edu.ar 23/263

Procesador y arquitectura (2)

I Ambas arquitecturas, MMU y no-MMU son soportadas,aunque la arquitectura no-MMU tiene algunas limitaciones.

I Linux no esta disenado para microcontroladores pequenos.

I Salvo el juego de herraminetas, el cargador de inicio y elkernel, todos los otros componentes generalmente sonindependientes de la arquitectura

DSI - FCEIA http://dsi.fceia.unr.edu.ar 24/263

RAM y almacenamiento

I RAM: un sistema basico con Linux puede funcionar con 8 MBde RAM, pero un sistema mas realista usualmente requiere 32MB de RAM. Depende del tipo y tamano de la aplicacion.

I Almacenamiento: un sistema basico con Linux puedetrabajar con 4 MB de almacenamiento, pero usualmente serequiere una mayor cantidad.

I El almacenamiento en Flash esta soportado, tanto flash NANDcomo NOR, con sistemas de archivos especıficos

I Almacenamiento en bloque incluyendo tarjetas SD/MMC yeMMC son soportadas

I Es preferible no tener muchas restricciones en la cantidad deRAM/almacenamiento: tener una cierta flexibilidad en estenivel nos permite reutilizar tantas aplicaciones como seaposible.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 25/263

Comunicacion

I El kernel de Linux tiene soporte para varios protocolos decomunicaciones comunes

I I2CI SPII CANI 1-wireI SDIOI USB

I Y tambien soporte para redes extensivoI Ethernet, Wifi, Bluetooth, CAN, etc.I IPv4, IPv6, TCP, UDP, SCTP, DCCP, etc.I Firewalling, ruteo avanzado, multicast

DSI - FCEIA http://dsi.fceia.unr.edu.ar 26/263

Tipos de Hardware y plataformas 1/2

I Plataformas de evaluacion del proveedor de SoC.Usualmente costosas, pero con muchos perifericos incluidos.Generalmente no recomendable para productos reales.

I Componente en Modulo, una pequena placa solamente conCPU/RAM/flash y algunos otros componentes, conconectores para acceder a todos los perifericos. Puede serutilizado para construir productos finales en pequenas omedianas cantidades.

I Plataformas de desarrollo comunitario, una nuevatendencia para hacer un SoC particular popular y facilmentedisponible. Estas estan listas para utilizar y a un bajo costo,pero generalmente tienen menos perifericos que lasplataformas de evaluacion. En algunos casos pueden serutilizadas para productos reales.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 27/263

Tipos de Hardware y plataformas 1/2

I Plataforma personalizada. Los esquematicos para placas deevaluacion o plataformas de desarrollo estan disponibles mascomunmente de forma libre, haciendo mas simple el desarrollode plataformas personalizadas.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 28/263

Criterios para la eleccion del Hardware

I Asegurese que el Hardware que planea utilizar estaactualmente soportado por el kernel de Linux, y posee uncargador de inicio de cogio abierto, especialmente para el SoCdestino.

I Teniendo soporte en las versiones oficiales de los proyectos(kernel, cargador de inicio): la calidad es mejor, y nuevasversiones estan disponibles.

I Algunos proveedores de SoC y/o proveedores de placas nocontribuyen sus cambios hacia la linea principal del kernel deLinux. Recomiende que lo hagan, o utilice otro producto deser posible. Una buena metrica es ver las diferencias entre sukernel y el oficial.

I Entre un hardware correctamente soportado en el kerneloficial de Linux y un hardware mal soportado, existiranenormes diferencias en tiempo de desarrollo y costo.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 29/263

Introduccion a Linux Embebido

Arquitectura de sistemas embebidosen Linux

DSI - FCEIA http://dsi.fceia.unr.edu.ar 30/263

Arquitectura global

DSI - FCEIA http://dsi.fceia.unr.edu.ar 31/263

Componentes Software

I Juego de herramientas de compilacion cruzadaI Compilador que corre en la maquina de desarrollo, pero genera

codigo para el destino

I Cargador de inicioI Ejecutado por el Hardware, responsable de la inicializacion

basica, cargao y ejecuta el kernel

I Kernel de LinuxI Contiene los proceso y el manejo de memoria, red,

controladores de dispositivos y provee servicios para laaplicacion en el espacio de usuario

I Biblioteca CI La interfaz entre el kernel y las aplicaciones en el espacio de

usuario

I Bibliotecas y aplicacionesI De terceros (Third-party or in-house)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 32/263

Trabajo sobre Linux embebido

Varias tareas de distinto tipo se necesitan al momento de desplegarun Linux embebido en un producto:

I Board Support Package development (BSP)I Un BSP contiene un bootloader y un kernel con los device

drivers adecuados para el Hardware destinoI Es el proposito del entrenamiento en desarrollo del Kernel

I Integracion del sistemaI Integrar todos los componentes, bootloader, kernel, y

bibliotecas de terceros y aplicaciones y aplicaciones in-house enun sistema funcional

I Es el proposito de este entrenamiento

I Desarrollo de aplicacionesI Aplicaciones Linux normales, pero utilizando bibliotecas

especialmente elegidas

DSI - FCEIA http://dsi.fceia.unr.edu.ar 33/263

Embedded Linux development environment

Embedded LinuxdevelopmentenvironmentFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 34/263

Soluciones de Linux Embebidas

I Dos formas de cambiar a Linux embebidoI Utilice soluciones proporcionadas y apoyadas por

vendedores como MontaVista, Wind River o TimeSys. Estassoluciones vienen con sus propias herramientas de desarrollo yentorno. Utilizan una mezcla de componentes de codigoabierto y herramientas propietarias.

I Utilice soluciones comunitarias. Estan completamenteabiertas, soportado por la comunidad.

I En estas sesiones de formacion, no promovemos un Proveedory, por lo tanto, utilizamos soluciones comunitarias

I Sin embargo, conociendo los conceptos, cambiar a otroproveedor es simple

DSI - FCEIA http://dsi.fceia.unr.edu.ar 35/263

SO para el desarrollo de Linux

I Recomendamos encarecidamente el uso de Linux comosistema para incorporar a los desarrolladores de Linux, pormultiples razones.

I Todas las herramientas de la comunidad estan desarrolladas ydisenadas para funcionar Linux. Intentar utilizarlos en otrossistemas operativos (Windows, Mac OS X) conducira aproblemas, y su uso en estos sistemas generalmente no sonapoyados por los desarrolladores de la comunidad.

I Como Linux tambien se ejecuta en el dispositivo embebido,todo el conocimiento ganado por el uso de Linux en elescritorio se aplicara de manera directa al dispositivoembebido.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 36/263

Distribucion de Linux de escritorio

I Cualquier distribucion de Linux deescritorio suficientemente reciente sepuede utilizar para la estacion de trabajode desarrollo

I Ubuntu, Debian, Fedora, openSUSE,Red Hat, etc.

I Hemos elegido Ubuntu, ya que es unadistribucion de Linux de escritorioampliamente utilizado y facil de usar

I La configuracion de Ubuntu en lascomputadoras portatiles de formacion haquedado intacta despues del proceso deinstalacion normal. Aprender Linuxembebido tambien consiste en aprenderlas herramientas necesarias en la estacionde trabajo de desarrollo!

DSI - FCEIA http://dsi.fceia.unr.edu.ar 37/263

Usuarios root y no root de Linux

I Linux es un sistema operativo multiusuarioI El usuario root es el administrador, y puede realizar

operaciones privilegiadas como: montar sistemas de archivos,configurar la red, crear archivos de dispositivos, cambiar laconfiguracion del sistema, instalar o eliminar software

I Todos los otros usuarios no tienen privilegios, y no puedenrealizar estas operaciones a nivel de administrador

I En un sistema Ubuntu, no es posible iniciar sesion como root,solo como usuario normal.

I El sistema se ha configurado para que la primer cuenta deusuario creada pueda ejecutar operaciones privilegiadas atraves de un programa llamado sudo.

I Ejemplo: sudo mount /dev/sda2 /mnt/disk

DSI - FCEIA http://dsi.fceia.unr.edu.ar 38/263

Paquetes de Software

I El mecanismo de distribucion para el software en GNU / Linuxes diferente de la de Windows

I Las distribuciones de Linux proporcionan una forma central ycoherente de instalar, actualizar y eliminar aplicaciones ybibliotecas: paquetes

I Packages contains the application or library files, andassociated meta-information, such as the version and thedependencies

I .deb en Debian y Ubuntu, .rpm en Red Hat, Fedora,openSUSE

I Los paquetes se almacenan en repositorios, usualmente enservidores HTTP o FTP

I Solo debe utilizar paquetes de repositorios oficiales para sudistribucion, a menos que sea estrictamente necesario.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 39/263

Gestion de paquetes de software (1)

Instrucciones para los sistemas GNU / Linux basados en Debian(Debian, Ubuntu...)

I Los repositorios de paquetes se especifican en/etc/apt/sources.list

I Para actualizar la lista de paquetes del repositorio:sudo apt-get update

I Para encontrar el nombre de un paquete a instalar, lo mejor esusar el motor de busqueda enhttp://packages.debian.org o enhttp://packages.ubuntu.com. Tambien puede usar:apt-cache search <keyword>

DSI - FCEIA http://dsi.fceia.unr.edu.ar 40/263

Gestion de paquetes de Software (2)

I Para instalar un paquete dado:sudo apt-get install <package>

I Para eliminar un parquete dado:sudo apt-get remove <package>

I Para instalar todas las actualizaciones de paquetes disponibles:sudo apt-get dist-upgrade

I Para obtener informacion acerca de un paquete:apt-cache show <package>

I Interfaces graficasI Para GNOME SynapticI Para KDE KPackageKit

Mas detalles sobre la gestion de paquetes:http://www.debian.org/doc/manuals/apt-howto/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 41/263

Host vs. destino

I Al hacer el desarrollo embebido, siempre hay una divisionentre

I El host, la estacion de trabajo de desarrollo, que estıpicamente una PC potente

I El destino, que es el sistema embebido bajo desarrollo

I Estan conectados por diversos medios: casi siempre una lıneaserie para fines de depuracion, con frecuencia una conexionEthernet, a veces una interfaz JTAG para la depuracion a bajonivel

DSI - FCEIA http://dsi.fceia.unr.edu.ar 42/263

Programa de comunicacion por lınea serie

I Una herramienta esencial para el desarrollo embebido es unprograma de comunicacion por lınea serie, comoHyperTerminal en Windows

I Hay multiples opciones disponibles en Linux: Minicom,Picocom, Gtkterm, Putty, etc.

I En estos sesiones de entrenamiento, recomendamos utilizar elmas simple de ellos: picocom

I Se instala con sudo apt-get install picocomI Se ejecuta con

picocom -b BAUD_RATE /dev/SERIAL_DEVICEI Se termina con Control-A Control-X

I Donde SERIAL_DEVICE generalmente esI ttyUSBx para conversores USB a serieI ttySx para puertos series reales

DSI - FCEIA http://dsi.fceia.unr.edu.ar 43/263

Consejos sobre la lınea de comandos

I El uso de la lınea de comandos es obligatorio para muchasoperaciones necesarias para el desarrollo de Linux

I Es una manera muy poderosa de interactuar con el sistema,con la cual usted puede ahorrar mucho tiempo.

I Algunos consejos utilesI Puede utilizar varias pestanas en el Gnome TerminalI Recuerde que puede utilizar rutas de acceso relativas (por

ejemplo: ../../ linux) ademas de rutas absolutas (porejemplo: /home/user)

I En un shell, pulse [Control] [r] y, a continuacion, unapalabra clave, esto buscara a traves del historial de comandos.Presione [Control] [r] de nuevo para buscar hacia atras enla historia

I Puede copiar y pegar rutas directamente desde el el terminalcon arrastrar y soltar.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 44/263

Juego de herramientas de compilacion cruzada

Juego deherramientas decompilacioncruzadaFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 45/263

Juego de herramientas de compilacion cruzada

Definiciones y Componentes

DSI - FCEIA http://dsi.fceia.unr.edu.ar 46/263

Definiciones 1/2

I Las herramientas de desarrollo usualmente disponibles en unaestacion de trabajo GNU/Linux son un juego deherramientas nativo

I Este juego de herramientas corre en la estacion de trabajo ygenera codigo para la propia estacion de trabajo(generalmente x86)

I Para el desarrollo de sistemas embebidos, es generalmenteimposible o no tiene interes el utilizar un juego deherramientas nativo

I El destino es muy restrictivo en terminos de almacenamientoy/o memoria

I El destino es muy lento comparado con la estacion de trabajoI Puede que no interese instalar todas las herraminetas de

desarrollo en el destino.

I Por lo tanto, se utilizan generalmente los juegos deherramientas de compilacion cruzada. Ellos corren en laestacion de trabajo, pero generan codigo para el destino.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 47/263

Definiciones 2/2

DSI - FCEIA http://dsi.fceia.unr.edu.ar 48/263

Maquinas en el proceso de construccion

I Se deben distinguir entre tres maquinas cuando se discute lacreacion del juego de herramientas

I La maquina de construccion o build, donde se construye eljuego de herraminetas.

I La maquina host, donde se ejecuta el juego de herraminetas.I La maquina destino o target, donde los binarios creados por el

juego de herraminetas son ejecutados.

I Cuatro formas de construccion son posibles para los juegos deherraminetas

DSI - FCEIA http://dsi.fceia.unr.edu.ar 49/263

Construccion del juego de herramientas

DSI - FCEIA http://dsi.fceia.unr.edu.ar 50/263

Componentes

DSI - FCEIA http://dsi.fceia.unr.edu.ar 51/263

Binutils

I Binutils es un juego de herraminetas para generar y manipularbinarios para una arquitectura CPU dada

I as, el ensamblador, que genera codigo binario desde el codigofuente ensamblador

I ld, el enlazadorI ar, ranlib, para generar los archivos .a, utilizados por las

bibliotecasI objdump, readelf, size, nm, strings, para inspeccionar

binarios. Herramientas de analisis muy utiles!I strip, para cortar partes de binarios inutiles y de esa forma

reducir su tamano

I http://www.gnu.org/software/binutils/

I Licencia GPL

DSI - FCEIA http://dsi.fceia.unr.edu.ar 52/263

Cabeceras del Kernel (1)

I La bibilioteca C y los programascompilados necesitan interactuarcon el Kernel

I Llamadas al sistema disponibles ysus correspondiente numeracion

I Definicion de constantesI Estructuras de datos, etc.

I Por lo tanto, compilar la bibliotecaC requiere de las cabeceras delKernel, y varias aplicacionestambien las requieren.

I Disponibles en los directorios<linux/...> y <asm/...> y enotros directorios correspondientes alos del directorio include/ en losfuentes del Kernel

DSI - FCEIA http://dsi.fceia.unr.edu.ar 53/263

Cabeceras del Kernel (2)

I Numeros de llamadas al sistema, en <asm/unistd.h>

#define __NR_exit 1

#define __NR_fork 2

#define __NR_read 3

I Definiciones de constantes, en <asm-generic/fcntl.h>,incluidos desde <asm/fcntl.h>, incluidos desde<linux/fcntl.h>

#define O_RDWR 00000002

I Estructuras de datos, en <asm/stat.h>

struct stat {

unsigned long st_dev;

unsigned long st_ino;

[...]

};

DSI - FCEIA http://dsi.fceia.unr.edu.ar 54/263

Cabeceras del Kernel (3)

I El ABI del Kernel al espacio de usuario es compatible haciaatras

I Binarios generados con un juego de herramientas utilizandocabeceras del Kernel mas viejas que las del Kernel en ejecucionvan a funcionar sin problemas, pero no se van a poder llamar alas nuevas llamadas al sistema, estructuras de datos, etc.

I Binarios generados con un juego de herramientas utilizandocabeceras del Kernel mas nuevas que las del Kernel enejecucıon pueden funcionar si no utilizan las caracterısticasrecientes, de otra manera van a fallar

I Utilizar las ultimas cabeceras del Kernel no es necesario, salvoque se necesiten las nuevas caracterısticas del Kernel

I Las cabeceras del Kernel se extraen del los fuentes del Kernelutilizando como destino del Makefile headers_install.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 55/263

GCC

I GNU Compiler Collection, el famoso compiladorde software libre

I Puede compilar C, C++, Ada, Fortran, Java,Objective-C, Objective-C++, y generar codigopara un gran numero de arquitecturas de CPU,incluyendo ARM, AVR, Blackfin, CRIS, FRV,M32, MIPS, MN10300, PowerPC, SH, v850,i386, x86 64, IA64, Xtensa, etc.

I http://gcc.gnu.org/

I Disponible bajo la licencia GPL, bibliotecas bajoLGPL.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 56/263

Bibioteca C

I La bibiloteca C es un componenteescencial de un sistema GNU/Linux

I Interactua entre la aplicacion y el KernelI Provee una API estandard de C bien

conocida para facilitar el desarrollo deaplicaciones

I Hay disponibles varias bibliotecas de C:glibc, uClibc, eglibc, dietlibc, newlib, etc.

I La eleccion de la biblioteca C se deberealizar en el momento de la generaciondel juego de herramientas de compilacioncruzada, dado que el compilador GCC secompila contra una biblioteca Cespecıfica.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 57/263

Juego de herramientas de compilacion cruzada

Bibliotecas C

DSI - FCEIA http://dsi.fceia.unr.edu.ar 58/263

glibc

I Licencia: LGPL

I Biblioteca C del proyecto GNU

I Disenado para el rendimiento, elcumplimiento de las normas y laportabilidad

I Se encuentra en todos los sistemasGNU/Linux

I Por supuesto, mantenido activamente

I Muy grande para los sistemas embebidospequenos: aprox 2.5 MB en ARM (version2.9 - libc: 1.5 MB, libm: 750 KB)

I http://www.gnu.org/software/libc/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 59/263

uClibc

I Licencia: LGPLI Biblioteca de C liviana para sistemas embebidos pequenos

I Alta configurabilidad: se pueden activar o deshabilitar muchasfunciones a traves de una interfaz menuconfig

I Funciona solo con Linux/uClinux, funciona en la mayorıa dearquitecturas

I No hay compatibilidad binaria garantizada. Puede necesitarrecompilar las aplicaciones cuando cambie la configuracion dela biblioteca.

I Enfocada en el tamano mas que en el rendimientoI Tiempo de compilacion corto

I http://www.uclibc.org/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 60/263

uClibc (2)

I Most of the applications compile with uClibc. This applies toall applications used in embedded systems.

I Size (arm): 4 times smaller than glibc!I uClibc 0.9.30.1: approx. 600 KB (libuClibc: 460 KB, libm:

96KB)I glibc 2.9: approx 2.5 MB

I Some features not available or limited: priority-inheritancemutexes, NPTL support is very new, fixed Name ServiceSwitch functionality, etc.

I Used on a large number of production embedded products,including consumer electronic devices

I Supported by all commercial embedded Linux providers (proofof maturity).

I Warning: though some development is still happening, themaintainers have stopped making releases since May 2012.The project is in trouble.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 61/263

eglibc

I Embedded glibc, tambien licencia LGPL

I Era una variante de glibc, mejor adaptada a lasnecesidades de los sistemas embebidos, por undesacuerdo con los mantenedores de la glibc.

I Los objetivos de eglibc incluyeron un menorconsumo de memoria, componentesconfigurables, un mejor soporte para lacompilacion cruzada y pruebas cruzadas

I Se podrıa construir sin soporte para NIS, locales,IPv6 y muchos otras caracterısticas

I Afortunadamente para eglibc, el mantenedor deglibc ha cambiado y sus caracterısticas y ahorase incluyen en glibc. La ultima version fua la2.19 (Febrero de 2014).

I http:

//en.wikipedia.org/wiki/Embedded_GLIBCDSI - FCEIA http://dsi.fceia.unr.edu.ar 62/263

Carino, encogı los programas!

I Comparacion del tamano ejecutable en ARM, probado coneglibc 2.15 y uClibc 0.9.33.2

I Programa “hello world” (stripped):helloworld estatico dinamico

uClibc 18kB 2.5kBuClibc con Thumb-2 14kB 2.4kBeglibc con Thumb-2 361kB 2.7kB

I Busybox (stripped):busybox static dynamic

uClibc 750kB 603kBuClibc con Thumb-2 533kB 439kBeglibc con Thumb-2 934kB 444kB

DSI - FCEIA http://dsi.fceia.unr.edu.ar 63/263

Otras bibliotecas de C pequenas

I Varias bibliotecas C mas pequenas han sido desarrolladas,pero ninguna de ellas tiene como objetivo de permitir lacompilacion de grandes aplicaciones ya existentes

I Necesitan programas y aplicaciones especialmente escritasI Opciones:

I Dietlibc, http://www.fefe.de/dietlibc/.Aproximadamente 70 KB.

I Newlib, http://sourceware.org/newlib/I Klibc, http://www.kernel.org/pub/linux/libs/klibc/,

disenado para ser utilizado con initramfs o initrd en elmomento del arranque.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 64/263

Juego de herramientas de compilacion cruzada

Opciones del Juego de herramientas

DSI - FCEIA http://dsi.fceia.unr.edu.ar 65/263

ABI (Application Binay Interface)

I Cuando se construye un juego de herramientas, el ABIutilizado para generar los binarios debe ser definido

I ABI define la convencion de llamadas (como se pasan losargumentos a una funcion, como se retorna el valor, como serealizan las llamadas al sistema) y la organizacion de lasestructuras (alineamiento, etc.)

I Todos los binarios en un sistema deben ser compilados con elmismo ABI, y el kernel debe entender dicho ABI.

I En ARM, existen dos ABIs: OABI and EABII Actualmente se utiliza EABI

I En MIPS, existen varios ABIs: o32, o64, n32, n64

I http://en.wikipedia.org/wiki/Application_Binary_

Interface

DSI - FCEIA http://dsi.fceia.unr.edu.ar 66/263

Soporte para punto flotante

I Algunos procesadores poseen una unidad de punto flotante, yotros no.

I Por ejemplo, muchas CPUs ARMv4 y ARMv5 no tienen unaunidad de punto flotante. Desde ARMv7, la unidad VFP(Vector Floating Point) es obligatoria.

I Para los procesadores que cuentan con una unidad de puntoflotante, el juego de herramientas debe generar codigo hardfloat, y ası poder utilizar las instrucciones de punto flotantedirectamente

I Para procesadores sin unidad de punto flotante, existen dossoluciones

I Generar hard float code y dejar que el kernel emule lasinstrucciones de punto flotante (esto es muy lento).

I Generar soft float code, para que en lugar de generarinstrucciones de punto flotante, se generen llamadas a libreriasen el espacio de usuario

I Esta decision debe ser tomada en el momento deconfiguracion del juego de herramientas

I Tambien es posible configurar que unidad de punto flotante vaa ser utilizada

DSI - FCEIA http://dsi.fceia.unr.edu.ar 67/263

Banderas de optimizacion de CPU

I Un juego de herramientas para compilacion cruzada esespecıfico para una arquitectuda de CPU (ARM, x86, MIPS,PowerPC)

I Sin embargo, con la opcion -march=, -mcpu=, -mtune=, sepuede seleccionar de forma mas precisa el tipo de CPUdestino

I Por ejemplo, -march=armv7 -mcpu=cortex-a8

I En el momento de compilar el juego de herramientas, sepueden elegir estos valores, los cuales seran utilizados:

I Como valores por defecto para las herramientas de compilacioncruzada, cuando ninguna otra opcion -march, -mcpu, -mtunees utilizada

I Para compilar la biblioteca C

I Incluso si la biblioteca C fue compilada para armv5t, noprohibe de compilar otros programas para armv7

DSI - FCEIA http://dsi.fceia.unr.edu.ar 68/263

Juego de herramientas de compilacion cruzada

Obteniendo el juego de herramientas

DSI - FCEIA http://dsi.fceia.unr.edu.ar 69/263

Construir el juego de herramientas de forma manual

Construir el juego de herramientas para la compilacion cruzada unomismo es una tarea dificil y compleja que puede llevar dıas eincluso semanas!

I Gran cantidad de detalles para aprender: muchoscomponentes, configuraciones complicadas

I Muchas decisiones que tomar (como ser la version de labiblioteca C, ABI, mecanismos de punto flotante, versiones delos componentes)

I Son necesarios los fuentes de las cabeceras del Kernel y labiblioteca C

I Es necesario estar familiarizado con los problemas actuales yparches de gcc para su plataforma

I Es util estar familiarizado con las herramientas deconstruccion y configuracion

I Vea el directorio docs/ de Crosstool-NG para detalles decomo se construyen los juegos de herramientas.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 70/263

Obtener un juego de herramientas pre-compilado

I Es una solucion utilizada por muchas personasI Ventaja: es la solucion mas simple y la mas convenienteI Desventaja: no es posible realizar un ajuste fino del juego de

herramientas de acuerdo a sus necesidades

I Determinar que juego de herramientas necesita: CPU,endianism, biblioteca C, version de componentes, ABI, softfloat o hard float, etc.

I Verificar que los juegos de herramientas disponibles se ajustana sus requerimientos.

I Opciones posiblesI Juegos de herramientas de Sourcery CodeBenchI Juegos de herramientas de LinaroI Mas referencias en http://elinux.org/Toolchains

DSI - FCEIA http://dsi.fceia.unr.edu.ar 71/263

Sourcery CodeBench

I CodeSourcery fue una companıa con un gran conocimiento enjuegos de herramientas libres: gcc, gdb, binutils y glibc. Fueadquirida por Mentor Graphics, la cual continua brindandoservicios y productos similares

I Venden juegos de herramientas con soporte, pero tambienposeen una version ”Lite”, que es de libre y se puede utilizaren productos comerciales

I Tienen juegos de herramientas disponibles paraI ARMI MIPSI PowerPCI SuperHI x86

I Asegurese de utilizar versiones Linux. Las versiones EABI sonpara el desarrollo bare-metal (sin sistema operativo)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 72/263

Juego de herramientas de Linaro

I Linaro contribuye a mejorar la lınea principal de gccpara ARM, en particular contratando desarrolladores deCodeSourcery.

I Para aquellos que no pueden esperar por la proximaversion de gcc, Linaro lanza los fuentes modificados deversiones estables de gcc, con optimizaciones paraARM (en general para CPUs Cortex recientes).

I Como cualquier version de gcc, estos fuentes puedenser utilizados por las herramientas de construccion paraconstruir sus propios juegos de herramientas binarios(Buildroot, OpenEmbedded, etc.) Esto permitesoportar glibc, uClibc y eglibc.

I https://wiki.linaro.org/WorkingGroups/ToolChain

I Paquetes binarios estan disponibles para usurios deUbuntu, https://launchpad.net/~linaro-maintainers/+archive/toolchain

DSI - FCEIA http://dsi.fceia.unr.edu.ar 73/263

Instalar un juego de herramientas pre-compilado

I Siga el procedimiento de instalacion propuesto por elfabricante

I Generalmente, es tan simple como extraer un archivo tar en laruta donde quiera que quede instalado.

I Luego, agregue la ruta a los binarios del juego deherramientas en su PATH:export PATH=/path/to/toolchain/bin/:$PATH

I Finalmente, compile sus aplicacionesPREFIX-gcc -o foobar foobar.c

I PREFIX depende de la configuracion del juego deherramientas, y permite distinguir entre herramientas decompilacion cruzada y utilidades de compilacion nativa

DSI - FCEIA http://dsi.fceia.unr.edu.ar 74/263

Utilidades para construir el juego de herramientas

Otra solucion es utilizar utilidades que automatizan el procesode construccion del juego de herramientas

I Las mismas ventajas que los juegos de herramientaspre-compilados: no necesita involucrarse en los detalles delproceso de construccion

I Pero tambien ofrece mas flexibilidad en terminos deconfiguracion del juego de herramientas, seleccion de laversion de componente, etc.

I Generalmente, tambien contienen varios parches que corrijenproblemas conocidos en diferentes componentes en algunasarquitecturas

I Multiples herramientas con identicos principios: shell scripts oMakefile que automaticamente recuperan, extraen,configuran, compilan e instalan los diferentes componentes

DSI - FCEIA http://dsi.fceia.unr.edu.ar 75/263

Utilidades para construir el juego de herramientas (2)

I Crosstool-ngI Refactorizacion de Crosstool, con una configuracion similar al

sistema menuconfigI Caracterısticas: soporta uClibc, glibc, eglibc, hard float y soft

float, varias arquitecturasI Mantenido activamenteI http://crosstool-ng.org/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 76/263

Utilidades para construir el juego de herramientas (3)

Varias utilidades para la construccion de sistemas de archivos raıztambien permiten la construccion de juego de herramientas

I BuildrootI Basado en Makefile. Puede construir juegos de herramientas

basado en (e)glibc, uClibc y musl, para una amplia gama dearquitecturas.

I http://www.buildroot.net

I PTXdistI Basado en Makefile, uClibc o glibc, mantenido por PengutronixI http://pengutronix.de/software/ptxdist/

I OpenEmbedded / YoctoI Muy completo en prestaciones, pero es un sistema de creacion

mas complicadoI http://www.openembedded.org/I https://www.yoctoproject.org/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 77/263

Crosstool-NG: instalacion y uso

I La instalacion de Crosstool-NG se puede realizar a nivel delsistema o solamente de forma local en un directorio particular.Para la instalacion local:

./configure --enable-local

make

make install

I Varias configuraciones de ejemplo para distintas arquitecturasestan disponibles en samples, se pueden visualizar utilizando

./ct-ng list-samples

I Para cargar una configuracion de ejemplo

./ct-ng <sample-name>

I Para ajustar la configuracion

./ct-ng menuconfig

I Para construir el juego de herramientas

./ct-ng build

DSI - FCEIA http://dsi.fceia.unr.edu.ar 78/263

Contenido del juego de herramientas

I Los binarios de compilacion cruzada en bin/I Este directorio puede ser agregado a su PATH para utilizar de

forma mas simple el juego de herramientasI Uno o mas sysroot, cada uno conteniendo

I La biblioteca C y bibliotecas relacionadas, compiladas para eldestino

I Las cabeceras de la biblioteca C y las cabeceras del KernelI Hay un sysroot por cada variante: los juegos de herramientas

pueden ser multilib si poseen varias copias de la biblioteca Cpara diferentes configuraciones (por ejemplo: ARMv4T,ARMv5T, etc.)

I Los juegos de herramientas de CodeSourcery para ARM sonmultilib, los sysroots estan enarm-none-linux-gnueabi/libc/,arm-none-linux-gnueabi/libc/armv4t/,arm-none-linux-gnueabi/libc/thumb2

I Los juegos de herramientas de Crosstool-NG pueden sermultilib tambien (todavıa en etapa de experimentacion), sinoel sysroot esta enarm-unknown-linux-glibcgnueabi/sysrootDSI - FCEIA http://dsi.fceia.unr.edu.ar 79/263

Gestor de arranque

Gestor de arranqueFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 80/263

Gestor de arranque

Secuencia de inicio

DSI - FCEIA http://dsi.fceia.unr.edu.ar 81/263

Gestores de arranque

I El gestor de arranque es una pieza responsable deI Inicializar de forma basica el HardwareI Cargar el binario de una aplicacion, generalmente el Kernel del

sistema operativo, desde el almacenamiento Flash, desde lared, o desde otro tipo de almacenamiento no volatil.

I Posibilita descomprimir el binario de la aplicacionI Ejecutar aplicacion

I Ademas de estas funciones basicas, la mayorıa de los gestoresarranque proveen un shell con una serie de comandosimplementando diferentes operaciones

I Carga de datos desde el almacenamiento o red, inspeccion dememoria, diagnosticos y pruebas de Hardware, etc.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 82/263

Gestores de arranque en x86 1/2

I Los procesadores x86 normalmente se incluyenen una placa con memoria no volatil quecontiene un programa, el BIOS.

I Este programa es ejecutado por CPU luego dereiniciar, y es responsable de la inicializacionbasica del Hardware y la carga de un fragmentode codigo desde una memoria no volatil.

I Este bloque de codigo generalmente ocupa losprimeros 512 bytes de un dispositivo dealmacenamiento

I Este bloque de codigo suele ser el gestor dearranque de primer nivel, que cargara el gestorde arranque completo.

I Tıpicamente comprende los formatos del sistemade archivos de modo que el archivo del Kernel sepuede cargar directamente desde un sistema dearchivos normal.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 83/263

Gestor de arranque en x86 2/2

I GRUB, Grand Unified Bootloader, el mas poderoso.http://www.gnu.org/software/grub/

I Puede leer muchos formatos de sistema de archivos para cargarla imagen del kernel y la configuracion, proporciona una shellpoderosa con varios comandos, puede cargar imagenes delkernel a traves de la red, etc.

I Vea nuestra presentacion dedicada para mas detalles:http://free-electrons.com/docs/grub/

I Syslinux, para arranque en red y medios extraıbles (clave USB,CD-ROM)http://www.kernel.org/pub/linux/utils/boot/syslinux/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 84/263

Arranque en CPUs embebidas: caso 1

I Cuando se activa, la CPU comienza a ejecutarcodigo en una direccion fija

I No hay ningun otro mecanismo de arranqueproporcionado por la CPU

I El diseno del hardware debe garantizar que unchip flash NOR este conectado para que seaaccesible en la direccion en la que la CPUcomienza a ejecutar instrucciones

I El gestor de arranque de la primera etapa debeestar programado en esa direccion en la NOR

I NOR es obligatorio, ya que permite el accesoaleatorio, que NAND no permite

I No muy comun (poco practico, y requiere unaFlash NOR)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 85/263

Arranque en CPUs embebidas: caso 2

I La CPU tiene un codigo de arranque integrado en ROMI BootROM en CPUs AT91, ”codigo ROM” en OMAP, etc.I Los detalles exactos dependen de la CPU

I Este codigo de arranque es capaz de cargar un gestor dearranque de primer nivel desde un almacenamiento en unaSRAM interna (la DRAM no se ha inicializado todavıa)

I El dispositivo de almacenamiento puede ser: MMC, NAND,flash SPI, UART, etc.

I El gestor de arranque de primer nivel esI Limitado en tamano debido a restricciones de hardware

(tamano SRAM)I Proporcionado ya sea por el vendedor de la CPU o por

proyectos comunitarios

I Este gestor de arranque de primer nivel debe inicializar laDRAM y otros dispositivos de Hardware y cargar el gestor dearranque de segundo nivel en la RAM

DSI - FCEIA http://dsi.fceia.unr.edu.ar 86/263

Arranque en ARM Atmel AT91

I RomBoot: intenta encontrar una imagen dearranque valida desde varias fuentes dealmacenamiento y cargarlo en SRAM (DRAM noinicializada todavıa). Tamano limitado a 4 KB.Ninguna interaccion del usuario es posible en elmodo de arranque estandar.

I AT91Bootstrap: se ejecuta desde SRAM.Inicializa la DRAM, el controlador NAND o SPI ycarga el gestor de arranque secundario en RAM ylo inicia. No es posible la interaccion con elusuario.

I U-Boot: se ejecuta desde RAM. Inicializa otrosdispositivos hardware (red, USB, etc.). Carga laimagen del nucleo desde almacenamiento o red aRAM y lo inicia. Provee un Shell con comandos.

I Linux Kernel: se ejecuta desde RAM. Recuperael sistema completamente (los gestores dearranque ya no existen).

DSI - FCEIA http://dsi.fceia.unr.edu.ar 87/263

Arranque en ARM TI OMAP3

I ROM Code: intenta encontrar una imagen dearranque valida desde varias fuentes dealmacenamiento y cargarlo en SRAM o RAM (laRAM puede ser inicializada por el codigo ROM atraves de un encabezado de configuracion).Tamano limitado a <64 KB. No hay interacciondel usuario posible.

I X-Loader o U-Boot: se ejecuta desde SRAM.Inicializa la DRAM, el controlador NAND o MMCy carga el gestor de arranque secundario en laRAM y lo inicia. No es posible la interaccion delusuario. Archivo llamado MLO.

I U-Boot: se ejecuta desde RAM. Inicializa otrosdispositivos hardware (red, USB, etc.). Carga laimagen del nucleo desde almacenamiento o red aRAM y lo inicia. Provee un Shell de comandos.Archivo llamado u-boot.bin o u-boot.img.

I Linux Kernel: se ejecuta desde RAM. Recuperael sistema completamente (el gestor no esta masdisponible).

DSI - FCEIA http://dsi.fceia.unr.edu.ar 88/263

Arranque en Marvell SoC

I ROM Code: intenta encontrar una imagen dearranque valida desde varias fuentes dealmacenamiento, y la carga en la RAM. Laconfiguracion de RAM se describe en unencabezado especıfico de la CPU, adjuntado a laimagen del gestor de arranque.

I U-Boot: se ejecuta desde RAM. Inicializa otrosdispositivos hardware (red, USB, etc.). Carga laimagen del nucleo desde almacenamiento o red aRAM y lo inicia. Provee un Shell con comandos.Archivo llamado u-boot.kwb

I Linux Kernel: se ejecuta desde RAM. Recuperael sistema completamente (los gestores dearranque ya no existen)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 89/263

Gestores de arranque genericos

I Nos centraremos en la parte generica, el cargador principal,que ofrece las caracterısticas mas importantes.

I Hay varios gestores de arranque genericos de codigo abierto.Aquı estan los mas populares:

I U-Boot, el gestor de arranque universal de DenxEl mas utilizado en ARM, tambien se utiliza en PPC, MIPS,x86, m68k, NIOS, etc. El estandar de facto actual. Loestudiaremos en detalle.http://www.denx.de/wiki/U-Boot

I Barebox, un nuevo gestor de arranque con arquitecturaneutra, escrito como un sucesor de U-Boot. Mejor diseno,mejor codigo, desarrollo activo, pero aun no tiene tantosoporte de hardware como U-Boot.http://www.barebox.org

I Tambien hay muchas otras aplicaciones de codigo abierto degestores de arranque, a menudo especıficos de la arquitectura

I RedBoot, Yaboot, PMON, etc.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 90/263

Gestor de arranque

El gestor de carga U-boot

DSI - FCEIA http://dsi.fceia.unr.edu.ar 91/263

U-Boot

U-Boot es un tıpico proyecto de software libre

I Licencia: GPLv2 (igual que Linux)

I Disponible de forma libre enhttp://www.denx.de/wiki/U-Boot

I Documentacion disponible enhttp://www.denx.de/wiki/U-Boot/Documentation

I El ultimo codigo fuente de desarrollo esta disponible en unrepositorio Git:http://git.denx.de/?p=u-boot.git;a=summary

I El desarrollo y las discusiones ocurren alrededor de una listaabierta http://lists.denx.de/pipermail/u-boot/

I Desde finales de 2008, sigue un intervalo de version fijo. Cadados meses, se lanza una nueva version. Las versions sellamana YYYY.MM.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 92/263

Configuracion de U-Boot

I Obtenga el codigo fuente del sitio web y descomprimaloI El directorio include/configs/ contiene un archivo de

configuracion para cada placa soportadaI Define el tipo de CPU, los perifericos y su configuracion, el

mapeo de memoria, las caracterısticas de U-Boot que se debencompilar, etc.

I Se trata de un simple archivo .h que establece las constantesdel preprocesador C. Vea el archivo README para ladocumentacion de estas constantes. Este archivo tambien sepuede ajustar para agregar o eliminar funciones de U-Boot(comandos, etc.).

I Suponiendo que su placa ya esta soportada por U-Boot, debehaber una entrada correspondiente a su placa en el archivoboards.cfg.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 93/263

Extracto del archivo de configuracion de U-Boot

/* CPU configuration */

#define CONFIG_ARMV7 1

#define CONFIG_OMAP 1

#define CONFIG_OMAP34XX 1

#define CONFIG_OMAP3430 1

#define CONFIG_OMAP3_IGEP0020 1

[...]

/* Memory configuration */

#define CONFIG_NR_DRAM_BANKS 2

#define PHYS_SDRAM_1 OMAP34XX_SDRC_CS0

#define PHYS_SDRAM_1_SIZE (32 << 20)

#define PHYS_SDRAM_2 OMAP34XX_SDRC_CS1

[...]

/* USB configuration */

#define CONFIG_MUSB_UDC 1

#define CONFIG_USB_OMAP3 1

#define CONFIG_TWL4030_USB 1

[...]

/* Available commands and features */

#define CONFIG_CMD_CACHE

#define CONFIG_CMD_EXT2

#define CONFIG_CMD_FAT

#define CONFIG_CMD_I2C

#define CONFIG_CMD_MMC

#define CONFIG_CMD_NAND

#define CONFIG_CMD_NET

#define CONFIG_CMD_DHCP

#define CONFIG_CMD_PING

#define CONFIG_CMD_NFS

#define CONFIG_CMD_MTDPARTS

[...]

DSI - FCEIA http://dsi.fceia.unr.edu.ar 94/263

Configuracion y compilacion de U-Boot

I U-Boot debe ser configurado antes de ser compiladoI make BOARDNAME_configI Donde BOARDNAME es el nombre de la placa, como se ve en el

archivo boards.cfg (primera columna).

I Asegurese de que el compilador cruzado este disponible enPATH

I Compile U-Boot, especificando el prefijo del compiladorcruzado.Por ejemplo, si el ejecutable del compilador cruzado esarm-linux-gcc:make CROSS_COMPILE=arm-linux-

I El resultado principal es un archivo u-boot.bin, que es laimagen de U-Boot. Dependiendo de su plataforma especıfica,puede haber otras imagenes especializadas: u-boot.img,u-boot.kwb, MLO, etc.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 95/263

Instalando U-Boot

I Por lo general, U-Boot debe instalarse en la memoria flashpara ser ejecutado por el hardware. Dependiendo delhardware, la instalacion de U-Boot se realiza de una maneradiferente:

I La CPU proporciona algun tipo de monitor de arranqueespecıfico con el que puede comunicarse a traves de un puertoserie o USB mediante un protocolo especıfico

I La CPU arranca primero en medios extraıbles (MMC) antes dearrancar desde medios fijos (NAND). En este caso, arrancadesde MMC para grabar una nueva version

I U-Boot ya esta instalado y puede utilizarse para grabar unanueva version de U-Boot. Sin embargo, tenga cuidado: i si lanueva version de U-Boot no funciona, la tarjeta es quedarainutilizable

I La placa proporciona una interfaz JTAG, que permite escribirla memoria flash de forma remota, sin ningun sistemaejecutandose en la placa. Tambien permite rescatar una placasi el gestor de arranque no funciona.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 96/263

Mensaje de U-boot

I Conecte el destino al anfitrion a traves de la consola serie

I Encienda la placa. En la consola serie va a ver algo como:

U-Boot 2013.04 (May 29 2013 - 10:30:21)

OMAP36XX/37XX-GP ES1.2, CPU-OPP2, L3-165MHz, Max CPU Clock 1 Ghz

IGEPv2 + LPDDR/NAND

I2C: ready

DRAM: 512 MiB

NAND: 512 MiB

MMC: OMAP SD/MMC: 0

Die ID #255000029ff800000168580212029011

Net: smc911x-0

U-Boot #

I El shell U-Boot ofrece un conjunto de comandos.Estudiaremos los mas importantes, consulte la documentacionpara obtener una referencia completa o el comando help.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 97/263

Comandos de informacion

Informacion Flash (NOR y SPI flash)

U-Boot> flinfo

DataFlash:AT45DB021

Nb pages: 1024

Page Size: 264

Size= 270336 bytes

Logical address: 0xC0000000

Area 0: C0000000 to C0001FFF (RO) Bootstrap

Area 1: C0002000 to C0003FFF Environment

Area 2: C0004000 to C0041FFF (RO) U-Boot

Informacion flash de NAND

U-Boot> nand info

Device 0: nand0, sector size 128 KiB

Page size 2048 b

OOB size 64 b

Erase size 131072 b

Detalles de la version

U-Boot> version

U-Boot 2013.04 (May 29 2013 - 10:30:21)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 98/263

Comandos importantes (1)

I El conjunto exacto de comandos depende de la configuracionde U-Boot

I help and help command

I boot, ejecuta el comando por defecto de inicio, almacenadoen bootcmd

I bootm <address>, inicia la imagen del kernel cargada en unadireccion de memoria RAM dada

I ext2load, carga un archivo desde el sistema de archivos ext2a la RAM

I Y tambien ext2ls para ver los archivos, ext2info parainformacion

I fatload, carga un archivo desde el sistema de archivos FAT ala RAM

I Tambien fatls y fatinfo

I tftp, carga un archivo desde la red a la RAM

I ping, para probar la red

DSI - FCEIA http://dsi.fceia.unr.edu.ar 99/263

Comandos importantes (2)

I loadb, loads, loady, carga un archivo desde la linea serie enRAM

I usb, para inicializar y controlar el sistema USB,principalmente utilizado para dispositivos de almacenamientoUSB como ser pendrives

I mmc, para inicializar y controlar el sistema MMC, utilizado porlas tarjetas SD y microSD

I nand, para borrar, leer y escribir contenidos a la flash NANDI erase, protect, cp, para borrar, proteger y escribir la flash

NORI md, muestra los contenidos de la memoria. Puede ser de

utilidad verificar los contenidos cargados en la memoria, omirar los registros del Hardware.

I mm, modifica el contenido de la memoria. Puede ser util paramodificar directamente los registros de Hardware, parapropositos de prueba.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 100/263

Comandos de variables de entorno (1)

I U-Boot se puede configurar a traves de variables de entorno,que afectan al comportamiento de los diferentes comandos.

I Las variables de entorno se cargan de flash a RAM al inicio deU-Boot, se puede modificar y guardar de nuevo en flash parapersistencia

I Hay una ubicacion dedicada en flash (o en el almacenamientode MMC) para almacenar el entorno de U-Boot, definido en elarchivo de configuracion de la tarjeta

DSI - FCEIA http://dsi.fceia.unr.edu.ar 101/263

Comandos de variables de entorno (2)

Comandos para manipular las variables de entorno:

I printenv

Muestra todas las variables

I printenv <variable-name>

Muestra el valor de una variable

I setenv <variable-name> <variable-value>

Cambia el valor de una variable, solo en RAM

I editenv <variable-name>

Modifica el valor de una variable, solo en RAM

I saveenv

Guarda el estado actual del entorno en flash

DSI - FCEIA http://dsi.fceia.unr.edu.ar 102/263

Comandos de variables de entorno - Ejemplo

u-boot # printenv

baudrate=19200

ethaddr=00:40:95:36:35:33

netmask=255.255.255.0

ipaddr=10.0.0.11

serverip=10.0.0.1

stdin=serial

stdout=serial

stderr=serial

u-boot # printenv serverip

serverip=10.0.0.1

u-boot # setenv serverip 10.0.0.100

u-boot # saveenv

DSI - FCEIA http://dsi.fceia.unr.edu.ar 103/263

Variables importantes del env de U-Boot

I bootcmd, contiene el comando que U-Boot ejecutara de formaautomatica al momento de iniciar despues de una esperaconfigurable, si el proceso no es interrumpido

I bootargs, contiene los argumentos pasados al kernel deLinux, contains the arguments passed to the Linux kernel,cubierto mas tarde

I serverip, la direccion IP del servidor que U-Boot contactarapara los comandos relacionados con la red

I ipaddr, la direccion IP que U-Boot va a usar

I netmask, la mascara de red para contactar al servidor

I ethaddr, la direccion MAC, se puede asignar solo una vez

I bootdelay, la espera en segundos antes de que U-Bootejecute bootcmd

I autostart, si es si, U-Boot inicia automaticamente unaimagen que haya sido cargada en memoria

DSI - FCEIA http://dsi.fceia.unr.edu.ar 104/263

Scripts en variables de entorno

I Las variables de entorno pueden contener pequenos scripts,para ejecutar varios comandos y probar los resultados de loscomandos.

I Util para automatizar el inicio o el proceso de mejoraI Varios comandos pueden ser enganchados utilizando el

operador ;I Las pruebas se pueden realizar haciendo

if command ; then ... ; else ... ; fiI Los Scripts se ejecutan haciendo run <variable-name>I Se pueden referenciar otras variables haciendo

${variable-name}

I EjemploI setenv mmc-boot ’if fatload mmc 0 80000000 boot.

ini; then source; else if fatload mmc 0 80000000

uImage; then run mmc-bootargs; bootm; fi; fi’

DSI - FCEIA http://dsi.fceia.unr.edu.ar 105/263

Transfiriendo archivos hacia el destino

I U-Boot se usa principalmente para cargar e iniciar una imagendel kernel, pero tambien permite cambiar la imagen del kernely el sistema de archivos raız almacenado en flash

I Los archivos deben intercambiarse entre el destino y laestacion de trabajo de desarrollo. Esto es posible:

I A traves de la red si el destino tiene una conexion Ethernet yU-Boot contiene un controlador para el chip Ethernet. Esta esla solucion mas rapida y eficiente.

I A traves de una llave USB, si U-Boot soporta el controladorUSB de su plataforma

I A traves de una tarjeta SD o microSD, si U-Boot admite elcontrolador MMC de su plataforma

I A traves del puerto serie

DSI - FCEIA http://dsi.fceia.unr.edu.ar 106/263

TFTP

I La transferencia sobre la red desde la estacion de desarrollo yU-Boot en el destino se realiza a traves de TFTP

I Trivial File Transfer ProtocolI Algo similar a FTP, pero sin autenticacion sobre UDP

I Un servidor TFTP es necesario en la estacion de trabajo dedesarrollo

I sudo apt-get install tftpd-hpaI Todos los archivos en /var/lib/tftpboot son visibles a

traves de TFTPI Un cliente TFTP esta disponible en el paquete tftp-hpa, para

pruebas

I Un cliente TFTP se encuentra integrado con U-BootI Configure las variables de entorno ipaddr y serveripI Utilice tftp <address> <filename> para cargar un archivo

DSI - FCEIA http://dsi.fceia.unr.edu.ar 107/263

mkimage de U-boot

I La imagen del nucleo que U-Boot carga e inicia debe estarpreparado, de modo que se anade un encabezado especıfico deU-Boot delante de la imagen

I Este encabezado proporciona detalles como el tamano de laimagen, la direccion de carga esperada, el tipo de compresion,etc.

I Esto se hace con una herramienta que viene en U-Boot,mkimage

I Debian / Ubuntu: simplemente instale el paqueteu-boot-tools.

I O, compılelo usted mismo: simplemente configure U-Bootpara cualquier placa de cualquier arquitectura y compile. Acontinuacion, instale mkimage:cp tools/mkimage /usr/local/bin/

I El destino especial uImage del Makefile del kernel puede luegoser utilizado para generar una imagen de kernel adecuada paraU-Boot.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 108/263

Linux kernel introduction

Linux kernelintroductionFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 109/263

Linux kernel introduction

Linux features

DSI - FCEIA http://dsi.fceia.unr.edu.ar 110/263

History

I The Linux kernel is one component of a system, which alsorequires libraries and applications to provide features to endusers.

I The Linux kernel was created as a hobby in 1991 by a Finnishstudent, Linus Torvalds.

I Linux quickly started to be used as the kernel for free softwareoperating systems

I Linus Torvalds has been able to create a large and dynamicdeveloper and user community around Linux.

I Nowadays, more than one thousand people contribute to eachkernel release, individuals or companies big and small.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 111/263

Linux kernel key features

I Portability and hardwaresupport. Runs on mostarchitectures.

I Scalability. Can run onsuper computers as well ason tiny devices (4 MB ofRAM is enough).

I Compliance to standardsand interoperability.

I Exhaustive networkingsupport.

I Security. It can’t hide itsflaws. Its code is reviewedby many experts.

I Stability and reliability.

I Modularity. Can includeonly what a system needseven at run time.

I Easy to program. You canlearn from existing code.Many useful resources onthe net.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 112/263

Linux kernel in the system

DSI - FCEIA http://dsi.fceia.unr.edu.ar 113/263

Linux kernel main roles

I Manage all the hardware resources: CPU, memory, I/O.

I Provide a set of portable, architecture and hardwareindependent APIs to allow user space applications andlibraries to use the hardware resources.

I Handle concurrent accesses and usage of hardwareresources from different applications.

I Example: a single network interface is used by multiple userspace applications through various network connections. Thekernel is responsible to “multiplex” the hardware resource.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 114/263

System calls

I The main interface between the kernel and user space is theset of system calls

I About 300 system calls that provide the main kernel servicesI File and device operations, networking operations,

inter-process communication, process management, memorymapping, timers, threads, synchronization primitives, etc.

I This interface is stable over time: only new system calls canbe added by the kernel developers

I This system call interface is wrapped by the C library, anduser space applications usually never make a system calldirectly but rather use the corresponding C library function

DSI - FCEIA http://dsi.fceia.unr.edu.ar 115/263

Pseudo filesystems

I Linux makes system and kernel information available in userspace through pseudo filesystems, sometimes also calledvirtual filesystems

I Pseudo filesystems allow applications to see directories andfiles that do not exist on any real storage: they are createdand updated on the fly by the kernel

I The two most important pseudo filesystems areI proc, usually mounted on /proc:

Operating system related information (processes, memorymanagement parameters...)

I sysfs, usually mounted on /sys:Representation of the system as a set of devices and buses.Information about these devices.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 116/263

Inside the Linux kernel

DSI - FCEIA http://dsi.fceia.unr.edu.ar 117/263

Linux license

I The whole Linux sources are Free Software released under theGNU General Public License version 2 (GPL v2).

I For the Linux kernel, this basically implies that:I When you receive or buy a device with Linux on it, you should

receive the Linux sources, with the right to study, modify andredistribute them.

I When you produce Linux based devices, you must release thesources to the recipient, with the same rights, with norestriction.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 118/263

Linux kernel introduction

Linux versioning scheme anddevelopment process

DSI - FCEIA http://dsi.fceia.unr.edu.ar 120/263

Until 2.6 (1)

I One stable major branch every 2 or 3 yearsI Identified by an even middle numberI Examples: 1.0.x, 2.0.x, 2.2.x, 2.4.x

I One development branch to integrate new functionalities andmajor changes

I Identified by an odd middle numberI Examples: 2.1.x, 2.3.x, 2.5.xI After some time, a development version becomes the new base

version for the stable branch

I Minor releases once in while: 2.2.23, 2.5.12, etc.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 121/263

Until 2.6 (2)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 122/263

Changes since Linux 2.6

I Since 2.6.0, kernel developers have been able to introducelots of new features one by one on a steady pace, withouthaving to make disruptive changes to existing subsystems.

I Since then, there has been no need to create a newdevelopment branch massively breaking compatibility with thestable branch.

I Thanks to this, more features are released to users at afaster pace.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 123/263

3.x stable branch

I From 2003 to 2011, the official kernel versions were named2.6.x.

I Linux 3.0 was released in July 2011I This is only a change to the numbering scheme

I Official kernel versions are now named 3.x (3.0, 3.1, 3.2,etc.)

I Stabilized versions are named 3.x.y (3.0.2, 3.4.3, etc.)I It effectively only removes a digit compared to the previous

numbering scheme

DSI - FCEIA http://dsi.fceia.unr.edu.ar 124/263

New development model

Using merge and bug fixing windows

DSI - FCEIA http://dsi.fceia.unr.edu.ar 125/263

New development model - Details

I After the release of a 3.x version (for example), a two-weeksmerge window opens, during which major additions aremerged.

I The merge window is closed by the release of test version3.(x+1)-rc1

I The bug fixing period opens, for 6 to 10 weeks.

I At regular intervals during the bug fixing period,3.(x+1)-rcY test versions are released.

I When considered sufficiently stable, kernel 3.(x+1) isreleased, and the process starts again.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 126/263

More stability for the kernel source tree

I Issue: bug and security fixes only releasedfor most recent stable kernel versions.

I Some people need to have a recent kernel,but with long term support for securityupdates.

I You could get long term support from acommercial embedded Linux provider.

I You could reuse sources for the kernelused in Ubuntu Long Term Supportreleases (5 years of free security updates).

I The http://kernel.org front pageshows which versions will be supported forsome time (up to 2 or 3 years), and whichones won’t be supported any more(”EOL: End Of Life”)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 127/263

What’s new in each Linux release?

I The official list of changes for each Linux release is just ahuge list of individual patches!commit aa6e52a35d388e730f4df0ec2ec48294590cc459Author: Thomas Petazzoni <[email protected]>Date: Wed Jul 13 11:29:17 2011 +0200

at91: at91-ohci: support overcurrent notification

Several USB power switches (AIC1526 or MIC2026) have a digital outputthat is used to notify that an overcurrent situation is takingplace. This digital outputs are typically connected to GPIO inputs ofthe processor and can be used to be notified of these overcurrentsituations.

Therefore, we add a new overcurrent_pin[] array in the at91_usbh_datastructure so that boards can tell the AT91 OHCI driver which pins areused for the overcurrent notification, and an overcurrent_supportedboolean to tell the driver whether overcurrent is supported or not.

The code has been largely borrowed from ohci-da8xx.c andohci-s3c2410.c.

Signed-off-by: Thomas Petazzoni <[email protected]>Signed-off-by: Nicolas Ferre <[email protected]>

I Very difficult to find out the key changes and to get the globalpicture out of individual changes.

I Fortunately, there are some useful resources availableI http://wiki.kernelnewbies.org/LinuxChangesI http://lwn.netI http://linuxfr.org, for French readers

DSI - FCEIA http://dsi.fceia.unr.edu.ar 128/263

Linux kernel introduction

Linux kernel sources

DSI - FCEIA http://dsi.fceia.unr.edu.ar 129/263

Location of kernel sources

I The official versions of the Linux kernel, as released by LinusTorvalds, are available at http://www.kernel.org

I These versions follow the development model of the kernelI However, they may not contain the latest development from a

specific area yet. Some features in development might not beready for mainline inclusion yet.

I Many chip vendors supply their own kernel sourcesI Focusing on hardware support firstI Can have a very important delta with mainline LinuxI Useful only when mainline hasn’t caught up yet.

I Many kernel sub-communities maintain their own kernel, withusually newer but less stable features

I Architecture communities (ARM, MIPS, PowerPC, etc.),device drivers communities (I2C, SPI, USB, PCI, network,etc.), other communities (real-time, etc.)

I No official releases, only development trees are available.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 130/263

Getting Linux sources

I The kernel sources are available fromhttp://kernel.org/pub/linux/kernel as full tarballs(complete kernel sources) and patches (differences betweentwo kernel versions).

I However, more and more people use the git version controlsystem. Absolutely needed for kernel development!

I Fetch the entire kernel sources and historygit clone git://git.kernel.org/pub/scm/linux/

kernel/git/torvalds/linux.gitI Create a branch that starts at a specific stable version

git checkout -b <name-of-branch> v3.11I Web interface available at http://git.kernel.org/cgit/

linux/kernel/git/torvalds/linux.git/tree/.I Read more about Git at http://git-scm.com/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 131/263

Linux kernel size (1)

I Linux 3.10 sources:Raw size: 573 MB (43,000 files, approx 15,800,000 lines)gzip compressed tar archive: 105 MBbzip2 compressed tar archive: 83 MB (better)xz compressed tar archive: 69 MB (best)

I Minimum Linux 3.17 compiled kernel size, booting on theARM Versatile board (hard drive on PCI, ext2 filesystem, ELFexecutable support, framebuffer console and input devices):876 KB (compressed), 2.3 MB (raw)

I Why are these sources so big?Because they include thousands of device drivers, manynetwork protocols, support many architectures andfilesystems...

I The Linux core (scheduler, memory management...) is prettysmall!

DSI - FCEIA http://dsi.fceia.unr.edu.ar 132/263

Getting Linux sources

I Full tarballsI Contain the complete kernel sources: long to download and

uncompress, but must be done at least onceI Example:

http://www.kernel.org/pub/linux/kernel/v3.x/linux-

3.10.9.tar.xz

I Extract command:tar xf linux-3.10.9.tar.xz

I Incremental patches between versionsI It assumes you already have a base version and you apply the

correct patches in the right order. Quick to download andapply

I Examples:http://www.kernel.org/pub/linux/kernel/v3.x/patch-3.10.xz

(3.9 to 3.10)http://www.kernel.org/pub/linux/kernel/v3.x/patch-3.10.9.xz

(3.10 to 3.10.9)

I All previous kernel versions are available inhttp://kernel.org/pub/linux/kernel/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 134/263

Patch

I A patch is the difference between two source treesI Computed with the diff tool, or with more elaborate version

control systems

I They are very common in the open-source community

I Excerpt from a patch:

diff -Nru a/Makefile b/Makefile

--- a/Makefile 2005-03-04 09:27:15 -08:00

+++ b/Makefile 2005-03-04 09:27:15 -08:00

@@ -1,7 +1,7 @@

VERSION = 2

PATCHLEVEL = 6

SUBLEVEL = 11

-EXTRAVERSION =

+EXTRAVERSION = .1

NAME=Woozy Numbat

# *DOCUMENTATION*

DSI - FCEIA http://dsi.fceia.unr.edu.ar 135/263

Contents of a patch

I One section per modified file, starting with a headerdiff -Nru a/Makefile b/Makefile

--- a/Makefile 2005-03-04 09:27:15 -08:00

+++ b/Makefile 2005-03-04 09:27:15 -08:00

I One sub-section per modified part of the file, starting withheader with the affected line numbers@@ -1,7 +1,7 @@

I Three lines of context before the changeVERSION = 2

PATCHLEVEL = 6

SUBLEVEL = 11

I The change itself-EXTRAVERSION =

+EXTRAVERSION = .1

I Three lines of context after the changeNAME=Woozy Numbat

# *DOCUMENTATION*

DSI - FCEIA http://dsi.fceia.unr.edu.ar 136/263

Using the patch command

The patch command:

I Takes the patch contents on its standard input

I Applies the modifications described by the patch into thecurrent directory

patch usage examples:

I patch -p<n> < diff_file

I cat diff_file | patch -p<n>

I xzcat diff_file.xz | patch -p<n>

I bzcat diff_file.bz2 | patch -p<n>

I zcat diff_file.gz | patch -p<n>

I Notes:I n: number of directory levels to skip in the file pathsI You can reverse apply a patch with the -R optionI You can test a patch with --dry-run option

DSI - FCEIA http://dsi.fceia.unr.edu.ar 137/263

Applying a Linux patch

I Two types of Linux patches:I Either to be applied to the previous stable version

(from 3.<x-1> to 3.x)I Or implementing fixes to the current stable version

(from 3.x to 3.x.y)

I Can be downloaded in gzip, bzip2 or xz (much smaller)compressed files.

I Always produced for n=1(that’s what everybody does... do it too!)

I Need to run the patch command inside the kernel sourcedirectory

I Linux patch command line example:

cd linux-3.9

xzcat ../patch-3.10.xz | patch -p1

xzcat ../patch-3.10.9.xz | patch -p1

cd ..; mv linux-3.9 linux-3.10.9

DSI - FCEIA http://dsi.fceia.unr.edu.ar 138/263

Linux kernel introduction

Kernel configuration

DSI - FCEIA http://dsi.fceia.unr.edu.ar 139/263

Kernel configuration and build system

I The kernel configuration and build system is based onmultiple Makefiles

I One only interacts with the main Makefile, present at thetop directory of the kernel source tree

I Interaction takes placeI using the make tool, which parses the MakefileI through various targets, defining which action should be done

(configuration, compilation, installation, etc.). Runmake help to see all available targets.

I ExampleI cd linux-3.6.x/I make <target>

DSI - FCEIA http://dsi.fceia.unr.edu.ar 140/263

Kernel configuration (1)

I The kernel contains thousands of device drivers, filesystemdrivers, network protocols and other configurable items

I Thousands of options are available, that are used toselectively compile parts of the kernel source code

I The kernel configuration is the process of defining the set ofoptions with which you want your kernel to be compiled

I The set of options dependsI On your hardware (for device drivers, etc.)I On the capabilities you would like to give to your kernel

(network capabilities, filesystems, real-time, etc.)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 141/263

Kernel configuration (2)

I The configuration is stored in the .config file at the root ofkernel sources

I Simple text file, key=value style

I As options have dependencies, typically never edited by hand,but through graphical or text interfaces:

I make xconfig, make gconfig (graphical)I make menuconfig, make nconfig (text)I You can switch from one to another, they all load/save the

same .config file, and show the same set of options

I To modify a kernel in a GNU/Linux distribution: theconfiguration files are usually released in /boot/, togetherwith kernel images: /boot/config-3.2.0-31-generic

DSI - FCEIA http://dsi.fceia.unr.edu.ar 142/263

Kernel or module?

I The kernel image is a single file, resulting from the linkingof all object files that correspond to features enabled in theconfiguration

I This is the file that gets loaded in memory by the bootloaderI All included features are therefore available as soon as the

kernel starts, at a time where no filesystem exists

I Some features (device drivers, filesystems, etc.) can howeverbe compiled as modules

I These are plugins that can be loaded/unloaded dynamically toadd/remove features to the kernel

I Each module is stored as a separate file in the filesystem,and therefore access to a filesystem is mandatory to usemodules

I This is not possible in the early boot procedure of the kernel,because no filesystem is available

DSI - FCEIA http://dsi.fceia.unr.edu.ar 143/263

Kernel option types

I There are different types of optionsI bool options, they are either

I true (to include the feature in the kernel) orI false (to exclude the feature from the kernel)

I tristate options, they are eitherI true (to include the feature in the kernel image) orI module (to include the feature as a kernel module) orI false (to exclude the feature)

I int options, to specify integer valuesI hex options, to specify hexadecimal valuesI string options, to specify string values

DSI - FCEIA http://dsi.fceia.unr.edu.ar 144/263

Kernel option dependencies

I There are dependencies between kernel options

I For example, enabling a network driver requires the networkstack to be enabled

I Two types of dependenciesI depends on dependencies. In this case, option A that depends

on option B is not visible until option B is enabledI select dependencies. In this case, with option A depending

on option B, when option A is enabled, option B isautomatically enabled

I make xconfig allows to see all options, even the ones thatcannot be selected because of missing dependencies. In thiscase, they are displayed in gray

DSI - FCEIA http://dsi.fceia.unr.edu.ar 145/263

make xconfig

make xconfig

I The most common graphical interface to configure the kernel.

I Make sure you readhelp -> introduction: useful options!

I File browser: easier to load configuration files

I Search interface to look for parameters

I Required Debian / Ubuntu packages: libqt4-dev g++

(libqt3-mt-dev for older kernel releases)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 146/263

make xconfig screenshot

DSI - FCEIA http://dsi.fceia.unr.edu.ar 147/263

make xconfig search interface

Looks for a keyword in the parameter name. Allows to select orunselect found parameters.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 148/263

Kernel configuration options

DSI - FCEIA http://dsi.fceia.unr.edu.ar 149/263

Corresponding .config file excerpt

Options are grouped by sections and are prefixed with CONFIG_.

#

# CD-ROM/DVD Filesystems

#

CONFIG_ISO9660_FS=m

CONFIG_JOLIET=y

CONFIG_ZISOFS=y

CONFIG_UDF_FS=y

CONFIG_UDF_NLS=y

#

# DOS/FAT/NT Filesystems

#

# CONFIG_MSDOS_FS is not set

# CONFIG_VFAT_FS is not set

CONFIG_NTFS_FS=m

# CONFIG_NTFS_DEBUG is not set

CONFIG_NTFS_RW=y

DSI - FCEIA http://dsi.fceia.unr.edu.ar 150/263

make gconfig

make gconfig

I GTK based graphicalconfiguration interface.Functionality similar to thatof make xconfig.

I Just lacking a searchfunctionality.

I Required Debian packages:libglade2-dev

DSI - FCEIA http://dsi.fceia.unr.edu.ar 151/263

make menuconfig

make menuconfig

I Useful when no graphics areavailable. Pretty convenienttoo!

I Same interface found inother tools: BusyBox,Buildroot...

I Required Debian packages:libncurses-dev

DSI - FCEIA http://dsi.fceia.unr.edu.ar 152/263

make nconfig

make nconfig

I A newer, similar textinterface

I More user friendly (forexample, easier to accesshelp information).

I Required Debian packages:libncurses-dev

DSI - FCEIA http://dsi.fceia.unr.edu.ar 153/263

make oldconfig

make oldconfig

I Needed very often!

I Useful to upgrade a .config file from an earlier kernel release

I Issues warnings for configuration parameters that no longerexist in the new kernel.

I Asks for values for new parameters

If you edit a .config file by hand, it’s strongly recommended torun make oldconfig afterwards!

DSI - FCEIA http://dsi.fceia.unr.edu.ar 154/263

Undoing configuration changes

A frequent problem:

I After changing several kernel configuration settings, yourkernel no longer works.

I If you don’t remember all the changes you made, you can getback to your previous configuration:$ cp .config.old .config

I All the configuration interfaces of the kernel (xconfig,menuconfig, oldconfig...) keep this .config.old backupcopy.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 155/263

Configuration per architecture

I The set of configuration options is architecture dependentI Some configuration options are very architecture-specificI Most of the configuration options (global kernel options,

network subsystem, filesystems, most of the device drivers) arevisible in all architectures.

I By default, the kernel build system assumes that the kernel isbeing built for the host architecture, i.e. native compilation

I The architecture is not defined inside the configuration, but ata higher level

I We will see later how to override this behaviour, to allow theconfiguration of kernels for a different architecture

DSI - FCEIA http://dsi.fceia.unr.edu.ar 156/263

Linux kernel introduction

Compiling and installing the kernelfor the host system

DSI - FCEIA http://dsi.fceia.unr.edu.ar 157/263

Compilacion del nucleo

I makeI en el directorio fuente principal de nucleoI Recuerde ejecutar multiples trabajos en paralelo si es que

posee multiples nucleos. Ejemplo: make -j 4I No es necesario ser administrador!

I Esto generaI vmlinux, the raw uncompressed kernel image, in the ELF

format, useful for debugging purposes, but cannot be bootedI arch/<arch>/boot/*Image, the final, usually compressed,

kernel image that can be bootedI bzImage for x86, zImage for ARM, vmImage.gz for Blackfin,

etc.

I arch/<arch>/boot/dts/*.dtb, compiled Device Tree files(on some architectures)

I All kernel modules, spread over the kernel source tree, as .ko

files.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 158/263

Kernel installation

I make installI Does the installation for the host system by default, so needs

to be run as root. Generally not used when compiling for anembedded system, as it installs files on the developmentworkstation.

I InstallsI /boot/vmlinuz-<version>

Compressed kernel image. Same as the one inarch/<arch>/boot

I /boot/System.map-<version>

Stores kernel symbol addressesI /boot/config-<version>

Kernel configuration for this version

I Typically re-runs the bootloader configuration utility to takethe new kernel into account.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 159/263

Module installation

I make modules_installI Does the installation for the host system by default, so needs

to be run as root

I Installs all modules in /lib/modules/<version>/I kernel/

Module .ko (Kernel Object) files, in the same directorystructure as in the sources.

I modules.alias

Module aliases for module loading utilities. Example line:alias sound-service-?-0 snd_mixer_oss

I modules.dep

Module dependenciesI modules.symbols

Tells which module a given symbol belongs to.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 160/263

Kernel cleanup targets

I Clean-up generated files (to forcere-compilation):make clean

I Remove all generated files. Needed whenswitching from one architecture to another.Caution: it also removes your .config file!make mrproper

I Also remove editor backup and patch reject files(mainly to generate patches):make distclean

DSI - FCEIA http://dsi.fceia.unr.edu.ar 161/263

Linux kernel introduction

Cross-compiling the kernel

DSI - FCEIA http://dsi.fceia.unr.edu.ar 162/263

Cross-compiling the kernel

When you compile a Linux kernel for another CPU architecture

I Much faster than compiling natively, when the target systemis much slower than your GNU/Linux workstation.

I Much easier as development tools for your GNU/Linuxworkstation are much easier to find.

I To make the difference with a native compiler, cross-compilerexecutables are prefixed by the name of the target system,architecture and sometimes library. Examples:mips-linux-gcc, the prefix is mips-linux-

arm-linux-gnueabi-gcc, the prefix is arm-linux-gnueabi-

DSI - FCEIA http://dsi.fceia.unr.edu.ar 163/263

Specifying cross-compilation (1)

The CPU architecture and cross-compiler prefix are defined throughthe ARCH and CROSS_COMPILE variables in the toplevel Makefile.

I ARCH is the name of the architecture. It is defined by thename of the subdirectory in arch/ in the kernel sources

I Example: arm if you want to compile a kernel for the arm

architecture.

I CROSS_COMPILE is the prefix of the cross compilation toolsI Example: arm-linux- if your compiler is arm-linux-gcc

DSI - FCEIA http://dsi.fceia.unr.edu.ar 164/263

Specifying cross-compilation (2)

Two solutions to define ARCH and CROSS_COMPILE:

I Pass ARCH and CROSS_COMPILE on the make command line:make ARCH=arm CROSS_COMPILE=arm-linux- ...

Drawback: it is easy to forget to pass these variables whenyou run any make command, causing your build andconfiguration to be screwed up.

I Define ARCH and CROSS_COMPILE as environment variables:export ARCH=arm

export CROSS_COMPILE=arm-linux-

Drawback: it only works inside the current shell or terminal.You could put these settings in a file that you source everytime you start working on the project. If you only work on asingle architecture with always the same toolchain, you couldeven put these settings in your ~/.bashrc file to make thempermanent and visible from any terminal.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 165/263

Predefined configuration files

I Default configuration files available, per board or per-CPUfamily

I They are stored in arch/<arch>/configs/, and are justminimal .config files

I This is the most common way of configuring a kernel forembedded platforms

I Run make help to find if one is available for your platform

I To load a default configuration file, just runmake acme_defconfig

I This will overwrite your existing .config file!

I To create your own default configuration fileI make savedefconfig, to create a minimal configuration fileI mv defconfig arch/<arch>/configs/myown_defconfig

DSI - FCEIA http://dsi.fceia.unr.edu.ar 166/263

Configuring the kernel

I After loading a default configuration file, you can adjust theconfiguration to your needs with the normal xconfig,gconfig or menuconfig interfaces

I You can also start the configuration from scratch withoutloading a default configuration file

I As the architecture is different from your host architectureI Some options will be different from the native configuration

(processor and architecture specific options, specific drivers,etc.)

I Many options will be identical (filesystems, network protocols,architecture-independent drivers, etc.)

I Make sure you have the support for the right CPU, the rightboard and the right device drivers.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 167/263

Device Tree

I Many embedded architectures have a lot of non-discoverablehardware.

I Depending on the architecture, such hardware is eitherdescribed using C code directly within the kernel, or using aspecial hardware description language in a Device Tree.

I ARM, PowerPC, OpenRISC, ARC, Microblaze are examples ofarchitectures using the Device Tree.

I A Device Tree Source, written by kernel developers, iscompiled into a binary Device Tree Blob, passed at boot timeto the kernel.

I There is one different Device Tree for each board/platformsupported by the kernel, available inarch/arm/boot/dts/<board>.dtb.

I The bootloader must load both the kernel image and theDevice Tree Blob in memory before starting the kernel.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 168/263

Customize your board device tree!

Often needed for embedded board users:

I To describe external devices attachedto non-discoverable busses (such asI2C) and configure them.

I To configure pin muxing: choosingwhat SoC signals are made availableon the board external connectors.

I To configure some system parameters:flash partitions, kernel command line(other ways exist)

I Useful reference: Device Tree forDummies, Thomas Petazzoni (Apr.2014): http://j.mp/1jQU6NR

DSI - FCEIA http://dsi.fceia.unr.edu.ar 169/263

Building and installing the kernel

I Run make

I Copy the final kernel image to the target storageI can be uImage, zImage, vmlinux, bzImage in

arch/<arch>/bootI copying the Device Tree Blob might be necessary as well, they

are available in arch/<arch>/boot/dts

I make install is rarely used in embedded development, asthe kernel image is a single file, easy to handle

I It is however possible to customize the make install

behaviour in arch/<arch>/boot/install.sh

I make modules_install is used even in embeddeddevelopment, as it installs many modules and description files

I make INSTALL_MOD_PATH=<dir>/ modules_installI The INSTALL_MOD_PATH variable is needed to install the

modules in the target root filesystem instead of your host rootfilesystem.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 170/263

Booting with U-Boot

I Recent versions of U-Boot can boot the zImage binary.I Older versions require a special kernel image format: uImage

I uImage is generated from zImage using the mkimage tool. Itis done automatically by the kernel make uImage target.

I On some ARM platforms, make uImage requires passing aLOADADDR environment variable, which indicates at whichphysical memory address the kernel will be executed.

I In addition to the kernel image, U-Boot can also pass aDevice Tree Blob to the kernel.

I The typical boot process is therefore:

1. Load zImage or uImage at address X in memory2. Load <board>.dtb at address Y in memory3. Start the kernel with bootz X - Y (zImage case), or

bootm X - Y (uImage case)The - in the middle indicates no initramfs

DSI - FCEIA http://dsi.fceia.unr.edu.ar 171/263

Kernel command line

I In addition to the compile time configuration, the kernelbehaviour can be adjusted with no recompilation using thekernel command line

I The kernel command line is a string that defines variousarguments to the kernel

I It is very important for system configurationI root= for the root filesystem (covered later)I console= for the destination of kernel messagesI Many more exist. The most important ones are documented in

admin-guide/kernel-parameters in kernel documentation.

I This kernel command line is eitherI Passed by the bootloader. In U-Boot, the contents of the

bootargs environment variable is automatically passed to thekernel

I Specified in the Device Tree (for architectures which use it)I Built into the kernel, using the CONFIG_CMDLINE option.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 172/263

Linux kernel introduction

Using kernel modules

DSI - FCEIA http://dsi.fceia.unr.edu.ar 173/263

Advantages of modules

I Modules make it easy to develop drivers without rebooting:load, test, unload, rebuild, load...

I Useful to keep the kernel image size to the minimum(essential in GNU/Linux distributions for PCs).

I Also useful to reduce boot time: you don’t spend timeinitializing devices and kernel features that you only need later.

I Caution: once loaded, have full control and privileges in thesystem. No particular protection. That’s why only the root

user can load and unload modules.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 174/263

Module dependencies

I Some kernel modules can depend on other modules, whichneed to be loaded first.

I Example: the usb-storage module depends on thescsi_mod, libusual and usbcore modules.

I Dependencies are described in/lib/modules/<kernel-version>/modules.dep

This file is generated when you run make modules_install.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 175/263

Kernel log

When a new module is loaded, related information is available inthe kernel log.

I The kernel keeps its messages in a circular buffer (so that itdoesn’t consume more memory with many messages)

I Kernel log messages are available through the dmesg

command (diagnostic message)

I Kernel log messages are also displayed in the system console(console messages can be filtered by level using the loglevel

kernel parameter, or completely disabled with the quiet

parameter).

I Note that you can write to the kernel log from user space too:echo "<n>Debug info" > /dev/kmsg

DSI - FCEIA http://dsi.fceia.unr.edu.ar 176/263

Module utilities (1)

I modinfo <module_name>

modinfo <module_path>.ko

Gets information about a module: parameters, license,description and dependencies.Very useful before deciding to load a module or not.

I sudo insmod <module_path>.ko

Tries to load the given module. The full path to the moduleobject file must be given.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 177/263

Understanding module loading issues

I When loading a module fails, insmod often doesn’t give youenough details!

I Details are often available in the kernel log.

I Example:

$ sudo insmod ./intr_monitor.ko

insmod: error inserting './intr_monitor.ko': -1 Device or resource busy

$ dmesg

[17549774.552000] Failed to register handler for irq channel 2

DSI - FCEIA http://dsi.fceia.unr.edu.ar 178/263

Module utilities (2)

I sudo modprobe <module_name>

Most common usage of modprobe: tries to load all themodules the given module depends on, and then this module.Lots of other options are available. modprobe automaticallylooks in /lib/modules/<version>/ for the object filecorresponding to the given module name.

I lsmod

Displays the list of loaded modulesCompare its output with the contents of /proc/modules!

DSI - FCEIA http://dsi.fceia.unr.edu.ar 179/263

Module utilities (3)

I sudo rmmod <module_name>

Tries to remove the given module.Will only be allowed if the module is no longer in use (forexample, no more processes opening a device file)

I sudo modprobe -r <module_name>

Tries to remove the given module and all dependent modules(which are no longer needed after removing the module)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 180/263

Passing parameters to modules

I Find available parameters:modinfo snd-intel8x0m

I Through insmod:sudo insmod ./snd-intel8x0m.ko index=-2

I Through modprobe:Set parameters in /etc/modprobe.conf or in any file in/etc/modprobe.d/:options snd-intel8x0m index=-2

I Through the kernel command line, when the driver is builtstatically into the kernel:snd-intel8x0m.index=-2

I snd-intel8x0m is the driver nameI index is the driver parameter nameI -2 is the driver parameter value

DSI - FCEIA http://dsi.fceia.unr.edu.ar 181/263

Check module parameter values

How to find the current values for the parameters of a loadedmodule?

I Check /sys/module/<name>/parameters.

I There is one file per parameter, containing the parametervalue.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 182/263

Useful reading

Linux Kernel in a Nutshell, Dec 2006

I By Greg Kroah-Hartman, O’Reillyhttp://www.kroah.com/lkn/

I A good reference book and guide onconfiguring, compiling and managing theLinux kernel sources.

I Freely available on-line!Great companion to the printed book foreasy electronic searches!Available as single PDF file onhttp://free-electrons.com/

community/kernel/lkn/

I Our rating: 2 stars

DSI - FCEIA http://dsi.fceia.unr.edu.ar 183/263

Linux kernel introduction

Device Tree

DSI - FCEIA http://dsi.fceia.unr.edu.ar 184/263

Vision general

Es una estructura de datos para describir al Hardware Se pasa alKernel en el momento de inicio Es una alternativa a los detalles dela plataforma hardcodeadas

I An example of this would be to describe how the UARTinterfaces with the system, which pins, how they should bemuxed, the device to enable, and which driver to use.

I The original BeagleBone didn’t use the DT, but the recentlyreleased BeagleBone Black was released with the DT and isnow using the 3.8 Linux Kernel.

I The following pages will attempt to break down the concepts,and give examples on howi and why you’d want to use thedevice tree in your every day development and hacking.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 185/263

Model del Device Tree

I Arbol de nodos y propiedadesI Los nodos dan estructuraI Las propiedades agregan detalle

I Pares clave-valor

I propiedad ’compatible’I Cada valor ’compatible’ asociado con un ’binding’

I ’phandles’I secondary connections between nodesI irqs, gpios, mdio, i2s, etc

DSI - FCEIA http://dsi.fceia.unr.edu.ar 186/263

Device Tree Background

The CPU architecture and cross-compiler prefix are defined throughthe ARCH and CROSS_COMPILE variables in the toplevel Makefile.

I ARCH is the name of the architecture. It is defined by thename of the subdirectory in arch/ in the kernel sources

I Example: arm if you want to compile a kernel for the arm

architecture.

I CROSS_COMPILE is the prefix of the cross compilation toolsI Example: arm-linux- if your compiler is arm-linux-gcc

DSI - FCEIA http://dsi.fceia.unr.edu.ar 187/263

Using an Intent to make a photo 3/4

/ {

node1 {

a-string-property = "A string";

a-string-list-property = "first string", "second string";

a-byte-data-property = [0x01 0x23 0x34 0x56];

child-node1 {

first-child-property;

second-child-property = <1>;

a-string-property = "Hello, world";

};

child-node2 {

};

};

node2 {

an-empty-property;

a-cell-property = <1 2 3 4>; /* each number (cell) is a uint32 */

child-node1 {

};

};

};

DSI - FCEIA http://dsi.fceia.unr.edu.ar 188/263

Device Tree Overlays

Two solutions to define ARCH and CROSS_COMPILE:

I Pass ARCH and CROSS_COMPILE on the make command line:make ARCH=arm CROSS_COMPILE=arm-linux- ...

Drawback: it is easy to forget to pass these variables whenyou run any make command, causing your build andconfiguration to be screwed up.

I Define ARCH and CROSS_COMPILE as environment variables:export ARCH=arm

export CROSS_COMPILE=arm-linux-

Drawback: it only works inside the current shell or terminal.You could put these settings in a file that you source everytime you start working on the project. If you only work on asingle architecture with always the same toolchain, you couldeven put these settings in your ~/.bashrc file to make thempermanent and visible from any terminal.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 189/263

Using an Intent to make a photo 3/4

/*

* Copyright (C) 2013 CircuitCo

*

* Virtual cape for UART1 on connector pins P9.24 P9.26

*

* This program is free software; you can redistribute it and/or modify

* it under the terms of the GNU General Public License version 2 as

* published by the Free Software Foundation.

*/

/dts-v1/;

/plugin/;

/ {

compatible = "ti,beaglebone", "ti,beaglebone-black";

/* identification */

part-number = "BB-UART1";

version = "00A0";

/* state the resources this cape uses */

exclusive-use =

/* the pin header uses */

"P9.24", /* uart1_txd */

"P9.26", /* uart1_rxd */

/* the hardware ip uses */

"uart1";

DSI - FCEIA http://dsi.fceia.unr.edu.ar 190/263

Using an Intent to make a photo 3/4

fragment@0 {

target = <&am33xx_pinmux>;

__overlay__ {

bb_uart1_pins: pinmux_bb_uart1_pins {

pinctrl-single,pins = <

0x184 0x20 /* P9.24 uart1_txd.uart1_txd MODE0 OUTPUT (TX) */

0x180 0x20 /* P9.26 uart1_rxd.uart1_rxd MODE0 INPUT (RX) */

>;

};

};

};

fragment@1 {

target = <&uart2>; /* really uart1 */

__overlay__ {

status = "okay";

pinctrl-names = "default";

pinctrl-0 = <&bb_uart1_pins>;

};

};

};

DSI - FCEIA http://dsi.fceia.unr.edu.ar 191/263

Predefined configuration files

I Default configuration files available, per board or per-CPUfamily

I They are stored in arch/<arch>/configs/, and are justminimal .config files

I This is the most common way of configuring a kernel forembedded platforms

I Run make help to find if one is available for your platform

I To load a default configuration file, just runmake acme_defconfig

I This will overwrite your existing .config file!

I To create your own default configuration fileI make savedefconfig, to create a minimal configuration fileI mv defconfig arch/<arch>/configs/myown_defconfig

DSI - FCEIA http://dsi.fceia.unr.edu.ar 192/263

Configuring the kernel

I After loading a default configuration file, you can adjust theconfiguration to your needs with the normal xconfig,gconfig or menuconfig interfaces

I You can also start the configuration from scratch withoutloading a default configuration file

I As the architecture is different from your host architectureI Some options will be different from the native configuration

(processor and architecture specific options, specific drivers,etc.)

I Many options will be identical (filesystems, network protocols,architecture-independent drivers, etc.)

I Make sure you have the support for the right CPU, the rightboard and the right device drivers.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 193/263

Device Tree

I Many embedded architectures have a lot of non-discoverablehardware.

I Depending on the architecture, such hardware is eitherdescribed using C code directly within the kernel, or using aspecial hardware description language in a Device Tree.

I ARM, PowerPC, OpenRISC, ARC, Microblaze are examples ofarchitectures using the Device Tree.

I A Device Tree Source, written by kernel developers, iscompiled into a binary Device Tree Blob, passed at boot timeto the kernel.

I There is one different Device Tree for each board/platformsupported by the kernel, available inarch/arm/boot/dts/<board>.dtb.

I The bootloader must load both the kernel image and theDevice Tree Blob in memory before starting the kernel.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 194/263

Customize your board device tree!

Often needed for embedded board users:

I To describe external devices attachedto non-discoverable busses (such asI2C) and configure them.

I To configure pin muxing: choosingwhat SoC signals are made availableon the board external connectors.

I To configure some system parameters:flash partitions, kernel command line(other ways exist)

I Useful reference: Device Tree forDummies, Thomas Petazzoni (Apr.2014): http://j.mp/1jQU6NR

DSI - FCEIA http://dsi.fceia.unr.edu.ar 195/263

Building and installing the kernel

I Run make

I Copy the final kernel image to the target storageI can be uImage, zImage, vmlinux, bzImage in

arch/<arch>/bootI copying the Device Tree Blob might be necessary as well, they

are available in arch/<arch>/boot/dts

I make install is rarely used in embedded development, asthe kernel image is a single file, easy to handle

I It is however possible to customize the make install

behaviour in arch/<arch>/boot/install.sh

I make modules_install is used even in embeddeddevelopment, as it installs many modules and description files

I make INSTALL_MOD_PATH=<dir>/ modules_installI The INSTALL_MOD_PATH variable is needed to install the

modules in the target root filesystem instead of your host rootfilesystem.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 196/263

Booting with U-Boot

I Recent versions of U-Boot can boot the zImage binary.I Older versions require a special kernel image format: uImage

I uImage is generated from zImage using the mkimage tool. Itis done automatically by the kernel make uImage target.

I On some ARM platforms, make uImage requires passing aLOADADDR environment variable, which indicates at whichphysical memory address the kernel will be executed.

I In addition to the kernel image, U-Boot can also pass aDevice Tree Blob to the kernel.

I The typical boot process is therefore:

1. Load zImage or uImage at address X in memory2. Load <board>.dtb at address Y in memory3. Start the kernel with bootz X - Y (zImage case), or

bootm X - Y (uImage case)The - in the middle indicates no initramfs

DSI - FCEIA http://dsi.fceia.unr.edu.ar 197/263

Kernel command line

I In addition to the compile time configuration, the kernelbehaviour can be adjusted with no recompilation using thekernel command line

I The kernel command line is a string that defines variousarguments to the kernel

I It is very important for system configurationI root= for the root filesystem (covered later)I console= for the destination of kernel messagesI Many more exist. The most important ones are documented in

admin-guide/kernel-parameters in kernel documentation.

I This kernel command line is eitherI Passed by the bootloader. In U-Boot, the contents of the

bootargs environment variable is automatically passed to thekernel

I Specified in the Device Tree (for architectures which use it)I Built into the kernel, using the CONFIG_CMDLINE option.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 198/263

Linux Root Filesystem

Linux RootFilesystemFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 199/263

Linux Root Filesystem

Principle and solutions

DSI - FCEIA http://dsi.fceia.unr.edu.ar 200/263

Filesystems

I Filesystems are used to organize data in directories and fileson storage devices or on the network. The directories and filesare organized as a hierarchy

I In Unix systems, applications and users see a single globalhierarchy of files and directories, which can be composed ofseveral filesystems.

I Filesystems are mounted in a specific location in thishierarchy of directories

I When a filesystem is mounted in a directory (called mountpoint), the contents of this directory reflects the contents ofthe storage device

I When the filesystem is unmounted, the mount point is emptyagain.

I This allows applications to access files and directories easily,regardless of their exact storage location

DSI - FCEIA http://dsi.fceia.unr.edu.ar 201/263

Filesystems (2)

I Create a mount point, which is just a directory$ mkdir /mnt/usbkey

I It is empty$ ls /mnt/usbkey

$

I Mount a storage device in this mount point$ mount -t vfat /dev/sda1 /mnt/usbkey

$

I You can access the contents of the USB key$ ls /mnt/usbkey

docs prog.c picture.png movie.avi

$

DSI - FCEIA http://dsi.fceia.unr.edu.ar 202/263

mount / umount

I mount allows to mount filesystemsI mount -t type device mountpointI type is the type of filesystemI device is the storage device, or network location to mountI mountpoint is the directory where files of the storage device

or network location will be accessibleI mount with no arguments shows the currently mounted

filesystems

I umount allows to unmount filesystemsI This is needed before rebooting, or before unplugging a USB

key, because the Linux kernel caches writes in memory toincrease performance. umount makes sure that these writes arecommitted to the storage.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 203/263

Root filesystem

I A particular filesystem is mounted at the root of the hierarchy,identified by /

I This filesystem is called the root filesystemI As mount and umount are programs, they are files inside a

filesystem.I They are not accessible before mounting at least one

filesystem.

I As the root filesystem is the first mounted filesystem, itcannot be mounted with the normal mount command

I It is mounted directly by the kernel, according to the root=

kernel option

I When no root filesystem is available, the kernel panicsPlease append a correct "root=" boot option

Kernel panic - not syncing: VFS: Unable to mount root fs on unknown block(0,0)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 204/263

Location of the root filesystem

I It can be mounted from different locationsI From the partition of a hard diskI From the partition of a USB keyI From the partition of an SD cardI From the partition of a NAND flash chip or similar type of

storage deviceI From the network, using the NFS protocolI From memory, using a pre-loaded filesystem (by the

bootloader)I etc.

I It is up to the system designer to choose the configuration forthe system, and configure the kernel behaviour with root=

DSI - FCEIA http://dsi.fceia.unr.edu.ar 205/263

Mounting rootfs from storage devices

I Partitions of a hard disk or USB keyI root=/dev/sdXY, where X is a letter indicating the device,

and Y a number indicating the partitionI /dev/sdb2 is the second partition of the second disk drive

(either USB key or ATA hard drive)

I Partitions of an SD cardI root=/dev/mmcblkXpY, where X is a number indicating the

device and Y a number indicating the partitionI /dev/mmcblk0p2 is the second partition of the first device

I Partitions of flash storageI root=/dev/mtdblockX, where X is the partition numberI /dev/mtdblock3 is the fourth partition of a NAND flash chip

(if only one NAND flash chip is present)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 206/263

Mounting rootfs over the network (1)

Once networking works, your root filesystem could be a directoryon your GNU/Linux development host, exported by NFS (NetworkFile System). This is very convenient for system development:

I Makes it very easy to update files on the root filesystem,without rebooting. Much faster than through the serial port.

I Can have a big root filesystem even if you don’t have supportfor internal or external storage yet.

I The root filesystem can be huge. You can even build nativecompiler tools and build all the tools you need on the targetitself (better to cross-compile though).

DSI - FCEIA http://dsi.fceia.unr.edu.ar 207/263

Mounting rootfs over the network (2)

On the development workstation side, a NFS server is needed

I Install an NFS server (example: Debian, Ubuntu)sudo apt-get install nfs-kernel-server

I Add the exported directory to your /etc/exports file:/home/tux/rootfs 192.168.1.111(rw,no_root_squash,no_subtree_check)

I 192.168.1.111 is the client IP addressI rw,no_root_squash,no_subtree_check are the NFS server

options for this directory export.

I Start or restart your NFS server (example: Debian, Ubuntu)sudo /etc/init.d/nfs-kernel-server restart

DSI - FCEIA http://dsi.fceia.unr.edu.ar 208/263

Mounting rootfs over the network (3)

I On the target systemI The kernel must be compiled with

I CONFIG_NFS_FS=y (NFS support)I CONFIG_IP_PNP=y (configure IP at boot time)I CONFIG_ROOT_NFS=y (support for NFS as rootfs)

I The kernel must be booted with the following parameters:I root=/dev/nfs (we want rootfs over NFS)I ip=192.168.1.111 (target IP address)I nfsroot=192.168.1.110:/home/tux/rootfs/ (NFS server

details)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 209/263

Mounting rootfs over the network (4)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 210/263

rootfs in memory: initramfs (1)

I It is also possible to have the root filesystem integrated intothe kernel image

I It is therefore loaded into memory together with the kernelI This mechanism is called initramfs

I It integrates a compressed archive of the filesystem into thekernel image

I Variant: the compressed archive can also be loaded separatelyby the bootloader.

I It is useful for two casesI Fast booting of very small root filesystems. As the filesystem is

completely loaded at boot time, application startup is very fast.I As an intermediate step before switching to a real root

filesystem, located on devices for which drivers not part of thekernel image are needed (storage drivers, filesystem drivers,network drivers). This is always used on the kernel ofdesktop/server distributions to keep the kernel image sizereasonable.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 211/263

rootfs in memory: initramfs (2)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 212/263

rootfs in memory: initramfs (3)

I The contents of an initramfs are defined at the kernelconfiguration level, with the CONFIG_INITRAMFS_SOURCEoption

I Can be the path to a directory containing the root filesystemcontents

I Can be the path to a cpio archiveI Can be a text file describing the contents of the initramfs

(see documentation for details)

I The kernel build process will automatically take the contentsof the CONFIG_INITRAMFS_SOURCE option and integrate theroot filesystem into the kernel image

I Details (in kernel sources):Documentation/filesystems/ramfs-rootfs-initramfs.txt

Documentation/early-userspace/README

DSI - FCEIA http://dsi.fceia.unr.edu.ar 213/263

Linux Root Filesystem

Contents

DSI - FCEIA http://dsi.fceia.unr.edu.ar 214/263

Root filesystem organization

I The organization of a Linux root filesystem in terms ofdirectories is well-defined by the Filesystem HierarchyStandard

I http://www.linuxfoundation.org/collaborate/

workgroups/lsb/fhs

I Most Linux systems conform to this specificationI Applications expect this organizationI It makes it easier for developers and users as the filesystem

organization is similar in all systems

DSI - FCEIA http://dsi.fceia.unr.edu.ar 215/263

Important directories (1)

/bin Basic programs

/boot Kernel image (only when the kernel is loaded from afilesystem, not common on non-x86 architectures)

/dev Device files (covered later)

/etc System-wide configuration

/home Directory for the users home directories

/lib Basic libraries

/media Mount points for removable media

/mnt Mount points for static media

/proc Mount point for the proc virtual filesystem

DSI - FCEIA http://dsi.fceia.unr.edu.ar 216/263

Important directories (2)

/root Home directory of the root user

/sbin Basic system programs

/sys Mount point of the sysfs virtual filesystem

/tmp Temporary files

/usr /usr/bin Non-basic programs/usr/lib Non-basic libraries

/usr/sbin Non-basic system programs

/var Variable data files. This includes spool directoriesand files, administrative and logging data, andtransient and temporary files

DSI - FCEIA http://dsi.fceia.unr.edu.ar 217/263

Separation of programs and libraries

I Basic programs are installed in /bin and /sbin and basiclibraries in /lib

I All other programs are installed in /usr/bin and /usr/sbin

and all other libraries in /usr/lib

I In the past, on Unix systems, /usr was very often mountedover the network, through NFS

I In order to allow the system to boot when the network wasdown, some binaries and libraries are stored in /bin, /sbinand /lib

I /bin and /sbin contain programs like ls, ifconfig, cp,bash, etc.

I /lib contains the C library and sometimes a few other basiclibraries

I All other programs and libraries are in /usr

DSI - FCEIA http://dsi.fceia.unr.edu.ar 218/263

Linux Root Filesystem

Device Files

DSI - FCEIA http://dsi.fceia.unr.edu.ar 219/263

Devices

I One of the kernel important role is to allow applications toaccess hardware devices

I In the Linux kernel, most devices are presented to user spaceapplications through two different abstractions

I Character deviceI Block device

I Internally, the kernel identifies each device by a triplet ofinformation

I Type (character or block)I Major (typically the category of device)I Minor (typically the identifier of the device)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 220/263

Types of devices

I Block devicesI A device composed of fixed-sized blocks, that can be read and

written to store dataI Used for hard disks, USB keys, SD cards, etc.

I Character devicesI Originally, an infinite stream of bytes, with no beginning, no

end, no size. The pure example: a serial port.I Used for serial ports, terminals, but also sound cards, video

acquisition devices, frame buffersI Most of the devices that are not block devices are represented

as character devices by the Linux kernel

DSI - FCEIA http://dsi.fceia.unr.edu.ar 221/263

Devices: everything is a file

I A very important Unix design decision was to represent mostof the “system objects” as files

I It allows applications to manipulate all “system objects” withthe normal file API (open, read, write, close, etc.)

I So, devices had to be represented as files to the applications

I This is done through a special artifact called a device file

I It is a special type of file, that associates a file name visible touser space applications to the triplet (type, major, minor) thatthe kernel understands

I All device files are by convention stored in the /dev directory

DSI - FCEIA http://dsi.fceia.unr.edu.ar 222/263

Device files examples

Example of device files in a Linux system

$ ls -l /dev/ttyS0 /dev/tty1 /dev/sda1 /dev/sda2 /dev/zero

brw-rw---- 1 root disk 8, 1 2011-05-27 08:56 /dev/sda1

brw-rw---- 1 root disk 8, 2 2011-05-27 08:56 /dev/sda2

crw------- 1 root root 4, 1 2011-05-27 08:57 /dev/tty1

crw-rw---- 1 root dialout 4, 64 2011-05-27 08:56 /dev/ttyS0

crw-rw-rw- 1 root root 1, 5 2011-05-27 08:56 /dev/zero

Example C code that uses the usual file API to write data to aserial port

int fd;

fd = open("/dev/ttyS0", O_RDWR);

write(fd, "Hello", 5);

close(fd);

DSI - FCEIA http://dsi.fceia.unr.edu.ar 223/263

Creating device files

I On a basic Linux system, the device files have to be createdmanually using the mknod command

I mknod /dev/<device> [c|b] major minorI Needs root privilegesI Coherency between device files and devices handled by the

kernel is left to the system developer

I On more elaborate Linux systems, mechanisms can be addedto create/remove them automatically when devices appearand disappear

I devtmpfs virtual filesystem, since kernel 2.6.32I udev daemon, solution used by desktop and server Linux

systemsI mdev program, a lighter solution than udev

DSI - FCEIA http://dsi.fceia.unr.edu.ar 224/263

Linux Root Filesystem

Pseudo Filesystems

DSI - FCEIA http://dsi.fceia.unr.edu.ar 225/263

proc virtual filesystem

I The proc virtual filesystem exists since the beginning of LinuxI It allows

I The kernel to expose statistics about running processes in thesystem

I The user to adjust at runtime various system parameters aboutprocess management, memory management, etc.

I The proc filesystem is used by many standard user spaceapplications, and they expect it to be mounted in /proc

I Applications such as ps or top would not work without theproc filesystem

I Command to mount /proc:mount -t proc nodev /proc

I Documentation/filesystems/proc.txt in the kernelsources

I man proc

DSI - FCEIA http://dsi.fceia.unr.edu.ar 226/263

proc contents

I One directory for each running process in the systemI /proc/<pid>I cat /proc/3840/cmdlineI It contains details about the files opened by the process, the

CPU and memory usage, etc.

I /proc/interrupts, /proc/devices, /proc/iomem,/proc/ioports contain general device-related information

I /proc/cmdline contains the kernel command lineI /proc/sys contains many files that can be written to to

adjust kernel parametersI They are called sysctl. See Documentation/sysctl/ in

kernel sources.I Example

echo 3 > /proc/sys/vm/drop_caches

DSI - FCEIA http://dsi.fceia.unr.edu.ar 227/263

sysfs filesystem

I The sysfs filesystem is a feature integrated in the 2.6 Linuxkernel

I It allows to represent in user space the vision that the kernelhas of the buses, devices and drivers in the system

I It is useful for various user space applications that need to listand query the available hardware, for example udev or mdev.

I All applications using sysfs expect it to be mounted in the/sys directory

I Command to mount /sys:mount -t sysfs nodev /sys

I $ ls /sys/

block bus class dev devices firmware

fs kernel module power

DSI - FCEIA http://dsi.fceia.unr.edu.ar 228/263

Linux Root Filesystem

Minimal filesystem

DSI - FCEIA http://dsi.fceia.unr.edu.ar 229/263

Basic applications

I In order to work, a Linux system needs at least a fewapplications

I An init application, which is the first user space applicationstarted by the kernel after mounting the root filesystem

I The kernel tries to run /sbin/init, /bin/init, /etc/initand /bin/sh.

I In the case of an initramfs, it will only look for /init.Another path can be supplied by the rdinit kernel argument.

I If none of them are found, the kernel panics and the bootprocess is stopped.

I The init application is responsible for starting all other userspace applications and services

I Usually a shell, to allow a user to interact with the systemI Basic Unix applications, to copy files, move files, list files

(commands like mv, cp, mkdir, cat, etc.)I These basic components have to be integrated into the root

filesystem to make it usable

DSI - FCEIA http://dsi.fceia.unr.edu.ar 230/263

Overall booting process

DSI - FCEIA http://dsi.fceia.unr.edu.ar 231/263

Overall booting process with initramfs

DSI - FCEIA http://dsi.fceia.unr.edu.ar 232/263

Busybox

BusyboxFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 233/263

Why Busybox?

I A Linux system needs a basic set of programs to workI An init programI A shellI Various basic utilities for file manipulation and system

configuration

I In normal Linux systems, these programs are provided bydifferent projects

I coreutils, bash, grep, sed, tar, wget, modutils, etc. areall different projects

I A lot of different components to integrateI Components not designed with embedded systems constraints

in mind: they are not very configurable and have a wide rangeof features

I Busybox is an alternative solution, extremely common onembedded systems

DSI - FCEIA http://dsi.fceia.unr.edu.ar 234/263

General purpose toolbox: BusyBox

I Rewrite of many useful Unix command line utilitiesI Integrated into a single project, which makes it easy to work

withI Designed with embedded systems in mind: highly configurable,

no unnecessary features

I All the utilities are compiled into a single executable,/bin/busybox

I Symbolic links to /bin/busybox are created for eachapplication integrated into Busybox

I For a fairly featureful configuration, less than 500 KB(statically compiled with uClibc) or less than 1 MB (staticallycompiled with glibc).

I http://www.busybox.net/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 235/263

BusyBox commands!

Commands available in BusyBox 1.13[, [[, addgroup, adduser, adjtimex, ar, arp, arping, ash, awk, basename, bbconfig, bbsh,brctl, bunzip2, busybox, bzcat, bzip2, cal, cat, catv, chat, chattr, chcon, chgrp, chmod,chown, chpasswd, chpst, chroot, chrt, chvt, cksum, clear, cmp, comm, cp, cpio, crond, crontab,cryptpw, cttyhack, cut, date, dc, dd, deallocvt, delgroup, deluser, depmod, devfsd, df,dhcprelay, diff, dirname, dmesg, dnsd, dos2unix, dpkg, dpkg_deb, du, dumpkmap, dumpleases,e2fsck, echo, ed, egrep, eject, env, envdir, envuidgid, ether_wake, expand, expr, fakeidentd,false, fbset, fbsplash, fdflush, fdformat, fdisk, fetchmail, fgrep, find, findfs, fold, free,freeramdisk, fsck, fsck_minix, ftpget, ftpput, fuser, getenforce, getopt, getsebool, getty,grep, gunzip, gzip, halt, hd, hdparm, head, hexdump, hostid, hostname, httpd, hush, hwclock,id, ifconfig, ifdown, ifenslave, ifup, inetd, init, inotifyd, insmod, install, ip, ipaddr,ipcalc, ipcrm, ipcs, iplink, iproute, iprule, iptunnel, kbd_mode, kill, killall, killall5,klogd, lash, last, length, less, linux32, linux64, linuxrc, ln, load_policy, loadfont,loadkmap, logger, login, logname, logread, losetup, lpd, lpq, lpr, ls, lsattr, lsmod, lzmacat,makedevs, man, matchpathcon, md5sum, mdev, mesg, microcom, mkdir, mke2fs, mkfifo, mkfs_minix,mknod, mkswap, mktemp, modprobe, more, mount, mountpoint, msh, mt, mv, nameif, nc, netstat,nice, nmeter, nohup, nslookup, od, openvt, parse, passwd, patch, pgrep, pidof, ping, ping6,pipe_progress, pivot_root, pkill, poweroff, printenv, printf, ps, pscan, pwd, raidautorun,rdate, rdev, readahead, readlink, readprofile, realpath, reboot, renice, reset, resize,restorecon, rm, rmdir, rmmod, route, rpm, rpm2cpio, rtcwake, run_parts, runcon, runlevel,runsv, runsvdir, rx, script, sed, selinuxenabled, sendmail, seq, sestatus, setarch,setconsole, setenforce, setfiles, setfont, setkeycodes, setlogcons, setsebool, setsid,setuidgid, sh, sha1sum, showkey, slattach, sleep, softlimit, sort, split, start_stop_daemon,stat, strings, stty, su, sulogin, sum, sv, svlogd, swapoff, swapon, switch_root, sync, sysctl,syslogd, tac, tail, tar, taskset, tcpsvd, tee, telnet, telnetd, test, tftp, tftpd, time, top,touch, tr, traceroute, true, tty, ttysize, tune2fs, udhcpc, udhcpd, udpsvd, umount, uname,uncompress, unexpand, uniq, unix2dos, unlzma, unzip, uptime, usleep, uudecode, uuencode,vconfig, vi, vlock, watch, watchdog, wc, wget, which, who, whoami, xargs, yes, zcat, zcip

DSI - FCEIA http://dsi.fceia.unr.edu.ar 236/263

Applet highlight: Busybox init

I Busybox provides an implementation of an init program

I Simpler than the init implementation found on desktop/serversystems: no runlevels are implemented

I A single configuration file: /etc/inittabI Each line has the form <id>::<action>:<process>

I Allows to run services at startup, and to make sure thatcertain services are always running on the system

I See examples/inittab in Busybox for details on theconfiguration

DSI - FCEIA http://dsi.fceia.unr.edu.ar 237/263

Applet highlight - BusyBox vi

I If you are using BusyBox, adding vi support only adds 20K.(built with shared libraries, using uClibc).

I You can select which exact features to compile in.

I Users hardly realize that they are using a lightweight viversion!

I Tip: you can learn vi on the desktop, by running thevimtutor command.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 238/263

Configuring BusyBox

I Get the latest stable sources from http://busybox.net

I Configure BusyBox (creates a .config file):I make defconfig

Good to begin with BusyBox.Configures BusyBox with all options for regular users.

I make allnoconfig

Unselects all options. Good to configure only what you need.

I make xconfig (graphical, needs the libqt3-mt-dev

package)or make menuconfig (text)Same configuration interfaces as the ones used by the Linuxkernel (though older versions are used).

DSI - FCEIA http://dsi.fceia.unr.edu.ar 239/263

BusyBox make xconfig

You can choose:

I the commandsto compile,

I and even thecommandoptions andfeatures thatyou need!

DSI - FCEIA http://dsi.fceia.unr.edu.ar 240/263

Compiling BusyBox

I Set the cross-compiler prefix in the configuration interface:BusyBox Settings -> Build Options -

> Cross Compiler prefix

Example: arm-linux-

I Set the installation directory in the configuration interface:BusyBox Settings -> Installation Options -

> BusyBox installation prefix

I Add the cross-compiler path to the PATH environmentvariable:export PATH=/usr/xtools/arm-unknown-linux-

uclibcgnueabi/bin:$PATH

I Compile BusyBox:make

I Install it (this creates a Unix directory structure symbolic linksto the busybox executable):make install

DSI - FCEIA http://dsi.fceia.unr.edu.ar 241/263

Laboratorio practico - A tiny embedded system

I Make Linux boot on a directory onyour workstation, shared by NFS

I Create and configure a minimalisticLinux embedded system

I Install and use BusyBox

I System startup with /sbin/init

I Set up a simple web interface

I Use shared libraries

DSI - FCEIA http://dsi.fceia.unr.edu.ar 242/263

Block filesystems

Block filesystemsFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 243/263

Block vs. flash

I Storage devices are classified in two main types: blockdevices and flash devices

I They are handled by different subsystems and differentfilesystems

I Block devices can be read and written to on a per-blockbasis, without erasing.

I Hard disks, floppy disks, RAM disksI USB keys, Compact Flash, SD card: these are based on flash

storage, but have an integrated controller that emulates ablock device, managing and erasing flash sectors in atransparent way.

I Flash devices can be read, but writing requires erasing, andoften occurs on a larger size than the “block” size.

I NOR flash, NAND flash

DSI - FCEIA http://dsi.fceia.unr.edu.ar 244/263

Block device list

I The list of all block devices available in the system can befound in /proc/partitions

$ cat /proc/partitions

major minor #blocks name

179 0 3866624 mmcblk0

179 1 73712 mmcblk0p1

179 2 3792896 mmcblk0p2

8 0 976762584 sda

8 1 1060258 sda1

8 2 975699742 sda2

I And also in /sys/block/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 245/263

Traditional block filesystems

Traditional filesystems

I Can be left in a non-coherent state after a system crash orsudden poweroff, which requires a full filesystem check afterreboot.

I ext2: traditional Linux filesystem(repair it with fsck.ext2)

I vfat: traditional Windows filesystem(repair it with fsck.vfat on GNU/Linux or Scandisk onWindows)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 246/263

Journaled filesystems

I Designed to stay in acorrect state evenafter system crashesor a sudden poweroff

I All writes are firstdescribed in thejournal before beingcommitted to files

DSI - FCEIA http://dsi.fceia.unr.edu.ar 247/263

Filesystem recovery after crashes

I Thanks to thejournal, the filesystemis never left in acorrupted state

I Recently saved datacould still be lost

DSI - FCEIA http://dsi.fceia.unr.edu.ar 248/263

Journaled block filesystems

Journaled filesystems

I ext3: ext2 with journal extensionext4: the new generation with many improvements.Ready for production. They are the default filesystems for allLinux systems in the world.

I The Linux kernel supports many other filesystems: reiserFS,JFS, XFS, etc. Each of them have their own characteristics,but are more oriented towards server or scientific workloads

I Btrfs (“Butter FS”)The next generation. Great performance. In mainline but stillexperimental.

We recommend ext2 for very small partitions (< 5 MB), becauseother filesystems need too much space for metadata (ext3 andext4 need about 1 MB for a 4 MB partition).

DSI - FCEIA http://dsi.fceia.unr.edu.ar 249/263

Creating ext2/ext3/ext4 volumes

I To create an empty ext2/ext3/ext4 filesystem on a blockdevice or inside an already-existing image file

I mkfs.ext2 /dev/hda3I mkfs.ext3 /dev/sda2I mkfs.ext4 /dev/sda3I mkfs.ext2 disk.img

I To create a filesystem image from a directory containing allyour files and directories

I Use the genext2fs tool, from the package of the same nameI genext2fs -d rootfs/ rootfs.imgI Your image is then ready to be transferred to your block device

DSI - FCEIA http://dsi.fceia.unr.edu.ar 250/263

Mounting filesystem images

I Once a filesystem image has been created, one can access andmodifies its contents from the development workstation, usingthe loop mechanism

I Example:genext2fs -d rootfs/ rootfs.img

mkdir /tmp/tst

mount -t ext2 -o loop rootfs.img /tmp/tst

I In the /tmp/tst directory, one can access and modify thecontents of the rootfs.img file.

I This is possible thanks to loop, which is a kernel driver thatemulates a block device with the contents of a file.

I Do not forget to run umount before using the filesystemimage!

DSI - FCEIA http://dsi.fceia.unr.edu.ar 251/263

F2FS

http://en.wikipedia.org/wiki/F2FS

I Filesystem optimized for block devices based on NAND flash

I Available in the mainline Linux kernel

I Benchmarks: best performer on flash devices most of the time:See http://lwn.net/Articles/520003/

I Technical details: http://lwn.net/Articles/518988/

DSI - FCEIA http://dsi.fceia.unr.edu.ar 252/263

Squashfs

Squashfs: http://squashfs.sourceforge.net

I Read-only, compressed filesystem for block devices. Fine forparts of a filesystem which can be read-only (kernel,binaries...)

I Great compression rate and read access performance

I Used in most live CDs and live USB distributions

I Supports LZO compression for better performance onembedded systems with slow CPUs (at the expense of aslightly degraded compression rate)

I Now supports XZ algorithm, for a much better compressionrate, at the expense of higher CPU usage and time.

Benchmarks: (roughly 3 times smaller than ext3, and 2-4 timesfaster)http://elinux.org/Squash_Fs_Comparisons

DSI - FCEIA http://dsi.fceia.unr.edu.ar 253/263

Squashfs - How to use

I Need to install the squashfs-tools packageI Creation of the image

I On your workstation, create your filesystem image:mksquashfs rootfs/ rootfs.sqfs

I Caution: if the image already exists remove it first,or use the -noappend option.

I Installation of the imageI Let’s assume your partition on the target is in /dev/sdc1I Copy the filesystem image on the device

dd if=rootfs.sqfs of=/dev/sdc1

Be careful when using dd to not overwrite the incorrectpartition!

I Mount your filesystem:mount -t squashfs /dev/sdc1 /mnt/root

DSI - FCEIA http://dsi.fceia.unr.edu.ar 254/263

tmpfs

Not a block filesystem of course!Perfect to store temporary data in RAM: system log files,connection data, temporary files...

I tmpfs configuration:File systems -> Pseudo filesystems

Lives in the Linux file cache. Doesn’t waste RAM: unlikeramdisks, no need to copy files to the file cache, grows andshrinks to accommodate stored files. Saves RAM: can swapout pages to disk when needed.

I How to use: choose a name to distinguish the various tmpfsinstances you could have. Examples:mount -t tmpfs varrun /var/run

mount -t tmpfs udev /dev

See Documentation/filesystems/tmpfs.txt in kernel sources.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 255/263

Mixing read-only and read-write filesystems

Good idea to split your block storage into:

I A compressed read-only partition(Squashfs)Typically used for the root filesystem(binaries, kernel...).Compression saves space. Read-onlyaccess protects your system from mistakesand data corruption.

I A read-write partition with a journaledfilesystem (like ext3)Used to store user or configuration data.Guarantees filesystem integrity afterpower off or crashes.

I Ram storage for temporary files (tmpfs)

DSI - FCEIA http://dsi.fceia.unr.edu.ar 256/263

Laboratorio practico - Block filesystems

I Creating partitions on your blockstorage

I Booting your system with a mix offilesystems: SquashFS for the rootfilesystem (including applications),ext3 for configuration and userdata, and tmpfs for temporarysystem files.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 257/263

References

ReferencesFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 258/263

Books

I Embedded Linux Primer, Second Edition,Prentice HallBy Christopher Hallinan, October 2010Covers a very wide range of interesting topics.http://j.mp/17NYxBP

I Building Embedded Linux Systems, O’ReillyBy Karim Yaghmour, Jon Masters, Gilad Ben-Yossef,Philippe Gerum and others (including MichaelOpdenacker), August 2008http://oreilly.com/catalog/9780596529680/

I Embedded Linux System Design andDevelopmentP. Raghavan, A. Lad, S. Neelakandan, Auerbach,Dec. 2005. Very good coverage of the POSIXprogramming API (still up to date).http://j.mp/19X8iu2

DSI - FCEIA http://dsi.fceia.unr.edu.ar 259/263

Web sites

I ELinux.org, http://elinux.org, a Wiki entirely dedicatedto embedded Linux. Lots of topics covered: real-time,filesystem, multimedia, tools, hardware platforms, etc.Interesting to explore to discover new things.

I LWN, http://lwn.net, very interesting news site aboutLinux in general, and specifically about the kernel. Weeklynewsletter, available for free after one week for non-payingvisitors.

I Linux Gizmos, http://linuxgizmos.com, a news siteabout embedded Linux, mainly oriented on hardwareplatforms related news.

DSI - FCEIA http://dsi.fceia.unr.edu.ar 260/263

International conferences

Useful conferences featuring embedded Linux and kernel topics

I Embedded Linux Conference:http://embeddedlinuxconference.com/

Organized by the Linux Foundation: California (SanFrancisco, Spring), in Europe (Fall). Very interesting kerneland user space topics for embedded systems developers.Presentation slides freely available

I Linux Plumbers, http://linuxplumbersconf.orgConference on the low-level plumbing of Linux: kernel, audio,power management, device management, multimedia, etc.

I FOSDEM: http://fosdem.org (Brussels, February)For developers. Presentations about system development.

I Don’t miss our free conference videos on http://free-

electrons.com/community/videos/conferences/!

DSI - FCEIA http://dsi.fceia.unr.edu.ar 261/263

Last slides

Last slidesFree Electrons

© Copyright 2004-2018, Free Electrons.Creative Commons BY-SA 3.0 license.Corrections, suggestions, contributions and translations are welcome!

Embedded LinuxDevelopers

DSI

DSI - FCEIA http://dsi.fceia.unr.edu.ar 262/263

Last slide

Thank you!And may the Source be with you

DSI - FCEIA http://dsi.fceia.unr.edu.ar 263/263