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