inet.af/netstack@v0.0.0-20220214151720-7585b01ddccf/sleep/sleep_unsafe.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package sleep allows goroutines to efficiently sleep on multiple sources of 16 // notifications (wakers). It offers O(1) complexity, which is different from 17 // multi-channel selects which have O(n) complexity (where n is the number of 18 // channels) and a considerable constant factor. 19 // 20 // It is similar to edge-triggered epoll waits, where the user registers each 21 // object of interest once, and then can repeatedly wait on all of them. 22 // 23 // A Waker object is used to wake a sleeping goroutine (G) up, or prevent it 24 // from going to sleep next. A Sleeper object is used to receive notifications 25 // from wakers, and if no notifications are available, to optionally sleep until 26 // one becomes available. 27 // 28 // A Waker can be associated with at most one Sleeper, but a Sleeper can be 29 // associated with multiple Wakers. A Sleeper has a list of asserted (ready) 30 // wakers; when Fetch() is called repeatedly, elements from this list are 31 // returned until the list becomes empty in which case the goroutine goes to 32 // sleep. When Assert() is called on a Waker, it adds itself to the Sleeper's 33 // asserted list and wakes the G up from its sleep if needed. 34 // 35 // Sleeper objects are expected to be used as follows, with just one goroutine 36 // executing this code: 37 // 38 // // One time set-up. 39 // s := sleep.Sleeper{} 40 // s.AddWaker(&w1) 41 // s.AddWaker(&w2) 42 // 43 // // Called repeatedly. 44 // for { 45 // switch s.Fetch(true) { 46 // case &w1: 47 // // Do work triggered by w1 being asserted. 48 // case &w2: 49 // // Do work triggered by w2 being asserted. 50 // } 51 // } 52 // 53 // And Waker objects are expected to call w.Assert() when they want the sleeper 54 // to wake up and perform work. 55 // 56 // The notifications are edge-triggered, which means that if a Waker calls 57 // Assert() several times before the sleeper has the chance to wake up, it will 58 // only be notified once and should perform all pending work (alternatively, it 59 // can also call Assert() on the waker, to ensure that it will wake up again). 60 // 61 // The "unsafeness" here is in the casts to/from unsafe.Pointer, which is safe 62 // when only one type is used for each unsafe.Pointer (which is the case here), 63 // we should just make sure that this remains the case in the future. The usage 64 // of unsafe package could be confined to sharedWaker and sharedSleeper types 65 // that would hold pointers in atomic.Pointers, but the go compiler currently 66 // can't optimize these as well (it won't inline their method calls), which 67 // reduces performance. 68 package sleep 69 70 import ( 71 "sync/atomic" 72 "unsafe" 73 74 "inet.af/netstack/sync" 75 ) 76 77 const ( 78 // preparingG is stored in sleepers to indicate that they're preparing 79 // to sleep. 80 preparingG = 1 81 ) 82 83 var ( 84 // assertedSleeper is a sentinel sleeper. A pointer to it is stored in 85 // wakers that are asserted. 86 assertedSleeper Sleeper 87 ) 88 89 // Sleeper allows a goroutine to sleep and receive wake up notifications from 90 // Wakers in an efficient way. 91 // 92 // This is similar to edge-triggered epoll in that wakers are added to the 93 // sleeper once and the sleeper can then repeatedly sleep in O(1) time while 94 // waiting on all wakers. 95 // 96 // None of the methods in a Sleeper can be called concurrently. Wakers that have 97 // been added to a sleeper A can only be added to another sleeper after A.Done() 98 // returns. These restrictions allow this to be implemented lock-free. 99 // 100 // This struct is thread-compatible. 101 type Sleeper struct { 102 // sharedList is a "stack" of asserted wakers. They atomically add 103 // themselves to the front of this list as they become asserted. 104 sharedList unsafe.Pointer 105 106 // localList is a list of asserted wakers that is only accessible to the 107 // waiter, and thus doesn't have to be accessed atomically. When 108 // fetching more wakers, the waiter will first go through this list, and 109 // only when it's empty will it atomically fetch wakers from 110 // sharedList. 111 localList *Waker 112 113 // allWakers is a list with all wakers that have been added to this 114 // sleeper. It is used during cleanup to remove associations. 115 allWakers *Waker 116 117 // waitingG holds the G that is sleeping, if any. It is used by wakers 118 // to determine which G, if any, they should wake. 119 waitingG uintptr 120 } 121 122 // AddWaker associates the given waker to the sleeper. 123 func (s *Sleeper) AddWaker(w *Waker) { 124 if w.allWakersNext != nil { 125 panic("waker has non-nil allWakersNext; owned by another sleeper?") 126 } 127 if w.next != nil { 128 panic("waker has non-nil next; queued in another sleeper?") 129 } 130 131 // Add the waker to the list of all wakers. 132 w.allWakersNext = s.allWakers 133 s.allWakers = w 134 135 // Try to associate the waker with the sleeper. If it's already 136 // asserted, we simply enqueue it in the "ready" list. 137 for { 138 p := (*Sleeper)(atomic.LoadPointer(&w.s)) 139 if p == &assertedSleeper { 140 s.enqueueAssertedWaker(w) 141 return 142 } 143 144 if atomic.CompareAndSwapPointer(&w.s, usleeper(p), usleeper(s)) { 145 return 146 } 147 } 148 } 149 150 // nextWaker returns the next waker in the notification list, blocking if 151 // needed. 152 func (s *Sleeper) nextWaker(block bool) *Waker { 153 // Attempt to replenish the local list if it's currently empty. 154 if s.localList == nil { 155 for atomic.LoadPointer(&s.sharedList) == nil { 156 // Fail request if caller requested that we 157 // don't block. 158 if !block { 159 return nil 160 } 161 162 // Indicate to wakers that we're about to sleep, 163 // this allows them to abort the wait by setting 164 // waitingG back to zero (which we'll notice 165 // before committing the sleep). 166 atomic.StoreUintptr(&s.waitingG, preparingG) 167 168 // Check if something was queued while we were 169 // preparing to sleep. We need this interleaving 170 // to avoid missing wake ups. 171 if atomic.LoadPointer(&s.sharedList) != nil { 172 atomic.StoreUintptr(&s.waitingG, 0) 173 break 174 } 175 176 // Try to commit the sleep and report it to the 177 // tracer as a select. 178 // 179 // gopark puts the caller to sleep and calls 180 // commitSleep to decide whether to immediately 181 // wake the caller up or to leave it sleeping. 182 const traceEvGoBlockSelect = 24 183 // See:runtime2.go in the go runtime package for 184 // the values to pass as the waitReason here. 185 const waitReasonSelect = 9 186 sync.Gopark(commitSleep, unsafe.Pointer(&s.waitingG), sync.WaitReasonSelect, sync.TraceEvGoBlockSelect, 0) 187 } 188 189 // Pull the shared list out and reverse it in the local 190 // list. Given that wakers push themselves in reverse 191 // order, we fix things here. 192 v := (*Waker)(atomic.SwapPointer(&s.sharedList, nil)) 193 for v != nil { 194 cur := v 195 v = v.next 196 197 cur.next = s.localList 198 s.localList = cur 199 } 200 } 201 202 // Remove the waker in the front of the list. 203 w := s.localList 204 s.localList = w.next 205 206 return w 207 } 208 209 // commitSleep signals to wakers that the given g is now sleeping. Wakers can 210 // then fetch it and wake it. 211 // 212 // The commit may fail if wakers have been asserted after our last check, in 213 // which case they will have set s.waitingG to zero. 214 // 215 //go:norace 216 //go:nosplit 217 func commitSleep(g uintptr, waitingG unsafe.Pointer) bool { 218 return sync.RaceUncheckedAtomicCompareAndSwapUintptr((*uintptr)(waitingG), preparingG, g) 219 } 220 221 // Fetch fetches the next wake-up notification. If a notification is 222 // immediately available, the asserted waker is returned immediately. 223 // Otherwise, the behavior depends on the value of 'block': if true, the 224 // current goroutine blocks until a notification arrives and returns the 225 // asserted waker; if false, nil will be returned. 226 // 227 // N.B. This method is *not* thread-safe. Only one goroutine at a time is 228 // allowed to call this method. 229 func (s *Sleeper) Fetch(block bool) *Waker { 230 for { 231 w := s.nextWaker(block) 232 if w == nil { 233 return nil 234 } 235 236 // Reassociate the waker with the sleeper. If the waker was 237 // still asserted we can return it, otherwise try the next one. 238 old := (*Sleeper)(atomic.SwapPointer(&w.s, usleeper(s))) 239 if old == &assertedSleeper { 240 return w 241 } 242 } 243 } 244 245 // Done is used to indicate that the caller won't use this Sleeper anymore. It 246 // removes the association with all wakers so that they can be safely reused 247 // by another sleeper after Done() returns. 248 func (s *Sleeper) Done() { 249 // Remove all associations that we can, and build a list of the ones we 250 // could not. An association can be removed right away from waker w if 251 // w.s has a pointer to the sleeper, that is, the waker is not asserted 252 // yet. By atomically switching w.s to nil, we guarantee that 253 // subsequent calls to Assert() on the waker will not result in it 254 // being queued. 255 for w := s.allWakers; w != nil; w = s.allWakers { 256 next := w.allWakersNext // Before zapping. 257 if atomic.CompareAndSwapPointer(&w.s, usleeper(s), nil) { 258 w.allWakersNext = nil 259 w.next = nil 260 s.allWakers = next // Move ahead. 261 continue 262 } 263 264 // Dequeue exactly one waiter from the list, it may not be 265 // this one but we know this one is in the process. We must 266 // leave it in the asserted state but drop it from our lists. 267 if w := s.nextWaker(true); w != nil { 268 prev := &s.allWakers 269 for *prev != w { 270 prev = &((*prev).allWakersNext) 271 } 272 *prev = (*prev).allWakersNext 273 w.allWakersNext = nil 274 w.next = nil 275 } 276 } 277 } 278 279 // enqueueAssertedWaker enqueues an asserted waker to the "ready" circular list 280 // of wakers that want to notify the sleeper. 281 func (s *Sleeper) enqueueAssertedWaker(w *Waker) { 282 // Add the new waker to the front of the list. 283 for { 284 v := (*Waker)(atomic.LoadPointer(&s.sharedList)) 285 w.next = v 286 if atomic.CompareAndSwapPointer(&s.sharedList, uwaker(v), uwaker(w)) { 287 break 288 } 289 } 290 291 // Nothing to do if there isn't a G waiting. 292 if atomic.LoadUintptr(&s.waitingG) == 0 { 293 return 294 } 295 296 // Signal to the sleeper that a waker has been asserted. 297 switch g := atomic.SwapUintptr(&s.waitingG, 0); g { 298 case 0, preparingG: 299 default: 300 // We managed to get a G. Wake it up. 301 sync.Goready(g, 0) 302 } 303 } 304 305 // Waker represents a source of wake-up notifications to be sent to sleepers. A 306 // waker can be associated with at most one sleeper at a time, and at any given 307 // time is either in asserted or non-asserted state. 308 // 309 // Once asserted, the waker remains so until it is manually cleared or a sleeper 310 // consumes its assertion (i.e., a sleeper wakes up or is prevented from going 311 // to sleep due to the waker). 312 // 313 // This struct is thread-safe, that is, its methods can be called concurrently 314 // by multiple goroutines. 315 // 316 // Note, it is not safe to copy a Waker as its fields are modified by value 317 // (the pointer fields are individually modified with atomic operations). 318 type Waker struct { 319 _ sync.NoCopy 320 321 // s is the sleeper that this waker can wake up. Only one sleeper at a 322 // time is allowed. This field can have three classes of values: 323 // nil -- the waker is not asserted: it either is not associated with 324 // a sleeper, or is queued to a sleeper due to being previously 325 // asserted. This is the zero value. 326 // &assertedSleeper -- the waker is asserted. 327 // otherwise -- the waker is not asserted, and is associated with the 328 // given sleeper. Once it transitions to asserted state, the 329 // associated sleeper will be woken. 330 s unsafe.Pointer 331 332 // next is used to form a linked list of asserted wakers in a sleeper. 333 next *Waker 334 335 // allWakersNext is used to form a linked list of all wakers associated 336 // to a given sleeper. 337 allWakersNext *Waker 338 } 339 340 // Assert moves the waker to an asserted state, if it isn't asserted yet. When 341 // asserted, the waker will cause its matching sleeper to wake up. 342 func (w *Waker) Assert() { 343 // Nothing to do if the waker is already asserted. This check allows us 344 // to complete this case (already asserted) without any interlocked 345 // operations on x86. 346 if atomic.LoadPointer(&w.s) == usleeper(&assertedSleeper) { 347 return 348 } 349 350 // Mark the waker as asserted, and wake up a sleeper if there is one. 351 switch s := (*Sleeper)(atomic.SwapPointer(&w.s, usleeper(&assertedSleeper))); s { 352 case nil: 353 case &assertedSleeper: 354 default: 355 s.enqueueAssertedWaker(w) 356 } 357 } 358 359 // Clear moves the waker to then non-asserted state and returns whether it was 360 // asserted before being cleared. 361 // 362 // N.B. The waker isn't removed from the "ready" list of a sleeper (if it 363 // happens to be in one), but the sleeper will notice that it is not asserted 364 // anymore and won't return it to the caller. 365 func (w *Waker) Clear() bool { 366 // Nothing to do if the waker is not asserted. This check allows us to 367 // complete this case (already not asserted) without any interlocked 368 // operations on x86. 369 if atomic.LoadPointer(&w.s) != usleeper(&assertedSleeper) { 370 return false 371 } 372 373 // Try to store nil in the sleeper, which indicates that the waker is 374 // not asserted. 375 return atomic.CompareAndSwapPointer(&w.s, usleeper(&assertedSleeper), nil) 376 } 377 378 // IsAsserted returns whether the waker is currently asserted (i.e., if it's 379 // currently in a state that would cause its matching sleeper to wake up). 380 func (w *Waker) IsAsserted() bool { 381 return (*Sleeper)(atomic.LoadPointer(&w.s)) == &assertedSleeper 382 } 383 384 func usleeper(s *Sleeper) unsafe.Pointer { 385 return unsafe.Pointer(s) 386 } 387 388 func uwaker(w *Waker) unsafe.Pointer { 389 return unsafe.Pointer(w) 390 }