1 #! /usr/bin/env python3
2 # SPDX-License-Identifier: BSD-3-Clause
3 # Copyright (c) 2020 Microsoft Corporation
4 """Script to query and setup huge pages for DPDK applications."""
13 # Standard binary prefix
16 # systemd mount point for huge pages
17 HUGE_MOUNT = "/dev/hugepages"
21 '''Format memory size in kB into conventional format'''
22 logk = int(log2(kb) / 10)
23 suffix = BINARY_PREFIX[logk]
25 return '{}{}b'.format(int(kb / unit), suffix)
29 '''Convert memory size with suffix to kB'''
30 match = re.match(r'(\d+)([' + BINARY_PREFIX + r']?)$', arg.upper())
32 sys.exit('{} is not a valid page size'.format(arg))
33 num = float(match.group(1))
34 suffix = match.group(2)
36 return int(num / 1024)
37 idx = BINARY_PREFIX.find(suffix)
38 return int(num * (2**(idx * 10)))
42 '''Test if NUMA is necessary on this system'''
43 return os.path.exists('/sys/devices/system/node')
46 def get_hugepages(path):
47 '''Read number of reserved pages'''
48 with open(path + '/nr_hugepages') as nr_hugepages:
49 return int(nr_hugepages.read())
53 def set_hugepages(path, pages):
54 '''Write the number of reserved huge pages'''
55 filename = path + '/nr_hugepages'
57 with open(filename, 'w') as nr_hugepages:
58 nr_hugepages.write('{}\n'.format(pages))
59 except PermissionError:
60 sys.exit('Permission denied: need to be root!')
61 except FileNotFoundError:
62 filename = os.path.basename(path)
64 sys.exit('{} is not a valid system huge page size'.format(size))
67 def show_numa_pages():
68 '''Show huge page reservations on Numa system'''
69 print('Node Pages Size Total')
70 for numa_path in glob.glob('/sys/devices/system/node/node*'):
71 node = numa_path[29:] # slice after /sys/devices/system/node/node
72 path = numa_path + '/hugepages'
73 for hdir in os.listdir(path):
74 pages = get_hugepages(path + '/' + hdir)
76 kb = int(hdir[10:-2]) # slice out of hugepages-NNNkB
77 print('{:<4} {:<5} {:<6} {}'.format(node, pages,
79 fmt_memsize(pages * kb)))
82 def show_non_numa_pages():
83 '''Show huge page reservations on non Numa system'''
84 print('Pages Size Total')
85 path = '/sys/kernel/mm/hugepages'
86 for hdir in os.listdir(path):
87 pages = get_hugepages(path + '/' + hdir)
90 print('{:<5} {:<6} {}'.format(pages, fmt_memsize(kb),
91 fmt_memsize(pages * kb)))
95 '''Show existing huge page settings'''
103 '''Clear all existing huge page mappings'''
106 '/sys/devices/system/node/node*/hugepages/hugepages-*')
108 dirs = glob.glob('/sys/kernel/mm/hugepages/hugepages-*')
111 set_hugepages(path, 0)
114 def default_pagesize():
115 '''Get default huge page size from /proc/meminfo'''
116 with open('/proc/meminfo') as meminfo:
118 if line.startswith('Hugepagesize:'):
119 return int(line.split()[1])
123 def set_numa_pages(pages, hugepgsz, node=None):
124 '''Set huge page reservation on Numa system'''
126 nodes = ['/sys/devices/system/node/node{}/hugepages'.format(node)]
128 nodes = glob.glob('/sys/devices/system/node/node*/hugepages')
130 for node_path in nodes:
131 huge_path = '{}/hugepages-{}kB'.format(node_path, hugepgsz)
132 set_hugepages(huge_path, pages)
135 def set_non_numa_pages(pages, hugepgsz):
136 '''Set huge page reservation on non Numa system'''
137 path = '/sys/kernel/mm/hugepages/hugepages-{}kB'.format(hugepgsz)
138 set_hugepages(path, pages)
141 def reserve_pages(pages, hugepgsz, node=None):
142 '''Set the number of huge pages to be reserved'''
143 if node or is_numa():
144 set_numa_pages(pages, hugepgsz, node=node)
146 set_non_numa_pages(pages, hugepgsz)
149 def get_mountpoints():
150 '''Get list of where hugepage filesystem is mounted'''
152 with open('/proc/mounts') as mounts:
154 fields = line.split()
155 if fields[2] != 'hugetlbfs':
157 mounted.append(fields[1])
161 def mount_huge(pagesize, mountpoint):
162 '''Mount the huge TLB file system'''
163 if mountpoint in get_mountpoints():
164 print(mountpoint, "already mounted")
166 cmd = "mount -t hugetlbfs"
168 cmd += ' -o pagesize={}'.format(pagesize * 1024)
169 cmd += ' nodev ' + mountpoint
173 def umount_huge(mountpoint):
174 '''Unmount the huge TLB file system (if mounted)'''
175 if mountpoint in get_mountpoints():
176 os.system("umount " + mountpoint)
180 '''Show where huge page filesystem is mounted'''
181 mounted = get_mountpoints()
183 print("Hugepages mounted on", *mounted)
185 print("Hugepages not mounted")
189 '''Process the command line arguments and setup huge pages'''
190 parser = argparse.ArgumentParser(
191 formatter_class=argparse.RawDescriptionHelpFormatter,
192 description="Setup huge pages",
196 To display current huge page settings:
199 To a complete setup of with 2 Gigabyte of 1G huge pages:
200 %(prog)s -p 1G --setup 2G
206 help="print the current huge page configuration")
208 '--clear', '-c', action='store_true', help="clear existing huge pages")
213 help='mount the huge page filesystem')
218 help='unmount the system huge page directory')
220 '--node', '-n', help='select numa node to reserve pages on')
225 help='choose huge page size to use')
230 help='reserve huge pages. Size is in bytes with K, M, or G suffix')
234 help='setup huge pages by doing clear, unmount, reserve and mount')
235 args = parser.parse_args()
240 args.reserve = args.setup
244 pagesize_kb = get_memsize(args.pagesize)
246 pagesize_kb = default_pagesize()
251 umount_huge(HUGE_MOUNT)
254 reserve_kb = get_memsize(args.reserve)
255 if reserve_kb % pagesize_kb != 0:
257 'Huge reservation {}kB is not a multiple of page size {}kB'.
258 format(reserve_kb, pagesize_kb))
260 int(reserve_kb / pagesize_kb), pagesize_kb, node=args.node)
262 mount_huge(pagesize_kb, HUGE_MOUNT)
269 if __name__ == "__main__":