selector.rs 18.9 KB
Newer Older
Carl Lerche's avatar
Carl Lerche committed
1 2
#![allow(deprecated)]

3
use std::{fmt, io};
Alex Crichton's avatar
Alex Crichton committed
4
use std::cell::UnsafeCell;
5 6
use std::os::windows::prelude::*;
use std::sync::{Arc, Mutex};
7
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
8
use std::time::Duration;
9

10 11
use lazycell::AtomicLazyCell;

12
use winapi::*;
Carl Lerche's avatar
Carl Lerche committed
13 14
use miow;
use miow::iocp::{CompletionPort, CompletionStatus};
15

Carl Lerche's avatar
Carl Lerche committed
16
use event_imp::{Event, Evented, Ready};
17
use poll::{self, Poll};
18
use sys::windows::buffer_pool::BufferPool;
19
use {Token, PollOpt};
20

21 22
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
Julian Tescher's avatar
Julian Tescher committed
23
/// registered with the `Selector`. If a type that is previously associated with
24 25 26 27
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;

28 29 30 31 32 33 34 35 36 37 38
/// The guts of the Windows event loop, this is the struct which actually owns
/// a completion port.
///
/// Internally this is just an `Arc`, and this allows handing out references to
/// the internals to I/O handles registered on this selector. This is
/// required to schedule I/O operations independently of being inside the event
/// loop (e.g. when a call to `write` is seen we're not "in the event loop").
pub struct Selector {
    inner: Arc<SelectorInner>,
}

39
struct SelectorInner {
40 41 42
    /// Unique identifier of the `Selector`
    id: usize,

43 44 45
    /// The actual completion port that's used to manage all I/O
    port: CompletionPort,

46 47 48 49 50
    /// A pool of buffers usable by this selector.
    ///
    /// Primitives will take buffers from this pool to perform I/O operations,
    /// and once complete they'll be put back in.
    buffers: Mutex<BufferPool>,
51 52 53 54
}

impl Selector {
    pub fn new() -> io::Result<Selector> {
55 56 57
        // offset by 1 to avoid choosing 0 as the id of a selector
        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;

58 59 60
        CompletionPort::new(1).map(|cp| {
            Selector {
                inner: Arc::new(SelectorInner {
61
                    id: id,
62
                    port: cp,
63
                    buffers: Mutex::new(BufferPool::new(256)),
64 65 66 67 68
                }),
            }
        })
    }

69 70 71 72
    pub fn select(&self,
                  events: &mut Events,
                  awakener: Token,
                  timeout: Option<Duration>) -> io::Result<bool> {
Carl Lerche's avatar
Carl Lerche committed
73 74
        trace!("select; timeout={:?}", timeout);

75
        // Clear out the previous list of I/O events and get some more!
76
        events.clear();
Carl Lerche's avatar
Carl Lerche committed
77 78

        trace!("polling IOCP");
79
        let n = match self.inner.port.get_many(&mut events.statuses, timeout) {
80 81 82 83 84
            Ok(statuses) => statuses.len(),
            Err(ref e) if e.raw_os_error() == Some(WAIT_TIMEOUT as i32) => 0,
            Err(e) => return Err(e),
        };

85 86 87
        let mut ret = false;
        for status in events.statuses[..n].iter() {
            // This should only ever happen from the awakener, and we should
88
            // only ever have one awakener right now, so assert as such.
89
            if status.overlapped() as usize == 0 {
90 91
                assert_eq!(status.token(), usize::from(awakener));
                ret = true;
92
                continue;
93 94
            }

Alex Crichton's avatar
Alex Crichton committed
95
            let callback = unsafe {
96
                (*(status.overlapped() as *mut Overlapped)).callback
Alex Crichton's avatar
Alex Crichton committed
97
            };
98

Carl Lerche's avatar
Carl Lerche committed
99
            trace!("select; -> got overlapped");
100
            callback(status.entry());
101 102
        }

Carl Lerche's avatar
Carl Lerche committed
103
        trace!("returning");
104
        Ok(ret)
105
    }
106

107 108 109 110 111 112 113 114 115
    /// Gets a reference to the underlying `CompletionPort` structure.
    pub fn port(&self) -> &CompletionPort {
        &self.inner.port
    }

    /// Gets a new reference to this selector, although all underlying data
    /// structures will refer to the same completion port.
    pub fn clone_ref(&self) -> Selector {
        Selector { inner: self.inner.clone() }
Carl Lerche's avatar
Carl Lerche committed
116
    }
117 118 119 120 121

    /// Return the `Selector`'s identifier
    pub fn id(&self) -> usize {
        self.inner.id
    }
Carl Lerche's avatar
Carl Lerche committed
122
}
123

Carl Lerche's avatar
Carl Lerche committed
124 125 126
impl SelectorInner {
    fn identical(&self, other: &SelectorInner) -> bool {
        (self as *const SelectorInner) == (other as *const SelectorInner)
127 128 129
    }
}

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
// A registration is stored in each I/O object which keeps track of how it is
// associated with a `Selector` above.
//
// Once associated with a `Selector`, a registration can never be un-associated
// (due to IOCP requirements). This is actually implemented through the
// `poll::Registration` and `poll::SetReadiness` APIs to keep track of all the
// level/edge/filtering business.
/// A `Binding` is embedded in all I/O objects associated with a `Poll`
/// object.
///
/// Each registration keeps track of which selector the I/O object is
/// associated with, ensuring that implementations of `Evented` can be
/// conformant for the various methods on Windows.
///
/// If you're working with custom IOCP-enabled objects then you'll want to
/// ensure that one of these instances is stored in your object and used in the
/// implementation of `Evented`.
147
///
148 149 150 151
/// For more information about how to use this see the `windows` module
/// documentation in this crate.
pub struct Binding {
    selector: AtomicLazyCell<Arc<SelectorInner>>,
Carl Lerche's avatar
Carl Lerche committed
152 153
}

154 155 156 157
impl Binding {
    /// Creates a new blank binding ready to be inserted into an I/O
    /// object.
    ///
158
    /// Won't actually do anything until associated with a `Poll` loop.
159 160 161 162 163 164 165 166 167 168
    pub fn new() -> Binding {
        Binding { selector: AtomicLazyCell::new() }
    }

    /// Registers a new handle with the `Poll` specified, also assigning the
    /// `token` specified.
    ///
    /// This function is intended to be used as part of `Evented::register` for
    /// custom IOCP objects. It will add the specified handle to the internal
    /// IOCP object with the provided `token`. All future events generated by
Julian Tescher's avatar
Julian Tescher committed
169
    /// the handled provided will be received by the `Poll`'s internal IOCP
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    /// object.
    ///
    /// # Unsafety
    ///
    /// This function is unsafe as the `Poll` instance has assumptions about
    /// what the `OVERLAPPED` pointer used for each I/O operation looks like.
    /// Specifically they must all be instances of the `Overlapped` type in
    /// this crate. More information about this can be found on the
    /// `windows` module in this crate.
    pub unsafe fn register_handle(&self,
                                  handle: &AsRawHandle,
                                  token: Token,
                                  poll: &Poll) -> io::Result<()> {
        let selector = poll::selector(poll);

        // Ignore errors, we'll see them on the next line.
        drop(self.selector.fill(selector.inner.clone()));
Guanqun Lu's avatar
Guanqun Lu committed
187
        self.check_same_selector(poll)?;
188 189 190 191 192 193 194 195 196 197 198

        selector.inner.port.add_handle(usize::from(token), handle)
    }

    /// Same as `register_handle` but for sockets.
    pub unsafe fn register_socket(&self,
                                  handle: &AsRawSocket,
                                  token: Token,
                                  poll: &Poll) -> io::Result<()> {
        let selector = poll::selector(poll);
        drop(self.selector.fill(selector.inner.clone()));
Guanqun Lu's avatar
Guanqun Lu committed
199
        self.check_same_selector(poll)?;
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 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
        selector.inner.port.add_socket(usize::from(token), handle)
    }

    /// Reregisters the handle provided from the `Poll` provided.
    ///
    /// This is intended to be used as part of `Evented::reregister` but note
    /// that this function does not currently reregister the provided handle
    /// with the `poll` specified. IOCP has a special binding for changing the
    /// token which has not yet been implemented. Instead this function should
    /// be used to assert that the call to `reregister` happened on the same
    /// `Poll` that was passed into to `register`.
    ///
    /// Eventually, though, the provided `handle` will be re-assigned to have
    /// the token `token` on the given `poll` assuming that it's been
    /// previously registered with it.
    ///
    /// # Unsafety
    ///
    /// This function is unsafe for similar reasons to `register`. That is,
    /// there may be pending I/O events and such which aren't handled correctly.
    pub unsafe fn reregister_handle(&self,
                                    _handle: &AsRawHandle,
                                    _token: Token,
                                    poll: &Poll) -> io::Result<()> {
        self.check_same_selector(poll)
    }

    /// Same as `reregister_handle`, but for sockets.
    pub unsafe fn reregister_socket(&self,
                                    _socket: &AsRawSocket,
                                    _token: Token,
                                    poll: &Poll) -> io::Result<()> {
        self.check_same_selector(poll)
    }

    /// Deregisters the handle provided from the `Poll` provided.
    ///
    /// This is intended to be used as part of `Evented::deregister` but note
    /// that this function does not currently deregister the provided handle
    /// from the `poll` specified. IOCP has a special binding for that which has
    /// not yet been implemented. Instead this function should be used to assert
    /// that the call to `deregister` happened on the same `Poll` that was
    /// passed into to `register`.
    ///
    /// # Unsafety
    ///
    /// This function is unsafe for similar reasons to `register`. That is,
    /// there may be pending I/O events and such which aren't handled correctly.
    pub unsafe fn deregister_handle(&self,
                                    _handle: &AsRawHandle,
                                    poll: &Poll) -> io::Result<()> {
        self.check_same_selector(poll)
    }

    /// Same as `deregister_handle`, but for sockets.
    pub unsafe fn deregister_socket(&self,
                                    _socket: &AsRawSocket,
                                    poll: &Poll) -> io::Result<()> {
        self.check_same_selector(poll)
    }

    fn check_same_selector(&self, poll: &Poll) -> io::Result<()> {
        let selector = poll::selector(poll);
        match self.selector.borrow() {
            Some(prev) if prev.identical(&selector.inner) => Ok(()),
            Some(_) |
            None => Err(other("socket already registered")),
        }
    }
269 270
}

271 272
impl fmt::Debug for Binding {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
273 274
        f.debug_struct("Binding")
            .finish()
275 276 277
    }
}

278 279 280 281 282 283 284 285 286
/// Helper struct used for TCP and UDP which bundles a `binding` with a
/// `SetReadiness` handle.
pub struct ReadyBinding {
    binding: Binding,
    readiness: Option<poll::SetReadiness>,
}

impl ReadyBinding {
    /// Creates a new blank binding ready to be inserted into an I/O object.
287 288
    ///
    /// Won't actually do anything until associated with an `Selector` loop.
289 290 291 292
    pub fn new() -> ReadyBinding {
        ReadyBinding {
            binding: Binding::new(),
            readiness: None,
293 294 295
        }
    }

296
    /// Returns whether this binding has been associated with a selector
297 298
    /// yet.
    pub fn registered(&self) -> bool {
299
        self.readiness.is_some()
Carl Lerche's avatar
Carl Lerche committed
300
    }
301

302 303 304 305 306
    /// Acquires a buffer with at least `size` capacity.
    ///
    /// If associated with a selector, this will attempt to pull a buffer from
    /// that buffer pool. If not associated with a selector, this will allocate
    /// a fresh buffer.
307
    pub fn get_buffer(&self, size: usize) -> Vec<u8> {
308 309
        match self.binding.selector.borrow() {
            Some(i) => i.buffers.lock().unwrap().get(size),
310 311
            None => Vec::with_capacity(size),
        }
312 313
    }

314
    /// Returns a buffer to this binding.
315 316 317
    ///
    /// If associated with a selector, this will push the buffer back into the
    /// selector's pool of buffers. Otherwise this will just drop the buffer.
318
    pub fn put_buffer(&self, buf: Vec<u8>) {
319 320
        if let Some(i) = self.binding.selector.borrow() {
            i.buffers.lock().unwrap().put(buf);
321
        }
322 323
    }

324
    /// Sets the readiness of this I/O object to a particular `set`.
325
    ///
326 327 328
    /// This is later used to fill out and respond to requests to `poll`. Note
    /// that this is all implemented through the `SetReadiness` structure in the
    /// `poll` module.
Carl Lerche's avatar
Carl Lerche committed
329
    pub fn set_readiness(&self, set: Ready) {
330
        if let Some(ref i) = self.readiness {
331
            trace!("set readiness to {:?}", set);
332
            i.set_readiness(set).expect("event loop disappeared?");
333 334
        }
    }
335

336 337 338
    /// Queries what the current readiness of this I/O object is.
    ///
    /// This is what's being used to generate events returned by `poll`.
Carl Lerche's avatar
Carl Lerche committed
339
    pub fn readiness(&self) -> Ready {
340 341
        match self.readiness {
            Some(ref i) => i.readiness(),
Carl Lerche's avatar
Carl Lerche committed
342
            None => Ready::empty(),
343
        }
344
    }
345

346 347 348 349 350
    /// Implementation of the `Evented::register` function essentially.
    ///
    /// Returns an error if we're already registered with another event loop,
    /// and otherwise just reassociates ourselves with the event loop to
    /// possible change tokens.
351 352
    pub fn register_socket(&mut self,
                           socket: &AsRawSocket,
353
                           poll: &Poll,
354
                           token: Token,
355
                           events: Ready,
356 357 358
                           opts: PollOpt,
                           registration: &Mutex<Option<poll::Registration>>)
                           -> io::Result<()> {
359 360
        trace!("register {:?} {:?}", token, events);
        unsafe {
Guanqun Lu's avatar
Guanqun Lu committed
361
            self.binding.register_socket(socket, token, poll)?;
362 363
        }

Carl Lerche's avatar
Carl Lerche committed
364
        let (r, s) = poll::new_registration(poll, token, events, opts);
365 366
        self.readiness = Some(s);
        *registration.lock().unwrap() = Some(r);
367 368 369
        Ok(())
    }

370
    /// Implementation of `Evented::reregister` function.
371
    pub fn reregister_socket(&mut self,
372
                             socket: &AsRawSocket,
373
                             poll: &Poll,
374
                             token: Token,
375
                             events: Ready,
376 377 378
                             opts: PollOpt,
                             registration: &Mutex<Option<poll::Registration>>)
                             -> io::Result<()> {
379 380
        trace!("reregister {:?} {:?}", token, events);
        unsafe {
Guanqun Lu's avatar
Guanqun Lu committed
381
            self.binding.reregister_socket(socket, token, poll)?;
382 383
        }

384 385
        registration.lock().unwrap()
                    .as_mut().unwrap()
Carl Lerche's avatar
Carl Lerche committed
386
                    .reregister(poll, token, events, opts)
387 388
    }

389
    /// Implementation of the `Evented::deregister` function.
390
    ///
391 392
    /// Doesn't allow registration with another event loop, just shuts down
    /// readiness notifications and such.
393
    pub fn deregister(&mut self,
394
                      socket: &AsRawSocket,
395 396 397
                      poll: &Poll,
                      registration: &Mutex<Option<poll::Registration>>)
                      -> io::Result<()> {
398
        trace!("deregistering");
399
        unsafe {
Guanqun Lu's avatar
Guanqun Lu committed
400
            self.binding.deregister_socket(socket, poll)?;
401
        }
402 403 404 405

        registration.lock().unwrap()
                    .as_ref().unwrap()
                    .deregister(poll)
406 407 408 409 410 411 412 413 414 415
    }
}

fn other(s: &str) -> io::Error {
    io::Error::new(io::ErrorKind::Other, s)
}

#[derive(Debug)]
pub struct Events {
    /// Raw I/O event completions are filled in here by the call to `get_many`
416 417
    /// on the completion port above. These are then processed to run callbacks
    /// which figure out what to do after the event is done.
418 419
    statuses: Box<[CompletionStatus]>,

420 421 422
    /// Literal events returned by `get` to the upwards `EventLoop`. This file
    /// doesn't really modify this (except for the awakener), instead almost all
    /// events are filled in by the `ReadinessQueue` from the `poll` module.
Carl Lerche's avatar
Carl Lerche committed
423
    events: Vec<Event>,
424 425 426
}

impl Events {
427 428
    pub fn with_capacity(cap: usize) -> Events {
        // Note that it's possible for the output `events` to grow beyond the
429 430 431
        // capacity as it can also include deferred events, but that's certainly
        // not the end of the world!
        Events {
432 433
            statuses: vec![CompletionStatus::zero(); cap].into_boxed_slice(),
            events: Vec::with_capacity(cap),
434 435 436
        }
    }

mcarton's avatar
mcarton committed
437 438 439 440
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

441 442 443 444
    pub fn len(&self) -> usize {
        self.events.len()
    }

Carl Lerche's avatar
Carl Lerche committed
445 446 447 448
    pub fn capacity(&self) -> usize {
        self.events.capacity()
    }

Carl Lerche's avatar
Carl Lerche committed
449 450
    pub fn get(&self, idx: usize) -> Option<Event> {
        self.events.get(idx).map(|e| *e)
451
    }
452 453 454 455

    pub fn push_event(&mut self, event: Event) {
        self.events.push(event);
    }
456 457 458 459

    pub fn clear(&mut self) {
        self.events.truncate(0);
    }
460 461
}

Alex Crichton's avatar
Alex Crichton committed
462
macro_rules! overlapped2arc {
463 464 465 466 467
    ($e:expr, $t:ty, $($field:ident).+) => ({
        let offset = offset_of!($t, $($field).+);
        debug_assert!(offset < mem::size_of::<$t>());
        FromRawArc::from_raw(($e as usize - offset) as *mut $t)
    })
Alex Crichton's avatar
Alex Crichton committed
468 469 470 471 472 473
}

macro_rules! offset_of {
    ($t:ty, $($field:ident).+) => (
        &(*(0 as *const $t)).$($field).+ as *const _ as usize
    )
474 475
}

476 477 478 479 480 481 482 483 484 485
// See sys::windows module docs for why this exists.
//
// The gist of it is that `Selector` assumes that all `OVERLAPPED` pointers are
// actually inside one of these structures so it can use the `Callback` stored
// right after it.
//
// We use repr(C) here to ensure that we can assume the overlapped pointer is
// at the start of the structure so we can just do a cast.
/// A wrapper around an internal instance over `miow::Overlapped` which is in
/// turn a wrapper around the Windows type `OVERLAPPED`.
486
///
487 488 489 490
/// This type is required to be used for all IOCP operations on handles that are
/// registered with an event loop. The event loop will receive notifications
/// over `OVERLAPPED` pointers that have completed, and it will cast that
/// pointer to a pointer to this structure and invoke the associated callback.
491 492 493
#[repr(C)]
pub struct Overlapped {
    inner: UnsafeCell<miow::Overlapped>,
494
    callback: fn(&OVERLAPPED_ENTRY),
495 496
}

Alex Crichton's avatar
Alex Crichton committed
497
impl Overlapped {
498 499 500 501 502 503 504 505
    /// Creates a new `Overlapped` which will invoke the provided `cb` callback
    /// whenever it's triggered.
    ///
    /// The returned `Overlapped` must be used as the `OVERLAPPED` passed to all
    /// I/O operations that are registered with mio's event loop. When the I/O
    /// operation associated with an `OVERLAPPED` pointer completes the event
    /// loop will invoke the function pointer provided by `cb`.
    pub fn new(cb: fn(&OVERLAPPED_ENTRY)) -> Overlapped {
Alex Crichton's avatar
Alex Crichton committed
506
        Overlapped {
Carl Lerche's avatar
Carl Lerche committed
507
            inner: UnsafeCell::new(miow::Overlapped::zero()),
Alex Crichton's avatar
Alex Crichton committed
508 509 510 511
            callback: cb,
        }
    }

512 513 514 515 516 517 518 519
    /// Get the underlying `Overlapped` instance as a raw pointer.
    ///
    /// This can be useful when only a shared borrow is held and the overlapped
    /// pointer needs to be passed down to winapi.
    pub fn as_mut_ptr(&self) -> *mut OVERLAPPED {
        unsafe {
            (*self.inner.get()).raw()
        }
520
    }
521
}
522

523 524
impl fmt::Debug for Overlapped {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525 526
        f.debug_struct("Overlapped")
            .finish()
527 528 529
    }
}

530 531 532 533 534
// Overlapped's APIs are marked as unsafe Overlapped's APIs are marked as
// unsafe as they must be used with caution to ensure thread safety. The
// structure itself is safe to send across threads.
unsafe impl Send for Overlapped {}
unsafe impl Sync for Overlapped {}