-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathadaptivemmd.c
1963 lines (1767 loc) · 50.9 KB
/
adaptivemmd.c
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
/*
* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* * This code is free software; you can redistribute it and/or modify it
* * under the terms of the GNU General Public License version 2 only, as
* * published by the Free Software Foundation.
* *
* * This code is distributed in the hope that it will be useful, but WITHOUT
* * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* * version 2 for more details (a copy is included in the LICENSE file that
* * accompanied this code).
* *
* * You should have received a copy of the GNU General Public License version
* * 2 along with this work; if not, write to the Free Software Foundation,
* * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
* *
* * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* * or visit www.oracle.com if you need additional information or have any
* * questions.
* */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include <limits.h>
#include <pthread.h>
#include <search.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <syslog.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <dirent.h>
#include <ctype.h>
#include <stdbool.h>
#include <signal.h>
#include <linux/kernel-page-flags.h>
#include "predict.h"
#define VERSION "2.1.0"
#define LOCKFILE "/var/run/adaptivemmd.pid"
/*
* System files that provide information
*/
#define BUDDYINFO "/proc/buddyinfo"
#define ZONEINFO "/proc/zoneinfo"
#define VMSTAT "/proc/vmstat"
#define MEMINFO "/proc/meminfo"
#define KPAGECOUNT "/proc/kpagecount"
#define KPAGEFLAGS "/proc/kpageflags"
#define MODULES "/proc/modules"
#define HUGEPAGESINFO "/sys/kernel/mm/hugepages"
/*
* System files to control reclamation and compaction
*/
#define RESCALE_WMARK "/proc/sys/vm/watermark_scale_factor"
#define COMPACT_PATH_FORMAT "/sys/devices/system/node/node%d/compact"
/*
* System files to control negative dentries
*/
#define NEG_DENTRY_LIMIT "/proc/sys/fs/negative-dentry-limit"
/*
* Possible locations for configuration files
*/
#define CONFIG_FILE1 "/etc/sysconfig/adaptivemmd"
#define CONFIG_FILE2 "/etc/default/adaptivemmd"
#define MAX_NUMANODES 1024
#define MAX_VERBOSE 5
#define MAX_AGGRESSIVE 3
#define MAX_NEGDENTRY 100
/*
* Number of consecutive samples showing growth in unaccounted memory
* that will trigger memory leak warning
*/
#define UNACCT_MEM_GRTH_MAX 10
/* Minimum % change in meminfo numbers to trigger warnings */
#define MEM_TRIGGER_DELTA 10
unsigned long min_wmark[MAX_NUMANODES], low_wmark[MAX_NUMANODES];
unsigned long high_wmark[MAX_NUMANODES], managed_pages[MAX_NUMANODES];
unsigned long total_free_pages, total_cache_pages, total_hugepages, base_psize;
long compaction_rate, reclaim_rate;
struct lsq_struct page_lsq[MAX_NUMANODES][MAX_ORDER];
int dry_run;
int debug_mode, verbose, del_lock = 0;
unsigned long maxgap;
int aggressiveness = 2;
int periodicity, skip_dmazone;
int neg_dentry_pct = 15; /* default is 1.5% */
/* Flags to enable various modules */
bool memory_pressure_check_enabled = true;
bool neg_dentry_check_enabled = true;
bool memleak_check_enabled = true;
/*
* Highest value to set watermark_scale_factor to. This value is tied
* to aggressiveness level. Higher level of aggressiveness will result
* in higher value for this. Set the default to match default
* aggressiveness value
*/
unsigned int maxwsf = 700;
unsigned int mywsf;
/*
* Highest order pages to lok at for fragmentation. Ignore order 10
* pages, they require moving around lots of pages to create and thus
* are expensive. This value is tied into aggressiveness level. Higher
* level of aggressiveness will result in going up on the order for
* fragmentation check. Set the default to match default aggressiveness
* value
*/
int max_compaction_order = MAX_ORDER - 4;
/*
* Clean up before exiting
*/
void
bailout(int retval)
{
if (del_lock)
unlink(LOCKFILE);
closelog();
exit(retval);
}
/*
* Signal handler to ensure cleanup before exiting
*/
void
mysig(int signo)
{
bailout(0);
}
void
log_msg(int level, char *fmt, ...)
{
va_list args;
va_start(args, fmt);
if (debug_mode) {
char stamp[32], prepend[16];
time_t now;
struct tm *timenow;
now = time(NULL);
timenow = localtime(&now);
strftime(stamp, 32, "%b %d %T", timenow);
printf("%s ", stamp);
switch (level) {
case LOG_ERR:
strcpy(prepend, "ERROR:");
break;
case LOG_WARNING:
strcpy(prepend, "Warning:");
break;
case LOG_INFO:
strcpy(prepend, "Info:");
break;
case LOG_DEBUG:
strcpy(prepend, "Debug:");
break;
}
printf("%s ", prepend);
vprintf(fmt, args);
printf("\n");
}
else {
vsyslog(level, fmt, args);
}
va_end(args);
}
/*
* Initiate memory compactiomn in the kernel on a given node.
*/
void
compact(int node_id)
{
char compactpath[PATH_MAX];
int fd;
char c = '1';
if (snprintf(compactpath, sizeof(compactpath), COMPACT_PATH_FORMAT,
node_id) >= sizeof(compactpath)) {
(void) log_err("compactpath is too long");
bailout(1);
}
if ((fd = open(compactpath, O_WRONLY|O_NONBLOCK)) == -1) {
log_err("opening compaction path (%s)", strerror(errno));
bailout(1);
}
if (write(fd, &c, sizeof(c)) != sizeof(c)) {
log_err("writing to compaction path (%s)", strerror(errno));
bailout(1);
}
close(fd);
}
/*
* Parse a single input line for buddyinfo; return 1 if successful
* or 0 otherwise.
*/
int
scan_buddyinfo(char *line, char *node, char *zone, unsigned long *nr_free)
{
char copy[LINE_MAX];
unsigned int order;
char *t;
(void) strncpy(copy, line, sizeof(copy));
if ((t = strtok(copy, " ")) == NULL || strcmp(t, "Node") ||
(t = strtok(NULL, ",")) == NULL || sscanf(t, "%s", node) != 1 ||
(t = strtok(NULL, " ")) == NULL || strcmp(t, "zone") ||
(t = strtok(NULL, " ")) == NULL || sscanf(t, "%s", zone) != 1)
return 0;
for (order = 0; order < MAX_ORDER; order++) {
if ((t = strtok(NULL, " ")) == NULL ||
sscanf(t, " %ld", &nr_free[order]) != 1)
return 0;
}
return 1;
}
/*
* Compile free page info for the next node and update free pages
* vector passed by the caller.
*
* RETURNS:
* 1 No error
* 0 Error
* -1 EOF
*
*/
#define FLDLEN 20
#define NO_ERR 1
#define ERR 0
#define EOF_RET -1
int
get_next_node(FILE *ifile, int *nid, unsigned long *nr_free)
{
char line[LINE_MAX];
char node[FLDLEN], zone[FLDLEN];
unsigned long free_pages[MAX_ORDER];
int order, current_node = -1;
for (order = 0; order < MAX_ORDER; order++)
nr_free[order] = 0;
/*
* Read the file one line at a time until we find the next
* "Normal" zone or reach EOF
*/
while (1) {
long cur_pos;
if ((cur_pos = ftell(ifile)) < 0) {
log_err("ftell on buddyinfo failed (%s)", strerror(errno));
return ERR;
}
if (fgets(line, sizeof(line), ifile) == NULL) {
if (feof(ifile)) {
rewind(ifile);
return EOF_RET;
}
log_err("fgets(): %s",
strerror(ferror(ifile)));
return ERR;
}
if (!scan_buddyinfo(line, node, zone, free_pages)) {
log_err("invalid input: %s", line);
return ERR;
}
if (sscanf(node, "%d", nid) <= 0) {
log_err("invalid input: %s", node);
return ERR;
}
/*
* Accumulate free pages infor for just the current node
*/
if (current_node == -1)
current_node = *nid;
if (*nid != current_node) {
if (fseek(ifile, cur_pos, SEEK_SET) < 0) {
log_err("fseek on buddyinfo failed (%s)", strerror(errno));
return ERR;
}
break;
}
/* Skip DMA zone if needed */
if (skip_dmazone && strncmp(zone, "DMA", FLDLEN) == 0)
continue;
/* Add up free page info for each order */
for (order = 0; order < MAX_ORDER; order++)
nr_free[order] += free_pages[order];
}
*nid = current_node;
return NO_ERR;
}
/*
* Compute the number of base pages tied up in hugepages.
*
* Return values:
* -1 Failed to read hugepages info
* >=0 Percentage change in number of hugepages since last update
*/
int
update_hugepages()
{
DIR *dp;
struct dirent *ep;
unsigned long newhpages = 0;
int rc = -1;
dp = opendir(HUGEPAGESINFO);
if (dp == NULL)
return rc;
while (((ep = readdir(dp)) != NULL) && (ep->d_type == DT_DIR)) {
FILE *fp;
long pages, psize;
char tmpstr[312];
/* Check if it is one of the hugepages dir */
if (strstr(ep->d_name, "hugepages-") == NULL)
continue;
snprintf(tmpstr, sizeof(tmpstr), "%s/%s/nr_hugepages",
HUGEPAGESINFO, ep->d_name);
fp = fopen(tmpstr, "r");
if (fp == NULL)
continue;
if (fgets(tmpstr, sizeof(tmpstr), fp) != NULL) {
sscanf(tmpstr, "%ld", &pages);
sscanf(ep->d_name, "hugepages-%ldkB", &psize);
newhpages += pages * psize / base_psize;
}
fclose(fp);
}
if (newhpages) {
unsigned long tmp;
tmp = abs(newhpages - total_hugepages);
/*
* If number of hugepages changes from 0 to a
* positive number, percentage calculation will
* fail. Set the percentage to a high number
*/
if (total_hugepages == 0)
rc = INT_MAX;
else
rc = (tmp*100)/total_hugepages;
}
/*
* If number of hugepages changes to 0, that would be
* a 100% change
*/
else if (total_hugepages)
rc = 100;
else
rc = 0;
total_hugepages = newhpages;
closedir(dp);
return rc;
}
/*
* Parse watermarks and zone_managed_pages values from /proc/zoneinfo
*/
#define ZONE_MIN "min"
#define ZONE_LOW "low"
#define ZONE_HIGH "high"
#define ZONE_MNGD "managed"
#define ZONE_PGST "pagesets"
int
update_zone_watermarks()
{
FILE *fp = NULL;
size_t len = 256;
char *line = malloc(len);
int current_node = -1;
fp = fopen(ZONEINFO, "r");
if (!fp)
return 0;
while ((fgets(line, len, fp) != NULL)) {
if (strncmp(line, "Node", 4) == 0) {
char node[FLDLEN], zone[FLDLEN], zone_name[FLDLEN];
int nid;
unsigned long min, low, high, managed;
if (sscanf(line, "%s %d, %s %8s\n", node, &nid, zone, zone_name) <= 0)
goto out;
if ((current_node == -1) || (current_node != nid)) {
current_node = nid;
min_wmark[nid] = low_wmark[nid] = 0;
high_wmark[nid] = managed_pages[nid] = 0;
}
/*
* Add up watermarks and managed pages for all
* zones. x86 and x86-64 reserve memory in DMA
* zone for use by I/O primarily. This memory should
* not be taken into account for free memory
* management. ARM on the other hand maps the
* first 1G of memory into DMA zone and then
* continues mapping into DMA32 and Normal zones.
* Ignore pages in DMA zone for x86 and x86-64.
*/
if (!skip_dmazone || (strncmp("DMA", zone_name, FLDLEN) != 0)) {
/*
* We found the normal zone. Now look for
* line "pages free"
*/
if (fgets(line, len, fp) == NULL)
goto out;
while (1) {
unsigned long val;
char name[256];
if (fgets(line, len, fp) == NULL)
goto out;
if (sscanf(line, "%s %lu\n", name, &val) <= 0)
goto out;
if (strncmp(name, ZONE_MIN, sizeof(ZONE_MIN)) == 0)
min = val;
if (strncmp(name, ZONE_LOW, sizeof(ZONE_LOW)) == 0)
low = val;
if (strncmp(name, ZONE_HIGH, sizeof(ZONE_HIGH)) == 0)
high = val;
if (strncmp(name, ZONE_MNGD, sizeof(ZONE_MNGD)) == 0)
managed = val;
if (strncmp(name, ZONE_PGST, sizeof(ZONE_PGST)) == 0)
break;
}
min_wmark[nid] += min;
low_wmark[nid] += low;
high_wmark[nid] += high;
managed_pages[nid] += managed;
}
}
}
out:
free(line);
fclose(fp);
return 0;
}
/*
* When kernel computes the gap between low and high watermarks
* using watermark scale factor, it computes a percentage of
* total memory on the system. This works when most of the
* moemory is reclaimable and subject to watermarks. On systems
* that allocate very large percentage of memory to hugepages,
* this results in kernel computing watermarks that are just
* too high for the remaining memory that is truly subject to
* reclamation. Rescale max wsf down so kernel will end up
* computing watermarks that are more in line with real
* available memory.
*/
void
rescale_maxwsf()
{
unsigned long reclaimable_pages, total_managed = 0;
unsigned long gap, new_wsf;
int i;
if (total_hugepages == 0)
return;
for (i = 0; i < MAX_NUMANODES; i++)
total_managed += managed_pages[i];
if (total_managed == 0) {
log_info(1, "Number of managed pages is 0");
return;
}
/*
* Compute what the gap would be if maxwsf is applied to
* just reclaimable memory
*/
reclaimable_pages = total_managed - total_hugepages;
gap = (reclaimable_pages * maxwsf)/10000;
/*
* Now compute WSF needed for same gap if all memory was taken
* into account
*/
new_wsf = (gap * 10000)/total_managed;
if ((new_wsf > 9) && (new_wsf < 1000))
mywsf = new_wsf;
else
log_warn("Failed to compute reasonable WSF, %ld, total pages %ld, reclaimable pages %ld", new_wsf, total_managed, reclaimable_pages);
}
/*
* Get the number of pages stolen by kswapd from /proc/vmstat.
*/
unsigned long
no_pages_reclaimed()
{
FILE *fp = NULL;
size_t len = 100;
char *line = malloc(len);
unsigned long val, reclaimed;
char desc[100];
fp = fopen(VMSTAT, "r");
if (!fp)
return 0;
total_cache_pages = reclaimed = 0;
while ((fgets(line, len, fp) != NULL)) {
if (sscanf(line, "%s %lu\n", desc, &val) <= 0)
break;
if (strcmp(desc, "pgsteal_kswapd") == 0)
reclaimed += val;
if (strcmp(desc, "pgsteal_kswapd_normal") == 0)
reclaimed += val;
if (strcmp(desc, "pgsteal_kswapd_movable") == 0)
reclaimed += val;
if (strcmp(desc, "nr_inactive_file") == 0)
total_cache_pages += val;
if (strcmp(desc, "nr_inactive_anon") == 0)
total_cache_pages += val;
}
free(line);
fclose(fp);
return reclaimed;
}
/*
* Dynamically rescale the watermark_scale_factor to make kswapd
* more aggressive
*/
void
rescale_watermarks(int scale_up)
{
int fd, i, count;
unsigned long scaled_watermark, frac_free;
char scaled_wmark[20], *c;
unsigned long total_managed = 0;
unsigned long mmark, lmark, hmark;
for (i = 0; i < MAX_NUMANODES; i++)
total_managed += managed_pages[i];
/*
* Hugepages should not be taken into account for watermark
* calculations since they are not reclaimable
*/
total_managed -= total_hugepages;
if (total_managed == 0) {
log_info(1, "Number of managed non-huge pages is 0");
return;
}
/*
* Fraction of managed pages currently free
*/
frac_free = (total_free_pages*1000)/total_managed;
/*
* Get the current watermark scale factor.
*/
if ((fd = open(RESCALE_WMARK, O_RDONLY)) == -1) {
log_err("Failed to open "RESCALE_WMARK" (%s)", strerror(errno));
return;
}
if (read(fd, scaled_wmark, sizeof(scaled_wmark)) < 0) {
log_err("Failed to read from "RESCALE_WMARK" (%s)", strerror(errno));
goto out;
}
close(fd);
/* strip off trailing CR from current watermark scale factor */
c = index(scaled_wmark, '\n');
*c = 0;
/*
* Compute average high and low watermarks across nodes
*/
lmark = hmark = count = 0;
for (i = 0; i < MAX_NUMANODES; i++) {
lmark += low_wmark[i];
hmark += high_wmark[i];
if (low_wmark[i] != 0)
count++;
}
lmark = lmark/count;
hmark = hmark/count;
/*
* If memory pressure is easing, scale watermarks back and let
* kernel reclaim pages at its natural rate. If number of free
* pages is below halfway between low and high watermarks, back
* off watermark scale factor 10% at a time
*/
if (!scale_up) {
if (total_free_pages < ((lmark+hmark)/2))
scaled_watermark = (atoi(scaled_wmark) * 9)/10;
else
scaled_watermark = ((unsigned long)(1000 - frac_free)/10)*10;
/*
* Make sure new watermark scale factor does not end up
* higher than current value accidentally
*/
if (scaled_watermark >= atoi(scaled_wmark))
scaled_watermark = (atoi(scaled_wmark) * 9)/10;
} else {
/*
* Determine how urgent the situation is regarding
* remaining free pages. If free pages are already
* below high watermark, check if there are enough
* pages potentially available in buffer cache.
*/
if (total_free_pages < hmark) {
if (total_cache_pages > (hmark - total_free_pages)) {
/*
* There are pages available to harvest.
* Aggressive reclaim is appropriate for
* this situation. Urgency is determined by
* the percentage of managed pages still
* available. As this number gets lower,
* watermark scale factor needs to go up
* to make kswapd reclaim pages more
* aggressively. Compute scale factor as
* multiples of 10.
*/
scaled_watermark = ((unsigned long)(1000 - frac_free)/10)*10;
if (scaled_watermark == 0)
return;
} else {
/*
* We are running low on free pages but
* there are not enough pages available to
* reclaim either, so no need to get
* overly aggressive. Be only half as
* aggressive as the case where pages are
* available to reclaim
*/
scaled_watermark = ((unsigned long)(1000 - frac_free)/20)*10;
if (scaled_watermark == 0)
return;
}
} else {
/*
* System is not in dire situation at this time yet.
* Free pages are expected to approach high
* watermark soon though. If there are lots of
* reclaimable pages available, start semi-aggressive
* reclamation. If not, raise watermark scale factor
* but only by 10% if above 100 otherwise by 20%
*/
if (total_cache_pages > (total_free_pages - hmark)) {
scaled_watermark = ((unsigned long)(1000 - frac_free)/20)*10;
if (scaled_watermark == 0)
return;
} else {
if (atoi(scaled_wmark) > 100)
scaled_watermark = (atoi(scaled_wmark) * 11)/10;
else
scaled_watermark = (atoi(scaled_wmark) * 12)/10;
}
}
/*
* Compare to current watermark scale factor. If it is
* the same as new scale factor, it means current setting
* is not working well enough already. Raise it by 10%
* instead.
*/
if (atoi(scaled_wmark) == scaled_watermark)
scaled_watermark = (scaled_watermark * 11)/10;
}
/*
* Highest possible value for watermark scaling factor is
* 1000. If current scale is already set to 1000, no point
* in updating it. Also make sure new value is at least the
* minimum allowed value.
*/
if (scaled_watermark > 1000)
scaled_watermark = 1000;
if (scaled_watermark < 10)
scaled_watermark = 10;
if (scaled_watermark > mywsf)
scaled_watermark = mywsf;
/*
* Before committing to the new higher value of wsf, make sure
* it will not cause low watermark to be raised above current
* number of free pages. If that were to happen OOM killer will
* step in immediately. Allow for at least 2% headroom over low
* watermark.
*/
if (scale_up) {
unsigned long threshold, loose_pages = total_free_pages +
total_cache_pages;
unsigned long new_lmark;
mmark = lmark = 0;
for (i = 0; i < MAX_NUMANODES; i++) {
mmark += min_wmark[i];
lmark += low_wmark[i];
}
/*
* Estimate the new low watermark if we were to increase
* WSF to this new value
*/
new_lmark = mmark +
((lmark-mmark)*scaled_watermark/atoi(scaled_wmark));
/*
* When low watermark gets raised, make sure there will
* still be enough free pages left for system to continue
* making progress. Use a headroom of 2% of currently
* available free pages. If the number of free pages is
* already below this threshold, setting this new wsf
* is very likely to kick OOM killer.
*/
threshold = new_lmark + total_free_pages * 1.02;
if (loose_pages <= threshold) {
/*
* See if we can raise wsf by 10%
*/
scaled_watermark = (atoi(scaled_wmark) * 11)/10;
new_lmark = mmark + ((lmark-mmark)*scaled_watermark/atoi(scaled_wmark));
threshold = new_lmark + total_free_pages * 1.02;
if (loose_pages <= threshold) {
log_info(2, "Not enough free pages to raise watermarks, free pages=%ld, reclaimable pages=%ld, new wsf=%ld, min=%ld, current low wmark=%ld, new projected low watermark=%ld", total_free_pages, total_cache_pages, scaled_watermark, mmark, lmark, new_lmark);
return;
}
}
}
if (atoi(scaled_wmark) == scaled_watermark) {
if (scaled_watermark == mywsf)
log_info(2, "At max WSF already (max WSF = %u)", mywsf);
return;
}
log_info(1, "Adjusting watermarks. Current watermark scale factor = %s", scaled_wmark);
if (dry_run)
goto out;
log_info(1, "New watermark scale factor = %ld", scaled_watermark);
sprintf(scaled_wmark, "%ld\n", scaled_watermark);
if ((fd = open(RESCALE_WMARK, O_WRONLY)) == -1) {
log_err("Failed to open "RESCALE_WMARK" (%s)", strerror(errno));
return;
}
if (write(fd, scaled_wmark, strlen(scaled_wmark)) < 0)
log_err("Failed to write to "RESCALE_WMARK" (%s)", strerror(errno));
out:
close(fd);
}
static inline unsigned long
get_msecs(struct timespec *spec)
{
if (!spec)
return -1;
return (unsigned long)((spec->tv_sec * 1000) + (spec->tv_nsec / 1000));
}
/*
* check_permissions() - Check all required permissions for this program to
* run successfully
*/
static int
check_permissions(void)
{
int fd;
char tmpstr[40];
/*
* Make sure running kernel supports watermark_scale_factor file
*/
if ((fd = open(RESCALE_WMARK, O_RDONLY)) == -1) {
fprintf(stderr, "Can not open "RESCALE_WMARK" (%s)", strerror(errno));
return 0;
}
/* Can we write to this file */
if (read(fd, tmpstr, sizeof(tmpstr)) < 0) {
fprintf(stderr, "Can not read "RESCALE_WMARK" (%s)", strerror(errno));
return 0;
}
close(fd);
if ((fd = open(RESCALE_WMARK, O_WRONLY)) == -1) {
fprintf(stderr, "Can not open "RESCALE_WMARK" (%s)", strerror(errno));
return 0;
}
if (write(fd, tmpstr, strlen(tmpstr)) < 0) {
fprintf(stderr, "Can not write to "RESCALE_WMARK" (%s)", strerror(errno));
return 0;
}
close(fd);
return 1;
}
/*
* update_neg_dentry() - Update the limit for negative dentries based
* upon current system state
*
* Negative dentry limit is expressed as a percentage of total memory
* on the system. If a significant amount of memory on the system is
* allocated to hugepages, that percentage of total memory can be too
* high a number of pages tobe allowed to be consumed by negative
* dentries. To compensate for this, the percentage should be scaled
* down so the number of maximum pages allowed for negative dentries
* amounts to about the same percentage of non-hugepage memory pages.
* As an example, a system with 512GB of memory:
*
* 512GB = 134217728 4k pages
*
* If negative dentry limit was set to 1%, that would amount to
* 1342177 pages. Now let us allocate 448GB of this memory to
* hugepages leaving 64GB of base pages:
*
* 64GB = 16777216 4k pages
*
* If we still allowed 1342177 pages to be consumed by negative
* dentries, that would amount to 8% of reclaimable memory which
* is significantly higher than original intent. To keep in line with
* the original intent of allowing only 1% of reclaimable memory
* this percentage should be scaled down to .1 which then yields up
* to 134217 allowed to be consumed by negative dentries and
*
* (134217/16777216)*100 = 0.08%
*
* NOTE: /proc/sys/fs/negative-dentry-limit is expressed as fraction
* of 1000, so above value will be translated to 1 which will be
* 0.1%
*/
void
update_neg_dentry(bool init)
{
int fd;
/*
* bail out if this module is not enabled
*/
if (!neg_dentry_check_enabled)
return;
/*
* Set up negative dentry limit if functionality is supported on
* this kernel.
*/
if (access(NEG_DENTRY_LIMIT, F_OK) == 0) {
if ((fd = open(NEG_DENTRY_LIMIT, O_RDWR)) == -1) {
log_err("Failed to open "NEG_DENTRY_LIMIT" (%s)", strerror(errno));
} else {
/*
* Compute the value for negative dentry limit
* based upon just the reclaimable pages
*/
int val, i;
unsigned long reclaimable_pages, total_managed = 0;
char neg_dentry[LINE_MAX];
for (i = 0; i < MAX_NUMANODES; i++)
total_managed += managed_pages[i];
reclaimable_pages = total_managed - total_hugepages;
val = (reclaimable_pages * neg_dentry_pct)/total_managed;
/*
* This value should not be 0 since that would
* disallow cacheing of negative dentries. It
* also not be higher than 75 since that would
* allow most of the free memory to be consumed
* by negative dentries.
*/
if (val < 1)
val = 1;
if (val > MAX_NEGDENTRY)
val = MAX_NEGDENTRY;
snprintf(neg_dentry, sizeof(neg_dentry), "%u\n", val);
log_info(1, "Updating negative dentry limit to %s", neg_dentry);
if (write(fd, neg_dentry, strlen(neg_dentry)) < 0)
log_err("Failed to write to "NEG_DENTRY_LIMIT" (%s)", strerror(errno));
close(fd);
}
}
}
/*
* get_unmapped_pages()- count number of unmapped pages reported in
* /proc/kpagecount
*
* /proc/kpagecount reports a current mapcount as a 64-bit integer for
* each PFN on the system. It includes PFN that may not have a physical
* page backing them. /proc/kpageflags reports current flags for each
* PFN including flag for whether a physical page is present at that
* PFN. This flag can be used to identify PFNs that do not have a
* backing pahysical page
*/
long
get_unmapped_pages()
{
#define BATCHSIZE 8192
int fd1, fd2;
long pagecnt[BATCHSIZE/sizeof(long)];
unsigned long pageflg[BATCHSIZE/sizeof(long)];
ssize_t inbytes1, inbytes2;
unsigned long count, unmapped_pages = 0;
if ((fd1 = open(KPAGECOUNT, O_RDONLY)) == -1) {
log_err("Error opening kpagecount");
return -1;
}
if ((fd2 = open(KPAGEFLAGS, O_RDONLY)) == -1) {
log_err("Error opening kpageflags");
return -1;
}
inbytes1 = read(fd1, pagecnt, BATCHSIZE);
inbytes2 = read(fd2, pageflg, BATCHSIZE);
count = inbytes1/sizeof(long);
while ((inbytes1 > 0) && (inbytes2 > 0)) {
unsigned long i;
i = 0;
while (i < count) {
/*
* Skip PFN not backed by physical page
*/
if ((pageflg[i]>>KPF_NOPAGE) & 1)
goto nextloop;
if ((pageflg[i]>>KPF_HWPOISON) & 1)
goto nextloop;
if ((pageflg[i]>>KPF_OFFLINE) & 1)
goto nextloop;
if ((pageflg[i]>>KPF_SLAB) & 1)
goto nextloop;
if ((pageflg[i]>>KPF_BUDDY) & 1)
goto nextloop;
if ((pageflg[i]>>KPF_PGTABLE) & 1)
goto nextloop;
/*
* Pages not mapped in are free unless
* they are reserved like hugetlb pages
*/
if ((pagecnt[i] == 0) &&
!((pageflg[i]>>KPF_HUGE) & 1))
unmapped_pages++;
nextloop:
i++;
}
inbytes1 = read(fd2, pageflg, BATCHSIZE);
inbytes2 = read(fd1, pagecnt, BATCHSIZE);
count = inbytes2/sizeof(long);
}
if ((inbytes1 < 0) || (inbytes2 < 0)) {