aboutsummaryrefslogtreecommitdiffstats
path: root/LICENSE
blob: d645695673349e3947e8e5ae42332d0ac3164cd7 (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
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
='#n984'>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 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
/*
 * Copyright (c) 2015 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <vpp/stats/stats.h>
#include <signal.h>
#include <vnet/fib/ip4_fib.h>
#include <vnet/fib/fib_entry.h>
#include <vnet/mfib/mfib_entry.h>
#include <vnet/dpo/load_balance.h>

#define STATS_DEBUG 0

stats_main_t stats_main;

#include <vnet/ip/ip.h>

#include <vpp/api/vpe_msg_enum.h>

#define f64_endian(a)
#define f64_print(a,b)

#define vl_typedefs		/* define message structures */
#include <vpp/api/vpe_all_api_h.h>
#undef vl_typedefs

#define vl_endianfun		/* define message structures */
#include <vpp/api/vpe_all_api_h.h>
#undef vl_endianfun

/* instantiate all the print functions we know about */
#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
#define vl_printfun
#include <vpp/api/vpe_all_api_h.h>
#undef vl_printfun

#define foreach_stats_msg						\
_(WANT_STATS, want_stats)						\
_(VNET_INTERFACE_SIMPLE_COUNTERS, vnet_interface_simple_counters)	\
_(WANT_INTERFACE_SIMPLE_STATS, want_interface_simple_stats)	\
_(VNET_INTERFACE_COMBINED_COUNTERS, vnet_interface_combined_counters)	\
_(WANT_INTERFACE_COMBINED_STATS, want_interface_combined_stats)	\
_(WANT_PER_INTERFACE_COMBINED_STATS, want_per_interface_combined_stats)	\
_(WANT_PER_INTERFACE_SIMPLE_STATS, want_per_interface_simple_stats) \
_(VNET_IP4_FIB_COUNTERS, vnet_ip4_fib_counters)				\
_(WANT_IP4_FIB_STATS, want_ip4_fib_stats)            \
_(VNET_IP6_FIB_COUNTERS, vnet_ip6_fib_counters)				\
_(WANT_IP6_FIB_STATS, want_ip6_fib_stats)        \
_(WANT_IP4_MFIB_STATS, want_ip4_mfib_stats)                             \
_(WANT_IP6_MFIB_STATS, want_ip6_mfib_stats)                             \
_(VNET_IP4_NBR_COUNTERS, vnet_ip4_nbr_counters)				\
_(WANT_IP4_NBR_STATS, want_ip4_nbr_stats)            \
_(VNET_IP6_NBR_COUNTERS, vnet_ip6_nbr_counters) \
_(WANT_IP6_NBR_STATS, want_ip6_nbr_stats) \
_(VNET_GET_SUMMARY_STATS, vnet_get_summary_stats)


#define vl_msg_name_crc_list
#include <vpp/stats/stats.api.h>
#undef vl_msg_name_crc_list

static void
setup_message_id_table (api_main_t * am)
{
#define _(id,n,crc) \
  vl_msg_api_add_msg_name_crc (am, #n "_" #crc, id);
  foreach_vl_msg_name_crc_stats;
#undef _
}

/* These constants ensure msg sizes <= 1024, aka ring allocation */
#define SIMPLE_COUNTER_BATCH_SIZE	126
#define COMBINED_COUNTER_BATCH_SIZE	63
#define IP4_FIB_COUNTER_BATCH_SIZE	48
#define IP6_FIB_COUNTER_BATCH_SIZE	30
#define IP4_MFIB_COUNTER_BATCH_SIZE	24
#define IP6_MFIB_COUNTER_BATCH_SIZE	15

/* 5ms */
#define STATS_RELEASE_DELAY_NS (1000 * 1000 * 5)
/*                              ns/us  us/ms        */

u8 *
format_vnet_interface_combined_counters (u8 * s, va_list * args)
{
  stats_main_t *sm = &stats_main;
  vl_api_vnet_interface_combined_counters_t *mp =
    va_arg (*args, vl_api_vnet_interface_combined_counters_t *);

  char *counter_name;
  u32 count, sw_if_index;
  int i;
  count = ntohl (mp->count);
  sw_if_index = ntohl (mp->first_sw_if_index);

  vlib_counter_t *vp;
  u64 packets, bytes;
  vp = (vlib_counter_t *) mp->data;

  switch (mp->vnet_counter_type)
    {
    case VNET_INTERFACE_COUNTER_RX:
      counter_name = "rx";
      break;
    case VNET_INTERFACE_COUNTER_TX:
      counter_name = "tx";
      break;
    default:
      counter_name = "bogus";
      break;
    }
  for (i = 0; i < count; i++)
    {
      packets = clib_mem_unaligned (&vp->packets, u64);
      packets = clib_net_to_host_u64 (packets);
      bytes = clib_mem_unaligned (&vp->bytes, u64);
      bytes = clib_net_to_host_u64 (bytes);
      vp++;
      s = format (s, "%U.%s.packets %lld\n",
		  format_vnet_sw_if_index_name,
		  sm->vnet_main, sw_if_index, counter_name, packets);
      s = format (s, "%U.%s.bytes %lld\n",
		  format_vnet_sw_if_index_name,
		  sm->vnet_main, sw_if_index, counter_name, bytes);
      sw_if_index++;
    }
  return s;
}

u8 *
format_vnet_interface_simple_counters (u8 * s, va_list * args)
{
  stats_main_t *sm = &stats_main;
  vl_api_vnet_interface_simple_counters_t *mp =
    va_arg (*args, vl_api_vnet_interface_simple_counters_t *);
  char *counter_name;
  u32 count, sw_if_index;
  count = ntohl (mp->count);
  sw_if_index = ntohl (mp->first_sw_if_index);
  u64 *vp, v;
  vp = (u64 *) mp->data;
  int i;

  switch (mp->vnet_counter_type)
    {
    case VNET_INTERFACE_COUNTER_DROP:
      counter_name = "drop";
      break;
    case VNET_INTERFACE_COUNTER_PUNT:
      counter_name = "punt";
      break;
    case VNET_INTERFACE_COUNTER_IP4:
      counter_name = "ip4";
      break;
    case VNET_INTERFACE_COUNTER_IP6:
      counter_name = "ip6";
      break;
    case VNET_INTERFACE_COUNTER_RX_NO_BUF:
      counter_name = "rx-no-buff";
      break;
    case VNET_INTERFACE_COUNTER_RX_MISS:
      counter_name = "rx-miss";
      break;
    case VNET_INTERFACE_COUNTER_RX_ERROR:
      counter_name = "rx-error (fifo-full)";
      break;
    case VNET_INTERFACE_COUNTER_TX_ERROR:
      counter_name = "tx-error (fifo-full)";
      break;
    default:
      counter_name = "bogus";
      break;
    }
  for (i = 0; i < count; i++)
    {
      v = clib_mem_unaligned (vp, u64);
      v = clib_net_to_host_u64 (v);
      vp++;
      s = format (s, "%U.%s %lld\n", format_vnet_sw_if_index_name,
		  sm->vnet_main, sw_if_index, counter_name, v);
      sw_if_index++;
    }

  return s;
}

static void
dslock (stats_main_t * sm, int release_hint, int tag)
{
  u32 thread_index;
  data_structure_lock_t *l = sm->data_structure_lock;

  if (PREDICT_FALSE (l == 0))
    return;

  thread_index = vlib_get_thread_index ();
  if (l->lock && l->thread_index == thread_index)
    {
      l->count++;
      return;
    }

  if (release_hint)
    l->release_hint++;

  while (__sync_lock_test_and_set (&l->lock, 1))
    /* zzzz */ ;
  l->tag = tag;
  l->thread_index = thread_index;
  l->count = 1;
}

void
stats_dslock_with_hint (int hint, int tag)
{
  stats_main_t *sm = &stats_main;
  dslock (sm, hint, tag);
}

static void
dsunlock (stats_main_t * sm)
{
  u32 thread_index;
  data_structure_lock_t *l = sm->data_structure_lock;

  if (PREDICT_FALSE (l == 0))
    return;

  thread_index = vlib_get_thread_index ();
  ASSERT (l->lock && l->thread_index == thread_index);
  l->count--;
  if (l->count == 0)
    {
      l->tag = -l->tag;
      l->release_hint = 0;
      CLIB_MEMORY_BARRIER ();
      l->lock = 0;
    }
}

void
stats_dsunlock (int hint, int tag)
{
  stats_main_t *sm = &stats_main;
  dsunlock (sm);
}

static vpe_client_registration_t *
get_client_for_stat (u32 reg, u32 item, u32 client_index)
{
  stats_main_t *sm = &stats_main;
  vpe_client_stats_registration_t *registration;
  uword *p;

  /* Is there anything listening for item in that reg */
  p = hash_get (sm->stats_registration_hash[reg], item);

  if (!p)
    return 0;			// Fail

  /* If there is, is our client_index one of them */
  registration = pool_elt_at_index (sm->stats_registrations[reg], p[0]);
  p = hash_get (registration->client_hash, client_index);

  if (!p)
    return 0;			// Fail

  return pool_elt_at_index (registration->clients, p[0]);

}

static int
set_client_for_stat (u32 reg, u32 item, vpe_client_registration_t * client)
{
  stats_main_t *sm = &stats_main;
  vpe_client_stats_registration_t *registration;
  vpe_client_registration_t *cr;
  uword *p;

  /* Is there anything listening for item in that reg */
  p = hash_get (sm->stats_registration_hash[reg], item);

  if (!p)
    {
      pool_get (sm->stats_registrations[reg], registration);
      registration->item = item;
      hash_set (sm->stats_registration_hash[reg], item,
		registration - sm->stats_registrations[reg]);
    }
  else
    {
      registration = pool_elt_at_index (sm->stats_registrations[reg], p[0]);
    }

  p = hash_get (registration->client_hash, client->client_index);

  if (!p)
    {
      pool_get (registration->clients, cr);
      cr->client_index = client->client_index;
      cr->client_pid = client->client_pid;
      hash_set (registration->client_hash, cr->client_index,
		cr - registration->clients);
    }

  return 1;			//At least one client is doing something ... poll
}

int
clear_client_for_stat (u32 reg, u32 item, u32 client_index)
{
  stats_main_t *sm = &stats_main;
  vpe_client_stats_registration_t *registration;
  vpe_client_registration_t *client;
  uword *p;
  int i, elts;

  /* Clear the client first */
  /* Is there anything listening for item in that reg */
  p = hash_get (sm->stats_registration_hash[reg], item);

  if (!p)
    goto exit;

  /* If there is, is our client_index one of them */
  registration = pool_elt_at_index (sm->stats_registrations[reg], p[0]);
  p = hash_get (registration->client_hash, client_index);

  if (!p)
    goto exit;

  client = pool_elt_at_index (registration->clients, p[0]);
  hash_unset (registration->client_hash, client->client_index);
  pool_put (registration->clients, client);

  /* Now check if that was the last client for that item */
  if (0 == pool_elts (registration->clients))
    {
      hash_unset (sm->stats_registration_hash[reg], item);
      pool_put (sm->stats_registrations[reg], registration);
    }

exit:
  elts = 0;
  /* Now check if that was the last item in any of the listened to stats */
  for (i = 0; i < STATS_REG_N_IDX; i++)
    {
      elts += pool_elts (sm->stats_registrations[i]);
    }
  return elts;
}

vpe_client_registration_t *
get_clients_for_stat (u32 reg, u32 item)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t *client, *clients = 0;
  vpe_client_stats_registration_t *registration;
  uword *p;

  /* Is there anything listening for item in that reg */
  p = hash_get (sm->stats_registration_hash[reg], item);

  if (!p)
    return 0;			// Fail

  /* If there is, is our client_index one of them */
  registration = pool_elt_at_index (sm->stats_registrations[reg], p[0]);

  vec_reset_length (clients);
  pool_foreach (client, registration->clients, (
						 {
						 vec_add1 (clients, *client);}
		));
  return clients;
}


static void
clear_client_reg (u32 ** registrations)
{
  /* When registrations[x] is a vector of pool indices
     here is a good place to clean up the pools
   */
#define stats_reg(n) vec_free(registrations[IDX_##n]);
#include <vpp/stats/stats.reg>
#undef stats_reg

  vec_free (registrations);
}

u32 **
init_client_reg (u32 ** registrations)
{

  /*
     Initialise the stats registrations for each
     type of stat a client can register for as well as
     a vector of "interested" indexes.
     Initially this is a u32 of either sw_if_index or fib_index
     but eventually this should migrate to a pool_index (u32)
     with a type specific pool that can include more complex things
     such as timing and structured events.
   */
  vec_validate (registrations, STATS_REG_N_IDX);
#define stats_reg(n) \
  vec_reset_length(registrations[IDX_##n]);
#include <vpp/stats/stats.reg>
#undef stats_reg

  /*
     When registrations[x] is a vector of pool indices, here
     is a good place to init the pools.
   */
  return registrations;
}

u32 **
enable_all_client_reg (u32 ** registrations)
{

  /*
     Enable all stats known by adding
     ~0 to the index vector. Eventually this
     should be deprecated.
   */
#define stats_reg(n)                            \
  vec_add1(registrations[IDX_##n], ~0);
#include <vpp/stats/stats.reg>
#undef stats_reg
  return registrations;
}

static void
do_simple_interface_counters (stats_main_t * sm)
{
  vl_api_vnet_interface_simple_counters_t *mp = 0;
  vnet_interface_main_t *im = sm->interface_main;
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  svm_queue_t *q = shmem_hdr->vl_input_queue;
  vlib_simple_counter_main_t *cm;
  u32 items_this_message = 0;
  u64 v, *vp = 0;
  int i, n_counts;

  /*
   * Prevent interface registration from expanding / moving the vectors...
   * That tends never to happen, so we can hold this lock for a while.
   */
  vnet_interface_counter_lock (im);

  vec_foreach (cm, im->sw_if_counters)
  {
    n_counts = vlib_simple_counter_n_counters (cm);
    for (i = 0; i < n_counts; i++)
      {
	if (mp == 0)
	  {
	    items_this_message = clib_min (SIMPLE_COUNTER_BATCH_SIZE,
					   n_counts - i);

	    mp = vl_msg_api_alloc_as_if_client
	      (sizeof (*mp) + items_this_message * sizeof (v));
	    mp->_vl_msg_id = ntohs (VL_API_VNET_INTERFACE_SIMPLE_COUNTERS);
	    mp->vnet_counter_type = cm - im->sw_if_counters;
	    mp->first_sw_if_index = htonl (i);
	    mp->count = 0;
	    vp = (u64 *) mp->data;
	  }
	v = vlib_get_simple_counter (cm, i);
	clib_mem_unaligned (vp, u64) = clib_host_to_net_u64 (v);
	vp++;
	mp->count++;
	if (mp->count == items_this_message)
	  {
	    mp->count = htonl (items_this_message);
	    /* Send to the main thread... */
	    vl_msg_api_send_shmem (q, (u8 *) & mp);
	    mp = 0;
	  }
      }
    ASSERT (mp == 0);
  }
  vnet_interface_counter_unlock (im);
}

void
handle_client_registration (vpe_client_registration_t * client, u32 stat,
			    u32 item, int enable_disable)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t *rp, _rp;

  rp = get_client_for_stat (stat, item, client->client_index);

  /* Disable case */
  if (enable_disable == 0)
    {
      if (!rp)			// No client to disable
	{
	  clib_warning ("pid %d: already disabled for stats...",
			client->client_pid);
	  return;
	}
      sm->enable_poller =
	clear_client_for_stat (stat, item, client->client_index);
      return;
    }
  /* Enable case */
  if (!rp)
    {
      rp = &_rp;
      rp->client_index = client->client_index;
      rp->client_pid = client->client_pid;
      sm->enable_poller = set_client_for_stat (stat, item, rp);
    }
}


/**********************************
 * ALL Interface Combined stats - to be deprecated
 **********************************/

/*
 * This API should be deprecated as _per_interface_ works with ~0 as sw_if_index.
 */
static void
  vl_api_want_interface_combined_stats_t_handler
  (vl_api_want_interface_combined_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_interface_combined_stats_reply_t *rmp;
  uword *p;
  i32 retval = 0;
  vl_api_registration_t *reg;
  u32 swif;

  swif = ~0;			//Using same mechanism as _per_interface_
  rp.client_index = mp->client_index;
  rp.client_pid = mp->pid;

  handle_client_registration (&rp, IDX_PER_INTERFACE_COMBINED_COUNTERS, swif,
			      mp->enable_disable);

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    {
      sm->enable_poller =
	clear_client_for_stat (IDX_PER_INTERFACE_COMBINED_COUNTERS, swif,
			       mp->client_index);
      return;
    }

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_INTERFACE_COMBINED_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}

static void
  vl_api_vnet_interface_combined_counters_t_handler
  (vl_api_vnet_interface_combined_counters_t * mp)
{
  vpe_client_registration_t *clients, client;
  stats_main_t *sm = &stats_main;
  vl_api_registration_t *reg, *reg_prev = NULL;
  vl_api_vnet_interface_combined_counters_t *mp_copy = NULL;
  u32 mp_size;
  int i;

  mp_size = sizeof (*mp) + (ntohl (mp->count) * sizeof (vlib_counter_t));

  clients =
    get_clients_for_stat (IDX_PER_INTERFACE_COMBINED_COUNTERS,
			  ~0 /*flag for all */ );

  for (i = 0; i < vec_len (clients); i++)
    {
      client = clients[i];
      reg = vl_api_client_index_to_registration (client.client_index);
      if (reg)
	{
	  if (reg_prev && vl_api_can_send_msg (reg_prev))
	    {
	      mp_copy = vl_msg_api_alloc_as_if_client (mp_size);
	      clib_memcpy (mp_copy, mp, mp_size);
	      vl_api_send_msg (reg_prev, (u8 *) mp);
	      mp = mp_copy;
	    }
	  reg_prev = reg;
	}
    }
#if STATS_DEBUG > 0
  fformat (stdout, "%U\n", format_vnet_combined_counters, mp);
#endif

  if (reg_prev && vl_api_can_send_msg (reg_prev))
    {
      vl_api_send_msg (reg_prev, (u8 *) mp);
    }
  else
    {
      vl_msg_api_free (mp);
    }
}

static void
do_combined_interface_counters (stats_main_t * sm)
{
  vl_api_vnet_interface_combined_counters_t *mp = 0;
  vnet_interface_main_t *im = sm->interface_main;
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  svm_queue_t *q = shmem_hdr->vl_input_queue;
  vlib_combined_counter_main_t *cm;
  u32 items_this_message = 0;
  vlib_counter_t v, *vp = 0;
  int i, n_counts;

  vnet_interface_counter_lock (im);

  vec_foreach (cm, im->combined_sw_if_counters)
  {
    n_counts = vlib_combined_counter_n_counters (cm);
    for (i = 0; i < n_counts; i++)
      {
	if (mp == 0)
	  {
	    items_this_message = clib_min (COMBINED_COUNTER_BATCH_SIZE,
					   n_counts - i);

	    mp = vl_msg_api_alloc_as_if_client
	      (sizeof (*mp) + items_this_message * sizeof (v));
	    mp->_vl_msg_id = ntohs (VL_API_VNET_INTERFACE_COMBINED_COUNTERS);
	    mp->vnet_counter_type = cm - im->combined_sw_if_counters;
	    mp->first_sw_if_index = htonl (i);
	    mp->count = 0;
	    vp = (vlib_counter_t *) mp->data;
	  }
	vlib_get_combined_counter (cm, i, &v);
	clib_mem_unaligned (&vp->packets, u64)
	  = clib_host_to_net_u64 (v.packets);
	clib_mem_unaligned (&vp->bytes, u64) = clib_host_to_net_u64 (v.bytes);
	vp++;
	mp->count++;
	if (mp->count == items_this_message)
	  {
	    mp->count = htonl (items_this_message);
	    /* Send to the main thread... */
	    vl_msg_api_send_shmem (q, (u8 *) & mp);
	    mp = 0;
	  }
      }
    ASSERT (mp == 0);
  }
  vnet_interface_counter_unlock (im);
}

/**********************************
 * Per Interface Combined stats
 **********************************/

/* Request from client registering interfaces it wants */
static void
  vl_api_want_per_interface_combined_stats_t_handler
  (vl_api_want_per_interface_combined_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_per_interface_combined_stats_reply_t *rmp;
  vlib_combined_counter_main_t *cm;
  uword *p;
  i32 retval = 0;
  vl_api_registration_t *reg;
  int i;
  u32 swif;

  // Validate we have good sw_if_indexes before registering
  for (i = 0; i < mp->num; i++)
    {
      swif = mp->sw_ifs[i];

      /* Check its a real sw_if_index that the client is allowed to see */
      if (swif != ~0)
	{
	  if (pool_is_free_index (sm->interface_main->sw_interfaces, swif))
	    {
	      retval = VNET_API_ERROR_INVALID_SW_IF_INDEX;
	      goto reply;
	    }
	}
    }

  for (i = 0; i < mp->num; i++)
    {
      swif = mp->sw_ifs[i];

      rp.client_index = mp->client_index;
      rp.client_pid = mp->pid;
      handle_client_registration (&rp, IDX_PER_INTERFACE_COMBINED_COUNTERS,
				  swif, mp->enable_disable);
    }

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    {
      for (i = 0; i < mp->num; i++)
	{
	  swif = mp->sw_ifs[i];
	  sm->enable_poller =
	    clear_client_for_stat (IDX_PER_INTERFACE_COMBINED_COUNTERS, swif,
				   mp->client_index);
	}
      return;
    }

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_PER_INTERFACE_COMBINED_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}

/* Per Interface Combined distribution to client */
static void
do_combined_per_interface_counters (stats_main_t * sm)
{
  vl_api_vnet_per_interface_combined_counters_t *mp = 0;
  vnet_interface_main_t *im = sm->interface_main;
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  vl_api_registration_t *vl_reg;
  vlib_combined_counter_main_t *cm;
  /*
   * items_this_message will eventually be used to optimise the batching
   * of per client messages for each stat. For now setting this to 1 then
   * iterate. This will not affect API.
   *
   * FIXME instead of enqueueing here, this should be sent to a batch
   * storer for per-client transmission. Each "mp" sent would be a single entry
   * and if a client is listening to other sw_if_indexes for same, it would be
   * appended to that *mp
   */
  u32 items_this_message = 1;
  vnet_combined_counter_t *vp = 0;
  vlib_counter_t v;
  int i, j;
  u32 timestamp;
  vpe_client_stats_registration_t *reg;
  vpe_client_registration_t *client;
  u32 *sw_if_index = 0;

  /*
     FIXME(s):
     - capturing the timestamp of the counters "when VPP knew them" is important.
     Less so is that the timing of the delivery to the control plane be in the same
     timescale.

     i.e. As long as the control plane can delta messages from VPP and work out
     velocity etc based on the timestamp, it can do so in a more "batch mode".

     It would be beneficial to keep a "per-client" message queue, and then
     batch all the stat messages for a client into one message, with
     discrete timestamps.

     Given this particular API is for "per interface" one assumes that the scale
     is less than the ~0 case, which the prior API is suited for.
   */
  vnet_interface_counter_lock (im);

  timestamp = vlib_time_now (sm->vlib_main);

  vec_reset_length (sm->regs_tmp);

  /* *INDENT-OFF* */
  pool_foreach (reg,
                sm->stats_registrations[IDX_PER_INTERFACE_COMBINED_COUNTERS],
  ({
    vec_add1 (sm->regs_tmp, reg);
  }));
  /* *INDENT-ON* */

  for (i = 0; i < vec_len (sm->regs_tmp); i++)
    {
      reg = sm->regs_tmp[i];
      if (reg->item == ~0)
	{
	  vnet_interface_counter_unlock (im);
	  do_combined_interface_counters (sm);
	  vnet_interface_counter_lock (im);
	  continue;
	}
      vec_reset_length (sm->clients_tmp);

      /* *INDENT-OFF* */
      pool_foreach (client, reg->clients, ({
	vec_add1 (sm->clients_tmp, client);
      }));
      /* *INDENT-ON* */

      //FIXME - should be doing non-variant part of mp here and managing
      // any alloc per client in that vec_foreach
      for (j = 0; j < vec_len (sm->clients_tmp); j++)
	{
	  client = sm->clients_tmp[j];

	  vl_reg = vl_api_client_index_to_registration (client->client_index);

	  //Client may have disconnected abrubtly, clean up so we don't poll nothing.
	  if (!vl_reg)
	    {
	      sm->enable_poller =
		clear_client_for_stat (IDX_PER_INTERFACE_COMBINED_COUNTERS,
				       reg->item, client->client_index);
	      continue;
	    }

	  mp = vl_msg_api_alloc (sizeof (*mp) +
				 (items_this_message *
				  (sizeof (*vp) /* rx */ )));

	  // FIXME when optimising for items_this_message > 1 need to include a
	  // SIMPLE_INTERFACE_BATCH_SIZE check.
	  mp->_vl_msg_id =
	    ntohs (VL_API_VNET_PER_INTERFACE_COMBINED_COUNTERS);

	  mp->count = items_this_message;
	  mp->timestamp = timestamp;
	  vp = (vnet_combined_counter_t *) mp->data;

	  vp->sw_if_index = htonl (reg->item);

	  cm = im->combined_sw_if_counters + VNET_INTERFACE_COUNTER_RX;
	  vlib_get_combined_counter (cm, reg->item, &v);
	  clib_mem_unaligned (&vp->rx_packets, u64)
	    = clib_host_to_net_u64 (v.packets);
	  clib_mem_unaligned (&vp->rx_bytes, u64) =
	    clib_host_to_net_u64 (v.bytes);


	  /* TX vlib_counter_t packets/bytes */
	  cm = im->combined_sw_if_counters + VNET_INTERFACE_COUNTER_TX;
	  vlib_get_combined_counter (cm, reg->item, &v);
	  clib_mem_unaligned (&vp->tx_packets, u64)
	    = clib_host_to_net_u64 (v.packets);
	  clib_mem_unaligned (&vp->tx_bytes, u64) =
	    clib_host_to_net_u64 (v.bytes);

	  vl_api_send_msg (vl_reg, (u8 *) mp);
	}
    }

  vnet_interface_counter_unlock (im);
}

/**********************************
 * Per Interface simple stats
 **********************************/

/* Request from client registering interfaces it wants */
static void
  vl_api_want_per_interface_simple_stats_t_handler
  (vl_api_want_per_interface_simple_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_per_interface_simple_stats_reply_t *rmp;
  vlib_simple_counter_main_t *cm;
  uword *p;
  i32 retval = 0;
  vl_api_registration_t *reg;
  int i;
  u32 swif;

  for (i = 0; i < mp->num; i++)
    {
      swif = mp->sw_ifs[i];

      /* Check its a real sw_if_index that the client is allowed to see */
      if (swif != ~0)
	{
	  if (pool_is_free_index (sm->interface_main->sw_interfaces, swif))
	    {
	      retval = VNET_API_ERROR_INVALID_SW_IF_INDEX;
	      goto reply;
	    }
	}
    }

  for (i = 0; i < mp->num; i++)
    {
      swif = mp->sw_ifs[i];

      rp.client_index = mp->client_index;
      rp.client_pid = mp->pid;
      handle_client_registration (&rp, IDX_PER_INTERFACE_SIMPLE_COUNTERS,
				  swif, mp->enable_disable);
    }

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);

  /* Client may have disconnected abruptly, clean up */
  if (!reg)
    {
      for (i = 0; i < mp->num; i++)
	{
	  swif = mp->sw_ifs[i];
	  sm->enable_poller =
	    clear_client_for_stat (IDX_PER_INTERFACE_SIMPLE_COUNTERS, swif,
				   mp->client_index);
	}

      return;
    }


  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_PER_INTERFACE_SIMPLE_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}

/* Per Interface Simple distribution to client */
static void
do_simple_per_interface_counters (stats_main_t * sm)
{
  vl_api_vnet_per_interface_simple_counters_t *mp = 0;
  vnet_interface_main_t *im = sm->interface_main;
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  vl_api_registration_t *vl_reg;
  vlib_simple_counter_main_t *cm;
  /*
   * items_this_message will eventually be used to optimise the batching
   * of per client messages for each stat. For now setting this to 1 then
   * iterate. This will not affect API.
   *
   * FIXME instead of enqueueing here, this should be sent to a batch
   * storer for per-client transmission. Each "mp" sent would be a single entry
   * and if a client is listening to other sw_if_indexes for same, it would be
   * appended to that *mp
   */
  u32 items_this_message = 1;
  int i, j, size;
  vpe_client_stats_registration_t *reg;
  vpe_client_registration_t *client;
  u32 timestamp;
  u32 count;
  vnet_simple_counter_t *vp = 0;
  counter_t v;

  /*
     FIXME(s):
     - capturing the timestamp of the counters "when VPP knew them" is important.
     Less so is that the timing of the delivery to the control plane be in the same
     timescale.

     i.e. As long as the control plane can delta messages from VPP and work out
     velocity etc based on the timestamp, it can do so in a more "batch mode".

     It would be beneficial to keep a "per-client" message queue, and then
     batch all the stat messages for a client into one message, with
     discrete timestamps.

     Given this particular API is for "per interface" one assumes that the scale
     is less than the ~0 case, which the prior API is suited for.
   */
  vnet_interface_counter_lock (im);

  timestamp = vlib_time_now (sm->vlib_main);

  vec_reset_length (sm->regs_tmp);

  /* *INDENT-OFF* */
  pool_foreach (reg,
                sm->stats_registrations[IDX_PER_INTERFACE_SIMPLE_COUNTERS], ({
    vec_add1 (sm->regs_tmp, reg);
  }));
  /* *INDENT-ON* */

  for (i = 0; i < vec_len (sm->regs_tmp); i++)
    {
      reg = sm->regs_tmp[i];
      if (reg->item == ~0)
	{
	  vnet_interface_counter_unlock (im);
	  do_simple_interface_counters (sm);
	  vnet_interface_counter_lock (im);
	  continue;
	}
      vec_reset_length (sm->clients_tmp);

      /* *INDENT-OFF* */
      pool_foreach (client, reg->clients, ({
	vec_add1 (sm->clients_tmp, client);
      }));
      /* *INDENT-ON* */

      //FIXME - should be doing non-variant part of mp here and managing
      // any alloc per client in that vec_foreach
      for (j = 0; j < vec_len (sm->clients_tmp); j++)
	{
	  client = sm->clients_tmp[j];
	  vl_reg = vl_api_client_index_to_registration (client->client_index);

	  /* Client may have disconnected abrubtly, clean up */
	  if (!vl_reg)
	    {
	      sm->enable_poller =
		clear_client_for_stat (IDX_PER_INTERFACE_SIMPLE_COUNTERS,
				       reg->item, client->client_index);
	      continue;
	    }

	  size = (sizeof (*mp) + (items_this_message * (sizeof (u64) * 10)));
	  mp = vl_msg_api_alloc (size);
	  // FIXME when optimising for items_this_message > 1 need to include a
	  // SIMPLE_INTERFACE_BATCH_SIZE check.
	  mp->_vl_msg_id = ntohs (VL_API_VNET_PER_INTERFACE_SIMPLE_COUNTERS);

	  mp->count = items_this_message;
	  mp->timestamp = timestamp;
	  vp = (vnet_simple_counter_t *) mp->data;

	  vp->sw_if_index = htonl (reg->item);

	  //FIXME will be simpler with a preprocessor macro
	  // VNET_INTERFACE_COUNTER_DROP
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_DROP;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->drop, u64) = clib_host_to_net_u64 (v);

	  // VNET_INTERFACE_COUNTER_PUNT
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_PUNT;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->punt, u64) = clib_host_to_net_u64 (v);

	  // VNET_INTERFACE_COUNTER_IP4
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_IP4;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->rx_ip4, u64) = clib_host_to_net_u64 (v);

	  //VNET_INTERFACE_COUNTER_IP6
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_IP6;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->rx_ip6, u64) = clib_host_to_net_u64 (v);

	  //VNET_INTERFACE_COUNTER_RX_NO_BUF
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_RX_NO_BUF;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->rx_no_buffer, u64) =
	    clib_host_to_net_u64 (v);

	  //VNET_INTERFACE_COUNTER_RX_MISS
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_RX_MISS;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->rx_miss, u64) = clib_host_to_net_u64 (v);

	  //VNET_INTERFACE_COUNTER_RX_ERROR
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_RX_ERROR;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->rx_error, u64) = clib_host_to_net_u64 (v);

	  //VNET_INTERFACE_COUNTER_TX_ERROR
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_TX_ERROR;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->tx_error, u64) = clib_host_to_net_u64 (v);

	  //VNET_INTERFACE_COUNTER_MPLS
	  cm = im->sw_if_counters + VNET_INTERFACE_COUNTER_MPLS;
	  v = vlib_get_simple_counter (cm, reg->item);
	  clib_mem_unaligned (&vp->rx_mpls, u64) = clib_host_to_net_u64 (v);

	  vl_api_send_msg (vl_reg, (u8 *) mp);
	}
    }

  vnet_interface_counter_unlock (im);
}

/**********************************
 * Per FIB IP4 stats
 **********************************/

static void
ip46_fib_stats_delay (stats_main_t * sm, u32 sec, u32 nsec)
{
  struct timespec _req, *req = &_req;
  struct timespec _rem, *rem = &_rem;

  req->tv_sec = sec;
  req->tv_nsec = nsec;
  while (1)
    {
      if (nanosleep (req, rem) == 0)
	break;
      *req = *rem;
      if (errno == EINTR)
	continue;
      clib_unix_warning ("nanosleep");
      break;
    }
}

/**
 * @brief The context passed when collecting adjacency counters
 */
typedef struct ip4_nbr_stats_ctx_t_
{
  /**
   * The SW IF index all these adjs belong to
   */
  u32 sw_if_index;

  /**
   * A vector of ip4 nbr counters
   */
  vl_api_ip4_nbr_counter_t *counters;
} ip4_nbr_stats_ctx_t;

static adj_walk_rc_t
ip4_nbr_stats_cb (adj_index_t ai, void *arg)
{
  vl_api_ip4_nbr_counter_t *vl_counter;
  vlib_counter_t adj_counter;
  ip4_nbr_stats_ctx_t *ctx;
  ip_adjacency_t *adj;

  ctx = arg;
  vlib_get_combined_counter (&adjacency_counters, ai, &adj_counter);

  if (0 != adj_counter.packets)
    {
      vec_add2 (ctx->counters, vl_counter, 1);
      adj = adj_get (ai);

      vl_counter->packets = clib_host_to_net_u64 (adj_counter.packets);
      vl_counter->bytes = clib_host_to_net_u64 (adj_counter.bytes);
      vl_counter->address = adj->sub_type.nbr.next_hop.ip4.as_u32;
      vl_counter->link_type = adj->ia_link;
    }
  return (ADJ_WALK_RC_CONTINUE);
}

#define MIN(x,y) (((x)<(y))?(x):(y))

static void
ip4_nbr_ship (stats_main_t * sm, ip4_nbr_stats_ctx_t * ctx)
{
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  svm_queue_t *q = shmem_hdr->vl_input_queue;
  vl_api_vnet_ip4_nbr_counters_t *mp = 0;
  int first = 0;

  /*
   * If the walk context has counters, which may be left over from the last
   * suspend, then we continue from there.
   */
  while (0 != vec_len (ctx->counters))
    {
      u32 n_items = MIN (vec_len (ctx->counters),
			 IP4_FIB_COUNTER_BATCH_SIZE);
      u8 pause = 0;

      dslock (sm, 0 /* release hint */ , 1 /* tag */ );

      mp = vl_msg_api_alloc_as_if_client (sizeof (*mp) +
					  (n_items *
					   sizeof
					   (vl_api_ip4_nbr_counter_t)));
      mp->_vl_msg_id = ntohs (VL_API_VNET_IP4_NBR_COUNTERS);
      mp->count = ntohl (n_items);
      mp->sw_if_index = ntohl (ctx->sw_if_index);
      mp->begin = first;
      first = 0;

      /*
       * copy the counters from the back of the context, then we can easily
       * 'erase' them by resetting the vector length.
       * The order we push the stats to the caller is not important.
       */
      clib_memcpy (mp->c,
		   &ctx->counters[vec_len (ctx->counters) - n_items],
		   n_items * sizeof (*ctx->counters));

      _vec_len (ctx->counters) = vec_len (ctx->counters) - n_items;

      /*
       * send to the shm q
       */
      svm_queue_lock (q);
      pause = svm_queue_is_full (q);

      vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
      svm_queue_unlock (q);
      dsunlock (sm);

      if (pause)
	ip46_fib_stats_delay (sm, 0 /* sec */ ,
			      STATS_RELEASE_DELAY_NS);
    }
}

static void
do_ip4_nbr_counters (stats_main_t * sm)
{
  vnet_main_t *vnm = vnet_get_main ();
  vnet_interface_main_t *im = &vnm->interface_main;
  vnet_sw_interface_t *si;

  ip4_nbr_stats_ctx_t ctx = {
    .sw_if_index = 0,
    .counters = NULL,
  };

  /* *INDENT-OFF* */
  pool_foreach (si, im->sw_interfaces,
  ({
    /*
     * update the interface we are now concerned with
     */
    ctx.sw_if_index = si->sw_if_index;

    /*
     * we are about to walk another interface, so we shouldn't have any pending
     * stats to export.
     */
    ASSERT(ctx.counters == NULL);

    /*
     * visit each neighbour adjacency on the interface and collect
     * its current stats.
     * Because we hold the lock the walk is synchronous, so safe to routing
     * updates. It's limited in work by the number of adjacenies on an
     * interface, which is typically not huge.
     */
    dslock (sm, 0 /* release hint */ , 1 /* tag */ );
    adj_nbr_walk (si->sw_if_index,
                  FIB_PROTOCOL_IP4,
                  ip4_nbr_stats_cb,
                  &ctx);
    dsunlock (sm);

    /*
     * if this interface has some adjacencies with counters then ship them,
     * else continue to the next interface.
     */
    if (NULL != ctx.counters)
      {
        ip4_nbr_ship(sm, &ctx);
      }
  }));
  /* *INDENT-OFF* */
}

/**
 * @brief The context passed when collecting adjacency counters
 */
typedef struct ip6_nbr_stats_ctx_t_
{
  /**
   * The SW IF index all these adjs belong to
   */
  u32 sw_if_index;

  /**
   * A vector of ip6 nbr counters
   */
  vl_api_ip6_nbr_counter_t *counters;
} ip6_nbr_stats_ctx_t;

static adj_walk_rc_t
ip6_nbr_stats_cb (adj_index_t ai,
                  void *arg)
{
  vl_api_ip6_nbr_counter_t *vl_counter;
  vlib_counter_t adj_counter;
  ip6_nbr_stats_ctx_t *ctx;
  ip_adjacency_t *adj;

  ctx = arg;
  vlib_get_combined_counter(&adjacency_counters, ai, &adj_counter);

  if (0 != adj_counter.packets)
    {
      vec_add2(ctx->counters, vl_counter, 1);
      adj = adj_get(ai);

      vl_counter->packets = clib_host_to_net_u64(adj_counter.packets);
      vl_counter->bytes   = clib_host_to_net_u64(adj_counter.bytes);
      vl_counter->address[0] = adj->sub_type.nbr.next_hop.ip6.as_u64[0];
      vl_counter->address[1] = adj->sub_type.nbr.next_hop.ip6.as_u64[1];
      vl_counter->link_type = adj->ia_link;
    }
  return (ADJ_WALK_RC_CONTINUE);
}

#define MIN(x,y) (((x)<(y))?(x):(y))

static void
ip6_nbr_ship (stats_main_t * sm,
              ip6_nbr_stats_ctx_t *ctx)
{
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  svm_queue_t *q = shmem_hdr->vl_input_queue;
  vl_api_vnet_ip6_nbr_counters_t *mp = 0;
  int first = 0;

  /*
   * If the walk context has counters, which may be left over from the last
   * suspend, then we continue from there.
   */
  while (0 != vec_len(ctx->counters))
    {
      u32 n_items = MIN (vec_len (ctx->counters),
			 IP6_FIB_COUNTER_BATCH_SIZE);
      u8 pause = 0;

      dslock (sm, 0 /* release hint */ , 1 /* tag */ );

      mp = vl_msg_api_alloc_as_if_client (sizeof (*mp) +
					  (n_items *
					   sizeof
					   (vl_api_ip6_nbr_counter_t)));
      mp->_vl_msg_id = ntohs (VL_API_VNET_IP6_NBR_COUNTERS);
      mp->count = ntohl (n_items);
      mp->sw_if_index = ntohl (ctx->sw_if_index);
      mp->begin = first;
      first = 0;

      /*
       * copy the counters from the back of the context, then we can easily
       * 'erase' them by resetting the vector length.
       * The order we push the stats to the caller is not important.
       */
      clib_memcpy (mp->c,
		   &ctx->counters[vec_len (ctx->counters) - n_items],
		   n_items * sizeof (*ctx->counters));

      _vec_len (ctx->counters) = vec_len (ctx->counters) - n_items;

      /*
       * send to the shm q
       */
      svm_queue_lock (q);
      pause = svm_queue_is_full (q);

      vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
      svm_queue_unlock (q);
      dsunlock (sm);

      if (pause)
        ip46_fib_stats_delay (sm, 0 /* sec */ ,
                              STATS_RELEASE_DELAY_NS);
    }
}

static void
do_ip6_nbr_counters (stats_main_t * sm)
{
  vnet_main_t *vnm = vnet_get_main ();
  vnet_interface_main_t *im = &vnm->interface_main;
  vnet_sw_interface_t *si;

  ip6_nbr_stats_ctx_t ctx = {
    .sw_if_index = 0,
    .counters = NULL,
  };

  /* *INDENT-OFF* */
  pool_foreach (si, im->sw_interfaces,
  ({
    /*
     * update the interface we are now concerned with
     */
    ctx.sw_if_index = si->sw_if_index;

    /*
     * we are about to walk another interface, so we shouldn't have any pending
     * stats to export.
     */
    ASSERT(ctx.counters == NULL);

    /*
     * visit each neighbour adjacency on the interface and collect
     * its current stats.
     * Because we hold the lock the walk is synchronous, so safe to routing
     * updates. It's limited in work by the number of adjacenies on an
     * interface, which is typically not huge.
     */
    dslock (sm, 0 /* release hint */ , 1 /* tag */ );
    adj_nbr_walk (si->sw_if_index,
                  FIB_PROTOCOL_IP6,
                  ip6_nbr_stats_cb,
                  &ctx);
    dsunlock (sm);

    /*
     * if this interface has some adjacencies with counters then ship them,
     * else continue to the next interface.
     */
    if (NULL != ctx.counters)
      {
        ip6_nbr_ship(sm, &ctx);
      }
  }));
  /* *INDENT-OFF* */
}

static void
do_ip4_fib_counters (stats_main_t * sm)
{
  ip4_main_t *im4 = &ip4_main;
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  svm_queue_t *q = shmem_hdr->vl_input_queue;
  ip4_route_t *r;
  fib_table_t *fib;
  ip4_fib_t *v4_fib;
  do_ip46_fibs_t *do_fibs;
  vl_api_vnet_ip4_fib_counters_t *mp = 0;
  u32 items_this_message;
  vl_api_ip4_fib_counter_t *ctrp = 0;
  u32 start_at_fib_index = 0;
  int i, j, k;

  do_fibs = &sm->do_ip46_fibs;

again:
  vec_reset_length (do_fibs->fibs);
  /* *INDENT-OFF* */
  pool_foreach (fib, im4->fibs,
                ({vec_add1(do_fibs->fibs,fib);}));

  /* *INDENT-ON* */

  for (j = 0; j < vec_len (do_fibs->fibs); j++)
    {
      fib = do_fibs->fibs[j];
      /* We may have bailed out due to control-plane activity */
      while ((fib - im4->fibs) < start_at_fib_index)
	continue;

      v4_fib = pool_elt_at_index (im4->v4_fibs, fib->ft_index);

      if (mp == 0)
	{
	  items_this_message = IP4_FIB_COUNTER_BATCH_SIZE;
	  mp = vl_msg_api_alloc_as_if_client
	    (sizeof (*mp) +
	     items_this_message * sizeof (vl_api_ip4_fib_counter_t));
	  mp->_vl_msg_id = ntohs (VL_API_VNET_IP4_FIB_COUNTERS);
	  mp->count = 0;
	  mp->vrf_id = ntohl (fib->ft_table_id);
	  ctrp = (vl_api_ip4_fib_counter_t *) mp->c;
	}
      else
	{
	  /* happens if the last FIB was empty... */
	  ASSERT (mp->count == 0);
	  mp->vrf_id = ntohl (fib->ft_table_id);
	}

      dslock (sm, 0 /* release hint */ , 1 /* tag */ );

      vec_reset_length (do_fibs->ip4routes);
      vec_reset_length (do_fibs->results);

      for (i = 0; i < ARRAY_LEN (v4_fib->fib_entry_by_dst_address); i++)
	{
	  uword *hash = v4_fib->fib_entry_by_dst_address[i];
	  hash_pair_t *p;
	  ip4_route_t x;

	  vec_reset_length (do_fibs->pvec);

	  x.address_length = i;

	  hash_foreach_pair (p, hash, (
					{
					vec_add1 (do_fibs->pvec, p);}
			     ));
	  for (k = 0; k < vec_len (do_fibs->pvec); k++)
	    {
	      p = do_fibs->pvec[k];
	      x.address.data_u32 = p->key;
	      x.index = p->value[0];

	      vec_add1 (do_fibs->ip4routes, x);
	      if (sm->data_structure_lock->release_hint)
		{
		  start_at_fib_index = fib - im4->fibs;
		  dsunlock (sm);
		  ip46_fib_stats_delay (sm, 0 /* sec */ ,
					STATS_RELEASE_DELAY_NS);
		  mp->count = 0;
		  ctrp = (vl_api_ip4_fib_counter_t *) mp->c;
		  goto again;
		}
	    }
	}

      vec_foreach (r, do_fibs->ip4routes)
      {
	vlib_counter_t c;
	const dpo_id_t *dpo_id;
	u32 index;

	dpo_id = fib_entry_contribute_ip_forwarding (r->index);
	index = (u32) dpo_id->dpoi_index;

	vlib_get_combined_counter (&load_balance_main.lbm_to_counters,
				   index, &c);
	/*
	 * If it has actually
	 * seen at least one packet, send it.
	 */
	if (c.packets > 0)
	  {

	    /* already in net byte order */
	    ctrp->address = r->address.as_u32;
	    ctrp->address_length = r->address_length;
	    ctrp->packets = clib_host_to_net_u64 (c.packets);
	    ctrp->bytes = clib_host_to_net_u64 (c.bytes);
	    mp->count++;
	    ctrp++;

	    if (mp->count == items_this_message)
	      {
		mp->count = htonl (items_this_message);
		/*
		 * If the main thread's input queue is stuffed,
		 * drop the data structure lock (which the main thread
		 * may want), and take a pause.
		 */
		svm_queue_lock (q);
		if (svm_queue_is_full (q))
		  {
		    dsunlock (sm);
		    vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
		    svm_queue_unlock (q);
		    mp = 0;
		    ip46_fib_stats_delay (sm, 0 /* sec */ ,
					  STATS_RELEASE_DELAY_NS);
		    goto again;
		  }
		vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
		svm_queue_unlock (q);

		items_this_message = IP4_FIB_COUNTER_BATCH_SIZE;
		mp = vl_msg_api_alloc_as_if_client
		  (sizeof (*mp) +
		   items_this_message * sizeof (vl_api_ip4_fib_counter_t));
		mp->_vl_msg_id = ntohs (VL_API_VNET_IP4_FIB_COUNTERS);
		mp->count = 0;
		mp->vrf_id = ntohl (fib->ft_table_id);
		ctrp = (vl_api_ip4_fib_counter_t *) mp->c;
	      }
	  }			/* for each (mp or single) adj */
	if (sm->data_structure_lock->release_hint)
	  {
	    start_at_fib_index = fib - im4->fibs;
	    dsunlock (sm);
	    ip46_fib_stats_delay (sm, 0 /* sec */ , STATS_RELEASE_DELAY_NS);
	    mp->count = 0;
	    ctrp = (vl_api_ip4_fib_counter_t *) mp->c;
	    goto again;
	  }
      }				/* vec_foreach (routes) */

      dsunlock (sm);

      /* Flush any data from this fib */
      if (mp->count)
	{
	  mp->count = htonl (mp->count);
	  vl_msg_api_send_shmem (q, (u8 *) & mp);
	  mp = 0;
	}
    }

  /* If e.g. the last FIB had no reportable routes, free the buffer */
  if (mp)
    vl_msg_api_free (mp);
}

static int
mfib_table_stats_walk_cb (fib_node_index_t fei, void *ctx)
{
  stats_main_t *sm = ctx;
  do_ip46_fibs_t *do_fibs;
  mfib_entry_t *entry;

  do_fibs = &sm->do_ip46_fibs;
  entry = mfib_entry_get (fei);

  vec_add1 (do_fibs->mroutes, entry->mfe_prefix);

  return (1);
}

static void
do_ip4_mfib_counters (stats_main_t * sm)
{
  ip4_main_t *im4 = &ip4_main;
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  svm_queue_t *q = shmem_hdr->vl_input_queue;
  mfib_prefix_t *pfx;
  mfib_table_t *mfib;
  do_ip46_fibs_t *do_fibs;
  vl_api_vnet_ip4_mfib_counters_t *mp = 0;
  u32 items_this_message;
  vl_api_ip4_mfib_counter_t *ctrp = 0;
  u32 start_at_mfib_index = 0;
  int i, j, k;

  do_fibs = &sm->do_ip46_fibs;

  vec_reset_length (do_fibs->mfibs);
  /* *INDENT-OFF* */
  pool_foreach (mfib, im4->mfibs, ({vec_add1(do_fibs->mfibs, mfib);}));
  /* *INDENT-ON* */

  for (j = 0; j < vec_len (do_fibs->mfibs); j++)
    {
      mfib = do_fibs->mfibs[j];
      /* We may have bailed out due to control-plane activity */
      while ((mfib - im4->mfibs) < start_at_mfib_index)
	continue;

      if (mp == 0)
	{
	  items_this_message = IP4_MFIB_COUNTER_BATCH_SIZE;
	  mp = vl_msg_api_alloc_as_if_client
	    (sizeof (*mp) +
	     items_this_message * sizeof (vl_api_ip4_mfib_counter_t));
	  mp->_vl_msg_id = ntohs (VL_API_VNET_IP4_MFIB_COUNTERS);
	  mp->count = 0;
	  mp->vrf_id = ntohl (mfib->mft_table_id);
	  ctrp = (vl_api_ip4_mfib_counter_t *) mp->c;
	}
      else
	{
	  /* happens if the last MFIB was empty... */
	  ASSERT (mp->count == 0);
	  mp->vrf_id = ntohl (mfib->mft_table_id);
	}

      vec_reset_length (do_fibs->mroutes);

      /*
       * walk the table with table updates blocked
       */
      dslock (sm, 0 /* release hint */ , 1 /* tag */ );

      mfib_table_walk (mfib->mft_index,
		       FIB_PROTOCOL_IP4, mfib_table_stats_walk_cb, sm);
      dsunlock (sm);

      vec_foreach (pfx, do_fibs->mroutes)
      {
	const dpo_id_t *dpo_id;
	fib_node_index_t mfei;
	vlib_counter_t c;
	u32 index;

	/*
	 * re-lookup the entry, since we suspend during the collection
	 */
	mfei = mfib_table_lookup (mfib->mft_index, pfx);

	if (FIB_NODE_INDEX_INVALID == mfei)
	  continue;

	dpo_id = mfib_entry_contribute_ip_forwarding (mfei);
	index = (u32) dpo_id->dpoi_index;

	vlib_get_combined_counter (&replicate_main.repm_counters,
				   dpo_id->dpoi_index, &c);
	/*
	 * If it has seen at least one packet, send it.
	 */
	if (c.packets > 0)
	  {
	    /* already in net byte order */
	    memcpy (ctrp->group, &pfx->fp_grp_addr.ip4, 4);
	    memcpy (ctrp->source, &pfx->fp_src_addr.ip4, 4);
	    ctrp->group_length = pfx->fp_len;
	    ctrp->packets = clib_host_to_net_u64 (c.packets);
	    ctrp->bytes = clib_host_to_net_u64 (c.bytes);
	    mp->count++;
	    ctrp++;

	    if (mp->count == items_this_message)
	      {
		mp->count = htonl (items_this_message);
		/*
		 * If the main thread's input queue is stuffed,
		 * drop the data structure lock (which the main thread
		 * may want), and take a pause.
		 */
		svm_queue_lock (q);

		while (svm_queue_is_full (q))
		  {
		    svm_queue_unlock (q);
		    ip46_fib_stats_delay (sm, 0 /* sec */ ,
					  STATS_RELEASE_DELAY_NS);
		    svm_queue_lock (q);
		  }
		vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
		svm_queue_unlock (q);

		items_this_message = IP4_MFIB_COUNTER_BATCH_SIZE;
		mp = vl_msg_api_alloc_as_if_client
		  (sizeof (*mp) +
		   items_this_message * sizeof (vl_api_ip4_mfib_counter_t));
		mp->_vl_msg_id = ntohs (VL_API_VNET_IP4_MFIB_COUNTERS);
		mp->count = 0;
		mp->vrf_id = ntohl (mfib->mft_table_id);
		ctrp = (vl_api_ip4_mfib_counter_t *) mp->c;
	      }
	  }
      }

      /* Flush any data from this mfib */
      if (mp->count)
	{
	  mp->count = htonl (mp->count);
	  vl_msg_api_send_shmem (q, (u8 *) & mp);
	  mp = 0;
	}
    }

  /* If e.g. the last FIB had no reportable routes, free the buffer */
  if (mp)
    vl_msg_api_free (mp);
}

static void
do_ip6_mfib_counters (stats_main_t * sm)
{
  ip6_main_t *im6 = &ip6_main;
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  svm_queue_t *q = shmem_hdr->vl_input_queue;
  mfib_prefix_t *pfx;
  mfib_table_t *mfib;
  do_ip46_fibs_t *do_fibs;
  vl_api_vnet_ip6_mfib_counters_t *mp = 0;
  u32 items_this_message;
  vl_api_ip6_mfib_counter_t *ctrp = 0;
  u32 start_at_mfib_index = 0;
  int i, j, k;

  do_fibs = &sm->do_ip46_fibs;

  vec_reset_length (do_fibs->mfibs);
  /* *INDENT-OFF* */
  pool_foreach (mfib, im6->mfibs, ({vec_add1(do_fibs->mfibs, mfib);}));
  /* *INDENT-ON* */

  for (j = 0; j < vec_len (do_fibs->mfibs); j++)
    {
      mfib = do_fibs->mfibs[j];
      /* We may have bailed out due to control-plane activity */
      while ((mfib - im6->mfibs) < start_at_mfib_index)
	continue;

      if (mp == 0)
	{
	  items_this_message = IP6_MFIB_COUNTER_BATCH_SIZE;
	  mp = vl_msg_api_alloc_as_if_client
	    (sizeof (*mp) +
	     items_this_message * sizeof (vl_api_ip6_mfib_counter_t));
	  mp->_vl_msg_id = ntohs (VL_API_VNET_IP6_MFIB_COUNTERS);
	  mp->count = 0;
	  mp->vrf_id = ntohl (mfib->mft_table_id);
	  ctrp = (vl_api_ip6_mfib_counter_t *) mp->c;
	}
      else
	{
	  /* happens if the last MFIB was empty... */
	  ASSERT (mp->count == 0);
	  mp->vrf_id = ntohl (mfib->mft_table_id);
	}

      vec_reset_length (do_fibs->mroutes);

      /*
       * walk the table with table updates blocked
       */
      dslock (sm, 0 /* release hint */ , 1 /* tag */ );

      mfib_table_walk (mfib->mft_index,
		       FIB_PROTOCOL_IP6, mfib_table_stats_walk_cb, sm);
      dsunlock (sm);

      vec_foreach (pfx, do_fibs->mroutes)
      {
	const dpo_id_t *dpo_id;
	fib_node_index_t mfei;
	vlib_counter_t c;
	u32 index;

	/*
	 * re-lookup the entry, since we suspend during the collection
	 */
	mfei = mfib_table_lookup (mfib->mft_index, pfx);

	if (FIB_NODE_INDEX_INVALID == mfei)
	  continue;

	dpo_id = mfib_entry_contribute_ip_forwarding (mfei);
	index = (u32) dpo_id->dpoi_index;

	vlib_get_combined_counter (&replicate_main.repm_counters,
				   dpo_id->dpoi_index, &c);
	/*
	 * If it has seen at least one packet, send it.
	 */
	if (c.packets > 0)
	  {
	    /* already in net byte order */
	    memcpy (ctrp->group, &pfx->fp_grp_addr.ip6, 16);
	    memcpy (ctrp->source, &pfx->fp_src_addr.ip6, 16);
	    ctrp->group_length = pfx->fp_len;
	    ctrp->packets = clib_host_to_net_u64 (c.packets);
	    ctrp->bytes = clib_host_to_net_u64 (c.bytes);
	    mp->count++;
	    ctrp++;

	    if (mp->count == items_this_message)
	      {
		mp->count = htonl (items_this_message);
		/*
		 * If the main thread's input queue is stuffed,
		 * drop the data structure lock (which the main thread
		 * may want), and take a pause.
		 */
		svm_queue_lock (q);

		while (svm_queue_is_full (q))
		  {
		    svm_queue_unlock (q);
		    ip46_fib_stats_delay (sm, 0 /* sec */ ,
					  STATS_RELEASE_DELAY_NS);
		    svm_queue_lock (q);
		  }
		vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
		svm_queue_unlock (q);

		items_this_message = IP6_MFIB_COUNTER_BATCH_SIZE;
		mp = vl_msg_api_alloc_as_if_client
		  (sizeof (*mp) +
		   items_this_message * sizeof (vl_api_ip6_mfib_counter_t));
		mp->_vl_msg_id = ntohs (VL_API_VNET_IP6_MFIB_COUNTERS);
		mp->count = 0;
		mp->vrf_id = ntohl (mfib->mft_table_id);
		ctrp = (vl_api_ip6_mfib_counter_t *) mp->c;
	      }
	  }
      }

      /* Flush any data from this mfib */
      if (mp->count)
	{
	  mp->count = htonl (mp->count);
	  vl_msg_api_send_shmem (q, (u8 *) & mp);
	  mp = 0;
	}
    }

  /* If e.g. the last FIB had no reportable routes, free the buffer */
  if (mp)
    vl_msg_api_free (mp);
}

typedef struct
{
  u32 fib_index;
  ip6_route_t **routep;
  stats_main_t *sm;
} add_routes_in_fib_arg_t;

static void
add_routes_in_fib (BVT (clib_bihash_kv) * kvp, void *arg)
{
  add_routes_in_fib_arg_t *ap = arg;
  stats_main_t *sm = ap->sm;

  if (sm->data_structure_lock->release_hint)
    clib_longjmp (&sm->jmp_buf, 1);

  if (kvp->key[2] >> 32 == ap->fib_index)
    {
      ip6_address_t *addr;
      ip6_route_t *r;
      addr = (ip6_address_t *) kvp;
      vec_add2 (*ap->routep, r, 1);
      r->address = addr[0];
      r->address_length = kvp->key[2] & 0xFF;
      r->index = kvp->value;
    }
}

static void
do_ip6_fib_counters (stats_main_t * sm)
{
  ip6_main_t *im6 = &ip6_main;
  api_main_t *am = sm->api_main;
  vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
  svm_queue_t *q = shmem_hdr->vl_input_queue;
  ip6_route_t *r;
  fib_table_t *fib;
  do_ip46_fibs_t *do_fibs;
  vl_api_vnet_ip6_fib_counters_t *mp = 0;
  u32 items_this_message;
  vl_api_ip6_fib_counter_t *ctrp = 0;
  u32 start_at_fib_index = 0;
  BVT (clib_bihash) * h = &im6->ip6_table[IP6_FIB_TABLE_FWDING].ip6_hash;
  add_routes_in_fib_arg_t _a, *a = &_a;
  int i;

  do_fibs = &sm->do_ip46_fibs;
again:
  vec_reset_length (do_fibs->fibs);
  /* *INDENT-OFF* */
  pool_foreach (fib, im6->fibs,
                ({vec_add1(do_fibs->fibs,fib);}));
  /* *INDENT-ON* */


  for (i = 0; i < vec_len (do_fibs->fibs); i++)
    {
      fib = do_fibs->fibs[i];
      /* We may have bailed out due to control-plane activity */
      while ((fib - im6->fibs) < start_at_fib_index)
	continue;

      if (mp == 0)
	{
	  items_this_message = IP6_FIB_COUNTER_BATCH_SIZE;
	  mp = vl_msg_api_alloc_as_if_client
	    (sizeof (*mp) +
	     items_this_message * sizeof (vl_api_ip6_fib_counter_t));
	  mp->_vl_msg_id = ntohs (VL_API_VNET_IP6_FIB_COUNTERS);
	  mp->count = 0;
	  mp->vrf_id = ntohl (fib->ft_table_id);
	  ctrp = (vl_api_ip6_fib_counter_t *) mp->c;
	}

      dslock (sm, 0 /* release hint */ , 1 /* tag */ );

      vec_reset_length (do_fibs->ip6routes);
      vec_reset_length (do_fibs->results);

      a->fib_index = fib - im6->fibs;
      a->routep = &do_fibs->ip6routes;
      a->sm = sm;

      if (clib_setjmp (&sm->jmp_buf, 0) == 0)
	{
	  start_at_fib_index = fib - im6->fibs;
	  BV (clib_bihash_foreach_key_value_pair) (h, add_routes_in_fib, a);
	}
      else
	{
	  dsunlock (sm);
	  ip46_fib_stats_delay (sm, 0 /* sec */ ,
				STATS_RELEASE_DELAY_NS);
	  mp->count = 0;
	  ctrp = (vl_api_ip6_fib_counter_t *) mp->c;
	  goto again;
	}

      vec_foreach (r, do_fibs->ip6routes)
      {
	vlib_counter_t c;

	vlib_get_combined_counter (&load_balance_main.lbm_to_counters,
				   r->index, &c);
	/*
	 * If it has actually
	 * seen at least one packet, send it.
	 */
	if (c.packets > 0)
	  {
	    /* already in net byte order */
	    ctrp->address[0] = r->address.as_u64[0];
	    ctrp->address[1] = r->address.as_u64[1];
	    ctrp->address_length = (u8) r->address_length;
	    ctrp->packets = clib_host_to_net_u64 (c.packets);
	    ctrp->bytes = clib_host_to_net_u64 (c.bytes);
	    mp->count++;
	    ctrp++;

	    if (mp->count == items_this_message)
	      {
		mp->count = htonl (items_this_message);
		/*
		 * If the main thread's input queue is stuffed,
		 * drop the data structure lock (which the main thread
		 * may want), and take a pause.
		 */
		svm_queue_lock (q);
		if (svm_queue_is_full (q))
		  {
		    dsunlock (sm);
		    vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
		    svm_queue_unlock (q);
		    mp = 0;
		    ip46_fib_stats_delay (sm, 0 /* sec */ ,
					  STATS_RELEASE_DELAY_NS);
		    goto again;
		  }
		vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
		svm_queue_unlock (q);

		items_this_message = IP6_FIB_COUNTER_BATCH_SIZE;
		mp = vl_msg_api_alloc_as_if_client
		  (sizeof (*mp) +
		   items_this_message * sizeof (vl_api_ip6_fib_counter_t));
		mp->_vl_msg_id = ntohs (VL_API_VNET_IP6_FIB_COUNTERS);
		mp->count = 0;
		mp->vrf_id = ntohl (fib->ft_table_id);
		ctrp = (vl_api_ip6_fib_counter_t *) mp->c;
	      }
	  }

	if (sm->data_structure_lock->release_hint)
	  {
	    start_at_fib_index = fib - im6->fibs;
	    dsunlock (sm);
	    ip46_fib_stats_delay (sm, 0 /* sec */ , STATS_RELEASE_DELAY_NS);
	    mp->count = 0;
	    ctrp = (vl_api_ip6_fib_counter_t *) mp->c;
	    goto again;
	  }
      }				/* vec_foreach (routes) */

      dsunlock (sm);

      /* Flush any data from this fib */
      if (mp->count)
	{
	  mp->count = htonl (mp->count);
	  vl_msg_api_send_shmem (q, (u8 *) & mp);
	  mp = 0;
	}
    }

  /* If e.g. the last FIB had no reportable routes, free the buffer */
  if (mp)
    vl_msg_api_free (mp);
}

static void
stats_thread_fn (void *arg)
{
  stats_main_t *sm = &stats_main;
  vlib_worker_thread_t *w = (vlib_worker_thread_t *) arg;
  vlib_thread_main_t *tm = vlib_get_thread_main ();

  /* stats thread wants no signals. */
  {
    sigset_t s;
    sigfillset (&s);
    pthread_sigmask (SIG_SETMASK, &s, 0);
  }

  if (vec_len (tm->thread_prefix))
    vlib_set_thread_name ((char *)
			  format (0, "%v_stats%c", tm->thread_prefix, '\0'));

  clib_mem_set_heap (w->thread_mheap);

  while (1)
    {
      /* 10 second poll interval */
      ip46_fib_stats_delay (sm, 10 /* secs */ , 0 /* nsec */ );

      if (!(sm->enable_poller))
	{
	  continue;
	}
      if (pool_elts
	  (sm->stats_registrations[IDX_PER_INTERFACE_COMBINED_COUNTERS]))
	do_combined_per_interface_counters (sm);

      if (pool_elts
	  (sm->stats_registrations[IDX_PER_INTERFACE_SIMPLE_COUNTERS]))
	do_simple_per_interface_counters (sm);

      if (pool_elts (sm->stats_registrations[IDX_IP4_FIB_COUNTERS]))
	do_ip4_fib_counters (sm);

      if (pool_elts (sm->stats_registrations[IDX_IP6_FIB_COUNTERS]))
	do_ip6_fib_counters (sm);

      if (pool_elts (sm->stats_registrations[IDX_IP4_MFIB_COUNTERS]))
	do_ip4_mfib_counters (sm);

      if (pool_elts (sm->stats_registrations[IDX_IP6_MFIB_COUNTERS]))
	do_ip6_mfib_counters (sm);

      if (pool_elts (sm->stats_registrations[IDX_IP4_NBR_COUNTERS]))
	do_ip4_nbr_counters (sm);

      if (pool_elts (sm->stats_registrations[IDX_IP6_NBR_COUNTERS]))
	do_ip6_nbr_counters (sm);
    }
}

static void
  vl_api_vnet_interface_simple_counters_t_handler
  (vl_api_vnet_interface_simple_counters_t * mp)
{
  vpe_client_registration_t *clients, client;
  stats_main_t *sm = &stats_main;
  vl_api_registration_t *reg, *reg_prev = NULL;
  vl_api_vnet_interface_simple_counters_t *mp_copy = NULL;
  u32 mp_size;
  int i;

  mp_size = sizeof (*mp) + (ntohl (mp->count) * sizeof (u64));

  clients =
    get_clients_for_stat (IDX_PER_INTERFACE_SIMPLE_COUNTERS,
			  ~0 /*flag for all */ );

  for (i = 0; i < vec_len (clients); i++)
    {
      client = clients[i];
      reg = vl_api_client_index_to_registration (client.client_index);
      if (reg)
	{
	  if (reg_prev && vl_api_can_send_msg (reg_prev))
	    {
	      mp_copy = vl_msg_api_alloc_as_if_client (mp_size);
	      clib_memcpy (mp_copy, mp, mp_size);
	      vl_api_send_msg (reg_prev, (u8 *) mp);
	      mp = mp_copy;
	    }
	  reg_prev = reg;
	}
      else
	{
	  sm->enable_poller =
	    clear_client_for_stat (IDX_PER_INTERFACE_SIMPLE_COUNTERS, ~0,
				   client.client_index);
	  continue;
	}
    }

#if STATS_DEBUG > 0
  fformat (stdout, "%U\n", format_vnet_simple_counters, mp);
#endif

  if (reg_prev && vl_api_can_send_msg (reg_prev))
    {
      vl_api_send_msg (reg_prev, (u8 *) mp);
    }
  else
    {
      vl_msg_api_free (mp);
    }
}

static void
vl_api_vnet_ip4_fib_counters_t_handler (vl_api_vnet_ip4_fib_counters_t * mp)
{
  stats_main_t *sm = &stats_main;
  vl_api_registration_t *reg, *reg_prev = NULL;
  vl_api_vnet_ip4_fib_counters_t *mp_copy = NULL;
  u32 mp_size;
  vpe_client_registration_t *clients, client;
  int i;

  mp_size = sizeof (*mp_copy) +
    ntohl (mp->count) * sizeof (vl_api_ip4_fib_counter_t);

  clients =
    get_clients_for_stat (IDX_IP4_FIB_COUNTERS, ~0 /*flag for all */ );

  for (i = 0; i < vec_len (clients); i++)
    {
      client = clients[i];
      reg = vl_api_client_index_to_registration (client.client_index);
      if (reg)
	{
	  if (reg_prev && vl_api_can_send_msg (reg_prev))
	    {
	      mp_copy = vl_msg_api_alloc_as_if_client (mp_size);
	      clib_memcpy (mp_copy, mp, mp_size);
	      vl_api_send_msg (reg_prev, (u8 *) mp);
	      mp = mp_copy;
	    }
	  reg_prev = reg;
	}
      else
	{
	  sm->enable_poller = clear_client_for_stat (IDX_IP4_FIB_COUNTERS,
						     ~0, client.client_index);
	  continue;
	}
    }

  if (reg_prev && vl_api_can_send_msg (reg_prev))
    {
      vl_api_send_msg (reg_prev, (u8 *) mp);
    }
  else
    {
      vl_msg_api_free (mp);
    }
}

static void
vl_api_vnet_ip4_nbr_counters_t_handler (vl_api_vnet_ip4_nbr_counters_t * mp)
{
  stats_main_t *sm = &stats_main;
  vl_api_registration_t *reg, *reg_prev = NULL;
  vl_api_vnet_ip4_nbr_counters_t *mp_copy = NULL;
  u32 mp_size;
  vpe_client_registration_t *clients, client;
  int i;

  mp_size = sizeof (*mp_copy) +
    ntohl (mp->count) * sizeof (vl_api_ip4_nbr_counter_t);

  clients =
    get_clients_for_stat (IDX_IP4_NBR_COUNTERS, ~0 /*flag for all */ );

  for (i = 0; i < vec_len (clients); i++)
    {
      client = clients[i];
      reg = vl_api_client_index_to_registration (client.client_index);
      if (reg)
	{
	  if (reg_prev && vl_api_can_send_msg (reg_prev))
	    {
	      mp_copy = vl_msg_api_alloc_as_if_client (mp_size);
	      clib_memcpy (mp_copy, mp, mp_size);
	      vl_api_send_msg (reg_prev, (u8 *) mp);
	      mp = mp_copy;
	    }
	  reg_prev = reg;
	}
      else
	{
	  sm->enable_poller = clear_client_for_stat (IDX_IP4_NBR_COUNTERS,
						     ~0, client.client_index);
	  continue;
	}
    }

  /* *INDENT-ON* */
  if (reg_prev && vl_api_can_send_msg (reg_prev))
    {
      vl_api_send_msg (reg_prev, (u8 *) mp);
    }
  else
    {
      vl_msg_api_free (mp);
    }
}

static void
vl_api_vnet_ip6_fib_counters_t_handler (vl_api_vnet_ip6_fib_counters_t * mp)
{
  stats_main_t *sm = &stats_main;
  vl_api_registration_t *reg, *reg_prev = NULL;
  vl_api_vnet_ip6_fib_counters_t *mp_copy = NULL;
  u32 mp_size;
  vpe_client_registration_t *clients, client;
  int i;

  mp_size = sizeof (*mp_copy) +
    ntohl (mp->count) * sizeof (vl_api_ip6_fib_counter_t);

  clients =
    get_clients_for_stat (IDX_IP6_FIB_COUNTERS, ~0 /*flag for all */ );

  for (i = 0; i < vec_len (clients); i++)
    {
      client = clients[i];
      reg = vl_api_client_index_to_registration (client.client_index);
      if (reg)
	{
	  if (reg_prev && vl_api_can_send_msg (reg_prev))
	    {
	      mp_copy = vl_msg_api_alloc_as_if_client (mp_size);
	      clib_memcpy (mp_copy, mp, mp_size);
	      vl_api_send_msg (reg_prev, (u8 *) mp);
	      mp = mp_copy;
	    }
	  reg_prev = reg;
	}
      else
	{
	  sm->enable_poller = clear_client_for_stat (IDX_IP6_FIB_COUNTERS,
						     ~0, client.client_index);
	  continue;
	}
    }
  /* *INDENT-ON* */
  if (reg_prev && vl_api_can_send_msg (reg_prev))
    {
      vl_api_send_msg (reg_prev, (u8 *) mp);
    }
  else
    {
      vl_msg_api_free (mp);
    }
}

static void
vl_api_vnet_ip6_nbr_counters_t_handler (vl_api_vnet_ip6_nbr_counters_t * mp)
{
  stats_main_t *sm = &stats_main;
  vl_api_registration_t *reg, *reg_prev = NULL;
  vl_api_vnet_ip6_nbr_counters_t *mp_copy = NULL;
  u32 mp_size;
  vpe_client_registration_t *clients, client;
  int i;

  mp_size = sizeof (*mp_copy) +
    ntohl (mp->count) * sizeof (vl_api_ip6_nbr_counter_t);

  clients =
    get_clients_for_stat (IDX_IP6_NBR_COUNTERS, ~0 /*flag for all */ );

  for (i = 0; i < vec_len (clients); i++)
    {
      client = clients[i];
      reg = vl_api_client_index_to_registration (client.client_index);
      if (reg)
	{
	  if (reg_prev && vl_api_can_send_msg (reg_prev))
	    {
	      mp_copy = vl_msg_api_alloc_as_if_client (mp_size);
	      clib_memcpy (mp_copy, mp, mp_size);
	      vl_api_send_msg (reg_prev, (u8 *) mp);
	      mp = mp_copy;
	    }
	  reg_prev = reg;
	}
      else
	{
	  sm->enable_poller = clear_client_for_stat (IDX_IP6_NBR_COUNTERS,
						     ~0, client.client_index);
	  continue;
	}
    }
  /* *INDENT-ON* */
  if (reg_prev && vl_api_can_send_msg (reg_prev))
    {
      vl_api_send_msg (reg_prev, (u8 *) mp);
    }
  else
    {
      vl_msg_api_free (mp);
    }
}

static void
vl_api_want_stats_t_handler (vl_api_want_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_stats_reply_t *rmp;
  uword *p;
  i32 retval = 0;
  u32 item;
  vl_api_registration_t *reg;

  item = ~0;			//"ALL THE THINGS IN THE THINGS
  rp.client_index = mp->client_index;
  rp.client_pid = mp->pid;

  handle_client_registration (&rp, IDX_PER_INTERFACE_SIMPLE_COUNTERS,
			      item, mp->enable_disable);

  handle_client_registration (&rp, IDX_PER_INTERFACE_COMBINED_COUNTERS,
			      item, mp->enable_disable);

  handle_client_registration (&rp, IDX_IP4_FIB_COUNTERS,
			      item, mp->enable_disable);

  handle_client_registration (&rp, IDX_IP4_NBR_COUNTERS,
			      item, mp->enable_disable);

  handle_client_registration (&rp, IDX_IP6_FIB_COUNTERS,
			      item, mp->enable_disable);

  handle_client_registration (&rp, IDX_IP6_NBR_COUNTERS,
			      item, mp->enable_disable);

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    return;

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}

static void
  vl_api_want_interface_simple_stats_t_handler
  (vl_api_want_interface_simple_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_interface_simple_stats_reply_t *rmp;
  uword *p;
  i32 retval = 0;
  u32 swif;
  vl_api_registration_t *reg;

  swif = ~0;			//Using same mechanism as _per_interface_
  rp.client_index = mp->client_index;
  rp.client_pid = mp->pid;

  handle_client_registration (&rp, IDX_PER_INTERFACE_SIMPLE_COUNTERS, swif,
			      mp->enable_disable);

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);

  if (!reg)
    {
      sm->enable_poller =
	clear_client_for_stat (IDX_PER_INTERFACE_SIMPLE_COUNTERS, swif,
			       mp->client_index);
      return;
    }

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_INTERFACE_SIMPLE_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}


static void
vl_api_want_ip4_fib_stats_t_handler (vl_api_want_ip4_fib_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_ip4_fib_stats_reply_t *rmp;
  uword *p;
  i32 retval = 0;
  vl_api_registration_t *reg;
  u32 fib;

  fib = ~0;			//Using same mechanism as _per_interface_
  rp.client_index = mp->client_index;
  rp.client_pid = mp->pid;

  handle_client_registration (&rp, IDX_IP4_FIB_COUNTERS, fib,
			      mp->enable_disable);

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);

  if (!reg)
    {
      sm->enable_poller = clear_client_for_stat (IDX_IP4_FIB_COUNTERS,
						 fib, mp->client_index);
      return;
    }

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_IP4_FIB_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}

static void
vl_api_want_ip4_mfib_stats_t_handler (vl_api_want_ip4_mfib_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_ip4_mfib_stats_reply_t *rmp;
  uword *p;
  i32 retval = 0;
  vl_api_registration_t *reg;
  u32 mfib;

  mfib = ~0;			//Using same mechanism as _per_interface_
  rp.client_index = mp->client_index;
  rp.client_pid = mp->pid;

  handle_client_registration (&rp, IDX_IP4_MFIB_COUNTERS, mfib,
			      mp->enable_disable);

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    {
      sm->enable_poller = clear_client_for_stat (IDX_IP4_MFIB_COUNTERS,
						 mfib, mp->client_index);
      return;
    }

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_IP4_MFIB_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}

static void
vl_api_want_ip6_fib_stats_t_handler (vl_api_want_ip6_fib_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_ip4_fib_stats_reply_t *rmp;
  uword *p;
  i32 retval = 0;
  vl_api_registration_t *reg;
  u32 fib;

  fib = ~0;			//Using same mechanism as _per_interface_
  rp.client_index = mp->client_index;
  rp.client_pid = mp->pid;

  handle_client_registration (&rp, IDX_IP6_FIB_COUNTERS, fib,
			      mp->enable_disable);

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    {
      sm->enable_poller = clear_client_for_stat (IDX_IP6_FIB_COUNTERS,
						 fib, mp->client_index);
      return;
    }

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_IP6_FIB_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}

static void
vl_api_want_ip6_mfib_stats_t_handler (vl_api_want_ip6_mfib_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vpe_client_registration_t rp;
  vl_api_want_ip4_mfib_stats_reply_t *rmp;
  uword *p;
  i32 retval = 0;
  vl_api_registration_t *reg;
  u32 mfib;

  mfib = ~0;			//Using same mechanism as _per_interface_
  rp.client_index = mp->client_index;
  rp.client_pid = mp->pid;

  handle_client_registration (&rp, IDX_IP6_MFIB_COUNTERS, mfib,
			      mp->enable_disable);

reply:
  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    {
      sm->enable_poller = clear_client_for_stat (IDX_IP6_MFIB_COUNTERS,
						 mfib, mp->client_index);
      return;
    }

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_WANT_IP6_MFIB_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = retval;

  vl_api_send_msg (reg, (u8 *) rmp);
}

/* FIXME - NBR stats broken - this will be fixed in subsequent patch */
static void
vl_api_want_ip4_nbr_stats_t_handler (vl_api_want_ip4_nbr_stats_t * mp)
{
}

static void
vl_api_want_ip6_nbr_stats_t_handler (vl_api_want_ip6_nbr_stats_t * mp)
{
}

static void
vl_api_vnet_get_summary_stats_t_handler (vl_api_vnet_get_summary_stats_t * mp)
{
  stats_main_t *sm = &stats_main;
  vnet_interface_main_t *im = sm->interface_main;
  vl_api_vnet_get_summary_stats_reply_t *rmp;
  vlib_combined_counter_main_t *cm;
  vlib_counter_t v;
  int i, which;
  u64 total_pkts[VLIB_N_RX_TX];
  u64 total_bytes[VLIB_N_RX_TX];
  vl_api_registration_t *reg;

  reg = vl_api_client_index_to_registration (mp->client_index);
  if (!reg)
    return;

  rmp = vl_msg_api_alloc (sizeof (*rmp));
  rmp->_vl_msg_id = ntohs (VL_API_VNET_GET_SUMMARY_STATS_REPLY);
  rmp->context = mp->context;
  rmp->retval = 0;

  memset (total_pkts, 0, sizeof (total_pkts));
  memset (total_bytes, 0, sizeof (total_bytes));

  vnet_interface_counter_lock (im);

  vec_foreach (cm, im->combined_sw_if_counters)
  {
    which = cm - im->combined_sw_if_counters;

    for (i = 0; i < vlib_combined_counter_n_counters (cm); i++)
      {
	vlib_get_combined_counter (cm, i, &v);
	total_pkts[which] += v.packets;
	total_bytes[which] += v.bytes;
      }
  }
  vnet_interface_counter_unlock (im);

  rmp->total_pkts[VLIB_RX] = clib_host_to_net_u64 (total_pkts[VLIB_RX]);
  rmp->total_bytes[VLIB_RX] = clib_host_to_net_u64 (total_bytes[VLIB_RX]);
  rmp->total_pkts[VLIB_TX] = clib_host_to_net_u64 (total_pkts[VLIB_TX]);
  rmp->total_bytes[VLIB_TX] = clib_host_to_net_u64 (total_bytes[VLIB_TX]);
  rmp->vector_rate =
    clib_host_to_net_u64 (vlib_last_vector_length_per_node (sm->vlib_main));

  vl_api_send_msg (reg, (u8 *) rmp);
}

int
stats_memclnt_delete_callback (u32 client_index)
{
  vpe_client_stats_registration_t *rp;
  stats_main_t *sm = &stats_main;
  uword *p;

  // FIXME
  /* p = hash_get (sm->stats_registration_hash, client_index); */
  /* if (p) */
  /*   { */
  /*     rp = pool_elt_at_index (sm->stats_registrations, p[0]); */
  /*     pool_put (sm->stats_registrations, rp); */
  /*     hash_unset (sm->stats_registration_hash, client_index); */
  /*   } */

  return 0;
}

#define vl_api_vnet_interface_simple_counters_t_endian vl_noop_handler
#define vl_api_vnet_interface_simple_counters_t_print vl_noop_handler
#define vl_api_vnet_interface_combined_counters_t_endian vl_noop_handler
#define vl_api_vnet_interface_combined_counters_t_print vl_noop_handler
#define vl_api_vnet_ip4_fib_counters_t_endian vl_noop_handler
#define vl_api_vnet_ip4_fib_counters_t_print vl_noop_handler
#define vl_api_vnet_ip6_fib_counters_t_endian vl_noop_handler
#define vl_api_vnet_ip6_fib_counters_t_print vl_noop_handler
#define vl_api_vnet_ip4_nbr_counters_t_endian vl_noop_handler
#define vl_api_vnet_ip4_nbr_counters_t_print vl_noop_handler
#define vl_api_vnet_ip6_nbr_counters_t_endian vl_noop_handler
#define vl_api_vnet_ip6_nbr_counters_t_print vl_noop_handler

static clib_error_t *
stats_init (vlib_main_t * vm)
{
  stats_main_t *sm = &stats_main;
  api_main_t *am = &api_main;
  void *vlib_worker_thread_bootstrap_fn (void *arg);

  sm->vlib_main = vm;
  sm->vnet_main = vnet_get_main ();
  sm->interface_main = &vnet_get_main ()->interface_main;
  sm->api_main = am;
  sm->stats_poll_interval_in_seconds = 10;
  sm->data_structure_lock =
    clib_mem_alloc_aligned (sizeof (data_structure_lock_t),
			    CLIB_CACHE_LINE_BYTES);
  memset (sm->data_structure_lock, 0, sizeof (*sm->data_structure_lock));

#define _(N,n)                                                  \
    vl_msg_api_set_handlers(VL_API_##N, #n,                     \
                           vl_api_##n##_t_handler,              \
                           vl_noop_handler,                     \
                           vl_api_##n##_t_endian,               \
                           vl_api_##n##_t_print,                \
                           sizeof(vl_api_##n##_t), 0 /* do NOT trace! */);
  foreach_stats_msg;
#undef _

  /* tell the msg infra not to free these messages... */
  am->message_bounce[VL_API_VNET_INTERFACE_SIMPLE_COUNTERS] = 1;
  am->message_bounce[VL_API_VNET_INTERFACE_COMBINED_COUNTERS] = 1;
  am->message_bounce[VL_API_VNET_IP4_FIB_COUNTERS] = 1;
  am->message_bounce[VL_API_VNET_IP6_FIB_COUNTERS] = 1;
  am->message_bounce[VL_API_VNET_IP4_NBR_COUNTERS] = 1;
  am->message_bounce[VL_API_VNET_IP6_NBR_COUNTERS] = 1;

  /*
   * Set up the (msg_name, crc, message-id) table
   */
  setup_message_id_table (am);

  vec_validate (sm->stats_registrations, STATS_REG_N_IDX);
  vec_validate (sm->stats_registration_hash, STATS_REG_N_IDX);
#define stats_reg(n)                            \
  sm->stats_registrations[IDX_##n] = 0; \
  sm->stats_registration_hash[IDX_##n] = 0;
#include <vpp/stats/stats.reg>
#undef stats_reg

  return 0;
}

VLIB_INIT_FUNCTION (stats_init);

/* *INDENT-OFF* */
VLIB_REGISTER_THREAD (stats_thread_reg, static) = {
  .name = "stats",
  .function = stats_thread_fn,
  .fixed_count = 1,
  .count = 1,
  .no_data_structure_clone = 1,
  .use_pthreads = 1,
};
/* *INDENT-ON* */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */