posix: Remove alloca usage for internal fnmatch implementation
[platform/upstream/glibc.git] / posix / sched_cpucount.c
index d7f6b7b..95c125f 100644 (file)
@@ -1,4 +1,4 @@
-/* Copyright (C) 2007 Free Software Foundation, Inc.
+/* Copyright (C) 2007-2021 Free Software Foundation, Inc.
    This file is part of the GNU C Library.
 
    The GNU C Library is free software; you can redistribute it and/or
    Lesser General Public License for more details.
 
    You should have received a copy of the GNU Lesser General Public
-   License along with the GNU C Library; if not, write to the Free
-   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
-   02111-1307 USA.  */
+   License along with the GNU C Library; if not, see
+   <https://www.gnu.org/licenses/>.  */
 
-#include <limits.h>
 #include <sched.h>
 
+/* Counting bits set, Brian Kernighan's way.
+   Using a open-coded routine is slight better for architectures that
+   do not have a popcount instruction (compiler might emit a library
+   call).  */
+static inline int
+countbits (__cpu_mask v)
+{
+  int s = 0;
+  for (; v != 0; s++)
+    v &= v - 1;
+  return s;
+}
 
 int
-__sched_cpucount (size_t setsize, cpu_set_t *setp)
+__sched_cpucount (size_t setsize, const cpu_set_t *setp)
 {
   int s = 0;
-  for (unsigned int j = 0; j < setsize / sizeof (__cpu_mask); ++j)
-    {
-      __cpu_mask l = setp->__bits[j];
-      if (l == 0)
-       continue;
-
-#if LONG_BIT > 32
-      l = (l & 0x5555555555555555ul) + ((l >> 1) & 0x5555555555555555ul);
-      l = (l & 0x3333333333333333ul) + ((l >> 2) & 0x3333333333333333ul);
-      l = (l & 0x0f0f0f0f0f0f0f0ful) + ((l >> 4) & 0x0f0f0f0f0f0f0f0ful);
-      l = (l & 0x00ff00ff00ff00fful) + ((l >> 8) & 0x00ff00ff00ff00fful);
-      l = (l & 0x0000ffff0000fffful) + ((l >> 16) & 0x0000ffff0000fffful);
-      l = (l & 0x00000000fffffffful) + ((l >> 32) & 0x00000000fffffffful);
-#else
-      l = (l & 0x55555555ul) + ((l >> 1) & 0x55555555ul);
-      l = (l & 0x33333333ul) + ((l >> 2) & 0x33333333ul);
-      l = (l & 0x0f0f0f0ful) + ((l >> 4) & 0x0f0f0f0ful);
-      l = (l & 0x00ff00fful) + ((l >> 8) & 0x00ff00fful);
-      l = (l & 0x0000fffful) + ((l >> 16) & 0x0000fffful);
-#endif
-
-      s += l;
-    }
-
+  for (int i = 0; i < setsize / sizeof (__cpu_mask); i++)
+    s += countbits (setp->__bits[i]);
   return s;
 }
+libc_hidden_def (__sched_cpucount)