Skip to content

fix(libkernel): posix mlock and munlock lock mapped pages like the console - #24706

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
olegon85:fix/libkernel-posix-mlock-locks-mapped-pages
Nov 25, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
olegon85:fix/libkernel-posix-mlock-locks-mapped-pages

Conversation

@olegon85

Copy link
Copy Markdown
Contributor

What

mlock and munlock failed with EPERM before looking at their arguments, on a FreeBSD 11.4 jail reading agreed in #11216 and explicitly recorded as never measured on a console. A payload process on a PS5 Pro (firmware 13.60) locked a mapped page through mlock with return 0 and unlocked it the same way, so the console does not deny it; the jail model does not hold. Both now forward to sceKernelMlock/sceKernelMunlock, which already lock and unlock host pages, mapping the kernel error codes to EINVAL or ENOMEM as the posix layer expects (length 0 succeeds, unmapped ranges give ENOMEM, an overflowing range EINVAL). mlockall and munlockall keep the EPERM stub - their console behavior was not measured.

The same session measured the pthread attribute family (type table 1..4 with default 1 confirmed against our implementation; Getkind, prioceiling and rwlock pshared answers diverge from our wrappers) - those findings feed follow-up work and are quoted in full in the first comment, together with the scePthreadMutexattrInit(NULL) console fault that ended an earlier run.

Probe sources and raw session output are in the first comment. Measurement context: PS5 Pro, kernel_get_fw_version = 0x13600007, payload process over elfldr (port 9021), sessions 2026-11-20T23:35Z and 23:39Z UTC; a title process was not measured.

Tested

  • Console: probes tw5/tw5b; mlock and munlock on a mapped page answered rc 0 both times.
  • Server (Linux): guest_mlock_tests passed with the change on 01ac7c81be, including the new success pins on a fresh mapping and the ENOMEM/EINVAL failure pins; the pre-existing sceKernelMlock family pins are untouched.
  • python3 tools/check_conventions.py --base origin/main: passed. git diff --check: clean. python3 tools/pr_overlap.py --branch fix/libkernel-posix-mlock-locks-mapped-pages: failed closed on 23 base-conflicting PRs sharing these files; each patch was grepped and only feat(libs): mirror libkernel exports through libkernel_sys #18190 touches the two functions - a mechanical _nid_no_patch rename keeping the stub body, so whichever merges later adapts it to the other. No open PR changes this behavior.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

@olegon85

Copy link
Copy Markdown
Contributor Author

Console evidence

Measurement context: PS5 Pro, kernel_get_fw_version = 0x13600007 (firmware 13.60), payload process loaded over elfldr (port 9021); a title process was not measured. Sessions 2026-11-20T23:35:42Z (tw5) and 23:39:19Z (tw5b). Every call is preceded by a flushed STEP line.

tw5b rows for this PR (posix lock family; rc/errno after each call):

T5B|mlock|rc=0|errno=0
T5B|munlock|rc=0|errno=0
T5B|clock-set-now|rc=0|errno=0|drift=0
T5B|clock-set-null|rc=-1|errno=22

The same session measured the pthread attribute family (type 1..4 with default 1, protocol 0..2, Getkind always 0x8001c500, prioceiling set refused / get 767, rwlock pshared only 0); full raw output:

T5B|FW|0x13600007
T5B|LK|880f7ae20|ok
T5B|mlock|rc=0|errno=0
T5B|munlock|rc=0|errno=0
T5B|clock-set-now|rc=0|errno=0|drift=0
T5B|clock-set-null|rc=-1|errno=22
T5B|ma-init|rc=0
T5B|type-0|set=-2147352554|get=0|val=1
T5B|type-1|set=0|get=0|val=1
T5B|type-2|set=0|get=0|val=2
T5B|type-3|set=0|get=0|val=3
T5B|type-4|set=0|get=0|val=4
T5B|type-5|set=-2147352554|get=0|val=4
T5B|type-999|set=-2147352554|get=0|val=4
T5B|proto-0|set=0|get=0|val=0
T5B|proto-1|set=0|get=0|val=1
T5B|proto-2|set=0|get=0|val=2
T5B|proto-999|set=-2147352554|get=0|val=2
T5B|kind--1|set=0|getA=0x8001c500|getB=0x8001c500|valB=-777
T5B|kind-0|set=0|getA=0x8001c500|getB=0x8001c500|valB=-777
T5B|kind-1|set=0|getA=0x8001c500|getB=0x8001c500|valB=-777
T5B|kind-2|set=0|getA=0x8001c500|getB=0x8001c500|valB=-777
T5B|kind-3|set=0|getA=0x8001c500|getB=0x8001c500|valB=-777
T5B|kind-999|set=0|getA=0x8001c500|getB=0x8001c500|valB=-777
T5B|prio-0|set=-2147352554|get=0|val=767
T5B|prio-100|set=-2147352554|get=0|val=767
T5B|prio--1|set=-2147352554|get=0|val=767
T5B|rw-init|rc=0
T5B|rw-psh-0|set=0|get=0|val=0
T5B|rw-psh-1|set=-2147352554|get=0|val=0
T5B|rw-psh-2|set=-2147352554|get=0|val=0
T5B|rw-psh--1|set=-2147352554|get=0|val=0
T5B|null-settype|rc=0x80020016|errno=0
T5B|ma-destroy|rc=0
T5B|DONE

An earlier run (tw5) reached STEP|null-init and the payload died there - scePthreadMutexattrInit(NULL) faults on the console; its tail:

TW5|STEP|null-settype
TW5|null-settype|rc=-2147352554|errno=0
TW5|STEP|null-init

Probe sources:

tw5b/main.c
#include <ps5/kernel.h>
#include <dlfcn.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

typedef int (*AttrFn)(void*);
typedef int (*SetTypeFn)(void*, int);
typedef int (*GetTypeFn)(void*, int*);
typedef int (*GetkindAFn)(void*);
typedef int (*GetkindBFn)(void*, int*);
typedef int (*MLockFn)(const void*, uint64_t);
typedef int (*ClockSetFn)(int, const struct timespec*);

static void step(const char* what) {
    printf("T5B|STEP|%s\n", what);
    fflush(stdout);
}

int main(void) {
    printf("T5B|FW|0x%x\n", kernel_get_fw_version());
    fflush(stdout);

    void* lk = dlopen("libkernel.sprx", RTLD_LAZY);
    printf("T5B|LK|%p|%s\n", lk, lk ? "ok" : dlerror());
    fflush(stdout);
    if (!lk) return 1;

    MLockFn MLOCK = (MLockFn)dlsym(lk, "mlock");
    MLockFn MUNLOCK = (MLockFn)dlsym(lk, "munlock");
    ClockSetFn CLOCKSET = (ClockSetFn)dlsym(lk, "clock_settime");
    AttrFn MA_INIT = (AttrFn)dlsym(lk, "scePthreadMutexattrInit");
    AttrFn MA_DESTROY = (AttrFn)dlsym(lk, "scePthreadMutexattrDestroy");
    SetTypeFn MA_SETTYPE = (SetTypeFn)dlsym(lk, "scePthreadMutexattrSettype");
    GetTypeFn MA_GETTYPE = (GetTypeFn)dlsym(lk, "scePthreadMutexattrGettype");
    SetTypeFn MA_SETPROTO = (SetTypeFn)dlsym(lk, "scePthreadMutexattrSetprotocol");
    GetTypeFn MA_GETPROTO = (GetTypeFn)dlsym(lk, "scePthreadMutexattrGetprotocol");
    SetTypeFn MA_SETKIND = (SetTypeFn)dlsym(lk, "scePthreadMutexattrSetkind");
    GetkindAFn GETKIND_A = (GetkindAFn)dlsym(lk, "scePthreadMutexattrGetkind");
    GetkindBFn GETKIND_B = (GetkindBFn)dlsym(lk, "scePthreadMutexattrGetkind");
    SetTypeFn MA_SETPRIO = (SetTypeFn)dlsym(lk, "scePthreadMutexattrSetprioceiling");
    GetTypeFn MA_GETPRIO = (GetTypeFn)dlsym(lk, "scePthreadMutexattrGetprioceiling");
    AttrFn RW_INIT = (AttrFn)dlsym(lk, "scePthreadRwlockattrInit");
    SetTypeFn RW_SETPSH = (SetTypeFn)dlsym(lk, "scePthreadRwlockattrSetpshared");
    GetTypeFn RW_GETPSH = (GetTypeFn)dlsym(lk, "scePthreadRwlockattrGetpshared");

    static uint8_t page[4096] __attribute__((aligned(4096)));
    if (MLOCK) {
        step("mlock-valid");
        errno = 0;
        int rc = MLOCK(page, sizeof(page));
        printf("T5B|mlock|rc=%d|errno=%d\n", rc, errno);
        fflush(stdout);
        if (MUNLOCK) {
            step("munlock");
            errno = 0;
            rc = MUNLOCK(page, sizeof(page));
            printf("T5B|munlock|rc=%d|errno=%d\n", rc, errno);
            fflush(stdout);
        }
    }
    if (CLOCKSET) {
        struct timespec now, after;
        clock_gettime(0, &now);
        step("clock-set-now");
        errno = 0;
        int rc = CLOCKSET(0, &now);
        clock_gettime(0, &after);
        printf("T5B|clock-set-now|rc=%d|errno=%d|drift=%lld\n", rc, errno, (long long)(after.tv_sec - now.tv_sec));
        fflush(stdout);
        step("clock-set-null");
        errno = 0;
        rc = CLOCKSET(0, 0);
        printf("T5B|clock-set-null|rc=%d|errno=%d\n", rc, errno);
        fflush(stdout);
    }

    static uint64_t mattr[8];
    if (MA_INIT) {
        step("ma-init");
        memset(mattr, 0xAA, sizeof(mattr));
        errno = 0;
        printf("T5B|ma-init|rc=%d\n", MA_INIT(mattr));
        fflush(stdout);
    }
    if (MA_SETTYPE && MA_GETTYPE) {
        static const int types[] = {0, 1, 2, 3, 4, 5, 999};
        for (unsigned i = 0; i < sizeof(types) / sizeof(types[0]); ++i) {
            char id[32];
            snprintf(id, sizeof(id), "type-%d", types[i]);
            step(id);
            errno = 0;
            int rc = MA_SETTYPE(mattr, types[i]);
            int val = -777;
            int grc = MA_GETTYPE(mattr, &val);
            printf("T5B|%s|set=%d|get=%d|val=%d\n", id, rc, grc, val);
            fflush(stdout);
        }
    }
    if (MA_SETPROTO && MA_GETPROTO) {
        static const int protos[] = {0, 1, 2, 999};
        for (unsigned i = 0; i < sizeof(protos) / sizeof(protos[0]); ++i) {
            char id[32];
            snprintf(id, sizeof(id), "proto-%d", protos[i]);
            step(id);
            errno = 0;
            int rc = MA_SETPROTO(mattr, protos[i]);
            int val = -777;
            int grc = MA_GETPROTO(mattr, &val);
            printf("T5B|%s|set=%d|get=%d|val=%d\n", id, rc, grc, val);
            fflush(stdout);
        }
    }
    if (MA_SETKIND) {
        static const int kinds[] = {-1, 0, 1, 2, 3, 999};
        for (unsigned i = 0; i < sizeof(kinds) / sizeof(kinds[0]); ++i) {
            char id[40];
            snprintf(id, sizeof(id), "kind-%d", kinds[i]);
            step(id);
            errno = 0;
            int rc = MA_SETKIND(mattr, kinds[i]);
            int val = -777;
            int ga = GETKIND_A ? GETKIND_A(mattr) : -1;
            int gb = GETKIND_B ? GETKIND_B(mattr, &val) : -1;
            printf("T5B|%s|set=%d|getA=0x%x|getB=0x%x|valB=%d\n", id, rc, (unsigned)ga, (unsigned)gb, val);
            fflush(stdout);
        }
    }
    if (MA_SETPRIO && MA_GETPRIO) {
        static const int prios[] = {0, 100, -1};
        for (unsigned i = 0; i < sizeof(prios) / sizeof(prios[0]); ++i) {
            char id[32];
            snprintf(id, sizeof(id), "prio-%d", prios[i]);
            step(id);
            errno = 0;
            int rc = MA_SETPRIO(mattr, prios[i]);
            int val = -777;
            int grc = MA_GETPRIO(mattr, &val);
            printf("T5B|%s|set=%d|get=%d|val=%d\n", id, rc, grc, val);
            fflush(stdout);
        }
    }

    static uint64_t rwattr[8];
    if (RW_INIT && RW_GETPSH) {
        step("rw-init");
        memset(rwattr, 0xAA, sizeof(rwattr));
        errno = 0;
        int rc = RW_INIT(rwattr);
        printf("T5B|rw-init|rc=%d\n", rc);
        fflush(stdout);
    }
    if (RW_SETPSH && RW_GETPSH) {
        static const int psh[] = {0, 1, 2, -1};
        for (unsigned i = 0; i < sizeof(psh) / sizeof(psh[0]); ++i) {
            char id[32];
            snprintf(id, sizeof(id), "rw-psh-%d", psh[i]);
            step(id);
            errno = 0;
            int rc = RW_SETPSH(rwattr, psh[i]);
            int val = -777;
            int grc = RW_GETPSH(rwattr, &val);
            printf("T5B|%s|set=%d|get=%d|val=%d\n", id, rc, grc, val);
            fflush(stdout);
        }
    }

    if (MA_SETTYPE) {
        step("null-settype");
        errno = 0;
        printf("T5B|null-settype|rc=0x%x|errno=%d\n", (unsigned)MA_SETTYPE(0, 0), errno);
        fflush(stdout);
    }
    if (MA_DESTROY) {
        step("ma-destroy");
        errno = 0;
        printf("T5B|ma-destroy|rc=%d\n", MA_DESTROY(mattr));
        fflush(stdout);
    }

    printf("T5B|DONE\n");
    fflush(stdout);
    return 0;
}

@olegon85
olegon85 force-pushed the fix/libkernel-posix-mlock-locks-mapped-pages branch from 8caf46d to 36096e4 Compare November 21, 2026 00:17

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — looks good

Nothing blocks this change; the inspected forwarding and error mapping are consistent with the existing kernel locking APIs.

What I ran

Reviewed head 36096e40a7515c98d039c5a3f5120c98b491adcf. No commands or tests were run. Read core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp, core/libs/prx/libkernel/DirectMemory/Export.cpp, core/libs/prx/libkernel/include/Api.hpp, core/libs/tests/GuestMlock.cpp, and the prepared review/description.md, review/commits.md, review/manifest.json, and review/diff.patch. core/libs/tests/GuestMlock.cpp and debt documentation are listed as excluded by review rule; I read the test file only for context, not as a changed file.

Results

Check Result Note
Changed code review passed Single changed file inspected
Tests not run Author reports server and console checks
Error mapping passed Kernel invalid maps to EINVAL; other returned errors map to ENOMEM

Findings

Blocking

None.

Non-blocking

None.

Not verified

No checks were run in this review. The author's console measurements and server test results were not independently verified. core/libs/tests/GuestMlock.cpp and the change debt note were excluded from this review by rule, although the test source was read for context. No other files were marked as reviewed in the prepared manifest.

To get this to a good state

Nothing is required.

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 36096e40a7:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_mlock_tests built cleanly.
  • CTest (guest_mlock):
    1/1 Test #5933: guest_mlock ......................   Passed    0.01 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #5933: guest_mlock ......................Subprocess aborted***Exception:   0.91 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified mlock_nid_postfix and munlock_nid_postfix correctly forward to sceKernelMlock_nid_postfix and sceKernelMunlock_nid_postfix with const_cast<void*>(address) and length
    • Verified ForwardPosixLock correctly checks result == 0 returning 0, and maps KernelInvalid (0x80020016 / SCE_KERNEL_ERROR_EINVAL) to GuestInvalid (EINVAL = 22) and all other errors to GuestNoMemory (ENOMEM = 12) per POSIX standards
    • Verified set error errno propagation matches FreeBSD/guest errno calling *__error_nid_postfix() = error
    • Verified docs/dev/debt/changes/fix-libkernel-posix-mlock-locks-mapped-pages.md accurately documents the change and debt fragment without rule violations
    • Verified core/libs/tests/GuestMlock.cpp exercises mlock and munlock on mapped memory, 0-length ranges, unmapped memory (ENOMEM), and overflow/invalid addresses (EINVAL)

Looks Good To Me

@olegon85

Copy link
Copy Markdown
Contributor Author

Follow-up measurement for this PR's debt entry, same console (PS5 Pro, kernel_get_fw_version = 0x13600007, payload process over elfldr): mlockall and munlockall are no longer unmeasured. Sessions 2026-11-21T00:32Z and 00:33Z UTC:

T5C|mlockall-0|rc=-1|errno=22
T5C|munlockall|rc=0|errno=0
T5D|mlockall-1|rc=0|errno=0
T5D|mlockall-2|rc=0|errno=0
T5D|mlockall-3|rc=0|errno=0
T5D|mlockall--1|rc=-1|errno=22
T5D|mlockall-4|rc=-1|errno=22
T5D|munlockall|rc=0|errno=0

The console validates the flags (MLOCK_ALL bit combinations 1/2/3 succeed, everything else is -1 with EINVAL) and munlockall succeeds; it does not deny either call. This PR leaves both as the EPERM stub, which stays correct until that follow-up - I am queuing a separate PR for them after this one merges, since both would edit the same [mlock, munlock, mlockall, munlockall] debt entry and fragments on one entry collide. No action needed here.

@relativespace2K

Copy link
Copy Markdown
Contributor

@olegon85 Windows check on head 36096e40a75, since the reported runs are console + Linux.

  • Machine: Windows 11 IoT Enterprise LTSC 10.0.26100, Ryzen 5 5600, WinLibs GCC 15.2.0 (UCRT, POSIX threads), Release with -DBUILD_TESTING=ON.
  • guest_mlock_tests built cleanly; ctest -R "^guest_mlock$" passed in 0.07 s.
  • The new success pins on a fresh flexible mapping, the ENOMEM/EINVAL failure pins and the unchanged sceKernelMlock family checks all pass on Windows.
  • Negative control: reverted only core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp to its old body, rebuilt, and the test aborts (SIGABRT, ctest exit 0xc0000409); restoring the change makes it pass again. Working tree clean.

I did not run the rest of the libkernel suite.

AI-assisted: yes

@olegon85

Copy link
Copy Markdown
Contributor Author

Thank you - Windows verification with a negative control on top of console + Linux is exactly the coverage these posix-forwarding changes needed. Recorded; nothing to change on our side.

This was referenced Nov 21, 2026
@kiwe147

kiwe147 commented Nov 21, 2026

Copy link
Copy Markdown

Tested head 36096e40a7, applied with git apply on main fd4aeed483 together with the other 26 PRs of one batch (#24498, #24665, #17297, #21499, #21726, #22534, #12900, #17843, #22051, #22075, #23087, #23206, #23222, #23227, #13147, #17482, #21935, #17477, #18272, #22858, #22929, #23028, #23295, #23916, #24179, #12619). All applied without conflicts and the whole tree built.

Setup: Windows 11 Pro 10.0.26200, Ryzen 7 9800X3D, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON. GPUs: NVIDIA GeForce RTX 3080 (driver 621.24) and the AMD Radeon iGPU of the CPU (gfx1036, driver 32.0.21036.18). No validation layer. iGPU run: ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 ANYPS5_GPU="AMD Radeon", agc_/video tests only.

tests RTX 3080 iGPU
guest_mlock (1 test, matched by name to the test file this PR changes) all pass outside the iGPU subset

Whole batch: the full ctest -j 12 (6525 tests) on the RTX 3080 has 8 failing tests; the 4 that also fail on main fd4aeed483 are agc_driver_stencil_plane_memory, agc_driver_msaa_dcc_unwatch, agc_storage_write_back_host_retile, and pr_overlap_names, which needs a newer Python than my 3.10. Intermittent in this run (pass when rerun alone, or known flaky): agc_driver_store_over_untracked. Traced to other PRs of the batch, each by reverting it and testing again: #18272 (guest_audio_out), #12900 (guest_user_service_initial_user_bounds); none is in this PR's area. Failing tests I could not trace to a single PR (reverting the likely candidates did not clear them): guest_content_search. The 2125 agc_/video tests on the iGPU have 2 failing: agc_driver_stencil_plane_memory, agc_driver_store_over_untracked (agc_driver_stencil_plane_memory also fails on main).

This is one combined tree, not a run of this PR alone.

AI-assisted: yes (Claude Code)

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 18190 core/libs/prx/libkernel/DirectMemory/PosixMemory.cpp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants