File: userfault-map.c

package info (click to toggle)
libnbd 1.22.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,636 kB
  • sloc: ansic: 53,855; ml: 12,311; sh: 8,499; python: 4,595; makefile: 2,902; perl: 165; cpp: 24
file content (302 lines) | stat: -rw-r--r-- 7,784 bytes parent folder | download | duplicates (2)
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
/* This example shows how to memory map a drive using userfaultfd(2)
 * to map in pages which are read from the remote disk using libnbd.
 *
 * Because it is an example, we just compute a simple histogram over
 * the data to prove it works, but a real program could do something
 * else with the memory-mapped drive.  A real program also ought to
 * handle userfaultfd events in parallel, and use nbd_aio_* operations
 * to better utilise the NBD socket.
 *
 * It requires Linux >= 4.11.  On other platforms it will print an
 * error instead.
 *
 * To try out this example with nbdkit:
 *
 *   nbdkit -U - random 1M --run './userfault-map $uri'
 *
 * (set LIBNBD_DEBUG=1 for more detail)
 */

#include "config.h" /* For HAVE_* macros below */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <unistd.h>

#ifdef HAVE_SYS_SYSCALL_H
#include <sys/syscall.h>
#endif

#if !defined(HAVE_SYS_SYSCALL_H) ||               \
    !defined(HAVE_LINUX_USERFAULTFD_H) ||         \
    !defined(__NR_userfaultfd)

int
main (int argc, char *argv[])
{
  fprintf (stderr, "%s: This program requires Linux >= 4.11\n", argv[0]);
  exit (EXIT_FAILURE);
}

#else

/* Here we can assume this is Linux so we don't need to use autoconf
 * portability macros.
 */

#include <fcntl.h>
#include <errno.h>
#include <assert.h>
#include <pthread.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <linux/userfaultfd.h>

#include <libnbd.h>

static struct nbd_handle *nbd;  /* libnbd handle. */
static int fd;                  /* Userfault file descriptor. */
static long page_size;          /* Machine page size. */
static int64_t size;            /* Size in bytes. */
static int64_t size_aligned;    /* Rounded up to next page size boundary. */
static void *memory;            /* Memory mapped drive. */

/* Background thread which handles userfaultfd events. */
static pthread_t thread;
static pthread_barrier_t barrier;
static void *handle_event (void *);

static void histogram (char *, size_t);

int
main (int argc, char *argv[])
{
  struct uffdio_api uffdio_api;
  struct uffdio_register uffdio_register;
  int err;

  if (argc != 2) {
    fprintf (stderr, "%s NBDURI\n", argv[0]);
    exit (EXIT_FAILURE);
  }

  /* Check we can use userfaultfd. */
  page_size = sysconf (_SC_PAGESIZE);
  if (page_size == -1) {
    perror ("sysconf");
    exit (EXIT_FAILURE);
  }
  assert (page_size > 0);

  fd = syscall (__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
  if (fd == -1) {
    perror ("userfaultfd");
    exit (EXIT_FAILURE);
  }

  uffdio_api.api = UFFD_API;
  uffdio_api.features = 0;
  if (ioctl (fd, UFFDIO_API, &uffdio_api) == -1) {
    perror ("ioctl: UFFDIO_API");
    exit (EXIT_FAILURE);
  }

  if (uffdio_api.api != UFFD_API) {
    fprintf (stderr, "%s: unsupported userfaultfd API %lld != %lld\n",
             argv[0], uffdio_api.api, UFFD_API);
    exit (EXIT_FAILURE);
  }

  /* Create the libnbd handle. */
  nbd = nbd_create ();
  if (nbd == NULL) {
    fprintf (stderr, "%s\n", nbd_get_error ());
    exit (EXIT_FAILURE);
  }

  /* Connect to the server. */
  if (nbd_connect_uri (nbd, argv[1]) == -1) {
    fprintf (stderr, "%s\n", nbd_get_error ());
    exit (EXIT_FAILURE);
  }

  size = nbd_get_size (nbd);
  if (size == -1) {
    fprintf (stderr, "%s\n", nbd_get_error ());
    exit (EXIT_FAILURE);
  }

  size_aligned = (size + page_size - 1) & -page_size;

  printf ("%s: connected to the NBD server\n", argv[0]);
  printf ("remote size (bytes):            %" PRIi64 "\n", size);
  printf ("allocation size (page aligned): %" PRIi64 "\n", size_aligned);
  fflush (stdout);

  /* mmap enough anonymous memory. */
  memory = mmap (NULL, size_aligned, PROT_READ, MAP_PRIVATE|MAP_ANONYMOUS,
                 -1, 0);
  if (memory == MAP_FAILED) {
    perror ("mmap");
    exit (EXIT_FAILURE);
  }

  /* Register the memory with userfaultfd. */
  uffdio_register.range.start = (unsigned long) memory;
  uffdio_register.range.len = size_aligned;
  uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
  if (ioctl (fd, UFFDIO_REGISTER, &uffdio_register) == -1) {
    perror ("ioctl: UFFDIO_REGISTER");
    exit (EXIT_FAILURE);
  }
#if 0
  if ((uffdio_register.ioctls & UFFD_API_RANGE_IOCTLS)
      != UFFD_API_RANGE_IOCTLS) {
    fprintf (stderr, "%s: unexpected userfaultfd ioctl range returned\n",
             argv[0]);
    exit (EXIT_FAILURE);
  }
#endif

  /* We need a background thread to handle userfaultfd events. */
  err = pthread_barrier_init (&barrier, NULL, 2);
  if (err != 0) {
    errno = err;
    perror ("pthread_barrier_init");
    exit (EXIT_FAILURE);
  }
  err = pthread_create (&thread, NULL, handle_event, NULL);
  if (err != 0) {
    errno = err;
    perror ("pthread_create");
    exit (EXIT_FAILURE);
  }

  /* Wait for the background thread to start. */
  pthread_barrier_wait (&barrier);
  pthread_barrier_destroy (&barrier);

  /* Prove you can pass the pointer to another function that works on
   * memory buffers.
   */
  printf ("Calculating byte histogram over drive ...\n");
  fflush (stdout);
  histogram (memory, size);

  /* Destroy the background thread. */
  printf ("Clean up and exit ...\n");
  fflush (stdout);
  pthread_cancel (thread);

  /* Close the libnbd handle. */
  nbd_close (nbd);

  exit (EXIT_SUCCESS);
}

static void *
handle_event (void *vp)
{
  char *buf;
  int oldstate;

  pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, &oldstate);

  buf = malloc (page_size);
  if (buf == NULL) {
    perror ("malloc");
    exit (EXIT_FAILURE);
  }

  /* Ready to serve requests. */
  pthread_barrier_wait (&barrier);

  for (;;) {
    struct uffd_msg msg;
    struct pollfd pollfd[1];
    int r;
    uintptr_t addr;
    uint64_t offset;
    size_t len;
    struct uffdio_copy uffdio_copy;

    pollfd[0].fd = fd;
    pollfd[0].events = POLLIN;

    r = poll (pollfd, 1, -1);
    if (r == -1) {
      perror ("poll");
      exit (EXIT_FAILURE);
    }
    if (r == 0) continue;

    if ((pollfd[0].revents & POLLERR) != 0) {
      fprintf (stderr, "poll: unexpected POLLERR returned\n");
      exit (EXIT_FAILURE);
    }

    if ((pollfd[0].revents & POLLIN) != 0) {
      r = read (fd, &msg, sizeof msg);
      if (r == -1) {
        if (errno == EAGAIN || errno == EWOULDBLOCK)
          continue;
        perror ("read");
        exit (EXIT_FAILURE);
      }

      if (r != sizeof msg) {
        fprintf (stderr, "read: unexpected size of message\n");
        exit (EXIT_FAILURE);
      }

      if (msg.event & UFFD_EVENT_PAGEFAULT) {
        /* Finally, handle the page fault ... */
        addr = msg.arg.pagefault.address;

        /* Read the data from the remote server. */
        offset = addr - (uintptr_t) memory;
        len = page_size;
        if (offset + page_size > size) {
          len -= offset + page_size - size;
          memset (buf, 0, page_size);
        }
        if (nbd_pread (nbd, buf, len, offset, 0)
            == -1) {
          fprintf (stderr, "%s\n", nbd_get_error ());
          exit (EXIT_FAILURE);
        }

        /* Atomically write the result to the memory map.  We can't
         * use memcpy here as explained in AA's talk.
         */
        uffdio_copy.src = (uintptr_t)buf;
        uffdio_copy.dst = addr;
        uffdio_copy.len = page_size;
        uffdio_copy.mode = 0;
        if (ioctl (fd, UFFDIO_COPY, &uffdio_copy) == -1) {
          perror ("ioctl: UFFDIO_COPY");
          exit (EXIT_FAILURE);
        }
      }
    }
  }
}

static void
histogram (char *buf, size_t len)
{
  size_t i;
  int count[256] = { 0 };

  for (i = 0; i < len; ++i)
    count[(int)buf[i]]++;

  printf ("number of zero bytes found in input = %d / %zu\n",
          count[0], len);
}

#endif /* platform supports userfaultfd */