xref: /openbsd-src/lib/libc/arch/powerpc64/gen/_atomic_lock.c (revision ff8a0eacba6073582059946ccbffd78d9f42a3ce)
1*ff8a0eacSdrahn /*	$OpenBSD: _atomic_lock.c,v 1.2 2020/06/25 02:22:31 drahn Exp $	*/
2e11d2af5Sdrahn /*
3e11d2af5Sdrahn  * Copyright (c) 1998 Dale Rahn <drahn@openbsd.org>
4e11d2af5Sdrahn  *
5e11d2af5Sdrahn  * Permission to use, copy, modify, and distribute this software for any
6e11d2af5Sdrahn  * purpose with or without fee is hereby granted, provided that the above
7e11d2af5Sdrahn  * copyright notice and this permission notice appear in all copies.
8e11d2af5Sdrahn  *
9e11d2af5Sdrahn  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10e11d2af5Sdrahn  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11e11d2af5Sdrahn  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12e11d2af5Sdrahn  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13e11d2af5Sdrahn  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14e11d2af5Sdrahn  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15e11d2af5Sdrahn  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16e11d2af5Sdrahn  */
17e11d2af5Sdrahn 
18e11d2af5Sdrahn /*
19e11d2af5Sdrahn  * Atomic lock for powerpc
20e11d2af5Sdrahn  */
21e11d2af5Sdrahn 
22e11d2af5Sdrahn #include <machine/spinlock.h>
23e11d2af5Sdrahn 
24e11d2af5Sdrahn int
_atomic_lock(volatile _atomic_lock_t * lock)25e11d2af5Sdrahn _atomic_lock(volatile _atomic_lock_t *lock)
26e11d2af5Sdrahn {
27e11d2af5Sdrahn 	_atomic_lock_t old;
28e11d2af5Sdrahn 
29*ff8a0eacSdrahn 	__asm__("1: lwarx 0,0,%1   \n"
30*ff8a0eacSdrahn 		"   stwcx. %2,0,%1 \n"
31e11d2af5Sdrahn 		"   bne- 1b        \n"
32e11d2af5Sdrahn 		"   mr %0, 0	   \n"
33e11d2af5Sdrahn 		: "=r" (old), "=r" (lock)
34e11d2af5Sdrahn 		: "r" (_ATOMIC_LOCK_LOCKED), "1" (lock) : "0"
35e11d2af5Sdrahn 	);
36e11d2af5Sdrahn 
37e11d2af5Sdrahn 	return (old != _ATOMIC_LOCK_UNLOCKED);
38e11d2af5Sdrahn 
39e11d2af5Sdrahn 	/*
40e11d2af5Sdrahn 	 * Dale <drahn@openbsd.org> says:
41e11d2af5Sdrahn 	 *   Side note. to prevent two processes from accessing
42*ff8a0eacSdrahn 	 *   the same address with the lwarx in one instruction
43*ff8a0eacSdrahn 	 *   and the stwcx in another process, the current powerpc
44*ff8a0eacSdrahn 	 *   kernel uses a stwcx instruction without the corresponding
45e11d2af5Sdrahn 	 *   lwarx which causes any reservation of a process
46e11d2af5Sdrahn 	 *   to be removed.  if a context switch occurs
47e11d2af5Sdrahn 	 *   between the two accesses the store will not occur
48e11d2af5Sdrahn 	 *   and the condition code will cause it to loop. If on
49e11d2af5Sdrahn 	 *   a dual processor machine, the reserve will cause
50e11d2af5Sdrahn 	 *   appropriate bus cycle accesses to notify other
51e11d2af5Sdrahn 	 *   processors.
52e11d2af5Sdrahn 	 */
53e11d2af5Sdrahn }
54