This repository was archived by the owner on Oct 5, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathdynv.cpp
More file actions
1423 lines (1225 loc) · 42.9 KB
/
Copy pathdynv.cpp
File metadata and controls
1423 lines (1225 loc) · 42.9 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <android/log.h>
#include <sys/stat.h>
#include <unistd.h>
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iostream>
#include <mutex>
#include <numeric>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_set>
#include <utility>
#include <vector>
#define SWAP_PROC_FILE "/proc/swaps"
#define ZRAM_DIR "/dev/block"
#define SWAP_DIR "/data/adb"
using namespace std;
using namespace chrono;
namespace fs = filesystem;
extern void save_pid(const string &filename, pid_t pid);
extern void dyn_swap_service();
extern void fmiop();
atomic<bool> running(true);
atomic<bool> is_swapoff_session{false};
atomic<bool> sleeper_alive(false);
vector<string> swapoff_tracker, active_swaps;
mutex safe_thread_mutex;
pair<vector<string>, vector<string>> available_swaps;
const string fmiop_dir = "/sdcard/Android/fmiop";
const string NVBASE = "/data/adb";
const string LOG_FOLDER = NVBASE + "/fmiop";
const string PIDS_DB = LOG_FOLDER + "/fmiop" + ".pids";
const string SWAP_FILE_PREFIX = "fmiop_swap.";
const string DEFAULT_CONFIG = "/data/adb/fmiop/config.yaml";
enum class LogType { ALWAYS, QUIET, ONCE };
enum class LogPriority {
DEBUG = ANDROID_LOG_DEBUG,
INFO = ANDROID_LOG_INFO,
WARNING = ANDROID_LOG_WARN,
ERROR = ANDROID_LOG_ERROR
};
#define LOG_TAG "fmiop"
/**
* Converts any type to string using stringstream.
*/
template <typename T>
string to_string_generic(const T &val) {
ostringstream oss;
oss << boolalpha << val; // handle bool as "true"/"false"
return oss.str();
}
class LogManager {
public:
/**
* @brief Logs a message with the specified type, priority, and format.
*
* This templated function logs messages using Android's logging system. It
* supports different log types, including normal, quiet (no logging), and
* once (logs only once per key). If the log type is QUIET, the function
* returns immediately without logging. If the log type is ONCE and the
* message with the given key has already been logged, it will not log again.
* Otherwise, it logs the formatted message with the provided arguments.
*
* @tparam Args Variadic template parameters for formatting the log message.
* @param type The type of log (e.g., normal, quiet, once).
* @param level The priority level of the log message.
* @param key A unique key to identify the log message (used for ONCE type).
* @param format The format string for the log message (printf-style).
* @param args Arguments to be formatted into the log message.
*/
template <typename... Args>
void log(LogType type, LogPriority level, const string &key,
const char *format, Args... args) {
if (type == LogType::QUIET) return;
if (type == LogType::ONCE && once_logged.find(key) != once_logged.end()) {
return;
}
__android_log_print(static_cast<int>(level), LOG_TAG, format, args...);
if (type == LogType::ONCE) {
once_logged.insert(key);
}
}
// Overloaded function with default parameters
template <typename... Args>
void log(const string &key, const char *format, Args... args) {
log(key, LogType::ALWAYS, LogPriority::INFO, format, args...);
}
void reset(const string &key) { once_logged.erase(key); }
void reset_all() { once_logged.clear(); }
private:
unordered_set<string> once_logged;
};
static LogManager log_manager;
#define ALOGD(format, ...) \
log_manager.log(LogType::ALWAYS, LogPriority::DEBUG, "", format, \
##__VA_ARGS__)
#define ALOGI(format, ...) \
log_manager.log(LogType::ALWAYS, LogPriority::INFO, "", format, ##__VA_ARGS__)
#define ALOGW(format, ...) \
log_manager.log(LogType::ALWAYS, LogPriority::WARNING, "", format, \
##__VA_ARGS__)
#define ALOGE(format, ...) \
log_manager.log(LogType::ALWAYS, LogPriority::ERROR, "", format, \
##__VA_ARGS__)
#define ALOGD_ONCE(key, format, ...) \
log_manager.log(LogType::ONCE, LogPriority::DEBUG, key, format, ##__VA_ARGS__)
#define ALOGI_ONCE(key, format, ...) \
log_manager.log(LogType::ONCE, LogPriority::INFO, key, format, ##__VA_ARGS__)
#define ALOGW_ONCE(key, format, ...) \
log_manager.log(LogType::ONCE, LogPriority::WARNING, key, format, \
##__VA_ARGS__)
#define ALOGE_ONCE(key, format, ...) \
log_manager.log(LogType::ONCE, LogPriority::ERROR, key, format, ##__VA_ARGS__)
#define ALOG_RESET(key) log_manager.reset(key)
/**
* Reads a value from a YAML config file with a default fallback.
*/
template <typename T>
T read_config(const string &key_path, T default_value) {
try {
YAML::Node node = YAML::LoadFile(DEFAULT_CONFIG);
size_t pos = 0, found;
string clean_key_path =
(key_path[0] == '.') ? key_path.substr(1) : key_path;
while ((found = clean_key_path.find('.', pos)) != string::npos) {
string key = clean_key_path.substr(pos, found - pos);
node = node[key];
if (!node) {
ALOGW("Config key not found: %s. Using default: %s", key_path.c_str(),
to_string_generic(default_value).c_str());
return default_value;
}
pos = found + 1;
}
string finalKey = clean_key_path.substr(pos);
node = node[finalKey];
if (!node) {
ALOGW("Config key not found: %s. Using default: %s", key_path.c_str(),
to_string_generic(default_value).c_str());
return default_value;
}
T value = node.as<T>();
ALOGI("Config [%s] = %s", key_path.c_str(),
to_string_generic(value).c_str());
return value;
} catch (const exception &e) {
ALOGE("Error reading config: %s", e.what());
return default_value;
}
}
vector<pair<int, int>> parse_pressure_pairs(const YAML::Node &node) {
vector<pair<int, int>> result;
if (!node || !node.IsSequence()) return result;
for (const auto &pairNode : node) {
if (pairNode.IsSequence() && pairNode.size() == 2) {
int threshold = pairNode[0].as<int>();
int value = pairNode[1].as<int>();
result.emplace_back(threshold, value);
}
}
return result;
}
/**
* Reads the current swappiness value from the system.
*/
int read_swappiness() {
ifstream file("/proc/sys/vm/swappiness");
int swappiness;
if (file >> swappiness) {
return swappiness;
}
return -1;
}
/**
* Writes a new swappiness value to the system.
*/
void write_swappiness(int value) {
ofstream file("/proc/sys/vm/swappiness");
if (!file) {
ALOGE(
"Error: Unable to write to /proc/sys/vm/swappiness. Check "
"permission.");
return;
}
file << value;
}
/**
* Reads a specific pressure metric from /proc/pressure/<resource>.
*/
double read_pressure(const string &resource, const string &level,
const string &key) {
string file_path = "/proc/pressure/" + resource;
ifstream file(file_path);
if (!file.is_open()) {
ALOGE("Error: Unable to open %s", file_path.c_str());
return nan("");
}
string line;
while (getline(file, line)) {
istringstream iss(line);
string word;
iss >> word;
if (word == level) {
string metric;
while (iss >> metric) {
size_t pos = metric.find('=');
if (pos != string::npos) {
string metric_key = metric.substr(0, pos);
string metric_value = metric.substr(pos + 1);
if (metric_key == key) {
return stod(metric_value);
}
}
}
}
}
ALOGE("Key: %s not found.", key.c_str());
return nan("");
}
/**
* Handles termination signals.
*/
void signal_handler(int signal) {
ALOGI("Received signal %d, exiting...", signal);
running = false;
_Exit(signal);
}
/**
* Saves a PID to a file (PID_DB) with a given name.
* If the name already exists, it is replaced.
*
* @param pid_name The name associated with the PID.
* @param pid_value The PID to be saved.
*/
void save_pid(const string &pid_name, int pid_value) {
vector<string> lines;
string line;
bool found = false;
// Open the PID_DB file for reading.
ifstream infile(PIDS_DB);
if (infile) {
while (getline(infile, line)) {
// Check if the line starts with "pid_name="
if (line.compare(0, pid_name.size() + 1, pid_name + "=") != 0) {
lines.push_back(line);
} else {
found = true;
}
}
infile.close();
}
// Append the new PID entry.
lines.push_back(pid_name + "=" + to_string(pid_value));
// Open PID_DB for writing (this overwrites the file).
ofstream outfile(PIDS_DB);
if (!outfile) {
ALOGE("Error: Unable to open %s for writing.", PIDS_DB.c_str());
return;
}
for (const auto &l : lines) {
outfile << l << "\n";
}
outfile.close();
ALOGD("Saved PID %d for %s %s", pid_value, pid_name.c_str(),
found ? "(Updated)" : "(New)");
}
// Function to get the smallest priority of active ZRAM swaps
int get_smlst_priority() {
ifstream file(SWAP_PROC_FILE);
if (!file) {
ALOGE("Error: Unable to open %s", SWAP_PROC_FILE);
return -1;
}
string line;
vector<int> priorities;
// Skip the first line (header)
getline(file, line);
while (getline(file, line)) {
istringstream iss(line);
string device;
int priority;
string temp;
// Extract values: device name is first, priority is the 5th column
for (int i = 0; i < 5; ++i) {
if (!(iss >> temp)) {
break;
}
if (i == 0) {
device = temp;
} else if (i == 4) {
priority = stoi(temp);
}
}
priorities.push_back(priority);
}
if (priorities.empty()) {
ALOGW("No active swaps found.");
return 32767;
}
return *min_element(priorities.begin(), priorities.end());
}
// Function to check if a ZRAM device is active
bool is_active(const string &device) {
ifstream file(SWAP_PROC_FILE);
if (!file) {
ALOGE("Error: Unable to open %s", SWAP_PROC_FILE);
return false;
}
string line;
while (getline(file, line)) {
if (line.find(device) != string::npos) {
return true;
}
}
return false;
}
pair<vector<string>, vector<string>> get_available_swap() {
vector<string> swap_files, zram_devices;
vector<string> dir_list = {SWAP_DIR, ZRAM_DIR};
for (const auto &dir : dir_list) {
if (!fs::exists(dir)) {
ALOGW("Directory does not exist: %s", dir.c_str());
continue;
}
if (!fs::is_directory(dir)) {
ALOGW("Path is not a directory: %s", dir.c_str());
continue;
}
for (const auto &entry : fs::directory_iterator(dir)) {
bool swap_found = false;
if (entry.is_directory()) continue;
string pathStr = entry.path().string();
if (is_active(pathStr)) {
ALOGI("ACTIVE SWAP detected: %s", pathStr.c_str());
} else {
if (pathStr.find("swap") != string::npos) {
swap_files.push_back(pathStr);
swap_found = true;
} else if (pathStr.find("zram") != string::npos) {
zram_devices.push_back(pathStr);
swap_found = true;
}
if (swap_found) {
ALOGD("INACTIVE SWAP found: %s", pathStr.c_str());
}
}
}
}
// ✅ **Sorting logic**
auto extract_number = [](const string &s) -> int {
size_t pos = s.find_last_not_of("0123456789");
return (pos != string::npos) ? stoi(s.substr(pos + 1)) : -1;
};
sort(swap_files.begin(), swap_files.end(),
[&](const string &a, const string &b) {
return extract_number(a) > extract_number(b);
});
sort(zram_devices.begin(), zram_devices.end(),
[&](const string &a, const string &b) {
return extract_number(a) > extract_number(b);
});
// ✅ **Combine them: swap first, then zram**
vector<string> available_swaps;
available_swaps.insert(available_swaps.end(), swap_files.begin(),
swap_files.end());
available_swaps.insert(available_swaps.end(), zram_devices.begin(),
zram_devices.end());
for (const auto &swap : available_swaps) {
ALOGD("Available SWAP: %s", swap.c_str());
}
return {zram_devices, swap_files};
}
vector<string> get_active_swap() {
string line;
vector<pair<string, long>> swaps; // Store (device, usage)
ifstream file(SWAP_PROC_FILE);
if (!file) {
ALOGE("Error: Unable to open %s", SWAP_PROC_FILE);
return {}; // Return empty if file can't be opened
}
// Skip header
getline(file, line);
while (getline(file, line)) {
istringstream iss(line);
string device;
long size, used; // We only care about "used"
iss >> device >> size >> used;
if (!device.empty()) {
swaps.emplace_back(device, used);
}
}
// Sort swaps by usage (descending order)
sort(swaps.begin(), swaps.end(),
[](const pair<string, long> &a, const pair<string, long> &b) {
return a.second > b.second; // Biggest usage first
});
// Extract sorted device names
vector<string> active_swaps;
for (const auto &swap : swaps) {
active_swaps.push_back(swap.first);
}
return active_swaps;
}
pair<int, int> get_swap_usage(const string &device) {
string line;
ifstream proc_file(SWAP_PROC_FILE);
getline(proc_file, line); // Skip header line
int size = 0, used = 0;
while (getline(proc_file, line)) {
if (line.find(device) != string::npos) {
istringstream iss(line);
string temp;
iss >> temp >> temp >> size >> used;
break;
}
}
if (size == 0) {
lock_guard<mutex> lock(safe_thread_mutex);
active_swaps = get_active_swap();
available_swaps = get_available_swap();
ALOGE("Error: Could not determine size of %s", device.c_str());
return {0, -1}; // Return -1% to indicate error
}
int used_percentage = (used * 100) / size;
int used_mb = (used / 1024);
return {used_mb, used_percentage}; // Return {used MB, percentage}
}
vector<string> get_lusg_swaps() {
string line;
ifstream proc_file(SWAP_PROC_FILE);
vector<string> low_usage_swaps;
getline(proc_file, line); // Skip header line
int used = 0;
string device;
while (getline(proc_file, line)) {
istringstream iss(line);
string temp;
iss >> device >> temp >> temp >> used;
int used_mb = (used / 1024);
if (used_mb < 10) {
low_usage_swaps.push_back(device);
}
}
return low_usage_swaps;
}
int get_memory_pressure() {
FILE *fp = popen("free -b", "r");
if (!fp) {
perror("popen failed");
return -1;
}
string line;
char buffer[256];
long mem_used = 0, swap_used = 0;
// Skip the header
fgets(buffer, sizeof(buffer), fp);
while (fgets(buffer, sizeof(buffer), fp)) {
istringstream iss(buffer);
string label;
long used = 0, temp;
iss >> label;
if (label == "Mem:") {
iss >> temp >> used;
mem_used = used;
} else if (label == "Swap:") {
iss >> temp >> used;
swap_used = used;
}
}
pclose(fp);
long total_used = mem_used + swap_used;
if (total_used == 0) return 0;
return static_cast<int>((mem_used * 100) / total_used);
}
template <typename T, typename U>
bool contains(const T &value, vector<U> &vector_data) {
return find(vector_data.begin(), vector_data.end(), value) !=
vector_data.end();
}
template <typename T>
void remove_element(const string &element, vector<T> *elements) {
lock_guard<mutex> lock(safe_thread_mutex);
elements->erase(remove(elements->begin(), elements->end(), element),
elements->end());
}
template <typename T>
void safe_push_back(const string &value, vector<T> &elements) {
lock_guard<mutex> lock(safe_thread_mutex);
elements.push_back(value);
}
// Function to perform swapoff on a single device
void swapoff_th(const string &device) {
string command = "/system/bin/swapoff " + device;
if (system(command.c_str()) == 0) {
ALOGI("Swap: %s is turned off.", device.c_str());
if (device.find("zram") != string::npos) {
safe_push_back(device, available_swaps.first);
} else {
safe_push_back(device, available_swaps.second);
}
remove_element(device, &swapoff_tracker);
remove_element(device, &active_swaps);
} else {
remove_element(device, &swapoff_tracker);
ALOGE("Failed: Turn off %s", device.c_str());
}
}
bool swapoff_(const string &device, vector<thread> &threads,
optional<string> message = nullopt) {
bool cntn_the_swap = contains(device, swapoff_tracker);
if (!cntn_the_swap) {
ALOGI("[THREAD] Swapoff: %s. %s", device.c_str(), message->c_str());
safe_push_back(device, swapoff_tracker);
threads.emplace_back(swapoff_th, device);
return true;
} else {
return false;
}
}
bool swapon(const string device, int priority) {
string command =
"/system/bin/swapon -p " + to_string(priority) + " " + device;
if (system(command.c_str()) == 0) {
ALOGI("SWAPON: %s, priority: %d", device.c_str(), priority);
return true;
} else {
ALOGE("Failed: turn on swap %s", device.c_str());
return false;
}
}
bool is_doze_mode() {
FILE *pipe = popen("dumpsys deviceidle get deep", "r");
if (!pipe) {
cerr << "Failed to check Doze Mode!" << endl;
return false;
}
char buffer[128];
string result = "";
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
result += buffer;
}
pclose(pipe);
// Trim whitespace
result.erase(0, result.find_first_not_of(" \n\r\t"));
result.erase(result.find_last_not_of(" \n\r\t") + 1);
return (result == "IDLE");
}
bool is_sleep_mode() {
FILE *pipe = popen("dumpsys power", "r");
if (!pipe) {
cerr << "Failed to check Sleep Mode!" << endl;
return false;
}
char buffer[128];
string result = "";
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
result += buffer;
}
pclose(pipe);
// Check if display is OFF
return (result.find("mWakefulness=Asleep") != string::npos);
}
void sleeper(int seconds, function<void()> on_complete = nullptr,
function<bool()> interrupt_check = nullptr) {
sleeper_alive = true;
bool interrupted = false;
auto deadline = steady_clock::now() + chrono::seconds(seconds);
ALOGI("Sleep for %d seconds...", seconds);
while (steady_clock::now() < deadline) {
this_thread::sleep_for(milliseconds(100));
if (interrupt_check && interrupt_check()) {
interrupted = true;
break;
}
}
if (!interrupted && on_complete) {
ALOGD("Sleep completed.");
on_complete();
}
sleeper_alive = false;
}
void start_swapoff_timer_if_idle(int wait_timeout) {
if (is_swapoff_session || !is_sleep_mode() || sleeper_alive) return;
thread([=] {
sleeper(
wait_timeout,
[] {
is_swapoff_session = true;
ALOGI_ONCE("swapoff_session", "Swapoff session started...");
ALOG_RESET("swapoff_timer");
},
[] {
if (!is_sleep_mode()) {
ALOGI("Device woke before timeout, swapoff canceled.");
ALOG_RESET("swapoff_timer");
ALOG_RESET("swapoff_session");
return true;
}
return false;
});
}).detach();
ALOGI_ONCE("swapoff timer", "Idle detected. Timer for swapoff initiated...");
}
struct Config {
float config_version;
int swappiness_max;
int swappiness_min;
int zram_activation_threshold;
int zram_deactivation_threshold;
int swap_activation_threshold;
int swap_deactivation_threshold;
int swap_deactivation_time;
bool pressure_binding;
bool deactivate_in_sleep;
string threshold_type;
void load_from_yaml() {
config_version = read_config(".config_version", -1.0);
swappiness_max =
read_config(".dynamic_swappiness.swappiness_range.max", 100);
swappiness_min =
read_config(".dynamic_swappiness.swappiness_range.min", 80);
zram_activation_threshold =
read_config(".virtual_memory.zram.activation_threshold", 70);
zram_deactivation_threshold =
read_config(".virtual_memory.zram.deactivation_threshold", 50);
swap_activation_threshold =
read_config(".virtual_memory.swap.activation_threshold", 90);
swap_deactivation_threshold =
read_config(".virtual_memory.swap.deactivation_threshold", 50);
swap_deactivation_time = read_config(".virtual_memory.wait_timeout", 10);
pressure_binding = read_config(".virtual_memory.pressure_binding", false);
deactivate_in_sleep =
read_config(".virtual_memory.deactivate_in_sleep", true);
threshold_type =
read_config(".dynamic_swappiness.threshold_type", string("psi"));
}
};
struct PressureMapping {
vector<pair<int, int>> cpu;
vector<pair<int, int>> memory;
vector<pair<int, int>> io;
vector<pair<int, int>> mem_pressure;
};
struct DynamicSwappinessConfig {
int min_swappiness;
int max_swappiness;
Config _config;
string threshold_type = _config.threshold_type;
PressureMapping pressure_mapping;
string mode;
int levels;
int cpu_max;
int cpu_min;
int mem_max;
int mem_min;
int io_max;
int io_min;
string cpu_time_window;
string mem_time_window;
string io_time_window;
string pressure_to_string(const vector<pair<int, int>> &pressure_vec) {
stringstream ss;
for (size_t i = 0; i < pressure_vec.size(); ++i) {
ss << "[" << pressure_vec[i].first << "," << pressure_vec[i].second
<< "]";
if (i != pressure_vec.size() - 1) {
ss << ", ";
}
}
return ss.str();
}
void load_from_yaml(const YAML::Node &config) {
ALOGD("Loading DynamicSwappinessConfig from YAML...");
auto dyn = config["dynamic_swappiness"];
if (!dyn) {
ALOGW("dynamic_swappiness section not found in config.");
return;
}
threshold_type = (dyn["threshold_type"] && dyn["threshold_type"].IsScalar())
? dyn["threshold_type"].as<string>()
: "psi";
if (dyn["swappiness_range"] && dyn["swappiness_range"].IsMap()) {
min_swappiness = (dyn["swappiness_range"]["min"] &&
dyn["swappiness_range"]["min"].IsScalar())
? dyn["swappiness_range"]["min"].as<int>()
: _config.swappiness_min;
max_swappiness = (dyn["swappiness_range"]["max"] &&
dyn["swappiness_range"]["max"].IsScalar())
? dyn["swappiness_range"]["max"].as<int>()
: _config.swappiness_max;
} else {
min_swappiness = _config.swappiness_min;
max_swappiness = _config.swappiness_max;
}
ALOGD("threshold_type: %s", threshold_type.c_str());
ALOGD("min_swappiness: %d, max_swappiness: %d", min_swappiness,
max_swappiness);
auto psi = dyn["threshold_psi"];
if (psi) {
// Provide default values if not present in YAML
pressure_mapping.cpu =
psi["cpu_pressure"] && psi["cpu_pressure"].IsSequence()
? parse_pressure_pairs(psi["cpu_pressure"])
: vector<pair<int, int>>{
{10, 160}, {20, 120}, {30, 80}, {40, 60}, {80, 40}};
pressure_mapping.memory =
psi["memory_pressure"] && psi["memory_pressure"].IsSequence()
? parse_pressure_pairs(psi["memory_pressure"])
: vector<pair<int, int>>{
{5, 160}, {10, 140}, {15, 100}, {20, 60}, {25, 40}};
pressure_mapping.io =
psi["io_pressure"] && psi["io_pressure"].IsSequence()
? parse_pressure_pairs(psi["io_pressure"])
: vector<pair<int, int>>{
{10, 140}, {15, 100}, {20, 80}, {25, 100}};
ALOGD("CPU Pressure Mapping: %s",
pressure_to_string(pressure_mapping.cpu).c_str());
ALOGD("Memory Pressure Mapping: %s",
pressure_to_string(pressure_mapping.memory).c_str());
ALOGD("IO Pressure Mapping: %s",
pressure_to_string(pressure_mapping.io).c_str());
} else {
ALOGW("threshold_psi section not found in config.");
}
auto mem = dyn["threshold_mem_pressure"];
mode = (psi && psi["mode"] && psi["mode"].IsScalar())
? psi["mode"].as<string>()
: "auto";
levels = (psi && psi["levels"] && psi["levels"].IsScalar())
? psi["levels"].as<int>()
: 10;
cpu_max = (psi && psi["auto_cpu"] && psi["auto_cpu"]["max"] &&
psi["auto_cpu"]["max"].IsScalar())
? psi["auto_cpu"]["max"].as<int>()
: 80;
cpu_min = (psi && psi["auto_cpu"] && psi["auto_cpu"]["min"] &&
psi["auto_cpu"]["min"].IsScalar())
? psi["auto_cpu"]["min"].as<int>()
: 0;
mem_max = (psi && psi["auto_memory"] && psi["auto_memory"]["max"] &&
psi["auto_memory"]["max"].IsScalar())
? psi["auto_memory"]["max"].as<int>()
: 20;
mem_min = (psi && psi["auto_memory"] && psi["auto_memory"]["min"] &&
psi["auto_memory"]["min"].IsScalar())
? psi["auto_memory"]["min"].as<int>()
: 0;
io_max = (psi && psi["auto_io"] && psi["auto_io"]["max"] &&
psi["auto_io"]["max"].IsScalar())
? psi["auto_io"]["max"].as<int>()
: 25;
io_min = (psi && psi["auto_io"] && psi["auto_io"]["min"] &&
psi["auto_io"]["min"].IsScalar())
? psi["auto_io"]["min"].as<int>()
: 0;
cpu_time_window =
(psi && psi["auto_cpu"] && psi["auto_cpu"]["time_window"] &&
psi["auto_cpu"]["time_window"].IsScalar())
? psi["auto_cpu"]["time_window"].as<string>()
: "avg60";
mem_time_window =
(psi && psi["auto_memory"] && psi["auto_memory"]["time_window"] &&
psi["auto_memory"]["time_window"].IsScalar())
? psi["auto_memory"]["time_window"].as<string>()
: "avg60";
io_time_window = (psi && psi["auto_io"] && psi["auto_io"]["time_window"] &&
psi["auto_io"]["time_window"].IsScalar())
? psi["auto_io"]["time_window"].as<string>()
: "avg60";
mem_time_window =
psi && psi["auto_memory"] && psi["auto_memory"]["time_window"]
? psi["auto_memory"]["time_window"].as<string>()
: "avg60";
io_time_window = psi && psi["auto_io"] && psi["auto_io"]["time_window"]
? psi["auto_io"]["time_window"].as<string>()
: "avg60";
ALOGD("mode: %s, levels: %d", mode.c_str(), levels);
ALOGD(
"cpu_max: %d, cpu_min: %d, mem_max: %d, mem_min: %d, io_max: %d, "
"io_min: %d",
cpu_max, cpu_min, mem_max, mem_min, io_max, io_min);
ALOGD("cpu_time_window: %s, mem_time_window: %s, io_time_window: %s",
cpu_time_window.c_str(), mem_time_window.c_str(),
io_time_window.c_str());
}
};
bool psi_available() {
ifstream cpu_file("/proc/pressure/cpu");
ifstream mem_file("/proc/pressure/memory");
ifstream io_file("/proc/pressure/io");
if (cpu_file.good() && mem_file.good() && io_file.good()) {
return true;
} else {
ALOGW_ONCE("psi_unavailable",
"PSI metrics unavailable. Falling back to mem_pressure.");
return false;
}
}
class SwappinessManager {
public:
SwappinessManager(const DynamicSwappinessConfig &config)
: config(config), last_swappiness(-1) {
// Cache sorted pressure maps
cached_cpu = sort_desc(config.pressure_mapping.cpu);
cached_mem = sort_desc(config.pressure_mapping.memory);
cached_io = sort_desc(config.pressure_mapping.io);
cached_legacy = sort_desc(config.pressure_mapping.mem_pressure);
}
int get_swappiness() {
int swappiness = config.threshold_type == "psi" && psi_available()
? evaluate_psi()
: evaluate_legacy();
return clamp(swappiness, config.min_swappiness, config.max_swappiness);
}
void apply_swappiness(int &swappiness) {
if (swappiness != last_swappiness) {
ALOGI("Swappiness -> %d", swappiness);
write_swappiness(swappiness);
last_swappiness = swappiness;
reset_threshold_logs();
}
}
private:
const DynamicSwappinessConfig &config;
int last_swappiness;
// Cached sorted maps
vector<pair<int, int>> cached_cpu;
vector<pair<int, int>> cached_mem;
vector<pair<int, int>> cached_io;
vector<pair<int, int>> cached_legacy;
static vector<pair<int, int>> sort_desc(const vector<pair<int, int>> &table) {
auto sorted = table;
sort(sorted.begin(), sorted.end(),
[](const auto &a, const auto &b) { return a.first > b.first; });
return sorted;
}