diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..b3bf734 --- /dev/null +++ b/README.en.md @@ -0,0 +1,329 @@ +# Amlogic Boot Scripts for Armbian + +**Language / Idioma:** [🟢 English](README.en.md) | [Português](README.md) + +## Table of Contents +- [Overview](#overview) +- [Setup](#setup) +- [Supported Devices](#supported-devices) +- [Advanced Troubleshooting — Bootloader Modification](#advanced-troubleshooting--bootloader-modification) +- [How It Works Internally](#how-it-works-internally) + +--- + +## Overview + +Armbian images for Amlogic TV Boxes normally rely on secondary u-boot blobs to boot the mainline kernel. In practice, these are unnecessary: the factory u-boot that came with your box is already capable of doing this on its own. All it takes are a few modifications to the Armbian boot scripts. + +> **Prerequisite:** the vendor u-boot must be running on eMMC. If your box was reflashed with a different bootloader, restore the stock Android image using the [Amlogic USB Burning Tool](https://androidmtk.com/download-amlogic-usb-burning-tool) before continuing. + +--- + +## Setup + +### Step 1 — Download the Armbian image + +Download the latest Armbian for s9xxx-box. We recommend [bookworm minimal](https://dl.armbian.com/aml-s9xx-box/Bookworm_current_minimal). + +--- + +### Step 2 — Prepare the installation media + +Flash the image to the USB drive using **[balenaEtcher](https://etcher.balena.io/)** — the simplest option — or via command line: + +```bash +sudo dd if=Armbian_*.img of=/dev/sdX bs=4M status=progress conv=fsync +``` + +> ⚠️ Replace `/dev/sdX` with your USB drive. Use `lsblk` or `fdisk -l` to confirm the correct device. With `dd`, writing to the wrong device will erase its data without any confirmation prompt. + +Mount the FAT partition of the USB drive and replace the boot scripts with the modified ones, overwriting the existing files: + +- **[aml_autoscript](https://github.com/projetotvbox/amlogic-bootscripts-Armbian/blob/main/aml_autoscript)** +- **[s905_autoscript](https://github.com/projetotvbox/amlogic-bootscripts-Armbian/blob/main/s905_autoscript)** +- **[emmc_autoscript](https://github.com/projetotvbox/amlogic-bootscripts-Armbian/blob/main/emmc_autoscript)** +- **[gxl-fixup.scr](https://github.com/projetotvbox/amlogic-bootscripts-Armbian/blob/main/gxl-fixup.scr)** *(only if your SoC is GXBB/S905 or GXL/S905X/W/L)* + +> **Compiling your own images or preparing multiple USB drives?** You can modify the `.img` file directly before flashing, avoiding the need to edit each drive individually. Mount the image with `losetup`: +> +> ```bash +> sudo losetup -fP Armbian_*.img +> lsblk | grep loop # identify the device and the FAT partition (usually loopXp1) +> sudo mount /dev/loop0p1 /mnt/armbian_boot +> ``` +> +> Copy the scripts normally to `/mnt/armbian_boot/` and **continue through the next steps as usual**, editing `armbianEnv.txt` and other parameters with the image still mounted. Only after completing all configurations, unmount and flash: +> +> ```bash +> sudo umount /mnt/armbian_boot +> sudo losetup -d /dev/loop0 +> sudo dd if=Armbian_*.img of=/dev/sdX bs=4M status=progress conv=fsync +> ``` + +--- + +### Step 3 — Configure `armbianEnv.txt` + +The `armbianEnv.txt` file controls essential boot parameters. Before editing, back up the original: + +```bash +sudo cp /mnt/your_usb/armbianEnv.txt /mnt/your_usb/armbianEnv.txt.bak +``` + +Edit with nano or your preferred editor: + +```bash +sudo nano /mnt/your_usb/armbianEnv.txt +``` + +**Reference content:** + +```bash +extraargs=earlycon=meson,0xfe07a000 console=ttyS0,921600n8 rootflags=data=writeback rw no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 watchdog.stop_on_reboot=0 pd_ignore_unused clk_ignore_unused rootdelay=5 +bootlogo=false +verbosity=7 +usbstoragequirks=0x2537:0x1066:u,0x2537:0x1068:u +console=both + +# DTB file for this tvbox +# fdtfile=amlogic/meson-gxl-s905x-nexbox-a95x.dtb +fdtfile=amlogic/meson-sm1-x96-air-gbit.dtb + +# set this to the UUID of the root partition (value can be found with blkid or in fstab) +#rootdev=UUID=92139c84-3871-41d7-a3f2-e8a943cbfa87 +# or use the default partition label: +#rootdev=LABEL=ROOTFS + +# Enable ONLY for gxbb (S905) / gxl (S905X/L/W) to create fake u-boot header +#soc_fixup=gxl- +``` + +> ⚠️ **This file is a starting point, not a universal configuration.** +> +> The content above works for many devices, but may not work for yours. Different TV boxes, SoCs, and Armbian versions may require different parameters — especially the `extraargs` line. +> +> **Before replacing the file**, compare it against the original `armbianEnv.txt` from the Armbian image and merge carefully. Parameters present in the original and absent here may be required for your hardware. When in doubt, start from the original and apply only the changes you understand. If the system fails to boot, restoring the backup (`armbianEnv.txt.bak`) is the first step to diagnose the issue. + +--- + +### Step 4 — Set the correct `fdtfile` + +Change the `fdtfile` line to the DTB that matches your box. Available files can be found in `/boot/dtb/amlogic/` inside the Armbian image. + +--- + +### Step 5 — Set `rootdev` *(optional since version 3)* + +By default, `rootdev` is commented out and the system uses the `ROOTFS` label automatically. If you need to specify it manually: + +| Media | Value | +|-------|-------| +| USB flash drive | `/dev/sda2` | +| SD card | `/dev/mmcblk0p2` | +| By UUID *(recommended)* | `UUID=` | +| By label | `LABEL=ROOTFS` | + +**How to get the root partition UUID:** + +With the system running from the USB drive or SD card, run: + +```bash +blkid +``` + +Expected output: + +``` +/dev/sda2: UUID="92139c84-3871-41d7-a3f2-e8a943cbfa87" TYPE="ext4" PARTUUID="..." +``` + +Copy the `UUID=` value of the root partition (usually `sda2` or `mmcblk0p2`) and paste it into `armbianEnv.txt`. The UUID can also be found in `/etc/fstab` or in the original `armbianEnv.txt` from the image, if already filled in. + +--- + +### Step 6 — Enable SoC fixup *(GXBB/GXL only)* + +If your box uses a GXBB (S905) or GXL (S905X/W/L) SoC, uncomment the line: + +``` +soc_fixup=gxl- +``` + +--- + +### Step 7 — Boot from USB + +1. Power off the box. +2. Insert the USB drive. +3. Press and **hold** the reset button. +4. Power on the box and keep holding for approximately **7 seconds**. +5. If everything is correct, Armbian will boot with a mainline kernel — without any secondary u-boot blobs. + +--- + +## Supported Devices + +**✅ Fully Tested & Working:** +- S905X, S905W, S912, S905X2, S922X, S905X3, S905X4 (HTV H8) + +**⚠️ Partial Support:** +- S905: Boots only on first attempt (known limitation) + +**❓ Untested:** +- S905W2: Likely compatible but untested (not currently supported by Armbian kernel) + +All files and source files are available on [Github](https://github.com/projetotvbox/amlogic-bootscripts-Armbian). + +--- + +## Advanced Troubleshooting — Bootloader Modification + +> ⚠️ **This section is for cases where the scripts simply do not work.** If the main method worked, you do not need this. +> +> Some devices have factory bootloaders that do not support running external scripts by default. In those cases, it is possible to modify the bootloader variables directly via serial console to force that support. This is a low-level procedure with a real risk of bricking the device. **Proceed only if you know what you are doing.** + +### Prerequisites + +- **Functional ARM Linux system:** Armbian, Debian, or Ubuntu ARM running from USB/SD on the Amlogic device — required to access eMMC and the shell. +- **Serial TTL adapter (3.3V UART):** ⚠️ **Use 3.3V only. 5V will damage the device.** Requires soldering TX/RX/GND pads on the board. +- **Serial terminal software:** PuTTY, Minicom, or picocom. + +### 🔒 Back Up eMMC Before Anything Else + +```bash +# Compressed backup (a 16GB backup becomes 2-4GB) +sudo dd if=/dev/mmcblkX bs=1M status=progress | gzip -c > backup_emmc_full.img.gz + +# To restore: +# gunzip -c backup_emmc_full.img.gz | sudo dd of=/dev/mmcblkX bs=1M status=progress +``` + +### Checking Bootloader Support + +#### Step 1: Connect the serial cable +Solder TX, RX, and GND to the device's UART pads and connect to your PC. + +#### Step 2: Open the serial console + +```bash +ls -la /dev/ttyUSB* + +picocom -b 115200 /dev/ttyUSB0 +# or: +minicom -D /dev/ttyUSB0 -b 115200 +``` + +#### Step 3: Interrupt U-Boot +Power on the device and quickly press `Ctrl+C` or `Enter` to interrupt U-Boot before it boots. + +#### Step 4: Check bootloader variables + +```bash +printenv bootcmd +``` + +Expected output: +``` +bootcmd=run start_autoscript; run storeboot +``` + +Also check: +```bash +printenv start_usb_autoscript +printenv start_mmc_autoscript +printenv start_emmc_autoscript +``` + +> Variable names may differ slightly. Look for patterns like `start_*_autoscript`. + +### Modifying the Variables + +If the bootloader is writable, run in the U-Boot console: + +```bash +setenv start_autoscript 'if mmcinfo; then run start_mmc_autoscript; fi; if usb start; then run start_usb_autoscript; fi; run start_emmc_autoscript' +setenv start_emmc_autoscript 'if fatload mmc 1 1020000 emmc_autoscript; then setenv devtype "mmc"; setenv devnum 1; autoscr 1020000; fi;' +setenv start_mmc_autoscript 'if fatload mmc 0 1020000 s905_autoscript; then setenv devtype "mmc"; setenv devnum 0; autoscr 1020000; fi;' +setenv start_usb_autoscript 'for usbdev in 0 1 2 3; do if fatload usb ${usbdev} 1020000 s905_autoscript; then setenv devtype "usb"; setenv devnum 0; autoscr 1020000; fi; done' +setenv upgrade_step 2 +setenv bootdelay 1 +``` + +#### ⚠️ Setting `bootcmd` — Preserve the Original Command + +**Do not simply use `run start_autoscript; run storeboot`** without checking your original `bootcmd` first. A generic command may brick your device if the original was different. + +1. **Write down the original `bootcmd`:** + ```bash + printenv bootcmd + ``` + +2. **Set it while preserving the original:** + ```bash + setenv bootcmd 'run start_autoscript; [YOUR ORIGINAL BOOTCMD HERE]' + ``` + +**Real device examples:** + +```bash +# Example 1 — Generic Amlogic box (original: run storeboot) +setenv bootcmd 'run start_autoscript; run storeboot' + +# Example 2 — HTV H8 (original: run start_emmc_autoscript; run storeboot) +setenv bootcmd 'run start_autoscript; run start_emmc_autoscript; run storeboot' + +# Example 3 — Complex bootcmd +# Original: if test -n ${upgrade_step}; then echo BOOT_STEP equals $upgrade_step; setenv upgrade_step; fi; run storeboot +setenv bootcmd 'run start_autoscript; if test -n ${upgrade_step}; then echo BOOT_STEP equals $upgrade_step; setenv upgrade_step; fi; run storeboot' +``` + +#### Save and verify + +```bash +saveenv +reset +``` + +Interrupt U-Boot again and confirm: + +```bash +printenv bootcmd +``` + +- **Variables saved** → writable bootloader, modifications applied successfully. +- **Variables not saved** → read-only bootloader; this method cannot be applied. + +--- + +## How It Works Internally + +For those who want to understand what happens under the hood — the role of each file in the boot chain. + +### `aml_autoscript` — The Route Injector + +Runs **only once**, at the moment you force recovery mode (by holding the reset button while powering on). It rewrites the factory U-Boot environment variables via `saveenv`, establishing a new boot order: SD card → USB → eMMC, redirecting the flow to the scripts below. + +### `s905_autoscript` — The External Media Loader + +Runs every time the board powers on with a USB drive or SD card connected. It reads `armbianEnv.txt`, loads the Kernel, DTB, and Initrd into RAM, prepares the `bootargs`, and hands control to the Kernel to start the operating system. + +### `emmc_autoscript` — The Internal Storage Loader + +Functionally identical to the previous script, but triggered when no bootable USB drive or SD card is connected. It points to the physical address of eMMC memory (`devnum 1`) and mounts the root filesystem from the internal partition. + +### `gxl-fixup.scr` — The Fake Header Hack *(GXBB/GXL only)* + +The factory bootloaders of GXBB (S905) and GXL (S905X/W/L) families only accept kernels in the legacy `uImage` format (using `bootm`). Modern Armbian uses the `Image` format (using `booti`), which those bootloaders simply refuse. + +Instead of compiling legacy-format kernels, the script solves this at runtime: + +1. Replaces the standard boot routine (`cmd_do_boot`). +2. Uses `mw.l` to write directly into memory a **fake** legacy u-boot header at address `0x1ffffc0`, just before the Kernel. +3. Injects a valid CRC into the fake header (`cmd_hdr_crc`). +4. Fires `bootm` — the bootloader sees the fake header, believes it's dealing with a valid `uImage`, and boots the modern Linux kernel normally. + +> **Restriction:** the Kernel file cannot exceed **32MB** in size. + +This is why Step 6 instructs you to uncomment `soc_fixup=gxl-` for these SoCs: without this hack, the original bootloader would stall at boot. + +--- diff --git a/README.md b/README.md index f6d8dce..446ccca 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,329 @@ -# Amlogic boot scripts for Armbian +# Scripts de Boot do Amlogic para Armbian -The Armbian images for Amlogic TV Boxes use secondary, chain loaded u-boot blobs to boot mainline kernel images. -The vendor u-boot bootloaders can however boot mainline Linux perfectly without them. So they are not needed. +**Language / Idioma:** [🟢 Português](README.md) | [English](README.en.md) -All it takes are some simple modifications of some of the Armbian u-boot scripts. +## Índice +- [Visão Geral](#visão-geral) +- [Configuração](#configuração) +- [Dispositivos Suportados](#dispositivos-suportados) +- [Solução de Problemas Avançada — Modificação do Bootloader](#solução-de-problemas-avançada--modificação-do-bootloader) +- [Como Funciona Internamente](#como-funciona-internamente) -# Setup -assumption: you have vendor u-boot (the one that came with the box) running on eMMC. If you don't, you can just restore the stock Android image with Amlogic USB Burning tool. +--- + +## Visão Geral + +As imagens do Armbian para TV Boxes Amlogic normalmente dependem de blobs secundários de u-boot para inicializar o kernel mainline. Na prática, eles não são necessários: o bootloader u-boot que veio de fábrica com a sua box já é capaz de fazer isso. Tudo que é preciso são algumas modificações nos scripts de boot do Armbian. + +> **Pré-requisito:** o u-boot do fabricante deve estar rodando na eMMC. Se sua box foi reflashada com outro bootloader, restaure a imagem Android original com a ferramenta [Amlogic USB Burning Tool](https://androidmtk.com/download-amlogic-usb-burning-tool) antes de continuar. + +--- + +## Configuração + +### Passo 1 — Baixe a imagem do Armbian + +Baixe a versão mais recente do Armbian para s9xxx-box. Recomendamos a [bookworm minimal](https://dl.armbian.com/aml-s9xx-box/Bookworm_current_minimal). + +--- + +### Passo 2 — Prepare a mídia de instalação + +Grave a imagem no pendrive usando o **[balenaEtcher](https://etcher.balena.io/)** — a opção mais simples — ou via linha de comando: -+ **Step 1:** Download latest Armbian for s9xxx-box, let's use [bookworm minimal](https://dl.armbian.com/aml-s9xx-box/Bookworm_current_minimal) -+ **Step 2:** Burn the image to a USB flash drive -+ **Step 3:** Copy the modified boot scripts (**[aml_autoscript](https://github.com/devmfc/amlogic-bootscripts-Armbian/blob/main/aml_autoscript)**, **[s905_autoscript](https://github.com/devmfc/amlogic-bootscripts-Armbian/blob/main/s905_autoscript)**, **[emmc_autoscript](https://github.com/devmfc/amlogic-bootscripts-Armbian/blob/main/emmc_autoscript)** ) to the fat partition on the USB drive. Overwrite the existing files. -+ **Step 4:** If you have a GXBB (S905) or GXL (S905X/W/L) soc, you also need **[gxl-fixup.scr](https://github.com/devmfc/amlogic-bootscripts-Armbian/blob/main/gxl-fixup.scr)** -+ **Step 5:** Add an armbianEnv.txt file with the following content (file is also on github): ```bash -extraargs=earlycon rootflags=data=writeback rw no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 +sudo dd if=Armbian_*.img of=/dev/sdX bs=4M status=progress conv=fsync +``` + +> ⚠️ Substitua `/dev/sdX` pelo seu pendrive. Use `lsblk` ou `fdisk -l` para confirmar o dispositivo correto. Com `dd`, gravar no dispositivo errado apaga os dados sem confirmação. + +Monte a partição FAT do pendrive e substitua os scripts de boot pelos modificados, sobrescrevendo os existentes: + +- **[aml_autoscript](https://github.com/projetotvbox/amlogic-bootscripts-Armbian/blob/main/aml_autoscript)** +- **[s905_autoscript](https://github.com/projetotvbox/amlogic-bootscripts-Armbian/blob/main/s905_autoscript)** +- **[emmc_autoscript](https://github.com/projetotvbox/amlogic-bootscripts-Armbian/blob/main/emmc_autoscript)** +- **[gxl-fixup.scr](https://github.com/projetotvbox/amlogic-bootscripts-Armbian/blob/main/gxl-fixup.scr)** *(apenas se o seu SoC for GXBB/S905 ou GXL/S905X/W/L)* + +> **Compilando imagens próprias ou preparando múltiplos pendrives?** É possível modificar a imagem `.img` diretamente antes de gravar, evitando ter que editar cada pendrive individualmente. Para isso, monte a imagem com `losetup`: +> +> ```bash +> sudo losetup -fP Armbian_*.img +> lsblk | grep loop # identifique o dispositivo e a partição FAT (geralmente loopXp1) +> sudo mount /dev/loop0p1 /mnt/armbian_boot +> ``` +> +> Copie os scripts normalmente para `/mnt/armbian_boot/` e **prossiga pelos próximos passos normalmente**, editando o `armbianEnv.txt` e os demais parâmetros com a imagem ainda montada. Só ao final, após concluir todas as configurações, desmonte e grave: +> +> ```bash +> sudo umount /mnt/armbian_boot +> sudo losetup -d /dev/loop0 +> sudo dd if=Armbian_*.img of=/dev/sdX bs=4M status=progress conv=fsync +> ``` + +--- + +### Passo 3 — Configure o `armbianEnv.txt` + +O `armbianEnv.txt` controla parâmetros essenciais do boot. Antes de editar, faça um backup do arquivo original: + +```bash +sudo cp /mnt/seu_pendrive/armbianEnv.txt /mnt/seu_pendrive/armbianEnv.txt.bak +``` + +Edite com nano ou o editor de sua preferência: + +```bash +sudo nano /mnt/seu_pendrive/armbianEnv.txt +``` + +**Conteúdo de referência:** + +```bash +extraargs=earlycon=meson,0xfe07a000 console=ttyS0,921600n8 rootflags=data=writeback rw no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 watchdog.stop_on_reboot=0 pd_ignore_unused clk_ignore_unused rootdelay=5 bootlogo=false verbosity=7 usbstoragequirks=0x2537:0x1066:u,0x2537:0x1068:u console=both -# DTB file for this tvbox +# Arquivo DTB para este TV Box # fdtfile=amlogic/meson-gxl-s905x-nexbox-a95x.dtb fdtfile=amlogic/meson-sm1-x96-air-gbit.dtb -# set this to the UUID of the root partition (value can be found -# in /extlinux/extlinux.conf after APPEND root= or with blkid) -rootdev=UUID=92139c84-3871-41d7-a3f2-e8a943cbfa87 +# defina isto para o UUID da partição raiz (o valor pode ser encontrado com blkid ou no fstab) +#rootdev=UUID=92139c84-3871-41d7-a3f2-e8a943cbfa87 +# ou use o label padrão da partição: +#rootdev=LABEL=ROOTFS -# Enable ONLY for gxbb (S905) / gxl (S905X/L/W) to create fake u-boot header +# Ativar APENAS para gxbb (S905) / gxl (S905X/L/W) para criar cabeçalho u-boot falso #soc_fixup=gxl- ``` -+ **Step 6:** Change *fdtfile* to the DTB for your box. -+ **Step 7:** (optional since version 3:) Change *rootdev* to the right UUID for the rootfs for your image or change to /dev/sda2 when booting from USB or /dev/mmcblk0p2 when booting from SDCARD -+ **Step 8:** Only if your box has a GXBB (S905) or GXL (S905X/W/L) soc, uncomment the line *soc_fixup=gxl-* -+ **Step 9:** Power off the the box. -+ **Step 10:** Put the USB disk in your box. -+ **Step 11:** Push the reset button and hold the button -+ **Step 12:** power up your box while holding the reset button for approx 7 seconds. -+ **Step 13:** If you're lucky, it will now boot Armbian with a mainline kernel. Without any secondary u-boot blobs. - -All used files and source files can be found on [Github](https://github.com/devmfc/amlogic-bootscripts-Armbian). - -This is tested on S905X, S905W, S912, S905X2, S922X, S905X3 and they all boot the kernel. -I did test S905 also, but it boots only the first time for some reason. -It will probably also work for S905X4 and S905W2, but did not test those. They are not supported by the Armbian kernel at this moment anyway. + +> ⚠️ **Este arquivo é um ponto de partida, não uma configuração universal.** +> +> O conteúdo acima funciona para muitos dispositivos, mas pode não funcionar para o seu. Diferentes boxes, SoCs e versões do Armbian podem exigir parâmetros distintos — especialmente a linha `extraargs`. +> +> **Antes de substituir**, compare com o `armbianEnv.txt` original da imagem e mescle com cuidado. Parâmetros presentes no original e ausentes aqui podem ser necessários para o seu hardware. Em caso de dúvida, parta do original e aplique apenas as alterações que você compreende. Se o sistema não inicializar, restaurar o backup (`armbianEnv.txt.bak`) é o primeiro passo para diagnosticar. + +--- + +### Passo 4 — Ajuste o `fdtfile` + +Altere a linha `fdtfile` para o DTB correspondente à sua box. Os arquivos disponíveis estão em `/boot/dtb/amlogic/` dentro da imagem do Armbian. + +--- + +### Passo 5 — Ajuste o `rootdev` *(opcional desde a versão 3)* + +Por padrão, `rootdev` está comentado e o sistema usa o label `ROOTFS` automaticamente. Se precisar especificar manualmente: + +| Mídia | Valor | +|-------|-------| +| Pendrive USB | `/dev/sda2` | +| Cartão SD | `/dev/mmcblk0p2` | +| Por UUID *(recomendado)* | `UUID=` | +| Por label | `LABEL=ROOTFS` | + +**Como obter o UUID da partição raiz:** + +Com o sistema rodando a partir do pendrive ou SD, execute: + +```bash +blkid +``` + +Saída esperada: + +``` +/dev/sda2: UUID="92139c84-3871-41d7-a3f2-e8a943cbfa87" TYPE="ext4" PARTUUID="..." +``` + +Copie o valor `UUID=` da partição raiz (geralmente `sda2` ou `mmcblk0p2`) e cole no `armbianEnv.txt`. O UUID também pode ser encontrado em `/etc/fstab` ou no `armbianEnv.txt` original da imagem, se já estiver preenchido. + +--- + +### Passo 6 — Ative o SoC fixup *(apenas GXBB/GXL)* + +Se sua box usar um SoC GXBB (S905) ou GXL (S905X/W/L), descomente a linha: + +``` +soc_fixup=gxl- +``` + +--- + +### Passo 7 — Inicialize pelo pendrive + +1. Desligue a box. +2. Insira o pendrive USB. +3. Pressione e **mantenha pressionado** o botão reset. +4. Ligue a box e continue segurando por aproximadamente **7 segundos**. +5. Se tudo estiver correto, o Armbian iniciará com kernel mainline — sem nenhum blob u-boot secundário. + +--- + +## Dispositivos Suportados + +**✅ Totalmente Testado e Funcionando:** +- S905X, S905W, S912, S905X2, S922X, S905X3, S905X4 (HTV H8) + +**⚠️ Suporte Parcial:** +- S905: Inicia apenas na primeira tentativa (limitação conhecida) + +**❓ Não Testado:** +- S905W2: Provavelmente compatível mas não testado (não suportado atualmente pelo kernel do Armbian) + +Todos os arquivos e fontes estão disponíveis no [Github](https://github.com/projetotvbox/amlogic-bootscripts-Armbian). + +--- + +## Solução de Problemas Avançada — Modificação do Bootloader + +> ⚠️ **Esta seção é para casos onde os scripts simplesmente não funcionam.** Se o método principal funcionou, você não precisa disso. +> +> Alguns dispositivos possuem bootloaders de fábrica que não suportam a execução de scripts externos por padrão. Nesses casos, é possível modificar as variáveis do bootloader diretamente via console serial para forçar esse suporte. Trata-se de um procedimento de baixo nível, com risco real de brick. **Prossiga apenas se souber o que está fazendo.** + +### Pré-requisitos + +- **Sistema ARM Linux funcional:** Armbian, Debian ou Ubuntu ARM rodando a partir de USB/SD no dispositivo — necessário para acessar a eMMC e o shell. +- **Adaptador Serial TTL (3.3V UART):** ⚠️ **Use apenas 3.3V. 5V danificará o dispositivo.** Requer solda nos pads TX/RX/GND da placa. +- **Software de terminal serial:** PuTTY, Minicom ou picocom. + +### 🔒 Faça Backup da eMMC Antes de Qualquer Coisa + +```bash +# Backup com compressão (um backup de 16GB vira 2-4GB) +sudo dd if=/dev/mmcblkX bs=1M status=progress | gzip -c > backup_emmc_full.img.gz + +# Para restaurar: +# gunzip -c backup_emmc_full.img.gz | sudo dd of=/dev/mmcblkX bs=1M status=progress +``` + +### Verificando o Suporte do Bootloader + +#### Passo 1: Conectar o cabo serial +Solde TX, RX e GND nos pads UART do dispositivo e conecte ao PC. + +#### Passo 2: Abrir o console serial + +```bash +ls -la /dev/ttyUSB* + +picocom -b 115200 /dev/ttyUSB0 +# ou: +minicom -D /dev/ttyUSB0 -b 115200 +``` + +#### Passo 3: Interromper o U-Boot +Ligue o dispositivo e pressione rapidamente `Ctrl+C` ou `Enter` para interromper o U-Boot antes de ele inicializar. + +#### Passo 4: Verificar as variáveis do bootloader + +```bash +printenv bootcmd +``` + +Saída esperada: +``` +bootcmd=run start_autoscript; run storeboot +``` + +Verifique também: +```bash +printenv start_usb_autoscript +printenv start_mmc_autoscript +printenv start_emmc_autoscript +``` + +> Os nomes das variáveis podem variar. Procure por padrões como `start_*_autoscript`. + +### Modificando as Variáveis + +Se o bootloader for gravável, execute no console do U-Boot: + +```bash +setenv start_autoscript 'if mmcinfo; then run start_mmc_autoscript; fi; if usb start; then run start_usb_autoscript; fi; run start_emmc_autoscript' +setenv start_emmc_autoscript 'if fatload mmc 1 1020000 emmc_autoscript; then setenv devtype "mmc"; setenv devnum 1; autoscr 1020000; fi;' +setenv start_mmc_autoscript 'if fatload mmc 0 1020000 s905_autoscript; then setenv devtype "mmc"; setenv devnum 0; autoscr 1020000; fi;' +setenv start_usb_autoscript 'for usbdev in 0 1 2 3; do if fatload usb ${usbdev} 1020000 s905_autoscript; then setenv devtype "usb"; setenv devnum 0; autoscr 1020000; fi; done' +setenv upgrade_step 2 +setenv bootdelay 1 +``` + +#### ⚠️ Configurando o `bootcmd` — Preserve o Comando Original + +**Não use simplesmente `run start_autoscript; run storeboot`** sem antes verificar o seu `bootcmd` original. Um comando genérico pode danificar seu dispositivo se o original for diferente. + +1. **Anote o `bootcmd` original:** + ```bash + printenv bootcmd + ``` + +2. **Configure preservando o original:** + ```bash + setenv bootcmd 'run start_autoscript; [SEU BOOTCMD ORIGINAL AQUI]' + ``` + +**Exemplos reais:** + +```bash +# Exemplo 1 — Box Amlogic genérica (original: run storeboot) +setenv bootcmd 'run start_autoscript; run storeboot' + +# Exemplo 2 — HTV H8 (original: run start_emmc_autoscript; run storeboot) +setenv bootcmd 'run start_autoscript; run start_emmc_autoscript; run storeboot' + +# Exemplo 3 — bootcmd complexo +# Original: if test -n ${upgrade_step}; then echo BOOT_STEP equals $upgrade_step; setenv upgrade_step; fi; run storeboot +setenv bootcmd 'run start_autoscript; if test -n ${upgrade_step}; then echo BOOT_STEP equals $upgrade_step; setenv upgrade_step; fi; run storeboot' +``` + +#### Salve e verifique + +```bash +saveenv +reset +``` + +Interrompa o U-Boot novamente e confirme: + +```bash +printenv bootcmd +``` + +- **Variáveis salvas** → bootloader gravável, modificações aplicadas com sucesso. +- **Variáveis não salvas** → bootloader somente leitura; este método não é aplicável. + +--- + +## Como Funciona Internamente + +Para quem quer entender o que acontece por baixo dos panos — o papel de cada arquivo na cadeia de boot. + +### `aml_autoscript` — O Injetor de Nova Rota + +Executado **apenas uma vez**, no momento em que você força o modo de recuperação (segurando o botão reset ao ligar). Ele reescreve as variáveis de ambiente do U-Boot de fábrica via `saveenv`, estabelecendo uma nova ordem de boot: SD card → USB → eMMC, redirecionando o fluxo para os scripts abaixo. + +### `s905_autoscript` — O Carregador de Mídia Externa + +Executado toda vez que a placa liga com pendrive ou SD card conectado. Lê o `armbianEnv.txt`, carrega o Kernel, DTB e Initrd para a RAM, prepara os `bootargs` e passa o controle para o Kernel inicializar o sistema. + +### `emmc_autoscript` — O Carregador da Memória Interna + +Idêntico ao anterior em função, mas acionado quando não há pendrive ou SD inicializável conectado. Aponta para o endereço físico da eMMC (`devnum 1`) e monta a raiz do sistema a partir da partição interna. + +### `gxl-fixup.scr` — O Hack do Cabeçalho Falso *(apenas GXBB/GXL)* + +Os bootloaders de fábrica das famílias GXBB (S905) e GXL (S905X/W/L) só aceitam kernels no formato legado `uImage` (comando `bootm`). O Armbian moderno usa o formato `Image` (comando `booti`), que esses bootloaders simplesmente recusam. + +Em vez de compilar kernels legados, o script resolve isso em tempo de execução: + +1. Substitui a rotina de boot padrão (`cmd_do_boot`). +2. Usa `mw.l` para escrever diretamente na memória um cabeçalho u-boot legado **falso** no endereço `0x1ffffc0`, logo antes do Kernel. +3. Injeta um CRC válido no cabeçalho (`cmd_hdr_crc`). +4. Dispara `bootm` — o bootloader vê o cabeçalho falso, acredita estar lidando com um `uImage` legítimo e inicializa o kernel moderno normalmente. + +> **Restrição:** o arquivo do Kernel não pode ultrapassar **32MB**. + +É por isso que o Passo 6 instrui a descomentar `soc_fixup=gxl-` nesses SoCs: sem esse hack, o bootloader travaria na inicialização. + +--- diff --git a/armbianEnv.txt b/armbianEnv.txt index dfb3439..1a047d0 100644 --- a/armbianEnv.txt +++ b/armbianEnv.txt @@ -1,4 +1,4 @@ -extraargs=earlycon rootflags=data=writeback rw no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 +extraargs=earlycon=meson,0xfe07a000 console=ttyS0,921600n8 rootflags=data=writeback rw no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 watchdog.stop_on_reboot=0 pd_ignore_unused clk_ignore_unused rootdelay=5 bootlogo=false verbosity=7 usbstoragequirks=0x2537:0x1066:u,0x2537:0x1068:u @@ -11,9 +11,7 @@ fdtfile=amlogic/meson-sm1-x96-air-gbit.dtb # set this to the UUID of the root partition (value can be found in /extlinux/extlinux.conf after APPEND root= or with blkid) #rootdev=UUID=92139c84-3871-41d7-a3f2-e8a943cbfa87 # or use the default partition label: -#rootdev=LABEL=armbi_root +#rootdev=LABEL=ROOTFS # Enable ONLY for gxbb (S905) / gxl (S905X/L/W) to create fake u-boot header #soc_fixup=gxl- - -