18c2ecf20Sopenharmony_ci/* SPDX-License-Identifier: GPL-2.0 */
28c2ecf20Sopenharmony_ci#ifndef __ASM_GENERIC_GETORDER_H
38c2ecf20Sopenharmony_ci#define __ASM_GENERIC_GETORDER_H
48c2ecf20Sopenharmony_ci
58c2ecf20Sopenharmony_ci#ifndef __ASSEMBLY__
68c2ecf20Sopenharmony_ci
78c2ecf20Sopenharmony_ci#include <linux/compiler.h>
88c2ecf20Sopenharmony_ci#include <linux/log2.h>
98c2ecf20Sopenharmony_ci
108c2ecf20Sopenharmony_ci/**
118c2ecf20Sopenharmony_ci * get_order - Determine the allocation order of a memory size
128c2ecf20Sopenharmony_ci * @size: The size for which to get the order
138c2ecf20Sopenharmony_ci *
148c2ecf20Sopenharmony_ci * Determine the allocation order of a particular sized block of memory.  This
158c2ecf20Sopenharmony_ci * is on a logarithmic scale, where:
168c2ecf20Sopenharmony_ci *
178c2ecf20Sopenharmony_ci *	0 -> 2^0 * PAGE_SIZE and below
188c2ecf20Sopenharmony_ci *	1 -> 2^1 * PAGE_SIZE to 2^0 * PAGE_SIZE + 1
198c2ecf20Sopenharmony_ci *	2 -> 2^2 * PAGE_SIZE to 2^1 * PAGE_SIZE + 1
208c2ecf20Sopenharmony_ci *	3 -> 2^3 * PAGE_SIZE to 2^2 * PAGE_SIZE + 1
218c2ecf20Sopenharmony_ci *	4 -> 2^4 * PAGE_SIZE to 2^3 * PAGE_SIZE + 1
228c2ecf20Sopenharmony_ci *	...
238c2ecf20Sopenharmony_ci *
248c2ecf20Sopenharmony_ci * The order returned is used to find the smallest allocation granule required
258c2ecf20Sopenharmony_ci * to hold an object of the specified size.
268c2ecf20Sopenharmony_ci *
278c2ecf20Sopenharmony_ci * The result is undefined if the size is 0.
288c2ecf20Sopenharmony_ci */
298c2ecf20Sopenharmony_cistatic inline __attribute_const__ int get_order(unsigned long size)
308c2ecf20Sopenharmony_ci{
318c2ecf20Sopenharmony_ci	if (__builtin_constant_p(size)) {
328c2ecf20Sopenharmony_ci		if (!size)
338c2ecf20Sopenharmony_ci			return BITS_PER_LONG - PAGE_SHIFT;
348c2ecf20Sopenharmony_ci
358c2ecf20Sopenharmony_ci		if (size < (1UL << PAGE_SHIFT))
368c2ecf20Sopenharmony_ci			return 0;
378c2ecf20Sopenharmony_ci
388c2ecf20Sopenharmony_ci		return ilog2((size) - 1) - PAGE_SHIFT + 1;
398c2ecf20Sopenharmony_ci	}
408c2ecf20Sopenharmony_ci
418c2ecf20Sopenharmony_ci	size--;
428c2ecf20Sopenharmony_ci	size >>= PAGE_SHIFT;
438c2ecf20Sopenharmony_ci#if BITS_PER_LONG == 32
448c2ecf20Sopenharmony_ci	return fls(size);
458c2ecf20Sopenharmony_ci#else
468c2ecf20Sopenharmony_ci	return fls64(size);
478c2ecf20Sopenharmony_ci#endif
488c2ecf20Sopenharmony_ci}
498c2ecf20Sopenharmony_ci
508c2ecf20Sopenharmony_ci#endif	/* __ASSEMBLY__ */
518c2ecf20Sopenharmony_ci
528c2ecf20Sopenharmony_ci#endif	/* __ASM_GENERIC_GETORDER_H */
53