aboutsummaryrefslogtreecommitdiffstats
path: root/drivers/input/touchscreen/elo.c
blob: 557d781719f12b631c6dd940b109c91be04cef9b (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
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
/*
 * Elo serial touchscreen driver
 *
 * Copyright (c) 2004 Vojtech Pavlik
 */

/*
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published by
 * the Free Software Foundation.
 */

/*
 * This driver can handle serial Elo touchscreens using either the Elo standard
 * 'E271-2210' 10-byte protocol, Elo legacy 'E281A-4002' 6-byte protocol, Elo
 * legacy 'E271-140' 4-byte protocol and Elo legacy 'E261-280' 3-byte protocol.
 */

#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#include <linux/ctype.h>

#define DRIVER_DESC	"Elo serial touchscreen driver"

MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");

/*
 * Definitions & global arrays.
 */

#define ELO_MAX_LENGTH		10

#define ELO10_PACKET_LEN	8
#define ELO10_TOUCH		0x03
#define ELO10_PRESSURE		0x80

#define ELO10_LEAD_BYTE		'U'

#define ELO10_ID_CMD		'i'

#define ELO10_TOUCH_PACKET	'T'
#define ELO10_ACK_PACKET	'A'
#define ELI10_ID_PACKET		'I'

/*
 * Per-touchscreen data.
 */

struct elo {
	struct input_dev *dev;
	struct serio *serio;
	struct mutex cmd_mutex;
	struct completion cmd_done;
	int id;
	int idx;
	unsigned char expected_packet;
	unsigned char csum;
	unsigned char data[ELO_MAX_LENGTH];
	unsigned char response[ELO10_PACKET_LEN];
	char phys[32];
};

static void elo_process_data_10(struct elo *elo, unsigned char data)
{
	struct input_dev *dev = elo->dev;

	elo->data[elo->idx] = data;
	switch (elo->idx++) {
		case 0:
			elo->csum = 0xaa;
			if (data != ELO10_LEAD_BYTE) {
				pr_debug("elo: unsynchronized data: 0x%02x\n", data);
				elo->idx = 0;
			}
			break;

		case 9:
			elo->idx = 0;
			if (data != elo->csum) {
				pr_debug("elo: bad checksum: 0x%02x, expected 0x%02x\n",
					 data, elo->csum);
				break;
			}
			if (elo->data[1] != elo->expected_packet) {
				if (elo->data[1] != ELO10_TOUCH_PACKET)
					pr_debug("elo: unexpected packet: 0x%02x\n",
						 elo->data[1]);
				break;
			}
			if (likely(elo->data[1] == ELO10_TOUCH_PACKET)) {
				input_report_abs(dev, ABS_X, (elo->data[4] << 8) | elo->data[3]);
				input_report_abs(dev, ABS_Y, (elo->data[6] << 8) | elo->data[5]);
				if (elo->data[2] & ELO10_PRESSURE)
					input_report_abs(dev, ABS_PRESSURE,
							(elo->data[8] << 8) | elo->data[7]);
				input_report_key(dev, BTN_TOUCH, elo->data[2] & ELO10_TOUCH);
				input_sync(dev);
			} else if (elo->data[1] == ELO10_ACK_PACKET) {
				if (elo->data[2] == '0')
					elo->expected_packet = ELO10_TOUCH_PACKET;
				complete(&elo->cmd_done);
			} else {
				memcpy(elo->response, &elo->data[1], ELO10_PACKET_LEN);
				elo->expected_packet = ELO10_ACK_PACKET;
			}
			break;
	}
	elo->csum += data;
}

static void elo_process_data_6(struct elo *elo, unsigned char data)
{
	struct input_dev *dev = elo->dev;

	elo->data[elo->idx] = data;

	switch (elo->idx++) {

		case 0: if ((data & 0xc0) != 0xc0) elo->idx = 0; break;
		case 1: if ((data & 0xc0) != 0x80) elo->idx = 0; break;
		case 2: if ((data & 0xc0) != 0x40) elo->idx = 0; break;

		case 3:
			if (data & 0xc0) {
				elo->idx = 0;
				break;
			}

			input_report_abs(dev, ABS_X, ((elo->data[0] & 0x3f) << 6) | (elo->data[1] & 0x3f));
			input_report_abs(dev, ABS_Y, ((elo->data[2] & 0x3f) << 6) | (elo->data[3] & 0x3f));

			if (elo->id == 2) {
				input_report_key(dev, BTN_TOUCH, 1);
				input_sync(dev);
				elo->idx = 0;
			}

			break;

		case 4:
			if (data) {
				input_sync(dev);
				elo->idx = 0;
			}
			break;

		case 5:
			if ((data & 0xf0) == 0) {
				input_report_abs(dev, ABS_PRESSURE, elo->data[5]);
				input_report_key(dev, BTN_TOUCH, !!elo->data[5]);
			}
			input_sync(dev);
			elo->idx = 0;
			break;
	}
}

static void elo_process_data_3(struct elo *elo, unsigned char data)
{
	struct input_dev *dev = elo->dev;

	elo->data[elo->idx] = data;

	switch (elo->idx++) {

		case 0:
			if ((data & 0x7f) != 0x01)
				elo->idx = 0;
			break;
		case 2:
			input_report_key(dev, BTN_TOUCH, !(elo->data[1] & 0x80));
			input_report_abs(dev, ABS_X, elo->data[1]);
			input_report_abs(dev, ABS_Y, elo->data[2]);
			input_sync(dev);
			elo->idx = 0;
			break;
	}
}

static irqreturn_t elo_interrupt(struct serio *serio,
		unsigned char data, unsigned int flags)
{
	struct elo *elo = serio_get_drvdata(serio);

	switch(elo->id) {
		case 0:
			elo_process_data_10(elo, data);
			break;

		case 1:
		case 2:
			elo_process_data_6(elo, data);
			break;

		case 3:
			elo_process_data_3(elo, data);
			break;
	}

	return IRQ_HANDLED;
}

static int elo_command_10(struct elo *elo, unsigned char *packet)
{
	int rc = -1;
	int i;
	unsigned char csum = 0xaa + ELO10_LEAD_BYTE;

	mutex_lock(&elo->cmd_mutex);

	serio_pause_rx(elo->serio);
	elo->expected_packet = toupper(packet[0]);
	init_completion(&elo->cmd_done);
	serio_continue_rx(elo->serio);

	if (serio_write(elo->serio, ELO10_LEAD_BYTE))
		goto out;

	for (i = 0; i < ELO10_PACKET_LEN; i++) {
		csum += packet[i];
		if (serio_write(elo->serio, packet[i]))
			goto out;
	}

	if (serio_write(elo->serio, csum))
		goto out;

	wait_for_completion_timeout(&elo->cmd_done, HZ);

	if (elo->expected_packet == ELO10_TOUCH_PACKET) {
		/* We are back in reporting mode, the command was ACKed */
		memcpy(packet, elo->response, ELO10_PACKET_LEN);
		rc = 0;
	}

 out:
	mutex_unlock(&elo->cmd_mutex);
	return rc;
}

static int elo_setup_10(struct elo *elo)
{
	static const char *elo_types[] = { "Accu", "Dura", "Intelli", "Carroll" };
	struct input_dev *dev = elo->dev;
	unsigned char packet[ELO10_PACKET_LEN] = { ELO10_ID_CMD };

	if (elo_command_10(elo, packet))
		return -1;

	dev->id.version = (packet[5] << 8) | packet[4];

	input_set_abs_params(dev, ABS_X, 96, 4000, 0, 0);
	input_set_abs_params(dev, ABS_Y, 96, 4000, 0, 0);
	if (packet[3] & ELO10_PRESSURE)
		input_set_abs_params(dev, ABS_PRESSURE, 0, 255, 0, 0);

	printk(KERN_INFO "elo: %sTouch touchscreen, fw: %02x.%02x, "
		"features: %x02x, controller: 0x%02x\n",
		elo_types[(packet[1] -'0') & 0x03],
		packet[5], packet[4], packet[3], packet[7]);

	return 0;
}

/*
 * elo_disconnect() is the opposite of elo_connect()
 */

static void elo_disconnect(struct serio *serio)
{
	struct elo *elo = serio_get_drvdata(serio);

	input_get_device(elo->dev);
	input_unregister_device(elo->dev);
	serio_close(serio);
	serio_set_drvdata(serio, NULL);
	input_put_device(elo->dev);
	kfree(elo);
}

/*
 * elo_connect() is the routine that is called when someone adds a
 * new serio device that supports Gunze protocol and registers it as
 * an input device.
 */

static int elo_connect(struct serio *serio, struct serio_driver *drv)
{
	struct elo *elo;
	struct input_dev *input_dev;
	int err;

	elo = kzalloc(sizeof(struct elo), GFP_KERNEL);
	input_dev = input_allocate_device();
	if (!elo || !input_dev) {
		err = -ENOMEM;
		goto fail1;
	}

	elo->serio = serio;
	elo->id = serio->id.id;
	elo->dev = input_dev;
	elo->expected_packet = ELO10_TOUCH_PACKET;
	mutex_init(&elo->cmd_mutex);
	init_completion(&elo->cmd_done);
	snprintf(elo->phys, sizeof(elo->phys), "%s/input0", serio->phys);

	input_dev->name = "Elo Serial TouchScreen";
	input_dev->phys = elo->phys;
	input_dev->id.bustype = BUS_RS232;
	input_dev->id.vendor = SERIO_ELO;
	input_dev->id.product = elo->id;
	input_dev->id.version = 0x0100;
	input_dev->dev.parent = &serio->dev;

	input_dev->evbit[0] = BIT(EV_KEY) | BIT(EV_ABS);
	input_dev->keybit[LONG(BTN_TOUCH)] = BIT(BTN_TOUCH);

	serio_set_drvdata(serio, elo);
	err = serio_open(serio, drv);
	if (err)
		goto fail2;

	switch (elo->id) {

		case 0: /* 10-byte protocol */
			if (elo_setup_10(elo))
				goto fail3;

			break;

		case 1: /* 6-byte protocol */
			input_set_abs_params(input_dev, ABS_PRESSURE, 0, 15, 0, 0);

		case 2: /* 4-byte protocol */
			input_set_abs_params(input_dev, ABS_X, 96, 4000, 0, 0);
			input_set_abs_params(input_dev, ABS_Y, 96, 4000, 0, 0);
			break;

		case 3: /* 3-byte protocol */
			input_set_abs_params(input_dev, ABS_X, 0, 255, 0, 0);
			input_set_abs_params(input_dev, ABS_Y, 0, 255, 0, 0);
			break;
	}

	err = input_register_device(elo->dev);
	if (err)
		goto fail3;

	return 0;

 fail3: serio_close(serio);
 fail2:	serio_set_drvdata(serio, NULL);
 fail1:	input_free_device(input_dev);
	kfree(elo);
	return err;
}

/*
 * The serio driver structure.
 */

static struct serio_device_id elo_serio_ids[] = {
	{
		.type	= SERIO_RS232,
		.proto	= SERIO_ELO,
		.id	= SERIO_ANY,
		.extra	= SERIO_ANY,
	},
	{ 0 }
};

MODULE_DEVICE_TABLE(serio, elo_serio_ids);

static struct serio_driver elo_drv = {
	.driver		= {
		.name	= "elo",
	},
	.description	= DRIVER_DESC,
	.id_table	= elo_serio_ids,
	.interrupt	= elo_interrupt,
	.connect	= elo_connect,
	.disconnect	= elo_disconnect,
};

/*
 * The functions for inserting/removing us as a module.
 */

static int __init elo_init(void)
{
	return serio_register_driver(&elo_drv);
}

static void __exit elo_exit(void)
{
	serio_unregister_driver(&elo_drv);
}

module_init(elo_init);
module_exit(elo_exit);
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



























































































































                                                                                                              


                                                                                    


















































































































































































































































                                                                                          
                    
                                  
      














































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                      
                                               






















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                            
                       

























                                                                                 












                                                                                           







































































































































































































                                                                                                             
                                  









































































                                                                                                                  
/*****************************************************************************/

/*
 *      sonicvibes.c  --  S3 Sonic Vibes audio driver.
 *
 *      Copyright (C) 1998-2001, 2003  Thomas Sailer (t.sailer@alumni.ethz.ch)
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * Special thanks to David C. Niemi
 *
 *
 * Module command line parameters:
 *   none so far
 *
 *
 *  Supported devices:
 *  /dev/dsp    standard /dev/dsp device, (mostly) OSS compatible
 *  /dev/mixer  standard /dev/mixer device, (mostly) OSS compatible
 *  /dev/midi   simple MIDI UART interface, no ioctl
 *
 *  The card has both an FM and a Wavetable synth, but I have to figure
 *  out first how to drive them...
 *
 *  Revision history
 *    06.05.1998   0.1   Initial release
 *    10.05.1998   0.2   Fixed many bugs, esp. ADC rate calculation
 *                       First stab at a simple midi interface (no bells&whistles)
 *    13.05.1998   0.3   Fix stupid cut&paste error: set_adc_rate was called instead of
 *                       set_dac_rate in the FMODE_WRITE case in sv_open
 *                       Fix hwptr out of bounds (now mpg123 works)
 *    14.05.1998   0.4   Don't allow excessive interrupt rates
 *    08.06.1998   0.5   First release using Alan Cox' soundcore instead of miscdevice
 *    03.08.1998   0.6   Do not include modversions.h
 *                       Now mixer behaviour can basically be selected between
 *                       "OSS documented" and "OSS actual" behaviour
 *    31.08.1998   0.7   Fix realplayer problems - dac.count issues
 *    10.12.1998   0.8   Fix drain_dac trying to wait on not yet initialized DMA
 *    16.12.1998   0.9   Fix a few f_file & FMODE_ bugs
 *    06.01.1999   0.10  remove the silly SA_INTERRUPT flag.
 *                       hopefully killed the egcs section type conflict
 *    12.03.1999   0.11  cinfo.blocks should be reset after GETxPTR ioctl.
 *                       reported by Johan Maes <joma@telindus.be>
 *    22.03.1999   0.12  return EAGAIN instead of EBUSY when O_NONBLOCK
 *                       read/write cannot be executed
 *    05.04.1999   0.13  added code to sv_read and sv_write which should detect
 *                       lockups of the sound chip and revive it. This is basically
 *                       an ugly hack, but at least applications using this driver
 *                       won't hang forever. I don't know why these lockups happen,
 *                       it might well be the motherboard chipset (an early 486 PCI
 *                       board with ALI chipset), since every busmastering 100MB
 *                       ethernet card I've tried (Realtek 8139 and Macronix tulip clone)
 *                       exhibit similar behaviour (they work for a couple of packets
 *                       and then lock up and can be revived by ifconfig down/up).
 *    07.04.1999   0.14  implemented the following ioctl's: SOUND_PCM_READ_RATE, 
 *                       SOUND_PCM_READ_CHANNELS, SOUND_PCM_READ_BITS; 
 *                       Alpha fixes reported by Peter Jones <pjones@redhat.com>
 *                       Note: dmaio hack might still be wrong on archs other than i386
 *    15.06.1999   0.15  Fix bad allocation bug.
 *                       Thanks to Deti Fliegl <fliegl@in.tum.de>
 *    28.06.1999   0.16  Add pci_set_master
 *    03.08.1999   0.17  adapt to Linus' new __setup/__initcall
 *                       added kernel command line options "sonicvibes=reverb" and "sonicvibesdmaio=dmaioaddr"
 *    12.08.1999   0.18  module_init/__setup fixes
 *    24.08.1999   0.19  get rid of the dmaio kludge, replace with allocate_resource
 *    31.08.1999   0.20  add spin_lock_init
 *                       use new resource allocation to allocate DDMA IO space
 *                       replaced current->state = x with set_current_state(x)
 *    03.09.1999   0.21  change read semantics for MIDI to match
 *                       OSS more closely; remove possible wakeup race
 *    28.10.1999   0.22  More waitqueue races fixed
 *    01.12.1999   0.23  New argument to allocate_resource
 *    07.12.1999   0.24  More allocate_resource semantics change
 *    08.01.2000   0.25  Prevent some ioctl's from returning bad count values on underrun/overrun;
 *                       Tim Janik's BSE (Bedevilled Sound Engine) found this
 *                       use Martin Mares' pci_assign_resource
 *    07.02.2000   0.26  Use pci_alloc_consistent and pci_register_driver
 *    21.11.2000   0.27  Initialize dma buffers in poll, otherwise poll may return a bogus mask
 *    12.12.2000   0.28  More dma buffer initializations, patch from
 *                       Tjeerd Mulder <tjeerd.mulder@fujitsu-siemens.com>
 *    31.01.2001   0.29  Register/Unregister gameport
 *                       Fix SETTRIGGER non OSS API conformity
 *    18.05.2001   0.30  PCI probing and error values cleaned up by Marcus
 *                       Meissner <mm@caldera.de>
 *    03.01.2003   0.31  open_mode fixes from Georg Acher <acher@in.tum.de>
 *
 */

/*****************************************************************************/
      
#include <linux/module.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/wait.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/sound.h>
#include <linux/slab.h>
#include <linux/soundcard.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/spinlock.h>
#include <linux/smp_lock.h>
#include <linux/gameport.h>

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

#include "dm.h"

#if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
#define SUPPORT_JOYSTICK 1
#endif

/* --------------------------------------------------------------------- */

#undef OSS_DOCUMENTED_MIXER_SEMANTICS

/* --------------------------------------------------------------------- */

#ifndef PCI_VENDOR_ID_S3
#define PCI_VENDOR_ID_S3             0x5333
#endif
#ifndef PCI_DEVICE_ID_S3_SONICVIBES
#define PCI_DEVICE_ID_S3_SONICVIBES  0xca00
#endif

#define SV_MAGIC  ((PCI_VENDOR_ID_S3<<16)|PCI_DEVICE_ID_S3_SONICVIBES)

#define SV_EXTENT_SB      0x10
#define SV_EXTENT_ENH     0x10
#define SV_EXTENT_SYNTH   0x4
#define SV_EXTENT_MIDI    0x4
#define SV_EXTENT_GAME    0x8
#define SV_EXTENT_DMA     0x10

/*
 * we are not a bridge and thus use a resource for DDMA that is used for bridges but
 * left empty for normal devices
 */
#define RESOURCE_SB       0
#define RESOURCE_ENH      1
#define RESOURCE_SYNTH    2
#define RESOURCE_MIDI     3
#define RESOURCE_GAME     4
#define RESOURCE_DDMA     7

#define SV_MIDI_DATA      0
#define SV_MIDI_COMMAND   1
#define SV_MIDI_STATUS    1

#define SV_DMA_ADDR0      0
#define SV_DMA_ADDR1      1
#define SV_DMA_ADDR2      2
#define SV_DMA_ADDR3      3
#define SV_DMA_COUNT0     4
#define SV_DMA_COUNT1     5
#define SV_DMA_COUNT2     6
#define SV_DMA_MODE       0xb
#define SV_DMA_RESET      0xd
#define SV_DMA_MASK       0xf

/*
 * DONT reset the DMA controllers unless you understand
 * the reset semantics. Assuming reset semantics as in
 * the 8237 does not work.
 */

#define DMA_MODE_AUTOINIT 0x10
#define DMA_MODE_READ     0x44    /* I/O to memory, no autoinit, increment, single mode */
#define DMA_MODE_WRITE    0x48    /* memory to I/O, no autoinit, increment, single mode */

#define SV_CODEC_CONTROL  0
#define SV_CODEC_INTMASK  1
#define SV_CODEC_STATUS   2
#define SV_CODEC_IADDR    4
#define SV_CODEC_IDATA    5

#define SV_CCTRL_RESET      0x80
#define SV_CCTRL_INTADRIVE  0x20
#define SV_CCTRL_WAVETABLE  0x08
#define SV_CCTRL_REVERB     0x04
#define SV_CCTRL_ENHANCED   0x01

#define SV_CINTMASK_DMAA    0x01
#define SV_CINTMASK_DMAC    0x04
#define SV_CINTMASK_SPECIAL 0x08
#define SV_CINTMASK_UPDOWN  0x40
#define SV_CINTMASK_MIDI    0x80

#define SV_CSTAT_DMAA       0x01
#define SV_CSTAT_DMAC	    0x04
#define SV_CSTAT_SPECIAL    0x08
#define SV_CSTAT_UPDOWN	    0x40
#define SV_CSTAT_MIDI	    0x80

#define SV_CIADDR_TRD       0x80
#define SV_CIADDR_MCE       0x40

/* codec indirect registers */
#define SV_CIMIX_ADCINL     0x00
#define SV_CIMIX_ADCINR     0x01
#define SV_CIMIX_AUX1INL    0x02
#define SV_CIMIX_AUX1INR    0x03
#define SV_CIMIX_CDINL      0x04
#define SV_CIMIX_CDINR      0x05
#define SV_CIMIX_LINEINL    0x06
#define SV_CIMIX_LINEINR    0x07
#define SV_CIMIX_MICIN      0x08
#define SV_CIMIX_SYNTHINL   0x0A
#define SV_CIMIX_SYNTHINR   0x0B
#define SV_CIMIX_AUX2INL    0x0C
#define SV_CIMIX_AUX2INR    0x0D
#define SV_CIMIX_ANALOGINL  0x0E
#define SV_CIMIX_ANALOGINR  0x0F
#define SV_CIMIX_PCMINL     0x10
#define SV_CIMIX_PCMINR     0x11

#define SV_CIGAMECONTROL    0x09
#define SV_CIDATAFMT        0x12
#define SV_CIENABLE         0x13
#define SV_CIUPDOWN         0x14
#define SV_CIREVISION       0x15
#define SV_CIADCOUTPUT      0x16
#define SV_CIDMAABASECOUNT1 0x18
#define SV_CIDMAABASECOUNT0 0x19
#define SV_CIDMACBASECOUNT1 0x1c
#define SV_CIDMACBASECOUNT0 0x1d
#define SV_CIPCMSR0         0x1e
#define SV_CIPCMSR1         0x1f
#define SV_CISYNTHSR0       0x20
#define SV_CISYNTHSR1       0x21
#define SV_CIADCCLKSOURCE   0x22
#define SV_CIADCALTSR       0x23
#define SV_CIADCPLLM        0x24
#define SV_CIADCPLLN        0x25
#define SV_CISYNTHPLLM      0x26
#define SV_CISYNTHPLLN      0x27
#define SV_CIUARTCONTROL    0x2a
#define SV_CIDRIVECONTROL   0x2b
#define SV_CISRSSPACE       0x2c
#define SV_CISRSCENTER      0x2d
#define SV_CIWAVETABLESRC   0x2e
#define SV_CIANALOGPWRDOWN  0x30
#define SV_CIDIGITALPWRDOWN 0x31


#define SV_CIMIX_ADCSRC_CD     0x20
#define SV_CIMIX_ADCSRC_DAC    0x40
#define SV_CIMIX_ADCSRC_AUX2   0x60
#define SV_CIMIX_ADCSRC_LINE   0x80
#define SV_CIMIX_ADCSRC_AUX1   0xa0
#define SV_CIMIX_ADCSRC_MIC    0xc0
#define SV_CIMIX_ADCSRC_MIXOUT 0xe0
#define SV_CIMIX_ADCSRC_MASK   0xe0

#define SV_CFMT_STEREO     0x01
#define SV_CFMT_16BIT      0x02
#define SV_CFMT_MASK       0x03
#define SV_CFMT_ASHIFT     0   
#define SV_CFMT_CSHIFT     4

static const unsigned sample_size[] = { 1, 2, 2, 4 };
static const unsigned sample_shift[] = { 0, 1, 1, 2 };

#define SV_CENABLE_PPE     0x4
#define SV_CENABLE_RE      0x2
#define SV_CENABLE_PE      0x1


/* MIDI buffer sizes */

#define MIDIINBUF  256
#define MIDIOUTBUF 256

#define FMODE_MIDI_SHIFT 2
#define FMODE_MIDI_READ  (FMODE_READ << FMODE_MIDI_SHIFT)
#define FMODE_MIDI_WRITE (FMODE_WRITE << FMODE_MIDI_SHIFT)

#define FMODE_DMFM 0x10

/* --------------------------------------------------------------------- */

struct sv_state {
	/* magic */
	unsigned int magic;

	/* list of sonicvibes devices */
	struct list_head devs;

	/* the corresponding pci_dev structure */
	struct pci_dev *dev;

	/* soundcore stuff */
	int dev_audio;
	int dev_mixer;
	int dev_midi;
	int dev_dmfm;

	/* hardware resources */
	unsigned long iosb, ioenh, iosynth, iomidi;  /* long for SPARC */
	unsigned int iodmaa, iodmac, irq;

        /* mixer stuff */
        struct {
                unsigned int modcnt;
#ifndef OSS_DOCUMENTED_MIXER_SEMANTICS
		unsigned short vol[13];
#endif /* OSS_DOCUMENTED_MIXER_SEMANTICS */
        } mix;

	/* wave stuff */
	unsigned int rateadc, ratedac;
	unsigned char fmt, enable;

	spinlock_t lock;
	struct semaphore open_sem;
	mode_t open_mode;
	wait_queue_head_t open_wait;

	struct dmabuf {
		void *rawbuf;
		dma_addr_t dmaaddr;
		unsigned buforder;
		unsigned numfrag;
		unsigned fragshift;
		unsigned hwptr, swptr;
		unsigned total_bytes;
		int count;
		unsigned error; /* over/underrun */
		wait_queue_head_t wait;
		/* redundant, but makes calculations easier */
		unsigned fragsize;
		unsigned dmasize;
		unsigned fragsamples;
		/* OSS stuff */
		unsigned mapped:1;
		unsigned ready:1;
		unsigned endcleared:1;
		unsigned enabled:1;
		unsigned ossfragshift;
		int ossmaxfrags;
		unsigned subdivision;
	} dma_dac, dma_adc;

	/* midi stuff */
	struct {
		unsigned ird, iwr, icnt;
		unsigned ord, owr, ocnt;
		wait_queue_head_t iwait;
		wait_queue_head_t owait;
		struct timer_list timer;
		unsigned char ibuf[MIDIINBUF];
		unsigned char obuf[MIDIOUTBUF];
	} midi;

#if SUPPORT_JOYSTICK
	struct gameport *gameport;
#endif
};

/* --------------------------------------------------------------------- */

static LIST_HEAD(devs);
static unsigned long wavetable_mem;

/* --------------------------------------------------------------------- */

static inline unsigned ld2(unsigned int x)
{
	unsigned r = 0;
	
	if (x >= 0x10000) {
		x >>= 16;
		r += 16;
	}
	if (x >= 0x100) {
		x >>= 8;
		r += 8;
	}
	if (x >= 0x10) {
		x >>= 4;
		r += 4;
	}
	if (x >= 4) {
		x >>= 2;
		r += 2;
	}
	if (x >= 2)
		r++;
	return r;
}

/*
 * hweightN: returns the hamming weight (i.e. the number
 * of bits set) of a N-bit word
 */

#ifdef hweight32
#undef hweight32
#endif

static inline unsigned int hweight32(unsigned int w)
{
        unsigned int res = (w & 0x55555555) + ((w >> 1) & 0x55555555);
        res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
        res = (res & 0x0F0F0F0F) + ((res >> 4) & 0x0F0F0F0F);
        res = (res & 0x00FF00FF) + ((res >> 8) & 0x00FF00FF);
        return (res & 0x0000FFFF) + ((res >> 16) & 0x0000FFFF);
}

/* --------------------------------------------------------------------- */

/*
 * Why use byte IO? Nobody knows, but S3 does it also in their Windows driver.
 */

#undef DMABYTEIO

static void set_dmaa(struct sv_state *s, unsigned int addr, unsigned int count)
{
#ifdef DMABYTEIO
	unsigned io = s->iodmaa, u;

	count--;
	for (u = 4; u > 0; u--, addr >>= 8, io++)
		outb(addr & 0xff, io);
	for (u = 3; u > 0; u--, count >>= 8, io++)
		outb(count & 0xff, io);
#else /* DMABYTEIO */
	count--;
	outl(addr, s->iodmaa + SV_DMA_ADDR0);
	outl(count, s->iodmaa + SV_DMA_COUNT0);
#endif /* DMABYTEIO */
	outb(0x18, s->iodmaa + SV_DMA_MODE);
}

static void set_dmac(struct sv_state *s, unsigned int addr, unsigned int count)
{
#ifdef DMABYTEIO
	unsigned io = s->iodmac, u;

	count >>= 1;
	count--;
	for (u = 4; u > 0; u--, addr >>= 8, io++)
		outb(addr & 0xff, io);
	for (u = 3; u > 0; u--, count >>= 8, io++)
		outb(count & 0xff, io);
#else /* DMABYTEIO */
	count >>= 1;
	count--;
	outl(addr, s->iodmac + SV_DMA_ADDR0);
	outl(count, s->iodmac + SV_DMA_COUNT0);
#endif /* DMABYTEIO */
	outb(0x14, s->iodmac + SV_DMA_MODE);
}

static inline unsigned get_dmaa(struct sv_state *s)
{
#ifdef DMABYTEIO
	unsigned io = s->iodmaa+6, v = 0, u;

	for (u = 3; u > 0; u--, io--) {
		v <<= 8;
		v |= inb(io);
	}
	return v + 1;
#else /* DMABYTEIO */
	return (inl(s->iodmaa + SV_DMA_COUNT0) & 0xffffff) + 1;
#endif /* DMABYTEIO */
}

static inline unsigned get_dmac(struct sv_state *s)
{
#ifdef DMABYTEIO
	unsigned io = s->iodmac+6, v = 0, u;

	for (u = 3; u > 0; u--, io--) {
		v <<= 8;
		v |= inb(io);
	}
	return (v + 1) << 1;
#else /* DMABYTEIO */
	return ((inl(s->iodmac + SV_DMA_COUNT0) & 0xffffff) + 1) << 1;
#endif /* DMABYTEIO */
}

static void wrindir(struct sv_state *s, unsigned char idx, unsigned char data)
{
	outb(idx & 0x3f, s->ioenh + SV_CODEC_IADDR);
	udelay(10);
	outb(data, s->ioenh + SV_CODEC_IDATA);
	udelay(10);
}

static unsigned char rdindir(struct sv_state *s, unsigned char idx)
{
	unsigned char v;

	outb(idx & 0x3f, s->ioenh + SV_CODEC_IADDR);
	udelay(10);
	v = inb(s->ioenh + SV_CODEC_IDATA);
	udelay(10);
	return v;
}

static void set_fmt(struct sv_state *s, unsigned char mask, unsigned char data)
{
	unsigned long flags;

	spin_lock_irqsave(&s->lock, flags);
	outb(SV_CIDATAFMT | SV_CIADDR_MCE, s->ioenh + SV_CODEC_IADDR);
	if (mask) {
		s->fmt = inb(s->ioenh + SV_CODEC_IDATA);
		udelay(10);
	}
	s->fmt = (s->fmt & mask) | data;
	outb(s->fmt, s->ioenh + SV_CODEC_IDATA);
	udelay(10);
	outb(0, s->ioenh + SV_CODEC_IADDR);
	spin_unlock_irqrestore(&s->lock, flags);
	udelay(10);
}

static void frobindir(struct sv_state *s, unsigned char idx, unsigned char mask, unsigned char data)
{
	outb(idx & 0x3f, s->ioenh + SV_CODEC_IADDR);
	udelay(10);
	outb((inb(s->ioenh + SV_CODEC_IDATA) & mask) ^ data, s->ioenh + SV_CODEC_IDATA);
	udelay(10);
}

#define REFFREQUENCY  24576000
#define ADCMULT 512
#define FULLRATE 48000

static unsigned setpll(struct sv_state *s, unsigned char reg, unsigned rate)
{
	unsigned long flags;
	unsigned char r, m=0, n=0;
	unsigned xm, xn, xr, xd, metric = ~0U;
	/* the warnings about m and n used uninitialized are bogus and may safely be ignored */

	if (rate < 625000/ADCMULT)
		rate = 625000/ADCMULT;
	if (rate > 150000000/ADCMULT)
		rate = 150000000/ADCMULT;
	/* slight violation of specs, needed for continuous sampling rates */
	for (r = 0; rate < 75000000/ADCMULT; r += 0x20, rate <<= 1);
	for (xn = 3; xn < 35; xn++)
		for (xm = 3; xm < 130; xm++) {
			xr = REFFREQUENCY/ADCMULT * xm / xn;
			xd = abs((signed)(xr - rate));
			if (xd < metric) {
				metric = xd;
				m = xm - 2;
				n = xn - 2;
			}
		}
	reg &= 0x3f;
	spin_lock_irqsave(&s->lock, flags);
	outb(reg, s->ioenh + SV_CODEC_IADDR);
	udelay(10);
	outb(m, s->ioenh + SV_CODEC_IDATA);
	udelay(10);
	outb(reg+1, s->ioenh + SV_CODEC_IADDR);
	udelay(10);
	outb(r | n, s->ioenh + SV_CODEC_IDATA);
	spin_unlock_irqrestore(&s->lock, flags);
	udelay(10);
	return (REFFREQUENCY/ADCMULT * (m + 2) / (n + 2)) >> ((r >> 5) & 7);
}

#if 0

static unsigned getpll(struct sv_state *s, unsigned char reg)
{
	unsigned long flags;
	unsigned char m, n;

	reg &= 0x3f;
	spin_lock_irqsave(&s->lock, flags);
	outb(reg, s->ioenh + SV_CODEC_IADDR);
	udelay(10);
	m = inb(s->ioenh + SV_CODEC_IDATA);
	udelay(10);
	outb(reg+1, s->ioenh + SV_CODEC_IADDR);
	udelay(10);
	n = inb(s->ioenh + SV_CODEC_IDATA);
	spin_unlock_irqrestore(&s->lock, flags);
	udelay(10);
	return (REFFREQUENCY/ADCMULT * (m + 2) / ((n & 0x1f) + 2)) >> ((n >> 5) & 7);
}

#endif

static void set_dac_rate(struct sv_state *s, unsigned rate)
{
	unsigned div;
	unsigned long flags;

	if (rate > 48000)
		rate = 48000;
	if (rate < 4000)
		rate = 4000;
	div = (rate * 65536 + FULLRATE/2) / FULLRATE;
	if (div > 65535)
		div = 65535;
	spin_lock_irqsave(&s->lock, flags);
	wrindir(s, SV_CIPCMSR1, div >> 8);
	wrindir(s, SV_CIPCMSR0, div);
	spin_unlock_irqrestore(&s->lock, flags);
	s->ratedac = (div * FULLRATE + 32768) / 65536;
}

static void set_adc_rate(struct sv_state *s, unsigned rate)
{
	unsigned long flags;
	unsigned rate1, rate2, div;

	if (rate > 48000)
		rate = 48000;
	if (rate < 4000)
		rate = 4000;
	rate1 = setpll(s, SV_CIADCPLLM, rate);
	div = (48000 + rate/2) / rate;
	if (div > 8)
		div = 8;
	rate2 = (48000 + div/2) / div;
	spin_lock_irqsave(&s->lock, flags);
	wrindir(s, SV_CIADCALTSR, (div-1) << 4);
	if (abs((signed)(rate-rate2)) <= abs((signed)(rate-rate1))) {
		wrindir(s, SV_CIADCCLKSOURCE, 0x10);
		s->rateadc = rate2;
	} else {
		wrindir(s, SV_CIADCCLKSOURCE, 0x00);
		s->rateadc = rate1;
	}
	spin_unlock_irqrestore(&s->lock, flags);
}

/* --------------------------------------------------------------------- */

static inline void stop_adc(struct sv_state *s)
{
	unsigned long flags;

	spin_lock_irqsave(&s->lock, flags);
	s->enable &= ~SV_CENABLE_RE;
	wrindir(s, SV_CIENABLE, s->enable);
	spin_unlock_irqrestore(&s->lock, flags);
}	

static inline void stop_dac(struct sv_state *s)
{
	unsigned long flags;

	spin_lock_irqsave(&s->lock, flags);
	s->enable &= ~(SV_CENABLE_PPE | SV_CENABLE_PE);
	wrindir(s, SV_CIENABLE, s->enable);
	spin_unlock_irqrestore(&s->lock, flags);
}	

static void start_dac(struct sv_state *s)
{
	unsigned long flags;

	spin_lock_irqsave(&s->lock, flags);
	if ((s->dma_dac.mapped || s->dma_dac.count > 0) && s->dma_dac.ready) {
		s->enable = (s->enable & ~SV_CENABLE_PPE) | SV_CENABLE_PE;
		wrindir(s, SV_CIENABLE, s->enable);
	}
	spin_unlock_irqrestore(&s->lock, flags);
}	

static void start_adc(struct sv_state *s)
{
	unsigned long flags;

	spin_lock_irqsave(&s->lock, flags);
	if ((s->dma_adc.mapped || s->dma_adc.count < (signed)(s->dma_adc.dmasize - 2*s->dma_adc.fragsize)) 
	    && s->dma_adc.ready) {
		s->enable |= SV_CENABLE_RE;
		wrindir(s, SV_CIENABLE, s->enable);
	}
	spin_unlock_irqrestore(&s->lock, flags);
}	

/* --------------------------------------------------------------------- */

#define DMABUF_DEFAULTORDER (17-PAGE_SHIFT)
#define DMABUF_MINORDER 1

static void dealloc_dmabuf(struct sv_state *s, struct dmabuf *db)
{
	struct page *page, *pend;

	if (db->rawbuf) {
		/* undo marking the pages as reserved */
		pend = virt_to_page(db->rawbuf + (PAGE_SIZE << db->buforder) - 1);
		for (page = virt_to_page(db->rawbuf); page <= pend; page++)
			ClearPageReserved(page);
		pci_free_consistent(s->dev, PAGE_SIZE << db->buforder, db->rawbuf, db->dmaaddr);
	}
	db->rawbuf = NULL;
	db->mapped = db->ready = 0;
}


/* DMAA is used for playback, DMAC is used for recording */

static int prog_dmabuf(struct sv_state *s, unsigned rec)
{
	struct dmabuf *db = rec ? &s->dma_adc : &s->dma_dac;
	unsigned rate = rec ? s->rateadc : s->ratedac;
	int order;
	unsigned bytepersec;
	unsigned bufs;
	struct page *page, *pend;
	unsigned char fmt;
	unsigned long flags;

	spin_lock_irqsave(&s->lock, flags);
	fmt = s->fmt;
	if (rec) {
		s->enable &= ~SV_CENABLE_RE;
		fmt >>= SV_CFMT_CSHIFT;
	} else {
		s->enable &= ~SV_CENABLE_PE;
		fmt >>= SV_CFMT_ASHIFT;
	}
	wrindir(s, SV_CIENABLE, s->enable);
	spin_unlock_irqrestore(&s->lock, flags);
	fmt &= SV_CFMT_MASK;
	db->hwptr = db->swptr = db->total_bytes = db->count = db->error = db->endcleared = 0;
	if (!db->rawbuf) {
		db->ready = db->mapped = 0;
		for (order = DMABUF_DEFAULTORDER; order >= DMABUF_MINORDER; order--)
			if ((db->rawbuf = pci_alloc_consistent(s->dev, PAGE_SIZE << order, &db->dmaaddr)))
				break;
		if (!db->rawbuf)
			return -ENOMEM;
		db->buforder = order;
		if ((virt_to_bus(db->rawbuf) ^ (virt_to_bus(db->rawbuf) + (PAGE_SIZE << db->buforder) - 1)) & ~0xffff)
			printk(KERN_DEBUG "sv: DMA buffer crosses 64k boundary: busaddr 0x%lx  size %ld\n", 
			       virt_to_bus(db->rawbuf), PAGE_SIZE << db->buforder);
		if ((virt_to_bus(db->rawbuf) + (PAGE_SIZE << db->buforder) - 1) & ~0xffffff)
			printk(KERN_DEBUG "sv: DMA buffer beyond 16MB: busaddr 0x%lx  size %ld\n", 
			       virt_to_bus(db->rawbuf), PAGE_SIZE << db->buforder);
		/* now mark the pages as reserved; otherwise remap_pfn_range doesn't do what we want */
		pend = virt_to_page(db->rawbuf + (PAGE_SIZE << db->buforder) - 1);
		for (page = virt_to_page(db->rawbuf); page <= pend; page++)
			SetPageReserved(page);
	}
	bytepersec = rate << sample_shift[fmt];
	bufs = PAGE_SIZE << db->buforder;
	if (db->ossfragshift) {
		if ((1000 << db->ossfragshift) < bytepersec)
			db->fragshift = ld2(bytepersec/1000);
		else
			db->fragshift = db->ossfragshift;
	} else {
		db->fragshift = ld2(bytepersec/100/(db->subdivision ? db->subdivision : 1));
		if (db->fragshift < 3)
			db->fragshift = 3;
	}
	db->numfrag = bufs >> db->fragshift;
	while (db->numfrag < 4 && db->fragshift > 3) {
		db->fragshift--;
		db->numfrag = bufs >> db->fragshift;
	}
	db->fragsize = 1 << db->fragshift;
	if (db->ossmaxfrags >= 4 && db->ossmaxfrags < db->numfrag)
		db->numfrag = db->ossmaxfrags;
	db->fragsamples = db->fragsize >> sample_shift[fmt];
	db->dmasize = db->numfrag << db->fragshift;
	memset(db->rawbuf, (fmt & SV_CFMT_16BIT) ? 0 : 0x80, db->dmasize);
	spin_lock_irqsave(&s->lock, flags);
	if (rec) {
		set_dmac(s, db->dmaaddr, db->numfrag << db->fragshift);
		/* program enhanced mode registers */
		wrindir(s, SV_CIDMACBASECOUNT1, (db->fragsamples-1) >> 8);
		wrindir(s, SV_CIDMACBASECOUNT0, db->fragsamples-1);
	} else {
		set_dmaa(s, db->dmaaddr, db->numfrag << db->fragshift);
		/* program enhanced mode registers */
		wrindir(s, SV_CIDMAABASECOUNT1, (db->fragsamples-1) >> 8);
		wrindir(s, SV_CIDMAABASECOUNT0, db->fragsamples-1);
	}
	spin_unlock_irqrestore(&s->lock, flags);
	db->enabled = 1;
	db->ready = 1;
	return 0;
}

static inline void clear_advance(struct sv_state *s)
{
	unsigned char c = (s->fmt & (SV_CFMT_16BIT << SV_CFMT_ASHIFT)) ? 0 : 0x80;
	unsigned char *buf = s->dma_dac.rawbuf;
	unsigned bsize = s->dma_dac.dmasize;
	unsigned bptr = s->dma_dac.swptr;
	unsigned len = s->dma_dac.fragsize;

	if (bptr + len > bsize) {
		unsigned x = bsize - bptr;
		memset(buf + bptr, c, x);
		bptr = 0;
		len -= x;
	}
	memset(buf + bptr, c, len);
}

/* call with spinlock held! */
static void sv_update_ptr(struct sv_state *s)
{
	unsigned hwptr;
	int diff;

	/* update ADC pointer */
	if (s->dma_adc.ready) {
		hwptr = (s->dma_adc.dmasize - get_dmac(s)) % s->dma_adc.dmasize;
		diff = (s->dma_adc.dmasize + hwptr - s->dma_adc.hwptr) % s->dma_adc.dmasize;
		s->dma_adc.hwptr = hwptr;
		s->dma_adc.total_bytes += diff;
		s->dma_adc.count += diff;
		if (s->dma_adc.count >= (signed)s->dma_adc.fragsize) 
			wake_up(&s->dma_adc.wait);
		if (!s->dma_adc.mapped) {
			if (s->dma_adc.count > (signed)(s->dma_adc.dmasize - ((3 * s->dma_adc.fragsize) >> 1))) {
				s->enable &= ~SV_CENABLE_RE;
				wrindir(s, SV_CIENABLE, s->enable);
				s->dma_adc.error++;
			}
		}
	}
	/* update DAC pointer */
	if (s->dma_dac.ready) {
		hwptr = (s->dma_dac.dmasize - get_dmaa(s)) % s->dma_dac.dmasize;
		diff = (s->dma_dac.dmasize + hwptr - s->dma_dac.hwptr) % s->dma_dac.dmasize;
		s->dma_dac.hwptr = hwptr;
		s->dma_dac.total_bytes += diff;
		if (s->dma_dac.mapped) {
			s->dma_dac.count += diff;
			if (s->dma_dac.count >= (signed)s->dma_dac.fragsize)
				wake_up(&s->dma_dac.wait);
		} else {
			s->dma_dac.count -= diff;