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