useful.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. *
  3. * Embedded Linux library
  4. *
  5. * Copyright (C) 2021 Intel Corporation. All rights reserved.
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. */
  22. #define align_len(len, boundary) (((len)+(boundary)-1) & ~((boundary)-1))
  23. #define likely(x) __builtin_expect(!!(x), 1)
  24. #define unlikely(x) __builtin_expect(!!(x), 0)
  25. static inline size_t minsize(size_t a, size_t b)
  26. {
  27. if (a <= b)
  28. return a;
  29. return b;
  30. }
  31. static inline void set_bit(void *addr, unsigned int bit)
  32. {
  33. unsigned char *field = addr;
  34. field[bit / 8] |= 1U << (bit % 8);
  35. }
  36. static inline int test_bit(const void *addr, unsigned int bit)
  37. {
  38. const unsigned char *field = addr;
  39. return (field[bit / 8] & (1U << (bit % 8))) != 0;
  40. }
  41. static inline unsigned char bit_field(const unsigned char oct,
  42. unsigned int start, unsigned int n_bits)
  43. {
  44. unsigned char mask = (1U << n_bits) - 1U;
  45. return (oct >> start) & mask;
  46. }
  47. #define DIV_ROUND_CLOSEST(x, divisor) \
  48. ({ \
  49. typeof(divisor) _d = (divisor); \
  50. typeof(x) _x = (x) + _d / 2; \
  51. _x / _d; \
  52. })
  53. #define __AUTODESTRUCT(var, func) \
  54. void cleanup_ ## var(void *ptr) \
  55. { func(*(void **) ptr); } \
  56. __attribute((cleanup(cleanup_ ## var)))
  57. #define _AUTODESTRUCT(var, func) \
  58. __AUTODESTRUCT(var, func)
  59. #define _auto_(func) \
  60. _AUTODESTRUCT(__COUNTER__, func)
  61. /*
  62. * Trick the compiler into thinking that var might be changed somehow by
  63. * the asm
  64. */
  65. #define DO_NOT_OPTIMIZE(var) \
  66. __asm__ ("" : "=r" (var) : "0" (var));
  67. static inline int secure_select(int select_left, int l, int r)
  68. {
  69. int mask = -(!!select_left);
  70. return r ^ ((l ^ r) & mask);
  71. }
  72. #define struct_alloc(structname, ...) \
  73. (struct structname *) l_memdup(&(struct structname) { __VA_ARGS__ }, \
  74. sizeof(struct structname))