blob: b073e0e4929a660333d7855eeadbe128518480ae [file] [log] [blame]
Angel Ponsebda03e2020-04-02 23:48:05 +02001/* SPDX-License-Identifier: GPL-2.0-only */
Martin Rothf4d015d2016-01-12 16:21:45 -07002
Aaron Durbindc9f5cd2015-09-08 13:34:43 -05003#ifndef COMMONLIB_HELPERS_H
4#define COMMONLIB_HELPERS_H
Aaron Durbindc9f5cd2015-09-08 13:34:43 -05005
Julius Werner98eeb962019-12-11 15:47:42 -08006/* This file is for helpers for both coreboot firmware and its utilities. Most
7 of this has moved into <commonlib/bsd/helpers.h> now, this wrapper is just
8 for the stuff that nobody bothered to confirm BSD-licensability of yet. */
Jonathan Neuschäfer7bd47152017-10-30 19:28:52 +01009
Julius Werner98eeb962019-12-11 15:47:42 -080010#include <commonlib/bsd/helpers.h>
Julius Wernerd371cf32015-05-22 18:09:48 -070011
Arthur Heymans29fc9bb2016-09-02 23:14:54 +020012/*
13 * Divide positive or negative dividend by positive divisor and round
14 * to closest integer. Result is undefined for negative divisors and
15 * for negative dividends if the divisor variable type is unsigned.
16 */
Julius Wernerd371cf32015-05-22 18:09:48 -070017#define DIV_ROUND_CLOSEST(x, divisor)({ \
18 __typeof__(x) _div_local_x = (x); \
19 __typeof__(divisor) _div_local_d = (divisor); \
20 (((__typeof__(x))-1) > 0 || \
21 ((__typeof__(divisor))-1) > 0 || (_div_local_x) > 0) ? \
22 ((_div_local_x + (_div_local_d / 2)) / _div_local_d) : \
23 ((_div_local_x - (_div_local_d / 2)) / _div_local_d); \
24})
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050025
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050026/**
27 * container_of - cast a member of a structure out to the containing structure
28 * @param ptr: the pointer to the member.
29 * @param type: the type of the container struct this is embedded in.
30 * @param member: the name of the member within the struct.
31 *
32 */
33#define container_of(ptr, type, member) ({ \
Lee Leahyd5a2a292017-03-10 10:35:43 -080034 const __typeof__(((type *)0)->member) *__mptr = (ptr); \
35 (type *)((char *)__mptr - offsetof(type, member)); })
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050036
Aaron Durbinca0a6762015-12-15 17:49:12 -060037#ifndef __unused
38#define __unused __attribute__((unused))
39#endif
40
Tim Wawrzynczakeef992d2019-10-27 14:02:10 -060041#ifndef alloca
42#define alloca(x) __builtin_alloca(x)
43#endif
44
Aaron Durbindc9f5cd2015-09-08 13:34:43 -050045#endif /* COMMONLIB_HELPERS_H */