Branch data Line data Source code
1 : : // Copyright 2026 HPActor Contributors
2 : : //
3 : : // Licensed under the Apache License, Version 2.0 (the "License");
4 : : // you may not use this file except in compliance with the License.
5 : : // You may obtain a copy of the License at
6 : : //
7 : : // http://www.apache.org/licenses/LICENSE-2.0
8 : : //
9 : : // Unless required by applicable law or agreed to in writing, software
10 : : // distributed under the License is distributed on an "AS IS" BASIS,
11 : : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : : // See the License for the specific language governing permissions and
13 : : // limitations under the License.
14 : :
15 : : #include <hpactor/mem/zram.hpp>
16 : :
17 : : #include <sys/mman.h>
18 : :
19 : : #if HPACTOR_PLATFORM_LINUX
20 : : # include <fstream>
21 : : # include <string>
22 : : #endif
23 : :
24 : : namespace hpactor::mem {
25 : :
26 : 1 : bool ZramManager::is_available() noexcept {
27 : : #if HPACTOR_PLATFORM_LINUX
28 : : // Check if zram0 device exists and has a compression algorithm configured
29 : 1 : std::ifstream f("/sys/block/zram0/comp_algorithm");
30 : 1 : if (!f.is_open()) return false;
31 : 0 : std::string line;
32 : 0 : std::getline(f, line);
33 : 0 : return !line.empty() && line.find("none") == std::string::npos;
34 : : #else
35 : : return false;
36 : : #endif
37 : 1 : }
38 : :
39 : 1 : void ZramManager::reclaim_pages(void* ptr, size_t size) noexcept {
40 : 1 : if (!ptr || size == 0) return;
41 : : #if HPACTOR_PLATFORM_LINUX
42 : 1 : madvise(ptr, size, MADV_PAGEOUT);
43 : : #elif HPACTOR_PLATFORM_MACOS
44 : : // macOS: MADV_FREE is the closest equivalent — marks pages as
45 : : // reusable, kernel will zero-fill on next access.
46 : : madvise(ptr, size, MADV_FREE);
47 : : #endif
48 : : }
49 : :
50 : 1 : void ZramManager::mark_cold(void* ptr, size_t size) noexcept {
51 : 1 : if (!ptr || size == 0) return;
52 : : #if HPACTOR_PLATFORM_LINUX
53 : 1 : madvise(ptr, size, MADV_COLD);
54 : : #elif HPACTOR_PLATFORM_MACOS
55 : : // macOS 10.15+ supports MADV_COLD
56 : : madvise(ptr, size, MADV_FREE);
57 : : #endif
58 : : }
59 : :
60 : 1 : void ZramManager::mark_will_need(void* ptr, size_t size) noexcept {
61 : 1 : if (!ptr || size == 0) return;
62 : 1 : madvise(ptr, size, MADV_WILLNEED);
63 : : }
64 : :
65 : : } // namespace hpactor::mem
|