[PATCH] Fix random_map
[fio.git] / memory.c
CommitLineData
2f9ade3c
JA
1/*
2 * Memory helpers
3 */
4#include <unistd.h>
5#include <sys/shm.h>
6#include <sys/mman.h>
7
8#include "fio.h"
9#include "os.h"
10
11extern unsigned long long mlock_size;
12static void *pinned_mem;
13
14void fio_unpin_memory(void)
15{
16 if (pinned_mem) {
17 if (munlock(pinned_mem, mlock_size) < 0)
18 perror("munlock");
19 munmap(pinned_mem, mlock_size);
20 pinned_mem = NULL;
21 }
22}
23
24int fio_pin_memory(void)
25{
26 unsigned long long phys_mem;
27
28 if (!mlock_size)
29 return 0;
30
31 /*
32 * Don't allow mlock of more than real_mem-128MB
33 */
34 phys_mem = os_phys_mem();
35 if (phys_mem) {
36 if ((mlock_size + 128 * 1024 * 1024) > phys_mem) {
37 mlock_size = phys_mem - 128 * 1024 * 1024;
38 fprintf(f_out, "fio: limiting mlocked memory to %lluMiB\n", mlock_size >> 20);
39 }
40 }
41
42 pinned_mem = mmap(NULL, mlock_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
43 if (pinned_mem == MAP_FAILED) {
44 perror("malloc locked mem");
45 pinned_mem = NULL;
46 return 1;
47 }
48 if (mlock(pinned_mem, mlock_size) < 0) {
49 perror("mlock");
50 munmap(pinned_mem, mlock_size);
51 pinned_mem = NULL;
52 return 1;
53 }
54
55 return 0;
56}
57
58/*
59 * Setup the buffer area we need for io.
60 */
61int allocate_io_mem(struct thread_data *td)
62{
63 if (td->mem_type == MEM_MALLOC)
64 td->orig_buffer = malloc(td->orig_buffer_size);
65 else if (td->mem_type == MEM_SHM) {
66 td->shm_id = shmget(IPC_PRIVATE, td->orig_buffer_size, IPC_CREAT | 0600);
67 if (td->shm_id < 0) {
68 td_verror(td, errno);
69 perror("shmget");
70 return 1;
71 }
72
73 td->orig_buffer = shmat(td->shm_id, NULL, 0);
74 if (td->orig_buffer == (void *) -1) {
75 td_verror(td, errno);
76 perror("shmat");
77 td->orig_buffer = NULL;
78 return 1;
79 }
80 } else if (td->mem_type == MEM_MMAP) {
81 td->orig_buffer = mmap(NULL, td->orig_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
82 if (td->orig_buffer == MAP_FAILED) {
83 td_verror(td, errno);
84 perror("mmap");
85 td->orig_buffer = NULL;
86 return 1;
87 }
88 }
89
90 return 0;
91}
92
93void free_io_mem(struct thread_data *td)
94{
95 if (td->mem_type == MEM_MALLOC)
96 free(td->orig_buffer);
97 else if (td->mem_type == MEM_SHM) {
98 struct shmid_ds sbuf;
99
100 shmdt(td->orig_buffer);
101 shmctl(td->shm_id, IPC_RMID, &sbuf);
102 } else if (td->mem_type == MEM_MMAP)
103 munmap(td->orig_buffer, td->orig_buffer_size);
104 else
105 log_err("Bad memory type %d\n", td->mem_type);
106
107 td->orig_buffer = NULL;
108}