select.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* SPDX-License-Identifier: LGPL-2.1 OR MIT */
  2. #include "../nolibc.h"
  3. #ifndef _NOLIBC_SYS_SELECT_H
  4. #define _NOLIBC_SYS_SELECT_H
  5. #include <linux/time.h>
  6. #include <linux/unistd.h>
  7. /* commonly an fd_set represents 256 FDs */
  8. #ifndef FD_SETSIZE
  9. #define FD_SETSIZE 256
  10. #endif
  11. #define FD_SETIDXMASK (8 * sizeof(unsigned long))
  12. #define FD_SETBITMASK (8 * sizeof(unsigned long)-1)
  13. /* for select() */
  14. typedef struct {
  15. unsigned long fds[(FD_SETSIZE + FD_SETBITMASK) / FD_SETIDXMASK];
  16. } fd_set;
  17. #define FD_CLR(fd, set) do { \
  18. fd_set *__set = (set); \
  19. int __fd = (fd); \
  20. if (__fd >= 0) \
  21. __set->fds[__fd / FD_SETIDXMASK] &= \
  22. ~(1U << (__fd & FD_SETBITMASK)); \
  23. } while (0)
  24. #define FD_SET(fd, set) do { \
  25. fd_set *__set = (set); \
  26. int __fd = (fd); \
  27. if (__fd >= 0) \
  28. __set->fds[__fd / FD_SETIDXMASK] |= \
  29. 1 << (__fd & FD_SETBITMASK); \
  30. } while (0)
  31. #define FD_ISSET(fd, set) ({ \
  32. fd_set *__set = (set); \
  33. int __fd = (fd); \
  34. int __r = 0; \
  35. if (__fd >= 0) \
  36. __r = !!(__set->fds[__fd / FD_SETIDXMASK] & \
  37. 1U << (__fd & FD_SETBITMASK)); \
  38. __r; \
  39. })
  40. #define FD_ZERO(set) do { \
  41. fd_set *__set = (set); \
  42. int __idx; \
  43. int __size = (FD_SETSIZE+FD_SETBITMASK) / FD_SETIDXMASK;\
  44. for (__idx = 0; __idx < __size; __idx++) \
  45. __set->fds[__idx] = 0; \
  46. } while (0)
  47. /*
  48. * int select(int nfds, fd_set *read_fds, fd_set *write_fds,
  49. * fd_set *except_fds, struct timeval *timeout);
  50. */
  51. static __attribute__((unused))
  52. int sys_select(int nfds, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *timeout)
  53. {
  54. #if defined(__NR_pselect6_time64)
  55. struct __kernel_timespec t;
  56. if (timeout) {
  57. t.tv_sec = timeout->tv_sec;
  58. t.tv_nsec = (uint32_t)timeout->tv_usec * 1000;
  59. }
  60. return my_syscall6(__NR_pselect6_time64, nfds, rfds, wfds, efds, timeout ? &t : NULL, NULL);
  61. #else
  62. struct __kernel_old_timespec t;
  63. if (timeout) {
  64. t.tv_sec = timeout->tv_sec;
  65. t.tv_nsec = (uint32_t)timeout->tv_usec * 1000;
  66. }
  67. return my_syscall6(__NR_pselect6, nfds, rfds, wfds, efds, timeout ? &t : NULL, NULL);
  68. #endif
  69. }
  70. static __attribute__((unused))
  71. int select(int nfds, fd_set *rfds, fd_set *wfds, fd_set *efds, struct timeval *timeout)
  72. {
  73. return __sysret(sys_select(nfds, rfds, wfds, efds, timeout));
  74. }
  75. #endif /* _NOLIBC_SYS_SELECT_H */