dpif-netdev: Use new "ovsthread_counter" to track dp statistics.
[sliver-openvswitch.git] / lib / ovs-thread.c
1 /*
2  * Copyright (c) 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ovs-thread.h"
19 #include <errno.h>
20 #include <poll.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include "compiler.h"
24 #include "hash.h"
25 #include "poll-loop.h"
26 #include "socket-util.h"
27 #include "util.h"
28
29 #ifdef __CHECKER__
30 /* Omit the definitions in this file because they are somewhat difficult to
31  * write without prompting "sparse" complaints, without ugliness or
32  * cut-and-paste.  Since "sparse" is just a checker, not a compiler, it
33  * doesn't matter that we don't define them. */
34 #else
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(ovs_thread);
38
39 /* If there is a reason that we cannot fork anymore (unless the fork will be
40  * immediately followed by an exec), then this points to a string that
41  * explains why. */
42 static const char *must_not_fork;
43
44 /* True if we created any threads beyond the main initial thread. */
45 static bool multithreaded;
46
47 #define LOCK_FUNCTION(TYPE, FUN) \
48     void \
49     ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
50                             const char *where) \
51         OVS_NO_THREAD_SAFETY_ANALYSIS \
52     { \
53         struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
54         int error = pthread_##TYPE##_##FUN(&l->lock); \
55         if (OVS_UNLIKELY(error)) { \
56             ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
57         } \
58         l->where = where; \
59     }
60 LOCK_FUNCTION(mutex, lock);
61 LOCK_FUNCTION(rwlock, rdlock);
62 LOCK_FUNCTION(rwlock, wrlock);
63
64 #define TRY_LOCK_FUNCTION(TYPE, FUN) \
65     int \
66     ovs_##TYPE##_##FUN##_at(const struct ovs_##TYPE *l_, \
67                             const char *where) \
68         OVS_NO_THREAD_SAFETY_ANALYSIS \
69     { \
70         struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
71         int error = pthread_##TYPE##_##FUN(&l->lock); \
72         if (OVS_UNLIKELY(error) && error != EBUSY) { \
73             ovs_abort(error, "pthread_%s_%s failed", #TYPE, #FUN); \
74         } \
75         if (!error) { \
76             l->where = where; \
77         } \
78         return error; \
79     }
80 TRY_LOCK_FUNCTION(mutex, trylock);
81 TRY_LOCK_FUNCTION(rwlock, tryrdlock);
82 TRY_LOCK_FUNCTION(rwlock, trywrlock);
83
84 #define UNLOCK_FUNCTION(TYPE, FUN) \
85     void \
86     ovs_##TYPE##_##FUN(const struct ovs_##TYPE *l_) \
87         OVS_NO_THREAD_SAFETY_ANALYSIS \
88     { \
89         struct ovs_##TYPE *l = CONST_CAST(struct ovs_##TYPE *, l_); \
90         int error; \
91         l->where = NULL; \
92         error = pthread_##TYPE##_##FUN(&l->lock); \
93         if (OVS_UNLIKELY(error)) { \
94             ovs_abort(error, "pthread_%s_%sfailed", #TYPE, #FUN); \
95         } \
96     }
97 UNLOCK_FUNCTION(mutex, unlock);
98 UNLOCK_FUNCTION(mutex, destroy);
99 UNLOCK_FUNCTION(rwlock, unlock);
100 UNLOCK_FUNCTION(rwlock, destroy);
101
102 #define XPTHREAD_FUNC1(FUNCTION, PARAM1)                \
103     void                                                \
104     x##FUNCTION(PARAM1 arg1)                            \
105     {                                                   \
106         int error = FUNCTION(arg1);                     \
107         if (OVS_UNLIKELY(error)) {                      \
108             ovs_abort(error, "%s failed", #FUNCTION);   \
109         }                                               \
110     }
111 #define XPTHREAD_FUNC2(FUNCTION, PARAM1, PARAM2)        \
112     void                                                \
113     x##FUNCTION(PARAM1 arg1, PARAM2 arg2)               \
114     {                                                   \
115         int error = FUNCTION(arg1, arg2);               \
116         if (OVS_UNLIKELY(error)) {                      \
117             ovs_abort(error, "%s failed", #FUNCTION);   \
118         }                                               \
119     }
120
121 XPTHREAD_FUNC1(pthread_mutex_lock, pthread_mutex_t *);
122 XPTHREAD_FUNC1(pthread_mutex_unlock, pthread_mutex_t *);
123 XPTHREAD_FUNC1(pthread_mutexattr_init, pthread_mutexattr_t *);
124 XPTHREAD_FUNC1(pthread_mutexattr_destroy, pthread_mutexattr_t *);
125 XPTHREAD_FUNC2(pthread_mutexattr_settype, pthread_mutexattr_t *, int);
126 XPTHREAD_FUNC2(pthread_mutexattr_gettype, pthread_mutexattr_t *, int *);
127
128 XPTHREAD_FUNC2(pthread_cond_init, pthread_cond_t *, pthread_condattr_t *);
129 XPTHREAD_FUNC1(pthread_cond_destroy, pthread_cond_t *);
130 XPTHREAD_FUNC1(pthread_cond_signal, pthread_cond_t *);
131 XPTHREAD_FUNC1(pthread_cond_broadcast, pthread_cond_t *);
132
133 XPTHREAD_FUNC2(pthread_join, pthread_t, void **);
134
135 typedef void destructor_func(void *);
136 XPTHREAD_FUNC2(pthread_key_create, pthread_key_t *, destructor_func *);
137 XPTHREAD_FUNC2(pthread_setspecific, pthread_key_t, const void *);
138
139 static void
140 ovs_mutex_init__(const struct ovs_mutex *l_, int type)
141 {
142     struct ovs_mutex *l = CONST_CAST(struct ovs_mutex *, l_);
143     pthread_mutexattr_t attr;
144     int error;
145
146     l->where = NULL;
147     xpthread_mutexattr_init(&attr);
148     xpthread_mutexattr_settype(&attr, type);
149     error = pthread_mutex_init(&l->lock, &attr);
150     if (OVS_UNLIKELY(error)) {
151         ovs_abort(error, "pthread_mutex_init failed");
152     }
153     xpthread_mutexattr_destroy(&attr);
154 }
155
156 /* Initializes 'mutex' as a normal (non-recursive) mutex. */
157 void
158 ovs_mutex_init(const struct ovs_mutex *mutex)
159 {
160     ovs_mutex_init__(mutex, PTHREAD_MUTEX_ERRORCHECK);
161 }
162
163 /* Initializes 'mutex' as a recursive mutex. */
164 void
165 ovs_mutex_init_recursive(const struct ovs_mutex *mutex)
166 {
167     ovs_mutex_init__(mutex, PTHREAD_MUTEX_RECURSIVE);
168 }
169
170 void
171 ovs_rwlock_init(const struct ovs_rwlock *l_)
172 {
173     struct ovs_rwlock *l = CONST_CAST(struct ovs_rwlock *, l_);
174     int error;
175
176     l->where = NULL;
177     error = pthread_rwlock_init(&l->lock, NULL);
178     if (OVS_UNLIKELY(error)) {
179         ovs_abort(error, "pthread_rwlock_init failed");
180     }
181 }
182
183 void
184 ovs_mutex_cond_wait(pthread_cond_t *cond, const struct ovs_mutex *mutex_)
185 {
186     struct ovs_mutex *mutex = CONST_CAST(struct ovs_mutex *, mutex_);
187     int error = pthread_cond_wait(cond, &mutex->lock);
188     if (OVS_UNLIKELY(error)) {
189         ovs_abort(error, "pthread_cond_wait failed");
190     }
191 }
192 \f
193 DEFINE_EXTERN_PER_THREAD_DATA(ovsthread_id, 0);
194
195 struct ovsthread_aux {
196     void *(*start)(void *);
197     void *arg;
198 };
199
200 static void *
201 ovsthread_wrapper(void *aux_)
202 {
203     static atomic_uint next_id = ATOMIC_VAR_INIT(1);
204
205     struct ovsthread_aux *auxp = aux_;
206     struct ovsthread_aux aux;
207     unsigned int id;
208
209     atomic_add(&next_id, 1, &id);
210     *ovsthread_id_get() = id;
211
212     aux = *auxp;
213     free(auxp);
214
215     return aux.start(aux.arg);
216 }
217
218 void
219 xpthread_create(pthread_t *threadp, pthread_attr_t *attr,
220                 void *(*start)(void *), void *arg)
221 {
222     struct ovsthread_aux *aux;
223     pthread_t thread;
224     int error;
225
226     forbid_forking("multiple threads exist");
227     multithreaded = true;
228
229     aux = xmalloc(sizeof *aux);
230     aux->start = start;
231     aux->arg = arg;
232
233     error = pthread_create(threadp ? threadp : &thread, attr,
234                            ovsthread_wrapper, aux);
235     if (error) {
236         ovs_abort(error, "pthread_create failed");
237     }
238 }
239 \f
240 bool
241 ovsthread_once_start__(struct ovsthread_once *once)
242 {
243     ovs_mutex_lock(&once->mutex);
244     if (!ovsthread_once_is_done__(once)) {
245         return false;
246     }
247     ovs_mutex_unlock(&once->mutex);
248     return true;
249 }
250
251 void
252 ovsthread_once_done(struct ovsthread_once *once)
253 {
254     atomic_store(&once->done, true);
255     ovs_mutex_unlock(&once->mutex);
256 }
257 \f
258 /* Asserts that the process has not yet created any threads (beyond the initial
259  * thread).
260  *
261  * ('where' is used in logging.  Commonly one would use
262  * assert_single_threaded() to automatically provide the caller's source file
263  * and line number for 'where'.) */
264 void
265 assert_single_threaded_at(const char *where)
266 {
267     if (multithreaded) {
268         VLOG_FATAL("%s: attempted operation not allowed when multithreaded",
269                    where);
270     }
271 }
272
273 /* Forks the current process (checking that this is allowed).  Aborts with
274  * VLOG_FATAL if fork() returns an error, and otherwise returns the value
275  * returned by fork().
276  *
277  * ('where' is used in logging.  Commonly one would use xfork() to
278  * automatically provide the caller's source file and line number for
279  * 'where'.) */
280 pid_t
281 xfork_at(const char *where)
282 {
283     pid_t pid;
284
285     if (must_not_fork) {
286         VLOG_FATAL("%s: attempted to fork but forking not allowed (%s)",
287                    where, must_not_fork);
288     }
289
290     pid = fork();
291     if (pid < 0) {
292         VLOG_FATAL("%s: fork failed (%s)", where, ovs_strerror(errno));
293     }
294     return pid;
295 }
296
297 /* Notes that the process must not call fork() from now on, for the specified
298  * 'reason'.  (The process may still fork() if it execs itself immediately
299  * afterward.) */
300 void
301 forbid_forking(const char *reason)
302 {
303     ovs_assert(reason != NULL);
304     must_not_fork = reason;
305 }
306
307 /* Returns true if the process is allowed to fork, false otherwise. */
308 bool
309 may_fork(void)
310 {
311     return !must_not_fork;
312 }
313 \f
314 /* ovsthread_counter.
315  *
316  * We implement the counter as an array of N_COUNTERS individual counters, each
317  * with its own lock.  Each thread uses one of the counters chosen based on a
318  * hash of the thread's ID, the idea being that, statistically, different
319  * threads will tend to use different counters and therefore avoid
320  * interfering with each other.
321  *
322  * Undoubtedly, better implementations are possible. */
323
324 /* Basic counter structure. */
325 struct ovsthread_counter__ {
326     struct ovs_mutex mutex;
327     unsigned long long int value;
328 };
329
330 /* Pad the basic counter structure to 64 bytes to avoid cache line
331  * interference. */
332 struct ovsthread_counter {
333     struct ovsthread_counter__ c;
334     char pad[ROUND_UP(sizeof(struct ovsthread_counter__), 64)
335              - sizeof(struct ovsthread_counter__)];
336 };
337
338 #define N_COUNTERS 16
339
340 struct ovsthread_counter *
341 ovsthread_counter_create(void)
342 {
343     struct ovsthread_counter *c;
344     int i;
345
346     c = xmalloc(N_COUNTERS * sizeof *c);
347     for (i = 0; i < N_COUNTERS; i++) {
348         ovs_mutex_init(&c[i].c.mutex);
349         c[i].c.value = 0;
350     }
351     return c;
352 }
353
354 void
355 ovsthread_counter_destroy(struct ovsthread_counter *c)
356 {
357     if (c) {
358         int i;
359
360         for (i = 0; i < N_COUNTERS; i++) {
361             ovs_mutex_destroy(&c[i].c.mutex);
362         }
363         free(c);
364     }
365 }
366
367 void
368 ovsthread_counter_inc(struct ovsthread_counter *c, unsigned long long int n)
369 {
370     c = &c[hash_int(ovsthread_id_self(), 0) % N_COUNTERS];
371
372     ovs_mutex_lock(&c->c.mutex);
373     c->c.value += n;
374     ovs_mutex_unlock(&c->c.mutex);
375 }
376
377 unsigned long long int
378 ovsthread_counter_read(const struct ovsthread_counter *c)
379 {
380     unsigned long long int sum;
381     int i;
382
383     sum = 0;
384     for (i = 0; i < N_COUNTERS; i++) {
385         ovs_mutex_lock(&c[i].c.mutex);
386         sum += c[i].c.value;
387         ovs_mutex_unlock(&c[i].c.mutex);
388     }
389     return sum;
390 }
391 \f
392 /* Parses /proc/cpuinfo for the total number of physical cores on this system
393  * across all CPU packages, not counting hyper-threads.
394  *
395  * Sets *n_cores to the total number of cores on this system, or 0 if the
396  * number cannot be determined. */
397 static void
398 parse_cpuinfo(long int *n_cores)
399 {
400     static const char file_name[] = "/proc/cpuinfo";
401     char line[128];
402     uint64_t cpu = 0; /* Support up to 64 CPU packages on a single system. */
403     long int cores = 0;
404     FILE *stream;
405
406     stream = fopen(file_name, "r");
407     if (!stream) {
408         VLOG_DBG("%s: open failed (%s)", file_name, ovs_strerror(errno));
409         return;
410     }
411
412     while (fgets(line, sizeof line, stream)) {
413         unsigned int id;
414
415         /* Find the next CPU package. */
416         if (ovs_scan(line, "physical id%*[^:]: %u", &id)) {
417             if (id > 63) {
418                 VLOG_WARN("Counted over 64 CPU packages on this system. "
419                           "Parsing %s for core count may be inaccurate.",
420                           file_name);
421                 cores = 0;
422                 break;
423             }
424
425             if (cpu & (1 << id)) {
426                 /* We've already counted this package's cores. */
427                 continue;
428             }
429             cpu |= 1 << id;
430
431             /* Find the number of cores for this package. */
432             while (fgets(line, sizeof line, stream)) {
433                 int count;
434
435                 if (ovs_scan(line, "cpu cores%*[^:]: %u", &count)) {
436                     cores += count;
437                     break;
438                 }
439             }
440         }
441     }
442     fclose(stream);
443
444     *n_cores = cores;
445 }
446
447 /* Returns the total number of cores on this system, or 0 if the number cannot
448  * be determined.
449  *
450  * Tries not to count hyper-threads, but may be inaccurate - particularly on
451  * platforms that do not provide /proc/cpuinfo, but also if /proc/cpuinfo is
452  * formatted different to the layout that parse_cpuinfo() expects. */
453 int
454 count_cpu_cores(void)
455 {
456     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
457     static long int n_cores;
458
459     if (ovsthread_once_start(&once)) {
460         parse_cpuinfo(&n_cores);
461         if (!n_cores) {
462             n_cores = sysconf(_SC_NPROCESSORS_ONLN);
463         }
464         ovsthread_once_done(&once);
465     }
466
467     return n_cores > 0 ? n_cores : 0;
468 }
469 #endif