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