vlib: move linux-specific code to vlib/linux
[vpp.git] / src / vlib / linux / physmem.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16  * physmem.c: Unix physical memory
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39
40 #include <unistd.h>
41 #include <sys/types.h>
42 #include <sys/mount.h>
43 #include <sys/mman.h>
44 #include <sys/fcntl.h>
45 #include <sys/stat.h>
46 #include <numa.h>
47 #include <numaif.h>
48
49 #include <vlib/vlib.h>
50 #include <vlib/physmem.h>
51 #include <vlib/unix/unix.h>
52 #include <vlib/linux/syscall.h>
53 #include <vlib/linux/sysfs.h>
54
55 static void *
56 unix_physmem_alloc_aligned (vlib_main_t * vm, vlib_physmem_region_index_t idx,
57                             uword n_bytes, uword alignment)
58 {
59   vlib_physmem_region_t *pr = vlib_physmem_get_region (vm, idx);
60   uword lo_offset, hi_offset;
61   uword *to_free = 0;
62
63   if (pr->heap == 0)
64     return 0;
65
66   /* IO memory is always at least cache aligned. */
67   alignment = clib_max (alignment, CLIB_CACHE_LINE_BYTES);
68
69   while (1)
70     {
71       mheap_get_aligned (pr->heap, n_bytes,
72                          /* align */ alignment,
73                          /* align offset */ 0,
74                          &lo_offset);
75
76       /* Allocation failed? */
77       if (lo_offset == ~0)
78         break;
79
80       if (pr->flags & VLIB_PHYSMEM_F_FAKE)
81         break;
82
83       /* Make sure allocation does not span DMA physical chunk boundary. */
84       hi_offset = lo_offset + n_bytes - 1;
85
86       if ((lo_offset >> pr->log2_page_size) ==
87           (hi_offset >> pr->log2_page_size))
88         break;
89
90       /* Allocation would span chunk boundary, queue it to be freed as soon as
91          we find suitable chunk. */
92       vec_add1 (to_free, lo_offset);
93     }
94
95   if (to_free != 0)
96     {
97       uword i;
98       for (i = 0; i < vec_len (to_free); i++)
99         mheap_put (pr->heap, to_free[i]);
100       vec_free (to_free);
101     }
102
103   return lo_offset != ~0 ? pr->heap + lo_offset : 0;
104 }
105
106 static void
107 unix_physmem_free (vlib_main_t * vm, vlib_physmem_region_index_t idx, void *x)
108 {
109   vlib_physmem_region_t *pr = vlib_physmem_get_region (vm, idx);
110   /* Return object to region's heap. */
111   mheap_put (pr->heap, x - pr->heap);
112 }
113
114 static u64
115 get_page_paddr (int fd, uword addr)
116 {
117   int pagesize = sysconf (_SC_PAGESIZE);
118   u64 seek, pagemap = 0;
119
120   seek = ((u64) addr / pagesize) * sizeof (u64);
121   if (lseek (fd, seek, SEEK_SET) != seek)
122     {
123       clib_unix_warning ("lseek to 0x%llx", seek);
124       return 0;
125     }
126   if (read (fd, &pagemap, sizeof (pagemap)) != (sizeof (pagemap)))
127     {
128       clib_unix_warning ("read ptbits");
129       return 0;
130     }
131   if ((pagemap & (1ULL << 63)) == 0)
132     return 0;
133
134   pagemap &= pow2_mask (55);
135
136   return pagemap * pagesize;
137 }
138
139 static clib_error_t *
140 unix_physmem_region_alloc (vlib_main_t * vm, char *name, u32 size,
141                            u8 numa_node, u32 flags,
142                            vlib_physmem_region_index_t * idx)
143 {
144   vlib_physmem_main_t *vpm = &vm->physmem_main;
145   vlib_physmem_region_t *pr;
146   clib_error_t *error = 0;
147   int pagemap_fd = -1;
148   u8 *mount_dir = 0;
149   u8 *filename = 0;
150   struct stat st;
151   int old_mpol;
152   int mmap_flags;
153   struct bitmask *old_mask = numa_allocate_nodemask ();
154
155   if (geteuid () != 0 && (flags & VLIB_PHYSMEM_F_FAKE) == 0)
156     return clib_error_return (0, "not allowed");
157
158   pool_get (vpm->regions, pr);
159
160   if ((pr - vpm->regions) >= 256)
161     {
162       error = clib_error_return (0, "maximum number of regions reached");
163       goto error;
164     }
165
166   pr->index = pr - vpm->regions;
167   pr->fd = -1;
168   pr->flags = flags;
169
170   if (get_mempolicy (&old_mpol, old_mask->maskp, old_mask->size + 1, NULL, 0)
171       == -1)
172     {
173       error = clib_error_return_unix (0, "get_mempolicy");
174       goto error;
175     }
176
177   if ((flags & VLIB_PHYSMEM_F_FAKE) == 0)
178     {
179       if ((pagemap_fd = open ((char *) "/proc/self/pagemap", O_RDONLY)) == -1)
180         {
181           error = clib_error_return_unix (0, "open '/proc/self/pagemap'");
182           goto error;
183         }
184
185       mount_dir = format (0, "%s/physmem_region%d%c",
186                           vlib_unix_get_runtime_dir (), pr->index, 0);
187       filename = format (0, "%s/mem%c", mount_dir, 0);
188
189       unlink ((char *) mount_dir);
190
191       error = vlib_unix_recursive_mkdir ((char *) mount_dir);
192       if (error)
193         goto error;
194
195       if (mount ("none", (char *) mount_dir, "hugetlbfs", 0, NULL))
196         {
197           error = clib_error_return_unix (0, "mount hugetlb directory '%s'",
198                                           mount_dir);
199           goto error;
200         }
201
202       if ((pr->fd = open ((char *) filename, O_CREAT | O_RDWR, 0755)) == -1)
203         {
204           error = clib_error_return_unix (0, "open");
205           goto error;
206         }
207
208       mmap_flags = MAP_SHARED | MAP_HUGETLB | MAP_LOCKED;
209     }
210   else
211     {
212       if ((pr->fd = memfd_create (name, MFD_ALLOW_SEALING)) == -1)
213         return clib_error_return_unix (0, "memfd_create");
214
215       if ((fcntl (pr->fd, F_ADD_SEALS, F_SEAL_SHRINK)) == -1)
216         {
217           error =
218             clib_error_return_unix (0, "fcntl (F_ADD_SEALS, F_SEAL_SHRINK)");
219           goto error;
220         }
221       mmap_flags = MAP_SHARED;
222     }
223
224   if (fstat (pr->fd, &st))
225     {
226       error = clib_error_return_unix (0, "fstat");
227       goto error;
228     }
229
230   pr->log2_page_size = min_log2 (st.st_blksize);
231   pr->n_pages = ((size - 1) >> pr->log2_page_size) + 1;
232   size = pr->n_pages * (1 << pr->log2_page_size);
233
234   if ((ftruncate (pr->fd, size)) == -1)
235     {
236       error = clib_error_return_unix (0, "ftruncate length: %d", size);
237       goto error;
238     }
239
240   if ((flags & VLIB_PHYSMEM_F_FAKE) == 0)
241     {
242       error = vlib_sysfs_prealloc_hugepages (numa_node,
243                                              1 << (pr->log2_page_size - 10),
244                                              pr->n_pages);
245       if (error)
246         goto error;
247     }
248
249   numa_set_preferred (numa_node);
250
251   pr->mem = mmap (0, size, (PROT_READ | PROT_WRITE), mmap_flags, pr->fd, 0);
252
253   if (pr->mem == MAP_FAILED)
254     {
255       pr->mem = 0;
256       error = clib_error_return_unix (0, "mmap");
257       goto error;
258     }
259
260   if (set_mempolicy (old_mpol, old_mask->maskp, old_mask->size + 1) == -1)
261     {
262       error = clib_error_return_unix (0, "set_mempolicy");
263       goto error;
264     }
265
266   pr->size = pr->n_pages << pr->log2_page_size;
267   pr->page_mask = (1 << pr->log2_page_size) - 1;
268   pr->numa_node = numa_node;
269   pr->name = format (0, "%s", name);
270
271   if ((flags & VLIB_PHYSMEM_F_FAKE) == 0)
272     {
273       int i;
274       for (i = 0; i < pr->n_pages; i++)
275         {
276           void *ptr = pr->mem + (i << pr->log2_page_size);
277           int node;
278           move_pages (0, 1, &ptr, 0, &node, 0);
279           if (numa_node != node)
280             {
281               clib_warning
282                 ("physmem page for region \'%s\' allocated on the wrong"
283                  " numa node (requested %u actual %u)", pr->name,
284                  pr->numa_node, node, i);
285               break;
286             }
287         }
288     }
289
290   if (flags & VLIB_PHYSMEM_F_INIT_MHEAP)
291     {
292       pr->heap = mheap_alloc_with_flags (pr->mem, pr->size,
293                                          /* Don't want mheap mmap/munmap with IO memory. */
294                                          MHEAP_FLAG_DISABLE_VM |
295                                          MHEAP_FLAG_THREAD_SAFE);
296       fformat (stdout, "%U", format_mheap, pr->heap, /* verbose */ 1);
297     }
298
299   if (flags & VLIB_PHYSMEM_F_HAVE_BUFFERS)
300     {
301       vlib_buffer_add_mem_range (vm, pointer_to_uword (pr->mem), pr->size);
302     }
303
304   *idx = pr->index;
305
306   if ((flags & VLIB_PHYSMEM_F_FAKE) == 0)
307     {
308       int i;
309       for (i = 0; i < pr->n_pages; i++)
310         {
311           uword vaddr =
312             pointer_to_uword (pr->mem) + (((u64) i) << pr->log2_page_size);
313           u64 page_paddr = get_page_paddr (pagemap_fd, vaddr);
314           vec_add1 (pr->page_table, page_paddr);
315         }
316     }
317
318   goto done;
319
320 error:
321   if (pr->fd > -1)
322     close (pr->fd);
323
324   if (pr->mem)
325     munmap (pr->mem, size);
326
327   memset (pr, 0, sizeof (*pr));
328   pool_put (vpm->regions, pr);
329
330 done:
331   if (mount_dir)
332     {
333       umount2 ((char *) mount_dir, MNT_DETACH);
334       rmdir ((char *) mount_dir);
335       vec_free (mount_dir);
336     }
337   numa_free_cpumask (old_mask);
338   vec_free (filename);
339   if (pagemap_fd > -1)
340     close (pagemap_fd);
341   return error;
342 }
343
344 static void
345 unix_physmem_region_free (vlib_main_t * vm, vlib_physmem_region_index_t idx)
346 {
347   vlib_physmem_main_t *vpm = &vm->physmem_main;
348   vlib_physmem_region_t *pr = vlib_physmem_get_region (vm, idx);
349
350   if (pr->fd > 0)
351     close (pr->fd);
352   munmap (pr->mem, pr->size);
353   vec_free (pr->name);
354   pool_put (vpm->regions, pr);
355 }
356
357 clib_error_t *
358 unix_physmem_init (vlib_main_t * vm)
359 {
360   clib_error_t *error = 0;
361
362   /* Avoid multiple calls. */
363   if (vm->os_physmem_alloc_aligned)
364     return error;
365
366   vm->os_physmem_alloc_aligned = unix_physmem_alloc_aligned;
367   vm->os_physmem_free = unix_physmem_free;
368   vm->os_physmem_region_alloc = unix_physmem_region_alloc;
369   vm->os_physmem_region_free = unix_physmem_region_free;
370
371   return error;
372 }
373
374 static clib_error_t *
375 show_physmem (vlib_main_t * vm,
376               unformat_input_t * input, vlib_cli_command_t * cmd)
377 {
378   vlib_physmem_main_t *vpm = &vm->physmem_main;
379   vlib_physmem_region_t *pr;
380
381   /* *INDENT-OFF* */
382   pool_foreach (pr, vpm->regions, (
383     {
384       vlib_cli_output (vm, "index %u name '%s' page-size %uKB num-pages %d "
385                        "numa-node %u fd %d\n",
386                        pr->index, pr->name, (1 << (pr->log2_page_size -10)),
387                        pr->n_pages, pr->numa_node, pr->fd);
388       if (pr->heap)
389         vlib_cli_output (vm, "  %U", format_mheap, pr->heap, /* verbose */ 1);
390       else
391         vlib_cli_output (vm, "  no heap\n");
392     }));
393   /* *INDENT-ON* */
394   return 0;
395 }
396
397 /* *INDENT-OFF* */
398 VLIB_CLI_COMMAND (show_physmem_command, static) = {
399   .path = "show physmem",
400   .short_help = "Show physical memory allocation",
401   .function = show_physmem,
402 };
403 /* *INDENT-ON* */
404
405 /*
406  * fd.io coding-style-patch-verification: ON
407  *
408  * Local Variables:
409  * eval: (c-set-style "gnu")
410  * End:
411  */