f52d3c9d2d69b074c5141609f2e9004344b39ab6
[sliver-openvswitch.git] / lib / learning-switch.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "learning-switch.h"
19
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <netinet/in.h>
23 #include <stdlib.h>
24 #include <time.h>
25
26 #include "byte-order.h"
27 #include "classifier.h"
28 #include "flow.h"
29 #include "hmap.h"
30 #include "mac-learning.h"
31 #include "ofpbuf.h"
32 #include "ofp-actions.h"
33 #include "ofp-errors.h"
34 #include "ofp-msgs.h"
35 #include "ofp-parse.h"
36 #include "ofp-print.h"
37 #include "ofp-util.h"
38 #include "openflow/openflow.h"
39 #include "poll-loop.h"
40 #include "rconn.h"
41 #include "shash.h"
42 #include "simap.h"
43 #include "timeval.h"
44 #include "vconn.h"
45 #include "vlog.h"
46
47 VLOG_DEFINE_THIS_MODULE(learning_switch);
48
49 struct lswitch_port {
50     struct hmap_node hmap_node; /* Hash node for port number. */
51     uint16_t port_no;           /* OpenFlow port number, in host byte order. */
52     uint32_t queue_id;          /* OpenFlow queue number. */
53 };
54
55 enum lswitch_state {
56     S_CONNECTING,               /* Waiting for connection to complete. */
57     S_FEATURES_REPLY,           /* Waiting for features reply. */
58     S_SWITCHING,                /* Switching flows. */
59 };
60
61 struct lswitch {
62     struct rconn *rconn;
63     enum lswitch_state state;
64
65     /* If nonnegative, the switch sets up flows that expire after the given
66      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
67      * Otherwise, the switch processes every packet. */
68     int max_idle;
69
70     enum ofputil_protocol protocol;
71     unsigned long long int datapath_id;
72     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
73     struct flow_wildcards wc;   /* Wildcards to apply to flows. */
74     bool action_normal;         /* Use OFPP_NORMAL? */
75
76     /* Queue distribution. */
77     uint32_t default_queue;     /* Default OpenFlow queue, or UINT32_MAX. */
78     struct hmap queue_numbers;  /* Map from port number to lswitch_port. */
79     struct shash queue_names;   /* Map from port name to lswitch_port. */
80
81     /* Number of outgoing queued packets on the rconn. */
82     struct rconn_packet_counter *queued;
83
84     /* If true, do not reply to any messages from the switch (for debugging
85      * fail-open mode). */
86     bool mute;
87
88     /* Optional "flow mod" requests to send to the switch at connection time,
89      * to set up the flow table. */
90     const struct ofputil_flow_mod *default_flows;
91     size_t n_default_flows;
92 };
93
94 /* The log messages here could actually be useful in debugging, so keep the
95  * rate limit relatively high. */
96 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
97
98 static void queue_tx(struct lswitch *, struct ofpbuf *);
99 static void send_features_request(struct lswitch *);
100
101 static void lswitch_process_packet(struct lswitch *, const struct ofpbuf *);
102 static enum ofperr process_switch_features(struct lswitch *,
103                                            struct ofp_header *);
104 static void process_packet_in(struct lswitch *, const struct ofp_header *);
105 static void process_echo_request(struct lswitch *, const struct ofp_header *);
106
107 /* Creates and returns a new learning switch whose configuration is given by
108  * 'cfg'.
109  *
110  * 'rconn' is used to send out an OpenFlow features request. */
111 struct lswitch *
112 lswitch_create(struct rconn *rconn, const struct lswitch_config *cfg)
113 {
114     struct lswitch *sw;
115
116     sw = xzalloc(sizeof *sw);
117     sw->rconn = rconn;
118     sw->state = S_CONNECTING;
119     sw->max_idle = cfg->max_idle;
120     sw->datapath_id = 0;
121     sw->ml = (cfg->mode == LSW_LEARN
122               ? mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME)
123               : NULL);
124     sw->action_normal = cfg->mode == LSW_NORMAL;
125
126     flow_wildcards_init_exact(&sw->wc);
127     if (cfg->wildcards) {
128         uint32_t ofpfw;
129
130         if (cfg->wildcards == UINT32_MAX) {
131             /* Try to wildcard as many fields as possible, but we cannot
132              * wildcard all fields.  We need in_port to detect moves.  We need
133              * Ethernet source and dest and VLAN VID to do L2 learning. */
134             ofpfw = (OFPFW10_DL_TYPE | OFPFW10_DL_VLAN_PCP
135                      | OFPFW10_NW_SRC_ALL | OFPFW10_NW_DST_ALL
136                      | OFPFW10_NW_TOS | OFPFW10_NW_PROTO
137                      | OFPFW10_TP_SRC | OFPFW10_TP_DST);
138         } else {
139             ofpfw = cfg->wildcards;
140         }
141
142         ofputil_wildcard_from_ofpfw10(ofpfw, &sw->wc);
143     }
144
145     sw->default_queue = cfg->default_queue;
146     hmap_init(&sw->queue_numbers);
147     shash_init(&sw->queue_names);
148     if (cfg->port_queues) {
149         struct simap_node *node;
150
151         SIMAP_FOR_EACH (node, cfg->port_queues) {
152             struct lswitch_port *port = xmalloc(sizeof *port);
153             hmap_node_nullify(&port->hmap_node);
154             port->queue_id = node->data;
155             shash_add(&sw->queue_names, node->name, port);
156         }
157     }
158
159     sw->default_flows = cfg->default_flows;
160     sw->n_default_flows = cfg->n_default_flows;
161
162     sw->queued = rconn_packet_counter_create();
163
164     return sw;
165 }
166
167 static void
168 lswitch_handshake(struct lswitch *sw)
169 {
170     enum ofputil_protocol protocol;
171
172     send_features_request(sw);
173
174     protocol = ofputil_protocol_from_ofp_version(rconn_get_version(sw->rconn));
175     if (sw->default_flows) {
176         enum ofputil_protocol usable_protocols;
177         struct ofpbuf *msg = NULL;
178         int error = 0;
179         size_t i;
180
181         /* If the initial protocol isn't good enough for default_flows, then
182          * pick one that will work and encode messages to set up that
183          * protocol.
184          *
185          * This could be improved by actually negotiating a mutually acceptable
186          * flow format with the switch, but that would require an asynchronous
187          * state machine.  This version ought to work fine in practice. */
188         usable_protocols = ofputil_flow_mod_usable_protocols(
189             sw->default_flows, sw->n_default_flows);
190         if (!(protocol & usable_protocols)) {
191             enum ofputil_protocol want = rightmost_1bit(usable_protocols);
192             while (!error) {
193                 msg = ofputil_encode_set_protocol(protocol, want, &protocol);
194                 if (!msg) {
195                     break;
196                 }
197                 error = rconn_send(sw->rconn, msg, NULL);
198             }
199         }
200
201         for (i = 0; !error && i < sw->n_default_flows; i++) {
202             msg = ofputil_encode_flow_mod(&sw->default_flows[i], protocol);
203             error = rconn_send(sw->rconn, msg, NULL);
204         }
205
206         if (error) {
207             VLOG_INFO_RL(&rl, "%s: failed to queue default flows (%s)",
208                          rconn_get_name(sw->rconn), strerror(error));
209         }
210     }
211     sw->protocol = protocol;
212 }
213
214 bool
215 lswitch_is_alive(const struct lswitch *sw)
216 {
217     return rconn_is_alive(sw->rconn);
218 }
219
220 /* Destroys 'sw'. */
221 void
222 lswitch_destroy(struct lswitch *sw)
223 {
224     if (sw) {
225         struct lswitch_port *node, *next;
226
227         rconn_destroy(sw->rconn);
228         HMAP_FOR_EACH_SAFE (node, next, hmap_node, &sw->queue_numbers) {
229             hmap_remove(&sw->queue_numbers, &node->hmap_node);
230             free(node);
231         }
232         shash_destroy(&sw->queue_names);
233         mac_learning_destroy(sw->ml);
234         rconn_packet_counter_destroy(sw->queued);
235         free(sw);
236     }
237 }
238
239 /* Takes care of necessary 'sw' activity, except for receiving packets (which
240  * the caller must do). */
241 void
242 lswitch_run(struct lswitch *sw)
243 {
244     int i;
245
246     if (sw->ml) {
247         mac_learning_run(sw->ml, NULL);
248     }
249
250     rconn_run(sw->rconn);
251
252     if (sw->state == S_CONNECTING) {
253         if (rconn_get_version(sw->rconn) != -1) {
254             lswitch_handshake(sw);
255             sw->state = S_FEATURES_REPLY;
256         }
257         return;
258     }
259
260     for (i = 0; i < 50; i++) {
261         struct ofpbuf *msg;
262
263         msg = rconn_recv(sw->rconn);
264         if (!msg) {
265             break;
266         }
267
268         if (!sw->mute) {
269             lswitch_process_packet(sw, msg);
270         }
271         ofpbuf_delete(msg);
272     }
273 }
274
275 void
276 lswitch_wait(struct lswitch *sw)
277 {
278     if (sw->ml) {
279         mac_learning_wait(sw->ml);
280     }
281     rconn_run_wait(sw->rconn);
282     rconn_recv_wait(sw->rconn);
283 }
284
285 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
286  * to the learning switch state in 'sw'.  The most likely result of processing
287  * is that flow-setup and packet-out OpenFlow messages will be sent out on
288  * 'rconn'.  */
289 static void
290 lswitch_process_packet(struct lswitch *sw, const struct ofpbuf *msg)
291 {
292     enum ofptype type;
293     struct ofpbuf b;
294
295     b = *msg;
296     if (ofptype_pull(&type, &b)) {
297         return;
298     }
299
300     if (sw->state == S_FEATURES_REPLY
301         && type != OFPTYPE_ECHO_REQUEST
302         && type != OFPTYPE_FEATURES_REPLY) {
303         return;
304     }
305
306     switch (type) {
307     case OFPTYPE_ECHO_REQUEST:
308         process_echo_request(sw, msg->data);
309         break;
310
311     case OFPTYPE_FEATURES_REPLY:
312         if (sw->state == S_FEATURES_REPLY) {
313             if (!process_switch_features(sw, msg->data)) {
314                 sw->state = S_SWITCHING;
315             } else {
316                 rconn_disconnect(sw->rconn);
317             }
318         }
319         break;
320
321     case OFPTYPE_PACKET_IN:
322         process_packet_in(sw, msg->data);
323         break;
324
325     case OFPTYPE_FLOW_REMOVED:
326         /* Nothing to do. */
327         break;
328
329     case OFPTYPE_HELLO:
330     case OFPTYPE_ERROR:
331     case OFPTYPE_ECHO_REPLY:
332     case OFPTYPE_FEATURES_REQUEST:
333     case OFPTYPE_GET_CONFIG_REQUEST:
334     case OFPTYPE_GET_CONFIG_REPLY:
335     case OFPTYPE_SET_CONFIG:
336     case OFPTYPE_PORT_STATUS:
337     case OFPTYPE_PACKET_OUT:
338     case OFPTYPE_FLOW_MOD:
339     case OFPTYPE_PORT_MOD:
340     case OFPTYPE_BARRIER_REQUEST:
341     case OFPTYPE_BARRIER_REPLY:
342     case OFPTYPE_DESC_STATS_REQUEST:
343     case OFPTYPE_DESC_STATS_REPLY:
344     case OFPTYPE_FLOW_STATS_REQUEST:
345     case OFPTYPE_FLOW_STATS_REPLY:
346     case OFPTYPE_AGGREGATE_STATS_REQUEST:
347     case OFPTYPE_AGGREGATE_STATS_REPLY:
348     case OFPTYPE_TABLE_STATS_REQUEST:
349     case OFPTYPE_TABLE_STATS_REPLY:
350     case OFPTYPE_PORT_STATS_REQUEST:
351     case OFPTYPE_PORT_STATS_REPLY:
352     case OFPTYPE_QUEUE_STATS_REQUEST:
353     case OFPTYPE_QUEUE_STATS_REPLY:
354     case OFPTYPE_PORT_DESC_STATS_REQUEST:
355     case OFPTYPE_PORT_DESC_STATS_REPLY:
356     case OFPTYPE_ROLE_REQUEST:
357     case OFPTYPE_ROLE_REPLY:
358     case OFPTYPE_SET_FLOW_FORMAT:
359     case OFPTYPE_FLOW_MOD_TABLE_ID:
360     case OFPTYPE_SET_PACKET_IN_FORMAT:
361     case OFPTYPE_FLOW_AGE:
362     case OFPTYPE_SET_ASYNC_CONFIG:
363     case OFPTYPE_SET_CONTROLLER_ID:
364     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
365     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
366     case OFPTYPE_FLOW_MONITOR_CANCEL:
367     case OFPTYPE_FLOW_MONITOR_PAUSED:
368     case OFPTYPE_FLOW_MONITOR_RESUMED:
369     default:
370         if (VLOG_IS_DBG_ENABLED()) {
371             char *s = ofp_to_string(msg->data, msg->size, 2);
372             VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
373                         sw->datapath_id, s);
374             free(s);
375         }
376     }
377 }
378 \f
379 static void
380 send_features_request(struct lswitch *sw)
381 {
382     struct ofpbuf *b;
383     struct ofp_switch_config *osc;
384     int ofp_version = rconn_get_version(sw->rconn);
385
386     assert(ofp_version > 0 && ofp_version < 0xff);
387
388     /* Send OFPT_FEATURES_REQUEST. */
389     b = ofpraw_alloc(OFPRAW_OFPT_FEATURES_REQUEST, ofp_version, 0);
390     queue_tx(sw, b);
391
392     /* Send OFPT_SET_CONFIG. */
393     b = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG, ofp_version, sizeof *osc);
394     osc = ofpbuf_put_zeros(b, sizeof *osc);
395     osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
396     queue_tx(sw, b);
397 }
398
399 static void
400 queue_tx(struct lswitch *sw, struct ofpbuf *b)
401 {
402     int retval = rconn_send_with_limit(sw->rconn, b, sw->queued, 10);
403     if (retval && retval != ENOTCONN) {
404         if (retval == EAGAIN) {
405             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
406                          sw->datapath_id, rconn_get_name(sw->rconn));
407         } else {
408             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
409                          sw->datapath_id, rconn_get_name(sw->rconn),
410                          strerror(retval));
411         }
412     }
413 }
414
415 static enum ofperr
416 process_switch_features(struct lswitch *sw, struct ofp_header *oh)
417 {
418     struct ofputil_switch_features features;
419     struct ofputil_phy_port port;
420     enum ofperr error;
421     struct ofpbuf b;
422
423     error = ofputil_decode_switch_features(oh, &features, &b);
424     if (error) {
425         VLOG_ERR("received invalid switch feature reply (%s)",
426                  ofperr_to_string(error));
427         return error;
428     }
429
430     sw->datapath_id = features.datapath_id;
431
432     while (!ofputil_pull_phy_port(oh->version, &b, &port)) {
433         struct lswitch_port *lp = shash_find_data(&sw->queue_names, port.name);
434         if (lp && hmap_node_is_null(&lp->hmap_node)) {
435             lp->port_no = port.port_no;
436             hmap_insert(&sw->queue_numbers, &lp->hmap_node,
437                         hash_int(lp->port_no, 0));
438         }
439     }
440     return 0;
441 }
442
443 static uint16_t
444 lswitch_choose_destination(struct lswitch *sw, const struct flow *flow)
445 {
446     uint16_t out_port;
447
448     /* Learn the source MAC. */
449     if (mac_learning_may_learn(sw->ml, flow->dl_src, 0)) {
450         struct mac_entry *mac = mac_learning_insert(sw->ml, flow->dl_src, 0);
451         if (mac_entry_is_new(mac) || mac->port.i != flow->in_port) {
452             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
453                         "port %"PRIu16, sw->datapath_id,
454                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
455
456             mac->port.i = flow->in_port;
457             mac_learning_changed(sw->ml, mac);
458         }
459     }
460
461     /* Drop frames for reserved multicast addresses. */
462     if (eth_addr_is_reserved(flow->dl_dst)) {
463         return OFPP_NONE;
464     }
465
466     out_port = OFPP_FLOOD;
467     if (sw->ml) {
468         struct mac_entry *mac;
469
470         mac = mac_learning_lookup(sw->ml, flow->dl_dst, 0, NULL);
471         if (mac) {
472             out_port = mac->port.i;
473             if (out_port == flow->in_port) {
474                 /* Don't send a packet back out its input port. */
475                 return OFPP_NONE;
476             }
477         }
478     }
479
480     /* Check if we need to use "NORMAL" action. */
481     if (sw->action_normal && out_port != OFPP_FLOOD) {
482         return OFPP_NORMAL;
483     }
484
485     return out_port;
486 }
487
488 static uint32_t
489 get_queue_id(const struct lswitch *sw, uint16_t in_port)
490 {
491     const struct lswitch_port *port;
492
493     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_int(in_port, 0),
494                              &sw->queue_numbers) {
495         if (port->port_no == in_port) {
496             return port->queue_id;
497         }
498     }
499
500     return sw->default_queue;
501 }
502
503 static void
504 process_packet_in(struct lswitch *sw, const struct ofp_header *oh)
505 {
506     struct ofputil_packet_in pi;
507     uint32_t queue_id;
508     uint16_t out_port;
509
510     uint64_t ofpacts_stub[64 / 8];
511     struct ofpbuf ofpacts;
512
513     struct ofputil_packet_out po;
514     enum ofperr error;
515
516     struct ofpbuf pkt;
517     struct flow flow;
518
519     error = ofputil_decode_packet_in(&pi, oh);
520     if (error) {
521         VLOG_WARN_RL(&rl, "failed to decode packet-in: %s",
522                      ofperr_to_string(error));
523         return;
524     }
525
526     /* Ignore packets sent via output to OFPP_CONTROLLER.  This library never
527      * uses such an action.  You never know what experiments might be going on,
528      * though, and it seems best not to interfere with them. */
529     if (pi.reason != OFPR_NO_MATCH) {
530         return;
531     }
532
533     /* Extract flow data from 'opi' into 'flow'. */
534     ofpbuf_use_const(&pkt, pi.packet, pi.packet_len);
535     flow_extract(&pkt, 0, pi.fmd.tun_id, pi.fmd.in_port, &flow);
536
537     /* Choose output port. */
538     out_port = lswitch_choose_destination(sw, &flow);
539
540     /* Make actions. */
541     queue_id = get_queue_id(sw, pi.fmd.in_port);
542     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
543     if (out_port == OFPP_NONE) {
544         /* No actions. */
545     } else if (queue_id == UINT32_MAX || out_port >= OFPP_MAX) {
546         ofpact_put_OUTPUT(&ofpacts)->port = out_port;
547     } else {
548         struct ofpact_enqueue *enqueue = ofpact_put_ENQUEUE(&ofpacts);
549         enqueue->port = out_port;
550         enqueue->queue = queue_id;
551     }
552     ofpact_pad(&ofpacts);
553
554     /* Prepare packet_out in case we need one. */
555     po.buffer_id = pi.buffer_id;
556     if (po.buffer_id == UINT32_MAX) {
557         po.packet = pkt.data;
558         po.packet_len = pkt.size;
559     } else {
560         po.packet = NULL;
561         po.packet_len = 0;
562     }
563     po.in_port = pi.fmd.in_port;
564     po.ofpacts = ofpacts.data;
565     po.ofpacts_len = ofpacts.size;
566
567     /* Send the packet, and possibly the whole flow, to the output port. */
568     if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
569         struct ofputil_flow_mod fm;
570         struct ofpbuf *buffer;
571
572         /* The output port is known, or we always flood everything, so add a
573          * new flow. */
574         memset(&fm, 0, sizeof fm);
575         cls_rule_init(&flow, &sw->wc, 0, &fm.cr);
576         fm.table_id = 0xff;
577         fm.command = OFPFC_ADD;
578         fm.idle_timeout = sw->max_idle;
579         fm.buffer_id = pi.buffer_id;
580         fm.out_port = OFPP_NONE;
581         fm.ofpacts = ofpacts.data;
582         fm.ofpacts_len = ofpacts.size;
583         buffer = ofputil_encode_flow_mod(&fm, sw->protocol);
584
585         queue_tx(sw, buffer);
586
587         /* If the switch didn't buffer the packet, we need to send a copy. */
588         if (pi.buffer_id == UINT32_MAX && out_port != OFPP_NONE) {
589             queue_tx(sw, ofputil_encode_packet_out(&po));
590         }
591     } else {
592         /* We don't know that MAC, or we don't set up flows.  Send along the
593          * packet without setting up a flow. */
594         if (pi.buffer_id != UINT32_MAX || out_port != OFPP_NONE) {
595             queue_tx(sw, ofputil_encode_packet_out(&po));
596         }
597     }
598 }
599
600 static void
601 process_echo_request(struct lswitch *sw, const struct ofp_header *rq)
602 {
603     queue_tx(sw, make_echo_reply(rq));
604 }