• 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 #include "src/core/lib/gprpp/crash.h"
37 #include "src/core/lib/gprpp/strerror.h"
38 
39 static int ncpus = 0;
40 
init_num_cpus()41 static void init_num_cpus() {
42 #ifndef GPR_MUSL_LIBC_COMPAT
43   if (sched_getcpu() < 0) {
44     gpr_log(GPR_ERROR, "Error determining current CPU: %s\n",
45             grpc_core::StrError(errno).c_str());
46     ncpus = 1;
47     return;
48   }
49 #endif
50   // This must be signed. sysconf returns -1 when the number cannot be
51   // determined
52   ncpus = static_cast<int>(sysconf(_SC_NPROCESSORS_CONF));
53   if (ncpus < 1) {
54     gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
55     ncpus = 1;
56   }
57 }
58 
gpr_cpu_num_cores(void)59 unsigned gpr_cpu_num_cores(void) {
60   static gpr_once once = GPR_ONCE_INIT;
61   gpr_once_init(&once, init_num_cpus);
62   return static_cast<unsigned>(ncpus);
63 }
64 
gpr_cpu_current_cpu(void)65 unsigned gpr_cpu_current_cpu(void) {
66 #ifdef GPR_MUSL_LIBC_COMPAT
67   // sched_getcpu() is undefined on musl
68   return 0;
69 #else
70   if (gpr_cpu_num_cores() == 1) {
71     return 0;
72   }
73   int cpu = sched_getcpu();
74   if (cpu < 0) {
75     gpr_log(GPR_ERROR, "Error determining current CPU: %s\n",
76             grpc_core::StrError(errno).c_str());
77     return 0;
78   }
79   if (static_cast<unsigned>(cpu) >= gpr_cpu_num_cores()) {
80     gpr_log(GPR_DEBUG, "Cannot handle hot-plugged CPUs");
81     return 0;
82   }
83   return static_cast<unsigned>(cpu);
84 #endif
85 }
86 
87 #endif  // GPR_CPU_LINUX
88