lists.osmocom.org
Sign In Sign Up
Manage this list Sign In Sign Up

Keyboard Shortcuts

Thread View

  • j: Next unread message
  • k: Previous unread message
  • j a: Jump to all threads
  • j l: Jump to MailingList overview

gerrit-log

Thread Start a new thread
Download
Threads by month
  • ----- 2026 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2025 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2024 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2023 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
  • ----- 2022 -----
  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January
gerrit-log@lists.osmocom.org

December 2026

  • 1 participants
  • 245 discussions
[L] Change in osmo-e1d[master]: add SD-RI-PLL self-tuning of the PID gains
by ale-leehrtz 04 Dec '26

04 Dec '26
Attention is currently required from: Hoernchen, laforge, tnt. ale-leehrtz has posted comments on this change by ale-leehrtz. ( https://gerrit.osmocom.org/c/osmo-e1d/+/44231?usp=email ) Change subject: add SD-RI-PLL self-tuning of the PID gains ...................................................................... Patch Set 2: PS2: fix lint (trailing whitespace) -- To view, visit https://gerrit.osmocom.org/c/osmo-e1d/+/44231?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: comment Gerrit-Project: osmo-e1d Gerrit-Branch: master Gerrit-Change-Id: Ifa5e1762df67c02093636908b45c6b5ce78fdc85 Gerrit-Change-Number: 44231 Gerrit-PatchSet: 2 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: tnt <tnt(a)246tNt.com> Gerrit-Attention: tnt <tnt(a)246tNt.com> Gerrit-Attention: laforge <laforge(a)osmocom.org> Gerrit-Attention: Hoernchen <ewild(a)sysmocom.de> Gerrit-Comment-Date: Fri, 04 Dec 2026 02:23:54 +0000 Gerrit-HasComments: No Gerrit-Has-Labels: No
1 0
0 0
[L] Change in osmo-e1d[master]: dahdi_trunkdev: add SD-RI-PLL software clock recovery
by ale-leehrtz 04 Dec '26

04 Dec '26
Attention is currently required from: Hoernchen, ale-leehrtz, laforge, tnt. Hello Hoernchen, Jenkins Builder, laforge, tnt, I'd like you to reexamine a change. Please visit https://gerrit.osmocom.org/c/osmo-e1d/+/44232?usp=email to look at the new patch set (#2). The following approvals got outdated and were removed: Verified-1 by Jenkins Builder Change subject: dahdi_trunkdev: add SD-RI-PLL software clock recovery ...................................................................... dahdi_trunkdev: add SD-RI-PLL software clock recovery Without a hardware clock source, the DAHDI coretimer that paces a trunkdev runs from the host clock, which is not the clock of the remote E1 that paces the incoming E1-over-IP stream, so the IP->E1 FIFO slowly drains or overflows. Close that loop in software: once per second, read the IP->E1 FIFO level of line 0, run the PID controller, and steer the coretimer via the new DAHDI_SW_CLOCK_SET ioctl of the osmocom DAHDI fork. The ioctl is defined locally if the DAHDI headers lack it; on a kernel without support the PLL disables itself with an error message. As the trunkdev span is the timing master in this setup, the dahdi_trunkdev module must be loaded with permit_clock_master=1. The PLL is off by default. New VTY commands on 'interface N dahdi-trunkdev': pll mode (off|fixed|self-tuning) pll pid-gains KP KI KD pll target-fifo <1-1792> pll self-tuning hold-time <0-31536000> pll self-tuning window <600-86400> pll log-file FILENAME / no pll log-file In self-tuning mode, the configured gains are used for at least the hold-time while the link is characterized; once the tuner has its first estimate (about 10 valid estimation windows, 1 h each by default), the self-tuned gains are applied bumplessly and updated after every window. A watchdog reverts to the configured gains if the loop runs away. The optional log file gets one CSV line per tick for offline analysis. 'show interface' shows the FIFO levels and the PLL state. Related: OS#7116 Change-Id: I20e0d62275c8422e3b272630dc52cebd80b66a15 --- M src/Makefile.am A src/dahdi_plltrunkdev.h M src/dahdi_trunkdev.c M src/e1d.h M src/vty.c 5 files changed, 612 insertions(+), 0 deletions(-) git pull ssh://gerrit.osmocom.org:29418/osmo-e1d refs/changes/32/44232/2 -- To view, visit https://gerrit.osmocom.org/c/osmo-e1d/+/44232?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newpatchset Gerrit-Project: osmo-e1d Gerrit-Branch: master Gerrit-Change-Id: I20e0d62275c8422e3b272630dc52cebd80b66a15 Gerrit-Change-Number: 44232 Gerrit-PatchSet: 2 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: tnt <tnt(a)246tNt.com> Gerrit-Attention: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org> Gerrit-Attention: tnt <tnt(a)246tNt.com> Gerrit-Attention: laforge <laforge(a)osmocom.org> Gerrit-Attention: Hoernchen <ewild(a)sysmocom.de>
1 0
0 0
[L] Change in osmo-e1d[master]: add SD-RI-PLL self-tuning of the PID gains
by ale-leehrtz 04 Dec '26

04 Dec '26
Attention is currently required from: Hoernchen, ale-leehrtz, laforge, tnt. Hello Hoernchen, Jenkins Builder, laforge, tnt, I'd like you to reexamine a change. Please visit https://gerrit.osmocom.org/c/osmo-e1d/+/44231?usp=email to look at the new patch set (#2). The following approvals got outdated and were removed: Verified-1 by Jenkins Builder Change subject: add SD-RI-PLL self-tuning of the PID gains ...................................................................... add SD-RI-PLL self-tuning of the PID gains The PID gains of the SD-RI-PLL determine the loop bandwidth, and the right bandwidth depends on the link: on a noisy link the loop must be slow, while a large oscillator wander calls for a fast loop. Add a self-tuning regulator layer on top of the unchanged PID law. It estimates the measurement noise of the FIFO level (sigma_v) and the frequency wander of the oscillator (q_phi, from Allan-style variances over 1 h windows), and from these recomputes the loop bandwidth wn = (q_phi / sigma_v^2)^(1/4) and Kp/Ki by pole placement, as well as a smoothing time constant for the error. Gain changes are rate-limited. It also gates outliers and reports link-down ticks, so that the caller can hold the output instead of integrating a stale or empty FIFO. On a 53 h A/B run against the sysmocom OCTOI hub (first 24 h with the default gains, then self-tuned), time-in-band went from 71% to 90% and the FIFO standard deviation from 70 to 47 frames. Like the PID controller, this is hooked up in a follow-up patch. Related: OS#7116 Change-Id: Ifa5e1762df67c02093636908b45c6b5ce78fdc85 --- M src/Makefile.am A src/pll_tune.c A src/pll_tune.h 3 files changed, 336 insertions(+), 2 deletions(-) git pull ssh://gerrit.osmocom.org:29418/osmo-e1d refs/changes/31/44231/2 -- To view, visit https://gerrit.osmocom.org/c/osmo-e1d/+/44231?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newpatchset Gerrit-Project: osmo-e1d Gerrit-Branch: master Gerrit-Change-Id: Ifa5e1762df67c02093636908b45c6b5ce78fdc85 Gerrit-Change-Number: 44231 Gerrit-PatchSet: 2 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org> Gerrit-Reviewer: Hoernchen <ewild(a)sysmocom.de> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: tnt <tnt(a)246tNt.com> Gerrit-Attention: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org> Gerrit-Attention: tnt <tnt(a)246tNt.com> Gerrit-Attention: laforge <laforge(a)osmocom.org> Gerrit-Attention: Hoernchen <ewild(a)sysmocom.de>
1 0
0 0
[S] Change in dahdi-linux[master]: trunkdev: add module parameter permit_clock_master
by ale-leehrtz 04 Dec '26

04 Dec '26
ale-leehrtz has uploaded this change for review. ( https://gerrit.osmocom.org/c/dahdi-linux/+/44235?usp=email ) Change subject: trunkdev: add module parameter permit_clock_master ...................................................................... trunkdev: add module parameter permit_clock_master So far, td_d_sync_tick() unconditionally hits BUG_ON() when a trunkdev span becomes the DAHDI timing master, as normally the trunkdev must be slaved to some other clock source to avoid re-entrancy of _dahdi_receive(). A reference-independent node (SD-RI-PLL, see the related ticket) has no other clock source: the DAHDI coretimer itself is disciplined from userspace via DAHDI_SW_CLOCK_SET, based on the fill level of the E1-over-IP FIFO. In that setup the trunkdev span is the timing master by design. Add a module parameter 'permit_clock_master' which allows this. It defaults to false, so the existing behavior is unchanged. Related: OS#7116 Change-Id: Iae232de00dde288b0e97ac287705aa5c8afcad4a --- M drivers/dahdi/trunkdev/trunkdev.c 1 file changed, 14 insertions(+), 2 deletions(-) git pull ssh://gerrit.osmocom.org:29418/dahdi-linux refs/changes/35/44235/1 diff --git a/drivers/dahdi/trunkdev/trunkdev.c b/drivers/dahdi/trunkdev/trunkdev.c index 6518109..f56a78a 100644 --- a/drivers/dahdi/trunkdev/trunkdev.c +++ b/drivers/dahdi/trunkdev/trunkdev.c @@ -1,5 +1,6 @@ /* DAHDI Virtual Trunk device driver. * (C) 2022 by Harald Welte <laforge(a)osmocom.org> + * (C) 2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> * for Osmocom retronetworking project * */ @@ -41,6 +42,16 @@ #define ALL_RY_ALARMS (DAHDI_ALARM_RED | DAHDI_ALARM_YELLOW | \ DAHDI_ALARM_LFA | DAHDI_ALARM_LMFA) +/* Permit a trunkdev span to be the DAHDI timing master. Off by default, as + * normally the trunkdev must be slaved to some other clock source (see + * td_d_sync_tick()). A reference-independent node, where the DAHDI coretimer + * is disciplined from userspace via DAHDI_SW_CLOCK_SET, has no other clock + * source and needs this. */ +static bool permit_clock_master; +module_param(permit_clock_master, bool, 0444); +MODULE_PARM_DESC(permit_clock_master, + "Permit a trunkdev span to become DAHDI timing master (default: no)"); + struct dahdi_trunkdev { /* pointer to 'file' _if_ somebody has opened us via DAHDI_TRUNKDEV_OPEM */ struct file *file; @@ -199,8 +210,9 @@ /* we must have some other clock source than this span, due to the way * how DAHDI works internally: This very sync_tick function is called when the * master device receives data via _dahdi_receive(). As we are calling - * _dahdi_receive() via _span_demux_one_frame(), this would lead to re-entrancy */ - BUG_ON(is_master); + * _dahdi_receive() via _span_demux_one_frame(), this would lead to re-entrancy. + * Exception: reference-independent operation, see permit_clock_master. */ + BUG_ON(is_master && !permit_clock_master); /* trigger transmission + reception of E1 frames */ for (i = 0; i < DAHDI_CHUNKSIZE; i++) { -- To view, visit https://gerrit.osmocom.org/c/dahdi-linux/+/44235?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newchange Gerrit-Project: dahdi-linux Gerrit-Branch: master Gerrit-Change-Id: Iae232de00dde288b0e97ac287705aa5c8afcad4a Gerrit-Change-Number: 44235 Gerrit-PatchSet: 1 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org>
1 0
0 0
[L] Change in dahdi-linux[master]: dahdi-base: add software clock correction of the coretimer
by ale-leehrtz 04 Dec '26

04 Dec '26
ale-leehrtz has uploaded this change for review. ( https://gerrit.osmocom.org/c/dahdi-linux/+/44234?usp=email ) Change subject: dahdi-base: add software clock correction of the coretimer ...................................................................... dahdi-base: add software clock correction of the coretimer Without a hardware clock source, DAHDI is paced by its coretimer, which runs from the host clock. For an E1-over-IP trunkdev this is not the clock of the remote E1, so the jitter buffer slowly drains or overflows. Allow user space to discipline the coretimer: it now runs at a rate of (1 + fudge / 2^32). When a new fudge is set, the raw and fudged time offsets are re-anchored so the coretimer stays phase-continuous. The scaling uses the existing 96-bit fixed-point lineartime helpers, without any allocation, as it runs in timer context. Two new ioctls on /dev/dahdi/channel, allocated downwards from 252 like the trunkdev ones to avoid clashes with upstream DAHDI: DAHDI_SW_CLOCK_GET: read target/current fudge and the coretimer interval DAHDI_SW_CLOCK_SET: set the target fudge (a single __s32) This is used by the SD-RI-PLL in osmo-e1d, see the related ticket. Related: OS#7116 Change-Id: I93243a48566b337b3bb8f728d0ccf4b756755e4d --- M drivers/dahdi/dahdi-base.c M include/dahdi/user.h 2 files changed, 633 insertions(+), 0 deletions(-) git pull ssh://gerrit.osmocom.org:29418/dahdi-linux refs/changes/34/44234/1 diff --git a/drivers/dahdi/dahdi-base.c b/drivers/dahdi/dahdi-base.c index 657eb34..bfee1d4 100644 --- a/drivers/dahdi/dahdi-base.c +++ b/drivers/dahdi/dahdi-base.c @@ -16,6 +16,8 @@ * * Copyright (C) 2001 Jim Dixon / Zapata Telephony. * Copyright (C) 2001 - 2012 Digium, Inc. + * Copyright (C) 2025 - 2026 C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> + * (software clock correction of the coretimer) * * All rights reserved. * @@ -205,6 +207,17 @@ atomic_t count; atomic_t shutdown; atomic_t last_count; + + /* SD-RI-PLL: the coretimer clock is scaled by (1 + fudge / 2^32), + * with the fudge supplied from user space via DAHDI_SW_CLOCK_SET. + * target_fudge is written by the ioctl; current_fudge is what the + * timer applies. The offsets keep the clock phase-continuous across + * a fudge change. fudge_lock serialises the ioctl against the timer. */ + int32_t target_fudge; + int32_t current_fudge; + ktime_t raw_time_offset; + ktime_t fudged_time_offset; + spinlock_t fudge_lock; } core_timer; #endif /* CONFIG_DAHDI_CORE_TIMER */ @@ -7008,6 +7021,36 @@ if (res) file->private_data = NULL; return res; +#ifdef CONFIG_DAHDI_CORE_TIMER + case DAHDI_SW_CLOCK_GET: { + struct dahdi_sw_clock clk; + struct timespec64 ts = ktime_to_timespec64(core_timer.start_interval); + unsigned long flags; + + spin_lock_irqsave(&core_timer.fudge_lock, flags); + clk.target_fudge = core_timer.target_fudge; + clk.current_fudge = core_timer.current_fudge; + spin_unlock_irqrestore(&core_timer.fudge_lock, flags); + clk.interval_sec = ts.tv_sec; + clk.interval_nsec = ts.tv_nsec; + + if (copy_to_user((void __user *)data, &clk, sizeof(clk))) + return -EFAULT; + return 0; + } + case DAHDI_SW_CLOCK_SET: { + __s32 fudge; + unsigned long flags; + + if (get_user(fudge, (__s32 __user *)data)) + return -EFAULT; + + spin_lock_irqsave(&core_timer.fudge_lock, flags); + core_timer.target_fudge = fudge; + spin_unlock_irqrestore(&core_timer.fudge_lock, flags); + return 0; + } +#endif /* CONFIG_DAHDI_CORE_TIMER */ default: return -ENOSYS; } @@ -10086,6 +10129,575 @@ return atomic_read(&ct->count) * DAHDI_MSECS_PER_CHUNK; } +/* + * SD-RI-PLL: software clock correction of the coretimer. + * + * User space (osmo-e1d) may discipline the coretimer through the + * DAHDI_SW_CLOCK_{GET,SET} ioctls: the coretimer then runs at a rate of + * (1 + fudge / 2^32). The time scaling uses 96-bit fixed-point arithmetic + * (2^64 * h + 2^32 * m + l nanoseconds) with 32-bit limbs only, so it needs + * neither 64-bit division nor floating point in the kernel. + */ + +/* We work with 32bit unsigned integers and 32bit signed integers */ +typedef uint32_t ui32_t; +typedef int32_t si32_t; + +/* 2^64 * h + 2^32 * m + l gives time in nanoseconds since an epoch */ +typedef struct { + ui32_t h; + ui32_t m; + ui32_t l; +} lineartime_t; + +/* Helper function for addition: 2^32 * cout + s = a + b + cin, cin + either 0 or 1 +*/ +static void __lineartime_add_ui32(ui32_t *cout, ui32_t *s, + ui32_t a, ui32_t b, ui32_t cin) { + ui32_t co, sum; + + co = (ui32_t) 0; + sum = a + b; + if (sum < a) co += (ui32_t) 1; + sum += cin; + if (sum < cin) co += (ui32_t) 1; + *cout = co; + *s = sum; +} + +/* Helper function for multiplication: 2^32 * h + l = a * b + c */ +static void __lineartime_muladd_ui32(ui32_t *h, ui32_t *l, + ui32_t a, ui32_t b, ui32_t c) { + ui32_t hi, lo; + ui32_t ah, al, bh, bl, ch, cl; + ui32_t ahbh, ahbl, albh, albl; + ui32_t ahblh, ahbll, albhh, albhl, alblh, albll; + ui32_t t1, t1h, t1l; + ui32_t t2, t2h, t2l; + + /* Split the arguments */ + ah = a >> 16; + al = a & ((((ui32_t) 1) << 16) - ((ui32_t) 1)); + + bh = b >> 16; + bl = b & ((((ui32_t) 1) << 16) - ((ui32_t) 1)); + + ch = c >> 16; + cl = c & ((((ui32_t) 1) << 16) - ((ui32_t) 1)); + + /* Four partial multiplications */ + ahbh = ah * bh; + ahbl = ah * bl; + albh = al * bh; + albl = al * bl; + + /* Split the intermediates */ + ahblh = ahbl >> 16; + ahbll = ahbl & ((((ui32_t) 1) << 16) - ((ui32_t) 1)); + + albhh = albh >> 16; + albhl = albh & ((((ui32_t) 1) << 16) - ((ui32_t) 1)); + + alblh = albl >> 16; + albll = albl & ((((ui32_t) 1) << 16) - ((ui32_t) 1)); + + /* + + |---- ahbh ----| + |---- ahblh ----|---- ahbll ----| + |---- albhh ----|---- albhl ----| + |---- alblh ----|---- albll ----| + |---- ch ----|---- cl ----| + + */ + t1 = albll + cl; + + /* Resplit */ + t1h = t1 >> 16; + t1l = t1 & ((((ui32_t) 1) << 16) - ((ui32_t) 1)); + + /* + + |---- ahbh ----| + |---- ahblh ----|---- ahbll ----| + |---- albhh ----|---- albhl ----| + |---- alblh ----| + |---- ch ----| + |---- t1h ----|---- t1l ----| + + */ + t2 = ahbll + albhl + alblh + ch + t1h; + + /* Resplit */ + t2h = t2 >> 16; + t2l = t2 & ((((ui32_t) 1) << 16) - ((ui32_t) 1)); + + /* + + |---- ahbh ----| + |---- ahblh ----| + |---- albhh ----| + |---- t2h ----|---- t2l ----| + |---- t1l ----| + + */ + lo = (t2l << 16) + t1l; + hi = ahbh + ahblh + albhh + t2h; + + /* Write back */ + *h = hi; + *l = lo; +} + +/* Helper function: convert time64_t to two times 32bits: + 2^32 * h + l <- t +*/ +static void __lineartime_time_to_limbs(ui32_t *h, ui32_t *l, + time64_t t) { + ui32_t hi, lo; + ui32_t hh, hl, lh, ll; + time64_t tm, t1, t2, t3; + + if (t < ((time64_t) 0)) { + hi = (ui32_t) 0; + lo = (ui32_t) 0; + } else { + tm = t; + + t1 = tm >> 16; + t2 = t1 << 16; + t3 = tm - t2; + tm = t1; + ll = (ui32_t) t3; + + t1 = tm >> 16; + t2 = t1 << 16; + t3 = tm - t2; + tm = t1; + lh = (ui32_t) t3; + + t1 = tm >> 16; + t2 = t1 << 16; + t3 = tm - t2; + tm = t1; + hl = (ui32_t) t3; + + t1 = tm >> 16; + t2 = t1 << 16; + t3 = tm - t2; + tm = t1; + hh = (ui32_t) t3; + + hi = (hh << 16) + hl; + lo = (lh << 16) + ll; + } + + *h = hi; + *l = lo; +} + +/* Helper function: divide 2^32 * h + l by 10^9 + + The function assumes that + + 0 <= 2^32 * h + l < 2^32 * 10^9 + + The function returns q and r such that + + 10^9 * q + r = 2^32 * h + l + + and 0 <= r <= 10^9 - 1. + +*/ +static void __lineartime_div_by_ten_to_nine(ui32_t *q, ui32_t *r, + ui32_t h, ui32_t l) { + const ui32_t two_52_by_five_9 = (ui32_t) 2305843009ull; + const ui32_t ten_9 = (ui32_t) 1000000000ull; + ui32_t ph, pm, t, pl, w, tl, rl, qo, re; + + /* 2^32 * t + pl = l * floor(2^52 / 5^9) */ + __lineartime_muladd_ui32(&t, &pl, l, two_52_by_five_9, ((ui32_t) 0)); + + /* 2^32 * ph + pm = h * floor(2^52 / 5^9) + t */ + __lineartime_muladd_ui32(&ph, &pm, h, two_52_by_five_9, t); + + /* 2^64 * ph + 2^32 * pm + pl = + = 2^32 * (2^32 * ph + pm) + pl + = 2^32 * (h * floor(2^52 / 5^9) + t) + pl + = 2^32 * h * floor(2^52 / 5^9) + 2^32 * t + pl + = 2^32 * h * floor(2^52 / 5^9) + l * floor(2^52 / 5^9) + = (2^32 * h + l) * floor(2^52 / 5^9) + = (2^32 * h + l) * (2^52 / 5^9 + delta1) w/ -1 < delta1 <= 0 + = (2^32 * h + l) * (2^61 / 10^9 + delta1) + = ((2^32 * h + l) / 10^9 + delta2) * 2^61 + + where delta2 = delta1 * (2^32 * h + l) / 2^61 + + We have delta2 bounded as follows: + + 0 >= delta2 > -1 * 2^32 * 10^9 / 2^61 + = -2^-29 * 10^9 + > -1.87 + + We know that 0 <= 2^-61 * pl <= 2^-61 * (2^32 - 1) < 2^-29. + + This means that + + w = 2^3 * ph + floor(pm / 2^29) = + = floor(2^3 * ph + 2^-29 * pm) + = floor(2^3 * ph + 2^-29 * pm + 2^-61 * pl) + = floor((2^32 * h + l) / 10^9 + delta2) + = floor((2^32 * h + l) / 10^9) + floor(delta3) + = floor((2^32 * h + l) / 10^9) - delta4 + + with delta3 = (2^32 * h + l) / 10^9 + - floor((2^32 * h + l) / 10^9) + + delta2 + + and delta4 = -floor(delta3). + + It is clear that delta3 is bounded by + + -1.87 < delta3 < 1. + + Therefore delta4 \in {0, 1, 2}. + + Clearly, w is bounded by + + 0 <= w < floor(2^32 * 10^9 / 10^9) - 0 = 2^32. + + */ + w = (ph << 3) + (pm >> 29); + + /* 2^32 * th + tl = w * 10^9 + + th does not get computed, see below. + + The next operation will do mod 2^32 arithmetic. This is accounted + for. + */ + tl = w * ten_9; + + /* 2^32 * th + tl + = (floor((2^32 * h + l) / 10^9) - delta4) * 10^9 + = floor((2^32 * h + l) / 10^9) * 10^9 - delta4 * 10^9 + + Therefore + + 2^32 * rh + rl + = 2^32 * h + l - (2^32 * th + tl) + = 2^32 * h + l - floor((2^32 * h + l) / 10^9) * 10^9 + + delta4 * 10^9 + + Clearly, + 0 <= 2^32 * h + l - floor((2^32 * h + l) / 10^9) * 10^9 + < 10^9 + + Hence + + 0 <= 2^32 * rh + rl < 10^9 + 2 * 10^9 = 3 * 10^9 < 2^32 + + This means, rh will be zero all the time and does not need to be + computed. This also means that th does not need to be computed. + + We get + + rl = 2^32 * h + l - (2^32 * th + tl) + + and + + 2^32 * h + l = w * 10^9 + rl. + + Therefore + + qo = floor((2^32 * h + l) / 10^9) = + = floor((w * 10^9 + rl) / 10^9) + = floor(w + rl / 10^9) + = w + floor(rl / 10^9) + + Clearly, 0 <= qo < floor(2^32 * 10^9 / 10^9) = 2^32. + + */ + rl = l - tl; + qo = w + (rl / ten_9); + + /* Compute the actual remainder. + + qo behaves like w in the multiplication and subtraction above. + + The modulo 2^32 behavior of the arithmetic has been accounted + for. + + */ + re = l - (qo * ten_9); + + /* Write back the results */ + *q = qo; + *r = re; +} + +/* Helper function: divide 2^64 * h + 2^32 * m + l by 10^9. + + Return 2^64 * qh + 2^32 * qm + ql and r such that + + (2^64 * qh + 2^32 * qm + ql) * 10^9 + r + = 2^64 * h + 2^32 * m + l + +*/ +static void __lineartime_long_div_by_ten_to_nine(ui32_t *qh, + ui32_t *qm, + ui32_t *ql, + ui32_t *r, + ui32_t h, + ui32_t m, + ui32_t l) { + ui32_t ra, rb, rc, rd; + ui32_t qa, qb, qc; + + ra = (ui32_t) 0; + + /* qa * 10^9 + rb = 2^32 * ra + h */ + __lineartime_div_by_ten_to_nine(&qa, &rb, ra, h); + + /* qb * 10^9 + rc = 2^32 * rb + m */ + __lineartime_div_by_ten_to_nine(&qb, &rc, rb, m); + + /* qc * 10^9 + rd = 2^32 * rc + l */ + __lineartime_div_by_ten_to_nine(&qc, &rd, rc, l); + + /* Here we have + + (2^64 * qa + 2^32 * qb + qc) * 10^9 + rd + = 2^32 * (2^32 * qa + qb) * 10^9 + qc * 10^9 + rd + = 2^32 * ((2^32 * qa + qb) * 10^9 + rc) + l + = 2^32 * (2^32 * qa * 10^9 + qb * 10^9 + rc) + l + = 2^32 * (2^32 * (qa * 10^9 + rb) + m) + l + = 2^32 * (2^32 * (2^32 * ra + h) + m) + l + = 2^32 * (2^32 * h + m) + l + = 2^64 * h + 2^32 * m + l + + with 0 <= rd <= 10^9 - 1. + + We have hence what we need. + + */ + *qh = qa; + *qm = qb; + *ql = qc; + *r = rd; +} + +/* rop <- op, rop becomes zero if op is negative */ +static void timespec_to_lineartime(lineartime_t *rop, + const struct timespec64 *op) { + ui32_t sh, sl, ns; + ui32_t t1h, t1l; + ui32_t t2h, t2l; + + /* (2^32 * sh + sl) * 10^9 + ns <- op */ + __lineartime_time_to_limbs(&sh, &sl, op->tv_sec); + ns = (ui32_t) op->tv_nsec; + + /* 2^32 * t1h + t1l = sl * 10^9 + ns */ + __lineartime_muladd_ui32(&t1h, &t1l, sl, ((ui32_t) 1000000000ull), ns); + + /* 2^32 * t2h + t2l = sh * 10^9 + t1h */ + __lineartime_muladd_ui32(&t2h, &t2l, sh, ((ui32_t) 1000000000ull), t1h); + + /* 2^64 * t2h + 2^32 * t2l + t1l = + = 2^32 * (2^32 * t2h + t2l) + t1l + = 2^32 * (sh * 10^9 + t1h) + t1l + = 2^32 * sh * 10^9 + 2^32 * t1h + t1l + = 2^32 * sh * 10^9 + sl * 10^9 + ns + = (2^32 * sh + sl) * 10^9 + ns + = op + */ + rop->h = t2h; + rop->m = t2l; + rop->l = t1l; +} + +/* rop <- op, rop becomes zero if op cannot be represented */ +static void lineartime_to_timespec(struct timespec64 *rop, + const lineartime_t *op) { + ui32_t sh, sm, sl, ns; + time64_t sec, t; + ui32_t th, tm, tl; + long nsl; + ui32_t tns; + + __lineartime_long_div_by_ten_to_nine(&sh, &sm, &sl, + &ns, + op->h, op->m, op->l); + + sec = (time64_t) 0; + + t = (time64_t) sh; + sec = ((sec << 16) << 16) + t; + + t = (time64_t) sm; + sec = ((sec << 16) << 16) + t; + + t = (time64_t) sl; + sec = ((sec << 16) << 16) + t; + + th = (ui32_t) 0; + __lineartime_time_to_limbs(&tm, &tl, sec); + + nsl = (long) ns; + tns = (ui32_t) nsl; + + if ((th != sh) || + (tm != sm) || + (tl != sl) || + (nsl < ((long) 0)) || + (tns != ns)) { + rop->tv_sec = (time64_t) 0; + rop->tv_nsec = (long) 0; + return; + } + + rop->tv_sec = sec; + rop->tv_nsec = nsl; +} + +/* rop <- op1 + op2 mod 2^96ns */ +static void lineartime_add(lineartime_t *rop, + const lineartime_t *op1, const lineartime_t *op2) { + ui32_t cin, cout; + + cin = (ui32_t) 0; + + __lineartime_add_ui32(&cout, &rop->l, op1->l, op2->l, cin); + cin = cout; + + __lineartime_add_ui32(&cout, &rop->m, op1->m, op2->m, cin); + cin = cout; + + __lineartime_add_ui32(&cout, &rop->h, op1->h, op2->h, cin); +} + +/* rop <- op1 - op2 mod 2^96ns */ +static void lineartime_sub(lineartime_t *rop, + const lineartime_t *op1, const lineartime_t *op2) { + ui32_t cin, cout; + + cin = (ui32_t) 1; + + __lineartime_add_ui32(&cout, &rop->l, op1->l, ~op2->l, cin); + cin = cout; + + __lineartime_add_ui32(&cout, &rop->m, op1->m, ~op2->m, cin); + cin = cout; + + __lineartime_add_ui32(&cout, &rop->h, op1->h, ~op2->h, cin); +} + +/* rop <- op1 * (1 + op2/2^32) mod 2^96ns */ +static void lineartime_scale(lineartime_t *rop, + const lineartime_t *op1, si32_t *op2) { + int neg; + ui32_t absop2; + lineartime_t t; + ui32_t d, c, b, a, h1, h2; + + /* op1 * (1 + op2/2^32) = op1 + op1 * op2 / 2^32 + = op1 +/- op1 * |op2| / 2^32 + */ + if (*op2 >= ((si32_t) 0)) { + absop2 = (ui32_t) *op2; + neg = 0; + } else { + absop2 = ((ui32_t) (-(*op2 + ((si32_t) 1)))) + ((ui32_t) 1); + neg = 1; + } + + /* t <- (op1 * absop2) / 2^32 + = ((2^64 * op1->h + 2^32 * op1->m + op1->l) * absop2) / 2^32 + */ + __lineartime_muladd_ui32(&h1, &a, op1->l, absop2, ((ui32_t) 0)); + __lineartime_muladd_ui32(&h2, &b, op1->m, absop2, h1); + __lineartime_muladd_ui32(&d, &c, op1->h, absop2, h2); + + /* 2^96 * d + 2^64 * c + 2^32 * b + a = + = 2^64 * (2^32 * d + c) + 2^32 * b + a + = 2^64 * (op1->h * absop2 + h2) + 2^32 * b + a + = 2^64 * op1->h * absop2 + 2^32 * (2^32 * h2 + b) + a + = 2^64 * op1->h * absop2 + 2^32 * (op1->m * absop2 + h1) + a + = 2^64 * op1->h * absop2 + 2^32 * op1->m * absop2 + 2^32 * h1 + a + = 2^64 * op1->h * absop2 + 2^32 * op1->m * absop2 + op1->l * absop2 + 0 + = (2^64 * op1->h + 2^32 * op1->m + op1->l) * absop2 + + */ + t.h = d; + t.m = c; + t.l = b; + + /* rop <- op1 +/- t */ + if (neg) { + lineartime_sub(rop, op1, &t); + } else { + lineartime_add(rop, op1, &t); + } +} + +/* + * fudged_now = fudged_offset + (now - unfudged_offset) * (1 + fudge/2^32) + * + * Computed with the 96-bit fixed-point lineartime_t helpers: integer-only, + * O(1), no allocation. This runs from the coretimer callback (timer/softirq + * context), so every operand lives on the stack. + */ +static ktime_t compute_fudged_now(ktime_t now, si32_t fudge, + ktime_t unfudged_offset, ktime_t fudged_offset) +{ + struct timespec64 ts_now, ts_unfudged, ts_fudged, ts_result; + lineartime_t lt_now, lt_unfudged, lt_fudged_offset; + lineartime_t lt_diff, lt_scaled, lt_result; + + ts_now = ktime_to_timespec64(now); + ts_unfudged = ktime_to_timespec64(unfudged_offset); + ts_fudged = ktime_to_timespec64(fudged_offset); + + timespec_to_lineartime(&lt_now, &ts_now); + timespec_to_lineartime(&lt_unfudged, &ts_unfudged); + timespec_to_lineartime(&lt_fudged_offset, &ts_fudged); + + lineartime_sub(&lt_diff, &lt_now, &lt_unfudged); /* now - unfudged_offset */ + lineartime_scale(&lt_scaled, &lt_diff, &fudge); /* * (1 + fudge/2^32) */ + lineartime_add(&lt_result, &lt_scaled, &lt_fudged_offset); /* + fudged_offset */ + + lineartime_to_timespec(&ts_result, &lt_result); + return timespec64_to_ktime(ts_result); +} + +/* + * Apply the software-PLL fudge to the raw monotonic time. When user space + * has pushed a new target fudge, re-anchor the offsets so the fudged clock + * stays phase-continuous across the change. + */ +static ktime_t coretimer_fudge(ktime_t now, struct core_timer *ct) +{ + ktime_t fudged_now; + unsigned long flags; + + fudged_now = compute_fudged_now(now, ct->current_fudge, + ct->raw_time_offset, + ct->fudged_time_offset); + + spin_lock_irqsave(&ct->fudge_lock, flags); + if (ct->target_fudge != ct->current_fudge) { + ct->current_fudge = ct->target_fudge; + ct->raw_time_offset = now; + ct->fudged_time_offset = fudged_now; + } + spin_unlock_irqrestore(&ct->fudge_lock, flags); + + return fudged_now; +} + + static void coretimer_func(TIMER_DATA_TYPE unused) { unsigned long flags; @@ -10098,6 +10710,9 @@ now = ktime_get(); + /* SD-RI-PLL: scale the coretimer clock by the user-space fudge */ + now = coretimer_fudge(now, &core_timer); + if (atomic_read(&core_timer.count) == atomic_read(&core_timer.last_count)) { @@ -10171,6 +10786,11 @@ core_timer.start_interval = ktime_get(); atomic_set(&core_timer.count, 0); atomic_set(&core_timer.shutdown, 0); + spin_lock_init(&core_timer.fudge_lock); + core_timer.target_fudge = 0; + core_timer.current_fudge = 0; + core_timer.raw_time_offset = core_timer.start_interval; + core_timer.fudged_time_offset = core_timer.start_interval; core_timer.interval = max(msecs_to_jiffies(DAHDI_MSECS_PER_CHUNK), 1UL); if (core_timer.interval < (HZ/250)) core_timer.interval = (HZ/250); diff --git a/include/dahdi/user.h b/include/dahdi/user.h index 17e7a0e..c75dabb 100644 --- a/include/dahdi/user.h +++ b/include/dahdi/user.h @@ -1243,6 +1243,19 @@ }; #define DAHDI_TRUNKDEV_OPEN _IOWR(DAHDI_CODE, 253, struct dahdi_trunkdev_open) +/* Software clock correction of the DAHDI coretimer (SD-RI-PLL). The coretimer + * runs at a rate of (1 + fudge / 2^32); user space steers it by setting the + * target fudge via DAHDI_SW_CLOCK_SET. Numbers are allocated downwards from + * 252, like the trunkdev ones above, to avoid clashes with upstream DAHDI. */ +struct dahdi_sw_clock { + __s32 interval_sec; /* coretimer start interval, seconds */ + __s32 interval_nsec; /* coretimer start interval, nanoseconds */ + __s32 target_fudge; /* last fudge set via DAHDI_SW_CLOCK_SET */ + __s32 current_fudge; /* fudge currently applied by the coretimer */ +}; +#define DAHDI_SW_CLOCK_GET _IOR(DAHDI_CODE, 252, struct dahdi_sw_clock) +#define DAHDI_SW_CLOCK_SET _IOW(DAHDI_CODE, 251, __s32) /* new target fudge */ + #endif /* _DAHDI_USER_H */ -- To view, visit https://gerrit.osmocom.org/c/dahdi-linux/+/44234?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newchange Gerrit-Project: dahdi-linux Gerrit-Branch: master Gerrit-Change-Id: I93243a48566b337b3bb8f728d0ccf4b756755e4d Gerrit-Change-Number: 44234 Gerrit-PatchSet: 1 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org>
1 0
0 0
[L] Change in osmo-e1d[master]: add SD-RI-PLL self-tuning of the PID gains
by ale-leehrtz 04 Dec '26

04 Dec '26
ale-leehrtz has uploaded this change for review. ( https://gerrit.osmocom.org/c/osmo-e1d/+/44231?usp=email ) Change subject: add SD-RI-PLL self-tuning of the PID gains ...................................................................... add SD-RI-PLL self-tuning of the PID gains The PID gains of the SD-RI-PLL determine the loop bandwidth, and the right bandwidth depends on the link: on a noisy link the loop must be slow, while a large oscillator wander calls for a fast loop. Add a self-tuning regulator layer on top of the unchanged PID law. It estimates the measurement noise of the FIFO level (sigma_v) and the frequency wander of the oscillator (q_phi, from Allan-style variances over 1 h windows), and from these recomputes the loop bandwidth wn = (q_phi / sigma_v^2)^(1/4) and Kp/Ki by pole placement, as well as a smoothing time constant for the error. Gain changes are rate-limited. It also gates outliers and reports link-down ticks, so that the caller can hold the output instead of integrating a stale or empty FIFO. On a 53 h A/B run against the sysmocom OCTOI hub (first 24 h with the default gains, then self-tuned), time-in-band went from 71% to 90% and the FIFO standard deviation from 70 to 47 frames. Like the PID controller, this is hooked up in a follow-up patch. Related: OS#7116 Change-Id: Ifa5e1762df67c02093636908b45c6b5ce78fdc85 --- M src/Makefile.am A src/pll_tune.c A src/pll_tune.h 3 files changed, 336 insertions(+), 2 deletions(-) git pull ssh://gerrit.osmocom.org:29418/osmo-e1d refs/changes/31/44231/1 diff --git a/src/Makefile.am b/src/Makefile.am index 94f9644..2670b9f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -26,6 +26,7 @@ ice1usb_proto.h \ log.h \ pll_pid.h \ + pll_tune.h \ usb.h \ e1gen/crc4itu.h \ e1gen/osmo_e1f.h \ @@ -79,6 +80,8 @@ $(NULL) if ENABLE_DAHDI_TRUNKDEV -osmo_e1d_SOURCES += dahdi_trunkdev.c pll_pid.c -osmo_e1gen_SOURCES += dahdi_trunkdev.c pll_pid.c +osmo_e1d_SOURCES += dahdi_trunkdev.c pll_pid.c pll_tune.c +osmo_e1gen_SOURCES += dahdi_trunkdev.c pll_pid.c pll_tune.c +osmo_e1d_LDADD += -lm +osmo_e1gen_LDADD += -lm endif diff --git a/src/pll_tune.c b/src/pll_tune.c new file mode 100644 index 0000000..1446096 --- /dev/null +++ b/src/pll_tune.c @@ -0,0 +1,231 @@ +/* + * pll_tune.c + * + * SD-RI-PLL: online self-tuning of the PID gains. See pll_tune.h. + * + * (C) 2025-2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> + * + * All Rights Reserved + * + * SPDX-License-Identifier: GPL-2.0+ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ +#include <math.h> +#include "pll_tune.h" + +#define TWO_POW_32 4294967296.0 + +void pll_tune_default_params(struct pll_tune_params *p) +{ + p->n_star = 248.0; + p->tick_s = 1.0; + p->frames_per_s = 8000.0; + p->window = 3600; + p->zeta = 0.7071; + p->wn_min = 2.0 * M_PI / (8.0 * 3600.0); + p->wn_max = 2.0 * M_PI / 600.0; + p->warmup_windows = 6; + p->min_var_samples = 6; + p->max_ratio = 1.5; + p->ewma_win = 0.1; + p->ewma_tick = 1e-3; + p->filt_factor = 10.0; + p->gate = 6.0; + p->sigma_v_min = 8.0 / sqrt(12.0); /* DAHDI reads 8 frames per chunk */ + p->max_reject = 5; +} + +static void reset_window(struct pll_tune *t) +{ + t->ws_k = t->ws_nh = t->ws_nt = t->ws_bad = t->ws_n = 0; + t->ws_head = t->ws_tail = t->ws_u = 0.0; +} + +void pll_tune_init(struct pll_tune *t, const struct pll_tune_params *p) +{ + unsigned int i; + + t->p = *p; + t->k_plant = p->frames_per_s / TWO_POW_32; + t->absdiff = 0.0; + t->have_absdiff = false; + t->last_fifo = 0.0; + t->have_last = false; + t->n_rej = 0; + t->n_rejected = 0; + reset_window(t); + for (i = 0; i < PLL_TUNE_HIST; i++) { + t->phi[i] = 0.0; + t->phi_ok[i] = false; + } + t->n_phi = 0; + t->v1 = t->v4 = 0.0; + t->n_var = t->n_windows = 0; + t->wn = 0.0; + t->kp = t->ki = t->tau_f = 0.0; + t->q_phi = 0.0; +} + +double pll_tune_sigma_v(const struct pll_tune *t) +{ + /* E|dz| = 2*sigma_v/sqrt(pi) for dz = v[k]-v[k-1], v Gaussian. The FIFO + * is quantized (DAHDI moves 8 frames per chunk), which is measurement noise + * in its own right and makes |dz| mostly zero when the jitter is small: + * never report less than the quantization noise. */ + double sv; + + if (!t->have_absdiff) + return -1.0; + sv = t->absdiff * sqrt(M_PI) / 2.0; + return sv > t->p.sigma_v_min ? sv : t->p.sigma_v_min; +} + +bool pll_tune_input(struct pll_tune *t, double *fifo, double e_f, double u_applied) +{ + const unsigned int M = t->p.window / 5; + double sv, z = *fifo; + + if (z <= 0.0) { /* link down / underrun: holdover */ + t->ws_bad++; + t->have_last = false; + t->n_rej = 0; + return false; + } + + /* noise estimate from 1-s differences of accepted samples */ + if (t->have_last) { + double dz = fabs(z - t->last_fifo); + sv = pll_tune_sigma_v(t); + if (sv < 0.0 || dz < t->p.gate * M_SQRT2 * sv) { + if (!t->have_absdiff) { + t->absdiff = dz; + t->have_absdiff = true; + } else { + t->absdiff += t->p.ewma_tick * (dz - t->absdiff); + } + } + } + + /* outlier gate against the smoothed error, never sticky */ + sv = pll_tune_sigma_v(t); + if (sv >= 0.0 && !isnan(e_f) && + fabs(z - (t->p.n_star + e_f)) > t->p.gate * sv && t->n_rej < t->p.max_reject) { + t->n_rej++; + t->n_rejected++; + z = t->p.n_star + e_f; + } else { + t->n_rej = 0; + t->last_fifo = z; + t->have_last = true; + } + + /* window sums: head/tail FIFO means and mean applied fudge */ + t->ws_n++; + t->ws_u += u_applied; + if (t->ws_k < M) { + t->ws_head += z; + t->ws_nh++; + } else if (t->ws_k >= t->p.window - M) { + t->ws_tail += z; + t->ws_nt++; + } + + *fifo = z; + return true; +} + +static bool retune(struct pll_tune *t) +{ + double sv = pll_tune_sigma_v(t); + double q = (t->v4 - t->v1) / (3.0 * t->p.window); + double wn; + + if (sv <= 0.0 || q <= 0.0) + return false; // no evidence above the noise floor: keep gains + + wn = pow(q / (sv * sv), 0.25); + if (wn < t->p.wn_min) + wn = t->p.wn_min; + if (wn > t->p.wn_max) + wn = t->p.wn_max; + if (t->wn > 0.0) { + if (wn < t->wn / t->p.max_ratio) + wn = t->wn / t->p.max_ratio; + if (wn > t->wn * t->p.max_ratio) + wn = t->wn * t->p.max_ratio; + } + t->wn = wn; + t->q_phi = q; + t->kp = 2.0 * t->p.zeta * wn / t->k_plant; + t->ki = wn * wn * t->p.tick_s / t->k_plant; + t->tau_f = 1.0 / (t->p.filt_factor * wn); + return true; +} + +static bool close_window(struct pll_tune *t) +{ + const unsigned int M = t->p.window / 5; + bool ok = t->ws_bad <= t->p.window / 20 && t->ws_nh > 0 && t->ws_nt > 0; + double phi = 0.0; + bool all_ok = true; + unsigned int i; + + if (ok) { + /* N(t2)-N(t1) = int(phi) - K*int(u) over the window */ + double rate = (t->ws_tail / t->ws_nt - t->ws_head / t->ws_nh) / + (double)(t->p.window - M); + phi = rate + t->k_plant * t->ws_u / t->ws_n; + } + /* shift ring: [0] oldest ... [HIST-1] newest */ + for (i = 0; i + 1 < PLL_TUNE_HIST; i++) { + t->phi[i] = t->phi[i + 1]; + t->phi_ok[i] = t->phi_ok[i + 1]; + } + t->phi[PLL_TUNE_HIST - 1] = phi; + t->phi_ok[PLL_TUNE_HIST - 1] = ok; + if (t->n_phi < PLL_TUNE_HIST) + t->n_phi++; + reset_window(t); + t->n_windows++; + + // lag-1 uses windows [3],[4]; lag-4 uses [0],[4]: only those must be valid + all_ok = t->phi_ok[0] && t->phi_ok[3] && t->phi_ok[4]; + if (t->n_phi == PLL_TUNE_HIST && all_ok) { + double d1 = t->phi[4] - t->phi[3]; + double d4 = t->phi[4] - t->phi[0]; + if (t->n_var == 0) { + t->v1 = d1 * d1; + t->v4 = d4 * d4; + } else { + t->v1 += t->p.ewma_win * (d1 * d1 - t->v1); + t->v4 += t->p.ewma_win * (d4 * d4 - t->v4); + } + t->n_var++; + } + if (t->n_windows >= t->p.warmup_windows && t->n_var >= t->p.min_var_samples) + return retune(t); + return false; +} + +bool pll_tune_end_tick(struct pll_tune *t) +{ + t->ws_k++; + if (t->ws_k >= t->p.window) + return close_window(t); + return false; +} + +double pll_tune_bumpless_integral(double u, double e_f, double d, + double kp, double ki, double kd) +{ + return (u - kp * e_f - kd * d) / ki; +} diff --git a/src/pll_tune.h b/src/pll_tune.h new file mode 100644 index 0000000..a4fe1d8 --- /dev/null +++ b/src/pll_tune.h @@ -0,0 +1,100 @@ +/* SD-RI-PLL: online self-tuning of the PID gains (Kp, Ki) and of the e_i smoothing + * + * The PID law (paper Eq. 2) is NOT changed. This module watches the FIFO and the + * applied fudge, estimates the link noise (sigma_v) and the oscillator frequency + * wander (q_phi), and periodically hands new gains to the PID: + * + * wn = (q_phi / sigma_v^2)^(1/4), zeta = 1/sqrt(2) + * Kp = 2*zeta*wn / K, Ki = wn^2 * T / K, tau_f = 1 / (10*wn) + * K = frames_per_s / 2^32 + * + * It also conditions the input (outlier gate) and tells the caller when the link + * is down so the PID output and integral are held (holdover, no windup). + * + * (C) 2025-2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> + * + * All Rights Reserved + * + * SPDX-License-Identifier: GPL-2.0+ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ +#pragma once + +#include <stdbool.h> +#include <stdint.h> + +#define PLL_TUNE_HIST 5 /* per-window frequency ring (lags 1 and 4) */ + +struct pll_tune_params { + double n_star; /* 248 */ + double tick_s; /* 1.0 */ + double frames_per_s; /* 8000 */ + unsigned int window; /* ticks per frequency window (3600) */ + double zeta; /* 0.7071 */ + double wn_min, wn_max; /* rad/s bounds on the loop bandwidth */ + unsigned int warmup_windows; /* 6 */ + unsigned int min_var_samples; /* 6 */ + double max_ratio; /* max change of wn per retune (1.5) */ + double ewma_win; /* EWMA weight for the window variances (0.1) */ + double ewma_tick; /* EWMA weight for |dFIFO| (1e-3) */ + double filt_factor; /* tau_f = 1/(filt_factor*wn) (10) */ + double gate; /* outlier gate in sigma_v (6) */ + double sigma_v_min; /* floor: FIFO quantization step/sqrt(12) (8 frames -> 2.31) */ + unsigned int max_reject; /* consecutive rejections before forced accept (5) */ +}; + +struct pll_tune { + struct pll_tune_params p; + double k_plant; + /* noise estimate */ + double absdiff; + bool have_absdiff; + double last_fifo; + bool have_last; + unsigned int n_rej; + uint64_t n_rejected; + /* current window */ + unsigned int ws_k, ws_nh, ws_nt, ws_bad, ws_n; + double ws_head, ws_tail, ws_u; + /* frequency history and Allan-style variances */ + double phi[PLL_TUNE_HIST]; + bool phi_ok[PLL_TUNE_HIST]; + unsigned int n_phi; + double v1, v4; + unsigned int n_var, n_windows; + /* output */ + double wn; /* 0 until the first retune */ + double kp, ki, tau_f; + double q_phi; +}; + +void pll_tune_default_params(struct pll_tune_params *p); +void pll_tune_init(struct pll_tune *t, const struct pll_tune_params *p); + +/* Call first in each PID tick. + * *fifo : raw e1t_fifo_level; replaced by the gated value to feed the PID + * e_f : the PID's current smoothed error (for the gate); pass NAN if none yet + * u_applied: fudge applied during the last tick (model sign, see sdripll_timer_cb()) + * Returns false if the link is down (FIFO <= 0): skip the PID update, hold the output. */ +bool pll_tune_input(struct pll_tune *t, double *fifo, double e_f, double u_applied); + +/* Call after the PID update of a tick for which pll_tune_input() returned true. + * Returns true when new gains are in t->kp, t->ki, t->tau_f; apply them with + * pll_tune_bumpless_integral() so the fudge does not jump. */ +bool pll_tune_end_tick(struct pll_tune *t); + +/* Integral value that keeps u unchanged under the new gains: + * u = kp*e_f + ki*I + kd*d -> I = (u - kp*e_f - kd*d) / ki */ +double pll_tune_bumpless_integral(double u, double e_f, double d, + double kp, double ki, double kd); + +double pll_tune_sigma_v(const struct pll_tune *t); -- To view, visit https://gerrit.osmocom.org/c/osmo-e1d/+/44231?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newchange Gerrit-Project: osmo-e1d Gerrit-Branch: master Gerrit-Change-Id: Ifa5e1762df67c02093636908b45c6b5ce78fdc85 Gerrit-Change-Number: 44231 Gerrit-PatchSet: 1 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org>
1 0
0 0
[M] Change in osmo-e1d[master]: add SD-RI-PLL PID controller
by ale-leehrtz 04 Dec '26

04 Dec '26
ale-leehrtz has uploaded this change for review. ( https://gerrit.osmocom.org/c/osmo-e1d/+/44230?usp=email ) Change subject: add SD-RI-PLL PID controller ...................................................................... add SD-RI-PLL PID controller Add a small user-space PID controller for the SD-RI-PLL (software- defined, reference-independent PLL) that recovers the E1 clock of an E1-over-IP line in software: it takes the IP->E1 FIFO fill level as a proxy for the phase error between the remote E1 clock and the local DAHDI coretimer, and computes a rate correction ("fudge") for the coretimer, which then runs at (1 + fudge / 2^32). The controller has anti-windup on the integral and clamps its output to roughly +/-465 ppm. The default gains and the FIFO setpoint of 248 frames are the ones validated on a live OCTOI link in a community network for the ISPCS 2026 paper, see the related ticket. This patch only adds the controller; it is hooked up to the DAHDI trunkdev driver in a follow-up patch. Related: OS#7116 Change-Id: I246c3680f310f1f7326d348c8a803bbe86359059 --- M src/Makefile.am A src/pll_pid.c A src/pll_pid.h 3 files changed, 171 insertions(+), 2 deletions(-) git pull ssh://gerrit.osmocom.org:29418/osmo-e1d refs/changes/30/44230/1 diff --git a/src/Makefile.am b/src/Makefile.am index 30f0c79..94f9644 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -25,6 +25,7 @@ e1d.h \ ice1usb_proto.h \ log.h \ + pll_pid.h \ usb.h \ e1gen/crc4itu.h \ e1gen/osmo_e1f.h \ @@ -78,6 +79,6 @@ $(NULL) if ENABLE_DAHDI_TRUNKDEV -osmo_e1d_SOURCES += dahdi_trunkdev.c -osmo_e1gen_SOURCES += dahdi_trunkdev.c +osmo_e1d_SOURCES += dahdi_trunkdev.c pll_pid.c +osmo_e1gen_SOURCES += dahdi_trunkdev.c pll_pid.c endif diff --git a/src/pll_pid.c b/src/pll_pid.c new file mode 100644 index 0000000..80b576e --- /dev/null +++ b/src/pll_pid.c @@ -0,0 +1,100 @@ +/* + * pll_pid.c + * + * Software-defined, reference-independent PLL (SD-RI-PLL) for E1 timing: + * user-space PID controller. See pll_pid.h for the overall design. + * + * (C) 2025-2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> + * + * All Rights Reserved + * + * SPDX-License-Identifier: GPL-2.0+ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include "pll_pid.h" + +void pll_pid_init(struct pll_pid_controller *pid, float kp, float ki, float kd, float target_fifo) +{ + pid->kp = kp; + pid->ki = ki; + pid->kd = kd; + pid->target = target_fifo; + pid->integral = 0.0f; + pid->last_error = 0.0f; + pid->fudge = 0; + pid->tau_f = 0.0f; + pid->err_f = 0.0f; + pid->have_err_f = 0; +} + +/* Run one control step. 'current_fifo' is the measured IP->E1 FIFO + * occupancy; the returned value is the signed fudge to hand to the kernel + * (see the (1 + fudge/2^32) rate correction described in pll_pid.h). */ +int32_t pll_pid_update(struct pll_pid_controller *pid, int32_t current_fifo) +{ + float error = pid->target - (float)current_fifo; + float derivative; + float adjustment; + + /* smoothed error for P and D; identical to 'error' when tau_f == 0 */ + if (pid->tau_f > 0.0f && pid->have_err_f) + pid->err_f += (error - pid->err_f) / (pid->tau_f + 1.0f); + else + pid->err_f = error; + pid->have_err_f = 1; + derivative = pid->err_f - pid->last_error; + + /* Integrate with anti-windup: bound the accumulator so the integral + * term alone cannot exceed the output clamp. Without this the + * accumulator can run away while the output is saturated. */ + pid->integral += error; + if (pid->ki > 0.0f) { + float integral_limit = (float)PLL_PID_FUDGE_LIMIT / pid->ki; + + if (pid->integral > integral_limit) + pid->integral = integral_limit; + else if (pid->integral < -integral_limit) + pid->integral = -integral_limit; + } + + pid->last_error = pid->err_f; + + adjustment = pid->kp * pid->err_f + + pid->ki * pid->integral + + pid->kd * derivative; + + /* The coretimer applies (1 + fudge/2^32); a positive FIFO error means + * the E1 side is draining too fast, so we slow the clock (negative + * fudge). */ + adjustment = -adjustment; + + if (adjustment > (float)PLL_PID_FUDGE_LIMIT) + adjustment = (float)PLL_PID_FUDGE_LIMIT; + else if (adjustment < -(float)PLL_PID_FUDGE_LIMIT) + adjustment = -(float)PLL_PID_FUDGE_LIMIT; + + pid->fudge = (int32_t)adjustment; + return pid->fudge; +} + +void pll_pid_set_gains(struct pll_pid_controller *pid, float kp, float ki, float tau_f) +{ + /* current output, before the sign flip applied in pll_pid_update() */ + float adjustment = -(float)pid->fudge; + + pid->kp = kp; + pid->ki = ki; + pid->tau_f = tau_f; + if (ki > 0.0f) + pid->integral = (adjustment - kp * pid->err_f) / ki; +} diff --git a/src/pll_pid.h b/src/pll_pid.h new file mode 100644 index 0000000..7769049 --- /dev/null +++ b/src/pll_pid.h @@ -0,0 +1,68 @@ +/* + * pll_pid.h + * + * Software-defined, reference-independent PLL (SD-RI-PLL) for E1 timing. + * + * User-space PID controller that steers the DAHDI coretimer clock so the + * IP->E1 FIFO occupancy tracks a setpoint. The FIFO level is used as a + * proxy for the accumulated phase error between the incoming (network) and + * outgoing (E1) rates; the controller output ("fudge") is pushed to the + * kernel via the DAHDI_SW_CLOCK_SET ioctl, where the coretimer applies a + * multiplicative rate correction of (1 + fudge / 2^32). + * + * (C) 2025-2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> + * + * All Rights Reserved + * + * SPDX-License-Identifier: GPL-2.0+ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#pragma once + +#include <stdint.h> + +/* Default control parameters, as validated on a live OCTOI link (and used in + * the ISPCS 2026 paper, Table II). The derivative gain is small because the + * FIFO signal carries network and scheduler jitter. All of them can be + * overridden via the VTY ('pll pid-gains', 'pll target-fifo'). */ +#define PLL_PID_DEFAULT_KP 1.0f +#define PLL_PID_DEFAULT_KI 0.05f +#define PLL_PID_DEFAULT_KD 0.1f +#define PLL_PID_DEFAULT_TARGET_FIFO 248.0f + +/* Output clamp on the fudge value. fudge/2^32 is a fractional rate, so + * this bounds the correction to roughly +/-465 ppm: well outside the pull + * range of a compliant E1 clock, while still preventing controller runaway. */ +#define PLL_PID_FUDGE_LIMIT 2000000 + +struct pll_pid_controller { + float kp; + float ki; + float kd; + float integral; + float last_error; + float target; + int32_t fudge; + /* First-order smoothing of the error for the P and D terms (paper, + * Table II). tau_f = 0 disables it: the controller then behaves + * exactly as the plain PID of Eq. (2). */ + float tau_f; + float err_f; + int have_err_f; +}; + +void pll_pid_init(struct pll_pid_controller *pid, float kp, float ki, float kd, float target_fifo); +int32_t pll_pid_update(struct pll_pid_controller *pid, int32_t current_fifo); +/* Change gains without a jump in the output: the integral is rescaled so the + * next update produces the same fudge for the same error (bumpless transfer). */ +void pll_pid_set_gains(struct pll_pid_controller *pid, float kp, float ki, float tau_f); -- To view, visit https://gerrit.osmocom.org/c/osmo-e1d/+/44230?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newchange Gerrit-Project: osmo-e1d Gerrit-Branch: master Gerrit-Change-Id: I246c3680f310f1f7326d348c8a803bbe86359059 Gerrit-Change-Number: 44230 Gerrit-PatchSet: 1 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org>
1 0
0 0
[L] Change in osmo-e1d[master]: doc: manual: describe dahdi-trunkdev and the SD-RI-PLL
by ale-leehrtz 04 Dec '26

04 Dec '26
ale-leehrtz has uploaded this change for review. ( https://gerrit.osmocom.org/c/osmo-e1d/+/44233?usp=email ) Change subject: doc: manual: describe dahdi-trunkdev and the SD-RI-PLL ...................................................................... doc: manual: describe dahdi-trunkdev and the SD-RI-PLL Add a section on the dahdi-trunkdev driver to the drivers chapter, which was not documented so far, and a new chapter on the SD-RI-PLL software clock recovery: principle of operation, self-tuning of the gains, kernel requirements, the new 'pll' VTY commands, monitoring (show interface, log messages, CSV columns), guidance on the estimation window based on the test runs, and a summary of the validation and of the contribution, with a reference to the ISPCS 2026 paper. Also add an example configuration for an OCTOI client on a DAHDI trunkdev with the SD-RI-PLL in self-tuning mode. Related: OS#7116 Change-Id: If04665cb352f1976d085883f44998037a724eecc --- A doc/examples/osmo-e1d-dahdi-trunkdev-pll.cfg M doc/manuals/chapters/drivers.adoc A doc/manuals/chapters/sdripll.adoc M doc/manuals/osmoe1d-usermanual.adoc 4 files changed, 354 insertions(+), 0 deletions(-) git pull ssh://gerrit.osmocom.org:29418/osmo-e1d refs/changes/33/44233/1 diff --git a/doc/examples/osmo-e1d-dahdi-trunkdev-pll.cfg b/doc/examples/osmo-e1d-dahdi-trunkdev-pll.cfg new file mode 100644 index 0000000..2e3bede --- /dev/null +++ b/doc/examples/osmo-e1d-dahdi-trunkdev-pll.cfg @@ -0,0 +1,35 @@ +! +! osmo-e1d example configuration: E1-over-IP client on a DAHDI trunkdev, +! with the SD-RI-PLL recovering the remote E1 clock in software. +! +! The dahdi_trunkdev kernel module must be loaded with +! permit_clock_master=1, and the trunkdev "octoi" must exist in DAHDI. +! +log stderr + logging filter all 1 + logging color 1 + logging print category-hex 0 + logging print category 1 + logging timestamp 1 + logging print file basename last + logging print level 1 + logging level e1d info + logging level linp info + logging level trunkdev notice +! +line vty + no login +! +e1d + interface 0 dahdi-trunkdev + trunkdev-name octoi + pll log-file /var/log/osmocom/sdripll.csv + pll mode self-tuning + line 0 + mode e1oip +octoi-client 192.0.2.1 10013 + local-bind 0.0.0.0 3333 + account my_user_1 + mode dahdi-trunkdev + dahdi-trunkdev name octoi + dahdi-trunkdev line-number 0 diff --git a/doc/manuals/chapters/drivers.adoc b/doc/manuals/chapters/drivers.adoc index e4a3858..27b961d 100644 --- a/doc/manuals/chapters/drivers.adoc +++ b/doc/manuals/chapters/drivers.adoc @@ -83,3 +83,38 @@ You can subsequently use the Lines just like you would use physical E1 lines. Any data you transmit on one line will be received on the other line, and vice versa. + +[[driver-dahdi-trunkdev]] +=== The `dahdi-trunkdev` driver for DAHDI virtual trunks + +The `dahdi-trunkdev` driver connects `osmo-e1d` to a _trunkdev_ of the +osmocom fork of DAHDI: a virtual E1 span inside the DAHDI kernel +subsystem. This lets DAHDI-based applications use an E1 line that +`osmo-e1d` transports over IP (see <<octoi>>) instead of a physical E1 +card. + +The trunkdev has to be created on the DAHDI side before `osmo-e1d` +opens it, for example with the `dahdi_trunkdev` tool of the osmocom fork +of `dahdi-tools`, followed by the usual `dahdi_cfg`. + +==== Configuration + +.Example configuration snippet for a DAHDI trunkdev used for E1-over-IP +---- +e1d + interface 0 dahdi-trunkdev + trunkdev-name octoi + line 0 + mode e1oip +octoi-client 192.0.2.1 10013 + account my_user_1 + mode dahdi-trunkdev + dahdi-trunkdev name octoi + dahdi-trunkdev line-number 0 +---- + +`trunkdev-name` must match the name of the trunkdev created in DAHDI. + +Without a hardware clock source, DAHDI is paced by its coretimer, which +does not follow the clock of the remote E1. To recover that clock in +software, see <<sdripll>>. diff --git a/doc/manuals/chapters/sdripll.adoc b/doc/manuals/chapters/sdripll.adoc new file mode 100644 index 0000000..868d70e --- /dev/null +++ b/doc/manuals/chapters/sdripll.adoc @@ -0,0 +1,282 @@ +[[sdripll]] +== Software clock recovery (SD-RI-PLL) + +When `osmo-e1d` terminates an E1-over-IP (OCTOI) line through a DAHDI +trunkdev (see <<driver-dahdi-trunkdev>>) on a host without a hardware E1 +clock source, DAHDI is paced by its _coretimer_, which runs from the +host's own clock. That clock is not the clock of the remote E1 that +paces the incoming E1-over-IP stream. As a result the IP->E1 FIFO +slowly drains or fills up, which eventually leads to underruns or +overflows, and to frame slips on the E1 side. + +The _software-defined, reference-independent PLL_ (SD-RI-PLL) closes +this loop in software. It needs no GPS receiver, no disciplined +oscillator and no other external reference: the timing information it +uses is the rate at which E1 frames arrive over IP. The design and its +evaluation on a live E1 link of a community telephone network are +described in <<sdripll-ispcs2026>>. The feature is tracked in +<<sdripll-os7116>>. + +The SD-RI-PLL is _disabled by default_. + +=== Principle of operation + +The loop has three parts: + +Phase detector:: The fill level of the IP->E1 FIFO of line 0 is used as +a proxy for the phase error between the remote E1 clock and the local +coretimer. If the coretimer runs slow, the FIFO fills up; if it runs +fast, the FIFO drains. The setpoint is a FIFO level of 248 frames by +default. + +Controller:: Once per second, a PID controller in `osmo-e1d` compares +the FIFO level against the setpoint and computes a rate correction, the +_fudge_. The integral term has anti-windup, and the output is clamped +to +/-2000000, which corresponds to about +/-466 ppm. + +Controlled oscillator:: The fudge is passed to the kernel with the +`DAHDI_SW_CLOCK_SET` ioctl. From then on the DAHDI coretimer runs at a +rate of ++ +---- +(2^32 + fudge) / 2^32 +---- ++ +When a new fudge is applied, the kernel re-anchors its raw and fudged +time offsets, so the coretimer stays phase-continuous across the +change. The scaling is done with 96-bit fixed-point arithmetic built +from 32-bit limbs, so the kernel needs neither 64-bit division nor +floating point, and it allocates no memory in timer context. + +The default PID gains are Kp = 1.0, Ki = 0.05 and Kd = 0.1, the values +used in <<sdripll-ispcs2026>>. With these gains the loop is slow and +weakly damped: the FIFO swings around the setpoint with a period of +several hours. For better regulation, use the self-tuning mode +described below, or configure other gains. + +=== Self-tuning of the gains + +The right loop bandwidth depends on the link. On a link with a noisy +FIFO level, the loop must be slow so it does not chase the noise; with +an oscillator that wanders a lot, it must be fast so it can follow. In +`self-tuning` mode, a self-tuning regulator layer adapts the gains of +the (unchanged) PID law to the measured link: + +* The _measurement noise_ sigma_v of the FIFO level is estimated from + the 1-second differences of the FIFO level. It is never taken to be + lower than the quantization noise of the FIFO, 8/sqrt(12) = 2.3 + frames, as DAHDI moves the FIFO in chunks of 8 frames. +* The _frequency wander_ q_phi of the oscillator is estimated from the + frequency offset measured over consecutive _estimation windows_ (1 h + each by default), comparing the variances of its changes at lags of + 1 and 4 windows. +* From both, the loop bandwidth is chosen as ++ +---- +wn = (q_phi / sigma_v^2)^(1/4) +---- ++ +bounded to a loop period between 10 minutes and 8 hours, and the gains +follow by pole placement with a damping of 0.707: ++ +---- +Kp = 2 * 0.707 * wn / K Ki = wn^2 * T / K K = 8000 / 2^32 +---- ++ +where T is the 1-second tick. The error is additionally smoothed with +a time constant of 1 / (10 * wn), and FIFO samples far off the smoothed +error are rejected as outliers. + +A self-tuning run has two phases: + +baseline:: The configured gains are used, and the tuner only observes. +This phase lasts at least `pll self-tuning hold-time`, and in any case +until the tuner has its first estimate. The first estimate needs about +10 _valid_ estimation windows. A window is only valid if at most 5 % of +its ticks are bad (FIFO empty, or no TDM received for more than 3 +seconds), so on a link with many underruns this phase can take much +longer than 10 windows. + +tuned:: The self-tuned gains are applied without a bump in the output, +and re-computed at the end of every valid window. The bandwidth may +change by at most a factor of 1.5 per update. While the FIFO is empty +or no TDM arrives, the output is held (holdover) and the integral does +not wind up. + +A watchdog guards the tuned phase: if more than half of the ticks over +the last ~30 minutes are bad (FIFO empty, or more than 300 frames away +from the setpoint while TDM is arriving), the controller reverts to the +configured gains and stays there (phase `reverted`). + +=== Requirements + +The SD-RI-PLL needs the osmocom fork of DAHDI with the software clock +ioctls `DAHDI_SW_CLOCK_GET` and `DAHDI_SW_CLOCK_SET` (ioctl numbers 252 +and 251). `osmo-e1d` defines them itself if the installed DAHDI headers +lack them, so it also builds against DAHDI headers without them; but on a kernel without +support, the PLL logs an error and disables itself. + +As the trunkdev span is the DAHDI timing master in this setup, the +`dahdi_trunkdev` kernel module must be loaded with the module parameter +`permit_clock_master=1`. Without it, the kernel hits a `BUG()` as soon +as the trunkdev span becomes timing master. + +.Loading the trunkdev module for use with the SD-RI-PLL +---- +modprobe dahdi +modprobe dahdi_trunkdev permit_clock_master=1 +---- + +To make this persistent, add a line +`options dahdi_trunkdev permit_clock_master=1` to a file in +`/etc/modprobe.d/`. + +=== Configuration + +The SD-RI-PLL is configured per E1 interface, in the node of a +`dahdi-trunkdev` interface: + +.Example configuration snippet with the SD-RI-PLL in self-tuning mode +---- +e1d + interface 0 dahdi-trunkdev + trunkdev-name octoi + pll log-file /var/log/osmocom/sdripll.csv + pll mode self-tuning + line 0 + mode e1oip +---- + +A complete example is installed as +`doc/examples/osmo-e1d-dahdi-trunkdev-pll.cfg`. + +[options="header",cols="2,1,4"] +|=== +|Command|Default|Meaning +|`pll mode (off\|fixed\|self-tuning)`|`off`|`off` leaves the coretimer alone. `fixed` runs the PID with the configured gains. `self-tuning` runs the PID with the configured gains first, then with self-tuned gains. +|`pll pid-gains KP KI KD`|`1 0.05 0.1`|PID gains for `fixed` mode, and the initial gains for `self-tuning` mode. +|`pll target-fifo <1-1792>`|`248`|Setpoint of the IP->E1 FIFO, in E1 frames. +|`pll self-tuning hold-time <0-31536000>`|`86400`|Minimum duration of the baseline phase, in seconds. +|`pll self-tuning window <600-86400>`|`3600`|Length of the estimation windows, in seconds. See <<sdripll-window>>. +|`pll log-file FILENAME`|none|Append one CSV line per tick to this file. `no pll log-file` stops logging. +|=== + +Any change of a `pll` setting on a running interface restarts the +controller from scratch: the coretimer is set back to a fudge of 0, and +the integral and the tuner estimates are reset. + +[[sdripll-window]] +==== Choosing the estimation window + +Shorter estimation windows give a first estimate sooner, but noisier +estimates, as the frequency change within a short window is small +compared to the noise of the FIFO level. The noise then looks like +oscillator wander, and the tuner tends to choose too high a bandwidth. + +On the link used for testing (against the sysmocom OCTOI hub), this +was clearly visible: + +* With the default window of 1 hour, a 53-hour A/B run (24 hours with + the default gains, then self-tuned) raised the share of time with + the FIFO between 160 and 280 frames from 71 % to 90 %, and lowered + the standard deviation of the FIFO level from 70 to 47 frames. +* With a window of 600 seconds, over a 22-day run, the tuner stayed at + the upper bandwidth bound (loop period 10 minutes, Kp of about 7950) + for the whole tuned phase. Compared to the baseline, the FIFO spent + more time near the setpoint, but short underruns rose from about + 7.3 % to about 11.1 % of the time (long network outages excluded). + +Unless you have a reason to change it, keep the default of 1 hour. + +=== Monitoring + +`show interface` shows the FIFO levels of the E1-over-IP line and the +state of the SD-RI-PLL: + +.Output of `show interface` during the baseline phase +---- +osmo-e1d> show interface 0 +Interface #0 (octoi), Driver: dahdi-trunkdev + FIFO E1->IP: 16 frames, IP->E1: 248 frames + Software PLL: baseline, fudge -1358, Kp 1, Ki 0.05 +---- + +The state is `inactive` while the PLL is off, `fixed` in fixed mode, +and `baseline`, `tuned` or `reverted` in self-tuning mode. + +At the `NOTICE` level, the `DTRUNKDEV` log category reports when the +controller starts, every set of self-tuned gains, and a tripped +watchdog: + +.Example log messages +---- +SD-RI-PLL: started, mode self-tuning, target FIFO 248 +SD-RI-PLL: configured gains for at least 86400 s, then self-tuned gains (estimation window 3600 s) +SD-RI-PLL: gains Kp=2727.3 Ki=6.9275 tau_f=28s (sigma_v=11.5, loop period 0.49 h) +---- + +At the `DEBUG` level, every tick is logged. For offline analysis, +`pll log-file` writes one CSV line per tick with these columns: + +[options="header",cols="1,4"] +|=== +|Column|Meaning +|`t`|Wall-clock time, in seconds since the epoch +|`fifo`|IP->E1 FIFO level, in frames (0 if unknown) +|`fudge`|Fudge applied to the coretimer +|`kp`, `ki`|Current PID gains +|`tau_f`|Smoothing time constant of the error, in seconds (0 if not smoothed) +|`sigma_v`|Estimated measurement noise, in frames (-1 if not self-tuning) +|`q_phi`|Estimated frequency wander (-1 if not self-tuning, 0 before the first estimate) +|`link_up`|In `self-tuning` mode, 1 if the tick was usable (TDM arriving and FIFO not empty). In `fixed` mode, 1 whenever the FIFO level is known. +|`phase`|0 baseline (or fixed mode), 1 tuned, 2 reverted +|=== + +=== Validation + +<<sdripll-ispcs2026>> evaluates the SD-RI-PLL over 11 days on a live E1 +link serving community telephone networks, against a node running +open-loop on the same setup. The regulated node kept its mean FIFO +occupancy 0.5 samples from the setpoint, against 90.8 samples for the +open-loop node, and its time in band (as defined in the paper) was +48.7 %, against 28.7 %. That evaluation used an earlier revision of the +code, before the changes made for upstream inclusion. + +This implementation was additionally tested against the sysmocom OCTOI +hub with the A/B runs described in <<sdripll-window>>. It ran for 22 +days without interruption. + +=== Summary of the contribution + +The SD-RI-PLL consists of the following parts: + +In the osmocom DAHDI fork (`dahdi-linux`):: +* Software clock correction of the DAHDI coretimer, with + phase-continuous re-anchoring and 96-bit fixed-point time scaling. +* The `DAHDI_SW_CLOCK_GET` and `DAHDI_SW_CLOCK_SET` ioctls. +* The `permit_clock_master` parameter of the `dahdi_trunkdev` module. + +In `osmo-e1d`:: +* The PID controller (`pll_pid.c`). +* The self-tuning regulator layer (`pll_tune.c`), which realizes the + adaptive gain selection proposed as future work in + <<sdripll-ispcs2026>>. +* The integration into the `dahdi-trunkdev` driver, the `pll` VTY + commands, the CSV log and the PLL state in `show interface`. + +The SD-RI-PLL was developed by C. Alejandra Carreón-Jiménez at the +University of Texas at El Paso, with Christoph Lauter and Gabriel +Miki. + +[bibliography] +=== References + +- [[[sdripll-ispcs2026]]] C. A. Carreón-Jiménez, G. Miki, C. Lauter: + _SD-RI-PLL: A Software-Defined, Reference-Independent Phase-Locked + Loop for Fault-Tolerant E1 Synchronization in Resource-Constrained + Community Networks_. 2026 IEEE International Symposium on Precision + Clock Synchronization for Measurement, Control, and Communication + (ISPCS), Brescia, Italy, October 2026. +- [[[sdripll-os7116]]] Osmocom feature ticket OS#7116: _SD-RI-PLL: + software clock recovery for DAHDI trunkdev (E1-over-IP)_. + https://osmocom.org/issues/7116 diff --git a/doc/manuals/osmoe1d-usermanual.adoc b/doc/manuals/osmoe1d-usermanual.adoc index 58bd20f..7f859af 100644 --- a/doc/manuals/osmoe1d-usermanual.adoc +++ b/doc/manuals/osmoe1d-usermanual.adoc @@ -16,6 +16,8 @@ include::{srcdir}/chapters/drivers.adoc[] +include::{srcdir}/chapters/sdripll.adoc[] + include::{srcdir}/chapters/tdmoip.adoc[] //include::{srcdir}/chapters/control.adoc[] -- To view, visit https://gerrit.osmocom.org/c/osmo-e1d/+/44233?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newchange Gerrit-Project: osmo-e1d Gerrit-Branch: master Gerrit-Change-Id: If04665cb352f1976d085883f44998037a724eecc Gerrit-Change-Number: 44233 Gerrit-PatchSet: 1 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org>
1 0
0 0
[L] Change in osmo-e1d[master]: dahdi_trunkdev: add SD-RI-PLL software clock recovery
by ale-leehrtz 04 Dec '26

04 Dec '26
ale-leehrtz has uploaded this change for review. ( https://gerrit.osmocom.org/c/osmo-e1d/+/44232?usp=email ) Change subject: dahdi_trunkdev: add SD-RI-PLL software clock recovery ...................................................................... dahdi_trunkdev: add SD-RI-PLL software clock recovery Without a hardware clock source, the DAHDI coretimer that paces a trunkdev runs from the host clock, which is not the clock of the remote E1 that paces the incoming E1-over-IP stream, so the IP->E1 FIFO slowly drains or overflows. Close that loop in software: once per second, read the IP->E1 FIFO level of line 0, run the PID controller, and steer the coretimer via the new DAHDI_SW_CLOCK_SET ioctl of the osmocom DAHDI fork. The ioctl is defined locally if the DAHDI headers lack it; on a kernel without support the PLL disables itself with an error message. As the trunkdev span is the timing master in this setup, the dahdi_trunkdev module must be loaded with permit_clock_master=1. The PLL is off by default. New VTY commands on 'interface N dahdi-trunkdev': pll mode (off|fixed|self-tuning) pll pid-gains KP KI KD pll target-fifo <1-1792> pll self-tuning hold-time <0-31536000> pll self-tuning window <600-86400> pll log-file FILENAME / no pll log-file In self-tuning mode, the configured gains are used for at least the hold-time while the link is characterized; once the tuner has its first estimate (about 10 valid estimation windows, 1 h each by default), the self-tuned gains are applied bumplessly and updated after every window. A watchdog reverts to the configured gains if the loop runs away. The optional log file gets one CSV line per tick for offline analysis. 'show interface' shows the FIFO levels and the PLL state. Related: OS#7116 Change-Id: I20e0d62275c8422e3b272630dc52cebd80b66a15 --- M src/Makefile.am A src/dahdi_plltrunkdev.h M src/dahdi_trunkdev.c M src/e1d.h M src/vty.c 5 files changed, 620 insertions(+), 0 deletions(-) git pull ssh://gerrit.osmocom.org:29418/osmo-e1d refs/changes/32/44232/1 diff --git a/src/Makefile.am b/src/Makefile.am index 2670b9f..2f9fe73 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -22,6 +22,7 @@ noinst_HEADERS = \ + dahdi_plltrunkdev.h \ e1d.h \ ice1usb_proto.h \ log.h \ diff --git a/src/dahdi_plltrunkdev.h b/src/dahdi_plltrunkdev.h new file mode 100644 index 0000000..fa0f943 --- /dev/null +++ b/src/dahdi_plltrunkdev.h @@ -0,0 +1,78 @@ +/* + * dahdi_plltrunkdev.h + * + * Per-interface state for the SD-RI-PLL (software-defined, reference- + * independent PLL) running on a DAHDI trunkdev line: the PID controller, + * the optional self-tuning layer and the periodic timer. + * + * (C) 2025-2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> + * + * All Rights Reserved + * + * SPDX-License-Identifier: GPL-2.0+ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#pragma once + +#include <stdbool.h> +#include <stdint.h> +#include <stdio.h> +#include <time.h> + +#include <sys/ioctl.h> +#include <dahdi/user.h> + +#include <osmocom/core/timer.h> + +#include "pll_pid.h" +#include "pll_tune.h" + +struct e1_line; + +/* The software clock ioctls are not part of every DAHDI version. Define them + * here so osmo-e1d builds against stock DAHDI headers; on a kernel without + * support, DAHDI_SW_CLOCK_SET fails at runtime and the PLL disables itself. */ +#ifndef DAHDI_SW_CLOCK_SET +struct dahdi_sw_clock { + int32_t interval_sec; /* coretimer start interval, seconds */ + int32_t interval_nsec; /* coretimer start interval, nanoseconds */ + int32_t target_fudge; /* last fudge set via DAHDI_SW_CLOCK_SET */ + int32_t current_fudge; /* fudge currently applied by the coretimer */ +}; +#define DAHDI_SW_CLOCK_GET _IOR(DAHDI_CODE, 252, struct dahdi_sw_clock) +#define DAHDI_SW_CLOCK_SET _IOW(DAHDI_CODE, 251, int32_t) /* new target fudge */ +#endif + +enum sdripll_phase { + SDRIPLL_PHASE_BASELINE = 0, /* configured gains; tuner only estimates */ + SDRIPLL_PHASE_TUNED = 1, /* tuner-proposed gains applied */ + SDRIPLL_PHASE_REVERTED = 2, /* watchdog tripped, back to configured gains */ +}; + +struct dahdi_trunkdev_pll { + struct e1_line *line; /* line whose IP->E1 FIFO is regulated */ + int chan_fd; /* /dev/dahdi/channel, for DAHDI_SW_CLOCK_SET */ + struct osmo_timer_list timer; + struct pll_pid_controller pid; + float kp0, ki0; /* configured gains, for the watchdog revert */ + bool unsupported; /* kernel lacks DAHDI_SW_CLOCK_SET; stopped */ + + /* online gain adaptation (pll mode self-tuning) */ + bool tune_enabled; + struct pll_tune tune; + enum sdripll_phase phase; + time_t t_start; + unsigned int hold_s; + double wd_ewma; /* watchdog: fraction of bad ticks, ~30 min */ + FILE *csv; +}; diff --git a/src/dahdi_trunkdev.c b/src/dahdi_trunkdev.c index 11c5b9f..660374f 100644 --- a/src/dahdi_trunkdev.c +++ b/src/dahdi_trunkdev.c @@ -2,6 +2,7 @@ * trunkdev.c * * (C) 2022 by Harald Welte <laforge(a)osmocom.org> + * (C) 2025-2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> (SD-RI-PLL) * * All Rights Reserved * @@ -24,18 +25,27 @@ #include <string.h> #include <talloc.h> #include <fcntl.h> +#include <math.h> +#include <stdlib.h> +#include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <osmocom/core/utils.h> +#include <osmocom/core/stat_item.h> #include <dahdi/user.h> #include "e1d.h" #include "log.h" +/* SD-RI-PLL: software-defined reference-independent PLL for E1 timing */ +#include "dahdi_plltrunkdev.h" +#include "octoi/octoi_sock.h" /* struct octoi_peer */ +#include "octoi/e1oip.h" /* struct e1oip_line, FIFO level stat */ + /*********************************************************************** * low-level trunkdev routines ***********************************************************************/ @@ -67,6 +77,8 @@ struct e1_trunkdev_intf_data { /* file descriptor to the character device /dev/dahdi/trunkdev */ struct osmo_fd ofd; + /* SD-RI-PLL, NULL unless running */ + struct dahdi_trunkdev_pll *pll; }; /* file-descriptor call-back. Triggered by DAHDI via poll(), whenever @@ -132,6 +144,307 @@ } +/*********************************************************************** + * SD-RI-PLL: software clock recovery + ***********************************************************************/ + +/* Without a hardware clock source, the DAHDI coretimer that paces the trunkdev + * runs from the host clock, which is not the clock of the remote E1 that paces + * the incoming E1-over-IP stream: the IP->E1 FIFO slowly drains or overflows. + * The SD-RI-PLL closes that loop in software. Once per second a PID controller + * compares the FIFO level against a setpoint and steers the coretimer rate via + * DAHDI_SW_CLOCK_SET. In 'pll mode self-tuning' the PID gains are additionally + * adapted online from the measured link noise and oscillator wander (see + * pll_tune.h). The trunkdev span then is the timing master, so the + * dahdi_trunkdev kernel module must be loaded with permit_clock_master=1. */ + +/* Watchdog: a tick is "bad" if the FIFO is empty or far from N*. A loop that + * runs away shows up as excursions AND as underruns (FIFO == 0), which the + * tuner treats as link-down, so the watchdog must look at every tick. + * Trip when the bad fraction over ~30 min exceeds one half. */ +#define SDRIPLL_WD_BAND 300.0 +#define SDRIPLL_WD_TAU 1800.0 +#define SDRIPLL_WD_TRIP 0.5 + +static const struct value_string sdripll_phase_names[] = { + { SDRIPLL_PHASE_BASELINE, "baseline" }, + { SDRIPLL_PHASE_TUNED, "tuned" }, + { SDRIPLL_PHASE_REVERTED, "reverted" }, + { 0, NULL } +}; + +static time_t mono_s(void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec; +} + +static void sdripll_log(struct dahdi_trunkdev_pll *pll, double fifo_raw, bool up) +{ + struct timespec ts; + + if (!pll->csv) + return; + clock_gettime(CLOCK_REALTIME, &ts); + fprintf(pll->csv, "%.3f,%.0f,%d,%.6g,%.6g,%.6g,%.4g,%.4g,%d,%d\n", + ts.tv_sec + ts.tv_nsec * 1e-9, fifo_raw, pll->pid.fudge, + (double)pll->pid.kp, (double)pll->pid.ki, (double)pll->pid.tau_f, + pll->tune_enabled ? pll_tune_sigma_v(&pll->tune) : -1.0, + pll->tune_enabled ? pll->tune.q_phi : -1.0, up ? 1 : 0, (int)pll->phase); +} + +static void sdripll_apply_tuned(struct dahdi_trunkdev_pll *pll) +{ + pll_pid_set_gains(&pll->pid, (float)pll->tune.kp, (float)pll->tune.ki, + (float)pll->tune.tau_f); + LOGPLI(pll->line, DTRUNKDEV, LOGL_NOTICE, + "SD-RI-PLL: gains Kp=%.1f Ki=%.4f tau_f=%.0fs (sigma_v=%.1f, loop period %.2f h)\n", + pll->tune.kp, pll->tune.ki, pll->tune.tau_f, pll_tune_sigma_v(&pll->tune), + 2.0 * M_PI / pll->tune.wn / 3600.0); +} + +/* Push a new fudge to the coretimer. Returns false if the kernel lacks the + * ioctl (DAHDI answers unknown ioctls with ENOSYS), in which case there is + * nothing to regulate and the caller stops the PLL. */ +static bool sdripll_set_fudge(struct dahdi_trunkdev_pll *pll, int32_t fudge) +{ + if (ioctl(pll->chan_fd, DAHDI_SW_CLOCK_SET, &fudge) == 0) + return true; + + if (errno == ENOSYS || errno == ENOTTY || errno == EINVAL) { + LOGPLI(pll->line, DTRUNKDEV, LOGL_ERROR, "SD-RI-PLL: DAHDI kernel module has no " + "DAHDI_SW_CLOCK_SET support (%s), PLL disabled\n", strerror(errno)); + pll->unsupported = true; + return false; + } + + LOGPLI(pll->line, DTRUNKDEV, LOGL_ERROR, "SD-RI-PLL: DAHDI_SW_CLOCK_SET failed: %s\n", + strerror(errno)); + return true; +} + +/* Periodic (1 Hz) tick: read the IP->E1 FIFO occupancy, run one control + * step, and push the resulting fudge to the DAHDI coretimer. */ +static void sdripll_timer_cb(void *data) +{ + struct dahdi_trunkdev_pll *pll = data; + struct e1_line *line = pll->line; + struct octoi_peer *peer = line->octoi_peer; + int32_t current_fifo = 0, new_fudge; + bool have_fifo = false, up = true, tdm_alive; + double z, e_f; + + /* The FIFO stats only exist once the OCTOI peer is up */ + if (peer && peer->iline && peer->iline->stats) { + current_fifo = osmo_stat_item_get_last( + osmo_stat_item_group_get_item(peer->iline->stats, LINE_STAT_E1oIP_E1T_FIFO)); + have_fifo = true; + } + /* TDM received within the last 3 s: the link is really up (same rule + * as the OCTOI FSMs; last_rx_tdm is CLOCK_MONOTONIC) */ + tdm_alive = peer && mono_s() - peer->last_rx_tdm <= 3; + + if (!pll->tune_enabled) { + /* plain PID, exactly as published */ + if (!have_fifo) + goto rearm; + z = current_fifo; + goto update; + } + + /* Tuner input conditioning. Model sign: e = FIFO - N* = -err_f, and a + * positive fudge drains the FIFO, so u_applied = +fudge. A FIFO <= 0 or + * no TDM arriving (link down / underrun) returns false: the tuner skips + * the tick. */ + z = (have_fifo && tdm_alive) ? (double)current_fifo : 0.0; + e_f = pll->pid.have_err_f ? -(double)pll->pid.err_f : NAN; + up = pll_tune_input(&pll->tune, &z, e_f, (double)pll->pid.fudge); + + if (pll->phase == SDRIPLL_PHASE_BASELINE) { + /* baseline: the tuner only observes; the PID gets the raw FIFO, + * exactly as the published controller (no gate, no holdover) */ + if (!have_fifo) + goto log; + z = current_fifo; + } else if (!up) { + /* tuned: holdover, the kernel keeps applying the last fudge and + * the integral does not wind up on a stale or empty FIFO */ + goto log; + } + +update: + new_fudge = pll_pid_update(&pll->pid, (int32_t)lrint(z)); + + LOGPLI(line, DTRUNKDEV, LOGL_DEBUG, "SD-RI-PLL: FIFO=%d target=%.0f -> fudge=%d\n", + current_fifo, (double)pll->pid.target, new_fudge); + + if (!sdripll_set_fudge(pll, new_fudge)) + return; /* no kernel support: do not re-arm */ + + if (!pll->tune_enabled) + goto log; + + if (up && pll_tune_end_tick(&pll->tune) && pll->phase == SDRIPLL_PHASE_TUNED) + sdripll_apply_tuned(pll); + + /* end of the baseline phase: switch to the proposed gains */ + if (pll->phase == SDRIPLL_PHASE_BASELINE && pll->tune.wn > 0.0 && + mono_s() - pll->t_start >= (time_t)pll->hold_s) { + sdripll_apply_tuned(pll); + pll->phase = SDRIPLL_PHASE_TUNED; + } + +log: + /* Watchdog: persistent runaway after the switch -> back to the configured + * gains. Only judge ticks while TDM is actually arriving: an empty FIFO + * with the link up is an underrun (bad); with no TDM for >3 s it is a link + * outage and says nothing about the loop. */ + if (pll->tune_enabled && pll->phase == SDRIPLL_PHASE_TUNED && have_fifo && tdm_alive) { + double bad = (current_fifo <= 0 || + fabs((double)current_fifo - (double)pll->pid.target) > SDRIPLL_WD_BAND); + pll->wd_ewma += (bad - pll->wd_ewma) / SDRIPLL_WD_TAU; + if (pll->wd_ewma > SDRIPLL_WD_TRIP) { + pll_pid_set_gains(&pll->pid, pll->kp0, pll->ki0, 0.0f); + pll->phase = SDRIPLL_PHASE_REVERTED; + LOGPLI(line, DTRUNKDEV, LOGL_ERROR, + "SD-RI-PLL: watchdog tripped, reverted to configured gains\n"); + } + } + sdripll_log(pll, have_fifo ? (double)current_fifo : 0.0, up && have_fifo); +rearm: + osmo_timer_schedule(&pll->timer, 1, 0); +} + +static void trunkdev_pll_start(struct e1_intf *e1i) +{ + struct e1_trunkdev_intf_data *tid = e1i->drv_data; + struct dahdi_trunkdev_pll *pll; + struct e1_line *e1l; + int cfd; + + if (!tid || tid->pll || e1i->dahdi_trunkdev.pll.mode == E1_TRUNKDEV_PLL_OFF) + return; + + e1l = e1_intf_find_line(e1i, 0); + if (!e1l) + return; + + cfd = open("/dev/dahdi/channel", O_RDWR); + if (cfd < 0) { + LOGPLI(e1l, DTRUNKDEV, LOGL_ERROR, + "SD-RI-PLL: cannot open /dev/dahdi/channel, PLL disabled: %s\n", strerror(errno)); + return; + } + + pll = talloc_zero(tid, struct dahdi_trunkdev_pll); + OSMO_ASSERT(pll); + pll->line = e1l; + pll->chan_fd = cfd; + pll->kp0 = e1i->dahdi_trunkdev.pll.kp; + pll->ki0 = e1i->dahdi_trunkdev.pll.ki; + pll_pid_init(&pll->pid, pll->kp0, pll->ki0, e1i->dahdi_trunkdev.pll.kd, + (float)e1i->dahdi_trunkdev.pll.target_fifo); + + pll->tune_enabled = e1i->dahdi_trunkdev.pll.mode == E1_TRUNKDEV_PLL_SELF_TUNING; + pll->phase = SDRIPLL_PHASE_BASELINE; + if (pll->tune_enabled) { + struct pll_tune_params tp; + + pll->hold_s = e1i->dahdi_trunkdev.pll.hold_s; + pll->t_start = mono_s(); + pll_tune_default_params(&tp); + tp.n_star = e1i->dahdi_trunkdev.pll.target_fifo; + tp.window = e1i->dahdi_trunkdev.pll.window_s; + pll_tune_init(&pll->tune, &tp); + } + + if (e1i->dahdi_trunkdev.pll.log_file) { + const char *path = e1i->dahdi_trunkdev.pll.log_file; + + pll->csv = fopen(path, "a"); + if (pll->csv) { + setvbuf(pll->csv, NULL, _IOLBF, 0); + if (ftell(pll->csv) == 0) + fprintf(pll->csv, "t,fifo,fudge,kp,ki,tau_f,sigma_v,q_phi,link_up,phase\n"); + } else { + LOGPLI(e1l, DTRUNKDEV, LOGL_ERROR, "SD-RI-PLL: cannot open log file %s: %s\n", + path, strerror(errno)); + } + } + + osmo_timer_setup(&pll->timer, sdripll_timer_cb, pll); + osmo_timer_schedule(&pll->timer, 1, 0); + tid->pll = pll; + + LOGPLI(e1l, DTRUNKDEV, LOGL_NOTICE, "SD-RI-PLL: started, mode %s, target FIFO %u\n", + pll->tune_enabled ? "self-tuning" : "fixed", e1i->dahdi_trunkdev.pll.target_fifo); + if (pll->tune_enabled) + LOGPLI(e1l, DTRUNKDEV, LOGL_NOTICE, "SD-RI-PLL: configured gains for at least %u s, then " + "self-tuned gains (estimation window %u s)\n", pll->hold_s, pll->tune.p.window); +} + +static void trunkdev_pll_stop(struct e1_intf *e1i) +{ + struct e1_trunkdev_intf_data *tid = e1i->drv_data; + struct dahdi_trunkdev_pll *pll; + + if (!tid || !tid->pll) + return; + pll = tid->pll; + + osmo_timer_del(&pll->timer); + /* do not leave the coretimer running at a stale rate */ + if (!pll->unsupported) + sdripll_set_fudge(pll, 0); + close(pll->chan_fd); + if (pll->csv) + fclose(pll->csv); + talloc_free(pll); + tid->pll = NULL; +} + +void +e1_dahdi_trunkdev_pll_defaults(struct e1_intf *e1i) +{ + e1i->dahdi_trunkdev.pll.mode = E1_TRUNKDEV_PLL_OFF; + e1i->dahdi_trunkdev.pll.kp = PLL_PID_DEFAULT_KP; + e1i->dahdi_trunkdev.pll.ki = PLL_PID_DEFAULT_KI; + e1i->dahdi_trunkdev.pll.kd = PLL_PID_DEFAULT_KD; + e1i->dahdi_trunkdev.pll.target_fifo = PLL_PID_DEFAULT_TARGET_FIFO; + e1i->dahdi_trunkdev.pll.hold_s = 86400; + e1i->dahdi_trunkdev.pll.window_s = 3600; + e1i->dahdi_trunkdev.pll.log_file = NULL; +} + +/* Apply a changed PLL configuration to an open trunkdev. Note that this + * restarts the controller from zero (integral, tuner estimates). */ +void +e1_dahdi_trunkdev_pll_restart(struct e1_intf *e1i) +{ + trunkdev_pll_stop(e1i); + trunkdev_pll_start(e1i); +} + +const char * +e1_dahdi_trunkdev_pll_state_str(const struct e1_intf *e1i) +{ + static char buf[128]; + const struct e1_trunkdev_intf_data *tid = e1i->drv_data; + const struct dahdi_trunkdev_pll *pll = tid ? tid->pll : NULL; + + if (!pll) + return "inactive"; + if (pll->unsupported) + return "disabled (no DAHDI_SW_CLOCK_SET in kernel)"; + + snprintf(buf, sizeof(buf), "%s, fudge %d, Kp %.4g, Ki %.4g", + pll->tune_enabled ? get_value_string(sdripll_phase_names, pll->phase) : "fixed", + pll->pid.fudge, (double)pll->pid.kp, (double)pll->pid.ki); + return buf; +} + int e1_dahdi_trunkdev_open(struct e1_intf *e1i) { @@ -197,6 +510,9 @@ llist_for_each_entry(e1l, &e1i->lines, list) e1_line_active(e1l); + /* SD-RI-PLL software clock recovery, if configured */ + trunkdev_pll_start(e1i); + return 0; } @@ -216,6 +532,8 @@ return 0; } + trunkdev_pll_stop(e1i); + osmo_fd_unregister(&tid->ofd); /* we're not deleting the dahdi trunkdev as that might upset the applications using diff --git a/src/e1d.h b/src/e1d.h index 7d2d4c6..a0eb484 100644 --- a/src/e1d.h +++ b/src/e1d.h @@ -2,6 +2,7 @@ * e1d.h * * (C) 2019 by Sylvain Munaut <tnt(a)246tNt.com> + * (C) 2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> * * All Rights Reserved * @@ -213,6 +214,12 @@ extern const struct value_string e1_driver_names[]; extern const struct value_string e1_line_mode_names[]; +enum e1_trunkdev_pll_mode { + E1_TRUNKDEV_PLL_OFF, /* coretimer left alone (default) */ + E1_TRUNKDEV_PLL_FIXED, /* PID with the configured gains */ + E1_TRUNKDEV_PLL_SELF_TUNING, /* PID gains adapted online */ +}; + struct e1_intf { struct llist_head list; @@ -229,6 +236,15 @@ } usb; struct { char *name; + /* SD-RI-PLL: software clock recovery, see dahdi_trunkdev.c */ + struct { + enum e1_trunkdev_pll_mode mode; + float kp, ki, kd; + unsigned int target_fifo; + unsigned int hold_s; /* self-tuning: baseline time before adapting */ + unsigned int window_s; /* self-tuning: frequency estimation window */ + char *log_file; /* optional CSV, one line per tick */ + } pll; } dahdi_trunkdev; bool vty_created; @@ -306,6 +322,15 @@ int e1_dahdi_trunkdev_close(struct e1_intf *e1i); + +void +e1_dahdi_trunkdev_pll_defaults(struct e1_intf *e1i); + +void +e1_dahdi_trunkdev_pll_restart(struct e1_intf *e1i); + +const char * +e1_dahdi_trunkdev_pll_state_str(const struct e1_intf *e1i); #endif int diff --git a/src/vty.c b/src/vty.c index c955a3f..9dd5266 100644 --- a/src/vty.c +++ b/src/vty.c @@ -1,5 +1,6 @@ /* osmo-e1d VTY interface */ /* (C) 2020 by Harald Welte <laforge(a)osmocom.org> + * (C) 2026 by C. Alejandra Carreon-Jimenez <alejandra.carreon(a)ale-leehrtz.org> * All Rights Reserved * * This program is free software; you can redistribute it and/or modify @@ -42,6 +43,11 @@ #include "e1d.h" #include "usb.h" +#include "octoi/octoi_sock.h" +#include "octoi/e1oip.h" +#ifdef HAVE_DAHDI_TRUNKDEV +#include "pll_pid.h" +#endif struct e1_daemon *vty_e1d; @@ -116,6 +122,25 @@ e1_usb_intf_gpsdo_state_string(buf, sizeof(buf), intf); vty_out(vty, " GPS-DO: %s%s", buf, VTY_NEWLINE); break; +#ifdef HAVE_DAHDI_TRUNKDEV + case E1_DRIVER_DAHDI_TRUNKDEV: + { + /* FIFO levels of the E1-over-IP line; IP->E1 is what the PLL regulates */ + const struct e1_line *line = e1_intf_find_line((struct e1_intf *)intf, 0); + + if (line && line->octoi_peer && line->octoi_peer->iline && + line->octoi_peer->iline->stats) { + struct osmo_stat_item_group *st = line->octoi_peer->iline->stats; + + vty_out(vty, " FIFO E1->IP: %d frames, IP->E1: %d frames%s", + osmo_stat_item_get_last(osmo_stat_item_group_get_item(st, LINE_STAT_E1oIP_E1O_FIFO)), + osmo_stat_item_get_last(osmo_stat_item_group_get_item(st, LINE_STAT_E1oIP_E1T_FIFO)), + VTY_NEWLINE); + } + vty_out(vty, " Software PLL: %s%s", e1_dahdi_trunkdev_pll_state_str(intf), VTY_NEWLINE); + break; + } +#endif default: break; } @@ -320,6 +345,8 @@ vty_out(vty, "%% Could not create interface%s", VTY_NEWLINE); return CMD_WARNING; } + if (intf->drv != E1_DRIVER_DAHDI_TRUNKDEV) + e1_dahdi_trunkdev_pll_defaults(intf); intf->drv = E1_DRIVER_DAHDI_TRUNKDEV; intf->vty_created = true; @@ -393,6 +420,167 @@ return CMD_SUCCESS; } + +#define PLL_STR "Software clock recovery (SD-RI-PLL) of the DAHDI coretimer\n" + +static const struct value_string pll_mode_names[] = { + { E1_TRUNKDEV_PLL_OFF, "off" }, + { E1_TRUNKDEV_PLL_FIXED, "fixed" }, + { E1_TRUNKDEV_PLL_SELF_TUNING, "self-tuning" }, + { 0, NULL } +}; + +static bool parse_gain(struct vty *vty, const char *str, float *out) +{ + char *end; + float f = strtof(str, &end); + + if (end == str || *end != '\0' || !(f >= 0.0f) || f > 1e9f) { + vty_out(vty, "%% Invalid gain '%s', expecting a non-negative number%s", str, VTY_NEWLINE); + return false; + } + *out = f; + return true; +} + +DEFUN(cfg_e1d_if_pll_mode, cfg_e1d_if_pll_mode_cmd, + "pll mode (off|fixed|self-tuning)", + PLL_STR "Operating mode of the software clock recovery\n" + "Do not touch the DAHDI coretimer (default)\n" + "PID controller with the configured gains\n" + "PID controller; after 'pll self-tuning hold-time', gains are adapted online\n") +{ + struct e1_intf *intf = vty->index; + + if (intf->drv != E1_DRIVER_DAHDI_TRUNKDEV) + return CMD_WARNING; + + intf->dahdi_trunkdev.pll.mode = get_string_value(pll_mode_names, argv[0]); + e1_dahdi_trunkdev_pll_restart(intf); + return CMD_SUCCESS; +} + +DEFUN(cfg_e1d_if_pll_gains, cfg_e1d_if_pll_gains_cmd, + "pll pid-gains KP KI KD", + PLL_STR "Configure the PID gains (in self-tuning mode: the initial gains)\n" + "Proportional gain\n" "Integral gain\n" "Derivative gain\n") +{ + struct e1_intf *intf = vty->index; + float kp, ki, kd; + + if (intf->drv != E1_DRIVER_DAHDI_TRUNKDEV) + return CMD_WARNING; + if (!parse_gain(vty, argv[0], &kp) || !parse_gain(vty, argv[1], &ki) || + !parse_gain(vty, argv[2], &kd)) + return CMD_WARNING; + + intf->dahdi_trunkdev.pll.kp = kp; + intf->dahdi_trunkdev.pll.ki = ki; + intf->dahdi_trunkdev.pll.kd = kd; + e1_dahdi_trunkdev_pll_restart(intf); + return CMD_SUCCESS; +} + +DEFUN(cfg_e1d_if_pll_target, cfg_e1d_if_pll_target_cmd, + "pll target-fifo <1-1792>", + PLL_STR "Configure the IP->E1 FIFO setpoint\n" + "FIFO level in E1 frames (default 248)\n") +{ + struct e1_intf *intf = vty->index; + + if (intf->drv != E1_DRIVER_DAHDI_TRUNKDEV) + return CMD_WARNING; + + intf->dahdi_trunkdev.pll.target_fifo = atoi(argv[0]); + e1_dahdi_trunkdev_pll_restart(intf); + return CMD_SUCCESS; +} + +DEFUN(cfg_e1d_if_pll_hold, cfg_e1d_if_pll_hold_cmd, + "pll self-tuning hold-time <0-31536000>", + PLL_STR "Self-tuning mode parameters\n" + "Minimum time to run with the configured gains while the link is characterized " + "(the switch also waits for the first self-tuned estimate)\n" + "Seconds (default 86400)\n") +{ + struct e1_intf *intf = vty->index; + + if (intf->drv != E1_DRIVER_DAHDI_TRUNKDEV) + return CMD_WARNING; + + intf->dahdi_trunkdev.pll.hold_s = atoi(argv[0]); + e1_dahdi_trunkdev_pll_restart(intf); + return CMD_SUCCESS; +} + +DEFUN(cfg_e1d_if_pll_window, cfg_e1d_if_pll_window_cmd, + "pll self-tuning window <600-86400>", + PLL_STR "Self-tuning mode parameters\n" + "Length of the windows over which the oscillator frequency is estimated. " + "The first self-tuned gains need about 10 valid windows; shorter windows " + "adapt sooner but give noisier estimates\n" + "Seconds (default 3600)\n") +{ + struct e1_intf *intf = vty->index; + + if (intf->drv != E1_DRIVER_DAHDI_TRUNKDEV) + return CMD_WARNING; + + intf->dahdi_trunkdev.pll.window_s = atoi(argv[0]); + e1_dahdi_trunkdev_pll_restart(intf); + return CMD_SUCCESS; +} + +DEFUN(cfg_e1d_if_pll_log, cfg_e1d_if_pll_log_cmd, + "pll log-file FILENAME", + PLL_STR "Log the controller state to a CSV file, one line per second\n" + "Path of the CSV file (appended to)\n") +{ + struct e1_intf *intf = vty->index; + + if (intf->drv != E1_DRIVER_DAHDI_TRUNKDEV) + return CMD_WARNING; + + osmo_talloc_replace_string(intf, &intf->dahdi_trunkdev.pll.log_file, argv[0]); + e1_dahdi_trunkdev_pll_restart(intf); + return CMD_SUCCESS; +} + +DEFUN(cfg_e1d_if_no_pll_log, cfg_e1d_if_no_pll_log_cmd, + "no pll log-file", + NO_STR PLL_STR "Stop logging the controller state to a CSV file\n") +{ + struct e1_intf *intf = vty->index; + + if (intf->drv != E1_DRIVER_DAHDI_TRUNKDEV) + return CMD_WARNING; + + TALLOC_FREE(intf->dahdi_trunkdev.pll.log_file); + e1_dahdi_trunkdev_pll_restart(intf); + return CMD_SUCCESS; +} + +static void config_write_trunkdev_pll(struct vty *vty, const struct e1_intf *intf) +{ + if (intf->dahdi_trunkdev.pll.kp != PLL_PID_DEFAULT_KP || + intf->dahdi_trunkdev.pll.ki != PLL_PID_DEFAULT_KI || + intf->dahdi_trunkdev.pll.kd != PLL_PID_DEFAULT_KD) + vty_out(vty, " pll pid-gains %g %g %g%s", (double)intf->dahdi_trunkdev.pll.kp, + (double)intf->dahdi_trunkdev.pll.ki, (double)intf->dahdi_trunkdev.pll.kd, + VTY_NEWLINE); + if (intf->dahdi_trunkdev.pll.target_fifo != (unsigned int)PLL_PID_DEFAULT_TARGET_FIFO) + vty_out(vty, " pll target-fifo %u%s", intf->dahdi_trunkdev.pll.target_fifo, VTY_NEWLINE); + if (intf->dahdi_trunkdev.pll.hold_s != 86400) + vty_out(vty, " pll self-tuning hold-time %u%s", intf->dahdi_trunkdev.pll.hold_s, VTY_NEWLINE); + if (intf->dahdi_trunkdev.pll.window_s != 3600) + vty_out(vty, " pll self-tuning window %u%s", intf->dahdi_trunkdev.pll.window_s, VTY_NEWLINE); + if (intf->dahdi_trunkdev.pll.log_file) + vty_out(vty, " pll log-file %s%s", intf->dahdi_trunkdev.pll.log_file, VTY_NEWLINE); + /* mode last, so that the controller starts once with all parameters set */ + if (intf->dahdi_trunkdev.pll.mode != E1_TRUNKDEV_PLL_OFF) + vty_out(vty, " pll mode %s%s", get_value_string(pll_mode_names, intf->dahdi_trunkdev.pll.mode), + VTY_NEWLINE); +} #endif /* HAVE_DAHDI_TRUNKDEV */ DEFUN(cfg_e1d_if_line, cfg_e1d_if_line_cmd, "line <0-255>", @@ -550,6 +738,9 @@ vty_out(vty, " interface %u dahdi-trunkdev%s", intf->id, VTY_NEWLINE); if (intf->dahdi_trunkdev.name && strlen(intf->dahdi_trunkdev.name)) vty_out(vty, " trunkdev-name %s%s", intf->dahdi_trunkdev.name, VTY_NEWLINE); +#ifdef HAVE_DAHDI_TRUNKDEV + config_write_trunkdev_pll(vty, intf); +#endif break; default: break; @@ -584,6 +775,13 @@ install_element(INTF_NODE, &cfg_e1d_if_no_gpsdo_manual_cmd); #ifdef HAVE_DAHDI_TRUNKDEV install_element(INTF_NODE, &cfg_e1d_if_trunkdev_name_cmd); + install_element(INTF_NODE, &cfg_e1d_if_pll_mode_cmd); + install_element(INTF_NODE, &cfg_e1d_if_pll_gains_cmd); + install_element(INTF_NODE, &cfg_e1d_if_pll_target_cmd); + install_element(INTF_NODE, &cfg_e1d_if_pll_hold_cmd); + install_element(INTF_NODE, &cfg_e1d_if_pll_window_cmd); + install_element(INTF_NODE, &cfg_e1d_if_pll_log_cmd); + install_element(INTF_NODE, &cfg_e1d_if_no_pll_log_cmd); #endif /* HAVE_DAHDI_TRUNKDEV */ install_node(&line_node, NULL); -- To view, visit https://gerrit.osmocom.org/c/osmo-e1d/+/44232?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: newchange Gerrit-Project: osmo-e1d Gerrit-Branch: master Gerrit-Change-Id: I20e0d62275c8422e3b272630dc52cebd80b66a15 Gerrit-Change-Number: 44232 Gerrit-PatchSet: 1 Gerrit-Owner: ale-leehrtz <alejandra.carreon(a)ale-leehrtz.org>
1 0
0 0
[L] Change in libosmocore[master]: gsm: new struct and en/decoding functions for BC-IE
by falconia 03 Dec '26

03 Dec '26
falconia has submitted this change. ( https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email ) Change subject: gsm: new struct and en/decoding functions for BC-IE ...................................................................... gsm: new struct and en/decoding functions for BC-IE Legacy struct gsm_mncc_bearer_cap is unable to represent 14.4 kbit/s mode of CSD, which is now supported by Osmocom BSS, and even for the mandatory set of BC-IE octets for all data modes, it lacks some of the bits. Introduce a new set of structures to serve as a replacement, as well as new encoding and decoding functions using the new structs. These new structures and functions were originally developed by American 2G Cooperative as part of Hera MSC back end, interfacing to OsmoMSC via the proposed MNCC raw mode and doing our own encoding and decoding of GSM 04.08 CC messages. The present patch is a small step toward making these ThemWi functional improvements available in pure Osmocom, in addition to Osmocom+ThemWi hybrid. The structures and functions have also been extended to be usable on the mobile side of GSM, in addition to the network side. Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 --- M TODO-RELEASE M include/osmocom/gsm/gsm48_ie.h M src/gsm/gsm48_ie.c M src/gsm/libosmogsm.map 4 files changed, 678 insertions(+), 4 deletions(-) Approvals: fixeria: Looks good to me, but someone else must approve Jenkins Builder: Verified pespin: Looks good to me, approved diff --git a/TODO-RELEASE b/TODO-RELEASE index 5f1904b..ac30d0a 100644 --- a/TODO-RELEASE +++ b/TODO-RELEASE @@ -10,3 +10,4 @@ vty added VTY node for libsosmo-sigtran L_CS7_QOS_CLASS_NODE vty added VTY nodes for libosmo-octoi L_OCTOI_SRV_NODE, L_OCTOI_ACCOUNT_NODE, L_OCTOI_CLNT_NODE, L_OCTOI_CLNT_ACCOUNT_NODE core added osmo_sockaddr_pton() +gsm added osmo_gsm48_decode_bcap(), osmo_gsm48_encode_bcap(), osmo_gsm48_bcap_apply_ms_rules() diff --git a/include/osmocom/gsm/gsm48_ie.h b/include/osmocom/gsm/gsm48_ie.h index 4768283..0f006eb 100644 --- a/include/osmocom/gsm/gsm48_ie.h +++ b/include/osmocom/gsm/gsm48_ie.h @@ -2,16 +2,98 @@ #pragma once +#include <stdbool.h> #include <stdint.h> #include <string.h> #include <errno.h> +#include <osmocom/core/bits.h> #include <osmocom/core/msgb.h> #include <osmocom/core/defs.h> #include <osmocom/gsm/tlv.h> #include <osmocom/gsm/mncc.h> #include <osmocom/gsm/protocol/gsm_04_08.h> +/* The following structures are intended as a replacement for + * legacy struct gsm_mncc_bearer_cap. */ + +/* Versions of 3GPP TS 24.008 that correspond to the final round + * of enhancements to GSM define a total of 9 different GSM speech + * versions - see Table 10.5.103/3GPP TS 24.008. Therefore, + * we should support this many speech versions in our decoded + * BC-IE data structure. */ +#define OSMO_BCAP_MAX_SPEECH_VER 9 + +struct osmo_bcap_speech { + bool ctm; + uint8_t vers[OSMO_BCAP_MAX_SPEECH_VER]; + uint8_t num_vers; +}; + +struct osmo_bcap_data { + /* fields from octet 4 */ + ubit_t compress; + uint8_t structure; + ubit_t duplex; + ubit_t config; + ubit_t nirr; + ubit_t establish; + /* fields from octet 5 */ + uint8_t rate_adaption; + uint8_t sig_access; + /* fields from octet 5a */ + uint8_t other_itc; + uint8_t other_ra; + /* fields from octet 5b */ + uint8_t v120_params; + /* fields from octet 6 */ + uint8_t uil1p; + ubit_t async; + /* fields from octet 6a */ + ubit_t stop_bits_ind; + ubit_t v110_negot; + ubit_t data_bits_ind; + uint8_t user_rate; + /* fields from octet 6b */ + uint8_t interm_rate; + ubit_t nic_tx; + ubit_t nic_rx; + uint8_t parity; + /* fields from octet 6c */ + uint8_t transp; + uint8_t modem_type; + /* fields from octet 6d */ + uint8_t other_modem_type; + uint8_t fnur; + /* fields from octet 6e */ + ubit_t accept_tchf144; + ubit_t accept_tchf96; + ubit_t accept_tchf48; + uint8_t max_tch_minus1; + /* fields from octet 6f */ + uint8_t uimi; + uint8_t waiur; + /* fields from octet 6g */ + ubit_t accept_tch288; + ubit_t accept_tch320; + ubit_t accept_tch432; + uint8_t asymmetry; + /* fields from octet 7 */ + uint8_t uil2p; + bool have_uil2p; +}; + +struct osmo_bearer_cap { + uint8_t itc; + ubit_t tmod; + ubit_t coding; + uint8_t rrq; + union { + struct osmo_bcap_speech speech; + struct osmo_bcap_data data; + }; +}; + /* decode a 'called/calling/connect party BCD number' as in 10.5.4.7 */ int gsm48_decode_bcd_number(char *output, int output_len, const uint8_t *bcd_lv, int h_len) @@ -25,10 +107,17 @@ int h_len, const char *input); /* decode 'bearer capability' */ int gsm48_decode_bearer_cap(struct gsm_mncc_bearer_cap *bcap, - const uint8_t *lv); + const uint8_t *lv) + OSMO_DEPRECATED("Use osmo_gsm48_decode_bcap() instead"); +int osmo_gsm48_decode_bcap(struct osmo_bearer_cap *bc, const uint8_t *ie_val, + uint8_t ie_len, bool for_ms); /* encode 'bearer capability' */ int gsm48_encode_bearer_cap(struct msgb *msg, int lv_only, - const struct gsm_mncc_bearer_cap *bcap); + const struct gsm_mncc_bearer_cap *bcap) + OSMO_DEPRECATED("Use osmo_gsm48_encode_bcap() instead"); +int osmo_gsm48_encode_bcap(struct msgb *msg, bool lv_only, + const struct osmo_bearer_cap *bc, bool for_ms); +int osmo_gsm48_bcap_apply_ms_rules(struct osmo_bearer_cap *bc); /* decode 'call control cap' */ int gsm48_decode_cccap(struct gsm_mncc_cccap *ccap, const uint8_t *lv); /* encode 'call control cap' */ diff --git a/src/gsm/gsm48_ie.c b/src/gsm/gsm48_ie.c index 866e0da..09c0d50 100644 --- a/src/gsm/gsm48_ie.c +++ b/src/gsm/gsm48_ie.c @@ -185,7 +185,7 @@ return (bcd_cur - bcd_lv); } -/*! Decode TS 04.08 Bearer Capability IE (10.5.4.5) +/*! Decode TS 04.08 Bearer Capability IE (10.5.4.5), legacy version. * \param[out] bcap Caller-provided memory for decoded output * \param[in] lv LV portion of TS 04.08 Bearer Capability * \returns 0 on success; negative on error */ @@ -315,7 +315,7 @@ return 0; } -/*! Encode TS 04.08 Bearer Capability IE (10.5.4.5) +/*! Encode TS 04.08 Bearer Capability IE (10.5.4.5), legacy version. * \param[out] msg Message Buffer to which IE is to be appended * \param[in] lv_only Write only LV portion (1) or TLV (0) * \param[in] bcap Decoded Bearer Capability to be encoded @@ -392,6 +392,587 @@ return 0; } +/* Low-level decoding of BC-IE data portion */ + +#define OSMO_BCAP_OCT5_MAX_EXT 2 +#define OSMO_BCAP_OCT6_MAX_EXT 7 + +struct osmo_bcap_data_ll { + uint8_t octet_4; + uint8_t octet_5; + uint8_t octet_5_ext[OSMO_BCAP_OCT5_MAX_EXT]; + uint8_t octet_6; + uint8_t octet_6_ext[OSMO_BCAP_OCT6_MAX_EXT]; + uint8_t octet_7; + uint8_t extent_of_5; + uint8_t extent_of_6; + bool have_octet_7; +}; + +/* Low-level decoding of the complete BC-IE */ + +struct osmo_bcap_ll { + uint8_t itc; + ubit_t tmod; + ubit_t coding; + uint8_t rrq; + union { + struct osmo_bcap_speech speech; + struct osmo_bcap_data_ll data; + }; +}; + +/*! Low-level decode bearer capability IE of 3GPP TS 24.008 section 10.5.4.5. + * \param[out] lld Caller-provided memory for decoded output. + * \param[in] ie_val Value part of the received BC-IE. + * \param[in] ie_len Length of the received BC-IE value part. + * \returns 0 on success; negative on error. + */ +static int decode_bcap_ll(struct osmo_bcap_ll *lld, const uint8_t *ie_val, + uint8_t ie_len) +{ + const uint8_t *cp = ie_val; + const uint8_t *endp = ie_val + ie_len; + + memset(lld, 0, sizeof(struct osmo_bcap_ll)); + if (cp >= endp) /* octet 3 is always mandatory */ + return -EINVAL; + lld->rrq = (*cp & 0x60) >> 5; + lld->coding = (*cp & 0x10) >> 4; + lld->tmod = (*cp & 0x08) >> 3; + lld->itc = *cp & 0x07; + switch (lld->itc) { + case GSM48_BCAP_ITCAP_SPEECH: + while (!(*cp & 0x80)) { + cp++; + if (cp >= endp) + return -EINVAL; + if (*cp & 0x40) /* not a speech version octet */ + continue; + if ((cp == ie_val + 1) && (*cp & 0x20)) + lld->speech.ctm = true; + if (lld->speech.num_vers >= OSMO_BCAP_MAX_SPEECH_VER) + break; + lld->speech.vers[lld->speech.num_vers++] = *cp & 0x0F; + } + break; + case GSM48_BCAP_ITCAP_UNR_DIG_INF: + case GSM48_BCAP_ITCAP_3k1_AUDIO: + case GSM48_BCAP_ITCAP_FAX_G3: + case GSM48_BCAP_ITCAP_OTHER: + /* There are no octets 3a etc for data, but the spec tells us + * to ignore them if received. */ + while (!(*cp & 0x80)) { + cp++; + if (cp >= endp) + return -EINVAL; + } + cp++; + if (cp >= endp) /* octet 4 is mandatory for data */ + return -EINVAL; + if (!(*cp & 0x80)) /* ... and does not allow extension */ + return -EINVAL; + lld->data.octet_4 = *cp++; + if (cp >= endp) /* octet 5 is mandatory too */ + return -EINVAL; + if ((*cp & 0x60) != 0x00) /* verify that it really is octet 5 */ + return -EINVAL; + lld->data.octet_5 = *cp; + while (!(*cp & 0x80)) { + cp++; + if (cp >= endp) + return -EINVAL; + if (lld->data.extent_of_5 >= OSMO_BCAP_OCT5_MAX_EXT) + return -EINVAL; + lld->data.octet_5_ext[lld->data.extent_of_5++] = *cp; + } + cp++; + if (cp >= endp) /* octet 6 is mandatory */ + return -EINVAL; + if ((*cp & 0x60) != 0x20) /* verify that it really is octet 6 */ + return -EINVAL; + lld->data.octet_6 = *cp; + while (!(*cp & 0x80)) { + cp++; + if (cp >= endp) + return -EINVAL; + if (lld->data.extent_of_6 >= OSMO_BCAP_OCT6_MAX_EXT) + return -EINVAL; + lld->data.octet_6_ext[lld->data.extent_of_6++] = *cp; + } + cp++; + if (cp >= endp) /* octet 7 is optional */ + break; + if ((*cp & 0x60) != 0x40) /* verify that it really is octet 7 */ + return -EINVAL; + if (!(*cp & 0x80)) /* it does not allow extension */ + return -EINVAL; + lld->data.have_octet_7 = true; + lld->data.octet_7 = *cp; + break; + default: + return -EOPNOTSUPP; + } + return 0; +} + +/*! Low-level encode bearer capability IE of 3GPP TS 24.008 section 10.5.4.5. + * \param[out] msg Message buffer to which BC-IE is to be appended. + * \param[in] lv_only Write only LV portion (true) or TLV (false). + * \param[in] lld Low-level decoded BC-IE to be encoded. + * \returns 0 on success; negative on error. + */ +static int encode_bcap_ll(struct msgb *msg, bool lv_only, + const struct osmo_bcap_ll *lld) +{ + uint8_t buf[14]; /* max len with all optional octets included */ + uint8_t *cp = buf; + uint8_t octet_3 = 0; + uint8_t n, len, space_needed; + + octet_3 |= lld->rrq << 5; + octet_3 |= lld->coding << 4; + octet_3 |= lld->tmod << 3; + octet_3 |= lld->itc; + switch (lld->itc) { + case GSM48_BCAP_ITCAP_SPEECH: + if (lld->speech.num_vers > OSMO_BCAP_MAX_SPEECH_VER) + return -EINVAL; + for (n = 0; n < lld->speech.num_vers; n++) { + *cp++ = octet_3; + octet_3 = lld->speech.vers[n]; + if (n == 0 && lld->speech.ctm) + octet_3 |= 0x20; + } + octet_3 |= 0x80; + *cp++ = octet_3; + break; + case GSM48_BCAP_ITCAP_UNR_DIG_INF: + case GSM48_BCAP_ITCAP_3k1_AUDIO: + case GSM48_BCAP_ITCAP_FAX_G3: + case GSM48_BCAP_ITCAP_OTHER: + if (lld->data.extent_of_5 > OSMO_BCAP_OCT5_MAX_EXT) + return -EINVAL; + if (lld->data.extent_of_6 > OSMO_BCAP_OCT6_MAX_EXT) + return -EINVAL; + octet_3 |= 0x80; + *cp++ = octet_3; + *cp++ = lld->data.octet_4; + *cp++ = lld->data.octet_5; + for (n = 0; n < lld->data.extent_of_5; n++) + *cp++ = lld->data.octet_5_ext[n]; + *cp++ = lld->data.octet_6; + for (n = 0; n < lld->data.extent_of_6; n++) + *cp++ = lld->data.octet_6_ext[n]; + if (lld->data.have_octet_7) + *cp++ = lld->data.octet_7; + break; + default: + return -EOPNOTSUPP; + } + + len = cp - buf; + space_needed = lv_only ? len + 1 : len + 2; + if (msgb_tailroom(msg) < space_needed) + return -ENOSPC; + if (lv_only) + msgb_lv_put(msg, len, buf); + else + msgb_tlv_put(msg, GSM48_IE_BEARER_CAP, len, buf); + return 0; +} + +static void bcap_speech_dec_phase1_logic(struct osmo_bearer_cap *bc) +{ + switch (bc->rrq) { + case GSM48_BCAP_RRQ_FR_ONLY: + bc->speech.vers[0] = GSM48_BCAP_SV_FR; + bc->speech.num_vers = 1; + break; + case GSM48_BCAP_RRQ_DUAL_HR: + bc->speech.vers[0] = GSM48_BCAP_SV_HR; + bc->speech.vers[1] = GSM48_BCAP_SV_FR; + bc->speech.num_vers = 2; + break; + case GSM48_BCAP_RRQ_DUAL_FR: + bc->speech.vers[0] = GSM48_BCAP_SV_FR; + bc->speech.vers[1] = GSM48_BCAP_SV_HR; + bc->speech.num_vers = 2; + break; + } +} + +static void bcap_hl_decode_data(struct osmo_bcap_data *hld, + const struct osmo_bcap_data_ll *lld) +{ + /* fields from octet 4 */ + hld->compress = (lld->octet_4 & 0x40) >> 6; + hld->structure = (lld->octet_4 & 0x30) >> 4; + hld->duplex = (lld->octet_4 & 0x08) >> 3; + hld->config = (lld->octet_4 & 0x04) >> 2; + hld->nirr = (lld->octet_4 & 0x02) >> 1; + hld->establish = lld->octet_4 & 0x01; + /* fields from octet 5 */ + hld->rate_adaption = (lld->octet_5 & 0x18) >> 3; + hld->sig_access = lld->octet_5 & 0x07; + /* fields from octet 5a */ + if (lld->extent_of_5 >= 1) { + hld->other_itc = (lld->octet_5_ext[0] & 0x60) >> 5; + hld->other_ra = (lld->octet_5_ext[0] & 0x18) >> 3; + } + /* fields from octet 5b */ + if (lld->extent_of_5 >= 2) + hld->v120_params = lld->octet_5_ext[1] & 0x7F; + /* fields from octet 6 */ + hld->uil1p = (lld->octet_6 & 0x1E) >> 1; + hld->async = lld->octet_6 & 0x01; + /* fields from octet 6a */ + hld->stop_bits_ind = (lld->octet_6_ext[0] & 0x40) >> 6; + hld->v110_negot = (lld->octet_6_ext[0] & 0x20) >> 5; + hld->data_bits_ind = (lld->octet_6_ext[0] & 0x10) >> 4; + hld->user_rate = lld->octet_6_ext[0] & 0x0F; + /* fields from octet 6b */ + hld->interm_rate = (lld->octet_6_ext[1] & 0x60) >> 5; + hld->nic_tx = (lld->octet_6_ext[1] & 0x10) >> 4; + hld->nic_rx = (lld->octet_6_ext[1] & 0x08) >> 3; + hld->parity = lld->octet_6_ext[1] & 0x07; + /* fields from octet 6c */ + hld->transp = (lld->octet_6_ext[2] & 0x60) >> 5; + hld->modem_type = lld->octet_6_ext[2] & 0x1F; + /* fields from octet 6d */ + if (lld->extent_of_6 >= 4) { + hld->other_modem_type = (lld->octet_6_ext[3] & 0x60) >> 5; + hld->fnur = lld->octet_6_ext[3] & 0x1F; + } + /* fields from octet 6e */ + if (lld->extent_of_6 >= 5) { + hld->accept_tchf144 = (lld->octet_6_ext[4] & 0x40) >> 6; + hld->accept_tchf96 = (lld->octet_6_ext[4] & 0x10) >> 4; + hld->accept_tchf48 = (lld->octet_6_ext[4] & 0x08) >> 3; + hld->max_tch_minus1 = lld->octet_6_ext[4] & 0x07; + } + /* fields from octet 6f */ + if (lld->extent_of_6 >= 6) { + hld->uimi = (lld->octet_6_ext[5] & 0x70) >> 4; + hld->waiur = lld->octet_6_ext[5] & 0x0F; + } + /* fields from octet 6g */ + if (lld->extent_of_6 >= 7) { + hld->accept_tch288 = (lld->octet_6_ext[6] & 0x40) >> 6; + hld->accept_tch320 = (lld->octet_6_ext[6] & 0x20) >> 5; + hld->accept_tch432 = (lld->octet_6_ext[6] & 0x10) >> 4; + hld->asymmetry = (lld->octet_6_ext[6] & 0x0C) >> 2; + } + /* fields from octet 7 */ + if (lld->have_octet_7) { + hld->uil2p = lld->octet_7 & 0x1F; + hld->have_uil2p = true; + } +} + +/*! High-level decode bearer capability IE of 3GPP TS 24.008 section 10.5.4.5. + * \param[out] bc Caller-provided memory for decoded output. + * \param[in] ie_val Value part of the received BC-IE. + * \param[in] ie_len Length of the received BC-IE value part. + * \param[in] for_ms True if decoding is done for GSM MS (network to MS + * direction) or false if decoding is done for an MSC (MS to network dir). + * \returns 0 on success; negative on error. + */ +int osmo_gsm48_decode_bcap(struct osmo_bearer_cap *bc, const uint8_t *ie_val, + uint8_t ie_len, bool for_ms) +{ + struct osmo_bcap_ll lld; + int rc; + + memset(bc, 0, sizeof(struct osmo_bearer_cap)); + rc = decode_bcap_ll(&lld, ie_val, ie_len); + if (rc < 0) + return rc; + bc->itc = lld.itc; + bc->tmod = lld.tmod; + bc->coding = lld.coding; + bc->rrq = lld.rrq; + switch (lld.itc) { + case GSM48_BCAP_ITCAP_SPEECH: + /* Table 10.5.103/3GPP TS 24.008, note at the very bottom + * of the table: + * + * Octet(s) 3a etc. network to MS direction + * + * The octet(s) 3a etc. shall be ignored by the MS. + * + * Given this strong "shall" language in the spec, block + * the passage of this speech version list in high-level + * decoding on behalf of MS, to prevent misunderstanding + * errors by downstream developers using this API. + * + * Furthermore if this "artificial suppression" logic + * were removed, bcap_speech_dec_phase1_logic() would get + * called in the normal case when the network sends no + * speech version list, and would give the MS application + * a misleading impression that the network specifically + * requested FRv1. + */ + if (!for_ms) { + if (lld.speech.num_vers != 0) { + memcpy(&bc->speech, &lld.speech, + sizeof(struct osmo_bcap_speech)); + } else { + bcap_speech_dec_phase1_logic(bc); + } + } + break; + case GSM48_BCAP_ITCAP_UNR_DIG_INF: + case GSM48_BCAP_ITCAP_3k1_AUDIO: + case GSM48_BCAP_ITCAP_FAX_G3: + case GSM48_BCAP_ITCAP_OTHER: + /* octets 6a, 6b and 6c are mandatory */ + if (lld.data.extent_of_6 < 3) + return -EINVAL; + bcap_hl_decode_data(&bc->data, &lld.data); + break; + default: + return -EOPNOTSUPP; + } + return 0; +} + +static void bcap_enc_trim_6d_6g(struct osmo_bcap_data_ll *lld, + bool ms_rules_6d_6e) +{ + if (lld->octet_6_ext[6]) { + lld->octet_6_ext[6] |= 0x80; + lld->extent_of_6 = 7; + return; + } + if (lld->octet_6_ext[5]) { + lld->octet_6_ext[5] |= 0x80; + lld->extent_of_6 = 6; + return; + } + if (lld->octet_6_ext[4]) { + lld->octet_6_ext[4] |= 0x80; + lld->extent_of_6 = 5; + return; + } + if (lld->octet_6_ext[3]) { + if (ms_rules_6d_6e) { + lld->octet_6_ext[4] |= 0x80; + lld->extent_of_6 = 5; + } else { + lld->octet_6_ext[3] |= 0x80; + lld->extent_of_6 = 4; + } + return; + } + lld->octet_6_ext[2] |= 0x80; + lld->extent_of_6 = 3; +} + +static void bcap_hl_encode_data(struct osmo_bcap_data_ll *lld, + const struct osmo_bcap_data *hld, + enum gsm48_bcap_itcap itcap, bool for_ms) +{ + lld->octet_4 = 0x80; + lld->octet_4 |= hld->compress << 6; + lld->octet_4 |= hld->structure << 4; + lld->octet_4 |= hld->duplex << 3; + lld->octet_4 |= hld->config << 2; + lld->octet_4 |= hld->nirr << 1; + lld->octet_4 |= hld->establish; + lld->octet_5 = 0; + lld->octet_5 |= hld->rate_adaption << 3; + lld->octet_5 |= hld->sig_access; + if (itcap == GSM48_BCAP_ITCAP_OTHER || + hld->rate_adaption == GSM48_BCAP_RA_OTHER) { + lld->octet_5_ext[0] = 0; + lld->octet_5_ext[0] |= (hld->other_itc) << 5; + lld->octet_5_ext[0] |= (hld->other_ra) << 3; + if (hld->rate_adaption == GSM48_BCAP_RA_OTHER && + hld->other_ra == GSM48_BCAP_OTHER_RA_V120) { + lld->octet_5_ext[1] = 0x80 | hld->v120_params; + lld->extent_of_5 = 2; + } else { + lld->octet_5_ext[0] |= 0x80; + lld->extent_of_5 = 1; + } + } else { + lld->octet_5 |= 0x80; + lld->extent_of_5 = 0; + } + lld->octet_6 = 0x20; + lld->octet_6 |= hld->uil1p << 1; + lld->octet_6 |= hld->async; + lld->octet_6_ext[0] = 0; + lld->octet_6_ext[0] |= hld->stop_bits_ind << 6; + lld->octet_6_ext[0] |= hld->v110_negot << 5; + lld->octet_6_ext[0] |= hld->data_bits_ind << 4; + lld->octet_6_ext[0] |= hld->user_rate; + lld->octet_6_ext[1] = 0; + lld->octet_6_ext[1] |= hld->interm_rate << 5; + lld->octet_6_ext[1] |= hld->nic_tx << 4; + lld->octet_6_ext[1] |= hld->nic_rx << 3; + lld->octet_6_ext[1] |= hld->parity; + lld->octet_6_ext[2] = 0; + lld->octet_6_ext[2] |= hld->transp << 5; + lld->octet_6_ext[2] |= hld->modem_type; + /* Octets 6d through 6g: fill out all of them initially, + * then trim any unused ones. */ + lld->octet_6_ext[3] = 0; + lld->octet_6_ext[3] |= hld->other_modem_type << 5; + lld->octet_6_ext[3] |= hld->fnur; + lld->octet_6_ext[4] = 0; + if (for_ms) { + lld->octet_6_ext[4] |= hld->accept_tchf144 << 6; + lld->octet_6_ext[4] |= hld->accept_tchf96 << 4; + lld->octet_6_ext[4] |= hld->accept_tchf48 << 3; + lld->octet_6_ext[4] |= hld->max_tch_minus1; + } + lld->octet_6_ext[5] = 0; + lld->octet_6_ext[5] |= hld->uimi << 4; + if (for_ms) + lld->octet_6_ext[5] |= hld->waiur; + lld->octet_6_ext[6] = 0; + if (for_ms) { + lld->octet_6_ext[6] |= hld->accept_tch288 << 6; + lld->octet_6_ext[6] |= hld->accept_tch320 << 5; + lld->octet_6_ext[6] |= hld->accept_tch432 << 4; + lld->octet_6_ext[6] |= hld->asymmetry << 2; + } + bcap_enc_trim_6d_6g(lld, for_ms); + if (hld->have_uil2p) { + lld->octet_7 = 0xC0 | hld->uil2p; + lld->have_octet_7 = true; + } else { + lld->have_octet_7 = false; + } +} + +/*! High-level encode bearer capability IE of 3GPP TS 24.008 section 10.5.4.5. + * \param[out] msg Message buffer to which BC-IE is to be appended. + * \param[in] lv_only Write only LV portion (true) or TLV (false). + * \param[in] bc High-level decoded BC-IE to be encoded. + * \param[in] for_ms True if encoding is done for GSM MS (MS to network + * direction) or false if encoding is done for an MSC (network to MS dir). + * \returns 0 on success; negative on error. + */ +int osmo_gsm48_encode_bcap(struct msgb *msg, bool lv_only, + const struct osmo_bearer_cap *bc, bool for_ms) +{ + struct osmo_bcap_ll lld; + + lld.itc = bc->itc; + lld.tmod = bc->tmod; + lld.coding = bc->coding; + if (for_ms) + lld.rrq = bc->rrq; + else + lld.rrq = GSM48_BCAP_RRQ_SPARE_NETWORK_TO_MS; + switch (lld.itc) { + case GSM48_BCAP_ITCAP_SPEECH: + if (for_ms) { + memcpy(&lld.speech, &bc->speech, + sizeof(struct osmo_bcap_speech)); + } else { + memset(&lld.speech, 0, sizeof(struct osmo_bcap_speech)); + } + break; + case GSM48_BCAP_ITCAP_UNR_DIG_INF: + case GSM48_BCAP_ITCAP_3k1_AUDIO: + case GSM48_BCAP_ITCAP_FAX_G3: + case GSM48_BCAP_ITCAP_OTHER: + bcap_hl_encode_data(&lld.data, &bc->data, lld.itc, for_ms); + break; + default: + return -EOPNOTSUPP; + } + return encode_bcap_ll(msg, lv_only, &lld); +} + +/*! Apply rules for MS->network direction to GSM 04.08 bearer capability IE + * prior to encoding. + * \param[in/out] bc High-level decoded BC-IE to be preened. + * \returns 0 on success; negative on error. + * + * If the information transfer capability is anything other than speech, + * this function does nothing. However, if a speech call is to be made, + * the MS implementation calling this API needs to fill out the BC-IE + * structure as follows: + * + * - List all supported GSM speech codecs in the usual part of the struct, + * in whatever order of preference you wish to indicate, but with FRv1 + * always included per GSM spec rules; + * + * - Leave the radio channel requirement field uninitialized. + * + * This function fills out the radio channel req field based on the indicated + * preference-ordered speech version list, and then conditionally deletes + * that speech version list if it includes only FRv1 and HRv1, as called for + * in 3GPP TS 24.008 section 10.5.4.5.1. + * + * A GSM MS application will typically first compose its desired BC-IE + * internally, then call osmo_gsm48_encode_bcap() to encode it. The present + * _optional_ API is intended for the composing stage, not the encoding stage, + * and it is optional in that some developer/research-oriented GSM MS + * may provide ability to intentionally violate these rules for network + * testing, in which case the call to the present function will be skipped. + */ +int osmo_gsm48_bcap_apply_ms_rules(struct osmo_bearer_cap *bc) +{ + int s; + int fr_pos = -1, hr_pos = -1; + bool newer_codecs = false; + + /* preening is needed only for speech calls */ + if (bc->itc != GSM48_BCAP_ITCAP_SPEECH) + return 0; + + /* find FRv1 and HRv1 in the caller-filled speech version list */ + for (s = 0; s < bc->speech.num_vers; s++) { + switch (bc->speech.vers[s]) { + case GSM48_BCAP_SV_FR: + if (fr_pos >= 0) /* duplicates invalid */ + return -EINVAL; + fr_pos = s; + break; + case GSM48_BCAP_SV_HR: + if (hr_pos >= 0) /* duplicates invalid */ + return -EINVAL; + hr_pos = s; + break; + default: + newer_codecs = true; + break; + } + } + /* FRv1 support is mandatory */ + if (fr_pos < 0) + return -EINVAL; + + /* Radio channel req bits are for ancient GSM networks that predate + * the addition of octets 3a etc: they indicate the v1-only subset + * of the full speech version list. */ + if (hr_pos < 0) + bc->rrq = GSM48_BCAP_RRQ_FR_ONLY; + else if (fr_pos < hr_pos) + bc->rrq = GSM48_BCAP_RRQ_DUAL_FR; + else + bc->rrq = GSM48_BCAP_RRQ_DUAL_HR; + + /* TS 24.008 section 10.5.4.5.1 says that octets 3a etc "shall" + * be included only if the MS supports either CTM text telephony + * or at least one newer-than-v1 speech codec. Other GSM MS + * implementations with available source code don't follow this + * stipulation, probably on the reasoning that if the code + * implementation is new enough to know about octets 3a etc, + * then the product it goes into will support at least EFR + * if not AMR - but let's honor the word of the spec + * for brownie points. */ + if (!newer_codecs && !bc->speech.ctm) + bc->speech.num_vers = 0; /* empty list => no octet 3a */ + return 0; +} + /*! Decode TS 04.08 Call Control Capabilities IE (10.5.4.5a) * \param[out] ccap Caller-provided memory for decoded CC capabilities * \param[in] lv Length-Value of IE diff --git a/src/gsm/libosmogsm.map b/src/gsm/libosmogsm.map index 88ee3ae..4c14793 100644 --- a/src/gsm/libosmogsm.map +++ b/src/gsm/libosmogsm.map @@ -436,6 +436,9 @@ gsm48_mi_to_string; gsm48_chan_mode_to_vamos; gsm48_chan_mode_to_non_vamos; +osmo_gsm48_bcap_apply_ms_rules; +osmo_gsm48_decode_bcap; +osmo_gsm48_encode_bcap; osmo_mobile_identity_to_str_buf; osmo_mobile_identity_to_str_c; osmo_mobile_identity_cmp; -- To view, visit https://gerrit.osmocom.org/c/libosmocore/+/44192?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.osmocom.org/settings?usp=email Gerrit-MessageType: merged Gerrit-Project: libosmocore Gerrit-Branch: master Gerrit-Change-Id: Ie864734fe1dfd1587bafddd4248ce69a7e066525 Gerrit-Change-Number: 44192 Gerrit-PatchSet: 7 Gerrit-Owner: falconia <falcon(a)freecalypso.org> Gerrit-Reviewer: Jenkins Builder Gerrit-Reviewer: falconia <falcon(a)freecalypso.org> Gerrit-Reviewer: fixeria <vyanitskiy(a)sysmocom.de> Gerrit-Reviewer: laforge <laforge(a)osmocom.org> Gerrit-Reviewer: pespin <pespin(a)sysmocom.de>
1 0
0 0
  • ← Newer
  • 1
  • ...
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • ...
  • 25
  • Older →

HyperKitty Powered by HyperKitty version 1.3.12.