Initial import
[sliver-openvswitch.git] / controller / controller.c
1 /* Copyright (C) 2007 Board of Trustees, Leland Stanford Jr. University.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to
5  * deal in the Software without restriction, including without limitation the
6  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7  * sell copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19  * IN THE SOFTWARE.
20  */
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <getopt.h>
25 #include <inttypes.h>
26 #include <netinet/in.h>
27 #include <poll.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #include "buffer.h"
33 #include "command-line.h"
34 #include "compiler.h"
35 #include "fault.h"
36 #include "flow.h"
37 #include "hash.h"
38 #include "list.h"
39 #include "mac.h"
40 #include "ofp-print.h"
41 #include "openflow.h"
42 #include "time.h"
43 #include "util.h"
44 #include "vconn.h"
45 #include "vlog-socket.h"
46 #include "xtoxll.h"
47
48 #include "vlog.h"
49 #define THIS_MODULE VLM_controller
50
51 #define MAX_SWITCHES 16
52 #define MAX_TXQ 128
53
54 struct switch_ {
55     char *name;
56     struct vconn *vconn;
57     struct pollfd *pollfd;
58
59     uint64_t datapath_id;
60     time_t last_control_hello;
61
62     int n_txq;
63     struct buffer *txq, *tx_tail;
64 };
65
66 /* -H, --hub: Use dumb hub instead of learning switch? */
67 static bool hub = false;
68
69 /* -n, --noflow: Pass traffic, but don't setup flows in switch */
70 static bool noflow = false;
71
72 static void parse_options(int argc, char *argv[]);
73 static void usage(void) NO_RETURN;
74
75 static struct switch_ *connect_switch(const char *name);
76 static struct switch_ *new_switch(const char *name, struct vconn *);
77 static void close_switch(struct switch_ *);
78
79 static void queue_tx(struct switch_ *, struct buffer *);
80
81 static void send_control_hello(struct switch_ *);
82
83 static int do_switch_recv(struct switch_ *this);
84 static int do_switch_send(struct switch_ *this);
85
86 static void process_packet(struct switch_ *, struct buffer *);
87 static void process_hub(struct switch_ *, struct ofp_packet_in *);
88 static void process_noflow(struct switch_ *, struct ofp_packet_in *);
89
90 static void switch_init(void);
91 static void process_switch(struct switch_ *, struct ofp_packet_in *);
92
93 int
94 main(int argc, char *argv[])
95 {
96     struct switch_ *switches[MAX_SWITCHES];
97     struct pollfd pollfds[MAX_SWITCHES + 1];
98     struct vlog_server *vlog_server;
99     int n_switches;
100     int retval;
101     int i;
102
103     set_program_name(argv[0]);
104     register_fault_handlers();
105     vlog_init();
106     parse_options(argc, argv);
107
108     if (!hub && !noflow) {
109         switch_init();
110     }
111
112     if (argc - optind < 1) {
113         fatal(0, "at least one vconn argument required; use --help for usage");
114     }
115
116     retval = vlog_server_listen(NULL, &vlog_server);
117     if (retval) {
118         fatal(retval, "Could not listen for vlog connections");
119     }
120
121     n_switches = 0;
122     for (i = 0; i < argc - optind; i++) {
123         struct switch_ *this = connect_switch(argv[optind + i]);
124         if (this) {
125             if (n_switches >= MAX_SWITCHES) {
126                 fatal(0, "max %d switch connections", n_switches);
127             }
128             switches[n_switches++] = this;
129         }
130     }
131     if (n_switches == 0) {
132         fatal(0, "could not connect to any switches");
133     }
134     
135     while (n_switches > 0) {
136         int retval;
137
138         /* Wait until there's something to do. */
139         for (i = 0; i < n_switches; i++) {
140             struct switch_ *this = switches[i];
141             int want;
142
143             if (vconn_is_passive(this->vconn)) {
144                 want = n_switches < MAX_SWITCHES ? WANT_ACCEPT : 0;
145             } else {
146                 want = WANT_RECV;
147                 if (this->n_txq) {
148                     want |= WANT_SEND;
149                 }
150             }
151
152             this->pollfd = &pollfds[i];
153             this->pollfd->fd = -1;
154             this->pollfd->events = 0;
155             vconn_prepoll(this->vconn, want, this->pollfd);
156         }
157         if (vlog_server) {
158             pollfds[n_switches].fd = vlog_server_get_fd(vlog_server);
159             pollfds[n_switches].events = POLLIN;
160         }
161         do {
162             retval = poll(pollfds, n_switches + (vlog_server != NULL), -1);
163         } while (retval < 0 && errno == EINTR);
164         if (retval <= 0) {
165             fatal(retval < 0 ? errno : 0, "poll");
166         }
167
168         /* Let each connection deal with any pending operations. */
169         for (i = 0; i < n_switches; i++) {
170             struct switch_ *this = switches[i];
171             vconn_postpoll(this->vconn, &this->pollfd->revents);
172             if (this->pollfd->revents & POLLERR) {
173                 this->pollfd->revents |= POLLIN | POLLOUT;
174             }
175         }
176         if (vlog_server && pollfds[n_switches].revents) {
177             vlog_server_poll(vlog_server);
178         }
179
180         for (i = 0; i < n_switches; ) {
181             struct switch_ *this = switches[i];
182
183             if (this->pollfd) {
184                 retval = 0;
185                 if (vconn_is_passive(this->vconn)) {
186                     if (this->pollfd->revents & POLLIN) {
187                         struct vconn *new_vconn;
188                         while (n_switches < MAX_SWITCHES 
189                                && (retval = vconn_accept(this->vconn,
190                                                          &new_vconn)) == 0) {
191                             switches[n_switches++] = new_switch("tcp",
192                                                                 new_vconn);
193                         }
194                     }
195                 } else {
196                     bool may_read = this->pollfd->revents & POLLIN;
197                     bool may_write = this->pollfd->revents & POLLOUT;
198                     if (may_read) {
199                         retval = do_switch_recv(this);
200                         if (!retval || retval == EAGAIN) {
201                             retval = 0;
202
203                             /* Enable writing to avoid round trip through poll
204                              * in common case. */
205                             may_write = true;
206                         }
207                     }
208                     while ((!retval || retval == EAGAIN) && may_write) {
209                         retval = do_switch_send(this);
210                         may_write = !retval;
211                     }
212                 }
213
214                 if (retval && retval != EAGAIN) {
215                     close_switch(this);
216                     switches[i] = switches[--n_switches];
217                     continue;
218                 }
219             } else {
220                 /* New switch that hasn't been polled yet. */
221             }
222             i++;
223         }
224     }
225
226     return 0;
227 }
228
229 static int
230 do_switch_recv(struct switch_ *this) 
231 {
232     struct buffer *msg;
233     int retval;
234
235     retval = vconn_recv(this->vconn, &msg);
236     if (!retval) {
237         process_packet(this, msg);
238         buffer_delete(msg);
239     }
240     return retval;
241 }
242
243 static int
244 do_switch_send(struct switch_ *this) 
245 {
246     int retval = 0;
247     if (this->n_txq) {
248         struct buffer *next = this->txq->next;
249
250         retval = vconn_send(this->vconn, this->txq);
251         if (retval) {
252             return retval;
253         }
254
255         this->txq = next;
256         if (this->txq == NULL) {
257             this->tx_tail = NULL;
258         }
259         this->n_txq--;
260         return 0;
261     }
262     return EAGAIN;
263 }
264
265 struct switch_ *
266 connect_switch(const char *name) 
267 {
268     struct vconn *vconn;
269     int retval;
270
271     retval = vconn_open(name, &vconn);
272     if (retval) {
273         VLOG_ERR("%s: connect: %s", name, strerror(retval));
274         return NULL;
275     }
276
277     return new_switch(name, vconn);
278 }
279
280 static struct switch_ *
281 new_switch(const char *name, struct vconn *vconn) 
282 {
283     struct switch_ *this = xmalloc(sizeof *this);
284     memset(this, 0, sizeof *this);
285     this->name = xstrdup(name);
286     this->vconn = vconn;
287     this->pollfd = NULL;
288     this->n_txq = 0;
289     this->txq = NULL;
290     this->tx_tail = NULL;
291     this->last_control_hello = 0;
292     if (!vconn_is_passive(vconn)) {
293         send_control_hello(this);
294     }
295     return this;
296 }
297
298 static void
299 close_switch(struct switch_ *this) 
300 {
301     if (this) {
302         struct buffer *cur, *next;
303
304         free(this->name);
305         vconn_close(this->vconn);
306         for (cur = this->txq; cur != NULL; cur = next) {
307             next = cur->next;
308             buffer_delete(cur);
309         }
310         free(this);
311     }
312 }
313
314 static void
315 send_control_hello(struct switch_ *this)
316 {
317     time_t now = time(0);
318     if (now >= this->last_control_hello + 1) {
319         struct buffer *b;
320         struct ofp_control_hello *och;
321
322         b = buffer_new(0);
323         och = buffer_put_uninit(b, sizeof *och);
324         memset(och, 0, sizeof *och);
325         och->header.version = OFP_VERSION;
326         och->header.length = htons(sizeof *och);
327
328         och->version = htonl(OFP_VERSION);
329         och->flags = htons(OFP_CHELLO_SEND_FLOW_EXP);
330         och->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
331         queue_tx(this, b);
332
333         this->last_control_hello = now;
334     }
335 }
336
337 static void
338 check_txq(struct switch_ *this UNUSED)
339 {
340 #if 0
341     struct buffer *iter;
342     size_t n;
343
344     assert(this->n_txq == 0
345            ? this->txq == NULL && this->tx_tail == NULL
346            : this->txq != NULL && this->tx_tail != NULL);
347
348     n = 0;
349     for (iter = this->txq; iter != NULL; iter = iter->next) {
350         n++;
351         assert((iter->next != NULL) == (iter != this->tx_tail));
352     }
353     assert(n == this->n_txq);
354 #endif
355 }
356
357 static void
358 queue_tx(struct switch_ *this, struct buffer *b) 
359 {
360     check_txq(this);
361
362     b->next = NULL;
363     if (this->n_txq++) {
364         this->tx_tail->next = b;
365     } else {
366         this->txq = b;
367     }
368     this->tx_tail = b;
369
370     check_txq(this);
371 }
372
373 static void
374 process_packet(struct switch_ *sw, struct buffer *msg) 
375 {
376     static const size_t min_size[UINT8_MAX + 1] = {
377         [0 ... UINT8_MAX] = SIZE_MAX,
378         [OFPT_CONTROL_HELLO] = sizeof (struct ofp_control_hello),
379         [OFPT_DATA_HELLO] = sizeof (struct ofp_data_hello),
380         [OFPT_PACKET_IN] = offsetof (struct ofp_packet_in, data),
381         [OFPT_PACKET_OUT] = sizeof (struct ofp_packet_out),
382         [OFPT_FLOW_MOD] = sizeof (struct ofp_flow_mod),
383         [OFPT_FLOW_EXPIRED] = sizeof (struct ofp_flow_expired),
384         [OFPT_TABLE] = sizeof (struct ofp_table),
385         [OFPT_PORT_MOD] = sizeof (struct ofp_port_mod),
386         [OFPT_PORT_STATUS] = sizeof (struct ofp_port_status),
387         [OFPT_FLOW_STAT_REQUEST] = sizeof (struct ofp_flow_stat_request),
388         [OFPT_FLOW_STAT_REPLY] = sizeof (struct ofp_flow_stat_reply),
389     };
390     struct ofp_header *oh;
391
392     oh = msg->data;
393     if (msg->size < min_size[oh->type]) {
394         VLOG_WARN("%s: too short (%zu bytes) for type %"PRIu8" (min %zu)",
395                   sw->name, msg->size, oh->type, min_size[oh->type]);
396         return;
397     }
398
399     if (oh->type == OFPT_DATA_HELLO) {
400         struct ofp_data_hello *odh = msg->data;
401         sw->datapath_id = odh->datapath_id;
402     } else if (sw->datapath_id == 0) {
403         send_control_hello(sw);
404         return;
405     }
406
407     if (oh->type == OFPT_PACKET_IN) {
408         if (sw->n_txq >= MAX_TXQ) {
409             VLOG_WARN("%s: tx queue overflow", sw->name);
410         } else if (noflow) {
411             process_noflow(sw, msg->data);
412         } else if (hub) {
413             process_hub(sw, msg->data);
414         } else {
415             process_switch(sw, msg->data);
416         }
417         return;
418     }
419
420     ofp_print(stdout, msg->data, msg->size, 2);
421 }
422
423 static void
424 process_hub(struct switch_ *sw, struct ofp_packet_in *opi)
425 {
426     size_t pkt_ofs, pkt_len;
427     struct buffer pkt;
428     struct flow flow;
429
430     /* Extract flow data from 'opi' into 'flow'. */
431     pkt_ofs = offsetof(struct ofp_packet_in, data);
432     pkt_len = ntohs(opi->header.length) - pkt_ofs;
433     pkt.data = opi->data;
434     pkt.size = pkt_len;
435     flow_extract(&pkt, ntohs(opi->in_port), &flow);
436
437     /* Add new flow. */
438     queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id),
439                                       OFPP_FLOOD));
440
441     /* If the switch didn't buffer the packet, we need to send a copy. */
442     if (ntohl(opi->buffer_id) == UINT32_MAX) {
443         queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(flow.in_port),
444                                                 OFPP_FLOOD));
445     }
446 }
447
448 static void
449 process_noflow(struct switch_ *sw, struct ofp_packet_in *opi)
450 {
451     /* If the switch didn't buffer the packet, we need to send a copy. */
452     if (ntohl(opi->buffer_id) == UINT32_MAX) {
453         size_t pkt_ofs, pkt_len;
454         struct buffer pkt;
455
456         /* Extract flow data from 'opi' into 'flow'. */
457         pkt_ofs = offsetof(struct ofp_packet_in, data);
458         pkt_len = ntohs(opi->header.length) - pkt_ofs;
459         pkt.data = opi->data;
460         pkt.size = pkt_len;
461
462         queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(opi->in_port),
463                     OFPP_FLOOD));
464     } else {
465         queue_tx(sw, make_buffered_packet_out(ntohl(opi->buffer_id), 
466                     ntohs(opi->in_port), OFPP_FLOOD));
467     }
468 }
469
470
471 #define MAC_HASH_BITS 10
472 #define MAC_HASH_MASK (MAC_HASH_SIZE - 1)
473 #define MAC_HASH_SIZE (1u << MAC_HASH_BITS)
474
475 #define MAC_MAX 1024
476
477 struct mac_source {
478     struct list hash_list;
479     struct list lru_list;
480     uint64_t datapath_id;
481     uint8_t mac[ETH_ADDR_LEN];
482     uint16_t port;
483 };
484
485 static struct list mac_table[MAC_HASH_SIZE];
486 static struct list lrus;
487 static size_t mac_count;
488
489 static void
490 switch_init(void)
491 {
492     int i;
493
494     list_init(&lrus);
495     for (i = 0; i < MAC_HASH_SIZE; i++) {
496         list_init(&mac_table[i]);
497     }
498 }
499
500 static struct list *
501 mac_table_bucket(uint64_t datapath_id, const uint8_t mac[ETH_ADDR_LEN]) 
502 {
503     uint32_t hash;
504     hash = hash_fnv(&datapath_id, sizeof datapath_id, HASH_FNV_BASIS);
505     hash = hash_fnv(mac, ETH_ADDR_LEN, hash);
506     return &mac_table[hash & MAC_HASH_BITS];
507 }
508
509 static void
510 process_switch(struct switch_ *sw, struct ofp_packet_in *opi)
511 {
512     size_t pkt_ofs, pkt_len;
513     struct buffer pkt;
514     struct flow flow;
515
516     uint16_t out_port;
517
518     /* Extract flow data from 'opi' into 'flow'. */
519     pkt_ofs = offsetof(struct ofp_packet_in, data);
520     pkt_len = ntohs(opi->header.length) - pkt_ofs;
521     pkt.data = opi->data;
522     pkt.size = pkt_len;
523     flow_extract(&pkt, ntohs(opi->in_port), &flow);
524
525     /* Learn the source. */
526     if (!mac_is_multicast(flow.dl_src)) {
527         struct mac_source *src;
528         struct list *bucket;
529         bool found;
530
531         bucket = mac_table_bucket(sw->datapath_id, flow.dl_src);
532         found = false;
533         LIST_FOR_EACH (src, struct mac_source, hash_list, bucket) {
534             if (src->datapath_id == sw->datapath_id
535                 && mac_equals(src->mac, flow.dl_src)) {
536                 found = true;
537                 break;
538             }
539         }
540
541         if (!found) {
542             /* Learn a new address. */
543
544             if (mac_count >= MAC_MAX) {
545                 /* Drop the least recently used mac source. */
546                 struct mac_source *lru;
547                 lru = CONTAINER_OF(lrus.next, struct mac_source, lru_list);
548                 list_remove(&lru->hash_list);
549                 list_remove(&lru->lru_list);
550                 free(lru);
551             } else {
552                 mac_count++;
553             }
554
555             /* Create new mac source */
556             src = xmalloc(sizeof *src);
557             src->datapath_id = sw->datapath_id;
558             memcpy(src->mac, flow.dl_src, ETH_ADDR_LEN);
559             src->port = -1;
560             list_push_front(bucket, &src->hash_list);
561             list_push_back(&lrus, &src->lru_list);
562         } else {
563             /* Make 'src' most-recently-used.  */
564             list_remove(&src->lru_list);
565             list_push_back(&lrus, &src->lru_list);
566         }
567
568         if (ntohs(flow.in_port) != src->port) {
569             src->port = ntohs(flow.in_port);
570             VLOG_DBG("learned that "MAC_FMT" is on datapath %"PRIx64" port %d",
571                      MAC_ARGS(src->mac), ntohll(src->datapath_id),
572                      src->port);
573         }
574     } else {
575         VLOG_DBG("multicast packet source "MAC_FMT, MAC_ARGS(flow.dl_src));
576     }
577
578     /* Figure out the destination. */
579     out_port = OFPP_FLOOD;
580     if (!mac_is_multicast(flow.dl_dst)) {
581         struct mac_source *dst;
582         struct list *bucket;
583
584         bucket = mac_table_bucket(sw->datapath_id, flow.dl_dst);
585         LIST_FOR_EACH (dst, struct mac_source, hash_list, bucket) {
586             if (dst->datapath_id == sw->datapath_id
587                 && mac_equals(dst->mac, flow.dl_dst)) {
588                 out_port = dst->port;
589                 break;
590             }
591         }
592     }
593
594     if (out_port != OFPP_FLOOD) {
595         /* The output port is known, so add a new flow. */
596         queue_tx(sw, make_add_simple_flow(&flow, ntohl(opi->buffer_id), 
597                     out_port));
598
599         /* If the switch didn't buffer the packet, we need to send a copy. */
600         if (ntohl(opi->buffer_id) == UINT32_MAX) {
601             queue_tx(sw, make_unbuffered_packet_out(&pkt, ntohs(flow.in_port),
602                                                     out_port));
603         }
604     } else {
605         /* We don't know that MAC.  Flood the packet. */
606         struct buffer *b;
607         if (ntohl(opi->buffer_id) == UINT32_MAX) {
608             b = make_unbuffered_packet_out(&pkt, ntohs(flow.in_port), out_port);
609         } else {
610             b = make_buffered_packet_out(ntohl(opi->buffer_id), 
611                         ntohs(flow.in_port), out_port);
612         }
613         queue_tx(sw, b);
614     }
615 }
616
617 static void
618 parse_options(int argc, char *argv[])
619 {
620     static struct option long_options[] = {
621         {"hub",         no_argument, 0, 'H'},
622         {"noflow",      no_argument, 0, 'n'},
623         {"verbose",     optional_argument, 0, 'v'},
624         {"help",        no_argument, 0, 'h'},
625         {"version",     no_argument, 0, 'V'},
626         {0, 0, 0, 0},
627     };
628     char *short_options = long_options_to_short_options(long_options);
629
630     for (;;) {
631         int indexptr;
632         int c;
633
634         c = getopt_long(argc, argv, short_options, long_options, &indexptr);
635         if (c == -1) {
636             break;
637         }
638
639         switch (c) {
640         case 'H':
641             hub = true;
642             break;
643
644         case 'n':
645             noflow = true;
646             break;
647
648         case 'h':
649             usage();
650
651         case 'V':
652             printf("%s "VERSION" compiled "__DATE__" "__TIME__"\n", argv[0]);
653             exit(EXIT_SUCCESS);
654
655         case 'v':
656             vlog_set_verbosity(optarg);
657             break;
658
659         case '?':
660             exit(EXIT_FAILURE);
661
662         default:
663             abort();
664         }
665     }
666     free(short_options);
667 }
668
669 static void
670 usage(void)
671 {
672     printf("%s: OpenFlow controller\n"
673            "usage: %s [OPTIONS] VCONN\n"
674            "where VCONN is one of the following:\n"
675 #ifdef HAVE_NETLINK
676            "  nl:DP_IDX               via netlink to local datapath DP_IDX\n"
677 #endif
678            "  ptcp:[PORT]             listen to TCP PORT (default: %d)\n"
679            "\nOther options:\n"
680            "  -H, --hub               act as hub instead of learning switch\n"
681            "  -n, --noflow            pass traffic, but don't add flows\n"
682            "  -v, --verbose           set maximum verbosity level\n"
683            "  -h, --help              display this help message\n"
684            "  -V, --version           display version information\n",
685            program_name, program_name, OFP_TCP_PORT);
686     exit(EXIT_SUCCESS);
687 }