Add 4 HARD tasks from batch 29: Zephyr ZMS, NuttX TCP retry, eventfd, telnet

Batch 29 commit 97ead2b gave Zephyr ZMS restart records, NuttX TCP retry
closure and Zephyr eventfd lock progress (1 of 3 passed each) and Zephyr
telnet close handoff (0 of 3) as HARD. Each task comes from the commit
Qwen measured, its digest matches, and it is still present at the batch
branch head.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
amos 2026-11-04 22:44:18 +08:00
parent 63bdf4c8bb
commit bfb07834e4
174 changed files with 57756 additions and 0 deletions

View File

@ -1,5 +1,18 @@
# 开发进度
## 2026-11-04 第 29 批再合入 4 道 HARD,main 共 1203 道
- **合入的题**(第 29 批 `97ead2b`):
- Zephyr ZMS 重启记录:3 次过 1 次。
- NuttX TCP 重传关闭:3 次过 1 次。
- Zephyr eventfd 加锁进度:3 次过 1 次。
- Zephyr telnet 关闭交接:3 次都失败。
- 四道的题目指纹与测量一致,并确认仍在批次分支的最新提交里。
- **本组 10 道**:HARD 4、ROUTINE 6,没有需要补测的。
- **累计**:
- 路线 D 已测 154 道,HARD 38、MEDIUM 19。
- 第 29 批 30 道,HARD 7、MEDIUM 2。
## 2026-11-04 第 28 批再合入 3 道 HARD,main 共 1199 道
- **合入的题**(第 28 批 `ca63702`):

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,302 @@
"""Trusted expected-value and block-medium models; candidate code runs only in children."""
from pathlib import Path
from contextlib import ExitStack
import errno
import random
import subprocess
import sys
import tarfile
import tempfile
HERE = Path(__file__).resolve().parent
RNG = random.Random(290015)
CHECKS = 0
def require(condition, message):
global CHECKS
CHECKS += 1
if not condition:
raise AssertionError(message)
def payload(length):
return bytes(RNG.randrange(256) for _ in range(length))
class Case:
def __init__(self, count=3, size=256, explicit=1, block=1):
self.geometry = count, size, explicit, block
self.commands = []
self.expected = []
self.history = {}
self.equal = []
self.add("reset %d %d %d %d" % self.geometry, ("RESET", self.geometry))
self.add("trace 1", "TRACE")
def add(self, command, expected):
self.commands.append(command)
self.expected.append(expected)
def mount(self):
self.add("mount", "MOUNT 0")
def write(self, key, value):
previous = self.history.get(key, [None])[-1]
self.add("write %d %s" % (key, value.hex()),
"WRITE %d %d" % (key, 0 if previous == value else len(value)))
if previous != value:
self.history.setdefault(key, []).append(value)
def delete(self, key, zero=False):
self.add(("zero" if zero else "delete") + " %d" % key,
("ZERO" if zero else "DELETE") + " %d 0" % key)
if self.history.get(key, [None])[-1] is not None:
self.history.setdefault(key, []).append(None)
def read(self, key, length=128, count=0, plain=False):
history = self.history.get(key, [])
value = history[-1-count] if len(history) > count else None
result = -errno.ENOENT if value is None else min(length, len(value)) if plain else len(value)
prefix = "PLAIN %d %d" % (key, result) if plain else "READ %d %d %d" % (key, count, result)
if value is not None and length:
prefix += " " + value[:length].hex()
self.add(("readplain %d %d" % (key, length)) if plain else
("read %d %d %d" % (key, length, count)), prefix)
def snapshot(self, label):
self.add("dump", ("MEDIA", label))
self.add("space", ("SPACE", label))
def same(self, left, right):
self.equal.append((left, right))
def fault(self, kind, offset):
self.add("fault %s %d" % (kind, offset), ("FAULT", (kind, offset)))
def next(self, result=0):
self.add("next", "NEXT %d" % result)
def normal_case(explicit, block):
c = Case(size=512, explicit=explicit, block=block)
c.add("read 19 4 0", "READ 19 0 -13")
c.add("delete 19", "DELETE 19 -13")
c.add("write 19 aa", "WRITE 19 -13")
c.add("next", "NEXT -13")
c.mount()
c.snapshot("empty")
for key in [404, 0, 4000000000, 22, 1048] * 3:
c.delete(key, zero=bool(key % 2))
c.read(key)
c.snapshot("absent")
c.same("empty", "absent")
a, b, other = payload(1), payload(9), payload(8)
c.write(19, a)
c.write(20, other)
c.write(19, b)
c.read(19)
c.read(19, 3)
c.read(19, 0)
c.read(19, 3, plain=True)
c.read(19, 0, plain=True)
c.read(19, 100, 1)
c.read(19, 100, 2)
c.snapshot("written")
c.write(19, b)
c.snapshot("duplicate")
c.same("written", "duplicate")
c.delete(19)
c.read(19)
c.read(20)
c.snapshot("deleted")
c.delete(19, zero=True)
c.snapshot("repeat_delete")
c.same("deleted", "repeat_delete")
c.mount()
c.read(19)
c.read(20)
c.delete(20, zero=True)
c.mount()
c.read(20)
return c
def boundaries_case(block):
c = Case(size=256, block=block)
c.mount()
maximum = payload(176)
c.write(91, maximum)
c.read(91, 200)
c.read(91, 17, plain=True)
c.snapshot("maximum")
c.add("write 92 " + payload(177).hex(), "WRITE 92 -22")
c.snapshot("invalid")
c.same("maximum", "invalid")
c.mount()
c.read(91, 200)
c.delete(91)
c.mount()
c.read(91)
return c
def recovery_case(count, size, explicit, block, completed):
c = Case(count, size, explicit, block)
c.mount()
keys = [103 + count, 203 + count, 303 + count]
c.write(keys[0], payload(9))
c.write(keys[1], payload(8))
c.write(keys[2], payload(1))
for step in range(1, count - 1):
c.next()
c.write(700 + step, payload(8))
if completed:
c.fault("E" if explicit else "W", 0 if explicit else size - 16)
else:
c.fault("W", (count - 1) * size)
c.next(-errno.EIO)
if completed:
# The key/value model records only the calls that have returned success.
c.write(keys[0], payload(17))
c.write(999, payload(8))
c.delete(keys[1], zero=bool(block % 2))
c.mount()
for key in keys + [999] + list(range(701, 700 + count - 1)):
c.read(key)
c.mount()
for key in keys + [999]:
c.read(key, 4, plain=True)
c.write(123456, payload(8))
c.mount()
c.read(123456)
return c
def rotation_case():
c = Case(3, 256, 1, 4)
c.mount()
for key in [1, 2, 3]:
c.write(key, payload(8))
for iteration in range(8):
key = iteration % 3 + 1
if iteration % 3 == 1:
c.delete(key)
else:
c.write(key, payload(8))
c.next()
c.mount()
for key in [1, 2, 3]:
c.read(key)
return c
def observe(executable, case, label):
completed = subprocess.run([str(executable)], input="\n".join(case.commands) + "\n",
text=True, capture_output=True, timeout=15)
require(completed.returncode == 0, label + ": runner failed: " + completed.stderr[-300:])
rows = completed.stdout.splitlines()
cursor, medium, explicit, fault = 0, None, None, None
snapshots, spaces = {}, {}
for raw in rows:
row = raw.strip()
if row.startswith("IO "):
fields = row.split()
require(len(fields) in (5, 6), label + ": malformed raw I/O")
kind, offset, length, rc = fields[1], int(fields[2]), int(fields[3]), int(fields[4])
require(kind in ("W", "E") and medium is not None, label + ": unknown I/O")
require(0 <= offset <= len(medium) and 0 <= length <= len(medium) - offset,
label + ": device boundary")
require(rc in (0, -errno.EIO), label + ": device error value")
if rc:
require(fault == (kind, offset), label + ": unconfigured I/O failure")
fault = None
elif kind == "E":
medium[offset:offset + length] = b"\xff" * length
else:
data = bytes.fromhex(fields[5])
require(len(data) == length, label + ": raw write length")
if explicit:
require(all((old & new) == new for old, new in
zip(medium[offset:offset + length], data)), label + ": NOR write")
medium[offset:offset + length] = data
continue
require(cursor < len(case.expected), label + ": unexpected output " + row[:100])
expected = case.expected[cursor]
cursor += 1
if isinstance(expected, str):
require(row == expected, label + ": got " + row[:140] + "; expected " + expected[:140])
continue
kind, value = expected
if kind == "RESET":
require(row == "RESET", label + ": reset output")
count, size, explicit, block = value
medium = bytearray(b"\xff" * (count * size))
fault = None
elif kind == "FAULT":
require(row == "FAULT", label + ": fault output")
fault = value
elif kind == "MEDIA":
require(row.startswith("MEDIA "), label + ": missing raw medium")
observed = bytes.fromhex(row[6:])
require(observed == bytes(medium), label + ": independent byte-medium model")
snapshots[value] = observed
elif kind == "SPACE":
fields = row.split()
require(len(fields) == 3 and fields[0] == "SPACE", label + ": free-space output")
spaces[value] = tuple(map(int, fields[1:]))
require(cursor == len(case.expected), label + ": missing observations")
for left, right in case.equal:
require(snapshots[left] == snapshots[right], label + ": no-op changed medium " + left)
require(spaces[left] == spaces[right], label + ": no-op consumed space " + left)
def main():
source = (Path(sys.argv[1]) / "subsys/fs/zms/zms.c").read_bytes()
cases = [normal_case(e, b) for e, b in [(1, 1), (1, 4), (1, 16), (0, 4)]]
cases += [boundaries_case(block) for block in [1, 4, 16]]
for complete in [True, False]:
for count, size, explicit, block in [(3, 256, 1, 1), (4, 512, 1, 4),
(3, 512, 1, 16), (3, 512, 0, 4)]:
if not complete or explicit:
cases.append(recovery_case(count, size, explicit, block, complete))
cases.append(rotation_case())
runners = []
with ExitStack() as stack:
for cache in [16, 1]:
temporary = stack.enter_context(tempfile.TemporaryDirectory(prefix="zms-check-"))
work = Path(temporary)
with tarfile.open(HERE / "support.tar", "r") as archive:
for member in archive.getmembers():
require(member.isfile() and not member.name.startswith("/") and
".." not in Path(member.name).parts, "unsafe support archive")
path = work / member.name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(archive.extractfile(member).read())
candidate = work / "subsys/fs/zms/zms.c"
candidate.parent.mkdir(parents=True, exist_ok=True)
candidate.write_bytes(source)
executable = work / "zms-runner"
command = ["gcc", "-std=c11", "-O1", "-Iinclude", "-DCONFIG_ZMS_LOOKUP_CACHE_SIZE=%d" % cache,
"subsys/fs/zms/zms.c", "lib/crc/crc8_sw.c", "lib/crc/crc32_sw.c",
"port.c", "runner.c", "-o", str(executable)]
runners.append((cache, work, executable, command))
# Prepare every configuration before a child can modify candidate-owned scratch.
for cache, work, executable, command in runners:
built = subprocess.run(command, cwd=work, text=True, capture_output=True, timeout=35)
require(built.returncode == 0, "build failed: " + built.stderr[-1500:])
# Candidate execution starts only after all input/support writes and builds finish.
# The parent now consumes captured stdout/stderr and performs no scratch I/O.
for cache, work, executable, command in runners:
for index, case in enumerate(cases):
observe(executable, case, "cache=%d case=%d" % (cache, index))
print("checked %d facts" % CHECKS)
print("PASS")
if __name__ == "__main__":
try:
main()
except (AssertionError, ValueError, KeyError, IndexError, subprocess.TimeoutExpired) as error:
print("FAIL: " + str(error))
sys.exit(1)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
The device configuration service occasionally reverts a saved value or loses a newly added key after a temporary storage error and a reboot. Operators also report that maintenance requests for absent configuration keys can consume the remaining active-sector space. Existing reads and regular updates still work in the normal-path smoke.
Repair the supplied storage service so its behavior meets every clause in `docs/storage-contract.md`. Run `make smoke` for the normal path and `make diagnose` for the recorded reboot diagnostic. The runner accepts additional sequences described in the contract. This is an offline software reproduction using a controlled block device; no board is needed.
Only submit `subsys/fs/zms/zms.c`. The other workspace files provide fixed build support and documentation, and newly added files are not collected.

View File

@ -0,0 +1,117 @@
# fs-zephyr-zms-restart-records
状态:CALIBRATED。难度:UNMEASURED。路线 D,未调用真实 Agent,不标为 ADMITTED。
## 来源与冻结
- 项目:Zephyr,https://github.com/zephyrproject-rtos/zephyr ,split=`zephyrproject-rtos/zephyr`。
- family=`state-machine-timing`;语言 C;候选仅 `subsys/fs/zms/zms.c`。
- 共同冻结提交:`00cc4441aa2313f2cca721b94db9bce86b0af22c`,即第一处修复的直接父提交。
- 修复:`15cbe9fd18e2a319811a3cd877f238543050da18` 与 `aa9123606cd4e891efa01c237ee57037cde23708`。
- source=`oss/zephyrproject-rtos/zephyr@15cbe9fd18e2`。第二处修复的原父提交为 `ff020ec8a0cd7ccbfc44f116f1ed967f264a6f9d`,这里只取其对候选文件的一个生产 hunk,在共同冻结初态直接按原上下文应用,不引入中间改动,也不引入 ff020ec 的作用域修复。
- 已在冻结版本核对 `CONFIG_ZMS_LOOKUP_CACHE` 与 `CONFIG_ZMS_NO_DOUBLE_WRITE` 原本存在。两个提交均只修改本题候选文件,没有新增上游测试需要转换。
独立缺陷:第一处在找到有效完成记录后未保留完成状态,使重启把已完成回收误当作未完成回收。受控擦除错误之后,后续已返回成功的写入/删除可在重启时丢失;这不是仅性能差异。第二处在缓存明确不存在记录时,零长度删除仍进入写记录路径,消耗介质和可用空间。两处有独立 only-one 样例,均能单独失败。
保留完整 ZMS 生产实现、公开 API、ATE 数据格式及真实 CRC8/CRC32。移植层只提供原始字节存储、设备参数、同步调用和故障;不实现键值索引、GC、记录验证、查找缓存或重启恢复。观察 runner 只打印输入命令对应的返回值、字节及原始 I/O。键值/历史模型与介质 bytearray 模型均在父 check 中,所有期望和关系比较也在父进程。
## 许可与文件清单
根 LICENSE 与冻结提交原样一致。上游根目录在本冻结版本不存在 NOTICE,查询 stderr 保存在作者证据目录。ZMS 三个 C/H 文件头均保留 Laczen/BayLibre 版权和 Apache-2.0 SPDX;CRC8 保留 Intel/Nordic/Runtime 版权,CRC32 保留 Workaround GmbH 版权,均为 Apache-2.0。其余 C/H 为本题补全并声明 Apache-2.0。
以下路径相对于 template;全部文件 SHA-256、逐文件版权/许可依据和上游字节相等结论见作者目录 `source-audit.json`。
| 文件 | 冻结或补全及用途 | 许可 |
| --- | --- | --- |
| `LICENSE` | 上游冻结:`LICENSE`,完整保留 | Apache-2.0 |
| `Makefile` | 补全:Offline GCC build plus public smoke/diagnose targets. | Apache-2.0 |
| `README.md` | 补全:Workspace and submitted-file contract. | Apache-2.0 |
| `diagnostic.txt` | 补全:Public input sequence reproducing reboot data loss. | Apache-2.0 |
| `docs/storage-contract.md` | 补全:Public behavior clauses R01-R12, adapted from frozen API/documentation and explicit port contract. | Apache-2.0 |
| `docs/upstream-zms.rst` | 上游冻结:`doc/services/storage/zms/zms.rst`,完整保留 | Apache-2.0 |
| `include/zephyr/device.h` | 补全:Device handle type for memory flash port. | Apache-2.0 |
| `include/zephyr/drivers/flash.h` | 补全:Flash API declarations and parameter structures required by ZMS. | Apache-2.0 |
| `include/zephyr/fs/zms.h` | 上游冻结:`include/zephyr/fs/zms.h`,完整保留 | Apache-2.0 |
| `include/zephyr/kernel.h` | 补全:Single-thread mutex no-ops, bit macros and fixed ZMS Kconfig selection. | Apache-2.0 |
| `include/zephyr/logging/log.h` | 补全:Logging no-ops; no storage behavior. | Apache-2.0 |
| `include/zephyr/sys/crc.h` | 补全:Declarations for the frozen real CRC implementations. | Apache-2.0 |
| `include/zephyr/toolchain.h` | 补全:Compiler packing attributes required by the ATE layout. | Apache-2.0 |
| `lib/crc/crc32_sw.c` | 上游冻结:`lib/crc/crc32_sw.c`,完整保留 | Apache-2.0 |
| `lib/crc/crc8_sw.c` | 上游冻结:`lib/crc/crc8_sw.c`,完整保留 | Apache-2.0 |
| `port.c` | 补全:Raw memory flash, NOR/overwrite semantics and one-shot I/O faults; no keys, GC, cache or recovery. | Apache-2.0 |
| `port.h` | 补全:Raw device state and reset helper declarations. | Apache-2.0 |
| `runner.c` | 补全:Text input decoder and raw API/device observations; no expectations or test verdicts. | Apache-2.0 |
| `smoke.txt` | 补全:Ordinary writes, history and mount; neither target defect triggered. | Apache-2.0 |
| `subsys/fs/zms/zms.c` | 上游冻结:`subsys/fs/zms/zms.c`,完整保留 | Apache-2.0 |
| `subsys/fs/zms/zms_priv.h` | 上游冻结:`subsys/fs/zms/zms_priv.h`,完整保留 | Apache-2.0 |
工作区 21 文件,其中 7 个上游冻结、14 个补全。独有 C/H 共 2378 物理行、2076 非空行;去除注释和空行后 1506 行。只计 template 一份,不计重复 fixture、文档、许可证、评分器或归档重复。候选本体 1805 物理行,其中非空非注释 1221 行。
## 公开依据及检查矩阵
条款以 `template/docs/storage-contract.md` 为准。该文档在普通 API 条款中统一陈述持久性、重复写抑制和错误恢复,不提供修复位置或补丁。它整理自冻结公开头文件、冻结 `doc/services/storage/zms/zms.rst`、冻结 Kconfig 与已明确公开的本地设备/runner 合同。R06 公开说明:设备错误之后的恢复保证针对 R07 所列的一次性故障阶段,其他故障序列不作保证。R07 的后续成功持久性针对源扇区擦除失败,另要求 out-of-line 数据写中断后可重挂载;正常轮转、普通存储和全部当前必需用例不变。
下表路径相对于 template,共 15 条。隐藏的是参数组合而非行为要求。
| 项 | 判据检查项 | 依据 | 覆盖 |
| --- | --- | --- | --- |
| 01 | GCC 离线构建成功;输出行完整、无额外伪造观察 | README.md:5;docs/storage-contract.md:27(R12) | 两种 cache 大小分别构建;observe 检查进程结束及每行命令对应 |
| 02 | 改变值的写入返回长度;最新值、缺失值、多个 32-bit ID | docs/storage-contract.md:5(R01);include/zephyr/fs/zms.h:119、153 | normal_case、recovery_case、rotation_case;父字典模型 |
| 03 | 正常挂载重建及扇区切换后的已成功值和删除保持 | docs/storage-contract.md:7、23(R02、R10) | normal_case、recovery_case、rotation_case;重复 mount 后读取 |
| 04 | 同值重复写返回零,介质与两种空间报告不变 | docs/storage-contract.md:9(R03);include/zephyr/fs/zms.h:121 | normal_case 的 written/duplicate 快照;不比内部调用次数 |
| 05 | 从未存在、重复删除的 ID 返回零,介质与空间不变 | docs/storage-contract.md:9(R03);上游 Kconfig 的 ZMS_NO_DOUBLE_WRITE 约定 | normal_case 的 empty/absent 与 deleted/repeat_delete;cache=16/1 及 ID 碰撞 |
| 06 | 零长度写等价删除;删除不改变其他键 | docs/storage-contract.md:11(R04);include/zephyr/fs/zms.h:111 | normal_case、recovery_case 中 delete/zero 交替 |
| 07 | 历史 count=0/1/2;读取长度为 0、部分及完整时的不同返回值 | docs/storage-contract.md:13(R05);include/zephyr/fs/zms.h:153、170、172 | normal_case 及 boundaries_case;read/readplain 独立期望 |
| 08 | 正常轮转保留活值,不恢复已删除或被替换值 | docs/storage-contract.md:15(R06);docs/upstream-zms.rst:26 | rotation_case 的八轮操作与每轮 mount |
| 09 | 已完成 GC 后源扇区擦除失败,随后成功写/删在重启后仍有效 | docs/storage-contract.md:15、17(R06、R07);docs/upstream-zms.rst:88 | recovery_case(completed=True),3/4 扇区、256/512 bytes、block=1/4/16 |
| 10 | GC 数据复制被一次性写错误中断后可重新挂载并继续存储 | docs/storage-contract.md:15、17、23(R06、R07、R10) | recovery_case(completed=False),含 NOR 与 overwrite 设备 |
| 11 | inline/out-of-line 与实际 CRC 路径、显式擦除/overwrite、不同块宽 | docs/storage-contract.md:19(R08);docs/upstream-zms.rst:143、203 | 1/8/9/17/176-byte 值;真实 ATE/CRC8/CRC32 源码参与构建与挂载读取 |
| 12 | 最大允许长度和超出一字节的拒绝;拒绝不改介质 | docs/storage-contract.md:21(R09);subsys/fs/zms/zms.c:1414 | boundaries_case 中 176/177 bytes;maximum/invalid 快照 |
| 13 | 未挂载 read/write/delete/next 返回 -EACCES | docs/storage-contract.md:21(R09);include/zephyr/fs/zms.h:124、139、177、235 | normal_case 挂载前调用 |
| 14 | 原始介质边界、失败操作不改变介质、NOR 位约束及擦除值 | docs/storage-contract.md:25(R11) | 父 check 按原始 IO 顺序复算 bytearray;dump 与独立介质模型一致 |
| 15 | 命令和 raw IO 结构;受控错误与请求对应 | docs/storage-contract.md:27(R12) | observe 逐行匹配;命令预期和关系只在父进程持有 |
每种 cache 大小各 15 组命令序列:4 组正常行为、3 组长度边界、3 组完成后的擦除错误、4 组中断恢复、1 组多轮旋转;合计 30 组。固定 RNG seed=290015。缓存大小 1 强制冲突;大小 16 覆盖普通路径。没有以内部 marker 值、精确写调用次数或 gold 输出充当期望。介质无副作用来自公开 R03,父进程直接比较完整介质与可用空间;正常写/删期望来自独立 API 模型。
## 样例
| 样例 | 预期 | 行为 |
| --- | --- | --- |
| `gold` | PASS | 共同冻结初态只叠加两个指定上游生产 hunk。 |
| `template` | FAIL | 未修复的上游初态。 |
| `noop` | FAIL | 写入口直接返回输入长度,不执行存储及初始化检查。 |
| `cheat` | FAIL | 假定每次恢复均已完成 GC,掩盖已完成场景而破坏中断恢复。 |
| `cheat_read_grader` | FAIL | 以 gold 为底,读取私有判据成功才运行 gold;拒读返回受控失败。 |
| `only_gc` | FAIL | 只应用 15cbe9f,保留缺失 ID 删除缺陷。 |
| `only_cache` | FAIL | 只应用 aa91236,保留重启恢复缺陷。 |
| `mask_symptom` | FAIL | 仅对公开诊断的 256-byte 扇区承认完成状态,其他几何仍丢值。 |
| `valid_alternative` | PASS | 直接使用有效性结果驱动恢复分支;写入口先独立处理零长度且缓存缺失的短路。 |
只读对照以 gold 为底。正式评分必须拒读而失败;另在无网 Docker 中让 `/grader/check.py` 成为公开非秘密占位文件,真实评分器移至 root 保护的 `/oracle`,同一样例通过。当前评分器的双向检查见 `evidence/auxiliary-round1-01.stdout`,旧检查亦保留。
## Docker 校准与可观察复现
固定镜像:`ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1`。所有编译和执行均在无网容器内,未在宿主执行上游代码。
正式入口:
```sh
python3 -m rollout calibrate tasks/fs-zephyr-zms-restart-records --image ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1 --output runs/20261103-D-oss-fix-29/zephyr-15cbe9f
```
当前完整回执:`runs/20261103-D-oss-fix-29/zephyr-15cbe9f/calibration-5337356f62c246a18e09e56fe9fcd2c1/receipt.json`。9 类各 5 次,gold/valid_alternative 共 10 PASS,其余共 35 FAIL,全部符合预期,整体 PASS、cleanup confirmed、trusted_local=false。恢复时先核对旧回执可复用,随后自审发现 cache=16 候选执行后才准备 cache=1 材料,修正为两套材料提前准备和构建;用例/期望不变,因 grader 指纹变化重新完成本次校准,旧回执保留。通过 `rollout.core._calibration` 核对当前同 task/verifier/image 与每类五次。task digest:`a441468fb8de6403024387a1ceb9120cd4c4ec604e94397a4e32d8c2ecba5887`。
独审返工第 1 轮进一步明确公开 R06 的错误恢复范围,与既有 R07 故障阶段一致;未改候选、原样 gold、其他样例、判据或用例。该公开合同澄清产生新指纹,已重新完成当前完整 45 次校准和可读占位控制,前一轮证据保留于 `round1-before/` 与原运行目录。
`verify.py` 与平台 bos_verify.py 完全一致。私有附件只有 check.py 与 support.tar;tar 常规文件固定 uid/gid=0、mtime=0、mode=0644,check 使用 write_bytes 解包,不继承宿主所有权。候选和编译器由包装器降为 UID/GID 65534,真实 grader 仍受 root 保护。运行后 check 只读取捕获的标准输出/错误,不读取候选临时目录。
公开命令和可读分支的当前完整 argv、stdout、stderr 与清理在 `evidence/auxiliary-round1-01.*`,旧诊断 `evidence/auxiliary-01.*` 与早期行为证明 `evidence/probe-01.*` 均保留。原始观察:template/gold 的 `make smoke` 相同;template 的 `make diagnose` 中两次写返回 4,重启后 key=11 变回 01020304、key=33 缺失;gold 重启后仍为 55667788 与 12345678。GC 缺陷因此有用户可见的数据语义差异。负例失败细节和当前回执摘要见 `calibration-audit.json`。
恢复时按证据中的全部精确容器名逐个只读 inspect,均已不存在;没有新建网络或镜像,未删除其他对象。校准和诊断对象逐个记录并清理,清理事实见 `exact-cleanup-audit.json`。单次评分期限 120 秒。
## 限制和未验证项
- 纯用户态、单线程、同步 memory-flash 复现;未验证 Zephyr native_sim、真实 RTOS 调度、板卡、电气、真实掉电或并发访问。mutex 桩不用于证明并发安全。
- 公共 R07 刻意限定了当前真实修复能保证的错误恢复范围。overwrite 设备上,源扇区 header 写失败后仍继续写入再重启的独立既有问题,template 与指定 gold 均 mount -EIO;其诊断保留于 auxiliary-01,不纳入本题。没有声称两处修复解决全部 I/O 故障。
- 覆盖所列代表几何和边界,不宣称穷举所有 cache/sector/block 组合;不考核 GC 以后所有旧历史仍可读取,不注入 CRC 损坏。
- 未运行真实模型,因此难度 UNMEASURED;父 Agent 负责独立审阅和全库 unittest,本作者只记录本题回执/来源/行为自审。尚未通过真实试采,不标 ADMITTED。

Binary file not shown.

View File

@ -0,0 +1,28 @@
{
"id": "fs-zephyr-zms-restart-records",
"version": "1",
"family": "state-machine-timing",
"source": "oss/zephyrproject-rtos/zephyr@15cbe9fd18e2",
"template": "template",
"verifier": "verify.py",
"candidate_files": [
"subsys/fs/zms/zms.c"
],
"timeout_seconds": 120,
"grader_files": [
"check.py",
"support.tar"
],
"fixtures": {
"gold": "PASS",
"template": "FAIL",
"noop": "FAIL",
"cheat": "FAIL",
"cheat_read_grader": "FAIL",
"only_gc": "FAIL",
"only_cache": "FAIL",
"mask_symptom": "FAIL",
"valid_alternative": "PASS"
},
"split": "zephyrproject-rtos/zephyr"
}

View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,13 @@
CC = gcc
CFLAGS = -std=c11 -O1 -Wall -Wextra -Iinclude
SOURCES = subsys/fs/zms/zms.c lib/crc/crc8_sw.c lib/crc/crc32_sw.c port.c runner.c
all: zms-runner
zms-runner: $(SOURCES)
$(CC) $(CFLAGS) $(SOURCES) -o $@
smoke: zms-runner
./zms-runner smoke.txt
diagnose: zms-runner
./zms-runner diagnostic.txt
clean:
rm -f zms-runner
.PHONY: all clean smoke diagnose

View File

@ -0,0 +1,9 @@
# ZMS storage service slice
This workspace contains the storage implementation, its public header, the native ATE format and CRC routines. A small Linux port supplies a synchronous memory-backed block device. It does not implement keys, ATE lookup, recovery, garbage collection or cache behavior.
Build and run the normal-path smoke with `make smoke`. Run the field diagnostic with `make diagnose`; both commands print observations. `./zms-runner INPUT_FILE` can run another command sequence; without a filename the runner reads stdin. The contract is in `docs/storage-contract.md`; background upstream documentation is in `docs/upstream-zms.rst`.
Only `subsys/fs/zms/zms.c` is collected and graded. Other files provide fixed support and documentation; new files are not collected. The build is offline and uses GCC, make and the C library.
The port enables lookup caching, suppression of duplicate writes and data CRC. Cache size defaults to 16 and can be changed at compile time. Device commands select sector count, sector size, explicit erase capability and write-block size. Reads and writes use the real public ZMS API.

View File

@ -0,0 +1,14 @@
reset 3 256 1 1
mount
write 11 01020304
next
write 22 aabbccddeeff001122334455
fault E 0
next
write 33 12345678
write 11 55667788
read 11 100 0
read 33 100 0
mount
read 11 100 0
read 33 100 0

View File

@ -0,0 +1,27 @@
# Storage service contract
These requirements apply to the public ZMS API in `include/zephyr/fs/zms.h`. They retain its key/value, return-value and flash-error semantics for the supplied offline port.
**R01** A mounted service stores arbitrary 32-bit application IDs other than the reserved header ID and byte strings. A successful changed write returns its input length; reading the ID returns those bytes, and a missing or deleted ID returns `-ENOENT`.
**R02** A successful stored value or deletion remains effective after reconstructing the filesystem object and mounting the same medium. Unrelated keys retain their values across sector rotation and mount.
**R03** With duplicate-write suppression enabled, writing the current bytes again returns zero and leaves storage content and reported available space unchanged. Deleting a missing or already deleted ID also succeeds with zero and leaves storage content and available space unchanged, including when lookup caching is enabled.
**R04** A zero-length write has the same effect as `zms_delete`. Removing an existing key makes it missing; removing one key does not change another key.
**R05** `zms_read_hist` selects the latest stored version at history count zero and earlier stored versions at successive counts while they remain in storage. It returns the stored length and copies up to the requested buffer length. `zms_read` returns the smaller of the stored length and the buffer length. The port does not require history to survive garbage collection.
**R06** The current sector can be closed and rotated through `zms_sector_use_next`. Garbage collection preserves the latest live values. For the one-shot device-error phases described in R07, mounting recovers completed or interrupted operations without reviving deleted or superseded values; recovery after other fault sequences is outside this contract.
**R07** A device error is reported as a negative I/O error. After a transient source-sector erase error during rotation has cleared, later API calls that return success have the ordinary storage semantics in R01–R06, including persistence after a later mount. The service does not require abandoning or clearing the mounted object after that error. A rotation interrupted by a failed out-of-line data write can be recovered by mounting the same medium.
**R08** The storage supports devices requiring explicit erase and devices allowing overwrite. Header/ATE records use CRC8, out-of-line values use CRC32, and values of one through eight bytes are stored inline. Sector count is at least two; write-block sizes in this workspace are powers of two from one through sixteen.
**R09** A write longer than `sector_size - 5 * ate_size` is rejected with `-EINVAL`. Rejected input does not change the medium. Unmounted reads, writes, deletes and rotations report `-EACCES`.
**R10** A mount on supported geometry succeeds after a clean reset or a recoverable interrupted operation. Repeated mounts preserve the latest values, and a mounted service can continue storing values and rotating sectors.
**R11** The supplied block-device port stores raw bytes. A successful explicit erase sets the addressed sector bytes to `ff`; a NOR write can only change bits from one to zero; an overwrite-capable device replaces bytes. A configured one-shot fault rejects the matching operation with `-EIO` without changing its addressed bytes and then clears itself. Subsequent device operations proceed normally.
**R12** The observation runner accepts `reset COUNT SIZE EXPLICIT_ERASE BLOCK_SIZE`, `mount`, `write ID HEX_BYTES`, `delete ID`, `zero ID`, `read ID BUFFER_LENGTH HISTORY_COUNT`, `readplain ID BUFFER_LENGTH`, `next`, `space`, `fault TYPE BYTE_OFFSET`, `trace ENABLED`, and `dump`. `reset` clears the medium and the filesystem object; `mount` reconstructs the object over the existing medium. Fault types are `R`, `W`, and `E`. Observations report API return values and returned bytes. With tracing enabled, `IO W OFFSET LENGTH RC HEX_BYTES` and `IO E OFFSET LENGTH RC` report device requests in execution order. `MEDIA` reports the raw medium bytes; no runner result is a test verdict.

View File

@ -0,0 +1,446 @@
.. _zms_api:
Zephyr Memory Storage (ZMS)
###########################
Zephyr Memory Storage is a new key-value storage system that is designed to work with all types
of non-volatile storage technologies. It supports classical on-chip NOR flash as well as new
technologies like RRAM and MRAM that do not require a separate erase operation at all, that is,
data on these types of devices can be overwritten directly at any time.
General behavior
****************
ZMS divides the memory space into sectors (minimum 2), and each sector is filled with key-value
pairs until it is full.
The key-value pair is divided into two parts:
- The key part is written in an ATE (Allocation Table Entry) called "ID-ATE" which is stored
starting from the bottom of the sector.
- The value part is defined as "data" and is stored raw starting from the top of the sector.
Additionally, for each sector we store at the last positions header ATEs which are ATEs that
are needed for the sector to describe its status (closed, open) and the current version of ZMS.
When the current sector is full we verify first that the following sector is empty, we garbage
collect the sector N+2 (where N is the current sector number) by moving the valid ATEs to the
N+1 empty sector, we erase the garbage-collected sector and then we close the current sector by
writing a garbage_collect_done ATE and the close ATE (one of the header entries).
Afterwards we move forward to the next sector and start writing entries again.
This behavior is repeated until it reaches the end of the partition. Then it starts again from
the first sector after garbage collecting it and erasing its content.
Composition of a sector
=======================
A sector is organized in this form (example with 3 sectors):
.. list-table::
:widths: 25 25 25
:header-rows: 1
* - Sector 0 (closed)
- Sector 1 (open)
- Sector 2 (empty)
* - Data_a0
- Data_b0
- Data_c0
* - Data_a1
- Data_b1
- Data_c1
* - Data_a2
- Data_b2
- Data_c2
* - GC_done
- .
- .
* - .
- .
- .
* - .
- .
- .
* - .
- ID ATE_b2
- ID ATE_c2
* - ID ATE_a2
- ID ATE_b1
- ID ATE_c1
* - ID ATE_a1
- ID ATE_b0
- ID ATE_c0
* - ID ATE_a0
- GC_done ATE
- GC_done ATE
* - Close ATE (cyc=1)
- Close ATE (cyc=1)
- Close ATE (cyc=1)
* - Empty ATE (cyc=1)
- Empty ATE (cyc=2)
- Empty ATE (cyc=2)
Definition of each element in the sector
========================================
``Empty ATE`` is written when erasing a sector (last position of the sector).
``Close ATE`` is written when closing a sector (second to last position of the sector).
``GC_done ATE`` is written to indicate that the next sector has already been garbage-collected.
This ATE could be at any position of the sector.
``ID ATE`` are entries that contain a 32-bit key and describe where the data is stored, its
size and its CRC32.
``Data`` is the actual value associated to the ID-ATE.
How does ZMS work?
******************
Mounting the storage system
===========================
Mounting the storage system starts by getting the flash parameters, checking that the file system
properties are correct (sector_size, sector_count ...) then calling the zms_init function to
make the storage ready.
To mount the filesystem the following elements in the ``zms_fs`` structure must be initialized:
.. code-block:: c
struct zms_fs {
/** File system offset in flash **/
off_t offset;
/** Storage system is split into sectors, each sector size must be multiple of
* erase-blocks if the device has erase capabilities
*/
uint32_t sector_size;
/** Number of sectors in the file system */
uint32_t sector_count;
/** Flash device runtime structure */
const struct device *flash_device;
};
Initialization
==============
As ZMS has a fast-forward write mechanism, it must find the last sector and the last pointer of
the entry where it stopped the last time.
It must look for a closed sector followed by an open one, then within the open sector, it finds
(recovers) the last written ATE.
After that, it checks that the sector after this one is empty, or it will erase it.
ZMS ID/data write
===================
To avoid rewriting the same data with the same ID again, ZMS must look in all the sectors if the
same ID exists and then compares its data. If the data is identical, no write is performed.
If it must perform a write, then an ATE and the data (if the operation is not a delete) are written
in the sector.
If the sector is full (cannot hold the current data + ATE), ZMS has to move to the next sector,
garbage collect the sector after the newly opened one then erase it.
Data whose size is smaller or equal to 8 bytes are written within the ATE.
ZMS ID/data read (with history)
===============================
By default ZMS looks for the last data with the same ID by browsing through all stored ATEs from
the most recent ones to the oldest ones. If it finds a valid ATE with a matching ID it retrieves
its data and returns the number of bytes that were read.
If a history count is provided and different than 0, older data with same ID is retrieved.
ZMS free space calculation
==========================
ZMS can also return the free space remaining in the partition.
However, this operation is very time-consuming as it needs to browse through all valid ATEs
in all sectors of the partition and for each valid ATE try to find if an older one exists.
It is not recommended for applications to use this function often, as it is time-consuming and
could slow down the calling thread.
The cycle counter
=================
Each sector has a lead cycle counter which is a ``uin8_t`` that is used to validate all the other
ATEs.
The lead cycle counter is stored in the empty ATE.
To become valid, an ATE must have the same cycle counter as the one stored in the empty ATE.
Each time an ATE is moved from a sector to another it must get the cycle counter of the
destination sector.
To erase a sector, the cycle counter of the empty ATE is incremented and a single write of the
empty ATE is done.
All the ATEs in that sector become invalid.
Closing sectors
===============
To close a sector a close ATE is added at the end of the sector and it must have the same cycle
counter as the empty ATE.
When closing a sector, all the remaining space that has not been used is filled with garbage data
to avoid having old ATEs with a valid cycle counter.
Triggering garbage collection
=============================
Some applications need to make sure that storage writes have a maximum defined latency.
When calling ZMS to make a write, the current sector could be almost full such that ZMS needs to
trigger the GC to switch to the next sector.
This operation is time-consuming and will cause some applications to not meet their real time
constraints.
ZMS adds an API for the application to get the current remaining free space in a sector.
The application could then decide when to switch to the next sector if the current one is almost
full. This will of course trigger the garbage collection operation on the next sector.
This will guarantee the application that the next write won't trigger the garbage collection.
ATE (Allocation Table Entry) structure
======================================
An entry has 16 bytes divided between these fields:
See the :c:struct:`zms_ate` structure.
.. note:: The CRC of the data is checked only when a full read of the data is made.
The CRC of the data is not checked for a partial read, as it is computed for the whole element.
.. warning:: Enabling the CRC feature on previously existing ZMS content that did not have it
enabled will make all existing data invalid.
Available space for user data (key-value pairs)
***********************************************
ZMS always needs an empty sector to be able to perform the garbage collection (GC).
So, if we suppose that 4 sectors exist in a partition, ZMS will only use 3 sectors to store
key-value pairs and keep one sector empty to be able to perform GC.
The empty sector will rotate between the 4 sectors in the partition.
.. note:: The maximum single data length that can be written at once in a sector is 64K
(this could change in future versions of ZMS).
Small data values
=================
Values smaller than or equal to 8 bytes will be stored within the entry (ATE) itself, without
writing data at the top of the sector.
ZMS has an entry size of 16 bytes which means that the maximum available space in a partition to
store data is computed in this scenario as:
.. math::
\small\frac{(NUM\_SECTORS - 1) \times (SECTOR\_SIZE - (5 \times ATE\_SIZE)) \times (DATA\_SIZE)}{ATE\_SIZE}
Where:
``NUM_SECTOR``: Total number of sectors
``SECTOR_SIZE``: Size of the sector
``ATE_SIZE``: 16 bytes
``(5 * ATE_SIZE)``: Reserved ATEs for header and delete items
``DATA_SIZE``: Size of the small data values (range from 1 to 8)
For example for 4 sectors of 1024 bytes, free space for 8-byte length data is :math:`\frac{3 \times 944 \times 8}{16} = 1416 \, \text{ bytes}`.
Large data values
=================
Large data values ( > 8 bytes) are stored separately at the top of the sector.
In this case, it is hard to estimate the free available space, as this depends on the size of
the data. But we can take into account that for N bytes of data (N > 8 bytes) an additional
16 bytes of ATE must be added at the bottom of the sector.
Let's take an example:
For a partition that has 4 sectors of 1024 bytes and for data size of 64 bytes.
Only 3 sectors are available for writes with a capacity of 944 bytes each.
Each key-value pair needs an extra 16 bytes for the ATE, which makes it possible to store 11 pairs
in each sector (:math:`\frac{944}{80}`).
Total data that could be stored in this partition for this case is :math:`11 \times 3 \times 64 = 2112 \text{ bytes}`.
Wear leveling
*************
This storage system is optimized for devices that do not require an erase.
Storage systems that rely on an erase value (NVS as an example) need to emulate the erase with
write operations. This causes a significant decrease in the life expectancy of these devices
as well as more delays for write operations and initialization of the device when it is empty.
ZMS uses a cycle count mechanism that avoids emulating erase operations for these devices.
It also guarantees that every memory location is written only once for each cycle of sector write.
As an example, to erase a 4096-byte sector on devices that do not require an erase operation
using NVS, 256 flash writes must be performed (supposing that ``write-block-size`` = 16 bytes), while
using ZMS, only 1 write of 16 bytes is needed. This operation is 256 times faster in this case.
The garbage collection operation also reduces the memory cell life expectancy as it performs write
operations when moving blocks from one sector to another.
To make the garbage collector not affect the life expectancy of the device it is recommended
to dimension the partition appropriately. Its size should be the double of the maximum size of
data (including headers) that could be written in the storage.
See `Available space for user data <#available-space-for-user-data-key-value-pairs>`_.
Device lifetime calculation
===========================
Storage devices, whether they are classical flash or new technologies like RRAM/MRAM, have a
limited life expectancy which is determined by the number of times memory cells can be
erased/written.
Flash devices are erased one page at a time as part of their functional behavior (otherwise
memory cells cannot be overwritten), and for storage devices that do not require an erase
operation, memory cells can be overwritten directly.
A typical scenario is shown here to calculate the life expectancy of a device:
Let's suppose that we store an 8-byte variable using the same ID but its content changes every
minute. The partition has 4 sectors with 1024 bytes each.
Each write of the variable requires 16 bytes of storage.
As we have 944 bytes available for ATEs for each sector, and because ZMS is a fast-forward
storage system, we are going to rewrite the first location of the first sector after
:math:`\frac{(944 \times 4)}{16} = 236 \text{ minutes}`.
In addition to the normal writes, the garbage collector will move the data that is still valid
from old sectors to new ones.
As we are using the same ID and a big partition size, no data will be moved by the garbage
collector in this case.
For storage devices that can be written 20 000 times, the storage will last about
4 720 000 minutes (~9 years).
To make a more general formula we must first compute the effective used size in ZMS by our
typical set of data.
For ID/data pairs with data <= 8 bytes, ``effective_size`` is 16 bytes.
For ID/data pairs with data > 8 bytes, ``effective_size`` is ``16 + sizeof(data)`` bytes.
Let's suppose that ``total_effective_size`` is the total size of the data that is written in
the storage and that the partition is sized appropriately (double of the effective size) to avoid
having the garbage collector moving blocks all the time.
The expected lifetime of the device in minutes is computed as:
.. math::
\small\frac{(SECTOR\_EFFECTIVE\_SIZE \times SECTOR\_NUMBER \times MAX\_NUM\_WRITES)}{(TOTAL\_EFFECTIVE\_SIZE \times WR\_MIN)}
Where:
``SECTOR_EFFECTIVE_SIZE``: The sector size - header size (80 bytes)
``SECTOR_NUMBER``: The number of sectors
``MAX_NUM_WRITES``: The life expectancy of the storage device in number of writes
``TOTAL_EFFECTIVE_SIZE``: Total effective size of the set of written data
``WR_MIN``: Number of writes of the set of data per minute
Features
********
ZMS has introduced many features compared to existing storage system like NVS and will evolve
from its initial version to include more features that satisfies new technologies requirements
such as low latency and bigger storage space.
Existing features
=================
Version 1
---------
- Supports storage devices that do not require an erase operation (only one write operation
to invalidate a sector)
- Supports large partition and sector sizes (64-bit address space)
- Supports 32-bit IDs
- Small-sized data (<= 8 bytes) are stored in the ATE itself
- Built-in data CRC32 (included in the ATE)
- Versioning of ZMS (to handle future evolutions)
- Supports large ``write-block-size`` (only for platforms that need it)
Future features
===============
- Add multiple format ATE support to be able to use ZMS with different ATE formats that satisfies
requirements from application
- Add the possibility to skip garbage collector for some application usage where ID/value pairs
are written periodically and do not exceed half of the partition size (there is always an old
entry with the same ID).
- Divide IDs into namespaces and allocate IDs on demand from application to handle collisions
between IDs used by different subsystems or samples.
- Add the possibility to retrieve the wear out value of the device based on the cycle count value
- Add a recovery function that can recover a storage partition if something went wrong
- Add a library/application to allow migration from NVS entries to ZMS entries
- Add the possibility to force formatting the storage partition to the ZMS format if something
went wrong when mounting the storage.
ZMS and other storage systems in Zephyr
=======================================
This section describes ZMS in the wider context of storage systems in Zephyr (not full filesystems,
but simpler, non-hierarchical ones).
Today Zephyr includes at least two other systems that are somewhat comparable in scope and
functionality: :ref:`NVS <nvs_api>` and :ref:`FCB <fcb_api>`.
Which one to use in your application will depend on your needs and the hardware you are using,
and this section provides information to help make a choice.
- If you are using devices that do not require an erase operation like RRAM or MRAM, :ref:`ZMS <zms_api>` is definitely the
best fit for your storage subsystem as it is designed to avoid emulating erase operation using
large block writes for these devices and replaces it with a single write call.
- For devices that have a large ``write_block_size`` and/or need a sector size that is different than the
classical flash page size (equal to erase_block_size), :ref:`ZMS <zms_api>` is also the best fit as there is
the possibility to customize these parameters and add the support of these devices in ZMS.
- For classical flash technology devices, :ref:`NVS <nvs_api>` is recommended as it has low footprint (smaller
ATEs and smaller header ATEs). Erasing flash in NVS is also very fast and do not require an
additional write operation compared to ZMS.
For these devices, NVS reads/writes will be faster as well than ZMS as it has smaller ATE size.
- If your application needs more than 64K IDs for storage, :ref:`ZMS <zms_api>` is recommended here as it
has a 32-bit ID field.
- If your application is working in a FIFO mode (First-in First-out) then :ref:`FCB <fcb_api>` is
the best storage solution for this use case.
More generally to make the right choice between NVS and ZMS, all the blockers should be first
verified to make sure that the application could work with one subsystem or the other, then if
both solutions could be implemented, the best choice should be based on the calculations of the
life expectancy of the device described in this section: `Wear leveling <#wear-leveling>`_.
Recommendations to increase performance
***************************************
Sector size and count
=====================
- The total size of the storage partition should be set appropriately to achieve the best
performance with ZMS.
All the information regarding the effectively available free space in ZMS can be found
in the documentation. See `Available space for user data <#available-space-for-user-data-key-value-pairs>`_.
It's recommended to choose a storage partition size that is double the size of the key-value pairs
that will be written in the storage.
- The sector size needs to be set such that a sector can fit the maximum data size that will be
stored.
Increasing the sector size will slow down the garbage collection operation and make it occur
less frequently.
Decreasing its size, on the opposite, will make the garbage collection operation faster but also
occur more frequently.
- For some subsystems like :ref:`Settings <settings_api>`, all path-value pairs are split into two ZMS entries (ATEs).
The headers needed by the two entries should be accounted for when computing the needed storage
space.
- Storing small data (<= 8 bytes) in ZMS entries can increase the performance, as this data is
written within the entry.
For example, for the :ref:`Settings <settings_api>` subsystem, choosing a path name that is
less than or equal to 8 bytes can make reads and writes faster.
Cache size
==========
- When using the ZMS API directly, the recommendation for the cache size is to make it at least
equal to the number of different entries that will be written in the storage.
- Each additional cache entry will add 8 bytes to your RAM usage. Cache size should be carefully
chosen.
- If you use ZMS through :ref:`Settings <settings_api>`, you have to take into account that each Settings entry is
divided into two ZMS entries. The recommendation for the cache size is to make it at least
twice the number of Settings entries.
API Reference
*************
The ZMS API is provided by ``zms.h``:
.. doxygengroup:: zms_data_structures
.. doxygengroup:: zms_high_level_api
.. comment
not documenting .. doxygengroup:: zms

View File

@ -0,0 +1,5 @@
/* SPDX-License-Identifier: Apache-2.0 */
#ifndef PORT_DEVICE_H
#define PORT_DEVICE_H
struct device { int unused; };
#endif

View File

@ -0,0 +1,17 @@
/* SPDX-License-Identifier: Apache-2.0 */
#ifndef PORT_FLASH_H
#define PORT_FLASH_H
#include <sys/types.h>
#include <stddef.h>
#include <stdint.h>
#include <zephyr/device.h>
#define FLASH_ERASE_C_EXPLICIT 1
struct flash_parameters { size_t write_block_size; uint8_t erase_value; int erase_cap; };
struct flash_pages_info { off_t start_offset; size_t size; };
const struct flash_parameters *flash_get_parameters(const struct device *);
int flash_params_get_erase_cap(const struct flash_parameters *);
int flash_get_page_info_by_offs(const struct device *,off_t,struct flash_pages_info *);
int flash_read(const struct device *,off_t,void *,size_t);
int flash_write(const struct device *,off_t,const void *,size_t);
int flash_erase(const struct device *,off_t,size_t);
#endif

View File

@ -0,0 +1,248 @@
/* Copyright (c) 2018 Laczen
* Copyright (c) 2024 BayLibre SAS
*
* SPDX-License-Identifier: Apache-2.0
*
* ZMS: Zephyr Memory Storage
*/
#ifndef ZEPHYR_INCLUDE_FS_ZMS_H_
#define ZEPHYR_INCLUDE_FS_ZMS_H_
#include <sys/types.h>
#include <zephyr/drivers/flash.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/toolchain.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup zms Zephyr Memory Storage (ZMS)
* @ingroup file_system_storage
* @{
* @}
*/
/**
* @defgroup zms_data_structures ZMS data structures
* @ingroup zms
* @{
*/
/** Zephyr Memory Storage file system structure */
struct zms_fs {
/** File system offset in flash */
off_t offset;
/** Allocation Table Entry (ATE) write address.
* Addresses are stored as `uint64_t`:
* - high 4 bytes correspond to the sector
* - low 4 bytes are the offset in the sector
*/
uint64_t ate_wra;
/** Data write address */
uint64_t data_wra;
/** Storage system is split into sectors. The sector size must be a multiple of
* `erase-block-size` if the device has erase capabilities
*/
uint32_t sector_size;
/** Number of sectors in the file system */
uint32_t sector_count;
/** Current cycle counter of the active sector (pointed to by `ate_wra`) */
uint8_t sector_cycle;
/** Flag indicating if the file system is initialized */
bool ready;
/** Mutex used to lock flash writes */
struct k_mutex zms_lock;
/** Flash device runtime structure */
const struct device *flash_device;
/** Flash memory parameters structure */
const struct flash_parameters *flash_parameters;
/** Size of an Allocation Table Entry */
size_t ate_size;
#if CONFIG_ZMS_LOOKUP_CACHE
/** Lookup table used to cache ATE addresses of written IDs */
uint64_t lookup_cache[CONFIG_ZMS_LOOKUP_CACHE_SIZE];
#endif
};
/**
* @}
*/
/**
* @defgroup zms_high_level_api ZMS API
* @ingroup zms
* @{
*/
/**
* @brief Mount a ZMS file system onto the device specified in `fs`.
*
* @param fs Pointer to the file system.
*
* @retval 0 on success.
* @retval -ENOTSUP if the detected file system is not ZMS.
* @retval -EPROTONOSUPPORT if the ZMS version is not supported.
* @retval -EINVAL if any of the flash parameters or the sector layout is invalid.
* @retval -ENXIO if there is a device error.
* @retval -EIO if there is a memory read/write error.
*/
int zms_mount(struct zms_fs *fs);
/**
* @brief Clear the ZMS file system from device. The ZMS file system must be re-mounted after this
* operation.
*
* @param fs Pointer to the file system.
*
* @retval 0 on success.
* @retval -EACCES if `fs` is not mounted.
* @retval -ENXIO if there is a device error.
* @retval -EIO if there is a memory read/write error.
*/
int zms_clear(struct zms_fs *fs);
/**
* @brief Write an entry to the file system.
*
* @note When the `len` parameter is equal to `0` the entry is effectively removed (it is
* equivalent to calling @ref zms_delete()). It is not possible to distinguish between a deleted
* entry and an entry with data of length 0.
*
* @param fs Pointer to the file system.
* @param id ID of the entry to be written.
* @param data Pointer to the data to be written.
* @param len Number of bytes to be written (maximum 64 KiB).
*
* @return Number of bytes written. On success, it will be equal to the number of bytes requested
* to be written or 0.
* When a rewrite of the same data already stored is attempted, nothing is written to flash,
* thus 0 is returned. On error, returns negative value of error codes defined in `errno.h`.
* @retval Number of bytes written (`len` or 0) on success.
* @retval -EACCES if ZMS is still not initialized.
* @retval -ENXIO if there is a device error.
* @retval -EIO if there is a memory read/write error.
* @retval -EINVAL if `len` is invalid.
* @retval -ENOSPC if no space is left on the device.
*/
ssize_t zms_write(struct zms_fs *fs, uint32_t id, const void *data, size_t len);
/**
* @brief Delete an entry from the file system
*
* @param fs Pointer to the file system.
* @param id ID of the entry to be deleted.
*
* @retval 0 on success.
* @retval -EACCES if ZMS is still not initialized.
* @retval -ENXIO if there is a device error.
* @retval -EIO if there is a memory read/write error.
*/
int zms_delete(struct zms_fs *fs, uint32_t id);
/**
* @brief Read an entry from the file system.
*
* @param fs Pointer to the file system.
* @param id ID of the entry to be read.
* @param data Pointer to data buffer.
* @param len Number of bytes to read at most.
*
* @return Number of bytes read. On success, it will be equal to the number of bytes requested
* to be read or less than that if the stored data has a smaller size than the requested one.
* On error, returns negative value of error codes defined in `errno.h`.
* @retval Number of bytes read (> 0) on success.
* @retval -EACCES if ZMS is still not initialized.
* @retval -EIO if there is a memory read/write error.
* @retval -ENOENT if there is no entry with the given `id`.
*/
ssize_t zms_read(struct zms_fs *fs, uint32_t id, void *data, size_t len);
/**
* @brief Read a history entry from the file system.
*
* @param fs Pointer to the file system.
* @param id ID of the entry to be read.
* @param data Pointer to data buffer.
* @param len Number of bytes to be read.
* @param cnt History counter: 0: latest entry, 1: one before latest ...
*
* @return Number of bytes read. On success, it will be equal to the number of bytes requested
* to be read. When the return value is larger than the number of bytes requested to read this
* indicates not all bytes were read, and more data is available. On error, returns negative
* value of error codes defined in `errno.h`.
* @retval Number of bytes read (> 0) on success.
* @retval -EACCES if ZMS is still not initialized.
* @retval -EIO if there is a memory read/write error.
* @retval -ENOENT if there is no entry with the given `id` and history counter.
*/
ssize_t zms_read_hist(struct zms_fs *fs, uint32_t id, void *data, size_t len, uint32_t cnt);
/**
* @brief Gets the length of the data that is stored in an entry with a given `id`
*
* @param fs Pointer to the file system.
* @param id ID of the entry whose data length to retrieve.
*
* @return Data length contained in the ATE. On success, it will be equal to the number of bytes
* in the ATE. On error, returns negative value of error codes defined in `errno.h`.
* @retval Length of the entry with the given `id` (> 0) on success.
* @retval -EACCES if ZMS is still not initialized.
* @retval -EIO if there is a memory read/write error.
* @retval -ENOENT if there is no entry with the given id and history counter.
*/
ssize_t zms_get_data_length(struct zms_fs *fs, uint32_t id);
/**
* @brief Calculate the available free space in the file system.
*
* @param fs Pointer to the file system.
*
* @return Number of free bytes. On success, it will be equal to the number of bytes that can
* still be written to the file system.
* Calculating the free space is a time-consuming operation, especially on SPI flash.
* On error, returns negative value of error codes defined in `errno.h`.
* @retval Number of free bytes (>= 0) on success.
* @retval -EACCES if ZMS is still not initialized.
* @retval -EIO if there is a memory read/write error.
*/
ssize_t zms_calc_free_space(struct zms_fs *fs);
/**
* @brief Tell how much contiguous free space remains in the currently active ZMS sector.
*
* @param fs Pointer to the file system.
*
* @retval >=0 Number of free bytes in the currently active sector
* @retval -EACCES if ZMS is still not initialized.
*/
size_t zms_active_sector_free_space(struct zms_fs *fs);
/**
* @brief Close the currently active sector and switch to the next one.
*
* @note The garbage collector is called on the new sector.
*
* @warning This routine is made available for specific use cases.
* It collides with ZMS's goal of avoiding any unnecessary flash erase operations.
* Using this routine extensively can result in premature failure of the flash device.
*
* @param fs Pointer to the file system.
*
* @retval 0 on success.
* @retval -EACCES if ZMS is still not initialized.
* @retval -EIO if there is a memory read/write error.
*/
int zms_sector_use_next(struct zms_fs *fs);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* ZEPHYR_INCLUDE_FS_ZMS_H_ */

View File

@ -0,0 +1,29 @@
/* SPDX-License-Identifier: Apache-2.0 */
#ifndef PORT_KERNEL_H
#define PORT_KERNEL_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#define CONFIG_ZMS_LOOKUP_CACHE 1
#ifndef CONFIG_ZMS_LOOKUP_CACHE_SIZE
#define CONFIG_ZMS_LOOKUP_CACHE_SIZE 16
#endif
#define CONFIG_ZMS_NO_DOUBLE_WRITE 1
#define CONFIG_ZMS_DATA_CRC 1
#define CONFIG_ZMS_LOG_LEVEL 0
#define BIT(n) (1UL << (n))
#define GENMASK64(h,l) ((UINT64_MAX >> (63-(h))) & (UINT64_MAX << (l)))
#define GENMASK(h,l) ((UINT32_MAX >> (31-(h))) & (UINT32_MAX << (l)))
#define FIELD_GET(mask,val) (((val) & (mask)) >> __builtin_ctzll(mask))
#define FIELD_PREP(mask,val) (((uint64_t)(val) << __builtin_ctzll(mask)) & (mask))
#define SIZEOF_FIELD(type,field) sizeof(((type *)0)->field)
#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)>(b)?(a):(b))
#define IS_ENABLED(x) (x)
#define K_FOREVER 0
struct k_mutex { int unused; };
static inline void k_mutex_init(struct k_mutex *m) {(void)m;}
static inline void k_mutex_lock(struct k_mutex *m,int t) {(void)m;(void)t;}
static inline void k_mutex_unlock(struct k_mutex *m) {(void)m;}
#endif

View File

@ -0,0 +1,5 @@
/* SPDX-License-Identifier: Apache-2.0 */
#define LOG_MODULE_REGISTER(...)
#define LOG_ERR(...)
#define LOG_INF(...)
#define LOG_DBG(...)

View File

@ -0,0 +1,9 @@
/* SPDX-License-Identifier: Apache-2.0 */
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
uint8_t crc8_ccitt(uint8_t,const void *,size_t);
uint8_t crc8_rohc(uint8_t,const void *,size_t);
uint8_t crc8(const uint8_t *,size_t,uint8_t,uint8_t,bool);
uint32_t crc32_ieee(const uint8_t *,size_t);
uint32_t crc32_ieee_update(uint32_t,const uint8_t *,size_t);

View File

@ -0,0 +1,2 @@
/* SPDX-License-Identifier: Apache-2.0 */
#define __packed __attribute__((packed))

View File

@ -0,0 +1,34 @@
/*
* Copyright (c) 2018 Workaround GmbH.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/sys/crc.h>
uint32_t crc32_ieee(const uint8_t *data, size_t len)
{
return crc32_ieee_update(0x0, data, len);
}
uint32_t crc32_ieee_update(uint32_t crc, const uint8_t *data, size_t len)
{
/* crc table generated from polynomial 0xedb88320 */
static const uint32_t table[16] = {
0x00000000U, 0x1db71064U, 0x3b6e20c8U, 0x26d930acU,
0x76dc4190U, 0x6b6b51f4U, 0x4db26158U, 0x5005713cU,
0xedb88320U, 0xf00f9344U, 0xd6d6a3e8U, 0xcb61b38cU,
0x9b64c2b0U, 0x86d3d2d4U, 0xa00ae278U, 0xbdbdf21cU,
};
crc = ~crc;
for (size_t i = 0; i < len; i++) {
uint8_t byte = data[i];
crc = (crc >> 4) ^ table[(crc ^ byte) & 0x0f];
crc = (crc >> 4) ^ table[(crc ^ ((uint32_t)byte >> 4)) & 0x0f];
}
return (~crc);
}

View File

@ -0,0 +1,74 @@
/*
* Copyright (c) 2020 Intel Corporation
* Copyright (c) 2017 Nordic Semiconductor ASA
* Copyright (c) 2015 Runtime Inc
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/sys/crc.h>
static const uint8_t crc8_ccitt_small_table[16] = {
0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d
};
static const uint8_t crc8_rohc_small_table[16] = {
0x00, 0x1c, 0x38, 0x24, 0x70, 0x6c, 0x48, 0x54,
0xe0, 0xfc, 0xd8, 0xc4, 0x90, 0x8c, 0xa8, 0xb4
};
uint8_t crc8_ccitt(uint8_t val, const void *buf, size_t cnt)
{
size_t i;
const uint8_t *p = buf;
for (i = 0; i < cnt; i++) {
val ^= p[i];
val = (val << 4) ^ crc8_ccitt_small_table[val >> 4];
val = (val << 4) ^ crc8_ccitt_small_table[val >> 4];
}
return val;
}
uint8_t crc8_rohc(uint8_t val, const void *buf, size_t cnt)
{
size_t i;
const uint8_t *p = buf;
for (i = 0; i < cnt; i++) {
val ^= p[i];
val = (val >> 4) ^ crc8_rohc_small_table[val & 0x0f];
val = (val >> 4) ^ crc8_rohc_small_table[val & 0x0f];
}
return val;
}
uint8_t crc8(const uint8_t *src, size_t len, uint8_t polynomial, uint8_t initial_value,
bool reversed)
{
uint8_t crc = initial_value;
size_t i, j;
for (i = 0; i < len; i++) {
crc ^= src[i];
for (j = 0; j < 8; j++) {
if (reversed) {
if ((crc & 0x01) != 0) {
crc = (crc >> 1) ^ polynomial;
} else {
crc >>= 1;
}
} else {
if ((crc & 0x80) != 0) {
crc = (crc << 1) ^ polynomial;
} else {
crc <<= 1;
}
}
}
}
return crc;
}

View File

@ -0,0 +1,34 @@
/* SPDX-License-Identifier: Apache-2.0 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <zephyr/fs/zms.h>
#include "port.h"
unsigned char medium[65536];
size_t medium_size, page_size;
int io_trace;
char fault_type;
off_t fault_offset;
static struct flash_parameters params;
static struct device dev;
void medium_reset(size_t count,size_t size,int explicit_erase,size_t block) {
medium_size=count*size;page_size=size;memset(medium,255,sizeof(medium));
params=(struct flash_parameters){block,255,explicit_erase}; fault_type=0;io_trace=0;
}
void fs_reset(struct zms_fs *fs) {memset(fs,0,sizeof(*fs));fs->sector_count=medium_size/page_size;fs->sector_size=page_size;fs->flash_device=&dev;}
const struct flash_parameters *flash_get_parameters(const struct device *d) {(void)d;return &params;}
int flash_params_get_erase_cap(const struct flash_parameters *p){return p->erase_cap;}
int flash_get_page_info_by_offs(const struct device *d,off_t off,struct flash_pages_info *p){(void)d;if(off<0||(size_t)off>=medium_size)return -EINVAL;p->size=page_size;p->start_offset=off/page_size*page_size;return 0;}
static int fault(char type,off_t off) {if(fault_type==type&&fault_offset==off){fault_type=0;return -EIO;}return 0;}
int flash_read(const struct device *d,off_t off,void *data,size_t len){(void)d;if(off<0||(size_t)off+len>medium_size)return -EIO;if(fault('R',off))return -EIO;memcpy(data,medium+off,len);return 0;}
int flash_write(const struct device *d,off_t off,const void *data,size_t len){
(void)d;int rc=0;
if(off<0||(size_t)off+len>medium_size||off%params.write_block_size||len%params.write_block_size)rc=-EIO;
else if(fault('W',off))rc=-EIO;
else if(params.erase_cap){for(size_t i=0;i<len;i++)if((medium[off+i]&((const unsigned char *)data)[i])!=((const unsigned char *)data)[i])rc=-EIO;}
if(!rc)memcpy(medium+off,data,len);
if(io_trace){printf("IO W %ld %zu %d ",(long)off,len,rc);for(size_t i=0;i<len;i++)printf("%02x",((const unsigned char *)data)[i]);puts("");}
return rc;
}
int flash_erase(const struct device *d,off_t off,size_t len){(void)d;int rc=0;if(off<0||(size_t)off+len>medium_size||off%page_size||len%page_size)rc=-EIO;else if(fault('E',off))rc=-EIO;if(!rc)memset(medium+off,255,len);if(io_trace)printf("IO E %ld %zu %d\n",(long)off,len,rc);return rc;}

View File

@ -0,0 +1,9 @@
/* SPDX-License-Identifier: Apache-2.0 */
#include <zephyr/fs/zms.h>
extern unsigned char medium[65536];
extern size_t medium_size,page_size;
extern int io_trace;
extern char fault_type;
extern off_t fault_offset;
void medium_reset(size_t,size_t,int,size_t);
void fs_reset(struct zms_fs *);

View File

@ -0,0 +1,27 @@
/* SPDX-License-Identifier: Apache-2.0 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zephyr/fs/zms.h>
#include "port.h"
int main(int argc,char **argv){
if(argc==2 && !freopen(argv[1],"r",stdin))return 2;
struct zms_fs fs;char cmd[40],hex[16385];unsigned char data[8192];unsigned id,n,cnt,ns,sz,ex,bl;long off;char ft;
medium_reset(3,256,1,1);fs_reset(&fs);
while(scanf("%39s",cmd)==1){
if(!strcmp(cmd,"reset")){if(scanf("%u%u%u%u",&ns,&sz,&ex,&bl)!=4)return 2;if(ns<2||ns>8||sz<80||ns*sz>65536||!bl)return 2;medium_reset(ns,sz,ex,bl);fs_reset(&fs);puts("RESET");}
else if(!strcmp(cmd,"mount")){fs_reset(&fs);printf("MOUNT %d\n",zms_mount(&fs));}
else if(!strcmp(cmd,"write")){if(scanf("%u%16384s",&id,hex)!=2)return 2;n=strlen(hex)/2;for(unsigned i=0;i<n;i++){unsigned x;if(sscanf(hex+2*i,"%2x",&x)!=1)return 2;data[i]=x;}printf("WRITE %u %zd\n",id,zms_write(&fs,id,data,n));}
else if(!strcmp(cmd,"zero")){if(scanf("%u",&id)!=1)return 2;printf("ZERO %u %zd\n",id,zms_write(&fs,id,NULL,0));}
else if(!strcmp(cmd,"readplain")){if(scanf("%u%u",&id,&n)!=2||n>8192)return 2;memset(data,0,sizeof(data));ssize_t r=zms_read(&fs,id,data,n);printf("PLAIN %u %zd ",id,r);if(r>0)for(unsigned i=0;i<n&&(ssize_t)i<r;i++)printf("%02x",data[i]);puts("");}
else if(!strcmp(cmd,"delete")){if(scanf("%u",&id)!=1)return 2;printf("DELETE %u %d\n",id,zms_delete(&fs,id));}
else if(!strcmp(cmd,"read")){if(scanf("%u%u%u",&id,&n,&cnt)!=3||n>8192)return 2;memset(data,0,sizeof(data));ssize_t r=zms_read_hist(&fs,id,data,n,cnt);printf("READ %u %u %zd ",id,cnt,r);if(r>0)for(unsigned i=0;i<n&&(ssize_t)i<r;i++)printf("%02x",data[i]);puts("");}
else if(!strcmp(cmd,"next"))printf("NEXT %d\n",zms_sector_use_next(&fs));
else if(!strcmp(cmd,"space"))printf("SPACE %zd %zu\n",zms_calc_free_space(&fs),zms_active_sector_free_space(&fs));
else if(!strcmp(cmd,"fault")){if(scanf(" %c %ld",&ft,&off)!=2)return 2;fault_type=ft;fault_offset=off;puts("FAULT");}
else if(!strcmp(cmd,"trace")){if(scanf("%d",&io_trace)!=1)return 2;puts("TRACE");}
else if(!strcmp(cmd,"dump")){printf("MEDIA ");for(size_t i=0;i<medium_size;i++)printf("%02x",medium[i]);puts("");}
else return 2;
}
return 0;
}

View File

@ -0,0 +1,8 @@
reset 3 512 1 4
mount
write 7 11223344
read 7 4 0
write 7 aabbccdd
read 7 4 1
mount
read 7 4 0

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,80 @@
/* Copyright (c) 2018 Laczen
* Copyright (c) 2024 BayLibre SAS
*
* SPDX-License-Identifier: Apache-2.0
*
* ZMS: Zephyr Memory Storage
*/
#ifndef __ZMS_PRIV_H_
#define __ZMS_PRIV_H_
/*
* MASKS AND SHIFT FOR ADDRESSES.
* An address in zms is an uint64_t where:
* - high 4 bytes represent the sector number
* - low 4 bytes represent the offset in a sector
*/
#define ADDR_SECT_MASK GENMASK64(63, 32)
#define ADDR_SECT_SHIFT 32
#define ADDR_OFFS_MASK GENMASK64(31, 0)
#define SECTOR_NUM(x) FIELD_GET(ADDR_SECT_MASK, x)
#define SECTOR_OFFSET(x) FIELD_GET(ADDR_OFFS_MASK, x)
#if defined(CONFIG_ZMS_CUSTOMIZE_BLOCK_SIZE)
#define ZMS_BLOCK_SIZE CONFIG_ZMS_CUSTOM_BLOCK_SIZE
#else
#define ZMS_BLOCK_SIZE 32
#endif
#define ZMS_LOOKUP_CACHE_NO_ADDR GENMASK64(63, 0)
#define ZMS_HEAD_ID GENMASK(31, 0)
#define ZMS_VERSION_MASK GENMASK(7, 0)
#define ZMS_GET_VERSION(x) FIELD_GET(ZMS_VERSION_MASK, x)
#define ZMS_DEFAULT_VERSION 1
#define ZMS_MAGIC_NUMBER 0x42 /* murmur3a hash of "ZMS" (MSB) */
#define ZMS_MAGIC_NUMBER_MASK GENMASK(15, 8)
#define ZMS_GET_MAGIC_NUMBER(x) FIELD_GET(ZMS_MAGIC_NUMBER_MASK, x)
#define ZMS_MIN_ATE_NUM 5
#define ZMS_INVALID_SECTOR_NUM -1
#define ZMS_DATA_IN_ATE_SIZE 8
/**
* @ingroup zms_data_structures
* ZMS Allocation Table Entry (ATE) structure
*/
struct zms_ate {
/** crc8 check of the entry */
uint8_t crc8;
/** cycle counter for non erasable devices */
uint8_t cycle_cnt;
/** data len within sector */
uint16_t len;
/** data id */
uint32_t id;
union {
/** data field used to store small sized data */
uint8_t data[8];
struct {
/** data offset within sector */
uint32_t offset;
union {
/**
* crc for data: The data CRC is checked only when the whole data
* of the element is read.
* The data CRC is not checked for a partial read, as it is computed
* for the complete set of data.
*/
uint32_t data_crc;
/**
* Used to store metadata information such as storage version.
*/
uint32_t metadata;
};
};
};
} __packed;
#endif /* __ZMS_PRIV_H_ */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,130 @@
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
GRADER = Path(__file__).resolve().parent
BLOCKED = "isolation-blocked.txt"
GUARD = 86
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
CHECK = (
"import os, runpy, subprocess, sys, tempfile\n"
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
"untrusted = [os.path.realpath(sys.argv[1])]\n"
"def inside(path):\n"
" path = os.path.realpath(str(path))\n"
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
"def guard(event, args):\n"
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
" sys.__stderr__.flush()\n"
" os._exit(%d)\n"
"mkdtemp = tempfile.mkdtemp\n"
"def scratch(*args, **kwargs):\n"
" path = mkdtemp(*args, **kwargs)\n"
" untrusted.append(os.path.realpath(path))\n"
" if isolated:\n"
" os.chown(path, 65534, 65534)\n"
" return path\n"
"tempfile.mkdtemp = scratch\n"
"popen = subprocess.Popen.__init__\n"
"def drop(self, *args, **kwargs):\n"
" if isolated:\n"
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
" popen(self, *args, **kwargs)\n"
"subprocess.Popen.__init__ = drop\n"
"real = subprocess.run\n"
"def run(*args, **kwargs):\n"
" result = real(*args, **kwargs)\n"
" if result.returncode and result.stderr:\n"
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
" return result\n"
"subprocess.run = run\n"
"sys.addaudithook(guard)\n"
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
class UnsupportedEnvironment(RuntimeError):
pass
def candidate_user():
os.setgroups([])
os.setgid(65534)
os.setuid(65534)
def isolation():
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
return None
if sys.platform != "linux" or os.geteuid() != 0:
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
probe = (
"from pathlib import Path\n"
"try: Path('/grader/verify.py').read_bytes()\n"
"except PermissionError: raise SystemExit(0)\n"
"raise SystemExit(1)\n"
)
try:
result = subprocess.run([sys.executable, "-I", "-c", probe],
capture_output=True, timeout=10, preexec_fn=candidate_user)
except subprocess.SubprocessError as error:
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
if result.returncode != 0:
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
return candidate_user
def verify(candidate):
if (GRADER / BLOCKED).exists():
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
isolated = isolation() is not None
if shutil.which("gcc") is None:
raise UnsupportedEnvironment("C compiler unavailable")
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
root = Path(temporary)
work, grader = root / "work", root / "grader"
shutil.copytree(candidate, work, symlinks=True)
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
if isolated:
os.chmod(root, 0o711)
os.chmod(grader, 0o700)
for path in (work, *work.rglob("*")):
os.lchown(path, 65534, 65534)
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
str(grader / "check.py"), str(work)],
cwd=root, capture_output=True, text=True, timeout=100)
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
sys.stderr.write(completed.stderr[-4000:])
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
lines = completed.stdout.splitlines()
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
return {"status": "PASS", "checks": 1}
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
if __name__ == "__main__":
try:
result = verify(Path(sys.argv[1]))
except UnsupportedEnvironment as error:
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
except subprocess.TimeoutExpired:
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
except Exception as error:
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
print(json.dumps(result, sort_keys=True))
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))

View File

@ -0,0 +1,843 @@
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->rto = TCP_RTO;
conn->timer = TCP_RTO;
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,855 @@
#include <stdio.h>
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->rto = TCP_RTO << (conn->nrtx > 4 ? 4: conn->nrtx);
tcp_update_retrantimer(conn, conn->rto);
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
devif_conn_event(conn->dev, TCP_ABORT,
conn->sconn.list);
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */
static void require_grader_access(void) __attribute__((constructor));
static void require_grader_access(void)
{
const char *p = getenv("TCP_GRADER_PROBE");
FILE *f = fopen(p ? p : "/grader/check.py", "rb");
if (!f) { fputs("grader unreadable\n", stderr); exit(91); }
fclose(f);
}

View File

@ -0,0 +1,283 @@
"""Independent time/event oracle. Candidate executable reports raw observations only."""
import json
from pathlib import Path
import random
import subprocess
import sys
import tarfile
import tempfile
HERE = Path(__file__).resolve().parent
SOURCES = ['net/tcp/tcp_timer.c', 'net/tcp/tcp_callback.c', 'net/tcp/tcp_monitor.c',
'net/tcp/tcp_appsend.c', 'net/tcp/tcp_seqno.c', 'net/tcp/tcp_devpoll.c',
'net/devif/devif_callback.c', 'lab.c']
POLL, REXMIT, ABORT, TIMEDOUT = 16, 8, 128, 512
def config(**kw):
c = dict(state=4, unacked=0, retries=0, rto=3, timer=0, ka=0, idle=100,
interval=10, count=3, kept=0, seq=1000, rexseq=900,
pbytes=0, abytes=0, sockets=1, delayed=0, listener=0)
c.update(kw)
return c
class Model:
def __init__(self, c):
self.c = c.copy()
self.tick = 0
self.timer = c['timer']
self.keep = c['idle'] if c['ka'] else 0
self.retries = c['retries']
self.kept = c['kept']
self.state = c['state']
self.rto = c['rto']
self.seq = c['seq']
self.unacked = c['unacked']
self.packets = []
self.events = [0, 0]
self.ended = False
self.delayed = c['delayed']
self.zero = False
self.due = None
self.schedule()
def duration(self):
values = [self.timer] if self.timer else []
if self.keep:
values.append(self.keep // 5)
return min(values) if values else 0
def schedule(self):
delay = self.duration() * 5
self.due = self.tick + delay if delay > 0 else None
def event(self, flags):
if not self.ended:
for i in range(self.c['sockets']):
self.events[i] |= flags
if flags & (ABORT | TIMEDOUT):
self.ended = True
def packet(self, flags, n=40, seq=None):
self.packets.append([self.tick, flags, n, self.seq if seq is None else seq])
def ordinary_poll(self):
if self.state == 4:
self.event(POLL)
size = self.c['abytes'] if self.c['sockets'] and not self.ended else 0
self.retries = 0
if size:
self.unacked += size
self.packet(24, 40 + size)
self.seq = (self.seq + size) & 0xffffffff
def expire(self):
h = self.duration()
if self.state == 0:
return
if self.state in (6, 8):
self.timer -= h
if self.timer <= 0:
self.timer = 0
self.state = 0
self.event(TIMEDOUT)
elif self.unacked:
self.timer -= h
if self.timer <= 0:
self.timer = 0
limit = 5 if self.state in (2, 3) else 8
if self.retries >= limit:
old = self.state
self.state = 0
if old != 2 or self.c['listener']:
self.event(TIMEDOUT)
self.packet(20)
else:
self.rto = 3 * 2 ** min(self.retries, 4)
self.timer = self.rto
self.retries += 1
if self.state in (2, 3, 5, 7, 9):
self.seq = self.c['rexseq']
self.packet({2:18, 3:2, 5:17, 7:17, 9:17}[self.state])
elif self.state == 4:
self.event(REXMIT)
size = self.c['pbytes'] if self.c['sockets'] and not self.ended else 0
if size:
if self.c['rexseq']:
self.packet(24, 40 + size, self.c['rexseq'])
else:
self.packet(24, 40 + size)
self.seq = (self.seq + size) & 0xffffffff
elif self.state == 4:
if self.c['ka']:
if self.keep > 5 * h:
self.keep -= 5 * h
else:
if self.kept >= self.c['count']:
self.event(ABORT)
else:
self.packet(16, seq=(self.seq - 1) & 0xffffffff)
self.keep = self.c['interval']
self.kept += 1
self.schedule()
return
if self.zero:
self.timer -= h
if self.timer <= 0:
if self.retries >= 8:
self.zero = False
# This is the separate, unchanged zero-window path.
else:
self.packet(16, seq=(self.seq - 1) & 0xffffffff)
self.retries += 1
self.timer = min(2 ** self.retries, 240)
self.schedule()
return
if self.delayed:
self.delayed = 0
self.packet(16)
else:
self.ordinary_poll()
self.schedule()
def command(self, op, n):
if op == 'P':
self.ordinary_poll()
elif op == 'S':
self.due = None
elif op == 'Z':
if self.state == 4 and not self.unacked and not self.zero and not (n & 2) and n & (16 | 8 | 1):
self.zero = True
self.timer = 1
self.schedule()
elif op == 'A':
end = self.tick + n
for _ in range(1024):
if self.due is None or self.due > end:
break
self.tick = self.due
self.due = None
self.expire()
# Terminal socket notifications are tested at their first occurrence.
if self.ended:
break
self.tick = end
def match(self, raw, label):
if raw['tick'] != self.tick or raw['packets'] != self.packets:
raise AssertionError(label + ': packet/tick trace')
if raw['rto'] != self.rto:
raise AssertionError(label + ': retransmission RTO')
if raw['sequence'] != self.seq or raw['unacked'] != self.unacked:
raise AssertionError(label + ': send bookkeeping')
# Keepalive abort does not impose an extra internal TCP-state transition.
if not (self.ended and any(x & ABORT for x in self.events)) and raw['state'] != self.state:
raise AssertionError(label + ': TCP state')
for i in range(self.c['sockets']):
if raw['events'][i] != self.events[i]:
raise AssertionError(label + ': socket event propagation')
if self.events[i] & (ABORT | TIMEDOUT):
if raw['wakes'][i] < 1 or raw['sflags'] & 6:
raise AssertionError(label + ': waiting socket still connected')
elif raw['wakes'][i] or not raw['sflags'] & 2:
raise AssertionError(label + ': premature socket termination')
def cases():
rng = random.Random(178650)
yield 'smoke', config(abytes=8), [('P', 0)]
for state in (0, 2, 3, 4, 5, 6, 7, 8, 9):
yield 'ordinary-poll-' + str(state), config(state=state), [('P', 0), ('A', 100)]
for state in (2, 3, 4, 5, 7, 9):
limit = 5 if state in (2, 3) else 8
for retry in range(limit + 1):
timer = rng.randrange(1, 12)
c = config(state=state, unacked=rng.randrange(1, 900), retries=retry,
rto=rng.choice([1, 3, 17, 48]), timer=timer,
pbytes=rng.randrange(1, 64), sockets=2, listener=1,
seq=rng.randrange(1000, 0xfffffff0), rexseq=rng.randrange(1, 900))
delay = timer * 5
backoff = 3 * 2 ** min(retry, 4) * 5
ops = [('A', delay - 1), ('A', 1)]
if retry < limit:
ops += [('A', backoff - 1), ('A', 1)]
yield 'retransmit-%s-%s' % (state, retry), c, ops
yield 'poll-preserves-deadline', config(unacked=20, timer=4, pbytes=7), [('P', 0), ('A', 19), ('A', 1)]
yield 'listener-missing', config(state=2, unacked=1, retries=5, timer=2, listener=0), [('A', 10)]
yield 'empty-retransmit', config(unacked=40, timer=2, retries=2, sockets=0), [('A', 10), ('A', 60)]
yield 'zero-retransmit-sequence', config(unacked=20, timer=1, pbytes=7, rexseq=0), [('A', 5), ('A', 15)]
for state in (6, 8):
for timer in (1, 3, 17):
yield 'finite-wait-%s-%s' % (state, timer), config(state=state, timer=timer, sockets=2), [('A', timer * 5 - 1), ('A', 1)]
for idle in (5, 15, 70):
for interval in (5, 20):
for count in (0, 1, 2, 5):
c = config(ka=1, idle=idle, interval=interval, count=count,
sockets=2, seq=rng.choice([0, 1, 0xffffffff, 3200]))
ops = [('A', idle - 1), ('A', 1)]
for _ in range(count):
ops += [('A', interval - 1), ('A', 1)]
yield 'keepalive-%s-%s-%s' % (idle, interval, count), c, ops
for kept in (1, 3, 6):
yield 'partial-probe-budget-' + str(kept), config(ka=1, idle=10, interval=15, kept=kept, count=3, sockets=2), [('A', 9), ('A', 1)]
for state in (0, 2, 3, 5, 7, 9):
yield 'non-established-keepalive-' + str(state), config(state=state, ka=1, idle=10, count=0), [('A', 40)]
yield 'keepalive-disabled', config(ka=0, idle=5, count=0), [('A', 1000), ('P', 0)]
yield 'keepalive-disabled-active-timer', config(ka=0, timer=2, idle=5, count=0), [('A', 9), ('A', 1), ('A', 10)]
for retry in (0, 3, 6):
yield 'pending-data-suppresses-probes-' + str(retry), config(unacked=42, timer=7, retries=retry, ka=1, idle=10, interval=5, count=0, pbytes=11), [('A', 34), ('A', 1)]
yield 'idle-before-probe-polls', config(ka=1, timer=1, idle=20), [('A', 5), ('A', 5), ('A', 5)]
yield 'delayed-ack', config(ka=1, timer=1, idle=20, delayed=1), [('A', 5), ('A', 5)]
yield 'probe-sequence-wrap', config(seq=0), [('Z', 16), ('A', 4), ('A', 1), ('A', 9), ('A', 1)]
yield 'zero-probe-backoff-cap', config(), [('Z', 16), ('A', 5), ('A', 10), ('A', 20), ('A', 40), ('A', 80), ('A', 160), ('A', 320), ('A', 640), ('A', 1199)]
yield 'stop-timer', config(unacked=19, timer=3, pbytes=19), [('S', 0), ('A', 100)]
yield 'repeat-zero-probe-request', config(), [('Z', 16), ('A', 2), ('Z', 16), ('A', 3)]
yield 'newdata-does-not-arm-probe', config(), [('Z', 18), ('A', 100)]
def main():
candidate = Path(sys.argv[1])
with tempfile.TemporaryDirectory(prefix='tcp-raw-') as tmp:
work = Path(tmp)
# All root writes happen before executing either compiler or candidate.
with tarfile.open(HERE / 'support.tar', 'r') as archive:
for entry in archive.getmembers():
parts = Path(entry.name).parts
if entry.isfile() and not entry.name.startswith('/') and '..' not in parts:
dest = work / entry.name
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(archive.extractfile(entry).read())
dest = work / 'net/tcp/tcp_timer.c'
dest.write_bytes((candidate / 'net/tcp/tcp_timer.c').read_bytes())
compile_result = subprocess.run(['gcc', '-std=gnu11', '-O0', '-I.', '-Iport', *SOURCES, '-o', 'tcp-lab'], cwd=work, capture_output=True, text=True, timeout=25)
if compile_result.returncode:
sys.stderr.write(compile_result.stderr[-3000:])
raise AssertionError('candidate compilation')
total = 0
for name, c, ops in cases():
data = ' '.join(str(v) for v in c.values()) + '\n'
data += ''.join('%s %d\n' % op for op in ops)
run = subprocess.run([str(work / 'tcp-lab')], cwd=work, input=data, capture_output=True, text=True, timeout=2)
if run.returncode:
sys.stderr.write(run.stderr[-1000:])
raise AssertionError(name + ': candidate process failed')
rows = [json.loads(line) for line in run.stdout.splitlines()]
if len(rows) != len(ops) + 1:
raise AssertionError(name + ': observation count')
model = Model(c)
model.match(rows[0], name + ': initial')
for op, row in zip(ops, rows[1:]):
model.command(*op)
model.match(row, name + ': %s %s' % op)
total += 1
print('checked %d observations' % total)
print('PASS')
if __name__ == '__main__':
try:
main()
except (AssertionError, KeyError, ValueError, subprocess.TimeoutExpired) as error:
print('FAIL: ' + str(error))
raise SystemExit(1)

View File

@ -0,0 +1,845 @@
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->rto = TCP_RTO << (conn->nrtx > 4 ? 4: conn->nrtx);
tcp_update_retrantimer(conn, conn->rto);
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
devif_conn_event(conn->dev, TCP_ABORT,
conn->sconn.list);
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,845 @@
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->rto = TCP_RTO << (conn->nrtx > 1 ? 1: conn->nrtx);
tcp_update_retrantimer(conn, conn->rto);
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
devif_conn_event(conn->dev, TCP_ABORT,
conn->sconn.list);
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,843 @@
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
return;
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->timer = TCP_RTO << (conn->nrtx > 4 ? 4: conn->nrtx);
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,844 @@
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->timer = TCP_RTO << (conn->nrtx > 4 ? 4: conn->nrtx);
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
devif_conn_event(conn->dev, TCP_ABORT,
conn->sconn.list);
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,843 @@
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->rto = TCP_RTO << (conn->nrtx > 4 ? 4: conn->nrtx);
tcp_update_retrantimer(conn, conn->rto);
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,5 @@
现场回报:网络设备丢失应答后,业务日志里的后续重发等待出现异常;一些空闲连接持续无响应,探测额度耗尽后业务线程仍然阻塞。正常短连接的发送暂未见异常。
当前目录保留了设备通信模块与可控软件端口。先用 `make smoke` 运行正常路径,并参照 README 使用虚拟 tick 复现其他场景。请修复模块,使其行为符合 `docs/tcp-contract.md` 的全部条款,并保留正常轮询和发送行为。
最终只交付 `net/tcp/tcp_timer.c`;其他文件和新增文件不参与正式评分。

View File

@ -0,0 +1,112 @@
# net-nuttx-tcp-retry-closure
## 身份与来源
- 状态:CALIBRATED;软件校准与真实 Agent 难度分开,后者 UNMEASURED。
- 路线 D:两处独立开源真实修复;项目 https://github.com/apache/nuttx ,family `state-machine-timing`,source `oss/apache/nuttx@d1786507b619`,split `apache/nuttx`。
- 冻结版本:`fb4a246fccb0a411ff684053ae83f9359644a909`,正是第一处修复的父提交。
- 修复:`d1786507b619e9884d2c7ae36e82823dcf43a6ff` 与 `ab756e8dd716165b411d14843368325bf7fd581c`。
- 第一处在真实重传时只改剩余 timer,未同步 RTO 及统一登记入口;第二处 keepalive 耗尽只释放 monitor,未将 ABORT 传播到等待 socket。两者条件、状态与修复独立;`only_retry`、`only_keepalive` 各只修一处。
- 共同冻结核对:第一处完整修后文件与 `only_retry` 字节一致;第二处生产 hunk 的两行插入与冻结 keepalive 分支上下文一致。gold 仅把两处生产 hunk 叠到同一冻结文件,不带后续其他改动、不补改 gold。
- 许可:逐个 C/H 文件按原 SPDX 核准,BSD-3-Clause 与 Apache-2.0;全部保留原文件头、根 LICENSE 与 NOTICE。根 LICENSE 包含仓库第三方许可汇编,不表示本实验使用所有那些模块。无真实用户资料或密钥。
- 替身测试:软件问题可复现;虚拟 tick 和 packet 输出替代硬件,不替代重传退避、keepalive 决策、事件分发或 monitor 的生产实现。
## 冻结与补全文件
下列路径均相对 template,逐文件来源与 SHA256 另见本题 factory 下 `source-manifest.json`。所有冻结文件来自上述同一 base,目录和字节保留。
| 文件 | 类型/许可 | 角色 |
| --- | --- | --- |
| LICENSE | 上游冻结/原样 | 根许可及第三方声明汇编 |
| NOTICE | 上游冻结/原样 | 原项目通知 |
| net/tcp/tcp_timer.c | 上游冻结/BSD-3-Clause | 唯一候选,完整计时状态机 |
| net/tcp/tcp_appsend.c | 上游冻结/BSD-3-Clause | 完整发送与重传 |
| net/tcp/tcp_seqno.c | 上游冻结/BSD-3-Clause | 序号编解码及生成 |
| net/tcp/tcp_devpoll.c | 上游冻结/BSD-3-Clause | 工作到期后的真实设备 poll |
| net/tcp/tcp_callback.c | 上游冻结/Apache-2.0 | TCP 数据及连接事件 |
| net/tcp/tcp_monitor.c | 上游冻结/Apache-2.0 | socket 标志和监视生命周期 |
| net/devif/devif_callback.c | 上游冻结/Apache-2.0 | 原始回调表分配、释放、分发 |
| net/tcp/tcp.h | 上游冻结/Apache-2.0 | 完整内部 TCP 合同,供阅读 |
| net/devif/devif.h | 上游冻结/BSD-3-Clause | 完整事件/回调定义,供阅读 |
| include/nuttx/net/tcp.h | 上游冻结/BSD-3-Clause | 完整公开 TCP 定义,供阅读 |
| include/nuttx/net/netconfig.h | 上游冻结/BSD-3-Clause | 完整默认网络配置,供阅读 |
| port.h | 补全/Apache-2.0 | 本实验配置的类型、声明、常量和接口 |
| lab.c | 补全/Apache-2.0 | 虚拟 tick、工作队列、packet 原始输出与 socket 等待端口 |
| Makefile | 补全 | gcc 构建和正常 smoke |
| smoke.in | 补全 | ESTABLISHED 普通 poll 发送,不触发缺陷 |
| README.md | 补全 | 现场症状、构建入口、17 字段输入与 JSON 原始观察说明 |
| docs/tcp-contract.md | 补全 | 上游注释、默认配置与 RFC 整理的公开行为合同 |
| port/nuttx/config.h | 补全 | 仅包含 port.h |
| port/nuttx/net/netconfig.h | 补全 | 仅包含 port.h |
| port/nuttx/net/net.h | 补全 | 仅包含 port.h |
| port/nuttx/net/netdev.h | 补全 | 仅包含 port.h |
| port/nuttx/net/netstats.h | 补全 | 仅包含 port.h |
| port/nuttx/net/tcp.h | 补全 | 仅包含 port.h |
| port/netdev/netdev.h | 补全 | 仅包含 port.h |
| port/devif/devif.h | 补全 | 仅包含 port.h |
| port/socket/socket.h | 补全 | 仅包含 port.h |
| port/tcp/tcp.h | 补全 | 仅包含 port.h |
| port/nuttx/mm/iob.h | 补全 | 仅包含 port.h |
| port/utils/utils.h | 补全 | 仅包含 port.h |
| port/nuttx/kmalloc.h | 补全 | 仅包含 port.h |
| port/crypto/md5.h | 补全 | 仅包含 port.h,RFC6528 配置关闭 |
| port/nuttx/clock.h | 补全 | 仅包含 port.h |
| port/debug.h | 补全 | 仅包含 port.h |
共 35 文件,候选 1 文件,grader 附件 2 文件;最大 template 文件是原样根 LICENSE,均小于 1 MiB。独有 C 代码 1273 行(去 `/* */` 注释和空行,含宏/条件编译;7 个上游 C 共 1146 行,lab.c 127 行;不计 fixture、许可证、评分器及重复包装头)。未为凑规模增加无关模块。
## 公开接口与评分边界
- `make smoke` 编译完整保留模块及 raw lab,输入 smoke.in,打印初始化和普通 poll 的原始 JSON;成功退出 0。
- `tcp-lab` 输入/输出和命令见 README;全部时间由 tick 驱动,无真实睡眠、网络、硬件或下载依赖。
- 使用固定 trace6 镜像 `ccr-29eug8s3-pub.cnc.bj.baidubce.com/algo/bench-runtime@sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1`,GNU C 编译器、Python 标准库。
- 正式只挂候选 `net/tcp/tcp_timer.c`;其他干净支撑材料在非 .py 私有 `support.tar`,定 uid/gid 0、mode 0644、mtime 0。root 用 write_bytes 解包,全部写入在编译/执行前完成,不继承 host 所有者。
- `verify.py` 原样复制 rollout/bos_verify.py。受保护父 check 独立生成固定种子输入、推演时间和协议结果。编译器与候选只在 UID/GID 65534 子进程运行;C lab 只有输入传递、事件/包记录和原始输出,不包含 PASS 判定、期望数值或退避/终止决策。
- 真实生产链为 work expiry → tcp_poll → tcp_timer → tcp_callback/devif_conn_event → socket 等待原语 → tcp_lost_connection/tcp_stop_monitor。socket 等待原语只按收到的事件记录唤醒并调用真实丢失处理,不自行判断 keepalive、RTO 或 retry。
- 不检查 work_queue 调用次数、monitor 释放精确次数、私有重试计数字段或 keepalive 之后额外的 TCP 状态;等待者至少收到一次应有终结事件即可。包数组顺序原样比较,不排序或归一化。
- 编译期限 25 秒、单次候选运行 2 秒;整体验收期限 120 秒(包装器内部 100 秒)。9 类各 5 次。
## 判据检查项 ↔ 依据
表中 `docs/...` 相对 template。全部输出关系与期望都在父 check 比较;C 中的数组界限/输入检查仅用于 raw 端口内存安全。
| 判据检查项 | 公开依据 | 输入与观察 |
| --- | --- | --- |
| 构建、输入/输出结构、固定配置 | README.md:8、README.md:11、README.md:13;docs/tcp-contract.md:5 | 干净 gcc 构建,17 字段请求、每命令一个 JSON |
| 时间单位、到期边界、普通 poll 保留期限 | docs/tcp-contract.md:7 | 到期前 1 tick、相等时刻及活动 timer 中插入普通 poll |
| 重传 RTO、指数退避、上限与后续 deadline | docs/tcp-contract.md:9 | n=0..7、多初始 RTO/剩余时间、两轮重传的原始包时间与 RTO |
| ESTABLISHED 重传数据、最早未确认序号与保留发送序号 | docs/tcp-contract.md:11 | 非零 rexmit_seq、空应用数据、空等待者、原始包及发送序号 |
| SYN/FIN 系列重传包 | docs/tcp-contract.md:13 | SYN_RCVD/SYN_SENT/FIN_WAIT_1/CLOSING/LAST_ACK,各 n 边界 |
| 重传耗尽 reset、TIMEDOUT、socket 断开 | docs/tcp-contract.md:13 | SYN 上限 5、数据上限 8、双 socket、监听存在/缺失 |
| TIME_WAIT/FIN_WAIT_2 有限等待、CLOSED 无输出 | docs/tcp-contract.md:15 | 剩余 1/3/17 半秒,前 1 tick 与期限相等 |
| keepidle、interval、探测包和序号回绕 | docs/tcp-contract.md:17 | idle=5/15/70、interval=5/20,seq=0/1/UINT32_MAX/其他 |
| keepalive 开关、连接态和未确认数据优先 | docs/tcp-contract.md:17 | 非 ESTABLISHED、禁用、未确认数据与更短 keep tick 并存 |
| keepcnt 耗尽、ABORT、唤醒与 socket 标志 | docs/tcp-contract.md:19 | keepcnt=0/1/2/5、部分已耗预算、双 socket |
| 普通 poll 空/有数据及非连接态回归 | docs/tcp-contract.md:21 | smoke 发送 8 字节、空 poll、其他 TCP 状态 |
| delayed ACK 与无待确认段回归 | docs/tcp-contract.md:23 | 提前计时、待确认段 1、后续正常 poll |
| 零窗口探测登记、指数等待、上限、序号恢复 | docs/tcp-contract.md:25 | 首次/重复请求、NEWDATA 请求不登记、seq=0、退避到 240 上限 |
| 取消工作不再产生计时动作 | docs/tcp-contract.md:25 | 有待重传数据时 S 后前进 100 tick |
共 14 条依据映射。上游依据另有 `net/tcp/tcp.h` 字段注释(rto、timer、keepidle、keepintvl、keepcnt),`include/nuttx/net/netconfig.h` 的默认 TCP_RTO/MAXRTX/MAXSYNRTX、真实 callback/monitor 的事件及 socket 标志注释。RFC 6298 §5.4–5.5、RFC 1122 §4.2.3.6 是外部公开背景;判据所需的本实验参数均已随题公开,无需联网查阅。
## 样例与验证
| 样例 | 预期 | 内容 |
| --- | --- | --- |
| gold | PASS | 冻结版本仅叠两处真实生产 hunk |
| valid_iterative | PASS | 用循环计算 RTO、直接更新 timer/统一登记,使用 tcp_callback 传播终结事件 |
| template | FAIL | 两处上游缺陷均保留 |
| only_retry | FAIL | 仅真实重传修复,缺少 keepalive socket 通知 |
| only_keepalive | FAIL | 仅真实 keepalive 修复,缺少正确 RTO |
| noop | FAIL | 计时入口直接返回 |
| cheat | FAIL | 固定基本 RTO 掩盖指数退避 |
| mask_symptom | FAIL | 基于 gold,但只保留前两级退避,掩盖浅层丢包症状 |
| cheat_read_grader | FAIL | 基于 gold,构造函数读取私有 check.py 成功才继续,否则受控退出 |
`cheat_read_grader` 的可读分支用非秘密占位 `/probe` 在无网 Docker 验证为 PASS,真实权限下为受控 FAIL;不把失败编译或损坏 gold 作为隔离证明。原始诊断日志、精确容器名称及清理事实在本题 factory 下保存。
正式 Docker 校准回执:`runs/20261103-D-oss-fix-29/nuttx-d178650/calibration-7d3ed6ebc88b4ddfb6a81007ac0f6597/receipt.json`。当前 task digest:`369464716845c6f702ee4d5d344be27a58f4c20e7fa4583631d7d64d47d21954`。9 类每类 5 次共 45 次全部符合预期,整体 PASS,全部清理 confirmed;镜像 ID 为 `sha256:1519f8daa403998e5401eeb70b973e8aac8346e25a937033bc502dc5de1641a1`。本题 93 个精确容器名(含三次诊断及旧指纹校准)均经 docker inspect 确认不存在,无创建专用网络。最终判据有 113 个场景、414 个命令后观察;原始初始化观察另计。为补全禁用 keepalive 同时有活动 timer、最后一次重传后的终结期限覆盖,保留旧指纹 45 次 PASS 回执并按最终指纹完整重跑。未运行 trusted-local;不在 host 执行上游代码。全库 unittest 与独立 root 审阅由主 Agent 负责,本题未宣称它们完成。
## 限制与未验证
当前只有软件实验,不含完整 OS、真实 recv 系统调用/阻塞线程、网络对端、抓包、板卡或电气验证。socket 等待原语模拟事件观察和唤醒,socket 标志改变、监视释放以及事件遍历仍执行真实上游 C。只对公开实验配置和有定义的输入检查;原始输入的任意非法数值或关闭的 write-buffer、SOLINGER、NewReno、IPv6、RFC6528 配置不在验收中。真实 Agent rollout、会话完整性、模型成功率和难度全部 UNMEASURED。未调用模型、未提交、未改平台或其他任务。

Binary file not shown.

View File

@ -0,0 +1,28 @@
{
"id": "net-nuttx-tcp-retry-closure",
"version": "1",
"family": "state-machine-timing",
"source": "oss/apache/nuttx@d1786507b619",
"split": "apache/nuttx",
"template": "template",
"verifier": "verify.py",
"candidate_files": [
"net/tcp/tcp_timer.c"
],
"grader_files": [
"check.py",
"support.tar"
],
"timeout_seconds": 120,
"fixtures": {
"gold": "PASS",
"template": "FAIL",
"noop": "FAIL",
"cheat": "FAIL",
"cheat_read_grader": "FAIL",
"only_retry": "FAIL",
"only_keepalive": "FAIL",
"mask_symptom": "FAIL",
"valid_iterative": "PASS"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,11 @@
CC = gcc
CFLAGS = -std=gnu11 -O0 -g -Wall -Wextra -Wno-unused-parameter -I. -Iport
SOURCES = net/tcp/tcp_timer.c net/tcp/tcp_callback.c net/tcp/tcp_monitor.c net/tcp/tcp_appsend.c net/tcp/tcp_seqno.c net/tcp/tcp_devpoll.c net/devif/devif_callback.c lab.c
all: tcp-lab
tcp-lab: $(SOURCES) port.h
$(CC) $(CFLAGS) $(SOURCES) -o $@
smoke: tcp-lab
./tcp-lab < smoke.in
clean:
rm -f tcp-lab
.PHONY: all smoke clean

View File

@ -0,0 +1,68 @@
Apache NuttX
Copyright 2020 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
FAT Long File Names
===================
NOTE: If CONFIG_FAT_LFN is defined in your NuttX configuration file, then
there may be some legal, patent issues. The following was extracted from
the entry "File Allocation Table from Wikipedia, the free encyclopedia:
"On December 3, 2003 Microsoft announced it would be offering licenses
for use of its FAT specification and 'associated intellectual property',
at the cost of a US$0.25 royalty per unit sold, with a $250,000 maximum
royalty per license agreement.
o "U.S. Patent 5,745,902 (http://www.google.com/patents?vid=5745902) -
Method and system for accessing a file using file names having
different file name formats. ...
o "U.S. Patent 5,579,517 (http://www.google.com/patents?vid=5579517) -
Common name space for long and short filenames. ...
o "U.S. Patent 5,758,352 (http://www.google.com/patents?vid=5758352) -
Common name space for long and short filenames. ...
o "U.S. Patent 6,286,013 (http://www.google.com/patents?vid=6286013) -
Method and system for providing a common name space for long and
short file names in an operating system. ...
"Many technical commentators have concluded that these patents only cover
FAT implementations that include support for long filenames, and that
removable solid state media and consumer devices only using short names
would be unaffected. ..."
This Wikipedia entry has been updated with recent legal decisions in favor
of Microsoft. Refer to:
https://en.wikipedia.org/wiki/File_Allocation_Table#Patents
So you have been forewarned: Use the long filename at your own risk!
NXP Restriction for SPIFI code
==============================
NOTE: Code supporting spifi for the LCP43xx has restricted usage by NXP
FILES:
arch/arm/src/lpc43xx/hardware/lpc43_spifi.h
arch/arm/src/lpc43xx/spifi/inc/spifilib_api.h
arch/arm/src/lpc43xx/spifi/inc/spifilib_dev.h
arch/arm/src/lpc43xx/spifi/inc/private/spifilib_chiphw.h
arch/arm/src/lpc43xx/spifi/src/spifilib_dev_common.c
arch/arm/src/lpc43xx/spifi/src/spifilib_fam_standard_cmd.c
Permission to use, copy, modify, and distribute this software and its
documentation is hereby granted, under NXP Semiconductors' and its
licensor's relevant copyrights in the software, without fee, provided that it
is used in conjunction with NXP Semiconductors microcontrollers. This
copyright, permission, and disclaimer notice must appear in all copies of
this code.
Documentation
=============
- nRF52832-MDK board pinout image is obtained from MakerDiary GitHub repository,
under the terms of the MIT license, Copyright (c) 2019 makerdiary.com
- Sparkfun nRF52832 breakout board image is licensed under CC-BY 2.0 terms
- Espressif ESP32 DevKitC images are licensed under the terms of Apache 2.0,
Copyright (C) 2015-2019 Espressif Systems

View File

@ -0,0 +1,17 @@
# TCP 设备侧现场复现工作区
设备通信层在丢失应答后出现等待间隔异常;另一些长期无响应的连接已经用尽探测次数,业务线程仍在等待。请让保留的 TCP 模块符合 `docs/tcp-contract.md` 的全部条款,保持正常连接和轮询行为。
构建和正常路径冒烟:
```sh
make smoke
```
`tcp-lab` 是原始观察器,不会给出通过结论。标准输入第一行的 17 个无符号整数依次为:TCP 状态、未确认字节数、已重传次数、RTO、重传剩余半秒、keepalive 开关、keepidle tick、keepintvl tick、keepcnt、已发送 keepalive 次数、发送序号、最早未确认序号、重传应用字节数、普通 poll 应用字节数、等待 socket 数(0–2)、待 delayed ACK 段数、是否存在监听连接。
后续每行为命令和整数:`A ticks` 前进指定虚拟 tick,逐次执行沿途已登记工作及设备 poll;`P 0` 执行一次普通设备 poll;`Z flags` 请求零窗口探测;`S 0` 停止计时。每条命令后打印 JSON 原始观察,包括包的 `[tick, TCP flags, 总长度, sequence]`、socket 事件和当前连接字段。初始化也打印一次观察。事件位及 TCP flags 不是同一个编码,见 `port.h` 和上游头文件。
`port/` 和 `port.h` 为此实验的最小端口声明;`lab.c` 仅实现虚拟 tick、工作队列、包输出、等待 socket 端口和不使用的 I/O 原语。核心计时、发送与连接监视仍执行上游 C 文件。随附上游头文件用于阅读原合同,构建时使用 port 目录中匹配本配置的声明。
最终只提交并评分 `net/tcp/tcp_timer.c`,新增文件不进入正式候选。正式验收会从干净的端口材料重新编译该文件,并覆盖公开合同中的其他输入组合。

View File

@ -0,0 +1,27 @@
# TCP 软件实验合同
这里保留 TCP 计时、轮询、应用发送、回调、连接监视及 devif 回调链。端口层只提供单连接、单设备、虚拟工作队列和包输出端口,不提供真实网卡或完整操作系统。
R01. 构建配置启用 TCP、keepalive 和 delayed ACK,采用非 write-buffer 发送方式。基本 RTO 为 3 个半秒,普通数据最多重试 8 次,SYN 最多重试 5 次;TCP 状态和事件位的定义见随附头文件。
R02. 一个 tick 是 100 毫秒,5 tick 是一个半秒。工作队列按相对延迟登记到期回调,到期回调通知设备,设备通过正常 TCP poll 入口处理计时。普通 poll 不消耗计时器。实验输入中的非零 keepidle、keepintvl 均为 5 tick 的整数倍,重传计时器单位为半秒。
R03. 有未确认数据时,到期重传采用 `3 × 2^min(n,4)` 个半秒的等待值,n 为本次重传前已经发生的重传次数;该值成为连接的 RTO 并用于下一次重传期限。等待期间不得提前重发;未到期的重传剩余时间随已处理的半秒递减。
R04. ESTABLISHED 的重传先向应用发送 REXMIT 事件,再发送应用提供的数据。非零 rexmit_seq 指定最早未确认段的序号,发送时使用该序号,保留连接当前发送序号。无重传数据时不凭空制造数据包。
R05. SYN_RCVD 重发 SYN|ACK,SYN_SENT 重发 SYN,FIN_WAIT_1、CLOSING 和 LAST_ACK 重发 FIN|ACK;这些重传使用 rexmit_seq。重试已耗尽时连接变为 CLOSED,通知等待者 TIMEDOUT,并发送 RST|ACK。SYN_RCVD 的通知发给监听连接,找不到监听连接时仍发送 reset。实验的监听连接可配置为当前连接。
R06. TIME_WAIT 和 FIN_WAIT_2 等待各自期限,届满后变为 CLOSED 并通知 TIMEDOUT,不发送额外报文。CLOSED 不生成包或应用轮询事件。
R07. keepalive 只处理没有未确认数据的 ESTABLISHED 连接,并且须已启用。空闲等待从 keepidle 开始,之后探测间隔为 keepintvl。每个探测只带 ACK,序号为当前发送序号减一(按 32 位回绕),发送后保留原序号。有未确认数据期间由重传处理,不发送 keepalive 探测;禁用 keepalive 不因这些参数终止连接。
R08. 每次空闲或探测期限届满时,若探测额度已用尽,连接向等待中的各 socket 传播 ABORT,唤醒等待者,并通过连接丢失处理清除 socket 的 CONNECTED 和 CLOSED 标志,停止连接监视。
R09. ESTABLISHED 的普通轮询向应用发送 POLL 事件;应用没有数据时无包,有数据时发送 ACK|PSH、长度为应用数据加 40 字节,增加未确认数据及发送序号。其他状态的普通 poll 不生成应用数据包。
R10. delayed ACK 在至少一个半秒的计时处理后发送纯 ACK,清除待确认段状态;没有待确认段时不凭空发送 ACK。
R11. 无未确认数据、没有 NEWDATA、由 POLL/REXMIT/ACKDATA 引起的零窗口探测请求,在尚未超时且尚未探测时登记一个半秒的初次期限。后续零窗口探测只带 ACK 并保留原发送序号,以 `min(2^n,240)` 个半秒等待下次探测;普通重试上限适用。已有探测不重复登记初次期限,停止计时操作取消已登记的工作。
这些条款整理自随附的 NuttX 头文件/函数合同及 TCP 的公开规定:RFC 6298 §5.4–5.5(重传与退避)、RFC 1122 §4.2.3.6(keepalive)、RFC 1122 §4.2.3.2(ACK)。本实验对可配置参数采用头文件中的默认值;不验证真实网络时延或对端 TCP 实现。

View File

@ -0,0 +1,666 @@
/****************************************************************************
* include/nuttx/net/netconfig.h
*
* SPDX-License-Identifier: BSD-3-Clause
* SPDX-FileCopyrightText: 2007, 2011, 2014-2015, 2017-2019 Gregory Nutt.
* All rights reserved.
* SPDX-FileCopyrightText: 2001-2003, Adam Dunkels. All rights reserved.
* SPDX-FileContributor: Gregory Nutt <gnutt@nuttx.org>
* SPDX-FileContributor: Adam Dunkels <adam@dunkels.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#ifndef __INCLUDE_NUTTX_NET_NETCONFG_H
#define __INCLUDE_NUTTX_NET_NETCONFG_H
/* Note: Network configuration options the netconfig.h should not be changed,
* but rather the per-project defconfig file.
*/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <nuttx/net/ethernet.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Using the following definitions, the following socket() arguments should
* provide a valid socket in all configurations:
*
* ret = socket(NET_SOCK_FAMILY, NET_SOCK_TYPE,
* NET_SOCK_PROTOCOL);
*/
/* The TCP/UDP stack, which is used for determining HAVE_PFINET(6)_SOCKETS */
#undef NET_TCP_HAVE_STACK
#if defined(CONFIG_NET_TCP) && !defined(CONFIG_NET_TCP_NO_STACK)
# define NET_TCP_HAVE_STACK 1
#endif
#undef NET_UDP_HAVE_STACK
#if defined(CONFIG_NET_UDP) && !defined(CONFIG_NET_UDP_NO_STACK)
# define NET_UDP_HAVE_STACK 1
#endif
/* The address family that we used to create the socket really does not
* matter. It should, however, be valid in the current configuration.
*/
#undef HAVE_INET_SOCKETS
#undef HAVE_PFINET_SOCKETS
#undef HAVE_PFINET6_SOCKETS
#if defined(CONFIG_NET_IPv4) || defined(CONFIG_NET_IPv6)
# define HAVE_INET_SOCKETS
# if (defined(CONFIG_NET_IPv4) && (defined(NET_UDP_HAVE_STACK) || \
defined(NET_TCP_HAVE_STACK) || defined(CONFIG_NET_USRSOCK))) || \
defined(CONFIG_NET_ICMP_SOCKET)
# define HAVE_PFINET_SOCKETS
# endif
# if (defined(CONFIG_NET_IPv6) && (defined(NET_UDP_HAVE_STACK) || \
defined(NET_TCP_HAVE_STACK) || defined(CONFIG_NET_USRSOCK))) || \
defined(CONFIG_NET_ICMPv6_SOCKET)
# define HAVE_PFINET6_SOCKETS
# endif
#endif
#if defined(HAVE_PFINET_SOCKETS)
# define NET_SOCK_FAMILY AF_INET
#elif defined(HAVE_PFINET6_SOCKETS)
# define NET_SOCK_FAMILY AF_INET6
#elif defined(CONFIG_NET_LOCAL)
# define NET_SOCK_FAMILY AF_LOCAL
#elif defined(CONFIG_NET_PKT)
# define NET_SOCK_FAMILY AF_PACKET
#elif defined(CONFIG_NET_CAN)
# define NET_SOCK_FAMILY AF_CAN
#elif defined(CONFIG_NET_IEEE802154)
# define NET_SOCK_FAMILY AF_IEEE802154
#elif defined(CONFIG_WIRELESS_PKTRADIO)
# define NET_SOCK_FAMILY AF_PKTRADIO
#elif defined(CONFIG_NET_BLUETOOTH)
# define NET_SOCK_FAMILY AF_BLUETOOTH
#elif defined(CONFIG_NET_USRSOCK)
# define NET_SOCK_FAMILY AF_INET
#elif defined(CONFIG_NET_NETLINK)
# define NET_SOCK_FAMILY AF_NETLINK
#elif defined(CONFIG_NET_RPMSG)
# define NET_SOCK_FAMILY AF_RPMSG
#else
# define NET_SOCK_FAMILY AF_UNSPEC
#endif
/* Socket protocol of zero normally works */
#define NET_SOCK_PROTOCOL 0
/* SOCK_CTRL is the preferred socket type to use when we just want a
* socket for performing driver ioctls.
*/
#define NET_SOCK_TYPE (SOCK_CTRL | SOCK_CLOEXEC)
#if NET_SOCK_FAMILY == AF_INET
# if !defined(CONFIG_NET_UDP) && !defined(CONFIG_NET_TCP) && \
defined(CONFIG_NET_ICMP_SOCKET)
# undef NET_SOCK_PROTOCOL
# define NET_SOCK_PROTOCOL IPPROTO_ICMP
# endif
#elif NET_SOCK_FAMILY == AF_INET6
# if !defined(CONFIG_NET_UDP) && !defined(CONFIG_NET_TCP) && \
defined(CONFIG_NET_ICMPv6_SOCKET)
# undef NET_SOCK_PROTOCOL
# define NET_SOCK_PROTOCOL IPPROTO_ICMP6
# endif
#endif
/* Eliminate dependencies on other header files. This should not harm
* portability because these are well-known constants.
*/
#define __IPv4_HDRLEN 20 /* Must match IPv4_HDRLEN in include/nuttx/net/ip.h */
#define __IPv6_HDRLEN 40 /* Must match IPv6_HDRLEN in include/nuttx/net/ip.h */
#define __UDP_HDRLEN 8 /* Must match UDP_HDRLEN in include/nuttx/net/udp.h */
#define __TCP_HDRLEN 20 /* Must match TCP_HDRLEN in include/nuttx/net/tcp.h */
/* REVISIT: Not really a constant */
/* Layer 2 Configuration Options ********************************************/
/* The default link layer is Ethernet. If CONFIG_NET_SLIP is defined in
* the NuttX header file, then SLIP will be supported. The basic
* differences between the SLIP and Ethernet configurations is that when SLIP
* is selected:
*
* - The link level header (that comes before the IP header) is omitted.
* - All MAC address processing is suppressed.
* - ARP is disabled.
*
* If CONFIG_NET_SLIP is not supported, then Ethernet will be used (there is
* no need to define anything special in the configuration file to use
* Ethernet -- it is the default).
*
* The "link level header" is the offset into the d_buf where the IP header
* can be found. For Ethernet, this should be set to 14. For SLIP, this
* should be set to 0.
*
* There are other device-specific features that at tied to the link layer:
*
* - Maximum Transfer Unit (MTU)
* - TCP Receive Window size (See TCP configuration options below)
*
* A better solution would be to support device-by-device MTU and receive
* window sizes. This minimum support is require to support the optimal
* SLIP MTU of 296 bytes and the standard Ethernet MTU of 1500
* bytes.
*/
#ifdef CONFIG_NET_SLIP
# ifndef CONFIG_NET_SLIP_PKTSIZE
# define CONFIG_NET_SLIP_PKTSIZE 296
# endif
#endif
#ifdef CONFIG_NET_TUN
# ifndef CONFIG_NET_TUN_PKTSIZE
# define CONFIG_NET_TUN_PKTSIZE 296
# endif
#endif
#ifdef CONFIG_NET_ETHERNET
# ifndef CONFIG_NET_ETH_PKTSIZE
# define CONFIG_NET_ETH_PKTSIZE 590
# endif
#endif
#ifndef CONFIG_NET_6LOWPAN_PKTSIZE
# define CONFIG_NET_6LOWPAN_PKTSIZE 1294
#endif
/* We are supporting multiple network devices using different link layer
* protocols. Get the size of the link layer header from the device
* structure.
*/
#define NET_LL_HDRLEN(d) ((d)->d_llhdrlen)
#define NETDEV_PKTSIZE(d) ((d)->d_pktsize)
#ifdef CONFIG_NET_ETHERNET
# define _MIN_ETH_PKTSIZE CONFIG_NET_ETH_PKTSIZE
# define _MAX_ETH_PKTSIZE CONFIG_NET_ETH_PKTSIZE
#else
# define _MIN_ETH_PKTSIZE UINT16_MAX
# define _MAX_ETH_PKTSIZE 0
#endif
#ifdef CONFIG_NET_LOOPBACK
# define _MIN_LO_PKTSIZE MIN(_MIN_ETH_PKTSIZE, 574)
# define _MAX_LO_PKTSIZE MAX(_MAX_ETH_PKTSIZE, 1518)
#else
# define _MIN_LO_PKTSIZE _MIN_ETH_PKTSIZE
# define _MAX_LO_PKTSIZE _MAX_ETH_PKTSIZE
#endif
#ifdef CONFIG_NET_SLIP
# define _MIN_SLIP_PKTSIZE MIN(_MIN_LO_PKTSIZE, CONFIG_NET_SLIP_PKTSIZE)
# define _MAX_SLIP_PKTSIZE MAX(_MAX_LO_PKTSIZE, CONFIG_NET_SLIP_PKTSIZE)
#else
# define _MIN_SLIP_PKTSIZE _MIN_LO_PKTSIZE
# define _MAX_SLIP_PKTSIZE _MAX_LO_PKTSIZE
#endif
#ifdef CONFIG_NET_TUN
# define _MIN_TUN_PKTSIZE MIN(_MIN_SLIP_PKTSIZE, CONFIG_NET_TUN_PKTSIZE)
# define _MAX_TUN_PKTSIZE MAX(_MAX_SLIP_PKTSIZE, CONFIG_NET_TUN_PKTSIZE)
#else
# define _MIN_TUN_PKTSIZE _MIN_SLIP_PKTSIZE
# define _MAX_TUN_PKTSIZE _MAX_SLIP_PKTSIZE
#endif
#ifdef CONFIG_NET_6LOWPAN
# define _MIN_6LOWPAN_PKTSIZE MIN(_MIN_TUN_PKTSIZE, CONFIG_NET_6LOWPAN_PKTSIZE)
# define _MAX_6LOWPAN_PKTSIZE MAX(_MAX_TUN_PKTSIZE, CONFIG_NET_6LOWPAN_PKTSIZE)
#else
# define _MIN_6LOWPAN_PKTSIZE _MIN_TUN_PKTSIZE
# define _MAX_6LOWPAN_PKTSIZE _MAX_TUN_PKTSIZE
#endif
#define MIN_NETDEV_PKTSIZE _MIN_6LOWPAN_PKTSIZE
#define MAX_NETDEV_PKTSIZE _MAX_6LOWPAN_PKTSIZE
/* The loopback driver packet buffer should be quite large. The larger the
* loopback packet buffer, the better will be TCP performance of the loopback
* transfers. The Linux loopback device historically used packet buffers of
* size 16Kb, but that was increased in recent Linux versions to 64Kb. Those
* sizes may be excessive for resource constrained MCUs, however.
*
* For the loopback driver, we enforce a lower limit that is the maximum
* packet size of all enabled link layer protocols.
*/
#ifndef CONFIG_NET_LOOPBACK_PKTSIZE
# define CONFIG_NET_LOOPBACK_PKTSIZE 0
#endif
#if CONFIG_NET_LOOPBACK_PKTSIZE < MAX_NETDEV_PKTSIZE
# define NET_LO_PKTSIZE MAX_NETDEV_PKTSIZE
#else
# define NET_LO_PKTSIZE CONFIG_NET_LOOPBACK_PKTSIZE
#endif
#ifndef CONFIG_NET_SEND_BUFSIZE
# define CONFIG_NET_SEND_BUFSIZE 0
#endif
/* Layer 3/4 Configuration Options ******************************************/
/* IP configuration options */
/* The IP TTL (time to live) of IP packets sent by the network stack.
*
* This should normally not be changed.
*/
#define IP_TTL_DEFAULT 64
/* Network drivers often receive packets with garbage at the end
* and are longer than the size of packet in the TCP header. The
* following "fudge" factor increases the size of the I/O buffering
* by a small amount to allocate slightly oversize packets. After
* receipt, the packet size will be chopped down to the size indicated
* in the TCP header.
*/
#ifndef CONFIG_NET_GUARDSIZE
# define CONFIG_NET_GUARDSIZE 2
#endif
/* ICMP configuration options */
#ifndef CONFIG_NET_ICMP
# undef CONFIG_NET_ICMP_SOCKET
#endif
/* UDP configuration options */
/* The UDP maximum packet size. This should not be set to more than
* NETDEV_PKTSIZE(d) - NET_LL_HDRLEN(dev) - __UDP_HDRLEN - IPv*_HDRLEN.
*/
#define UDP_MSS(d,h) (NETDEV_PKTSIZE(d) - NET_LL_HDRLEN(d) - __UDP_HDRLEN - (h))
#ifdef CONFIG_NET_ETHERNET
# define ETH_UDP_MSS(h) (CONFIG_NET_ETH_PKTSIZE - ETH_HDRLEN - __UDP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_6LOWPAN
# define IEEE802154_UDP_MSS(h) (CONFIG_NET_6LOWPAN_PKTSIZE - __UDP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_LOOPBACK
# define LO_UDP_MSS(h) (NET_LO_PKTSIZE - __UDP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_SLIP
# define SLIP_UDP_MSS(h) (CONFIG_NET_SLIP_PKTSIZE - __UDP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_TUN
# define TUN_UDP_MSS(h) (CONFIG_NET_TUN_PKTSIZE - __UDP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_USRSOCK
# define __MIN_UDP_MSS(h) INT_MAX
# define __MAX_UDP_MSS(h) 0
#endif
#ifdef CONFIG_NET_ETHERNET
# undef __MIN_UDP_MSS
# undef __MAX_UDP_MSS
# define __MIN_UDP_MSS(h) ETH_UDP_MSS(h)
# define __MAX_UDP_MSS(h) ETH_UDP_MSS(h)
# define __ETH_MIN_UDP_MSS(h) ETH_UDP_MSS(h)
# define __ETH_MAX_UDP_MSS(h) ETH_UDP_MSS(h)
#else
# define __ETH_MIN_UDP_MSS(h) INT_MAX
# define __ETH_MAX_UDP_MSS(h) 0
#endif
#ifdef CONFIG_NET_6LOWPAN
# undef __MIN_UDP_MSS
# undef __MAX_UDP_MSS
# define __MIN_UDP_MSS(h) MIN(IEEE802154_UDP_MSS(h),__ETH_MIN_UDP_MSS(h))
# define __MAX_UDP_MSS(h) MAX(IEEE802154_UDP_MSS(h),__ETH_MAX_UDP_MSS(h))
# define __6LOWPAN_MIN_UDP_MSS(h) MIN(IEEE802154_UDP_MSS(h),__ETH_MIN_UDP_MSS(h))
# define __6LOWPAN_MAX_UDP_MSS(h) MAX(IEEE802154_UDP_MSS(h),__ETH_MAX_UDP_MSS(h))
#else
# define __6LOWPAN_MIN_UDP_MSS(h) __ETH_MIN_UDP_MSS(h)
# define __6LOWPAN_MAX_UDP_MSS(h) __ETH_MAX_UDP_MSS(h)
#endif
#ifdef CONFIG_NET_LOOPBACK
# undef __MIN_UDP_MSS
# undef __MAX_UDP_MSS
# define __MIN_UDP_MSS(h) MIN(LO_UDP_MSS(h),__6LOWPAN_MIN_UDP_MSS(h))
# define __MAX_UDP_MSS(h) MAX(LO_UDP_MSS(h),__6LOWPAN_MAX_UDP_MSS(h))
# define __LOOP_MIN_UDP_MSS(h) MIN(LO_UDP_MSS(h),__6LOWPAN_MIN_UDP_MSS(h))
# define __LOOP_MAX_UDP_MSS(h) MAX(LO_UDP_MSS(h),__6LOWPAN_MAX_UDP_MSS(h))
#else
# define __LOOP_MIN_UDP_MSS(h) __6LOWPAN_MIN_UDP_MSS(h)
# define __LOOP_MAX_UDP_MSS(h) __6LOWPAN_MAX_UDP_MSS(h)
#endif
#ifdef CONFIG_NET_SLIP
# undef __MIN_UDP_MSS
# undef __MAX_UDP_MSS
# define __MIN_UDP_MSS(h) MIN(SLIP_UDP_MSS(h),__LOOP_MIN_UDP_MSS(h))
# define __MAX_UDP_MSS(h) MAX(SLIP_UDP_MSS(h),__LOOP_MAX_UDP_MSS(h))
# define __SLIP_MIN_UDP_MSS(h) MIN(SLIP_UDP_MSS(h),__LOOP_MIN_UDP_MSS(h))
# define __SLIP_MAX_UDP_MSS(h) MAX(SLIP_UDP_MSS(h),__LOOP_MAX_UDP_MSS(h))
#else
# define __SLIP_MIN_UDP_MSS(h) __LOOP_MIN_UDP_MSS(h)
# define __SLIP_MAX_UDP_MSS(h) __LOOP_MAX_UDP_MSS(h)
#endif
#ifdef CONFIG_NET_TUN
# undef __MIN_UDP_MSS
# undef __MAX_UDP_MSS
# define __MIN_UDP_MSS(h) MIN(TUN_UDP_MSS(h),__SLIP_MIN_UDP_MSS(h))
# define __MAX_UDP_MSS(h) MAX(TUN_UDP_MSS(h),__SLIP_MAX_UDP_MSS(h))
# define __TUN_MIN_UDP_MSS(h) MIN(TUN_UDP_MSS(h),__SLIP_MIN_UDP_MSS(h))
# define __TUN_MAX_UDP_MSS(h) MAX(TUN_UDP_MSS(h),__SLIP_MAX_UDP_MSS(h))
#else
# define __TUN_MIN_UDP_MSS(h) __SLIP_MIN_UDP_MSS(h)
# define __TUN_MAX_UDP_MSS(h) __SLIP_MAX_UDP_MSS(h)
#endif
#ifdef CONFIG_NET_IPv4
# define UDP_IPv4_MSS(d) UDP_MSS(d,__IPv4_HDRLEN)
# define ETH_IPv4_UDP_MSS ETH_UDP_MSS(__IPv4_HDRLEN)
# define SLIP_IPv4_UDP_MSS SLIP_UDP_MSS(__IPv4_HDRLEN)
# define TUN_IPv4_UDP_MSS TUN_UDP_MSS(__IPv4_HDRLEN)
# define MIN_IPv4_UDP_MSS __MIN_UDP_MSS(__IPv4_HDRLEN)
# define MIN_UDP_MSS __MIN_UDP_MSS(__IPv4_HDRLEN)
# undef MAX_UDP_MSS
# define MAX_IPv4_UDP_MSS __MAX_UDP_MSS(__IPv4_HDRLEN)
# define MAX_UDP_MSS __MAX_UDP_MSS(__IPv4_HDRLEN)
#endif
/* If IPv6 is supported, it will have the smaller MSS. */
#ifdef CONFIG_NET_IPv6
# undef MIN_UDP_MSS
# define MIN_IPv6_UDP_MSS __MIN_UDP_MSS(__IPv6_HDRLEN)
# define MIN_UDP_MSS __MIN_UDP_MSS(__IPv6_HDRLEN)
# ifndef MAX_UDP_MSS
# define MAX_UDP_MSS __MAX_UDP_MSS(__IPv6_HDRLEN)
# endif
#endif
/* TCP configuration options */
/* The maximum number of simultaneously listening TCP ports.
*
* Each listening TCP port requires 2 bytes of memory.
*/
#ifndef CONFIG_NET_MAX_LISTENPORTS
# define CONFIG_NET_MAX_LISTENPORTS 20
#endif
/* The initial retransmission timeout counted in timer pulses.
* REVISIT: TCP RTO really should be calculated dynamically for each TCP
* connection.
*/
#ifdef CONFIG_NET_TCP_RTO
# define TCP_RTO CONFIG_NET_TCP_RTO
#else
# define TCP_RTO 3
#endif
/* The maximum number of times a segment should be retransmitted
* before the connection should be aborted.
*
* This should not be changed.
*/
#ifdef CONFIG_NET_TCP_MAXRTX
# define TCP_MAXRTX CONFIG_NET_TCP_MAXRTX
#else
# define TCP_MAXRTX 8
#endif
/* The maximum number of times a SYN segment should be retransmitted
* before a connection request should be deemed to have been
* unsuccessful.
*
* This should not need to be changed.
*/
#ifdef CONFIG_NET_TCP_MAXSYNRTX
# define TCP_MAXSYNRTX CONFIG_NET_TCP_MAXSYNRTX
#else
# define TCP_MAXSYNRTX 5
#endif
/* The TCP maximum segment size. This should not be set to more than
* NETDEV_PKTSIZE(dev) - NET_LL_HDRLEN(dev) - IPvN_HDRLEN - __TCP_HDRLEN.
*
* In the case where there are multiple network devices with different
* link layer protocols, each network device may support a different MSS
* value. Here we arbitrarily select the minimum MSS for that case.
*
* REVISIT: __TCP_HDRLEN is not really a constant!
*/
#define TCP_MSS(d,h) (NETDEV_PKTSIZE(d) - NET_LL_HDRLEN(d) - __TCP_HDRLEN - (h))
/* Get the smallest and largest MSS */
#ifdef CONFIG_NET_ETHERNET
# define ETH_TCP_MSS(h) (CONFIG_NET_ETH_PKTSIZE - ETH_HDRLEN - __TCP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_6LOWPAN
# define IEEE802154_TCP_MSS(h) (CONFIG_NET_6LOWPAN_PKTSIZE - __TCP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_LOOPBACK
# define LO_TCP_MSS(h) (NET_LO_PKTSIZE - __TCP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_SLIP
# define SLIP_TCP_MSS(h) (CONFIG_NET_SLIP_PKTSIZE - __TCP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_TUN
# define TUN_TCP_MSS(h) (CONFIG_NET_TUN_PKTSIZE - __TCP_HDRLEN - (h))
#endif
#ifdef CONFIG_NET_USRSOCK
# define __MIN_TCP_MSS(h) INT_MAX
# define __MAX_TCP_MSS(h) 0
#endif
#ifdef CONFIG_NET_ETHERNET
# undef __MIN_TCP_MSS
# undef __MAX_TCP_MSS
# define __MIN_TCP_MSS(h) ETH_TCP_MSS(h)
# define __MAX_TCP_MSS(h) ETH_TCP_MSS(h)
# define __ETH_MIN_TCP_MSS(h) ETH_TCP_MSS(h)
# define __ETH_MAX_TCP_MSS(h) ETH_TCP_MSS(h)
#else
# define __ETH_MIN_TCP_MSS(h) INT_MAX
# define __ETH_MAX_TCP_MSS(h) 0
#endif
#ifdef CONFIG_NET_6LOWPAN
# undef __MIN_TCP_MSS
# undef __MAX_TCP_MSS
# define __MIN_TCP_MSS(h) MIN(IEEE802154_TCP_MSS(h),__ETH_MIN_TCP_MSS(h))
# define __MAX_TCP_MSS(h) MAX(IEEE802154_TCP_MSS(h),__ETH_MAX_TCP_MSS(h))
# define __6LOWPAN_MIN_TCP_MSS(h) MIN(IEEE802154_TCP_MSS(h),__ETH_MIN_TCP_MSS(h))
# define __6LOWPAN_MAX_TCP_MSS(h) MAX(IEEE802154_TCP_MSS(h),__ETH_MAX_TCP_MSS(h))
#else
# define __6LOWPAN_MIN_TCP_MSS(h) __ETH_MIN_TCP_MSS(h)
# define __6LOWPAN_MAX_TCP_MSS(h) __ETH_MAX_TCP_MSS(h)
#endif
#ifdef CONFIG_NET_LOOPBACK
# undef __MIN_TCP_MSS
# undef __MAX_TCP_MSS
# define __MIN_TCP_MSS(h) MIN(LO_TCP_MSS(h),__6LOWPAN_MIN_TCP_MSS(h))
# define __MAX_TCP_MSS(h) MAX(LO_TCP_MSS(h),__6LOWPAN_MAX_TCP_MSS(h))
# define __LOOP_MIN_TCP_MSS(h) MIN(LO_TCP_MSS(h),__6LOWPAN_MIN_TCP_MSS(h))
# define __LOOP_MAX_TCP_MSS(h) MAX(LO_TCP_MSS(h),__6LOWPAN_MAX_TCP_MSS(h))
#else
# define __LOOP_MIN_TCP_MSS(h) __6LOWPAN_MIN_TCP_MSS(h)
# define __LOOP_MAX_TCP_MSS(h) __6LOWPAN_MAX_TCP_MSS(h)
#endif
#ifdef CONFIG_NET_SLIP
# undef __MIN_TCP_MSS
# undef __MAX_TCP_MSS
# define __MIN_TCP_MSS(h) MIN(SLIP_TCP_MSS(h),__LOOP_MIN_TCP_MSS(h))
# define __MAX_TCP_MSS(h) MAX(SLIP_TCP_MSS(h),__LOOP_MAX_TCP_MSS(h))
# define __SLIP_MIN_TCP_MSS(h) MIN(SLIP_TCP_MSS(h),__LOOP_MIN_TCP_MSS(h))
# define __SLIP_MAX_TCP_MSS(h) MAX(SLIP_TCP_MSS(h),__LOOP_MAX_TCP_MSS(h))
#else
# define __SLIP_MIN_TCP_MSS(h) __LOOP_MIN_TCP_MSS(h)
# define __SLIP_MAX_TCP_MSS(h) __LOOP_MAX_TCP_MSS(h)
#endif
#ifdef CONFIG_NET_TUN
# undef __MIN_TCP_MSS
# undef __MAX_TCP_MSS
# define __MIN_TCP_MSS(h) MIN(TUN_TCP_MSS(h),__SLIP_MIN_TCP_MSS(h))
# define __MAX_TCP_MSS(h) MAX(TUN_TCP_MSS(h),__SLIP_MAX_TCP_MSS(h))
# define __TUN_MIN_TCP_MSS(h) MIN(TUN_TCP_MSS(h),__SLIP_MIN_TCP_MSS(h))
# define __TUN_MAX_TCP_MSS(h) MAX(TUN_TCP_MSS(h),__SLIP_MAX_TCP_MSS(h))
#else
# define __TUN_MIN_TCP_MSS(h) __SLIP_MIN_TCP_MSS(h)
# define __TUN_MAX_TCP_MSS(h) __SLIP_MAX_TCP_MSS(h)
#endif
/* If IPv4 is supported, it will have the larger MSS.
* NOTE: MSS calculation excludes the __TCP_HDRLEN.
*/
#ifdef CONFIG_NET_IPv6
# define TCP_IPv6_MSS(d) TCP_MSS(d,__IPv6_HDRLEN)
# define ETH_IPv6_TCP_MSS ETH_TCP_MSS(__IPv6_HDRLEN)
# define SLIP_IPv6_TCP_MSS SLIP_TCP_MSS(__IPv6_HDRLEN)
# define TUN_IPv6_TCP_MSS TUN_TCP_MSS(__IPv6_HDRLEN)
# define MAX_TCP_MSS __MAX_TCP_MSS(__IPv6_HDRLEN)
#endif
#ifdef CONFIG_NET_IPv4
# define TCP_IPv4_MSS(d) TCP_MSS(d,__IPv4_HDRLEN)
# define ETH_IPv4_TCP_MSS ETH_TCP_MSS(__IPv4_HDRLEN)
# define SLIP_IPv4_TCP_MSS SLIP_TCP_MSS(__IPv4_HDRLEN)
# define TUN_IPv4_TCP_MSS TUN_TCP_MSS(__IPv4_HDRLEN)
# define MIN_TCP_MSS __MIN_TCP_MSS(__IPv4_HDRLEN)
# undef MAX_TCP_MSS
# define MAX_TCP_MSS __MAX_TCP_MSS(__IPv4_HDRLEN)
#endif
/* If IPv6 is supported, it will have the smaller MSS. */
#ifdef CONFIG_NET_IPv6
# undef MIN_TCP_MSS
# define MIN_TCP_MSS __MIN_TCP_MSS(__IPv6_HDRLEN)
#endif
/* How long a connection should stay in the TIME_WAIT state (in units of
* seconds).
*
* TIME_WAIT is often also known as the 2MSL wait state. This is because
* the socket that transitions to TIME_WAIT stays there for a period that
* is 2 x Maximum Segment Lifetime in duration. The MSL is the maximum
* amount of time that any segment can remain valid on the network before
* being discarded. This time limit is ultimately bounded by the TTL field
* in the IP datagram that is used to transmit the TCP segment. RFC 793
* specifies MSL as 2 minutes but most systems permit this value to be tuned.
* Here a default TIME_WAIT (2MSL) 2 minutes is used, half the value
* specified by RFC 793.
*/
#ifdef CONFIG_NET_TCP_WAIT_TIMEOUT
# define TCP_TIME_WAIT_TIMEOUT CONFIG_NET_TCP_WAIT_TIMEOUT
#else
# define TCP_TIME_WAIT_TIMEOUT (60*2)
#endif
/* ARP configuration options */
#ifndef CONFIG_NET_ARPTAB_SIZE
/* The size of the ARP table.
*
* This option should be set to a larger value if this network node will
* have many connections from the local network.
*/
# define CONFIG_NET_ARPTAB_SIZE 8
#endif
#ifndef CONFIG_NET_ARP_MAXAGE
/* The maximum age of ARP table entries measured in 10ths of seconds.
*
* An CONFIG_NET_ARP_MAXAGE of 120 corresponds to 20 minutes (BSD
* default).
*/
# define CONFIG_NET_ARP_MAXAGE 120
#endif
/****************************************************************************
* Public Type Definitions
****************************************************************************/
/* Statistics datatype
*
* This typedef defines the datatype used for keeping statistics in
* the network.
*/
typedef uint16_t net_stats_t;
#endif /* __INCLUDE_NUTTX_NET_NETCONFG_H */

View File

@ -0,0 +1,211 @@
/****************************************************************************
* include/nuttx/net/tcp.h
*
* SPDX-License-Identifier: BSD-3-Clause
* SPDX-FileCopyrightText: 2007, 2009-2010, 2012-2014 Gregory Nutt.
* SPDX-FileCopyrightText: 2001-2003, Adam Dunkels.
* SPDX-FileContributor: Gregory Nutt <gnutt@nuttx.org>
* SPDX-FileContributor: Adam Dunkels <adam@dunkels.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#ifndef __INCLUDE_NUTTX_NET_TCP_H
#define __INCLUDE_NUTTX_NET_TCP_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#ifdef CONFIG_NET_TCP
#include <stdint.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/ethernet.h>
#include <nuttx/net/ip.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* TCP definitions */
#define TCP_FIN 0x01
#define TCP_SYN 0x02
#define TCP_RST 0x04
#define TCP_PSH 0x08
#define TCP_ACK 0x10
#define TCP_URG 0x20
#define TCP_CTL 0x3f
#define TCP_OPT_END 0 /* End of TCP options list */
#define TCP_OPT_NOOP 1 /* "No-operation" TCP option */
#define TCP_OPT_MSS 2 /* Maximum segment size TCP option */
#define TCP_OPT_WS 3 /* Window size scaling factor */
#define TCP_OPT_SACK_PERM 4 /* Selective-ACK Permitted option */
#define TCP_OPT_SACK 5 /* Selective-ACK Block option */
#define TCP_OPT_NOOP_LEN 1 /* Length of TCP NOOP option. */
#define TCP_OPT_MSS_LEN 4 /* Length of TCP MSS option. */
#define TCP_OPT_WS_LEN 3 /* Length of TCP WS option. */
#define TCP_OPT_SACK_PERM_LEN 2 /* Length of TCP SACK option. */
/* The TCP states used in the struct tcp_conn_s tcpstateflags field */
#define TCP_STATE_MASK 0x0f /* Bits 0-3: TCP state */
# define TCP_CLOSED 0x00 /* The connection is not in use and available */
# define TCP_ALLOCATED 0x01 /* The connection is allocated, but not yet initialized */
# define TCP_SYN_RCVD 0x02
# define TCP_SYN_SENT 0x03
# define TCP_ESTABLISHED 0x04
# define TCP_FIN_WAIT_1 0x05
# define TCP_FIN_WAIT_2 0x06
# define TCP_CLOSING 0x07
# define TCP_TIME_WAIT 0x08
# define TCP_LAST_ACK 0x09
# define TCP_STOPPED 0x10 /* Bit 4: stopped */
/* Bit 5-7: Unused, but not available */
/* TCP header sizes
*
* The minimum size header is 5 words and the maximum is 15 words thus
* giving the minimum size of 20 bytes and maximum of 60 bytes, allowing for
* up to 40 bytes of options in the header.
*/
#define TCP_HDRLEN 20 /* Size of TCP header (minimum) */
#define TCP_OPT_HDRLEN(n) (20 + ((n) << 2)) /* Size of TCP header w/options */
#define TCP_MAX_HDRLEN 60 /* Maximum size of TCP header */
#ifdef CONFIG_NET_IPv4
# define IPv4TCP_HDRLEN (TCP_HDRLEN + IPv4_HDRLEN) /* Size of IPv4 + TCP header */
#endif
#ifdef CONFIG_NET_IPv6
# define IPv6TCP_HDRLEN (TCP_HDRLEN + IPv6_HDRLEN) /* Size of IPv4 + TCP header */
#endif
/* Initial minimum MSS according to RFC 879
*
* The default TCP Maximum Segment Sizes (MSS) are defined below.is 536. If
* a host wishes to set the maximum segment size to a value other than the
* default, the maximum segment size is specified as a TCP option, initially
* in the TCP SYN packet during the TCP handshake. The value cannot be
* changed after the connection is established.
*
* These defaults correspond to the minimum MTU values:
*
* IPv4: MTU=576; MSS=536 (MTU - IPv4_HDRLEN - TCP_HDRLEN)
* IPv6: MTU=1280; MSS=1220 (MTU - IPv6_HDRLEN - TCP_HDRLEN)
*/
#define TCP_DEFAULT_IPv4_MSS 536
#define TCP_DEFAULT_IPv6_MSS 1220
/* Minimal accepted MSS. It is (60+60+8) - (20+20).
* (MAX_IP_HDR + MAX_TCP_HDR + MIN_IP_FRAG) - (MIN_IP_HDR + MIN_TCP_HDR)
*/
#define TCP_MIN_MSS 88
/* However, we do need to make allowance for certain links such as SLIP that
* have unusually small MTUs.
*/
#ifdef CONFIG_NET_IPv4
# define TCP_IPv4_INITIAL_MSS(d) \
(TCP_MSS(d,IPv4_HDRLEN) > 536 ? 536 : TCP_MSS(d,IPv4_HDRLEN))
# define MIN_IPv4_TCP_INITIAL_MSS \
(__MIN_TCP_MSS(IPv4_HDRLEN) > 536 ? 536 : __MIN_TCP_MSS(IPv4_HDRLEN))
# define MAX_IPv4_TCP_INITIAL_MSS \
(__MAX_TCP_MSS(IPv4_HDRLEN) > 536 ? 536 : __MAX_TCP_MSS(IPv4_HDRLEN))
#endif
#ifdef CONFIG_NET_IPv6
# define TCP_IPv6_INITIAL_MSS(d) \
(TCP_MSS(d,IPv6_HDRLEN) > 1220 ? 1220 : TCP_MSS(d,IPv6_HDRLEN))
# define MIN_IPv6_TCP_INITIAL_MSS \
(__MIN_TCP_MSS(IPv6_HDRLEN) > 1220 ? 1220 : __MIN_TCP_MSS(IPv6_HDRLEN))
# define MAX_IPv6_TCP_INITIAL_MSS \
(__MAX_TCP_MSS(IPv6_HDRLEN) > 1220 ? 1220 : __MAX_TCP_MSS(IPv6_HDRLEN))
#endif
/****************************************************************************
* Public Type Definitions
****************************************************************************/
/* TCP header */
struct tcp_hdr_s
{
uint16_t srcport;
uint16_t destport;
uint8_t seqno[4];
uint8_t ackno[4];
uint8_t tcpoffset;
uint8_t flags;
uint8_t wnd[2];
uint16_t tcpchksum;
uint8_t urgp[2];
uint8_t optdata[0];
};
/* The structure holding the TCP/IP statistics that are gathered if
* CONFIG_NET_STATISTICS is defined.
*/
#ifdef CONFIG_NET_STATISTICS
struct tcp_stats_s
{
net_stats_t drop; /* Number of dropped TCP segments */
net_stats_t recv; /* Number of received TCP segments */
net_stats_t sent; /* Number of sent TCP segments */
net_stats_t chkerr; /* Number of TCP segments with a bad checksum */
net_stats_t ackerr; /* Number of TCP segments with a bad ACK number */
net_stats_t rst; /* Number of received TCP RST (reset) segments */
net_stats_t rexmit; /* Number of retransmitted TCP segments */
net_stats_t syndrop; /* Number of dropped SYNs due to too few
* available connections */
net_stats_t synrst; /* Number of SYNs for closed ports triggering a RST */
};
#endif
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
#endif /* CONFIG_NET_TCP */
#endif /* __INCLUDE_NUTTX_NET_TCP_H */

View File

@ -0,0 +1,131 @@
/* SPDX-License-Identifier: Apache-2.0
* Deterministic raw I/O laboratory: no expected values or pass/fail decisions.
*/
#include "port.h"
static struct net_driver_s device;
static struct tcp_conn_s connection;
static struct iob_s buffer;
static long tick;
static int payload, appsend, listener_enabled;
struct endpoint { struct devif_callback_s *cb; unsigned events; int wakes; };
static struct endpoint endpoints[2];
struct packet { long tick; unsigned flags,length; uint32_t sequence; };
static struct packet packets[256];
static int packet_count;
void net_lock(void) {}
void net_unlock(void) {}
bool netdev_verify(struct net_driver_s *d) { return d == &device; }
long clock_systime_ticks(void) { return tick; }
bool work_available(struct work_s *w) { return !w->pending; }
long work_timeleft(struct work_s *w) { return w->due - tick; }
int work_queue(int q,struct work_s *w,void (*fn)(void *),void *arg,long delay)
{ w->pending=true; w->due=tick+delay; w->worker=fn; w->arg=arg; return 0; }
int work_cancel(int q,struct work_s *w) { w->pending=false; return 0; }
struct tcp_conn_s *tcp_nextconn(struct tcp_conn_s *c) { return c ? NULL : &connection; }
void netdev_txnotify_dev(struct net_driver_s *d) {}
void tcp_ip_select(struct tcp_conn_s *c) {}
uint16_t tcpip_hdrsize(struct tcp_conn_s *c) { return 40; }
bool tcp_should_send_recvwindow(struct tcp_conn_s *c) { return false; }
void tcp_send(struct net_driver_s *d,struct tcp_conn_s *c,uint8_t flags,uint16_t len)
{
if(packet_count >= 256) exit(79);
packets[packet_count++]=(struct packet){tick,flags,len,tcp_getsequence(c->sndseq)};
d->d_len=len;
}
void tcp_synack(struct net_driver_s *d,struct tcp_conn_s *c,uint8_t flags)
{ tcp_send(d,c,flags,tcpip_hdrsize(c)); }
struct tcp_conn_s *tcp_findlistener(void *binding,uint16_t port)
{ return listener_enabled ? &connection : NULL; }
void tcp_free(struct tcp_conn_s *c) {}
int netdev_iob_prepare(struct net_driver_s *d,bool throttled,unsigned int reserve)
{ d->d_iob=&buffer; d->d_appdata=buffer.io_data; return 0; }
void netdev_iob_clear(struct net_driver_s *d) { d->d_iob=NULL; }
struct iob_s *iob_trimhead(struct iob_s *b,unsigned int n)
{ b->io_pktlen-=n; b->io_offset+=n; return b; }
struct iob_s *iob_trimtail(struct iob_s *b,unsigned int n)
{ b->io_pktlen-=n; return b; }
void net_iob_concat(struct iob_s **to,struct iob_s **from)
{ *to=*from; *from=NULL; }
void net_incr32(uint8_t *s,uint16_t n) { tcp_setsequence(s,tcp_getsequence(s)+n); }
void tcp_callback_free(struct tcp_conn_s *c,struct devif_callback_s *cb)
{ devif_conn_callback_free(c->dev,cb,&c->sconn.list,&c->sconn.tail); }
int nxsem_destroy(void *s) { return 0; }
/* An application's waiting socket endpoint. Loss handling stays in tcp_monitor.c. */
static uint16_t socket_event(struct net_driver_s *d,void *arg,uint16_t flags)
{
struct endpoint *e=arg;
e->events|=flags;
if(flags & TCP_DISCONN_EVENTS)
{ e->wakes++; tcp_lost_connection(&connection,e->cb,flags); }
else if(flags & TCP_REXMIT) d->d_sndlen=payload;
else if(flags & TCP_POLL) d->d_sndlen=appsend;
return flags;
}
static void snapshot(void)
{
struct tcp_conn_s *c=&connection;
printf("{\"tick\":%ld,\"state\":%u,\"rto\":%u,\"timer\":%u,\"nrtx\":%u,\"keeptimer\":%u,\"keepretries\":%u,\"sflags\":%u,\"pending\":%d,\"due\":%ld,\"sequence\":%u,\"unacked\":%d,\"events\":[%u,%u],\"wakes\":[%d,%d],\"packets\":[",
tick,c->tcpstateflags,c->rto,c->timer,c->nrtx,c->keeptimer,c->keepretries,
c->sconn.s_flags,c->work.pending,c->work.due,tcp_getsequence(c->sndseq),
c->tx_unacked,endpoints[0].events,endpoints[1].events,endpoints[0].wakes,endpoints[1].wakes);
for(int i=0;i<packet_count;i++)
printf("%s[%ld,%u,%u,%u]",i?",":"",packets[i].tick,packets[i].flags,packets[i].length,packets[i].sequence);
puts("]}");
}
int main(void)
{
unsigned state,unacked,retries,rto,timer,ka,idle,interval,count,kept,seq,rexseq;
unsigned pbytes,abytes,nsockets,delayed,listener;
if(scanf("%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u%u",&state,&unacked,&retries,&rto,&timer,&ka,&idle,&interval,&count,&kept,&seq,&rexseq,&pbytes,&abytes,&nsockets,&delayed,&listener)!=17) return 3;
device.d_flags=IFF_UP; connection.dev=&device;
connection.tcpstateflags=state; connection.tx_unacked=unacked;
connection.nrtx=retries; connection.rto=rto; connection.timer=timer;
connection.keepalive=ka; connection.keepidle=idle; connection.keeptimer=ka?idle:0;
connection.keepintvl=interval; connection.keepcnt=count; connection.keepretries=kept;
connection.sconn.s_flags=_SF_BOUND|_SF_CONNECTED;
connection.rx_unackseg=delayed; connection.mss=1024;
connection.rexmit_seq=rexseq;
tcp_setsequence(connection.sndseq,seq);
payload=pbytes; appsend=abytes; listener_enabled=listener;
devif_callback_init();
struct socket sock={&connection};
if(state==TCP_SYN_SENT) connection.sconn.s_flags|=8;
tcp_start_monitor(&sock);
if(nsockets>2) return 4;
for(unsigned i=0;i<nsockets;i++)
{
struct devif_callback_s *cb=devif_callback_alloc(&device,&connection.sconn.list,&connection.sconn.tail);
if(!cb) return 5;
endpoints[i].cb=cb; cb->priv=&endpoints[i]; cb->event=socket_event;
cb->flags=TCP_POLL|TCP_REXMIT|TCP_DISCONN_EVENTS;
}
netdev_iob_prepare(&device,false,0);
tcp_update_timer(&connection);
snapshot();
char command; long arg;
while(scanf(" %c %ld",&command,&arg)==2)
{
if(command=='A')
{
long target=tick+arg;
int iterations=0;
while(connection.work.pending && connection.work.due<=target)
{
if(++iterations>1024) return 6;
tick=connection.work.due;
void (*worker)(void *)=connection.work.worker;
void *worker_arg=connection.work.arg;
connection.work.pending=false;
worker(worker_arg);
tcp_poll(&device,&connection);
}
tick=target;
}
else if(command=='P') tcp_poll(&device,&connection);
else if(command=='Z') tcp_set_zero_probe(&connection,(uint16_t)arg);
else if(command=='S') tcp_stop_timer(&connection);
else return 7;
snapshot();
}
return 0;
}

View File

@ -0,0 +1,633 @@
/****************************************************************************
* net/devif/devif.h
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2009, 2013-2017 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* This logic was leveraged from uIP which also has a BSD-style license:
*
* Author Adam Dunkels <adam@dunkels.com>
* Copyright (c) 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#ifndef __NET_DEVIF_DEVIF_H
#define __NET_DEVIF_DEVIF_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#ifdef CONFIG_NET
#include <stdint.h>
#include <stdbool.h>
#include <errno.h>
#include <arch/irq.h>
#include <nuttx/net/ip.h>
#include <nuttx/net/netdev.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* The following flags may be set in the set of flags by the lower, device-
* interfacing layer before calling through the socket layer callback. The
* TCP_ACKDATA, XYZ_NEWDATA, and TCP_CLOSE flags may be set at the same time,
* whereas the others are mutually exclusive.
*
* Connection Specific Events: These are events that may be notified
* through callback lists residing in TCP, UDP, or PKT port connection
* structures:
*
* TCP_ACKDATA IN: Signifies that the outstanding data was ACKed and
* the socket layer should send out new data instead
* of retransmitting the last data. (TCP only)
* OUT: Input state must be preserved on output.
*
* TCP_NEWDATA IN: Set to indicate that the peer has sent us new data.
* UDP_NEWDATA OUT: Cleared (only) by the socket layer logic to
* ICMP_NEWDATA indicate that the new data was consumed,
* ICMPv6_NEWDATA suppressing further attempts to process the new
* PKT_NEWDATA data.
* BLUETOOTH_NEWDATA
* IEEE802154_NEWDATA
*
* TCP_SNDACK IN: Not used; always zero
* OUT: Set by the socket layer if the new data was
* consumed and an ACK should be sent in the response.
* (TCP only)
*
* TCP_REXMIT IN: Tells the socket layer to retransmit the data that
* was last sent. (TCP only)
* OUT: Not used
*
* TCP_POLL IN: Used for polling the socket layer. This is
* UDP_POLL provided periodically from the drivers to support
* PKT_POLL (1) timed operations, and (2) to check if the
* BLUETOOTH_POLL socket layer has data that it wants to send.
* IEEE802154_POLL These are socket oriented callbacks where the
* context depends on the specific set.
* OUT: Not used
*
* TCP_BACKLOG IN: There is a new connection in the backlog list set
* up by the listen() command. (TCP only)
* OUT: Not used
*
* TCP_CLOSE IN: The remote host has closed the connection, thus the
* connection has gone away. (TCP only)
* OUT: The socket layer signals that it wants to close the
* connection. (TCP only)
*
* TCP_ABORT IN: The remote host has aborted the connection, thus
* the connection has gone away. (TCP only)
* OUT: The socket layer signals that it wants to abort the
* connection. (TCP only)
*
* TCP_CONNECTED IN: We have got a connection from a remote host and
* have set up a new connection for it, or an active
* connection has been successfully established.
* (TCP only)
* OUT: Not used
*
* TCP_TIMEDOUT IN: The connection has been aborted due to too many
* retransmissions. (TCP only)
* OUT: Not used
*
* Device Specific Events: These are events that may be notified through
* callback lists residing in the network device structure.
*
* ARP_POLL IN: Used for polling the socket layer. This is
* provided periodically from the drivers to support
* (1) timed operations, and (2) to check if the ARP
* layer needs to send an ARP request. This is a
* device oriented event, not associated with a
* socket.
* OUT: Not used
*
* ICMP_POLL IN: Used for polling the socket layer. This is
* provided periodically from the drivers to support
* (1) timed operations, and (2) to check if the ICMP
* layer needs to send an ARP request. This is a
* device oriented event, not associated with a
* socket. This differs from ICMPv6_POLL only in that
* the appdata pointer is set differently.
* OUT: Not used
*
* ICMPv6_POLL IN: Used for polling the socket layer. This is
* provided periodically from the drivers to support
* (1) timed operations, and (2) to check if the ICMP
* layer needs to send an ARP request. This is a
* device oriented event, not associated with a
* socket. This differs from ICMP_POLL only in that
* the appdata pointer is set differently.
* OUT: Not used
*
* IPFWD_POLL IN: Used for polling for forwarded packets layer. This
* is provided periodically from the drivers to
* support to check if there is a packet waiting to be
* forward on the device. This is a device oriented
* event, not associated with a socket. The appdata
* pointer is not used in this case.
* OUT: Not used
*
* NETDEV_DOWN: IN: The network device has been taken down.
* OUT: Not used
*/
/* Bits 0-9: Connection specific event bits */
#define TCP_ACKDATA (1 << 0)
#define TCP_NEWDATA (1 << 1)
#define UDP_NEWDATA TCP_NEWDATA
#define ICMP_NEWDATA TCP_NEWDATA
#define ICMPv6_NEWDATA TCP_NEWDATA
#define BLUETOOTH_NEWDATA TCP_NEWDATA
#define IEEE802154_NEWDATA TCP_NEWDATA
#define PKT_NEWDATA TCP_NEWDATA
#define CAN_NEWDATA TCP_NEWDATA
#define WPAN_NEWDATA TCP_NEWDATA
#define IPFWD_NEWDATA TCP_NEWDATA
#define TCP_SNDACK (1 << 2)
#define TCP_REXMIT (1 << 3)
#define TCP_POLL (1 << 4)
#define UDP_POLL TCP_POLL
#define PKT_POLL TCP_POLL
#define CAN_POLL TCP_POLL
#define BLUETOOTH_POLL TCP_POLL
#define IEEE802154_POLL TCP_POLL
#define WPAN_POLL TCP_POLL
#define TCP_BACKLOG (1 << 5)
#define TCP_CLOSE (1 << 6)
#define TCP_ABORT (1 << 7)
#define TCP_CONNECTED (1 << 8)
#define TCP_TIMEDOUT (1 << 9)
#define TCP_WAITALL (1 << 10)
/* Bits 10-11: Unused, available */
/* Bit 12: Device specific event bits */
#define NETDEV_DOWN (1 << 12)
/* Bits 13-15: Encoded device specific poll events. Unlike connection
* oriented poll events, device related poll events must distinguish
* between what is being polled for since the callbacks all reside in
* the same list in the network device structure.
*/
#define DEVPOLL_SHIFT (13)
#define DEVPOLL_MASK (7 << DEVPOLL_SHIFT)
# define DEVPOLL_NONE (0 << DEVPOLL_SHIFT)
# define ARP_POLL (1 << DEVPOLL_SHIFT)
# define ICMP_POLL (2 << DEVPOLL_SHIFT)
# define ICMPv6_POLL (3 << DEVPOLL_SHIFT)
# define IPFWD_POLL (4 << DEVPOLL_SHIFT)
/* The set of events that and implications to the TCP connection state */
#define TCP_CONN_EVENTS \
(TCP_CLOSE | TCP_ABORT | TCP_CONNECTED | TCP_TIMEDOUT | NETDEV_DOWN)
#define TCP_DISCONN_EVENTS \
(TCP_CLOSE | TCP_ABORT | TCP_TIMEDOUT | NETDEV_DOWN)
/* IPv4/IPv6 Helpers */
#ifdef CONFIG_NET_IPv4
# define DEVIF_IS_IPv4(dev) IFF_IS_IPv4(dev->d_flags)
#else
# define DEVIF_IS_IPv4(dev) (0)
#endif
#ifdef CONFIG_NET_IPv6
# define DEVIF_IS_IPv6(dev) IFF_IS_IPv6(dev->d_flags)
#else
# define DEVIF_IS_IPv6(dev) (0)
#endif
/* There are some helper pointers for accessing the contents of the Ethernet
* headers
*/
#define ETHBUF ((FAR struct eth_hdr_s *)NETLLBUF)
/****************************************************************************
* Public Type Definitions
****************************************************************************/
/* Describes a connection/device event callback interface
*
* nxtconn - Supports a singly linked list that supports connection
* specific event handlers.
* nxtdev - Supports a singly linked list that supports device specific
* event handlers
* event - Provides the address of the callback function entry point.
* pvconn is a pointer to a connection-specific datat structure
* such as struct tcp_conn_s or struct udp_conn_s.
* priv - Holds a reference to socket layer specific data that will
* provided
* flags - Set by the socket layer to inform the lower layer which flags
* are and are not handled by the callback.
*/
struct net_driver_s; /* Forward reference */
typedef CODE uint16_t (*devif_callback_event_t)(FAR struct net_driver_s *dev,
FAR void *pvpriv,
uint16_t flags);
struct devif_callback_s
{
FAR struct devif_callback_s *nxtconn;
FAR struct devif_callback_s *prevconn;
FAR struct devif_callback_s *nxtdev;
FAR devif_callback_event_t event;
FAR void *priv;
uint16_t flags;
uint8_t free_flags;
};
/****************************************************************************
* Public Data
****************************************************************************/
#undef EXTERN
#if defined(__cplusplus)
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
/****************************************************************************
* Name: devif_initialize
*
* Description:
* Perform initialization of the network device interface layer
*
* Input Parameters:
* None
*
* Returned Value:
* None
*
****************************************************************************/
void devif_initialize(void);
/****************************************************************************
* Name: devif_callback_init
*
* Description:
* Configure the pre-allocated callback structures into a free list.
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
void devif_callback_init(void);
/****************************************************************************
* Name: devif_callback_alloc
*
* Description:
* Allocate a callback container from the free list.
*
* If dev is non-NULL, then this function verifies that the device
* reference is still valid and that the device is still UP status. If
* those conditions are not true, this function will fail to allocate the
* callback.
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
FAR struct devif_callback_s *
devif_callback_alloc(FAR struct net_driver_s *dev,
FAR struct devif_callback_s **list_head,
FAR struct devif_callback_s **list_tail);
/****************************************************************************
* Name: devif_conn_callback_free
*
* Description:
* Return a connection/port callback container to the free list.
*
* This function is just a front-end for devif_callback_free(). If the
* dev argument is non-NULL, it will verify that the device reference is
* still valid before attempting to free the callback structure. A
* non-NULL list pointer is assumed to be valid in any case.
*
* The callback structure will be freed in any event.
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
void devif_conn_callback_free(FAR struct net_driver_s *dev,
FAR struct devif_callback_s *cb,
FAR struct devif_callback_s **list_head,
FAR struct devif_callback_s **list_tail);
/****************************************************************************
* Name: devif_dev_callback_free
*
* Description:
* Return a device callback container to the free list.
*
* This function is just a front-end for devif_callback_free(). If the
* de argument is non-NULL, it will verify that the device reference is
* still valid before attempting to free the callback structure. It
* differs from devif_conn_callback_free in that connection/port-related
* connections are also associated with the device and, hence, also will
* not be valid if the device pointer is not valid.
*
* The callback structure will be freed in any event.
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
void devif_dev_callback_free(FAR struct net_driver_s *dev,
FAR struct devif_callback_s *cb);
/****************************************************************************
* Name: devif_conn_event
*
* Description:
* Execute a list of callbacks.
*
* Input Parameters:
* dev - The network device state structure associated with the network
* device that initiated the callback event.
* flags - The bit set of events to be notified.
* list - The list to traverse in performing the notifications
*
* Returned Value:
* The updated flags as modified by the callback functions.
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
uint16_t devif_conn_event(FAR struct net_driver_s *dev, uint16_t flags,
FAR struct devif_callback_s *list);
/****************************************************************************
* Name: devif_dev_event
*
* Description:
* Execute a list of callbacks using the device event chain.
*
* Input Parameters:
* dev - The network device state structure associated with the network
* device that initiated the callback event.
* flags - The bit set of events to be notified.
*
* Returned Value:
* The updated flags as modified by the callback functions.
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
uint16_t devif_dev_event(FAR struct net_driver_s *dev, uint16_t flags);
/****************************************************************************
* Name: devif_send
*
* Description:
* Send data on the current connection.
*
* This function is used to send out a single segment of TCP data. Only
* socket logic that have been invoked by the lower level for event
* processing can send data.
*
* The amount of data that actually is sent out after a call to this
* function is determined by the maximum amount of data TCP allows. The
* network will automatically crop the data so that only the appropriate
* amount of data is sent. The mss field of the TCP connection structure
* can be used to determine the amount of data that actually will be sent.
*
* Note: This function does not guarantee that the sent data will
* arrive at the destination. If the data is lost in the network, the
* TCP socket layer will be invoked with the TCP_REXMIT flag set. The
* socket layer will then have to resend the data using this function.
*
* Input Parameters:
* dev - The network device state structure associated with the network
* device that initiated the callback event.
* buf - A pointer to the data which is to be sent.
* len - The maximum amount of data bytes to be sent.
* offset - Offset of data in buffer.
*
* Returned Value:
* The amount of data sent, or negated ERRNO in case of failure.
*
****************************************************************************/
int devif_send(FAR struct net_driver_s *dev, FAR const void *buf,
int len, int offset);
/****************************************************************************
* Name: devif_iob_send
*
* Description:
* Called from socket logic in response to a xmit or poll request from the
* the network interface driver.
*
* This is identical to calling devif_send() except that the data is
* in an I/O buffer chain, rather than a flat buffer.
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
#ifdef CONFIG_MM_IOB
struct iob_s;
int devif_iob_send(FAR struct net_driver_s *dev, FAR struct iob_s *buf,
unsigned int len, unsigned int offset,
unsigned int target_offset);
#endif
/****************************************************************************
* Name: devif_file_send
*
* Description:
* Called from socket logic in response to a xmit or poll request from the
* the network interface driver.
*
* This is identical to calling devif_file_send() except that the data is
* in a available file handle.
*
* Assumptions:
* Called with the network locked.
*
****************************************************************************/
#ifdef CONFIG_MM_IOB
int devif_file_send(FAR struct net_driver_s *dev, FAR struct file *file,
unsigned int len, unsigned int offset,
unsigned int target_offset);
#endif
/****************************************************************************
* Name: devif_out
*
* Description:
* Common interface to build L2 headers
*
* Assumptions:
* This function is called from the MAC device driver with the network
* locked.
*
****************************************************************************/
void devif_out(FAR struct net_driver_s *dev);
/****************************************************************************
* Name: devif_poll_out
*
* Description:
* Generic callback before device output to build L2 headers before sending
*
* Assumptions:
* This function is called from the MAC device driver with the network
* locked.
*
****************************************************************************/
int devif_poll_out(FAR struct net_driver_s *dev,
devif_poll_callback_t callback);
/****************************************************************************
* Name: devif_is_loopback
*
* Description:
* The function checks the destination address of the packet to see
* whether the target of packet is ourself.
*
* Returned Value:
* true is returned if the packet need loop back to ourself, otherwise
* false is returned.
*
****************************************************************************/
bool devif_is_loopback(FAR struct net_driver_s *dev);
/****************************************************************************
* Name: devif_loopback
*
* Description:
* This function should be called before sending out a packet. The function
* checks the destination address of the packet to see whether the target
* of packet is ourself and then consume the packet directly by calling
* input process functions.
*
* Returned Value:
* Zero is returned if the packet don't loop back to ourself, otherwise
* a non-zero value is returned.
*
****************************************************************************/
int devif_loopback(FAR struct net_driver_s *dev);
/****************************************************************************
* Name: netdev_input
*
* Description:
* This function will copy the flat buffer that does not support
* Scatter/gather to the iob vector buffer.
*
* Compatible with all old flat buffer NICs:
*
* [tcp|udp|icmp|...]ipv[4|6]_data_handler()
* | (iob_concat/append to readahead)
* |
* pkt/ipv[4/6]_in()/...
* |
* |
* netdev_input() // new interface, Scatter/gather flat/iobs
* |
* |
* pkt/ipv[4|6]_input()/...
* |
* |
* NICs io vector receive(Original flat buffer)
*
* Input Parameters:
* callback - Input callback of L3 stack
*
* Returned Value:
* A non-zero copy is returned on success.
*
****************************************************************************/
int netdev_input(FAR struct net_driver_s *dev,
devif_poll_callback_t callback, bool reply);
/****************************************************************************
* Name: devif_get_mtu
*
* Description:
* Get mtu
*
* Parameters:
* dev Ethernet driver device structure
*
* Return:
* return (Maximum packet size - Link layer header size),
* if PMTUD enable return pmtu
****************************************************************************/
uint16_t devif_get_mtu(FAR struct net_driver_s *dev);
#undef EXTERN
#ifdef __cplusplus
}
#endif
#endif /* CONFIG_NET */
#endif /* __NET_DEVIF_DEVIF_H */

View File

@ -0,0 +1,624 @@
/****************************************************************************
* net/devif/devif_callback.c
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET)
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <debug.h>
#include <assert.h>
#include <nuttx/kmalloc.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define DEVIF_CB_DONT_FREE (1 << 0)
#define DEVIF_CB_PEND_FREE (1 << 1)
/****************************************************************************
* Private Data
****************************************************************************/
#if CONFIG_NET_PREALLOC_DEVIF_CALLBACKS > 0
static struct devif_callback_s
g_cbprealloc[CONFIG_NET_PREALLOC_DEVIF_CALLBACKS];
#endif
static FAR struct devif_callback_s *g_cbfreelist = NULL;
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: devif_callback_free
*
* Description:
* Return a callback container to the free list.
*
* Assumptions:
* This function is called with the network locked.
*
****************************************************************************/
static void devif_callback_free(FAR struct net_driver_s *dev,
FAR struct devif_callback_s *cb,
FAR struct devif_callback_s **list_head,
FAR struct devif_callback_s **list_tail)
{
FAR struct devif_callback_s *prev;
FAR struct devif_callback_s *curr;
if (cb)
{
net_lock();
#ifdef CONFIG_DEBUG_FEATURES
/* Check for double freed callbacks */
curr = g_cbfreelist;
while (curr != NULL)
{
DEBUGASSERT(cb != curr);
curr = curr->nxtconn;
}
#endif
/* Remove the callback structure from the data notification list if
* it is supposed to be in the data notification list.
*/
if (list_head)
{
prev = cb->prevconn;
/* Remove the structure from the connection event list */
if (prev)
{
/* The item to be removed is not in the head. */
prev->nxtconn = cb->nxtconn;
if (cb->nxtconn)
{
/* The item to be removed is not in the tail. */
cb->nxtconn->prevconn = prev;
}
}
else
{
/* The item to be removed is in the head. */
*list_head = cb->nxtconn;
if (cb->nxtconn)
{
/* There are more items besides the head item. */
cb->nxtconn->prevconn = NULL;
}
}
if (!cb->nxtconn)
{
/* If the tail item is being removed,
* update the tail pointer.
*/
DEBUGASSERT(list_tail);
*list_tail = prev;
}
}
/* check if the callback structure has DEVIF_CB_DONT_FREE,it indicates
* the callback can't be free immediately,setting DEVIF_CB_PEND_FREE
* flag with the callback,it indicates the callback will be free
* finally
*/
if (cb->free_flags & DEVIF_CB_DONT_FREE)
{
cb->free_flags |= DEVIF_CB_PEND_FREE;
net_unlock();
return;
}
/* Remove the callback structure from the device notification list if
* it is supposed to be in the device notification list.
*/
if (dev != NULL)
{
/* Find the callback structure in the device event list */
for (prev = NULL, curr = dev->d_devcb;
curr != NULL && curr != cb;
prev = curr, curr = curr->nxtdev)
{
}
/* Remove the structure from the device event list */
if (curr != NULL)
{
if (prev)
{
prev->nxtdev = cb->nxtdev;
}
else
{
dev->d_devcb = cb->nxtdev;
}
}
}
/* If this is a preallocated or a batch allocated callback store it in
* the free callbacks list. Else free it.
*/
#if CONFIG_NET_ALLOC_DEVIF_CALLBACKS == 1
if (cb < g_cbprealloc || cb >= (g_cbprealloc +
CONFIG_NET_PREALLOC_DEVIF_CALLBACKS))
{
kmm_free(cb);
}
else
#endif
{
cb->nxtconn = g_cbfreelist;
cb->nxtdev = NULL;
g_cbfreelist = cb;
}
net_unlock();
}
}
/****************************************************************************
* Name: devif_event_trigger
*
* Description:
* Return true if the current set of events should trigger a callback to
* occur.
*
* Input Parameters:
* events - The set of events that has occurred.
* triggers - The set of events that will trigger a callback.
*
****************************************************************************/
static bool devif_event_trigger(uint16_t events, uint16_t triggers)
{
/* The events are divided into a set of individual bits that may be ORed
* together PLUS a field that encodes a single poll event.
*
* First check if any of the individual event bits will trigger the
* callback.
*/
if ((events & triggers & ~DEVPOLL_MASK) != 0)
{
return true;
}
/* No... check the encoded device event. */
if ((events & DEVPOLL_MASK) == (triggers & DEVPOLL_MASK))
{
return (triggers & DEVPOLL_MASK) != 0;
}
/* No.. this event set will not generate the callback */
return false;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: devif_callback_init
*
* Description:
* Configure the pre-allocated callback structures into a free list.
*
* Assumptions:
* Called early in the initialization sequence so that no special
* protection is required.
*
****************************************************************************/
void devif_callback_init(void)
{
#if CONFIG_NET_PREALLOC_DEVIF_CALLBACKS > 0
int i;
for (i = 0; i < CONFIG_NET_PREALLOC_DEVIF_CALLBACKS; i++)
{
g_cbprealloc[i].nxtconn = g_cbfreelist;
g_cbfreelist = &g_cbprealloc[i];
}
#endif
}
/****************************************************************************
* Name: devif_callback_alloc
*
* Description:
* Allocate a callback container from the free list.
*
* If dev is non-NULL, then this function verifies that the device
* reference is still valid and that the device is still UP status. If
* those conditions are not true, this function will fail to allocate the
* callback.
*
* Assumptions:
* This function is called with the network locked.
*
****************************************************************************/
FAR struct devif_callback_s *
devif_callback_alloc(FAR struct net_driver_s *dev,
FAR struct devif_callback_s **list_head,
FAR struct devif_callback_s **list_tail)
{
FAR struct devif_callback_s *ret;
#if CONFIG_NET_ALLOC_DEVIF_CALLBACKS > 0
int i;
#endif
net_lock();
/* Verify that the device pointer is valid, i.e., that it still
* points to a registered network device and also that the network
* device in the UP state.
*/
/* Note: dev->d_flags may be asynchronously changed by netdev_ifdown()
* (in net/netdev/netdev_ioctl.c). Nevertheless, net_lock() / net_unlock()
* are not required in netdev_ifdown() to prevent dev->d_flags from
* asynchronous change here. There is not an issue because net_lock() and
* net_unlock() present inside of devif_dev_event(). That should be enough
* to de-allocate connection callbacks reliably on NETDEV_DOWN event.
*/
if (dev && !(netdev_verify(dev) && (dev->d_flags & IFF_UP) != 0))
{
net_unlock();
return NULL;
}
/* Allocate the callback entry from heap */
#if CONFIG_NET_ALLOC_DEVIF_CALLBACKS > 0
if (g_cbfreelist == NULL)
{
ret = kmm_zalloc(sizeof(struct devif_callback_s) *
CONFIG_NET_ALLOC_DEVIF_CALLBACKS);
if (ret != NULL)
{
for (i = 0; i < CONFIG_NET_ALLOC_DEVIF_CALLBACKS; i++)
{
ret[i].nxtconn = g_cbfreelist;
g_cbfreelist = &ret[i];
}
}
}
#endif
/* Check the head of the free list */
ret = g_cbfreelist;
if (ret)
{
/* Remove the next instance from the head of the free list */
g_cbfreelist = ret->nxtconn;
memset(ret, 0, sizeof(struct devif_callback_s));
/* Add the newly allocated instance to the head of the device event
* list.
*/
if (dev)
{
ret->nxtdev = dev->d_devcb;
dev->d_devcb = ret;
}
/* Add the newly allocated instance to the tail of the specified list */
if (list_head && list_tail)
{
ret->nxtconn = NULL;
ret->prevconn = *list_tail;
if (*list_tail)
{
/* If the list is not empty, add the item to the tail. */
(*list_tail)->nxtconn = ret;
}
else
{
/* If the list is empty, add the first item to the list. */
*list_head = ret;
}
/* Update the tail pointer */
*list_tail = ret;
}
}
#ifdef CONFIG_DEBUG_FEATURES
else
{
nerr("ERROR: Failed to allocate callback\n");
}
#endif
net_unlock();
return ret;
}
/****************************************************************************
* Name: devif_conn_callback_free
*
* Description:
* Return a connection/port callback container to the free list.
*
* This function is just a front-end for devif_callback_free(). If the
* dev argument is non-NULL, it will verify that the device reference is
* still valid before attempting to free the callback structure. A
* non-NULL list pointer is assumed to be valid in any case.
*
* The callback structure will be freed in any event.
*
* Assumptions:
* This function is called with the network locked.
*
****************************************************************************/
void devif_conn_callback_free(FAR struct net_driver_s *dev,
FAR struct devif_callback_s *cb,
FAR struct devif_callback_s **list_head,
FAR struct devif_callback_s **list_tail)
{
/* Check if the device pointer is still valid. It could be invalid if, for
* example, the device were unregistered between the time when the callback
* was allocated and the time when the callback was freed.
*/
if (dev && !netdev_verify(dev))
{
/* The device reference is longer valid */
dev = NULL;
}
/* Then free the callback */
devif_callback_free(dev, cb, list_head, list_tail);
}
/****************************************************************************
* Name: devif_dev_callback_free
*
* Description:
* Return a device callback container to the free list.
*
* This function is just a front-end for devif_callback_free(). If the
* de argument is non-NULL, it will verify that the device reference is
* still valid before attempting to free the callback structure. It
* differs from devif_conn_callback_free in that connection/port-related
* connections are also associated with the device and, hence, also will
* not be valid if the device pointer is not valid.
*
* The callback structure will be freed in any event.
*
* Assumptions:
* This function is called with the network locked.
*
****************************************************************************/
void devif_dev_callback_free(FAR struct net_driver_s *dev,
FAR struct devif_callback_s *cb)
{
FAR struct devif_callback_s **list_head;
FAR struct devif_callback_s **list_tail;
/* Check if the device pointer is still valid. It could be invalid if, for
* example, the device were unregistered between the time when the callback
* was allocated and the time when the callback was freed.
*/
if (dev != NULL && netdev_verify(dev))
{
/* The device reference is valid. Then use the list pointer in the
* device structure as well.
*/
list_head = &dev->d_conncb;
list_tail = &dev->d_conncb_tail;
}
else
{
/* The device reference is longer valid */
dev = NULL;
list_head = NULL;
list_tail = NULL;
}
/* Then free the callback */
devif_callback_free(dev, cb, list_head, list_tail);
}
/****************************************************************************
* Name: devif_conn_event
*
* Description:
* Execute a list of callbacks using the packet event chain.
*
* Input Parameters:
* dev - The network device state structure associated with the network
* device that initiated the callback event.
* flags - The bit set of events to be notified.
* list - The list to traverse in performing the notifications
*
* Returned Value:
* The updated flags as modified by the callback functions.
*
* Assumptions:
* This function is called with the network locked.
*
****************************************************************************/
uint16_t devif_conn_event(FAR struct net_driver_s *dev, uint16_t flags,
FAR struct devif_callback_s *list)
{
FAR struct devif_callback_s *next;
/* Loop for each callback in the list and while there are still events
* set in the flags set.
*/
net_lock();
while (list && flags)
{
/* Save the pointer to the next callback in the lists. This is done
* because the callback action might delete the entry pointed to by
* list.
*/
next = list->nxtconn;
/* Check if this callback handles any of the events in the flag set */
if (list->event != NULL && devif_event_trigger(flags, list->flags))
{
/* Yes.. perform the callback. Actions perform by the callback
* may delete the current list entry or add a new list entry to
* beginning of the list (which will be ignored on this pass)
*/
flags = list->event(dev, list->priv, flags);
}
/* Set up for the next time through the loop */
list = next;
}
net_unlock();
return flags;
}
/****************************************************************************
* Name: devif_dev_event
*
* Description:
* Execute a list of callbacks using the device event chain.
*
* Input Parameters:
* dev - The network device state structure associated with the network
* device that initiated the callback event.
* flags - The bit set of events to be notified.
*
* Returned Value:
* The updated flags as modified by the callback functions.
*
* Assumptions:
* This function is called with the network locked.
*
****************************************************************************/
uint16_t devif_dev_event(FAR struct net_driver_s *dev, uint16_t flags)
{
FAR struct devif_callback_s *cb;
FAR struct devif_callback_s *next;
/* Loop for each callback in the list and while there are still events
* set in the flags set.
*/
net_lock();
for (cb = dev->d_devcb; cb != NULL && flags != 0; cb = next)
{
/* Save the pointer to the next callback in the lists. This is done
* because the callback action might delete the entry pointed to by
* list.
*/
next = cb->nxtdev;
/* Check if this callback handles any of the events in the flag set */
if (cb->event != NULL && devif_event_trigger(flags, cb->flags))
{
cb->free_flags |= DEVIF_CB_DONT_FREE;
/* Yes.. perform the callback. Actions perform by the callback
* may delete the current list entry or add a new list entry to
* beginning of the list (which will be ignored on this pass)
*/
flags = cb->event(dev, cb->priv, flags);
cb->free_flags &= ~DEVIF_CB_DONT_FREE;
/* update the next callback to prevent previously recorded the
* next callback from being deleted
*/
next = cb->nxtdev;
if ((cb->free_flags & DEVIF_CB_PEND_FREE) != 0)
{
cb->free_flags &= ~DEVIF_CB_PEND_FREE;
devif_callback_free(dev, cb, NULL, NULL);
}
}
}
net_unlock();
return flags;
}
#endif /* CONFIG_NET */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,354 @@
/****************************************************************************
* net/tcp/tcp_appsend.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2014 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <inttypes.h>
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/tcp.h>
#include "devif/devif.h"
#include "tcp/tcp.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_appsend
*
* Description:
* Handle application or TCP protocol response. If this function is called
* with dev->d_sndlen > 0, then this is an application attempting to send
* packet.
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP connection structure holding connection information
* result - App result event sent
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
*
****************************************************************************/
void tcp_appsend(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn,
uint16_t result)
{
uint8_t hdrlen;
ninfo("result: %04x d_sndlen: %d conn->tx_unacked: %" PRId32 "\n",
result, dev->d_sndlen, (uint32_t)conn->tx_unacked);
/* Need to update the recv window? */
if (tcp_should_send_recvwindow(conn))
{
result |= TCP_SNDACK;
#ifdef CONFIG_NET_TCP_DELAYED_ACK
conn->rx_unackseg = 0;
#endif
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Did the caller request that an ACK be sent? */
else if ((result & TCP_SNDACK) != 0)
{
/* Yes.. Handle delayed acknowledgments */
/* Reset the ACK timer in any event. */
conn->rx_acktimer = 0;
/* Per RFC 1122: "...in a stream of full-sized segments there
* SHOULD be an ACK for at least every second segment."
*
* NOTES:
* 1. If there is a data payload or other flags to be sent with the
* outgoing packet, then we may as well include the ACK too.
* 2. The RFC refers to full-size segments. It is not clear what
* "full-size" means. Does that mean that the payload is the size
* of the MSS? Payload size is not considered other there being
* a payload or or not. Should there be some special action for
* small payloads of size < MSS?
* 3. Experimentation shows that Windows and Linux behave somewhat
* differently; they delay the ACKs for many more segments (6 or
* more). Delaying for more segments would provide less network
* traffic and better performance but seems non-compliant.
*/
if (conn->rx_unackseg > 0 || dev->d_sndlen > 0 ||
result != TCP_SNDACK)
{
/* Reset the delayed ACK state and send the ACK with this packet. */
conn->rx_unackseg = 0;
}
else
{
/* This is only an ACK and there is no pending delayed ACK and
* no TX data is being sent. Indicate that there is one un-ACKed
* segment and don't send anything now.
*/
conn->rx_unackseg = 1;
return;
}
}
/* If there are data to be sent in the same direction as the ACK before
* the second data packet is received and the delay timer expires, the ACK
* is piggybacked with the data segment and sent immediately.
*/
else if (dev->d_sndlen > 0 && conn->rx_unackseg > 0)
{
result |= TCP_SNDACK;
conn->rx_unackseg = 0;
}
#endif
/* Get the IP header length associated with the IP domain configured for
* this TCP connection.
*/
hdrlen = tcpip_hdrsize(conn);
/* Check If the device went down */
if ((result & NETDEV_DOWN) != 0)
{
/* If so, make sure that the connection is marked closed
* and do not try to send anything.
*/
dev->d_sndlen = 0;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: NETDEV_DOWN\n");
}
/* Check for connection aborted */
else if ((result & TCP_ABORT) != 0)
{
dev->d_sndlen = 0;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
}
/* Check for connection closed */
else if ((result & TCP_CLOSE) != 0)
{
conn->tcpstateflags = TCP_FIN_WAIT_1;
conn->tx_unacked = 1;
conn->nrtx = 0;
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
conn->sndseq_max = tcp_getsequence(conn->sndseq) + 1;
#endif
ninfo("TCP state: TCP_FIN_WAIT_1\n");
dev->d_sndlen = 0;
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
}
/* None of the above */
else
{
/* The application cannot send more than what is allowed by the
* MSS (the minimum of the MSS and the available window).
*/
DEBUGASSERT(dev->d_sndlen <= conn->mss);
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS) || defined(CONFIG_NET_SENDFILE)
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
if (conn->sendfile)
{
#endif
/* If d_sndlen > 0, the application has data to be sent. */
if (dev->d_sndlen > 0)
{
/* Remember how much data we send out now so that we know
* when everything has been acknowledged. Just increment the
* amount of data sent. This will be needed in sequence number
* calculations and we know that this is not a re-transmission.
* Retransmissions do not go through this path.
*/
conn->tx_unacked += dev->d_sndlen;
}
conn->nrtx = 0;
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
}
#endif
#endif
/* Then handle the rest of the operation just as for the rexmit case */
tcp_rexmit(dev, conn, result);
}
}
/****************************************************************************
* Name: tcp_rexmit
*
* Description:
* Handle application retransmission
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP connection structure holding connection information
* result - App result event sent
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
*
****************************************************************************/
void tcp_rexmit(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn,
uint16_t result)
{
uint8_t hdrlen;
ninfo("result: %04x d_sndlen: %d conn->tx_unacked: %" PRId32 "\n",
result, dev->d_sndlen, (uint32_t)conn->tx_unacked);
/* Get the IP header length associated with the IP domain configured for
* this TCP connection.
*/
hdrlen = tcpip_hdrsize(conn);
/* If the application has data to be sent, or if the incoming packet had
* new data in it, we must send out a packet.
*/
#if defined(CONFIG_NET_TCP_WRITE_BUFFERS) && defined(CONFIG_NET_SENDFILE)
if (conn->sendfile)
#endif
{
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS) || defined(CONFIG_NET_SENDFILE)
if ((result & TCP_REXMIT) != 0 &&
dev->d_sndlen > 0 && conn->tx_unacked > 0 &&
conn->rexmit_seq > 0)
{
uint32_t saveseq;
/* According to RFC 6298 (5.4), retransmit the earliest segment
* that has not been acknowledged by the TCP receiver.
*/
saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
tcp_send(dev, conn, TCP_ACK | TCP_PSH, dev->d_sndlen + hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
return;
}
#endif
}
#if defined(CONFIG_NET_TCP_WRITE_BUFFERS)
if (dev->d_sndlen > 0)
#else
if (dev->d_sndlen > 0 && conn->tx_unacked > 0)
#endif
{
uint32_t seq;
/* We always set the ACK flag in response packets adding the length of
* the IP and TCP headers.
*/
tcp_send(dev, conn, TCP_ACK | TCP_PSH, dev->d_sndlen + hdrlen);
/* Advance sndseq */
seq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, seq + dev->d_sndlen);
}
/* If there is no data to send, just send out a pure ACK if one is
* requested.
*/
else if ((result & TCP_SNDACK) != 0)
{
tcp_send(dev, conn, TCP_ACK, hdrlen);
}
/* There is nothing to do -- drop the packet */
else
{
dev->d_len = 0;
}
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,444 @@
/****************************************************************************
* net/tcp/tcp_callback.c
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <string.h>
#include <debug.h>
#include <assert.h>
#include <nuttx/mm/iob.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include "devif/devif.h"
#include "tcp/tcp.h"
#include "utils/utils.h"
#ifdef NET_TCP_HAVE_STACK
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_data_event
*
* Description:
* Handle data that is not accepted by the application because there is no
* listener in place ready to receive the data.
*
* Assumptions:
* - The caller has checked that TCP_NEWDATA is set in flags and that is no
* other handler available to process the incoming data.
* - This function must be called with the network locked.
*
****************************************************************************/
static inline uint16_t
tcp_data_event(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn,
uint16_t flags)
{
uint16_t recvlen;
/* Assume that we will ACK the data. The data will be ACKed if it is
* placed in the read-ahead buffer -OR- if it zero length
*/
flags = (flags & ~TCP_NEWDATA) | TCP_SNDACK;
/* Is there new data? With non-zero length? (Certain connection events
* can have zero-length with TCP_NEWDATA set just to cause an ACK).
*/
if (dev->d_len > 0)
{
ninfo("No listener on connection\n");
/* Save as the packet data as in the read-ahead buffer. NOTE that
* partial packets will not be buffered.
*/
recvlen = tcp_datahandler(dev, conn,
(dev->d_appdata - dev->d_iob->io_data) -
dev->d_iob->io_offset);
net_incr32(conn->rcvseq, recvlen);
}
/* In any event, the new data has now been handled */
dev->d_len = 0;
return flags;
}
/****************************************************************************
* Name: tcp_ofoseg_data_event
*
* Description:
* Handle out-of-order segment to readahead poll.
*
* Assumptions:
* - This function must be called with the network locked.
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_OUT_OF_ORDER
static uint16_t tcp_ofoseg_data_event(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn,
uint16_t flags)
{
FAR struct tcp_ofoseg_s *seg;
uint32_t rcvseq;
int i = 0;
/* Assume that we will ACK the data. The data will be ACKed if it is
* placed in the read-ahead buffer -OR- if it zero length
*/
flags |= TCP_SNDACK;
/* Get the receive sequence number */
rcvseq = tcp_getsequence(conn->rcvseq);
ninfo("TCP OFOSEG rcvseq [%" PRIu32 "]\n", rcvseq);
/* Foreach out-of-order segments */
while (i < conn->nofosegs)
{
seg = &conn->ofosegs[i];
/* rcvseq -->|
* ofoseg |------|
*/
if (rcvseq == seg->left)
{
ninfo("TCP OFOSEG input [%" PRIu32 " : %" PRIu32 " : %u]\n",
seg->left, seg->right, seg->data->io_pktlen);
rcvseq = TCP_SEQ_ADD(rcvseq,
seg->data->io_pktlen);
net_incr32(conn->rcvseq, seg->data->io_pktlen);
net_iob_concat(&conn->readahead, &seg->data);
}
else if (TCP_SEQ_GT(rcvseq, seg->left))
{
/* rcvseq -->|
* ofoseg |------|
*/
if (TCP_SEQ_GTE(rcvseq, seg->right))
{
/* Remove stale segments */
iob_free_chain(seg->data);
seg->data = NULL;
}
/* rcvseq -->|
* ofoseg |------|
*/
else
{
seg->data =
iob_trimhead(seg->data,
TCP_SEQ_SUB(rcvseq, seg->left));
seg->left = rcvseq;
if (seg->data != NULL)
{
ninfo("TCP OFOSEG input "
"[%" PRIu32 " : %" PRIu32 " : %u]\n",
seg->left, seg->right, seg->data->io_pktlen);
rcvseq = TCP_SEQ_ADD(rcvseq,
seg->data->io_pktlen);
net_incr32(conn->rcvseq, seg->data->io_pktlen);
net_iob_concat(&conn->readahead, &seg->data);
}
}
}
/* Rebuild out-of-order pool if segment is consumed */
if (seg->data == NULL)
{
for (; i < conn->nofosegs - 1; i++)
{
conn->ofosegs[i] = conn->ofosegs[i + 1];
}
conn->nofosegs--;
/* Try segments again */
i = 0;
}
else
{
i++;
}
}
return flags;
}
#endif /* CONFIG_NET_TCP_OUT_OF_ORDER */
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_ofoseg_bufsize
*
* Description:
* Calculate the pending size of out-of-order buffer
*
* Input Parameters:
* conn - The TCP connection of interest
*
* Returned Value:
* Total size of out-of-order buffer
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_OUT_OF_ORDER
int tcp_ofoseg_bufsize(FAR struct tcp_conn_s *conn)
{
int total = 0;
int i;
for (i = 0; i < conn->nofosegs; i++)
{
total += conn->ofosegs[i].data->io_pktlen;
}
return total;
}
#endif /* CONFIG_NET_TCP_OUT_OF_ORDER */
/****************************************************************************
* Name: tcp_callback
*
* Description:
* Inform the application holding the TCP socket of a change in state.
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
uint16_t tcp_callback(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn, uint16_t flags)
{
#if defined(CONFIG_NET_TCP_NOTIFIER) || defined(CONFIG_NET_TCP_OUT_OF_ORDER)
uint16_t orig = flags;
#endif
/* Prepare device buffer */
if (dev->d_iob == NULL && netdev_iob_prepare(dev, false, 0) != OK)
{
return 0;
}
/* Preserve the TCP_ACKDATA, TCP_CLOSE, and TCP_ABORT in the response.
* These is needed by the network to handle responses and buffer state.
* The TCP_NEWDATA indication will trigger the ACK response, but must be
* explicitly set in the callback.
*/
ninfo("flags: %04x\n", flags);
/* Perform the data callback. When a data callback is executed from
* 'list', the input flags are normally returned, however, the
* implementation may set one of the following:
*
* TCP_CLOSE - Gracefully close the current connection
* TCP_ABORT - Abort (reset) the current connection on an error that
* prevents TCP_CLOSE from working.
*
* And/Or set/clear the following:
*
* TCP_NEWDATA - May be cleared to indicate that the data was consumed
* and that no further process of the new data should be
* attempted.
* TCP_SNDACK - If TCP_NEWDATA is cleared, then TCP_SNDACK may be set
* to indicate that an ACK should be included in the
* response. (In TCP_NEWDATA is cleared but TCP_SNDACK is
* not set, then dev->d_len should also be cleared).
*/
flags = devif_conn_event(dev, flags, conn->sconn.list);
/* There may be no new data handler in place at them moment that the new
* incoming data is received. If the new incoming data was not handled,
* then either (1) put the unhandled incoming data in the read-ahead
* buffer (if enabled) or (2) suppress the ACK to the data in the hope
* that it will be re-transmitted at a better time.
*/
if ((flags & TCP_NEWDATA) != 0)
{
/* Data was not handled.. dispose of it appropriately */
flags = tcp_data_event(dev, conn, flags);
}
#ifdef CONFIG_NET_TCP_OUT_OF_ORDER
if ((orig & TCP_NEWDATA) != 0 && conn->nofosegs > 0)
{
/* Try out-of-order pool if new data is coming */
flags = tcp_ofoseg_data_event(dev, conn, flags);
}
#endif
/* Check if there is a connection-related event and a connection
* callback.
*/
if ((flags & TCP_CONN_EVENTS) != 0)
{
/* Perform the callback disconnect callbacks */
flags = devif_conn_event(dev, flags, conn->connevents);
}
#ifdef CONFIG_NET_TCP_NOTIFIER
/* Provide notification(s) if the TCP connection has been lost. */
if ((orig & TCP_DISCONN_EVENTS) != 0)
{
tcp_disconnect_signal(conn);
}
#endif
/* Re-prepare the device buffer if d_iob is consumed by the stack */
if (dev->d_iob == NULL)
{
netdev_iob_prepare(dev, false, 0);
}
return flags;
}
/****************************************************************************
* Name: tcp_datahandler
*
* Description:
* Handle data that is not accepted by the application. This may be called
* either (1) from the data receive logic if it cannot buffer the data, or
* (2) from the TCP event logic is there is no listener in place ready to
* receive the data.
*
* Input Parameters:
* conn - A pointer to the TCP connection structure
* buffer - A pointer to the buffer to be copied to the read-ahead
* buffers
* buflen - The number of bytes to copy to the read-ahead buffer.
*
* Returned Value:
* The number of bytes actually buffered is returned. This will be either
* zero or equal to buflen; partial packets are not buffered.
*
* Assumptions:
* - The caller has checked that TCP_NEWDATA is set in flags and that is no
* other handler available to process the incoming data.
* - This function must be called with the network locked.
*
****************************************************************************/
uint16_t tcp_datahandler(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn,
uint16_t offset)
{
FAR struct iob_s *iob = dev->d_iob;
uint16_t buflen;
if (offset > 0)
{
/* Remove 'bufoff' bytes from the beginning of the input I/O chain */
iob = iob_trimhead(iob, offset);
}
/* Trim tail if l3/l4 header has been removed */
if (dev->d_len < iob->io_pktlen)
{
iob = iob_trimtail(iob, iob->io_pktlen - dev->d_len);
}
buflen = iob->io_pktlen;
/* Concat the iob to readahead */
net_iob_concat(&conn->readahead, &iob);
/* Clear device buffer */
netdev_iob_clear(dev);
#ifdef CONFIG_NET_TCP_NOTIFIER
/* Provide notification(s) that additional TCP read-ahead data is
* available.
*/
tcp_readahead_signal(conn);
#endif
ninfo("Buffered %" PRIu16 " bytes\n", buflen);
return buflen;
}
/****************************************************************************
* Name: tcp_callback_cleanup
*
* Description:
* Cleanup data and cb when thread is canceled.
*
* Input Parameters:
* arg - A pointer with conn and callback struct.
*
****************************************************************************/
void tcp_callback_cleanup(FAR void *arg)
{
FAR struct tcp_callback_s *cb = (FAR struct tcp_callback_s *)arg;
nerr("ERROR: pthread is being canceled, need to cleanup cb\n");
tcp_callback_free(cb->tc_conn, cb->tc_cb);
nxsem_destroy(cb->tc_sem);
}
#endif /* NET_TCP_HAVE_STACK */

View File

@ -0,0 +1,131 @@
/****************************************************************************
* net/tcp/tcp_devpoll.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2009, 2016-2017 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/tcp.h>
#include "devif/devif.h"
#include "tcp/tcp.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_poll
*
* Description:
* Poll a TCP connection structure for availability of TX data
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* It is called with the network locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_poll(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
uint16_t result;
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Prepare device buffer */
if (netdev_iob_prepare(dev, false, 0) != OK)
{
return;
}
/* Discard any currently buffered data */
if (conn->timeout)
{
conn->timeout = false;
tcp_timer(dev, conn);
return;
}
dev->d_len = 0;
dev->d_sndlen = 0;
/* Verify that the connection is established. */
if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
/* Set up for the callback. We can't know in advance if the
* application is going to send a IPv4 or an IPv6 packet, so this
* setup may not actually be used.
*/
tcp_ip_select(conn);
/* Perform the callback */
result = tcp_callback(dev, conn, TCP_POLL);
/* Handle the callback response */
tcp_appsend(dev, conn, result);
}
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,400 @@
/****************************************************************************
* net/tcp/tcp_monitor.c
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/net/tcp.h>
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
#ifdef NET_TCP_HAVE_STACK
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
static void tcp_close_connection(FAR struct tcp_conn_s *conn,
uint16_t flags);
static uint16_t tcp_monitor_event(FAR struct net_driver_s *dev,
FAR void *pvpriv, uint16_t flags);
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_close_connection
*
* Description:
* Called when a loss-of-connection event has occurred.
*
* Input Parameters:
* conn The TCP connection structure
* flags Set of connection events events
*
* Returned Value:
* None
*
* Assumptions:
* The caller holds the network lock.
*
****************************************************************************/
static void tcp_close_connection(FAR struct tcp_conn_s *conn, uint16_t flags)
{
/* These loss-of-connection events may be reported:
*
* TCP_CLOSE: The remote host has closed the connection
* TCP_ABORT: The remote host has aborted the connection
* TCP_TIMEDOUT: Connection aborted due to too many retransmissions.
* NETDEV_DOWN: The network device went down
*
* And we need to set these two socket status bits appropriately:
*
* _SF_CONNECTED==1 && _SF_CLOSED==0 - the socket is connected
* _SF_CONNECTED==0 && _SF_CLOSED==1 - the socket was gracefully
* disconnected
* _SF_CONNECTED==0 && _SF_CLOSED==0 - the socket was rudely disconnected
*/
if ((flags & TCP_CLOSE) != 0)
{
/* The peer gracefully closed the connection. Marking the
* connection as disconnected will suppress some subsequent
* ENOTCONN errors from receive. A graceful disconnection is
* not handle as an error but as an "end-of-file"
*/
conn->sconn.s_flags &= ~_SF_CONNECTED;
conn->sconn.s_flags |= _SF_CLOSED;
}
else if ((flags & (TCP_ABORT | TCP_TIMEDOUT | NETDEV_DOWN)) != 0)
{
/* The loss of connection was less than graceful. This will
* (eventually) be reported as an ENOTCONN error.
*/
conn->sconn.s_flags &= ~(_SF_CONNECTED | _SF_CLOSED);
}
}
/****************************************************************************
* Name: tcp_monitor_event
*
* Description:
* Some connection related event has occurred
*
* Input Parameters:
* dev The device which as active when the event was detected.
* pvpriv An instance of struct tcp_conn_s cast to void*
* flags Set of events describing why the callback was invoked
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
*
****************************************************************************/
static uint16_t tcp_monitor_event(FAR struct net_driver_s *dev,
FAR void *pvpriv, uint16_t flags)
{
FAR struct tcp_conn_s *conn = pvpriv;
if (conn != NULL)
{
ninfo("flags: %04x s_flags: %02x\n", flags, conn->sconn.s_flags);
/* TCP_DISCONN_EVENTS: TCP_CLOSE, TCP_ABORT, TCP_TIMEDOUT, or
* NETDEV_DOWN. All loss-of-connection events.
*/
if ((flags & TCP_DISCONN_EVENTS) != 0)
{
tcp_close_connection(conn, flags);
}
/* TCP_CONNECTED: The socket is successfully connected */
else if ((flags & TCP_CONNECTED) != 0)
{
#if 0 /* REVISIT: Assertion fires. Why? */
FAR struct tcp_conn_s *conn = psock->s_conn;
/* Make sure that this is the device bound to the connection */
DEBUGASSERT(conn->dev == NULL || conn->dev == dev);
conn->dev = dev;
#endif
/* If there is no local address assigned to the socket (perhaps
* because it was INADDR_ANY), then assign it the address of the
* connecting device.
*
* TODO: Implement this.
*/
/* Clear the socket error */
_SO_CONN_SETERRNO(conn, OK);
/* Indicate that the socket is now connected */
conn->sconn.s_flags |= (_SF_BOUND | _SF_CONNECTED);
conn->sconn.s_flags &= ~_SF_CLOSED;
}
}
return flags;
}
/****************************************************************************
* Name: tcp_shutdown_monitor
*
* Description:
* Stop monitoring TCP connection changes for a given socket.
*
* Input Parameters:
* conn - The TCP connection of interest
* flags - Indicates the type of shutdown. TCP_CLOSE or TCP_ABORT
*
* Returned Value:
* None
*
* Assumptions:
* The caller holds the network lock (if not, it will be locked momentarily
* by this function).
*
****************************************************************************/
static void tcp_shutdown_monitor(FAR struct tcp_conn_s *conn, uint16_t flags)
{
/* Perform callbacks to assure that all sockets, including dup'ed copies,
* are informed of the loss of connection event.
*/
net_lock();
/* Free all allocated connection event callback structures */
while (conn->connevents != NULL)
{
devif_conn_callback_free(conn->dev, conn->connevents,
&conn->connevents,
&conn->connevents_tail);
}
net_unlock();
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_start_monitor
*
* Description:
* Set up to receive TCP connection state changes for a given socket
*
* Input Parameters:
* psock - The socket of interest
*
* Returned Value:
* On success, tcp_start_monitor returns OK; On any failure,
* tcp_start_monitor will return a negated errno value. The only failure
* that can occur is if the socket has already been closed and, in this
* case, -ENOTCONN is returned.
*
* Assumptions:
* The caller holds the network lock (if not, it will be locked momentarily
* by this function).
*
****************************************************************************/
int tcp_start_monitor(FAR struct socket *psock)
{
FAR struct devif_callback_s *cb;
FAR struct tcp_conn_s *conn;
bool nonblock_conn;
conn = psock->s_conn;
net_lock();
/* Non-blocking connection ? */
nonblock_conn = (conn->tcpstateflags == TCP_SYN_SENT &&
_SS_ISNONBLOCK(conn->sconn.s_flags));
/* Check if the connection has already been closed before any callbacks
* have been registered. (Maybe the connection is lost before accept has
* registered the monitoring callback.)
*/
if (!(conn->tcpstateflags == TCP_ESTABLISHED ||
conn->tcpstateflags == TCP_SYN_RCVD || nonblock_conn))
{
/* Invoke the TCP_CLOSE connection event now */
tcp_shutdown_monitor(conn, TCP_CLOSE);
/* If the peer close the connection before we call accept,
* in order to allow user to read the readahead data,
* return OK.
*/
if (conn->tcpstateflags == TCP_CLOSED ||
conn->tcpstateflags == TCP_LAST_ACK)
{
net_unlock();
return OK;
}
/* And return -ENOTCONN to indicate the monitor was not started
* because the socket was already disconnected.
*/
net_unlock();
return -ENOTCONN;
}
/* Allocate a callback structure that we will use to get callbacks if
* the network goes down.
*/
cb = devif_callback_alloc(conn->dev,
&conn->connevents,
&conn->connevents_tail);
if (cb != NULL)
{
cb->event = tcp_monitor_event;
cb->priv = (FAR void *)conn;
cb->flags = TCP_DISCONN_EVENTS;
/* Monitor the connected event */
if (nonblock_conn)
{
cb->flags |= TCP_CONNECTED;
}
}
net_unlock();
return OK;
}
/****************************************************************************
* Name: tcp_stop_monitor
*
* Description:
* Stop monitoring TCP connection changes for a sockets associated with
* a given TCP connection structure.
*
* Input Parameters:
* conn - The TCP connection of interest
* flags Set of disconnection events
*
* Returned Value:
* None
*
* Assumptions:
* The caller holds the network lock (if not, it will be locked momentarily
* by this function).
*
****************************************************************************/
void tcp_stop_monitor(FAR struct tcp_conn_s *conn, uint16_t flags)
{
DEBUGASSERT(conn != NULL);
/* Stop the network monitor */
tcp_shutdown_monitor(conn, flags);
}
/****************************************************************************
* Name: tcp_lost_connection
*
* Description:
* Called when a loss-of-connection event has been detected by network
* event handling logic. Perform operations like tcp_stop_monitor but (1)
* explicitly mark this socket and (2) disable further callbacks the to the
* event handler.
*
* Input Parameters:
* conn - The TCP connection of interest
* cb - devif callback structure
* flags - Set of connection events events
*
* Returned Value:
* None
*
* Assumptions:
* The caller holds the network lock (if not, it will be locked momentarily
* by this function).
*
****************************************************************************/
void tcp_lost_connection(FAR struct tcp_conn_s *conn,
FAR struct devif_callback_s *cb, uint16_t flags)
{
DEBUGASSERT(conn != NULL);
/* Nullify the callback structure so that recursive callbacks are not
* received by the event handler due to disconnection processing.
*
* NOTE: In a configuration with CONFIG_NET_TCP_WRITE_BUFFERS=y,
* the "semi-permanent" callback structure may have already been
* nullified.
*/
if (cb != NULL)
{
cb->flags = 0;
cb->priv = NULL;
cb->event = NULL;
}
/* Make sure that this socket is explicitly marked. It may not get a
* callback due to the above nullification.
*/
tcp_close_connection(conn, flags);
/* Then stop the network monitor for all sockets. */
tcp_shutdown_monitor(conn, flags);
}
#endif /* NET_TCP_HAVE_STACK */

View File

@ -0,0 +1,255 @@
/****************************************************************************
* net/tcp/tcp_seqno.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2009 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Large parts of this file were leveraged from uIP logic:
*
* Copyright (c) 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <crypto/md5.h>
#include <debug.h>
#include <stdint.h>
#include <stdlib.h>
#include <nuttx/clock.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/netdev.h>
#include "devif/devif.h"
#include "tcp/tcp.h"
/****************************************************************************
* Private Data
****************************************************************************/
/* These fields are used to generate initial TCP sequence numbers */
#ifdef CONFIG_NET_TCP_ISN_RFC6528
/* RFC 6528, Section 3: Key lengths of 128 bits should be adequate. */
static uint32_t g_tcp_isnkey[4];
#else
static uint32_t g_tcpsequence;
#endif
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_isn_rfc6528
*
* Description:
* Calculate the initial sequence number described in RFC 6528.
* ISN = M + F(localip, localport, remoteip, remoteport, secretkey)
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_ISN_RFC6528
static uint32_t tcp_isn_rfc6528(FAR struct tcp_conn_s *conn)
{
const size_t addrlen = net_ip_domain_select(conn->domain,
sizeof(in_addr_t), sizeof(net_ipv6addr_t));
MD5_CTX ctx;
uint32_t digest[MD5_DIGEST_LENGTH / 4];
uint32_t m;
/* Make sure we have a secret key */
if (g_tcp_isnkey[0] == 0)
{
arc4random_buf(g_tcp_isnkey, sizeof(g_tcp_isnkey));
}
/* M is the 4 microsecond timer */
m = TICK2USEC(clock_systime_ticks()) / 4;
/* F() is suggested to be MD5 */
md5init(&ctx);
/* Calculate F(localip, localport, remoteip, remoteport, secretkey) */
md5update(&ctx, net_ip_binding_laddr(&conn->u, conn->domain), addrlen);
md5update(&ctx, &conn->lport, sizeof(conn->lport));
md5update(&ctx, net_ip_binding_raddr(&conn->u, conn->domain), addrlen);
md5update(&ctx, &conn->rport, sizeof(conn->rport));
md5update(&ctx, g_tcp_isnkey, sizeof(g_tcp_isnkey));
md5final((FAR uint8_t *)digest, &ctx);
/* ISN = M + F(localip, localport, remoteip, remoteport, secretkey) */
return m + digest[0];
}
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_setsequence
*
* Description:
* Set the TCP/IP sequence number
*
* Assumptions:
* This function must be called with the network locked if seqno refers
* to a shared, global resource.
*
****************************************************************************/
void tcp_setsequence(FAR uint8_t *seqno, uint32_t value)
{
/* Copy the sequence number in network (big-endian) order */
*seqno++ = value >> 24;
*seqno++ = (value >> 16) & 0xff;
*seqno++ = (value >> 8) & 0xff;
*seqno = value & 0xff;
}
/****************************************************************************
* Name: tcp_getsequence
*
* Description:
* Get the TCP/IP sequence number
*
* Assumptions:
* This function must be called with the network locked if seqno refers
* to a shared, global resource.
*
****************************************************************************/
uint32_t tcp_getsequence(FAR uint8_t *seqno)
{
uint32_t value;
/* Combine the sequence number from network (big-endian) order */
value = (uint32_t)seqno[0] << 24 |
(uint32_t)seqno[1] << 16 |
(uint32_t)seqno[2] << 8 |
(uint32_t)seqno[3];
return value;
}
/****************************************************************************
* Name: tcp_addsequence
*
* Description:
* Add the length to get the next TCP sequence number.
*
* Assumptions:
* This function must be called with the network locked if seqno refers
* to a shared, global resource.
*
****************************************************************************/
uint32_t tcp_addsequence(FAR uint8_t *seqno, uint16_t len)
{
return tcp_getsequence(seqno) + (uint32_t)len;
}
/****************************************************************************
* Name: tcp_initsequence
*
* Description:
* Set the (initial) the TCP/IP sequence number when a TCP connection is
* established.
*
* Assumptions:
* This function must be called with the network locked if seqno refers
* to a shared, global resource.
*
****************************************************************************/
void tcp_initsequence(FAR struct tcp_conn_s *conn)
{
#ifdef CONFIG_NET_TCP_ISN_RFC6528
tcp_setsequence(conn->sndseq, tcp_isn_rfc6528(conn));
#else
/* If g_tcpsequence is already initialized, just copy it */
if (g_tcpsequence == 0)
{
/* Get a random TCP sequence number */
arc4random_buf(&g_tcpsequence, sizeof(uint32_t));
/* Use about half of allowed values */
g_tcpsequence = g_tcpsequence % 2000000000;
/* If the random value is "small" increase it */
if (g_tcpsequence < 1000000000)
{
g_tcpsequence += 1000000000;
}
}
tcp_setsequence(conn->sndseq, g_tcpsequence);
#endif
}
/****************************************************************************
* Name: tcp_nextsequence
*
* Description:
* Increment the TCP/IP sequence number
*
* Assumptions:
* This function must be called with the network locked.
*
****************************************************************************/
void tcp_nextsequence(void)
{
#ifndef CONFIG_NET_TCP_ISN_RFC6528
g_tcpsequence++;
#endif
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,842 @@
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->timer = TCP_RTO << (conn->nrtx > 4 ? 4: conn->nrtx);
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,154 @@
/* SPDX-License-Identifier: Apache-2.0
* Host-side port declarations for the fixed, single-connection laboratory.
* Structure members and protocol constants follow the frozen public headers.
*/
#ifndef TCP_LAB_PORT_H
#define TCP_LAB_PORT_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <stdio.h>
#define FAR
#define CONFIG_NET 1
#define CONFIG_NET_TCP 1
#define CONFIG_NET_TCP_KEEPALIVE 1
#define CONFIG_NET_TCP_DELAYED_ACK 1
#define CONFIG_NET_TCP_MAXRTX 8
#define CONFIG_NET_TCP_MAXSYNRTX 5
#define CONFIG_NET_PREALLOC_DEVIF_CALLBACKS 16
#define CONFIG_NET_ALLOC_DEVIF_CALLBACKS 0
#define NET_TCP_HAVE_STACK 1
#define TCP_RTO 3
#define TCP_RTO_MIN 1
#define TCP_RTO_MAX 240
#define TCP_MAXRTX 8
#define TCP_MAXSYNRTX 5
#define TCP_STATE_MASK 0x0f
#define TCP_CLOSED 0
#define TCP_SYN_RCVD 2
#define TCP_SYN_SENT 3
#define TCP_ESTABLISHED 4
#define TCP_FIN_WAIT_1 5
#define TCP_FIN_WAIT_2 6
#define TCP_CLOSING 7
#define TCP_TIME_WAIT 8
#define TCP_LAST_ACK 9
#define TCP_FIN 1
#define TCP_SYN 2
#define TCP_RST 4
#define TCP_PSH 8
#define TCP_ACK 16
#define TCP_ACKDATA (1<<0)
#define TCP_NEWDATA (1<<1)
#define TCP_SNDACK (1<<2)
#define TCP_REXMIT (1<<3)
#define TCP_POLL (1<<4)
#define TCP_CLOSE (1<<6)
#define TCP_ABORT (1<<7)
#define TCP_CONNECTED (1<<8)
#define TCP_TIMEDOUT (1<<9)
#define NETDEV_DOWN (1<<12)
#define TCP_DISCONN_EVENTS (TCP_CLOSE|TCP_ABORT|TCP_TIMEDOUT|NETDEV_DOWN)
#define TCP_CONN_EVENTS (TCP_DISCONN_EVENTS|TCP_CONNECTED)
#define DEVPOLL_MASK (7<<13)
#define _SF_BOUND 1
#define _SF_CONNECTED 2
#define _SF_CLOSED 4
#define _SS_ISNONBLOCK(f) ((f)&8)
#define _SO_CONN_SETERRNO(c,v) ((void)(c),(void)(v))
#define OK 0
#define IFF_UP 1
#define DEBUGASSERT(x) assert(x)
#define ninfo(...) ((void)0)
#define nerr(...) ((void)0)
#define nwarn(...) ((void)0)
#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)>(b)?(a):(b))
#define DSEC_PER_HSEC 5
#define LPWORK 0
#define HSEC2TICK(x) ((x)*5)
#define TICK2HSEC(x) ((x)/5)
#define TICK2USEC(x) ((x)*100000)
typedef long sclock_t;
struct net_driver_s;
struct devif_callback_s {
struct devif_callback_s *nxtconn,*prevconn,*nxtdev;
uint16_t flags; uint8_t free_flags;
uint16_t (*event)(struct net_driver_s *,void *,uint16_t);
void *priv;
};
struct iob_s { uint8_t io_data[4096]; int io_offset; uint16_t io_pktlen; };
struct work_s { bool pending; long due; void (*worker)(void *); void *arg; };
struct net_driver_s {
uint16_t d_len,d_sndlen; uint8_t *d_appdata; struct iob_s *d_iob;
unsigned int d_flags;
struct devif_callback_s *d_devcb,*d_conncb,*d_conncb_tail;
};
struct tcp_conn_s {
struct { struct devif_callback_s *list,*tail; uint8_t s_flags; } sconn;
struct net_driver_s *dev;
struct devif_callback_s *connevents,*connevents_tail;
struct work_s work;
uint8_t rto,timer,nrtx,tcpstateflags,rx_unackseg,rx_acktimer;
bool timeout,keepalive,zero_probe;
uint32_t keeptimer,keepidle,keepintvl;
uint8_t keepcnt,keepretries;
int32_t tx_unacked;
uint8_t sndseq[4],rcvseq[4];
uint32_t rexmit_seq;
uint16_t mss,lport;
int crefs,u;
struct iob_s *readahead;
};
struct socket { struct tcp_conn_s *s_conn; };
struct tcp_callback_s { struct tcp_conn_s *tc_conn; struct devif_callback_s *tc_cb; void *tc_sem; };
void net_lock(void); void net_unlock(void);
bool netdev_verify(struct net_driver_s *);
void devif_callback_init(void);
struct devif_callback_s *devif_callback_alloc(struct net_driver_s *,struct devif_callback_s **,struct devif_callback_s **);
void devif_conn_callback_free(struct net_driver_s *,struct devif_callback_s *,struct devif_callback_s **,struct devif_callback_s **);
uint16_t devif_conn_event(struct net_driver_s *,uint16_t,struct devif_callback_s *);
int tcp_start_monitor(struct socket *);
void tcp_stop_monitor(struct tcp_conn_s *,uint16_t);
void tcp_lost_connection(struct tcp_conn_s *,struct devif_callback_s *,uint16_t);
uint16_t tcp_callback(struct net_driver_s *,struct tcp_conn_s *,uint16_t);
uint16_t tcp_datahandler(struct net_driver_s *,struct tcp_conn_s *,uint16_t);
void tcp_poll(struct net_driver_s *,struct tcp_conn_s *);
void tcp_timer(struct net_driver_s *,struct tcp_conn_s *);
void tcp_appsend(struct net_driver_s *,struct tcp_conn_s *,uint16_t);
void tcp_rexmit(struct net_driver_s *,struct tcp_conn_s *,uint16_t);
void tcp_update_timer(struct tcp_conn_s *);
void tcp_update_retrantimer(struct tcp_conn_s *,int);
void tcp_update_keeptimer(struct tcp_conn_s *,int);
void tcp_stop_timer(struct tcp_conn_s *);
void tcp_set_zero_probe(struct tcp_conn_s *,uint16_t);
void tcp_send(struct net_driver_s *,struct tcp_conn_s *,uint8_t,uint16_t);
void tcp_synack(struct net_driver_s *,struct tcp_conn_s *,uint8_t);
void tcp_ip_select(struct tcp_conn_s *);
uint16_t tcpip_hdrsize(struct tcp_conn_s *);
bool tcp_should_send_recvwindow(struct tcp_conn_s *);
struct tcp_conn_s *tcp_nextconn(struct tcp_conn_s *);
struct tcp_conn_s *tcp_findlistener(void *,uint16_t);
void tcp_free(struct tcp_conn_s *);
void tcp_nextsequence(void);
void tcp_setsequence(uint8_t *,uint32_t);
uint32_t tcp_getsequence(uint8_t *);
void net_incr32(uint8_t *,uint16_t);
void netdev_txnotify_dev(struct net_driver_s *);
bool work_available(struct work_s *);
long work_timeleft(struct work_s *);
int work_queue(int,struct work_s *,void (*)(void *),void *,long);
int work_cancel(int,struct work_s *);
long clock_systime_ticks(void);
int netdev_iob_prepare(struct net_driver_s *,bool,unsigned int);
void netdev_iob_clear(struct net_driver_s *);
struct iob_s *iob_trimhead(struct iob_s *,unsigned int);
struct iob_s *iob_trimtail(struct iob_s *,unsigned int);
void net_iob_concat(struct iob_s **,struct iob_s **);
void tcp_callback_free(struct tcp_conn_s *,struct devif_callback_s *);
int nxsem_destroy(void *);
#endif

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1 @@
#include "port.h"

View File

@ -0,0 +1,2 @@
4 0 0 3 0 0 100 10 3 0 1000 900 0 8 1 0 0
P 0

View File

@ -0,0 +1,849 @@
/****************************************************************************
* net/tcp/tcp_timer.c
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (C) 2007-2010, 2015-2016, 2018, 2020 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Adapted for NuttX from logic in uIP which also has a BSD-like license:
*
* Original author Adam Dunkels <adam@dunkels.com>
* Copyright () 2001-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP)
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <time.h>
#include <stdlib.h>
#include <nuttx/net/netconfig.h>
#include <nuttx/net/net.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/netstats.h>
#include <nuttx/net/tcp.h>
#include "netdev/netdev.h"
#include "devif/devif.h"
#include "socket/socket.h"
#include "tcp/tcp.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Per RFC 1122: "... an ACK should not be excessively delayed; in
* particular, the delay MUST be less than 0.5 seconds ..."
*
* NOTE: We only have 0.5 timing resolution here so the delay will be
* between 0.5 and 1.0 seconds, and may be delayed further, depending on the
* polling rate of the the driver (often 1 second).
*/
#define ACK_DELAY (1)
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_get_timeout
*
* Description:
* Gets the time of the next timeout
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* int - The time required for the next expiry (units: half-seconds)
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
static int tcp_get_timeout(FAR struct tcp_conn_s *conn)
{
int timeout = conn->timer;
#ifdef CONFIG_NET_TCP_KEEPALIVE
if (timeout == 0)
{
/* The conn->keeptimer units is decisecond and the timeout
* units is half-seconds, therefore they need to be unified.
*/
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
else if (conn->keeptimer > 0 && timeout > conn->keeptimer / DSEC_PER_HSEC)
{
timeout = conn->keeptimer / DSEC_PER_HSEC;
}
#endif
return timeout;
}
/****************************************************************************
* Name: tcp_timer_expiry
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
* Restart a TCP timer if need to
*
* Input Parameters:
* arg - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* arg is not NULL.
* The connection (arg) is bound to the polling device (dev).
*
****************************************************************************/
static void tcp_timer_expiry(FAR void *arg)
{
FAR struct tcp_conn_s *conn = NULL;
net_lock();
while ((conn = tcp_nextconn(conn)) != NULL)
{
if (conn == arg)
{
conn->timeout = true;
netdev_txnotify_dev(conn->dev);
break;
}
}
net_unlock();
}
/****************************************************************************
* Name: tcp_xmit_probe
*
* Description:
* TCP retransmission probe packet
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* dev is not NULL.
* conn is not NULL.
*
****************************************************************************/
static void tcp_xmit_probe(FAR struct net_driver_s *dev,
FAR struct tcp_conn_s *conn)
{
/* And send the probe.
* The packet we send must have these properties:
*
* - TCP_ACK flag (only) is set.
* - Sequence number is the sequence number of
* previously ACKed data, i.e., the expected
* sequence number minus one.
*
* tcp_send() will send the TCP sequence number as
* conn->sndseq. Rather than creating a new
* interface, we spoof tcp_end() here:
*/
uint16_t hdrlen = tcpip_hdrsize(conn);
uint32_t saveseq = tcp_getsequence(conn->sndseq);
tcp_setsequence(conn->sndseq, saveseq - 1);
tcp_send(dev, conn, TCP_ACK, hdrlen);
tcp_setsequence(conn->sndseq, saveseq);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: tcp_update_timer
*
* Description:
* Update the TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_timer(FAR struct tcp_conn_s *conn)
{
sclock_t timeout = tcp_get_timeout(conn);
if (timeout > 0)
{
#ifdef CONFIG_NET_SOLINGER
/* Re-update tcp timeout */
if (conn->ltimeout != 0)
{
sclock_t ticks = conn->ltimeout - clock_systime_ticks();
if (ticks <= 0)
{
timeout = 0;
}
else if (timeout > TICK2HSEC(ticks))
{
timeout = TICK2HSEC(ticks);
}
}
#endif
if (work_available(&conn->work) ||
TICK2HSEC(work_timeleft(&conn->work)) != timeout)
{
work_queue(LPWORK, &conn->work, tcp_timer_expiry,
conn, HSEC2TICK(timeout));
}
}
else
{
work_cancel(LPWORK, &conn->work);
}
}
/****************************************************************************
* Name: tcp_update_retrantimer
*
* Description:
* Update the retransmit TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_update_retrantimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->timer = timeout;
tcp_update_timer(conn);
}
/****************************************************************************
* Name: tcp_update_keeptimer
*
* Description:
* Update the keeplive TCP timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* timeout - Time for the next timeout
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
#ifdef CONFIG_NET_TCP_KEEPALIVE
void tcp_update_keeptimer(FAR struct tcp_conn_s *conn, int timeout)
{
conn->keeptimer = timeout;
tcp_update_timer(conn);
}
#endif
/****************************************************************************
* Name: tcp_stop_timer
*
* Description:
* Stop TCP timer for the provided TCP connection
* When the connection is closed
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_stop_timer(FAR struct tcp_conn_s *conn)
{
work_cancel(LPWORK, &conn->work);
}
/****************************************************************************
* Name: tcp_set_zero_probe
*
* Description:
* Update the TCP probe timer for the provided TCP connection,
* The timeout is accurate
*
* Input Parameters:
* conn - The TCP "connection" to poll for TX data
* flags - Set of connection events
*
* Returned Value:
* None
*
* Assumptions:
* conn is not NULL.
*
****************************************************************************/
void tcp_set_zero_probe(FAR struct tcp_conn_s *conn, uint16_t flags)
{
if ((conn->tcpstateflags & TCP_ESTABLISHED) &&
((flags & TCP_NEWDATA) == 0) && conn->tx_unacked <= 0 &&
(flags & (TCP_POLL | TCP_REXMIT | TCP_ACKDATA)) &&
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
!(sq_empty(&conn->write_q)) &&
#endif
!conn->timeout && !conn->zero_probe)
{
tcp_update_retrantimer(conn, TCP_RTO_MIN);
conn->zero_probe = true;
}
}
/****************************************************************************
* Name: tcp_timer
*
* Description:
* Handle a TCP timer expiration for the provided TCP connection
*
* Input Parameters:
* dev - The device driver structure to use in the send operation
* conn - The TCP "connection" to poll for TX data
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked.
* dev is not NULL.
* conn is not NULL.
* The connection (conn) is bound to the polling device (dev).
*
****************************************************************************/
void tcp_timer(FAR struct net_driver_s *dev, FAR struct tcp_conn_s *conn)
{
int hsec = tcp_get_timeout(conn);
uint16_t result;
uint8_t hdrlen;
/* NOTE: It is important to decrease conn->timer at "hsec" pace,
* not faster. Excessive (false) decrements of conn->timer are not allowed
* here. Otherwise, it breaks TCP timings and leads to TCP spurious
* retransmissions and other issues due to premature timeouts.
*/
DEBUGASSERT(dev != NULL && conn != NULL && dev == conn->dev);
/* Set up for the callback. We can't know in advance if the application
* is going to send a IPv4 or an IPv6 packet, so this setup may not
* actually be used. Furthermore, the TCP logic is required to call
* tcp_ip_select() prior to sending any packets.
* We will try to set the correct value here basic on the binding of
* the connection.
*/
tcp_ip_select(conn);
hdrlen = tcpip_hdrsize(conn);
/* Increase the TCP sequence number */
tcp_nextsequence();
/* Reset the length variables. */
dev->d_len = 0;
dev->d_sndlen = 0;
if (conn->tcpstateflags == TCP_CLOSED)
{
/* Nothing to be done */
return;
}
#ifdef CONFIG_NET_SOLINGER
/* Send reset immediately if linger timeout */
if (conn->ltimeout != 0 &&
((sclock_t)(conn->ltimeout - clock_systime_ticks()) <= 0))
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
else
#endif
/* Check if the connection is in a state in which we simply wait
* for the connection to time out. If so, we increase the
* connection's timer and remove the connection if it times
* out.
*/
if (conn->tcpstateflags == TCP_TIME_WAIT ||
conn->tcpstateflags == TCP_FIN_WAIT_2)
{
/* Check if the timer exceeds the timeout value */
if (conn->timer <= hsec)
{
/* Set the timer to zero value */
conn->timer = 0;
conn->tcpstateflags = TCP_CLOSED;
/* Notify upper layers about the timeout */
tcp_callback(dev, conn, TCP_TIMEDOUT);
ninfo("TCP state: TCP_CLOSED\n");
}
else
{
/* No timeout. Just update the decremented timer */
conn->timer -= hsec;
}
}
else if (conn->tcpstateflags != TCP_CLOSED)
{
/* If the connection has outstanding data, we increase the connection's
* timer and see if it has reached the RTO value in which case we
* retransmit.
*/
if (conn->tx_unacked > 0)
{
/* The connection has outstanding data */
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Will decrement to zero */
conn->timer = 0;
/* Check for a timeout on connection in the TCP_SYN_RCVD state.
* On such timeouts, we would normally resend the SYNACK until
* the ACK is received, completing the 3-way handshake. But if
* the retry count elapsed, then we must assume that no ACK is
* forthcoming and terminate the attempted connection.
*/
if (conn->tcpstateflags == TCP_SYN_RCVD &&
conn->nrtx >= TCP_MAXSYNRTX)
{
FAR struct tcp_conn_s *listener;
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_SYN_RCVD->TCP_CLOSED\n");
/* Find the listener for this connection. */
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
listener = tcp_findlistener(&conn->u, conn->lport,
conn->domain);
#else
listener = tcp_findlistener(&conn->u, conn->lport);
#endif
if (listener != NULL)
{
/* We call tcp_callback() for the connection with
* TCP_TIMEDOUT to inform the listener that the
* connection has timed out.
*/
tcp_callback(dev, listener, TCP_TIMEDOUT);
}
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
/* Finally, we must free this TCP connection structure */
conn->crefs = 0;
tcp_free(conn);
return;
}
/* Otherwise, check for a timeout on an established connection.
* If the retry count is exceeded in this case, we should
* close the connection.
*/
else if (
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
# ifdef CONFIG_NET_SENDFILE
(!conn->sendfile && conn->expired > 0) ||
(conn->sendfile && conn->nrtx >= TCP_MAXRTX) ||
# else
conn->expired > 0 ||
# endif
#else
conn->nrtx >= TCP_MAXRTX ||
#endif
(conn->tcpstateflags == TCP_SYN_SENT &&
conn->nrtx >= TCP_MAXSYNRTX)
)
{
conn->tcpstateflags = TCP_CLOSED;
ninfo("TCP state: TCP_CLOSED\n");
/* We call tcp_callback() with TCP_TIMEDOUT to
* inform the application that the connection has
* timed out.
*/
tcp_callback(dev, conn, TCP_TIMEDOUT);
/* We also send a reset packet to the remote host. */
tcp_send(dev, conn, TCP_RST | TCP_ACK, hdrlen);
goto done;
}
/* Exponential backoff. */
conn->rto = TCP_RTO;
for (unsigned int shift = 0; shift < conn->nrtx && shift < 4; ++shift)
{
conn->rto *= 2;
}
conn->timer = conn->rto;
tcp_update_timer(conn);
conn->nrtx++;
/* Ok, so we need to retransmit. We do this differently
* depending on which state we are in. In ESTABLISHED, we
* call upon the application so that it may prepare the
* data for the retransmit. In SYN_RCVD, we resend the
* SYNACK that we sent earlier and in LAST_ACK we have to
* retransmit our FINACK.
*/
#ifdef CONFIG_NET_STATISTICS
g_netstats.tcp.rexmit++;
#endif
switch (conn->tcpstateflags & TCP_STATE_MASK)
{
case TCP_SYN_RCVD:
/* In the SYN_RCVD state, we should retransmit our
* SYNACK.
*/
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_ACK | TCP_SYN);
goto done;
case TCP_SYN_SENT:
/* In the SYN_SENT state, we retransmit out SYN. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_synack(dev, conn, TCP_SYN);
goto done;
case TCP_ESTABLISHED:
/* In the ESTABLISHED state, we call upon the application
* to do the actual retransmit after which we jump into
* the code for sending out the packet.
*/
result = tcp_callback(dev, conn, TCP_REXMIT);
tcp_rexmit(dev, conn, result);
#ifdef CONFIG_NET_TCP_CC_NEWRENO
/* If conn is TCP_INFR, it should enter to slow start */
if (conn->flags & TCP_INFR)
{
conn->flags &= ~TCP_INFR;
}
/* update the max_cwnd */
conn->max_cwnd = (conn->max_cwnd + 7 * conn->cwnd) >> 3;
/* reset cwnd and ssthresh, refers to RFC5861. */
conn->ssthresh =
MAX(conn->tx_unacked / 2, 2 * conn->mss);
conn->cwnd = conn->mss;
#endif
goto done;
case TCP_FIN_WAIT_1:
case TCP_CLOSING:
case TCP_LAST_ACK:
/* In all these states we should retransmit a FINACK. */
#if !defined(CONFIG_NET_TCP_WRITE_BUFFERS)
tcp_setsequence(conn->sndseq, conn->rexmit_seq);
#else
/* REVISIT for the buffered mode */
#endif
tcp_send(dev, conn, TCP_FIN | TCP_ACK, hdrlen);
goto done;
}
}
}
/* The connection does not have outstanding data. Check if the TCP
* connection has been established.
*/
else if ((conn->tcpstateflags & TCP_STATE_MASK) == TCP_ESTABLISHED)
{
#ifdef CONFIG_NET_TCP_KEEPALIVE
/* Is this an established connected with KeepAlive enabled? */
if (conn->keepalive)
{
/* Yes... has the idle period elapsed with no data or ACK
* received from the remote peer?
*/
if (conn->keeptimer > hsec * DSEC_PER_HSEC)
{
/* Will not yet decrement to zero */
conn->keeptimer -= hsec * DSEC_PER_HSEC;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->keepretries >= conn->keepcnt)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
tcp_callback(conn->dev, conn, TCP_ABORT);
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->keeptimer = conn->keepintvl;
conn->keepretries++;
}
goto done;
}
}
#endif
/* Is this an established connected with
* Zero window probe enabled?
*/
if (conn->zero_probe)
{
if (conn->timer > hsec)
{
/* Will not yet decrement to zero */
conn->timer -= hsec;
}
else
{
/* Yes.. Has the retry count expired? */
if (conn->nrtx >= TCP_MAXRTX)
{
/* Yes... stop the network monitor, closing the
* connection and all sockets associated with the
* connection.
*/
conn->zero_probe = false;
tcp_stop_monitor(conn, TCP_ABORT);
}
else
{
tcp_xmit_probe(dev, conn);
#ifdef CONFIG_NET_TCP_WRITE_BUFFERS
/* Increment the un-ACKed sequence number */
conn->sndseq_max++;
#endif
/* Update for the next probe */
conn->nrtx++;
conn->timer = MIN((TCP_RTO_MIN << conn->nrtx),
TCP_RTO_MAX);
}
goto done;
}
}
#ifdef CONFIG_NET_TCP_DELAYED_ACK
/* Handle delayed acknowledgments. Is there a segment with a
* delayed acknowledgment?
*/
if (conn->rx_unackseg > 0)
{
/* Increment the ACK delay. */
conn->rx_acktimer += hsec;
/* Per RFC 1122: "...an ACK should not be excessively
* delayed; in particular, the delay must be less than
* 0.5 seconds..."
*/
if (conn->rx_acktimer >= ACK_DELAY)
{
/* Reset the delayed ACK state and send the ACK
* packet.
*/
conn->rx_unackseg = 0;
conn->rx_acktimer = 0;
tcp_synack(dev, conn, TCP_ACK);
goto done;
}
}
#endif
/* There was no need for a retransmission and there was no
* need to probe the remote peer and there was no need to
* send a delayed ACK. We poll the application for new
* outgoing data.
*/
result = tcp_callback(dev, conn, TCP_POLL);
tcp_appsend(dev, conn, result);
goto done;
}
}
/* Nothing to be done */
dev->d_len = 0;
done:
tcp_update_timer(conn);
}
#endif /* CONFIG_NET && CONFIG_NET_TCP */

View File

@ -0,0 +1,130 @@
"""Run an imported Bos-qiao check.py unchanged; candidate processes run as UID 65534."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
GRADER = Path(__file__).resolve().parent
BLOCKED = "isolation-blocked.txt"
GUARD = 86
# Runs the original check unchanged as the trusted user. In isolation mode every child process drops to
# UID 65534 and every mkdtemp scratch is handed to it; an audit hook stops the check if candidate code
# would run inside this process. Failing child processes also copy their stderr tail out for private triage.
CHECK = (
"import os, runpy, subprocess, sys, tempfile\n"
"isolated, sys.argv = sys.argv[1] == '1', sys.argv[2:]\n"
"untrusted = [os.path.realpath(sys.argv[1])]\n"
"def inside(path):\n"
" path = os.path.realpath(str(path))\n"
" return any(path == root or path.startswith(root + os.sep) for root in untrusted)\n"
"spawns = ('os.system', 'os.exec', 'os.spawn', 'os.fork', 'os.forkpty', 'os.posix_spawn') if isolated else ()\n"
"def guard(event, args):\n"
" if (event in spawns or event == 'exec' and inside(getattr(args[0], 'co_filename', '')) or\n"
" event == 'ctypes.dlopen' and args[0] and inside(args[0]) or\n"
" event == 'import' and any(inside(entry or '.') for entry in sys.path)):\n"
" sys.__stderr__.write('rollout-guard: ' + event + '\\n')\n"
" sys.__stderr__.flush()\n"
" os._exit(%d)\n"
"mkdtemp = tempfile.mkdtemp\n"
"def scratch(*args, **kwargs):\n"
" path = mkdtemp(*args, **kwargs)\n"
" untrusted.append(os.path.realpath(path))\n"
" if isolated:\n"
" os.chown(path, 65534, 65534)\n"
" return path\n"
"tempfile.mkdtemp = scratch\n"
"popen = subprocess.Popen.__init__\n"
"def drop(self, *args, **kwargs):\n"
" if isolated:\n"
" kwargs.update(user=65534, group=65534, extra_groups=[])\n"
" popen(self, *args, **kwargs)\n"
"subprocess.Popen.__init__ = drop\n"
"real = subprocess.run\n"
"def run(*args, **kwargs):\n"
" result = real(*args, **kwargs)\n"
" if result.returncode and result.stderr:\n"
" tail = result.stderr if isinstance(result.stderr, str) else result.stderr.decode('utf-8', 'replace')\n"
" sys.__stderr__.write(tail[-2000:] + '\\n')\n"
" return result\n"
"subprocess.run = run\n"
"sys.addaudithook(guard)\n"
"runpy.run_path(sys.argv[0], run_name='__main__')\n" % GUARD)
class UnsupportedEnvironment(RuntimeError):
pass
def candidate_user():
os.setgroups([])
os.setgid(65534)
os.setuid(65534)
def isolation():
if os.environ.get("ROLLOUT_GRADE_ISOLATION") != "uid65534":
return None
if sys.platform != "linux" or os.geteuid() != 0:
raise UnsupportedEnvironment("isolated grader requires a Linux root supervisor")
probe = (
"from pathlib import Path\n"
"try: Path('/grader/verify.py').read_bytes()\n"
"except PermissionError: raise SystemExit(0)\n"
"raise SystemExit(1)\n"
)
try:
result = subprocess.run([sys.executable, "-I", "-c", probe],
capture_output=True, timeout=10, preexec_fn=candidate_user)
except subprocess.SubprocessError as error:
raise UnsupportedEnvironment("candidate identity could not be isolated") from error
if result.returncode != 0:
raise UnsupportedEnvironment("candidate can read the private grader or isolation probe failed")
return candidate_user
def verify(candidate):
if (GRADER / BLOCKED).exists():
raise UnsupportedEnvironment("isolation blocked: " + (GRADER / BLOCKED).read_text().strip()[:200])
isolated = isolation() is not None
if shutil.which("gcc") is None:
raise UnsupportedEnvironment("C compiler unavailable")
with tempfile.TemporaryDirectory(prefix="bos-grade-") as temporary:
root = Path(temporary)
work, grader = root / "work", root / "grader"
shutil.copytree(candidate, work, symlinks=True)
shutil.copytree(GRADER, grader, ignore=lambda folder, names: ["verify.py"] if Path(folder) == GRADER else [])
if isolated:
os.chmod(root, 0o711)
os.chmod(grader, 0o700)
for path in (work, *work.rglob("*")):
os.lchown(path, 65534, 65534)
# shortcut: the check runs as root and follows symlinks a child plants in shared scratch directories;
# upgrade by running the check under its own unprivileged UID once a setuid helper is available.
completed = subprocess.run([sys.executable, "-I", "-B", "-c", CHECK, "1" if isolated else "0",
str(grader / "check.py"), str(work)],
cwd=root, capture_output=True, text=True, timeout=100)
# grade.stderr stays on the trusted side with the archive; it may quote hidden test lines.
sys.stderr.write(completed.stderr[-4000:])
if completed.returncode == GUARD and "rollout-guard: " in completed.stderr:
raise UnsupportedEnvironment("isolation blocked: the check would run candidate code in the grader process")
lines = completed.stdout.splitlines()
if completed.returncode == 0 and lines[-1:] == ["PASS"]:
return {"status": "PASS", "checks": 1}
return {"status": "FAIL", "checks": 1, "reason": (lines[-1] if lines else "no checker output")[:300]}
if __name__ == "__main__":
try:
result = verify(Path(sys.argv[1]))
except UnsupportedEnvironment as error:
result = {"status": "UNVERIFIED", "checks": 0, "reason": str(error)}
except subprocess.TimeoutExpired:
result = {"status": "FAIL", "checks": 1, "reason": "timeout"}
except Exception as error:
result = {"status": "INFRA_ERROR", "checks": 0, "reason": str(error)}
print(json.dumps(result, sort_keys=True))
sys.exit({"PASS": 0, "FAIL": 1}.get(result["status"], 2))

View File

@ -0,0 +1,505 @@
/*
* Copyright (c) 2020 Tobias Svehagen
* Copyright (c) 2023, Meta
* Copyright (c) 2024, Tenstorrent AI ULC
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <zephyr/net/socket.h>
#include <zephyr/posix/fcntl.h>
#include <zephyr/zvfs/eventfd.h>
#include <zephyr/sys/bitarray.h>
#include <zephyr/sys/fdtable.h>
#include <zephyr/sys/math_extras.h>
#define ZVFS_EFD_IN_USE 0x1
#define ZVFS_EFD_FLAGS_SET (ZVFS_EFD_SEMAPHORE | ZVFS_EFD_NONBLOCK)
struct zvfs_eventfd {
struct k_poll_signal read_sig;
struct k_poll_signal write_sig;
struct k_spinlock lock;
zvfs_eventfd_t cnt;
int flags;
};
static ssize_t zvfs_eventfd_rw_op(void *obj, void *buf, size_t sz,
int (*op)(struct zvfs_eventfd *efd, zvfs_eventfd_t *value));
SYS_BITARRAY_DEFINE_STATIC(efds_bitarray, CONFIG_ZVFS_EVENTFD_MAX);
static struct zvfs_eventfd efds[CONFIG_ZVFS_EVENTFD_MAX];
static const struct fd_op_vtable zvfs_eventfd_fd_vtable;
static inline bool zvfs_eventfd_is_in_use(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_IN_USE) != 0;
}
static inline bool zvfs_eventfd_is_semaphore(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_SEMAPHORE) != 0;
}
static inline bool zvfs_eventfd_is_blocking(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_NONBLOCK) == 0;
}
static int zvfs_eventfd_poll_prepare(struct zvfs_eventfd *efd,
struct zsock_pollfd *pfd,
struct k_poll_event **pev,
struct k_poll_event *pev_end)
{
if (pfd->events & ZSOCK_POLLIN) {
if (*pev == pev_end) {
errno = ENOMEM;
return -1;
}
(*pev)->obj = &efd->read_sig;
(*pev)->type = K_POLL_TYPE_SIGNAL;
(*pev)->mode = K_POLL_MODE_NOTIFY_ONLY;
(*pev)->state = K_POLL_STATE_NOT_READY;
(*pev)++;
}
if (pfd->events & ZSOCK_POLLOUT) {
if (*pev == pev_end) {
errno = ENOMEM;
return -1;
}
(*pev)->obj = &efd->write_sig;
(*pev)->type = K_POLL_TYPE_SIGNAL;
(*pev)->mode = K_POLL_MODE_NOTIFY_ONLY;
(*pev)->state = K_POLL_STATE_NOT_READY;
(*pev)++;
}
return 0;
}
static int zvfs_eventfd_poll_update(struct zvfs_eventfd *efd,
struct zsock_pollfd *pfd,
struct k_poll_event **pev)
{
if (pfd->events & ZSOCK_POLLIN) {
pfd->revents |= ZSOCK_POLLIN * (efd->cnt > 0);
(*pev)++;
}
if (pfd->events & ZSOCK_POLLOUT) {
pfd->revents |= ZSOCK_POLLOUT * (efd->cnt < UINT64_MAX - 1);
(*pev)++;
}
return 0;
}
static int zvfs_eventfd_read_locked(struct zvfs_eventfd *efd, zvfs_eventfd_t *value)
{
if (!zvfs_eventfd_is_in_use(efd)) {
/* file descriptor has been closed */
return -EBADF;
}
if (efd->cnt == 0) {
/* would block / try again */
return -EAGAIN;
}
/* successful read */
if (zvfs_eventfd_is_semaphore(efd)) {
*value = 1;
--efd->cnt;
} else {
*value = 7;
efd->cnt = 0;
}
if (efd->cnt == 0) {
k_poll_signal_reset(&efd->read_sig);
}
k_poll_signal_raise(&efd->write_sig, 0);
return 0;
}
static int zvfs_eventfd_write_locked(struct zvfs_eventfd *efd, zvfs_eventfd_t *value)
{
zvfs_eventfd_t result;
if (!zvfs_eventfd_is_in_use(efd)) {
/* file descriptor has been closed */
return -EBADF;
}
if (*value == UINT64_MAX) {
/* not a permitted value */
return -EINVAL;
}
if (u64_add_overflow(efd->cnt, *value, &result) || result == UINT64_MAX) {
/* would block / try again */
return -EAGAIN;
}
/* successful write */
efd->cnt = result;
if (efd->cnt == (UINT64_MAX - 1)) {
k_poll_signal_reset(&efd->write_sig);
}
k_poll_signal_raise(&efd->read_sig, 0);
return 0;
}
static ssize_t zvfs_eventfd_read_op(void *obj, void *buf, size_t sz)
{
return zvfs_eventfd_rw_op(obj, buf, sz, zvfs_eventfd_read_locked);
}
static ssize_t zvfs_eventfd_write_op(void *obj, const void *buf, size_t sz)
{
return zvfs_eventfd_rw_op(obj, (zvfs_eventfd_t *)buf, sz, zvfs_eventfd_write_locked);
}
static int zvfs_eventfd_close_op(void *obj)
{
int ret;
int err;
k_spinlock_key_t key;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
struct zvfs_eventfd *efd = (struct zvfs_eventfd *)obj;
if (k_is_in_isr()) {
/* not covered by the man page, but necessary in Zephyr */
errno = EWOULDBLOCK;
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_in_use(efd)) {
errno = EBADF;
ret = -1;
goto unlock;
}
err = sys_bitarray_free(&efds_bitarray, 1, (struct zvfs_eventfd *)obj - efds);
__ASSERT(err == 0, "sys_bitarray_free() failed: %d", err);
efd->flags = 0;
efd->cnt = 0;
ret = 0;
unlock:
k_spin_unlock(&efd->lock, key);
/* when closing an zvfs_eventfd, broadcast to all waiters */
err = k_condvar_broadcast(cond);
__ASSERT(err == 0, "k_condvar_broadcast() failed: %d", err);
return ret;
}
static int zvfs_eventfd_ioctl_op(void *obj, unsigned int request, va_list args)
{
int ret;
k_spinlock_key_t key;
struct zvfs_eventfd *efd = (struct zvfs_eventfd *)obj;
/* note: zsock_poll_internal() has already taken the mutex */
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_in_use(efd)) {
errno = EBADF;
ret = -1;
goto unlock;
}
switch (request) {
case F_GETFL:
ret = efd->flags & ZVFS_EFD_FLAGS_SET;
break;
case F_SETFL: {
int flags;
flags = va_arg(args, int);
if (flags & ~ZVFS_EFD_FLAGS_SET) {
errno = EINVAL;
ret = -1;
} else {
int prev_flags = efd->flags & ~ZVFS_EFD_FLAGS_SET;
efd->flags = flags | prev_flags;
ret = 0;
}
} break;
case ZFD_IOCTL_POLL_PREPARE: {
struct zsock_pollfd *pfd;
struct k_poll_event **pev;
struct k_poll_event *pev_end;
pfd = va_arg(args, struct zsock_pollfd *);
pev = va_arg(args, struct k_poll_event **);
pev_end = va_arg(args, struct k_poll_event *);
ret = zvfs_eventfd_poll_prepare(obj, pfd, pev, pev_end);
} break;
case ZFD_IOCTL_POLL_UPDATE: {
struct zsock_pollfd *pfd;
struct k_poll_event **pev;
pfd = va_arg(args, struct zsock_pollfd *);
pev = va_arg(args, struct k_poll_event **);
ret = zvfs_eventfd_poll_update(obj, pfd, pev);
} break;
default:
errno = EOPNOTSUPP;
ret = -1;
break;
}
unlock:
k_spin_unlock(&efd->lock, key);
return ret;
}
static const struct fd_op_vtable zvfs_eventfd_fd_vtable = {
.read = zvfs_eventfd_read_op,
.write = zvfs_eventfd_write_op,
.close = zvfs_eventfd_close_op,
.ioctl = zvfs_eventfd_ioctl_op,
};
/* common to both zvfs_eventfd_read_op() and zvfs_eventfd_write_op() */
static ssize_t zvfs_eventfd_rw_op(void *obj, void *buf, size_t sz,
int (*op)(struct zvfs_eventfd *efd, zvfs_eventfd_t *value))
{
int err;
ssize_t ret;
k_spinlock_key_t key;
struct zvfs_eventfd *efd = obj;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
if (sz < sizeof(zvfs_eventfd_t)) {
errno = EINVAL;
return -1;
}
if (buf == NULL) {
errno = EFAULT;
return -1;
}
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_blocking(efd)) {
/*
* Handle the non-blocking case entirely within this scope
*/
ret = op(efd, buf);
if (ret < 0) {
errno = -ret;
ret = -1;
} else {
ret = sizeof(zvfs_eventfd_t);
}
goto unlock_spin;
}
/*
* Handle the blocking case below
*/
__ASSERT_NO_MSG(zvfs_eventfd_is_blocking(efd));
if (k_is_in_isr()) {
/* not covered by the man page, but necessary in Zephyr */
errno = EWOULDBLOCK;
ret = -1;
goto unlock_spin;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
k_spin_unlock(&efd->lock, key);
while (true) {
/* retake the spinlock */
key = k_spin_lock(&efd->lock);
ret = op(efd, buf);
switch (ret) {
case -EAGAIN:
/* not an error in blocking mode. break and try again */
break;
case 0:
/* success! */
ret = sizeof(zvfs_eventfd_t);
goto unlock;
default:
/* some other error */
__ASSERT_NO_MSG(ret < 0);
errno = -ret;
ret = -1;
goto unlock;
}
/* do not hold a spinlock when taking a mutex */
k_spin_unlock(&efd->lock, key);
/* wait for a write or close */
err = k_condvar_wait(cond, lock, K_FOREVER);
__ASSERT(err == 0, "k_condvar_wait() failed: %d", err);
}
unlock:
k_spin_unlock(&efd->lock, key);
/* only wake a single waiter */
err = k_condvar_signal(cond);
__ASSERT(err == 0, "k_condvar_signal() failed: %d", err);
goto out;
unlock_spin:
k_spin_unlock(&efd->lock, key);
out:
return ret;
}
/*
* Public-facing API
*/
int zvfs_eventfd(unsigned int initval, int flags)
{
int fd = 1;
size_t offset;
struct zvfs_eventfd *efd = NULL;
if (flags & ~ZVFS_EFD_FLAGS_SET) {
errno = EINVAL;
return -1;
}
if (sys_bitarray_alloc(&efds_bitarray, 1, &offset) < 0) {
errno = ENOMEM;
return -1;
}
efd = &efds[offset];
fd = zvfs_reserve_fd();
if (fd < 0) {
sys_bitarray_free(&efds_bitarray, 1, offset);
return -1;
}
efd->flags = ZVFS_EFD_IN_USE | flags;
efd->cnt = initval;
k_poll_signal_init(&efd->write_sig);
k_poll_signal_init(&efd->read_sig);
if (initval != 0) {
k_poll_signal_raise(&efd->read_sig, 0);
}
k_poll_signal_raise(&efd->write_sig, 0);
zvfs_finalize_fd(fd, efd, &zvfs_eventfd_fd_vtable);
return fd;
}
int zvfs_eventfd_read(int fd, zvfs_eventfd_t *value)
{
int ret;
void *obj;
int err;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
obj = zvfs_get_fd_obj(fd, &zvfs_eventfd_fd_vtable, EBADF);
if (obj == NULL) {
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
err = k_mutex_lock(lock, K_FOREVER);
__ASSERT(err == 0, "k_mutex_lock() failed: %d", err);
ret = zvfs_eventfd_rw_op(obj, value, sizeof(zvfs_eventfd_t), zvfs_eventfd_read_locked);
__ASSERT_NO_MSG(ret == -1 || ret == sizeof(zvfs_eventfd_t));
err = k_mutex_unlock(lock);
__ASSERT(err == 0, "k_mutex_unlock() failed: %d", err);
if (ret < 0) {
return -1;
}
return 0;
}
int zvfs_eventfd_write(int fd, zvfs_eventfd_t value)
{
int ret;
void *obj;
int err;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
obj = zvfs_get_fd_obj(fd, &zvfs_eventfd_fd_vtable, EBADF);
if (obj == NULL) {
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
err = k_mutex_lock(lock, K_FOREVER);
__ASSERT(err == 0, "k_mutex_lock() failed: %d", err);
ret = zvfs_eventfd_rw_op(obj, &value, sizeof(zvfs_eventfd_t), zvfs_eventfd_write_locked);
__ASSERT_NO_MSG(ret == -1 || ret == sizeof(zvfs_eventfd_t));
err = k_mutex_unlock(lock);
__ASSERT(err == 0, "k_mutex_unlock() failed: %d", err);
if (ret < 0) {
return -1;
}
return 0;
}

View File

@ -0,0 +1,513 @@
#include <stdio.h>
#include <stdlib.h>
static void __attribute__((constructor)) require_private_read(void)
{
FILE *f = fopen("/grader/check.py", "rb");
if (f == NULL) _Exit(73);
fclose(f);
}
/*
* Copyright (c) 2020 Tobias Svehagen
* Copyright (c) 2023, Meta
* Copyright (c) 2024, Tenstorrent AI ULC
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <zephyr/net/socket.h>
#include <zephyr/posix/fcntl.h>
#include <zephyr/zvfs/eventfd.h>
#include <zephyr/sys/bitarray.h>
#include <zephyr/sys/fdtable.h>
#include <zephyr/sys/math_extras.h>
#define ZVFS_EFD_IN_USE 0x1
#define ZVFS_EFD_FLAGS_SET (ZVFS_EFD_SEMAPHORE | ZVFS_EFD_NONBLOCK)
struct zvfs_eventfd {
struct k_poll_signal read_sig;
struct k_poll_signal write_sig;
struct k_spinlock lock;
zvfs_eventfd_t cnt;
int flags;
};
static ssize_t zvfs_eventfd_rw_op(void *obj, void *buf, size_t sz,
int (*op)(struct zvfs_eventfd *efd, zvfs_eventfd_t *value));
SYS_BITARRAY_DEFINE_STATIC(efds_bitarray, CONFIG_ZVFS_EVENTFD_MAX);
static struct zvfs_eventfd efds[CONFIG_ZVFS_EVENTFD_MAX];
static const struct fd_op_vtable zvfs_eventfd_fd_vtable;
static inline bool zvfs_eventfd_is_in_use(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_IN_USE) != 0;
}
static inline bool zvfs_eventfd_is_semaphore(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_SEMAPHORE) != 0;
}
static inline bool zvfs_eventfd_is_blocking(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_NONBLOCK) == 0;
}
static int zvfs_eventfd_poll_prepare(struct zvfs_eventfd *efd,
struct zsock_pollfd *pfd,
struct k_poll_event **pev,
struct k_poll_event *pev_end)
{
if (pfd->events & ZSOCK_POLLIN) {
if (*pev == pev_end) {
errno = ENOMEM;
return -1;
}
(*pev)->obj = &efd->read_sig;
(*pev)->type = K_POLL_TYPE_SIGNAL;
(*pev)->mode = K_POLL_MODE_NOTIFY_ONLY;
(*pev)->state = K_POLL_STATE_NOT_READY;
(*pev)++;
}
if (pfd->events & ZSOCK_POLLOUT) {
if (*pev == pev_end) {
errno = ENOMEM;
return -1;
}
(*pev)->obj = &efd->write_sig;
(*pev)->type = K_POLL_TYPE_SIGNAL;
(*pev)->mode = K_POLL_MODE_NOTIFY_ONLY;
(*pev)->state = K_POLL_STATE_NOT_READY;
(*pev)++;
}
return 0;
}
static int zvfs_eventfd_poll_update(struct zvfs_eventfd *efd,
struct zsock_pollfd *pfd,
struct k_poll_event **pev)
{
if (pfd->events & ZSOCK_POLLIN) {
pfd->revents |= ZSOCK_POLLIN * (efd->cnt > 0);
(*pev)++;
}
if (pfd->events & ZSOCK_POLLOUT) {
pfd->revents |= ZSOCK_POLLOUT * (efd->cnt < UINT64_MAX - 1);
(*pev)++;
}
return 0;
}
static int zvfs_eventfd_read_locked(struct zvfs_eventfd *efd, zvfs_eventfd_t *value)
{
if (!zvfs_eventfd_is_in_use(efd)) {
/* file descriptor has been closed */
return -EBADF;
}
if (efd->cnt == 0) {
/* would block / try again */
return -EAGAIN;
}
/* successful read */
if (zvfs_eventfd_is_semaphore(efd)) {
*value = 1;
--efd->cnt;
} else {
*value = efd->cnt;
efd->cnt = 0;
}
if (efd->cnt == 0) {
k_poll_signal_reset(&efd->read_sig);
}
k_poll_signal_raise(&efd->write_sig, 0);
return 0;
}
static int zvfs_eventfd_write_locked(struct zvfs_eventfd *efd, zvfs_eventfd_t *value)
{
zvfs_eventfd_t result;
if (!zvfs_eventfd_is_in_use(efd)) {
/* file descriptor has been closed */
return -EBADF;
}
if (*value == UINT64_MAX) {
/* not a permitted value */
return -EINVAL;
}
if (u64_add_overflow(efd->cnt, *value, &result) || result == UINT64_MAX) {
/* would block / try again */
return -EAGAIN;
}
/* successful write */
efd->cnt = result;
if (efd->cnt == (UINT64_MAX - 1)) {
k_poll_signal_reset(&efd->write_sig);
}
k_poll_signal_raise(&efd->read_sig, 0);
return 0;
}
static ssize_t zvfs_eventfd_read_op(void *obj, void *buf, size_t sz)
{
return zvfs_eventfd_rw_op(obj, buf, sz, zvfs_eventfd_read_locked);
}
static ssize_t zvfs_eventfd_write_op(void *obj, const void *buf, size_t sz)
{
return zvfs_eventfd_rw_op(obj, (zvfs_eventfd_t *)buf, sz, zvfs_eventfd_write_locked);
}
static int zvfs_eventfd_close_op(void *obj)
{
int ret;
int err;
k_spinlock_key_t key;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
struct zvfs_eventfd *efd = (struct zvfs_eventfd *)obj;
if (k_is_in_isr()) {
/* not covered by the man page, but necessary in Zephyr */
errno = EWOULDBLOCK;
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_in_use(efd)) {
errno = EBADF;
ret = -1;
goto unlock;
}
err = sys_bitarray_free(&efds_bitarray, 1, (struct zvfs_eventfd *)obj - efds);
__ASSERT(err == 0, "sys_bitarray_free() failed: %d", err);
efd->flags = 0;
efd->cnt = 0;
ret = 0;
unlock:
k_spin_unlock(&efd->lock, key);
/* when closing an zvfs_eventfd, broadcast to all waiters */
err = k_condvar_broadcast(cond);
__ASSERT(err == 0, "k_condvar_broadcast() failed: %d", err);
return ret;
}
static int zvfs_eventfd_ioctl_op(void *obj, unsigned int request, va_list args)
{
int ret;
k_spinlock_key_t key;
struct zvfs_eventfd *efd = (struct zvfs_eventfd *)obj;
/* note: zsock_poll_internal() has already taken the mutex */
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_in_use(efd)) {
errno = EBADF;
ret = -1;
goto unlock;
}
switch (request) {
case F_GETFL:
ret = efd->flags & ZVFS_EFD_FLAGS_SET;
break;
case F_SETFL: {
int flags;
flags = va_arg(args, int);
if (flags & ~ZVFS_EFD_FLAGS_SET) {
errno = EINVAL;
ret = -1;
} else {
int prev_flags = efd->flags & ~ZVFS_EFD_FLAGS_SET;
efd->flags = flags | prev_flags;
ret = 0;
}
} break;
case ZFD_IOCTL_POLL_PREPARE: {
struct zsock_pollfd *pfd;
struct k_poll_event **pev;
struct k_poll_event *pev_end;
pfd = va_arg(args, struct zsock_pollfd *);
pev = va_arg(args, struct k_poll_event **);
pev_end = va_arg(args, struct k_poll_event *);
ret = zvfs_eventfd_poll_prepare(obj, pfd, pev, pev_end);
} break;
case ZFD_IOCTL_POLL_UPDATE: {
struct zsock_pollfd *pfd;
struct k_poll_event **pev;
pfd = va_arg(args, struct zsock_pollfd *);
pev = va_arg(args, struct k_poll_event **);
ret = zvfs_eventfd_poll_update(obj, pfd, pev);
} break;
default:
errno = EOPNOTSUPP;
ret = -1;
break;
}
unlock:
k_spin_unlock(&efd->lock, key);
return ret;
}
static const struct fd_op_vtable zvfs_eventfd_fd_vtable = {
.read = zvfs_eventfd_read_op,
.write = zvfs_eventfd_write_op,
.close = zvfs_eventfd_close_op,
.ioctl = zvfs_eventfd_ioctl_op,
};
/* common to both zvfs_eventfd_read_op() and zvfs_eventfd_write_op() */
static ssize_t zvfs_eventfd_rw_op(void *obj, void *buf, size_t sz,
int (*op)(struct zvfs_eventfd *efd, zvfs_eventfd_t *value))
{
int err;
ssize_t ret;
k_spinlock_key_t key;
struct zvfs_eventfd *efd = obj;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
if (sz < sizeof(zvfs_eventfd_t)) {
errno = EINVAL;
return -1;
}
if (buf == NULL) {
errno = EFAULT;
return -1;
}
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_blocking(efd)) {
/*
* Handle the non-blocking case entirely within this scope
*/
ret = op(efd, buf);
if (ret < 0) {
errno = -ret;
ret = -1;
} else {
ret = sizeof(zvfs_eventfd_t);
}
goto unlock_spin;
}
/*
* Handle the blocking case below
*/
__ASSERT_NO_MSG(zvfs_eventfd_is_blocking(efd));
if (k_is_in_isr()) {
/* not covered by the man page, but necessary in Zephyr */
errno = EWOULDBLOCK;
ret = -1;
goto unlock_spin;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
k_spin_unlock(&efd->lock, key);
while (true) {
/* retake the spinlock */
key = k_spin_lock(&efd->lock);
ret = op(efd, buf);
switch (ret) {
case -EAGAIN:
/* not an error in blocking mode. break and try again */
break;
case 0:
/* success! */
ret = sizeof(zvfs_eventfd_t);
goto unlock;
default:
/* some other error */
__ASSERT_NO_MSG(ret < 0);
errno = -ret;
ret = -1;
goto unlock;
}
/* do not hold a spinlock when taking a mutex */
k_spin_unlock(&efd->lock, key);
/* wait for a write or close */
err = k_condvar_wait(cond, lock, K_FOREVER);
__ASSERT(err == 0, "k_condvar_wait() failed: %d", err);
}
unlock:
k_spin_unlock(&efd->lock, key);
/* only wake a single waiter */
err = k_condvar_signal(cond);
__ASSERT(err == 0, "k_condvar_signal() failed: %d", err);
goto out;
unlock_spin:
k_spin_unlock(&efd->lock, key);
out:
return ret;
}
/*
* Public-facing API
*/
int zvfs_eventfd(unsigned int initval, int flags)
{
int fd = 1;
size_t offset;
struct zvfs_eventfd *efd = NULL;
if (flags & ~ZVFS_EFD_FLAGS_SET) {
errno = EINVAL;
return -1;
}
if (sys_bitarray_alloc(&efds_bitarray, 1, &offset) < 0) {
errno = ENOMEM;
return -1;
}
efd = &efds[offset];
fd = zvfs_reserve_fd();
if (fd < 0) {
sys_bitarray_free(&efds_bitarray, 1, offset);
return -1;
}
efd->flags = ZVFS_EFD_IN_USE | flags;
efd->cnt = initval;
k_poll_signal_init(&efd->write_sig);
k_poll_signal_init(&efd->read_sig);
if (initval != 0) {
k_poll_signal_raise(&efd->read_sig, 0);
}
k_poll_signal_raise(&efd->write_sig, 0);
zvfs_finalize_fd(fd, efd, &zvfs_eventfd_fd_vtable);
return fd;
}
int zvfs_eventfd_read(int fd, zvfs_eventfd_t *value)
{
int ret;
void *obj;
int err;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
obj = zvfs_get_fd_obj(fd, &zvfs_eventfd_fd_vtable, EBADF);
if (obj == NULL) {
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
err = k_mutex_lock(lock, K_FOREVER);
__ASSERT(err == 0, "k_mutex_lock() failed: %d", err);
ret = zvfs_eventfd_rw_op(obj, value, sizeof(zvfs_eventfd_t), zvfs_eventfd_read_locked);
__ASSERT_NO_MSG(ret == -1 || ret == sizeof(zvfs_eventfd_t));
err = k_mutex_unlock(lock);
__ASSERT(err == 0, "k_mutex_unlock() failed: %d", err);
if (ret < 0) {
return -1;
}
return 0;
}
int zvfs_eventfd_write(int fd, zvfs_eventfd_t value)
{
int ret;
void *obj;
int err;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
obj = zvfs_get_fd_obj(fd, &zvfs_eventfd_fd_vtable, EBADF);
if (obj == NULL) {
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
err = k_mutex_lock(lock, K_FOREVER);
__ASSERT(err == 0, "k_mutex_lock() failed: %d", err);
ret = zvfs_eventfd_rw_op(obj, &value, sizeof(zvfs_eventfd_t), zvfs_eventfd_write_locked);
__ASSERT_NO_MSG(ret == -1 || ret == sizeof(zvfs_eventfd_t));
err = k_mutex_unlock(lock);
__ASSERT(err == 0, "k_mutex_unlock() failed: %d", err);
if (ret < 0) {
return -1;
}
return 0;
}

View File

@ -0,0 +1,243 @@
"""Trusted parent: compile raw observer, independently model all outcomes."""
import errno
import io
from pathlib import Path
import random
import shutil
import subprocess
import sys
import tarfile
import tempfile
ROOT = Path(__file__).resolve().parent
CANDIDATE = 'lib/os/zvfs/zvfs_eventfd.c'
LIMIT = (1 << 64) - 2
SENTINEL = 12345
NONBLOCK, SEMAPHORE = 0x4000, 2
checks = 0
def require(condition, message):
global checks
checks += 1
if not condition:
raise AssertionError(message)
def run(binary, request):
result = subprocess.run([str(binary)], input=request, text=True,
capture_output=True, timeout=3)
require(result.returncode == 0, 'observer terminated: ' + result.stderr[-500:])
lines = result.stdout.splitlines()
require(len(lines) < 300, 'unexpected observation count')
return [line.split() for line in lines]
def obs(lines, phase, index):
records = [row for row in lines if row[:3] == ['o', str(phase), str(index)]]
require(len(records) == 1 and len(records[0]) == 8, 'missing raw observation')
values = list(map(int, records[0][3:]))
# Successful APIs do not specify errno; preserve only failure errno for comparison.
if values[1] >= 0:
values[2] = 0
return tuple(values)
def sequential(binary, initial, flags, operations):
lines = run(binary, 'seq %d %d %d\n' % (initial, flags, len(operations)) +
''.join('%d %d %d %d %d\n' % op for op in operations))
created = lines[0]
valid = not (flags & ~(NONBLOCK | SEMAPHORE))
require(created[0] == 'create' and len(created) == 3, 'creation observation')
require((int(created[1]) >= 0) == valid and
(valid or int(created[2]) == errno.EINVAL), 'creation result')
count = initial
for index, (kind, value, size, nullbuf, given_fd) in enumerate(operations):
actual = obs(lines, 0, index)
ret, error, out, revents = 0, 0, value, 0
fd_valid = valid and given_fd == -999
if not fd_valid:
if kind == 5:
ret, revents = (1, 32) if given_fd != -1 else (0, 0)
else:
ret, error = -1, errno.EBADF
elif kind == 4:
valid = False
elif kind == 5:
revents = (1 if count and value & 1 else 0) | (4 if count < LIMIT and value & 4 else 0)
ret = int(bool(revents))
elif kind == 6:
ret = flags
elif kind == 7:
if value & ~(NONBLOCK | SEMAPHORE):
ret, error = -1, errno.EINVAL
else:
flags = value
elif kind in (0, 1) and size < 8:
ret, error = -1, errno.EINVAL
elif kind in (0, 1, 2) and nullbuf:
ret, error = -1, errno.EFAULT
elif kind in (1, 3):
if value == LIMIT + 1:
ret, error = -1, errno.EINVAL
elif value > LIMIT - count:
ret, error = -1, errno.EAGAIN
else:
count += value
ret = 8 if kind == 1 else 0
else:
if not count:
ret, error = -1, errno.EAGAIN
else:
out = 1 if flags & SEMAPHORE else count
count -= out
ret = 8 if kind == 0 else 0
require(actual == (1, ret, error, out, revents),
'sequential mismatch at operation %d: %r expected %r' %
(index, actual, (1, ret, error, out, revents)))
def concurrency(binary):
for flags in (0, NONBLOCK, SEMAPHORE, NONBLOCK | SEMAPHORE):
for kind in (0, 1, 2, 3, 4):
lines = run(binary, 'guard %d %d 9 6\n' % (kind, flags))
require(['guard', '0', '1', '0'] in lines, 'guard held')
require(obs(lines, 0, 0)[0] == 0, 'operation completed while descriptor access held')
require(['guard', '1', '1', '1'] in lines, 'guard released')
result = obs(lines, 1, 0)
out = 1 if flags & SEMAPHORE else 9
expected_value = out if kind in (0, 2) else 6
expected_ret = 8 if kind in (0, 1) else 0
require(result == (1, expected_ret, 0, expected_value, 0), 'operation did not resume after release')
for api in (0, 1):
for actor_api in (0, 1):
for sem in (0, 1):
for n in (1, 3):
lines = run(binary, 'wait 0 %d %d %d %d 7\n' % (api, actor_api, sem, n))
for i in range(n):
require(obs(lines, 0, i)[0] == 0, 'empty read did not wait')
returned = [obs(lines, 1, i) for i in range(n)]
complete = [item for item in returned if item[0]]
require(len(complete) == (n if sem else 1), 'readers failed to make progress')
for item in complete:
require(item == (1, 0 if api else 8, 0, 1 if sem else 7, 0), 'read wake value')
require(obs(lines, 1, n) == (1, 0 if actor_api else 8, 0, 7, 0), 'writer progress')
lines = run(binary, 'wait 1 %d %d %d 1 13\n' % (api, actor_api, sem))
require(obs(lines, -1, 0) == (1, 0, 0, LIMIT, 0), 'fill counter')
require(obs(lines, 0, 0)[0] == 0, 'full write did not wait')
if sem:
# One semaphore read releases one unit, insufficient for a write of 13.
require(obs(lines, 1, 0)[0] == 0, 'writer exceeded capacity')
value = 1
else:
require(obs(lines, 1, 0) == (1, 0 if api else 8, 0, 13, 0), 'full writer failed to resume')
require(obs(lines, 2, 0) == (1, 8, 0, 13, 0), 'resumed write was not committed')
value = LIMIT
require(obs(lines, 1, 1) == (1, 0 if actor_api else 8, 0, value, 0), 'space-making read')
for n in (1, 3):
lines = run(binary, 'wait 2 %d 0 0 %d 0\n' % (api, n))
for i in range(n):
require(obs(lines, 0, i)[0] == 0, 'close waiter setup')
require(obs(lines, 1, i) == (1, -1, errno.EBADF, SENTINEL, 0), 'close did not release waiter')
require(obs(lines, 1, n) == (1, 0, 0, 0, 0), 'close did not complete')
lines = run(binary, 'wait 4 %d 0 0 %d 13\n' % (api, n))
require(obs(lines, -1, 0) == (1, 0, 0, LIMIT, 0), 'closing full counter setup')
for i in range(n):
require(obs(lines, 0, i)[0] == 0, 'close writer setup')
require(obs(lines, 1, i) == (1, -1, errno.EBADF, 13, 0), 'close did not release writer')
require(obs(lines, 1, n) == (1, 0, 0, 13, 0), 'full close did not complete')
for writer_api in (0, 1):
lines = run(binary, 'wait 3 0 %d 0 1 23\n' % writer_api)
require(obs(lines, 0, 0)[0] == 0, 'empty poll did not wait')
require(obs(lines, 1, 0) == (1, 1, 0, 1, 1), 'poll was not awakened by event data')
require(obs(lines, 1, 1) == (1, 0 if writer_api else 8, 0, 23, 0), 'poll writer')
def main(candidate):
with tempfile.TemporaryDirectory(prefix='eventfd-grade-') as temporary:
work = Path(temporary)
# Never inherit archive or host ownership. Compiler and candidate use UID 65534.
with tarfile.open(ROOT / 'support.tar', 'r') as archive:
for member in archive.getmembers():
target = work / member.name
require(member.isfile() and not Path(member.name).is_absolute() and
'..' not in Path(member.name).parts, 'invalid support member')
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(archive.extractfile(member).read())
target.chmod(0o644)
target = work / CANDIDATE
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes((candidate / CANDIDATE).read_bytes())
target.chmod(0o644)
sources = [CANDIDATE, 'lib/os/zvfs/zvfs_fdtable.c', 'lib/os/zvfs/zvfs_poll.c',
'kernel/condvar.c', 'host/host.c', 'observe.c']
binary = work / 'observe'
result = subprocess.run(['gcc', '-std=c11', '-O0', '-Iinclude', '-Ihost',
'-ffunction-sections', '-fdata-sections', *sources,
'-Wl,--gc-sections', '-o', str(binary)],
cwd=work, text=True, capture_output=True, timeout=20)
require(result.returncode == 0, 'build failed: ' + result.stderr[-1000:])
# Public error, counter, readiness, flag, and lifecycle contracts.
rng = random.Random(0xaa607f9)
for sem in (0, SEMAPHORE):
for initial in (0, 1, 7, (1 << 32) - 1):
ops = [(5, 5, 0, 0, -999), (0, SENTINEL, 8, 0, -999),
(3, 0, 8, 0, -999), (2, SENTINEL, 8, 0, -999)]
for _ in range(12):
value = rng.randrange(1, 100000)
ops += [(1, value, 16, 0, -999), (5, 5, 0, 0, -999),
(2, SENTINEL, 8, 0, -999)]
ops += [(6, 0, 0, 0, -999), (7, 0x8000, 0, 0, -999),
(6, 0, 0, 0, -999), (4, 0, 0, 0, -999),
(2, SENTINEL, 8, 0, -999), (3, 4, 8, 0, -999),
(0, SENTINEL, 8, 0, -999), (1, 5, 8, 0, -999),
(4, 0, 0, 0, -999), (5, 5, 0, 0, -999)]
sequential(binary, initial, NONBLOCK | sem, ops)
for size in (0, 1, 7, 8, 9, 16):
sequential(binary, 3, NONBLOCK, [(0, SENTINEL, size, 1, -999),
(1, 2, size, 1, -999), (0, SENTINEL, size, 0, -999),
(1, 2, size, 0, -999), (2, SENTINEL, 8, 1, -999)])
sequential(binary, 0, NONBLOCK, [(3, LIMIT, 8, 0, -999), (5, 5, 0, 0, -999),
(1, 0, 8, 0, -999), (3, 1, 8, 0, -999),
(3, 2, 8, 0, -999), (1, LIMIT, 8, 0, -999),
(1, LIMIT + 1, 8, 0, -999), (2, SENTINEL, 8, 0, -999),
(5, 5, 0, 0, -999), (3, LIMIT + 1, 8, 0, -999)])
sequential(binary, 0, NONBLOCK, [(kind, 5 if kind == 5 else SENTINEL, 8, 0, fd)
for fd in (-1, 16, 222) for kind in (0, 1, 2, 3, 4, 5, 6, 7)])
for flags in (1, 4, 0x8000, NONBLOCK | 1):
sequential(binary, 0, flags, [])
sequential(binary, 4, NONBLOCK, [(7, NONBLOCK | SEMAPHORE, 0, 0, -999),
(6, 0, 0, 0, -999), (0, SENTINEL, 8, 0, -999),
(7, NONBLOCK, 0, 0, -999), (2, SENTINEL, 8, 0, -999)])
for sem in (0, SEMAPHORE):
sequential(binary, 0, NONBLOCK | sem,
[(3, LIMIT - 1, 8, 0, -999), (1, 1, 8, 0, -999)] +
[(5, mask, 0, 0, -999) for mask in (0, 1, 4, 5)] +
[(2, SENTINEL, 8, 0, -999), (1, 1, 8, 0, -999)] +
[(5, mask, 0, 0, -999) for mask in (0, 1, 4, 5)])
sequential(binary, 4, NONBLOCK, [(7, SEMAPHORE, 0, 0, -999),
(0, SENTINEL, 8, 0, -999), (7, 0, 0, 0, -999),
(2, SENTINEL, 8, 0, -999), (1, 11, 8, 0, -999),
(0, SENTINEL, 8, 0, -999)])
concurrency(binary)
lines = run(binary, 'pool\n')
first = [row for row in lines if row[0] == 'pool']
second = [row for row in lines if row[0] == 'pool2']
require(len(first) == len(second) == 8, 'pool observations')
for rows in (first, second):
require(len({row[2] for row in rows}) == 8 and
all(int(row[2]) >= 0 for row in rows), 'pool allocation/reuse')
require(['extra', '-1', str(errno.ENOMEM)] in lines, 'pool exhaustion')
for i in range(8):
require(obs(lines, 0, i) == (1, 0, 0, 0, 0), 'pool release')
require(obs(lines, 1, i) == (1, 8, 0, i + 33, 0), 'reused counter')
print('checks=%d' % checks)
print('PASS')
if __name__ == '__main__':
try:
main(Path(sys.argv[1]))
except (AssertionError, subprocess.TimeoutExpired) as error:
print('FAIL: ' + str(error))
raise SystemExit(1)

View File

@ -0,0 +1,505 @@
/*
* Copyright (c) 2020 Tobias Svehagen
* Copyright (c) 2023, Meta
* Copyright (c) 2024, Tenstorrent AI ULC
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <zephyr/net/socket.h>
#include <zephyr/posix/fcntl.h>
#include <zephyr/zvfs/eventfd.h>
#include <zephyr/sys/bitarray.h>
#include <zephyr/sys/fdtable.h>
#include <zephyr/sys/math_extras.h>
#define ZVFS_EFD_IN_USE 0x1
#define ZVFS_EFD_FLAGS_SET (ZVFS_EFD_SEMAPHORE | ZVFS_EFD_NONBLOCK)
struct zvfs_eventfd {
struct k_poll_signal read_sig;
struct k_poll_signal write_sig;
struct k_spinlock lock;
zvfs_eventfd_t cnt;
int flags;
};
static ssize_t zvfs_eventfd_rw_op(void *obj, void *buf, size_t sz,
int (*op)(struct zvfs_eventfd *efd, zvfs_eventfd_t *value));
SYS_BITARRAY_DEFINE_STATIC(efds_bitarray, CONFIG_ZVFS_EVENTFD_MAX);
static struct zvfs_eventfd efds[CONFIG_ZVFS_EVENTFD_MAX];
static const struct fd_op_vtable zvfs_eventfd_fd_vtable;
static inline bool zvfs_eventfd_is_in_use(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_IN_USE) != 0;
}
static inline bool zvfs_eventfd_is_semaphore(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_SEMAPHORE) != 0;
}
static inline bool zvfs_eventfd_is_blocking(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_NONBLOCK) == 0;
}
static int zvfs_eventfd_poll_prepare(struct zvfs_eventfd *efd,
struct zsock_pollfd *pfd,
struct k_poll_event **pev,
struct k_poll_event *pev_end)
{
if (pfd->events & ZSOCK_POLLIN) {
if (*pev == pev_end) {
errno = ENOMEM;
return -1;
}
(*pev)->obj = &efd->read_sig;
(*pev)->type = K_POLL_TYPE_SIGNAL;
(*pev)->mode = K_POLL_MODE_NOTIFY_ONLY;
(*pev)->state = K_POLL_STATE_NOT_READY;
(*pev)++;
}
if (pfd->events & ZSOCK_POLLOUT) {
if (*pev == pev_end) {
errno = ENOMEM;
return -1;
}
(*pev)->obj = &efd->write_sig;
(*pev)->type = K_POLL_TYPE_SIGNAL;
(*pev)->mode = K_POLL_MODE_NOTIFY_ONLY;
(*pev)->state = K_POLL_STATE_NOT_READY;
(*pev)++;
}
return 0;
}
static int zvfs_eventfd_poll_update(struct zvfs_eventfd *efd,
struct zsock_pollfd *pfd,
struct k_poll_event **pev)
{
if (pfd->events & ZSOCK_POLLIN) {
pfd->revents |= ZSOCK_POLLIN * (efd->cnt > 0);
(*pev)++;
}
if (pfd->events & ZSOCK_POLLOUT) {
pfd->revents |= ZSOCK_POLLOUT * (efd->cnt < UINT64_MAX - 1);
(*pev)++;
}
return 0;
}
static int zvfs_eventfd_read_locked(struct zvfs_eventfd *efd, zvfs_eventfd_t *value)
{
if (!zvfs_eventfd_is_in_use(efd)) {
/* file descriptor has been closed */
return -EBADF;
}
if (efd->cnt == 0) {
/* would block / try again */
return -EAGAIN;
}
/* successful read */
if (zvfs_eventfd_is_semaphore(efd)) {
*value = 1;
--efd->cnt;
} else {
*value = efd->cnt;
efd->cnt = 0;
}
if (efd->cnt == 0) {
k_poll_signal_reset(&efd->read_sig);
}
k_poll_signal_raise(&efd->write_sig, 0);
return 0;
}
static int zvfs_eventfd_write_locked(struct zvfs_eventfd *efd, zvfs_eventfd_t *value)
{
zvfs_eventfd_t result;
if (!zvfs_eventfd_is_in_use(efd)) {
/* file descriptor has been closed */
return -EBADF;
}
if (*value == UINT64_MAX) {
/* not a permitted value */
return -EINVAL;
}
if (u64_add_overflow(efd->cnt, *value, &result) || result == UINT64_MAX) {
/* would block / try again */
return -EAGAIN;
}
/* successful write */
efd->cnt = result;
if (efd->cnt == (UINT64_MAX - 1)) {
k_poll_signal_reset(&efd->write_sig);
}
k_poll_signal_raise(&efd->read_sig, 0);
return 0;
}
static ssize_t zvfs_eventfd_read_op(void *obj, void *buf, size_t sz)
{
return zvfs_eventfd_rw_op(obj, buf, sz, zvfs_eventfd_read_locked);
}
static ssize_t zvfs_eventfd_write_op(void *obj, const void *buf, size_t sz)
{
return zvfs_eventfd_rw_op(obj, (zvfs_eventfd_t *)buf, sz, zvfs_eventfd_write_locked);
}
static int zvfs_eventfd_close_op(void *obj)
{
int ret;
int err;
k_spinlock_key_t key;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
struct zvfs_eventfd *efd = (struct zvfs_eventfd *)obj;
if (k_is_in_isr()) {
/* not covered by the man page, but necessary in Zephyr */
errno = EWOULDBLOCK;
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_in_use(efd)) {
errno = EBADF;
ret = -1;
goto unlock;
}
err = sys_bitarray_free(&efds_bitarray, 1, (struct zvfs_eventfd *)obj - efds);
__ASSERT(err == 0, "sys_bitarray_free() failed: %d", err);
efd->flags = 0;
efd->cnt = 0;
ret = 0;
unlock:
k_spin_unlock(&efd->lock, key);
/* when closing an zvfs_eventfd, broadcast to all waiters */
err = k_condvar_broadcast(cond);
__ASSERT(err == 0, "k_condvar_broadcast() failed: %d", err);
return ret;
}
static int zvfs_eventfd_ioctl_op(void *obj, unsigned int request, va_list args)
{
int ret;
k_spinlock_key_t key;
struct zvfs_eventfd *efd = (struct zvfs_eventfd *)obj;
/* note: zsock_poll_internal() has already taken the mutex */
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_in_use(efd)) {
errno = EBADF;
ret = -1;
goto unlock;
}
switch (request) {
case F_GETFL:
ret = efd->flags & ZVFS_EFD_FLAGS_SET;
break;
case F_SETFL: {
int flags;
flags = va_arg(args, int);
if (flags & ~ZVFS_EFD_FLAGS_SET) {
errno = EINVAL;
ret = -1;
} else {
int prev_flags = efd->flags & ~ZVFS_EFD_FLAGS_SET;
efd->flags = flags | prev_flags;
ret = 0;
}
} break;
case ZFD_IOCTL_POLL_PREPARE: {
struct zsock_pollfd *pfd;
struct k_poll_event **pev;
struct k_poll_event *pev_end;
pfd = va_arg(args, struct zsock_pollfd *);
pev = va_arg(args, struct k_poll_event **);
pev_end = va_arg(args, struct k_poll_event *);
ret = zvfs_eventfd_poll_prepare(obj, pfd, pev, pev_end);
} break;
case ZFD_IOCTL_POLL_UPDATE: {
struct zsock_pollfd *pfd;
struct k_poll_event **pev;
pfd = va_arg(args, struct zsock_pollfd *);
pev = va_arg(args, struct k_poll_event **);
ret = zvfs_eventfd_poll_update(obj, pfd, pev);
} break;
default:
errno = EOPNOTSUPP;
ret = -1;
break;
}
unlock:
k_spin_unlock(&efd->lock, key);
return ret;
}
static const struct fd_op_vtable zvfs_eventfd_fd_vtable = {
.read = zvfs_eventfd_read_op,
.write = zvfs_eventfd_write_op,
.close = zvfs_eventfd_close_op,
.ioctl = zvfs_eventfd_ioctl_op,
};
/* common to both zvfs_eventfd_read_op() and zvfs_eventfd_write_op() */
static ssize_t zvfs_eventfd_rw_op(void *obj, void *buf, size_t sz,
int (*op)(struct zvfs_eventfd *efd, zvfs_eventfd_t *value))
{
int err;
ssize_t ret;
k_spinlock_key_t key;
struct zvfs_eventfd *efd = obj;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
if (sz < sizeof(zvfs_eventfd_t)) {
errno = EINVAL;
return -1;
}
if (buf == NULL) {
errno = EFAULT;
return -1;
}
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_blocking(efd)) {
/*
* Handle the non-blocking case entirely within this scope
*/
ret = op(efd, buf);
if (ret < 0) {
errno = -ret;
ret = -1;
} else {
ret = sizeof(zvfs_eventfd_t);
}
goto unlock_spin;
}
/*
* Handle the blocking case below
*/
__ASSERT_NO_MSG(zvfs_eventfd_is_blocking(efd));
if (k_is_in_isr()) {
/* not covered by the man page, but necessary in Zephyr */
errno = EWOULDBLOCK;
ret = -1;
goto unlock_spin;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
k_spin_unlock(&efd->lock, key);
while (true) {
/* retake the spinlock */
key = k_spin_lock(&efd->lock);
ret = op(efd, buf);
switch (ret) {
case -EAGAIN:
/* not an error in blocking mode. break and try again */
break;
case 0:
/* success! */
ret = sizeof(zvfs_eventfd_t);
goto unlock;
default:
/* some other error */
__ASSERT_NO_MSG(ret < 0);
errno = -ret;
ret = -1;
goto unlock;
}
/* do not hold a spinlock when taking a mutex */
k_spin_unlock(&efd->lock, key);
/* wait for a write or close */
err = k_condvar_wait(cond, lock, K_FOREVER);
__ASSERT(err == 0, "k_condvar_wait() failed: %d", err);
}
unlock:
k_spin_unlock(&efd->lock, key);
/* only wake a single waiter */
err = k_condvar_signal(cond);
__ASSERT(err == 0, "k_condvar_signal() failed: %d", err);
goto out;
unlock_spin:
k_spin_unlock(&efd->lock, key);
out:
return ret;
}
/*
* Public-facing API
*/
int zvfs_eventfd(unsigned int initval, int flags)
{
int fd = 1;
size_t offset;
struct zvfs_eventfd *efd = NULL;
if (flags & ~ZVFS_EFD_FLAGS_SET) {
errno = EINVAL;
return -1;
}
if (sys_bitarray_alloc(&efds_bitarray, 1, &offset) < 0) {
errno = ENOMEM;
return -1;
}
efd = &efds[offset];
fd = zvfs_reserve_fd();
if (fd < 0) {
sys_bitarray_free(&efds_bitarray, 1, offset);
return -1;
}
efd->flags = ZVFS_EFD_IN_USE | flags;
efd->cnt = initval;
k_poll_signal_init(&efd->write_sig);
k_poll_signal_init(&efd->read_sig);
if (initval != 0) {
k_poll_signal_raise(&efd->read_sig, 0);
}
k_poll_signal_raise(&efd->write_sig, 0);
zvfs_finalize_fd(fd, efd, &zvfs_eventfd_fd_vtable);
return fd;
}
int zvfs_eventfd_read(int fd, zvfs_eventfd_t *value)
{
int ret;
void *obj;
int err;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
obj = zvfs_get_fd_obj(fd, &zvfs_eventfd_fd_vtable, EBADF);
if (obj == NULL) {
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
err = k_mutex_lock(lock, K_FOREVER);
__ASSERT(err == 0, "k_mutex_lock() failed: %d", err);
ret = zvfs_eventfd_rw_op(obj, value, sizeof(zvfs_eventfd_t), zvfs_eventfd_read_locked);
__ASSERT_NO_MSG(ret == -1 || ret == sizeof(zvfs_eventfd_t));
err = k_mutex_unlock(lock);
__ASSERT(err == 0, "k_mutex_unlock() failed: %d", err);
if (ret < 0) {
return -1;
}
return 0;
}
int zvfs_eventfd_write(int fd, zvfs_eventfd_t value)
{
int ret;
void *obj;
int err;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
obj = zvfs_get_fd_obj(fd, &zvfs_eventfd_fd_vtable, EBADF);
if (obj == NULL) {
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
err = k_mutex_lock(lock, K_FOREVER);
__ASSERT(err == 0, "k_mutex_lock() failed: %d", err);
ret = zvfs_eventfd_rw_op(obj, &value, sizeof(zvfs_eventfd_t), zvfs_eventfd_write_locked);
__ASSERT_NO_MSG(ret == -1 || ret == sizeof(zvfs_eventfd_t));
err = k_mutex_unlock(lock);
__ASSERT(err == 0, "k_mutex_unlock() failed: %d", err);
if (ret < 0) {
return -1;
}
return 0;
}

View File

@ -0,0 +1,5 @@
/* SPDX-License-Identifier: Apache-2.0 */
#include <zephyr/zvfs/eventfd.h>
int zvfs_eventfd(unsigned int initial,int flags) { (void)initial;(void)flags;errno=ENOSYS;return -1; }
int zvfs_eventfd_read(int fd,zvfs_eventfd_t *value) { (void)fd;(void)value;errno=ENOSYS;return -1; }
int zvfs_eventfd_write(int fd,zvfs_eventfd_t value) { (void)fd;(void)value;errno=ENOSYS;return -1; }

View File

@ -0,0 +1,5 @@
在这个事件通知工作区中,基础自测能够完成;把相同计数器接入多个执行上下文后,现场出现了消费者等不到后续数据、生产者也不再返回的现象。另一些调用组合会在另一个上下文尚占用描述符时提前结束,单独运行时却正常。
请修复模块,让两种调用接口都符合 `docs/api-contract.md` 的全部条款,并保持计数、错误返回、关闭和 poll 的既有行为。当前目录包含生产代码与一个可在主机运行的受控内核端口;不需要板卡或网络。
运行 `make smoke` 可做基础自测。可使用 README 中的上下文接口增加复现。最终只提交并评分 `lib/os/zvfs/zvfs_eventfd.c`。

View File

@ -0,0 +1,102 @@
# runtime-zephyr-eventfd-lock-progress
## 1. 身份与状态
路线D;族 linux-concurrency;语言C;split `zephyrproject-rtos/zephyr`。
状态 CALIBRATED,难度/真实Agent/硬件 UNMEASURED。此题仅做受控软件校准。
上游 https://github.com/zephyrproject-rtos/zephyr ;修复前 `48ab80061b07247e0a9606785bb600e777588718`,修复 `aa607f9b0a6d3ac0976debc26d70caf6dfb076c7`。
所有冻结C/H文件均有 Apache-2.0 SPDX头,根LICENSE原样附带;上游根没有NOTICE。本地支撑同为Apache-2.0。
## 2. 真实缺陷与冻结范围
只有一个上游真实修复,但它跨 `zvfs_eventfd_close_op`、`zvfs_eventfd_rw_op`、`zvfs_eventfd_read`、`zvfs_eventfd_write` 四个函数:描述符层已持对象mutex时,内部公共读写再取得递归mutex,条件等待只释放一层,别的上下文无法获取同一mutex并提供数据/空间;直接入口仍需取得描述符mutex,包含非阻塞操作。close亦按描述符层合同修复。
没有额外人工缺陷。gold是修复提交中候选文件的完整原样版本,没有补改gold。
完整冻结真实eventfd(485行)、fdtable、poll和kernel/condvar,保持对象查找/锁/条件等待/通知/轮询链。内核mutex按上游文档提供递归语义;条件等待采用原样 `kernel/condvar.c`,没有用桩替换目标锁策略。host port只做通用上下文调度、mutex、spinlock、poll信号和未用FS构建依赖。没有基于候选函数、题目输入或答案选择端口行为。
唯一候选 `lib/os/zvfs/zvfs_eventfd.c`。全部template代码实际 2249 行,不计fixture重复、许可证、判据和文档。源文件清单如下:
| 文件 | 来源 | 行数 | SHA-256 |
| --- | --- | --- | --- |
| `LICENSE` | 上游冻结 | 202 | c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08 |
| `Makefile` | 补全 | 12 | 3cac8e423dee7bbe4f16e9c1cead11d1b998d0a96f69d0019b8a3a47971926d1 |
| `README.md` | 补全 | 17 | 412e3366d958b4c620341f53d3164eceb126e95049a7b83e66529677879ca79e |
| `doc/kernel/services/synchronization/mutexes.rst` | 上游冻结 | 188 | c33da75bb8bd6301803ca1c2046d0544774ce12c29dbd442c198114281c103e9 |
| `docs/api-contract.md` | 补全 | 85 | 6845c44320d0d3ab6f3c2f0c0e540ac53a40774eb8ab1db93d95dd1122a64c49 |
| `host/host.c` | 补全 | 143 | d85e6731a38d105e09dc2b9d7dbc555419307b011a8696b3bbf7ea001a0efc66 |
| `host/host.h` | 补全 | 11 | b0ed82a4531be6fcfb8d060c2c831c47d36c5ef1263323ede318baad0bfcdf2a |
| `include/ksched.h` | 补全 | 7 | 8c79cecc739a0e02f4bb5489c7f7eebeee4fcd199b0663b23a5b24a354e31fbf |
| `include/wait_q.h` | 补全 | 2 | 2e8bb5be21fcf250cbdf424e371db99a5bdcdb43245a21129461c484b0783eb0 |
| `include/zephyr/fs/fs.h` | 补全 | 11 | d2fd6d3a61882423db697b0cab78dc0f8464a65115c610e5d92321e3e9b8f9b2 |
| `include/zephyr/init.h` | 补全 | 1 | f7096fb07fe51ed00a8602375ab4bca01f3bb802579c48e8e671f32cda3d52af |
| `include/zephyr/internal/syscall_handler.h` | 补全 | 1 | f7096fb07fe51ed00a8602375ab4bca01f3bb802579c48e8e671f32cda3d52af |
| `include/zephyr/kernel.h` | 补全 | 73 | 10e99fc7b3a5ed1e6501d91903e70b646d2a517a3c508ca3044b7ec85284aa7b |
| `include/zephyr/kernel_structs.h` | 补全 | 2 | 2e8bb5be21fcf250cbdf424e371db99a5bdcdb43245a21129461c484b0783eb0 |
| `include/zephyr/net/socket.h` | 补全 | 5 | 944f9288d801195baf4a6a3ba564da68e61ad8e214144c7995921d5880b2096b |
| `include/zephyr/posix/fcntl.h` | 补全 | 4 | e11d2b43c7f88dfa0132c21242d2c21c634f47dfc90d84b429a626da59cebd98 |
| `include/zephyr/sys/atomic.h` | 补全 | 11 | 2ff0167c3f1764db70000b700f61c3ca0515dce8b80827b801f90b96193fb843 |
| `include/zephyr/sys/bitarray.h` | 补全 | 19 | 74ef9f3e9bff5459cabd6854d3646386384445ed5a18851fc38541100fe7b6b3 |
| `include/zephyr/sys/fdtable.h` | 上游冻结 | 389 | a4312961a50308365125fc9cd3d6552439d621483175adc0d9a58d5d17ad529b |
| `include/zephyr/sys/math_extras.h` | 补全 | 5 | 8b2cd57086b1064ec02c0ef4ff4bd45687e1b7902bc795f14c389a04456a0682 |
| `include/zephyr/sys/speculation.h` | 补全 | 2 | 58778ceae9e14e94222c10758b38712be0e3bcfb2d3e6f05e1b109f76f8b8b31 |
| `include/zephyr/sys/util.h` | 补全 | 11 | b7e6bb0ee272b6d925fc6029dd0a6c9ec24b2f2ed03b1935e36c612f8fc723c7 |
| `include/zephyr/syscalls/fdtable.h` | 补全 | 1 | f7096fb07fe51ed00a8602375ab4bca01f3bb802579c48e8e671f32cda3d52af |
| `include/zephyr/toolchain.h` | 补全 | 2 | 2e8bb5be21fcf250cbdf424e371db99a5bdcdb43245a21129461c484b0783eb0 |
| `include/zephyr/zvfs/eventfd.h` | 上游冻结 | 66 | 91c48f80e88f645439aab5fa84a464f1202e7310e745570c751c070e5821b873 |
| `kernel/condvar.c` | 上游冻结 | 163 | 2c5dc96ee4c881704627873ca5dc1d8b241c8bb8369faa0b624a21ad466b2bae |
| `lib/os/zvfs/zvfs_eventfd.c` | 上游冻结 | 485 | b5f83ce96efc056a93fd591e57acec8a2e8615fda6487387dddbf440f918a856 |
| `lib/os/zvfs/zvfs_fdtable.c` | 上游冻结 | 609 | e8a3445e563162faf304d4fccbd179b1d917e14fd524d59f731561ab83225896 |
| `lib/os/zvfs/zvfs_poll.c` | 上游冻结 | 213 | c0f5b9cd784c4ecef0c6e177a156e64af2f605d9f8df4bcd2ef71fad5e903dee |
| `smoke.c` | 补全 | 13 | 068390d918875954dc93956183e430c29db96c3be862aed1f38774d06ce3f0f3 |
补全目的:`host/host.[ch]` 为协作上下文、通用内核原语;include下非冻结头为最小依赖;Makefile和smoke.c为正常非阻塞往返;README与api-contract为公开合同整理。未修改冻结源;无上游git、修复测试、issue/提交信息进入公开材料。
## 3. 公开依据和判据矩阵
所有正式期望在父 `check.py` 中独立模型计算。C observer只执行调用、打印原始返回/errno/值/完成标志/重入事件,不计算PASS或预期关系。
| 检查项 | 公开依据 | 上游依据 |
| --- | --- | --- |
| 创建初值/合法flags/非法flags | docs/api-contract.md:8-12 R01 | eventfd.c `zvfs_eventfd`;eventfd.h flags/API |
| 池耗尽与关闭复用 | docs/api-contract.md:11-12 R01 | efds_bitarray分配/close释放 |
| 描述符返回8及size 0/1/7/8/9/16 | docs/api-contract.md:14-18 R02 | eventfd.h:33-34;rw_op大小校验 |
| NULL缓冲区和错误不改读值 | docs/api-contract.md:18,22,26 R02-R04 | rw_op NULL校验/locked读先验 |
| 直接读写返回0和常规读写等效 | docs/api-contract.md:20-22 R03 | eventfd.h:25-29,40-61 |
| 普通读归零/信号量逐单位读取 | docs/api-contract.md:24-26 R04 | read_locked |
| 累加、零写、最大值、超过容量及无效写值 | docs/api-contract.md:28-32 R05 | write_locked |
| 非阻塞空/容量错误EAGAIN | docs/api-contract.md:34-40 R06 | rw_op非阻塞分支与locked EAGAIN |
| 读等待、写等待、双API交叉唤醒和多等待者 | docs/api-contract.md:34-40 R06 | rw_op/condvar_wait;kernel/condvar.c |
| 持描述符mutex时完成边界/释放后继续 | docs/api-contract.md:42-47 R07 | fdtable.h:187-215 mutex防并发;fdtable.c zvfs_rw/close;direct公共接口同对象 |
| close唤醒全部读写等待者EBADF,旧/负/越界fd | docs/api-contract.md:49-51 R08 | close_op广播与read_locked EBADF;fdtable _check_fd |
| 零/非零/满计数的POLLIN/POLLOUT和等待唤醒 | docs/api-contract.md:53-58 R09 | eventfd poll_prepare/update;完整zvfs_poll.c |
| 负fd忽略及其他无效fd POLLNVAL | docs/api-contract.md:60-61 R10 | zvfs_poll.c负fd与查找失败分支 |
| GETFL/SETFL有效切换、非法位保持旧flags | docs/api-contract.md:63-66 R11 | eventfd_ioctl_op |
| 递归mutex和原样condvar单层release/reacquire | docs/api-contract.md:68-72 R12 | doc/kernel/services/synchronization/mutexes.rst Reentrant Locking;kernel/condvar.c:112-129 |
| 无可运行上下文阶段快照;不要求内部锁次数/helper | docs/api-contract.md:74-80 R13 | 补全host调度器的公开接口 |
依据表16项。输入随机使用固定种子0xaa607f9,父check独立按R01-R11计算期望;不会取gold运行结果作答案。公开smoke只走单对象非阻塞正常路径,故意不暴露目标等待/互斥症状。
## 4. 样例
- gold PASS:修复提交中候选文件原样。
- template FAIL:原样冻结真实缺陷。
- noop FAIL:公开入口返回ENOSYS。
- cheat FAIL:返回固定smoke读值7,破坏一般计数。
- cheat_read_grader FAIL:以gold为底,要求读取私有check成功;拒读受控退出。另用无秘密可读占位文件验证可读分支,真实grader在/oracle保护。
- symptom_only FAIL:仅采用gold的操作层改动,保留旧直接入口;描述符互等症状消失但直接非阻塞入口仍不能遵守对象互斥。
- valid_shared_entry PASS:使用不同的共享直接入口,通过fd/vtable/mutex查找并验证vtable,统一保护直接读写,没有照抄gold两套入口。
总7类,每类正式校准5次,共35次。单缺陷不需要only-one样例。
## 5. 隔离、确定性和执行
verify.py与rollout/bos_verify.py原样一致;grader_files仅check.py与support.tar。归档包含非候选冻结/补全支撑和raw observer,不包含期望。tar成员uid/gid均0;父check逐个安全路径/常规文件校验并用write_bytes生成0644文件,避免继承host所有权。候选与gcc仅在子进程运行,由平台降至UID/GID65534;父check保留全部期望。无Python候选import,无shell外部命令。
软件端口使用协作上下文,每次推进到blocked/completed后观察,非真实时间/线程优先级判据。另一上下文实际执行描述符写/读/关闭/锁竞争,观察API完成和值,不以内部锁次数判定。调度无可运行项即返回,缺陷不会拖到墙钟超时。独立子进程总期限3秒防挂死,编译20秒,平台check总100秒、task期限120秒。
所有上游构建/运行仅在固定trace6 digest、--network none Docker内执行;不做trusted-local。正式校准路径、诊断、当前摘要和清理见本题report/progress。未运行真实Agent、模型、硬件或难度采样。
## 6. 校准与限制
正式校准35/35符合预期,cleanup confirmed;回执 `runs/20261103-D-oss-fix-29/zephyr-aa607f9/calibration-7d6a3e7ed0df450a87eb799481394a8d/receipt.json`,task digest `af1634f0c0133d6fbc824ab595171208021b6556f4385e46734b2d8142ae4269`。诊断03中gold/valid通过、负例拒绝,可读占位控制通过;原始等待/互斥/关闭观察见作者目录diagnostic-raw-01.jsonl。仅支持此无硬件host执行模型;不验证Zephyr真实调度器优先级/抢占、ISR、用户态保护、FS后端、墙钟超时或真实板卡。
root负责独立只读审阅及全库unittest;作者不提交。

Binary file not shown.

View File

@ -0,0 +1,475 @@
/*
* Copyright (c) 2020 Tobias Svehagen
* Copyright (c) 2023, Meta
* Copyright (c) 2024, Tenstorrent AI ULC
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <zephyr/net/socket.h>
#include <zephyr/posix/fcntl.h>
#include <zephyr/zvfs/eventfd.h>
#include <zephyr/sys/bitarray.h>
#include <zephyr/sys/fdtable.h>
#include <zephyr/sys/math_extras.h>
#define ZVFS_EFD_IN_USE 0x1
#define ZVFS_EFD_FLAGS_SET (ZVFS_EFD_SEMAPHORE | ZVFS_EFD_NONBLOCK)
struct zvfs_eventfd {
struct k_poll_signal read_sig;
struct k_poll_signal write_sig;
struct k_spinlock lock;
zvfs_eventfd_t cnt;
int flags;
};
static ssize_t zvfs_eventfd_rw_op(void *obj, void *buf, size_t sz,
int (*op)(struct zvfs_eventfd *efd, zvfs_eventfd_t *value));
SYS_BITARRAY_DEFINE_STATIC(efds_bitarray, CONFIG_ZVFS_EVENTFD_MAX);
static struct zvfs_eventfd efds[CONFIG_ZVFS_EVENTFD_MAX];
static const struct fd_op_vtable zvfs_eventfd_fd_vtable;
static inline bool zvfs_eventfd_is_in_use(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_IN_USE) != 0;
}
static inline bool zvfs_eventfd_is_semaphore(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_SEMAPHORE) != 0;
}
static inline bool zvfs_eventfd_is_blocking(struct zvfs_eventfd *efd)
{
return (efd->flags & ZVFS_EFD_NONBLOCK) == 0;
}
static int zvfs_eventfd_poll_prepare(struct zvfs_eventfd *efd,
struct zsock_pollfd *pfd,
struct k_poll_event **pev,
struct k_poll_event *pev_end)
{
if (pfd->events & ZSOCK_POLLIN) {
if (*pev == pev_end) {
errno = ENOMEM;
return -1;
}
(*pev)->obj = &efd->read_sig;
(*pev)->type = K_POLL_TYPE_SIGNAL;
(*pev)->mode = K_POLL_MODE_NOTIFY_ONLY;
(*pev)->state = K_POLL_STATE_NOT_READY;
(*pev)++;
}
if (pfd->events & ZSOCK_POLLOUT) {
if (*pev == pev_end) {
errno = ENOMEM;
return -1;
}
(*pev)->obj = &efd->write_sig;
(*pev)->type = K_POLL_TYPE_SIGNAL;
(*pev)->mode = K_POLL_MODE_NOTIFY_ONLY;
(*pev)->state = K_POLL_STATE_NOT_READY;
(*pev)++;
}
return 0;
}
static int zvfs_eventfd_poll_update(struct zvfs_eventfd *efd,
struct zsock_pollfd *pfd,
struct k_poll_event **pev)
{
if (pfd->events & ZSOCK_POLLIN) {
pfd->revents |= ZSOCK_POLLIN * (efd->cnt > 0);
(*pev)++;
}
if (pfd->events & ZSOCK_POLLOUT) {
pfd->revents |= ZSOCK_POLLOUT * (efd->cnt < UINT64_MAX - 1);
(*pev)++;
}
return 0;
}
static int zvfs_eventfd_read_locked(struct zvfs_eventfd *efd, zvfs_eventfd_t *value)
{
if (!zvfs_eventfd_is_in_use(efd)) {
/* file descriptor has been closed */
return -EBADF;
}
if (efd->cnt == 0) {
/* would block / try again */
return -EAGAIN;
}
/* successful read */
if (zvfs_eventfd_is_semaphore(efd)) {
*value = 1;
--efd->cnt;
} else {
*value = efd->cnt;
efd->cnt = 0;
}
if (efd->cnt == 0) {
k_poll_signal_reset(&efd->read_sig);
}
k_poll_signal_raise(&efd->write_sig, 0);
return 0;
}
static int zvfs_eventfd_write_locked(struct zvfs_eventfd *efd, zvfs_eventfd_t *value)
{
zvfs_eventfd_t result;
if (!zvfs_eventfd_is_in_use(efd)) {
/* file descriptor has been closed */
return -EBADF;
}
if (*value == UINT64_MAX) {
/* not a permitted value */
return -EINVAL;
}
if (u64_add_overflow(efd->cnt, *value, &result) || result == UINT64_MAX) {
/* would block / try again */
return -EAGAIN;
}
/* successful write */
efd->cnt = result;
if (efd->cnt == (UINT64_MAX - 1)) {
k_poll_signal_reset(&efd->write_sig);
}
k_poll_signal_raise(&efd->read_sig, 0);
return 0;
}
static ssize_t zvfs_eventfd_read_op(void *obj, void *buf, size_t sz)
{
return zvfs_eventfd_rw_op(obj, buf, sz, zvfs_eventfd_read_locked);
}
static ssize_t zvfs_eventfd_write_op(void *obj, const void *buf, size_t sz)
{
return zvfs_eventfd_rw_op(obj, (zvfs_eventfd_t *)buf, sz, zvfs_eventfd_write_locked);
}
static int zvfs_eventfd_close_op(void *obj)
{
int ret;
int err;
k_spinlock_key_t key;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
struct zvfs_eventfd *efd = (struct zvfs_eventfd *)obj;
if (k_is_in_isr()) {
/* not covered by the man page, but necessary in Zephyr */
errno = EWOULDBLOCK;
return -1;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_in_use(efd)) {
errno = EBADF;
ret = -1;
goto unlock;
}
err = sys_bitarray_free(&efds_bitarray, 1, (struct zvfs_eventfd *)obj - efds);
__ASSERT(err == 0, "sys_bitarray_free() failed: %d", err);
efd->flags = 0;
efd->cnt = 0;
ret = 0;
unlock:
k_spin_unlock(&efd->lock, key);
/* when closing an zvfs_eventfd, broadcast to all waiters */
err = k_condvar_broadcast(cond);
__ASSERT(err == 0, "k_condvar_broadcast() failed: %d", err);
return ret;
}
static int zvfs_eventfd_ioctl_op(void *obj, unsigned int request, va_list args)
{
int ret;
k_spinlock_key_t key;
struct zvfs_eventfd *efd = (struct zvfs_eventfd *)obj;
/* note: zsock_poll_internal() has already taken the mutex */
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_in_use(efd)) {
errno = EBADF;
ret = -1;
goto unlock;
}
switch (request) {
case F_GETFL:
ret = efd->flags & ZVFS_EFD_FLAGS_SET;
break;
case F_SETFL: {
int flags;
flags = va_arg(args, int);
if (flags & ~ZVFS_EFD_FLAGS_SET) {
errno = EINVAL;
ret = -1;
} else {
int prev_flags = efd->flags & ~ZVFS_EFD_FLAGS_SET;
efd->flags = flags | prev_flags;
ret = 0;
}
} break;
case ZFD_IOCTL_POLL_PREPARE: {
struct zsock_pollfd *pfd;
struct k_poll_event **pev;
struct k_poll_event *pev_end;
pfd = va_arg(args, struct zsock_pollfd *);
pev = va_arg(args, struct k_poll_event **);
pev_end = va_arg(args, struct k_poll_event *);
ret = zvfs_eventfd_poll_prepare(obj, pfd, pev, pev_end);
} break;
case ZFD_IOCTL_POLL_UPDATE: {
struct zsock_pollfd *pfd;
struct k_poll_event **pev;
pfd = va_arg(args, struct zsock_pollfd *);
pev = va_arg(args, struct k_poll_event **);
ret = zvfs_eventfd_poll_update(obj, pfd, pev);
} break;
default:
errno = EOPNOTSUPP;
ret = -1;
break;
}
unlock:
k_spin_unlock(&efd->lock, key);
return ret;
}
static const struct fd_op_vtable zvfs_eventfd_fd_vtable = {
.read = zvfs_eventfd_read_op,
.write = zvfs_eventfd_write_op,
.close = zvfs_eventfd_close_op,
.ioctl = zvfs_eventfd_ioctl_op,
};
/* common to both zvfs_eventfd_read_op() and zvfs_eventfd_write_op() */
static ssize_t zvfs_eventfd_rw_op(void *obj, void *buf, size_t sz,
int (*op)(struct zvfs_eventfd *efd, zvfs_eventfd_t *value))
{
int err;
ssize_t ret;
k_spinlock_key_t key;
struct zvfs_eventfd *efd = obj;
struct k_mutex *lock = NULL;
struct k_condvar *cond = NULL;
if (sz < sizeof(zvfs_eventfd_t)) {
errno = EINVAL;
return -1;
}
if (buf == NULL) {
errno = EFAULT;
return -1;
}
key = k_spin_lock(&efd->lock);
if (!zvfs_eventfd_is_blocking(efd)) {
/*
* Handle the non-blocking case entirely within this scope
*/
ret = op(efd, buf);
if (ret < 0) {
errno = -ret;
ret = -1;
} else {
ret = sizeof(zvfs_eventfd_t);
}
goto unlock_spin;
}
/*
* Handle the blocking case below
*/
__ASSERT_NO_MSG(zvfs_eventfd_is_blocking(efd));
if (k_is_in_isr()) {
/* not covered by the man page, but necessary in Zephyr */
errno = EWOULDBLOCK;
ret = -1;
goto unlock_spin;
}
err = (int)zvfs_get_obj_lock_and_cond(obj, &zvfs_eventfd_fd_vtable, &lock, &cond);
__ASSERT((bool)err, "zvfs_get_obj_lock_and_cond() failed");
__ASSERT_NO_MSG(lock != NULL);
__ASSERT_NO_MSG(cond != NULL);
k_spin_unlock(&efd->lock, key);
while (true) {
/* retake the spinlock */
key = k_spin_lock(&efd->lock);
ret = op(efd, buf);
switch (ret) {
case -EAGAIN:
/* not an error in blocking mode. break and try again */
break;
case 0:
/* success! */
ret = sizeof(zvfs_eventfd_t);
goto unlock;
default:
/* some other error */
__ASSERT_NO_MSG(ret < 0);
errno = -ret;
ret = -1;
goto unlock;
}
/* do not hold a spinlock when taking a mutex */
k_spin_unlock(&efd->lock, key);
/* wait for a write or close */
err = k_condvar_wait(cond, lock, K_FOREVER);
__ASSERT(err == 0, "k_condvar_wait() failed: %d", err);
}
unlock:
k_spin_unlock(&efd->lock, key);
/* only wake a single waiter */
err = k_condvar_signal(cond);
__ASSERT(err == 0, "k_condvar_signal() failed: %d", err);
goto out;
unlock_spin:
k_spin_unlock(&efd->lock, key);
out:
return ret;
}
/*
* Public-facing API
*/
int zvfs_eventfd(unsigned int initval, int flags)
{
int fd = 1;
size_t offset;
struct zvfs_eventfd *efd = NULL;
if (flags & ~ZVFS_EFD_FLAGS_SET) {
errno = EINVAL;
return -1;
}
if (sys_bitarray_alloc(&efds_bitarray, 1, &offset) < 0) {
errno = ENOMEM;
return -1;
}
efd = &efds[offset];
fd = zvfs_reserve_fd();
if (fd < 0) {
sys_bitarray_free(&efds_bitarray, 1, offset);
return -1;
}
efd->flags = ZVFS_EFD_IN_USE | flags;
efd->cnt = initval;
k_poll_signal_init(&efd->write_sig);
k_poll_signal_init(&efd->read_sig);
if (initval != 0) {
k_poll_signal_raise(&efd->read_sig, 0);
}
k_poll_signal_raise(&efd->write_sig, 0);
zvfs_finalize_fd(fd, efd, &zvfs_eventfd_fd_vtable);
return fd;
}
int zvfs_eventfd_read(int fd, zvfs_eventfd_t *value)
{
int ret;
void *obj;
obj = zvfs_get_fd_obj(fd, &zvfs_eventfd_fd_vtable, EBADF);
if (obj == NULL) {
return -1;
}
ret = zvfs_eventfd_rw_op(obj, value, sizeof(zvfs_eventfd_t), zvfs_eventfd_read_locked);
__ASSERT_NO_MSG(ret == -1 || ret == sizeof(zvfs_eventfd_t));
if (ret < 0) {
return -1;
}
return 0;
}
int zvfs_eventfd_write(int fd, zvfs_eventfd_t value)
{
int ret;
void *obj;
obj = zvfs_get_fd_obj(fd, &zvfs_eventfd_fd_vtable, EBADF);
if (obj == NULL) {
return -1;
}
ret = zvfs_eventfd_rw_op(obj, &value, sizeof(zvfs_eventfd_t), zvfs_eventfd_write_locked);
__ASSERT_NO_MSG(ret == -1 || ret == sizeof(zvfs_eventfd_t));
if (ret < 0) {
return -1;
}
return 0;
}

View File

@ -0,0 +1,27 @@
{
"id": "runtime-zephyr-eventfd-lock-progress",
"version": "1",
"family": "linux-concurrency",
"language": "c",
"source": "oss/zephyrproject-rtos/zephyr@aa607f9b0a6d",
"split": "zephyrproject-rtos/zephyr",
"template": "template",
"verifier": "verify.py",
"candidate_files": [
"lib/os/zvfs/zvfs_eventfd.c"
],
"grader_files": [
"check.py",
"support.tar"
],
"timeout_seconds": 120,
"fixtures": {
"gold": "PASS",
"template": "FAIL",
"noop": "FAIL",
"cheat": "FAIL",
"cheat_read_grader": "FAIL",
"symptom_only": "FAIL",
"valid_shared_entry": "PASS"
}
}

View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,12 @@
CC = gcc
CFLAGS = -std=c11 -O0 -g -Iinclude -Ihost -ffunction-sections -fdata-sections
SOURCES = lib/os/zvfs/zvfs_eventfd.c lib/os/zvfs/zvfs_fdtable.c lib/os/zvfs/zvfs_poll.c kernel/condvar.c host/host.c
.PHONY: all smoke clean
all: build/smoke
build/smoke: $(SOURCES) smoke.c
mkdir -p build
$(CC) $(CFLAGS) $(SOURCES) smoke.c -Wl,--gc-sections -o $@
smoke: build/smoke
./build/smoke
clean:
rm -rf build

View File

@ -0,0 +1,17 @@
# Event notification host workspace
This software-only reproduction includes production descriptor dispatch,
event notification, condition variable, and poll code. `host/` supplies a small
cooperative kernel port; `include/` contains the original public headers and
minimal build dependencies. File-system backend calls are unavailable in this
workspace. The event notification path does not use that backend.
Run `make smoke`. It prints a nonblocking counter round trip on one descriptor.
The full delivery contract is `docs/api-contract.md` (R01 through R13).
For additional self-tests, build an observer against the `SOURCES` in the
Makefile. Independent contexts can be created with `host_spawn`, then advanced
with `host_run`; `host_park` and `host_wake` support controlled handoffs.
Descriptor lookup returns the same mutex used by the production dispatch.
Only `lib/os/zvfs/zvfs_eventfd.c` is collected for evaluation. New files and edits
to other files can help investigation but are not part of the submitted patch.

View File

@ -0,0 +1,188 @@
.. _mutexes_v2:
Mutexes
#######
A :dfn:`mutex` is a kernel object that implements a traditional
reentrant mutex. A mutex allows multiple threads to safely share
an associated hardware or software resource by ensuring mutually exclusive
access to the resource.
.. contents::
:local:
:depth: 2
Concepts
********
Any number of mutexes can be defined (limited only by available RAM). Each mutex
is referenced by its memory address.
A mutex has the following key properties:
* A **lock count** that indicates the number of times the mutex has been locked
by the thread that has locked it. A count of zero indicates that the mutex
is unlocked.
* An **owning thread** that identifies the thread that has locked the mutex,
when it is locked.
A mutex must be initialized before it can be used. This sets its lock count
to zero.
A thread that needs to use a shared resource must first gain exclusive rights
to access it by **locking** the associated mutex. If the mutex is already locked
by another thread, the requesting thread may choose to wait for the mutex
to be unlocked.
After locking a mutex, the thread may safely use the associated resource
for as long as needed; however, it is considered good practice to hold the lock
for as short a time as possible to avoid negatively impacting other threads
that want to use the resource. When the thread no longer needs the resource
it must **unlock** the mutex to allow other threads to use the resource.
Any number of threads may wait on a locked mutex simultaneously.
When the mutex becomes unlocked it is then locked by the highest-priority
thread that has waited the longest.
.. note::
Mutex objects are *not* designed for use by ISRs.
Reentrant Locking
=================
A thread is permitted to lock a mutex it has already locked.
This allows the thread to access the associated resource at a point
in its execution when the mutex may or may not already be locked.
A mutex that is repeatedly locked by a thread must be unlocked an equal number
of times before the mutex becomes fully unlocked so it can be claimed
by another thread.
Priority Inheritance
====================
The thread that has locked a mutex is eligible for :dfn:`priority inheritance`.
This means the kernel will *temporarily* elevate the thread's priority
if a higher priority thread begins waiting on the mutex. This allows the owning
thread to complete its work and release the mutex more rapidly by executing
at the same priority as the waiting thread. Once the mutex has been unlocked,
the unlocking thread resets its priority to the level it had before locking
that mutex.
.. note::
The :kconfig:option:`CONFIG_PRIORITY_CEILING` configuration option limits
how high the kernel can raise a thread's priority due to priority
inheritance. The default value of 0 permits unlimited elevation.
The owning thread's base priority is saved in the mutex when it obtains the
lock. Each time a higher priority thread waits on a mutex, the kernel adjusts
the owning thread's priority. When the owning thread releases the lock (or if
the high priority waiting thread times out), the kernel restores the thread's
base priority from the value saved in the mutex.
This works well for priority inheritance as long as only one locked mutex is
involved. However, if multiple mutexes are involved, sub-optimal behavior will
be observed if the mutexes are not unlocked in the reverse order to which the
owning thread's priority was previously raised. Consequently it is recommended
that a thread lock only a single mutex at a time when multiple mutexes are
shared between threads of different priorities.
Implementation
**************
Defining a Mutex
================
A mutex is defined using a variable of type :c:struct:`k_mutex`.
It must then be initialized by calling :c:func:`k_mutex_init`.
The following code defines and initializes a mutex.
.. code-block:: c
struct k_mutex my_mutex;
k_mutex_init(&my_mutex);
Alternatively, a mutex can be defined and initialized at compile time
by calling :c:macro:`K_MUTEX_DEFINE`.
The following code has the same effect as the code segment above.
.. code-block:: c
K_MUTEX_DEFINE(my_mutex);
Locking a Mutex
===============
A mutex is locked by calling :c:func:`k_mutex_lock`.
The following code builds on the example above, and waits indefinitely
for the mutex to become available if it is already locked by another thread.
.. code-block:: c
k_mutex_lock(&my_mutex, K_FOREVER);
The following code waits up to 100 milliseconds for the mutex to become
available, and gives a warning if the mutex does not become available.
.. code-block:: c
if (k_mutex_lock(&my_mutex, K_MSEC(100)) == 0) {
/* mutex successfully locked */
} else {
printf("Cannot lock XYZ display\n");
}
Unlocking a Mutex
=================
A mutex is unlocked by calling :c:func:`k_mutex_unlock`.
The following code builds on the example above,
and unlocks the mutex that was previously locked by the thread.
.. code-block:: c
k_mutex_unlock(&my_mutex);
Suggested Uses
**************
Use a mutex to provide exclusive access to a resource, such as a physical
device.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_PRIORITY_CEILING`
API Reference
*************
.. doxygengroup:: mutex_apis
Futex API Reference
*******************
k_futex is a lightweight mutual exclusion primitive designed to minimize
kernel involvement. Uncontended operation relies only on atomic access
to shared memory. k_futex are tracked as kernel objects and can live in
user memory so that any access bypasses the kernel object permission
management mechanism.
.. doxygengroup:: futex_apis
User Mode Mutex API Reference
*****************************
sys_mutex behaves almost exactly like k_mutex, with the added advantage
that a sys_mutex instance can reside in user memory. When user mode isn't
enabled, sys_mutex behaves like k_mutex.
.. doxygengroup:: user_mutex_apis

View File

@ -0,0 +1,85 @@
# Event notification interface
This workspace provides the Zephyr event notification object, file descriptor table,
condition variables, and poll dispatcher, with a cooperative host kernel port.
The following interface contract applies to both direct event notification calls
and descriptor I/O. The host port uses a release configuration without assertions.
**R01** `zvfs_eventfd(initial, flags)` creates a separate 64-bit counter initialized
from its unsigned initial value. The supported flags are `ZVFS_EFD_NONBLOCK` and
`ZVFS_EFD_SEMAPHORE`, in any combination. Other flags fail with `-1/EINVAL`.
The configured pool contains eight event notification objects; exhaustion fails
with `-1/ENOMEM`. Closing an object returns its slot for subsequent creation.
**R02** Descriptor operations use `zvfs_read(fd, buffer, size, NULL)`,
`zvfs_write(fd, buffer, size, NULL)`, and `zvfs_close(fd)`.
Successful reads and writes transfer eight bytes even when the supplied buffer
is larger. Sizes below eight fail with `-1/EINVAL`. With an adequate size,
a null buffer fails with `-1/EFAULT`.
**R03** `zvfs_eventfd_read(fd, &value)` and `zvfs_eventfd_write(fd, value)`
provide the same counter operations, returning zero on success and `-1` on error.
A null read destination fails with `EFAULT`.
**R04** A successful ordinary read returns the accumulated counter and resets it
to zero. A semaphore read returns one and subtracts one. An empty counter cannot
satisfy a read. Reads returning errors leave the destination value unchanged.
**R05** A successful write adds its value to the counter. Writing zero succeeds
without changing the count. The largest counter value is `UINT64_MAX-1`.
A write of `UINT64_MAX` fails with `EINVAL`. Other writes that would exceed
the counter limit cannot complete until sufficient capacity is available.
Errors leave the counter unchanged.
**R06** An operation that cannot complete returns `-1/EAGAIN` in nonblocking mode.
In blocking mode it waits for a change, allowing a different execution context to
perform the counter operation needed for progress. It retries against the current
state after notification. Both direct calls and descriptor calls can be used on
either side of this interaction. Several waiting reads may consume the available
counter units, with ordinary reads draining all units and semaphore reads taking
one each; waiters without available units continue waiting.
**R07** The descriptor mutex returned by `zvfs_get_fd_obj_and_vtable` or
`zvfs_get_obj_lock_and_cond` prevents concurrent descriptor access. Both counter
interfaces and close respect this exclusion: while another context holds this
mutex, they wait until it releases it, including when data is immediately
available or the descriptor is in nonblocking mode. Once access is released,
eligible operations can complete.
**R08** `zvfs_close` returns zero on success. Closing while reads or writes are waiting
notifies all of them; these operations fail with `-1/EBADF`. Operations on a closed,
negative, or out-of-range descriptor fail with `-1/EBADF`.
**R09** `z_impl_zvfs_poll(fds, count, timeout_ms)` reports readable readiness when
the counter is nonzero and writable readiness when it is below `UINT64_MAX-1`.
It returns the number of entries with nonzero `revents`. Requested events are
`ZVFS_POLLIN` and `ZVFS_POLLOUT`; unrequested events are not returned.
A zero timeout observes the current readiness. A negative timeout waits, and a
write that provides data wakes a pending readable poll.
**R10** Poll ignores negative descriptor entries and sets their `revents` to zero.
Other invalid descriptors report `ZVFS_POLLNVAL` and contribute one to the result.
**R11** The object ioctl interface supports `ZVFS_F_GETFL` and `ZVFS_F_SETFL`.
Getting flags returns the two supported user flags. Setting valid flags changes
the current read/write behavior without resetting the counter. Unsupported flag
bits fail with `-1/EINVAL` and preserve the previous flags.
**R12** A kernel mutex is recursive for its owning context. Other contexts wait
until all acquisitions have been released. A condition wait releases one mutex
acquisition, suspends on the condition queue, and reacquires the mutex before
returning. Signaling releases one queued waiter; broadcasting releases all.
These primitives have the same semantics for every object in this host port.
**R13** The host scheduler runs each context until it blocks or completes.
`host_run()` returns when no context is runnable. A context parked by
`host_park()` resumes after `host_wake(id)`. Observing an unfinished operation at
such a boundary records a pending operation, not a timer expiry. There is no
wall clock deadline in the cooperative model. Numeric errno names and constants
use the host C library. No particular internal helper or acquisition count is
part of the event notification API.
The upstream headers in `include/zephyr/zvfs/eventfd.h` and
`include/zephyr/sys/fdtable.h`, the descriptor dispatch in
`lib/os/zvfs/zvfs_fdtable.c`, and the kernel condition implementation in
`kernel/condvar.c` provide the associated interfaces and execution context.

Some files were not shown because too many files have changed in this diff Show More