Building a Linux system for the STM32MP1: remote firmware updates

After another long break, here is our new article in the series of blog posts about building a Linux system for the STM32MP1 platform. After showing how to build a minimal Linux system for the STM32MP157 platform, how to connect and use an I2C based pressure/temperature/humidity sensor and how to integrate Qt5 in our system, how to set up a development environment to write our own Qt5 application, how to develop a Qt5 application, and how to setup factory flashing, we are now going to discuss the topic of in-field firmware update.

List of articles in this series:

  1. Building a Linux system for the STM32MP1: basic system
  2. Building a Linux system for the STM32MP1: connecting an I2C sensor
  3. Building a Linux system for the STM32MP1: enabling Qt5 for graphical applications
  4. Building a Linux system for the STM32MP1: setting up a Qt5 application development environment
  5. Building a Linux system for the STM32MP1: developing a Qt5 graphical application
  6. Building a Linux system for the STM32MP1: implementing factory flashing
  7. Building a Linux system for the STM32MP1: remote firmware updates

Why remote firmware updates?

The days and age when it was possible to build and flash an embedded system firmware, ship the device and forget it, are long behind us. Systems have gotten more complicated, and we therefore have to fix bugs and security issues after the device has been shipped, and we often want to deploy new features in the field into existing devices. For all those reasons, the ability to remotely update the firmware of embedded devices is now a must-have.

Open-source firmware update tools

There are different possibilities to update your system:

  • If you’re using a binary distribution, use the package manager of this distribution to update individual components
  • Do complete system image updates, at the block-level, replacing the entire system image with an updated one. Three main open-source solutions are available: swupdate, Mender.io and RAUC.
  • Do file-based updates, with solutions such as OSTree.

In this blog post, we are going to show how to set up the swupdate solution.

swupdate is a tool installed on the target that can receive an update image (.swu file), either from a local media or from a remote server, and use it to update various parts of the system. Typically, it will be used to update the Linux kernel and the root filesystem, but it can also be used to update additional partitions, FPGA bitstreams, etc.

swupdate implements two possible update strategies:

  • A dual copy strategy, where the storage has enough space to store two copies of the entire filesystem. This allows to run the system from copy A, update copy B, and reboot it into copy B. The next update will of course update copy A.
  • A single copy strategy, where the upgrade process consists in rebooting into a minimal system that runs entirely from RAM, and that will be responsible for updating the system on storage.

For this blog post, we will implement the dual copy strategy, but the single copy strategy is also supported for systems with tighter storage restrictions.

We are going to setup swupdate step by step: first by triggering updates locally, and then seeing how to trigger updates remotely.

Local usage of swupdate

Add USB storage support

As a first step, in order to transfer the update image to the target, we will use a USB stick. This requires having USB mass storage support in the Linux kernel. So let’s adjust our Linux kernel configuration by running make linux-menuconfig. Within the Linux kernel configuration:

  • Enable the CONFIG_SCSI option. This is a requirement for USB mass storage support
  • Enable the CONFIG_BLK_DEV_SD option, needed for SCSI disk support, which is another requirement for USB mass storage.
  • Enable the CONFIG_USB_STORAGE option.
  • The CONFIG_VFAT_FS option, to support the FAT filesystem, is already enabled.
  • Enable the CONFIG_NLS_CODEPAGE_437 and CONFIG_NLS_ISO8859_1 options, to have the necessary support to decode filenames in the FAT filesystem.

Then, run make linux-update-defconfig to preserve these kernel configurations changes in your kernel configuration file at board/stmicroelectronics/stm32mp157-dk/linux.config.

swupdate setup

In Target packages, System tools, enable swupdate. You can disable the install default website setting since we are not going to use the internal swupdate web server.

Take this opportunity to also enable the gptfdisk tool and its sgdisk sub-option in the Hardware handling submenu. We will need this tool later to update the partition table at the end of the update process.

Now that we have both both USB storage support and the swupdate package enabled, let’s build a new version of our system by running make. Flash the resulting image on your SD card, and boot your target. You should have swupdate available:

# swupdate -h
Swupdate v2018.11.0

Licensed under GPLv2. See source distribution for detailed copyright notices.

swupdate (compiled Mar  4 2020)
Usage swupdate [OPTION]
 -f, --file           : configuration file to use
 -p, --postupdate               : execute post-update command
 -e, --select , : Select software images set and source
                                  Ex.: stable,main
 -i, --image          : Software to be installed
 -l, --loglevel          : logging level
 -L, --syslog                   : enable syslog logger
 -n, --dry-run                  : run SWUpdate without installing the software
 -N, --no-downgrading  : not install a release older as 
 -o, --output      : saves the incoming stream
 -v, --verbose                  : be verbose, set maximum loglevel
     --version                  : print SWUpdate version and exit
 -c, --check                    : check image and exit, use with -i 
 -h, --help                     : print this help and exit
 -w, --webserver [OPTIONS]      : Parameters to be passed to webserver
	mongoose arguments:
	  -l, --listing                  : enable directory listing
	  -p, --port               : server port number  (default: 8080)
	  -r, --document-root      : path to document root directory (default: .)
	  -a, --api-version [1|2]        : set Web protocol API to v1 (legacy) or v2 (default v2)
	  --auth-domain                  : set authentication domain if any (default: none)
	  --global-auth-file             : set authentication file if any (default: none)

Take a USB stick with a FAT filesystem on it, which you can mount:

# mount /dev/sda1 /mnt

If that works, we’re now ready to move on to the next step of actually getting a firmware update image.

Generate the swupdate image

swupdate has its own update image format, and you need to generate an image that complies with this format so that swupdate can use it to upgrade your system. The format is simple: it’s a CPIO archive, which contains one file named sw-description describing the contents of the update image, and one or several additional files that are the images to update.

First, let’s create our sw-description file in board/stmicroelectronics/stm32mp157-dk/sw-description. The tags and properties available are described in the swupdate documentation.

software = {
	version = "0.1.0";
	rootfs = {
		rootfs-1: {
			images: (
			{
				filename = "rootfs.ext4.gz";
				compressed = true;
				device = "/dev/mmcblk0p4";
			});
		}
		rootfs-2: {
			images: (
			{
				filename = "rootfs.ext4.gz";
				compressed = true;
				device = "/dev/mmcblk0p5";
			});
		}
	}
}

This describes a single software component rootfs, which is available as two software collections, to implement the dual copy mechanism. The root filesystem will have one copy in /dev/mmcblk0p4 and another copy in /dev/mmcblk0p5. They will be updated from a compressed image called rootfs.ext4.gz.

Once this sw-description file is written, we can write a small script that generates the swupdate image. We’ll put this script in board/stmicroelectronics/stm32mp157-dk/gen-swupdate-image.sh:

#!/bin/sh

BOARD_DIR=$(dirname $0)

cp ${BOARD_DIR}/sw-description ${BINARIES_DIR}

IMG_FILES="sw-description rootfs.ext4.gz"

pushd ${BINARIES_DIR}
for f in ${IMG_FILES} ; do
	echo ${f}
done | cpio -ovL -H crc > buildroot.swu
popd

It simply copies the sw-description file to BINARIES_DIR (which is output/images), and then creates a buildroot.swu CPIO archive that contains the sw-description and rootfs.ext4.gz files.

Of course, make sure this script has executable permissions.

Then, we need to slightly adjust our Buildroot configuration, so run make menuconfig, and:

  • In System configuration, in the option Custom scripts to run after creating filesystem images, add board/stmicroelectronics/stm32mp157-dk/gen-swupdate-image.sh after the existing value support/scripts/genimage.sh. This will make sure our new script generating the swupdate image is executed as a post-image script, at the end of the build.
  • In Filesystem images, enable the gzip compression method for the ext2/3/4 root filesystem, so that a rootfs.ext4.gz image is generated.

With that in place, we are now able to generate our firmware image, by simply running make in Buildroot. At the end of the build, the output/images/ folder should contain the sw-description and rootfs.ext4.gz files. You can look at the contents of buildroot.swu:

$ cat output/images/buildroot.swu | cpio -it
sw-description
rootfs.ext4.gz
58225 blocks

Partioning scheme and booting logic

We now need to adjust the partitioning scheme of our SD card so that it has two partitions for the root filesystem, one for each copy. This partitioning scheme is defined in board/stmicroelectronics/stm32mp157-dk/genimage.cfg, which we change to:

image sdcard.img {
        hdimage {
                gpt = "true"
        }

        partition fsbl1 {
                image = "tf-a-stm32mp157c-dk2.stm32"
        }

        partition fsbl2 {
                image = "tf-a-stm32mp157c-dk2.stm32"
        }

        partition ssbl {
                image = "u-boot.stm32"
        }

        partition rootfs1 {
                image = "rootfs.ext4"
                partition-type = 0x83
                bootable = "yes"
                size = 256M
        }

        partition rootfs2 {
                partition-type = 0x83
                size = 256M
        }
}

As explained in the first blog post of this series, the /boot/extlinux/extlinux.conf file is read by the bootloader to know how to boot the system. Among other things, this file defines the Linux kernel command line, which contains root=/dev/mmcblk0p4 to tell the kernel where the root filesystem is. But with our dual copy upgrade scheme, the root filesystem will sometimes be on /dev/mmcblk0p4, sometimes on /dev/mmcblk0p5. To achieve that without constantly updating the extlinux.conf file, we will use /dev/mmcblk0p${devplist} instead. devplist is a U-Boot variable that indicates from which partition the extlinux.conf file was read, which turns out to be the partition of our root filesystem. So, your board/stmicroelectronics/stm32mp157-dk/overlay/boot/extlinux/extlinux.conf file should look like this:

label stm32mp15-buildroot
  kernel /boot/zImage
  devicetree /boot/stm32mp157c-dk2.dtb
  append root=/dev/mmcblk0p${devplist} rootwait console=ttySTM0,115200 vt.global_cursor_default=0

For the dual copy strategy to work, we need to tell the bootloader to boot either from the root filesystem in the rootfs1 partition or the rootfs2 partition. This will be done using the bootable flag of each GPT partition, and this is what this script does: it toggles the bootable flag of 4th and 5th partition of the SD card. This way, the partition with the bootable flag will lose it, and the other partition will gain it. Thanks to this, at the next reboot, U-Boot will consider the system located in the other SD card partition. This work will be done by a /etc/swupdate/postupdate.sh script, that you will store in board/stmicroelectronics/stm32mp157-dk/overlay/etc/swupdate/postupdate.sh, which contains:

#!/bin/sh
sgdisk -A 4:toggle:2 -A 5:toggle:2 /dev/mmcblk0
reboot

Make sure this script is executable.

With all these changes in place, let’s restart the Buildroot build by running make. The sdcard.img should contain the new partioning scheme:

$ sgdisk -p output/images/sdcard.img
[...]
Number  Start (sector)    End (sector)  Size       Code  Name
   1              34             497   232.0 KiB   8300  fsbl1
   2             498             961   232.0 KiB   8300  fsbl2
   3             962            2423   731.0 KiB   8300  ssbl
   4            2424          526711   256.0 MiB   8300  rootfs1
   5          526712         1050999   256.0 MiB   8300  rootfs2

Reflash your SD card with the new sdcard.img, and boot this new system. Transfer the buildroot.swu update image to your USB stick.

Testing the firmware update locally

After booting the system, mount the USB stick, which contains the buildroot.swu file:

# mount /dev/sda1 /mnt/
# ls /mnt/
buildroot.swu

Let’s trigger the system upgrade with swupdate:

# swupdate -i /mnt/buildroot.swu -e rootfs,rootfs-2 -p /etc/swupdate/postupdate.sh

Swupdate v2018.11.0

Licensed under GPLv2. See source distribution for detailed copyright notices.

Registered handlers:
	dummy
	raw
	rawfile
software set: rootfs mode: rootfs-2
Software updated successfully
Please reboot the device to start the new software
[INFO ] : SWUPDATE successful ! 
Warning: The kernel is still using the old partition table.
The new table will be used at the next reboot or after you
run partprobe(8) or kpartx(8)
The operation has completed successfully.
# Stopping qt-sensor-demo: OK
Stopping dropbear sshd: OK
Stopping network: OK
Saving random seed... done.
Stopping klogd: OK
Stopping syslogd: OK
umount: devtmpfs busy - remounted read-only
[  761.949576] EXT4-fs (mmcblk0p4): re-mounted. Opts: (null)
The system is going down NOW!
Sent SIGTERM to all processes
Sent SIGKILL to all processes
Requesting system reboot
[  763.965243] reboot: ResNOTICE:  CPU: STM32MP157CAC Rev.B
NOTICE:  Model: STMicroelectronics STM32MP157C-DK2 Discovery Board

The -i option indicates the firmware update file, while the -e option indicates which software component should be updated. Here we update the rootfs in its slot 2, rootfs-2, which is in /dev/mmcblk0p5. The -p option tells to run our post-update script when the update is successful. In the above log, we see that the system is being rebooted right after the update.

At the next boot, you should see:

U-Boot 2018.11-stm32mp-r2.1 (Mar 04 2020 - 15:28:34 +0100)
[...]
mmc0 is current device
Scanning mmc 0:5...
Found /boot/extlinux/extlinux.conf
[...]
append: root=/dev/mmcblk0p5 rootwait console=ttySTM0,115200 vt.global_cursor_default=0

during the U-Boot part. So we see it is loading extlinux.conf from the MMC partition 5, and has properly set root=/dev/mmcblk0p5. So the kernel and Device Tree will be loaded from MMC partition 5, and this partition will also be used by Linux as the root filesystem.

With all this logic, we could now potentially have some script that gets triggered when a USB stick is inserted, mount it, check if an update image is available on the USB stick, and if so, launch swupdate and reboot. This would be perfectly fine for local updates, for example with an operator in charge of doing the update of the device.

However, we can do better, and support over-the-air updates, a topic that we will discuss in the next section.

Over-the-air updates

To support over-the-air updates with swupdate, we will have to:

  1. Install on a server a Web interface that allows the swupdate program to retrieve firmware update files, and the user to trigger the updates.
  2. Run swupdate in daemon mode on the target.

Set up the web server: hawkBit

swupdate is capable of interfacing with a management interface provided by the Eclipse hawkBit project. Using this web interface, one can manage its fleet of embedded devices, and rollout updates to these devices remotely.

hawkBit has plenty of capabilities, and we are here going to set it up in a very minimal way, with no authentication and a very simple configuration.

As suggested in the project getting started page, we’ll use a pre-existing Docker container image to run hawkBit:

sudo docker run -p 8080:8080 hawkbit/hawkbit-update-server:latest \
     --hawkbit.dmf.rabbitmq.enabled=false \
     --hawkbit.server.ddi.security.authentication.anonymous.enabled=true

After a short while, it should show:

2020-03-06 09:15:46.492  ... Started ServerConnector@3728a578{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2020-03-06 09:15:46.507  ... Jetty started on port(s) 8080 (http/1.1) with context path '/'
2020-03-06 09:15:46.514  ... Started Start in 21.312 seconds (JVM running for 22.108)

From this point, you can connect with your web browser to http://localhost:8080 to access the hawkBit interface. Login with the admin login and admin password.

hawkBit login

Once in the main hawkBit interface, go to the System Config tab, and enable the option Allow targets to download artifacts without security credentials. Of course, for a real deployment, you will want to set up proper credentials and authentification.

hawkBit System Config

In the Distribution tab, create a new Distribution by clicking on the plus sign in the Distributions panel:

hawkBit New Distribution

Then in the same tab, but in the Software Modules panel, create a new software module:

hawkBit New Software Module

Once done, assign the newly added software module to the Buildroot distribution by dragging-drop it into the Buildroot distribution. Things should then look like this:

hawkBit Distribution

Things are now pretty much ready on the hawkBit side now. Let’s move on with the embedded device side.

Configure swupdate

We need to adjust the configuration of swupdate to enable its Suricatta functionality which is what allows to connect to an hawkBit server.

In Buildroot’s menuconfig, enable the libcurl (BR2_PACKAGE_LIBCURL) and json-c (BR2_PACKAGE_JSON_C) packages, both of which are needed for swupdate’s Suricatta. While at it, since we will adjust the swupdate configuration and we’ll want to preserve our custom configuration, change the BR2_PACKAGE_SWUPDATE_CONFIG option to point to board/stmicroelectronics/stm32mp157-dk/swupdate.config.

Then, run:

$ make swupdate-menuconfig

to enter the swupdate configuration interface. Enable the Suricatta option, and inside this menu, in the Server submenu, verify that the Server Type is hawkBit support. You can now exit the swupdate menuconfig.

Save our custom swupdate configuration permanently:

$ make swupdate-update-defconfig

With this proper swupdate configuration in place, we now need to create a runtime configuration file for swupdate, and an init script to start swupdate at boot time. Let’s start with the runtime configuration file, which we’ll store in board/stmicroelectronics/stm32mp157-dk/overlay/etc/swupdate/swupdate.cfg, containing:

globals :
{
	postupdatecmd = "/etc/swupdate/postupdate.sh";
};

suricatta :
{
	tenant = "default";
	id = "DEV001";
	url = "http://192.168.42.1:8080";
};

We specify the path to our post-update script so that it doesn’t have to be specified on the command line, and then we specify the Suricatta configuration details: id is the unique identifier of our board, the URL is the URL to connect to the hawkBit instance (make sure to replace that with the IP address of where you’re running hawkBit). tenant should be default, unless you’re using your hawkBit instance in complex setups to for example serve multiple customers.

Our post-update script also needs to be slightly adjusted. Indeed, we will need a marker that tells us upon reboot that an update has been done, in order to confirm to the server that the update has been successfully applied. So we change board/stmicroelectronics/stm32mp157-dk/overlay/etc/swupdate/postupdate.sh to:

#!/bin/sh

PART_STATUS=$(sgdisk -A 4:get:2 /dev/mmcblk0)
if test "${PART_STATUS}" = "4:2:1" ; then
        NEXT_ROOTFS=/dev/mmcblk0p5
else
        NEXT_ROOTFS=/dev/mmcblk0p4
fi

# Add update marker
mount ${NEXT_ROOTFS} /mnt
touch /mnt/update-ok
umount /mnt

sgdisk -A 4:toggle:2 -A 5:toggle:2 /dev/mmcblk0
reboot

What we do is that we simply mount the next root filesystem, and create a file /update-ok. This file will be checked by our swupdate init script, see below.

Then, our init script will be in board/stmicroelectronics/stm32mp157-dk/overlay/etc/init.d/S98swupdate, with executable permissions, and contain:

#!/bin/sh

DAEMON="swupdate"
PIDFILE="/var/run/$DAEMON.pid"

PART_STATUS=$(sgdisk -A 4:get:2 /dev/mmcblk0)
if test "${PART_STATUS}" = "4:2:1" ; then
	ROOTFS=rootfs-2
else
	ROOTFS=rootfs-1
fi

if test -f /update-ok ; then
	SURICATTA_ARGS="-c 2"
	rm -f /update-ok
fi

start() {
	printf 'Starting %s: ' "$DAEMON"
	# shellcheck disable=SC2086 # we need the word splitting
	start-stop-daemon -b -q -m -S -p "$PIDFILE" -x "/usr/bin/$DAEMON" \
		-- -f /etc/swupdate/swupdate.cfg -L -e rootfs,${ROOTFS} -u "${SURICATTA_ARGS}"
	status=$?
	if [ "$status" -eq 0 ]; then
		echo "OK"
	else
		echo "FAIL"
	fi
	return "$status"
}

stop() {
	printf 'Stopping %s: ' "$DAEMON"
	start-stop-daemon -K -q -p "$PIDFILE"
	status=$?
	if [ "$status" -eq 0 ]; then
		rm -f "$PIDFILE"
		echo "OK"
	else
		echo "FAIL"
	fi
	return "$status"
}

restart() {
	stop
	sleep 1
	start
}

case "$1" in
        start|stop|restart)
		"$1";;
	reload)
		# Restart, since there is no true "reload" feature.
		restart;;
        *)
                echo "Usage: $0 {start|stop|restart|reload}"
                exit 1
esac

This is modeled after typical Buildroot init scripts. A few points worth mentioning:

  • At the beginning of the script, we determine which copy of the root filesystem needs to be updated by looking at which partition currently is marked “bootable”. This is used to fill in the ROOTFS variable.
  • We also determine if we are just finishing an update, by looking at the presence of a /update-ok file.
  • When starting swupdate, we pass a few options: -f with the path to the swupdate configuration file, -L to enable syslog logging, -e to indicate which copy of the root filesystem should be updated, and -u '${SURICATTA_ARGS}' to run in Suricatta mode, with SURICATTA_ARGS containing -c 2 to confirm the completion of an update.

Generate a new image with the updated swupdate, its configuration file and init script, and reboot your system.

Deploying an update

When booting, your system starts swupdate automatically:

Starting swupdate: OK
[...]
# ps aux | grep swupdate
  125 root     /usr/bin/swupdate -f /etc/swupdate/swupdate.cfg -L -e rootfs,rootfs-1 -u
  132 root     /usr/bin/swupdate -f /etc/swupdate/swupdate.cfg -L -e rootfs,rootfs-1 -u

Back to the hawkBit administration interface, the Deployment tab should show one notification:

hawkBit new device notification

and when clicking on it, you should see our DEV001 device:

hawkBit new device

Now, go to the Upload tab, select the Buildroot software module, and click on Upload File. Upload the buildroot.swu file here:

hawkBit Upload

Back into the Deployment tab, drag and drop the Buildroot distribution into the DEV001 device. A pending update should appear in the Action history for DEV001:

hawkBit upgrade pending

The swupdate on your target will poll regularly the server (by default every 300 seconds, can be customized in the System config tab of the hawkBit interface) to know if an update is available. When that happens, the update will be downloaded and applied, the system will reboot, and at the next boot the update will be confirmed as successful, showing this status in the hawkBit interface:

hawkBit upgrade confirmed

If you’ve reached this step, your system has been successfully updated, congratulations! Of course, there are many more things to do to get a proper swupdate/hawkBit deployment: assign unique device IDs (for example based on MAC addresses or SoC serial number), implement proper authentication between the swupdate client and the server, implement image encryption if necessary, improve the upgrade validation mechanism to make sure it detects if the new image doesn’t boot properly, etc.

Conclusion

In this blog post, we have learned about firmware upgrade solutions, and specifically about swupdate. We’ve seen how to set up swupdate in the context of Buildroot, first for local updates, and then for remote updates using the hawkBit management interface. Hopefully this will be useful for your future embedded projects!

As usual, the complete Buildroot code to reproduce the same setup is available in our branch 2019.02/stm32mp157-dk-blog-7, in two commits: one for the first step implementing support just for local updates, and another one for remote update support.

Bootlin at Embedded World 2020

STMicro at Embedded World 2020Bootlin will be preent at Embedded World 2020, in Nuremberg on February 25-27. We will be present on STMicroelectronics booth in hall 4A, stand 138. We will have two demos of the STM32MP1 platform running Linux, and of course details about Bootlin services around embedded Linux and Linux kernel development and training.

Three people from Bootlin will be present: Michael Opdenacker (CEO), Thomas Petazzoni (CTO) and Alexandre Belloni (embedded Linux engineer and trainer).

Embedded World 2020

Do not hesitate to get in touch with us prior to the event if you would like to schedule a meeting to discuss business, project or career opportunities.

Linux 5.5 released, Bootlin contributions inside

Linux 5.5 was recently released, as usual bringing a large number of new features and improvements, which are nicely detailed in the LWN articles on merge window part 1 and merge window part 2, but also on the Kernelnewbies wiki.

According to the statistics, a total of 14350 changes were made to this kernel release, to which Bootlin contributed 124 patches, making us the 19th contributing company by number of commits. Here are the highlights of our contributions:

  • By far and large our most important achievement in Linux 5.5 is the merge of the H265 decoding support in the Allwinner VPU driver, developed by Paul Kocialkowski. This was the last missing feature to complete the effort funded by the Kickstarter campaign we launched in February 2018. See our blog post wrapping up the Allwinner VPU work.
  • Alexandre Belloni as the RTC subsystem maintainer, as usual contributed a large number of RTC driver improvements and fixes.
  • Antoine Ténart contributed some improvements to the Cadence MACB driver, most notably used as the Ethernet controller driver on Microchip/Atmel platforms. The main improvement is the conversion to the phylink subsystem for the interaction with the Ethernet PHY.
  • Grégory Clement contributed numerous enhancements to the Microchip/Atmel SPI controller driver, mainly aimed at fixing and improving the support for Chip Select, both native Chip Selects and GPIO-based Chip Selects.
  • Kamel Bouhara contributed a few additional Device Tree files to describe home automation hardware platforms from Overkiz, based on the Microchip SAMA5D2 processor, as well as an improvement to a Microchip SoC driver that allows to expose the platform serial number to user-space.
  • Miquèl Raynal added support for a new Marvell system-on-chip called Marvell CN9130. Despite the name, this chip is from a hardware point of view in the same family as the Marvell Armada 7K and 8K, which were already supported upstream.
  • Miquèl Raynal contributed a number of fixes and improvements to the Macronix SPI controller driver.
  • Miquèl Raynal added support for the ADC converters over SPI MAX1227, MAX1229 and MAX1231 to the existing max1027 IIO driver in the kernel. These ADCs have a 12-bit resolution.
  • Miquèl Raynal improved the SPI controller driver for the Zynq system-on-chips to correctly support multiple Chip Selects.

In addition to these direct contributions, some of the Bootlin engineers are also Linux kernel maintainers and therefore review and merge patches from other contributors: Alexandre Belloni as the RTC subsystem maintainer and Microchip platform co-maintainer reviewed and merged 45 patches from other contributors, Miquèl Raynal as the MTD subsystem co-maintainer reviewed and merged 39 patches from other contributors and Grégory Clement as the Marvell platform co-maintainer reviewed and merged 29 patches from other contributors.

Here is the detail of our contributions:

Building a Linux system for the STM32MP1: implementing factory flashing

After several months, it’s time to resume our series of blog posts about building a Linux system for the STM32MP1 platform. After showing how to build a minimal Linux system for the STM32MP157 platform, how to connect and use an I2C based pressure/temperature/humidity sensor and how to integrate Qt5 in our system, how to set up a development environment to write our own Qt5 application and how to develop a Qt5 application, we will now cover the topic of factory flashing.

List of articles in this series:

  1. Building a Linux system for the STM32MP1: basic system
  2. Building a Linux system for the STM32MP1: connecting an I2C sensor
  3. Building a Linux system for the STM32MP1: enabling Qt5 for graphical applications
  4. Building a Linux system for the STM32MP1: setting up a Qt5 application development environment
  5. Building a Linux system for the STM32MP1: developing a Qt5 graphical application
  6. Building a Linux system for the STM32MP1: implementing factory flashing
  7. Building a Linux system for the STM32MP1: remote firmware updates

What is factory flashing ?

So far, we have used a microSD card as storage for the Linux system running on the STM32MP1 platform. Since this media is removable, we can easily switch the microSD card back and forth between the STM32MP1 platform and our development workstation, which is nice during development and debugging.

However, an actual product will most likely use some form of non-removable persistent storage, typically an eMMC or a NAND flash. While not available on the STM32MP1-DK1 board probably for cost reasons, these storage devices are very common in most embedded systems. For example, the STM32MP157A-EV1 board provides three non-removable persistent storage devices: a 4 GB eMMC, a 1 GB NAND flash, and a 64 MB QSPI NOR flash.

When such storage devices are shipped by their manufacturer, they are typically empty. Therefore, as part of the manufacturing process of your embedded systems, you will have to load the relevant storage device with your Linux system, applications and data, so that the embedded system is fully operational: this is the process referred to as factory flashing in this blog post.

If you are doing a very high volume product, you can ask your eMMC or NAND flash vendor to pre-load a system image on the storage before it is shipped to you and assembled on your board. However, many companies do products with volumes that are not large enough to make such a strategy possible: in this case, you really receive an empty storage device, and have to flash it.

A first possibility to flash the non-removable storage is to use a removable storage device, boot a Linux system on the device, and use it to flash the non-removable storage. This can definitely be a possible option in some situations, but it is not always possible (if there’s no removable storage device interface at all) or not always practical.

However, most system-on-chips, including the STM32MP1 include some ROM code that the processor executes at boot time, even before it loads the first stage bootloader. This ROM code is primarly responsible for loading the first stage bootloader into memory, but it also very often offers a communication channel with the outside world, which can be used to gain control of a platform that has nothing at all on its storage. This communication channel is typically over USB or UART, and most often uses a custom, vendor-specific protocol, which is understood by vendor-specific tools. This protocol generally allows to send some code to the target and get it executed, which is sufficient to be able to reflash the target device.

Here are a few examples with system-on-chips from various vendors:

  • The ROM code of the NXP i.MX processors implements a USB-based protocol, which can be interfaced either using the NXP-provided mfgtools, or using the community-developed imx_usb_loader. The latter was presented in one of our earlier blog posts about i.MX6 factory flashing.
  • The ROM code of Microchip SAMA5 processors implements a USB-based protocol, which can be interfaced using a tool called SAM-BA
  • The ROM code of Rockchip processors implements a USB-based protocol, which can be interfaced either using a Rockchip-specific tool called rkdeveloptool
  • The ROM code of the ST STM32MP15 processors also implement a USB-based protocol, which can be interfaced using the STM32 Cube Programmer

Obviously, in this blog post, we are going to use the latter, STM32 Cube Programmer, to flash our STM32MP1 platform. Since the DK2 board only has a removable device, we will use the tool to flash the SD card, but the process and logic would be the same for any other (non-removable) storage device.

Getting and installing STM32 Cube Programmer

While ST generally has very good upstream and open-source support for its products, the STM32 Cube Programmer unfortunately doesn’t follow this strategy: you need to be registered on the ST web site to download it, and its source code is not available. Due to this registration process, we for example cannot create a Buildroot package that would automatically download and install this tool for you.

So, follow the process to create an account on the ST web site, and then go to the STM32 Cube Programmer page. At the time of this writing, the latest version is 2.2.1, but according this Wiki page, this version doesn’t work for the STM32MP1 platform. Instead, select to download the 2.2.0 version, which is known to work. You will then download a file called en.stm32cubeprog.zip (it doesn’t have the version in its name, which isn’t great) weighting 187 MB, and which has the SHA256 hash 91107b4d605d126f5c32977247d7419d42abb2655848d2d1a16d52f5f7633d2d.

Extract this ZIP file somewhere in your system, and then run the SetupSTM32CubeProgrammer-2.2.0.linux executable:

$ ./SetupSTM32CubeProgrammer-2.2.0.linux

Got through the installation steps. On our system, we customized the installation path to be just $HOME/stm32cube, and the remainder of this blog post will assume this is where you installed the STM32 Cube Programmer.

In this blog post, we are only going to use the command line interface (CLI) of STM32 Cube Programmer, so just make sure you can run the corresponding tool:

$ ~/stm32cube/bin/STM32_Programmer_CLI
      -------------------------------------------------------------------
                        STM32CubeProgrammer v2.2.0
      -------------------------------------------------------------------


Usage :
STM32_Programmer_CLI.exe [command_1] [Arguments_1][[command_2] [Arguments_2]...]
[...]

Testing the communication with the board

On the back of the board, there is a two-way DIP switch labeled SW1, which is used to configure the boot mode. When both are “ON”, the board boots from the SD card. When both are “OFF”, the board enters the “USB boot for flashing mode”, which is what we are going to use. So switch both switches to OFF, and reset the board.

Plug an additional USB-C cable from the board CN7 connector (which is located between the HDMI port and the 4 USB host ports).

USB-C connection for factory flashing

Then, reset the board. If you run lsusb on your Linux workstation, you should see a new device:

Bus 003 Device 011: ID 0483:df11 STMicroelectronics STM Device in DFU Mode

Then, you can ask STM32_Programmer_CLI to list the devices it sees over USB. This needs root permissions (unless appropriate udev rules are created):

$ sudo ~/stm32cube/bin/STM32_Programmer_CLI -l usb
      -------------------------------------------------------------------
                        STM32CubeProgrammer v2.2.0
      -------------------------------------------------------------------

=====  DFU Interface   =====

Total number of available STM32 device in DFU mode: 1

  Device Index           : USB1
  USB Bus Number         : 003
  USB Address Number     : 003
  Product ID             : DFU in HS Mode @Device ID /0x500, @Revision ID /0x0000
  Serial number          : 004200343338510534383330
  Firmware version       : 0x0110
  Device ID              : 0x0500

Good, the STM32CubeProgrammer tool is seeing our board, and we see that the Device Index is USB1. Keep that in mind for the next steps.

Change the Linux system boot chain

STM32CubeProgrammer works by sending a U-Boot bootloader over USB, and then talking to this U-Boot to make it erase the MMC or NAND flash, and make it write some data to those storage devices. However, for some reason, STM32CubeProgrammer doesn’t work with the boot flow we have used so far, which uses the U-Boot SPL as the first-stage bootloader, and U-Boot itself as the second stage bootloader. It only works when the first stage bootloader is the Arm Trusted Firmware, also called TF-A. You can get more details about the different possible boot chains on STM32MP1 on this Wiki page.

Due to this constraint, we are going to switch our Buildroot configuration to use TF-A instead of U-Boot SPL as the first stage bootloader.

First of all, we need to backport two Buildroot commits, which did not exist in the Buildroot 2019.02 we are using, but have been integrated later. The first commit, 9dbc934217e170578d4cbfdf524bc1b3988d0b9e allows to build TF-A for ARM 32-bit platforms, while the second commit, e4d276c357fdf9f19f99f826cab63f373687f902 allows to provide a custom name for the TF-A image name.

In Buildroot, do:

$ git cherry-pick 9dbc934217e170578d4cbfdf524bc1b3988d0b9e
$ git cherry-pick e4d276c357fdf9f19f99f826cab63f373687f902

The second one will cause some minor conflict in boot/arm-trusted-firmware/Config.in. Resolve the conflict by removing the BR2_TARGET_ARM_TRUSTED_FIRMWARE_DEBUG option from this file, remove the conflict markers, then run:

git add boot/arm-trusted-firmware/Config.in
git commit

If you’re not sure about this, you can check our 2019.02/stm32mp157-dk-blog-6 branch on Github, which has these changes already integrated.

Once done, we can run make menuconfig and start modifying the Buildroot configuration. Here are the changes that we need:

  • In the Bootloaders menu, enable ARM Trusted Firmware (ATF), and then:
    • Set ATF Version to Custom Git repository
    • Set URL of custom repository to https://github.com/STMicroelectronics/arm-trusted-firmware.git
    • Set Custom repository version to v2.0-stm32mp-r2
    • Set ATF platform to stm32mp1
    • Set Additional ATF build variables to DTB_FILE_NAME=stm32mp157c-dk2.dtb AARCH32_SP=sp_min. The DTB_FILE_NAME selects the correct Device Tree file for the DK2 board, while the AARCH32_SP indicates that we are using the “minimal” secure payload, and not a complete Trusted Execution Environment such as OP-TEE.
    • Set Binary boot images to *.stm32. This makes sure the final image gets copied to output/images.
  • Still in the Bootloaders menu, inside the U-Boot option, make the following changes:
    • Change Board defconfig to stm32mp15_trusted. This is the most important change, which makes U-Boot build only the second stage, and in a format that gets loaded by TF-A as the first stage.
    • In U-Boot binary format, disable u-boot.img, and instead enable Custom (specify below) and indicate u-boot.stm32 as the value for U-Boot binary format: custom names.
    • Disable the Install U-Boot SPL binary image option.

Overall, the diff of the changes in the configuration looks like this:

@@ -30,16 +30,22 @@ BR2_TARGET_ROOTFS_EXT2=y
 BR2_TARGET_ROOTFS_EXT2_4=y
 BR2_TARGET_ROOTFS_EXT2_SIZE="120M"
 # BR2_TARGET_ROOTFS_TAR is not set
+BR2_TARGET_ARM_TRUSTED_FIRMWARE=y
+BR2_TARGET_ARM_TRUSTED_FIRMWARE_CUSTOM_GIT=y
+BR2_TARGET_ARM_TRUSTED_FIRMWARE_CUSTOM_REPO_URL="https://github.com/STMicroelectronics/arm-trusted-firmware.git"
+BR2_TARGET_ARM_TRUSTED_FIRMWARE_CUSTOM_REPO_VERSION="69cc28c5a1b877cf67def7f94dece087f3917b1c"
+BR2_TARGET_ARM_TRUSTED_FIRMWARE_PLATFORM="stm32mp1"
+BR2_TARGET_ARM_TRUSTED_FIRMWARE_ADDITIONAL_VARIABLES="DTB_FILE_NAME=stm32mp157c-dk2.dtb AARCH32_SP=sp_min"
+BR2_TARGET_ARM_TRUSTED_FIRMWARE_IMAGES="*.stm32"
 BR2_TARGET_UBOOT=y
 BR2_TARGET_UBOOT_BUILD_SYSTEM_KCONFIG=y
 BR2_TARGET_UBOOT_CUSTOM_GIT=y
 BR2_TARGET_UBOOT_CUSTOM_REPO_URL="https://github.com/STMicroelectronics/u-boot.git"
 BR2_TARGET_UBOOT_CUSTOM_REPO_VERSION="v2018.11-stm32mp-r2.1"
-BR2_TARGET_UBOOT_BOARD_DEFCONFIG="stm32mp15_basic"
+BR2_TARGET_UBOOT_BOARD_DEFCONFIG="stm32mp15_trusted"
 BR2_TARGET_UBOOT_CONFIG_FRAGMENT_FILES="board/stmicroelectronics/stm32mp157-dk/uboot-fragment.config"
 # BR2_TARGET_UBOOT_FORMAT_BIN is not set
-BR2_TARGET_UBOOT_FORMAT_IMG=y
-BR2_TARGET_UBOOT_SPL=y
-BR2_TARGET_UBOOT_SPL_NAME="spl/u-boot-spl.stm32"
+BR2_TARGET_UBOOT_FORMAT_CUSTOM=y
+BR2_TARGET_UBOOT_FORMAT_CUSTOM_NAME="u-boot.stm32"
 BR2_TARGET_UBOOT_CUSTOM_MAKEOPTS="DEVICE_TREE=stm32mp157c-dk2"
 BR2_PACKAGE_HOST_GENIMAGE=y

Before we can restart the build, we need to adjust the genimage.cfg file that describes the layout of the SD card. Indeed, the file name of the first stage bootloader is now tf-a-stm32mp157c-dk2.stm32 instead of u-boot-spl.stm32 and the file name of the second stage bootloader is now u-boot.stm32 instead of u-boot.img. All in all, your genimage.cfg file in board/stmicroelectronics/stm32mp157-dk/genimage.cfg should now look like this:

image sdcard.img {
	hdimage {
		gpt = "true"
	}

	partition fsbl1 {
		image = "tf-a-stm32mp157c-dk2.stm32"
	}

	partition fsbl2 {
		image = "tf-a-stm32mp157c-dk2.stm32"
	}

	partition ssbl {
		image = "u-boot.stm32"
	}

	partition rootfs {
		image = "rootfs.ext4"
		partition-type = 0x83
		bootable = "yes"
		size = 256M
	}
}

With this in place, it’s time to restart the build. You can do a complete rebuild with make clean all, or you can just clean up U-Boot, and restart the build:

$ make uboot-dirclean
$ make

You should now have in output/images the new TF-A image tf-a-stm32mp157c-dk2.stm32 and the new U-Boot image u-boot.stm32. Of course the sdcard.img file has been updated.

Rather than updating our SD card on our workstation, we’ll directly use the STM32CubeProgrammer tool to do that, in the next section.

Flashing the board

The STM32CubeProgrammer tool takes as input a flash layout file, which has a .tsv extension. The format of this file is extensively documented on this Wiki page. It is essentially a text file that says what should be flashed in each partition.

In our case, we are going to simply flash the entire sdcard.img instead of flashing partition by partition. To achieve this, we are going to use the RawImage image type, also described on the Wiki page.

Let’s create a file board/stmicroelectronics/stm32mp157-dk/flash.tsv, with the following contents:

#Opt	Id	Name	Type	IP	Offset	Binary
-	0x01	fsbl1-boot	Binary	none	0x0	tf-a-stm32mp157c-dk2.stm32
-	0x03	ssbl-boot	Binary	none	0x0	u-boot.stm32
P	0x10	sdcard	RawImage	mmc0		0x0	sdcard.img

The first line is a comment, just to help remember what each field is about. The second and third lines tell STM32CubeProgrammer which bootloader images should be used as part of the flashing process. Finally, the last line says we want to flash sdcard.img as a raw image on the mmc0 device.

Then, go do output/images, and run STM32CubeProgrammer. We use the -c port=usb1 argument, because our board was detected as device USB1 when we enumerated all detected devices using the -l usb previously.

$ cd output/images/
$ sudo ~/stm32cube/bin/STM32_Programmer_CLI -c port=usb1 -w ../../board/stmicroelectronics/stm32mp157-dk/flash.tsv

The output will look like this:

      -------------------------------------------------------------------
                        STM32CubeProgrammer v2.2.0                  
      -------------------------------------------------------------------



USB speed   : High Speed (480MBit/s)
Manuf. ID   : STMicroelectronics
Product ID  : DFU in HS Mode @Device ID /0x500, @Revision ID /0x0000
SN          : 004200343338510534383330
FW version  : 0x0110
Device ID   : 0x0500
Device name : STM32MPxxx
Device type : MPU
Device CPU  : Cortex-A7


Start Embedded Flashing service



Memory Programming ...
Opening and parsing file: tf-a-stm32mp157c-dk2.stm32
  File          : tf-a-stm32mp157c-dk2.stm32
  Size          : 237161 Bytes
  Partition ID  : 0x01 

Download in Progress:
[==================================================] 100% 

File download complete
Time elapsed during download operation: 00:00:00.444

RUNNING Program ... 
  PartID:      :0x01 
Start operation done successfully at partition 0x01

Flashlayout Programming ...
[==================================================] 100% 
Running Flashlayout Partition ...
Flashlayout partition started successfully


Memory Programming ...
Opening and parsing file: u-boot.stm32
  File          : u-boot.stm32
  Size          : 748042 Bytes
  Partition ID  : 0x03 

Download in Progress:
[==================================================] 100% 

File download complete
Time elapsed during download operation: 00:00:00.791

RUNNING Program ... 
  PartID:      :0x03 

reconnecting the device ...

USB speed   : High Speed (480MBit/s)
Manuf. ID   : STMicroelectronics
Product ID  : USB download gadget@Device ID /0x500, @Revision ID /0x0000
SN          : 004200343338510534383330
FW version  : 0x0110
Device ID   : 0x0500
Start operation done successfully at partition 0x03


Memory Programming ...
Opening and parsing file: sdcard.img
  File          : sdcard.img
  Size          : 539002368 Bytes
  Partition ID  : 0x10 

Download in Progress:
[==================================================] 100% 

File download complete
Time elapsed during download operation: 00:04:31.583

RUNNING Program ... 
  PartID:      :0x10 
Start operation done successfully at partition 0x10
Flashing service completed successfully

Finally, we can toggle back the SW1 DIP switches to their ON position, to boot again from SD card, and hit the reset button. The board should boot, but this time with our new image, which uses TF-A instead of U-Boot SPL, so the first lines of the boot process should look like this:

NOTICE:  CPU: STM32MP157CAC Rev.B
NOTICE:  Model: STMicroelectronics STM32MP157C-DK2 Discovery Board
NOTICE:  Board: MB1272 Var2 Rev.C-01
NOTICE:  BL2: v2.0-r2.0(release):
NOTICE:  BL2: Built : 16:10:53, Jan  7 2020
NOTICE:  BL2: Booting BL32
NOTICE:  SP_MIN: v2.0-r2.0(release):
NOTICE:  SP_MIN: Built : 16:10:53, Jan  7 2020

U-Boot 2018.11-stm32mp-r2.1 (Jan 07 2020 - 16:13:55 +0100)

Conclusion

In this article, we have discussed the concept of factory flashing, understood better the different boot chains available for the STM32MP1, switched to a boot chain using TF-A, and presented how to use STM32CubeProgrammer to reflash the entire SD card.

As usual, we have a branch on Github with the Buildroot changes corresponding to this blog post, see the branch 2019.02/stm32mp157-dk-blog-6.

Stay tuned for the next article in this series of blog post, in which we will cover the topic of Over-The-Air firmware update.

2019 at Bootlin, a year in review

First of all, the entire team at Bootlin wishes you a Happy New Year, and best wishes for 2020 in your personal and professional life. The beginning of the new year is a good time to look back and see the achievements of the past year, which is why we review the 2019 year in terms of Bootlin news and activity.

Linux kernel contributions

In 2019, we made contributions to Linux 5.0, Linux 5.1, Linux 5.2, Linux 5.3 and Linux 5.4. We contributed a total of 1078 patches to these releases.

Some of the highlights were:

  • The brand new subsystem to support the MIPI I3C bus that we developed from scratch was merged in Linux 5.0. This paved the way to support both I3C controllers and I3C devices in Linux. See our blog post.
  • The Marvell Ethernet controller driver was extended to support packet classification offloading in hardware.
  • A brand new driver in the IIO subsystem for the TI ADS8344 ADC chip.
  • Support for HW-accelerated H264 video decoding was added to the Allwinner VPU driver, as part of our crowd-funded project, see our recent blog post.
  • Numerous improvements in the support of Allwinner, Microchip and Marvell platforms, see our blog posts for each kernel release for more details.

Other contributions

  • We contributed 52 patches to the U-Boot project in 2019: a new network driver the Microsemi Ocelot platform, improvements to the MTD subsystem, fixes to the NXP LPC3250 and Rockchip PX30 platform support.
  • We contributed 314 patches to the Buildroot project, our most significant contribution is support for top-level parallel build, which will land in the upcoming Buildroot 2020.02 release. In addition, Bootlin engineer Thomas Petazzoni remains an active Buildroot co-maintainer: in 2019 he reviewed and merged 2924 patches from other contributors, out of the total of 5503 patches merged throughout the year.
  • We improved our Web-based Elixir code browser. Elixir now indexes the sources of 16 projects, allows to browse various types of include files, has support for project specific HTML post-processing filters, has a new REST API (thanks to Carmeli Tamir), and has many fixed bugs. All this activity corresponds to a round number of commits: 128.

Engineering projects

Of course, most of the contributions described above are driven by the engineering projects we have with our customers worldwide. Here are some of the significant engineering projects we worked on in 2019:

  • Implemented support for MACsec hardware offloading, and support for this functionality for the Microchip VSC8584 Ethernet PHY. We presented this work in detail in a blog post, and submitted 4 iterations in 2019 and hope to see this merged in early 2020.
  • Improved the Intel GMA500 display driver to support page flipping, so that one of our customers can use the Weston Wayland compositor on hardware platforms that use this display controller.
  • Started a project to support the Microchip VSC8572 Ethernet PHY in Linux, used as a pass-through to SFP cages. As part of this project, we already contributed patches to convert the cpsw network driver to phylink, and we will contribute VSC8572 patches once the project has made enough progress.
  • Migrated a complete Buildroot-based BSP for a Danish customer in the healthcare industry: migration to a newer Linux kernel version and a newer Buildroot version for a Microchip AT91SAM9G45 platform and a TI AM335x platform.
  • Migrated a complete Yocto-based BSP for a Belgian customer to a newer mainline version of the Linux kernel for an i.MX6 platform, implemented secure boot and optimized the boot time.
  • For a major US customer, implemented a complete Linux BSP for a custom Xilinx Zynq 7000 platform: upstream U-Boot, upstream Linux and Yocto-based build system. As part of this project, we did a number of kernel contributions and we still have a major kernel contribution pending: a complete DRM driver for the logiCVC display controller.
  • For a German customer in the healthcare industry, continued to support additional hardware features of an i.MX6 platform, and built a complete new BSP for an SAMA5D3-based hardware platform.
  • For a Canadian customer, completely upgraded the Linux BSP for a NXP LPC3250 platform: update to U-Boot upstream, to Linux upstream, and migration to Buildroot as a build system.
  • For an Italian customer, started a brand new BSP for a Rockchip PX30 based platform, which will require a number of improvements and additions to the Linux kernel support for this platform, which we will work on in 2020.
  • For a Belgian customer, migrated a Linux BSP for an OMAP44xx platform with complex audio interfaces to a recent upstream Linux kernel version.
  • For a French customer, implemented and delivered a complete Yocto-based Linux BSP for an i.MX6 platform.
  • For the French company Overkiz, updated, cleaned-up and upstreamed to the Linux kernel the Device Tree files for their Microchip SAMA5 home automation platforms.
  • Implemented support for software-based ECC and external hardware ECC engines in the SPI flash subsystem of the Linux kernel, for one of our customers that manufactures flash chips. This patch series is still under review, but we expect to get it merged in early 2020.
  • Implemented support for dm-verity and SELinux in OpenWRT, for one of our customers. See our blog post.
  • Continued to work on implementing top-level parallel build in Buildroot, which finally got merged at the end of 2019 in upstream Buildroot.
  • Continued to work on improving the support for Microchip ARM processors and Marvell Armada ARM processors in the Linux kernel, in many areas.
  • For a customer building a complex audio product based on an Allwinner system-on-chip, we implemented support for TDM in the Allwinner audio interface driver and used it in conjunction with PDM microphones.
  • Published a long series of blog posts on how to create a Linux system with Buildroot for the STM32MP1 platform: part 1, part 2, part 3, part 4 and part 5. This series will continue in 2020.
  • Completed the work on the Allwinner VPU that was funded by the Kickstarter campaign of early 2018: the Allwinner VPU driver was merged, with MPEG2, H264 and H265 decoding support, see our blog post.
  • Continued to work on the support for the RaspberryPi platforms, making a number of enhancements to the display support and its testing, as we reported in a blog post.

Training

Our training business has seen quite a bit of activity in 2019:

  • We created and published a new training course: Displaying and rendering graphics with Linux. This 2-day course, created by Bootlin engineer Paul Kocialkowski provides a detailed walk-through of Linux graphics: graphics hardware and theory, low-level support in the Linux kernel, support in user-space in Wayland or X.org, OpenGL acceleration, etc. This course is available on-site and we already delivered it to customers in Spain, Portugal and France.
  • Our Embedded Linux and Yocto/OpenEmbedded training courses have been ported to use the STM32MP1 platform for practical labs, and we became a member of the STMicroelectronics Partner Program. The support for STM32MP1 in our training courses is proposed as an alternative to the Microchip SAMA5D3 platform (for the Embedded Linux training) and the BeagleBone Black (for the Yocto training) that we continue to support as well.
  • Thanks to funding from Zuehlke Engineering in Serbia, we expanded our Linux boot time optimization training course to 3 days, adding much more lecture and lab content, and collecting useful benchmarks that we later shared in the Embedded Linux Conference Europe.
  • Overall our publicly available training materials have received 376 commits during the course of 2019, all visible in their GitHub repository.
  • We delivered many of our on-site training courses in France, India, Spain, Serbia, Poland, Finland, Portugal, Nederlands and Austria, and continued to offer our training courses in public sessions in Avignon, France.

Conferences

As usual in 2019, we attended and participated to a number of conferences:

  • Our networking experts Antoine Ténart and Maxime Chevallier attended the Netdev 0x13 conference in Prague.
  • Bootlin engineer Alexandre Belloni attended the SiFive Tech Symposium about the RISC-V architecture, in Grenoble.
  • A significant part of our engineering team attended the Linux Plumbers conference in Lisbon.
  • Bootlin engineer Grégory Clement attended the Kernel Recipes conference in Paris.
  • Our display/video expert Paul Kocialkowski attended the X.org Developers Conference, in Montreal.
  • And of course, we attended the Embedded Linux Conference Europe 2019. We gave 5 talks and 2 tutorials at this event (see our blog post) and shared our selection of talks.
  • We participated to the Capitole du Libre conference in Toulouse, where Michael Opdenacker gave a talk on Embedded Linux from scratch in 40 minutes (on RISC-V).
  • Participated to the Buildroot Developers Meeting throughout the year: after FOSDEM 2019 and before ELCE 2019. See our report from the FOSDEM meeting.
  • Recruiting

    • An additional engineer joined our team in Lyon: Kamel Bouhara. Kamel is now working with our senior engineers Grégory Clement and Alexandre Belloni in this office.
    • During the summer 2019, Victor Huesca joined Bootlin as an intern in Toulouse, and worked on improving the tooling used for the maintenance of the Buildroot project. All the work done by Victor is now used by the Buildroot community, see our blog post for more details.
    • An additional engineer will join our Toulouse office at the end of January 2020, and 3 interns will also join Bootlin during the first half of 2020, working on improving the Elixir Cross Referencer, and contributing to Linux and U-Boot.
    • We still have positions opened for Embedded Linux and kernel engineers, see job offer.

Wrapping up the Allwinner VPU crowdfunded Linux driver work

Back in early 2018, Bootlin started a crowd-funding campaign to fund the development of an upstream Linux kernel driver for the VPU found in Allwinner processors. Thanks to the support from over 400 contributors, companies and individuals, we have been able to bring support for hardware-accelerated video decoding in the mainline Linux kernel for Allwinner platforms.

From April 2018 to end of 2019, Paul Kocialkowski and Maxime Ripard at Bootlin worked hard on developing the driver and getting it accepted upstream, as well as developing the corresponding user-space components. We regularly published the progress of our work on this blog.

As of the end of 2019, we can say that all the goals defined in the Kickstarter have been completed:

  • We have an upstream Linux kernel for the Allwinner VPU, in drivers/staging/media/sunxi/cedrus, which supports MPEG2 decoding (since Linux 4.19), H264 decoding (since Linux 5.2) and H265 decoding (will be in the upcoming Linux 5.5)
  • We have a user-space VA-API implementation called libva-v4l2-request, and which allows to use any Linux kernel video codec based on the request API.
  • We have enabled the Linux kernel driver on all platforms we listed in our Kickstarter campaign: A13/A10S/A20/A33/H3 (since Linux 4.19), A64/H5 (since Linux 4.20), A10 (since Linux 5.0) and H6 (since Linux 5.1, contributed by Jernej Skrabec)

This means that the effort that was funded by the Kickstarter campaign is now over, and from now on, we are operating in maintenance mode regarding the cedrus driver: we are currently not actively working on developing new features for the driver anymore.

The Cedrus Linux driver in action

Of course, there are plenty of additional features that can be added to the driver: support for H264 encoding, support for high-profile H264 decoding, support for other video codecs. Bootlin is obviously available to develop those additional features for customers, do not hesitate to contact us if you are interested.

Overall, we found this experience of funding upstream Linux kernel development through crowd-funding very interesting and we’re happy to have been successful at delivering what was promised in our campaign. Looking at the bigger picture, the Linux userspace API for video decoding with stateless hardware codecs in V4L2 has been maturing for a while and is getting closer and closer to being finalized and declared a stable kernel API: this project has been key in the introduction of this API, as cedrus was the first driver merged to require and use it. Additional drivers are appearing for other stateless decoding engines, such as the Hantro G1 (found in Rockchip, i.MX and Microchip platforms) or the rkvdec engine. We are of course also interested in working on support for these VPUs, as we have gained significant familiarity with all things related to hardware video decoding during the cedrus adventure.

Linux 5.4 released, Bootlin contributions inside

LinuxThis time around, we’re quite late to the party, but Linux 5.4 was indeed released a number of weeks ago, and once again, Bootlin contributed a number of patches to this Linux kernel release. As usual, the most useful source of information to learn about the major features brought by Linux 5.4 are the LWN articles (part 1, part 2) and the KernelNewbies Wiki.

With a total of 143 patches contributed to this release, Bootlin is the 17th contributing company by number of commits acccording to the Linux Kernel Patch Statistic.

Here are the highlights of our contributions:

  • Antoine Ténart contributed support for IEEE 1588 Precision Time Protocol (PTP) to the Microsemi Ocelot Ethernet switch driver, which Bootlin developed and upstreamed in 2018 (see our blog post)
  • In the MTD subsystem, a number of contributions to the spi-nor support, written originally by Boris Brezillon, made their way upstream.
  • In the support of Microchip (formerly Atmel) platforms, Kamel Bouhara, who joined Bootlin in September 2019, sees his first kernel contribution merged as a Bootlin engineer: dropping useless support for platform_data from the Atmel PWM driver.
  • In the support of Allwinner platforms
    • Maxime Ripard contributed a brand new driver for the Allwinner A10 camera interface driver, a driver that we started at Bootlin for the CHIP platform back in the days, and that we finished more recently.
    • Maxime Ripard contributed a significant number of improvements to the sun4i-i2s audio interface driver, especially TDM support, which was developed as part of a customer project at Bootlin.
    • Maxime Ripard also contributed numerous enhancements to Allwinner platform Device Tree files, especially in the area of using YAML schemas.
  • In the support for Marvell platforms
    • Grégory Clement added cpufreq support to the Marvell Armada 7K/8K platform by extending some of its clock drivers.
    • Miquèl Raynal contributed improvements to the Marvell CP110 COMPHY driver, which is used to control SERDES lanes on the Marvell Armada 7K/8K platforms, and added the description of the SERDES lanes used by various IP blocks in those processors.
  • Alexandre Belloni, as the RTC subsystem maintainer, did a number of fixes and improvements in several RTC drivers (mainly pcf2123 and pcf8563)
  • For the LPC3250 platform, for which Bootlin delivered a modern BSP to a customer last year, Alexandre Belloni fixed an issue in the lpc_eth network driver, which was preventing the system from booting if the network had been initialized by the bootloader.

In addition to being contributors, some Bootlin engineers are also maintainers of various parts of the Linux kernel, and as such review and merge code from other contributors:

  • As the RTC subsystem maintainer and Microchip platform co-maintainer, Alexandre Belloni merged 47 patches from other contributors
  • As the MTD subsystem co-maintainer, Miquèl Raynal merged 33 patches from other contributors
  • As the Marvell platform co-maintainer, Grégory Clement merged 11 patches from other contributors

Here are the details of all our contributions to Linux 5.4:

Security contributions to OpenWrt: dm-verity and SELinux

OpenWrtWhile Bootlin is largely known for its expertise with the Buildroot and Yocto/OpenEmbedded build systems, we do also work with other build systems for customer projects. Specifically, in 2019, we have worked for one of our customers on extending OpenWrt to add support for two security features: dm-verity and SELinux, which we have contributed to upstream OpenWrt. In this blog post, we provide some details about those features, and how they are integrated in OpenWrt.

dm-verity support

dm-verity is a device mapper target that allows to create a block device on top of an existing block device, with a transparent integrity checking in-between. Provided a tree of per-block hashes that is generated offline, dm-verity will verify at run-time that all the data read from the underlying block device matches the hashes that are provided. This allows to guarantee that the data has not been modified, as a root hash must be passed from a trusted source when setting up the dm-verity block device at boot time. If any bit in the storage has been modified, the verification of the hashes all the way up to the root hash will fail, and the I/O operation on the block of data being read from storage will be rejected. Therefore, dm-verity is typically used as part of a secure boot strategy, which allows the root hash to be passed by the bootloader to the kernel, where the bootloader and kernel themselves are verified by other means. Also, due to the nature of the integrity verification, dm-verity provides a read-only block device, and will therefore only work with read-only filesystems.

dm-verity was also presented in our Secure Boot from A to Z talk the Embedded Linux Conference 2018, from slide 28.

dm-verity in "Secure Boot from A to Z"

We implemented an integration of this mechanism in OpenWrt, and contributed a first version back in March, and we just sent a second version in November.

In essence, our integration consists in:

  1. Packaging the different tools that are needed to generate at build time the tree of hashes corresponding to a given filesystem image. The important package here is cryptsetup (patch 05/12), but it requires packaging a few dependencies: libjson-c (patch 04/12), popt (patch 03/12), lvm2 (patch 02/12) and libaio (patch 01/12)
  2. Extending the mechanism of OpenWrt to generate FIT images for the kernel so that it can include a U-Boot script (patch 06/12 and patch 08/12). Indeed, we have chosen to embed the root hash information inside the FIT image, as FIT image can be signed and verified by the bootloader before booting, ensuring that the root hash is part of the trusted information.
  3. Extending the squashfs filesystem image generation logic so that a dm-verity-capable image can optionally be generated (patch 09/12). If this is the case, then the squashfs image itself is concatenated with the tree of hashes, and a U-Boot script containing the details of the dm-verity image is generated. This includes the important root hash information.
  4. Backporting to the 4.14 and 4.19 Linux kernels currently supported by OpenWrt the DM_INIT mechanism that is in upstream Linux since 5.1, and which allows to setup a device mapper target at boot time using the dm-mod.create= kernel argument (patch 10/12). This allows to have the root filesystem on a device mapper block device, without the need for an initramfs to setup the device mapper target.
  5. Showing with the example of the Marvell Armada XP GP platform how to enable this mechanism on a specific hardware platform already supported by OpenWrt (patch 11/12 and patch 12/12).

For more details, you can read the cover letter of the patch series.

SELinux support

SELinux logoSELinux is a Linux security module that implements Mandatory Access Control and that is generally pretty infamously known in the Linux user community for being difficult to use and configure. However, it is widely used in security-sensitive systems, including embedded systems and as such, makes sense to see supported in OpenWrt. For example, SELinux is already supported in the Yocto/OpenEmbedded ecosystem through the meta-selinux layer, and in the Buildroot project since 2014, contributed by Collins Aerospace.

In short, the basic principle of SELinux is that important objects in the system (files, processes, etc.) are associated to a security context. Then, a policy defines which operations are allowed, depending on the security context of who is doing the operation and on what the operation takes place. This policy is compiled into a binary policy, which is loaded into the kernel early at boot time, and then enforced by the kernel during the system life. Of course, around this, SELinux provides a wide range of tools and libraries to manipulate the policy, build the policy, debug policy violations, and more.

The SELinux support in OpenWrt comes in two parts: a number of additional packages for various libraries and applications, and some integration work in OpenWrt. We will cover both in the next sections. It is worth mentioning that our work does not provide a SELinux policy specifically modified or adjusted for OpenWrt: we simply use the SELinux reference policy, which users will have to tune to their needs.

SELinux-related packages

Getting SELinux to work required a number of new packages to be added in OpenWrt. Those packages were contributed to the community-maintained package feed at https://github.com/openwrt/packages/. They were initially submitted through the mailing list, and then submitted as a pull request.

In short, it contains:

  • libsepol, the binary policy manipulation library.
  • libselinux, the runtime SELinux library that provides interfaces to ELinux-aware applications.
  • audit, which contains the user space utilities for storing and searching the audit records generated by the audit subsystem of the Linux kernel.
  • libcap-ng, which allows to use the POSIX capabilities, and is needed by policycoreutils.
  • policycoreutils, which is the set of core SELinux utilities such as sestatus, secon, setfiles, load_policy and more.
  • libsemanage, which is the policy management library.
  • checkpolicy, which is the SELinux policy compiler.
  • refpolicy, which is the SELinux reference policy.
  • selinux-python, a number of SELinux tools written in Python, especially audit2allow for policy debugging.

SELinux integration

Our second patch series, for OpenWrt itself, allows to build a SELinux-enabled system thanks to the following changes:

  • Allow to build Busybox with SELinux support, so that all the Busybox applets that support SELinux specific options such as -Z can be built with libselinux (patch 1/7)
  • Add support in OpenWrt’s init application, called procd, for loading the SELinux policy at boot time (patch 2/7). This patch has been submitted separately for integration into the procd project.
  • Add support for building a new host tool called fakeroot (patch 3/7).
  • Add support for building squashfs images with extended attributes generated by SELinux setfiles tool (patch 4/7). This is why fakeroot is needed: writing those extended attributes that store SELinux security contexts require root access, so we run the entire process within a fakeroot environment. This also requires building the squashfs tools with extended attributes support (patch 7/7).
  • Add new options to enable in the Linux kernel support for SELinux and SquashFS with extended attributes (patch 5/7 and patch 6/7).

Conclusion

Integrating those two security features in OpenWrt required numerous changes in the build system, and the corresponding patches are still under review by the OpenWrt community. We hope to see these features merged in 2020.

Linux 5.3 released, Bootlin contributions inside

Penguin from Mylène Josserand
Drawing from Mylène Josserand, based on a picture from Samuel Blanc (https://commons.wikimedia.org/wiki/File:Manchot_royal_-_King_Penguin.jpg)
The 5.3 version of the Linux kernel was released recently. As usual, we recommend our readers to look at the LWN coverage for this release merge window: part 1 and part 2. Together with the KernelNewbies page, these articles give a very nice overview of the major features and improvements of this new release.

For this release, Bootlin is the 16th contributing company by number of commits, with 143 patches merged in the Linux kernel. Our significant contributions this time were:

  • Support for Allwinner processors
    • The support for H264 video decoding, from Maxime Ripard, was finally merged in the cedrus VPU driver that we have developed thanks to the funding of our Kickstarter campaign last year. The last missing piece is H265 video decoding, which we have submitted several times and we hope to get merged soon.
  • Support for Marvell platforms
    • Antoine Ténart contributed a number of bug fixes and updates to the inside-secure crypto driver, which is used for the cryptographic hardware accelerator found on Marvell Armada 3700 and Marvell Armada 7K/8K.
    • Maxime Chevallier contributed many improvements to the mvpp2 network driver, used on the Marvell Armada 375 and Armada 7K/8K systems. His patches improve the traffic classification offloading capabilities, a topic he will present in detail at the next Embedded Linux Conference Europe.
    • Miquèl Raynal added PHY support for the PCIe Armada 8K driver, and adjusted a few things in the Marvell Armada 7K/8K Device Tree files.
  • Support for Microchip MPU (formerly Atmel) platforms
    • Alexandre Belloni converted the remaining SoCs (SAM9x5, SAM9G45, SAM9RL and SAMA5D3) to the new slow clock controller bindings.
    • Antoine Ténart contributed a few small improvements to the macb driver, for the Cadence network controller used on Microchip platforms.
  • Maxime Ripard contributed numerous YAML Device Tree schemas, to help the effort of converting many Device Tree bindings to the new YAML format, which can be used to validate Device Trees against their bindings.
  • Maxime Ripard contributed numerous patches to the core DRM subsystem: a complete rewrite of the command line parser that parses the DRM-related options of the kernel command line, and support for new options. This was done as part of an effort to make sure the upstream Linux kernel can support all the possible options that the downstream RaspberryPi kernel+firmware combination provides to configure the display.
  • Paul Kocialkowski contributed a few improvements to the RaspberryPi vc4 display controller driver, related to buffer allocation.

Also, several of Bootlin engineers are also kernel maintainers, so they review and merge patches from other contributors:

  • Miquèl Raynal as the NAND subsystem maintainer and MTD subsystem co-maintainer, reviewed and merged 51 patches from other contributors
  • Maxime Ripard as the Allwinner platform co-maintainer, reviewed and merged 38 patches from other contributors
  • Alexandre Belloni as the RTC maintainer and Microchip platform co-maintainer, reviewed and merged 36 patches from other contributors
  • Grégory Clement as the Marvell EBU platform co-maintainer, reviewed and merged 9 patches from other contributors

Here is the details of all our contributions, patch by patch:

Building a Linux system for the STM32MP1: developing a Qt5 graphical application

After showing how to build a minimal Linux system for the STM32MP157 platform, how to connect and use an I2C based pressure/temperature/humidity sensor and how to integrate Qt5 in our system, how to set up a development environment to write our own Qt5 application, we are finally going to write our Qt5 application.

List of articles in this series:

  1. Building a Linux system for the STM32MP1: basic system
  2. Building a Linux system for the STM32MP1: connecting an I2C sensor
  3. Building a Linux system for the STM32MP1: enabling Qt5 for graphical applications
  4. Building a Linux system for the STM32MP1: setting up a Qt5 application development environment
  5. Building a Linux system for the STM32MP1: developing a Qt5 graphical application
  6. Building a Linux system for the STM32MP1: implementing factory flashing
  7. Building a Linux system for the STM32MP1: remote firmware updates

Disclaimer

Before we get started in this blog post, it is important to mention that it is not meant to be a full introduction to programming applications with Qt5. This would require much more than a blog post, and the Qt web site has extensive documentation.

Also, we want to make it clear that Bootlin’s core expertise is in low-level embedded Linux development, not in Qt application development. Therefore, our example application may not show the best practices in terms of Qt development. We welcome comments and suggestions from our readers to improve the example used in this blog post.

Reading sensor data

As we’ve seen in a previous article, the sensor data is available by reading the following files:

  • /sys/bus/iio/devices/iio:device2/in_temp_input for the temperature
  • /sys/bus/iio/devices/iio:device2/in_pressure_input for the pressure
  • /sys/bus/iio/devices/iio:device2/in_humidityrelative_input for the humidity

So what we will do is writing a new class called DataProvider, which will read those files once per second, and emit a signal with the 3 values every second. Slots and signals is a fundamental mechanism in Qt, which allows to connect emitters of events to receivers for those events. In our case, the DataProvider class will emit a signal when new sensor values are read, while another class in charge of the graphical UI will receive those signals.

At this step, we don’t yet have a graphical UI, so we’ll simply add a few debugging messages in the DataProvider to make sure it works as expected.

Let’s start by adding a data-provider.h file to our project:

#ifndef DATA_PROVIDER_H
#define DATA_PROVIDER_H

#include <QtCore/QTimer>

class DataProvider: public QObject
{
    Q_OBJECT

public:
    DataProvider();

private slots:
    void handleTimer();

signals:
    void valueChanged(float temp, float pressure, float humidity);

private:
    QTimer timer;
};

#endif /* DATA_PROVIDER_H */

It creates a very simple class than inherits from QObject, with:

  • A constructor
  • A private slot handleTimer which will be used internally by the class QTimer’s instance to notify that a timer has expired. This is what will allow us to poll the sensor values every second.
  • A valueChanged signal, which will be emitted by the class every time new sensor values are available.

Then, the implementation of this class in data-provider.cpp is fairly straight-forward:

#include <QtCore/QFile>
#include <QDebug>
#include "data-provider.h"

DataProvider::DataProvider()
{
    QObject::connect(&timer, &QTimer::timeout,
		     this, &DataProvider::handleTimer);
    timer.setInterval(1000);
    timer.start();
}

void DataProvider::handleTimer()
{
    QFile temp_f("/sys/bus/iio/devices/iio:device2/in_temp_input");
    QFile pressure_f("/sys/bus/iio/devices/iio:device2/in_pressure_input");
    QFile humidity_f("/sys/bus/iio/devices/iio:device2/in_humidityrelative_input");

    if (!temp_f.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    if (!pressure_f.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    if (!humidity_f.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    float temp = QString(temp_f.readAll()).toDouble() / 1000;
    float pressure = QString(pressure_f.readAll()).toDouble() * 10;
    float humidity = QString(humidity_f.readAll()).toDouble() / 1000;

    qDebug() << "Temperature: " << temp << "Pressure: " << pressure << "Humidity: " << humidity;

    emit valueChanged(temp, pressure, humidity);
}

The constructor of the class connects the QTimer::timeout signal of the QTimer to this class handlerTimer slot, sets the timer interval to 1000 milliseconds, and starts the timer. This is what will ensure the handleTimer method gets called every second.

In the handleTimer method, we open the 3 files in sysfs, read their value and convert them to meaningful units: the temperature in Celcius, the pressure in hPA, and the humidity in percent. We then print a debugging message and emit the signal with the three values.

With this in place, we need to make sure those two files are properly taken into account by our project, by changing the .pro file as follows:

QT += widgets
SOURCES = main.cpp data-provider.cpp
HEADERS = data-provider.h
INSTALLS += target
target.path = /usr/bin

The data-provider.cpp file was added to SOURCES, while data-provider.h was added to the new HEADERS.

Now, we just need to change main.cpp to instantiate one DataProvider object:

#include <QApplication>
#include <QPushButton&ht;
#include "data-provider.h"

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    QPushButton hello("Hello world!");
    DataProvider dp;
    hello.resize(100,30);
    hello.show();
    return app.exec();
}

With this, you can now build and run the application, and you should see every second the debugging message showing the temperature, pressure and humidity values:

# qt-sensor-demo -platform linuxfb
Temperature:  28.12  Pressure:  1003.08  Humidity:  32.235
Temperature:  28.12  Pressure:  1003.07  Humidity:  32.246
Temperature:  28.12  Pressure:  1003.06  Humidity:  32.256
Temperature:  28.12  Pressure:  1003.08  Humidity:  32.267

Displaying sensor data

We now want to display the sensor data. For this, we'll create a UI with two panels, one to display the numeric value of the temperature, humidity and pressure, and another panel with a chart of the temperature. At the bottom of the screen, two buttons Values and Chart will allow to switch between both panels.

So, we'll create a Window class to encapsulate the overall window layout and behavior, and a Values class providing the widget showing the 3 values. We'll leave the chart implementation to the next section. To help you follow the code in this section, here is a diagram that shows the different widgets and how they will be grouped together in our user interface:

Qt Sensor demo UI

Let's start by implementing the Values widget, which will be used to show the 3 numeric values, one below each other. The values.h file will look like this:

#ifndef VALUES_H
#define VALUES_H

#include <QWidget>

class QLabel;

class Values : public QWidget
{
    Q_OBJECT

public:
    Values();

public slots:
    void handleValueChanged(float temp, float pressure, float humidity);

private:
    QLabel *temperature_v;
    QLabel *pressure_v;
    QLabel *humidity_v;
};

#endif /* VALUES_H */

So it has a simple constructor, a slot to be notified of new values available, and 3 text labels to display the 3 values. The implementation in values.cpp is:

// SPDX-License-Identifier: MIT
#include <QtWidgets>
#include "values.h"

Values::Values()
{
    QVBoxLayout *layout = new QVBoxLayout;

    QLabel *temperature_l = new QLabel(tr("Temperature (°C)"));
    QLabel *pressure_l = new QLabel(tr("Pressure (hPa)"));
    QLabel *humidity_l = new QLabel(tr("Humidity (%)"));

    temperature_v = new QLabel();
    pressure_v = new QLabel();
    humidity_v = new QLabel();

    QFont f = temperature_v->font();
    f.setPointSize(28);
    f.setBold(true);
    temperature_v->setFont(f);
    pressure_v->setFont(f);
    humidity_v->setFont(f);
    temperature_v->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    pressure_v->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    humidity_v->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    layout->addWidget(temperature_l);
    layout->addWidget(temperature_v);
    layout->addWidget(pressure_l);
    layout->addWidget(pressure_v);
    layout->addWidget(humidity_l);
    layout->addWidget(humidity_v);

    setLayout(layout);
}

void Values::handleValueChanged(float temp, float pressure, float humidity)
{
    temperature_v->setText(QString::number(temp, 'f', 2));
    pressure_v->setText(QString::number(pressure, 'f', 1));
    humidity_v->setText(QString::number(humidity, 'f', 1));
}

The constructor creates 3 text labels for the legends ("Temperature (°C)", "Pressure (hPA)" and "Humidity (%)"), then instantiates the 3 text labels for the values themselves. It sets up the font and text alignment properties for those labels, and then adds all widgets in a QVBoxLayout so that they all appear vertically below each other.

The handleValueChanged slot simply updates the text labels contents with the new sensor values, doing the proper text formatting on the way.

With the Values class implemented, we can now implement the main Window class. The window.h will contain:

#ifndef WINDOW_H
#define WINDOW_H

#include <QWidget>

class Values;

class Window : public QWidget
{
    Q_OBJECT

public slots:
    void handleValueChanged(float temp, float pressure, float humidity);

public:
    Window();

private:
    Values *values;
};

#endif

Beyond a simple constructor, it has a slot to receive new sensor values, and a reference to a Values widget instance.

The implementation in window.cpp is as follows:

#include <QtWidgets>

#include "window.h"
#include "values.h"

Window::Window()
{
    values = new Values;
    QVBoxLayout *layout = new QVBoxLayout;
    QHBoxLayout *buttons = new QHBoxLayout;

    QPushButton *values_button = new QPushButton("Values");
    QPushButton *chart_button = new QPushButton("Chart");

    buttons->addWidget(values_button);
    buttons->addWidget(chart_button);

    layout->addWidget(values);
    layout->addLayout(buttons);

    setLayout(layout);

    setWindowTitle(tr("Sensors"));
}

void Window::handleValueChanged(float temp, float pressure, float humidity)
{
    values->handleValueChanged(temp, pressure, humidity);
}

The constructor creates a horizontal layout QHBoxLayout with two buttons: Values and Chart. Those will be used in the next section to switch between the Values panel and the Chart panel. For now, they don't do anything.

Then, the constructor adds the Value widget, and the horizontal layout box with the buttons into a vertical box layout, assigns the main window layout and defines the window title.

The handleValueChanged slot implementation just forwards the call to the Values::handleValueChanged method.

Now, obviously main.cpp needs to be changed: instead of creating a button, we'll create our window, and do a bit of additional setup:

#include <QApplication>
#include "window.h"
#include "data-provider.h"

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    DataProvider dp;
    Window window;

    QObject::connect(&dp, &DataProvider::valueChanged,
		     &window, &Window::handleValueChanged);

    window.setFixedSize(480, 800);
    window.setStyleSheet("background-color: white;");
    window.show();
    return app.exec();
}

So, not only we create the Window, but more importantly, we connect the valueChanged signal of DataProvider to the handleValueChanged slot of Window. We define the window size (which is fixed, to match the STM32MP15 Discovery board panel) and set the background color of the application.

Obviously, the qt-sensor-demo.pro file needs to be adjusted to build our new files. It now looks like this:

QT += widgets
SOURCES = main.cpp data-provider.cpp window.cpp values.cpp
HEADERS = data-provider.h window.h values.h
INSTALLS += target
target.path = /usr/bin

With this done, we can run the Qt5 application on our target, and see:

Qt5 application showing the I2C sensor data

Graphing the temperature

The final part of developing our application is to implement a graph showing the evolution of temperature over time. For this, we are going to use the very convenient Qt Charts module, which is available in a separate Qt module from the base of Qt.

To implement the graph widget itself, we'll create a new Chart class:

#ifndef CHART_H
#define CHART_H

#include <QtCharts/QChart>

QT_CHARTS_BEGIN_NAMESPACE
class QSplineSeries;
class QValueAxis;
QT_CHARTS_END_NAMESPACE

QT_CHARTS_USE_NAMESPACE

class Chart: public QChart
{
    Q_OBJECT

public:
    Chart(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);

public slots:
    void handleValueChanged(float temp, float pressure, float humidity);

private:
    QSplineSeries *m_series;
    QStringList m_titles;
    QValueAxis *m_axisX;
    QValueAxis *m_axisY;
    int xpos;
};

#endif /* CHART_H */

This class inherits from the QChart class provided by Qt. It provides a constructor and destructor, a slot that allows to receive notification of new sensor values, and it has a number of private variables to manage the chart itself.

Let's go through the implementation of this class now:

#include "chart.h"
#include <QtCharts/QAbstractAxis>
#include <QtCharts/QSplineSeries>
#include <QtCharts/QValueAxis>

Chart::Chart(QGraphicsItem *parent, Qt::WindowFlags wFlags):
    QChart(QChart::ChartTypeCartesian, parent, wFlags),
    m_series(0),
    m_axisX(new QValueAxis()),
    m_axisY(new QValueAxis()),
    xpos(0)
{
    m_series = new QSplineSeries(this);
    QPen pen(Qt::red);
    pen.setWidth(2);
    m_series->setPen(pen);
    m_series->append(xpos, 30);

    addSeries(m_series);

    addAxis(m_axisX,Qt::AlignBottom);
    addAxis(m_axisY,Qt::AlignLeft);
    m_series->attachAxis(m_axisX);
    m_series->attachAxis(m_axisY);
    m_axisX->setTickCount(5);
    m_axisX->setRange(0, 60);
    m_axisY->setRange(0, 50);

    QFont f = m_axisX->labelsFont();
    f.setPointSize(8);
    m_axisX->setLabelsFont(f);
    m_axisY->setLabelsFont(f);

    setMargins(QMargins(0,0,0,0));

    setTitle("Temperature (°C)");
    legend()->hide();
}

void Chart::handleValueChanged(float temp, float pressure, float humidity)
{
    Q_UNUSED(pressure);
    Q_UNUSED(humidity);
    m_series->append(xpos, temp);
    xpos++;
    if (xpos >= 60)
      scroll(plotArea().width() / 60, 0);
}

The constructor simply sets up the QChart we inherit from: defining the axis, their range, the pen width and color, etc. On the X axis (time), we are going to show 60 measurements, and since our handleValueChanged slot is going to be called every second, it means our graph will show the last 60 seconds of temperature measurement. On the Y axis (temperature), we can show temperatures from 0°C to 50°C. Of course, this is all very hardcoded in this example, for simplicity.

The handleValueChanged slot appends the new temperature value to the graph, and then updates the area displayed by the graph so that always the last 60 seconds are visible.

Now, we need to integrate this to our existing Window class, so that we can display the chart, and switch between the numeric values and the chart. First, we need to do some changes in window.h, and below we'll show only the diff to make the differences very clear:

diff --git a/window.h b/window.h
index 3d63d38..05d1f39 100644
--- a/window.h
+++ b/window.h
@@ -3,8 +3,12 @@
 #define WINDOW_H
 
 #include <QWidget>
+#include <QtCharts/QChartView>
+
+QT_CHARTS_USE_NAMESPACE
 
 class Values;
+class Chart;
 
 class Window : public QWidget
 {
@@ -13,11 +17,17 @@ class Window : public QWidget
 public slots:
     void handleValueChanged(float temp, float pressure, float humidity);
 
+private slots:
+    void chartButtonClicked();
+    void valuesButtonClicked();
+
 public:
     Window();
 
 private:
     Values *values;
+    QChartView *chartView;
+    Chart *chart;
 };
 
 #endif

So, we're defining two private slots that will be used for the two buttons that allow to switch between the numeric values and the chart, and then we add two variables, one for the chart itself, and one for the QChartView (which basically renders the graph into a widget).

Then, in window.cpp, we do the following changes:

diff --git a/window.cpp b/window.cpp
index aba2862..d654964 100644
--- a/window.cpp
+++ b/window.cpp
@@ -3,28 +3,54 @@
 
 #include "window.h"
 #include "values.h"
+#include "chart.h"
 
 Window::Window()
 {
     values = new Values;
+    chart = new Chart;
     QVBoxLayout *layout = new QVBoxLayout;
     QHBoxLayout *buttons = new QHBoxLayout;
 
     QPushButton *values_button = new QPushButton("Values");
     QPushButton *chart_button = new QPushButton("Chart");
 
+    QObject::connect(chart_button, &QPushButton::clicked,
+                    this, &Window::chartButtonClicked);
+    QObject::connect(values_button, &QPushButton::clicked,
+                    this, &Window::valuesButtonClicked);
+
     buttons->addWidget(values_button);
     buttons->addWidget(chart_button);
 
+    chartView = new QChartView(chart);
+    chartView->setRenderHint(QPainter::Antialiasing);
+
     layout->addWidget(values);
+    layout->addWidget(chartView);
     layout->addLayout(buttons);
 
     setLayout(layout);
 
+    chartView->hide();
+
     setWindowTitle(tr("Sensors"));
 }
 
 void Window::handleValueChanged(float temp, float pressure, float humidity)
 {
     values->handleValueChanged(temp, pressure, humidity);
+    chart->handleValueChanged(temp, pressure, humidity);
+}
+
+void Window::chartButtonClicked()
+{
+    values->hide();
+    chartView->show();
+}
+
+void Window::valuesButtonClicked()
+{
+    values->show();
+    chartView->hide();
 }

So, in the constructor we are connecting the clicked signals of the two buttons to their respective slots. We create the Chart object, and then the QChartView to render the graph. We add the latter as an additional widget in the QVBoxLayout, and we hide it.

The existing handleValueChanged slot is modified to also update the Chart object with the new sensor values.

Finally, the new chartButtonClicked and valuesButtonClicked slots implement the logic that is executed when the buttons are pressed. We simply hide or show the appropriate widget to display either the numeric values or the chart. There is probably a nicer way to achieve this in Qt, but this was good enough for our example.

Now that the source code is in place, we of course need to adjust the build logic in qt-sensor-demo.pro:

--- a/qt-sensor-demo.pro
+++ b/qt-sensor-demo.pro
@@ -1,6 +1,6 @@
 # SPDX-License-Identifier: MIT
-QT += widgets
-SOURCES = main.cpp data-provider.cpp window.cpp values.cpp
-HEADERS = data-provider.h window.h values.h
+QT += widgets charts
+SOURCES = main.cpp data-provider.cpp window.cpp values.cpp chart.cpp
+HEADERS = data-provider.h window.h values.h chart.h
 INSTALLS += target
 target.path = /usr/bin

Besides the obvious addition of the chart.cpp and chart.h file, the other important addition is charts to the QT variable. This tells qmake that our application is using the Qt Charts, and that we therefore need to link against the appropriate libraries.

Building the application

At this point, if you try to build the application, it will fail because QtCharts has not been built as part of our Buildroot configuration. In order to address this, run Buildroot's make menuconfig, enable the BR2_PACKAGE_QT5CHARTS option (in Target packages -> Graphic libraries and applications -> Qt5 -> qt5charts).

Then, run the Buildroot build with make, and reflash the resulting SD card image.

Now, you can build again your application, either with Qt Creator if you've been using Qt Creator, or manually. If you build it manually, you'll have to run qmake again to regenerate the Makefile, and then build with make.

When you run the application on the target, the GUI will display the same numeric values as before, but now if you press the Chart button, it will show something like:

Qt5 application with chart

Adjusting the Buildroot package

We have for now been building this application manually, but as explained in our previous blog post, we really want Buildroot to be able to build our complete system, including our application. For this reason, we had created a qt-sensor-demo package, which gets our application source code, configures it with qmake, builds it and installs it.

However, with the new use of Qt Charts, our qt-sensor-demo package needs a few adjustements:

  • The Config.in file needs an additional select BR2_PACKAGE_QT5CHARTS, to make sure Qt Charts are enabled in the Buildroot configuration
  • The qt-sensor-demo.mk file needs an additional qt5charts in the QT_SENSOR_DEMO_DEPENDENCIES variable to make sure the qt5charts package gets built before qt-sensor-demo

With this in place, you can run:

make qt-sensor-demo-rebuild
make

And you have an SD card image that includes our application!

Starting the application automatically at boot time

The next and almost final step for this blog post is to get our application automatically started at boot time. We can simply add a small shell script on the target in /etc/init.d/: the default Buildroot configuration for the init system will execute all scripts named Ssomething in /etc/init.d/. We'll add a file named package/qt-sensor-demo/S99qt-sensor-demo with these contents:

#!/bin/sh

DAEMON="qt-sensor-demo"
DAEMON_ARGS="-platform linuxfb"
PIDFILE="/var/run/qt-sensor-demo.pid"

start() {
	printf 'Starting %s: ' "$DAEMON"
	start-stop-daemon -b -m -S -q -p "$PIDFILE" -x "/usr/bin/$DAEMON" -- $DAEMON_ARGS
	status=$?
	if [ "$status" -eq 0 ]; then
		echo "OK"
	else
		echo "FAIL"
	fi
	return "$status"
}

stop () {
	printf 'Stopping %s: ' "$DAEMON"
	start-stop-daemon -K -q -p "$PIDFILE"
	status=$?
	if [ "$status" -eq 0 ]; then
		rm -f "$PIDFILE"
		echo "OK"
	else
		echo "FAIL"
	fi
	return "$status"
}

restart () {
	stop
	sleep 1
	start
}

case "$1" in
        start|stop|restart)
		"$1";;
	reload)
		# Restart, since there is no true "reload" feature.
		restart;;
        *)
                echo "Usage: $0 {start|stop|restart|reload}"
                exit 1
esac

This is the canonical init script used in Buildroot to start system daemons and services, and is modeled after the one in package/busybox/S01syslogd. It uses the start-stop-daemon program to start our application in the background.

Then, to get this init script installed, we need to adjust package/qt-sensor-demo/qt-sensor-demo.mk with the following additional lines:

define QT_SENSOR_DEMO_INSTALL_INIT_SYSV
        $(INSTALL) -D -m 755 package/qt-sensor-demo/S99qt-sensor-demo \
                $(TARGET_DIR)/etc/init.d/S99qt-sensor-demo
endef

This ensures that the init script gets installed in /etc/init.d/S99qt-sensor-demo as part of the build process of our qt-sensor-demo package. Note that an init script works fine if you're using the Busybox init implementation or the sysvinit init implementation (we're using the default Buildroot setup here, which uses the Busybox init implementation). If you want to use systemd as an init implementation, then a different setup is necessary.

With this done, you simply need to reinstall the application and regenerate the SD card image

$ make qt-sensor-demo-reinstall
$ make

You can now test your SD card image on you board, and you should see the application being started automatically, with the following messages at boot time

Starting dropbear sshd: OK
Starting qt-sensor-demo: OK

Welcome to Buildroot

Avoid unnecessary logging on the display panel

In our current setup, the kernel messages are being sent to both the serial port and the framebuffer console, which means they appear on the display panel. This is not very pretty, and we would like the display to remain black until the application starts, while keeping the kernel messages on the serial port for debugging purposes. Also, we would like the framebuffer console text cursor to not be displayed, to really have a fully black screen. To achieve this we will add two arguments on the Linux kernel command line:

  • console=ttySTM0,115200, which will tell the Linux kernel to only use the serial port as the console, and not all registered consoles, which would include the framebuffer console. This option will make sure the kernel messages are not displayed on the screen.
  • vt.global_cursor_default=0, which will tell the Linux kernel to not display any cursor on the framebuffer console.

So, to add those options, we simply modify board/stmicroelectronics/stm32mp157-dk/overlay/boot/extlinux/extlinux.conf in Buildroot as follows:

label stm32mp15-buildroot
  kernel /boot/zImage
  devicetree /boot/stm32mp157c-dk2.dtb
  append root=/dev/mmcblk0p4 rootwait console=ttySTM0,115200 vt.global_cursor_default=0

Of course, rebuild the SD card image with make, reflash and test the result on your STM32MP1 platform.

Conclusion

In this blog post, we have seen how to write a real (but admittedly very simple) Qt application, how to make it read and display sensor data, and how to integrate this application so that it gets started at boot time.

You can find the Buildroot changes corresponding to this blog post in the 2019.02/stm32mp157-dk-blog-5 branch of our repository. The qt-sensor-demo application code can be found in the blog-5 branch of this application Git repository.

Stay tuned for our next blog post about factory flashing and OTA update!