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