aboutsummaryrefslogtreecommitdiffstats
path: root/kernel/trace/trace_workqueue.c
blob: cc2d2faa7d9e037734f1e4c11e87418c4a3a5400 (plain) (blame)
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
/*
 * Workqueue statistical tracer.
 *
 * Copyright (C) 2008 Frederic Weisbecker <fweisbec@gmail.com>
 *
 */


#include <trace/events/workqueue.h>
#include <linux/list.h>
#include <linux/percpu.h>
#include <linux/slab.h>
#include <linux/kref.h>
#include "trace_stat.h"
#include "trace.h"


/* A cpu workqueue thread */
struct cpu_workqueue_stats {
	struct list_head            list;
	struct kref                 kref;
	int		            cpu;
	pid_t			    pid;
/* Can be inserted from interrupt or user context, need to be atomic */
	atomic_t	            inserted;
/*
 *  Don't need to be atomic, works are serialized in a single workqueue thread
 *  on a single CPU.
 */
	unsigned int		    executed;
};

/* List of workqueue threads on one cpu */
struct workqueue_global_stats {
	struct list_head	list;
	spinlock_t		lock;
};

/* Don't need a global lock because allocated before the workqueues, and
 * never freed.
 */
static DEFINE_PER_CPU(struct workqueue_global_stats, all_workqueue_stat);
#define workqueue_cpu_stat(cpu) (&per_cpu(all_workqueue_stat, cpu))

static void cpu_workqueue_stat_free(struct kref *kref)
{
	kfree(container_of(kref, struct cpu_workqueue_stats, kref));
}

/* Insertion of a work */
static void
probe_workqueue_insertion(struct task_struct *wq_thread,
			  struct work_struct *work)
{
	int cpu = cpumask_first(&wq_thread->cpus_allowed);
	struct cpu_workqueue_stats *node;
	unsigned long flags;

	spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
	list_for_each_entry(node, &workqueue_cpu_stat(cpu)->list, list) {
		if (node->pid == wq_thread->pid) {
			atomic_inc(&node->inserted);
			goto found;
		}
	}
	pr_debug("trace_workqueue: entry not found\n");
found:
	spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
}

/* Execution of a work */
static void
probe_workqueue_execution(struct task_struct *wq_thread,
			  struct work_struct *work)
{
	int cpu = cpumask_first(&wq_thread->cpus_allowed);
	struct cpu_workqueue_stats *node;
	unsigned long flags;

	spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
	list_for_each_entry(node, &workqueue_cpu_stat(cpu)->list, list) {
		if (node->pid == wq_thread->pid) {
			node->executed++;
			goto found;
		}
	}
	pr_debug("trace_workqueue: entry not found\n");
found:
	spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
}

/* Creation of a cpu workqueue thread */
static void probe_workqueue_creation(struct task_struct *wq_thread, int cpu)
{
	struct cpu_workqueue_stats *cws;
	unsigned long flags;

	WARN_ON(cpu < 0);

	/* Workqueues are sometimes created in atomic context */
	cws = kzalloc(sizeof(struct cpu_workqueue_stats), GFP_ATOMIC);
	if (!cws) {
		pr_warning("trace_workqueue: not enough memory\n");
		return;
	}
	INIT_LIST_HEAD(&cws->list);
	kref_init(&cws->kref);
	cws->cpu = cpu;
	cws->pid = wq_thread->pid;

	spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
	list_add_tail(&cws->list, &workqueue_cpu_stat(cpu)->list);
	spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
}

/* Destruction of a cpu workqueue thread */
static void probe_workqueue_destruction(struct task_struct *wq_thread)
{
	/* Workqueue only execute on one cpu */
	int cpu = cpumask_first(&wq_thread->cpus_allowed);
	struct cpu_workqueue_stats *node, *next;
	unsigned long flags;

	spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
	list_for_each_entry_safe(node, next, &workqueue_cpu_stat(cpu)->list,
							list) {
		if (node->pid == wq_thread->pid) {
			list_del(&node->list);
			kref_put(&node->kref, cpu_workqueue_stat_free);
			goto found;
		}
	}

	pr_debug("trace_workqueue: don't find workqueue to destroy\n");
found:
	spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);

}

static struct cpu_workqueue_stats *workqueue_stat_start_cpu(int cpu)
{
	unsigned long flags;
	struct cpu_workqueue_stats *ret = NULL;


	spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);

	if (!list_empty(&workqueue_cpu_stat(cpu)->list)) {
		ret = list_entry(workqueue_cpu_stat(cpu)->list.next,
				 struct cpu_workqueue_stats, list);
		kref_get(&ret->kref);
	}

	spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);

	return ret;
}

static void *workqueue_stat_start(struct tracer_stat *trace)
{
	int cpu;
	void *ret = NULL;

	for_each_possible_cpu(cpu) {
		ret = workqueue_stat_start_cpu(cpu);
		if (ret)
			return ret;
	}
	return NULL;
}

static void *workqueue_stat_next(void *prev, int idx)
{
	struct cpu_workqueue_stats *prev_cws = prev;
	struct cpu_workqueue_stats *ret;
	int cpu = prev_cws->cpu;
	unsigned long flags;

	spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
	if (list_is_last(&prev_cws->list, &workqueue_cpu_stat(cpu)->list)) {
		spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
		do {
			cpu = cpumask_next(cpu, cpu_possible_mask);
			if (cpu >= nr_cpu_ids)
				return NULL;
		} while (!(ret = workqueue_stat_start_cpu(cpu)));
		return ret;
	} else {
		ret = list_entry(prev_cws->list.next,
				 struct cpu_workqueue_stats, list);
		kref_get(&ret->kref);
	}
	spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);

	return ret;
}

static int workqueue_stat_show(struct seq_file *s, void *p)
{
	struct cpu_workqueue_stats *cws = p;
	struct pid *pid;
	struct task_struct *tsk;

	pid = find_get_pid(cws->pid);
	if (pid) {
		tsk = get_pid_task(pid, PIDTYPE_PID);
		if (tsk) {
			seq_printf(s, "%3d %6d     %6u       %s\n", cws->cpu,
				   atomic_read(&cws->inserted), cws->executed,
				   tsk->comm);
			put_task_struct(tsk);
		}
		put_pid(pid);
	}

	return 0;
}

static void workqueue_stat_release(void *stat)
{
	struct cpu_workqueue_stats *node = stat;

	kref_put(&node->kref, cpu_workqueue_stat_free);
}

static int workqueue_stat_headers(struct seq_file *s)
{
	seq_printf(s, "# CPU  INSERTED  EXECUTED   NAME\n");
	seq_printf(s, "# |      |         |          |\n");
	return 0;
}

struct tracer_stat workqueue_stats __read_mostly = {
	.name = "workqueues",
	.stat_start = workqueue_stat_start,
	.stat_next = workqueue_stat_next,
	.stat_show = workqueue_stat_show,
	.stat_release = workqueue_stat_release,
	.stat_headers = workqueue_stat_headers
};


int __init stat_workqueue_init(void)
{
	if (register_stat_tracer(&workqueue_stats)) {
		pr_warning("Unable to register workqueue stat tracer\n");
		return 1;
	}

	return 0;
}
fs_initcall(stat_workqueue_init);

/*
 * Workqueues are created very early, just after pre-smp initcalls.
 * So we must register our tracepoints at this stage.
 */
int __init trace_workqueue_early_init(void)
{
	int ret, cpu;

	ret = register_trace_workqueue_insertion(probe_workqueue_insertion);
	if (ret)
		goto out;

	ret = register_trace_workqueue_execution(probe_workqueue_execution);
	if (ret)
		goto no_insertion;

	ret = register_trace_workqueue_creation(probe_workqueue_creation);
	if (ret)
		goto no_execution;

	ret = register_trace_workqueue_destruction(probe_workqueue_destruction);
	if (ret)
		goto no_creation;

	for_each_possible_cpu(cpu) {
		spin_lock_init(&workqueue_cpu_stat(cpu)->lock);
		INIT_LIST_HEAD(&workqueue_cpu_stat(cpu)->list);
	}

	return 0;

no_creation:
	unregister_trace_workqueue_creation(probe_workqueue_creation);
no_execution:
	unregister_trace_workqueue_execution(probe_workqueue_execution);
no_insertion:
	unregister_trace_workqueue_insertion(probe_workqueue_insertion);
out:
	pr_warning("trace_workqueue: unable to trace workqueues\n");

	return 1;
}
early_initcall(trace_workqueue_early_init);
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
/*=============================================================================
 *
 * A  PCMCIA client driver for the Raylink wireless LAN card.
 * The starting point for this module was the skeleton.c in the
 * PCMCIA 2.9.12 package written by David Hinds, dahinds@users.sourceforge.net
 *
 *
 * Copyright (c) 1998  Corey Thomas (corey@world.std.com)
 *
 * This driver is free software; you can redistribute it and/or modify
 * it under the terms of version 2 only of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * It is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 *
 * Changes:
 * Arnaldo Carvalho de Melo <acme@conectiva.com.br> - 08/08/2000
 * - reorganize kmallocs in ray_attach, checking all for failure
 *   and releasing the previous allocations if one fails
 *
 * Daniele Bellucci <bellucda@tiscali.it> - 07/10/2003
 * - Audit copy_to_user in ioctl(SIOCGIWESSID)
 *
=============================================================================*/

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/ptrace.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_arp.h>
#include <linux/ioport.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <linux/ieee80211.h>

#include <pcmcia/cs_types.h>
#include <pcmcia/cs.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
#include <pcmcia/mem_op.h>

#include <linux/wireless.h>
#include <net/iw_handler.h>

#include <asm/io.h>
#include <asm/system.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>

/* Warning : these stuff will slow down the driver... */
#define WIRELESS_SPY		/* Enable spying addresses */
/* Definitions we need for spy */
typedef struct iw_statistics iw_stats;
typedef u_char mac_addr[ETH_ALEN];	/* Hardware address */

#include "rayctl.h"
#include "ray_cs.h"


/** Prototypes based on PCMCIA skeleton driver *******************************/
static int ray_config(struct pcmcia_device *link);
static void ray_release(struct pcmcia_device *link);
static void ray_detach(struct pcmcia_device *p_dev);

/***** Prototypes indicated by device structure ******************************/
static int ray_dev_close(struct net_device *dev);
static int ray_dev_config(struct net_device *dev, struct ifmap *map);
static struct net_device_stats *ray_get_stats(struct net_device *dev);
static int ray_dev_init(struct net_device *dev);

static const struct ethtool_ops netdev_ethtool_ops;

static int ray_open(struct net_device *dev);
static netdev_tx_t ray_dev_start_xmit(struct sk_buff *skb,
					    struct net_device *dev);
static void set_multicast_list(struct net_device *dev);
static void ray_update_multi_list(struct net_device *dev, int all);
static int translate_frame(ray_dev_t *local, struct tx_msg __iomem *ptx,
			   unsigned char *data, int len);
static void ray_build_header(ray_dev_t *local, struct tx_msg __iomem *ptx,
			     UCHAR msg_type, unsigned char *data);
static void untranslate(ray_dev_t *local, struct sk_buff *skb, int len);
static iw_stats *ray_get_wireless_stats(struct net_device *dev);
static const struct iw_handler_def ray_handler_def;

/***** Prototypes for raylink functions **************************************/
static int asc_to_int(char a);
static void authenticate(ray_dev_t *local);
static int build_auth_frame(ray_dev_t *local, UCHAR *dest, int auth_type);
static void authenticate_timeout(u_long);
static int get_free_ccs(ray_dev_t *local);
static int get_free_tx_ccs(ray_dev_t *local);
static void init_startup_params(ray_dev_t *local);
static int parse_addr(char *in_str, UCHAR *out);
static int ray_hw_xmit(unsigned char *data, int len, struct net_device *dev, UCHAR type);
static int ray_init(struct net_device *dev);
static int interrupt_ecf(ray_dev_t *local, int ccs);
static void ray_reset(struct net_device *dev);
static void ray_update_parm(struct net_device *dev, UCHAR objid, UCHAR *value, int len);
static void verify_dl_startup(u_long);

/* Prototypes for interrpt time functions **********************************/
static irqreturn_t ray_interrupt(int reg, void *dev_id);
static void clear_interrupt(ray_dev_t *local);
static void rx_deauthenticate(ray_dev_t *local, struct rcs __iomem *prcs,
			      unsigned int pkt_addr, int rx_len);
static int copy_from_rx_buff(ray_dev_t *local, UCHAR *dest, int pkt_addr, int len);
static void ray_rx(struct net_device *dev, ray_dev_t *local, struct rcs __iomem *prcs);
static void release_frag_chain(ray_dev_t *local, struct rcs __iomem *prcs);
static void rx_authenticate(ray_dev_t *local, struct rcs __iomem *prcs,
			    unsigned int pkt_addr, int rx_len);
static void rx_data(struct net_device *dev, struct rcs __iomem *prcs,
		    unsigned int pkt_addr, int rx_len);
static void associate(ray_dev_t *local);

/* Card command functions */
static int dl_startup_params(struct net_device *dev);
static void join_net(u_long local);
static void start_net(u_long local);
/* void start_net(ray_dev_t *local); */

/*===========================================================================*/
/* Parameters that can be set with 'insmod' */

/* ADHOC=0, Infrastructure=1 */
static int net_type = ADHOC;

/* Hop dwell time in Kus (1024 us units defined by 802.11) */
static int hop_dwell = 128;

/* Beacon period in Kus */
static int beacon_period = 256;

/* power save mode (0 = off, 1 = save power) */
static int psm;

/* String for network's Extended Service Set ID. 32 Characters max */
static char *essid;

/* Default to encapsulation unless translation requested */
static int translate = 1;

static int country = USA;

static int sniffer;

static int bc;

/* 48 bit physical card address if overriding card's real physical
 * address is required.  Since IEEE 802.11 addresses are 48 bits
 * like ethernet, an int can't be used, so a string is used. To
 * allow use of addresses starting with a decimal digit, the first
 * character must be a letter and will be ignored. This letter is
 * followed by up to 12 hex digits which are the address.  If less
 * than 12 digits are used, the address will be left filled with 0's.
 * Note that bit 0 of the first byte is the broadcast bit, and evil
 * things will happen if it is not 0 in a card address.
 */
static char *phy_addr = NULL;


/* A struct pcmcia_device structure has fields for most things that are needed
   to keep track of a socket, but there will usually be some device
   specific information that also needs to be kept track of.  The
   'priv' pointer in a struct pcmcia_device structure can be used to point to
   a device-specific private data structure, like this.
*/
static unsigned int ray_mem_speed = 500;

/* WARNING: THIS DRIVER IS NOT CAPABLE OF HANDLING MULTIPLE DEVICES! */
static struct pcmcia_device *this_device = NULL;

MODULE_AUTHOR("Corey Thomas <corey@world.std.com>");
MODULE_DESCRIPTION("Raylink/WebGear wireless LAN driver");
MODULE_LICENSE("GPL");

module_param(net_type, int, 0);
module_param(hop_dwell, int, 0);
module_param(beacon_period, int, 0);
module_param(psm, int, 0);
module_param(essid, charp, 0);
module_param(translate, int, 0);
module_param(country, int, 0);
module_param(sniffer, int, 0);
module_param(bc, int, 0);
module_param(phy_addr, charp, 0);
module_param(ray_mem_speed, int, 0);

static UCHAR b5_default_startup_parms[] = {
	0, 0,			/* Adhoc station */
	'L', 'I', 'N', 'U', 'X', 0, 0, 0,	/* 32 char ESSID */
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	1, 0,			/* Active scan, CA Mode */
	0, 0, 0, 0, 0, 0,	/* No default MAC addr  */
	0x7f, 0xff,		/* Frag threshold */
	0x00, 0x80,		/* Hop time 128 Kus */
	0x01, 0x00,		/* Beacon period 256 Kus */
	0x01, 0x07, 0xa3,	/* DTIM, retries, ack timeout */
	0x1d, 0x82, 0x4e,	/* SIFS, DIFS, PIFS */
	0x7f, 0xff,		/* RTS threshold */
	0x04, 0xe2, 0x38, 0xA4,	/* scan_dwell, max_scan_dwell */
	0x05,			/* assoc resp timeout thresh */
	0x08, 0x02, 0x08,	/* adhoc, infra, super cycle max */
	0,			/* Promiscuous mode */
	0x0c, 0x0bd,		/* Unique word */
	0x32,			/* Slot time */
	0xff, 0xff,		/* roam-low snr, low snr count */
	0x05, 0xff,		/* Infra, adhoc missed bcn thresh */
	0x01, 0x0b, 0x4f,	/* USA, hop pattern, hop pat length */
/* b4 - b5 differences start here */
	0x00, 0x3f,		/* CW max */
	0x00, 0x0f,		/* CW min */
	0x04, 0x08,		/* Noise gain, limit offset */
	0x28, 0x28,		/* det rssi, med busy offsets */
	7,			/* det sync thresh */
	0, 2, 2,		/* test mode, min, max */
	0,			/* allow broadcast SSID probe resp */
	0, 0,			/* privacy must start, can join */
	2, 0, 0, 0, 0, 0, 0, 0	/* basic rate set */
};

static UCHAR b4_default_startup_parms[] = {
	0, 0,			/* Adhoc station */
	'L', 'I', 'N', 'U', 'X', 0, 0, 0,	/* 32 char ESSID */
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0,
	1, 0,			/* Active scan, CA Mode */
	0, 0, 0, 0, 0, 0,	/* No default MAC addr  */
	0x7f, 0xff,		/* Frag threshold */
	0x02, 0x00,		/* Hop time */
	0x00, 0x01,		/* Beacon period */
	0x01, 0x07, 0xa3,	/* DTIM, retries, ack timeout */
	0x1d, 0x82, 0xce,	/* SIFS, DIFS, PIFS */
	0x7f, 0xff,		/* RTS threshold */
	0xfb, 0x1e, 0xc7, 0x5c,	/* scan_dwell, max_scan_dwell */
	0x05,			/* assoc resp timeout thresh */
	0x04, 0x02, 0x4,	/* adhoc, infra, super cycle max */
	0,			/* Promiscuous mode */
	0x0c, 0x0bd,		/* Unique word */
	0x4e,			/* Slot time (TBD seems wrong) */
	0xff, 0xff,		/* roam-low snr, low snr count */
	0x05, 0xff,		/* Infra, adhoc missed bcn thresh */
	0x01, 0x0b, 0x4e,	/* USA, hop pattern, hop pat length */
/* b4 - b5 differences start here */
	0x3f, 0x0f,		/* CW max, min */
	0x04, 0x08,		/* Noise gain, limit offset */
	0x28, 0x28,		/* det rssi, med busy offsets */
	7,			/* det sync thresh */
	0, 2, 2			/* test mode, min, max */
};

/*===========================================================================*/
static unsigned char eth2_llc[] = { 0xaa, 0xaa, 3, 0, 0, 0 };

static char hop_pattern_length[] = { 1,
	USA_HOP_MOD, EUROPE_HOP_MOD,
	JAPAN_HOP_MOD, KOREA_HOP_MOD,
	SPAIN_HOP_MOD, FRANCE_HOP_MOD,
	ISRAEL_HOP_MOD, AUSTRALIA_HOP_MOD,
	JAPAN_TEST_HOP_MOD
};

static char rcsid[] =
    "Raylink/WebGear wireless LAN - Corey <Thomas corey@world.std.com>";

static const struct net_device_ops ray_netdev_ops = {
	.ndo_init 		= ray_dev_init,
	.ndo_open 		= ray_open,
	.ndo_stop 		= ray_dev_close,
	.ndo_start_xmit		= ray_dev_start_xmit,
	.ndo_set_config		= ray_dev_config,
	.ndo_get_stats		= ray_get_stats,
	.ndo_set_multicast_list = set_multicast_list,
	.ndo_change_mtu		= eth_change_mtu,
	.ndo_set_mac_address 	= eth_mac_addr,
	.ndo_validate_addr	= eth_validate_addr,
};

/*=============================================================================
    ray_attach() creates an "instance" of the driver, allocating
    local data structures for one device.  The device is registered
    with Card Services.
    The dev_link structure is initialized, but we don't actually
    configure the card at this point -- we wait until we receive a
    card insertion event.
=============================================================================*/
static int ray_probe(struct pcmcia_device *p_dev)
{
	ray_dev_t *local;
	struct net_device *dev;

	dev_dbg(&p_dev->dev, "ray_attach()\n");

	/* Allocate space for private device-specific data */
	dev = alloc_etherdev(sizeof(ray_dev_t));
	if (!dev)
		goto fail_alloc_dev;

	local = netdev_priv(dev);
	local->finder = p_dev;

	/* The io structure describes IO port mapping. None used here */
	p_dev->io.NumPorts1 = 0;
	p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
	p_dev->io.IOAddrLines = 5;

	/* Interrupt setup. For PCMCIA, driver takes what's given */
	p_dev->irq.Attributes = IRQ_TYPE_DYNAMIC_SHARING;
	p_dev->irq.Handler = &ray_interrupt;

	/* General socket configuration */
	p_dev->conf.Attributes = CONF_ENABLE_IRQ;
	p_dev->conf.IntType = INT_MEMORY_AND_IO;
	p_dev->conf.ConfigIndex = 1;

	p_dev->priv = dev;

	local->finder = p_dev;
	local->card_status = CARD_INSERTED;
	local->authentication_state = UNAUTHENTICATED;
	local->num_multi = 0;
	dev_dbg(&p_dev->dev, "ray_attach p_dev = %p,  dev = %p,  local = %p, intr = %p\n",
	      p_dev, dev, local, &ray_interrupt);

	/* Raylink entries in the device structure */
	dev->netdev_ops = &ray_netdev_ops;
	SET_ETHTOOL_OPS(dev, &netdev_ethtool_ops);
	dev->wireless_handlers = &ray_handler_def;
#ifdef WIRELESS_SPY
	local->wireless_data.spy_data = &local->spy_data;
	dev->wireless_data = &local->wireless_data;
#endif /* WIRELESS_SPY */


	dev_dbg(&p_dev->dev, "ray_cs ray_attach calling ether_setup.)\n");
	netif_stop_queue(dev);

	init_timer(&local->timer);

	this_device = p_dev;
	return ray_config(p_dev);

fail_alloc_dev:
	return -ENOMEM;
} /* ray_attach */

/*=============================================================================
    This deletes a driver "instance".  The device is de-registered
    with Card Services.  If it has been released, all local data
    structures are freed.  Otherwise, the structures will be freed
    when the device is released.
=============================================================================*/
static void ray_detach(struct pcmcia_device *link)
{
	struct net_device *dev;
	ray_dev_t *local;

	dev_dbg(&link->dev, "ray_detach\n");

	this_device = NULL;
	dev = link->priv;

	ray_release(link);

	local = netdev_priv(dev);
	del_timer(&local->timer);

	if (link->priv) {
		if (link->dev_node)
			unregister_netdev(dev);
		free_netdev(dev);
	}
	dev_dbg(&link->dev, "ray_cs ray_detach ending\n");
} /* ray_detach */

/*=============================================================================
    ray_config() is run after a CARD_INSERTION event
    is received, to configure the PCMCIA socket, and to make the
    ethernet device available to the system.
=============================================================================*/
#define MAX_TUPLE_SIZE 128
static int ray_config(struct pcmcia_device *link)
{
	int ret = 0;
	int i;
	win_req_t req;
	memreq_t mem;
	struct net_device *dev = (struct net_device *)link->priv;
	ray_dev_t *local = netdev_priv(dev);

	dev_dbg(&link->dev, "ray_config\n");

	/* Determine card type and firmware version */
	printk(KERN_INFO "ray_cs Detected: %s%s%s%s\n",
	       link->prod_id[0] ? link->prod_id[0] : " ",
	       link->prod_id[1] ? link->prod_id[1] : " ",
	       link->prod_id[2] ? link->prod_id[2] : " ",
	       link->prod_id[3] ? link->prod_id[3] : " ");

	/* Now allocate an interrupt line.  Note that this does not
	   actually assign a handler to the interrupt.
	 */
	ret = pcmcia_request_irq(link, &link->irq);
	if (ret)
		goto failed;
	dev->irq = link->irq.AssignedIRQ;

	/* This actually configures the PCMCIA socket -- setting up
	   the I/O windows and the interrupt mapping.
	 */
	ret = pcmcia_request_configuration(link, &link->conf);
	if (ret)
		goto failed;

/*** Set up 32k window for shared memory (transmit and control) ************/
	req.Attributes =
	    WIN_DATA_WIDTH_8 | WIN_MEMORY_TYPE_CM | WIN_ENABLE | WIN_USE_WAIT;
	req.Base = 0;
	req.Size = 0x8000;
	req.AccessSpeed = ray_mem_speed;
	ret = pcmcia_request_window(link, &req, &link->win);
	if (ret)
		goto failed;
	mem.CardOffset = 0x0000;
	mem.Page = 0;
	ret = pcmcia_map_mem_page(link, link->win, &mem);
	if (ret)
		goto failed;
	local->sram = ioremap(req.Base, req.Size);

/*** Set up 16k window for shared memory (receive buffer) ***************/
	req.Attributes =
	    WIN_DATA_WIDTH_8 | WIN_MEMORY_TYPE_CM | WIN_ENABLE | WIN_USE_WAIT;
	req.Base = 0;
	req.Size = 0x4000;
	req.AccessSpeed = ray_mem_speed;
	ret = pcmcia_request_window(link, &req, &local->rmem_handle);
	if (ret)
		goto failed;
	mem.CardOffset = 0x8000;
	mem.Page = 0;
	ret = pcmcia_map_mem_page(link, local->rmem_handle, &mem);
	if (ret)
		goto failed;
	local->rmem = ioremap(req.Base, req.Size);

/*** Set up window for attribute memory ***********************************/
	req.Attributes =
	    WIN_DATA_WIDTH_8 | WIN_MEMORY_TYPE_AM | WIN_ENABLE | WIN_USE_WAIT;
	req.Base = 0;
	req.Size = 0x1000;
	req.AccessSpeed = ray_mem_speed;
	ret = pcmcia_request_window(link, &req, &local->amem_handle);
	if (ret)
		goto failed;
	mem.CardOffset = 0x0000;
	mem.Page = 0;
	ret = pcmcia_map_mem_page(link, local->amem_handle, &mem);
	if (ret)
		goto failed;
	local->amem = ioremap(req.Base, req.Size);

	dev_dbg(&link->dev, "ray_config sram=%p\n", local->sram);
	dev_dbg(&link->dev, "ray_config rmem=%p\n", local->rmem);
	dev_dbg(&link->dev, "ray_config amem=%p\n", local->amem);
	if (ray_init(dev) < 0) {
		ray_release(link);
		return -ENODEV;
	}

	SET_NETDEV_DEV(dev, &link->dev);
	i = register_netdev(dev);
	if (i != 0) {
		printk("ray_config register_netdev() failed\n");
		ray_release(link);
		return i;
	}

	strcpy(local->node.dev_name, dev->name);
	link->dev_node = &local->node;

	printk(KERN_INFO "%s: RayLink, irq %d, hw_addr %pM\n",
	       dev->name, dev->irq, dev->dev_addr);

	return 0;

failed:
	ray_release(link);
	return -ENODEV;
} /* ray_config */

static inline struct ccs __iomem *ccs_base(ray_dev_t *dev)
{
	return dev->sram + CCS_BASE;
}

static inline struct rcs __iomem *rcs_base(ray_dev_t *dev)
{
	/*
	 * This looks nonsensical, since there is a separate
	 * RCS_BASE. But the difference between a "struct rcs"
	 * and a "struct ccs" ends up being in the _index_ off
	 * the base, so the base pointer is the same for both
	 * ccs/rcs.
	 */
	return dev->sram + CCS_BASE;
}

/*===========================================================================*/
static int ray_init(struct net_device *dev)
{
	int i;
	UCHAR *p;
	struct ccs __iomem *pccs;
	ray_dev_t *local = netdev_priv(dev);
	struct pcmcia_device *link = local->finder;
	dev_dbg(&link->dev, "ray_init(0x%p)\n", dev);
	if (!(pcmcia_dev_present(link))) {
		dev_dbg(&link->dev, "ray_init - device not present\n");
		return -1;
	}

	local->net_type = net_type;
	local->sta_type = TYPE_STA;

	/* Copy the startup results to local memory */
	memcpy_fromio(&local->startup_res, local->sram + ECF_TO_HOST_BASE,
		      sizeof(struct startup_res_6));

	/* Check Power up test status and get mac address from card */
	if (local->startup_res.startup_word != 0x80) {
		printk(KERN_INFO "ray_init ERROR card status = %2x\n",
		       local->startup_res.startup_word);
		local->card_status = CARD_INIT_ERROR;
		return -1;
	}

	local->fw_ver = local->startup_res.firmware_version[0];
	local->fw_bld = local->startup_res.firmware_version[1];
	local->fw_var = local->startup_res.firmware_version[2];
	dev_dbg(&link->dev, "ray_init firmware version %d.%d \n", local->fw_ver,
	      local->fw_bld);

	local->tib_length = 0x20;
	if ((local->fw_ver == 5) && (local->fw_bld >= 30))
		local->tib_length = local->startup_res.tib_length;
	dev_dbg(&link->dev, "ray_init tib_length = 0x%02x\n", local->tib_length);
	/* Initialize CCS's to buffer free state */
	pccs = ccs_base(local);
	for (i = 0; i < NUMBER_OF_CCS; i++) {
		writeb(CCS_BUFFER_FREE, &(pccs++)->buffer_status);
	}
	init_startup_params(local);

	/* copy mac address to startup parameters */
	if (parse_addr(phy_addr, local->sparm.b4.a_mac_addr)) {
		p = local->sparm.b4.a_mac_addr;
	} else {
		memcpy(&local->sparm.b4.a_mac_addr,
		       &local->startup_res.station_addr, ADDRLEN);
		p = local->sparm.b4.a_mac_addr;
	}

	clear_interrupt(local);	/* Clear any interrupt from the card */
	local->card_status = CARD_AWAITING_PARAM;
	dev_dbg(&link->dev, "ray_init ending\n");
	return 0;
} /* ray_init */

/*===========================================================================*/
/* Download startup parameters to the card and command it to read them       */
static int dl_startup_params(struct net_device *dev)
{
	int ccsindex;
	ray_dev_t *local = netdev_priv(dev);
	struct ccs __iomem *pccs;
	struct pcmcia_device *link = local->finder;

	dev_dbg(&link->dev, "dl_startup_params entered\n");
	if (!(pcmcia_dev_present(link))) {
		dev_dbg(&link->dev, "ray_cs dl_startup_params - device not present\n");
		return -1;
	}

	/* Copy parameters to host to ECF area */
	if (local->fw_ver == 0x55)
		memcpy_toio(local->sram + HOST_TO_ECF_BASE, &local->sparm.b4,
			    sizeof(struct b4_startup_params));
	else
		memcpy_toio(local->sram + HOST_TO_ECF_BASE, &local->sparm.b5,
			    sizeof(struct b5_startup_params));

	/* Fill in the CCS fields for the ECF */
	if ((ccsindex = get_free_ccs(local)) < 0)
		return -1;
	local->dl_param_ccs = ccsindex;
	pccs = ccs_base(local) + ccsindex;
	writeb(CCS_DOWNLOAD_STARTUP_PARAMS, &pccs->cmd);
	dev_dbg(&link->dev, "dl_startup_params start ccsindex = %d\n",
	      local->dl_param_ccs);
	/* Interrupt the firmware to process the command */
	if (interrupt_ecf(local, ccsindex)) {
		printk(KERN_INFO "ray dl_startup_params failed - "
		       "ECF not ready for intr\n");
		local->card_status = CARD_DL_PARAM_ERROR;
		writeb(CCS_BUFFER_FREE, &(pccs++)->buffer_status);
		return -2;
	}
	local->card_status = CARD_DL_PARAM;
	/* Start kernel timer to wait for dl startup to complete. */
	local->timer.expires = jiffies + HZ / 2;
	local->timer.data = (long)local;
	local->timer.function = &verify_dl_startup;
	add_timer(&local->timer);
	dev_dbg(&link->dev,
	      "ray_cs dl_startup_params started timer for verify_dl_startup\n");
	return 0;
} /* dl_startup_params */

/*===========================================================================*/
static void init_startup_params(ray_dev_t *local)
{
	int i;

	if (country > JAPAN_TEST)
		country = USA;
	else if (country < USA)
		country = USA;
	/* structure for hop time and beacon period is defined here using
	 * New 802.11D6.1 format.  Card firmware is still using old format
	 * until version 6.
	 *    Before                    After
	 *    a_hop_time ms byte        a_hop_time ms byte
	 *    a_hop_time 2s byte        a_hop_time ls byte
	 *    a_hop_time ls byte        a_beacon_period ms byte
	 *    a_beacon_period           a_beacon_period ls byte
	 *
	 *    a_hop_time = uS           a_hop_time = KuS
	 *    a_beacon_period = hops    a_beacon_period = KuS
	 *//* 64ms = 010000 */
	if (local->fw_ver == 0x55) {
		memcpy((UCHAR *) &local->sparm.b4, b4_default_startup_parms,
		       sizeof(struct b4_startup_params));
		/* Translate sane kus input values to old build 4/5 format */
		/* i = hop time in uS truncated to 3 bytes */
		i = (hop_dwell * 1024) & 0xffffff;
		local->sparm.b4.a_hop_time[0] = (i >> 16) & 0xff;
		local->sparm.b4.a_hop_time[1] = (i >> 8) & 0xff;
		local->sparm.b4.a_beacon_period[0] = 0;
		local->sparm.b4.a_beacon_period[1] =
		    ((beacon_period / hop_dwell) - 1) & 0xff;
		local->sparm.b4.a_curr_country_code = country;
		local->sparm.b4.a_hop_pattern_length =
		    hop_pattern_length[(int)country] - 1;
		if (bc) {
			local->sparm.b4.a_ack_timeout = 0x50;
			local->sparm.b4.a_sifs = 0x3f;
		}
	} else { /* Version 5 uses real kus values */
		memcpy((UCHAR *) &local->sparm.b5, b5_default_startup_parms,
		       sizeof(struct b5_startup_params));

		local->sparm.b5.a_hop_time[0] = (hop_dwell >> 8) & 0xff;
		local->sparm.b5.a_hop_time[1] = hop_dwell & 0xff;
		local->sparm.b5.a_beacon_period[0] =
		    (beacon_period >> 8) & 0xff;
		local->sparm.b5.a_beacon_period[1] = beacon_period & 0xff;
		if (psm)
			local->sparm.b5.a_power_mgt_state = 1;
		local->sparm.b5.a_curr_country_code = country;
		local->sparm.b5.a_hop_pattern_length =
		    hop_pattern_length[(int)country];
	}

	local->sparm.b4.a_network_type = net_type & 0x01;
	local->sparm.b4.a_acting_as_ap_status = TYPE_STA;

	if (essid != NULL)
		strncpy(local->sparm.b4.a_current_ess_id, essid, ESSID_SIZE);
} /* init_startup_params */

/*===========================================================================*/
static void verify_dl_startup(u_long data)
{
	ray_dev_t *local = (ray_dev_t *) data;
	struct ccs __iomem *pccs = ccs_base(local) + local->dl_param_ccs;
	UCHAR status;
	struct pcmcia_device *link = local->finder;

	if (!(pcmcia_dev_present(link))) {
		dev_dbg(&link->dev, "ray_cs verify_dl_startup - device not present\n");
		return;
	}
#if 0
	{
		int i;
		printk(KERN_DEBUG
		       "verify_dl_startup parameters sent via ccs %d:\n",
		       local->dl_param_ccs);
		for (i = 0; i < sizeof(struct b5_startup_params); i++) {
			printk(" %2x",
			       (unsigned int)readb(local->sram +
						   HOST_TO_ECF_BASE + i));
		}
		printk("\n");
	}
#endif

	status = readb(&pccs->buffer_status);
	if (status != CCS_BUFFER_FREE) {
		printk(KERN_INFO
		       "Download startup params failed.  Status = %d\n",
		       status);
		local->card_status = CARD_DL_PARAM_ERROR;
		return;
	}
	if (local->sparm.b4.a_network_type == ADHOC)
		start_net((u_long) local);
	else
		join_net((u_long) local);

	return;
} /* end verify_dl_startup */

/*===========================================================================*/
/* Command card to start a network */
static void start_net(u_long data)
{
	ray_dev_t *local = (ray_dev_t *) data;
	struct ccs __iomem *pccs;
	int ccsindex;
	struct pcmcia_device *link = local->finder;
	if (!(pcmcia_dev_present(link))) {
		dev_dbg(&link->dev, "ray_cs start_net - device not present\n");
		return;
	}
	/* Fill in the CCS fields for the ECF */
	if ((ccsindex = get_free_ccs(local)) < 0)
		return;
	pccs = ccs_base(local) + ccsindex;
	writeb(CCS_START_NETWORK, &pccs->cmd);
	writeb(0, &pccs->var.start_network.update_param);
	/* Interrupt the firmware to process the command */
	if (interrupt_ecf(local, ccsindex)) {
		dev_dbg(&link->dev, "ray start net failed - card not ready for intr\n");
		writeb(CCS_BUFFER_FREE, &(pccs++)->buffer_status);
		return;
	}
	local->card_status = CARD_DOING_ACQ;
	return;
} /* end start_net */

/*===========================================================================*/
/* Command card to join a network */
static void join_net(u_long data)
{
	ray_dev_t *local = (ray_dev_t *) data;

	struct ccs __iomem *pccs;
	int ccsindex;
	struct pcmcia_device *link = local->finder;

	if (!(pcmcia_dev_present(link))) {
		dev_dbg(&link->dev, "ray_cs join_net - device not present\n");
		return;
	}
	/* Fill in the CCS fields for the ECF */
	if ((ccsindex = get_free_ccs(local)) < 0)
		return;
	pccs = ccs_base(local) + ccsindex;
	writeb(CCS_JOIN_NETWORK, &pccs->cmd);
	writeb(0, &pccs->var.join_network.update_param);
	writeb(0, &pccs->var.join_network.net_initiated);
	/* Interrupt the firmware to process the command */
	if (interrupt_ecf(local, ccsindex)) {
		dev_dbg(&link->dev, "ray join net failed - card not ready for intr\n");
		writeb(CCS_BUFFER_FREE, &(pccs++)->buffer_status);
		return;
	}
	local->card_status = CARD_DOING_ACQ;
	return;
}

/*============================================================================
    After a card is removed, ray_release() will unregister the net
    device, and release the PCMCIA configuration.  If the device is
    still open, this will be postponed until it is closed.
=============================================================================*/
static void ray_release(struct pcmcia_device *link)
{
	struct net_device *dev = link->priv;
	ray_dev_t *local = netdev_priv(dev);
	int i;

	dev_dbg(&link->dev, "ray_release\n");

	del_timer(&local->timer);

	iounmap(local->sram);
	iounmap(local->rmem);
	iounmap(local->amem);
	/* Do bother checking to see if these succeed or not */
	i = pcmcia_release_window(link, local->amem_handle);
	if (i != 0)
		dev_dbg(&link->dev, "ReleaseWindow(local->amem) ret = %x\n", i);
	i = pcmcia_release_window(link, local->rmem_handle);
	if (i != 0)
		dev_dbg(&link->dev, "ReleaseWindow(local->rmem) ret = %x\n", i);
	pcmcia_disable_device(link);

	dev_dbg(&link->dev, "ray_release ending\n");
}

static int ray_suspend(struct pcmcia_device *link)
{
	struct net_device *dev = link->priv;

	if (link->open)
		netif_device_detach(dev);

	return 0;
}

static int ray_resume(struct pcmcia_device *link)
{
	struct net_device *dev = link->priv;

	if (link->open) {
		ray_reset(dev);
		netif_device_attach(dev);
	}

	return 0;
}

/*===========================================================================*/
static int ray_dev_init(struct net_device *dev)
{
#ifdef RAY_IMMEDIATE_INIT
	int i;
#endif /* RAY_IMMEDIATE_INIT */
	ray_dev_t *local = netdev_priv(dev);
	struct pcmcia_device *link = local->finder;

	dev_dbg(&link->dev, "ray_dev_init(dev=%p)\n", dev);
	if (!(pcmcia_dev_present(link))) {
		dev_dbg(&link->dev, "ray_dev_init - device not present\n");
		return -1;
	}
#ifdef RAY_IMMEDIATE_INIT
	/* Download startup parameters */
	if ((i = dl_startup_params(dev)) < 0) {
		printk(KERN_INFO "ray_dev_init dl_startup_params failed - "
		       "returns 0x%x\n", i);
		return -1;
	}
#else /* RAY_IMMEDIATE_INIT */
	/* Postpone the card init so that we can still configure the card,
	 * for example using the Wireless Extensions. The init will happen
	 * in ray_open() - Jean II */
	dev_dbg(&link->dev,
	      "ray_dev_init: postponing card init to ray_open() ; Status = %d\n",
	      local->card_status);
#endif /* RAY_IMMEDIATE_INIT */

	/* copy mac and broadcast addresses to linux device */
	memcpy(dev->dev_addr, &local->sparm.b4.a_mac_addr, ADDRLEN);
	memset(dev->broadcast, 0xff, ETH_ALEN);

	dev_dbg(&link->dev, "ray_dev_init ending\n");
	return 0;
}

/*===========================================================================*/
static int ray_dev_config(struct net_device *dev, struct ifmap *map)
{
	ray_dev_t *local = netdev_priv(dev);
	struct pcmcia_device *link = local->finder;
	/* Dummy routine to satisfy device structure */
	dev_dbg(&link->dev, "ray_dev_config(dev=%p,ifmap=%p)\n", dev, map);
	if (!(pcmcia_dev_present(link))) {
		dev_dbg(&link->dev, "ray_dev_config - device not present\n");
		return -1;
	}

	return 0;
}

/*===========================================================================*/
static netdev_tx_t ray_dev_start_xmit(struct sk_buff *skb,
					    struct net_device *dev)
{
	ray_dev_t *local = netdev_priv(dev);
	struct pcmcia_device *link = local->finder;
	short length = skb->len;

	if (!pcmcia_dev_present(link)) {
		dev_dbg(&link->dev, "ray_dev_start_xmit - device not present\n");
		dev_kfree_skb(skb);
		return NETDEV_TX_OK;
	}

	dev_dbg(&link->dev, "ray_dev_start_xmit(skb=%p, dev=%p)\n", skb, dev);
	if (local->authentication_state == NEED_TO_AUTH) {
		dev_dbg(&link->dev, "ray_cs Sending authentication request.\n");
		if (!build_auth_frame(local, local->auth_id, OPEN_AUTH_REQUEST)) {
			local->authentication_state = AUTHENTICATED;
			netif_stop_queue(dev);
			return NETDEV_TX_BUSY;
		}
	}

	if (length < ETH_ZLEN) {
		if (skb_padto(skb, ETH_ZLEN))
			return NETDEV_TX_OK;
		length = ETH_ZLEN;
	}
	switch (ray_hw_xmit(skb->data, length, dev, DATA_TYPE)) {
	case XMIT_NO_CCS:
	case XMIT_NEED_AUTH:
		netif_stop_queue(dev);
		return NETDEV_TX_BUSY;
	case XMIT_NO_INTR:
	case XMIT_MSG_BAD:
	case XMIT_OK:
	default:
		dev->trans_start = jiffies;
		dev_kfree_skb(skb);
	}

	return NETDEV_TX_OK;
} /* ray_dev_start_xmit */

/*===========================================================================*/
static int ray_hw_xmit(unsigned char *data, int len, struct net_device *dev,
		       UCHAR msg_type)
{
	ray_dev_t *local = netdev_priv(dev);
	struct ccs __iomem *pccs;
	int ccsindex;
	int offset;
	struct tx_msg __iomem *ptx;	/* Address of xmit buffer in PC space */
	short int addr;		/* Address of xmit buffer in card space */

	pr_debug("ray_hw_xmit(data=%p, len=%d, dev=%p)\n", data, len, dev);
	if (len + TX_HEADER_LENGTH > TX_BUF_SIZE) {
		printk(KERN_INFO "ray_hw_xmit packet too large: %d bytes\n",
		       len);
		return XMIT_MSG_BAD;
	}
	switch (ccsindex = get_free_tx_ccs(local)) {
	case ECCSBUSY:
		pr_debug("ray_hw_xmit tx_ccs table busy\n");
	case ECCSFULL:
		pr_debug("ray_hw_xmit No free tx ccs\n");
	case ECARDGONE:
		netif_stop_queue(dev);
		return XMIT_NO_CCS;
	default:
		break;
	}
	addr = TX_BUF_BASE + (ccsindex << 11);

	if (msg_type == DATA_TYPE) {
		local->stats.tx_bytes += len;
		local->stats.tx_packets++;
	}

	ptx = local->sram + addr;

	ray_build_header(local, ptx, msg_type, data);
	if (translate) {
		offset = translate_frame(local, ptx, data, len);
	} else { /* Encapsulate frame */
		/* TBD TIB length will move address of ptx->var */
		memcpy_toio(&ptx->var, data, len);
		offset = 0;
	}

	/* fill in the CCS */
	pccs = ccs_base(local) + ccsindex;
	len += TX_HEADER_LENGTH + offset;
	writeb(CCS_TX_REQUEST, &pccs->cmd);
	writeb(addr >> 8, &pccs->var.tx_request.tx_data_ptr[0]);
	writeb(local->tib_length, &pccs->var.tx_request.tx_data_ptr[1]);
	writeb(len >> 8, &pccs->var.tx_request.tx_data_length[0]);
	writeb(len & 0xff, &pccs->var.tx_request.tx_data_length[1]);
/* TBD still need psm_cam? */
	writeb(PSM_CAM, &pccs->var.tx_request.pow_sav_mode);
	writeb(local->net_default_tx_rate, &pccs->var.tx_request.tx_rate);
	writeb(0, &pccs->var.tx_request.antenna);
	pr_debug("ray_hw_xmit default_tx_rate = 0x%x\n",
	      local->net_default_tx_rate);

	/* Interrupt the firmware to process the command */
	if (interrupt_ecf(local, ccsindex)) {
		pr_debug("ray_hw_xmit failed - ECF not ready for intr\n");
/* TBD very inefficient to copy packet to buffer, and then not
   send it, but the alternative is to queue the messages and that
   won't be done for a while.  Maybe set tbusy until a CCS is free?
*/
		writeb(CCS_BUFFER_FREE, &pccs->buffer_status);
		return XMIT_NO_INTR;
	}
	return XMIT_OK;
} /* end ray_hw_xmit */

/*===========================================================================*/
static int translate_frame(ray_dev_t *local, struct tx_msg __iomem *ptx,
			   unsigned char *data, int len)
{
	__be16 proto = ((struct ethhdr *)data)->h_proto;
	if (ntohs(proto) >= 1536) { /* DIX II ethernet frame */
		pr_debug("ray_cs translate_frame DIX II\n");
		/* Copy LLC header to card buffer */
		memcpy_toio(&ptx->var, eth2_llc, sizeof(eth2_llc));
		memcpy_toio(((void __iomem *)&ptx->var) + sizeof(eth2_llc),
			    (UCHAR *) &proto, 2);
		if (proto == htons(ETH_P_AARP) || proto == htons(ETH_P_IPX)) {
			/* This is the selective translation table, only 2 entries */
			writeb(0xf8,
			       &((struct snaphdr_t __iomem *)ptx->var)->org[3]);
		}
		/* Copy body of ethernet packet without ethernet header */
		memcpy_toio((void __iomem *)&ptx->var +
			    sizeof(struct snaphdr_t), data + ETH_HLEN,
			    len - ETH_HLEN);
		return (int)sizeof(struct snaphdr_t) - ETH_HLEN;
	} else { /* already  802 type, and proto is length */
		pr_debug("ray_cs translate_frame 802\n");
		if (proto == htons(0xffff)) { /* evil netware IPX 802.3 without LLC */
			pr_debug("ray_cs translate_frame evil IPX\n");
			memcpy_toio(&ptx->var, data + ETH_HLEN, len - ETH_HLEN);
			return 0 - ETH_HLEN;
		}
		memcpy_toio(&ptx->var, data + ETH_HLEN, len - ETH_HLEN);
		return 0 - ETH_HLEN;
	}
	/* TBD do other frame types */
} /* end translate_frame */

/*===========================================================================*/
static void ray_build_header(ray_dev_t *local, struct tx_msg __iomem *ptx,
			     UCHAR msg_type, unsigned char *data)
{
	writeb(PROTOCOL_VER | msg_type, &ptx->mac.frame_ctl_1);
/*** IEEE 802.11 Address field assignments *************
		TODS	FROMDS	addr_1		addr_2		addr_3	addr_4
Adhoc		0	0	dest		src (terminal)	BSSID	N/A
AP to Terminal	0	1	dest		AP(BSSID)	source	N/A
Terminal to AP	1	0	AP(BSSID)	src (terminal)	dest	N/A
AP to AP	1	1	dest AP		src AP		dest	source
*******************************************************/
	if (local->net_type == ADHOC) {
		writeb(0, &ptx->mac.frame_ctl_2);
		memcpy_toio(ptx->mac.addr_1, ((struct ethhdr *)data)->h_dest,