← Documents Documentation/core-api/assoc_array.rst GitHub 원문 ↗

Linux 6.18.37 · Core API

Generic Associative Array Implementation

RCU-safe opaque object container의 edit script API, callback table, 16-way radix-like tree, shortcut, node split·collapse와 concurrent iteration 규칙을 설명합니다.

Source pathDocumentation/core-api/assoc_array.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

assoc_array.rst:1-554

generic associative array는 unique index key로 opaque pointer를 저장하며 16-slot node, leaf packing과 shortcut을 조합해 memory와 traversal 비용을 줄입니다.

수정 API는 필요한 metadata를 미리 할당한 edit script를 반환하고 적용 단계에서 write barrier와 RCU grace period를 사용해 concurrent reader를 보호합니다.

RCU read lock 아래 lookup과 iteration은 수정과 동시에 진행할 수 있습니다. 일부 leaf를 다시 볼 수는 있지만 삭제되지 않은 object를 놓치지 않도록 back pointer와 node 교체 규칙을 설계했습니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

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

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Generic associative array의 성질

1-55

`Generic Associative Array Implementation`은 opaque object pointer를 보관하는 container입니다. 구현은 pointer가 실제로 어디를 가리키는지 또는 무엇을 가리키는지 알 필요가 없습니다.

object pointer의 least significant bit는 반드시 0이어야 합니다. 구현이 내부 pointer type 표시용으로 이 bit를 사용합니다.

  • object 자체에 array linkage block을 넣지 않습니다. metadata block이 object를 가리키므로 같은 object를 여러 array에 동시에 둘 수 있습니다.
  • object를 찾으려면 index key가 필요하며 key는 고유해야 합니다. 같은 key로 insert하면 기존 object를 교체합니다.
  • index key는 길이가 서로 달라도 되고 임의 길이일 수 있지만, 길이에 따른 차이가 나타나기 전에 key 앞부분에 length를 encode하는 편이 좋습니다.
  • key에 hash를 넣어 object를 array 전체에 흩을 수 있습니다.
  • array를 iteration할 수 있지만 object가 반드시 key 순서로 나오지는 않습니다.
  • iterator가 RCU read lock을 잡으면 수정 중에도 iteration할 수 있습니다. object를 두 번 볼 수 있으므로 문제가 되면 modifier와 lock해야 하지만 삭제되지 않은 object를 놓치지는 않습니다.
  • index key로 lookup할 수 있으며 lookup thread가 RCU read lock을 잡으면 수정과 동시에 검색할 수 있습니다.

내부 구현은 radix tree처럼 각 level에서 index key nibble로 선택하는 16-pointer node tree를 사용합니다. memory 효율을 높이기 위해 single-occupancy node 연속 구간을 shortcut으로 건너뛰고, node가 가득 차 새 branch가 필요해질 때까지 남는 slot에 leaf object pointer를 함께 pack합니다.

Public API와 edit script

56-110

public API는 `<linux/assoc_array.h>`에 있고 associative array의 root는 다음 structure입니다.

struct assoc_array {
        ...
};

다음 명령으로 `CONFIG_ASSOCIATIVE_ARRAY`를 활성화해 code를 선택합니다.

./script/config -e ASSOCIATIVE_ARRAY

insert와 delete function은 나중에 적용할 `edit script`를 생성합니다. internal tree에 설치할 metadata block을 미리 allocate하고 적용 시 제거할 block도 기록하므로 실제 변경 시 `ENOMEM` 위험이 없습니다.

script 적용 뒤에는 dead block과 dead object도 기록하여 나중에 해제합니다. RCU grace period가 지난 뒤 free하므로 access function은 RCU read lock 아래 계속 진행할 수 있습니다.

API에서 script는 다음 opaque pointer type으로 보입니다.

struct assoc_array_edit;

edit script를 적용하는 function은 다음과 같습니다.

void assoc_array_apply_edit(struct assoc_array_edit *edit);

`assoc_array_apply_edit()`은 여러 write barrier를 배치하며 edit을 실행해 RCU read lock 아래의 access가 계속되게 합니다. 이어 script를 `call_rcu()`에 넘겨 script와 가리키는 dead object를 해제합니다.

edit script를 취소하는 function은 다음과 같습니다.

void assoc_array_cancel_edit(struct assoc_array_edit *edit);

`assoc_array_cancel_edit()`은 script와 preallocated memory를 즉시 해제합니다. insert용 script였다면 새 object는 해제하지 않으므로 caller가 직접 release해야 합니다. 두 function은 실패하지 않습니다.

assoc_array_ops callback 규약

111-164

여러 API function은 다음 operation table을 받습니다.

struct assoc_array_ops {
        ...
};

모든 method를 제공해야 합니다.

unsigned long (*get_key_chunk)(const void *index_key, int level);

`get_key_chunk()`는 caller가 제공한 index key에서 `level` bit 위치부터 `ASSOC_ARRAY_KEY_CHUNK_SIZE` bits를 반환합니다. `level`은 chunk size의 배수이며 오류는 발생하지 않습니다.

unsigned long (*get_object_key_chunk)(const void *object, int level);

`get_object_key_chunk()`는 같은 방식으로 array 안 object의 index key에서 chunk를 얻습니다.

bool (*compare_object)(const void *object, const void *index_key);

`compare_object()`는 object와 index key를 비교해 일치하면 `true`, 아니면 `false`를 반환합니다.

int (*diff_objects)(const void *object, const void *index_key);

`diff_objects()`는 지정 object의 index key가 주어진 key와 처음 달라지는 bit position을 반환하고 같으면 `-1`을 반환합니다.

void (*free_object)(void *object);

`free_object()`는 object를 해제합니다. `assoc_array_apply_edit()` 뒤 RCU grace period가 지난 후 호출될 수 있으므로 module unload에는 `synchronize_rcu()`가 필요할 수 있습니다.

초기화, insert·replace와 delete

165-221

associative array base structure는 다음 function으로 초기화하며 실패하지 않습니다.

void assoc_array_init(struct assoc_array *array);

object insert 또는 replace interface는 다음과 같습니다.

struct assoc_array_edit *
assoc_array_insert(struct assoc_array *array,
                   const struct assoc_array_ops *ops,
                   const void *index_key,
                   void *object);

`assoc_array_insert()`에 넘기는 object pointer의 least significant bit는 내부 type mark에 쓰이므로 0이어야 합니다. 같은 key의 object가 이미 있으면 새 object로 교체하고 기존 object는 자동 해제합니다.

`index_key`는 operation table method에 전달할 key 정보를 담습니다. function은 array를 직접 바꾸지 않고 적용해야 할 edit script를 반환하며 out-of-memory면 `-ENOMEM`을 반환합니다. caller는 다른 modifier와 배타적으로 lock해야 합니다.

object delete interface는 다음과 같습니다.

struct assoc_array_edit *
assoc_array_delete(struct assoc_array *array,
                   const struct assoc_array_ops *ops,
                   const void *index_key);

`assoc_array_delete()`는 지정 key와 일치하는 object를 삭제할 edit script를 만듭니다. `index_key`는 ops method로 전달됩니다. out-of-memory면 `-ENOMEM`, object를 찾지 못하면 `NULL`을 반환하며 caller는 다른 modifier와 배타적으로 lock해야 합니다.

clear, destroy와 garbage collection

222-279

모든 object를 지우고 array를 완전히 비우는 interface입니다.

struct assoc_array_edit *
assoc_array_clear(struct assoc_array *array,
                  const struct assoc_array_ops *ops);

`assoc_array_clear()`도 직접 수정하지 않고 적용할 edit script를 반환하며 `-ENOMEM`이 가능하고 다른 modifier와 배타적으로 lock해야 합니다.

array 내용을 destroy하고 완전히 비우는 interface입니다.

void assoc_array_destroy(struct assoc_array *array,
                         const struct assoc_array_ops *ops);

`assoc_array_destroy()`는 memory release를 RCU로 지연하지 않습니다. 지연하려면 추가 allocation이 필요하기 때문입니다. 따라서 실행 중 다른 thread가 RCU read lock 아래 array를 traverse하면 안 되며 caller는 modifier와 accessor 모두에 대해 배타적으로 lock해야 합니다.

garbage collection interface는 다음과 같습니다.

int assoc_array_gc(struct assoc_array *array,
                   const struct assoc_array_ops *ops,
                   bool (*iterator)(void *object, void *iterator_data),
                   void *iterator_data);

`assoc_array_gc()`는 모든 object를 `iterator()`에 전달합니다. callback이 `true`면 object를 유지하고 `false`면 해제합니다. 유지할 때는 반환 전에 필요한 refcount 증가를 수행해야 합니다.

iteration 중 가능한 경우 internal tree를 pack하여 node 수를 줄입니다. `iterator_data`는 callback에 그대로 전달할 뿐 API가 해석하지 않습니다. 성공은 0, memory 부족은 `-ENOMEM`입니다.

GC가 진행되는 동안 다른 thread가 RCU read lock 아래 iteration 또는 search할 수 있습니다. caller는 다른 modifier에 대해서만 배타적으로 lock해야 합니다.

iteration과 key lookup

280-322

모든 object를 순회하는 interface는 다음과 같습니다.

int assoc_array_iterate(const struct assoc_array *array,
                        int (*iterator)(const void *object,
                                        void *iterator_data),
                        void *iterator_data);

`assoc_array_iterate()`는 각 object를 callback에 전달하고 `iterator_data`를 callback 전용 data로 넘깁니다. RCU read lock을 잡으면 수정과 동시에 사용할 수 있지만 일부 object를 두 번 볼 수 있습니다. 중복이 문제라면 modification을 lock해야 하며 algorithm은 object를 놓치지 않습니다.

array가 비어 있으면 0을, 그렇지 않으면 마지막 callback 결과를 반환합니다. callback이 0이 아닌 값을 반환하면 iteration을 즉시 멈춥니다.

index key로 object를 찾는 interface입니다.

void *assoc_array_find(const struct assoc_array *array,
                       const struct assoc_array_ops *ops,
                       const void *index_key);

`assoc_array_find()`는 internal tree를 직접 따라 key가 지정한 object로 갑니다. RCU read lock을 잡으면 수정과 동시에 사용할 수 있습니다. 찾으면 object를 반환하고 `*_type`을 object type으로 설정하며, 찾지 못하면 `NULL`을 반환합니다.

Index key 형식과 scattering

323-348

index key는 어떤 형식도 가능하지만 algorithm은 key 길이를 따로 알지 못합니다. 길이 차이가 comparison에 영향을 주기 전에 key 앞부분에 length를 포함할 것을 강하게 권장합니다.

그러면 길이가 다른 key의 leaf는 서로 흩어지고 같은 길이 key는 함께 모입니다. key 나머지 부분의 hash를 시작에 두면 keyspace 전체 scattering을 최대화할 수 있습니다.

scattering이 좋을수록 internal tree는 더 넓고 낮아집니다. 나쁘더라도 shortcut이 있고 node가 leaf와 metadata pointer를 섞어 담을 수 있어 심각한 문제는 아닙니다.

index key는 machine word chunk로 읽고 각 chunk를 level당 nibble, 즉 4 bits로 나눕니다. 32-bit CPU에서는 word 하나로 8 levels, 64-bit CPU에서는 16 levels를 처리합니다. scattering이 매우 나쁘지 않다면 특정 key에서 word 하나보다 많이 사용할 가능성은 작습니다.

내부 node와 shortcut

349-362

associative array 내부 tree는 node와 shortcut 두 종류 metadata block으로 구성됩니다.

node는 slot array이며 각 slot에는 네 종류 가운데 하나가 들어갑니다.

  • `NULL` pointer: 빈 slot
  • object pointer: leaf
  • 다음 level node pointer
  • shortcut pointer

기본 내부 tree layout과 leaf packing

363-459

shortcut을 제외하면 node는 multilevel tree를 이룹니다. index keyspace는 node에 의해 엄격히 분할되고 node는 고정 level에 놓입니다. 원문의 7-node ASCII tree를 연결 관계로 구조화하면 다음과 같습니다.

A-G node tree
parent nodeslotchild nodechild level
A1B1
AeF1
B3C2
F6G2
C7D3
C8E3

각 node는 0-f의 16 slots를 가지며 표시된 slot이 다음 metadata node로 연결됩니다.

다른 metadata node가 없다고 가정하면 key prefix별 담당 node는 다음과 같습니다.

key prefixnode
137*D
138*E
13[0-69-f]*C
1[0-24-f]*B
e6*G
e[0-57-f]*F
[02-df]*A

예제 index key가 위치할 node는 다음과 같습니다.

index keyprefixnode
1369489289248913C
13795289025897137D
13889dde88793 / 138bbb89003093138E
139487952478913C
14589524891B
9431809de993ba / b4542910809cd / f3842239082-A
e5284310def98 / e7fffcbd443eF
e68428974237e6G

memory 절약을 위해 node가 자기 keyspace의 모든 leaf를 담을 수 있으면 일부 leaf가 같은 logical slot을 원하더라도 metadata pointer 없이 모두 그 node에 둡니다.

node는 leaf와 metadata pointer를 섞어 담을 수 있습니다. metadata pointer는 keyspace subdivision과 일치하는 slot에 있어야 하지만 leaf는 metadata가 차지하지 않은 아무 slot에나 둘 수 있습니다. metadata slot의 prefix와 일치하는 leaf는 반드시 그 pointer가 가리키는 subtree에 있으므로 같은 node에 남지 않습니다.

nodeslotcontentkey/prefix
A1PTR TO NODE B1*
AanyLEAF9431809de993ba
AanyLEAFb4542910809cd
AePTR TO NODE Fe*
AanyLEAFf3842239082
B3PTR TO NODE C13*
BanyLEAF1458952489

single-occupancy level을 건너뛰는 shortcut

460-473

shortcut은 keyspace 일부를 한 번에 건너뛰는 metadata record로, 여러 level에 이어진 single-occupancy node를 대체하여 memory를 절약하고 traversal을 빠르게 합니다.

tree root 자체가 shortcut일 수도 있습니다. 예를 들어 key prefix `1111`을 공유하는 node가 17개 이상이면 insertion algorithm은 `1111` keyspace를 한 번에 건너뛰어 실제 차이가 생기는 fourth level로 가는 shortcut을 넣습니다.

node split·collapse와 non-recursive iteration

474-501

node maximum capacity는 leaf와 metadata pointer 합계 16개입니다. 17번째 object를 넣으려 하면 현재 level에서 공통 key segment를 가진 leaf 최소 두 개를 그 segment slot에 root를 둔 별도 node로 분리합니다.

full node의 leaf와 새 leaf가 충분히 비슷하면 tree에 shortcut도 삽입합니다. 한 node 아래 subtree의 object 수가 16개 이하로 줄면 subtree를 node 하나로 collapse하고 가능하면 root 방향으로 연쇄 적용합니다.

각 node와 shortcut은 parent back pointer와 parent에서 자신을 가리키는 slot number를 가집니다. non-recursive iteration은 이를 이용해 parent 방향으로 올라가고 parent node의 slot `N + 1`부터 계속하여 stack 없이도 전진합니다.

이 back pointer 구조는 modification과 iteration을 동시에 수행할 때 추가 주의가 필요합니다.

수정과 iteration의 동시 수행

502-554

동시 수정과 iteration에서는 다음 경우를 고려합니다.

  • 단순 insert/replace: barrier 뒤 `NULL` 또는 기존 matching leaf pointer만 새 leaf로 교체합니다. metadata는 바뀌지 않고 기존 leaf는 RCU grace period 뒤 해제합니다.
  • 단순 delete: 기존 matching leaf를 지웁니다. metadata는 바뀌지 않고 leaf는 grace period 뒤 해제합니다.
  • 아직 들어가지 않은 subtree 일부를 insertion이 교체: 아직 그 pointer에 도달하지 않았고 ancestor layout은 바뀌지 않으므로 iteration에 영향이 없습니다.
  • 현재 처리 중인 node를 insertion이 교체: anchoring pointer를 이미 지났으므로 back pointer를 따라갈 때까지 새 layout으로 전환하지 않습니다. 다만 뒤쪽 slot의 새 branch로 split된 leaf를 다시 볼 수 있습니다.
  • 현재 처리하는 dependent branch의 ancestor node를 insertion이 교체: back pointer를 따라가기 전까지 영향이 없으며 앞 경우와 비슷합니다.
  • 현재 아래에 있는 branch를 deletion이 collapse: back pointer가 새 node를 보기 전에 그 parent로 돌려보냅니다. 폐기된 subtree는 같은 slot에 그대로 root되어 있으므로 slot + 1로 돌아가 두 번 처리하지 않습니다.

parent pointer와 parent slot pointer를 동시에 바꿔야 하는 경우 read와 lock하지 않고는 안전하게 바꿀 수 없으므로 해당 node도 교체해야 합니다. shortcut을 node로 바꿀 때는 shortcut slot이 하나뿐이라 backward traversal에서 parent slot number를 쓰지 않으므로, 적절한 barrier로 parent slot number가 back pointer 뒤에 읽히게 하면 slot number부터 바꿔도 됩니다.

obsolete block과 leaf는 RCU grace period 뒤 해제됩니다. walk나 iteration을 수행하는 모든 code가 RCU read lock을 잡는 한 이전 superstructure가 사용 중 사라지지 않습니다.