Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rbtree xarray #3

Closed
wants to merge 4 commits into from
Closed
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions rbtree-xarray.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
Subject: Migrating from `RBTree` to `XArray` in Binder

# Background
Hello,

I'm working on a project to rewrite Android's
[binder driver](https://github.com/torvalds/linux/tree/master/drivers/android) in rust.
Recently we addressed some TODOs around worst-case performance by
[using red-black trees instead of a linked list](https://android-review.googlesource.com/c/kernel/common/+/2567935).
We've since learned that the upstream `RBTree` data structure is deprecated. Our understanding is that `RBTree` should
never be used for any new code, and we should use the `XArray` data structure instead.

`XArray` should be fine for all of our use cases in binder except one - the "range allocator".
We're not sure what to do for this particular case, and are looking for guidance. [The C driver uses
RBTree](https://github.com/torvalds/linux/blob/3f01e9fed8454dcd89727016c3e5b2fbb8f8e50c/drivers/android/binder_alloc.h#L83-L85),
which led us down that path in the first place.

## TLDR
**How should we use `XArray` (or some other data structure that is not deprecated) to address the following scenario?**

# Range Allocator
Range allocator stores collection of "Descriptors":
```
struct Descriptor<T> {
size: usize,
offset: usize,
data: Option<T>,
state: DescriptorState // Free, Reserved, or Allocated
}
```

## Lookups
We need to look descriptors up one of two ways:
1. Find a descriptor with a particular `offset`. Each offset in the collection is unique.
2. Find the *smallest* descriptor with a state of `Free` and a `size` greater than or equal to a given `size`. Multiple descriptors can have the same size.

## Merging
The other nuance is that neighboring descriptors (based on their `offset`) should never *both* be in a state of `Free`.
When a descriptor transitions to this state, we check it's neighbors, and merge them together accordingly, e.g.:

`(Reserved, Free, Reserved) -> (Reserved, Free, Free) -> (Reserved, Free)` (2nd and 3rd entries merged)

`(Free, Reserved, Free) -> (Free, Free, Free) -> (Free)` (all 3 entries merged into 1)

# Design
## Naive Approach
Prior to the above change, descriptors were stored in a LinkedList, which was obviously not great. It meant O(n)
lookups everywhere.
```
struct RangeAllocator<T> {
list: LinkedList<Box<Descriptor<T>>>
}
```

## Using RBTree
We improved this with a combination of two RBTree fields:
```
struct RangeAllocator<T> {
// all descriptors by offset
tree: RBTree<usize, Descriptor<T>>
// free descriptors by (size, offset)
free_tree: RBTree((usize, usize), ())
}
```

RBTree allows storing user defined structs as keys, provided they are ordered. A tuple of integers naturally satisfies this constraint.
By storing `(size, offset)`, we're able to provide `O(log(n))` lookup of a "best sized" free descriptor. Since `XArray` only supports
integer keys, we see the following options:

# Migration Options

## Option 1: Use XArray<Box<LinkedList<usize>>>
```
struct RangeAllocator<T> {
descriptors: XArray<Box<Descriptor<T>>>,
free_indices: XArray<Box<LinkedList<usize>>>
}
```

TODO: Get help explaining why this is bad. I guess We'd have 3 layers of pointers to an integer which I guess is inefficient? I
Copy link

@boqun-msft boqun-msft Jul 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How hard would it be to implement a micro-benchmark module in C (or Rust)? People usually could understand the problem better if they can reproduce it on their own.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We actually did some (very naive) benchmarking comparing LinkedList to RBTree just using kernel log timestamps. I'm not able to share this doc globally but just gave you access: https://docs.google.com/document/d/1SRJJj8MzzyjLGfBmqaybe5AOrM_GdPZdPWBYlu3YTcI/edit?resourcekey=0-AhO9TyT3L5vM5sLIOrKMQQ#bookmark=id.hrgqt03we1j2

I assume you mean creating a minimal benchmark as its own module/kunit test/something like that? That sounds feasible, I'm not sure how much bandwidth I have at the moment to do it though 😢

Another option is to implement this using our proposed XArray abstraction and do the same benchmarking we already did. Maybe the XArray<Box<LinkedList<usize>>>> won't be that bad (@Darksonn is skeptical that this will work).

p.s. - I could also copy that doc to a non-google.com gmail account for public viewing if its helpful, but thought it's a bit long winded for this purpose.

I'm also not sure how awkward traversing/modifying a list behind those 3 pointers will be.

## Option 2: Add `prev_same_size` and `next_same_size` to `Descriptor<T>`
```
struct Descriptor<T> {
// other fields
prev_same_size_index: Option<usize>
next_same_size_index: Option<usize>
}


struct RangeAllocator<T> {
descriptors: XArray<Box<Descriptor<T>>>,
free_indices: XArray<Box<usize>>
}
```
In this option, we store a single free index in the XArray, and are able to check other descriptors of the same size
via these two fields on the `Descriptor` itself. The obvious downside here is introducing lots of complexity to keep
track of all descriptors of a given size, updating these links accordingly.

## Option 3: Use another data structure?
Is there some other data structure/aproach that we haven't thought of. We're very open to suggestions :-)

Thanks in advance,

Matt