Better abstract OpenFlow error codes.
[sliver-openvswitch.git] / lib / learning-switch.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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-errors.h"
33 #include "ofp-parse.h"
34 #include "ofp-print.h"
35 #include "ofp-util.h"
36 #include "openflow/openflow.h"
37 #include "poll-loop.h"
38 #include "rconn.h"
39 #include "shash.h"
40 #include "timeval.h"
41 #include "vconn.h"
42 #include "vlog.h"
43
44 VLOG_DEFINE_THIS_MODULE(learning_switch);
45
46 struct lswitch_port {
47     struct hmap_node hmap_node; /* Hash node for port number. */
48     uint16_t port_no;           /* OpenFlow port number, in host byte order. */
49     uint32_t queue_id;          /* OpenFlow queue number. */
50 };
51
52 struct lswitch {
53     /* If nonnegative, the switch sets up flows that expire after the given
54      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
55      * Otherwise, the switch processes every packet. */
56     int max_idle;
57
58     unsigned long long int datapath_id;
59     time_t last_features_request;
60     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
61     struct flow_wildcards wc;   /* Wildcards to apply to flows. */
62     bool action_normal;         /* Use OFPP_NORMAL? */
63
64     /* Queue distribution. */
65     uint32_t default_queue;     /* Default OpenFlow queue, or UINT32_MAX. */
66     struct hmap queue_numbers;  /* Map from port number to lswitch_port. */
67     struct shash queue_names;   /* Map from port name to lswitch_port. */
68
69     /* Number of outgoing queued packets on the rconn. */
70     struct rconn_packet_counter *queued;
71 };
72
73 /* The log messages here could actually be useful in debugging, so keep the
74  * rate limit relatively high. */
75 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
76
77 static void queue_tx(struct lswitch *, struct rconn *, struct ofpbuf *);
78 static void send_features_request(struct lswitch *, struct rconn *);
79
80 static void process_switch_features(struct lswitch *,
81                                     struct ofp_switch_features *);
82 static void process_packet_in(struct lswitch *, struct rconn *,
83                               const struct ofp_packet_in *);
84 static void process_echo_request(struct lswitch *, struct rconn *,
85                                  const struct ofp_header *);
86
87 /* Creates and returns a new learning switch whose configuration is given by
88  * 'cfg'.
89  *
90  * 'rconn' is used to send out an OpenFlow features request. */
91 struct lswitch *
92 lswitch_create(struct rconn *rconn, const struct lswitch_config *cfg)
93 {
94     struct lswitch *sw;
95
96     sw = xzalloc(sizeof *sw);
97     sw->max_idle = cfg->max_idle;
98     sw->datapath_id = 0;
99     sw->last_features_request = time_now() - 1;
100     sw->ml = cfg->mode == LSW_LEARN ? mac_learning_create() : NULL;
101     sw->action_normal = cfg->mode == LSW_NORMAL;
102
103     flow_wildcards_init_exact(&sw->wc);
104     if (cfg->wildcards) {
105         uint32_t ofpfw;
106
107         if (cfg->wildcards == UINT32_MAX) {
108             /* Try to wildcard as many fields as possible, but we cannot
109              * wildcard all fields.  We need in_port to detect moves.  We need
110              * Ethernet source and dest and VLAN VID to do L2 learning. */
111             ofpfw = (OFPFW_DL_TYPE | OFPFW_DL_VLAN_PCP
112                      | OFPFW_NW_SRC_ALL | OFPFW_NW_DST_ALL
113                      | OFPFW_NW_TOS | OFPFW_NW_PROTO
114                      | OFPFW_TP_SRC | OFPFW_TP_DST);
115         } else {
116             ofpfw = cfg->wildcards;
117         }
118
119         ofputil_wildcard_from_openflow(ofpfw, &sw->wc);
120     }
121
122     sw->default_queue = cfg->default_queue;
123     hmap_init(&sw->queue_numbers);
124     shash_init(&sw->queue_names);
125     if (cfg->port_queues) {
126         struct shash_node *node;
127
128         SHASH_FOR_EACH (node, cfg->port_queues) {
129             struct lswitch_port *port = xmalloc(sizeof *port);
130             hmap_node_nullify(&port->hmap_node);
131             port->queue_id = (uintptr_t) node->data;
132             shash_add(&sw->queue_names, node->name, port);
133         }
134     }
135
136     sw->queued = rconn_packet_counter_create();
137     send_features_request(sw, rconn);
138
139     if (cfg->default_flows) {
140         const struct ofpbuf *b;
141
142         LIST_FOR_EACH (b, list_node, cfg->default_flows) {
143             struct ofpbuf *copy = ofpbuf_clone(b);
144             int error = rconn_send(rconn, copy, NULL);
145             if (error) {
146                 VLOG_INFO_RL(&rl, "%s: failed to queue default flows (%s)",
147                              rconn_get_name(rconn), strerror(error));
148                 ofpbuf_delete(copy);
149                 break;
150             }
151         }
152     }
153
154     return sw;
155 }
156
157 /* Destroys 'sw'. */
158 void
159 lswitch_destroy(struct lswitch *sw)
160 {
161     if (sw) {
162         struct lswitch_port *node, *next;
163
164         HMAP_FOR_EACH_SAFE (node, next, hmap_node, &sw->queue_numbers) {
165             hmap_remove(&sw->queue_numbers, &node->hmap_node);
166             free(node);
167         }
168         shash_destroy(&sw->queue_names);
169         mac_learning_destroy(sw->ml);
170         rconn_packet_counter_destroy(sw->queued);
171         free(sw);
172     }
173 }
174
175 /* Takes care of necessary 'sw' activity, except for receiving packets (which
176  * the caller must do). */
177 void
178 lswitch_run(struct lswitch *sw)
179 {
180     if (sw->ml) {
181         mac_learning_run(sw->ml, NULL);
182     }
183 }
184
185 void
186 lswitch_wait(struct lswitch *sw)
187 {
188     if (sw->ml) {
189         mac_learning_wait(sw->ml);
190     }
191 }
192
193 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
194  * to the learning switch state in 'sw'.  The most likely result of processing
195  * is that flow-setup and packet-out OpenFlow messages will be sent out on
196  * 'rconn'.  */
197 void
198 lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
199                        const struct ofpbuf *msg)
200 {
201     const struct ofp_header *oh = msg->data;
202     const struct ofputil_msg_type *type;
203
204     if (sw->datapath_id == 0
205         && oh->type != OFPT_ECHO_REQUEST
206         && oh->type != OFPT_FEATURES_REPLY) {
207         send_features_request(sw, rconn);
208         return;
209     }
210
211     ofputil_decode_msg_type(oh, &type);
212     switch (ofputil_msg_type_code(type)) {
213     case OFPUTIL_OFPT_ECHO_REQUEST:
214         process_echo_request(sw, rconn, msg->data);
215         break;
216
217     case OFPUTIL_OFPT_FEATURES_REPLY:
218         process_switch_features(sw, msg->data);
219         break;
220
221     case OFPUTIL_OFPT_PACKET_IN:
222         process_packet_in(sw, rconn, msg->data);
223         break;
224
225     case OFPUTIL_OFPT_FLOW_REMOVED:
226         /* Nothing to do. */
227         break;
228
229     case OFPUTIL_MSG_INVALID:
230     case OFPUTIL_OFPT_HELLO:
231     case OFPUTIL_OFPT_ERROR:
232     case OFPUTIL_OFPT_ECHO_REPLY:
233     case OFPUTIL_OFPT_FEATURES_REQUEST:
234     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
235     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
236     case OFPUTIL_OFPT_SET_CONFIG:
237     case OFPUTIL_OFPT_PORT_STATUS:
238     case OFPUTIL_OFPT_PACKET_OUT:
239     case OFPUTIL_OFPT_FLOW_MOD:
240     case OFPUTIL_OFPT_PORT_MOD:
241     case OFPUTIL_OFPT_BARRIER_REQUEST:
242     case OFPUTIL_OFPT_BARRIER_REPLY:
243     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
244     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
245     case OFPUTIL_OFPST_DESC_REQUEST:
246     case OFPUTIL_OFPST_FLOW_REQUEST:
247     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
248     case OFPUTIL_OFPST_TABLE_REQUEST:
249     case OFPUTIL_OFPST_PORT_REQUEST:
250     case OFPUTIL_OFPST_QUEUE_REQUEST:
251     case OFPUTIL_OFPST_DESC_REPLY:
252     case OFPUTIL_OFPST_FLOW_REPLY:
253     case OFPUTIL_OFPST_QUEUE_REPLY:
254     case OFPUTIL_OFPST_PORT_REPLY:
255     case OFPUTIL_OFPST_TABLE_REPLY:
256     case OFPUTIL_OFPST_AGGREGATE_REPLY:
257     case OFPUTIL_NXT_ROLE_REQUEST:
258     case OFPUTIL_NXT_ROLE_REPLY:
259     case OFPUTIL_NXT_FLOW_MOD_TABLE_ID:
260     case OFPUTIL_NXT_SET_FLOW_FORMAT:
261     case OFPUTIL_NXT_SET_PACKET_IN_FORMAT:
262     case OFPUTIL_NXT_PACKET_IN:
263     case OFPUTIL_NXT_FLOW_MOD:
264     case OFPUTIL_NXT_FLOW_REMOVED:
265     case OFPUTIL_NXST_FLOW_REQUEST:
266     case OFPUTIL_NXST_AGGREGATE_REQUEST:
267     case OFPUTIL_NXST_FLOW_REPLY:
268     case OFPUTIL_NXST_AGGREGATE_REPLY:
269     default:
270         if (VLOG_IS_DBG_ENABLED()) {
271             char *s = ofp_to_string(msg->data, msg->size, 2);
272             VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
273                         sw->datapath_id, s);
274             free(s);
275         }
276     }
277 }
278 \f
279 static void
280 send_features_request(struct lswitch *sw, struct rconn *rconn)
281 {
282     time_t now = time_now();
283     if (now >= sw->last_features_request + 1) {
284         struct ofpbuf *b;
285         struct ofp_switch_config *osc;
286
287         /* Send OFPT_FEATURES_REQUEST. */
288         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
289         queue_tx(sw, rconn, b);
290
291         /* Send OFPT_SET_CONFIG. */
292         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
293         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
294         queue_tx(sw, rconn, b);
295
296         sw->last_features_request = now;
297     }
298 }
299
300 static void
301 queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
302 {
303     int retval = rconn_send_with_limit(rconn, b, sw->queued, 10);
304     if (retval && retval != ENOTCONN) {
305         if (retval == EAGAIN) {
306             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
307                          sw->datapath_id, rconn_get_name(rconn));
308         } else {
309             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
310                          sw->datapath_id, rconn_get_name(rconn),
311                          strerror(retval));
312         }
313     }
314 }
315
316 static void
317 process_switch_features(struct lswitch *sw, struct ofp_switch_features *osf)
318 {
319     size_t n_ports;
320     size_t i;
321
322     sw->datapath_id = ntohll(osf->datapath_id);
323
324     n_ports = (ntohs(osf->header.length) - sizeof *osf) / sizeof *osf->ports;
325     for (i = 0; i < n_ports; i++) {
326         struct ofp_phy_port *opp = &osf->ports[i];
327         struct lswitch_port *lp;
328
329         opp->name[OFP_MAX_PORT_NAME_LEN - 1] = '\0';
330         lp = shash_find_data(&sw->queue_names, opp->name);
331         if (lp && hmap_node_is_null(&lp->hmap_node)) {
332             lp->port_no = ntohs(opp->port_no);
333             hmap_insert(&sw->queue_numbers, &lp->hmap_node,
334                         hash_int(lp->port_no, 0));
335         }
336     }
337 }
338
339 static uint16_t
340 lswitch_choose_destination(struct lswitch *sw, const struct flow *flow)
341 {
342     uint16_t out_port;
343
344     /* Learn the source MAC. */
345     if (mac_learning_may_learn(sw->ml, flow->dl_src, 0)) {
346         struct mac_entry *mac = mac_learning_insert(sw->ml, flow->dl_src, 0);
347         if (mac_entry_is_new(mac) || mac->port.i != flow->in_port) {
348             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
349                         "port %"PRIu16, sw->datapath_id,
350                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
351
352             mac->port.i = flow->in_port;
353             mac_learning_changed(sw->ml, mac);
354         }
355     }
356
357     /* Drop frames for reserved multicast addresses. */
358     if (eth_addr_is_reserved(flow->dl_dst)) {
359         return OFPP_NONE;
360     }
361
362     out_port = OFPP_FLOOD;
363     if (sw->ml) {
364         struct mac_entry *mac;
365
366         mac = mac_learning_lookup(sw->ml, flow->dl_dst, 0, NULL);
367         if (mac) {
368             out_port = mac->port.i;
369             if (out_port == flow->in_port) {
370                 /* Don't send a packet back out its input port. */
371                 return OFPP_NONE;
372             }
373         }
374     }
375
376     /* Check if we need to use "NORMAL" action. */
377     if (sw->action_normal && out_port != OFPP_FLOOD) {
378         return OFPP_NORMAL;
379     }
380
381     return out_port;
382 }
383
384 static uint32_t
385 get_queue_id(const struct lswitch *sw, uint16_t in_port)
386 {
387     const struct lswitch_port *port;
388
389     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_int(in_port, 0),
390                              &sw->queue_numbers) {
391         if (port->port_no == in_port) {
392             return port->queue_id;
393         }
394     }
395
396     return sw->default_queue;
397 }
398
399 static void
400 process_packet_in(struct lswitch *sw, struct rconn *rconn,
401                   const struct ofp_packet_in *opi)
402 {
403     uint16_t in_port = ntohs(opi->in_port);
404     uint32_t queue_id;
405     uint16_t out_port;
406
407     struct ofp_action_header actions[2];
408     size_t actions_len;
409
410     size_t pkt_ofs, pkt_len;
411     struct ofpbuf pkt;
412     struct flow flow;
413
414     /* Ignore packets sent via output to OFPP_CONTROLLER.  This library never
415      * uses such an action.  You never know what experiments might be going on,
416      * though, and it seems best not to interfere with them. */
417     if (opi->reason != OFPR_NO_MATCH) {
418         return;
419     }
420
421     /* Extract flow data from 'opi' into 'flow'. */
422     pkt_ofs = offsetof(struct ofp_packet_in, data);
423     pkt_len = ntohs(opi->header.length) - pkt_ofs;
424     ofpbuf_use_const(&pkt, opi->data, pkt_len);
425     flow_extract(&pkt, 0, 0, in_port, &flow);
426
427     /* Choose output port. */
428     out_port = lswitch_choose_destination(sw, &flow);
429
430     /* Make actions. */
431     queue_id = get_queue_id(sw, in_port);
432     if (out_port == OFPP_NONE) {
433         actions_len = 0;
434     } else if (queue_id == UINT32_MAX || out_port >= OFPP_MAX) {
435         struct ofp_action_output oao;
436
437         memset(&oao, 0, sizeof oao);
438         oao.type = htons(OFPAT_OUTPUT);
439         oao.len = htons(sizeof oao);
440         oao.port = htons(out_port);
441
442         memcpy(actions, &oao, sizeof oao);
443         actions_len = sizeof oao;
444     } else {
445         struct ofp_action_enqueue oae;
446
447         memset(&oae, 0, sizeof oae);
448         oae.type = htons(OFPAT_ENQUEUE);
449         oae.len = htons(sizeof oae);
450         oae.port = htons(out_port);
451         oae.queue_id = htonl(queue_id);
452
453         memcpy(actions, &oae, sizeof oae);
454         actions_len = sizeof oae;
455     }
456     assert(actions_len <= sizeof actions);
457
458     /* Send the packet, and possibly the whole flow, to the output port. */
459     if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
460         struct ofpbuf *buffer;
461         struct cls_rule rule;
462
463         /* The output port is known, or we always flood everything, so add a
464          * new flow. */
465         cls_rule_init(&flow, &sw->wc, 0, &rule);
466         buffer = make_add_flow(&rule, ntohl(opi->buffer_id),
467                                sw->max_idle, actions_len);
468         ofpbuf_put(buffer, actions, actions_len);
469         queue_tx(sw, rconn, buffer);
470
471         /* If the switch didn't buffer the packet, we need to send a copy. */
472         if (ntohl(opi->buffer_id) == UINT32_MAX && actions_len > 0) {
473             queue_tx(sw, rconn,
474                      make_packet_out(&pkt, UINT32_MAX, in_port,
475                                      actions, actions_len / sizeof *actions));
476         }
477     } else {
478         /* We don't know that MAC, or we don't set up flows.  Send along the
479          * packet without setting up a flow. */
480         if (ntohl(opi->buffer_id) != UINT32_MAX || actions_len > 0) {
481             queue_tx(sw, rconn,
482                      make_packet_out(&pkt, ntohl(opi->buffer_id), in_port,
483                                      actions, actions_len / sizeof *actions));
484         }
485     }
486 }
487
488 static void
489 process_echo_request(struct lswitch *sw, struct rconn *rconn,
490                      const struct ofp_header *rq)
491 {
492     queue_tx(sw, rconn, make_echo_reply(rq));
493 }