savedata: persist save data memory durably #696

Closed
github-bot wants to merge 1 commit from gh-pr/696/head into gh-pr/696/base
Owner

@⁠1OO1O11O on GitHub · 2026-09-18 08:40 UTC · original
1OO1O11O:savedata-durable-memory → main · +1208 −112 · 7 files · 1 commits · closed without merging

Problem

sceSaveDataSetupSaveDataMemory2 / Get / Set / Sync are backed by one process-wide std::vector<uint8_t> that is never written to disk:

  • progress is lost the moment the emulator exits — the save data memory API is how a number of titles store their progress;
  • every user, slot and title shares the same buffer, so they overwrite each other;
  • Get returns a zeroed SaveDataParam and an icon of size 0 regardless of what was stored;
  • SaveDataSyncSaveDataMemory does nothing and never queues the completion event a title waits on.

What this does

Adds Libs::SaveData::SaveDataMemoryStore (src/libs/saveDataMemory.{h,cpp}) and wires the four entry points to it. Each title/user/slot keeps its own snapshot at:

_SaveData/<title id>/sce_sdmemory[N]/<user id>/memory.sdm

Durability. Guest bytes, SaveDataParam and the icon live in one checksummed container, so an update is published by a single rename: write a temporary file → flush it to the platter → rename over the previous save → flush the directory entry. Interrupt it anywhere before the rename and the previous save is still intact; a file that does not decode is reported as SAVE_DATA_ERROR_BROKEN instead of being handed to the title as its save. I/O failures are mapped to save data errors and returned, never swallowed into a successful-looking save.

Write-through. Every Set is published before it returns, so a title that never calls sceSaveDataSyncSaveDataMemory still keeps its progress across an exit or a crash. Sync re-publishes (a retry for a previously failed durability barrier) and, in its asynchronous form, queues SAVE_DATA_EVENT_TYPE_MEMORY_SYNC_END.

Windows sharing conflicts. A replacing rename fails while any other process holds a handle that does not permit deletion — which is exactly what a virus scanner or search indexer does for a moment after every file close. Uncontended, this lost roughly two out of three saves on the machine this was developed on. Such a failure is now waited out for about a second before the save is reported as failed; a genuine permission error still surfaces.

Isolation. A slot is held under an exclusive lock file while it is set up, so a second emulator process cannot write the same save concurrently (it gets SAVE_DATA_ERROR_BUSY). The event queue gained its own mutex, since the sync event is now queued from a path that already holds the mount lock.

API fidelity. init_param / init_icon are only read when the caller passes SET_PARAM, since a title that did not ask for them may leave those pointers uninitialized; setup never truncates existing progress or overwrites existing metadata with initialization data; user_id < 0 returns SAVE_DATA_ERROR_INVALID_LOGIN_USER; data_num is capped at the documented maximum; the store stamps param.mtime on every update; a Set with nothing to update does no I/O. The title id is reduced to characters that cannot form a path component of their own before it names a directory (CWE-22) — deliberately not a CUSA/PPSA format check, which would leave homebrew and system titles unable to save at all.

Tests

tests/SaveDataMemoryTests.cpp (registered as save_data_memory, added to the Windows, macOS and Linux CI jobs) covers:

  • parameter validation, unsafe title ids, and ordinary non-CUSA title ids;
  • SET_PARAM gating of the initialization data;
  • isolation across users, slots and titles, including cross-process exclusion;
  • injected I/O failures at create, write, flush, rename and directory-flush, each checked for "the old save is still there and still complete";
  • corrupt, truncated and extended save files;
  • a scanner-style sharing conflict (fails without the retry above);
  • concurrent writers with no lost updates;
  • child processes killed mid-write, mid-flush, mid-rename and after publication, with a fresh process verifying that what it reads back is either the complete old snapshot or the complete new one.

tests/save_data_memory/CMakeLists.txt builds the same test standalone, so it runs on a machine with no Vulkan SDK, Qt or glslangValidator:

cmake -S tests/save_data_memory -B _Build/save-memory -G Ninja
cmake --build _Build/save-memory && ctest --test-dir _Build/save-memory --output-on-failure

Ran green 25+ consecutive times on Windows (MinGW). The full emulator build was not exercised locally — this environment has no clang-cl/Vulkan toolchain — so the CI jobs are the real check on that; src/libs/libSaveData.cpp was compiled standalone against the emulator headers.

Relationship to #659

#659 fixes the same bug with a different on-disk layout (raw memory.dat plus a param.bin sidecar) and is the older PR; this one focuses on making an update atomic and its failures visible: a single checksummed file replaced by one rename, flushes checked, and crash/interruption behaviour covered by tests that kill real child processes. The container here is deliberately named memory.sdm so neither implementation can read the other's file as if it were its own format. Happy to rebase on top of #659, fold the two together, or close this if you prefer that approach.

**@⁠1OO1O11O** on GitHub · 2026-09-18 08:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/696) `1OO1O11O:savedata-durable-memory` → `main` · +1208 −112 · 7 files · 1 commits · closed without merging ## Problem `sceSaveDataSetupSaveDataMemory2` / `Get` / `Set` / `Sync` are backed by one process-wide `std::vector<uint8_t>` that is never written to disk: - progress is lost the moment the emulator exits — the save data memory API is how a number of titles store their progress; - every user, slot and title shares the same buffer, so they overwrite each other; - `Get` returns a zeroed `SaveDataParam` and an icon of size 0 regardless of what was stored; - `SaveDataSyncSaveDataMemory` does nothing and never queues the completion event a title waits on. ## What this does Adds `Libs::SaveData::SaveDataMemoryStore` (`src/libs/saveDataMemory.{h,cpp}`) and wires the four entry points to it. Each title/user/slot keeps its own snapshot at: ``` _SaveData/<title id>/sce_sdmemory[N]/<user id>/memory.sdm ``` **Durability.** Guest bytes, `SaveDataParam` and the icon live in one checksummed container, so an update is published by a single rename: write a temporary file → flush it to the platter → rename over the previous save → flush the directory entry. Interrupt it anywhere before the rename and the previous save is still intact; a file that does not decode is reported as `SAVE_DATA_ERROR_BROKEN` instead of being handed to the title as its save. I/O failures are mapped to save data errors and returned, never swallowed into a successful-looking save. **Write-through.** Every `Set` is published before it returns, so a title that never calls `sceSaveDataSyncSaveDataMemory` still keeps its progress across an exit or a crash. `Sync` re-publishes (a retry for a previously failed durability barrier) and, in its asynchronous form, queues `SAVE_DATA_EVENT_TYPE_MEMORY_SYNC_END`. **Windows sharing conflicts.** A replacing rename fails while any other process holds a handle that does not permit deletion — which is exactly what a virus scanner or search indexer does for a moment after every file close. Uncontended, this lost roughly two out of three saves on the machine this was developed on. Such a failure is now waited out for about a second before the save is reported as failed; a genuine permission error still surfaces. **Isolation.** A slot is held under an exclusive lock file while it is set up, so a second emulator process cannot write the same save concurrently (it gets `SAVE_DATA_ERROR_BUSY`). The event queue gained its own mutex, since the sync event is now queued from a path that already holds the mount lock. **API fidelity.** `init_param` / `init_icon` are only read when the caller passes `SET_PARAM`, since a title that did not ask for them may leave those pointers uninitialized; setup never truncates existing progress or overwrites existing metadata with initialization data; `user_id < 0` returns `SAVE_DATA_ERROR_INVALID_LOGIN_USER`; `data_num` is capped at the documented maximum; the store stamps `param.mtime` on every update; a `Set` with nothing to update does no I/O. The title id is reduced to characters that cannot form a path component of their own before it names a directory (CWE-22) — deliberately not a `CUSA`/`PPSA` format check, which would leave homebrew and system titles unable to save at all. ## Tests `tests/SaveDataMemoryTests.cpp` (registered as `save_data_memory`, added to the Windows, macOS and Linux CI jobs) covers: - parameter validation, unsafe title ids, and ordinary non-`CUSA` title ids; - `SET_PARAM` gating of the initialization data; - isolation across users, slots and titles, including cross-process exclusion; - injected I/O failures at create, write, flush, rename and directory-flush, each checked for "the old save is still there and still complete"; - corrupt, truncated and extended save files; - a scanner-style sharing conflict (fails without the retry above); - concurrent writers with no lost updates; - child processes killed mid-write, mid-flush, mid-rename and after publication, with a fresh process verifying that what it reads back is either the complete old snapshot or the complete new one. `tests/save_data_memory/CMakeLists.txt` builds the same test standalone, so it runs on a machine with no Vulkan SDK, Qt or glslangValidator: ``` cmake -S tests/save_data_memory -B _Build/save-memory -G Ninja cmake --build _Build/save-memory && ctest --test-dir _Build/save-memory --output-on-failure ``` Ran green 25+ consecutive times on Windows (MinGW). The full emulator build was not exercised locally — this environment has no clang-cl/Vulkan toolchain — so the CI jobs are the real check on that; `src/libs/libSaveData.cpp` was compiled standalone against the emulator headers. ## Relationship to #659 #659 fixes the same bug with a different on-disk layout (raw `memory.dat` plus a `param.bin` sidecar) and is the older PR; this one focuses on making an update atomic and its failures visible: a single checksummed file replaced by one rename, flushes checked, and crash/interruption behaviour covered by tests that kill real child processes. The container here is deliberately named `memory.sdm` so neither implementation can read the other's file as if it were its own format. Happy to rebase on top of #659, fold the two together, or close this if you prefer that approach.
sceSaveDataSetupSaveDataMemory2 and friends kept the save data memory in a
single process-wide std::vector that was never written anywhere, so every title
using the save data memory API lost its progress on exit, and all users, slots
and titles shared one buffer.

Store each title/user/slot as its own snapshot under
_SaveData/<title>/sce_sdmemory[N]/<user>/memory.sdm. Data, parameters and icon
live in one checksummed file so an update is published by a single rename: the
replacement is written to a temporary file, flushed to the platter, renamed over
the previous save and the directory entry flushed after it. A snapshot that is
interrupted anywhere before the rename leaves the previous save intact, and a
file that does not decode is reported as SAVE_DATA_ERROR_BROKEN instead of being
handed to the title as its save. I/O failures reach the caller as save data
errors rather than being reported as a successful save.

Every Set is published before it returns, so a title that never calls
sceSaveDataSyncSaveDataMemory keeps its progress across an exit or a crash.
Sync re-publishes and, in its asynchronous form, queues the MEMORY_SYNC_END
event the title waits for.

On Windows a replacing rename fails while any other process holds a handle that
does not permit deletion, which is what a virus scanner or search indexer does
for a moment after every close. Uncontended, that lost roughly two out of three
saves on this machine. A sharing failure is now waited out for about a second
before the save is reported as failed.

A slot is held under an exclusive lock file for as long as it is set up, so a
second emulator process cannot write the same save concurrently, and the event
queue now has its own mutex because the sync event is queued from a locked path.

Tested by tests/SaveDataMemoryTests.cpp: validation, title ids, setup options,
user/slot/title isolation, injected I/O failures at each stage, corrupt and
truncated saves, a scanner-style sharing conflict, concurrent writers, and child
processes killed mid-write, mid-flush, mid-rename and after publication, each
verifying that a reopened save is either the complete old snapshot or the
complete new one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:30:05 +00:00
github-bot closed this pull request 2026-11-26 09:30:05 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 08:53 UTC · original

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change replaces process-local save-data memory with filesystem-backed SaveDataMemoryStore persistence. It adds validated snapshots, locking, checksums, atomic replacement, synchronization, and fault injection. The save-data library delegates memory operations to the store and queues sync completion events. New integration tests cover persistence, corruption, concurrency, failures, and restart recovery. CMake and CI now build and run the tests on Windows, macOS, and Linux.

Suggested reviewers: nmzik

Priority: ➖ Normal

Change: Bug fix

Merge Risk: 🟡 Moderate · up to 18a1e

Distinct titles can share or overwrite save data, while some macOS volumes cannot save at all. These persistence issues should be fixed before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 75 functions across 4 files. (3 skipped: 3… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description clearly explains the durable, isolated persistence changes, implementation details, API behavior, and tests.
Title check ✅ Passed The title clearly and concisely identifies the main change: durable persistence for save data memory.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 9.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 75 functions across 4 files. (3 skipped: 3 unsupported.)


Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 08:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/696#issuecomment-5727622653) <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/696#gh-light-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg" alt="Review Change Stack" width="202" height="32"></a><a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/696#gh-dark-mode-only"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg" alt="Review Change Stack" width="202" height="32"></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary>📝 Walkthrough</summary> ## Walkthrough The change replaces process-local save-data memory with filesystem-backed `SaveDataMemoryStore` persistence. It adds validated snapshots, locking, checksums, atomic replacement, synchronization, and fault injection. The save-data library delegates memory operations to the store and queues sync completion events. New integration tests cover persistence, corruption, concurrency, failures, and restart recovery. CMake and CI now build and run the tests on Windows, macOS, and Linux. **Suggested reviewers:** `nmzik` </details> <!-- walkthrough_end --> <!-- change_assessment_start --> **Priority:** ➖ Normal <!-- change_assessment_commit:"18a1e79588382c98bfaeb9935e6372242a79fff0" --> **Change:** Bug fix <!-- change_assessment_end --> <!-- final_review_risk_start --> **Merge Risk:** _🟡 Moderate_ · up to `18a1e` <!-- final_review_risk_coverage:{"sourceCommitId":"18a1e79588382c98bfaeb9935e6372242a79fff0","coveredCommitId":"18a1e79588382c98bfaeb9935e6372242a79fff0","kind":"reviewed"} --> Distinct titles can share or overwrite save data, while some macOS volumes cannot save at all. These persistence issues should be fixed before merge. <!-- final_review_risk_end --> <!-- pre_merge_checks_walkthrough_start --> <details> <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary> ### ❌ Failed checks (1 warning) | Check name | Status | Explanation | Resolution | | :----------------: | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ⚠️ Warning | Docstring coverage is 9.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 75 functions across 4 files. (3 skipped: 3… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary>✅ Passed checks (4 passed)</summary> | Check name | Status | Explanation | | :------------------------: | :------- | :--------------------------------------------------------------------------------------------------------------------------- | | Description check | ✅ Passed | The description clearly explains the durable, isolated persistence changes, implementation details, API behavior, and tests. | | Title check | ✅ Passed | The title clearly and concisely identifies the main change: durable persistence for save data memory. | | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. | </details> <details> <summary>Full details: Docstring Coverage</summary> **Explanation** Docstring coverage is 9.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 75 functions across 4 files. (3 skipped: 3 unsupported.) </details> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- tips_start --> --- <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -250,3 +203,4 @@
static void queue_save_data_event(uint32_t type, int32_t user_id,
const SceSaveDataTitleId* title_id,
const SceSaveDataDirName* dir_name, int32_t error_code = OK) {
Common::LockGuard event_lock(g_event_mutex);
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 08:53 UTC · original

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '165,215p' src/libs/libSaveData.cpp
sed -n '390,470p' src/libs/saveDataMemory.cpp
rg -n 'get_title_id|TitleId|title_id|UNKNOWN|ValidTitle' src/libs tests/SaveDataMemoryTests.cpp

Repository: KytyPS5/KytyPS5

Length of output: 12825


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- saveDataMemory key validation and path/lock flow ---'
sed -n '130,210p' src/libs/saveDataMemory.cpp
sed -n '1,130p' src/libs/saveDataMemory.cpp
printf '%s\n' '--- libSaveData memory API callers ---'
sed -n '430,520p' src/libs/libSaveData.cpp
printf '%s\n' '--- TITLE_ID loader binding ---'
rg -n -A12 -B8 'SystemContentParamSfoGetString' --glob '*.cpp' --glob '*.h' .
printf '%s\n' '--- focused tests ---'
sed -n '200,255p' tests/SaveDataMemoryTests.cpp
sed -n '255,405p' tests/SaveDataMemoryTests.cpp
printf '%s\n' '--- public memory API registration/declarations ---'
rg -n -A8 -B8 'sceSaveData(Set|Get|Setup)SaveDataMemory|SaveDataMemory(Setup|Get|Set)' src tests

Repository: KytyPS5/KytyPS5

Length of output: 50371


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exact title-ID source implementation ---'
sed -n '560,645p' src/loader/systemContent.cpp
rg -n -A20 -B12 'GetParamString|LoadParamSfo|param.sfo|SystemContentLoadParamSfo' src/loader src/common tests --glob '*.cpp' --glob '*.h'
printf '%s\n' '--- complete memory lookup and lock flow ---'
sed -n '250,430p' src/libs/saveDataMemory.cpp
printf '%s\n' '--- all direct get_title_id uses and save-data registrations ---'
rg -n -A5 -B5 'SaveData(Setup|Get|Set)SaveDataMemory2|SaveDataMemory2|get_title_id\(\)' src --glob '*.cpp' --glob '*.h'
printf '%s\n' '--- title-ID format evidence ---'
rg -n -i -A4 -B4 'title.?id|content.?id|CUSA|PPSA|NPXS|UNKNOWN' README.md docs src tests --glob '*.md' --glob '*.cpp' --glob '*.h' --glob '*.json' | head -n 240

Repository: KytyPS5/KytyPS5

Length of output: 50371


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- Psf text-value parsing and validation ---'
sed -n '45,125p' src/loader/systemContent.cpp
sed -n '125,230p' src/loader/systemContent.cpp
sed -n '230,340p' src/loader/systemContent.cpp
printf '%s\n' '--- param-file construction and TITLE_ID examples ---'
rg -n -A8 -B8 'TITLE_ID|AddParamString|OpenJson|param.json' src/loader tests --glob '*.cpp' --glob '*.h'

Repository: KytyPS5/KytyPS5

Length of output: 21490


Use a collision-free title-ID key. SystemContent::OpenJson() accepts any string-valued titleId, and Psf::GetParamString() returns it without title-ID validation. get_title_id() then removes every character outside [A-Za-z0-9_-] and maps missing, empty, or fully removed values to UNKNOWN.

Distinct source values such as A.B and AB therefore produce the same key. A missing TITLE_ID also shares a key with a title whose value is UNKNOWN. The memory APIs pass this key to SaveDataMemoryStore; ValidTitle() accepts it, and the store uses it in the record key and in the save and lock paths. One title can therefore read or overwrite another title's save, or both titles can contend for the same lock.

Encode the complete source value without collisions, or reject invalid and ambiguous values at this boundary. Keep the missing-value fallback separate from a valid UNKNOWN title ID.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 08:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/696#discussion_r4045253400) _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '165,215p' src/libs/libSaveData.cpp sed -n '390,470p' src/libs/saveDataMemory.cpp rg -n 'get_title_id|TitleId|title_id|UNKNOWN|ValidTitle' src/libs tests/SaveDataMemoryTests.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 12825 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- saveDataMemory key validation and path/lock flow ---' sed -n '130,210p' src/libs/saveDataMemory.cpp sed -n '1,130p' src/libs/saveDataMemory.cpp printf '%s\n' '--- libSaveData memory API callers ---' sed -n '430,520p' src/libs/libSaveData.cpp printf '%s\n' '--- TITLE_ID loader binding ---' rg -n -A12 -B8 'SystemContentParamSfoGetString' --glob '*.cpp' --glob '*.h' . printf '%s\n' '--- focused tests ---' sed -n '200,255p' tests/SaveDataMemoryTests.cpp sed -n '255,405p' tests/SaveDataMemoryTests.cpp printf '%s\n' '--- public memory API registration/declarations ---' rg -n -A8 -B8 'sceSaveData(Set|Get|Setup)SaveDataMemory|SaveDataMemory(Setup|Get|Set)' src tests ``` Repository: KytyPS5/KytyPS5 Length of output: 50371 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- exact title-ID source implementation ---' sed -n '560,645p' src/loader/systemContent.cpp rg -n -A20 -B12 'GetParamString|LoadParamSfo|param.sfo|SystemContentLoadParamSfo' src/loader src/common tests --glob '*.cpp' --glob '*.h' printf '%s\n' '--- complete memory lookup and lock flow ---' sed -n '250,430p' src/libs/saveDataMemory.cpp printf '%s\n' '--- all direct get_title_id uses and save-data registrations ---' rg -n -A5 -B5 'SaveData(Setup|Get|Set)SaveDataMemory2|SaveDataMemory2|get_title_id\(\)' src --glob '*.cpp' --glob '*.h' printf '%s\n' '--- title-ID format evidence ---' rg -n -i -A4 -B4 'title.?id|content.?id|CUSA|PPSA|NPXS|UNKNOWN' README.md docs src tests --glob '*.md' --glob '*.cpp' --glob '*.h' --glob '*.json' | head -n 240 ``` Repository: KytyPS5/KytyPS5 Length of output: 50371 --- 🏁 Script executed: ```bash #!/bin/bash set -e printf '%s\n' '--- Psf text-value parsing and validation ---' sed -n '45,125p' src/loader/systemContent.cpp sed -n '125,230p' src/loader/systemContent.cpp sed -n '230,340p' src/loader/systemContent.cpp printf '%s\n' '--- param-file construction and TITLE_ID examples ---' rg -n -A8 -B8 'TITLE_ID|AddParamString|OpenJson|param.json' src/loader tests --glob '*.cpp' --glob '*.h' ``` Repository: KytyPS5/KytyPS5 Length of output: 21490 --- </details> **Use a collision-free title-ID key.** `SystemContent::OpenJson()` accepts any string-valued `titleId`, and `Psf::GetParamString()` returns it without title-ID validation. `get_title_id()` then removes every character outside `[A-Za-z0-9_-]` and maps missing, empty, or fully removed values to `UNKNOWN`. Distinct source values such as `A.B` and `AB` therefore produce the same key. A missing `TITLE_ID` also shares a key with a title whose value is `UNKNOWN`. The memory APIs pass this key to `SaveDataMemoryStore`; `ValidTitle()` accepts it, and the store uses it in the record key and in the save and lock paths. One title can therefore read or overwrite another title's save, or both titles can contend for the same lock. Encode the complete source value without collisions, or reject invalid and ambiguous values at this boundary. Keep the missing-value fallback separate from a valid `UNKNOWN` title ID. <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:4c8253440b9bf7f96410a54b --> <!-- This is an auto-generated comment by CodeRabbit -->
@ -0,0 +338,4 @@
do { flushed = fcntl(file.handle, F_FULLFSYNC); } while (flushed < 0 && errno == EINTR);
#else
do { flushed = fsync(file.handle); } while (flushed < 0 && errno == EINTR);
#endif
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 08:53 UTC · original

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '300,380p' src/libs/saveDataMemory.cpp
sed -n '429,540p' src/libs/saveDataMemory.cpp
rg -n 'F_FULLFSYNC|FullFlush|WriteSnapshot|fsync' src tests

Repository: KytyPS5/KytyPS5

Length of output: 10761


🌐 Web query:

Apple macOS F_FULLFSYNC unsupported filesystem ENOTSUP EINVAL fallback fsync documentation

💡 Result:

<search_synthesis>
On macOS, the F_FULLFSYNC command used with fcntl(2) is intended to provide stronger data persistence guarantees than the standard fsync(2) system call by requesting that the storage device flush all buffered data to permanent storage [1][2][3]. However, support for F_FULLFSYNC is filesystem-dependent and is not implemented across all volumes (e.g., it is typically supported on HFS, APFS, and UDF, but often unsupported on network mounts like SMB, or FUSE-based filesystems) [4][5][6][2][3]. When a filesystem does not support F_FULLFSYNC, fcntl(fd, F_FULLFSYNC) will fail [7][6]. Crucially, there is no single, reliable errno value that indicates a lack of support; various filesystems and kernel versions may return different error codes, including ENOTSUP (Not supported), EINVAL (Invalid argument), or ENOTTY (Inappropriate ioctl for device) [7][5][6]. Because of this inconsistency in error reporting, authoritative technical guidance and common practice among robust applications (such as database engines and language runtimes) is to use a fallback strategy [7][6]. If fcntl(fd, F_FULLFSYNC) fails, the application should fall back to calling fsync(fd) [7][6][8]. Many developers choose to treat any error from F_FULLFSYNC as a signal to fall back to fsync, as relying on specific errno codes is insufficient to guarantee compatibility across all storage environments [7][6].
</search_synthesis>

<source_evidence>

https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fsync.2.html Mac OS X Manual Page For fsync(2) Search Search Documentation Archive | ADC Home> Reference Library> Reference > Mac OS X > Mac OS X Man Pages | | --- | | This document is a Mac OS X manual page. Manual pages are a command-line technology for providing documentation. You can view these manual pages locally using the man(1) command. These manual pages come from many different sources, and thus, have a variety of writing styles. For more information about the manual page format, see the manual page for manpages(5). | | --- | --- | FSYNC(2) BSD System Calls Manual FSYNC(2) NAME fsync -- synchronize a file&`#39`;s in-core state with that on disk SYNOPSIS `#include` <unistd.h> int fsync(int fildes); DESCRIPTION Fsync() causes all modified data and attributes of fildes to be moved to a permanent storage device. This normally results in all in-core modi-fied modified fied copies of buffers for the associated file to be written to a disk. Note that while fsync() will flush all data from the host to the drive (i.e. the "permanent storage device"), the drive itself may not physi-cally physically cally write the data to the platters for quite some time and it may be written in an out-of-order sequence. Specifically, if the drive loses power or the OS crashes, the application may find that only some or none of their data was written. The disk drive may also re-order the data so that later writes may be present, while earlier writes are not. This is not a theoretical edge case. This scenario is easily reproduced with real world workloads and drive power failures. For applications that require tighter guarantees about the integrity of their data, Mac OS X provides the F_FULLFSYNC fcntl. The F_FULLFSYNC fcntl asks the drive to flush all buffered data to permanent storage. Applications, such as databases, that require a strict ordering of writes should use F_FULLFSYNC to ensure that their data is written in the order they expect. Please see fcntl(2) for more detail. RETURN VALUES The fsync() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error. ERRORS The fsync() system call will fail if: [EBADF] fildes is not a valid descriptor. [EINTR] Its execution is interrupted by a signal. [EINVAL] fildes refers to a file type (e.g., a socket) that does not support this operation. [EIO] An I/O error occurred while reading from or writing to the file system. If a queued I/O operation fails, fsync() may fail with any of the errors defined for read(2) or write(2). SEE ALSO fcntl(2), read(2), sync(2), write(2), sync(8), update(8) HISTORY The fsync() function call appeared in 4.2BSD. 4.2 Berkeley Distribution June 4, 1993 4.2 Berkeley Distribution | | --- | https://keith.github.io/xcode-man-pages/fcntl.2.html `F_BARRIERFSYNC` ... : Does the same thing as fsync(2) then issues a barrier command to the drive (arg is ignored). The barrier applies to I/O that have been flushed with fsync(2) on the same device before. These operations are guaranteed to be persisted before any other I/O that would follow the barrier, although no assumption should be made on what has been persisted or not when this call returns. After the barrier has been issued, operations on other FDs that have been fsync&`#39`;d before can still be re-ordered by the device, but not after the barrier. This is typically useful to guarantee valid state on disk when ordering is a concern but durability is not. A barrier can be used to order two phases of operations on a set of file descriptors and ensure that no file can possibly get persisted with the effect of the second phase without the effect of the first one. To do so, execute operations of phase one, then fsync(2) each FD and issue a single barrier. Finally execute operations of phase two. This is currently implemented on HFS and APFS. It requires hardware support, which Apple SSDs are guaranteed to provide. ... `F_FULLFSYNC` ... : Does the same thing as fsync(2) then asks the drive to flush all buffered data to the permanent storage device (arg is ignored). As this drains the entire queue of the device and acts as a barrier, data that had been fsync&`#39`;d on the same device before is guaranteed to be persisted when this call returns. This is currently implemented on HFS, MS-DOS (FAT), Universal Disk Format (UDF) and APFS file systems. The operation may take quite a while to complete. Certain FireWire drives have also been known to ignore the request to flush their buffered data. ... [`EINVAL`] : Cmd is `F_DUPFD` and arg is negative or greater than the maximum allowable number (see getdtablesize(2)). The argument cmd is `F_GETLK`, `F_SETLK`, `F_SETLKW`, `F_OFD_GETLK`, `F_OFD_SETLK` or `F_OFD_SETLKW`, and the data to which arg points is not valid, or fildes refers to a file that does not support locking. ... The argument cmd is `F_PREALLOCATE` and the fst_posmode is not a valid mode, or when `F_PEOFPOSMODE` is set and fst_offset is a non-zero value, or when `F_VOLPOSMODE` is set and fst_offset is a negative or zero value. ... TRANSFEREXTENTS` and the additional file ... is negative or both file descriptors reference ... [`ENOTSUP`] : Cmd is `F_TRANSFEREXTENTS` and the given files aren&`#39`;t on an APFS volume. https://manp.gs/mac/2/fcntl `F_BARRIERFSYNC` ... : Does the same thing as fsync(2) then issues a barrier command to the drive (arg is ignored). The barrier applies to I/O that have been flushed with fsync(2) on the same device before. These operations are guaranteed to be persisted before any other I/O that would follow the barrier, although no assumption should be made on what has been persisted or not when this call returns. After the barrier has been issued, operations on other FDs that have been fsync&`#39`;d before can still be re-ordered by the device, but not after the barrier. This is typically useful to guarantee valid state on disk when ordering is a concern but durability is not. A barrier can be used to order two phases of operations on a set of file descriptors and ensure that no file can possibly get persisted with the effect of the second phase without the effect of the first one. To do so, execute operations of phase one, then fsync(2) each FD and issue a single barrier. Finally execute operations of phase two. This is currently implemented on HFS and APFS. It requires hardware support, which Apple SSDs are guaranteed to provide. ... `F_FULLFSYNC` ... : Does the same thing as fsync(2) then asks the drive to flush all buffered data to the permanent storage device (arg is ignored). As this drains the entire queue of the device and acts as a barrier, data that had been fsync&`#39`;d on the same device before is guaranteed to be persisted when this call returns. This is currently implemented on HFS, MS-DOS (FAT), Universal Disk Format (UDF) and APFS file systems. The operation may take quite a while to complete. Certain FireWire drives have also been known to ignore the request to flush their buffered data. ... [`EINVAL`] : Cmd is `F_DUPFD` and arg is negative or greater than the maximum allowable number (see getdtablesize(2)). The argument cmd is `F_GETLK`, `F_SETLK`, `F_SETLKW`, `F_OFD_GETLK`, `F_OFD_SETLK` or `F_OFD_SETLKW`, and the data to which arg points is not valid, or fildes refers to a file that does not support locking. ... The argument cmd is `F_PREALLOCATE` and the fst_posmode is not a valid mode, or when `F_PEOFPOSMODE` is set and fst_offset is a non-zero value, or when `F_VOLPOSMODE` is set and fst_offset is a negative or zero value. ... The argument cmd is `F_PUNCHHOLE` and either fp_offset or fp_length are negative, or when both fp_offset and fp_length are not multiples of the file system block size, or when either fp_flags or reserved is non-zero value. ... The argument cmd is `F_TRANSFEREXTENTS` and the additional file descriptor is negative or both file descriptors reference the same file. ... [`ENOTSUP`] : Cmd is `F_TRANSFEREXTENTS` and the given files aren&`#39`;t on an APFS volume. GitHub issue 64215 in golang/go (link omitted to avoid creating a cross-reference) # Issue: golang/go `#64215` - Repository: golang/go | The Go programming language | 133K stars | Go ## os: File.Sync() returns ENOTSUP on network mounts that support fsync - Author: [`@⁠iamcalledrob`](https://github.com/iamcalledrob) - State: closed (completed) - Locked: true - Labels: OS-Darwin, NeedsFix, FrozenDueToAge - Assignees: [`@⁠mauri870`](https://github.com/mauri870) - Milestone: Go1.23 - Created: 2023-11-16T22:22:18Z - Updated: 2025-03-07T20:09:11Z - Closed: 2024-03-07T19:21:25Z - Closed by: [`@⁠gopherbot`](https://github.com/gopherbot) ### What version of Go are you using (`go version`)? ``` $ go version go version go1.21.0 darwin/arm64 ``` ### Does this issue reproduce with the latest release? Yes ### What operating system and processor architecture are you using (`go env`)? **`go env` Output** ``` $ go env GO111MODULE=&`#39`;&`#39`; GOARCH=&`#39`;arm64&`#39`; GOBIN=&`#39`;&`#39`; GOCACHE=&`#39`;/Users/rob/Library/Caches/go-build&`#39`; GOENV=&`#39`;/Users/rob/Library/Application Support/go/env&`#39`; GOEXE=&`#39`;&`#39`; GOEXPERIMENT=&`#39`;&`#39`; GOFLAGS=&`#39`;&`#39`; GOHOSTARCH=&`#39`;arm64&`#39`; GOHOSTOS=&`#39`;darwin&`#39`; GOINSECURE=&`#39`;&`#39`; GOMODCACHE=&`#39`;/Users/rob/go/pkg/mod&`#39`; GONOPROXY=&`#39`;&`#39`; GONOSUMDB=&`#39`;&`#39`; GOOS=&`#39`;darwin&`#39`; GOPATH=&`#39`;/Users/rob/go&`#39`; GOPRIVATE=&`#39`;&`#39`; GOPROXY=&`#39`;https://proxy.golang.org,direct&`#39`; GOROOT=&`#39`;/opt/homebrew/Cellar/go/1.21.0/libexec&`#39`; GOSUMDB=&`#39`;sum.golang.org&`#39`; GOTMPDIR=&`#39`;&`#39`; GOTOOLCHAIN=&`#39`;auto&`#39`; GOTOOLDIR=&`#39`;/opt/homebrew/Cellar/go/1.21.0/libexec/pkg/tool/darwin_arm64&`#39`; GOVCS=&`#39`;&`#39`; GOVERSION=&`#39`;go1.21.0&`#39`; GCCGO=&`#39`;gccgo&`#39`; AR=&`#39`;ar&`#39`; CC=&`#39`;cc&`#39`; CXX=&`#39`;c++&`#39`; CGO_ENABLED=&`#39`;1&`#39`; GOMOD=&`#39`;/dev/null&`#39`; GOWORK=&`#39`;&`#39`; CGO_CFLAGS=&`#39`;-O2 -g&`#39`; CGO_CPPFLAGS=&`#39`;&`#39`; CGO_CXXFLAGS=&`#39`;-O2 -g&`#39`; CGO_FFLAGS=&`#39`;-O2 -g&`#39`; CGO_LDFLAGS=&`#39`;-O2 -g&`#39`; PKG_CONFIG=&`#39`;pkg-config&`#39`; GOGCCFLAGS=&`#39`;-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/9x/tzryjjm93zvcvhmn517n9t3h0000gn/T/go-build3328922198=/tmp/go-build -gno-record-gcc-switches -fno-common&`#39`; ``` ### What did you do? 1. Mount a SMB share on macOS that supports fsync (`strict sync = yes`, the default since Samba 4.7.0) 2. Open a file on that share 3. Call `file.Sync()` ### What did you expect to see? No error. The fsync instruction is passed down to the network share, which takes action (or not, depending on its configuration) ### What did you see instead? Error: `ENOTSUP` It appears that a change was implemented in go1.12 for `#26650` which switched File.Sync() to call `fcntl(fd, F_FULLFSYNC)` rather than `fsync(fd)`. This was due to fsync not being implemented as expected on darwin. On local volumes, this change appears to work correctly. However, `F_FULLFSYNC` appears to be unsupported on SMB volumes--and likely elsewhere too. This means that the change as a result of `#26650` leads to `ENOTSUP` being returned where a Sync would have succeeded before. (I&`#39`;ve verified via samba logging that calling `unix.Fsync()` on the fd results in the correct fsync instruction being sent to the server, so darwin&`#39`;s wonky fsync() behaviour seems to only apply to local volumes) I&`#39`;d bet that most Go developers are not testing file operations in SMB mounts, so are shipping software that would have worked in 1.11, but in 1.12+ will fail. I&`#39`;ve had to resort to a workaround: ```go func sync(f *os.File) error { err := f.Sync() // Ensure fsync is called if Sync is not supported. There are scenarios (SMB mounts, ...?) where fsync will succeed but Sync will fail due if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && errors.Is(err, syscall.ENOTSUP) { err = unix.Fsync(int(file.Fd())) } return err } ``` --- ### Timeline **mauri870** added label `OS-Darwin`; added label `NeedsInvestigation` · Nov 17, 2023 at 4:30am **`@⁠mauri870`** commented · Nov 17, 2023 at 5:13am …[truncated] GitHub issue 79 in macfuse/macfuse (link omitted to avoid creating a cross-reference) # Calling fcntl(..., F_FULLFSYNC) on osxfuse volume returns "Invalid argument" error - State: closed - Author: AlexPlas - Created: 2013-04-10T16:56:56Z - Updated: 2013-04-23T18:41:55Z - Repository: macfuse/macfuse - Number: `#79` - Assignees: bfleischer --- Here is a simple test application which returns "Invalid argument" error for any file located on the osxfuse volume. I&`#39`;ve tested it on my own FS and on SSHFS from the site as well. ``` C `#include` <fcntl.h> int main(int argc, char **argv) { int fd; argc--; argv++; if(argc<1) exit(0); fd = open(*argv, O_RDWR|O_CREAT); if(fd<0) { perror("OPEN"); exit(0); } if(write(fd,"test",4)<0) { perror("WRITE"); exit(0); } if(fcntl(fd, F_FULLFSYNC) < 0) { perror("FCNTL"); exit(0); } close(fd); } ``` ## Timeline **dbgreen** commented on 2013-04-15T16:50:51Z: > Basically, any program that tries to do a full-sync will have issues. We also noticed this trying to run a database in an OSXFuse fs. **bfleischer** commented on 2013-04-15T17:24:51Z: > Sorry for the late reply. > > F_FULLFSYNC is currently not implemented. Thats why you are seeing the error. From a technical standpoint there would be no difference between calling `fsync` or `fcntl` with `F_FULLFSYNC` on a FUSE volume. For volumes that are actually backed by a physical hard drive is makes a difference though. Implementing F_FULLFSYNC should not be too difficult. > > On a side note, running a database on a FUSE volume might not be ideal because of the overhead and it will be very difficult to guarantee data integrity in case of a file system crash. Depending on the file system there might be several layers of caching that are not getting flushed when calling fsync or doing a fnctl with F_FULLFSYNC. **dbgreen** commented on 2013-04-15T18:19:41Z: > Benjamin, > The real problem for us is that we want to be able to run third party > software from within the fs, and since we don&`#39`;t control the code we can&`#39`;t > disable the full_sync. I personally would be fine if there were just a way > to accept the call but not do the full_sync, just do a fsync instead. > Right now it triggers an invalid arg error though. > > On Mon, Apr 15, 2013 at 12:24 PM, Benjamin Fleischer < > [email protected]> wrote: > > > Sorry for the late reply. > > > > From a technical standpoint there would be no difference between calling > > fsync or fcntl with F_FULLFSYNC on a FUSE volume. For volumes that are > > actually backed by a physical hard drive is makes a difference though. > > > > — > > Reply to this email directly or view it on GitHubhttps://github.com/osxfuse/osxfuse/issues/79#issuecomment-16399077 > > . **bfleischer** commented on 2013-04-15T18:41:37Z: > I edited my previous reply shortly after posting it.You might not have received a notification containing the edited version. > > I agree that we should be doing a plain `fsync` when `fnctl` is called with `F_FULLFSYNC`. Just accepting the call is not a good solution because it might cause data loss for some users. - bfleischer was assigned **dbgreen** commented on 2013-04-16T19:12:26Z: > Yeah, I agree that doing a plain fsync when fcntl is called with F_FULLSYNC is called would be the way to go. **bfleischer** commented on 2013-04-23T18:41:55Z: > Commit github.com/osxfuse/kext@e940e7d2fd adds support for `F_FULLSYNC`. Please let me know if you encounter any problems with the patch. - bfleischer closed

Citations:


🏁 Script executed:

sed -n '1,180p' src/libs/saveDataMemory.cpp
sed -n '260,355p' src/libs/saveDataMemory.cpp
rg -n -C 3 'IoError|WriteSnapshot|DirectoryFlush|F_FULLFSYNC|SAVE_DATA_ERROR_INTERNAL|Sync\(' src tests

Repository: KytyPS5/KytyPS5

Length of output: 46798


Fall back to fsync when F_FULLFSYNC is unavailable.

On macOS, fcntl(file.handle, F_FULLFSYNC) can fail with ENOTSUP, EOPNOTSUPP, EINVAL, or ENOTTY on writable volumes that do not implement it. WriteSnapshot maps that failure to SAVE_DATA_ERROR_INTERNAL before rename, so Set and Sync fail without publishing the snapshot. Fall back to fsync for these unsupported-operation errors. This preserves the write-before-rename sequence, but fsync does not provide F_FULLFSYNC's stronger power-loss guarantee.

🛡️ Proposed fallback
 	int flushed;
 `#ifdef` __APPLE__
 	do { flushed = fcntl(file.handle, F_FULLFSYNC); } while (flushed < 0 && errno == EINTR);
-#else
-	do { flushed = fsync(file.handle); } while (flushed < 0 && errno == EINTR);
+	if (flushed != 0 &&
+	    (errno == ENOTSUP || errno == EOPNOTSUPP || errno == EINVAL || errno == ENOTTY))
 `#endif`
+	{
+		do { flushed = fsync(file.handle); } while (flushed < 0 && errno == EINTR);
+	}
 	if (flushed != 0) return IoError();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

#ifdef __APPLE__
	do { flushed = fcntl(file.handle, F_FULLFSYNC); } while (flushed < 0 && errno == EINTR);
	if (flushed != 0 &&
	    (errno == ENOTSUP || errno == EOPNOTSUPP || errno == EINVAL || errno == ENOTTY))
#endif
	{
		do { flushed = fsync(file.handle); } while (flushed < 0 && errno == EINTR);
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 08:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/696#discussion_r4045253410) _🩺 Stability & Availability_ | _🟡 Minor_ | _⚡ Quick win_ <details> <summary>🔎 Supported by static analysis</summary> 🏁 Script executed: ```bash sed -n '300,380p' src/libs/saveDataMemory.cpp sed -n '429,540p' src/libs/saveDataMemory.cpp rg -n 'F_FULLFSYNC|FullFlush|WriteSnapshot|fsync' src tests ``` Repository: KytyPS5/KytyPS5 Length of output: 10761 --- 🌐 Web query: `Apple macOS F_FULLFSYNC unsupported filesystem ENOTSUP EINVAL fallback fsync documentation` 💡 Result: <search_synthesis> On macOS, the `F_FULLFSYNC` command used with `fcntl(2)` is intended to provide stronger data persistence guarantees than the standard `fsync(2)` system call by requesting that the storage device flush all buffered data to permanent storage [1][2][3]. However, support for `F_FULLFSYNC` is filesystem-dependent and is not implemented across all volumes (e.g., it is typically supported on HFS, APFS, and UDF, but often unsupported on network mounts like SMB, or FUSE-based filesystems) [4][5][6][2][3]. When a filesystem does not support `F_FULLFSYNC`, `fcntl(fd, F_FULLFSYNC)` will fail [7][6]. Crucially, there is no single, reliable `errno` value that indicates a lack of support; various filesystems and kernel versions may return different error codes, including `ENOTSUP` (Not supported), `EINVAL` (Invalid argument), or `ENOTTY` (Inappropriate ioctl for device) [7][5][6]. Because of this inconsistency in error reporting, authoritative technical guidance and common practice among robust applications (such as database engines and language runtimes) is to use a fallback strategy [7][6]. If `fcntl(fd, F_FULLFSYNC)` fails, the application should fall back to calling `fsync(fd)` [7][6][8]. Many developers choose to treat *any* error from `F_FULLFSYNC` as a signal to fall back to `fsync`, as relying on specific `errno` codes is insufficient to guarantee compatibility across all storage environments [7][6]. </search_synthesis> <source_evidence> <source> <title>Mac OS X Manual Page For fsync(2)</title> <location>https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fsync.2.html</location> <excerpt>Mac OS X Manual Page For fsync(2) Search Search Documentation Archive | ADC Home&gt; Reference Library&gt; Reference &gt; Mac OS X &gt; Mac OS X Man Pages | | --- | | This document is a Mac OS X manual page. Manual pages are a command-line technology for providing documentation. You can view these manual pages locally using the man(1) command. These manual pages come from many different sources, and thus, have a variety of writing styles. For more information about the manual page format, see the manual page for manpages(5). | | --- | --- | FSYNC(2) BSD System Calls Manual FSYNC(2) NAME fsync -- synchronize a file&`#39`;s in-core state with that on disk SYNOPSIS `#include` &lt;unistd.h&gt; int fsync(int fildes); DESCRIPTION Fsync() causes all modified data and attributes of fildes to be moved to a permanent storage device. This normally results in all in-core modi-fied modified fied copies of buffers for the associated file to be written to a disk. Note that while fsync() will flush all data from the host to the drive (i.e. the &quot;permanent storage device&quot;), the drive itself may not physi-cally physically cally write the data to the platters for quite some time and it may be written in an out-of-order sequence. Specifically, if the drive loses power or the OS crashes, the application may find that only some or none of their data was written. The disk drive may also re-order the data so that later writes may be present, while earlier writes are not. This is not a theoretical edge case. This scenario is easily reproduced with real world workloads and drive power failures. For applications that require tighter guarantees about the integrity of their data, Mac OS X provides the F_FULLFSYNC fcntl. The F_FULLFSYNC fcntl asks the drive to flush all buffered data to permanent storage. Applications, such as databases, that require a strict ordering of writes should use F_FULLFSYNC to ensure that their data is written in the order they expect. Please see fcntl(2) for more detail. RETURN VALUES The fsync() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error. ERRORS The fsync() system call will fail if: [EBADF] fildes is not a valid descriptor. [EINTR] Its execution is interrupted by a signal. [EINVAL] fildes refers to a file type (e.g., a socket) that does not support this operation. [EIO] An I/O error occurred while reading from or writing to the file system. If a queued I/O operation fails, fsync() may fail with any of the errors defined for read(2) or write(2). SEE ALSO fcntl(2), read(2), sync(2), write(2), sync(8), update(8) HISTORY The fsync() function call appeared in 4.2BSD. 4.2 Berkeley Distribution June 4, 1993 4.2 Berkeley Distribution | | --- |</excerpt> </source> <source> <title>FCNTL(2)</title> <location>https://keith.github.io/xcode-man-pages/fcntl.2.html</location> <excerpt>`F_BARRIERFSYNC` ... : Does the same thing as fsync(2) then issues a barrier command to the drive (arg is ignored). The barrier applies to I/O that have been flushed with fsync(2) on the same device before. These operations are guaranteed to be persisted before any other I/O that would follow the barrier, although no assumption should be made on what has been persisted or not when this call returns. After the barrier has been issued, operations on other FDs that have been fsync&`#39`;d before can still be re-ordered by the device, but not after the barrier. This is typically useful to guarantee valid state on disk when ordering is a concern but durability is not. A barrier can be used to order two phases of operations on a set of file descriptors and ensure that no file can possibly get persisted with the effect of the second phase without the effect of the first one. To do so, execute operations of phase one, then fsync(2) each FD and issue a single barrier. Finally execute operations of phase two. This is currently implemented on HFS and APFS. It requires hardware support, which Apple SSDs are guaranteed to provide. ... `F_FULLFSYNC` ... : Does the same thing as fsync(2) then asks the drive to flush all buffered data to the permanent storage device (arg is ignored). As this drains the entire queue of the device and acts as a barrier, data that had been fsync&`#39`;d on the same device before is guaranteed to be persisted when this call returns. This is currently implemented on HFS, MS-DOS (FAT), Universal Disk Format (UDF) and APFS file systems. The operation may take quite a while to complete. Certain FireWire drives have also been known to ignore the request to flush their buffered data. ... [`EINVAL`] : Cmd is `F_DUPFD` and arg is negative or greater than the maximum allowable number (see getdtablesize(2)). The argument cmd is `F_GETLK`, `F_SETLK`, `F_SETLKW`, `F_OFD_GETLK`, `F_OFD_SETLK` or `F_OFD_SETLKW`, and the data to which arg points is not valid, or fildes refers to a file that does not support locking. ... The argument cmd is `F_PREALLOCATE` and the fst_posmode is not a valid mode, or when `F_PEOFPOSMODE` is set and fst_offset is a non-zero value, or when `F_VOLPOSMODE` is set and fst_offset is a negative or zero value. ... TRANSFEREXTENTS` and the additional file ... is negative or both file descriptors reference ... [`ENOTSUP`] : Cmd is `F_TRANSFEREXTENTS` and the given files aren&`#39`;t on an APFS volume.</excerpt> </source> <source> <title>FCNTL(2)</title> <location>https://manp.gs/mac/2/fcntl</location> <excerpt>`F_BARRIERFSYNC` ... : Does the same thing as fsync(2) then issues a barrier command to the drive (arg is ignored). The barrier applies to I/O that have been flushed with fsync(2) on the same device before. These operations are guaranteed to be persisted before any other I/O that would follow the barrier, although no assumption should be made on what has been persisted or not when this call returns. After the barrier has been issued, operations on other FDs that have been fsync&`#39`;d before can still be re-ordered by the device, but not after the barrier. This is typically useful to guarantee valid state on disk when ordering is a concern but durability is not. A barrier can be used to order two phases of operations on a set of file descriptors and ensure that no file can possibly get persisted with the effect of the second phase without the effect of the first one. To do so, execute operations of phase one, then fsync(2) each FD and issue a single barrier. Finally execute operations of phase two. This is currently implemented on HFS and APFS. It requires hardware support, which Apple SSDs are guaranteed to provide. ... `F_FULLFSYNC` ... : Does the same thing as fsync(2) then asks the drive to flush all buffered data to the permanent storage device (arg is ignored). As this drains the entire queue of the device and acts as a barrier, data that had been fsync&`#39`;d on the same device before is guaranteed to be persisted when this call returns. This is currently implemented on HFS, MS-DOS (FAT), Universal Disk Format (UDF) and APFS file systems. The operation may take quite a while to complete. Certain FireWire drives have also been known to ignore the request to flush their buffered data. ... [`EINVAL`] : Cmd is `F_DUPFD` and arg is negative or greater than the maximum allowable number (see getdtablesize(2)). The argument cmd is `F_GETLK`, `F_SETLK`, `F_SETLKW`, `F_OFD_GETLK`, `F_OFD_SETLK` or `F_OFD_SETLKW`, and the data to which arg points is not valid, or fildes refers to a file that does not support locking. ... The argument cmd is `F_PREALLOCATE` and the fst_posmode is not a valid mode, or when `F_PEOFPOSMODE` is set and fst_offset is a non-zero value, or when `F_VOLPOSMODE` is set and fst_offset is a negative or zero value. ... The argument cmd is `F_PUNCHHOLE` and either fp_offset or fp_length are negative, or when both fp_offset and fp_length are not multiples of the file system block size, or when either fp_flags or reserved is non-zero value. ... The argument cmd is `F_TRANSFEREXTENTS` and the additional file descriptor is negative or both file descriptors reference the same file. ... [`ENOTSUP`] : Cmd is `F_TRANSFEREXTENTS` and the given files aren&`#39`;t on an APFS volume.</excerpt> </source> <source> <title>os: File.Sync() returns ENOTSUP on network mounts that support fsync · Issue `#64215` · golang/go</title> <location>GitHub issue 64215 in golang/go (link omitted to avoid creating a cross-reference)</location> <excerpt># Issue: golang/go `#64215` - Repository: golang/go | The Go programming language | 133K stars | Go ## os: File.Sync() returns ENOTSUP on network mounts that support fsync - Author: [`@⁠iamcalledrob`](https://github.com/iamcalledrob) - State: closed (completed) - Locked: true - Labels: OS-Darwin, NeedsFix, FrozenDueToAge - Assignees: [`@⁠mauri870`](https://github.com/mauri870) - Milestone: Go1.23 - Created: 2023-11-16T22:22:18Z - Updated: 2025-03-07T20:09:11Z - Closed: 2024-03-07T19:21:25Z - Closed by: [`@⁠gopherbot`](https://github.com/gopherbot) ### What version of Go are you using (`go version`)? ``` $ go version go version go1.21.0 darwin/arm64 ``` ### Does this issue reproduce with the latest release? Yes ### What operating system and processor architecture are you using (`go env`)? **`go env` Output** ``` $ go env GO111MODULE=&`#39`;&`#39`; GOARCH=&`#39`;arm64&`#39`; GOBIN=&`#39`;&`#39`; GOCACHE=&`#39`;/Users/rob/Library/Caches/go-build&`#39`; GOENV=&`#39`;/Users/rob/Library/Application Support/go/env&`#39`; GOEXE=&`#39`;&`#39`; GOEXPERIMENT=&`#39`;&`#39`; GOFLAGS=&`#39`;&`#39`; GOHOSTARCH=&`#39`;arm64&`#39`; GOHOSTOS=&`#39`;darwin&`#39`; GOINSECURE=&`#39`;&`#39`; GOMODCACHE=&`#39`;/Users/rob/go/pkg/mod&`#39`; GONOPROXY=&`#39`;&`#39`; GONOSUMDB=&`#39`;&`#39`; GOOS=&`#39`;darwin&`#39`; GOPATH=&`#39`;/Users/rob/go&`#39`; GOPRIVATE=&`#39`;&`#39`; GOPROXY=&`#39`;https://proxy.golang.org,direct&`#39`; GOROOT=&`#39`;/opt/homebrew/Cellar/go/1.21.0/libexec&`#39`; GOSUMDB=&`#39`;sum.golang.org&`#39`; GOTMPDIR=&`#39`;&`#39`; GOTOOLCHAIN=&`#39`;auto&`#39`; GOTOOLDIR=&`#39`;/opt/homebrew/Cellar/go/1.21.0/libexec/pkg/tool/darwin_arm64&`#39`; GOVCS=&`#39`;&`#39`; GOVERSION=&`#39`;go1.21.0&`#39`; GCCGO=&`#39`;gccgo&`#39`; AR=&`#39`;ar&`#39`; CC=&`#39`;cc&`#39`; CXX=&`#39`;c++&`#39`; CGO_ENABLED=&`#39`;1&`#39`; GOMOD=&`#39`;/dev/null&`#39`; GOWORK=&`#39`;&`#39`; CGO_CFLAGS=&`#39`;-O2 -g&`#39`; CGO_CPPFLAGS=&`#39`;&`#39`; CGO_CXXFLAGS=&`#39`;-O2 -g&`#39`; CGO_FFLAGS=&`#39`;-O2 -g&`#39`; CGO_LDFLAGS=&`#39`;-O2 -g&`#39`; PKG_CONFIG=&`#39`;pkg-config&`#39`; GOGCCFLAGS=&`#39`;-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/9x/tzryjjm93zvcvhmn517n9t3h0000gn/T/go-build3328922198=/tmp/go-build -gno-record-gcc-switches -fno-common&`#39`; ``` ### What did you do? 1. Mount a SMB share on macOS that supports fsync (`strict sync = yes`, the default since Samba 4.7.0) 2. Open a file on that share 3. Call `file.Sync()` ### What did you expect to see? No error. The fsync instruction is passed down to the network share, which takes action (or not, depending on its configuration) ### What did you see instead? Error: `ENOTSUP` It appears that a change was implemented in go1.12 for `#26650` which switched File.Sync() to call `fcntl(fd, F_FULLFSYNC)` rather than `fsync(fd)`. This was due to fsync not being implemented as expected on darwin. On local volumes, this change appears to work correctly. However, `F_FULLFSYNC` appears to be unsupported on SMB volumes--and likely elsewhere too. This means that the change as a result of `#26650` leads to `ENOTSUP` being returned where a Sync would have succeeded before. (I&`#39`;ve verified via samba logging that calling `unix.Fsync()` on the fd results in the correct fsync instruction being sent to the server, so darwin&`#39`;s wonky fsync() behaviour seems to only apply to local volumes) I&`#39`;d bet that most Go developers are not testing file operations in SMB mounts, so are shipping software that would have worked in 1.11, but in 1.12+ will fail. I&`#39`;ve had to resort to a workaround: ```go func sync(f *os.File) error { err := f.Sync() // Ensure fsync is called if Sync is not supported. There are scenarios (SMB mounts, ...?) where fsync will succeed but Sync will fail due if (runtime.GOOS == &quot;darwin&quot; || runtime.GOOS == &quot;ios&quot;) &amp;&amp; errors.Is(err, syscall.ENOTSUP) { err = unix.Fsync(int(file.Fd())) } return err } ``` --- ### Timeline **mauri870** added label `OS-Darwin`; added label `NeedsInvestigation` · Nov 17, 2023 at 4:30am **`@⁠mauri870`** commented · Nov 17, 2023 at 5:13am …[truncated]</excerpt> </source> <source> <title>Calling fcntl(..., F_FULLFSYNC) on osxfuse volume returns &quot;Invalid argument&quot; error</title> <location>GitHub issue 79 in macfuse/macfuse (link omitted to avoid creating a cross-reference)</location> <excerpt># Calling fcntl(..., F_FULLFSYNC) on osxfuse volume returns &quot;Invalid argument&quot; error - State: closed - Author: AlexPlas - Created: 2013-04-10T16:56:56Z - Updated: 2013-04-23T18:41:55Z - Repository: macfuse/macfuse - Number: `#79` - Assignees: bfleischer --- Here is a simple test application which returns &quot;Invalid argument&quot; error for any file located on the osxfuse volume. I&`#39`;ve tested it on my own FS and on SSHFS from the site as well. ``` C `#include` &lt;fcntl.h&gt; int main(int argc, char **argv) { int fd; argc--; argv++; if(argc&lt;1) exit(0); fd = open(*argv, O_RDWR|O_CREAT); if(fd&lt;0) { perror(&quot;OPEN&quot;); exit(0); } if(write(fd,&quot;test&quot;,4)&lt;0) { perror(&quot;WRITE&quot;); exit(0); } if(fcntl(fd, F_FULLFSYNC) &lt; 0) { perror(&quot;FCNTL&quot;); exit(0); } close(fd); } ``` ## Timeline **dbgreen** commented on 2013-04-15T16:50:51Z: &gt; Basically, any program that tries to do a full-sync will have issues. We also noticed this trying to run a database in an OSXFuse fs. **bfleischer** commented on 2013-04-15T17:24:51Z: &gt; Sorry for the late reply. &gt; &gt; F_FULLFSYNC is currently not implemented. Thats why you are seeing the error. From a technical standpoint there would be no difference between calling `fsync` or `fcntl` with `F_FULLFSYNC` on a FUSE volume. For volumes that are actually backed by a physical hard drive is makes a difference though. Implementing F_FULLFSYNC should not be too difficult. &gt; &gt; On a side note, running a database on a FUSE volume might not be ideal because of the overhead and it will be very difficult to guarantee data integrity in case of a file system crash. Depending on the file system there might be several layers of caching that are not getting flushed when calling fsync or doing a fnctl with F_FULLFSYNC. **dbgreen** commented on 2013-04-15T18:19:41Z: &gt; Benjamin, &gt; The real problem for us is that we want to be able to run third party &gt; software from within the fs, and since we don&`#39`;t control the code we can&`#39`;t &gt; disable the full_sync. I personally would be fine if there were just a way &gt; to accept the call but not do the full_sync, just do a fsync instead. &gt; Right now it triggers an invalid arg error though. &gt; &gt; On Mon, Apr 15, 2013 at 12:24 PM, Benjamin Fleischer &lt; &gt; [email protected]&gt; wrote: &gt; &gt; &gt; Sorry for the late reply. &gt; &gt; &gt; &gt; From a technical standpoint there would be no difference between calling &gt; &gt; fsync or fcntl with F_FULLFSYNC on a FUSE volume. For volumes that are &gt; &gt; actually backed by a physical hard drive is makes a difference though. &gt; &gt; &gt; &gt; — &gt; &gt; Reply to this email directly or view it on GitHubhttps://github.com/osxfuse/osxfuse/issues/79#issuecomment-16399077 &gt; &gt; . **bfleischer** commented on 2013-04-15T18:41:37Z: &gt; I edited my previous reply shortly after posting it.You might not have received a notification containing the edited version. &gt; &gt; I agree that we should be doing a plain `fsync` when `fnctl` is called with `F_FULLFSYNC`. Just accepting the call is not a good solution because it might cause data loss for some users. - bfleischer was assigned **dbgreen** commented on 2013-04-16T19:12:26Z: &gt; Yeah, I agree that doing a plain fsync when fcntl is called with F_FULLSYNC is called would be the way to go. **bfleischer** commented on 2013-04-23T18:41:55Z: &gt; Commit https://github.com/osxfuse/kext/commit/e940e7d2fd34d8f11b18fc57615d1c5a18d3f485 adds support for `F_FULLSYNC`. Please let me know if you encounter any problems with the patch. - bfleischer closed</excerpt> </source> </source_evidence> Citations: - 1: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fsync.2.html - 2: https://keith.github.io/xcode-man-pages/fcntl.2.html - 3: https://manp.gs/mac/2/fcntl - 4: GitHub issue 64215 in golang/go (link omitted to avoid creating a cross-reference) - 5: GitHub issue 79 in macfuse/macfuse (link omitted to avoid creating a cross-reference) - 6: GitHub pull request 2135 in libuv/libuv (link omitted to avoid creating a cross-reference) - 7: GitHub pull request 26534 in bitcoin/bitcoin (link omitted to avoid creating a cross-reference) - 8: https://mail.openjdk.org/pipermail/nio-dev/2015-May/003167.html --- 🏁 Script executed: ```bash sed -n '1,180p' src/libs/saveDataMemory.cpp sed -n '260,355p' src/libs/saveDataMemory.cpp rg -n -C 3 'IoError|WriteSnapshot|DirectoryFlush|F_FULLFSYNC|SAVE_DATA_ERROR_INTERNAL|Sync\(' src tests ``` Repository: KytyPS5/KytyPS5 Length of output: 46798 --- </details> **Fall back to `fsync` when `F_FULLFSYNC` is unavailable.** On macOS, `fcntl(file.handle, F_FULLFSYNC)` can fail with `ENOTSUP`, `EOPNOTSUPP`, `EINVAL`, or `ENOTTY` on writable volumes that do not implement it. `WriteSnapshot` maps that failure to `SAVE_DATA_ERROR_INTERNAL` before rename, so `Set` and `Sync` fail without publishing the snapshot. Fall back to `fsync` for these unsupported-operation errors. This preserves the write-before-rename sequence, but `fsync` does not provide `F_FULLFSYNC`'s stronger power-loss guarantee. <details> <summary>🛡️ Proposed fallback</summary> ```diff int flushed; `#ifdef` __APPLE__ do { flushed = fcntl(file.handle, F_FULLFSYNC); } while (flushed < 0 && errno == EINTR); -#else - do { flushed = fsync(file.handle); } while (flushed < 0 && errno == EINTR); + if (flushed != 0 && + (errno == ENOTSUP || errno == EOPNOTSUPP || errno == EINVAL || errno == ENOTTY)) `#endif` + { + do { flushed = fsync(file.handle); } while (flushed < 0 && errno == EINTR); + } if (flushed != 0) return IoError(); ``` </details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion #ifdef __APPLE__ do { flushed = fcntl(file.handle, F_FULLFSYNC); } while (flushed < 0 && errno == EINTR); if (flushed != 0 && (errno == ENOTSUP || errno == EOPNOTSUPP || errno == EINVAL || errno == ENOTTY)) #endif { do { flushed = fsync(file.handle); } while (flushed < 0 && errno == EINTR); } ``` </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:quokka --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f7e177d79d812508bb197d3f --> <!-- This is an auto-generated comment by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-09-18 08:53 UTC · original · reviewed

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/libs/saveDataMemory.cpp (1)

522-526: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Avoid redundant synchronous snapshot writes.

Set calls WriteSnapshot for every nonempty update. WriteSnapshot rewrites the complete snapshot and performs the file and directory durability operations before returning. Repeated updates with no data, parameter, or icon changes can therefore perform unnecessary synchronous I/O.

Detect a no-op before assigning candidate.param.mtime. Return without calling WriteSnapshot only when the requested persisted fields are unchanged. Keep WriteSnapshot synchronous for changed updates so the write-through contract remains intact.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: b9a20cc6-7c5e-4734-bbe8-a0af6649aa52

📥 Commits

Reviewing files that changed from the base of the PR and between 5b7d3343cf and 18a1e79588.

📒 Files selected for processing (7)
  • .github/workflows/build.yml
  • CMakeLists.txt
  • src/libs/libSaveData.cpp
  • src/libs/saveDataMemory.cpp
  • src/libs/saveDataMemory.h
  • tests/SaveDataMemoryTests.cpp
  • tests/save_data_memory/CMakeLists.txt

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-09-18 08:53 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/696#pullrequestreview-5245989549) · **reviewed** **Actionable comments posted: 2** <details> <summary>🧹 Nitpick comments (1)</summary><blockquote> <details> <summary>src/libs/saveDataMemory.cpp (1)</summary><blockquote> `522-526`: _🚀 Performance & Scalability_ | _🔵 Trivial_ | _⚡ Quick win_ **Avoid redundant synchronous snapshot writes.** `Set` calls `WriteSnapshot` for every nonempty update. `WriteSnapshot` rewrites the complete snapshot and performs the file and directory durability operations before returning. Repeated updates with no data, parameter, or icon changes can therefore perform unnecessary synchronous I/O. Detect a no-op before assigning `candidate.param.mtime`. Return without calling `WriteSnapshot` only when the requested persisted fields are unchanged. Keep `WriteSnapshot` synchronous for changed updates so the write-through contract remains intact. <!-- cr-comment:v1:b2e703f24084255f4df392ef --> </blockquote></details> </blockquote></details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Path: .coderabbit.yaml **Review profile**: CHILL **Plan**: Advanced **Run ID**: `b9a20cc6-7c5e-4734-bbe8-a0af6649aa52` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between 5b7d3343cf1586e42068f0ce455ab0675ec43ada and 18a1e79588382c98bfaeb9935e6372242a79fff0. </details> <details> <summary>📒 Files selected for processing (7)</summary> * `.github/workflows/build.yml` * `CMakeLists.txt` * `src/libs/libSaveData.cpp` * `src/libs/saveDataMemory.cpp` * `src/libs/saveDataMemory.h` * `tests/SaveDataMemoryTests.cpp` * `tests/save_data_memory/CMakeLists.txt` </details> **Included review availability:** Your plan provides up to 10 included reviews per hour; 9 remain after this review. </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
Author
Owner

@⁠Nmzik on GitHub · 2026-09-20 14:30 UTC · original

closed in favor #659. If there is something we missed, feel free to open new PR/new bug report

**@⁠Nmzik** on GitHub · 2026-09-20 14:30 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/696#issuecomment-5750426801) closed in favor #659. If there is something we missed, feel free to open new PR/new bug report

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.