aboutsummaryrefslogtreecommitdiffstats
path: root/epan/dissectors/packet-umts_rlc.c
blob: a89c524379398b2ae01c4de2c73e2ba740a5461c (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
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
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
/* packet-umts_rlc.c
 * Routines for UMTS RLC (Radio Link Control) v9.3.0 disassembly
 * http://www.3gpp.org/ftp/Specs/archive/25_series/25.322/
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "config.h"

#include <epan/packet.h>
#include <epan/conversation.h>
#include <epan/expert.h>
#include <epan/prefs.h>
#include <epan/proto_data.h>

#include <wiretap/wtap.h>

/*
 * Optional include, for KASUMI support,
 * see header file for more information.
 * */

#include "packet-umts_fp.h"
#include "packet-umts_rlc.h"
#include "packet-rrc.h"

/* TODO:
 * - distinguish between startpoints and endpoints?
 * - use sub_num in fragment identification?
 */

void proto_register_rlc(void);
void proto_reg_handoff_rlc(void);

int proto_umts_rlc = -1;

extern int proto_fp;

/* Preference to perform reassembly */
static gboolean global_rlc_perform_reassemby = TRUE;

/* Preference to expect RLC headers without payloads */
static gboolean global_rlc_headers_expected = FALSE;

/* Preference to expect ONLY ciphered data */
static gboolean global_rlc_ciphered = FALSE;

/* Preference to ignore ciphering state reported from RRC */
/* This is important for captures with deciphered traffic AND the original security RRC messages present*/
static gboolean global_ignore_rrc_ciphering_indication = FALSE;

/* Preference to try deciphering */
static gboolean global_rlc_try_decipher = FALSE;

#ifdef HAVE_UMTS_KASUMI
static const char *global_rlc_kasumi_key = NULL;
#endif

/* LI size preference */
#define RLC_LI_UPPERLAYER 255 /* LI-size comes from rlc_info struct rather than preference */
static gint global_rlc_li_size = RLC_LI_UPPERLAYER;

static const enum_val_t li_size_enumvals[] = {
    {"7 bits", "7 bits", RLC_LI_7BITS},
    {"15 bits", "15 bits", RLC_LI_15BITS},
    {"Let upper layers decide", "Let upper layers decide", RLC_LI_UPPERLAYER},
    {NULL, NULL, -1}};

/* fields */
static int hf_rlc_seq = -1;
static int hf_rlc_ext = -1;
static int hf_rlc_pad = -1;
static int hf_rlc_frags = -1;
static int hf_rlc_frag = -1;
static int hf_rlc_duplicate_of = -1;
static int hf_rlc_reassembled_in = -1;
static int hf_rlc_he = -1;
static int hf_rlc_dc = -1;
static int hf_rlc_p = -1;
static int hf_rlc_li = -1;
static int hf_rlc_li_value = -1;
static int hf_rlc_li_ext = -1;
static int hf_rlc_li_data = -1;
static int hf_rlc_data = -1;
static int hf_rlc_ciphered_data = -1;
static int hf_rlc_ciphered_lis_data = -1;
static int hf_rlc_ctrl_type = -1;
static int hf_rlc_r1 = -1;
static int hf_rlc_rsn = -1;
static int hf_rlc_hfni = -1;
static int hf_rlc_sufi = -1;
static int hf_rlc_sufi_type = -1;
static int hf_rlc_sufi_lsn = -1;
static int hf_rlc_sufi_wsn = -1;
static int hf_rlc_sufi_sn = -1;
static int hf_rlc_sufi_l = -1;
static int hf_rlc_sufi_fsn = -1;
static int hf_rlc_sufi_len = -1;
static int hf_rlc_sufi_bitmap = -1;
static int hf_rlc_sufi_cw = -1;
static int hf_rlc_sufi_n = -1;
static int hf_rlc_sufi_sn_ack = -1;
static int hf_rlc_sufi_sn_mrw = -1;
static int hf_rlc_sufi_poll_sn = -1;
static int hf_rlc_header_only = -1;
static int hf_rlc_channel = -1;
static int hf_rlc_channel_rbid = -1;
static int hf_rlc_channel_dir = -1;
static int hf_rlc_channel_ueid = -1;
static int hf_rlc_sequence_number = -1;
static int hf_rlc_length = -1;
static int hf_rlc_bitmap_string = -1;

/* subtrees */
static int ett_rlc = -1;
static int ett_rlc_frag = -1;
static int ett_rlc_fragments = -1;
static int ett_rlc_sdu = -1;
static int ett_rlc_sufi = -1;
static int ett_rlc_bitmap = -1;
static int ett_rlc_rlist = -1;
static int ett_rlc_channel = -1;

static expert_field ei_rlc_li_reserved = EI_INIT;
static expert_field ei_rlc_he = EI_INIT;
static expert_field ei_rlc_li_incorrect_mal = EI_INIT;
static expert_field ei_rlc_sufi_cw = EI_INIT;
static expert_field ei_rlc_kasumi_implementation_missing = EI_INIT;
static expert_field ei_rlc_reassembly_unknown_error = EI_INIT;
static expert_field ei_rlc_reassembly_lingering_endpoint = EI_INIT;
static expert_field ei_rlc_sufi_len = EI_INIT;
static expert_field ei_rlc_reassembly_fail_unfinished_sequence = EI_INIT;
static expert_field ei_rlc_reassembly_fail_flag_set = EI_INIT;
static expert_field ei_rlc_sufi_type = EI_INIT;
static expert_field ei_rlc_reserved_bits_not_zero = EI_INIT;
static expert_field ei_rlc_ctrl_type = EI_INIT;
static expert_field ei_rlc_li_incorrect_warn = EI_INIT;
static expert_field ei_rlc_li_too_many = EI_INIT;
static expert_field ei_rlc_header_only = EI_INIT;
static expert_field ei_rlc_ciphered_data = EI_INIT;
static expert_field ei_rlc_no_per_frame_data = EI_INIT;
static expert_field ei_rlc_incomplete_sequence = EI_INIT;
static expert_field ei_rlc_unknown_udp_framing_tag = EI_INIT;
static expert_field ei_rlc_missing_udp_framing_tag = EI_INIT;

static dissector_handle_t ip_handle;
static dissector_handle_t rrc_handle;
static dissector_handle_t bmc_handle;

enum rlc_channel_type {
    RLC_PCCH,
    RLC_BCCH,
    RLC_UL_CCCH,
    RLC_DL_CCCH,
    RLC_UL_DCCH,
    RLC_DL_DCCH,
    RLC_PS_DTCH,
    RLC_DL_CTCH,
    RLC_UNKNOWN_CH
};

static const value_string rlc_dir_vals[] = {
    { P2P_DIR_UL, "Uplink" },
    { P2P_DIR_DL, "Downlink" },
    { 0, NULL }
};

static const true_false_string rlc_header_only_val = {
    "RLC PDU header only", "RLC PDU header and body present"
};

static const true_false_string rlc_ext_val = {
    "Next field is Length Indicator and E Bit", "Next field is data, piggybacked STATUS PDU or padding"
};

static const true_false_string rlc_dc_val = {
    "Data", "Control"
};

static const true_false_string rlc_p_val = {
    "Request a status report", "Status report not requested"
};

static const value_string rlc_he_vals[] = {
    { 0, "The succeeding octet contains data" },
    { 1, "The succeeding octet contains a length indicator and E bit" },
    { 2, "The succeeding octet contains data and the last octet of the PDU is the last octet of an SDU" },
    { 0, NULL }
};

#define RLC_STATUS      0x0
#define RLC_RESET       0x1
#define RLC_RESET_ACK   0x2
static const value_string rlc_ctrl_vals[] = {
    { RLC_STATUS,       "Status" },
    { RLC_RESET,        "Reset" },
    { RLC_RESET_ACK,    "Reset Ack" },
    { 0, NULL }
};

#define RLC_SUFI_NOMORE     0x0
#define RLC_SUFI_WINDOW     0x1
#define RLC_SUFI_ACK        0x2
#define RLC_SUFI_LIST       0x3
#define RLC_SUFI_BITMAP     0x4
#define RLC_SUFI_RLIST      0x5
#define RLC_SUFI_MRW        0x6
#define RLC_SUFI_MRW_ACK    0x7
#define RLC_SUFI_POLL       0x8
static const value_string rlc_sufi_vals[] = {
    { RLC_SUFI_NOMORE,  "No more data" },
    { RLC_SUFI_WINDOW,  "Window size" },
    { RLC_SUFI_ACK,     "Acknowledgement" },
    { RLC_SUFI_LIST,    "List" },
    { RLC_SUFI_BITMAP,  "Bitmap" },
    { RLC_SUFI_RLIST,   "Relative list" },
    { RLC_SUFI_MRW,     "Move receiving window" },
    { RLC_SUFI_MRW_ACK, "Move receiving window acknowledgement" },
    { RLC_SUFI_POLL,    "Poll" },
    { 0, NULL }
};

/* reassembly related data */
static GHashTable *fragment_table    = NULL; /* table of not yet assembled fragments */
static GHashTable *endpoints = NULL; /* List of SDU-endpoints */
static GHashTable *reassembled_table = NULL; /* maps fragment -> complete sdu */
static GHashTable *sequence_table    = NULL; /* channel -> seq */
static GHashTable *duplicate_table = NULL; /* duplicates */

/* identify an RLC channel, using one of two options:
 *  - via Radio Bearer ID and unique UE ID
 *  - via Radio Bearer ID and (VPI/VCI/CID) + Link ID
 */
struct rlc_channel {
    guint32          ueid;
    guint16          vpi;
    guint16          vci;
    guint8           cid;
    guint16          link;  /* link number */
    guint8           rbid;  /* radio bearer ID */
    guint8           dir;   /* direction */
    enum rlc_li_size li_size;
    enum rlc_mode    mode;
};

/* used for duplicate detection */
struct rlc_seq {
    guint32  frame_num;
    nstime_t arrival;
    guint16  seq;
    guint16  oc;        /* overflow counter, this is not used? */
};

struct rlc_seqlist {
    struct rlc_channel ch;
    GList *list;
    /* We will store one seqlist per channel so this is a good place to indicate
     *  whether or not this channel's reassembly has failed or not. */
    guint fail_packet; /* Equal to packet where fail flag was set or 0 otherwise. */
};

/* fragment representation */
struct rlc_frag {
    guint32             frame_num;
    struct rlc_channel  ch;
    guint16             seq;  /* RLC sequence number */
    guint16             li;   /* LI within current RLC frame */
    guint16             len;  /* length of fragment data */
    guint8             *data; /* store fragment data here */

    struct rlc_frag *next; /* next fragment */
};

struct rlc_sdu {
    tvbuff_t        *tvb;     /* contains reassembled tvb */
    guint16          len;     /* total length of reassembled SDU */
    guint16          fragcnt; /* number of fragments within this SDU */
    guint8          *data;    /* reassembled data buffer */

    struct rlc_frag *reassembled_in;
    struct rlc_frag *frags;   /* pointer to list of fragments */
    struct rlc_frag *last;    /* pointer to last fragment */
};

struct rlc_li {
    guint16     li;   /* original li */
    guint16     len;  /* length of this data fragment */
    guint8      ext;  /* extension bit value */
    proto_tree *tree; /* subtree for this LI */
};

/*** KASUMI related variables and structs ***/
typedef struct umts_kat_key{    /*Stores 128-bits KASUMI key*/
    guint64 high;       /*64 MSB*/
    guint64 low;    /*64 LSB*/
}kasumi_key;


/*Counter used as input for confidentiality algorithm*/
static guint32 ps_counter[31][2] ;
static gboolean counter_init[31][2];
static guint32 max_counter = 0;
static GTree  * counter_map;    /*Saves the countervalues at first pass through, since they will be update*/

/* hashtable functions for fragment table
 * rlc_channel -> SDU
 */
static guint
rlc_channel_hash(gconstpointer key)
{
    const struct rlc_channel *ch = (const struct rlc_channel *)key;

    if (ch->ueid)
        return ch->ueid | ch->rbid | ch->mode;

    return (ch->vci << 16) | (ch->link << 16) | ch->vpi | ch->vci;
}

static gboolean
rlc_channel_equal(gconstpointer a, gconstpointer b)
{
    const struct rlc_channel *x = (const struct rlc_channel *)a, *y = (const struct rlc_channel *)b;

    if (x->ueid || y->ueid)
        return x->ueid == y->ueid &&
            x->rbid == y->rbid &&
            x->mode == y->mode &&
            x->dir == y->dir ? TRUE : FALSE;

    return x->vpi == y->vpi &&
        x->vci == y->vci &&
        x->cid == y->cid &&
        x->rbid == y->rbid &&
        x->mode == y->mode &&
        x->dir == y->dir &&
        x->link == y->link ? TRUE : FALSE;
}

static int
rlc_channel_assign(struct rlc_channel *ch, enum rlc_mode mode, packet_info *pinfo, struct atm_phdr *atm)
{
    rlc_info        *rlcinf;
    fp_info         *fpinf;

    fpinf = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    rlcinf = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0);
    if (!fpinf || !rlcinf) return -1;

    if (rlcinf->ueid[fpinf->cur_tb]) {
        ch->ueid = rlcinf->ueid[fpinf->cur_tb];
        ch->vpi = ch->vci = ch->link = ch->cid = 0;
    } else {
        if (!atm) return -1;
        ch->ueid = 1;
        ch->vpi = atm->vpi;
        ch->vci = atm->vci;
        ch->cid = atm->aal2_cid;
        ch->link = pinfo->link_number;
    }
    ch->rbid = rlcinf->rbid[fpinf->cur_tb];
    ch->dir = pinfo->link_dir;
    ch->mode = mode;
    ch->li_size = rlcinf->li_size[fpinf->cur_tb];

    return 0;
}

static struct rlc_channel *
rlc_channel_create(enum rlc_mode mode, packet_info *pinfo, struct atm_phdr *atm)
{
    struct rlc_channel *ch;
    int rv;

    ch = (struct rlc_channel *)g_malloc0(sizeof(struct rlc_channel));
    rv = rlc_channel_assign(ch, mode, pinfo, atm);

    if (rv != 0) {
        /* channel assignment failed */
        g_free(ch);
        ch = NULL;
        REPORT_DISSECTOR_BUG("Failed to assign channel");
    }
    return ch;
}

static void
rlc_channel_delete(gpointer data)
{
    g_free(data);
}

/* hashtable functions for reassembled table
 * fragment -> SDU
 */
static guint
rlc_frag_hash(gconstpointer key)
{
    const struct rlc_frag *frag = (const struct rlc_frag *)key;
    return (frag->frame_num << 12) | frag->seq;
}

static gboolean
rlc_frag_equal(gconstpointer a, gconstpointer b)
{
    const struct rlc_frag *x = (const struct rlc_frag *)a;
    const struct rlc_frag *y = (const struct rlc_frag *)b;

    return rlc_channel_equal(&x->ch, &y->ch) &&
        x->seq == y->seq &&
        x->frame_num == y->frame_num &&
        x->li == y->li ? TRUE : FALSE;
}

static struct rlc_sdu *
rlc_sdu_create(void)
{
    struct rlc_sdu *sdu;

    sdu = (struct rlc_sdu *)wmem_alloc0(wmem_file_scope(), sizeof(struct rlc_sdu));
    return sdu;
}

static void
rlc_frag_delete(gpointer data)
{
    struct rlc_frag *frag = (struct rlc_frag *)data;

    if (frag->data) {
        g_free(frag->data);
        frag->data = NULL;
    }
}

static void
rlc_sdu_frags_delete(gpointer data)
{
    struct rlc_sdu  *sdu = (struct rlc_sdu *)data;
    struct rlc_frag *frag;

    frag = sdu->frags;
    while (frag) {
        if (frag->data) {
            g_free(frag->data);
        }
        frag->data = NULL;
        frag = frag->next;
    }
}

static int
rlc_frag_assign(struct rlc_frag *frag, enum rlc_mode mode, packet_info *pinfo,
        guint16 seq, guint16 li, struct atm_phdr *atm)
{
    frag->frame_num = pinfo->num;
    frag->seq       = seq;
    frag->li        = li;
    frag->len       = 0;
    frag->data      = NULL;
    rlc_channel_assign(&frag->ch, mode, pinfo, atm);

    return 0;
}

static int
rlc_frag_assign_data(struct rlc_frag *frag, tvbuff_t *tvb,
             guint16 offset, guint16 length)
{
    frag->len  = length;
    frag->data = (guint8 *)tvb_memdup(wmem_file_scope(), tvb, offset, length);
    return 0;
}

static struct rlc_frag *
rlc_frag_create(tvbuff_t *tvb, enum rlc_mode mode, packet_info *pinfo,
        guint16 offset, guint16 length, guint16 seq, guint16 li,
        struct atm_phdr *atm)
{
    struct rlc_frag *frag;

    frag = (struct rlc_frag *)wmem_alloc0(wmem_file_scope(), sizeof(struct rlc_frag));
    rlc_frag_assign(frag, mode, pinfo, seq, li, atm);
    rlc_frag_assign_data(frag, tvb, offset, length);

    return frag;
}

static int
rlc_cmp_seq(gconstpointer a, gconstpointer b)
{
    const struct rlc_seq *_a = (const struct rlc_seq *)a, *_b = (const struct rlc_seq *)b;

    return  _a->seq < _b->seq ? -1 :
            _a->seq > _b->seq ?  1 :
            0;
}

static int moduloCompare(guint16 a, guint16 b, guint16 modulus)
{
    int ret;
    a = a % modulus;
    b = b % modulus;

    if( a <= b ){
        ret = a - b;
    } else {
        ret = a - (b + modulus);
    }
    if( ret == (1 - modulus) ){
        ret = 1;
    }
    return ret;
}

static guint16 getChannelSNModulus(struct rlc_channel * ch_lookup)
{
    if( RLC_UM == ch_lookup->mode){ /*FIXME: This is a very heuristic way to determine SN bitwidth. */
        return 128;
    } else {
        return 4096;
    }
}

/* "Value destroy" function called each time an entry is removed
 *  from the sequence_table hash.
 * It frees the GList pointed to by the entry.
 */
static void
free_sequence_table_entry_data(gpointer data)
{
    struct rlc_seqlist *list = (struct rlc_seqlist *)data;
    if (list->list != NULL) {
        g_list_free(list->list);
        list->list = NULL;   /* for good measure */
    }
}

/** Utility functions used for various comparisons/cleanups in tree **/
static gint
rlc_simple_key_cmp(gconstpointer b_ptr, gconstpointer a_ptr, gpointer ignore _U_){
    if( GPOINTER_TO_INT(a_ptr) > GPOINTER_TO_INT(b_ptr) ){
        return  -1;
    }
    return GPOINTER_TO_INT(a_ptr) < GPOINTER_TO_INT(b_ptr);
}

static void
fragment_table_init(void)
{
    int i;
    fragment_table = g_hash_table_new_full(rlc_channel_hash, rlc_channel_equal, rlc_channel_delete, NULL);
    endpoints = g_hash_table_new_full(rlc_channel_hash, rlc_channel_equal, rlc_channel_delete, NULL);
    reassembled_table = g_hash_table_new_full(rlc_frag_hash, rlc_frag_equal,
        rlc_frag_delete, rlc_sdu_frags_delete);
    sequence_table = g_hash_table_new_full(rlc_channel_hash, rlc_channel_equal,
        NULL, free_sequence_table_entry_data);
    duplicate_table = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL);

    /*Reset and or clear deciphering variables*/
    counter_map = g_tree_new_full(rlc_simple_key_cmp,NULL,NULL,rlc_channel_delete);
    for(i = 0; i< 31; i++ ){
        ps_counter[i][0] = 0;
        ps_counter[i][1] = 0;
        counter_init[i][0] = 0;
        counter_init[i][1] = 0;
    }
    max_counter = 0;
}

static void
fragment_table_cleanup(void)
{
    g_tree_destroy(counter_map);
    g_hash_table_destroy(fragment_table);
    g_hash_table_destroy(endpoints);
    g_hash_table_destroy(reassembled_table);
    g_hash_table_destroy(sequence_table);
    g_hash_table_destroy(duplicate_table);
}

/* add the list of fragments for this sdu to 'tree' */
static void
tree_add_fragment_list(struct rlc_sdu *sdu, tvbuff_t *tvb, proto_tree *tree)
{
    proto_item      *ti;
    proto_tree      *frag_tree;
    guint16          offset;
    struct rlc_frag *sdufrag;

    ti = proto_tree_add_item(tree, hf_rlc_frags, tvb, 0, -1, ENC_NA);
    frag_tree = proto_item_add_subtree(ti, ett_rlc_fragments);
    proto_item_append_text(ti, " (%u bytes, %u fragments): ",
        sdu->len, sdu->fragcnt);
    sdufrag = sdu->frags;
    offset = 0;
    while (sdufrag) {
        if (sdufrag->len > 0) {
            proto_tree_add_uint_format(frag_tree, hf_rlc_frag, tvb, offset,
                sdufrag->len, sdufrag->frame_num, "Frame: %u, payload: %u-%u (%u bytes) (Seq: %u)",
                sdufrag->frame_num, offset, offset + sdufrag->len - 1, sdufrag->len, sdufrag->seq);
        } else {
            proto_tree_add_uint_format(frag_tree, hf_rlc_frag, tvb, offset,
                sdufrag->len, sdufrag->frame_num, "Frame: %u, payload: none (0 bytes) (Seq: %u)",
                sdufrag->frame_num, sdufrag->seq);
        }
        offset += sdufrag->len;
        sdufrag = sdufrag->next;
    }
}

/* add the list of fragments for this sdu to 'tree' */
static void
tree_add_fragment_list_incomplete(struct rlc_sdu *sdu, tvbuff_t *tvb, proto_tree *tree)
{
    proto_item      *ti;
    proto_tree      *frag_tree;
    guint16          offset;
    struct rlc_frag *sdufrag;

    ti = proto_tree_add_item(tree, hf_rlc_frags, tvb, 0, 0, ENC_NA);
    frag_tree = proto_item_add_subtree(ti, ett_rlc_fragments);
    proto_item_append_text(ti, " (%u bytes, %u fragments): ",
        sdu->len, sdu->fragcnt);
    sdufrag = sdu->frags;
    offset = 0;
    while (sdufrag) {
        proto_tree_add_uint_format(frag_tree, hf_rlc_frag, tvb, 0,
            0, sdufrag->frame_num, "Frame: %u, payload %u-%u (%u bytes) (Seq: %u)",
            sdufrag->frame_num, offset, offset + sdufrag->len - 1, sdufrag->len, sdufrag->seq);
        offset += sdufrag->len;
        sdufrag = sdufrag->next;
    }
}

/* Add the same description to too the two given proto_items */
static void
add_description(proto_item *li_ti, proto_item *length_ti,
                const char *format, ...)
{
#define MAX_INFO_BUFFER 256
    static char info_buffer[MAX_INFO_BUFFER];

    va_list ap;

    va_start(ap, format);
    g_vsnprintf(info_buffer, MAX_INFO_BUFFER, format, ap);
    va_end(ap);

    proto_item_append_text(li_ti, " (%s)", info_buffer);
    proto_item_append_text(length_ti, " (%s)", info_buffer);
}

/* add information for an LI to 'tree' */
static proto_tree *
tree_add_li(enum rlc_mode mode, struct rlc_li *li, guint8 li_idx, guint32 hdr_offs,
        gboolean li_is_on_2_bytes, tvbuff_t *tvb, proto_tree *tree)
{
    proto_item *root_ti, *ti;
    proto_tree *li_tree;
    guint32     li_offs;
    guint64     length;

    if (!tree) return NULL;

    if (li_is_on_2_bytes) {
        li_offs = hdr_offs + li_idx*2;
        root_ti = proto_tree_add_item(tree, hf_rlc_li, tvb, li_offs, 2, ENC_NA);
        li_tree = proto_item_add_subtree(root_ti, ett_rlc_frag);
        ti = proto_tree_add_bits_ret_val(li_tree, hf_rlc_li_value, tvb, li_offs*8, 15, &length, ENC_BIG_ENDIAN);

        switch (li->li) {
            case 0x0000:
                add_description(root_ti, ti, "The previous RLC PDU was exactly filled with the last segment of an RLC SDU and there is no LI that indicates the end of the RLC SDU in the previous RLC PDU");
                break;
            case 0x7ffa:
                if (mode == RLC_UM) {
                    add_description(root_ti, ti, "The first data octet in this RLC PDU is the first octet of an RLC SDU and the second last octet in this RLC PDU is the last octet of the same RLC SDU. The remaining octet in the RLC PDU is ignored");
                } else {
                    add_description(root_ti, ti, "Reserved");
                }
                break;
            case 0x7ffb:
                add_description(root_ti, ti, "The second last octet in the previous RLC PDU is the last octet of an RLC SDU and there is no LI to indicate the end of SDU. The remaining octet in the previous RLC PDU is ignored");
                break;
            case 0x7ffc:
                if (mode == RLC_UM) {
                    add_description(root_ti, ti, "The first data octet in this RLC PDU is the first octet of an RLC SDU");
                } else {
                    add_description(root_ti, ti, "Reserved");
                }
                break;
            case 0x7ffd:
                if (mode == RLC_UM) {
                    add_description(root_ti, ti, "The first data octet in this RLC PDU is the first octet of an RLC SDU and the last octet in this RLC PDU is the last octet of the same RLC SDU");
                } else {
                    add_description(root_ti, ti, "Reserved");
                }
                break;
            case 0x7ffe:
                if (mode == RLC_UM) {
                    add_description(root_ti, ti, "The RLC PDU contains a segment of an SDU but neither the first octet nor the last octet of this SDU");
                } else {
                    add_description(root_ti, ti, "The rest of the RLC PDU includes a piggybacked STATUS PDU");
                }
                break;
            case 0x7fff:
                add_description(root_ti, ti, "The rest of the RLC PDU is padding");
                break;

            default:
                add_description(root_ti, ti, "length=%u", (guint16)length);
                break;
        }
        proto_tree_add_bits_item(li_tree, hf_rlc_li_ext, tvb, li_offs*8+15, 1, ENC_BIG_ENDIAN);
    } else {
        li_offs = hdr_offs + li_idx;
        root_ti = proto_tree_add_item(tree, hf_rlc_li, tvb, li_offs, 1, ENC_NA);
        li_tree = proto_item_add_subtree(root_ti, ett_rlc_frag);
        ti = proto_tree_add_bits_ret_val(li_tree, hf_rlc_li_value, tvb, li_offs*8, 7, &length, ENC_BIG_ENDIAN);
        switch (li->li) {
            case 0x00:
                add_description(root_ti, ti, "The previous RLC PDU was exactly filled with the last segment of an RLC SDU and there is no LI that indicates the end of the RLC SDU in the previous RLC PDU");
                break;
            case 0x7c:
                if (mode == RLC_UM) {
                    add_description(root_ti, ti, "The first data octet in this RLC PDU is the first octet of an RLC SDU");
                } else {
                    add_description(root_ti, ti, "Reserved");
                }
                break;
            case 0x7d:
                if (mode == RLC_UM) {
                    add_description(root_ti, ti, "The first data octet in this RLC PDU is the first octet of an RLC SDU and the last octet in this RLC PDU is the last octet of the same RLC SDU");
                } else {
                    add_description(root_ti, ti, "Reserved");
                }
                break;
            case 0x7e:
                if (mode == RLC_UM) {
                    add_description(root_ti, ti, "The RLC PDU contains a segment of an SDU but neither the first octet nor the last octet of this SDU");
                } else {
                    add_description(root_ti, ti, "The rest of the RLC PDU includes a piggybacked STATUS PDU");
                }
                break;
            case 0x7f:
                add_description(root_ti, ti, "The rest of the RLC PDU is padding");
                break;

            default:
                add_description(root_ti, ti, "length=%u", (guint16)length);
                break;
        }
        proto_tree_add_bits_item(li_tree, hf_rlc_li_ext, tvb, li_offs*8+7, 1, ENC_BIG_ENDIAN);
    }

    if (li->len > 0) {
        if (li->li > tvb_reported_length_remaining(tvb, hdr_offs)) return li_tree;
        if (li->len > li->li) return li_tree;
        ti = proto_tree_add_item(li_tree, hf_rlc_li_data, tvb, hdr_offs + li->li - li->len, li->len, ENC_NA);
        PROTO_ITEM_SET_HIDDEN(ti);
    }

    return li_tree;
}

/* add a fragment to an SDU */
static int
rlc_sdu_add_fragment(enum rlc_mode mode, struct rlc_sdu *sdu, struct rlc_frag *frag)
{
    struct rlc_frag *tmp;

    if (!sdu->frags) {
        /* insert as first element */
        sdu->frags = frag;
        sdu->last = frag;
        sdu->fragcnt++;
        sdu->len += frag->len;
        return 0;
    }
    switch (mode) {
        case RLC_UM:
            /* insert as last element */
            sdu->last->next = frag;
            frag->next = NULL;
            sdu->last = frag;
            sdu->len += frag->len;
            break;
        case RLC_AM:
            /* insert ordered */
            tmp = sdu->frags;

            /* If receiving exotic border line sequence, e.g. 4094, 4095, 0, 1 */
            if (frag->seq+2048 < tmp->seq) {
                while (tmp->next && frag->seq+2048 < tmp->seq)
                    tmp = tmp->next;
                if (tmp->next == NULL) {
                    tmp->next = frag;
                    sdu->last = frag;
                } else {
                    while (tmp->next && tmp->next->seq < frag->seq)
                        tmp = tmp->next;
                    frag->next = tmp->next;
                    tmp->next = frag;
                    if (frag->next == NULL) sdu->last = frag;
                }
            } else { /* Receiving ordinary sequence */
                if (frag->seq < tmp->seq) {
                    /* insert as first element */
                    frag->next = tmp;
                    sdu->frags = frag;
                } else {
                    while (tmp->next && tmp->next->seq < frag->seq)
                        tmp = tmp->next;
                    frag->next = tmp->next;
                    tmp->next = frag;
                    if (frag->next == NULL) sdu->last = frag;
                }
            }
            sdu->len += frag->len;
            break;
        default:
            return -2;
    }
    sdu->fragcnt++;
    return 0;
}

static void
reassemble_data(struct rlc_channel *ch, struct rlc_sdu *sdu, struct rlc_frag *frag)
{
    struct rlc_frag *temp;
    guint16          offs = 0;

    if (!sdu || !ch || !sdu->frags) return;

    if (sdu->data) return; /* already assembled */

    if (frag)
        sdu->reassembled_in = frag;
    else
        sdu->reassembled_in = sdu->last;

    sdu->data = (guint8 *)wmem_alloc(wmem_file_scope(), sdu->len);
    temp = sdu->frags;
    while (temp && ((offs + temp->len) <= sdu->len)) {
        memcpy(sdu->data + offs, temp->data, temp->len);
        wmem_free(wmem_file_scope(), temp->data);
        temp->data = NULL;
        /* mark this fragment in reassembled table */
        g_hash_table_insert(reassembled_table, temp, sdu);

        offs += temp->len;
        temp = temp->next;
    }
}

#define RLC_ADD_FRAGMENT_FAIL_PRINT 0
#define RLC_ADD_FRAGMENT_DEBUG_PRINT 0
#if RLC_ADD_FRAGMENT_DEBUG_PRINT
static void
printends(GList * list)
{
    if (list == NULL)
        return;
    g_print("-> length: %d\n[", g_list_length(list));
    while (list)
    {
        g_print("%d ", GPOINTER_TO_INT(list->data));
        list = list->next;
    }
    g_print("]\n");
}
#endif

static struct rlc_frag **
get_frags(packet_info * pinfo, struct rlc_channel * ch_lookup, struct atm_phdr *atm)
{
    gpointer value = NULL;
    struct rlc_frag ** frags = NULL;
    /* Look for already created frags table */
    if (g_hash_table_lookup_extended(fragment_table, ch_lookup, NULL, &value)) {
        frags = (struct rlc_frag **)value;
    } else if (pinfo != NULL) {
        struct rlc_channel *ch;
        ch = rlc_channel_create(ch_lookup->mode, pinfo, atm);
        frags = (struct rlc_frag **)wmem_alloc0(wmem_file_scope(), sizeof(struct rlc_frag *) * 4096);
        g_hash_table_insert(fragment_table, ch, frags);
    } else {
        return NULL;
    }
    return frags;
}
static struct rlc_seqlist *
get_endlist(packet_info * pinfo, struct rlc_channel * ch_lookup, struct atm_phdr *atm)
{
    gpointer value = NULL;
    struct rlc_seqlist * endlist = NULL;
    /* If there already exists a frag table for this channel use that one. */
    if (g_hash_table_lookup_extended(endpoints, ch_lookup, NULL, &value)) {
        endlist = (struct rlc_seqlist *)value;
    } else if (pinfo != NULL) { /* Else create a new one. */
        struct rlc_channel * ch;

        endlist = wmem_new(wmem_file_scope(), struct rlc_seqlist);
        ch = rlc_channel_create(ch_lookup->mode, pinfo, atm);
        endlist->fail_packet = 0;
        endlist->list = NULL;
        endlist->list = g_list_prepend(endlist->list, GINT_TO_POINTER(-1));
        g_hash_table_insert(endpoints, ch, endlist);
    } else {
        return NULL;
    }
    return endlist;
}

static void
reassemble_sequence(struct rlc_frag ** frags, struct rlc_seqlist * endlist,
                    struct rlc_channel * ch_lookup, guint16 start, guint16 end)
{
    GList * element = NULL;
    struct rlc_sdu * sdu = rlc_sdu_create();

    guint16 snmod = getChannelSNModulus(ch_lookup);

    /* Insert fragments into SDU. */
    for (; moduloCompare(start,end,snmod ) <= 0; start = (start+1)%snmod)
    {
        struct rlc_frag * tempfrag = NULL;
        tempfrag = frags[start]->next;
        frags[start]->next = NULL;
        rlc_sdu_add_fragment(ch_lookup->mode, sdu, frags[start]);
        frags[start] = tempfrag;
    }

    /* Remove first endpoint. */
    element = g_list_first(endlist->list);
    if (element) {
        endlist->list = g_list_remove_link(endlist->list, element);
        if (frags[end] != NULL) {
            if (endlist->list) {
                endlist->list->data = GINT_TO_POINTER((GPOINTER_TO_INT(endlist->list->data) - 1 + snmod) % snmod);
            }
        }
    }
    reassemble_data(ch_lookup, sdu, NULL);
}

/* Reset the specified channel's reassembly data, useful for when a sequence
 * resets on transport channel swap. */
void
rlc_reset_channel(enum rlc_mode mode, guint8 rbid, guint8 dir, guint32 ueid,
                  struct atm_phdr *atm)
{
    struct rlc_frag ** frags = NULL;
    struct rlc_seqlist * endlist = NULL;
    struct rlc_channel ch_lookup;
    guint i;

    ch_lookup.mode = mode;
    ch_lookup.rbid = rbid;
    ch_lookup.dir = dir;
    ch_lookup.ueid = ueid;
    frags = get_frags(NULL, &ch_lookup, atm);
    endlist = get_endlist(NULL, &ch_lookup, atm);
    DISSECTOR_ASSERT(frags && endlist);

    endlist->fail_packet = 0;
    g_list_free(endlist->list);
    endlist->list = NULL;

    for (i = 0; i < 4096; i++) {
        frags[i] = NULL;
    }
}

/* add a new fragment to an SDU
 * if length == 0, just finalize the specified SDU
 */
static struct rlc_frag *
add_fragment(enum rlc_mode mode, tvbuff_t *tvb, packet_info *pinfo,
         proto_tree *tree, guint16 offset, guint16 seq, guint16 num_li,
         guint16 len, gboolean final, struct atm_phdr *atm)
{
    struct rlc_channel  ch_lookup;
    struct rlc_frag     frag_lookup, *frag = NULL;
    gpointer            orig_key = NULL, value = NULL;
    struct rlc_sdu     *sdu = NULL;
    struct rlc_frag ** frags = NULL;
    struct rlc_seqlist * endlist = NULL;
    GList * element = NULL;
    int snmod;

    if (rlc_channel_assign(&ch_lookup, mode, pinfo, atm) == -1) {
        return NULL;
    }
    rlc_frag_assign(&frag_lookup, mode, pinfo, seq, num_li, atm);
    #if RLC_ADD_FRAGMENT_DEBUG_PRINT
        g_print("packet: %d, channel (%d %d %d) seq: %u, num_li: %u, offset: %u, \n", pinfo->num, ch_lookup.dir, ch_lookup.rbid, ch_lookup.ueid, seq, num_li, offset);
    #endif

    snmod = getChannelSNModulus(&ch_lookup);

    /* look for an already assembled SDU */
    if (g_hash_table_lookup_extended(reassembled_table, &frag_lookup, &orig_key, &value)) {
        /* this fragment is already reassembled somewhere */
        frag = (struct rlc_frag *)orig_key;
        sdu = (struct rlc_sdu *)value;
        if (tree) {
            /* mark the fragment, if reassembly happened somewhere else */
            if (frag->seq != sdu->reassembled_in->seq ||
                frag->li != sdu->reassembled_in->li)
                proto_tree_add_uint(tree, hf_rlc_reassembled_in, tvb, 0, 0,
                    sdu->reassembled_in->frame_num);
        }
        return frag;
    }

    frags = get_frags(pinfo, &ch_lookup, atm);
    endlist = get_endlist(pinfo, &ch_lookup, atm);

    /* If already done reassembly */
    if (pinfo->fd->flags.visited) {
        if (tree && len > 0) {
            if (endlist->list && endlist->list->next) {
                gint16 start = (GPOINTER_TO_INT(endlist->list->data) + 1) % snmod;
                gint16 end = GPOINTER_TO_INT(endlist->list->next->data);
                gint16 missing = start;
                gboolean wecanreasmmore = TRUE;

                for (; moduloCompare(missing,end,snmod ) <= 0; missing = (missing+1)%snmod)
                {
                    if (frags[missing] == NULL) {
                        wecanreasmmore = FALSE;
                        break;
                    }
                }

                if (wecanreasmmore) {
                    reassemble_sequence(frags, endlist, &ch_lookup, start, end);
                } else {
                    if (end >= 0 && end < snmod && frags[end]) {
                        proto_tree_add_expert_format(tree, pinfo, &ei_rlc_reassembly_fail_unfinished_sequence, tvb, 0, 0,
                                        "Did not perform reassembly because of unfinished sequence (%d->%d [packet %u]), could not find %d.", start, end, frags[end]->frame_num, missing);
                    } else {
                        proto_tree_add_expert_format(tree, pinfo, &ei_rlc_reassembly_fail_unfinished_sequence, tvb, 0, 0,
                                        "Did not perform reassembly because of unfinished sequence (%d->%d [could not determine packet]), could not find %d.", start, end, missing);
                    }
                }
            } else if (endlist->list) {
                if (endlist->fail_packet != 0 && endlist->fail_packet <= pinfo->num) {
                    proto_tree_add_expert_format(tree, pinfo, &ei_rlc_reassembly_fail_flag_set, tvb, 0, 0, "Did not perform reassembly because fail flag was set in packet %u.", endlist->fail_packet);
                } else {
                    gint16 end = GPOINTER_TO_INT(endlist->list->data);
                    if (end >= 0 && end < snmod && frags[end]) {
                        proto_tree_add_expert_format(tree, pinfo, &ei_rlc_reassembly_lingering_endpoint, tvb, 0, 0, "Did not perform reassembly because of unfinished sequence, found lingering endpoint (%d [packet %d]).", end, frags[end]->frame_num);
                    } else {
                        proto_tree_add_expert_format(tree, pinfo, &ei_rlc_reassembly_lingering_endpoint, tvb, 0, 0, "Did not perform reassembly because of unfinished sequence, found lingering endpoint (%d [could not determine packet]).", end);
                    }
                }
            } else {
                expert_add_info(pinfo, NULL, &ei_rlc_reassembly_unknown_error);
            }
        }
        return NULL; /* If already done reassembly and no SDU found, too bad */
    }

    if (endlist->fail_packet != 0) { /* don't continue after sh*t has hit the fan */
        return NULL;
    }

    frag = rlc_frag_create(tvb, mode, pinfo, offset, len, seq, num_li, atm);

    /* If frags[seq] is not NULL then we must have data from several PDUs in the
     * same RLC packet (using Length Indicators) or something has gone terribly
     * wrong. */
    if (frags[seq] != NULL) {
        if (num_li > 0) {
            struct rlc_frag * tempfrag = frags[seq];
            while (tempfrag->next != NULL)
                tempfrag = tempfrag->next;
            tempfrag->next = frag;
        } else { /* This should never happen */
            endlist->fail_packet = pinfo->num;
            return NULL;
        }
    } else {
        frags[seq] = frag;
    }

    /* It is also possible that frags[seq] is NULL even though we do have data
     * from several PDUs in the same RLC packet. This is if the reassembly is
     * not lagging behind at all because of perfectly ordered sequences. */
    if (endlist->list && num_li != 0) {
        gint16 first = GPOINTER_TO_INT(endlist->list->data);
        if (seq == first) {
            endlist->list->data = GINT_TO_POINTER(first-1);
        }
    }

    /* If this is an endpoint */
    if (final) {
        endlist->list = g_list_append(endlist->list, GINT_TO_POINTER((gint)seq));
    }

    #if RLC_ADD_FRAGMENT_DEBUG_PRINT
    printends(endlist->list);
    #endif

    /* Try to reassemble SDU. */
    if (endlist->list && endlist->list->next) {
        gint16 start = (GPOINTER_TO_INT(endlist->list->data) + 1) % snmod;
        gint16 end = GPOINTER_TO_INT(endlist->list->next->data);
        if (frags[end] == NULL) {
#if RLC_ADD_FRAGMENT_FAIL_PRINT
            proto_tree_add_debug_text(tree, "frag[end] is null, this is probably because end was a startpoint but because of some error ended up being treated as an endpoint, setting fail flag, start %d, end %d, packet %u\n", start, end, pinfo->num);
#endif
            endlist->fail_packet = pinfo->num;
            return NULL;
        }

        /* If our endpoint is a LI=0 with no data. */
        if (start == end && frags[start]->len == 0) {
            element = g_list_first(endlist->list);
            if (element) {
                endlist->list = g_list_remove_link(endlist->list, element);
            }
            frags[start] = frags[start]->next;

            /* If frags[start] is not NULL now, then that means that there was
             * another fragment with the same seq number because of LI. If we
             * don't decrease the endpoint by 1 then that fragment will be
             * skipped and all hell will break lose. */
            if (frags[start] != NULL) {
                endlist->list->data = GINT_TO_POINTER(start-1);
            }
            /* NOTE: frags[start] is wmem_alloc'ed and will remain until file closes, we would want to free it here maybe. */
            return NULL;
        }

        #if RLC_ADD_FRAGMENT_DEBUG_PRINT
        g_print("start: %d, end: %d\n",start, end);
        #endif

        for (;  moduloCompare(start,end,snmod ) < 0; start = (start+1)%snmod)
        {
            if (frags[start] == NULL) {
                if (MIN((start-seq+snmod)%snmod, (seq-start+snmod)%snmod) >= snmod/4) {
#if RLC_ADD_FRAGMENT_FAIL_PRINT
                    proto_tree_add_debug_text(tree,
"Packet %u. Setting fail flag because RLC fragment with sequence number %u was \
too far away from an unfinished sequence (%u->%u). The missing sequence number \
is %u. The most recently complete sequence ended in packet %u.", pinfo->num, seq, 0, end, start, 0);
#endif
                    endlist->fail_packet = pinfo->num; /* If it has gone too far, give up */
                    return NULL;
                }
                return frag;
            }
        }
        start = (GPOINTER_TO_INT(endlist->list->data) + 1) % snmod;
        reassemble_sequence(frags, endlist, &ch_lookup, start, end);
    } else if (endlist->list) {
        gint16 first = (GPOINTER_TO_INT(endlist->list->data) + 1) % snmod;
        /* If the distance between the oldest stored endpoint in endlist and
         * this endpoint is too large, set fail flag. */
        if (MIN((first-seq+snmod)%snmod, (seq-first+snmod)%snmod) >= snmod/4) {
#if RLC_ADD_FRAGMENT_FAIL_PRINT
            proto_tree_add_debug_text(tree,
"Packet %u. Setting fail flag because RLC fragment with sequence number %u was \
too far away from an unfinished sequence with start %u and without end.", pinfo->num, seq, first);
#endif
            endlist->fail_packet = pinfo->num; /* Give up if things have gone too far. */
            return NULL;
        }
    }

    return frag;
}

/* is_data is used to identify rlc data parts that are not identified by an LI, but are at the end of
 * the RLC frame
 * these can be valid reassembly points, but only if the LI of the *next* relevant RLC frame is
 * set to '0' (this is indicated in the reassembled SDU
 */
static tvbuff_t *
get_reassembled_data(enum rlc_mode mode, tvbuff_t *tvb, packet_info *pinfo,
             proto_tree *tree, guint16 seq, guint16 num_li,
             struct atm_phdr *atm)
{
    gpointer         orig_frag, orig_sdu;
    struct rlc_sdu  *sdu;
    struct rlc_frag  lookup, *frag;

    rlc_frag_assign(&lookup, mode, pinfo, seq, num_li, atm);

    if (!g_hash_table_lookup_extended(reassembled_table, &lookup,
        &orig_frag, &orig_sdu))
        return NULL;

    sdu = (struct rlc_sdu *)orig_sdu;
    if (!sdu || !sdu->data)
        return NULL;

    /* TODO */
#if 0
    if (!rlc_frag_equal(&lookup, sdu->reassembled_in)) return NULL;
#endif

    frag = sdu->frags;
    while (frag->next) {
        if (frag->next->seq - frag->seq > 1) {
            proto_tree_add_expert(tree, pinfo, &ei_rlc_incomplete_sequence, tvb, 0, 0);
            tree_add_fragment_list_incomplete(sdu, tvb, tree);
            return NULL;
        }
        frag = frag->next;
    }

    sdu->tvb = tvb_new_child_real_data(tvb, sdu->data, sdu->len, sdu->len);
    add_new_data_source(pinfo, sdu->tvb, "Reassembled RLC Message");

    /* reassembly happened here, so create the fragment list */
    if (tree && sdu->fragcnt > 1)
        tree_add_fragment_list(sdu, sdu->tvb, tree);

    return sdu->tvb;
}

#define RLC_RETRANSMISSION_TIMEOUT 5 /* in seconds */
static gboolean
rlc_is_duplicate(enum rlc_mode mode, packet_info *pinfo, guint16 seq,
         guint32 *original, struct atm_phdr *atm)
{
    GList              *element;
    struct rlc_seqlist  lookup, *list;
    struct rlc_seq      seq_item, *seq_new;
    guint16 snmod;
    nstime_t delta;
    gboolean is_duplicate,is_unseen;

    if (rlc_channel_assign(&lookup.ch, mode, pinfo, atm) == -1)
        return FALSE;
    list = (struct rlc_seqlist *)g_hash_table_lookup(sequence_table, &lookup.ch);
    if (!list) {
        /* we see this channel for the first time */
        list = (struct rlc_seqlist *)wmem_alloc0(wmem_file_scope(), sizeof(*list));
        rlc_channel_assign(&list->ch, mode, pinfo, atm);
        g_hash_table_insert(sequence_table, &list->ch, list);
    }
    seq_item.seq = seq;
    seq_item.frame_num = pinfo->num;

    /* When seq is 12 bit (in RLC protocol), it will wrap around after 4096. */
    /* Window size is at most 4095 so we remove packets further away than that */
    element = g_list_first(list->list);
    snmod = getChannelSNModulus(&lookup.ch);
    if (element) {
        seq_new = (struct rlc_seq *)element->data;
        /* Add SN modulus because %-operation for negative values in C is not equal to mathematical modulus */
        if (MIN((seq_new->seq-seq+snmod)%snmod, (seq-seq_new->seq+snmod)%snmod) >= snmod/4) {
            list->list = g_list_remove_link(list->list, element);
        }
    }

    is_duplicate = FALSE;
    is_unseen = TRUE;
    element = g_list_find_custom(list->list, &seq_item, rlc_cmp_seq);
    while(element) {
        /* Check if this is a different frame (by comparing frame numbers) which arrived less than */
        /* RLC_RETRANSMISSION_TIMEOUT seconds ago */
        seq_new = (struct rlc_seq *)element->data;
        if (seq_new->frame_num < seq_item.frame_num) {
            nstime_delta(&delta, &pinfo->abs_ts, &seq_new->arrival);
            if (delta.secs < RLC_RETRANSMISSION_TIMEOUT) {
                /* This is a duplicate. */
                if (original) {
                    /* Save the frame number where our sequence number was previously seen */
                    *original = seq_new->frame_num;
                }
                is_duplicate = TRUE;
            }
        }
        else if (seq_new->frame_num == seq_item.frame_num) {
            /* Check if our frame is already in the list and this is a secondary check.*/
            /* in this case raise a flag so the frame isn't entered more than once to the list */
            is_unseen = FALSE;
        }
        element = g_list_find_custom(element->next, &seq_item, rlc_cmp_seq);
    }
    if(is_unseen) {
        /* Add to list for the first time this frame is checked */
        seq_new = (struct rlc_seq *)wmem_alloc0(wmem_file_scope(), sizeof(struct rlc_seq));
        *seq_new = seq_item;
        seq_new->arrival = pinfo->abs_ts;
        list->list = g_list_append(list->list, seq_new); /* insert in order of arrival */
    }
    return is_duplicate;
}

static void
rlc_call_subdissector(enum rlc_channel_type channel, tvbuff_t *tvb,
              packet_info *pinfo, proto_tree *tree)
{
    enum rrc_message_type msgtype;
    switch (channel) {
        case RLC_UL_CCCH:
            msgtype = RRC_MESSAGE_TYPE_UL_CCCH;
            break;
        case RLC_DL_CCCH:
            msgtype = RRC_MESSAGE_TYPE_DL_CCCH;
            break;
        case RLC_DL_CTCH:
            msgtype = RRC_MESSAGE_TYPE_INVALID;
            call_dissector(bmc_handle, tvb, pinfo, tree);
            /* once the packet has been dissected, protect it from further changes using a 'fence' in the INFO column */
            col_append_str(pinfo->cinfo, COL_INFO," ");
            col_set_fence(pinfo->cinfo, COL_INFO);
            break;
        case RLC_UL_DCCH:
            msgtype = RRC_MESSAGE_TYPE_UL_DCCH;
            break;
        case RLC_DL_DCCH:
            msgtype = RRC_MESSAGE_TYPE_DL_DCCH;
            break;
        case RLC_PCCH:
            msgtype = RRC_MESSAGE_TYPE_PCCH;
            break;
        case RLC_BCCH:
            msgtype = RRC_MESSAGE_TYPE_BCCH_FACH;
            break;
        case RLC_PS_DTCH:
            msgtype = RRC_MESSAGE_TYPE_INVALID;
            /* assume transparent PDCP for now */
            call_dissector(ip_handle, tvb, pinfo, tree);
            /* once the packet has been dissected, protect it from further changes using a 'fence' in the INFO column */
            col_append_str(pinfo->cinfo, COL_INFO," ");
            col_set_fence(pinfo->cinfo, COL_INFO);
            break;
        default:
            return; /* stop dissecting */
    }
    if (msgtype != RRC_MESSAGE_TYPE_INVALID) {
        struct rrc_info *rrcinf;
        fp_info *fpinf;
        fpinf = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
        rrcinf = (rrc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_rrc, 0);
        if (!rrcinf) {
            rrcinf = (rrc_info *)wmem_alloc0(wmem_file_scope(), sizeof(struct rrc_info));
            p_add_proto_data(wmem_file_scope(), pinfo, proto_rrc, 0, rrcinf);
        }
        rrcinf->msgtype[fpinf->cur_tb] = msgtype;
        call_dissector(rrc_handle, tvb, pinfo, tree);
        /* once the packet has been dissected, protect it from further changes using a 'fence' in the INFO column */
        col_append_str(pinfo->cinfo, COL_INFO," ");
        col_set_fence(pinfo->cinfo, COL_INFO);
    }
}

static void
add_channel_info(packet_info * pinfo, proto_tree * tree, fp_info * fpinf, rlc_info * rlcinf)
{
    proto_item * item;
    proto_tree * channel_tree ;

    item = proto_tree_add_item(tree, hf_rlc_channel, NULL, 0, 0, ENC_NA);
    channel_tree = proto_item_add_subtree(item, ett_rlc_channel);
    proto_item_append_text(item, " (rbid: %u, dir: %s, uid: 0x%08x)", rlcinf->rbid[fpinf->cur_tb],
                           val_to_str_const(pinfo->link_dir, rlc_dir_vals, "Unknown"), rlcinf->ueid[fpinf->cur_tb]);
    PROTO_ITEM_SET_GENERATED(item);
    item = proto_tree_add_uint(channel_tree, hf_rlc_channel_rbid, NULL, 0, 0, rlcinf->rbid[fpinf->cur_tb]);
    PROTO_ITEM_SET_GENERATED(item);
    item = proto_tree_add_uint(channel_tree, hf_rlc_channel_dir, NULL, 0, 0, pinfo->link_dir);
    PROTO_ITEM_SET_GENERATED(item);
    item = proto_tree_add_uint(channel_tree, hf_rlc_channel_ueid, NULL, 0, 0, rlcinf->ueid[fpinf->cur_tb]);
    PROTO_ITEM_SET_GENERATED(item);

}

#ifdef HAVE_UMTS_KASUMI
static guint8 *
translate_hex_key(gchar * char_key){
    int i,j;
    guint8 * key_in;

    key_in = wmem_alloc0(wmem_packet_scope(), sizeof(guint8)*16);
    j= (int)(strlen(char_key)/2)-1;
    /*Translate "hex-string" into a byte aligned block */
    for(i = (int)strlen(char_key); i> 0; i-=2 ){
        key_in[j] =  ( (guint8)  (strtol( &char_key[i-2], NULL, 16 ) ));
        char_key[i-2] = '\0';
        j--;
    }
    return key_in;

}
#endif

/** @brief Deciphers a given tvb
 *
 * Note that the actual KASUMI implementation needs to be placed into
 * epan/crypt/kasumi.* by "end users" since due to patents the actual implementation
 * cannot be distributed openly at the moment.
 *
 * Refer to 3GPP TS 35.201 and 3GPP TS 35.202 for further information.
 *
 *  @param tvb The ciphered data.
 *  @param  pinfo Packet info.
 *  @param counter the COUNTER value input
 *  @param rbid the radiobear id
 *  @param dir Direction of the link
 *  @param header_size Size of the unciphered header
 *  @return tvb Returns a deciphered tvb
 */
static tvbuff_t *
#ifndef HAVE_UMTS_KASUMI
rlc_decipher_tvb(tvbuff_t *tvb _U_, packet_info *pinfo, guint32 counter _U_,
                 guint8 rbid _U_, gboolean dir _U_, guint8 header_size _U_) {
    /*Check if we have a KASUMI implementation*/
    expert_add_info(pinfo, NULL, &ei_rlc_kasumi_implementation_missing);
    return NULL;
#else
rlc_decipher_tvb(tvbuff_t *tvb, packet_info *pinfo, guint32 counter, guint8 rbid, gboolean dir, guint8 header_size) {
    guint8* out=NULL,*key_in = NULL;
    tvbuff_t *t;

    /*Fix the key into a byte block*/
    /*TODO: This should be done in a preferences callback function*/
    out = wmem_alloc0(wmem_packet_scope(), strlen(global_rlc_kasumi_key)+1);
    memcpy(out,global_rlc_kasumi_key,strlen(global_rlc_kasumi_key));    /*Copy from prefrence const pointer*/
    key_in = translate_hex_key(out);    /*Translation*/

    /*Location for decrypted data & original RLC header*/
    out = tvb_memdup(pinfo->pool, tvb, 0, tvb_captured_length(tvb));

    /*Call f8 confidentiality function, note that rbid is zero indexed*/
    f8( key_in, counter, rbid-1, dir, &out[header_size], (tvb_captured_length(tvb)-header_size)*8 );

    /*Create new tvb.*/
    t = tvb_new_real_data(out,tvb_captured_length(tvb), tvb_reported_length(tvb));
    add_new_data_source(pinfo, t, "Deciphered RLC");
    return t;
#endif /* HAVE_UMTS_KASUMI */
}

/** @brief Checks if an RLC packet is ciphered, according to information reported from the RRC layer
 *
 *  @param pinfo Packet info.
 *  @param fpinf FP info
 *  @param rlcinf RLC info
 *  @param seq Sequence number of the RLC packet
 *  @return gboolean Returns TRUE if the packet is ciphered and false otherwise
 */
static gboolean
is_ciphered_according_to_rrc(packet_info *pinfo, fp_info *fpinf, rlc_info *rlcinf ,guint16 seq) {
    gint16              cur_tb;
    guint32             ueid;
    rrc_ciphering_info *ciphering_info;
    guint8              rbid;
    guint8              direction;
    guint32             security_mode_frame_num;
    gint32              ciphering_begin_seq;

    if(global_ignore_rrc_ciphering_indication) {
        return FALSE;
    }

    cur_tb = fpinf->cur_tb;
    ueid = rlcinf->ueid[cur_tb];
    ciphering_info =  (rrc_ciphering_info *)g_tree_lookup(rrc_ciph_info_tree, GINT_TO_POINTER((gint)ueid));
    if(ciphering_info != NULL) {
        rbid = rlcinf->rbid[cur_tb];
        direction = fpinf->is_uplink ? P2P_DIR_UL : P2P_DIR_DL;
        security_mode_frame_num = ciphering_info->setup_frame[direction];
        ciphering_begin_seq = ciphering_info->seq_no[rbid][direction];
        /* Making sure the rrc security message's frame number makes sense */
        if( security_mode_frame_num > 0 && security_mode_frame_num <= pinfo->num) {
            /* Making sure the sequence number where ciphering starts makes sense */
            /* TODO: This check is incorrect if the sequence numbers wrap around */
            if(ciphering_begin_seq >= 0 && ciphering_begin_seq <= seq){
                return TRUE;
            }
        }
    }
    return FALSE;
}

/*
 * @param key is created with GINT_TO_POINTER
 * @param value is a pointer to a guint32
 * @param data is a pointer to a guint32
 */
static gboolean
iter_same(gpointer key, gpointer value, gpointer data) {
    /*If true we found the correct frame*/
    if ((guint32)GPOINTER_TO_INT(key) > *(guint32*)data){
        *((guint32*)data) = *((guint32*)value);
        return TRUE;
    }
    *((guint32*)data) = (guint32)GPOINTER_TO_INT(key);

    return TRUE;
}

/**
 * Used for looking up and old ciphering counter value in the counter_map tree.
 * @param key is created with GINT_TO_POINTER
 * @param value is pointer to an array of 2 guint32s
 * @param data is a pointer to an array of 3 guint32s
 */
static gboolean
rlc_find_old_counter(gpointer key, gpointer value, gpointer data) {

    /*If true we found the correct frame*/
    if( (guint32)GPOINTER_TO_INT(key) >= ((guint32 *)data)[0] ){
        return TRUE;
    }
    /*Overwrite the data since the previous one wasn't correct*/
    ((guint32*)data)[1] = ((guint32*)value)[0];
    ((guint32*)data)[2] = ((guint32*)value)[1];

    return FALSE;
}

static void
rlc_decipher(tvbuff_t *tvb, packet_info * pinfo, proto_tree * tree, fp_info * fpinf,
             rlc_info * rlcinf, guint16 seq, enum rlc_mode mode)
{
    rrc_ciphering_info *ciphering_info;
    guint8 indx, header_size, hfn_shift;
    gint16 pos;
    guint8 ext;
    int ciphered_data_hf;

    indx = fpinf->is_uplink ? P2P_DIR_UL : P2P_DIR_DL;
    pos = fpinf->cur_tb;
    if (mode ==RLC_UM) {
        header_size = 1;
        hfn_shift = 7;
    } else {
        header_size = 2;
        hfn_shift = 12;
    }

    /*Ciphering info singled in RRC by securitymodecommands */
    ciphering_info =  (rrc_ciphering_info *)g_tree_lookup(rrc_ciph_info_tree, GINT_TO_POINTER((gint)rlcinf->ueid[fpinf->cur_tb]));

    /*TODO: This doesn't really work for all packets..*/
    /*Check if we have ciphering info and that this frame is ciphered*/
    if(ciphering_info!=NULL && ( (ciphering_info->setup_frame[indx] > 0 && ciphering_info->setup_frame[indx] < pinfo->num && ciphering_info->seq_no[rlcinf->rbid[pos]][indx] == -1)  ||
                     (ciphering_info->setup_frame[indx] < pinfo->num && ciphering_info->seq_no[rlcinf->rbid[pos]][indx] >= 0  && ciphering_info->seq_no[rlcinf->rbid[pos]][indx] <= seq) )){

        tvbuff_t *t;

        /*Check if this counter has been initialized*/
        if(!counter_init[rlcinf->rbid[pos]][indx] ){
            guint32 frame_num = pinfo->num;

            /*Initializes counter*/
            counter_init[rlcinf->rbid[pos]][0] = TRUE;
            counter_init[rlcinf->rbid[pos]][1] = TRUE;
            /*Find appropriate start value*/
            g_tree_foreach(ciphering_info->start_ps, (GTraverseFunc)iter_same, &frame_num);

            /*Set COUNTER value accordingly as specified by 6.4.8 in 3GPP TS 33.102 */
            if(max_counter +2 > frame_num && ciphering_info->seq_no[rlcinf->rbid[pos]][indx] == -1){
                ps_counter[rlcinf->rbid[pos]][0] = (max_counter+2) << hfn_shift;
                ps_counter[rlcinf->rbid[pos]][1] = (max_counter+2) << hfn_shift;
            }else{
                ps_counter[rlcinf->rbid[pos]][0] = frame_num << hfn_shift;
                ps_counter[rlcinf->rbid[pos]][1] = frame_num << hfn_shift;
            }

            if(!tree){
                /*Preserve counter value for next dissection round*/
                guint32 * ciph;
                ciph = (guint32 *)g_malloc(sizeof(guint32)*2);
                ciph[0] = ps_counter[rlcinf->rbid[pos]][0];
                ciph[1] = ps_counter[rlcinf->rbid[pos]][1];
                g_tree_insert(counter_map, GINT_TO_POINTER((gint)pinfo->num), ciph);
            }

        }
        /*Update the maximal COUNTER value seen so far*/
        max_counter = MAX(max_counter,((ps_counter[rlcinf->rbid[pos]][indx]) | seq) >> hfn_shift);

    /*XXX: Since RBID in umts isn't configured properly..*/
        if(rlcinf->rbid[pos] == 9 ){
            if(tree){
                guint32 frame_num[3];
                /*Set frame num we will be "searching" around*/
                frame_num[0] = pinfo->num;
                /*Find the correct counter value*/
                g_tree_foreach(counter_map, (GTraverseFunc)rlc_find_old_counter, &frame_num[0]);
                t = rlc_decipher_tvb(tvb, pinfo, (frame_num[indx+1] | seq),16,!fpinf->is_uplink,header_size);
            }else{
                t = rlc_decipher_tvb(tvb, pinfo, ((ps_counter[rlcinf->rbid[pos]][indx]) | seq),16,!fpinf->is_uplink,header_size);
            }
        }else{
            if(tree){
                /*We need to find the original counter value for second dissection pass*/
                guint32 frame_num[3];
                frame_num[0] = pinfo->num;
                g_tree_foreach(counter_map, (GTraverseFunc)rlc_find_old_counter, &frame_num[0]);
                t = rlc_decipher_tvb(tvb, pinfo, (frame_num[indx+1] | seq),rlcinf->rbid[pos],!fpinf->is_uplink,header_size);
            }else
                t = rlc_decipher_tvb(tvb, pinfo, ((ps_counter[rlcinf->rbid[pos]][indx]) | seq),rlcinf->rbid[pos],!fpinf->is_uplink,header_size);
        }

        /*Update the hyperframe number*/
        if(seq == 4095){

            ps_counter[rlcinf->rbid[pos]][indx] += 1 << hfn_shift;

            if(!tree){/*Preserve counter for second packet analysis run*/
                guint32 * ciph;
                ciph = (guint32 *)g_malloc(sizeof(guint32)*2);
                ciph[0] = ps_counter[rlcinf->rbid[pos]][0];
                ciph[1] = ps_counter[rlcinf->rbid[pos]][1];
                g_tree_insert(counter_map, GINT_TO_POINTER((gint)pinfo->num+1), ciph);
            }
        }

        /*Unable to decipher the packet*/
        if(t == NULL){
            /* Choosing the right field text ("LIs & Data" or just "Data") based on extension bit / header extension */
            ext = tvb_get_guint8(tvb, header_size - 1) & 0x01;
            ciphered_data_hf = (ext == 1) ? hf_rlc_ciphered_lis_data : hf_rlc_ciphered_data;
            /* Adding ciphered payload field to tree */
            proto_tree_add_item(tree, ciphered_data_hf, tvb, header_size, -1, ENC_NA);
            proto_tree_add_expert(tree, pinfo, &ei_rlc_ciphered_data, tvb, header_size, -1);
            col_append_str(pinfo->cinfo, COL_INFO, "[Ciphered Data]");
            return;

        }else{
            col_append_str(pinfo->cinfo, COL_INFO, "[Deciphered Data]");

            /*TODO: Old tvb should be freed here?*/
        }
    }
}

static void
dissect_rlc_tm(enum rlc_channel_type channel, tvbuff_t *tvb, packet_info *pinfo,
           proto_tree *top_level, proto_tree *tree)
{
    fp_info       *fpinf;
    rlc_info      *rlcinf;

    fpinf = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    rlcinf = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0);

    if (tree) {
        if (fpinf && rlcinf) {
            /* Add "channel" information, very useful for debugging. */
            add_channel_info(pinfo, tree, fpinf, rlcinf);
        }
        proto_tree_add_item(tree, hf_rlc_data, tvb, 0, -1, ENC_NA);
    }
    rlc_call_subdissector(channel, tvb, pinfo, top_level);
}


static void
rlc_um_reassemble(tvbuff_t *tvb, guint8 offs, packet_info *pinfo, proto_tree *tree,
          proto_tree *top_level, enum rlc_channel_type channel, guint16 seq,
          struct rlc_li *li, guint16 num_li, gboolean li_is_on_2_bytes,
          struct atm_phdr *atm)
{
    guint8    i;
    gboolean  dissected = FALSE;
    gint      length;
    tvbuff_t *next_tvb  = NULL;

    /* perform reassembly now */
    for (i = 0; i < num_li; i++) {
        if ((!li_is_on_2_bytes && (li[i].li == 0x7f)) || (li[i].li == 0x7fff)) {
            /* padding, must be last LI */
            if (tree) {
                proto_tree_add_item(tree, hf_rlc_pad, tvb, offs, tvb_captured_length_remaining(tvb, offs), ENC_NA);
            }
            offs += tvb_captured_length_remaining(tvb, offs);
        } else if ((!li_is_on_2_bytes && (li[i].li == 0x7c)) || (li[i].li == 0x7ffc)) {
            /* a new SDU starts here, mark this seq as the first PDU. */
            struct rlc_channel  ch_lookup;
            struct rlc_seqlist * endlist = NULL;
            if( -1 != rlc_channel_assign(&ch_lookup, RLC_UM, pinfo, atm ) ){
                endlist = get_endlist(pinfo, &ch_lookup, atm);
                endlist->list->data = GINT_TO_POINTER((gint)seq);
                endlist->fail_packet=0;
            }

        } else if (li[i].li == 0x7ffa) {
            /* the first data octet in this RLC PDU is the first octet of an RLC SDU
               and the second last octet in this RLC PDU is the last octet of the same RLC SDU */
            length = tvb_reported_length_remaining(tvb, offs);
            if (length > 1) {
                length--;
                if (tree && length) {
                    proto_tree_add_item(tree, hf_rlc_data, tvb, offs, length, ENC_NA);
                }
                if (global_rlc_perform_reassemby) {
                    add_fragment(RLC_UM, tvb, pinfo, li[i].tree, offs, seq, i, length, TRUE, atm);
                    next_tvb = get_reassembled_data(RLC_UM, tvb, pinfo, tree, seq, i, atm);
                }
                offs += length;
            }
            if (tree) {
                proto_tree_add_item(tree, hf_rlc_pad, tvb, offs, 1, ENC_NA);
            }
            offs += 1;
        } else {
            if (tree && li[i].len) {
                proto_tree_add_item(tree, hf_rlc_data, tvb, offs, li[i].len, ENC_NA);
            }
            if (global_rlc_perform_reassemby) {
                add_fragment(RLC_UM, tvb, pinfo, li[i].tree, offs, seq, i, li[i].len, TRUE, atm);
                next_tvb = get_reassembled_data(RLC_UM, tvb, pinfo, tree, seq, i, atm);
            }
        }
        if (next_tvb) {
            dissected = TRUE;
            rlc_call_subdissector(channel, next_tvb, pinfo, top_level);
            next_tvb = NULL;
        }
        offs += li[i].len;
    }

    /* is there data left? */
    if (tvb_reported_length_remaining(tvb, offs) > 0) {
        if (tree) {
            proto_tree_add_item(tree, hf_rlc_data, tvb, offs, -1, ENC_NA);
        }
        if (global_rlc_perform_reassemby) {
            /* add remaining data as fragment */
            add_fragment(RLC_UM, tvb, pinfo, tree, offs, seq, i, tvb_captured_length_remaining(tvb, offs), FALSE, atm);
            if (dissected == FALSE)
                col_set_str(pinfo->cinfo, COL_INFO, "[RLC UM Fragment]");
        }
    }
    if (dissected == FALSE)
        col_append_fstr(pinfo->cinfo, COL_INFO, "[RLC UM Fragment]  SN=%u", seq);
    else
        if (channel == RLC_UNKNOWN_CH)
            col_append_fstr(pinfo->cinfo, COL_INFO, "[RLC UM Data]  SN=%u", seq);
}

static gint16
rlc_decode_li(enum rlc_mode mode, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
          struct rlc_li *li, guint8 max_li, gboolean li_on_2_bytes)
{
    guint32     hdr_len, offs = 0, li_offs;
    guint8      ext, num_li = 0;
    guint16     next_bytes, prev_li = 0;
    proto_item *malformed;
    guint16     total_len;

    switch (mode) {
        case RLC_AM:
            offs = 1;
            break;
        case RLC_UM:
            offs = 0;
            break;
        case RLC_TM:
            /* fall through */
        case RLC_UNKNOWN_MODE:
        default:
            return -1;
    }
    hdr_len = offs;
    /* calculate header length */
    ext = tvb_get_guint8(tvb, hdr_len++) & 0x01;
    while (ext) {
        next_bytes = li_on_2_bytes ? tvb_get_ntohs(tvb, hdr_len) : tvb_get_guint8(tvb, hdr_len);
        ext = next_bytes & 0x01;
        hdr_len += li_on_2_bytes ? 2 : 1;
    }
    total_len = tvb_captured_length_remaining(tvb, hdr_len);

    /* do actual evaluation of LIs */
    ext = tvb_get_guint8(tvb, offs++) & 0x01;
    li_offs = offs;
    while (ext) {
        if (li_on_2_bytes) {
            next_bytes = tvb_get_ntohs(tvb, offs);
            offs += 2;
        } else {
            next_bytes = tvb_get_guint8(tvb, offs++);
        }
        ext = next_bytes & 0x01;
        li[num_li].ext = ext;
        li[num_li].li = next_bytes >> 1;

        if (li_on_2_bytes) {
            switch (li[num_li].li) {
                case 0x0000: /* previous segment was the last one */
                case 0x7ffb: /* previous PDU contains last segment of SDU (minus last byte) */
                case 0x7ffe: /* contains piggybacked STATUS in AM or segment in UM */
                case 0x7fff: /* padding */
                    li[num_li].len = 0;
                    break;
                case 0x7ffa: /* contains exactly one SDU (minus last byte), UM only */
                case 0x7ffc: /* start of a new SDU, UM only */
                case 0x7ffd: /* contains exactly one SDU, UM only */
                    li[num_li].len = 0;
                    if (mode == RLC_UM) {
                        /* valid for UM */
                        break;
                    }
                    /*invalid for AM */
                    /* add malformed LI for investigation */
                    malformed = tree_add_li(mode, &li[num_li], num_li, li_offs, li_on_2_bytes, tvb, tree);
                    expert_add_info(pinfo, malformed, &ei_rlc_li_reserved);
                    return -1; /* just give up on this */
                default:
                    /* since the LI is an offset (from the end of the header), it
                    * may not be larger than the total remaining length and no
                    * LI may be smaller than its preceding one
                    */
                    if (((li[num_li].li > total_len) && !global_rlc_headers_expected)
                        || (li[num_li].li < prev_li)) {
                        /* add malformed LI for investigation */
                        li[num_li].len = 0;
                        malformed = tree_add_li(mode, &li[num_li], num_li, li_offs, li_on_2_bytes, tvb, tree);
                        expert_add_info(pinfo, malformed, &ei_rlc_li_incorrect_warn);
                        return -1; /* just give up on this */
                    }
                    li[num_li].len = li[num_li].li - prev_li;
                    prev_li = li[num_li].li;
            }
        } else {
            switch (li[num_li].li) {
                case 0x00: /* previous segment was the last one */
                case 0x7e: /* contains piggybacked STATUS in AM or segment in UM */
                case 0x7f: /* padding */
                    li[num_li].len = 0;
                    break;
                case 0x7c: /* start of a new SDU, UM only */
                case 0x7d: /* contains exactly one SDU, UM only */
                    li[num_li].len = 0;
                    if (mode == RLC_UM) {
                        /* valid for UM */
                        break;
                    }
                    /*invalid for AM */
                    /* add malformed LI for investigation */
                    malformed = tree_add_li(mode, &li[num_li], num_li, li_offs, li_on_2_bytes, tvb, tree);
                    expert_add_info(pinfo, malformed, &ei_rlc_li_reserved);
                    return -1; /* just give up on this */
                default:
                    /* since the LI is an offset (from the end of the header), it
                    * may not be larger than the total remaining length and no
                    * LI may be smaller than its preceding one
                    */
                    li[num_li].len = li[num_li].li - prev_li;
                    if (((li[num_li].li > total_len) && !global_rlc_headers_expected)
                        || (li[num_li].li < prev_li)) {
                        /* add malformed LI for investigation */
                        li[num_li].len = 0;
                        malformed = tree_add_li(mode, &li[num_li], num_li, li_offs, li_on_2_bytes, tvb, tree);
                        expert_add_info_format(pinfo, malformed, &ei_rlc_li_incorrect_mal, "Incorrect LI value 0x%x", li[num_li].li);
                        return -1; /* just give up on this */
                    }
                    prev_li = li[num_li].li;
            }
        }
        li[num_li].tree = tree_add_li(mode, &li[num_li], num_li, li_offs, li_on_2_bytes, tvb, tree);
        num_li++;

        if (num_li >= max_li) {
            /* OK, so this is not really a malformed packet, but for now,
            * we will treat it as such, so that it is marked in some way */
            expert_add_info(pinfo, li[num_li-1].tree, &ei_rlc_li_too_many);
            return -1;
        }
    }
    return num_li;
}

static void
dissect_rlc_um(enum rlc_channel_type channel, tvbuff_t *tvb, packet_info *pinfo,
           proto_tree *top_level, proto_tree *tree, struct atm_phdr *atm)
{
#define MAX_LI 16
    struct rlc_li  li[MAX_LI];
    fp_info       *fpinf;
    rlc_info      *rlcinf;
    guint32        orig_num;
    guint8         seq;
    guint8         ext;
    guint8         next_byte, offs = 0;
    gint16         cur_tb, num_li  = 0;
    gboolean       is_truncated, li_is_on_2_bytes;
    proto_item    *truncated_ti;
    gboolean       ciphered_according_to_rrc = FALSE;
    gboolean       ciphered_flag = FALSE;
    gboolean       deciphered_flag = FALSE;
    int            ciphered_data_hf;


    next_byte = tvb_get_guint8(tvb, offs++);
    seq = next_byte >> 1;

    fpinf = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    rlcinf = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0);

    if (tree) {
        if (fpinf && rlcinf) {
            /* Add "channel" information, very useful for debugging. */
            add_channel_info(pinfo, tree, fpinf, rlcinf);
        }
        /* show sequence number and extension bit */
        proto_tree_add_bits_item(tree, hf_rlc_seq, tvb, 0, 7, ENC_BIG_ENDIAN);
        proto_tree_add_bits_item(tree, hf_rlc_ext, tvb, 7, 1, ENC_BIG_ENDIAN);
    }

    if (!fpinf || !rlcinf) {
        proto_tree_add_expert(tree, pinfo, &ei_rlc_no_per_frame_data, tvb, 0, -1);
        return;
    }

    cur_tb = fpinf->cur_tb;
    ciphered_according_to_rrc = is_ciphered_according_to_rrc(pinfo, fpinf, rlcinf, (guint16)seq);
    ciphered_flag = rlcinf->ciphered[cur_tb];
    deciphered_flag = rlcinf->deciphered[cur_tb];
    if (((ciphered_according_to_rrc || ciphered_flag) && !deciphered_flag) || global_rlc_ciphered) {
        if(global_rlc_try_decipher){
            rlc_decipher(tvb, pinfo, tree, fpinf, rlcinf, seq, RLC_UM);
        }else{
            /* Choosing the right field text ("LIs & Data" or just "Data") based on extension bit */
            ext = tvb_get_guint8(tvb, 0) & 0x01;
            ciphered_data_hf = (ext == 1) ? hf_rlc_ciphered_lis_data : hf_rlc_ciphered_data;
            /* Adding ciphered payload field to tree */
            proto_tree_add_item(tree, ciphered_data_hf, tvb, offs, -1, ENC_NA);
            proto_tree_add_expert(tree, pinfo, &ei_rlc_ciphered_data, tvb, offs, -1);
            col_append_str(pinfo->cinfo, COL_INFO, "[Ciphered Data]");
            return;
        }
    }

    if (global_rlc_li_size == RLC_LI_UPPERLAYER) {
        if (rlcinf->li_size[cur_tb] == RLC_LI_VARIABLE) {
            li_is_on_2_bytes = (tvb_reported_length(tvb) > 125) ? TRUE : FALSE;
        } else {
            li_is_on_2_bytes = (rlcinf->li_size[cur_tb] == RLC_LI_15BITS) ? TRUE : FALSE;
        }
    } else { /* Override rlcinf configuration with preference. */
        li_is_on_2_bytes = (global_rlc_li_size == RLC_LI_15BITS) ? TRUE : FALSE;
    }



    num_li = rlc_decode_li(RLC_UM, tvb, pinfo, tree, li, MAX_LI, li_is_on_2_bytes);
    if (num_li == -1) return; /* something went wrong */
    offs += ((li_is_on_2_bytes) ? 2 : 1) * num_li;

    if (global_rlc_headers_expected) {
        /* There might not be any data, if only header was logged */
        is_truncated = (tvb_captured_length_remaining(tvb, offs) == 0);
        truncated_ti = proto_tree_add_boolean(tree, hf_rlc_header_only, tvb, 0, 0,
                                              is_truncated);
        if (is_truncated) {
            PROTO_ITEM_SET_GENERATED(truncated_ti);
            expert_add_info(pinfo, truncated_ti, &ei_rlc_header_only);
            return;
        } else {
            PROTO_ITEM_SET_HIDDEN(truncated_ti);
        }
    }

    /* do not detect duplicates or reassemble, if prefiltering is done */
    if (pinfo->num == 0) return;
    /* check for duplicates */
    if (rlc_is_duplicate(RLC_UM, pinfo, seq, &orig_num, atm) == TRUE) {
        col_add_fstr(pinfo->cinfo, COL_INFO, "[RLC UM Fragment] [Duplicate]  SN=%u", seq);
        proto_tree_add_uint(tree, hf_rlc_duplicate_of, tvb, 0, 0, orig_num);
        return;
    }
    rlc_um_reassemble(tvb, offs, pinfo, tree, top_level, channel, seq, li, num_li, li_is_on_2_bytes, atm);
}

static void
dissect_rlc_status(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint8 offset)
{
    guint8      sufi_type, bits;
    guint64     len, sn, wsn, lsn, l;
    guint16     value, previous_sn;
    gboolean    isErrorBurstInd;
    gint        bit_offset, previous_bit_offset;
    guint       i, j;
    proto_tree *sufi_tree, *bitmap_tree, *rlist_tree;
    proto_item *sufi_item, *ti;
    #define BUFF_SIZE 41
    gchar      *buff                     = NULL;
    guint8      cw[15];
    guint8      sufi_start_offset;
    gboolean    seen_last                = FALSE;
    guint16     number_of_bitmap_entries = 0;

    bit_offset = offset*8 + 4; /* first SUFI type is always 4 bit shifted */

    while (!seen_last && tvb_reported_length_remaining(tvb, bit_offset/8) > 0) {
        /* SUFI */
        sufi_type = tvb_get_bits8(tvb, bit_offset, 4);
        sufi_start_offset = bit_offset/8;
        sufi_item = proto_tree_add_item(tree, hf_rlc_sufi, tvb, sufi_start_offset, 0, ENC_NA);
        sufi_tree = proto_item_add_subtree(sufi_item, ett_rlc_sufi);
        proto_tree_add_bits_item(sufi_tree, hf_rlc_sufi_type, tvb, bit_offset, 4, ENC_BIG_ENDIAN);
        proto_item_append_text(sufi_item, " (%s)", val_to_str_const(sufi_type, rlc_sufi_vals, "Unknown"));
        bit_offset += 4;
        switch (sufi_type) {
            case RLC_SUFI_NOMORE:
                seen_last = TRUE;
                break;
            case RLC_SUFI_ACK:
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_lsn, tvb, bit_offset, 12, &lsn, ENC_BIG_ENDIAN);
                col_append_fstr(pinfo->cinfo, COL_INFO, " LSN=%u", (guint16)lsn);
                proto_item_append_text(sufi_item, " LSN=%u", (guint16)lsn);
                bit_offset += 12;
                seen_last = TRUE;
                break;
            case RLC_SUFI_WINDOW:
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_wsn, tvb, bit_offset, 12, &wsn, ENC_BIG_ENDIAN);
                col_append_fstr(pinfo->cinfo, COL_INFO, " WSN=%u", (guint16)wsn);
                bit_offset += 12;
                break;
            case RLC_SUFI_LIST:
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_len, tvb, bit_offset, 4, &len, ENC_BIG_ENDIAN);
                col_append_fstr(pinfo->cinfo, COL_INFO,  " LIST(%u) - ", (guint8)len);
                bit_offset += 4;
                if (len) {
                    while (len) {
                        ti = proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_sn, tvb, bit_offset, 12, &sn, ENC_BIG_ENDIAN);
                        proto_item_append_text(ti, " (AMD PDU not correctly received)");
                        bit_offset += 12;
                        ti = proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_l, tvb, bit_offset, 4, &l, ENC_BIG_ENDIAN);
                        if (l) {
                            proto_item_append_text(ti, " (all consecutive AMD PDUs up to SN %u not correctly received)",
                                                   (unsigned)(sn+l)&0xfff);
                            col_append_fstr(pinfo->cinfo, COL_INFO,  "%u-%u ", (guint16)sn, (unsigned)(sn+l)&0xfff);
                        }
                        else {
                            col_append_fstr(pinfo->cinfo, COL_INFO,  "%u ", (guint16)sn);
                        }
                        bit_offset += 4;
                        len--;
                    }
                } else {
                    expert_add_info(pinfo, tree, &ei_rlc_sufi_len);
                }
                break;
            case RLC_SUFI_BITMAP:
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_len, tvb, bit_offset, 4, &len, ENC_BIG_ENDIAN);
                bit_offset += 4;
                len++; /* bitmap is len + 1 */
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_fsn, tvb, bit_offset, 12, &sn, ENC_BIG_ENDIAN);
                bit_offset += 12;
                proto_tree_add_item(sufi_tree, hf_rlc_sufi_bitmap, tvb, bit_offset/8, (gint)len, ENC_NA);
                bitmap_tree = proto_tree_add_subtree(sufi_tree, tvb, bit_offset/8, (gint)len, ett_rlc_bitmap, &ti, "Decoded bitmap:");
                col_append_str(pinfo->cinfo, COL_INFO, " BITMAP=(");

                buff = (gchar *)wmem_alloc(wmem_packet_scope(), BUFF_SIZE);
                for (i=0; i<len; i++) {
                    bits = tvb_get_bits8(tvb, bit_offset, 8);
                    for (l=0, j=0; l<8; l++) {
                        if ((bits << l) & 0x80) {
                            j += g_snprintf(&buff[j], BUFF_SIZE-j, "%4u,", (unsigned)(sn+(8*i)+l)&0xfff);
                            col_append_fstr(pinfo->cinfo, COL_INFO, " %u", (unsigned)(sn+(8*i)+l)&0xfff);
                            number_of_bitmap_entries++;
                        } else {
                            j += g_snprintf(&buff[j], BUFF_SIZE-j, "    ,");
                        }
                    }
                    proto_tree_add_string_format(bitmap_tree, hf_rlc_bitmap_string, tvb, bit_offset/8, 1, buff, "%s", buff);
                    bit_offset += 8;
                }
                proto_item_append_text(ti, " (%u SNs)", number_of_bitmap_entries);
                col_append_str(pinfo->cinfo, COL_INFO, " )");
                break;
            case RLC_SUFI_RLIST:
                previous_bit_offset = bit_offset;
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_len, tvb, bit_offset, 4, &len, ENC_BIG_ENDIAN);
                bit_offset += 4;
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_fsn, tvb, bit_offset, 12, &sn, ENC_BIG_ENDIAN);
                bit_offset += 12;
                proto_item_append_text(sufi_item, " (%u codewords)", (guint16)len);

                for (i=0; i<len; i++) {
                    ti = proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_cw, tvb, bit_offset, 4, &l, ENC_BIG_ENDIAN);
                    if (l == 0x01) {
                        proto_item_append_text(ti, " (Error burst indication)");
                    }
                    bit_offset += 4;
                    cw[i] = (guint8)l;
                }
                if (len && (((cw[len-1] & 0x01) == 0) || (cw[len-1] == 0x01))) {
                    expert_add_info(pinfo, tree, &ei_rlc_sufi_cw);
                } else {
                    rlist_tree = proto_tree_add_subtree(sufi_tree, tvb, previous_bit_offset/8, (bit_offset-previous_bit_offset)/8, ett_rlc_rlist, NULL, "Decoded list:");
                    proto_tree_add_uint_format_value(rlist_tree, hf_rlc_sequence_number, tvb, (previous_bit_offset+4)/8, 12/8, (guint32)sn, "%u (AMD PDU not correctly received)", (unsigned)sn);
                    col_append_fstr(pinfo->cinfo, COL_INFO, " RLIST=(%u", (unsigned)sn);

                    for (i=0, isErrorBurstInd=FALSE, j=0, previous_sn=(guint16)sn, value=0; i<len; i++) {
                        if (cw[i] == 0x01) {
                            isErrorBurstInd = TRUE;
                        } else {
                            value |= (cw[i] >> 1) << j;
                            j += 3;
                            if (cw[i] & 0x01) {
                                if (isErrorBurstInd) {
                                    previous_sn = (previous_sn + value) & 0xfff;
                                    ti = proto_tree_add_uint(rlist_tree, hf_rlc_length, tvb, (previous_bit_offset+16+4*i)/8, 1, value);
                                    if (value) {
                                        proto_item_append_text(ti, "  (all consecutive AMD PDUs up to SN %u not correctly received)", previous_sn);
                                        col_append_fstr(pinfo->cinfo, COL_INFO, " ->%u", previous_sn);
                                    }
                                    isErrorBurstInd = FALSE;
                                } else {
                                    value = (value + previous_sn) & 0xfff;
                                    proto_tree_add_uint_format_value(rlist_tree, hf_rlc_sequence_number, tvb, (previous_bit_offset+16+4*i)/8, 1, value, "%u (AMD PDU not correctly received)",value);
                                    col_append_fstr(pinfo->cinfo, COL_INFO, " %u", value);
                                    previous_sn = value;
                                }
                                value = j = 0;
                            }
                        }
                    }
                    col_append_str(pinfo->cinfo, COL_INFO, ")");
                }
                break;
            case RLC_SUFI_MRW_ACK:
                col_append_str(pinfo->cinfo, COL_INFO, " MRW-ACK");
                proto_tree_add_bits_item(sufi_tree, hf_rlc_sufi_n, tvb, bit_offset, 4, ENC_BIG_ENDIAN);
                bit_offset += 4;
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_sn_ack, tvb, bit_offset, 12, &sn, ENC_BIG_ENDIAN);
                bit_offset += 12;
                col_append_fstr(pinfo->cinfo, COL_INFO, " SN=%u", (guint16)sn);
                break;
            case RLC_SUFI_MRW:
                col_append_str(pinfo->cinfo, COL_INFO, " MRW");
                proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_len, tvb, bit_offset, 4, &len, ENC_BIG_ENDIAN);
                bit_offset += 4;
                if (len) {
                    while (len) {
                        proto_tree_add_bits_ret_val(sufi_tree, hf_rlc_sufi_sn_mrw, tvb, bit_offset, 12, &sn, ENC_BIG_ENDIAN);
                        col_append_fstr(pinfo->cinfo, COL_INFO, " SN=%u", (guint16)sn);
                        bit_offset += 12;
                        len--;
                    }
                } else {
                    /* only one SN_MRW field is present */
                    ti = proto_tree_add_bits_item(sufi_tree, hf_rlc_sufi_sn_mrw, tvb, bit_offset, 12, ENC_BIG_ENDIAN);
                    proto_item_append_text(ti, " (RLC SDU to be discarded in the Receiver extends above the configured transmission window in the Sender)");
                    bit_offset += 12;
                }
                proto_tree_add_bits_item(sufi_tree, hf_rlc_sufi_n, tvb, bit_offset, 4, ENC_BIG_ENDIAN);
                bit_offset += 4;
                break;
            case RLC_SUFI_POLL:
                proto_tree_add_bits_item(sufi_tree, hf_rlc_sufi_poll_sn, tvb, bit_offset, 12, ENC_BIG_ENDIAN);
                bit_offset += 12;
                break;

            default:
                expert_add_info(pinfo, tree, &ei_rlc_sufi_type);
                return; /* invalid value, ignore the rest */
        }

        /* Set extent of SUFI root */
        proto_item_set_len(sufi_item, ((bit_offset+7)/8) - sufi_start_offset);
    }
}

static void
dissect_rlc_control(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
    guint8      type, next_byte;
    proto_item *ti;
    guint64     r1;
    guint64     rsn, hfn;

    next_byte = tvb_get_guint8(tvb, 0);
    type = (next_byte >> 4) & 0x07;

    ti = proto_tree_add_bits_item(tree, hf_rlc_ctrl_type, tvb, 1, 3, ENC_BIG_ENDIAN);
    switch (type) {
        case RLC_STATUS:
            dissect_rlc_status(tvb, pinfo, tree, 0);
            break;
        case RLC_RESET:
        case RLC_RESET_ACK:
            col_append_str(pinfo->cinfo, COL_INFO, (type == RLC_RESET) ? " RESET" : " RESET-ACK");
            proto_tree_add_bits_ret_val(tree, hf_rlc_rsn, tvb, 4, 1, &rsn, ENC_BIG_ENDIAN);
            proto_tree_add_bits_ret_val(tree, hf_rlc_r1, tvb, 5, 3, &r1, ENC_BIG_ENDIAN);
            if (r1) {
                expert_add_info(pinfo, ti, &ei_rlc_reserved_bits_not_zero);
                return;
            }
            proto_tree_add_bits_ret_val(tree, hf_rlc_hfni, tvb, 8, 20, &hfn, ENC_BIG_ENDIAN);
            col_append_fstr(pinfo->cinfo, COL_INFO, " RSN=%u HFN=%u", (guint16)rsn, (guint32)hfn);
            break;
        default:
            expert_add_info_format(pinfo, ti, &ei_rlc_ctrl_type, "Invalid RLC AM control type %u", type);
            return; /* invalid */
    }
}

static void
rlc_am_reassemble(tvbuff_t *tvb, guint8 offs, packet_info *pinfo,
          proto_tree *tree, proto_tree *top_level,
          enum rlc_channel_type channel, guint16 seq, gboolean poll_set, struct rlc_li *li,
          guint16 num_li, gboolean final, gboolean li_is_on_2_bytes,
          struct atm_phdr *atm)
{
    guint8    i;
    gboolean  piggyback = FALSE, dissected = FALSE;
    tvbuff_t *next_tvb  = NULL;

    struct rlc_channel  ch_lookup;
    struct rlc_seqlist * endlist = NULL;
    if( 0 == seq ){ /* assuming that a new RRC Connection is established when 0==seq.  */
        if( -1 != rlc_channel_assign(&ch_lookup, RLC_AM, pinfo, atm ) ){
            endlist = get_endlist(pinfo, &ch_lookup, atm);
            endlist->list->data = GINT_TO_POINTER( -1);
        }
    }

    /* perform reassembly now */
    for (i = 0; i < num_li; i++) {
        if ((!li_is_on_2_bytes && (li[i].li == 0x7e)) || (li[i].li == 0x7ffe)) {
            /* piggybacked status */
            piggyback = TRUE;
        } else if ((!li_is_on_2_bytes && (li[i].li == 0x7f)) || (li[i].li == 0x7fff)) {
            /* padding, must be last LI */
            if (tvb_reported_length_remaining(tvb, offs) > 0) {
                if (tree) {
                    proto_tree_add_item(tree, hf_rlc_pad, tvb, offs, -1, ENC_NA);
                }
                if (i == 0) {
                    /* Insert empty RLC frag so RLC doesn't miss this seq number. */
                    add_fragment(RLC_AM, tvb, pinfo, li[i].tree, offs, seq, i, 0, TRUE, atm);
                }
            }
            offs += tvb_captured_length_remaining(tvb, offs);
        } else {
            if (tree) {
                proto_tree_add_item(tree, hf_rlc_data, tvb, offs, li[i].len, ENC_NA);
            }
            if (global_rlc_perform_reassemby) {
                add_fragment(RLC_AM, tvb, pinfo, li[i].tree, offs, seq, i, li[i].len, TRUE, atm);
                next_tvb = get_reassembled_data(RLC_AM, tvb, pinfo, tree, seq, i, atm);
            }
        }
        if (next_tvb) {
            dissected = TRUE;
            rlc_call_subdissector(channel, next_tvb, pinfo, top_level);
            next_tvb = NULL;
        }
        offs += li[i].len;
    }

    if (piggyback) {
        dissect_rlc_status(tvb, pinfo, tree, offs);
    } else {
        if (tvb_reported_length_remaining(tvb, offs) > 0) {
            /* we have remaining data, which we need to mark in the tree */
            if (tree) {
                proto_tree_add_item(tree, hf_rlc_data, tvb, offs, -1, ENC_NA);
            }
            if (global_rlc_perform_reassemby) {
                add_fragment(RLC_AM, tvb, pinfo, tree, offs, seq, i,
                    tvb_captured_length_remaining(tvb,offs), final, atm);
                if (final) {
                    next_tvb = get_reassembled_data(RLC_AM, tvb, pinfo, tree, seq, i, atm);
                }
            }
        }
        if (next_tvb) {
            dissected = TRUE;
            rlc_call_subdissector(channel, next_tvb, pinfo, top_level);
            next_tvb = NULL;
        }
    }
    if (dissected == FALSE)
        col_append_fstr(pinfo->cinfo, COL_INFO, "[RLC AM Fragment]  SN=%u %s",
                     seq, poll_set ? "(P)" : "");
    else
        if (channel == RLC_UNKNOWN_CH)
            col_append_fstr(pinfo->cinfo, COL_INFO, "[RLC AM Data]  SN=%u %s",
                         seq, poll_set ? "(P)" : "");
}

static void
dissect_rlc_am(enum rlc_channel_type channel, tvbuff_t *tvb, packet_info *pinfo,
           proto_tree *top_level, proto_tree *tree, struct atm_phdr *atm)
{
#define MAX_LI 16
    struct rlc_li  li[MAX_LI];
    fp_info       *fpinf;
    rlc_info      *rlcinf;
    guint8         ext, dc;
    guint8         next_byte, offs = 0;
    guint32        orig_num        = 0;
    gint16         num_li          = 0;
    gint16         cur_tb;
    guint16        seq;
    gboolean       is_truncated, li_is_on_2_bytes;
    proto_item    *truncated_ti, *ti;
    guint64        polling;
    gboolean       ciphered_according_to_rrc = FALSE;
    gboolean       ciphered_flag = FALSE;
    gboolean       deciphered_flag = FALSE;
    int            ciphered_data_hf;

    fpinf = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    rlcinf = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0);

    next_byte = tvb_get_guint8(tvb, offs++);
    dc = next_byte >> 7;
    if (tree) {
        if (fpinf && rlcinf) {
            /* Add "channel" information, very useful for debugging. */
            add_channel_info(pinfo, tree, fpinf, rlcinf);
        }
        proto_tree_add_bits_item(tree, hf_rlc_dc, tvb, 0, 1, ENC_BIG_ENDIAN);
    }
    if (dc == 0) {
        col_set_str(pinfo->cinfo, COL_INFO, "[RLC Control Frame]");
        dissect_rlc_control(tvb, pinfo, tree);
        return;
    }

    seq = next_byte & 0x7f;
    seq <<= 5;
    next_byte = tvb_get_guint8(tvb, offs++);
    seq |= (next_byte >> 3);

    ext = next_byte & 0x03;
    /* show header fields */
    proto_tree_add_bits_item(tree, hf_rlc_seq, tvb, 1, 12, ENC_BIG_ENDIAN);
    proto_tree_add_bits_ret_val(tree, hf_rlc_p, tvb, 13, 1, &polling, ENC_BIG_ENDIAN);
    ti = proto_tree_add_bits_item(tree, hf_rlc_he, tvb, 14, 2, ENC_BIG_ENDIAN);

    /* header extension may only be 00, 01 or 10 */
    if (ext > 2) {
        expert_add_info(pinfo, ti, &ei_rlc_he);
        return;
    }

    if (!fpinf || !rlcinf) {
        proto_tree_add_expert(tree, pinfo, &ei_rlc_no_per_frame_data, tvb, 0, -1);
        return;
    }

    cur_tb = fpinf->cur_tb;
    /**
     * WARNING DECIPHERING IS HIGHLY EXPERIMENTAL!!!
     * */
    ciphered_according_to_rrc = is_ciphered_according_to_rrc(pinfo, fpinf, rlcinf, (guint16)seq);
    ciphered_flag = rlcinf->ciphered[cur_tb];
    deciphered_flag = rlcinf->deciphered[cur_tb];
    if (((ciphered_according_to_rrc || ciphered_flag) && !deciphered_flag) || global_rlc_ciphered) {
        if(global_rlc_try_decipher){
            rlc_decipher(tvb, pinfo, tree, fpinf, rlcinf, seq, RLC_AM);
        }else{
            /* Choosing the right field text ("LIs & Data" or just "Data") based on header extension field */
            ciphered_data_hf = (ext == 0x01) ? hf_rlc_ciphered_lis_data : hf_rlc_ciphered_data;
            /* Adding ciphered payload field to tree */
            proto_tree_add_item(tree, ciphered_data_hf, tvb, offs, -1, ENC_NA);
            proto_tree_add_expert(tree, pinfo, &ei_rlc_ciphered_data, tvb, offs, -1);
            col_append_str(pinfo->cinfo, COL_INFO, "[Ciphered Data]");
            return;
        }
    }

    if (global_rlc_li_size == RLC_LI_UPPERLAYER) {
        if (rlcinf->li_size[cur_tb] == RLC_LI_VARIABLE) {
            li_is_on_2_bytes = (tvb_reported_length(tvb) > 126) ? TRUE : FALSE;
        } else {
            li_is_on_2_bytes = (rlcinf->li_size[cur_tb] == RLC_LI_15BITS) ? TRUE : FALSE;
        }
    } else { /* Override rlcinf configuration with preference. */
        li_is_on_2_bytes = (global_rlc_li_size == RLC_LI_15BITS) ? TRUE : FALSE;
    }

    num_li = rlc_decode_li(RLC_AM, tvb, pinfo, tree, li, MAX_LI, li_is_on_2_bytes);
    if (num_li == -1) return; /* something went wrong */
    offs += ((li_is_on_2_bytes) ? 2 : 1) * num_li;
    if (global_rlc_headers_expected) {
        /* There might not be any data, if only header was logged */
        is_truncated = (tvb_captured_length_remaining(tvb, offs) == 0);
        truncated_ti = proto_tree_add_boolean(tree, hf_rlc_header_only, tvb, 0, 0,
                                              is_truncated);
        if (is_truncated) {
            PROTO_ITEM_SET_GENERATED(truncated_ti);
            expert_add_info(pinfo, truncated_ti, &ei_rlc_header_only);
            return;
        } else {
            PROTO_ITEM_SET_HIDDEN(truncated_ti);
        }
    }

    /* do not detect duplicates or reassemble, if prefiltering is done */
    if (pinfo->num == 0) return;
    /* check for duplicates, but not if already visited */
    if (pinfo->fd->flags.visited == FALSE && rlc_is_duplicate(RLC_AM, pinfo, seq, &orig_num, atm) == TRUE) {
        g_hash_table_insert(duplicate_table, GUINT_TO_POINTER(pinfo->num), GUINT_TO_POINTER(orig_num));
        return;
    } else if (pinfo->fd->flags.visited == TRUE && tree) {
        gpointer value = g_hash_table_lookup(duplicate_table, GUINT_TO_POINTER(pinfo->num));
        if (value != NULL) {
            col_add_fstr(pinfo->cinfo, COL_INFO, "[RLC AM Fragment] [Duplicate]  SN=%u %s", seq, (polling != 0) ? "(P)" : "");
            proto_tree_add_uint(tree, hf_rlc_duplicate_of, tvb, 0, 0, GPOINTER_TO_UINT(value));
            return;
        }
    }

    rlc_am_reassemble(tvb, offs, pinfo, tree, top_level, channel, seq, polling != 0,
                      li, num_li, ext == 2, li_is_on_2_bytes, atm);
}

/* dissect entry functions */
static int
dissect_rlc_pcch(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
    proto_tree *subtree = NULL;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
    col_clear(pinfo->cinfo, COL_INFO);

    /* PCCH is always RLC TM */
    if (tree) {
        proto_item *ti;
        ti = proto_tree_add_item(tree, proto_umts_rlc, tvb, 0, -1, ENC_NA);
        subtree = proto_item_add_subtree(ti, ett_rlc);
        proto_item_append_text(ti, " TM (PCCH)");
    }
    dissect_rlc_tm(RLC_PCCH, tvb, pinfo, tree, subtree);
    return tvb_captured_length(tvb);
}

static int
dissect_rlc_bcch(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
    fp_info    *fpi;
    proto_item *ti      = NULL;
    proto_tree *subtree = NULL;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
    col_clear(pinfo->cinfo, COL_INFO);

    fpi = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    if (!fpi) return 0; /* dissection failure */

    if (tree) {
        ti = proto_tree_add_item(tree, proto_umts_rlc, tvb, 0, -1, ENC_NA);
        subtree = proto_item_add_subtree(ti, ett_rlc);
    }
    proto_item_append_text(ti, " TM (BCCH)");
    dissect_rlc_tm(RLC_BCCH, tvb, pinfo, tree, subtree);
    return tvb_captured_length(tvb);
}

static int
dissect_rlc_ccch(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
    fp_info    *fpi;
    proto_item *ti      = NULL;
    proto_tree *subtree = NULL;
    struct atm_phdr *atm = (struct atm_phdr *)data;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
    col_clear(pinfo->cinfo, COL_INFO);

    fpi = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    if (!fpi) return 0; /* dissection failure */

    if (tree) {
        ti = proto_tree_add_item(tree, proto_umts_rlc, tvb, 0, -1, ENC_NA);
        subtree = proto_item_add_subtree(ti, ett_rlc);
    }

    if (fpi->is_uplink) {
        /* UL CCCH is always RLC TM */
        proto_item_append_text(ti, " TM (CCCH)");
        dissect_rlc_tm(RLC_UL_CCCH, tvb, pinfo, tree, subtree);
    } else {
        /* DL CCCH is always UM */
        proto_item_append_text(ti, " UM (CCCH)");
        dissect_rlc_um(RLC_DL_CCCH, tvb, pinfo, tree, subtree, atm);
    }
    return tvb_captured_length(tvb);
}

static int
dissect_rlc_ctch(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void  *data)
{
    fp_info    *fpi;
    proto_item *ti      = NULL;
    proto_tree *subtree = NULL;
    struct atm_phdr *atm = (struct atm_phdr *)data;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
    col_clear(pinfo->cinfo, COL_INFO);

    fpi = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    if (!fpi) return 0; /* dissection failure */

    if (tree) {
        ti = proto_tree_add_item(tree, proto_umts_rlc, tvb, 0, -1, ENC_NA);
        subtree = proto_item_add_subtree(ti, ett_rlc);
    }

    /* CTCH is always UM */
    proto_item_append_text(ti, " UM (CTCH)");
    dissect_rlc_um(RLC_DL_CTCH, tvb, pinfo, tree, subtree, atm);
    return tvb_captured_length(tvb);
}

static int
dissect_rlc_dcch(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
    proto_item            *ti      = NULL;
    proto_tree            *subtree = NULL;
    fp_info               *fpi;
    rlc_info              *rlci;
    enum rlc_channel_type  channel;
    struct atm_phdr       *atm = (struct atm_phdr *)data;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
    col_clear(pinfo->cinfo, COL_INFO);

    fpi = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    rlci = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0);

    if (!fpi || !rlci){
        proto_tree_add_expert(tree, pinfo, &ei_rlc_no_per_frame_data, tvb, 0, -1);
        return 1;
    }

    if (tree) {
        ti = proto_tree_add_item(tree, proto_umts_rlc, tvb, 0, -1, ENC_NA);
        subtree = proto_item_add_subtree(ti, ett_rlc);
    }

    channel = fpi->is_uplink ? RLC_UL_DCCH : RLC_DL_DCCH;

    switch (rlci->mode[fpi->cur_tb]) {
        case RLC_UM:
            proto_item_append_text(ti, " UM (DCCH)");
            dissect_rlc_um(channel, tvb, pinfo, tree, subtree, atm);
            break;
        case RLC_AM:
            proto_item_append_text(ti, " AM (DCCH)");
            dissect_rlc_am(channel, tvb, pinfo, tree, subtree, atm);
            break;
    }
    return tvb_captured_length(tvb);
}

static int
dissect_rlc_ps_dtch(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
    proto_item *ti      = NULL;
    proto_tree *subtree = NULL;
    fp_info    *fpi;
    rlc_info   *rlci;
    struct atm_phdr *atm = (struct atm_phdr *)data;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
    col_clear(pinfo->cinfo, COL_INFO);

    fpi  = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    rlci = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0);

    if (!fpi || !rlci) {
        proto_tree_add_expert(tree, pinfo, &ei_rlc_no_per_frame_data, tvb, 0, -1);
        return 1;
    }

    if (tree) {
        ti = proto_tree_add_item(tree, proto_umts_rlc, tvb, 0, -1, ENC_NA);
        subtree = proto_item_add_subtree(ti, ett_rlc);
    }

    switch (rlci->mode[fpi->cur_tb]) {
        case RLC_UM:
            proto_item_append_text(ti, " UM (PS DTCH)");
            dissect_rlc_um(RLC_PS_DTCH, tvb, pinfo, tree, subtree, atm);
            break;
        case RLC_AM:
            proto_item_append_text(ti, " AM (PS DTCH)");
            dissect_rlc_am(RLC_PS_DTCH, tvb, pinfo, tree, subtree, atm);
            break;
        case RLC_TM:
            proto_item_append_text(ti, " TM (PS DTCH)");
            dissect_rlc_tm(RLC_PS_DTCH, tvb, pinfo, tree, subtree);
            break;
    }
    return tvb_captured_length(tvb);
}

static int
dissect_rlc_dch_unknown(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
    proto_item *ti      = NULL;
    proto_tree *subtree = NULL;
    fp_info    *fpi;
    rlc_info   *rlci;
    struct atm_phdr *atm = (struct atm_phdr *)data;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
    col_clear(pinfo->cinfo, COL_INFO);

    fpi = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    rlci = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0);

    if (!fpi || !rlci) return 0;

    if (tree) {
        ti = proto_tree_add_item(tree, proto_umts_rlc, tvb, 0, -1, ENC_NA);
        subtree = proto_item_add_subtree(ti, ett_rlc);
    }

    switch (rlci->mode[fpi->cur_tb]) {
        case RLC_UM:
            proto_item_append_text(ti, " UM (Unknown)");
            dissect_rlc_um(RLC_UNKNOWN_CH, tvb, pinfo, tree, subtree, atm);
            break;
        case RLC_AM:
            proto_item_append_text(ti, " AM (Unknown)");
            dissect_rlc_am(RLC_UNKNOWN_CH, tvb, pinfo, tree, subtree, atm);
            break;
        case RLC_TM:
            proto_item_append_text(ti, " TM (Unknown)");
            dissect_rlc_tm(RLC_UNKNOWN_CH, tvb, pinfo, tree, subtree);
            break;
    }
    return tvb_captured_length(tvb);
}

static void
report_heur_error(proto_tree *tree, packet_info *pinfo, expert_field *eiindex,
                  tvbuff_t *tvb, gint start, gint length)
{
    proto_item *ti;
    proto_tree *subtree;

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
    col_clear(pinfo->cinfo, COL_INFO);
    ti = proto_tree_add_item(tree, proto_umts_rlc, tvb, 0, -1, ENC_NA);
    subtree = proto_item_add_subtree(ti, ett_rlc);
    proto_tree_add_expert(subtree, pinfo, eiindex, tvb, start, length);
}

/* Heuristic dissector looks for supported framing protocol (see wiki page)  */
static gboolean
dissect_rlc_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
    gint        offset             = 0;
    fp_info    *fpi;
    rlc_info   *rlci;
    tvbuff_t   *rlc_tvb;
    guint8      tag                = 0;
    guint       channelType        = UMTS_CHANNEL_TYPE_UNSPECIFIED;
    gboolean    fpInfoAlreadySet   = FALSE;
    gboolean    rlcInfoAlreadySet  = FALSE;
    gboolean    channelTypePresent = FALSE;
    gboolean    rlcModePresent     = FALSE;
    proto_item *ti                 = NULL;
    proto_tree *subtree            = NULL;
    struct atm_phdr *atm           = (struct atm_phdr *)data;

    /* Do this again on re-dissection to re-discover offset of actual PDU */

    /* Needs to be at least as long as:
       - the signature string
       - conditional header bytes
       - tag for data
       - at least one byte of RLC PDU payload */
    if (tvb_captured_length_remaining(tvb, offset) < (gint)(strlen(RLC_START_STRING)+2+2)) {
        return FALSE;
    }

    /* OK, compare with signature string */
    if (tvb_strneql(tvb, offset, RLC_START_STRING, (gint)strlen(RLC_START_STRING)) != 0) {
        return FALSE;
    }
    offset += (gint)strlen(RLC_START_STRING);

    /* If redissecting, use previous info struct (if available) */
    fpi = (fp_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_fp, 0);
    if (fpi == NULL) {
        /* Allocate new info struct for this frame */
        fpi = (fp_info *)wmem_alloc0(wmem_file_scope(), sizeof(fp_info));
    } else {
        fpInfoAlreadySet = TRUE;
    }
    rlci = (rlc_info *)p_get_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0);
    if (rlci == NULL) {
        /* Allocate new info struct for this frame */
        rlci = (rlc_info *)wmem_alloc0(wmem_file_scope(), sizeof(rlc_info));
    } else {
        rlcInfoAlreadySet = TRUE;
    }

    /* Setting non-zero UE-ID for RLC reassembly to work, might be
     * overriden if the optional URNTI tag is present */
    rlci->ueid[fpi->cur_tb] = 1;

    /* Read conditional/optional fields */
    while (tag != RLC_PAYLOAD_TAG) {
        /* Process next tag */
        tag = tvb_get_guint8(tvb, offset++);
        switch (tag) {
            case RLC_CHANNEL_TYPE_TAG:
                channelType = tvb_get_guint8(tvb, offset);
                offset++;
                channelTypePresent = TRUE;
                break;
            case RLC_MODE_TAG:
                rlci->mode[fpi->cur_tb] = tvb_get_guint8(tvb, offset);
                offset++;
                rlcModePresent = TRUE;
                break;
            case RLC_DIRECTION_TAG:
                if (tvb_get_guint8(tvb, offset) == DIRECTION_UPLINK) {
                    fpi->is_uplink = TRUE;
                    pinfo->link_dir = P2P_DIR_UL;
                } else {
                    fpi->is_uplink = FALSE;
                    pinfo->link_dir = P2P_DIR_DL;
                }
                offset++;
                break;
            case RLC_URNTI_TAG:
                rlci->ueid[fpi->cur_tb] = tvb_get_ntohl(tvb, offset);
                offset += 4;
                break;
            case RLC_RADIO_BEARER_ID_TAG:
                rlci->rbid[fpi->cur_tb] = tvb_get_guint8(tvb, offset);
                offset++;
                break;
            case RLC_LI_SIZE_TAG:
                rlci->li_size[fpi->cur_tb] = (enum rlc_li_size) tvb_get_guint8(tvb, offset);
                offset++;
                break;
            case RLC_PAYLOAD_TAG:
                /* Have reached data, so get out of loop */
                continue;
            default:
                /* It must be a recognised tag */
                report_heur_error(tree, pinfo, &ei_rlc_unknown_udp_framing_tag, tvb, offset-1, 1);
                return TRUE;
        }
    }

    if ((channelTypePresent == FALSE) && (rlcModePresent == FALSE)) {
        /* Conditional fields are missing */
        report_heur_error(tree, pinfo, &ei_rlc_missing_udp_framing_tag, tvb, 0, offset);
        return TRUE;
    }

    /* Store info in packet if needed */
    if (!fpInfoAlreadySet) {
        p_add_proto_data(wmem_file_scope(), pinfo, proto_fp, 0, fpi);
    }
    if (!rlcInfoAlreadySet) {
        p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_rlc, 0, rlci);
    }

    /**************************************/
    /* OK, now dissect as RLC             */

    /* Create tvb that starts at actual RLC PDU */
    rlc_tvb = tvb_new_subset_remaining(tvb, offset);
    switch (channelType) {
        case UMTS_CHANNEL_TYPE_UNSPECIFIED:
            /* Call relevant dissector according to RLC mode */
            col_set_str(pinfo->cinfo, COL_PROTOCOL, "RLC");
            col_clear(pinfo->cinfo, COL_INFO);

            if (tree) {
                ti = proto_tree_add_item(tree, proto_umts_rlc, rlc_tvb, 0, -1, ENC_NA);
                subtree = proto_item_add_subtree(ti, ett_rlc);
            }

            if (rlci->mode[fpi->cur_tb] == RLC_AM) {
                proto_item_append_text(ti, " AM");
                dissect_rlc_am(RLC_UNKNOWN_CH, rlc_tvb, pinfo, tree, subtree, atm);
            } else if (rlci->mode[fpi->cur_tb] == RLC_UM) {
                proto_item_append_text(ti, " UM");
                dissect_rlc_um(RLC_UNKNOWN_CH, rlc_tvb, pinfo, tree, subtree, atm);
            } else {
                proto_item_append_text(ti, " TM");
                dissect_rlc_tm(RLC_UNKNOWN_CH, rlc_tvb, pinfo, tree, subtree);
            }
            break;
        case UMTS_CHANNEL_TYPE_PCCH:
            dissect_rlc_pcch(rlc_tvb, pinfo, tree, data);
            break;
        case UMTS_CHANNEL_TYPE_CCCH:
            dissect_rlc_ccch(rlc_tvb, pinfo, tree, data);
            break;
        case UMTS_CHANNEL_TYPE_DCCH:
            dissect_rlc_dcch(rlc_tvb, pinfo, tree, data);
            break;
        case UMTS_CHANNEL_TYPE_PS_DTCH:
            dissect_rlc_ps_dtch(rlc_tvb, pinfo, tree, data);
            break;
        case UMTS_CHANNEL_TYPE_CTCH:
            dissect_rlc_ctch(rlc_tvb, pinfo, tree, data);
            break;
        case UMTS_CHANNEL_TYPE_BCCH:
            dissect_rlc_bcch(rlc_tvb, pinfo, tree, data);
            break;
        default:
            /* Unknown channel type */
            return FALSE;
    }

    return TRUE;
}

void
proto_register_rlc(void)
{
    module_t *rlc_module;
    expert_module_t* expert_rlc;
    static hf_register_info hf[] = {
        { &hf_rlc_dc,
          { "D/C Bit", "rlc.dc",
            FT_BOOLEAN, BASE_NONE, TFS(&rlc_dc_val), 0, NULL, HFILL }
        },
        { &hf_rlc_ctrl_type,
          { "Control PDU Type", "rlc.ctrl_pdu_type",
            FT_UINT8, BASE_DEC, VALS(rlc_ctrl_vals), 0, "PDU Type", HFILL }
        },
        { &hf_rlc_r1,
          { "Reserved 1", "rlc.r1",
            FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_rsn,
          { "Reset Sequence Number", "rlc.rsn",
            FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_hfni,
          { "Hyper Frame Number Indicator", "rlc.hfni",
            FT_UINT24, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_seq,
          { "Sequence Number", "rlc.seq",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_ext,
          { "Extension Bit", "rlc.ext",
            FT_BOOLEAN, BASE_NONE, TFS(&rlc_ext_val), 0, NULL, HFILL }
        },
        { &hf_rlc_he,
          { "Header Extension Type", "rlc.he",
            FT_UINT8, BASE_DEC, VALS(rlc_he_vals), 0, NULL, HFILL }
        },
        { &hf_rlc_p,
          { "Polling Bit", "rlc.p",
            FT_BOOLEAN, BASE_NONE, TFS(&rlc_p_val), 0, NULL, HFILL }
        },
        { &hf_rlc_pad,
          { "Padding", "rlc.padding",
            FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_frags,
          { "Reassembled Fragments", "rlc.fragments",
            FT_NONE, BASE_NONE, NULL, 0, "Fragments", HFILL }
        },
        { &hf_rlc_frag,
          { "RLC Fragment", "rlc.fragment",
            FT_FRAMENUM, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_duplicate_of,
          { "Duplicate of", "rlc.duplicate_of",
            FT_FRAMENUM, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_reassembled_in,
          { "Reassembled Message in frame", "rlc.reassembled_in",
            FT_FRAMENUM, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_data,
          { "Data", "rlc.data",
            FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_ciphered_data,
          { "Ciphered Data", "rlc.ciphered_data",
            FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_ciphered_lis_data,
          { "Ciphered LIs & Data", "rlc.ciphered_data",
            FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        /* LI information */
        { &hf_rlc_li,
          { "LI", "rlc.li",
            FT_NONE, BASE_NONE, NULL, 0, "Length Indicator", HFILL }
        },
        { &hf_rlc_li_value,
          { "LI value", "rlc.li.value",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_li_ext,
          { "LI extension bit", "rlc.li.ext",
            FT_BOOLEAN, BASE_NONE, TFS(&rlc_ext_val), 0, NULL, HFILL }
        },
        { &hf_rlc_li_data,
          { "LI Data", "rlc.li.data",
            FT_NONE, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        /* SUFI information */
        { &hf_rlc_sufi,
          { "SUFI", "rlc.sufi",
            FT_NONE, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_type,
          { "SUFI Type", "rlc.sufi.type",
            FT_UINT8, BASE_DEC, VALS(rlc_sufi_vals), 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_lsn,
          { "Last Sequence Number", "rlc.sufi.lsn",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_wsn,
          { "Window Size Number", "rlc.sufi.wsn",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_sn,
          { "Sequence Number", "rlc.sufi.sn",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_l,
          { "Length", "rlc.sufi.l",
            FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_len,
          { "Length", "rlc.sufi.len",
            FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_fsn,
          { "First Sequence Number", "rlc.sufi.fsn",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_bitmap,
          { "Bitmap", "rlc.sufi.bitmap",
            FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_cw,
          { "Codeword", "rlc.sufi.cw",
            FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_n,
          { "Nlength", "rlc.sufi.n",
            FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_sn_ack,
          { "SN ACK", "rlc.sufi.sn_ack",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_sn_mrw,
          { "SN MRW", "rlc.sufi.sn_mrw",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sufi_poll_sn,
          { "Poll SN", "rlc.sufi.poll_sn",
            FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        /* Other information */
        { &hf_rlc_header_only,
          { "RLC PDU header only", "rlc.header_only",
            FT_BOOLEAN, BASE_NONE, TFS(&rlc_header_only_val), 0 ,NULL, HFILL }
        },
        { &hf_rlc_channel,
          { "Channel", "rlc.channel",
            FT_NONE, BASE_NONE, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_channel_rbid,
          { "Radio Bearer ID", "rlc.channel.rbid",
            FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_channel_dir,
          { "Direction", "rlc.channel.dir",
            FT_UINT8, BASE_DEC, VALS(rlc_dir_vals), 0, NULL, HFILL }
        },
        { &hf_rlc_channel_ueid,
          { "User Equipment ID", "rlc.channel.ueid",
            FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_sequence_number,
          { "Sequence Number", "rlc.sequence_number",
            FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_length,
          { "Length", "rlc.length",
            FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL }
        },
        { &hf_rlc_bitmap_string,
          { "Bitmap string", "rlc.bitmap_string",
            FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL }
        },
    };

    static gint *ett[] = {
        &ett_rlc,
        &ett_rlc_frag,
        &ett_rlc_fragments,
        &ett_rlc_sdu,
        &ett_rlc_sufi,
        &ett_rlc_bitmap,
        &ett_rlc_rlist,
        &ett_rlc_channel
    };
    static ei_register_info ei[] = {
        { &ei_rlc_reassembly_fail_unfinished_sequence, { "rlc.reassembly.fail.unfinished_sequence", PI_REASSEMBLE, PI_ERROR, "Did not perform reassembly because of previous unfinished sequence.", EXPFILL }},
        { &ei_rlc_reassembly_fail_flag_set, { "rlc.reassembly.fail.flag_set", PI_REASSEMBLE, PI_ERROR, "Did not perform reassembly because fail flag was set previously.", EXPFILL }},
        { &ei_rlc_reassembly_lingering_endpoint, { "rlc.lingering_endpoint", PI_REASSEMBLE, PI_ERROR, "Lingering endpoint.", EXPFILL }},
        { &ei_rlc_reassembly_unknown_error, { "rlc.reassembly.unknown_error", PI_REASSEMBLE, PI_ERROR, "Unknown error.", EXPFILL }},
        { &ei_rlc_kasumi_implementation_missing, { "rlc.kasumi_implementation_missing", PI_UNDECODED, PI_WARN, "Unable to decipher packet since KASUMI implementation is missing.", EXPFILL }},
        { &ei_rlc_li_reserved, { "rlc.li.reserved", PI_PROTOCOL, PI_WARN, "Uses reserved LI", EXPFILL }},
        { &ei_rlc_li_incorrect_warn, { "rlc.li.incorrect", PI_PROTOCOL, PI_WARN, "Incorrect LI value", EXPFILL }},
        { &ei_rlc_li_incorrect_mal, { "rlc.li.incorrect", PI_MALFORMED, PI_ERROR, "Incorrect LI value 0x%x", EXPFILL }},
        { &ei_rlc_li_too_many, { "rlc.li.too_many", PI_MALFORMED, PI_ERROR, "Too many LI entries", EXPFILL }},
        { &ei_rlc_header_only, { "rlc.header_only.expert", PI_SEQUENCE, PI_NOTE, "RLC PDU SDUs have been omitted", EXPFILL }},
        { &ei_rlc_sufi_len, { "rlc.sufi.len.invalid", PI_MALFORMED, PI_ERROR, "Invalid length", EXPFILL }},
        { &ei_rlc_sufi_cw, { "rlc.sufi.cw.invalid", PI_PROTOCOL, PI_WARN, "Invalid last codeword", EXPFILL }},
        { &ei_rlc_sufi_type, { "rlc.sufi.type.invalid", PI_PROTOCOL, PI_WARN, "Invalid SUFI type", EXPFILL }},
        { &ei_rlc_reserved_bits_not_zero, { "rlc.reserved_bits_not_zero", PI_PROTOCOL, PI_WARN, "reserved bits not zero", EXPFILL }},
        { &ei_rlc_ctrl_type, { "rlc.ctrl_pdu_type.invalid", PI_PROTOCOL, PI_WARN, "Invalid RLC AM control type", EXPFILL }},
        { &ei_rlc_he, { "rlc.he.invalid", PI_PROTOCOL, PI_WARN, "Incorrect HE value", EXPFILL }},
        { &ei_rlc_ciphered_data, { "rlc.ciphered_data", PI_UNDECODED, PI_WARN, "Cannot dissect RLC frame because it is ciphered", EXPFILL }},
        { &ei_rlc_no_per_frame_data, { "rlc.no_per_frame_data", PI_PROTOCOL, PI_WARN, "Can't dissect RLC frame because no per-frame info was attached!", EXPFILL }},
        { &ei_rlc_incomplete_sequence, { "rlc.incomplete_sequence", PI_MALFORMED, PI_ERROR, "Error: Incomplete sequence", EXPFILL }},
        { &ei_rlc_unknown_udp_framing_tag, { "rlc.unknown_udp_framing_tag", PI_UNDECODED, PI_WARN, "Unknown UDP framing tag, aborting dissection", EXPFILL }},
        { &ei_rlc_missing_udp_framing_tag, { "rlc.missing_udp_framing_tag", PI_UNDECODED, PI_WARN, "Missing UDP framing conditional tag, aborting dissection", EXPFILL }}
    };

    proto_umts_rlc = proto_register_protocol("Radio Link Control", "RLC", "rlc");
    register_dissector("rlc.bcch",        dissect_rlc_bcch,        proto_umts_rlc);
    register_dissector("rlc.pcch",        dissect_rlc_pcch,        proto_umts_rlc);
    register_dissector("rlc.ccch",        dissect_rlc_ccch,        proto_umts_rlc);
    register_dissector("rlc.ctch",        dissect_rlc_ctch,        proto_umts_rlc);
    register_dissector("rlc.dcch",        dissect_rlc_dcch,        proto_umts_rlc);
    register_dissector("rlc.ps_dtch",     dissect_rlc_ps_dtch,     proto_umts_rlc);
    register_dissector("rlc.dch_unknown", dissect_rlc_dch_unknown, proto_umts_rlc);

    proto_register_field_array(proto_umts_rlc, hf, array_length(hf));
    proto_register_subtree_array(ett, array_length(ett));
    expert_rlc = expert_register_protocol(proto_umts_rlc);
    expert_register_field_array(expert_rlc, ei, array_length(ei));

    /* Preferences */
    rlc_module = prefs_register_protocol(proto_umts_rlc, NULL);

    prefs_register_obsolete_preference(rlc_module, "heuristic_rlc_over_udp");

    prefs_register_bool_preference(rlc_module, "perform_reassembly",
        "Try to reassemble SDUs",
        "When enabled, try to reassemble SDUs from the various PDUs received",
        &global_rlc_perform_reassemby);

    prefs_register_bool_preference(rlc_module, "header_only_mode",
        "May see RLC headers only",
        "When enabled, if data is not present, don't report as an error, but instead "
        "add expert info to indicate that headers were omitted",
        &global_rlc_headers_expected);

    prefs_register_bool_preference(rlc_module, "ignore_rrc_cipher_indication",
        "Ignore ciphering indication from higher layers",
        "When enabled, RLC will ignore sequence numbers reported in 'Security Mode Command'/'Security Mode Complete' (RRC) messages when checking if frames are ciphered",
        &global_ignore_rrc_ciphering_indication);

    prefs_register_bool_preference(rlc_module, "ciphered_data",
        "All data is ciphered",
        "When enabled, RLC will assume all payloads in RLC frames are ciphered",
        &global_rlc_ciphered);

#ifdef HAVE_UMTS_KASUMI
    prefs_register_bool_preference(rlc_module, "try_decipher",
        "Try to decipher data",
        "When enabled, RLC will try to decipher data. (Experimental)",
        &global_rlc_try_decipher);

    prefs_register_string_preference(rlc_module, "kasumi_key",
        "KASUMI key", "Key for kasumi 32 characters long hex-string", &global_rlc_kasumi_key);
#else
    /* If Wireshark isn't compiled with KASUMI we still want to register the above preferences
     * We are doing so for two reasons:
     * 1. To inform the user about the disabled preferences (using static text preference)
     * 2. To prevent errors when Wireshark reads a preferences file which includes records for these preferences
     */
    prefs_register_static_text_preference(rlc_module, "try_decipher",
        "Data deciphering is disabled", "Wireshark was compiled without the KASUMI decryption algorithm");

    prefs_register_obsolete_preference(rlc_module, "kasumi_key");
#endif /* HAVE_UMTS_KASUMI */

    prefs_register_enum_preference(rlc_module, "li_size",
        "LI size",
        "LI size in bits, either 7 or 15 bit",
        &global_rlc_li_size, li_size_enumvals, FALSE);

    register_init_routine(fragment_table_init);
    register_cleanup_routine(fragment_table_cleanup);
}

void
proto_reg_handoff_rlc(void)
{
    rrc_handle = find_dissector_add_dependency("rrc", proto_umts_rlc);
    ip_handle  = find_dissector_add_dependency("ip", proto_umts_rlc);
    bmc_handle = find_dissector_add_dependency("bmc", proto_umts_rlc);
    /* Add as a heuristic UDP dissector */
    heur_dissector_add("udp", dissect_rlc_heur, "RLC over UDP", "rlc_udp", proto_umts_rlc, HEURISTIC_DISABLE);
}

/*
 * Editor modelines
 *
 * Local Variables:
 * c-basic-offset: 4
 * tab-width: 8
 * indent-tabs-mode: nil
 * End:
 *
 * ex: set shiftwidth=4 tabstop=8 expandtab:
 * :indentSize=4:tabSize=8:noTabs=true:
 */