blob: 0e337c9ce7de44e6e64ef629efbcf56c88c4f757 [file] [log] [blame]
Aaron Durbindc9f5cd2015-09-08 13:34:43 -05001#ifndef COMMONLIB_HELPERS_H
2#define COMMONLIB_HELPERS_H
3/* This file is for helpers for both coreboot firmware and its utilities. */
4
5#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
6
Aaron Durbin7ffcc0b2015-10-01 14:20:57 -05007#define ALIGN(x,a) __ALIGN_MASK(x,(__typeof__(x))(a)-1UL)
Aaron Durbindc9f5cd2015-09-08 13:34:43 -05008#define __ALIGN_MASK(x,mask) (((x)+(mask))&~(mask))
9#define ALIGN_UP(x,a) ALIGN((x),(a))
Aaron Durbin7ffcc0b2015-10-01 14:20:57 -050010#define ALIGN_DOWN(x,a) ((x) & ~((__typeof__(x))(a)-1UL))
11#define IS_ALIGNED(x,a) (((x) & ((__typeof__(x))(a)-1UL)) == 0)
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050012
Aaron Durbin7ffcc0b2015-10-01 14:20:57 -050013#ifndef MIN
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050014#define MIN(a,b) ((a) < (b) ? (a) : (b))
Aaron Durbin7ffcc0b2015-10-01 14:20:57 -050015#endif
16#ifndef MAX
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050017#define MAX(a,b) ((a) > (b) ? (a) : (b))
Aaron Durbin7ffcc0b2015-10-01 14:20:57 -050018#endif
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050019#define ABS(a) (((a) < 0) ? (-(a)) : (a))
20#define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))
21#define IS_POWER_OF_2(x) (((x) & ((x) - 1)) == 0)
22
23/* Standard units. */
24#define KiB (1<<10)
25#define MiB (1<<20)
26#define GiB (1<<30)
27/* Could we ever run into this one? I hope we get this much memory! */
28#define TiB (1<<40)
29
30#define KHz (1000)
31#define MHz (1000 * KHz)
32#define GHz (1000 * MHz)
33
Aaron Durbin7ffcc0b2015-10-01 14:20:57 -050034#ifndef offsetof
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050035#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
Aaron Durbin7ffcc0b2015-10-01 14:20:57 -050036#endif
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050037
38#if !defined(__clang__)
39#define check_member(structure, member, offset) _Static_assert( \
40 offsetof(struct structure, member) == offset, \
41 "`struct " #structure "` offset for `" #member "` is not " #offset )
42#else
43#define check_member(structure, member, offset)
44#endif
45
46/**
47 * container_of - cast a member of a structure out to the containing structure
48 * @param ptr: the pointer to the member.
49 * @param type: the type of the container struct this is embedded in.
50 * @param member: the name of the member within the struct.
51 *
52 */
53#define container_of(ptr, type, member) ({ \
Aaron Durbin7ffcc0b2015-10-01 14:20:57 -050054 const __typeof__( ((type *)0)->member ) *__mptr = (ptr); \
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050055 (type *)( (char *)__mptr - offsetof(type,member) );})
56
57#endif /* COMMONLIB_HELPERS_H */