This file is indexed.

/usr/src/adv-17v35x-5.0.3.0-2/adv17v35x.c is in adv-17v35x-dkms 5.0.3.0-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
/*****************************************************************************/
/*
*      adv17v35x.c  -- Advantech multiport serial driver.
*
*      Copyright (C) 2016 Advantech Corporation.
*
*      Based on Linux 2.6.37 Kernel's  drivers/serial/8250.c and /8250_pci.c
*
*      This program is free software; you can redistribute it and/or modify
*      it under the terms of the GNU General Public License as published by
*      the Free Software Foundation; either version 2 of the License, or
*      (at your option) any later version.
*
*      This program is distributed in the hope that it will be useful,
*      but WITHOUT ANY WARRANTY; without even the implied warranty of
*      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*      GNU General Public License for more details.
*
*      You should have received a copy of the GNU General Public License
*      along with this program; if not, write to the Free Software
*      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*
*
*	   Multiport Serial Driver for EXAR's PCI Family of UARTs (XR17V358/354/352)
*
*       ChangeLog:
*	   for			: LINUX 2.6.9 and newer (Tested on various kernel versions from 2.6.9 to 4.2.x)
*	   date			: Mar 2017
*	   version		: 5.0.3.0
*
*	Check Release Notes for information on what has changed in the new version.
*
*/

#include <linux/module.h>
#include <linux/tty.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/slab.h>

#include <linux/tty_flip.h>
#include <linux/serial_reg.h>
#include <linux/serial.h>
#include <linux/serial_core.h>

#include <asm/io.h>
#include <asm/irq.h>
#include <asm/irq.h>
#include <asm/bitops.h>
#include <asm/byteorder.h>
#include <asm/serial.h>
#include <asm/io.h>
#include <asm/uaccess.h>

#include "linux/version.h"
#include "precomp.h"

#define _INLINE_ inline

#if LINUX_VERSION_CODE > KERNEL_VERSION(3, 8, 0)
#define __devinitdata
#define __devinit
#define __devexit
#define __devexit_p
#endif

#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 7, 0)
struct serial_uart_config {
	char	*name;
	int	dfl_xmit_fifo_size;
	int	flags;
};
#endif

//void tty_flip_buffer_push(struct tty_port *port);

/*
 * Definitions for PCI support.
 */

#define ADVANTECH_EXAR_VER	        "5.0.3.0"
#define ADVANTECH_EXAR_DATE	        "2017/03/06"
#define ADVANTECH_EXAR_FILE_VER     "5.0.3.0"

#define ADVANTECH_VID	            0x13FE

#define PCIE_1602		            0x000E
#define PCIE_1604		            0x000D
#define PCIE_1610		            0x000C
#define PCIE_1612		            0x000B
#define PCIE_1620		            0x000A
#define PCIE_1622		            0x0009

// support for beijing's cards
#define PCIE_0014					0x0014
#define PCIE_0015					0x0015
#define PCIE_0016					0x0016

#define PCM_3612I                   0x001F
#define PCI_1602                    0x0018
#define PCI_1604                    0x0019
#define PCI_1610                    0x001A
#define PCI_1612                    0x001B
#define PCI_1620                    0x001C
#define PCI_1622                    0x001D


#define FL_BASE_MASK		        0x0007
#define FL_BASE0		            0x0000
#define FL_GET_BASE(x)		        (x & FL_BASE_MASK)

#define NR_PORTS	                256

#define XR_MAJOR                    0
#define XR_MINOR                    0

/*
 * The special register set for XR17V35x UARTs.
 */
#define XR_17v35x_UART_RHR			0 
#define	XR_17V35X_UART_DLD	        2
#define	XR_17V35X_UART_MSR	        6
#define XR_17V35X_EXTENDED_FCTR		8
#define XR_17V35X_EXTENDED_EFR		9
#define XR_17V35X_TXFIFO_CNT		10
#define XR_17V35X_EXTENDED_TXTRG	10
#define XR_17V35X_RXFIFO_CNT		11
#define XR_17V35X_EXTENDED_RXTRG	11
#define XR_17V35X_UART_XOFF2        	13 
#define XR_17V35X_UART_XOFF1 		0xC0
#define XR_17V35X_UART_XON1		0xE0
#define XR_17V35X_FCTR_RTS_8DELAY	0x03
#define XR_17V35X_FCTR_TRGD		192
#define XR_17V35x_FCTR_RS485	        0x20

#define XR_17V35x_MPIOLVL_7_0       0x90
#define XR_17V35x_MPIO3T_7_0        0x91
#define XR_17V35x_MPIOSEL_7_0       0x93
#define XR_17V35x_MPIOLVL_15_8       0x96
#define XR_17V35x_MPIO3T_15_8        0x97
#define XR_17V35x_MPIOSEL_15_8       0x99


// Set this parameter to 1 to enabled internal loopback
#define ENABLE_INTERNAL_LOOPBACK      0

#define UART_17V35X_RX_OFFSET		0x100
#define UART_17V35X_TX_OFFSET 		0x100

#define	XR_17V35X_IER_RTSDTR	        0x40
#define XR_17V35X_IER_CTSDSR	        0x80

#define XR_17V35X_8XMODE	        0x88
#define XR_17V35X_4XMODE	        0x89

#define XR_17V35X_MPIOLVL_L		    0x90
#define XR_17V35X_MPIOLVL_H		    0x96

#define XR_17V35X_MPIOSEL_L		    0x93
#define XR_17V35X_MPIOSEL_H		    0x99

#define DIVISOR_CHANGED   0
#define XR_17V35X_RESET             0x8A

#define PCI_NUM_BAR_RESOURCES	6


/*
 * serial mode, RS232 RS422 Master  RS485/RS422 Slave
 */
#define SERIAL_MODE_UNKNOWN         0
#define SERIAL_MODE_RS232           1
#define SERIAL_MODE_RS422M          2
#define SERIAL_MODE_RS485ORRS422S   3

#define PASS_LIMIT					512

/*
 * macro for calcaute divide of baud
 */
#define TRUNC(X_Decuple)		            ( (X_Decuple)/10 )
#define ROUND(X_Decuple)		            ( ((X_Decuple)%10)>=5 ? (X_Decuple)/10+1 : (X_Decuple)/10 )		

#define 	ADVANTECH_EXAR_MAIGC            'x'
#define		ADV_READ_REG      				_IO(ADVANTECH_EXAR_MAIGC, 1)
#define 	ADV_WRITE_REG     				_IO(ADVANTECH_EXAR_MAIGC, 2)
#define 	ADV_GET_SERIAL_MODE				_IO(ADVANTECH_EXAR_MAIGC, 3)
#define 	ADV_SET_TURN_AROUND_DELAY		_IO(ADVANTECH_EXAR_MAIGC, 4)

/* For SPI bus, to get Board ID */
#define	REGB			0x8E
#define	EECK_BIT		0x10
#define	EECS_BIT		0x20
#define	EEDI_BIT		0x40
#define	EEDO_BIT		0x80

#define	GPIOA				0x12
#define	SPI_READ_CMD		0x41

/* For fixed number */
#define	MAX_STRING_LEN		64
#define	MAX_CARD_SUPPORT	16

/* DTR/DSR flow control support */
#ifndef CDTRDSR
#define CDTRDSR				004000000000		/* For DTR/DSR flow control */
#endif

#if 0
#define DEBUG_INTR(fmt...)	printk(fmt)
#else
#define DEBUG_INTR(fmt...)	do { } while (0)
#endif

struct serial_private {
	struct pci_dev		*dev;
	unsigned int		nr;
	void __iomem		*remapped_bar[PCI_NUM_BAR_RESOURCES];
	struct pci_serial_quirk	*quirk;
	int    uart_index[NR_PORTS];
	int			line[0];
};

struct pciserial_board {
	unsigned int flags;
	unsigned int num_ports;
	unsigned int base_baud;
	unsigned int uart_offset;
	unsigned int reg_shift;
	unsigned int first_offset;
};

/*
 * init function returns:
 *  > 0 - number of ports
 *  = 0 - use board->num_ports
 *  < 0 - error
 */
struct pci_serial_quirk {
	u32	vendor;
	u32	device;
	u32	subvendor;
	u32	subdevice;
	int	(*init)(struct pci_dev *dev);
	int	(*setup)(struct serial_private *, 
			 const struct pciserial_board *,
			 struct uart_port *, int);
	void	(*exit)(struct pci_dev *dev);
};

/*
 * This is the configuration table for all of the PCI serial boards
 * which we support.  It is directly indexed by the advpci_board_num_t enum
 * value, which is encoded in the pci_device_id PCI probe table's
 * driver_data member.
 *
 * The makeup of these names are:
 *  pbn_bn{_bt}_n_baud
 *
 *  bn   = PCI BAR number
 *  bt   = Index using PCI BARs
 *  n    = number of serial ports
 *  baud = baud rate
 */
enum advpci_board_num_t {
	adv_8port = 0,
	adv_4port,
	adv_2port,
};

static struct pciserial_board advpciserial_boards[] __devinitdata = {
	[adv_2port] = {
		.flags		    = FL_BASE0,
		.num_ports	    = 2,
		.base_baud	    = 7812500,
		.uart_offset	= 0x400,
		.reg_shift	    = 0,
		.first_offset	= 0,
	},

	[adv_4port] = {
		.flags		    = FL_BASE0,
		.num_ports	    = 4,
		.base_baud	    = 7812500,
		.uart_offset	= 0x400,
		.reg_shift	    = 0,
		.first_offset	= 0,
	},

	[adv_8port] = {
		.flags		    = FL_BASE0,
		.num_ports	    = 8,
		.base_baud	    = 7812500,
		.uart_offset	= 0x400,
		.reg_shift	    = 0,
		.first_offset	= 0,
	},
};

/*
 * Configuration:
 *   share_irqs - whether we pass SA_SHIRQ to request_irq().  This option
 *                is unsafe when used on edge-triggered interrupts.
 */
#define SERIALEXAR_SHARE_IRQS 1 
unsigned int share_irqs = SERIALEXAR_SHARE_IRQS;

/*
 * We default to IRQ0 for the "no irq" hack.   Some
 * machine types want others as well - they're free
 * to redefine this in their header file.
 */
#define is_real_interrupt(irq)	((irq) != 0)
#define MSR_SAVE_FLAGS UART_MSR_ANY_DELTA

#define LSR_SAVE_FLAGS UART_LSR_BRK_ERROR_BITS
struct uart_adv_port {
	struct uart_port	port;
	struct timer_list	timer;		/* "no irq" timer */
	struct list_head	list;		/* ports on this IRQ */
	unsigned short		capabilities;	/* port capabilities */
	unsigned short		bugs;		/* port bugs */
	unsigned int		tx_loadsz;	/* transmit fifo load size */
	unsigned char		acr;
	unsigned char		ier;
	unsigned char		lcr;
	unsigned char		mcr;
	unsigned char		mcr_mask;	/* mask of user bits */
	unsigned char		mcr_force;	/* mask of forced bits */

	unsigned char		lsr_saved_flags;
	unsigned char		msr_saved_flags;
	
	unsigned short 		deviceid;
	unsigned short 		board_id;
	unsigned char		channelnum;

	/*
	 * We provide a per-port pm hook.
	 */
	void			(*pm)(struct uart_port *port,
					  unsigned int state, unsigned int old);

	int 			index;			/* serial index in card, start at 0 */
	int				serialMode;		/* RS232 or RS422 or RS485 */

	int				current_card_nr;
	int				fix_number_index;
};

struct irq_info {
	struct			hlist_node node;
	int			irq;
	spinlock_t		lock;	/* Protects list not the hash */
	struct list_head	*head;
};

#define NR_IRQ_HASH		32	/* Can be adjusted later */
static struct hlist_head irq_lists[NR_IRQ_HASH];
static DEFINE_MUTEX(hash_mutex);	/* Used to walk the hash */

/*
 * Here we define the default xmit fifo size used for each type of UART.
 */
#define PORT_MAX_XR 1
#define XRPCIe_TYPE 1 // the second entry that is [1] in the array

static const struct serial_uart_config uart_config[PORT_MAX_XR+1] = {
	{ "Unknown",	1,	    0 },
	{ "ADV17v35x",	256,	0 },
};

/*++++++++++++++++++++++++++++++++  function declare  ++++++++++++++++++++++++++++++++*/

static int serialadv_setRS485(struct uart_port *port, int turnOn, int turnaroundTime);
static void serial_set_dtrdsr ( struct uart_port *port, int turn_on);
static void serial_set_ctsrts(struct uart_port *port, int turn_on);
static unsigned int
serialadv_calc_divisor(struct uart_port *port, unsigned int baud,
						unsigned int *quot, unsigned int *quot_fraction, unsigned int *devide1);

/*--------------------------------  function declare  --------------------------------*/

static int
setup_port(struct serial_private *priv, struct uart_port *port,
	   int bar, int offset, int regshift)
{
	struct pci_dev *dev = priv->dev;
	unsigned long base, len;

	if (bar >= PCI_NUM_BAR_RESOURCES)
		return -EINVAL;

	base = pci_resource_start(dev, bar);

	if (pci_resource_flags(dev, bar) & IORESOURCE_MEM) {
		len =  pci_resource_len(dev, bar);

		if (!priv->remapped_bar[bar])
			priv->remapped_bar[bar] = ioremap(base, len);
		if (!priv->remapped_bar[bar])
			return -ENOMEM;

		port->iotype = UPIO_MEM;
		port->iobase = 0;
		port->mapbase = base + offset;
		port->membase = priv->remapped_bar[bar] + offset;
		port->regshift = regshift;
	} else {
		// got to be memory mapped. some hardware reading error?
		return -EINVAL;
	}
	return 0;
}


static int
pci_default_setup(struct serial_private *priv,
		  const struct pciserial_board *board,
		  struct uart_port *port, int idx)
{
	unsigned int bar, offset = board->first_offset;

	bar = FL_GET_BASE(board->flags);	
	offset += idx * board->uart_offset;

	return setup_port(priv, port, bar, offset, board->reg_shift);
}

/*
 * Master list of serial port init/setup/exit quirks.
 * This does not describe the general nature of the port.
 * (ie, baud base, number and location of ports, etc)
 *
 * This list is ordered alphabetically by vendor then device.
 * Specific entries must come before more generic entries.
 */
static struct pci_serial_quirk pci_serial_quirks[] = {	
	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_1602,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},
	
	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_1604,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_1610,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_1612,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_1620,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_1622,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_0014,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_0015,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCIE_0016,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCM_3612I,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},
	{
		.vendor		= ADVANTECH_VID,
		.device		= PCI_1602,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,	
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCI_1604,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCI_1610,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCI_1612,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCI_1620,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,
	},

	{
		.vendor		= ADVANTECH_VID,
		.device		= PCI_1622,
		.subvendor	= PCI_ANY_ID,
		.subdevice	= PCI_ANY_ID,
		.setup		= pci_default_setup,
	},
};

static _INLINE_ int quirk_id_matches(u32 quirk_id, u32 dev_id)
{
	return quirk_id == PCI_ANY_ID || quirk_id == dev_id;
}

static struct pci_serial_quirk *find_quirk(struct pci_dev *dev)
{
	struct pci_serial_quirk *quirk;

	for (quirk = pci_serial_quirks; ; quirk++)
		if (quirk_id_matches(quirk->vendor, dev->vendor) &&
		    quirk_id_matches(quirk->device, dev->device))		    
		 	break;
	return quirk;
}

static _INLINE_ unsigned int serial_in(struct uart_adv_port *up, int offset)
{
	return readb(up->port.membase + offset);
}

static _INLINE_ void
serial_out(struct uart_adv_port *up, int offset, int value)
{
	writeb(value, up->port.membase + offset);
}

static int serial_get_mode(struct uart_adv_port *up)
{
    unsigned char mpiolvl_l = 0, mpiolvl_h = 0;
	unsigned char serialMode = SERIAL_MODE_UNKNOWN;
	unsigned char mpioData = 0;
	int	index=0;
   
	// all MPIO set as input
	serial_out(up, XR_17V35X_MPIOSEL_L, 0xFF);
	serial_out(up, XR_17V35X_MPIOSEL_H, 0xFF);
	
	mpiolvl_l = serial_in(up, XR_17V35X_MPIOLVL_L);
	mpiolvl_h = serial_in(up, XR_17V35X_MPIOLVL_H);
    
	mpioData = up->index<4 ? mpiolvl_l : mpiolvl_h;
	index = up->index<4 ? up->index : up->index-4;	

	if ( mpioData & (1<<(index*2)) )
	{
	    serialMode = SERIAL_MODE_RS232;
	}
	else if ( mpioData & (1<<(index*2+1)) )
	{
	    serialMode = SERIAL_MODE_RS485ORRS422S;
	}
	else
	{
	    serialMode = SERIAL_MODE_RS422M;
	}
	DEBUG_INTR(KERN_INFO "serialMode = %d\n", serialMode);
	up->serialMode = serialMode;
	
	return serialMode;
}


#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 16)
static void serialadv_stop_tx(struct uart_port *port, unsigned int tty_stop)
#else
static void serialadv_stop_tx(struct uart_port *port)
#endif
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;

	if (up->ier & UART_IER_THRI) {
		up->ier &= ~UART_IER_THRI;
		serial_out(up, UART_IER, up->ier);
	}
}

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 16)
static void serialadv_start_tx(struct uart_port *port, unsigned int tty_stop)
#else
static void serialadv_start_tx(struct uart_port *port)
#endif
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;

	if (!(up->ier & UART_IER_THRI)) {
		up->ier |= UART_IER_THRI;
		serial_out(up, UART_IER, up->ier);
	}
}

static void serialadv_stop_rx(struct uart_port *port)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;

	up->ier &= ~UART_IER_RLSI;
	up->port.read_status_mask &= ~UART_LSR_DR;
	serial_out(up, UART_IER, up->ier);
}

static void serialadv_enable_ms(struct uart_port *port)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;

	up->ier |= UART_IER_MSI;
	serial_out(up, UART_IER, up->ier);
}

static void
receive_chars(struct uart_adv_port *up, unsigned int *status)
{
#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 9, 0)  // prevent compile warning

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 32)
	struct tty_struct *tty = up->port.state->port.tty;
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
	struct tty_struct *tty = up->port.info->port.tty;
#else 
	struct tty_struct *tty = up->port.info->tty;
#endif

#endif

#if LINUX_VERSION_CODE > KERNEL_VERSION(3, 9, 0)	
	struct uart_port *port = &up->port;
#endif	
	unsigned char ch[256], lsr = *status;
	char flag;
	int i, datasize_in_fifo = 0, port_index;	
	while(datasize_in_fifo!=serial_in(up, XR_17V35X_RXFIFO_CNT))
	/*Read Receive Fifo count until we get read same value twice*/
		datasize_in_fifo=serial_in(up, XR_17V35X_RXFIFO_CNT);

	port_index = up->port.line;
	flag = TTY_NORMAL;
  
	if (unlikely(lsr & (UART_LSR_BI | UART_LSR_PE | UART_LSR_FE | UART_LSR_OE))) 
	{
		/*
		* Mask off conditions which should be ignored.
		*/
		lsr &= up->port.read_status_mask;

		if (lsr & UART_LSR_BI) 
		{
			DEBUG_INTR("handling break....");
			flag = TTY_BREAK;
		} 
		else if (lsr & UART_LSR_PE)
		{
			flag = TTY_PARITY;
			printk("handling port<%d> Parity error....\n",port_index);			
		}
		else if (lsr & UART_LSR_FE)
		{
		    DEBUG_INTR("handling Frame error....\n");	
			flag = TTY_FRAME;
		}
	}
	
	//memcpy_fromio(ch, up->port.membase + UART_17V35X_RX_OFFSET, datasize_in_fifo);
    for(i=0;i<datasize_in_fifo;i++)
    {
      ch[i]= serial_in(up, XR_17v35x_UART_RHR);
    }
	up->port.icount.rx+=datasize_in_fifo;
	
	for(i = 0; i < datasize_in_fifo; i++)
	{
	#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 21)
	    if (uart_handle_sysrq_char(&up->port, ch[i], NULL)) 
	#else
		if (uart_handle_sysrq_char(&up->port, ch[i])) 
	#endif
		{
			continue;
		}
		uart_insert_char(&up->port, lsr, UART_LSR_OE, ch[i], flag);
	}
    spin_unlock(&up->port.lock);
#if LINUX_VERSION_CODE > KERNEL_VERSION(3, 9, 0)
	tty_flip_buffer_push(&port->state->port);
#else
	tty_flip_buffer_push(tty);
#endif
	spin_lock(&up->port.lock);

	DEBUG_INTR(" LSR_DR...");
}

static void transmit_chars(struct uart_adv_port *up)
{
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 32) 
	struct circ_buf *xmit = &up->port.info->xmit;
#else
	struct circ_buf *xmit = &up->port.state->xmit;
#endif
	int count, bytes_in_fifo;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 16)
	int tmp;
#endif

	if (up->port.x_char) {
		serial_out(up, UART_TX, up->port.x_char);
		up->port.icount.tx++;
		up->port.x_char = 0;
		return;
	}
	if (uart_tx_stopped(&up->port)) {
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 16)
		serialadv_stop_tx(&up->port, 0);
#else
		serialadv_stop_tx(&up->port);
#endif
		return;
	}
	if (uart_circ_empty(xmit)) {
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 16)
		serialadv_stop_tx(&up->port, 0);
#else
		serialadv_stop_tx(&up->port);
#endif
		return;
	}

	bytes_in_fifo = serial_in(up, XR_17V35X_TXFIFO_CNT);
	// read the fifo count untill we get the same value twice
	while (bytes_in_fifo != serial_in(up, XR_17V35X_TXFIFO_CNT))
		bytes_in_fifo = serial_in(up, XR_17V35X_TXFIFO_CNT);

	// how much buffer is availabe now to write?	
	count = up->port.fifosize - bytes_in_fifo;
	
	if (uart_circ_chars_pending(xmit) < count)
		count = uart_circ_chars_pending(xmit);

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 16)
	if(count > 0)
	{
		//serial_out(up, UART_TX, xmit->buf[xmit->tail]);
		memcpy_toio(up->port.membase + UART_17V35X_TX_OFFSET, &(xmit->buf[xmit->tail]), 1);
		xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
	}
#else
	do
	{	
		// if the count is more than (tail to end of the buffer), transmit only the rest here.
		// tail+tmp&(UART_XMIT_SIZE-1) will reset the tail to the starting of the circular buffer
		if( ((xmit->tail + count) & (UART_XMIT_SIZE-1)) < xmit->tail)
		{			
			tmp = UART_XMIT_SIZE - xmit->tail;
			memcpy_toio(up->port.membase + UART_17V35X_TX_OFFSET, &(xmit->buf[xmit->tail]), tmp);
			xmit->tail += tmp;
			xmit->tail &= (UART_XMIT_SIZE-1);
			up->port.icount.tx += tmp;
			count	-= tmp;
		}
		else
		{		
			memcpy_toio(up->port.membase + UART_17V35X_TX_OFFSET, &(xmit->buf[xmit->tail]), count);	
			xmit->tail += count;
			xmit->tail &= UART_XMIT_SIZE - 1;
			up->port.icount.tx += count;
			count = 0;
		}

	}while (count > 0);
#endif


	if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
		uart_write_wakeup(&up->port);

	DEBUG_INTR("THRE...");

	if (uart_circ_empty(xmit))
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 16)
		serialadv_stop_tx(&up->port, 0);
#else
		serialadv_stop_tx(&up->port);
#endif
}

static unsigned int check_modem_status(struct uart_adv_port *up)
{
	unsigned int status = serial_in(up, UART_MSR);

	status |= up->msr_saved_flags;
	up->msr_saved_flags = 0;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 27) 
	if (status & UART_MSR_ANY_DELTA && up->ier & UART_IER_MSI) 
#else
	if (status & UART_MSR_ANY_DELTA && up->ier & UART_IER_MSI &&
	    up->port.state != NULL) 
#endif
	{
		if (status & UART_MSR_TERI)
			up->port.icount.rng++;
		if (status & UART_MSR_DDSR)
			up->port.icount.dsr++;
		if (status & UART_MSR_DDCD)
			uart_handle_dcd_change(&up->port, status & UART_MSR_DCD);
		if (status & UART_MSR_DCTS)
			uart_handle_cts_change(&up->port, status & UART_MSR_CTS);

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 32) 
		wake_up_interruptible(&up->port.info->delta_msr_wait);
#else
		wake_up_interruptible(&up->port.state->port.delta_msr_wait);
#endif
	}

	return status;
}

/*
 * This handles the interrupt from one port.
 */
static void serialadv_handle_port(struct uart_adv_port *up)
{
	unsigned int status;
	unsigned long flags;

	spin_lock_irqsave(&up->port.lock, flags);

	status = serial_in(up, UART_LSR);

	DEBUG_INTR("status = %x...", status);

	if (status & (UART_LSR_DR | UART_LSR_BI))
		receive_chars(up, &status);
	check_modem_status(up);
	if (status & UART_LSR_THRE)
		transmit_chars(up);

	spin_unlock_irqrestore(&up->port.lock, flags);
}

/*
 * This is the serial driver's interrupt routine.
 *
 * Arjan thinks the old way was overly complex, so it got simplified.
 * Alan disagrees, saying that need the complexity to handle the weird
 * nature of ISA shared interrupts.  (This is a special exception.)
 *
 * In order to handle ISA shared interrupts properly, we need to check
 * that all ports have been serviced, and therefore the ISA interrupt
 * line has been de-asserted.
 *
 * This means we need to loop through all ports. checking that they
 * don't have an interrupt pending.
 */
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 18)
static irqreturn_t serialadv_interrupt(int irq, void *dev_id, struct pt_regs *regs)
#else
static irqreturn_t serialadv_interrupt(int irq, void *dev_id)
#endif
{
	struct irq_info *i = dev_id;
	struct list_head *l, *end = NULL;
	int pass_counter = 0, handled = 0;

	DEBUG_INTR("serialadv_interrupt(%d)...", irq);

	spin_lock(&i->lock);

	l = i->head;
	do {
		struct uart_adv_port *up;
		unsigned int iir, lcr;

		up = list_entry(l, struct uart_adv_port, list);

		lcr = serial_in(up, UART_LCR);  // store value of LCR
		serial_out(up, UART_LCR, lcr & 0x7F); // ensure LCR bit-7=0 before reading UART_IIR
		iir = serial_in(up, UART_IIR);
		if (!(iir & UART_IIR_NO_INT)) {
			serialadv_handle_port(up);

			handled = 1;

			end = NULL;
		} else if (end == NULL)
			end = l;

		serial_out(up, UART_LCR, lcr); // restore LCR
		l = l->next;

		if (l == i->head && pass_counter++ > PASS_LIMIT) {
			/* If we hit this, we're dead. */
			printk(KERN_ERR
				"serialadv: too much work for irq%d\n", irq);
			break;
		}
	} while (l != end);

	spin_unlock(&i->lock);

	DEBUG_INTR("end.\n");

	return IRQ_RETVAL(handled);
}

/*
 * To support ISA shared interrupts, we need to have one interrupt
 * handler that ensures that the IRQ line has been deasserted
 * before returning.  Failing to do this will result in the IRQ
 * line being stuck active, and, since ISA irqs are edge triggered,
 * no more IRQs will be seen.
 */
static void serial_do_unlink(struct irq_info *i, struct uart_adv_port *up)
{
	spin_lock_irq(&i->lock);

	if (!list_empty(i->head)) {
		if (i->head == &up->list)
			i->head = i->head->next;
		list_del(&up->list);
	} else {
		BUG_ON(i->head != &up->list);
		i->head = NULL;
	}

	spin_unlock_irq(&i->lock);

	/* List empty so throw away the hash node */
	if (i->head == NULL) {
		hlist_del(&i->node);
		kfree(i);
	}
}

static int serial_link_irq_chain(struct uart_adv_port *up)
{
	struct hlist_head *h;
	struct hlist_node *n;
	struct irq_info *i;

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 16)
	int ret, irq_flags = up->port.flags & UPF_SHARE_IRQ ? IRQF_SHARED : 0;
#else
	int ret, irq_flags = up->port.flags & UPF_SHARE_IRQ ? SA_SHIRQ : 0;
#endif

	mutex_lock(&hash_mutex);

	h = &irq_lists[up->port.irq % NR_IRQ_HASH];

	hlist_for_each(n, h) {
		i = hlist_entry(n, struct irq_info, node);
		if (i->irq == up->port.irq)
			break;
	}

	if (n == NULL) {
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 9)
		i = kmalloc(sizeof(struct irq_info), GFP_KERNEL);
		memset(i , 0, sizeof(struct irq_info));
#else
		i = kzalloc(sizeof(struct irq_info), GFP_KERNEL);
#endif
		if (i == NULL) {
			mutex_unlock(&hash_mutex);
			return -ENOMEM;
		}
		spin_lock_init(&i->lock);
		i->irq = up->port.irq;
		hlist_add_head(&i->node, h);
	}
	mutex_unlock(&hash_mutex);

	spin_lock_irq(&i->lock);

	if (i->head) {
		list_add_tail(&up->list, i->head);
		spin_unlock_irq(&i->lock);

		ret = 0;
	} else {
		INIT_LIST_HEAD(&up->list);
		i->head = &up->list;
		spin_unlock_irq(&i->lock);

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 32)
		//irq_flags = up->port.flags & UPF_SHARE_IRQ ? IRQF_SHARED: 0;
		irq_flags |= up->port.irqflags;
#elif LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 16)
		irq_flags = up->port.flags & UPF_SHARE_IRQ ? SA_SHIRQ : 0;
#else
		irq_flags = up->port.flags & UPF_SHARE_IRQ ? IRQF_SHARED : 0;
#endif
		ret = request_irq(up->port.irq, serialadv_interrupt,
				  irq_flags, "ADVserial", i);
		if (ret < 0)
			serial_do_unlink(i, up);
	}

	return ret;
}

static void serial_unlink_irq_chain(struct uart_adv_port *up)
{
	struct irq_info *i = NULL;
	struct hlist_node *n;
	struct hlist_head *h;

	mutex_lock(&hash_mutex);

	h = &irq_lists[up->port.irq % NR_IRQ_HASH];

	hlist_for_each(n, h) {
		i = hlist_entry(n, struct irq_info, node);
		if (i->irq == up->port.irq)
			break;
	}

	BUG_ON(n == NULL);
	BUG_ON(i->head == NULL);

	if (list_empty(i->head))
		free_irq(up->port.irq, i);

	serial_do_unlink(i, up);
	mutex_unlock(&hash_mutex);
}

static inline int poll_timeout(int timeout)
{
	return timeout > 6 ? (timeout / 2 - 2) : 1;
}

/*
 * This function is used to handle ports that do not have an
 * interrupt.  This doesn't work very well for 16450's, but gives
 * barely passable results for a 16550A.  (Although at the expense
 * of much CPU overhead).
 */
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 15, 0)
static void serialadv_timeout(unsigned long data)
#else
static void serialadv_timeout(struct timer_list *t)
#endif
{
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 15, 0)
	struct uart_adv_port *up = (struct uart_adv_port *)data;
#else
	struct uart_adv_port *up = from_timer(up, t, timer);
#endif
	unsigned int iir;

	iir = serial_in(up, UART_IIR);
	if (!(iir & UART_IIR_NO_INT))
		serialadv_handle_port(up);
	mod_timer(&up->timer, jiffies + poll_timeout(up->port.timeout));
}

#define BOTH_EMPTY (UART_LSR_TEMT | UART_LSR_THRE)

static unsigned int serialadv_tx_empty(struct uart_port *port)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned long flags;
	unsigned int lsr;

	spin_lock_irqsave(&up->port.lock, flags);
	lsr = serial_in(up, UART_LSR);
	up->lsr_saved_flags |= lsr & LSR_SAVE_FLAGS;
	spin_unlock_irqrestore(&up->port.lock, flags);

	return (lsr & BOTH_EMPTY) == BOTH_EMPTY ? TIOCSER_TEMT : 0;
}

static unsigned int serialadv_get_mctrl(struct uart_port *port)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned int status;
	unsigned int ret;

	status = check_modem_status(up);

	ret = 0;
	if (status & UART_MSR_DCD)
		ret |= TIOCM_CAR;
	if (status & UART_MSR_RI)
		ret |= TIOCM_RNG;
	if (status & UART_MSR_DSR)
		ret |= TIOCM_DSR;
	if (status & UART_MSR_CTS)
		ret |= TIOCM_CTS;
	return ret;
}

static void serialadv_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned char mcr = 0;

	if (mctrl & TIOCM_RTS)
		mcr |= UART_MCR_RTS;
	if (mctrl & TIOCM_DTR)
		mcr |= UART_MCR_DTR;
	if (mctrl & TIOCM_OUT1)
		mcr |= UART_MCR_OUT1;
	if (mctrl & TIOCM_OUT2)
		mcr |= UART_MCR_OUT2;
	if (mctrl & TIOCM_LOOP)
		mcr |= UART_MCR_LOOP;

	mcr = (mcr & up->mcr_mask) | up->mcr_force | up->mcr;

	serial_out(up, UART_MCR, mcr);
}

static void serialadv_break_ctl(struct uart_port *port, int break_state)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned long flags;

	spin_lock_irqsave(&up->port.lock, flags);
	if (break_state == -1)
		up->lcr |= UART_LCR_SBC;
	else
		up->lcr &= ~UART_LCR_SBC;
	serial_out(up, UART_LCR, up->lcr);
	spin_unlock_irqrestore(&up->port.lock, flags);
}

static int serialadv_startup(struct uart_port *port)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned long flags;
	int retval;

	up->capabilities = uart_config[up->port.type].flags;

	serial_out(up, XR_17V35X_EXTENDED_EFR, UART_EFR_ECB);
	serial_out(up, UART_IER, 0);

	/* Set the RX/TX trigger levels */
	/* These are some default values, the OEMs can change these values
		* according to their best case scenarios */
	
	serial_out(up, XR_17V35X_EXTENDED_RXTRG, 32);
	serial_out(up, XR_17V35X_EXTENDED_TXTRG, 64);


	/* Hysteresis level of 8 */
	serial_out(up, XR_17V35X_EXTENDED_FCTR, XR_17V35X_FCTR_TRGD | XR_17V35X_FCTR_RTS_8DELAY);

	serial_out(up, UART_LCR, 0);

	/* Wake up and initialize UART */
	serial_out(up, XR_17V35X_EXTENDED_EFR, UART_EFR_ECB | 0x10/*Enable Shaded bits access*/);
	serial_out(up,XR_17V35X_UART_MSR, 0);
	serial_out(up, UART_IER, 0);
	serial_out(up, UART_LCR, 0);

	/*
	 * Clear the FIFO buffers and disable them.
	 * (they will be reeanbled in set_termios())
	 */
	serial_out(up, UART_FCR, UART_FCR_ENABLE_FIFO |
			UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT);
	serial_out(up, UART_FCR, 0);
	
	/*
	 * Clear the interrupt registers.
	 */
	(void) serial_in(up, UART_LSR);
	(void) serial_in(up, UART_RX);
	(void) serial_in(up, UART_IIR);
	(void) serial_in(up, UART_MSR);

	if(port->irq) {
		retval = serial_link_irq_chain(up);
		if(retval)
			return retval;
	}

	/*
	 * Now, initialize the UART
	 */
	serial_out(up, UART_LCR, UART_LCR_WLEN8);

	spin_lock_irqsave(&up->port.lock, flags);
		
	/*
	* Most PC uarts need OUT2 raised to enable interrupts.
	*/
	if (is_real_interrupt(up->port.irq))
		up->port.mctrl |= TIOCM_OUT2;
	//to enable intenal loop, uncomment the line below
	//up->port.mctrl |= TIOCM_LOOP;

	serialadv_set_mctrl(&up->port, up->port.mctrl);
	spin_unlock_irqrestore(&up->port.lock, flags);

	/*
	 * Finally, enable interrupts.  Note: Modem status interrupts
	 * are set via set_termios(), which will be occurring imminently
	 * anyway, so we don't enable them here.
	 */
	up->ier = UART_IER_RLSI | UART_IER_RDI;
	serial_out(up, UART_IER, up->ier);

	/*
	 * And clear the interrupt registers again for luck.
	 */
	(void) serial_in(up, UART_LSR);
	(void) serial_in(up, UART_RX);
	(void) serial_in(up, UART_IIR);
	(void) serial_in(up, UART_MSR);

	return 0;
}

static void serialadv_shutdown(struct uart_port *port)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned long flags;

	/*
	 * Disable interrupts from this port
	 */
	up->ier = 0;
	serial_out(up, UART_IER, 0);

	spin_lock_irqsave(&up->port.lock, flags);
	
	up->port.mctrl &= ~TIOCM_OUT2;

	serialadv_set_mctrl(&up->port, up->port.mctrl);
	spin_unlock_irqrestore(&up->port.lock, flags);

	/*
	 * Disable break condition and FIFOs
	 */
	serial_out(up, UART_LCR, serial_in(up, UART_LCR) & ~UART_LCR_SBC);
	serial_out(up, UART_FCR, UART_FCR_ENABLE_FIFO |
				  UART_FCR_CLEAR_RCVR |
				  UART_FCR_CLEAR_XMIT);
	serial_out(up, UART_FCR, 0);

	/*
	 * Read data port to reset things, and then unlink from
	 * the IRQ chain.
	 */
	(void) serial_in(up, UART_RX);

	if (port->irq)
		serial_unlink_irq_chain(up);
}

static unsigned int serialadv_get_divisor(struct uart_port *port, unsigned int baud, unsigned int *quot, unsigned int *quot_fraction, unsigned int *devide1)
{
	serialadv_calc_divisor(port, baud, quot, quot_fraction, devide1);

	return 0;
}

static void
serialadv_set_special_baudrate(struct uart_port *port, unsigned int special_baudrate)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	signed int baud, quot, quot_fraction;
	unsigned char lcr_bak;
	unsigned int reg_read;
	int port_index;
	unsigned int devide1;
	/* for baud rate settings */
	unsigned char   oldEFR = 0;
	unsigned char   oldMCR = 0;
	unsigned char   valof4xreg = 0, valof8xreg= 0;

	port_index = up->port.line;
	quot_fraction = 0;
	printk(KERN_INFO "Enter in serialadv_set non-standard baudrate:%d\n",special_baudrate);

	baud = special_baudrate/*uart_get_baud_rate(port, termios, old, 0, port->uartclk/4)*/;
    lcr_bak = serial_in(up, UART_LCR);
	    	
	if((port_index > 15)||(port_index < 0))
	{
	   return;
	}
	if(port_index >= 8) port_index = port_index - 8;

	serialadv_get_divisor(port, baud, &quot, &quot_fraction, &devide1);

	// set baud rate
	// set sample 16
	valof8xreg = serial_in(up, XR_17V35X_8XMODE);
	valof4xreg = serial_in(up, XR_17V35X_4XMODE);
	valof4xreg &= ~(1 << up->index);
	valof8xreg &= ~(1 << up->index);
	serial_out(up, XR_17V35X_8XMODE, valof8xreg);
	serial_out(up, XR_17V35X_4XMODE, valof4xreg);

	oldEFR = serial_in(up, XR_17V35X_EXTENDED_EFR);
	serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR|0x10);
	if(devide1)		//Prescaler Divide by 1
	{
		oldMCR = serial_in(up, UART_MCR);
		oldMCR &= ~UART_MCR_CLKSEL; // using Prescaler Divide by 1
		up->port.mctrl &= ~UART_MCR_CLKSEL;
		serial_out (up, UART_MCR, oldMCR);
	}
	else			//Prescaler Divide by 4
	{
		oldMCR = serial_in(up, UART_MCR);
		oldMCR |= UART_MCR_CLKSEL;  // using Prescaler Divide by 4
		up->port.mctrl |= UART_MCR_CLKSEL;
		serial_out (up, UART_MCR, oldMCR);
	}
	serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR);

    serial_out(up, UART_LCR, lcr_bak | UART_LCR_DLAB);/* set DLAB */
    serial_out(up, UART_DLL, quot & 0xff);		/* LS of divisor */
    serial_out(up, UART_DLM, quot >> 8);		/* MS of divisor */

	/* if RS485,we set DLD[7] */
	quot_fraction = up->serialMode == SERIAL_MODE_RS485ORRS422S ? ((quot_fraction&0x0f)|0x80) : (quot_fraction&0x0f);

	//Fractional baud rate support
	{
	    reg_read=(serial_in(up, XR_17V35X_UART_DLD)&0xF0);
	    DEBUG_INTR(KERN_INFO "serialadv_set_special_baudrate: quot =0x%x quot_fraction=0x%x DLD_reg=0x%x\n",quot,quot_fraction,reg_read);		
	    serial_out(up, XR_17V35X_UART_DLD, quot_fraction | reg_read);
	    reg_read=serial_in(up, XR_17V35X_UART_DLD);
	 }
	 serial_out(up, UART_LCR, lcr_bak);		/* reset DLAB */

}

static unsigned int serialadv_calc_divisor(struct uart_port *port, unsigned int baud, unsigned int *quot, unsigned int *quot_fraction, unsigned int *devide1)
{
	// calculate the most appropriate baud,
	// Prescaler divide by 1 or 4
	unsigned long     AppropriateInt_Decuple0 = 0, AppropriateInt_Decuple1 = 0;
	unsigned long     baudWithPrescaler0 = 0, baudWithPrescaler1 = 0;
	unsigned long     deviation = 0;
	unsigned long     deviationPersent0 = 0, deviationPersent1 = 0;
	unsigned long     tempclock = 125000000;
	unsigned long     samplingrate = 16;
	unsigned short    tmpBaudInt0 = 0, tmpBaudInt1 = 0;
	unsigned short    tmpBaudFraction0 = 0, tmpBaudFraction1 = 0;

	//calculate in prescaler Divide by 1
	AppropriateInt_Decuple0 = (unsigned long) (tempclock * 10 /(samplingrate * baud) );
	DEBUG_INTR(KERN_INFO"AppropriateInt_Decuple0 = %ld, tempclock = %ld, baud = %d, samplingrate = %ld\n",
			AppropriateInt_Decuple0, tempclock, baud, samplingrate);
	tmpBaudInt0 = (unsigned short)TRUNC(AppropriateInt_Decuple0);
	tmpBaudFraction0 = (unsigned short)ROUND ((AppropriateInt_Decuple0 -TRUNC(AppropriateInt_Decuple0) *10)*16);
	baudWithPrescaler0 = (tempclock * 10) /((tmpBaudInt0 * 10 + (tmpBaudFraction0 * 10/16))*samplingrate) ;
	deviation = baudWithPrescaler0 > baud ? (baudWithPrescaler0 - baud) : (baud -baudWithPrescaler0 ) ;
	deviationPersent0 = deviation * 100 / baud;
	DEBUG_INTR(KERN_INFO"deviationPersent0 = %ld, tmpBaudInt0 = 0x%x, tmpBaudFraction0 = 0x%x\n",
			deviationPersent0, tmpBaudInt0, tmpBaudFraction0);

	//calculate in prescaler Divide by 4
	tempclock = tempclock / 4;
	AppropriateInt_Decuple1 = (unsigned long) (tempclock * 10 /(samplingrate * baud) );
	tmpBaudInt1 = (unsigned short)TRUNC(AppropriateInt_Decuple1);
	tmpBaudFraction1 = (unsigned short) ROUND ((AppropriateInt_Decuple1 -TRUNC(AppropriateInt_Decuple1)*10 )*16);
	baudWithPrescaler1 = (tempclock * 10) / ((tmpBaudInt1 * 10 + (tmpBaudFraction1 * 10/16))*samplingrate);
	deviation = baudWithPrescaler1 > baud ? (baudWithPrescaler1 - baud) : (baud -baudWithPrescaler1 ) ;
	deviationPersent1 = deviation * 100 / baud;
	DEBUG_INTR(KERN_INFO"deviationPersent1 = %ld, tmpBaudInt1 = 0x%x, tmpBaudFraction1 = 0x%x\n",
			deviationPersent1, tmpBaudInt1, tmpBaudFraction1);

	/*
	 *  clk is 125000000, samplingrate is 16, quot is 16bits data,
	 *  calculate rule: quot = clk / (16*baud)
	 *  if baud<120, quot will be overrun, so we need devide clk by 4.
	 *  Though we set tmpBaudInt0, tmpBaudInt1 as unsinged short to prevent overrun, it's better to check it as 120.
	 */
	if(baud < 120)
	{
		*quot = tmpBaudInt1;
		*quot_fraction = tmpBaudFraction1;
		*devide1 = 0;
	}
	else
	{
		//find which one is  less deviation
		if ( deviationPersent0 > deviationPersent1)
		{
			*quot = tmpBaudInt1;
			*quot_fraction = tmpBaudFraction1;
			*devide1 = 0;
		}
		else
		{
			*quot = tmpBaudInt0;
			*quot_fraction = tmpBaudFraction0;
			*devide1 = 1;
		}
	}

	return 0;
}

static void serial_set_ctsrts(struct uart_port *port, int turn_on)
{
	unsigned char old_efr, old_mcr;
	struct uart_adv_port *up = (struct uart_adv_port *)port;

	old_efr = serial_in(up, XR_17V35X_EXTENDED_EFR);

	if(turn_on)
	{
		old_efr |= 0xc0;
		serial_out(up, XR_17V35X_EXTENDED_EFR, old_efr);
		
		old_mcr = serial_in(up, UART_MCR);
		old_mcr |= 0x02;
		serial_out(up, UART_MCR, (unsigned char) old_mcr);
	}
	else
	{
		old_efr &= 0x3f;
		serial_out(up, XR_17V35X_EXTENDED_EFR, old_efr);

		/* Force RTS# output to a HIGH (default) */
		old_mcr = serial_in(up, UART_MCR);
		old_mcr &= 0xfd;
		serial_out(up, UART_MCR, (unsigned char) old_mcr);
	}
}

static void serial_set_dtrdsr(struct uart_port *port, int turn_on)
{
	unsigned char old_efr, old_mcr;
	struct uart_adv_port *up = (struct uart_adv_port *)port;

	old_efr = serial_in(up, XR_17V35X_EXTENDED_EFR);
	
	if(turn_on)
	{
		old_efr |= 0xc0;
		serial_out(up, XR_17V35X_EXTENDED_EFR, old_efr);

		old_mcr = serial_in(up, UART_MCR);
		old_mcr |= 0x05;
		serial_out(up, UART_MCR, (unsigned char) old_mcr);
	}
	else
	{
		old_efr &= 0x3f;
		serial_out(up, XR_17V35X_EXTENDED_EFR, old_efr);

		/* Force DTR# output to a HIGH (default) */
		old_mcr = serial_in(up, UART_MCR);
		old_mcr &= 0xfe;
		serial_out(up, UART_MCR, (unsigned char) old_mcr);
	}
}

static void
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 23)
serialadv_set_termios(struct uart_port *port, struct termios *termios,
		       struct termios *old)
#else
serialadv_set_termios(struct uart_port *port, struct ktermios *termios,
		       struct ktermios *old)
#endif
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned char cval;
	unsigned long flags;
	unsigned int baud, quot, quot_fraction;
	unsigned int devide1 = 0;
	unsigned int reg_read;
	/* for baud rate settings */
	unsigned char   oldEFR = 0;
	unsigned char   oldMCR = 0;
	unsigned char   valof4xreg = 0, valof8xreg= 0;

	int port_index;
	port_index = up->port.line;
	quot_fraction = 0;

	switch (termios->c_cflag & CSIZE) 
	{
	case CS5:
		cval = 0x00;
		break;
	case CS6:
		cval = 0x01;
		break;
	case CS7:
		cval = 0x02;
		break;
	default:
	case CS8:
		cval = 0x03;
		break;
	}

	if (termios->c_cflag & CSTOPB)
		cval |= 0x04;
	if (termios->c_cflag & PARENB)
		cval |= UART_LCR_PARITY;
	if (!(termios->c_cflag & PARODD))
		cval |= UART_LCR_EPAR;
#ifdef CMSPAR
	if (termios->c_cflag & CMSPAR)
		cval |= UART_LCR_SPAR;
#endif

	/*
	 * Ask the core to calculate the divisor for us.
	 * Add limited max baud rate as 921600. 
	 */
	baud = uart_get_baud_rate(port, termios, old, 0, 921600); 

	if((port_index > 15)||(port_index < 0))
	{
		return;
	}
	if(port_index >= 8) port_index = port_index - 8;

	serialadv_get_divisor(port, baud, &quot, &quot_fraction, &devide1);
	DEBUG_INTR(KERN_INFO"serialadv_get_divisor::baud =%d, quot=0x%x, quot_fraction=0x%x, devide1=%d\n", baud, quot, quot_fraction, devide1);

	/*
	 * Ok, we're now changing the port state.  Do it with
	 * interrupts disabled.
	 */
	spin_lock_irqsave(&up->port.lock, flags);

	/*
	 * Update the per-port timeout.
	 */
	uart_update_timeout(port, termios->c_cflag, baud);

	up->port.read_status_mask = UART_LSR_OE | UART_LSR_THRE | UART_LSR_PE | UART_LSR_DR;
	if (termios->c_iflag & INPCK)
		up->port.read_status_mask |= UART_LSR_FE | UART_LSR_PE;
	if (termios->c_iflag & (BRKINT | PARMRK))
		up->port.read_status_mask |= UART_LSR_BI;

	/*
	 * Characteres to ignore
	 */
	up->port.ignore_status_mask = 0;
	if (termios->c_iflag & IGNPAR)
		up->port.ignore_status_mask |= UART_LSR_PE | UART_LSR_FE;
	if (termios->c_iflag & IGNBRK) {
		up->port.ignore_status_mask |= UART_LSR_BI;
		/*
		 * If we're ignoring parity and break indicators,
		 * ignore overruns too (for real raw support).
		 */
		if (termios->c_iflag & IGNPAR)
			up->port.ignore_status_mask |= UART_LSR_OE;
	}

	/*
	 * ignore all characters if CREAD is not set
	 */
	if ((termios->c_cflag & CREAD) == 0)
		up->port.ignore_status_mask |= UART_LSR_DR;

	/*
	 * CTS flow control flag and modem status interrupts
	 */
	up->ier &= ~UART_IER_MSI;
	if (UART_ENABLE_MS(&up->port, termios->c_cflag))
		up->ier |= UART_IER_MSI;

	serial_out(up, UART_IER, up->ier);

	serial_set_ctsrts(port, 0);
	serial_set_dtrdsr(port, 0);
	if(termios->c_cflag & CRTSCTS)
	{
		serial_set_ctsrts(port, 1);
	}
	else if(termios->c_cflag & CDTRDSR)
	{
		serial_set_dtrdsr(port, 1);
	}

	/*
	*	Auto XON/XOFF software flow control flags
	*/
	reg_read=serial_in(up, XR_17V35X_EXTENDED_EFR);
	if(((termios->c_iflag) & IXOFF)&&((termios->c_iflag) & IXON))
	{
		serial_out(up, XR_17V35X_UART_XON1,0x11); //Initializing XON1
		serial_out(up, XR_17V35X_UART_XOFF1,0x13); //Initializing XOFF1
		serial_out(up, XR_17V35X_EXTENDED_EFR, (reg_read & 0xF0) | 0x0A );
		printk(KERN_INFO "Software Flow Control Enabled\n");
	}
	else 
	{
		serial_out(up, XR_17V35X_EXTENDED_EFR, (reg_read) & 0xF0 );
		printk(KERN_INFO "No Software Flow Control\n");
	}	

	reg_read=serial_in(up, XR_17V35X_EXTENDED_EFR);
	if((termios->c_iflag) & IXANY)
	{
		serial_out(up, XR_17V35X_EXTENDED_EFR, ((termios->c_iflag) & IXOFF)&&((termios->c_iflag) & IXON)?((reg_read) | 0x2A):((reg_read) | 0x20));
		reg_read=serial_in(up, UART_MCR);
		serial_out(up, UART_MCR, ((reg_read) & 0xDF) | 0x20 );
		reg_read=serial_in(up,XR_17V35X_EXTENDED_EFR);
		serial_out(up, XR_17V35X_EXTENDED_EFR, (reg_read) & 0xEF );
		printk(KERN_INFO "AUTO XANY Enabled\n");
	}
	else 
	{
		serial_out(up, XR_17V35X_EXTENDED_EFR, (reg_read) | 0x10 );
		reg_read=serial_in(up, UART_MCR);
		serial_out(up, UART_MCR, (reg_read) & 0xDF );
		reg_read=serial_in(up,XR_17V35X_EXTENDED_EFR);
		serial_out(up, XR_17V35X_EXTENDED_EFR, (reg_read) & 0xEF );
		printk(KERN_INFO "AUTO XANY NOT Enabled\n");
	}
	
//---------------------------------------------------------------------------//

	if(!((baud == 38400) && ((port->flags & UPF_SPD_MASK) == UPF_SPD_CUST)))
	{
		// set baud rate
		// set sample 16
		valof8xreg = serial_in(up, XR_17V35X_8XMODE);
		valof4xreg = serial_in(up, XR_17V35X_4XMODE);
		valof4xreg &= ~(1 << up->index);
		valof8xreg &= ~(1 << up->index);
		serial_out(up, XR_17V35X_8XMODE, valof8xreg);
		serial_out(up, XR_17V35X_4XMODE, valof4xreg);

		oldEFR = serial_in(up, XR_17V35X_EXTENDED_EFR);
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR|0x10);
		if(devide1)  	//Prescaler Divide by 1
		{
			oldMCR = serial_in(up, UART_MCR);
			oldMCR &= ~UART_MCR_CLKSEL; // using Prescaler Divide by 1
			up->port.mctrl &= ~UART_MCR_CLKSEL;
			serial_out (up, UART_MCR, oldMCR);
		}
		else		//Prescaler Divide by 4
		{
			oldMCR = serial_in(up, UART_MCR);
			oldMCR |= UART_MCR_CLKSEL;  // using Prescaler Divide by 4
			up->port.mctrl |= UART_MCR_CLKSEL;
			serial_out (up, UART_MCR, oldMCR);
		}
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR);


		serial_out(up, UART_LCR, cval | UART_LCR_DLAB);/* set DLAB */

		serial_out(up, UART_DLL, (unsigned char)(quot & 0xff));		/* LS of divisor */
		serial_out(up, UART_DLM, (unsigned char)(quot >> 8));		/* MS of divisor */

		/* if RS485,we set DLD[7] */
		quot_fraction = up->serialMode == SERIAL_MODE_RS485ORRS422S ? ((quot_fraction&0x0f)|0x80) : (quot_fraction&0x0f);

		//Fractional baud rate support
		reg_read=(serial_in(up, XR_17V35X_UART_DLD)&0xF0);
		DEBUG_INTR(KERN_INFO "serialxr_set_termios: quot =0x%x quot_fraction=0x%x DLD_reg=0x%x\n",quot,quot_fraction,reg_read);		
		serial_out(up, XR_17V35X_UART_DLD, quot_fraction | reg_read);

		serial_out(up, UART_LCR, cval);				/* reset DLAB */
		up->lcr = cval;						/* Save LCR */
	}
	
	// set RS485
	up->serialMode == SERIAL_MODE_RS485ORRS422S ? serialadv_setRS485(&up->port, 1, 0) : serialadv_setRS485(&up->port, 0, 0);

	serial_out(up, UART_FCR, UART_FCR_ENABLE_FIFO);/* set fcr */
	/*
		Configuring MPIO as inputs
	*/
	if((up->deviceid == 0x354)||(up->deviceid == 0x4354)||(up->deviceid == 0x8354))
	{
		serial_out(up, XR_17V35x_MPIOSEL_7_0,0x0FF); //0x0ff= ALL INPUTS	
	}
	else if((up->deviceid == 0x358)||(up->deviceid == 0x4358)||(up->deviceid == 0x8358))
	{
		serial_out(up, XR_17V35x_MPIOSEL_7_0,0x0FF); //0x0ff= ALL INPUTS
		serial_out(up, XR_17V35x_MPIOSEL_15_8,0x0FF); //0x0ff= ALL INPUTS
	}
	
	serialadv_set_mctrl(&up->port, up->port.mctrl);
#if ENABLE_INTERNAL_LOOPBACK
	reg_read=serial_in(up, UART_MCR);
	serial_out(up, UART_MCR, (reg_read) | 0x10);
	printk(KERN_INFO "Enabling Internal Loopback\n");
#endif
	spin_unlock_irqrestore(&up->port.lock, flags);
}

/*
 *      EXAR ioctls
 */
//#define 	FIOQSIZE		0x5460 
#define		EXAR_READ_REG      	(FIOQSIZE + 1)
#define 	EXAR_WRITE_REG     	(FIOQSIZE + 2)

#define 	EXAR_SET_MULTIDROP_MODE_NORMAL   (FIOQSIZE + 3)
#define 	EXAR_SET_MULTIDROP_MODE_AUTO     (FIOQSIZE + 4)
#define 	EXAR_SET_REMOVE_MULTIDROP_MODE   (FIOQSIZE + 5)



struct advioctl_rw_reg {
	unsigned char reg;
	unsigned char regvalue;
};
/*
 * This function is used to handle Advantech Device specific ioctl calls
 * The user level application should have defined the above ioctl
 * commands with the above values to access these ioctls and the 
 * input parameters for these ioctls should be struct advioctl_rw_reg
 * The Ioctl functioning is pretty much self explanatory here in the code,
 * and the register values should be between 0 to XR_17V35X_EXTENDED_RXTRG
 */

static int
serialadv_ioctl(struct uart_port *port, unsigned int cmd, unsigned long arg)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	int ret = -ENOIOCTLCMD;
	struct advioctl_rw_reg ioctlrwarg;
	int iArg = 0;
	switch (cmd)
	{
		case ADV_READ_REG:
			if (copy_from_user(&ioctlrwarg, (void *)arg, sizeof(ioctlrwarg)))
				return -EFAULT;
			ioctlrwarg.regvalue = serial_in(up, ioctlrwarg.reg);
			if (copy_to_user((void *)arg, &ioctlrwarg, sizeof(ioctlrwarg)))
				return -EFAULT;
			DEBUG_INTR(KERN_INFO "serialadv_ioctl read reg[0x%02x]=0x%02x \n",ioctlrwarg.reg,ioctlrwarg.regvalue);
			ret = 0;
			break;
		
		case ADV_WRITE_REG:
			if (copy_from_user(&ioctlrwarg, (void *)arg, sizeof(ioctlrwarg)))
				return -EFAULT;
			serial_out(up, ioctlrwarg.reg, ioctlrwarg.regvalue);
			DEBUG_INTR(KERN_INFO "serialadv_ioctl write reg[0x%02x]=0x%02x \n",ioctlrwarg.reg,ioctlrwarg.regvalue);
			ret = 0;
			break;

		// serial have RS232/RS422/RS485 mode, get it
		case ADV_GET_SERIAL_MODE:
			DEBUG_INTR(KERN_INFO"enter ADV_GET_SERIAL_MODE\n");		
			if ( copy_to_user((void *)arg, &up->serialMode, sizeof(int)) )
				return -EFAULT;
			ret = 0;
			break;

		case ADV_SET_TURN_AROUND_DELAY:
			DEBUG_INTR(KERN_INFO"enter ADV_SET_TURN_AROUND_DELAY\n");
			iArg = (int) arg;

			DEBUG_INTR(KERN_INFO"iArg = %d\n", iArg);
			if( (up->serialMode!=SERIAL_MODE_RS485ORRS422S) || iArg<0 || iArg>15)
				return -EFAULT;

			serialadv_setRS485(&up->port, 1, iArg);
			ret = 0;
			break;
	}
	
	return ret;
}
	      
static void
serialadv_pm(struct uart_port *port, unsigned int state,
	      unsigned int oldstate)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned char oldEFR = 0;
	oldEFR = serial_in(up, XR_17V35X_EXTENDED_EFR);
	if (state) {
		/* sleep */
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR | 0x10);
		serial_out(up, UART_IER, UART_IERX_SLEEP);
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR &(~0x10));
	} else {
		/* wake */
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR | 0x10);
		serial_out(up, UART_IER, 0);
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR &(~0x10));
	}

	if (up->pm)
		up->pm(port, state, oldstate);
}

static void serialadv_release_port(struct uart_port *port)
{	
}

static int serialadv_request_port(struct uart_port *port)
{
	return 0;
}

static void serialadv_config_port(struct uart_port *port, int flags)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;	

	if (flags & UART_CONFIG_TYPE)
	{	
		up->port.type = XRPCIe_TYPE;
		if((uart_config[up->port.type].dfl_xmit_fifo_size >> sizeof(up->port.fifosize)) != 0 )
			up->port.fifosize =  0xff;
		else
			up->port.fifosize = uart_config[up->port.type].dfl_xmit_fifo_size;
		up->capabilities = uart_config[up->port.type].flags;	
	}
}

static const char *
serialadv_type(struct uart_port *port)
{
	int type = port->type;
	
	if (type >= ARRAY_SIZE(uart_config))
		type = 0;
	return uart_config[type].name;
}

static int serialadv_setRS485(struct uart_port *port, int turnOn, int turnaroundTime)
{
	struct uart_adv_port *up = (struct uart_adv_port *)port;
	unsigned char oldFCTR 	= 0;
	unsigned char oldDLD 	= 0;
	unsigned char oldLCR	= 0;
	unsigned char oldEFR	= 0;
	unsigned char valueMSR 	= 0;
	DEBUG_INTR("enter serialadv_setRS485\n");
	oldFCTR = serial_in(up, XR_17V35X_EXTENDED_FCTR);
	if(turnOn)	// set RS485
	{
		// Auto RS485 Enable 
		oldFCTR |= 0x20;
		serial_out(up, XR_17V35X_EXTENDED_FCTR, oldFCTR);
		
		// set RS-485 Polarity to 1
		oldLCR = serial_in(up, UART_LCR);
		serial_out(up, UART_LCR, oldLCR|UART_LCR_DLAB);
		oldDLD = serial_in(up, XR_17V35X_UART_DLD);
		serial_out(up, XR_17V35X_UART_DLD, oldDLD|0x80);
		serial_out(up, UART_LCR, oldLCR);	

		/* 
		 * set RS-485 turn-around delay
		 */
		oldEFR = serial_in(up, XR_17V35X_EXTENDED_EFR);
		oldEFR |= 0x10;
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR);	
		
		// MSR write only
		valueMSR = turnaroundTime<<4;
		serial_out(up, UART_MSR, valueMSR);	

		oldEFR &= ~(0x10);
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR);	
	}
	else		// unset RS485
	{
		// Auto RS485 Disable
		oldFCTR &= 0xdf;
		serial_out(up, XR_17V35X_EXTENDED_FCTR, oldFCTR);

		// restore msr	
		oldEFR = serial_in(up, XR_17V35X_EXTENDED_EFR);
		oldEFR |= 0x10;
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR);	
		
		// MSR write only
		valueMSR = 0;
		serial_out(up, UART_MSR, valueMSR);

		oldEFR &= ~(0x10);
		serial_out(up, XR_17V35X_EXTENDED_EFR, oldEFR);	
	}
	DEBUG_INTR("leave serialadv_setRS485\n");
	return 0;
}

void serialadv_spi_delay(void)
{
	int idex = 10;

	while(idex-- > 0)
	{
		;
	}

	return;
}

void serialadv_spi_write_slave(struct uart_adv_port *up, unsigned char data)
{
	int				idex		= 0;
	int				send_bit	= 0;
	unsigned char	reg_value	= 0;

	for(idex = 7; idex >= 0; idex--)
	{
		send_bit = data & (1<<idex) ? 1 : 0;
		serial_out(up, REGB, 0);					/* CK low */
		serialadv_spi_delay();
		reg_value = send_bit ? EEDI_BIT : 0;
		serial_out(up, REGB, reg_value);			/* write EEDI bit */
		serialadv_spi_delay();
		serial_out(up, REGB, reg_value | EECK_BIT);	/* CK high */
		serialadv_spi_delay();
		serial_out(up, REGB, 0);					/* CK low */
		serialadv_spi_delay();
	}

	return;
}

int serialadv_spi_read_slave(struct uart_adv_port *up, unsigned char *p_data)
{
	int				idex		= 0;
	int				recv_bit	= 0;
	unsigned char	reg_value	= 0;

	if(!p_data)
	{
		DEBUG_INTR("p_data == NULL\n");
		return -1;
	}

	*p_data = 0;
	for(idex = 7; idex >= 0; idex--)
	{
		serial_out(up, REGB, 0);			/* CK low */
		serialadv_spi_delay();
		serial_out(up, REGB, EECK_BIT);		/* CK high */
		serialadv_spi_delay();
		serial_out(up, REGB, 0);			/* CK high */
		serialadv_spi_delay();

		reg_value = serial_in(up, REGB);	/* read EEDO bit */
		recv_bit = reg_value & EEDO_BIT ? 1 : 0;
		*p_data |= recv_bit << idex;
	}

	return 0;
}

void serialadv_spi_start(struct uart_adv_port *up)
{
	/*
	 * SPI start, set CS low
	 */
	serial_out(up, XR_17V35X_MPIOSEL_H, 0x7F);
	serial_out(up, XR_17V35X_MPIOLVL_H, 0x0);
	serialadv_spi_delay();

	return;
}

void serialadv_spi_stop(struct uart_adv_port *up)
{
	/*
	 * SPI start, set CS low
	 */
	serial_out(up, XR_17V35X_MPIOSEL_H, 0x7F);
	serial_out(up, XR_17V35X_MPIOLVL_H, 0x80);
	serialadv_spi_delay();

	return;
}

/*
 * Routine Description:
 *    This routine will get card's board ID by SPI bus.
 * Arguments:
 *    up          - Pointer to the device structure
 *    p_boardID   - save board ID
 *Return value:
 *    0 on success, something else appropriate on failure
 */
int serialadv_get_boardID(struct uart_adv_port *up, short unsigned int *p_boardID)
{
	unsigned char boardID = 0;

	serialadv_spi_start(up);
	serialadv_spi_write_slave(up, SPI_READ_CMD);
	serialadv_spi_write_slave(up, GPIOA);
	serialadv_spi_read_slave(up, &boardID);
	serialadv_spi_stop(up);
	*p_boardID = boardID;

	return 0;
}

static int serialadv_verify_port(struct uart_port *port, struct serial_struct *ser)
{
	int ret = 0;
	printk(KERN_INFO "serialadv_set_special_baudrate flags:%d custom_divisor=%d\n",ser->flags,ser->custom_divisor);
	if(ser->custom_divisor > 0)
		serialadv_set_special_baudrate(port,ser->baud_base/ser->custom_divisor);
	return ret;
}

static struct uart_ops serialadv_pops = {
	.tx_empty	    = serialadv_tx_empty,
	.set_mctrl	    = serialadv_set_mctrl,
	.get_mctrl	    = serialadv_get_mctrl,
	.stop_tx	    = serialadv_stop_tx,
	.start_tx	    = serialadv_start_tx,
	.stop_rx	    = serialadv_stop_rx,
	.enable_ms	    = serialadv_enable_ms,
	.break_ctl	    = serialadv_break_ctl,
	.startup	    = serialadv_startup,
	.shutdown	    = serialadv_shutdown,
	.set_termios	= serialadv_set_termios,
	.verify_port	= serialadv_verify_port, 
	.pm		        = serialadv_pm,
	.type		    = serialadv_type,
	.release_port	= serialadv_release_port,
	.request_port	= serialadv_request_port,
	.config_port	= serialadv_config_port,
	.ioctl		    = serialadv_ioctl,
};

static DEFINE_MUTEX(serial_mutex);

static struct uart_adv_port serialadv_ports[NR_PORTS];

#define SERIALADV_CONSOLE	NULL

static struct uart_driver adv_uart_driver[MAX_CARD_SUPPORT];
static char adv_dev_name[MAX_CARD_SUPPORT][MAX_STRING_LEN];
static char adv_driver_name[MAX_CARD_SUPPORT][MAX_STRING_LEN];
unsigned int old_method_cnt = 0;

static struct uart_adv_port *serialadv_find_match_or_unused(struct uart_port *port)
{
	int i;

	/*
	 * First, find a port entry which matches.
	 */
	for (i = 0; i < NR_PORTS; i++)
		if (uart_match_port(&serialadv_ports[i].port, port))
			return &serialadv_ports[i];

	/*
	 * We didn't find a matching entry, so look for the first
	 * free entry.  We look for one which hasn't been previously
	 * used (indicated by zero iobase).
	 */
	for (i = 0; i < NR_PORTS; i++)
		if (serialadv_ports[i].port.type == PORT_UNKNOWN &&
		    serialadv_ports[i].port.iobase == 0)
		{
			port->line = i;
			return &serialadv_ports[i];
		}

	/*
	 * That also failed.  Last resort is to find any entry which
	 * doesn't have a real port associated with it.
	 */
	for (i = 0; i < NR_PORTS; i++)
		if (serialadv_ports[i].port.type == PORT_UNKNOWN)
			return &serialadv_ports[i];

	return NULL;
}

void init_adv_uart_struct(void)
{
	int i;

	/*
	 * We do not init "dev_name", "nr" here, these will be
	 * initiated after getting boardID.
	 */
	for(i = 0; i < MAX_CARD_SUPPORT; i++)
	{
		adv_uart_driver[i].owner		= THIS_MODULE;
		adv_uart_driver[i].driver_name	= "ADVserial";
		adv_uart_driver[i].major		= XR_MAJOR;
		adv_uart_driver[i].minor		= XR_MINOR + i;
		adv_uart_driver[i].cons			= SERIALADV_CONSOLE;
	}

	return;
}

/*
 *	serialadv_register_port - register a serial port
 *	@port: serial port template
 *
 *	Configure the serial port specified by the request. If the
 *	port exists and is in use, it is hung up and unregistered
 *	first.
 *
 *	The port is then probed and if necessary the IRQ is autodetected
 *	If this fails an error is returned.
 *
 *	On success the port is ready to use and the line number is returned.
 */
int serialadv_register_port(struct uart_port *port, unsigned short deviceid,
								int index, int nr_ports)
{
	struct uart_adv_port *uart;
	int i, boardID = 0, ret = -ENOSPC;
	char tmp_string[MAX_STRING_LEN], tmp_dev_name[MAX_STRING_LEN];

	if (port->uartclk == 0)
		return -EINVAL;

	mutex_lock(&serial_mutex);
	uart = serialadv_find_match_or_unused(port);
	if (uart) {
		uart->port.iobase   = port->iobase;
		uart->port.membase  = port->membase;
		uart->port.irq      = port->irq;
		uart->port.uartclk  = port->uartclk;
		uart->port.fifosize = port->fifosize;
		uart->port.regshift = port->regshift;
		uart->port.iotype   = port->iotype;
		uart->port.flags    = port->flags | UPF_BOOT_AUTOCONF;
		uart->port.mapbase  = port->mapbase;
		if (port->dev)
			uart->port.dev = port->dev;

		uart->deviceid = deviceid;
		uart->channelnum = index;
		uart->port.line = port->line;
		uart->index = index;
		spin_lock_init(&uart->port.lock);

#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 15, 0)
		init_timer(&uart->timer);
		uart->timer.function = serialadv_timeout;
#else
		timer_setup(&uart->timer, serialadv_timeout, 0);
#endif

		/*
		 * ALPHA_KLUDGE_MCR needs to be killed.
		 */
		uart->mcr_mask = ~(0x0); //~ALPHA_KLUDGE_MCR;
		uart->mcr_force = 0; // ALPHA_KLUDGE_MCR;

		uart->port.ops = &serialadv_pops;		

		/*
		 * Get serial mode
		 */
		serial_get_mode(uart);

		/*
		 * Get board ID
		 */
		for(i = 0; i < 10; i++)
		{
			serialadv_get_boardID(uart, &uart->board_id);
			if(uart->board_id != 0 && uart->board_id == boardID)
				break;
			boardID = uart->board_id;
		}

		uart->current_card_nr = nr_ports;
		if(uart->board_id == 0x0)
		{
			/*
			 * Use old naming methods "ttyAP*"
			 * WARNING: DO NOT try to modify this value "state" anywhere,
			 * this is private value for kernel
			 */
			if(adv_uart_driver[0].state == NULL)
			{
				/*
				 * The first member adv_uart_driver[0] is reserved for "ttyAP*"
				 */
				memset(adv_dev_name[0], 0, sizeof(adv_dev_name[0]));
				strncpy(adv_dev_name[0], "ttyAP", sizeof(adv_dev_name[0]) - 1);
				adv_uart_driver[0].dev_name = adv_dev_name[0];
				adv_uart_driver[0].nr = NR_PORTS;

				uart_register_driver(&adv_uart_driver[0]);
			}

			/*
			 * Add this port to first member
			 */
			uart->port.line = old_method_cnt++;
			uart->fix_number_index = 0;
			ret = uart_add_one_port(&adv_uart_driver[0], &uart->port);
		}
		else
		{
			/*
			 * Enable fixed number.
			 * Fill temp buffer, "ttyB" + boardID + "P" + port_num
			 */
			memset(tmp_dev_name, 0, sizeof(tmp_dev_name));
			strncpy(tmp_dev_name, "ttyB", sizeof(tmp_dev_name) - 1);
			sprintf(tmp_string, "%02d", uart->board_id);
			strncat(tmp_dev_name, tmp_string,
					 sizeof(tmp_dev_name) - strlen(tmp_dev_name));
			strncat(tmp_dev_name, "P",
					 sizeof(tmp_dev_name) - strlen(tmp_dev_name));

			/*
			 * The first member is reserved for "ttyAP*", begin to loop from 1
			 */
			for(i = 1; i < MAX_CARD_SUPPORT; i++)
			{
				/*
				 * Try to find filled member out first
				 */
				if(adv_uart_driver[i].state != NULL
					&& strlen(adv_uart_driver[i].dev_name) > 0
					&& strlen(tmp_dev_name) > 0)
				{
					if(strcmp(adv_uart_driver[i].dev_name, tmp_dev_name) == 0)
					{
						uart->port.line = index;
						uart->fix_number_index = i;
						ret = uart_add_one_port(&adv_uart_driver[i], &uart->port);
						break;
					}
				}

				/*
				 * Try to find& init the first uninitial member at this step
				 */
				if(adv_uart_driver[i].state == NULL)
				{
					/*
					 * Re-write index for port number
					 */
					adv_uart_driver[i].nr = nr_ports;

					/*
					 * Set device_name, "ttyB" + boardID + "P" + port_num
					 */
					memset(adv_dev_name[i], 0, sizeof(adv_dev_name[i]));
					strncpy(adv_dev_name[i], tmp_dev_name, sizeof(tmp_dev_name));
					adv_uart_driver[i].dev_name = adv_dev_name[i];

					memset(adv_driver_name[i], 0, sizeof(adv_driver_name[i]));
					sprintf(adv_driver_name[i], "ADVserialBID");
					strncat(adv_driver_name[i], tmp_string,
							 sizeof(adv_driver_name[i]) - strlen(adv_driver_name[i]));
					adv_uart_driver[i].driver_name = adv_driver_name[i];

					uart_register_driver(&adv_uart_driver[i]);

					uart->port.line = index;
					uart->fix_number_index = i;
					ret = uart_add_one_port(&adv_uart_driver[i], &uart->port);
					break;
				}
			}
		}
#if 0
		if (ret == 0)
		{
			ret = uart->port.line;

			if (is_real_interrupt(uart->port.irq)) {
				serial_link_irq_chain(uart);
			}
		}
#endif
	}
	mutex_unlock(&serial_mutex);

	return ret;
}

/*
 * Probe one serial board.  Unfortunately, there is no rhyme nor reason
 * to the arrangement of serial ports on a PCI card.
 */
static int __devinit
init_one_advpciserialcard(struct pci_dev *dev, const struct pci_device_id *ent)
{
	struct serial_private *priv;
	struct pciserial_board *board;
	struct pci_serial_quirk *quirk;
	struct uart_port serial_port;
	int rc, nr_ports, i;
			
	if (ent->driver_data >= ARRAY_SIZE(advpciserial_boards)) {
		printk(KERN_INFO "pci_init_one: invalid driver_data: %ld\n",
			ent->driver_data);
		return -EINVAL;
	}

	board = &advpciserial_boards[ent->driver_data];

	rc = pci_enable_device(dev);
	if (rc)
		return rc;
	
	nr_ports = board->num_ports;

	/*
	 * Find an init and setup quirks.
	 */
	quirk = find_quirk(dev);

	/*
	 * Run the new-style initialization function.
	 * The initialization function returns:
	 *  <0  - error
	 *   0  - use board->num_ports
	 *  >0  - number of ports
	 */
	if (quirk->init) {
		rc = quirk->init(dev);
		if (rc < 0)
			goto disable;
		if (rc)
			nr_ports = rc;
	}

	priv = kmalloc(sizeof(struct serial_private) +
		       sizeof(unsigned int) * nr_ports,
		       GFP_KERNEL);
	if (!priv) {
		rc = -ENOMEM;
		goto deinit;
	}

	memset(priv, 0, sizeof(struct serial_private) +
			sizeof(unsigned int) * nr_ports);

	priv->dev = dev;
	priv->quirk = quirk;

	memset(&serial_port, 0, sizeof(struct uart_port));
	serial_port.flags = UPF_SKIP_TEST | UPF_BOOT_AUTOCONF | UPF_SHARE_IRQ;

	serial_port.uartclk = board->base_baud*16;
	serial_port.irq = dev->irq;
	serial_port.dev = &dev->dev;
	for (i = 0; i < nr_ports; i++) {
		if (quirk->setup(priv, board, &serial_port, i))
			break;

		rc = serialadv_register_port(&serial_port, dev->device, i, nr_ports);
		if (rc < 0) {
			printk(KERN_WARNING "Couldn't register serial port %s: %d\n", pci_name(dev), i);
			break;
		}
				
		printk(KERN_WARNING "init_one_advpciserialcard line:%d\n",serial_port.line);
		priv->uart_index[i] = serial_port.line;
		priv->line[i] = rc;
	}

	priv->nr = i;

	if (!IS_ERR(priv)) {
		pci_set_drvdata(dev, priv);
		return 0;
	}

 deinit:
	if (quirk->exit)
		quirk->exit(dev);
 disable:
	pci_disable_device(dev);
	return rc;
}

/*
 *	serialadv_unregister_port - remove a serial port at runtime
 *	@line: serial line number
 *
 *	Remove one serial port.  This may not be called from interrupt
 *	context.  We hand the port back to the our control.
 */
void serialadv_unregister_port(int index, int line)
{
	struct uart_adv_port *uart = &serialadv_ports[line];

	mutex_lock(&serial_mutex);
#if 0
	if (is_real_interrupt(uart->port.irq))
	  serial_unlink_irq_chain(uart);
#endif
	if(adv_uart_driver[index].state != NULL)
	{
		uart_remove_one_port(&adv_uart_driver[index], &uart->port);
	}
	uart->port.dev = NULL;	
	mutex_unlock(&serial_mutex);
}

void pciserial_remove_ports(struct serial_private *priv)
{
	int i, current_index;
	struct pci_serial_quirk *quirk;

	/*
	 * Unregister ports one by one
	 */
	current_index =serialadv_ports[priv->uart_index[0]].fix_number_index;

	if((adv_uart_driver[current_index].state != NULL) && (adv_uart_driver[current_index].nr > 0))
	{
		for(i = 0; i < serialadv_ports[priv->uart_index[0]].current_card_nr; i++)
		{
			serialadv_unregister_port(current_index, priv->uart_index[i]);
		}

		if(current_index != 0)
			adv_uart_driver[current_index].nr = 0;
	}

	for (i = 0; i < PCI_NUM_BAR_RESOURCES; i++) {
		if (priv->remapped_bar[i])
			iounmap(priv->remapped_bar[i]);
		priv->remapped_bar[i] = NULL;
	}

	/*
	 * Find the exit quirks.
	 */
	quirk = find_quirk(priv->dev);
	if (quirk->exit)
		quirk->exit(priv->dev);

	kfree(priv);
}

static void __devexit remove_one_advpciserialcard(struct pci_dev *dev)
{
	struct serial_private *priv = pci_get_drvdata(dev);

	pci_set_drvdata(dev, NULL);

	pciserial_remove_ports(priv);

	pci_disable_device(dev);
}


static struct pci_device_id advserial_pci_tbl[] = {
	{	ADVANTECH_VID, PCIE_1602,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_2port },
	{	ADVANTECH_VID, PCIE_1604,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_2port },
	{	ADVANTECH_VID, PCIE_1610,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_4port },
	{	ADVANTECH_VID, PCIE_1612,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_4port },
	{	ADVANTECH_VID, PCIE_1620,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_8port },
	{	ADVANTECH_VID, PCIE_1622,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_8port },
	{	ADVANTECH_VID, PCIE_0014,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_8port },
	{	ADVANTECH_VID, PCIE_0015,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_4port },
	{	ADVANTECH_VID, PCIE_0016,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_2port },	
	{	ADVANTECH_VID, PCM_3612I,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_4port },
	{	ADVANTECH_VID, PCI_1602,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_2port },
	{	ADVANTECH_VID, PCI_1604,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_2port },
	{	ADVANTECH_VID, PCI_1610,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_4port },
	{	ADVANTECH_VID, PCI_1612,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_4port },
	{	ADVANTECH_VID, PCI_1620,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_8port },
	{	ADVANTECH_VID, PCI_1622,
		PCI_ANY_ID, PCI_ANY_ID,
		0, 0, adv_8port },        		
	{ 0, }
};

static struct pci_driver advserial_pci_driver = {
	.name		= "ADVserial",
	.probe		= init_one_advpciserialcard,
	.remove		= __devexit_p(remove_one_advpciserialcard),
	.id_table	= advserial_pci_tbl,
};


static int __init serialadv_init(void)
{
	int i, ret;

	printk("\n");
	printk("==========================================================="
			"====\n");
	printk("Advantech PCIe (17V35x) Serial Device Drivers.\n");
	printk("Product V%s [%s]\nFile V%s\n",
		ADVANTECH_EXAR_VER, ADVANTECH_EXAR_DATE, ADVANTECH_EXAR_FILE_VER);
	printk("Supports: RS232/422/485 auto detection and setting\n");
	printk("Devices:  ICOM: PCIE-1602, PCIE-1604\n"
			"                PCIE-1610, PCIE-1612\n"
			"                PCIE-1620, PCIE-1622\n"
			"                PCM_3612I\n"
			"                PCI-1602, PCI-1604\n"
			"                PCI-1610, PCI-1612\n"
			"                PCI-1620, PCI-1622\n"
			);
	printk("Advantech Industrial Automation Group.\n");
	printk("==========================================================="
			"====\n");

	init_adv_uart_struct();

	ret = pci_register_driver(&advserial_pci_driver);

	if (ret < 0)
	{
		for(i = 0; i < MAX_CARD_SUPPORT; i++)
		{
			if(adv_uart_driver[i].state != NULL)
			{
				uart_unregister_driver(&adv_uart_driver[i]);
			}
		}
	}

	return ret;	
}

static void __exit serialadv_exit(void)
{
	int i;

	pci_unregister_driver(&advserial_pci_driver);
	
	for(i = 0; i < MAX_CARD_SUPPORT; i++)
	{
		if(adv_uart_driver[i].state != NULL)
		{
			uart_unregister_driver(&adv_uart_driver[i]);
		}
	}
}

module_init(serialadv_init);
module_exit(serialadv_exit);

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Advantech PCIe specific serial driver for ADV17V35X");
MODULE_VERSION(ADVANTECH_EXAR_VER);

MODULE_DEVICE_TABLE(pci, advserial_pci_tbl);