Linux Audio

Check our new training course

Loading...
v6.2
  1// SPDX-License-Identifier: GPL-2.0-or-later
  2/*
  3 *  Copyright (c) 1998-2005 Vojtech Pavlik
  4 */
  5
  6/*
  7 * Microsoft SideWinder joystick family driver for Linux
  8 */
  9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 10#include <linux/delay.h>
 11#include <linux/kernel.h>
 12#include <linux/module.h>
 13#include <linux/slab.h>
 14#include <linux/input.h>
 15#include <linux/gameport.h>
 16#include <linux/jiffies.h>
 17
 18#define DRIVER_DESC	"Microsoft SideWinder joystick family driver"
 19
 20MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
 21MODULE_DESCRIPTION(DRIVER_DESC);
 22MODULE_LICENSE("GPL");
 23
 24/*
 25 * These are really magic values. Changing them can make a problem go away,
 26 * as well as break everything.
 27 */
 28
 29#undef SW_DEBUG
 30#undef SW_DEBUG_DATA
 31
 32#define SW_START	600	/* The time we wait for the first bit [600 us] */
 33#define SW_STROBE	60	/* Max time per bit [60 us] */
 34#define SW_TIMEOUT	6	/* Wait for everything to settle [6 ms] */
 35#define SW_KICK		45	/* Wait after A0 fall till kick [45 us] */
 36#define SW_END		8	/* Number of bits before end of packet to kick */
 37#define SW_FAIL		16	/* Number of packet read errors to fail and reinitialize */
 38#define SW_BAD		2	/* Number of packet read errors to switch off 3d Pro optimization */
 39#define SW_OK		64	/* Number of packet read successes to switch optimization back on */
 40#define SW_LENGTH	512	/* Max number of bits in a packet */
 41
 42#ifdef SW_DEBUG
 43#define dbg(format, arg...) printk(KERN_DEBUG __FILE__ ": " format "\n" , ## arg)
 44#else
 45#define dbg(format, arg...) do {} while (0)
 46#endif
 47
 48/*
 49 * SideWinder joystick types ...
 50 */
 51
 52#define SW_ID_3DP	0
 53#define SW_ID_GP	1
 54#define SW_ID_PP	2
 55#define SW_ID_FFP	3
 56#define SW_ID_FSP	4
 57#define SW_ID_FFW	5
 58
 59/*
 60 * Names, buttons, axes ...
 61 */
 62
 63static char *sw_name[] = {	"3D Pro", "GamePad", "Precision Pro", "Force Feedback Pro", "FreeStyle Pro",
 64				"Force Feedback Wheel" };
 65
 66static char sw_abs[][7] = {
 67	{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
 68	{ ABS_X, ABS_Y },
 69	{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
 70	{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
 71	{ ABS_X, ABS_Y,         ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
 72	{ ABS_RX, ABS_RUDDER,   ABS_THROTTLE }};
 73
 74static char sw_bit[][7] = {
 75	{ 10, 10,  9, 10,  1,  1 },
 76	{  1,  1                 },
 77	{ 10, 10,  6,  7,  1,  1 },
 78	{ 10, 10,  6,  7,  1,  1 },
 79	{ 10, 10,  6,  1,  1     },
 80	{ 10,  7,  7,  1,  1     }};
 81
 82static short sw_btn[][12] = {
 83	{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_THUMB2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_MODE },
 84	{ BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_START, BTN_MODE },
 85	{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_SELECT },
 86	{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_SELECT },
 87	{ BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_START, BTN_MODE, BTN_SELECT },
 88	{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_THUMB2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4 }};
 89
 90static struct {
 91	int x;
 92	int y;
 93} sw_hat_to_axis[] = {{ 0, 0}, { 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}};
 94
 95struct sw {
 96	struct gameport *gameport;
 97	struct input_dev *dev[4];
 98	char name[64];
 99	char phys[4][32];
100	int length;
101	int type;
102	int bits;
103	int number;
104	int fail;
105	int ok;
106	int reads;
107	int bads;
108};
109
110/*
111 * sw_read_packet() is a function which reads either a data packet, or an
112 * identification packet from a SideWinder joystick. The protocol is very,
113 * very, very braindamaged. Microsoft patented it in US patent #5628686.
114 */
115
116static int sw_read_packet(struct gameport *gameport, unsigned char *buf, int length, int id)
117{
118	unsigned long flags;
119	int timeout, bitout, sched, i, kick, start, strobe;
120	unsigned char pending, u, v;
121
122	i = -id;						/* Don't care about data, only want ID */
123	timeout = id ? gameport_time(gameport, SW_TIMEOUT * 1000) : 0; /* Set up global timeout for ID packet */
124	kick = id ? gameport_time(gameport, SW_KICK) : 0;	/* Set up kick timeout for ID packet */
125	start = gameport_time(gameport, SW_START);
126	strobe = gameport_time(gameport, SW_STROBE);
127	bitout = start;
128	pending = 0;
129	sched = 0;
130
131        local_irq_save(flags);					/* Quiet, please */
132
133	gameport_trigger(gameport);				/* Trigger */
134	v = gameport_read(gameport);
135
136	do {
137		bitout--;
138		u = v;
139		v = gameport_read(gameport);
140	} while (!(~v & u & 0x10) && (bitout > 0));		/* Wait for first falling edge on clock */
141
142	if (bitout > 0)
143		bitout = strobe;				/* Extend time if not timed out */
144
145	while ((timeout > 0 || bitout > 0) && (i < length)) {
146
147		timeout--;
148		bitout--;					/* Decrement timers */
149		sched--;
150
151		u = v;
152		v = gameport_read(gameport);
153
154		if ((~u & v & 0x10) && (bitout > 0)) {		/* Rising edge on clock - data bit */
155			if (i >= 0)				/* Want this data */
156				buf[i] = v >> 5;		/* Store it */
157			i++;					/* Advance index */
158			bitout = strobe;			/* Extend timeout for next bit */
159		}
160
161		if (kick && (~v & u & 0x01)) {			/* Falling edge on axis 0 */
162			sched = kick;				/* Schedule second trigger */
163			kick = 0;				/* Don't schedule next time on falling edge */
164			pending = 1;				/* Mark schedule */
165		}
166
167		if (pending && sched < 0 && (i > -SW_END)) {	/* Second trigger time */
168			gameport_trigger(gameport);		/* Trigger */
169			bitout = start;				/* Long bit timeout */
170			pending = 0;				/* Unmark schedule */
171			timeout = 0;				/* Switch from global to bit timeouts */
172		}
173	}
174
175	local_irq_restore(flags);					/* Done - relax */
176
177#ifdef SW_DEBUG_DATA
178	{
179		int j;
180		printk(KERN_DEBUG "sidewinder.c: Read %d triplets. [", i);
181		for (j = 0; j < i; j++) printk("%d", buf[j]);
182		printk("]\n");
183	}
184#endif
185
186	return i;
187}
188
189/*
190 * sw_get_bits() and GB() compose bits from the triplet buffer into a __u64.
191 * Parameter 'pos' is bit number inside packet where to start at, 'num' is number
192 * of bits to be read, 'shift' is offset in the resulting __u64 to start at, bits
193 * is number of bits per triplet.
194 */
195
196#define GB(pos,num) sw_get_bits(buf, pos, num, sw->bits)
197
198static __u64 sw_get_bits(unsigned char *buf, int pos, int num, char bits)
199{
200	__u64 data = 0;
201	int tri = pos % bits;						/* Start position */
202	int i   = pos / bits;
203	int bit = 0;
204
205	while (num--) {
206		data |= (__u64)((buf[i] >> tri++) & 1) << bit++;	/* Transfer bit */
207		if (tri == bits) {
208			i++;						/* Next triplet */
209			tri = 0;
210		}
211	}
212
213	return data;
214}
215
216/*
217 * sw_init_digital() initializes a SideWinder 3D Pro joystick
218 * into digital mode.
219 */
220
221static void sw_init_digital(struct gameport *gameport)
222{
223	static const int seq[] = { 140, 140+725, 140+300, 0 };
224	unsigned long flags;
225	int i, t;
226
227        local_irq_save(flags);
228
229	i = 0;
230        do {
231                gameport_trigger(gameport);			/* Trigger */
232		t = gameport_time(gameport, SW_TIMEOUT * 1000);
233		while ((gameport_read(gameport) & 1) && t) t--;	/* Wait for axis to fall back to 0 */
234                udelay(seq[i]);					/* Delay magic time */
235        } while (seq[++i]);
236
237	gameport_trigger(gameport);				/* Last trigger */
238
239	local_irq_restore(flags);
240}
241
242/*
243 * sw_parity() computes parity of __u64
244 */
245
246static int sw_parity(__u64 t)
247{
248	int x = t ^ (t >> 32);
249
250	x ^= x >> 16;
251	x ^= x >> 8;
252	x ^= x >> 4;
253	x ^= x >> 2;
254	x ^= x >> 1;
255	return x & 1;
256}
257
258/*
259 * sw_ccheck() checks synchronization bits and computes checksum of nibbles.
260 */
261
262static int sw_check(__u64 t)
263{
264	unsigned char sum = 0;
265
266	if ((t & 0x8080808080808080ULL) ^ 0x80)			/* Sync */
267		return -1;
268
269	while (t) {						/* Sum */
270		sum += t & 0xf;
271		t >>= 4;
272	}
273
274	return sum & 0xf;
275}
276
277/*
278 * sw_parse() analyzes SideWinder joystick data, and writes the results into
279 * the axes and buttons arrays.
280 */
281
282static int sw_parse(unsigned char *buf, struct sw *sw)
283{
284	int hat, i, j;
285	struct input_dev *dev;
286
287	switch (sw->type) {
288
289		case SW_ID_3DP:
290
291			if (sw_check(GB(0,64)) || (hat = (GB(6,1) << 3) | GB(60,3)) > 8)
292				return -1;
293
294			dev = sw->dev[0];
295
296			input_report_abs(dev, ABS_X,        (GB( 3,3) << 7) | GB(16,7));
297			input_report_abs(dev, ABS_Y,        (GB( 0,3) << 7) | GB(24,7));
298			input_report_abs(dev, ABS_RZ,       (GB(35,2) << 7) | GB(40,7));
299			input_report_abs(dev, ABS_THROTTLE, (GB(32,3) << 7) | GB(48,7));
300
301			input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
302			input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
303
304			for (j = 0; j < 7; j++)
305				input_report_key(dev, sw_btn[SW_ID_3DP][j], !GB(j+8,1));
306
307			input_report_key(dev, BTN_BASE4, !GB(38,1));
308			input_report_key(dev, BTN_BASE5, !GB(37,1));
309
310			input_sync(dev);
311
312			return 0;
313
314		case SW_ID_GP:
315
316			for (i = 0; i < sw->number; i ++) {
317
318				if (sw_parity(GB(i*15,15)))
319					return -1;
320
321				input_report_abs(sw->dev[i], ABS_X, GB(i*15+3,1) - GB(i*15+2,1));
322				input_report_abs(sw->dev[i], ABS_Y, GB(i*15+0,1) - GB(i*15+1,1));
323
324				for (j = 0; j < 10; j++)
325					input_report_key(sw->dev[i], sw_btn[SW_ID_GP][j], !GB(i*15+j+4,1));
326
327				input_sync(sw->dev[i]);
328			}
329
330			return 0;
331
332		case SW_ID_PP:
333		case SW_ID_FFP:
334
335			if (!sw_parity(GB(0,48)) || (hat = GB(42,4)) > 8)
336				return -1;
337
338			dev = sw->dev[0];
339			input_report_abs(dev, ABS_X,        GB( 9,10));
340			input_report_abs(dev, ABS_Y,        GB(19,10));
341			input_report_abs(dev, ABS_RZ,       GB(36, 6));
342			input_report_abs(dev, ABS_THROTTLE, GB(29, 7));
343
344			input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
345			input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
346
347			for (j = 0; j < 9; j++)
348				input_report_key(dev, sw_btn[SW_ID_PP][j], !GB(j,1));
349
350			input_sync(dev);
351
352			return 0;
353
354		case SW_ID_FSP:
355
356			if (!sw_parity(GB(0,43)) || (hat = GB(28,4)) > 8)
357				return -1;
358
359			dev = sw->dev[0];
360			input_report_abs(dev, ABS_X,        GB( 0,10));
361			input_report_abs(dev, ABS_Y,        GB(16,10));
362			input_report_abs(dev, ABS_THROTTLE, GB(32, 6));
363
364			input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
365			input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
366
367			for (j = 0; j < 6; j++)
368				input_report_key(dev, sw_btn[SW_ID_FSP][j], !GB(j+10,1));
369
370			input_report_key(dev, BTN_TR,     !GB(26,1));
371			input_report_key(dev, BTN_START,  !GB(27,1));
372			input_report_key(dev, BTN_MODE,   !GB(38,1));
373			input_report_key(dev, BTN_SELECT, !GB(39,1));
374
375			input_sync(dev);
376
377			return 0;
378
379		case SW_ID_FFW:
380
381			if (!sw_parity(GB(0,33)))
382				return -1;
383
384			dev = sw->dev[0];
385			input_report_abs(dev, ABS_RX,       GB( 0,10));
386			input_report_abs(dev, ABS_RUDDER,   GB(10, 6));
387			input_report_abs(dev, ABS_THROTTLE, GB(16, 6));
388
389			for (j = 0; j < 8; j++)
390				input_report_key(dev, sw_btn[SW_ID_FFW][j], !GB(j+22,1));
391
392			input_sync(dev);
393
394			return 0;
395	}
396
397	return -1;
398}
399
400/*
401 * sw_read() reads SideWinder joystick data, and reinitializes
402 * the joystick in case of persistent problems. This is the function that is
403 * called from the generic code to poll the joystick.
404 */
405
406static int sw_read(struct sw *sw)
407{
408	unsigned char buf[SW_LENGTH];
409	int i;
410
411	i = sw_read_packet(sw->gameport, buf, sw->length, 0);
412
413	if (sw->type == SW_ID_3DP && sw->length == 66 && i != 66) {		/* Broken packet, try to fix */
414
415		if (i == 64 && !sw_check(sw_get_bits(buf,0,64,1))) {		/* Last init failed, 1 bit mode */
416			printk(KERN_WARNING "sidewinder.c: Joystick in wrong mode on %s"
417				" - going to reinitialize.\n", sw->gameport->phys);
418			sw->fail = SW_FAIL;					/* Reinitialize */
419			i = 128;						/* Bogus value */
420		}
421
422		if (i < 66 && GB(0,64) == GB(i*3-66,64))			/* 1 == 3 */
423			i = 66;							/* Everything is fine */
424
425		if (i < 66 && GB(0,64) == GB(66,64))				/* 1 == 2 */
426			i = 66;							/* Everything is fine */
427
428		if (i < 66 && GB(i*3-132,64) == GB(i*3-66,64)) {		/* 2 == 3 */
429			memmove(buf, buf + i - 22, 22);				/* Move data */
430			i = 66;							/* Carry on */
431		}
432	}
433
434	if (i == sw->length && !sw_parse(buf, sw)) {				/* Parse data */
435
436		sw->fail = 0;
437		sw->ok++;
438
439		if (sw->type == SW_ID_3DP && sw->length == 66			/* Many packets OK */
440			&& sw->ok > SW_OK) {
441
442			printk(KERN_INFO "sidewinder.c: No more trouble on %s"
443				" - enabling optimization again.\n", sw->gameport->phys);
444			sw->length = 22;
445		}
446
447		return 0;
448	}
449
450	sw->ok = 0;
451	sw->fail++;
452
453	if (sw->type == SW_ID_3DP && sw->length == 22 && sw->fail > SW_BAD) {	/* Consecutive bad packets */
454
455		printk(KERN_INFO "sidewinder.c: Many bit errors on %s"
456			" - disabling optimization.\n", sw->gameport->phys);
457		sw->length = 66;
458	}
459
460	if (sw->fail < SW_FAIL)
461		return -1;							/* Not enough, don't reinitialize yet */
462
463	printk(KERN_WARNING "sidewinder.c: Too many bit errors on %s"
464		" - reinitializing joystick.\n", sw->gameport->phys);
465
466	if (!i && sw->type == SW_ID_3DP) {					/* 3D Pro can be in analog mode */
467		mdelay(3 * SW_TIMEOUT);
468		sw_init_digital(sw->gameport);
469	}
470
471	mdelay(SW_TIMEOUT);
472	i = sw_read_packet(sw->gameport, buf, SW_LENGTH, 0);			/* Read normal data packet */
473	mdelay(SW_TIMEOUT);
474	sw_read_packet(sw->gameport, buf, SW_LENGTH, i);			/* Read ID packet, this initializes the stick */
475
476	sw->fail = SW_FAIL;
477
478	return -1;
479}
480
481static void sw_poll(struct gameport *gameport)
482{
483	struct sw *sw = gameport_get_drvdata(gameport);
484
485	sw->reads++;
486	if (sw_read(sw))
487		sw->bads++;
488}
489
490static int sw_open(struct input_dev *dev)
491{
492	struct sw *sw = input_get_drvdata(dev);
493
494	gameport_start_polling(sw->gameport);
495	return 0;
496}
497
498static void sw_close(struct input_dev *dev)
499{
500	struct sw *sw = input_get_drvdata(dev);
501
502	gameport_stop_polling(sw->gameport);
503}
504
505/*
506 * sw_print_packet() prints the contents of a SideWinder packet.
507 */
508
509static void sw_print_packet(char *name, int length, unsigned char *buf, char bits)
510{
511	int i;
512
513	printk(KERN_INFO "sidewinder.c: %s packet, %d bits. [", name, length);
514	for (i = (((length + 3) >> 2) - 1); i >= 0; i--)
515		printk("%x", (int)sw_get_bits(buf, i << 2, 4, bits));
516	printk("]\n");
517}
518
519/*
520 * sw_3dp_id() translates the 3DP id into a human legible string.
521 * Unfortunately I don't know how to do this for the other SW types.
522 */
523
524static void sw_3dp_id(unsigned char *buf, char *comment, size_t size)
525{
526	int i;
527	char pnp[8], rev[9];
528
529	for (i = 0; i < 7; i++)						/* ASCII PnP ID */
530		pnp[i] = sw_get_bits(buf, 24+8*i, 8, 1);
531
532	for (i = 0; i < 8; i++)						/* ASCII firmware revision */
533		rev[i] = sw_get_bits(buf, 88+8*i, 8, 1);
534
535	pnp[7] = rev[8] = 0;
536
537	snprintf(comment, size, " [PnP %d.%02d id %s rev %s]",
538		(int) ((sw_get_bits(buf, 8, 6, 1) << 6) |		/* Two 6-bit values */
539			sw_get_bits(buf, 16, 6, 1)) / 100,
540		(int) ((sw_get_bits(buf, 8, 6, 1) << 6) |
541			sw_get_bits(buf, 16, 6, 1)) % 100,
542		 pnp, rev);
543}
544
545/*
546 * sw_guess_mode() checks the upper two button bits for toggling -
547 * indication of that the joystick is in 3-bit mode. This is documented
548 * behavior for 3DP ID packet, and for example the FSP does this in
549 * normal packets instead. Fun ...
550 */
551
552static int sw_guess_mode(unsigned char *buf, int len)
553{
554	int i;
555	unsigned char xor = 0;
556
557	for (i = 1; i < len; i++)
558		xor |= (buf[i - 1] ^ buf[i]) & 6;
559
560	return !!xor * 2 + 1;
561}
562
563/*
564 * sw_connect() probes for SideWinder type joysticks.
565 */
566
567static int sw_connect(struct gameport *gameport, struct gameport_driver *drv)
568{
569	struct sw *sw;
570	struct input_dev *input_dev;
571	int i, j, k, l;
572	int err = 0;
573	unsigned char *buf = NULL;	/* [SW_LENGTH] */
574	unsigned char *idbuf = NULL;	/* [SW_LENGTH] */
575	unsigned char m = 1;
576	char comment[40];
577
578	comment[0] = 0;
579
580	sw = kzalloc(sizeof(struct sw), GFP_KERNEL);
581	buf = kmalloc(SW_LENGTH, GFP_KERNEL);
582	idbuf = kmalloc(SW_LENGTH, GFP_KERNEL);
583	if (!sw || !buf || !idbuf) {
584		err = -ENOMEM;
585		goto fail1;
586	}
587
588	sw->gameport = gameport;
589
590	gameport_set_drvdata(gameport, sw);
591
592	err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
593	if (err)
594		goto fail1;
595
596	dbg("Init 0: Opened %s, io %#x, speed %d",
597		gameport->phys, gameport->io, gameport->speed);
598
599	i = sw_read_packet(gameport, buf, SW_LENGTH, 0);		/* Read normal packet */
600	msleep(SW_TIMEOUT);
601	dbg("Init 1: Mode %d. Length %d.", m , i);
602
603	if (!i) {							/* No data. 3d Pro analog mode? */
604		sw_init_digital(gameport);				/* Switch to digital */
605		msleep(SW_TIMEOUT);
606		i = sw_read_packet(gameport, buf, SW_LENGTH, 0);	/* Retry reading packet */
607		msleep(SW_TIMEOUT);
608		dbg("Init 1b: Length %d.", i);
609		if (!i) {						/* No data -> FAIL */
610			err = -ENODEV;
611			goto fail2;
612		}
613	}
614
615	j = sw_read_packet(gameport, idbuf, SW_LENGTH, i);		/* Read ID. This initializes the stick */
616	m |= sw_guess_mode(idbuf, j);					/* ID packet should carry mode info [3DP] */
617	dbg("Init 2: Mode %d. ID Length %d.", m, j);
618
619	if (j <= 0) {							/* Read ID failed. Happens in 1-bit mode on PP */
620		msleep(SW_TIMEOUT);
621		i = sw_read_packet(gameport, buf, SW_LENGTH, 0);	/* Retry reading packet */
622		m |= sw_guess_mode(buf, i);
623		dbg("Init 2b: Mode %d. Length %d.", m, i);
624		if (!i) {
625			err = -ENODEV;
626			goto fail2;
627		}
628		msleep(SW_TIMEOUT);
629		j = sw_read_packet(gameport, idbuf, SW_LENGTH, i);	/* Retry reading ID */
630		dbg("Init 2c: ID Length %d.", j);
631	}
632
633	sw->type = -1;
634	k = SW_FAIL;							/* Try SW_FAIL times */
635	l = 0;
636
637	do {
638		k--;
639		msleep(SW_TIMEOUT);
640		i = sw_read_packet(gameport, buf, SW_LENGTH, 0);	/* Read data packet */
641		dbg("Init 3: Mode %d. Length %d. Last %d. Tries %d.", m, i, l, k);
642
643		if (i > l) {						/* Longer? As we can only lose bits, it makes */
644									/* no sense to try detection for a packet shorter */
645			l = i;						/* than the previous one */
646
647			sw->number = 1;
648			sw->gameport = gameport;
649			sw->length = i;
650			sw->bits = m;
651
652			dbg("Init 3a: Case %d.\n", i * m);
653
654			switch (i * m) {
655				case 60:
656					sw->number++;
657					fallthrough;
658				case 45:				/* Ambiguous packet length */
659					if (j <= 40) {			/* ID length less or eq 40 -> FSP */
660					fallthrough;
661				case 43:
662						sw->type = SW_ID_FSP;
663						break;
664					}
665					sw->number++;
666					fallthrough;
667				case 30:
668					sw->number++;
669					fallthrough;
670				case 15:
671					sw->type = SW_ID_GP;
672					break;
673				case 33:
674				case 31:
675					sw->type = SW_ID_FFW;
676					break;
677				case 48:				/* Ambiguous */
678					if (j == 14) {			/* ID length 14*3 -> FFP */
679						sw->type = SW_ID_FFP;
680						sprintf(comment, " [AC %s]", sw_get_bits(idbuf,38,1,3) ? "off" : "on");
681					} else
682						sw->type = SW_ID_PP;
683					break;
684				case 66:
685					sw->bits = 3;
686					fallthrough;
687				case 198:
688					sw->length = 22;
689					fallthrough;
690				case 64:
691					sw->type = SW_ID_3DP;
692					if (j == 160)
693						sw_3dp_id(idbuf, comment, sizeof(comment));
694					break;
695			}
696		}
697
698	} while (k && sw->type == -1);
699
700	if (sw->type == -1) {
701		printk(KERN_WARNING "sidewinder.c: unknown joystick device detected "
702			"on %s, contact <vojtech@ucw.cz>\n", gameport->phys);
703		sw_print_packet("ID", j * 3, idbuf, 3);
704		sw_print_packet("Data", i * m, buf, m);
705		err = -ENODEV;
706		goto fail2;
707	}
708
709#ifdef SW_DEBUG
710	sw_print_packet("ID", j * 3, idbuf, 3);
711	sw_print_packet("Data", i * m, buf, m);
712#endif
713
714	gameport_set_poll_handler(gameport, sw_poll);
715	gameport_set_poll_interval(gameport, 20);
716
717	k = i;
718	l = j;
719
720	for (i = 0; i < sw->number; i++) {
721		int bits, code;
722
723		snprintf(sw->name, sizeof(sw->name),
724			 "Microsoft SideWinder %s", sw_name[sw->type]);
725		snprintf(sw->phys[i], sizeof(sw->phys[i]),
726			 "%s/input%d", gameport->phys, i);
727
728		sw->dev[i] = input_dev = input_allocate_device();
729		if (!input_dev) {
730			err = -ENOMEM;
731			goto fail3;
732		}
733
734		input_dev->name = sw->name;
735		input_dev->phys = sw->phys[i];
736		input_dev->id.bustype = BUS_GAMEPORT;
737		input_dev->id.vendor = GAMEPORT_ID_VENDOR_MICROSOFT;
738		input_dev->id.product = sw->type;
739		input_dev->id.version = 0x0100;
740		input_dev->dev.parent = &gameport->dev;
741
742		input_set_drvdata(input_dev, sw);
743
744		input_dev->open = sw_open;
745		input_dev->close = sw_close;
746
747		input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
748
749		for (j = 0; (bits = sw_bit[sw->type][j]); j++) {
750			int min, max, fuzz, flat;
751
752			code = sw_abs[sw->type][j];
753			min = bits == 1 ? -1 : 0;
754			max = (1 << bits) - 1;
755			fuzz = (bits >> 1) >= 2 ? 1 << ((bits >> 1) - 2) : 0;
756			flat = code == ABS_THROTTLE || bits < 5 ?
757				0 : 1 << (bits - 5);
758
759			input_set_abs_params(input_dev, code,
760					     min, max, fuzz, flat);
761		}
762
763		for (j = 0; (code = sw_btn[sw->type][j]); j++)
764			__set_bit(code, input_dev->keybit);
765
766		dbg("%s%s [%d-bit id %d data %d]\n", sw->name, comment, m, l, k);
767
768		err = input_register_device(sw->dev[i]);
769		if (err)
770			goto fail4;
771	}
772
773 out:	kfree(buf);
774	kfree(idbuf);
775
776	return err;
777
778 fail4:	input_free_device(sw->dev[i]);
779 fail3:	while (--i >= 0)
780		input_unregister_device(sw->dev[i]);
781 fail2:	gameport_close(gameport);
782 fail1:	gameport_set_drvdata(gameport, NULL);
783	kfree(sw);
784	goto out;
785}
786
787static void sw_disconnect(struct gameport *gameport)
788{
789	struct sw *sw = gameport_get_drvdata(gameport);
790	int i;
791
792	for (i = 0; i < sw->number; i++)
793		input_unregister_device(sw->dev[i]);
794	gameport_close(gameport);
795	gameport_set_drvdata(gameport, NULL);
796	kfree(sw);
797}
798
799static struct gameport_driver sw_drv = {
800	.driver		= {
801		.name	= "sidewinder",
802		.owner	= THIS_MODULE,
803	},
804	.description	= DRIVER_DESC,
805	.connect	= sw_connect,
806	.disconnect	= sw_disconnect,
807};
808
809module_gameport_driver(sw_drv);
v3.15
 
  1/*
  2 *  Copyright (c) 1998-2005 Vojtech Pavlik
  3 */
  4
  5/*
  6 * Microsoft SideWinder joystick family driver for Linux
  7 */
  8
  9/*
 10 * This program is free software; you can redistribute it and/or modify
 11 * it under the terms of the GNU General Public License as published by
 12 * the Free Software Foundation; either version 2 of the License, or
 13 * (at your option) any later version.
 14 *
 15 * This program is distributed in the hope that it will be useful,
 16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 18 * GNU General Public License for more details.
 19 *
 20 * You should have received a copy of the GNU General Public License
 21 * along with this program; if not, write to the Free Software
 22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 23 *
 24 * Should you need to contact me, the author, you can do so either by
 25 * e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
 26 * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
 27 */
 28
 29#include <linux/delay.h>
 30#include <linux/kernel.h>
 31#include <linux/module.h>
 32#include <linux/slab.h>
 33#include <linux/input.h>
 34#include <linux/gameport.h>
 35#include <linux/jiffies.h>
 36
 37#define DRIVER_DESC	"Microsoft SideWinder joystick family driver"
 38
 39MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
 40MODULE_DESCRIPTION(DRIVER_DESC);
 41MODULE_LICENSE("GPL");
 42
 43/*
 44 * These are really magic values. Changing them can make a problem go away,
 45 * as well as break everything.
 46 */
 47
 48#undef SW_DEBUG
 49#undef SW_DEBUG_DATA
 50
 51#define SW_START	600	/* The time we wait for the first bit [600 us] */
 52#define SW_STROBE	60	/* Max time per bit [60 us] */
 53#define SW_TIMEOUT	6	/* Wait for everything to settle [6 ms] */
 54#define SW_KICK		45	/* Wait after A0 fall till kick [45 us] */
 55#define SW_END		8	/* Number of bits before end of packet to kick */
 56#define SW_FAIL		16	/* Number of packet read errors to fail and reinitialize */
 57#define SW_BAD		2	/* Number of packet read errors to switch off 3d Pro optimization */
 58#define SW_OK		64	/* Number of packet read successes to switch optimization back on */
 59#define SW_LENGTH	512	/* Max number of bits in a packet */
 60
 61#ifdef SW_DEBUG
 62#define dbg(format, arg...) printk(KERN_DEBUG __FILE__ ": " format "\n" , ## arg)
 63#else
 64#define dbg(format, arg...) do {} while (0)
 65#endif
 66
 67/*
 68 * SideWinder joystick types ...
 69 */
 70
 71#define SW_ID_3DP	0
 72#define SW_ID_GP	1
 73#define SW_ID_PP	2
 74#define SW_ID_FFP	3
 75#define SW_ID_FSP	4
 76#define SW_ID_FFW	5
 77
 78/*
 79 * Names, buttons, axes ...
 80 */
 81
 82static char *sw_name[] = {	"3D Pro", "GamePad", "Precision Pro", "Force Feedback Pro", "FreeStyle Pro",
 83				"Force Feedback Wheel" };
 84
 85static char sw_abs[][7] = {
 86	{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
 87	{ ABS_X, ABS_Y },
 88	{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
 89	{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
 90	{ ABS_X, ABS_Y,         ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
 91	{ ABS_RX, ABS_RUDDER,   ABS_THROTTLE }};
 92
 93static char sw_bit[][7] = {
 94	{ 10, 10,  9, 10,  1,  1 },
 95	{  1,  1                 },
 96	{ 10, 10,  6,  7,  1,  1 },
 97	{ 10, 10,  6,  7,  1,  1 },
 98	{ 10, 10,  6,  1,  1     },
 99	{ 10,  7,  7,  1,  1     }};
100
101static short sw_btn[][12] = {
102	{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_THUMB2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_MODE },
103	{ BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_START, BTN_MODE },
104	{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_SELECT },
105	{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_SELECT },
106	{ BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_START, BTN_MODE, BTN_SELECT },
107	{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_THUMB2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4 }};
108
109static struct {
110	int x;
111	int y;
112} sw_hat_to_axis[] = {{ 0, 0}, { 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}};
113
114struct sw {
115	struct gameport *gameport;
116	struct input_dev *dev[4];
117	char name[64];
118	char phys[4][32];
119	int length;
120	int type;
121	int bits;
122	int number;
123	int fail;
124	int ok;
125	int reads;
126	int bads;
127};
128
129/*
130 * sw_read_packet() is a function which reads either a data packet, or an
131 * identification packet from a SideWinder joystick. The protocol is very,
132 * very, very braindamaged. Microsoft patented it in US patent #5628686.
133 */
134
135static int sw_read_packet(struct gameport *gameport, unsigned char *buf, int length, int id)
136{
137	unsigned long flags;
138	int timeout, bitout, sched, i, kick, start, strobe;
139	unsigned char pending, u, v;
140
141	i = -id;						/* Don't care about data, only want ID */
142	timeout = id ? gameport_time(gameport, SW_TIMEOUT * 1000) : 0; /* Set up global timeout for ID packet */
143	kick = id ? gameport_time(gameport, SW_KICK) : 0;	/* Set up kick timeout for ID packet */
144	start = gameport_time(gameport, SW_START);
145	strobe = gameport_time(gameport, SW_STROBE);
146	bitout = start;
147	pending = 0;
148	sched = 0;
149
150        local_irq_save(flags);					/* Quiet, please */
151
152	gameport_trigger(gameport);				/* Trigger */
153	v = gameport_read(gameport);
154
155	do {
156		bitout--;
157		u = v;
158		v = gameport_read(gameport);
159	} while (!(~v & u & 0x10) && (bitout > 0));		/* Wait for first falling edge on clock */
160
161	if (bitout > 0)
162		bitout = strobe;				/* Extend time if not timed out */
163
164	while ((timeout > 0 || bitout > 0) && (i < length)) {
165
166		timeout--;
167		bitout--;					/* Decrement timers */
168		sched--;
169
170		u = v;
171		v = gameport_read(gameport);
172
173		if ((~u & v & 0x10) && (bitout > 0)) {		/* Rising edge on clock - data bit */
174			if (i >= 0)				/* Want this data */
175				buf[i] = v >> 5;		/* Store it */
176			i++;					/* Advance index */
177			bitout = strobe;			/* Extend timeout for next bit */
178		}
179
180		if (kick && (~v & u & 0x01)) {			/* Falling edge on axis 0 */
181			sched = kick;				/* Schedule second trigger */
182			kick = 0;				/* Don't schedule next time on falling edge */
183			pending = 1;				/* Mark schedule */
184		}
185
186		if (pending && sched < 0 && (i > -SW_END)) {	/* Second trigger time */
187			gameport_trigger(gameport);		/* Trigger */
188			bitout = start;				/* Long bit timeout */
189			pending = 0;				/* Unmark schedule */
190			timeout = 0;				/* Switch from global to bit timeouts */
191		}
192	}
193
194	local_irq_restore(flags);					/* Done - relax */
195
196#ifdef SW_DEBUG_DATA
197	{
198		int j;
199		printk(KERN_DEBUG "sidewinder.c: Read %d triplets. [", i);
200		for (j = 0; j < i; j++) printk("%d", buf[j]);
201		printk("]\n");
202	}
203#endif
204
205	return i;
206}
207
208/*
209 * sw_get_bits() and GB() compose bits from the triplet buffer into a __u64.
210 * Parameter 'pos' is bit number inside packet where to start at, 'num' is number
211 * of bits to be read, 'shift' is offset in the resulting __u64 to start at, bits
212 * is number of bits per triplet.
213 */
214
215#define GB(pos,num) sw_get_bits(buf, pos, num, sw->bits)
216
217static __u64 sw_get_bits(unsigned char *buf, int pos, int num, char bits)
218{
219	__u64 data = 0;
220	int tri = pos % bits;						/* Start position */
221	int i   = pos / bits;
222	int bit = 0;
223
224	while (num--) {
225		data |= (__u64)((buf[i] >> tri++) & 1) << bit++;	/* Transfer bit */
226		if (tri == bits) {
227			i++;						/* Next triplet */
228			tri = 0;
229		}
230	}
231
232	return data;
233}
234
235/*
236 * sw_init_digital() initializes a SideWinder 3D Pro joystick
237 * into digital mode.
238 */
239
240static void sw_init_digital(struct gameport *gameport)
241{
242	int seq[] = { 140, 140+725, 140+300, 0 };
243	unsigned long flags;
244	int i, t;
245
246        local_irq_save(flags);
247
248	i = 0;
249        do {
250                gameport_trigger(gameport);			/* Trigger */
251		t = gameport_time(gameport, SW_TIMEOUT * 1000);
252		while ((gameport_read(gameport) & 1) && t) t--;	/* Wait for axis to fall back to 0 */
253                udelay(seq[i]);					/* Delay magic time */
254        } while (seq[++i]);
255
256	gameport_trigger(gameport);				/* Last trigger */
257
258	local_irq_restore(flags);
259}
260
261/*
262 * sw_parity() computes parity of __u64
263 */
264
265static int sw_parity(__u64 t)
266{
267	int x = t ^ (t >> 32);
268
269	x ^= x >> 16;
270	x ^= x >> 8;
271	x ^= x >> 4;
272	x ^= x >> 2;
273	x ^= x >> 1;
274	return x & 1;
275}
276
277/*
278 * sw_ccheck() checks synchronization bits and computes checksum of nibbles.
279 */
280
281static int sw_check(__u64 t)
282{
283	unsigned char sum = 0;
284
285	if ((t & 0x8080808080808080ULL) ^ 0x80)			/* Sync */
286		return -1;
287
288	while (t) {						/* Sum */
289		sum += t & 0xf;
290		t >>= 4;
291	}
292
293	return sum & 0xf;
294}
295
296/*
297 * sw_parse() analyzes SideWinder joystick data, and writes the results into
298 * the axes and buttons arrays.
299 */
300
301static int sw_parse(unsigned char *buf, struct sw *sw)
302{
303	int hat, i, j;
304	struct input_dev *dev;
305
306	switch (sw->type) {
307
308		case SW_ID_3DP:
309
310			if (sw_check(GB(0,64)) || (hat = (GB(6,1) << 3) | GB(60,3)) > 8)
311				return -1;
312
313			dev = sw->dev[0];
314
315			input_report_abs(dev, ABS_X,        (GB( 3,3) << 7) | GB(16,7));
316			input_report_abs(dev, ABS_Y,        (GB( 0,3) << 7) | GB(24,7));
317			input_report_abs(dev, ABS_RZ,       (GB(35,2) << 7) | GB(40,7));
318			input_report_abs(dev, ABS_THROTTLE, (GB(32,3) << 7) | GB(48,7));
319
320			input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
321			input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
322
323			for (j = 0; j < 7; j++)
324				input_report_key(dev, sw_btn[SW_ID_3DP][j], !GB(j+8,1));
325
326			input_report_key(dev, BTN_BASE4, !GB(38,1));
327			input_report_key(dev, BTN_BASE5, !GB(37,1));
328
329			input_sync(dev);
330
331			return 0;
332
333		case SW_ID_GP:
334
335			for (i = 0; i < sw->number; i ++) {
336
337				if (sw_parity(GB(i*15,15)))
338					return -1;
339
340				input_report_abs(sw->dev[i], ABS_X, GB(i*15+3,1) - GB(i*15+2,1));
341				input_report_abs(sw->dev[i], ABS_Y, GB(i*15+0,1) - GB(i*15+1,1));
342
343				for (j = 0; j < 10; j++)
344					input_report_key(sw->dev[i], sw_btn[SW_ID_GP][j], !GB(i*15+j+4,1));
345
346				input_sync(sw->dev[i]);
347			}
348
349			return 0;
350
351		case SW_ID_PP:
352		case SW_ID_FFP:
353
354			if (!sw_parity(GB(0,48)) || (hat = GB(42,4)) > 8)
355				return -1;
356
357			dev = sw->dev[0];
358			input_report_abs(dev, ABS_X,        GB( 9,10));
359			input_report_abs(dev, ABS_Y,        GB(19,10));
360			input_report_abs(dev, ABS_RZ,       GB(36, 6));
361			input_report_abs(dev, ABS_THROTTLE, GB(29, 7));
362
363			input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
364			input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
365
366			for (j = 0; j < 9; j++)
367				input_report_key(dev, sw_btn[SW_ID_PP][j], !GB(j,1));
368
369			input_sync(dev);
370
371			return 0;
372
373		case SW_ID_FSP:
374
375			if (!sw_parity(GB(0,43)) || (hat = GB(28,4)) > 8)
376				return -1;
377
378			dev = sw->dev[0];
379			input_report_abs(dev, ABS_X,        GB( 0,10));
380			input_report_abs(dev, ABS_Y,        GB(16,10));
381			input_report_abs(dev, ABS_THROTTLE, GB(32, 6));
382
383			input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
384			input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
385
386			for (j = 0; j < 6; j++)
387				input_report_key(dev, sw_btn[SW_ID_FSP][j], !GB(j+10,1));
388
389			input_report_key(dev, BTN_TR,     !GB(26,1));
390			input_report_key(dev, BTN_START,  !GB(27,1));
391			input_report_key(dev, BTN_MODE,   !GB(38,1));
392			input_report_key(dev, BTN_SELECT, !GB(39,1));
393
394			input_sync(dev);
395
396			return 0;
397
398		case SW_ID_FFW:
399
400			if (!sw_parity(GB(0,33)))
401				return -1;
402
403			dev = sw->dev[0];
404			input_report_abs(dev, ABS_RX,       GB( 0,10));
405			input_report_abs(dev, ABS_RUDDER,   GB(10, 6));
406			input_report_abs(dev, ABS_THROTTLE, GB(16, 6));
407
408			for (j = 0; j < 8; j++)
409				input_report_key(dev, sw_btn[SW_ID_FFW][j], !GB(j+22,1));
410
411			input_sync(dev);
412
413			return 0;
414	}
415
416	return -1;
417}
418
419/*
420 * sw_read() reads SideWinder joystick data, and reinitializes
421 * the joystick in case of persistent problems. This is the function that is
422 * called from the generic code to poll the joystick.
423 */
424
425static int sw_read(struct sw *sw)
426{
427	unsigned char buf[SW_LENGTH];
428	int i;
429
430	i = sw_read_packet(sw->gameport, buf, sw->length, 0);
431
432	if (sw->type == SW_ID_3DP && sw->length == 66 && i != 66) {		/* Broken packet, try to fix */
433
434		if (i == 64 && !sw_check(sw_get_bits(buf,0,64,1))) {		/* Last init failed, 1 bit mode */
435			printk(KERN_WARNING "sidewinder.c: Joystick in wrong mode on %s"
436				" - going to reinitialize.\n", sw->gameport->phys);
437			sw->fail = SW_FAIL;					/* Reinitialize */
438			i = 128;						/* Bogus value */
439		}
440
441		if (i < 66 && GB(0,64) == GB(i*3-66,64))			/* 1 == 3 */
442			i = 66;							/* Everything is fine */
443
444		if (i < 66 && GB(0,64) == GB(66,64))				/* 1 == 2 */
445			i = 66;							/* Everything is fine */
446
447		if (i < 66 && GB(i*3-132,64) == GB(i*3-66,64)) {		/* 2 == 3 */
448			memmove(buf, buf + i - 22, 22);				/* Move data */
449			i = 66;							/* Carry on */
450		}
451	}
452
453	if (i == sw->length && !sw_parse(buf, sw)) {				/* Parse data */
454
455		sw->fail = 0;
456		sw->ok++;
457
458		if (sw->type == SW_ID_3DP && sw->length == 66			/* Many packets OK */
459			&& sw->ok > SW_OK) {
460
461			printk(KERN_INFO "sidewinder.c: No more trouble on %s"
462				" - enabling optimization again.\n", sw->gameport->phys);
463			sw->length = 22;
464		}
465
466		return 0;
467	}
468
469	sw->ok = 0;
470	sw->fail++;
471
472	if (sw->type == SW_ID_3DP && sw->length == 22 && sw->fail > SW_BAD) {	/* Consecutive bad packets */
473
474		printk(KERN_INFO "sidewinder.c: Many bit errors on %s"
475			" - disabling optimization.\n", sw->gameport->phys);
476		sw->length = 66;
477	}
478
479	if (sw->fail < SW_FAIL)
480		return -1;							/* Not enough, don't reinitialize yet */
481
482	printk(KERN_WARNING "sidewinder.c: Too many bit errors on %s"
483		" - reinitializing joystick.\n", sw->gameport->phys);
484
485	if (!i && sw->type == SW_ID_3DP) {					/* 3D Pro can be in analog mode */
486		mdelay(3 * SW_TIMEOUT);
487		sw_init_digital(sw->gameport);
488	}
489
490	mdelay(SW_TIMEOUT);
491	i = sw_read_packet(sw->gameport, buf, SW_LENGTH, 0);			/* Read normal data packet */
492	mdelay(SW_TIMEOUT);
493	sw_read_packet(sw->gameport, buf, SW_LENGTH, i);			/* Read ID packet, this initializes the stick */
494
495	sw->fail = SW_FAIL;
496
497	return -1;
498}
499
500static void sw_poll(struct gameport *gameport)
501{
502	struct sw *sw = gameport_get_drvdata(gameport);
503
504	sw->reads++;
505	if (sw_read(sw))
506		sw->bads++;
507}
508
509static int sw_open(struct input_dev *dev)
510{
511	struct sw *sw = input_get_drvdata(dev);
512
513	gameport_start_polling(sw->gameport);
514	return 0;
515}
516
517static void sw_close(struct input_dev *dev)
518{
519	struct sw *sw = input_get_drvdata(dev);
520
521	gameport_stop_polling(sw->gameport);
522}
523
524/*
525 * sw_print_packet() prints the contents of a SideWinder packet.
526 */
527
528static void sw_print_packet(char *name, int length, unsigned char *buf, char bits)
529{
530	int i;
531
532	printk(KERN_INFO "sidewinder.c: %s packet, %d bits. [", name, length);
533	for (i = (((length + 3) >> 2) - 1); i >= 0; i--)
534		printk("%x", (int)sw_get_bits(buf, i << 2, 4, bits));
535	printk("]\n");
536}
537
538/*
539 * sw_3dp_id() translates the 3DP id into a human legible string.
540 * Unfortunately I don't know how to do this for the other SW types.
541 */
542
543static void sw_3dp_id(unsigned char *buf, char *comment, size_t size)
544{
545	int i;
546	char pnp[8], rev[9];
547
548	for (i = 0; i < 7; i++)						/* ASCII PnP ID */
549		pnp[i] = sw_get_bits(buf, 24+8*i, 8, 1);
550
551	for (i = 0; i < 8; i++)						/* ASCII firmware revision */
552		rev[i] = sw_get_bits(buf, 88+8*i, 8, 1);
553
554	pnp[7] = rev[8] = 0;
555
556	snprintf(comment, size, " [PnP %d.%02d id %s rev %s]",
557		(int) ((sw_get_bits(buf, 8, 6, 1) << 6) |		/* Two 6-bit values */
558			sw_get_bits(buf, 16, 6, 1)) / 100,
559		(int) ((sw_get_bits(buf, 8, 6, 1) << 6) |
560			sw_get_bits(buf, 16, 6, 1)) % 100,
561		 pnp, rev);
562}
563
564/*
565 * sw_guess_mode() checks the upper two button bits for toggling -
566 * indication of that the joystick is in 3-bit mode. This is documented
567 * behavior for 3DP ID packet, and for example the FSP does this in
568 * normal packets instead. Fun ...
569 */
570
571static int sw_guess_mode(unsigned char *buf, int len)
572{
573	int i;
574	unsigned char xor = 0;
575
576	for (i = 1; i < len; i++)
577		xor |= (buf[i - 1] ^ buf[i]) & 6;
578
579	return !!xor * 2 + 1;
580}
581
582/*
583 * sw_connect() probes for SideWinder type joysticks.
584 */
585
586static int sw_connect(struct gameport *gameport, struct gameport_driver *drv)
587{
588	struct sw *sw;
589	struct input_dev *input_dev;
590	int i, j, k, l;
591	int err = 0;
592	unsigned char *buf = NULL;	/* [SW_LENGTH] */
593	unsigned char *idbuf = NULL;	/* [SW_LENGTH] */
594	unsigned char m = 1;
595	char comment[40];
596
597	comment[0] = 0;
598
599	sw = kzalloc(sizeof(struct sw), GFP_KERNEL);
600	buf = kmalloc(SW_LENGTH, GFP_KERNEL);
601	idbuf = kmalloc(SW_LENGTH, GFP_KERNEL);
602	if (!sw || !buf || !idbuf) {
603		err = -ENOMEM;
604		goto fail1;
605	}
606
607	sw->gameport = gameport;
608
609	gameport_set_drvdata(gameport, sw);
610
611	err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
612	if (err)
613		goto fail1;
614
615	dbg("Init 0: Opened %s, io %#x, speed %d",
616		gameport->phys, gameport->io, gameport->speed);
617
618	i = sw_read_packet(gameport, buf, SW_LENGTH, 0);		/* Read normal packet */
619	msleep(SW_TIMEOUT);
620	dbg("Init 1: Mode %d. Length %d.", m , i);
621
622	if (!i) {							/* No data. 3d Pro analog mode? */
623		sw_init_digital(gameport);				/* Switch to digital */
624		msleep(SW_TIMEOUT);
625		i = sw_read_packet(gameport, buf, SW_LENGTH, 0);	/* Retry reading packet */
626		msleep(SW_TIMEOUT);
627		dbg("Init 1b: Length %d.", i);
628		if (!i) {						/* No data -> FAIL */
629			err = -ENODEV;
630			goto fail2;
631		}
632	}
633
634	j = sw_read_packet(gameport, idbuf, SW_LENGTH, i);		/* Read ID. This initializes the stick */
635	m |= sw_guess_mode(idbuf, j);					/* ID packet should carry mode info [3DP] */
636	dbg("Init 2: Mode %d. ID Length %d.", m, j);
637
638	if (j <= 0) {							/* Read ID failed. Happens in 1-bit mode on PP */
639		msleep(SW_TIMEOUT);
640		i = sw_read_packet(gameport, buf, SW_LENGTH, 0);	/* Retry reading packet */
641		m |= sw_guess_mode(buf, i);
642		dbg("Init 2b: Mode %d. Length %d.", m, i);
643		if (!i) {
644			err = -ENODEV;
645			goto fail2;
646		}
647		msleep(SW_TIMEOUT);
648		j = sw_read_packet(gameport, idbuf, SW_LENGTH, i);	/* Retry reading ID */
649		dbg("Init 2c: ID Length %d.", j);
650	}
651
652	sw->type = -1;
653	k = SW_FAIL;							/* Try SW_FAIL times */
654	l = 0;
655
656	do {
657		k--;
658		msleep(SW_TIMEOUT);
659		i = sw_read_packet(gameport, buf, SW_LENGTH, 0);	/* Read data packet */
660		dbg("Init 3: Mode %d. Length %d. Last %d. Tries %d.", m, i, l, k);
661
662		if (i > l) {						/* Longer? As we can only lose bits, it makes */
663									/* no sense to try detection for a packet shorter */
664			l = i;						/* than the previous one */
665
666			sw->number = 1;
667			sw->gameport = gameport;
668			sw->length = i;
669			sw->bits = m;
670
671			dbg("Init 3a: Case %d.\n", i * m);
672
673			switch (i * m) {
674				case 60:
675					sw->number++;
 
676				case 45:				/* Ambiguous packet length */
677					if (j <= 40) {			/* ID length less or eq 40 -> FSP */
 
678				case 43:
679						sw->type = SW_ID_FSP;
680						break;
681					}
682					sw->number++;
 
683				case 30:
684					sw->number++;
 
685				case 15:
686					sw->type = SW_ID_GP;
687					break;
688				case 33:
689				case 31:
690					sw->type = SW_ID_FFW;
691					break;
692				case 48:				/* Ambiguous */
693					if (j == 14) {			/* ID length 14*3 -> FFP */
694						sw->type = SW_ID_FFP;
695						sprintf(comment, " [AC %s]", sw_get_bits(idbuf,38,1,3) ? "off" : "on");
696					} else
697						sw->type = SW_ID_PP;
698					break;
699				case 66:
700					sw->bits = 3;
 
701				case 198:
702					sw->length = 22;
 
703				case 64:
704					sw->type = SW_ID_3DP;
705					if (j == 160)
706						sw_3dp_id(idbuf, comment, sizeof(comment));
707					break;
708			}
709		}
710
711	} while (k && sw->type == -1);
712
713	if (sw->type == -1) {
714		printk(KERN_WARNING "sidewinder.c: unknown joystick device detected "
715			"on %s, contact <vojtech@ucw.cz>\n", gameport->phys);
716		sw_print_packet("ID", j * 3, idbuf, 3);
717		sw_print_packet("Data", i * m, buf, m);
718		err = -ENODEV;
719		goto fail2;
720	}
721
722#ifdef SW_DEBUG
723	sw_print_packet("ID", j * 3, idbuf, 3);
724	sw_print_packet("Data", i * m, buf, m);
725#endif
726
727	gameport_set_poll_handler(gameport, sw_poll);
728	gameport_set_poll_interval(gameport, 20);
729
730	k = i;
731	l = j;
732
733	for (i = 0; i < sw->number; i++) {
734		int bits, code;
735
736		snprintf(sw->name, sizeof(sw->name),
737			 "Microsoft SideWinder %s", sw_name[sw->type]);
738		snprintf(sw->phys[i], sizeof(sw->phys[i]),
739			 "%s/input%d", gameport->phys, i);
740
741		sw->dev[i] = input_dev = input_allocate_device();
742		if (!input_dev) {
743			err = -ENOMEM;
744			goto fail3;
745		}
746
747		input_dev->name = sw->name;
748		input_dev->phys = sw->phys[i];
749		input_dev->id.bustype = BUS_GAMEPORT;
750		input_dev->id.vendor = GAMEPORT_ID_VENDOR_MICROSOFT;
751		input_dev->id.product = sw->type;
752		input_dev->id.version = 0x0100;
753		input_dev->dev.parent = &gameport->dev;
754
755		input_set_drvdata(input_dev, sw);
756
757		input_dev->open = sw_open;
758		input_dev->close = sw_close;
759
760		input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
761
762		for (j = 0; (bits = sw_bit[sw->type][j]); j++) {
763			int min, max, fuzz, flat;
764
765			code = sw_abs[sw->type][j];
766			min = bits == 1 ? -1 : 0;
767			max = (1 << bits) - 1;
768			fuzz = (bits >> 1) >= 2 ? 1 << ((bits >> 1) - 2) : 0;
769			flat = code == ABS_THROTTLE || bits < 5 ?
770				0 : 1 << (bits - 5);
771
772			input_set_abs_params(input_dev, code,
773					     min, max, fuzz, flat);
774		}
775
776		for (j = 0; (code = sw_btn[sw->type][j]); j++)
777			__set_bit(code, input_dev->keybit);
778
779		dbg("%s%s [%d-bit id %d data %d]\n", sw->name, comment, m, l, k);
780
781		err = input_register_device(sw->dev[i]);
782		if (err)
783			goto fail4;
784	}
785
786 out:	kfree(buf);
787	kfree(idbuf);
788
789	return err;
790
791 fail4:	input_free_device(sw->dev[i]);
792 fail3:	while (--i >= 0)
793		input_unregister_device(sw->dev[i]);
794 fail2:	gameport_close(gameport);
795 fail1:	gameport_set_drvdata(gameport, NULL);
796	kfree(sw);
797	goto out;
798}
799
800static void sw_disconnect(struct gameport *gameport)
801{
802	struct sw *sw = gameport_get_drvdata(gameport);
803	int i;
804
805	for (i = 0; i < sw->number; i++)
806		input_unregister_device(sw->dev[i]);
807	gameport_close(gameport);
808	gameport_set_drvdata(gameport, NULL);
809	kfree(sw);
810}
811
812static struct gameport_driver sw_drv = {
813	.driver		= {
814		.name	= "sidewinder",
815		.owner	= THIS_MODULE,
816	},
817	.description	= DRIVER_DESC,
818	.connect	= sw_connect,
819	.disconnect	= sw_disconnect,
820};
821
822module_gameport_driver(sw_drv);