| 1 | // SPDX-License-Identifier: BSD-2-Clause |
| 2 | /* |
| 3 | * Copyright (C) 2022-2025 Linutronix GmbH |
| 4 | * Author Kurt Kanzenbach <[email protected]> |
| 5 | */ |
| 6 | |
| 7 | #include "tx_time.h" |
| 8 | |
| 9 | #include "config.h" |
| 10 | #include "log.h" |
| 11 | #include "utils.h" |
| 12 | |
| 13 | uint64_t tx_time_get_frame_duration(uint32_t link_speed, size_t frame_length) |
| 14 | { |
| 15 | uint64_t duration_ns; |
| 16 | |
| 17 | /* ((frameLength * 8) / (linkSpeed * 1000000ULL)) * 1000000000ULL */ |
| 18 | duration_ns = (frame_length * 8 * 1000) / link_speed; |
| 19 | |
| 20 | return duration_ns; |
| 21 | } |
| 22 | |
| 23 | uint64_t tx_time_get_frame_tx_time(uint64_t sequence_counter, uint64_t duration, |
| 24 | size_t num_frames_per_cycle, uint64_t tx_time_offset, |
| 25 | const char *traffic_class) |
| 26 | { |
| 27 | const uint64_t cycle_time = app_config.application_base_cycle_time_ns; |
| 28 | uint64_t tx_time, base_time, now_ns, past_cycles; |
| 29 | struct timespec now; |
| 30 | |
| 31 | /* |
| 32 | * Calculate frame transmission time for next cycle. txTimeOffset is used to specify the |
| 33 | * offset within cycle, which has to be aligned with configured Qbv schedule. |
| 34 | * |
| 35 | * BaseTime + TxOffset + |
| 36 | * (sequenceCounter % numFramesPerCycle) * duration |
| 37 | * |
| 38 | * |---------------------------|---------------------------| |
| 39 | * ^BaseTime of n-1 BaseTime of n ^^^^^^ |
| 40 | * |
| 41 | * All calculations are performed in nanoseconds. |
| 42 | */ |
| 43 | |
| 44 | clock_gettime(app_config.application_clock_id, &now); |
| 45 | now_ns = ts_to_ns(&now); |
| 46 | past_cycles = (now_ns - app_config.application_base_start_time_ns) / cycle_time; |
| 47 | base_time = (past_cycles + 1) * cycle_time + app_config.application_base_start_time_ns; |
| 48 | |
| 49 | tx_time = base_time + tx_time_offset + (sequence_counter % num_frames_per_cycle) * duration; |
| 50 | |
| 51 | /* |
| 52 | * TxTime has to be in the future. If not the frame will be dropped by ETF Qdisc. This may |
| 53 | * happen due to delays, preemption and so on. Inform the user accordingly. |
| 54 | */ |
| 55 | if (tx_time <= now_ns) |
| 56 | log_message(LOG_LEVEL_ERROR, "%sTx: TxTime not in future!\n", traffic_class); |
| 57 | |
| 58 | return tx_time; |
| 59 | } |