pthread_attr_setaffinity.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* Copyright (C) 2003, 2004, 2006 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Ulrich Drepper <drepper@redhat.com>, 2003.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <assert.h>
  16. #include <errno.h>
  17. #include <limits.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <pthreadP.h>
  21. /* Defined in pthread_setaffinity.c. */
  22. extern size_t __kernel_cpumask_size attribute_hidden;
  23. extern int __determine_cpumask_size (pid_t tid);
  24. libpthread_hidden_proto(__determine_cpumask_size)
  25. int
  26. pthread_attr_setaffinity_np (pthread_attr_t *attr, size_t cpusetsize,
  27. const cpu_set_t *cpuset)
  28. {
  29. struct pthread_attr *iattr;
  30. assert (sizeof (*attr) >= sizeof (struct pthread_attr));
  31. iattr = (struct pthread_attr *) attr;
  32. if (cpuset == NULL || cpusetsize == 0)
  33. {
  34. free (iattr->cpuset);
  35. iattr->cpuset = NULL;
  36. iattr->cpusetsize = 0;
  37. }
  38. else
  39. {
  40. if (__kernel_cpumask_size == 0)
  41. {
  42. int res = __determine_cpumask_size (THREAD_SELF->tid);
  43. if (res != 0)
  44. /* Some serious problem. */
  45. return res;
  46. }
  47. /* Check whether the new bitmask has any bit set beyond the
  48. last one the kernel accepts. */
  49. size_t cnt;
  50. for (cnt = __kernel_cpumask_size; cnt < cpusetsize; ++cnt)
  51. if (((char *) cpuset)[cnt] != '\0')
  52. /* Found a nonzero byte. This means the user request cannot be
  53. fulfilled. */
  54. return EINVAL;
  55. if (iattr->cpusetsize != cpusetsize)
  56. {
  57. void *newp = (cpu_set_t *) realloc (iattr->cpuset, cpusetsize);
  58. if (newp == NULL)
  59. return ENOMEM;
  60. iattr->cpuset = newp;
  61. iattr->cpusetsize = cpusetsize;
  62. }
  63. memcpy (iattr->cpuset, cpuset, cpusetsize);
  64. }
  65. return 0;
  66. }