assoc_array.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. ========================================
  2. GENERIC ASSOCIATIVE ARRAY IMPLEMENTATION
  3. ========================================
  4. Contents:
  5. - Overview.
  6. - The public API.
  7. - Edit script.
  8. - Operations table.
  9. - Manipulation functions.
  10. - Access functions.
  11. - Index key form.
  12. - Internal workings.
  13. - Basic internal tree layout.
  14. - Shortcuts.
  15. - Splitting and collapsing nodes.
  16. - Non-recursive iteration.
  17. - Simultaneous alteration and iteration.
  18. ========
  19. OVERVIEW
  20. ========
  21. This associative array implementation is an object container with the following
  22. properties:
  23. (1) Objects are opaque pointers. The implementation does not care where they
  24. point (if anywhere) or what they point to (if anything).
  25. [!] NOTE: Pointers to objects _must_ be zero in the least significant bit.
  26. (2) Objects do not need to contain linkage blocks for use by the array. This
  27. permits an object to be located in multiple arrays simultaneously.
  28. Rather, the array is made up of metadata blocks that point to objects.
  29. (3) Objects require index keys to locate them within the array.
  30. (4) Index keys must be unique. Inserting an object with the same key as one
  31. already in the array will replace the old object.
  32. (5) Index keys can be of any length and can be of different lengths.
  33. (6) Index keys should encode the length early on, before any variation due to
  34. length is seen.
  35. (7) Index keys can include a hash to scatter objects throughout the array.
  36. (8) The array can iterated over. The objects will not necessarily come out in
  37. key order.
  38. (9) The array can be iterated over whilst it is being modified, provided the
  39. RCU readlock is being held by the iterator. Note, however, under these
  40. circumstances, some objects may be seen more than once. If this is a
  41. problem, the iterator should lock against modification. Objects will not
  42. be missed, however, unless deleted.
  43. (10) Objects in the array can be looked up by means of their index key.
  44. (11) Objects can be looked up whilst the array is being modified, provided the
  45. RCU readlock is being held by the thread doing the look up.
  46. The implementation uses a tree of 16-pointer nodes internally that are indexed
  47. on each level by nibbles from the index key in the same manner as in a radix
  48. tree. To improve memory efficiency, shortcuts can be emplaced to skip over
  49. what would otherwise be a series of single-occupancy nodes. Further, nodes
  50. pack leaf object pointers into spare space in the node rather than making an
  51. extra branch until as such time an object needs to be added to a full node.
  52. ==============
  53. THE PUBLIC API
  54. ==============
  55. The public API can be found in <linux/assoc_array.h>. The associative array is
  56. rooted on the following structure:
  57. struct assoc_array {
  58. ...
  59. };
  60. The code is selected by enabling CONFIG_ASSOCIATIVE_ARRAY.
  61. EDIT SCRIPT
  62. -----------
  63. The insertion and deletion functions produce an 'edit script' that can later be
  64. applied to effect the changes without risking ENOMEM. This retains the
  65. preallocated metadata blocks that will be installed in the internal tree and
  66. keeps track of the metadata blocks that will be removed from the tree when the
  67. script is applied.
  68. This is also used to keep track of dead blocks and dead objects after the
  69. script has been applied so that they can be freed later. The freeing is done
  70. after an RCU grace period has passed - thus allowing access functions to
  71. proceed under the RCU read lock.
  72. The script appears as outside of the API as a pointer of the type:
  73. struct assoc_array_edit;
  74. There are two functions for dealing with the script:
  75. (1) Apply an edit script.
  76. void assoc_array_apply_edit(struct assoc_array_edit *edit);
  77. This will perform the edit functions, interpolating various write barriers
  78. to permit accesses under the RCU read lock to continue. The edit script
  79. will then be passed to call_rcu() to free it and any dead stuff it points
  80. to.
  81. (2) Cancel an edit script.
  82. void assoc_array_cancel_edit(struct assoc_array_edit *edit);
  83. This frees the edit script and all preallocated memory immediately. If
  84. this was for insertion, the new object is _not_ released by this function,
  85. but must rather be released by the caller.
  86. These functions are guaranteed not to fail.
  87. OPERATIONS TABLE
  88. ----------------
  89. Various functions take a table of operations:
  90. struct assoc_array_ops {
  91. ...
  92. };
  93. This points to a number of methods, all of which need to be provided:
  94. (1) Get a chunk of index key from caller data:
  95. unsigned long (*get_key_chunk)(const void *index_key, int level);
  96. This should return a chunk of caller-supplied index key starting at the
  97. *bit* position given by the level argument. The level argument will be a
  98. multiple of ASSOC_ARRAY_KEY_CHUNK_SIZE and the function should return
  99. ASSOC_ARRAY_KEY_CHUNK_SIZE bits. No error is possible.
  100. (2) Get a chunk of an object's index key.
  101. unsigned long (*get_object_key_chunk)(const void *object, int level);
  102. As the previous function, but gets its data from an object in the array
  103. rather than from a caller-supplied index key.
  104. (3) See if this is the object we're looking for.
  105. bool (*compare_object)(const void *object, const void *index_key);
  106. Compare the object against an index key and return true if it matches and
  107. false if it doesn't.
  108. (4) Diff the index keys of two objects.
  109. int (*diff_objects)(const void *object, const void *index_key);
  110. Return the bit position at which the index key of the specified object
  111. differs from the given index key or -1 if they are the same.
  112. (5) Free an object.
  113. void (*free_object)(void *object);
  114. Free the specified object. Note that this may be called an RCU grace
  115. period after assoc_array_apply_edit() was called, so synchronize_rcu() may
  116. be necessary on module unloading.
  117. MANIPULATION FUNCTIONS
  118. ----------------------
  119. There are a number of functions for manipulating an associative array:
  120. (1) Initialise an associative array.
  121. void assoc_array_init(struct assoc_array *array);
  122. This initialises the base structure for an associative array. It can't
  123. fail.
  124. (2) Insert/replace an object in an associative array.
  125. struct assoc_array_edit *
  126. assoc_array_insert(struct assoc_array *array,
  127. const struct assoc_array_ops *ops,
  128. const void *index_key,
  129. void *object);
  130. This inserts the given object into the array. Note that the least
  131. significant bit of the pointer must be zero as it's used to type-mark
  132. pointers internally.
  133. If an object already exists for that key then it will be replaced with the
  134. new object and the old one will be freed automatically.
  135. The index_key argument should hold index key information and is
  136. passed to the methods in the ops table when they are called.
  137. This function makes no alteration to the array itself, but rather returns
  138. an edit script that must be applied. -ENOMEM is returned in the case of
  139. an out-of-memory error.
  140. The caller should lock exclusively against other modifiers of the array.
  141. (3) Delete an object from an associative array.
  142. struct assoc_array_edit *
  143. assoc_array_delete(struct assoc_array *array,
  144. const struct assoc_array_ops *ops,
  145. const void *index_key);
  146. This deletes an object that matches the specified data from the array.
  147. The index_key argument should hold index key information and is
  148. passed to the methods in the ops table when they are called.
  149. This function makes no alteration to the array itself, but rather returns
  150. an edit script that must be applied. -ENOMEM is returned in the case of
  151. an out-of-memory error. NULL will be returned if the specified object is
  152. not found within the array.
  153. The caller should lock exclusively against other modifiers of the array.
  154. (4) Delete all objects from an associative array.
  155. struct assoc_array_edit *
  156. assoc_array_clear(struct assoc_array *array,
  157. const struct assoc_array_ops *ops);
  158. This deletes all the objects from an associative array and leaves it
  159. completely empty.
  160. This function makes no alteration to the array itself, but rather returns
  161. an edit script that must be applied. -ENOMEM is returned in the case of
  162. an out-of-memory error.
  163. The caller should lock exclusively against other modifiers of the array.
  164. (5) Destroy an associative array, deleting all objects.
  165. void assoc_array_destroy(struct assoc_array *array,
  166. const struct assoc_array_ops *ops);
  167. This destroys the contents of the associative array and leaves it
  168. completely empty. It is not permitted for another thread to be traversing
  169. the array under the RCU read lock at the same time as this function is
  170. destroying it as no RCU deferral is performed on memory release -
  171. something that would require memory to be allocated.
  172. The caller should lock exclusively against other modifiers and accessors
  173. of the array.
  174. (6) Garbage collect an associative array.
  175. int assoc_array_gc(struct assoc_array *array,
  176. const struct assoc_array_ops *ops,
  177. bool (*iterator)(void *object, void *iterator_data),
  178. void *iterator_data);
  179. This iterates over the objects in an associative array and passes each one
  180. to iterator(). If iterator() returns true, the object is kept. If it
  181. returns false, the object will be freed. If the iterator() function
  182. returns true, it must perform any appropriate refcount incrementing on the
  183. object before returning.
  184. The internal tree will be packed down if possible as part of the iteration
  185. to reduce the number of nodes in it.
  186. The iterator_data is passed directly to iterator() and is otherwise
  187. ignored by the function.
  188. The function will return 0 if successful and -ENOMEM if there wasn't
  189. enough memory.
  190. It is possible for other threads to iterate over or search the array under
  191. the RCU read lock whilst this function is in progress. The caller should
  192. lock exclusively against other modifiers of the array.
  193. ACCESS FUNCTIONS
  194. ----------------
  195. There are two functions for accessing an associative array:
  196. (1) Iterate over all the objects in an associative array.
  197. int assoc_array_iterate(const struct assoc_array *array,
  198. int (*iterator)(const void *object,
  199. void *iterator_data),
  200. void *iterator_data);
  201. This passes each object in the array to the iterator callback function.
  202. iterator_data is private data for that function.
  203. This may be used on an array at the same time as the array is being
  204. modified, provided the RCU read lock is held. Under such circumstances,
  205. it is possible for the iteration function to see some objects twice. If
  206. this is a problem, then modification should be locked against. The
  207. iteration algorithm should not, however, miss any objects.
  208. The function will return 0 if no objects were in the array or else it will
  209. return the result of the last iterator function called. Iteration stops
  210. immediately if any call to the iteration function results in a non-zero
  211. return.
  212. (2) Find an object in an associative array.
  213. void *assoc_array_find(const struct assoc_array *array,
  214. const struct assoc_array_ops *ops,
  215. const void *index_key);
  216. This walks through the array's internal tree directly to the object
  217. specified by the index key..
  218. This may be used on an array at the same time as the array is being
  219. modified, provided the RCU read lock is held.
  220. The function will return the object if found (and set *_type to the object
  221. type) or will return NULL if the object was not found.
  222. INDEX KEY FORM
  223. --------------
  224. The index key can be of any form, but since the algorithms aren't told how long
  225. the key is, it is strongly recommended that the index key includes its length
  226. very early on before any variation due to the length would have an effect on
  227. comparisons.
  228. This will cause leaves with different length keys to scatter away from each
  229. other - and those with the same length keys to cluster together.
  230. It is also recommended that the index key begin with a hash of the rest of the
  231. key to maximise scattering throughout keyspace.
  232. The better the scattering, the wider and lower the internal tree will be.
  233. Poor scattering isn't too much of a problem as there are shortcuts and nodes
  234. can contain mixtures of leaves and metadata pointers.
  235. The index key is read in chunks of machine word. Each chunk is subdivided into
  236. one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and
  237. on a 64-bit CPU, 16 levels. Unless the scattering is really poor, it is
  238. unlikely that more than one word of any particular index key will have to be
  239. used.
  240. =================
  241. INTERNAL WORKINGS
  242. =================
  243. The associative array data structure has an internal tree. This tree is
  244. constructed of two types of metadata blocks: nodes and shortcuts.
  245. A node is an array of slots. Each slot can contain one of four things:
  246. (*) A NULL pointer, indicating that the slot is empty.
  247. (*) A pointer to an object (a leaf).
  248. (*) A pointer to a node at the next level.
  249. (*) A pointer to a shortcut.
  250. BASIC INTERNAL TREE LAYOUT
  251. --------------------------
  252. Ignoring shortcuts for the moment, the nodes form a multilevel tree. The index
  253. key space is strictly subdivided by the nodes in the tree and nodes occur on
  254. fixed levels. For example:
  255. Level: 0 1 2 3
  256. =============== =============== =============== ===============
  257. NODE D
  258. NODE B NODE C +------>+---+
  259. +------>+---+ +------>+---+ | | 0 |
  260. NODE A | | 0 | | | 0 | | +---+
  261. +---+ | +---+ | +---+ | : :
  262. | 0 | | : : | : : | +---+
  263. +---+ | +---+ | +---+ | | f |
  264. | 1 |---+ | 3 |---+ | 7 |---+ +---+
  265. +---+ +---+ +---+
  266. : : : : | 8 |---+
  267. +---+ +---+ +---+ | NODE E
  268. | e |---+ | f | : : +------>+---+
  269. +---+ | +---+ +---+ | 0 |
  270. | f | | | f | +---+
  271. +---+ | +---+ : :
  272. | NODE F +---+
  273. +------>+---+ | f |
  274. | 0 | NODE G +---+
  275. +---+ +------>+---+
  276. : : | | 0 |
  277. +---+ | +---+
  278. | 6 |---+ : :
  279. +---+ +---+
  280. : : | f |
  281. +---+ +---+
  282. | f |
  283. +---+
  284. In the above example, there are 7 nodes (A-G), each with 16 slots (0-f).
  285. Assuming no other meta data nodes in the tree, the key space is divided thusly:
  286. KEY PREFIX NODE
  287. ========== ====
  288. 137* D
  289. 138* E
  290. 13[0-69-f]* C
  291. 1[0-24-f]* B
  292. e6* G
  293. e[0-57-f]* F
  294. [02-df]* A
  295. So, for instance, keys with the following example index keys will be found in
  296. the appropriate nodes:
  297. INDEX KEY PREFIX NODE
  298. =============== ======= ====
  299. 13694892892489 13 C
  300. 13795289025897 137 D
  301. 13889dde88793 138 E
  302. 138bbb89003093 138 E
  303. 1394879524789 12 C
  304. 1458952489 1 B
  305. 9431809de993ba - A
  306. b4542910809cd - A
  307. e5284310def98 e F
  308. e68428974237 e6 G
  309. e7fffcbd443 e F
  310. f3842239082 - A
  311. To save memory, if a node can hold all the leaves in its portion of keyspace,
  312. then the node will have all those leaves in it and will not have any metadata
  313. pointers - even if some of those leaves would like to be in the same slot.
  314. A node can contain a heterogeneous mix of leaves and metadata pointers.
  315. Metadata pointers must be in the slots that match their subdivisions of key
  316. space. The leaves can be in any slot not occupied by a metadata pointer. It
  317. is guaranteed that none of the leaves in a node will match a slot occupied by a
  318. metadata pointer. If the metadata pointer is there, any leaf whose key matches
  319. the metadata key prefix must be in the subtree that the metadata pointer points
  320. to.
  321. In the above example list of index keys, node A will contain:
  322. SLOT CONTENT INDEX KEY (PREFIX)
  323. ==== =============== ==================
  324. 1 PTR TO NODE B 1*
  325. any LEAF 9431809de993ba
  326. any LEAF b4542910809cd
  327. e PTR TO NODE F e*
  328. any LEAF f3842239082
  329. and node B:
  330. 3 PTR TO NODE C 13*
  331. any LEAF 1458952489
  332. SHORTCUTS
  333. ---------
  334. Shortcuts are metadata records that jump over a piece of keyspace. A shortcut
  335. is a replacement for a series of single-occupancy nodes ascending through the
  336. levels. Shortcuts exist to save memory and to speed up traversal.
  337. It is possible for the root of the tree to be a shortcut - say, for example,
  338. the tree contains at least 17 nodes all with key prefix '1111'. The insertion
  339. algorithm will insert a shortcut to skip over the '1111' keyspace in a single
  340. bound and get to the fourth level where these actually become different.
  341. SPLITTING AND COLLAPSING NODES
  342. ------------------------------
  343. Each node has a maximum capacity of 16 leaves and metadata pointers. If the
  344. insertion algorithm finds that it is trying to insert a 17th object into a
  345. node, that node will be split such that at least two leaves that have a common
  346. key segment at that level end up in a separate node rooted on that slot for
  347. that common key segment.
  348. If the leaves in a full node and the leaf that is being inserted are
  349. sufficiently similar, then a shortcut will be inserted into the tree.
  350. When the number of objects in the subtree rooted at a node falls to 16 or
  351. fewer, then the subtree will be collapsed down to a single node - and this will
  352. ripple towards the root if possible.
  353. NON-RECURSIVE ITERATION
  354. -----------------------
  355. Each node and shortcut contains a back pointer to its parent and the number of
  356. slot in that parent that points to it. None-recursive iteration uses these to
  357. proceed rootwards through the tree, going to the parent node, slot N + 1 to
  358. make sure progress is made without the need for a stack.
  359. The backpointers, however, make simultaneous alteration and iteration tricky.
  360. SIMULTANEOUS ALTERATION AND ITERATION
  361. -------------------------------------
  362. There are a number of cases to consider:
  363. (1) Simple insert/replace. This involves simply replacing a NULL or old
  364. matching leaf pointer with the pointer to the new leaf after a barrier.
  365. The metadata blocks don't change otherwise. An old leaf won't be freed
  366. until after the RCU grace period.
  367. (2) Simple delete. This involves just clearing an old matching leaf. The
  368. metadata blocks don't change otherwise. The old leaf won't be freed until
  369. after the RCU grace period.
  370. (3) Insertion replacing part of a subtree that we haven't yet entered. This
  371. may involve replacement of part of that subtree - but that won't affect
  372. the iteration as we won't have reached the pointer to it yet and the
  373. ancestry blocks are not replaced (the layout of those does not change).
  374. (4) Insertion replacing nodes that we're actively processing. This isn't a
  375. problem as we've passed the anchoring pointer and won't switch onto the
  376. new layout until we follow the back pointers - at which point we've
  377. already examined the leaves in the replaced node (we iterate over all the
  378. leaves in a node before following any of its metadata pointers).
  379. We might, however, re-see some leaves that have been split out into a new
  380. branch that's in a slot further along than we were at.
  381. (5) Insertion replacing nodes that we're processing a dependent branch of.
  382. This won't affect us until we follow the back pointers. Similar to (4).
  383. (6) Deletion collapsing a branch under us. This doesn't affect us because the
  384. back pointers will get us back to the parent of the new node before we
  385. could see the new node. The entire collapsed subtree is thrown away
  386. unchanged - and will still be rooted on the same slot, so we shouldn't
  387. process it a second time as we'll go back to slot + 1.
  388. Note:
  389. (*) Under some circumstances, we need to simultaneously change the parent
  390. pointer and the parent slot pointer on a node (say, for example, we
  391. inserted another node before it and moved it up a level). We cannot do
  392. this without locking against a read - so we have to replace that node too.
  393. However, when we're changing a shortcut into a node this isn't a problem
  394. as shortcuts only have one slot and so the parent slot number isn't used
  395. when traversing backwards over one. This means that it's okay to change
  396. the slot number first - provided suitable barriers are used to make sure
  397. the parent slot number is read after the back pointer.
  398. Obsolete blocks and leaves are freed up after an RCU grace period has passed,
  399. so as long as anyone doing walking or iteration holds the RCU read lock, the
  400. old superstructure should not go away on them.