xarray: Add XArray iterators
[linux-block.git] / include / linux / xarray.h
CommitLineData
f6bb2a2c
MW
1/* SPDX-License-Identifier: GPL-2.0+ */
2#ifndef _LINUX_XARRAY_H
3#define _LINUX_XARRAY_H
4/*
5 * eXtensible Arrays
6 * Copyright (c) 2017 Microsoft Corporation
3d0186bb 7 * Author: Matthew Wilcox <willy@infradead.org>
3159f943
MW
8 *
9 * See Documentation/core-api/xarray.rst for how to use the XArray.
f6bb2a2c
MW
10 */
11
3159f943 12#include <linux/bug.h>
f8d5d0cc 13#include <linux/compiler.h>
9b89a035 14#include <linux/gfp.h>
f8d5d0cc 15#include <linux/kconfig.h>
ad3d6c72
MW
16#include <linux/kernel.h>
17#include <linux/rcupdate.h>
f6bb2a2c 18#include <linux/spinlock.h>
3159f943
MW
19#include <linux/types.h>
20
21/*
22 * The bottom two bits of the entry determine how the XArray interprets
23 * the contents:
24 *
25 * 00: Pointer entry
26 * 10: Internal entry
27 * x1: Value entry or tagged pointer
28 *
29 * Attempting to store internal entries in the XArray is a bug.
02c02bf1
MW
30 *
31 * Most internal entries are pointers to the next node in the tree.
32 * The following internal entries have a special meaning:
33 *
34 * 0-62: Sibling entries
35 * 256: Retry entry
ad3d6c72
MW
36 *
37 * Errors are also represented as internal entries, but use the negative
38 * space (-4094 to -2). They're never stored in the slots array; only
39 * returned by the normal API.
3159f943
MW
40 */
41
42#define BITS_PER_XA_VALUE (BITS_PER_LONG - 1)
43
44/**
45 * xa_mk_value() - Create an XArray entry from an integer.
46 * @v: Value to store in XArray.
47 *
48 * Context: Any context.
49 * Return: An entry suitable for storing in the XArray.
50 */
51static inline void *xa_mk_value(unsigned long v)
52{
53 WARN_ON((long)v < 0);
54 return (void *)((v << 1) | 1);
55}
56
57/**
58 * xa_to_value() - Get value stored in an XArray entry.
59 * @entry: XArray entry.
60 *
61 * Context: Any context.
62 * Return: The value stored in the XArray entry.
63 */
64static inline unsigned long xa_to_value(const void *entry)
65{
66 return (unsigned long)entry >> 1;
67}
68
69/**
70 * xa_is_value() - Determine if an entry is a value.
71 * @entry: XArray entry.
72 *
73 * Context: Any context.
74 * Return: True if the entry is a value, false if it is a pointer.
75 */
76static inline bool xa_is_value(const void *entry)
77{
78 return (unsigned long)entry & 1;
79}
80
81/**
82 * xa_tag_pointer() - Create an XArray entry for a tagged pointer.
83 * @p: Plain pointer.
84 * @tag: Tag value (0, 1 or 3).
85 *
86 * If the user of the XArray prefers, they can tag their pointers instead
87 * of storing value entries. Three tags are available (0, 1 and 3).
88 * These are distinct from the xa_mark_t as they are not replicated up
89 * through the array and cannot be searched for.
90 *
91 * Context: Any context.
92 * Return: An XArray entry.
93 */
94static inline void *xa_tag_pointer(void *p, unsigned long tag)
95{
96 return (void *)((unsigned long)p | tag);
97}
98
99/**
100 * xa_untag_pointer() - Turn an XArray entry into a plain pointer.
101 * @entry: XArray entry.
102 *
103 * If you have stored a tagged pointer in the XArray, call this function
104 * to get the untagged version of the pointer.
105 *
106 * Context: Any context.
107 * Return: A pointer.
108 */
109static inline void *xa_untag_pointer(void *entry)
110{
111 return (void *)((unsigned long)entry & ~3UL);
112}
113
114/**
115 * xa_pointer_tag() - Get the tag stored in an XArray entry.
116 * @entry: XArray entry.
117 *
118 * If you have stored a tagged pointer in the XArray, call this function
119 * to get the tag of that pointer.
120 *
121 * Context: Any context.
122 * Return: A tag.
123 */
124static inline unsigned int xa_pointer_tag(void *entry)
125{
126 return (unsigned long)entry & 3UL;
127}
f6bb2a2c 128
02c02bf1
MW
129/*
130 * xa_mk_internal() - Create an internal entry.
131 * @v: Value to turn into an internal entry.
132 *
133 * Context: Any context.
134 * Return: An XArray internal entry corresponding to this value.
135 */
136static inline void *xa_mk_internal(unsigned long v)
137{
138 return (void *)((v << 2) | 2);
139}
140
141/*
142 * xa_to_internal() - Extract the value from an internal entry.
143 * @entry: XArray entry.
144 *
145 * Context: Any context.
146 * Return: The value which was stored in the internal entry.
147 */
148static inline unsigned long xa_to_internal(const void *entry)
149{
150 return (unsigned long)entry >> 2;
151}
152
153/*
154 * xa_is_internal() - Is the entry an internal entry?
155 * @entry: XArray entry.
156 *
157 * Context: Any context.
158 * Return: %true if the entry is an internal entry.
159 */
160static inline bool xa_is_internal(const void *entry)
161{
162 return ((unsigned long)entry & 3) == 2;
163}
164
ad3d6c72
MW
165/**
166 * xa_is_err() - Report whether an XArray operation returned an error
167 * @entry: Result from calling an XArray function
168 *
169 * If an XArray operation cannot complete an operation, it will return
170 * a special value indicating an error. This function tells you
171 * whether an error occurred; xa_err() tells you which error occurred.
172 *
173 * Context: Any context.
174 * Return: %true if the entry indicates an error.
175 */
176static inline bool xa_is_err(const void *entry)
177{
178 return unlikely(xa_is_internal(entry));
179}
180
181/**
182 * xa_err() - Turn an XArray result into an errno.
183 * @entry: Result from calling an XArray function.
184 *
185 * If an XArray operation cannot complete an operation, it will return
186 * a special pointer value which encodes an errno. This function extracts
187 * the errno from the pointer value, or returns 0 if the pointer does not
188 * represent an errno.
189 *
190 * Context: Any context.
191 * Return: A negative errno or 0.
192 */
193static inline int xa_err(void *entry)
194{
195 /* xa_to_internal() would not do sign extension. */
196 if (xa_is_err(entry))
197 return (long)entry >> 2;
198 return 0;
199}
200
9b89a035
MW
201typedef unsigned __bitwise xa_mark_t;
202#define XA_MARK_0 ((__force xa_mark_t)0U)
203#define XA_MARK_1 ((__force xa_mark_t)1U)
204#define XA_MARK_2 ((__force xa_mark_t)2U)
205#define XA_PRESENT ((__force xa_mark_t)8U)
206#define XA_MARK_MAX XA_MARK_2
207
58d6ea30
MW
208enum xa_lock_type {
209 XA_LOCK_IRQ = 1,
210 XA_LOCK_BH = 2,
211};
212
9b89a035
MW
213/*
214 * Values for xa_flags. The radix tree stores its GFP flags in the xa_flags,
215 * and we remain compatible with that.
216 */
58d6ea30
MW
217#define XA_FLAGS_LOCK_IRQ ((__force gfp_t)XA_LOCK_IRQ)
218#define XA_FLAGS_LOCK_BH ((__force gfp_t)XA_LOCK_BH)
9b89a035
MW
219#define XA_FLAGS_MARK(mark) ((__force gfp_t)((1U << __GFP_BITS_SHIFT) << \
220 (__force unsigned)(mark)))
221
f8d5d0cc
MW
222/**
223 * struct xarray - The anchor of the XArray.
224 * @xa_lock: Lock that protects the contents of the XArray.
225 *
226 * To use the xarray, define it statically or embed it in your data structure.
227 * It is a very small data structure, so it does not usually make sense to
228 * allocate it separately and keep a pointer to it in your data structure.
229 *
230 * You may use the xa_lock to protect your own data structures as well.
231 */
232/*
233 * If all of the entries in the array are NULL, @xa_head is a NULL pointer.
234 * If the only non-NULL entry in the array is at index 0, @xa_head is that
235 * entry. If any other entry in the array is non-NULL, @xa_head points
236 * to an @xa_node.
237 */
238struct xarray {
239 spinlock_t xa_lock;
240/* private: The rest of the data structure is not to be used directly. */
241 gfp_t xa_flags;
242 void __rcu * xa_head;
243};
244
245#define XARRAY_INIT(name, flags) { \
246 .xa_lock = __SPIN_LOCK_UNLOCKED(name.xa_lock), \
247 .xa_flags = flags, \
248 .xa_head = NULL, \
249}
250
251/**
252 * DEFINE_XARRAY_FLAGS() - Define an XArray with custom flags.
253 * @name: A string that names your XArray.
254 * @flags: XA_FLAG values.
255 *
256 * This is intended for file scope definitions of XArrays. It declares
257 * and initialises an empty XArray with the chosen name and flags. It is
258 * equivalent to calling xa_init_flags() on the array, but it does the
259 * initialisation at compiletime instead of runtime.
260 */
261#define DEFINE_XARRAY_FLAGS(name, flags) \
262 struct xarray name = XARRAY_INIT(name, flags)
263
264/**
265 * DEFINE_XARRAY() - Define an XArray.
266 * @name: A string that names your XArray.
267 *
268 * This is intended for file scope definitions of XArrays. It declares
269 * and initialises an empty XArray with the chosen name. It is equivalent
270 * to calling xa_init() on the array, but it does the initialisation at
271 * compiletime instead of runtime.
272 */
273#define DEFINE_XARRAY(name) DEFINE_XARRAY_FLAGS(name, 0)
274
275void xa_init_flags(struct xarray *, gfp_t flags);
ad3d6c72 276void *xa_load(struct xarray *, unsigned long index);
58d6ea30 277void *xa_store(struct xarray *, unsigned long index, void *entry, gfp_t);
41aec91f
MW
278void *xa_cmpxchg(struct xarray *, unsigned long index,
279 void *old, void *entry, gfp_t);
9b89a035
MW
280bool xa_get_mark(struct xarray *, unsigned long index, xa_mark_t);
281void xa_set_mark(struct xarray *, unsigned long index, xa_mark_t);
282void xa_clear_mark(struct xarray *, unsigned long index, xa_mark_t);
b803b428
MW
283void *xa_find(struct xarray *xa, unsigned long *index,
284 unsigned long max, xa_mark_t) __attribute__((nonnull(2)));
285void *xa_find_after(struct xarray *xa, unsigned long *index,
286 unsigned long max, xa_mark_t) __attribute__((nonnull(2)));
f8d5d0cc
MW
287
288/**
289 * xa_init() - Initialise an empty XArray.
290 * @xa: XArray.
291 *
292 * An empty XArray is full of NULL entries.
293 *
294 * Context: Any context.
295 */
296static inline void xa_init(struct xarray *xa)
297{
298 xa_init_flags(xa, 0);
299}
300
ad3d6c72
MW
301/**
302 * xa_empty() - Determine if an array has any present entries.
303 * @xa: XArray.
304 *
305 * Context: Any context.
306 * Return: %true if the array contains only NULL pointers.
307 */
308static inline bool xa_empty(const struct xarray *xa)
309{
310 return xa->xa_head == NULL;
311}
312
9b89a035
MW
313/**
314 * xa_marked() - Inquire whether any entry in this array has a mark set
315 * @xa: Array
316 * @mark: Mark value
317 *
318 * Context: Any context.
319 * Return: %true if any entry has this mark set.
320 */
321static inline bool xa_marked(const struct xarray *xa, xa_mark_t mark)
322{
323 return xa->xa_flags & XA_FLAGS_MARK(mark);
324}
325
58d6ea30
MW
326/**
327 * xa_erase() - Erase this entry from the XArray.
328 * @xa: XArray.
329 * @index: Index of entry.
330 *
331 * This function is the equivalent of calling xa_store() with %NULL as
332 * the third argument. The XArray does not need to allocate memory, so
333 * the user does not need to provide GFP flags.
334 *
335 * Context: Process context. Takes and releases the xa_lock.
336 * Return: The entry which used to be at this index.
337 */
338static inline void *xa_erase(struct xarray *xa, unsigned long index)
339{
340 return xa_store(xa, index, NULL, 0);
341}
342
41aec91f
MW
343/**
344 * xa_insert() - Store this entry in the XArray unless another entry is
345 * already present.
346 * @xa: XArray.
347 * @index: Index into array.
348 * @entry: New entry.
349 * @gfp: Memory allocation flags.
350 *
351 * If you would rather see the existing entry in the array, use xa_cmpxchg().
352 * This function is for users who don't care what the entry is, only that
353 * one is present.
354 *
355 * Context: Process context. Takes and releases the xa_lock.
356 * May sleep if the @gfp flags permit.
357 * Return: 0 if the store succeeded. -EEXIST if another entry was present.
358 * -ENOMEM if memory could not be allocated.
359 */
360static inline int xa_insert(struct xarray *xa, unsigned long index,
361 void *entry, gfp_t gfp)
362{
363 void *curr = xa_cmpxchg(xa, index, NULL, entry, gfp);
364 if (!curr)
365 return 0;
366 if (xa_is_err(curr))
367 return xa_err(curr);
368 return -EEXIST;
369}
370
b803b428
MW
371/**
372 * xa_for_each() - Iterate over a portion of an XArray.
373 * @xa: XArray.
374 * @entry: Entry retrieved from array.
375 * @index: Index of @entry.
376 * @max: Maximum index to retrieve from array.
377 * @filter: Selection criterion.
378 *
379 * Initialise @index to the lowest index you want to retrieve from the
380 * array. During the iteration, @entry will have the value of the entry
381 * stored in @xa at @index. The iteration will skip all entries in the
382 * array which do not match @filter. You may modify @index during the
383 * iteration if you want to skip or reprocess indices. It is safe to modify
384 * the array during the iteration. At the end of the iteration, @entry will
385 * be set to NULL and @index will have a value less than or equal to max.
386 *
387 * xa_for_each() is O(n.log(n)) while xas_for_each() is O(n). You have
388 * to handle your own locking with xas_for_each(), and if you have to unlock
389 * after each iteration, it will also end up being O(n.log(n)). xa_for_each()
390 * will spin if it hits a retry entry; if you intend to see retry entries,
391 * you should use the xas_for_each() iterator instead. The xas_for_each()
392 * iterator will expand into more inline code than xa_for_each().
393 *
394 * Context: Any context. Takes and releases the RCU lock.
395 */
396#define xa_for_each(xa, entry, index, max, filter) \
397 for (entry = xa_find(xa, &index, max, filter); entry; \
398 entry = xa_find_after(xa, &index, max, filter))
399
f6bb2a2c
MW
400#define xa_trylock(xa) spin_trylock(&(xa)->xa_lock)
401#define xa_lock(xa) spin_lock(&(xa)->xa_lock)
402#define xa_unlock(xa) spin_unlock(&(xa)->xa_lock)
403#define xa_lock_bh(xa) spin_lock_bh(&(xa)->xa_lock)
404#define xa_unlock_bh(xa) spin_unlock_bh(&(xa)->xa_lock)
405#define xa_lock_irq(xa) spin_lock_irq(&(xa)->xa_lock)
406#define xa_unlock_irq(xa) spin_unlock_irq(&(xa)->xa_lock)
407#define xa_lock_irqsave(xa, flags) \
408 spin_lock_irqsave(&(xa)->xa_lock, flags)
409#define xa_unlock_irqrestore(xa, flags) \
410 spin_unlock_irqrestore(&(xa)->xa_lock, flags)
411
9b89a035 412/*
58d6ea30
MW
413 * Versions of the normal API which require the caller to hold the
414 * xa_lock. If the GFP flags allow it, they will drop the lock to
415 * allocate memory, then reacquire it afterwards. These functions
416 * may also re-enable interrupts if the XArray flags indicate the
417 * locking should be interrupt safe.
418 */
419void *__xa_erase(struct xarray *, unsigned long index);
420void *__xa_store(struct xarray *, unsigned long index, void *entry, gfp_t);
41aec91f
MW
421void *__xa_cmpxchg(struct xarray *, unsigned long index, void *old,
422 void *entry, gfp_t);
9b89a035
MW
423void __xa_set_mark(struct xarray *, unsigned long index, xa_mark_t);
424void __xa_clear_mark(struct xarray *, unsigned long index, xa_mark_t);
425
41aec91f
MW
426/**
427 * __xa_insert() - Store this entry in the XArray unless another entry is
428 * already present.
429 * @xa: XArray.
430 * @index: Index into array.
431 * @entry: New entry.
432 * @gfp: Memory allocation flags.
433 *
434 * If you would rather see the existing entry in the array, use __xa_cmpxchg().
435 * This function is for users who don't care what the entry is, only that
436 * one is present.
437 *
438 * Context: Any context. Expects xa_lock to be held on entry. May
439 * release and reacquire xa_lock if the @gfp flags permit.
440 * Return: 0 if the store succeeded. -EEXIST if another entry was present.
441 * -ENOMEM if memory could not be allocated.
442 */
443static inline int __xa_insert(struct xarray *xa, unsigned long index,
444 void *entry, gfp_t gfp)
445{
446 void *curr = __xa_cmpxchg(xa, index, NULL, entry, gfp);
447 if (!curr)
448 return 0;
449 if (xa_is_err(curr))
450 return xa_err(curr);
451 return -EEXIST;
452}
453
58d6ea30
MW
454/**
455 * xa_erase_bh() - Erase this entry from the XArray.
456 * @xa: XArray.
457 * @index: Index of entry.
458 *
459 * This function is the equivalent of calling xa_store() with %NULL as
460 * the third argument. The XArray does not need to allocate memory, so
461 * the user does not need to provide GFP flags.
462 *
463 * Context: Process context. Takes and releases the xa_lock while
464 * disabling softirqs.
465 * Return: The entry which used to be at this index.
466 */
467static inline void *xa_erase_bh(struct xarray *xa, unsigned long index)
468{
469 void *entry;
470
471 xa_lock_bh(xa);
472 entry = __xa_erase(xa, index);
473 xa_unlock_bh(xa);
474
475 return entry;
476}
477
478/**
479 * xa_erase_irq() - Erase this entry from the XArray.
480 * @xa: XArray.
481 * @index: Index of entry.
482 *
483 * This function is the equivalent of calling xa_store() with %NULL as
484 * the third argument. The XArray does not need to allocate memory, so
485 * the user does not need to provide GFP flags.
486 *
487 * Context: Process context. Takes and releases the xa_lock while
488 * disabling interrupts.
489 * Return: The entry which used to be at this index.
490 */
491static inline void *xa_erase_irq(struct xarray *xa, unsigned long index)
492{
493 void *entry;
494
495 xa_lock_irq(xa);
496 entry = __xa_erase(xa, index);
497 xa_unlock_irq(xa);
498
499 return entry;
500}
501
02c02bf1
MW
502/* Everything below here is the Advanced API. Proceed with caution. */
503
504/*
505 * The xarray is constructed out of a set of 'chunks' of pointers. Choosing
506 * the best chunk size requires some tradeoffs. A power of two recommends
507 * itself so that we can walk the tree based purely on shifts and masks.
508 * Generally, the larger the better; as the number of slots per level of the
509 * tree increases, the less tall the tree needs to be. But that needs to be
510 * balanced against the memory consumption of each node. On a 64-bit system,
511 * xa_node is currently 576 bytes, and we get 7 of them per 4kB page. If we
512 * doubled the number of slots per node, we'd get only 3 nodes per 4kB page.
513 */
514#ifndef XA_CHUNK_SHIFT
515#define XA_CHUNK_SHIFT (CONFIG_BASE_SMALL ? 4 : 6)
516#endif
517#define XA_CHUNK_SIZE (1UL << XA_CHUNK_SHIFT)
518#define XA_CHUNK_MASK (XA_CHUNK_SIZE - 1)
01959dfe
MW
519#define XA_MAX_MARKS 3
520#define XA_MARK_LONGS DIV_ROUND_UP(XA_CHUNK_SIZE, BITS_PER_LONG)
521
522/*
523 * @count is the count of every non-NULL element in the ->slots array
524 * whether that is a value entry, a retry entry, a user pointer,
525 * a sibling entry or a pointer to the next level of the tree.
526 * @nr_values is the count of every element in ->slots which is
527 * either a value entry or a sibling of a value entry.
528 */
529struct xa_node {
530 unsigned char shift; /* Bits remaining in each slot */
531 unsigned char offset; /* Slot offset in parent */
532 unsigned char count; /* Total entry count */
533 unsigned char nr_values; /* Value entry count */
534 struct xa_node __rcu *parent; /* NULL at top of tree */
535 struct xarray *array; /* The array we belong to */
536 union {
537 struct list_head private_list; /* For tree user */
538 struct rcu_head rcu_head; /* Used when freeing node */
539 };
540 void __rcu *slots[XA_CHUNK_SIZE];
541 union {
542 unsigned long tags[XA_MAX_MARKS][XA_MARK_LONGS];
543 unsigned long marks[XA_MAX_MARKS][XA_MARK_LONGS];
544 };
545};
02c02bf1 546
ad3d6c72
MW
547void xa_dump(const struct xarray *);
548void xa_dump_node(const struct xa_node *);
549
550#ifdef XA_DEBUG
551#define XA_BUG_ON(xa, x) do { \
552 if (x) { \
553 xa_dump(xa); \
554 BUG(); \
555 } \
556 } while (0)
557#define XA_NODE_BUG_ON(node, x) do { \
558 if (x) { \
559 if (node) xa_dump_node(node); \
560 BUG(); \
561 } \
562 } while (0)
563#else
564#define XA_BUG_ON(xa, x) do { } while (0)
565#define XA_NODE_BUG_ON(node, x) do { } while (0)
566#endif
567
568/* Private */
569static inline void *xa_head(const struct xarray *xa)
570{
571 return rcu_dereference_check(xa->xa_head,
572 lockdep_is_held(&xa->xa_lock));
573}
574
575/* Private */
576static inline void *xa_head_locked(const struct xarray *xa)
577{
578 return rcu_dereference_protected(xa->xa_head,
579 lockdep_is_held(&xa->xa_lock));
580}
581
582/* Private */
583static inline void *xa_entry(const struct xarray *xa,
584 const struct xa_node *node, unsigned int offset)
585{
586 XA_NODE_BUG_ON(node, offset >= XA_CHUNK_SIZE);
587 return rcu_dereference_check(node->slots[offset],
588 lockdep_is_held(&xa->xa_lock));
589}
590
591/* Private */
592static inline void *xa_entry_locked(const struct xarray *xa,
593 const struct xa_node *node, unsigned int offset)
594{
595 XA_NODE_BUG_ON(node, offset >= XA_CHUNK_SIZE);
596 return rcu_dereference_protected(node->slots[offset],
597 lockdep_is_held(&xa->xa_lock));
598}
599
9b89a035
MW
600/* Private */
601static inline struct xa_node *xa_parent(const struct xarray *xa,
602 const struct xa_node *node)
603{
604 return rcu_dereference_check(node->parent,
605 lockdep_is_held(&xa->xa_lock));
606}
607
608/* Private */
609static inline struct xa_node *xa_parent_locked(const struct xarray *xa,
610 const struct xa_node *node)
611{
612 return rcu_dereference_protected(node->parent,
613 lockdep_is_held(&xa->xa_lock));
614}
615
58d6ea30
MW
616/* Private */
617static inline void *xa_mk_node(const struct xa_node *node)
618{
619 return (void *)((unsigned long)node | 2);
620}
621
ad3d6c72
MW
622/* Private */
623static inline struct xa_node *xa_to_node(const void *entry)
624{
625 return (struct xa_node *)((unsigned long)entry - 2);
626}
627
02c02bf1
MW
628/* Private */
629static inline bool xa_is_node(const void *entry)
630{
631 return xa_is_internal(entry) && (unsigned long)entry > 4096;
632}
633
634/* Private */
635static inline void *xa_mk_sibling(unsigned int offset)
636{
637 return xa_mk_internal(offset);
638}
639
640/* Private */
641static inline unsigned long xa_to_sibling(const void *entry)
642{
643 return xa_to_internal(entry);
644}
645
646/**
647 * xa_is_sibling() - Is the entry a sibling entry?
648 * @entry: Entry retrieved from the XArray
649 *
650 * Return: %true if the entry is a sibling entry.
651 */
652static inline bool xa_is_sibling(const void *entry)
653{
654 return IS_ENABLED(CONFIG_XARRAY_MULTI) && xa_is_internal(entry) &&
655 (entry < xa_mk_sibling(XA_CHUNK_SIZE - 1));
656}
657
658#define XA_RETRY_ENTRY xa_mk_internal(256)
659
ad3d6c72
MW
660/**
661 * xa_is_retry() - Is the entry a retry entry?
662 * @entry: Entry retrieved from the XArray
663 *
664 * Return: %true if the entry is a retry entry.
665 */
666static inline bool xa_is_retry(const void *entry)
667{
668 return unlikely(entry == XA_RETRY_ENTRY);
669}
670
671/**
672 * typedef xa_update_node_t - A callback function from the XArray.
673 * @node: The node which is being processed
674 *
675 * This function is called every time the XArray updates the count of
676 * present and value entries in a node. It allows advanced users to
677 * maintain the private_list in the node.
678 *
679 * Context: The xa_lock is held and interrupts may be disabled.
680 * Implementations should not drop the xa_lock, nor re-enable
681 * interrupts.
682 */
683typedef void (*xa_update_node_t)(struct xa_node *node);
684
685/*
686 * The xa_state is opaque to its users. It contains various different pieces
687 * of state involved in the current operation on the XArray. It should be
688 * declared on the stack and passed between the various internal routines.
689 * The various elements in it should not be accessed directly, but only
690 * through the provided accessor functions. The below documentation is for
691 * the benefit of those working on the code, not for users of the XArray.
692 *
693 * @xa_node usually points to the xa_node containing the slot we're operating
694 * on (and @xa_offset is the offset in the slots array). If there is a
695 * single entry in the array at index 0, there are no allocated xa_nodes to
696 * point to, and so we store %NULL in @xa_node. @xa_node is set to
697 * the value %XAS_RESTART if the xa_state is not walked to the correct
698 * position in the tree of nodes for this operation. If an error occurs
699 * during an operation, it is set to an %XAS_ERROR value. If we run off the
700 * end of the allocated nodes, it is set to %XAS_BOUNDS.
701 */
702struct xa_state {
703 struct xarray *xa;
704 unsigned long xa_index;
705 unsigned char xa_shift;
706 unsigned char xa_sibs;
707 unsigned char xa_offset;
708 unsigned char xa_pad; /* Helps gcc generate better code */
709 struct xa_node *xa_node;
710 struct xa_node *xa_alloc;
711 xa_update_node_t xa_update;
712};
713
714/*
715 * We encode errnos in the xas->xa_node. If an error has happened, we need to
716 * drop the lock to fix it, and once we've done so the xa_state is invalid.
717 */
718#define XA_ERROR(errno) ((struct xa_node *)(((unsigned long)errno << 2) | 2UL))
719#define XAS_BOUNDS ((struct xa_node *)1UL)
720#define XAS_RESTART ((struct xa_node *)3UL)
721
722#define __XA_STATE(array, index, shift, sibs) { \
723 .xa = array, \
724 .xa_index = index, \
725 .xa_shift = shift, \
726 .xa_sibs = sibs, \
727 .xa_offset = 0, \
728 .xa_pad = 0, \
729 .xa_node = XAS_RESTART, \
730 .xa_alloc = NULL, \
731 .xa_update = NULL \
732}
733
734/**
735 * XA_STATE() - Declare an XArray operation state.
736 * @name: Name of this operation state (usually xas).
737 * @array: Array to operate on.
738 * @index: Initial index of interest.
739 *
740 * Declare and initialise an xa_state on the stack.
741 */
742#define XA_STATE(name, array, index) \
743 struct xa_state name = __XA_STATE(array, index, 0, 0)
744
745/**
746 * XA_STATE_ORDER() - Declare an XArray operation state.
747 * @name: Name of this operation state (usually xas).
748 * @array: Array to operate on.
749 * @index: Initial index of interest.
750 * @order: Order of entry.
751 *
752 * Declare and initialise an xa_state on the stack. This variant of
753 * XA_STATE() allows you to specify the 'order' of the element you
754 * want to operate on.`
755 */
756#define XA_STATE_ORDER(name, array, index, order) \
757 struct xa_state name = __XA_STATE(array, \
758 (index >> order) << order, \
759 order - (order % XA_CHUNK_SHIFT), \
760 (1U << (order % XA_CHUNK_SHIFT)) - 1)
761
762#define xas_marked(xas, mark) xa_marked((xas)->xa, (mark))
763#define xas_trylock(xas) xa_trylock((xas)->xa)
764#define xas_lock(xas) xa_lock((xas)->xa)
765#define xas_unlock(xas) xa_unlock((xas)->xa)
766#define xas_lock_bh(xas) xa_lock_bh((xas)->xa)
767#define xas_unlock_bh(xas) xa_unlock_bh((xas)->xa)
768#define xas_lock_irq(xas) xa_lock_irq((xas)->xa)
769#define xas_unlock_irq(xas) xa_unlock_irq((xas)->xa)
770#define xas_lock_irqsave(xas, flags) \
771 xa_lock_irqsave((xas)->xa, flags)
772#define xas_unlock_irqrestore(xas, flags) \
773 xa_unlock_irqrestore((xas)->xa, flags)
774
775/**
776 * xas_error() - Return an errno stored in the xa_state.
777 * @xas: XArray operation state.
778 *
779 * Return: 0 if no error has been noted. A negative errno if one has.
780 */
781static inline int xas_error(const struct xa_state *xas)
782{
783 return xa_err(xas->xa_node);
784}
785
786/**
787 * xas_set_err() - Note an error in the xa_state.
788 * @xas: XArray operation state.
789 * @err: Negative error number.
790 *
791 * Only call this function with a negative @err; zero or positive errors
792 * will probably not behave the way you think they should. If you want
793 * to clear the error from an xa_state, use xas_reset().
794 */
795static inline void xas_set_err(struct xa_state *xas, long err)
796{
797 xas->xa_node = XA_ERROR(err);
798}
799
800/**
801 * xas_invalid() - Is the xas in a retry or error state?
802 * @xas: XArray operation state.
803 *
804 * Return: %true if the xas cannot be used for operations.
805 */
806static inline bool xas_invalid(const struct xa_state *xas)
807{
808 return (unsigned long)xas->xa_node & 3;
809}
810
811/**
812 * xas_valid() - Is the xas a valid cursor into the array?
813 * @xas: XArray operation state.
814 *
815 * Return: %true if the xas can be used for operations.
816 */
817static inline bool xas_valid(const struct xa_state *xas)
818{
819 return !xas_invalid(xas);
820}
821
9b89a035
MW
822/* True if the pointer is something other than a node */
823static inline bool xas_not_node(struct xa_node *node)
824{
825 return ((unsigned long)node & 3) || !node;
826}
827
58d6ea30
MW
828/* True if the node represents head-of-tree, RESTART or BOUNDS */
829static inline bool xas_top(struct xa_node *node)
830{
831 return node <= XAS_RESTART;
832}
833
ad3d6c72
MW
834/**
835 * xas_reset() - Reset an XArray operation state.
836 * @xas: XArray operation state.
837 *
838 * Resets the error or walk state of the @xas so future walks of the
839 * array will start from the root. Use this if you have dropped the
840 * xarray lock and want to reuse the xa_state.
841 *
842 * Context: Any context.
843 */
844static inline void xas_reset(struct xa_state *xas)
845{
846 xas->xa_node = XAS_RESTART;
847}
848
849/**
850 * xas_retry() - Retry the operation if appropriate.
851 * @xas: XArray operation state.
852 * @entry: Entry from xarray.
853 *
854 * The advanced functions may sometimes return an internal entry, such as
855 * a retry entry or a zero entry. This function sets up the @xas to restart
856 * the walk from the head of the array if needed.
857 *
858 * Context: Any context.
859 * Return: true if the operation needs to be retried.
860 */
861static inline bool xas_retry(struct xa_state *xas, const void *entry)
862{
863 if (!xa_is_retry(entry))
864 return false;
865 xas_reset(xas);
866 return true;
867}
868
869void *xas_load(struct xa_state *);
58d6ea30 870void *xas_store(struct xa_state *, void *entry);
b803b428 871void *xas_find(struct xa_state *, unsigned long max);
ad3d6c72 872
9b89a035
MW
873bool xas_get_mark(const struct xa_state *, xa_mark_t);
874void xas_set_mark(const struct xa_state *, xa_mark_t);
875void xas_clear_mark(const struct xa_state *, xa_mark_t);
b803b428 876void *xas_find_marked(struct xa_state *, unsigned long max, xa_mark_t);
58d6ea30
MW
877void xas_init_marks(const struct xa_state *);
878
879bool xas_nomem(struct xa_state *, gfp_t);
b803b428 880void xas_pause(struct xa_state *);
9b89a035 881
ad3d6c72
MW
882/**
883 * xas_reload() - Refetch an entry from the xarray.
884 * @xas: XArray operation state.
885 *
886 * Use this function to check that a previously loaded entry still has
887 * the same value. This is useful for the lockless pagecache lookup where
888 * we walk the array with only the RCU lock to protect us, lock the page,
889 * then check that the page hasn't moved since we looked it up.
890 *
891 * The caller guarantees that @xas is still valid. If it may be in an
892 * error or restart state, call xas_load() instead.
893 *
894 * Return: The entry at this location in the xarray.
895 */
896static inline void *xas_reload(struct xa_state *xas)
897{
898 struct xa_node *node = xas->xa_node;
899
900 if (node)
901 return xa_entry(xas->xa, node, xas->xa_offset);
902 return xa_head(xas->xa);
903}
904
58d6ea30
MW
905/**
906 * xas_set() - Set up XArray operation state for a different index.
907 * @xas: XArray operation state.
908 * @index: New index into the XArray.
909 *
910 * Move the operation state to refer to a different index. This will
911 * have the effect of starting a walk from the top; see xas_next()
912 * to move to an adjacent index.
913 */
914static inline void xas_set(struct xa_state *xas, unsigned long index)
915{
916 xas->xa_index = index;
917 xas->xa_node = XAS_RESTART;
918}
919
920/**
921 * xas_set_order() - Set up XArray operation state for a multislot entry.
922 * @xas: XArray operation state.
923 * @index: Target of the operation.
924 * @order: Entry occupies 2^@order indices.
925 */
926static inline void xas_set_order(struct xa_state *xas, unsigned long index,
927 unsigned int order)
928{
929#ifdef CONFIG_XARRAY_MULTI
930 xas->xa_index = order < BITS_PER_LONG ? (index >> order) << order : 0;
931 xas->xa_shift = order - (order % XA_CHUNK_SHIFT);
932 xas->xa_sibs = (1 << (order % XA_CHUNK_SHIFT)) - 1;
933 xas->xa_node = XAS_RESTART;
934#else
935 BUG_ON(order > 0);
936 xas_set(xas, index);
937#endif
938}
939
940/**
941 * xas_set_update() - Set up XArray operation state for a callback.
942 * @xas: XArray operation state.
943 * @update: Function to call when updating a node.
944 *
945 * The XArray can notify a caller after it has updated an xa_node.
946 * This is advanced functionality and is only needed by the page cache.
947 */
948static inline void xas_set_update(struct xa_state *xas, xa_update_node_t update)
949{
950 xas->xa_update = update;
951}
952
b803b428
MW
953/**
954 * xas_next_entry() - Advance iterator to next present entry.
955 * @xas: XArray operation state.
956 * @max: Highest index to return.
957 *
958 * xas_next_entry() is an inline function to optimise xarray traversal for
959 * speed. It is equivalent to calling xas_find(), and will call xas_find()
960 * for all the hard cases.
961 *
962 * Return: The next present entry after the one currently referred to by @xas.
963 */
964static inline void *xas_next_entry(struct xa_state *xas, unsigned long max)
965{
966 struct xa_node *node = xas->xa_node;
967 void *entry;
968
969 if (unlikely(xas_not_node(node) || node->shift ||
970 xas->xa_offset != (xas->xa_index & XA_CHUNK_MASK)))
971 return xas_find(xas, max);
972
973 do {
974 if (unlikely(xas->xa_index >= max))
975 return xas_find(xas, max);
976 if (unlikely(xas->xa_offset == XA_CHUNK_MASK))
977 return xas_find(xas, max);
978 entry = xa_entry(xas->xa, node, xas->xa_offset + 1);
979 if (unlikely(xa_is_internal(entry)))
980 return xas_find(xas, max);
981 xas->xa_offset++;
982 xas->xa_index++;
983 } while (!entry);
984
985 return entry;
986}
987
988/* Private */
989static inline unsigned int xas_find_chunk(struct xa_state *xas, bool advance,
990 xa_mark_t mark)
991{
992 unsigned long *addr = xas->xa_node->marks[(__force unsigned)mark];
993 unsigned int offset = xas->xa_offset;
994
995 if (advance)
996 offset++;
997 if (XA_CHUNK_SIZE == BITS_PER_LONG) {
998 if (offset < XA_CHUNK_SIZE) {
999 unsigned long data = *addr & (~0UL << offset);
1000 if (data)
1001 return __ffs(data);
1002 }
1003 return XA_CHUNK_SIZE;
1004 }
1005
1006 return find_next_bit(addr, XA_CHUNK_SIZE, offset);
1007}
1008
1009/**
1010 * xas_next_marked() - Advance iterator to next marked entry.
1011 * @xas: XArray operation state.
1012 * @max: Highest index to return.
1013 * @mark: Mark to search for.
1014 *
1015 * xas_next_marked() is an inline function to optimise xarray traversal for
1016 * speed. It is equivalent to calling xas_find_marked(), and will call
1017 * xas_find_marked() for all the hard cases.
1018 *
1019 * Return: The next marked entry after the one currently referred to by @xas.
1020 */
1021static inline void *xas_next_marked(struct xa_state *xas, unsigned long max,
1022 xa_mark_t mark)
1023{
1024 struct xa_node *node = xas->xa_node;
1025 unsigned int offset;
1026
1027 if (unlikely(xas_not_node(node) || node->shift))
1028 return xas_find_marked(xas, max, mark);
1029 offset = xas_find_chunk(xas, true, mark);
1030 xas->xa_offset = offset;
1031 xas->xa_index = (xas->xa_index & ~XA_CHUNK_MASK) + offset;
1032 if (xas->xa_index > max)
1033 return NULL;
1034 if (offset == XA_CHUNK_SIZE)
1035 return xas_find_marked(xas, max, mark);
1036 return xa_entry(xas->xa, node, offset);
1037}
1038
1039/*
1040 * If iterating while holding a lock, drop the lock and reschedule
1041 * every %XA_CHECK_SCHED loops.
1042 */
1043enum {
1044 XA_CHECK_SCHED = 4096,
1045};
1046
1047/**
1048 * xas_for_each() - Iterate over a range of an XArray.
1049 * @xas: XArray operation state.
1050 * @entry: Entry retrieved from the array.
1051 * @max: Maximum index to retrieve from array.
1052 *
1053 * The loop body will be executed for each entry present in the xarray
1054 * between the current xas position and @max. @entry will be set to
1055 * the entry retrieved from the xarray. It is safe to delete entries
1056 * from the array in the loop body. You should hold either the RCU lock
1057 * or the xa_lock while iterating. If you need to drop the lock, call
1058 * xas_pause() first.
1059 */
1060#define xas_for_each(xas, entry, max) \
1061 for (entry = xas_find(xas, max); entry; \
1062 entry = xas_next_entry(xas, max))
1063
1064/**
1065 * xas_for_each_marked() - Iterate over a range of an XArray.
1066 * @xas: XArray operation state.
1067 * @entry: Entry retrieved from the array.
1068 * @max: Maximum index to retrieve from array.
1069 * @mark: Mark to search for.
1070 *
1071 * The loop body will be executed for each marked entry in the xarray
1072 * between the current xas position and @max. @entry will be set to
1073 * the entry retrieved from the xarray. It is safe to delete entries
1074 * from the array in the loop body. You should hold either the RCU lock
1075 * or the xa_lock while iterating. If you need to drop the lock, call
1076 * xas_pause() first.
1077 */
1078#define xas_for_each_marked(xas, entry, max, mark) \
1079 for (entry = xas_find_marked(xas, max, mark); entry; \
1080 entry = xas_next_marked(xas, max, mark))
1081
f6bb2a2c 1082#endif /* _LINUX_XARRAY_H */