diff mbox

[1/2] Optimize generic spinlock code and use C11 like atomic macros.

Message ID 60a34645-17e4-6693-1343-03c55b0c47ad@linux.vnet.ibm.com
State Superseded
Headers show

Commit Message

Stefan Liebler Feb. 15, 2017, 9:35 a.m. UTC
On 02/13/2017 09:29 PM, Torvald Riegel wrote:
> Thanks for working on this.  Detailed comments below.
>
> Generally, I think we need to keep working on optimizing this (this can
> happen in follow-up patches).  For example, we should have
> microbenchmarks for the exchange vs. CAS choice.
>
> Also, some of the tuning knobs such as
> SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG apply to atomics in general and
> not just the spinlock.  I'd prefer if these where in a state in which we
> could add them as property that's part of the atomics interface.
>
> On Wed, 2017-02-08 at 15:49 +0100, Stefan Liebler wrote:
>> diff --git a/include/atomic.h b/include/atomic.h
>> index 7f32640..770db4a 100644
>> --- a/include/atomic.h
>>
>> +++ b/include/atomic.h
>>
>> @@ -54,7 +54,7 @@
>>     and following args.  */
>>  #define __atomic_val_bysize(pre, post, mem, ...)			      \
>>    ({									      \
>> -    __typeof (*mem) __atg1_result;					      \
>>
>> +    __typeof ((__typeof (*(mem))) *(mem)) __atg1_result;		      \
>>
>>      if (sizeof (*mem) == 1)						      \
>>        __atg1_result = pre##_8_##post (mem, __VA_ARGS__);		      \
>>      else if (sizeof (*mem) == 2)					      \
>> @@ -162,9 +162,9 @@
>>  /* Store NEWVALUE in *MEM and return the old value.  */
>>  #ifndef atomic_exchange_acq
>>  # define atomic_exchange_acq(mem, newvalue) \
>> -  ({ __typeof (*(mem)) __atg5_oldval;					      \
>>
>> +  ({ __typeof ((__typeof (*(mem))) *(mem)) __atg5_oldval;		      \
>>
>>       __typeof (mem) __atg5_memp = (mem);				      \
>> -     __typeof (*(mem)) __atg5_value = (newvalue);			      \
>>
>> +     __typeof ((__typeof (*(mem))) *(mem)) __atg5_value = (newvalue);	      \
>>
>>  									      \
>>       do									      \
>>         __atg5_oldval = *__atg5_memp;					      \
>> @@ -668,7 +668,7 @@ void __atomic_link_error (void);
>>
>>  # ifndef atomic_load_relaxed
>>  #  define atomic_load_relaxed(mem) \
>> -   ({ __typeof (*(mem)) __atg100_val;					      \
>>
>> +   ({ __typeof ((__typeof (*(mem))) *(mem)) __atg100_val;		      \
>>
>>     __asm ("" : "=r" (__atg100_val) : "0" (*(mem)));			      \
>>     __atg100_val; })
>>  # endif
>
> You could keep these changes, but it's a bit odd because you only apply
> them for the functions you needed them for.  I think it would be better
> to just remove the volatile qualification in the caller (ie, cast lock
> to nonvolatile in pthread_spin_lock etc.
>
Yes, I've only applied them for the functions needed in spinlock-code.
Removing volatile from type pthread_spinlock_t is no option and
casting the volatile pointer to a non-volatile pointer is undefined.
See comment from Florian:
On 12/16/2016 09:12 PM, Florian Weimer wrote:
> That's undefined:
>
> “If an attempt is made to refer to an object defined with a
> volatile-qualified type through use of an lvalue with
> non-volatile-qualified type, the behavior is undefined.”
>
> But we cannot drop the volatile qualifier from the definition of
> pthread_spinlock_t because it would change the C++ mangling of
> pthread_spinlock_t * and similar types.


>> diff --git a/nptl/pthread_spin_init.c b/nptl/pthread_spin_init.c
>> index 01dec5e..bca3590 100644
>> --- a/nptl/pthread_spin_init.c
>>
>> +++ b/nptl/pthread_spin_init.c
>>
>> @@ -22,6 +22,8 @@
>>  int
>>  pthread_spin_init (pthread_spinlock_t *lock, int pshared)
>>  {
>> -  *lock = 0;
>>
>> +  /* The atomic_store_relaxed is enough as we only initialize the spinlock here
>>
>> +     and we are not in a critical region.  */
>
> I would change the comment to:
> /* Relaxed MO is fine because this is an initializing store.  */
Okay.

>
>>
>> +  atomic_store_relaxed (lock, 0);
>>
>>    return 0;
>>  }
>> diff --git a/nptl/pthread_spin_lock.c b/nptl/pthread_spin_lock.c
>> index 4d03b78..4107b5e 100644
>> --- a/nptl/pthread_spin_lock.c
>>
>> +++ b/nptl/pthread_spin_lock.c
>>
>> @@ -21,7 +21,7 @@
>>
>>  /* A machine-specific version can define SPIN_LOCK_READS_BETWEEN_CMPXCHG
>>    to the number of plain reads that it's optimal to spin on between uses
>> -  of atomic_compare_and_exchange_val_acq.  If spinning forever is optimal
>>
>> +  of atomic_compare_exchange_weak_acquire.  If spinning forever is optimal
>
> , at the end of this line.
>
Okay

>>    then use -1.  If no plain reads here would ever be optimal, use 0.  */
>>  #ifndef SPIN_LOCK_READS_BETWEEN_CMPXCHG
>>  # warning machine-dependent file should define SPIN_LOCK_READS_BETWEEN_CMPXCHG
>> @@ -37,10 +37,13 @@ pthread_spin_lock (pthread_spinlock_t *lock)
>>       when the lock is locked.
>>       We assume that the first try mostly will be successful, and we use
>>       atomic_exchange.  For the subsequent tries we use
>> -     atomic_compare_and_exchange.  */
>>
>> -  if (atomic_exchange_acq (lock, 1) == 0)
>>
>> +     atomic_compare_and_exchange.
>>
>> +     We need acquire memory order here as we need to see if another thread has
>>
>> +     locked / unlocked this spinlock.  */
>
> Please change to:
> We use acquire MO to synchronize-with the release MO store in
> pthread_spin_unlock, and thus ensure that prior critical sections
> happen-before this critical section.
>
Okay.

>>
>> +  if (__glibc_likely (atomic_exchange_acquire (lock, 1) == 0))
>>
>>      return 0;
>>
>> +  int val;
>>
>>    do
>>      {
>>        /* The lock is contended and we need to wait.  Going straight back
>> @@ -50,20 +53,39 @@ pthread_spin_lock (pthread_spinlock_t *lock)
>>  	 On the other hand, we do want to update memory state on the local core
>>  	 once in a while to avoid spinning indefinitely until some event that
>>  	 will happen to update local memory as a side-effect.  */
>> -      if (SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0)
>>
>> +
>>
>> +#if SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0
>>
>> +      /* Use at most SPIN_LOCK_READS_BETWEEN_CMPXCHG plain reads between the
>>
>> +	 atomic compare and exchanges.  */
>>
Also changed this comment to:
/* Use at most SPIN_LOCK_READS_BETWEEN_CMPXCHG relaxed MO reads between
    the atomic compare and exchanges.  */

>> +      int wait;
>>
>> +      for (wait = 0; wait < SPIN_LOCK_READS_BETWEEN_CMPXCHG;  wait ++)
>>
>>  	{
>> -	  int wait = SPIN_LOCK_READS_BETWEEN_CMPXCHG;
>>
>> +	  atomic_spin_nop ();
>>
>>
>> -	  while (*lock != 0 && wait > 0)
>>
>> -	    --wait;
>>
>> +	  val = atomic_load_relaxed (lock);
>>
>> +	  if (val == 0)
>>
>> +	    break;
>>
>>  	}
>> -      else
>>
>> +
>>
>> +      /* Set expected value to zero for the next compare and exchange.  */
>>
>> +      val = 0;
>>
>> +
>>
>> +#else /* SPIN_LOCK_READS_BETWEEN_CMPXCHG < 0  */
>>
>> +      /* Use plain reads until spinlock is free and then try a further atomic
>
>> +	 compare and exchange the next time.  */
>
>
> Please change to:
> Use relaxed-MO reads until we observe the lock to not be acquired
> anymore.
>
Okay.
>
>> +      do
>>
>>  	{
>> -	  while (*lock != 0)
>>
>> -	    ;
>>
>> +	  atomic_spin_nop ();
>>
>> +
>>
>> +	  val = atomic_load_relaxed (lock);
>>
>>  	}
>> +      while (val != 0);
>>
>> +
>>
>> +#endif
>>
>> +      /* We need acquire memory order here for the same reason as mentioned
>>
>> +	 for the first try to lock the spinlock.  */
>>
>>      }
>> -  while (atomic_compare_and_exchange_val_acq (lock, 1, 0) != 0);
>>
>> +  while (!atomic_compare_exchange_weak_acquire (lock, &val, 1));
>>
>>
>>    return 0;
>>  }
>> diff --git a/nptl/pthread_spin_trylock.c b/nptl/pthread_spin_trylock.c
>> index 593bba3..942a38f 100644
>> --- a/nptl/pthread_spin_trylock.c
>>
>> +++ b/nptl/pthread_spin_trylock.c
>>
>> @@ -20,8 +20,29 @@
>>  #include <atomic.h>
>>  #include "pthreadP.h"
>>
>> +/* A machine-specific version can define
>>
>> +   SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG to 1 if an explicit test if
>>
>> +   lock is free is optimal.  */
>>
>> +#ifndef SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG
>>
>> +# define SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG 0
>>
>> +#endif
>
> A while ago we tried hard to remove all code that would fail silently
> when a macro had a typo in the name, for example.  We still have a few
> of them left (e.g., in the atomics), but I think this here doesn't
> warrant an exception.
>
Okay. You're right.

In comment of patch 2/2, you've mentioned a header where an architecture
shall define those parameters.
Thus I've added the file nptl/pthread_spin_parameters.h.
It includes the description of the macros and it emits a warning
if one architecture tries to use generic spinlock implementation without
the definition of those macros.

Furthermore I've added pthread_spin_parameters.h files for the
architectures using the generic spinlock implementation
with definition of those macros.
The pthread_spin_lock.c files for those architectures are no longer 
required.

I've added a compiler error in nptl/pthread_spin_trylock.c
if the macro is not defined to zero or one.

If some arch has an empty pthread_spin_parameters.h file or a file 
without the definition of those macros and the include_next directive,
the pthread_spin_lock.c / pthread_spin_trylock.c will emit a Wundef warning.

> Also, the name does not match the description.  What are you really
> trying to parametrize here?  Do you want to do test-and-test-and-set vs.
> test-and-set? Or do you want to make some statement about how CAS vs.
> exchange behave in terms of runtime costs / effect on caches?  Or do you
> want to have a flag that says that exchange is implemented through a CAS
> loop anyway, and thus it's not worth trying an exchange if we actually
> want to bail out when the value is not equal to the expected value?
>
See below.

>>
>> +
>>
>>  int
>>  pthread_spin_trylock (pthread_spinlock_t *lock)
>>  {
>> -  return atomic_exchange_acq (lock, 1) ? EBUSY : 0;
>>
>> +  /* We need acquire memory order here as we need to see if another
>>
>> +     thread has locked / unlocked this spinlock.  */
>
> See above.  Please fix the comment in a similar way.
>
Changed comment to:
   /* We use acquire MO to synchronize-with the release MO store in
      pthread_spin_unlock, and thus ensure that prior critical sections
      happen-before this critical section.  */

>>
>> +#if SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG == 1
>>
>> +  /* Load and test the spinlock and only try to lock the spinlock if it is
>>
>> +     free.  */
>>
>> +  int val = atomic_load_relaxed (lock);
>>
>> +  if (__glibc_likely (val == 0 && atomic_exchange_acquire (lock, 1) == 0))
>
> I think that's not quite the same as a choice between CAS and exchange.
Yes. You are right.
> Doing a load first could be helpful for *both* CAS and exchange.  OTOH,
> if we assume that trylock will succeed most of the time, then the load
> is unnecessary and might be more costly (eg, if it causes the state of
> the cache line to change twice).
>
E.g. on s390, there exists no instruction which atomically exchanges the 
value. Instead a CAS loop is used. The CAS instruction locks the 
cache-line exclusively whether the value in memory equals the expected
old-value or not. Therefore the value is loaded and compared before 
using the CAS instruction.
If no other CPU has accessed the lock-value, the load will cause
the state of the cache line to exclusive.
If the lock is not acquired, the subsequent CAS instruction does not
need to change the state of the cache line.
If another CPU has accessed the lock-value e.g. by acquiring the lock,
the load will cause the state of the cache line either to read-only
or exclusive. This depends on the other CPU - whether it has already 
stored a new value or not.

As this behaviour depends on the architecture, the architecture has to
decide whether it should load and test the lock-value before the 
atomic-macro.

I've changed the name of the macro-define to 
SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG.
>>
>> +    return 0;
>>
>> +#else
>>
>> +  /* Set spinlock to locked and test if we have locked it.  */
>
> Just say that we try to acquire the lock, which succeeds if the lock had
> not been acquired.
Okay.
>
>> +  if (__glibc_likely (atomic_exchange_acquire (lock, 1) == 0))
>>
>> +    return 0;
>>
>> +#endif
>>
>> +
>>
>> +  return EBUSY;
>>
>>  }
>> diff --git a/nptl/pthread_spin_unlock.c b/nptl/pthread_spin_unlock.c
>> index 5fd73e5..f83b696 100644
>> --- a/nptl/pthread_spin_unlock.c
>>
>> +++ b/nptl/pthread_spin_unlock.c
>>
>> @@ -23,7 +23,9 @@
>>  int
>>  pthread_spin_unlock (pthread_spinlock_t *lock)
>>  {
>> -  atomic_full_barrier ();
>>
>> -  *lock = 0;
>>
>> +  /* The atomic_store_release synchronizes-with the atomic_exchange_acquire
>>
>> +     or atomic_compare_exchange_weak_acquire in pthread_spin_lock /
>>
>> +     pthread_spin_trylock.  */
>>
>> +  atomic_store_release (lock, 0);
>>
>>    return 0;
>>  }
>
> I agree with this change.  However, depending on how one interprets
> POSIX' memory model, one may expect lock releases to be sequentially
> consistent.  Nonetheless, IMO, glibc should use only release MO.
>
> But we need to announce this change.  Some of us have been considering
> an additional section in the manual were we specify where we deviate
> from POSIX; this change might be the first we're listing there (though
> to be fair, this is a deviation only on some architectures because on
> others such as powerpc I think, we've been using release MO forever).
>
>
As not all architectures use the generic spinlock implementation, what 
about a NEWS entry like:

* The new generic spinlock implementation uses C11 like atomics.
   The pthread_spin_unlock implementation is now using release
   memory order instead of sequentially consistent memory order.




Here is an updated version of patch 1/2.
(Patch 2/2 has to be aligned due to these changes, too)

Thanks.
Stefan

ChangeLog:

	* NEWS: Mention new spinlock implementation.
	* include/atomic.h:
	(__atomic_val_bysize): Cast type to omit volatile qualifier.
	(atomic_exchange_acq): Likewise.
	(atomic_load_relaxed): Likewise.
	* nptl/pthread_spin_init.c (pthread_spin_init):
	Use atomic_store_relaxed.
	* nptl/pthread_spin_lock.c (pthread_spin_lock):
	Use C11-like atomic macros.
	* nptl/pthread_spin_trylock.c
	(pthread_spin_trylock): Likewise.  Use an explicit load and
	test if lock is free before exchange,  if new macro
	SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG macro is set to one.
	* nptl/pthread_spin_unlock.c (pthread_spin_unlock):
	Use atomic_store_release.
	* nptl/pthread_spin_parameters.h: New File.
	* sysdeps/aarch64/nptl/pthread_spin_lock.c: Delete File.
	* sysdeps/aarch64/nptl/pthread_spin_parameters.h: New File.
	* sysdeps/arm/nptl/pthread_spin_lock.c: Delete File.
	* sysdeps/arm/nptl/pthread_spin_parameters.h: New File.
	* sysdeps/hppa/nptl/pthread_spin_lock.c: Delete File.
	* sysdeps/hppa/nptl/pthread_spin_parameters.h: New File.
	* sysdeps/m68k/nptl/pthread_spin_lock.c: Delete File.
	* sysdeps/m68k/nptl/pthread_spin_parameters.h: New File.
	* sysdeps/microblaze/nptl/pthread_spin_lock.c: Delete File.
	* sysdeps/microblaze/nptl/pthread_spin_parameters.h: New File.
	* sysdeps/mips/nptl/pthread_spin_lock.c: Delete File.
	* sysdeps/mips/nptl/pthread_spin_parameters.h: New File.
	* sysdeps/nios2/nptl/pthread_spin_lock.c: Delete File.
	* sysdeps/nios2/nptl/pthread_spin_parameters.h: New File.

Comments

Torvald Riegel Feb. 18, 2017, 4:57 p.m. UTC | #1
On Wed, 2017-02-15 at 10:35 +0100, Stefan Liebler wrote:
> On 02/13/2017 09:29 PM, Torvald Riegel wrote:
> > Thanks for working on this.  Detailed comments below.
> >
> > Generally, I think we need to keep working on optimizing this (this can
> > happen in follow-up patches).  For example, we should have
> > microbenchmarks for the exchange vs. CAS choice.
> >
> > Also, some of the tuning knobs such as
> > SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG apply to atomics in general and
> > not just the spinlock.  I'd prefer if these where in a state in which we
> > could add them as property that's part of the atomics interface.
> >
> > On Wed, 2017-02-08 at 15:49 +0100, Stefan Liebler wrote:
> >> diff --git a/include/atomic.h b/include/atomic.h
> >> index 7f32640..770db4a 100644
> >> --- a/include/atomic.h
> >>
> >> +++ b/include/atomic.h
> >>
> >> @@ -54,7 +54,7 @@
> >>     and following args.  */
> >>  #define __atomic_val_bysize(pre, post, mem, ...)			      \
> >>    ({									      \
> >> -    __typeof (*mem) __atg1_result;					      \
> >>
> >> +    __typeof ((__typeof (*(mem))) *(mem)) __atg1_result;		      \
> >>
> >>      if (sizeof (*mem) == 1)						      \
> >>        __atg1_result = pre##_8_##post (mem, __VA_ARGS__);		      \
> >>      else if (sizeof (*mem) == 2)					      \
> >> @@ -162,9 +162,9 @@
> >>  /* Store NEWVALUE in *MEM and return the old value.  */
> >>  #ifndef atomic_exchange_acq
> >>  # define atomic_exchange_acq(mem, newvalue) \
> >> -  ({ __typeof (*(mem)) __atg5_oldval;					      \
> >>
> >> +  ({ __typeof ((__typeof (*(mem))) *(mem)) __atg5_oldval;		      \
> >>
> >>       __typeof (mem) __atg5_memp = (mem);				      \
> >> -     __typeof (*(mem)) __atg5_value = (newvalue);			      \
> >>
> >> +     __typeof ((__typeof (*(mem))) *(mem)) __atg5_value = (newvalue);	      \
> >>
> >>  									      \
> >>       do									      \
> >>         __atg5_oldval = *__atg5_memp;					      \
> >> @@ -668,7 +668,7 @@ void __atomic_link_error (void);
> >>
> >>  # ifndef atomic_load_relaxed
> >>  #  define atomic_load_relaxed(mem) \
> >> -   ({ __typeof (*(mem)) __atg100_val;					      \
> >>
> >> +   ({ __typeof ((__typeof (*(mem))) *(mem)) __atg100_val;		      \
> >>
> >>     __asm ("" : "=r" (__atg100_val) : "0" (*(mem)));			      \
> >>     __atg100_val; })
> >>  # endif
> >
> > You could keep these changes, but it's a bit odd because you only apply
> > them for the functions you needed them for.  I think it would be better
> > to just remove the volatile qualification in the caller (ie, cast lock
> > to nonvolatile in pthread_spin_lock etc.
> >
> Yes, I've only applied them for the functions needed in spinlock-code.
> Removing volatile from type pthread_spinlock_t is no option and
> casting the volatile pointer to a non-volatile pointer is undefined.
> See comment from Florian:
> On 12/16/2016 09:12 PM, Florian Weimer wrote:
> > That's undefined:
> >
> > “If an attempt is made to refer to an object defined with a
> > volatile-qualified type through use of an lvalue with
> > non-volatile-qualified type, the behavior is undefined.”
> >
> > But we cannot drop the volatile qualifier from the definition of
> > pthread_spinlock_t because it would change the C++ mangling of
> > pthread_spinlock_t * and similar types.

Generally, I wouldn't agree with Florian's comment.  However, all we are
interested in is the storage behind the volatile-qualified type.  Users
aren't allowed the object through other means than the pthread_spin*
functions, so if we cast everywhere, we'll never have any
volatile-qualified accesses.  I believe none of the architectures we
support makes weaker requirements on alignment for volatile-qualified
than for non-volatile-qualified types, so I can't see any problem in
practice with the cast.


> >>
> >> +  if (__glibc_likely (atomic_exchange_acquire (lock, 1) == 0))
> >>
> >>      return 0;
> >>
> >> +  int val;
> >>
> >>    do
> >>      {
> >>        /* The lock is contended and we need to wait.  Going straight back
> >> @@ -50,20 +53,39 @@ pthread_spin_lock (pthread_spinlock_t *lock)
> >>  	 On the other hand, we do want to update memory state on the local core
> >>  	 once in a while to avoid spinning indefinitely until some event that
> >>  	 will happen to update local memory as a side-effect.  */
> >> -      if (SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0)
> >>
> >> +
> >>
> >> +#if SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0
> >>
> >> +      /* Use at most SPIN_LOCK_READS_BETWEEN_CMPXCHG plain reads between the
> >>
> >> +	 atomic compare and exchanges.  */
> >>
> Also changed this comment to:
> /* Use at most SPIN_LOCK_READS_BETWEEN_CMPXCHG relaxed MO reads between
>     the atomic compare and exchanges.  */

Thanks.

> > A while ago we tried hard to remove all code that would fail silently
> > when a macro had a typo in the name, for example.  We still have a few
> > of them left (e.g., in the atomics), but I think this here doesn't
> > warrant an exception.
> >
> Okay. You're right.
> 
> In comment of patch 2/2, you've mentioned a header where an architecture
> shall define those parameters.
> Thus I've added the file nptl/pthread_spin_parameters.h.

I think the stub version should be in sysdeps/ but the wiki is missing
this information (default ENOTSUP location):
https://sourceware.org/glibc/wiki/Style_and_Conventions#Proper_sysdeps_Location

I think we should just get rid of SPIN_LOCK_READS_BETWEEN_CMPXCHG, and
make some choice for SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG.  There is
no technical reason for throwing in a CAS every now and then, and so far
we have no evidence that it can improve performance (if that would be
the case, we'd need to think harder about that, because we have
spin-waiting loops elsewhere that don't want to modify the value after
waiting for a change of the value).

With that applied you don't have to solve the header problem in this
patch.

I'll write a separate email with suggestions about how to refactor the
spinlock code project-wide.  Also, some more comments on the tuning
parameters below.

I'm still a bit undecided about how to deal with other arch's
pthread_spin_lock.c files that just set SPIN_LOCK_READS_BETWEEN_CMPXCHG
and then include the generic pthread_spin_lock.c.  Maybe it's best if we
just remove them in this patch of yours.

> >>
> >> +#if SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG == 1
> >>
> >> +  /* Load and test the spinlock and only try to lock the spinlock if it is
> >>
> >> +     free.  */
> >>
> >> +  int val = atomic_load_relaxed (lock);
> >>
> >> +  if (__glibc_likely (val == 0 && atomic_exchange_acquire (lock, 1) == 0))
> >
> > I think that's not quite the same as a choice between CAS and exchange.
> Yes. You are right.
> > Doing a load first could be helpful for *both* CAS and exchange.  OTOH,
> > if we assume that trylock will succeed most of the time, then the load
> > is unnecessary and might be more costly (eg, if it causes the state of
> > the cache line to change twice).
> >
> E.g. on s390, there exists no instruction which atomically exchanges the 
> value. Instead a CAS loop is used. The CAS instruction locks the 
> cache-line exclusively whether the value in memory equals the expected
> old-value or not. Therefore the value is loaded and compared before 
> using the CAS instruction.
> If no other CPU has accessed the lock-value, the load will cause
> the state of the cache line to exclusive.
> If the lock is not acquired, the subsequent CAS instruction does not
> need to change the state of the cache line.
> If another CPU has accessed the lock-value e.g. by acquiring the lock,
> the load will cause the state of the cache line either to read-only
> or exclusive. This depends on the other CPU - whether it has already 
> stored a new value or not.
> 
> As this behaviour depends on the architecture, the architecture has to
> decide whether it should load and test the lock-value before the 
> atomic-macro.

I agree that the there are architecture-specific properties of atomic
operations that have a significant effect on performance.  For s390, you
list the following points:
* atomic exchange (I suppose all atomic read-modify-write ops?) are
implemented through CAS.
* CAS always brings the cache line into an exclusive state.

(Is the second point correct? I'm not quite sure I understood you
correctly: for example, you write that a load move a cache line to an
exclusive state, which seems odd).
 
These properties are specific to the architecture, but they are not
specific to the synchronization code (eg, to spinlocks).  Thus, I think
such settings should be in the atomics headers (i.e., in
atomic-machine.h).
This should probably be a separate patch.  I would propose the following
macros (both are bool):
/* Nonzero iff all atomic read-modify-write operations (e.g., atomic
exchange) are implemented using a CAS loop.  */
#define ATOMIC_RMW_USES_CAS 1
/* Nonzero iff CAS always assumes it will store, and thus has cache
performance effects similar to a store (e.g., it always puts the
respective cacheline into an exclusive state, even if the comparison
against the expected value fails).  */
ATOMIC_CAS_ALWAYS_PREPARES_FOR_STORE 1

I'm not sure whether there are architectures for which the second macro
would not be true.  It would be good to investigate this, maybe we don't
need to add this at all.



For the spin lock specifically, we have the following possibilities:

1) If we assume that trylock will most likely succeed in practice:
* We just do an exchange.  The properties above don't matter.

2) If we want to bias towards cases where trylock succeeds, but don't
rule out contention:
* If exchange not a CAS loop, and exchange is faster than CAS, do an
exchange.
* If exchange is a CAS loop, use a weak CAS and not an exchange so we
bail out after the first failed attempt to change the state.

3) If we expect contention to be likely:
* If CAS always brings the cache line into an exclusive state, then load
first.  Then do 2).

Do we have consensus yet on whether we assume 2 or 3 (I don't think 1
buys us anything over 2)?


> >> diff --git a/nptl/pthread_spin_unlock.c b/nptl/pthread_spin_unlock.c
> >> index 5fd73e5..f83b696 100644
> >> --- a/nptl/pthread_spin_unlock.c
> >>
> >> +++ b/nptl/pthread_spin_unlock.c
> >>
> >> @@ -23,7 +23,9 @@
> >>  int
> >>  pthread_spin_unlock (pthread_spinlock_t *lock)
> >>  {
> >> -  atomic_full_barrier ();
> >>
> >> -  *lock = 0;
> >>
> >> +  /* The atomic_store_release synchronizes-with the atomic_exchange_acquire
> >>
> >> +     or atomic_compare_exchange_weak_acquire in pthread_spin_lock /
> >>
> >> +     pthread_spin_trylock.  */
> >>
> >> +  atomic_store_release (lock, 0);
> >>
> >>    return 0;
> >>  }
> >
> > I agree with this change.  However, depending on how one interprets
> > POSIX' memory model, one may expect lock releases to be sequentially
> > consistent.  Nonetheless, IMO, glibc should use only release MO.
> >
> > But we need to announce this change.  Some of us have been considering
> > an additional section in the manual were we specify where we deviate
> > from POSIX; this change might be the first we're listing there (though
> > to be fair, this is a deviation only on some architectures because on
> > others such as powerpc I think, we've been using release MO forever).
> >
> >
> As not all architectures use the generic spinlock implementation, what 
> about a NEWS entry like:
> 
> * The new generic spinlock implementation uses C11 like atomics.
>    The pthread_spin_unlock implementation is now using release
>    memory order instead of sequentially consistent memory order.

That's a good start, but I think we need to be more specific.  We also
don't need to say that we use C11-like atomics because that's an
implementation detail.

I'd add something like this instead:

The synchronization that pthread_spin_unlock performs has been changed
to now be equivalent to a C11 atomic store with release memory order to
the spin lock's memory location.  This ensures correct synchronization
for the spin lock's operations and critical sections protected by a spin
lock.  Previously, several (but not all) architectures used stronger
synchronization (e.g., containing what is often called a full barrier).
This change can improve performance, but may affect odd fringe uses of
spin locks that depend on the previous behavior (e.g., using spin locks
as atomic variables to try to implement Dekker's mutual exclusion
algorithm).

This should highlight the potential change for the weird (ab)uses of
spin locks but also makes it clear that this won't affect correctness of
all the common code.
Florian Weimer Feb. 19, 2017, 9:20 a.m. UTC | #2
* Torvald Riegel:

>> On 12/16/2016 09:12 PM, Florian Weimer wrote:
>> > That's undefined:
>> >
>> > “If an attempt is made to refer to an object defined with a
>> > volatile-qualified type through use of an lvalue with
>> > non-volatile-qualified type, the behavior is undefined.”
>> >
>> > But we cannot drop the volatile qualifier from the definition of
>> > pthread_spinlock_t because it would change the C++ mangling of
>> > pthread_spinlock_t * and similar types.
>
> Generally, I wouldn't agree with Florian's comment.  However, all we are
> interested in is the storage behind the volatile-qualified type.  Users
> aren't allowed the object through other means than the pthread_spin*
> functions, so if we cast everywhere, we'll never have any
> volatile-qualified accesses.

The spinlock is defined with the volatile qualifier.  This means that
accesses without the qualifier are undefined.

> I believe none of the architectures we
> support makes weaker requirements on alignment for volatile-qualified
> than for non-volatile-qualified types, so I can't see any problem in
> practice with the cast.

We also need separate compilation or some other optimization barrier.

If GCC can prove that code accesses a volatile object in this matter,
it can assume that the code never executes and eliminate it (and its
surrounding code).

We could talk to the GCC folks and ask for a suitable GCC extension.
Like you said, there shouldn't be any ABI concerns which would make
this difficult.
Stefan Liebler Feb. 20, 2017, 12:15 p.m. UTC | #3
On 02/18/2017 05:57 PM, Torvald Riegel wrote:
> On Wed, 2017-02-15 at 10:35 +0100, Stefan Liebler wrote:
>> On 02/13/2017 09:29 PM, Torvald Riegel wrote:
>>> Thanks for working on this.  Detailed comments below.
>>>
>>> Generally, I think we need to keep working on optimizing this (this can
>>> happen in follow-up patches).  For example, we should have
>>> microbenchmarks for the exchange vs. CAS choice.
>>>
>>> Also, some of the tuning knobs such as
>>> SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG apply to atomics in general and
>>> not just the spinlock.  I'd prefer if these where in a state in which we
>>> could add them as property that's part of the atomics interface.
>>>
>>> On Wed, 2017-02-08 at 15:49 +0100, Stefan Liebler wrote:
>>>> diff --git a/include/atomic.h b/include/atomic.h
>>>> index 7f32640..770db4a 100644
>>>> --- a/include/atomic.h
>>>>
>>>> +++ b/include/atomic.h
>>>>
>>>> @@ -54,7 +54,7 @@
>>>>     and following args.  */
>>>>  #define __atomic_val_bysize(pre, post, mem, ...)			      \
>>>>    ({									      \
>>>> -    __typeof (*mem) __atg1_result;					      \
>>>>
>>>> +    __typeof ((__typeof (*(mem))) *(mem)) __atg1_result;		      \
>>>>
>>>>      if (sizeof (*mem) == 1)						      \
>>>>        __atg1_result = pre##_8_##post (mem, __VA_ARGS__);		      \
>>>>      else if (sizeof (*mem) == 2)					      \
>>>> @@ -162,9 +162,9 @@
>>>>  /* Store NEWVALUE in *MEM and return the old value.  */
>>>>  #ifndef atomic_exchange_acq
>>>>  # define atomic_exchange_acq(mem, newvalue) \
>>>> -  ({ __typeof (*(mem)) __atg5_oldval;					      \
>>>>
>>>> +  ({ __typeof ((__typeof (*(mem))) *(mem)) __atg5_oldval;		      \
>>>>
>>>>       __typeof (mem) __atg5_memp = (mem);				      \
>>>> -     __typeof (*(mem)) __atg5_value = (newvalue);			      \
>>>>
>>>> +     __typeof ((__typeof (*(mem))) *(mem)) __atg5_value = (newvalue);	      \
>>>>
>>>>  									      \
>>>>       do									      \
>>>>         __atg5_oldval = *__atg5_memp;					      \
>>>> @@ -668,7 +668,7 @@ void __atomic_link_error (void);
>>>>
>>>>  # ifndef atomic_load_relaxed
>>>>  #  define atomic_load_relaxed(mem) \
>>>> -   ({ __typeof (*(mem)) __atg100_val;					      \
>>>>
>>>> +   ({ __typeof ((__typeof (*(mem))) *(mem)) __atg100_val;		      \
>>>>
>>>>     __asm ("" : "=r" (__atg100_val) : "0" (*(mem)));			      \
>>>>     __atg100_val; })
>>>>  # endif
>>>
>>> You could keep these changes, but it's a bit odd because you only apply
>>> them for the functions you needed them for.  I think it would be better
>>> to just remove the volatile qualification in the caller (ie, cast lock
>>> to nonvolatile in pthread_spin_lock etc.
>>>
>> Yes, I've only applied them for the functions needed in spinlock-code.
>> Removing volatile from type pthread_spinlock_t is no option and
>> casting the volatile pointer to a non-volatile pointer is undefined.
>> See comment from Florian:
>> On 12/16/2016 09:12 PM, Florian Weimer wrote:
>>> That's undefined:
>>>
>>> “If an attempt is made to refer to an object defined with a
>>> volatile-qualified type through use of an lvalue with
>>> non-volatile-qualified type, the behavior is undefined.”
>>>
>>> But we cannot drop the volatile qualifier from the definition of
>>> pthread_spinlock_t because it would change the C++ mangling of
>>> pthread_spinlock_t * and similar types.
>
> Generally, I wouldn't agree with Florian's comment.  However, all we are
> interested in is the storage behind the volatile-qualified type.  Users
> aren't allowed the object through other means than the pthread_spin*
> functions, so if we cast everywhere, we'll never have any
> volatile-qualified accesses.  I believe none of the architectures we
> support makes weaker requirements on alignment for volatile-qualified
> than for non-volatile-qualified types, so I can't see any problem in
> practice with the cast.
>
>
>>>>
>>>> +  if (__glibc_likely (atomic_exchange_acquire (lock, 1) == 0))
>>>>
>>>>      return 0;
>>>>
>>>> +  int val;
>>>>
>>>>    do
>>>>      {
>>>>        /* The lock is contended and we need to wait.  Going straight back
>>>> @@ -50,20 +53,39 @@ pthread_spin_lock (pthread_spinlock_t *lock)
>>>>  	 On the other hand, we do want to update memory state on the local core
>>>>  	 once in a while to avoid spinning indefinitely until some event that
>>>>  	 will happen to update local memory as a side-effect.  */
>>>> -      if (SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0)
>>>>
>>>> +
>>>>
>>>> +#if SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0
>>>>
>>>> +      /* Use at most SPIN_LOCK_READS_BETWEEN_CMPXCHG plain reads between the
>>>>
>>>> +	 atomic compare and exchanges.  */
>>>>
>> Also changed this comment to:
>> /* Use at most SPIN_LOCK_READS_BETWEEN_CMPXCHG relaxed MO reads between
>>     the atomic compare and exchanges.  */
>
> Thanks.
>
>>> A while ago we tried hard to remove all code that would fail silently
>>> when a macro had a typo in the name, for example.  We still have a few
>>> of them left (e.g., in the atomics), but I think this here doesn't
>>> warrant an exception.
>>>
>> Okay. You're right.
>>
>> In comment of patch 2/2, you've mentioned a header where an architecture
>> shall define those parameters.
>> Thus I've added the file nptl/pthread_spin_parameters.h.
>
> I think the stub version should be in sysdeps/ but the wiki is missing
> this information (default ENOTSUP location):
> https://sourceware.org/glibc/wiki/Style_and_Conventions#Proper_sysdeps_Location
In case we need a new header, shall we move it to sysdeps/nptl/ ?

>
> I think we should just get rid of SPIN_LOCK_READS_BETWEEN_CMPXCHG, and
> make some choice for SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG.  There is
> no technical reason for throwing in a CAS every now and then, and so far
> we have no evidence that it can improve performance (if that would be
> the case, we'd need to think harder about that, because we have
> spin-waiting loops elsewhere that don't want to modify the value after
> waiting for a change of the value).
Okay. For s390 we don't need a CAS every now and then.

>
> With that applied you don't have to solve the header problem in this
> patch.
>
> I'll write a separate email with suggestions about how to refactor the
> spinlock code project-wide.  Also, some more comments on the tuning
> parameters below.
>
> I'm still a bit undecided about how to deal with other arch's
> pthread_spin_lock.c files that just set SPIN_LOCK_READS_BETWEEN_CMPXCHG
> and then include the generic pthread_spin_lock.c.  Maybe it's best if we
> just remove them in this patch of yours.
>
I think the archs currently using the generic implementation have just 
copied the default value to get rid of the warning "machine-dependent 
file should define SPIN_LOCK_READS_BETWEEN_CMPXCHG". But this is only an 
assumption.
In general removing those "wrapper"-pthread_spin_lock.c files and using 
information from a header like the proposed pthread_spin_parameters.h or 
atomic-machine.h is a good approach.

>>>>
>>>> +#if SPIN_TRYLOCK_USE_CMPXCHG_INSTEAD_OF_XCHG == 1
>>>>
>>>> +  /* Load and test the spinlock and only try to lock the spinlock if it is
>>>>
>>>> +     free.  */
>>>>
>>>> +  int val = atomic_load_relaxed (lock);
>>>>
>>>> +  if (__glibc_likely (val == 0 && atomic_exchange_acquire (lock, 1) == 0))
>>>
>>> I think that's not quite the same as a choice between CAS and exchange.
>> Yes. You are right.
>>> Doing a load first could be helpful for *both* CAS and exchange.  OTOH,
>>> if we assume that trylock will succeed most of the time, then the load
>>> is unnecessary and might be more costly (eg, if it causes the state of
>>> the cache line to change twice).
>>>
>> E.g. on s390, there exists no instruction which atomically exchanges the
>> value. Instead a CAS loop is used. The CAS instruction locks the
>> cache-line exclusively whether the value in memory equals the expected
>> old-value or not. Therefore the value is loaded and compared before
>> using the CAS instruction.
>> If no other CPU has accessed the lock-value, the load will cause
>> the state of the cache line to exclusive.
>> If the lock is not acquired, the subsequent CAS instruction does not
>> need to change the state of the cache line.
>> If another CPU has accessed the lock-value e.g. by acquiring the lock,
>> the load will cause the state of the cache line either to read-only
>> or exclusive. This depends on the other CPU - whether it has already
>> stored a new value or not.
>>
>> As this behaviour depends on the architecture, the architecture has to
>> decide whether it should load and test the lock-value before the
>> atomic-macro.
>
> I agree that the there are architecture-specific properties of atomic
> operations that have a significant effect on performance.  For s390, you
> list the following points:
> * atomic exchange (I suppose all atomic read-modify-write ops?) are
> implemented through CAS.
atomic exchange is implemented by a CAS loop due to lack of an exchange 
instruction. For exchanging to a "0", s390 can use the load-and-and 
instruction instead of a CAS loop (See my atomic-machine.h patch; For 
gcc, we plan to emit such a load-and-and instruction for builtin 
__atomic_exchange_n in future;). This also saves one register usage 
compared to the CAS loop.
Exchanging to "0" is e.g. used for lll_unlock macro or in 
malloc_consolidate.

Starting with z196 zarch CPUs, the following instructions which are used 
by the appropriate __atomic_fetch_xyz builtins instead of a CAS loop:
load-and-add, load-and-and, load-and-exclusive-or, load-and-or.
As information:
I will update my atomic-machine.h patch to use at least some of the C11 
atomic builtins or all depending on gcc version.
As additional information:
E.g. RHEL 7 / SLES 12 are using z196 as architecture baseline level.
A 64bit s390x glibc build always use zarch instructions.
A 31bit s390 glibc build does not use zarch instructions by default, but 
somebody can build glibc with gcc -mzarch option.
The latter means, that a CAS loop is used for a default 31bit s390 build.

> * CAS always brings the cache line into an exclusive state.
Yes that's true.

>
> (Is the second point correct? I'm not quite sure I understood you
> correctly: for example, you write that a load move a cache line to an
> exclusive state, which seems odd).
Not in all cases, but in the case if no other CPU accesses this cache 
line. Otherwise it is read-only.

>
> These properties are specific to the architecture, but they are not
> specific to the synchronization code (eg, to spinlocks).  Thus, I think
> such settings should be in the atomics headers (i.e., in
> atomic-machine.h).
> This should probably be a separate patch.  I would propose the following
> macros (both are bool):
> /* Nonzero iff all atomic read-modify-write operations (e.g., atomic
> exchange) are implemented using a CAS loop.  */
> #define ATOMIC_RMW_USES_CAS 1
Is one macro enough to describe all read-modify-write operations in 
include/atomic.h?
Please also see my comment above.

> /* Nonzero iff CAS always assumes it will store, and thus has cache
> performance effects similar to a store (e.g., it always puts the
> respective cacheline into an exclusive state, even if the comparison
> against the expected value fails).  */
> ATOMIC_CAS_ALWAYS_PREPARES_FOR_STORE 1
>
> I'm not sure whether there are architectures for which the second macro
> would not be true.  It would be good to investigate this, maybe we don't
> need to add this at all.
>
We plan that in future gcc will emit e.g. a load-and-test instruction in 
front of the CAS instruction if the old-value is a constant zero.
>
>
> For the spin lock specifically, we have the following possibilities:
>
> 1) If we assume that trylock will most likely succeed in practice:
> * We just do an exchange.  The properties above don't matter.
>
> 2) If we want to bias towards cases where trylock succeeds, but don't
> rule out contention:
> * If exchange not a CAS loop, and exchange is faster than CAS, do an
> exchange.
> * If exchange is a CAS loop, use a weak CAS and not an exchange so we
> bail out after the first failed attempt to change the state.
>
> 3) If we expect contention to be likely:
> * If CAS always brings the cache line into an exclusive state, then load
> first.  Then do 2).
>
> Do we have consensus yet on whether we assume 2 or 3 (I don't think 1
> buys us anything over 2)?
>
Yes. Sounds good.

>
>>>> diff --git a/nptl/pthread_spin_unlock.c b/nptl/pthread_spin_unlock.c
>>>> index 5fd73e5..f83b696 100644
>>>> --- a/nptl/pthread_spin_unlock.c
>>>>
>>>> +++ b/nptl/pthread_spin_unlock.c
>>>>
>>>> @@ -23,7 +23,9 @@
>>>>  int
>>>>  pthread_spin_unlock (pthread_spinlock_t *lock)
>>>>  {
>>>> -  atomic_full_barrier ();
>>>>
>>>> -  *lock = 0;
>>>>
>>>> +  /* The atomic_store_release synchronizes-with the atomic_exchange_acquire
>>>>
>>>> +     or atomic_compare_exchange_weak_acquire in pthread_spin_lock /
>>>>
>>>> +     pthread_spin_trylock.  */
>>>>
>>>> +  atomic_store_release (lock, 0);
>>>>
>>>>    return 0;
>>>>  }
>>>
>>> I agree with this change.  However, depending on how one interprets
>>> POSIX' memory model, one may expect lock releases to be sequentially
>>> consistent.  Nonetheless, IMO, glibc should use only release MO.
>>>
>>> But we need to announce this change.  Some of us have been considering
>>> an additional section in the manual were we specify where we deviate
>>> from POSIX; this change might be the first we're listing there (though
>>> to be fair, this is a deviation only on some architectures because on
>>> others such as powerpc I think, we've been using release MO forever).
>>>
>>>
>> As not all architectures use the generic spinlock implementation, what
>> about a NEWS entry like:
>>
>> * The new generic spinlock implementation uses C11 like atomics.
>>    The pthread_spin_unlock implementation is now using release
>>    memory order instead of sequentially consistent memory order.
>
> That's a good start, but I think we need to be more specific.  We also
> don't need to say that we use C11-like atomics because that's an
> implementation detail.
>
> I'd add something like this instead:
>
> The synchronization that pthread_spin_unlock performs has been changed
> to now be equivalent to a C11 atomic store with release memory order to
> the spin lock's memory location.  This ensures correct synchronization
> for the spin lock's operations and critical sections protected by a spin
> lock.  Previously, several (but not all) architectures used stronger
> synchronization (e.g., containing what is often called a full barrier).
> This change can improve performance, but may affect odd fringe uses of
> spin locks that depend on the previous behavior (e.g., using spin locks
> as atomic variables to try to implement Dekker's mutual exclusion
> algorithm).
>
> This should highlight the potential change for the weird (ab)uses of
> spin locks but also makes it clear that this won't affect correctness of
> all the common code.
>
Okay. The next patch-iteration will use the text above.
Torvald Riegel Feb. 20, 2017, 1:11 p.m. UTC | #4
On Sun, 2017-02-19 at 10:20 +0100, Florian Weimer wrote:
> * Torvald Riegel:
> 
> >> On 12/16/2016 09:12 PM, Florian Weimer wrote:
> >> > That's undefined:
> >> >
> >> > “If an attempt is made to refer to an object defined with a
> >> > volatile-qualified type through use of an lvalue with
> >> > non-volatile-qualified type, the behavior is undefined.”
> >> >
> >> > But we cannot drop the volatile qualifier from the definition of
> >> > pthread_spinlock_t because it would change the C++ mangling of
> >> > pthread_spinlock_t * and similar types.
> >
> > Generally, I wouldn't agree with Florian's comment.  However, all we are
> > interested in is the storage behind the volatile-qualified type.  Users
> > aren't allowed the object through other means than the pthread_spin*
> > functions, so if we cast everywhere, we'll never have any
> > volatile-qualified accesses.
> 
> The spinlock is defined with the volatile qualifier.  This means that
> accesses without the qualifier are undefined.

The footnote for 6.7.3p6 (footnote 133, N1570) reads:
This applies to those objects that behave as if they were defined with
qualified types, even if they are
never actually defined as objects in the program (such as an object at a
memory-mapped input/output
address).

I don't remember whether footnotes are normative, but this doesn't apply
in our case.

> > I believe none of the architectures we
> > support makes weaker requirements on alignment for volatile-qualified
> > than for non-volatile-qualified types, so I can't see any problem in
> > practice with the cast.
> 
> We also need separate compilation or some other optimization barrier.

Also consider 2.14.2 in
https://www.cl.cam.ac.uk/~pes20/cerberus/notes30-full.pdf

This states that one can cast between a union and the pointers to
individual parts of a union.  If the spinlock's underlying type and the
volatile-qualified type both have the same size+alignment, then the
union will have the same size and alignment too.
In our virtual union, we only ever use the non-volatile member (users
are not allowed to acccess spinlocks other than through pthread_spin_*
functions, which don't use volatile-qualified accesses).  But we pass
the pointer to the volatile member around as handle to the spinlock.

Thus, I'm not concerned about the cast from volatile-qualified to
non-volatile-qualified in this particular case.

Maybe its best to just change pthread_spinlock_t from volatile int to
int.  The generic spinlock uses only atomic ops with Stefan's changes,
so that's okay for at least the archs that use the generic code; for all
others, we could either keep them as is or change it and confirm that
the custom code they use doesn't rely on the volatile.
Torvald Riegel Feb. 20, 2017, 1:51 p.m. UTC | #5
On Mon, 2017-02-20 at 13:15 +0100, Stefan Liebler wrote:
> >>> A while ago we tried hard to remove all code that would fail silently
> >>> when a macro had a typo in the name, for example.  We still have a few
> >>> of them left (e.g., in the atomics), but I think this here doesn't
> >>> warrant an exception.
> >>>
> >> Okay. You're right.
> >>
> >> In comment of patch 2/2, you've mentioned a header where an architecture
> >> shall define those parameters.
> >> Thus I've added the file nptl/pthread_spin_parameters.h.
> >
> > I think the stub version should be in sysdeps/ but the wiki is missing
> > this information (default ENOTSUP location):
> > https://sourceware.org/glibc/wiki/Style_and_Conventions#Proper_sysdeps_Location
> In case we need a new header, shall we move it to sysdeps/nptl/ ?

I would guess that this would be the right place for a stub / generic
variant of such a header, but I'm not quite sure.

> >
> > I'm still a bit undecided about how to deal with other arch's
> > pthread_spin_lock.c files that just set SPIN_LOCK_READS_BETWEEN_CMPXCHG
> > and then include the generic pthread_spin_lock.c.  Maybe it's best if we
> > just remove them in this patch of yours.
> >
> I think the archs currently using the generic implementation have just 
> copied the default value to get rid of the warning "machine-dependent 
> file should define SPIN_LOCK_READS_BETWEEN_CMPXCHG". But this is only an 
> assumption.
> In general removing those "wrapper"-pthread_spin_lock.c files and using 
> information from a header like the proposed pthread_spin_parameters.h or 
> atomic-machine.h is a good approach.

Okay.  So let's do that.

> > I agree that the there are architecture-specific properties of atomic
> > operations that have a significant effect on performance.  For s390, you
> > list the following points:
> > * atomic exchange (I suppose all atomic read-modify-write ops?) are
> > implemented through CAS.
> atomic exchange is implemented by a CAS loop due to lack of an exchange 
> instruction. For exchanging to a "0", s390 can use the load-and-and 
> instruction instead of a CAS loop (See my atomic-machine.h patch; For 
> gcc, we plan to emit such a load-and-and instruction for builtin 
> __atomic_exchange_n in future;). This also saves one register usage 
> compared to the CAS loop.
> Exchanging to "0" is e.g. used for lll_unlock macro or in 
> malloc_consolidate.

I guess this may then be yet another property atomic-machine.h could
expose: Whether an atomic fetch-and-and exists and is not implemented
throough a CAS loop.  Something like lll_unlock would then do an
exchange or fetch-and-and, and if that fails, a CAS loop.

> Starting with z196 zarch CPUs, the following instructions which are used 
> by the appropriate __atomic_fetch_xyz builtins instead of a CAS loop:
> load-and-add, load-and-and, load-and-exclusive-or, load-and-or.
> As information:
> I will update my atomic-machine.h patch to use at least some of the C11 
> atomic builtins or all depending on gcc version.

Thanks.

> > These properties are specific to the architecture, but they are not
> > specific to the synchronization code (eg, to spinlocks).  Thus, I think
> > such settings should be in the atomics headers (i.e., in
> > atomic-machine.h).
> > This should probably be a separate patch.  I would propose the following
> > macros (both are bool):
> > /* Nonzero iff all atomic read-modify-write operations (e.g., atomic
> > exchange) are implemented using a CAS loop.  */
> > #define ATOMIC_RMW_USES_CAS 1
> Is one macro enough to describe all read-modify-write operations in 
> include/atomic.h?
> Please also see my comment above.

Yes, it may not be enough (e.g., you say that s390 may have fetch_and
but not an exchange, but other archs may just have an exchange but no
custom fetch_and).
So maybe we should add ATOMIC_EXCHANGE_USES_CAS and
ATOMIC_FETCH_AND_USES_CAS for now, and add further ones on demand?

> > /* Nonzero iff CAS always assumes it will store, and thus has cache
> > performance effects similar to a store (e.g., it always puts the
> > respective cacheline into an exclusive state, even if the comparison
> > against the expected value fails).  */
> > ATOMIC_CAS_ALWAYS_PREPARES_FOR_STORE 1
> >
> > I'm not sure whether there are architectures for which the second macro
> > would not be true.  It would be good to investigate this, maybe we don't
> > need to add this at all.
> >
> We plan that in future gcc will emit e.g. a load-and-test instruction in 
> front of the CAS instruction if the old-value is a constant zero.

That can be useful, but what I outlined would be about a more generic
case.  If you are going to solve this for your arch in gcc, you might
not need to address this in this patch.

> >
> >
> > For the spin lock specifically, we have the following possibilities:
> >
> > 1) If we assume that trylock will most likely succeed in practice:
> > * We just do an exchange.  The properties above don't matter.
> >
> > 2) If we want to bias towards cases where trylock succeeds, but don't
> > rule out contention:
> > * If exchange not a CAS loop, and exchange is faster than CAS, do an
> > exchange.
> > * If exchange is a CAS loop, use a weak CAS and not an exchange so we
> > bail out after the first failed attempt to change the state.
> >
> > 3) If we expect contention to be likely:
> > * If CAS always brings the cache line into an exclusive state, then load
> > first.  Then do 2).
> >
> > Do we have consensus yet on whether we assume 2 or 3 (I don't think 1
> > buys us anything over 2)?
> >
> Yes. Sounds good.

I read this as stating that you agree that 1) doesn't need to be
considered.  But we still to choose between 2) and 3)  :)

I'm not quite sure what to favor because some of the code out there that
uses trylock just uses it to prevent deadlock (e.g., when trying to
acquire multiple locks at once), whereas other code uses spin_trylock to
implement their own back-off and bounded spinning.
I lean towards assuming that lock acquisitons, including the former use
case for trylock, are supposed to succeed in the common case.  That is,
I would pick 2), but I have no data to back this up.

Either way, whatever we choose, we should document polish the cases 1-3
above and the reasoning behind our choice for one of them, and add it as
a comment to the spinlock code.
Florian Weimer Feb. 26, 2017, 7:55 a.m. UTC | #6
* Torvald Riegel:

> On Sun, 2017-02-19 at 10:20 +0100, Florian Weimer wrote:
>> * Torvald Riegel:
>> 
>> >> On 12/16/2016 09:12 PM, Florian Weimer wrote:
>> >> > That's undefined:
>> >> >
>> >> > “If an attempt is made to refer to an object defined with a
>> >> > volatile-qualified type through use of an lvalue with
>> >> > non-volatile-qualified type, the behavior is undefined.”
>> >> >
>> >> > But we cannot drop the volatile qualifier from the definition of
>> >> > pthread_spinlock_t because it would change the C++ mangling of
>> >> > pthread_spinlock_t * and similar types.
>> >
>> > Generally, I wouldn't agree with Florian's comment.  However, all we are
>> > interested in is the storage behind the volatile-qualified type.  Users
>> > aren't allowed the object through other means than the pthread_spin*
>> > functions, so if we cast everywhere, we'll never have any
>> > volatile-qualified accesses.
>> 
>> The spinlock is defined with the volatile qualifier.  This means that
>> accesses without the qualifier are undefined.
>
> The footnote for 6.7.3p6 (footnote 133, N1570) reads:
> This applies to those objects that behave as if they were defined with
> qualified types, even if they are
> never actually defined as objects in the program (such as an object at a
> memory-mapped input/output
> address).
>
> I don't remember whether footnotes are normative,

They are not.

> but this doesn't apply in our case.

I think it's a clarification intended to *extend* the scope of the
paragraph to objects not defined using C language elments.  It's not
intended to restrict this paragraph to such objects only.  The
footnote is not particularly meaningful anyway because it discusses
certain vendor extensions whose behavior is not described by the
standard.

(And on GNU, objects created by mmap or dlopen are not implicitly
volatile.)

>> > I believe none of the architectures we
>> > support makes weaker requirements on alignment for volatile-qualified
>> > than for non-volatile-qualified types, so I can't see any problem in
>> > practice with the cast.
>> 
>> We also need separate compilation or some other optimization barrier.
>
> Also consider 2.14.2 in
> https://www.cl.cam.ac.uk/~pes20/cerberus/notes30-full.pdf

Not sure how this applies here.  There's no volatile qualifier in
there.

> This states that one can cast between a union and the pointers to
> individual parts of a union.  If the spinlock's underlying type and the
> volatile-qualified type both have the same size+alignment, then the
> union will have the same size and alignment too.
> In our virtual union, we only ever use the non-volatile member (users
> are not allowed to acccess spinlocks other than through pthread_spin_*
> functions, which don't use volatile-qualified accesses).  But we pass
> the pointer to the volatile member around as handle to the spinlock.

We also need to cover the case when a spinlock is defined like this:

static pthread_spinlock_t lock;

And I don't see a way to get rid of the volatile there without a
compiler extension.

We cannot introduce an union here because …

> Maybe its best to just change pthread_spinlock_t from volatile int to
> int.

… like this, it would change the C++ name mangling of anything related
to pthread_spinlock_t.  It is defined as a typedef, so the mangling
uses the definition to refer to the type, not the name, according to
the language rules, where typedef does not create a new type, and
typedefs with the same definition can be used interchangeably.
Torvald Riegel Feb. 26, 2017, 8:05 p.m. UTC | #7
On Sun, 2017-02-26 at 08:55 +0100, Florian Weimer wrote:
> * Torvald Riegel:
> 
> > On Sun, 2017-02-19 at 10:20 +0100, Florian Weimer wrote:
> >> * Torvald Riegel:
> >> 
> >> >> On 12/16/2016 09:12 PM, Florian Weimer wrote:
> >> >> > That's undefined:
> >> >> >
> >> >> > “If an attempt is made to refer to an object defined with a
> >> >> > volatile-qualified type through use of an lvalue with
> >> >> > non-volatile-qualified type, the behavior is undefined.”
> >> >> >
> >> >> > But we cannot drop the volatile qualifier from the definition of
> >> >> > pthread_spinlock_t because it would change the C++ mangling of
> >> >> > pthread_spinlock_t * and similar types.
> >> >
> >> > Generally, I wouldn't agree with Florian's comment.  However, all we are
> >> > interested in is the storage behind the volatile-qualified type.  Users
> >> > aren't allowed the object through other means than the pthread_spin*
> >> > functions, so if we cast everywhere, we'll never have any
> >> > volatile-qualified accesses.
> >> 
> >> The spinlock is defined with the volatile qualifier.  This means that
> >> accesses without the qualifier are undefined.
> >
> > The footnote for 6.7.3p6 (footnote 133, N1570) reads:
> > This applies to those objects that behave as if they were defined with
> > qualified types, even if they are
> > never actually defined as objects in the program (such as an object at a
> > memory-mapped input/output
> > address).
> >
> > I don't remember whether footnotes are normative,
> 
> They are not.
> 
> > but this doesn't apply in our case.
> 
> I think it's a clarification intended to *extend* the scope of the
> paragraph to objects not defined using C language elments.

I don't read it that way, and I think it is intended to explain the
intention of this paragraph.

> It's not
> intended to restrict this paragraph to such objects only.  The
> footnote is not particularly meaningful anyway because it discusses
> certain vendor extensions whose behavior is not described by the
> standard.
> 
> (And on GNU, objects created by mmap or dlopen are not implicitly
> volatile.)
> 
> >> > I believe none of the architectures we
> >> > support makes weaker requirements on alignment for volatile-qualified
> >> > than for non-volatile-qualified types, so I can't see any problem in
> >> > practice with the cast.
> >> 
> >> We also need separate compilation or some other optimization barrier.
> >
> > Also consider 2.14.2 in
> > https://www.cl.cam.ac.uk/~pes20/cerberus/notes30-full.pdf
> 
> Not sure how this applies here.  There's no volatile qualifier in
> there.

But it makes a statement about pointers being interchangeable and, at
least as I read it, compatible.  So we can transform this into a
question about unions.

> > This states that one can cast between a union and the pointers to
> > individual parts of a union.  If the spinlock's underlying type and the
> > volatile-qualified type both have the same size+alignment, then the
> > union will have the same size and alignment too.
> > In our virtual union, we only ever use the non-volatile member (users
> > are not allowed to acccess spinlocks other than through pthread_spin_*
> > functions, which don't use volatile-qualified accesses).  But we pass
> > the pointer to the volatile member around as handle to the spinlock.
> 
> We also need to cover the case when a spinlock is defined like this:
> 
> static pthread_spinlock_t lock;
> 
> And I don't see a way to get rid of the volatile there without a
> compiler extension.
> 
> We cannot introduce an union here because …
> 
> > Maybe its best to just change pthread_spinlock_t from volatile int to
> > int.
> 
> … like this, it would change the C++ name mangling of anything related
> to pthread_spinlock_t.  It is defined as a typedef, so the mangling
> uses the definition to refer to the type, not the name, according to
> the language rules, where typedef does not create a new type, and
> typedefs with the same definition can be used interchangeably.

I'm not saying that we should change the definition to a union.  What
2.14.2 in the document cited above states is that the pointers to the
union and the individual parts are interchangeable.  So we can use a
pointer to a part (ie, non-volatile) interchangeably with the pointer to
the union that we use internally.
Florian Weimer Feb. 26, 2017, 8:29 p.m. UTC | #8
* Torvald Riegel:

>> … like this, it would change the C++ name mangling of anything related
>> to pthread_spinlock_t.  It is defined as a typedef, so the mangling
>> uses the definition to refer to the type, not the name, according to
>> the language rules, where typedef does not create a new type, and
>> typedefs with the same definition can be used interchangeably.
>
> I'm not saying that we should change the definition to a union.  What
> 2.14.2 in the document cited above states is that the pointers to the
> union and the individual parts are interchangeable.  So we can use a
> pointer to a part (ie, non-volatile) interchangeably with the pointer to
> the union that we use internally.

The relevant quote from that document (C memory object and value
semantics: the space of de facto and ISO standards) is:

| The standard says: 6.7.2.1p16 “The size of a union is
| sufficient to contain the largest of its members. The value of
| at most one of the members can be stored in a union object
| at any time. *A pointer to a union object, suitably converted,*
| *points to each of its members (or if a member is a bit-field,*
| *then to the unit in which it resides), and vice versa.*” (bold
| emphasis added).

So I think this is only valid if you actually start with a union
object.  A plain top-level definition of a volatile int is not a union
member, so this rule does not apply (in the “vice versa” part).

I think it would be much simpler to ask for a GCC extension which
would allow us to use non-volatile access on a volatile object in a
well-defined fashion.
Torvald Riegel Feb. 26, 2017, 8:35 p.m. UTC | #9
On Sun, 2017-02-26 at 21:29 +0100, Florian Weimer wrote:
> * Torvald Riegel:
> 
> >> … like this, it would change the C++ name mangling of anything related
> >> to pthread_spinlock_t.  It is defined as a typedef, so the mangling
> >> uses the definition to refer to the type, not the name, according to
> >> the language rules, where typedef does not create a new type, and
> >> typedefs with the same definition can be used interchangeably.
> >
> > I'm not saying that we should change the definition to a union.  What
> > 2.14.2 in the document cited above states is that the pointers to the
> > union and the individual parts are interchangeable.  So we can use a
> > pointer to a part (ie, non-volatile) interchangeably with the pointer to
> > the union that we use internally.
> 
> The relevant quote from that document (C memory object and value
> semantics: the space of de facto and ISO standards) is:
> 
> | The standard says: 6.7.2.1p16 “The size of a union is
> | sufficient to contain the largest of its members. The value of
> | at most one of the members can be stored in a union object
> | at any time. *A pointer to a union object, suitably converted,*
> | *points to each of its members (or if a member is a bit-field,*
> | *then to the unit in which it resides), and vice versa.*” (bold
> | emphasis added).
> 
> So I think this is only valid if you actually start with a union
> object.  A plain top-level definition of a volatile int is not a union
> member, so this rule does not apply (in the “vice versa” part).

Then we'll have to agree to disagree.  What do others think about this
question?

> I think it would be much simpler to ask for a GCC extension which
> would allow us to use non-volatile access on a volatile object in a
> well-defined fashion.

I guess such an "extension" could simply be GCC promising that casts
between volatile-qualified T and non-volatile-qualified T are okay if
the object is only accessed using one of the two.
Szabolcs Nagy Feb. 27, 2017, 5:57 p.m. UTC | #10
On 26/02/17 20:35, Torvald Riegel wrote:
> On Sun, 2017-02-26 at 21:29 +0100, Florian Weimer wrote:
>> * Torvald Riegel:
>>
>>>> … like this, it would change the C++ name mangling of anything related
>>>> to pthread_spinlock_t.  It is defined as a typedef, so the mangling
>>>> uses the definition to refer to the type, not the name, according to
>>>> the language rules, where typedef does not create a new type, and
>>>> typedefs with the same definition can be used interchangeably.
>>>
>>> I'm not saying that we should change the definition to a union.  What
>>> 2.14.2 in the document cited above states is that the pointers to the
>>> union and the individual parts are interchangeable.  So we can use a
>>> pointer to a part (ie, non-volatile) interchangeably with the pointer to
>>> the union that we use internally.
>>
>> The relevant quote from that document (C memory object and value
>> semantics: the space of de facto and ISO standards) is:
>>
>> | The standard says: 6.7.2.1p16 “The size of a union is
>> | sufficient to contain the largest of its members. The value of
>> | at most one of the members can be stored in a union object
>> | at any time. *A pointer to a union object, suitably converted,*
>> | *points to each of its members (or if a member is a bit-field,*
>> | *then to the unit in which it resides), and vice versa.*” (bold
>> | emphasis added).
>>
>> So I think this is only valid if you actually start with a union
>> object.  A plain top-level definition of a volatile int is not a union
>> member, so this rule does not apply (in the “vice versa” part).
> 
> Then we'll have to agree to disagree.  What do others think about this
> question?

i think the standard says that

volatile int x;
*(int*)&x;

is undefined and i think

int r = *p;

can be transformed by the compiler to

int r = *p;
*p = r;

if p has type int* (with a conflicting write the
original code would be undefined, without a
conflicting write the transformed code behaves
the same way on targets where the write is atomic),
but this is not valid if p is volatile int*.
Torvald Riegel Feb. 28, 2017, 7:15 a.m. UTC | #11
On Mon, 2017-02-27 at 17:57 +0000, Szabolcs Nagy wrote:
> On 26/02/17 20:35, Torvald Riegel wrote:
> > On Sun, 2017-02-26 at 21:29 +0100, Florian Weimer wrote:
> >> * Torvald Riegel:
> >>
> >>>> … like this, it would change the C++ name mangling of anything related
> >>>> to pthread_spinlock_t.  It is defined as a typedef, so the mangling
> >>>> uses the definition to refer to the type, not the name, according to
> >>>> the language rules, where typedef does not create a new type, and
> >>>> typedefs with the same definition can be used interchangeably.
> >>>
> >>> I'm not saying that we should change the definition to a union.  What
> >>> 2.14.2 in the document cited above states is that the pointers to the
> >>> union and the individual parts are interchangeable.  So we can use a
> >>> pointer to a part (ie, non-volatile) interchangeably with the pointer to
> >>> the union that we use internally.
> >>
> >> The relevant quote from that document (C memory object and value
> >> semantics: the space of de facto and ISO standards) is:
> >>
> >> | The standard says: 6.7.2.1p16 “The size of a union is
> >> | sufficient to contain the largest of its members. The value of
> >> | at most one of the members can be stored in a union object
> >> | at any time. *A pointer to a union object, suitably converted,*
> >> | *points to each of its members (or if a member is a bit-field,*
> >> | *then to the unit in which it resides), and vice versa.*” (bold
> >> | emphasis added).
> >>
> >> So I think this is only valid if you actually start with a union
> >> object.  A plain top-level definition of a volatile int is not a union
> >> member, so this rule does not apply (in the “vice versa” part).
> > 
> > Then we'll have to agree to disagree.  What do others think about this
> > question?
> 
> i think the standard says that
> 
> volatile int x;
> *(int*)&x;
> 
> is undefined and i think
> 
> int r = *p;

At least on the architectures that already use the __atomic builtins, we
never perform such an access -- everything goes through __atomic*.  On
other architectures, we already use plain, non-volatile accesses to
emulate real atomics (eg, see atomic_store_relaxed).  ISTM that we
wouldn't be making things worse in the sense that we already make
assumptions about what the compiler would do or would not (e.g., the
compiler does not store to *p again as in your third example).
Stefan Liebler March 14, 2017, 3:55 p.m. UTC | #12
On 02/28/2017 08:15 AM, Torvald Riegel wrote:
> On Mon, 2017-02-27 at 17:57 +0000, Szabolcs Nagy wrote:
>> On 26/02/17 20:35, Torvald Riegel wrote:
>>> On Sun, 2017-02-26 at 21:29 +0100, Florian Weimer wrote:
>>>> * Torvald Riegel:
>>>>
>>>>>> … like this, it would change the C++ name mangling of anything related
>>>>>> to pthread_spinlock_t.  It is defined as a typedef, so the mangling
>>>>>> uses the definition to refer to the type, not the name, according to
>>>>>> the language rules, where typedef does not create a new type, and
>>>>>> typedefs with the same definition can be used interchangeably.
>>>>>
>>>>> I'm not saying that we should change the definition to a union.  What
>>>>> 2.14.2 in the document cited above states is that the pointers to the
>>>>> union and the individual parts are interchangeable.  So we can use a
>>>>> pointer to a part (ie, non-volatile) interchangeably with the pointer to
>>>>> the union that we use internally.
>>>>
>>>> The relevant quote from that document (C memory object and value
>>>> semantics: the space of de facto and ISO standards) is:
>>>>
>>>> | The standard says: 6.7.2.1p16 “The size of a union is
>>>> | sufficient to contain the largest of its members. The value of
>>>> | at most one of the members can be stored in a union object
>>>> | at any time. *A pointer to a union object, suitably converted,*
>>>> | *points to each of its members (or if a member is a bit-field,*
>>>> | *then to the unit in which it resides), and vice versa.*” (bold
>>>> | emphasis added).
>>>>
>>>> So I think this is only valid if you actually start with a union
>>>> object.  A plain top-level definition of a volatile int is not a union
>>>> member, so this rule does not apply (in the “vice versa” part).
>>>
>>> Then we'll have to agree to disagree.  What do others think about this
>>> question?
>>
>> i think the standard says that
>>
>> volatile int x;
>> *(int*)&x;
>>
>> is undefined and i think
>>
>> int r = *p;
>
> At least on the architectures that already use the __atomic builtins, we
> never perform such an access -- everything goes through __atomic*.  On
> other architectures, we already use plain, non-volatile accesses to
> emulate real atomics (eg, see atomic_store_relaxed).  ISTM that we
> wouldn't be making things worse in the sense that we already make
> assumptions about what the compiler would do or would not (e.g., the
> compiler does not store to *p again as in your third example).
>

Yes, architectures which use the C11 atomics passes the volatile int * 
to the __atomic* builtins.

For architectures not using C11 atomics:
 From the spinlock perspective, the latest patch does not access a 
casted pointer which discards the volatile qualifier.

Instead in atomic_exchange_acq there is a
read from a volatile int * into a local int variable.
The volatile int * is passed to
atomic_compare_and_exchange_bool_acq macro.
The passed oldval / newval variables have type int instead
of volatile int.

atomic_load_relaxed is now using a local variable of type int instead of 
volatile int. Reading from the volatile int * is done by gcc via inline 
assembly. Afterwards the local int variable is returned to the user of 
this macro.

__atomic_val_bysize is now using a local variable of type int instead
of volatile int. The return value of pre##_<sizeof(*mem)>_##post is 
stored in the local variable and then returned to the user of this macro.

If this is okay, I prefer to use the changes from the latest patch.
Then this will fix - if compiled with GCC >= 5 - the usage of
the atomic macros in include/atomic.h with volatile int *
for architectures which do not define USE_ATOMIC_COMPILER_BUILTINS
to one.

If this is not okay, I would skip those changes in include/atomic.h
for this patch.
After we have a solution, we should work on a separate patch.
Even if gcc provides an extension as mentioned by Florian, I think it 
will only be available with new GCCs. What about the current GCCs?

Bye
Stefan
diff mbox

Patch

commit 2110f18d944bcb018f57d35b1efe19b9b5f78b1a
Author: Stefan Liebler <stli@linux.vnet.ibm.com>
Date:   Wed Feb 15 10:19:27 2017 +0100

    Optimize generic spinlock code and use C11 like atomic macros.
    
    This patch optimizes the generic spinlock code.
    
    The type pthread_spinlock_t is a typedef to volatile int on all archs.
    Passing a volatile pointer to the atomic macros can lead to extra stores
    and loads to stack if such a macro creates a temporary variable by using
    "__typeof (*(mem)) tmp;".  Thus, those macros which are used by spinlock code -
    atomic_exchange_acquire, atomic_load_relaxed,
    atomic_compare_exchange_weak_acquire - have to be adjusted.
    According to the comment from  Szabolcs Nagy, the type of a cast expression is
    unqualified (see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_423.htm):
    __typeof ((__typeof (*(mem)) *(mem)) tmp;
    This patch adjusts those macros in include/atomic.h.
    
    The atomic macros are replaced by the C11 like atomic macros and thus
    the code is aligned to it.  The pthread_spin_unlock implementation is now
    using release memory order instead of sequentially consistent memory order.
    The issue with passed volatile int pointers applies to the C11 like atomic
    macros as well as the ones used before.
    
    I've added a glibc_likely hint to the first atomic exchange in
    pthread_spin_lock in order to return immediately to the caller if the lock is
    free.  Without the hint, there is an additional jump if the lock is free.
    
    I've added the atomic_spin_nop macro within the loop of plain reads.
    The plain reads are also realized by C11 like atomic_load_relaxed macro.
    
    For pthread_spin_trylock, a machine-specific version can define
    SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG to 1 if an explicit test if
    lock is free is optimal.
    
    An architecture which wants to use the generic spinlock implementation
    has to create the file pthread_spin_parameters.h with the definition of
    the following parameter macros instead of creating a wrapper file which
    includes nptl/pthread_spin_lock.c:
    SPIN_LOCK_READS_BETWEEN_CMPXCHG
    SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG
    
    ChangeLog:
    
    	* NEWS: Mention new spinlock implementation.
    	* include/atomic.h:
    	(__atomic_val_bysize): Cast type to omit volatile qualifier.
    	(atomic_exchange_acq): Likewise.
    	(atomic_load_relaxed): Likewise.
    	* nptl/pthread_spin_init.c (pthread_spin_init):
    	Use atomic_store_relaxed.
    	* nptl/pthread_spin_lock.c (pthread_spin_lock):
    	Use C11-like atomic macros.
    	* nptl/pthread_spin_trylock.c
    	(pthread_spin_trylock): Likewise.  Use an explicit load and
    	test if lock is free before exchange,  if new macro
    	SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG macro is set to one.
    	* nptl/pthread_spin_unlock.c (pthread_spin_unlock):
    	Use atomic_store_release.
    	* nptl/pthread_spin_parameters.h: New File.
    	* sysdeps/aarch64/nptl/pthread_spin_lock.c: Delete File.
    	* sysdeps/aarch64/nptl/pthread_spin_parameters.h: New File.
    	* sysdeps/arm/nptl/pthread_spin_lock.c: Delete File.
    	* sysdeps/arm/nptl/pthread_spin_parameters.h: New File.
    	* sysdeps/hppa/nptl/pthread_spin_lock.c: Delete File.
    	* sysdeps/hppa/nptl/pthread_spin_parameters.h: New File.
    	* sysdeps/m68k/nptl/pthread_spin_lock.c: Delete File.
    	* sysdeps/m68k/nptl/pthread_spin_parameters.h: New File.
    	* sysdeps/microblaze/nptl/pthread_spin_lock.c: Delete File.
    	* sysdeps/microblaze/nptl/pthread_spin_parameters.h: New File.
    	* sysdeps/mips/nptl/pthread_spin_lock.c: Delete File.
    	* sysdeps/mips/nptl/pthread_spin_parameters.h: New File.
    	* sysdeps/nios2/nptl/pthread_spin_lock.c: Delete File.
    	* sysdeps/nios2/nptl/pthread_spin_parameters.h: New File.

diff --git a/NEWS b/NEWS
index b5a401c..b85b734 100644
--- a/NEWS
+++ b/NEWS
@@ -7,7 +7,9 @@  using `glibc' in the "product" field.
 
 Version 2.26
 
-[Add important changes here]
+* The new generic spinlock implementation uses C11 like atomics.
+  The pthread_spin_unlock implementation is now using release
+  memory order instead of sequentially consistent memory order.
 
 Security related changes:
 
diff --git a/include/atomic.h b/include/atomic.h
index 7f32640..770db4a 100644
--- a/include/atomic.h
+++ b/include/atomic.h
@@ -54,7 +54,7 @@ 
    and following args.  */
 #define __atomic_val_bysize(pre, post, mem, ...)			      \
   ({									      \
-    __typeof (*mem) __atg1_result;					      \
+    __typeof ((__typeof (*(mem))) *(mem)) __atg1_result;		      \
     if (sizeof (*mem) == 1)						      \
       __atg1_result = pre##_8_##post (mem, __VA_ARGS__);		      \
     else if (sizeof (*mem) == 2)					      \
@@ -162,9 +162,9 @@ 
 /* Store NEWVALUE in *MEM and return the old value.  */
 #ifndef atomic_exchange_acq
 # define atomic_exchange_acq(mem, newvalue) \
-  ({ __typeof (*(mem)) __atg5_oldval;					      \
+  ({ __typeof ((__typeof (*(mem))) *(mem)) __atg5_oldval;		      \
      __typeof (mem) __atg5_memp = (mem);				      \
-     __typeof (*(mem)) __atg5_value = (newvalue);			      \
+     __typeof ((__typeof (*(mem))) *(mem)) __atg5_value = (newvalue);	      \
 									      \
      do									      \
        __atg5_oldval = *__atg5_memp;					      \
@@ -668,7 +668,7 @@  void __atomic_link_error (void);
 
 # ifndef atomic_load_relaxed
 #  define atomic_load_relaxed(mem) \
-   ({ __typeof (*(mem)) __atg100_val;					      \
+   ({ __typeof ((__typeof (*(mem))) *(mem)) __atg100_val;		      \
    __asm ("" : "=r" (__atg100_val) : "0" (*(mem)));			      \
    __atg100_val; })
 # endif
diff --git a/nptl/pthread_spin_init.c b/nptl/pthread_spin_init.c
index 01dec5e..fe30913 100644
--- a/nptl/pthread_spin_init.c
+++ b/nptl/pthread_spin_init.c
@@ -22,6 +22,7 @@ 
 int
 pthread_spin_init (pthread_spinlock_t *lock, int pshared)
 {
-  *lock = 0;
+  /* Relaxed MO is fine because this is an initializing store.  */
+  atomic_store_relaxed (lock, 0);
   return 0;
 }
diff --git a/nptl/pthread_spin_lock.c b/nptl/pthread_spin_lock.c
index 4d03b78..65d34a3 100644
--- a/nptl/pthread_spin_lock.c
+++ b/nptl/pthread_spin_lock.c
@@ -18,15 +18,7 @@ 
 
 #include <atomic.h>
 #include "pthreadP.h"
-
-/* A machine-specific version can define SPIN_LOCK_READS_BETWEEN_CMPXCHG
-  to the number of plain reads that it's optimal to spin on between uses
-  of atomic_compare_and_exchange_val_acq.  If spinning forever is optimal
-  then use -1.  If no plain reads here would ever be optimal, use 0.  */
-#ifndef SPIN_LOCK_READS_BETWEEN_CMPXCHG
-# warning machine-dependent file should define SPIN_LOCK_READS_BETWEEN_CMPXCHG
-# define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
-#endif
+#include <pthread_spin_parameters.h>
 
 int
 pthread_spin_lock (pthread_spinlock_t *lock)
@@ -37,10 +29,14 @@  pthread_spin_lock (pthread_spinlock_t *lock)
      when the lock is locked.
      We assume that the first try mostly will be successful, and we use
      atomic_exchange.  For the subsequent tries we use
-     atomic_compare_and_exchange.  */
-  if (atomic_exchange_acq (lock, 1) == 0)
+     atomic_compare_and_exchange.
+     We use acquire MO to synchronize-with the release MO store in
+     pthread_spin_unlock, and thus ensure that prior critical sections
+     happen-before this critical section.  */
+  if (__glibc_likely (atomic_exchange_acquire (lock, 1) == 0))
     return 0;
 
+  int val;
   do
     {
       /* The lock is contended and we need to wait.  Going straight back
@@ -50,20 +46,39 @@  pthread_spin_lock (pthread_spinlock_t *lock)
 	 On the other hand, we do want to update memory state on the local core
 	 once in a while to avoid spinning indefinitely until some event that
 	 will happen to update local memory as a side-effect.  */
-      if (SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0)
+
+#if SPIN_LOCK_READS_BETWEEN_CMPXCHG >= 0
+      /* Use at most SPIN_LOCK_READS_BETWEEN_CMPXCHG relaxed MO reads between
+	 the atomic compare and exchanges.  */
+      int wait;
+      for (wait = 0; wait < SPIN_LOCK_READS_BETWEEN_CMPXCHG;  wait ++)
 	{
-	  int wait = SPIN_LOCK_READS_BETWEEN_CMPXCHG;
+	  atomic_spin_nop ();
 
-	  while (*lock != 0 && wait > 0)
-	    --wait;
+	  val = atomic_load_relaxed (lock);
+	  if (val == 0)
+	    break;
 	}
-      else
+
+      /* Set expected value to zero for the next compare and exchange.  */
+      val = 0;
+
+#else /* SPIN_LOCK_READS_BETWEEN_CMPXCHG < 0  */
+      /* Use relaxed MO reads until we observe the lock to not be acquired
+	 anymore.  */
+      do
 	{
-	  while (*lock != 0)
-	    ;
+	  atomic_spin_nop ();
+
+	  val = atomic_load_relaxed (lock);
 	}
+      while (val != 0);
+
+#endif
+      /* We need acquire memory order here for the same reason as mentioned
+	 for the first try to lock the spinlock.  */
     }
-  while (atomic_compare_and_exchange_val_acq (lock, 1, 0) != 0);
+  while (!atomic_compare_exchange_weak_acquire (lock, &val, 1));
 
   return 0;
 }
diff --git a/nptl/pthread_spin_parameters.h b/nptl/pthread_spin_parameters.h
new file mode 100644
index 0000000..6cde482
--- /dev/null
+++ b/nptl/pthread_spin_parameters.h
@@ -0,0 +1,35 @@ 
+/* Parameters for generic pthread_spinlock_t implementation.  Generic version.
+   Copyright (C) 2017 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
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   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, see
+   <http://www.gnu.org/licenses/>.  */
+
+/* A machine-specific version can define SPIN_LOCK_READS_BETWEEN_CMPXCHG
+   to the number of plain reads that it's optimal to spin on between uses
+   of atomic_compare_exchange_weak_acquire.  If spinning forever is optimal,
+   then use -1.  If no plain reads here would ever be optimal, use 0.  */
+#ifndef SPIN_LOCK_READS_BETWEEN_CMPXCHG
+# warning machine-dependent file should define SPIN_LOCK_READS_BETWEEN_CMPXCHG
+# define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
+#endif
+
+/* A machine-specific version can define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG
+   to 1 if an explicit load and test if lock is not acquired before executing
+   atomic_exchange_acquire is optimal.  Define to 0 to execute
+   atomic_exchange_acquire without an additional load and test.  */
+#ifndef SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG
+# warning machine-dependent file should define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG
+# define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG 0
+#endif
diff --git a/nptl/pthread_spin_trylock.c b/nptl/pthread_spin_trylock.c
index 593bba3..1e22843 100644
--- a/nptl/pthread_spin_trylock.c
+++ b/nptl/pthread_spin_trylock.c
@@ -19,9 +19,28 @@ 
 #include <errno.h>
 #include <atomic.h>
 #include "pthreadP.h"
+#include <pthread_spin_parameters.h>
 
 int
 pthread_spin_trylock (pthread_spinlock_t *lock)
 {
-  return atomic_exchange_acq (lock, 1) ? EBUSY : 0;
+  /* We use acquire MO to synchronize-with the release MO store in
+     pthread_spin_unlock, and thus ensure that prior critical sections
+     happen-before this critical section.  */
+#if SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG == 1
+  /* Load and test the spinlock and only try to acquire the lock if it has
+     not been acquired.  */
+  int val = atomic_load_relaxed (lock);
+  if (__glibc_likely (val == 0 && atomic_exchange_acquire (lock, 1) == 0))
+    return 0;
+#elif SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG == 0
+  /* Try to acquire the lock, which succeeds if the lock had not been
+     acquired.  */
+  if (__glibc_likely (atomic_exchange_acquire (lock, 1) == 0))
+    return 0;
+#else
+# error SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG has to be defined to 0 or 1
+#endif
+
+  return EBUSY;
 }
diff --git a/nptl/pthread_spin_unlock.c b/nptl/pthread_spin_unlock.c
index 5fd73e5..f83b696 100644
--- a/nptl/pthread_spin_unlock.c
+++ b/nptl/pthread_spin_unlock.c
@@ -23,7 +23,9 @@ 
 int
 pthread_spin_unlock (pthread_spinlock_t *lock)
 {
-  atomic_full_barrier ();
-  *lock = 0;
+  /* The atomic_store_release synchronizes-with the atomic_exchange_acquire
+     or atomic_compare_exchange_weak_acquire in pthread_spin_lock /
+     pthread_spin_trylock.  */
+  atomic_store_release (lock, 0);
   return 0;
 }
diff --git a/sysdeps/aarch64/nptl/pthread_spin_lock.c b/sysdeps/aarch64/nptl/pthread_spin_lock.c
deleted file mode 100644
index fcfcb40..0000000
--- a/sysdeps/aarch64/nptl/pthread_spin_lock.c
+++ /dev/null
@@ -1,24 +0,0 @@ 
-/* Copyright (C) 2008-2017 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
-   modify it under the terms of the GNU Lesser General Public License as
-   published by the Free Software Foundation; either version 2.1 of the
-   License, or (at your option) any later version.
-
-   The GNU C Library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   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, see
-   <http://www.gnu.org/licenses/>.  */
-
-#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
-
-/* We can't use the normal "#include <nptl/pthread_spin_lock.c>" because
-   it will resolve to this very file.  Using "sysdeps/.." as reference to the
-   top level directory does the job.  */
-#include <sysdeps/../nptl/pthread_spin_lock.c>
diff --git a/sysdeps/aarch64/nptl/pthread_spin_parameters.h b/sysdeps/aarch64/nptl/pthread_spin_parameters.h
new file mode 100644
index 0000000..5fd319c
--- /dev/null
+++ b/sysdeps/aarch64/nptl/pthread_spin_parameters.h
@@ -0,0 +1,22 @@ 
+/* Parameters for generic pthread_spinlock_t implementation.  aarch64 version.
+   Copyright (C) 2017 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
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   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, see
+   <http://www.gnu.org/licenses/>.  */
+
+#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
+#define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG 0
+
+#include_next <pthread_spin_parameters.h>
diff --git a/sysdeps/arm/nptl/pthread_spin_lock.c b/sysdeps/arm/nptl/pthread_spin_lock.c
deleted file mode 100644
index 037b3b8..0000000
--- a/sysdeps/arm/nptl/pthread_spin_lock.c
+++ /dev/null
@@ -1,23 +0,0 @@ 
-/* Copyright (C) 2008-2017 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
-   modify it under the terms of the GNU Lesser General Public
-   License as published by the Free Software Foundation; either
-   version 2.1 of the License, or (at your option) any later version.
-
-   The GNU C Library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   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, see
-   <http://www.gnu.org/licenses/>.  */
-
-#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
-
-/* We can't use the normal "#include <nptl/pthread_spin_lock.c>" because
-   it will resolve to this very file.  Using "sysdeps/.." as reference to the
-   top level directory does the job.  */
-#include <sysdeps/../nptl/pthread_spin_lock.c>
diff --git a/sysdeps/arm/nptl/pthread_spin_parameters.h b/sysdeps/arm/nptl/pthread_spin_parameters.h
new file mode 100644
index 0000000..3f8285a
--- /dev/null
+++ b/sysdeps/arm/nptl/pthread_spin_parameters.h
@@ -0,0 +1,22 @@ 
+/* Parameters for generic pthread_spinlock_t implementation.  arm version.
+   Copyright (C) 2017 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
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   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, see
+   <http://www.gnu.org/licenses/>.  */
+
+#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
+#define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG 0
+
+#include_next <pthread_spin_parameters.h>
diff --git a/sysdeps/hppa/nptl/pthread_spin_lock.c b/sysdeps/hppa/nptl/pthread_spin_lock.c
deleted file mode 100644
index 14f36a6..0000000
--- a/sysdeps/hppa/nptl/pthread_spin_lock.c
+++ /dev/null
@@ -1,23 +0,0 @@ 
-/* Copyright (C) 2005-2017 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
-   modify it under the terms of the GNU Lesser General Public
-   License as published by the Free Software Foundation; either
-   version 2.1 of the License, or (at your option) any later version.
-
-   The GNU C Library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   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, see
-   <http://www.gnu.org/licenses/>.  */
-
-#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
-
-/* We can't use the normal "#include <nptl/pthread_spin_lock.c>" because
-   it will resolve to this very file.  Using "sysdeps/.." as reference to the
-   top level directory does the job.  */
-#include <sysdeps/../nptl/pthread_spin_lock.c>
diff --git a/sysdeps/hppa/nptl/pthread_spin_parameters.h b/sysdeps/hppa/nptl/pthread_spin_parameters.h
new file mode 100644
index 0000000..ebeb162
--- /dev/null
+++ b/sysdeps/hppa/nptl/pthread_spin_parameters.h
@@ -0,0 +1,22 @@ 
+/* Parameters for generic pthread_spinlock_t implementation.  hppa version.
+   Copyright (C) 2017 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
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   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, see
+   <http://www.gnu.org/licenses/>.  */
+
+#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
+#define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG 0
+
+#include_next <pthread_spin_parameters.h>
diff --git a/sysdeps/m68k/nptl/pthread_spin_lock.c b/sysdeps/m68k/nptl/pthread_spin_lock.c
deleted file mode 100644
index 62795f4..0000000
--- a/sysdeps/m68k/nptl/pthread_spin_lock.c
+++ /dev/null
@@ -1,24 +0,0 @@ 
-/* Copyright (C) 2010-2017 Free Software Foundation, Inc.
-   This file is part of the GNU C Library.
-   Contributed by Maxim Kuvyrkov <maxim@codesourcery.com>, 2010.
-
-   The GNU C Library is free software; you can redistribute it and/or
-   modify it under the terms of the GNU Lesser General Public
-   License as published by the Free Software Foundation; either
-   version 2.1 of the License, or (at your option) any later version.
-
-   The GNU C Library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   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, see
-   <http://www.gnu.org/licenses/>.  */
-
-#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
-
-/* We can't use the normal "#include <nptl/pthread_spin_lock.c>" because
-   it will resolve to this very file.  Using "sysdeps/.." as reference to the
-   top level directory does the job.  */
-#include <sysdeps/../nptl/pthread_spin_lock.c>
diff --git a/sysdeps/m68k/nptl/pthread_spin_parameters.h b/sysdeps/m68k/nptl/pthread_spin_parameters.h
new file mode 100644
index 0000000..b7b8581
--- /dev/null
+++ b/sysdeps/m68k/nptl/pthread_spin_parameters.h
@@ -0,0 +1,22 @@ 
+/* Parameters for generic pthread_spinlock_t implementation.  m68k version.
+   Copyright (C) 2017 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
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   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, see
+   <http://www.gnu.org/licenses/>.  */
+
+#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
+#define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG 0
+
+#include_next <pthread_spin_parameters.h>
diff --git a/sysdeps/microblaze/nptl/pthread_spin_lock.c b/sysdeps/microblaze/nptl/pthread_spin_lock.c
deleted file mode 100644
index fcfcb40..0000000
--- a/sysdeps/microblaze/nptl/pthread_spin_lock.c
+++ /dev/null
@@ -1,24 +0,0 @@ 
-/* Copyright (C) 2008-2017 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
-   modify it under the terms of the GNU Lesser General Public License as
-   published by the Free Software Foundation; either version 2.1 of the
-   License, or (at your option) any later version.
-
-   The GNU C Library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   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, see
-   <http://www.gnu.org/licenses/>.  */
-
-#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
-
-/* We can't use the normal "#include <nptl/pthread_spin_lock.c>" because
-   it will resolve to this very file.  Using "sysdeps/.." as reference to the
-   top level directory does the job.  */
-#include <sysdeps/../nptl/pthread_spin_lock.c>
diff --git a/sysdeps/microblaze/nptl/pthread_spin_parameters.h b/sysdeps/microblaze/nptl/pthread_spin_parameters.h
new file mode 100644
index 0000000..ef5827b
--- /dev/null
+++ b/sysdeps/microblaze/nptl/pthread_spin_parameters.h
@@ -0,0 +1,23 @@ 
+/* Parameters for generic pthread_spinlock_t implementation.
+   microblaze version.
+   Copyright (C) 2017 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
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   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, see
+   <http://www.gnu.org/licenses/>.  */
+
+#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
+#define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG 0
+
+#include_next <pthread_spin_parameters.h>
diff --git a/sysdeps/mips/nptl/pthread_spin_lock.c b/sysdeps/mips/nptl/pthread_spin_lock.c
deleted file mode 100644
index 19d87a5..0000000
--- a/sysdeps/mips/nptl/pthread_spin_lock.c
+++ /dev/null
@@ -1,23 +0,0 @@ 
-/* Copyright (C) 2012-2017 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
-   modify it under the terms of the GNU Lesser General Public
-   License as published by the Free Software Foundation; either
-   version 2.1 of the License, or (at your option) any later version.
-
-   The GNU C Library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   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, see
-   <http://www.gnu.org/licenses/>.  */
-
-#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
-
-/* We can't use the normal "#include <nptl/pthread_spin_lock.c>" because
-   it will resolve to this very file.  Using "sysdeps/.." as reference to the
-   top level directory does the job.  */
-#include <sysdeps/../nptl/pthread_spin_lock.c>
diff --git a/sysdeps/mips/nptl/pthread_spin_parameters.h b/sysdeps/mips/nptl/pthread_spin_parameters.h
new file mode 100644
index 0000000..4f03890
--- /dev/null
+++ b/sysdeps/mips/nptl/pthread_spin_parameters.h
@@ -0,0 +1,22 @@ 
+/* Parameters for generic pthread_spinlock_t implementation.  mips version.
+   Copyright (C) 2017 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
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   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, see
+   <http://www.gnu.org/licenses/>.  */
+
+#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
+#define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG 0
+
+#include_next <pthread_spin_parameters.h>
diff --git a/sysdeps/nios2/nptl/pthread_spin_lock.c b/sysdeps/nios2/nptl/pthread_spin_lock.c
deleted file mode 100644
index b203469..0000000
--- a/sysdeps/nios2/nptl/pthread_spin_lock.c
+++ /dev/null
@@ -1,24 +0,0 @@ 
-/* pthread spin-lock implementation for Nios II.
-   Copyright (C) 2005-2017 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
-   modify it under the terms of the GNU Lesser General Public
-   License as published by the Free Software Foundation; either
-   version 2.1 of the License, or (at your option) any later version.
-
-   The GNU C Library is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   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, see
-   <http://www.gnu.org/licenses/>.  */
-
-#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
-
-/* We can't use the normal "#include <nptl/pthread_spin_lock.c>" because
-   it will resolve to this very file.  Using "sysdeps/.." as reference to the
-   top level directory does the job.  */
-#include <sysdeps/../nptl/pthread_spin_lock.c>
diff --git a/sysdeps/nios2/nptl/pthread_spin_parameters.h b/sysdeps/nios2/nptl/pthread_spin_parameters.h
new file mode 100644
index 0000000..237edb3
--- /dev/null
+++ b/sysdeps/nios2/nptl/pthread_spin_parameters.h
@@ -0,0 +1,22 @@ 
+/* Parameters for generic pthread_spinlock_t implementation.  nios2 version.
+   Copyright (C) 2017 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
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   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, see
+   <http://www.gnu.org/licenses/>.  */
+
+#define SPIN_LOCK_READS_BETWEEN_CMPXCHG 1000
+#define SPIN_TRYLOCK_LOAD_AND_TEST_BEFORE_XCHG 0
+
+#include_next <pthread_spin_parameters.h>