Nous sommes le 20/05/2013
Votre adresse IP est : 50.16.17.90
Catégorie : Embarqué
Liste des news
Inside the Linux boot process 02/01/2008 15:23:40
The process of booting a Linux® system consists of a number of stages. But whether you're booting a standard x86 desktop or a deeply embedded PowerPC® target, much of the flow is surprisingly similar. This article explores the Linux boot process from the initial bootstrap to the start of the first user-space application. Along the way, you'll learn about various other boot-related topics such as the boot loaders, kernel decompression, the initial RAM disk, and other elements of Linux boot.

In the early days, bootstrapping a computer meant feeding a paper tape containing a boot program or manually loading a boot program using the front panel address/data/control switches. Today's computers are equipped with facilities to simplify the boot process, but that doesn't necessarily make it simple.

Let's start with a high-level view of Linux boot so you can see the entire landscape. Then we'll review what's going on at each of the individual steps. Source references along the way will help you navigate the kernel tree and dig in further.

Overview

Figure 1 gives you the 20,000-foot view.


Figure 1. The 20,000-foot view of the Linux boot process
High-level view of the Linux kernel boot

When a system is first booted, or is reset, the processor executes code at a well-known location. In a personal computer (PC), this location is in the basic input/output system (BIOS), which is stored in flash memory on the motherboard. The central processing unit (CPU) in an embedded system invokes the reset vector to start a program at a known address in flash/ROM. In either case, the result is the same. Because PCs offer so much flexibility, the BIOS must determine which devices are candidates for boot. We'll look at this in more detail later.

When a boot device is found, the first-stage boot loader is loaded into RAM and executed. This boot loader is less than 512 bytes in length (a single sector), and its job is to load the second-stage boot loader.

When the second-stage boot loader is in RAM and executing, a splash screen is commonly displayed, and Linux and an optional initial RAM disk (temporary root file system) are loaded into memory. When the images are loaded, the second-stage boot loader passes control to the kernel image and the kernel is decompressed and initialized. At this stage, the second-stage boot loader checks the system hardware, enumerates the attached hardware devices, mounts the root device, and then loads the necessary kernel modules. When complete, the first user-space program (init) starts, and high-level system initialization is performed.

That's Linux boot in a nutshell. Now let's dig in a little further and explore some of the details of the Linux boot process.



Back to top


System startup

The system startup stage depends on the hardware that Linux is being booted on. On an embedded platform, a bootstrap environment is used when the system is powered on, or reset. Examples include U-Boot, RedBoot, and MicroMonitor from Lucent. Embedded platforms are commonly shipped with a boot monitor. These programs reside in special region of flash memory on the target hardware and provide the means to download a Linux kernel image into flash memory and subsequently execute it. In addition to having the ability to store and boot a Linux image, these boot monitors perform some level of system test and hardware initialization. In an embedded target, these boot monitors commonly cover both the first- and second-stage boot loaders.

Extracting the MBR

To see the contents of your MBR, use this command:

# dd if=/dev/hda of=mbr.bin bs=512 count=1
# od -xa mbr.bin

The dd command, which needs to be run from root, reads the first 512 bytes from /dev/hda (the first Integrated Drive Electronics, or IDE drive) and writes them to the mbr.bin file. The od command prints the binary file in hex and ASCII formats.

In a PC, booting Linux begins in the BIOS at address 0xFFFF0. The first step of the BIOS is the power-on self test (POST). The job of the POST is to perform a check of the hardware. The second step of the BIOS is local device enumeration and initialization.

Given the different uses of BIOS functions, the BIOS is made up of two parts: the POST code and runtime services. After the POST is complete, it is flushed from memory, but the BIOS runtime services remain and are available to the target operating system.

To boot an operating system, the BIOS runtime searches for devices that are both active and bootable in the order of preference defined by the complementary metal oxide semiconductor (CMOS) settings. A boot device can be a floppy disk, a CD-ROM, a partition on a hard disk, a device on the network, or even a USB flash memory stick.

Commonly, Linux is booted from a hard disk, where the Master Boot Record (MBR) contains the primary boot loader. The MBR is a 512-byte sector, located in the first sector on the disk (sector 1 of cylinder 0, head 0). After the MBR is loaded into RAM, the BIOS yields control to it.



Back to top


Stage 1 boot loader

The primary boot loader that resides in the MBR is a 512-byte image containing both program code and a small partition table (see Figure 2). The first 446 bytes are the primary boot loader, which contains both executable code and error message text. The next sixty-four bytes are the partition table, which contains a record for each of four partitions (sixteen bytes each). The MBR ends with two bytes that are defined as the magic number (0xAA55). The magic number serves as a validation check of the MBR.


Figure 2. Anatomy of the MBR
Anatomy of the MBR

The job of the primary boot loader is to find and load the secondary boot loader (stage 2). It does this by looking through the partition table for an active partition. When it finds an active partition, it scans the remaining partitions in the table to ensure that they're all inactive. When this is verified, the active partition's boot record is read from the device into RAM and executed.



Back to top


Stage 2 boot loader

The secondary, or second-stage, boot loader could be more aptly called the kernel loader. The task at this stage is to load the Linux kernel and optional initial RAM disk.

GRUB stage boot loaders

The /boot/grub directory contains the stage1, stage1.5, and stage2 boot loaders, as well as a number of alternate loaders (for example, CR-ROMs use the iso9660_stage_1_5).

The first- and second-stage boot loaders combined are called Linux Loader (LILO) or GRand Unified Bootloader (GRUB) in the x86 PC environment. Because LILO has some disadvantages that were corrected in GRUB, let's look into GRUB. (See many additional resources on GRUB, LILO, and related topics in the Resources section later in this article.)

The great thing about GRUB is that it includes knowledge of Linux file systems. Instead of using raw sectors on the disk, as LILO does, GRUB can load a Linux kernel from an ext2 or ext3 file system. It does this by making the two-stage boot loader into a three-stage boot loader. Stage 1 (MBR) boots a stage 1.5 boot loader that understands the particular file system containing the Linux kernel image. Examples include reiserfs_stage1_5 (to load from a Reiser journaling file system) or e2fs_stage1_5 (to load from an ext2 or ext3 file system). When the stage 1.5 boot loader is loaded and running, the stage 2 boot loader can be loaded.

With stage 2 loaded, GRUB can, upon request, display a list of available kernels (defined in /etc/grub.conf, with soft links from /etc/grub/menu.lst and /etc/grub.conf). You can select a kernel and even amend it with additional kernel parameters. Optionally, you can use a command-line shell for greater manual control over the boot process.

With the second-stage boot loader in memory, the file system is consulted, and the default kernel image and initrd image are loaded into memory. With the images ready, the stage 2 boot loader invokes the kernel image.



Back to top


Kernel

Manual boot in GRUB

From the GRUB command-line, you can boot a specific kernel with a named initrd image as follows:

grub> kernel /bzImage-2.6.14.2
[Linux-bzImage, setup=0x1400, size=0x29672e]

grub> initrd /initrd-2.6.14.2.img
[Linux-initrd @ 0x5f13000, 0xcc199 bytes]

grub> boot

Uncompressing Linux... Ok, booting the kernel.

If you don't know the name of the kernel to boot, just type a forward slash (/) and press the Tab key. GRUB will display the list of kernels and initrd images.

With the kernel image in memory and control given from the stage 2 boot loader, the kernel stage begins. The kernel image isn't so much an executable kernel, but a compressed kernel image. Typically this is a zImage (compressed image, less than 512KB) or a bzImage (big compressed image, greater than 512KB), that has been previously compressed with zlib. At the head of this kernel image is a routine that does some minimal amount of hardware setup and then decompresses the kernel contained within the kernel image and places it into high memory. If an initial RAM disk image is present, this routine moves it into memory and notes it for later use. The routine then calls the kernel and the kernel boot begins.

When the bzImage (for an i386 image) is invoked, you begin at ./arch/i386/boot/head.S in the start assembly routine (see Figure 3 for the major flow). This routine does some basic hardware setup and invokes the startup_32 routine in ./arch/i386/boot/compressed/head.S. This routine sets up a basic environment (stack, etc.) and clears the Block Started by Symbol (BSS). The kernel is then decompressed through a call to a C function called decompress_kernel (located in ./arch/i386/boot/compressed/misc.c). When the kernel is decompressed into memory, it is called. This is yet another startup_32 function, but this function is in ./arch/i386/kernel/head.S.

In the new startup_32 function (also called the swapper or process 0), the page tables are initialized and memory paging is enabled. The type of CPU is detected along with any optional floating-point unit (FPU) and stored away for later use. The start_kernel function is then invoked (init/main.c), which takes you to the non-architecture specific Linux kernel. This is, in essence, the main function for the Linux kernel.


Figure 3. Major functions flow for the Linux kernel i386 boot
Major Functions in Linux Kernel i386 Boot Process

With the call to start_kernel, a long list of initialization functions are called to set up interrupts, perform further memory configuration, and load the initial RAM disk. In the end, a call is made to kernel_thread (in arch/i386/kernel/process.c) to start the init function, which is the first user-space process. Finally, the idle task is started and the scheduler can now take control (after the call to cpu_idle). With interrupts enabled, the pre-emptive scheduler periodically takes control to provide multitasking.

During the boot of the kernel, the initial-RAM disk (initrd) that was loaded into memory by the stage 2 boot loader is copied into RAM and mounted. This initrd serves as a temporary root file system in RAM and allows the kernel to fully boot without having to mount any physical disks. Since the necessary modules needed to interface with peripherals can be part of the initrd, the kernel can be very small, but still support a large number of possible hardware configurations. After the kernel is booted, the root file system is pivoted (via pivot_root) where the initrd root file system is unmounted and the real root file system is mounted.

decompress_kernel output

The decompress_kernel function is where you see the usual decompression messages emitted to the display:

Uncompressing Linux... Ok, booting the kernel.

The initrd function allows you to create a small Linux kernel with drivers compiled as loadable modules. These loadable modules give the kernel the means to access disks and the file systems on those disks, as well as drivers for other hardware assets. Because the root file system is a file system on a disk, the initrd function provides a means of bootstrapping to gain access to the disk and mount the real root file system. In an embedded target without a hard disk, the initrd can be the final root file system, or the final root file system can be mounted via the Network File System (NFS).



Back to top


Init

After the kernel is booted and initialized, the kernel starts the first user-space application. This is the first program invoked that is compiled with the standard C library. Prior to this point in the process, no standard C applications have been executed.

In a desktop Linux system, the first application started is commonly /sbin/init. But it need not be. Rarely do embedded systems require the extensive initialization provided by init (as configured through /etc/inittab). In many cases, you can invoke a simple shell script that starts the necessary embedded applications.




Summary

Much like Linux itself, the Linux boot process is highly flexible, supporting a huge number of processors and hardware platforms. In the beginning, the loadlin boot loader provided a simple way to boot Linux without any frills. The LILO boot loader expanded the boot capabilities, but lacked any file system awareness. The latest generation of boot loaders, such as GRUB, permits Linux to boot from a range of file systems (from Minix to Reiser).

Resources

Learn
  • Boot Records Revealed is a great resource on MBRs and the various boot loaders. This resource not only disassembles MBRs, but also discusses GRUB, LILO, and the various Windows® boot loaders.

  • Check out the Disk Geometry page to understand disks and their geometries. You'll find an interesting summary of disk attributes.

  • A live CD is an operating system that's bootable from a CD or DVD without needing a hard drive.

  • "Boot loader showdown: Getting to know LILO and GRUB" (developerWorks, August 2005) gives you a detailed look at the LILO and GRUB boot loaders.

  • In the Linux Professional Institute (LPI) exam prep series of developerWorks tutorials, get a comprehensive introduction to booting a Linux system and many other fundamental Linux tasks while you prepare for system administrator certification.

  • LILO was the precursor to GRUB, but you can still find it booting Linux.

  • The mkintrd command is used to create an initial RAM disk image. This command is useful for building an initial root file system for boot configuration that allows preloading of block devices needed to access the real root file system.

  • At the Debian Linux Kernel Project, find more information on the Linux kernel, boot, and embedded development.

  • In the developerWorks Linux zone, find more resources for Linux developers.

  • Stay current with developerWorks technical events and Webcasts.
Get products and technologies
  • The MicroMonitor provides a boot environment for a variety of small target devices. You can use this monitor to boot Linux in an embedded environment. It has ports for ARM, XScale, MIPS, PowerPC, Coldfire, and Hitachi's Super-H.

  • GNU GRUB is a boot shell filled with options and flexibility.

  • LinuxBIOS is a BIOS replacement. Not only does it boot Linux, LinuxBIOS, itself, is a compressed Linux kernel.

  • OpenBIOS is another portable BIOS project that operates on a variety of architectures such as x86, Alpha, and AMD64.

  • At kernel.org, grab the latest kernel tree.

  • Order the SEK for Linux, a two-DVD set containing the latest IBM trial software for Linux from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.

  • With IBM trial software, available for download directly from developerWorks, build your next development project on Linux.
Discuss
mramfs 22/12/2007 18:57:09
File systems using non-volatile RAM (NVRAM) promise great improvements in file system performance over conventional disk storage. However, current technology allows for a relatively small amount of NVRAM, limiting the effectiveness of such an approach. We have developed a prototype in-memory file system which utilizes data compression on inodes, and which has preliminary support for compression of file blocks. Our file system, MRAMFS, is also based on data structures tuned for storage efficiency in non-volatile memory. This prototype allows us to examine how to use this limited resource more efficiently. Simulations show that inodes can be reduced to 15-20 bytes each at a rate of 250,000 or more inodes per second. This is a space savings of 79-85% over conventional 128-byte inodes.

http://ssrc.cse.ucsc.edu/Papers/edel-mascots04.pdf
http://www.usenix.org/events/fast04/wips/edel.pdf
Gumstix 18/12/2007 11:06:17
About Gumstix, Inc.

Founded in 2003, Gumstix develops and sells small form factor computers & related products to commercial product designers, network managers, software engineers & hobbyists in more than 50 countries around the world. The Gumstix product lines support the growing networking and wireless devices markets with a full ranger of motherboards, expansion boards and computers running an open-source platform suitable for rapid product development and scalable
deployment.

http://gumstix.com/
SUSE Linux Enterprise Real Time 10 et Red Hat Enterprise MRG 14/12/2007 10:47:21
Les deux grandes distributions commerciales, Novell et Red Hat, ont récemment annoncé la sortie d'une version dédiée spécialement au temps réel et la compétition s'annonce âpre dans ce secteur stratégique. Novell a ouvert le feu le 27 novembre avec SUSE Linux Enterprise Real Time 10 et Red Hat a immédiatement répliqué le 4 décembre avec Red Hat Enterprise MRG (Messaging, Realtime et Grid Technologies).

Cette volonté de ne pas laisser un concurrent en position de monopole sur ce secteur, même pour une durée infime, s'explique aisément. En effet de plus en plus les entreprises reposent sur l'automatisation poussée de leurs processus afin de gagner en réactivité. On se rappelle, lors du sommet Linux 2007, le témoignage du représentant du Crédit Suisse qui indiquait qu'un noyau patché pour le temps réel aidait à maintenir les profits lors d'une transaction financière.

La prédictibilité des temps de réponse est donc un enjeu crucial et les distributeurs commerciaux de Linux sont en compétition pour couvrir ce marché au point, comme nous allons le voir, de déclencher une véritable guerre des communiqués.

> Lire la dépêche (49 commentaires, moyenne: 3,8).  

Depuis plusieurs années la branche principale du noyau Linux a intégré de nombreux patchs ayant un rapport, proche ou lointain, avec la problématique du temps réel. On peut songer aux mutex, à l'héritage de priorité ou encore la gestion dynamique des tranches de temps. De ce point de vue Linux est donc devenu une solution envisageable pour du temps réel « mou » (donc avec une certaine tolérance pour des latences de traitement).

Pour accéder au vrai temps réel il faut néanmoins intégrer beaucoup plus de patchs au noyau Linux et ces patchs, bien qu'en développement depuis longtemps, n'ont pas encore rejoints la branche principale. Le site LWN avait décrit ces modifications temps réel dans un article d'octobre dernier et avait abouti a un décompte de près de 400 patchs.
On y trouve notamment le remplacement des spinlocks par des mutex temps réel entièrement préemptibles et bénéficiant de l'héritage de priorité. Il existe aussi un patch permettant de gérer les interruptions dans des threads séparés et un autre qui modifie la gestion des pages mémoires pour éliminer les verrous.
Tout ce travail est donc disponible pour ceux qui désirent appliquer ces patchs au noyau traditionnel (c'est ce que fait la branche -rt) et cette série de patchs forme la base de ce qui se trouve dans les deux nouvelles offres de Novell et de Red Hat.

L'aspect technique des noyaux temps réel est toutefois un peu occulté dans les communiqués officiels rédigés par les département marketing au profit de phrases telles que « increase revenue opportunities » ou « grow their own top-line revenues » ou encore « customers gain time advantage over competitors to make more money or avoid financial losses ».
Cette compétition marketing a été particulièrement farouche et un des dirigeants de Red Hat est allé jusqu'à remettre en cause les contributions de Novell dans le domaine du temps réel.
Selon Scott Crenshaw le noyau Novell temps réel n'est pas stable et il ne serait que de la qualité d'une bêta. De plus les patchs RT ont été écrits à 80% par des développeurs Red Hat ce qui remettrait en cause le niveau de compétence de Novell sur ce sujet. Scott Crenshaw a ajouté sarcastiquement
Nous souhaitons la bienvenue à Novell dans la communauté temps réel. Nous espérons qu'elle fera des contributions à l'avenir.

Du coté Novell la réponse a été prompte :
Note à Red Hat: C'est de l'open source vous vous souvenez ? Novell propose un Linux testé est renforcé pour les entreprises avec des capacités temps réel. Ce n'est pas parce que Red Hat est une fois de plus en retard sur le marché (voir le desktop Linux pour les entreprises, la virtualisation avec Xen...etc) que cela signifie que notre noyau contient du code de qualité bêta (...) Ce n'est pas plus du code Red Hat que les millions de lignes de code apportées par Novell (...) C'est ça le modèle Open Source.

LWN s'est penché sur cette controverse et son verdict est assez nuancé : "En fait une bonne partie de ce travail, incluant le travail crucial de bas niveau sur la préemption qui a permis l'avancement du projet temps réel, a été effectué par Red Hat. Mais d'autres composants viennent de compagnies comme MontaVista, Linutronix, TimeSys et, oui, Novell (ainsi que d'autres bien entendu). Pour ces deux compagnies le fait de se disputer au sujet du crédit en tant qu'auteur du code est un peu stupide. Les deux sont des contributeurs significatifs du noyau (et au-delà)".

L'article de LWN indique également qu'au niveau des développeurs il n'y a aucun signe d'animosité et que le travail en commun sur la LKML ou les listes spécialisées se déroule bien. La tension semble se concentrer chez les gestionnaires et des managers des deux firmes qui perçoivent l'importance des enjeux financiers. A titre d'exemple cet article indique que le coût d'une licence Novell SLERT est de 2500 dollars par serveur (en plus des 799 dollars la licence SLES classique). Du coté Red Hat ce sera sans doute comparable.

Dans le monde du logiciel libre il est difficile d'obtenir un avantage comparatif sur ses concurrents puisque ces derniers peuvent réutiliser votre code. La compétition doit donc se déplacer sur d'autres secteurs comme la capacité d'expertise interne ou le service, le support, le développement d'adaptations spécifiques...etc.
Cette nouvelle donne met du temps à être intégrée par les managers traditionnels qui raisonnent encore en terme d'attribution de paternité et de communiqués triomphants. En 2005 on avait déjà assisté à une répétition de la situation d'aujourd'hui (à l'époque c'était Montavista contre Red Hat) et nous devons nous attendre à en voir encore à l'avenir.
Installing Debian onto USB flash media with everything encrypted 10/12/2007 16:30:04

This is a simple procedure for installing Debian GNU/Linux onto a USB key flash media. It includes several configuration changes but tries to stay as close to a default debian install as possible.
http://www.debian-administration.org/articles/179

This is useful for administrators that need to carry sensitive information or people concerned about their privacy.


This was tested on Debian Sid and Knoppix 3.8 with the USB Keys listed below.

Tested Media:

  1. Transcend Jetflash 256MB ( only the base debootstrap install plus a few select packages ).
  2. Apacer Handy Steno HT203 1GB ( very fast, recommended ).

Other reviews of USB Flash media:

  1. ArsTechnica USB 2.0 Hi-Speed Flash Drive Roundup - http://arstechnica.com/reviews/hardware/flash.ars/1
  2. ArsTechnica Son of USB 2.0 Hi-Speed Flash Drive Roundup - http://arstechnica.com/reviews/hardware/flash2005.ars/1

Note on Devices: All device names and mappings are as they were detected and I used them on my system. You will need to substitute the correct device as it is detected on your system.

KNOPPIX NOTE: When you see these notes, there are special steps necessary for installing from Knoppix.


Installation Procedure

1. Shred the drive

shred -n 1 -z -v /dev/sdd
(One pass to shred, one pass to zero)

2. Create Partitions

We will create two partitions on the USB key, one for /boot and one for / (root). We do not create a swap partition because that would prematurely age the usb key. You may mount and use swap partitions from the local harddrives ala knoppix but that is up to you.
parted /dev/sdd "mklabel msdos mkpart primary 0 14 mkpart primary 15 -0"

3. Shred rootfs

shred -n 1 -v /dev/sdd2
(zero'd filesystems are bad for encrypted ones.)

4. Load modules if necessary

modprobe dm-crypt
modprobe aes
KNOPPIX NOTE: We need to install a few packages.
apt-get update
apt-get install cryptsetup dmsetup libdevmapper1.01

5. Created mapped crypt device for root

cryptsetup -y create rootfs /dev/sdd2

6. Format filesystems:

Since we can't use journaling filesystems on flash media (premature aging again), we fall back to good old ext2.
mkfs.ext2 /dev/mapper/rootfs
mkfs.ext2 /dev/sdd1
sync ; sync

7. Apply disk labels

We do this so that we can identify our drive when we boot on various systems. Using a strict device mapping often breaks if other usb or flash devices are detected before ours.You may use any label that you like, but you will have to remember to update the initrd (file: /sbin/init)
e2label /dev/sdd1 PRIVDEB_BOOT

8. Make temporary mount points and mount

mkdir /mnt/buildroot/
mount /dev/mapper/rootfs /mnt/buildroot
mkdir /mnt/buildroot/boot
mount /dev/sdd1 /mnt/buildroot/boot

9. Install base files.

debootstrap --arch i386 sid /mnt/buildroot
Note: Installed size is about 160MB at this stage.
KNOPPIX NOTE: We need to copy a few extra devices over.
cp -ap /dev/ub[a-f]* /mnt/buildroot/dev/

10. Enter chroot jail to work on system.

chroot /mnt/buildroot/ /bin/su -

11. Build fstab and mount everything.

Create /etc/fstab file
#/etc/fstab: static file system information.
#
LABEL=PRIVDEB_BOOT /boot ext2 defaults,noatime 0 2
/dev/mapper/rootfs / ext2 defaults,errors=remount-ro,noatime 0 1
proc /proc proc defaults 0 0
tmpfs /etc/network/run tmpfs defaults,noatime 0 0
tmpfs /tmp tmpfs defaults,noatime 0 0
tmpfs /var/lock tmpfs defaults,noatime 0 0
tmpfs /var/log tmpfs defaults,noatime 0 0
tmpfs /var/run tmpfs defaults,noatime 0 0
tmpfs /var/tmp tmpfs defaults,noatime 0 0
tmpfs /home//Scratch tmpfs defaults,noatime 0 0

#Warning: By mounting /var/log on tmpfs, logs will only be available for the current session.
Mount it all
mount -a

12. Build sources.list

Create /etc/apt/sources.list
deb http://mirrors.kernel.org/debian/ sid main non-free contrib
deb-src http://mirrors.kernel.org/debian/ sid main non-free contrib

deb http://ftp.uk.debian.org/debian-non-US/ sid non-US/main non-US/non-free non-US/contrib
deb-src http://ftp.uk.debian.org/debian-non-US/ sid non-US/main non-US/non-free non-US/contrib

# If you are using debian stable (woody) include the security updates.
# deb http://security.debian.org/ sid/updates main non-free contrib
Note: You can install and use apt-spy to test for the fastest downloading mirrors in your area.

13. System adjustments

blkid.tab: this file is cached as drives are scanned. Since the scan only takes a few seconds, you dont lose much by not caching or setting the default cache to /dev/null. This file generates an error on boot if the cache file has different device mappings than are currently detected. By removing the cache and forcing a fresh scan every time, the error is eliminated.
rm -f /etc/blkid.tab*
ln -s /dev/null /etc/blkid.tab
mtab: This file is written a lot and may prematurely age parts of the flash media and the information can simply be accessed from /proc directly.
rm -f /etc/mtab
ln -s /proc/mounts /etc/mtab
Set Hostname
vi /etc/hostname
Set /etc/hosts with localhost + hostname
vim /etc/hosts
127.0.0.1 localhost.localdoman localhost

14. Install additional required packages

apt-get update
apt-get install cryptsetup dmsetup libdevmapper1.01
apt-get install discover1 libdiscover1
apt-get install module-init-tools equivs cramfsprogs
apt-get clean

15. Install custom mkinitrd script and equiv package

Create mkinitrd.dmcrypt-usb file in /usr/local/sbin
#!/bin/bash

# Filename: mkinitrd.dmcrypt-usb
# Maintainer: Dave Vehrs

# Help
: << HELP_STEXT
Options:
-c Temporary directory to build image in.
-k Keep temporary directory used to build image.
-l Use to indenify boot partition.
-o Write to outfie
-d,-m,-r Included for fake support of default mkinitrd script
(anything passed to them is discarded).

See http://www.saout.de/tikiwiki/tiki-index.php?page=USBFlashMedia for more info.
HELP_STEXT

function display_shelp {
echo; echo "Usage $0 [OPTION]...<-o outfile> [version]"
sed --silent -e '/HELP_STEXT$/,/^HELP_STEXT/p' "$0" | sed -e '/HELP_STEXT/d'
}

# Set defaults
BOOT_LABEL="PRIVDEB_BOOT"
CRAMFSDIR=/tmp/cramfs
keep_temp=0
unset VERSION

# Parse command line.
# if version + other options not specified, exit.
if [ $# -eq 0 ] ; then
display_shelp
exit 1
fi

while [ $# -ge 1 ] ; do
case $1 in
-c ) CRAMFSDIR=$2 ; shift ; shift ;;
-d ) dir_conf=$2 ; shift ; shift ;;
-k ) keep_temp=1 ; shift ;;
-l ) BOOT_LABEL=$2 ; shift ; shift ;;
-m ) cmd_mkinitrd=$2 ; shift ; shift ;;
-o ) outfile_name=$2 ; shift ; shift ;;
-r ) initrd_root=$2 ; shift ; shift ;;
* ) VERSION=$1 ; shift ;;
esac
done

# Exit if version not specified
if [ -z "$VERSION" ] ; then
echo "Error: You need to specify a kernel version to build for."
exit 1
else
VERSION=${VERSION##*/}
fi

# Start build...
echo "Build directory tree."
install -d $CRAMFSDIR/{bin,dev/mapper,etc,proc,mnt,sbin}

echo "Copy binaries from /bin."
# Copy /bin binaries over and any require libraries.
files_bin="bash grep mount umount mkdir mknod sed sleep uname"
for file in $files_bin ; do
install /bin/$file $CRAMFSDIR/bin/$file
for lib in $( ldd /bin/$file | awk '{print $3}' | grep -v fffe000 ) ; do
install -d $CRAMFSDIR/${lib%/*}
install $lib $CRAMFSDIR/$lib
done
done

echo "Copy binaries from /usr/bin."
# Copy /usr/bin binaries over and any require libraries.
files_usrbin="find mawk"
for file in $files_usrbin ; do
install /usr/bin/$file $CRAMFSDIR/bin/$file
for lib in $( ldd /usr/bin/$file | awk '{print $3}' | grep -v fffe000 ); do
install -d $CRAMFSDIR/${lib%/*}
install $lib $CRAMFSDIR/$lib
done
done

echo "Copy binaries from /sbin."
# Copy /sbin binaries over and any require libraries.
files_sbin="cryptsetup e2label modprobe pivot_root"
for file in $files_sbin ; do
install /sbin/$file $CRAMFSDIR/sbin/$file
for lib in $( ldd /sbin/$file | awk '{print $3}' | grep -v fffe000 ) ; do
install -d $CRAMFSDIR/${lib%/*}
install $lib $CRAMFSDIR/$lib
done
done

# Add common links
ln -s bash /tmp/cramfs/bin/sh
ln -s mawk /tmp/cramfs/bin/awk

echo "Copy devices over."
# Copy devices over
cp -apL /dev/{console,hd,initrd,null,ram,scd,sd}* $CRAMFSDIR/dev/

echo "Copy modules over."
# Copy modules over
modules="aes-i586 dm-crypt sd_mod sr_mod ehci-hcd uhci-hcd ohci-hcd sl811-hcd usbhid usbkbd usb-storage vesafb fbcon ext2 unix"
for mod in $modules; do
for ko in $( modprobe --set-version $VERSION --show-depends $mod | cut -b8- ) ; do
install -d $CRAMFSDIR/${ko%/*}
install $ko $CRAMFSDIR/$ko
done
done

cp -apL /lib/modules/$VERSION/modules.* $CRAMFSDIR/lib/modules/$VERSION/

echo "Copy /etc files over."
# Copy required config files over
cp -apr /etc/modprobe.d $CRAMFSDIR/etc/
echo "Copy custom init over."
# Copy custom init file. (see below)
cat <$CRAMFSDIR/sbin/init
#!/bin/bash

# Filename: /sbin/init
# Dependencies: awk, bash, cryptsetup, e2label, find, grep, modprobe
# mount, pivot_root, sed, sleep and uname.
#
# This file generated by mkinitrd.dmcrypt-usb by Dave Vehrs.
set -e

# Set vars
unset pass part_boot part_rootfs major minor label
dm_name="device-mapper"
dm_dir="mapper"
dir="/dev/\$dm_dir"
control="\$dir/control"
count=0

# Mount /proc
/bin/mount -n -t proc none /proc

# Mount /dev/mapper on tmpfs
/bin/mount -o rw -n -t tmpfs none /dev/mapper

# Modules to load
CORE_MODULES="unix ide-core scsi_mod sd_mod sr_mod mbcache ext2"
DISPLAY_MODULES="vesafb fbcon"
CRYPT_MODULES="aes-i586 dm-mod dm-crypt"
USB_MODULES="ehci-hcd ohci-hcd uhci-hcd sl811-hcd usbcore usbhid usbkbd usb-storage"

# Load Modules
if [ -e /lib/modules/\$(/bin/uname -r) ] ; then
echo "initrd: loading modules."
for module in \$DISPLAY_MODULES \$CORE_MODULES \$CRYPT_MODULES \$USB_MODULES ; do
/bin/find /lib/modules/\$(/bin/uname -r) -name \$module.ko -exec /sbin/modprobe \$module \;
done
fi

# Test to be sure the procfs is mounted, if not exit.
if [ ! -e /proc/devices ] ; then
echo "initrd: procfs not found: please create \$control manually."
exit 1
fi

major=\$(/bin/sed -n 's/^ *\\([0-9]\+\\) \+misc$/\1/p' /proc/devices)
minor=\$(/bin/sed -n "s/^ *\\([0-9]\+\\) \+\$dm_name\\\$/\1/p" /proc/misc)

# Test to be sure dm_mod loaded
if [ -z "\$major" -o -z "\$minor" ] ; then
echo "initrd: \$dm_name kernel module not loaded: can't create \$control."
exit 1
fi

# Create new control device.
echo "initrd: creating \$control character device with major:\$major minor:\$minor."
/bin/mknod --mode=600 \$control c \$major \$minor

# Sleep to let kernel finish loading. 15 seconds is enough on most systems.
echo "initrd: sleeping for 15 seconds so kernel can finish detecting devices."
/bin/sleep 5
echo "initrd: sleeping for 10 more seconds..."
/bin/sleep 5
echo "initrd: sleeping for 5 more seconds..."
/bin/sleep 5
echo "initrd: awake...."

# Search for boot partition label. When usb media is detected by the operating
# system seems to migrate a little depending on what port you connect to on the
# mainboard and what if any other devices are connected and where. To
# compensate for that, we search for the label on our boot partition.
echo "initrd: searching for boot partition label."
for device in \$( /bin/grep sd[a-h]1 /proc/partitions | /bin/awk '{print \$4}' ) ; do
label=\$( /sbin/e2label /dev/\$device 2>/dev/null )
if [ ! -z "\$label" ] ; then
if [ "\$label" == "$BOOT_LABEL" ] ; then
part_boot="/dev/\$device"
break
fi
fi
done

# Exit if boot partition not found.
if [ -z "\$part_boot" ] ; then
echo "initrd: error -- boot partition label not found (\$part_boot)."
exit 1
fi

# Assign rootfs variable from boot (i.e. if boot is on /dev/sda1, this will
# set part_rootfs to /dev/sda2).
part_rootfs=\$( echo \$part_boot | /bin/sed -e 's/1/2/' )

# Unmount /proc
/bin/umount /proc

# Prompt for password
echo -en "\\nplease enter password for rootfs filesystem: "
read -s pass
echo -e

# Attempt mounting
echo "initrd: attempting to mount rootfs."
echo \$pass | /sbin/cryptsetup create rootfs \$part_rootfs
/bin/mount -r -n -t ext2 /dev/mapper/rootfs /mnt

# Loop for bad password attempts
while [ \$? -ne 0 ] ; do
# Remove old crypt mount.
/sbin/cryptsetup remove rootfs

# Test for max tries.
if [ \$count -ge 5 ] ; then
echo -e "\\ninitrd: too many bad guesses. aborting."
exit 1
else
count=\$(( \$count + 1 ))
fi

# Reprompt for password
echo -e "\\ninitrd: error -- rootfs mount failed."
echo -n "please re-enter password: "
read -s pass
echo

# Reattempt mounting
echo \$pass | /sbin/cryptsetup create rootfs \$part_rootfs
/bin/mount -r -n -t ext2 /dev/mapper/rootfs /mnt
done

unset pass

echo "initrd: rootfs successfully mounted."

# Now that the encrypted media is readable, shift the root to it and continue
# the boot cycle by running its init.
cd /mnt
/sbin/pivot_root . initrd
exec /usr/sbin/chroot . /sbin/init
EOF
chown root:root $CRAMFSDIR/sbin/init
chmod 755 $CRAMFSDIR/sbin/init

# make cramfs file
if [ -z "$outfile_name" ] ; then
mkcramfs $CRAMFSDIR ./initrd-$VERSION.img
else
mkcramfs $CRAMFSDIR $outfile_name
fi

# Cleanup
if [ $keep_temp -eq 0 ] ; then
rm -rf $CRAMFSDIR
fi
Set permissions, and links.
chown root.root /usr/local/sbin/mkinitrd.dmcrypt-usb
chmod 750 /usr/local/sbin/mkinitrd.dmcrypt-usb
ln -s /usr/local/sbin/mkinitrd.dmcrypt-usb /usr/sbin/mkinitrd
Next we need to install an equivs package to let the package system know that we installed this ourselves and not to install initrd-tools
cd /tmp
equivs-control initrd-tools
Edit the generated template so that it looks like:
Section: misc
Priority: optional
Standards-Version:

Package: initrd-tools
Build equivs package
equivs-build initrd-tools
Install the package
dpkg -i initrd-tools_1.0_all.deb
For more information about equivs, see the APT howto at: APT-Howto: Equivs

16. Remove unwanted locales

Be very careful configuring and running localepurge. It is very easy to delete too many locales.
apt-get install localepurge
localepurge
apt-get clean
For more information about localepurge, see the APT howto at: APT-Howto: localepurge

17. Install kernel

WARNING: Kernels prior to 2.6.10 had a bug in the dm_crypt modules that potentially could reveal data. Only use 2.6.10 or better.
apt-get install kernel-image-2.6.11-1-686
apt-get clean
Note: Install size is approximately 184MB now. If you want to install a kernel built from source you can. After you install it, run /sbin/mkinitrd to build the /boot/initrd file. When you run /sbin/mkinitrd, it may print several FATAL errors regarding modules that it cannot find. If you built these modules into the kernel then you can ignore the error messages. If you omitted the modules, this is your warning to go build them as modules or into the kernel. Required modules: dm_crypt, aes, ide_core, scsi_mod, sd_mod, ehci-hcd, ohci-hcd, uhci-hcd, sl811-hcd, usb-storage, usb-hid, dm_mod, cramfs

18. Install optional packages

apt-get install vim irsii-text mutt fetchmail antiword screen
apt-get install exuberant-ctags less procmail
apt-get install python2.3 python2.3-pexpect python2.3-fuse
apt-get install xserver-common xserver-xfree86 xbase-clients xfree86-common
apt-get install ion3 -or- blackbox -or- fluxbox -or- icewm
apt-get install xterm
apt-get install memtest86+
Note: All this is approximately 300mb installed (with dependencies).

19. Install grub

apt-get install grub
grub-install /dev/sdd
mkdir /boot/grub
grub
root (hd1,0)
setup (hd1)
quit
Create /boot/grub/menu.lst file
# default num
default 0

# timeout sec
timeout 5

# pretty colours
color green/black black/green

title Debian GNU/Linux-2.6.11-1-686
root (hd0,0)
kernel /vmlinuz-2.6.11-1-686 root=/dev/ram0 init=/sbin/init vga=794
initrd /initrd.img-2.6.11-1-686
savedefault
boot

title Debian GNU/Linux-2.6.11-1-686 (Rescue/Single)
root (hd0,0)
kernel /vmlinuz-2.6.11-1-686 root=/dev/ram0 init=/sbin/init single
initrd /initrd.img-2.6.11-1-686
boot

title Memtest86+
root (hd0,0)
kernel /memtest86+.bin
boot

20. Add User accounts

Either:

Copy an existing /etc/group, /etc/passwd, and /etc/shadow file over from another system (this has to be done from outside the chroot directory).

Or:

Add users locally.

  1. set root password
    passwd root
  2. add local user
    useradd 
    passwd
  3. repeat step 2 as necessary

21. Exit Jail

umount -a
umount /proc
exit

22. Unmount and remove crypt mapping

cd
umount /mnt/buildroot/
cryptsetup remove rootfs

23. Reboot to test media

shutdown -r now

MOUNTING ON ANOTHER LINUX SYSTEM

1. Make sure required modules are loaded.

modprobe dm_crypt
modprobe aes-i586 (or aes)
modprobe usb-storage

2. Insert USB key into port

3. Create device mapping and mount

cryptsetup create rootfs /dev/sdd2
mount /dev/mapper/rootfs /mnt/buildroot

Posted by Anonymous (193.124.xx.xx) on Sat 23 Jul 2005 at 11:26
Really cool article. Great respect to the author.

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Wed 27 Jul 2005 at 03:51
[ Send Message ]
Yes, feed the ego....but on a serious note, thank you.

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Wed 27 Jul 2005 at 03:38
[ Send Message ]
Debian stopped using the non-US sources for SID so we can simplify the sources.list file to be:
deb http://mirrors.kernel.org/debian/ sid main non-free contrib
deb-src http://mirrors.kernel.org/debian/ sid main non-free contrib


# If you are using debian stable (woody) include the security updates.
# deb http://security.debian.org/ sid/updates main non-free contrib

[ Parent | Reply to this comment ]

Posted by Anonymous (199.209.xx.xx) on Wed 3 Aug 2005 at 21:10
Hi,
I'm a newbie and I have a question about how do you determine what the device name is for the USB flash media. I have Debian 3.1 loaded, and when I insert my USB flash media, the system recognizes it and mounts it. However, the properties show it to be in /media/"volume name". I have no idea name it is associated to under /dev/

TIA,
Jon

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Wed 3 Aug 2005 at 23:51
[ Send Message ]
Run the mount command and the output will tell you what is mounted where.

For example:
$ mount
/dev/sda2 on / type ext2 (rw,errors=remount-ro)
proc on /proc type proc (rw)
/dev/sda1 on /boot type ext2 (rw)

[ Parent | Reply to this comment ]

Posted by Anonymous (199.209.xx.xx) on Thu 4 Aug 2005 at 13:30
Thanks Dave,
That is exactly what I needed ;-)

[ Parent | Reply to this comment ]

Posted by Anonymous (199.209.xx.xx) on Thu 4 Aug 2005 at 18:52
Dave,
I have run into a problem with this at Step 5. When I enter "cryptsetup -y create rootfs /dev/sdb2", I get prompted for a passphrase. I enter one and get prompted to retype it, which I do. At this point, I get the error: "command failed: invalid argument"

Do you happen to know what might cause this?

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Thu 4 Aug 2005 at 20:44
[ Send Message ]
I've seen reports of that with more recent versions of libdevmapper1.01. What version do you have installed?

Also, what versions of dmsetup and cryptsetup?

Also what platform are you running on AMD64 or i386? I generally use AMD64 but I can open a 32bit jail for some testing....

[ Parent | Reply to this comment ]

Posted by Anonymous (199.209.xx.xx) on Thu 4 Aug 2005 at 21:26
Dave,
I have the following:
libdevmapper=2:1.01.00-4 (that's how synaptic shows it)
dmsetup=2:1.01.00-4
cryptsetup=20050111-3

I am running on i386

Thanks

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Fri 5 Aug 2005 at 16:32
[ Send Message ]
First, do you have libdevmapper or libdevmapper1.01 installed? If its libdevmapper, uninstall it and install libdevmapper1.01.

Second, I think your dmsetup is a couple versions behind current and a quick apt-get update/upgrade should fix that.

(I have version 1.01.03-1 for dmsetup and libdevmapper1.01)

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Sat 6 Aug 2005 at 03:42
[ Send Message ]
Ok, after further research it appears that something big is broken. I'm getting a variety of errors on both my amd64 and i386 test boxes.

The only versions I have that still mount are all a couple of months out of updates so I'll try and work backwards from them to see what changed.

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Sat 6 Aug 2005 at 06:17
[ Send Message ]

OK, rebuilding libdevmapper1.01 and dmsetup from the source package fixed my problems.

Easiest/fastest way to rebuild it is with apt-src.

First, install apt-src if you need to and remove prebuilt versions of libdevmapper1.01, dmsetup:

apt-get install apt-src
apt-get remove libdevmapper1.01 dmsetup

Note: cryptsetup will get removed as well because it depends on libdevmapper1.01 and dmsetup.

Second, create a directory to store source files in and use apt-src to download/install the necessary files:

cd $HOME
mkdir SRC
apt-src install libdevmapper1.01

Third, build the packages:

apt-src build libdevmapper1.01 dmsetup

Forth, install the packages:

dpkg -i libdevmapper1.01*.deb libdevmapper-dev*.deb dmsetup*.deb

Fifth, put cryptsetup back:

apt-get install cryptsetup

Note: Until the binary distribution of libdevmapper1.01 and dmsetup is fixed, you will also need to run apt-src update/upgrade when you do regular system updates with apt-get update/upgrade.

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Sat 6 Aug 2005 at 06:29
[ Send Message ]

Small correction.

Change into the SRC directory after you create it, as apt-src will create quite a few directories and files.

cd $HOME
mkdir SRC
cd SRC
apt-src install libdevmapper1.01

....

[ Parent | Reply to this comment ]

Posted by Anonymous (199.209.xx.xx) on Tue 9 Aug 2005 at 18:42
Dave,
Sorry about the delay in getting back to you (I hosed my kernel trying to get sound support working and had to rebuild). Anyway, everything appears to be fine now until I get to step 9. I execute "debootstrap --arch i386 sid /mnt/buildroot" and the system goes out and downloads a lot of files but it errors out with: "Couldn't download libsigc++-1.2-5c102" and then I get kicked back to a prompt.

Jon

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Tue 9 Aug 2005 at 19:42
[ Send Message ]
Jon,

Yeah, debootstrap can be a little finky sometimes. However, the good news is you can just run it again as many times as necessary until you get the successful install message.

If its a download issue then generally a second run is all thats necessary.

Or if its a problem with the mirror's update status, try different mirror or wait a day then try again.

[ Parent | Reply to this comment ]

Posted by irishjd (199.209.xx.xx) on Wed 10 Aug 2005 at 17:19
[ Send Message ]
Dave,
I tried multiple downloads and multiple mirrors, but debootstrap keep failing at: "Couldn't download libsigc++-1.2-5c102" Do you happen to know of a mirror that you know works?

Thanks,
Jon

[ Parent | Reply to this comment ]

Posted by Anonymous (134.96.xx.xx) on Fri 12 Aug 2005 at 11:55
Ok...

I had the same problem when trying to install to a
loop device

try

--exclude=libsigc++-1.2-5c102

to exclude the file from the bootstrap. It can later be added :)

[ Parent | Reply to this comment ]

Posted by Anonymous (86.8.xx.xx) on Sun 28 Aug 2005 at 21:18
Hello! Yes great work! I had on my mind to do something like this for quite sometime and today I came across this page! because I could not download libsigc++-1.2-5c102 I used sarge instead of sid... maybe I shouldn't... at the end of debootstrap I got:
I: Extracting libstdc++5... ar: /mnt/buildroot//var/cache/apt/archives/dpkg_1.10.28_i386.deb /var/cache/apt/archives/dpkg_1.13.11_i386.deb: No such file or directory zcat: stdin: unexpected end of file I: Installing core packages... ln: `/mnt/buildroot/usr/bin/awk': File exists umount: /mnt/buildroot/dev/pts: not mounted umount: /mnt/buildroot/dev/shm: not mounted umount: /mnt/buildroot/proc/bus/usb: not mounted
then on chroot I just can't su:
Portatil:/mnt/buildroot# chroot /mnt/buildroot/ /bin/su - Sorry. Portatil:/mnt/buildroot# chroot /mnt/buildroot/ I have no name!@Portatil:/# su Sorry.
Then on step 11
I have no name!@Portatil:/# pico /etc/fstab bash: pico: command not found I have no name!@Portatil:/# nano /etc/fstab bash: nano: command not found I have no name!@Portatil:/# vi /etc/fstab bash: vi: command not found
ok so I used my own environment to create the /mnt/buildroot/etc/fstab entrie but when on chroot I used the mount -a:
I have no name!@Portatil:/# mount -a warning: can't open /etc/mtab: No such file or directory mount: special device LABEL=PRIVDEB_BOOT does not exist mount: mount point /etc/network/run does not exist mount: mount point /home//Scratch does not exist
On step 12 I used again my own environment and I copied my own sources.list (for debian sarge). And on step 13 on the /etc/hosts and /etc/hostname I also have also used my own environment... Now the big problem is step 14:
I have no name!@Portatil:/# apt-get update bash: apt-get: command not found I have no name!@Portatil:/# aptitude
please I would like some help... should I erase everything and use debootstrap sid with --exclude=libsigc++-1.2-5c102 ? thanks in advance Tiago Geada

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Sun 28 Aug 2005 at 22:08
[ Send Message ]

Almost all of the errors after su failed are related to the fact that your new chroot environment is not setup properly. For example, the applications can't be found cause the PATH variable is not set.

For the mount error, if you created the link to /etc/mtab to /proc/mounts, then the error is that /proc probably isn't mounted yet. Try this:

mount -t proc none /proc
mount -a

However having said all that, I believe that the root problem is that debootstrap error. While its probably fixable, the quickest solution is to just erase everything and start over with either sarge or sid.

[ Parent | Reply to this comment ]

Posted by cusco (86.8.xx.xx) on Mon 29 Aug 2005 at 00:32
[ Send Message ]
ok now everything went good until installing the kernel

as I have choosen sarge instead of sid I would have to install kernel-image-2.6.8-2-686 instead (like not caring about the bug that could reveal data). Altho I get the following output:

---
Portatil:/tmp# apt-get install kernel-image-2.6.8-2-686
Reading Package Lists... Done
Building Dependency Tree... Done
kernel-image-2.6.8-2-686 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
1 not fully installed or removed.
Need to get 0B of archives.
After unpacking 0B of additional disk space will be used.
Setting up kernel-image-2.6.8-2-686 (2.6.8-16) ...
Build directory tree.
Copy binaries from /bin.
Copy binaries from /usr/bin.
Copy binaries from /sbin.
Copy devices over.
Copy modules over.
FATAL: Module sl811_hcd not found.
Copy /etc files over.
Copy custom init over.
/usr/sbin/mkinitrd: line 120: /tmp/cramfs/sbin/init: No such file or directory
mount: proc already mounted
Failed to create initrd image.
dpkg: error processing kernel-image-2.6.8-2-686 (--configure):
subprocess post-installation script returned error exit status 9
Errors were encountered while processing:
kernel-image-2.6.8-2-686
E: Sub-process /usr/bin/dpkg returned an error code (1)
---

so Im stuck here... should I go back all the process again and choose sid instead??

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Mon 29 Aug 2005 at 01:12
[ Send Message ]

It should still work. Let me look into it.

Off of the top of my head the problem is in step 15, maybe you can retry from there. (no need to erase it all)

Ignore the "FATAL: Module sl811_hcd not found.", thats only a problem if thats your USB controller chipset which obviously isn't a problem for you because you're already accessing usb devices.

[ Parent | Reply to this comment ]

Posted by cusco (86.8.xx.xx) on Tue 30 Aug 2005 at 00:55
[ Send Message ]
I don't know why or how but I cant install the kernel

I don't understand anything about the initrd...

-----

Get:1 http://mirrors.kernel.org sarge/main
kernel-image-2.6.8-2-686 2.6.8-16 [15.5MB]
Fetched 15.5MB in 1m19s (196kB/s)
Selecting previously deselected package
kernel-image-2.6.8-2-686.
(Reading database ... 10083 files and directories currently installed.)
Unpacking kernel-image-2.6.8-2-686 (from .../kernel-image-2.6.8-2-686_2.6.8-16_i386.deb) ...

You are attempting to install an initrd kernel image (version 2.6.8-2-686)
This will not work unless you have configured your boot loader to use initrd. (An initrd image is a kernel image that expects to use an INITial Ram Disk to mount a minimal root file system into RAM and use that for booting).

As a reminder, in order to configure LILO, you need
to add an 'initrd=/initrd.img' to the image=/vmlinuz
stanza of your /etc/lilo.conf

I repeat, You need to configure your boot loader -- please read your
bootloader documentation for details on how to add initrd images.

If you have already done so, and you wish to get rid of this message,
please put
"do_initrd = Yes"
in /etc/kernel-img.conf. Note that this is optional, but if you do not,
you will continue to see this message whenever you install a kernel
image using initrd.
Do you want to stop now? [Y/n]n
Setting up kernel-image-2.6.8-2-686 (2.6.8-16) ...
Build directory tree.
Copy binaries from /bin.
Copy binaries from /usr/bin.
Copy binaries from /sbin.
Copy devices over.
cp: cannot stat `/dev/hd*': No such file or directory
cp: cannot stat `/dev/initrd*': No such file or directory
cp: cannot stat `/dev/scd*': No such file or directory
cp: cannot stat `/dev/sd*': No such file or directory
Copy modules over.
FATAL: Module sl811_hcd not found.
Copy /etc files over.
Copy custom init over.
/usr/sbin/mkinitrd: line 120: /tmp/cramfs/sbin/init: No such file or directory
mount: mount point /dev/mapper does not exist
Failed to create initrd image.
dpkg: error processing kernel-image-2.6.8-2-686 (--configure):
subprocess post-installation script returned error exit status 9
Errors were encountered while processing:
kernel-image-2.6.8-2-686
localepurge: Disk space freed in /usr/share/locale: 25116K
E: Sub-process /usr/bin/dpkg returned an error code (1)

---------

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Tue 30 Aug 2005 at 06:32
[ Send Message ]

Ok, I dunno why sarge isn't working, but I've done most of my testing with sid and it works like clockwork. Try it.

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Thu 15 Sep 2005 at 02:29
[ Send Message ]

Looks like I may have discovered the bug that was causing this to fail for you. Sorry I didn't catch it sooner.

See post http://www.debian-administration.org/articles/179#comment_28

[ Parent | Reply to this comment ]

Posted by DaveV (24.8.xx.xx) on Mon 29 Aug 2005 at 01:42
[ Send Message ]

Just out of curiosity, what brands and sizes of usb media have people been using? Any recommendations or warnings?

[ Parent |

Construire un système linux read-only sur une compact flash 10/12/2007 16:27:54

Problématiques

Les installations classiques sont sensibles aux coupures électriques et aux arrêt brutaux qui peuvent conduire à des pertes de donnée voir empêcher un redémarrage normal. Par ailleurs les disques compact flash supportent un nombre limité d'écriture qu'il est important de contrôler dans le cas d'un système sur compact-flash
Pour mettre en œuvre facilement un système robuste où les disques ne sont pas montés en écriture il est possible d'utiliser des systèmes de fichier en ram 'fusionnés' avec des partitions sur disque en utilisant le module unionfs.
Je décris ici plusieurs approches en sachant que nous voulons à la fois avoir un système read only mais aussi pouvoir sauver les modifications et garantir l'intégrité des données...

Qu'est ce qu'unionfs?

 Unionfs est un système de fichier permettant de fusionner virtuellement des systèmes de fichier (appelé branches). Chaque branche se voie attribuée une priorité et peut-être read-only ou read-write. Unionfs est largement utilisé sur les live CD car il implémente un mécanisme de copy on write, c'est à dire que quand un fichier d'une union est modifiée, le contenu du fichier est recopié dans la branche read-write est ainsi l'union parait read-write alors qu'une ou plusieurs branches sont read-only.

Mise en œuvre

 Il faut utiliser un noyau récent (cad > 2.6.18 pour utiliser unionfs v2) et compiler le module unionfs disponible ici . Malheureusement unionfs n'est pas présent dans le noyau officiel, mais il est dans la branche d'Andrew Morton (-mm). Je ne parle ici que d'unionfs 2.1 qui apporte des amélioration intéressantes par rapport à la précédant, en particulier elle permet d'acceder aux branches "raw" d'une union. Notez que la version dans debian etch est ancienne est à déconseiller!

Pour créer des union on utilise simplement la syntaxe:

mount -t unionfs unionfs /nom_de_lunion -o dirs=/rep1=rw:/rep2=ro:...

Il est possible de fusionner de nombreuses branches, la première apparaissant étant la plus prioritaire. 

 Sous unix, les répertoires /etc, /var et /tmp doivent être read-write. Pour /tmp, pas de problème, un tmpfs fait l'affaire, pour /var et /etc il faut jouer avec les unions...

Première approche

On va créer  des systèmes de fichier tmpfs qui seront des branches read-write pour /var et /etc. Appelons les /rametc et /ramvar. Ensuite on crée des unions respectivement avec /etc et /var.

Pour ne pas s'embêter avec la gestion de /etc/mtab, on peut faire un lien vers /proc/mounts  

Pour monter les répertoires en unionfs très tôt lors du boot, on peut ajouter les lignes suivantes au début du fichier /etc/init.d/rcS (sur une debian):
/bin/mount -n -t tmpfs tmpfs /rametc -o size=30M
/bin/mount -n -t tmpfs tmpfs /ramvar -o size=50M
/bin/mount -n -t unionfs unionfs /etc -o dirs=/rametc=rw:/etc=ro
/bin/mount -n -t unionfs unionfs /var -o dirs=/ramvar=rw:/var=ro
echo "tmpfs /rametc tmpfs rw,size=30M 0 0" >> /etc/mtab
echo "tmpfs /ramvar tmpfs rw,size=50M 0 0" >> /etc/mtab
echo "unionfs /etc unionfs rw,dirs=/rametc=rw:/etc=ro 0 0" >> /etc/mtab
echo "unionfs /var unionfs rw,dirs=/ramvar=rw:/var=ro 0 0" >> /etc/mtab

 

Dans /etc/fstab on n'oublie pas tmp:

none /tmp tmpfs defaults,nosuid,nodev,noexec 0 0

et du coup on peut mettre /,/boot et /var en ro

Cette technique est également décrite: ici 

Cette approche pose problème pour remonter les partitions en rw et surtout on n'accède plus aux branches /var et /etc initiales, donc la resynchronisation n'est pas possible.

 

Deuxième approche

Une autre solution consisterai à créer des unions ou l'on veux et ensuite utiliser la commande pivot_root. Cette commande permet de remplacer le répertoire racine et le répertoire courant de tous les processus en cours d'exécution.

En général on utilise pivot_root à la fin du script d'init présent dans initramfs. Pour se simplifier la vie, on peut le lancer dans rcS (debian) 

Dans ce cas on procède ainsi: 

- Montage de root dans /n/root

- Montage de tmpfs dans /n/tmpfs

- mount unionfs avec dirs=/n/tmpfs:/n/root=ro dans /mnt/unionfs

- pivot_root dans /mnt/unionfs 

- chroot du shell en cours dans l'union

Eventuellement mount --move de /dev/ 

Attention, chroot doit être accessible dans le système pivoté... une copie en dehors de /usr ne fait pas de mal. 

Encore une solution

Sur la partition / on crée les répertoires /etc et /var qui resterons read-only.
On crée des partitions sur le disque qui serviront à la synchro des repertoires tmpfs (dans l'exemple suivant on les monte dans /rw_etc et /rw_var)
On crée des répertoires /varram etc /etcram en tmpfs .
On monte dans /etc et /var respectivement les unions de /etcram(rw)+/rw_etc(ro)+/etc(ro) et de /varram+rw_var+/var
Dans ce cas on peut remonter quand on veut /rw_etc en rw et faire des rsync

Comme précédemment, pour ne pas s'embêter avec la gestion de /etc/mtab, on peut faire un lien vers /proc/mounts 

Code pour /etc/init.d/rcS

/bin/mount -n -t tmpfs tmpfs /rametc -o size=30M
/bin/mount -n /dev/sdb1 /rw_etc -o ro
/bin/mount -n -t unionfs unionfs /etc/ -o dirs=/rametc=rw:/rw_etc=ro:/etc=ro
echo "tmpfs /rametc tmpfs rw,size=30M 0 0" >> /etc/mtab
echo "/dev/sdb1 /rw_etc ext3 rw 0 0" >> /etc/mtab
echo "unionfs /etc/ unionfs rw,dirs=/rametc=rw:rw_etc=ro:/etc=ro 0 0" >> /etc/mtab
/bin/mount /dev/sdc1 /rw_var -o ro
/bin/mount -t tmpfs tmpfs /ramvar -o size=50M
/bin/mount -t unionfs unionfs /var/ -o dirs=/ramvar=rw:/rw_var=ro:/var=ro

Le gros avantage de cette structure à trois branches par union est outre de permettre des copies entre branche pour la synchro, de pouvoir effacer quand on veux les repertoire rw_* et ainsi revenir dans l'état d'instalation (reset to factory).

Il y a plein de façon de faire avec unionfs... 

Resyncronisation

Avec unionfs 2.1 (et contrairement à ce que dit la page de manuel) on peut intervenir directement sur les branches. Il est donc possible de remonter les partitions en rw le temps de faire un rsync.

  Un problème qui se pose est alors de purger les partitions tmpfs pour quelles ne continuent pas à remplir la mémoire et de bien effacer de la compact flash les fichiers qui ont été détruit. Pour cela unionfs crée des fichiers "whiteout" (.wh.nomdufichier) dans la branche rw quand un fichier ou un répertoire est détruit. Il est facile de pacourir ces fichiers et de détruire les fichiers originaux.

 Voici un exemple de script de syncho (à lancer périodiquement et/ou au reboot)

#On remonte /rw_etc en rw pour copier les modifs dessus. 

mount -o remount,rw /rw_etc

 rsync -a --exclude '.wh*' /rametc /rw_etc
#Pour être sur de bien flusher les caches 
mount -o remount,incgen /etc

#Il vaut mieux retirer la branche avant d'effacer les fichiers
mount -t unionfs -o remount,del=/rametc none /etc

find /rametc \( -regex '.*/\.wh\.[^/]*' -type f \) | sed -e 's/\.\///;s/\.wh\.//' |
while read N
do
    rm -rf /rw_etc/$N
done
rm -rf /rametc/*
mount -t unionfs -o remount,add=/rametc none /etc
mount -o remount,ro /rw_etc

Évidement, faire des copies de fichiers ouverts, éventuellement en écriture, ce n'est pas forcement fiable. Idéalement il faudrai synchroniser lors d'un shutdown, mais la copie à chaud ne marche pas si mal à condition de prendre certaines précautions.

Pour une base de donnée, on peut locker les tables en lecture uniquement. Ca fonctionne correctement avec MySQL avec des tables MyISAM. 

L'astuce pour locker les tables pendant le temps le plus court possible consiste à faire un double rsync.

- Un premier rsync crée une première copie

- On lock les table: mysql -p ... -u ... < "FLUSH TABLES WITH READ LOCK"

- Un deuxième rsync qui va être ultra rapide cette fois

- on delock: "UNLOCK TABLES"

  Une autre solution élégante serai de faire un snapshot avec LVM, par contre on ne peut pas utiliser LVM avec tmpfs, donc il faudrai utiliser un ramdisk, pas très pratique à mettre en œuvre... Il y a des discussions intéressante à ce propos ici

Références:

Site officiel de Unionfs 

Unionfs: User- and Community-Oriented Development of a Unification File System: http://www.fsl.cs.sunysb.edu/docs/sipek-ols2006/index.html 

Tutorial Gentoo, http://gentoo-wiki.com/HOWTO_Read-only_root_filesystem#Unionfs_Method

Snapshot LVM et MySQL : http://mike.kruckenberg.com/archives/2006/05/mysql_backups_u.html

Aufs, un concurant de unionfs: http://aufs.sourceforge.net/  

Freesco 08/12/2007 18:47:02
Freesco (qui vient de FREE ciSCO) est une distribution Linux très petite (MiniLinux), destinée à être utilisée comme firewall/routeur, ce qui permet le partage d'une connexion internet entre plusieurs ordinateurs d'un même réseau local. Elle peut être stockée sur une simple disquette 1.44 Mo, et nécessite un minimum de 8Mo de RAM.

http://fr.wikipedia.org/wiki/Freesco
http://www.freesco.org/
http://freesco.sourceforge.net/


Générateur de rootfs linux pour l'embarqué 05/12/2007 18:35:35
 Voici une liste de systemes qui permettent de créer des images root_fs comme celui de la livebox, freebox, ou tout systeme embarqué ... ou non (liste non exhaustive) :

 Buildroot :

 http://buildroot.uclibc.org/cgi-bin/viewcvs.cgi/trunk/buildroot/
 Propose un buildsystem + download sources/patch +  création firmware

 Emdebian :
 http://www.emdebian.org/

 Fish :
 http://www.michaeladams.org/fish/download/

 Leaf :
 http://leaf.sourceforge.net/bering-uclibc/index.php?module=pagemaster&PAGE_user_op=view_page&PAGE_id=3&MMN_position=3:3
 http://leaf.sourceforge.net/doc/guide/buc-buildtool.html
 Leaf propose buildsystem ("buildtool") + download des sources/patch + packaging

 LRP :
 (LEAF= Linux Embedded Appliance Firewall, LRP=LinuxRouterProject)

 OpenWRT
 http://openwrt.alphacore.net/
 OpenWrt propose buildsystem + download sources/patch
 +
 packaging IPKG (à la debian)
 (WRT= wireless router (linksys wrt54g), IPKG= (issue
 de familiar sur IPaq)

 PTXdist :
 http://www.pengutronix.de/software/ptxdist_en.html

 Scratchbox :
 ScratchBox fournit des environnements de
 cross-compilation similaires à ce que l'on peut
 proposer dans SDKBOX (entre buildsystem et
 simulator).
 [/etc/apt/source.list  "deb                                
 http://scratchbox.org/debian ./" ]

 PeeWee Linux :
 http://peeweelinux.com/


LCD-Linux 04/12/2007 10:46:29
LCD-Linux is a Linux software abstraction layer to drive LCD alphanumeric displays. It features complete VT102 console emulation and aims to be as general and flexible as possible. It consists of two kernel modules, lcd-linux and the display driver. Currently, only the Hitachi HD44780 is supported, but drivers for other LCD controllers can be easily written.

Author: Mattia Jona [contact developer]

Homepage: http://lcd-linux.sourceforge.net/

Tar/GZ: http://sourceforge.net/project/showfiles.php?group_id=123240

Trove categories: 
[Development Status]  5 - Production/Stable
[Intended Audience]  Advanced End Users, Developers, System Administrators
[License]  OSI Approved :: GNU General Public License (GPL)
[Operating System]  POSIX :: Linux
[Programming Language]  C
[Topic]  System :: Hardware
[Translations]  English

Liste des articles
Free-EOS 08/12/2007 18:49:26
Free-EOS frɪ e ɒ s est un projet de distribution linux libre fournissant un serveur réseau d'application adapté à des PME/PMI, des particuliers ou à des organismes d'enseignement ou associatifs. Par la suite le projet à évolué pour se décomposer aujourd'hui en trois branches de développement d'applications libres. La principale se nomme tout simplement Free-EOS, c'est une distribution Linux destinée à fournir une solution clé en main de serveur Intranet/Internet proposant de multiples services. La seconde se nomme Free-EOS winstation, elle est le complément idéale de la solution Free-EOS précédente. Elle consiste en une compilation de logiciels pouvant être installés sur des stations de travail Windows afin d'exploiter pleinement les services fournis par un serveur Free-EOS. Une utilisation indépendante du serveur est bien évidemment possible si l'on désire simplement disposer d'un large éventail d'applications libres. Son utilisation principale concerne les Espaces Publics Numériques. La dernière Bureau libre Free-EOS est une compilation héritée de Free-EOS winstation résolument orientée grand public. Elle privilégie une approche très documentée afin de pouvoir être mise entre des mains non initiées (utilisation domestique, milieu scolaire, milieu associatif, etc.)
Uboot 03/12/2007 16:39:18
This is the DENX U-Boot and Linux Guide to Embedded PowerPC, ARM and MIPS Systems. The document describes how to configure, build and use the firmware Das U-Boot (typically abbreviated as just "U-Boot") and the operating system Linux for Embedded PowerPC, ARM and MIPS Systems.
Redboot 03/12/2007 16:31:12
open source application that uses the eCos real-time operating system Hardware Abstraction Layer to provide bootstrap firmware for embedded systems. RedBoot is used in both product development and in deployed products in the field. RedBoot allows download and execution of embedded applications via serial or Ethernet, including embedded Linux and eCos applications. It provides debug support in conjunction with GDB to allow development and debugging of embedded applications. It also provides an interactive command line interface to allow management of the Flash images, image download, RedBoot configuration, etc., accessible via serial or ethernet. For unattended or automated startup, boot scripts can be stored in Flash allowing for example loading of images from Flash, hard disk, or a TFTP server.
Liste des liens
Inside the Linux boot process
The process of booting a Linux® system consists of a number of stages. But whether you're booting a standard x86 desktop or a deeply embedded PowerPC® target, much of the flow is surprisingly similar. This article explores the Linux boot process from the initial bootstrap to the start of the first user-space application. Along the way, you'll learn about various other boot-related topics such as the boot loaders, kernel decompression, the initial RAM disk, and other elements of Linux boot.
Page perso d'un geek breton
©2009 LinuX Maine - Tous droits réservés