radix-tree.c 43.1 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3
/*
 * Copyright (C) 2001 Momchil Velikov
 * Portions Copyright (C) 2001 Christoph Hellwig
C
Christoph Lameter 已提交
4
 * Copyright (C) 2005 SGI, Christoph Lameter
5
 * Copyright (C) 2006 Nick Piggin
6
 * Copyright (C) 2012 Konstantin Khlebnikov
7 8
 * Copyright (C) 2016 Intel, Matthew Wilcox
 * Copyright (C) 2016 Intel, Ross Zwisler
L
Linus Torvalds 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
28
#include <linux/export.h>
L
Linus Torvalds 已提交
29 30 31
#include <linux/radix-tree.h>
#include <linux/percpu.h>
#include <linux/slab.h>
32
#include <linux/kmemleak.h>
L
Linus Torvalds 已提交
33 34 35 36
#include <linux/notifier.h>
#include <linux/cpu.h>
#include <linux/string.h>
#include <linux/bitops.h>
37
#include <linux/rcupdate.h>
38
#include <linux/preempt.h>		/* in_interrupt() */
L
Linus Torvalds 已提交
39 40 41 42 43


/*
 * Radix tree node cache.
 */
44
static struct kmem_cache *radix_tree_node_cachep;
L
Linus Torvalds 已提交
45

46 47 48 49 50 51 52 53 54 55 56 57 58
/*
 * The radix tree is variable-height, so an insert operation not only has
 * to build the branch to its corresponding item, it also has to build the
 * branch to existing items if the size has to be increased (by
 * radix_tree_extend).
 *
 * The worst case is a zero height tree with just a single item at index 0,
 * and then inserting an item at index ULONG_MAX. This requires 2 new branches
 * of RADIX_TREE_MAX_PATH size to be created, with only the root node shared.
 * Hence:
 */
#define RADIX_TREE_PRELOAD_SIZE (RADIX_TREE_MAX_PATH * 2 - 1)

L
Linus Torvalds 已提交
59 60 61 62
/*
 * Per-cpu pool of preloaded nodes
 */
struct radix_tree_preload {
M
Matthew Wilcox 已提交
63
	unsigned nr;
64 65
	/* nodes->private_data points to next preallocated node */
	struct radix_tree_node *nodes;
L
Linus Torvalds 已提交
66
};
67
static DEFINE_PER_CPU(struct radix_tree_preload, radix_tree_preloads) = { 0, };
L
Linus Torvalds 已提交
68

69
static inline void *node_to_entry(void *ptr)
N
Nick Piggin 已提交
70
{
71
	return (void *)((unsigned long)ptr | RADIX_TREE_INTERNAL_NODE);
N
Nick Piggin 已提交
72 73
}

74
#define RADIX_TREE_RETRY	node_to_entry(NULL)
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
#ifdef CONFIG_RADIX_TREE_MULTIORDER
/* Sibling slots point directly to another slot in the same node */
static inline bool is_sibling_entry(struct radix_tree_node *parent, void *node)
{
	void **ptr = node;
	return (parent->slots <= ptr) &&
			(ptr < parent->slots + RADIX_TREE_MAP_SIZE);
}
#else
static inline bool is_sibling_entry(struct radix_tree_node *parent, void *node)
{
	return false;
}
#endif

static inline unsigned long get_slot_offset(struct radix_tree_node *parent,
						 void **slot)
{
	return slot - parent->slots;
}

static unsigned radix_tree_descend(struct radix_tree_node *parent,
				struct radix_tree_node **nodep, unsigned offset)
{
	void **entry = rcu_dereference_raw(parent->slots[offset]);

#ifdef CONFIG_RADIX_TREE_MULTIORDER
103
	if (radix_tree_is_internal_node(entry)) {
104 105 106 107 108 109 110 111 112 113 114 115
		unsigned long siboff = get_slot_offset(parent, entry);
		if (siboff < RADIX_TREE_MAP_SIZE) {
			offset = siboff;
			entry = rcu_dereference_raw(parent->slots[offset]);
		}
	}
#endif

	*nodep = (void *)entry;
	return offset;
}

N
Nick Piggin 已提交
116 117 118 119 120
static inline gfp_t root_gfp_mask(struct radix_tree_root *root)
{
	return root->gfp_mask & __GFP_BITS_MASK;
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
static inline void tag_set(struct radix_tree_node *node, unsigned int tag,
		int offset)
{
	__set_bit(offset, node->tags[tag]);
}

static inline void tag_clear(struct radix_tree_node *node, unsigned int tag,
		int offset)
{
	__clear_bit(offset, node->tags[tag]);
}

static inline int tag_get(struct radix_tree_node *node, unsigned int tag,
		int offset)
{
	return test_bit(offset, node->tags[tag]);
}

static inline void root_tag_set(struct radix_tree_root *root, unsigned int tag)
{
	root->gfp_mask |= (__force gfp_t)(1 << (tag + __GFP_BITS_SHIFT));
}

M
Matthew Wilcox 已提交
144
static inline void root_tag_clear(struct radix_tree_root *root, unsigned tag)
145 146 147 148 149 150 151 152 153 154 155
{
	root->gfp_mask &= (__force gfp_t)~(1 << (tag + __GFP_BITS_SHIFT));
}

static inline void root_tag_clear_all(struct radix_tree_root *root)
{
	root->gfp_mask &= __GFP_BITS_MASK;
}

static inline int root_tag_get(struct radix_tree_root *root, unsigned int tag)
{
M
Matthew Wilcox 已提交
156
	return (__force int)root->gfp_mask & (1 << (tag + __GFP_BITS_SHIFT));
157 158
}

159 160 161 162 163
static inline unsigned root_tags_get(struct radix_tree_root *root)
{
	return (__force unsigned)root->gfp_mask >> __GFP_BITS_SHIFT;
}

164 165 166 167 168 169
/*
 * Returns 1 if any slot in the node has this tag set.
 * Otherwise returns 0.
 */
static inline int any_tag_set(struct radix_tree_node *node, unsigned int tag)
{
M
Matthew Wilcox 已提交
170
	unsigned idx;
171 172 173 174 175 176
	for (idx = 0; idx < RADIX_TREE_TAG_LONGS; idx++) {
		if (node->tags[tag][idx])
			return 1;
	}
	return 0;
}
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

/**
 * radix_tree_find_next_bit - find the next set bit in a memory region
 *
 * @addr: The address to base the search on
 * @size: The bitmap size in bits
 * @offset: The bitnumber to start searching at
 *
 * Unrollable variant of find_next_bit() for constant size arrays.
 * Tail bits starting from size to roundup(size, BITS_PER_LONG) must be zero.
 * Returns next bit offset, or size if nothing found.
 */
static __always_inline unsigned long
radix_tree_find_next_bit(const unsigned long *addr,
			 unsigned long size, unsigned long offset)
{
	if (!__builtin_constant_p(size))
		return find_next_bit(addr, size, offset);

	if (offset < size) {
		unsigned long tmp;

		addr += offset / BITS_PER_LONG;
		tmp = *addr >> (offset % BITS_PER_LONG);
		if (tmp)
			return __ffs(tmp) + offset;
		offset = (offset + BITS_PER_LONG) & ~(BITS_PER_LONG - 1);
		while (offset < size) {
			tmp = *++addr;
			if (tmp)
				return __ffs(tmp) + offset;
			offset += BITS_PER_LONG;
		}
	}
	return size;
}

214
#ifndef __KERNEL__
M
Matthew Wilcox 已提交
215
static void dump_node(struct radix_tree_node *node, unsigned long index)
M
Matthew Wilcox 已提交
216
{
217
	unsigned long i;
M
Matthew Wilcox 已提交
218

219
	pr_debug("radix node: %p offset %d tags %lx %lx %lx shift %d count %d parent %p\n",
220
		node, node->offset,
221
		node->tags[0][0], node->tags[1][0], node->tags[2][0],
222
		node->shift, node->count, node->parent);
223 224

	for (i = 0; i < RADIX_TREE_MAP_SIZE; i++) {
M
Matthew Wilcox 已提交
225 226
		unsigned long first = index | (i << node->shift);
		unsigned long last = first | ((1UL << node->shift) - 1);
227 228 229 230 231 232
		void *entry = node->slots[i];
		if (!entry)
			continue;
		if (is_sibling_entry(node, entry)) {
			pr_debug("radix sblng %p offset %ld val %p indices %ld-%ld\n",
					entry, i,
233
					*(void **)entry_to_node(entry),
234
					first, last);
235
		} else if (!radix_tree_is_internal_node(entry)) {
236 237 238
			pr_debug("radix entry %p offset %ld indices %ld-%ld\n",
					entry, i, first, last);
		} else {
239
			dump_node(entry_to_node(entry), first);
240 241
		}
	}
M
Matthew Wilcox 已提交
242 243 244 245 246
}

/* For debug */
static void radix_tree_dump(struct radix_tree_root *root)
{
M
Matthew Wilcox 已提交
247 248
	pr_debug("radix root: %p rnode %p tags %x\n",
			root, root->rnode,
M
Matthew Wilcox 已提交
249
			root->gfp_mask >> __GFP_BITS_SHIFT);
250
	if (!radix_tree_is_internal_node(root->rnode))
M
Matthew Wilcox 已提交
251
		return;
252
	dump_node(entry_to_node(root->rnode), 0);
M
Matthew Wilcox 已提交
253 254 255
}
#endif

L
Linus Torvalds 已提交
256 257 258 259 260 261 262
/*
 * This assumes that the caller has performed appropriate preallocation, and
 * that the caller has pinned this thread of control to the current CPU.
 */
static struct radix_tree_node *
radix_tree_node_alloc(struct radix_tree_root *root)
{
263
	struct radix_tree_node *ret = NULL;
N
Nick Piggin 已提交
264
	gfp_t gfp_mask = root_gfp_mask(root);
L
Linus Torvalds 已提交
265

266
	/*
M
Matthew Wilcox 已提交
267 268 269
	 * Preload code isn't irq safe and it doesn't make sense to use
	 * preloading during an interrupt anyway as all the allocations have
	 * to be atomic. So just do normal allocation when in interrupt.
270
	 */
271
	if (!gfpflags_allow_blocking(gfp_mask) && !in_interrupt()) {
L
Linus Torvalds 已提交
272 273
		struct radix_tree_preload *rtp;

274 275 276 277 278 279 280 281 282
		/*
		 * Even if the caller has preloaded, try to allocate from the
		 * cache first for the new node to get accounted.
		 */
		ret = kmem_cache_alloc(radix_tree_node_cachep,
				       gfp_mask | __GFP_ACCOUNT | __GFP_NOWARN);
		if (ret)
			goto out;

283 284 285 286 287
		/*
		 * Provided the caller has preloaded here, we will always
		 * succeed in getting a node here (and never reach
		 * kmem_cache_alloc)
		 */
288
		rtp = this_cpu_ptr(&radix_tree_preloads);
L
Linus Torvalds 已提交
289
		if (rtp->nr) {
290 291 292
			ret = rtp->nodes;
			rtp->nodes = ret->private_data;
			ret->private_data = NULL;
L
Linus Torvalds 已提交
293 294
			rtp->nr--;
		}
295 296 297 298 299
		/*
		 * Update the allocation stack trace as this is more useful
		 * for debugging.
		 */
		kmemleak_update_trace(ret);
300
		goto out;
L
Linus Torvalds 已提交
301
	}
302 303 304
	ret = kmem_cache_alloc(radix_tree_node_cachep,
			       gfp_mask | __GFP_ACCOUNT);
out:
305
	BUG_ON(radix_tree_is_internal_node(ret));
L
Linus Torvalds 已提交
306 307 308
	return ret;
}

309 310 311 312
static void radix_tree_node_rcu_free(struct rcu_head *head)
{
	struct radix_tree_node *node =
			container_of(head, struct radix_tree_node, rcu_head);
313
	int i;
314 315 316 317 318 319

	/*
	 * must only free zeroed nodes into the slab. radix_tree_shrink
	 * can leave us with a non-NULL entry in the first slot, so clear
	 * that here to make sure.
	 */
320 321 322
	for (i = 0; i < RADIX_TREE_MAX_TAGS; i++)
		tag_clear(node, i, 0);

323 324 325
	node->slots[0] = NULL;
	node->count = 0;

326 327 328
	kmem_cache_free(radix_tree_node_cachep, node);
}

L
Linus Torvalds 已提交
329 330 331
static inline void
radix_tree_node_free(struct radix_tree_node *node)
{
332
	call_rcu(&node->rcu_head, radix_tree_node_rcu_free);
L
Linus Torvalds 已提交
333 334 335 336 337 338 339
}

/*
 * Load up this CPU's radix_tree_node buffer with sufficient objects to
 * ensure that the addition of a single element in the tree cannot fail.  On
 * success, return zero, with preemption disabled.  On error, return -ENOMEM
 * with preemption not disabled.
340 341
 *
 * To make use of this facility, the radix tree must be initialised without
342
 * __GFP_DIRECT_RECLAIM being passed to INIT_RADIX_TREE().
L
Linus Torvalds 已提交
343
 */
344
static int __radix_tree_preload(gfp_t gfp_mask)
L
Linus Torvalds 已提交
345 346 347 348 349 350
{
	struct radix_tree_preload *rtp;
	struct radix_tree_node *node;
	int ret = -ENOMEM;

	preempt_disable();
351
	rtp = this_cpu_ptr(&radix_tree_preloads);
352
	while (rtp->nr < RADIX_TREE_PRELOAD_SIZE) {
L
Linus Torvalds 已提交
353
		preempt_enable();
C
Christoph Lameter 已提交
354
		node = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
L
Linus Torvalds 已提交
355 356 357
		if (node == NULL)
			goto out;
		preempt_disable();
358
		rtp = this_cpu_ptr(&radix_tree_preloads);
359 360 361 362 363
		if (rtp->nr < RADIX_TREE_PRELOAD_SIZE) {
			node->private_data = rtp->nodes;
			rtp->nodes = node;
			rtp->nr++;
		} else {
L
Linus Torvalds 已提交
364
			kmem_cache_free(radix_tree_node_cachep, node);
365
		}
L
Linus Torvalds 已提交
366 367 368 369 370
	}
	ret = 0;
out:
	return ret;
}
371 372 373 374 375 376 377 378

/*
 * Load up this CPU's radix_tree_node buffer with sufficient objects to
 * ensure that the addition of a single element in the tree cannot fail.  On
 * success, return zero, with preemption disabled.  On error, return -ENOMEM
 * with preemption not disabled.
 *
 * To make use of this facility, the radix tree must be initialised without
379
 * __GFP_DIRECT_RECLAIM being passed to INIT_RADIX_TREE().
380 381 382 383
 */
int radix_tree_preload(gfp_t gfp_mask)
{
	/* Warn on non-sensical use... */
384
	WARN_ON_ONCE(!gfpflags_allow_blocking(gfp_mask));
385 386
	return __radix_tree_preload(gfp_mask);
}
387
EXPORT_SYMBOL(radix_tree_preload);
L
Linus Torvalds 已提交
388

389 390 391 392 393 394 395
/*
 * The same as above function, except we don't guarantee preloading happens.
 * We do it, if we decide it helps. On success, return zero with preemption
 * disabled. On error, return -ENOMEM with preemption not disabled.
 */
int radix_tree_maybe_preload(gfp_t gfp_mask)
{
396
	if (gfpflags_allow_blocking(gfp_mask))
397 398 399 400 401 402 403
		return __radix_tree_preload(gfp_mask);
	/* Preloading doesn't help anything with this gfp mask, skip it */
	preempt_disable();
	return 0;
}
EXPORT_SYMBOL(radix_tree_maybe_preload);

L
Linus Torvalds 已提交
404
/*
M
Matthew Wilcox 已提交
405
 * The maximum index which can be stored in a radix tree
L
Linus Torvalds 已提交
406
 */
407 408 409 410 411
static inline unsigned long shift_maxindex(unsigned int shift)
{
	return (RADIX_TREE_MAP_SIZE << shift) - 1;
}

412 413
static inline unsigned long node_maxindex(struct radix_tree_node *node)
{
414
	return shift_maxindex(node->shift);
415 416 417 418 419 420 421 422 423
}

static unsigned radix_tree_load_root(struct radix_tree_root *root,
		struct radix_tree_node **nodep, unsigned long *maxindex)
{
	struct radix_tree_node *node = rcu_dereference_raw(root->rnode);

	*nodep = node;

424
	if (likely(radix_tree_is_internal_node(node))) {
425
		node = entry_to_node(node);
426
		*maxindex = node_maxindex(node);
427
		return node->shift + RADIX_TREE_MAP_SHIFT;
428 429 430 431 432 433
	}

	*maxindex = 0;
	return 0;
}

L
Linus Torvalds 已提交
434 435 436
/*
 *	Extend a radix tree so it can store key @index.
 */
437
static int radix_tree_extend(struct radix_tree_root *root,
M
Matthew Wilcox 已提交
438
				unsigned long index, unsigned int shift)
L
Linus Torvalds 已提交
439
{
440
	struct radix_tree_node *slot;
M
Matthew Wilcox 已提交
441
	unsigned int maxshift;
L
Linus Torvalds 已提交
442 443
	int tag;

M
Matthew Wilcox 已提交
444 445 446 447
	/* Figure out what the shift should be.  */
	maxshift = shift;
	while (index > shift_maxindex(maxshift))
		maxshift += RADIX_TREE_MAP_SHIFT;
L
Linus Torvalds 已提交
448

M
Matthew Wilcox 已提交
449 450
	slot = root->rnode;
	if (!slot)
L
Linus Torvalds 已提交
451 452 453
		goto out;

	do {
M
Matthew Wilcox 已提交
454 455 456
		struct radix_tree_node *node = radix_tree_node_alloc(root);

		if (!node)
L
Linus Torvalds 已提交
457 458 459
			return -ENOMEM;

		/* Propagate the aggregated tag info into the new root */
460
		for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
N
Nick Piggin 已提交
461
			if (root_tag_get(root, tag))
L
Linus Torvalds 已提交
462 463 464
				tag_set(node, tag, 0);
		}

M
Matthew Wilcox 已提交
465 466
		BUG_ON(shift > BITS_PER_LONG);
		node->shift = shift;
467
		node->offset = 0;
L
Linus Torvalds 已提交
468
		node->count = 1;
469
		node->parent = NULL;
470
		if (radix_tree_is_internal_node(slot))
471
			entry_to_node(slot)->parent = node;
472
		node->slots[0] = slot;
473 474
		slot = node_to_entry(node);
		rcu_assign_pointer(root->rnode, slot);
M
Matthew Wilcox 已提交
475 476
		shift += RADIX_TREE_MAP_SHIFT;
	} while (shift <= maxshift);
L
Linus Torvalds 已提交
477
out:
M
Matthew Wilcox 已提交
478
	return maxshift + RADIX_TREE_MAP_SHIFT;
L
Linus Torvalds 已提交
479 480 481
}

/**
482
 *	__radix_tree_create	-	create a slot in a radix tree
L
Linus Torvalds 已提交
483 484
 *	@root:		radix tree root
 *	@index:		index key
485
 *	@order:		index occupies 2^order aligned slots
486 487
 *	@nodep:		returns node
 *	@slotp:		returns slot
L
Linus Torvalds 已提交
488
 *
489 490 491 492 493 494 495 496
 *	Create, if necessary, and return the node and slot for an item
 *	at position @index in the radix tree @root.
 *
 *	Until there is more than one item in the tree, no nodes are
 *	allocated and @root->rnode is used as a direct slot instead of
 *	pointing to a node, in which case *@nodep will be NULL.
 *
 *	Returns -ENOMEM, or 0 for success.
L
Linus Torvalds 已提交
497
 */
498
int __radix_tree_create(struct radix_tree_root *root, unsigned long index,
499 500
			unsigned order, struct radix_tree_node **nodep,
			void ***slotp)
L
Linus Torvalds 已提交
501
{
502
	struct radix_tree_node *node = NULL, *slot;
503
	unsigned long maxindex;
504
	unsigned int shift, offset;
505 506 507
	unsigned long max = index | ((1UL << order) - 1);

	shift = radix_tree_load_root(root, &slot, &maxindex);
L
Linus Torvalds 已提交
508 509

	/* Make sure the tree is high enough.  */
510
	if (max > maxindex) {
M
Matthew Wilcox 已提交
511
		int error = radix_tree_extend(root, max, shift);
512
		if (error < 0)
L
Linus Torvalds 已提交
513
			return error;
514 515
		shift = error;
		slot = root->rnode;
M
Matthew Wilcox 已提交
516
		if (order == shift)
517
			shift += RADIX_TREE_MAP_SHIFT;
L
Linus Torvalds 已提交
518 519 520
	}

	offset = 0;			/* uninitialised var warning */
521
	while (shift > order) {
522
		shift -= RADIX_TREE_MAP_SHIFT;
523
		if (slot == NULL) {
L
Linus Torvalds 已提交
524
			/* Have to add a child node.  */
M
Matthew Wilcox 已提交
525 526
			slot = radix_tree_node_alloc(root);
			if (!slot)
L
Linus Torvalds 已提交
527
				return -ENOMEM;
528
			slot->shift = shift;
529
			slot->offset = offset;
530
			slot->parent = node;
531
			if (node) {
532
				rcu_assign_pointer(node->slots[offset],
533
							node_to_entry(slot));
L
Linus Torvalds 已提交
534
				node->count++;
535
			} else
536
				rcu_assign_pointer(root->rnode,
537
							node_to_entry(slot));
538
		} else if (!radix_tree_is_internal_node(slot))
539
			break;
L
Linus Torvalds 已提交
540 541

		/* Go a level down */
542
		node = entry_to_node(slot);
543 544
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
		offset = radix_tree_descend(node, &slot, offset);
545 546
	}

547
#ifdef CONFIG_RADIX_TREE_MULTIORDER
548
	/* Insert pointers to the canonical entry */
549 550
	if (order > shift) {
		int i, n = 1 << (order - shift);
551
		offset = offset & ~(n - 1);
552
		slot = node_to_entry(&node->slots[offset]);
553 554 555 556 557 558 559 560 561
		for (i = 0; i < n; i++) {
			if (node->slots[offset + i])
				return -EEXIST;
		}

		for (i = 1; i < n; i++) {
			rcu_assign_pointer(node->slots[offset + i], slot);
			node->count++;
		}
N
Nick Piggin 已提交
562
	}
563
#endif
L
Linus Torvalds 已提交
564

565 566 567 568 569 570 571 572
	if (nodep)
		*nodep = node;
	if (slotp)
		*slotp = node ? node->slots + offset : (void **)&root->rnode;
	return 0;
}

/**
573
 *	__radix_tree_insert    -    insert into a radix tree
574 575
 *	@root:		radix tree root
 *	@index:		index key
576
 *	@order:		key covers the 2^order indices around index
577 578 579 580
 *	@item:		item to insert
 *
 *	Insert an item into the radix tree at position @index.
 */
581 582
int __radix_tree_insert(struct radix_tree_root *root, unsigned long index,
			unsigned order, void *item)
583 584 585 586 587
{
	struct radix_tree_node *node;
	void **slot;
	int error;

588
	BUG_ON(radix_tree_is_internal_node(item));
589

590
	error = __radix_tree_create(root, index, order, &node, &slot);
591 592 593
	if (error)
		return error;
	if (*slot != NULL)
L
Linus Torvalds 已提交
594
		return -EEXIST;
595
	rcu_assign_pointer(*slot, item);
596

N
Nick Piggin 已提交
597
	if (node) {
598
		unsigned offset = get_slot_offset(node, slot);
N
Nick Piggin 已提交
599
		node->count++;
600 601 602
		BUG_ON(tag_get(node, 0, offset));
		BUG_ON(tag_get(node, 1, offset));
		BUG_ON(tag_get(node, 2, offset));
N
Nick Piggin 已提交
603
	} else {
604
		BUG_ON(root_tags_get(root));
N
Nick Piggin 已提交
605
	}
L
Linus Torvalds 已提交
606 607 608

	return 0;
}
609
EXPORT_SYMBOL(__radix_tree_insert);
L
Linus Torvalds 已提交
610

611 612 613 614 615 616 617 618 619 620 621 622 623
/**
 *	__radix_tree_lookup	-	lookup an item in a radix tree
 *	@root:		radix tree root
 *	@index:		index key
 *	@nodep:		returns node
 *	@slotp:		returns slot
 *
 *	Lookup and return the item at position @index in the radix
 *	tree @root.
 *
 *	Until there is more than one item in the tree, no nodes are
 *	allocated and @root->rnode is used as a direct slot instead of
 *	pointing to a node, in which case *@nodep will be NULL.
624
 */
625 626
void *__radix_tree_lookup(struct radix_tree_root *root, unsigned long index,
			  struct radix_tree_node **nodep, void ***slotp)
L
Linus Torvalds 已提交
627
{
628
	struct radix_tree_node *node, *parent;
629 630
	unsigned long maxindex;
	unsigned int shift;
631
	void **slot;
N
Nick Piggin 已提交
632

633 634 635 636 637
 restart:
	parent = NULL;
	slot = (void **)&root->rnode;
	shift = radix_tree_load_root(root, &node, &maxindex);
	if (index > maxindex)
L
Linus Torvalds 已提交
638 639
		return NULL;

640
	while (radix_tree_is_internal_node(node)) {
641
		unsigned offset;
L
Linus Torvalds 已提交
642

643 644
		if (node == RADIX_TREE_RETRY)
			goto restart;
645
		parent = entry_to_node(node);
L
Linus Torvalds 已提交
646
		shift -= RADIX_TREE_MAP_SHIFT;
647 648 649 650
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
		offset = radix_tree_descend(parent, &node, offset);
		slot = parent->slots + offset;
	}
L
Linus Torvalds 已提交
651

652 653 654 655 656
	if (nodep)
		*nodep = parent;
	if (slotp)
		*slotp = slot;
	return node;
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
}

/**
 *	radix_tree_lookup_slot    -    lookup a slot in a radix tree
 *	@root:		radix tree root
 *	@index:		index key
 *
 *	Returns:  the slot corresponding to the position @index in the
 *	radix tree @root. This is useful for update-if-exists operations.
 *
 *	This function can be called under rcu_read_lock iff the slot is not
 *	modified by radix_tree_replace_slot, otherwise it must be called
 *	exclusive from other writers. Any dereference of the slot must be done
 *	using radix_tree_deref_slot.
 */
void **radix_tree_lookup_slot(struct radix_tree_root *root, unsigned long index)
{
674 675 676 677 678
	void **slot;

	if (!__radix_tree_lookup(root, index, NULL, &slot))
		return NULL;
	return slot;
679 680 681 682 683 684 685 686 687
}
EXPORT_SYMBOL(radix_tree_lookup_slot);

/**
 *	radix_tree_lookup    -    perform lookup operation on a radix tree
 *	@root:		radix tree root
 *	@index:		index key
 *
 *	Lookup the item at the position @index in the radix tree @root.
688 689 690 691 692
 *
 *	This function can be called under rcu_read_lock, however the caller
 *	must manage lifetimes of leaf nodes (eg. RCU may also be used to free
 *	them safely). No RCU barriers are required to access or modify the
 *	returned item, however.
693 694 695
 */
void *radix_tree_lookup(struct radix_tree_root *root, unsigned long index)
{
696
	return __radix_tree_lookup(root, index, NULL, NULL);
L
Linus Torvalds 已提交
697 698 699 700 701 702 703
}
EXPORT_SYMBOL(radix_tree_lookup);

/**
 *	radix_tree_tag_set - set a tag on a radix tree node
 *	@root:		radix tree root
 *	@index:		index key
M
Matthew Wilcox 已提交
704
 *	@tag:		tag index
L
Linus Torvalds 已提交
705
 *
706 707
 *	Set the search tag (which must be < RADIX_TREE_MAX_TAGS)
 *	corresponding to @index in the radix tree.  From
L
Linus Torvalds 已提交
708 709
 *	the root all the way down to the leaf node.
 *
M
Matthew Wilcox 已提交
710
 *	Returns the address of the tagged item.  Setting a tag on a not-present
L
Linus Torvalds 已提交
711 712 713
 *	item is a bug.
 */
void *radix_tree_tag_set(struct radix_tree_root *root,
714
			unsigned long index, unsigned int tag)
L
Linus Torvalds 已提交
715
{
716 717 718
	struct radix_tree_node *node, *parent;
	unsigned long maxindex;
	unsigned int shift;
L
Linus Torvalds 已提交
719

720 721
	shift = radix_tree_load_root(root, &node, &maxindex);
	BUG_ON(index > maxindex);
L
Linus Torvalds 已提交
722

723
	while (radix_tree_is_internal_node(node)) {
724
		unsigned offset;
L
Linus Torvalds 已提交
725 726

		shift -= RADIX_TREE_MAP_SHIFT;
727 728
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;

729
		parent = entry_to_node(node);
730 731 732 733 734
		offset = radix_tree_descend(parent, &node, offset);
		BUG_ON(!node);

		if (!tag_get(parent, tag, offset))
			tag_set(parent, tag, offset);
L
Linus Torvalds 已提交
735 736
	}

N
Nick Piggin 已提交
737
	/* set the root's tag bit */
738
	if (!root_tag_get(root, tag))
N
Nick Piggin 已提交
739 740
		root_tag_set(root, tag);

741
	return node;
L
Linus Torvalds 已提交
742 743 744 745 746 747 748
}
EXPORT_SYMBOL(radix_tree_tag_set);

/**
 *	radix_tree_tag_clear - clear a tag on a radix tree node
 *	@root:		radix tree root
 *	@index:		index key
M
Matthew Wilcox 已提交
749
 *	@tag:		tag index
L
Linus Torvalds 已提交
750
 *
751
 *	Clear the search tag (which must be < RADIX_TREE_MAX_TAGS)
M
Matthew Wilcox 已提交
752 753
 *	corresponding to @index in the radix tree.  If this causes
 *	the leaf node to have no tags set then clear the tag in the
L
Linus Torvalds 已提交
754 755 756 757 758 759
 *	next-to-leaf node, etc.
 *
 *	Returns the address of the tagged item on success, else NULL.  ie:
 *	has the same return value and semantics as radix_tree_lookup().
 */
void *radix_tree_tag_clear(struct radix_tree_root *root,
760
			unsigned long index, unsigned int tag)
L
Linus Torvalds 已提交
761
{
762 763 764
	struct radix_tree_node *node, *parent;
	unsigned long maxindex;
	unsigned int shift;
765
	int uninitialized_var(offset);
L
Linus Torvalds 已提交
766

767 768 769
	shift = radix_tree_load_root(root, &node, &maxindex);
	if (index > maxindex)
		return NULL;
L
Linus Torvalds 已提交
770

771
	parent = NULL;
L
Linus Torvalds 已提交
772

773
	while (radix_tree_is_internal_node(node)) {
774
		shift -= RADIX_TREE_MAP_SHIFT;
L
Linus Torvalds 已提交
775
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
776

777
		parent = entry_to_node(node);
778
		offset = radix_tree_descend(parent, &node, offset);
L
Linus Torvalds 已提交
779 780
	}

781
	if (node == NULL)
L
Linus Torvalds 已提交
782 783
		goto out;

784 785 786 787
	index >>= shift;

	while (parent) {
		if (!tag_get(parent, tag, offset))
788
			goto out;
789 790
		tag_clear(parent, tag, offset);
		if (any_tag_set(parent, tag))
791
			goto out;
792 793 794

		index >>= RADIX_TREE_MAP_SHIFT;
		offset = index & RADIX_TREE_MAP_MASK;
795
		parent = parent->parent;
N
Nick Piggin 已提交
796 797 798 799 800 801
	}

	/* clear the root's tag bit */
	if (root_tag_get(root, tag))
		root_tag_clear(root, tag);

L
Linus Torvalds 已提交
802
out:
803
	return node;
L
Linus Torvalds 已提交
804 805 806 807
}
EXPORT_SYMBOL(radix_tree_tag_clear);

/**
808 809 810
 * radix_tree_tag_get - get a tag on a radix tree node
 * @root:		radix tree root
 * @index:		index key
M
Matthew Wilcox 已提交
811
 * @tag:		tag index (< RADIX_TREE_MAX_TAGS)
L
Linus Torvalds 已提交
812
 *
813
 * Return values:
L
Linus Torvalds 已提交
814
 *
N
Nick Piggin 已提交
815 816
 *  0: tag not present or not set
 *  1: tag set
817 818 819 820
 *
 * Note that the return value of this function may not be relied on, even if
 * the RCU lock is held, unless tag modification and node deletion are excluded
 * from concurrency.
L
Linus Torvalds 已提交
821 822
 */
int radix_tree_tag_get(struct radix_tree_root *root,
823
			unsigned long index, unsigned int tag)
L
Linus Torvalds 已提交
824
{
825 826 827
	struct radix_tree_node *node, *parent;
	unsigned long maxindex;
	unsigned int shift;
L
Linus Torvalds 已提交
828

N
Nick Piggin 已提交
829 830 831
	if (!root_tag_get(root, tag))
		return 0;

832 833 834
	shift = radix_tree_load_root(root, &node, &maxindex);
	if (index > maxindex)
		return 0;
835 836 837
	if (node == NULL)
		return 0;

838
	while (radix_tree_is_internal_node(node)) {
839
		int offset;
N
Nick Piggin 已提交
840

841 842
		shift -= RADIX_TREE_MAP_SHIFT;
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
L
Linus Torvalds 已提交
843

844
		parent = entry_to_node(node);
845
		offset = radix_tree_descend(parent, &node, offset);
L
Linus Torvalds 已提交
846

847
		if (!node)
L
Linus Torvalds 已提交
848
			return 0;
849
		if (!tag_get(parent, tag, offset))
850
			return 0;
851 852
		if (node == RADIX_TREE_RETRY)
			break;
L
Linus Torvalds 已提交
853
	}
854 855

	return 1;
L
Linus Torvalds 已提交
856 857 858
}
EXPORT_SYMBOL(radix_tree_tag_get);

859 860 861 862 863 864 865 866
static inline void __set_iter_shift(struct radix_tree_iter *iter,
					unsigned int shift)
{
#ifdef CONFIG_RADIX_TREE_MULTIORDER
	iter->shift = shift;
#endif
}

867 868 869 870 871 872 873 874 875 876 877 878 879
/**
 * radix_tree_next_chunk - find next chunk of slots for iteration
 *
 * @root:	radix tree root
 * @iter:	iterator state
 * @flags:	RADIX_TREE_ITER_* flags and tag index
 * Returns:	pointer to chunk first slot, or NULL if iteration is over
 */
void **radix_tree_next_chunk(struct radix_tree_root *root,
			     struct radix_tree_iter *iter, unsigned flags)
{
	unsigned shift, tag = flags & RADIX_TREE_ITER_TAG_MASK;
	struct radix_tree_node *rnode, *node;
880
	unsigned long index, offset, maxindex;
881 882 883 884 885 886 887 888 889

	if ((flags & RADIX_TREE_ITER_TAGGED) && !root_tag_get(root, tag))
		return NULL;

	/*
	 * Catch next_index overflow after ~0UL. iter->index never overflows
	 * during iterating; it can be zero only at the beginning.
	 * And we cannot overflow iter->next_index in a single step,
	 * because RADIX_TREE_MAP_SHIFT < BITS_PER_LONG.
890 891 892
	 *
	 * This condition also used by radix_tree_next_slot() to stop
	 * contiguous iterating, and forbid swithing to the next chunk.
893 894 895 896 897
	 */
	index = iter->next_index;
	if (!index && iter->index)
		return NULL;

898 899 900 901 902
 restart:
	shift = radix_tree_load_root(root, &rnode, &maxindex);
	if (index > maxindex)
		return NULL;

903
	if (radix_tree_is_internal_node(rnode)) {
904
		rnode = entry_to_node(rnode);
905
	} else if (rnode) {
906
		/* Single-slot tree */
907 908
		iter->index = index;
		iter->next_index = maxindex + 1;
909
		iter->tags = 1;
910
		__set_iter_shift(iter, shift);
911 912 913 914
		return (void **)&root->rnode;
	} else
		return NULL;

915
	shift -= RADIX_TREE_MAP_SHIFT;
916 917 918 919
	offset = index >> shift;

	node = rnode;
	while (1) {
920
		struct radix_tree_node *slot;
921 922 923 924 925 926 927 928
		unsigned new_off = radix_tree_descend(node, &slot, offset);

		if (new_off < offset) {
			offset = new_off;
			index &= ~((RADIX_TREE_MAP_SIZE << shift) - 1);
			index |= offset << shift;
		}

929
		if ((flags & RADIX_TREE_ITER_TAGGED) ?
930
				!tag_get(node, tag, offset) : !slot) {
931 932 933 934 935 936 937 938 939 940 941
			/* Hole detected */
			if (flags & RADIX_TREE_ITER_CONTIG)
				return NULL;

			if (flags & RADIX_TREE_ITER_TAGGED)
				offset = radix_tree_find_next_bit(
						node->tags[tag],
						RADIX_TREE_MAP_SIZE,
						offset + 1);
			else
				while (++offset	< RADIX_TREE_MAP_SIZE) {
942 943 944 945
					void *slot = node->slots[offset];
					if (is_sibling_entry(node, slot))
						continue;
					if (slot)
946 947 948 949 950 951 952 953 954
						break;
				}
			index &= ~((RADIX_TREE_MAP_SIZE << shift) - 1);
			index += offset << shift;
			/* Overflow after ~0UL */
			if (!index)
				return NULL;
			if (offset == RADIX_TREE_MAP_SIZE)
				goto restart;
955
			slot = rcu_dereference_raw(node->slots[offset]);
956 957
		}

958
		if ((slot == NULL) || (slot == RADIX_TREE_RETRY))
959
			goto restart;
960
		if (!radix_tree_is_internal_node(slot))
961
			break;
962

963
		node = entry_to_node(slot);
964 965 966 967 968
		shift -= RADIX_TREE_MAP_SHIFT;
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
	}

	/* Update the iterator state */
969 970 971
	iter->index = index & ~((1 << shift) - 1);
	iter->next_index = (index | ((RADIX_TREE_MAP_SIZE << shift) - 1)) + 1;
	__set_iter_shift(iter, shift);
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994

	/* Construct iter->tags bit-mask from node->tags[tag] array */
	if (flags & RADIX_TREE_ITER_TAGGED) {
		unsigned tag_long, tag_bit;

		tag_long = offset / BITS_PER_LONG;
		tag_bit  = offset % BITS_PER_LONG;
		iter->tags = node->tags[tag][tag_long] >> tag_bit;
		/* This never happens if RADIX_TREE_TAG_LONGS == 1 */
		if (tag_long < RADIX_TREE_TAG_LONGS - 1) {
			/* Pick tags from next element */
			if (tag_bit)
				iter->tags |= node->tags[tag][tag_long + 1] <<
						(BITS_PER_LONG - tag_bit);
			/* Clip chunk size, here only BITS_PER_LONG tags */
			iter->next_index = index + BITS_PER_LONG;
		}
	}

	return node->slots + offset;
}
EXPORT_SYMBOL(radix_tree_next_chunk);

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
/**
 * radix_tree_range_tag_if_tagged - for each item in given range set given
 *				   tag if item has another tag set
 * @root:		radix tree root
 * @first_indexp:	pointer to a starting index of a range to scan
 * @last_index:		last index of a range to scan
 * @nr_to_tag:		maximum number items to tag
 * @iftag:		tag index to test
 * @settag:		tag index to set if tested tag is set
 *
 * This function scans range of radix tree from first_index to last_index
 * (inclusive).  For each item in the range if iftag is set, the function sets
 * also settag. The function stops either after tagging nr_to_tag items or
 * after reaching last_index.
 *
1010 1011 1012 1013 1014 1015 1016
 * The tags must be set from the leaf level only and propagated back up the
 * path to the root. We must do this so that we resolve the full path before
 * setting any tags on intermediate nodes. If we set tags as we descend, then
 * we can get to the leaf node and find that the index that has the iftag
 * set is outside the range we are scanning. This reults in dangling tags and
 * can lead to problems with later tag operations (e.g. livelocks on lookups).
 *
M
Matthew Wilcox 已提交
1017
 * The function returns the number of leaves where the tag was set and sets
1018
 * *first_indexp to the first unscanned index.
1019 1020
 * WARNING! *first_indexp can wrap if last_index is ULONG_MAX. Caller must
 * be prepared to handle that.
1021 1022 1023 1024 1025 1026
 */
unsigned long radix_tree_range_tag_if_tagged(struct radix_tree_root *root,
		unsigned long *first_indexp, unsigned long last_index,
		unsigned long nr_to_tag,
		unsigned int iftag, unsigned int settag)
{
1027 1028 1029
	struct radix_tree_node *slot, *node = NULL;
	unsigned long maxindex;
	unsigned int shift = radix_tree_load_root(root, &slot, &maxindex);
1030 1031
	unsigned long tagged = 0;
	unsigned long index = *first_indexp;
1032

1033
	last_index = min(last_index, maxindex);
1034 1035 1036 1037 1038 1039 1040 1041
	if (index > last_index)
		return 0;
	if (!nr_to_tag)
		return 0;
	if (!root_tag_get(root, iftag)) {
		*first_indexp = last_index + 1;
		return 0;
	}
1042
	if (!radix_tree_is_internal_node(slot)) {
1043 1044 1045 1046 1047
		*first_indexp = last_index + 1;
		root_tag_set(root, settag);
		return 1;
	}

1048
	node = entry_to_node(slot);
1049
	shift -= RADIX_TREE_MAP_SHIFT;
1050 1051

	for (;;) {
1052
		unsigned long upindex;
1053
		unsigned offset;
1054 1055

		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
1056 1057
		offset = radix_tree_descend(node, &slot, offset);
		if (!slot)
1058
			goto next;
1059
		if (!tag_get(node, iftag, offset))
1060
			goto next;
1061
		/* Sibling slots never have tags set on them */
1062
		if (radix_tree_is_internal_node(slot)) {
1063
			node = entry_to_node(slot);
1064 1065
			shift -= RADIX_TREE_MAP_SHIFT;
			continue;
1066 1067 1068
		}

		/* tag the leaf */
1069 1070
		tagged++;
		tag_set(node, settag, offset);
1071

1072
		slot = node->parent;
1073
		/* walk back up the path tagging interior nodes */
1074 1075
		upindex = index >> shift;
		while (slot) {
1076 1077 1078
			upindex >>= RADIX_TREE_MAP_SHIFT;
			offset = upindex & RADIX_TREE_MAP_MASK;

1079
			/* stop if we find a node with the tag already set */
1080
			if (tag_get(slot, settag, offset))
1081
				break;
1082 1083
			tag_set(slot, settag, offset);
			slot = slot->parent;
1084
		}
1085

1086
 next:
1087 1088
		/* Go to next item at level determined by 'shift' */
		index = ((index >> shift) + 1) << shift;
1089 1090
		/* Overflow can happen when last_index is ~0UL... */
		if (index > last_index || !index)
1091
			break;
1092 1093
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
		while (offset == 0) {
1094 1095 1096 1097 1098
			/*
			 * We've fully scanned this node. Go up. Because
			 * last_index is guaranteed to be in the tree, what
			 * we do below cannot wander astray.
			 */
1099
			node = node->parent;
1100
			shift += RADIX_TREE_MAP_SHIFT;
1101
			offset = (index >> shift) & RADIX_TREE_MAP_MASK;
1102
		}
1103 1104 1105 1106
		if (is_sibling_entry(node, node->slots[offset]))
			goto next;
		if (tagged >= nr_to_tag)
			break;
1107 1108
	}
	/*
1109 1110
	 * We need not to tag the root tag if there is no tag which is set with
	 * settag within the range from *first_indexp to last_index.
1111
	 */
1112 1113
	if (tagged > 0)
		root_tag_set(root, settag);
1114 1115 1116 1117 1118 1119
	*first_indexp = index;

	return tagged;
}
EXPORT_SYMBOL(radix_tree_range_tag_if_tagged);

L
Linus Torvalds 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
/**
 *	radix_tree_gang_lookup - perform multiple lookup on a radix tree
 *	@root:		radix tree root
 *	@results:	where the results of the lookup are placed
 *	@first_index:	start the lookup from this key
 *	@max_items:	place up to this many items at *results
 *
 *	Performs an index-ascending scan of the tree for present items.  Places
 *	them at *@results and returns the number of items which were placed at
 *	*@results.
 *
 *	The implementation is naive.
1132 1133 1134
 *
 *	Like radix_tree_lookup, radix_tree_gang_lookup may be called under
 *	rcu_read_lock. In this case, rather than the returned results being
M
Matthew Wilcox 已提交
1135 1136 1137 1138
 *	an atomic snapshot of the tree at a single point in time, the
 *	semantics of an RCU protected gang lookup are as though multiple
 *	radix_tree_lookups have been issued in individual locks, and results
 *	stored in 'results'.
L
Linus Torvalds 已提交
1139 1140 1141 1142 1143
 */
unsigned int
radix_tree_gang_lookup(struct radix_tree_root *root, void **results,
			unsigned long first_index, unsigned int max_items)
{
1144 1145 1146
	struct radix_tree_iter iter;
	void **slot;
	unsigned int ret = 0;
1147

1148
	if (unlikely(!max_items))
1149
		return 0;
L
Linus Torvalds 已提交
1150

1151
	radix_tree_for_each_slot(slot, root, &iter, first_index) {
1152
		results[ret] = rcu_dereference_raw(*slot);
1153 1154
		if (!results[ret])
			continue;
1155
		if (radix_tree_is_internal_node(results[ret])) {
1156 1157 1158
			slot = radix_tree_iter_retry(&iter);
			continue;
		}
1159
		if (++ret == max_items)
L
Linus Torvalds 已提交
1160 1161
			break;
	}
1162

L
Linus Torvalds 已提交
1163 1164 1165 1166
	return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup);

1167 1168 1169 1170
/**
 *	radix_tree_gang_lookup_slot - perform multiple slot lookup on radix tree
 *	@root:		radix tree root
 *	@results:	where the results of the lookup are placed
1171
 *	@indices:	where their indices should be placed (but usually NULL)
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
 *	@first_index:	start the lookup from this key
 *	@max_items:	place up to this many items at *results
 *
 *	Performs an index-ascending scan of the tree for present items.  Places
 *	their slots at *@results and returns the number of items which were
 *	placed at *@results.
 *
 *	The implementation is naive.
 *
 *	Like radix_tree_gang_lookup as far as RCU and locking goes. Slots must
 *	be dereferenced with radix_tree_deref_slot, and if using only RCU
 *	protection, radix_tree_deref_slot may fail requiring a retry.
 */
unsigned int
1186 1187
radix_tree_gang_lookup_slot(struct radix_tree_root *root,
			void ***results, unsigned long *indices,
1188 1189
			unsigned long first_index, unsigned int max_items)
{
1190 1191 1192
	struct radix_tree_iter iter;
	void **slot;
	unsigned int ret = 0;
1193

1194
	if (unlikely(!max_items))
1195 1196
		return 0;

1197 1198
	radix_tree_for_each_slot(slot, root, &iter, first_index) {
		results[ret] = slot;
1199
		if (indices)
1200 1201
			indices[ret] = iter.index;
		if (++ret == max_items)
1202 1203 1204 1205 1206 1207 1208
			break;
	}

	return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_slot);

L
Linus Torvalds 已提交
1209 1210 1211 1212 1213 1214 1215
/**
 *	radix_tree_gang_lookup_tag - perform multiple lookup on a radix tree
 *	                             based on a tag
 *	@root:		radix tree root
 *	@results:	where the results of the lookup are placed
 *	@first_index:	start the lookup from this key
 *	@max_items:	place up to this many items at *results
1216
 *	@tag:		the tag index (< RADIX_TREE_MAX_TAGS)
L
Linus Torvalds 已提交
1217 1218 1219 1220 1221 1222 1223
 *
 *	Performs an index-ascending scan of the tree for present items which
 *	have the tag indexed by @tag set.  Places the items at *@results and
 *	returns the number of items which were placed at *@results.
 */
unsigned int
radix_tree_gang_lookup_tag(struct radix_tree_root *root, void **results,
1224 1225
		unsigned long first_index, unsigned int max_items,
		unsigned int tag)
L
Linus Torvalds 已提交
1226
{
1227 1228 1229
	struct radix_tree_iter iter;
	void **slot;
	unsigned int ret = 0;
N
Nick Piggin 已提交
1230

1231
	if (unlikely(!max_items))
1232 1233
		return 0;

1234
	radix_tree_for_each_tagged(slot, root, &iter, first_index, tag) {
1235
		results[ret] = rcu_dereference_raw(*slot);
1236 1237
		if (!results[ret])
			continue;
1238
		if (radix_tree_is_internal_node(results[ret])) {
1239 1240 1241
			slot = radix_tree_iter_retry(&iter);
			continue;
		}
1242
		if (++ret == max_items)
L
Linus Torvalds 已提交
1243 1244
			break;
	}
1245

L
Linus Torvalds 已提交
1246 1247 1248 1249
	return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_tag);

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
/**
 *	radix_tree_gang_lookup_tag_slot - perform multiple slot lookup on a
 *					  radix tree based on a tag
 *	@root:		radix tree root
 *	@results:	where the results of the lookup are placed
 *	@first_index:	start the lookup from this key
 *	@max_items:	place up to this many items at *results
 *	@tag:		the tag index (< RADIX_TREE_MAX_TAGS)
 *
 *	Performs an index-ascending scan of the tree for present items which
 *	have the tag indexed by @tag set.  Places the slots at *@results and
 *	returns the number of slots which were placed at *@results.
 */
unsigned int
radix_tree_gang_lookup_tag_slot(struct radix_tree_root *root, void ***results,
		unsigned long first_index, unsigned int max_items,
		unsigned int tag)
{
1268 1269 1270
	struct radix_tree_iter iter;
	void **slot;
	unsigned int ret = 0;
1271

1272
	if (unlikely(!max_items))
1273 1274
		return 0;

1275 1276 1277
	radix_tree_for_each_tagged(slot, root, &iter, first_index, tag) {
		results[ret] = slot;
		if (++ret == max_items)
1278 1279 1280 1281 1282 1283 1284
			break;
	}

	return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_tag_slot);

1285 1286 1287
#if defined(CONFIG_SHMEM) && defined(CONFIG_SWAP)
#include <linux/sched.h> /* for cond_resched() */

1288 1289 1290 1291 1292
struct locate_info {
	unsigned long found_index;
	bool stop;
};

1293 1294 1295 1296
/*
 * This linear search is at present only useful to shmem_unuse_inode().
 */
static unsigned long __locate(struct radix_tree_node *slot, void *item,
1297
			      unsigned long index, struct locate_info *info)
1298
{
1299
	unsigned int shift;
1300 1301
	unsigned long i;

1302
	shift = slot->shift + RADIX_TREE_MAP_SHIFT;
1303

1304 1305
	do {
		shift -= RADIX_TREE_MAP_SHIFT;
1306

1307 1308 1309 1310 1311 1312 1313
		for (i = (index >> shift) & RADIX_TREE_MAP_MASK;
		     i < RADIX_TREE_MAP_SIZE;
		     i++, index += (1UL << shift)) {
			struct radix_tree_node *node =
					rcu_dereference_raw(slot->slots[i]);
			if (node == RADIX_TREE_RETRY)
				goto out;
1314
			if (!radix_tree_is_internal_node(node)) {
1315 1316 1317 1318 1319 1320
				if (node == item) {
					info->found_index = index;
					info->stop = true;
					goto out;
				}
				continue;
1321
			}
1322
			node = entry_to_node(node);
1323 1324 1325 1326
			if (is_sibling_entry(slot, node))
				continue;
			slot = node;
			break;
1327
		}
1328 1329 1330
		if (i == RADIX_TREE_MAP_SIZE)
			break;
	} while (shift);
1331 1332

out:
1333 1334
	if ((index == 0) && (i == RADIX_TREE_MAP_SIZE))
		info->stop = true;
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
	return index;
}

/**
 *	radix_tree_locate_item - search through radix tree for item
 *	@root:		radix tree root
 *	@item:		item to be found
 *
 *	Returns index where item was found, or -1 if not found.
 *	Caller must hold no lock (since this time-consuming function needs
 *	to be preemptible), and must check afterwards if item is still there.
 */
unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item)
{
	struct radix_tree_node *node;
	unsigned long max_index;
	unsigned long cur_index = 0;
1352 1353 1354 1355
	struct locate_info info = {
		.found_index = -1,
		.stop = false,
	};
1356 1357 1358 1359

	do {
		rcu_read_lock();
		node = rcu_dereference_raw(root->rnode);
1360
		if (!radix_tree_is_internal_node(node)) {
1361 1362
			rcu_read_unlock();
			if (node == item)
1363
				info.found_index = 0;
1364 1365 1366
			break;
		}

1367
		node = entry_to_node(node);
1368 1369

		max_index = node_maxindex(node);
1370 1371
		if (cur_index > max_index) {
			rcu_read_unlock();
1372
			break;
1373
		}
1374

1375
		cur_index = __locate(node, item, cur_index, &info);
1376 1377
		rcu_read_unlock();
		cond_resched();
1378
	} while (!info.stop && cur_index <= max_index);
1379

1380
	return info.found_index;
1381 1382 1383 1384 1385 1386 1387
}
#else
unsigned long radix_tree_locate_item(struct radix_tree_root *root, void *item)
{
	return -1;
}
#endif /* CONFIG_SHMEM && CONFIG_SWAP */
1388

1389
/**
M
Matthew Wilcox 已提交
1390
 *	radix_tree_shrink    -    shrink radix tree to minimum height
1391 1392
 *	@root		radix tree root
 */
1393
static inline bool radix_tree_shrink(struct radix_tree_root *root)
1394
{
1395 1396
	bool shrunk = false;

M
Matthew Wilcox 已提交
1397
	for (;;) {
1398 1399
		struct radix_tree_node *node = root->rnode;
		struct radix_tree_node *child;
1400

1401
		if (!radix_tree_is_internal_node(node))
M
Matthew Wilcox 已提交
1402
			break;
1403
		node = entry_to_node(node);
N
Nick Piggin 已提交
1404 1405 1406

		/*
		 * The candidate node has more than one child, or its child
M
Matthew Wilcox 已提交
1407 1408
		 * is not at the leftmost slot, or the child is a multiorder
		 * entry, we cannot shrink.
N
Nick Piggin 已提交
1409
		 */
1410
		if (node->count != 1)
N
Nick Piggin 已提交
1411
			break;
1412 1413
		child = node->slots[0];
		if (!child)
N
Nick Piggin 已提交
1414
			break;
1415
		if (!radix_tree_is_internal_node(child) && node->shift)
1416 1417
			break;

1418 1419
		if (radix_tree_is_internal_node(child))
			entry_to_node(child)->parent = NULL;
N
Nick Piggin 已提交
1420

1421 1422
		/*
		 * We don't need rcu_assign_pointer(), since we are simply
N
Nick Piggin 已提交
1423 1424
		 * moving the node from one part of the tree to another: if it
		 * was safe to dereference the old pointer to it
1425
		 * (node->slots[0]), it will be safe to dereference the new
N
Nick Piggin 已提交
1426
		 * one (root->rnode) as far as dependent read barriers go.
1427
		 */
1428
		root->rnode = child;
N
Nick Piggin 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

		/*
		 * We have a dilemma here. The node's slot[0] must not be
		 * NULLed in case there are concurrent lookups expecting to
		 * find the item. However if this was a bottom-level node,
		 * then it may be subject to the slot pointer being visible
		 * to callers dereferencing it. If item corresponding to
		 * slot[0] is subsequently deleted, these callers would expect
		 * their slot to become empty sooner or later.
		 *
		 * For example, lockless pagecache will look up a slot, deref
M
Matthew Wilcox 已提交
1440
		 * the page pointer, and if the page has 0 refcount it means it
N
Nick Piggin 已提交
1441 1442 1443 1444 1445 1446 1447
		 * was concurrently deleted from pagecache so try the deref
		 * again. Fortunately there is already a requirement for logic
		 * to retry the entire slot lookup -- the indirect pointer
		 * problem (replacing direct root node with an indirect pointer
		 * also results in a stale slot). So tag the slot as indirect
		 * to force callers to retry.
		 */
1448 1449
		if (!radix_tree_is_internal_node(child))
			node->slots[0] = RADIX_TREE_RETRY;
N
Nick Piggin 已提交
1450

1451
		radix_tree_node_free(node);
1452
		shrunk = true;
1453
	}
1454 1455

	return shrunk;
1456 1457
}

1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
/**
 *	__radix_tree_delete_node    -    try to free node after clearing a slot
 *	@root:		radix tree root
 *	@node:		node containing @index
 *
 *	After clearing the slot at @index in @node from radix tree
 *	rooted at @root, call this function to attempt freeing the
 *	node and shrinking the tree.
 *
 *	Returns %true if @node was freed, %false otherwise.
 */
1469
bool __radix_tree_delete_node(struct radix_tree_root *root,
1470 1471 1472 1473 1474 1475 1476 1477
			      struct radix_tree_node *node)
{
	bool deleted = false;

	do {
		struct radix_tree_node *parent;

		if (node->count) {
1478
			if (node == entry_to_node(root->rnode))
1479
				deleted |= radix_tree_shrink(root);
1480 1481 1482 1483 1484
			return deleted;
		}

		parent = node->parent;
		if (parent) {
1485
			parent->slots[node->offset] = NULL;
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
			parent->count--;
		} else {
			root_tag_clear_all(root);
			root->rnode = NULL;
		}

		radix_tree_node_free(node);
		deleted = true;

		node = parent;
	} while (node);

	return deleted;
}

1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
static inline void delete_sibling_entries(struct radix_tree_node *node,
					void *ptr, unsigned offset)
{
#ifdef CONFIG_RADIX_TREE_MULTIORDER
	int i;
	for (i = 1; offset + i < RADIX_TREE_MAP_SIZE; i++) {
		if (node->slots[offset + i] != ptr)
			break;
		node->slots[offset + i] = NULL;
		node->count--;
	}
#endif
}

L
Linus Torvalds 已提交
1515
/**
1516
 *	radix_tree_delete_item    -    delete an item from a radix tree
L
Linus Torvalds 已提交
1517 1518
 *	@root:		radix tree root
 *	@index:		index key
1519
 *	@item:		expected item
L
Linus Torvalds 已提交
1520
 *
1521
 *	Remove @item at @index from the radix tree rooted at @root.
L
Linus Torvalds 已提交
1522
 *
1523 1524
 *	Returns the address of the deleted item, or NULL if it was not present
 *	or the entry at the given @index was not @item.
L
Linus Torvalds 已提交
1525
 */
1526 1527
void *radix_tree_delete_item(struct radix_tree_root *root,
			     unsigned long index, void *item)
L
Linus Torvalds 已提交
1528
{
1529
	struct radix_tree_node *node;
1530
	unsigned int offset;
1531 1532
	void **slot;
	void *entry;
1533
	int tag;
L
Linus Torvalds 已提交
1534

1535 1536 1537
	entry = __radix_tree_lookup(root, index, &node, &slot);
	if (!entry)
		return NULL;
L
Linus Torvalds 已提交
1538

1539 1540 1541 1542
	if (item && entry != item)
		return NULL;

	if (!node) {
N
Nick Piggin 已提交
1543 1544
		root_tag_clear_all(root);
		root->rnode = NULL;
1545
		return entry;
N
Nick Piggin 已提交
1546
	}
L
Linus Torvalds 已提交
1547

1548
	offset = get_slot_offset(node, slot);
1549

L
Linus Torvalds 已提交
1550
	/*
1551 1552
	 * Clear all tags associated with the item to be deleted.
	 * This way of doing it would be inefficient, but seldom is any set.
L
Linus Torvalds 已提交
1553
	 */
1554
	for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
1555
		if (tag_get(node, tag, offset))
N
Nick Piggin 已提交
1556
			radix_tree_tag_clear(root, index, tag);
1557
	}
L
Linus Torvalds 已提交
1558

1559
	delete_sibling_entries(node, node_to_entry(slot), offset);
1560 1561
	node->slots[offset] = NULL;
	node->count--;
1562

1563
	__radix_tree_delete_node(root, node);
N
Nick Piggin 已提交
1564

1565
	return entry;
L
Linus Torvalds 已提交
1566
}
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
EXPORT_SYMBOL(radix_tree_delete_item);

/**
 *	radix_tree_delete    -    delete an item from a radix tree
 *	@root:		radix tree root
 *	@index:		index key
 *
 *	Remove the item at @index from the radix tree rooted at @root.
 *
 *	Returns the address of the deleted item, or NULL if it was not present.
 */
void *radix_tree_delete(struct radix_tree_root *root, unsigned long index)
{
	return radix_tree_delete_item(root, index, NULL);
}
L
Linus Torvalds 已提交
1582 1583 1584 1585 1586 1587 1588
EXPORT_SYMBOL(radix_tree_delete);

/**
 *	radix_tree_tagged - test whether any items in the tree are tagged
 *	@root:		radix tree root
 *	@tag:		tag to test
 */
1589
int radix_tree_tagged(struct radix_tree_root *root, unsigned int tag)
L
Linus Torvalds 已提交
1590
{
N
Nick Piggin 已提交
1591
	return root_tag_get(root, tag);
L
Linus Torvalds 已提交
1592 1593 1594 1595
}
EXPORT_SYMBOL(radix_tree_tagged);

static void
1596
radix_tree_node_ctor(void *arg)
L
Linus Torvalds 已提交
1597
{
1598 1599 1600 1601
	struct radix_tree_node *node = arg;

	memset(node, 0, sizeof(*node));
	INIT_LIST_HEAD(&node->private_list);
L
Linus Torvalds 已提交
1602 1603 1604
}

static int radix_tree_callback(struct notifier_block *nfb,
M
Matthew Wilcox 已提交
1605
				unsigned long action, void *hcpu)
L
Linus Torvalds 已提交
1606
{
M
Matthew Wilcox 已提交
1607 1608 1609 1610 1611 1612 1613 1614
	int cpu = (long)hcpu;
	struct radix_tree_preload *rtp;
	struct radix_tree_node *node;

	/* Free per-cpu pool of preloaded nodes */
	if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
		rtp = &per_cpu(radix_tree_preloads, cpu);
		while (rtp->nr) {
1615 1616 1617 1618
			node = rtp->nodes;
			rtp->nodes = node->private_data;
			kmem_cache_free(radix_tree_node_cachep, node);
			rtp->nr--;
M
Matthew Wilcox 已提交
1619 1620 1621
		}
	}
	return NOTIFY_OK;
L
Linus Torvalds 已提交
1622 1623 1624 1625 1626 1627
}

void __init radix_tree_init(void)
{
	radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
			sizeof(struct radix_tree_node), 0,
C
Christoph Lameter 已提交
1628 1629
			SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
			radix_tree_node_ctor);
L
Linus Torvalds 已提交
1630 1631
	hotcpu_notifier(radix_tree_callback, 0);
}