Merge "master" into "next".
[cascardo/ovs.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 = xzalloc(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     if (stp) {
262         free(stp->name);
263         free(stp);
264     }
265 }
266
267 /* Runs 'stp' given that 'ms' milliseconds have passed. */
268 void
269 stp_tick(struct stp *stp, int ms)
270 {
271     struct stp_port *p;
272     int elapsed;
273
274     /* Convert 'ms' to STP timer ticks.  Preserve any leftover milliseconds
275      * from previous stp_tick() calls so that we don't lose STP ticks when we
276      * are called too frequently. */
277     ms = clamp(ms, 0, INT_MAX - 1000) + stp->elapsed_remainder;
278     elapsed = ms_to_timer(ms);
279     stp->elapsed_remainder = ms_to_timer_remainder(ms);
280     if (!elapsed) {
281         return;
282     }
283
284     if (stp_timer_expired(&stp->hello_timer, elapsed, stp->hello_time)) {
285         stp_hello_timer_expiry(stp);
286     }
287     if (stp_timer_expired(&stp->tcn_timer, elapsed, stp->bridge_hello_time)) {
288         stp_tcn_timer_expiry(stp);
289     }
290     if (stp_timer_expired(&stp->topology_change_timer, elapsed,
291                           stp->max_age + stp->forward_delay)) {
292         stp_topology_change_timer_expiry(stp);
293     }
294     FOR_EACH_ENABLED_PORT (p, stp) {
295         if (stp_timer_expired(&p->message_age_timer, elapsed, stp->max_age)) {
296             stp_message_age_timer_expiry(p);
297         }
298     }
299     FOR_EACH_ENABLED_PORT (p, stp) {
300         if (stp_timer_expired(&p->forward_delay_timer, elapsed,
301                               stp->forward_delay)) {
302             stp_forward_delay_timer_expiry(p);
303         }
304         if (stp_timer_expired(&p->hold_timer, elapsed, ms_to_timer(1000))) {
305             stp_hold_timer_expiry(p);
306         }
307     }
308 }
309
310 static void
311 set_bridge_id(struct stp *stp, stp_identifier new_bridge_id)
312 {
313     if (new_bridge_id != stp->bridge_id) {
314         bool root;
315         struct stp_port *p;
316
317         root = stp_is_root_bridge(stp);
318         FOR_EACH_ENABLED_PORT (p, stp) {
319             if (stp_is_designated_port(p)) {
320                 p->designated_bridge = new_bridge_id;
321             }
322         }
323         stp->bridge_id = new_bridge_id;
324         stp_configuration_update(stp);
325         stp_port_state_selection(stp);
326         if (stp_is_root_bridge(stp) && !root) {
327             stp_become_root_bridge(stp);
328         }
329     }
330 }
331
332 void
333 stp_set_bridge_id(struct stp *stp, stp_identifier bridge_id)
334 {
335     const uint64_t mac_bits = (UINT64_C(1) << 48) - 1;
336     const uint64_t pri_bits = ~mac_bits;
337     set_bridge_id(stp, (stp->bridge_id & pri_bits) | (bridge_id & mac_bits));
338 }
339
340 void
341 stp_set_bridge_priority(struct stp *stp, uint16_t new_priority)
342 {
343     const uint64_t mac_bits = (UINT64_C(1) << 48) - 1;
344     set_bridge_id(stp, ((stp->bridge_id & mac_bits)
345                         | ((uint64_t) new_priority << 48)));
346 }
347
348 /* Sets the desired hello time for 'stp' to 'ms', in milliseconds.  The actual
349  * hello time is clamped to the range of 1 to 10 seconds and subject to the
350  * relationship (bridge_max_age >= 2 * (bridge_hello_time + 1 s)).  The bridge
351  * hello time is only used when 'stp' is the root bridge. */
352 void
353 stp_set_hello_time(struct stp *stp, int ms)
354 {
355     stp->rq_hello_time = ms;
356     stp_update_bridge_timers(stp);
357 }
358
359 /* Sets the desired max age for 'stp' to 'ms', in milliseconds.  The actual max
360  * age is clamped to the range of 6 to 40 seconds and subject to the
361  * relationships (2 * (bridge_forward_delay - 1 s) >= bridge_max_age) and
362  * (bridge_max_age >= 2 * (bridge_hello_time + 1 s)).  The bridge max age is
363  * only used when 'stp' is the root bridge. */
364 void
365 stp_set_max_age(struct stp *stp, int ms)
366 {
367     stp->rq_max_age = ms;
368     stp_update_bridge_timers(stp);
369 }
370
371 /* Sets the desired forward delay for 'stp' to 'ms', in milliseconds.  The
372  * actual forward delay is clamped to the range of 4 to 30 seconds and subject
373  * to the relationship (2 * (bridge_forward_delay - 1 s) >= bridge_max_age).
374  * The bridge forward delay is only used when 'stp' is the root bridge. */
375 void
376 stp_set_forward_delay(struct stp *stp, int ms)
377 {
378     stp->rq_forward_delay = ms;
379     stp_update_bridge_timers(stp);
380 }
381
382 /* Returns the name given to 'stp' in the call to stp_create(). */
383 const char *
384 stp_get_name(const struct stp *stp)
385 {
386     return stp->name;
387 }
388
389 /* Returns the bridge ID for 'stp'. */
390 stp_identifier
391 stp_get_bridge_id(const struct stp *stp)
392 {
393     return stp->bridge_id;
394 }
395
396 /* Returns the bridge ID of the bridge currently believed to be the root. */
397 stp_identifier
398 stp_get_designated_root(const struct stp *stp)
399 {
400     return stp->designated_root;
401 }
402
403 /* Returns true if 'stp' believes itself to the be root of the spanning tree,
404  * false otherwise. */
405 bool
406 stp_is_root_bridge(const struct stp *stp)
407 {
408     return stp->bridge_id == stp->designated_root;
409 }
410
411 /* Returns the cost of the path from 'stp' to the root of the spanning tree. */
412 int
413 stp_get_root_path_cost(const struct stp *stp)
414 {
415     return stp->root_path_cost;
416 }
417
418 /* Returns the bridge hello time, in ms.  The returned value is not necessarily
419  * the value passed to stp_set_hello_time(): it is clamped to the valid range
420  * and quantized to the STP timer resolution.  */
421 int
422 stp_get_hello_time(const struct stp *stp)
423 {
424     return timer_to_ms(stp->bridge_hello_time);
425 }
426
427 /* Returns the bridge max age, in ms.  The returned value is not necessarily
428  * the value passed to stp_set_max_age(): it is clamped to the valid range,
429  * quantized to the STP timer resolution, and adjusted to match the constraints
430  * due to the hello time.  */
431 int
432 stp_get_max_age(const struct stp *stp)
433 {
434     return timer_to_ms(stp->bridge_max_age);
435 }
436
437 /* Returns the bridge forward delay, in ms.  The returned value is not
438  * necessarily the value passed to stp_set_forward_delay(): it is clamped to
439  * the valid range, quantized to the STP timer resolution, and adjusted to
440  * match the constraints due to the forward delay.  */
441 int
442 stp_get_forward_delay(const struct stp *stp)
443 {
444     return timer_to_ms(stp->bridge_forward_delay);
445 }
446
447 /* Returns the port in 'stp' with index 'port_no', which must be between 0 and
448  * STP_MAX_PORTS. */
449 struct stp_port *
450 stp_get_port(struct stp *stp, int port_no)
451 {
452     assert(port_no >= 0 && port_no < ARRAY_SIZE(stp->ports));
453     return &stp->ports[port_no];
454 }
455
456 /* Returns the port connecting 'stp' to the root bridge, or a null pointer if
457  * there is no such port. */
458 struct stp_port *
459 stp_get_root_port(struct stp *stp)
460 {
461     return stp->root_port;
462 }
463
464 /* Finds a port whose state has changed.  If successful, stores the port whose
465  * state changed in '*portp' and returns true.  If no port has changed, stores
466  * NULL in '*portp' and returns false. */
467 bool
468 stp_get_changed_port(struct stp *stp, struct stp_port **portp)
469 {
470     struct stp_port *end = &stp->ports[ARRAY_SIZE(stp->ports)];
471     struct stp_port *p;
472
473     for (p = stp->first_changed_port; p < end; p++) {
474         if (p->state_changed) {
475             p->state_changed = false;
476             stp->first_changed_port = p + 1;
477             *portp = p;
478             return true;
479         }
480     }
481     stp->first_changed_port = end;
482     *portp = NULL;
483     return false;
484 }
485
486 /* Returns the name for the given 'state' (for use in debugging and log
487  * messages). */
488 const char *
489 stp_state_name(enum stp_state state)
490 {
491     switch (state) {
492     case STP_DISABLED:
493         return "disabled";
494     case STP_LISTENING:
495         return "listening";
496     case STP_LEARNING:
497         return "learning";
498     case STP_FORWARDING:
499         return "forwarding";
500     case STP_BLOCKING:
501         return "blocking";
502     default:
503         NOT_REACHED();
504     }
505 }
506
507 /* Returns true if 'state' is one in which packets received on a port should
508  * be forwarded, false otherwise.
509  *
510  * Returns true if 'state' is STP_DISABLED, since presumably in that case the
511  * port should still work, just not have STP applied to it. */
512 bool
513 stp_forward_in_state(enum stp_state state)
514 {
515     return (state & (STP_DISABLED | STP_FORWARDING)) != 0;
516 }
517
518 /* Returns true if 'state' is one in which MAC learning should be done on
519  * packets received on a port, false otherwise.
520  *
521  * Returns true if 'state' is STP_DISABLED, since presumably in that case the
522  * port should still work, just not have STP applied to it. */
523 bool
524 stp_learn_in_state(enum stp_state state)
525 {
526     return (state & (STP_DISABLED | STP_LEARNING | STP_FORWARDING)) != 0;
527 }
528
529 /* Notifies the STP entity that bridge protocol data unit 'bpdu', which is
530  * 'bpdu_size' bytes in length, was received on port 'p'.
531  *
532  * This function may call the 'send_bpdu' function provided to stp_create(). */
533 void
534 stp_received_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
535 {
536     struct stp *stp = p->stp;
537     const struct stp_bpdu_header *header;
538
539     if (p->state == STP_DISABLED) {
540         return;
541     }
542
543     if (bpdu_size < sizeof(struct stp_bpdu_header)) {
544         VLOG_WARN("%s: received runt %zu-byte BPDU", stp->name, bpdu_size);
545         return;
546     }
547
548     header = bpdu;
549     if (header->protocol_id != htons(STP_PROTOCOL_ID)) {
550         VLOG_WARN("%s: received BPDU with unexpected protocol ID %"PRIu16,
551                   stp->name, ntohs(header->protocol_id));
552         return;
553     }
554     if (header->protocol_version != STP_PROTOCOL_VERSION) {
555         VLOG_DBG("%s: received BPDU with unexpected protocol version %"PRIu8,
556                  stp->name, header->protocol_version);
557     }
558
559     switch (header->bpdu_type) {
560     case STP_TYPE_CONFIG:
561         if (bpdu_size < sizeof(struct stp_config_bpdu)) {
562             VLOG_WARN("%s: received config BPDU with invalid size %zu",
563                       stp->name, bpdu_size);
564             return;
565         }
566         stp_received_config_bpdu(stp, p, bpdu);
567         break;
568
569     case STP_TYPE_TCN:
570         if (bpdu_size != sizeof(struct stp_tcn_bpdu)) {
571             VLOG_WARN("%s: received TCN BPDU with invalid size %zu",
572                       stp->name, bpdu_size);
573             return;
574         }
575         stp_received_tcn_bpdu(stp, p);
576         break;
577
578     default:
579         VLOG_WARN("%s: received BPDU of unexpected type %"PRIu8,
580                   stp->name, header->bpdu_type);
581         return;
582     }
583 }
584
585 /* Returns the STP entity in which 'p' is nested. */
586 struct stp *
587 stp_port_get_stp(struct stp_port *p)
588 {
589     return p->stp;
590 }
591
592 /* Returns the index of port 'p' within its bridge. */
593 int
594 stp_port_no(const struct stp_port *p)
595 {
596     struct stp *stp = p->stp;
597     assert(p >= stp->ports && p < &stp->ports[ARRAY_SIZE(stp->ports)]);
598     return p - stp->ports;
599 }
600
601 /* Returns the state of port 'p'. */
602 enum stp_state
603 stp_port_get_state(const struct stp_port *p)
604 {
605     return p->state;
606 }
607
608 /* Disables STP on port 'p'. */
609 void
610 stp_port_disable(struct stp_port *p)
611 {
612     struct stp *stp = p->stp;
613     if (p->state != STP_DISABLED) {
614         bool root = stp_is_root_bridge(stp);
615         stp_become_designated_port(p);
616         stp_set_port_state(p, STP_DISABLED);
617         p->topology_change_ack = false;
618         p->config_pending = false;
619         stp_stop_timer(&p->message_age_timer);
620         stp_stop_timer(&p->forward_delay_timer);
621         stp_configuration_update(stp);
622         stp_port_state_selection(stp);
623         if (stp_is_root_bridge(stp) && !root) {
624             stp_become_root_bridge(stp);
625         }
626     }
627 }
628
629 /* Enables STP on port 'p'.  The port will initially be in "blocking" state. */
630 void
631 stp_port_enable(struct stp_port *p)
632 {
633     if (p->state == STP_DISABLED) {
634         stp_initialize_port(p, STP_BLOCKING);
635         stp_port_state_selection(p->stp);
636     }
637 }
638
639 /* Sets the priority of port 'p' to 'new_priority'.  Lower numerical values
640  * are interpreted as higher priorities. */
641 void
642 stp_port_set_priority(struct stp_port *p, uint8_t new_priority)
643 {
644     uint16_t new_port_id = (p->port_id & 0xff) | (new_priority << 8);
645     if (p->port_id != new_port_id) {
646         struct stp *stp = p->stp;
647         if (stp_is_designated_port(p)) {
648             p->designated_port = new_port_id;
649         }
650         p->port_id = new_port_id;
651         if (stp->bridge_id == p->designated_bridge
652             && p->port_id < p->designated_port) {
653             stp_become_designated_port(p);
654             stp_port_state_selection(stp);
655         }
656     }
657 }
658
659 /* Sets the path cost of port 'p' to 'path_cost'.  Lower values are generally
660  * used to indicate faster links.  Use stp_port_set_speed() to automatically
661  * generate a default path cost from a link speed. */
662 void
663 stp_port_set_path_cost(struct stp_port *p, uint16_t path_cost)
664 {
665     if (p->path_cost != path_cost) {
666         struct stp *stp = p->stp;
667         p->path_cost = path_cost;
668         stp_configuration_update(stp);
669         stp_port_state_selection(stp);
670     }
671 }
672
673 /* Sets the path cost of port 'p' based on 'speed' (measured in Mb/s). */
674 void
675 stp_port_set_speed(struct stp_port *p, unsigned int speed)
676 {
677     stp_port_set_path_cost(p, (speed >= 10000 ? 2  /* 10 Gb/s. */
678                                : speed >= 1000 ? 4 /* 1 Gb/s. */
679                                : speed >= 100 ? 19 /* 100 Mb/s. */
680                                : speed >= 16 ? 62  /* 16 Mb/s. */
681                                : speed >= 10 ? 100 /* 10 Mb/s. */
682                                : speed >= 4 ? 250  /* 4 Mb/s. */
683                                : 19));             /* 100 Mb/s (guess). */
684 }
685
686 /* Enables topology change detection on port 'p'. */
687 void
688 stp_port_enable_change_detection(struct stp_port *p)
689 {
690     p->change_detection_enabled = true;
691 }
692
693 /* Disables topology change detection on port 'p'. */
694 void
695 stp_port_disable_change_detection(struct stp_port *p)
696 {
697     p->change_detection_enabled = false;
698 }
699 \f
700 static void
701 stp_transmit_config(struct stp_port *p)
702 {
703     struct stp *stp = p->stp;
704     bool root = stp_is_root_bridge(stp);
705     if (!root && !stp->root_port) {
706         return;
707     }
708     if (p->hold_timer.active) {
709         p->config_pending = true;
710     } else {
711         struct stp_config_bpdu config;
712         memset(&config, 0, sizeof config);
713         config.header.protocol_id = htons(STP_PROTOCOL_ID);
714         config.header.protocol_version = STP_PROTOCOL_VERSION;
715         config.header.bpdu_type = STP_TYPE_CONFIG;
716         config.flags = 0;
717         if (p->topology_change_ack) {
718             config.flags |= htons(STP_CONFIG_TOPOLOGY_CHANGE_ACK);
719         }
720         if (stp->topology_change) {
721             config.flags |= htons(STP_CONFIG_TOPOLOGY_CHANGE);
722         }
723         config.root_id = htonll(stp->designated_root);
724         config.root_path_cost = htonl(stp->root_path_cost);
725         config.bridge_id = htonll(stp->bridge_id);
726         config.port_id = htons(p->port_id);
727         if (root) {
728             config.message_age = htons(0);
729         } else {
730             config.message_age = htons(stp->root_port->message_age_timer.value
731                                        + MESSAGE_AGE_INCREMENT);
732         }
733         config.max_age = htons(stp->max_age);
734         config.hello_time = htons(stp->hello_time);
735         config.forward_delay = htons(stp->forward_delay);
736         if (ntohs(config.message_age) < stp->max_age) {
737             p->topology_change_ack = false;
738             p->config_pending = false;
739             stp_send_bpdu(p, &config, sizeof config);
740             stp_start_timer(&p->hold_timer, 0);
741         }
742     }
743 }
744
745 static bool
746 stp_supersedes_port_info(const struct stp_port *p,
747                          const struct stp_config_bpdu *config)
748 {
749     if (ntohll(config->root_id) != p->designated_root) {
750         return ntohll(config->root_id) < p->designated_root;
751     } else if (ntohl(config->root_path_cost) != p->designated_cost) {
752         return ntohl(config->root_path_cost) < p->designated_cost;
753     } else if (ntohll(config->bridge_id) != p->designated_bridge) {
754         return ntohll(config->bridge_id) < p->designated_bridge;
755     } else {
756         return (ntohll(config->bridge_id) != p->stp->bridge_id
757                 || ntohs(config->port_id) <= p->designated_port);
758     }
759 }
760
761 static void
762 stp_record_config_information(struct stp_port *p,
763                               const struct stp_config_bpdu *config)
764 {
765     p->designated_root = ntohll(config->root_id);
766     p->designated_cost = ntohl(config->root_path_cost);
767     p->designated_bridge = ntohll(config->bridge_id);
768     p->designated_port = ntohs(config->port_id);
769     stp_start_timer(&p->message_age_timer, ntohs(config->message_age));
770 }
771
772 static void
773 stp_record_config_timeout_values(struct stp *stp,
774                                  const struct stp_config_bpdu  *config)
775 {
776     stp->max_age = ntohs(config->max_age);
777     stp->hello_time = ntohs(config->hello_time);
778     stp->forward_delay = ntohs(config->forward_delay);
779     stp->topology_change = config->flags & htons(STP_CONFIG_TOPOLOGY_CHANGE);
780 }
781
782 static bool
783 stp_is_designated_port(const struct stp_port *p)
784 {
785     return (p->designated_bridge == p->stp->bridge_id
786             && p->designated_port == p->port_id);
787 }
788
789 static void
790 stp_config_bpdu_generation(struct stp *stp)
791 {
792     struct stp_port *p;
793
794     FOR_EACH_ENABLED_PORT (p, stp) {
795         if (stp_is_designated_port(p)) {
796             stp_transmit_config(p);
797         }
798     }
799 }
800
801 static void
802 stp_transmit_tcn(struct stp *stp)
803 {
804     struct stp_port *p = stp->root_port;
805     struct stp_tcn_bpdu tcn_bpdu;
806     if (!p) {
807         return;
808     }
809     tcn_bpdu.header.protocol_id = htons(STP_PROTOCOL_ID);
810     tcn_bpdu.header.protocol_version = STP_PROTOCOL_VERSION;
811     tcn_bpdu.header.bpdu_type = STP_TYPE_TCN;
812     stp_send_bpdu(p, &tcn_bpdu, sizeof tcn_bpdu);
813 }
814
815 static void
816 stp_configuration_update(struct stp *stp)
817 {
818     stp_root_selection(stp);
819     stp_designated_port_selection(stp);
820 }
821
822 static bool
823 stp_supersedes_root(const struct stp_port *root, const struct stp_port *p)
824 {
825     int p_cost = p->designated_cost + p->path_cost;
826     int root_cost = root->designated_cost + root->path_cost;
827
828     if (p->designated_root != root->designated_root) {
829         return p->designated_root < root->designated_root;
830     } else if (p_cost != root_cost) {
831         return p_cost < root_cost;
832     } else if (p->designated_bridge != root->designated_bridge) {
833         return p->designated_bridge < root->designated_bridge;
834     } else if (p->designated_port != root->designated_port) {
835         return p->designated_port < root->designated_port;
836     } else {
837         return p->port_id < root->port_id;
838     }
839 }
840
841 static void
842 stp_root_selection(struct stp *stp)
843 {
844     struct stp_port *p, *root;
845
846     root = NULL;
847     FOR_EACH_ENABLED_PORT (p, stp) {
848         if (stp_is_designated_port(p)
849             || p->designated_root >= stp->bridge_id) {
850             continue;
851         }
852         if (root && !stp_supersedes_root(root, p)) {
853             continue;
854         }
855         root = p;
856     }
857     stp->root_port = root;
858     if (!root) {
859         stp->designated_root = stp->bridge_id;
860         stp->root_path_cost = 0;
861     } else {
862         stp->designated_root = root->designated_root;
863         stp->root_path_cost = root->designated_cost + root->path_cost;
864     }
865 }
866
867 static void
868 stp_designated_port_selection(struct stp *stp)
869 {
870     struct stp_port *p;
871
872     FOR_EACH_ENABLED_PORT (p, stp) {
873         if (stp_is_designated_port(p)
874             || p->designated_root != stp->designated_root
875             || stp->root_path_cost < p->designated_cost
876             || (stp->root_path_cost == p->designated_cost
877                 && (stp->bridge_id < p->designated_bridge
878                     || (stp->bridge_id == p->designated_bridge
879                         && p->port_id <= p->designated_port))))
880         {
881             stp_become_designated_port(p);
882         }
883     }
884 }
885
886 static void
887 stp_become_designated_port(struct stp_port *p)
888 {
889     struct stp *stp = p->stp;
890     p->designated_root = stp->designated_root;
891     p->designated_cost = stp->root_path_cost;
892     p->designated_bridge = stp->bridge_id;
893     p->designated_port = p->port_id;
894 }
895
896 static void
897 stp_port_state_selection(struct stp *stp)
898 {
899     struct stp_port *p;
900
901     FOR_EACH_ENABLED_PORT (p, stp) {
902         if (p == stp->root_port) {
903             p->config_pending = false;
904             p->topology_change_ack = false;
905             stp_make_forwarding(p);
906         } else if (stp_is_designated_port(p)) {
907             stp_stop_timer(&p->message_age_timer);
908             stp_make_forwarding(p);
909         } else {
910             p->config_pending = false;
911             p->topology_change_ack = false;
912             stp_make_blocking(p);
913         }
914     }
915 }
916
917 static void
918 stp_make_forwarding(struct stp_port *p)
919 {
920     if (p->state == STP_BLOCKING) {
921         stp_set_port_state(p, STP_LISTENING);
922         stp_start_timer(&p->forward_delay_timer, 0);
923     }
924 }
925
926 static void
927 stp_make_blocking(struct stp_port *p)
928 {
929     if (!(p->state & (STP_DISABLED | STP_BLOCKING))) {
930         if (p->state & (STP_FORWARDING | STP_LEARNING)) {
931             if (p->change_detection_enabled) {
932                 stp_topology_change_detection(p->stp);
933             }
934         }
935         stp_set_port_state(p, STP_BLOCKING);
936         stp_stop_timer(&p->forward_delay_timer);
937     }
938 }
939
940 static void
941 stp_set_port_state(struct stp_port *p, enum stp_state state)
942 {
943     if (state != p->state && !p->state_changed) {
944         p->state_changed = true;
945         if (p < p->stp->first_changed_port) {
946             p->stp->first_changed_port = p;
947         }
948     }
949     p->state = state;
950 }
951
952 static void
953 stp_topology_change_detection(struct stp *stp)
954 {
955     if (stp_is_root_bridge(stp)) {
956         stp->topology_change = true;
957         stp_start_timer(&stp->topology_change_timer, 0);
958     } else if (!stp->topology_change_detected) {
959         stp_transmit_tcn(stp);
960         stp_start_timer(&stp->tcn_timer, 0);
961     }
962     stp->topology_change_detected = true;
963 }
964
965 static void
966 stp_topology_change_acknowledged(struct stp *stp)
967 {
968     stp->topology_change_detected = false;
969     stp_stop_timer(&stp->tcn_timer);
970 }
971
972 static void
973 stp_acknowledge_topology_change(struct stp_port *p)
974 {
975     p->topology_change_ack = true;
976     stp_transmit_config(p);
977 }
978
979 void
980 stp_received_config_bpdu(struct stp *stp, struct stp_port *p,
981                          const struct stp_config_bpdu *config)
982 {
983     if (ntohs(config->message_age) >= ntohs(config->max_age)) {
984         VLOG_WARN("%s: received config BPDU with message age (%u) greater "
985                   "than max age (%u)",
986                   stp->name,
987                   ntohs(config->message_age), ntohs(config->max_age));
988         return;
989     }
990     if (p->state != STP_DISABLED) {
991         bool root = stp_is_root_bridge(stp);
992         if (stp_supersedes_port_info(p, config)) {
993             stp_record_config_information(p, config);
994             stp_configuration_update(stp);
995             stp_port_state_selection(stp);
996             if (!stp_is_root_bridge(stp) && root) {
997                 stp_stop_timer(&stp->hello_timer);
998                 if (stp->topology_change_detected) {
999                     stp_stop_timer(&stp->topology_change_timer);
1000                     stp_transmit_tcn(stp);
1001                     stp_start_timer(&stp->tcn_timer, 0);
1002                 }
1003             }
1004             if (p == stp->root_port) {
1005                 stp_record_config_timeout_values(stp, config);
1006                 stp_config_bpdu_generation(stp);
1007                 if (config->flags & htons(STP_CONFIG_TOPOLOGY_CHANGE_ACK)) {
1008                     stp_topology_change_acknowledged(stp);
1009                 }
1010             }
1011         } else if (stp_is_designated_port(p)) {
1012             stp_transmit_config(p);
1013         }
1014     }
1015 }
1016
1017 void
1018 stp_received_tcn_bpdu(struct stp *stp, struct stp_port *p)
1019 {
1020     if (p->state != STP_DISABLED) {
1021         if (stp_is_designated_port(p)) {
1022             stp_topology_change_detection(stp);
1023             stp_acknowledge_topology_change(p);
1024         }
1025     }
1026 }
1027
1028 static void
1029 stp_hello_timer_expiry(struct stp *stp)
1030 {
1031     stp_config_bpdu_generation(stp);
1032     stp_start_timer(&stp->hello_timer, 0);
1033 }
1034
1035 static void
1036 stp_message_age_timer_expiry(struct stp_port *p)
1037 {
1038     struct stp *stp = p->stp;
1039     bool root = stp_is_root_bridge(stp);
1040     stp_become_designated_port(p);
1041     stp_configuration_update(stp);
1042     stp_port_state_selection(stp);
1043     if (stp_is_root_bridge(stp) && !root) {
1044         stp->max_age = stp->bridge_max_age;
1045         stp->hello_time = stp->bridge_hello_time;
1046         stp->forward_delay = stp->bridge_forward_delay;
1047         stp_topology_change_detection(stp);
1048         stp_stop_timer(&stp->tcn_timer);
1049         stp_config_bpdu_generation(stp);
1050         stp_start_timer(&stp->hello_timer, 0);
1051     }
1052 }
1053
1054 static bool
1055 stp_is_designated_for_some_port(const struct stp *stp)
1056 {
1057     const struct stp_port *p;
1058
1059     FOR_EACH_ENABLED_PORT (p, stp) {
1060         if (p->designated_bridge == stp->bridge_id) {
1061             return true;
1062         }
1063     }
1064     return false;
1065 }
1066
1067 static void
1068 stp_forward_delay_timer_expiry(struct stp_port *p)
1069 {
1070     if (p->state == STP_LISTENING) {
1071         stp_set_port_state(p, STP_LEARNING);
1072         stp_start_timer(&p->forward_delay_timer, 0);
1073     } else if (p->state == STP_LEARNING) {
1074         stp_set_port_state(p, STP_FORWARDING);
1075         if (stp_is_designated_for_some_port(p->stp)) {
1076             if (p->change_detection_enabled) {
1077                 stp_topology_change_detection(p->stp);
1078             }
1079         }
1080     }
1081 }
1082
1083 static void
1084 stp_tcn_timer_expiry(struct stp *stp)
1085 {
1086     stp_transmit_tcn(stp);
1087     stp_start_timer(&stp->tcn_timer, 0);
1088 }
1089
1090 static void
1091 stp_topology_change_timer_expiry(struct stp *stp)
1092 {
1093     stp->topology_change_detected = false;
1094     stp->topology_change = false;
1095 }
1096
1097 static void
1098 stp_hold_timer_expiry(struct stp_port *p)
1099 {
1100     if (p->config_pending) {
1101         stp_transmit_config(p);
1102     }
1103 }
1104
1105 static void
1106 stp_initialize_port(struct stp_port *p, enum stp_state state)
1107 {
1108     assert(state & (STP_DISABLED | STP_BLOCKING));
1109     stp_become_designated_port(p);
1110     stp_set_port_state(p, state);
1111     p->topology_change_ack = false;
1112     p->config_pending = false;
1113     p->change_detection_enabled = true;
1114     stp_stop_timer(&p->message_age_timer);
1115     stp_stop_timer(&p->forward_delay_timer);
1116     stp_stop_timer(&p->hold_timer);
1117 }
1118
1119 static void
1120 stp_become_root_bridge(struct stp *stp)
1121 {
1122     stp->max_age = stp->bridge_max_age;
1123     stp->hello_time = stp->bridge_hello_time;
1124     stp->forward_delay = stp->bridge_forward_delay;
1125     stp_topology_change_detection(stp);
1126     stp_stop_timer(&stp->tcn_timer);
1127     stp_config_bpdu_generation(stp);
1128     stp_start_timer(&stp->hello_timer, 0);
1129 }
1130
1131 static void
1132 stp_start_timer(struct stp_timer *timer, int value)
1133 {
1134     timer->value = value;
1135     timer->active = true;
1136 }
1137
1138 static void
1139 stp_stop_timer(struct stp_timer *timer)
1140 {
1141     timer->active = false;
1142 }
1143
1144 static bool
1145 stp_timer_expired(struct stp_timer *timer, int elapsed, int timeout)
1146 {
1147     if (timer->active) {
1148         timer->value += elapsed;
1149         if (timer->value >= timeout) {
1150             timer->active = false;
1151             return true;
1152         }
1153     }
1154     return false;
1155 }
1156
1157 /* Returns the number of whole STP timer ticks in 'ms' milliseconds.  There
1158  * are 256 STP timer ticks per second. */
1159 static int
1160 ms_to_timer(int ms)
1161 {
1162     return ms * 0x100 / 1000;
1163 }
1164
1165 /* Returns the number of leftover milliseconds when 'ms' is converted to STP
1166  * timer ticks. */
1167 static int
1168 ms_to_timer_remainder(int ms)
1169 {
1170     return ms * 0x100 % 1000;
1171 }
1172
1173 /* Returns the number of whole milliseconds in 'timer' STP timer ticks.  There
1174  * are 256 STP timer ticks per second. */
1175 static int
1176 timer_to_ms(int timer)
1177 {
1178     return timer * 1000 / 0x100;
1179 }
1180
1181 static int
1182 clamp(int x, int min, int max)
1183 {
1184     return x < min ? min : x > max ? max : x;
1185 }
1186
1187 static void
1188 stp_update_bridge_timers(struct stp *stp)
1189 {
1190     int ht, ma, fd;
1191
1192     ht = clamp(stp->rq_hello_time, 1000, 10000);
1193     ma = clamp(stp->rq_max_age, MAX(2 * (ht + 1000), 6000), 40000);
1194     fd = clamp(stp->rq_forward_delay, ma / 2 + 1000, 30000);
1195
1196     stp->bridge_hello_time = ms_to_timer(ht);
1197     stp->bridge_max_age = ms_to_timer(ma);
1198     stp->bridge_forward_delay = ms_to_timer(fd);
1199
1200     if (stp_is_root_bridge(stp)) {
1201         stp->max_age = stp->bridge_max_age;
1202         stp->hello_time = stp->bridge_hello_time;
1203         stp->forward_delay = stp->bridge_forward_delay;
1204     }
1205 }
1206
1207 static void
1208 stp_send_bpdu(struct stp_port *p, const void *bpdu, size_t bpdu_size)
1209 {
1210     struct eth_header *eth;
1211     struct llc_header *llc;
1212     struct ofpbuf *pkt;
1213
1214     /* Skeleton. */
1215     pkt = ofpbuf_new(ETH_HEADER_LEN + LLC_HEADER_LEN + bpdu_size);
1216     pkt->l2 = eth = ofpbuf_put_zeros(pkt, sizeof *eth);
1217     llc = ofpbuf_put_zeros(pkt, sizeof *llc);
1218     pkt->l3 = ofpbuf_put(pkt, bpdu, bpdu_size);
1219
1220     /* 802.2 header. */
1221     memcpy(eth->eth_dst, stp_eth_addr, ETH_ADDR_LEN);
1222     /* p->stp->send_bpdu() must fill in source address. */
1223     eth->eth_type = htons(pkt->size - ETH_HEADER_LEN);
1224
1225     /* LLC header. */
1226     llc->llc_dsap = STP_LLC_DSAP;
1227     llc->llc_ssap = STP_LLC_SSAP;
1228     llc->llc_cntl = STP_LLC_CNTL;
1229
1230     p->stp->send_bpdu(pkt, stp_port_no(p), p->stp->aux);
1231 }