stream.rs 19.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// Stream channels
///
/// This is the flavor of channels which are optimized for one sender and one
/// receiver. The sender will be upgraded to a shared channel if the channel is
/// cloned.
///
/// High level implementation details can be found in the comment of the parent
/// module.

S
Steven Fackler 已提交
20 21 22 23 24
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::Message::*;

A
Alex Crichton 已提交
25 26
use core::prelude::*;

27
use alloc::boxed::Box;
A
Alex Crichton 已提交
28 29 30 31 32 33
use core::cmp;
use core::int;
use rustrt::local::Local;
use rustrt::task::{Task, BlockedTask};
use rustrt::thread::Thread;

A
Aaron Turon 已提交
34
use sync::atomic;
A
Alex Crichton 已提交
35
use comm::spsc_queue as spsc;
36
use comm::Receiver;
37

A
Alex Crichton 已提交
38
const DISCONNECTED: int = int::MIN;
39
#[cfg(test)]
A
Alex Crichton 已提交
40
const MAX_STEALS: int = 5;
41
#[cfg(not(test))]
A
Alex Crichton 已提交
42
const MAX_STEALS: int = 1 << 20;
43 44 45 46

pub struct Packet<T> {
    queue: spsc::Queue<Message<T>>, // internal queue for all message

A
Aaron Turon 已提交
47
    cnt: atomic::AtomicInt, // How many items are on this channel
48
    steals: int, // How many times has a port received without blocking?
A
Aaron Turon 已提交
49
    to_wake: atomic::AtomicUint, // Task to wake up
50

A
Aaron Turon 已提交
51
    port_dropped: atomic::AtomicBool, // flag if the channel has been destroyed.
52 53 54 55 56
}

pub enum Failure<T> {
    Empty,
    Disconnected,
57
    Upgraded(Receiver<T>),
58 59 60 61 62 63 64 65 66 67 68
}

pub enum UpgradeResult {
    UpSuccess,
    UpDisconnected,
    UpWoke(BlockedTask),
}

pub enum SelectionResult<T> {
    SelSuccess,
    SelCanceled(BlockedTask),
69
    SelUpgraded(BlockedTask, Receiver<T>),
70 71 72 73 74 75
}

// Any message could contain an "upgrade request" to a new shared port, so the
// internal queue it's a queue of T, but rather Message<T>
enum Message<T> {
    Data(T),
76
    GoUp(Receiver<T>),
77 78 79 80 81
}

impl<T: Send> Packet<T> {
    pub fn new() -> Packet<T> {
        Packet {
82
            queue: unsafe { spsc::Queue::new(128) },
83

A
Aaron Turon 已提交
84
            cnt: atomic::AtomicInt::new(0),
85
            steals: 0,
A
Aaron Turon 已提交
86
            to_wake: atomic::AtomicUint::new(0),
87

A
Aaron Turon 已提交
88
            port_dropped: atomic::AtomicBool::new(false),
89 90 91 92
        }
    }


93 94 95 96
    pub fn send(&mut self, t: T) -> Result<(), T> {
        // If the other port has deterministically gone away, then definitely
        // must return the data back up the stack. Otherwise, the data is
        // considered as being sent.
A
Aaron Turon 已提交
97
        if self.port_dropped.load(atomic::SeqCst) { return Err(t) }
98

99
        match self.do_send(Data(t)) {
100 101
            UpSuccess | UpDisconnected => {},
            UpWoke(task) => { task.wake().map(|t| t.reawaken()); }
102
        }
103
        Ok(())
104
    }
105
    pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
106 107
        // If the port has gone away, then there's no need to proceed any
        // further.
A
Aaron Turon 已提交
108
        if self.port_dropped.load(atomic::SeqCst) { return UpDisconnected }
109

110 111 112 113 114
        self.do_send(GoUp(up))
    }

    fn do_send(&mut self, t: Message<T>) -> UpgradeResult {
        self.queue.push(t);
A
Aaron Turon 已提交
115
        match self.cnt.fetch_add(1, atomic::SeqCst) {
116 117 118 119 120 121 122 123 124 125 126 127 128
            // As described in the mod's doc comment, -1 == wakeup
            -1 => UpWoke(self.take_to_wake()),
            // As as described before, SPSC queues must be >= -2
            -2 => UpSuccess,

            // Be sure to preserve the disconnected state, and the return value
            // in this case is going to be whether our data was received or not.
            // This manifests itself on whether we have an empty queue or not.
            //
            // Primarily, are required to drain the queue here because the port
            // will never remove this data. We can only have at most one item to
            // drain (the port drains the rest).
            DISCONNECTED => {
A
Aaron Turon 已提交
129
                self.cnt.store(DISCONNECTED, atomic::SeqCst);
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
                let first = self.queue.pop();
                let second = self.queue.pop();
                assert!(second.is_none());

                match first {
                    Some(..) => UpSuccess,  // we failed to send the data
                    None => UpDisconnected, // we successfully sent data
                }
            }

            // Otherwise we just sent some data on a non-waiting queue, so just
            // make sure the world is sane and carry on!
            n => { assert!(n >= 0); UpSuccess }
        }
    }

    // Consumes ownership of the 'to_wake' field.
    fn take_to_wake(&mut self) -> BlockedTask {
A
Aaron Turon 已提交
148 149
        let task = self.to_wake.load(atomic::SeqCst);
        self.to_wake.store(0, atomic::SeqCst);
150 151 152 153 154 155 156 157
        assert!(task != 0);
        unsafe { BlockedTask::cast_from_uint(task) }
    }

    // Decrements the count on the channel for a sleeper, returning the sleeper
    // back if it shouldn't sleep. Note that this is the location where we take
    // steals into account.
    fn decrement(&mut self, task: BlockedTask) -> Result<(), BlockedTask> {
A
Aaron Turon 已提交
158
        assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
159
        let n = unsafe { task.cast_to_uint() };
A
Aaron Turon 已提交
160
        self.to_wake.store(n, atomic::SeqCst);
161 162 163 164

        let steals = self.steals;
        self.steals = 0;

A
Aaron Turon 已提交
165 166
        match self.cnt.fetch_sub(1 + steals, atomic::SeqCst) {
            DISCONNECTED => { self.cnt.store(DISCONNECTED, atomic::SeqCst); }
167 168 169 170 171 172 173 174
            // If we factor in our steals and notice that the channel has no
            // data, we successfully sleep
            n => {
                assert!(n >= 0);
                if n - steals <= 0 { return Ok(()) }
            }
        }

A
Aaron Turon 已提交
175
        self.to_wake.store(0, atomic::SeqCst);
176 177 178 179 180 181 182 183 184 185 186 187
        Err(unsafe { BlockedTask::cast_from_uint(n) })
    }

    pub fn recv(&mut self) -> Result<T, Failure<T>> {
        // Optimistic preflight check (scheduling is expensive).
        match self.try_recv() {
            Err(Empty) => {}
            data => return data,
        }

        // Welp, our channel has no data. Deschedule the current task and
        // initiate the blocking protocol.
188
        let task: Box<Task> = Local::take();
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        task.deschedule(1, |task| {
            self.decrement(task)
        });

        match self.try_recv() {
            // Messages which actually popped from the queue shouldn't count as
            // a steal, so offset the decrement here (we already have our
            // "steal" factored into the channel count above).
            data @ Ok(..) |
            data @ Err(Upgraded(..)) => {
                self.steals -= 1;
                data
            }

            data => data,
        }
    }

    pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
        match self.queue.pop() {
            // If we stole some data, record to that effect (this will be
210 211 212 213 214 215 216 217 218 219
            // factored into cnt later on).
            //
            // Note that we don't allow steals to grow without bound in order to
            // prevent eventual overflow of either steals or cnt as an overflow
            // would have catastrophic results. Sometimes, steals > cnt, but
            // other times cnt > steals, so we don't know the relation between
            // steals and cnt. This code path is executed only rarely, so we do
            // a pretty slow operation, of swapping 0 into cnt, taking steals
            // down as much as possible (without going negative), and then
            // adding back in whatever we couldn't factor into steals.
220 221
            Some(data) => {
                if self.steals > MAX_STEALS {
A
Aaron Turon 已提交
222
                    match self.cnt.swap(0, atomic::SeqCst) {
223
                        DISCONNECTED => {
A
Aaron Turon 已提交
224
                            self.cnt.store(DISCONNECTED, atomic::SeqCst);
225
                        }
226 227 228
                        n => {
                            let m = cmp::min(n, self.steals);
                            self.steals -= m;
229
                            self.bump(n - m);
230
                        }
231 232 233
                    }
                    assert!(self.steals >= 0);
                }
234
                self.steals += 1;
235 236 237 238 239 240 241
                match data {
                    Data(t) => Ok(t),
                    GoUp(up) => Err(Upgraded(up)),
                }
            }

            None => {
A
Aaron Turon 已提交
242
                match self.cnt.load(atomic::SeqCst) {
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
                    n if n != DISCONNECTED => Err(Empty),

                    // This is a little bit of a tricky case. We failed to pop
                    // data above, and then we have viewed that the channel is
                    // disconnected. In this window more data could have been
                    // sent on the channel. It doesn't really make sense to
                    // return that the channel is disconnected when there's
                    // actually data on it, so be extra sure there's no data by
                    // popping one more time.
                    //
                    // We can ignore steals because the other end is
                    // disconnected and we'll never need to really factor in our
                    // steals again.
                    _ => {
                        match self.queue.pop() {
                            Some(Data(t)) => Ok(t),
                            Some(GoUp(up)) => Err(Upgraded(up)),
                            None => Err(Disconnected),
                        }
                    }
                }
            }
        }
    }

    pub fn drop_chan(&mut self) {
        // Dropping a channel is pretty simple, we just flag it as disconnected
        // and then wakeup a blocker if there is one.
A
Aaron Turon 已提交
271
        match self.cnt.swap(DISCONNECTED, atomic::SeqCst) {
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
            -1 => { self.take_to_wake().wake().map(|t| t.reawaken()); }
            DISCONNECTED => {}
            n => { assert!(n >= 0); }
        }
    }

    pub fn drop_port(&mut self) {
        // Dropping a port seems like a fairly trivial thing. In theory all we
        // need to do is flag that we're disconnected and then everything else
        // can take over (we don't have anyone to wake up).
        //
        // The catch for Ports is that we want to drop the entire contents of
        // the queue. There are multiple reasons for having this property, the
        // largest of which is that if another chan is waiting in this channel
        // (but not received yet), then waiting on that port will cause a
        // deadlock.
        //
        // So if we accept that we must now destroy the entire contents of the
        // queue, this code may make a bit more sense. The tricky part is that
        // we can't let any in-flight sends go un-dropped, we have to make sure
        // *everything* is dropped and nothing new will come onto the channel.

        // The first thing we do is set a flag saying that we're done for. All
        // sends are gated on this flag, so we're immediately guaranteed that
        // there are a bounded number of active sends that we'll have to deal
        // with.
A
Aaron Turon 已提交
298
        self.port_dropped.store(true, atomic::SeqCst);
299 300 301 302 303 304 305 306 307 308 309 310

        // Now that we're guaranteed to deal with a bounded number of senders,
        // we need to drain the queue. This draining process happens atomically
        // with respect to the "count" of the channel. If the count is nonzero
        // (with steals taken into account), then there must be data on the
        // channel. In this case we drain everything and then try again. We will
        // continue to fail while active senders send data while we're dropping
        // data, but eventually we're guaranteed to break out of this loop
        // (because there is a bounded number of senders).
        let mut steals = self.steals;
        while {
            let cnt = self.cnt.compare_and_swap(
A
Aaron Turon 已提交
311
                            steals, DISCONNECTED, atomic::SeqCst);
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
            cnt != DISCONNECTED && cnt != steals
        } {
            loop {
                match self.queue.pop() {
                    Some(..) => { steals += 1; }
                    None => break
                }
            }
        }

        // At this point in time, we have gated all future senders from sending,
        // and we have flagged the channel as being disconnected. The senders
        // still have some responsibility, however, because some sends may not
        // complete until after we flag the disconnection. There are more
        // details in the sending methods that see DISCONNECTED
    }

    ////////////////////////////////////////////////////////////////////////////
    // select implementation
    ////////////////////////////////////////////////////////////////////////////

    // Tests to see whether this port can receive without blocking. If Ok is
    // returned, then that's the answer. If Err is returned, then the returned
    // port needs to be queried instead (an upgrade happened)
336
    pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
        // We peek at the queue to see if there's anything on it, and we use
        // this return value to determine if we should pop from the queue and
        // upgrade this channel immediately. If it looks like we've got an
        // upgrade pending, then go through the whole recv rigamarole to update
        // the internal state.
        match self.queue.peek() {
            Some(&GoUp(..)) => {
                match self.recv() {
                    Err(Upgraded(port)) => Err(port),
                    _ => unreachable!(),
                }
            }
            Some(..) => Ok(true),
            None => Ok(false)
        }
    }

354 355
    // increment the count on the channel (used for selection)
    fn bump(&mut self, amt: int) -> int {
A
Aaron Turon 已提交
356
        match self.cnt.fetch_add(amt, atomic::SeqCst) {
357
            DISCONNECTED => {
A
Aaron Turon 已提交
358
                self.cnt.store(DISCONNECTED, atomic::SeqCst);
359 360 361 362 363 364
                DISCONNECTED
            }
            n => n
        }
    }

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    // Attempts to start selecting on this port. Like a oneshot, this can fail
    // immediately because of an upgrade.
    pub fn start_selection(&mut self, task: BlockedTask) -> SelectionResult<T> {
        match self.decrement(task) {
            Ok(()) => SelSuccess,
            Err(task) => {
                let ret = match self.queue.peek() {
                    Some(&GoUp(..)) => {
                        match self.queue.pop() {
                            Some(GoUp(port)) => SelUpgraded(task, port),
                            _ => unreachable!(),
                        }
                    }
                    Some(..) => SelCanceled(task),
                    None => SelCanceled(task),
                };
                // Undo our decrement above, and we should be guaranteed that the
                // previous value is positive because we're not going to sleep
383 384
                let prev = self.bump(1);
                assert!(prev == DISCONNECTED || prev >= 0);
385 386 387 388 389 390 391
                return ret;
            }
        }
    }

    // Removes a previous task from being blocked in this port
    pub fn abort_selection(&mut self,
392
                           was_upgrade: bool) -> Result<bool, Receiver<T>> {
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
        // If we're aborting selection after upgrading from a oneshot, then
        // we're guarantee that no one is waiting. The only way that we could
        // have seen the upgrade is if data was actually sent on the channel
        // half again. For us, this means that there is guaranteed to be data on
        // this channel. Furthermore, we're guaranteed that there was no
        // start_selection previously, so there's no need to modify `self.cnt`
        // at all.
        //
        // Hence, because of these invariants, we immediately return `Ok(true)`.
        // Note that the data may not actually be sent on the channel just yet.
        // The other end could have flagged the upgrade but not sent data to
        // this end. This is fine because we know it's a small bounded windows
        // of time until the data is actually sent.
        if was_upgrade {
            assert_eq!(self.steals, 0);
A
Aaron Turon 已提交
408
            assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
409 410 411 412 413 414 415
            return Ok(true)
        }

        // We want to make sure that the count on the channel goes non-negative,
        // and in the stream case we can have at most one steal, so just assume
        // that we had one steal.
        let steals = 1;
416
        let prev = self.bump(steals + 1);
417 418 419 420

        // If we were previously disconnected, then we know for sure that there
        // is no task in to_wake, so just keep going
        let has_data = if prev == DISCONNECTED {
A
Aaron Turon 已提交
421
            assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
            true // there is data, that data is that we're disconnected
        } else {
            let cur = prev + steals + 1;
            assert!(cur >= 0);

            // If the previous count was negative, then we just made things go
            // positive, hence we passed the -1 boundary and we're responsible
            // for removing the to_wake() field and trashing it.
            //
            // If the previous count was positive then we're in a tougher
            // situation. A possible race is that a sender just incremented
            // through -1 (meaning it's going to try to wake a task up), but it
            // hasn't yet read the to_wake. In order to prevent a future recv()
            // from waking up too early (this sender picking up the plastered
            // over to_wake), we spin loop here waiting for to_wake to be 0.
            // Note that this entire select() implementation needs an overhaul,
            // and this is *not* the worst part of it, so this is not done as a
            // final solution but rather out of necessity for now to get
            // something working.
            if prev < 0 {
                self.take_to_wake().trash();
            } else {
A
Aaron Turon 已提交
444
                while self.to_wake.load(atomic::SeqCst) != 0 {
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
                    Thread::yield_now();
                }
            }
            assert_eq!(self.steals, 0);
            self.steals = steals;

            // if we were previously positive, then there's surely data to
            // receive
            prev >= 0
        };

        // Now that we've determined that this queue "has data", we peek at the
        // queue to see if the data is an upgrade or not. If it's an upgrade,
        // then we need to destroy this port and abort selection on the
        // upgraded port.
        if has_data {
            match self.queue.peek() {
                Some(&GoUp(..)) => {
                    match self.queue.pop() {
                        Some(GoUp(port)) => Err(port),
                        _ => unreachable!(),
                    }
                }
                _ => Ok(true),
            }
        } else {
            Ok(false)
        }
    }
}

#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
    fn drop(&mut self) {
479 480 481 482
        // Note that this load is not only an assert for correctness about
        // disconnection, but also a proper fence before the read of
        // `to_wake`, so this assert cannot be removed with also removing
        // the `to_wake` assert.
A
Aaron Turon 已提交
483 484
        assert_eq!(self.cnt.load(atomic::SeqCst), DISCONNECTED);
        assert_eq!(self.to_wake.load(atomic::SeqCst), 0);
485 486
    }
}