imsd, engine: the registration through a sleep
The refresh of the registration was due after so many awake seconds: its
gate ran on the steady clock, which stands still in a suspend, while the
network counts the registration's lifetime on. A phone that slept most
of two hours sent no refresh and lost its registration (the dev phone,
KPN, 1.1.0, 2026-11-19: registered 09:15:48 for 7200 s, the network's
NOTIFY of the expiry at 11:16:37, registered again 11:37:38 behind the
fresh-SA throttle). Until now the image imsd was written on did not let
its phone suspend.
The refresh's gate and the renewal of the reg-event subscription ahead
of its granted lifetime's end now run on the boot clock, as the recovery
policy's waits already did. And a timer on CLOCK_BOOTTIME_ALARM, which
the kernel turns into the RTC's alarm for a suspend, is armed at the end
of every turn of the loop that takes no command off the queue (one that
takes a command handles it and goes straight to the next turn) for the
time the new WakeAt names (Imsd:Engine): now while a call or a text is
in flight (the hold below); else, with a registration on a live flow,
the refresh's due time, or the subscription's renewal where that comes
first; with a dead flow under a registration the recovery policy's word;
none where nothing waits to be done. The timer is never read: the waking
is the whole of it, and the loop's own clock checks act once the phone
is awake. A resume by itself sends nothing. Where the kernel gives no
such timer (it takes CAP_WAKE_ALARM) or has no RTC behind it, the
journal says so once.
What imsd waits for with the phone awake must not be cut off by a
suspend either. Beside the call's lock the main thread asks for a second
block inhibitor, in the way it asks for the call's, while a step of the
registration exchanges with the network (the refresh, a reconnect, a
fresh registration, the bring-up) and while a text is being sent, whose
waits (128 s for a MESSAGE's final, 130 s for the report) count awake
seconds; not while a bring-up waits out a hold the network set, which
can be an hour. A step can begin before the bus connection is there: its
lock, like a call's, is asked for when the connection comes. For a
suspend that begins all the same (logind refused such a lock where a
suspend's operation was already running; a request can tell it to ignore
inhibitors) there is the alarm: under a call and under a text in flight,
and where a step is due that the next turn runs (but for the look after
a local wait, which has its own slower time), it is set 1.9 s ahead at
every such turn, and the kernel refuses a suspend under an alarm less
than two seconds ahead (alarmtimer_suspend, read at v7.3) where the
suspend comes to that check before the alarm has fired: it syncs and
freezes the processes first. A registration step keeps it at most 30 s
ahead while it waits for the network, whatever else is in flight, so
that a sleep that begins under the step ends there. The alarm fires
once, and a wait can outlast the sleep it ended: it is set anew before
every second of such a wait (a connect's answer, the pause before the
next try, a REGISTER's answer). One of those waits is a receive with a
timeout (the fresh registration's first answer, on a socket of its own),
which the kernel ends with EINTR when a suspend freezes the thread: it
is taken up again for the rest of its time. The connect for a call's
resend is no step and sets the 1.9 s anew the same way, before every
second. A wait for a helper program keeps the alarm that stood when it
began.
A coverage gap must not cost the phone its sleep. The recovery tried a
reconnect 5 s after each one that failed, over TCP 34 s of waiting for
an answer that cannot come: with a lock around the step and an alarm for
the next, a phone in a cellar would have been held awake 34 s of every
39. While the modem reports no packet service the recovery tries nothing
now and takes no lock, and a dead flow's socket that is still open then
is closed without the FIN's exchange (Abort): over TCP, left open it is
readable at every turn of the loop, which would spin instead of waiting,
and a FIN sent into the gap would hold the address pair against the
reconnect after it, as the FIN of a step that closed its flow after an
unanswered wait does. A Dial that finds the flow dead in a gap ends at
once: the recovery's one immediate try for it tries nothing either, and
the INVITE fails on a flow that is gone. Awake and with no call up, the
modem is asked again every 5 s, the pause that was between two
reconnects. A sleeping phone is woken for the next look after as long
again as the modem has been without service, 10 s at the least and 15
min at the most (RegRecovery::WakeTime), counted from the modem's first
word of no service since the network last answered: the modem's word for
its service starts no count over, and where it alternates at the edge of
coverage an attempt made on it costs its wait under the lock while the
looks keep their pace. Every step that follows no local wait is woken
for at the policy's own time: a reconnect cycle the network was silent
to is no local wait where the modem has service, a fresh attempt it was
silent to never is. The kernel refuses a connect locally for as long as
the old flow's socket holds the address pair, which clears in awake
seconds. That is the other local wait: awake and with no call up, the
next look comes 5 s after each; a sleeping phone is woken for it after
as long again as the kernel's refusals have lasted, 10 s at the least
and 15 min at the most, counted from its first refusal since the modem's
last word of no service or the network's last answer, whichever came
later.
Left as they were, among others: the CRLF keepalive, the reg-event
subscription's Timer F, its retries and its renewal after the network
has ended it, the times SMS over IP measures (its two waits, the
30-minute age-out, its tables) and a step's own waits for the network
count awake seconds. Nothing holds a sleep off under the bring-up
script, which runs before the daemon, nor in the wait before a restart
after a failure: a phone suspended there does not register until it is
awake again. And between the alarm's waking the phone and the step it
woke it for, the loop's next turn, there is neither alarm nor lock; nor
is the alarm set again yet, for up to a second, after it has ended a
sleep under a step's wait (where the freeze has ended the receive of the
fresh registration's first wait with time left, it is set at once), and
a helper program the step goes on to in that second has none until the
step's next wait for the network.
Tested: the suites (WakeAt and the policy's wake after a local wait are
pinned in tests/Engine; the rest is the shell's). On the workstation
(the fp6 journal's 2026-11-25-through-sleep capture,
bench/bench-sleep.sh) the sleep is a preloaded clock_gettime under which
the boot clock runs ahead of the steady clock: with it 50 s ahead a
refresh set for 60 s went out 20 s into the registration, and 1.2.4's
did not; with it 599500 s ahead the subscription was renewed, and
1.2.4's was not; with no jump the refresh came at its awake time and not
before. The second lock was taken and released around a refresh, asked
for again at the stand-in logind's PrepareForSleep(false) where that had
refused it at a refresh's start, and held for the 256 s from a text's
sending to its "failed" where the stand-in network answered no MESSAGE.
In a gap of 40 s (the stand-in modem without packet service, no SYN let
through, the flow closed by the network) no connect was tried and no
lock taken, the daemon's own processor time stayed under a second (an
earlier build of this change, which kept the dead flow's socket through
the gap, used 33.9 s of it), and the reconnect came 3 to 5 s after the
gap's end; a Dial inside such a gap ended at once with nothing reopened
under it, the reconnect then 0.5 to 1.5 s after the gap's end; and in a
gap that let no segment through the daemon had no socket of the old flow
at the gap's end; a daemon started inside a hold of 60 s held no lock
for it. With WAKE_TRACE=1, a test seam, the daemon writes a line
whenever the time the alarm is armed for changes (by the second; one
line for a run of times less than two seconds ahead), with a timer or
without: in a gap that a refresh ran into, with the boot clock put 1000
s ahead inside it, the alarm named 900 s ahead; after the gap's end,
where the old flow's socket had two connects refused, it named no more
than 30 s ahead, and the reconnect came 15 to 16 s after the gap's end;
where the stand-in modem reported service twice inside such a gap, the
alarm named 900 s ahead again after each; where the modem still reported
service when the refresh failed, where the network stayed silent for 80
s after the modem's return, and over UDP, it named no more than 30 s
ahead from the modem's return to the recovery; while a step waited for
the network (a refresh's 12 s, a connect's 12 s and the 10 s before the
next try, a fresh registration's two waits with the stand-in holding its
answers back) it named a new time every second, and through the connect
for a call's resend, which the stand-in answered at once, no time 2 s or
more ahead. Stopped 1.5 s into a fresh registration's wait for its first
401 and continued 2 s later (a stop and a continue end a datagram
receive under a timeout as a freeze does), the daemon registered when
the stand-in's held-back 401 came, five runs of five; an earlier build
of this change and 1.2.4 gave the wait up at the continue, five of five
each. The bench's namespace gives no CAP_WAKE_ALARM: every life of this
daemon there says "no wake alarm (Operation not permitted)" and runs on.
The alarm is the dev phone's (KPN, a 7.3 kernel, this commit's daemon
built with the next commit's version string, the capture's phone/,
2026-11-28), with REFRESH_INTERVAL=120 and deep suspends asked of
logind: every refresh that fell due under a sleep went out within 3 s of
its due time, after a resume whose first interrupt was the RTC's alarm
(1.2.4, in three sleeps of that script as it was on 2026-11-25, on the
same kernel build, sent no refresh in seven minutes); under a call a
suspend told to ignore inhibitors was refused by the kernel (alarmtimer,
-16), twice, systemd-sleep having tried its second state; under a text
in flight logind refused a suspend and the kernel a forced one; and
under a refresh whose REGISTER the phone itself dropped, a forced
suspend a second into the wait was ended by imsd's alarm (the RTC's the
first interrupt, 30.6 s in), after which imsd's timer, zero at the
test's first look, read 29 to 30 s ahead at each of its 32 looks from
0.2 s later to the wait's end, which the test saw about 10 s after that
first look (an earlier build of this change, which set the alarm once
for the wait, read zero at every reading until the wait had ended; in
another run, with two more forced suspends in that wait, it slept to the
test's own alarm of 75 s both times). The re-registration after that
refresh came 71 s after its "no reply", the kernel refusing nine
connects over a minute first (the old flow's socket). Seven recovery
steps that fell due under a sleep ran 1.5 to 3 s after their time (an
earlier build, 2026-11-25). A test program's datagram receive under a
timeout returned EINTR at the phone's resume from a suspend
(evidence/recv-eintr/ there). Not run: a suspend under a fresh
registration's first wait with the daemon on a phone; an alarm clock
with no RTC behind it ("no RTC that can wake the phone"), and a
timerfd_settime that fails ("wake alarm not set"); the alarm's disarming
and "wake trace: none", which nothing reaches once the loop runs; a
second forced suspend under one wait with this commit's daemon on a
phone (the dev phone is not to be suspended within ten seconds of a
resume: the earlier build's run with three did so, and its wifi firmware
crashed; and the wait the test stages, an unanswered refresh's 12 s, is
over at about that time); the 1.9 s through a connect for a call's
resend that waits; a fresh registration's look at the modem finding no
packet service (the reconnect's has run); a bring-up the network defers
or refuses, and a stop during a bring-up's hold; the work's lock asked
for at the bus connection's coming (no record tells that request from
the step's own); a coverage gap on a phone, and the wake for its slower
look; on a phone, a sleep longer than a refresh interval of 1800 s; the
alarm at most 30 s ahead through a step's wait while a text is in
flight, which is read from the code; the subscription's renewal on a
network.
This commit is contained in:
parent
52d4b4f217
commit
3b9c0fed98
4 changed files with 848 additions and 72 deletions
|
|
@ -44,6 +44,7 @@ its subscriber set on the main thread too.
|
|||
#include <signal.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/timerfd.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
|
@ -482,11 +483,17 @@ public:
|
|||
// datagram socket to the same peer — the kernel then delivers that peer's
|
||||
// datagrams here in preference to the unconnected ServerPorts socket on
|
||||
// the same port. A UDP connect() cannot be refused by the peer, so it is
|
||||
// one attempt.
|
||||
bool Connect(const std::string& local, int lport, const std::string& pcscf, int pport, Transport t, int tries = 10, int silentLimit = 0) {
|
||||
// one attempt. `tick` is called before every try and then before every
|
||||
// second of a try's wait for its answer and of the pause before the
|
||||
// next try: what the caller must do at least that often while this
|
||||
// thread waits (the wake alarm, under a registration step and under
|
||||
// the connect for a call's resend).
|
||||
bool Connect(const std::string& local, int lport, const std::string& pcscf, int pport, Transport t, int tries = 10, int silentLimit = 0,
|
||||
const std::function<void()>& tick = {}) {
|
||||
transport_ = t;
|
||||
lastConnectLocal_ = false;
|
||||
int fam = Is6(local) ? AF_INET6 : AF_INET;
|
||||
if (tick) tick();
|
||||
if (t == Transport::Udp) {
|
||||
int fd = socket(fam, SOCK_DGRAM, 0);
|
||||
if (fd < 0) return SocketFailed();
|
||||
|
|
@ -507,6 +514,7 @@ public:
|
|||
}
|
||||
int silent = 0;
|
||||
for (int attempt = 0; attempt < tries; attempt++) {
|
||||
if (tick && attempt > 0) tick();
|
||||
int fd = socket(fam, SOCK_STREAM, 0);
|
||||
if (fd < 0) return SocketFailed();
|
||||
int one = 1;
|
||||
|
|
@ -527,7 +535,7 @@ public:
|
|||
int err = localRefusal ? errno : 0;
|
||||
if (rc < 0 && errno == EINPROGRESS) {
|
||||
pollfd p{fd, POLLOUT, 0};
|
||||
if (poll(&p, 1, 12000) > 0) {
|
||||
if (PollTicked(p, 12000, tick) > 0) {
|
||||
socklen_t el = sizeof err;
|
||||
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el);
|
||||
connected = (err == 0);
|
||||
|
|
@ -554,10 +562,24 @@ public:
|
|||
return false;
|
||||
}
|
||||
Log(std::format("connect failed; retry in 10s ({}) [{}/{}]", why, attempt + 1, tries));
|
||||
sleep(10);
|
||||
for (int s = 0; s < 10; s++) {
|
||||
if (tick) tick();
|
||||
sleep(1);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// poll(2) on one descriptor for `ms`, in pieces of a second with `tick`
|
||||
// called before each where there is one. Answers as poll does.
|
||||
static int PollTicked(pollfd& p, int ms, const std::function<void()>& tick) {
|
||||
if (!tick) return poll(&p, 1, ms);
|
||||
for (;;) {
|
||||
tick();
|
||||
int piece = std::min(ms, 1000);
|
||||
int r = poll(&p, 1, piece);
|
||||
if (r != 0 || (ms -= piece) <= 0) return r;
|
||||
}
|
||||
}
|
||||
// socket() failing is ours, not the network's: logged, and a local
|
||||
// refusal like a connect() the kernel turns down.
|
||||
bool SocketFailed() {
|
||||
|
|
@ -600,7 +622,10 @@ public:
|
|||
if (send(fd_, "\r\n\r\n", 4, MSG_NOSIGNAL) <= 0) alive_ = false;
|
||||
}
|
||||
|
||||
std::optional<std::string> RecvMsg(double timeoutSec) {
|
||||
// The next whole message on the flow, within `timeoutSec`. With a
|
||||
// `tick` the wait for the socket is PollTicked's (Connect has what the
|
||||
// tick is for).
|
||||
std::optional<std::string> RecvMsg(double timeoutSec, const std::function<void()>& tick = {}) {
|
||||
auto deadline = std::chrono::steady_clock::now() +
|
||||
std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(timeoutSec));
|
||||
for (;;) {
|
||||
|
|
@ -609,7 +634,7 @@ public:
|
|||
if (now >= deadline) return std::nullopt;
|
||||
int ms = static_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now).count());
|
||||
pollfd p{fd_, POLLIN, 0};
|
||||
int r = poll(&p, 1, ms);
|
||||
int r = PollTicked(p, ms, tick);
|
||||
if (r <= 0) { if (r == 0) return std::nullopt; if (errno == EINTR) continue; return std::nullopt; }
|
||||
std::optional<std::string> m;
|
||||
if (!ReadOnce(m)) return std::nullopt;
|
||||
|
|
@ -1011,7 +1036,7 @@ struct StatusSnapshot {
|
|||
|
||||
// engine -> main-loop event
|
||||
struct Event {
|
||||
enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState } type;
|
||||
enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState, Work } type;
|
||||
CallInfo info; // Added
|
||||
std::string uni, state, reason; // State/Deleted; SmsState (uni: the message id); SmsReceived (uni: the id)
|
||||
StatusSnapshot status; // Registration/Status
|
||||
|
|
@ -1020,6 +1045,7 @@ struct Event {
|
|||
std::int64_t at = 0; // SmsReceived: when it arrived (epoch seconds)
|
||||
std::string to; // SmsReceived: the subscriber it arrived for (the own number the daemon held then)
|
||||
std::string simOperator; // SmsReceived: the operator id of the SIM it arrived under
|
||||
bool on = false; // Work: a registration step or a text's sending wants the work's lock (true: at its begin, after its wait for a hold) or no longer does (at its end, for such a wait)
|
||||
};
|
||||
|
||||
GDBusConnection* DbusConn = nullptr;
|
||||
|
|
@ -1414,6 +1440,11 @@ GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt
|
|||
// Where logind gives no lock at all (the session bus of --session has no
|
||||
// logind) calls go on without one. The journal says so once until a
|
||||
// call's lock is next given.
|
||||
// A second lock is asked for, in the way the call's is, while the engine has work in flight that waits for
|
||||
// the network: a step of the registration (Engine::Step) or a text being
|
||||
// sent. A suspend under one would leave it where it stood until something
|
||||
// wakes the phone: a text's waits count awake seconds. It is asked for where it is wanted and not
|
||||
// held, released when nothing wants it any more, and the journal has no line for any of that.
|
||||
struct SleepLock {
|
||||
const char* why; // logind's "why": what the lock is held for
|
||||
bool told; // its taking, its release and a refusal go to the journal
|
||||
|
|
@ -1421,6 +1452,8 @@ struct SleepLock {
|
|||
int fd = -1; // the inhibitor's file descriptor (-1: not held)
|
||||
};
|
||||
SleepLock CallLock{"a call", true};
|
||||
SleepLock WorkLock{"a registration step or a text in flight", false};
|
||||
int WorksInFlight = 0; // the engine's Work events, true less false: what wants the work's lock now (a step that waits out a hold is not in it)
|
||||
bool NoSleepLockTold = false; // the journal has a refusal's line since a call's lock was last given
|
||||
void HoldSleepOff(SleepLock& lock, bool want) {
|
||||
lock.want = want;
|
||||
|
|
@ -1464,6 +1497,7 @@ void OnPrepareForSleep(GDBusConnection*, const gchar*, const gchar*, const gchar
|
|||
g_variant_get(params, "(b)", &entering);
|
||||
if (entering) return;
|
||||
HoldSleepOff(CallLock, CallLock.want);
|
||||
HoldSleepOff(WorkLock, WorkLock.want);
|
||||
}
|
||||
|
||||
gboolean OnIdleEvent(gpointer data) {
|
||||
|
|
@ -1508,6 +1542,10 @@ gboolean OnIdleEvent(gpointer data) {
|
|||
Log(std::format("idle: {} — nothing to do; systemctl start imsd when that changes", ev->text));
|
||||
g_main_loop_quit(MainLoop);
|
||||
break;
|
||||
case Event::Type::Work:
|
||||
WorksInFlight = std::max(0, WorksInFlight + (ev->on ? 1 : -1));
|
||||
HoldSleepOff(WorkLock, WorksInFlight > 0);
|
||||
break;
|
||||
case Event::Type::SmsReceived:
|
||||
for (const std::string& to : Subscribers)
|
||||
EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms, ev->at, ev->to, ev->simOperator)));
|
||||
|
|
@ -1685,6 +1723,7 @@ public:
|
|||
}
|
||||
for (;;) {
|
||||
try {
|
||||
Step step(*this);
|
||||
BringUp();
|
||||
break;
|
||||
} catch (const Stopping&) {
|
||||
|
|
@ -1758,6 +1797,7 @@ public:
|
|||
Execute(call_->OnDeadline());
|
||||
MaybeDropCall();
|
||||
}
|
||||
ArmWake(WakeDue());
|
||||
if (auto msg = sip_.RecvMsg(0.3)) OnFlowMessage(*msg);
|
||||
}
|
||||
// shutdown: release an active call, keep the SA/registration for resume
|
||||
|
|
@ -1819,11 +1859,19 @@ private:
|
|||
// after it, not before. False when the engine is stopping.
|
||||
bool WaitForPolicy() {
|
||||
bool waited = false;
|
||||
// No lock under this wait, which can be an hour: nothing is waited
|
||||
// for from the network, and the alarm ends a sleep at its end. For a
|
||||
// step it is called from (the bring-up's) the lock is asked for again after.
|
||||
const int paused = !quit_.load() && recovery_.Next(Boot()).at > Boot() ? steps_ : 0;
|
||||
for (int i = 0; i < paused; i++) PostWork(false);
|
||||
while (!quit_.load() && recovery_.Next(Boot()).at > Boot()) {
|
||||
waited = true;
|
||||
if (auto cmd = PopCmd()) { HandleCmd(*cmd); MaybeDropCall(); continue; }
|
||||
ArmWake(recovery_.Next(Boot()).at); // a wait the phone sleeps under ends with the phone awake
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
for (int i = 0; i < paused; i++) PostWork(true);
|
||||
if (waited) netAlarm_(); // the wait's alarm has fired where the phone slept under it
|
||||
if (waited && !quit_.load()) RefreshPani();
|
||||
return !quit_.load();
|
||||
}
|
||||
|
|
@ -1907,7 +1955,7 @@ private:
|
|||
bool subPending_ = false; // SUBSCRIBE sent, no final yet
|
||||
double subSentAt_ = 0;
|
||||
double subRetryAt_ = 0; // a failed/ended subscription is renewed at this time (0: none due)
|
||||
double subRenewAt_ = 0; // the live subscription is subscribed anew at this time, ahead of its granted expiry (0: none)
|
||||
double subRenewAt_ = 0; // the live subscription is subscribed anew at this time on the boot clock, ahead of its granted expiry (0: none)
|
||||
double subRetryDelay_ = 60; // 60 s doubling to 10 min between failed SUBSCRIBEs
|
||||
int portPs_ = 0; // P-CSCF protected server port (reconnect target)
|
||||
imsd::engine::RegRecovery recovery_; // what to do when the registration stops working
|
||||
|
|
@ -1929,8 +1977,10 @@ private:
|
|||
std::function<void(const std::string&)> callReply_;
|
||||
|
||||
// timers
|
||||
double lastRefresh_ = 0;
|
||||
double lastKa_ = 0;
|
||||
double lastRefresh_ = 0; // on the boot clock (Boot): the registration's lifetime runs at the network while the phone sleeps
|
||||
double lastKa_ = 0; // on the steady clock (Mono)
|
||||
int wakeFd_ = -1; // the wake alarm, a timer on CLOCK_BOOTTIME_ALARM (-2: the kernel gave none)
|
||||
double wakeAt_ = 0; // the boot-clock time it was last armed for, fired or not (0: not armed)
|
||||
std::atomic<bool> quit_{false};
|
||||
bool devMode_ = false;
|
||||
|
||||
|
|
@ -1966,6 +2016,133 @@ private:
|
|||
return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
// The refresh's interval: half the granted lifetime (of 3600 s where none
|
||||
// was granted), within 120-1800 s (REFRESH_INTERVAL= sets it).
|
||||
double RefreshInterval() const {
|
||||
if (const char* o = std::getenv("REFRESH_INTERVAL")) return std::atof(o);
|
||||
long exp = reg_.expiry ? reg_.expiry : 3600;
|
||||
return std::max(120.0, std::min(exp * 0.5, 1800.0));
|
||||
}
|
||||
|
||||
// The wake alarm. The registration's lifetime runs at the network while
|
||||
// the phone sleeps, and the steady clock does not: a refresh counted in
|
||||
// awake seconds comes too late for a phone that sleeps most of the time
|
||||
// (the dev phone, 2026-11-19: asleep for most of a registration's two hours, no refresh, the
|
||||
// binding expired). So the refresh is due on the boot clock, and a timer
|
||||
// on CLOCK_BOOTTIME_ALARM, armed by the loop for the time WakeDue names (ArmWake's other callers arm their own), makes the
|
||||
// kernel wake a sleeping phone then (its RTC's alarm; CAP_WAKE_ALARM,
|
||||
// which the system service has). The descriptor is never read: the
|
||||
// waking is the whole of it, and the loop's own clock checks act once
|
||||
// the phone is awake. Where the kernel gives no such timer the journal
|
||||
// says so once and the daemon runs without: awake, nothing differs.
|
||||
void ArmWake(double at) {
|
||||
if (wakeTrace_) TraceWake(at);
|
||||
if (wakeFd_ == -2 || at == wakeAt_) return;
|
||||
if (wakeFd_ < 0) {
|
||||
// the timer can be had without an RTC behind it, and then
|
||||
// neither wakes the phone nor makes the kernel refuse a suspend:
|
||||
// the clock's resolution is what the kernel answers only with one
|
||||
timespec res{};
|
||||
if (clock_getres(CLOCK_BOOTTIME_ALARM, &res) != 0) {
|
||||
Log("no wake alarm (no RTC that can wake the phone): a sleeping phone is not woken for the registration's refresh");
|
||||
wakeFd_ = -2;
|
||||
return;
|
||||
}
|
||||
wakeFd_ = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_CLOEXEC);
|
||||
if (wakeFd_ < 0) {
|
||||
Log(std::format("no wake alarm ({}): a sleeping phone is not woken for the registration's refresh", std::strerror(errno)));
|
||||
wakeFd_ = -2;
|
||||
return;
|
||||
}
|
||||
Log("wake alarm: a sleeping phone is woken when the registration's refresh is due");
|
||||
}
|
||||
itimerspec its{}; // all zero disarms
|
||||
if (at > 0) {
|
||||
its.it_value.tv_sec = static_cast<time_t>(at);
|
||||
its.it_value.tv_nsec = static_cast<long>((at - std::floor(at)) * 1e9);
|
||||
}
|
||||
if (timerfd_settime(wakeFd_, TFD_TIMER_ABSTIME, &its, nullptr) < 0) {
|
||||
Log(std::format("wake alarm not set: {}", std::strerror(errno)));
|
||||
return;
|
||||
}
|
||||
wakeAt_ = at;
|
||||
}
|
||||
// What the loop arms the alarm for at the end of a turn that took no
|
||||
// command off the queue (one that took a command handles it and goes
|
||||
// straight to the next turn). A time that has come (a call, a text in
|
||||
// flight; a step that is due, which the next turn runs) is armed
|
||||
// WakeHold ahead at every such turn: the kernel refuses a suspend
|
||||
// that finds an alarm less than two seconds ahead at its check (alarmtimer_suspend),
|
||||
// whoever asks for it. For a step that follows a local wait (no
|
||||
// packet service, a connect the kernel refused) the policy names the
|
||||
// slower look's time: with no call and no text in flight nothing is
|
||||
// held then.
|
||||
static constexpr double WakeHold = 1.9;
|
||||
// WAKE_TRACE=1, a test seam: a line whenever the time the alarm is
|
||||
// armed for changes (by the second), with or without a timer to arm (a
|
||||
// bench has none). A time under two seconds ahead is "held", said once
|
||||
// while it lasts.
|
||||
const bool wakeTrace_ = EnvOr("WAKE_TRACE", "0") == "1";
|
||||
std::string wakeTraced_;
|
||||
void TraceWake(double at) {
|
||||
double ahead = at - Boot();
|
||||
std::string s = at <= 0 ? "none" : ahead < 2 ? "held under 2 s ahead" : std::format("{:.0f} s on the boot clock", at);
|
||||
if (s == wakeTraced_) return;
|
||||
wakeTraced_ = s;
|
||||
Log(at > 0 && ahead >= 2 ? std::format("wake trace: {} ({:.0f} s ahead)", s, ahead) : std::format("wake trace: {}", s));
|
||||
}
|
||||
double WakeDue() const {
|
||||
bool recovering = portPs_ != 0 && !reg_.callid.empty(); // MaybeReconnect's own condition
|
||||
bool renewal = registered_ && !subCallid_.empty() && !subPending_; // MaybeResubscribe's own, with the live flow
|
||||
double now = Boot();
|
||||
double at = imsd::engine::WakeAt(now, call_.has_value() || smsOut_.has_value(), !reg_.callid.empty() && sip_.Alive(),
|
||||
lastRefresh_ + RefreshInterval(), renewal ? subRenewAt_ : 0,
|
||||
recovering, recovering ? recovery_.WakeTime(now) : 0);
|
||||
return at > 0 && at < now + WakeHold ? now + WakeHold : at;
|
||||
}
|
||||
// A step of the registration that exchanges with the network: the
|
||||
// refresh, a reconnect, a fresh registration, the bring-up. The main
|
||||
// thread asks for logind's sleep lock while one runs (WorkLock, which a
|
||||
// text in flight wants as well; held where logind gives it), so that the step's waits run their
|
||||
// awake seconds in one piece; not while the bring-up waits out a hold
|
||||
// (WaitForPolicy). For a sleep that begins under a step all the same
|
||||
// (logind refused such a lock on the dev phone where a suspend's operation was already running; a suspend
|
||||
// told to ignore inhibitors) the alarm stands at most WakeNet ahead
|
||||
// while the step waits for the network: set as it begins, and anew
|
||||
// before every second of a connect's wait, of the pause before the next
|
||||
// try and of a wait for a REGISTER's answer. It fires once, and a wait
|
||||
// can outlast the sleep it ended: set every second, it stands again
|
||||
// within a second of that wake, for the sleep that may follow. Where there is an alarm the
|
||||
// sleep ends there, a lock logind had refused is asked for at its end (one held is kept), and the step goes
|
||||
// on. A wait for a helper program (mmcli, qmicli, ip) has the alarm
|
||||
// that stood when it began, once. After the step
|
||||
// the loop's own arming takes over again (WakeDue).
|
||||
static constexpr double WakeNet = 30;
|
||||
struct Step {
|
||||
explicit Step(Engine& engine) : e(engine) { e.steps_++; e.PostWork(true); e.netAlarm_(); }
|
||||
~Step() { e.steps_--; e.PostWork(false); }
|
||||
Step(const Step&) = delete;
|
||||
Step& operator=(const Step&) = delete;
|
||||
Engine& e;
|
||||
};
|
||||
int steps_ = 0; // the steps under way: what a hold's wait pauses (WaitForPolicy)
|
||||
bool noServiceTold_ = false; // the journal has the line of the coverage gap that runs
|
||||
// What a step sets the alarm to as it begins and before every second of
|
||||
// its waits for the network: WakeNet ahead, also where a call or a text
|
||||
// is in flight (the loop's WakeHold needs setting anew within two
|
||||
// seconds, which a helper program's wait does not give: under a step
|
||||
// the sleep is bounded, not refused).
|
||||
const std::function<void()> netAlarm_ = [this] { ArmWake(Boot() + WakeNet); };
|
||||
// The connect for a call's resend is no step: no helper program runs
|
||||
// under it, and the loop arms again at the end of the turn it runs in.
|
||||
// It keeps the loop's hold through its wait, set anew every second.
|
||||
const std::function<void()> holdAlarm_ = [this] { ArmWake(Boot() + WakeHold); };
|
||||
void PostWork(bool on) {
|
||||
auto ev = std::make_unique<Event>();
|
||||
ev->type = Event::Type::Work; ev->on = on;
|
||||
PostEvent(std::move(ev));
|
||||
}
|
||||
|
||||
std::optional<Cmd> PopCmd() {
|
||||
std::scoped_lock g(cmdLock_);
|
||||
if (cmds_.empty()) return std::nullopt;
|
||||
|
|
@ -2266,10 +2443,11 @@ private:
|
|||
SetTransport(t);
|
||||
// Local refusals (TIME_WAIT after a restart) keep retrying; two
|
||||
// silences mean the flow is not coming back — fresh instead.
|
||||
if (!sip_.Connect(local_, PortUc, pcscf_, sa->portPs, transport_, 10, 2)) {
|
||||
if (!sip_.Connect(local_, PortUc, pcscf_, sa->portPs, transport_, 10, 2, netAlarm_)) {
|
||||
Log(std::format("resume connect failed; {}", ResumeFailedNext()));
|
||||
return ResumeOutcome::Failed;
|
||||
}
|
||||
if (transport_ == Transport::Tcp) recovery_.OnNetworkAnswered();
|
||||
reg_.callid = *ps->callid;
|
||||
reg_.ftag = ps->ftag.value_or("");
|
||||
// The refresh must carry the SAME Contact URI as the stored binding;
|
||||
|
|
@ -2460,7 +2638,7 @@ private:
|
|||
}
|
||||
}
|
||||
bool autoTcp = (sipPolicy_ == "auto" && transport_ == Transport::Tcp && !tcpKnownGood);
|
||||
if (!sip_.Connect(local_, PortUc, pcscf_, portPs, transport_, 10, autoTcp ? 2 : 0)) {
|
||||
if (!sip_.Connect(local_, PortUc, pcscf_, portPs, transport_, 10, autoTcp ? 2 : 0, netAlarm_)) {
|
||||
if (autoTcp) {
|
||||
// Two unanswered TCP connects: treat the P-CSCF as UDP-only
|
||||
// and register again over UDP — a new challenge and a new SA
|
||||
|
|
@ -2529,7 +2707,8 @@ private:
|
|||
double deadline = Mono() + 12.0;
|
||||
for (;;) {
|
||||
double left = deadline - Mono();
|
||||
auto m = left > 0 ? sip_.RecvMsg(left) : std::nullopt;
|
||||
// the alarm is set anew before every second of the wait (Step)
|
||||
auto m = left > 0 ? sip_.RecvMsg(left, netAlarm_) : std::nullopt;
|
||||
if (!m) throw std::runtime_error(std::format("no reply to {}", what));
|
||||
auto st = imsd::sip::Status(*m);
|
||||
if (!st) {
|
||||
|
|
@ -2542,6 +2721,7 @@ private:
|
|||
if (!OnSubscribeResponse(*m, *st) && !OnSmsResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what));
|
||||
continue;
|
||||
}
|
||||
recovery_.OnNetworkAnswered(); // a response to our REGISTER, whatever it says: the network is in reach
|
||||
if (*st >= 200) return *m;
|
||||
Log(std::format("{} -> {} (provisional); waiting for the final", what, *st));
|
||||
deadline = Mono() + 12.0;
|
||||
|
|
@ -2563,6 +2743,9 @@ private:
|
|||
for (;;) {
|
||||
double left = deadline - Mono();
|
||||
if (left <= 0) break;
|
||||
// in pieces of a second, the alarm set anew before each (Step)
|
||||
netAlarm_();
|
||||
left = std::min(left, 1.0);
|
||||
long sec = static_cast<long>(left);
|
||||
long usec = static_cast<long>((left - static_cast<double>(sec)) * 1e6);
|
||||
if (sec == 0 && usec == 0) usec = 1000;
|
||||
|
|
@ -2570,7 +2753,14 @@ private:
|
|||
setsockopt(us, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
|
||||
sockaddr_storage src; socklen_t sl = sizeof src;
|
||||
ssize_t n = recvfrom(us, buf, sizeof buf, 0, reinterpret_cast<sockaddr*>(&src), &sl);
|
||||
if (n < 0) break;
|
||||
if (n < 0) {
|
||||
// a piece is over, or the receive was interrupted (EINTR: by
|
||||
// a suspend's freeze, after which the kernel takes a poll up
|
||||
// again but not a datagram receive under a timeout; by a stop and a
|
||||
// continue; by a signal handled here): the deadline is looked at above
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue;
|
||||
break;
|
||||
}
|
||||
const int sp = PortOf(src);
|
||||
std::string why;
|
||||
auto framed = imsd::sip::DatagramMessage(std::string_view(buf, static_cast<std::size_t>(n)), &why);
|
||||
|
|
@ -2585,6 +2775,7 @@ private:
|
|||
continue;
|
||||
}
|
||||
int st = *imsd::sip::Status(m);
|
||||
recovery_.OnNetworkAnswered();
|
||||
if (st >= 200) { close(us); return m; }
|
||||
Log(std::format("unprotected REGISTER -> {} (provisional); waiting for the final", st));
|
||||
deadline = Mono() + 8.0;
|
||||
|
|
@ -2717,11 +2908,8 @@ private:
|
|||
void MaybeRefresh() {
|
||||
if (call_ || reg_.callid.empty()) return;
|
||||
if (!sip_.Alive()) return; // MaybeReconnect owns dead-flow recovery
|
||||
long exp = reg_.expiry ? reg_.expiry : 3600;
|
||||
double interval;
|
||||
if (const char* o = std::getenv("REFRESH_INTERVAL")) interval = std::atof(o);
|
||||
else interval = std::max(120.0, std::min(exp * 0.5, 1800.0));
|
||||
if (Mono() - lastRefresh_ < interval) return;
|
||||
if (Boot() - lastRefresh_ < RefreshInterval()) return;
|
||||
Step step(*this);
|
||||
try {
|
||||
RefreshPani();
|
||||
auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1);
|
||||
|
|
@ -2748,7 +2936,7 @@ private:
|
|||
Log(std::format("keepalive re-REGISTER failed: {}", e.what()));
|
||||
CloseFlowAfterWait();
|
||||
}
|
||||
lastRefresh_ = Mono();
|
||||
lastRefresh_ = Boot();
|
||||
lastKa_ = Mono();
|
||||
}
|
||||
|
||||
|
|
@ -2787,7 +2975,7 @@ private:
|
|||
if (recovery_.Reconnectable() && call_->ResendDue()) {
|
||||
Log(std::format("call {}: the client flow died before any response to the INVITE; reopening it", call_->Uni()));
|
||||
sip_.Abort();
|
||||
ok = sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/1) && Execute(call_->OnFlowReopened());
|
||||
ok = sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/1, 0, holdAlarm_) && Execute(call_->OnFlowReopened());
|
||||
}
|
||||
if (!ok && call_ && !call_->Terminated()) Execute(call_->OnFlowLost());
|
||||
MaybeDropCall();
|
||||
|
|
@ -2836,15 +3024,48 @@ private:
|
|||
// refuses while the old one is live, and drops it for.
|
||||
void CoverageGap(std::string_view what) {
|
||||
if (registered_) { registered_ = false; EmitStatus(true); }
|
||||
recovery_.OnLocalRefusal(Boot());
|
||||
recovery_.OnLocalRefusal(Boot(), imsd::engine::RegRecovery::Local::NoService);
|
||||
Log(std::format("{} while the modem reports no packet service: not counted; {}", what, NextStep()));
|
||||
}
|
||||
|
||||
// While the modem reports no packet service the recovery tries nothing
|
||||
// (this is its look before a reconnect cycle and before a fresh
|
||||
// registration of its own; a bring-up does not ask): a reconnect would wait for answers that cannot come (over TCP
|
||||
// two connects of 12 s, over UDP the re-REGISTER's 12 s), and a fresh registration its first REGISTER's 8 s, with the sleep
|
||||
// lock held. The policy looks again LocalRetry on while the phone is
|
||||
// awake, and wakes a sleeping one for a look at its slower pace
|
||||
// (RegRecovery::WakeTime). One line where the modem is found without
|
||||
// service, and again after a look that found it with. The modem's word
|
||||
// does not start the gap's count over: only the network's answer does
|
||||
// (RegRecovery::OnNetworkAnswered: the shell's calls and the policy's
|
||||
// own). The look asks ModemManager, which can take its time: the alarm
|
||||
// stands under it. A dead flow's socket that is still open does not
|
||||
// outlive the look: left open through the wait a TCP one is readable at every
|
||||
// turn of the loop (its end of file, its error), which would then spin
|
||||
// instead of waiting, and a Dial's INVITE would be written into it.
|
||||
// Abort, as at a call's reopen: a TCP FIN sent into a gap would hold the
|
||||
// address pair against the reconnect after it, as a step's own close after an unanswered wait does (CloseFlowAfterWait). (A recovery step runs
|
||||
// on a dead flow only: MaybeReconnect.)
|
||||
bool NoService(std::string_view what) {
|
||||
netAlarm_();
|
||||
if (PacketServiceUp()) { noServiceTold_ = false; return false; }
|
||||
sip_.Abort();
|
||||
if (registered_) { registered_ = false; EmitStatus(true); }
|
||||
recovery_.OnLocalRefusal(Boot(), imsd::engine::RegRecovery::Local::NoService);
|
||||
if (!noServiceTold_) {
|
||||
Log(std::format("the modem reports no packet service: {} waits until it has it again", what));
|
||||
noServiceTold_ = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ReconnectCycle() {
|
||||
using F = imsd::engine::RegRecovery::Failure;
|
||||
if (NoService("the reconnect")) return;
|
||||
Log("client flow dead; reconnecting");
|
||||
Step step(*this);
|
||||
sip_.Close();
|
||||
if (!sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/2)) {
|
||||
if (!sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/2, 0, netAlarm_)) {
|
||||
if (AddressGone()) return;
|
||||
if (sip_.LastConnectLocal()) {
|
||||
if (registered_) { registered_ = false; EmitStatus(true); }
|
||||
|
|
@ -2855,6 +3076,10 @@ private:
|
|||
RecoveryFailed(F::Silent, 0, "P-CSCF silent");
|
||||
return;
|
||||
}
|
||||
// a TCP connect the P-CSCF answered: the network is in reach (a
|
||||
// UDP "connect" says nothing of it; there a REGISTER's response
|
||||
// does, in AwaitFinal)
|
||||
if (transport_ == Transport::Tcp) recovery_.OnNetworkAnswered();
|
||||
try {
|
||||
RefreshPani();
|
||||
auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1);
|
||||
|
|
@ -2903,7 +3128,9 @@ private:
|
|||
// nothing is retried until the next fresh attempt.
|
||||
void FreshRecover() {
|
||||
using F = imsd::engine::RegRecovery::Failure;
|
||||
if (NoService("the fresh registration")) return;
|
||||
Log(std::format("registering fresh (recovery attempt {})", recovery_.freshAttempts + 1));
|
||||
Step step(*this);
|
||||
sip_.Close();
|
||||
saReplaced_ = false; // this attempt's, whatever fails first
|
||||
// the subscription dialog is the registration's and goes with the
|
||||
|
|
@ -3039,7 +3266,7 @@ private:
|
|||
bool was = registered_;
|
||||
registered_ = true;
|
||||
EmitStatus(!was);
|
||||
lastRefresh_ = Mono(); lastKa_ = Mono();
|
||||
lastRefresh_ = Boot(); lastKa_ = Mono();
|
||||
// a refresh or a reconnect opens no subscription dialog while imsd
|
||||
// holds one for the registration or has a retry scheduled; a fresh
|
||||
// registration (or a start) has none yet, and a fresh attempt drops
|
||||
|
|
@ -3103,7 +3330,7 @@ private:
|
|||
ScheduleResubscribe(0);
|
||||
}
|
||||
if (call_ || !registered_ || !sip_.Alive()) return;
|
||||
if (!subCallid_.empty() && !subPending_ && subRenewAt_ > 0 && Mono() >= subRenewAt_) {
|
||||
if (!subCallid_.empty() && !subPending_ && subRenewAt_ > 0 && Boot() >= subRenewAt_) {
|
||||
// the granted lifetime is running out: a new dialog (the S-CSCF
|
||||
// closes the previous one — KPN with noresource), on the same
|
||||
// registration
|
||||
|
|
@ -3121,8 +3348,8 @@ private:
|
|||
// end, or halfway through a shorter grant.
|
||||
void ArmSubscriptionRenewal(long expires) {
|
||||
double ahead = expires > 1200 ? expires - 600.0 : expires / 2.0;
|
||||
subRenewAt_ = Mono() + std::max(ahead, 30.0);
|
||||
Log(std::format("reg-event: subscription granted {} s; renewed in {:.0f} s", expires, subRenewAt_ - Mono()));
|
||||
subRenewAt_ = Boot() + std::max(ahead, 30.0);
|
||||
Log(std::format("reg-event: subscription granted {} s; renewed in {:.0f} s", expires, subRenewAt_ - Boot()));
|
||||
}
|
||||
|
||||
// The network's view of our binding (RFC 3680 reginfo), read from any
|
||||
|
|
@ -3317,6 +3544,7 @@ private:
|
|||
const bool wantsReport = p.statusReport;
|
||||
const std::string destination = p.number;
|
||||
smsOut_.emplace(ctx_, rng_, smsSubmitted_, id, std::move(p));
|
||||
PostWork(true); // the work's lock while it is in flight: its waits count awake seconds
|
||||
auto actions = smsOut_->Start(Mono());
|
||||
// on record from the start — the SC may deliver segment 1 and report on
|
||||
// it while segment 2 is still in flight — and only for a message that
|
||||
|
|
@ -3340,6 +3568,7 @@ private:
|
|||
void EndSms() {
|
||||
rpMr_ = smsOut_->NextRpMr();
|
||||
smsOut_.reset();
|
||||
PostWork(false);
|
||||
}
|
||||
|
||||
// The message in flight ended: the next queued message starts (its
|
||||
|
|
@ -3933,6 +4162,7 @@ void OnBusAcquired(GDBusConnection* conn, const gchar*, gpointer) {
|
|||
"/org/freedesktop/login1", nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnPrepareForSleep, nullptr, nullptr);
|
||||
// the engine began before the bus was there: what it has asked for by now
|
||||
HoldSleepOff(CallLock, CallLock.want);
|
||||
HoldSleepOff(WorkLock, WorkLock.want);
|
||||
GError* err = nullptr;
|
||||
GDBusNodeInfo* node = g_dbus_node_info_new_for_xml(IntrospectionXml, &err);
|
||||
if (!node) { Log(std::format("introspection XML: {}", err ? err->message : "?")); if (err) g_error_free(err); return; }
|
||||
|
|
|
|||
Loading…
Reference in a new issue