timerfd can be emulated using eventfd

The necessary background knowledge for this post is knowing about the Linux features "timerfd" and "eventfd".

You can read 8 bytes from a timerfd, and you'll get the number of expiration since the last read.

As it happens, that neatly matches the interface of eventfd: You can read 8 bytes from an eventfd, and you'll get the number of events that have been written to the eventfd since the last read.

So if you set up your timerfd up-front and only then inject it into the rest of the program, you can place "time" under userspace control by replacing the timerfd with an eventfd, and only writing to the eventfd when you want to signal a "time event".

So, if you only interact with time through reading a timerfd, then you can fully hide time behind a nice, low-level abstraction boundary.

I think one can argue that any well-designed application should not need to interact with time at all; and, if it does need to interact with time, it should be able to restrict that interaction to reading on some number of pre-created timerfds, getting a count of how many "time events" have happened. And if you do that, you'll be able to swap those timerfds out for eventfds if you ever figure out a way to remove your dependency on time.

This post is inspired by the time namespacing patches that were recently posted on LKML. I understand that time namespacing might be needed for backward compatibility, but a timerfd/eventfd-based approach to virtualizing time seems better, and a natural evolution of Unix.

And what if we don't care about naturally evolving Unix, and we're willing to go to some fully-fledged capability-secure object oriented OS like KeyKOS? I still think it might be better for programs to depend on just a generic "event notifier" object, like with timerfd/eventfd, rather than depending on a more rich "clock" interface. Programs shouldn't depend on time, after all, so they shouldn't know about "clocks".

Created: 2018-09-23 Sun 02:14