1 /* 2 * Copyright 2007-2011, Ingo Weinhold, ingo_weinhold@gmx.de. 3 * Copyright 2019-2023, 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 // #pragma mark - ConditionVariableEntry 51 52 53 ConditionVariableEntry::ConditionVariableEntry() 54 : fVariable(NULL) 55 { 56 } 57 58 59 ConditionVariableEntry::~ConditionVariableEntry() 60 { 61 // We can use an "unsafe" non-atomic access of fVariable here, since we only 62 // care whether it is non-NULL, not what its specific value is. 63 if (fVariable != NULL) 64 _RemoveFromVariable(); 65 } 66 67 68 bool 69 ConditionVariableEntry::Add(const void* object) 70 { 71 ASSERT(object != NULL); 72 73 InterruptsLocker _; 74 ReadSpinLocker hashLocker(sConditionVariableHashLock); 75 76 ConditionVariable* variable = sConditionVariableHash.Lookup(object); 77 78 if (variable == NULL) { 79 fWaitStatus = B_ENTRY_NOT_FOUND; 80 return false; 81 } 82 83 SpinLocker variableLocker(variable->fLock); 84 hashLocker.Unlock(); 85 86 _AddToLockedVariable(variable); 87 88 return true; 89 } 90 91 92 ConditionVariable* 93 ConditionVariableEntry::Variable() const 94 { 95 return atomic_pointer_get(&fVariable); 96 } 97 98 99 inline void 100 ConditionVariableEntry::_AddToLockedVariable(ConditionVariable* variable) 101 { 102 ASSERT(fVariable == NULL); 103 104 fThread = thread_get_current_thread(); 105 fVariable = variable; 106 fWaitStatus = STATUS_ADDED; 107 fVariable->fEntries.Add(this); 108 atomic_add(&fVariable->fEntriesCount, 1); 109 } 110 111 112 void 113 ConditionVariableEntry::_RemoveFromVariable() 114 { 115 // This section is critical because it can race with _NotifyLocked on the 116 // variable's thread, so we must not be interrupted during it. 117 InterruptsLocker _; 118 119 ConditionVariable* variable = atomic_pointer_get(&fVariable); 120 if (atomic_pointer_get_and_set(&fThread, (Thread*)NULL) == NULL) { 121 // If fThread was already NULL, that means the variable is already 122 // in the process of clearing us out (or already has finished doing so.) 123 // We thus cannot access fVariable, and must spin until it is cleared. 124 int32 tries = 0; 125 while (atomic_pointer_get(&fVariable) != NULL) { 126 tries++; 127 if ((tries % 10000) == 0) 128 dprintf("variable pointer was not unset for a long time!\n"); 129 cpu_pause(); 130 } 131 132 return; 133 } 134 135 while (true) { 136 if (atomic_pointer_get(&fVariable) == NULL) { 137 // The variable must have cleared us out. Acknowledge this and return. 138 atomic_add(&variable->fEntriesCount, -1); 139 return; 140 } 141 142 // There is of course a small race between checking the pointer and then 143 // the try_acquire in which the variable might clear out our fVariable. 144 // However, in the case where we were the ones to clear fThread, the 145 // variable will notice that and then wait for us to acknowledge the 146 // removal by decrementing fEntriesCount, as we do above; and until 147 // we do that, we may validly use our cached pointer to the variable. 148 if (try_acquire_spinlock(&variable->fLock)) 149 break; 150 } 151 152 // We now hold the variable's lock. Remove ourselves. 153 if (fVariable->fEntries.Contains(this)) 154 fVariable->fEntries.Remove(this); 155 156 atomic_pointer_set(&fVariable, (ConditionVariable*)NULL); 157 atomic_add(&variable->fEntriesCount, -1); 158 release_spinlock(&variable->fLock); 159 } 160 161 162 status_t 163 ConditionVariableEntry::Wait(uint32 flags, bigtime_t timeout) 164 { 165 #if KDEBUG 166 if (!are_interrupts_enabled()) { 167 panic("ConditionVariableEntry::Wait() called with interrupts " 168 "disabled, entry: %p, variable: %p", this, fVariable); 169 return B_ERROR; 170 } 171 #endif 172 173 ConditionVariable* variable = atomic_pointer_get(&fVariable); 174 if (variable == NULL) 175 return fWaitStatus; 176 177 if ((flags & B_RELATIVE_TIMEOUT) != 0 && timeout <= 0) { 178 _RemoveFromVariable(); 179 return B_WOULD_BLOCK; 180 } 181 182 InterruptsLocker _; 183 SpinLocker schedulerLocker(thread_get_current_thread()->scheduler_lock); 184 185 if (fWaitStatus <= 0) 186 return fWaitStatus; 187 fWaitStatus = STATUS_WAITING; 188 189 thread_prepare_to_block(thread_get_current_thread(), flags, 190 THREAD_BLOCK_TYPE_CONDITION_VARIABLE, variable); 191 192 schedulerLocker.Unlock(); 193 194 status_t error; 195 if ((flags & (B_RELATIVE_TIMEOUT | B_ABSOLUTE_TIMEOUT)) != 0) 196 error = thread_block_with_timeout(flags, timeout); 197 else 198 error = thread_block(); 199 200 _RemoveFromVariable(); 201 202 // We need to always return the actual wait status, if we received one. 203 if (fWaitStatus <= 0) 204 return fWaitStatus; 205 206 return error; 207 } 208 209 210 status_t 211 ConditionVariableEntry::Wait(const void* object, uint32 flags, 212 bigtime_t timeout) 213 { 214 if (Add(object)) 215 return Wait(flags, timeout); 216 return B_ENTRY_NOT_FOUND; 217 } 218 219 220 // #pragma mark - ConditionVariable 221 222 223 /*! Initialization method for anonymous (unpublished) condition variables. 224 */ 225 void 226 ConditionVariable::Init(const void* object, const char* objectType) 227 { 228 fObject = object; 229 fObjectType = objectType; 230 new(&fEntries) EntryList; 231 fEntriesCount = 0; 232 B_INITIALIZE_SPINLOCK(&fLock); 233 234 T_SCHEDULING_ANALYSIS(InitConditionVariable(this, object, objectType)); 235 NotifyWaitObjectListeners(&WaitObjectListener::ConditionVariableInitialized, 236 this); 237 } 238 239 240 void 241 ConditionVariable::Publish(const void* object, const char* objectType) 242 { 243 ASSERT(object != NULL); 244 245 Init(object, objectType); 246 247 InterruptsWriteSpinLocker _(sConditionVariableHashLock); 248 249 ASSERT_PRINT(sConditionVariableHash.Lookup(object) == NULL, 250 "condition variable: %p\n", sConditionVariableHash.Lookup(object)); 251 252 sConditionVariableHash.InsertUnchecked(this); 253 } 254 255 256 void 257 ConditionVariable::Unpublish() 258 { 259 ASSERT(fObject != NULL); 260 261 InterruptsLocker _; 262 WriteSpinLocker hashLocker(sConditionVariableHashLock); 263 SpinLocker selfLocker(fLock); 264 265 #if KDEBUG 266 ConditionVariable* variable = sConditionVariableHash.Lookup(fObject); 267 if (variable != this) { 268 panic("Condition variable %p not published, found: %p", this, variable); 269 return; 270 } 271 #endif 272 273 sConditionVariableHash.RemoveUnchecked(this); 274 fObject = NULL; 275 fObjectType = NULL; 276 277 hashLocker.Unlock(); 278 279 if (!fEntries.IsEmpty()) 280 _NotifyLocked(true, B_ENTRY_NOT_FOUND); 281 } 282 283 284 void 285 ConditionVariable::Add(ConditionVariableEntry* entry) 286 { 287 InterruptsSpinLocker _(fLock); 288 entry->_AddToLockedVariable(this); 289 } 290 291 292 status_t 293 ConditionVariable::Wait(uint32 flags, bigtime_t timeout) 294 { 295 ConditionVariableEntry entry; 296 Add(&entry); 297 return entry.Wait(flags, timeout); 298 } 299 300 301 status_t 302 ConditionVariable::Wait(mutex* lock, uint32 flags, bigtime_t timeout) 303 { 304 ConditionVariableEntry entry; 305 Add(&entry); 306 mutex_unlock(lock); 307 status_t res = entry.Wait(flags, timeout); 308 mutex_lock(lock); 309 return res; 310 } 311 312 313 status_t 314 ConditionVariable::Wait(recursive_lock* lock, uint32 flags, bigtime_t timeout) 315 { 316 ConditionVariableEntry entry; 317 Add(&entry); 318 int32 recursion = recursive_lock_get_recursion(lock); 319 320 for (int32 i = 0; i < recursion; i++) 321 recursive_lock_unlock(lock); 322 323 status_t res = entry.Wait(flags, timeout); 324 325 for (int32 i = 0; i < recursion; i++) 326 recursive_lock_lock(lock); 327 328 return res; 329 } 330 331 332 /*static*/ int32 333 ConditionVariable::NotifyOne(const void* object, status_t result) 334 { 335 return _Notify(object, false, result); 336 } 337 338 339 /*static*/ int32 340 ConditionVariable::NotifyAll(const void* object, status_t result) 341 { 342 return _Notify(object, true, result); 343 } 344 345 346 /*static*/ int32 347 ConditionVariable::_Notify(const void* object, bool all, status_t result) 348 { 349 InterruptsLocker ints; 350 ReadSpinLocker hashLocker(sConditionVariableHashLock); 351 ConditionVariable* variable = sConditionVariableHash.Lookup(object); 352 if (variable == NULL) 353 return 0; 354 SpinLocker variableLocker(variable->fLock); 355 hashLocker.Unlock(); 356 357 return variable->_NotifyLocked(all, result); 358 } 359 360 361 int32 362 ConditionVariable::_Notify(bool all, status_t result) 363 { 364 InterruptsSpinLocker _(fLock); 365 if (!fEntries.IsEmpty()) { 366 if (result > B_OK) { 367 panic("tried to notify with invalid result %" B_PRId32 "\n", result); 368 result = B_ERROR; 369 } 370 371 return _NotifyLocked(all, result); 372 } 373 return 0; 374 } 375 376 377 /*! Called with interrupts disabled and the condition variable's spinlock held. 378 */ 379 int32 380 ConditionVariable::_NotifyLocked(bool all, status_t result) 381 { 382 int32 notified = 0; 383 384 // Dequeue and wake up the blocked threads. 385 while (ConditionVariableEntry* entry = fEntries.RemoveHead()) { 386 Thread* thread = atomic_pointer_get_and_set(&entry->fThread, (Thread*)NULL); 387 if (thread == NULL) { 388 // The entry must be in the process of trying to remove itself from us. 389 // Clear its variable and wait for it to acknowledge this in fEntriesCount, 390 // as it is the one responsible for decrementing that. 391 const int32 oldCount = atomic_get(&fEntriesCount); 392 atomic_pointer_set(&entry->fVariable, (ConditionVariable*)NULL); 393 394 // As fEntriesCount is only modified while our lock is held, nothing else 395 // will modify it while we are spinning, since we hold it at present. 396 int32 tries = 0; 397 while (atomic_get(&fEntriesCount) == oldCount) { 398 tries++; 399 if ((tries % 10000) == 0) 400 dprintf("entries count was not decremented for a long time!\n"); 401 cpu_pause(); 402 } 403 } else { 404 SpinLocker schedulerLocker(thread->scheduler_lock); 405 status_t lastWaitStatus = entry->fWaitStatus; 406 entry->fWaitStatus = result; 407 if (lastWaitStatus == STATUS_WAITING && thread->state != B_THREAD_WAITING) { 408 // The thread is not in B_THREAD_WAITING state, so we must unblock it early, 409 // in case it tries to re-block itself immediately after we unset fVariable. 410 thread_unblock_locked(thread, result); 411 lastWaitStatus = result; 412 } 413 414 // No matter what the thread is doing, as we were the ones to clear its 415 // fThread, so we are the ones responsible for decrementing fEntriesCount. 416 // (We may not validly access the entry once we unset its fVariable.) 417 atomic_pointer_set(&entry->fVariable, (ConditionVariable*)NULL); 418 atomic_add(&fEntriesCount, -1); 419 420 // If the thread was in B_THREAD_WAITING state, we unblock it after unsetting 421 // fVariable, because otherwise it will wake up before thread_unblock returns 422 // and spin while waiting for us to do so. 423 if (lastWaitStatus == STATUS_WAITING) 424 thread_unblock_locked(thread, result); 425 426 notified++; 427 } 428 429 if (!all) 430 break; 431 } 432 433 return notified; 434 } 435 436 437 // #pragma mark - 438 439 440 /*static*/ void 441 ConditionVariable::ListAll() 442 { 443 kprintf(" variable object (type) waiting threads\n"); 444 kprintf("------------------------------------------------------------\n"); 445 ConditionVariableHash::Iterator it(&sConditionVariableHash); 446 while (ConditionVariable* variable = it.Next()) { 447 // count waiting threads 448 int count = variable->fEntries.Count(); 449 450 kprintf("%p %p %-20s %15d\n", variable, variable->fObject, 451 variable->fObjectType, count); 452 } 453 } 454 455 456 void 457 ConditionVariable::Dump() const 458 { 459 kprintf("condition variable %p\n", this); 460 kprintf(" object: %p (%s)\n", fObject, fObjectType); 461 kprintf(" threads:"); 462 463 for (EntryList::ConstIterator it = fEntries.GetIterator(); 464 ConditionVariableEntry* entry = it.Next();) { 465 kprintf(" %" B_PRId32, entry->fThread->id); 466 } 467 kprintf("\n"); 468 } 469 470 471 static int 472 list_condition_variables(int argc, char** argv) 473 { 474 ConditionVariable::ListAll(); 475 return 0; 476 } 477 478 479 static int 480 dump_condition_variable(int argc, char** argv) 481 { 482 if (argc != 2) { 483 print_debugger_command_usage(argv[0]); 484 return 0; 485 } 486 487 addr_t address = parse_expression(argv[1]); 488 if (address == 0) 489 return 0; 490 491 ConditionVariable* variable = sConditionVariableHash.Lookup((void*)address); 492 493 if (variable == NULL) { 494 // It must be a direct pointer to a condition variable. 495 variable = (ConditionVariable*)address; 496 } 497 498 if (variable != NULL) { 499 variable->Dump(); 500 501 set_debug_variable("_cvar", (addr_t)variable); 502 set_debug_variable("_object", (addr_t)variable->Object()); 503 504 } else 505 kprintf("no condition variable at or with key %p\n", (void*)address); 506 507 return 0; 508 } 509 510 511 // #pragma mark - 512 513 514 void 515 condition_variable_init() 516 { 517 new(&sConditionVariableHash) ConditionVariableHash; 518 519 status_t error = sConditionVariableHash.Init(kConditionVariableHashSize); 520 if (error != B_OK) { 521 panic("condition_variable_init(): Failed to init hash table: %s", 522 strerror(error)); 523 } 524 525 add_debugger_command_etc("cvar", &dump_condition_variable, 526 "Dump condition variable info", 527 "<address>\n" 528 "Prints info for the specified condition variable.\n" 529 " <address> - Address of the condition variable or the object it is\n" 530 " associated with.\n", 0); 531 add_debugger_command_etc("cvars", &list_condition_variables, 532 "List condition variables", 533 "\n" 534 "Lists all published condition variables\n", 0); 535 } 536 537 538 ssize_t 539 debug_condition_variable_type_strlcpy(ConditionVariable* cvar, char* name, size_t size) 540 { 541 const int32 typePointerOffset = offsetof(ConditionVariable, fObjectType); 542 543 const char* pointer; 544 status_t status = debug_memcpy(B_CURRENT_TEAM, &pointer, 545 (int8*)cvar + typePointerOffset, sizeof(const char*)); 546 if (status != B_OK) 547 return status; 548 549 return debug_strlcpy(B_CURRENT_TEAM, name, pointer, size); 550 } 551