net.c 15.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
 * Copyright 2021 Max Planck Institute for Software Systems, and
 * National University of Singapore
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

25
#include "dist/common/net.h"
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#include <assert.h>
#include <fcntl.h>
#include <getopt.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/mman.h>
#include <unistd.h>

#include <simbricks/proto/base.h>

41
#include "dist/common/utils.h"
42

43
44
static const uint64_t kPollReportThreshold = 128;
static const uint64_t kCleanReportThreshold = 128;
45
static const uint64_t kPollMax = 8;
46
static const uint64_t kCleanupMax = 16;
47

48
49
static size_t shm_size;
void *shm_base;
50
51
52
53
54
55
static int shm_fd = -1;
static size_t shm_alloc_off = 0;

size_t peer_num = 0;
struct Peer *peers = NULL;

56
static int epfd = -1;
57

58
59
60
61
62
63
64
65
int NetInit(const char *shm_path_, size_t shm_size_, int epfd_) {
  shm_size = shm_size_;
  if ((shm_fd = ShmCreate(shm_path_, shm_size_, &shm_base)) < 0)
    return 1;

  epfd = epfd_;
  return 0;
}
66

67
static int ShmAlloc(size_t size, uint64_t *off) {
68
69
70
71
#ifdef DEBUG
  fprintf(stderr, "ShmAlloc(%zu)\n", size);
#endif

72
73
74
75
76
77
78
79
80
81
  if (shm_alloc_off + size > shm_size) {
    fprintf(stderr, "ShmAlloc: alloc of %zu bytes failed\n", size);
    return 1;
  }

  *off = shm_alloc_off;
  shm_alloc_off += size;
  return 0;
}

82
bool NetPeerAdd(const char *path, bool dev) {
83
84
  struct Peer *peer = realloc(peers, sizeof(*peers) * (peer_num + 1));
  if (!peer) {
85
    perror("NetPeerAdd: realloc failed");
86
87
88
89
90
91
    return false;
  }
  peers = peer;
  peer += peer_num;
  peer_num++;

92
  memset(peer, 0, sizeof(*peer));
93
  if (!(peer->sock_path = strdup(path))) {
94
    perror("NetPeerAdd: strdup failed");
95
96
97
98
99
100
101
102
103
    return false;
  }
  peer->is_dev = dev;
  peer->sock_fd = -1;
  peer->shm_fd = -1;
  return true;
}


104
int NetListen() {
105
106
107
108
#ifdef DEBUG
  fprintf(stderr, "Creating net listening sockets\n");
#endif

109
110
111
112
113
  for (size_t i = 0; i < peer_num; i++) {
    struct Peer *peer = &peers[i];
    if (peer->is_dev)
      continue;

114
115
116
117
#ifdef DEBUG
    fprintf(stderr, "  Creating socket %s %zu\n", peer->sock_path, i);
#endif
    if ((peer->listen_fd = UxsocketInit(peer->sock_path)) < 0) {
118
119
120
121
122
123
124
      perror("PeersInitNets: unix socket init failed");
      return 1;
    }

    struct epoll_event epev;
    epev.events = EPOLLIN;
    epev.data.ptr = peer;
125
126
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, peer->listen_fd, &epev)) {
      perror("PeersInitNets: epoll_ctl accept failed");
127
128
129
      return 1;
    }
  }
130
131
132
133

#ifdef DEBUG
  fprintf(stderr, "PeerInitNets done\n");
#endif
134
135
136
  return 0;
}

137
int NetConnect() {
138
139
140
141
#ifdef DEBUG
  fprintf(stderr, "Connecting to device sockets\n");
#endif

142
143
144
145
146
  for (size_t i = 0; i < peer_num; i++) {
    struct Peer *peer = &peers[i];
    if (!peer->is_dev)
      continue;

147
148
149
150
#ifdef DEBUG
    fprintf(stderr, "  Connecting to socket %s %zu\n", peer->sock_path, i);
#endif

151
152
153
154
155
156
157
158
159
160
161
162
163
164
    if ((peer->sock_fd = UxsocketConnect(peer->sock_path)) < 0)
      return 1;

    struct epoll_event epev;
    epev.events = EPOLLIN;
    epev.data.ptr = peer;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, peer->sock_fd, &epev)) {
      perror("PeersInitNets: epoll_ctl failed");
      return 1;
    }
  }
  return 0;
}

165
int NetPeerSendDevIntro(struct Peer *peer) {
166
#ifdef DEBUG
167
  fprintf(stderr, "PeerDevSendIntro(%s)\n", peer->sock_path);
168
#endif
169
170

  struct SimbricksProtoNetDevIntro *di = &peer->dev_intro;
171
  peer->local_base = (void *) ((uintptr_t) peer->shm_base + di->d2n_offset);
172
173
174
  peer->local_elen = di->d2n_elen;
  peer->local_enum = di->d2n_nentries;

175
176
177
178
  peer->cleanup_base = (void *) ((uintptr_t) peer->shm_base + di->n2d_offset);
  peer->cleanup_elen = di->n2d_elen;
  peer->cleanup_enum = di->n2d_nentries;

179
180
181
182
183
184
185
186
187
188
189
190
  struct SimbricksProtoNetNetIntro *ni = &peer->net_intro;
  ssize_t ret = send(peer->sock_fd, ni, sizeof(*ni), 0);
  if (ret < 0) {
    perror("PeerDevSendIntro: send failed");
    return 1;
  } else if (ret != (ssize_t) sizeof(*ni)) {
    fprintf(stderr, "PeerDevSendIntro: send incomplete\n");
    return 1;
  }
  return 0;
}

191
int NetPeerSetupNetQueues(struct Peer *peer) {
192
193
  struct SimbricksProtoNetDevIntro *di = &peer->dev_intro;

194
#ifdef DEBUG
195
  fprintf(stderr, "PeerNetSetupQueues(%s)\n", peer->sock_path);
196
197
  fprintf(stderr, "  d2n_el=%lu d2n_n=%lu n2d_el=%lu n2d_n=%lu\n", di->d2n_elen,
      di->d2n_nentries, di->n2d_elen, di->n2d_nentries);
198
#endif
199
200
201
202
203

  if (ShmAlloc(di->d2n_elen * di->d2n_nentries, &di->d2n_offset)) {
    fprintf(stderr, "PeerNetSetupQueues: ShmAlloc d2n failed");
    return 1;
  }
204
  if (ShmAlloc(di->n2d_elen * di->n2d_nentries, &di->n2d_offset)) {
205
206
207
208
209
210
211
212
213
214
    fprintf(stderr, "PeerNetSetupQueues: ShmAlloc n2d failed");
    return 1;
  }
  peer->shm_fd = shm_fd;
  peer->shm_base = shm_base;

  peer->local_base = (void *) ((uintptr_t) shm_base + di->n2d_offset);
  peer->local_elen = di->n2d_elen;
  peer->local_enum = di->n2d_nentries;

215
216
217
218
  peer->cleanup_base = (void *) ((uintptr_t) shm_base + di->d2n_offset);
  peer->cleanup_elen = di->d2n_elen;
  peer->cleanup_enum = di->d2n_nentries;

219
220
221
222
223
224
225
226
227
228
229
  if (peer->sock_fd == -1) {
    /* We can receive the welcome message from our peer before our local
       connection to the simulator is established. In this case we hold the
       message till the connection is established and send it then. */
#ifdef DEBUG
    fprintf(stderr, "PeerNetSetupQueues: socket not ready yet, delaying "
        "send\n");
#endif
    return 0;
  }

230
231
232
233
234
235
236
237
  if (UxsocketSendFd(peer->sock_fd, di, sizeof(*di), peer->shm_fd)) {
    fprintf(stderr, "PeerNetSetupQueues: sending welcome message failed (%lu)",
            peer - peers);
    return 1;
  }
  return 0;
}

238
int NetPeerReport(struct Peer *peer, uint32_t written_pos, uint32_t clean_pos) {
239
  uint32_t pos = peer->local_pos_cleaned;
240
  if (written_pos == peer->cleanup_pos_last &&
241
      clean_pos == pos)
242
243
    return 0;

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
  // make sure there are not suddenly fewer entries to be cleaned up
  uint32_t n_before = (peer->cleanup_pos_reported <= peer->cleanup_pos_last ?
      peer->cleanup_pos_last - peer->cleanup_pos_reported :
      peer->cleanup_enum - peer->cleanup_pos_reported + peer->cleanup_pos_last);
  uint32_t n_after = (peer->cleanup_pos_reported <= written_pos ?
      written_pos - peer->cleanup_pos_reported :
      peer->cleanup_enum - peer->cleanup_pos_reported + written_pos);
  if (n_before > n_after) {
    fprintf(stderr, "PeerReport: BUG fewer entries to clean up after report: "
          "peer %s written %u -> %u, cleaned %u -> %u\n",
          peer->sock_path, peer->cleanup_pos_last, written_pos,
          peer->local_pos_cleaned, clean_pos);
    abort();
  }

  // make sure clean pos is between l_p_c and l_p_r
  if (((peer->local_pos_cleaned <= peer->local_pos_reported) &&
          (clean_pos < peer->local_pos_cleaned ||
            clean_pos > peer->local_pos_reported)) ||
      ((peer->local_pos_cleaned > peer->local_pos_reported) &&
          (clean_pos > peer->local_pos_reported &&
           clean_pos < peer->local_pos_cleaned))) {
    fprintf(stderr, "PeerReport: BUG invalid last clean position report: "
          "peer %s written %u -> %u, cleaned %u -> %u (lpr=%u)\n",
          peer->sock_path, peer->cleanup_pos_last, written_pos,
          peer->local_pos_cleaned, clean_pos, peer->local_pos_reported);
    abort();
  }

273
274
275
276
277
278
279
#ifdef DEBUG
  fprintf(stderr, "PeerReport: peer %s written %u -> %u, cleaned %u -> %u\n",
          peer->sock_path, peer->cleanup_pos_last, written_pos,
          peer->local_pos_cleaned, clean_pos);
#endif

  peer->cleanup_pos_last = written_pos;
280
281
  while (pos != clean_pos) {
    void *entry = (peer->local_base + pos * peer->local_elen);
282
283
284
285
286
287
288
289
    if (peer->is_dev) {
      struct SimbricksProtoNetD2NDummy *d2n = entry;
      d2n->own_type = SIMBRICKS_PROTO_NET_D2N_OWN_DEV;
    } else {
      struct SimbricksProtoNetN2DDummy *n2d = entry;
      n2d->own_type = SIMBRICKS_PROTO_NET_N2D_OWN_NET;
    }

290
291
292
    pos += 1;
    if (pos >= peer->local_enum)
      pos -= peer->local_enum;
293
  }
294
  peer->local_pos_cleaned = pos;
295
296
297
298

  return 0;
}

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
static int PeerAcceptEvent(struct Peer *peer) {
#ifdef DEBUG
  fprintf(stderr, "PeerAcceptEvent(%s)\n", peer->sock_path);
#endif
  assert(!peer->is_dev);

  if ((peer->sock_fd = accept(peer->listen_fd, NULL, NULL)) < 0) {
    perror("PeersInitNets: accept failed");
    return 1;
  }

#ifdef DEBUG
  fprintf(stderr, "Accepted %zu\n", peer - peers);
#endif

  close(peer->listen_fd);

  struct epoll_event epev;
  epev.events = EPOLLIN;
  epev.data.ptr = peer;
  if (epoll_ctl(epfd, EPOLL_CTL_ADD, peer->sock_fd, &epev)) {
    perror("PeersInitNets: epoll_ctl failed");
    return 1;
  }

  /* we may have already received the welcome message from our remote peer. In
     that case, send it now. */
  if (peer->intro_valid_remote) {
#ifdef DEBUG
    fprintf(stderr, "PeerAcceptEvent(%s): sending welcome message\n",
        peer->sock_path);
#endif
    if (UxsocketSendFd(peer->sock_fd, &peer->dev_intro, sizeof(peer->dev_intro),
                       peer->shm_fd)) {
      fprintf(stderr, "PeerAcceptEvent: sending welcome message failed (%lu)",
              peer - peers);
      return 1;
    }
  }
  return 0;
}

341
int NetPeerEvent(struct Peer *peer, uint32_t events) {
342
#ifdef DEBUG
343
  fprintf(stderr, "PeerEvent(%s)\n", peer->sock_path);
344
#endif
345
346
347
348
349
350
351
352
353

  // disable peer if not an input event
  if (!(events & EPOLLIN)) {
    fprintf(stderr, "PeerEvent: non-input event, disabling peer (%s)",
            peer->sock_path);
    peer->ready = false;
    return 1;
  }

354
355
356
357
358
  // if peer is network and not yet connected, this is an accept event
  if (!peer->is_dev && peer->sock_fd == -1) {
    return PeerAcceptEvent(peer);
  }

359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
  // if we already have the intro, this is not expected
  if (peer->intro_valid_local) {
    fprintf(stderr, "PeerEvent: receive event after intro (%s)\n",
            peer->sock_path);
    return 1;
  }

  // receive intro message
  if (peer->is_dev) {
    if (UxsocketRecvFd(peer->sock_fd, &peer->dev_intro, sizeof(peer->dev_intro),
                       &peer->shm_fd))
      return 1;

    if (!(peer->shm_base = ShmMap(peer->shm_fd, &peer->shm_size)))
      return 1;
  } else {
    ssize_t ret = recv(peer->sock_fd, &peer->net_intro, sizeof(peer->net_intro),
                       0);
    if (ret < 0) {
      perror("PeerEvent: recv failed");
      return 1;
    } else if (ret != (ssize_t) sizeof(peer->net_intro)) {
      fprintf(stderr, "PeerEvent: partial receive (%zd)\n", ret);
      return 1;
    }
  }

  peer->intro_valid_local = true;

388
389
  // pass intro along
  if (NetOpPassIntro(peer))
390
391
392
    return 1;

  if (peer->intro_valid_remote) {
393
394
395
#ifdef DEBUG
    fprintf(stderr, "PeerEvent(%s): marking peer as ready\n", peer->sock_path);
#endif
396
397
398
399
400
    peer->ready = true;
  }
  return 0;
}

401
402
403
static inline void PollPeerTransfer(struct Peer *peer, bool *report) {
  // XXX: consider batching this to forward multiple entries at once if possible

404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
  size_t n;
  for (n = 0; n < kPollMax && peer->local_pos + n < peer->local_enum; n++) {
    void *entry = (peer->local_base + (peer->local_pos + n) * peer->local_elen);
    bool ready;
    if (peer->is_dev) {
      struct SimbricksProtoNetD2NDummy *d2n = entry;
      ready = (d2n->own_type & SIMBRICKS_PROTO_NET_D2N_OWN_MASK) ==
          SIMBRICKS_PROTO_NET_D2N_OWN_NET;
    } else {
      struct SimbricksProtoNetN2DDummy *n2d = entry;
      ready = (n2d->own_type & SIMBRICKS_PROTO_NET_N2D_OWN_MASK) ==
          SIMBRICKS_PROTO_NET_N2D_OWN_DEV;
    }
    if (!ready)
      break;
419
420
  }

421
  if (n > 0) {
422
    NetOpPassEntries(peer, peer->local_pos, n);
423
    peer->local_pos += n;
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    if (peer->local_pos >= peer->local_enum)
      peer->local_pos -= peer->local_enum;

    uint64_t unreported = (peer->local_pos - peer->local_pos_reported) %
                          peer->local_enum;
    if (unreported >= kPollReportThreshold)
      *report = true;
  }
}

static inline void PollPeerCleanup(struct Peer *peer, bool *report) {
  if (peer->cleanup_pos_next == peer->cleanup_pos_last)
    return;

438
439
440
441
442
443
444
445
446
447
448
449
450
451
  bool ready;
  uint64_t cnt = 0;
  do {
    void *entry =
        (peer->cleanup_base + peer->cleanup_pos_next * peer->cleanup_elen);
    if (peer->is_dev) {
      struct SimbricksProtoNetN2DDummy *n2d = entry;
      ready = (n2d->own_type & SIMBRICKS_PROTO_NET_N2D_OWN_MASK) ==
          SIMBRICKS_PROTO_NET_N2D_OWN_NET;
    } else {
      struct SimbricksProtoNetD2NDummy *d2n = entry;
      ready = (d2n->own_type & SIMBRICKS_PROTO_NET_D2N_OWN_MASK) ==
          SIMBRICKS_PROTO_NET_D2N_OWN_DEV;
    }
452

453
454
455
456
    if (!ready)
      break;

  #ifdef DEBUG
457
458
459
460
461
462
    fprintf(stderr, "PollPeerCleanup: peer %s has clean entry at %u\n",
            peer->sock_path, peer->cleanup_pos_next);
#endif
    peer->cleanup_pos_next += 1;
    if (peer->cleanup_pos_next >= peer->cleanup_enum)
      peer->cleanup_pos_next -= peer->cleanup_enum;
463
464
  } while (++cnt <= kCleanupMax &&
           peer->cleanup_pos_next != peer->cleanup_pos_last);
465

466
  if (cnt > 0) {
467
468
469
470
471
472
473
    uint64_t unreported = (peer->cleanup_pos_next - peer->cleanup_pos_reported)
                          % peer->cleanup_enum;
    if (unreported >= kCleanReportThreshold)
      *report = true;
  }
}

474
475
476
477
478
479
void NetPoll() {
  bool report = false;
  for (size_t i = 0; i < peer_num; i++) {
    struct Peer *peer = &peers[i];
    if (!peer->ready)
      continue;
480

481
482
    PollPeerTransfer(peer, &report);
    PollPeerCleanup(peer, &report);
483
484
  }

485
486
  if (report)
    NetOpPassReport();
487
488
489
490
}

void NetEntryReceived(struct Peer *peer, uint32_t pos, void *data)
{
491
492
493
494
495
496
497
498
499
500
501
502
  // validate position for debugging:
  if ((peer->cleanup_pos_reported <= peer->cleanup_pos_last &&
        (pos >= peer->cleanup_pos_reported && pos < peer->cleanup_pos_last)) ||
      (peer->cleanup_pos_reported > peer->cleanup_pos_last &&
        (pos >= peer->cleanup_pos_reported ||
         pos < peer->cleanup_pos_last))) {
    fprintf(stderr, "NetEntryReceived: BUG position %u is in window to be "
            "cleaned %u -> %u", pos, peer->cleanup_pos_reported,
            peer->cleanup_pos_last);
    abort();
  }

503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
  uint64_t off = (uint64_t) pos * peer->cleanup_elen;
  void *entry = peer->cleanup_base + off;

  if (peer->is_dev) {
    struct SimbricksProtoNetD2NDummy *d2n = entry;
    // first copy data after header
    memcpy(d2n + 1, (uint8_t *) data + sizeof(*d2n),
           peer->cleanup_elen - sizeof(*d2n));
    // then copy header except for last byte
    memcpy(entry, data, sizeof(*d2n) - 1);
    // WMB()
    // now copy last byte
    struct SimbricksProtoNetD2NDummy *src_d2n = data;
    d2n->own_type = src_d2n->own_type;
  } else {
    struct SimbricksProtoNetN2DDummy *n2d = entry;
    // first copy data after header
    memcpy(n2d + 1, (uint8_t *) data + sizeof(*n2d),
           peer->cleanup_elen - sizeof(*n2d));
    // then copy header except for last byte
    memcpy(entry, data, sizeof(*n2d) - 1);
    // WMB()
    // now copy last byte
    struct SimbricksProtoNetN2DDummy *src_n2d = data;
    n2d->own_type = src_n2d->own_type;
  }
529
}