88a8618c8849ec8b983f5c2ae8b52c4dc000b46c
[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 static void send_default_flows(struct lswitch *sw, struct rconn *rconn, 
67                                FILE *default_flows);
68
69 typedef void packet_handler_func(struct lswitch *, struct rconn *, void *);
70 static packet_handler_func process_switch_features;
71 static packet_handler_func process_packet_in;
72 static packet_handler_func process_echo_request;
73
74 /* Creates and returns a new learning switch.
75  *
76  * If 'learn_macs' is true, the new switch will learn the ports on which MAC
77  * addresses appear.  Otherwise, the new switch will flood all packets.
78  *
79  * If 'max_idle' is nonnegative, the new switch will set up flows that expire
80  * after the given number of seconds (or never expire, if 'max_idle' is
81  * OFP_FLOW_PERMANENT).  Otherwise, the new switch will process every packet.
82  *
83  * The caller may provide the file stream 'default_flows' that defines
84  * default flows that should be pushed when a switch connects.  Each
85  * line is a flow entry in the format described for "add-flows" command
86  * in the Flow Syntax section of the ovs-ofct(8) man page.  The caller
87  * is responsible for closing the stream.
88  *
89  * 'rconn' is used to send out an OpenFlow features request. */
90 struct lswitch *
91 lswitch_create(struct rconn *rconn, bool learn_macs,
92                bool exact_flows, int max_idle, bool action_normal,
93                FILE *default_flows)
94 {
95     struct lswitch *sw;
96
97     sw = xzalloc(sizeof *sw);
98     sw->max_idle = max_idle;
99     sw->datapath_id = 0;
100     sw->last_features_request = time_now() - 1;
101     sw->ml = learn_macs ? mac_learning_create() : NULL;
102     sw->action_normal = action_normal;
103     if (exact_flows) {
104         /* Exact match. */
105         sw->wildcards = 0;
106     } else {
107         /* We cannot wildcard all fields.
108          * We need in_port to detect moves.
109          * We need both SA and DA to do learning. */
110         sw->wildcards = (OFPFW_DL_TYPE | OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK
111                          | OFPFW_NW_PROTO | OFPFW_TP_SRC | OFPFW_TP_DST);
112     }
113     sw->queue = UINT32_MAX;
114     sw->queued = rconn_packet_counter_create();
115     send_features_request(sw, rconn);
116     if (default_flows) {
117         send_default_flows(sw, rconn, default_flows);
118     }
119     return sw;
120 }
121
122 /* Destroys 'sw'. */
123 void
124 lswitch_destroy(struct lswitch *sw)
125 {
126     if (sw) {
127         mac_learning_destroy(sw->ml);
128         rconn_packet_counter_destroy(sw->queued);
129         free(sw);
130     }
131 }
132
133 /* Sets 'queue' as the OpenFlow queue used by packets and flows set up by 'sw'.
134  * Specify UINT32_MAX to avoid specifying a particular queue, which is also the
135  * default if this function is never called for 'sw'.  */
136 void
137 lswitch_set_queue(struct lswitch *sw, uint32_t queue)
138 {
139     sw->queue = queue;
140 }
141
142 /* Takes care of necessary 'sw' activity, except for receiving packets (which
143  * the caller must do). */
144 void
145 lswitch_run(struct lswitch *sw)
146 {
147     if (sw->ml) {
148         mac_learning_run(sw->ml, NULL);
149     }
150 }
151
152 void
153 lswitch_wait(struct lswitch *sw)
154 {
155     if (sw->ml) {
156         mac_learning_wait(sw->ml);
157     }
158 }
159
160 /* Processes 'msg', which should be an OpenFlow received on 'rconn', according
161  * to the learning switch state in 'sw'.  The most likely result of processing
162  * is that flow-setup and packet-out OpenFlow messages will be sent out on
163  * 'rconn'.  */
164 void
165 lswitch_process_packet(struct lswitch *sw, struct rconn *rconn,
166                        const struct ofpbuf *msg)
167 {
168     struct processor {
169         uint8_t type;
170         size_t min_size;
171         packet_handler_func *handler;
172     };
173     static const struct processor processors[] = {
174         {
175             OFPT_ECHO_REQUEST,
176             sizeof(struct ofp_header),
177             process_echo_request
178         },
179         {
180             OFPT_FEATURES_REPLY,
181             sizeof(struct ofp_switch_features),
182             process_switch_features
183         },
184         {
185             OFPT_PACKET_IN,
186             offsetof(struct ofp_packet_in, data),
187             process_packet_in
188         },
189         {
190             OFPT_FLOW_REMOVED,
191             sizeof(struct ofp_flow_removed),
192             NULL
193         },
194     };
195     const size_t n_processors = ARRAY_SIZE(processors);
196     const struct processor *p;
197     struct ofp_header *oh;
198
199     oh = msg->data;
200     if (sw->datapath_id == 0
201         && oh->type != OFPT_ECHO_REQUEST
202         && oh->type != OFPT_FEATURES_REPLY) {
203         send_features_request(sw, rconn);
204         return;
205     }
206
207     for (p = processors; p < &processors[n_processors]; p++) {
208         if (oh->type == p->type) {
209             if (msg->size < p->min_size) {
210                 VLOG_WARN_RL(&rl, "%016llx: %s: too short (%zu bytes) for "
211                              "type %"PRIu8" (min %zu)", sw->datapath_id,
212                              rconn_get_name(rconn), msg->size, oh->type,
213                              p->min_size);
214                 return;
215             }
216             if (p->handler) {
217                 (p->handler)(sw, rconn, msg->data);
218             }
219             return;
220         }
221     }
222     if (VLOG_IS_DBG_ENABLED()) {
223         char *p = ofp_to_string(msg->data, msg->size, 2);
224         VLOG_DBG_RL(&rl, "%016llx: OpenFlow packet ignored: %s",
225                     sw->datapath_id, p);
226         free(p);
227     }
228 }
229 \f
230 static void
231 send_features_request(struct lswitch *sw, struct rconn *rconn)
232 {
233     time_t now = time_now();
234     if (now >= sw->last_features_request + 1) {
235         struct ofpbuf *b;
236         struct ofp_switch_config *osc;
237
238         /* Send OFPT_FEATURES_REQUEST. */
239         make_openflow(sizeof(struct ofp_header), OFPT_FEATURES_REQUEST, &b);
240         queue_tx(sw, rconn, b);
241
242         /* Send OFPT_SET_CONFIG. */
243         osc = make_openflow(sizeof *osc, OFPT_SET_CONFIG, &b);
244         osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
245         queue_tx(sw, rconn, b);
246
247         sw->last_features_request = now;
248     }
249 }
250
251 static void
252 send_default_flows(struct lswitch *sw, struct rconn *rconn, 
253                    FILE *default_flows)
254 {
255     char line[1024];
256
257     while (fgets(line, sizeof line, default_flows)) {
258         struct ofpbuf *b;
259         struct ofp_flow_mod *ofm;
260         uint16_t priority, idle_timeout, hard_timeout;
261         uint64_t cookie;
262         struct ofp_match match;
263         
264         char *comment;
265         
266         /* Delete comments. */
267         comment = strchr(line, '#');
268         if (comment) { 
269             *comment = '\0';
270         }
271         
272         /* Drop empty lines. */
273         if (line[strspn(line, " \t\n")] == '\0') {
274             continue;
275         }   
276     
277         /* Parse and send.  str_to_flow() will expand and reallocate the data
278          * in 'buffer', so we can't keep pointers to across the str_to_flow()
279          * call. */
280         make_openflow(sizeof *ofm, OFPT_FLOW_MOD, &b);
281         parse_ofp_str(line, &match, b,
282                       NULL, NULL, &priority, &idle_timeout, &hard_timeout,
283                       &cookie);
284         ofm = b->data;
285         ofm->match = match;
286         ofm->command = htons(OFPFC_ADD);
287         ofm->cookie = htonll(cookie);
288         ofm->idle_timeout = htons(idle_timeout);
289         ofm->hard_timeout = htons(hard_timeout);
290         ofm->buffer_id = htonl(UINT32_MAX);
291         ofm->priority = htons(priority);
292
293         update_openflow_length(b);
294         queue_tx(sw, rconn, b);
295     }
296 }
297
298 static void
299 queue_tx(struct lswitch *sw, struct rconn *rconn, struct ofpbuf *b)
300 {
301     int retval = rconn_send_with_limit(rconn, b, sw->queued, 10);
302     if (retval && retval != ENOTCONN) {
303         if (retval == EAGAIN) {
304             VLOG_INFO_RL(&rl, "%016llx: %s: tx queue overflow",
305                          sw->datapath_id, rconn_get_name(rconn));
306         } else {
307             VLOG_WARN_RL(&rl, "%016llx: %s: send: %s",
308                          sw->datapath_id, rconn_get_name(rconn),
309                          strerror(retval));
310         }
311     }
312 }
313
314 static void
315 process_switch_features(struct lswitch *sw, struct rconn *rconn OVS_UNUSED,
316                         void *osf_)
317 {
318     struct ofp_switch_features *osf = osf_;
319
320     sw->datapath_id = ntohll(osf->datapath_id);
321 }
322
323 static uint16_t
324 lswitch_choose_destination(struct lswitch *sw, const flow_t *flow)
325 {
326     uint16_t out_port;
327
328     /* Learn the source MAC. */
329     if (sw->ml) {
330         if (mac_learning_learn(sw->ml, flow->dl_src, 0, flow->in_port,
331                                GRAT_ARP_LOCK_NONE)) {
332             VLOG_DBG_RL(&rl, "%016llx: learned that "ETH_ADDR_FMT" is on "
333                         "port %"PRIu16, sw->datapath_id,
334                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
335         }
336     }
337
338     /* Drop frames for reserved multicast addresses. */
339     if (eth_addr_is_reserved(flow->dl_dst)) {
340         return OFPP_NONE;
341     }
342
343     out_port = OFPP_FLOOD;
344     if (sw->ml) {
345         int learned_port = mac_learning_lookup(sw->ml, flow->dl_dst, 0, NULL);
346         if (learned_port >= 0) {
347             out_port = learned_port;
348             if (out_port == flow->in_port) {
349                 /* Don't send a packet back out its input port. */
350                 return OFPP_NONE;
351             }
352         }
353     }
354
355     /* Check if we need to use "NORMAL" action. */
356     if (sw->action_normal && out_port != OFPP_FLOOD) {
357         return OFPP_NORMAL;
358     }
359
360     return out_port;
361 }
362
363 static void
364 process_packet_in(struct lswitch *sw, struct rconn *rconn, void *opi_)
365 {
366     struct ofp_packet_in *opi = opi_;
367     uint16_t in_port = ntohs(opi->in_port);
368     uint16_t out_port;
369
370     struct ofp_action_header actions[2];
371     size_t actions_len;
372
373     size_t pkt_ofs, pkt_len;
374     struct ofpbuf pkt;
375     flow_t flow;
376
377     /* Ignore packets sent via output to OFPP_CONTROLLER.  This library never
378      * uses such an action.  You never know what experiments might be going on,
379      * though, and it seems best not to interfere with them. */
380     if (opi->reason != OFPR_NO_MATCH) {
381         return;
382     }
383
384     /* Extract flow data from 'opi' into 'flow'. */
385     pkt_ofs = offsetof(struct ofp_packet_in, data);
386     pkt_len = ntohs(opi->header.length) - pkt_ofs;
387     pkt.data = opi->data;
388     pkt.size = pkt_len;
389     flow_extract(&pkt, 0, in_port, &flow);
390
391     /* Choose output port. */
392     out_port = lswitch_choose_destination(sw, &flow);
393
394     /* Make actions. */
395     if (out_port == OFPP_NONE) {
396         actions_len = 0;
397     } else if (sw->queue == UINT32_MAX || out_port >= OFPP_MAX) {
398         struct ofp_action_output oao;
399
400         memset(&oao, 0, sizeof oao);
401         oao.type = htons(OFPAT_OUTPUT);
402         oao.len = htons(sizeof oao);
403         oao.port = htons(out_port);
404
405         memcpy(actions, &oao, sizeof oao);
406         actions_len = sizeof oao;
407     } else {
408         struct ofp_action_enqueue oae;
409
410         memset(&oae, 0, sizeof oae);
411         oae.type = htons(OFPAT_ENQUEUE);
412         oae.len = htons(sizeof oae);
413         oae.port = htons(out_port);
414         oae.queue_id = htonl(sw->queue);
415
416         memcpy(actions, &oae, sizeof oae);
417         actions_len = sizeof oae;
418     }
419     assert(actions_len <= sizeof actions);
420
421     /* Send the packet, and possibly the whole flow, to the output port. */
422     if (sw->max_idle >= 0 && (!sw->ml || out_port != OFPP_FLOOD)) {
423         struct ofpbuf *buffer;
424         struct ofp_flow_mod *ofm;
425
426         /* The output port is known, or we always flood everything, so add a
427          * new flow. */
428         buffer = make_add_flow(&flow, ntohl(opi->buffer_id),
429                                sw->max_idle, actions_len);
430         ofpbuf_put(buffer, actions, actions_len);
431         ofm = buffer->data;
432         ofm->match.wildcards = htonl(sw->wildcards);
433         queue_tx(sw, rconn, buffer);
434
435         /* If the switch didn't buffer the packet, we need to send a copy. */
436         if (ntohl(opi->buffer_id) == UINT32_MAX && actions_len > 0) {
437             queue_tx(sw, rconn,
438                      make_packet_out(&pkt, UINT32_MAX, in_port,
439                                      actions, actions_len / sizeof *actions));
440         }
441     } else {
442         /* We don't know that MAC, or we don't set up flows.  Send along the
443          * packet without setting up a flow. */
444         if (ntohl(opi->buffer_id) != UINT32_MAX || actions_len > 0) {
445             queue_tx(sw, rconn,
446                      make_packet_out(&pkt, ntohl(opi->buffer_id), in_port,
447                                      actions, actions_len / sizeof *actions));
448         }
449     }
450 }
451
452 static void
453 process_echo_request(struct lswitch *sw, struct rconn *rconn, void *rq_)
454 {
455     struct ofp_header *rq = rq_;
456     queue_tx(sw, rconn, make_echo_reply(rq));
457 }