summaryrefslogtreecommitdiffstats
path: root/bgpd/bgp_fsm.c
blob: 1fc425f8f5b3fe567d7d8a5770af41a262a74efc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
/* BGP-4 Finite State Machine   
 * From RFC1771 [A Border Gateway Protocol 4 (BGP-4)]
 * Copyright (C) 1996, 97, 98 Kunihiro Ishiguro
 *
 * This file is part of GNU Zebra.
 *
 * GNU Zebra is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * GNU Zebra is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; see the file COPYING; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <zebra.h>

#include "linklist.h"
#include "prefix.h"
#include "sockunion.h"
#include "thread.h"
#include "log.h"
#include "stream.h"
#include "memory.h"
#include "plist.h"
#include "workqueue.h"
#include "queue.h"
#include "filter.h"
#include "command.h"

#include "lib/json.h"
#include "bgpd/bgpd.h"
#include "bgpd/bgp_attr.h"
#include "bgpd/bgp_debug.h"
#include "bgpd/bgp_fsm.h"
#include "bgpd/bgp_packet.h"
#include "bgpd/bgp_network.h"
#include "bgpd/bgp_route.h"
#include "bgpd/bgp_dump.h"
#include "bgpd/bgp_open.h"
#include "bgpd/bgp_advertise.h"
#include "bgpd/bgp_updgrp.h"
#include "bgpd/bgp_nht.h"
#include "bgpd/bgp_bfd.h"
#include "bgpd/bgp_memory.h"

DEFINE_HOOK(peer_backward_transition, (struct peer *peer), (peer))
DEFINE_HOOK(peer_established, (struct peer *peer), (peer))

/* Definition of display strings corresponding to FSM events. This should be
 * kept consistent with the events defined in bgpd.h
 */
static const char *bgp_event_str[] =
{
  NULL,
  "BGP_Start",
  "BGP_Stop",
  "TCP_connection_open",
  "TCP_connection_closed",
  "TCP_connection_open_failed",
  "TCP_fatal_error",
  "ConnectRetry_timer_expired",
  "Hold_Timer_expired",
  "KeepAlive_timer_expired",
  "Receive_OPEN_message",
  "Receive_KEEPALIVE_message",
  "Receive_UPDATE_message",
  "Receive_NOTIFICATION_message",
  "Clearing_Completed",
};

/* BGP FSM (finite state machine) has three types of functions.  Type
   one is thread functions.  Type two is event functions.  Type three
   is FSM functions.  Timer functions are set by bgp_timer_set
   function. */

/* BGP event function. */
int bgp_event (struct thread *);

/* BGP thread functions. */
static int bgp_start_timer (struct thread *);
static int bgp_connect_timer (struct thread *);
static int bgp_holdtime_timer (struct thread *);
static int bgp_keepalive_timer (struct thread *);

/* BGP FSM functions. */
static int bgp_start (struct peer *);

static void
peer_xfer_stats (struct peer *peer_dst, struct peer *peer_src)
{
  /* Copy stats over. These are only the pre-established state stats */
  peer_dst->open_in += peer_src->open_in;
  peer_dst->open_out += peer_src->open_out;
  peer_dst->keepalive_in += peer_src->keepalive_in;
  peer_dst->keepalive_out += peer_src->keepalive_out;
  peer_dst->notify_in += peer_src->notify_in;
  peer_dst->notify_out += peer_src->notify_out;
  peer_dst->dynamic_cap_in += peer_src->dynamic_cap_in;
  peer_dst->dynamic_cap_out += peer_src->dynamic_cap_out;
}

static struct peer *
peer_xfer_conn(struct peer *from_peer)
{
  struct peer *peer;
  afi_t afi;
  safi_t safi;
  int fd;
  int status, pstatus;
  unsigned char last_evt, last_maj_evt;

  assert(from_peer != NULL);

  peer = from_peer->doppelganger;

  if (!peer || !CHECK_FLAG(peer->flags, PEER_FLAG_CONFIG_NODE))
    return from_peer;

  if (bgp_debug_neighbor_events(peer))
    zlog_debug ("%s: peer transfer %p fd %d -> %p fd %d)", from_peer->host,
                from_peer, from_peer->fd, peer, peer->fd);

  BGP_WRITE_OFF(peer->t_write);
  BGP_READ_OFF(peer->t_read);
  BGP_WRITE_OFF(from_peer->t_write);
  BGP_READ_OFF(from_peer->t_read);

  BGP_TIMER_OFF(peer->t_routeadv);
  BGP_TIMER_OFF(from_peer->t_routeadv);

  fd = peer->fd;
  peer->fd = from_peer->fd;
  from_peer->fd = fd;
  stream_reset(peer->ibuf);
  stream_fifo_clean(peer->obuf);
  stream_fifo_clean(from_peer->obuf);

  peer->as = from_peer->as;
  peer->v_holdtime = from_peer->v_holdtime;
  peer->v_keepalive = from_peer->v_keepalive;
  peer->routeadv = from_peer->routeadv;
  peer->v_routeadv = from_peer->v_routeadv;
  peer->v_gr_restart = from_peer->v_gr_restart;
  peer->cap = from_peer->cap;
  status = peer->status;
  pstatus = peer->ostatus;
  last_evt = peer->last_event;
  last_maj_evt = peer->last_major_event;
  peer->status = from_peer->status;
  peer->ostatus = from_peer->ostatus;
  peer->last_event = from_peer->last_event;
  peer->last_major_event = from_peer->last_major_event;
  from_peer->status = status;
  from_peer->ostatus = pstatus;
  from_peer->last_event = last_evt;
  from_peer->last_major_event = last_maj_evt;
  peer->remote_id = from_peer->remote_id;

  if (from_peer->hostname != NULL)
    {
      if (peer->hostname)
        {
          XFREE(MTYPE_BGP_PEER_HOST, peer->hostname);
          peer->hostname = NULL;
        }

      peer->hostname = from_peer->hostname;
      from_peer->hostname = NULL;
    }

  if (from_peer->domainname != NULL)
    {
      if (peer->domainname)
        {
          XFREE(MTYPE_BGP_PEER_HOST, peer->domainname);
          peer->domainname= NULL;
        }

      peer->domainname = from_peer->domainname;
      from_peer->domainname = NULL;
    }

  for (afi = AFI_IP; afi < AFI_MAX; afi++)
    for (safi = SAFI_UNICAST; safi < SAFI_MAX; safi++)
      {
	peer->af_flags[afi][safi] = from_peer->af_flags[afi][safi];
	peer->af_sflags[afi][safi] = from_peer->af_sflags[afi][safi];
	peer->af_cap[afi][safi] = from_peer->af_cap[afi][safi];
	peer->afc_nego[afi][safi] = from_peer->afc_nego[afi][safi];
	peer->afc_adv[afi][safi] = from_peer->afc_adv[afi][safi];
	peer->afc_recv[afi][safi] = from_peer->afc_recv[afi][safi];
	peer->orf_plist[afi][safi] = from_peer->orf_plist[afi][safi];
      }

  if (bgp_getsockname(peer) < 0)
    {
      zlog_err ("%%bgp_getsockname() failed for %s peer %s fd %d (from_peer fd %d)",
                (CHECK_FLAG (peer->sflags, PEER_STATUS_ACCEPT_PEER) ? "accept" : ""),
                peer->host, peer->fd, from_peer->fd);
      bgp_stop(peer);
      bgp_stop(from_peer);
      return NULL;
    }
  if (from_peer->status > Active)
    {
      if (bgp_getsockname(from_peer) < 0)
        {
          zlog_err ("%%bgp_getsockname() failed for %s from_peer %s fd %d (peer fd %d)",
             (CHECK_FLAG (from_peer->sflags, PEER_STATUS_ACCEPT_PEER) ? "accept" : ""),
             from_peer->host, from_peer->fd, peer->fd);
          bgp_stop(from_peer);
          from_peer = NULL;
        }
    }

  BGP_READ_ON(peer->t_read, bgp_read, peer->fd);
  BGP_WRITE_ON(peer->t_write, bgp_write, peer->fd);

  if (from_peer)
    peer_xfer_stats(peer, from_peer);

  return(peer);
}

/* Hook function called after bgp event is occered.  And vty's
   neighbor command invoke this function after making neighbor
   structure. */
void
bgp_timer_set (struct peer *peer)
{
  switch (peer->status)
    {
    case Idle:
      /* First entry point of peer's finite state machine.  In Idle
	 status start timer is on unless peer is shutdown or peer is
	 inactive.  All other timer must be turned off */
      if (BGP_PEER_START_SUPPRESSED (peer) || ! peer_active (peer))
	{
	  BGP_TIMER_OFF (peer->t_start);
	}
      else
	{
	  BGP_TIMER_ON (peer->t_start, bgp_start_timer,
			peer->v_start);
	}
      BGP_TIMER_OFF (peer->t_connect);
      BGP_TIMER_OFF (peer->t_holdtime);
      BGP_TIMER_OFF (peer->t_keepalive);
      BGP_TIMER_OFF (peer->t_routeadv);
      break;

    case Connect:
      /* After start timer is expired, the peer moves to Connect
         status.  Make sure start timer is off and connect timer is
         on. */
      BGP_TIMER_OFF (peer->t_start);
      BGP_TIMER_ON (peer->t_connect, bgp_connect_timer, peer->v_connect);
      BGP_TIMER_OFF (peer->t_holdtime);
      BGP_TIMER_OFF (peer->t_keepalive);
      BGP_TIMER_OFF (peer->t_routeadv);
      break;

    case Active:
      /* Active is waiting connection from remote peer.  And if
         connect timer is expired, change status to Connect. */
      BGP_TIMER_OFF (peer->t_start);
      /* If peer is passive mode, do not set connect timer. */
      if (CHECK_FLAG (peer->flags, PEER_FLAG_PASSIVE)
	  || CHECK_FLAG (peer->sflags, PEER_STATUS_NSF_WAIT))
	{
	  BGP_TIMER_OFF (peer->t_connect);
	}
      else
	{
	  BGP_TIMER_ON (peer->t_connect, bgp_connect_timer, peer->v_connect);
	}
      BGP_TIMER_OFF (peer->t_holdtime);
      BGP_TIMER_OFF (peer->t_keepalive);
      BGP_TIMER_OFF (peer->t_routeadv);
      break;

    case OpenSent:
      /* OpenSent status. */
      BGP_TIMER_OFF (peer->t_start);
      BGP_TIMER_OFF (peer->t_connect);
      if (peer->v_holdtime != 0)
	{
	  BGP_TIMER_ON (peer->t_holdtime, bgp_holdtime_timer, 
			peer->v_holdtime);
	}
      else
	{
	  BGP_TIMER_OFF (peer->t_holdtime);
	}
      BGP_TIMER_OFF (peer->t_keepalive);
      BGP_TIMER_OFF (peer->t_routeadv);
      break;

    case OpenConfirm:
      /* OpenConfirm status. */
      BGP_TIMER_OFF (peer->t_start);
      BGP_TIMER_OFF (peer->t_connect);

      /* If the negotiated Hold Time value is zero, then the Hold Time
         timer and KeepAlive timers are not started. */
      if (peer->v_holdtime == 0)
	{
	  BGP_TIMER_OFF (peer->t_holdtime);
	  BGP_TIMER_OFF (peer->t_keepalive);
	}
      else
	{
	  BGP_TIMER_ON (peer->t_holdtime, bgp_holdtime_timer,
			peer->v_holdtime);
	  BGP_TIMER_ON (peer->t_keepalive, bgp_keepalive_timer, 
			peer->v_keepalive);
	}
      BGP_TIMER_OFF (peer->t_routeadv);
      break;

    case Established:
      /* In Established status start and connect timer is turned
         off. */
      BGP_TIMER_OFF (peer->t_start);
      BGP_TIMER_OFF (peer->t_connect);

      /* Same as OpenConfirm, if holdtime is zero then both holdtime
         and keepalive must be turned off. */
      if (peer->v_holdtime == 0)
	{
	  BGP_TIMER_OFF (peer->t_holdtime);
	  BGP_TIMER_OFF (peer->t_keepalive);
	}
      else
	{
	  BGP_TIMER_ON (peer->t_holdtime, bgp_holdtime_timer,
			peer->v_holdtime);
	  BGP_TIMER_ON (peer->t_keepalive, bgp_keepalive_timer,
			peer->v_keepalive);
	}
      break;
    case Deleted:
      BGP_TIMER_OFF (peer->t_gr_restart);
      BGP_TIMER_OFF (peer->t_gr_stale);
      BGP_TIMER_OFF (peer->t_pmax_restart);
    case Clearing:
      BGP_TIMER_OFF (peer->t_start);
      BGP_TIMER_OFF (peer->t_connect);
      BGP_TIMER_OFF (peer->t_holdtime);
      BGP_TIMER_OFF (peer->t_keepalive);
      BGP_TIMER_OFF (peer->t_routeadv);
      break;
    }
}

/* BGP start timer.  This function set BGP_Start event to thread value
   and process event. */
static int
bgp_start_timer (struct thread *thread)
{
  struct peer *peer;

  peer = THREAD_ARG (thread);
  peer->t_start = NULL;

  if (bgp_debug_neighbor_events(peer))
    zlog_debug("%s [FSM] Timer (start timer expire).", peer->host);

  THREAD_VAL (thread) = BGP_Start;
  bgp_event (thread);  /* bgp_event unlocks peer */

  return 0;
}

/* BGP connect retry timer. */
static int
bgp_connect_timer (struct thread *thread)
{
  struct peer *peer;
  int ret;

  peer = THREAD_ARG (thread);
  peer->t_connect = NULL;

  if (bgp_debug_neighbor_events(peer))
    zlog_debug("%s [FSM] Timer (connect timer expire)", peer->host);

  if (CHECK_FLAG(peer->sflags, PEER_STATUS_ACCEPT_PEER))
    {
      bgp_stop(peer);
      ret = -1;
    }
  else
    {
      THREAD_VAL (thread) = ConnectRetry_timer_expired;
      bgp_event (thread); /* bgp_event unlocks peer */
      ret = 0;
    }

  return ret;
}

/* BGP holdtime timer. */
static int
bgp_holdtime_timer (struct thread *thread)
{
  struct peer *peer;

  peer = THREAD_ARG (thread);
  peer->t_holdtime = NULL;

  if (bgp_debug_neighbor_events(peer))
    zlog_debug ("%s [FSM] Timer (holdtime timer expire)", peer->host);

  THREAD_VAL (thread) = Hold_Timer_expired;
  bgp_event (thread); /* bgp_event unlocks peer */

  return 0;
}

/* BGP keepalive fire ! */
static int
bgp_keepalive_timer (struct thread *thread)
{
  struct peer *peer;

  peer = THREAD_ARG (thread);
  peer->t_keepalive = NULL;

  if (bgp_debug_neighbor_events(peer))
    zlog_debug ("%s [FSM] Timer (keepalive timer expire)", peer->host);

  THREAD_VAL (thread) = KeepAlive_timer_expired;
  bgp_event (thread); /* bgp_event unlocks peer */

  return 0;
}

int
bgp_routeadv_timer (struct thread *thread)
{
  struct peer *peer;

  peer = THREAD_ARG (thread);
  peer->t_routeadv = NULL;

  if (bgp_debug_neighbor_events(peer))
    zlog_debug ("%s [FSM] Timer (routeadv timer expire)", peer->host);

  peer->synctime = bgp_clock ();

  BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);

  /* MRAI timer will be started again when FIFO is built, no need to
   * do it here.
   */
  return 0;
}

/* BGP Peer Down Cause */
const char *peer_down_str[] =
{
  "",
  "Router ID changed",
  "Remote AS changed",
  "Local AS change",
  "Cluster ID changed",
  "Confederation identifier changed",
  "Confederation peer changed",
  "RR client config change",
  "RS client config change",
  "Update source change",
  "Address family activated",
  "Admin. shutdown",
  "User reset",
  "BGP Notification received",
  "BGP Notification send",
  "Peer closed the session",
  "Neighbor deleted",
  "Peer-group add member",
  "Peer-group delete member",
  "Capability changed",
  "Passive config change",
  "Multihop config change",
  "NSF peer closed the session",
  "Intf peering v6only config change",
  "BFD down received",
  "Interface down",
  "Neighbor address lost"
};

static int
bgp_graceful_restart_timer_expire (struct thread *thread)
{
  struct peer *peer;
  afi_t afi;
  safi_t safi;

  peer = THREAD_ARG (thread);
  peer->t_gr_restart = NULL;

  /* NSF delete stale route */
  for (afi = AFI_IP ; afi < AFI_MAX ; afi++)
    for (safi = SAFI_UNICAST ; safi < SAFI_RESERVED_4 ; safi++)
      if (peer->nsf[afi][safi])
	bgp_clear_stale_route (peer, afi, safi);

  UNSET_FLAG (peer->sflags, PEER_STATUS_NSF_WAIT);
  BGP_TIMER_OFF (peer->t_gr_stale);

  if (bgp_debug_neighbor_events(peer))
    {
      zlog_debug ("%s graceful restart timer expired", peer->host);
      zlog_debug ("%s graceful restart stalepath timer stopped", peer->host);
    }

  bgp_timer_set (peer);

  return 0;
}

static int
bgp_graceful_stale_timer_expire (struct thread *thread)
{
  struct peer *peer;
  afi_t afi;
  safi_t safi;

  peer = THREAD_ARG (thread);
  peer->t_gr_stale = NULL;

  if (bgp_debug_neighbor_events(peer))
    zlog_debug ("%s graceful restart stalepath timer expired", peer->host);

  /* NSF delete stale route */
  for (afi = AFI_IP ; afi < AFI_MAX ; afi++)
    for (safi = SAFI_UNICAST ; safi < SAFI_RESERVED_4 ; safi++)
      if (peer->nsf[afi][safi])
	bgp_clear_stale_route (peer, afi, safi);

  return 0;
}

static int
bgp_update_delay_applicable (struct bgp *bgp)
{
  /* update_delay_over flag should be reset (set to 0) for any new
     applicability of the update-delay during BGP process lifetime.
     And it should be set after an occurence of the update-delay is over)*/
  if (!bgp->update_delay_over)
    return 1;

  return 0;
}

int
bgp_update_delay_active (struct bgp *bgp)
{
  if (bgp->t_update_delay)
    return 1;

  return 0;
}

int
bgp_update_delay_configured (struct bgp *bgp)
{
  if (bgp->v_update_delay)
    return 1;

  return 0;
}

/* Do the post-processing needed when bgp comes out of the read-only mode
   on ending the update delay. */
void
bgp_update_delay_end (struct bgp *bgp)
{
  THREAD_TIMER_OFF (bgp->t_update_delay);
  THREAD_TIMER_OFF (bgp->t_establish_wait);

  /* Reset update-delay related state */
  bgp->update_delay_over = 1;
  bgp->established = 0;
  bgp->restarted_peers = 0;
  bgp->implicit_eors = 0;
  bgp->explicit_eors = 0;

  quagga_timestamp(3, bgp->update_delay_end_time,
                   sizeof(bgp->update_delay_end_time));

  /*
   * Add an end-of-initial-update marker to the main process queues so that
   * the route advertisement timer for the peers can be started. Also set
   * the zebra and peer update hold flags. These flags are used to achieve
   * three stages in the update-delay post processing:
   *  1. Finish best-path selection for all the prefixes held on the queues.
   *     (routes in BGP are updated, and peers sync queues are populated too)
   *  2. As the eoiu mark is reached in the bgp process routine, ship all the
   *     routes to zebra. With that zebra should see updates from BGP close
   *     to each other.
   *  3. Unblock the peer update writes. With that peer update packing with
   *     the prefixes should be at its maximum.
   */
  bgp_add_eoiu_mark(bgp);
  bgp->main_zebra_update_hold = 1;
  bgp->main_peers_update_hold = 1;

  /* Resume the queue processing. This should trigger the event that would take
     care of processing any work that was queued during the read-only mode. */
  work_queue_unplug(bm->process_main_queue);
}

/**
 * see bgp_fsm.h
 */
void
bgp_start_routeadv (struct bgp *bgp)
{
  struct listnode *node, *nnode;
  struct peer *peer;

  zlog_info("bgp_start_routeadv(), update hold status %d",
             bgp->main_peers_update_hold);

  if (bgp->main_peers_update_hold)
    return;

  quagga_timestamp(3, bgp->update_delay_peers_resume_time,
                   sizeof(bgp->update_delay_peers_resume_time));

  for (ALL_LIST_ELEMENTS (bgp->peer, node, nnode, peer))
    {
      if (peer->status != Established)
	continue;
      BGP_TIMER_OFF(peer->t_routeadv);
      BGP_TIMER_ON(peer->t_routeadv, bgp_routeadv_timer, 0);
    }
}

/**
 * see bgp_fsm.h
 */
void
bgp_adjust_routeadv (struct peer *peer)
{
  time_t nowtime = bgp_clock();
  double diff;
  unsigned long remain;

  /* Bypass checks for special case of MRAI being 0 */
  if (peer->v_routeadv == 0)
    {
      /* Stop existing timer, just in case it is running for a different
       * duration and schedule write thread immediately.
       */
      if (peer->t_routeadv)
        BGP_TIMER_OFF(peer->t_routeadv);

      peer->synctime = bgp_clock ();
      BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
      return;
    }


  /*
   * CASE I:
   * If the last update was written more than MRAI back, expire the timer
   * instantly so that we can send the update out sooner.
   *
   *                           <-------  MRAI --------->
   *         |-----------------|-----------------------|
   *         <------------- m ------------>
   *         ^                 ^          ^
   *         |                 |          |
   *         |                 |     current time
   *         |            timer start
   *      last write
   *
   *                     m > MRAI
   */
  diff = difftime(nowtime, peer->last_update);
  if (diff > (double) peer->v_routeadv)
    {
      BGP_TIMER_OFF(peer->t_routeadv);
      BGP_TIMER_ON(peer->t_routeadv, bgp_routeadv_timer, 0);
      return;
    }

  /*
   * CASE II:
   * - Find when to expire the MRAI timer.
   *   If MRAI timer is not active, assume we can start it now.
   *
   *                      <-------  MRAI --------->
   *         |------------|-----------------------|
   *         <-------- m ----------><----- r ----->
   *         ^            ^        ^
   *         |            |        |
   *         |            |   current time
   *         |       timer start
   *      last write
   *
   *                     (MRAI - m) < r
   */
  if (peer->t_routeadv)
    remain = thread_timer_remain_second(peer->t_routeadv);
  else
    remain = peer->v_routeadv;
  diff = peer->v_routeadv - diff;
  if (diff <= (double) remain)
    {
      BGP_TIMER_OFF(peer->t_routeadv);
      BGP_TIMER_ON(peer->t_routeadv, bgp_routeadv_timer, diff);
    }
}

static int
bgp_maxmed_onstartup_applicable (struct bgp *bgp)
{
  if (!bgp->maxmed_onstartup_over)
    return 1;

  return 0;
}

int
bgp_maxmed_onstartup_configured (struct bgp *bgp)
{
  if (bgp->v_maxmed_onstartup != BGP_MAXMED_ONSTARTUP_UNCONFIGURED)
    return 1;

  return 0;
}

int
bgp_maxmed_onstartup_active (struct bgp *bgp)
{
  if (bgp->t_maxmed_onstartup)
    return 1;

  return 0;
}

void
bgp_maxmed_update (struct bgp *bgp)
{
  u_char     maxmed_active;
  u_int32_t  maxmed_value;

  if (bgp->v_maxmed_admin)
    {
      maxmed_active = 1;
      maxmed_value = bgp->maxmed_admin_value;
    }
  else if (bgp->t_maxmed_onstartup)
    {
      maxmed_active = 1;
      maxmed_value = bgp->maxmed_onstartup_value;
    }
  else
    {
      maxmed_active = 0;
      maxmed_value = BGP_MAXMED_VALUE_DEFAULT;
    }

  if (bgp->maxmed_active != maxmed_active ||
      bgp->maxmed_value != maxmed_value)
    {
      bgp->maxmed_active = maxmed_active;
      bgp->maxmed_value = maxmed_value;

      update_group_announce(bgp);
    }
}

/* The maxmed onstartup timer expiry callback. */
static int
bgp_maxmed_onstartup_timer (struct thread *thread)
{
  struct bgp *bgp;

  zlog_info ("Max med on startup ended - timer expired.");

  bgp = THREAD_ARG (thread);
  THREAD_TIMER_OFF (bgp->t_maxmed_onstartup);
  bgp->maxmed_onstartup_over = 1;

  bgp_maxmed_update(bgp);

  return 0;
}

static void
bgp_maxmed_onstartup_begin (struct bgp *bgp)
{
  /* Applicable only once in the process lifetime on the startup */
  if (bgp->maxmed_onstartup_over)
    return;

  zlog_info ("Begin maxmed onstartup mode - timer %d seconds",
             bgp->v_maxmed_onstartup);

  thread_add_timer(bm->master, bgp_maxmed_onstartup_timer, bgp,
                   bgp->v_maxmed_onstartup, &bgp->t_maxmed_onstartup);

  if (!bgp->v_maxmed_admin)
    {
      bgp->maxmed_active = 1;
      bgp->maxmed_value = bgp->maxmed_onstartup_value;
    }

  /* Route announce to all peers should happen after this in bgp_establish() */
}

static void
bgp_maxmed_onstartup_process_status_change(struct peer *peer)
{
  if (peer->status == Established && !peer->bgp->established)
    {
      bgp_maxmed_onstartup_begin(peer->bgp);
    }
}

/* The update delay timer expiry callback. */
static int
bgp_update_delay_timer (struct thread *thread)
{
  struct bgp *bgp;

  zlog_info ("Update delay ended - timer expired.");

  bgp = THREAD_ARG (thread);
  THREAD_TIMER_OFF (bgp->t_update_delay);
  bgp_update_delay_end(bgp);

  return 0;
}

/* The establish wait timer expiry callback. */
static int
bgp_establish_wait_timer (struct thread *thread)
{
  struct bgp *bgp;

  zlog_info ("Establish wait - timer expired.");

  bgp = THREAD_ARG (thread);
  THREAD_TIMER_OFF (bgp->t_establish_wait);
  bgp_check_update_delay(bgp);

  return 0;
}

/* Steps to begin the update delay:
     - initialize queues if needed
     - stop the queue processing
     - start the timer */
static void
bgp_update_delay_begin (struct bgp *bgp)
{
  struct listnode *node, *nnode;
  struct peer *peer;

  /* Stop the processing of queued work. Enqueue shall continue */
  work_queue_plug(bm->process_main_queue);

  for (ALL_LIST_ELEMENTS (bgp->peer, node, nnode, peer))
    peer->update_delay_over = 0;

  /* Start the update-delay timer */
  thread_add_timer(bm->master, bgp_update_delay_timer, bgp,
                   bgp->v_update_delay, &bgp->t_update_delay);

  if (bgp->v_establish_wait != bgp->v_update_delay)
    thread_add_timer(bm->master, bgp_establish_wait_timer, bgp,
                     bgp->v_establish_wait, &bgp->t_establish_wait);

  quagga_timestamp(3, bgp->update_delay_begin_time,
                   sizeof(bgp->update_delay_begin_time));
}

static void
bgp_update_delay_process_status_change(struct peer *peer)
{
  if (peer->status == Established)
    {
      if (!peer->bgp->established++)
        {
          bgp_update_delay_begin(peer->bgp);
          zlog_info ("Begin read-only mode - update-delay timer %d seconds",
                     peer->bgp->v_update_delay);
        }
      if (CHECK_FLAG (peer->cap, PEER_CAP_RESTART_BIT_RCV))
        bgp_update_restarted_peers(peer);
    }
  if (peer->ostatus == Established && bgp_update_delay_active(peer->bgp))
    {
      /* Adjust the update-delay state to account for this flap.
         NOTE: Intentionally skipping adjusting implicit_eors or explicit_eors
         counters. Extra sanity check in bgp_check_update_delay() should
         be enough to take care of any additive discrepancy in bgp eor
         counters */
      peer->bgp->established--;
      peer->update_delay_over = 0;
    }
}

/* Called after event occured, this function change status and reset
   read/write and timer thread. */
void
bgp_fsm_change_status (struct peer *peer, int status)
{

  bgp_dump_state (peer, peer->status, status);

  /* Transition into Clearing or Deleted must /always/ clear all routes.. 
   * (and must do so before actually changing into Deleted..
   */
  if (status >= Clearing)
    {
      bgp_clear_route_all (peer);

      /* If no route was queued for the clear-node processing, generate the
       * completion event here. This is needed because if there are no routes
       * to trigger the background clear-node thread, the event won't get
       * generated and the peer would be stuck in Clearing. Note that this
       * event is for the peer and helps the peer transition out of Clearing
       * state; it should not be generated per (AFI,SAFI). The event is
       * directly posted here without calling clear_node_complete() as we
       * shouldn't do an extra unlock. This event will get processed after
       * the state change that happens below, so peer will be in Clearing
       * (or Deleted).
       */
      if (!work_queue_is_scheduled (peer->clear_node_queue))
        BGP_EVENT_ADD (peer, Clearing_Completed);
    }
  
  /* Preserve old status and change into new status. */
  peer->ostatus = peer->status;
  peer->status = status;

  /* Save event that caused status change. */
  peer->last_major_event = peer->cur_event;

  if (status == Established)
    UNSET_FLAG(peer->sflags, PEER_STATUS_ACCEPT_PEER);

  /* If max-med processing is applicable, do the necessary. */
  if (status == Established)
    {
      if (bgp_maxmed_onstartup_configured(peer->bgp) &&
          bgp_maxmed_onstartup_applicable(peer->bgp))
        bgp_maxmed_onstartup_process_status_change(peer);
      else
        peer->bgp->maxmed_onstartup_over = 1;
    }

  /* If update-delay processing is applicable, do the necessary. */
  if (bgp_update_delay_configured(peer->bgp) &&
      bgp_update_delay_applicable(peer->bgp))
    bgp_update_delay_process_status_change(peer);

  if (bgp_debug_neighbor_events(peer))
    zlog_debug ("%s went from %s to %s",
		peer->host,
		lookup_msg(bgp_status_msg, peer->ostatus, NULL),
		lookup_msg(bgp_status_msg, peer->status, NULL));
}

/* Flush the event queue and ensure the peer is shut down */
static int
bgp_clearing_completed (struct peer *peer)
{
  int rc = bgp_stop(peer);

  if (rc >= 0)
    BGP_EVENT_FLUSH (peer);

  return rc;
}

/* Administrative BGP peer stop event. */
/* May be called multiple times for the same peer */
int
bgp_stop (struct peer *peer)
{
  afi_t afi;
  safi_t safi;
  char orf_name[BUFSIZ];
  int ret = 0;

  if (peer_dynamic_neighbor(peer) &&
      !(CHECK_FLAG(peer->flags, PEER_FLAG_DELETE)))
    {
      if (bgp_debug_neighbor_events(peer))
        zlog_debug ("%s (dynamic neighbor) deleted", peer->host);
      peer_delete (peer);
      return -1;
    }

  /* Can't do this in Clearing; events are used for state transitions */
  if (peer->status != Clearing)
    {
      /* Delete all existing events of the peer */
      BGP_EVENT_FLUSH (peer);
    }

  /* Increment Dropped count. */
  if (peer->status == Established)
    {
      peer->dropped++;

      /* bgp log-neighbor-changes of neighbor Down */
      if (bgp_flag_check (peer->bgp, BGP_FLAG_LOG_NEIGHBOR_CHANGES))
	{
	  struct vrf *vrf = vrf_lookup_by_id (peer->bgp->vrf_id);
	  zlog_info ("%%ADJCHANGE: neighbor %s(%s) in vrf %s Down %s",
		     peer->host,
		     (peer->hostname) ? peer->hostname : "Unknown",
		     vrf ? ((vrf->vrf_id != VRF_DEFAULT) ? vrf->name : "Default") : "",
		     peer_down_str [(int) peer->last_reset]);
	}

      /* graceful restart */
      if (peer->t_gr_stale)
	{
	  BGP_TIMER_OFF (peer->t_gr_stale);
          if (bgp_debug_neighbor_events(peer))
	    zlog_debug ("%s graceful restart stalepath timer stopped", peer->host);
	}
      if (CHECK_FLAG (peer->sflags, PEER_STATUS_NSF_WAIT))
	{
          if (bgp_debug_neighbor_events(peer))
	    {
	      zlog_debug ("%s graceful restart timer started for %d sec",
			  peer->host, peer->v_gr_restart);
	      zlog_debug ("%s graceful restart stalepath timer started for %d sec",
			  peer->host, peer->bgp->stalepath_time);
	    }
	  BGP_TIMER_ON (peer->t_gr_restart, bgp_graceful_restart_timer_expire,
			peer->v_gr_restart);
	  BGP_TIMER_ON (peer->t_gr_stale, bgp_graceful_stale_timer_expire,
			peer->bgp->stalepath_time);
	}
      else
	{
	  UNSET_FLAG (peer->sflags, PEER_STATUS_NSF_MODE);

	  for (afi = AFI_IP ; afi < AFI_MAX ; afi++)
	    for (safi = SAFI_UNICAST ; safi < SAFI_RESERVED_4 ; safi++)
	      peer->nsf[afi][safi] = 0;
	}

      /* set last reset time */
      peer->resettime = peer->uptime = bgp_clock ();

      if (BGP_DEBUG (update_groups, UPDATE_GROUPS))
	zlog_debug ("%s remove from all update group", peer->host);
      update_group_remove_peer_afs(peer);

      hook_call(peer_backward_transition, peer);

      /* Reset peer synctime */
      peer->synctime = 0;

      bgp_bfd_deregister_peer(peer);
    }

  /* Stop read and write threads when exists. */
  BGP_READ_OFF (peer->t_read);
  BGP_WRITE_OFF (peer->t_write);

  /* Stop all timers. */
  BGP_TIMER_OFF (peer->t_start);
  BGP_TIMER_OFF (peer->t_connect);
  BGP_TIMER_OFF (peer->t_holdtime);
  BGP_TIMER_OFF (peer->t_keepalive);
  BGP_TIMER_OFF (peer->t_routeadv);

  /* Stream reset. */
  peer->packet_size = 0;

  /* Clear input and output buffer.  */
  if (peer->ibuf)
    stream_reset (peer->ibuf);
  if (peer->work)
    stream_reset (peer->work);
  if (peer->obuf)
    stream_fifo_clean (peer->obuf);

  /* Close of file descriptor. */
  if (peer->fd >= 0)
    {
      close (peer->fd);
      peer->fd = -1;
    }

  for (afi = AFI_IP ; afi < AFI_MAX ; afi++)
    for (safi = SAFI_UNICAST ; safi < SAFI_MAX ; safi++)
      {
        /* Reset all negotiated variables */
        peer->afc_nego[afi][safi] = 0;
        peer->afc_adv[afi][safi] = 0;
        peer->afc_recv[afi][safi] = 0;

	/* peer address family capability flags*/
	peer->af_cap[afi][safi] = 0;

	/* peer address family status flags*/
	peer->af_sflags[afi][safi] = 0;

	/* Received ORF prefix-filter */
	peer->orf_plist[afi][safi] = NULL;

	if ((peer->status == OpenConfirm) || (peer->status == Established))  {
	  /* ORF received prefix-filter pnt */
	  sprintf (orf_name, "%s.%d.%d", peer->host, afi, safi);
	  prefix_bgp_orf_remove_all (afi, orf_name);
	}
      }

  /* Reset keepalive and holdtime */
  if (CHECK_FLAG (peer->config, PEER_CONFIG_TIMER))
    {
      peer->v_keepalive = peer->keepalive;
      peer->v_holdtime = peer->holdtime;
    }
  else
    {
      peer->v_keepalive = peer->bgp->default_keepalive;
      peer->v_holdtime = peer->bgp->default_holdtime;
    }

  peer->update_time = 0;

  /* Until we are sure that there is no problem about prefix count
     this should be commented out.*/
#if 0
  /* Reset prefix count */
  peer->pcount[AFI_IP][SAFI_UNICAST] = 0;
  peer->pcount[AFI_IP][SAFI_MULTICAST] = 0;
  peer->pcount[AFI_IP][SAFI_LABELED_UNICAST] = 0;
  peer->pcount[AFI_IP][SAFI_MPLS_VPN] = 0;
  peer->pcount[AFI_IP6][SAFI_UNICAST] = 0;
  peer->pcount[AFI_IP6][SAFI_MULTICAST] = 0;
  peer->pcount[AFI_IP6][SAFI_LABELED_UNICAST] = 0;
#endif /* 0 */

  if (!CHECK_FLAG(peer->flags, PEER_FLAG_CONFIG_NODE) &&
      !(CHECK_FLAG(peer->flags, PEER_FLAG_DELETE)))
    {
      peer_delete(peer);
      ret = -1;
    }
  else
    {
      bgp_peer_conf_if_to_su_update(peer);
    }

  return ret;
}

/* BGP peer is stoped by the error. */
static int
bgp_stop_with_error (struct peer *peer)
{
  /* Double start timer. */
  peer->v_start *= 2;

  /* Overflow check. */
  if (peer->v_start >= (60 * 2))
    peer->v_start = (60 * 2);

  if (peer_dynamic_neighbor(peer))
    {
      if (bgp_debug_neighbor_events(peer))
        zlog_debug ("%s (dynamic neighbor) deleted", peer->host);
      peer_delete (peer);
      return -1;
    }

  return(bgp_stop (peer));
}


/* something went wrong, send notify and tear down */
static int
bgp_stop_with_notify (struct peer *peer, u_char code, u_char sub_code)
{
  /* Send notify to remote peer */
  bgp_notify_send (peer, code, sub_code);

  if (peer_dynamic_neighbor(peer))
    {
      if (bgp_debug_neighbor_events(peer))
        zlog_debug ("%s (dynamic neighbor) deleted", peer->host);
      peer_delete (peer);
      return -1;
    }

  /* Clear start timer value to default. */
  peer->v_start = BGP_INIT_START_TIMER;

  return(bgp_stop(peer));
}


/* TCP connection open.  Next we send open message to remote peer. And
   add read thread for reading open message. */
static int
bgp_connect_success (struct peer *peer)
{
  if (peer->fd < 0)
    {
      zlog_err ("bgp_connect_success peer's fd is negative value %d",
		peer->fd);
      bgp_stop(peer);
      return -1;
    }

  if (bgp_getsockname (peer) < 0)
    {
      zlog_err ("%s: bgp_getsockname(): failed for peer %s, fd %d", __FUNCTION__,
		peer->host, peer->fd);
      bgp_notify_send(peer, BGP_NOTIFY_FSM_ERR, 0); /* internal error */
      return -1;
    }

  BGP_READ_ON (peer->t_read, bgp_read, peer->fd);

  if (bgp_debug_neighbor_events(peer))
    {
      char buf1[SU_ADDRSTRLEN];

      if (! CHECK_FLAG (peer->sflags, PEER_STATUS_ACCEPT_PEER))
	zlog_debug ("%s open active, local address %s", peer->host,
		    sockunion2str (peer->su_local, buf1, SU_ADDRSTRLEN));
      else
	zlog_debug ("%s passive open", peer->host);
    }

  bgp_open_send (peer);

  return 0;
}

/* TCP connect fail */
static int
bgp_connect_fail (struct peer *peer)
{
  if (peer_dynamic_neighbor(peer))
    {
      if (bgp_debug_neighbor_events(peer))
        zlog_debug ("%s (dynamic neighbor) deleted", peer->host);
      peer_delete (peer);
      return -1;
    }

  return (bgp_stop (peer));
}

/* This function is the first starting point of all BGP connection. It
   try to connect to remote peer with non-blocking IO. */
int
bgp_start (struct peer *peer)
{
  int status;
  int connected = 0;

  bgp_peer_conf_if_to_su_update(peer);

  if (peer->su.sa.sa_family == AF_UNSPEC)
    {
      if (bgp_debug_neighbor_events(peer))
        zlog_debug ("%s [FSM] Unable to get neighbor's IP address, waiting...",
		    peer->host);
      return -1;
    }

  if (BGP_PEER_START_SUPPRESSED (peer))
    {
      if (bgp_debug_neighbor_events(peer))
        zlog_err ("%s [FSM] Trying to start suppressed peer"
                  " - this is never supposed to happen!", peer->host);
      return -1;
    }

  /* Scrub some information that might be left over from a previous,
   * session
   */
  /* Connection information. */
  if (peer->su_local)
    {
      sockunion_free (peer->su_local);
      peer->su_local = NULL;
    }

  if (peer->su_remote)
    {
      sockunion_free (peer->su_remote);
      peer->su_remote = NULL;
    }

  /* Clear remote router-id. */
  peer->remote_id.s_addr = 0;

  /* Clear peer capability flag. */
  peer->cap = 0;
    
  /* If the peer is passive mode, force to move to Active mode. */
  if (CHECK_FLAG (peer->flags, PEER_FLAG_PASSIVE))
    {
      BGP_EVENT_ADD (peer, TCP_connection_open_failed);
      return 0;
    }

  /* Register to be notified on peer up */
  if (peer->sort == BGP_PEER_EBGP && peer->ttl == 1 &&
      ! CHECK_FLAG (peer->flags, PEER_FLAG_DISABLE_CONNECTED_CHECK)
      && ! bgp_flag_check(peer->bgp, BGP_FLAG_DISABLE_NH_CONNECTED_CHK))
    connected = 1;
  else
    connected = 0;

  if (!bgp_find_or_add_nexthop(peer->bgp, family2afi(peer->su.sa.sa_family),
			       NULL, peer, connected))
    {
#if defined (HAVE_CUMULUS)
      if (bgp_debug_neighbor_events(peer))
	zlog_debug ("%s [FSM] Waiting for NHT", peer->host);

      BGP_EVENT_ADD(peer, TCP_connection_open_failed);
      return 0;
#endif
    }

  status = bgp_connect (peer);

  switch (status)
    {
    case connect_error:
      if (bgp_debug_neighbor_events(peer))
	zlog_debug ("%s [FSM] Connect error", peer->host);
      BGP_EVENT_ADD (peer, TCP_connection_open_failed);
      break;
    case connect_success:
      if (bgp_debug_neighbor_events(peer))
	zlog_debug ("%s [FSM] Connect immediately success, fd %d",
		   peer->host, peer->fd);
      BGP_EVENT_ADD (peer, TCP_connection_open);
      break;
    case connect_in_progress:
      /* To check nonblocking connect, we wait until socket is
         readable or writable. */
      if (bgp_debug_neighbor_events(peer))
	zlog_debug ("%s [FSM] Non blocking connect waiting result, fd %d",
		   peer->host, peer->fd);
      if (peer->fd < 0)
	{
	  zlog_err ("bgp_start peer's fd is negative value %d",
		    peer->fd);
	  return -1;
	}
      BGP_READ_ON (peer->t_read, bgp_read, peer->fd);
      BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
      break;
    }
  return 0;
}

/* Connect retry timer is expired when the peer status is Connect. */
static int
bgp_reconnect (struct peer *peer)
{
  if (bgp_stop (peer) < 0)
    return -1;

  bgp_start (peer);
  return 0;
}

static int
bgp_fsm_open (struct peer *peer)
{
  /* Send keepalive and make keepalive timer */
  bgp_keepalive_send (peer);

  /* Reset holdtimer value. */
  BGP_TIMER_OFF (peer->t_holdtime);

  return 0;
}

/* Keepalive send to peer. */
static int
bgp_fsm_keepalive_expire (struct peer *peer)
{
  bgp_keepalive_send (peer);
  return 0;
}

/* FSM error, unexpected event.  This is error of BGP connection. So cut the
   peer and change to Idle status. */
static int
bgp_fsm_event_error (struct peer *peer)
{
  zlog_err ("%s [FSM] unexpected packet received in state %s",
	    peer->host, lookup_msg(bgp_status_msg, peer->status, NULL));

  return bgp_stop_with_notify (peer, BGP_NOTIFY_FSM_ERR, 0);
}

/* Hold timer expire.  This is error of BGP connection. So cut the
   peer and change to Idle status. */
static int
bgp_fsm_holdtime_expire (struct peer *peer)
{
  if (bgp_debug_neighbor_events(peer))
    zlog_debug ("%s [FSM] Hold timer expire", peer->host);

  return bgp_stop_with_notify (peer, BGP_NOTIFY_HOLD_ERR, 0);
}

/* Status goes to Established.  Send keepalive packet then make first
   update information. */
static int
bgp_establish (struct peer *peer)
{
  afi_t afi;
  safi_t safi;
  int nsf_af_count = 0;
  int ret = 0;
  struct peer *other;

  other = peer->doppelganger;
  peer = peer_xfer_conn(peer);
  if (!peer)
    {
      zlog_err ("%%Neighbor failed in xfer_conn");
      return -1;
    }

  if (other == peer)
    ret = 1; /* bgp_establish specific code when xfer_conn happens. */

  /* Reset capability open status flag. */
  if (! CHECK_FLAG (peer->sflags, PEER_STATUS_CAPABILITY_OPEN))
    SET_FLAG (peer->sflags, PEER_STATUS_CAPABILITY_OPEN);

  /* Clear start timer value to default. */
  peer->v_start = BGP_INIT_START_TIMER;

  /* Increment established count. */
  peer->established++;
  bgp_fsm_change_status (peer, Established);

  /* bgp log-neighbor-changes of neighbor Up */
  if (bgp_flag_check (peer->bgp, BGP_FLAG_LOG_NEIGHBOR_CHANGES))
    {
      struct vrf *vrf = vrf_lookup_by_id (peer->bgp->vrf_id);
      zlog_info ("%%ADJCHANGE: neighbor %s(%s) in vrf %s Up",
		 peer->host,
		 (peer->hostname) ? peer->hostname : "Unknown",
		 vrf ? ((vrf->vrf_id != VRF_DEFAULT ) ? vrf->name : "Default") : "");
    }
  /* assign update-group/subgroup */
  update_group_adjust_peer_afs(peer);

  /* graceful restart */
  UNSET_FLAG (peer->sflags, PEER_STATUS_NSF_WAIT);
  for (afi = AFI_IP ; afi < AFI_MAX ; afi++)
    for (safi = SAFI_UNICAST ; safi < SAFI_RESERVED_4 ; safi++)
      {
	if (peer->afc_nego[afi][safi]
	    && CHECK_FLAG (peer->cap, PEER_CAP_RESTART_ADV)
	    && CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_RESTART_AF_RCV))
	  {
	    if (peer->nsf[afi][safi]
		&& ! CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_RESTART_AF_PRESERVE_RCV))
	      bgp_clear_stale_route (peer, afi, safi);

	    peer->nsf[afi][safi] = 1;
	    nsf_af_count++;
	  }
	else
	  {
	    if (peer->nsf[afi][safi])
	      bgp_clear_stale_route (peer, afi, safi);
	    peer->nsf[afi][safi] = 0;
	  }
      }

  if (nsf_af_count)
    SET_FLAG (peer->sflags, PEER_STATUS_NSF_MODE);
  else
    {
      UNSET_FLAG (peer->sflags, PEER_STATUS_NSF_MODE);
      if (peer->t_gr_stale)
	{
	  BGP_TIMER_OFF (peer->t_gr_stale);
          if (bgp_debug_neighbor_events(peer))
	    zlog_debug ("%s graceful restart stalepath timer stopped", peer->host);
	}
    }

  if (peer->t_gr_restart)
    {
      BGP_TIMER_OFF (peer->t_gr_restart);
      if (bgp_debug_neighbor_events(peer))
	zlog_debug ("%s graceful restart timer stopped", peer->host);
    }

  hook_call(peer_established, peer);

  /* Reset uptime, send keepalive, send current table. */
  peer->uptime = bgp_clock ();

  /* Send route-refresh when ORF is enabled */
  for (afi = AFI_IP ; afi < AFI_MAX ; afi++)
    for (safi = SAFI_UNICAST ; safi < SAFI_MAX ; safi++)
      if (CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_ORF_PREFIX_SM_ADV))
	{
	  if (CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_ORF_PREFIX_RM_RCV))
	    bgp_route_refresh_send (peer, afi, safi, ORF_TYPE_PREFIX,
				    REFRESH_IMMEDIATE, 0);
	  else if (CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_ORF_PREFIX_RM_OLD_RCV))
	    bgp_route_refresh_send (peer, afi, safi, ORF_TYPE_PREFIX_OLD,
				    REFRESH_IMMEDIATE, 0);
	}

  /* First update is deferred until ORF or ROUTE-REFRESH is received */
  for (afi = AFI_IP ; afi < AFI_MAX ; afi++)
    for (safi = SAFI_UNICAST ; safi < SAFI_MAX ; safi++)
      if (CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_ORF_PREFIX_RM_ADV))
	if (CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_ORF_PREFIX_SM_RCV)
	    || CHECK_FLAG (peer->af_cap[afi][safi], PEER_CAP_ORF_PREFIX_SM_OLD_RCV))
	  SET_FLAG (peer->af_sflags[afi][safi], PEER_STATUS_ORF_WAIT_REFRESH);

  bgp_announce_peer (peer);

  /* Start the route advertisement timer to send updates to the peer - if BGP
   * is not in read-only mode. If it is, the timer will be started at the end
   * of read-only mode.
   */
  if (!bgp_update_delay_active(peer->bgp))
    {
      BGP_TIMER_OFF(peer->t_routeadv);
      BGP_TIMER_ON (peer->t_routeadv, bgp_routeadv_timer, 0);
    }

  if (peer->doppelganger && (peer->doppelganger->status != Deleted))
    {
      if (bgp_debug_neighbor_events(peer))
	zlog_debug("[Event] Deleting stub connection for peer %s", peer->host);

      if (peer->doppelganger->status > Active)
	bgp_notify_send (peer->doppelganger, BGP_NOTIFY_CEASE,
			 BGP_NOTIFY_CEASE_COLLISION_RESOLUTION);
      else
	peer_delete(peer->doppelganger);
    }

  bgp_bfd_register_peer(peer);
  return ret;
}

/* Keepalive packet is received. */
static int
bgp_fsm_keepalive (struct peer *peer)
{
  bgp_update_implicit_eors(peer);

  /* peer count update */
  peer->keepalive_in++;

  BGP_TIMER_OFF (peer->t_holdtime);
  return 0;
}

/* Update packet is received. */
static int
bgp_fsm_update (struct peer *peer)
{
  BGP_TIMER_OFF (peer->t_holdtime);
  return 0;
}

/* This is empty event. */
static int
bgp_ignore (struct peer *peer)
{
  zlog_err ("%s [FSM] Ignoring event %s in state %s, prior events %s, %s, fd %d",
             peer->host, bgp_event_str[peer->cur_event],
	     lookup_msg(bgp_status_msg, peer->status, NULL),
             bgp_event_str[peer->last_event],
             bgp_event_str[peer->last_major_event], peer->fd);
  return 0;
}

/* This is to handle unexpected events.. */
static int
bgp_fsm_exeption (struct peer *peer)
{
  zlog_err ("%s [FSM] Unexpected event %s in state %s, prior events %s, %s, fd %d",
             peer->host, bgp_event_str[peer->cur_event],
	     lookup_msg(bgp_status_msg, peer->status, NULL),
             bgp_event_str[peer->last_event],
             bgp_event_str[peer->last_major_event], peer->fd);
  return(bgp_stop (peer));
}

void
bgp_fsm_nht_update(struct peer *peer, int valid)
{
  if (!peer)
    return;

  switch (peer->status)
    {
    case Idle:
      if (valid)
	BGP_EVENT_ADD(peer, BGP_Start);
      break;
    case Connect:
      if (!valid)
	{
	  BGP_TIMER_OFF(peer->t_connect);
	  BGP_EVENT_ADD(peer, TCP_fatal_error);
	}
      break;
    case Active:
      if (valid)
	{
	  BGP_TIMER_OFF(peer->t_connect);
	  BGP_EVENT_ADD(peer, ConnectRetry_timer_expired);
	}
      break;
    case OpenSent:
    case OpenConfirm:
    case Established:
      if (!valid && (peer->gtsm_hops == 1))
	BGP_EVENT_ADD(peer, TCP_fatal_error);
    case Clearing:
    case Deleted:
    default:
      break;
    }
}


/* Finite State Machine structure */
static const struct {
  int (*func) (struct peer *);
  int next_state;
} FSM [BGP_STATUS_MAX - 1][BGP_EVENTS_MAX - 1] = 
{
  {
    /* Idle state: In Idle state, all events other than BGP_Start is
       ignored.  With BGP_Start event, finite state machine calls
       bgp_start(). */
    {bgp_start,  Connect},	/* BGP_Start                    */
    {bgp_stop,   Idle},		/* BGP_Stop                     */
    {bgp_stop,   Idle},		/* TCP_connection_open          */
    {bgp_stop,   Idle},		/* TCP_connection_closed        */
    {bgp_ignore, Idle},		/* TCP_connection_open_failed   */
    {bgp_stop,   Idle},		/* TCP_fatal_error              */
    {bgp_ignore, Idle},		/* ConnectRetry_timer_expired   */
    {bgp_ignore, Idle},		/* Hold_Timer_expired           */
    {bgp_ignore, Idle},		/* KeepAlive_timer_expired      */
    {bgp_ignore, Idle},		/* Receive_OPEN_message         */
    {bgp_ignore, Idle},		/* Receive_KEEPALIVE_message    */
    {bgp_ignore, Idle},		/* Receive_UPDATE_message       */
    {bgp_ignore, Idle},		/* Receive_NOTIFICATION_message */
    {bgp_ignore, Idle},         /* Clearing_Completed           */
  },
  {
    /* Connect */
    {bgp_ignore,  Connect},	/* BGP_Start                    */
    {bgp_stop,    Idle},	/* BGP_Stop                     */
    {bgp_connect_success, OpenSent}, /* TCP_connection_open          */
    {bgp_stop, Idle},		/* TCP_connection_closed        */
    {bgp_connect_fail, Active}, /* TCP_connection_open_failed   */
    {bgp_connect_fail, Idle},	/* TCP_fatal_error              */
    {bgp_reconnect, Connect},	/* ConnectRetry_timer_expired   */
    {bgp_fsm_exeption,  Idle},	/* Hold_Timer_expired           */
    {bgp_fsm_exeption,  Idle},	/* KeepAlive_timer_expired      */
    {bgp_fsm_exeption,  Idle},	/* Receive_OPEN_message         */
    {bgp_fsm_exeption,  Idle},	/* Receive_KEEPALIVE_message    */
    {bgp_fsm_exeption,  Idle},	/* Receive_UPDATE_message       */
    {bgp_stop,    Idle},	/* Receive_NOTIFICATION_message */
    {bgp_fsm_exeption,  Idle},         /* Clearing_Completed           */
  },
  {
    /* Active, */
    {bgp_ignore,  Active},	/* BGP_Start                    */
    {bgp_stop,    Idle},	/* BGP_Stop                     */
    {bgp_connect_success, OpenSent}, /* TCP_connection_open          */
    {bgp_stop,    Idle},	/* TCP_connection_closed        */
    {bgp_ignore,  Active},	/* TCP_connection_open_failed   */
    {bgp_fsm_exeption,  Idle},	/* TCP_fatal_error              */
    {bgp_start,   Connect},	/* ConnectRetry_timer_expired   */
    {bgp_fsm_exeption,  Idle},	/* Hold_Timer_expired           */
    {bgp_fsm_exeption,  Idle},	/* KeepAlive_timer_expired      */
    {bgp_fsm_exeption,  Idle},	/* Receive_OPEN_message         */
    {bgp_fsm_exeption,  Idle},	/* Receive_KEEPALIVE_message    */
    {bgp_fsm_exeption,  Idle},	/* Receive_UPDATE_message       */
    {bgp_fsm_exeption, Idle}, /* Receive_NOTIFICATION_message */
    {bgp_fsm_exeption, Idle},         /* Clearing_Completed           */
  },
  {
    /* OpenSent, */
    {bgp_ignore,  OpenSent},	/* BGP_Start                    */
    {bgp_stop,    Idle},	/* BGP_Stop                     */
    {bgp_stop,    Active},	/* TCP_connection_open          */
    {bgp_stop,    Active},	/* TCP_connection_closed        */
    {bgp_stop,    Active},	/* TCP_connection_open_failed   */
    {bgp_stop,    Active},	/* TCP_fatal_error              */
    {bgp_fsm_exeption,  Idle},	/* ConnectRetry_timer_expired   */
    {bgp_fsm_holdtime_expire, Idle},	/* Hold_Timer_expired           */
    {bgp_fsm_exeption,  Idle},	/* KeepAlive_timer_expired      */
    {bgp_fsm_open,    OpenConfirm},	/* Receive_OPEN_message         */
    {bgp_fsm_event_error, Idle}, /* Receive_KEEPALIVE_message    */
    {bgp_fsm_event_error, Idle}, /* Receive_UPDATE_message       */
    {bgp_stop_with_error, Idle}, /* Receive_NOTIFICATION_message */
    {bgp_fsm_exeption, Idle},         /* Clearing_Completed           */
  },
  {
    /* OpenConfirm, */
    {bgp_ignore,  OpenConfirm},	/* BGP_Start                    */
    {bgp_stop,    Idle},	/* BGP_Stop                     */
    {bgp_stop,    Idle},	/* TCP_connection_open          */
    {bgp_stop,    Idle},	/* TCP_connection_closed        */
    {bgp_stop,    Idle},	/* TCP_connection_open_failed   */
    {bgp_stop,    Idle},	/* TCP_fatal_error              */
    {bgp_fsm_exeption,  Idle},	/* ConnectRetry_timer_expired   */
    {bgp_fsm_holdtime_expire, Idle},	/* Hold_Timer_expired           */
    {bgp_ignore,  OpenConfirm},	/* KeepAlive_timer_expired      */
    {bgp_fsm_exeption,  Idle},	/* Receive_OPEN_message         */
    {bgp_establish, Established}, /* Receive_KEEPALIVE_message    */
    {bgp_fsm_exeption,  Idle},	/* Receive_UPDATE_message       */
    {bgp_stop_with_error, Idle}, /* Receive_NOTIFICATION_message */
    {bgp_fsm_exeption, Idle},         /* Clearing_Completed           */
  },
  {
    /* Established, */
    {bgp_ignore,               Established}, /* BGP_Start                    */
    {bgp_stop,                    Clearing}, /* BGP_Stop                     */
    {bgp_stop,                    Clearing}, /* TCP_connection_open          */
    {bgp_stop,                    Clearing}, /* TCP_connection_closed        */
    {bgp_stop,                 Clearing},	/* TCP_connection_open_failed   */
    {bgp_stop,                    Clearing}, /* TCP_fatal_error              */
    {bgp_stop,                 Clearing},	/* ConnectRetry_timer_expired   */
    {bgp_fsm_holdtime_expire,     Clearing}, /* Hold_Timer_expired           */
    {bgp_fsm_keepalive_expire, Established}, /* KeepAlive_timer_expired      */
    {bgp_stop,                    Clearing}, /* Receive_OPEN_message         */
    {bgp_fsm_keepalive,        Established}, /* Receive_KEEPALIVE_message    */
    {bgp_fsm_update,           Established}, /* Receive_UPDATE_message       */
    {bgp_stop_with_error,         Clearing}, /* Receive_NOTIFICATION_message */
    {bgp_fsm_exeption,            Idle}, /* Clearing_Completed           */
  },
  {
    /* Clearing, */
    {bgp_ignore,  Clearing},	/* BGP_Start                    */
    {bgp_stop,			Clearing},	/* BGP_Stop                     */
    {bgp_stop,			Clearing},	/* TCP_connection_open          */
    {bgp_stop,			Clearing},	/* TCP_connection_closed        */
    {bgp_stop,			Clearing},	/* TCP_connection_open_failed   */
    {bgp_stop,			Clearing},	/* TCP_fatal_error              */
    {bgp_stop,			Clearing},	/* ConnectRetry_timer_expired   */
    {bgp_stop,			Clearing},	/* Hold_Timer_expired           */
    {bgp_stop,			Clearing},	/* KeepAlive_timer_expired      */
    {bgp_stop,			Clearing},	/* Receive_OPEN_message         */
    {bgp_stop,			Clearing},	/* Receive_KEEPALIVE_message    */
    {bgp_stop,			Clearing},	/* Receive_UPDATE_message       */
    {bgp_stop,			Clearing},	/* Receive_NOTIFICATION_message */
    {bgp_clearing_completed,    Idle},		/* Clearing_Completed           */
  },
  {
    /* Deleted, */
    {bgp_ignore,  Deleted},	/* BGP_Start                    */
    {bgp_ignore,  Deleted},	/* BGP_Stop                     */
    {bgp_ignore,  Deleted},	/* TCP_connection_open          */
    {bgp_ignore,  Deleted},	/* TCP_connection_closed        */
    {bgp_ignore,  Deleted},	/* TCP_connection_open_failed   */
    {bgp_ignore,  Deleted},	/* TCP_fatal_error              */
    {bgp_ignore,  Deleted},	/* ConnectRetry_timer_expired   */
    {bgp_ignore,  Deleted},	/* Hold_Timer_expired           */
    {bgp_ignore,  Deleted},	/* KeepAlive_timer_expired      */
    {bgp_ignore,  Deleted},	/* Receive_OPEN_message         */
    {bgp_ignore,  Deleted},	/* Receive_KEEPALIVE_message    */
    {bgp_ignore,  Deleted},	/* Receive_UPDATE_message       */
    {bgp_ignore,  Deleted},	/* Receive_NOTIFICATION_message */
    {bgp_ignore,  Deleted},	/* Clearing_Completed           */
  },
};

/* Execute event process. */
int
bgp_event (struct thread *thread)
{
  int event;
  struct peer *peer;
  int ret;

  peer = THREAD_ARG (thread);
  event = THREAD_VAL (thread);

  ret = bgp_event_update(peer, event);

  return (ret);
}

int
bgp_event_update (struct peer *peer, int event)
{
  int next;
  int ret = 0;
  struct peer *other;
  int passive_conn = 0;
  int dyn_nbr;

  other = peer->doppelganger;
  passive_conn = (CHECK_FLAG(peer->sflags, PEER_STATUS_ACCEPT_PEER)) ? 1 : 0;
  dyn_nbr = peer_dynamic_neighbor(peer);

  /* Logging this event. */
  next = FSM [peer->status -1][event - 1].next_state;

  if (bgp_debug_neighbor_events(peer) && peer->status != next)
    zlog_debug ("%s [FSM] %s (%s->%s), fd %d", peer->host,
	       bgp_event_str[event],
	       lookup_msg(bgp_status_msg, peer->status, NULL),
	       lookup_msg(bgp_status_msg, next, NULL), peer->fd);

  peer->last_event = peer->cur_event;
  peer->cur_event = event;

  /* Call function. */
  if (FSM [peer->status -1][event - 1].func)
    ret = (*(FSM [peer->status - 1][event - 1].func))(peer);

  /* When function do not want proceed next job return -1. */
  if (ret >= 0)
    {
      if (ret == 1 && next == Established)
        {
          /* The case when doppelganger swap accurred in bgp_establish.
             Update the peer pointer accordingly */
          peer = other;
        }

      /* If status is changed. */
      if (next != peer->status)
        bgp_fsm_change_status (peer, next);
      
      /* Make sure timer is set. */
      bgp_timer_set (peer);

    }
  else if (!dyn_nbr && !passive_conn && peer->bgp)
    {
      /* If we got a return value of -1, that means there was an error, restart
       * the FSM. If the peer structure was deleted
       */
      zlog_err ("%s [FSM] Failure handling event %s in state %s, "
                 "prior events %s, %s, fd %d",
                 peer->host, bgp_event_str[peer->cur_event],
	         lookup_msg(bgp_status_msg, peer->status, NULL),
                 bgp_event_str[peer->last_event],
                 bgp_event_str[peer->last_major_event], peer->fd);
      bgp_stop (peer);
      bgp_fsm_change_status(peer, Idle);
      bgp_timer_set(peer);
    }
  return ret;
}