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