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