| 6 |
| 7 | #include <algorithm> |
| 8 | #include <limits> |
| 9 | #include <vector> |
| 10 |
| 11 | #include "base/debug/activity_tracker.h" |
| 12 | #include "base/logging.h" |
| 13 | #include "base/optional.h" |
| 14 | #include "base/synchronization/condition_variable.h" |
| 15 | #include "base/synchronization/lock.h" |
| 16 | #include "base/synchronization/waitable_event.h" |
| 17 | #include "base/threading/scoped_blocking_call.h" |
| 18 | #include "base/threading/thread_restrictions.h" |
| 19 | #include "base/time/time.h" |
| 20 | #include "base/time/time_override.h" |
| 21 |
| 22 | // ----------------------------------------------------------------------------- |
| 23 | // A WaitableEvent on POSIX is implemented as a wait-list. Currently we don't |
| 24 | // support cross-process events (where one process can signal an event which |
| 25 | // others are waiting on). Because of this, we can avoid having one thread per |
| 26 | // listener in several cases. |
| 27 | // |
| 28 | // The WaitableEvent maintains a list of waiters, protected by a lock. Each |
| 29 | // waiter is either an async wait, in which case we have a Task and the |
| 30 | // MessageLoop to run it on, or a blocking wait, in which case we have the |
| 31 | // condition variable to signal. |
| 32 | // |
| 33 | // Waiting involves grabbing the lock and adding oneself to the wait list. Async |
| 34 | // waits can be canceled, which means grabbing the lock and removing oneself |
| 35 | // from the list. |
| 36 | // |
| 37 | // Waiting on multiple events is handled by adding a single, synchronous wait to |
| 38 | // the wait-list of many events. An event passes a pointer to itself when |
| 39 | // firing a waiter and so we can store that pointer to find out which event |
| 40 | // triggered. |
| 41 | // ----------------------------------------------------------------------------- |
| 42 |
| 43 | namespace base { |
| 44 |
| 45 | // ----------------------------------------------------------------------------- |
| 46 | // This is just an abstract base class for waking the two types of waiters |
| 47 | // ----------------------------------------------------------------------------- |
| 48 | WaitableEvent::WaitableEvent(ResetPolicy reset_policy, |
| 49 | InitialState initial_state) |
| 50 | : kernel_(new WaitableEventKernel(reset_policy, initial_state)) {} |
| 51 |
| 52 | WaitableEvent::~WaitableEvent() = default; |
| 53 |
| 54 | void WaitableEvent::Reset() { |
| 55 | base::AutoLock locked(kernel_->lock_); |
| 56 | kernel_->signaled_ = false; |
| 57 | } |
| 58 |
| 59 | void WaitableEvent::Signal() { |
| 60 | base::AutoLock locked(kernel_->lock_); |
| 61 |
| 62 | if (kernel_->signaled_) |
| 63 | return; |
| 64 |
| 65 | if (kernel_->manual_reset_) { |
| 66 | SignalAll(); |
| 67 | kernel_->signaled_ = true; |
| 68 | } else { |
| 69 | // In the case of auto reset, if no waiters were woken, we remain |
| 70 | // signaled. |
| 71 | if (!SignalOne()) |
| 72 | kernel_->signaled_ = true; |
| 73 | } |
| 74 | } |
| 75 |
| 76 | bool WaitableEvent::IsSignaled() { |
| 77 | base::AutoLock locked(kernel_->lock_); |
| 78 |
| 79 | const bool result = kernel_->signaled_; |
| 80 | if (result && !kernel_->manual_reset_) |
| 81 | kernel_->signaled_ = false; |
| 82 | return result; |
| 83 | } |
| 84 |
| 85 | // ----------------------------------------------------------------------------- |
| 86 | // Synchronous waits |
| 87 |
| 88 | // ----------------------------------------------------------------------------- |
| 89 | // This is a synchronous waiter. The thread is waiting on the given condition |
| 90 | // variable and the fired flag in this object. |
| 91 | // ----------------------------------------------------------------------------- |
| 92 | class SyncWaiter : public WaitableEvent::Waiter { |
| 93 | public: |
| 94 | SyncWaiter() |
| 95 | : fired_(false), signaling_event_(nullptr), lock_(), cv_(&lock_) {} |
| 96 |
| 97 | bool Fire(WaitableEvent* signaling_event) override { |
| 98 | base::AutoLock locked(lock_); |
| 99 |
| 100 | if (fired_) |
| 101 | return false; |
| 102 |
| 103 | fired_ = true; |
| 104 | signaling_event_ = signaling_event; |
| 105 |
| 106 | cv_.Broadcast(); |
| 107 |
| 108 | // Unlike AsyncWaiter objects, SyncWaiter objects are stack-allocated on |
| 109 | // the blocking thread's stack. There is no |delete this;| in Fire. The |
| 110 | // SyncWaiter object is destroyed when it goes out of scope. |
| 111 |
| 112 | return true; |
| 113 | } |
| 114 |
| 115 | WaitableEvent* signaling_event() const { |
| 116 | return signaling_event_; |
| 117 | } |
| 118 |
| 119 | // --------------------------------------------------------------------------- |
| 120 | // These waiters are always stack allocated and don't delete themselves. Thus |
| 121 | // there's no problem and the ABA tag is the same as the object pointer. |
| 122 | // --------------------------------------------------------------------------- |
| 123 | bool Compare(void* tag) override { return this == tag; } |
| 124 |
| 125 | // --------------------------------------------------------------------------- |
| 126 | // Called with lock held. |
| 127 | // --------------------------------------------------------------------------- |
| 128 | bool fired() const { |
| 129 | return fired_; |
| 130 | } |
| 131 |
| 132 | // --------------------------------------------------------------------------- |
| 133 | // During a TimedWait, we need a way to make sure that an auto-reset |
| 134 | // WaitableEvent doesn't think that this event has been signaled between |
| 135 | // unlocking it and removing it from the wait-list. Called with lock held. |
| 136 | // --------------------------------------------------------------------------- |
| 137 | void Disable() { |
| 138 | fired_ = true; |
| 139 | } |
| 140 |
| 141 | base::Lock* lock() { |
| 142 | return &lock_; |
| 143 | } |
| 144 |
| 145 | base::ConditionVariable* cv() { |
| 146 | return &cv_; |
| 147 | } |
| 148 |
| 149 | private: |
| 150 | bool fired_; |
| 151 | WaitableEvent* signaling_event_; // The WaitableEvent which woke us |
| 152 | base::Lock lock_; |
| 153 | base::ConditionVariable cv_; |
| 154 | }; |
| 155 |
| 156 | void WaitableEvent::Wait() { |
| 157 | bool result = TimedWait(TimeDelta::Max()); |
| 158 | DCHECK(result) << "TimedWait() should never fail with infinite timeout"; |
| 159 | } |
| 160 |
| 161 | bool WaitableEvent::TimedWait(const TimeDelta& wait_delta) { |
| 162 | if (wait_delta <= TimeDelta()) |
| 163 | return IsSignaled(); |
| 164 |
| 165 | // Record the event that this thread is blocking upon (for hang diagnosis) and |
| 166 | // consider it blocked for scheduling purposes. Ignore this for non-blocking |
| 167 | // WaitableEvents. |
| 168 | Optional<debug::ScopedEventWaitActivity> event_activity; |
| 169 | Optional<internal::ScopedBlockingCallWithBaseSyncPrimitives> |
| 170 | scoped_blocking_call; |
| 171 | if (waiting_is_blocking_) { |
| 172 | event_activity.emplace(this); |
| 173 | scoped_blocking_call.emplace(FROM_HERE, BlockingType::MAY_BLOCK); |
| 174 | } |
| 175 |
| 176 | kernel_->lock_.Acquire(); |
| 177 | if (kernel_->signaled_) { |
| 178 | if (!kernel_->manual_reset_) { |
| 179 | // In this case we were signaled when we had no waiters. Now that |
| 180 | // someone has waited upon us, we can automatically reset. |
| 181 | kernel_->signaled_ = false; |
| 182 | } |
| 183 |
| 184 | kernel_->lock_.Release(); |
| 185 | return true; |
| 186 | } |
| 187 |
| 188 | SyncWaiter sw; |
| 189 | if (!waiting_is_blocking_) |
| 190 | sw.cv()->declare_only_used_while_idle(); |
| 191 | sw.lock()->Acquire(); |
| 192 |
| 193 | Enqueue(&sw); |
| 194 | kernel_->lock_.Release(); |
| 195 | // We are violating locking order here by holding the SyncWaiter lock but not |
| 196 | // the WaitableEvent lock. However, this is safe because we don't lock |lock_| |
| 197 | // again before unlocking it. |
| 198 |
| 199 | // TimeTicks takes care of overflow but we special case is_max() nonetheless |
| 200 | // to avoid invoking TimeTicksNowIgnoringOverride() unnecessarily (same for |
| 201 | // the increment step of the for loop if the condition variable returns |
| 202 | // early). Ref: https://crbug.com/910524#c7 |
| 203 | const TimeTicks end_time = |
| 204 | wait_delta.is_max() ? TimeTicks::Max() |
| 205 | : subtle::TimeTicksNowIgnoringOverride() + wait_delta; |
| 206 | for (TimeDelta remaining = wait_delta; remaining > TimeDelta() && !sw.fired(); |
| 207 | remaining = end_time.is_max() |
| 208 | ? TimeDelta::Max() |
| 209 | : end_time - subtle::TimeTicksNowIgnoringOverride()) { |
| 210 | if (end_time.is_max()) |
| 211 | sw.cv()->Wait(); |
| 212 | else |
| 213 | sw.cv()->TimedWait(remaining); |
| 214 | } |
| 215 |
| 216 | // Get the SyncWaiter signaled state before releasing the lock. |
| 217 | const bool return_value = sw.fired(); |
| 218 |
| 219 | // We can't acquire |lock_| before releasing the SyncWaiter lock (because of |
| 220 | // locking order), however, in between the two a signal could be fired and |
| 221 | // |sw| would accept it, however we will still return false, so the signal |
| 222 | // would be lost on an auto-reset WaitableEvent. Thus we call Disable which |
| 223 | // makes sw::Fire return false. |
| 224 | sw.Disable(); |
| 225 | sw.lock()->Release(); |
| 226 |
| 227 | // This is a bug that has been enshrined in the interface of WaitableEvent |
| 228 | // now: |Dequeue| is called even when |sw.fired()| is true, even though it'll |
| 229 | // always return false in that case. However, taking the lock ensures that |
| 230 | // |Signal| has completed before we return and means that a WaitableEvent can |
| 231 | // synchronise its own destruction. |
| 232 | kernel_->lock_.Acquire(); |
| 233 | kernel_->Dequeue(&sw, &sw); |
| 234 | kernel_->lock_.Release(); |
| 235 |
| 236 | return return_value; |
| 237 | } |
| 238 |
| 239 | // ----------------------------------------------------------------------------- |
| 240 | // Synchronous waiting on multiple objects. |
| 241 |
| 242 | static bool // StrictWeakOrdering |
| 243 | cmp_fst_addr(const std::pair<WaitableEvent*, unsigned> &a, |
| 244 | const std::pair<WaitableEvent*, unsigned> &b) { |
| 245 | return a.first < b.first; |
| 246 | } |
| 247 |
| 248 | // static |
| 249 | // NO_THREAD_SAFETY_ANALYSIS: Complex control flow. |
| 250 | size_t WaitableEvent::WaitMany(WaitableEvent** raw_waitables, |
| 251 | size_t count) NO_THREAD_SAFETY_ANALYSIS { |
| 252 | DCHECK(count) << "Cannot wait on no events"; |
| 253 | internal::ScopedBlockingCallWithBaseSyncPrimitives scoped_blocking_call( |
| 254 | FROM_HERE, BlockingType::MAY_BLOCK); |
| 255 | // Record an event (the first) that this thread is blocking upon. |
| 256 | debug::ScopedEventWaitActivity event_activity(raw_waitables[0]); |
| 257 |
| 258 | // We need to acquire the locks in a globally consistent order. Thus we sort |
| 259 | // the array of waitables by address. We actually sort a pairs so that we can |
| 260 | // map back to the original index values later. |
| 261 | std::vector<std::pair<WaitableEvent*, size_t> > waitables; |
| 262 | waitables.reserve(count); |
| 263 | for (size_t i = 0; i < count; ++i) |
| 264 | waitables.push_back(std::make_pair(raw_waitables[i], i)); |
| 265 |
| 266 | DCHECK_EQ(count, waitables.size()); |
| 267 |
| 268 | sort(waitables.begin(), waitables.end(), cmp_fst_addr); |
| 269 |
| 270 | // The set of waitables must be distinct. Since we have just sorted by |
| 271 | // address, we can check this cheaply by comparing pairs of consecutive |
| 272 | // elements. |
| 273 | for (size_t i = 0; i < waitables.size() - 1; ++i) { |
| 274 | DCHECK(waitables[i].first != waitables[i+1].first); |
| 275 | } |
| 276 |
| 277 | SyncWaiter sw; |
| 278 |
| 279 | const size_t r = EnqueueMany(&waitables[0], count, &sw); |
| 280 | if (r < count) { |
| 281 | // One of the events is already signaled. The SyncWaiter has not been |
| 282 | // enqueued anywhere. |
| 283 | return waitables[r].second; |
| 284 | } |
| 285 |
| 286 | // At this point, we hold the locks on all the WaitableEvents and we have |
| 287 | // enqueued our waiter in them all. |
| 288 | sw.lock()->Acquire(); |
| 289 | // Release the WaitableEvent locks in the reverse order |
| 290 | for (size_t i = 0; i < count; ++i) { |
| 291 | waitables[count - (1 + i)].first->kernel_->lock_.Release(); |
| 292 | } |
| 293 |
| 294 | for (;;) { |
| 295 | if (sw.fired()) |
| 296 | break; |
| 297 |
| 298 | sw.cv()->Wait(); |
| 299 | } |
| 300 | sw.lock()->Release(); |
| 301 |
| 302 | // The address of the WaitableEvent which fired is stored in the SyncWaiter. |
| 303 | WaitableEvent *const signaled_event = sw.signaling_event(); |
| 304 | // This will store the index of the raw_waitables which fired. |
| 305 | size_t signaled_index = 0; |
| 306 |
| 307 | // Take the locks of each WaitableEvent in turn (except the signaled one) and |
| 308 | // remove our SyncWaiter from the wait-list |
| 309 | for (size_t i = 0; i < count; ++i) { |
| 310 | if (raw_waitables[i] != signaled_event) { |
| 311 | raw_waitables[i]->kernel_->lock_.Acquire(); |
| 312 | // There's no possible ABA issue with the address of the SyncWaiter here |
| 313 | // because it lives on the stack. Thus the tag value is just the pointer |
| 314 | // value again. |
| 315 | raw_waitables[i]->kernel_->Dequeue(&sw, &sw); |
| 316 | raw_waitables[i]->kernel_->lock_.Release(); |
| 317 | } else { |
| 318 | // By taking this lock here we ensure that |Signal| has completed by the |
| 319 | // time we return, because |Signal| holds this lock. This matches the |
| 320 | // behaviour of |Wait| and |TimedWait|. |
| 321 | raw_waitables[i]->kernel_->lock_.Acquire(); |
| 322 | raw_waitables[i]->kernel_->lock_.Release(); |
| 323 | signaled_index = i; |
| 324 | } |
| 325 | } |
| 326 |
| 327 | return signaled_index; |
| 328 | } |
| 329 |
| 330 | // ----------------------------------------------------------------------------- |
| 331 | // If return value == count: |
| 332 | // The locks of the WaitableEvents have been taken in order and the Waiter has |
| 333 | // been enqueued in the wait-list of each. None of the WaitableEvents are |
| 334 | // currently signaled |
| 335 | // else: |
| 336 | // None of the WaitableEvent locks are held. The Waiter has not been enqueued |
| 337 | // in any of them and the return value is the index of the WaitableEvent which |
| 338 | // was signaled with the lowest input index from the original WaitMany call. |
| 339 | // ----------------------------------------------------------------------------- |
| 340 | // static |
| 341 | // NO_THREAD_SAFETY_ANALYSIS: Complex control flow. |
| 342 | size_t WaitableEvent::EnqueueMany(std::pair<WaitableEvent*, size_t>* waitables, |
| 343 | size_t count, |
| 344 | Waiter* waiter) NO_THREAD_SAFETY_ANALYSIS { |
| 345 | size_t winner = count; |
| 346 | size_t winner_index = count; |
| 347 | for (size_t i = 0; i < count; ++i) { |
| 348 | auto& kernel = waitables[i].first->kernel_; |
| 349 | kernel->lock_.Acquire(); |
| 350 | if (kernel->signaled_ && waitables[i].second < winner) { |
| 351 | winner = waitables[i].second; |
| 352 | winner_index = i; |
| 353 | } |
| 354 | } |
| 355 |
| 356 | // No events signaled. All locks acquired. Enqueue the Waiter on all of them |
| 357 | // and return. |
| 358 | if (winner == count) { |
| 359 | for (size_t i = 0; i < count; ++i) |
| 360 | waitables[i].first->Enqueue(waiter); |
| 361 | return count; |
| 362 | } |
| 363 |
| 364 | // Unlock in reverse order and possibly clear the chosen winner's signal |
| 365 | // before returning its index. |
| 366 | for (auto* w = waitables + count - 1; w >= waitables; --w) { |
| 367 | auto& kernel = w->first->kernel_; |
| 368 | if (w->second == winner) { |
| 369 | if (!kernel->manual_reset_) |
| 370 | kernel->signaled_ = false; |
| 371 | } |
| 372 | kernel->lock_.Release(); |
| 373 | } |
| 374 |
| 375 | return winner_index; |
| 376 | } |
| 377 |
| 378 | // ----------------------------------------------------------------------------- |
| 379 |
| 380 |
| 381 | // ----------------------------------------------------------------------------- |
| 382 | // Private functions... |
| 383 |
| 384 | WaitableEvent::WaitableEventKernel::WaitableEventKernel( |
| 385 | ResetPolicy reset_policy, |
| 386 | InitialState initial_state) |
| 387 | : manual_reset_(reset_policy == ResetPolicy::MANUAL), |
| 388 | signaled_(initial_state == InitialState::SIGNALED) {} |
| 389 |
| 390 | WaitableEvent::WaitableEventKernel::~WaitableEventKernel() = default; |
| 391 |
| 392 | // ----------------------------------------------------------------------------- |
| 393 | // Wake all waiting waiters. Called with lock held. |
| 394 | // ----------------------------------------------------------------------------- |
| 395 | bool WaitableEvent::SignalAll() { |
| 396 | bool signaled_at_least_one = false; |
| 397 |
| 398 | for (auto* i : kernel_->waiters_) { |
| 399 | if (i->Fire(this)) |
| 400 | signaled_at_least_one = true; |
| 401 | } |
| 402 |
| 403 | kernel_->waiters_.clear(); |
| 404 | return signaled_at_least_one; |
| 405 | } |
| 406 |
| 407 | // --------------------------------------------------------------------------- |
| 408 | // Try to wake a single waiter. Return true if one was woken. Called with lock |
| 409 | // held. |
| 410 | // --------------------------------------------------------------------------- |
| 411 | bool WaitableEvent::SignalOne() { |
| 412 | for (;;) { |
| 413 | if (kernel_->waiters_.empty()) |
| 414 | return false; |
| 415 |
| 416 | const bool r = (*kernel_->waiters_.begin())->Fire(this); |
| 417 | kernel_->waiters_.pop_front(); |
| 418 | if (r) |
| 419 | return true; |
| 420 | } |
| 421 | } |
| 422 |
| 423 | // ----------------------------------------------------------------------------- |
| 424 | // Add a waiter to the list of those waiting. Called with lock held. |
| 425 | // ----------------------------------------------------------------------------- |
| 426 | void WaitableEvent::Enqueue(Waiter* waiter) { |
| 427 | kernel_->waiters_.push_back(waiter); |
| 428 | } |
| 429 |
| 430 | // ----------------------------------------------------------------------------- |
| 431 | // Remove a waiter from the list of those waiting. Return true if the waiter was |
| 432 | // actually removed. Called with lock held. |
| 433 | // ----------------------------------------------------------------------------- |
| 434 | bool WaitableEvent::WaitableEventKernel::Dequeue(Waiter* waiter, void* tag) { |
| 435 | for (auto i = waiters_.begin(); i != waiters_.end(); ++i) { |
| 436 | if (*i == waiter && (*i)->Compare(tag)) { |
| 437 | waiters_.erase(i); |
| 438 | return true; |
| 439 | } |
| 440 | } |
| 441 |
| 442 | return false; |
| 443 | } |
| 444 |
| 445 | // ----------------------------------------------------------------------------- |
| 446 |
| 447 | } // namespace base |
| 448 |