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.

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

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.

Ath5k AP Mode

People seem to keep asking about this, despite there being a quality page on kernel.org on how to run an AP with any mac80211 driver. So for what it’s worth, here’s how my setup works. Note if you are seeing flakiness with certain clients, e.g. it works fine with a computer but not with your cell phone, it is likely there is some bug with the power saving handling. I’m currently working on a few such issues, so it may be fixed soon enough.

To get started, you need the following:

  • some sort of network uplink, like a wired ethernet port
  • a kernel with ap mode support for ath5k (2.6.31+) and netfilter (for NAT)
  • dnsmasq
  • hostapd

You have two basic options for interfacing the wireless network with your wired network. One is by using a bridge directly to the wired network. Another is to use NAT so the wireless network is on its own subnet. The former is more typical of an embedded device, but I prefer the latter on my home LAN, so that’s what I’ll describe.

Turn off any wireless daemon (such as NetworkManager) while you experiment with hostapd to ensure that nothing else has the device open.

The hostapd.conf is large but self-explanatory. One can get away with a rather small config file if using the defaults. This example sets up an AP on wlan0 with the SSID “hostapd_ath5k”. It has a wlan-facing IP address 192.168.10.1, it’s on channel 11, supports 802.11g, and has the WPA pre-shared key “my_password”. I have also set up EAP, it works but requires making a lot of certs and such, so Google is your friend here.

hostapd.conf:

interface=wlan0
driver=nl80211
ssid=hostapd_ath5k
hw_mode=g
channel=11
auth_algs=3
own_ip_addr=192.168.10.1
wpa=1
wpa_passphrase=my_password
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP

For DHCP and DNS forwarding, I use dnsmasq. This couldn’t be easier. Just put something like the following in /etc/dnsmasq.conf:

   dhcp-range=192.168.10.50,192.168.10.150,12h

This will hand out addresses in the 192.168.10.X subnet. Then I use a small script to enable IP masquerading before launching hostapd (note, it will flush all iptables rules, which may not be what you want, so use with caution).

run.sh:

#!/bin/sh

DEV=wlan0
GW_DEV=eth0

# set IPs
ifconfig $DEV down
ifconfig $DEV up
ifconfig $DEV 192.168.10.1

# setup ip masq
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -F
iptables -t nat -F
iptables -A FORWARD -i $DEV -j ACCEPT
iptables -A FORWARD -o $DEV -j ACCEPT
iptables -t nat -A POSTROUTING -o $GW_DEV -j MASQUERADE

./hostapd hostapd.conf

Running the script will launch hostapd, and if all goes well, you’ll see it show up in scans from other computers.

If anything goes wrong, make sure:

  • you’ve started dnsmasq
  • you have a valid backhaul connection
  • you aren’t using power save mode on client (iwconfig wlan0 power off — see previous comment about PS bugs)
  • you haven’t found a bug

Constantly folded

I was poking around with the disassembler the other day, which is never a good idea. One of the things I looked at was the following bit in the RX hotpath for ath5k:

rxs->qual = rs.rs_rssi * 100 / 35;

Now, that’s not a very significant calculation, and I doubt it will show up in profiles, but divides automatically trigger my “can we do better?” reflex. I was interested to see how gcc compiled this, because we have division by a constant, but we first have to multiply by a variable due to order of operations.

We can generally remove a division by multiplying by its reciprocal. Interestingly, gcc already does that. I couldn’t quite puzzle out all of the steps, but here’s the disassembly with my best guess:

; multiply eax by 100, store in ecx
 80483d0:	6b c8 64             	imul   $0x64,%eax,%ecx

; load (32 / 35) * 2**32 into edx
 80483d3:	ba eb a0 0e ea       	mov    $0xea0ea0eb,%edx

; multiply 100 * argc by 32/35 and store in edx:eax
 80483d8:	89 c8                	mov    %ecx,%eax
 80483da:	f7 ea                	imul   %edx

; take top 32 bits of result in edx (when sign extended, the
; complement of the final answer?) and add it back to the numerator
 80483dc:	8d 04 0a             	lea    (%edx,%ecx,1),%eax
 80483df:	89 c2                	mov    %eax,%edx

; divide by 32 to remove pre-multiply
 80483e1:	c1 fa 05             	sar    $0x5,%edx

; subtract one if we need to round
 80483e4:	89 c8                	mov    %ecx,%eax
 80483e6:	c1 f8 1f             	sar    $0x1f,%eax
 80483e9:	29 c2                	sub    %eax,%edx


So then I went hunting for the constant folding code in gcc, and there are all kinds of tricks like this. Very neat. Along the way I also found a link to the book Hacker’s Delight, now wish-listed.

In the original code, the denominator is a bit arbitrary, we could pick a different number that is more amenable to shifts and adds and save a multiply, but it’s hardly worth it.