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