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


/* ==========================================================================
      _               __            __           __   ____ _  __
     (_)____   _____ / /__  __ ____/ /___   ____/ /  / __/(_)/ /___   _____
    / // __ \ / ___// // / / // __  // _ \ / __  /  / /_ / // // _ \ / ___/
   / // / / // /__ / // /_/ // /_/ //  __// /_/ /  / __// // //  __/(__  )
  /_//_/ /_/ \___//_/ \__,_/ \__,_/ \___/ \__,_/  /_/  /_//_/ \___//____/

   ========================================================================== */


#if HAVE_CONFIG_H

#   include "config.h"

#endif /* HAVE_CONFIG_H */

#ifdef TRACE_LOG

#   define _GNU_SOURCE
#   include <stdio.h>
#   include <syscall.h>
#   include <unistd.h>

#   define trace(x) do                                                         \
    {                                                                          \
        printf("[%s:%d:%s():%ld]" , __FILE__, __LINE__, __func__,              \
            syscall(SYS_gettid));                                              \
        printf x ;                                                             \
        printf("\n");                                                          \
    }                                                                          \
    while (0)

#else

#   define trace(x)

#endif

#if HAVE_ASSERT_H

#   include <assert.h>

#else /* HAVE_ASSERT_H */

#   define assert(x)

#endif /* HAVE_ASSERT_H */

#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#if ENABLE_THREADS

#   include <fcntl.h>
#   include <pthread.h>
#   include <sys/socket.h>
#   include <sys/time.h>

#   if ENABLE_POSIX_CALLS

#       include <signal.h>

#   endif /* ENABLE_POSIX_CALLS */

#endif /* ENABLE_THREADS */

#if ENABLE_POSIX_CALLS

#   include <unistd.h>

#   if HAVE_SYS_SELECT_H

#       include <sys/select.h>

#   else /* HAVE_SYS_SELECT_H */

        /*
         * some systems (like hpux 11.11) may not have sys/select.h as it is
         * mandatory only from POSIX 1003.1-2001 and these are old  includes
         * for select() function
         */

#       include <sys/time.h>
#       include <sys/types.h>

#   endif /* HAVE_SYS_SELECT_H */

#endif /* ENABLE_POSIX_CALLS */

#include "rb.h"
#include "valid.h"


/* ==========================================================================
                  _                __           __
    ____   _____ (_)_   __ ____ _ / /_ ___     / /_ __  __ ____   ___   _____
   / __ \ / ___// /| | / // __ `// __// _ \   / __// / / // __ \ / _ \ / ___/
  / /_/ // /   / / | |/ // /_/ // /_ /  __/  / /_ / /_/ // /_/ //  __/(__  )
 / .___//_/   /_/  |___/ \__,_/ \__/ \___/   \__/ \__, // .___/ \___//____/
/_/                                              /____//_/
   ========================================================================== */


#if ENABLE_POSIX_CALLS && ENABLE_THREADS

/*
 * sadly there is no portable pthread_t invalid value like '0', so  we  need
 * used field to know if field in blocked threads list is empty or not.
 */

struct blocked_threads
{
    pthread_t  thread;  /* blocked thread */
    int        valid;   /* if set, thread is valid */
};

#endif /* ENABLE_POSIX_CALLS && ENABLE_THREADS */

/*
 * Ring buffer information.  This needs to be  hidden  in  c,  because  some
 * fields might not be accessible depending on compilation choices.  Imagine
 * these beautiful segfaults, when shared library would be compiled with all
 * fields, and application using library would  be  compiled  without  these
 * fields - it would allocate less memory on stack than it would be  needed.
 * We use malloc anyway to reserve memory for buffer, so it  is  not  a  big
 * deal to reserve memory also for this structure
 */


struct rb
{
    size_t           head;        /* pointer to buffer's head */
    size_t           tail;        /* pointer to buffer's tail */
    size_t           count;       /* maximum number of elements in buffer */
    size_t           object_size; /* size of a single object in buffer */
    unsigned long    flags;       /* flags used with buffer */
    unsigned char   *buffer;      /* pointer to ring buffer in memory */

#if ENABLE_THREADS

    pthread_mutex_t  lock;        /* mutex for concurrent access */
    pthread_mutex_t  rlock;       /* global lock for reading from rb */
    pthread_mutex_t  wlock;       /* global lock for writing to rb */
    pthread_cond_t   wait_data;   /* ca, will block if buffer is empty */
    pthread_cond_t   wait_room;   /* ca, will block if buffer is full */
    pthread_t        stop_thread; /* thread to force thread to exit send/recv */
    int              stopped_all; /* when set no threads are in send/recv */
    int              force_exit;  /* if set, library will stop all operations */

#   if ENABLE_POSIX_CALLS

    struct blocked_threads *blocked_threads; /* blocked threads in rb */
    int              curr_blocked;  /* current number of threads in read() */
    int              max_blocked;   /* size of blocked_threads array */
    int              signum;        /* signal to send when stopping blocked
                                       threads */

#   endif /* ENABLE_POSIX_CALLS */

#endif /* ENABLE_THREADS */
};


/* ==========================================================================
                                   _                __
                     ____   _____ (_)_   __ ____ _ / /_ ___
                    / __ \ / ___// /| | / // __ `// __// _ \
                   / /_/ // /   / / | |/ // /_/ // /_ /  __/
                  / .___//_/   /_/  |___/ \__,_/ \__/ \___/
                 /_/
               ____                     __   _
              / __/__  __ ____   _____ / /_ (_)____   ____   _____
             / /_ / / / // __ \ / ___// __// // __ \ / __ \ / ___/
            / __// /_/ // / / // /__ / /_ / // /_/ // / / /(__  )
           /_/   \__,_//_/ /_/ \___/ \__//_/ \____//_/ /_//____/

   ========================================================================== */


/* ==========================================================================
    Calculates number of elements in ring buffer.  ns stands for not safe as
    in there are no checks.
   ========================================================================== */


static size_t rb_count_ns
(
    const struct rb  *rb  /* rb object */
)
{
    return (rb->head - rb->tail) & (rb->count - 1);
}


/* ==========================================================================
    Calculates how many elements can be pushed into ring buffer.   ns stands
    for nos safe as in there are no checks.
   ========================================================================== */


static size_t rb_space_ns
(
    const struct rb  *rb  /* rb object */
)
{
    return (rb->tail - (rb->head + 1)) & (rb->count - 1);
}


/* ==========================================================================
    Calculates number of elements in ring buffer until  the  end  of  buffer
    memory.  If elements don't overlap memory, function acts  like  rb_count
   ========================================================================== */


static size_t rb_count_end
(
    const struct rb  *rb  /* rb object */
)
{
    size_t            end;
    size_t            n;
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    end = rb->count - rb->tail;
    n = (rb->head + end) & (rb->count - 1);

    return n < end ? n : end;
}


/* ==========================================================================
    Calculates how many elements can be  pushed  into  ring  buffer  without
    overlapping memory
   ========================================================================== */


static size_t rb_space_end
(
    const struct rb  *rb  /* rb object */
)
{
    size_t            end;
    size_t            n;
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    end = rb->count - 1 - rb->head;
    n = (end + rb->tail) & (rb->count - 1);

    return n <= end ? n : end + 1;
}


/* ==========================================================================
    Checks if number x is exactly power of two number (ie.  1, 2, 4, 8,  16)
   ========================================================================== */


static int rb_is_power_of_two
(
    size_t  x  /* number to check */
)
{
    return (x != 0) && ((x & (~x + 1)) == x);
}


/* ==========================================================================
    Signal action handler. It's called when we signal blocked thread to exit
    blocked system call, it does nothing, it's here so we don't crash.
   ========================================================================== */


#if ENABLE_THREADS && ENABLE_POSIX_CALLS

static void rb_sigaction(int signum)
{
    (void)signum;
    return;
}

#endif /* ENABLE_THREADS && ENABLE_POSIX_CALLS */


/* ==========================================================================
    This function will add currently executing thread to the list of blocked
    threads. It will try to allocate more memory if it detects all slots are
    used up.

    On success 0 is returned, on error -1. Error can be returned only when
    realloc fails - that is there is not enough memory in the sytem.
   ========================================================================== */


#if ENABLE_THREADS && ENABLE_POSIX_CALLS

static int rb_add_blocked_thread
(
    struct rb  *rb  /* rb object */
)
{
    int         i;  /* just an iterator */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    if (rb->curr_blocked >= rb->max_blocked)
    {
        void *p;  /* new pointer for blocked threads */
        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


        /*
         * all slots for blocked threads are used up, we  need  to  allocate
         * more by doubling available memory
         */

        p = realloc(rb->blocked_threads,
            2 * rb->max_blocked * sizeof(struct blocked_threads));

        if (p == NULL)
        {
            /*
             * failed to realloc memory, we  return  error  without  chaning
             * anything in rb object
             */

            return -1;
        }

        /*
         * realocation was a success, we can now change rb object to reflect
         * new memory
         */

        rb->blocked_threads = p;
        rb->max_blocked *= 2;

        /*
         * one thing left, new memory we got from realloc contains  garbage,
         * so we need to initialize it to 0.  We just doubled  memory  size,
         * so only second half of memory needs to be zeroed.
         */

        memset(rb->blocked_threads + rb->max_blocked / 2, 0x00,
            rb->max_blocked / 2 * sizeof(struct blocked_threads));
        trace(("i/increase blocked size; new size is %d", rb->max_blocked));
    }

    /*
     * there is at least one slot available for our blocked thread info
     */

    for (i = 0; i != rb->max_blocked; ++i)
    {
        /*
         * let's find free slot
         */

        if (rb->blocked_threads[i].valid)
        {
            /*
             * nope, that ain't it
             */

            continue;
        }

        /*
         * and here is our free slot, let's fill it with thread info
         */

        rb->blocked_threads[i].thread = pthread_self();
        rb->blocked_threads[i].valid = 1;
        rb->curr_blocked++;
        trace(("i/slots used: %d, max %d", rb->curr_blocked, rb->max_blocked));
        return 0;
    }

    /*
     * I have *NO* idea how could we get here.  Anyway, let's  return  error
     * as we didn't add thread to the list
     */

    assert(0 && "rb_add_blocked_thread() error adding thread, all slots used?");
    return -1;
}

#endif /* ENABLE_THREADS && ENABLE_POSIX_CALLS */


/* ==========================================================================
    This will remove current thread from the list of  blocked  threads.   It
    shouldn't fail. If it does, there is logic error in the code.
   ========================================================================== */


#if ENABLE_THREADS && ENABLE_POSIX_CALLS

static int rb_del_blocked_thread
(
    struct rb  *rb            /* rb object */
)
{
    int         i;            /* just an iterator */
    pthread_t   curr_thread;  /* current thread */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    curr_thread = pthread_self();

    for (i = 0; i != rb->max_blocked; ++i)
    {
        if (rb->blocked_threads[i].valid == 0)
        {
            /*
             * empty slot, nothing to do
             */

            continue;
        }

        if (pthread_equal(curr_thread, rb->blocked_threads[i].thread))
        {
            /*
             * this is our slot, remove thread from the list,  there  is  no
             * need to set .thread field to 0, as 0 may still  be  valid  id
             */

            rb->blocked_threads[i].valid = 0;
            rb->curr_blocked--;
            trace(("i/used %d max %d", rb->curr_blocked, rb->max_blocked));
            return 0;
        }
    }

    /*
     * couldn't find current thread on the list, shouldn't happen, but still
     * life can be surprising
     */

    assert(0 && "rb_del_blocked_thread() thread not found on the list");
    return -1;
}

#endif /* ENABLE_THREADS && ENABLE_POSIX_CALLS */


/* ==========================================================================
    Reads 'count' bytes of data from 'fd'  into  memory  pointed  by  'dst'.
    This function is basically read() but it first checks if read()  can  be
    called without blocking. It's like non-blocking read();

    Number of bytes read or -1 on error.
   ========================================================================== */


#if ENABLE_POSIX_CALLS

static long rb_nb_read
(
    int             fd,    /* file descriptor to check */
    void           *dst,   /* where data from read() should be stored */
    size_t          count  /* number of bytes to read */
)
{
    struct timeval  tv;    /* timeout for select() function */
    fd_set          fds;   /* fd set to check for activity */
    int             sact;  /* return value from select() */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    /*
     * we simply want to check if data is available and don't want select()
     * to block
     */

    tv.tv_sec = 0;
    tv.tv_usec = 0;

    FD_ZERO(&fds);
    FD_SET(fd, &fds);

    sact = select(fd + 1, &fds, NULL, NULL, &tv);

    if (sact == -1)
    {
        /*
         * critical error, we're fucked... I mean caller is fucked
         */

        return -1;
    }

    if (sact == 0)
    {
        /*
         * no data to read immediately from 'fd' socket
         */

        errno = EAGAIN;
        return -1;
    }

    return read(fd, dst, count);
}

#endif /* ENABLE_POSIX_CALLS */


/* ==========================================================================
    Writes 'cont' bytes of data from 'src' into file descriptor 'fd'. It's
    basically non blocking write().

    Returns number of bytes or -1 on error
   ========================================================================== */


#if ENABLE_POSIX_CALLS

static long rb_nb_write
(
    int             fd,    /* file descriptor to check */
    void           *src,   /* location to write data from */
    size_t          count  /* number of bytes to write */
)
{
    struct timeval  tv;    /* timeout for select() function */
    fd_set          fds;   /* fd set to check for activity */
    int             sact;  /* return value from select() */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    /*
     * we simply want to check if data is available and don't want select()
     * to block
     */

    tv.tv_sec = 0;
    tv.tv_usec = 0;

    FD_ZERO(&fds);
    FD_SET(fd, &fds);

    sact = select(fd + 1, NULL, &fds, NULL, &tv);

    if (sact == -1)
    {
        /*
         * critical error, we're fucked... I mean caller is fucked
         */

        return -1;
    }

    if (sact == 0)
    {
        /*
         * no data to write immediately to 'fd' socket
         */

        errno = EAGAIN;
        return -1;
    }

    return write(fd, src, count);
}

#endif /* ENABLE_POSIX_CALLS */


/* ==========================================================================
    Function reads maximum count of data from rb  into  buffer.   When  user
    requested more data than there is in a buffer, function  will  copy  all
    data from rb and will return number of bytes copied.  When there  is  no
    data in buffer, function will return -1 and EAGAIN

    If MSG_PEEK flag is set, data will  be  copied  into  buffer,  but  tail
    pointer will not be moved, so consequent call  to  rb_recv  will  return
    same data.
   ========================================================================== */


static long rb_recvs
(
    struct rb*      rb,       /* rb object */
    void*           buffer,   /* buffer where received data will be copied */
    int             fd,       /* file descriptor where data will be copied */
    size_t          count,    /* number of elements to copy to buffer */
    unsigned long   flags     /* receiving options */
)
{
    size_t          rbcount;  /* number of elements in rb */
    size_t          cnte;     /* number of elements in rb until overlap */
    size_t          tail;     /* rb->tail copy in case we need to restore it */
    size_t          objsize;  /* size, in bytes, of single object in rb */
    unsigned char*  buf;      /* buffer treated as unsigned char type */
    long            w;        /* number of bytes wrote with write() */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    trace(("i/fd: %d, count: %zu, flags: %lu", fd, count, flags));

    if (count > (rbcount = rb_count_ns(rb)))
    {
        /*
         * Caller requested more data then is available, adjust count
         */

        count = rbcount;
    }

    if (count == 0)
    {
        trace(("e/eagain"));
        errno = EAGAIN;
        return -1;
    }

    objsize = rb->object_size;
    cnte = rb_count_end(rb);
    buf = buffer;

#if ENABLE_POSIX_CALLS

    if (buf)
    {

#endif /* ENABLE_POSIX_CALLS */

        if (count > cnte)
        {
            /*
             * Memory overlaps, copy data in two turns
             */

            memcpy(buf, rb->buffer + rb->tail * objsize, objsize * cnte);
            memcpy(buf + cnte * objsize, rb->buffer, (count - cnte) * objsize);
            rb->tail = flags & MSG_PEEK ? rb->tail : count - cnte;
        }
        else
        {
            /*
             * Memory doesn't overlap, good we can do copying on one go
             */

            memcpy(buf, rb->buffer + rb->tail * objsize, count * objsize);
            rb->tail += flags & MSG_PEEK ? 0 : count;
            rb->tail &= rb->count - 1;
        }

        trace(("i/ret %zu", count));
        return count;

#if ENABLE_POSIX_CALLS

    }

    /*
     * copy data from buffer to fd
     */

    if (count > cnte)
    {
        long  tw;     /* total number of elements wrote to fd */
        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


        /*
         * memory overlaps, we'll need to copy data in two steps
         */

        w = rb_nb_write(fd, rb->buffer + rb->tail * objsize, objsize * cnte);
        if (w == -1)
        {
            trace(("e/write() %s", strerror(errno)));
            return -1;
        }

        /*
         * we operate on elements, and write() returns number of bytes read,
         * so here we convert number of bytes wrote into number of  elements
         * wrote
         */

        tw = w / objsize;

        if ((size_t)tw != cnte)
        {
            /*
             * write() returned less bytes than we  wanted,  looks  like  fd
             * cannot accept more data right now, return  partial  write  to
             * the caller
             */

            rb->tail += flags & MSG_PEEK ? 0 : tw;
            rb->tail &= rb->count - 1;
            trace(("i/ret %lu", tw));
            return tw;
        }

        w = rb_nb_write(fd, rb->buffer, (count - cnte) * objsize);
        if (w == -1)
        {
            trace(("e/write() %s", strerror(errno)));
            return -1;
        }

        tw += w / objsize;
        rb->tail = flags & MSG_PEEK ? rb->tail : w / objsize;
        trace(("i/ret %lu", tw));
        return tw;
    }

    /*
     * write to fd without overlap
     */

    w = rb_nb_write(fd, rb->buffer + rb->tail * objsize, count * objsize);
    if (w == -1)
    {
        trace(("e/write() %s", strerror(errno)));
        return -1;
    }

    rb->tail += flags & MSG_PEEK ? 0 : w / objsize;
    rb->tail &= rb->count - 1;
    trace(("i/ret %zu", w / objsize));
    return w / objsize;

#endif /* ENABLE_POSIX_CALLS */
}


/* ==========================================================================
    Reads count data  from  rb  into  buffer.   Function  will  block  until
    count elements are stored into buffer, unless blocking flag is set to 1.
    When rb is exhausted and there is still  data  to  read,  caller  thread
    will be put to sleep and will be waked up as soon as there  is  data  in
    rb.  count can be any size, it can be much bigger  than  rb  size,  just
    keep in mind if count is  too  big,  time  waiting  for  data  might  be
    significant.  When blocking flag is set to 1, and there is less data  in
    rb than count expects, function will copy as many  elements  as  it  can
    (actually it will copy all of data  that  is  in  rb)  and  will  return
    with   number   of   elements   stored   in    buffer. When there is  no
    data in buffer, function will return -1 and EAGAIN
   ========================================================================== */


#if ENABLE_THREADS


static long rb_recvt
(
    struct rb*      rb,      /* rb object */
    void*           buffer,  /* buffer where received data will be copied to */
    int             fd,
    size_t          count,   /* number of elements to copy to buffer */
    unsigned long   flags    /* receiving options */
)
{
    size_t          r;       /* number of elements read */
    unsigned char*  buf;     /* buffer treated as unsigned char type */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    r = 0;
    errno = 0;
    buf = buffer;

    /*
     * globally lock read mutex, we don't want to let  multiple  readers  to
     * read from single rb, this may lead to situation when T1 reads part of
     * data, then T2 comes in reads some data, and then T1  comes  back  and
     * reads more data, and now T1 read data that is  not  continous.   Very
     * bad when reading full packets
     */

    trace(("i/read lock"));
    pthread_mutex_lock(&rb->rlock);
    trace(("i/fd: %d, count: %zu, flags: %lu", fd, count, flags));
    while (count)
    {
        size_t  count_to_end;
        size_t  count_to_read;
        size_t  bytes_to_read;
        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);

        while (rb_count_ns(rb) == 0 && rb->force_exit == 0)
        {
            struct timespec ts;  /* timeout for pthread_cond_timedwait */
            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


            /*
             * buffer is empty and no data can be  read,  we  wait  for  any
             * data or exit if 'rb' is nonblocking
             */

            if (rb->flags & O_NONBLOCK || flags & MSG_DONTWAIT)
            {
                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));
                pthread_mutex_unlock(&rb->rlock);
                trace(("read unlock"));

                if (r == 0)
                {
                    /*
                     * set errno only when we did not read any bytes from rb
                     * this is how standard posix read/send works
                     */

                    trace(("e/eagain"));
                    errno = EAGAIN;
                    return -1;
                }
                return r;
            }

            clock_gettime(CLOCK_REALTIME, &ts);
            ts.tv_sec += 5;

            /*
             * This happens only after calling rb_stop()
             *
             * on some very rare ocassions it is possible that signal  won't
             * reach out rb->wait_data conditional variable.  This shouldn't
             * happend, but yet it does.  Such behaviour may cause deadlock.
             * To prevent deadlock we wake this thread every now and then to
             * make sure program is running.  When everything works ok, this
             * has marginal impact on performance and when things go  south,
             * instead of deadlocking  we  stall  execution  for  maximum  5
             * seconds.
             *
             * TODO: look into this and try to make proper fix
             */

            pthread_cond_timedwait(&rb->wait_data, &rb->lock, &ts);
        }

        if (rb->force_exit)
        {
            /*
             * ring buffer is going down operations on buffer are not allowed
             */

            pthread_mutex_unlock(&rb->lock);
            trace(("i/rb unlock"));
            pthread_mutex_unlock(&rb->rlock);
            trace(("read unlock"));
            trace(("i/force exit"));
            errno = ECANCELED;
            return -1;
        }

#   if ENABLE_POSIX_CALLS

        if (buf)
        {

#   endif /* ENABLE_POSIX_CALLS */

            /*
             * Elements in memory can overlap, so we need to  calculate  how
             * much elements we can safel
             */

            count_to_end = rb_count_end(rb);
            count_to_read = count > count_to_end ? count_to_end : count;
            bytes_to_read = count_to_read * rb->object_size;

            memcpy(buf, rb->buffer + rb->tail * rb->object_size, bytes_to_read);
            buf += bytes_to_read;

#   if ENABLE_POSIX_CALLS

        }
        else
        {
            long            w;
            fd_set          fds;
            int             sact;
            struct timeval  tv;
            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


            /*
             * check rb_sendt() function to why we do what we do  here  with
             * select(), it's the same thing  but  for  write()  instead  of
             * read().  In short, write() may block  and  that  could  cause
             * deadlock, and select() saves us from that
             */

            if (rb_add_blocked_thread(rb) == -1)
            {
                flags |= MSG_DONTWAIT;
            }

            pthread_mutex_unlock(&rb->lock);
            trace(("i/rb unlock"));

            tv.tv_sec = 0;
            tv.tv_usec = 0;

            FD_ZERO(&fds);
            FD_SET(fd, &fds);

            if (rb->flags & O_NONBLOCK || flags & MSG_DONTWAIT)
            {
                sact = select(fd + 1, NULL, &fds, NULL, &tv);
            }
            else
            {
                sact = select(fd + 1, NULL, &fds, NULL, NULL);
            }

            trace(("i/rb lock"));
            pthread_mutex_lock(&rb->lock);
            rb_del_blocked_thread(rb);

            /*
             * Elements in memory can overlap, so we need to  calculate  how
             * much elements we can safel
             */

            count_to_end = rb_count_end(rb);
            count_to_read = count > count_to_end ? count_to_end : count;
            bytes_to_read = count_to_read * rb->object_size;

            if (sact == -1)
            {
                trace(("e/select() %s", strerror(errno)));

                if (rb->force_exit == 1)
                {
                    errno = ECANCELED;
                }

                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));
                pthread_mutex_unlock(&rb->rlock);
                trace(("read unlock"));
                return -1;
            }

            if (sact == 0)
            {
                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));

                if (rb->flags & O_NONBLOCK || flags & MSG_DONTWAIT)
                {
                    pthread_mutex_unlock(&rb->rlock);
                    trace(("read unlock"));

                    if (r == 0)
                    {
                        trace(("w/select() timeout, eagain"));
                        errno = EAGAIN;
                        return -1;
                    }

                    trace(("i/select() timeout, ret %zu", r));
                    return r;
                }

                continue;
            }

            w = write(fd, rb->buffer + rb->tail * rb->object_size,
                bytes_to_read);

            if (w == -1)
            {
                trace(("e/write() %s", strerror(errno)));
                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));

                if (errno == EAGAIN)
                {
                    if (rb->flags & O_NONBLOCK || flags & MSG_DONTWAIT)
                    {
                        /*
                         * write cannot be finished without blocking- EAGAIN
                         * and user requested non blocking operation, so  we
                         * return. We don't notify anyone here, as this loop
                         * didn't take anything from rb
                         */

                        pthread_mutex_unlock(&rb->rlock);
                        trace(("read unlock"));
                        trace(("i/ret %zu", r ? r : -1));
                        return r ? r : -1;
                    }

                    /*
                     * looks like, passed fd is a non blocking  socket,  but
                     * caller  wants  blocking  operation,  so   we   simply
                     * continue but without notifying another threads as  no
                     * data has been read from rb
                     */

                    continue;
                }

                /*
                 * got some nasty error from write(), not much to do, return
                 * number of elements read - user must check errno to see if
                 * there was any error
                 */

                pthread_mutex_unlock(&rb->rlock);
                trace(("read unlock"));
                trace(("i/ret %zu", r ? r : -1));
                return r ? r : -1;
            }

            /*
             * write() returned something meaningfull,  overwrite  count  to
             * read variable to what was actually read, so pointers are  set
             * properly
             */

            count_to_read = w / rb->object_size;
       }

#   endif /* ENABLE_POSIX_CALLS */

        /*
         * Adjust pointers and counts for the next read
         */

        rb->tail += count_to_read;
        rb->tail &= rb->count - 1;
        r += count_to_read;
        count -= count_to_read;

        /*
         * Signal any threads that waits for space to put data in buffer
         */

        pthread_cond_signal(&rb->wait_room);
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
    }

    pthread_mutex_unlock(&rb->rlock);
    trace(("read unlock"));
    trace(("i/ret %zu", r));
    return r;
}

#endif  /* ENABLE_THREADS */


/* ==========================================================================
    Function writes maximum count of data into ring buffer  from  buffer  or
    file/socket described by fd.  If there is not enough space to store  all
    data from buffer, function will store as many as it can, and will return
    count of objects stored into ring buffer.  If buffer is  full,  function
    returns -1 and EAGAIN error.

    Either buffer or fd can be passed, never both!
   ========================================================================== */


static long rb_sends
(
    struct rb*            rb,       /* rb object */
    const void*           buffer,   /* location of data to put into rb */
    int                   fd,       /* file descriptor to read data from */
    size_t                count,    /* number of elements to put on the rb */
    unsigned long         flags     /* receiving options */
)
{
    size_t                rbspace;  /* space left in rb */
    size_t                spce;     /* space left in rb until overlap */
    size_t                objsize;  /* size of a single element in rb */
    const unsigned char*  buf;      /* buffer treated as unsigned char */
    long                  r;        /* number of bytes read from fd */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    (void)flags;
    trace(("i/fd: %d, count: %zu, flags: %lu", fd, count, flags));

    if (count > (rbspace = rb_space_ns(rb)))
    {
        /*
         * Caller wants to store more data then there is space available
         */

        count = rbspace;
    }

    if (count == 0)
    {
        trace(("e/eagain"));
        errno = EAGAIN;
        return -1;
    }

    objsize = rb->object_size;
    spce = rb_space_end(rb);
    buf = buffer;

#if ENABLE_POSIX_CALLS

    if (buf)
    {

#endif /* ENABLE_POSIX_CALLS */

        if (count > spce)
        {
            /*
             * Memory overlaps, copy data in two turns
             */

            memcpy(rb->buffer + rb->head * objsize, buf, spce * objsize);
            memcpy(rb->buffer, buf + spce * objsize, (count - spce) * objsize);
            rb->head = count - spce;
        }
        else
        {
            /*
             * Memory doesn't overlap, good, we can do copying in one go
             */

            memcpy(rb->buffer + rb->head * objsize, buf, count * objsize);
            rb->head += count;
            rb->head &= rb->count - 1;
        }

        trace(("i/ret %zu", count));
        return count;

#if ENABLE_POSIX_CALLS

    }

    /*
     * use file descriptor as a source of data to put into rb
     */

    if (count > spce)
    {
        long  tr;     /* total number of elements read from fd */
        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


        r = rb_nb_read(fd, rb->buffer + rb->head * objsize, spce * objsize);

        if (r == -1)
        {
            trace(("e/read() %s", strerror(errno)));
            return -1;
        }

        /*
         * we operate on elements, and read() returns number of bytes  read,
         * so here we convert number of bytes read into number  of  elements
         * read.
         */

        tr = r / objsize;

        if ((size_t)tr != spce)
        {
            /*
             * read() returned less bytes than we wanted, fd  is  empty,  no
             * need for another call and we didn't overlap memory
             */

            rb->head += tr;
            rb->head &= rb->count -1;
            trace(("i/ret %ld", tr));
            return tr;
        }

        r = rb_nb_read(fd, rb->buffer, (count - spce) * objsize);

        if (r == -1)
        {
            trace(("e/read() %s", strerror(errno)));
            return -1;
        }

        /*
         * since we overlaped and put data to rb->head, new rb->head pointer
         * is simply moved by the number of elements read from the read()
         */

        tr += r / objsize;
        rb->head = r / objsize;

        /*
         * and we return number of elements totaly read from read()
         */

        trace(("i/ret %ld", tr));
        return tr;
    }

    /*
     * read from fd when memory does not overlap and we can do read in a
     * single read
     */

    r = rb_nb_read(fd, rb->buffer + rb->head * objsize, count * objsize);

    if (r == -1)
    {
        trace(("e/read() %s", strerror(errno)));
        return -1;
    }

    rb->head += r / objsize;
    rb->head &= rb->count -1;
    trace(("i/ret %zu", r / objsize));
    return r / objsize;

#endif /* ENABLE_POSIX_CALLS */
}


/* ==========================================================================
    Writes count data pointed by buffer or fd into rb.  Function will  block
    until count elements are stored into rb, unless blocking flag is set  to
    1.  When rb is full and there is still data to write, caller thread will
    be put to sleep and will be waked up as soon as there is  space  in  rb.
    count can be any size, it can be much bigger than rb size, just keep  in
    mind if count is too big, time waiting for space might  be  significant.
    When blocking flag is set to 1, and there is less space in rb than count
    expects, function will copy as many elements as it can and  will  return
    with number of elements written to rb.   If  buffer  is  full,  function
    returns -1 and EAGAIN error.

    Either buffer or fd can be set, never both!
   ========================================================================== */


#if ENABLE_THREADS

long rb_sendt
(
    struct rb*            rb,       /* rb object */
    const void*           buffer,   /* location of data to put into rb */
    int                   fd,       /* file descriptor to read data from */
    size_t                count,    /* number of elements to put on the rb */
    unsigned long         flags     /* receiving options */
)
{
    size_t                w;        /* number of elements written to rb */
    const unsigned char*  buf;      /* buffer treated as unsigned char type */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    w = 0;
    buf = buffer;
    trace(("i/fd: %d, count: %zu, flags: %lu", fd, count, flags));
    trace(("i/write lock"));
    pthread_mutex_lock(&rb->wlock);

    while (count)
    {
        size_t  count_to_end;
        size_t  count_to_write;
        size_t  bytes_to_write;
        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);

        while (rb_space_ns(rb) == 0 && rb->force_exit == 0)
        {
            struct timespec ts;  /* timeout for pthread_cond_timedwait */
            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


            /*
             * buffer is full and no new data can be  pushed,  we  wait  for
             * room or exit if 'rb' is nonblocking
             */

            if (rb->flags & O_NONBLOCK || flags & MSG_DONTWAIT)
            {
                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));
                pthread_mutex_unlock(&rb->wlock);
                trace(("i/write unlock"));

                if (w == 0)
                {
                    /*
                     * set errno only when we did not read any bytes from rb
                     * this is how standard posix read/send works
                     */

                    errno = EAGAIN;
                    return -1;
                }

                trace(("i/ret %zu", w));
                return w;
            }

            clock_gettime(CLOCK_REALTIME, &ts);
            ts.tv_sec += 5;

            /*
             * This happens only after calling rb_stop()
             *
             * on some very rare ocassions it is possible that signal  won't
             * reach out rb->wait_room conditional variable.  This shouldn't
             * happend, but yet it does.  Such behaviour may cause deadlock.
             * To prevent deadlock we wake this thread every now and then to
             * make sure program is running.  When everything works ok, this
             * has marginal impact on performance and when things go  south,
             * instead of deadlocking  we  stall  execution  for  maximum  5
             * seconds.
             *
             * TODO: look into this and try to make proper fix
             */

            pthread_cond_timedwait(&rb->wait_room, &rb->lock, &ts);
        }

        if (rb->force_exit == 1)
        {
            /*
             * ring buffer is going down operations on buffer are not allowed
             */

            pthread_mutex_unlock(&rb->lock);
            trace(("i/rb unlock"));
            pthread_mutex_unlock(&rb->wlock);
            trace(("i/write unlock"));
            trace(("i/force exit"));
            errno = ECANCELED;
            return -1;
        }

#   if ENABLE_POSIX_CALLS

        if (buf)
        {

#   endif /* ENABLE_POSIX_CALLS */

            /*
             * Count might be too  large  to  store  it  in  one  burst,  we
             * calculate how many elements can we store  before  needing  to
             * overlap memor
             */

            count_to_end = rb_space_end(rb);
            count_to_write = count > count_to_end ? count_to_end : count;
            bytes_to_write = count_to_write * rb->object_size;

            memcpy(rb->buffer + rb->head * rb->object_size,
                buf, bytes_to_write);
            buf += bytes_to_write;

#   if ENABLE_POSIX_CALLS

        }
        else
        {
            long            r;     /* number of bytes read from read() */
            fd_set          fds;   /* watch set for select() */
            int             sact;  /* select() return code */
            struct timeval  tv;    /* timeout for select() */
            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

            /*
             * add current thread to the list of possible locked threads in
             * read() so we can interrupt them on rb_stop()
             */

            if (rb_add_blocked_thread(rb) == -1)
            {
                /*
                 * we couldn't add blockedthread, very unlikely, but we set
                 * this call to be non blocking to avoid deadlock
                 */

                flags |= MSG_DONTWAIT;
            }

            /*
             * read() may block, and read() uses rb directly, so blocking in
             * read() here would cause  massive  deadlock  as  rb  mutex  is
             * locked here.  To prevent bad things from happening we need to
             * make sure read() can be invoked without blocking, for that we
             * will use good old fashioned select() and  we  can  do  it  in
             * unlocked state, so when we  wait  in  select(),  some  thread
             * calling rb_write() could write to rb
             */

            pthread_mutex_unlock(&rb->lock);
            trace(("i/rb unlock"));

            tv.tv_sec = 0;
            tv.tv_usec = 0;

            FD_ZERO(&fds);
            FD_SET(fd, &fds);

            if (rb->flags & O_NONBLOCK || flags & MSG_DONTWAIT)
            {
                /*
                 * call select() without blocking (timeout = 0)
                 */

                sact = select(fd + 1, &fds, NULL, NULL, &tv);
            }
            else
            {
                /*
                 * call select() without timeout, so it block indefinitely
                 */

                sact = select(fd + 1, &fds, NULL, NULL, NULL);
            }

            trace(("i/rb lock"));
            pthread_mutex_lock(&rb->lock);
            rb_del_blocked_thread(rb);

            /*
             * Count might be too  large  to  store  it  in  one  burst,  we
             * calculate how many elements can we store  before  needing  to
             * overlap memor
             */

            count_to_end = rb_space_end(rb);
            count_to_write = count > count_to_end ? count_to_end : count;
            bytes_to_write = count_to_write * rb->object_size;

            if (sact == -1)
            {
                trace(("e/select() %s", strerror(errno)));

                if (rb->force_exit == 1)
                {
                    /*
                     * if select was interrupted by us, overwrite  errno  to
                     * ECANCELED, or else it might be EINTR,  which  may  be
                     * missleading for user.
                     */

                    errno = ECANCELED;
                }

                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));
                pthread_mutex_unlock(&rb->wlock);
                trace(("i/write unlock"));

                return -1;
            }

            if (sact == 0)
            {
                /*
                 * timeout in select() occured
                 */

                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));

                if (rb->flags & O_NONBLOCK || flags & MSG_DONTWAIT)
                {
                    pthread_mutex_unlock(&rb->wlock);
                    trace(("i/write unlock"));

                    /*
                     * in non blocking mode, we return what has been already
                     * put into rb (or -1 if nothing has been stored in rb)
                     */

                    if (w == 0)
                    {
                        errno = EAGAIN;
                        trace(("w/select() timeout, eagain"));
                        return -1;
                    }

                    trace(("i/select() timeout, return %zu", w));
                    return w;
                }

                /*
                 * okay, so open group defines when select() is called  with
                 * timeout set to NULL,  select()  will  block  until  event
                 * occurs
                 *
                 * > If the timeout argument is  a  null  pointer,  select()
                 * > blocks until an event causes one of  the  masks  to  be
                 * > returned with a valid (non-zero) value
                 * http://pubs.opengroup.org/onlinepubs/7908799/xsh/select.html
                 *
                 * freebsd also will block indefiniately:
                 *
                 * > If  timeout  is  a  nil  pointer,   the  select  blocks
                 * > indefinitely.
                 * http://nixdoc.net/man-pages/FreeBSD/man4/man2/select.2.html
                 *
                 * But linux man page states that select() only *CAN*  block
                 * indefinitely, not *MUST*
                 *
                 * > If timeout is NULL  (no timeout),  select()  can  block
                 * > indefinitely.
                 * http://man7.org/linux/man-pages/man2/select.2.html
                 *
                 * Taking that into  considaration,  even  though  it's  not
                 * fully posix compliant, we expect  select()  to  return  0
                 * when timeout  was  set  to  NULL,  it  won't  harm  posix
                 * implementation of select(), but will save our asses  from
                 * Linux
                 */

                continue;
            }

            /*
             * now we are sure read() won't block
             */

            r = read(fd, rb->buffer + rb->head * rb->object_size,
                bytes_to_write);

            if (r == -1)
            {
                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));

                if (errno == EAGAIN)
                {
                    if (rb->flags & O_NONBLOCK || flags & MSG_DONTWAIT)
                    {
                        /*
                         * write cannot be finished without blocking- EAGAIN
                         * and user requested non blocking operation, so  we
                         * return. We don't notify anyone here, as this loop
                         * didn't take anything from rb
                         */

                        pthread_mutex_unlock(&rb->wlock);
                        trace(("i/write unlock"));
                        trace(("w/read() eagain, ret: %zu", w ? w : -1));
                        return w ? w : -1;
                    }

                    /*
                     * looks like, passed fd is a non blocking  socket,  but
                     * caller  wants  blocking  operation,  so   we   simply
                     * continue but without notifying another threads as  no
                     * data has been read from rb
                     */

                    continue;
                }

                /*
                 * got some nasty error from write(), not much to do, return
                 * number of elements read - user must check errno to see if
                 * there was any error
                 */

                pthread_mutex_unlock(&rb->wlock);
                trace(("i/write unlock"));
                trace(("e/read() %s, ret: %zu", strerror(errno), w ? w : -1));
                return w ? w : -1;
            }

            if (r == 0)
            {
                /*
                 * returning 0 from read() is quite special, it can be  that
                 * we read end of file, or connection with  the  socket  was
                 * closed, it should not be ignored as  it  carry  important
                 * meaning, so we return what was already written to rb.  It
                 * may be even 0.
                 */

                pthread_mutex_unlock(&rb->lock);
                trace(("i/rb unlock"));
                pthread_mutex_unlock(&rb->wlock);
                trace(("i/write unlock"));
                return w;
            }

            /*
             * write() returned something meaningfull,  overwrite  count  to
             * read variable to what was actually read, so pointers are  set
             * properly
             */

            count_to_write = r / rb->object_size;
        }

#   endif /* ENABLE_POSIX_CALLS */

        /*
         * Adjust pointers and counts for next write
         */

        rb->head += count_to_write;
        rb->head &= rb->count - 1;
        w += count_to_write;
        count -= count_to_write;

        /*
         * Signal any threads that waits for data to read
         */

        pthread_cond_signal(&rb->wait_data);
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
    }

    pthread_mutex_unlock(&rb->wlock);
    trace(("i/write unlock"));
    trace(("i/ret %zu", w));
    return w;
}


/* ==========================================================================
    This function simply signals all  conditional  variables  to  force  any
    locked thread to exit from read/send functions
   ========================================================================== */


static void *rb_stop_thread
(
    void       *arg       /* disguised rb object */
)
{
    struct rb  *rb;       /* ring buffer object */
    int         stopped;  /* copy of rb->stopped_all */
    int         i;        /* i stands for iterator dude! */

#   if ENABLE_POSIX_CALLS

    struct sigaction sa;  /* signal action info */
    struct sigaction osa; /* Office of Secret Actions... kidding, it's old sa */
    time_t           now; /* current time in seconds */
    time_t           prev;/* previous time */

#   endif /* ENABLE_POSIX_CALLS */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    rb = arg;
    stopped = 0;
    trace(("starting"));

    trace(("i/rb lock"));
    pthread_mutex_lock(&rb->lock);
    rb->force_exit = 1;
    pthread_mutex_unlock(&rb->lock);
    trace(("i/rb unlock"));

#   if ENABLE_POSIX_CALLS

    prev = 0;

    /*
     * we need to install action handler, so sending signal won't kill  kill
     * application
     */

    memset(&sa, 0x00, sizeof(sa));
    memset(&osa, 0x00, sizeof(osa));
    sa.sa_handler = rb_sigaction;

    /*
     * install signal action for user specified signal (or default one if he
     * didn't define it)
     */

    sigaction(rb->signum, &sa, NULL);

#   endif /* ENABLE_POSIX_CALLS */

    /*
     * Send cond signal, until all threads exits read/send functions.   This
     * loop will finish once user calls rb_cleanup().  It's his job to check
     * if all threads finished before calling rb_cleanup()
     */

    while (stopped != 1)
    {
        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);
        pthread_cond_signal(&rb->wait_data);
        pthread_cond_signal(&rb->wait_room);
        stopped = rb->stopped_all;

#   if ENABLE_POSIX_CALLS

        /*
         * send signal to all threads locked in  system  call,  signal  will
         * make sytem call to interrupt
         */

        now = time(NULL);

        if (now != prev)
        {
            prev = now;
            trace(("i/sending kill"));
            for (i = 0; i != rb->max_blocked; ++i)
            {
                if (rb->curr_blocked == 0)
                {
                    /*
                     * no threads in blocked state, no need for iteration
                     */

                    break;
                }

                if (rb->blocked_threads[i].valid == 0)
                {
                    /*
                     * empty slot
                     */

                    continue;
                }

                pthread_kill(rb->blocked_threads[i].thread, rb->signum);
            }
        }

#   endif /* ENABLE_POSIX_CALLS */

        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
    }

#   if  ENABLE_POSIX_CALLS

    /*
     * if we overwritten user's sigaction, now it's time to restore it
     */

    if (((osa.sa_flags & SA_SIGINFO) == 0 && osa.sa_handler) ||
        ((osa.sa_flags & SA_SIGINFO) && osa.sa_sigaction))
    {
        /*
         * SIGUSR1 is the only signal we could overwrite
         */

        sigaction(SIGUSR1, &osa, NULL);
    }

#   endif /* ENABLE_POSIX_CALLS */

    trace(("return NULL"));
    return NULL;
}


#endif  /* ENABLE_THREADS */


/* ==========================================================================
    Initializes rb buffer to known state. Does not initialize rb->buffer
   ========================================================================== */


static int rb_init_p
(
    struct rb     *rb,           /* rb object to init */
    size_t         count,        /* number of elements that buffer can hold */
    size_t         object_size,  /* size, in bytes, of a single object */
    unsigned long  flags         /* flags to create buffer with */
)
{
#if ENABLE_THREADS
    int            e;            /* errno value from pthread function */
#endif

    VALID(EINVAL, rb_is_power_of_two(count) == 1);
    trace(("count: %zu, objsize: %zu, flags: %lu", count, object_size, flags));

    rb->head = 0;
    rb->tail = 0;
    rb->count = count;
    rb->object_size = object_size;
    rb->flags = flags;

#if ENABLE_THREADS == 0
    /*
     * multithreaded operations are not allowed when library is compiled
     * without threads
     */
    VALID(ENOSYS, (flags & O_MULTITHREAD) == 0);

    return 0;
#else
    if ((flags & O_MULTITHREAD) == 0)
    {
        /*
         * when working in non multi-threaded mode, force  O_NONBLOCK  flag,
         * and return, as we don't need to init pthread elements.
         */

        rb->flags |= O_NONBLOCK;
        return 0;
    }

    /*
     * Multithreaded environment
     */

#if ENABLE_POSIX_CALLS

    /*
     * it may happen that rb will be blocked in read() or  write()  function
     * and the only way to interrupt such blocked syscall is  to  send  kill
     * signal to blocked thread. We start with assumption max 2 threads will
     * concurently try to access rb  object  (most  common  case)  and  will
     * increase it when needed
     */

    rb->max_blocked = 2;
    rb->curr_blocked = 0;
    rb->signum = SIGUSR1;
    rb->blocked_threads = calloc(rb->max_blocked,
        sizeof(struct blocked_threads));

    if (rb->blocked_threads == NULL)
    {
        errno = ENOMEM;
        return -1;
    }

#endif /* ENABLE_POSIX_CALLS */

    rb->stopped_all = -1;
    rb->force_exit = 0;

    VALIDGO(e, error_lock,  (e = pthread_mutex_init(&rb->lock, NULL)) == 0);
    VALIDGO(e, error_rlock, (e = pthread_mutex_init(&rb->rlock, NULL)) == 0);
    VALIDGO(e, error_wlock, (e = pthread_mutex_init(&rb->wlock, NULL)) == 0);
    VALIDGO(e, error_data,  (e = pthread_cond_init(&rb->wait_data, NULL)) == 0);
    VALIDGO(e, error_room,  (e = pthread_cond_init(&rb->wait_room, NULL)) == 0);

    return 0;

error_room:
    pthread_cond_destroy(&rb->wait_data);
error_data:
    pthread_mutex_destroy(&rb->wlock);
error_wlock:
    pthread_mutex_destroy(&rb->rlock);
error_rlock:
    pthread_mutex_destroy(&rb->lock);
error_lock:
    errno = e;
    return -1;
#endif
}


/* ==========================================================================
    Cleans up resources allocated by pthread stuff
   ========================================================================== */

#if ENABLE_THREADS

static int rb_cleanup_p
(
    struct rb  *rb  /* rb object */
)
{
    /*
     * check if user called rb_stop, if not (rb->stopped will be -1), we trust
     * caller made sure all threads are stopped before calling destroy.
     */

    trace(("i/rb lock"));
    pthread_mutex_lock(&rb->lock);

#   if ENABLE_POSIX_CALLS

    free(rb->blocked_threads);

#   endif /* ENABLE_POSIX_CALLS */

    if (rb->stopped_all == 0)
    {
        rb->stopped_all = 1;
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
        pthread_join(rb->stop_thread, NULL);
    }
    else
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
    }

    pthread_cond_destroy(&rb->wait_data);
    pthread_cond_destroy(&rb->wait_room);
    pthread_mutex_destroy(&rb->lock);
    pthread_mutex_destroy(&rb->rlock);
    pthread_mutex_destroy(&rb->wlock);

    return 0;
}

#endif /* ENABLE_THREADS */

/* ==========================================================================
                                        __     __ _
                         ____   __  __ / /_   / /(_)_____
                        / __ \ / / / // __ \ / // // ___/
                       / /_/ // /_/ // /_/ // // // /__
                      / .___/ \__,_//_.___//_//_/ \___/
                     /_/
               ____                     __   _
              / __/__  __ ____   _____ / /_ (_)____   ____   _____
             / /_ / / / // __ \ / ___// __// // __ \ / __ \ / ___/
            / __// /_/ // / / // /__ / /_ / // /_/ // / / /(__  )
           /_/   \__,_//_/ /_/ \___/ \__//_/ \____//_/ /_//____/

   ========================================================================== */


/* ==========================================================================
    Initializes new ring buffer object like rb_new but does not use dynamic
    memory allocation, but uses memory pointer by mem.
   ========================================================================== */


struct rb *rb_init
(
    size_t         count,        /* number of elements that buffer can hold */
    size_t         object_size,  /* size, in bytes, of a single object */
    unsigned long  flags,        /* flags to create buffer with */
    void          *mem           /* memory area to use for rb object */
)
{
    struct rb     *rb;           /* treat passed mem as rb object */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    VALIDR(EINVAL, NULL, mem);

    rb = mem;
    rb->buffer = (unsigned char *)rb + sizeof(*rb);

    if (rb_init_p(rb, count, object_size, flags) == 0)
    {
        return rb;
    }

    return NULL;
}


/* ==========================================================================
    Initializes ring buffer and allocates all  necessary  resources.   Newly
    created rb  will  returned  as  a  pointer.   In  case  of  an  function
    error, NULL will be returned
   ========================================================================== */


struct rb *rb_new
(
    size_t         count,        /* number of elements that buffer can hold */
    size_t         object_size,  /* size, in bytes, of a single object */
    unsigned long  flags         /* flags to create buffer with */
)
{
    struct rb     *rb;           /* pointer to newly created buffer */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    if ((rb = malloc(sizeof(*rb))) == NULL)
    {
        errno = ENOMEM;
        return NULL;
    }

    if ((rb->buffer = malloc(count * object_size)) == NULL)
    {
        free(rb);
        errno = ENOMEM;
        return NULL;
    }

    if (rb_init_p(rb, count, object_size, flags) == 0)
    {
        return rb;
    }

    free(rb->buffer);
    free(rb);
    return NULL;
}


/* ==========================================================================
    Reads maximum of count elements from rb and  stores  them  into  buffer.

    If rb is working in single  thread  mode  or  O_NONBLOCK  flag  is  set,
    function will never block, and cannot guarantee writing  count  elements
    into buffer.  If there is not enough data in ring buffer, function  will
    read whole buffer and return with elements read.

    If rb is threaded and  blocking,  function  will  block  (sleep)  caller
    thread until all count  elements  were  copied  into  buffer.   Function
    is   equivalent   to   call   rb_recv   with flags   ==   0
   ========================================================================== */


long rb_read
(
    struct rb  *rb,      /* rb object */
    void       *buffer,  /* location where data from rb will be stored */
    size_t      count    /* requested number of data from rb */
)
{
    return rb_recv(rb, buffer, count, 0);
}


/* ==========================================================================
    Same as rb_read but also accepts flags
   ========================================================================== */


long rb_recv
(
    struct rb     *rb,      /* rb object */
    void          *buffer,  /* location where data from rb will be stored */
    size_t         count,   /* requested number of data from rb */
    unsigned long  flags    /* operation flags */
)
{
    VALID(EINVAL, rb);
    VALID(EINVAL, buffer);
    VALID(EINVAL, rb->buffer);

    if (count > (size_t)LONG_MAX)
    {
        /*
         * function cannot read more than LONG_MAX count of  elements,  trim
         * users count to acceptable value
         */

        count = LONG_MAX;
    }

#if ENABLE_THREADS
    if ((rb->flags & O_MULTITHREAD) == 0)
    {
        return rb_recvs(rb, buffer, -1, count, flags);
    }

    trace(("i/rb lock"));
    pthread_mutex_lock(&rb->lock);
    if (rb->force_exit)
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
        errno = ECANCELED;
        return -1;
    }
    pthread_mutex_unlock(&rb->lock);
    trace(("i/rb unlock"));

    if (flags & MSG_PEEK)
    {
        /*
         * when called is just peeking, we can simply call function for
         * single thread, as it will not modify no data, and will not cause
         * deadlock
         */

        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);
        count = rb_recvs(rb, buffer, -1, count, flags);
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
        return count;
    }

    return rb_recvt(rb, buffer, -1, count, flags);
#else
    return rb_recvs(rb, buffer, -1, count, flags);
#endif
}


/* ==========================================================================
    Same as rb_read, but data is copied to file descriptor 'fd'  instead  of
    user provided buffer
   ========================================================================== */


long rb_posix_read
(
    struct rb  *rb,    /* rb object */
    int         fd,    /* file descriptor data from rb will be copied to */
    size_t      count  /* requested number of elements to be copied from rb */
)
{
    return rb_posix_recv(rb, fd, count, 0);
}


/* ==========================================================================
    Same as rb_posix_read but also accepts flags
   ========================================================================== */


long rb_posix_recv
(
    struct rb     *rb,    /* rb object */
    int            fd,    /* file descriptor data from rb will be copied to */
    size_t         count, /* requested number of elements to be copied from rb*/
    unsigned long  flags  /* operation flags */
)
{
#if ENABLE_POSIX_CALLS

    VALID(EINVAL, rb);
    VALID(EINVAL, rb->buffer);
    VALID(EINVAL, rb->object_size == 1);
    VALID(EINVAL, fd >= 0);

    if (count > (size_t)LONG_MAX)
    {
        /*
         * function cannot read more than LONG_MAX count of  elements,  trim
         * users count to acceptable value
         */

        count = LONG_MAX;
    }

#   if ENABLE_THREADS

    if ((rb->flags & O_MULTITHREAD) == 0)
    {
        return rb_recvs(rb, NULL, fd, count, flags);
    }

    trace(("i/rb lock"));
    pthread_mutex_lock(&rb->lock);
    if (rb->force_exit)
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
        errno = ECANCELED;
        return -1;
    }
    pthread_mutex_unlock(&rb->lock);
    trace(("i/rb unlock"));

    if (flags & MSG_PEEK)
    {
        /*
         * when called is just peeking, we can simply call function for
         * single thread, as it will not modify no data, and will not cause
         * deadlock
         */

        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);
        count = rb_recvs(rb, NULL, fd, count, flags);
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
        return count;
    }

    return rb_recvt(rb, NULL, fd, count, flags);

#   else /* ENABLE_THREADS */

    return rb_recvs(rb, NULL, fd, count, flags);

#   endif /* ENABLE_THREADS */

#else /* ENABLE_POSIX_CALLS */

    /*
     * function is no implemented
     */

    errno = ENOSYS;
    return -1;

#endif /* ENABLE_POSIX_CALLS */
}


/* ==========================================================================
    Writes maximum count data from buffer into rb.

    If rb is working in single  thread  mode  or  O_NONBLOCK  flag  is  set,
    function will never block, but also cannot guarantee that count elements
    will be copied from buffer. If there is not enough space in rb, function
    will store as many elements  as  it  can,  and  return  with  number  of
    elements stored into rb.

    If rb is multithreaded, and in blocking mode function will block (sleep)
    caller until count elements have been stored into rb.

    Function   os   equivalent   to   call   rb_send   with   flags   ==   0
   ========================================================================== */


long rb_write
(
    struct rb   *rb,      /* rb object */
    const void  *buffer,  /* data to be put into rb */
    size_t       count    /* requested number of elements to be put into rb */
)
{
    return rb_send(rb, buffer, count, 0);
}


/* ==========================================================================
    Same as rb_write but also accepts flags
   ========================================================================== */


long rb_send
(
    struct rb     *rb,      /* rb object */
    const void    *buffer,  /* data to be put into rb */
    size_t         count,   /* requested number of elements to be put into r */
    unsigned long  flags    /* operation flags */
)
{
    VALID(EINVAL, rb);
    VALID(EINVAL, buffer);
    VALID(EINVAL, rb->buffer);

    if (count > (size_t)LONG_MAX)
    {
        /*
         * function cannot read more than LONG_MAX count of  elements,  trim
         * users count to acceptable value
         */

        count = LONG_MAX;
    }

#if ENABLE_THREADS
    if ((rb->flags & O_MULTITHREAD) == 0)
    {
        return rb_sends(rb, buffer, -1, count, flags);
    }

    trace(("i/rb lock"));
    pthread_mutex_lock(&rb->lock);
    if (rb->force_exit)
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
        errno = ECANCELED;
        return -1;
    }
    pthread_mutex_unlock(&rb->lock);
    trace(("i/rb unlock"));

    return rb_sendt(rb, buffer, -1, count, flags);
#else
    return rb_sends(rb, buffer, -1, count, flags);
#endif
}


/* ==========================================================================
    Same as rb_write, but data is copied from file descriptor  'fd'  instead
    of user provided buffer.
   ========================================================================== */


long rb_posix_write
(
    struct rb   *rb,      /* rb object */
    int          fd,      /* file descriptor from which copy data to buffer */
    size_t       count    /* requested number of elements to be put into rb */
)
{
    return rb_posix_send(rb, fd, count, 0);
}


/* ==========================================================================
    Same as rb_posix_write but also accepts 'flags'
   ========================================================================== */


long rb_posix_send
(
    struct rb     *rb,      /* rb object */
    int            fd,      /* file descriptor from which copy data to buffer */
    size_t         count,   /* requested number of elements to be put into r */
    unsigned long  flags    /* operation flags */
)
{
#if ENABLE_POSIX_CALLS

    VALID(EINVAL, rb);
    VALID(EINVAL, rb->buffer);
    VALID(EINVAL, rb->object_size == 1);
    VALID(EINVAL, fd >= 0);

    if (count > (size_t)LONG_MAX)
    {
        /*
         * function cannot read more than LONG_MAX count of  elements,  trim
         * users count to acceptable value
         */

        count = LONG_MAX;
    }

#   if ENABLE_THREADS

    if ((rb->flags & O_MULTITHREAD) == 0)
    {
        return rb_sends(rb, NULL, fd, count, flags);
    }

    trace(("i/rb lock"));
    pthread_mutex_lock(&rb->lock);
    if (rb->force_exit)
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
        errno = ECANCELED;
        return -1;
    }
    pthread_mutex_unlock(&rb->lock);
    trace(("i/rb unlock"));

    return rb_sendt(rb, NULL, fd, count, flags);

#   else /* ENABLE_THREADS */

    return rb_sends(rb, NULL, fd, count, flags);

#   endif /* ENABLE_THREADS */

#else /* ENABLE_POSIX_CALLS */

    /*
     * function is not implemented
     */

    errno = ENOSYS;
    return -1;

#endif /* ENABLE_POSIX_CALLS */
}


/* ==========================================================================
    Clears all data in the buffer
   ========================================================================== */


int rb_clear
(
    struct rb  *rb,    /* rb object */
    int         clear  /* if set to 1, also clears memory */
)
{
    VALID(EINVAL, rb);
    VALID(EINVAL, rb->buffer);

#if ENABLE_THREADS
    if ((rb->flags & O_NONBLOCK) == 0)
    {
        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);
    }
#endif

    if (clear)
    {
        memset(rb->buffer, 0x00, rb->count * rb->object_size);
    }

    rb->head = 0;
    rb->tail = 0;

#if ENABLE_THREADS
    if ((rb->flags & O_NONBLOCK) == 0)
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
    }
#endif

    return 0;
}


/* ==========================================================================
    Frees resources allocated by rb_new. Due to pthread nature this function
    should be called *only*  when no other threads are working on rb object,
    and rb object was allocated with rb_new.
   ========================================================================== */


int rb_destroy
(
    struct rb  *rb  /* rb object */
)
{
    int         e;  /* error code to return */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    VALID(EINVAL, rb);
    VALID(EINVAL, rb->buffer);
    e = 0;

#if ENABLE_THREADS
    if ((rb->flags & O_MULTITHREAD) == 0)
    {
        free(rb->buffer);
        free(rb);
        return e;
    }

    e = rb_cleanup_p(rb);
#endif

    free(rb->buffer);
    free(rb);

    return e;
}


/* ==========================================================================
    Same as rb_destroy but should be caled only when rb object was allocated
    with rb_init function
   ========================================================================== */


int rb_cleanup
(
    struct rb  *rb  /* rb object */
)
{
    VALID(EINVAL, rb);

#if ENABLE_THREADS
    if (rb->flags & O_MULTITHREAD)
    {
        return rb_cleanup_p(rb);
    }
#endif

    return 0;
}


/* ==========================================================================
    Simply starts rb_stop_thread  that will force all threads to exit any
    rb_* public functions.
   ========================================================================== */


int rb_stop
(
    struct rb  *rb  /* rb object */
)
{
#if ENABLE_THREADS
    int         e;  /* errno value */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    VALID(EINVAL, rb);
    VALID(EINVAL, rb->flags & O_MULTITHREAD);

    rb->stopped_all = 0;
    if ((e = pthread_create(&rb->stop_thread, NULL, rb_stop_thread, rb)) != 0)
    {
        errno = e;
        return -1;
    }

    return 0;
#else
    errno = ENOSYS;
    return -1;
#endif
}


/* ==========================================================================
    Sets what signal to send upon calling rb_stop()
   ========================================================================== */


int rb_stop_signal
(
    struct rb        *rb,     /* rb object */
    int               signum  /* signal to send with pthread_kill() */
)
{
# if ENABLE_THREADS && ENABLE_POSIX_CALLS

    struct sigaction  sa;     /* sigaction to check if signum is valid */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    VALID(EINVAL, rb);

    memset(&sa, 0x00, sizeof(sa));
    sa.sa_handler = rb_sigaction;

    /*
     * install signal action for user specified signal (or default one if he
     * didn't define it)
     */

    if (sigaction(signum, &sa, NULL) == -1)
    {
        /*
         * provided signum is invalid on this system, signal won't  be  set,
         * and we will use default SIGUSR1 by default
         */

        return -1;
    }

    trace("rb lock");
    pthread_mutex_lock(&rb->lock);
    rb->signum = signum;
    pthread_mutex_unlock(&rb->lock);
    trace("rb unlock");
    return 0;

#else /* ENABLE_THREADS && ENABLE_POSIX_CALLS */

    errno = ENOSYS;
    return -1;

#endif /* ENABLE_THREADS && ENABLE_POSIX_CALLS */
}


/* ==========================================================================
    Function that discards data from tail of buffer.  This works  just  like
    rb_reads function, but is way faster as there  is  no  copying  involved
   ========================================================================== */


long rb_discard
(
    struct rb  *rb,       /* rb object */
    size_t      count     /* number of elements to discard */
)
{
    size_t      rbcount;  /* number of elements in rb */
    size_t      cnte;     /* number of elements in rb until overlap */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    VALID(EINVAL, rb);
    VALID(EINVAL, rb->buffer);

#if ENABLE_THREADS
    if ((rb->flags & O_NONBLOCK) == 0)
    {
        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);
    }
#endif

    cnte = rb_count_end(rb);
    rbcount = rb_count_ns(rb);

    if (count > rbcount)
    {
        count = rbcount;
    }

    if (count > cnte)
    {
        rb->tail = count - cnte;
    }
    else
    {
        rb->tail += count;
        rb->tail &= rb->count -1;
    }

#if ENABLE_THREADS
    if ((rb->flags & O_NONBLOCK) == 0)
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
    }
#endif

    return (long)count;
}


/* ==========================================================================
    Returns version of the library
   ========================================================================== */


const char* rb_version
(
    char*  major,            /* major version info will be stored here */
    char*  minor,            /* minor version info will be stored here */
    char*  patch             /* patch version info will be stored here */
)
{
    char   version[11 + 1];  /* copy of VERSION */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

    if (major && minor && patch)
    {
        strcpy(version, VERSION);

        strcpy(major, strtok(version, "."));
        strcpy(minor, strtok(NULL, "."));
        strcpy(patch, strtok(NULL, "."));
    }

    return VERSION;
}


/* ==========================================================================
    Returns number of elements in buffer.
   ========================================================================== */


long rb_count
(
    struct rb  *rb      /* rb object */
)
{
    size_t      count;  /* number of elements in buffer */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    VALID(EINVAL, rb);
    VALID(EINVAL, rb->buffer);

#if ENABLE_THREADS
    if ((rb->flags & O_NONBLOCK) == 0)
    {
        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);
    }
#endif

    count = rb_count_ns(rb);

#if ENABLE_THREADS
    if ((rb->flags & O_NONBLOCK) == 0)
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
    }
#endif

    return (long)count;
}


/* ==========================================================================
    Return number of free space in buffer
   ========================================================================== */


long rb_space
(
    struct rb  *rb      /* rb object */
)
{
    size_t      space;  /* number of free slots in buffer */
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


    VALID(EINVAL, rb);
    VALID(EINVAL, rb->buffer);

#if ENABLE_THREADS
    if ((rb->flags & O_NONBLOCK) == 0)
    {
        trace(("i/rb lock"));
        pthread_mutex_lock(&rb->lock);
    }
#endif

    space = rb_space_ns(rb);

#if ENABLE_THREADS
    if ((rb->flags & O_NONBLOCK) == 0)
    {
        pthread_mutex_unlock(&rb->lock);
        trace(("i/rb unlock"));
    }
#endif

    return (long)space;
}


/* ==========================================================================
    Return size of rb struct for current implementation.  This size  may  be
    different depending on compilation flags and/or architecture
   ========================================================================== */


size_t rb_header_size(void)
{
    return sizeof(struct rb);
}