Linux Audio

Check our new training course

Embedded Linux Audio

Check our new training course
with Creative Commons CC-BY-SA
lecture materials

Bootlin logo

Elixir Cross Referencer

Loading...
   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
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
/*======================================================================

    Aironet driver for 4500 and 4800 series cards

    This code is released under both the GPL version 2 and BSD licenses.
    Either license may be used.  The respective licenses are found at
    the end of this file.

    This code was developed by Benjamin Reed <breed@users.sourceforge.net>
    including portions of which come from the Aironet PC4500
    Developer's Reference Manual and used with permission.  Copyright
    (C) 1999 Benjamin Reed.  All Rights Reserved.  Permission to use
    code in the Developer's manual was granted for this driver by
    Aironet.  Major code contributions were received from Javier Achirica
    and Jean Tourrilhes <jt@hpl.hp.com>.  Code was also integrated from
    the Cisco Aironet driver for Linux.
    
======================================================================*/

#include <linux/config.h>
#include <linux/version.h>
#include <asm/segment.h>
#include <linux/init.h>

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>

#include <linux/sched.h>
#include <linux/ptrace.h>
#include <linux/malloc.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/bitops.h>

#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/ioport.h>
#include <linux/config.h>
#include <linux/pci.h>

#ifdef CONFIG_PCI
static struct pci_device_id card_ids[] = __devinitdata {
	{ 0x14b9, 1, PCI_ANY_ID, PCI_ANY_ID, },
	{ 0x14b9, 0x4500, PCI_ANY_ID, PCI_ANY_ID },
	{ 0x14b9, 0x4800, PCI_ANY_ID, PCI_ANY_ID, },
	{ 0x14b9, 0x0340, PCI_ANY_ID, PCI_ANY_ID, },
	{ 0x14b9, 0x0350, PCI_ANY_ID, PCI_ANY_ID, },
	{ 0, } 
};
MODULE_DEVICE_TABLE(pci, card_ids);

static int airo_pci_probe(struct pci_dev *, const struct pci_device_id *);
static void airo_pci_remove(struct pci_dev *);

static struct pci_driver airo_driver = {
	name:     "airo",
	id_table: card_ids,
	probe:    airo_pci_probe,
	remove:   airo_pci_remove,
};
#endif /* CONFIG_PCI */

/* Include Wireless Extension definition and check version - Jean II */
#include <linux/wireless.h>
#if WIRELESS_EXT < 9
#warning "Wireless extension v9 or newer required - please upgrade your kernel"
#undef WIRELESS_EXT
#endif
#define WIRELESS_SPY		// enable iwspy support
#define CISCO_EXT		// enable Cisco extensions

#ifdef CISCO_EXT
#include <linux/delay.h>
#endif

/* As you can see this list is HUGH!
   I really don't know what a lot of these counts are about, but they
   are all here for completeness.  If the IGNLABEL macro is put in
   infront of the label, that statistic will not be included in the list
   of statistics in the /proc filesystem */

#define IGNLABEL 0&(int)
static char *statsLabels[] = {
	"RxOverrun",
	IGNLABEL "RxPlcpCrcErr",
	IGNLABEL "RxPlcpFormatErr",
	IGNLABEL "RxPlcpLengthErr",
	"RxMacCrcErr",
	"RxMacCrcOk",
	"RxWepErr",
	"RxWepOk",
	"RetryLong",
	"RetryShort",
	"MaxRetries",
	"NoAck",
	"NoCts",
	"RxAck",
	"RxCts",
	"TxAck",
	"TxRts",
	"TxCts",
	"TxMc",
	"TxBc",
	"TxUcFrags",
	"TxUcPackets",
	"TxBeacon",
	"RxBeacon",
	"TxSinColl",
	"TxMulColl",
	"DefersNo",
	"DefersProt",
	"DefersEngy",
	"DupFram",
	"RxFragDisc",
	"TxAged",
	"RxAged",
	"LostSync-MaxRetry",
	"LostSync-MissedBeacons",
	"LostSync-ArlExceeded",
	"LostSync-Deauth",
	"LostSync-Disassoced",
	"LostSync-TsfTiming",
	"HostTxMc",
	"HostTxBc",
	"HostTxUc",
	"HostTxFail",
	"HostRxMc",
	"HostRxBc",
	"HostRxUc",
	"HostRxDiscard",
	IGNLABEL "HmacTxMc",
	IGNLABEL "HmacTxBc",
	IGNLABEL "HmacTxUc",
	IGNLABEL "HmacTxFail",
	IGNLABEL "HmacRxMc",
	IGNLABEL "HmacRxBc",
	IGNLABEL "HmacRxUc",
	IGNLABEL "HmacRxDiscard",
	IGNLABEL "HmacRxAccepted",
	"SsidMismatch",
	"ApMismatch",
	"RatesMismatch",
	"AuthReject",
	"AuthTimeout",
	"AssocReject",
	"AssocTimeout",
	IGNLABEL "ReasonOutsideTable",
	IGNLABEL "ReasonStatus1",
	IGNLABEL "ReasonStatus2",
	IGNLABEL "ReasonStatus3",
	IGNLABEL "ReasonStatus4",
	IGNLABEL "ReasonStatus5",
	IGNLABEL "ReasonStatus6",
	IGNLABEL "ReasonStatus7",
	IGNLABEL "ReasonStatus8",
	IGNLABEL "ReasonStatus9",
	IGNLABEL "ReasonStatus10",
	IGNLABEL "ReasonStatus11",
	IGNLABEL "ReasonStatus12",
	IGNLABEL "ReasonStatus13",
	IGNLABEL "ReasonStatus14",
	IGNLABEL "ReasonStatus15",
	IGNLABEL "ReasonStatus16",
	IGNLABEL "ReasonStatus17",
	IGNLABEL "ReasonStatus18",
	IGNLABEL "ReasonStatus19",
	"RxMan",
	"TxMan",
	"RxRefresh",
	"TxRefresh",
	"RxPoll",
	"TxPoll",
	"HostRetries",
	"LostSync-HostReq",
	"HostTxBytes",
	"HostRxBytes",
	"ElapsedUsec",
	"ElapsedSec",
	"LostSyncBetterAP",
	"PrivacyMismatch",
	"Jammed",
	"DiscRxNotWepped",
	"PhyEleMismatch",
	(char*)-1 };
#ifndef RUN_AT
#define RUN_AT(x) (jiffies+(x))
#endif


/* These variables are for insmod, since it seems that the rates
   can only be set in setup_card.  Rates should be a comma separated
   (no spaces) list of rates (up to 8). */

static int rates[8];
static int basic_rate;
static char *ssids[3];

static int io[4];
static int irq[4];

static
int maxencrypt /* = 0 */; /* The highest rate that the card can encrypt at.
		       0 means no limit.  For old cards this was 4 */

static int auto_wep /* = 0 */; /* If set, it tries to figure out the wep mode */
static int aux_bap /* = 0 */; /* Checks to see if the aux ports are needed to read
		    the bap, needed on some older cards and buses. */   
static int adhoc;

static int proc_uid /* = 0 */;

static int proc_gid /* = 0 */;

static int airo_perm = 0555;

static int proc_perm = 0644;

MODULE_AUTHOR("Benjamin Reed");
MODULE_DESCRIPTION("Support for Cisco/Aironet 802.11 wireless ethernet \
                   cards.  Direct support for ISA/PCI cards and support \
		   for PCMCIA when used with airo_cs.");
MODULE_SUPPORTED_DEVICE("Aironet 4500, 4800 and Cisco 340");
MODULE_PARM(io,"1-4i");
MODULE_PARM(irq,"1-4i");
MODULE_PARM(basic_rate,"i");
MODULE_PARM(rates,"1-8i");
MODULE_PARM(ssids,"1-3s");
MODULE_PARM(auto_wep,"i");
MODULE_PARM_DESC(auto_wep, "If non-zero, the driver will keep looping through \
the authentication options until an association is made.  The value of \
auto_wep is number of the wep keys to check.  A value of 2 will try using \
the key at index 0 and index 1.");
MODULE_PARM(aux_bap,"i");
MODULE_PARM_DESC(aux_bap, "If non-zero, the driver will switch into a mode \
than seems to work better for older cards with some older buses.  Before \
switching it checks that the switch is needed.");
MODULE_PARM(maxencrypt, "i");
MODULE_PARM_DESC(maxencrypt, "The maximum speed that the card can do \
encryption.  Units are in 512kbs.  Zero (default) means there is no limit. \
Older cards used to be limited to 2mbs (4).");
MODULE_PARM(adhoc, "i");
MODULE_PARM_DESC(adhoc, "If non-zero, the card will start in adhoc mode.");

MODULE_PARM(proc_uid, "i");
MODULE_PARM_DESC(proc_uid, "The uid that the /proc files will belong to.");
MODULE_PARM(proc_gid, "i");
MODULE_PARM_DESC(proc_gid, "The gid that the /proc files will belong to.");
MODULE_PARM(airo_perm, "i");
MODULE_PARM_DESC(airo_perm, "The permission bits of /proc/[driver/]aironet.");
MODULE_PARM(proc_perm, "i");
MODULE_PARM_DESC(proc_perm, "The permission bits of the files in /proc");

#include <asm/uaccess.h>

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

/* This is a kind of sloppy hack to get this information to OUT4500 and
   IN4500.  I would be extremely interested in the situation where this
   doesnt work though!!! */
static int do8bitIO = 0;

/* Return codes */
#define SUCCESS 0
#define ERROR -1
#define NO_PACKET -2

/* Commands */
#define NOP 0x0010
#define MAC_ENABLE 0x0001
#define MAC_DISABLE 0x0002
#define CMD_ACCESS 0x0021
#define CMD_ALLOCATETX 0x000a
#define CMD_TRANSMIT 0x000b
#define HOSTSLEEP 0x85
#define CMD_SETMODE 0x0009
#define CMD_ENABLEAUX 0x0111
#define CMD_SOFTRESET 0x0004

/* Registers */
#define COMMAND 0x00
#define PARAM0 0x02
#define PARAM1 0x04
#define PARAM2 0x06
#define STATUS 0x08
#define RESP0 0x0a
#define RESP1 0x0c
#define RESP2 0x0e
#define LINKSTAT 0x10
#define SELECT0 0x18
#define OFFSET0 0x1c
#define RXFID 0x20
#define TXALLOCFID 0x22
#define TXCOMPLFID 0x24
#define DATA0 0x36
#define EVSTAT 0x30
#define EVINTEN 0x32
#define EVACK 0x34
#define SWS0 0x28
#define SWS1 0x2a
#define SWS2 0x2c
#define SWS3 0x2e
#define AUXPAGE 0x3A
#define AUXOFF 0x3C
#define AUXDATA 0x3E

/* BAP selectors */
#define BAP0 0 // Used for receiving packets
#define BAP1 2 // Used for xmiting packets and working with RIDS

/* Flags */
#define COMMAND_BUSY 0x8000

#define BAP_BUSY 0x8000
#define BAP_ERR 0x4000
#define BAP_DONE 0x2000

#define PROMISC 0xffff
#define NOPROMISC 0x0000

#define EV_CMD 0x10
#define EV_CLEARCOMMANDBUSY 0x4000
#define EV_RX 0x01
#define EV_TX 0x02
#define EV_TXEXC 0x04
#define EV_ALLOC 0x08
#define EV_LINK 0x80
#define EV_AWAKE 0x100
#define EV_UNKNOWN 0x800
#define STATUS_INTS ( EV_AWAKE | EV_LINK | EV_TXEXC | EV_TX | EV_RX | EV_UNKNOWN)

/* The RIDs */
#define RID_CAPABILITIES 0xFF00
#define RID_CONFIG     0xFF10
#define RID_SSID       0xFF11
#define RID_APLIST     0xFF12
#define RID_DRVNAME    0xFF13
#define RID_ETHERENCAP 0xFF14
#define RID_WEP_TEMP   0xFF15
#define RID_WEP_PERM   0xFF16
#define RID_MODULATION 0xFF17
#define RID_ACTUALCONFIG 0xFF20 /*readonly*/
#define RID_LEAPUSERNAME 0xFF23
#define RID_LEAPPASSWORD 0xFF24
#define RID_STATUS     0xFF50
#define RID_STATS      0xFF68
#define RID_STATSDELTA 0xFF69
#define RID_STATSDELTACLEAR 0xFF6A

/*
 * Rids and endian-ness:  The Rids will always be in cpu endian, since
 * this all the patches from the big-endian guys end up doing that.
 * so all rid access should use the read/writeXXXRid routines.
 */

/* This structure came from an email sent to me from an engineer at
   aironet for inclusion into this driver */
typedef struct {
	u16 len;
	u16 kindex;
	u8 mac[6];
	u16 klen;
	u8 key[16];
} WepKeyRid;

/* These structures are from the Aironet's PC4500 Developers Manual */
typedef struct {
	u16 len;
	u8 ssid[32];
} Ssid;

typedef struct {
	u16 len;
	Ssid ssids[3];
} SsidRid;

typedef struct {
        u16 len;
        u16 modulation;
#define MOD_DEFAULT 0
#define MOD_CCK 1
#define MOD_MOK 2
} ModulationRid;

typedef struct {
	u16 cmd;
	u16 parm0;
	u16 parm1;
	u16 parm2;
} Cmd;

typedef struct {
	u16 status;
	u16 rsp0;
	u16 rsp1;
	u16 rsp2;
} Resp;

typedef struct {
	u16 len; /* sizeof(ConfigRid) */
	u16 opmode; /* operating mode */
#define MODE_STA_IBSS 0
#define MODE_STA_ESS 1
#define MODE_AP 2
#define MODE_AP_RPTR 3
#define MODE_ETHERNET_HOST (0<<8) /* rx payloads converted */
#define MODE_LLC_HOST (1<<8) /* rx payloads left as is */
#define MODE_AIRONET_EXTEND (1<<9) /* enable Aironet extenstions */
#define MODE_AP_INTERFACE (1<<10) /* enable ap interface extensions */
#define MODE_ANTENNA_ALIGN (1<<11) /* enable antenna alignment */
#define MODE_ETHER_LLC (1<<12) /* enable ethernet LLC */
#define MODE_LEAF_NODE (1<<13) /* enable leaf node bridge */
#define MODE_CF_POLLABLE (1<<14) /* enable CF pollable */
	u16 rmode; /* receive mode */
#define RXMODE_BC_MC_ADDR 0
#define RXMODE_BC_ADDR 1 /* ignore multicasts */
#define RXMODE_ADDR 2 /* ignore multicast and broadcast */
#define RXMODE_RFMON 3 /* wireless monitor mode */
#define RXMODE_RFMON_ANYBSS 4
#define RXMODE_LANMON 5 /* lan style monitor -- data packets only */
#define RXMODE_DISABLE_802_3_HEADER (1<<8) /* disables 802.3 header on rx */
#define RXMODE_NORMALIZED_RSSI (1<<9) /* return normalized RSSI */
	u16 fragThresh;
	u16 rtsThres;
	u8 macAddr[6];
	u8 rates[8];
	u16 shortRetryLimit;
	u16 longRetryLimit;
	u16 txLifetime; /* in kusec */
	u16 rxLifetime; /* in kusec */
	u16 stationary;
	u16 ordering;
	u16 u16deviceType; /* for overriding device type */
	u16 cfpRate;
	u16 cfpDuration;
	u16 _reserved1[3];
	/*---------- Scanning/Associating ----------*/
	u16 scanMode;
#define SCANMODE_ACTIVE 0
#define SCANMODE_PASSIVE 1
#define SCANMODE_AIROSCAN 2
	u16 probeDelay; /* in kusec */
	u16 probeEnergyTimeout; /* in kusec */
        u16 probeResponseTimeout;
	u16 beaconListenTimeout;
	u16 joinNetTimeout;
	u16 authTimeout;
	u16 authType;
#define AUTH_OPEN 0x1
#define AUTH_ENCRYPT 0x101
#define AUTH_SHAREDKEY 0x102
#define AUTH_ALLOW_UNENCRYPTED 0x200
	u16 associationTimeout;
	u16 specifiedApTimeout;
	u16 offlineScanInterval;
	u16 offlineScanDuration;
	u16 linkLossDelay;
	u16 maxBeaconLostTime;
	u16 refreshInterval;
#define DISABLE_REFRESH 0xFFFF
	u16 _reserved1a[1];
	/*---------- Power save operation ----------*/
	u16 powerSaveMode;
#define POWERSAVE_CAM 0
#define POWERSAVE_PSP 1
#define POWERSAVE_PSPCAM 2
	u16 sleepForDtims;
	u16 listenInterval;
	u16 fastListenInterval;
	u16 listenDecay;
	u16 fastListenDelay;
	u16 _reserved2[2];
	/*---------- Ap/Ibss config items ----------*/
	u16 beaconPeriod;
	u16 atimDuration;
	u16 hopPeriod;
	u16 channelSet;
	u16 channel;
	u16 dtimPeriod;
	u16 bridgeDistance;
	u16 radioID;
	/*---------- Radio configuration ----------*/
	u16 radioType;
#define RADIOTYPE_DEFAULT 0
#define RADIOTYPE_802_11 1
#define RADIOTYPE_LEGACY 2
	u8 rxDiversity;
	u8 txDiversity;
	u16 txPower;
#define TXPOWER_DEFAULT 0
	u16 rssiThreshold;
#define RSSI_DEFAULT 0
        u16 modulation;
	u16 shortPreamble;
	u16 homeProduct;
	u16 radioSpecific;
	/*---------- Aironet Extensions ----------*/
	u8 nodeName[16];
	u16 arlThreshold;
	u16 arlDecay;
	u16 arlDelay;
	u16 _reserved4[1];
	/*---------- Aironet Extensions ----------*/
	u16 magicAction;
#define MAGIC_ACTION_STSCHG 1
#define MACIC_ACTION_RESUME 2
#define MAGIC_IGNORE_MCAST (1<<8)
#define MAGIC_IGNORE_BCAST (1<<9)
#define MAGIC_SWITCH_TO_PSP (0<<10)
#define MAGIC_STAY_IN_CAM (1<<10)
	u16 magicControl;
	u16 autoWake;
} ConfigRid;

typedef struct {
	u16 len;
	u8 mac[6];
	u16 mode;
	u16 errorCode;
	u16 sigQuality;
	u16 SSIDlen;
	char SSID[32];
	char apName[16];
	char bssid[4][6];
	u16 beaconPeriod;
	u16 dimPeriod;
	u16 atimDuration;
	u16 hopPeriod;
	u16 channelSet;
	u16 channel;
	u16 hopsToBackbone;
	u16 apTotalLoad;
	u16 generatedLoad;
	u16 accumulatedArl;
	u16 signalQuality;
	u16 currentXmitRate;
	u16 apDevExtensions;
	u16 normalizedSignalStrength;
	u16 _reserved[10];
} StatusRid;

typedef struct {
	u16 len;
	u16 spacer;
	u32 vals[100];
} StatsRid;
	

typedef struct {
	u16 len;
	u8 ap[4][6];
} APListRid;

typedef struct {
	u16 len;
	char oui[3];
	u16 prodNum;
	char manName[32];
	char prodName[16];
	char prodVer[8];
	char factoryAddr[6];
	char aironetAddr[6];
	u16 radioType;
	u16 country;
	char callid[6];
	char supportedRates[8];
	char rxDiversity;
	char txDiversity;
	u16 txPowerLevels[8];
	u16 hardVer;
	u16 hardCap;
	u16 tempRange;
	u16 softVer;
	u16 softSubVer;
	u16 interfaceVer;
	u16 softCap;
	u16 bootBlockVer;
	u16 requiredHard;
} CapabilityRid;

#define TXCTL_TXOK (1<<1) /* report if tx is ok */
#define TXCTL_TXEX (1<<2) /* report if tx fails */
#define TXCTL_802_3 (0<<3) /* 802.3 packet */
#define TXCTL_802_11 (1<<3) /* 802.11 mac packet */
#define TXCTL_ETHERNET (0<<4) /* payload has ethertype */
#define TXCTL_LLC (1<<4) /* payload is llc */
#define TXCTL_RELEASE (0<<5) /* release after completion */
#define TXCTL_NORELEASE (1<<5) /* on completion returns to host */

#define BUSY_FID 0x10000

#ifdef CISCO_EXT
#define AIROMAGIC	0xa55a
#define AIROIOCTL	SIOCDEVPRIVATE
#define AIROIDIFC 	AIROIOCTL + 1

/* Ioctl constants to be used in airo_ioctl.command */

#define	AIROGCAP  		0	// Capability rid
#define AIROGCFG		1       // USED A LOT 
#define AIROGSLIST		2	// System ID list 
#define AIROGVLIST		3       // List of specified AP's
#define AIROGDRVNAM		4	//  NOTUSED
#define AIROGEHTENC		5	// NOTUSED
#define AIROGWEPKTMP		6
#define AIROGWEPKNV		7
#define AIROGSTAT		8
#define AIROGSTATSC32		9
#define AIROGSTATSD32		10

/* Leave gap of 40 commands after AIROGSTATSD32 for future */

#define AIROPCAP               	AIROGSTATSD32 + 40
#define AIROPVLIST              AIROPCAP      + 1
#define AIROPSLIST		AIROPVLIST    + 1
#define AIROPCFG		AIROPSLIST    + 1
#define AIROPSIDS		AIROPCFG      + 1
#define AIROPAPLIST		AIROPSIDS     + 1
#define AIROPMACON		AIROPAPLIST   + 1	/* Enable mac  */
#define AIROPMACOFF		AIROPMACON    + 1 	/* Disable mac */
#define AIROPSTCLR		AIROPMACOFF   + 1
#define AIROPWEPKEY		AIROPSTCLR    + 1
#define AIROPWEPKEYNV		AIROPWEPKEY   + 1
#define AIROPLEAPPWD            AIROPWEPKEYNV + 1
#define AIROPLEAPUSR            AIROPLEAPPWD  + 1

/* Flash codes */

#define AIROFLSHRST	       AIROPWEPKEYNV  + 40
#define AIROFLSHGCHR           AIROFLSHRST    + 1
#define AIROFLSHSTFL           AIROFLSHGCHR   + 1
#define AIROFLSHPCHR           AIROFLSHSTFL   + 1
#define AIROFLPUTBUF           AIROFLSHPCHR   + 1
#define AIRORESTART            AIROFLPUTBUF   + 1

#define FLASHSIZE	32768

typedef struct aironet_ioctl {
	unsigned short command;	// What to do
	unsigned short len;		// Len of data
	unsigned char *data;		// d-data
} aironet_ioctl;
#endif /* CISCO_EXT */

#ifdef WIRELESS_EXT
// Frequency list (map channels to frequencies)
const long frequency_list[] = { 2412, 2417, 2422, 2427, 2432, 2437, 2442,
				2447, 2452, 2457, 2462, 2467, 2472, 2484 };

// A few details needed for WEP (Wireless Equivalent Privacy)
#define MAX_KEY_SIZE 13			// 128 (?) bits
#define MIN_KEY_SIZE  5			// 40 bits RC4 - WEP
#define MAX_KEYS      4			// 4 different keys
typedef struct wep_key_t {
	u16	len;
	u8	key[16];	/* 40-bit and 104-bit keys */
} wep_key_t;
#endif /* WIRELESS_EXT */

static const char version[] = "airo.c 0.2 (Ben Reed & Javier Achirica)";

struct airo_info;

static int get_dec_u16( char *buffer, int *start, int limit );
static void OUT4500( struct airo_info *, u16 register, u16 value );
static unsigned short IN4500( struct airo_info *, u16 register );
static u16 setup_card(struct airo_info*, u8 *mac, ConfigRid *);
static void enable_interrupts(struct airo_info*);
static void disable_interrupts(struct airo_info*);
static u16 issuecommand(struct airo_info*, Cmd *pCmd, Resp *pRsp);
static int bap_setup(struct airo_info*, u16 rid, u16 offset, int whichbap);
static int aux_bap_read(struct airo_info*, u16 *pu16Dst, int bytelen, 
			int whichbap);
static int fast_bap_read(struct airo_info*, u16 *pu16Dst, int bytelen, 
			 int whichbap);
static int bap_write(struct airo_info*, const u16 *pu16Src, int bytelen,
		     int whichbap);
static int PC4500_accessrid(struct airo_info*, u16 rid, u16 accmd);
static int PC4500_readrid(struct airo_info*, u16 rid, void *pBuf, int len);
static int PC4500_writerid(struct airo_info*, u16 rid, const void
			   *pBuf, int len);
static int do_writerid( struct airo_info*, u16 rid, const void *rid_data, 
			int len );
static u16 transmit_allocate(struct airo_info*, int lenPayload);
static int transmit_802_3_packet(struct airo_info*, u16 TxFid, char
				 *pPacket, int len);

static void airo_interrupt( int irq, void* dev_id, struct pt_regs
			    *regs);
static int airo_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
#ifdef WIRELESS_EXT
struct iw_statistics *airo_get_wireless_stats (struct net_device *dev);
#endif /* WIRELESS_EXT */
#ifdef CISCO_EXT
static int readrids(struct net_device *dev, aironet_ioctl *comp);
static int writerids(struct net_device *dev, aironet_ioctl *comp);
int flashcard(struct net_device *dev, aironet_ioctl *comp);
#endif /* CISCO_EXT */

struct airo_info {
	struct net_device_stats	stats;
	int open;
	struct net_device             *dev;
	/* Note, we can have MAX_FIDS outstanding.  FIDs are 16-bits, so we
	   use the high bit to mark wether it is in use. */
#define MAX_FIDS 6
	int                           fids[MAX_FIDS];
	int registered;
	ConfigRid config;
	u16 authtype; // Used with auto_wep 
	char keyindex; // Used with auto wep
	char defindex; // Used with auto wep
	struct timer_list timer;
	struct proc_dir_entry *proc_entry;
	struct airo_info *next;
        spinlock_t bap0_lock;
        spinlock_t bap1_lock;
        spinlock_t aux_lock;
        spinlock_t cmd_lock;
        int flags;
#define FLAG_PROMISC   0x01
#define FLAG_RADIO_OFF 0x02
	int (*bap_read)(struct airo_info*, u16 *pu16Dst, int bytelen, 
			int whichbap);
	int (*header_parse)(struct sk_buff*, unsigned char *);
#ifdef WIRELESS_EXT
	int			need_commit;	// Need to set config
	struct iw_statistics	wstats;		// wireless stats
#ifdef WIRELESS_SPY
	int			spy_number;
	u_char			spy_address[IW_MAX_SPY][6];
	struct iw_quality	spy_stat[IW_MAX_SPY];
#endif /* WIRELESS_SPY */
#endif /* WIRELESS_EXT */
};

static inline int bap_read(struct airo_info *ai, u16 *pu16Dst, int bytelen, 
			   int whichbap) {
	return ai->bap_read(ai, pu16Dst, bytelen, whichbap);
}

static int setup_proc_entry( struct net_device *dev,
			     struct airo_info *apriv );
static int takedown_proc_entry( struct net_device *dev,
				struct airo_info *apriv );

static int readWepKeyRid(struct airo_info*ai, WepKeyRid *wkr, int temp) {
	int rc = PC4500_readrid(ai, temp ? RID_WEP_TEMP : RID_WEP_PERM, 
				wkr, sizeof(*wkr));
	
	wkr->len = le16_to_cpu(wkr->len);
	wkr->kindex = le16_to_cpu(wkr->kindex);
	wkr->klen = le16_to_cpu(wkr->klen);
	return rc;
}
/* In the writeXXXRid routines we copy the rids so that we don't screwup
 * the originals when we endian them... */
static int writeWepKeyRid(struct airo_info*ai, WepKeyRid *pwkr, int perm) {
	int rc;
	WepKeyRid wkr = *pwkr;

	wkr.len = cpu_to_le16(wkr.len);
	wkr.kindex = cpu_to_le16(wkr.kindex);
	wkr.klen = cpu_to_le16(wkr.klen);
	rc = do_writerid(ai, RID_WEP_TEMP, &wkr, sizeof(wkr));
	if (rc!=SUCCESS) printk(KERN_ERR "airo:  WEP_TEMP set %x\n", rc); 
	if (perm) {
		rc = do_writerid(ai, RID_WEP_PERM, &wkr, sizeof(wkr));
		if (rc!=SUCCESS) {
			printk(KERN_ERR "airo:  WEP_PERM set %x\n", rc);
		}
	}
	return rc;
}

static int readSsidRid(struct airo_info*ai, SsidRid *ssidr) {
	int i;
	int rc = PC4500_readrid(ai, RID_SSID, ssidr, sizeof(*ssidr));

	ssidr->len = le16_to_cpu(ssidr->len);
	for(i = 0; i < 3; i++) {
		ssidr->ssids[i].len = le16_to_cpu(ssidr->ssids[i].len);
	}
	return rc;
}
static int writeSsidRid(struct airo_info*ai, SsidRid *pssidr) {
	int rc;
	int i;
	SsidRid ssidr = *pssidr;

	ssidr.len = cpu_to_le16(ssidr.len);
	for(i = 0; i < 3; i++) {
		ssidr.ssids[i].len = cpu_to_le16(ssidr.ssids[i].len);
	}
	rc = do_writerid(ai, RID_SSID, &ssidr, sizeof(ssidr));
	return rc;
}
static int readConfigRid(struct airo_info*ai, ConfigRid *cfgr) {
	int rc = PC4500_readrid(ai, RID_ACTUALCONFIG, cfgr, sizeof(*cfgr));
	u16 *s;
	
	for(s = &cfgr->len; s <= &cfgr->rtsThres; s++) *s = le16_to_cpu(*s);

	for(s = &cfgr->shortRetryLimit; s <= &cfgr->radioType; s++)
		*s = le16_to_cpu(*s);

	for(s = &cfgr->txPower; s <= &cfgr->radioSpecific; s++)
		*s = le16_to_cpu(*s);
	
	for(s = &cfgr->arlThreshold; s <= &cfgr->autoWake; s++)
		*s = le16_to_cpu(*s);
	
	return rc;
}
static int writeConfigRid(struct airo_info*ai, ConfigRid *pcfgr) {
	u16 *s;
	ConfigRid cfgr = *pcfgr;
	
	for(s = &cfgr.len; s <= &cfgr.rtsThres; s++) *s = cpu_to_le16(*s);

	for(s = &cfgr.shortRetryLimit; s <= &cfgr.radioType; s++)
		*s = cpu_to_le16(*s);

	for(s = &cfgr.txPower; s <= &cfgr.radioSpecific; s++)
		*s = cpu_to_le16(*s);
	
	for(s = &cfgr.arlThreshold; s <= &cfgr.autoWake; s++)
		*s = cpu_to_le16(*s);
	
	return do_writerid( ai, RID_CONFIG, &cfgr, sizeof(cfgr));
}
static int readStatusRid(struct airo_info*ai, StatusRid *statr) {
	int rc = PC4500_readrid(ai, RID_STATUS, statr, sizeof(*statr));
	u16 *s;

	statr->len = le16_to_cpu(statr->len);
	for(s = &statr->mode; s <= &statr->SSIDlen; s++) *s = le16_to_cpu(*s);

	for(s = &statr->beaconPeriod; s <= &statr->_reserved[9]; s++)
		*s = le16_to_cpu(*s);

	return rc;
}
static int readAPListRid(struct airo_info*ai, APListRid *aplr) {
	int rc =  PC4500_readrid(ai, RID_APLIST, aplr, sizeof(*aplr));
	aplr->len = le16_to_cpu(aplr->len);
	return rc;
}
static int writeAPListRid(struct airo_info*ai, APListRid *aplr) {
	int rc;
	aplr->len = cpu_to_le16(aplr->len);
	rc = do_writerid(ai, RID_APLIST, aplr, sizeof(*aplr));
	return rc;
}
static int readCapabilityRid(struct airo_info*ai, CapabilityRid *capr) {
	int rc = PC4500_readrid(ai, RID_CAPABILITIES, capr, sizeof(*capr));
	u16 *s;
	
	capr->len = le16_to_cpu(capr->len);
	capr->prodNum = le16_to_cpu(capr->prodNum);
	capr->radioType = le16_to_cpu(capr->radioType);
	capr->country = le16_to_cpu(capr->country);
	for(s = &capr->txPowerLevels[0]; s <= &capr->requiredHard; s++)
		*s = le16_to_cpu(*s);
	return rc;
}
static int readStatsRid(struct airo_info*ai, StatsRid *sr, int rid) {
	int rc = PC4500_readrid(ai, rid, sr, sizeof(*sr));
	u32 *i;

	sr->len = le16_to_cpu(sr->len);
	for(i = &sr->vals[0]; i <= &sr->vals[99]; i++) *i = le32_to_cpu(*i);
	return rc;
}

static int airo_open(struct net_device *dev) {
	struct airo_info *info = dev->priv;

	enable_interrupts(info);

	netif_start_queue(dev);
	return 0;
}

static int airo_start_xmit(struct sk_buff *skb, struct net_device *dev) {
	s16 len;
	s16 retval = 0;
	u16 status;
	u32 flags;
	s8 *buffer;
	int i,j;
	struct airo_info *priv = (struct airo_info*)dev->priv;
	u32 *fids = priv->fids;
	
	if ( skb == NULL ) {
		printk( KERN_ERR "airo:  skb == NULL!!!\n" );
		return 0;
	}
	
	/* Find a vacant FID */
	spin_lock_irqsave(&priv->bap1_lock, flags);
	for( j = 0, i = -1; j < MAX_FIDS; j++ ) {
		if ( !( fids[j] & 0xffff0000 ) ) {
			if ( i == -1 ) i = j;
			else break;
		}
	}
	if ( j == MAX_FIDS ) netif_stop_queue(dev);
	if ( i == -1 ) {
		retval = -EBUSY;
		goto tx_done;
	}
	
	len = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN; /* check min length*/
	buffer = skb->data;
	
	status = transmit_802_3_packet( priv, 
					fids[i],
					skb->data, len );
	
	if ( status == SUCCESS ) {
                /* Mark fid as used & save length for later */
		fids[i] |= (len << 16); 
		dev->trans_start = jiffies;
	} else {
		priv->stats.tx_errors++;
	}
 tx_done:
	spin_unlock_irqrestore(&priv->bap1_lock, flags);
	dev_kfree_skb(skb);
	return 0;
}

static struct net_device_stats *airo_get_stats(struct net_device *dev) {
	return &(((struct airo_info*)dev->priv)->stats);
}

static int enable_MAC( struct airo_info *ai, Resp *rsp );
static void disable_MAC(struct airo_info *ai);

static void airo_set_multicast_list(struct net_device *dev) {
	struct airo_info *ai = (struct airo_info*)dev->priv;
	Cmd cmd;
	Resp rsp;
	  
	memset(&cmd, 0, sizeof(cmd));
	cmd.cmd=CMD_SETMODE;
	cmd.parm0=(dev->flags&IFF_PROMISC) ? PROMISC : NOPROMISC;
	issuecommand(ai, &cmd, &rsp);

	if ((dev->flags&IFF_ALLMULTI)||dev->mc_count>0) {
		/* Turn on multicast.  (Should be already setup...) */
	}
}

static int airo_set_mac_address(struct net_device *dev, void *p)
{
	struct airo_info *ai = (struct airo_info*)dev->priv;
	struct sockaddr *addr = p;
	ConfigRid cfg;

	readConfigRid (ai, &cfg);
	memcpy (cfg.macAddr, addr->sa_data, dev->addr_len);
	writeConfigRid (ai, &cfg);
	memcpy (dev->dev_addr, addr->sa_data, dev->addr_len);
	return 0;
}

static int airo_change_mtu(struct net_device *dev, int new_mtu)
{
	if ((new_mtu < 68) || (new_mtu > 2400))
		return -EINVAL;
	dev->mtu = new_mtu;
	return 0;
}


static int airo_close(struct net_device *dev) { 
	struct airo_info *ai = (struct airo_info*)dev->priv;

	netif_stop_queue(dev);
	disable_interrupts( ai );
	return 0;
}

static void del_airo_dev( struct net_device *dev );

void stop_airo_card( struct net_device *dev, int freeres ) 
{
	struct airo_info *ai = (struct airo_info*)dev->priv;
	takedown_proc_entry( dev, ai );
	if (ai->registered) {
		unregister_netdev( dev );
		ai->registered = 0;
	}
	disable_interrupts(ai);
	free_irq( dev->irq, dev );
	if (auto_wep) del_timer_sync(&ai->timer);
	if (freeres) {
		/* PCMCIA frees this stuff, so only for PCI and ISA */
	        release_region( dev->base_addr, 64 );
        }
	del_airo_dev( dev );
	kfree( dev );
}

static int add_airo_dev( struct net_device *dev ); 

struct net_device *init_airo_card( unsigned short irq, int port, int is_pcmcia )
{
	struct net_device *dev;
	struct airo_info *ai;
	int i, rc;
	
	/* Create the network device object. */
        dev = alloc_etherdev(sizeof(*ai));
        if (!dev) {
		printk(KERN_ERR "airo:  Couldn't alloc_etherdev\n");
		return NULL;
        }
	ai = dev->priv;
	ai->registered = 1;
        ai->dev = dev;
	ai->bap0_lock = SPIN_LOCK_UNLOCKED;
	ai->bap1_lock = SPIN_LOCK_UNLOCKED;
	ai->aux_lock = SPIN_LOCK_UNLOCKED;
	ai->cmd_lock = SPIN_LOCK_UNLOCKED;
	ai->header_parse = dev->hard_header_parse;
	rc = add_airo_dev( dev );
	if (rc)
		goto err_out_free;
	
	/* The Airo-specific entries in the device structure. */
	dev->hard_start_xmit = &airo_start_xmit;
	dev->get_stats = &airo_get_stats;
	dev->set_multicast_list = &airo_set_multicast_list;
	dev->set_mac_address = &airo_set_mac_address;
	dev->do_ioctl = &airo_ioctl;
#ifdef WIRELESS_EXT
	dev->get_wireless_stats = airo_get_wireless_stats;
#endif /* WIRELESS_EXT */
	dev->change_mtu = &airo_change_mtu;
	dev->open = &airo_open;
	dev->stop = &airo_close;
	dev->irq = irq;
	dev->base_addr = port;
	
	rc = register_netdev(dev);
	if (rc)
		goto err_out_unlink;
	
	rc = request_irq( dev->irq, airo_interrupt, 
			  SA_SHIRQ | SA_INTERRUPT, dev->name, dev );
	if (rc) {
		printk(KERN_ERR "airo: register interrupt %d failed, rc %d\n", irq, rc );
		goto err_out_unregister;
	}
	if (!is_pcmcia) {
		if (!request_region( dev->base_addr, 64, dev->name )) {
			rc = -EBUSY;
			goto err_out_irq;
		}
	}
	
	if ( setup_card( ai, dev->dev_addr, &ai->config) != SUCCESS ) {
		printk( KERN_ERR "airo: MAC could not be enabled\n" );
		rc = -EIO;
		goto err_out_res;
	}

	printk( KERN_INFO "airo: MAC enabled %s %x:%x:%x:%x:%x:%x\n",
		dev->name,
		dev->dev_addr[0], dev->dev_addr[1], dev->dev_addr[2],
		dev->dev_addr[3], dev->dev_addr[4], dev->dev_addr[5] );

	/* Allocate the transmit buffers */
	for( i = 0; i < MAX_FIDS; i++ )
		ai->fids[i] = transmit_allocate( ai, 2312 );

	setup_proc_entry( dev, dev->priv ); /* XXX check for failure */
	netif_start_queue(dev);
	SET_MODULE_OWNER(dev);
	return dev;

err_out_res:
	if (!is_pcmcia)
	        release_region( dev->base_addr, 64 );
err_out_irq:
	free_irq(dev->irq, dev);
err_out_unregister:
	unregister_netdev(dev);
err_out_unlink:
	del_airo_dev(dev);
err_out_free:
	kfree(dev);
	return NULL;
}

int waitbusy (struct airo_info *ai) {
	int delay = 0;
	while ((IN4500 (ai, COMMAND) & COMMAND_BUSY) & (delay < 10000)) {
		udelay (10);
		if (++delay % 20)
			OUT4500(ai, EVACK, EV_CLEARCOMMANDBUSY);
	}  
	return delay < 10000;
}

int reset_airo_card( struct net_device *dev ) {
	int i, flags;
	struct airo_info *ai = (struct airo_info*)dev->priv;

	disable_MAC(ai);
	spin_lock_irqsave(&ai->cmd_lock, flags);
	waitbusy (ai);
	OUT4500(ai,COMMAND,CMD_SOFTRESET);
	set_current_state (TASK_UNINTERRUPTIBLE);
	schedule_timeout (HZ/5);
	waitbusy (ai);
	set_current_state (TASK_UNINTERRUPTIBLE);
	schedule_timeout (HZ/5);
	spin_unlock_irqrestore(&ai->cmd_lock, flags);
	if ( setup_card(ai, dev->dev_addr, &(ai)->config) != SUCCESS ) {
		printk( KERN_ERR "airo: MAC could not be enabled\n" );
		return -1;
	} else {
		printk( KERN_INFO "airo: MAC enabled %s %x:%x:%x:%x:%x:%x\n",
			dev->name,
			dev->dev_addr[0],
			dev->dev_addr[1],
			dev->dev_addr[2],
			dev->dev_addr[3],
			dev->dev_addr[4],
			dev->dev_addr[5]
			);
		/* Allocate the transmit buffers */
		for( i = 0; i < MAX_FIDS; i++ )
			ai->fids[i] = transmit_allocate( ai, 2312 );
	}
	enable_interrupts( ai );
	netif_wake_queue(dev);
	return 0;
}

int wll_header_parse(struct sk_buff *skb, unsigned char *haddr)
{
	memcpy(haddr, skb->mac.raw + 10, ETH_ALEN);
	return ETH_ALEN;
}

static void airo_interrupt ( int irq, void* dev_id, struct pt_regs *regs) {
	struct net_device *dev = (struct net_device *)dev_id;
	u16 status;
	u16 fid;
	struct airo_info *apriv = (struct airo_info *)dev->priv;
	u16 savedInterrupts;
	

	if (!netif_device_present(dev))
		return;
	
	status = IN4500( apriv, EVSTAT );
	if ( !status || status == 0xffff ) return;
	
	if ( status & EV_AWAKE ) {
		OUT4500( apriv, EVACK, EV_AWAKE );
		OUT4500( apriv, EVACK, EV_AWAKE );
	}
	
	savedInterrupts = IN4500( apriv, EVINTEN );
	OUT4500( apriv, EVINTEN, 0 );
	
	if ( status & EV_LINK ) {
		/* The link status has changed, if you want to put a
		   monitor hook in, do it here.  (Remember that
		   interrupts are still disabled!)
		*/
		u16 newStatus = IN4500(apriv, LINKSTAT);
		/* Here is what newStatus means: */
#define NOBEACON 0x8000 /* Loss of sync - missed beacons */
#define MAXRETRIES 0x8001 /* Loss of sync - max retries */
#define MAXARL 0x8002 /* Loss of sync - average retry level exceeded*/
#define FORCELOSS 0x8003 /* Loss of sync - host request */
#define TSFSYNC 0x8004 /* Loss of sync - TSF synchronization */
#define DEAUTH 0x8100 /* Deauthentication (low byte is reason code) */
#define DISASS 0x8200 /* Disassociation (low byte is reason code) */
#define ASSFAIL 0x8400 /* Association failure (low byte is reason
			  code) */
#define AUTHFAIL 0x0300 /* Authentication failure (low byte is reason
			   code) */
#define ASSOCIATED 0x0400 /* Assocatied */
#define RC_RESERVED 0 /* Reserved return code */
#define RC_NOREASON 1 /* Unspecified reason */
#define RC_AUTHINV 2 /* Previous authentication invalid */
#define RC_DEAUTH 3 /* Deauthenticated because sending station is
		       leaving */
#define RC_NOACT 4 /* Disassociated due to inactivity */
#define RC_MAXLOAD 5 /* Disassociated because AP is unable to handle
			all currently associated stations */
#define RC_BADCLASS2 6 /* Class 2 frame received from
			  non-Authenticated station */
#define RC_BADCLASS3 7 /* Class 3 frame received from
			  non-Associated station */
#define RC_STATLEAVE 8 /* Disassociated because sending station is
			  leaving BSS */
#define RC_NOAUTH 9 /* Station requesting (Re)Association is not
		       Authenticated with the responding station */
		if (newStatus != ASSOCIATED) {
			if (auto_wep && !timer_pending(&apriv->timer)) {
				apriv->timer.expires = RUN_AT(HZ*3);
	      			add_timer(&apriv->timer);
			}
		}
	}
	
	/* Check to see if there is something to receive */
	if ( status & EV_RX  ) {
		struct sk_buff *skb = NULL;
		int flags;
		u16 fc, len, hdrlen = 0;
		struct {
			u16 status, len;
			u8 rssi[2];
		} hdr;

		fid = IN4500( apriv, RXFID );

		/* Get the packet length */
	        spin_lock_irqsave(&apriv->bap0_lock, flags);
		if (dev->type == ARPHRD_IEEE80211) {
			bap_setup (apriv, fid, 4, BAP0);
			bap_read (apriv, (u16*)&hdr, sizeof(hdr), BAP0);
			/* Bad CRC. Ignore packet */
			if (le16_to_cpu(hdr.status) == 2) {
				apriv->stats.rx_crc_errors++;
				apriv->stats.rx_errors++;
				hdr.len = 0;
			}
		} else {
			bap_setup (apriv, fid, 6, BAP0);
			bap_read (apriv, (u16*)&hdr.len, 4, BAP0);
		}
		len = le16_to_cpu(hdr.len);

		if (len > 2312) {
			apriv->stats.rx_length_errors++;
			apriv->stats.rx_errors++;
			printk( KERN_ERR 
				"airo: Bad size %d\n", len );
			len = 0;
		}
		if (len) {
			if (dev->type == ARPHRD_IEEE80211) {
				bap_setup (apriv, fid, 0x14, BAP0);
				bap_read (apriv, (u16*)&fc, sizeof(fc), BAP0);
				if ((le16_to_cpu(fc) & 0x300) == 0x300)
					hdrlen = 30;
				else
					hdrlen = 24;
			} else
				hdrlen = 12;

			skb = dev_alloc_skb( len + hdrlen + 2 );
			if ( !skb ) {
				apriv->stats.rx_dropped++;
				len = 0;
			}
		}
		if (len) {
			u16 *buffer;
			buffer = (u16*)skb_put (skb, len + hdrlen);
			if (dev->type == ARPHRD_IEEE80211) {
				u16 gap, tmpbuf[4];
				buffer[0] = fc;
				bap_read (apriv, buffer + 1, hdrlen - 2, BAP0);
				if (hdrlen == 24)
					bap_read (apriv, tmpbuf, 6, BAP0);

				bap_read (apriv, &gap, sizeof(gap), BAP0);
				gap = le16_to_cpu(gap);
				if (gap && gap <= 8)
					bap_read (apriv, tmpbuf, gap, BAP0);

				bap_read (apriv, buffer + hdrlen/2, len, BAP0);
			} else {
		                bap_setup (apriv, fid, 0x38, BAP0);
				bap_read (apriv, buffer,len + hdrlen,BAP0);
			}
#ifdef WIRELESS_SPY
			if (apriv->spy_number > 0) {
				int i;
				char *sa;

				sa = (char*)buffer + ((dev->type == ARPHRD_IEEE80211) ? 10 : 6);

				for (i=0; i<apriv->spy_number; i++)
					if (!memcmp(sa,apriv->spy_address[i],6))
					{
						apriv->spy_stat[i].qual = hdr.rssi[0];
						apriv->spy_stat[i].level = hdr.rssi[1];
						apriv->spy_stat[i].noise = 0;
						apriv->spy_stat[i].updated = 3;
						break;
					}
			}
#endif /* WIRELESS_SPY  */
			apriv->stats.rx_packets++;
			apriv->stats.rx_bytes += len + hdrlen;
			dev->last_rx = jiffies;
			skb->dev = dev;
			skb->ip_summed = CHECKSUM_NONE;
			if (dev->type == ARPHRD_IEEE80211) {
				skb->mac.raw = skb->data;
				skb_pull (skb, hdrlen);
				skb->pkt_type = PACKET_OTHERHOST;
				skb->protocol = htons(ETH_P_802_2);
			} else
				skb->protocol = eth_type_trans( skb, dev );

			netif_rx( skb );
		}
		spin_unlock_irqrestore(&apriv->bap0_lock, flags);
	}

	/* Check to see if a packet has been transmitted */
	if (  status & ( EV_TX|EV_TXEXC ) ) {
		int i;
		int len = 0;
		int full = 1;
		int index = -1;
		
		fid = IN4500(apriv, TXCOMPLFID);
		
		for( i = 0; i < MAX_FIDS; i++ ) {
			if (!(apriv->fids[i] & 0xffff0000)) full = 0;
			if ( ( apriv->fids[i] & 0xffff ) == fid ) {
				len = apriv->fids[i] >> 16;
				index = i;
				/* Set up to be used again */
				apriv->fids[i] &= 0xffff; 
			}
		}
		if (full) netif_wake_queue(dev);
		if (index==-1) {
			printk( KERN_ERR
				"airo: Unallocated FID was used to xmit\n" );
		}
		if ( status & EV_TX ) {
			apriv->stats.tx_packets++;
			if(index!=-1)
				apriv->stats.tx_bytes += len;
		} else {
			apriv->stats.tx_errors++;
		}
	}
	if ( status & ~STATUS_INTS ) 
		printk( KERN_WARNING 
			"airo: Got weird status %x\n", 
			status & ~STATUS_INTS );
	OUT4500( apriv, EVACK, status & STATUS_INTS );
	OUT4500( apriv, EVINTEN, savedInterrupts );
	
	/* done.. */
	return;     
}

/*
 *  Routines to talk to the card
 */

/*
 *  This was originally written for the 4500, hence the name
 *  NOTE:  If use with 8bit mode and SMP bad things will happen!
 *         Why would some one do 8 bit IO in an SMP machine?!?
 */
static void OUT4500( struct airo_info *ai, u16 reg, u16 val ) {
	if ( !do8bitIO )
		outw( val, ai->dev->base_addr + reg );
	else {
		outb( val & 0xff, ai->dev->base_addr + reg );
		outb( val >> 8, ai->dev->base_addr + reg + 1 );
	}
}

static u16 IN4500( struct airo_info *ai, u16 reg ) {
	unsigned short rc;
	
	if ( !do8bitIO )
		rc = inw( ai->dev->base_addr + reg );
	else {
		rc = inb( ai->dev->base_addr + reg );
		rc += ((int)inb( ai->dev->base_addr + reg + 1 )) << 8;
	}
	return rc;
}

static int enable_MAC( struct airo_info *ai, Resp *rsp ) {
        Cmd cmd;

        if (ai->flags&FLAG_RADIO_OFF) return SUCCESS;
	memset(&cmd, 0, sizeof(cmd));
	cmd.cmd = MAC_ENABLE;
	return issuecommand(ai, &cmd, rsp);
}

static void disable_MAC( struct airo_info *ai ) {
        Cmd cmd;
	Resp rsp;

	memset(&cmd, 0, sizeof(cmd));
	cmd.cmd = MAC_DISABLE; // disable in case already enabled
	issuecommand(ai, &cmd, &rsp);
}

static void enable_interrupts( struct airo_info *ai ) {
	/* Reset the status register */
	u16 status = IN4500( ai, EVSTAT );
	OUT4500( ai, EVACK, status );
	/* Enable the interrupts */
	OUT4500( ai, EVINTEN, STATUS_INTS );
	/* Note there is a race condition between the last two lines that
	   I dont know how to get rid of right now... */
}

static void disable_interrupts( struct airo_info *ai ) {
	OUT4500( ai, EVINTEN, 0 );
}

static u16 setup_card(struct airo_info *ai, u8 *mac, 
		      ConfigRid *config)
{
	Cmd cmd; 
	Resp rsp;
	ConfigRid cfg;
	int status;
	int i;
	SsidRid mySsid;
	u16 lastindex;
	WepKeyRid wkr;
	int rc;

	memset( &mySsid, 0, sizeof( mySsid ) );

	/* The NOP is the first step in getting the card going */
	cmd.cmd = NOP;
	cmd.parm0 = cmd.parm1 = cmd.parm2 = 0;
	if ( issuecommand( ai, &cmd, &rsp ) != SUCCESS ) {
		return ERROR;
	}
	memset(&cmd, 0, sizeof(cmd));
	cmd.cmd = MAC_DISABLE; // disable in case already enabled
	if ( issuecommand( ai, &cmd, &rsp ) != SUCCESS ) {
		return ERROR;
	}
	
	// Let's figure out if we need to use the AUX port
	cmd.cmd = CMD_ENABLEAUX;
	if (issuecommand(ai, &cmd, &rsp) != SUCCESS) {
		printk(KERN_ERR "airo: Error checking for AUX port\n");
		return ERROR;
	}
	if (!aux_bap || rsp.status & 0xff00) {
		ai->bap_read = fast_bap_read;
		printk(KERN_DEBUG "airo: Doing fast bap_reads\n");
	} else {
		ai->bap_read = aux_bap_read;
		printk(KERN_DEBUG "airo: Doing AUX bap_reads\n");
	}
	if ( config->len ) {
		cfg = *config;
	} else {
		// general configuration (read/modify/write)
		status = readConfigRid(ai, &cfg);
		if ( status != SUCCESS ) return ERROR;
		cfg.opmode = adhoc ? MODE_STA_IBSS : MODE_STA_ESS;
    
		/* Save off the MAC */
		for( i = 0; i < 6; i++ ) {
			mac[i] = cfg.macAddr[i];
		}

		/* Check to see if there are any insmod configured 
		   rates to add */
		if ( rates ) {
			int i = 0;
			if ( rates[0] ) memset(cfg.rates,0,sizeof(cfg.rates));
			for( i = 0; i < 8 && rates[i]; i++ ) {
				cfg.rates[i] = rates[i];
			}    
		}
		if ( basic_rate > 0 ) {
			int i;
			for( i = 0; i < 8; i++ ) {
				if ( cfg.rates[i] == basic_rate ||
				     !cfg.rates ) {
					cfg.rates[i] = basic_rate | 0x80;
					break;
				}
			}
		}
		cfg.authType = ai->authtype;
		*config = cfg;
	}
	
	/* Setup the SSIDs if present */
	if ( ssids[0] ) {
		int i = 0;
		for( i = 0; i < 3 && ssids[i]; i++ ) {
			mySsid.ssids[i].len = strlen(ssids[i]);
			if ( mySsid.ssids[i].len > 32 ) 
				mySsid.ssids[i].len = 32;
			memcpy(mySsid.ssids[i].ssid, ssids[i],
			       mySsid.ssids[i].len);
			mySsid.ssids[i].len = mySsid.ssids[i].len;
		}
	}
	
	status = writeConfigRid(ai, &cfg);
	if ( status != SUCCESS ) return ERROR;
	
	/* Set up the SSID list */
	status = writeSsidRid(ai, &mySsid);
	if ( status != SUCCESS ) return ERROR;
	
	/* Grab the initial wep key, we gotta save it for auto_wep */
	rc = readWepKeyRid(ai, &wkr, 1);
	if (rc == SUCCESS) do {
		lastindex = wkr.kindex;
		if (wkr.kindex == 0xffff) {
			ai->defindex = wkr.mac[0];
		}
		rc = readWepKeyRid(ai, &wkr, 0);
	} while(lastindex != wkr.kindex);
	
	if (auto_wep && !timer_pending(&ai->timer)) {
		ai->timer.expires = RUN_AT(HZ*3);
		add_timer(&ai->timer);
	}
	return SUCCESS;
}

static u16 issuecommand(struct airo_info *ai, Cmd *pCmd, Resp *pRsp) {
        // Im really paranoid about letting it run forever!
	int max_tries = 600000;  
        int rc = SUCCESS;
	int flags;

	spin_lock_irqsave(&ai->cmd_lock, flags);
	OUT4500(ai, PARAM0, pCmd->parm0);
	OUT4500(ai, PARAM1, pCmd->parm1);
	OUT4500(ai, PARAM2, pCmd->parm2);
	OUT4500(ai, COMMAND, pCmd->cmd);
	while ( max_tries-- &&
		(IN4500(ai, EVSTAT) & EV_CMD) == 0) {
		if ( IN4500(ai, COMMAND) == pCmd->cmd) { 
			// PC4500 didn't notice command, try again
			OUT4500(ai, COMMAND, pCmd->cmd);
		}
	}
	if ( max_tries == -1 ) {
		printk( KERN_ERR 
			"airo: Max tries exceeded when issueing command\n" );
                rc = ERROR;
                goto done;
	}
	// command completed
	pRsp->status = IN4500(ai, STATUS);
	pRsp->rsp0 = IN4500(ai, RESP0);
	pRsp->rsp1 = IN4500(ai, RESP1);
	pRsp->rsp2 = IN4500(ai, RESP2);
	
	// clear stuck command busy if necessary
	if (IN4500(ai, COMMAND) & COMMAND_BUSY) {
		OUT4500(ai, EVACK, EV_CLEARCOMMANDBUSY);
	}
	// acknowledge processing the status/response
	OUT4500(ai, EVACK, EV_CMD);
 done:
	spin_unlock_irqrestore(&ai->cmd_lock, flags);
	return rc;
}

/* Sets up the bap to start exchange data.  whichbap should
 * be one of the BAP0 or BAP1 defines.  Locks should be held before
 * calling! */
static int bap_setup(struct airo_info *ai, u16 rid, u16 offset, int whichbap )
{
	int timeout = 50;
	int max_tries = 3;
	
	OUT4500(ai, SELECT0+whichbap, rid);
	OUT4500(ai, OFFSET0+whichbap, offset);
	while (1) {
		int status = IN4500(ai, OFFSET0+whichbap);
		if (status & BAP_BUSY) {
                        /* This isn't really a timeout, but its kinda
			   close */
			if (timeout--) { 
				continue;
			}
		} else if ( status & BAP_ERR ) {
			/* invalid rid or offset */
			printk( KERN_ERR "airo: BAP error %x %d\n", 
				status, whichbap );
			return ERROR;
		} else if (status & BAP_DONE) { // success
			return SUCCESS;
		}
		if ( !(max_tries--) ) {
			printk( KERN_ERR 
				"airo: BAP setup error too many retries\n" );
			return ERROR;
		}
		// -- PC4500 missed it, try again
		OUT4500(ai, SELECT0+whichbap, rid);
		OUT4500(ai, OFFSET0+whichbap, offset);
		timeout = 50;
	}
}

/* should only be called by aux_bap_read.  This aux function and the
   following use concepts not documented in the developers guide.  I
   got them from a patch given to my by Aironet */
static u16 aux_setup(struct airo_info *ai, u16 page,
		     u16 offset, u16 *len)
{
	u16 next;

	OUT4500(ai, AUXPAGE, page);
	OUT4500(ai, AUXOFF, 0);
	next = IN4500(ai, AUXDATA);
	*len = IN4500(ai, AUXDATA)&0xff;
	if (offset != 4) OUT4500(ai, AUXOFF, offset);
	return next;
}

/* requires call to bap_setup() first */
static int aux_bap_read(struct airo_info *ai, u16 *pu16Dst,
			int bytelen, int whichbap) 
{
	u16 len;
	u16 page;
	u16 offset;
	u16 next;
	int words;
	int i;
	int flags;

	spin_lock_irqsave(&ai->aux_lock, flags);
	page = IN4500(ai, SWS0+whichbap);
	offset = IN4500(ai, SWS2+whichbap);
	next = aux_setup(ai, page, offset, &len);
	words = (bytelen+1)>>1;

	for (i=0; i<words;) {
		int count;
		count = (len>>1) < (words-i) ? (len>>1) : (words-i);
		if ( !do8bitIO ) 
			insw( ai->dev->base_addr+DATA0+whichbap, 
			      pu16Dst+i,count );
		else
			insb( ai->dev->base_addr+DATA0+whichbap, 
			      pu16Dst+i, count << 1 );
		i += count;
		if (i<words) {
			next = aux_setup(ai, next, 4, &len);
		}
	}
	spin_unlock_irqrestore(&ai->aux_lock, flags);
	return SUCCESS;
}


/* requires call to bap_setup() first */
static int fast_bap_read(struct airo_info *ai, u16 *pu16Dst, 
			 int bytelen, int whichbap)
{
	bytelen = (bytelen + 1) & (~1); // round up to even value
	if ( !do8bitIO ) 
		insw( ai->dev->base_addr+DATA0+whichbap, pu16Dst, bytelen>>1 );
	else
		insb( ai->dev->base_addr+DATA0+whichbap, pu16Dst, bytelen );
	return SUCCESS;
}

/* requires call to bap_setup() first */
static int bap_write(struct airo_info *ai, const u16 *pu16Src, 
		     int bytelen, int whichbap)
{
	bytelen = (bytelen + 1) & (~1); // round up to even value
	if ( !do8bitIO ) 
		outsw( ai->dev->base_addr+DATA0+whichbap, 
		       pu16Src, bytelen>>1 );
	else
		outsb( ai->dev->base_addr+DATA0+whichbap, pu16Src, bytelen );
	return SUCCESS;
}

static int PC4500_accessrid(struct airo_info *ai, u16 rid, u16 accmd)
{
	Cmd cmd; /* for issuing commands */
	Resp rsp; /* response from commands */
	u16 status;

	memset(&cmd, 0, sizeof(cmd));
	cmd.cmd = accmd;
	cmd.parm0 = rid;
	status = issuecommand(ai, &cmd, &rsp);
	if (status != 0) return status;
	if ( (rsp.status & 0x7F00) != 0) {
		return (accmd << 8) + (rsp.rsp0 & 0xFF);
	}
	return 0;
}

/*  Note, that we are using BAP1 which is also used by transmit, so
 *  we must get a lock. */
static int PC4500_readrid(struct airo_info *ai, u16 rid, void *pBuf, int len)
{
	u16 status;
        int flags;
        int rc = SUCCESS;

	spin_lock_irqsave(&ai->bap1_lock, flags);
	if ( (status = PC4500_accessrid(ai, rid, CMD_ACCESS)) != SUCCESS) {
                rc = status;
                goto done;
        }
	if (bap_setup(ai, rid, 0, BAP1) != SUCCESS) {
		rc = ERROR;
                goto done;
        }
	// read the rid length field
	bap_read(ai, pBuf, 2, BAP1);
	// length for remaining part of rid
	len = min(len, le16_to_cpu(*(u16*)pBuf)) - 2;
	
	if ( len <= 2 ) {
		printk( KERN_ERR 
			"airo: Rid %x has a length of %d which is too short\n",
			(int)rid,
			(int)len );
		rc = ERROR;
                goto done;
	}
	// read remainder of the rid
	if (bap_setup(ai, rid, 2, BAP1) != SUCCESS) {
                rc = ERROR;
                goto done;
        }
	rc = bap_read(ai, ((u16*)pBuf)+1, len, BAP1);
 done:
	spin_unlock_irqrestore(&ai->bap1_lock, flags);
	return rc;
}

/*  Note, that we are using BAP1 which is also used by transmit, so
 *  make sure this isnt called when a transmit is happening */
static int PC4500_writerid(struct airo_info *ai, u16 rid, 
			   const void *pBuf, int len)
{
	u16 status;
        int flags;
	int rc = SUCCESS;

	spin_lock_irqsave(&ai->bap1_lock, flags);
	// --- first access so that we can write the rid data
	if ( (status = PC4500_accessrid(ai, rid, CMD_ACCESS)) != 0) {
                rc = status;
                goto done;
        }
	// --- now write the rid data
	if (bap_setup(ai, rid, 0, BAP1) != SUCCESS) {
                rc = ERROR;
                goto done;
        }
	bap_write(ai, pBuf, len, BAP1);
	// ---now commit the rid data
	rc = PC4500_accessrid(ai, rid, 0x100|CMD_ACCESS);
 done:
	spin_unlock_irqrestore(&ai->bap1_lock, flags);
        return rc;
}

/* Allocates a FID to be used for transmitting packets.  We only use
   one for now. */
static u16 transmit_allocate(struct airo_info *ai, int lenPayload)
{
	Cmd cmd;
	Resp rsp;
	u16 txFid;
	u16 txControl;
        int flags;

	cmd.cmd = CMD_ALLOCATETX;
	cmd.parm0 = lenPayload;
	if (issuecommand(ai, &cmd, &rsp) != SUCCESS) return 0;
	if ( (rsp.status & 0xFF00) != 0) return 0;
	/* wait for the allocate event/indication
	 * It makes me kind of nervous that this can just sit here and spin,
	 * but in practice it only loops like four times. */
	while ( (IN4500(ai, EVSTAT) & EV_ALLOC) == 0) ;
	// get the allocated fid and acknowledge
	txFid = IN4500(ai, TXALLOCFID);
	OUT4500(ai, EVACK, EV_ALLOC);
  
	/*  The CARD is pretty cool since it converts the ethernet packet
	 *  into 802.11.  Also note that we don't release the FID since we
	 *  will be using the same one over and over again. */
	/*  We only have to setup the control once since we are not
	 *  releasing the fid. */
	txControl = cpu_to_le16(TXCTL_TXOK | TXCTL_TXEX | TXCTL_802_3
		| TXCTL_ETHERNET | TXCTL_NORELEASE);
	spin_lock_irqsave(&ai->bap1_lock, flags);
	if (bap_setup(ai, txFid, 0x0008, BAP1) != SUCCESS) {
		spin_unlock_irqrestore(&ai->bap1_lock, flags);
		return ERROR;
	}
	bap_write(ai, &txControl, sizeof(txControl), BAP1);
	spin_unlock_irqrestore(&ai->bap1_lock, flags);

	return txFid;
}

/* In general BAP1 is dedicated to transmiting packets.  However,
   since we need a BAP when accessing RIDs, we also use BAP1 for that.
   Make sure the BAP1 spinlock is held when this is called. */
static int transmit_802_3_packet(struct airo_info *ai, u16 txFid, 
				 char *pPacket, int len)
{
	u16 payloadLen;
	Cmd cmd;
	Resp rsp;
	
	if (len < 12) {
		printk( KERN_WARNING "Short packet %d\n", len );
		return ERROR;
	}
	
	// packet is destination[6], source[6], payload[len-12]
	// write the payload length and dst/src/payload
	if (bap_setup(ai, txFid, 0x0036, BAP1) != SUCCESS) return ERROR;
	/* The hardware addresses aren't counted as part of the payload, so
	 * we have to subtract the 12 bytes for the addresses off */
	payloadLen = cpu_to_le16(len-12);
	bap_write(ai, &payloadLen, sizeof(payloadLen),BAP1);
	bap_write(ai, (const u16*)pPacket, len, BAP1);
	// issue the transmit command
	memset( &cmd, 0, sizeof( cmd ) );
	cmd.cmd = CMD_TRANSMIT;
	cmd.parm0 = txFid;
	if (issuecommand(ai, &cmd, &rsp) != SUCCESS) return ERROR;
	if ( (rsp.status & 0xFF00) != 0) return ERROR;
	return SUCCESS;
}

/*
 *  This is the proc_fs routines.  It is a bit messier than I would
 *  like!  Feel free to clean it up!
 */

/*
 *  Unfortunately sometime between 2.0 and 2.2 the proc interface changed...
 *  Unfortunately I dont know when it was...
 *  Im guessing it is sometime around 0x20155...  Anybody know?
 */

static ssize_t proc_read( struct file *file,
			  char *buffer,
			  size_t len,
			  loff_t *offset);

static ssize_t proc_write( struct file *file,
			   const char *buffer,
			   size_t len,
			   loff_t *offset );
static int proc_close( struct inode *inode, struct file *file );

static int proc_stats_open( struct inode *inode, struct file *file );
static int proc_statsdelta_open( struct inode *inode, struct file *file );
static int proc_status_open( struct inode *inode, struct file *file );
static int proc_SSID_open( struct inode *inode, struct file *file );
static int proc_APList_open( struct inode *inode, struct file *file );
static int proc_config_open( struct inode *inode, struct file *file );
static int proc_wepkey_open( struct inode *inode, struct file *file );

static struct file_operations proc_statsdelta_ops = {
	read:           proc_read,
	open:           proc_statsdelta_open,
	release:        proc_close
};

static struct file_operations proc_stats_ops = {
	read:           proc_read,
	open:           proc_stats_open,
	release:        proc_close
};

static struct file_operations proc_status_ops = {
	read:            proc_read,
	open:            proc_status_open,
	release:         proc_close
};

static struct file_operations proc_SSID_ops = {
	read:          proc_read,
	write:         proc_write,
	open:          proc_SSID_open,
	release:       proc_close
};

static struct file_operations proc_APList_ops = {
	read:          proc_read,
	write:         proc_write,
	open:          proc_APList_open,
	release:       proc_close
};

static struct file_operations proc_config_ops = {
	read:          proc_read,
	write:         proc_write,
	open:          proc_config_open,
	release:       proc_close
};

static struct file_operations proc_wepkey_ops = {
	read:          proc_read,
	write:         proc_write,
	open:          proc_wepkey_open,
	release:       proc_close
};

static struct proc_dir_entry *airo_entry = 0;

struct proc_data {
	int release_buffer;
	int readlen;
	char *rbuffer;
	int writelen;
	int maxwritelen;
	char *wbuffer;
	void (*on_close) (struct inode *, struct file *);
};

static int setup_proc_entry( struct net_device *dev,
			     struct airo_info *apriv ) {
	struct proc_dir_entry *entry;
	/* First setup the device directory */
	apriv->proc_entry = create_proc_entry(dev->name,
					      S_IFDIR|airo_perm,
					      airo_entry);
        apriv->proc_entry->uid = proc_uid;
        apriv->proc_entry->gid = proc_gid;

	/* Setup the StatsDelta */
	entry = create_proc_entry("StatsDelta",
				  S_IFREG | (S_IRUGO&proc_perm),
				  apriv->proc_entry);
        entry->uid = proc_uid;
        entry->gid = proc_gid;
	entry->data = dev;
/*	This is what was needed right up to the last few versions
        of 2.3:
	entry->ops = &proc_inode_statsdelta_ops;
*/
	entry->proc_fops = &proc_statsdelta_ops;
	
	/* Setup the Stats */
	entry = create_proc_entry("Stats",
				  S_IFREG | (S_IRUGO&proc_perm),
				  apriv->proc_entry);
        entry->uid = proc_uid;
        entry->gid = proc_gid;
	entry->data = dev;
	entry->proc_fops = &proc_stats_ops;
	
	/* Setup the Status */
	entry = create_proc_entry("Status",
				  S_IFREG | (S_IRUGO&proc_perm),
				  apriv->proc_entry);
        entry->uid = proc_uid;
        entry->gid = proc_gid;
	entry->data = dev;
	entry->proc_fops = &proc_status_ops;
	
	/* Setup the Config */
	entry = create_proc_entry("Config",
				  S_IFREG | proc_perm,
				  apriv->proc_entry);
        entry->uid = proc_uid;
        entry->gid = proc_gid;
	entry->data = dev;
	entry->proc_fops = &proc_config_ops;

	/* Setup the SSID */
	entry = create_proc_entry("SSID",
				  S_IFREG | proc_perm,
				  apriv->proc_entry);
        entry->uid = proc_uid;
        entry->gid = proc_gid;
	entry->data = dev;
	entry->proc_fops = &proc_SSID_ops;

	/* Setup the APList */
	entry = create_proc_entry("APList",
				  S_IFREG | proc_perm,
				  apriv->proc_entry);
        entry->uid = proc_uid;
        entry->gid = proc_gid;
	entry->data = dev;
	entry->proc_fops = &proc_APList_ops;

	/* Setup the WepKey */
	entry = create_proc_entry("WepKey",
				  S_IFREG | proc_perm,
				  apriv->proc_entry);
        entry->uid = proc_uid;
        entry->gid = proc_gid;
	entry->data = dev;
	entry->proc_fops = &proc_wepkey_ops;

	return 0;
}

static int takedown_proc_entry( struct net_device *dev,
				struct airo_info *apriv ) {
	if ( !apriv->proc_entry->namelen ) return 0;
	remove_proc_entry("Stats",apriv->proc_entry);
	remove_proc_entry("StatsDelta",apriv->proc_entry);
	remove_proc_entry("Status",apriv->proc_entry);
	remove_proc_entry("Config",apriv->proc_entry);
	remove_proc_entry("SSID",apriv->proc_entry);
	remove_proc_entry("APList",apriv->proc_entry);
	remove_proc_entry("WepKey",apriv->proc_entry);
	remove_proc_entry(dev->name,airo_entry);
	return 0;
}

/*
 *  What we want from the proc_fs is to be able to efficiently read
 *  and write the configuration.  To do this, we want to read the
 *  configuration when the file is opened and write it when the file is
 *  closed.  So basically we allocate a read buffer at open and fill it
 *  with data, and allocate a write buffer and read it at close.
 */

/*
 *  The read routine is generic, it relies on the preallocated rbuffer
 *  to supply the data.
 */
static ssize_t proc_read( struct file *file,
			  char *buffer,
			  size_t len,
			  loff_t *offset )
{
	int i;
	int pos;
	struct proc_data *priv = (struct proc_data*)file->private_data;
	
	if( !priv->rbuffer ) return -EINVAL;
	
	pos = *offset;
	for( i = 0; i+pos < priv->readlen && i < len; i++ ) {
		if (put_user( priv->rbuffer[i+pos], buffer+i ))
			return -EFAULT;
	}
	*offset += i;
	return i;
}

/*
 *  The write routine is generic, it fills in a preallocated rbuffer
 *  to supply the data.
 */
static ssize_t proc_write( struct file *file,
			   const char *buffer,
			   size_t len,
			   loff_t *offset ) 
{
	int i;
	int pos;
	struct proc_data *priv = (struct proc_data*)file->private_data;
	
	if ( !priv->wbuffer ) {
		return -EINVAL;
	}
	
	pos = *offset;
	
	for( i = 0; i + pos <  priv->maxwritelen &&
		     i < len; i++ ) {
		if (get_user( priv->wbuffer[i+pos], buffer + i ))
			return -EFAULT;
	}
	if ( i+pos > priv->writelen ) priv->writelen = i+file->f_pos;
	*offset += i;
	return i;
}

static int proc_status_open( struct inode *inode, struct file *file ) {
	struct proc_data *data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *apriv = (struct airo_info *)dev->priv;
	CapabilityRid cap_rid;
	StatusRid status_rid;
	
	MOD_INC_USE_COUNT;
	
	dp = inode->u.generic_ip;
	
	if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
		return -ENOMEM;
	memset(file->private_data, 0, sizeof(struct proc_data));
	data = (struct proc_data *)file->private_data;
	if ((data->rbuffer = kmalloc( 2048, GFP_KERNEL )) == NULL) {
		kfree (file->private_data);
		return -ENOMEM;
	}
	
	readStatusRid(apriv, &status_rid);
	readCapabilityRid(apriv, &cap_rid);
	
	sprintf( data->rbuffer, "Mode: %x\n"
		 "Signal Strength: %d\n"
		 "Signal Quality: %d\n"
		 "SSID: %-.*s\n"
		 "AP: %-.16s\n"
		 "Freq: %d\n"
		 "BitRate: %dmbs\n"
		 "Driver Version: %s\n"
		 "Device: %s\nManufacturer: %s\nFirmware Version: %s\n"
		 "Radio type: %x\nCountry: %x\nHardware Version: %x\n"
		 "Software Version: %x\nSoftware Subversion: %x\n"
		 "Boot block version: %x\n",
		 (int)status_rid.mode,
		 (int)status_rid.normalizedSignalStrength,
		 (int)status_rid.signalQuality,
		 (int)status_rid.SSIDlen,
		 status_rid.SSID,
		 status_rid.apName,
		 (int)status_rid.channel,
		 (int)status_rid.currentXmitRate/2,
		 version,
		 cap_rid.prodName,
		 cap_rid.manName,
		 cap_rid.prodVer,
		 cap_rid.radioType,
		 cap_rid.country,
		 cap_rid.hardVer,
		 (int)cap_rid.softVer,
		 (int)cap_rid.softSubVer,
		 (int)cap_rid.bootBlockVer );
	data->readlen = strlen( data->rbuffer );
	return 0;
}

static int proc_stats_rid_open(struct inode*, struct file*, u16);
static int proc_statsdelta_open( struct inode *inode, 
				 struct file *file ) {
	if (file->f_mode&FMODE_WRITE) {
		return proc_stats_rid_open(inode, file, RID_STATSDELTACLEAR);
	}
	return proc_stats_rid_open(inode, file, RID_STATSDELTA);
}

static int proc_stats_open( struct inode *inode, struct file *file ) {
	return proc_stats_rid_open(inode, file, RID_STATS);
}

static int proc_stats_rid_open( struct inode *inode, 
				struct file *file,
				u16 rid ) {
	struct proc_data *data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *apriv = (struct airo_info *)dev->priv;
	StatsRid stats;
	int i, j;
	int *vals = stats.vals;
	MOD_INC_USE_COUNT;
	
	
	dp = inode->u.generic_ip;
	
	if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
		return -ENOMEM;
	memset(file->private_data, 0, sizeof(struct proc_data));
	data = (struct proc_data *)file->private_data;
	if ((data->rbuffer = kmalloc( 4096, GFP_KERNEL )) == NULL) {
		kfree (file->private_data);
		return -ENOMEM;
	}
	
	readStatsRid(apriv, &stats, rid);
	
        j = 0;
	for(i=0; (int)statsLabels[i]!=-1 && 
		    i*4<stats.len; i++){
		if (!statsLabels[i]) continue;
		if (j+strlen(statsLabels[i])+16>4096) {
			printk(KERN_WARNING
			       "airo: Potentially disasterous buffer overflow averted!\n");
			break;
		}
		j+=sprintf(data->rbuffer+j, "%s: %d\n", statsLabels[i], vals[i]);
	}
	if (i*4>=stats.len){
		printk(KERN_WARNING
		       "airo: Got a short rid\n");
	}
	data->readlen = j;
	return 0;
}

static int get_dec_u16( char *buffer, int *start, int limit ) {
	u16 value;
	int valid = 0;
	for( value = 0; buffer[*start] >= '0' &&
		     buffer[*start] <= '9' &&
		     *start < limit; (*start)++ ) {
		valid = 1;
		value *= 10;
		value += buffer[*start] - '0';
	}
	if ( !valid ) return -1;
	return value;
}

static void checkThrottle(ConfigRid *config) {
	int i;
/* Old hardware had a limit on encryption speed */
	if (config->authType != AUTH_OPEN && maxencrypt) {
		for(i=0; i<8; i++) {
			if (config->rates[i] > maxencrypt) {
				config->rates[i] = 0;
			}
		}
	}
}

static void proc_config_on_close( struct inode *inode, struct file *file ) {
	struct proc_data *data = file->private_data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *ai = (struct airo_info*)dev->priv;
	ConfigRid config;
	Resp rsp;
	char *line;
	int need_reset = 0;
	
	if ( !data->writelen ) return;
	dp = (struct proc_dir_entry *) inode->u.generic_ip;
	
	disable_MAC(ai);
	readConfigRid(ai, &config);

	line = data->wbuffer;
	while( line[0] ) {
/*** Mode processing */
		if ( !strncmp( line, "Mode: ", 6 ) ) {
			line += 6;
			config.rmode &= 0xfe00;
			if ( line[0] == 'a' ) {
				config.opmode = 0;
			} else {
				config.opmode = 1;
				if ( line[0] == 'r' )
					config.rmode |= RXMODE_RFMON | RXMODE_DISABLE_802_3_HEADER;
				else if ( line[0] == 'y' )
					config.rmode |= RXMODE_RFMON_ANYBSS | RXMODE_DISABLE_802_3_HEADER;
			}
			if (config.rmode & RXMODE_DISABLE_802_3_HEADER) {
				dev->type = ARPHRD_IEEE80211;
				dev->hard_header_parse = wll_header_parse;
			} else if (dev->type == ARPHRD_IEEE80211) {
				dev->type = ARPHRD_ETHER;
				dev->hard_header_parse = ai->header_parse;
				need_reset = 1;
			}
		}
		
/*** Radio status */
		else if (!strncmp(line,"Radio: ", 7)) {
			line += 7;
			if (!strncmp(line,"off",3)) {
				ai->flags |= FLAG_RADIO_OFF;
			} else {
				ai->flags &= ~FLAG_RADIO_OFF;
			}
		}
/*** NodeName processing */
		else if ( !strncmp( line, "NodeName: ", 10 ) ) {
			int j;
			
			line += 10;
			memset( config.nodeName, 0, 16 );
/* Do the name, assume a space between the mode and node name */
			for( j = 0; j < 16 && line[j] != '\n'; j++ ) {
				config.nodeName[j] = line[j];
			}
		} 
		
/*** PowerMode processing */
		else if ( !strncmp( line, "PowerMode: ", 11 ) ) {
			line += 11;
			if ( !strncmp( line, "PSPCAM", 6 ) ) {
				config.powerSaveMode = POWERSAVE_PSPCAM;
			} else if ( !strncmp( line, "PSP", 3 ) ) {
				config.powerSaveMode = POWERSAVE_PSP;
			} else {
				config.powerSaveMode = POWERSAVE_CAM;
			}	
		} else if ( !strncmp( line, "DataRates: ", 11 ) ) {
			int v, i = 0, k = 0; /* i is index into line, 
						k is index to rates */
			
			line += 11;
			while((v = get_dec_u16(line, &i, 3))!=-1) {
				config.rates[k++] = (u8)v;
				line += i + 1;
				i = 0;
			}
		} else if ( !strncmp( line, "Channel: ", 9 ) ) {
			int v, i = 0;
			line += 9;
			v = get_dec_u16(line, &i, i+3);
			if ( v != -1 ) 
				config.channelSet = (u16)v;
		} else if ( !strncmp( line, "XmitPower: ", 11 ) ) {
			int v, i = 0;
			line += 11;
			v = get_dec_u16(line, &i, i+3);
			if ( v != -1 ) config.txPower = (u16)v;
		} else if ( !strncmp( line, "WEP: ", 5 ) ) {
			line += 5;
			switch( line[0] ) {
			case 's':
				config.authType = (u16)AUTH_SHAREDKEY;
				break;
			case 'e':
				config.authType = (u16)AUTH_ENCRYPT;
				break;
			default:
				config.authType = (u16)AUTH_OPEN;
				break;
			}
		} else if ( !strncmp( line, "LongRetryLimit: ", 16 ) ) {
			int v, i = 0;
			
			line += 16;
			v = get_dec_u16(line, &i, 3);
			v = (v<0) ? 0 : ((v>255) ? 255 : v);
			config.longRetryLimit = (u16)v;
		} else if ( !strncmp( line, "ShortRetryLimit: ", 17 ) ) {
			int v, i = 0;
			
			line += 17;
			v = get_dec_u16(line, &i, 3);
			v = (v<0) ? 0 : ((v>255) ? 255 : v);
			config.shortRetryLimit = (u16)v;
		} else if ( !strncmp( line, "RTSThreshold: ", 14 ) ) {
			int v, i = 0;
			
			line += 14;
			v = get_dec_u16(line, &i, 4);
			v = (v<0) ? 0 : ((v>2312) ? 2312 : v);
			config.rtsThres = (u16)v;
		} else if ( !strncmp( line, "TXMSDULifetime: ", 16 ) ) {
			int v, i = 0;
			
			line += 16;
			v = get_dec_u16(line, &i, 5);
			v = (v<0) ? 0 : v;
			config.txLifetime = (u16)v;
		} else if ( !strncmp( line, "RXMSDULifetime: ", 16 ) ) {
			int v, i = 0;
			
			line += 16;
			v = get_dec_u16(line, &i, 5);
			v = (v<0) ? 0 : v;
			config.rxLifetime = (u16)v;
		} else if ( !strncmp( line, "TXDiversity: ", 13 ) ) {
			config.txDiversity = 
				(line[13]=='l') ? 1 :
				((line[13]=='r')? 2: 3);
		} else if ( !strncmp( line, "RXDiversity: ", 13 ) ) {
			config.rxDiversity = 
				(line[13]=='l') ? 1 :
				((line[13]=='r')? 2: 3);
		} else if ( !strncmp( line, "FragThreshold: ", 15 ) ) {
			int v, i = 0;
			
			line += 15;
			v = get_dec_u16(line, &i, 4);
			v = (v<256) ? 256 : ((v>2312) ? 2312 : v);
			v = v & 0xfffe; /* Make sure its even */
			config.fragThresh = (u16)v;
		} else if (!strncmp(line, "Modulation: ", 12)) {
			line += 12;
			switch(*line) {
			case 'd':  config.modulation=MOD_DEFAULT; break;
			case 'c':  config.modulation=MOD_CCK; break;
			case 'm':  config.modulation=MOD_MOK; break;
			default:
				printk( KERN_WARNING "airo: Unknown modulation\n" );
			}
		} else {
			printk( KERN_WARNING "Couldn't figure out %s\n", line );
		}
		while( line[0] && line[0] != '\n' ) line++;
		if ( line[0] ) line++;
	}
	checkThrottle(&config);
	ai->config = config;
	if (need_reset) {
		APListRid APList_rid;
		SsidRid SSID_rid;

		readAPListRid(ai, &APList_rid);
		readSsidRid(ai, &SSID_rid);
		reset_airo_card(dev);
		writeSsidRid(ai, &SSID_rid);
		writeAPListRid(ai, &APList_rid);
	}
	writeConfigRid(ai, &config);
	enable_MAC(ai, &rsp);
}

static int proc_config_open( struct inode *inode, struct file *file ) {
	struct proc_data *data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *ai = (struct airo_info*)dev->priv;
	ConfigRid config;
	int i;
	
	MOD_INC_USE_COUNT;
	
	dp = (struct proc_dir_entry *) inode->u.generic_ip;
	
	if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
		return -ENOMEM;
	memset(file->private_data, 0, sizeof(struct proc_data));
	data = (struct proc_data *)file->private_data;
	if ((data->rbuffer = kmalloc( 2048, GFP_KERNEL )) == NULL) {
		kfree (file->private_data);
		return -ENOMEM;
	}
	if ((data->wbuffer = kmalloc( 2048, GFP_KERNEL )) == NULL) {
		kfree (data->rbuffer);
		kfree (file->private_data);
		return -ENOMEM;
	}
	memset( data->wbuffer, 0, 2048 );
	data->maxwritelen = 2048;
	data->on_close = proc_config_on_close;
	
	readConfigRid(ai, &config);
	
	i = sprintf( data->rbuffer, 
		     "Mode: %s\n"
		     "Radio: %s\n"
		     "NodeName: %-16s\n"
		     "PowerMode: %s\n"
		     "DataRates: %d %d %d %d %d %d %d %d\n"
		     "Channel: %d\n"
		     "XmitPower: %d\n",
		     config.opmode == 0 ? "adhoc" : 
		     config.opmode == 1 ? "ESS" :
		     config.opmode == 2 ? "AP" : 
		     config.opmode == 3 ? "AP RPTR" : "Error",
		     ai->flags&FLAG_RADIO_OFF ? "off" : "on",
		     config.nodeName,
		     config.powerSaveMode == 0 ? "CAM" :
		     config.powerSaveMode == 1 ? "PSP" :
		     config.powerSaveMode == 2 ? "PSPCAM" : "Error",
		     (int)config.rates[0],
		     (int)config.rates[1],
		     (int)config.rates[2],
		     (int)config.rates[3],
		     (int)config.rates[4],
		     (int)config.rates[5],
		     (int)config.rates[6],
		     (int)config.rates[7],
		     (int)config.channelSet,
		     (int)config.txPower
		);
	sprintf( data->rbuffer + i,
		 "LongRetryLimit: %d\n"
		 "ShortRetryLimit: %d\n"
		 "RTSThreshold: %d\n"
		 "TXMSDULifetime: %d\n"
		 "RXMSDULifetime: %d\n"
		 "TXDiversity: %s\n"
		 "RXDiversity: %s\n"
		 "FragThreshold: %d\n"
		 "WEP: %s\n"
		 "Modulation: %s\n",
		 (int)config.longRetryLimit,
		 (int)config.shortRetryLimit,
		 (int)config.rtsThres,
		 (int)config.txLifetime,
		 (int)config.rxLifetime,
		 config.txDiversity == 1 ? "left" :
		 config.txDiversity == 2 ? "right" : "both",
		 config.rxDiversity == 1 ? "left" :
		 config.rxDiversity == 2 ? "right" : "both",
		 (int)config.fragThresh,
		 config.authType == AUTH_ENCRYPT ? "encrypt" :
		 config.authType == AUTH_SHAREDKEY ? "shared" : "open",
		 config.modulation == 0 ? "default" :
		 config.modulation == MOD_CCK ? "cck" :
		 config.modulation == MOD_MOK ? "mok" : "error"
		);
	data->readlen = strlen( data->rbuffer );
	return 0;
}

static void proc_SSID_on_close( struct inode *inode, struct file *file ) {
	struct proc_data *data = (struct proc_data *)file->private_data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *ai = (struct airo_info*)dev->priv;
	SsidRid SSID_rid;
	int i;
	int offset = 0;
	
	if ( !data->writelen ) return;
	
	memset( &SSID_rid, 0, sizeof( SSID_rid ) );
	
	for( i = 0; i < 3; i++ ) {
		int j;
		for( j = 0; j+offset < data->writelen && j < 32 &&
			     data->wbuffer[offset+j] != '\n'; j++ ) {
			SSID_rid.ssids[i].ssid[j] = data->wbuffer[offset+j];
		}
		if ( j == 0 ) break;
		SSID_rid.ssids[i].len = j;
		offset += j;
		while( data->wbuffer[offset] != '\n' && 
		       offset < data->writelen ) offset++;
		offset++;
	}
	writeSsidRid(ai, &SSID_rid);
}

inline static u8 hexVal(char c) {
	if (c>='0' && c<='9') return c -= '0';
	if (c>='a' && c<='f') return c -= 'a'-10;
	if (c>='A' && c<='F') return c -= 'A'-10;
	return 0;
}

static void proc_APList_on_close( struct inode *inode, struct file *file ) {
	struct proc_data *data = (struct proc_data *)file->private_data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *ai = (struct airo_info*)dev->priv;
	APListRid APList_rid;
	int i;
	
	if ( !data->writelen ) return;
	
	memset( &APList_rid, 0, sizeof(APList_rid) );
	APList_rid.len = sizeof(APList_rid);
	
	for( i = 0; i < 4 && data->writelen >= (i+1)*6*3; i++ ) {
		int j;
		for( j = 0; j < 6*3 && data->wbuffer[j+i*6*3]; j++ ) {
			switch(j%3) {
			case 0:
				APList_rid.ap[i][j/3]=
					hexVal(data->wbuffer[j+i*6*3])<<4;
				break;
			case 1:
				APList_rid.ap[i][j/3]|=
					hexVal(data->wbuffer[j+i*6*3]);
				break;
			}
		}
	}
	writeAPListRid(ai, &APList_rid);
}

/* This function wraps PC4500_writerid with a MAC disable */
static int do_writerid( struct airo_info *ai, u16 rid, const void *rid_data,
			int len ) {
	int rc;
	Resp rsp;
	
	disable_MAC(ai);
	rc = PC4500_writerid(ai, rid, rid_data, len);
	enable_MAC(ai, &rsp);
	return rc;
}

/* Returns the length of the key at the index.  If index == 0xffff
 * the index of the transmit key is returned.  If the key doesn't exist,
 * -1 will be returned.
 */
static int get_wep_key(struct airo_info *ai, u16 index) {
	WepKeyRid wkr;
	int rc;
	u16 lastindex;

	rc = readWepKeyRid(ai, &wkr, 1);
	if (rc == SUCCESS) do {
		lastindex = wkr.kindex;
		if (wkr.kindex == index) {
			if (index == 0xffff) {
				return wkr.mac[0];
			}
			return wkr.klen;
		}
		readWepKeyRid(ai, &wkr, 0);
	} while(lastindex != wkr.kindex);
	return -1;
}

static int set_wep_key(struct airo_info *ai, u16 index,
		       const char *key, u16 keylen, int perm ) {
	static const unsigned char macaddr[6] = { 0x01, 0, 0, 0, 0, 0 };
	WepKeyRid wkr;

	memset(&wkr, 0, sizeof(wkr));
	if (keylen == 0) {
// We are selecting which key to use
		wkr.len = sizeof(wkr);
		wkr.kindex = 0xffff;
		wkr.mac[0] = (char)index;
		if (perm) printk(KERN_INFO "Setting transmit key to %d\n", index);
		if (perm) ai->defindex = (char)index;
	} else {
// We are actually setting the key
		wkr.len = sizeof(wkr);
		wkr.kindex = index;
		wkr.klen = keylen;
		memcpy( wkr.key, key, keylen );
		memcpy( wkr.mac, macaddr, 6 );
		printk(KERN_INFO "Setting key %d\n", index);
	}
	
	writeWepKeyRid(ai, &wkr, perm);
	return 0;
}

static void proc_wepkey_on_close( struct inode *inode, struct file *file ) {
	struct proc_data *data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *ai = (struct airo_info*)dev->priv;
	int i;
	char key[16];
	u16 index = 0;
	int j = 0;

	memset(key, 0, sizeof(key));
	
	dp = (struct proc_dir_entry *) inode->u.generic_ip;
	data = (struct proc_data *)file->private_data;
	if ( !data->writelen ) return;
	
	if (data->wbuffer[0] >= '0' && data->wbuffer[0] <= '3' &&
	    (data->wbuffer[1] == ' ' || data->wbuffer[1] == '\n')) {
		index = data->wbuffer[0] - '0';
		if (data->wbuffer[1] == '\n') {
			set_wep_key(ai, index, 0, 0, 1);
			return;
		}
		j = 2;
	} else {
		printk(KERN_ERR "airo:  WepKey passed invalid key index\n");
		return;
	}

	for( i = 0; i < 16*3 && data->wbuffer[i+j]; i++ ) {
		switch(i%3) {
		case 0:
			key[i/3] = hexVal(data->wbuffer[i+j])<<4;
			break;
		case 1:
			key[i/3] |= hexVal(data->wbuffer[i+j]);
			break;
		}
	}
	set_wep_key(ai, index, key, i/3, 1);
}

static int proc_wepkey_open( struct inode *inode, struct file *file ) {
	struct proc_data *data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *ai = (struct airo_info*)dev->priv;
	char *ptr;
	WepKeyRid wkr;
	u16 lastindex;
	int j=0;
	int rc;
	
	MOD_INC_USE_COUNT;
	
	dp = (struct proc_dir_entry *) inode->u.generic_ip;
	
	if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
		return -ENOMEM;
	memset(file->private_data, 0, sizeof(struct proc_data));
	memset(&wkr, 0, sizeof(wkr));
	data = (struct proc_data *)file->private_data;
	if ((data->rbuffer = kmalloc( 180, GFP_KERNEL )) == NULL) {
		kfree (file->private_data);
		return -ENOMEM;
	}
	memset(data->rbuffer, 0, 180);
	data->writelen = 0;
	data->maxwritelen = 80;
	if ((data->wbuffer = kmalloc( 80, GFP_KERNEL )) == NULL) {
		kfree (data->rbuffer);
		kfree (file->private_data);
		return -ENOMEM;
	}
	memset( data->wbuffer, 0, 80 );
	data->on_close = proc_wepkey_on_close;
	
	ptr = data->rbuffer;
	strcpy(ptr, "No wep keys\n");
	rc = readWepKeyRid(ai, &wkr, 1);
	if (rc == SUCCESS) do {
		lastindex = wkr.kindex;
		if (wkr.kindex == 0xffff) {
			j += sprintf(ptr+j, "Tx key = %d\n",
				     (int)wkr.mac[0]);
		} else {
			j += sprintf(ptr+j, "Key %d set with length = %d\n",
				     (int)wkr.kindex, (int)wkr.klen);
		}
		readWepKeyRid(ai, &wkr, 0);
	} while((lastindex != wkr.kindex) && (j < 180-30));

	data->readlen = strlen( data->rbuffer );
	return 0;
}

static int proc_SSID_open( struct inode *inode, struct file *file ) {
	struct proc_data *data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *ai = (struct airo_info*)dev->priv;
	int i;
	char *ptr;
	SsidRid SSID_rid;

	MOD_INC_USE_COUNT;
	
	dp = (struct proc_dir_entry *) inode->u.generic_ip;
	
	if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
		return -ENOMEM;
	memset(file->private_data, 0, sizeof(struct proc_data));
	data = (struct proc_data *)file->private_data;
	if ((data->rbuffer = kmalloc( 104, GFP_KERNEL )) == NULL) {
		kfree (file->private_data);
		return -ENOMEM;
	}
	data->writelen = 0;
	data->maxwritelen = 33*3;
	if ((data->wbuffer = kmalloc( 33*3, GFP_KERNEL )) == NULL) {
		kfree (data->rbuffer);
		kfree (file->private_data);
		return -ENOMEM;
	}
	memset( data->wbuffer, 0, 33*3 );
	data->on_close = proc_SSID_on_close;
	
	readSsidRid(ai, &SSID_rid);
	ptr = data->rbuffer;
	for( i = 0; i < 3; i++ ) {
		int j;
		if ( !SSID_rid.ssids[i].len ) break;
		for( j = 0; j < 32 && 
			     j < SSID_rid.ssids[i].len && 
			     SSID_rid.ssids[i].ssid[j]; j++ ) {
			*ptr++ = SSID_rid.ssids[i].ssid[j]; 
		}
		*ptr++ = '\n';
	}
	*ptr = '\0';
	data->readlen = strlen( data->rbuffer );
	return 0;
}

static int proc_APList_open( struct inode *inode, struct file *file ) {
	struct proc_data *data;
	struct proc_dir_entry *dp = inode->u.generic_ip;
	struct net_device *dev = dp->data;
	struct airo_info *ai = (struct airo_info*)dev->priv;
	int i;
	char *ptr;
	APListRid APList_rid;

	MOD_INC_USE_COUNT;
	
	dp = (struct proc_dir_entry *) inode->u.generic_ip;
	
	if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
		return -ENOMEM;
	memset(file->private_data, 0, sizeof(struct proc_data));
	data = (struct proc_data *)file->private_data;
	if ((data->rbuffer = kmalloc( 104, GFP_KERNEL )) == NULL) {
		kfree (file->private_data);
		return -ENOMEM;
	}
	data->writelen = 0;
	data->maxwritelen = 4*6*3;
	if ((data->wbuffer = kmalloc( data->maxwritelen, GFP_KERNEL )) == NULL) {
		kfree (data->rbuffer);
		kfree (file->private_data);
		return -ENOMEM;
	}
	memset( data->wbuffer, 0, data->maxwritelen );
	data->on_close = proc_APList_on_close;
	
	readAPListRid(ai, &APList_rid);
	ptr = data->rbuffer;
	for( i = 0; i < 4; i++ ) {
// We end when we find a zero MAC
		if ( !*(int*)APList_rid.ap[i] &&
		     !*(int*)&APList_rid.ap[i][2]) break;
		ptr += sprintf(ptr, "%02x:%02x:%02x:%02x:%02x:%02x\n",
			       (int)APList_rid.ap[i][0],
			       (int)APList_rid.ap[i][1],
			       (int)APList_rid.ap[i][2],
			       (int)APList_rid.ap[i][3],
			       (int)APList_rid.ap[i][4],
			       (int)APList_rid.ap[i][5]);
	}
	if (i==0) ptr += sprintf(ptr, "Not using specific APs\n");

	*ptr = '\0';
	data->readlen = strlen( data->rbuffer );
	return 0;
}

static int proc_close( struct inode *inode, struct file *file ) 
{
	struct proc_data *data = (struct proc_data *)file->private_data;
	if ( data->on_close != NULL ) data->on_close( inode, file );
	MOD_DEC_USE_COUNT;
	if ( data->rbuffer ) kfree( data->rbuffer );
	if ( data->wbuffer ) kfree( data->wbuffer );
	kfree( data );
	return 0;
}

static struct net_device_list {
	struct net_device *dev;
	struct net_device_list *next;
} *airo_devices = 0;

/* Since the card doesnt automatically switch to the right WEP mode,
   we will make it do it.  If the card isn't associated, every secs we
   will switch WEP modes to see if that will help.  If the card is
   associated we will check every minute to see if anything has
   changed. */
static void timer_func( u_long data ) {
	struct net_device *dev = (struct net_device*)data;
	struct airo_info *apriv = (struct airo_info *)dev->priv;
	u16 linkstat = IN4500(apriv, LINKSTAT);
	
	if (linkstat != 0x400 ) {
/* We don't have a link so try changing the authtype */
		ConfigRid config = apriv->config;

		switch(apriv->authtype) {
		case AUTH_ENCRYPT:
/* So drop to OPEN */
			config.authType = AUTH_OPEN;
			apriv->authtype = AUTH_OPEN;
			break;
		case AUTH_SHAREDKEY:
			if (apriv->keyindex < auto_wep) {
				set_wep_key(apriv, apriv->keyindex, 0, 0, 0);
				config.authType = AUTH_SHAREDKEY;
				apriv->authtype = AUTH_SHAREDKEY;
				apriv->keyindex++;
			} else {
			        /* Drop to ENCRYPT */
				apriv->keyindex = 0;
				set_wep_key(apriv, apriv->defindex, 0, 0, 0);
				config.authType = AUTH_ENCRYPT;
				apriv->authtype = AUTH_ENCRYPT;
			}
			break;
		default:  /* We'll escalate to SHAREDKEY */
			config.authType = AUTH_SHAREDKEY;
			apriv->authtype = AUTH_SHAREDKEY;
		}
		checkThrottle(&config);
		writeConfigRid(apriv, &config);

/* Schedule check to see if the change worked */
		apriv->timer.expires = RUN_AT(HZ*3);
		add_timer(&apriv->timer);
	}
}

static int add_airo_dev( struct net_device *dev ) {
	struct net_device_list *node = kmalloc( sizeof( *node ), GFP_KERNEL );
	if ( !node )
		return -ENOMEM;

	if ( auto_wep ) {
		struct airo_info *apriv=dev->priv;
		struct timer_list *timer = &apriv->timer;
			
		timer->function = timer_func;
		timer->data = (u_long)dev;
		init_timer(timer);
		apriv->authtype = AUTH_SHAREDKEY;
	}
		
	node->dev = dev;
	node->next = airo_devices;
	airo_devices = node;

	return 0;
}

static void del_airo_dev( struct net_device *dev ) {
	struct net_device_list **p = &airo_devices;
	while( *p && ( (*p)->dev != dev ) )
		p = &(*p)->next;
	if ( *p && (*p)->dev == dev )
		*p = (*p)->next; 
}

#ifdef CONFIG_PCI
static int __devinit airo_pci_probe(struct pci_dev *pdev, 
				    const struct pci_device_id *pent)
{
	pdev->driver_data = init_airo_card(pdev->irq, 
					   pdev->resource[2].start, 0);
	if (!pdev->driver_data) {
		return -ENODEV;
	}
	return 0;
}

static void __devexit airo_pci_remove(struct pci_dev *pdev)
{
	stop_airo_card(pdev->driver_data, 1);
}

#endif

static int __init airo_init_module( void )
{
	int i, rc = 0, have_isa_dev = 0;
	
	airo_entry = create_proc_entry("aironet",
				       S_IFDIR | airo_perm,
				       proc_root_driver);
        airo_entry->uid = proc_uid;
        airo_entry->gid = proc_gid;
	
	for( i = 0; i < 4 && io[i] && irq[i]; i++ ) {
		printk( KERN_INFO 
			"airo:  Trying to configure ISA adapter at irq=%d io=0x%x\n",
			irq[i], io[i] );
		if (init_airo_card( irq[i], io[i], 0 ))
			have_isa_dev = 1;
	}
	
#ifdef CONFIG_PCI
	printk( KERN_INFO "airo:  Probing for PCI adapters\n" );
	rc = pci_module_init(&airo_driver);
	printk( KERN_INFO "airo:  Finished probing for PCI adapters\n" );
#endif

	/* arguably, we should clean up and error exit if pci_module_init
	 * fails with an error other than -ENODEV, instead of proceeding,
	 * if ISA devs are present.
	 */
	if (have_isa_dev)
		return 0;
	if (rc && (rc != -ENODEV))
		return rc;
	return 0;
}

static void __exit airo_cleanup_module( void )
{
	while( airo_devices ) {
		printk( KERN_INFO "airo: Unregistering %s\n", airo_devices->dev->name );
		stop_airo_card( airo_devices->dev, 1 );
	}
	remove_proc_entry("aironet", proc_root_driver);
}

#ifdef WIRELESS_EXT
/*
 * Initial Wireless Extension code for Aironet driver by :
 *	Jean Tourrilhes <jt@hpl.hp.com> - HPL - 17 November 00
 */
#ifndef IW_ENCODE_NOKEY
#define IW_ENCODE_NOKEY         0x0800  /* Key is write only, so not present */
#define IW_ENCODE_MODE  (IW_ENCODE_DISABLED | IW_ENCODE_RESTRICTED | IW_ENCODE_OPEN)
#endif /* IW_ENCODE_NOKEY */
#endif /* WIRELESS_EXT */

/*
 * This defines the configuration part of the Wireless Extensions
 * Note : irq and spinlock protection will occur in the subroutines
 *
 * TODO :
 *	o Check input value more carefully and fill correct values in range
 *	o Implement : POWER, SPY, APLIST
 *	o Optimise when adapter is closed (aggregate changes, commit later)
 *	o Test and shakeout the bugs (if any)
 *
 * Jean II
 *
 * Javier Achirica did a great job of merging code from the unnamed CISCO
 * developer that added support for flashing the card.
 */
static int airo_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
	int rc = 0;
#ifdef WIRELESS_EXT
	struct airo_info *local = (struct airo_info*) dev->priv;
	struct iwreq *wrq = (struct iwreq *) rq;
	ConfigRid config;		/* Configuration info */
	CapabilityRid cap_rid;		/* Card capability info */
	StatusRid status_rid;		/* Card status info */
	int i;

#ifdef CISCO_EXT
	if (cmd != SIOCGIWPRIV && cmd != AIROIOCTL && cmd != AIROIDIFC)
#endif /* CISCO_EXT */
	{
		/* If the command read some stuff, we better get it out of
		 * the card first... */
		if(IW_IS_GET(cmd))
			readStatusRid(local, &status_rid);
		if(IW_IS_GET(cmd) || (cmd == SIOCSIWRATE) || (cmd == SIOCSIWENCODE))
			readCapabilityRid(local, &cap_rid);
		/* Get config in all cases, because SET will just modify it */
		readConfigRid(local, &config);
	}
#endif /* WIRELESS_EXT */

	switch (cmd) {
#ifdef WIRELESS_EXT
		// Get name
	case SIOCGIWNAME:
		strcpy(wrq->u.name, "IEEE 802.11-DS");
		break;

		// Set frequency/channel
	case SIOCSIWFREQ:
		/* If setting by frequency, convert to a channel */
		if((wrq->u.freq.e == 1) &&
		   (wrq->u.freq.m >= (int) 2.412e8) &&
		   (wrq->u.freq.m <= (int) 2.487e8)) {
			int f = wrq->u.freq.m / 100000;
			int c = 0;
			while((c < 14) && (f != frequency_list[c]))
				c++;
			/* Hack to fall through... */
			wrq->u.freq.e = 0;
			wrq->u.freq.m = c + 1;
		}
		/* Setting by channel number */
		if((wrq->u.freq.m > 1000) || (wrq->u.freq.e > 0))
			rc = -EOPNOTSUPP;
		else {
			int channel = wrq->u.freq.m;
			/* We should do a better check than that,
			 * based on the card capability !!! */
			if((channel < 1) || (channel > 16)) {
				printk(KERN_DEBUG "%s: New channel value of %d is invalid!\n", dev->name, wrq->u.freq.m);
				rc = -EINVAL;
			} else {
				/* Yes ! We can set it !!! */
				config.channelSet = (u16)(channel - 1);
				local->need_commit = 1;
			}
		}
		break;

		// Get frequency/channel
	case SIOCGIWFREQ:
#ifdef WEXT_USECHANNELS
		wrq->u.freq.m = ((int)status_rid.channel) + 1;
		wrq->u.freq.e = 0;
#else
		{
			int f = (int)status_rid.channel;
			wrq->u.freq.m = frequency_list[f] * 100000;
			wrq->u.freq.e = 1;
		}
#endif
		break;

		// Set desired network name (ESSID)
	case SIOCSIWESSID:
		if (wrq->u.data.pointer) {
			char	essid[IW_ESSID_MAX_SIZE + 1];
			SsidRid SSID_rid;		/* SSIDs */

			/* Reload the list of current SSID */
			readSsidRid(local, &SSID_rid);

			/* Check if we asked for `any' */
			if(wrq->u.data.flags == 0) {
				/* Just send an empty SSID list */
				memset(&SSID_rid, 0, sizeof(SSID_rid));
			} else {
				int	index = (wrq->u.data.flags &
						 IW_ENCODE_INDEX) - 1;

				/* Check the size of the string */
				if(wrq->u.data.length > IW_ESSID_MAX_SIZE+1) {
					rc = -E2BIG;
					break;
				}
				/* Check if index is valid */
				if((index < 0) || (index >= 4)) {
					rc = -EINVAL;
					break;
				}

				/* Set the SSID */
				memset(essid, 0, sizeof(essid));
				copy_from_user(essid,
					       wrq->u.data.pointer,
					       wrq->u.data.length);
				memcpy(SSID_rid.ssids[index].ssid, essid,
				       sizeof(essid) - 1);
				SSID_rid.ssids[index].len = wrq->u.data.length - 1;
			}
			/* Write it to the card */
			writeSsidRid(local, &SSID_rid);
		}
		break;

		// Get current network name (ESSID)
	case SIOCGIWESSID:
		if (wrq->u.data.pointer) {
			char essid[IW_ESSID_MAX_SIZE + 1];

			/* Note : if wrq->u.data.flags != 0, we should
			 * get the relevant SSID from the SSID list... */

			/* Get the current SSID */
			memcpy(essid, status_rid.SSID, status_rid.SSIDlen);
			essid[status_rid.SSIDlen] = '\0';
			/* If none, we may want to get the one that was set */

			/* Push it out ! */
			wrq->u.data.length = strlen(essid) + 1;
			wrq->u.data.flags = 1; /* active */
			if (copy_to_user(wrq->u.data.pointer, essid, sizeof(essid)))
				rc = -EFAULT;
		}
		break;

	case SIOCSIWAP:
		if (wrq->u.ap_addr.sa_family != ARPHRD_ETHER)
			rc = -EINVAL;
		else {
			APListRid APList_rid;

			memset(&APList_rid, 0, sizeof(APList_rid));
			APList_rid.len = sizeof(APList_rid);
			memcpy(APList_rid.ap[0], wrq->u.ap_addr.sa_data, 6);
			writeAPListRid(local, &APList_rid);
			local->need_commit = 1;
		}
		break;

		// Get current Access Point (BSSID)
	case SIOCGIWAP:
		/* Tentative. This seems to work, wow, I'm lucky !!! */
		memcpy(wrq->u.ap_addr.sa_data, status_rid.bssid[0], 6);
		wrq->u.ap_addr.sa_family = ARPHRD_ETHER;
		break;

		// Set desired station name
	case SIOCSIWNICKN:
		if (wrq->u.data.pointer) {
			char	name[16 + 1];

			/* Check the size of the string */
			if(wrq->u.data.length > 16 + 1) {
				rc = -E2BIG;
				break;
			}
			memset(name, 0, sizeof(name));
			copy_from_user(name, wrq->u.data.pointer, wrq->u.data.length);
			memcpy(config.nodeName, name, 16);
			local->need_commit = 1;
		}
		break;

		// Get current station name
	case SIOCGIWNICKN:
		if (wrq->u.data.pointer) {
			char name[IW_ESSID_MAX_SIZE + 1];

			strncpy(name, config.nodeName, 16);
			name[16] = '\0';
			wrq->u.data.length = strlen(name) + 1;
			if (copy_to_user(wrq->u.data.pointer, name, sizeof(name)))
				rc = -EFAULT;
		}
		break;

		// Set the desired bit-rate
	case SIOCSIWRATE:
	{
		/* First : get a valid bit rate value */
		u8	brate = 0;
		int	i;

		/* Which type of value ? */
		if((wrq->u.bitrate.value < 8) &&
		   (wrq->u.bitrate.value >= 0)) {
			/* Setting by rate index */
			/* Find value in the magic rate table */
			brate = cap_rid.supportedRates[wrq->u.bitrate.value];
		} else {
			/* Setting by frequency value */
			u8	normvalue = (u8) (wrq->u.bitrate.value/500000);

			/* Check if rate is valid */
			for(i = 0 ; i < 8 ; i++) {
				if(normvalue == cap_rid.supportedRates[i]) {
					brate = normvalue;
					break;
				}
			}
		}
		/* -1 designed the max rate (mostly auto mode) */
		if(wrq->u.bitrate.value == -1) {
			/* Get the highest available rate */
			for(i = 0 ; i < 8 ; i++) {
				if(cap_rid.supportedRates[i] == 0)
					break;
			}
			if(i != 0)
				brate = cap_rid.supportedRates[i - 1];
		}
		/* Check that it is valid */
		if(brate == 0) {
			rc = -EINVAL;
			break;
		}

		/* Now, check if we want a fixed or auto value */
		if(wrq->u.bitrate.fixed == 0) {
			/* Fill all the rates up to this max rate */
			memset(config.rates, 0, 8);
			for(i = 0 ; i < 8 ; i++) {
				config.rates[i] = cap_rid.supportedRates[i];
				if(config.rates[i] == brate)
					break;
			}
			local->need_commit = 1;
		} else {
			/* Fixed mode */
			/* One rate, fixed */
			memset(config.rates, 0, 8);
			config.rates[0] = brate;
			local->need_commit = 1;
		}
		break;
	}

	// Get the current bit-rate
	case SIOCGIWRATE:
	{
		int brate = status_rid.currentXmitRate;
		wrq->u.bitrate.value = brate * 500000;
		/* If more than one rate, set auto */
		wrq->u.rts.fixed = (config.rates[1] == 0);
	}
	break;

	// Set the desired RTS threshold
	case SIOCSIWRTS:
	{
		int rthr = wrq->u.rts.value;
		if(wrq->u.rts.disabled)
			rthr = 2312;
		if((rthr < 0) || (rthr > 2312)) {
			rc = -EINVAL;
		} else {
			config.rtsThres = rthr;
			local->need_commit = 1;
		}
	}
	break;

	// Get the current RTS threshold
	case SIOCGIWRTS:
		wrq->u.rts.value = config.rtsThres;
		wrq->u.rts.disabled = (wrq->u.rts.value >= 2312);
		wrq->u.rts.fixed = 1;
		break;

		// Set the desired fragmentation threshold
	case SIOCSIWFRAG:
	{
		int fthr = wrq->u.frag.value;
		if(wrq->u.frag.disabled)
			fthr = 2312;
		if((fthr < 256) || (fthr > 2312)) {
			rc = -EINVAL;
		} else {
			fthr &= ~0x1;	/* Get an even value */
			config.fragThresh = (u16)fthr;
			local->need_commit = 1;
		}
	}
	break;

	// Get the current fragmentation threshold
	case SIOCGIWFRAG:
		wrq->u.frag.value = config.fragThresh;
		wrq->u.frag.disabled = (wrq->u.frag.value >= 2312);
		wrq->u.frag.fixed = 1;
		break;

		// Set mode of operation
	case SIOCSIWMODE:
		switch(wrq->u.mode) {
		case IW_MODE_ADHOC:
			config.opmode = MODE_STA_IBSS;
			local->need_commit = 1;
			break;
		case IW_MODE_INFRA:
			config.opmode = MODE_STA_ESS;
			local->need_commit = 1;
			break;
		case IW_MODE_MASTER:
			config.opmode = MODE_AP;
			local->need_commit = 1;
			break;
		case IW_MODE_REPEAT:
			config.opmode = MODE_AP_RPTR;
			local->need_commit = 1;
			break;
		default:
			rc = -EINVAL;
		}
		break;

		// Get mode of operation
	case SIOCGIWMODE:
		/* If not managed, assume it's ad-hoc */
		switch (config.opmode & 0xFF) {
		case MODE_STA_ESS:
			wrq->u.mode = IW_MODE_INFRA;
			break;
		case MODE_AP:
			wrq->u.mode = IW_MODE_MASTER;
			break;
		case MODE_AP_RPTR:
			wrq->u.mode = IW_MODE_REPEAT;
			break;
		default:
			wrq->u.mode = IW_MODE_ADHOC;
		}
		break;

		// Set WEP keys and mode
	case SIOCSIWENCODE:
		/* Is WEP supported ? */
		/* Older firmware doesn't support this...
		if(!(cap_rid.softCap & 2)) {
			rc = -EOPNOTSUPP;
			break;
		} */
		/* Basic checking: do we have a key to set ? */
		if (wrq->u.encoding.pointer != (caddr_t) 0) {
			wep_key_t key;
			int index = (wrq->u.encoding.flags & IW_ENCODE_INDEX) - 1;
			int current_index = get_wep_key(local, 0xffff);
			/* Check the size of the key */
			if (wrq->u.encoding.length > MAX_KEY_SIZE) {
				rc = -EINVAL;
				break;
			}
			/* Check the index (none -> use current) */
			if ((index < 0) || (index >= MAX_KEYS))
				index = current_index;
			/* Set the length */
			if (wrq->u.encoding.length > MIN_KEY_SIZE)
				key.len = MAX_KEY_SIZE;
			else
				if (wrq->u.encoding.length > 0)
					key.len = MIN_KEY_SIZE;
				else
					/* Disable the key */
					key.len = 0;
			/* Check if the key is not marked as invalid */
			if(!(wrq->u.encoding.flags & IW_ENCODE_NOKEY)) {
				/* Cleanup */
				memset(key.key, 0, MAX_KEY_SIZE);
				/* Copy the key in the driver */
				if(copy_from_user(key.key,
						  wrq->u.encoding.pointer,
						  wrq->u.encoding.length)) {
					key.len = 0;
					rc = -EFAULT;
					break;
				}
				/* Send the key to the card */
				set_wep_key(local, index, key.key,
					    key.len, 1);
			}
			/* WE specify that if a valid key is set, encryption
			 * should be enabled (user may turn it off later)
			 * This is also how "iwconfig ethX key on" works */
			if((index == current_index) && (key.len > 0) &&
			   (config.authType == AUTH_OPEN)) {
				config.authType = AUTH_ENCRYPT;
				local->need_commit = 1;
			}
		} else {
			/* Do we want to just set the transmit key index ? */
			int index = (wrq->u.encoding.flags & IW_ENCODE_INDEX) - 1;
			if ((index >= 0) && (index < MAX_KEYS)) {
				set_wep_key(local, index, 0, 0, 1);
			} else
				/* Don't complain if only change the mode */
				if(!wrq->u.encoding.flags & IW_ENCODE_MODE) {
					rc = -EINVAL;
					break;
				}
		}
		/* Read the flags */
		if(wrq->u.encoding.flags & IW_ENCODE_DISABLED)
			config.authType = AUTH_OPEN;	// disable encryption
		if(wrq->u.encoding.flags & IW_ENCODE_RESTRICTED)
			config.authType = AUTH_SHAREDKEY;	// Only Both
		if(wrq->u.encoding.flags & IW_ENCODE_OPEN)
			config.authType = AUTH_ENCRYPT;	// Only Wep
		/* Commit the changes if needed */
		if(wrq->u.encoding.flags & IW_ENCODE_MODE)
			local->need_commit = 1;
		break;

		// Get the WEP keys and mode
	case SIOCGIWENCODE:
		/* Is it supported ? */
		if(!(cap_rid.softCap & 2)) {
			rc = -EOPNOTSUPP;
			break;
		}
		// Only super-user can see WEP key
		if (!capable(CAP_NET_ADMIN)) {
			rc = -EPERM;
			break;
		}

		// Basic checking...
		if (wrq->u.encoding.pointer != (caddr_t) 0) {
			char zeros[16];
			int index = (wrq->u.encoding.flags & IW_ENCODE_INDEX) - 1;

			memset(zeros,0, sizeof(zeros));
			/* Check encryption mode */
			wrq->u.encoding.flags = IW_ENCODE_NOKEY;
			/* Is WEP enabled ??? */
			switch(config.authType)	{
			case AUTH_ENCRYPT:
				wrq->u.encoding.flags |= IW_ENCODE_OPEN;
				break;
			case AUTH_SHAREDKEY:
				wrq->u.encoding.flags |= IW_ENCODE_RESTRICTED;
				break;
			default:
			case AUTH_OPEN:
				wrq->u.encoding.flags |= IW_ENCODE_DISABLED;
				break;
			}

			/* Which key do we want ? -1 -> tx index */
			if((index < 0) || (index >= MAX_KEYS))
				index = get_wep_key(local, 0xffff);
			wrq->u.encoding.flags |= index + 1;
			/* Copy the key to the user buffer */
			wrq->u.encoding.length = get_wep_key(local, index);
			if (wrq->u.encoding.length > 16) {
				wrq->u.encoding.length=0;
			}

			if(copy_to_user(wrq->u.encoding.pointer, zeros,
					wrq->u.encoding.length))
				rc = -EFAULT;
		}
		break;

#if WIRELESS_EXT > 9
		// Get the current Tx-Power
	case SIOCGIWTXPOW:
		wrq->u.txpower.value = config.txPower;
		wrq->u.txpower.fixed = 1;	/* No power control */
		wrq->u.txpower.disabled = (local->flags & FLAG_RADIO_OFF);
		wrq->u.txpower.flags = IW_TXPOW_MWATT;
		break;
	case SIOCSIWTXPOW:
		if (wrq->u.txpower.disabled) {
			local->flags |= FLAG_RADIO_OFF;
			local->need_commit = 1;
			break;
		}
		if (wrq->u.txpower.flags != IW_TXPOW_MWATT) {
			rc = -EINVAL;
			break;
		}
		local->flags &= ~FLAG_RADIO_OFF;
		rc = -EINVAL;
		for (i = 0; cap_rid.txPowerLevels[i] && (i < 8); i++)
			if ((wrq->u.txpower.value==cap_rid.txPowerLevels[i])) {
				config.txPower = wrq->u.txpower.value;
				local->need_commit = 1;
				rc = 0;
				break;
			}
		break;
#endif /* WIRELESS_EXT > 9 */

#if WIRELESS_EXT > 10
	case SIOCGIWRETRY:
		wrq->u.retry.disabled = 0;
		if ((wrq->u.retry.flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME)
			wrq->u.retry.value = (int)config.txLifetime * 1024;
		else {
			wrq->u.retry.value = (int)config.shortRetryLimit;
			wrq->u.retry.flags = IW_RETRY_LIMIT;
		}
		break;

	case SIOCSIWRETRY: 
		if (wrq->u.retry.disabled) {
			config.shortRetryLimit = 0;
			config.longRetryLimit = 0;
			config.txLifetime = 0;
			local->need_commit = 1;
			break;
		}
		if ((wrq->u.retry.flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME) {
			config.txLifetime = (wrq->u.retry.value + 500) / 1024;
			local->need_commit = 1;
		} else if ((wrq->u.retry.flags & IW_RETRY_TYPE) == IW_RETRY_LIMIT) {
			config.shortRetryLimit = config.longRetryLimit = wrq->u.retry.value;
			local->need_commit = 1;
		}
		break;
#endif /* WIRELESS_EXT > 10 */

		// Get range of parameters
	case SIOCGIWRANGE:
		if (wrq->u.data.pointer) {
			struct iw_range range;
			int		i;
			int		k;

			wrq->u.data.length = sizeof(range);
			/* Should adapt depending on max rate */
			range.throughput = 1.6 * 1024 * 1024;
			range.min_nwid = 0x0000;
			range.max_nwid = 0x0000;
			range.num_channels = 14;
			/* Should be based on cap_rid.country to give only
			 * what the current card support */
			k = 0;
			for(i = 0; i < 14; i++) {
				range.freq[k].i = i + 1; /* List index */
				range.freq[k].m = frequency_list[i] * 100000;
				range.freq[k++].e = 1;	/* Values in table in MHz -> * 10^5 * 10 */
			}
			range.num_frequency = k;

			/* Hum... Should put the right values there */
			range.max_qual.qual = 10;
			range.max_qual.level = 100;
			range.max_qual.noise = 0;
			range.sensitivity = 65535;

			for(i = 0 ; i < 8 ; i++) {
				range.bitrate[i] = cap_rid.supportedRates[i] * 500000;
				if(range.bitrate[i] == 0)
					break;
			}
			range.num_bitrates = i;

			range.min_rts = 0;
			range.max_rts = 2312;
			range.min_frag = 256;
			range.max_frag = 2312;

			if(cap_rid.softCap & 2) {
				// WEP: RC4 40 bits
				range.encoding_size[0] = 5;
				// RC4 ~128 bits
				if (cap_rid.softCap & 0x100) {
					range.encoding_size[1] = 13;
					range.num_encoding_sizes = 2;
				} else
					range.num_encoding_sizes = 1;
				range.max_encoding_tokens = 4;	// 4 keys
			} else {
				range.num_encoding_sizes = 0;
				range.max_encoding_tokens = 0;
			}
#if WIRELESS_EXT > 9
			range.min_pmp = 0;
			range.max_pmp = 5000000;	/* 5 secs */
			range.min_pmt = 0;
			range.max_pmt = 65535 * 1024;	/* ??? */
			range.pmp_flags = IW_POWER_PERIOD;
			range.pmt_flags = IW_POWER_TIMEOUT;
			range.pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT | IW_POWER_ALL_R;

			/* Transmit Power - values are in mW */
			for(i = 0 ; i < 8 ; i++) {
				range.txpower[i] = cap_rid.txPowerLevels[i];
				if(range.txpower[i] == 0)
					break;
			}
			range.num_txpower = i;
			range.txpower_capa = IW_TXPOW_MWATT;
#endif /* WIRELESS_EXT > 9 */
#if WIRELESS_EXT > 10
			range.we_version_source = 11;
			range.we_version_compiled = WIRELESS_EXT;
			range.retry_capa = IW_RETRY_LIMIT | IW_RETRY_LIFETIME;
			range.retry_flags = IW_RETRY_LIMIT;
			range.r_time_flags = IW_RETRY_LIFETIME;
			range.min_retry = 1;
			range.max_retry = 65535;
			range.min_r_time = 1024;
			range.max_r_time = 65535 * 1024;
#endif /* WIRELESS_EXT > 10 */

			if (copy_to_user(wrq->u.data.pointer, &range, sizeof(struct iw_range)))
				rc = -EFAULT;
		}
		break;

	case SIOCGIWPOWER:
	{
		int mode = config.powerSaveMode;
		if ((wrq->u.power.disabled = (mode == POWERSAVE_CAM)))
			break;
		if ((wrq->u.power.flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
			wrq->u.power.value = (int)config.fastListenDelay * 1024;
			wrq->u.power.flags = IW_POWER_TIMEOUT;
		} else {
			wrq->u.power.value = (int)config.fastListenInterval * 1024;
			wrq->u.power.flags = IW_POWER_PERIOD;
		}
		if ((config.rmode & 0xFF) == RXMODE_ADDR)
			wrq->u.power.flags |= IW_POWER_UNICAST_R;
		else
			wrq->u.power.flags |= IW_POWER_ALL_R;
	}
	break;

	case SIOCSIWPOWER: 
		if (wrq->u.power.disabled) {
			if ((config.rmode & 0xFF) >= RXMODE_RFMON) {
				rc = -EINVAL;
				break;
			}
			config.powerSaveMode = POWERSAVE_CAM;
			config.rmode &= 0xFF00;
			config.rmode |= RXMODE_BC_MC_ADDR;
			local->need_commit = 1;
			break;
		}
		if ((wrq->u.power.flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
			config.fastListenDelay = (wrq->u.power.value + 500) / 1024;
			config.powerSaveMode = POWERSAVE_PSPCAM;
			local->need_commit = 1;
		} else if ((wrq->u.power.flags & IW_POWER_TYPE) == IW_POWER_PERIOD) {
			config.fastListenInterval = config.listenInterval = (wrq->u.power.value + 500) / 1024;
			config.powerSaveMode = POWERSAVE_PSPCAM;
			local->need_commit = 1;
		}
		switch (wrq->u.power.flags & IW_POWER_MODE) {
		case IW_POWER_UNICAST_R:
			if ((config.rmode & 0xFF) >= RXMODE_RFMON) {
				rc = -EINVAL;
				break;
			}
			config.rmode &= 0xFF00;
			config.rmode |= RXMODE_ADDR;
			local->need_commit = 1;
			break;
		case IW_POWER_ALL_R:
			if ((config.rmode & 0xFF) >= RXMODE_RFMON) {
				rc = -EINVAL;
				break;
			}
			config.rmode &= 0xFF00;
			config.rmode |= RXMODE_BC_MC_ADDR;
			local->need_commit = 1;
		case IW_POWER_ON:
			break;
		default:
			rc = -EINVAL;
		}
		break;

	case SIOCGIWSENS:
		wrq->u.sens.value = config.rssiThreshold;
		wrq->u.sens.disabled = (wrq->u.sens.value == 0);
		wrq->u.sens.fixed = 1;
		break;

	case SIOCSIWSENS:
		config.rssiThreshold = wrq->u.sens.disabled ? RSSI_DEFAULT : wrq->u.sens.value;
		local->need_commit = 1;
		break;

	case SIOCGIWAPLIST:
		if (wrq->u.data.pointer) {
			int i;
			struct sockaddr s[4];

			for (i = 0; i < 4; i++) {
				memcpy(s[i].sa_data, status_rid.bssid[i], 6);
				s[i].sa_family = ARPHRD_ETHER;
			}
			wrq->u.data.length = 4;
			if (copy_to_user(wrq->u.data.pointer, &s, sizeof(s)))
				rc = -EFAULT;
		}
		break;

#ifdef WIRELESS_SPY
		// Set the spy list
	case SIOCSIWSPY:
		if (wrq->u.data.length > IW_MAX_SPY)
		{
			rc = -E2BIG;
			break;
		}
		local->spy_number = wrq->u.data.length;
		if (local->spy_number > 0)
		{
			struct sockaddr address[IW_MAX_SPY];
			int i;

			if (copy_from_user(address, wrq->u.data.pointer,
					   sizeof(struct sockaddr) * local->spy_number)) {
				rc = -EFAULT;
				break;
			}
			for (i=0; i<local->spy_number; i++)
				memcpy(local->spy_address[i], address[i].sa_data, 6);
			memset(local->spy_stat, 0, sizeof(struct iw_quality) * IW_MAX_SPY);
		}
		break;

		// Get the spy list
	case SIOCGIWSPY:
		wrq->u.data.length = local->spy_number;
		if ((local->spy_number > 0) && (wrq->u.data.pointer))
		{
			struct sockaddr address[IW_MAX_SPY];
			int i;
			rc = verify_area(VERIFY_WRITE, wrq->u.data.pointer, (sizeof(struct iw_quality)+sizeof(struct sockaddr)) * IW_MAX_SPY);
			if (rc)
				break;
			for (i=0; i<local->spy_number; i++)
			{
				memcpy(address[i].sa_data, local->spy_address[i], 6);
				address[i].sa_family = AF_UNIX;
			}
			copy_to_user(wrq->u.data.pointer, address, sizeof(struct sockaddr) * local->spy_number);
			copy_to_user(wrq->u.data.pointer + (sizeof(struct sockaddr)*local->spy_number), local->spy_stat, sizeof(struct iw_quality) * local->spy_number);
			for (i=0; i<local->spy_number; i++)
				local->spy_stat[i].updated = 0;
		}
		break;
#endif /* WIRELESS_SPY */

#ifdef CISCO_EXT
	case SIOCGIWPRIV:
		if(wrq->u.data.pointer)
		{
			struct iw_priv_args   priv[] =
			{ /* cmd, set_args, get_args, name */
				{ AIROIOCTL, IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | sizeof (aironet_ioctl), IW_PRIV_TYPE_BYTE | 2047, "airoioctl" },
				{ AIROIDIFC, IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | sizeof (aironet_ioctl), IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "airoidifc" },
			};

			/* Set the number of ioctl available */
			wrq->u.data.length = 2;

			/* Copy structure to the user buffer */
			if(copy_to_user(wrq->u.data.pointer, (u_char *) priv,
					sizeof(priv)))
				rc = -EFAULT;
		}
		break;
#endif /* CISCO_EXT */
#endif /* WIRELESS_EXT */

#ifdef CISCO_EXT
	case AIROIDIFC:
	{
		int val = AIROMAGIC;
		aironet_ioctl com;
		if (copy_from_user(&com,rq->ifr_data,sizeof(com)))
			rc = -EFAULT;
		else if (copy_to_user(com.data,(char *)&val,sizeof(val)))
			rc = -EFAULT;
	}
	break;
  
	case AIROIOCTL:
		/* Get the command struct and hand it off for evaluation by 
		 * the proper subfunction
		 */
	{
		aironet_ioctl com;
		copy_from_user(&com,rq->ifr_data,sizeof(com));

		/* Seperate R/W functions bracket legality here
		 */
		if ( com.command <= AIROGSTATSD32 )
			rc = readrids(dev,&com);
		else if ( com.command >= AIROPCAP && com.command <= AIROPLEAPUSR )
			rc = writerids(dev,&com);
		else if ( com.command >= AIROFLSHRST && com.command <= AIRORESTART )
			rc = flashcard(dev,&com);
		else
			rc = -EINVAL;      /* Bad command in ioctl */
	}
	break;
#endif /* CISCO_EXT */

	// All other calls are currently unsupported
	default:
		rc = -EOPNOTSUPP;
	}

#ifdef WIRELESS_EXT
	/* Some of the "SET" function may have modified some of the
	 * parameters. It's now time to commit them in the card */
	if(local->need_commit) {
		/* A classical optimisation here is to not commit any change
		 * if the card is not "opened". This is what we do in
		 * wvlan_cs (see for details).
		 * For that, we would need to have the config RID saved in
		 * the airo_info struct and make sure to not re-read it if
		 * local->need_commit != 0. Then, you need to patch "open"
		 * to do the final commit of all parameters...
		 * Jean II */
		Resp rsp;

		disable_MAC(local);
		local->config = config;	/* ???? config is local !!! */
		checkThrottle(&config);
		writeConfigRid(local, &config);
		enable_MAC(local, &rsp);

		local->need_commit = 0;
	}
#endif /* WIRELESS_EXT */

	return(rc);
}

#ifdef WIRELESS_EXT
/*
 * Get the Wireless stats out of the driver
 * Note : irq and spinlock protection will occur in the subroutines
 *
 * TODO :
 *	o Check if work in Ad-Hoc mode (otherwise, use SPY, as in wvlan_cs)
 *	o Find the noise level
 *	o Convert values to dBm
 *	o Fill out discard.misc with something interesting
 *
 * Jean
 */
struct iw_statistics *airo_get_wireless_stats(struct net_device *dev)
{
	struct airo_info *local = (struct airo_info*) dev->priv;
	StatusRid status_rid;
	StatsRid stats_rid;
	int *vals = stats_rid.vals;

	/* Get stats out of the card */
	readStatusRid(local, &status_rid);
	readStatsRid(local, &stats_rid, RID_STATS);

	/* The status */
	local->wstats.status = status_rid.mode;

	/* Signal quality and co. But where is the noise level ??? */
	local->wstats.qual.qual = status_rid.signalQuality;
	local->wstats.qual.level = status_rid.normalizedSignalStrength;
	local->wstats.qual.noise = 0;
	local->wstats.qual.updated = 3;

	/* Packets discarded in the wireless adapter due to wireless
	 * specific problems */
	local->wstats.discard.nwid = vals[56] + vals[57] + vals[58];/* SSID Mismatch */
	local->wstats.discard.code = vals[6];/* RxWepErr */
	local->wstats.discard.misc = vals[1] + vals[2] + vals[3] + vals[4] + vals[30] + vals[32];
	return (&local->wstats);
}
#endif /* WIRELESS_EXT */

#ifdef CISCO_EXT
/*
 * This just translates from driver IOCTL codes to the command codes to 
 * feed to the radio's host interface. Things can be added/deleted 
 * as needed.  This represents the READ side of control I/O to 
 * the card
 */
static int readrids(struct net_device *dev, aironet_ioctl *comp) {
	unsigned short ridcode;
	unsigned char iobuf[2048]; 

	switch(comp->command)
	{
	case AIROGCAP:      ridcode = RID_CAPABILITIES; break;
	case AIROGCFG:      ridcode = RID_CONFIG;       break;
	case AIROGSLIST:    ridcode = RID_SSID;         break;
	case AIROGVLIST:    ridcode = RID_APLIST;       break;
	case AIROGDRVNAM:   ridcode = RID_DRVNAME;      break;
	case AIROGEHTENC:   ridcode = RID_ETHERENCAP;   break;
	case AIROGWEPKTMP:  ridcode = RID_WEP_TEMP;
		/* Only super-user can read WEP keys */
		if (!capable(CAP_NET_ADMIN))
			return -EPERM;
		break;
	case AIROGWEPKNV:   ridcode = RID_WEP_PERM;
		/* Only super-user can read WEP keys */
		if (!capable(CAP_NET_ADMIN))
			return -EPERM;
		break;
	case AIROGSTAT:     ridcode = RID_STATUS;       break;
	case AIROGSTATSD32: ridcode = RID_STATSDELTA;   break;
	case AIROGSTATSC32: ridcode = RID_STATS;        break;
	default:
		return -EINVAL;  
		break;
	}

	PC4500_readrid((struct airo_info *)dev->priv,ridcode,iobuf,sizeof(iobuf));
	/* get the count of bytes in the rid  docs say 1st 2 bytes is it.
	 * then return it to the user 
	 * 9/22/2000 Honor user given length
	 */

	if (copy_to_user(comp->data, iobuf, min (comp->len, sizeof(iobuf))))
		return -EFAULT;
	return 0;
}

/*
 * Danger Will Robinson write the rids here
 */

static int writerids(struct net_device *dev, aironet_ioctl *comp) {
	int  ridcode;
	Resp      rsp;
	static int (* writer)(struct airo_info *, u16 rid, const void *, int);
	unsigned char iobuf[2048]; 

	/* Only super-user can write RIDs */
	if (!capable(CAP_NET_ADMIN))
		return -EPERM;

	ridcode = 0;
	writer = do_writerid;

	switch(comp->command)
	{
	case AIROPSIDS:     ridcode = RID_SSID;         break;
	case AIROPCAP:      ridcode = RID_CAPABILITIES; break;
	case AIROPAPLIST:   ridcode = RID_APLIST;       break;
	case AIROPCFG:      ridcode = RID_CONFIG;       break;
	case AIROPWEPKEYNV: ridcode = RID_WEP_PERM;     break;
	case AIROPLEAPUSR:  ridcode = RID_LEAPUSERNAME; break;
	case AIROPLEAPPWD:  ridcode = RID_LEAPPASSWORD; break;
	case AIROPWEPKEY:   ridcode = RID_WEP_TEMP; writer = PC4500_writerid;
		break;

		/* this is not really a rid but a command given to the card 
		 * same with MAC off
		 */
	case AIROPMACON:
		if (enable_MAC(dev->priv, &rsp) != 0)
			return -EIO;
		return 0;

		/* 
		 * Evidently this code in the airo driver does not get a symbol
		 * as disable_MAC. it's probably so short the compiler does not gen one.
		 */
	case AIROPMACOFF:
		disable_MAC(dev->priv);
		return 0;

		/* This command merely clears the counts does not actually store any data
		 * only reads rid. But as it changes the cards state, I put it in the
		 * writerid routines.
		 */
	case AIROPSTCLR:
		ridcode = RID_STATSDELTACLEAR;

		PC4500_readrid(dev->priv,ridcode,iobuf,sizeof(iobuf));

		if (copy_to_user(comp->data,iobuf,min(comp->len,sizeof(iobuf))))
			return -EFAULT;
		return 0;

	default:
		return -EOPNOTSUPP;	/* Blarg! */
	}
	if(comp->len > sizeof(iobuf))
		return -EINVAL;

	copy_from_user(iobuf,comp->data,comp->len);
	if((*writer)((struct airo_info *)dev->priv, ridcode, iobuf,comp->len))
		return -EIO;
	return 0;
}

/*****************************************************************************
 * Ancillary flash / mod functions much black magic lurkes here              *
 *****************************************************************************
 */

/* 
 * Flash command switch table
 */

int flashcard(struct net_device *dev, aironet_ioctl *comp) {
	int z;
	int cmdreset(struct airo_info *);
	int setflashmode(struct airo_info *);
	int flashgchar(struct airo_info *,int,int);
	int flashpchar(struct airo_info *,int,int);
	int flashputbuf(struct airo_info *, unsigned short *);
	int flashrestart(struct airo_info *,struct net_device *);
	unsigned short * flashbuffer;

	/* Only super-user can modify flash */
	if (!capable(CAP_NET_ADMIN))
		return -EPERM;

	switch(comp->command)
	{
	case AIROFLSHRST:
		return cmdreset((struct airo_info *)dev->priv);

	case AIROFLSHSTFL:
		return setflashmode((struct airo_info *)dev->priv);

	case AIROFLSHGCHR: /* Get char from aux */
		if(comp->len != sizeof(int))
			return -EINVAL;
		copy_from_user(&z,comp->data,comp->len);
		return flashgchar((struct airo_info *)dev->priv,z,8000);

	case AIROFLSHPCHR: /* Send char to card. */
		if(comp->len != sizeof(int))
			return -EINVAL;
		copy_from_user(&z,comp->data,comp->len);
		return flashpchar((struct airo_info *)dev->priv,z,8000);

	case AIROFLPUTBUF: /* Send 32k to card */
		if(comp->len > FLASHSIZE)
			return -EINVAL;
		if ((flashbuffer = kmalloc (FLASHSIZE, GFP_KERNEL)) == NULL)
			return -ENOMEM;
		if(copy_from_user(flashbuffer,comp->data,comp->len)) {
			kfree (flashbuffer);
			return -EINVAL;
		}

		flashputbuf((struct airo_info *)dev->priv,flashbuffer);
		kfree (flashbuffer);
		return 0;

	case AIRORESTART:
		if(flashrestart((struct airo_info *)dev->priv,dev))
			return -EIO;
		return 0;
	}
	return -EINVAL;
}

#define FLASH_COMMAND  0x7e7e

/* 
 * STEP 1)
 * Disable MAC and do soft reset on 
 * card. 
 */

int cmdreset(struct airo_info *ai) {
	int flags;

	disable_MAC(ai);

	spin_lock_irqsave(&ai->cmd_lock, flags);
	if(!waitbusy (ai)){
		printk(KERN_INFO "Waitbusy hang before RESET\n");
		return -EBUSY;
	}
    
	OUT4500(ai,COMMAND,CMD_SOFTRESET);

	set_current_state (TASK_UNINTERRUPTIBLE);
	schedule_timeout (HZ);          /* WAS 600 12/7/00 */

	if(!waitbusy (ai)){
		printk(KERN_INFO "Waitbusy hang AFTER RESET\n");
		return -EBUSY;
	}
	spin_unlock_irqrestore(&ai->cmd_lock, flags);
	return 0;
}

/* STEP 2)
 * Put the card in legendary flash 
 * mode
 */

int setflashmode (struct airo_info *ai) {
	int flags;

	spin_lock_irqsave(&ai->cmd_lock, flags);
	OUT4500(ai, SWS0, FLASH_COMMAND);
	OUT4500(ai, SWS1, FLASH_COMMAND);
	OUT4500(ai, SWS0, FLASH_COMMAND);
	OUT4500(ai, COMMAND,0x10);
	set_current_state (TASK_UNINTERRUPTIBLE);
	schedule_timeout (HZ/2); /* 500ms delay */
	spin_unlock_irqrestore(&ai->cmd_lock, flags);
  
	if(!waitbusy(ai)) {
		printk(KERN_INFO "Waitbusy hang after setflash mode\n");
		return -EIO;
	}
	return 0;
}

/* Put character to SWS0 wait for dwelltime 
 * x 50us for  echo . 
 */

int flashpchar(struct airo_info *ai,int byte,int dwelltime) {
	int echo;
	int waittime;

	byte |= 0x8000;

	if(dwelltime == 0 )
		dwelltime = 200;
  
	waittime=dwelltime;

	/* Wait for busy bit d15 to go false indicating buffer empty */
	while ((IN4500 (ai, SWS0) & 0x8000) && waittime > 0) {
		udelay (50);
		waittime -= 50;
	}

	/* timeout for busy clear wait */
	if(waittime <= 0 ){
		printk(KERN_INFO "flash putchar busywait timeout! \n");
		return -EBUSY;
	}

	/* Port is clear now write byte and wait for it to echo back */
	do {
		OUT4500(ai,SWS0,byte);
		udelay(50);
		dwelltime -= 50;
		echo = IN4500(ai,SWS1);
	} while (dwelltime >= 0 && echo != byte);

	OUT4500(ai,SWS1,0);

	return (echo == byte) ? 0 : -EIO;
}

/*
 * Get a character from the card matching matchbyte
 * Step 3)
 */
int flashgchar(struct airo_info *ai,int matchbyte,int dwelltime){
	int           rchar;
	unsigned char rbyte=0;

	do {
		rchar = IN4500(ai,SWS1);
    
		if(dwelltime && !(0x8000 & rchar)){
			dwelltime -= 10;
			mdelay(10);
			continue;
		}
		rbyte = 0xff & rchar;

		if( (rbyte == matchbyte) && (0x8000 & rchar) ){
			OUT4500(ai,SWS1,0);
			return 0;
		}
		if( rbyte == 0x81 || rbyte == 0x82 || rbyte == 0x83 || rbyte == 0x1a || 0xffff == rchar)
			break;
		OUT4500(ai,SWS1,0);

	}while(dwelltime > 0);
	return -EIO;
}

/* 
 * Transfer 32k of firmware data from user buffer to our buffer and 
 * send to the card 
 */

int flashputbuf(struct airo_info *ai, unsigned short *bufp){
	int            nwords;

	/* Write stuff */
	OUT4500(ai,AUXPAGE,0x100);
	OUT4500(ai,AUXOFF,0);

	for(nwords=0;nwords != FLASHSIZE / 2;nwords++){
		OUT4500(ai,AUXDATA,bufp[nwords] & 0xffff);
	}
  
	OUT4500(ai,SWS0,0x8000);

	return 0;
}

/*
 *
 */
int flashrestart(struct airo_info *ai,struct net_device *dev){
	int    i,status;

	set_current_state (TASK_UNINTERRUPTIBLE);
	schedule_timeout (HZ);          /* Added 12/7/00 */
	status = setup_card(ai, dev->dev_addr,&((struct airo_info*)dev->priv)->config);

	for( i = 0; i < MAX_FIDS; i++ ) {
		ai->fids[i] = transmit_allocate( ai, 2312 );
	}

	set_current_state (TASK_UNINTERRUPTIBLE);
	schedule_timeout (HZ);          /* Added 12/7/00 */
	return status;
}
#endif /* CISCO_EXT */

/*
    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.

    In addition:

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
    3. The name of the author may not be used to endorse or promote
       products derived from this software without specific prior written
       permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
    IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.    
*/

module_init(airo_init_module);
module_exit(airo_cleanup_module);