net_switch.cc 13.6 KB
Newer Older
Antoine Kaufmann's avatar
Antoine Kaufmann committed
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 <unistd.h>
Jialin Li's avatar
Jialin Li committed
26
#include <pcap/pcap.h>
27
28
29
#include <linux/ip.h>
#include <linux/if_ether.h>
#include <arpa/inet.h>
30
31
32
33

#include <cassert>
#include <climits>
#include <csignal>
Jialin Li's avatar
Jialin Li committed
34
35
36
#include <cstdio>
#include <cstdlib>
#include <cstring>
37
#include <string>
Jialin Li's avatar
Jialin Li committed
38
#include <unordered_map>
39
#include <vector>
Jialin Li's avatar
Jialin Li committed
40

41
#include <simbricks/base/cxxatomicfix.h>
Jialin Li's avatar
Jialin Li committed
42
extern "C" {
43
#include <simbricks/network/if.h>
44
#include <simbricks/nicif/nicif.h>
Jialin Li's avatar
Jialin Li committed
45
46
};

47
//#define NETSWITCH_DEBUG
Hejing Li's avatar
Hejing Li committed
48
#define NETSWITCH_STAT
49

50
struct SimbricksBaseIfParams netParams;
Jialin Li's avatar
Jialin Li committed
51
static pcap_dumper_t *dumpfile = nullptr;
Jialin Li's avatar
Jialin Li committed
52

Hejing Li's avatar
Hejing Li committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#ifdef NETSWITCH_STAT
#endif

#ifdef NETSWITCH_STAT
static uint64_t d2n_poll_total = 0;
static uint64_t d2n_poll_suc = 0;
static uint64_t d2n_poll_sync = 0;

static uint64_t s_d2n_poll_total = 0;
static uint64_t s_d2n_poll_suc = 0;
static uint64_t s_d2n_poll_sync = 0;

static int stat_flag = 0;
#endif

Jialin Li's avatar
Jialin Li committed
68
69
/* MAC address type */
struct MAC {
70
  const uint8_t *data;
Jialin Li's avatar
Jialin Li committed
71

72
  explicit MAC(const uint8_t *data) : data(data) {
73
  }
Jialin Li's avatar
Jialin Li committed
74

75
76
77
78
79
  bool operator==(const MAC &other) const {
    for (int i = 0; i < 6; i++) {
      if (data[i] != other.data[i]) {
        return false;
      }
Jialin Li's avatar
Jialin Li committed
80
    }
81
82
    return true;
  }
Jialin Li's avatar
Jialin Li committed
83
84
};
namespace std {
Antoine Kaufmann's avatar
Antoine Kaufmann committed
85
template <>
86
87
struct hash<MAC> {
  size_t operator()(const MAC &m) const {
Antoine Kaufmann's avatar
Antoine Kaufmann committed
88
89
    size_t res = 0;
    for (int i = 0; i < 6; i++) {
90
      res = (res << 4) | (res ^ m.data[i]);
Antoine Kaufmann's avatar
Antoine Kaufmann committed
91
92
    }
    return res;
93
  }
Antoine Kaufmann's avatar
Antoine Kaufmann committed
94
95
};
}  // namespace std
Jialin Li's avatar
Jialin Li committed
96

97

98
99
/** Normal network switch port (conneting to a NIC) */
class NetPort {
100
101
102
103
104
105
 public:
  enum RxPollState {
    kRxPollSuccess = 0,
    kRxPollFail = 1,
    kRxPollSync = 2,
  };
106
  struct SimbricksNetIf netif_;
107

108
 protected:
109
  volatile union SimbricksProtoNetMsg *rx_;
110
  int sync_;
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
  const char *path_;

  bool Init() {
    struct SimbricksBaseIfParams params = netParams;
    params.sync_mode = (sync_ ? kSimbricksBaseIfSyncOptional
                              : kSimbricksBaseIfSyncDisabled);
    params.sock_path = path_;
    params.blocking_conn = false;

    if (SimbricksBaseIfInit(&netif_.base, &params)) {
      perror("Init: SimbricksBaseIfInit failed");
      return false;
    }

    return true;
  }
127
128

 public:
129
130
  NetPort(const char *path, int sync) : rx_(nullptr), sync_(sync), path_(path) {
    memset(&netif_, 0, sizeof(netif_));
131
132
  }

133
134
135
136
137
138
139
140
141
142
143
144
145
146
  NetPort(const NetPort &other) : netif_(other.netif_),
      rx_(other.rx_), sync_(other.sync_), path_(other.path_) {}

  virtual bool Prepare() {
    if (!Init())
      return false;

    if (SimbricksBaseIfConnect(&netif_.base)) {
      perror("Prepare: SimbricksBaseIfConnect failed");
      return false;
    }

    return true;
  }
147

148
149
  virtual void Prepared() {
    sync_ = SimbricksBaseIfSyncEnabled(&netif_.base);
150
151
  }

152
  bool IsSync() {
153
154
155
    return sync_;
  }

156
157
  void Sync(uint64_t cur_ts) {
    while (SimbricksNetIfOutSync(&netif_, cur_ts));
158
159
  }

160
161
  uint64_t NextTimestamp() {
    return SimbricksNetIfInTimestamp(&netif_);
162
163
  }

164
165
  enum RxPollState RxPacket(
      const void *& data, size_t &len, uint64_t cur_ts) {
166
167
    assert(rx_ == nullptr);

168
    rx_ = SimbricksNetIfInPoll(&netif_, cur_ts);
169
170
171
    if (!rx_)
      return kRxPollFail;

172
    uint8_t type = SimbricksNetIfInType(&netif_, rx_);
173
174
175
    if (type == SIMBRICKS_PROTO_NET_MSG_PACKET) {
      data = (const void *)rx_->packet.data;
      len = rx_->packet.len;
176
      return kRxPollSuccess;
177
    } else if (type == SIMBRICKS_PROTO_MSG_TYPE_SYNC) {
178
179
180
181
182
183
184
      return kRxPollSync;
    } else {
      fprintf(stderr, "switch_pkt: unsupported type=%u\n", type);
      abort();
    }
  }

185
  void RxDone() {
186
187
    assert(rx_ != nullptr);

188
    SimbricksNetIfInDone(&netif_, rx_);
189
190
191
    rx_ = nullptr;
  }

192
193
  bool TxPacket(
      const void *data, size_t len, uint64_t cur_ts) {
194
    volatile union SimbricksProtoNetMsg *msg_to =
195
      SimbricksNetIfOutAlloc(&netif_, cur_ts);
196
    if (!msg_to && !sync_) {
197
      return false;
198
199
    } else if (!msg_to && sync_) {
      while (!msg_to)
200
        msg_to = SimbricksNetIfOutAlloc(&netif_, cur_ts);
201
    }
202
203
    volatile struct SimbricksProtoNetMsgPacket *rx;
    rx = &msg_to->packet;
204
205
206
207
    rx->len = len;
    rx->port = 0;
    memcpy((void *)rx->data, data, len);

208
    SimbricksNetIfOutSend(&netif_, msg_to, SIMBRICKS_PROTO_NET_MSG_PACKET);
209
210
211
212
    return true;
  }
};

213

214
215
/** Listening switch port (connected to by another network) */
class NetListenPort : public NetPort {
216
 protected:
217
  struct SimbricksBaseIfSHMPool pool_;
218
219

 public:
220
221
  NetListenPort(const char *path, int sync) : NetPort(path, sync) {
    memset(&pool_, 0, sizeof(pool_));
222
223
  }

224
225
  NetListenPort(const NetListenPort &other) : NetPort(other),
      pool_(other.pool_) {
226
  }
227

228
229
230
231
232
  virtual bool Prepare() override {
    if (!Init())
      return false;

    std::string shm_path = path_;
233
234
    shm_path += "-shm";

235
236
237
238
239
240
241
242
243
244
245
246
    if (SimbricksBaseIfSHMPoolCreate(&pool_, shm_path.c_str(),
          SimbricksBaseIfSHMSize(&netif_.base.params)) != 0) {
      perror("Prepare: SimbricksBaseIfSHMPoolCreate failed");
      return false;
    }

    if (SimbricksBaseIfListen(&netif_.base, &pool_) != 0) {
      perror("Prepare: SimbricksBaseIfListen failed");
      return false;
    }

    return true;
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
static bool ConnectAll(std::vector<NetPort *> ports)
{
  size_t n = ports.size();
  struct SimBricksBaseIfEstablishData ests[n];
  struct SimbricksProtoNetIntro intro;

  printf("start connecting...\n");
  for (size_t i = 0; i < n; i++) {
    NetPort *p = ports[i];
    ests[i].base_if = &p->netif_.base;
    ests[i].tx_intro = &intro;
    ests[i].tx_intro_len = sizeof(intro);
    ests[i].rx_intro = &intro;
    ests[i].rx_intro_len = sizeof(intro);

    if (!p->Prepare())
      return false;
  }

 if (SimBricksBaseIfEstablish(ests, n)) {
   fprintf(stderr, "ConnectAll: SimBricksBaseIfEstablish failed\n");
   return false;
 }

  printf("done connecting\n");
  return true;
}
277

Jialin Li's avatar
Jialin Li committed
278
279
280
/* Global variables */
static uint64_t cur_ts = 0;
static int exiting = 0;
281
static const uint8_t bcast[6] = {0xFF};
Jialin Li's avatar
Jialin Li committed
282
static const MAC bcast_addr(bcast);
283
static std::vector<NetPort *> ports;
Jialin Li's avatar
Jialin Li committed
284
285
static std::unordered_map<MAC, int> mac_table;

286
287
static void sigint_handler(int dummy) {
  exiting = 1;
Jialin Li's avatar
Jialin Li committed
288
289
}

Hejing Li's avatar
Hejing Li committed
290
291
static void sigusr1_handler(int dummy) {
  fprintf(stderr, "main_time = %lu\n", cur_ts);
292
293
294
295
296
297
298
299
300
301
  size_t n = ports.size();
    for (size_t i = 0; i < n; i++) {
    NetPort *p = ports[i];
    uint64_t in_timestamp = p->netif_.base.in_timestamp;
    uint64_t out_timestamp = p->netif_.base.out_timestamp;

    fprintf(stderr, "[ ports %lu ]: in_timestamp == %lu\n", i, in_timestamp);
    fprintf(stderr, "[ ports %lu ]: out_timestamp == %lu\n", i, out_timestamp);
  }

Hejing Li's avatar
Hejing Li committed
302
303
304
305
306
307
308
309
}

#ifdef NETSWITCH_STAT
static void sigusr2_handler(int dummy) {
  stat_flag = 1;
}
#endif

310
311
static void forward_pkt(const void *pkt_data, size_t pkt_len, size_t port_id,
                        size_t iport_id) {
Jialin Li's avatar
Jialin Li committed
312
  struct pcap_pkthdr ph;
313
  NetPort &dest_port = *ports[port_id];
314

Jialin Li's avatar
Jialin Li committed
315
316
317
318
319
  // log to pcap file if initialized
  if (dumpfile) {
      memset(&ph, 0, sizeof(ph));
      ph.ts.tv_sec = cur_ts / 1000000000000ULL;
      ph.ts.tv_usec = (cur_ts % 1000000000000ULL) / 1000ULL;
320
321
322
      ph.caplen = pkt_len;
      ph.len = pkt_len;
      pcap_dump((unsigned char *)dumpfile, &ph, (unsigned char *)pkt_data);
Jialin Li's avatar
Jialin Li committed
323
  }
324
  // print sending tick: [packet type] source_IP -> dest_IP len:
325

326
327
328
329
#ifdef NETSWITCH_DEBUG
  uint16_t eth_proto;
  struct ethhdr *hdr;
  struct iphdr *iph;
330
  hdr = (struct ethhdr*)pkt_data;
331
332
  eth_proto = ntohs(hdr->h_proto);
  iph = (struct iphdr *)(hdr + 1);
333
334
335
336
  uint64_t dmac = (*(uint64_t *) hdr->h_dest) & 0xFFFFFFFFFFULL;
  uint64_t smac = (*(uint64_t *) hdr->h_source) & 0xFFFFFFFFFFULL;
  fprintf(stderr, "%20lu: [P %zu -> %zu] %lx -> %lx ", cur_ts, iport_id,
          port_id, smac, dmac);
337
338
  if (eth_proto == ETH_P_IP){
    fprintf(stderr, "[ IP] ");
339
340
    fprintf(stderr, "%8X -> %8X len: %lu\n", iph->saddr, iph->daddr,
            ntohs(iph->tot_len) + sizeof(struct ethhdr));
341
342
  } 
  else if(eth_proto == ETH_P_ARP){
343
344
345
    fprintf(stderr, "[ARP] %8X -> %8X\n",
            *(uint32_t *) ((uint8_t *) pkt_data + 28),
            *(uint32_t *) ((uint8_t *) pkt_data + 38) );
346
347
  } 
  else{
348
    fprintf(stderr, "unknown eth type\n");
349
350
351
  }
#endif

352
353
  if (!dest_port.TxPacket(pkt_data, pkt_len, cur_ts))
    fprintf(stderr, "forward_pkt: dropping packet on port %zu\n", port_id);
Jialin Li's avatar
Jialin Li committed
354
355
}

356
static void switch_pkt(NetPort &port, size_t iport) {
357
358
359
  const void *pkt_data;
  size_t pkt_len;

Hejing Li's avatar
Hejing Li committed
360
361
362
363
364
365
366
#ifdef NETSWITCH_STAT
  d2n_poll_total += 1;
  if (stat_flag){
    s_d2n_poll_total += 1;
  }
#endif

367
368
  enum NetPort::RxPollState poll = port.RxPacket(pkt_data, pkt_len, cur_ts);
  if (poll == NetPort::kRxPollFail) {
369
370
371
    return;
  }

Hejing Li's avatar
Hejing Li committed
372
373
374
375
376
377
378
#ifdef NETSWITCH_STAT
  d2n_poll_suc += 1;
  if (stat_flag){
    s_d2n_poll_suc += 1;
  }
#endif

379
  if (poll == NetPort::kRxPollSuccess) {
380
    // Get MAC addresses
381
    MAC dst((const uint8_t *)pkt_data), src((const uint8_t *)pkt_data + 6);
382
383
384
    // MAC learning
    if (!(src == bcast_addr)) {
      mac_table[src] = iport;
Jialin Li's avatar
Jialin Li committed
385
    }
386
    // L2 forwarding
387
388
389
    auto i = mac_table.find(dst);
    if (i != mac_table.end()) {
      size_t eport = i->second;
390
      if (eport != iport)
391
        forward_pkt(pkt_data, pkt_len, eport, iport);
Jialin Li's avatar
Jialin Li committed
392
    } else {
393
      // Broadcast
394
      for (size_t eport = 0; eport < ports.size(); eport++) {
395
396
        if (eport != iport) {
          // Do not forward to ingress port
397
          forward_pkt(pkt_data, pkt_len, eport, iport);
398
399
        }
      }
Jialin Li's avatar
Jialin Li committed
400
    }
401
  } else if (poll == NetPort::kRxPollSync) {
Hejing Li's avatar
Hejing Li committed
402
403
404
405
406
407
#ifdef NETSWITCH_STAT
    d2n_poll_sync += 1;
    if (stat_flag){
      s_d2n_poll_sync += 1;
    }
#endif
408
  } else {
409
    fprintf(stderr, "switch_pkt: unsupported poll result=%u\n", poll);
410
411
    abort();
  }
412
  port.RxDone();
Jialin Li's avatar
Jialin Li committed
413
414
}

415
416
417
int main(int argc, char *argv[]) {
  int c;
  int bad_option = 0;
418
  int sync_eth = 1;
Jialin Li's avatar
Jialin Li committed
419
  pcap_t *pc = nullptr;
420

421
422
  SimbricksNetIfDefaultParams(&netParams);

423
  // Parse command line argument
424
  while ((c = getopt(argc, argv, "s:h:uS:E:p:")) != -1 && !bad_option) {
425
426
    switch (c) {
      case 's': {
427
        NetPort *port = new NetPort(optarg, sync_eth);
428
        fprintf(stderr, "Switch connecting to: %s\n", optarg);
429
        ports.push_back(port);
430
431
432
        break;
      }

433
      case 'h': {
434
        NetListenPort *port = new NetListenPort(optarg, sync_eth);
435
436
437
438
439
        fprintf(stderr, "Switch listening on: %s\n", optarg);
        ports.push_back(port);
        break;
      }

440
441
442
443
      case 'u':
        sync_eth = 0;
        break;

444
      case 'S':
445
        netParams.sync_interval = strtoull(optarg, NULL, 0) * 1000ULL;
446
447
448
        break;

      case 'E':
449
        netParams.link_latency = strtoull(optarg, NULL, 0) * 1000ULL;
450
451
        break;

Jialin Li's avatar
Jialin Li committed
452
453
454
455
456
457
458
459
460
461
462
      case 'p':
        pc = pcap_open_dead_with_tstamp_precision(DLT_EN10MB, 65535,
                                                  PCAP_TSTAMP_PRECISION_NANO);
        if (pc == nullptr) {
            perror("pcap_open_dead failed");
            return EXIT_FAILURE;
        }

        dumpfile = pcap_dump_open(pc, optarg);
        break;

463
464
465
466
      default:
        fprintf(stderr, "unknown option %c\n", c);
        bad_option = 1;
        break;
Jialin Li's avatar
Jialin Li committed
467
    }
468
469
  }

470
  if (ports.empty() || bad_option) {
471
472
473
474
475
476
477
478
    fprintf(stderr,
            "Usage: net_switch [-S SYNC-PERIOD] [-E ETH-LATENCY] "
            "-s SOCKET-A [-s SOCKET-B ...]\n");
    return EXIT_FAILURE;
  }

  signal(SIGINT, sigint_handler);
  signal(SIGTERM, sigint_handler);
Hejing Li's avatar
Hejing Li committed
479
480
481
482
483
484
  signal(SIGUSR1, sigusr1_handler);

#ifdef NETSWITCH_STAT
  signal(SIGUSR2, sigusr2_handler);
#endif

485
486
  if (!ConnectAll(ports))
    return EXIT_FAILURE;
487
488
489
490

  printf("start polling\n");
  while (!exiting) {
    // Sync all interfaces
491
492
    for (auto port : ports)
      port->Sync(cur_ts);
493
494
495
496
497

    // Switch packets
    uint64_t min_ts;
    do {
      min_ts = ULLONG_MAX;
498
      for (size_t port_i = 0; port_i < ports.size(); port_i++) {
499
        auto &port = *ports[port_i];
500
501
502
        switch_pkt(port, port_i);
        if (port.IsSync()) {
          uint64_t ts = port.NextTimestamp();
503
          min_ts = ts < min_ts ? ts : min_ts;
Jialin Li's avatar
Jialin Li committed
504
        }
505
506
507
508
509
      }
    } while (!exiting && (min_ts <= cur_ts));

    // Update cur_ts
    if (min_ts < ULLONG_MAX) {
510
      cur_ts = min_ts;
Jialin Li's avatar
Jialin Li committed
511
    }
512
  }
Jialin Li's avatar
Jialin Li committed
513

Hejing Li's avatar
Hejing Li committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
#ifdef NETSWITCH_STAT
  fprintf(stderr, "%20s: %22lu %20s: %22lu  poll_suc_rate: %f\n",
          "d2n_poll_total", d2n_poll_total, "d2n_poll_suc", d2n_poll_suc,
          (double)d2n_poll_suc / d2n_poll_total);
  fprintf(stderr, "%65s: %22lu  sync_rate: %f\n", "d2n_poll_sync",
          d2n_poll_sync, (double)d2n_poll_sync / d2n_poll_suc);

  fprintf(stderr, "%20s: %22lu %20s: %22lu  poll_suc_rate: %f\n",
          "s_d2n_poll_total", s_d2n_poll_total, "s_d2n_poll_suc", s_d2n_poll_suc,
          (double)s_d2n_poll_suc / s_d2n_poll_total);
  fprintf(stderr, "%65s: %22lu  sync_rate: %f\n", "s_d2n_poll_sync",
          s_d2n_poll_sync, (double)s_d2n_poll_sync / s_d2n_poll_suc);
#endif

528
  return 0;
Jialin Li's avatar
Jialin Li committed
529
}