Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Kernel
Kernel
II
HISTORIAL DE REVISIONES
NMERO
FECHA
v1.0.0
2013 May 5
MODIFICACIONES
NOMBRE
CA
Kernel
III
ndice
1. Introduction
1.1. Objetivos: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2. References
2.1. OFICIALES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1.1. online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2. Admon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3. Basica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4. University . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4.3. Otros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4.5. JOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4.6. linux-book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4.7. linux-slides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5. Planetas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6. Apuntes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7. Tutoriales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8. Libros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.3. Biblioteca . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.12.1. Generalidades SO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3. Tutorial Primer
3.1. Descarga de los fuentes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4. UNIX-like systems: UN*X / *nix
8
8
9
4.1. Asociaciones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.2. Fundamentos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Kernel
IV
5. Linux
11
12
6.1. boot-BIOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7. Process
12
7.1. Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
7.2. Dudas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
7.3. Parametros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
8. Memory
13
9. Interrupciones
13
10. Drivers
13
11. Instalacin
13
11.1. how-to . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
11.2. postinstalacin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
11.2.1. kernel files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
11.2.2. imagen vmlinux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
12. Interfaz User-Kernel
14
12.1. Referencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
12.2. Introduccion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
12.3. Inter Process Communications (IPC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
12.4. Interfaz tipo Fichero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
12.4.1. procfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
12.4.2. sysfs
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
12.4.3. udev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
12.4.4. debugfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
12.4.5. configfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Kernel
V
23
13.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
13.2. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
13.2.1. Metodo de Aprendizaje . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
13.2.2. Fichero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
13.2.3. Tipos de ficheros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
13.2.4. Bloque . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.2.5. Gestor de Ficheros del Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3. Diversidad de Sistemas de Ficheros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3.1. Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3.2. Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3.3. Solaris . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
13.3.4. BSD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.3.5. IBM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.3.6. btrfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.3.7. Comparativa: Ext, NTFS, etc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.4. Lineas Futuras . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5. EXT: Linux File System Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5.1. Referencias Basicas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5.2. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
13.5.3. EXT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
13.5.4. EXT2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
13.5.5. EXT3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Kernel
VI
13.5.6. EXT4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
13.6. EXT: Caractersticas Generales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.7. EXT4: Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.7.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.8. EXT4: Caractersticas Principales: High Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.9. EXT4: Caractersticas Principales: Low Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.9.1. Layout Disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.9.2. Layout Partition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
13.9.3. Layout File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.9.4. Layout SuperBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.9.5. Layout Inode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.9.6. Directory Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.10.Architecture (Capas, Multinivel) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
13.10.1.Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
13.10.2.Estructura top-down del subsistema VFS del kernel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
13.10.3.Kernel Modules (Device Driver) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
13.10.4.Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13.10.5.Data Flow, Control Flow, and Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13.11.File Systems Objects (abstracciones) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13.12.File Descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.13.File Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.14.Directory Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.15.Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.16.dentry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.17.Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.18.Superblock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
13.19.Tipos de FS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
13.20.Root File System level: VFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
13.21.Root File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
13.21.1.mount . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
13.21.2.CHROOT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
13.22.Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
13.22.1.Device File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
13.22.2./dev/loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
14. Virtual Disks
37
Kernel
VII
37
15.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
15.2. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
15.3. losetup (loop-setup) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
15.4. Tutorial Basico. I. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
15.5. Analisis de la imagen de un sistema de ficheros virtual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
15.6. FS contenedor del fichero imagen y FS contenido en el fichero imagen . . . . . . . . . . . . . . . . . . . . . . . 42
15.7. Particiones del sistema de ficheros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
15.8. Tutorial Basico. II. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
15.9. tutorial basico III: NTFS virtual disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
16. File System FORENSICS
47
16.1. Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
16.2. Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
16.3. Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
17. Otros Sistemas de Ficheros
48
17.1. NTFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
17.2. Fuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
17.3. gvfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
17.4. usb:mtp,ptp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
18. DMA
49
49
20. Networking
49
20.1. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
20.2. ISO Stack Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
20.3. TCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
20.4. WIFI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
21. INTEL: Interfaces Usuario-Sistema: Normativa Unix
50
Kernel
VIII
51
22.1. Tutoriales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.1.1. Excesivamente simple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.1.2. Completo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.2. Flavors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.2.1. PC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.3. Versiones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.4. Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
22.5. Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
23. Instalacion del Kernel
52
52
52
53
26.1. Referencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.2. Introduccin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.3. Herramientas Necesarias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.4. Compilacion del Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.4.1. Introduccion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
26.4.2. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
26.4.3. Buildroot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
26.4.4. Download kernel, busybox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
26.4.5. Download uclibc, buildroot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
26.4.6. Create uclibc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
26.4.7. Create toolchain for uclibc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
26.4.8. Duda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
26.4.9. Create kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
26.4.10.Create filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
26.4.11.Create Busybox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
26.4.12.Fill filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
26.5. Emulate kernel and filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
26.6. FUNCIONA O NO FUNCIONA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
27. QEMU
58
58
28.1. blogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Kernel
IX
58
29.1. General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
29.2. Flavors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
29.3. Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
30. Kernel: Small, Tiny
59
30.1. Referencias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
30.2. How to Build A Custom Linux Kernel For Qemu (2015 Edition) . . . . . . . . . . . . . . . . . . . . . . . . . . 59
31. TEST
59
60
60
61
61
62
66
66
Kernel
X
66
74
40.1. Introduccin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
40.2. Hello World con kernel freebsd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
40.3. Hello World Bare Metal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
40.3.1. Introduccin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
40.3.2. carpeta tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
40.3.3. fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
40.3.4. Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
40.3.5. Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
40.3.6. Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
40.3.7. Desensamblaje . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
41. Tutorial Baremetal: hello world rectangle Bosch
83
83
84
43.1. Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.1.1. Problemas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.2. Referencia . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.3. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.3.1. C and executable formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.3.2. kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
43.3.3. physical address space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.4. Dynamic Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.5. Inline Assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.6. C standard library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.7. C Run Time Library (RTL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.3.8. Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.4. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.4.1. Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.5. The Build Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
43.5.1. VFD - Virtual Floppy Drive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
43.5.2. Floppy Image on linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Kernel
XI
43.5.3. NASM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
43.5.4. Copying the Boot Loader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
43.5.5. Test del floppy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
43.5.6. Bochs Emulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
43.5.7. Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
43.5.8. boot2.asm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
43.5.9. BIOS Parameter Block(BPB) (OEM Parameter) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
43.6. Basic Theory and History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
44. Websofia BareMetal: Writing your own toy operating system
90
90
90
94
Kernel
XII
ndice de cuadros
1.
Tipos de IPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.
Comparativa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Kernel
1 / 94
1.
Introduction
1.1.
Objetivos:
Estudiar exhaustivamente la estructura interna del ncleo del Sistema Operativo Linux
Interactuar con la estructura del kernel a travs de APIs del Sistema Operativo
Info del gestor de procesos
Info del gestor de memoria
Info de la red
Info del sistema virtual de ficheros
Info del sistema de ficheros de dispositivos tipo bloque
Info de los dispositivos de tipo carcter
Info de los mdulos del kernel drivers
1.2.
Ejercicios Basicos
2.
References
2.1.
OFICIALES
2.1.1.
online
http://www.linfo.org/kernelresources.html
phoronix
News Linux: HW architecture, Kernel
https://www.kernel.org: no solo tengo los fuentes, tambin documentacin, herramientas, etc
https://www.kernel.org/pub/software/scm/git/: aqu tengo la herramienta git
https://www.kernel.org/category/releases.html: al final estn las wikis, planet
source home release
Puedo DESCARGA la versin estable 3.9.2 el 15 de Mayo 2013: versin git, versin comprimida tar 69 MB.
https://www.kernel.org/pub/linux/kernel/v3.x/ TODAS LAS VERSIONES
https://github.com/torvalds/linux
git online tree: recomendado
Por ejemplo DMA-API_HOWTO
documentation: recomendado. Enlaces a las fuentes oficiales de diferentes topics: C, ABI, ELF, ARM, SUS, etc
Doc:
Kernel
2 / 94
Linux kernel source tree documentation. Se puede hacer un make en los fuentes linux-3.9.2$ make pdfdocs
y generar pdf si estn bien instaladas los paquetes utils-docbook y latex
informacin sobre la arquitectura del kernel
[Error: itemizedlist too deeply nested]
referencias sobre libros
HOWTO: No es info tecnica sino how to become a Linux kernel developer and how to learn to work with the Linux
kernel development community: referencias a recursos como libros
API: librera de funciones para desarrollar el kernel.
Ejemplo de doc : proc filesystem
esta misma info est en http://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html
esta info esta en la distribucin
wiki: info de algunos topicos: ata,
Linux Source Code - Linux Cross Reference:
Cdigo fuente de todas las versiones del kernel: Navegable
Entre los archivos del kernel en la carpeta pub estn los archivos pblicos, entre los cuales se provee de una serie de servicios,
utilidades, etc:
distribucion knopixx
utils
util-linux
comando losetup (loop-setup) que asocia un fichero al pseudo-device loop
klibc: libera c del kernel
http://code.metager.de/source/xref/linux/klibc/usr/utils/ : losetup.c source code
utils
open group: SUS manual: API
exhaustivo
Miles de Articulos muy avanzados de aspectos muy concretos del kernel
Fuentes del kernel
tdlp: viejo pero bsico
linux home: Muy general. Cursos malillos primer, intermediate, avanced
http://www.makelinux.net: recomendado
http://www.makelinux.net/resources links a libros
linux kernel: online
Advancede Linux Programming
poster
glossary
proyectos: bueno
proyectos de aprendizaje practico
Documentos: articulos bsicos, listado de libros
osdever:muchos tutoriales y diversos a nivel bajo
Kernel
3 / 94
2.2.
Admon
Red Hat
Debian
Oracle
pdf
html
Archlinux
archlinux
gentoo
2.3.
Basica
http://en.wikipedia.org/wiki/Linux
2.4.
2.4.1.
University
La construccin del sistema operativo Linux 2.0
2.4.3.
Otros
Kernel
4 / 94
http://cseweb.ucsd.edu/classes/su10/cse120/
los apuntes esquematicos del libro de Silberschatz permiten un recordatorio rpido
http://www.shsu.edu/csc_tjm/cs431/
los apuntes esquematicos del libro de Silberschatz permiten un recordatorio rpido
http://pages.cs.wisc.edu/~dusseau/Classes/CS537-F04/#schedule
CS 537: Introduction to Operating Systems . Fall 2004. Operating System Concepts (6th Edition), by Silberschatz, Galvin,
and Gagne;Modern Operating Systems by Andrew Tanenbaum. Operating Systems: A Modern Perspective by Gary Nutt
Ejercicios con soluciones.
http://etc.unitbv.ro/~danciu/cursuri_so/
buenas transparencias
http://www.win.tue.nl/~aeb/linux/lk/lk.html: del 2003 pero es corto y claro.
carnegie mellon
http://www.enseignement.polytechnique.fr/informatique/INF583/
buscar en delicious
2.4.4.
Minirighi: IA-32
minirighi
Minirighi is a multi-threading operating system for IA-32 architecture. The main feature of Minirighi is its light kernel, easy
to read from all, simply by analyzing the source code, unlike many other open-source kernels.
Ver el apartado Device Drivers: rs232, keyboar, etc
2.4.5.
JOS
Kernel
5 / 94
2.4.6.
linux-book
linux-slides
http://linux.linti.unlp.edu.ar/index.php?title=P%C3%A1gina_principal
2.4.8.
Universidad de Cantabria
http://www.ctr.unican.es/asignaturas/dec/Doc/kernel_cpu_memoria.pdf
2.5.
Planetas
vicente navarra: compila el kernel para la tarjeta grfica VIA EPIA y configura el sistema operativo para dicha tarjeta.
2.6.
Apuntes
universidad polaca: guin con referencias al cdigo fuente del kernel del repositorio Linux Source Code - Linux Cross Reference
2.7.
Tutoriales
2.8.
2.8.1.
Libros
Interfaz del usuario al Kernel: linux programming
Kernel
6 / 94
(Addison-Wesley Professional Computing Series) [Hardcover].W. Richard Stevens, Stephen A. Rago. 2 Edicin 2005.
university
Advanced UNIX Programming:
Marc J. Rochkind. 2 Edition. Addison Wesley Professional Computing Series.
Detalle de las interfaces HOW TO.
Recomendado. Lo cojo de la biblioteca
Linux System Programming (December 5, 2007):
Love. Programacin en C desde el espacio de usuario pero a muy bajo nivel, interactuando con el Kernel de Linux, con
llamadas al sistema muy primitivas. Equivalente al de Richard Stevens pero en lugar de Unix/BSD, lo hace con Linux.
Descargado.
Linux Programming Interface:
Realmente intenta abarcar conceptos generales de sistemas operativos y las intefaces. Es decir, no est estrictamente especializado en programacin.
Michael Kerrisk.2010.Descargado. recomendado
beginning
Beginning Linux Programming 4th Edition Neil Matthew Richard Stones
Sencillo. No requiere muchos conocimientos de S.O. Explica hasta como compilar, shell programming.
ethz:
Escueto pero recomendado. ONLINE.
This document is written for programmers with some experience in system programming
Hace referencias a fuentes de informacin especializadas en el kernel, por lo que no es un documento cerrado. No recomendado para principiantes pero s ayuda a extraer los conceptos pilares del kernel.
listado de libros:
kernelnewbies: referenciado en la linux foundation.
Art of linux programming:
Eric Raymond. Filosofico. Descargado
unix system programming:
Robbins. Practico. 2 Edicin. Descargado
the documentation linux project:
guides
Programacin de Sistemas Pablo Garaizar Sagarminaga
Lo escrito es bsico y muy claro. El problema es que trata pocos temas: procesos con tuberas
Kernel
7 / 94
2.8.2.
Kernel Internals
http://oss.sgi.com/LDP/HOWTO/Kernel-HOWTO/index.html
Prof Linux Kernel Arch Wolfgang Mauerer
Recomendado Descargado
Muy sintetizado
Referencias a modulos fuente del kernel que definen funciones.
listado de libros
Linux Kernel Development, Second Edition (March 9, 2005): Love 2 Edicion
Linux Kernel Development, Third Edition (December 15,2010): Love . Recomendado
The Linux Kernel Primer (October 5, 2005):The Linux Kernel Primer: A Top-Down Approach for x86 and PowerPC Architectures . Descargado. En la biblioteca.
Understanding the Linux Kernel, 3rd Edition (November 22, 2005): Daniel P. Bovet. OReilly. Descargado. Explicacin de
la funcionalidad del kernel linux y su implementacin en el cdigo fuente. Recomendado.
Understanding Linux Network Internals (January 24, 2006) Oreilly
User Mode Linux (May 16, 2006): UML. Virtualizacion. Descargado
Linux Kernel in a Nutshell (February 7, 2007): Kroah. online. Descargado. download, compile, and install a new kernel
California-Irvine: demasiado terico.
https://gustavus.edu/+max/os-book/: recomendado ms arriba
https://0xax.gitbooks.io/linux-insides/content/index.html: recomendado ingls y espaol. Lo he utilizado para estudiar un
poco la gestin de las interrupciones.
https://github.com/leolas95/linux-insides: en espaol
2.8.3.
Biblioteca
El objetivo del libro no es como est implementado el kernel, ni como utilizar los comandos del interprete bash shell. El
objetivo es ensear a utilizar las llamadas al sistema, call system, del kernel desde las aplicaciones de usuario. Se ensea el
How y tambin se indican las virtudes y defectos de las llamadas.
El libro empieza indicando como podemos especificar en una plataforma determinada qu API utilizar, y que opciones de una
API determinada autorizar.
Kernel
8 / 94
2.9.
Manuales online
debian-reference
2.10.
2.11.
Libros generales de SO
2.12.
Metodo aprendizaje
2.12.1.
Generalidades SO
3.
3.1.
Tutorial Primer
Descarga de los fuentes
Descargo la versin que tiene un mantenimiento a largo plazo. En https://www.kernel.org/category/releases.html observo que
la versin 3.2 tiene mantenimiento hasta el 2016.
En ubuntu uname -r veo que precisamente tiene la versin 3.2
3.2.0-61-generic : al haber un guin despus de la versin significa que no es un kernel puro sino una distribucin.
sitio de descarga
en protocolos http, ftp, tengo
signatures, archivo tar y patch. Los patch son desviaciones del original para solucionar problemas o aadir una extensin
particular. ftp://ftp.kernel.org/pub/ linux kernel : ftp://ftp.kernel.org/pub/linux/kernel/v3.x/
tambin tengo tools crosscompilers
Pincho en 3.2.59 cgit pincho en el titulo index : kernel/git/stable/linux-stable.git
Me imagino que https://github.com/torvalds/linux es el repositorio git de la ltima versin o de qu versin
Hay que leerse el README: These are the release notes for Linux version 3.
Kernel
9 / 94
4.
4.1.
Linux Foundation :
La fundacin linux es la madre de linux
Servicios: Noticiario, blogs, documentos
Linux Foundation: news, tutorials, etc
http://www.linuxfoundation.org/
https://www.usenix.org/about
the USENIX Association has brought together the community of engineers, system administrators, scientists,
members login
4.2.
Fundamentos
Versin 7 Unix
nacimiento de Unix en los laboratorios Bell en 1979: la versin 7 es la primera versin portable
Es el origen de C, make, lint, lex, yacc, herramientas bsicas de desarrollo, bash, awk, umask, system calls, pcc compiler,
....
brief history and book
The UNIX V7 Product Standard is a significantly enhanced version of the UNIX 03 Product Standard. The most significant
change is alignment with the Single UNIX Specification, Version 4 that includes The Open Group Base Specifications,
Issue 7, and approved Technical Corrigenda (if any).
ms historia hasta el pinguino
UN*X: 2 versiones principales de Unix:
BSD de Berkeley University comercializado por Sun y SysV creado y comercializdo por AT&T
SysV:
Unin entre AT&T y Sun microsystems
Versin comercial: System V Release 4 - SVR4
SysV: en las distintas versiones se puede ver la compatibilidad de SVR4 con posix, abi, etc
unix war:
rbol genealgico de las familias *nix
Guerra entre OSF de HP, DEC, IBM y Unix International de AT&T,Sun por la creacin de un open standard standard
pblico. En Europa el X/Open de Bull, ICL, Siemens, Olivetti, and Nixdorf estaba en tierra de nadie.
La paz llega en 1996 con el Open group formado por empresas y asociaciones gubernamentales americanas y japonesas
como: Capgemini, Fujitsu, Oracle, Hitachi, HP, Orbus Software, IBM, Kingdee, NEC, SAP, US Department of Defense,
NASA and others.
Open group:
Standard Single Unix Specification-SUS
Extiende la norma POSIX y actualmente es la definicin OFICIAL de un sistema Unix.
actualmente en la norma Versin 4
SUS-v4
Kernel
10 / 94
The Single UNIX Specification Version 4 - incorporating POSIX (IEEE Std 1003.1 ISO/IEC 9945:2009) and integrating
the industrys Open Systems standards
Compatible con The ISO/IEC 9899:1999 standard Standard C.
There are now 1833 interfaces defined in the Single UNIX Specification, Version 4. The table below gives the breakdown
for each volume of the Single UNIX Specification: XSH(1191)+ XCU(174)+ XBD(82)+ XCURSES(386).
Tiene links a test de software test-suite: Unix, linux, embedded, posix, real-time
Manual PDF: 5 Volmenes: XBD, XSH,XCU,XRAT y XCURSES
POSIX: Manual: Clicar Frames Index para tener a la derecha un ndice.
"Portable Operating System Interface"
Core programming interface : Describe las llamadas al sistema
standarizado por la Asociacin IEcubo: IEEE Std 1003.1-1988 llamado Internacionalmente como ISO/IEC 9945:2009 (
A technical corrigendum was approved in August 2012 - ISO/IEC 9945:2009/Cor 1:2013(E))
la ltima versin es Posix-2008.1 (IEEE Std 1003.1-2008) que incluye 4 volumenes:
the Base Definitions, Issue 7 (Open Group) : Volumen XBD.Glosario de reglas y definiciones. Por ejemplo dice que
cuando emplea el verbo shall significa de obligado cumplimiento.
the System Interfaces and Headers, Issue 7, : Volumen XSH.Describe las Interfaces de LLamadas al kernel del sistema
que las implementar el Kernel mediante funciones de C. Define las Cabeceras de las Interfaces al Sistema. Describe
la interfaz de una librera: prototipos y cabeceras:The C POSIX library is a specification of a C standard library for
POSIX systems
[Error: itemizedlist too deeply nested]
the Commands and Utilities, Issue 7. : Volumen XCU. Shell & Utilities: Lenguaje de Comandos para el interprete shell.
Trata sobre la sintaxis mas que sobre el lxico. Es decir trata del HOW utilizar los comandos y realizar un programa
mediante el lenguaje de comandos. Respecto de las utilidades: dd, cp, awk, bc, sed, yacc, make,c99, ctags, kill . . . ,
acceder desde el men principal. Hay utilidades que se corresponden con la misma funcionalidad que una llamada al
sistema, por eso en la descripcin de la utilidad aparece la notacin XSI (Ver codes en el manual XBD), indicando que
se acuda a la informacin del volumen del manual XSI a la interfaz del sistema con el mismo nombre: Un ejemplo es
la utilidad kill y la llamada kill() [Error: itemizedlist too deeply nested]
Rationale for base definition: Volumen XRAT. Explica cual ha sido el razonamiento para desarrollar la norma
[Error: itemizedlist too deeply nested]
XCURSES is not part of the Base Specifications, Issue 7, but is a separate Open Group Technical Standard. XCURSES
describes a set of interfaces providing a terminal-independent method of updating character screens that are available
to application programs on systems conformant to this part of the Single UNIX Specification.
[Error: itemizedlist too deeply nested]
Berkeley Software Distribution-BSD:
BSD, despus de la Unix-war no form parte del Open Group y fue por libre
openBSD
netBSD
DragonFly_BSD
FreeNAS : FreeNAS is a free, open source, Network-Attached Storage operating system based on FreeBSD
freeBSD: FreeBSD has long been a popular choice for server systems and embedded applications requiring a high level
of security and stability
GNU
1983: sistema operativo UN*X
gnu project
http://en.wikipedia.org/wiki/GNU_Hurd [kernel gnu hurd]
Resumen
Kernel
11 / 94
5.
5.1.
5.1.1.
Linux
Linux Programming
Libros
Tutoriales
http://www.linuxjournal.com/article/8381
5.2.
Linux
Linux cumple con el API POSIX y con el ABI LSB que est basado en el ABI SYSV-X86-64
GNU es una extensin de POSIX creando un Sistema Operativo mucho ms eficaz.
5.3.
http://www.linuxfoundation.org/collaborate/workgroups/lsb
http://es.wikipedia.org/wiki/Linux_Standard_Base
Linux Standard Base
Linux Standard Base Doc: mal camino ya que se llega a documentacin obsoleta
Especificaciones de Referencia de Linux Fundation: camino correcto hacia info actualizada
LSB: Incluye tanto API (interfaces de lenguajes de alto nivel como C) como ABI (interfaces en lenguaje mquina o ensamblador) pero est obsoleto
FHS: Jerarqua del sistema de ficheros
API
DWARF: Compatible with the DWARF debugging format used at the time by SVR4 compilers and debuggers from AT&T.
Ver gdb
wikipedia
5.4.
Linux Images
5.5.
Intel-Linux
Kernel
12 / 94
5.6.
Documentation
5.7.
5.8.
Linux-Libre
6.
6.1.
Boot-Grub-BIOS
boot-BIOS
boot-BIOS
7.
7.1.
Process
Commands
leer el man ps
ps --help
ps -aucandido : list process (all of user candido)
ps -e: todos los del sistema
ps -C firefox : proceso cuyo nombre comando es firefox
ps -fC firefox : full format : ojo , importa el orden de las opciones
ps -jC firefox: job format
ps -ejH | more : all system, job format, Hierarchy : tree padres e hijos de todo el sistema
pstree : arbol de todos los procesos
top
pgrep firefox : visualiza el pid
pgrep sh
ps H : only threaders
ps -eo pid,user,args,flags --sort user :
e: all system, o: output format
especificadores de formato: primera columna pid, 2 user, 3 args, 4 flags
sort user: agrupar por usuarios
Kernel
13 / 94
7.2.
Dudas
7.3.
Parametros
8.
Memory
Understanding The Linux Virtual Memory Manager. Mel Gorman Prentice Hall. Descargado
9.
Interrupciones
interrupciones
10.
Drivers
11.
Instalacin
11.1.
how-to
https://www.kernel.org/
git tutorial
Kernel
14 / 94
11.2.
postinstalacin
11.2.1.
kernel files
http://oss.sgi.com/LDP/HOWTO/Kernel-HOWTO/kernel_files_info.html
11.2.2.
imagen vmlinux
http://blog.packagecloud.io/eng/2016/03/08/how-to-extract-and-disassmble-a-linux-kernel-image-vmlinuz/
https://raw.githubusercontent.com/torvalds/linux/master/scripts/extract-vmlinux
12.
Interfaz User-Kernel
12.1.
Referencia
Referencia : http://people.ee.ethz.ch/~arkeller/linux/kernel_user_space_howto.html
12.2.
Introduccion
Debido a que el kernel tiene privilegios que no tiene el usuario como por ejemplo el acceso al hardware, es necesario que el
kernel y el usuario se comuniquen de distintas maneras (Ver IPC, interprocess communications), mediante distintas interfaces:
procfs
sysfs
debugfs
configfs
socket
ioctl
system call
signal
upcall
mmap
sysctl
12.3.
http://en.wikipedia.org/wiki/Inter-process_communication#Main_IPC_methods
Cuadro 1: Tipos de IPC
Method
Short Description
File
Kernel
15 / 94
Cuadro 1: (continued)
Method
Short Description
Signal
Socket
Message
queue
Pipe
Named pipe
Semaphore
Shared
memory
Message
passing
(shared
nothing)
Memory-mapped
file
12.4.
Una forma de comunicarse usuario y kernel es mediante un sistema de ficheros como forma de almacenar datos estructurados
en ficheros.
El kernel genera un sistema de ficheros en el espacio de usuario que es utilizado para escribir/leer por ambos (el kernel y por
usuario)
El usuario puede escribir parmetros de configuracin del kernel mientras este se est ejecutando
El sistema de ficheros es virtual, se implementa en RAM. Tambin se llama pseudo-file system por ser virtual y no tener
asociado un dispositivo de almacenamiento permanente que almacene bloques.
Kernel
16 / 94
12.4.1.
procfs
sysfs
Tipo nodev, es decir, no tiene un device fsico asignado por lo que es virtual.
Sistema de ficheros con info de los devices y los drives
inicialmente se denomin ddfs: device driver file system
Es sistema de ficheros (estructura en arbol con directorios,subdirectorios,ficheros y enlaces entre s) est montado en
$mount
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
12.4.3.
udev
https://docs.oracle.com/cd/E37670_01/E41138/html/ch07s03.html
https://wiki.debian.org/udev
udev device manager dynamically creates or removes device node files at boot time or later
When creating a device node, udev reads the devices /sys directory for attributes such as the label, serial number, and bus
device number.
Udev uses rules files that determine how it identifies devices and creates device name
Create a rule file under /etc/udev/rules.d with a file name such as 10-local.rules that udev will read before any other rules file
udev on /dev type devtmpfs (rw,mode=0755)
The /dev directory contains device files (also sometimes known as device special files and device nodes)
Ejemplo de comandos
Ver ejemplo en apuntes smartphone
Kernel
17 / 94
12.4.4.
debugfs
Tipo nodev, es decir, no tiene un device fsico asignado por lo que es virtual.
Sistema de ficheros que se utiliza para depurar un sistema de ficheros. Permite analizar y tambin configuarlo. Por ejemplo se
utiliza para recuperar archivos borrados.
Se monta en /sys/kernel/debug
$ mount | grep debugfs
none on /sys/kernel/debug type debugfs (rw)
$ sudo ls -l /sys/kernel/debug/
[sudo] password for candido:
total 0
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 31 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
drwxr-xr-x 4 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
-r--r--r-- 1 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
-rw-r--r-- 1 root root 0 Jul 25
-r--r--r-- 1 root root 0 Jul 25
drwxr-xr-x 6 root root 0 Jul 25
drwxr-xr-x 3 root root 0 Jul 25
-r--r--r-- 1 root root 0 Jul 25
drwxr-xr-x 2 root root 0 Jul 25
2013
14:46
14:43
2013
2013
2013
14:43
2013
14:43
2013
2013
2013
2013
2013
2013
2013
2013
2013
2013
acpi
bdi
bluetooth
dri
extfrag
gpio
ieee80211
kprobes
kvm
mce
mmc0
regmap
regulator
sched_features
suspend_stats
tracing
usb
wakeup_sources
x86
info
man debugfs
kernel documentation
$ ls -l /usr/src/linux-3.4.4/Documentation/filesystems/debugfs.txt
-rw-rw-r-- 1 root root 8322 Jun 22 2012 /usr/src/linux-3.4.4/Documentation/filesystems/ debugfs.txt
-> el documento tiene poco inters.
tutoriales
no he encontrado, por lo que solo queda experimentar
12.4.5.
configfs
12.5.
12.5.1.
Referencias
12.5.2.
Introduccion
Socket: Enchufe
Es un tipo de inter-process communication (IPC).
La idea principal es:
Kernel
18 / 94
Un socket es una INTERFAZ para los programas de usuario que facilita las comunicaciones IPC, por ejemplo para comunicarse a travs de internet queremos una herramienta que comunique el proceso cliente con el proceso servidor a travs de una
red de comunicaiones. El socket es una herramienta proporcionada por el sistema operativo. Un smil entre socket y telfono:
El telfono sera la aplicacin de usario (agenda, marcador, etc ) y el socket sera todo lo relacionado con lo necesario por el
usuario para la conexin con la red de telefona (terminal telefnico, compaia proveedora de la red, nmero de telfono origen, nmero de telfono destino, seal acstica, colgar, descolgar, etc). La implementacin de todas esas funciones y recursos
(socket) para el usuario, es responsabilidad del sistema operativo.
Visualizacin
Diagrama User communications applications process socket port TCP IP
Kernel
19 / 94
12.5.3.
Mtodo de estudio
Domain-Type-Protocol
http://techpubs.sgi.com/library/dynaweb_docs/0530/SGI_Developer/books/IRIX_NetPG/sgi_html/ch04.html
A socket is an endpoint of communication to which a name can be bound. Each socket has one or more associated processes
Para generar un socket es necesario tener en cuenta el tipo de comunicaciones al que queremos acceder. Inicialmente la
forma de definir el tipo de comunicaciones era a partir de 3 argumentos: dominio-tipo-protocolo. Al mismo tiempo que se
desarrollaban los sockets tambin se estaban desarrollando las comunicaciones. Hoy en da no hay una flexibilidad al 100 %
para poder seleccionar el tipo de protocolo, el tipo de socket y el dominio de las comunicaciones de forma independiente sino
que al seleccionar el dominio tenemos limitados los protocolos, etc
A socket domain is an abstraction that provides an addressing structure and a set of protocols, por lo tanto define la
arquitectura de las comunicaciones. Sockets connect only with sockets in the same domain
The sockets facility supports three communication domains: unix-internet-raw
The UNIX domain is used only for on-system communication: sockets are named with UNIX pathnames; a socket, for
example, may be named /dev/foo.
The Internet domain is used by processes that communicate using the Internet standard communication protocols IP/TCP/UDP.
The Raw domain provides access to the link-level protocols of network interfaces (unique to IRIX).
Each interfaz socket in use has a type . Socket types define the communication properties visible to the application (INTERFAZ ARGUMENTS). Processes communicate only between sockets of the same type
stream socket interfaz: provide a bidirectional, reliable, sequenced, and unduplicated flow of message data.
datagram socket : support bidirectional data flow, but dont guarantee that the message data is sequenced, reliable, or
unduplicated.
raw socket interfaz :give you access to the underlying communication protocols that support socket abstractions.
Cada socket tiene asociado un protocolo
Ver Capa de transporte de ISO network.
Un socket es una plataforma que lleva asociados los siguintes recursos:
network socket: endpoint of an inter-process communication flow across a computer network. Define los eventos y su organizacin para permitir que la comunicacin tenga lugar: protocolos de comunicaciones.
socket API: BSD socket. Son llamadas al kernel (system call)
socket()
creates an endpoint for communication and returns a file descriptor for the socket.
socket() takes three arguments: domain, type, protocol
bind()
listen()
close()
socket address is the combination of an IP address and a port number
Kernel
20 / 94
12.5.5.
Linux Command
Foreign Address
77.69.18.95.dynam:37945
84.77.96.85:6686
222.83-213-87.dyna:4662
grape.canonical.c:https
peerbooter.peerate:7111
mistletoe.canonica:http
90.165.121.7:47470
host56-68-dynamic.:4662
16.Red-83-55-189.:55085
90.165.121.7:47470
host56-68-dynamic.:4662
State
ESTABLISHED
ESTABLISHED
FIN_WAIT1
ESTABLISHED
ESTABLISHED
CLOSE_WAIT
ESTABLISHED
ESTABLISHED
ESTABLISHED
ESTABLISHED
ESTABLISHED
unix sockets
netstat -x
unix 3
unix 3
Hx1mck4n
unix 3
unix 3
khJk3eHX
unix 3
unix 3
y8275KZu
[ ]
[ ]
STREAM
STREAM
CONNECTED
CONNECTED
777062
777395
@/dbus-vfs-daemon/socket- -
[ ]
[ ]
STREAM
STREAM
CONNECTED
CONNECTED
778262
777394
@/dbus-vfs-daemon/socket- -
[ ]
[ ]
STREAM
STREAM
CONNECTED
CONNECTED
778261
777393
@/dbus-vfs-daemon/socket- -
Kernel
21 / 94
unix 3
unix 3
tBhvWrSI
unix 3
unix 3
12.5.8.
[ ]
[ ]
STREAM
STREAM
CONNECTED
CONNECTED
777048
777392
@/dbus-vfs-daemon/socket- -
[ ]
[ ]
STREAM
STREAM
CONNECTED
CONNECTED
777047
777391
@/tmp/dbus-4AKNj7Vwtg
Programming sockets
http://linuxeco.com/?p=1: leerlo despus de conocer los conceptos. Comenta de forma bsica las funciones y procedimientos
para programar con sockets.
All Linux networking works with System Calls creating network sockets (using the Socket
System Call). The Socket System Call returns an integer (socket descriptor).
Writing or reading to/from that socket descriptor (as though it were a file) using
generic System Calls write / read respectively creates TCP network traffic rather
than file-system writes/reads.
Note: The file-system descriptor would have been created by the Open system call IF ... the descriptor were a regular file-system descriptor, intended for regular / file- system writes and reads (via System Calls write/read respectively) to files etc.
Further Note: This implies that the network socket descriptor created by the socket System Call will be used by systems programmer to write/read , using the same System Calls write/read used for regular file system writes/reads (System Calls that would, under normal and other circumstances, write/read data to/from memory).
Further further Note: A System Call write (to the descriptor that was created by the socket System Call) must translate magically into a TCP transaction that writes the data across the network (ostensibly to the client on the other end), with the data written encapsulated within the payload section of a TCP packet.
This process of adapting and hijacking the kernel file-system infrastructure to incorporate network operations /socket operations is called SOCKFS (Socket File System ).
So how does the linux kernel accomplish this process, where a file-system write is faked into a network-system write, if indeed it can be called that ?
Well...as is usually the case, the linux kernels methods begins at System / Kernel Initialization, when a special socket file-system (statically defined sock_fs_type)
for networks is registered by register_file_system. This happens in sock_init. File systems are registered so that disk partitions can be mounted for that file system.
The kernel registered file system type sock_fs_type so that it could create a fake mount point using kern_mount (for the file system sock_fs_type). This mount point is necessary if the kernel is to later create a fake file
*struct file using
existing/generic mechanisms and infrastructure made available for the Virtual File System (VFS). These mechanisms and infrastructure would include a mount point being available.
Note:
No actual mount point exists, not in the sense an inode etc etc.
We will blog on file systems later.
Then when the socket System Call is initiated (to create the socket descriptor), the kernel executes sock_create to create a new descriptor (aka the socket descriptor). The kernel also executes sock_map_fd, which creates a
fake file , and assigns the fake file to the socket descriptor. The fake files ops ( file->f_op) are then initialized to be socket_file_ops (statically defined at compile time in source/net/ socket.c).
Kernel
22 / 94
The kernel assigns/maps the socket descriptor created earlier to the new fake
using fd_install.
file
This socket descriptor is returned by the Socket System Call (as required by the MAN page
of the Socket System Call) to the user program.
I only call it fake file because a System Call write executed against that socket descriptor will use the VFS infrastructure created, but the data will not be written into a disk-file anywhere. It will, instead, be translated into a network operation because of the f_ops assigned to the fake file (socket_file_ops).
The kernel is now set up to create network traffic when System Calls write/read are executed to/from to the fake file descriptor (the socket descriptor) which was returned to the user when System Call socket was executed.
In point of fact, a System Call write to the fake files socket descriptor will then translate into a call to __sock_sendmsg within the kernel, instead of a write into the regular file system. Because that is how socket_file_ops is statically defined before assignment to the fake file.
And then we are into networking space. And the promised Lan of milk, honey,
SOCKFS and File Systems.
TCP traffic,
No one said understanding the kernel was easy. But extremely gratification awaits those that work on it. And also creates enormous opportunities for innovation. I explain Linux Kernel concepts and more in my classes ( Advanced Linux Kernel Programming @UCSC -Extension, and also in other classes that I teach independently).
12.6.
12.7.
Interfaz ioctl
12.8.
Interfaz signal
12.9.
Interfaz upcall
12.10.
Interfaz mmap
12.11.
.
Interfaz sysctl
Kernel
23 / 94
13.
13.1.
Referencias
13.2.
Introduction
13.2.1.
Metodo de Aprendizaje
El gestor de ficheros del kernel de linux se puede estudiar desde distintos puntos de vista ya que est estructurado en capas. El
mtodo ms recomendable es el TOP DOWN, estudiando primero aplicaciones o herramientas de uso del sistema de ficheros
por parte del usuario y finalizando con los aspectos internos del diseo y desarrollo del kernel en lenguaje C. Este estudio vertical
no puede ser lineal y no tiene sentido estudiar primero el TOP sin saber nada del nivel DOWN.
Se recomienda estudira primero lo bsico del TOP, luego lo bsico del DOWN, profundizar en el TOP teniendo en cuenta lo
aprendido en el DOWN, profundizar en el DOWM, y as ir realimentando los dos niveles.
Un posible orden sera:
Nivel intermedio:
comprender que es un sistema de ficheros: discos, tipos, sistemas intefaz con el kernel como /sys, virtuales
crear un sistema de ficheros , enlazarlo con el /dev/loop y montarlo en un punto del file system root
Nivel intermedio: comprender la estructura de capas del sistema VFS
Nivel bajo:
comprender un poco que es un fichero, un inode, un superblock
comprobar la utilidad de la herramienta debugfs, stat, ls -i, etc
instalar el paquete gratuito de file system forensics http://www.sleuthkit.org/
comprobar los nuevos comandos herramienta: istat, etc
Nivel top :
No es fundamental conocer la IMPLEMENTACION del sistema de ficheros estructurado sino el para que. No el HOW sino
el WHAT
estudiar la evolucin del sistema de ficheros ext:
CARACTERISTICAS, OBJETIVOS Y LIMITACIONES.
coger un libro con generalidades sobre sistemas de archivos y en concreto sobre el sistema ext4 de linux.
libro silbertchaz
libro love linux programming
linux admon guide
wiki sobre ext4: estudiar unicamente las lneas generales, sin detalles.
articulo:
Practicar lo aprendido con los comandos
Nivel intermedio EXT4:
profundizar en EXT4
wiki oficial
linux guide
libro silber
libro love programming
Kernel
24 / 94
importante
Hay que estudiar pensando que el sistema de ficheros actual EXT4 evoluciona y probablemente sea sustituido por uno
nuevo. Por lo que son muy importante las caractersticas de los sistemas de archivos, los objetivos que persiguen y
sus limitaciones.
13.2.2.
Fichero
Tipos de ficheros
Regular
Directorio
especiales
device
block
character
FIFO: pipe
symlink
socket
Kernel
25 / 94
13.2.4.
Bloque
La organizacin de los datos del disco duro en bloques significa que nos transfieren bytes sino conjuntos de bytes denominados
bloques. Se utiliza el ancho de banda del bus SCSI para transferir por ejemplo un bloque de 512 bytes con la consiguiente
optimizacin del ancho de banda efectivo.
Los dispositivos orientados a caracter transmiten byte a byte.
13.2.5.
13.3.
13.3.1.
Linux
Ao 2013: EXT4
13.3.2.
Windows
Ao 2013: NTFS
13.3.3.
Solaris
Ao 2013: UFS
Kernel
26 / 94
13.3.4.
BSD
Ao 2013:
13.3.5.
IBM
Ao 2013: JFS
13.3.6.
btrfs
.
13.3.7.
filesystem overview
Cuadro 2: Comparativa
File System
MINIX
Extfs
Ext2
Ext3
Ext4
UFS
FFS
FAT
NTFS
13.4.
kernel
si
no
si
no
Linux
2.6.28
no
nn
j
j
Bytes
2
2
4
4
8
8
si
Lineas Futuras
http://lwn.net/Articles/548089/
cambios para el kernel 3.9
13.5.
13.5.1.
Referencias Basicas
wikipedia
developer ext3 stat art
Mingming Cao, Theodore Y. Tso, Badari Pulavarty, Suparna Bhattacharya, Avantika Mathur
13.5.2.
Introduction
Kernel
27 / 94
UFS
Unix File System
Berkeley File system : Fast File System FFS
Hoy en da es el sistema de Solaris
Metadata Structure
Minix utiliza una versin simplificada de ufs
BootBlock - SuperBlock - InodeBitMap - ZoneBitMap - InodeTable - Data
13.5.3.
EXT
EXT
http://www.ibm.com/developerworks/linux/library/l-anatomy-ext4/
Remy Card, April 1992
Linux kernel 0.96c
2GB
VFS
13.5.4.
EXT2
EXT2
http://e2fsprogs.sourceforge.net/ext2intro.html
Remy Card, Enero 1993
Standard:
extended supported file systems of 4TB in size evoluciona hasta 32TB
Layout: BootSector-BlockGroup1-BlockGroup2 Each block group contains a redundant copy of crucial filesystem control informations (superblock and the filesystem
descriptors) and also contains a part of the filesystem (a block bitmap, an inode bitmap, a piece of the inode table, and
data blocks)
BlockGroup Layout: SuperBlock- FSDespcriptors- BlockBitMap - InodeBitMap - InodeTable - DataBlocks
13.5.5.
EXT3
EXT3
Stephen Tweedie, noviembre 2001
Maintainer: Theodore Tso
journaling
13.5.6.
EXT4
EXT4
http://www.ibm.com/developerworks/linux/library/l-anatomy-ext4/
1 ExaByte
Theodore Tso, Diciembre 2008
Kernel 2.6.28
Kernel
28 / 94
Copia el concepto extent del sistema JFS de IBM: the extent approach to block management
improvements in timestamps: en resolucin pasando de segundos a nanosegundos y en rango hasta 500 aos.
escalabilidad:
file system volumes, file sizes, and subdirectory limits
Extents: agrupa bloques de forma contigua permitiendo referencias extents en lugar de bloques individuales
perfomance
file level preallocation
delay allocation
multiblock allocation
reliability
checksum
online degramentation
13.6.
13.7.
EXT4: Introduction
La estructura del sistema de ficheros se organiza entre el nivel fsico y los niveles abstractos a distintos niveles.
El nivel VFS se estructura de forma muy parecida al Sistema de Ficheros especfico Extendido EXT4, por lo que estudir EXT4
significa estudiar VFS.
Para comprender la informacin que manipula el VFS o EXT4 podemos hacerlo va las estructuras de datos en C donde se explica
el significado de cada campo o va algn libro que describa est misma informacin sin detallar que es parte de una estructrura
de datos en C. Por lo que interesa tener un libro, tener las estructuras de VFS y tener la referencia de EXT4.
El mejor mtodo de aprendizaje es estudiar la evolucin de los sistema de ficheros en linux.
ufs ext ext2 ext3 ext4
13.7.1.
Referencias
13.8.
13.9.
13.9.1.
Layout Disk
Tanenbaum
MBR-Partition Table-Partition1-Partition2-. . . -PartitionN
13.9.2.
Layout Partition
Tanenbaum
Boot_Block - Superblock - Free_space_manager - I_nodes -
Kernel
29 / 94
13.9.3.
13.9.4.
Layout SuperBlock
13.9.5.
Layout Inode
13.9.6.
Directory Indexing
Distintas estructuras de datos (algoritmos de bsqueda etc) se han utilizado para organizar el rbol jerrquico de directorios
del FS.
list linking : ext2,ext3
Htree
ext3, ext4
Hash Tree
ms fcil de implementar que Btree
phillips
State of the Art: Where we are with the Ext3 filesystem
forensics fairbanks
13.10.
http://docs.huihoo.com/linux/kernel/a1/#Toc_3_3
Figure 3.3: Virtual File System in Context
Kernel
30 / 94
13.10.1.
Introduction
Al igual que otros subsistema del kernel el gestor de archivos del Sistema Operativo abstrae todo lo fsico para facilitar la tarea
del administrador de sistemas. La abstraccin es jerrquica por niveles, siendo las capas superiores las ms abstractas y ms
prximas a las tareas del administrador.
The virtual file system is designed to present a consistent view of data as stored on hardware devices. Almost all hardware devices
in a computer are represented using a generic device driver interface. The virtual file system goes further, and allows the system
administrator to mount any of a set of logical file systems on any physical device. Logical file systems promote compatibility
with other operating system standards, and permit developers to implement file systems with different policies. The virtual file
system abstracts the details of both physical device and logical file system, and allows user processes to access files using a
common interface, without necessarily knowing what physical or logical system the file resides on.
In addition to traditional file-system goals, the virtual file system is also responsible for loading new executable programs. This
responsibility is accomplished by the logical file system module, and this allows Linux to support several executable formats.
13.10.2.
Capas:
system call (open,close,etc ) virtual file system (VFS) logical file systems (ext4,ext3,vfat,etc) device driver (kernel
module) physical device(hdd, cd, usb, etc)
Kernel
31 / 94
System Call system independent interface (VFS: vnode, etc) logical FS Device Independent interfaz (operaciones
con bloques o character) Device Driver (comandos de la controladora) HW (controladora, puerto, periferico)
System Call
Es la interfaz del administrador para pedir al kernel la realizacin de una tarea de gestin de ficheros. Ejemplo: escribir en
un fichero, crear un fichero, eliminar un fichero, etc
Capa VFS: Virtual File Switch
es level root de la estructura lgica del sistema de ficheros. El level superior.
Implementa un modelo comn de gestin de ficheros independientemente del Sistema de Ficheros Lgico encargado de
gestior el disco duro.
Conmuta entre los distintos tipos especficos de ficheros: ext4, ntfs, fat, etc
Logical File System
Es el sistema de ficheros especfico con el que ha sido formateado el disco duro. Depende del sistema operativo.
Se encarga de organizar y acceder a los ficheros mediante una interfaz. Convierte operaciones de fichero en operaciones de
bloque.
Ejemplos: Ext4 en Linux, NTFS en Windows
Device Independent Interfaz
Operaciones a nivel de dispositivo independientemente del tipo especfico de dispositivo usb,hdd,CD, etc
Es el Device File de tipo bloque o carcter: sobre estos dispositivos se realizan operaciones de tipo bloque o carcter, por
eso es un fichero especial diferente de los ficheros regulares.
Device Driver
Traslada las operaciones de bloque a comandos de la controlador i/o especfica del driver de la unidad de almacenamiento
masivo
Ejemplo: write() sys_write() logical fs write METHOD device
write() es la llamada al sistema realizada por el usuario
sys_write() analiza el descriptor de fichero para saber a que tipo sistema lgico de ficheros hace referencia y por lo tanto
selecciona la funcin de escritura.
se ejecuta la funcin o mtodo de escritura especifica del FS llamando al device driver.
13.10.3.
There is one device driver module for each supported hardware controller. Since there are a large number of incompatible
hardware devices, there are a large number of device drivers. The most common extension of a Linux system is the addition of a
new device driver.
The Device Independent Interface module (API de bloques y caracteres) provides a consistent view of all devices. Ver DRIVERS
(Device File)
There is one logical file system module for each supported file system.
The system independent interface (VFS) presents a hardware and logical-file-system independent view of the hardware resources.
This module presents all resources using either a block-oriented or character-oriented device file interface.
Finally, the system call interface provides controlled access to the file system for user processes. The virtual file system exports
only specific functionality to user processes.
Kernel
32 / 94
13.10.4.
Data Representation
All files are represented using i-nodes. Each i-node structure contains location information for specifying where on the physical
device the file blocks are. In addition, the i-node stores pointers to routines in the logical file system module and device driver
that will perform required read and write operations. By storing function pointers in this fashion, logical file systems and device
drivers can register themselves with the kernel without having the kernel depend on any specific module.
13.10.5.
One specific device driver is por ejemplo a ramdisk; this device allocates an area of main memory and treats it as a persistentstorage device. This device driver uses the memory manager to accomplish its tasks, and thus there is a dependency, control flow,
and data flow between the file system device drivers and the memory manager.
One of the specific logical file systems that is supported is the network file system NFS (as a client only). This file system accesses
files on another machine as if they were part of the local machine. To accomplish this, one of the logical file system modules
uses the network subsystem to complete its tasks. This introduces a dependency, control flow, and data flow between the two
subsystems.
As mentioned in memory section, the memory manager uses the virtual file system to accomplish memory swapping and memorymapped I/O. Also, the virtual file system uses the process scheduler to disable processes while waiting for hardware requests to
complete, and resume them once the request has been completed. Finally, the system call interface allows user processes to call
in to the virtual file system to store or retrieve data. Unlike the previous subsystems, there is no mechanism for users to register
for implicit invocation, so there is no control flow from the virtual file system towards user processes (resuming processes is not
considered control flow).
13.11.
Los objetos de los sistemas de ficheros son distintas estructuras de datos que almacenan informacin abstracta de la estructura
y organizacin del sistema de ficheros. Cada tipo de objeto o estructura de datos se implementa como un rea de memoria en el
espacio de kernel de la memoria RAM.
Objects
file object
directory object
directory entry object
inodes object
superblock object
caches
page cache:
conceptos hw cache (cache de la DRAM), memory cache (allocation memory slab), disk cache (cache en DRAM del
HDD)
Con Page Cache nos referimos a Disk Cache.
Page es un agrupamiento de bloques.
copia temporalmente en DRAM las peticiones (R/W) entre el sistema de ficheros y la unidad fsica HDD.
Si los datos ms probables de leer o escribir estn en RAM, el acceso es ms rpido que acceder al disco duro.
Un algoritmo para decidir que info guardo temporalmente es la LRU (Least Recent Used), el usado recientemente.
En la Page cache hay pginas de datos y pginas de control de distintos ficheros
A las pginas de control se les llama buffer cache.
sincronizar el buffer cache es hacer un flush del buffer copiando su contenido en el disco duro y posteriormente vaciar
el buffer.
inode cache:
dentry cache:
Kernel
33 / 94
13.12.
File Descriptor
13.13.
File Object
VFS file represents an open file (keeps state for the open file such as the write offset, and so on).
13.14.
Directory Object
13.15.
Path
El anidamiento de directorios o carpetas da lugar a las rutas cuyos componentes son los dentry
13.16.
dentry
A dentry (short for "directory entry") is what the Linux kernel uses to keep track of the hierarchy of files in directories. Each
dentry maps an inode number to a file name and a parent directory.
translate between file names and file inodes. The dentry also maintains relationships between directories and files for traversing
file systems
13.17.
Node
Kernel
34 / 94
13.18.
Superblock
Toda la informacin (files, directory, inodes, dentry) es controlada por la informacin del superbloque, que es un metadato del
todo el sistema de ficheros. Por ejemplo, cuantos directorios hay, cuantos bloques libres, etc
Es un objeto de la capa superior VFS.
man dumpe2fs
13.19.
Tipos de FS
Referencia
/usr/src/linux-3.4.4/Documentation/filesystems/
man fs
listado de sistemas de ficheros soportados o registrados: gedit /proc/filesystems
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
nodev
sysfs
rootfs
bdev
proc
cgroup
cpuset
tmpfs
devtmpfs
debugfs
securityfs
sockfs
pipefs
anon_inodefs
devpts
ext3
ext4
ramfs
hugetlbfs
ecryptfs
fuseblk
fuse
fusectl
pstore
mqueue
btrfs
binfmt_misc
vfat
Logical FS soportados
ext3
ext4
fuseblk
btrfs
vfat
nodev:
son pseudosistemas ya que no hay un dispositivo fsico asociado a l, son virtuales.
se pueden implementar en RAM
procfs: el kernel genera este sistema de ficheros como interfaz user-kernel con info sobre procesos
Kernel
35 / 94
sysfs : el kernel genera este sistema de ficheros como interfaz user-kernel con info sobre procesos
debugfs
configfs
etc
13.20.
VFS layer
The VFS keeps track of:
the currently-supported file systems
cat /proc/filesystems
13.21.
Filesystem
/dev/sda1
ext2
/dev/sda2
ext3
-tmpfs
/var/local/home bind mount
/var/local/srv bind mount
Mount point
/
/var
/tmp
/home
/srv
RO/RW
RO
RW
RW
RW
RW
Kernel
36 / 94
13.21.1.
mount
CHROOT
13.22.
Devices
Device File
Son los file system nodes interfaces con los dispositivos y que estn montados en /dev/
Es la interfaz entre el sistema de ficheros y el driver del dispositivo.
Es un fichero especial o sistema de ficheros, de tipo bloque o carcter que interfiere con el driver del dispositivo. Tiene que
traducir estructuras de tipo fichero a estructuras de tipo bloque o carcter. Ver apuntes de drivers, major-minor number, etc ..
Tipos de Device Files
Unidades de almacenamiento tipo bloque
/dev/sda
/dev/sdb
/dev/fd
/dev/sr
Especiales
/dev/null
/dev/zero
/dev/loop
Kernel
37 / 94
13.22.2.
/dev/loop
Es un dispositivo de tipo bloque virtual ya que el file node no est asociado directamente a una unidad de almacenamiento
externa como un usb, etc.
En lugar de estar asociado a una unidad fsica, se asocia a un fichero regular. Es decir, /dev/loop es la interfaz a un fichero que
emula a un dispositivo.
Como el fichero regular asociado al Device File /dev/loop est almacenado en la misma particin, se habla de loop back.
Si el device file /dev/loop est almacenado en una particin del disco duro ST9500420AS Seagate . Todos los datos que
se dirigen a la interfaz /dev/loop no van a otro dispositivo (CD, usb, hdd, etc) sino que vuelven ( LOOP BACK) al mismo
disco duro ST9500420AS Seagate. El concepto LOOP BACK tiene una segunda interpretacin y creo que es la adecuada:
se puede ver como el flujo de datos que llega a la capa /dev/loop procedente de VFS y no baja a un dispositivo fsico sino
que retorna a un fichero, es decir, retorna a la capa VFS.
Esquema
14.
Virtual Disks
concepts &
dd, formatting, qcow, loop devices
15.
15.1.
Referencias
15.2.
Introduction
El objetivo es entender los conceptos de un sistema de ficheros desde el punto de vista prctico, es decir, desde el punto de
vista del administrador.
Kernel
38 / 94
15.3.
losetup (loop-setup)
15.4.
Tutorial Basico. I.
http://web2.clarkson.edu/projects/itl/honeypot/ddtutorial.txt
Crear un sistema de ficheros virtual propio. (Un sistema de ficheros virtual sera el asociado a uno real de una nica particin)
$ dd if=/dev/zero of=~/myFileSystem.img bs=1024 count=1048576
regular myFilesystem.img y lo inicializa a ceros.
1048576+0 records in
1048576+0 records out
1073741824 bytes (1.1 GB) copied, 12.2151 s, 87.9 MB/s
Observo que me da informacin de objetos del gestor de ficheros de VFS del kernel: inodes, superblock, etc
man mke2fs:
create an ext2/ext3/ext4 filesystem
The defaults of the parameters for the newly created filesystem, if not overridden by the options listed below, are controlled
by the /etc/mke2fs.conf configuration file. See the mke2fs.conf(5) manual page for more details.
Dispositivos virtuales o PseudoDispositivos
Kernel
39 / 94
/dev -
El sistema de ficheros est sin enlazar con un dispositivo virtual y tambin est sin montar por lo que no puedo acceder a l
para ejecutar comandos como crear ficheros, carpetas, etc
asociacion sistemafichero(myfilesystem) con dispositivo virtual /dev/loopx
$ losetup -j myFileSystem.img -> informa de cual es el dispositivo enlazado al fichero imagen -> en este caso ninguno
$ losetup myFileSystem.img
loop: cant get info on device myFileSystem.img: Inappropriate ioctl for device
$ losetup /dev/loop0 myFileSystem.img -> enlace entre el dispositivo y el sistema de ficheros
$ losetup -j myFileSystem.img -> consulta qu dispositivo est asociado al sistema de ficheros
/dev/loop0: [0803]:4596853 (/home/candido/tutoriales/dev_loop/myFileSystem.img)
$ ls -l /proc/fs/ext4 -> el kernel INFORMA de los dispositivos con sistema de ficheros tipo ext4 que estn montados
$ losetup -d /dev/loop0 -> elimina el enlace
Dec
Dec
Dec
Dec
Dec
Dec
8
8
8
8
8
8
12:53
12:53
12:53
12:53
12:53
12:53
delayed_allocation_blocks
inode_goal
inode_readahead_blks
lifetime_write_kbytes
max_writeback_mb_bump
mb_group_prealloc
Kernel
40 / 94
-rw-r--r--rw-r--r--rw-r--r--rw-r--r--rw-r--r--r--r--r--
1
1
1
1
1
1
root
root
root
root
root
root
root
root
root
root
root
root
4096
4096
4096
4096
4096
4096
Dec
Dec
Dec
Dec
Dec
Dec
8
8
8
8
8
8
12:53
12:53
12:53
12:53
12:53
12:53
mb_max_to_scan
mb_min_to_scan
mb_order2_req
mb_stats
mb_stream_req
session_write_kbytes
Ahora puedo poblar el sistema de ficheros generando, moviendo, copiando ficheros en /mnt/virtual ya que realmente lo que
estamos poblando es el fichero imagen myFileSystem, es decir, estoy poblando la imagen de mi sistema de ficheros virtual.
$ cd /mnt/virtual
$ touch prueba.txt
$ echo "hola" > prueba.txt
$ ls -l /mnt/virtual
total 20
-rw-rw-r-- 1 candido candido
11 Dec
drwx------ 2 root
root
16384 Dec
8 12:58 prueba.txt
8 12:08 lost+found
Se puede asociar y montar en una misma orden con mount. Asociacion sistemafichero(myfilesystem) con dispositivo virtual
y montaje del fichero(myfilesystem) en el sistema de ficheros general.
$ sudo mkdir /mnt/virtual ->punto de montaje
$ sudo mount -o loop myFileSystem.img /mnt/virtual ---> Con la opcin -o loop realizamos la asociacin previa la montaje
$sudo mount myFileSystem.img /mnt/virtual ---> tambin se realizar la asociacin ya que el fichero myFileSystem es un sistema de ficheros.
$ $ mount | grep myFileSystem
/home/candido/tutoriales/dev_loop/myFileSystem.img on /media/borrar type ext4 (rw) ----------> NO MUESTRA EL DISPOSITIVO /dev/loop1
15.5.
Kernel
41 / 94
[root]
INODE:
debugfs: stat .
PATH: /
--> estadstica del inode especificado
Inode: 2
Type: directory
Mode: 0755
Flags: 0x80000
inode number 2
Generation: 0
Version: 0x00000000:00000001
User: 1000
Group: 1000
Size: 4096
File ACL: 0
Directory ACL: 0
Links: 4
Blockcount: 8
Fragment: Address: 0
Number: 0
Size: 0
ctime: 0x51e988e1:81ca1804 -- Fri Jul 19 20:43:45 2013
atime: 0x51e9958a:0c2e5614 -- Fri Jul 19 21:37:46 2013
mtime: 0x51e988e1:81ca1804 -- Fri Jul 19 20:43:45 2013
crtime: 0x51e97764:00000000 -- Fri Jul 19 19:29:08 2013
Size of extra inode fields: 28
EXTENTS:
(0):73
(END)
--> entra en una nueva consola con los atajos --> h
blocks .
1
blocks
-->
ls -l
2
2
11
40755 (2)
40755 (2)
40700 (2)
perdidos
1000
1000
1000
1000
1000
1000
--> objetos
(END)
-------------------> en esta nueva consola teclear h para info de los atajos, q para
salir
ls -l lost+found
q
-------> quit
stat
imap .
Inode 2 is part of block group 0
located at block 97, offset 0x0100
icheck 97
--> buscar el inode relacionado con un bloque determinado
Block
Inode number
97
<block not found>
stats
params
features
opciones de debugs
Kernel
42 / 94
15.6.
15.7.
sudo parted
Particiones del HDD
$ sudo parted
(parted) print
Model: ATA ST9500420AS (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number
1
2
3
Start
32.3kB
105GB
110GB
End
105GB
110GB
425GB
Size
105GB
5240MB
315GB
Type
primary
primary
primary
File system
ntfs
ntfs
ext4
Flags
boot
15.8.
Start
0.00B
End
1074MB
Size
1074MB
File system
ext4
Flags
Kernel
43 / 94
15.9.
importante
http://lnx.cx/docs/vdg/output/Virtual-Disk-Operations.html#VDG-Concepts-Creation
candido.img
104857600
Blocks: 204808
IO Block: 4096
regular file
803h/2051d
Inode: 5768315
Links: 1
(0664/-rw-rw-r--) Uid: ( 1000/ candido)
Gid: ( 1000/ candido)
2014-06-16 13:39:27.315674214 +0200
2014-06-16 13:39:23.095757294 +0200
2014-06-16 13:39:23.095757294 +0200
-
---> OJO
Necesito herramientas para manipular el disco ntfs: para generar una particin, tabla de particiones, etiqueta, etc
sudo parted candido.img mklabel msdos: Crear una tabla de particiones
Kernel
44 / 94
Start
End
Blocks
Id
--> SE MANTIENE
System
With a loop device inserted between programs and our disk image we can view and operate on the disk image as if it were
a regular drive. When accessed through a loop device fdisk can properly determine the number of cylinders, heads, and
everything else required to create partitions.
El sistema operativo no puede realizar operaciones de bloque sobre un fichero si este no est asociado a un dispositivo de
bloque
Tenemos dos alternativas para formatear el disco:
fdisk menu
gparted gui
1 ALTERNATIVA FALLADA: Mediante fdisk menu no lo he realizado bien
* +sudo fdisk /dev/loop0+ -> m-n-p-1-primer_sector:default:2048 - last_sector:default, ->
t-1-fs_code=7 (NTFS), ->w
+sudo
partprobe /dev/loop0+
*
* +fdisk -l /dev/loop0+
* Sectores
** En total hay 204800 sectores: desde el 0 hasta el 204799
** En el primer sector (sector 0) est el MBR.
** La particin_1 comienza en el sector 2048 y finaliza en la 204799 -> 202752 sectores en
al primera particin.
** qu hay en los sectores 1-2047? Modern boot loaders (NTLDR[28], GRUB[29], etc) use this space to store additional code and data necessary to boot the system
* /dev/loop0p1 es la particin 1 del disco loop0
* 2048*512 = 1048576 bytes : offset desde el comienzo del disco hasta la primera particin
.
* +sudo losetup -o 1048576 -f /dev/loop0+ -> asocio la particin 1 de /dev/loop0 al dispositivo /dev/loop1
IMPORTANT: POR QUE?? Para formatear la primera particin y poder MONTARLA para acceder
a ella a travs del sistema de ficheros.
Kernel
45 / 94
Kernel
46 / 94
* +fdisk -l /dev/loop0+ -> no es correcta la info del volcado porque deba dar info de una particin.
fdisk
-l /dev/loop0
*
Disk /dev/loop0: 104 MB, 104857600 bytes
255 heads, 63 sectors/track, 12 cylinders, total 204800 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x2052474d
This doesnt look like a partition table
Probably you selected the wrong device.
Device Boot
Start
/dev/loop0p1
?
6579571
/dev/loop0p2
? 1953251627
/dev/loop0p3
?
225735265
/dev/loop0p4
2642411520
End
1924427647
3771827541
225735274
2642463409
Blocks
958924038+
909287957+
5
25945
Id
70
43
72
0
System
DiskSecure Multi-Boot
Unknown
Unknown
Empty
Start
2048
104448
End
104447
165887
Blocks
51200
30720
Id
7
83
System
HPFS/NTFS/exFAT
Linux
mmls candido.img
DOS Partition Table
Offset Sector: 0
Units are in 512-byte sectors
00:
01:
02:
03:
04:
Slot
Meta
----00:00
00:01
-----
Start
0000000000
0000000000
0000002048
0000104448
0000165888
End
0000000000
0000002047
0000104447
0000165887
0000204799
Length
0000000001
0000002048
0000102400
0000061440
0000038912
Description
Primary Table (#0)
Unallocated
NTFS (0x07)
Linux (0x83)
Unallocated
Kernel
47 / 94
0000
2100
3a06
0000
0000
0000
077f
8353
0000
0000
0000
3906
090a
0000
0000
0000
0008
0098
0000
0000
3a67
0000
0100
0000
0000
0e00
0090
00f0
0000
0000
0000
0100
0000
0000
0000
0020
007f
0000
0000
55aa
........:g.....
!...9...........
:..S............
................
..............U.
16.
16.1.
16.2.
Books
file system forensic analysis, Brian Carrier: descargado, portal con herramientas
http://www.porcupine.org/forensics/forensic-discovery/: online
16.3.
Tools
Kernel
48 / 94
17.
17.1.
NTFS
http://www.tuxera.com/community/ntfs-3g-manual/
New Technology File System
Sistema adecuado para las particiones de gran tamao requeridas en estaciones de trabajo de alto rendimiento y servidores,
hasta 2641 clsteres.
Sistema de Windows NT
Controlador NTFS-3G
Driver de Linux que permite acceder a sistemas NTFS
NTFS-3G monta las particiones NTFS usando el mdulo de espacio de usuario FUSE
modprobe -l | grep ntfs : driver ntfs
17.2.
Fuse
fuse home
The FUSE kernel module and the FUSE library communicate via a special file descriptor which is obtained by opening
/dev/fuse
cat /proc/filesystems nodev fuse sistema de ficheros fuse
modprobe -l | grep fuse : driver fuse
17.3.
gvfs
17.4.
usb:mtp,ptp
usb
Multimedia Transfer Protocol : mtp
mtp
https://wiki.archlinux.org/index.php/MTP
Picture Transfer Protocl ptp
how to smartphone
practico con comandos en linea
Kernel
49 / 94
18.
DMA
19.
Video
20.
Networking
20.1.
Overview
20.2.
Ejemplo
user application: navegador firefox application level: HTTP
Transport level : TCP (fiable: sin errores y segura)
la frontera entre HTTP y TCP la establece el socket
Network Level: IP (no fiable)
Link Level: ethernet
20.3.
TCP
Kernel
50 / 94
Socket
In Unix operatingsystems, the software performingall the tasks and protocols described above is usually part of the kernel, and
so it is in Linux. The programming interface most common in the Unix world is the Berkeley Socket Library. Its name derives
from a popular analogy that views ports as sockets and connecting to a port as plugging in. It provides the bind call to specify
a remote host, a transport protocol, and a service that a program can connect
Ver IPC-Sockets
20.4.
WIFI
21.
21.1.
21.2.
API
21.3.
ABI
21.4.
ISA
Kernel
51 / 94
22.
Compilacin kernel
22.1.
Tutoriales
22.1.1.
Excesivamente simple
http://www.linuxchix.org/content/courses/kernel_hacking/lesson0
http://www.haifux.org/lectures/88-sil/kernel-compilation.html
http://kernelnewbies.org/KernelBuild: recomendado
http://linux.yyz.us/git-howto.html#update_tree: bajar el kernel con git
22.1.2.
Completo
22.2.
Flavors
22.2.1.
PC
22.3.
Versiones
linux 2.4
22.4.
Configuration
22.5.
Debugger
http://kernel-handbook.alioth.debian.org/ch-scope.html
Kernel
52 / 94
23.
23.1.
vmlinux
VirtualMemoryLinux
archivo ejecutable que contien el nucleo del sistema operativo en formato:ELF, COFF, etc que nicamente se puede utilizar
para depurarlo, no para cargarlo en ram.
para usarlo como ncleo del sistema operativo debe ser capaz de ejecutarse e iniciar el computador. Para esto se debe agregar
un encabezado de arranque mltiple, un sector de arranque y rutinas de inicializacin.
el kernel vmlinux lleva asociado el fichero de smbolos system.map
imagen de vmlinux: bzimage
mvlinux se comprime con zlib y se genera la imagen vmlinuz o zImage
Big Compressed Image: debido al tamao grande del ncleo fue necesario el formato bzimage que permite dividir el ncleo
en regiones no contiguas de memoria.
El archivo bzImage contiene la concatenacin de
24.
bootsect.o
setup.o
misc.o
piggy.o : gzip del kernel vmlinux
https://wiki.gentoo.org/wiki/Custom_Initramfs
25.
http://www.linuxfromscratch.org/lfs/view/development/index.html
nota
No sigo las instrucciones del libro porque hace falta instalar primero versiones especficas de las herramientas y
tambin PARCHES . Pero sera interesante leerlo para entender el proceso de instalacin. Intentar hacerlo con las
herramientas ya instaladas me imagino que dar problemas ya que por lo menos los parches no sern apropiados.
Resumiendo, tiene inters como mtodo de aprendizaje y no como mtodo prctico universal.
http://www.escomposlinux.org/lfs-es/lfs-es-SVN/chapter03/introduction.html
mkdir -p ~/tutoriales/lfs
cd tutoriales
export LFS=lfs
mkdir -v $LFS/sources
chmod -v a+wt $LFS/sources
Kernel
53 / 94
26.
26.1.
Referencia
https://sites.google.com/site/4utils/articles/minimal_linux_system/minimal-linux-system-from-scratch
http://emsys.denayer.wenk.be/emedu/linux_from_scratch_qemu_tutorial.pdf: utiliza la librera uclibc. Recomendado. He realizado este tutorial pero todava no lo he terminado. Est copiado de:
http://free-electrons.com/doc/embedded_lfs.pdf
http://free-electrons.com/doc/embedded_lfs.odp
LFS
lfs spanish: versin 6.3
bfls qemu
26.2.
Introduccin
26.3.
Herramientas Necesarias
toolchain
uclibc
busybox
root file system
kernel menuconfig
26.4.
26.4.1.
Introduccion
Para utilizar la librera uclibc no s donde tengo que instalarla, tampoco s donde instalar el toolchain. Seguir el tutorial de
freelectronics en lugar del de denayer.
Kernel
54 / 94
26.4.2.
Preface
libc6-dev
gcc
make
linux-headers-386
libncurses5-dev
libuclibc-dev >
en ubuntu 12.04 no existe. http://uclibc.org/: uClibc (aka Clibc/pronounced yew-see-lib-see) is a C library for developing
embedded Linux systems.
en la web de busybox, http://www.busybox.net/:
On Linux, Busybox releases are tested against uClibc (0.9.27 or later) and glibc (2.2 or later)
If you require a small C library for Linux, the Busybox developers recommend uClibc
http://busybox.net/~vda/HOWTO/i486-linux-uclibc/HOWTO.txt
conclusin: descargo el fuente uclibc y lo compilo con make menuconfig y make.
http://www.eglibc.org/home. tengo instalado el paquete libc-dev-bin
uclibc-toolchain > http://www.uclibc.org/toolchains.html: genero el toolchain manualmente: native uClibc toolchain using
the uClibc buildroot system. Est explicado en los apartados siguientes
26.4.3.
Buildroot
Kernel
55 / 94
26.4.6.
Create uclibc
cd ~/git_repos/buildroot
make menuconfig
Target Options: i386 y core2
Toolchain
Cross compilation:NONE
make
OUTPUT candido@lur:~/git_repos/buildroot/output$ ls build host images staging target
build
buildroot-config
host-gmp-6.0.0a
host-mpc-1.0.2 -
host-m4-1.4.17
host-mpfr -
host-makedevs-undefined
linux-headers -
host-fakeroot-1.18.2
toolchain-undefined
host-gcc-final-4.7.3
uclibc-0.9.33.2
host-gcc-initial-4.7.3
_users_table.txt
build-time.log
-3.1.2
busybox-1.22.1
-2.6.32
libintl
libpthread
libm
libresolv
libnsl
librt
i686-buildroot-linux-uclibc
include
lib
libexec
share
TOOLCHAIN ~/git_repos/buildroot/output/host/usr/i686-buildroot-linux-uclibc/bin$ ls
ar
as
cc
gcc
images/rootfs.tar
staging
ld
ld.bfd
nm
objcopy
objdump
ranlib
strip
Kernel
56 / 94
bin
lib
lib32
usr
target
bin
opt
proc
root
run
sbin
sys
ha creado:
imagen: root file system
librera uclibc
toolchain
26.4.8.
Duda
Create kernel
Create filesystem
cd ../
dd if=/dev/zero of=rootfs.img bs=1024k count=1
mkfs.ext2 -i 1024 -F rootfs.img
26.4.11.
Create Busybox
cd busybox-1.22.1
make menuconfig
Busybox Settings >
Build Options >
Build BusyBox as a static binary >
YES
Busybox Settings >
Build Options >
Build BusyBox with a Cross Compiler >
Kernel
57 / 94
YES
Busybox Settings >
Build Options >
Cross Compiler prefix:
/usr/i386uclibclinux/
bin/i386uclibclinux
Coreutils >
cat chmod chown chroot cp cut date df du echo env false head ln ls mkdir
mknod mv printf pwd rm rmdir sleep sort stat stty sync tail test touch true tty uname
Console Utilities >
setconsole
Editors >
vi
Finding Utilities >
grep
Init Utilities >
init
Login/Password Management Utilities >
addgroup delgroup adduser deluser getty login
passwd su
Linux System Utilities >
more mount umount
Process Utilities >
free kill
Shells >
ash
Shells >
Choose your default shell >
ash
# make
sudo make install
26.4.12.
Fill filesystem
cd ..
sudo mkdir /mnt/rootfs
sudo mount -o loop rootfs.img /mnt/rootfs
rsync -a busyboxxxx/_install/* /mnt/rootfs/
sudo mkdir /mnt/rootfs/dev
sudo mkdir /mnt/rootfs/etc
sudo mkdir /mnt/rootfs/proc
sudo mkdir /mnt/rootfs/sys
sudo mkdir /mnt/rootfs/etc/init.d
sudo mknod /mnt/rootfs/dev/console c 5 1
sudo mknod /mnt/rootfs/dev/null c 1 3
Create file (/mnt/rootfs/etc/inittab)
Kernel
58 / 94
26.5.
26.6.
FUNCIONA O NO FUNCIONA
????????????????
27.
QEMU
28.
28.1.
blog
linux 3.2, armv7, versatile express platform, linaro toolchain.
blog
linux 3.9, busybox, versatile express platform, qemu from linaro, codesourcery platform
29.
29.1.
http://retired.beyondlogic.org/uClinux/builduC.htm
Kernel
59 / 94
29.2.
Flavors
29.3.
Platforms
30.
30.1.
Referencias
30.2.
http://mgalgs.github.io/2015/05/16/how-to-build-a-custom-linux-kernel-for-qemu-2015-edition.html
Arranca en menos de un segundo. Creo que el sistema de ficheros est en ram. No hay disco duro
31.
TEST
31.1.
Kernel
60 / 94
32.
TODO: ME GUSTARIA
32.1.
http://wiki.osdev.org/Detecting_Memory_%28x86%29#BIOS_Function:_INT_0x15.2C_EAX_.3D_0xE820
lo referencian en el Manula de Pure64 de Return Infinity Os bare metal : https://github.com/ReturnInfinity/Pure64/blob/master/Pure64%20Manual.md
32.2.
bare_metal de devos_myos i686 con color y el de kernel-201 con teclado de Arjun Sreedharan
32.3.
baremetal-qemu-kernel(keyboard-busybox)-file system
objetivo: Cmo aadir a un kernelconkeyboard la posibilidad de interpretar unos pequeos comandos (editar un fichero)
http://elinux.org/QEMU
33.
http://susam.in/articles/boot-sector-code/
#
#
#
#
#
#
#
#
#
.code16
.section .text
.globl _start
_start:
mov $0xb800, %ax #direccin de la memoria de video -> VGA
mov %ax, %ds
#inicializo el registro del segmento de datos
movb $A, 0
#en el offset cero (DS:0) cargo el byte A -> caracter a escribir
movb $0x1e, 1
#en el offset uno (DS:1) cargo el byte ox1e -> color background y foreground
idle:
jmp idle # bucle infinito
Kernel
61 / 94
string.s
as -o string.o string.s
ld --oformat binary -Ttext 7c00 -Tdata 7c20 -o string string.o Ttext es el offset de la seccin
While booting, the BIOS reads the code from the first sector of the boot device into the memory at physical address
0x7c00 and jumps to that address.
objdump -bbinary -mi8086 -D string
hd string
string.com para emular con emulDOS
as -o string.o string.s
ld --oformat binary -Ttext 100 -Tdata 120 -o string.com string.o
objdump -bbinary -mi8086 -D string.com
hd string.com
cp string.con ~/.dosemu/drive_c
Ctrl-F1 : lo ejecuto desde la consola
cd ~/.dosemu/drive_c
SOLUCION
Qu tal ejecutar DOSBox: http://www.dosbox.com/
34.
35.
Kernel
62 / 94
36.
36.1.
Kernel 101
36.1.1.
intro
FUNCIONA
http://arjunsreedharan.org/post/82710718100/kernel-101-lets-write-a-kernel
simple kernel which could be loaded with the GRUB bootloader on an x86
runs in protected mode and prints a string on the screen
tools
NASM assembler
gcc
ld (GNU Linker)
grub
https://github.com/arjun024/mkernel
36.1.2.
kernel
source modules
kernel.asm: run on a processor operating in 32 bit mode. Call to kmain()
kmain.c : memory in protected mode
The memory mapped input/output for the screen starts at [0xb8000] and supports 25 lines, each line contain 80 ascii
characters
linker script link.ld
enlazar kernel.o y kmain.o
definicion de las secciones
we set the location counter to [0x100000]
After the linker places the text output section, the value of the location counter will become 0x1000000 ms the size of
the text output section.
36.1.3.
boot process
CPU 0xFFFFFFF0 address :apunta al top -16bytes del espacio de 32 bytes (4GBytes) ser una direccin de la bios
en esos 16 bytes hay una instruccin de salto incondicional a la direccin donde estn las siguientes instrucciones de la bios
Bios
a. BIOS first searches for a bootable device in the configured boot device order. It checks for a certain magic number to
determine if the device is bootable or not.
b. Once the BIOS has found a bootable device, it copies the contents of the devices first sector into RAM starting from
physical address 0x7c00. El cdigo se ha copiado ha sido el bootloader
c. El espacio de direcciones pasa de la Flash de la Bios a la RAM: jump 0x7c00 : se ejecuta el bootloader cargado
previamente en la RAM
d. The bootloader then loads the kernel at the physical address [0x100000]
Kernel
63 / 94
36.1.4.
kernel building
kernel.c
/*
* kernel.c
*/
void kmain(void)
{
const char *str = "my first kernel";
char *vidptr = (char*)0xb8000; //video mem begins here.
unsigned int i = 0;
unsigned int j = 0;
/* this loops clears the screen
* there are 25 lines each of 80 columns; each element takes 2 bytes */
while(j < 80 * 25 * 2) {
/* blank character */
vidptr[j] = ;
/* attribute-byte - light grey on black screen */
vidptr[j+1] = 0x07;
j = j + 2;
}
j = 0;
/* this loop writes the string to video memory */
while(str[j] != \0) {
/* the characters ascii */
vidptr[i] = str[j];
/* attribute-byte: give character black bg and light grey fg */
vidptr[i+1] = 0x07;
++j;
i = i + 2;
}
return;
}
GRUB will only load our kernel if it complies with the Multiboot spec.
modificamos el kernel.asm
;;kernel.asm
;nasm directive - 32 bit
bits 32
section .text
;multiboot spec
align 4
dd 0x1BADB002
;magic
dd 0x00
;flags
dd - (0x1BADB002 + 0x00) ;checksum. m+f+c should be zero
global start
extern kmain
start:
cli
mov esp, stack_space
call kmain
hlt
;block interrupts
;set stack pointer
;halt the CPU
Kernel
64 / 94
section .bss
resb 8192
stack_space:
Emulation
en ~/tutoriales/bare_metal/kernel-101
mkdir -p isodir/boot
cp kernel-101 isodir/boot/kernel-101
mkdir -p isodir/boot/grub
cp grub.cfg isodir/boot/grub/grub.cfg
grub-mkrescue -o kernel-101.iso isodir
Kernel
65 / 94
Resultado
candido@lur:~/tutoriales/bare_metal/kernel-101$ ls
grub.cfg isodir kasm.o kc.o kernel-101 kernel-101.iso
kernel.asm
kernel.c
link.ld
Bootloader on disk
36.2.
Kernel 201
36.2.1.
info
FUNCIONA
http://arjunsreedharan.org/post/99370248137/kernel-201-lets-write-a-kernel-with-keyboard
Extension of the Kernel 101
Today, we will extend that kernel to include keyboard driver that can read the characters a-z and 0-9 from the keyboard
and print them on screen.
tools
https://github.com/arjun024/mkeykernel
36.2.2.
source
README.md
Kernel
66 / 94
36.2.3.
Build
Readme
nasm -f elf32 kernel.asm -o kasm.o
gcc -m32 -c kernel.c -o kc.o
ld -m elf_i386 -T link.ld -o kernel kasm.o kc.o
qemu-system-i386 -kernel kernel
FUNCIONA
37.
http://wiki.osdev.org/Tutorials
http://wiki.osdev.org/Bare_Bones 32 bits FUNCIONA
http://wiki.osdev.org/Creating_a_64-bit_kernel
http://wiki.osdev.org/Real_mode_assembly_bare_bones
http://wiki.osdev.org/How_Do_I_Use_A_Debugger_With_My_OS debug kernel
38.
http://wiki.osdev.org/Creating_a_64-bit_kernel
Sin hacer
39.
39.1.
Boot y kernel
FUNCIONA
http://wiki.osdev.org/Bare_Bones
Ver GCC Cross Compiler Apuntes
el sistema MyOS ha de ser para una cpu de 32 bits por lo que el target platform del cross compiler ser i686-elf donde el
i686 no puede ser x86_64 y s x86.
an operating system for x86
boot.s - kernel entry point that sets up the processor environment
kernel.c - your actual kernel routines
linker.ld - for linking the above files
booting de operating system
export PATH="$HOME/software/cross_i686-elf/bin:$PATH" acceso al cross compiler
cd ~/tutoriales/bare_metal/os_dev
copiamos boot.s
Kernel
67 / 94
.section .multiboot
.align 4
.long MAGIC
.long FLAGS
.long CHECKSUM
#
#
#
#
Currently the stack pointer register (esp) points at anything and using it may
cause massive harm. Instead, well provide our own stack. We will allocate
room for a small temporary stack by creating a symbol at the bottom of it,
then allocating 16384 bytes for it, and finally creating a symbol at the top.
By now, you are perhaps tired of assembly language. You realize some
things simply cannot be done in C, such as making the multiboot header in
the right section and setting up the stack. However, you would like to
write the operating system in a higher level language, such as C or C++.
To that end, the next task is preparing the processor for execution of
such code. C doesnt expect much at this point and we only need to set up
a stack. Note that the processor is not fully initialized yet and stuff
such as floating point instructions are not available yet.
# To set up a stack, we simply set the esp register to point to the top of
# our stack (as it grows downwards).
movl $stack_top, %esp
Kernel
68 / 94
In case the function returns, well want to put the computer into an
infinite loop. To do that, we use the clear interrupt (cli) instruction
to disable interrupts, the halt instruction (hlt) to stop the CPU until
the next interrupt arrives, and jumping to the halt instruction if it ever
continues execution, just to be safe. We will create a local label rather
than real symbol and jump to there endlessly.
cli
hlt
.Lhang:
jmp .Lhang
# Set the size of the _start symbol to the current location . minus its start.
# This is useful when debugging or when you implement call tracing.
.size _start, . - _start
Kernel
69 / 94
COLOR_WHITE = 15,
};
uint8_t make_color(enum vga_color fg, enum vga_color bg) {
return fg | bg << 4;
}
uint16_t make_vgaentry(char c, uint8_t color) {
uint16_t c16 = c;
uint16_t color16 = color;
return c16 | color16 << 8;
}
size_t strlen(const char* str) {
size_t ret = 0;
while ( str[ret] != 0 )
ret++;
return ret;
}
static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 25;
size_t terminal_row;
size_t terminal_column;
uint8_t terminal_color;
uint16_t* terminal_buffer;
void terminal_initialize() {
terminal_row = 0;
terminal_column = 0;
terminal_color = make_color(COLOR_LIGHT_GREY, COLOR_BLACK);
terminal_buffer = (uint16_t*) 0xB8000;
for (size_t y = 0; y < VGA_HEIGHT; y++) {
for (size_t x = 0; x < VGA_WIDTH; x++) {
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry( , terminal_color);
}
}
}
void terminal_setcolor(uint8_t color) {
terminal_color = color;
}
void terminal_putentryat(char c, uint8_t color, size_t x, size_t y) {
const size_t index = y * VGA_WIDTH + x;
terminal_buffer[index] = make_vgaentry(c, color);
}
void terminal_putchar(char c) {
terminal_putentryat(c, terminal_color, terminal_column, terminal_row);
if (++terminal_column == VGA_WIDTH) {
terminal_column = 0;
if (++terminal_row == VGA_HEIGHT) {
terminal_row = 0;
}
}
}
void terminal_writestring(const char* data) {
size_t datalen = strlen(data);
Kernel
70 / 94
Kernel
71 / 94
/* The compiler may produce other sections, by default it will put them in
a segment with the same name. Simply add stuff here as needed. */
}
39.2.
myos.bin
https://searchcode.com/codesearch/view/76193342/
Puede que sea un error del propio programa QEMU; habr que compilarlo desde los fuentes con sumo cuidado de la
configuracion
solucion: reeditar el script del linker: linker.ld
/*el script oficial da error al ejecutar el kernel directamente: qemu-system-i386 - kernel myos.bin
la solucin est en editar el alineamiento de las secciones BLOCK(4K) : ALIGN(4K)
REEDITO BLOCK(2K) : ALIGN(2K) en lugar de BLOCK(4K) : ALIGN(4K)
*/
/* output format i386*/
OUTPUT_FORMAT(elf32-i386)
/* The bootloader will look at this image and start execution at the symbol
designated as the entry point. */
ENTRY(_start)
/* Tell where the various sections of the object files will be put in the final
kernel image. */
SECTIONS
{
/* Begin putting sections at 1 MiB, a conventional place for kernels to be
loaded at by the bootloader. */
. = 1M;
Kernel
72 / 94
.bss
{
BLOCK(2K) : ALIGN(2K)
*(COMMON)
*(.bss)
*(.bootstrap_stack)
/* The compiler may produce other sections, by default it will put them in
a segment with the same name. Simply add stuff here as needed. */
}
FUNCIONA: el problema deber ser el tamao de los bloques. 4K es una pgina. No s el por qu de esta limitacin
Kernel
73 / 94
39.3.
39.4.
Kernel Debug
http://www.linux-magazine.com/Online/Features/Qemu-and-the-Kernel
http://wiki.osdev.org/Kernel_Debugging: sigo el tutorial
Apuntes GDB Server
Compilacion con la opcin -g
cd ~/tutoriales/bare_metal/os_dev_debug
export PATH="$HOME/software/cross_i686-elf/bin:$PATH"
i686-elf-gcc -g -c kernel.c -o kernel.o -std=gnu99 -ffreestanding -O2 -Wall -Wextra
i686-elf-as -gstabs boot.s -o boot.o
boot.s
grub.cfg
isodir
kernel.c
kernel.o
linker.ld
myos.bin
myos.iso
Kernel
74 / 94
(gdb)s
(gdb)s
Breakpoint 2, kernel_main () at kernel.c:103
(gdb)s
Se ejecuta paso a paso hasta el final FUNCIONA
40.
40.1.
Introduccin
Kernel
75 / 94
40.2.
cc -static -o hello0 hello0.c: esttico para tener los smbolos de las llamada al sistema write
ktrace y kdump son propios del sistema operativo FreeBSD
Hello, World in FreeBSD/amd64 (interacciona con el kernel) Assembler: GNU ASM (GAS)
// hello_amd64.S -- hello world in GNU ASM (GAS). FreeBSD/amd64 version.
// Some constants
.equiv STDOUT, 1
.equiv RETVAL, 0
.equiv SYS_WRITE, 4
.equiv SYS_EXIT, 1
/*
/*
/*
/*
write(STDOUT,msg,len);
$len, %edx
$msg, %rsi
$STDOUT, %edi
Kernel
76 / 94
movq
$SYS_WRITE, %rax
movq
%rcx, %r10
syscall
bye:
// Call exit(0);
movl
$RETVAL, %edi
movq
$SYS_EXIT, %rax
movq
%rcx, %r10
syscall
Compilacion
% as --64 -o hello_amd64.o hello_amd64.S
% ld -o hello_amd64 hello_amd64.o
40.3.
40.3.1.
Introduccin
carpeta tutorial
~/tutoriales/bare_metal/farid
40.3.3.
fundamentals
http://farid.hajji.name/blog/2010/05/25/hello-world-on-the-bare-metal/
In the beginning, Man created Hardware and Firmware.
Firmware laid lurking in a Flash/ROM chip
CPU initialized itself to Real Mode, by setting its registers to well-defined values
CPU jumped to the address 0xFFFF:FFF0, which was the entry point of the Firmware. And the BIOS awoke and took
over from there, initializing the rest of the Hardware.
BIOS looked at its list of boot devices: started loading the first 512-bytes sector of the first boot device into the
RAM at address 0x0000:7C00.
having verified that the sector it loaded into RAM was valid and magic (last word of that sector contained the magic bytes
0x55 and 0xAA) the BIOS made the CPU jump (with joy) to this initial address 0xFFFF:FFF0
Kernel
77 / 94
40.3.4.
Source Code
Makefile, which contains the instructions how to build and execute our program;
make
as -o hello.o hello.S
ld -N -e start -Ttext 0x7c00 --oformat binary -o hello hello.o
biosfunc.S, which will serve as an include file and which will contain multiple convenience functions used by the main
program;
define las funciones clrscr,curshome(), puts(), putc()
/* biosfunc.S -- real-mode BIOS and convenience functions. */
.file
.code16
"biosfunc.S"
/*
* The following convenience functions are only available
* in real mode through BIOS:
*
# clear display
* void clrscr()
# move cursor home (0:0)
* void curshome()
void
puts(
%si)
# display string
*
# display char
* void putc( %al)
*
* use this libary like this:
.include biosfunc.S
*
*/
/* clrscr() -- clear dislay */
clrscr:
/*
* clrscr() clears the video buffer, using a special case in
* the BIOS function "SCROLL UP WINDOW". Note that this
* function is only available in real mode, and that some
* buggy BIOSes destroy the base pointer %bp, so we better
* temporarily save it on the stack.
*/
pushw %bp
# BIOS call below *can* destroy %BP
movb
movb
movb
movw
movw
int
$0x06,
$0x0,
$0x7,
$0x0,
$0x184f,
$0x10
popw
retw
%bp
%ah
%al
%bh
%cx
%dx
#
#
#
#
#
#
Kernel
78 / 94
movw $0x0,
int $0x10
retw
%dx
hello.S, which contains the assembly code for the main program.
/* hello.S -- Hello, World on bare metal, just after BIOS boot. x86 */
.file "hello.S"
/*
* A couple of constants.
*
* These cant be changed, because they are set by the
* firmware (BIOS).
*/
.set LOAD,
0x7c00
# BIOS loads and jumps here
.set MAGIC,
0xaa55
# Must be at the end of the 512-byte block
.set BLOCKSIZE, 512
# Boot block is BLOCKSIZE bytes long
/*
* The .text section contains the opcodes (code) for our
* program.
*/
.section .text
# This is a code (text) section.
.code16
# Boot code runs in 16-bit real mode
.globl start
# Entry point is public, for the linker.
start:
/*
* The processor starts in real mode and executes the first
* instruction at address $0xFFFF:FFF0. System designers
* usually map BIOS at this address, so the CPU starts running
Kernel
79 / 94
Kernel
80 / 94
40.3.5.
Compilation
Makefile
# Makefile for baremetal utilities
PROGS
= hello
INCLIBS
= biosfunc.S
RUNTARGET = boot0
all:
$(PROGS) $(INCLIBS)
@echo $(PROGS) built.
@echo now mv SOMEPROG $(RUNTARGET)
@echo then make run, make xrun or make disassemble...
hello: hello.o
ld -N -e start -Ttext 0x7c00 --oformat binary -o hello hello.o
hello.o: hello.S $(INCLIBS)
as -o hello.o hello.S
disassemble: $(RUNTARGET)
objdump --disassemble-all --target=binary --architecture=i8086 $(RUNTARGET)
run: $(RUNTARGET)
@echo qemu will start shortly. Kill it from another console...
qemu -hda ./$(RUNTARGET) -curses
echo back from qemu
xrun: $(RUNTARGET)
qemu -hda ./$(RUNTARGET)
clean:
rm -f *.o a.out $(PROGS) $(RUNTARGET) *~
cp hello boot0 el fichero boot0 es el mdulo ejecutable que utilizan las utilidades:
Kernel
81 / 94
make xrun
make run
make disassemble
40.3.6.
Execution
1. We could copy those 512 bytes to an USB key, to a diskette etc. . . (with something like dd if=hello of=/dev/floppy bs=512
count=1), and boot real hardware.
dd if=hello of=/dev/floppy bs=512 count=1 en dev/floppy debiera estar montado el USB?
2. We could install an 8086 or 80386+ emulator like qemu or VirtualBox on the host machine, and run hello in the emulator.
Emulation
X terminal: qemu-system-x86_64 -hda ./hello o make xrun con boot0
Text console: ctrl-alt-F1 qemu-system-x86_64 -hda ./hello -curses o make run con boot0
para matar el proceso: ctrl-alt-f7 ps aux kill -s KILL pid del proceso qemu-system-x86_64
-hda ./hello -curses
killall -9 qemu-system-x86_64 from another (virtual) console
40.3.7.
Desensamblaje
xor
mov
mov
mov
mov
call
call
call
hlt
%ax, %ax
%ax, %es
%ax, %ds
%ax, %ss
$0x7c00, %sp
1c <clrscr>
2d <curshome>
15 <greeting>
0000000000000015 <greeting>:
15:
be 00 00
18:
e8 1c 00
1b:
c3
mov
call
ret
$0x0, %si
37 <puts>
000000000000001c <clrscr>:
1c:
55
1d:
b4 06
1f:
b0 00
21:
b7 07
23:
b9 00 00
26:
ba 4f 18
29:
cd 10
2b:
5d
2c:
c3
push
mov
mov
mov
mov
mov
int
pop
ret
%bp
$0x6, %ah
$0x0, %al
$0x7, %bh
$0x0, %cx
$0x184f, %dx
$0x10
%bp
000000000000002d <curshome>:
2d:
b4 02
mov
$0x2, %ah
Kernel
82 / 94
2f:
b7 00
31:
ba 00 00
34:
cd 10
36:
c3
000000000000002d <curshome>:
2d:
b4 02
2f:
b7 00
31:
ba 00 00
34:
cd 10
36:
c3
mov
mov
int
ret
$0x0, %bh
$0x0, %dx
$0x10
mov
mov
mov
int
ret
$0x2, %ah
$0x0, %bh
$0x0, %dx
$0x10
0000000000000037 <puts>:
37:
ac
38:
3c 00
3a:
74 05
3c:
e8 03 00
3f:
eb f6
lods
cmp
je
call
jmp
0000000000000041 <puts1>:
41:
c3
ret
0000000000000042 <putc>:
42:
bb 07 00
45:
b4 0e
47:
cd 10
49:
c3
mov
mov
int
ret
$0x7, %bx
$0xe, %ah
$0x10
dec
gs
insb
insb
outsw
sub
push
outsw
jb
and
or
%ax
( %dx), %es:( %di)
( %dx), %es:( %di)
%ds:( %si),( %dx)
$0x20, %al
%di
%ds:( %si),( %dx)
c1 <msg+0x77>
%cx, %fs:( %di)
( %bx, %si), %al
push
stos
%bp
%al, %es:( %di)
000000000000004a <msg>:
4a:
48
4b:
65
4c:
6c
4d:
6c
4e:
6f
4f:
2c 20
51:
57
52:
6f
53:
72 6c
55:
64 21 0d
58:
0a 00
...
1fe:
55
1ff:
aa
xor
mov
mov
mov
mov
call
call
call
hlt
mov
%ax, %ax
%ax, %es
%ax, %ds
%ax, %ss
$0x7c00, %sp
0x1c
0x2d
0x15
$0x7c4a, %si
Kernel
83 / 94
18:
1b:
1c:
1d:
1f:
21:
23:
26:
29:
2b:
2c:
2d:
2f:
31:
34:
36:
37:
38:
3a:
3c:
3f:
41:
42:
45:
47:
49:
4a:
4b:
4c:
4d:
4e:
4f:
51:
52:
53:
55:
58:
1fe:
1ff:
41.
e8 1c
c3
55
b4 06
b0 00
b7 07
b9 00
ba 4f
cd 10
5d
c3
b4 02
b7 00
ba 00
cd 10
c3
ac
3c 00
74 05
e8 03
eb f6
c3
bb 07
b4 0e
cd 10
c3
48
65
6c
6c
6f
2c 20
57
6f
72 6c
64 21
0a 00
...
55
aa
00
00
18
00
00
00
0d
call
ret
push
mov
mov
mov
mov
mov
int
pop
ret
mov
mov
mov
int
ret
lods
cmp
je
call
jmp
ret
mov
mov
int
ret
dec
gs
insb
insb
outsw
sub
push
outsw
jb
and
or
push
stos
%bp
%al, %es:( %di)
%bp
$0x6, %ah
$0x0, %al
$0x7, %bh
$0x0, %cx
$0x184f, %dx
$0x10
%bp
-------> BIOS
$0x2, %ah
$0x0, %bh
$0x0, %dx
$0x10
%ds:( %si), %al
$0x0, %al
0x41
0x42
0x37
-------> SEGMENTACION
$0x7, %bx
$0xe, %ah
$0x10
%ax
Hello World
rectangle asm in C
42.
0x37
Kernel
84 / 94
43.
43.1.
Tutorial
:~/tutoriales/kernel/brokenthorn_baremetal$
43.1.1.
Problemas
43.2.
Referencia
http://www.brokenthorn.com/Resources/OSDevIndex.html
43.3.
Preface
El Objetivo es ensear los conceptos de la Arquitectura de una Computadora PC de un modo prctico: disear un sistema
BareMetal de 32 bits programando un kernel casero con los lenguajes ensamblador y C. En la narrativa habla del sistema
operativo casero Neptune que se puede pedir mandando un email.
Lenguajes de programacin
ensamblador de intel 32 bits con NASM assembler
C: I will be using Microsoft Visual C++ for developing the system. However, it is also possible to develop in other compilers
such as DJGPP, GCC
In the series, we will be creating a 32 bit operating system. Because of this, we will be using a 32 bit C compiler.
CPU
x86
ISA 32 bits
43.3.1.
BIOS BootLoader (flat binary program): bios carga el bootloader que est localizado en el boot sector.
El compilador de C no soporta como salida un flat binary y por ello es necesario el lenguaje ensamblador.
El bootloader est dividido en stages y el stage1 se llame Boot Code que estar en lenguaje asm.
Se puede utilizar C para el bootloader
Opcin 1: el stage1 est en asm y carga un fichero donde estn enlazados dos mdulos objeto: un mdulo stub en asm y el
otro mdulo en C.
43.3.2.
kernel
Esta escrito en C
Kernel
85 / 94
43.3.3.
Direcciones que pueden ser utilizadas, excluyendo las no permitidas. El espacio es diferente para las aplicaciones o para el
kernel. Por ejemplo la direccin 0 es la primera entrada de la tabla de vectores de interrupcin (IVT), que est excluida del
espacio de direcciones para las aplicaciones. Si una aplicacin intenta acceder a la direccin cero el compilador lo indicar
diciendo que se intenta violar un segmento.
En el caso del kernel puede haber direcciones del physical address space que no existan en memoria. Se puede leer o escribir
de ests direcciones sin memoria pero su resultado ser imprevisto.
43.3.4.
43.3.5.
Inline Assembly
43.3.6.
C standard library
Como la librera standard utiliza llamadas al sistema, estas rutinas no son vlidas para la programacin de sistemas.
Ser necesario programar una librera propia.
43.3.7.
El compilador inserta en el cdigo ejecutable llamadas a rutinas que tienen en cuenta el Entorno del Sistema, por ejemplo
servicios de interrupcin, depuracin, operaciones complejas que no puede realizar la propia CPU, etc . . . Esta rutinas forman
parte de la RTL.
Ser necesario implementar una RTL propia.
43.3.8.
Debugging
The series uses (and explains) how to use the Bochs Debugger, which is a debugger that comes with the Bochs emulator.
43.4.
Introduction
43.4.1.
Resources
43.5.
There are a lot of tools listed above. To better understand how they can be useful, we should take a look at the entire build process
of the OS.
Setting everything up
Use VFD to create and format a virtual floppy image to use.
Set up Bochs Emulator to boot from the floppy image.
The bootloader
Assemble the bootloader with NASM to create a flat binary program. : nasm -f bin boot2.
Use PartCopy or the DEBUG command to copy the bootloader to the bootsector of the virtu
The Kernel (And basically all other programs)
Assembly and/or compile all sources into an object format (Such as ELF or PE) that can
Copy kernel into floppy disk using Windows Explorer.
Test it!
Using Bochs emulator and debugger, using a real floppy disk, or by using MagicISO to cr
Kernel
86 / 94
43.5.1.
VFD es de Windows
43.5.2.
file floppy.img - floppy.img: DOS floppy 1440k, x86 hard disk boot sector
vuelco el contenido binario del floppy con emacs hexl-mode
00000000: eb3c 906d 6b64 6f73 6673 0000 0201 0100 .<.mkdosfs......
00000010: 02e0 0040 0bf0 0900 1200 0200 0000 0000 ...@............
00000020: 0000 0000 0000 29e3 5ad0 8263 616e 6469 ......).Z..candi
00000030: 646f 2020 2020 4641 5431 3220 2020 0e1f do
FAT12
..
00000040: be5b 7cac 22c0 740b 56b4 0ebb 0700 cd10 .[|.".t.V.......
00000050: 5eeb f032 e4cd 16cd 19eb fe54 6869 7320 ^..2.......This
00000060: 6973 206e 6f74 2061 2062 6f6f 7461 626c is not a bootabl
00000070: 6520 6469 736b 2e20 2050 6c65 6173 6520 e disk. Please
00000080: 696e 7365 7274 2061 2062 6f6f 7461 626c insert a bootabl
00000090: 6520 666c 6f70 7079 2061 6e64 0d0a 7072 e floppy and..pr
000000a0: 6573 7320 616e 7920 6b65 7920 746f 2074 ess any key to t
000000b0: 7279 2061 6761 696e 202e 2e2e 200d 0a00 ry again ... ...
000000c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................
Observo que es NOT bootable DISK
sudo mount -o loop,uid=$UID -t vfat floppy.img /mnt/floppy
Tengo montado el floppy en /dev/loop0, compruebo que el proximo loop es loop1 con losetup -f
Formatos FAT
http://technet.microsoft.com/en-us/library/cc750354.aspx: vfat es una extensin de fat
http://bochs.sourceforge.net/doc/docbook/user/loop-device-usage.html
Using Floppy images is easy, because there is no partition table:
losetup /dev/loop0 /usr/local/bochs/dlxlinux/floppya.img
pseudodispositivo
Kernel
87 / 94
43.5.3.
NASM
; Boot Signiture
the first sector of the boot disk (the bootloader) is loaded at address 0x07c0:0000 (0x7c00 in real addressing mode) and control
jumps to that address.
Bootloader binary flat: nasm -f bin boot1.asm -o boot1.bin
43.5.4.
The bootloader is a pure binary program that is stored in a single 512 byte sector
PartCopy - Low Level Disk Copier: formato exe para windows
Windows debugger : se puede utilizar para realizar la copia en un sector determinado.
dd if=boot1.bin of=/dev/loop0 : para ello tengo que tener creada la imagen del floppy, montarla y asociarla a un
pseudodispositivo
43.5.5.
Kernel
88 / 94
43.5.6.
Bochs Emulator
OSDev.log
action=report
action=report
bochs -f bochs.conf -q
error ya que no sale ningn mensaje en la pantalla.
43.5.7.
Error
Da el mismo resultado que si no conecto el floppy donde est el cdigo del bootloader, por lo que hay que investigar porque la bios no carga el bootloader almacenado en el diskette. Investigamos la configuracin floppya: 1_44=/dev/loop0:, status=inserted # Boot from drive A del fichero bochsrc:
Est conectado el floppy virtual a la mquina virtual o lo hemos dejado conectado al host? 1_44=/dev/loop0 especifica que
estar conectado al host. En el original de windows la configuracin es 1_44=a donde a NO ES UN dispositivo real ya que
en el original mediante la herramienta VFD se ha creado el floppy virtual a.
Al final descubro que es un problema del video ya que unas veces salen los mensajes de la bios y otros no
43.5.8.
boot2.asm
http://www.ntfs.com/fat-partition-sector.htm
http://www.win.tue.nl/~aeb/linux/lk/lk-7.html
The first sector (512 bytes) of a FAT filesystem is the boot sector. In Unix-like terminology this would be called the superblock. It contains some general information.
FAT12 BPB:
Kernel
89 / 94
FAT16 BPB:
FAT16
Bytes
0-2
24-25
26-27
Content
Jump to bootstrap (E.g. eb 3c 90; on i86: JMP 003E NOP.
One finds either eb xx 90, or e9 xx xx.
The position of the bootstrap varies.)
OEM name/version (E.g. "IBM 3.3", "MSDOS5.0", "MSWIN4.0".
Various format utilities leave their own name, like "CH-FOR18".
Sometimes just garbage. Microsoft recommends "MSWIN4.1".)
/* BIOS Parameter Block starts here */
Number of bytes per sector (512)
Must be one of 512, 1024, 2048, 4096.
Number of sectors per cluster (1)
Must be one of 1, 2, 4, 8, 16, 32, 64, 128.
A cluster should have at most 32768 bytes. In rare cases 65536 is OK.
Number of reserved sectors (1)
FAT12 and FAT16 use 1. FAT32 uses 32.
Number of FAT copies (2)
Number of root directory entries (224)
0 for FAT32. 512 is recommended for FAT16.
Total number of sectors in the filesystem (2880)
(in case the partition is not FAT32 and smaller than 32 MB)
Media descriptor type (f0: 1.4 MB floppy, f8: hard disk; see below)
Number of sectors per FAT (9)
0 for FAT32.
Number of sectors per track (12)
Number of heads (2, for a double-sided diskette)
11-27
28-31
32-35
0xb-0xfb
fc-1f
20-23
36
37
24
25
38
26
39-42
43-53
54-61
62-509
510-511
27-2a
2b-35
36-3d
3e-1fd
1fe-1ff
3-10
11-12
13
14-15
16
17-18
19-20
21
22-23
(as before)
Number of hidden sectors (0)
Total number of sectors in the filesystem
(in case the total was not given in bytes 19-20)
Logical Drive Number (for use with INT 13, e.g. 0 or 0x80)
Reserved (Earlier: Current Head, the track containing the Boot Re
Used by Windows NT: bit 0: need disk check; bit 1: need surface s
Extended signature (0x29)
Indicates that the three following fields are present.
Serial number of partition
Volume label or "NO NAME
"
Filesystem type (E.g. "FAT12
", "FAT16
", "FAT
", or all
Bootstrap
Signature 55 aa
Boot Binario boot1.bin propio creado para el arranque de nuestra sistema emulado.
00000000:
00000010:
00000020:
00000030:
00000040:
00000050:
00000060:
eb68
02e0
0000
4c4f
6c63
6174
c074
0000
0040
0000
5050
6f6d
696e
06b4
0000
0bf0
0000
5920
6520
6720
0ecd
0000
0900
29a3
4641
746f
5379
10eb
0000
1200
a2a1
5431
204d
7374
f5c3
0000
0200
a04d
3220
7920
656d
31c0
0201
0000
4f53
2020
4f70
2100
8ed8
0100
0000
2046
5765
6572
ac08
8ec0
.h..............
...@............
......)....MOS F
LOPPY FAT12
We
lcome to My Oper
ating System!...
.t........1.....
Kernel
90 / 94
.>|..........boo
................
................
..............U.
Leo la BIOS que tengo instalada en mi porttil teniendo en cuenta que el sistema de ficheros es NTFS y el dispositivo de
arranque el disco duro.
sudo dd if=/dev/mem of=bios.bin bs=65536 skip=15 count=1
emacs bios.bin hexl-mode copio los bytes de posiciones 0x00-0x3f
00000000:
00000010:
00000020:
00000030:
4177
4946
00f0
0000
6172
4524
6008
c0b4
6420
9856
18ef
0f00
5669
0200
d9da
9001
7374
0009
0000
0000
6100
0000
0000
60b1
0000
00f0
e000
0f00
0000
aa00
0f00
b001
Award Vista.....
IFE$.V..........
http://technet.microsoft.com/en-us/library/cc977221.aspx: conceptos e info buena para el fat y para el ntfs, bios parameter
BPB
http://en.wikipedia.org/wiki/FAT_BPB#BPB: info buena
http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/bios-parameter-block.html:
Windows NT (a.k.a. version 8.0) BPBs : The NTFS filesystem format on Windows NT
http://www.ntfs.com/ntfs.htm: Ver tambin forensics o sistemas de ficheros. Solo est bien para el fat32
43.6.
44.
http://www.websofia.com/writing-your-own-toy-operating-system/
lo he probado en la carpeta de tutoriales y no me sale porque no tengo bien configurado bochs.
REPETIRLOOOOOOOOOOOOOOOOOOOOO
45.
Princeton BareMetal
46.
Kernel
91 / 94
46.1.
Referencia http://docs.slackware.com/howtos:slackware_admin:building_the_linux_kernel_using_git_repository
dos mtodos: el git y la descarga directa del tarball. Hacemos el git.
git clone --depth 1 git://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git
git pull
git checkout v3.2.59 eligo esa versin porque es la long term que utiliza ubuntu
git log compruebo que es la versin especificada en git checkout
git tag -v v3.2.59 compruebo la firma
gpg: Signature made Sunday 18 May 2014 03:58:11 PM CEST using RSA key ID 95861109
gpg: Cant check signature: public key not found
Importo la firma segn https://www.kernel.org/category/signatures.html
gpg --recv-keys 95861109
git tag -v v3.2.59 gpg: Good signature from "Ben Hutchings (DOB: 1977-01-11)"
46.2.
ls -l /home/candido/git_repos/linux-stable/arch
x86, x86_64, arm, mips, etc
ls -l /home/candido/git_repos/linux-stable/arch/mips/kernel
ls -l /home/candido/git_repos/linux-stable/arch/boot/kernel
46.3.
preBuild
make clean
make mrproper elimina .config y otros restos.
46.4.
referencia: http://oreilly.com/linux/excerpts/9780596100797/kernel-build-command-line-reference.html
Linux Kernel Build System
config symbols
opciones de compilacin para decidir cuales sern los objetos empotrados en el ncleo y cuales sern los mdulos generados.
Kconfig files
Definen los config smbolos y sus atributos. Este fichero servir al menuconfig para definir las entradas de los mens
despegables
.config file
Es el fichero de salida que contiene los valores de los parmetros definidos en Kconfig. Este fichero puede generarse
automaticamente con menuconfig, oldconfig, etc
Makefile
relacin entre los fuentes para generar la imagen del ncleo y sus mdulos.
Kernel
92 / 94
46.5.
Configuration
Referencias
README
Documentation/kbuild/kconfig.txt
Copio una configuracin que ya tengo: cp /boot/config-3.2.0-59-generic .config aunque no es la del kernel
del host ls -l /boot/config-uname -r
make oldconfig
candido@lur:~/git_repos/linux-stable$ make oldconfig
HOSTCC scripts/basic/fixdep
HOSTCC scripts/kconfig/conf.o
SHIPPED scripts/kconfig/zconf.tab.c
SHIPPED scripts/kconfig/zconf.lex.c
SHIPPED scripts/kconfig/zconf.hash.c
HOSTCC scripts/kconfig/zconf.tab.o
HOSTLD scripts/kconfig/conf
scripts/kconfig/conf --oldconfig Kconfig
.config:1021:warning: symbol value m invalid for NET_DSA
.config:2029:warning: symbol value m invalid for NET_DSA_MV88E6XXX
.config:2030:warning: symbol value m invalid for NET_DSA_MV88E6060
.config:2032:warning: symbol value m invalid for NET_DSA_MV88E6131
.config:2033:warning: symbol value m invalid for NET_DSA_MV88E6123_61_65
.config:4128:warning: symbol value m invalid for FB_VESA
*
* Restart config...
*
*
* Distributed Switch Architecture support
*
Distributed Switch Architecture support (NET_DSA) [N/y/?] (NEW) N
Support for frame buffer devices (FB) [Y/m/?] y
Quanta Optical Touch panels (HID_QUANTA) [N/m/?] (NEW) y
Quanta Optical Touch panels (HID_QUANTA) [N/m/?] (NEW) N
46.6.
make -j 4 - utilizo la opcin --jobs y el nmero de ncleos de mi cpu Tarda ms de 30 minutos en generar el Makefile
y compilar los fuentes.
make modules
WARNING: modpost: Found 4 section mismatch(es)
To see full details build your kernel with:
make CONFIG_DEBUG_SECTION_MISMATCH=y
Kernel
93 / 94
46.7.
$ ls -lh vmlinux : -rwxrwxr-x 1 candido candido 142M May 24 10:33 vmlinux 142MB
$ readelf -h vmlinux
ELF Header:
Magic:
7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class:
ELF64
Data:
2s complement, little endian
Version:
1 (current)
OS/ABI:
UNIX - System V
ABI Version:
0
Type:
EXEC (Executable file)
Machine:
Advanced Micro Devices X86-64
Version:
0x1
Entry point address:
0x1000000
Start of program headers:
64 (bytes into file)
Start of section headers:
144824872 (bytes into file)
Flags:
0x0
Size of this header:
64 (bytes)
Size of program headers:
56 (bytes)
Number of program headers:
5
Size of section headers:
64 (bytes)
Number of section headers:
47
Section header string table index: 44
imagen comprimida
$ ls -l /home/candido/git_repos/linux-stable/arch/x86/boot/bzImage
-rw-rw-r-- 1 candido candido 4905968 May 24 10:33 /home/candido/git_repos/linux-stable/ arch/x86/boot/bzImage
mdulos ko
find . -name *.ko
CONTINUAR CON
http://en.wikipedia.org/wiki/Vmlinux. ver links initrd,etc
http://oss.sgi.com/LDP/HOWTO/Kernel-HOWTO/index.html
http://oss.sgi.com/LDP/HOWTO/Kernel-HOWTO/kernel_files_info.html
libro oreilly nutshell, captulo 5
manuales oficiales https://www.kernel.org/doc/Documentation/
howto
https://www.kernel.org/doc/Documentation/kbuild/modules.txt
hay que ejecutar sudo make modules y sudo make modules_install?
http://www.linux.org/threads/the-linux-kernel-compiling-and-installing.5208/
http://sopa.dis.ulpgc.es/ii-aso/portal_aso/practicas/compilar.htm
46.8.
make
make
make
make
make
Resumen de comandos
mrproper
menuconfig
dep
clean
bzImage
Kernel
94 / 94
make modules
make modules_install
cp arch/i386/boot/bzImage /boot/vmlinuz-2.4.19
cp System.map /boot
46.9.
http://wiki.eclipse.org/HowTo_use_the_CDT_to_navigate_Linux_kernel_source
46.10.
http://wiki.eclipse.org/HowTo_use_the_CDT_to_navigate_Linux_kernel_source
http://www.yonch.com/tech/84-debugging-the-linux-kernel-with-qemu-and-eclipse
http://www.opensourceforu.com/2011/02/kernel-development-debugging-using-eclipse/
http://issaris.blogspot.com.es/2007/12/download-linux-kernel-sourcecode-from.html
47.
Glosario
Glosario