Search Trees Revisted

I have been investigating search trees to see if binary search trees’ memory layout can, in practice, make a large difference in performance. Now that I’ve fixed the bugs in my test application, I can say: yes! The theory here is in so-called “cache-oblivious” algorithms. The idea is that you can use divide-and-conquer algorithms and data structures to exploit locality and ensure that at some point you will be working with the granularity of your memory transfer size (such as the size of a cache line or disk block).

How well does it work? Take a look:

This machine has a 2 meg L2 cache and 32 K L1 d-cache. The size of nodes in this test was 32 bytes, so the L1 cache is blown at 2**10 items, and the L2 cache at 2**16.

With the exception of “base,” the trees are all laid out in an array; “vEB” is the cache-oblivious version in which the tree uses a van Emde Boas layout: the top half of the tree is stored in the array, followed by each of the subtrees in left-to-right order, recursively. Unfortunately, constructing the tree dynamically is rather complicated.

So far I’m just exploring ground that’s already been covered, but I do think this is an interesting class of data structures that hasn’t trickled out into the real world yet.

A tale of two search trees

As a warm up for a research topic I’m doing this semester, I am looking at static search tree performance. Consider the following tree fragment where nodes are numbered according to BFS order:

            1
      2            3
   4     5      6      7
  8 9  10 11  12 13  14 15

The nodes are located in memory wherever malloc() put them. An interesting question is whether a different in-memory layout has better search performance. One possible layout is in an array with the following order: 1,2,3,4,8,9,5,10,11,6,12,13,7,14,15 (this pattern is not original to me).

So far, the answer, surprisingly to me, is: not with this layout. With a benchmark of 10 million searches of a randomly-inserted (otherwise unbalanced) tree, I get:

Original Tree: 77s
Reordered Tree: 87s

The tree searches are exactly the same — only the memory layout changed. I can reduce these numbers quite a bit by using -O2 and reducing the size of tree nodes, but there’s still a consistent net loss to the array ordering.

I suspect my cache-emptying routines don’t, but if not, it will be interesting to see where I made the stupid mistake / mental lapse.

Hummus

HummusAnge and I have been on a real Hummus kick lately for some reason. A container of Sabra is usually gone within a few minutes of being opened around here. So I decided to save a few trips to the store and try making it at home. Turns out, this is really easy: dump a can of chick peas, 1/4 c each of olive oil, water, and tahini (finding this is the hard part), a garlic clove and 1-2 tbsp of vinegar into the food processor, and press “On.” A little time spent chilling in the fridge and it’s good to go. A couple of roasted habaneros wouldn’t be a bad addition, either.

I also made my own pita chips from pita bread. While tasty and a lot cheaper than pre-made chips, I think that is far too much work when you’re hungry.

Android rebuilt

While stuck inside for days due to snow, I once again downloaded the Android source trees from the repos. I plan to update my Android wifi page with better, step-by-step instructions to go from nothing to a working set of wireless utilities on the phone. In the meantime, I’ve re-familiarized myself with the current Android build environment (for various values of current — this uses donut since as far as I know, eclair doesn’t have a definition for the Dream (G1/ADP1) phone yet).

I do have to say that things in this area have improved a lot. While it still took some google-fu to figure out which branch to check out to get the correct software (tag donut-plus-aosp), buildling the entire image from scratch was rather straightforward (. build/envsetup.sh; lunch aosp_dream_us-eng; make). My main complaint is that the build system is far too slow to use for day-to-day work. Is Google still not eating their dogfood here?

So far I have libnl, iw, and packetspammer now integrated properly via Android.mk makefiles, and a custom kernel plus the support modules for wl1251. Unfortunately, space is really tight on the system partition, so the TI driver had to go to make room for everything. I’m still waiting for someone to port the Android runtime to emdebian or maemo with /usr on the sdcard, but perhaps I’ll mess around with bind mounts until then.

It seems wl1251 SDIO doesn’t like the new power-saving code, so that is something else I’ll look into soon. For now, one can disable that in the driver or possibly via “iwconfig power off”.

wl1251: cmd set ps mode
wl1251: cmd configure
mmc0: Data timeout
wl1251: ERROR sdio write failed (-110)
...
wl1251: ERROR elp wakeup timeout

Storage Menagerie

I recently found myself needing to become familiar with the disk layouts of a few filesystems for a future research project. At the same time, I wanted to experience the fail whale that is github.com (my other git trees are hosted on repo.or.cz, which is spare and of tenuous funding, but works just fine). So over the weekend I threw together this little git tree.

Not much there, just ext2 and yaffs2 so far. I chose the latter because I wanted to look at a log-structured filesystem, while simultaneously producing something useful for Android work. I plan to add btrfs shortly and maybe some other log FS. This is just junk code: if you really want to use these filesystems in FUSE, there are much better implementations. Also there’s a great hack out there to run the kernel FS implementations in userspace via UML.

Still, it’s fun reinventing the wheel, and it’s a nice way to get a handle on this stuff.

New GPG Key

After 10 years, I finally received an encrypted email from the ether. Which reminded me that:

  1. The key goes to bobc@ieee.org, which I no longer own
  2. There are probably numerous security holes with the old versions of gpg and/or Debian openssl used to generate the keypair
  3. The key is over 10 years old so NSA have cracked it long ago

Thus, it has been revoked. Let it be widely disseminated that my new key fingerprint is:

037A AD54 51B3 09AD 2362 93EF 7154 040D C976 F35E

19110

Welcome belatedly to the tens. I suppose I should summarize the previous year as is my typical MO in January.

We kicked off 2k9 freezing our appendages watching the inauguration in DC. Still worth it.

Angeline settled in to her new private practice, wowing patients and colleagues alike with her acumen and meticulousness. At the same time, in a series of poor decisions, I gained a renewed respect for Clark Kent jobs as I went part time with mine to attend grad school.

We cheered the Caps on in another playoff run from our seats in aisle 117, row G. I took ice skating lessons. My cred as honorary Canadian waxes.

We spent some time in Germany, increasing our vocabulary slightly beyond words learned from Castle Wolfenstein.

I’m close to making good pizza at home. Ange is mastering Cirque du Soleil yoga. She has also picked up lots of trivia on hockey great Bobby Orr, and learned the true meaning of “imaret” through daily application to the NYT crossword puzzles.

My goal of 100 kernel patches in 2009 was reached (123). This year, my goal is to be a better maintainer and stop sitting on patches, even while having much less time to contribute due to school.

’10 promises to be a big year as we continue that whole nucleotide ordering experiment.

JBoss Hash

Here’s how to figure out the hashes of method names used by JBoss’ RMI invoker from the shell. The first two numbers in the method signature form the length of the string. Maybe there’s a better way to do the backrefs in sed, but you do need to swap them around.

$ echo $[`printf "0031ping(Ljava/lang/String;)V" | 
    sha1sum | 
    sed -e "s/(..)(..)(..)(..)(..)(..)(..)(..).*/0x87654321/g"`]

Don’t ask me why I figured that out.

Numerology

I’m technically on break from school now, although I’m still putting the final polish on one last project. But things have slowed down enough that I can bore you with technical crap again.

There’s an interesting section of TPOP wherein the authors discuss studying the “numerology” of a bug; that is, look for patterns in the data instead of just looking at the code. I’ve had a lot of practice with this idea lately when trying to decipher kernel crashes with nothing but an Oops message to go on (these being much easier than infrequent lockups with no output at all!). It’s quite useful for userspace as well, if you are using a language where memory corruption is a fact of life. To show why, here’s a lengthy anecdote about how I recently used the power of man ascii to find and fix a memory corruption bug in about five minutes while racing to meet a project deadline.

First, some background: in the kernel, linked lists are implemented by embedding the next and previous pointers directly into the linked object, by way of the struct list_node. For example:

struct list_node {
    struct list_node *next;
    struct list_node *prev;
};

/* one item in a list */
struct item {
    int id;
    struct list_node list;
};

/* some other object that has a list of items */
struct bar {
    struct list_node item_list_head;
};

This is a curious construction, but once you get used to it, it’s quite handy — you can embed an object in multiple simultaneous lists without having to worry about the lifetime of void pointers, and without having to malloc container structures all the time. The list code is object-agnostic, operating only on the list_node structures, but of course you need a way to get from a struct list_node back to the object that contains it. For that, there is the container_of macro and friends. These are just C macros that, given the address of the struct list_node, the variable name of the structure, and the type of the item in which the struct is embedded, finds the start of the containing structure with a little pointer arithmetic.

I had implemented a similar set of list routines for a userspace program and started getting weird crashes, so I fired up gdb to see something like the following:

gdb > p *item
$1 = {id = 134269966, item_list = {next = 0x804b008, prev = 0x804b008},
      global_list = {next = 0x72657375, prev = 0x40313030},
      src = "machine.org", '00' <repeats 69 times>}

Had I taken a minute to look at this in detail, I would have noticed that the value of id was quite higher than it should be, and that the leading part of src was truncated. But what jumped out at me immediately was that global_list.next and global_list.prev were obviously wrong pointer values. In Linux on x86, heap addresses are usually above 0x0804b000, and stack addresses are below 0xbfffc000. Clearly, the global_list pointers don’t meet these ranges. However, the item_list.next and item_list.prev addresses looked fine. So either the global list pointers weren’t being initialized, or they were being corrupted somehow. Sometimes that kind of corruption happens if the list pointers aren’t updated properly, causing the code to follow a next pointer into random memory, but then it would be unlikely that the item_list pointers and src had meaningful values. Plus, I unit-tested the list routines and was pretty confident they were working correctly.

My initial theory was that something was overwriting the global_list struct, and the byte values looked to be in the ascii range. So I turned to the ascii(7) man page, which gives you a nice little table of hex ordinal to character value mappings. Looking at the bytes in turn gives: 0x72 = ‘r’, 0x65 = ‘e’, 0x73 = ‘s’, 0x75 = ‘u’, 0x40 = ‘@’, 0x31 = ‘1’, 0x30 = ‘0’, 0x30 = ‘0’. Since x86 is little-endian, this works out to the string “user001@”, which should have been the first part of src. The bug must be where the code filled in the src string. However, that code looked fine. I then decided that the pointer to the entire structure must be offset somehow. Sure enough, when I looked at the surrounding code, I saw something like this:

    struct list_node *n;
    struct item *item;

    for (n = list_start(&item_list_head); n;
         n = list_next(&item_list_head, n))
    {
        item = container_of(n, struct item, global_list);
        /* strncpy and other stuff ... */
    }

Oops. I had passed the wrong list name to container_of(), with the effect that the item pointer was actually 8 bytes prior to the real start of the structure. As a result, the string copy overwrote the pointer values of just one of the list structures, a bug which didn’t actually have a negative effect until later.

There are morals a-plenty, including “macros are evil” and “this is why templates were invented.” Yet, I’ve seen Linus use this technique more than once when others were stuck on a kernel memory corruption bug, so I’ll go with “Kernighan and Pike are always right[1].”

[1] Except, I’m still not sold on using capital letters in Go. Perhaps in time I can be convinced.

job

I love getting stuff like this in my inbox:

Must have skills:
Expert in C or C++ programming
(Windows || Mac || Linux) system internals.
(Windows || Mac || Linux) kernel and device driver development
Experienced in assembly and debugging

Desired Skills: Experience writing/integrating MS SQL Stored
Procedures into C/C++ software. C (especially object oriented
like abstraction with pointers).

lolz.