Most Debian source packages are using the 3.0 (quilt) format. This means that Debian changes to upstream files are managed in a quilt patch series. Knowledge of quilt is thus a must if you want to get involved in some serious packaging work. Don t worry, this tutorial will teach you how to use quilt in the context of Debian packaging.
Pre-requisites
Install the packaging-dev package to get a decent set of packages to do Debian packaging. It includes the quilt package.
$ sudo apt-get install packaging-devWhat s quilt? Read the description of the Debian package:
Quilt manages a series of patches by keeping track of the changes each of them makes. They are logically organized as a stack, and you can apply, un-apply, update them easily by traveling into the stack (push/pop). Quilt is good for managing additional patches applied to a package received as a tarball or maintained in another version control system. The stacked organization is proven to be efficient for the management of very large patch sets (more than hundred patches). As matter of fact, it was designed by and for Linux kernel hackers (Andrew Morton, from the -mm branch, is the original author), and its main use by the current upstream maintainer is to manage the (hundreds of) patches against the kernel made for the SUSE distribution.The various files involved
To better understand the various quilt commands, you should have a basic idea of how the tool works. The stack of patches is maintained in a dedicated directory ( patches by default, but in Debian packages we override this value to debian/patches ). This directory contains the patch files and a series file that gives an ordered list of patches to apply. Example:
$ ls debian/patches/ 01_use_stdlib_htmlparser_when_possible.diff 02_disable-sources-in-sphinxdoc.diff 03_manpage.diff 06_use_debian_geoip_database_as_default.diff series $ cat debian/patches/series 01_use_stdlib_htmlparser_when_possible.diff 02_disable-sources-in-sphinxdoc.diff 03_manpage.diff 06_use_debian_geoip_database_as_default.diffWhen quilt is used, it also maintains some internal files in a directory of its own (it s named .pc ). This directory is used to know what patches are currently applied (.pc/applied-patches) and to keep backup copies of files modified by the various patches. Configuring quilt Before going further, you should put this in your
~/.quiltrc file:
for where in ./ ../ ../../ ../../../ ../../../../ ../../../../../; do
if [ -e $ where debian/rules -a -d $ where debian/patches ]; then
export QUILT_PATCHES=debian/patches
break
fi
done
This ensures that quilt will always use debian/patches instead of patches when your current directory is within a Debian source package where debian/patches exists. If you only use quilt for debian packaging, then you can be more expedient and put a simple export QUILT_PATCHES=debian/patches in that file.
As a matter of personal preferences, I also have those lines in my ~/.quiltrc:
QUILT_PUSH_ARGS="--color=auto" QUILT_DIFF_ARGS="--no-timestamps --no-index -p ab --color=auto" QUILT_REFRESH_ARGS="--no-timestamps --no-index -p ab" QUILT_DIFF_OPTS='-p'It enables syntax coloring for the output of several commands and customizes the generated patches to get rid of useless information. I recommend you to use those settings too. Applying and unapplying patches, navigating in the stack of patches When you already have a patch series, you can navigate in the stack of patches so that any subset of consecutive patches (starting from the bottom) can be applied. quilt series will list all patches known by quilt. You can apply all patches with quilt push -a or unapply them all with quilt pop -a. You can also verify what patches are applied (quilt applied) or unapplied (quilt unapplied). quilt push applies the next unapplied patch (i.e. the patch returned by quilt next) and quilt pop unapplies the last applied patch (i.e. the patch returned by quilt top). You can give a patch name as parameter to quilt push/pop and it will apply/unapply all the patches required until the given patch is on the top. Here are some examples of navigation in a quilt patch series
$ quilt series 02_disable-sources-in-sphinxdoc.diff 03_manpage.diff 06_use_debian_geoip_database_as_default.diff $ quilt applied No patches applied $ quilt next 02_disable-sources-in-sphinxdoc.diff $ quilt push Applying patch 02_disable-sources-in-sphinxdoc.diff patching file docs/conf.py Now at patch 02_disable-sources-in-sphinxdoc.diff $ quilt push Applying patch 03_manpage.diff patching file docs/man/django-admin.1 Now at patch 03_manpage.diff $ quilt applied 02_disable-sources-in-sphinxdoc.diff 03_manpage.diff $ quilt unapplied 06_use_debian_geoip_database_as_default.diff $ quilt pop -a Removing patch 03_manpage.diff Restoring docs/man/django-admin.1 Removing patch 02_disable-sources-in-sphinxdoc.diff Restoring docs/conf.py No patches applied $ quilt push 03_manpage.diff Applying patch 02_disable-sources-in-sphinxdoc.diff patching file docs/conf.py Applying patch 03_manpage.diff patching file docs/man/django-admin.1 Now at patch 03_manpage.diff $ quilt top 03_manpage.diffCreating a new patch If there s no quilt series yet, you want to create the debian/patches directory first. If you already have one, you need to decide where to insert the new patch. Quilt will always add the new patch just after the patch which is currently on top. So if you want to add the patch at the end of the series, you need to run quilt push -a first. Then you can use
quilt new name-of-my-patch.diff to tell quilt to insert a new empty patch after the current topmost patch. In this operation quilt does almost nothing except updating the series file and recording the fact that the new patch is applied (even if still empty at this point!).
Now to add changes in this patch, you re supposed to modify files but only after having informed quilt of your intent to modify those files. You do this with quilt add file-to-modify. At this point quilt will make a backup copy of that file so that it can generate the final patch when you re done with your changes. It s quite common to forget this step and to be unable to generate the patch afterward. That s why I recommend you to use quilt edit file-to-modify which is a shorthand for doing quilt add and then opening the file in your favorite text editor.
If you want, you can review your work in progress with quilt diff.
When you re done with the changes, you should call quilt refresh to generate the patch (or to update it if it was already existing). And since you re a good packager, you call quilt header --dep3 -e to add DEP-3 meta-information to your patch header.
Importing an external patch
If someone else already prepared a patch, you can just import it right away with quilt import /tmp/the-patch. If you want to import it under a better name you can use the option -P better-patch-name . Like quilt new, it inserts the patch after the topmost patch.
Updating patches for a new upstream version
With some luck, your patches will still apply with some offsets in line numbers (quilt displays those offsets) and sometimes with some fuzz:
$ quilt push [...] Hunk #1 succeeded at 1362 (offset 11 lines). Hunk #2 succeeded at 1533 with fuzz 1 (offset 4 lines). [...]While offsets are nothing to worry about (it means some lines were added and/or removed before the patched part), fuzz means that patch had to ignore some context lines to find the place where to apply the changes. In that case, you need to double check that patch did the right thing because it might have made changes somewhere where it shouldn t. Also, you ll have to update those patches because dpkg-source doesn t accept any fuzz. If you re confident that all patches are correctly applied by quilt, you can refresh them to get rid of those warnings:
$ quilt pop -a [...] $ while quilt push; do quilt refresh; doneThat was for the easy case. Now let s deal with the case where some of the patches no longer apply. There s one case that is usually nice to have:
$ quilt push Applying patch 04_hyphen-manpage.diff patching file docs/man/django-admin.1 Hunk #1 FAILED at 194. 1 out of 1 hunk FAILED -- rejects in file docs/man/django-admin.1 Patch 04_hyphen-manpage.diff can be reverse-appliedWhen the patch can be reverse-applied, it means that the upstream authors included the Debian patch (or that they made the same change even though you forgot to forward the patch). You can thus get rid of it:
$ quilt delete -r 04_hyphen-manpage.diff Removed patch 04_hyphen-manpage.diffNote that without the -r the patch is only dropped from the series file. With -r the patch file is also removed. But there s a less desirable case where the patch is still relevant but it doesn t apply any longer:
$ quilt push Applying patch 01_disable_broken_test.diff patching file tests/regressiontests/test_utils/tests.py Hunk #1 FAILED at 422. 1 out of 1 hunk FAILED -- rejects in file tests/regressiontests/test_utils/tests.py Patch 01_disable_broken_test.diff does not apply (enforce with -f)In that case, you should follow quilt s advice to force the patch application, manually apply the parts of the patch that were rejected, and then refresh the patch.
$ quilt push -f Applying patch 01_disable_broken_test.diff patching file tests/regressiontests/test_utils/tests.py Hunk #1 FAILED at 422. 1 out of 1 hunk FAILED -- saving rejects to file tests/regressiontests/test_utils/tests.py.rej Applied patch 01_disable_broken_test.diff (forced; needs refresh) $ vim tests/regressiontests/test_utils/tests.py $ quilt refresh Refreshed patch 01_disable_broken_test.diffOther quilt commands You should probably read quilt s manual page too to learn about the various other commands and options that exist. There s at least
quilt rename new-name that you can also find useful to rename the topmost patch (you can use -P patch-to-rename to rename a patch which is not currently at the top).
Feedback
Please leave comments if you have suggestions of improvements, or if there are some tips that are good to know. I might incorporate them in this article.
Feel free to share this article with newbie packagers which are struggling with quilt. For your convenience, you can also refer to this article with this URL: http://raphaelhertzog.com/go/quilt
Found it useful? Be sure to not miss other packaging tips (or lessons), click here to subscribe to my free newsletter and get new articles by email.
2 comments Liked this article? Click here. My blog is Flattr-enabled.
I have happily used FVWM as my window manager for more than 10
years. However, I recently got tired of manually arranging windows and
using the mouse so much. A window manager is one of the handful pieces
of software getting in your way at every moment which explains why
there are so many of them and why we might put so much time in it.
I decided to try a tiling window manager. While i3 seemed
pretty hot and powerful (watch the screencast!), I
really wanted something configurable and extensible with some
language. So far, the common choices are:
Mod4 and is
usually unused by most applications and can therefore be dedicated to
the window manager.
The main problem with the ability to define many keybindings is to
remember the less frequently used one. I have monkey-patched
awful.key module to be able to attach a documentation string to a
keybinding. I have documented the whole process on the
awesome wiki.
$ xrandr --output VGA-1 --auto --left-of LVDS-1
XF86Display symbol. I
have associated this key to a function that will
cycle through possible configurations depending on the
plugged screens. For example, if I plug an external screen to my
laptop, I can cycle through the following configurations:
local volwidget = widget( type = "textbox" ) vicious.register(volwidget, vicious.widgets.volume, '<span font="Terminus 8">$2 $1%</span>', 2, "Master") volwidget:buttons(awful.util.table.join( awful.button( , 1, volume.mixer), awful.button( , 3, volume.toggle), awful.button( , 4, volume.increase), awful.button( , 5, volume.decrease)))
XF86ScreenSaver key symbol which will in turn be bound to a function
that will trigger xautolock to lock the screen.
Thanks to a great article about
extending the X keyboard map with xkb, I discovered
that X was able to switch from one layout to another using
groups2. I finally opted for this simple configuration:
$ setxkbmap us,fr '' compose:rwin ctrl:nocaps grp:rctrl_rshift_toggle $ xmodmap -e 'keysym Pause = XF86ScreenSaver'
us to fr by pressing both left Control and left
Shift keys.
gnome-session, gnome-settings-daemon and others. I had numerous
problems when I tried to setup everything without pulling the whole
GNOME stack. At each GNOME update, something was broken: the
screensaver didn t start automatically anymore until a full session
restart or some keybindings were randomly hijacked by
gnome-settings-daemon.
Therefore, I have decided to get rid of most of those components. I
have replaced GNOME Power Manager with system-level tools like
sleepd and the PM utilities. I replaced the GNOME screensaver with
i3lock and xautolock. GDM has been replaced by SLiM which
now features ConsoleKit support3. I use ~/.gtkrc-2.0
and ~/.config/gtk-3.0/settings.ini to configure GTK+.
The future will wait.
I have also switched to Xft for font rendering using DejaVu Sans
Mono as my default font (instead of fixed) with the following
configuration in ~/.Xresources:
Xft.antialias: true Xft.hinting: true Xft.hintstyle: hintlight Xft.rgba: rgb URxvt.font: xft:DejaVu Sans Mono-8 URxvt.letterSpace: -1
I've been thinking a lot recently about information security and passwords. It's widely agreed that two-factor authentication, which combines something-you-know (a password) with something you have (eg. a smart card or some one-time-password) is superior to using a password by itself. Most solutions I've seen, short of client-side certificates, both require a trusted third party and provide little auditability.
On a lark, I signed up for the pilot program of the Google Cr-48 about a week ago. To my surprise, I found the distinctive box on my doorstep a week later. After initially mistaking it for an overpacked, late-model OLPC XO-1 I would have to repair, I sort of did a double-take as I realized what I had received.
Wow, they weren't kidding about the boot time. Chrome OS responds (to suspend / resume and boot / power-off) very quickly. Responsiveness elsewhere in the OS of course varies on system load and other factors. On the "terms" page, there is a "system security setting" which tells me I have a Trusted Platform Module, and that my TPM has a randomly generated password. The dialog could use some rewording; I'm pretty familiar with the idea of a TPM, but I'm still not sure what I'm to do with that information.
RCBW report for 2012/29 (16.7.-22.7.)
The motto for this week was:
exiv2 -k -M"set Exif.Image.Orientation 8" -M"set Exif.Panasonic.Rotation 8" -M"set Exif.Thumbnail.Orientation 8" P1020800.JPG
Camera rotated clockwise (shutter button at bottom):exiv2 -k -M"set Exif.Image.Orientation 6" -M"set Exif.Panasonic.Rotation 6" -M"set Exif.Thumbnail.Orientation 6" P1020800.JPG
Very little done last night. Advocated a
maintainer. My
desktop computer is completely hosed as part of a wheezy update: many issues at
once but one is GDM going into an infinite loop, spawning millions of X
servers; another is something in the boot processes seemingly prodding
/dev/sdc and failing. I'm not sure if I have time to get to the bottom of
it, I might just reinstall from a d-i daily. Priority going forward should be
to finish off the musicbrainz stuff. Pleased to see my gnome sushi patch
merged upstream.
porter-* groups, so
that I can fulfill installation requests in various chroots on
Debian porterboxes; this means real DSA members can concentrate on
more important things while still keeping the turnaround quick for
developers who want to debug stuff on exotic architectures.
Reminder for that procedure:
Chroot Install Request Guidelines.kfreebsd-* buildds for a while, I m
still in the wanna-build team, meaning I can take care of give
backs, one of the most common requests on debian-wb-team@. It s
been a while since it s been split up from debian-release@, and
instructions are still available in
wanna-build.txt.
Basically: anything buildd-related goes to
$arch@buildd.debian.org or debian-wb-team@lists.debian.org,
with the sole exception of binNMUs, which are handled by the
release team.testing, and more recently, dealing with unblock
requests during the freeze. While the Debian world is usually
driven by the just do motto, there s one area where one has to
learn to say no, sorry . Hopefully people won t hate us for that,
and we ll find alternative ways (like backporting specific fixes,
or postponing new features until wheezy-backports is open).debian-boot@ stepped up to prepare new
debian-installer releases, I figured I would give a hand there
until somebody more involved with d-i would manage that on the
long run. That s
a
lot
of
heavy
work,
trying to get all involved packages into shape at a given moment,
and getting people to fix their stuff when anything
breaks. Hopefully that ll work out and once CD images are ready, we
should be able to run some more tests on those before officially
publishing d-i beta 1.pettersson (the very nice machine on which images
are built), using the debian-cd account. The intent was to make
sure debian-installer could safely migrate from unstable to
testing. That has happened lately, so images are being prepared.debian-cd. I m also pretty sure having
more people involved in the d-i team would be very nice, especially
if one could find out how to make the whole release process less
insane than it is currently. I guess we could try out new ideas right
after the release; it feels to me that right now is just not the time
to fight the current release process.
Originally posted by bubulle on Planet Debian, a shell prompt that displays the current git branch, in colour on some terminals, after the current working directory. The following snippet does similar things for mksh users, except it doesn t redefine your prompt but amend it just throw it at the bottom of your ~/.mkshrc before that last line beginning with a colon (copy from /etc/skel/.mkshrc if you haven t done that yet):
function parse_git_branch git branch 2>/dev/null sed -n '/^\* \(.*\)/s//(\1)/p' function amend_prompt_with_git local p q='$(parse_git_branch)' r if [[ $TERM = @(xterm-color xterm screen*) ]]; then if [[ $ PS1:1:1 = $'\r' ]]; then p=$ PS1:0:1 else p=$'\001' PS1=$p$'\r'$PS1 fi q=$p$'\e[1;33m'$p$q$p$'\e[0m'$p fi p=$ PS1%%*( )[#$]*( ) if [[ $p != "$PS1" ]]; then # prompt ends with space + #-or-$ + space, we can amend r=$ PS1: $ #p PS1=$p$q$r fi amend_prompt_with_git unset -f amend_prompt_with_git
The indirection by use of a function is not strictly necessary but allows the use of locals. I took the liberty of adding an asterisk after screen to match the GNU/Linux nonsense of having TERM=screen.xterm or somesuch.
We need to understand how to invite people with different backgrounds than packaging to join the Debian project [...] I don't know what exactly, but we need to do more to attract those kinds of people.Francesca and I know what we could do: make other kinds of contributions visible. Basically, we should track and acknowledge the contributions of webmasters, translators, programmers, sysadmins, event organisers, and so on, at the same level as what we do for packagers: DDPO, minechangelogs, Portfolio... For any non-packaging activity that we can make visible and credited, we get:
l10n-tagged BTS bugs at any rate.maintainer="name" on normal wml
pages, while for DPN translations we have a specific translator="name"
field. The problem is that this field is not mandatory, so sometimes
there's no indication of the maintainer. Again, it's ok to only support the
main workflow.
Anyway, this is preferable to the cvs log: often the commit is done by the
coordinator of the team and not by the actual translator. See above for the
alternative solution of using the statistics provided by the i18n bot.$LANG/* pages. A nice idea would be to have
translated pages list the version of the page that was translated and who
did the translation.editor=.www.debian.org/events/$year/$date-$eventname.wml: grep for <define-tag coord>;
for events not published on the http://www.debian.org, but only on http://wiki.debian.org, the
coordinator or the contact for the event is usually present on the page
itself.
Continuing in my better running through technology phase that
I'm currently going through, I got all excited when I discovered that Polar
make a Bluetooth-enabled heart rate monitor chest strap.
Prior to this, I'd be lamenting how there wasn't a large choice of ANT+ enabled
Android phones (to my knowledge there's just something Sony
makes)
So I got all excited and ordered a strap and it arrived today. This is my
initial review (I haven't gone running with it yet, I've just had a tinker)
I'll start with the bad first
Forward Error Correction with the TI CC1120 Sub-GHz transceiver
We re building a new, fancier flight computer and decided to give the
new, fancier TI CC1120 chip a try.
It has significantly more transmit power (+16dBm) and receive
sensitivity (-109dBm) than the transciever built in to
the TI CC1111 RF SoC that we ve
built our other boards with. Given that we d already decided to use a
fancier STM32L
processor, using the nicest stand-alone radio chip we could find
seemed to make good sense.
One of the nice features found in the CC1111 is support for FEC using a
1/2 rate constraint length 4 convolutional code.
Both the encoder and the soft-decision Viterbi decoder
are built right into the chip; all we had to do was flip a couple of
bits and we got error correction, interleaving, data whitening and CRC
checking all for free.
We assumed that, as the CC1120 was advertised as a better
replacement for our CC1111 radio, that it would also include all of
these fine features. After we got the chip all soldered down to our
first prototype boards, we read through the reference manual looking
for the right register values to flip for forward error correction. We
found support for CRC computation and data whitening, but no mention
of interleaving or forward error correction at all.
Thanks, TI. Of course, without the FEC pieces, the other packet
handling hardware is worthless you can t exactly do a CRC on the
encoded data and expect it to be useful on the other end of the link,
and data whitening happens after the CRC.
Basic CC1120 driver
I assumed I d eventually figure out something to do about the FEC
pieces and started writing a basic
CC1120 driver
AltOS, the operating system used in
all of our projects. I started with the transmit side, as that seemed
easier as I could use the existing packet hardware by uploading the
desired bit sequence using whatever fancy encoding desired and the
hardware would happily transmit it.
I first tested that using low data-rate bits (2kbps), transmitting an
alternating sequence of zeros and ones to generate a 1kHz tone on a
regular 70cm receiver. That seemed to work just fine, demonstrating
that I had some grasp of the basic operation of the chip.
Convolutional Encoding in Software
Not to be daunted by a small challenge in software, I set out to
replicate the encoding scheme used in the CC1111 chips for use in our
CC1120-based design. We obviously want our CC1120 boards to
interoperate with the CC1111 boards. Fortunately, TI
fully documents
the CRC, data whitening, convolutional encoding and interleaving done
in the hardware.
I created my own implementation of the encoder (licensed, as usual, under the
GPLv2) which you can see in the file
ao_fec_tx.c
It s not quite as flexible as the hardware, it always whitens the data
and always appends the CRC bytes to the end of the packet, along with
the necessary trellis termination bytes.
The core of that code is surprisingly simple:
static const uint8_t ao_fec_encode_table[16] =
/* next 0 1 state */
0, 3, /* 000 */
1, 2, /* 001 */
3, 0, /* 010 */
2, 1, /* 011 */
3, 0, /* 100 */
2, 1, /* 101 */
0, 3, /* 110 */
1, 2 /* 111 */
;
uint8_t
ao_fec_encode(const uint8_t *in, uint8_t len, uint8_t *out)
uint8_t extra[AO_FEC_PREPARE_EXTRA];
uint8_t extra_len;
uint32_t encode, interleave;
uint8_t pair, byte, bit;
uint16_t fec = 0;
const uint8_t *whiten = ao_fec_whiten_table;
extra_len = ao_fec_prepare(in, len, extra);
for (pair = 0; pair < len + extra_len; pair += 2)
encode = 0;
for (byte = 0; byte < 2; byte++)
if (pair + byte == len)
in = extra;
fec = *in++ ^ *whiten++;
for (bit = 0; bit < 8; bit++)
encode = encode << 2 ao_fec_encode_table[fec >> 7];
fec = (fec << 1) & 0x7ff;
interleave = 0;
for (bit = 0; bit < 4 * 4; bit++)
uint8_t byte_shift = (bit & 0x3) << 3;
uint8_t bit_shift = (bit & 0xc) >> 1;
interleave = (interleave << 2) ((encode >> (byte_shift + bit_shift)) & 0x3);
*out++ = interleave >> 24;
*out++ = interleave >> 16;
*out++ = interleave >> 8;
*out++ = interleave >> 0;
return (len + extra_len) * 2;
ao_fec_encode_table takes care of the convolutional piece,
ao_fec_whiten_table (not shown) contains the data whitening codes
while the little loop at the bottom does the interleaving. I didn t
spend a lot of time optimizing this as it seemed to run plenty fast on
the 32MHz processor.
With the bits all nicely encoded, I passed them to my simple CC1120
driver and let it send them along to our CC1111 receiver. Much to my
delight, with only a few bugs fixed, it worked just fine! I d managed
to get one direction working, validating the hardware and making it
clear that we d at least be able to use the board in flight for
telemetry.
Getting Soft-decision data out of the CC1120
In packet mode, the CC1120 receiver converts the incoming GFSK stream
directly into bits, making its best guess as to whether the detected
value was a one or zero. Of course, like any FM modulation, the
receiver will be producing intermediate values, especially when the
signal is weak or masked by interference. A Viterbi decoder can make
good use of this information;these noisy intermediate values are less
influential in the final resulting path cost which allows the strong
0/1 values to pull the solution to the right one. Soft decision
decoding yields a theoretical 2dB gain over hard decision decoders,
and given our desire for maximum packet reception over long distances,
it seemed important to make this work.
The CC1120 has a way to recover the soft decision values, but only one
8-bit value at a time. It does, however, helpfully provide a GPIO
wire which can be programmed to interrupt the CPU when the soft
decision data has arrived.
So, I hooked up a GPIO line on the processor to the GPIO line on the
CC1120 and let it interrupt once per bit time, or 38400 times
per second, to read this valuable soft decision data out of the radio
part. According to TI support, this is the only way to make this work,
and that they generally recommend that developers use the packet mode
stuff and throw away this valueable source of data.
I was happily surprised to learn that the STM32L can in fact survive
this interrupt rate, and by setting interrupt priorities
appropriately, I manage to reliably capture an entire packets worth of
data without dropping a single bit.
I set up a simple packet dumping function to run on the prototype
board and captured raw encoded bytes from our CC1111-based flight
computer so that I d have some real data to work from.
Soft-decision Viterbi Decoding
The sample encoding implementation from TI made that piece fairly
straightforward. Lacking a similar sample for the decoding piece meant
that I d be starting from scratch. And, implementing something that
seemed like magic to me when I started. I started by reading a few
articles on Viterbi decoding:
I found Chip Fleming s tutorial
very useful as it included a bunch of worked examples using a
convolutional encoders with constraint length (k) of 3 instead of 4;
this makes all of the trellis diagrams half the size.
I also sent my friend, Phil Karn, a query about
this process, and he responded with a bunch of helpful suggestions,
while also recommending that I just steal his
DSP and FEC library
implementation. Of course, I don t like using code that I can t
understand, and his code only implements much longer codes than I
needed, so I d have to understand it anyways to make it work for
me. Phil s code is a marvel, but it s not exactly comprehensible to
someone who doesn t even know what a Viterbi decoder is supposed to do.
So, with Chip s tutorial on my screen, I wrote a primitive Viterbi
decoder. This did only the Viterbi step, and split that into two
phases. The first computed the cost for each state in the system for
every received pair of symbols received. It also tracked the chain of
states through the entire decode process:
for (state = 0; state < 8; state++)
struct ao_soft_sym zero = ao_soft_sym(ao_fec_encode_table[state * 2 + 0]);
struct ao_soft_sym one = ao_soft_sym(ao_fec_encode_table[state * 2 + 1]);
uint8_t zero_state = ao_next_state(state, 0);
uint8_t one_state = ao_next_state(state, 1);
int zero_cost = ao_cost(s, zero);
int one_cost = ao_cost(s, one);
zero_cost += cost[b][state];
one_cost += cost[b][state];
if (zero_cost < cost[b+1][zero_state])
prev[b+1][zero_state] = state;
cost[b+1][zero_state] = zero_cost;
if (one_cost < cost[b+1][one_state])
prev[b+1][one_state] = state;
cost[b+1][one_state] = one_cost;
At the end of the packet, it found the least costly path and walked
that from back to front, generating output bits (yes, one bit per
element of the bits array):
for (state = 1; state < 8; state++)
if (cost[b][state] < c)
c = cost[b][state];
min_state = state;
for (b = len/2; b > 0; b--)
bits[b-1] = min_state & 1;
min_state = prev[b][min_state];
Completely separate from this code were the interleaving and data
whitening stages. Keeping those separate allowed them to be tested
independently, which made debugging them far easier.
None of this code ever ran on the STM32L processor, it was instead run
in a test framework on my laptop. I first got this working with data
generated by the software convolutional encoder, then I managed to get
it to decode the raw packets that I had recorded directly from the
receiver it self.
This marked a significant milestone in my mind I d managed to
replace, in software, the CC1111 FEC encoder and decoder. However, the
decoder performance was not fast enough to manage back-to-back packets
yet. Having something in hand that worked meant that further
development would be directly comparable to something that did work,
making optimization much easier. Yet another lesson in making it work,
and then making it work fast.
Optimizing the Viterbi Decoder
The first step was to reduce memory usage within the decoder. While
it s best to defer computing the path until the very last bit has been
received, it s also true that the chances of a bit affecting old data
reduces as the distance between the new and old data increases. With
the rule of thumb being a distance of k 6 or k 7, I saved 32 output
bits for each state and wrote the oldest of 8 each time the buffer
filled up, making a distance of 24 bits between the newest saved data
and the current decoding position. That meant a fixed amount of
storage was needed for an arbitrarily long packet.
I tested a variety of different history sizes from 8 to 56 bits
(cooresponding to 16, 32 and 64 bits of saved data for each
state). With 100000 random packets generated that had gaussian noise
added to each bit, here are the error rates for the different history lengths:
| History Length | Total Packets | Correct | Incorrect |
|---|---|---|---|
| 8 bits | 100000 | 90520 (90.52%) | 9480 (9.48%) |
| 24 bits | 100000 | 93614 (93.61%) | 6386 (6.39%) |
| 56 bits | 100000 | 93620 (93.62%) | 6380 (6.38%) |
/* Metric for a zero bit */
uint32_t bitcost = ((uint32_t) (s0 ^ ao_fec_decode_table[(state<<1)]) +
(uint32_t) (s1 ^ ao_fec_decode_table[(state<<1)+1]));
/* Total path metric and state for a zero bit */
uint32_t cost0 = cost[p][state] + bitcost;
uint8_t state0 = ao_next_state(state, 0);
/* Compare the total path metric against all existing
* metrics heading into the same new state, choosing
* the least expensive and killing the others. Record
* the new lowest cost and output bit.
*/
if (cost0 < cost[n][state0])
cost[n][state0] = cost0;
bits[n][state0] = (bits[p][state] << 1) (state & 1);
/* Total path metric and state for a one bit. Because
* encoding a one is always exactly the opposite of
* encoding a zero from any state, this cost is
* 255*2 - bitcost
*/
uint32_t cost1 = cost[p][state] + 510 - bitcost;
uint8_t state1 = ao_next_state(state, 1);
if (cost1 < cost[n][state1])
cost[n][state1] = cost1;
bits[n][state1] = (bits[p][state] << 1) (state & 1);
Before this loop is run, I have to initialize cost[n] to a large
value so that the comparisons will be true for the first case to reach
each state. Phil s code, in contrast, doesn t have to initialize
cost[n] as we know which two states can reach any possible new
state. His code looks like this:
/* Metric for a zero bit */
bitcost = ((uint32_t) (s0 ^ ao_fec_decode_table[(state<<1)]) +
(uint32_t) (s1 ^ ao_fec_decode_table[(state<<1) 1]));
/* Only state and state+4 reach state<<1 with a zero bit */
/* Cost from state to state<<1 for a zero bit*/
m0 = cost[p][state] + bitcost;
/* Cost from state+4 to state<<1 for a zero bit */
m1 = cost[p][state+4] + (510 - bitcost);
/* Which source state is cheaper? */
bit = m0 > m1;
/* Record the cheaper cost and the add to the path of bits */
cost[n][state<<1] = bit ? m1 : m0;
bits[n][state<<1] = (bits[p][state + (bit<<2)] << 1) (state&1);
/* State and state+4 reach (state<<1)+1 with a one bit */
/* Cost from state to (state<<1)+1 for a one bit */
m0 -= (bitcost+bitcost-510);
/* Cost from state+4 to (state<<1)+1 for a one bit */
m1 += (bitcost+bitcost-510);
/* Which source state is cheaper? */
bit = m0 > m1;
/* Record cheaper cost and add to the path of bits */
cost[n][(state<<1)+1] = bit ? m1 : m0;
bits[n][(state<<1)+1] = (bits[p][state + (bit<<2)] << 1) (state&1);
This code does two states at a time, and so while it s slightly longer
than the above, it only needs to run half as many times. The resulting
code now decodes packets in 5.7ms.
The final version of the code can be see in
ao_fec_rx.c
The whole AltOS operating system, with many drivers and support for
CC1111, AVR and STM32L processirs is available, under the GPLv2 from
git://git.gag.com/scm/git/fw/altos
Yet another Grand Plan today: run in Masaya Volcan National Park.
Masaya
Volcano is one of the most active volcanoes in Nicaragua. It is
located only 20km south-east of Managua, so going there is as easy as
renting a taxi.
The original plan was to drive to the entrance of the National park
(on the road to Masaya city), then run up to the volcan, so from 250m
altitude up to about 600m.
I therefore rented a taxi with the kind help of Norman, and we agreed
to meet up at 08:30 at the hotel, along with No l and Daniel (who was
planning to walk up, not running).
After discussing here or there, Kurt and Gaudenz joined, both with the
intent of running up. Others would also have liked to join, but I
wasn't in the mood of organizing a full bus of Debconfers..:-). My
plan was to enjoy pyself the hike...not to manage several taxis, etc.
We thus packed in Denis blue taxi...a fancy and very visible
customized blue car that looked like it had been the topic of on
episode of the "Pimp My Ride" TV show..:-)
Sitting 4 people at the back of a regular car without hitting some
blue neon lights, or 7" TV screens is kinda tricky, but we made it.
When arriving at the park's entrance, we however learned that it is
forbidden to walk or hike up the road by foot, because of potential
high concentrations of Carbon Dioxide. Sadly, we then had to pack
again in the car and go up with it.
After reaching the parking close to the volcano's active crater
(that is said to have a small lava lake at its bottom, one of the very
few in the world), we decided to head up for going round the Nindira
crater, an inactive crater located slightly above. Unfortunately,
again, the path around the Masaya crater is forbidden to walk on,
because of landslides.
We indeed still had great fun by running around this crater (which is
about a 2.5 kilometers round trip, very very hilly and sometimes hard
to run on such as a mountain path.
After about 50 minutes and two laps (after all, we had a giant
stadium!), we headed back to the parking, packed 5 sweating geeks in
the car and went back to the hotel.
Full GPS trace is
here. I also put a few pictures on Facebook, supposedly visible by
anybody : Masaya
crater and Nindiri
crater.
It's still good to be at Debcamp before DebConf and I'm not running
all day long, contrary to what you might think by reading my posts.
Of course, I'm always busy with "social-like" activities such as doing
my best for us to have a good Cheese and
Wine Party as, now that I'm
trapped into it, people expect it to be better and better each year.
Or to revive the traditional Assassins
game.
But Debian is not only about killing cheese with socks and I try to
also achieve a few things while being here.
As of now, I can already count a few things:
The Grand Plan today was reaching the end of the road I already
explored on Tuesday. Named "Camino Las
Viudas", it's climbing in the southern hills up to a place named
"Intermzeeo del Bosque", apparently a very fancy (and expensive)
restaurant.
The road climbs in the apparently "rich" neighbourhood of Managua,
with very fancy villas as guarded by private security, as well as
private condominiums, guarded as well.
What's funny to see is that, at the bottom of the road, when it
crosses a large avenue (Pista Suburbana Espana), you can find several
auto-rickshaws,
just like those you find everywhere in India.
Those autos
apparently drive people who happen to work in these villas (like
maids, gardeners, security guards, etc.) up to the place they work.
We even met two cows wandering on the road and I hesitated waiting for
a rickshaw to show up and take a pic of the road (with holes), the
auto and the cows, then pretending that I'm no longer in Nicaragua but
back
in Karnataka.
I did the run along with No l K the, who I was very happy to find
again, restoring our now famous Debconf Runners Duet. We even found the
German Embassy!
Though climb, even if we took care to start at 6 a.m. to avoid the
heat (and also the traffic and noise). No l unfortunately had to give
up at 1km from the top of the road, when a 15% climb suddenly "killed"
his legs. I need to train him more for ups and downs..:-)
I could continue the road and finally reached the restaurant....which
was guarded by private security (as apparently everything in this
country) who unfortunately didn't let me in despite my desperate
attempts to convince him, in broken Spanish, that I just wanted to
take a few pictures and not place a bomb or rob someone...
So, I gota little bit disappointed and the only option was then....to
run down for another 8.5 kilometers, accelerating all the way, to finish
nearly at 14 km/h on Managua's sidewalks...Fun.
Great run (nearly 400m positive slope in less than 17km). Next
challenge : find another such nice run in the neighbourhood! Maybe
Volcan Masaya tomorrow.
GPS trace is here.
I spent a bunch of the past week trying to figure out why my UEFI bootloader code was crashing in bizarre ways. It turns out to be a known issue that various people have hit in the past. After a lot of staring (and swearing) I finally got to the point where I could run a debugger against a running UEFI binary under qemu and found that I was entering a function with valid arguments but executing it with invalid ones. After spending a while crying on IRC people suggested that maybe the red zone was getting corrupted, and it turned out that this was the problem.Next.