forked from mozilla-b2g/gonk-misc
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathb2gkillerd.cpp
1408 lines (1220 loc) · 40.2 KB
/
b2gkillerd.cpp
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 <cutils/properties.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <sys/eventfd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <ctype.h>
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <functional>
#include <memory>
#include <vector>
#include <set>
#ifdef ANDROID
#include "android/log.h"
#define LOGD(...) \
if (debugging_b2g_killer) { \
__android_log_print(ANDROID_LOG_INFO, "b2gkillerd", ## __VA_ARGS__); \
}
#define LOGI(...) __android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, "b2gkillerd", ## __VA_ARGS__);
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "b2gkillerd", ## __VA_ARGS__);
#else
#define LOGD(...) printf(## __VA_ARGS__)
#define LOGI(...) printf(## __VA_ARGS__)
#define LOGE(...) fprintf(stderr, ## __VA_ARGS__)
#endif
/**
* Classes:
*
* MemPressureWatcher
* |
* | <<callback>>
* v
* killer -----> MemPressureCounter
* |
* |
* +---> ProcessKiller -----> ProcessList
* |
* |
* +---> KickGCCC()
*
* MemPressureWatcher:
*
* It listens events of memory.pressure_level of the root cgroup and
* pass the counter to the callback. The counter is increased
* whenever memory pressure is low/medium/or high. So far, it
* listens medium pressure.
*
* MemPressureCounter:
*
* It implements a counter for memory pressure. The counter is an
* exponential moving average of the number of events over time.
*
* ProcessList:
*
* It keeps a list of process and reads memory usages of processes
* from the procfs.
*
* ProcessKiller:
*
* It pick one of background process to kill, according types and
* memory usages.
*
* KickGCCC:
*
* Send a signal to the parent process to start GC/CC.
*/
#define ASSERT(x, msg) do { \
if (!(x)) { \
LOGE("ASSERT! ERROR: %s : %s:%d\n", \
(msg), __FILE__, __LINE__); abort(); \
} \
} while (0)
#define ABORT(msg) do { \
LOGE("ABORT! ERROR: %s : %s:%d\n", \
(msg), __FILE__, __LINE__); abort(); \
} while (0)
#ifdef ANDROID
#define CGROUP_FS "/dev/memcg/"
#else
#define CGROUP_FS "/sys/fs/cgroup/memory/"
#endif
#define B2G_CGROUP CGROUP_FS "b2g/"
#define FG_CGROUP B2G_CGROUP "fg/"
#define BG_CGROUP B2G_CGROUP "bg/"
#define TRY_TO_KEEP_CGROUP BG_CGROUP "try_to_keep/"
#define DEFAULT_CGROUP B2G_CGROUP "default/"
#define MEMORY_PRESSURE_LEVEL_PATH CGROUP_FS "memory.pressure_level"
#define EVENT_CONTROL CGROUP_FS "cgroup.event_control"
// Data points will degrade by EMA_FACTOR every second.
// Half life period = ln(0.5) / ln(EMA_FACTOR_DFL)
// new_value = old_value * EMA_FACTOR_DFL ^ n-seconds
#define EMA_FACTOR_DFL 0.1
#define PRESSURE_LEVEL "medium"
#define MEMINFO_PATH "/proc/meminfo"
#define MEMINFO_FIELD_COUNT 9
#define PID_FILE "/data/local/tmp/b2gkillerd.pid"
#define LOWEST_SCORE 1.0
#define IDLE_MPCOUNTER 2.0
static double mem_pressure_high_threshold = 60.0;
static double mem_pressure_low_threshold = 30.0;
// Trigger GC/CC only when the memory pressure is between max and min
// threshold below.
static double gc_cc_max = 60.0;
static double gc_cc_min = 40.0;
/**
* Dirty memory have to be written out before reclaiming it while
* clean memory can be reclaimed and used without additional cost.
* So, we have to weigh dirty memory differently.
*/
static double dirty_mem_weight = 0.2;
enum KilleeType {
BACKGROUND,
TRY_TO_KEEP,
FOREGROUND,
KILLEE_TYPE_NUMS
};
/**
* For the case of zram, swapped pages take memory too. They are
* compressed, so it shoud multiply a weight.
*/
static double swapped_mem_weight = 0.5;
// High swapped mem weight.
static double high_swapped_mem_weight = 1.5;
// Consecutive kicks should be longer than |min_kick_interval| seconds.
static double min_kick_interval = 0.5;
// Consecutive kicks should be longer than |min_kill_interval| seconds.
static double min_kill_interval = 0.8;
// Available swap free threshold.
static double swap_free_soft_threshold = 0.25;
static double swap_free_hard_threshold = 0.20;
static int mem_free_low_watermark[KILLEE_TYPE_NUMS] = { INT_MAX, 8192, 8192 };
static int cache_low_watermark[KILLEE_TYPE_NUMS] = { INT_MAX, 51200, 51200 };
static bool debugging_b2g_killer = false;
static bool enable_dumpping_process_info = false;
union meminfo {
struct {
int64_t free;
int64_t cached;
int64_t swap_cached;
int64_t buffers;
int64_t shmem;
int64_t unevictable;
int64_t total_swap;
int64_t free_swap;
int64_t dirty;
} field;
int64_t arr[MEMINFO_FIELD_COUNT];
};
static const char* field_names[MEMINFO_FIELD_COUNT] = {
"MemFree:",
"Cached:",
"SwapCached:",
"Buffers:",
"Shmem:",
"Unevictable:",
"SwapTotal:",
"SwapFree:",
"Dirty:",
};
enum field_match_result {
NO_MATCH,
PARSE_FAIL,
PARSE_SUCCESS
};
static bool ParseInt64(const char* str, int64_t* ret) {
char* endptr;
long long val = strtoll(str, &endptr, 10);
if (str == endptr) {
return false;
}
*ret = (int64_t)val;
return true;
}
static enum field_match_result MatchField(const char* cp, const char* ap,
const char* const field_names[],
int field_count, int64_t* field,
int *field_idx) {
int i;
for (i = 0; i < field_count; i++) {
if (!strcmp(cp, field_names[i])) {
*field_idx = i;
return ParseInt64(ap, field) ? PARSE_SUCCESS : PARSE_FAIL;
}
}
return NO_MATCH;
}
static bool MemInfoParseLine(char *line, union meminfo *mi) {
char *cp = line;
char *ap;
char *save_ptr;
int64_t val;
int field_idx;
enum field_match_result match_res;
cp = strtok_r(line, " ", &save_ptr);
if (!cp) {
return false;
}
ap = strtok_r(NULL, " ", &save_ptr);
if (!ap) {
return false;
}
match_res = MatchField(cp, ap, field_names, MEMINFO_FIELD_COUNT,
&val, &field_idx);
if (match_res == PARSE_SUCCESS) {
mi->arr[field_idx] = val;
}
return (match_res != PARSE_FAIL);
}
static bool MemInfoParse(union meminfo *mi) {
size_t sz = 128;
char *buf = (char*)malloc(sz);
memset(mi, 0, sizeof(union meminfo));
FILE* fo = fopen(MEMINFO_PATH, "r");
if (fo == nullptr) {
return false;
}
while (getline(&buf, &sz, fo) >= 0) {
if (!MemInfoParseLine(buf, mi)) {
LOGI("meminfo parse error");
return false;
}
}
free(buf);
fclose(fo);
return true;
}
/**
* Counting memory pressure with a moving average.
*/
class MemPressureCounter {
public:
MemPressureCounter(double aMul = EMA_FACTOR_DFL) : factor(aMul), datum(0.0) {
}
MemPressureCounter(const MemPressureCounter& aOther)
: factor(aOther.factor),
datum(aOther.datum),
last_tm(aOther.last_tm) {
}
double HalfLifePeriod() {
return log(0.5) / log(factor);
}
double Average() { return datum; }
double AddOne() {
datum = exponentialMA(datum, 1.0, DiffLastTimestamp(), factor);
return datum;
}
double Add(double addend) {
datum = exponentialMA(datum, addend, DiffLastTimestamp(), factor);
return datum;
}
double ForceUpdate() {
datum = exponentialMA(datum, 0, DiffLastTimestamp(), factor);
return datum;
}
double Reset() {
datum = 0.0;
return datum;
}
private:
double factor;
double datum;
timespec last_tm;
double DiffLastTimestamp() {
timespec tm;
clock_gettime(CLOCK_MONOTONIC_COARSE, &tm);
double diff_sec =
(double)(tm.tv_sec - last_tm.tv_sec) +
(double)(tm.tv_nsec - last_tm.tv_nsec) * 1.0e-9;
last_tm = tm;
return diff_sec;
}
/**
* Exponential Moving Average.
*
* https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
*/
static double
exponentialMA(double old, double addend, double elapse, double factor) {
double new_value = addend;
if (old > 0.0) {
new_value += old * pow(factor, elapse);
}
return new_value;
}
};
/**
* The information (memory usages) of a process.
*/
class ProcessInfo {
public:
ProcessInfo(int aPid) : mValid(false), mPid(aPid) {}
bool IsValid() const { return mValid; }
int GetPid() const { return mPid; }
/**
* Read memory usages of the process from procfs.
*/
bool Update() {
mValid = UpdateStatus() && UpdateComm() && UpdateSmaps();
return mValid;
}
private:
bool UpdateComm() {
// Read app name
char commpath[64];
snprintf(commpath, 64, "/proc/%d/comm", mPid);
std::unique_ptr<FILE, int(*)(FILE*)> commfp(fopen(commpath, "r"), fclose);
if (commfp == nullptr) {
return false;
}
char _appname[64];
const char *appname;
int cp = fread(_appname, 1, 63, commfp.get());
if (cp > 0) {
// Remove trailing spaces
while (cp > 0 && isspace(_appname[cp - 1])) {
cp--;
}
_appname[cp] = 0;
appname = _appname;
} else {
appname = "<unknown>";
}
strncpy(mAppName, appname, 64);
return true;
}
bool UpdateStatus() {
char status_fn[64];
snprintf(status_fn, 64, "/proc/%d/status", mPid);
std::unique_ptr<FILE, int(*)(FILE*)> fo(fopen(status_fn, "r"), fclose);
if (fo == nullptr) {
return false;
}
size_t sz = 128;
char *buf = (char*)malloc(sz);
while (getline(&buf, &sz, fo.get()) >= 0) {
char *saveptr;
char *field = strtok_r(buf, " \t\n:", &saveptr);
if (strcmp(field, "VmSize") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mVmSize = atol(value);
} else if (strcmp(field, "VmRSS") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mVmRSS = atol(value);
} else if (strcmp(field, "RssAnon") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mRssAnon = atol(value);
} else if (strcmp(field, "RssFile") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mRssFile = atol(value);
} else if (strcmp(field, "RssShmem") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mRssShmem = atol(value);
} else if (strcmp(field, "VmSwap") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mVmSwap = atol(value);
} else if (strcmp(field, "State") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
strncpy(&mState, value, 1);
}
}
free(buf);
return true;
}
bool UpdateSmaps() {
char status_fn[64];
snprintf(status_fn, 64, "/proc/%d/smaps", mPid);
std::unique_ptr<FILE, int(*)(FILE*)> fo(fopen(status_fn, "r"), fclose);
if (fo == nullptr) {
return false;
}
mSharedClean = 0;
mSharedDirty = 0;
mPrivateClean = 0;
mPrivateDirty = 0;
size_t sz = 128;
char *buf = (char*)malloc(sz);
while (getline(&buf, &sz, fo.get()) >= 0) {
char *saveptr;
char *field = strtok_r(buf, " \t\n:", &saveptr);
if (strcmp(field, "Shared_Clean") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mSharedClean += atol(value);
} else if (strcmp(field, "Shared_Dirty") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mSharedDirty += atol(value);
} else if (strcmp(field, "Private_Clean") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mPrivateClean += atol(value);
} else if (strcmp(field, "Private_Dirty") == 0) {
char *value = strtok_r(nullptr, " \t\n:", &saveptr);
mPrivateDirty += atol(value);
}
}
free(buf);
return true;
}
bool mValid;
int mPid;
public:
// from status
long mVmSize;
long mVmRSS;
long mRssAnon;
long mRssFile;
long mRssShmem;
long mVmSwap;
// from smaps
long mSharedClean;
long mSharedDirty;
long mPrivateClean;
long mPrivateDirty;
char mAppName[64];
char mState;
};
/**
* Keep a list of processes of foreground, background and try_to_keep.
*/
class ProcessList {
public:
typedef std::vector<ProcessInfo> ListType;
ProcessList() {}
bool HasProc(int aPid) {
return find_proc_itr(aPid) != mProcs.end();
}
// Make this process a foreground processess
void AddFG(int aPid) {
add_proc(aPid);
mFgProc.insert(aPid);
}
int HasFG(int aPid) const {
return mFgProc.find(aPid) != mFgProc.end();
}
// Make this process a foreground processess
void AddBG(int aPid) {
add_proc(aPid);
mBgProc.insert(aPid);
}
int HasBG(int aPid) const {
return mBgProc.find(aPid) != mBgProc.end();
}
// Try to keep this bacground processes
void AddTryToKeep(int aPid) {
add_proc(aPid);
mTryToKeepSet.insert(aPid);
}
void UpdateInfo() {
for (auto& pinfo : mProcs) {
pinfo.Update();
}
}
void RemoveProc(int aPid) {
for (auto itr = mProcs.begin(); itr != mProcs.end(); ++itr) {
if (itr->GetPid() == aPid) {
mProcs.erase(itr);
mTryToKeepSet.erase(aPid);
mFgProc.erase(aPid);
mBgProc.erase(aPid);
break;
}
}
}
const ProcessInfo* GetProcInfo(int aPid) const {
auto itr = find_proc_itr(aPid);
if (itr != mProcs.end()) {
return &*itr;
}
return nullptr;
}
ListType::const_iterator begin() const {
return mProcs.begin();
}
ListType::const_iterator end() const {
return mProcs.end();
}
bool HasTryToKeep(int aPid) const {
return mTryToKeepSet.find(aPid) != mTryToKeepSet.end();
}
size_t size() const {
return mProcs.size();
}
private:
typedef std::set<int> ProcIdSet;
ListType mProcs;
ProcIdSet mTryToKeepSet;
ProcIdSet mFgProc;
ProcIdSet mBgProc;
std::vector<ProcessInfo>::const_iterator find_proc_itr(int aPid) const {
// Assuming this list is short, it doesn't spend much time.
for (auto itr = mProcs.begin(); itr != mProcs.end(); itr++) {
if (itr->GetPid() == aPid) {
return itr;
}
}
return mProcs.end();
}
void add_proc(int aPid) {
ASSERT(!HasProc(aPid), "add an existing process");
mProcs.push_back(ProcessInfo(aPid));
}
};
/**
* Pick a process to kill.
*
* This class actually has no any states. It is just a collection of
* all functions that implement this feature.
*/
class ProcessKiller {
/**
* Add proccess processes to a ProcessList. The are found from
* cgroups of b2g/fg, b2g/bg, and b2g/bg/try_to_keep. They are
* belong to foreground, background, and try_to_keep processes.
*
* When the memory falls short, it try to kill a process picked from
* background process to release memory. There are try_to_keep
* processes. They are background processes too, but we try to keep
* them in the memory if possible, so other background processes will
* be killed before the try_to_keep processes.
*/
static void FillB2GProcessList(ProcessList* aProcs) {
size_t lsz = 128;
char *line = (char*)malloc(lsz);
FILE* fp = fopen(BG_CGROUP "cgroup.procs", "r");
ASSERT(fp != nullptr, "Can't open background cgroup");
while (getline(&line, &lsz, fp) > 0) {
auto pid = atoi(line);
aProcs->AddBG(pid);
}
fclose(fp);
fp = fopen(TRY_TO_KEEP_CGROUP "cgroup.procs", "r");
ASSERT(fp != nullptr, "Can't open try_to_keep cgroup");
while (getline(&line, &lsz, fp) > 0) {
auto pid = atoi(line);
if (aProcs->HasProc(pid)) {
// Since b2gkillerd and procmanager are asynchronous,
// procmanager can change cgroup.procs inbetween readings
// here. Remove previous added info to do our best.
aProcs->RemoveProc(pid);
}
aProcs->AddTryToKeep(pid);
}
fclose(fp);
fp = fopen(FG_CGROUP "cgroup.procs", "r");
ASSERT(fp != nullptr, "Can't open foreground cgroup");
while (getline(&line, &lsz, fp) > 0) {
auto pid = atoi(line);
if (aProcs->HasProc(pid)) {
// Since b2gkillerd and procmanager are asynchronous,
// procmanager can change cgroup.procs inbetween readings
// here. Remove previous added info to do our best.
//
// FG is more important to previous groups, so adding to the
// FG group is prefered.
aProcs->RemoveProc(pid);
}
aProcs->AddFG(pid);
}
fclose(fp);
free(line);
aProcs->UpdateInfo();
}
static double ProcInfoKillScore(const ProcessInfo& aPInfo, bool aSwapSensitive) {
// Prefer the processes that has more clean private pages over
// processes that has dirty pages sicne dirty ones should be
// written out before using it.
//
// Shared memory is not counted here for that it may not make more
// available memory from shared memory to kill a process.
double score = aPInfo.mPrivateClean +
aPInfo.mPrivateDirty * dirty_mem_weight;
// Prefer the higher SWAP space consumer to be killed.
if (aSwapSensitive) {
score += aPInfo.mVmSwap * high_swapped_mem_weight;
} else {
score += aPInfo.mVmSwap * swapped_mem_weight;
}
return score;
}
static bool
IsTargetKillee(const ProcessInfo& aProc, ProcessList *aProcs, KilleeType aType) {
if (!aProc.IsValid()) {
// Return false if process' information is invalid.
return false;
} else if (aProc.mState != 'S' && aProc.mState != 'R') {
// If the process's state is 'D' (Uninterruptible Sleep), it's high
// possibilty that we cannot kill process and reclaim the memory
// immediately. If the state is 'Z' (Zombie), it means process is in the end
// of its life cycle, we should not kill it again.
// So we skip it if state of process is not 'S' (Sleep) nor 'R' (Running).
return false;
} else if ((aProcs->HasBG(aProc.GetPid()) && (aType == BACKGROUND)) ||
(aProcs->HasTryToKeep(aProc.GetPid()) && (aType == TRY_TO_KEEP)) ||
(aProcs->HasFG(aProc.GetPid()) && (aType == FOREGROUND))) {
return true;
} else {
return false;
}
}
static const ProcessInfo*
FindBestProcToKill(ProcessList* aProcs, KilleeType aType, bool aSwapSensetive,
const meminfo* aMemInfo) {
const ProcessInfo *best = nullptr;
double best_score = 0.0;
if (aMemInfo == nullptr) {
return best;
}
LOGD("Try to kill process with priority %d\n", aType);
for (auto& proc : *aProcs) {
if (!IsTargetKillee(proc, aProcs, aType)) {
continue;
}
if (aMemInfo->field.free > mem_free_low_watermark[aType] ||
aMemInfo->field.cached > cache_low_watermark[aType]) {
LOGD("Try to %s but still have enough free memory (%" PRIi64 "KB + %"
PRIi64 "KB), skip it", proc.mAppName, aMemInfo->field.free,
aMemInfo->field.cached);
continue;
}
// Set launcher app as lowest score to let it stay longer.
double score = strcmp(proc.mAppName, "launcher") ?
ProcInfoKillScore(proc, aSwapSensetive) : LOWEST_SCORE;
if (score > best_score) {
best = &proc;
best_score = score;
}
}
return best;
}
public:
static const char* GetProcessPriority(ProcessList* aProcs, int aPid) {
if (aProcs->HasFG(aPid)) {
return "fg";
} else if (aProcs->HasBG(aPid)) {
return "bg";
} else if (aProcs->HasTryToKeep(aPid)) {
return "try_to_keep";
} else {
return "default";
}
}
static void DumpProcessesInfo(ProcessList* aProcs) {
int pid;
const char* priority;
for (auto proc = aProcs->begin(); proc != aProcs->end(); proc++) {
if (!proc->IsValid()) {
continue;
}
pid = proc->GetPid();
priority = GetProcessPriority(aProcs, pid);
LOGI("name: %s, pid: %d, state: %c, priority: %s, score: %.2lf/%.2lf, "
"RSS: %ld, VSS: %ld\n",
proc->mAppName, pid, proc->mState, priority,
ProcInfoKillScore(*proc, false), ProcInfoKillScore(*proc, true),
proc->mVmRSS, proc->mVmSize);
}
}
/**
* Choice one of processes and kill it. Return true if kill successfully.
*
* Basing on the information from cgroup filesystem, it pick one of
* background process to kill. It will kill one of background
* processes other than try-to-keep ones, unless only try-to-keeps
* ones are left.
*/
static bool KillOneProc(KilleeType aType, bool aSwapSensetive,
const meminfo* aMemInfo) {
bool success = false;
if (aMemInfo == nullptr) {
return success;
}
timespec tm;
// Consecutive kills should be longer than |min_kill_interval| seconds.
clock_gettime(CLOCK_MONOTONIC_COARSE, &tm);
double tm_diff = (double)(tm.tv_sec - mLastTm.tv_sec) +
(double)(tm.tv_nsec - mLastTm.tv_nsec) * 1e-9;
// Here we allow background app could be killed consecutively.
if (aType != BACKGROUND && tm_diff < min_kill_interval) {
LOGD("Try to kill app in a short interval (%fs), ignore it!\n",
min_kill_interval);
return success;
}
ProcessList procs;
FillB2GProcessList(&procs);
if (enable_dumpping_process_info) {
DumpProcessesInfo(&procs);
}
auto proc = FindBestProcToKill(&procs, aType, aSwapSensetive, aMemInfo);
if (proc == nullptr) {
LOGD("There is no proper process to kill!\n");
return success;
}
int pid = proc->GetPid();
if (kill(pid, SIGKILL)) {
LOGI("Failed to kill proc %s (%d) with error: %s\n", proc->mAppName, pid,
strerror(errno));
} else {
// XXX: Don't touch line before talking with the data team.
// They want the format of this log to be fixed.
LOGI("Kill proc %s (%d) for memory pressure:%d:%ld/%ld\n",
proc->mAppName, pid, (int)aType, proc->mVmRSS, proc->mVmSize);
success = true;
mLastTm = tm;
}
if (enable_dumpping_process_info) {
DumpProcessesInfo(&procs);
}
return success;
}
private:
static timespec mLastTm;
};
timespec ProcessKiller::mLastTm = { 0, 0 };
/**
* Watch at memory pressure events.
*
* It will call the callback whenever the memory pressure is above a
* level; high, medium or low. The callback should be assigned by
* calling |init()|.
*
* EXAMPLE:
* MemPressureWatcher watcher;
* watcher.init(callback);
* watcher.watch(); // |callback| will be called for memory pressure.
*/
class MemPressureWatcher {
public:
// The socket path to receive incremental changes of hints.
constexpr static const char* HINT_SOCK_PATH = "/dev/socket/b2gkiller_hints";
// Names of supported hints.
// An ID is given to each names in their order in this array.
// For example, boot's ID is 0, and it is at bit 0 of mHints.
constexpr static const char* HINT_NAMES[] = {
"boot"
};
enum { HINT_BOOT = 0 };
// The hint file that contain all current hints.
// This file is updated by api-daemon.
constexpr static const char* HINT_FILE = "/data/local/tmp/prochints.dat";
using Handler = std::function<bool(unsigned int)>;
MemPressureWatcher()
: mEventFd(-1),
mMemPressureLevelFd(-1),
mHintFd(-1),
mHints(0) {
}
~MemPressureWatcher() {
if (mEventFd >= 0) {
close(mEventFd);
}
if (mMemPressureLevelFd >= 0) {
close(mMemPressureLevelFd);
}
if (mHintFd >= 0) {
close(mHintFd);
}
}
void Init(Handler&& aHandler) {
int eflags = 0;
int efd = eventfd(0, eflags);
int mpl_fd = open(MEMORY_PRESSURE_LEVEL_PATH, O_RDWR);
// Create a socket to receiveincremental update of hints from api-daemon.
remove(HINT_SOCK_PATH);
struct sockaddr_un addr;
bzero(&addr, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, HINT_SOCK_PATH, strlen(HINT_SOCK_PATH) + 1);
int hint_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
ASSERT(hint_fd >= 0, "Fail to create a socket for b2gkiller_hint");
int hint_bind_r = bind(hint_fd, (const struct sockaddr*)&addr, sizeof(addr));
ASSERT(hint_bind_r >= 0, "Fail to bind b2gkiller_hint");
LoadHintFile();
char msg[256];
snprintf(msg, 256, "%d %d " PRESSURE_LEVEL "\n", efd, mpl_fd);
int cfd = open(EVENT_CONTROL, O_RDWR);
int cp = 0;
cp = write(cfd, msg, strlen(msg));
ASSERT(cp >= 0, "Can not write to the event control");
close(cfd);
mEventFd = efd;
mMemPressureLevelFd = mpl_fd;
mHintFd = hint_fd;
mHandler = std::move(aHandler);
}
void Watch() {
pollfd fds[2] = {{mEventFd, POLLIN, 0},
{mHintFd, POLLIN, 0}};
int wait = 1000; // 1s
while (poll(fds, 1, wait) >= 0) {
uint64_t cnt = 0;
if (fds[0].revents) {
int cp = read(mEventFd, &cnt, 8);
ASSERT(cp > 0, "Fail to read from the event fd");
}
fds[0].revents = 0;
bool cont = mHandler(cnt);
if (!cont) {
break;
}
if (fds[1].revents) {
// Handle incremental changes of hints.
//
// The received messages are in the format of
//
// modify +add_hint_1 +add_hint_2 -remove_hint_3
// or
// reset
//
// |modify| is to modify, adding or removing, hints following it.
// |reset| is to clear/remove all hints.
//
char buf[256];
int cp = recv(mHintFd, buf, 256, 0);
ASSERT(cp > 0, "Fail to receive a b2gkiller_hint message");
ASSERT(cp < 256, "The received message from b2gkiller_hint is too big (> 255)");
buf[cp] = 0;
if (strncmp(buf, "modify ", 7) == 0) {
char* savedptr = nullptr;
char* ptr;
while ((ptr = strtok_r(buf + 7, " ", &savedptr)) != nullptr) {
switch(ptr[0]) {
case '+':
{
auto hintid = get_hint_id(ptr + 1);
ASSERT(hintid >= 0, "Unknown hint name");
mHints |= 1 << hintid;
}
break;
case '-':
{
auto hintid = get_hint_id(ptr + 1);
ASSERT(hintid >= 0, "Unknown hint name");
mHints &= ~(1 << hintid);
}
break;
default:
ABORT("Invalid b2gkiller_hint operator (+/-)");
}
}
} else if (strcmp(buf, "reset") == 0) {
mHints = 0;
} else {
ABORT("Invalid b2gkiller_hint message");
}
}
}
}
uint32_t GetHintFlags() {
return mHints;
}
private:
int get_hint_id(const char* hint) {
int n = sizeof(HINT_NAMES) / sizeof(HINT_NAMES[0]);
for (int i = 0; i < n; i++) {
if (strcmp(HINT_NAMES[i], hint) == 0) {
return i;
}
}
return -1;
}
/**