xref: /freebsd/libexec/rtld-elf/rtld_lock.c (revision ce6a89e27cd190313be39bb479880aeda4778436)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1999, 2000 John D. Polstra.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  *	from: FreeBSD: src/libexec/rtld-elf/sparc64/lockdflt.c,v 1.3 2002/10/09
28  * $FreeBSD$
29  */
30 
31 /*
32  * Thread locking implementation for the dynamic linker.
33  *
34  * We use the "simple, non-scalable reader-preference lock" from:
35  *
36  *   J. M. Mellor-Crummey and M. L. Scott. "Scalable Reader-Writer
37  *   Synchronization for Shared-Memory Multiprocessors." 3rd ACM Symp. on
38  *   Principles and Practice of Parallel Programming, April 1991.
39  *
40  * In this algorithm the lock is a single word.  Its low-order bit is
41  * set when a writer holds the lock.  The remaining high-order bits
42  * contain a count of readers desiring the lock.  The algorithm requires
43  * atomic "compare_and_store" and "add" operations, which we take
44  * from machine/atomic.h.
45  */
46 
47 #include <sys/param.h>
48 #include <sys/signalvar.h>
49 #include <signal.h>
50 #include <stdlib.h>
51 #include <time.h>
52 
53 #include "debug.h"
54 #include "rtld.h"
55 #include "rtld_machdep.h"
56 #include "rtld_libc.h"
57 
58 void _rtld_thread_init(struct RtldLockInfo *) __exported;
59 void _rtld_atfork_pre(int *) __exported;
60 void _rtld_atfork_post(int *) __exported;
61 
62 #define WAFLAG		0x1	/* A writer holds the lock */
63 #define RC_INCR		0x2	/* Adjusts count of readers desiring lock */
64 
65 typedef struct Struct_Lock {
66 	volatile u_int lock;
67 	void *base;
68 } Lock;
69 
70 static sigset_t fullsigmask, oldsigmask;
71 static int thread_flag, wnested;
72 static uint32_t fsigblock;
73 
74 static void *
75 def_lock_create(void)
76 {
77     void *base;
78     char *p;
79     uintptr_t r;
80     Lock *l;
81 
82     /*
83      * Arrange for the lock to occupy its own cache line.  First, we
84      * optimistically allocate just a cache line, hoping that malloc
85      * will give us a well-aligned block of memory.  If that doesn't
86      * work, we allocate a larger block and take a well-aligned cache
87      * line from it.
88      */
89     base = xmalloc(CACHE_LINE_SIZE);
90     p = (char *)base;
91     if ((uintptr_t)p % CACHE_LINE_SIZE != 0) {
92 	free(base);
93 	base = xmalloc(2 * CACHE_LINE_SIZE);
94 	p = (char *)base;
95 	if ((r = (uintptr_t)p % CACHE_LINE_SIZE) != 0)
96 	    p += CACHE_LINE_SIZE - r;
97     }
98     l = (Lock *)p;
99     l->base = base;
100     l->lock = 0;
101     return l;
102 }
103 
104 static void
105 def_lock_destroy(void *lock)
106 {
107     Lock *l = (Lock *)lock;
108 
109     free(l->base);
110 }
111 
112 static void
113 def_rlock_acquire(void *lock)
114 {
115     Lock *l = (Lock *)lock;
116 
117     atomic_add_acq_int(&l->lock, RC_INCR);
118     while (l->lock & WAFLAG)
119 	    ;	/* Spin */
120 }
121 
122 static void
123 sig_fastunblock(void)
124 {
125 	uint32_t oldval;
126 
127 	assert((fsigblock & ~SIGFASTBLOCK_FLAGS) >= SIGFASTBLOCK_INC);
128 	oldval = atomic_fetchadd_32(&fsigblock, -SIGFASTBLOCK_INC);
129 	if (oldval == (SIGFASTBLOCK_PEND | SIGFASTBLOCK_INC))
130 		__sys_sigfastblock(SIGFASTBLOCK_UNBLOCK, NULL);
131 }
132 
133 static void
134 def_wlock_acquire(void *lock)
135 {
136 	Lock *l;
137 	sigset_t tmp_oldsigmask;
138 
139 	l = (Lock *)lock;
140 	if (ld_fast_sigblock) {
141 		for (;;) {
142 			atomic_add_32(&fsigblock, SIGFASTBLOCK_INC);
143 			if (atomic_cmpset_acq_int(&l->lock, 0, WAFLAG))
144 				break;
145 			sig_fastunblock();
146 		}
147 	} else {
148 		for (;;) {
149 			sigprocmask(SIG_BLOCK, &fullsigmask, &tmp_oldsigmask);
150 			if (atomic_cmpset_acq_int(&l->lock, 0, WAFLAG))
151 				break;
152 			sigprocmask(SIG_SETMASK, &tmp_oldsigmask, NULL);
153 		}
154 		if (atomic_fetchadd_int(&wnested, 1) == 0)
155 			oldsigmask = tmp_oldsigmask;
156 	}
157 }
158 
159 static void
160 def_lock_release(void *lock)
161 {
162 	Lock *l;
163 
164 	l = (Lock *)lock;
165 	if ((l->lock & WAFLAG) == 0)
166 		atomic_add_rel_int(&l->lock, -RC_INCR);
167 	else {
168 		atomic_add_rel_int(&l->lock, -WAFLAG);
169 		if (ld_fast_sigblock)
170 			sig_fastunblock();
171 		else if (atomic_fetchadd_int(&wnested, -1) == 1)
172 			sigprocmask(SIG_SETMASK, &oldsigmask, NULL);
173 	}
174 }
175 
176 static int
177 def_thread_set_flag(int mask)
178 {
179 	int old_val = thread_flag;
180 	thread_flag |= mask;
181 	return (old_val);
182 }
183 
184 static int
185 def_thread_clr_flag(int mask)
186 {
187 	int old_val = thread_flag;
188 	thread_flag &= ~mask;
189 	return (old_val);
190 }
191 
192 /*
193  * Public interface exposed to the rest of the dynamic linker.
194  */
195 static struct RtldLockInfo lockinfo;
196 static struct RtldLockInfo deflockinfo;
197 
198 static __inline int
199 thread_mask_set(int mask)
200 {
201 	return lockinfo.thread_set_flag(mask);
202 }
203 
204 static __inline void
205 thread_mask_clear(int mask)
206 {
207 	lockinfo.thread_clr_flag(mask);
208 }
209 
210 #define	RTLD_LOCK_CNT	3
211 static struct rtld_lock {
212 	void	*handle;
213 	int	 mask;
214 } rtld_locks[RTLD_LOCK_CNT];
215 
216 rtld_lock_t	rtld_bind_lock = &rtld_locks[0];
217 rtld_lock_t	rtld_libc_lock = &rtld_locks[1];
218 rtld_lock_t	rtld_phdr_lock = &rtld_locks[2];
219 
220 void
221 rlock_acquire(rtld_lock_t lock, RtldLockState *lockstate)
222 {
223 
224 	if (lockstate == NULL)
225 		return;
226 
227 	if (thread_mask_set(lock->mask) & lock->mask) {
228 		dbg("rlock_acquire: recursed");
229 		lockstate->lockstate = RTLD_LOCK_UNLOCKED;
230 		return;
231 	}
232 	lockinfo.rlock_acquire(lock->handle);
233 	lockstate->lockstate = RTLD_LOCK_RLOCKED;
234 }
235 
236 void
237 wlock_acquire(rtld_lock_t lock, RtldLockState *lockstate)
238 {
239 
240 	if (lockstate == NULL)
241 		return;
242 
243 	if (thread_mask_set(lock->mask) & lock->mask) {
244 		dbg("wlock_acquire: recursed");
245 		lockstate->lockstate = RTLD_LOCK_UNLOCKED;
246 		return;
247 	}
248 	lockinfo.wlock_acquire(lock->handle);
249 	lockstate->lockstate = RTLD_LOCK_WLOCKED;
250 }
251 
252 void
253 lock_release(rtld_lock_t lock, RtldLockState *lockstate)
254 {
255 
256 	if (lockstate == NULL)
257 		return;
258 
259 	switch (lockstate->lockstate) {
260 	case RTLD_LOCK_UNLOCKED:
261 		break;
262 	case RTLD_LOCK_RLOCKED:
263 	case RTLD_LOCK_WLOCKED:
264 		thread_mask_clear(lock->mask);
265 		lockinfo.lock_release(lock->handle);
266 		break;
267 	default:
268 		assert(0);
269 	}
270 }
271 
272 void
273 lock_upgrade(rtld_lock_t lock, RtldLockState *lockstate)
274 {
275 
276 	if (lockstate == NULL)
277 		return;
278 
279 	lock_release(lock, lockstate);
280 	wlock_acquire(lock, lockstate);
281 }
282 
283 void
284 lock_restart_for_upgrade(RtldLockState *lockstate)
285 {
286 
287 	if (lockstate == NULL)
288 		return;
289 
290 	switch (lockstate->lockstate) {
291 	case RTLD_LOCK_UNLOCKED:
292 	case RTLD_LOCK_WLOCKED:
293 		break;
294 	case RTLD_LOCK_RLOCKED:
295 		siglongjmp(lockstate->env, 1);
296 		break;
297 	default:
298 		assert(0);
299 	}
300 }
301 
302 void
303 lockdflt_init(void)
304 {
305 	int i;
306 
307 	deflockinfo.rtli_version = RTLI_VERSION;
308 	deflockinfo.lock_create = def_lock_create;
309 	deflockinfo.lock_destroy = def_lock_destroy;
310 	deflockinfo.rlock_acquire = def_rlock_acquire;
311 	deflockinfo.wlock_acquire = def_wlock_acquire;
312 	deflockinfo.lock_release = def_lock_release;
313 	deflockinfo.thread_set_flag = def_thread_set_flag;
314 	deflockinfo.thread_clr_flag = def_thread_clr_flag;
315 	deflockinfo.at_fork = NULL;
316 
317 	for (i = 0; i < RTLD_LOCK_CNT; i++) {
318 		rtld_locks[i].mask   = (1 << i);
319 		rtld_locks[i].handle = NULL;
320 	}
321 
322 	memcpy(&lockinfo, &deflockinfo, sizeof(lockinfo));
323 	_rtld_thread_init(NULL);
324 	if (ld_fast_sigblock) {
325 		__sys_sigfastblock(SIGFASTBLOCK_SETPTR, &fsigblock);
326 	} else {
327 		/*
328 		 * Construct a mask to block all signals.  Note that
329 		 * blocked traps mean that the process is terminated
330 		 * if trap occurs while we are in locked section, with
331 		 * the default settings for kern.forcesigexit.
332 		 */
333 		sigfillset(&fullsigmask);
334 	}
335 }
336 
337 /*
338  * Callback function to allow threads implementation to
339  * register their own locking primitives if the default
340  * one is not suitable.
341  * The current context should be the only context
342  * executing at the invocation time.
343  */
344 void
345 _rtld_thread_init(struct RtldLockInfo *pli)
346 {
347 	int flags, i;
348 	void *locks[RTLD_LOCK_CNT];
349 
350 	/* disable all locking while this function is running */
351 	flags =	thread_mask_set(~0);
352 
353 	if (pli == NULL)
354 		pli = &deflockinfo;
355 	else if (ld_fast_sigblock) {
356 		fsigblock = 0;
357 		__sys_sigfastblock(SIGFASTBLOCK_UNSETPTR, NULL);
358 	}
359 
360 	for (i = 0; i < RTLD_LOCK_CNT; i++)
361 		if ((locks[i] = pli->lock_create()) == NULL)
362 			break;
363 
364 	if (i < RTLD_LOCK_CNT) {
365 		while (--i >= 0)
366 			pli->lock_destroy(locks[i]);
367 		abort();
368 	}
369 
370 	for (i = 0; i < RTLD_LOCK_CNT; i++) {
371 		if (rtld_locks[i].handle == NULL)
372 			continue;
373 		if (flags & rtld_locks[i].mask)
374 			lockinfo.lock_release(rtld_locks[i].handle);
375 		lockinfo.lock_destroy(rtld_locks[i].handle);
376 	}
377 
378 	for (i = 0; i < RTLD_LOCK_CNT; i++) {
379 		rtld_locks[i].handle = locks[i];
380 		if (flags & rtld_locks[i].mask)
381 			pli->wlock_acquire(rtld_locks[i].handle);
382 	}
383 
384 	lockinfo.lock_create = pli->lock_create;
385 	lockinfo.lock_destroy = pli->lock_destroy;
386 	lockinfo.rlock_acquire = pli->rlock_acquire;
387 	lockinfo.wlock_acquire = pli->wlock_acquire;
388 	lockinfo.lock_release  = pli->lock_release;
389 	lockinfo.thread_set_flag = pli->thread_set_flag;
390 	lockinfo.thread_clr_flag = pli->thread_clr_flag;
391 	lockinfo.at_fork = pli->at_fork;
392 
393 	/* restore thread locking state, this time with new locks */
394 	thread_mask_clear(~0);
395 	thread_mask_set(flags);
396 	dbg("_rtld_thread_init: done");
397 }
398 
399 void
400 _rtld_atfork_pre(int *locks)
401 {
402 	RtldLockState ls[2];
403 
404 	if (locks == NULL)
405 		return;
406 
407 	/*
408 	 * Warning: this did not worked well with the rtld compat
409 	 * locks above, when the thread signal mask was corrupted (set
410 	 * to all signals blocked) if two locks were taken
411 	 * simultaneously in the write mode.  The caller of the
412 	 * _rtld_atfork_pre() must provide the working implementation
413 	 * of the locks anyway, and libthr locks are fine.
414 	 */
415 	wlock_acquire(rtld_phdr_lock, &ls[0]);
416 	wlock_acquire(rtld_bind_lock, &ls[1]);
417 
418 	/* XXXKIB: I am really sorry for this. */
419 	locks[0] = ls[1].lockstate;
420 	locks[2] = ls[0].lockstate;
421 }
422 
423 void
424 _rtld_atfork_post(int *locks)
425 {
426 	RtldLockState ls[2];
427 
428 	if (locks == NULL)
429 		return;
430 
431 	bzero(ls, sizeof(ls));
432 	ls[0].lockstate = locks[2];
433 	ls[1].lockstate = locks[0];
434 	lock_release(rtld_bind_lock, &ls[1]);
435 	lock_release(rtld_phdr_lock, &ls[0]);
436 }
437