Debian Codegraph @

elflink.c

raw symbols SCIP
1 /*
2 * libhugetlbfs - Easy use of Linux hugepages
3 * Copyright (C) 2005-2006 David Gibson & Adam Litke, IBM Corporation.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public License
7 * as published by the Free Software Foundation; either version 2.1 of
8 * the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 #define _GNU_SOURCE
21
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <link.h>
26 #include <malloc.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <sys/syscall.h>
32 #include <sys/file.h>
33 #include <linux/unistd.h>
34 #include <sys/mman.h>
35 #include <sys/wait.h>
36 #include <sys/stat.h>
37 #include <errno.h>
38 #include <limits.h>
39 #include <elf.h>
40 #include <dlfcn.h>
41
42 #include "version.h"
43 #include "hugetlbfs.h"
44 #include "libhugetlbfs_internal.h"
45
46 #ifdef __LP64__
47 #define Elf_Ehdr Elf64_Ehdr
48 #define Elf_Phdr Elf64_Phdr
49 #define Elf_Dyn Elf64_Dyn
50 #define Elf_Sym Elf64_Sym
51 #define ELF_ST_BIND(x) ELF64_ST_BIND(x)
52 #define ELF_ST_TYPE(x) ELF64_ST_TYPE(x)
53 #else
54 #define Elf_Ehdr Elf32_Ehdr
55 #define Elf_Phdr Elf32_Phdr
56 #define Elf_Dyn Elf32_Dyn
57 #define Elf_Sym Elf32_Sym
58 #define ELF_ST_BIND(x) ELF64_ST_BIND(x)
59 #define ELF_ST_TYPE(x) ELF64_ST_TYPE(x)
60 #endif
61
62 /*
63 * SHARED_TIMEOUT is used by find_or_prepare_shared_file for when it
64 * should timeout while waiting for other users to finish preparing
65 * the file it wants. The value is the number of tries before giving
66 * up with a 1 second wait between tries
67 */
68 #define SHARED_TIMEOUT 10
69
70 /* This function prints an error message to stderr, then aborts. It
71 * is safe to call, even if the executable segments are presently
72 * unmapped.
73 *
74 * Arguments are printf() like, but at present supports only %d and %p
75 * with no modifiers
76 *
77 * FIXME: This works in practice, but I suspect it
78 * is not guaranteed safe: the library functions we call could in
79 * theory call other functions via the PLT which will blow up. */
80 static void write_err(const char *start, int len)
81 {
82 direct_syscall(__NR_write, 2 /*stderr*/, start, len);
83 }
84 static void sys_abort(void)
85 {
86 pid_t pid = direct_syscall(__NR_getpid);
87
88 direct_syscall(__NR_kill, pid, SIGABRT);
89 }
90 static void write_err_base(unsigned long val, int base)
91 {
92 const char digit[] = "0123456789abcdef";
93 char str1[sizeof(val)*8];
94 char str2[sizeof(val)*8];
95 int len = 0;
96 int i;
97
98 str1[0] = '0';
99 while (val) {
100 str1[len++] = digit[val % base];
101 val /= base;
102 }
103
104 if (len == 0)
105 len = 1;
106
107 /* Reverse digits */
108 for (i = 0; i < len; i++)
109 str2[i] = str1[len-i-1];
110
111 write_err(str2, len);
112 }
113
114 static void unmapped_abort(const char *fmt, ...)
115 {
116 const char *p, *q;
117 int done = 0;
118 unsigned long val;
119 va_list ap;
120
121 /* World's worst printf()... */
122 va_start(ap, fmt);
123 p = q = fmt;
124 while (! done) {
125 switch (*p) {
126 case '\0':
127 write_err(q, p-q);
128 done = 1;
129 break;
130
131 case '%':
132 write_err(q, p-q);
133 p++;
134 switch (*p) {
135 case 'u':
136 val = va_arg(ap, unsigned);
137 write_err_base(val, 10);
138 p++;
139 break;
140 case 'p':
141 val = (unsigned long)va_arg(ap, void *);
142 write_err_base(val, 16);
143 p++;
144 break;
145 }
146 q = p;
147 break;
148 default:
149 p++;
150 }
151 }
152
153 va_end(ap);
154
155 sys_abort();
156 }
157
158 /* The directory to use for sharing readonly segments */
159 static char share_readonly_path[PATH_MAX+1];
160
161 #define MAX_HTLB_SEGS 4
162 #define MAX_SEGS 10
163
164 struct seg_info {
165 void *vaddr;
166 unsigned long filesz, memsz, extrasz;
167 int prot;
168 int fd;
169 int index;
170 long page_size;
171 };
172
173 struct seg_layout {
174 unsigned long start, end;
175 long page_size;
176 };
177
178 static struct seg_info htlb_seg_table[MAX_HTLB_SEGS];
179 static int htlb_num_segs;
180 static unsigned long force_remap; /* =0 */
181 static long hpage_readonly_size, hpage_writable_size;
182
183 /**
184 * assemble_path - handy wrapper around snprintf() for building paths
185 * @dst: buffer of size PATH_MAX+1 to assemble string into
186 * @fmt: format string for path
187 * @...: printf() style parameters for path
188 *
189 * assemble_path() builds a path in the target buffer (which must have
190 * PATH_MAX+1 available bytes), similar to sprintf(). However, f the
191 * assembled path would exceed PATH_MAX characters in length,
192 * assemble_path() prints an error and abort()s, so there is no need
193 * to check the return value and backout.
194 */
195 static void assemble_path(char *dst, const char *fmt, ...)
196 {
197 va_list ap;
198 int len;
199
200 va_start(ap, fmt);
201 len = vsnprintf(dst, PATH_MAX+1, fmt, ap);
202 va_end(ap);
203
204 if (len < 0) {
205 ERROR("vsnprintf() error\n");
206 abort();
207 }
208
209 if (len > PATH_MAX) {
210 ERROR("Overflow assembling path\n");
211 abort();
212 }
213 }
214
215 static void check_memsz()
216 {
217 int i;
218 unsigned long memsz_total = 0, memsz_max = 0;
219 if (htlb_num_segs == 0)
220 return;
221 /*
222 * rough heuristic to see if we'll run out of address
223 * space
224 */
225 for (i = 0; i < htlb_num_segs; i++) {
226 memsz_total += htlb_seg_table[i].memsz;
227 if (htlb_seg_table[i].memsz > memsz_max)
228 memsz_max = htlb_seg_table[i].memsz;
229 }
230 /* avoid overflow checking by using two checks */
231 DEBUG("Total memsz = %#0lx, memsz of largest segment = %#0lx\n",
232 memsz_total, memsz_max);
233 }
234
235 /**
236 * find_or_create_share_path - obtain a directory to store the shared
237 * hugetlbfs files
238 *
239 * Checks environment and filesystem to locate a suitable directory
240 * for shared hugetlbfs files, creating a new directory if necessary.
241 * The determined path is stored in global variable share_readonly_path.
242 *
243 * returns:
244 * -1, on error
245 * 0, on success
246 */
247 static int find_or_create_share_path(long page_size)
248 {
249 const char *base_path;
250 struct stat sb;
251 int ret;
252
253 /* If no remaping is planned for the read-only segments we are done */
254 if (!page_size)
255 return 0;
256
257 if (__hugetlb_opts.share_path) {
258 /* Given an explicit path */
259 if (hugetlbfs_test_path(__hugetlb_opts.share_path) != 1) {
260 WARNING("HUGETLB_SHARE_PATH %s is not on a hugetlbfs"
261 " filesystem\n", __hugetlb_opts.share_path);
262 return -1;
263 }
264
265 /* Make sure the page size matches */
266 if (page_size !=
267 hugetlbfs_test_pagesize(__hugetlb_opts.share_path)) {
268 WARNING("HUGETLB_SHARE_PATH %s is not valid for a %li "
269 "kB page size\n", __hugetlb_opts.share_path,
270 page_size / 1024);
271 return -1;
272 }
273 assemble_path(share_readonly_path, "%s",
274 __hugetlb_opts.share_path);
275 return 0;
276 }
277
278 base_path = hugetlbfs_find_path_for_size(page_size);
279 if (!base_path)
280 return -1;
281
282 assemble_path(share_readonly_path, "%s/elflink-uid-%d",
283 base_path, getuid());
284
285 ret = mkdir(share_readonly_path, 0700);
286 if ((ret != 0) && (errno != EEXIST)) {
287 WARNING("Error creating share directory %s\n",
288 share_readonly_path);
289 return -1;
290 }
291
292 /* Check the share directory is sane */
293 ret = lstat(share_readonly_path, &sb);
294 if (ret != 0) {
295 WARNING("Couldn't stat() %s: %s\n", share_readonly_path,
296 strerror(errno));
297 return -1;
298 }
299
300 if (! S_ISDIR(sb.st_mode)) {
301 WARNING("%s is not a directory\n", share_readonly_path);
302 return -1;
303 }
304
305 if (sb.st_uid != getuid()) {
306 WARNING("%s has wrong owner (uid=%d instead of %d)\n",
307 share_readonly_path, sb.st_uid, getuid());
308 return -1;
309 }
310
311 if (sb.st_mode & (S_IWGRP | S_IWOTH)) {
312 WARNING("%s has bad permissions 0%03o\n",
313 share_readonly_path, sb.st_mode);
314 return -1;
315 }
316
317 return 0;
318 }
319
320 /*
321 * Look for non-zero BSS data inside a range and print out any matches
322 */
323
324 static void check_bss(unsigned long *start, unsigned long *end)
325 {
326 unsigned long *addr;
327
328 for (addr = start; addr < end; addr++) {
329 if (*addr != 0)
330 DEBUG("Non-zero BSS data @ %p: %lx\n", addr, *addr);
331 }
332 }
333
334 /**
335 * get_shared_file_name - create a shared file name from program name,
336 * segment number and current word size
337 * @htlb_seg_info: pointer to program's segment data
338 * @file_path: pointer to a PATH_MAX+1 array to store filename in
339 *
340 * The file name created is *not* intended to be unique, except when
341 * the name, gid or phdr number differ. The goal here is to have a
342 * standard means of accessing particular segments of particular
343 * executables.
344 *
345 * returns:
346 * -1, on failure
347 * 0, on success
348 */
349 static int get_shared_file_name(struct seg_info *htlb_seg_info, char *file_path)
350 {
351 int ret;
352 char binary[PATH_MAX+1];
353 char *binary2;
354
355 memset(binary, 0, sizeof(binary));
356 ret = readlink("/proc/self/exe", binary, PATH_MAX);
357 if (ret < 0) {
358 WARNING("shared_file: readlink() on /proc/self/exe "
359 "failed: %s\n", strerror(errno));
360 return -1;
361 }
362
363 binary2 = basename(binary);
364 if (!binary2) {
365 WARNING("shared_file: basename() on %s failed: %s\n",
366 binary, strerror(errno));
367 return -1;
368 }
369
370 assemble_path(file_path, "%s/%s_%zd_%d", share_readonly_path, binary2,
371 sizeof(unsigned long) * 8, htlb_seg_info->index);
372
373 return 0;
374 }
375
376 /* Find the .dynamic program header */
377 static int find_dynamic(Elf_Dyn **dyntab, const ElfW(Addr) addr,
378 const Elf_Phdr *phdr, int phnum)
379 {
380 int i = 1;
381
382 while ((phdr[i].p_type != PT_DYNAMIC) && (i < phnum)) {
383 ++i;
384 }
385 if (phdr[i].p_type == PT_DYNAMIC) {
386 *dyntab = (Elf_Dyn *)(addr + phdr[i].p_vaddr);
387 return 0;
388 } else {
389 DEBUG("No dynamic segment found\n");
390 return -1;
391 }
392 }
393
394 /* Find the dynamic string and symbol tables */
395 static int find_tables(Elf_Dyn *dyntab, Elf_Sym **symtab, char **strtab)
396 {
397 int i = 1;
398 while ((dyntab[i].d_tag != DT_NULL)) {
399 if (dyntab[i].d_tag == DT_SYMTAB)
400 *symtab = (Elf_Sym *)dyntab[i].d_un.d_ptr;
401 else if (dyntab[i].d_tag == DT_STRTAB)
402 *strtab = (char *)dyntab[i].d_un.d_ptr;
403 i++;
404 }
405
406 if (!*symtab) {
407 DEBUG("No symbol table found\n");
408 return -1;
409 }
410 if (!*strtab) {
411 DEBUG("No string table found\n");
412 return -1;
413 }
414 return 0;
415 }
416
417 /* Find the number of symbol table entries */
418 static int find_numsyms(Elf_Sym *symtab, char *strtab)
419 {
420 /*
421 * WARNING - The symbol table size calculation does not follow the ELF
422 * standard, but rather exploits an assumption we enforce in
423 * our linker scripts that the string table follows
424 * immediately after the symbol table. The linker scripts
425 * must maintain this assumption or this code will break.
426 */
427 if ((void *)strtab <= (void *)symtab) {
428 DEBUG("Could not calculate dynamic symbol table size\n");
429 return -1;
430 }
431 return ((void *)strtab - (void *)symtab) / sizeof(Elf_Sym);
432 }
433
434 /*
435 * To reduce the size of the extra copy window, we can eliminate certain
436 * symbols based on information in the dynamic section. The following
437 * characteristics apply to symbols which may require copying:
438 * - Within the BSS
439 * - Global or Weak binding
440 * - Object type (variable)
441 * - Non-zero size (zero size means the symbol is just a marker with no data)
442 */
443 static inline int keep_symbol(char *strtab, Elf_Sym *s, void *start, void *end)
444 {
445 if ((void *)s->st_value < start)
446 return 0;
447 if ((void *)s->st_value > end)
448 return 0;
449 if ((ELF_ST_BIND(s->st_info) != STB_GLOBAL) &&
450 (ELF_ST_BIND(s->st_info) != STB_WEAK))
451 return 0;
452 if (ELF_ST_TYPE(s->st_info) != STT_OBJECT)
453 return 0;
454 if (s->st_size == 0)
455 return 0;
456
457 if (__hugetlbfs_debug)
458 DEBUG("symbol to copy at %p: %s\n", (void *)s->st_value,
459 strtab + s->st_name);
460
461 return 1;
462 }
463
464 /* If unspecified by the architecture, no extra copying of the plt is needed */
465 ElfW(Word) __attribute__ ((weak)) plt_extrasz(ElfW(Dyn) *dyntab)
466 {
467 return 0;
468 }
469
470 /*
471 * Subtle: Since libhugetlbfs depends on glibc, we allow it
472 * it to be loaded before us. As part of its init functions, it
473 * initializes stdin, stdout, and stderr in the bss. We need to
474 * include these initialized variables in our copy.
475 */
476
477 static void get_extracopy(struct seg_info *seg, const ElfW(Addr) addr,
478 const Elf_Phdr *phdr, int phnum)
479 {
480 Elf_Dyn *dyntab; /* dynamic segment table */
481 Elf_Sym *symtab = NULL; /* dynamic symbol table */
482 Elf_Sym *sym; /* a symbol */
483 char *strtab = NULL; /* string table for dynamic symbols */
484 int ret, numsyms, found_sym = 0;
485 void *start, *end, *end_orig;
486 void *sym_end;
487 void *plt_end;
488
489 end_orig = seg->vaddr + seg->memsz;
490 start = seg->vaddr + seg->filesz;
491 if (seg->filesz == seg->memsz)
492 return;
493 if (!__hugetlb_opts.min_copy)
494 goto bail2;
495
496 /* Find dynamic program header */
497 ret = find_dynamic(&dyntab, addr, phdr, phnum);
498 if (ret < 0)
499 goto bail;
500
501 /* Find symbol and string tables */
502 ret = find_tables(dyntab, &symtab, &strtab);
503 if (ret < 0)
504 goto bail;
505
506 numsyms = find_numsyms(symtab, strtab);
507 if (numsyms < 0)
508 goto bail;
509
510 /*
511 * We must ensure any returns done hereafter have sane start and end
512 * values, as the criss-cross apple sauce algorithm is beginning
513 */
514 end = start;
515
516 for (sym = symtab; sym < symtab + numsyms; sym++) {
517 if (!keep_symbol(strtab, sym, start, end_orig))
518 continue;
519
520 /* These are the droids we are looking for */
521 found_sym = 1;
522 sym_end = (void *)(sym->st_value + sym->st_size);
523 if (sym_end > end)
524 end = sym_end;
525 }
526
527 /*
528 * Some platforms (PowerPC 64bit ELF) place their PLT beyond the filesz
529 * part of the data segment. When this is the case, we must extend the
530 * copy window to include this data which has been initialized by the
531 * run-time linker.
532 */
533 plt_end = start + plt_extrasz(dyntab);
534 if (plt_end > end) {
535 end = plt_end;
536 found_sym = 1;
537 }
538
539 if (__hugetlbfs_debug)
540 check_bss(end, end_orig);
541
542 if (found_sym) {
543 seg->extrasz = end - start;
544 }
545 /*
546 * else no need to copy anything, so leave seg->extrasz as zero
547 */
548 return;
549
550 bail:
551 DEBUG("Unable to perform minimal copy\n");
552 bail2:
553 seg->extrasz = end_orig - start;
554 }
555
556 #if defined(__powerpc64__) || \
557 (defined(__powerpc__) && !defined(PPC_NO_SEGMENTS))
558 #define SLICE_LOW_TOP (0x100000000UL)
559 #define SLICE_LOW_SIZE (1UL << SLICE_LOW_SHIFT)
560 #define SLICE_HIGH_SIZE (1UL << SLICE_HIGH_SHIFT)
561 #endif
562
563 /*
564 * Return the address of the start and end of the hugetlb slice
565 * containing @addr. A slice is a range of addresses, start inclusive
566 * and end exclusive.
567 * Note, that since relinking is not supported on ia64, we can leave it
568 * out here.
569 */
570 static unsigned long hugetlb_slice_start(unsigned long addr)
571 {
572 if (arch_has_slice_support()) {
573 #if defined(__powerpc64__)
574 if (addr < SLICE_LOW_TOP)
575 return ALIGN_DOWN(addr, SLICE_LOW_SIZE);
576 else if (addr < SLICE_HIGH_SIZE)
577 return SLICE_LOW_TOP;
578 else
579 return ALIGN_DOWN(addr, SLICE_HIGH_SIZE);
580 #elif defined(__powerpc__) && !defined(PPC_NO_SEGMENTS)
581 return ALIGN_DOWN(addr, SLICE_LOW_SIZE);
582 #endif
583 }
584
585 return ALIGN_DOWN(addr, gethugepagesize());
586 }
587
588 static unsigned long hugetlb_slice_end(unsigned long addr)
589 {
590 if (arch_has_slice_support()) {
591 #if defined(__powerpc64__)
592 if (addr < SLICE_LOW_TOP)
593 return ALIGN_UP(addr, SLICE_LOW_SIZE) - 1;
594 else
595 return ALIGN_UP(addr, SLICE_HIGH_SIZE) - 1;
596 #elif defined(__powerpc__) && !defined(PPC_NO_SEGMENTS)
597 return ALIGN_UP(addr, SLICE_LOW_SIZE) - 1;
598 #endif
599 }
600
601 return ALIGN_UP(addr, gethugepagesize()) - 1;
602 }
603
604 static unsigned long hugetlb_next_slice_start(unsigned long addr)
605 {
606 return hugetlb_slice_end(addr) + 1;
607 }
608
609 static unsigned long hugetlb_prev_slice_end(unsigned long addr)
610 {
611 return hugetlb_slice_start(addr) - 1;
612 }
613
614 /*
615 * Store a copy of the given program header
616 */
617 static int save_phdr(int table_idx, int phnum, const ElfW(Addr) addr,
618 const ElfW(Phdr) *phdr)
619 {
620 int prot = 0;
621
622 if (table_idx >= MAX_HTLB_SEGS) {
623 WARNING("Executable has too many segments (max %d)\n",
624 MAX_HTLB_SEGS);
625 htlb_num_segs = 0;
626 return -1;
627 }
628
629 if (phdr->p_flags & PF_R)
630 prot |= PROT_READ;
631 if (phdr->p_flags & PF_W)
632 prot |= PROT_WRITE;
633 if (phdr->p_flags & PF_X)
634 prot |= PROT_EXEC;
635
636 htlb_seg_table[table_idx].vaddr = (void *)(addr + phdr->p_vaddr);
637 htlb_seg_table[table_idx].filesz = phdr->p_filesz;
638 htlb_seg_table[table_idx].memsz = phdr->p_memsz;
639 htlb_seg_table[table_idx].prot = prot;
640 htlb_seg_table[table_idx].index = phnum;
641
642 INFO("Segment %d (phdr %d): %#0lx-%#0lx (filesz=%#0lx) "
643 "(prot = %#0x)\n", table_idx, phnum,
644 (unsigned long) addr + phdr->p_vaddr,
645 (unsigned long) addr + phdr->p_vaddr + phdr->p_memsz,
646 (unsigned long) phdr->p_filesz, (unsigned int) prot);
647
648 return 0;
649 }
650
651 static int verify_segment_layout(struct seg_layout *segs, int num_segs)
652 {
653 int i;
654 long base_size = getpagesize();
655
656 for (i = 1; i < num_segs; i++) {
657 unsigned long prev_end = segs[i - 1].end;
658 unsigned long start = segs[i].start;
659
660 /*
661 * Do not worry about the boundary between segments that will
662 * not be remapped.
663 */
664 if (segs[i - 1].page_size == base_size &&
665 segs[i].page_size == base_size)
666 continue;
667
668 /* Make sure alignment hasn't caused segments to overlap */
669 if (prev_end > start) {
670 WARNING("Layout problem with segments %i and %i:\n\t"
671 "Segments would overlap\n", i - 1, i);
672 return 1;
673 }
674
675 /* Make sure page size transitions occur on slice boundaries */
676 if ((segs[i - 1].page_size != segs[i].page_size) &&
677 hugetlb_slice_end(prev_end) >
678 hugetlb_slice_start(start)) {
679 WARNING("Layout problem with segments %i and %i:\n\t"
680 "Only one page size per slice\n", i - 1, i);
681 return 1;
682 }
683 }
684 return 0;
685 }
686
687 static long segment_requested_page_size(const ElfW(Phdr) *phdr)
688 {
689 int writable = phdr->p_flags & PF_W;
690
691 /* Check if a page size was requested by the user */
692 if (writable && hpage_writable_size)
693 return hpage_writable_size;
694 if (!writable && hpage_readonly_size)
695 return hpage_readonly_size;
696
697 /* Check if this segment requests remapping by default */
698 if (!hpage_readonly_size && !hpage_writable_size &&
699 (phdr->p_flags & PF_LINUX_HUGETLB))
700 return gethugepagesize();
701
702 /* No remapping selected, return the base page size */
703 return getpagesize();
704 }
705
706 static
707 int parse_elf_normal(struct dl_phdr_info *info, size_t size, void *data)
708 {
709 int i, num_segs;
710 unsigned long page_size, seg_psize, start, end;
711 struct seg_layout segments[MAX_SEGS];
712
713 page_size = getpagesize();
714 num_segs = 0;
715
716 for (i = 0; i < info->dlpi_phnum; i++) {
717 if (info->dlpi_phdr[i].p_type != PT_LOAD)
718 continue;
719
720 if (i >= MAX_SEGS) {
721 WARNING("Maximum number of PT_LOAD segments"
722 "exceeded\n");
723 return 1;
724 }
725
726 seg_psize = segment_requested_page_size(&info->dlpi_phdr[i]);
727 if (seg_psize != page_size) {
728 if (save_phdr(htlb_num_segs, i, info->dlpi_addr,
729 &info->dlpi_phdr[i]))
730 return 1;
731 get_extracopy(&htlb_seg_table[htlb_num_segs],
732 info->dlpi_addr, info->dlpi_phdr,
733 info->dlpi_phnum);
734 htlb_seg_table[htlb_num_segs].page_size = seg_psize;
735 htlb_num_segs++;
736 }
737 start = ALIGN_DOWN(info->dlpi_addr +
738 info->dlpi_phdr[i].p_vaddr, seg_psize);
739 end = ALIGN(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr +
740 info->dlpi_phdr[i].p_memsz, seg_psize);
741
742 segments[num_segs].page_size = seg_psize;
743 segments[num_segs].start = start;
744 segments[num_segs].end = end;
745 num_segs++;
746 }
747 if (verify_segment_layout(segments, num_segs))
748 htlb_num_segs = 0;
749
750 if (__hugetlbfs_debug)
751 check_memsz();
752
753 return 1;
754 }
755
756 /*
757 * Parse the phdrs of a normal program to attempt partial segment remapping
758 */
759 static
760 int parse_elf_partial(struct dl_phdr_info *info, size_t size, void *data)
761 {
762 unsigned long vaddr, memsz, gap;
763 unsigned long slice_end;
764 int i;
765
766 /* This should never actually be called more than once in an
767 * iteration: we assume that dl_iterate_phdrs() always gives
768 * us the main program's phdrs on the first iteration, and
769 * always return 1 to cease iteration at that point. */
770
771 for (i = 0; i < info->dlpi_phnum; i++) {
772 if (info->dlpi_phdr[i].p_type != PT_LOAD)
773 continue;
774
775 /*
776 * Partial segment remapping only makes sense if the
777 * memory size of the segment is larger than the
778 * granularity at which hugepages can be used. This
779 * mostly affects ppc, where the segment must be larger
780 * than 256M. This guarantees that remapping the binary
781 * in this forced way won't violate any contiguity
782 * constraints.
783 */
784 vaddr = hugetlb_next_slice_start(info->dlpi_addr +
785 info->dlpi_phdr[i].p_vaddr);
786 gap = vaddr - (info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
787 slice_end = hugetlb_slice_end(vaddr);
788 /*
789 * we should stop remapping just before the slice
790 * containing the end of the memsz portion (taking away
791 * the gap of the memsz)
792 */
793 memsz = info->dlpi_phdr[i].p_memsz;
794 if (memsz < gap) {
795 INFO("Segment %d's unaligned memsz is too small: "
796 "%#0lx < %#0lx\n",
797 i, memsz, gap);
798 continue;
799 }
800 memsz -= gap;
801 if (memsz < (slice_end - vaddr)) {
802 INFO("Segment %d's aligned memsz is too small: "
803 "%#0lx < %#0lx\n",
804 i, memsz, slice_end - vaddr);
805 continue;
806 }
807 memsz = hugetlb_prev_slice_end(vaddr + memsz) - vaddr;
808
809 if (save_phdr(htlb_num_segs, i, info->dlpi_addr,
810 &info->dlpi_phdr[i]))
811 return 1;
812
813 /*
814 * When remapping partial segments, we create a sub-segment
815 * that is based on the original. For this reason, we must
816 * make some changes to the phdr captured by save_phdr():
817 * vaddr is aligned upwards to a slice boundary
818 * memsz is aligned downwards to a slice boundary
819 * filesz is set to memsz to force all memory to be copied
820 */
821 htlb_seg_table[htlb_num_segs].vaddr = (void *)vaddr;
822 htlb_seg_table[htlb_num_segs].filesz = memsz;
823 htlb_seg_table[htlb_num_segs].memsz = memsz;
824
825 htlb_num_segs++;
826 }
827 return 1;
828 }
829
830 /*
831 * Verify that a range of memory is unoccupied and usable
832 */
833 static void check_range_empty(void *addr, unsigned long len)
834 {
835 void *p;
836
837 p = mmap(addr, len, PROT_READ, MAP_PRIVATE|MAP_ANON, 0, 0);
838 if (p != addr) {
839 WARNING("Unable to verify address range %p - %p. Not empty?\n",
840 addr, addr + len);
841 if (__hugetlbfs_debug)
842 dump_proc_pid_maps();
843 }
844 if (p != MAP_FAILED)
845 munmap(p, len);
846 }
847
848 /*
849 * Copy a program segment into a huge page. If possible, try to copy the
850 * smallest amount of data possible, unless the user disables this
851 * optimization via the HUGETLB_ELFMAP environment variable.
852 */
853 static int prepare_segment(struct seg_info *seg)
854 {
855 void *start, *p, *end, *new_end;
856 unsigned long size, offset;
857 long page_size = getpagesize();
858 long hpage_size;
859 int mmap_reserve = __hugetlb_opts.no_reserve ? MAP_NORESERVE : 0;
860
861 hpage_size = seg->page_size;
862
863 /*
864 * mmaps must begin at an address aligned to the page size. If the
865 * vaddr of this segment is not hpage_size aligned, align it downward
866 * and begin the mmap there. Note the offset so we can copy data to
867 * the correct starting address within the temporary mmap.
868 */
869 start = (void *) ALIGN_DOWN((unsigned long)seg->vaddr, hpage_size);
870 offset = seg->vaddr - start;
871
872 /*
873 * Calculate the size of the temporary mapping we must create.
874 * This includes the offset (described above) and the filesz and
875 * extrasz portions of the segment (described below). We must align
876 * this total to the huge page size so it will be valid for mmap.
877 */
878 size = ALIGN(offset + seg->filesz + seg->extrasz, hpage_size);
879
880 /*
881 * If the segment's start or end addresses have been adjusted to align
882 * them to the hpage_size, check to make sure nothing is mapped in the
883 * padding before and after the segment.
884 */
885 end = (void *) ALIGN((unsigned long)seg->vaddr + seg->memsz, page_size);
886 new_end = (void *) ALIGN((unsigned long)end, hpage_size);
887 if (ALIGN_DOWN(offset, page_size))
888 check_range_empty(start, ALIGN_DOWN(offset, page_size));
889 if (end != new_end)
890 check_range_empty(end, new_end - end);
891
892 /* Create the temporary huge page mmap */
893 p = mmap(NULL, size, PROT_READ|PROT_WRITE,
894 MAP_SHARED|mmap_reserve, seg->fd, 0);
895 if (p == MAP_FAILED) {
896 WARNING("Couldn't map hugepage segment to copy data: %s\n",
897 strerror(errno));
898 return -1;
899 }
900
901 /*
902 * Minimizing the amount of data copied will maximize performance.
903 * By definition, the filesz portion of the segment contains
904 * initialized data and must be copied. If part of the memsz portion
905 * is known to be initialized already, extrasz will be non-zero and
906 * that many addtional bytes will be copied from the beginning of the
907 * memsz region. The rest of the memsz is understood to be zeroes and
908 * need not be copied.
909 */
910 INFO("Mapped hugeseg at %p. Copying %#0lx bytes and %#0lx extra bytes"
911 " from %p...", p, seg->filesz, seg->extrasz, seg->vaddr);
912 memcpy(p + offset, seg->vaddr, seg->filesz + seg->extrasz);
913 INFO_CONT("done\n");
914
915 munmap(p, size);
916
917 return 0;
918 }
919
920 /*
921 * [PPC] Prior to 2.6.22 (which added slices), our temporary hugepage
922 * mappings are placed in the segment before the stack. This 'taints' that
923 * segment for be hugepage-only for the lifetime of the process, resulting
924 * in a maximum stack size of 256MB. If we instead create our hugepage
925 * mappings in a child process, we can avoid this problem.
926 *
927 * This does not adversely affect non-PPC platforms so do it everywhere.
928 */
929 static int fork_and_prepare_segment(struct seg_info *htlb_seg_info)
930 {
931 int pid, ret, status;
932
933 if ((pid = fork()) < 0) {
934 WARNING("fork failed");
935 return -1;
936 }
937 if (pid == 0) {
938 ret = prepare_segment(htlb_seg_info);
939 if (ret < 0) {
940 WARNING("Failed to prepare segment\n");
941 exit(1);
942 }
943 else
944 exit(0);
945 }
946 ret = waitpid(pid, &status, 0);
947 if (ret == -1) {
948 WARNING("waitpid failed");
949 return -1;
950 }
951
952 if (WEXITSTATUS(status) != 0)
953 return -1;
954
955 INFO("Prepare succeeded\n");
956 return 0;
957 }
958
959 /**
960 * find_or_prepare_shared_file - get one shareable file
961 * @htlb_seg_info: pointer to program's segment data
962 *
963 * This function either locates a hugetlbfs file already containing
964 * data for a given program segment, or creates one if it doesn't
965 * already exist.
966 *
967 * We use the following algorithm to ensure that when processes race
968 * to instantiate the hugepage file, we will never obtain an
969 * incompletely prepared file or have multiple processes prepar
970 * separate copies of the file.
971 * - first open 'filename.tmp' with O_EXCL (this acts as a lockfile)
972 * - second open 'filename' with O_RDONLY (even if the first open
973 * succeeded).
974 * Then:
975 * - If both opens succeed, close the O_EXCL open, unlink
976 * filename.tmp and use the O_RDONLY fd. (Somebody else has prepared
977 * the file already)
978 * - If only the O_RDONLY open suceeds, and the O_EXCL open
979 * fails with EEXIST, just used the O_RDONLY fd. (Somebody else has
980 * prepared the file already, but we raced with their rename()).
981 * - If only the O_EXCL open suceeds, and the O_RDONLY fails with
982 * ENOENT, prepare the the O_EXCL open, then rename() filename.tmp to
983 * filename. (We're the first in, we have to prepare the file).
984 * - If both opens fail, with EEXIST and ENOENT, respectively,
985 * wait for a little while, then try again from the beginning
986 * (Somebody else is preparing the file, but hasn't finished yet)
987 *
988 * returns:
989 * -1, on failure
990 * 0, on success
991 */
992 static int find_or_prepare_shared_file(struct seg_info *htlb_seg_info)
993 {
994 int fdx = -1, fds;
995 int errnox, errnos;
996 int ret;
997 int i;
998 char final_path[PATH_MAX+1];
999 char tmp_path[PATH_MAX+1];
1000
1001 ret = get_shared_file_name(htlb_seg_info, final_path);
1002 if (ret < 0)
1003 return -1;
1004 assemble_path(tmp_path, "%s.tmp", final_path);
1005
1006 for (i = 0; i < SHARED_TIMEOUT; i++) {
1007 /* NB: mode is modified by umask */
1008 fdx = open(tmp_path, O_CREAT | O_EXCL | O_RDWR, 0666);
1009 errnox = errno;
1010 fds = open(final_path, O_RDONLY);
1011 errnos = errno;
1012
1013 if (fds >= 0) {
1014 /* Got an already-prepared file -> use it */
1015 if (fdx > 0) {
1016 /* Also got an exclusive file -> clean up */
1017 ret = unlink(tmp_path);
1018 if (ret != 0)
1019 WARNING("shared_file: unable to clean "
1020 "up unneeded file %s: %s\n",
1021 tmp_path, strerror(errno));
1022 close(fdx);
1023 } else if (errnox != EEXIST) {
1024 WARNING("shared_file: Unexpected failure on exclusive"
1025 " open of %s: %s\n", tmp_path,
1026 strerror(errnox));
1027 }
1028 htlb_seg_info->fd = fds;
1029 return 0;
1030 }
1031
1032 if (fdx >= 0) {
1033 /* It's our job to prepare */
1034 if (errnos != ENOENT)
1035 WARNING("shared_file: Unexpected failure on"
1036 " shared open of %s: %s\n", final_path,
1037 strerror(errnos));
1038
1039 htlb_seg_info->fd = fdx;
1040
1041 INFO("Got unpopulated shared fd -- Preparing\n");
1042 ret = fork_and_prepare_segment(htlb_seg_info);
1043 if (ret < 0)
1044 goto fail;
1045
1046 INFO("Prepare succeeded\n");
1047 /* move to permanent location */
1048 ret = rename(tmp_path, final_path);
1049 if (ret != 0) {
1050 WARNING("shared_file: unable to rename %s"
1051 " to %s: %s\n", tmp_path, final_path,
1052 strerror(errno));
1053 goto fail;
1054 }
1055
1056 return 0;
1057 }
1058
1059 /* Both opens failed, somebody else is still preparing */
1060 /* Wait and try again */
1061 sleep(1);
1062 }
1063
1064 fail:
1065 if (fdx > 0) {
1066 ret = unlink(tmp_path);
1067 if (ret != 0)
1068 WARNING("shared_file: Unable to clean up temp file %s "
1069 "on failure: %s\n", tmp_path, strerror(errno));
1070 close(fdx);
1071 }
1072
1073 return -1;
1074 }
1075
1076 /**
1077 * obtain_prepared_file - multiplex callers depending on if
1078 * sharing or not
1079 * @htlb_seg_info: pointer to program's segment data
1080 *
1081 * returns:
1082 * -1, on error
1083 * 0, on success
1084 */
1085 static int obtain_prepared_file(struct seg_info *htlb_seg_info)
1086 {
1087 int fd = -1;
1088 int ret;
1089 long hpage_size = htlb_seg_info->page_size;
1090
1091 /* Share only read-only segments */
1092 if (__hugetlb_opts.sharing && !(htlb_seg_info->prot & PROT_WRITE)) {
1093 /* first, try to share */
1094 ret = find_or_prepare_shared_file(htlb_seg_info);
1095 if (ret == 0)
1096 return 0;
1097 /* but, fall through to unlinked files, if sharing fails */
1098 WARNING("Falling back to unlinked files\n");
1099 }
1100 fd = hugetlbfs_unlinked_fd_for_size(hpage_size);
1101 if (fd < 0)
1102 return -1;
1103 htlb_seg_info->fd = fd;
1104
1105 return fork_and_prepare_segment(htlb_seg_info);
1106 }
1107
1108 static void remap_segments(struct seg_info *seg, int num)
1109 {
1110 int i;
1111 void *p;
1112 unsigned long start, offset, mapsize;
1113 long page_size = getpagesize();
1114 long hpage_size;
1115 int mmap_flags;
1116
1117 /*
1118 * XXX: The bogus call to mmap below forces ld.so to resolve the
1119 * mmap symbol before we unmap the plt in the data segment
1120 * below. This might only be needed in the case where sharing
1121 * is enabled and the hugetlbfs files have already been prepared
1122 * by another process.
1123 */
1124 p = mmap(0, 0, 0, 0, 0, 0);
1125
1126 /* This is the hairy bit, between unmap and remap we enter a
1127 * black hole. We can't call anything which uses static data
1128 * (ie. essentially any library function...)
1129 */
1130 for (i = 0; i < num; i++) {
1131 start = ALIGN_DOWN((unsigned long)seg[i].vaddr, page_size);
1132 offset = (unsigned long)(seg[i].vaddr - start);
1133 mapsize = ALIGN(offset + seg[i].memsz, page_size);
1134 munmap((void *) start, mapsize);
1135 }
1136
1137 /* Step 4. Rebuild the address space with hugetlb mappings */
1138 /* NB: we can't do the remap as hugepages within the main loop
1139 * because of PowerPC: we may need to unmap all the normal
1140 * segments before the MMU segment is ok for hugepages */
1141 for (i = 0; i < num; i++) {
1142 hpage_size = seg[i].page_size;
1143 start = ALIGN_DOWN((unsigned long)seg[i].vaddr, hpage_size);
1144 offset = (unsigned long)(seg[i].vaddr - start);
1145 mapsize = ALIGN(offset + seg[i].memsz, hpage_size);
1146 mmap_flags = MAP_PRIVATE|MAP_FIXED;
1147
1148 /* If requested, make no reservations */
1149 if (__hugetlb_opts.no_reserve)
1150 mmap_flags |= MAP_NORESERVE;
1151
1152 /*
1153 * If this is a read-only mapping whose contents are
1154 * entirely contained within the file, then use MAP_NORESERVE.
1155 * The assumption is that the pages already exist in the
1156 * page cache for the hugetlbfs file since it was prepared
1157 * earlier and that mprotect() will not be called which would
1158 * require a COW
1159 */
1160 if (!(seg[i].prot & PROT_WRITE) &&
1161 seg[i].filesz == seg[i].memsz)
1162 mmap_flags |= MAP_NORESERVE;
1163
1164 p = mmap((void *) start, mapsize, seg[i].prot,
1165 mmap_flags, seg[i].fd, 0);
1166 if (p == MAP_FAILED)
1167 unmapped_abort("Failed to map hugepage segment %u: "
1168 "%p-%p (errno=%u)\n", i, start,
1169 start + mapsize, errno);
1170 if (p != (void *) start)
1171 unmapped_abort("Mapped hugepage segment %u (%p-%p) at "
1172 "wrong address %p\n", i, seg[i].vaddr,
1173 seg[i].vaddr+mapsize, p);
1174 }
1175 /* The segments are all back at this point.
1176 * and it should be safe to reference static data
1177 */
1178 }
1179
1180 static int set_hpage_sizes(const char *env)
1181 {
1182 char *pos;
1183 long size;
1184 char *key;
1185 char keys[5] = { "R\0" "W\0" "\0" };
1186
1187 /* For each key in R,W */
1188 for (key = keys; *key != '\0'; key += 2) {
1189 pos = strcasestr(env, key);
1190 if (!pos)
1191 continue;
1192
1193 if (*(++pos) == '=') {
1194 size = parse_page_size(pos + 1);
1195 if (size == -1)
1196 return size;
1197 } else
1198 size = gethugepagesize();
1199
1200 if (size <= 0) {
1201 if (errno == ENOSYS)
1202 WARNING("Hugepages unavailable\n");
1203 else if (errno == EOVERFLOW)
1204 WARNING("Hugepage size too large\n");
1205 else
1206 WARNING("Hugepage size (%s)\n",
1207 strerror(errno));
1208 size = 0;
1209 } else if (!hugetlbfs_find_path_for_size(size)) {
1210 WARNING("Hugepage size %li unavailable", size);
1211 size = 0;
1212 }
1213
1214 if (*key == 'R')
1215 hpage_readonly_size = size;
1216 else
1217 hpage_writable_size = size;
1218 }
1219 return 0;
1220 }
1221
1222 static int check_env(void)
1223 {
1224 extern Elf_Ehdr __executable_start __attribute__((weak));
1225
1226 if (__hugetlb_opts.elfmap &&
1227 (strcasecmp(__hugetlb_opts.elfmap, "no") == 0)) {
1228 INFO("HUGETLB_ELFMAP=%s, not attempting to remap program "
1229 "segments\n", __hugetlb_opts.elfmap);
1230 return -1;
1231 }
1232 if (__hugetlb_opts.elfmap && set_hpage_sizes(__hugetlb_opts.elfmap)) {
1233 WARNING("Cannot set elfmap page sizes: %s", strerror(errno));
1234 return -1;
1235 }
1236
1237 if (__hugetlb_opts.ld_preload &&
1238 strstr(__hugetlb_opts.ld_preload, "libhugetlbfs")) {
1239 if (__hugetlb_opts.force_elfmap) {
1240 force_remap = 1;
1241 INFO("HUGETLB_FORCE_ELFMAP=yes, "
1242 "enabling partial segment "
1243 "remapping for non-relinked "
1244 "binaries\n");
1245 INFO("Disabling filesz copy optimization\n");
1246 __hugetlb_opts.min_copy = false;
1247 } else {
1248 if (&__executable_start) {
1249 WARNING("LD_PRELOAD is incompatible with "
1250 "segment remapping\n");
1251 WARNING("Segment remapping has been "
1252 "DISABLED\n");
1253 return -1;
1254 }
1255 }
1256 }
1257
1258 if (__hugetlb_opts.sharing == 2) {
1259 WARNING("HUGETLB_SHARE=%d, however sharing of writable\n"
1260 "segments has been deprecated and is now disabled\n",
1261 __hugetlb_opts.sharing);
1262 __hugetlb_opts.sharing = 0;
1263 } else {
1264 INFO("HUGETLB_SHARE=%d, sharing ", __hugetlb_opts.sharing);
1265 if (__hugetlb_opts.sharing == 1) {
1266 INFO_CONT("enabled for only read-only segments\n");
1267 } else {
1268 INFO_CONT("disabled\n");
1269 __hugetlb_opts.sharing = 0;
1270 }
1271 }
1272
1273 INFO("HUGETLB_NO_RESERVE=%s, reservations %s\n",
1274 __hugetlb_opts.no_reserve ? "yes" : "no",
1275 __hugetlb_opts.no_reserve ? "disabled" : "enabled");
1276
1277 return 0;
1278 }
1279
1280 /*
1281 * Parse an ELF header and record segment information for any segments
1282 * which contain hugetlb information.
1283 */
1284 static int parse_elf()
1285 {
1286 if (force_remap)
1287 dl_iterate_phdr(parse_elf_partial, NULL);
1288 else
1289 dl_iterate_phdr(parse_elf_normal, NULL);
1290
1291 if (htlb_num_segs == 0) {
1292 INFO("No segments were appropriate for remapping\n");
1293 return -1;
1294 }
1295
1296 return 0;
1297 }
1298
1299 void hugetlbfs_setup_elflink(void)
1300 {
1301 int i, ret;
1302
1303 if (check_env())
1304 return;
1305
1306 if (parse_elf())
1307 return;
1308
1309 INFO("libhugetlbfs version: %s\n", VERSION);
1310
1311 /* Do we need to find a share directory */
1312 if (__hugetlb_opts.sharing) {
1313 /*
1314 * If HUGETLB_ELFMAP is undefined but a shareable segment has
1315 * PF_LINUX_HUGETLB set, segment remapping will occur using the
1316 * default huge page size.
1317 */
1318 long page_size = hpage_readonly_size ?
1319 hpage_readonly_size : gethugepagesize();
1320
1321 ret = find_or_create_share_path(page_size);
1322 if (ret != 0) {
1323 WARNING("Segment remapping is disabled");
1324 return;
1325 }
1326 }
1327
1328 /* Step 1. Obtain hugepage files with our program data */
1329 for (i = 0; i < htlb_num_segs; i++) {
1330 ret = obtain_prepared_file(&htlb_seg_table[i]);
1331 if (ret < 0) {
1332 WARNING("Failed to setup hugetlbfs file for segment "
1333 "%d\n", i);
1334
1335 /* Close files we have already prepared */
1336 for (i--; i >= 0; i--)
1337 close(htlb_seg_table[i].fd);
1338
1339 return;
1340 }
1341 }
1342
1343 /* Step 3. Unmap the old segments, map in the new ones */
1344 remap_segments(htlb_seg_table, htlb_num_segs);
1345 }