94b9a4b5b993d17c5f0d1a8519f4262b011ceaa9
[sliver-openvswitch.git] / lib / stp.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 /* Based on sample implementation in 802.1D-1998.  Above copyright and license
18  * applies to all modifications. */
19
20 #include <config.h>
21
22 #include "stp.h"
23 #include <sys/types.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <assert.h>
27 #include <inttypes.h>
28 #include <stdlib.h>
29 #include "byte-order.h"
30 #include "ofpbuf.h"
31 #include "packets.h"
32 #include "util.h"
33 #include "vlog.h"
34
35 VLOG_DEFINE_THIS_MODULE(stp);
36
37 #define STP_PROTOCOL_ID 0x0000
38 #define STP_PROTOCOL_VERSION 0x00
39 #define STP_TYPE_CONFIG 0x00
40 #define STP_TYPE_TCN 0x80
41
42 struct stp_bpdu_header {
43     ovs_be16 protocol_id;       /* STP_PROTOCOL_ID. */
44     uint8_t protocol_version;   /* STP_PROTOCOL_VERSION. */
45     uint8_t bpdu_type;          /* One of STP_TYPE_*. */
46 } __attribute__((packed));
47 BUILD_ASSERT_DECL(sizeof(struct stp_bpdu_header) == 4);
48
49 enum stp_config_bpdu_flags {
50     STP_CONFIG_TOPOLOGY_CHANGE_ACK = 0x80,
51     STP_CONFIG_TOPOLOGY_CHANGE = 0x01
52 };
53
54 struct stp_config_bpdu {
55     struct stp_bpdu_header header; /* Type STP_TYPE_CONFIG. */
56     uint8_t flags;                 /* STP_CONFIG_* flags. */
57     ovs_be64 root_id;              /* 8.5.1.1: Bridge believed to be root. */
58     ovs_be32 root_path_cost;       /* 8.5.1.2: Cost of path to root. */
59     ovs_be64 bridge_id;            /* 8.5.1.3: ID of transmitting bridge. */
60     ovs_be16 port_id;              /* 8.5.1.4: Port transmitting the BPDU. */
61     ovs_be16 message_age;          /* 8.5.1.5: Age of BPDU at tx time. */
62     ovs_be16 max_age;              /* 8.5.1.6: Timeout for received data. */
63     ovs_be16 hello_time;           /* 8.5.1.7: Time between BPDU generation. */
64     ovs_be16 forward_delay;        /* 8.5.1.8: State progression delay. */
65 } __attribute__((packed));
66 BUILD_ASSERT_DECL(sizeof(struct stp_config_bpdu) == 35);
67
68 struct stp_tcn_bpdu {
69     struct stp_bpdu_header header; /* Type STP_TYPE_TCN. */
70 } __attribute__((packed));
71 BUILD_ASSERT_DECL(sizeof(struct stp_tcn_bpdu) == 4);
72
73 struct stp_timer {
74     bool active;                 /* Timer in use? */
75     int value;                   /* Current value of timer, counting up. */
76 };
77
78 struct stp_port {
79     struct stp *stp;
80     void *aux;                      /* Auxiliary data the user may retrieve. */
81     int port_id;                    /* 8.5.5.1: Unique port identifier. */
82     enum stp_state state;           /* 8.5.5.2: Current state. */
83     int path_cost;                  /* 8.5.5.3: Cost of tx/rx on this port. */
84     stp_identifier designated_root; /* 8.5.5.4. */
85     int designated_cost;            /* 8.5.5.5: Path cost to root on port. */
86     stp_identifier designated_bridge; /* 8.5.5.6. */
87     int designated_port;            /* 8.5.5.7: Port to send config msgs on. */
88     bool topology_change_ack;       /* 8.5.5.8: Flag for next config BPDU. */
89     bool config_pending;            /* 8.5.5.9: Send BPDU when hold expires? */
90     bool change_detection_enabled;  /* 8.5.5.10: Detect topology changes? */
91
92     struct stp_timer message_age_timer; /* 8.5.6.1: Age of received info. */
93     struct stp_timer forward_delay_timer; /* 8.5.6.2: State change timer. */
94     struct stp_timer hold_timer;        /* 8.5.6.3: BPDU rate limit timer. */
95
96     bool state_changed;
97 };
98
99 struct stp {
100     /* Static bridge data. */
101     char *name;                     /* Human-readable name for log messages. */
102     stp_identifier bridge_id;       /* 8.5.3.7: This bridge. */
103     int max_age;                    /* 8.5.3.4: Time to drop received data. */
104     int hello_time;                 /* 8.5.3.5: Time between sending BPDUs. */
105     int forward_delay;              /* 8.5.3.6: Delay between state changes. */
106     int bridge_max_age;             /* 8.5.3.8: max_age when we're root. */
107     int bridge_hello_time;          /* 8.5.3.9: hello_time as root. */
108     int bridge_forward_delay;       /* 8.5.3.10: forward_delay as root. */
109     int rq_max_age;                 /* User-requested max age, in ms. */
110     int rq_hello_time;              /* User-requested hello time, in ms. */
111     int rq_forward_delay;           /* User-requested forward delay, in ms. */
112     int elapsed_remainder;          /* Left-over msecs from last stp_tick(). */
113
114     /* Dynamic bridge data. */
115     stp_identifier designated_root; /* 8.5.3.1: Bridge believed to be root. */
116     unsigned int root_path_cost;    /* 8.5.3.2: Cost of path to root. */
117     struct stp_port *root_port;     /* 8.5.3.3: Lowest cost port to root. */
118     bool topology_change_detected;  /* 8.5.3.11: Detected a topology change? */
119     bool topology_change;           /* 8.5.3.12: Received topology change? */
120
121     /* Bridge timers. */
122     struct stp_timer hello_timer;   /* 8.5.4.1: Hello timer. */
123     struct stp_timer tcn_timer;     /* 8.5.4.2: Topology change timer. */
124     struct stp_timer topology_change_timer; /* 8.5.4.3. */
125
126     /* Ports. */
127     struct stp_port ports[STP_MAX_PORTS];
128
129     /* Interface to client. */
130     struct stp_port *first_changed_port;
131     void (*send_bpdu)(struct ofpbuf *bpdu, int port_no, void *aux);
132     void *aux;
133 };
134
135 #define FOR_EACH_ENABLED_PORT(PORT, STP)                        \
136     for ((PORT) = stp_next_enabled_port((STP), (STP)->ports);   \
137          (PORT);                                                \
138          (PORT) = stp_next_enabled_port((STP), (PORT) + 1))
139 static struct stp_port *
140 stp_next_enabled_port(const struct stp *stp, const struct stp_port *port)
141 {
142     for (; port < &stp->ports[ARRAY_SIZE(stp->ports)]; port++) {
143         if (port->state != STP_DISABLED) {
144             return (struct stp_port *) port;
145         }
146     }
147     return NULL;
148 }
149
150 #define MESSAGE_AGE_INCREMENT 1
151
152 static void stp_transmit_config(struct stp_port *);
153 static bool stp_supersedes_port_info(const struct stp_port *,
154                                      const struct stp_config_bpdu *);
155 static void stp_record_config_information(struct stp_port *,
156                                           const struct stp_config_bpdu *);
157 static void stp_record_config_timeout_values(struct stp *,
158                                              const struct stp_config_bpdu  *);
159 static bool stp_is_designated_port(const struct stp_port *);
160 static void stp_config_bpdu_generation(struct stp *);
161 static void stp_transmit_tcn(struct stp *);
162 static void stp_configuration_update(struct stp *);
163 static bool stp_supersedes_root(const struct stp_port *root,
164                                 const struct stp_port *);
165 static void stp_root_selection(struct stp *);
166 static void stp_designated_port_selection(struct stp *);
167 static void stp_become_designated_port(struct stp_port *);
168 static void stp_port_state_selection(struct stp *);
169 static void stp_make_forwarding(struct stp_port *);
170 static void stp_make_blocking(struct stp_port *);
171 static void stp_set_port_state(struct stp_port *, enum stp_state);
172 static void stp_topology_change_detection(struct stp *);
173 static void stp_topology_change_acknowledged(struct stp *);
174 static void stp_acknowledge_topology_change(struct stp_port *);
175 static void stp_received_config_bpdu(struct stp *, struct stp_port *,
176                                      const struct stp_config_bpdu *);
177 static void stp_received_tcn_bpdu(struct stp *, struct stp_port *);
178 static void stp_hello_timer_expiry(struct stp *);
179 static void stp_message_age_timer_expiry(struct stp_port *);
180 static bool stp_is_designated_for_some_port(const struct stp *);
181 static void stp_forward_delay_timer_expiry(struct stp_port *);
182 static void stp_tcn_timer_expiry(struct stp *);
183 static void stp_topology_change_timer_expiry(struct stp *);
184 static void stp_hold_timer_expiry(struct stp_port *);
185 static void stp_initialize_port(struct stp_port *, enum stp_state);
186 static void stp_become_root_bridge(struct stp *);
187 static void stp_update_bridge_timers(struct stp *);
188
189 static int clamp(int x, int min, int max);
190 static int ms_to_timer(int ms);
191 static int ms_to_timer_remainder(int ms);
192 static int timer_to_ms(int timer);
193 static void stp_start_timer(struct stp_timer *, int value);
194 static void stp_stop_timer(struct stp_timer *);
195 static bool stp_timer_expired(struct stp_timer *, int elapsed, int timeout);
196
197 static void stp_send_bpdu(struct stp_port *, const void *, size_t);
198
199 /* Creates and returns a new STP instance that initially has no ports enabled.
200  *
201  * 'bridge_id' should be a 48-bit MAC address as returned by
202  * eth_addr_to_uint64().  'bridge_id' may also have a priority value in its top
203  * 16 bits; if those bits are set to 0, STP_DEFAULT_BRIDGE_PRIORITY is used.
204  * (This priority may be changed with stp_set_bridge_priority().)
205  *
206  * When the bridge needs to send out a BPDU, it calls 'send_bpdu'.  This
207  * callback may be called from stp_tick() or stp_received_bpdu().  The
208  * arguments to 'send_bpdu' are an STP BPDU encapsulated in 'bpdu',
209  * the spanning tree port number 'port_no' that should transmit the
210  * packet, and auxiliary data to be passed to the callback in 'aux'.
211  */
212 struct stp *
213 stp_create(const char *name, stp_identifier bridge_id,
214            void (*send_bpdu)(struct ofpbuf *bpdu, int port_no, void *aux),
215            void *aux)
216 {
217     struct stp *stp;
218     struct stp_port *p;
219
220     stp = xzalloc(sizeof *stp);
221     stp->name = xstrdup(name);
222     stp->bridge_id = bridge_id;
223     if (!(stp->bridge_id >> 48)) {
224         stp->bridge_id |= (uint64_t) STP_DEFAULT_BRIDGE_PRIORITY << 48;
225     }
226
227     stp->rq_max_age = STP_DEFAULT_MAX_AGE;
228     stp->rq_hello_time = STP_DEFAULT_HELLO_TIME;
229     stp->rq_forward_delay = STP_DEFAULT_FWD_DELAY;
230     stp_update_bridge_timers(stp);
231     stp->max_age = stp->bridge_max_age;
232     stp->hello_time = stp->bridge_hello_time;
233     stp->forward_delay = stp->bridge_forward_delay;
234
235     stp->designated_root = stp->bridge_id;
236     stp->root_path_cost = 0;
237     stp->root_port = NULL;
238     stp->topology_change_detected = false;
239     stp->topology_change = false;
240
241     stp_stop_timer(&stp->tcn_timer);
242     stp_stop_timer(&stp->topology_change_timer);
243     stp_start_timer(&stp->hello_timer, 0);
244
245     stp->send_bpdu = send_bpdu;
246     stp->aux = aux;
247
248     stp->first_changed_port = &stp->ports[ARRAY_SIZE(stp->ports)];
249     for (p = stp->ports; p < &stp->ports[ARRAY_SIZE(stp->ports)]; p++) {
250         p->stp = stp;
251         p->port_id = (stp_port_no(p) + 1) | (STP_DEFAULT_PORT_PRIORITY << 8);
252         p->path_cost = 19;      /* Recommended default for 100 Mb/s link. */
253         stp_initialize_port(p, STP_DISABLED);
254     }
255     return stp;
256 }
257
258 /* Destroys 'stp'. */
259 void
260 stp_destroy(struct stp *stp)
261 {
262     if (stp) {
263         free(stp->name);
264         free(stp);
265     }
266 }
267
268 /* Runs 'stp' given that 'ms' milliseconds have passed. */
269 void
270 stp_tick(struct stp *stp, int ms)
271 {
272     struct stp_port *p;
273     int elapsed;
274
275     /* Convert 'ms' to STP timer ticks.  Preserve any leftover milliseconds
276      * from previous stp_tick() calls so that we don't lose STP ticks when we
277      * are called too frequently. */
278     ms = clamp(ms, 0, INT_MAX - 1000) + stp->elapsed_remainder;
279     elapsed = ms_to_timer(ms);
280     stp->elapsed_remainder = ms_to_timer_remainder(ms);
281     if (!elapsed) {
282         return;
283     }
284
285     if (stp_timer_expired(&stp->hello_timer, elapsed, stp->hello_time)) {
286         stp_hello_timer_expiry(stp);
287     }
288     if (stp_timer_expired(&stp->tcn_timer, elapsed, stp->bridge_hello_time)) {
289         stp_tcn_timer_expiry(stp);
290     }
291     if (stp_timer_expired(&stp->topology_change_timer, elapsed,
292                           stp->max_age + stp->forward_delay)) {
293         stp_topology_change_timer_expiry(stp);
294     }
295     FOR_EACH_ENABLED_PORT (p, stp) {
296         if (stp_timer_expired(&p->message_age_timer, elapsed, stp->max_age)) {
297             stp_message_age_timer_expiry(p);
298         }
299     }
300     FOR_EACH_ENABLED_PORT (p, stp) {
301         if (stp_timer_expired(&p->forward_delay_timer, elapsed,
302                               stp->forward_delay)) {
303             stp_forward_delay_timer_expiry(p);
304         }
305         if (stp_timer_expired(&p->hold_timer, elapsed, ms_to_timer(1000))) {
306             stp_hold_timer_expiry(p);
307         }
308     }
309 }
310
311 static void
312 set_bridge_id(struct stp *stp, stp_identifier new_bridge_id)
313 {
314     if (new_bridge_id != stp->bridge_id) {
315         bool root;
316         struct stp_port *p;
317
318         root = stp_is_root_bridge(stp);
319         FOR_EACH_ENABLED_PORT (p, stp) {
320             if (stp_is_designated_port(p)) {
321                 p->designated_bridge = new_bridge_id;
322             }
323         }
324         stp->bridge_id = new_bridge_id;
325         stp_configuration_update(stp);
326         stp_port_state_selection(stp);
327         if (stp_is_root_bridge(stp) && !root) {
328             stp_become_root_bridge(stp);
329         }
330     }
331 }
332
333 void
334 stp_set_bridge_id(struct stp *stp, stp_identifier bridge_id)
335 {
336     const uint64_t mac_bits = (UINT64_C(1) << 48) - 1;
337     const uint64_t pri_bits = ~mac_bits;
338     set_bridge_id(stp, (stp->bridge_id & pri_bits) | (bridge_id & mac_bits));
339 }
340
341 void
342 stp_set_bridge_priority(struct stp *stp, uint16_t new_priority)
343 {
344     const uint64_t mac_bits = (UINT64_C(1) << 48) - 1;
345     set_bridge_id(stp, ((stp->bridge_id & mac_bits)
346                         | ((uint64_t) new_priority << 48)));
347 }
348
349 /* Sets the desired hello time for 'stp' to 'ms', in milliseconds.  The actual
350  * hello time is clamped to the range of 1 to 10 seconds and subject to the
351  * relationship (bridge_max_age >= 2 * (bridge_hello_time + 1 s)).  The bridge
352  * hello time is only used when 'stp' is the root bridge. */
353 void
354 stp_set_hello_time(struct stp *stp, int ms)
355 {
356     stp->rq_hello_time = ms;
357     stp_update_bridge_timers(stp);
358 }
359
360 /* Sets the desired max age for 'stp' to 'ms', in milliseconds.  The actual max
361  * age is clamped to the range of 6 to 40 seconds and subject to the
362  * relationships (2 * (bridge_forward_delay - 1 s) >= bridge_max_age) and
363  * (bridge_max_age >= 2 * (bridge_hello_time + 1 s)).  The bridge max age is
364  * only used when 'stp' is the root bridge. */
365 void
366 stp_set_max_age(struct stp *stp, int ms)
367 {
368     stp->rq_max_age = ms;
369     stp_update_bridge_timers(stp);
370 }
371
372 /* Sets the desired forward delay for 'stp' to 'ms', in milliseconds.  The
373  * actual forward delay is clamped to the range of 4 to 30 seconds and subject
374  * to the relationship (2 * (bridge_forward_delay - 1 s) >= bridge_max_age).
375  * The bridge forward delay is only used when 'stp' is the root bridge. */
376 void
377 stp_set_forward_delay(struct stp *stp, int ms)
378 {
379     stp->rq_forward_delay = ms;
380     stp_update_bridge_timers(stp);
381 }
382
383 /* Returns the name given to 'stp' in the call to stp_create(). */
384 const char *
385 stp_get_name(const struct stp *stp)
386 {
387     return stp->name;
388 }
389
390 /* Returns the bridge ID for 'stp'. */
391 stp_identifier
392 stp_get_bridge_id(const struct stp *stp)
393 {
394     return stp->bridge_id;
395 }
396
397 /* Returns the bridge ID of the bridge currently believed to be the root. */
398 stp_identifier
399 stp_get_designated_root(const struct stp *stp)
400 {
401     return stp->designated_root;
402 }
403
404 /* Returns true if 'stp' believes itself to the be root of the spanning tree,
405  * false otherwise. */
406 bool
407 stp_is_root_bridge(const struct stp *stp)
408 {
409     return stp->bridge_id == stp->designated_root;
410 }
411
412 /* Returns the cost of the path from 'stp' to the root of the spanning tree. */
413 int
414 stp_get_root_path_cost(const struct stp *stp)
415 {
416     return stp->root_path_cost;
417 }
418
419 /* Returns the bridge hello time, in ms.  The returned value is not necessarily
420  * the value passed to stp_set_hello_time(): it is clamped to the valid range
421  * and quantized to the STP timer resolution.  */
422 int
423 stp_get_hello_time(const struct stp *stp)
424 {
425     return timer_to_ms(stp->bridge_hello_time);
426 }
427
428 /* Returns the bridge max age, in ms.  The returned value is not necessarily
429  * the value passed to stp_set_max_age(): it is clamped to the valid range,
430  * quantized to the STP timer resolution, and adjusted to match the constraints
431  * due to the hello time.  */
432 int
433 stp_get_max_age(const struct stp *stp)
434 {
435     return timer_to_ms(stp->bridge_max_age);
436 }
437
438 /* Returns the bridge forward delay, in ms.  The returned value is not
439  * necessarily the value passed to stp_set_forward_delay(): it is clamped to
440  * the valid range, quantized to the STP timer resolution, and adjusted to
441  * match the constraints due to the forward delay.  */
442 int
443 stp_get_forward_delay(const struct stp *stp)
444 {
445     return timer_to_ms(stp->bridge_forward_delay);
446 }
447
448 /* Returns the port in 'stp' with index 'port_no', which must be between 0 and
449  * STP_MAX_PORTS. */
450 struct stp_port *
451 stp_get_port(struct stp *stp, int port_no)
452 {
453     assert(port_no >= 0 && port_no < ARRAY_SIZE(stp->ports));
454     return &stp->ports[port_no];
455 }
456
457 /* Returns the port connecting 'stp' to the root bridge, or a null pointer if
458  * there is no such port. */
459 struct stp_port *
460 stp_get_root_port(struct stp *stp)
461 {
462     return stp->root_port;
463 }
464
465 /* Finds a port whose state has changed.  If successful, stores the port whose
466  * state changed in '*portp' and returns true.  If no port has changed, stores
467  * NULL in '*portp' and returns false. */
468 bool
469 stp_get_changed_port(struct stp *stp, struct stp_port **portp)
470 {
471     struct stp_port *end = &stp->ports[ARRAY_SIZE(stp->ports)];
472     struct stp_port *p;
473
474     for (p = stp->first_changed_port; p < end; p++) {
475         if (p->state_changed) {
476             p->state_changed = false;
477             stp->first_changed_port = p + 1;
478             *portp = p;
479             return true;
480         }
481     }
482     stp->first_changed_port = end;
483     *portp = NULL;
484     return false;
485 }
486
487 /* Returns the name for the given 'state' (for use in debugging and log
488  * messages). */
489 const char *
490 stp_state_name(enum stp_state state)
491 {
492     switch (state) {
493     case STP_DISABLED:
494         return "disabled";
495     case STP_LISTENING:
496         return "listening";
497     case STP_LEARNING:
498         return "learning";
499     case STP_FORWARDING:
500         return "forwarding";
501     case STP_BLOCKING:
502         return "blocking";
503     default:
504         NOT_REACHED();
505     }
506 }
507
508 /* Returns true if 'state' is one in which packets received on a port should
509  * be forwarded, false otherwise.
510  *
511  * Returns true if 'state' is STP_DISABLED, since presumably in that case the
512  * port should still work, just not have STP applied to it. */
513 bool
514 stp_forward_in_state(enum stp_state state)
515 {
516     return (state & (STP_DISABLED | STP_FORWARDING)) != 0;
517 }
518
519 /* Returns true if 'state' is one in which MAC learning should be done on
520  * packets received on a port, false otherwise.
521  *
522  * Returns true if 'state' is STP_DISABLED, since presumably in that case the
523  * port should still work, just not have STP applied to it. */
524 bool
525 stp_learn_in_state(enum stp_state state)
526 {
527     return (state & (STP_DISABLED | STP_LEARNING | STP_FORWARDING)) != 0;
528 }
529
530 /* Returns the name for the given 'role' (for use in debugging and log
531  * messages). */
532 const char *
533 stp_role_name(enum stp_role role)
534 {
535     switch (role) {
536     case STP_ROLE_ROOT:
537         return "root";
538     case STP_ROLE_DESIGNATED:
539         return "designated";
540     case STP_ROLE_ALTERNATE:
541         return "alternate";
542     case STP_ROLE_DISABLED:
543         return "disabled";
544     default:
545         NOT_REACHED();
546     }
547 }
548
549 /* Notifies the STP entity that bridge protocol data unit 'bpdu', which is
550  * 'bpdu_size' bytes in length, was received on port 'p'.
551  *
552  * This function may call the 'send_bpdu' function provided to stp_create(). */
553 void
554 stp_received_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
555 {
556     struct stp *stp = p->stp;
557     const struct stp_bpdu_header *header;
558
559     if (p->state == STP_DISABLED) {
560         return;
561     }
562
563     if (bpdu_size < sizeof(struct stp_bpdu_header)) {
564         VLOG_WARN("%s: received runt %zu-byte BPDU", stp->name, bpdu_size);
565         return;
566     }
567
568     header = bpdu;
569     if (header->protocol_id != htons(STP_PROTOCOL_ID)) {
570         VLOG_WARN("%s: received BPDU with unexpected protocol ID %"PRIu16,
571                   stp->name, ntohs(header->protocol_id));
572         return;
573     }
574     if (header->protocol_version != STP_PROTOCOL_VERSION) {
575         VLOG_DBG("%s: received BPDU with unexpected protocol version %"PRIu8,
576                  stp->name, header->protocol_version);
577     }
578
579     switch (header->bpdu_type) {
580     case STP_TYPE_CONFIG:
581         if (bpdu_size < sizeof(struct stp_config_bpdu)) {
582             VLOG_WARN("%s: received config BPDU with invalid size %zu",
583                       stp->name, bpdu_size);
584             return;
585         }
586         stp_received_config_bpdu(stp, p, bpdu);
587         break;
588
589     case STP_TYPE_TCN:
590         if (bpdu_size != sizeof(struct stp_tcn_bpdu)) {
591             VLOG_WARN("%s: received TCN BPDU with invalid size %zu",
592                       stp->name, bpdu_size);
593             return;
594         }
595         stp_received_tcn_bpdu(stp, p);
596         break;
597
598     default:
599         VLOG_WARN("%s: received BPDU of unexpected type %"PRIu8,
600                   stp->name, header->bpdu_type);
601         return;
602     }
603 }
604
605 /* Returns the STP entity in which 'p' is nested. */
606 struct stp *
607 stp_port_get_stp(struct stp_port *p)
608 {
609     return p->stp;
610 }
611
612 /* Sets the 'aux' member of 'p'.
613  *
614  * The 'aux' member will be reset to NULL when stp_port_disable() is
615  * called or stp_port_enable() is called when the port is in a Disabled
616  * state. */
617 void
618 stp_port_set_aux(struct stp_port *p, void *aux)
619 {
620     p->aux = aux;
621 }
622
623 /* Returns the 'aux' member of 'p'. */
624 void *
625 stp_port_get_aux(struct stp_port *p)
626 {
627     return p->aux;
628 }
629
630 /* Returns the index of port 'p' within its bridge. */
631 int
632 stp_port_no(const struct stp_port *p)
633 {
634     struct stp *stp = p->stp;
635     assert(p >= stp->ports && p < &stp->ports[ARRAY_SIZE(stp->ports)]);
636     return p - stp->ports;
637 }
638
639 /* Returns the port ID for 'p'. */
640 int
641 stp_port_get_id(const struct stp_port *p)
642 {
643     return p->port_id;
644 }
645
646 /* Returns the state of port 'p'. */
647 enum stp_state
648 stp_port_get_state(const struct stp_port *p)
649 {
650     return p->state;
651 }
652
653 /* Returns the role of port 'p'. */
654 enum stp_role
655 stp_port_get_role(const struct stp_port *p)
656 {
657     struct stp_port *root_port = stp_get_root_port(p->stp);
658
659     if (root_port && root_port->port_id == p->port_id) {
660         return STP_ROLE_ROOT;
661     } else if (stp_is_designated_port(p)) {
662         return STP_ROLE_DESIGNATED;
663     } else if (p->state == STP_DISABLED) {
664         return STP_ROLE_DISABLED;
665     } else {
666         return STP_ROLE_ALTERNATE;
667     }
668 }
669
670 /* Disables STP on port 'p'. */
671 void
672 stp_port_disable(struct stp_port *p)
673 {
674     struct stp *stp = p->stp;
675     if (p->state != STP_DISABLED) {
676         bool root = stp_is_root_bridge(stp);
677         stp_become_designated_port(p);
678         stp_set_port_state(p, STP_DISABLED);
679         p->topology_change_ack = false;
680         p->config_pending = false;
681         stp_stop_timer(&p->message_age_timer);
682         stp_stop_timer(&p->forward_delay_timer);
683         stp_configuration_update(stp);
684         stp_port_state_selection(stp);
685         if (stp_is_root_bridge(stp) && !root) {
686             stp_become_root_bridge(stp);
687         }
688         p->aux = NULL;
689     }
690 }
691
692 /* Enables STP on port 'p'.  The port will initially be in "blocking" state. */
693 void
694 stp_port_enable(struct stp_port *p)
695 {
696     if (p->state == STP_DISABLED) {
697         stp_initialize_port(p, STP_BLOCKING);
698         stp_port_state_selection(p->stp);
699     }
700 }
701
702 /* Sets the priority of port 'p' to 'new_priority'.  Lower numerical values
703  * are interpreted as higher priorities. */
704 void
705 stp_port_set_priority(struct stp_port *p, uint8_t new_priority)
706 {
707     uint16_t new_port_id = (p->port_id & 0xff) | (new_priority << 8);
708     if (p->port_id != new_port_id) {
709         struct stp *stp = p->stp;
710         if (stp_is_designated_port(p)) {
711             p->designated_port = new_port_id;
712         }
713         p->port_id = new_port_id;
714         if (stp->bridge_id == p->designated_bridge
715             && p->port_id < p->designated_port) {
716             stp_become_designated_port(p);
717             stp_port_state_selection(stp);
718         }
719     }
720 }
721
722 /* Convert 'speed' (measured in Mb/s) into the path cost. */
723 uint16_t
724 stp_convert_speed_to_cost(unsigned int speed)
725 {
726     return speed >= 10000 ? 2  /* 10 Gb/s. */
727            : speed >= 1000 ? 4 /* 1 Gb/s. */
728            : speed >= 100 ? 19 /* 100 Mb/s. */
729            : speed >= 16 ? 62  /* 16 Mb/s. */
730            : speed >= 10 ? 100 /* 10 Mb/s. */
731            : speed >= 4 ? 250  /* 4 Mb/s. */
732            : 19;             /* 100 Mb/s (guess). */
733 }
734
735 /* Sets the path cost of port 'p' to 'path_cost'.  Lower values are generally
736  * used to indicate faster links.  Use stp_port_set_speed() to automatically
737  * generate a default path cost from a link speed. */
738 void
739 stp_port_set_path_cost(struct stp_port *p, uint16_t path_cost)
740 {
741     if (p->path_cost != path_cost) {
742         struct stp *stp = p->stp;
743         p->path_cost = path_cost;
744         stp_configuration_update(stp);
745         stp_port_state_selection(stp);
746     }
747 }
748
749 /* Sets the path cost of port 'p' based on 'speed' (measured in Mb/s). */
750 void
751 stp_port_set_speed(struct stp_port *p, unsigned int speed)
752 {
753     stp_port_set_path_cost(p, stp_convert_speed_to_cost(speed));
754 }
755
756 /* Enables topology change detection on port 'p'. */
757 void
758 stp_port_enable_change_detection(struct stp_port *p)
759 {
760     p->change_detection_enabled = true;
761 }
762
763 /* Disables topology change detection on port 'p'. */
764 void
765 stp_port_disable_change_detection(struct stp_port *p)
766 {
767     p->change_detection_enabled = false;
768 }
769 \f
770 static void
771 stp_transmit_config(struct stp_port *p)
772 {
773     struct stp *stp = p->stp;
774     bool root = stp_is_root_bridge(stp);
775     if (!root && !stp->root_port) {
776         return;
777     }
778     if (p->hold_timer.active) {
779         p->config_pending = true;
780     } else {
781         struct stp_config_bpdu config;
782         memset(&config, 0, sizeof config);
783         config.header.protocol_id = htons(STP_PROTOCOL_ID);
784         config.header.protocol_version = STP_PROTOCOL_VERSION;
785         config.header.bpdu_type = STP_TYPE_CONFIG;
786         config.flags = 0;
787         if (p->topology_change_ack) {
788             config.flags |= STP_CONFIG_TOPOLOGY_CHANGE_ACK;
789         }
790         if (stp->topology_change) {
791             config.flags |= STP_CONFIG_TOPOLOGY_CHANGE;
792         }
793         config.root_id = htonll(stp->designated_root);
794         config.root_path_cost = htonl(stp->root_path_cost);
795         config.bridge_id = htonll(stp->bridge_id);
796         config.port_id = htons(p->port_id);
797         if (root) {
798             config.message_age = htons(0);
799         } else {
800             config.message_age = htons(stp->root_port->message_age_timer.value
801                                        + MESSAGE_AGE_INCREMENT);
802         }
803         config.max_age = htons(stp->max_age);
804         config.hello_time = htons(stp->hello_time);
805         config.forward_delay = htons(stp->forward_delay);
806         if (ntohs(config.message_age) < stp->max_age) {
807             p->topology_change_ack = false;
808             p->config_pending = false;
809             stp_send_bpdu(p, &config, sizeof config);
810             stp_start_timer(&p->hold_timer, 0);
811         }
812     }
813 }
814
815 static bool
816 stp_supersedes_port_info(const struct stp_port *p,
817                          const struct stp_config_bpdu *config)
818 {
819     if (ntohll(config->root_id) != p->designated_root) {
820         return ntohll(config->root_id) < p->designated_root;
821     } else if (ntohl(config->root_path_cost) != p->designated_cost) {
822         return ntohl(config->root_path_cost) < p->designated_cost;
823     } else if (ntohll(config->bridge_id) != p->designated_bridge) {
824         return ntohll(config->bridge_id) < p->designated_bridge;
825     } else {
826         return (ntohll(config->bridge_id) != p->stp->bridge_id
827                 || ntohs(config->port_id) <= p->designated_port);
828     }
829 }
830
831 static void
832 stp_record_config_information(struct stp_port *p,
833                               const struct stp_config_bpdu *config)
834 {
835     p->designated_root = ntohll(config->root_id);
836     p->designated_cost = ntohl(config->root_path_cost);
837     p->designated_bridge = ntohll(config->bridge_id);
838     p->designated_port = ntohs(config->port_id);
839     stp_start_timer(&p->message_age_timer, ntohs(config->message_age));
840 }
841
842 static void
843 stp_record_config_timeout_values(struct stp *stp,
844                                  const struct stp_config_bpdu  *config)
845 {
846     stp->max_age = ntohs(config->max_age);
847     stp->hello_time = ntohs(config->hello_time);
848     stp->forward_delay = ntohs(config->forward_delay);
849     stp->topology_change = config->flags & STP_CONFIG_TOPOLOGY_CHANGE;
850 }
851
852 static bool
853 stp_is_designated_port(const struct stp_port *p)
854 {
855     return (p->designated_bridge == p->stp->bridge_id
856             && p->designated_port == p->port_id);
857 }
858
859 static void
860 stp_config_bpdu_generation(struct stp *stp)
861 {
862     struct stp_port *p;
863
864     FOR_EACH_ENABLED_PORT (p, stp) {
865         if (stp_is_designated_port(p)) {
866             stp_transmit_config(p);
867         }
868     }
869 }
870
871 static void
872 stp_transmit_tcn(struct stp *stp)
873 {
874     struct stp_port *p = stp->root_port;
875     struct stp_tcn_bpdu tcn_bpdu;
876     if (!p) {
877         return;
878     }
879     tcn_bpdu.header.protocol_id = htons(STP_PROTOCOL_ID);
880     tcn_bpdu.header.protocol_version = STP_PROTOCOL_VERSION;
881     tcn_bpdu.header.bpdu_type = STP_TYPE_TCN;
882     stp_send_bpdu(p, &tcn_bpdu, sizeof tcn_bpdu);
883 }
884
885 static void
886 stp_configuration_update(struct stp *stp)
887 {
888     stp_root_selection(stp);
889     stp_designated_port_selection(stp);
890 }
891
892 static bool
893 stp_supersedes_root(const struct stp_port *root, const struct stp_port *p)
894 {
895     int p_cost = p->designated_cost + p->path_cost;
896     int root_cost = root->designated_cost + root->path_cost;
897
898     if (p->designated_root != root->designated_root) {
899         return p->designated_root < root->designated_root;
900     } else if (p_cost != root_cost) {
901         return p_cost < root_cost;
902     } else if (p->designated_bridge != root->designated_bridge) {
903         return p->designated_bridge < root->designated_bridge;
904     } else if (p->designated_port != root->designated_port) {
905         return p->designated_port < root->designated_port;
906     } else {
907         return p->port_id < root->port_id;
908     }
909 }
910
911 static void
912 stp_root_selection(struct stp *stp)
913 {
914     struct stp_port *p, *root;
915
916     root = NULL;
917     FOR_EACH_ENABLED_PORT (p, stp) {
918         if (stp_is_designated_port(p)
919             || p->designated_root >= stp->bridge_id) {
920             continue;
921         }
922         if (root && !stp_supersedes_root(root, p)) {
923             continue;
924         }
925         root = p;
926     }
927     stp->root_port = root;
928     if (!root) {
929         stp->designated_root = stp->bridge_id;
930         stp->root_path_cost = 0;
931     } else {
932         stp->designated_root = root->designated_root;
933         stp->root_path_cost = root->designated_cost + root->path_cost;
934     }
935 }
936
937 static void
938 stp_designated_port_selection(struct stp *stp)
939 {
940     struct stp_port *p;
941
942     FOR_EACH_ENABLED_PORT (p, stp) {
943         if (stp_is_designated_port(p)
944             || p->designated_root != stp->designated_root
945             || stp->root_path_cost < p->designated_cost
946             || (stp->root_path_cost == p->designated_cost
947                 && (stp->bridge_id < p->designated_bridge
948                     || (stp->bridge_id == p->designated_bridge
949                         && p->port_id <= p->designated_port))))
950         {
951             stp_become_designated_port(p);
952         }
953     }
954 }
955
956 static void
957 stp_become_designated_port(struct stp_port *p)
958 {
959     struct stp *stp = p->stp;
960     p->designated_root = stp->designated_root;
961     p->designated_cost = stp->root_path_cost;
962     p->designated_bridge = stp->bridge_id;
963     p->designated_port = p->port_id;
964 }
965
966 static void
967 stp_port_state_selection(struct stp *stp)
968 {
969     struct stp_port *p;
970
971     FOR_EACH_ENABLED_PORT (p, stp) {
972         if (p == stp->root_port) {
973             p->config_pending = false;
974             p->topology_change_ack = false;
975             stp_make_forwarding(p);
976         } else if (stp_is_designated_port(p)) {
977             stp_stop_timer(&p->message_age_timer);
978             stp_make_forwarding(p);
979         } else {
980             p->config_pending = false;
981             p->topology_change_ack = false;
982             stp_make_blocking(p);
983         }
984     }
985 }
986
987 static void
988 stp_make_forwarding(struct stp_port *p)
989 {
990     if (p->state == STP_BLOCKING) {
991         stp_set_port_state(p, STP_LISTENING);
992         stp_start_timer(&p->forward_delay_timer, 0);
993     }
994 }
995
996 static void
997 stp_make_blocking(struct stp_port *p)
998 {
999     if (!(p->state & (STP_DISABLED | STP_BLOCKING))) {
1000         if (p->state & (STP_FORWARDING | STP_LEARNING)) {
1001             if (p->change_detection_enabled) {
1002                 stp_topology_change_detection(p->stp);
1003             }
1004         }
1005         stp_set_port_state(p, STP_BLOCKING);
1006         stp_stop_timer(&p->forward_delay_timer);
1007     }
1008 }
1009
1010 static void
1011 stp_set_port_state(struct stp_port *p, enum stp_state state)
1012 {
1013     if (state != p->state && !p->state_changed) {
1014         p->state_changed = true;
1015         if (p < p->stp->first_changed_port) {
1016             p->stp->first_changed_port = p;
1017         }
1018     }
1019     p->state = state;
1020 }
1021
1022 static void
1023 stp_topology_change_detection(struct stp *stp)
1024 {
1025     if (stp_is_root_bridge(stp)) {
1026         stp->topology_change = true;
1027         stp_start_timer(&stp->topology_change_timer, 0);
1028     } else if (!stp->topology_change_detected) {
1029         stp_transmit_tcn(stp);
1030         stp_start_timer(&stp->tcn_timer, 0);
1031     }
1032     stp->topology_change_detected = true;
1033 }
1034
1035 static void
1036 stp_topology_change_acknowledged(struct stp *stp)
1037 {
1038     stp->topology_change_detected = false;
1039     stp_stop_timer(&stp->tcn_timer);
1040 }
1041
1042 static void
1043 stp_acknowledge_topology_change(struct stp_port *p)
1044 {
1045     p->topology_change_ack = true;
1046     stp_transmit_config(p);
1047 }
1048
1049 static void
1050 stp_received_config_bpdu(struct stp *stp, struct stp_port *p,
1051                          const struct stp_config_bpdu *config)
1052 {
1053     if (ntohs(config->message_age) >= ntohs(config->max_age)) {
1054         VLOG_WARN("%s: received config BPDU with message age (%u) greater "
1055                   "than max age (%u)",
1056                   stp->name,
1057                   ntohs(config->message_age), ntohs(config->max_age));
1058         return;
1059     }
1060     if (p->state != STP_DISABLED) {
1061         bool root = stp_is_root_bridge(stp);
1062         if (stp_supersedes_port_info(p, config)) {
1063             stp_record_config_information(p, config);
1064             stp_configuration_update(stp);
1065             stp_port_state_selection(stp);
1066             if (!stp_is_root_bridge(stp) && root) {
1067                 stp_stop_timer(&stp->hello_timer);
1068                 if (stp->topology_change_detected) {
1069                     stp_stop_timer(&stp->topology_change_timer);
1070                     stp_transmit_tcn(stp);
1071                     stp_start_timer(&stp->tcn_timer, 0);
1072                 }
1073             }
1074             if (p == stp->root_port) {
1075                 stp_record_config_timeout_values(stp, config);
1076                 stp_config_bpdu_generation(stp);
1077                 if (config->flags & STP_CONFIG_TOPOLOGY_CHANGE_ACK) {
1078                     stp_topology_change_acknowledged(stp);
1079                 }
1080             }
1081         } else if (stp_is_designated_port(p)) {
1082             stp_transmit_config(p);
1083         }
1084     }
1085 }
1086
1087 static void
1088 stp_received_tcn_bpdu(struct stp *stp, struct stp_port *p)
1089 {
1090     if (p->state != STP_DISABLED) {
1091         if (stp_is_designated_port(p)) {
1092             stp_topology_change_detection(stp);
1093             stp_acknowledge_topology_change(p);
1094         }
1095     }
1096 }
1097
1098 static void
1099 stp_hello_timer_expiry(struct stp *stp)
1100 {
1101     stp_config_bpdu_generation(stp);
1102     stp_start_timer(&stp->hello_timer, 0);
1103 }
1104
1105 static void
1106 stp_message_age_timer_expiry(struct stp_port *p)
1107 {
1108     struct stp *stp = p->stp;
1109     bool root = stp_is_root_bridge(stp);
1110     stp_become_designated_port(p);
1111     stp_configuration_update(stp);
1112     stp_port_state_selection(stp);
1113     if (stp_is_root_bridge(stp) && !root) {
1114         stp->max_age = stp->bridge_max_age;
1115         stp->hello_time = stp->bridge_hello_time;
1116         stp->forward_delay = stp->bridge_forward_delay;
1117         stp_topology_change_detection(stp);
1118         stp_stop_timer(&stp->tcn_timer);
1119         stp_config_bpdu_generation(stp);
1120         stp_start_timer(&stp->hello_timer, 0);
1121     }
1122 }
1123
1124 static bool
1125 stp_is_designated_for_some_port(const struct stp *stp)
1126 {
1127     const struct stp_port *p;
1128
1129     FOR_EACH_ENABLED_PORT (p, stp) {
1130         if (p->designated_bridge == stp->bridge_id) {
1131             return true;
1132         }
1133     }
1134     return false;
1135 }
1136
1137 static void
1138 stp_forward_delay_timer_expiry(struct stp_port *p)
1139 {
1140     if (p->state == STP_LISTENING) {
1141         stp_set_port_state(p, STP_LEARNING);
1142         stp_start_timer(&p->forward_delay_timer, 0);
1143     } else if (p->state == STP_LEARNING) {
1144         stp_set_port_state(p, STP_FORWARDING);
1145         if (stp_is_designated_for_some_port(p->stp)) {
1146             if (p->change_detection_enabled) {
1147                 stp_topology_change_detection(p->stp);
1148             }
1149         }
1150     }
1151 }
1152
1153 static void
1154 stp_tcn_timer_expiry(struct stp *stp)
1155 {
1156     stp_transmit_tcn(stp);
1157     stp_start_timer(&stp->tcn_timer, 0);
1158 }
1159
1160 static void
1161 stp_topology_change_timer_expiry(struct stp *stp)
1162 {
1163     stp->topology_change_detected = false;
1164     stp->topology_change = false;
1165 }
1166
1167 static void
1168 stp_hold_timer_expiry(struct stp_port *p)
1169 {
1170     if (p->config_pending) {
1171         stp_transmit_config(p);
1172     }
1173 }
1174
1175 static void
1176 stp_initialize_port(struct stp_port *p, enum stp_state state)
1177 {
1178     assert(state & (STP_DISABLED | STP_BLOCKING));
1179     stp_become_designated_port(p);
1180     stp_set_port_state(p, state);
1181     p->topology_change_ack = false;
1182     p->config_pending = false;
1183     p->change_detection_enabled = true;
1184     p->aux = NULL;
1185     stp_stop_timer(&p->message_age_timer);
1186     stp_stop_timer(&p->forward_delay_timer);
1187     stp_stop_timer(&p->hold_timer);
1188 }
1189
1190 static void
1191 stp_become_root_bridge(struct stp *stp)
1192 {
1193     stp->max_age = stp->bridge_max_age;
1194     stp->hello_time = stp->bridge_hello_time;
1195     stp->forward_delay = stp->bridge_forward_delay;
1196     stp_topology_change_detection(stp);
1197     stp_stop_timer(&stp->tcn_timer);
1198     stp_config_bpdu_generation(stp);
1199     stp_start_timer(&stp->hello_timer, 0);
1200 }
1201
1202 static void
1203 stp_start_timer(struct stp_timer *timer, int value)
1204 {
1205     timer->value = value;
1206     timer->active = true;
1207 }
1208
1209 static void
1210 stp_stop_timer(struct stp_timer *timer)
1211 {
1212     timer->active = false;
1213 }
1214
1215 static bool
1216 stp_timer_expired(struct stp_timer *timer, int elapsed, int timeout)
1217 {
1218     if (timer->active) {
1219         timer->value += elapsed;
1220         if (timer->value >= timeout) {
1221             timer->active = false;
1222             return true;
1223         }
1224     }
1225     return false;
1226 }
1227
1228 /* Returns the number of whole STP timer ticks in 'ms' milliseconds.  There
1229  * are 256 STP timer ticks per second. */
1230 static int
1231 ms_to_timer(int ms)
1232 {
1233     return ms * 0x100 / 1000;
1234 }
1235
1236 /* Returns the number of leftover milliseconds when 'ms' is converted to STP
1237  * timer ticks. */
1238 static int
1239 ms_to_timer_remainder(int ms)
1240 {
1241     return ms * 0x100 % 1000;
1242 }
1243
1244 /* Returns the number of whole milliseconds in 'timer' STP timer ticks.  There
1245  * are 256 STP timer ticks per second. */
1246 static int
1247 timer_to_ms(int timer)
1248 {
1249     return timer * 1000 / 0x100;
1250 }
1251
1252 static int
1253 clamp(int x, int min, int max)
1254 {
1255     return x < min ? min : x > max ? max : x;
1256 }
1257
1258 static void
1259 stp_update_bridge_timers(struct stp *stp)
1260 {
1261     int ht, ma, fd;
1262
1263     ht = clamp(stp->rq_hello_time, 1000, 10000);
1264     ma = clamp(stp->rq_max_age, MAX(2 * (ht + 1000), 6000), 40000);
1265     fd = clamp(stp->rq_forward_delay, ma / 2 + 1000, 30000);
1266
1267     stp->bridge_hello_time = ms_to_timer(ht);
1268     stp->bridge_max_age = ms_to_timer(ma);
1269     stp->bridge_forward_delay = ms_to_timer(fd);
1270
1271     if (stp_is_root_bridge(stp)) {
1272         stp->max_age = stp->bridge_max_age;
1273         stp->hello_time = stp->bridge_hello_time;
1274         stp->forward_delay = stp->bridge_forward_delay;
1275     }
1276 }
1277
1278 static void
1279 stp_send_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
1280 {
1281     struct eth_header *eth;
1282     struct llc_header *llc;
1283     struct ofpbuf *pkt;
1284
1285     /* Skeleton. */
1286     pkt = ofpbuf_new(ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1287     pkt->l2 = eth = ofpbuf_put_zeros(pkt, sizeof *eth);
1288     llc = ofpbuf_put_zeros(pkt, sizeof *llc);
1289     pkt->l3 = ofpbuf_put(pkt, bpdu, bpdu_size);
1290
1291     /* 802.2 header. */
1292     memcpy(eth->eth_dst, eth_addr_stp, ETH_ADDR_LEN);
1293     /* p->stp->send_bpdu() must fill in source address. */
1294     eth->eth_type = htons(pkt->size - ETH_HEADER_LEN);
1295
1296     /* LLC header. */
1297     llc->llc_dsap = STP_LLC_DSAP;
1298     llc->llc_ssap = STP_LLC_SSAP;
1299     llc->llc_cntl = STP_LLC_CNTL;
1300
1301     p->stp->send_bpdu(pkt, stp_port_no(p), p->stp->aux);
1302 }