Whamcloud - gitweb
LU-13723 lustre: Convert ERR_PTR(PTR_ERR()) to ERR_CAST()
[fs/lustre-release.git] / libcfs / include / libcfs / linux / xarray.h
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
7  * Author: Matthew Wilcox <willy@infradead.org>
8  *
9  * This is taken from kernel commit:
10  *
11  * 7b785645e ("mm: fix page cache convergence regression")
12  *
13  * at kernel verison 5.2-rc2
14  *
15  * See Documentation/core-api/xarray.rst for how to use the XArray.
16  */
17 #ifdef HAVE_RADIX_TREE_EXCEPTIONAL_ENTRY
18 #include <linux/bug.h>
19 #include <linux/compiler.h>
20 #include <linux/gfp.h>
21 #include <linux/kconfig.h>
22 #include <linux/kernel.h>
23 #include <linux/rcupdate.h>
24 #include <linux/spinlock.h>
25 #include <linux/types.h>
26
27 /*
28  * The bottom two bits of the entry determine how the XArray interprets
29  * the contents:
30  *
31  * 00: Pointer entry
32  * 10: Internal entry
33  * x1: Value entry or tagged pointer
34  *
35  * Attempting to store internal entries in the XArray is a bug.
36  *
37  * Most internal entries are pointers to the next node in the tree.
38  * The following internal entries have a special meaning:
39  *
40  * 0-62: Sibling entries
41  * 256: Zero entry
42  * 257: Retry entry
43  *
44  * Errors are also represented as internal entries, but use the negative
45  * space (-4094 to -2).  They're never stored in the slots array; only
46  * returned by the normal API.
47  */
48
49 #define BITS_PER_XA_VALUE       (BITS_PER_LONG - 1)
50
51 /**
52  * xa_mk_value() - Create an XArray entry from an integer.
53  * @v: Value to store in XArray.
54  *
55  * Context: Any context.
56  * Return: An entry suitable for storing in the XArray.
57  */
58 static inline void *xa_mk_value(unsigned long v)
59 {
60         WARN_ON((long)v < 0);
61         return (void *)((v << 1) | 1);
62 }
63
64 /**
65  * xa_to_value() - Get value stored in an XArray entry.
66  * @entry: XArray entry.
67  *
68  * Context: Any context.
69  * Return: The value stored in the XArray entry.
70  */
71 static inline unsigned long xa_to_value(const void *entry)
72 {
73         return (unsigned long)entry >> 1;
74 }
75
76 /**
77  * xa_is_value() - Determine if an entry is a value.
78  * @entry: XArray entry.
79  *
80  * Context: Any context.
81  * Return: True if the entry is a value, false if it is a pointer.
82  */
83 static inline bool xa_is_value(const void *entry)
84 {
85         return (unsigned long)entry & 1;
86 }
87
88 /**
89  * xa_tag_pointer() - Create an XArray entry for a tagged pointer.
90  * @p: Plain pointer.
91  * @tag: Tag value (0, 1 or 3).
92  *
93  * If the user of the XArray prefers, they can tag their pointers instead
94  * of storing value entries.  Three tags are available (0, 1 and 3).
95  * These are distinct from the xa_mark_t as they are not replicated up
96  * through the array and cannot be searched for.
97  *
98  * Context: Any context.
99  * Return: An XArray entry.
100  */
101 static inline void *xa_tag_pointer(void *p, unsigned long tag)
102 {
103         return (void *)((unsigned long)p | tag);
104 }
105
106 /**
107  * xa_untag_pointer() - Turn an XArray entry into a plain pointer.
108  * @entry: XArray entry.
109  *
110  * If you have stored a tagged pointer in the XArray, call this function
111  * to get the untagged version of the pointer.
112  *
113  * Context: Any context.
114  * Return: A pointer.
115  */
116 static inline void *xa_untag_pointer(void *entry)
117 {
118         return (void *)((unsigned long)entry & ~3UL);
119 }
120
121 /**
122  * xa_pointer_tag() - Get the tag stored in an XArray entry.
123  * @entry: XArray entry.
124  *
125  * If you have stored a tagged pointer in the XArray, call this function
126  * to get the tag of that pointer.
127  *
128  * Context: Any context.
129  * Return: A tag.
130  */
131 static inline unsigned int xa_pointer_tag(void *entry)
132 {
133         return (unsigned long)entry & 3UL;
134 }
135
136 /*
137  * xa_mk_internal() - Create an internal entry.
138  * @v: Value to turn into an internal entry.
139  *
140  * Internal entries are used for a number of purposes.  Entries 0-255 are
141  * used for sibling entries (only 0-62 are used by the current code).  256
142  * is used for the retry entry.  257 is used for the reserved / zero entry.
143  * Negative internal entries are used to represent errnos.  Node pointers
144  * are also tagged as internal entries in some situations.
145  *
146  * Context: Any context.
147  * Return: An XArray internal entry corresponding to this value.
148  */
149 static inline void *xa_mk_internal(unsigned long v)
150 {
151         return (void *)((v << 2) | 2);
152 }
153
154 /*
155  * xa_to_internal() - Extract the value from an internal entry.
156  * @entry: XArray entry.
157  *
158  * Context: Any context.
159  * Return: The value which was stored in the internal entry.
160  */
161 static inline unsigned long xa_to_internal(const void *entry)
162 {
163         return (unsigned long)entry >> 2;
164 }
165
166 /*
167  * xa_is_internal() - Is the entry an internal entry?
168  * @entry: XArray entry.
169  *
170  * Context: Any context.
171  * Return: %true if the entry is an internal entry.
172  */
173 static inline bool xa_is_internal(const void *entry)
174 {
175         return ((unsigned long)entry & 3) == 2;
176 }
177
178 #define XA_ZERO_ENTRY           xa_mk_internal(257)
179
180 /**
181  * xa_is_zero() - Is the entry a zero entry?
182  * @entry: Entry retrieved from the XArray
183  *
184  * The normal API will return NULL as the contents of a slot containing
185  * a zero entry.  You can only see zero entries by using the advanced API.
186  *
187  * Return: %true if the entry is a zero entry.
188  */
189 static inline bool xa_is_zero(const void *entry)
190 {
191         return unlikely(entry == XA_ZERO_ENTRY);
192 }
193
194 /**
195  * xa_is_err() - Report whether an XArray operation returned an error
196  * @entry: Result from calling an XArray function
197  *
198  * If an XArray operation cannot complete an operation, it will return
199  * a special value indicating an error.  This function tells you
200  * whether an error occurred; xa_err() tells you which error occurred.
201  *
202  * Context: Any context.
203  * Return: %true if the entry indicates an error.
204  */
205 static inline bool xa_is_err(const void *entry)
206 {
207         return unlikely(xa_is_internal(entry) &&
208                         entry >= xa_mk_internal(-MAX_ERRNO));
209 }
210
211 /**
212  * xa_err() - Turn an XArray result into an errno.
213  * @entry: Result from calling an XArray function.
214  *
215  * If an XArray operation cannot complete an operation, it will return
216  * a special pointer value which encodes an errno.  This function extracts
217  * the errno from the pointer value, or returns 0 if the pointer does not
218  * represent an errno.
219  *
220  * Context: Any context.
221  * Return: A negative errno or 0.
222  */
223 static inline int xa_err(void *entry)
224 {
225         /* xa_to_internal() would not do sign extension. */
226         if (xa_is_err(entry))
227                 return (long)entry >> 2;
228         return 0;
229 }
230
231 /**
232  * struct xa_limit - Represents a range of IDs.
233  * @min: The lowest ID to allocate (inclusive).
234  * @max: The maximum ID to allocate (inclusive).
235  *
236  * This structure is used either directly or via the XA_LIMIT() macro
237  * to communicate the range of IDs that are valid for allocation.
238  * Two common ranges are predefined for you:
239  * * xa_limit_32b       - [0 - UINT_MAX]
240  * * xa_limit_31b       - [0 - INT_MAX]
241  */
242 struct xa_limit {
243         u32 max;
244         u32 min;
245 };
246
247 #define XA_LIMIT(_min, _max) (struct xa_limit) { .min = _min, .max = _max }
248
249 #define xa_limit_32b    XA_LIMIT(0, UINT_MAX)
250 #define xa_limit_31b    XA_LIMIT(0, INT_MAX)
251
252 typedef unsigned __bitwise xa_mark_t;
253 #define XA_MARK_0               ((__force xa_mark_t)0U)
254 #define XA_MARK_1               ((__force xa_mark_t)1U)
255 #define XA_MARK_2               ((__force xa_mark_t)2U)
256 #define XA_PRESENT              ((__force xa_mark_t)8U)
257 #define XA_MARK_MAX             XA_MARK_2
258 #define XA_FREE_MARK            XA_MARK_0
259
260 enum xa_lock_type {
261         XA_LOCK_IRQ = 1,
262         XA_LOCK_BH = 2,
263 };
264
265 /*
266  * Values for xa_flags.  The radix tree stores its GFP flags in the xa_flags,
267  * and we remain compatible with that.
268  */
269 #define XA_FLAGS_LOCK_IRQ       ((__force gfp_t)XA_LOCK_IRQ)
270 #define XA_FLAGS_LOCK_BH        ((__force gfp_t)XA_LOCK_BH)
271 #define XA_FLAGS_TRACK_FREE     ((__force gfp_t)4U)
272 #define XA_FLAGS_ZERO_BUSY      ((__force gfp_t)8U)
273 #define XA_FLAGS_ALLOC_WRAPPED  ((__force gfp_t)16U)
274 #define XA_FLAGS_ACCOUNT        ((__force gfp_t)32U)
275 #define XA_FLAGS_MARK(mark)     ((__force gfp_t)((1U << __GFP_BITS_SHIFT) << \
276                                                 (__force unsigned)(mark)))
277
278 /* ALLOC is for a normal 0-based alloc.  ALLOC1 is for an 1-based alloc */
279 #define XA_FLAGS_ALLOC  (XA_FLAGS_TRACK_FREE | XA_FLAGS_MARK(XA_FREE_MARK))
280 #define XA_FLAGS_ALLOC1 (XA_FLAGS_TRACK_FREE | XA_FLAGS_ZERO_BUSY)
281
282 /**
283  * struct xarray - The anchor of the XArray.
284  * @xa_lock: Lock that protects the contents of the XArray.
285  *
286  * To use the xarray, define it statically or embed it in your data structure.
287  * It is a very small data structure, so it does not usually make sense to
288  * allocate it separately and keep a pointer to it in your data structure.
289  *
290  * You may use the xa_lock to protect your own data structures as well.
291  */
292 /*
293  * If all of the entries in the array are NULL, @xa_head is a NULL pointer.
294  * If the only non-NULL entry in the array is at index 0, @xa_head is that
295  * entry.  If any other entry in the array is non-NULL, @xa_head points
296  * to an @xa_node.
297  */
298 struct xarray {
299         spinlock_t      xa_lock;
300 /* private: The rest of the data structure is not to be used directly. */
301         gfp_t           xa_flags;
302         void __rcu      *xa_head;
303 };
304
305 #define XARRAY_INIT(name, flags) {                              \
306         .xa_lock = __SPIN_LOCK_UNLOCKED(name.xa_lock),          \
307         .xa_flags = flags,                                      \
308         .xa_head = NULL,                                        \
309 }
310
311 /**
312  * DEFINE_XARRAY_FLAGS() - Define an XArray with custom flags.
313  * @name: A string that names your XArray.
314  * @flags: XA_FLAG values.
315  *
316  * This is intended for file scope definitions of XArrays.  It declares
317  * and initialises an empty XArray with the chosen name and flags.  It is
318  * equivalent to calling xa_init_flags() on the array, but it does the
319  * initialisation at compiletime instead of runtime.
320  */
321 #define DEFINE_XARRAY_FLAGS(name, flags)                                \
322         struct xarray name = XARRAY_INIT(name, flags)
323
324 /**
325  * DEFINE_XARRAY() - Define an XArray.
326  * @name: A string that names your XArray.
327  *
328  * This is intended for file scope definitions of XArrays.  It declares
329  * and initialises an empty XArray with the chosen name.  It is equivalent
330  * to calling xa_init() on the array, but it does the initialisation at
331  * compiletime instead of runtime.
332  */
333 #define DEFINE_XARRAY(name) DEFINE_XARRAY_FLAGS(name, 0)
334
335 /**
336  * DEFINE_XARRAY_ALLOC() - Define an XArray which allocates IDs starting at 0.
337  * @name: A string that names your XArray.
338  *
339  * This is intended for file scope definitions of allocating XArrays.
340  * See also DEFINE_XARRAY().
341  */
342 #define DEFINE_XARRAY_ALLOC(name) DEFINE_XARRAY_FLAGS(name, XA_FLAGS_ALLOC)
343
344 /**
345  * DEFINE_XARRAY_ALLOC1() - Define an XArray which allocates IDs starting at 1.
346  * @name: A string that names your XArray.
347  *
348  * This is intended for file scope definitions of allocating XArrays.
349  * See also DEFINE_XARRAY().
350  */
351 #define DEFINE_XARRAY_ALLOC1(name) DEFINE_XARRAY_FLAGS(name, XA_FLAGS_ALLOC1)
352
353 void *xa_load(struct xarray *, unsigned long index);
354 void *xa_store(struct xarray *, unsigned long index, void *entry, gfp_t);
355 void *xa_erase(struct xarray *, unsigned long index);
356 void *xa_store_range(struct xarray *, unsigned long first, unsigned long last,
357                         void *entry, gfp_t);
358 bool xa_get_mark(struct xarray *, unsigned long index, xa_mark_t);
359 void xa_set_mark(struct xarray *, unsigned long index, xa_mark_t);
360 void xa_clear_mark(struct xarray *, unsigned long index, xa_mark_t);
361 void *xa_find(struct xarray *xa, unsigned long *index,
362                 unsigned long max, xa_mark_t) __attribute__((nonnull(2)));
363 void *xa_find_after(struct xarray *xa, unsigned long *index,
364                 unsigned long max, xa_mark_t) __attribute__((nonnull(2)));
365 unsigned int xa_extract(struct xarray *, void **dst, unsigned long start,
366                 unsigned long max, unsigned int n, xa_mark_t);
367 void xa_destroy(struct xarray *);
368
369 /**
370  * xa_init_flags() - Initialise an empty XArray with flags.
371  * @xa: XArray.
372  * @flags: XA_FLAG values.
373  *
374  * If you need to initialise an XArray with special flags (eg you need
375  * to take the lock from interrupt context), use this function instead
376  * of xa_init().
377  *
378  * Context: Any context.
379  */
380 static inline void xa_init_flags(struct xarray *xa, gfp_t flags)
381 {
382         spin_lock_init(&xa->xa_lock);
383         xa->xa_flags = flags;
384         xa->xa_head = NULL;
385 }
386
387 /**
388  * xa_init() - Initialise an empty XArray.
389  * @xa: XArray.
390  *
391  * An empty XArray is full of NULL entries.
392  *
393  * Context: Any context.
394  */
395 static inline void xa_init(struct xarray *xa)
396 {
397         xa_init_flags(xa, 0);
398 }
399
400 /**
401  * xa_empty() - Determine if an array has any present entries.
402  * @xa: XArray.
403  *
404  * Context: Any context.
405  * Return: %true if the array contains only NULL pointers.
406  */
407 static inline bool xa_empty(const struct xarray *xa)
408 {
409         return xa->xa_head == NULL;
410 }
411
412 /**
413  * xa_marked() - Inquire whether any entry in this array has a mark set
414  * @xa: Array
415  * @mark: Mark value
416  *
417  * Context: Any context.
418  * Return: %true if any entry has this mark set.
419  */
420 static inline bool xa_marked(const struct xarray *xa, xa_mark_t mark)
421 {
422         return xa->xa_flags & XA_FLAGS_MARK(mark);
423 }
424
425 /**
426  * xa_for_each_start() - Iterate over a portion of an XArray.
427  * @xa: XArray.
428  * @index: Index of @entry.
429  * @entry: Entry retrieved from array.
430  * @start: First index to retrieve from array.
431  *
432  * During the iteration, @entry will have the value of the entry stored
433  * in @xa at @index.  You may modify @index during the iteration if you
434  * want to skip or reprocess indices.  It is safe to modify the array
435  * during the iteration.  At the end of the iteration, @entry will be set
436  * to NULL and @index will have a value less than or equal to max.
437  *
438  * xa_for_each_start() is O(n.log(n)) while xas_for_each() is O(n).  You have
439  * to handle your own locking with xas_for_each(), and if you have to unlock
440  * after each iteration, it will also end up being O(n.log(n)).
441  * xa_for_each_start() will spin if it hits a retry entry; if you intend to
442  * see retry entries, you should use the xas_for_each() iterator instead.
443  * The xas_for_each() iterator will expand into more inline code than
444  * xa_for_each_start().
445  *
446  * Context: Any context.  Takes and releases the RCU lock.
447  */
448 #define xa_for_each_start(xa, index, entry, start)                      \
449         for (index = start,                                             \
450              entry = xa_find(xa, &index, ULONG_MAX, XA_PRESENT);        \
451              entry;                                                     \
452              entry = xa_find_after(xa, &index, ULONG_MAX, XA_PRESENT))
453
454 /**
455  * xa_for_each() - Iterate over present entries in an XArray.
456  * @xa: XArray.
457  * @index: Index of @entry.
458  * @entry: Entry retrieved from array.
459  *
460  * During the iteration, @entry will have the value of the entry stored
461  * in @xa at @index.  You may modify @index during the iteration if you want
462  * to skip or reprocess indices.  It is safe to modify the array during the
463  * iteration.  At the end of the iteration, @entry will be set to NULL and
464  * @index will have a value less than or equal to max.
465  *
466  * xa_for_each() is O(n.log(n)) while xas_for_each() is O(n).  You have
467  * to handle your own locking with xas_for_each(), and if you have to unlock
468  * after each iteration, it will also end up being O(n.log(n)).  xa_for_each()
469  * will spin if it hits a retry entry; if you intend to see retry entries,
470  * you should use the xas_for_each() iterator instead.  The xas_for_each()
471  * iterator will expand into more inline code than xa_for_each().
472  *
473  * Context: Any context.  Takes and releases the RCU lock.
474  */
475 #define xa_for_each(xa, index, entry) \
476         xa_for_each_start(xa, index, entry, 0)
477
478 /**
479  * xa_for_each_marked() - Iterate over marked entries in an XArray.
480  * @xa: XArray.
481  * @index: Index of @entry.
482  * @entry: Entry retrieved from array.
483  * @filter: Selection criterion.
484  *
485  * During the iteration, @entry will have the value of the entry stored
486  * in @xa at @index.  The iteration will skip all entries in the array
487  * which do not match @filter.  You may modify @index during the iteration
488  * if you want to skip or reprocess indices.  It is safe to modify the array
489  * during the iteration.  At the end of the iteration, @entry will be set to
490  * NULL and @index will have a value less than or equal to max.
491  *
492  * xa_for_each_marked() is O(n.log(n)) while xas_for_each_marked() is O(n).
493  * You have to handle your own locking with xas_for_each(), and if you have
494  * to unlock after each iteration, it will also end up being O(n.log(n)).
495  * xa_for_each_marked() will spin if it hits a retry entry; if you intend to
496  * see retry entries, you should use the xas_for_each_marked() iterator
497  * instead.  The xas_for_each_marked() iterator will expand into more inline
498  * code than xa_for_each_marked().
499  *
500  * Context: Any context.  Takes and releases the RCU lock.
501  */
502 #define xa_for_each_marked(xa, index, entry, filter) \
503         for (index = 0, entry = xa_find(xa, &index, ULONG_MAX, filter); \
504              entry; entry = xa_find_after(xa, &index, ULONG_MAX, filter))
505
506 #define xa_trylock(xa)          spin_trylock(&(xa)->xa_lock)
507 #define xa_lock(xa)             spin_lock(&(xa)->xa_lock)
508 #define xa_unlock(xa)           spin_unlock(&(xa)->xa_lock)
509 #define xa_lock_bh(xa)          spin_lock_bh(&(xa)->xa_lock)
510 #define xa_unlock_bh(xa)        spin_unlock_bh(&(xa)->xa_lock)
511 #define xa_lock_irq(xa)         spin_lock_irq(&(xa)->xa_lock)
512 #define xa_unlock_irq(xa)       spin_unlock_irq(&(xa)->xa_lock)
513 #define xa_lock_irqsave(xa, flags) \
514                                 spin_lock_irqsave(&(xa)->xa_lock, flags)
515 #define xa_unlock_irqrestore(xa, flags) \
516                                 spin_unlock_irqrestore(&(xa)->xa_lock, flags)
517
518 /*
519  * Versions of the normal API which require the caller to hold the
520  * xa_lock.  If the GFP flags allow it, they will drop the lock to
521  * allocate memory, then reacquire it afterwards.  These functions
522  * may also re-enable interrupts if the XArray flags indicate the
523  * locking should be interrupt safe.
524  */
525 void *__xa_erase(struct xarray *, unsigned long index);
526 void *__xa_store(struct xarray *, unsigned long index, void *entry, gfp_t);
527 void *__xa_cmpxchg(struct xarray *, unsigned long index, void *old,
528                 void *entry, gfp_t);
529 int __must_check __xa_insert(struct xarray *, unsigned long index,
530                 void *entry, gfp_t);
531 int __must_check __xa_alloc(struct xarray *, u32 *id, void *entry,
532                 struct xa_limit, gfp_t);
533 int __must_check __xa_alloc_cyclic(struct xarray *, u32 *id, void *entry,
534                 struct xa_limit, u32 *next, gfp_t);
535 void __xa_set_mark(struct xarray *, unsigned long index, xa_mark_t);
536 void __xa_clear_mark(struct xarray *, unsigned long index, xa_mark_t);
537
538 /**
539  * xa_store_bh() - Store this entry in the XArray.
540  * @xa: XArray.
541  * @index: Index into array.
542  * @entry: New entry.
543  * @gfp: Memory allocation flags.
544  *
545  * This function is like calling xa_store() except it disables softirqs
546  * while holding the array lock.
547  *
548  * Context: Any context.  Takes and releases the xa_lock while
549  * disabling softirqs.
550  * Return: The entry which used to be at this index.
551  */
552 static inline void *xa_store_bh(struct xarray *xa, unsigned long index,
553                 void *entry, gfp_t gfp)
554 {
555         void *curr;
556
557         xa_lock_bh(xa);
558         curr = __xa_store(xa, index, entry, gfp);
559         xa_unlock_bh(xa);
560
561         return curr;
562 }
563
564 /**
565  * xa_store_irq() - Store this entry in the XArray.
566  * @xa: XArray.
567  * @index: Index into array.
568  * @entry: New entry.
569  * @gfp: Memory allocation flags.
570  *
571  * This function is like calling xa_store() except it disables interrupts
572  * while holding the array lock.
573  *
574  * Context: Process context.  Takes and releases the xa_lock while
575  * disabling interrupts.
576  * Return: The entry which used to be at this index.
577  */
578 static inline void *xa_store_irq(struct xarray *xa, unsigned long index,
579                 void *entry, gfp_t gfp)
580 {
581         void *curr;
582
583         xa_lock_irq(xa);
584         curr = __xa_store(xa, index, entry, gfp);
585         xa_unlock_irq(xa);
586
587         return curr;
588 }
589
590 /**
591  * xa_erase_bh() - Erase this entry from the XArray.
592  * @xa: XArray.
593  * @index: Index of entry.
594  *
595  * After this function returns, loading from @index will return %NULL.
596  * If the index is part of a multi-index entry, all indices will be erased
597  * and none of the entries will be part of a multi-index entry.
598  *
599  * Context: Any context.  Takes and releases the xa_lock while
600  * disabling softirqs.
601  * Return: The entry which used to be at this index.
602  */
603 static inline void *xa_erase_bh(struct xarray *xa, unsigned long index)
604 {
605         void *entry;
606
607         xa_lock_bh(xa);
608         entry = __xa_erase(xa, index);
609         xa_unlock_bh(xa);
610
611         return entry;
612 }
613
614 /**
615  * xa_erase_irq() - Erase this entry from the XArray.
616  * @xa: XArray.
617  * @index: Index of entry.
618  *
619  * After this function returns, loading from @index will return %NULL.
620  * If the index is part of a multi-index entry, all indices will be erased
621  * and none of the entries will be part of a multi-index entry.
622  *
623  * Context: Process context.  Takes and releases the xa_lock while
624  * disabling interrupts.
625  * Return: The entry which used to be at this index.
626  */
627 static inline void *xa_erase_irq(struct xarray *xa, unsigned long index)
628 {
629         void *entry;
630
631         xa_lock_irq(xa);
632         entry = __xa_erase(xa, index);
633         xa_unlock_irq(xa);
634
635         return entry;
636 }
637
638 /**
639  * xa_cmpxchg() - Conditionally replace an entry in the XArray.
640  * @xa: XArray.
641  * @index: Index into array.
642  * @old: Old value to test against.
643  * @entry: New value to place in array.
644  * @gfp: Memory allocation flags.
645  *
646  * If the entry at @index is the same as @old, replace it with @entry.
647  * If the return value is equal to @old, then the exchange was successful.
648  *
649  * Context: Any context.  Takes and releases the xa_lock.  May sleep
650  * if the @gfp flags permit.
651  * Return: The old value at this index or xa_err() if an error happened.
652  */
653 static inline void *xa_cmpxchg(struct xarray *xa, unsigned long index,
654                         void *old, void *entry, gfp_t gfp)
655 {
656         void *curr;
657
658         xa_lock(xa);
659         curr = __xa_cmpxchg(xa, index, old, entry, gfp);
660         xa_unlock(xa);
661
662         return curr;
663 }
664
665 /**
666  * xa_cmpxchg_bh() - Conditionally replace an entry in the XArray.
667  * @xa: XArray.
668  * @index: Index into array.
669  * @old: Old value to test against.
670  * @entry: New value to place in array.
671  * @gfp: Memory allocation flags.
672  *
673  * This function is like calling xa_cmpxchg() except it disables softirqs
674  * while holding the array lock.
675  *
676  * Context: Any context.  Takes and releases the xa_lock while
677  * disabling softirqs.  May sleep if the @gfp flags permit.
678  * Return: The old value at this index or xa_err() if an error happened.
679  */
680 static inline void *xa_cmpxchg_bh(struct xarray *xa, unsigned long index,
681                         void *old, void *entry, gfp_t gfp)
682 {
683         void *curr;
684
685         xa_lock_bh(xa);
686         curr = __xa_cmpxchg(xa, index, old, entry, gfp);
687         xa_unlock_bh(xa);
688
689         return curr;
690 }
691
692 /**
693  * xa_cmpxchg_irq() - Conditionally replace an entry in the XArray.
694  * @xa: XArray.
695  * @index: Index into array.
696  * @old: Old value to test against.
697  * @entry: New value to place in array.
698  * @gfp: Memory allocation flags.
699  *
700  * This function is like calling xa_cmpxchg() except it disables interrupts
701  * while holding the array lock.
702  *
703  * Context: Process context.  Takes and releases the xa_lock while
704  * disabling interrupts.  May sleep if the @gfp flags permit.
705  * Return: The old value at this index or xa_err() if an error happened.
706  */
707 static inline void *xa_cmpxchg_irq(struct xarray *xa, unsigned long index,
708                         void *old, void *entry, gfp_t gfp)
709 {
710         void *curr;
711
712         xa_lock_irq(xa);
713         curr = __xa_cmpxchg(xa, index, old, entry, gfp);
714         xa_unlock_irq(xa);
715
716         return curr;
717 }
718
719 /**
720  * xa_insert() - Store this entry in the XArray unless another entry is
721  *                      already present.
722  * @xa: XArray.
723  * @index: Index into array.
724  * @entry: New entry.
725  * @gfp: Memory allocation flags.
726  *
727  * Inserting a NULL entry will store a reserved entry (like xa_reserve())
728  * if no entry is present.  Inserting will fail if a reserved entry is
729  * present, even though loading from this index will return NULL.
730  *
731  * Context: Any context.  Takes and releases the xa_lock.  May sleep if
732  * the @gfp flags permit.
733  * Return: 0 if the store succeeded.  -EBUSY if another entry was present.
734  * -ENOMEM if memory could not be allocated.
735  */
736 static inline int __must_check xa_insert(struct xarray *xa,
737                 unsigned long index, void *entry, gfp_t gfp)
738 {
739         int err;
740
741         xa_lock(xa);
742         err = __xa_insert(xa, index, entry, gfp);
743         xa_unlock(xa);
744
745         return err;
746 }
747
748 /**
749  * xa_insert_bh() - Store this entry in the XArray unless another entry is
750  *                      already present.
751  * @xa: XArray.
752  * @index: Index into array.
753  * @entry: New entry.
754  * @gfp: Memory allocation flags.
755  *
756  * Inserting a NULL entry will store a reserved entry (like xa_reserve())
757  * if no entry is present.  Inserting will fail if a reserved entry is
758  * present, even though loading from this index will return NULL.
759  *
760  * Context: Any context.  Takes and releases the xa_lock while
761  * disabling softirqs.  May sleep if the @gfp flags permit.
762  * Return: 0 if the store succeeded.  -EBUSY if another entry was present.
763  * -ENOMEM if memory could not be allocated.
764  */
765 static inline int __must_check xa_insert_bh(struct xarray *xa,
766                 unsigned long index, void *entry, gfp_t gfp)
767 {
768         int err;
769
770         xa_lock_bh(xa);
771         err = __xa_insert(xa, index, entry, gfp);
772         xa_unlock_bh(xa);
773
774         return err;
775 }
776
777 /**
778  * xa_insert_irq() - Store this entry in the XArray unless another entry is
779  *                      already present.
780  * @xa: XArray.
781  * @index: Index into array.
782  * @entry: New entry.
783  * @gfp: Memory allocation flags.
784  *
785  * Inserting a NULL entry will store a reserved entry (like xa_reserve())
786  * if no entry is present.  Inserting will fail if a reserved entry is
787  * present, even though loading from this index will return NULL.
788  *
789  * Context: Process context.  Takes and releases the xa_lock while
790  * disabling interrupts.  May sleep if the @gfp flags permit.
791  * Return: 0 if the store succeeded.  -EBUSY if another entry was present.
792  * -ENOMEM if memory could not be allocated.
793  */
794 static inline int __must_check xa_insert_irq(struct xarray *xa,
795                 unsigned long index, void *entry, gfp_t gfp)
796 {
797         int err;
798
799         xa_lock_irq(xa);
800         err = __xa_insert(xa, index, entry, gfp);
801         xa_unlock_irq(xa);
802
803         return err;
804 }
805
806 /**
807  * xa_alloc() - Find somewhere to store this entry in the XArray.
808  * @xa: XArray.
809  * @id: Pointer to ID.
810  * @entry: New entry.
811  * @limit: Range of ID to allocate.
812  * @gfp: Memory allocation flags.
813  *
814  * Finds an empty entry in @xa between @limit.min and @limit.max,
815  * stores the index into the @id pointer, then stores the entry at
816  * that index.  A concurrent lookup will not see an uninitialised @id.
817  *
818  * Context: Any context.  Takes and releases the xa_lock.  May sleep if
819  * the @gfp flags permit.
820  * Return: 0 on success, -ENOMEM if memory could not be allocated or
821  * -EBUSY if there are no free entries in @limit.
822  */
823 static inline __must_check int xa_alloc(struct xarray *xa, u32 *id,
824                 void *entry, struct xa_limit limit, gfp_t gfp)
825 {
826         int err;
827
828         xa_lock(xa);
829         err = __xa_alloc(xa, id, entry, limit, gfp);
830         xa_unlock(xa);
831
832         return err;
833 }
834
835 /**
836  * xa_alloc_bh() - Find somewhere to store this entry in the XArray.
837  * @xa: XArray.
838  * @id: Pointer to ID.
839  * @entry: New entry.
840  * @limit: Range of ID to allocate.
841  * @gfp: Memory allocation flags.
842  *
843  * Finds an empty entry in @xa between @limit.min and @limit.max,
844  * stores the index into the @id pointer, then stores the entry at
845  * that index.  A concurrent lookup will not see an uninitialised @id.
846  *
847  * Context: Any context.  Takes and releases the xa_lock while
848  * disabling softirqs.  May sleep if the @gfp flags permit.
849  * Return: 0 on success, -ENOMEM if memory could not be allocated or
850  * -EBUSY if there are no free entries in @limit.
851  */
852 static inline int __must_check xa_alloc_bh(struct xarray *xa, u32 *id,
853                 void *entry, struct xa_limit limit, gfp_t gfp)
854 {
855         int err;
856
857         xa_lock_bh(xa);
858         err = __xa_alloc(xa, id, entry, limit, gfp);
859         xa_unlock_bh(xa);
860
861         return err;
862 }
863
864 /**
865  * xa_alloc_irq() - Find somewhere to store this entry in the XArray.
866  * @xa: XArray.
867  * @id: Pointer to ID.
868  * @entry: New entry.
869  * @limit: Range of ID to allocate.
870  * @gfp: Memory allocation flags.
871  *
872  * Finds an empty entry in @xa between @limit.min and @limit.max,
873  * stores the index into the @id pointer, then stores the entry at
874  * that index.  A concurrent lookup will not see an uninitialised @id.
875  *
876  * Context: Process context.  Takes and releases the xa_lock while
877  * disabling interrupts.  May sleep if the @gfp flags permit.
878  * Return: 0 on success, -ENOMEM if memory could not be allocated or
879  * -EBUSY if there are no free entries in @limit.
880  */
881 static inline int __must_check xa_alloc_irq(struct xarray *xa, u32 *id,
882                 void *entry, struct xa_limit limit, gfp_t gfp)
883 {
884         int err;
885
886         xa_lock_irq(xa);
887         err = __xa_alloc(xa, id, entry, limit, gfp);
888         xa_unlock_irq(xa);
889
890         return err;
891 }
892
893 /**
894  * xa_alloc_cyclic() - Find somewhere to store this entry in the XArray.
895  * @xa: XArray.
896  * @id: Pointer to ID.
897  * @entry: New entry.
898  * @limit: Range of allocated ID.
899  * @next: Pointer to next ID to allocate.
900  * @gfp: Memory allocation flags.
901  *
902  * Finds an empty entry in @xa between @limit.min and @limit.max,
903  * stores the index into the @id pointer, then stores the entry at
904  * that index.  A concurrent lookup will not see an uninitialised @id.
905  * The search for an empty entry will start at @next and will wrap
906  * around if necessary.
907  *
908  * Context: Any context.  Takes and releases the xa_lock.  May sleep if
909  * the @gfp flags permit.
910  * Return: 0 if the allocation succeeded without wrapping.  1 if the
911  * allocation succeeded after wrapping, -ENOMEM if memory could not be
912  * allocated or -EBUSY if there are no free entries in @limit.
913  */
914 static inline int xa_alloc_cyclic(struct xarray *xa, u32 *id, void *entry,
915                 struct xa_limit limit, u32 *next, gfp_t gfp)
916 {
917         int err;
918
919         xa_lock(xa);
920         err = __xa_alloc_cyclic(xa, id, entry, limit, next, gfp);
921         xa_unlock(xa);
922
923         return err;
924 }
925
926 /**
927  * xa_alloc_cyclic_bh() - Find somewhere to store this entry in the XArray.
928  * @xa: XArray.
929  * @id: Pointer to ID.
930  * @entry: New entry.
931  * @limit: Range of allocated ID.
932  * @next: Pointer to next ID to allocate.
933  * @gfp: Memory allocation flags.
934  *
935  * Finds an empty entry in @xa between @limit.min and @limit.max,
936  * stores the index into the @id pointer, then stores the entry at
937  * that index.  A concurrent lookup will not see an uninitialised @id.
938  * The search for an empty entry will start at @next and will wrap
939  * around if necessary.
940  *
941  * Context: Any context.  Takes and releases the xa_lock while
942  * disabling softirqs.  May sleep if the @gfp flags permit.
943  * Return: 0 if the allocation succeeded without wrapping.  1 if the
944  * allocation succeeded after wrapping, -ENOMEM if memory could not be
945  * allocated or -EBUSY if there are no free entries in @limit.
946  */
947 static inline int xa_alloc_cyclic_bh(struct xarray *xa, u32 *id, void *entry,
948                 struct xa_limit limit, u32 *next, gfp_t gfp)
949 {
950         int err;
951
952         xa_lock_bh(xa);
953         err = __xa_alloc_cyclic(xa, id, entry, limit, next, gfp);
954         xa_unlock_bh(xa);
955
956         return err;
957 }
958
959 /**
960  * xa_alloc_cyclic_irq() - Find somewhere to store this entry in the XArray.
961  * @xa: XArray.
962  * @id: Pointer to ID.
963  * @entry: New entry.
964  * @limit: Range of allocated ID.
965  * @next: Pointer to next ID to allocate.
966  * @gfp: Memory allocation flags.
967  *
968  * Finds an empty entry in @xa between @limit.min and @limit.max,
969  * stores the index into the @id pointer, then stores the entry at
970  * that index.  A concurrent lookup will not see an uninitialised @id.
971  * The search for an empty entry will start at @next and will wrap
972  * around if necessary.
973  *
974  * Context: Process context.  Takes and releases the xa_lock while
975  * disabling interrupts.  May sleep if the @gfp flags permit.
976  * Return: 0 if the allocation succeeded without wrapping.  1 if the
977  * allocation succeeded after wrapping, -ENOMEM if memory could not be
978  * allocated or -EBUSY if there are no free entries in @limit.
979  */
980 static inline int xa_alloc_cyclic_irq(struct xarray *xa, u32 *id, void *entry,
981                 struct xa_limit limit, u32 *next, gfp_t gfp)
982 {
983         int err;
984
985         xa_lock_irq(xa);
986         err = __xa_alloc_cyclic(xa, id, entry, limit, next, gfp);
987         xa_unlock_irq(xa);
988
989         return err;
990 }
991
992 /**
993  * xa_reserve() - Reserve this index in the XArray.
994  * @xa: XArray.
995  * @index: Index into array.
996  * @gfp: Memory allocation flags.
997  *
998  * Ensures there is somewhere to store an entry at @index in the array.
999  * If there is already something stored at @index, this function does
1000  * nothing.  If there was nothing there, the entry is marked as reserved.
1001  * Loading from a reserved entry returns a %NULL pointer.
1002  *
1003  * If you do not use the entry that you have reserved, call xa_release()
1004  * or xa_erase() to free any unnecessary memory.
1005  *
1006  * Context: Any context.  Takes and releases the xa_lock.
1007  * May sleep if the @gfp flags permit.
1008  * Return: 0 if the reservation succeeded or -ENOMEM if it failed.
1009  */
1010 static inline __must_check
1011 int xa_reserve(struct xarray *xa, unsigned long index, gfp_t gfp)
1012 {
1013         return xa_err(xa_cmpxchg(xa, index, NULL, XA_ZERO_ENTRY, gfp));
1014 }
1015
1016 /**
1017  * xa_reserve_bh() - Reserve this index in the XArray.
1018  * @xa: XArray.
1019  * @index: Index into array.
1020  * @gfp: Memory allocation flags.
1021  *
1022  * A softirq-disabling version of xa_reserve().
1023  *
1024  * Context: Any context.  Takes and releases the xa_lock while
1025  * disabling softirqs.
1026  * Return: 0 if the reservation succeeded or -ENOMEM if it failed.
1027  */
1028 static inline __must_check
1029 int xa_reserve_bh(struct xarray *xa, unsigned long index, gfp_t gfp)
1030 {
1031         return xa_err(xa_cmpxchg_bh(xa, index, NULL, XA_ZERO_ENTRY, gfp));
1032 }
1033
1034 /**
1035  * xa_reserve_irq() - Reserve this index in the XArray.
1036  * @xa: XArray.
1037  * @index: Index into array.
1038  * @gfp: Memory allocation flags.
1039  *
1040  * An interrupt-disabling version of xa_reserve().
1041  *
1042  * Context: Process context.  Takes and releases the xa_lock while
1043  * disabling interrupts.
1044  * Return: 0 if the reservation succeeded or -ENOMEM if it failed.
1045  */
1046 static inline __must_check
1047 int xa_reserve_irq(struct xarray *xa, unsigned long index, gfp_t gfp)
1048 {
1049         return xa_err(xa_cmpxchg_irq(xa, index, NULL, XA_ZERO_ENTRY, gfp));
1050 }
1051
1052 /**
1053  * xa_release() - Release a reserved entry.
1054  * @xa: XArray.
1055  * @index: Index of entry.
1056  *
1057  * After calling xa_reserve(), you can call this function to release the
1058  * reservation.  If the entry at @index has been stored to, this function
1059  * will do nothing.
1060  */
1061 static inline void xa_release(struct xarray *xa, unsigned long index)
1062 {
1063         xa_cmpxchg(xa, index, XA_ZERO_ENTRY, NULL, 0);
1064 }
1065
1066 /* Everything below here is the Advanced API.  Proceed with caution. */
1067
1068 /*
1069  * The xarray is constructed out of a set of 'chunks' of pointers.  Choosing
1070  * the best chunk size requires some tradeoffs.  A power of two recommends
1071  * itself so that we can walk the tree based purely on shifts and masks.
1072  * Generally, the larger the better; as the number of slots per level of the
1073  * tree increases, the less tall the tree needs to be.  But that needs to be
1074  * balanced against the memory consumption of each node.  On a 64-bit system,
1075  * xa_node is currently 576 bytes, and we get 7 of them per 4kB page.  If we
1076  * doubled the number of slots per node, we'd get only 3 nodes per 4kB page.
1077  */
1078 #ifndef XA_CHUNK_SHIFT
1079 #define XA_CHUNK_SHIFT          (CONFIG_BASE_SMALL ? 4 : 6)
1080 #endif
1081 #define XA_CHUNK_SIZE           (1UL << XA_CHUNK_SHIFT)
1082 #define XA_CHUNK_MASK           (XA_CHUNK_SIZE - 1)
1083 #define XA_MAX_MARKS            3
1084 #define XA_MARK_LONGS           DIV_ROUND_UP(XA_CHUNK_SIZE, BITS_PER_LONG)
1085
1086 /*
1087  * @count is the count of every non-NULL element in the ->slots array
1088  * whether that is a value entry, a retry entry, a user pointer,
1089  * a sibling entry or a pointer to the next level of the tree.
1090  * @nr_values is the count of every element in ->slots which is
1091  * either a value entry or a sibling of a value entry.
1092  */
1093 struct xa_node {
1094         unsigned char   shift;          /* Bits remaining in each slot */
1095         unsigned char   offset;         /* Slot offset in parent */
1096         unsigned char   count;          /* Total entry count */
1097         unsigned char   nr_values;      /* Value entry count */
1098         struct xa_node __rcu *parent;   /* NULL at top of tree */
1099         struct xarray   *array;         /* The array we belong to */
1100         union {
1101                 struct list_head private_list;  /* For tree user */
1102                 struct rcu_head rcu_head;       /* Used when freeing node */
1103         };
1104         void __rcu      *slots[XA_CHUNK_SIZE];
1105         union {
1106                 unsigned long   tags[XA_MAX_MARKS][XA_MARK_LONGS];
1107                 unsigned long   marks[XA_MAX_MARKS][XA_MARK_LONGS];
1108         };
1109 };
1110
1111 void xa_dump(const struct xarray *);
1112 void xa_dump_node(const struct xa_node *);
1113
1114 #ifdef XA_DEBUG
1115 #define XA_BUG_ON(xa, x) do {                                   \
1116                 if (x) {                                        \
1117                         xa_dump(xa);                            \
1118                         BUG();                                  \
1119                 }                                               \
1120         } while (0)
1121 #define XA_NODE_BUG_ON(node, x) do {                            \
1122                 if (x) {                                        \
1123                         if (node) xa_dump_node(node);           \
1124                         BUG();                                  \
1125                 }                                               \
1126         } while (0)
1127 #else
1128 #define XA_BUG_ON(xa, x)        do { } while (0)
1129 #define XA_NODE_BUG_ON(node, x) do { } while (0)
1130 #endif
1131
1132 /* Private */
1133 static inline void *xa_head(const struct xarray *xa)
1134 {
1135         return rcu_dereference_check(xa->xa_head,
1136                                                 lockdep_is_held(&xa->xa_lock));
1137 }
1138
1139 /* Private */
1140 static inline void *xa_head_locked(const struct xarray *xa)
1141 {
1142         return rcu_dereference_protected(xa->xa_head,
1143                                                 lockdep_is_held(&xa->xa_lock));
1144 }
1145
1146 /* Private */
1147 static inline void *xa_entry(const struct xarray *xa,
1148                                 const struct xa_node *node, unsigned int offset)
1149 {
1150         XA_NODE_BUG_ON(node, offset >= XA_CHUNK_SIZE);
1151         return rcu_dereference_check(node->slots[offset],
1152                                                 lockdep_is_held(&xa->xa_lock));
1153 }
1154
1155 /* Private */
1156 static inline void *xa_entry_locked(const struct xarray *xa,
1157                                 const struct xa_node *node, unsigned int offset)
1158 {
1159         XA_NODE_BUG_ON(node, offset >= XA_CHUNK_SIZE);
1160         return rcu_dereference_protected(node->slots[offset],
1161                                                 lockdep_is_held(&xa->xa_lock));
1162 }
1163
1164 /* Private */
1165 static inline struct xa_node *xa_parent(const struct xarray *xa,
1166                                         const struct xa_node *node)
1167 {
1168         return rcu_dereference_check(node->parent,
1169                                                 lockdep_is_held(&xa->xa_lock));
1170 }
1171
1172 /* Private */
1173 static inline struct xa_node *xa_parent_locked(const struct xarray *xa,
1174                                         const struct xa_node *node)
1175 {
1176         return rcu_dereference_protected(node->parent,
1177                                                 lockdep_is_held(&xa->xa_lock));
1178 }
1179
1180 /* Private */
1181 static inline void *xa_mk_node(const struct xa_node *node)
1182 {
1183         return (void *)((unsigned long)node | 2);
1184 }
1185
1186 /* Private */
1187 static inline struct xa_node *xa_to_node(const void *entry)
1188 {
1189         return (struct xa_node *)((unsigned long)entry - 2);
1190 }
1191
1192 /* Private */
1193 static inline bool xa_is_node(const void *entry)
1194 {
1195         return xa_is_internal(entry) && (unsigned long)entry > 4096;
1196 }
1197
1198 /* Private */
1199 static inline void *xa_mk_sibling(unsigned int offset)
1200 {
1201         return xa_mk_internal(offset);
1202 }
1203
1204 /* Private */
1205 static inline unsigned long xa_to_sibling(const void *entry)
1206 {
1207         return xa_to_internal(entry);
1208 }
1209
1210 /**
1211  * xa_is_sibling() - Is the entry a sibling entry?
1212  * @entry: Entry retrieved from the XArray
1213  *
1214  * Return: %true if the entry is a sibling entry.
1215  */
1216 static inline bool xa_is_sibling(const void *entry)
1217 {
1218         return IS_ENABLED(CONFIG_XARRAY_MULTI) && xa_is_internal(entry) &&
1219                 (entry < xa_mk_sibling(XA_CHUNK_SIZE - 1));
1220 }
1221
1222 #define XA_RETRY_ENTRY          xa_mk_internal(256)
1223
1224 /**
1225  * xa_is_retry() - Is the entry a retry entry?
1226  * @entry: Entry retrieved from the XArray
1227  *
1228  * Return: %true if the entry is a retry entry.
1229  */
1230 static inline bool xa_is_retry(const void *entry)
1231 {
1232         return unlikely(entry == XA_RETRY_ENTRY);
1233 }
1234
1235 /**
1236  * xa_is_advanced() - Is the entry only permitted for the advanced API?
1237  * @entry: Entry to be stored in the XArray.
1238  *
1239  * Return: %true if the entry cannot be stored by the normal API.
1240  */
1241 static inline bool xa_is_advanced(const void *entry)
1242 {
1243         return xa_is_internal(entry) && (entry <= XA_RETRY_ENTRY);
1244 }
1245
1246 /**
1247  * typedef xa_update_node_t - A callback function from the XArray.
1248  * @node: The node which is being processed
1249  *
1250  * This function is called every time the XArray updates the count of
1251  * present and value entries in a node.  It allows advanced users to
1252  * maintain the private_list in the node.
1253  *
1254  * Context: The xa_lock is held and interrupts may be disabled.
1255  *          Implementations should not drop the xa_lock, nor re-enable
1256  *          interrupts.
1257  */
1258 typedef void (*xa_update_node_t)(struct xa_node *node);
1259
1260 /*
1261  * The xa_state is opaque to its users.  It contains various different pieces
1262  * of state involved in the current operation on the XArray.  It should be
1263  * declared on the stack and passed between the various internal routines.
1264  * The various elements in it should not be accessed directly, but only
1265  * through the provided accessor functions.  The below documentation is for
1266  * the benefit of those working on the code, not for users of the XArray.
1267  *
1268  * @xa_node usually points to the xa_node containing the slot we're operating
1269  * on (and @xa_offset is the offset in the slots array).  If there is a
1270  * single entry in the array at index 0, there are no allocated xa_nodes to
1271  * point to, and so we store %NULL in @xa_node.  @xa_node is set to
1272  * the value %XAS_RESTART if the xa_state is not walked to the correct
1273  * position in the tree of nodes for this operation.  If an error occurs
1274  * during an operation, it is set to an %XAS_ERROR value.  If we run off the
1275  * end of the allocated nodes, it is set to %XAS_BOUNDS.
1276  */
1277 struct xa_state {
1278         struct xarray *xa;
1279         unsigned long xa_index;
1280         unsigned char xa_shift;
1281         unsigned char xa_sibs;
1282         unsigned char xa_offset;
1283         unsigned char xa_pad;           /* Helps gcc generate better code */
1284         struct xa_node *xa_node;
1285         struct xa_node *xa_alloc;
1286         xa_update_node_t xa_update;
1287 };
1288
1289 /*
1290  * We encode errnos in the xas->xa_node.  If an error has happened, we need to
1291  * drop the lock to fix it, and once we've done so the xa_state is invalid.
1292  */
1293 #define XA_ERROR(errno) ((struct xa_node *)(((unsigned long)errno << 2) | 2UL))
1294 #define XAS_BOUNDS      ((struct xa_node *)1UL)
1295 #define XAS_RESTART     ((struct xa_node *)3UL)
1296
1297 #define __XA_STATE(array, index, shift, sibs)  {        \
1298         .xa = array,                                    \
1299         .xa_index = index,                              \
1300         .xa_shift = shift,                              \
1301         .xa_sibs = sibs,                                \
1302         .xa_offset = 0,                                 \
1303         .xa_pad = 0,                                    \
1304         .xa_node = XAS_RESTART,                         \
1305         .xa_alloc = NULL,                               \
1306         .xa_update = NULL                               \
1307 }
1308
1309 /**
1310  * XA_STATE() - Declare an XArray operation state.
1311  * @name: Name of this operation state (usually xas).
1312  * @array: Array to operate on.
1313  * @index: Initial index of interest.
1314  *
1315  * Declare and initialise an xa_state on the stack.
1316  */
1317 #define XA_STATE(name, array, index)                            \
1318         struct xa_state name = __XA_STATE(array, index, 0, 0)
1319
1320 /**
1321  * XA_STATE_ORDER() - Declare an XArray operation state.
1322  * @name: Name of this operation state (usually xas).
1323  * @array: Array to operate on.
1324  * @index: Initial index of interest.
1325  * @order: Order of entry.
1326  *
1327  * Declare and initialise an xa_state on the stack.  This variant of
1328  * XA_STATE() allows you to specify the 'order' of the element you
1329  * want to operate on.`
1330  */
1331 #define XA_STATE_ORDER(name, array, index, order)               \
1332         struct xa_state name = __XA_STATE(array,                \
1333                         (index >> order) << order,              \
1334                         order - (order % XA_CHUNK_SHIFT),       \
1335                         (1U << (order % XA_CHUNK_SHIFT)) - 1)
1336
1337 #define xas_marked(xas, mark)   xa_marked((xas)->xa, (mark))
1338 #define xas_trylock(xas)        xa_trylock((xas)->xa)
1339 #define xas_lock(xas)           xa_lock((xas)->xa)
1340 #define xas_unlock(xas)         xa_unlock((xas)->xa)
1341 #define xas_lock_bh(xas)        xa_lock_bh((xas)->xa)
1342 #define xas_unlock_bh(xas)      xa_unlock_bh((xas)->xa)
1343 #define xas_lock_irq(xas)       xa_lock_irq((xas)->xa)
1344 #define xas_unlock_irq(xas)     xa_unlock_irq((xas)->xa)
1345 #define xas_lock_irqsave(xas, flags) \
1346                                 xa_lock_irqsave((xas)->xa, flags)
1347 #define xas_unlock_irqrestore(xas, flags) \
1348                                 xa_unlock_irqrestore((xas)->xa, flags)
1349
1350 /**
1351  * xas_error() - Return an errno stored in the xa_state.
1352  * @xas: XArray operation state.
1353  *
1354  * Return: 0 if no error has been noted.  A negative errno if one has.
1355  */
1356 static inline int xas_error(const struct xa_state *xas)
1357 {
1358         return xa_err(xas->xa_node);
1359 }
1360
1361 /**
1362  * xas_set_err() - Note an error in the xa_state.
1363  * @xas: XArray operation state.
1364  * @err: Negative error number.
1365  *
1366  * Only call this function with a negative @err; zero or positive errors
1367  * will probably not behave the way you think they should.  If you want
1368  * to clear the error from an xa_state, use xas_reset().
1369  */
1370 static inline void xas_set_err(struct xa_state *xas, long err)
1371 {
1372         xas->xa_node = XA_ERROR(err);
1373 }
1374
1375 /**
1376  * xas_invalid() - Is the xas in a retry or error state?
1377  * @xas: XArray operation state.
1378  *
1379  * Return: %true if the xas cannot be used for operations.
1380  */
1381 static inline bool xas_invalid(const struct xa_state *xas)
1382 {
1383         return (unsigned long)xas->xa_node & 3;
1384 }
1385
1386 /**
1387  * xas_valid() - Is the xas a valid cursor into the array?
1388  * @xas: XArray operation state.
1389  *
1390  * Return: %true if the xas can be used for operations.
1391  */
1392 static inline bool xas_valid(const struct xa_state *xas)
1393 {
1394         return !xas_invalid(xas);
1395 }
1396
1397 /**
1398  * xas_is_node() - Does the xas point to a node?
1399  * @xas: XArray operation state.
1400  *
1401  * Return: %true if the xas currently references a node.
1402  */
1403 static inline bool xas_is_node(const struct xa_state *xas)
1404 {
1405         return xas_valid(xas) && xas->xa_node;
1406 }
1407
1408 /* True if the pointer is something other than a node */
1409 static inline bool xas_not_node(struct xa_node *node)
1410 {
1411         return ((unsigned long)node & 3) || !node;
1412 }
1413
1414 /* True if the node represents RESTART or an error */
1415 static inline bool xas_frozen(struct xa_node *node)
1416 {
1417         return (unsigned long)node & 2;
1418 }
1419
1420 /* True if the node represents head-of-tree, RESTART or BOUNDS */
1421 static inline bool xas_top(struct xa_node *node)
1422 {
1423         return node <= XAS_RESTART;
1424 }
1425
1426 /**
1427  * xas_reset() - Reset an XArray operation state.
1428  * @xas: XArray operation state.
1429  *
1430  * Resets the error or walk state of the @xas so future walks of the
1431  * array will start from the root.  Use this if you have dropped the
1432  * xarray lock and want to reuse the xa_state.
1433  *
1434  * Context: Any context.
1435  */
1436 static inline void xas_reset(struct xa_state *xas)
1437 {
1438         xas->xa_node = XAS_RESTART;
1439 }
1440
1441 /**
1442  * xas_retry() - Retry the operation if appropriate.
1443  * @xas: XArray operation state.
1444  * @entry: Entry from xarray.
1445  *
1446  * The advanced functions may sometimes return an internal entry, such as
1447  * a retry entry or a zero entry.  This function sets up the @xas to restart
1448  * the walk from the head of the array if needed.
1449  *
1450  * Context: Any context.
1451  * Return: true if the operation needs to be retried.
1452  */
1453 static inline bool xas_retry(struct xa_state *xas, const void *entry)
1454 {
1455         if (xa_is_zero(entry))
1456                 return true;
1457         if (!xa_is_retry(entry))
1458                 return false;
1459         xas_reset(xas);
1460         return true;
1461 }
1462
1463 void *xas_load(struct xa_state *);
1464 void *xas_store(struct xa_state *, void *entry);
1465 void *xas_find(struct xa_state *, unsigned long max);
1466 void *xas_find_conflict(struct xa_state *);
1467
1468 bool xas_get_mark(const struct xa_state *, xa_mark_t);
1469 void xas_set_mark(const struct xa_state *, xa_mark_t);
1470 void xas_clear_mark(const struct xa_state *, xa_mark_t);
1471 void *xas_find_marked(struct xa_state *, unsigned long max, xa_mark_t);
1472 void xas_init_marks(const struct xa_state *);
1473
1474 bool xas_nomem(struct xa_state *, gfp_t);
1475 void xas_pause(struct xa_state *);
1476
1477 void xas_create_range(struct xa_state *);
1478
1479 /**
1480  * xas_reload() - Refetch an entry from the xarray.
1481  * @xas: XArray operation state.
1482  *
1483  * Use this function to check that a previously loaded entry still has
1484  * the same value.  This is useful for the lockless pagecache lookup where
1485  * we walk the array with only the RCU lock to protect us, lock the page,
1486  * then check that the page hasn't moved since we looked it up.
1487  *
1488  * The caller guarantees that @xas is still valid.  If it may be in an
1489  * error or restart state, call xas_load() instead.
1490  *
1491  * Return: The entry at this location in the xarray.
1492  */
1493 static inline void *xas_reload(struct xa_state *xas)
1494 {
1495         struct xa_node *node = xas->xa_node;
1496
1497         if (node)
1498                 return xa_entry(xas->xa, node, xas->xa_offset);
1499         return xa_head(xas->xa);
1500 }
1501
1502 /**
1503  * xas_set() - Set up XArray operation state for a different index.
1504  * @xas: XArray operation state.
1505  * @index: New index into the XArray.
1506  *
1507  * Move the operation state to refer to a different index.  This will
1508  * have the effect of starting a walk from the top; see xas_next()
1509  * to move to an adjacent index.
1510  */
1511 static inline void xas_set(struct xa_state *xas, unsigned long index)
1512 {
1513         xas->xa_index = index;
1514         xas->xa_node = XAS_RESTART;
1515 }
1516
1517 /**
1518  * xas_set_order() - Set up XArray operation state for a multislot entry.
1519  * @xas: XArray operation state.
1520  * @index: Target of the operation.
1521  * @order: Entry occupies 2^@order indices.
1522  */
1523 static inline void xas_set_order(struct xa_state *xas, unsigned long index,
1524                                         unsigned int order)
1525 {
1526 #ifdef CONFIG_XARRAY_MULTI
1527         xas->xa_index = order < BITS_PER_LONG ? (index >> order) << order : 0;
1528         xas->xa_shift = order - (order % XA_CHUNK_SHIFT);
1529         xas->xa_sibs = (1 << (order % XA_CHUNK_SHIFT)) - 1;
1530         xas->xa_node = XAS_RESTART;
1531 #else
1532         BUG_ON(order > 0);
1533         xas_set(xas, index);
1534 #endif
1535 }
1536
1537 /**
1538  * xas_set_update() - Set up XArray operation state for a callback.
1539  * @xas: XArray operation state.
1540  * @update: Function to call when updating a node.
1541  *
1542  * The XArray can notify a caller after it has updated an xa_node.
1543  * This is advanced functionality and is only needed by the page cache.
1544  */
1545 static inline void xas_set_update(struct xa_state *xas, xa_update_node_t update)
1546 {
1547         xas->xa_update = update;
1548 }
1549
1550 /**
1551  * xas_next_entry() - Advance iterator to next present entry.
1552  * @xas: XArray operation state.
1553  * @max: Highest index to return.
1554  *
1555  * xas_next_entry() is an inline function to optimise xarray traversal for
1556  * speed.  It is equivalent to calling xas_find(), and will call xas_find()
1557  * for all the hard cases.
1558  *
1559  * Return: The next present entry after the one currently referred to by @xas.
1560  */
1561 static inline void *xas_next_entry(struct xa_state *xas, unsigned long max)
1562 {
1563         struct xa_node *node = xas->xa_node;
1564         void *entry;
1565
1566         if (unlikely(xas_not_node(node) || node->shift ||
1567                         xas->xa_offset != (xas->xa_index & XA_CHUNK_MASK)))
1568                 return xas_find(xas, max);
1569
1570         do {
1571                 if (unlikely(xas->xa_index >= max))
1572                         return xas_find(xas, max);
1573                 if (unlikely(xas->xa_offset == XA_CHUNK_MASK))
1574                         return xas_find(xas, max);
1575                 entry = xa_entry(xas->xa, node, xas->xa_offset + 1);
1576                 if (unlikely(xa_is_internal(entry)))
1577                         return xas_find(xas, max);
1578                 xas->xa_offset++;
1579                 xas->xa_index++;
1580         } while (!entry);
1581
1582         return entry;
1583 }
1584
1585 /* Private */
1586 static inline unsigned int xas_find_chunk(struct xa_state *xas, bool advance,
1587                 xa_mark_t mark)
1588 {
1589         unsigned long *addr = xas->xa_node->marks[(__force unsigned)mark];
1590         unsigned int offset = xas->xa_offset;
1591
1592         if (advance)
1593                 offset++;
1594         if (XA_CHUNK_SIZE == BITS_PER_LONG) {
1595                 if (offset < XA_CHUNK_SIZE) {
1596                         unsigned long data = *addr & (~0UL << offset);
1597                         if (data)
1598                                 return __ffs(data);
1599                 }
1600                 return XA_CHUNK_SIZE;
1601         }
1602
1603         return find_next_bit(addr, XA_CHUNK_SIZE, offset);
1604 }
1605
1606 /**
1607  * xas_next_marked() - Advance iterator to next marked entry.
1608  * @xas: XArray operation state.
1609  * @max: Highest index to return.
1610  * @mark: Mark to search for.
1611  *
1612  * xas_next_marked() is an inline function to optimise xarray traversal for
1613  * speed.  It is equivalent to calling xas_find_marked(), and will call
1614  * xas_find_marked() for all the hard cases.
1615  *
1616  * Return: The next marked entry after the one currently referred to by @xas.
1617  */
1618 static inline void *xas_next_marked(struct xa_state *xas, unsigned long max,
1619                                                                 xa_mark_t mark)
1620 {
1621         struct xa_node *node = xas->xa_node;
1622         unsigned int offset;
1623
1624         if (unlikely(xas_not_node(node) || node->shift))
1625                 return xas_find_marked(xas, max, mark);
1626         offset = xas_find_chunk(xas, true, mark);
1627         xas->xa_offset = offset;
1628         xas->xa_index = (xas->xa_index & ~XA_CHUNK_MASK) + offset;
1629         if (xas->xa_index > max)
1630                 return NULL;
1631         if (offset == XA_CHUNK_SIZE)
1632                 return xas_find_marked(xas, max, mark);
1633         return xa_entry(xas->xa, node, offset);
1634 }
1635
1636 /*
1637  * If iterating while holding a lock, drop the lock and reschedule
1638  * every %XA_CHECK_SCHED loops.
1639  */
1640 enum {
1641         XA_CHECK_SCHED = 4096,
1642 };
1643
1644 /**
1645  * xas_for_each() - Iterate over a range of an XArray.
1646  * @xas: XArray operation state.
1647  * @entry: Entry retrieved from the array.
1648  * @max: Maximum index to retrieve from array.
1649  *
1650  * The loop body will be executed for each entry present in the xarray
1651  * between the current xas position and @max.  @entry will be set to
1652  * the entry retrieved from the xarray.  It is safe to delete entries
1653  * from the array in the loop body.  You should hold either the RCU lock
1654  * or the xa_lock while iterating.  If you need to drop the lock, call
1655  * xas_pause() first.
1656  */
1657 #define xas_for_each(xas, entry, max) \
1658         for (entry = xas_find(xas, max); entry; \
1659              entry = xas_next_entry(xas, max))
1660
1661 /**
1662  * xas_for_each_marked() - Iterate over a range of an XArray.
1663  * @xas: XArray operation state.
1664  * @entry: Entry retrieved from the array.
1665  * @max: Maximum index to retrieve from array.
1666  * @mark: Mark to search for.
1667  *
1668  * The loop body will be executed for each marked entry in the xarray
1669  * between the current xas position and @max.  @entry will be set to
1670  * the entry retrieved from the xarray.  It is safe to delete entries
1671  * from the array in the loop body.  You should hold either the RCU lock
1672  * or the xa_lock while iterating.  If you need to drop the lock, call
1673  * xas_pause() first.
1674  */
1675 #define xas_for_each_marked(xas, entry, max, mark) \
1676         for (entry = xas_find_marked(xas, max, mark); entry; \
1677              entry = xas_next_marked(xas, max, mark))
1678
1679 /**
1680  * xas_for_each_conflict() - Iterate over a range of an XArray.
1681  * @xas: XArray operation state.
1682  * @entry: Entry retrieved from the array.
1683  *
1684  * The loop body will be executed for each entry in the XArray that lies
1685  * within the range specified by @xas.  If the loop completes successfully,
1686  * any entries that lie in this range will be replaced by @entry.  The caller
1687  * may break out of the loop; if they do so, the contents of the XArray will
1688  * be unchanged.  The operation may fail due to an out of memory condition.
1689  * The caller may also call xa_set_err() to exit the loop while setting an
1690  * error to record the reason.
1691  */
1692 #define xas_for_each_conflict(xas, entry) \
1693         while ((entry = xas_find_conflict(xas)))
1694
1695 void *__xas_next(struct xa_state *);
1696 void *__xas_prev(struct xa_state *);
1697
1698 /**
1699  * xas_prev() - Move iterator to previous index.
1700  * @xas: XArray operation state.
1701  *
1702  * If the @xas was in an error state, it will remain in an error state
1703  * and this function will return %NULL.  If the @xas has never been walked,
1704  * it will have the effect of calling xas_load().  Otherwise one will be
1705  * subtracted from the index and the state will be walked to the correct
1706  * location in the array for the next operation.
1707  *
1708  * If the iterator was referencing index 0, this function wraps
1709  * around to %ULONG_MAX.
1710  *
1711  * Return: The entry at the new index.  This may be %NULL or an internal
1712  * entry.
1713  */
1714 static inline void *xas_prev(struct xa_state *xas)
1715 {
1716         struct xa_node *node = xas->xa_node;
1717
1718         if (unlikely(xas_not_node(node) || node->shift ||
1719                                 xas->xa_offset == 0))
1720                 return __xas_prev(xas);
1721
1722         xas->xa_index--;
1723         xas->xa_offset--;
1724         return xa_entry(xas->xa, node, xas->xa_offset);
1725 }
1726
1727 /**
1728  * xas_next() - Move state to next index.
1729  * @xas: XArray operation state.
1730  *
1731  * If the @xas was in an error state, it will remain in an error state
1732  * and this function will return %NULL.  If the @xas has never been walked,
1733  * it will have the effect of calling xas_load().  Otherwise one will be
1734  * added to the index and the state will be walked to the correct
1735  * location in the array for the next operation.
1736  *
1737  * If the iterator was referencing index %ULONG_MAX, this function wraps
1738  * around to 0.
1739  *
1740  * Return: The entry at the new index.  This may be %NULL or an internal
1741  * entry.
1742  */
1743 static inline void *xas_next(struct xa_state *xas)
1744 {
1745         struct xa_node *node = xas->xa_node;
1746
1747         if (unlikely(xas_not_node(node) || node->shift ||
1748                                 xas->xa_offset == XA_CHUNK_MASK))
1749                 return __xas_next(xas);
1750
1751         xas->xa_index++;
1752         xas->xa_offset++;
1753         return xa_entry(xas->xa, node, xas->xa_offset);
1754 }
1755 #endif /* HAVE_RADIX_TREE_EXCEPTIONAL_ENTRY */
1756
1757 #endif /* _LINUX_XARRAY_H */