9414121fb78eb077372237399869319526e2e8d1
[platform/upstream/glibc.git] / ports / sysdeps / tile / nptl / pthread_spin_lock.c
1 /* Copyright (C) 2011-2014 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3    Contributed by Chris Metcalf <cmetcalf@tilera.com>, 2011.
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 "pthreadP.h"
20 #include <arch/spr_def.h>
21 #include <atomic.h>
22
23 /* Bound point for bounded exponential backoff */
24 #define BACKOFF_MAX 2048
25
26 /* Initial cycle delay for exponential backoff */
27 #define BACKOFF_START 32
28
29 #ifdef __tilegx__
30 /* Use cmpexch() after the initial fast-path exch to avoid
31    invalidating the cache line of the lock holder.  */
32 # define TNS(p) atomic_exchange_acq((p), 1)
33 # define CMPTNS(p) atomic_compare_and_exchange_val_acq((p), 1, 0)
34 #else
35 # define TNS(p) __insn_tns(p)
36 # define CMPTNS(p) __insn_tns(p)
37 # define SPR_CYCLE SPR_CYCLE_LOW   /* The low 32 bits are sufficient. */
38 #endif
39
40 int
41 pthread_spin_lock (pthread_spinlock_t *lock)
42 {
43   if (__builtin_expect (TNS (lock) != 0, 0))
44     {
45       unsigned int backoff = BACKOFF_START;
46       while (CMPTNS (lock) != 0)
47         {
48           unsigned int start = __insn_mfspr (SPR_CYCLE);
49           while (__insn_mfspr (SPR_CYCLE) - start < backoff)
50             ;
51           if (backoff < BACKOFF_MAX)
52             backoff *= 2;
53         }
54     }
55   return 0;
56 }