Notes on "from introduction to mastery of embedded system in maker College" -- 10 comprehensive mastery of embedded system transplantation

 

catalog

 

01 basic concept of embedded, building of embedded development environment, building of target machine, building of TFTP service, building of NFS service

1. System migration overview and environment construction

1. General embedded system software components

2. Conditions and prospects of Linux Application in embedded system

3. Embedded Linux kernel structure

4.Android system

2. Building of embedded development environment

1. Basic hardware composition of embedded Linux cross development environment

2. Startup process of development board

3. Main work of building embedded Linux development environment

4. Building of development host

5.TFTP services

6. Services for NFS

7. Target machine installation (u-boot burn debugging) - SD card required

8.fastboot burn

02 bootloader migration (basic concept of bootloader, common U-boot commands and configuration compilation

1.Bootloader introduction

1. What is Bootloader

2. Characteristics of bootloader

3. Operation mode of bootloader

2. Introduction to common bootloader

3. Introduction to u-boot

4. Introduction to u-boot command

1.printenv displays all environment variables

2.setenv sets new environment variables

3.saveenv saves all currently defined environment variable values into flash

4.tftp downloads programs through the network

5.protect writes to Nor Flash

6.erase Nor FLASH

7.Nand related orders

8.movi command

9.bootcmd self start command

10.bootm kernel-addr ramdisk-addr dtb-addr

11.go addr

5.U-BOOT configuration compilation

1.U-Boot directory structure

2. Compile U-boot

3. Download and burn the u-boot image

03u boot startup process, U-boot migration

1.U-BOOT startup process

1.1u-boot three 2

1.2 start up steps (key points)

2. Source code analysis of u-boot

2.1 first command position

2.2 boot entry of u-boot

2.3 initialization of basic hardware

2.4 most hardware initialization

2.5 switching between two modes of bootloader

3.u-boot boot analysis

3.1u-boot environment variable setting

3.2u-boot startup phase

3.3 Linux kernel startup phase

3.4 root file system phase (running application)

4.U-BOOT migration method

04 Linux kernel analysis (Linux kernel basic concept, Linux kernel startup analysis, Linux kernel debugging method)

1. Basic concepts of Linux kernel

1.1 Linux kernel

1.2 mainstream Linux distributions

1.3 features of Linux kernel

1.4 Linux kernel version

Linux kernel subsystem

1.5 Linux kernel module structure

2.linux kernel compilation (ported)

2.1 compiling kernel make uImage

2.2 compile device tree make dtbs

2.3 Linux kernel code structure (1)

2.4 source code directory structure of Linux system (2)

Linux kernel boot analysis

3. Analysis of startup information of embedded system

3.1u-boot startup phase

3.2 Linux kernel startup phase

3.3 root file system phase (application runnable)

3.4 startup process of embedded system

3.5 kernel startup process

4.Linux kernel debugging method

4.1 kernel debugging method 1: lighting method

4.2 kernel debugging method 2: printk printout information

4.3 kernel debugging method 3: OOP kernel exception information

Linux kernel migration and network card migration

1.Linux kernel configuration compilation

1.1 download kernel source code

1.2 decompression in Linux system

1.3 modify Makefile to specify cross compilation tool chain

1.4 configure kernel make menuconfig

1.5 compiling kernel make uImage

1.6 compile device tree make dtbs

1.7 network card migration

Error analysis

2. Network card migration platform independent

2.1 configure kernel support network

2.2 set device tree to describe the connection between network card and CPU

2.3 modify the file driver/clk/clk.c

3.CPU and device connection description - device tree

3.1 description of CPU internal bus node corresponding to network card

3.2 description of network card node

4. Description of CPU and equipment connection platform equipment

06 third party driver migration (driver compiled into kernel Makefile, image configuration Kconfig, driver module, black and white box comparison)

1. Third party drive black box transplantation

2. Driver compiles into kernel Makefile

2.1 select the drive storage directory (or any directory)

2.2 change the Makefile to make the driver compile into the kernel (synchronous modification, corresponding to the Makefile in the directory)

2.3 change Kconfig (configurable interface)

2.4 compile and copy to the root file system. 2.5 run the test program on the development board to analyze the source of the printing information. 3. Create the device file

3.1 create equipment file

4. Graphical configuration Kconfig

The relationship among make menuconfig, Makefile, Kconfig,. config

4.1 configure Kconfig

5. Compile the driver as an independent module

5.1C programming

5.2 makefile

5.3 compile ko module

Configure as module mode

5.4make modules compiling all modules

5.5 when linux is running, modules can be loaded and unloaded

6. White box transplantation

Black and white box contrast

Drive frame

Character device framework

Character device introduction

Character device driver related

Platform equipment framework

07 root file system production (basic concept of root file system, root file system equipment, access to root file system production)

1. Basic concepts of root file system

1.1 what is the root file system?

1.2 main directory structure of root file system

1.3 placement of procedure documents

1.4 custom application

1.5 placement of library files

2.Linux device files

give an example

2.1 example of character equipment

2.2 example of equipment

2.3 main equipment No. secondary equipment No

3. Create device node

4. Boot process of Linux system

Make root file system

5. Production steps of file system

6.BusyBox project construction system command

7.BusyBox tool installation

8. Testing

File / etc/inittab

File / etc/fstab

File / etc/profile

Make the required rootfs type format

Details of different root file systems

nfs rootfs

CRAMFS

JFFS2 and YAFFS2

EXT2 over RAM disk

Making EXT2 over RAM disk file system

01 basic concept of embedded, building of embedded development environment, building of target machine, building of TFTP service, building of NFS service

1. System migration overview and environment construction

1. General embedded system software components

  • Composition diagram of non os embedded system
  • Composition diagram of os embedded system

2. Conditions and prospects of Linux Application in embedded system

Embedded system is more and more pursuing digitization, networking and intelligence. This requires that the whole embedded system must be open, provide standard API, and can easily communicate with many third-party hardware and software.
Linux is an open source system under the GPL protocol. The kernel can be customized and tailored, has powerful functions, supports a variety of file systems, network functions, and is very suitable for high-end embedded systems.
More importantly, linux not only supports the cpu of X86 architecture, but also supports many cpu/mcu of architecture.
Android system was originally based on linux-2.6.23. Basic hardware requirements armv5 ARM926EJ-S 200Mhz 64M

3. Embedded Linux kernel structure

 

4.Android system

2. Building of embedded development environment

1. Basic hardware composition of embedded Linux cross development environment

  1. Development Host
  2. Target machine
  3. Connecting media

2. Startup process of development board

3. Main work of building embedded Linux development environment

  1. Prepare the development host, target machine (development board) and their connecting media
  2. Prepare target code
  3. Install cross tool chain
  4. Develop the software installed on the host (for the convenience of debugging)
  5. Terminal software (putty, minicom)
  6. tftp service
  7. nfs service
  8. Target machine installation (u-boot burn debugging) SD card mode Fastboot mode (after success, the board has serial port information output)
  9. Host and target function connection
  10. Network automatic tftp loads the kernel and mounts nfs rootfs to start

4. Building of development host

 

ubuntu environment

 

5.TFTP services

 

Host side tftp server configuration

6. Services for NFS

7. Target machine installation (u-boot burn debugging) - SD card required

Make SD card and start it from SD card (using u-boot version 2010, which supports fastboot writing)

Sdfuse_ Copy Q to Linux
Plug SD card into computer and identify
Enter sdfuse_q do the following

 $ sudo ./mkuboot.sh /dev/sdb 

The following message appears, indicating that the SD boot disk is made successfully

Fuse FS4412 trustzone uboot file into SD card
/dev/sdb reader is identified.
u-boot-fs4412.bin fusing...
1029+1 records in
1029+1 records out
527104 bytes (527 kB) copied, 5.31834 s, 99.1 kB/s
u-boot-fs4412.bin image has been fused successfully.
Eject SD card

Turn off the power supply of the development board and set the dial switch SW1 to (1000)(SD start mode)
The SD boot disk just made is inserted into the SD card slot
Turn on the power

8.fastboot burn

	Connect the USB cable to the USB OTG port on the board 
	COM2 port connecting serial port line to board   
	Restart the board and stop it quickly. Input the following command at the serial terminal/*
						  If necessary, format eMMC and create partition
						  $ fdisk -c 0
					    $ fatformat mmc 0:1
					    $ ext3format mmc 0:2
					    $ ext3format mmc 0:3
					    $ ext3format mmc 0:4
    */
  $reset restart switch to sd card 2010  
  $fastboot / / prompts to install the driver. Select the first day_ fastboot in environment building_ Driver installation 	
  Open dos terminal to enter USB_ fastboot_ Tool \ platform Tools Directory input
  > fastboot.exe flash bootloader u-boot-fs4412.bin  /*
          In the same way, you can burn other images
			    > fastboot.exe flash kernel zImage
				  > fastboot.exe flash ramdisk ramdisk-uboot.img
			    > fastboot.exe flash system system.img
			    > fastboot -w
       */
  
  Turn off the power supply of the development board and turn on the power supply after turning the dial switch SW1 to 0110(EMMC start mode)
  Starting from flash's u-boot/*
      If the startup fails, you can recover to SD card through dial switch
      If the boot is successful, you want to restore to the original u-boot boot boot (the first time you enter reset, it will automatically switch back, and you do not need to dial the dial switch)   
    */

 

IP address settings

The board can ping the virtual machine (to close the firewall network card, right-click advanced)
|Board 192.168.2.10|
--------------------------
------------------------
|The IP address of the computer 192.168.2.112 | / / is in the same network segment as the IP address of the board virtual machine, and cannot be the same as their IP address
------------------------
------------------------
|Virtual machine 192.168.2.231|

Make sure that the board and the computer can communicate

Set the ip of the computer network card to 192.168.2.112 255.255.255.0 192.168.9.1
Start the board, quickly press any key to stop at boot, and set the environment variable of u-boot

#setenv serverip 192.168.2.231 / / note that it should be consistent with the ip of ubuntu in the virtual machine
#setenv ipaddr 192.168.2.10
#setenv gatewayip  192.168.2.1

#pri view the effect after setting

FS4412 # pri
baudrate=115200
bootargs=root=/dev/nfs nfsroot=192.168.9.120:/nfs/rootfs rw console=ttySAC2,115200 clk_ignore_unused init=/linuxrc ip=192.168.9.9
bootcmd=tftp 41000000 uImage;tftp 42000000 exynos4412-fs4412.dtb;bootm 41000000 - 42000000
bootdelay=3
ethact=dm9000
ethaddr=11:22:33:44:55:66
gatewayip=192.168.2.1
ipaddr =192.168.2.10
netmask=255.255.255.0
serverip=192.168.2.231

#ping 192.168.2.231
Test whether the network is connected. Note that in u-boot, it can ping the computer, and the computer cannot Ping it. Note: Unplug the jtag cable, or Ping will restart
host 192.168.2.231 is alive //is alive means ok

Confirm that the computer can communicate with the virtual machine

Edit - > virtual network editor - > vmnet0 bridge to (select the network card of the board). / / do not use automic. Specify the corresponding network card manually
Virtual machine - > Settings - > network adapter - > Custom (select VMnet0)
Connect the virtual network card in the virtual machine to the network card actually used by the computer
By selecting VMnet0 and VMnet1. Connecting board or internet switching

Network automatic tftp loads the kernel and mounts nfs rootfs to start

  1. Set tftp mode to load kernel
    setenv bootcmd tftp 41000000 uImage;tftp 42000000 exynos4412-origen.dtb;bootm 41000000 - 42000000
    setenv bootcmd setting environment variable (bootcmd)
    tftp 41000000 uImage; download the kernel uImage from the virtual machine / tftpboot directory to the memory 41000000 of the board through tftp. ; used to split multiple commands
    tftp 42000000 exynos4412-origen.dtb Download the device tree file exynos4412-fs4412.dtb through TFTP to the memory of the board 42000000 places
    bootm 41000000 - 42000000 boot kernel (the kernel uimage is placed at 41000000, and the device tree file is placed at 42000000)

  2. Mount nfs rootfs
    setenv bootargs root=/dev/nfs nfsroot=192.168.2.231:/nfs/rootfs rw console=ttySAC2,115200 clk_ignore_unused init=/linuxrc ip=192.168.2.10

    setenv bootarg sets the environment variable (bootarg is the startup parameter)
    root=/dev/nfs specifies that the root file system type is nfs
    nfsroot=192.168.2.231:/source/rootfs specifies the location of source rootfs (on the machine with ip of 192.168.2.231, under the / source/rootfs directory). Note that / nfs/rootfs must be consistent with the previous NFS service configuration file settings

  3. savenenv / / save environment variables
    Power down and restart the board to see if nfs rootfs can be successfully mounted
    You can see the following message to indicate success
    [root@farsight ]# ls
    etc linuxrc proc sbin tmp var
    bin dev lib mnt root sys usr
    Create files in it and synchronize changes on / nfs/rootfs of the computer

02 bootloader migration (basic concept of bootloader, common U-boot commands and configuration compilation

1.Bootloader introduction

1. What is Bootloader

  • Bootloader is the boot program started by hardware and the premise of operating system;
  • A small piece of code that runs before the operating system kernel or user application runs. Initialize and set the hardware and software to prepare the environment for the final operation of the operating system;
  • In embedded system, Bootloader is usually used to load the whole system.

2. Characteristics of bootloader

  • Bootloader is not an operating system. It is usually developed in assembly language and C language. It needs to be written for a specific hardware platform.
  • When porting the system, first porting the Bootloader for the development board.
  • Bootloader not only depends on the architecture of CPU, but also depends on the configuration of board level devices in embedded system.

3. Operation mode of bootloader

  • Self boot mode: in this mode, Bootloader loads the operating system from a solid-state storage device on the target computer to RAM for operation, and the whole process is not involved by the user.
  • Interactive mode: in this mode, the Bootloader on the target machine will download the kernel image and root file system image from the development Host (Host) to RAM through serial port or network communication means. It can be written to the solid-state storage medium on the target computer by Bootloader, or directly boot the system. You can also receive commands from users through the serial port.

2. Introduction to common bootloader

3. Introduction to u-boot

u-boot(Universal Boot Loader) is a bootloader program developed by German DENX team for a variety of embedded CPU s. Subject to the terms of the GPL.
It evolved from FADSROM, 8xxROM, PPCBOOT and Armboot;
Current version number: refer to Makefile.
http://www.denx.de/wiki/U-Boot/WebHome
Features of U-boot:
Clear code structure, easy to migrate (see directory structure)
Supports multiple processor architectures (see arch catalog)
Support many development boards (there are more than 200 kinds of official packages at present, see board directory)
Rich command and monitoring function
Support network protocol, USB, SD and other protocols and devices
Support file system
More active updates, more users, help solve problems

4. Introduction to u-boot command

Command classification
Environment setting, data transmission, memory access, loading and running

1.printenv displays all environment variables

ORIGEN # pri

2.setenv sets new environment variables

ORIGEN # set myboard FS4412 
ORIGEN # pri

3.saveenv saves all currently defined environment variable values into flash

4.tftp downloads programs through the network

U-boot ා setenv ethaddr 11:22:33:44:55:66 / / set the physical address of the development board

   U-boot # setenv  ipaddr  192.168.2.10
   U-boot # setenv  serverip  192.168.2.231
   U-boot # tftp  41000000  application.bin
   U-boot # tftp  41000000  zImage

5.protect writes to Nor Flash

protect on 0 10000 write protect the interval [0x0, 0x10000]
protect off 0 10000 cancel write protection for the above range

6.erase Nor FLASH

Erase all erase all sectors of FLASH
 erase 0 10000 erase FLASH interval [0x0, 0x10000]

7.Nand related orders

nand read addr off size
nand write addr off size
nand erase [clean] [off size]

The difference between NAND flash and NOR flash https://zhidao.baidu.com/question/1993729068599410707.html
NAND flash by block and NOR flash by byte
NAND flash must be erased before writing

8.movi command

eMMC

movi init —initialization eMMC And display relevant information
movi read u-boot/kernel addr //Read u-boot or kernel. You can choose
movi write u-boot/kernel addr
movi read rootfs addr size
movi write rootfs addr size

9.bootcmd self start command

If the variable is defined, the commands in the environment variable will be executed in self startup mode.
Download the file to the specified address automatically through tftp
U-boot # setenv bootcmd tftp 41000000 uImage; bootm 41000000
U-boot # saveenv

bootargs is a string passed from uboot to kernel to boot parameter
 console=xxx: tell which device the debugging information is output from when the kernel starts. This is serial port 2
 init=xxx: tell the kernel what is linux to the first user process
 root=xxx: tell the kernel where the root file system is
 root=/dev/nfs indicates that the root file system is at the remote end of the network
 nfsroot = (development board) ip:path rw where rw means readable and writable
 ip=xxx: (Ubuntu ip) tells the kernel what the ip address is when the kernel is powered on (static ip allocation)

 

10.bootm kernel-addr ramdisk-addr dtb-addr

The booting kernel is the kernel parameter, and the kernel and ramdisk are usually binary files processed by mkimage.
Start the program automatically from this address

11.go addr

Execute binary code in memory, simply jump to the specified address (run bare metal program)

5.U-BOOT configuration compilation

1.U-Boot directory structure

  • Platform related
    arch, board, include...
  • Platform independent
    common, net, fs, drivers...
  • Tools and documentation
    tools, doc

2. Compile U-boot

  • Compilation of U-boot
    The whole project is compiled through makefile. The Makefile in the top-level directory contains the configuration information of the development board. From the top directory, we call the makefile recursively, and link it to the u-boot image.
  • Makefile in the top directory
    It is responsible for the overall configuration and compilation of u-boot
    Specify the cross toolchain to use in the Makefile
    Configure u-boot: make origen_config
    Compiling: make

use build.sh compile

linux@linux:~/u-boot-2013.01-fs4412$ ./build.sh

see build.sh

#!/bin/sh

sec_path="CodeSign4SecureBoot/"
CPU_JOB_NUM=$(grep processor /proc/cpuinfo | awk '{field=$NF};END{print field+1}')
ROOT_DIR=$(pwd)
CUR_DIR=${ROOT_DIR##*/}

case "$1" in
	clean)
		echo make clean
		make mrproper
		;;
	*)
			
		if [ ! -d $sec_path ]
		then
			echo "**********************************************"
			echo "[ERR]please get the CodeSign4SecureBoot first"
			echo "**********************************************"
			return
		fi
		
		make fs4412_config
		
		make -j$CPU_JOB_NUM
		
		if [ ! -f checksum_bl2_14k.bin ]
		then
			echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			echo "There are some error(s) while building uboot, please use command make to check."
			echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			exit 0
		fi
		
		cp -rf checksum_bl2_14k.bin $sec_path
		cp -rf u-boot.bin $sec_path
		rm checksum_bl2_14k.bin
		
		cd $sec_path
		cat E4412_N.bl1.SCP2G.bin bl2.bin all00_padding.bin u-boot.bin tzsw_SMDK4412_SCP_2GB.bin > u-boot-fs4412.bin
		mv u-boot-fs4412.bin $ROOT_DIR
		
		rm checksum_bl2_14k.bin
		rm u-boot.bin

		echo 
		echo 
		;;
		
esac

Image file generated by U-BOOT compilation

3. Download and burn the u-boot image

Burn the image u generated by compilation- boot.bin
For the first time or when the development board code is damaged and cannot be started normally, JTAG tool can be used for burning
Special burning tools such as h-jtag or DNW
When the u-boot is working, upgrade or modify the u-boot, you can use the command in the u-boot to burn it
Other methods such as SD card and Fastboot command
Image curing location
ROM, NOR FLASH, NAND FLASH EMMC, etc

u-boot-fs4412.bin

  1. u-boot.bin It is generated directly after the source code is compiled by uboot. For a general development board, you can burn and write this file directly
  2. But Samsung's cortex_a9 exynos4412 CPU splits some initialization clock and other codes from uboot, so the compiled u-boot.bin We need to add the part that has been peeled off before it can be used normally
  3. So in build.sh In the script file, in u-boot.bin After the split part is added, u-boot-fs4412.bin is generated

 

03u boot startup process, U-boot migration

1.U-BOOT startup process

1.1u-boot three 2

  1. There are two stages: assembly stage (special function register C cannot be accessed directly, the stack needs to be prepared before C runs), and C stage

  2. Two moves: u-boot self move, kernel move

  3. Twice initialization: basic hardware initialization, most hardware initialization

     First command position (reference u- boot.map )In arch / arm / CPU / armv7 / start. S_ start: b	reset 
     Set to SVC mode msr cpsr,r0
     Turn off MMU cache CPU_ init_ cp15    
     Initialization of basic hardware device board / sampling / fs4412 / lowlevel_ Lowell of init. S_ init   
                             Turn off the interrupt watchdog (the initialization time of clock serial port, flash, memory, etc. may be long, so the watchdog will restart the development board continuously, so before initializing the hardware, first turn off MMU Cache and turn off the interrupt watchdog) 
                             , initialize clock serial port, flash, memory
     Self move to memory relocate_code  
     						(move the rest of the u-boot to memory and run it)
     IRQ stack frame 
     						(the stack must be set before the C code runs.)
     
     Prepare to enter part C bl_ main (refer to u-boot.map  )  
     Most hardware initializes arch \ arm \ lib \ board. C \ board_ init_ Init in F_ sequence 
     Move the kernel to memory and run common / main. C Main_ loop -> getenv ("bootcmd")  
                                bootdelay >=     0 && s    && !abortboot (bootdelay)) 
                                 Run under_ command (bootcmd)
    

In the EMMC of the hair board, after the development board is powered on, the BootLoader runs,

Set to SVC mode, turn off MMUCache, and initialize the basic hardware,

Move to memory (the rest of the uboot program enters memory), set the stack, and prepare to enter the C language part,

Most of the hardware is initialized and the kernel is moved to memory (through the network tftp service, uImage and device tree files are loaded into memory)

Mount the root file system (load rootfs into memory through the network nfs service)

1.2 start up steps (key points)

  1. Power on and start bootloader
    Basic hardware initialization
    Self move to memory
    Move kernel to memory
    Pass kernel start parameter (parmer_struct or taglist)
  2. Load kernel
    a. Decompress / / arch / arm / boot / compressed / head. S
    b. Run the head.S entry of the assembly part of the kernel stext //arch/arm/kernel/head.S
    Check validity (CPU type, machine type)
    c. Run kernel part C start_kernel //init/main.c
    Installation and setup of CPU and machine parameters_ arch
    Basic initialization of interrupt, timing, terminal, memory, etc
    Create core process kernel_init run, start multi task scheduling, idle CPU of original parent process_ IDE
  3. Mount rootfs (mount_root)
  4. Run the application / / the first application is init (specified by init=/linuxrc in bootargs of u-boot)
    a. Run the startup script (run_init_process("/etc/init.d/rcS") / / init parses script execution
    b. Other applications / / usually added at the end of the script (for example, add. / app at the end of rcS)

2. Source code analysis of u-boot

  • Where does the power on system start and where is the startup code?
    After power on, some systems can choose whether to start from NAND flash or Norflash through the level of hardware pin. Here is the specified startup from Nandflash
    The boot code U-boot can't be put in RAM, because it disappears after power failure.

  • Why is boot first set to SVC mode?
    For the sake of security, the CPU itself puts forward a variety of modes to achieve security and efficiency.
    SVC mode is a kind of CPU protection for resources. It is not accessible in normal user mode. It can only be accessed by switching to SVC mode.

  • Why and turn off interrupt, MMU, watchdog, etc?
    At the beginning, for security, the system is purified and other interferences are eliminated. Only u-boot is used to realize simple code transfer,
    Function of. So turn off interrupt to avoid the problem of saving return caused by interrupt interrupt. Turn off MMU, because u-boot software is hardware real address access.
    There is no memory address mapping at all. If the watchdog is not turned off, it will be reset by default. So turn it off

  • Why can't C code be used for initial boot of the device, but assembly code?
    Special instructions, such as operating coprocessor, MMC CASH, switching SVC mode, etc., cannot be done by C.

  • Why do U-BOOT move to RAM?
    In RAM, the speed is faster, but it will be lost due to power failure, so it should be saved in NAND flash or Norflash.
    If you move it, you can run it directly on Norflash. Nandflash is not suitable for direct operation due to its block based operation.

  • How U-boot passes parameters to the kernel. What should I pay attention to when migrating?
    Mode I adopts param_struct: (we are using this method now) see common / CMD_ Optimization of boot. C go command
    The second method is taglist

/- start steps of u-boot (important)
//Stage 1 (compilation)
Set to SVC mode, turn off interrupt, MMU, watchdog / / prepare
Initialization of basic hardware devices / / initialization of clock, serial port, flash, memory, see CPU / arm_ CPU of cortex 8 / start. S_ init_ crit
From move to memory / / copy_uboot_to_ram or relocate
Set up the stack / / stack_setup
Jump to the second stage code entry / / LDR PC_ start_ armboot
//Phase II (C language)
Most hardware initialization / / Lib_ arm/board.c/start_ armboot -> init_ sequence
Move kernel to memory / / common / main. C Main_ Run under loop - > getenv ("bootcmd") bootdelay > = 0 & & S & &! Abortboot (bootdelay))_ command (bootcmd)
Running the kernel

2.1 first command position

{//---u-boot.lds   Or u-boot.map     Indicates the location of the first instruction
	arch/arm/cpu/armv7/start.o     
}   

2.2 boot entry of u-boot

{//---The starting entry of arch / arm / CPU / armv7 / start. S u-boot
_start: b	reset   
	ldr	pc, _undefined_instruction
	ldr	pc, _software_interrupt
	ldr	pc, _prefetch_abort
	ldr	pc, _data_abort
	ldr	pc, _not_used
	ldr	pc, _irq
	ldr	pc, _fiq	
	
reset:
	/*
	 * set the cpu to SVC32 mode
	 */
	mrs	r0, cpsr
	bic	r0, r0, #0x1f
	orr	r0, r0, #0xd3
	msr	cpsr,r0	
	
	bl	cpu_init_cp15   //Turn off interrupt cache MMU, etc
	bl	cpu_init_crit

	bl	_main	         //Jump to part C, arch/arm/lib/board.c (in u-boot.map Search inside_ main) 
		

ENTRY(relocate_code)   //Self moving relocation (see u for operation opportunity)- boot.map  Internal execution position)
	adr	r0, _start
	cmp	r0, r6
	moveq	r9, #0		/* no relocation. relocation offset(r9) = 0 */
	beq	relocate_done		/* skip relocation */
	mov	r1, r6			/* r1 <- scratch for copy_loop */
	ldr	r3, _image_copy_end_ofs
	add	r2, r0, r3		/* r2 <- source end address	    */
copy_loop:
	ldmia	r0!, {r9-r10}		/* copy from source address [r0]    */
	stmia	r1!, {r9-r10}		/* copy to   target address [r1]    */
	cmp	r0, r2			/* until source end address [r2]    */
	blo	copy_loop		
ENDPROC(relocate_code)		
		
		
ENTRY(cpu_init_cp15)
	/*
	 * Invalidate L1 I/D
	 */
	mov	r0, #0			@ set up for MCR
	mcr	p15, 0, r0, c8, c7, 0	@ invalidate TLBs
	mcr	p15, 0, r0, c7, c5, 0	@ invalidate icache

	/*
	 * disable MMU stuff and caches
	 */
	mrc	p15, 0, r0, c1, c0, 0
	bic	r0, r0, #0x00002000	@ clear bits 13 (--V-)
	bic	r0, r0, #0x00000007	@ clear bits 2:0 (-CAM)
	mcr	p15, 0, r0, c1, c0, 0
	mov	pc, lr			@ back to my caller
ENDPROC(cpu_init_cp15)	

	
ENTRY(cpu_init_crit)
	b	lowlevel_init		@ go setup pll,mux,memory   //Location board / sampling / fs4412 / libfs4412. O (in u-boot.map Search for Lowell_ init) 
ENDPROC(cpu_init_crit)	
	
	
}	  

2.3 initialization of basic hardware

{//---board/samsung/fs4412/lowlevel_init.S basic hardware initialization (turn off watchdog interrupt clock initialization serial port initialization nand initialization dram initialization)
lowlevel_init:      //Some initializations have been split into bli or BL1 by Samsung  
	/* init system clock */
	bl system_clock_init

	/* Memory initialize */
	bl mem_ctrl_asm_init

	/* for UART */
	bl uart_asm_init	
	mov	pc, lr	
}	 

2.4 most hardware initialization

{//---arch/arm/lib/board.c initializes most of the hardware and calls the main loop main_loop (see common/main.c)
	init_fnc_t *init_sequence[] = {
		arch_cpu_init,		/* basic arch cpu dependent setup */
		mark_bootstage,
	#if defined(CONFIG_BOARD_EARLY_INIT_F)
		board_early_init_f,
	#endif
		timer_init,		/* initialize timer */
		env_init,		/* initialize environment */
		init_baudrate,		/* initialze baudrate settings */
		serial_init,		/* serial communications setup */
		console_init_f,		/* stage 1 init of console */
		display_banner,		/* say that we are here */
		dram_init,		/* configure available RAM banks */
		NULL,
	};	
		
	
	void board_init_r(gd_t *id, ulong dest_addr)
	{
		board_init();	/* Setup chipselects */
		
		/* main_loop() can return to retry autoboot, if so just run it again. */
		for (;;) {
			main_loop(); //Call main loop_ loop
		}
	}	
	
	void board_init(ulong bootflag)
	{
		for (init_fnc_ptr = init_sequence; *init_fnc_ptr; ++init_fnc_ptr) {  //Most hardware initialization
			if ((*init_fnc_ptr)() != 0) {
				hang ();
			}
		}
	}
	
	
	
}

2.5 switching between two modes of bootloader

{//5.common/main.c / / main loop_ If there is no input before the delay time of bootdelay in loop implementation, bootcmd will be loaded to enter the self startup mode; if there is input, it will enter the interactive mode
  void main_loop (void)
	{
	
		s = getenv ("bootdelay");
		bootdelay = s ? (int)simple_strtol(s, NULL, 10) : CONFIG_BOOTDELAY;
	
	  s = getenv ("bootcmd");  //Get the self starting command such as bootcmd = TFTP 20008000 zimage; go zimage means to load the kernel from the network and run it
	
	
	  if (bootdelay >= 0 && s && !abortboot (bootdelay)) {
        run_command (s, 0);            //If the delay is greater than or equal to zero and no key is received during the delay, run the bootcmd command to boot the kernel. Enter self starting mode
    }
	
	 //Otherwise, enter interactive mode 
		/*
		 * Main Loop for Monitor Command Processing
		 */
		for (;;) {
				len = readline (CONFIG_SYS_PROMPT);      //Read command
		
				rc = run_command (lastcommand, flag);    //Run command

		}
  }	
}  
   
}	
			
}

3.u-boot boot analysis

3.1u-boot environment variable setting

ORIGEN # pri
baudrate=115200
bootargs=root=/dev/nfs nfsroot=192.168.2.231:/nfs/rootfs rw console=ttySAC2,115200 clk_ignore_unused init=/linuxrc ip=192.168.2.10
bootcmd=tftp 41000000 uImage;tftp 42000000 exynos4412-origen.dtb;bootm 41000000 - 42000000
bootdelay=3
ethact=dm9000
ethaddr=11:22:33:44:55:66
fileaddr=42000000
filesize=8400
gatewayip=192.168.2.1
ipaddr=192.168.2.10
myboard=FS4412
netmask=255.255.255.0
serverip=192.168.2.231
stderr=serial
stdin=serial
stdout=serial

Environment size: 498/16380 bytes

3.2u-boot startup phase

{//-------u-boot startup phase
	U-Boot 2013.01 (Aug 24 2014 - 12:01:19) for FS4412
	CPU:	Exynos4412@1000MHz
	Board: FS4412
	DRAM:  1 GiB
	WARNING: Caches not enabled
	MMC:   MMC0:	3728 MB
	In:    serial
	Out:   serial
	Err:   serial
	MMC read: dev # 0, block # 48, count 16 ...16 blocks read: OK
	eMMC CLOSE Success.!!
	Checking Boot Mode ... EMMC4.41
	Net:   dm9000
	Hit any key to stop autoboot:  3  2  1  0 

	dm9000 i/o: 0x5000000, id: 0x90000a46 
	DM9000: running in 16 bit mode
	MAC: 11:22:33:44:55:66
	operating at 100M full duplex mode
	Using dm9000 device
	TFTP from server 192.168.9.120; our IP address is 192.168.9.9  //TFTP 0x41000000uimage corresponding to bootcmd 
	Filename 'uImage'.
	Load address: 0x41000000
	Loading: *#################################################################
		 #################################################################
		 #################################################################
		 #################################################################
		 #################################################################
		 #################################################################
		 #################################################################
		 #################################################################
		 #################################################################
		 #######
		 69.3 KiB/s
	done
	Bytes transferred = 3028040 (2e3448 hex)
	dm9000 i/o: 0x5000000, id: 0x90000a46 
	DM9000: running in 16 bit mode
	MAC: 11:22:33:44:55:66
	operating at 100M full duplex mode
	Using dm9000 device
	TFTP from server 192.168.9.120; our IP address is 192.168.9.9  //tftp 42000000 exynos4412-fs4412.dtb corresponding to bootcmd 
	Filename 'exynos4412-fs4412.dtb'.
	Load address: 0x42000000
	Loading: *#######
		 393.6 KiB/s
	done
	Bytes transferred = 33876 (8454 hex)
	   Booting kernel from Legacy Image at 41000000 ...
	   Image Name:   Linux-3.14.0
	   Image Type:   ARM Linux Kernel Image (uncompressed)
	   Data Size:    3027976 Bytes = 2.9 MiB
	   Load Address: 40008000
	   Entry Point:  40008000
	   Verifying Checksum ... OK
	   Flattened Device Tree blob at 42000000
	   Booting using the fdt blob at 0x42000000
	   Loading Kernel Image ... OK
	   Loading Device Tree to 4fff4000, end 4ffff453 ... OK
	   
	Starting kernel ...   /*Boot kernel (corresponding to bootm 41000000 - 42000000 of bootmmcd)
								If it fails to start here, possible reasons      
						    1.u-boot Parameter setting error. For example, ttySAC2 in bootargs is set to ttySAC1  
						    2.uImage something the matter. Try another OK one, or put this uImage on another board for verification
						    3.If there is a problem with the kernel source code, add the print information trace and turn on the kernel debugging information switch, init \ main. C start_ kernel()
						        If machine type does not match
						    4.Hardware related, such as u-boot initial CPU frequency, wrong frequency division 
						    */    

3.3 Linux kernel startup phase

Booting Linux on physical CPU 0xa00
//init\main.c  start_kernel()
Linux version 3.14.0 (david@ubuntu) (gcc version 4.6.4 (crosstool-NG hg+default-2685dfa9de14 - tc0002) ) #23 SMP PREEMPT Fri Aug 15 11:30:16 CST 2014

CPU: ARMv7 Processor [413fc090] revision 0 (ARMv7), cr=10c5387d

CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache

Machine model: Insignal Origen evaluation board based on Exynos4412

Memory policy: Data cache writealloc

CPU EXYNOS4412 (id 0xe4412011)

Running under secure firmware.

PERCPU: Embedded 7 pages/cpu @eefb6000 s7424 r8192 d13056 u32768

Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 256528

Kernel command line: root=/dev/nfs nfsroot=192.168.9.120:/nfs/rootfs rw console=ttySAC2,115200 init=/linuxrc ip=192.168.9.9  //Analysis of the bootargs parameter passed in from u-boot by kernel

PID hash table entries: 4096 (order: 2, 16384 bytes)

Dentry cache hash table entries: 131072 (order: 7, 524288 bytes)

Inode-cache hash table entries: 65536 (order: 6, 262144 bytes)

Memory: 1016852K/1032192K available (3956K kernel code, 237K rwdata, 1320K rodata, 231K init, 276K bss, 15340K reserved, 270336K highmem)

Virtual kernel memory layout:

    vector  : 0xffff0000 - 0xffff1000   (   4 kB)

    fixmap  : 0xfff00000 - 0xfffe0000   ( 896 kB)

    vmalloc : 0xf0000000 - 0xff000000   ( 240 MB)

    lowmem  : 0xc0000000 - 0xef800000   ( 760 MB)

    pkmap   : 0xbfe00000 - 0xc0000000   (   2 MB)

    modules : 0xbf000000 - 0xbfe00000   (  14 MB)

      .text : 0xc0008000 - 0xc052f41c   (5278 kB)

      .init : 0xc0530000 - 0xc0569d00   ( 232 kB)

      .data : 0xc056a000 - 0xc05a5540   ( 238 kB)

       .bss : 0xc05a554c - 0xc05ea584   ( 277 kB)

SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=4, Nodes=1

Preemptible hierarchical RCU implementation.

	RCU restricting CPUs from NR_CPUS=8 to nr_cpu_ids=4.

RCU: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=4

NR_IRQS:16 nr_irqs:16 16

Exynos4x12 clocks: sclk_apll = 500000000, sclk_mpll = 800000000

	sclk_epll = 96000000, sclk_vpll = 350000000, arm_clk = 1000000000

sched_clock: 32 bits at 200 Hz, resolution 5000000ns, wraps every 10737418240000000ns

Console: colour dummy device 80x30

Calibrating delay loop... 1992.29 BogoMIPS (lpj=4980736)

pid_max: default: 32768 minimum: 301

Mount-cache hash table entries: 2048 (order: 1, 8192 bytes)

Mountpoint-cache hash table entries: 2048 (order: 1, 8192 bytes)

CPU: Testing write buffer coherency: ok

missing device node for CPU 0

missing device node for CPU 1

missing device node for CPU 2

missing device node for CPU 3

CPU0: thread -1, cpu 0, socket 10, mpidr 80000a00

Setting up static identity map for 0x403c0e10 - 0x403c0e68

CPU1: Booted secondary processor

CPU1: thread -1, cpu 1, socket 10, mpidr 80000a01

CPU2: Booted secondary processor

CPU2: thread -1, cpu 2, socket 10, mpidr 80000a02

CPU3: Booted secondary processor

CPU3: thread -1, cpu 3, socket 10, mpidr 80000a03

Brought up 4 CPUs

SMP: Total of 4 processors activated.

CPU: All CPU(s) started in SVC mode.

devtmpfs: initialized

VFP support v0.3: implementor 41 architecture 3 part 30 variant 9 rev 4

pinctrl core: initialized pinctrl subsystem

regulator-dummy: no parameters

NET: Registered protocol family 16

DMA: preallocated 256 KiB pool for atomic coherent allocations

S3C Power Management, Copyright 2004 Simtec Electronics

EXYNOS4x12 PMU Initialize

EXYNOS: Initializing architecture

bio: create slab <bio-0> at 0

VMEM_VDD_2.8V: 2800 mV 

SCSI subsystem initialized

usbcore: registered new interface driver usbfs

usbcore: registered new interface driver hub

usbcore: registered new device driver usb

s3c-i2c 13860000.i2c: slave address 0x00

s3c-i2c 13860000.i2c: bus frequency set to 19 KHz

sec_pmic 0-0066: No interrupt specified, no interrupts

VDD_ALIVE: failed to apply 1100000uV constraint

s5m8767-pmic s5m8767-pmic: regulator init failed for 0

s3c-i2c 13860000.i2c: i2c-0: S3C I2C adapter

Switched to clocksource mct-frc

NET: Registered protocol family 2

TCP established hash table entries: 8192 (order: 3, 32768 bytes)

TCP bind hash table entries: 8192 (order: 5, 163840 bytes)

TCP: Hash tables configured (established 8192 bind 8192)

TCP: reno registered

UDP hash table entries: 512 (order: 2, 24576 bytes)

UDP-Lite hash table entries: 512 (order: 2, 24576 bytes)

NET: Registered protocol family 1

RPC: Registered named UNIX socket transport module.

RPC: Registered udp transport module.

RPC: Registered tcp transport module.

RPC: Registered tcp NFSv4.1 backchannel transport module.

futex hash table entries: 1024 (order: 4, 65536 bytes)

bounce pool size: 64 pages

ROMFS MTD (C) 2007 Red Hat, Inc.

msgmni has been set to 1458

io scheduler noop registered

io scheduler deadline registered

io scheduler cfq registered (default)

dma-pl330 12680000.pdma: Loaded driver for PL330 DMAC-1315632

dma-pl330 12680000.pdma: 	DBUFF-32x4bytes Num_Chans-8 Num_Peri-32 Num_Events-32

dma-pl330 12690000.pdma: Loaded driver for PL330 DMAC-1315632

dma-pl330 12690000.pdma: 	DBUFF-32x4bytes Num_Chans-8 Num_Peri-32 Num_Events-32

dma-pl330 12850000.mdma: Loaded driver for PL330 DMAC-1315632

dma-pl330 12850000.mdma: 	DBUFF-64x8bytes Num_Chans-8 Num_Peri-1 Num_Events-32

Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled

13800000.serial: ttySAC0 at MMIO 0x13800000 (irq = 84, base_baud = 0) is a S3C6400/10

13810000.serial: ttySAC1 at MMIO 0x13810000 (irq = 85, base_baud = 0) is a S3C6400/10

13820000.serial: ttySAC2 at MMIO 0x13820000 (irq = 86, base_baud = 0) is a S3C6400/10

console [ttySAC2] enabled

13830000.serial: ttySAC3 at MMIO 0x13830000 (irq = 87, base_baud = 0) is a S3C6400/10

brd: module loaded

loop: module loaded

dm9000 5000000.ethernet: read wrong id 0x01010101

eth0: dm9000a at f0076000,f0078004 IRQ 167 MAC: 00:0a:2d:a6:55:a2 (platform data)

usbcore: registered new interface driver asix

usbcore: registered new interface driver ax88179_178a

usbcore: registered new interface driver cdc_ether

usbcore: registered new interface driver smsc75xx

usbcore: registered new interface driver smsc95xx

usbcore: registered new interface driver net1080

usbcore: registered new interface driver cdc_subset

usbcore: registered new interface driver zaurus

usbcore: registered new interface driver cdc_ncm

ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver

ehci-exynos: EHCI EXYNOS driver

usbcore: registered new interface driver usb-storage

mousedev: PS/2 mouse device common for all mice

input: 100a0000.keypad as /devices/100a0000.keypad/input/input0

device-mapper: ioctl: 4.27.0-ioctl (2013-10-30) initialised: dm-devel@redhat.com

sdhci: Secure Digital Host Controller Interface driver

sdhci: Copyright(c) Pierre Ossman

s3c-sdhci 12530000.sdhci: clock source 2: mmc_busclk.2 (40000000 Hz)

mmc0: no vqmmc regulator found

mmc0: SDHCI controller on samsung-hsmmc [12530000.sdhci] using ADMA

Synopsys Designware Multimedia Card Interface Driver

dwmmc_exynos 12550000.mmc: no vmmc regulator found: -19

dwmmc_exynos 12550000.mmc: Using internal DMA controller.

dwmmc_exynos 12550000.mmc: Version ID is 240a

dwmmc_exynos 12550000.mmc: DW MMC controller at irq 109, 32 bit host data width, 128 deep fifo

dwmmc_exynos 12550000.mmc: 1 slots initialized

usbcore: registered new interface driver usbhid

usbhid: USB HID core driver

TCP: cubic registered

NET: Registered protocol family 17

NET: Registered protocol family 15

Registering SWP/SWPB emulation handler

VMEM_VDD_2.8V: disabling

regulator-dummy: disabling

drivers/rtc/hctosys.c: unable to open rtc device (rtc0)

mmc1: BKOPS_EN bit is not set

dm9000 5000000.ethernet eth0: link down

mmc_host mmc1: Bus speed (slot 0) = 50000000Hz (slot req 52000000Hz, actual 50000000HZ div = 0)

mmc_host mmc1: Bus speed (slot 0) = 100000000Hz (slot req 52000000Hz, actual 50000000HZ div = 1)

mmc1: new high speed DDR MMC card at address 0001

mmcblk0: mmc1:0001 4YMD3R 3.64 GiB 

mmcblk0boot0: mmc1:0001 4YMD3R partition 1 4.00 MiB

mmcblk0boot1: mmc1:0001 4YMD3R partition 2 4.00 MiB

mmcblk0rpmb: mmc1:0001 4YMD3R partition 3 512 KiB

 mmcblk0: p1 p2 p3 p4

 mmcblk0boot1: unknown partition table

 mmcblk0boot0: unknown partition table

dm9000 5000000.ethernet eth0: link up, 100Mbps, full-duplex, lpa 0x45E1

IP-Config: Guessing netmask 255.255.255.0

IP-Config: Complete:

     device=eth0, hwaddr=00:0a:2d:a6:55:a2, ipaddr=192.168.9.9, mask=255.255.255.0, gw=255.255.255.255

     host=192.168.9.9, domain=, nis-domain=(none)

     bootserver=255.255.255.255, rootserver=192.168.9.120, rootpath=

clk: Not disabling unused clocks

VFS: Mounted root (nfs filesystem) on device 0:10.  /*Mount the root file system (from nfs filesystem, it is known that NFS rootfs is mounted)
  It can also mount jffs2 ramdisk cramfs and other formats rootfs               
      If it fails to start here, possible reasons
      1. bootargs Parameter setting problems, such as setting mtdblock2 to mtdblock3, or path, name is not equal
      2. Set it to nfs mount, and verify whether there is any problem with rootfs content
      3. Is there any problem in the process of making image 
      */			
	
devtmpfs: mounted

Freeing unused kernel memory: 228K (c0530000 - c0569000)  	

3.4 root file system phase (running application)

[root@farsight ]# ls
a.out dev lib mnt root sys usr
bin etc linuxrc proc sbin tmp var
[root@farsight ]# ./a.out
hello

4.U-BOOT migration method

Make good use of the comparison software Beyond

  1. Select the official source version to download, configure and compile
    a. Specify cross compile toolchain
    b. Specify cpu and board (refer to the most similar configuration such as origen)
    c, Compile
  2. Realize serial port information output
    a. Tracking operation path (led lighting method)
    b. Serial port output (check the code of uart initialization, see lowlevel_init.s)
  3. Transplantation of network card (implementation of tftp nfs to facilitate development and debugging)
    a. Register address
    b. Parameter setting
  4. FLASH migration (realize downloading software to FLASH, and the product can run offline)

04 Linux kernel analysis (Linux kernel basic concept, Linux kernel startup analysis, Linux kernel debugging method)

1. Basic concepts of Linux kernel

1.1 Linux kernel

  • Technically speaking, linux is a kernel
  • "Kernel" refers to a system software that provides hardware abstraction layer, disk and file system control, multitasking and other functions. A kernel is not a complete operating system.
  • Generally, the linux system we use is a distribution package (distribution) that integrates linux kernel, tool set, various libraries, desktop manager, applications, etc

1.2 mainstream Linux distributions

  • Debian GNU/Linux
  • Red Hat Linux
  • Fedora Core
  • Ubuntu Linux
  • SUSE Linux
  • Gentoo Linux
  • Asianux
  • Slackware Linux
  • Turbo Linux
  • CentOS

1.3 features of Linux kernel

  • Free and open source
  • Portable, supporting a wide range of hardware platforms
    arm, i386, m68k, m32r,m68knommu, mips, ppc, s390, sh, sparc
  • high scalability
  • Tailorable, scalable, can run on mainframe or PC
  • High reliability and stability
  • Stability is a distinctive feature of linux. The host of linux system is installed,
    It's very common to run continuously for one year without downtime
  • Powerful network function
  • Real multitasking, multiuser system
  • Modular design
  • The module can be loaded and unloaded dynamically, which can reduce the volume of the system. At the same time, it can be used to solve conflicts and debug modules

1.4 Linux kernel version

At present, linux system adopts version number management mode of A.B.C.D

  • A indicates the major version number of linux
  • B indicates the minor version number of linux, B indicates the stable version, and odd indicates the version in development
  • C is the linux release number
  • D is the update version number
    Major version (X.Y)
    1.0 2.0 2.2 2.4 2.6 3.x

Linux kernel subsystem

  • Process management
  • memory management
  • file system
  • Network protocol
  • device management

linux system is not a real-time system (it is made by rotating time slices)
Vxwork of the US military is a real-time system (interrupt preemption)

1.5 Linux kernel module structure

The application accesses the kernel through system call
Kernel access to hardware through mapping

2.linux kernel compilation (ported)

2.1 compiling kernel make uImage

Change the cross compilation tool in makefile first

linux@linux:~/linux-3.14-fs4412$ make uImage 
CHK     include/config/kernel.release
CHK     include/generated/uapi/linux/version.h
CHK     include/generated/utsrelease.h
make[1]: "include/generated/mach-types.h"It's the latest.
CALL    scripts/checksyscalls.sh
CHK     include/generated/compile.h
Kernel: arch/arm/boot/Image is ready
Kernel: arch/arm/boot/zImage is ready
Image arch/arm/boot/uImage is ready
linux@linux:~/linux-3.14-fs4412$ 

2.2 compile device tree make dtbs

linux@linux:~/linux-3.14-fs4412$ make dtbs 
DTC     arch/arm/boot/dts/exynos4210-origen.dtb
DTC     arch/arm/boot/dts/exynos4210-smdkv310.dtb
DTC     arch/arm/boot/dts/exynos4210-trats.dtb
DTC     arch/arm/boot/dts/exynos4210-universal_c210.dtb
DTC     arch/arm/boot/dts/exynos4412-odroidx.dtb
DTC     arch/arm/boot/dts/exynos4412-origen.dtb
DTC     arch/arm/boot/dts/exynos4412-fs4412.dtb
DTC     arch/arm/boot/dts/exynos4412-smdk4412.dtb
DTC     arch/arm/boot/dts/exynos4412-tiny4412.dtb
DTC     arch/arm/boot/dts/exynos4412-trats2.dtb
DTC     arch/arm/boot/dts/exynos5250-arndale.dtb
DTC     arch/arm/boot/dts/exynos5250-smdk5250.dtb
DTC     arch/arm/boot/dts/exynos5250-snow.dtb
DTC     arch/arm/boot/dts/exynos5420-arndale-octa.dtb
DTC     arch/arm/boot/dts/exynos5420-smdk5420.dtb
DTC     arch/arm/boot/dts/exynos5440-sd5v1.dtb
DTC     arch/arm/boot/dts/exynos5440-ssdk5440.dtb

2.3 Linux kernel code structure (1)

2.4 source code directory structure of Linux system (2)

Linux kernel boot analysis

3. Analysis of startup information of embedded system

3.1u-boot startup phase

U-Boot 2013.01 (Aug 24 2014 - 12:01:19) for FS4412
CPU:	Exynos4412@1000MHz
Board: FS4412
DRAM:  1 GiB
......Loading: * ######################
Starting kernel ...

3.2 Linux kernel startup phase

Booting Linux on physical CPU 0xa00
Linux version 3.14.0 (david@ubuntu)
CPU: ARMv7 Processor [413fc090] revision 0 (ARMv7), cr=10c5387d
Machine model: Insignal Origen evaluation board based on Exynos4412
IP-Config: Complete:
VFS: Mounted root (nfs filesystem) on device 0:10

3.3 root file system phase (application runnable)

[root@farsight ]# ls
a.out    dev      lib      mnt      root     sys      usr
bin      etc      linuxrc  proc     sbin     tmp      va

3.4 startup process of embedded system

//Stage 1 (compilation) 
Set to SVC mode, turn off interrupt, MMU, watchdog
 Initialization of basic hardware devices / / initialization of clock, serial port, flash and memory    
Self move to memory          
Set the stack and jump to phase C
 //Phase II (C language)
Most hardware initialization
 Move kernel to memory
 Running the kernel

3.5 kernel startup process

a. Decompress (arch / arm / boot / compressed / head. S)

b. Run the head.S entry stext (arch/arm/kernel/head.S) of the kernel assembly part
Check validity (CPU type, machine type)

c. Run kernel part C start_kernel (init/main.c)
Installation and setup of CPU and machine parameters_ arch
Basic initialization of interrupt, timing, terminal, memory, etc
Create core process kernel_init run, start multi task scheduling

d. Mount rootfs

e. Run the first application init (usually linuxrc)

4.Linux kernel debugging method

4.1 kernel debugging method 1: lighting method

ldr r0, =0x11000c40 @GPK2_7 led2
ldr r1, [r0]
bic r1, r1, #0xf0000000
orr r1, r1, #0x10000000
str r1, [r0]

ldr r0, =0x11000c44
mov r1,#0xff
str r1, [r0]

4.2 kernel debugging method 2: printk printout information

Print function

puts (before kernel decompression)
Printascii (before console initialization)
printk (after kernel decompression, information output is displayed after console initialization)

Print level

#define KERN_EMERG        "<0>"   	/* system is unusable           */
#define KERN_ALERT        "<1>"     /* action must be taken immediately */
#define KERN_CRIT         "<2>"   	/* critical conditions          */
#define KERN_ERR          "<3>"   	/* error conditions         */
#define KERN_WARNING      "<4>"   	/* warning conditions           */
#define KERN_NOTICE       "<5>"     /* normal but significant condition */
#define KERN_INFO         "<6>"   	/* informational            */
#define KERN_DEBUG        "<7>"   	/* debug-level messages

printk( KERN_INFO " \n INFO Level \n");

Viewing and modifying log levels at run time through proc

cat /proc/sys/kernel/printk            Display 4 4 1 7
echo "7 4 1 7" > /proc/sys/kernel/printk  after 
cat /proc/sys/kernel/printk            Display 7 4 1 7

4.3 kernel debugging method 3: OOP kernel exception information

Make a mistake

Modify drivers/char/fs4412_led_drv.c
 At s5pv210_ led_ In the init function, int RET = 0; add the following statement: int * PTR = null; * PTR = 0xff;

Run the kernel to report an error

[    1.165000] Unable to handle kernel NULL pointer dereference at virtual address 00000000
[    1.170000] pgd = c0004000
[    1.175000] [00000000] *pgd=00000000
[    1.175000] Internal error: Oops: 805 [#1] PREEMPT SMP ARM
[    1.180000] Modules linked in:
[    1.185000] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 3.14.0 #25
[    1.190000] task: ee8a0000 ti: ee8a4000 task.ti: ee8a4000
[    1.195000] PC is at s5pv210_led_init+0x18/0x180
[    1.200000] LR is at do_one_initcall+0x30/0x144
[    1.205000] pc : [<c024225c>]    lr : [<c00087b4>]    psr: 60000153
[    1.205000] sp : ee8a5ef8  ip : c059afac  fp : 00000000
[    1.215000] r10: c052d4fc  r9 : c0564b80  r8 : c0242244
[    1.220000] r7 : c05a3400  r6 : c055134c  r5 : 00000000  r4 : ee8a4000
[    1.230000] r3 : 00000055  r2 : c04c0430  r1 : 00000001  r0 : 1f400000
[    1.235000] Flags: nZCv  IRQs on  FIQs off  Mode SVC_32  ISA ARM  Segment kernel
[    1.245000] Control: 10c5387d  Table: 4000404a  DAC: 00000015
[    1.250000] Process swapper/0 (pid: 1, stack limit = 0xee8a4240)
[    1.255000] Stack: (0xee8a5ef8 to 0xee8a6000)

Find the error location (arm none Linux gnueabi addr2line)

According to PC is at s5pv210_led_init+0x18/0x180 knows that the function in error is s5pv210_led_init
 Know the error location according to PC: [< c02425c >]
#Arm-none-linux-gnueabi-addr2line c02425c-e vmlinux-f will show the specific error location in the source code

Linux kernel migration and network card migration

1.Linux kernel configuration compilation

1.1 download kernel source code

(Google searches linux-3.14 tar.xz , a list of many kernel versions will be found soon.)

1.2 decompression in Linux system

( tar -xvf linux-3.14.tar.xz Note that it cannot be decompressed in the shared directory with window s)

linux@linux:~$ ls
deja-dup  develop    Downloads         gcc-4.6.4         linux-3.14.79      linux-5.1.8   Music   Pictures  sdfuse_q   u-boot-2013.01-fs4412         u-boot-fs4412.bin  Videos                Unnamed folder
Desktop   Documents  examples.desktop  gcc-4.6.4.tar.xz  linux-3.14-fs4412  linux_kernel  myfifo  Public    Templates  u-boot-2013.01-fs4412.tar.gz  uImage             vmware-tools-distrib
linux@linux:~$ cd linux-3.14.79/
linux@linux:~/linux-3.14.79$ ls
arch   COPYING  crypto         drivers   fs       init  Kbuild   kernel  MAINTAINERS  mm               modules.order   net     REPORTING-BUGS  scripts   sound       tools  virt     vmlinux.o
block  CREDITS  Documentation  firmware  include  ipc   Kconfig  lib     Makefile     modules.builtin  Module.symvers  README  samples         security  System.map  usr    vmlinux
linux@linux:~/linux-3.14.79$ 

1.3 modify Makefile to specify cross compilation tool chain

Import configuration make exynos_defconfig

(see arch/arm/configs / for the list of configurations.)

Error will be reported in direct compilation. You need to select first

Import configuration

Import configuration, error found, cross compile tool chain needs to be modified in Makefile

Import configuration again

1.4 configure kernel make menuconfig

Activate configuration before compiling kernel

linux@linux:~/linux-3.14.79$ make menuconfig
 *** Unable to find the ncurses libraries or the
 *** required header files.
 *** 'make menuconfig' requires the ncurses libraries.
 *** 
 *** Install ncurses (ncurses-devel) and try again.
 *** 
make[1]: *** [scripts/kconfig/dochecklxdialog] Error 1
make: *** [menuconfig] Error 2

Unable to find the ncurses libraries
resolvent:

linux@linux:~/linux-3.14.79$ sudo apt-get install ncurses-dev
linux@linux:~/linux-3.14.79$ make menuconfig

1.5 compiling kernel make uImage

linux@linux:~/linux-3.14.79$ make uImage

The following message appears to indicate that the compilation is successful

linux@linux:~/linux-3.14.79$ make uImage -j2
CHK     include/config/kernel.release
CHK     include/generated/uapi/linux/version.h
CHK     include/generated/utsrelease.h
make[1]: "include/generated/mach-types.h"It's the latest.
CALL    scripts/checksyscalls.sh
CHK     include/generated/compile.h
Kernel: arch/arm/boot/Image is ready
Kernel: arch/arm/boot/zImage is ready
Image arch/arm/boot/uImage is ready
linux@linux:~/linux-3.14.79$ 

1.6 compile device tree make dtbs

linux@linux:~/linux-3.14.79$ make dtbs

1.7 network card migration

After the development board is powered on and restarted, the kernel is stuck in the Starting kernel


reason:
Because there is no power management unit driver in the original uboot, it can't be used. The uboot needs to be replaced. The current uboot has a power management driver, which can solve the problem of being stuck in the starting kernel.

Power on again after replacing the uboot. After the kernel is started, it is found that the kernel has crash information

Error analysis


  1. After the development board is started, BootLoader runs, tftp downloads the kernel, the kernel is downloaded successfully, and the root file system is mounted through the kernel
  2. There is a parameter bootargs in the uboot environment variable. After bootm starts the kernel, uboot will pass bootargs to the kernel
  3. The kernel knows from bootargs where the root file system is mounted (on a remote computer)
  4. The root file system is mounted by the kernel, which must be mounted through the network cable
  5. The network card on the development board is different from that on Samsung's official demo board (origen board), so it needs to be modified

2. Network card migration platform independent

2.1 configure kernel support network

   $ make menuconfig

Configure network protocol to support TCP/IP

    [*] Networking support   --->     //Note that you need to enter y to select the menu, and then press enter to see the following options
     	Networking options  ---> 
                <*> Packet socket
                <*> Unix domain sockets
	            [*] TCP/IP networking
               	[*]   IP: kernel level autoconfiguration
               	[*]     IP: BOOTP support   

Configure support for network file system NFS

   File systems  --->   
   		[*] Network File Systems  --->
     		   	<*>   NFS client support
    		   	<*>     NFS client support for NFS version 2
               	[*]     NFS client support for NFS version 3
             	[*]     NFS client support for the NFSv3 
                        ACL protocol extension
            	[*]   Root file system on NFS    

Configuration supports dm9000 network card driver

Device Drivers  --->
            [*] Network device support  --->
            	[*]   Ethernet driver support  --->
          			 <*>   DM9000 support       (Only this can be selected in the network card driver, and all others can be removed.)

Network card migration platform related

2.2 set device tree to describe the connection between network card and CPU

$ vim arch/arm/boot/dts/exynos4412-origen.dts   Add the following code before regulators
srom-cs1@5000000 {
    compatible = "simple-bus";
    #address-cells = <1>;
    #size-cells = <1>;
    reg = <0x5000000 0x1000000>;    Corresponding chip manual 3 Memory Map 0 of x0500_0000  And 16 MB 		
    ranges;

    ethernet@5000000 {
         compatible = "davicom,dm9000";  The kernel matches the driver by this name
         reg = <0x5000000 0x2 0x5000004 0x2>;  Register address and data width
         interrupt-parent = <&gpx0>;   Inherited from interrupt controller gpx0
            interrupts = <6 4>; 6  Corresponding interrupt source DM9000_IRQ -> XEINT6 . 4 corresponding active high level-sensitive 	     							
            davicom,no-eeprom;
         mac-address = [00 0a 2d a6 55 a2];
    };
};

 



2.3 modify the file driver/clk/clk.c

static bool clk_ignore_unused;

Change to

static bool clk_ignore_unused = true;      //It means to ignore the unused clock


After modification, power on the development board and restart
Make uimage-j2 means double thread compilation, speeding up compilation time
Successful migration

3.CPU and device connection description - device tree

  1. Device Tree is a data structure that describes hardware information
    Used to manage hardware topology and hardware resource information.
    Device Tree consists of a series of named nodes and properties, and the nodes themselves can contain child nodes.
    The so-called attribute is actually a pair of name and value.
  2. help
    Baidu: linux Device Tree
    Official website: http://www.devicetree.org And http://elinux.org/Device_Tree
    Source code example:
    Description: Documentation/devicetree/bindings/arm
    Source: arch/arm/boot/dts/exynos4412-origen.dts

3.1 description of CPU internal bus node corresponding to network card

Check the schematic diagram to find out the network card chip selection signal control I/O



According to the control I/O, read the chip manual


Finally, it can be found that enable 1 corresponds to bank 1

  • So the address is 0x5000000, and the length is 0x6000000-0x5000000=0x1000000

3.2 description of network card node


View the official cases


4. Description of CPU and equipment connection platform equipment

There is a structure "struct machine" in the kernel_ Desc ", the kernel uses this structure to represent an actual board, and there will be a file to define this structure for each board, which is called platform code;
For example: arch / arm / mach-s5pv21 / mach-smdkv210. C (there is no platform code based on Exynos4412 in the new version of the kernel, here take s5pv210 as an example)

MACHINE_START(SMDKV210, "SMDKV210")
		/* Maintainer: Kukjin Kim <kgene.kim@samsung.com> */
		.atag_offset	= 0x100,
		.init_irq	= s5pv210_init_irq,
		.map_io	= smdkv210_map_io,
		.init_machine	= smdkv210_machine_init,
		.init_time	= samsung_timer_init,
		.restart	= s5pv210_restart,
		.reserve	= &smdkv210_reserve,
MACHINE_END

06 third party driver migration (driver compiled into kernel Makefile, image configuration Kconfig, driver module, black and white box comparison)

1. Third party drive black box transplantation

2. Driver compiles into kernel Makefile

1. First, find out whether the device's driver configuration is supported in the kernel
 2. Drivers not in the kernel are ported in -- third party driver migration

Put the third-party driver code into the driver directory in the linux source tree
 Modify makefile kconfig (interface configuration) 
Modified and newly added code will be recompiled
 If the program needs to run on the board, it needs to be compiled with cross compilation tools
 mknod /dev/led c or b primary device No. secondary device No

2.1 select the drive storage directory (or any directory)

Copy the LED driver to the drivers directory
LED belongs to character device, so it is placed in the drivers/char / directory

2.2 change the Makefile to make the driver compile into the kernel (synchronous modification, corresponding to the Makefile in the directory)


2.3 change Kconfig (configurable interface)

Test driven

Burn image to development board

Driver test code

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>

#define LED_MAGIC 'L'
#define LED_ON  _IOW(LED_MAGIC, 1, int)
#define LED_OFF _IOW(LED_MAGIC, 2, int)

int main(int argc, char **argv)
{
	int fd;
	
	fd = open("/dev/led", O_RDWR);
	if (fd < 0) {
		perror("open");
		exit(1);
	}
	
	printf("open led ok\n");
	
	//Realize LED flashing
	while(1)
	{
	  ioctl(fd, LED_ON); //Lights up
	  usleep(100000);
	  ioctl(fd, LED_OFF); //Lights out
	  usleep(100000);
	}
	
	return 0;
}

2.4 compile and copy to root file system

2.5 run the test program on the development board

Analyze the source of this printed information

3. Device files need to be created

3.1 create equipment file

mknod /dev/led c 501 0


After creating the device file and running the test program, you can see that the LED is flashing

4. Graphical configuration Kconfig

The relationship among make menuconfig, Makefile, Kconfig,. config

When menuconfig is running, it will read all the Kconfig under the kernel and generate the corresponding graphical interface according to the Kconfig
 Makfile specific compiled file
 Kconfig option to generate a graphical interface (show some options in the interface)
	Add a light option in Kconfig
	The interface has been modified, and the Makfile needs to be modified again
	[] there are only two options to compile (y) or not compile (n)  
	There are three options to compile (y), not compile (n), or compile to module (m)
	obj-y obj-n obj-$(CONFIG_XXX)
Convenient drive management

 

4.1 configure Kconfig

Add a light option in Kconfig

linux@linux:~/linux-3.14.79$ make menuconfig

You can see that there is a corresponding option in the graphic interface

Modify Makefile

Choose not to compile the LED driver in the graphic interface to see if it is successful


No compiled LED driver

When the development board is powered on and restarted, it can also be tested that the LED driver is not compiled

5. Compile the driver as an independent module

Driver module learning detailed video
linux kernel module http://www.makeru.com.cn/live/1392_586.html
Driver Junior will also explain in detail

5.1C programming

Create a folder for the driver, copy the file in, and write a makefile for it

5.2 makefile

5.3 compile ko module

  • After making, it will automatically jump into the kernel and use the kernel's make file to compile the current driver into ko file

Configure as module mode


5.4make modules compiling all modules

5.5 when linux is running, modules can be loaded and unloaded

Copy LED driver module to root file system

By manually loading the module insmod *.ko

Uninstall is rmmod

Create device node (entry to application access driver)

Running test driven applications

6. White box transplantation

  1. Print trace
    The so-called white box migration is to add some print information (printk) to the driver code to track
  2. Drive frame
    To add print information, you need to be familiar with the framework

Black and white box contrast

Black box transplantation
	Two ways
		1. Driver compiled into the kernel
			Select source directory
			Modify Makefile
			Modify Kconfig
			
		2. Compile the driver into a separate module
			Configure as module by modifying Kconfig
			Compiling to modules using make modules
			Load module insmod xxx.ko
			Create device node mknod /dev/xxx c xx xx
			Running test driven applications
 White box transplantation
	Need to read the source code and be familiar with the driver framework
	1. Character equipment 2. Platform equipment
		Character device framework
								application
		User Mode					||
									\/
		--------------------------------------------------	
							System Call Interface
									||
		Kernel Mode				\/
							Virture File System(VFS)
								|      |     |
						   Character Block  Network
								|      |     |
							Device interface
									||
									\/
		-------------------------------------------------
		Hardware		Physical Device (Hardware)

 

Drive frame

Character device framework

Character device introduction

1. All equipment is documented
	The operation of the device is read write of the device file
2. open read write ioctl 
3. Number the equipment (consisting of primary and secondary equipment numbers)

 

Character device driver related

1. Register to obtain the device number
 2. Initialize the device
 3. Operating device file_operations		-- open release read write ioctl...
4. Two macro definition modules_ init  module_ Exit two commands insmod rmmod
 5. Register device number_ chrdev_ region
 6. cdev_init initialization character device
 7. cdev_add add character device to the system

The driver is called passively and triggered by the application 
Application's open call to driver's file_ Open of operations
 The read of the application is called to the file of the driver_ Read of operations
 The write of the application is called to the file of the driver_ Write of operations
 ioctl of the application is called to the file of the driver_ ioctl of operations
 The close call of the application to the file of the driver_ Releases of operations

 

LED driver code - fs4412_led_drv.c

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>	
#include <linux/cdev.h>
#include <asm/io.h>


#define LED_MAGIC 'L'
#define LED_ON  _IOW(LED_MAGIC, 1, int)
#define LED_OFF _IOW(LED_MAGIC, 2, int)

#define LED_MA   501
#define LED_MI    0
#define LED_NUM   1

#define LED_CON 0x11000C20
#define LED_DAT 0x11000C24

struct cdev cdev;

unsigned int *ledcon;
unsigned int *leddat;

int led_open (struct inode *inode, struct file *file)
{
  printk("led_open\n");

  ledcon = ioremap(LED_CON, 4);  	//Kernel access hardware requires address mapping
  if(ledcon == NULL)
  {
	  printk("ioremap LED_CON error\n");
      return -1;
  }
  writel(0x01, ledcon);  //Set LED3 GPX1_0 is the output mode

 leddat = ioremap(LED_DAT, 4);  	//Kernel access hardware requires address mapping
 if(leddat == NULL)
 {
	 printk("ioremap LED_DAT error\n");
	 return -1;
 }
 writel(1, leddat);	//Set LED3 GPX1_0 output high level
  
  return 0;
}

int led_release(struct inode *inode, struct file *file)
{
   printk("led_close\n");
   return 0;
}

long led_ioctl(struct file *file, unsigned int cmd, unsigned long args)
{
  switch(cmd)
  {
  case  LED_ON:
	   printk("led on ..\n");
       writel(1, leddat);	//Set LED3 GPX1_0 output high level
  	   break;
  case  LED_OFF:
	   printk("led off ..\n");  	
       writel(0, leddat);	//Set LED3 GPX1_0 output high level	  
	   break;
  default:
  	   printk("no command\n");
  	   break;
  }
  return 0;
}

struct file_operations led_fops = { //File operation
	.owner = THIS_MODULE,
    .open = led_open,
    .release =led_release,
    .unlocked_ioctl = led_ioctl,
};

static led_init(void)
{
   int ret;
   dev_t devno = MKDEV(LED_MA, LED_MI); 
   ret= register_chrdev_region(devno, LED_NUM, "newled");  //Registered equipment number
   if(ret)
   {
	   printk("register_chrdev_region error\n");
       return -1;
   }

   cdev_init(&cdev, &led_fops);           //Initialize character device
   ret = cdev_add(&cdev, devno, LED_NUM); //Add character device to the system
   if (ret < 0) {
	   printk("cdev_add error\n");
	   return -1;
   }

	printk("Led init  5    \n");
	return 0;
}

static void led_exit(void)
{
	dev_t devno = MKDEV(LED_MA, LED_MI);
	cdev_del(&cdev);
	unregister_chrdev_region(devno, LED_NUM);  //Unregister	
	printk("Led exit\n");	
}

module_init(led_init);   		//Module loading entry corresponding command insmod
module_exit(led_exit); 			//Command rmmod corresponding to module unloading entry
MODULE_LICENSE("Dual BSD/GPL"); //Free open source statement

 

Platform equipment framework

Introduction of platform equipment


Split the hardware information in the driver and put it in the device tree file

1. The address value of the register is found according to the chip manual and schematic diagram
 2. The physical address cannot be directly used for the operation of register address content. ioremap is required
 3. ioremap maps physical address to virtual address
 4. platform is used to separate hardware information and driver code
 5. The probe function is executed successfully through name matching
 6. Drive through platform_get_resource get hardware device resource
 7. Easy to maintain

07 root file system production (basic concept of root file system, root file system equipment, access to root file system production)

1. Basic concepts of root file system

1.1 what is the root file system?

  • The root file system is the place where all kinds of tools, software, library files, scripts, configuration files and other special files necessary for running and maintaining the system are stored, and various software packages can also be installed.
  • The first file system to run after the whole system is up
  • Other file systems can be built under the root file system

1.2 main directory structure of root file system

1.3 placement of procedure documents

Program file directory

/bin: a basic program that can be executed by both ordinary users and root users

  ping, mknod, mount, tar, grep, gzip, etc

/SBIN: basic program that root user can execute

  int, insmod, route, mkfs, rmmod, ifconfig

/usr/bin: more unnecessary user programs

  autorun, bibtex, latex, biff, ftp, wc, whereis, whoami

/usr/sbin: more unnecessary root programs

  automount, httpd, in.telnetd, in.talkd, sendmail

1.4 custom application

Configure basic linux commands (Embedded Linux is made by busybox)

  cat, chmod, chown, cp, chroot, copi, date, dd, df, dmesg, dos2unix, du, echo, env, expr,  find, grep, gunzip, gzip, halt, id, ifconfig, init, insmod wait

Configure the user's own application
Desktop Manager and so on

1.5 placement of library files

/lib: dynamic library files needed for system and basic commands
/usr/lib: all other libraries
/usr/lib/xxx: private libraries for some Toolkits
For example, / usr/lib/perl5

2.Linux device files

  • All objects (including devices) in Linux system are represented in the form of files
  • In Linux system, all device files (such as device nodes) are usually placed under / dev
  • In embedded system, only necessary device nodes need to be created

give an example

2.1 example of character equipment

ls – l /dev / "c" indicates that the device node is a character device

crw-rw---- 1 root uucp  4,    64 Feb 23 2004 /dev/ttyS0      //4 is the main equipment number, 64 is the secondary equipment number
crw--w---- 1 jdoe tty    136, 1   Feb 23 2004 /dev/pts/1
crw-------- 1 root root   13,   32 Feb 23 2004 /dev/input/mouse0
crw-rw-rw 1 root root   1,    3    Feb 23 2004 /dev/null

Typical equipment
keyboards, mice, parallel port, IrDA, Bluetooth port, consoles, terminals, sound, video...

2.2 example of equipment

"b" indicates that the device node is a block device (ls -l)

brw-rw--- 1 root disk      3, 1 Feb 23 2004 hda1
brw-rw--- 1 jdoe floppy  2, 0 Feb 23 2004 fd0
brw-rw--- 1 root disk      7, 0 Feb 23 2004 loop0
brw-rw--- 1 root disk      1, 1 Feb 23 2004 ram1
brw------- 1 root root      8, 1 Feb 23 2004 sda1

Typical block device

Disk, ramdisk, SD, USB, etc

2.3 main equipment No. secondary equipment No

  • Linux system distinguishes devices by primary device number and secondary device number
  • Main equipment number: (major)
    What kind of devices does the kernel use to distinguish
  • Secondary equipment No.: (minor)
    Distinguish which device in a certain type of device
  • Documentation in kernel/ devices.txt
  •  

3. Create device node

  • The device file cannot be created automatically when the driver is loaded. It should be created by instruction

  • General syntax for creating device files:

      $ mknod /dev/<device> [c|b] <major> <minor>
    

For example:

  $ mknod  /dev/ttySAC0  c  4  64
  $ mknod  /dev/hda1  b  3  1

Basic device nodes

4. Boot process of Linux system

Make root file system

5. Production steps of file system

  1. Make the contents of the root file system
    Creating basic commands with Busybox
    Create the basic directory / lib /etc /var /tmp /dev /sys /proc, etc
    Add glibc basic dynamic library
    Create basic device nodes
    Add startup configuration and script program / etc/inittab /etc/fstab /etc/init.d/rcS
  2. Test the correctness of rootfs content
  3. Make the required rootfs type format

6.BusyBox project construction system command

  1. BusyBox project was created by Bruce Perens in 1996
    http://www.busybox.net/
    BusyBox is an open source software released under the GNU GPL license agreement
  2. It enjoys the reputation of "Swiss Army knife for embedded Linux", maintained by Mr. Erik Andersen;
  3. Busybox is a UNIX system tool set, which integrates many common UNIX tools into a small executable file and provides most common commands for ordinary users;
  4. BusyBox is often used to make linux commands. The main instructions include
    cat, chmod, chown, cp, chroot, copi, date, dd, df, dmesg, dos2unix, du, echo, env, expr, find, grep, gunzip, gzip, halt, id, ifconfig, init, insmod, etc

7.BusyBox tool installation

linux@linux:~$ cp /mnt/hgfs/Linuxsharexiaomei/busybox-1.22.1.tar.bz2 .
linux@linux:~$ tar -vxf busybox-1.22.1.tar.bz2 
linux@linux:~$ cd busybox-1.22.1/

Make the contents of the root file system

$ make menuconfig
    Busybox Settings ---> 
	Build Options --->
		[*] Build BusyBox as a static binary (no shared libs)
		(arm-none-linux-gnueabi-) Cross Compiler prefix   Be sure to specify cross compilation tools
$ make
$ file busybox   Verify that the build is ARM Of the platform (shown as ELF 32-bit LSB executable, ARM)

 

$make install installation (default installation path is_ install)

$ cd _install
$  ls
      bin  linuxrc  sbin  usr
$ mkdir  dev  etc  mnt  proc  var  tmp  sys  root       Create the required directory

$CP ~ / gcc-4.6.4/arm-arm1176jzfssf-linux-gnueabi/lib/. - a note: Lib/ 
$du -mh lib view the size of the Lib Library
 $RM lib / *. A crop, delete static library file  
$arm none Linux gnueabi strip lib prune debugging information not recognized some libraries cannot be ignored by strip
 $sudo RM lib / libstdc + + * delete unnecessary libraries and ensure that all libraries are no larger than 4M in size  
$du -mh lib viewing the size of the Lib library may show 3.4M lib (make sure it is less than 8m here) 	

$CP / NFS / rootfs / etc - RF. Copy the mature reference configuration 





$sudo mknod dev / console C 5 1 must have a console device node

8. Testing

See if the new root file system can mount to the development board normally

linux@linux:~/busybox-1.22.1$ mv /nfs/rootfs /nfs/rootfs.ok       Back up the original root file system
 linux@linux:~/busybox-1.22.1$ sudo cp -rf _install /nfs/rootfs copy the new root file system (renamed rootfs)

Profile I

File / etc/inittab

#this is run first except when booting in single-user mode.
:: sysinit:/etc/init.d/rcS  Specifies that the system initialization script is rcS You can also specify another name, but you are used to rcS
# /bin/sh invocations on selected ttys
# start an "askfirst" shell on the console (whatever that may be)
::askfirst:-/bin/sh    Specify the initial console (enter after startup# Status)  
::restart:/sbin/init
::ctrlaltdel:/sbin/reboot

File / etc/init.d/rcS (startup script)

#!/bin/sh
# This is the first script called by init process
/bin/mount  -a                                 mount all stuff from /etc/fstab  
/etc/init.d/rc.local                           Extend subscript
echo  /sbin/mdev  >  /proc/sys/kernel/hotplug  Set the system's hotplug The procedure is mdev
/sbin/mdev  -s                                 
./app.exe   //Let scripts run your program automatically 

Profile II

File / etc/fstab

#device     mount-point     type        options        dump     fsck order
proc          /proc        proc        defaults         0             0
tmpfs         /tmp          tmpfs       defaults         0             0
sysfs          /sys         sysfs       defaults         0             0
tmpfs         /dev          tmpfs       defaults         0             0   

File / etc/profile

#!/bin/sh
export HOSTNAME=farsight
export USER=root
export HOME=root
export PS1="[$USER@$HOSTNAME \W]\# "Prompt in front of terminal
PATH=/bin:/sbin:/usr/bin:/usr/sbin
LD_LIBRARY_PATH=/lib:/usr/lib:$LD_LIBRARY_PATH
export PATH  LD_LIBRARY_PATH 

Test the correctness of rootfs content

$ cd /nfs
$ mkdir rootfs
$ cp  _install/*   rootfs   –a                        
$ chmod 777 /nfs/rootfs/		

If NFS can mount successfully, the root file system content is basically correct

Make the required rootfs type format

Details of different root file systems

nfs rootfs

Is the network file system, through the network cable remote mount a file system, file system in the remote computer. The biggest benefit is synchronization, which is mainly used for development and debugging

CRAMFS

Read only, cannot write. High security, some areas of the data can not be changed, can be defined as CRAMFS.

JFFS2 and YAFFS2

Readable, writable, for flash. JFFS2 is widely used in small application systems. JFFS2 has one feature: it is a log file system, which can be powered down at any time during use. YAFFS2 can only be used for Nand flash. Nand flash is used most in mobile phones. The file system is YAFFS2

EXT2 over RAM disk

Virtual a piece of memory into a disk. Memory can only be accessed as a buffer according to address space. When the memory of application product is large and the flash is small, a piece of memory can be virtualized as a disk according to this format

Making EXT2 over RAM disk file system

Make a 8M image

linux@linux:~$ dd if=/dev/zero of=ramdisk  bs=1k  count=8192

if	: (input file)input file 
/dev/zero	:It is a virtual device, and the data read from this device is all 0
of	: (output file)output file
bs=1k count=8192: Unit size is 1 k,The quantity is 8 k,It's 8 M size

Format this image as EXT2

linux@linux:~$ mkfs.ext2 -F ramdisk

Create the initrd directory under mount as the mount point

linux@linux:~$ sudo mkdir /mnt/initrd

Mount the disk image file to / mnt/initrd

Note that the ramdisk here cannot be stored in the rootfs directory

linux@linux:~$ sudo mount -t ext2 ramdisk /mnt/initrd

Copy our file system to ramdisk

Copy all the contents of the tested file system to the directory / mnt/initrd

linux@linux:~$ sudo cp /nfs/rootfs/* /mnt/initrd/ -a

Uninstall initrd

linux@linux:~$ sudo umount /mnt/initrd

Compress ramdisk to ramdisk.gz And copy to / tftpboot

linux@linux:~$ gzip --best -c ramdisk > ramdisk.gz

Format to uboot recognized format and copy to / tftpboot

linux@linux:~$ mkimage -n "ramdisk" -A arm -O linux -T ramdisk -C gzip -d ramdisk.gz ramdisk.img

linux@linux:~$ cp ramdisk.img /tftpboot/

Configure kernel to support RAMDISK

Finished ramdisk.img After that, you need to configure the kernel to support RAMDISK as the boot file system

make menuconfig

	File systems  --->   
		<*> Second extended fs support  
	Device Drivers  --->        
		SCSI device support  --->     
          	<*> SCSI disk support     
		[*] Block devices  --->  
			<*>   RAM block device support                                                   
			(16)    Default number of RAM disks                                            
			(8192)  Default RAM disk size (kbytes)  (Change to 8 M)
	General setup  --->  
		[*] Initial RAM filesystem and RAM disk (initramfs/initrd) support  

Recompile kernel, copy to / tftpboot

Reset the startup parameters on the U-BOOT command line

Tags: Linux network Makefile sudo

Posted on Wed, 17 Jun 2020 01:19:12 -0400 by hessodreamy