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