Untethering Jetson-TK1

September 25, 2016 — Leave a comment

Normally I netboot all my ARM devices but in case of Jetson TK1 I thought it would be nice to go and try to make it “real computer” – running by itself, may be use it for some port builds. I added Samsung EVO to it but the plan was to use SSD for builds/source code, and to use either external SD card or eMMC as a root device. TK1 survived buildworld/buildkernel (I had to add swap though, clang is a memory monster) so it was time to populate root device and eMMC was picked as a target. There were some ms-basic-data partitions on eMMC but I didn’t think much of it and happily typed dd if=/dev/zero of=/dev/mmcsd0 bs=128m. Well… Big mistake. Among those partitions was u-boot. And probably earlier stage boot loader as well. So I had to install ubuntu on one of unused machines and re-flash TK1. Luckily no permanent damage was done to the device. After this accident I added a little bit of planning into the process. Here is short summary:

Default eMMC partition looks like this:

Tegra124 (Jetson TK1) #  mmc part

Partition Map for MMC device 0  --   Partition Type: EFI

Part    Start LBA       End LBA         Name
        Attributes
        Type GUID
        Partition GUID
  1     0x00017000      0x01c16fff      "APP"
        attrs:  0x0001000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   7369c667-ff51-ec4a-29cd-baabf2fbe346
  2     0x01c17000      0x01c18fff      "DTB"
        attrs:  0x0002000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   f854c27c-e81b-8de7-765a-2e63339fc99a
  3     0x01c19000      0x01c38fff      "EFI"
        attrs:  0x0003000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   b70d3266-5831-5aa3-255d-051758e95ed4
  4     0x01c39000      0x01c3afff      "USP"
        attrs:  0x0004000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   c6cdb2ab-b49b-1154-0e82-7441213ddc87
  5     0x01c3b000      0x01c3cfff      "TP1"
        attrs:  0x0005000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   a13ee970-e141-67fc-3e01-7e97eadc6b96
  6     0x01c3d000      0x01c3efff      "TP2"
        attrs:  0x0006000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   2a5c388f-b0ec-fb3b-32af-3c54ec18db5c
  7     0x01c3f000      0x01c40fff      "TP3"
        attrs:  0x0007000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   43fe1a02-fafb-3aaa-fb29-d1e6053c7c94
  8     0x01c41000      0x01c41fff      "WB0"
        attrs:  0x0008000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   61bed875-f989-bb5c-a899-0f95b1ebf1b3
  9     0x01c42000      0x01d58fff      "UDA"
        attrs:  0x0009000000000001
        type:   ebd0a0a2-b9e5-4433-87c0-68b6b72699c7
        guid:   00f7ef05-a1e9-e53a-ca0b-cbd0484764bd

We need two things to make TK1 bootable: place ubldr on flash so u-boot can load it and create rootfs. The latter one is simple: APP partition is the one to be user as root. For the former either of TPx partitions can be used, TP stands for “Temporary Placeholder” and can be used for app-specific tasks. All three TPx are just 4Mb but ubldr is small enough to fit just fine. So let’s place ubldr to TP1:

# newfs_msdos /dev/gpt/TP1
# mount_msdosfs /dev/gpt/TP1 /mnt
# cp ubldr.tk1 /mnt/
# umount /mnt

Then populate rootfs:

# newfs /dev/gpt/APP
# mount /dev/gpt/APP /mnt

Then build/install stuff: … buildworld, buildkernel. installworld, distribution and installkernel with DESTDIR=/mnt …

Create /etc/fstab so kernel would pick up correct rootfs location. I also use nullfs to mount /tmp to the directory on SSD drive, and added swap file on SSD.

/dev/gpt/APP /       ufs     rw,noatime     0       0
/dev/ada0    /src    ufs     rw,noatime     0       0
md99         none    swap    sw,file=/src/swap,late      0       0
/src/tmp     /tmp    nullfs  rw             0       0
# umount /mnt

Reboot to u-boot and set up boot command:

Tegra124 (Jetson TK1) # setenv bootcmd 'fatload mmc 0:5 $loadaddr ubldr.tk1; bootelf'
Tegra124 (Jetson TK1) # saveenv
Saving Environment to MMC...
Writing to MMC(0)... done
Tegra124 (Jetson TK1) # boot

That’s it. Also if I need to revert back to netbooting TK1 I can just set loaderdev to “net” in u-boot:

Tegra124 (Jetson TK1) # setenv loaderdev net; boot

I spent Labor Day weekend laboring on VBox shared folders support for FreeBSD. It’s been some time since I worked on it last time so I had to refresh my memory first. Things have moved on since then – VBox in ports was updated to version 5, but fortunately Li-Wen synced up freebsd-vboxfs repo to the latest version. After three days of laid-back hacking I am glad to announce that following VOPs are kind of implemented (in no particular order): lookup, access, readdir, read, getattr, readlink, remove, rmdir, symlink, close, create, open, write. “Kind of implemented” means that I was able to mount directory, traverse it, read file, calculate md5 sums and compare with host’s md5sum, create/remove directories, unzip zip file, etc but I doubt it would survive stress-test. Locking is all wrong at the moment and read/write VOPs allocate buffers for every operation.

I hit a roadblock with rename VOP: it involves some non-trivial locking logic and also there is a problem with cached paths. VBox hypervisor operates on full paths so we cache them in vboxfs nodes, but if one of parent directories is renamed, all cached names should be modified accordingly. I am going to tackle these two problems once I have long enough stretch of time time sit and concentrate on task.

Looks like my attempt to cheap out on SSD for TK1 has backfired. I went for the cheapest SSD available in local store (Toshiba Q300) but when I tried to checkout FreeBSD sources to the drive I got bunch of WRITE_FPDMA_QUEUED timeouts and system locked up. The same thing happened when I tried to perform checkout on Linux. The drive itself was OK, it survived “svn co …/head” and dd when connected using USB-to-SATA adapter.

I believe the problem was that TK1 SATA voltage was out of Toshiba’s tolerance range. I replaced Q300 with Samsung EVO 850 and was able to checkout sources and finish buildworld using SSD for src/obj storage.

FreeBSD on Jetson TK1

June 28, 2016 — 4 Comments

I finally got around to BSDify my Jetson TK1. Here is short summary of what is involved. And to save you some scrolling here are artifacts obtained from whole ordeal: https://people.freebsd.org/~gonzo/arm/jetson-tk1/

Jetson TK1

U-Boot

First of all – my TK1 didn’t have U-Boot. Type of bootloader depends on the version of Linux4Tegra TK1 comes with. Mine had L4T R19, with some kind of “not u-boot” bootloader. My first attempt was to use tegrarcm tool, it uses libusb, so it’s possible to build it on FreeBSD with some elbow grease, but once I tried to run it – it gave me cryptic errors and USB is not my strong skill so I took low road and installed Ubuntu VM. For what is’s worth I got the same kind of error on Ubuntu.

Next step was to use official update procedure described in http://developer.download.nvidia.com/embedded/L4T/r21_Release_v4.0/l4t_quick_start_guide.txt. Since I wasn’t going to boot Linux on the board I didn’t need sample rootfs. So the whole procedure was:

- Go to L4T R21.4 page
- Download Tegra124_Linux_R21.4.0_armhf.tbz2
- Unpack it
- Connect microUSB port on device to Linux VM
- Get device into recover mode: power cycle, press and hold recovery button, press and release power button, release recovery button
- Run ./flash.sh jetson-tk1 mmcblk0p1, this should rewrite eMMC flash on the board and after reboot you will get u-boot prompt on serial console

FreeBSD

At this point you can boot FreeBSD on TK1. I use netboot for most of my device so in this case it was: build and deploy world to /src/FreeBSD/tftproot/tk1, build and install kernel to the same directory, copy /src/FreeBSD/tftproot/tk1/boot/kernel/kernel to kernel.TK1 in tftproot directory, add entry do DHCP config and restart DHCP server. Entry looks like this:

host tk1 {
        hardware ethernet 00:04:4b:49:08:9e;
        fixed-address 192.168.10.98;
        filename "kernel.TK1";
        option root-path "/src/FreeBSD/tftproot/tk1";
        option root-opts "nolockd";
        option routers 192.168.10.1;
}

And also you need to add this to sys/arm/conf/JETSON-TK1 before building kernel:

options        BOOTP
options        BOOTP_NFSROOT
options        BOOTP_COMPAT
options        BOOTP_NFSV3

On the device you just run “dhcp; bootelf” and voila – it just works.

ubldr

Next step was to get ubldr running. I prefer suing ubldr because it gives more control over boot process accessible from booted FreeBSD system. ubldr requires U-Boot with API support, so I had to rebuild U-Boot from sources provided by nvidia with added #define CONFIG_API and all standard patches from sysutils/u-boot-* ports. Build procedure is standard:

export ARCH=arm
export CROSS_COMPILE=arm-linux-gnueabihf-
make jetson-tk1_config
make

It will generate multiple files, u-boot-dtb-tegra.bin is the one you want.

To reflash board with non-standard u-boot run ./flash.sh -L /path/to/u-boot-dtb-tegra.bin jetson-tk1 mmcblk0p1

Back to ubldr. It was easy to build and load it. Build script:

#!/bin/sh
export TARGET=arm
export TARGET_ARCH=armv6
export SRCROOT=/src/FreeBSD/wip
export MAKEOBJDIRPREFIX=/src/FreeBSD/obj
export MAKESYSPATH=$SRCROOT/share/mk

set -x
set -e

buildenv=`make -C $SRCROOT TARGET_ARCH=armv6 buildenvvars`
eval $buildenv make -C $SRCROOT/sys/boot -m $MAKESYSPATH obj
eval $buildenv make -C $SRCROOT/sys/boot -m $MAKESYSPATH clean
eval $buildenv make -C $SRCROOT/sys/boot -m $MAKESYSPATH UBLDR_LOADADDR=0x80600000 all

sudo cp /src/FreeBSD/obj/arm.armv6/src/FreeBSD/wip/sys/boot/arm/uboot/ubldr /src/FreeBSD/tftpboot/ubldr.TK1

Obviously, kernel.TK1 in DHCP config needs to be replaced with ubldr.TK1. 0×80600000 is some value I came up with by looking at u-boot default environment. Something not high enough to overlap with kernel and not low enough to overlap with u-boot.

And that’s where thing got hairy. To load ubldr and then netboot kernel, you need to set u-boot env loaderdev variable first: setenv loaderdev net; saveenv. And then do the same thing as above: dhcp; bootelf. Unfortunately I got this:

## Starting application at 0x81000098 ...
Consoles: U-Boot console
Compatible U-Boot API signature found @0xffa3e410

FreeBSD/armv6 U-Boot loader, Revision 1.2
(gonzo@eb3.bluezbox.com, Mon Jun 27 19:59:22 PDT 2016)

DRAM: 2048MB
MMC: no card present
MMC Device 2 not found
MMC Device 3 not found
MMC: no card present
MMC: no card present
MMC: no card present
MMC: no card present
MMC: no card present
MMC: no card present
MMC Device 2 not found
Number of U-Boot devices: 3
U-Boot env: loaderdev='net'
Found U-Boot device: disk
Found U-Boot device: net
Booting from net0:
panic: arp: no response for 192.168.10.1

--> Press a key on the console to reboot <--
Rebooting...
resetting ...

After some heavy thinking and code digging problem was narrowed down to u-boot network driver drivers/net/rtl8169.c. Instead of returning 0 on success and negative value on error it returns number of bytes sent on success and zero on error. Which confused ubldr into thinking nothing is sent, so recv part of exchange was never invoked. After fixing this issue kernel was loaded just fine but hang right afert

Using DTB compiled into kernel.
Kernel entry at 0x0x80800100...
Kernel args: (null)

Logn story short - it was caused by enabled D-Cache so I had to add

#ifndef CONFIG_SPL_BUILD
#define CONFIG_SYS_DCACHE_OFF
#define CONFIG_CMD_CACHE
#endif

to u-boot config and go through rebuild/reflash cycle again. After this whole boot chain went through right to login prompt.

My next goal is to make TK1 self-contained box: get base system installed on eMMC and use attached SSD as scratch disk for swap and builds.

Few weeks back Ralf Nolden, who is *BSD champion in Qt community, urged me to clean-up and submit my Qt5-related projects to upstream and scfb platform plugin was picked as a test dummy. It took 12 iterations to get things right, along the way plugin was renamed to bsdfb, but eventually patch has been merged.

Next two candidates are bsdkeyboard and bsdsysmouse input plugins.

Two months ago I tried to setup dev environment using FreeBSD Vagrant box just to find out that FreeBSD does not support VirtualBox shared folders. After some googling I found Li-Wen Hsu’s github repository with some work in this area. Li-Wen and Will Andrews has already done major chunk of work: patches to VirtualBox build system, skeleton VFS driver, API to talk to hypervisor but hit a block with some implementation details in VirtualBox’s virtual-memory compatibility layer. Will provided very comprehensive analysis of the problem.

Li-Wen was occupied with some other projects so he gave me his OK to work on shared folder support on my own. Will’s suggestion was easy to implement – lock only userland memory, like Solaris driver does. VFS part was more complicated though: fs nodes, vnode, their lifecycle and locking is too hairy for drive-by hacking. I used tmpfs as a reference to learn some VFS magic, but a lot of things are still obscure. Nevertheless after few weeks of tinkering first milestone has been achieved: I can mount/unmount shared VirtualBox folder and navigate mounted filesystem without immediate kernel panic. Next goal (if time permits): stable and non-leaking read-only filesystem.

To those who do not track FreeBSD commit messages: I committed gpiokeys driver to -CURRENT as r299475. The driver is not enabled in any of the kernels but can be built as a loadable module.

For now it stays disconnected from main build because it breaks some MIPS kernel configs. Configs in question include “modules/gpio” as part of MODULES_OVERRIDE variable and since gpiokeys can be built only with FDT-enabled kernel the build fails.

gpiokeys can be used as a base for more input device driver: “gpio-keys-polled” and “gpio-matrix-keypad“. I do not have hardware to test this at the moment. If you do and you’re looking for small FreeBSD project to work on – here you go.

Next step on my ToDo list is to try tricking people into committing evdev patch, which at the moment is the only requirement for unlocking touchscreen support.

Qt 5.6 is finally out so I thought I’d give it a spin on my Raspberry Pi. Previously I used cross-compilation but this time I thought I’d spend some time in trying to create ports Qt modules. There is Qt 5.5.1 in ports and it’s nicely split into sub-ports and most of gory details are hidden in bsd.qt.mk library. The problem with it is it’s highly coupled with Xorg stuff and I didn’t find easy way to squeeze non-desktop use cases into current infrastructure. So I just created new custom devel/qt56 port.

In order to get it done as fast as possible I took several shortcuts: all the stuff is installed to /usr/local/qt5 directory, there is no meta-port for submodules to share common part yet. Also besides base the only module I packaged (I was particularly interested in it) was QtMultimedia. Should be fairly easy to fix last 2 items though.

Qt layer for UI provider is called QPA: Qt Platform Abstraction. There are quite a few of them but I am familiar and interested in two: plain framebuffer and eglfs. Plain framebuffer stock QPA plugin is called linuxfb and naturally we can’t use it for FreeBSD. Luckily there is a lot of similarities between Linux fb and syscons(or vt) fb (you can’t get very innovative with framebuffer) so writing QPA support for scfb was easy. It can be used with any generic SoC with framebuffer support: AM335x(beaglebone black), i.MX6(Wandboard), NVIDIA Tegra, Pi.

elgfs is full-screen OpenGL mode. OpenGL implementation depends on SoC vendor, e.g. Pi’s library is provided by raspberrypi-userland port. If we had OpenGL support for AM335x it would have been provided by PowerVR userland libraries. As far as I understand eglfs can’t be made universal: each implementation has its own quirks so you have to specify target OpenGL vendor during build time. So far we support eglfs only for Raspberry Pi thanks to Broadcom’s open-sourcing kernel drivers and userland libraries.

Then there is question of input. When you start your application from console you have several options to get user’s input: keyboard, mouse, touchscreen. Common way to do this on Linux is through evdev which is a universal ways to access these kinds of devices. There is effort to get this functionality on FreeBSD so when it’s there stock input plugins could be used as-is. Until then there are two non-standard plugins by yours truly: bsdkeyboard and bsdsysmouse.

scfb, bsdysmouse, and bsdkeyboard are included in experimental ports as patches.

All in all experience of getting Qt 5.6 running on FreeBSD/Pi was smooth. And to make this post more entertining here are two demos running on my Pi2 with official touchscreen.

Qt demo player with visualizer (src):

OpenGL demo with Qt logo in it (src):

Being able to power cycle ARM boards remotely (without spending a lot of $$$) was on my wish list for way to long, so I finally got around to put something together. The obvious way to do this is power relay controlled by GPIO + remotely accessible GPIO port. For the former I picked up this relay by Digital Loggers. It was four ports, only two of them are connected at a time, you can switch selected pair by setting control port level. For a controller part I picked up RIoTBoard but actually any ARM board with sshd running on it and user-accessible GPIO pin would do.

On riotboard there are several GPIO pins available on J13 expansion port. You can find values in board’s user manual. Just in case you don’t know (and it’s not in manual) pin 1 on the port marked with white triangle, if you look at port so that pin 1 is in top-left corner, next to it on the right is pin 2, and right under it is pin 3. So it goes like:
[ 1 2 ]
[ 3 4 ]
[ 5 6 ]
… and so on …

I used GPIO4_16 (pin 5). You need to connect GND and GPIO pin to relay’s control port. Polarity does not matter in this case. For port control you can use gpioctl utility. But first we need to identify this pin on FreeBSD’s side. For each GPIO bank FreeBSD has /dev/gpiocX device node, where X starts from zero. But it’s not uncommon for SoC vendors to start numbering GPIO banks from 1. riotboard’s vendor is one of them so GPIO4 is actually controlled through /dev/gpioc3. By default pin 16 is configured as input, so you need to change it to out:

# gpioctl -f /dev/gpioc3 -c 16 OUT

and then you can start giving orders to relay:

# gpioctl -f /dev/gpioc3 16 0
# gpioctl -f /dev/gpioc3 16 1
# gpioctl -f /dev/gpioc3 -t 16

Demo video:

Back from vacation and back to work. Once I got RIoTboard up and running next natural step was to wrap up some i.MX6 project I had in “almost finished” state for months. So now they’re in “going through review” state: drivers for HDMI framer and IPU. They add basic 1024×768 console for iMX6 board. Video mode management requires more sophisticated timers framework, that is being work on as a part of Jetson TK1 port.