aboutsummaryrefslogtreecommitdiff
path: root/src/linux/poll.rs
blob: 12809f010d429c9c264924ba6b0f63db2cc4b860 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
269
270
271
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
// Copyright 2019 Intel Corporation. All Rights Reserved.
//
// Copyright 2017 The Chromium OS Authors. All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause

//! Traits and structures for working with
//! [`epoll`](http://man7.org/linux/man-pages/man7/epoll.7.html)

use std::cell::{Cell, Ref, RefCell};
use std::cmp::min;
use std::fs::File;
use std::i32;
use std::i64;
use std::io::{stderr, Cursor, Write};
use std::marker::PhantomData;
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
use std::ptr::null_mut;
use std::slice;
use std::thread;
use std::time::Duration;

use libc::{
    c_int, epoll_create1, epoll_ctl, epoll_event, epoll_wait, EINTR, EPOLLERR, EPOLLHUP, EPOLLIN,
    EPOLLOUT, EPOLL_CLOEXEC, EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD,
};

use crate::errno::{errno_result, Error, Result};

macro_rules! handle_eintr_errno {
    ($x:expr) => {{
        let mut res;
        loop {
            res = $x;
            if res != -1 || Error::last() != Error::new(EINTR) {
                break;
            }
        }
        res
    }};
}

const POLL_CONTEXT_MAX_EVENTS: usize = 16;

/// A wrapper of raw `libc::epoll_event`.
///
/// This should only be used with [`EpollContext`](struct.EpollContext.html).
pub struct EpollEvents(RefCell<[epoll_event; POLL_CONTEXT_MAX_EVENTS]>);

impl EpollEvents {
    /// Creates a new EpollEvents.
    pub fn new() -> EpollEvents {
        EpollEvents(RefCell::new(
            [epoll_event { events: 0, u64: 0 }; POLL_CONTEXT_MAX_EVENTS],
        ))
    }
}

impl Default for EpollEvents {
    fn default() -> Self {
        Self::new()
    }
}

/// Trait for a token that can be associated with an `fd` in a [`PollContext`](struct.PollContext.html).
///
/// Simple enums that have no or primitive variant data can use the `#[derive(PollToken)]`
/// custom derive to implement this trait.
pub trait PollToken {
    /// Converts this token into a u64 that can be turned back into a token via `from_raw_token`.
    fn as_raw_token(&self) -> u64;

    /// Converts a raw token as returned from `as_raw_token` back into a token.
    ///
    /// It is invalid to give a raw token that was not returned via `as_raw_token` from the same
    /// `Self`. The implementation can expect that this will never happen as a result of its usage
    /// in `PollContext`.
    fn from_raw_token(data: u64) -> Self;
}

impl PollToken for usize {
    fn as_raw_token(&self) -> u64 {
        *self as u64
    }

    fn from_raw_token(data: u64) -> Self {
        data as Self
    }
}

impl PollToken for u64 {
    fn as_raw_token(&self) -> u64 {
        *self as u64
    }

    fn from_raw_token(data: u64) -> Self {
        data as Self
    }
}

impl PollToken for u32 {
    fn as_raw_token(&self) -> u64 {
        u64::from(*self)
    }

    fn from_raw_token(data: u64) -> Self {
        data as Self
    }
}

impl PollToken for u16 {
    fn as_raw_token(&self) -> u64 {
        u64::from(*self)
    }

    fn from_raw_token(data: u64) -> Self {
        data as Self
    }
}

impl PollToken for u8 {
    fn as_raw_token(&self) -> u64 {
        u64::from(*self)
    }

    fn from_raw_token(data: u64) -> Self {
        data as Self
    }
}

impl PollToken for () {
    fn as_raw_token(&self) -> u64 {
        0
    }

    fn from_raw_token(_data: u64) -> Self {}
}

/// An event returned by [`PollContext::wait`](struct.PollContext.html#method.wait).
pub struct PollEvent<'a, T> {
    event: &'a epoll_event,
    token: PhantomData<T>, // Needed to satisfy usage of T
}

impl<'a, T: PollToken> PollEvent<'a, T> {
    /// Gets the token associated in
    /// [`PollContext::add`](struct.PollContext.html#method.add) with this event.
    pub fn token(&self) -> T {
        T::from_raw_token(self.event.u64)
    }

    /// Get the raw events returned by the kernel.
    pub fn raw_events(&self) -> u32 {
        self.event.events
    }

    /// Checks if the event is readable.
    ///
    /// True if the `fd` associated with this token in
    /// [`PollContext::add`](struct.PollContext.html#method.add) is readable.
    pub fn readable(&self) -> bool {
        self.event.events & (EPOLLIN as u32) != 0
    }

    /// Checks if the event is writable.
    ///
    /// True if the `fd` associated with this token in
    /// [`PollContext::add`](struct.PollContext.html#method.add) is writable.
    pub fn writable(&self) -> bool {
        self.event.events & (EPOLLOUT as u32) != 0
    }

    /// Checks if the event has been hangup on.
    ///
    /// True if the `fd` associated with this token in
    /// [`PollContext::add`](struct.PollContext.html#method.add) has been hungup on.
    pub fn hungup(&self) -> bool {
        self.event.events & (EPOLLHUP as u32) != 0
    }

    /// Checks if the event has associated error conditions.
    ///
    /// True if the `fd` associated with this token in
    /// [`PollContext::add`](struct.PollContext.html#method.add) has associated error conditions.
    pub fn has_error(&self) -> bool {
        self.event.events & (EPOLLERR as u32) != 0
    }
}

/// An iterator over a subset of events returned by
/// [`PollContext::wait`](struct.PollContext.html#method.wait).
pub struct PollEventIter<'a, I, T>
where
    I: Iterator<Item = &'a epoll_event>,
{
    mask: u32,
    iter: I,
    tokens: PhantomData<[T]>, // Needed to satisfy usage of T
}

impl<'a, I, T> Iterator for PollEventIter<'a, I, T>
where
    I: Iterator<Item = &'a epoll_event>,
    T: PollToken,
{
    type Item = PollEvent<'a, T>;
    fn next(&mut self) -> Option<Self::Item> {
        let mask = self.mask;
        self.iter
            .find(|event| (event.events & mask) != 0)
            .map(|event| PollEvent {
                event,
                token: PhantomData,
            })
    }
}

/// The list of events returned by [`PollContext::wait`](struct.PollContext.html#method.wait).
pub struct PollEvents<'a, T> {
    count: usize,
    events: Ref<'a, [epoll_event; POLL_CONTEXT_MAX_EVENTS]>,
    tokens: PhantomData<[T]>, // Needed to satisfy usage of T
}

impl<'a, T: PollToken> PollEvents<'a, T> {
    /// Creates owned structure from borrowed [`PollEvents`](struct.PollEvents.html).
    ///
    /// Copies the events to an owned structure so the reference to this (and by extension
    /// [`PollContext`](struct.PollContext.html)) can be dropped.
    pub fn to_owned(&self) -> PollEventsOwned<T> {
        PollEventsOwned {
            count: self.count,
            events: RefCell::new(*self.events),
            tokens: PhantomData,
        }
    }

    /// Iterates over each event.
    pub fn iter(&self) -> PollEventIter<'_, slice::Iter<'_, epoll_event>, T> {
        PollEventIter {
            mask: 0xffff_ffff,
            iter: self.events[..self.count].iter(),
            tokens: PhantomData,
        }
    }

    /// Iterates over each readable event.
    pub fn iter_readable(&self) -> PollEventIter<'_, slice::Iter<'_, epoll_event>, T> {
        PollEventIter {
            mask: EPOLLIN as u32,
            iter: self.events[..self.count].iter(),
            tokens: PhantomData,
        }
    }

    /// Iterates over each hungup event.
    pub fn iter_hungup(&self) -> PollEventIter<'_, slice::Iter<'_, epoll_event>, T> {
        PollEventIter {
            mask: EPOLLHUP as u32,
            iter: self.events[..self.count].iter(),
            tokens: PhantomData,
        }
    }
}

/// A deep copy of the event records from [`PollEvents`](struct.PollEvents.html).
pub struct PollEventsOwned<T> {
    count: usize,
    events: RefCell<[epoll_event; POLL_CONTEXT_MAX_EVENTS]>,
    tokens: PhantomData<T>, // Needed to satisfy usage of T
}

impl<T: PollToken> PollEventsOwned<T> {
    /// Creates borrowed structure from owned structure
    /// [`PollEventsOwned`](struct.PollEventsOwned.html).
    ///
    /// Takes a reference to the events so it can be iterated via methods in
    /// [`PollEvents`](struct.PollEvents.html).
    pub fn as_ref(&self) -> PollEvents<'_, T> {
        PollEvents {
            count: self.count,
            events: self.events.borrow(),
            tokens: PhantomData,
        }
    }
}

/// Watching events taken by [`PollContext`](struct.PollContext.html).
#[derive(Copy, Clone)]
pub struct WatchingEvents(u32);

impl WatchingEvents {
    /// Returns empty `WatchingEvents`.
    #[inline(always)]
    pub fn empty() -> WatchingEvents {
        WatchingEvents(0)
    }

    /// Creates a new `WatchingEvents` with a specified value.
    ///
    /// Builds `WatchingEvents` from raw `epoll_event`.
    ///
    /// # Arguments
    ///
    /// * `raw`: the events to be created for watching.
    #[inline(always)]
    pub fn new(raw: u32) -> WatchingEvents {
        WatchingEvents(raw)
    }

    /// Sets read events.
    ///
    /// Sets the events to be readable.
    #[inline(always)]
    pub fn set_read(self) -> WatchingEvents {
        WatchingEvents(self.0 | EPOLLIN as u32)
    }

    /// Sets write events.
    ///
    /// Sets the events to be writable.
    #[inline(always)]
    pub fn set_write(self) -> WatchingEvents {
        WatchingEvents(self.0 | EPOLLOUT as u32)
    }

    /// Gets the underlying epoll events.
    pub fn get_raw(&self) -> u32 {
        self.0
    }
}

/// A wrapper of linux [`epoll`](http://man7.org/linux/man-pages/man7/epoll.7.html).
///
/// It provides similar interface to [`PollContext`](struct.PollContext.html).
/// It is thread safe while PollContext is not. It requires user to pass in a reference of
/// EpollEvents while PollContext does not. Always use PollContext if you don't need to access the
/// same epoll from different threads.
///
/// # Examples
///
/// ```
/// extern crate vmm_sys_util;
/// use vmm_sys_util::eventfd::EventFd;
/// use vmm_sys_util::poll::{EpollContext, EpollEvents};
///
/// let evt = EventFd::new(0).unwrap();
/// let ctx: EpollContext<u32> = EpollContext::new().unwrap();
/// let events = EpollEvents::new();
///
/// evt.write(1).unwrap();
/// ctx.add(&evt, 1).unwrap();
///
/// for event in ctx.wait(&events).unwrap().iter_readable() {
///     assert_eq!(event.token(), 1);
/// }
/// ```
pub struct EpollContext<T> {
    epoll_ctx: File,
    // Needed to satisfy usage of T
    tokens: PhantomData<[T]>,
}

impl<T: PollToken> EpollContext<T> {
    /// Creates a new `EpollContext`.
    ///
    /// Uses [`epoll_create1`](http://man7.org/linux/man-pages/man2/epoll_create.2.html)
    /// to create a new epoll fd.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate vmm_sys_util;
    /// use vmm_sys_util::poll::EpollContext;
    ///
    /// let ctx: EpollContext<usize> = EpollContext::new().unwrap();
    /// ```
    pub fn new() -> Result<EpollContext<T>> {
        // SAFETY: Safe because we check the return value.
        let epoll_fd = unsafe { epoll_create1(EPOLL_CLOEXEC) };
        if epoll_fd < 0 {
            return errno_result();
        }
        Ok(EpollContext {
            // SAFETY: Safe because we verified that the FD is valid and we trust `epoll_create1`.
            epoll_ctx: unsafe { File::from_raw_fd(epoll_fd) },
            tokens: PhantomData,
        })
    }

    /// Adds the given `fd` to this context and associates the given
    /// `token` with the `fd`'s readable events.
    ///
    /// A `fd` can only be added once and does not need to be kept open.
    /// If the `fd` is dropped and there were no duplicated file descriptors
    /// (i.e. adding the same descriptor with a different FD number) added
    /// to this context, events will not be reported by `wait` anymore.
    ///
    /// # Arguments
    ///
    /// * `fd`: the target file descriptor to be added.
    /// * `token`: a `PollToken` implementation, used to be as u64 of `libc::epoll_event` structure.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate vmm_sys_util;
    /// use vmm_sys_util::eventfd::EventFd;
    /// use vmm_sys_util::poll::EpollContext;
    ///
    /// let evt = EventFd::new(0).unwrap();
    /// let ctx: EpollContext<u32> = EpollContext::new().unwrap();
    /// ctx.add(&evt, 1).unwrap();
    /// ```
    pub fn add(&self, fd: &dyn AsRawFd, token: T) -> Result<()> {
        self.add_fd_with_events(fd, WatchingEvents::empty().set_read(), token)
    }

    /// Adds the given `fd` to this context, watching for the specified `events`
    /// and associates the given 'token' with those events.
    ///
    /// A `fd` can only be added once and does not need to be kept open. If the `fd`
    /// is dropped and there were no duplicated file descriptors (i.e. adding the same
    /// descriptor with a different FD number) added to this context, events will
    /// not be reported by `wait` anymore.
    ///
    /// # Arguments
    ///
    /// * `fd`: the target file descriptor to be added.
    /// * `events`: specifies the events to be watched.
    /// * `token`: a `PollToken` implementation, used to be as u64 of `libc::epoll_event` structure.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate vmm_sys_util;
    /// use vmm_sys_util::eventfd::EventFd;
    /// use vmm_sys_util::poll::{EpollContext, WatchingEvents};
    ///
    /// let evt = EventFd::new(0).unwrap();
    /// let ctx: EpollContext<u32> = EpollContext::new().unwrap();
    /// ctx.add_fd_with_events(&evt, WatchingEvents::empty().set_read(), 1)
    ///     .unwrap();
    /// ```
    pub fn add_fd_with_events(
        &self,
        fd: &dyn AsRawFd,
        events: WatchingEvents,
        token: T,
    ) -> Result<()> {
        let mut evt = epoll_event {
            events: events.get_raw(),
            u64: token.as_raw_token(),
        };
        // SAFETY: Safe because we give a valid epoll FD and FD to watch, as well as a
        // valid epoll_event structure. Then we check the return value.
        let ret = unsafe {
            epoll_ctl(
                self.epoll_ctx.as_raw_fd(),
                EPOLL_CTL_ADD,
                fd.as_raw_fd(),
                &mut evt,
            )
        };
        if ret < 0 {
            return errno_result();
        };
        Ok(())
    }

    /// Changes the setting associated with the given `fd` in this context.
    ///
    /// If `fd` was previously added to this context, the watched events will be replaced with
    /// `events` and the token associated with it will be replaced with the given `token`.
    ///
    /// # Arguments
    ///
    /// * `fd`: the target file descriptor to be performed.
    /// * `events`: specifies the events to be watched.
    /// * `token`: a `PollToken` implementation, used to be as u64 of `libc::epoll_event` structure.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate vmm_sys_util;
    /// use vmm_sys_util::eventfd::EventFd;
    /// use vmm_sys_util::poll::{EpollContext, WatchingEvents};
    ///
    /// let evt = EventFd::new(0).unwrap();
    /// let ctx: EpollContext<u32> = EpollContext::new().unwrap();
    /// ctx.add_fd_with_events(&evt, WatchingEvents::empty().set_read(), 1)
    ///     .unwrap();
    /// ctx.modify(&evt, WatchingEvents::empty().set_write(), 2)
    ///     .unwrap();
    /// ```
    pub fn modify(&self, fd: &dyn AsRawFd, events: WatchingEvents, token: T) -> Result<()> {
        let mut evt = epoll_event {
            events: events.0,
            u64: token.as_raw_token(),
        };
        // SAFETY: Safe because we give a valid epoll FD and FD to modify, as well as a valid
        // epoll_event structure. Then we check the return value.
        let ret = unsafe {
            epoll_ctl(
                self.epoll_ctx.as_raw_fd(),
                EPOLL_CTL_MOD,
                fd.as_raw_fd(),
                &mut evt,
            )
        };
        if ret < 0 {
            return errno_result();
        };
        Ok(())
    }

    /// Deletes the given `fd` from this context.
    ///
    /// If an `fd`'s token shows up in the list of hangup events, it should be removed using this
    /// method or by closing/dropping (if and only if the fd was never dup()'d/fork()'d) the `fd`.
    /// Failure to do so will cause the `wait` method to always return immediately, causing ~100%
    /// CPU load.
    ///
    /// # Arguments
    ///
    /// * `fd`: the target file descriptor to be removed.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate vmm_sys_util;
    /// use vmm_sys_util::eventfd::EventFd;
    /// use vmm_sys_util::poll::EpollContext;
    ///
    /// let evt = EventFd::new(0).unwrap();
    /// let ctx: EpollContext<u32> = EpollContext::new().unwrap();
    /// ctx.add(&evt, 1).unwrap();
    /// ctx.delete(&evt).unwrap();
    /// ```
    pub fn delete(&self, fd: &dyn AsRawFd) -> Result<()> {
        // SAFETY: Safe because we give a valid epoll FD and FD to stop watching. Then we check
        // the return value.
        let ret = unsafe {
            epoll_ctl(
                self.epoll_ctx.as_raw_fd(),
                EPOLL_CTL_DEL,
                fd.as_raw_fd(),
                null_mut(),
            )
        };
        if ret < 0 {
            return errno_result();
        };
        Ok(())
    }

    /// Waits for any events to occur in FDs that were previously added to this context.
    ///
    /// The events are level-triggered, meaning that if any events are unhandled (i.e. not reading
    /// for readable events and not closing for hungup events), subsequent calls to `wait` will
    /// return immediately. The consequence of not handling an event perpetually while calling
    /// `wait` is that the callers loop will degenerated to busy loop polling, pinning a CPU to
    /// ~100% usage.
    ///
    /// # Arguments
    ///
    /// * `events`: the events to wait for.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate vmm_sys_util;
    /// use vmm_sys_util::eventfd::EventFd;
    /// use vmm_sys_util::poll::{EpollContext, EpollEvents};
    ///
    /// let evt = EventFd::new(0).unwrap();
    /// let ctx: EpollContext<u32> = EpollContext::new().unwrap();
    /// let events = EpollEvents::new();
    ///
    /// evt.write(1).unwrap();
    /// ctx.add(&evt, 1).unwrap();
    ///
    /// for event in ctx.wait(&events).unwrap().iter_readable() {
    ///     assert_eq!(event.token(), 1);
    /// }
    /// ```
    pub fn wait<'a>(&self, events: &'a EpollEvents) -> Result<PollEvents<'a, T>> {
        self.wait_timeout(events, Duration::new(i64::MAX as u64, 0))
    }

    /// Like [`wait`](struct.EpollContext.html#method.wait) except will only block for a
    /// maximum of the given `timeout`.
    ///
    /// This may return earlier than `timeout` with zero events if the duration indicated exceeds
    /// system limits.
    ///
    /// # Arguments
    ///
    /// * `events`: the events to wait for.
    /// * `timeout`: specifies the timeout that will block.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate vmm_sys_util;
    /// # use std::time::Duration;
    /// use vmm_sys_util::eventfd::EventFd;
    /// use vmm_sys_util::poll::{EpollContext, EpollEvents};
    ///
    /// let evt = EventFd::new(0).unwrap();
    /// let ctx: EpollContext<u32> = EpollContext::new().unwrap();
    /// let events = EpollEvents::new();
    ///
    /// evt.write(1).unwrap();
    /// ctx.add(&evt, 1).unwrap();
    /// for event in ctx
    ///     .wait_timeout(&events, Duration::new(100, 0))
    ///     .unwrap()
    ///     .iter_readable()
    /// {
    ///     assert_eq!(event.token(), 1);
    /// }
    /// ```
    pub fn wait_timeout<'a>(
        &self,
        events: &'a EpollEvents,
        timeout: Duration,
    ) -> Result<PollEvents<'a, T>> {
        let timeout_millis = if timeout.as_secs() as i64 == i64::max_value() {
            // We make the convenient assumption that 2^63 seconds is an effectively unbounded time
            // frame. This is meant to mesh with `wait` calling us with no timeout.
            -1
        } else {
            // In cases where we the number of milliseconds would overflow an i32, we substitute the
            // maximum timeout which is ~24.8 days.
            let millis = timeout
                .as_secs()
                .checked_mul(1_000)
                .and_then(|ms| ms.checked_add(u64::from(timeout.subsec_nanos()) / 1_000_000))
                .unwrap_or(i32::max_value() as u64);
            min(i32::max_value() as u64, millis) as i32
        };
        let ret = {
            let mut epoll_events = events.0.borrow_mut();
            let max_events = epoll_events.len() as c_int;
            // SAFETY: Safe because we give an epoll context and a properly sized epoll_events
            // array pointer, which we trust the kernel to fill in properly.
            unsafe {
                handle_eintr_errno!(epoll_wait(
                    self.epoll_ctx.as_raw_fd(),
                    &mut epoll_events[0],
                    max_events,
                    timeout_millis
                ))
            }
        };
        if ret < 0 {
            return errno_result();
        }
        let epoll_events = events.0.borrow();
        let events = PollEvents {
            count: ret as usize,
            events: epoll_events,
            tokens: PhantomData,
        };
        Ok(events)
    }
}

impl<T: PollToken> AsRawFd for EpollContext<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.epoll_ctx.as_raw_fd()
    }
}

impl<T: PollToken> IntoRawFd for EpollContext<T> {
    fn into_raw_fd(self) -> RawFd {
        self.epoll_ctx.into_raw_fd()
    }
}

/// Used to poll multiple objects that have file descriptors.
///
/// # Example
///
/// ```
/// # use vmm_sys_util::errno::Result;
/// # use vmm_sys_util::eventfd::EventFd;
/// # use vmm_sys_util::poll::{PollContext, PollEvents};
/// let evt1 = EventFd::new(0).unwrap();
/// let evt2 = EventFd::new(0).unwrap();
/// evt2.write(1).unwrap();
///
/// let ctx: PollContext<u32> = PollContext::new().unwrap();
/// ctx.add(&evt1, 1).unwrap();
/// ctx.add(&evt2, 2).unwrap();
///
/// let pollevents: PollEvents<u32> = ctx.wait().unwrap();
/// let tokens: Vec<u32> = pollevents.iter_readable().map(|e| e.token()).collect();
/// assert_eq!(&tokens[..], &[2]);
/// ```
pub struct PollContext<T> {
    epoll_ctx: EpollContext<T>,

    // We use a RefCell here so that the `wait` method only requires an immutable self reference
    // while returning the events (encapsulated by PollEvents). Without the RefCell, `wait` would
    // hold a mutable reference that lives as long as its returned reference (i.e. the PollEvents),
    // even though that reference is immutable. This is terribly inconvenient for the caller because
    // the borrow checking would prevent them from using `delete` and `add` while the events are in
    // scope.
    events: EpollEvents,

    // Hangup busy loop detection variables. See `check_for_hungup_busy_loop`.
    check_for_hangup: bool,
    hangups: Cell<usize>,
    max_hangups: Cell<usize>,
}

impl<T: PollToken> PollContext<T> {
    /// Creates a new `PollContext`.
    pub fn new() -> Result<PollContext<T>> {
        Ok(PollContext {
            epoll_ctx: EpollContext::new()?,
            events: EpollEvents::new(),
            check_for_hangup: true,
            hangups: Cell::new(0),
            max_hangups: Cell::new(0),
        })
    }

    /// Enable/disable of checking for unhandled hangup events.
    pub fn set_check_for_hangup(&mut self, enable: bool) {
        self.check_for_hangup = enable;
    }

    /// Adds the given `fd` to this context and associates the given `token` with the `fd`'s
    /// readable events.
    ///
    /// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and
    /// there were no duplicated file descriptors (i.e. adding the same descriptor with a different
    /// FD number) added to this context, events will not be reported by `wait` anymore.
    ///
    /// # Arguments
    ///
    /// * `fd`: the target file descriptor to be added.
    /// * `token`: a `PollToken` implementation, used to be as u64 of `libc::epoll_event` structure.
    pub fn add(&self, fd: &dyn AsRawFd, token: T) -> Result<()> {
        self.add_fd_with_events(fd, WatchingEvents::empty().set_read(), token)
    }

    /// Adds the given `fd` to this context, watching for the specified events and associates the
    /// given 'token' with those events.
    ///
    /// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and
    /// there were no duplicated file descriptors (i.e. adding the same descriptor with a different
    /// FD number) added to this context, events will not be reported by `wait` anymore.
    ///
    /// # Arguments
    ///
    /// * `fd`: the target file descriptor to be added.
    /// * `events`: specifies the events to be watched.
    /// * `token`: a `PollToken` implementation, used to be as u64 of `libc::epoll_event` structure.
    pub fn add_fd_with_events(
        &self,
        fd: &dyn AsRawFd,
        events: WatchingEvents,
        token: T,
    ) -> Result<()> {
        self.epoll_ctx.add_fd_with_events(fd, events, token)?;
        self.hangups.set(0);
        self.max_hangups.set(self.max_hangups.get() + 1);
        Ok(())
    }

    /// Changes the setting associated with the given `fd` in this context.
    ///
    /// If `fd` was previously added to this context, the watched events will be replaced with
    /// `events` and the token associated with it will be replaced with the given `token`.
    ///
    /// # Arguments
    ///
    /// * `fd`: the target file descriptor to be modified.
    /// * `events`: specifies the events to be watched.
    /// * `token`: a `PollToken` implementation, used to be as u64 of `libc::epoll_event` structure.
    pub fn modify(&self, fd: &dyn AsRawFd, events: WatchingEvents, token: T) -> Result<()> {
        self.epoll_ctx.modify(fd, events, token)
    }

    /// Deletes the given `fd` from this context.
    ///
    /// If an `fd`'s token shows up in the list of hangup events, it should be removed using this
    /// method or by closing/dropping (if and only if the fd was never dup()'d/fork()'d) the `fd`.
    /// Failure to do so will cause the `wait` method to always return immediately, causing ~100%
    /// CPU load.
    ///
    /// # Arguments
    ///
    /// * `fd`: the target file descriptor to be removed.
    pub fn delete(&self, fd: &dyn AsRawFd) -> Result<()> {
        self.epoll_ctx.delete(fd)?;
        self.hangups.set(0);
        self.max_hangups.set(self.max_hangups.get() - 1);
        Ok(())
    }

    // This method determines if the the user of wait is misusing the `PollContext` by leaving FDs
    // in this `PollContext` that have been shutdown or hungup on. Such an FD will cause `wait` to
    // return instantly with a hungup event. If that FD is perpetually left in this context, a busy
    // loop burning ~100% of one CPU will silently occur with no human visible malfunction.
    //
    // How do we know if the client of this context is ignoring hangups? A naive implementation
    // would trigger if consecutive wait calls yield hangup events, but there are legitimate cases
    // for this, such as two distinct sockets becoming hungup across two consecutive wait calls. A
    // smarter implementation would only trigger if `delete` wasn't called between waits that
    // yielded hangups. Sadly `delete` isn't the only way to remove an FD from this context. The
    // other way is for the client to close the hungup FD, which automatically removes it from this
    // context. Assuming that the client always uses close, this implementation would too eagerly
    // trigger.
    //
    // The implementation used here keeps an upper bound of FDs in this context using a counter
    // hooked into add/delete (which is imprecise because close can also remove FDs without us
    // knowing). The number of consecutive (no add or delete in between) hangups yielded by wait
    // calls is counted and compared to the upper bound. If the upper bound is exceeded by the
    // consecutive hangups, the implementation triggers the check and logs.
    //
    // This implementation has false negatives because the upper bound can be completely too high,
    // in the worst case caused by only using close instead of delete. However, this method has the
    // advantage of always triggering eventually genuine busy loop cases, requires no dynamic
    // allocations, is fast and constant time to compute, and has no false positives.
    fn check_for_hungup_busy_loop(&self, new_hangups: usize) {
        let old_hangups = self.hangups.get();
        let max_hangups = self.max_hangups.get();
        if old_hangups <= max_hangups && old_hangups + new_hangups > max_hangups {
            let mut buf = [0u8; 512];
            let (res, len) = {
                let mut buf_cursor = Cursor::new(&mut buf[..]);
                (
                    writeln!(
                        &mut buf_cursor,
                        "[{}:{}] busy poll wait loop with hungup FDs detected on thread {}\n",
                        file!(),
                        line!(),
                        thread::current().name().unwrap_or("")
                    ),
                    buf_cursor.position() as usize,
                )
            };

            if res.is_ok() {
                let _ = stderr().write_all(&buf[..len]);
            }
            // This panic is helpful for tests of this functionality.
            #[cfg(test)]
            panic!("hungup busy loop detected");
        }
        self.hangups.set(old_hangups + new_hangups);
    }

    /// Waits for any events to occur in FDs that were previously added to this context.
    ///
    /// The events are level-triggered, meaning that if any events are unhandled (i.e. not reading
    /// for readable events and not closing for hungup events), subsequent calls to `wait` will
    /// return immediately. The consequence of not handling an event perpetually while calling
    /// `wait` is that the callers loop will degenerated to busy loop polling, pinning a CPU to
    /// ~100% usage.
    ///
    /// # Panics
    /// Panics if the returned `PollEvents` structure is not dropped before subsequent `wait` calls.
    pub fn wait(&self) -> Result<PollEvents<'_, T>> {
        self.wait_timeout(Duration::new(i64::MAX as u64, 0))
    }

    /// Like [`wait`](struct.EpollContext.html#method.wait) except will only block for a
    /// maximum of the given `timeout`.
    ///
    /// This may return earlier than `timeout` with zero events if the duration indicated exceeds
    /// system limits.
    ///
    /// # Arguments
    ///
    /// * `timeout`: specify the time that will block.
    pub fn wait_timeout(&self, timeout: Duration) -> Result<PollEvents<'_, T>> {
        let events = self.epoll_ctx.wait_timeout(&self.events, timeout)?;
        let hangups = events.iter_hungup().count();
        if self.check_for_hangup {
            self.check_for_hungup_busy_loop(hangups);
        }
        Ok(events)
    }
}

impl<T: PollToken> AsRawFd for PollContext<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.epoll_ctx.as_raw_fd()
    }
}

impl<T: PollToken> IntoRawFd for PollContext<T> {
    fn into_raw_fd(self) -> RawFd {
        self.epoll_ctx.into_raw_fd()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::eventfd::EventFd;
    use std::os::unix::net::UnixStream;
    use std::time::Instant;

    #[test]
    fn test_poll_context() {
        let evt1 = EventFd::new(0).unwrap();
        let evt2 = EventFd::new(0).unwrap();
        evt1.write(1).unwrap();
        evt2.write(1).unwrap();
        let ctx: PollContext<u32> = PollContext::new().unwrap();
        ctx.add(&evt1, 1).unwrap();
        ctx.add(&evt2, 2).unwrap();

        let mut evt_count = 0;
        while evt_count < 2 {
            for event in ctx.wait().unwrap().iter_readable() {
                evt_count += 1;
                match event.token() {
                    1 => {
                        evt1.read().unwrap();
                        ctx.delete(&evt1).unwrap();
                    }
                    2 => {
                        evt2.read().unwrap();
                        ctx.delete(&evt2).unwrap();
                    }
                    _ => panic!("unexpected token"),
                };
            }
        }
        assert_eq!(evt_count, 2);
    }

    #[test]
    fn test_poll_context_overflow() {
        const EVT_COUNT: usize = POLL_CONTEXT_MAX_EVENTS * 2 + 1;
        let ctx: PollContext<usize> = PollContext::new().unwrap();
        let mut evts = Vec::with_capacity(EVT_COUNT);
        for i in 0..EVT_COUNT {
            let evt = EventFd::new(0).unwrap();
            evt.write(1).unwrap();
            ctx.add(&evt, i).unwrap();
            evts.push(evt);
        }
        let mut evt_count = 0;
        while evt_count < EVT_COUNT {
            for event in ctx.wait().unwrap().iter_readable() {
                evts[event.token()].read().unwrap();
                evt_count += 1;
            }
        }
    }

    #[test]
    #[should_panic]
    fn test_poll_context_hungup() {
        let (s1, s2) = UnixStream::pair().unwrap();
        let ctx: PollContext<u32> = PollContext::new().unwrap();
        ctx.add(&s1, 1).unwrap();

        // Causes s1 to receive hangup events, which we purposefully ignore to trip the detection
        // logic in `PollContext`.
        drop(s2);

        // Should easily panic within this many iterations.
        for _ in 0..1000 {
            ctx.wait().unwrap();
        }
    }

    #[test]
    fn test_poll_context_timeout() {
        let mut ctx: PollContext<u32> = PollContext::new().unwrap();
        let dur = Duration::from_millis(10);
        let start_inst = Instant::now();

        ctx.set_check_for_hangup(false);
        ctx.wait_timeout(dur).unwrap();
        assert!(start_inst.elapsed() >= dur);
    }

    #[test]
    fn test_poll_event() {
        let event = epoll_event {
            events: (EPOLLIN | EPOLLERR | EPOLLOUT | EPOLLHUP) as u32,
            u64: 0x10,
        };
        let ev = PollEvent::<u32> {
            event: &event,
            token: PhantomData,
        };

        assert_eq!(ev.token(), 0x10);
        assert!(ev.readable());
        assert!(ev.writable());
        assert!(ev.hungup());
        assert!(ev.has_error());
        assert_eq!(
            ev.raw_events(),
            (EPOLLIN | EPOLLERR | EPOLLOUT | EPOLLHUP) as u32
        );
    }
}