aboutsummaryrefslogtreecommitdiff
path: root/hugeadm.c
blob: 403193fc376d30ef9f2cdddc1808fbf9e40204de (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
/***************************************************************************
 *   User front end for using huge pages Copyright (C) 2008, IBM           *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the Lesser GNU General Public License as        *
 *   published by the Free Software Foundation; either version 2.1 of the  *
 *   License, or at your option) any later version.                        *
 *                                                                         *
 *   This program 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 Lesser General Public License for more details.                   *
 *                                                                         *
 *   You should have received a copy of the Lesser GNU General Public      *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

/*
 * hugeadm is designed to make an administrators life simpler, to automate
 * and simplify basic system configuration as it relates to hugepages.  It
 * is designed to help with pool and mount configuration.
 */

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <mntent.h>
#include <unistd.h>
#include <grp.h>
#include <pwd.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <sys/swap.h>
#include <sys/wait.h>

#define _GNU_SOURCE /* for getopt_long */
#include <unistd.h>
#include <getopt.h>

#define REPORT_UTIL "hugeadm"
#define REPORT(level, prefix, format, ...)                                    \
	do {                                                                  \
		if (verbose_level >= level)                                   \
			fprintf(stderr, "hugeadm:" prefix ": " format,       \
				##__VA_ARGS__);                               \
	} while (0);

#include "libhugetlbfs_internal.h"
#include "hugetlbfs.h"

extern int optind;
extern char *optarg;

#define OPTION(opts, text)	fprintf(stderr, " %-25s  %s\n", opts, text)
#define CONT(text) 		fprintf(stderr, " %-25s  %s\n", "", text)

#define MOUNT_DIR "/var/lib/hugetlbfs"
#define OPT_MAX 4096

#define PROCMOUNTS "/proc/mounts"
#define PROCHUGEPAGES_MOVABLE "/proc/sys/vm/hugepages_treat_as_movable"
#define FS_NAME "hugetlbfs"
#define MIN_COL 20
#define MAX_SIZE_MNTENT (64 + PATH_MAX + 32 + 128 + 2 * sizeof(int))
#define FORMAT_LEN 20

#define SWAP_FREE "SwapFree:"
#define SWAP_TOTAL "SwapTotal:"

void print_usage()
{
	fprintf(stderr, "hugeadm [options]\n");
	fprintf(stderr, "options:\n");

	OPTION("--list-all-mounts", "List all current hugetlbfs mount points");
	OPTION("--pool-list", "List all pools");
	OPTION("--hard", "specified with --pool-pages-min to make");
	CONT("multiple attempts at adjusting the pool size to the");
	CONT("specified count on failure");
	OPTION("--pool-pages-min <size>:[+|-]<count>", "");
	CONT("Adjust pool 'size' lower bound");
	OPTION("--pool-pages-max <size>:[+|-]<count>", "");
	CONT("Adjust pool 'size' upper bound");
	OPTION("--add-temp-swap", "Specified with --pool-pages-min to create");
	CONT("temporary swap space for the duration of the pool resize");
	OPTION("--enable-zone-movable", "Use ZONE_MOVABLE for huge pages");
	OPTION("--disable-zone-movable", "Do not use ZONE_MOVABLE for huge pages");
	OPTION("--create-mounts", "Creates a mount point for each available");
	CONT("huge page size on this system under /var/lib/hugetlbfs");
	OPTION("--create-user-mounts <user>", "");
	CONT("Creates a mount point for each available huge");
	CONT("page size under /var/lib/hugetlbfs/<user>");
	CONT("usable by user <user>");
	OPTION("--create-group-mounts <group>", "");
	CONT("Creates a mount point for each available huge");
	CONT("page size under /var/lib/hugetlbfs/<group>");
	CONT("usable by group <group>");
	OPTION("--create-global-mounts", "");
	CONT("Creates a mount point for each available huge");
	CONT("page size under /var/lib/hugetlbfs/global");
	CONT("usable by anyone");

	OPTION("--page-sizes", "Display page sizes that a configured pool");
	OPTION("--page-sizes-all",
			"Display page sizes support by the hardware");
	OPTION("--dry-run", "Print the equivalent shell commands for what");
	CONT("the specified options would have done without");
	CONT("taking any action");

	OPTION("--explain", "Gives a overview of the status of the system");
	CONT("with respect to huge page availability");

	OPTION("--verbose <level>, -v", "Increases/sets tracing levels");
	OPTION("--help, -h", "Prints this message");
}

int opt_dry_run = 0;
int opt_hard = 0;
int opt_movable = -1;
int opt_temp_swap = 0;
int verbose_level = VERBOSITY_DEFAULT;

void setup_environment(char *var, char *val)
{
	setenv(var, val, 1);
	DEBUG("%s='%s'\n", var, val);

	if (opt_dry_run)
		printf("%s='%s'\n", var, val);
}

/* Enable/disable allocation of hugepages from ZONE_MOVABLE */
void setup_zone_movable(int able)
{
	DEBUG("Setting %s to %d\n", PROCHUGEPAGES_MOVABLE, able);

	/* libhugetlbfs reports any error that occurs */
	file_write_ulong(PROCHUGEPAGES_MOVABLE, (unsigned long)able);

	if (opt_dry_run)
		printf("echo %d > %s\n", able, PROCHUGEPAGES_MOVABLE);
}

void verbose_init(void)
{
	char *env;

	env = getenv("HUGETLB_VERBOSE");
	if (env)
		verbose_level = atoi(env);
	env = getenv("HUGETLB_DEBUG");
	if (env)
		verbose_level = VERBOSITY_MAX;
}

void verbose(char *which)
{
	int new_level;

	if (which) {
		new_level = atoi(which);
		if (new_level < 0 || new_level > 99) {
			ERROR("%d: verbosity out of range 0-99\n",
				new_level);
			exit(EXIT_FAILURE);
		}
	} else {
		new_level = verbose_level + 1;
		if (new_level == 100) {
			WARNING("verbosity limited to 99\n");
			new_level--;
		}
	}
	verbose_level = new_level;
}

void verbose_expose(void)
{
	char level[3];

	if (verbose_level == 99) {
		setup_environment("HUGETLB_DEBUG", "yes");
	}
	snprintf(level, sizeof(level), "%d", verbose_level);
	setup_environment("HUGETLB_VERBOSE", level);
}

/*
 * getopts return values for options which are long only.
 */
#define LONG_POOL		('p' << 8)
#define LONG_POOL_LIST		(LONG_POOL|'l')
#define LONG_POOL_MIN_ADJ	(LONG_POOL|'m')
#define LONG_POOL_MAX_ADJ	(LONG_POOL|'M')

#define LONG_MOVABLE		('z' << 8)
#define LONG_MOVABLE_ENABLE	(LONG_MOVABLE|'e')
#define LONG_MOVABLE_DISABLE	(LONG_MOVABLE|'d')

#define LONG_HARD		('h' << 8)
#define LONG_ADD_TEMP_SWAP	('s' << 8)

#define LONG_PAGE	('P' << 8)
#define LONG_PAGE_SIZES	(LONG_PAGE|'s')
#define LONG_PAGE_AVAIL	(LONG_PAGE|'a')

#define LONG_MOUNTS			('m' << 8)
#define LONG_CREATE_MOUNTS		(LONG_MOUNTS|'C')
#define LONG_CREATE_USER_MOUNTS		(LONG_MOUNTS|'U')
#define LONG_CREATE_GROUP_MOUNTS	(LONG_MOUNTS|'g')
#define LONG_CREATE_GLOBAL_MOUNTS	(LONG_MOUNTS|'G')
#define LONG_LIST_ALL_MOUNTS		(LONG_MOUNTS|'A')

#define LONG_EXPLAIN	('e' << 8)

#define MAX_POOLS	32

static int cmpsizes(const void *p1, const void *p2)
{
	return ((struct hpage_pool *)p1)->pagesize >
			((struct hpage_pool *)p2)->pagesize;
}

void pool_list(void)
{
	struct hpage_pool pools[MAX_POOLS];
	int pos;
	int cnt;

	cnt = hpool_sizes(pools, MAX_POOLS);
	if (cnt < 0) {
		ERROR("unable to obtain pools list");
		exit(EXIT_FAILURE);
	}
	qsort(pools, cnt, sizeof(pools[0]), cmpsizes);

	printf("%10s %8s %8s %8s %8s\n",
		"Size", "Minimum", "Current", "Maximum", "Default");
	for (pos = 0; cnt--; pos++) {
		printf("%10ld %8ld %8ld %8ld %8s\n", pools[pos].pagesize,
			pools[pos].minimum, pools[pos].size,
			pools[pos].maximum, (pools[pos].is_default) ? "*" : "");
	}
}

struct mount_list
{
	struct mntent entry;
	char data[MAX_SIZE_MNTENT];
	struct mount_list *next;
};

void print_mounts(struct mount_list *current, int longest)
{
	char format_str[FORMAT_LEN];

	snprintf(format_str, FORMAT_LEN, "%%-%ds %%s\n", longest);
	printf(format_str, "Mount Point", "Options");
	while (current) {
		printf(format_str, current->entry.mnt_dir,
				   current->entry.mnt_opts);
		current = current->next;
	}
}

/*
 * collect_active_mounts returns a list of active hugetlbfs
 * mount points, and, if longest is not NULL, the number of
 * characters in the longest mount point to ease output
 * formatting.  Caller is expected to free the list of mounts.
 */
struct mount_list *collect_active_mounts(int *longest)
{
	FILE *mounts;
	struct mount_list *list, *current, *previous = NULL;
	int length;

	/* First try /proc/mounts, then /etc/mtab */
	mounts = setmntent(PROCMOUNTS, "r");
	if (!mounts) {
		mounts = setmntent(MOUNTED, "r");
		if (!mounts) {
			ERROR("unable to open %s or %s for reading",
				PROCMOUNTS, MOUNTED);
			exit(EXIT_FAILURE);
		}
	}

	list = malloc(sizeof(struct mount_list));
	if (!list) {
		ERROR("out of memory");
		exit(EXIT_FAILURE);
	}

	list->next = NULL;
	current = list;
	while (getmntent_r(mounts, &(current->entry), current->data, MAX_SIZE_MNTENT)) {
		if (strcasecmp(current->entry.mnt_type, FS_NAME) == 0) {
			length = strlen(current->entry.mnt_dir);
			if (longest && length > *longest)
				*longest = length;

			current->next = malloc(sizeof(struct mount_list));
			if (!current->next) {
				ERROR("out of memory");
				exit(EXIT_FAILURE);
			}
			previous = current;
			current = current->next;
			current->next = NULL;
		}
	}

	endmntent(mounts);

	if (previous) {
		free(previous->next);
		previous->next = NULL;
		return list;
	}
	return NULL;
}

void mounts_list_all(void)
{
	struct mount_list *list, *previous;
	int longest = MIN_COL;

	list = collect_active_mounts(&longest);

	if (!list) {
		ERROR("No hugetlbfs mount points found\n");
		return;
	}

	print_mounts(list, longest);

	while (list) {
		previous = list;
		list = list->next;
		free(previous);
	}
}

int make_dir(char *path, mode_t mode, uid_t uid, gid_t gid)
{
	struct passwd *pwd;
	struct group *grp;

	if (opt_dry_run) {
		pwd = getpwuid(uid);
		grp = getgrgid(gid);
		printf("if [ ! -e %s ]\n", path);
		printf("then\n");
		printf(" mkdir %s\n", path);
		printf(" chown %s:%s %s\n", pwd->pw_name, grp->gr_name, path);
		printf(" chmod %o %s\n", mode, path);
		printf("fi\n");
		return 0;
	}

	if (mkdir(path, mode)) {
		if (errno != EEXIST) {
			ERROR("Unable to create dir %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}
	} else {
		if (chown(path, uid, gid)) {
			ERROR("Unable to change ownership of %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}

		if (chmod(path, mode)) {
			ERROR("Unable to change permission on %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}
	}

	return 0;
}

/**
 * ensure_dir will build the entire directory structure up to and
 * including path, all directories built will be owned by
 * user:group and permissions will be set to mode.
 */
int ensure_dir(char *path, mode_t mode, uid_t uid, gid_t gid)
{
	char *idx;

	if (!path || strlen(path) == 0)
		return 0;

	idx = strchr(path + 1, '/');

	do {
		if (idx)
			*idx = '\0';

		if (make_dir(path, mode, uid, gid))
			return 1;

		if (idx) {
			*idx = '/';
			idx++;
		}
	} while ((idx = strchr(idx, '/')) != NULL);

	if (make_dir(path, mode, uid, gid))
		return 1;

	return 0;
}

int check_if_already_mounted(struct mount_list *list, char *path)
{
	while (list) {
		if (!strcmp(list->entry.mnt_dir, path))
			return 1;
		list = list->next;
	}
	return 0;
}

int mount_dir(char *path, char *options, mode_t mode, uid_t uid, gid_t gid)
{
	struct passwd *pwd;
	struct group *grp;
	struct mntent entry;
	FILE *mounts;
	struct mount_list *list, *previous;

	list = collect_active_mounts(NULL);

	if (list && check_if_already_mounted(list, path)) {
		WARNING("Directory %s is already mounted.\n", path);

		while (list) {
			previous = list;
			list = list->next;
			free(previous);
		}
		return 0;
	}

	while (list) {
		previous = list;
		list = list->next;
		free(previous);
	}

	if (opt_dry_run) {
		pwd = getpwuid(uid);
		grp = getgrgid(gid);
		printf("mount -t %s none %s -o %s\n", FS_NAME,
			path, options);
		printf("chown %s:%s %s\n", pwd->pw_name, grp->gr_name,
			path);
		printf("chmod %o %s\n", mode, path);
	} else {
		if (mount("none", path, FS_NAME, 0, options)) {
			ERROR("Unable to mount %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}

		mounts = setmntent(MOUNTED, "a+");
		if (mounts) {
			entry.mnt_fsname = FS_NAME;
			entry.mnt_dir = path;
			entry.mnt_type = FS_NAME;
			entry.mnt_opts = options;
			entry.mnt_freq = 0;
			entry.mnt_passno = 0;
			if (addmntent(mounts, &entry))
				WARNING("Unable to add entry %s to %s, error: %s\n",
					path, MOUNTED, strerror(errno));
			endmntent(mounts);
		} else {
			WARNING("Unable to open %s, error: %s\n",
				MOUNTED, strerror(errno));
		}

		if (chown(path, uid, gid)) {
			ERROR("Unable to change ownership of %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}

		if (chmod(path, mode)) {
			ERROR("Unable to set permissions on %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}
	}
	return 0;
}


void create_mounts(char *user, char *group, char *base, mode_t mode)
{
	struct hpage_pool pools[MAX_POOLS];
	char path[PATH_MAX];
	char options[OPT_MAX];
	int cnt, pos;
	struct passwd *pwd;
	struct group *grp;
	uid_t uid = 0;
	gid_t gid = 0;

	if (geteuid() != 0) {
		ERROR("Mounts can only be created by root\n");
		exit(EXIT_FAILURE);
	}

	if (user) {
		pwd = getpwnam(user);
		if (!pwd) {
			ERROR("Could not find specified user %s\n", user);
			exit(EXIT_FAILURE);
		}
		uid = pwd->pw_uid;
	} else if (group) {
		grp = getgrnam(group);
		if (!grp) {
			ERROR("Could not find specified group %s\n", group);
			exit(EXIT_FAILURE);
		}
		gid = grp->gr_gid;
	}

	if (ensure_dir(base,
		S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH, 0, 0))
		exit(EXIT_FAILURE);

	cnt = hpool_sizes(pools, MAX_POOLS);
	if (cnt < 0) {
		ERROR("Unable to obtain pools list\n");
		exit(EXIT_FAILURE);
	}

	for (pos=0; cnt--; pos++) {
		if (user)
			snprintf(path, PATH_MAX, "%s/%s/pagesize-%ld",
				base, user, pools[pos].pagesize);
		else if (group)
			snprintf(path, PATH_MAX, "%s/%s/pagesize-%ld",
				base, group, pools[pos].pagesize);
		else
			snprintf(path, PATH_MAX, "%s/pagesize-%ld",
				base, pools[pos].pagesize);
		snprintf(options, OPT_MAX, "pagesize=%ld",
				pools[pos].pagesize);
		if (ensure_dir(path, mode, uid, gid))
			exit(EXIT_FAILURE);

		if (mount_dir(path, options, mode, uid, gid))
			exit(EXIT_FAILURE);
	}
}

/**
 * check_swap shouldn't change the behavior of any of its
 * callers, it only prints a message to the user if something
 * is being done that might fail without swap available.  i.e.
 * resizing a huge page pool
 */
void check_swap()
{
	long swap_sz;
	long swap_total;

	swap_total = read_meminfo(SWAP_TOTAL);
	if (swap_total <= 0) {
		WARNING("There is no swap space configured, resizing hugepage pool may fail\n");
		WARNING("Use --add-temp-swap option to temporarily add swap during the resize\n");
		return;
	}

	swap_sz = read_meminfo(SWAP_FREE);
	/* meminfo keeps values in kb, but we use bytes for hpage sizes */
	swap_sz *= 1024;
	if (swap_sz <= gethugepagesize()) {
		WARNING("There is very little swap space free, resizing hugepage pool may fail\n");
		WARNING("Use --add-temp-swap option to temporarily add swap during the resize\n");
	}
}

void add_temp_swap()
{
	char path[PATH_MAX];
	char file[PATH_MAX];
	char mkswap_cmd[PATH_MAX];
	FILE *f;
	char *buf;
	long swap_size;
	long pid;
	int ret;

	if (geteuid() != 0) {
		ERROR("Swap can only be manipulated by root\n");
		exit(EXIT_FAILURE);
	}

	pid = getpid();
	snprintf(path, PATH_MAX, "%s/swap/temp", MOUNT_DIR);
	snprintf(file, PATH_MAX, "%s/swapfile-%ld", path, pid);


	if (ensure_dir(path, S_IRWXU | S_IRGRP | S_IXGRP, 0, 0))
		exit(EXIT_FAILURE);

	f = fopen(file, "wx");
	if (!f) {
		WARNING("Couldn't open %s: %s\n", file, strerror(errno));
		opt_temp_swap = 0;
		return;
	}

	/* swapsize is 5 hugepages */
	swap_size = gethugepagesize() * 5;
	buf = malloc(swap_size);
	memset(buf, 0, swap_size);
	fwrite(buf, sizeof(char), swap_size, f);
	free(buf);
	fclose(f);

	snprintf(mkswap_cmd, PATH_MAX, "mkswap %s", file);
	ret = system(mkswap_cmd);
	if (WIFSIGNALED(ret)) {
		WARNING("Call to mkswap failed\n");
		opt_temp_swap = 0;
		return;
	} else if (WIFEXITED(ret)) {
		ret = WEXITSTATUS(ret);
		if (ret) {
			WARNING("Call to mkswap failed\n");
			opt_temp_swap = 0;
			return;
		}
	}

	DEBUG("swapon %s\n", file);
	if (swapon(file, 0)) {
		WARNING("swapon on %s failed: %s\n", file, strerror(errno));
		opt_temp_swap = 0;
	}
}

void rem_temp_swap() {
	char file[PATH_MAX];

	snprintf(file, PATH_MAX, "%s/swap/temp/swapfile", MOUNT_DIR);
	if (swapoff(file))
		WARNING("swapoff on %s failed: %s\n", file, strerror(errno));
	remove(file);
	DEBUG("swapoff %s\n", file);
}

enum {
	POOL_MIN,
	POOL_MAX,
	POOL_BOTH,
};

static long value_adjust(char *adjust_str, long base)
{
	long adjust;
	char *iter;

	/* Convert and validate the adjust. */
	adjust = strtol(adjust_str, &iter, 0);
	if (*iter) {
		ERROR("%s: invalid adjustment\n", adjust_str);
		exit(EXIT_FAILURE);
	}

	if (adjust_str[0] != '+' && adjust_str[0] != '-')
		base = 0;

	/* Ensure we neither go negative nor exceed LONG_MAX. */
	if (adjust < 0 && -adjust > base) {
		adjust = -base;
	}
	if (adjust > 0 && (base + adjust) < base) {
		adjust = LONG_MAX - base;
	}
	base += adjust;

	return base;
}


void pool_adjust(char *cmd, unsigned int counter)
{
	struct hpage_pool pools[MAX_POOLS];
	int pos;
	int cnt;

	char *iter = NULL;
	char *page_size_str = NULL;
	char *adjust_str = NULL;
	long page_size;

	unsigned long min;
	unsigned long min_orig;
	unsigned long max;
	unsigned long last_pool_value;

	/* Extract the pagesize and adjustment. */
	page_size_str = strtok_r(cmd, ":", &iter);
	if (page_size_str)
		adjust_str = strtok_r(NULL, ":", &iter);

	if (!page_size_str || !adjust_str) {
		ERROR("%s: invalid resize specificiation\n", cmd);
		exit(EXIT_FAILURE);
	}
	INFO("page_size<%s> adjust<%s> counter<%d>\n",
					page_size_str, adjust_str, counter);

	/* Convert and validate the page_size. */
	page_size = parse_page_size(page_size_str);

	cnt = hpool_sizes(pools, MAX_POOLS);
	if (cnt < 0) {
		ERROR("unable to obtain pools list");
		exit(EXIT_FAILURE);
	}
	for (pos = 0; cnt--; pos++) {
		if (pools[pos].pagesize == page_size)
			break;
	}
	if (cnt < 0) {
		ERROR("%s: unknown page size\n", page_size_str);
		exit(EXIT_FAILURE);
	}

	min_orig = min = pools[pos].minimum;
	max = pools[pos].maximum;

	if (counter == POOL_BOTH) {
		min = value_adjust(adjust_str, min);
		max = min;
	} else if (counter == POOL_MIN) {
		min = value_adjust(adjust_str, min);
		if (min > max)
			max = min;
	} else {
		max = value_adjust(adjust_str, max);
		if (max < min)
			min = max;
	}

	INFO("%ld, %ld -> %ld, %ld\n", pools[pos].minimum, pools[pos].maximum,
		min, max);

	if ((pools[pos].maximum - pools[pos].minimum) < (max - min)) {
		INFO("setting HUGEPAGES_OC to %ld\n", (max - min));
		set_huge_page_counter(page_size, HUGEPAGES_OC, (max - min));
	}

	if (opt_hard)
		cnt = 5;
	else
		cnt = -1;

	if (min > min_orig) {
		if (opt_temp_swap)
			add_temp_swap();
		check_swap();
	}

	INFO("setting HUGEPAGES_TOTAL to %ld\n", min);
	set_huge_page_counter(page_size, HUGEPAGES_TOTAL, min);
	get_pool_size(page_size, &pools[pos]);

	/* If we fail to make an allocation, retry if user requests */
	last_pool_value = pools[pos].minimum;
	while ((pools[pos].minimum != min) && (cnt > 0)) {
		/* Make note if progress is being made and sleep for IO */
		if (last_pool_value == pools[pos].minimum)
			cnt--;
		else
			cnt = 5;
		sleep(6);

		last_pool_value = pools[pos].minimum;
		INFO("Retrying allocation HUGEPAGES_TOTAL to %ld current %ld\n",
							min, pools[pos].minimum);
		set_huge_page_counter(page_size, HUGEPAGES_TOTAL, min);
		get_pool_size(page_size, &pools[pos]);
	}

	if ((min > min_orig) && opt_temp_swap)
		rem_temp_swap();

	/*
	 * HUGEPAGES_TOTAL is not guarenteed to check to exactly the figure
	 * requested should there be insufficient pages.  Check the new
	 * value and adjust HUGEPAGES_OC accordingly.
	 */
	if (pools[pos].minimum != min) {
		WARNING("failed to set pool minimum to %ld became %ld\n",
			min, pools[pos].minimum);
		min = pools[pos].minimum;
	}
	if (pools[pos].maximum != max) {
		INFO("setting HUGEPAGES_OC to %ld\n", (max - min));
		set_huge_page_counter(page_size, HUGEPAGES_OC, (max - min));
	}
}

void page_sizes(int all)
{
	struct hpage_pool pools[MAX_POOLS];
	int pos;
	int cnt;

	cnt = hpool_sizes(pools, MAX_POOLS);
	if (cnt < 0) {
		ERROR("unable to obtain pools list");
		exit(EXIT_FAILURE);
	}
	qsort(pools, cnt, sizeof(pools[0]), cmpsizes);

	for (pos = 0; cnt--; pos++) {
		if (all || (pools[pos].maximum &&
		    hugetlbfs_find_path_for_size(pools[pos].pagesize)))
			printf("%ld\n", pools[pos].pagesize);
	}
}

void explain()
{
	mounts_list_all();
	printf("\nHuge page pools:\n");
	pool_list();
	printf("\nHuge page sizes with configured pools:\n");
	page_sizes(0);
	check_swap();
	printf("\nNote: Permanent swap space should be preferred when dynamic "
		"huge page pools are used.\n");
}

int main(int argc, char** argv)
{
	int ops;
	int has_hugepages = kernel_has_hugepages();

	char opts[] = "+hdv";
	char base[PATH_MAX];
	char *opt_min_adj[MAX_POOLS], *opt_max_adj[MAX_POOLS];
	char *opt_user_mounts = NULL, *opt_group_mounts = NULL;
	int opt_list_mounts = 0, opt_pool_list = 0, opt_create_mounts = 0;
	int opt_global_mounts = 0, opt_pgsizes = 0, opt_pgsizes_all = 0;
	int opt_explain = 0, minadj_count = 0, maxadj_count = 0;
	int ret = 0, index = 0;
	struct option long_opts[] = {
		{"help",       no_argument, NULL, 'h'},
		{"verbose",    required_argument, NULL, 'v' },

		{"list-all-mounts", no_argument, NULL, LONG_LIST_ALL_MOUNTS},
		{"pool-list", no_argument, NULL, LONG_POOL_LIST},
		{"pool-pages-min", required_argument, NULL, LONG_POOL_MIN_ADJ},
		{"pool-pages-max", required_argument, NULL, LONG_POOL_MAX_ADJ},
		{"enable-zone-movable", no_argument, NULL, LONG_MOVABLE_ENABLE},
		{"disable-zone-movable", no_argument, NULL, LONG_MOVABLE_DISABLE},
		{"hard", no_argument, NULL, LONG_HARD},
		{"add-temp-swap", no_argument, NULL, LONG_ADD_TEMP_SWAP},
		{"create-mounts", no_argument, NULL, LONG_CREATE_MOUNTS},
		{"create-user-mounts", required_argument, NULL, LONG_CREATE_USER_MOUNTS},
		{"create-group-mounts", required_argument, NULL, LONG_CREATE_GROUP_MOUNTS},
		{"create-global-mounts", no_argument, NULL, LONG_CREATE_GLOBAL_MOUNTS},

		{"page-sizes", no_argument, NULL, LONG_PAGE_SIZES},
		{"page-sizes-all", no_argument, NULL, LONG_PAGE_AVAIL},
		{"dry-run", no_argument, NULL, 'd'},
		{"explain", no_argument, NULL, LONG_EXPLAIN},

		{0},
	};

	hugetlbfs_setup_debug();
	setup_mounts();
	verbose_init();

	ops = 0;
	while (ret != -1) {
		ret = getopt_long(argc, argv, opts, long_opts, &index);
		switch (ret) {
		case -1:
			break;

		case '?':
			print_usage();
			exit(EXIT_FAILURE);

		case 'h':
			print_usage();
			exit(EXIT_SUCCESS);

		case 'v':
			verbose(optarg);
			continue;

		case 'd':
			opt_dry_run = 1;
			continue;

		default:
			/* All other commands require hugepage support. */
			if (! has_hugepages) {
				ERROR("kernel does not support huge pages\n");
				exit(EXIT_FAILURE);
			}
		}
		switch (ret) {
		case -1:
			break;

		case LONG_HARD:
			opt_hard = 1;
			continue;

		case LONG_ADD_TEMP_SWAP:
			opt_temp_swap = 1;
			break;

		case LONG_LIST_ALL_MOUNTS:
			opt_list_mounts = 1;
			break;

		case LONG_POOL_LIST:
			opt_pool_list = 1;
			break;

		case LONG_POOL_MIN_ADJ:
			if (minadj_count == MAX_POOLS) {
				WARNING("Attempting to adjust an invalid "
					"pool or a pool multiple times, "
					"ignoring request: '%s'\n", optarg);
			} else {
				opt_min_adj[minadj_count++] = optarg;
			}
			break;

		case LONG_POOL_MAX_ADJ:
			if (! kernel_has_overcommit()) {
				ERROR("kernel does not support overcommit, "
					"max cannot be adjusted\n");
				exit(EXIT_FAILURE);
			}

			if (maxadj_count == MAX_POOLS) {
				WARNING("Attempting to adjust an invalid "
					"pool or a pool multiple times, "
					"ignoring request: '%s'\n", optarg);
			} else {
				opt_max_adj[maxadj_count++] = optarg;
			}
                        break;

		case LONG_MOVABLE_ENABLE:
			opt_movable = 1;
			break;

		case LONG_MOVABLE_DISABLE:
			opt_movable = 0;
			break;

		case LONG_CREATE_MOUNTS:
			opt_create_mounts = 1;
			break;

		case LONG_CREATE_USER_MOUNTS:
			opt_user_mounts = optarg;
			break;

		case LONG_CREATE_GROUP_MOUNTS:
			opt_group_mounts = optarg;
			break;

		case LONG_CREATE_GLOBAL_MOUNTS:
			opt_global_mounts = 1;
			break;

		case LONG_PAGE_SIZES:
			opt_pgsizes = 1;
			break;

		case LONG_PAGE_AVAIL:
			opt_pgsizes_all = 1;
			break;

		case LONG_EXPLAIN:
			opt_explain = 1;
			break;

		default:
			WARNING("unparsed option %08x\n", ret);
			ret = -1;
			break;
		}
		if (ret != -1)
			ops++;
	}

	verbose_expose();

	if (opt_list_mounts)
		mounts_list_all();

	if (opt_pool_list)
		pool_list();

	if (opt_movable != -1)
		setup_zone_movable(opt_movable);

	while (--minadj_count >= 0) {
		if (! kernel_has_overcommit())
			pool_adjust(opt_min_adj[minadj_count], POOL_BOTH);
		else
			pool_adjust(opt_min_adj[minadj_count], POOL_MIN);
	}

	while (--maxadj_count >=0)
			pool_adjust(opt_max_adj[maxadj_count], POOL_MAX);

	if (opt_create_mounts) {
		snprintf(base, PATH_MAX, "%s", MOUNT_DIR);
		create_mounts(NULL, NULL, base, S_IRWXU | S_IRWXG);
	}


	if (opt_user_mounts != NULL) {
		snprintf(base, PATH_MAX, "%s/user", MOUNT_DIR);
		create_mounts(optarg, NULL, base, S_IRWXU);
	}

	if (opt_group_mounts) {
		snprintf(base, PATH_MAX, "%s/group", MOUNT_DIR);
		create_mounts(NULL, optarg, base, S_IRWXG);
	}

	if (opt_global_mounts) {
		snprintf(base, PATH_MAX, "%s/global", MOUNT_DIR);
		create_mounts(NULL, NULL, base, S_IRWXU | S_IRWXG | S_IRWXO);
	}

	if (opt_pgsizes)
		page_sizes(0);

	if (opt_pgsizes_all)
		page_sizes(1);

	if (opt_explain)
		explain();

	index = optind;

	if ((argc - index) != 0 || ops == 0) {
		print_usage();
		exit(EXIT_FAILURE);
	}

	exit(EXIT_SUCCESS);
}