]> git.lizzy.rs Git - rust.git/blob - src/libnative/io/timer_unix.rs
return &mut T from the arenas, not &T
[rust.git] / src / libnative / io / timer_unix.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Timers for non-Linux/non-Windows OSes
12 //!
13 //! This module implements timers with a worker thread, select(), and a lot of
14 //! witchcraft that turns out to be horribly inaccurate timers. The unfortunate
15 //! part is that I'm at a loss of what else to do one these OSes. This is also
16 //! why Linux has a specialized timerfd implementation and windows has its own
17 //! implementation (they're more accurate than this one).
18 //!
19 //! The basic idea is that there is a worker thread that's communicated to via a
20 //! channel and a pipe, the pipe is used by the worker thread in a select()
21 //! syscall with a timeout. The timeout is the "next timer timeout" while the
22 //! channel is used to send data over to the worker thread.
23 //!
24 //! Whenever the call to select() times out, then a channel receives a message.
25 //! Whenever the call returns that the file descriptor has information, then the
26 //! channel from timers is drained, enqueuing all incoming requests.
27 //!
28 //! The actual implementation of the helper thread is a sorted array of
29 //! timers in terms of target firing date. The target is the absolute time at
30 //! which the timer should fire. Timers are then re-enqueued after a firing if
31 //! the repeat boolean is set.
32 //!
33 //! Naturally, all this logic of adding times and keeping track of
34 //! relative/absolute time is a little lossy and not quite exact. I've done the
35 //! best I could to reduce the amount of calls to 'now()', but there's likely
36 //! still inaccuracies trickling in here and there.
37 //!
38 //! One of the tricky parts of this implementation is that whenever a timer is
39 //! acted upon, it must cancel whatever the previous action was (if one is
40 //! active) in order to act like the other implementations of this timer. In
41 //! order to do this, the timer's inner pointer is transferred to the worker
42 //! thread. Whenever the timer is modified, it first takes ownership back from
43 //! the worker thread in order to modify the same data structure. This has the
44 //! side effect of "cancelling" the previous requests while allowing a
45 //! re-enqueuing later on.
46 //!
47 //! Note that all time units in this file are in *milliseconds*.
48
49 use libc;
50 use std::mem;
51 use std::os;
52 use std::ptr;
53 use std::rt::rtio;
54 use std::rt::rtio::IoResult;
55 use std::sync::atomic;
56 use std::comm;
57
58 use io::c;
59 use io::file::FileDesc;
60 use io::helper_thread::Helper;
61
62 helper_init!(static HELPER: Helper<Req>)
63
64 pub struct Timer {
65     id: uint,
66     inner: Option<Box<Inner>>,
67 }
68
69 pub struct Inner {
70     cb: Option<Box<rtio::Callback + Send>>,
71     interval: u64,
72     repeat: bool,
73     target: u64,
74     id: uint,
75 }
76
77 pub enum Req {
78     // Add a new timer to the helper thread.
79     NewTimer(Box<Inner>),
80
81     // Remove a timer based on its id and then send it back on the channel
82     // provided
83     RemoveTimer(uint, Sender<Box<Inner>>),
84 }
85
86 // returns the current time (in milliseconds)
87 pub fn now() -> u64 {
88     unsafe {
89         let mut now: libc::timeval = mem::zeroed();
90         assert_eq!(c::gettimeofday(&mut now, ptr::null_mut()), 0);
91         return (now.tv_sec as u64) * 1000 + (now.tv_usec as u64) / 1000;
92     }
93 }
94
95 fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) {
96     let mut set: c::fd_set = unsafe { mem::zeroed() };
97
98     let mut fd = FileDesc::new(input, true);
99     let mut timeout: libc::timeval = unsafe { mem::zeroed() };
100
101     // active timers are those which are able to be selected upon (and it's a
102     // sorted list, and dead timers are those which have expired, but ownership
103     // hasn't yet been transferred back to the timer itself.
104     let mut active: Vec<Box<Inner>> = vec![];
105     let mut dead = vec![];
106
107     // inserts a timer into an array of timers (sorted by firing time)
108     fn insert(t: Box<Inner>, active: &mut Vec<Box<Inner>>) {
109         match active.iter().position(|tm| tm.target > t.target) {
110             Some(pos) => { active.insert(pos, t); }
111             None => { active.push(t); }
112         }
113     }
114
115     // signals the first requests in the queue, possible re-enqueueing it.
116     fn signal(active: &mut Vec<Box<Inner>>,
117               dead: &mut Vec<(uint, Box<Inner>)>) {
118         let mut timer = match active.remove(0) {
119             Some(timer) => timer, None => return
120         };
121         let mut cb = timer.cb.take().unwrap();
122         cb.call();
123         if timer.repeat {
124             timer.cb = Some(cb);
125             timer.target += timer.interval;
126             insert(timer, active);
127         } else {
128             dead.push((timer.id, timer));
129         }
130     }
131
132     'outer: loop {
133         let timeout = if active.len() == 0 {
134             // Empty array? no timeout (wait forever for the next request)
135             ptr::null_mut()
136         } else {
137             let now = now();
138             // If this request has already expired, then signal it and go
139             // through another iteration
140             if active[0].target <= now {
141                 signal(&mut active, &mut dead);
142                 continue;
143             }
144
145             // The actual timeout listed in the requests array is an
146             // absolute date, so here we translate the absolute time to a
147             // relative time.
148             let tm = active[0].target - now;
149             timeout.tv_sec = (tm / 1000) as libc::time_t;
150             timeout.tv_usec = ((tm % 1000) * 1000) as libc::suseconds_t;
151             &mut timeout as *mut libc::timeval
152         };
153
154         c::fd_set(&mut set, input);
155         match unsafe {
156             c::select(input + 1, &mut set, ptr::null_mut(),
157                       ptr::null_mut(), timeout)
158         } {
159             // timed out
160             0 => signal(&mut active, &mut dead),
161
162             // file descriptor write woke us up, we've got some new requests
163             1 => {
164                 loop {
165                     match messages.try_recv() {
166                         Err(comm::Disconnected) => {
167                             assert!(active.len() == 0);
168                             break 'outer;
169                         }
170
171                         Ok(NewTimer(timer)) => insert(timer, &mut active),
172
173                         Ok(RemoveTimer(id, ack)) => {
174                             match dead.iter().position(|&(i, _)| id == i) {
175                                 Some(i) => {
176                                     let (_, i) = dead.remove(i).unwrap();
177                                     ack.send(i);
178                                     continue
179                                 }
180                                 None => {}
181                             }
182                             let i = active.iter().position(|i| i.id == id);
183                             let i = i.expect("no timer found");
184                             let t = active.remove(i).unwrap();
185                             ack.send(t);
186                         }
187                         Err(..) => break
188                     }
189                 }
190
191                 // drain the file descriptor
192                 let mut buf = [0];
193                 assert_eq!(fd.inner_read(buf).ok().unwrap(), 1);
194             }
195
196             -1 if os::errno() == libc::EINTR as int => {}
197             n => fail!("helper thread failed in select() with error: {} ({})",
198                        n, os::last_os_error())
199         }
200     }
201 }
202
203 impl Timer {
204     pub fn new() -> IoResult<Timer> {
205         // See notes above regarding using int return value
206         // instead of ()
207         HELPER.boot(|| {}, helper);
208
209         static ID: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
210         let id = ID.fetch_add(1, atomic::Relaxed);
211         Ok(Timer {
212             id: id,
213             inner: Some(box Inner {
214                 cb: None,
215                 interval: 0,
216                 target: 0,
217                 repeat: false,
218                 id: id,
219             })
220         })
221     }
222
223     pub fn sleep(ms: u64) {
224         let mut to_sleep = libc::timespec {
225             tv_sec: (ms / 1000) as libc::time_t,
226             tv_nsec: ((ms % 1000) * 1000000) as libc::c_long,
227         };
228         while unsafe { libc::nanosleep(&to_sleep, &mut to_sleep) } != 0 {
229             if os::errno() as int != libc::EINTR as int {
230                 fail!("failed to sleep, but not because of EINTR?");
231             }
232         }
233     }
234
235     fn inner(&mut self) -> Box<Inner> {
236         match self.inner.take() {
237             Some(i) => i,
238             None => {
239                 let (tx, rx) = channel();
240                 HELPER.send(RemoveTimer(self.id, tx));
241                 rx.recv()
242             }
243         }
244     }
245 }
246
247 impl rtio::RtioTimer for Timer {
248     fn sleep(&mut self, msecs: u64) {
249         let mut inner = self.inner();
250         inner.cb = None; // cancel any previous request
251         self.inner = Some(inner);
252
253         Timer::sleep(msecs);
254     }
255
256     fn oneshot(&mut self, msecs: u64, cb: Box<rtio::Callback + Send>) {
257         let now = now();
258         let mut inner = self.inner();
259
260         inner.repeat = false;
261         inner.cb = Some(cb);
262         inner.interval = msecs;
263         inner.target = now + msecs;
264
265         HELPER.send(NewTimer(inner));
266     }
267
268     fn period(&mut self, msecs: u64, cb: Box<rtio::Callback + Send>) {
269         let now = now();
270         let mut inner = self.inner();
271
272         inner.repeat = true;
273         inner.cb = Some(cb);
274         inner.interval = msecs;
275         inner.target = now + msecs;
276
277         HELPER.send(NewTimer(inner));
278     }
279 }
280
281 impl Drop for Timer {
282     fn drop(&mut self) {
283         self.inner = Some(self.inner());
284     }
285 }