36594ac636687e36df41fa91a2e607862213f725
[sliver-openvswitch.git] / lib / learning-switch.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 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 "flow.h"
27 #include "mac-learning.h"
28 #include "ofpbuf.h"
29 #include "ofp-parse.h"
30 #include "ofp-print.h"
31 #include "ofp-util.h"
32 #include "openflow/openflow.h"
33 #include "poll-loop.h"
34 #include "queue.h"
35 #include "rconn.h"
36 #include "timeval.h"
37 #include "vconn.h"
38 #include "vlog.h"
39 #include "xtoxll.h"
40
41 VLOG_DEFINE_THIS_MODULE(learning_switch)
42
43 struct lswitch {
44     /* If nonnegative, the switch sets up flows that expire after the given
45      * number of seconds (or never expire, if the value is OFP_FLOW_PERMANENT).
46      * Otherwise, the switch processes every packet. */
47     int max_idle;
48
49     unsigned long long int datapath_id;
50     time_t last_features_request;
51     struct mac_learning *ml;    /* NULL to act as hub instead of switch. */
52     uint32_t wildcards;         /* Wildcards to apply to flows. */
53     bool action_normal;         /* Use OFPP_NORMAL? */
54     uint32_t queue;             /* OpenFlow queue to use, or UINT32_MAX. */
55
56     /* Number of outgoing queued packets on the rconn. */
57     struct rconn_packet_counter *queued;
58 };
59
60 /* The log messages here could actually be useful in debugging, so keep the
61  * rate limit relatively high. */
62 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
63
64 static void queue_tx(struct lswitch *, struct rconn *, struct ofpbuf *);
65 static void send_features_request(struct lswitch *, struct rconn *);
66
67 typedef void packet_handler_func(struct lswitch *, struct rconn *, void *);
68 static packet_handler_func process_switch_features;
69 static packet_handler_func process_packet_in;
70 static packet_handler_func process_echo_request;
71
72 /* Creates and returns a new learning switch.
73  *
74  * If 'learn_macs' is true, the new switch will learn the ports on which MAC
75  * addresses appear.  Otherwise, the new switch will flood all packets.
76  *
77  * If 'max_idle' is nonnegative, the new switch will set up flows that expire
78  * after the given number of seconds (or never expire, if 'max_idle' is
79  * OFP_FLOW_PERMANENT).  Otherwise, the new switch will process every packet.
80  *
81  * The caller may provide an ofpbuf 'default_flows' that consists of a chain of
82  * one or more OpenFlow messages to send to the switch at time of connection.
83  * Presumably these will be OFPT_FLOW_MOD requests to set up the flow table.
84  *
85  * 'rconn' is used to send out an OpenFlow features request. */
86 struct lswitch *
87 lswitch_create(struct rconn *rconn, bool learn_macs,
88                bool exact_flows, int max_idle, bool action_normal,
89                const struct ofpbuf *default_flows)
90 {
91     const struct ofpbuf *b;
92     struct lswitch *sw;
93
94     sw = xzalloc(sizeof *sw);
95     sw->max_idle = max_idle;
96     sw->datapath_id = 0;
97     sw->last_features_request = time_now() - 1;
98     sw->ml = learn_macs ? mac_learning_create() : NULL;
99     sw->action_normal = action_normal;
100     if (exact_flows) {
101         /* Exact match. */
102         sw->wildcards = 0;
103     } else {
104         /* We cannot wildcard all fields.
105          * We need in_port to detect moves.
106          * We need both SA and DA to do learning. */
107         sw->wildcards = (OFPFW_DL_TYPE | OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK
108                          | OFPFW_NW_PROTO | OFPFW_TP_SRC | OFPFW_TP_DST);
109     }
110     sw->queue = UINT32_MAX;
111     sw->queued = rconn_packet_counter_create();
112     send_features_request(sw, rconn);
113
114     for (b = default_flows; b; b = b->next) {
115         queue_tx(sw, rconn, ofpbuf_clone(b));
116     }
117
118     return sw;
119 }
120
121 /* Destroys 'sw'. */
122 void
123 lswitch_destroy(struct lswitch *sw)
124 {
125     if (sw) {
126         mac_learning_destroy(sw->ml);
127         rconn_packet_counter_destroy(sw->queued);
128         free(sw);
129     }
130 }
131
132 /* Sets 'queue' as the OpenFlow queue used by packets and flows set up by 'sw'.
133  * Specify UINT32_MAX to avoid specifying a particular queue, which is also the
134  * default if this function is never called for 'sw'.  */
135 void
136 lswitch_set_queue(struct lswitch *sw, uint32_t queue)
137 {
138     sw->queue = queue;
139 }
140
141 /* Takes care of necessary 'sw' activity, except for receiving packets (which
142  * the caller must do). */
143 void
144 lswitch_run(struct lswitch *sw)
145 {
146     if (sw->ml) {
147         mac_learning_run(sw->ml, NULL);
148     }
149 }
150
151 void
152 lswitch_wait(struct lswitch *sw)
153 {
154     if (sw->ml) {
155         mac_learning_wait(sw->ml);
156     }
157 }
158
159 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
160  * to the learning switch state in 'sw'.  The most likely result of processing
161  * is that flow-setup and packet-out OpenFlow messages will be sent out on
162  * 'rconn'.  */
163 void
164 lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
165                        const struct ofpbuf *msg)
166 {
167     struct processor {
168         uint8_t type;
169         size_t min_size;
170         packet_handler_func *handler;
171     };
172     static const struct processor processors[] = {
173         {
174             OFPT_ECHO_REQUEST,
175             sizeof(struct ofp_header),
176             process_echo_request
177         },
178         {
179             OFPT_FEATURES_REPLY,
180             sizeof(struct ofp_switch_features),
181             process_switch_features
182         },
183         {
184             OFPT_PACKET_IN,
185             offsetof(struct ofp_packet_in, data),
186             process_packet_in
187         },
188         {
189             OFPT_FLOW_REMOVED,
190             sizeof(struct ofp_flow_removed),
191             NULL
192         },
193     };
194     const size_t n_processors = ARRAY_SIZE(processors);
195     const struct processor *p;
196     struct ofp_header *oh;
197
198     oh = msg->data;
199     if (sw->datapath_id == 0
200         && oh->type != OFPT_ECHO_REQUEST
201         && oh->type != OFPT_FEATURES_REPLY) {
202         send_features_request(sw, rconn);
203         return;
204     }
205
206     for (p = processors; p < &processors[n_processors]; p++) {
207         if (oh->type == p->type) {
208             if (msg->size < p->min_size) {
209                 VLOG_WARN_RL(&rl, "%016llx: %s: too short (%zu bytes) for "
210                              "type %"PRIu8" (min %zu)", sw->datapath_id,
211                              rconn_get_name(rconn), msg->size, oh->type,
212                              p->min_size);
213                 return;
214             }
215             if (p->handler) {
216                 (p->handler)(sw, rconn, msg->data);
217             }
218             return;
219         }
220     }
221     if (VLOG_IS_DBG_ENABLED()) {
222         char *s = ofp_to_string(msg->data, msg->size, 2);
223         VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
224                     sw->datapath_id, s);
225         free(s);
226     }
227 }
228 \f
229 static void
230 send_features_request(struct lswitch *sw, struct rconn *rconn)
231 {
232     time_t now = time_now();
233     if (now >= sw->last_features_request + 1) {
234         struct ofpbuf *b;
235         struct ofp_switch_config *osc;
236
237         /* Send OFPT_FEATURES_REQUEST. */
238         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
239         queue_tx(sw, rconn, b);
240
241         /* Send OFPT_SET_CONFIG. */
242         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
243         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
244         queue_tx(sw, rconn, b);
245
246         sw->last_features_request = now;
247     }
248 }
249
250 static void
251 queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
252 {
253     int retval = rconn_send_with_limit(rconn, b, sw->queued, 10);
254     if (retval && retval != ENOTCONN) {
255         if (retval == EAGAIN) {
256             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
257                          sw->datapath_id, rconn_get_name(rconn));
258         } else {
259             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
260                          sw->datapath_id, rconn_get_name(rconn),
261                          strerror(retval));
262         }
263     }
264 }
265
266 static void
267 process_switch_features(struct lswitch *sw, struct rconn *rconn OVS_UNUSED,
268                         void *osf_)
269 {
270     struct ofp_switch_features *osf = osf_;
271
272     sw->datapath_id = ntohll(osf->datapath_id);
273 }
274
275 static uint16_t
276 lswitch_choose_destination(struct lswitch *sw, const flow_t *flow)
277 {
278     uint16_t out_port;
279
280     /* Learn the source MAC. */
281     if (sw->ml) {
282         if (mac_learning_learn(sw->ml, flow->dl_src, 0, flow->in_port,
283                                GRAT_ARP_LOCK_NONE)) {
284             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
285                         "port %"PRIu16, sw->datapath_id,
286                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
287         }
288     }
289
290     /* Drop frames for reserved multicast addresses. */
291     if (eth_addr_is_reserved(flow->dl_dst)) {
292         return OFPP_NONE;
293     }
294
295     out_port = OFPP_FLOOD;
296     if (sw->ml) {
297         int learned_port = mac_learning_lookup(sw->ml, flow->dl_dst, 0, NULL);
298         if (learned_port >= 0) {
299             out_port = learned_port;
300             if (out_port == flow->in_port) {
301                 /* Don't send a packet back out its input port. */
302                 return OFPP_NONE;
303             }
304         }
305     }
306
307     /* Check if we need to use "NORMAL" action. */
308     if (sw->action_normal && out_port != OFPP_FLOOD) {
309         return OFPP_NORMAL;
310     }
311
312     return out_port;
313 }
314
315 static void
316 process_packet_in(struct lswitch *sw, struct rconn *rconn, void *opi_)
317 {
318     struct ofp_packet_in *opi = opi_;
319     uint16_t in_port = ntohs(opi->in_port);
320     uint16_t out_port;
321
322     struct ofp_action_header actions[2];
323     size_t actions_len;
324
325     size_t pkt_ofs, pkt_len;
326     struct ofpbuf pkt;
327     flow_t flow;
328
329     /* Ignore packets sent via output to OFPP_CONTROLLER.  This library never
330      * uses such an action.  You never know what experiments might be going on,
331      * though, and it seems best not to interfere with them. */
332     if (opi->reason != OFPR_NO_MATCH) {
333         return;
334     }
335
336     /* Extract flow data from 'opi' into 'flow'. */
337     pkt_ofs = offsetof(struct ofp_packet_in, data);
338     pkt_len = ntohs(opi->header.length) - pkt_ofs;
339     pkt.data = opi->data;
340     pkt.size = pkt_len;
341     flow_extract(&pkt, 0, in_port, &flow);
342
343     /* Choose output port. */
344     out_port = lswitch_choose_destination(sw, &flow);
345
346     /* Make actions. */
347     if (out_port == OFPP_NONE) {
348         actions_len = 0;
349     } else if (sw->queue == UINT32_MAX || out_port >= OFPP_MAX) {
350         struct ofp_action_output oao;
351
352         memset(&oao, 0, sizeof oao);
353         oao.type = htons(OFPAT_OUTPUT);
354         oao.len = htons(sizeof oao);
355         oao.port = htons(out_port);
356
357         memcpy(actions, &oao, sizeof oao);
358         actions_len = sizeof oao;
359     } else {
360         struct ofp_action_enqueue oae;
361
362         memset(&oae, 0, sizeof oae);
363         oae.type = htons(OFPAT_ENQUEUE);
364         oae.len = htons(sizeof oae);
365         oae.port = htons(out_port);
366         oae.queue_id = htonl(sw->queue);
367
368         memcpy(actions, &oae, sizeof oae);
369         actions_len = sizeof oae;
370     }
371     assert(actions_len <= sizeof actions);
372
373     /* Send the packet, and possibly the whole flow, to the output port. */
374     if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
375         struct ofpbuf *buffer;
376         struct ofp_flow_mod *ofm;
377
378         /* The output port is known, or we always flood everything, so add a
379          * new flow. */
380         buffer = make_add_flow(&flow, ntohl(opi->buffer_id),
381                                sw->max_idle, actions_len);
382         ofpbuf_put(buffer, actions, actions_len);
383         ofm = buffer->data;
384         ofm->match.wildcards = htonl(sw->wildcards);
385         queue_tx(sw, rconn, buffer);
386
387         /* If the switch didn't buffer the packet, we need to send a copy. */
388         if (ntohl(opi->buffer_id) == UINT32_MAX && actions_len > 0) {
389             queue_tx(sw, rconn,
390                      make_packet_out(&pkt, UINT32_MAX, in_port,
391                                      actions, actions_len / sizeof *actions));
392         }
393     } else {
394         /* We don't know that MAC, or we don't set up flows.  Send along the
395          * packet without setting up a flow. */
396         if (ntohl(opi->buffer_id) != UINT32_MAX || actions_len > 0) {
397             queue_tx(sw, rconn,
398                      make_packet_out(&pkt, ntohl(opi->buffer_id), in_port,
399                                      actions, actions_len / sizeof *actions));
400         }
401     }
402 }
403
404 static void
405 process_echo_request(struct lswitch *sw, struct rconn *rconn, void *rq_)
406 {
407     struct ofp_header *rq = rq_;
408     queue_tx(sw, rconn, make_echo_reply(rq));
409 }