xref: /haiku/src/system/kernel/condition_variable.cpp (revision f6373f2244fd555c134f3266657ffe8b540da397)
1 /*
2  * Copyright 2007-2011, Ingo Weinhold, ingo_weinhold@gmx.de.
3  * Copyright 2019, Haiku, Inc. All rights reserved.
4  * Distributed under the terms of the MIT License.
5  */
6 
7 #include <condition_variable.h>
8 
9 #include <new>
10 #include <stdlib.h>
11 #include <string.h>
12 
13 #include <debug.h>
14 #include <kscheduler.h>
15 #include <ksignal.h>
16 #include <int.h>
17 #include <listeners.h>
18 #include <scheduling_analysis.h>
19 #include <thread.h>
20 #include <util/AutoLock.h>
21 #include <util/atomic.h>
22 
23 
24 #define STATUS_ADDED	1
25 #define STATUS_WAITING	2
26 
27 
28 static const int kConditionVariableHashSize = 512;
29 
30 
31 struct ConditionVariableHashDefinition {
32 	typedef const void* KeyType;
33 	typedef	ConditionVariable ValueType;
34 
35 	size_t HashKey(const void* key) const
36 		{ return (size_t)key; }
37 	size_t Hash(ConditionVariable* variable) const
38 		{ return (size_t)variable->fObject; }
39 	bool Compare(const void* key, ConditionVariable* variable) const
40 		{ return key == variable->fObject; }
41 	ConditionVariable*& GetLink(ConditionVariable* variable) const
42 		{ return variable->fNext; }
43 };
44 
45 typedef BOpenHashTable<ConditionVariableHashDefinition> ConditionVariableHash;
46 static ConditionVariableHash sConditionVariableHash;
47 static rw_spinlock sConditionVariableHashLock;
48 
49 
50 static int
51 list_condition_variables(int argc, char** argv)
52 {
53 	ConditionVariable::ListAll();
54 	return 0;
55 }
56 
57 
58 static int
59 dump_condition_variable(int argc, char** argv)
60 {
61 	if (argc != 2) {
62 		print_debugger_command_usage(argv[0]);
63 		return 0;
64 	}
65 
66 	addr_t address = parse_expression(argv[1]);
67 	if (address == 0)
68 		return 0;
69 
70 	ConditionVariable* variable = sConditionVariableHash.Lookup((void*)address);
71 
72 	if (variable == NULL) {
73 		// It must be a direct pointer to a condition variable.
74 		variable = (ConditionVariable*)address;
75 	}
76 
77 	if (variable != NULL) {
78 		variable->Dump();
79 
80 		set_debug_variable("_cvar", (addr_t)variable);
81 		set_debug_variable("_object", (addr_t)variable->Object());
82 
83 	} else
84 		kprintf("no condition variable at or with key %p\n", (void*)address);
85 
86 	return 0;
87 }
88 
89 
90 // #pragma mark - ConditionVariableEntry
91 
92 
93 ConditionVariableEntry::ConditionVariableEntry()
94 	: fVariable(NULL)
95 {
96 }
97 
98 
99 ConditionVariableEntry::~ConditionVariableEntry()
100 {
101 	// We can use an "unsafe" non-atomic access of fVariable here, since we only
102 	// care whether it is non-NULL, not what its specific value is.
103 	if (fVariable != NULL)
104 		_RemoveFromVariable();
105 }
106 
107 
108 bool
109 ConditionVariableEntry::Add(const void* object)
110 {
111 	ASSERT(object != NULL);
112 
113 	InterruptsLocker _;
114 	ReadSpinLocker hashLocker(sConditionVariableHashLock);
115 
116 	ConditionVariable* variable = sConditionVariableHash.Lookup(object);
117 
118 	if (variable == NULL) {
119 		fWaitStatus = B_ENTRY_NOT_FOUND;
120 		return false;
121 	}
122 
123 	SpinLocker variableLocker(variable->fLock);
124 	hashLocker.Unlock();
125 
126 	_AddToLockedVariable(variable);
127 
128 	return true;
129 }
130 
131 
132 inline void
133 ConditionVariableEntry::_AddToLockedVariable(ConditionVariable* variable)
134 {
135 	ASSERT(fVariable == NULL);
136 
137 	fThread = thread_get_current_thread();
138 	fVariable = variable;
139 	fWaitStatus = STATUS_ADDED;
140 	fVariable->fEntries.Add(this);
141 	atomic_add(&fVariable->fEntriesCount, 1);
142 }
143 
144 
145 void
146 ConditionVariableEntry::_RemoveFromVariable()
147 {
148 	// This section is critical because it can race with _NotifyLocked on the
149 	// variable's thread, so we must not be interrupted during it.
150 	InterruptsLocker _;
151 
152 	ConditionVariable* variable = atomic_pointer_get(&fVariable);
153 	if (atomic_pointer_get_and_set(&fThread, (Thread*)NULL) == NULL) {
154 		// If fThread was already NULL, that means the variable is already
155 		// in the process of clearing us out (or already has finished doing so.)
156 		// We thus cannot access fVariable, and must spin until it is cleared.
157 		int32 tries = 0;
158 		while (atomic_pointer_get(&fVariable) != NULL) {
159 			tries++;
160 			if ((tries % 10000) == 0)
161 				panic("variable pointer was not unset for a long time!");
162 			cpu_pause();
163 		}
164 
165 		return;
166 	}
167 
168 	while (true) {
169 		if (atomic_pointer_get(&fVariable) == NULL) {
170 			// The variable must have cleared us out. Acknowledge this and return.
171 			atomic_add(&variable->fEntriesCount, -1);
172 			return;
173 		}
174 
175 		// There is of course a small race between checking the pointer and then
176 		// the try_acquire in which the variable might clear out our fVariable.
177 		// However, in the case where we were the ones to clear fThread, the
178 		// variable will notice that and then wait for us to acknowledge the
179 		// removal by decrementing fEntriesCount, as we do above; and until
180 		// we do that, we may validly use our cached pointer to the variable.
181 		if (try_acquire_spinlock(&variable->fLock))
182 			break;
183 	}
184 
185 	// We now hold the variable's lock. Remove ourselves.
186 	if (fVariable->fEntries.Contains(this))
187 		fVariable->fEntries.Remove(this);
188 
189 	atomic_pointer_set(&fVariable, (ConditionVariable*)NULL);
190 	atomic_add(&variable->fEntriesCount, -1);
191 	release_spinlock(&variable->fLock);
192 }
193 
194 
195 status_t
196 ConditionVariableEntry::Wait(uint32 flags, bigtime_t timeout)
197 {
198 #if KDEBUG
199 	if (!are_interrupts_enabled()) {
200 		panic("ConditionVariableEntry::Wait() called with interrupts "
201 			"disabled, entry: %p, variable: %p", this, fVariable);
202 		return B_ERROR;
203 	}
204 #endif
205 
206 	// The race in-between get_and_set and (re)set is irrelevant, because
207 	// if the status really is <= 0, we have already been or are about to
208 	// be removed from the variable, and nothing else is going to set the status.
209 	status_t waitStatus = atomic_get_and_set(&fWaitStatus, STATUS_WAITING);
210 	if (waitStatus <= 0) {
211 		fWaitStatus = waitStatus;
212 		return waitStatus;
213 	}
214 
215 	InterruptsLocker _;
216 
217 	thread_prepare_to_block(thread_get_current_thread(), flags,
218 		THREAD_BLOCK_TYPE_CONDITION_VARIABLE, atomic_pointer_get(&fVariable));
219 
220 	waitStatus = atomic_get(&fWaitStatus);
221 	if (waitStatus <= 0) {
222 		// We were just woken up! Unblock ourselves immediately.
223 		thread_unblock(thread_get_current_thread(), waitStatus);
224 	}
225 
226 	status_t error;
227 	if ((flags & (B_RELATIVE_TIMEOUT | B_ABSOLUTE_TIMEOUT)) != 0)
228 		error = thread_block_with_timeout(flags, timeout);
229 	else
230 		error = thread_block();
231 
232 	_RemoveFromVariable();
233 	return error;
234 }
235 
236 
237 status_t
238 ConditionVariableEntry::Wait(const void* object, uint32 flags,
239 	bigtime_t timeout)
240 {
241 	if (Add(object))
242 		return Wait(flags, timeout);
243 	return B_ENTRY_NOT_FOUND;
244 }
245 
246 
247 // #pragma mark - ConditionVariable
248 
249 
250 /*!	Initialization method for anonymous (unpublished) condition variables.
251 */
252 void
253 ConditionVariable::Init(const void* object, const char* objectType)
254 {
255 	fObject = object;
256 	fObjectType = objectType;
257 	new(&fEntries) EntryList;
258 	fEntriesCount = 0;
259 	B_INITIALIZE_SPINLOCK(&fLock);
260 
261 	T_SCHEDULING_ANALYSIS(InitConditionVariable(this, object, objectType));
262 	NotifyWaitObjectListeners(&WaitObjectListener::ConditionVariableInitialized,
263 		this);
264 }
265 
266 
267 void
268 ConditionVariable::Publish(const void* object, const char* objectType)
269 {
270 	ASSERT(object != NULL);
271 
272 	fObject = object;
273 	fObjectType = objectType;
274 	new(&fEntries) EntryList;
275 	fEntriesCount = 0;
276 	B_INITIALIZE_SPINLOCK(&fLock);
277 
278 	T_SCHEDULING_ANALYSIS(InitConditionVariable(this, object, objectType));
279 	NotifyWaitObjectListeners(&WaitObjectListener::ConditionVariableInitialized,
280 		this);
281 
282 	InterruptsWriteSpinLocker _(sConditionVariableHashLock);
283 
284 	ASSERT_PRINT(sConditionVariableHash.Lookup(object) == NULL,
285 		"condition variable: %p\n", sConditionVariableHash.Lookup(object));
286 
287 	sConditionVariableHash.InsertUnchecked(this);
288 }
289 
290 
291 void
292 ConditionVariable::Unpublish()
293 {
294 	ASSERT(fObject != NULL);
295 
296 	InterruptsLocker _;
297 	WriteSpinLocker hashLocker(sConditionVariableHashLock);
298 	SpinLocker selfLocker(fLock);
299 
300 #if KDEBUG
301 	ConditionVariable* variable = sConditionVariableHash.Lookup(fObject);
302 	if (variable != this) {
303 		panic("Condition variable %p not published, found: %p", this, variable);
304 		return;
305 	}
306 #endif
307 
308 	sConditionVariableHash.RemoveUnchecked(this);
309 	fObject = NULL;
310 	fObjectType = NULL;
311 
312 	hashLocker.Unlock();
313 
314 	if (!fEntries.IsEmpty())
315 		_NotifyLocked(true, B_ENTRY_NOT_FOUND);
316 }
317 
318 
319 void
320 ConditionVariable::Add(ConditionVariableEntry* entry)
321 {
322 	InterruptsSpinLocker _(fLock);
323 	entry->_AddToLockedVariable(this);
324 }
325 
326 
327 status_t
328 ConditionVariable::Wait(uint32 flags, bigtime_t timeout)
329 {
330 	ConditionVariableEntry entry;
331 	Add(&entry);
332 	return entry.Wait(flags, timeout);
333 }
334 
335 
336 /*static*/ void
337 ConditionVariable::NotifyOne(const void* object, status_t result)
338 {
339 	InterruptsReadSpinLocker locker(sConditionVariableHashLock);
340 	ConditionVariable* variable = sConditionVariableHash.Lookup(object);
341 	locker.Unlock();
342 	if (variable == NULL)
343 		return;
344 
345 	variable->NotifyOne(result);
346 }
347 
348 
349 /*static*/ void
350 ConditionVariable::NotifyAll(const void* object, status_t result)
351 {
352 	InterruptsReadSpinLocker locker(sConditionVariableHashLock);
353 	ConditionVariable* variable = sConditionVariableHash.Lookup(object);
354 	locker.Unlock();
355 	if (variable == NULL)
356 		return;
357 
358 	variable->NotifyAll(result);
359 }
360 
361 
362 void
363 ConditionVariable::_Notify(bool all, status_t result)
364 {
365 	InterruptsSpinLocker _(fLock);
366 
367 	if (!fEntries.IsEmpty()) {
368 		if (result > B_OK) {
369 			panic("tried to notify with invalid result %" B_PRId32 "\n", result);
370 			result = B_ERROR;
371 		}
372 
373 		_NotifyLocked(all, result);
374 	}
375 }
376 
377 
378 /*! Called with interrupts disabled and the condition variable's spinlock held.
379  */
380 void
381 ConditionVariable::_NotifyLocked(bool all, status_t result)
382 {
383 	// Dequeue and wake up the blocked threads.
384 	while (ConditionVariableEntry* entry = fEntries.RemoveHead()) {
385 		Thread* thread = atomic_pointer_get_and_set(&entry->fThread, (Thread*)NULL);
386 		if (thread == NULL) {
387 			// The entry must be in the process of trying to remove itself from us.
388 			// Clear its variable and wait for it to acknowledge this in fEntriesCount,
389 			// as it is the one responsible for decrementing that.
390 			const int32 oldCount = atomic_get(&fEntriesCount);
391 			atomic_pointer_set(&entry->fVariable, (ConditionVariable*)NULL);
392 
393 			// As fEntriesCount is only modified while our lock is held, nothing else
394 			// will modify it while we are spinning, since we hold it at present.
395 			int32 tries = 0;
396 			while (atomic_get(&fEntriesCount) == oldCount) {
397 				tries++;
398 				if ((tries % 10000) == 0)
399 					panic("entries count was not decremented for a long time!");
400 				cpu_pause();
401 			}
402 		} else {
403 			status_t waitStatus = atomic_get_and_set(&entry->fWaitStatus, result);
404 
405 			SpinLocker threadLocker(thread->scheduler_lock);
406 			if (waitStatus == STATUS_WAITING && thread->state != B_THREAD_WAITING) {
407 				// The thread is not in B_THREAD_WAITING state, so we must unblock it early,
408 				// in case it tries to re-block itself immediately after we unset fVariable.
409 				thread_unblock_locked(thread, result);
410 				waitStatus = result;
411 			}
412 
413 			// No matter what the thread is doing, as we were the ones to clear its
414 			// fThread, so we are the ones responsible for decrementing fEntriesCount.
415 			// (We may not validly access the entry once we unset its fVariable.)
416 			atomic_pointer_set(&entry->fVariable, (ConditionVariable*)NULL);
417 			atomic_add(&fEntriesCount, -1);
418 
419 			// If the thread was in B_THREAD_WAITING state, we unblock it after unsetting
420 			// fVariable, because otherwise it will wake up before thread_unblock returns
421 			// and spin while waiting for us to do so.
422 			if (waitStatus == STATUS_WAITING)
423 				thread_unblock_locked(thread, result);
424 		}
425 
426 		if (!all)
427 			break;
428 	}
429 }
430 
431 
432 /*static*/ void
433 ConditionVariable::ListAll()
434 {
435 	kprintf("  variable      object (type)                waiting threads\n");
436 	kprintf("------------------------------------------------------------\n");
437 	ConditionVariableHash::Iterator it(&sConditionVariableHash);
438 	while (ConditionVariable* variable = it.Next()) {
439 		// count waiting threads
440 		int count = variable->fEntries.Count();
441 
442 		kprintf("%p  %p  %-20s %15d\n", variable, variable->fObject,
443 			variable->fObjectType, count);
444 	}
445 }
446 
447 
448 void
449 ConditionVariable::Dump() const
450 {
451 	kprintf("condition variable %p\n", this);
452 	kprintf("  object:  %p (%s)\n", fObject, fObjectType);
453 	kprintf("  threads:");
454 
455 	for (EntryList::ConstIterator it = fEntries.GetIterator();
456 		 ConditionVariableEntry* entry = it.Next();) {
457 		kprintf(" %" B_PRId32, entry->fThread->id);
458 	}
459 	kprintf("\n");
460 }
461 
462 
463 // #pragma mark -
464 
465 
466 void
467 condition_variable_init()
468 {
469 	new(&sConditionVariableHash) ConditionVariableHash;
470 
471 	status_t error = sConditionVariableHash.Init(kConditionVariableHashSize);
472 	if (error != B_OK) {
473 		panic("condition_variable_init(): Failed to init hash table: %s",
474 			strerror(error));
475 	}
476 
477 	add_debugger_command_etc("cvar", &dump_condition_variable,
478 		"Dump condition variable info",
479 		"<address>\n"
480 		"Prints info for the specified condition variable.\n"
481 		"  <address>  - Address of the condition variable or the object it is\n"
482 		"               associated with.\n", 0);
483 	add_debugger_command_etc("cvars", &list_condition_variables,
484 		"List condition variables",
485 		"\n"
486 		"Lists all existing condition variables\n", 0);
487 }
488