summaryrefslogtreecommitdiff
path: root/src/commonlib/include/commonlib/helpers.h
blob: a5fe87d42e69c718c05a10eb6a179b17bfae1e7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
 * This file is part of the coreboot project.
 *
 * 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; version 2 of the License.
 *
 * 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.
 */

#ifndef COMMONLIB_HELPERS_H
#define COMMONLIB_HELPERS_H

/* This file is for helpers for both coreboot firmware and its utilities. Most
   of this has moved into <commonlib/bsd/helpers.h> now, this wrapper is just
   for the stuff that nobody bothered to confirm BSD-licensability of yet. */

#include <commonlib/bsd/helpers.h>

/*
 * Divide positive or negative dividend by positive divisor and round
 * to closest integer. Result is undefined for negative divisors and
 * for negative dividends if the divisor variable type is unsigned.
 */
#define DIV_ROUND_CLOSEST(x, divisor)({					\
	__typeof__(x) _div_local_x = (x);				\
	__typeof__(divisor) _div_local_d = (divisor);			\
	(((__typeof__(x))-1) > 0 ||					\
	 ((__typeof__(divisor))-1) > 0 || (_div_local_x) > 0) ?		\
		((_div_local_x + (_div_local_d / 2)) / _div_local_d) :	\
		((_div_local_x - (_div_local_d / 2)) / _div_local_d);	\
})

/**
 * container_of - cast a member of a structure out to the containing structure
 * @param ptr:    the pointer to the member.
 * @param type:   the type of the container struct this is embedded in.
 * @param member: the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member) ({			\
	const __typeof__(((type *)0)->member) *__mptr = (ptr);	\
	(type *)((char *)__mptr - offsetof(type, member)); })

#ifndef __unused
#define __unused __attribute__((unused))
#endif

#ifndef alloca
#define alloca(x) __builtin_alloca(x)
#endif

#endif /* COMMONLIB_HELPERS_H */