• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #ifndef _GNU_SOURCE
20 #define _GNU_SOURCE
21 #endif /* _GNU_SOURCE */
22 
23 #include <grpc/support/port_platform.h>
24 
25 #ifdef GPR_CPU_LINUX
26 
27 #include <errno.h>
28 #include <sched.h>
29 #include <string.h>
30 #include <unistd.h>
31 
32 #include <grpc/support/cpu.h>
33 #include <grpc/support/log.h>
34 #include <grpc/support/sync.h>
35 
36 static int ncpus = 0;
37 
init_num_cpus()38 static void init_num_cpus() {
39 #ifndef GPR_MUSL_LIBC_COMPAT
40   if (sched_getcpu() < 0) {
41     gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno));
42     ncpus = 1;
43     return;
44   }
45 #endif
46   /* This must be signed. sysconf returns -1 when the number cannot be
47      determined */
48   ncpus = static_cast<int>(sysconf(_SC_NPROCESSORS_CONF));
49   if (ncpus < 1) {
50     gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
51     ncpus = 1;
52   }
53 }
54 
gpr_cpu_num_cores(void)55 unsigned gpr_cpu_num_cores(void) {
56   static gpr_once once = GPR_ONCE_INIT;
57   gpr_once_init(&once, init_num_cpus);
58   return static_cast<unsigned>(ncpus);
59 }
60 
gpr_cpu_current_cpu(void)61 unsigned gpr_cpu_current_cpu(void) {
62 #ifdef GPR_MUSL_LIBC_COMPAT
63   // sched_getcpu() is undefined on musl
64   return 0;
65 #else
66   if (gpr_cpu_num_cores() == 1) {
67     return 0;
68   }
69   int cpu = sched_getcpu();
70   if (cpu < 0) {
71     gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno));
72     return 0;
73   }
74   if (static_cast<unsigned>(cpu) >= gpr_cpu_num_cores()) {
75     gpr_log(GPR_DEBUG, "Cannot handle hot-plugged CPUs");
76     return 0;
77   }
78   return static_cast<unsigned>(cpu);
79 #endif
80 }
81 
82 #endif /* GPR_CPU_LINUX */
83