Booting from SD/ru

From Openmoko

(Difference between revisions)
Jump to: navigation, search
(Загрузка ядра)
(catchg)
 
(6 intermediate revisions by one user not shown)
Line 40: Line 40:
 
=== Параметры корневой файловой системы ===
 
=== Параметры корневой файловой системы ===
  
The contents of the "bootargs" environment variable are passed to the kernel. Bootargs is a space-delimited list of "name=value" definitions. The items relevant to SD-booting are "root", "rootfstype", and "rootdelay".  
+
Содержимое переменной среды "bootargs" отправляется ядру. Bootargs это список разделенных пробелами объявлений "имя=значение". Элементы, относящиеся к SD-загрузке - "root", "rootfstype", и "rootdelay".  
  
For example, the following parameters would tell the kernel to mount the third partition of the SD-card as an ext3 filesystem:
+
Например, следующие параметры заставят ядро смонтировать третий раздел карты SD как файлоую систему ext3:
  
 
   root=/dev/mmcblk0p3 rootfstype=ext3 rootdelay=5  
 
   root=/dev/mmcblk0p3 rootfstype=ext3 rootdelay=5  
  
The "rootdelay" parameter allows time for the card to be properly initialized before it is accessed.  
+
Параметр "rootdelay" позволяет установить время, отводимое на инициализацию карты, перед тем, как будет произведено обращение к ней.  
  
Note that the kernel must have built-in support (i.e. not a module) for the filesystem specified in "rootfstype". The default Openmoko kernel configs as of [http://git.openmoko.org/?p=kernel.git;a=commit;h=642cbda5f3b7e7a61512426e1d30a41ab4691123| 2008-07-17] have built-in support for both ext2 and ext3. You can check the available filesystems with the Linux command
+
Заметьте, что у ядра должна быть встроенная поддержка (то есть не модуль) файловой системы, определенной в "rootfstype". По умолчанию ядро Openmoko настроено как [http://git.openmoko.org/?p=kernel.git;a=commit;h=642cbda5f3b7e7a61512426e1d30a41ab4691123| 2008-07-17], имеет поддержку как ext2, так и ext3. Вы можете проверить доступные файловые системы командой:
  
 
  less /proc/filesystems
 
  less /proc/filesystems
  
It is not possible to use VFAT for the root filesystem.
+
Не возможн использовать VFAT в качестве корневой файловой системы.
  
 
==== ext2 в сравнении ext3 ====
 
==== ext2 в сравнении ext3 ====
  
Opinion is divided on whether it is better to use ext2 or ext3 for the root filesystem. Ext3 in general is a superior choice, because it is a journalled filesystem and so does not require a long 'fsck' (file system check) after an unclean shutdown. However, if used on a flash device that does not support wear-leveling then ext3 may cause premature wear on the blocks of the card where the journal is stored. SD cards are supposed to support wear leveling, but this can not be guaranteed for all vendors.
+
Мнения о том, что лучше использовать ext2 или ext3 для корневой файловой системы, разделяются. Ext3 вообще лучший выбор, поскольку это журналируемая файловая система, так что не требует длительной 'fsck' (проверки файловой системы) после некорректного отключения. Однако, если используется на flash устройстве, которое не поддерживает выравнивание изнашивания тогда, ext3 может вызвать преждевременное изнашивание блоков карты, в которых хранится журнал. Предполагается, что карты SD поддерживают выравнивание изнашивания, но этого нельзя гарантировать для всех поставщиков.
  
 
== Получение tar-архива корневой файловой системы ==
 
== Получение tar-архива корневой файловой системы ==
Line 93: Line 93:
  
 
u-boot pre-2008-07-23 может грузить систему только с файловой системой FAT; если вы обновили u-boot, вы можеет грузиться с FAT или ext2.
 
u-boot pre-2008-07-23 может грузить систему только с файловой системой FAT; если вы обновили u-boot, вы можеет грузиться с FAT или ext2.
Этот пример показывает примерное использование утилиты fdisk для создания разделов на карте. Feel free to use the partitioning utility of your liking for this task.
+
Этот пример показывает примерное использование утилиты fdisk для создания разделов на карте. Не стесняйтесь использовать вашу любимую утилиту разбиения для решения этой задачи.
  
 
  fdisk /dev/mmcblk0
 
  fdisk /dev/mmcblk0
  
'''''Примечание:''''' The device file might differ on your system. If you are not sure about it, you may check your kernel message log by calling ''dmesg'' to find the correct device.
+
'''''Примечание:''''' Файл устройства может отличаться в вашей системе. Если вы не уверены в этом, проверьте лог сообщений ядра вызывом ''dmesg'' для поиска нужного устройства.
  
мы создадим раздел 8 мегабайт для ядра и остальнео пространство для всего остального.
+
мы создадим раздел 8 мегабайт для ядра и остальное пространство для всего остального.
  
 
   Command (m for help): d
 
   Command (m for help): d
Line 127: Line 127:
 
   Syncing disks.
 
   Syncing disks.
  
''Should probably need to change type of first partition to FAT 16 too ?''
+
''Вероятно, необходимо изменить тип первого раздела на также FAT 16?''
  
if it exits with something like
+
если это завершится с чем-то вроде:
  
 
   Calling ioctl() to re-read partition table
 
   Calling ioctl() to re-read partition table
 
   fdisk: WARNING: rereading partition table failed, kernel still uses old table:  Device or resource busy
 
   fdisk: WARNING: rereading partition table failed, kernel still uses old table:  Device or resource busy
  
do
+
выполните:
  
 
   umount /dev/mmcblk0p1
 
   umount /dev/mmcblk0p1
  
on another shell and try again.
+
в другой оболочке и попробуйте снова.
  
 
=== Форматирование SD карты ===
 
=== Форматирование SD карты ===
Line 145: Line 145:
  
 
  mkfs.vfat /dev/mmcblk0p1
 
  mkfs.vfat /dev/mmcblk0p1
{{Note|if you do not have mkfs.vfat you must find and install the "dosfstools" package. This package does not seem to be in the official feeds, but an unofficial build may be downloaded from http://members.shaw.ca/mmontour/neo/dosfstools_2.11-r0_armv4t.ipk}}
+
{{Note|Если у вас нет mkfs.vfat вам потребуется найти и установить пакет "dosfstools". Этот пакет, кажется, не находится в официальных поставках, но может быть загружен с http://members.shaw.ca/mmontour/neo/dosfstools_2.11-r0_armv4t.ipk}}
  
  
Line 156: Line 156:
 
Ваша карточка готова к загрузки на нее ядра и файловой системы.
 
Ваша карточка готова к загрузки на нее ядра и файловой системы.
  
Mount the second partition of your SD card somewhere and put the image on it:
+
Смонтируйте куда-нибудь второй раздел вашей SD карты и поместите на него образ корнеой файловой системы:
  
 
  mount /dev/mmcblk0p2 /mnt/moko
 
  mount /dev/mmcblk0p2 /mnt/moko
 
  tar -C /mnt/moko/ -xzvf openmoko-devel-image-fic-gta01-20070313022035.rootfs.tar.gz
 
  tar -C /mnt/moko/ -xzvf openmoko-devel-image-fic-gta01-20070313022035.rootfs.tar.gz
  
'''''Note:''''' As always in this guide the device name as well as the rootfs name needs to be adjusted to your device and filename structure
+
'''''Важно:''''' Как обычно подразумевается, что название устройства, так же как и название образа rootfs должны быть заменены на ваше устройство и имя вашего файла rootfs.
  
'''''Note:''''' There's a nice gotcha to take care about if you use your host OS automount. Some hosts mount these removable devices with "nodev" option by default for security. If the image you are unpacking has a populated /dev directory, the nodes will fail to create as devices then. If automounting the SD on your host, confirm there are no unexpected mount options by using "mount" command alone to list the mounts.
+
'''''Важно:''''' Если вы используете автоматическое монтирование в вашей операционной системе, неплохо бы позаботиться о некоторых вещах. Некоторые хосты монтируют сменные устройства с опцией "nodev" по умолчанию для безопасности. Если в образе, который вы монтируете, будет непустой каталог /dev, то узлы не смогут проинициализировать это устройство. Если используется автоматическое монтирование SD на вашем хосте, убедитесь, что не используется никаких опций, которые могут вызвать проблемы, простым выполнением команды "mount", которая вернет список точек смонтированных устройств.
  
The next step is to mount the first partition of the sd card and install the kernel on it.
+
Следующим шагом смонтируйте первый раздел SD карты и установите на него ядро:
  
 
  mount /dev/mmcblk0p1 /mnt/mokokernel
 
  mount /dev/mmcblk0p1 /mnt/mokokernel
 
  cp uImage-fic-gta01-latest.bin /mnt/mokokernel/uImage.bin
 
  cp uImage-fic-gta01-latest.bin /mnt/mokokernel/uImage.bin
  
Make sure your kernel is called ''uImage.bin''. If the u-boot doesn't find the kernel image during boot, [[Bootloader#Using usbtty from Linux|log into the bootloader]] with ''[http://www.airs.com/ian/uucp.html cu]'', mount the partition with mmcinit and check the presence and the name of the kernel image with ''fatls mmc 1:1'' for FAT filesystem or ''ext2ls mmc 1:1'' for ext2 filesystem.
+
Убедитесь, что ваше ядро называется ''uImage.bin''. Если u-boot не находит образ ядра во время загрузки, [[Bootloader#Using usbtty from Linux|зарегистрируйтесь в bootloader]] с помощью ''[http://www.airs.com/ian/uucp.html cu]'', смонтируйте раздел при помощи mmcinit и проверьте присутствие, а также имя ядра командой ''fatls mmc 1:1'' для системы FAT, или ''ext2ls mmc 1:1'' - для ext2.
  
Unmount both the rootfs partition and the kernel partition and make sure all remaining buffers are written to it:
+
Отмонтируйте оба раздела, корневой файловой системы и ядра, убедившись, что все оставшиеся буферы синхронизированы с памятью:
  
 
  umount /mnt/moko
 
  umount /mnt/moko
Line 307: Line 307:
  
 
[[Category:Flashing Openmoko]]
 
[[Category:Flashing Openmoko]]
[[Category:Advanced End User]]
+
[[Category:MicroSD]]
 
[[Category:System Developers/ru]]
 
[[Category:System Developers/ru]]

Latest revision as of 10:33, 19 July 2009

Эта страница рассказывает как загружаться FreeRunner с карты (micro-)SD вместо встроенной NAND флеш памяти. Карта SD разделяет шину с GPU, поэтому, возможно, не будет работать также хорошо, но имеется такая возможность.

WARNING: Загрузка с SDHC может иметь некоторые проблемы (смотри ниже).


Contents

[edit] Загрузка с SDHC / проблемы с приостановкой работы

Вначале предупреждение. Очень старый баг, который сущестрвует в ядре Linux, наличие тенденции к съедению таблицы разделов на картах SD большой емкости, когда система приостанавливает работу. Это карточка #1802. Посмотрите эту нить для прояснения ситуации с удалением таблицы разделов и, возможно, других проблем, связанных с использованием карт SD большой емкости. В качестве безопасности запишите параметры таблицы карты на бумагу чтобы в случае повреждения пересоздать как было(данные не портятся).

[edit] Как это работает

В Neo, u-boot выполняет роль загрузчика 'grub' как на PC. U-boot загружает образ ядра в память и передает параметры ядру. Параметры показывают где расположены остальные части системы и другие параметры ядра.

При загрузке ядра происходит инициализация аппаратных средств, а затем монтируется корневая файловая система. Ядро запускает процесс "/sbin/init", который управляет оставшейся частью последовательности начальной загрузки (например отображением заставки или индикатора прогресса).

Эта последовательность та же самая, не зависимо от того, загружается ли устройство со встроенной памяти или с карты SD. Различия кроются лишь в том, как загружено ядро и какое устройство смонтировано в качестве корневой файловой системы.

Следующие разделы освещают дополнительные детали.

[edit] Вход в меню

U-boot меню определены переменными с именами "menu_X" (где X является числом). Значение переменных -строка "<метка>:<команды>", где <метка> это текст который показан на экране, а <команды> из списка команд u-boot (разделены символом ';' ) для выполнения когда данное меню будет выделено. Когда вводятся строки команд, символы ';' и '$' должны быть экранированы обратным слешем '\' ("\;" и "\$").

[edit] Загрузка ядра

Для загрузки ядра с карты SD должны быть использованы две команды u-boot. Первая - "mmcinit", которая заставит u-boot обнаружить карту. Следующая команда для загрузки файла в память - либо "fatload", либо "ext2load", в зависимости от того, находится ядро на файловой системе FAT или ext2/ext3.

Синтаксис команд такой:

fatload mmc 1:<p> 0x32000000 <filepath>
ext2load mmc 1:<p> 0x32000000 <filepath>

здесь <p> - номер раздела, и <filepath> - путь к файлу, который должен быть загружен.

NOTE: Команда "ext2load" не работает в u-boot раньше чем "20080723", включая тот, что идет с первой партией FreeRunner-ов, затронутых ошибкой #799. Если Вы обновите свой u-Boot и пакеты ядра, вы можете использовать прямую загрузку ext2/3 все в одном разделе.


WARNING: Будьте осторожны, когда обновляете u-boot на Neo1973, поскольку есть риск bricking-а устройства (если у вас нет отладочной платы). Это не проблема для FreeRunner, имеющего защищенную копию u-boot в NOR памяти.


NOTE: U-Boot поддерживает протокол SDHC только на FreeRunner: на Neo1973, u-boot не будет иметь доступа к картам SDHC (4G или больше). Ядро имеет поддержку SDHC на Neo1973, что дает возможность иметь корневую файловую систему на SDHC ядро на NAND чтобы работать таким образом.


[edit] Параметры корневой файловой системы

Содержимое переменной среды "bootargs" отправляется ядру. Bootargs это список разделенных пробелами объявлений "имя=значение". Элементы, относящиеся к SD-загрузке - "root", "rootfstype", и "rootdelay".

Например, следующие параметры заставят ядро смонтировать третий раздел карты SD как файлоую систему ext3:

 root=/dev/mmcblk0p3 rootfstype=ext3 rootdelay=5 

Параметр "rootdelay" позволяет установить время, отводимое на инициализацию карты, перед тем, как будет произведено обращение к ней.

Заметьте, что у ядра должна быть встроенная поддержка (то есть не модуль) файловой системы, определенной в "rootfstype". По умолчанию ядро Openmoko настроено как 2008-07-17, имеет поддержку как ext2, так и ext3. Вы можете проверить доступные файловые системы командой:

less /proc/filesystems

Не возможн использовать VFAT в качестве корневой файловой системы.

[edit] ext2 в сравнении ext3

Мнения о том, что лучше использовать ext2 или ext3 для корневой файловой системы, разделяются. Ext3 вообще лучший выбор, поскольку это журналируемая файловая система, так что не требует длительной 'fsck' (проверки файловой системы) после некорректного отключения. Однако, если используется на flash устройстве, которое не поддерживает выравнивание изнашивания тогда, ext3 может вызвать преждевременное изнашивание блоков карты, в которых хранится журнал. Предполагается, что карты SD поддерживают выравнивание изнашивания, но этого нельзя гарантировать для всех поставщиков.

[edit] Получение tar-архива корневой файловой системы

Существует два пути получения образа корневой ФС в tar-архиве. Вы можете создать его сами с помощью OpenEmbedded дистрибутива. Или загрузить его с openmoko buildhost.

[edit] Вариант 1: Скачать rootfs/kernel tar с Openmoko

Выберите rootfs/kernel комбинацию из Последних Образов.

[edit] Вариант 2: Создание tar-архива дистрибутива с помощью OpenEmbedded

Другая возможность получить tar архив вашей корневой файловой системы состоит в том, чтобы создать его самостоятельно с помощью среды OpenEmbedded.

В случае с OM-2007.2 вам потребуется добавить "tar" к типам образов в local.conf:

IMAGE_FSTYPES = "jffs2 tar"

После чего создать новый образ так:

bitbake openmoko-devel-image

или, если используется MokoMakefile:

make openmoko-devel-image

Когда процесс завершен, будет создан файл Openmoko-....tar, который и будет вашим только что созданным архивом корневой файловой системы.

[edit] Вариант 3 : Преобразование образа jff2 в tar архив

Посмотрите Корневой образ пространства пользователя для более детального описания того, как получить доступ к содержимому образа jffs2.

[edit] Подготовка SD карты

[edit] Разделы на SD карте

u-boot pre-2008-07-23 может грузить систему только с файловой системой FAT; если вы обновили u-boot, вы можеет грузиться с FAT или ext2. Этот пример показывает примерное использование утилиты fdisk для создания разделов на карте. Не стесняйтесь использовать вашу любимую утилиту разбиения для решения этой задачи.

fdisk /dev/mmcblk0

Примечание: Файл устройства может отличаться в вашей системе. Если вы не уверены в этом, проверьте лог сообщений ядра вызывом dmesg для поиска нужного устройства.

мы создадим раздел 8 мегабайт для ядра и остальное пространство для всего остального.

  Command (m for help): d
  Selected partition 1
  Command (m for help): n
  Command action
     e   extended
     p   primary partition (1-4)
  p
  Partition number (1-4): 1
  First cylinder (1-983, default 1):
  Using default value 1
  Last cylinder or +size or +sizeM or +sizeK (1-983, default 983): +8M
  Command (m for help): n
  Command action
     e   extended
     p   primary partition (1-4)
  p
  Partition number (1-4): 2
  First cylinder (18-983, default 18):
  Using default value 18
  Last cylinder or +size or +sizeM or +sizeK (18-983, default 983):
  Using default value 983
  Command (m for help): w
  The partition table has been altered!
  Calling ioctl() to re-read partition table.
  Syncing disks.

Вероятно, необходимо изменить тип первого раздела на также FAT 16?

если это завершится с чем-то вроде:

  Calling ioctl() to re-read partition table
  fdisk: WARNING: rereading partition table failed, kernel still uses old table:   Device or resource busy

выполните:

  umount /dev/mmcblk0p1

в другой оболочке и попробуйте снова.

[edit] Форматирование SD карты

Создаем на первом разделе FAT файловую систему:

mkfs.vfat /dev/mmcblk0p1
NOTE: Если у вас нет mkfs.vfat вам потребуется найти и установить пакет "dosfstools". Этот пакет, кажется, не находится в официальных поставках, но может быть загружен с http://members.shaw.ca/mmontour/neo/dosfstools_2.11-r0_armv4t.ipk



Вторую часть карты делаем как ext3 (для работы с ext2 надо создать ядро с корректной конфигурацией):

mkfs.ext3 /dev/mmcblk0p2

[edit] Перенос на карту SD

Ваша карточка готова к загрузки на нее ядра и файловой системы.

Смонтируйте куда-нибудь второй раздел вашей SD карты и поместите на него образ корнеой файловой системы:

mount /dev/mmcblk0p2 /mnt/moko
tar -C /mnt/moko/ -xzvf openmoko-devel-image-fic-gta01-20070313022035.rootfs.tar.gz

Важно: Как обычно подразумевается, что название устройства, так же как и название образа rootfs должны быть заменены на ваше устройство и имя вашего файла rootfs.

Важно: Если вы используете автоматическое монтирование в вашей операционной системе, неплохо бы позаботиться о некоторых вещах. Некоторые хосты монтируют сменные устройства с опцией "nodev" по умолчанию для безопасности. Если в образе, который вы монтируете, будет непустой каталог /dev, то узлы не смогут проинициализировать это устройство. Если используется автоматическое монтирование SD на вашем хосте, убедитесь, что не используется никаких опций, которые могут вызвать проблемы, простым выполнением команды "mount", которая вернет список точек смонтированных устройств.

Следующим шагом смонтируйте первый раздел SD карты и установите на него ядро:

mount /dev/mmcblk0p1 /mnt/mokokernel
cp uImage-fic-gta01-latest.bin /mnt/mokokernel/uImage.bin

Убедитесь, что ваше ядро называется uImage.bin. Если u-boot не находит образ ядра во время загрузки, зарегистрируйтесь в bootloader с помощью cu, смонтируйте раздел при помощи mmcinit и проверьте присутствие, а также имя ядра командой fatls mmc 1:1 для системы FAT, или ext2ls mmc 1:1 - для ext2.

Отмонтируйте оба раздела, корневой файловой системы и ядра, убедившись, что все оставшиеся буферы синхронизированы с памятью:

umount /mnt/moko
umount /mnt/mokokernel
sync

[edit] Add uboot boot entry

Depending on the revision of the phone and the partition type (ext2/ext3) you are using, it might be necessary to add an entry to the bootmenu to be able to boot the system off your SD card. If you are using a FreeRunner and have created an FAT kernel/ext2 rootfs partition you should be able to boot from the card right out of the box, because a boot menu entry for this should already exist in the NOR/NAND boot menu. In any other case you should at least make sure the needed entry exists in your menu before proceeding. You will need to enter the uboot shell of the NAND boot menu for this. A description on how to connect to the uboot loader shell can be found in this article: Uboot#Bootloader_prompt. Details on howto get into the NAND boot menu can be found here.

After you read these two references you should be connected to your NAND uboot shell right now. The first thing to do is to set the boot menu timeout to a really high value. Unfortunately if you don't do this, the boot loader will continue booting after the default timeout (60 seconds) even if you are connected to the uboot shell. Just enter the following command to the menu prompt:

setenv boot_menu_timeout 99999

This will set the timeout to 99999 seconds which should definitely enough time for us finish whatever work we want accomplish in the boot loader shell.

Now we will make sure a appropriate menu item for booting from sd exists, or create it otherwise. You can print the defined boot loader environment by issuing the command:

printenv

If it shows a line beginning with menu_ followed by the commands which are just to follow in this guide, you do not need to create a new menu entry. In any other case please proceed with the following.

Please make sure you are using the correct configuration based on the decisions you made earlier. For more information on the uboot prompt, see

help 
help <command>

and Bootloader and Bootloader commands.

NOTE: The backslashes (\) are important for uboot to set the command as new environment variable (menu_9) instead of just executing them as soon as enter is pressed.


NOTE: Copy and paste may not work depending on your terminal emulator. Commi just works or you can use neocon terminal emulator and add a per-character delay. Otherwise, you will have to type in the commandline manually.


It is important to distinguish between FAT or ext2 kernel partitions and ext2 or ext3 root partitions at this point.

Please watch partition numbers in the following commands. In particular, you may need to change root=/dev/mmcblk0p# and fatload mmc # or ext2load mmc # depending on which partition number your root and kernel, respectively, are located. Number starts from unity.

Boot entry for FAT kernel+ext3 rootfs partitions:

setenv menu_9 Boot from microSD (FAT+ext3): setenv bootargs \${bootargs_base} rootfstype=ext3 root=/dev/mmcblk0p2 rootdelay=5 \${mtdparts} ro\; mmcinit\; fatload mmc 1 0x32000000 \${sd_image_name}\; bootm 0x32000000

Boot entry for FAT kernel+ext2 rootfs partitions:

setenv menu_9 Boot from microSD (FAT+ext2): setenv bootargs \${bootargs_base} rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 \${mtdparts} ro\; mmcinit\; fatload mmc 1 0x32000000 \${sd_image_name}\; bootm 0x32000000

or : with additional 'init=/sbin/init' kernel parameter (may be needed for some images) :

setenv menu_9 Boot 200808 from microSD (FAT+ext2): setenv bootargs \${bootargs_base} rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 \${mtdparts} init=/sbin/init ro\; mmcinit\; fatload mmc 1 0x32000000 \${sd_image_name}\; bootm 0x32000000

Boot entry for ext2 kernel+ext2 rootfs partitions: (requires newer u-boot)

setenv menu_2 Boot from microSD part2 (ext2+ext2): setenv bootargs \${bootargs_base} rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 \${mtdparts} ro\; mmcinit\; ext2load mmc 1 0x32000000 \${sd_image_name}\; bootm 0x32000000

Boot entry for kernel and rootfs on same ext2 partition (tested with Qtopia/requires newer u-boot)

setenv menu_3 QTopia: setenv bootargs \${bootargs_base} rootfstype=ext2 root=/dev/mmcblk0p1 rootdelay=5 \${mtdparts} ro\; mmcinit\; ext2load mmc 1:1 0x32000000 \${sd_image_name}\; bootm 0x32000000

You are nearly done. Just issue a

printenv

and verify that your newly created entry is correctly displayed (This time the backslashes are not displayed anyone).

If everything looks fine enter

saveenv

into the prompt and press enter. The new configuration should now be saved to the NAND.

Shutdown your neo with the following command:

neo1973 power-off

After you restarted the Neo and got back to the NAND boot menu you should be able to select your newly created menu entry and successfully boot into the rootfs from your SD card.


See also Moving current system from flash to SD which shows how to move the running system currently running in flash to an SD card, in order to keep a backup system on SD on which to boot from.


[edit] Приложение

[edit] Загрузка с SDHC

NOTE: the following text was written for the Neo1973. SDHC and SD should both work in a FreeRunner if you have u-boot from 2008-07-23 or later.


As SDHC is not supported in older u-boot versions you can't use the Booting from SD guide. But there's a kind of workaround that is a good option to have at least your rootfs on the microSDHC:

First you can follow Step 1 to get an kernel-image with mmc- and ext2-support. But instead of copying the image to the rootfs you will have to flash it to the Neo's internal NAND-Flash (using Dfu-util). Now you can continue with Step 2 (like mentioned before you do not have to copy your uImage to the rootfs) and follow the instructions to Step 3. Instead of the setenv commands in Step 3 you have to enter the following:

GTA01Bv4 # setenv menu_5 Boot from SDHC: setenv  bootargs root=/dev/mmcblk0p1 console=tty0 rootdelay=5 neo1973-nand:0x00040000(u-boot),0x00004000(u-boot_env),0x00200000(kernel),0x000a0000(splash)\; nand read.e 0x32000000 kernel\; bootm 0x32000000
GTA01Bv4 # saveenv

And that's it! Now you can use the newly created menu option "Boot from SDHC" to boot the internal kernel, using the root-filesystem on the microSDHC.

[edit] Автозагрузка с SDHC

Maybe you want to Boot automatically from SDHC: Set a new Bootmenu Entry for booting from NAND first

GTA01Bv4 # setenv menu_6 Boot from NAND: setenv bootargs \${bootargs_base} \${mtdparts}\; nand read.e 0x32000000 kernel\; bootm 0x32000000
GTA01Bv4 # saveenv

then Power-off, and enter the Bootmenu to test the new Entry.If you can boot from NAND, shutdown, enter Boot menu, connect to bootloader and set the (auto)bootcmd for boot from SDHC:

GTA01Bv4 # setenv bootcmd setenv bootargs root=/dev/mmcblk0p1 rootdelay=10 console=tty0 neo1973-nand:0x00040000(u-boot),0x00004000(u-boot_env),0x00200000(kernel),0x000a0000(splash)\; nand read.e 0x32000000 kernel\; bootm 0x32000000 
GTA01Bv4 # saveenv

Now you boot from SDHC everytime you press the Power-Button or reboot and if you like to boot from NAND -just use the bootmenu.


[edit] Fixing udev automount

Udev automatically mounts the SD Card in /media/mmcblk0p1/ you can disable this with

echo /dev/mmcblk >> /etc/udev/mount.blacklist

[edit] Remarks on Kernel Parameters

[edit] Деталезация лога

Some people suggested adding:

loglevel=8

to the kernel command line. IF you also have "console=tty0" on your kernel commandline this makes the boot process extremely slow because the framebuffer (the neo display in text mode) has to print out tons of lines of debug messages like:

s3c2410-sdi s3c2410-sdi: ......
mmc0: ....
Personal tools

Эта страница рассказывает как загружаться FreeRunner с карты (micro-)SD вместо встроенной NAND флеш памяти. Карта SD разделяет шину с GPU, поэтому, возможно, не будет работать также хорошо, но имеется такая возможность.

WARNING: Загрузка с SDHC может иметь некоторые проблемы (смотри ниже).


Загрузка с SDHC / проблемы с приостановкой работы

Вначале предупреждение. Очень старый баг, который сущестрвует в ядре Linux, наличие тенденции к съедению таблицы разделов на картах SD большой емкости, когда система приостанавливает работу. Это карточка #1802. Посмотрите эту нить для прояснения ситуации с удалением таблицы разделов и, возможно, других проблем, связанных с использованием карт SD большой емкости. В качестве безопасности запишите параметры таблицы карты на бумагу чтобы в случае повреждения пересоздать как было(данные не портятся).

Как это работает

В Neo, u-boot выполняет роль загрузчика 'grub' как на PC. U-boot загружает образ ядра в память и передает параметры ядру. Параметры показывают где расположены остальные части системы и другие параметры ядра.

При загрузке ядра происходит инициализация аппаратных средств, а затем монтируется корневая файловая система. Ядро запускает процесс "/sbin/init", который управляет оставшейся частью последовательности начальной загрузки (например отображением заставки или индикатора прогресса).

Эта последовательность та же самая, не зависимо от того, загружается ли устройство со встроенной памяти или с карты SD. Различия кроются лишь в том, как загружено ядро и какое устройство смонтировано в качестве корневой файловой системы.

Следующие разделы освещают дополнительные детали.

Вход в меню

U-boot меню определены переменными с именами "menu_X" (где X является числом). Значение переменных -строка "<метка>:<команды>", где <метка> это текст который показан на экране, а <команды> из списка команд u-boot (разделены символом ';' ) для выполнения когда данное меню будет выделено. Когда вводятся строки команд, символы ';' и '$' должны быть экранированы обратным слешем '\' ("\;" и "\$").

Загрузка ядра

Для загрузки ядра с карты SD должны быть использованы две команды u-boot. Первая - "mmcinit", которая заставит u-boot обнаружить карту. Следующая команда для загрузки файла в память - либо "fatload", либо "ext2load", в зависимости от того, находится ядро на файловой системе FAT или ext2/ext3.

Синтаксис команд такой:

fatload mmc 1:<p> 0x32000000 <filepath>
ext2load mmc 1:<p> 0x32000000 <filepath>

здесь <p> - номер раздела, и <filepath> - путь к файлу, который должен быть загружен.

NOTE: Команда "ext2load" не работает в u-boot раньше чем "20080723", включая тот, что идет с первой партией FreeRunner-ов, затронутых ошибкой #799. Если Вы обновите свой u-Boot и пакеты ядра, вы можете использовать прямую загрузку ext2/3 все в одном разделе.


WARNING: Будьте осторожны, когда обновляете u-boot на Neo1973, поскольку есть риск bricking-а устройства (если у вас нет отладочной платы). Это не проблема для FreeRunner, имеющего защищенную копию u-boot в NOR памяти.


NOTE: U-Boot поддерживает протокол SDHC только на FreeRunner: на Neo1973, u-boot не будет иметь доступа к картам SDHC (4G или больше). Ядро имеет поддержку SDHC на Neo1973, что дает возможность иметь корневую файловую систему на SDHC ядро на NAND чтобы работать таким образом.


Параметры корневой файловой системы

The contents of the "bootargs" environment variable are passed to the kernel. Bootargs is a space-delimited list of "name=value" definitions. The items relevant to SD-booting are "root", "rootfstype", and "rootdelay".

For example, the following parameters would tell the kernel to mount the third partition of the SD-card as an ext3 filesystem:

 root=/dev/mmcblk0p3 rootfstype=ext3 rootdelay=5 

The "rootdelay" parameter allows time for the card to be properly initialized before it is accessed.

Note that the kernel must have built-in support (i.e. not a module) for the filesystem specified in "rootfstype". The default Openmoko kernel configs as of 2008-07-17 have built-in support for both ext2 and ext3. You can check the available filesystems with the Linux command

less /proc/filesystems

It is not possible to use VFAT for the root filesystem.

ext2 в сравнении ext3

Opinion is divided on whether it is better to use ext2 or ext3 for the root filesystem. Ext3 in general is a superior choice, because it is a journalled filesystem and so does not require a long 'fsck' (file system check) after an unclean shutdown. However, if used on a flash device that does not support wear-leveling then ext3 may cause premature wear on the blocks of the card where the journal is stored. SD cards are supposed to support wear leveling, but this can not be guaranteed for all vendors.

Получение tar-архива корневой файловой системы

Существует два пути получения образа корневой ФС в tar-архиве. Вы можете создать его сами с помощью OpenEmbedded дистрибутива. Или загрузить его с openmoko buildhost.

Вариант 1: Скачать rootfs/kernel tar с Openmoko

Выберите rootfs/kernel комбинацию из Последних Образов.

Вариант 2: Создание tar-архива дистрибутива с помощью OpenEmbedded

Другая возможность получить tar архив вашей корневой файловой системы состоит в том, чтобы создать его самостоятельно с помощью среды OpenEmbedded.

В случае с OM-2007.2 вам потребуется добавить "tar" к типам образов в local.conf:

IMAGE_FSTYPES = "jffs2 tar"

После чего создать новый образ так:

bitbake openmoko-devel-image

или, если используется MokoMakefile:

make openmoko-devel-image

Когда процесс завершен, будет создан файл Openmoko-....tar, который и будет вашим только что созданным архивом корневой файловой системы.

Вариант 3 : Преобразование образа jff2 в tar архив

Посмотрите Корневой образ пространства пользователя для более детального описания того, как получить доступ к содержимому образа jffs2.

Подготовка SD карты

Разделы на SD карте

u-boot pre-2008-07-23 может грузить систему только с файловой системой FAT; если вы обновили u-boot, вы можеет грузиться с FAT или ext2. Этот пример показывает примерное использование утилиты fdisk для создания разделов на карте. Feel free to use the partitioning utility of your liking for this task.

fdisk /dev/mmcblk0

Примечание: The device file might differ on your system. If you are not sure about it, you may check your kernel message log by calling dmesg to find the correct device.

мы создадим раздел 8 мегабайт для ядра и остальнео пространство для всего остального.

  Command (m for help): d
  Selected partition 1
  Command (m for help): n
  Command action
     e   extended
     p   primary partition (1-4)
  p
  Partition number (1-4): 1
  First cylinder (1-983, default 1):
  Using default value 1
  Last cylinder or +size or +sizeM or +sizeK (1-983, default 983): +8M
  Command (m for help): n
  Command action
     e   extended
     p   primary partition (1-4)
  p
  Partition number (1-4): 2
  First cylinder (18-983, default 18):
  Using default value 18
  Last cylinder or +size or +sizeM or +sizeK (18-983, default 983):
  Using default value 983
  Command (m for help): w
  The partition table has been altered!
  Calling ioctl() to re-read partition table.
  Syncing disks.

Should probably need to change type of first partition to FAT 16 too ?

if it exits with something like

  Calling ioctl() to re-read partition table
  fdisk: WARNING: rereading partition table failed, kernel still uses old table:   Device or resource busy

do

  umount /dev/mmcblk0p1

on another shell and try again.

Форматирование SD карты

Создаем на первом разделе FAT файловую систему:

mkfs.vfat /dev/mmcblk0p1
NOTE: if you do not have mkfs.vfat you must find and install the "dosfstools" package. This package does not seem to be in the official feeds, but an unofficial build may be downloaded from http://members.shaw.ca/mmontour/neo/dosfstools_2.11-r0_armv4t.ipk



Вторую часть карты делаем как ext3 (для работы с ext2 надо создать ядро с корректной конфигурацией):

mkfs.ext3 /dev/mmcblk0p2

Перенос на карту SD

Ваша карточка готова к загрузки на нее ядра и файловой системы.

Mount the second partition of your SD card somewhere and put the image on it:

mount /dev/mmcblk0p2 /mnt/moko
tar -C /mnt/moko/ -xzvf openmoko-devel-image-fic-gta01-20070313022035.rootfs.tar.gz

Note: As always in this guide the device name as well as the rootfs name needs to be adjusted to your device and filename structure

Note: There's a nice gotcha to take care about if you use your host OS automount. Some hosts mount these removable devices with "nodev" option by default for security. If the image you are unpacking has a populated /dev directory, the nodes will fail to create as devices then. If automounting the SD on your host, confirm there are no unexpected mount options by using "mount" command alone to list the mounts.

The next step is to mount the first partition of the sd card and install the kernel on it.

mount /dev/mmcblk0p1 /mnt/mokokernel
cp uImage-fic-gta01-latest.bin /mnt/mokokernel/uImage.bin

Make sure your kernel is called uImage.bin. If the u-boot doesn't find the kernel image during boot, log into the bootloader with cu, mount the partition with mmcinit and check the presence and the name of the kernel image with fatls mmc 1:1 for FAT filesystem or ext2ls mmc 1:1 for ext2 filesystem.

Unmount both the rootfs partition and the kernel partition and make sure all remaining buffers are written to it:

umount /mnt/moko
umount /mnt/mokokernel
sync

Add uboot boot entry

Depending on the revision of the phone and the partition type (ext2/ext3) you are using, it might be necessary to add an entry to the bootmenu to be able to boot the system off your SD card. If you are using a FreeRunner and have created an FAT kernel/ext2 rootfs partition you should be able to boot from the card right out of the box, because a boot menu entry for this should already exist in the NOR/NAND boot menu. In any other case you should at least make sure the needed entry exists in your menu before proceeding. You will need to enter the uboot shell of the NAND boot menu for this. A description on how to connect to the uboot loader shell can be found in this article: Uboot#Bootloader_prompt. Details on howto get into the NAND boot menu can be found here.

After you read these two references you should be connected to your NAND uboot shell right now. The first thing to do is to set the boot menu timeout to a really high value. Unfortunately if you don't do this, the boot loader will continue booting after the default timeout (60 seconds) even if you are connected to the uboot shell. Just enter the following command to the menu prompt:

setenv boot_menu_timeout 99999

This will set the timeout to 99999 seconds which should definitely enough time for us finish whatever work we want accomplish in the boot loader shell.

Now we will make sure a appropriate menu item for booting from sd exists, or create it otherwise. You can print the defined boot loader environment by issuing the command:

printenv

If it shows a line beginning with menu_ followed by the commands which are just to follow in this guide, you do not need to create a new menu entry. In any other case please proceed with the following.

Please make sure you are using the correct configuration based on the decisions you made earlier. For more information on the uboot prompt, see

help 
help <command>

and Bootloader and Bootloader commands.

NOTE: The backslashes (\) are important for uboot to set the command as new environment variable (menu_9) instead of just executing them as soon as enter is pressed.


NOTE: Copy and paste may not work depending on your terminal emulator. Commi just works or you can use neocon terminal emulator and add a per-character delay. Otherwise, you will have to type in the commandline manually.


It is important to distinguish between FAT or ext2 kernel partitions and ext2 or ext3 root partitions at this point.

Please watch partition numbers in the following commands. In particular, you may need to change root=/dev/mmcblk0p# and fatload mmc # or ext2load mmc # depending on which partition number your root and kernel, respectively, are located. Number starts from unity.

Boot entry for FAT kernel+ext3 rootfs partitions:

setenv menu_9 Boot from microSD (FAT+ext3): setenv bootargs \${bootargs_base} rootfstype=ext3 root=/dev/mmcblk0p2 rootdelay=5 \${mtdparts} ro\; mmcinit\; fatload mmc 1 0x32000000 \${sd_image_name}\; bootm 0x32000000

Boot entry for FAT kernel+ext2 rootfs partitions:

setenv menu_9 Boot from microSD (FAT+ext2): setenv bootargs \${bootargs_base} rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 \${mtdparts} ro\; mmcinit\; fatload mmc 1 0x32000000 \${sd_image_name}\; bootm 0x32000000

or : with additional 'init=/sbin/init' kernel parameter (may be needed for some images) :

setenv menu_9 Boot 200808 from microSD (FAT+ext2): setenv bootargs \${bootargs_base} rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 \${mtdparts} init=/sbin/init ro\; mmcinit\; fatload mmc 1 0x32000000 \${sd_image_name}\; bootm 0x32000000

Boot entry for ext2 kernel+ext2 rootfs partitions: (requires newer u-boot)

setenv menu_2 Boot from microSD part2 (ext2+ext2): setenv bootargs \${bootargs_base} rootfstype=ext2 root=/dev/mmcblk0p2 rootdelay=5 \${mtdparts} ro\; mmcinit\; ext2load mmc 1 0x32000000 \${sd_image_name}\; bootm 0x32000000

Boot entry for kernel and rootfs on same ext2 partition (tested with Qtopia/requires newer u-boot)

setenv menu_3 QTopia: setenv bootargs \${bootargs_base} rootfstype=ext2 root=/dev/mmcblk0p1 rootdelay=5 \${mtdparts} ro\; mmcinit\; ext2load mmc 1:1 0x32000000 \${sd_image_name}\; bootm 0x32000000

You are nearly done. Just issue a

printenv

and verify that your newly created entry is correctly displayed (This time the backslashes are not displayed anyone).

If everything looks fine enter

saveenv

into the prompt and press enter. The new configuration should now be saved to the NAND.

Shutdown your neo with the following command:

neo1973 power-off

After you restarted the Neo and got back to the NAND boot menu you should be able to select your newly created menu entry and successfully boot into the rootfs from your SD card.


See also Moving current system from flash to SD which shows how to move the running system currently running in flash to an SD card, in order to keep a backup system on SD on which to boot from.


Приложение

Загрузка с SDHC

NOTE: the following text was written for the Neo1973. SDHC and SD should both work in a FreeRunner if you have u-boot from 2008-07-23 or later.


As SDHC is not supported in older u-boot versions you can't use the Booting from SD guide. But there's a kind of workaround that is a good option to have at least your rootfs on the microSDHC:

First you can follow Step 1 to get an kernel-image with mmc- and ext2-support. But instead of copying the image to the rootfs you will have to flash it to the Neo's internal NAND-Flash (using Dfu-util). Now you can continue with Step 2 (like mentioned before you do not have to copy your uImage to the rootfs) and follow the instructions to Step 3. Instead of the setenv commands in Step 3 you have to enter the following:

GTA01Bv4 # setenv menu_5 Boot from SDHC: setenv  bootargs root=/dev/mmcblk0p1 console=tty0 rootdelay=5 neo1973-nand:0x00040000(u-boot),0x00004000(u-boot_env),0x00200000(kernel),0x000a0000(splash)\; nand read.e 0x32000000 kernel\; bootm 0x32000000
GTA01Bv4 # saveenv

And that's it! Now you can use the newly created menu option "Boot from SDHC" to boot the internal kernel, using the root-filesystem on the microSDHC.

Автозагрузка с SDHC

Maybe you want to Boot automatically from SDHC: Set a new Bootmenu Entry for booting from NAND first

GTA01Bv4 # setenv menu_6 Boot from NAND: setenv bootargs \${bootargs_base} \${mtdparts}\; nand read.e 0x32000000 kernel\; bootm 0x32000000
GTA01Bv4 # saveenv

then Power-off, and enter the Bootmenu to test the new Entry.If you can boot from NAND, shutdown, enter Boot menu, connect to bootloader and set the (auto)bootcmd for boot from SDHC:

GTA01Bv4 # setenv bootcmd setenv bootargs root=/dev/mmcblk0p1 rootdelay=10 console=tty0 neo1973-nand:0x00040000(u-boot),0x00004000(u-boot_env),0x00200000(kernel),0x000a0000(splash)\; nand read.e 0x32000000 kernel\; bootm 0x32000000 
GTA01Bv4 # saveenv

Now you boot from SDHC everytime you press the Power-Button or reboot and if you like to boot from NAND -just use the bootmenu.


Fixing udev automount

Udev automatically mounts the SD Card in /media/mmcblk0p1/ you can disable this with

echo /dev/mmcblk >> /etc/udev/mount.blacklist

Remarks on Kernel Parameters

Деталезация лога

Some people suggested adding:

loglevel=8

to the kernel command line. IF you also have "console=tty0" on your kernel commandline this makes the boot process extremely slow because the framebuffer (the neo display in text mode) has to print out tons of lines of debug messages like:

s3c2410-sdi s3c2410-sdi: ......
mmc0: ....