summaryrefslogtreecommitdiff
path: root/Kernel/Syscalls/purge.cpp
blob: 72057dbafe89f43f03e9b1ef665f92f6f13cf3af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/NonnullRefPtrVector.h>
#include <Kernel/Memory/AnonymousVMObject.h>
#include <Kernel/Memory/InodeVMObject.h>
#include <Kernel/Memory/MemoryManager.h>
#include <Kernel/Process.h>

namespace Kernel {

KResultOr<FlatPtr> Process::sys$purge(int mode)
{
    VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this)
    REQUIRE_NO_PROMISES;
    if (!is_superuser())
        return EPERM;
    size_t purged_page_count = 0;
    if (mode & PURGE_ALL_VOLATILE) {
        NonnullRefPtrVector<Memory::AnonymousVMObject> vmobjects;
        {
            KResult result(KSuccess);
            MM.for_each_vmobject([&](auto& vmobject) {
                if (vmobject.is_anonymous()) {
                    // In the event that the append fails, only attempt to continue
                    // the purge if we have already appended something successfully.
                    if (!vmobjects.try_append(static_cast<Memory::AnonymousVMObject&>(vmobject)) && vmobjects.is_empty()) {
                        result = ENOMEM;
                        return IterationDecision::Break;
                    }
                }
                return IterationDecision::Continue;
            });

            if (result.is_error())
                return result.error();
        }
        for (auto& vmobject : vmobjects) {
            purged_page_count += vmobject.purge();
        }
    }
    if (mode & PURGE_ALL_CLEAN_INODE) {
        NonnullRefPtrVector<Memory::InodeVMObject> vmobjects;
        {
            KResult result(KSuccess);
            MM.for_each_vmobject([&](auto& vmobject) {
                if (vmobject.is_inode()) {
                    // In the event that the append fails, only attempt to continue
                    // the purge if we have already appended something successfully.
                    if (!vmobjects.try_append(static_cast<Memory::InodeVMObject&>(vmobject)) && vmobjects.is_empty()) {
                        result = ENOMEM;
                        return IterationDecision::Break;
                    }
                }
                return IterationDecision::Continue;
            });

            if (result.is_error())
                return result.error();
        }
        for (auto& vmobject : vmobjects) {
            purged_page_count += vmobject.release_all_clean_pages();
        }
    }
    return purged_page_count;
}

}