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