Bootloaders porting using linux

About
This article describes how to get debug uart, when you don't have vendor's debug uart cable and don't want to disassemble your phone, and how to execute a payload (i.e. you bootloader port).

You must have debug uart, if you want to port bootloader on your phone. However, some bootloaders and/or MUIC chips does not allow you to connect to debug uart (like recent Samsung phones with usb type-c). In this case, you can either:
 * disassemble the phone, find and connect to debug uart pins, exposed on the board.
 * Hack linux to force expose debug uart, and then test your bootloader.

We'll speak about the latter.

This method is quite similar to kexec, though differs in some details:
 * MMU should be turned off completely
 * Use bin format, to simplify load process.

Getting started
You'll need:
 * PmOs downstream port (TWRP can be used)
 * Stuff for building debug cable

Hack MUIC driver to expose uart on request
We can use sysfs attribute to tell muic driver, we need to switch debug uart to usb. For example, MUIC driver patch for Samsung Galaxy S9

This patch will add new sysfs attribute, so that MUIC driver will attach uart on '1' write to that attribute, and detach it on '0' write.

Setup pmos to switch muic on key combination
Use triggerhappy

Build a cable
The process is similar to finding TX RX pins on the PCB For type-c devices it will likely be either D+D- or SBU pins.
 * determine, on what pins MUIC multiplexes uart, i.e. find TX RX pins on usb.
 * assemble cable
 * ensure you get an output from your cable, when writing to corresponding tty on the phone

Hack kernel to execute your bootloader
Simplest way is to delete device tree node, for qcom device usually
 * enable
 * disable watchdog timer (it forces reboot, if kernel not responds)
 * apply a patch to launch bootloader from linux


 * load and run your code with run_file.py script like:


 * On systems with no python, like TWRP use sh

Run bootloader builds

 * Connect to phone via ssh
 * Build bootloader bin file, upload it on phone.
 * Run . It will give you 20 secs timeout to plugin debug uart cable, and switch muic.
 * After timeout is expired, your bin file will be launched, with MMU disabled.

DMA uart mode.
Linux may run uart in DMA mode, instead of FIFO, like typical bootloader. For example, qcom SOCs GENI core uart works in data mover mode, using DMA, so you need to switch it to FIFO mode. Refer to early_con uart setup in linux, setup uart via devmem accordingly

Uart is reset by bootloader.
Refer to early_con uart setup in linux

Phone reboots after executing bootloader
Turn off watchdog