summaryrefslogtreecommitdiff
path: root/sys/dev/wscons/wsmouse.c
blob: d3ebd7741afb289bc6cd23596f997e9702d59992 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
/* $OpenBSD: wsmouse.c,v 1.38 2017/03/16 10:03:27 mpi Exp $ */
/* $NetBSD: wsmouse.c,v 1.35 2005/02/27 00:27:52 perry Exp $ */

/*
 * Copyright (c) 1996, 1997 Christopher G. Demetriou.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Christopher G. Demetriou
 *	for the NetBSD Project.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)ms.c	8.1 (Berkeley) 6/11/93
 */

/*
 * Copyright (c) 2015, 2016 Ulf Brosziewski
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Mouse driver.
 */

#include <sys/param.h>
#include <sys/conf.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <sys/kernel.h>
#include <sys/proc.h>
#include <sys/syslog.h>
#include <sys/systm.h>
#include <sys/tty.h>
#include <sys/signalvar.h>
#include <sys/device.h>
#include <sys/vnode.h>
#include <sys/poll.h>
#include <sys/malloc.h>

#include <dev/wscons/wscons_features.h>
#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wsmousevar.h>
#include <dev/wscons/wseventvar.h>
#include <dev/wscons/wsmouseinput.h>
#include <dev/rndvar.h>

#include "wsmux.h"
#include "wsdisplay.h"
#include "wskbd.h"

#include <dev/wscons/wsmuxvar.h>

#if defined(WSMUX_DEBUG) && NWSMUX > 0
#define	DPRINTF(x)	if (wsmuxdebug) printf x
#define	DPRINTFN(n,x)	if (wsmuxdebug > (n)) printf x
extern int wsmuxdebug;
#else
#define	DPRINTF(x)
#define	DPRINTFN(n,x)
#endif

struct wsmouse_softc {
	struct wsevsrc	sc_base;

	const struct wsmouse_accessops *sc_accessops;
	void		*sc_accesscookie;

	struct wsmouseinput sc_input;

	int		sc_refcnt;
	u_char		sc_dying;	/* device is being detached */
};

int	wsmouse_match(struct device *, void *, void *);
void	wsmouse_attach(struct device *, struct device *, void *);
int	wsmouse_detach(struct device *, int);
int	wsmouse_activate(struct device *, int);

int	wsmouse_do_ioctl(struct wsmouse_softc *, u_long, caddr_t, 
			      int, struct proc *);

#if NWSMUX > 0
int	wsmouse_mux_open(struct wsevsrc *, struct wseventvar *);
int	wsmouse_mux_close(struct wsevsrc *);
#endif

int	wsmousedoioctl(struct device *, u_long, caddr_t, int, 
			    struct proc *);
int	wsmousedoopen(struct wsmouse_softc *, struct wseventvar *);

struct cfdriver wsmouse_cd = {
	NULL, "wsmouse", DV_TTY
};

struct cfattach wsmouse_ca = {
	sizeof (struct wsmouse_softc), wsmouse_match, wsmouse_attach,
	wsmouse_detach, wsmouse_activate
};

#if NWSMUX > 0
struct wssrcops wsmouse_srcops = {
	WSMUX_MOUSE,
	wsmouse_mux_open, wsmouse_mux_close, wsmousedoioctl, NULL, NULL
};
#endif

/*
 * Print function (for parent devices).
 */
int
wsmousedevprint(void *aux, const char *pnp)
{

	if (pnp)
		printf("wsmouse at %s", pnp);
	return (UNCONF);
}

int
wsmouse_match(struct device *parent, void *match, void *aux)
{
	return (1);
}

void
wsmouse_attach(struct device *parent, struct device *self, void *aux)
{
	struct wsmouse_softc *sc = (struct wsmouse_softc *)self;
	struct wsmousedev_attach_args *ap = aux;
#if NWSMUX > 0
	int mux, error;
#endif

	sc->sc_accessops = ap->accessops;
	sc->sc_accesscookie = ap->accesscookie;

	sc->sc_input.evar = &sc->sc_base.me_evp;

#if NWSMUX > 0
	sc->sc_base.me_ops = &wsmouse_srcops;
	mux = sc->sc_base.me_dv.dv_cfdata->wsmousedevcf_mux;
	if (mux >= 0) {
		error = wsmux_attach_sc(wsmux_getmux(mux), &sc->sc_base);
		if (error)
			printf(" attach error=%d", error);
		else
			printf(" mux %d", mux);
	}
#else
#if 0	/* not worth keeping, especially since the default value is not -1... */
	if (sc->sc_base.me_dv.dv_cfdata->wsmousedevcf_mux >= 0)
		printf(" (mux ignored)");
#endif
#endif	/* NWSMUX > 0 */

	printf("\n");
}

int
wsmouse_activate(struct device *self, int act)
{
	struct wsmouse_softc *sc = (struct wsmouse_softc *)self;

	if (act == DVACT_DEACTIVATE)
		sc->sc_dying = 1;
	return (0);
}

/*
 * Detach a mouse.  To keep track of users of the softc we keep
 * a reference count that's incremented while inside, e.g., read.
 * If the mouse is active and the reference count is > 0 (0 is the
 * normal state) we post an event and then wait for the process
 * that had the reference to wake us up again.  Then we blow away the
 * vnode and return (which will deallocate the softc).
 */
int
wsmouse_detach(struct device *self, int flags)
{
	struct wsmouse_softc *sc = (struct wsmouse_softc *)self;
	struct wseventvar *evar;
	int maj, mn;
	int s;

#if NWSMUX > 0
	/* Tell parent mux we're leaving. */
	if (sc->sc_base.me_parent != NULL) {
		DPRINTF(("wsmouse_detach:\n"));
		wsmux_detach_sc(&sc->sc_base);
	}
#endif

	/* If we're open ... */
	evar = sc->sc_base.me_evp;
	if (evar != NULL && evar->io != NULL) {
		s = spltty();
		if (--sc->sc_refcnt >= 0) {
			/* Wake everyone by generating a dummy event. */
			if (++evar->put >= WSEVENT_QSIZE)
				evar->put = 0;
			WSEVENT_WAKEUP(evar);
			/* Wait for processes to go away. */
			if (tsleep(sc, PZERO, "wsmdet", hz * 60))
				printf("wsmouse_detach: %s didn't detach\n",
				       sc->sc_base.me_dv.dv_xname);
		}
		splx(s);
	}

	/* locate the major number */
	for (maj = 0; maj < nchrdev; maj++)
		if (cdevsw[maj].d_open == wsmouseopen)
			break;

	/* Nuke the vnodes for any open instances (calls close). */
	mn = self->dv_unit;
	vdevgone(maj, mn, mn, VCHR);

	wsmouse_input_cleanup(&sc->sc_input);

	return (0);
}

int
wsmouseopen(dev_t dev, int flags, int mode, struct proc *p)
{
	struct wsmouse_softc *sc;
	struct wseventvar *evar;
	int error, unit;

	unit = minor(dev);
	if (unit >= wsmouse_cd.cd_ndevs ||	/* make sure it was attached */
	    (sc = wsmouse_cd.cd_devs[unit]) == NULL)
		return (ENXIO);

#if NWSMUX > 0
	DPRINTF(("wsmouseopen: %s mux=%p p=%p\n", sc->sc_base.me_dv.dv_xname,
		 sc->sc_base.me_parent, p));
#endif

	if (sc->sc_dying)
		return (EIO);

	if ((flags & (FREAD | FWRITE)) == FWRITE)
		return (0);			/* always allow open for write
						   so ioctl() is possible. */

#if NWSMUX > 0
	if (sc->sc_base.me_parent != NULL) {
		/* Grab the mouse out of the greedy hands of the mux. */
		DPRINTF(("wsmouseopen: detach\n"));
		wsmux_detach_sc(&sc->sc_base);
	}
#endif

	if (sc->sc_base.me_evp != NULL)
		return (EBUSY);

	evar = &sc->sc_base.me_evar;
	wsevent_init(evar);
	evar->io = p->p_p;

	error = wsmousedoopen(sc, evar);
	if (error) {
		DPRINTF(("wsmouseopen: %s open failed\n",
			 sc->sc_base.me_dv.dv_xname));
		sc->sc_base.me_evp = NULL;
		wsevent_fini(evar);
	}
	return (error);
}

int
wsmouseclose(dev_t dev, int flags, int mode, struct proc *p)
{
	struct wsmouse_softc *sc =
	    (struct wsmouse_softc *)wsmouse_cd.cd_devs[minor(dev)];
	struct wseventvar *evar = sc->sc_base.me_evp;

	if ((flags & (FREAD | FWRITE)) == FWRITE)
		return (0);			/* see wsmouseopen() */

	if (evar == NULL)
		/* not open for read */
		return (0);
	sc->sc_base.me_evp = NULL;
	(*sc->sc_accessops->disable)(sc->sc_accesscookie);
	wsevent_fini(evar);

#if NWSMUX > 0
	if (sc->sc_base.me_parent == NULL) {
		int mux, error;

		DPRINTF(("wsmouseclose: attach\n"));
		mux = sc->sc_base.me_dv.dv_cfdata->wsmousedevcf_mux;
		if (mux >= 0) {
			error = wsmux_attach_sc(wsmux_getmux(mux), &sc->sc_base);
			if (error)
				printf("%s: can't attach mux (error=%d)\n",
				    sc->sc_base.me_dv.dv_xname, error);
		}
	}
#endif

	return (0);
}

int
wsmousedoopen(struct wsmouse_softc *sc, struct wseventvar *evp)
{
	sc->sc_base.me_evp = evp;

	wsmouse_input_reset(&sc->sc_input);

	/* enable the device, and punt if that's not possible */
	return (*sc->sc_accessops->enable)(sc->sc_accesscookie);
}

int
wsmouseread(dev_t dev, struct uio *uio, int flags)
{
	struct wsmouse_softc *sc = wsmouse_cd.cd_devs[minor(dev)];
	int error;

	if (sc->sc_dying)
		return (EIO);

#ifdef DIAGNOSTIC
	if (sc->sc_base.me_evp == NULL) {
		printf("wsmouseread: evp == NULL\n");
		return (EINVAL);
	}
#endif

	sc->sc_refcnt++;
	error = wsevent_read(sc->sc_base.me_evp, uio, flags);
	if (--sc->sc_refcnt < 0) {
		wakeup(sc);
		error = EIO;
	}
	return (error);
}

int
wsmouseioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	return (wsmousedoioctl(wsmouse_cd.cd_devs[minor(dev)],
	    cmd, data, flag, p));
}

/* A wrapper around the ioctl() workhorse to make reference counting easy. */
int
wsmousedoioctl(struct device *dv, u_long cmd, caddr_t data, int flag,
    struct proc *p)
{
	struct wsmouse_softc *sc = (struct wsmouse_softc *)dv;
	int error;

	sc->sc_refcnt++;
	error = wsmouse_do_ioctl(sc, cmd, data, flag, p);
	if (--sc->sc_refcnt < 0)
		wakeup(sc);
	return (error);
}

int
wsmouse_param_ioctl(struct wsmouse_softc *sc,
    u_long cmd, struct wsmouse_param *params, u_int nparams)
{
	struct wsmouse_param *buf;
	int error, s, size;

	if (params == NULL || nparams > WSMOUSECFG_MAX)
		return (EINVAL);

	size = nparams * sizeof(struct wsmouse_param);
	buf = malloc(size, M_DEVBUF, M_WAITOK);
	if (buf == NULL)
		return (ENOMEM);

	if ((error = copyin(params, buf, size))) {
		free(buf, M_DEVBUF, size);
		return (error);
	}

	s = spltty();
	if (cmd == WSMOUSEIO_SETPARAMS) {
		if (wsmouse_set_params((struct device *) sc, buf, nparams))
			error = EINVAL;
	} else {
		if (wsmouse_get_params((struct device *) sc, buf, nparams))
			error = EINVAL;
		else
			error = copyout(buf, params, size);
	}
	splx(s);
	free(buf, M_DEVBUF, size);
	return (error);
}

int
wsmouse_do_ioctl(struct wsmouse_softc *sc, u_long cmd, caddr_t data, int flag,
    struct proc *p)
{
	int error;

	if (sc->sc_dying)
		return (EIO);

	/*
	 * Try the generic ioctls that the wsmouse interface supports.
	 */

	switch (cmd) {
	case FIOASYNC:
	case FIOSETOWN:
	case TIOCSPGRP:
		if ((flag & FWRITE) == 0)
			return (EACCES);
	}

	switch (cmd) {
	case FIONBIO:		/* we will remove this someday (soon???) */
		return (0);

	case FIOASYNC:
		if (sc->sc_base.me_evp == NULL)
			return (EINVAL);
		sc->sc_base.me_evp->async = *(int *)data != 0;
		return (0);

	case FIOSETOWN:
		if (sc->sc_base.me_evp == NULL)
			return (EINVAL);
		if (-*(int *)data != sc->sc_base.me_evp->io->ps_pgid
		    && *(int *)data != sc->sc_base.me_evp->io->ps_pid)
			return (EPERM);
		return (0);

	case TIOCSPGRP:
		if (sc->sc_base.me_evp == NULL)
			return (EINVAL);
		if (*(int *)data != sc->sc_base.me_evp->io->ps_pgid)
			return (EPERM);
		return (0);
	case WSMOUSEIO_GETPARAMS:
	case WSMOUSEIO_SETPARAMS:
		return (wsmouse_param_ioctl(sc, cmd,
		    ((struct wsmouse_parameters *) data)->params,
		    ((struct wsmouse_parameters *) data)->nparams));
	}

	/*
	 * Try the mouse driver for WSMOUSEIO ioctls.  It returns -1
	 * if it didn't recognize the request.
	 */
	error = (*sc->sc_accessops->ioctl)(sc->sc_accesscookie, cmd,
	    data, flag, p);
	return (error != -1 ? error : ENOTTY);
}

int
wsmousepoll(dev_t dev, int events, struct proc *p)
{
	struct wsmouse_softc *sc = wsmouse_cd.cd_devs[minor(dev)];

	if (sc->sc_base.me_evp == NULL)
		return (POLLERR);
	return (wsevent_poll(sc->sc_base.me_evp, events, p));
}

int
wsmousekqfilter(dev_t dev, struct knote *kn)
{
	struct wsmouse_softc *sc = wsmouse_cd.cd_devs[minor(dev)];

	if (sc->sc_base.me_evp == NULL)
		return (ENXIO);
	return (wsevent_kqfilter(sc->sc_base.me_evp, kn));
}

#if NWSMUX > 0
int
wsmouse_mux_open(struct wsevsrc *me, struct wseventvar *evp)
{
	struct wsmouse_softc *sc = (struct wsmouse_softc *)me;

	if (sc->sc_base.me_evp != NULL)
		return (EBUSY);

	return wsmousedoopen(sc, evp);
}

int
wsmouse_mux_close(struct wsevsrc *me)
{
	struct wsmouse_softc *sc = (struct wsmouse_softc *)me;

	sc->sc_base.me_evp = NULL;
	(*sc->sc_accessops->disable)(sc->sc_accesscookie);

	return (0);
}

int
wsmouse_add_mux(int unit, struct wsmux_softc *muxsc)
{
	struct wsmouse_softc *sc;

	if (unit < 0 || unit >= wsmouse_cd.cd_ndevs ||
	    (sc = wsmouse_cd.cd_devs[unit]) == NULL)
		return (ENXIO);

	if (sc->sc_base.me_parent != NULL || sc->sc_base.me_evp != NULL)
		return (EBUSY);

	return (wsmux_attach_sc(muxsc, &sc->sc_base));
}
#endif	/* NWSMUX > 0 */

void
wsmouse_buttons(struct device *sc, u_int buttons)
{
	struct btn_state *btn = &((struct wsmouse_softc *) sc)->sc_input.btn;

	if (btn->sync)
		/* Restore the old state. */
		btn->buttons ^= btn->sync;

	btn->sync = btn->buttons ^ buttons;
	btn->buttons = buttons;
}

void
wsmouse_motion(struct device *sc, int dx, int dy, int dz, int dw)
{
	struct motion_state *motion =
	    &((struct wsmouse_softc *) sc)->sc_input.motion;

	motion->dx = dx;
	motion->dy = dy;
	motion->dz = dz;
	motion->dw = dw;
	if (dx || dy || dz || dw)
		motion->sync |= SYNC_DELTAS;
}

/*
 * Handle absolute coordinates.
 *
 * x_delta/y_delta are used by touchpad code. The values are only
 * valid if the SYNC-flags are set, and will be cleared by update- or
 * conversion-functions if a touch shouldn't trigger pointer motion.
 */
void
wsmouse_position(struct device *sc, int x, int y)
{
	struct motion_state *motion =
	    &((struct wsmouse_softc *) sc)->sc_input.motion;
	int delta;

	delta = x - motion->x;
	if (delta) {
		motion->x = x;
		motion->sync |= SYNC_X;
		motion->x_delta = delta;
	}
	delta = y - motion->y;
	if (delta) {
		motion->y = y;
		motion->sync |= SYNC_Y;
		motion->y_delta = delta;
	}
}

static inline int
normalized_pressure(struct wsmouseinput *input, int pressure)
{
	int limit = imax(input->touch.min_pressure, 1);

	if (pressure >= limit)
		return pressure;
	else
		return (pressure < 0 ? limit : 0);
}

void
wsmouse_touch(struct device *sc, int pressure, int contacts)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	struct touch_state *touch = &input->touch;

	pressure = normalized_pressure(input, pressure);
	contacts = (pressure ? imax(contacts, 1) : 0);

	if (pressure == 0 || pressure != touch->pressure) {
		/*
		 * pressure == 0: Drivers may report possibly arbitrary
		 * coordinates in this case; touch_update will correct them.
		 */
		touch->pressure = pressure;
		touch->sync |= SYNC_PRESSURE;
	}
	touch->prev_contacts = touch->contacts;
	if (contacts != touch->contacts) {
		touch->contacts = contacts;
		touch->sync |= SYNC_CONTACTS;
	}
}

void
wsmouse_mtstate(struct device *sc, int slot, int x, int y, int pressure)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	struct mt_state *mt = &input->mt;
	struct mt_slot *mts;
	u_int bit;
	int initial;

	if (slot < 0 || slot >= mt->num_slots)
		return;

	bit = (1 << slot);
	mt->frame |= bit;

	/* Is this a new touch? */
	initial = ((mt->touches & bit) == (mt->sync[MTS_TOUCH] & bit));

	mts = &mt->slots[slot];
	if (x != mts->x || initial) {
		mts->x = x;
		mt->sync[MTS_X] |= bit;
	}
	if (y != mts->y || initial) {
		mts->y = y;
		mt->sync[MTS_Y] |= bit;
	}
	pressure = normalized_pressure(input, pressure);
	if (pressure != mts->pressure || initial) {
		mts->pressure = pressure;
		mt->sync[MTS_PRESSURE] |= bit;

		if (pressure) {
			if ((mt->touches & bit) == 0) {
				mt->num_touches++;
				mt->touches |= bit;
				mt->sync[MTS_TOUCH] |= bit;
			}
		} else if (mt->touches & bit) {
			mt->num_touches--;
			mt->touches ^= bit;
			mt->sync[MTS_TOUCH] |= bit;
		}
	}
}

void
wsmouse_set(struct device *sc, enum wsmouseval type, int value, int aux)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	struct mt_slot *mts;

	if (WSMOUSE_IS_MT_CODE(type)) {
		if (aux < 0 || aux >= input->mt.num_slots)
			return;
		mts = &input->mt.slots[aux];
	}

	switch (type) {
	case WSMOUSE_REL_X:
		value += input->motion.x; /* fall through */
	case WSMOUSE_ABS_X:
		wsmouse_position(sc, value, input->motion.y);
		return;
	case WSMOUSE_REL_Y:
		value += input->motion.y;
	case WSMOUSE_ABS_Y:
		wsmouse_position(sc, input->motion.x, value);
		return;
	case WSMOUSE_PRESSURE:
		wsmouse_touch(sc, value, input->touch.contacts);
		return;
	case WSMOUSE_CONTACTS:
		/* Contact counts can be overridden by wsmouse_touch. */
		if (value != input->touch.contacts) {
			input->touch.contacts = value;
			input->touch.sync |= SYNC_CONTACTS;
		}
		return;
	case WSMOUSE_TOUCH_WIDTH:
		if (value != input->touch.width) {
			input->touch.width = value;
			input->touch.sync |= SYNC_TOUCH_WIDTH;
		}
		return;
	case WSMOUSE_MT_REL_X:
		value += mts->x; /* fall through */
	case WSMOUSE_MT_ABS_X:
		wsmouse_mtstate(sc, aux, value, mts->y, mts->pressure);
		return;
	case WSMOUSE_MT_REL_Y:
		value += mts->y;
	case WSMOUSE_MT_ABS_Y:
		wsmouse_mtstate(sc, aux, mts->x, value, mts->pressure);
		return;
	case WSMOUSE_MT_PRESSURE:
		wsmouse_mtstate(sc, aux, mts->x, mts->y, value);
		return;
	}
}

/* Make touch and motion state consistent. */
void
wsmouse_touch_update(struct wsmouseinput *input)
{
	struct motion_state *motion = &input->motion;
	struct touch_state *touch = &input->touch;

	if (touch->pressure == 0) {
		/* Restore valid coordinates. */
		if (motion->sync & SYNC_X)
			motion->x -= motion->x_delta;
		if (motion->sync & SYNC_Y)
			motion->y -= motion->y_delta;
		/* Don't generate motion/position events. */
		motion->sync &= ~SYNC_POSITION;
	}
	if (touch->sync & SYNC_CONTACTS)
		/* Suppress pointer motion. */
		motion->x_delta = motion->y_delta = 0;

	if ((touch->sync & SYNC_PRESSURE) && touch->min_pressure) {
		if (touch->pressure >= input->filter.pressure_hi)
			touch->min_pressure = input->filter.pressure_lo;
		else if (touch->pressure < input->filter.pressure_lo)
			touch->min_pressure = input->filter.pressure_hi;
	}
}

/* Normalize multitouch state. */
void
wsmouse_mt_update(struct wsmouseinput *input)
{
	int i;

	/*
	 * The same as above: There may be arbitrary coordinates if
	 * (pressure == 0). Clear the sync flags for touches that have
	 * been released.
	 */
	if (input->mt.sync[MTS_TOUCH] & ~input->mt.touches) {
		for (i = MTS_X; i < MTS_SIZE; i++)
			input->mt.sync[i] &= input->mt.touches;
	}
}

/*
 * Select the pointer-controlling MT slot.
 *
 * Pointer-control is assigned to slots with non-zero motion deltas if
 * at least one such slot exists. This function doesn't impose any
 * restrictions on the way drivers use wsmouse_mtstate(), it covers
 * partial, unordered, and "delta-filtered" input.
 *
 * The "cycle" is the set of slots with X/Y updates in previous sync
 * operations; it will be cleared and rebuilt whenever a slot that is
 * being updated is already a member. If a cycle ends that doesn't
 * contain the pointer-controlling slot, a new slot will be selected.
 */
void
wsmouse_ptr_ctrl(struct mt_state *mt)
{
	u_int updates;
	int select, slot;

	mt->prev_ptr = mt->ptr;

	if (mt->num_touches <= 1) {
		mt->ptr = mt->touches;
		mt->ptr_cycle = mt->ptr;
		return;
	}

	/*
	 * If there is no pointer-controlling slot or it is inactive,
	 * select a new one.
	 */
	select = ((mt->ptr & mt->touches) == 0);

	/* Remove slots without X/Y deltas from the cycle. */
	updates = (mt->sync[MTS_X] | mt->sync[MTS_Y]) & ~mt->sync[MTS_TOUCH];
	mt->ptr_cycle &= ~(mt->frame ^ updates);

	if (mt->ptr_cycle & updates) {
		select |= ((mt->ptr_cycle & mt->ptr) == 0);
		mt->ptr_cycle = updates;
	} else {
		mt->ptr_cycle |= updates;
	}
	if (select) {
		slot = (mt->ptr_cycle
		    ? ffs(mt->ptr_cycle) - 1 : ffs(mt->touches) - 1);
		mt->ptr = (1 << slot);
	}
}

/* Derive touch and motion state from MT state. */
void
wsmouse_mt_convert(struct device *sc)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	struct mt_state *mt = &input->mt;
	struct mt_slot *mts;
	int slot, pressure;

	wsmouse_ptr_ctrl(mt);

	if (mt->ptr) {
		slot = ffs(mt->ptr) - 1;
		mts = &mt->slots[slot];
		wsmouse_position(sc, mts->x, mts->y);
		if (mt->ptr != mt->prev_ptr)
			/* Suppress pointer motion. */
			input->motion.x_delta = input->motion.y_delta = 0;
		pressure = mts->pressure;
	} else {
		pressure = 0;
	}

	wsmouse_touch(sc, pressure, mt->num_touches);
}

void
wsmouse_evq_put(struct evq_access *evq, int ev_type, int ev_value)
{
	struct wscons_event *ev;
	int space;

	space = evq->evar->get - evq->put;
	if (space != 1 && space != 1 - WSEVENT_QSIZE) {
		ev = &evq->evar->q[evq->put++];
		evq->put %= WSEVENT_QSIZE;
		ev->type = ev_type;
		ev->value = ev_value;
		memcpy(&ev->time, &evq->ts, sizeof(struct timespec));
		evq->result |= EVQ_RESULT_SUCCESS;
	} else {
		evq->result = EVQ_RESULT_OVERFLOW;
	}
}


void
wsmouse_btn_sync(struct btn_state *btn, struct evq_access *evq)
{
	int button, ev_type;
	u_int bit, sync;

	for (sync = btn->sync; sync; sync ^= bit) {
		button = ffs(sync) - 1;
		bit = (1 << button);
		ev_type = (btn->buttons & bit) ? BTN_DOWN_EV : BTN_UP_EV;
		wsmouse_evq_put(evq, ev_type, button);
	}
}

/*
 * Scale with a [*.12] fixed-point factor and a remainder:
 */
static inline int
scale(int val, int factor, int *rmdr)
{
	val = val * factor + *rmdr;
	if (val >= 0) {
		*rmdr = val & 0xfff;
		return (val >> 12);
	} else {
		*rmdr = -(-val & 0xfff);
		return -(-val >> 12);
	}
}

void
wsmouse_motion_sync(struct wsmouseinput *input, struct evq_access *evq)
{
	struct motion_state *motion = &input->motion;
	struct axis_filter *h = &input->filter.h;
	struct axis_filter *v = &input->filter.v;
	int x, y, dx, dy;

	if (motion->sync & SYNC_DELTAS) {
		dx = h->inv ? -motion->dx : motion->dx;
		dy = v->inv ? -motion->dy : motion->dy;
		if (h->scale)
			dx = scale(dx, h->scale, &h->rmdr);
		if (v->scale)
			dy = scale(dy, v->scale, &v->rmdr);
		if (dx)
			wsmouse_evq_put(evq, DELTA_X_EV(input), dx);
		if (dy)
			wsmouse_evq_put(evq, DELTA_Y_EV(input), dy);
		if (motion->dz)
			wsmouse_evq_put(evq, DELTA_Z_EV, motion->dz);
		if (motion->dw)
			wsmouse_evq_put(evq, DELTA_W_EV, motion->dw);
	}
	if (motion->sync & SYNC_POSITION) {
		if (motion->sync & SYNC_X) {
			x = (h->inv ? h->inv - motion->x : motion->x);
			wsmouse_evq_put(evq, ABS_X_EV(input), x);
		}
		if (motion->sync & SYNC_Y) {
			y = (v->inv ? v->inv - motion->y : motion->y);
			wsmouse_evq_put(evq, ABS_Y_EV(input), y);
		}
		if (motion->x_delta == 0 && motion->y_delta == 0
		    && (input->flags & TPAD_NATIVE_MODE))
			/* Suppress pointer motion. */
			wsmouse_evq_put(evq, WSCONS_EVENT_TOUCH_RESET, 0);
	}
}

void
wsmouse_touch_sync(struct wsmouseinput *input, struct evq_access *evq)
{
	struct touch_state *touch = &input->touch;

	if (touch->sync & SYNC_PRESSURE)
		wsmouse_evq_put(evq, ABS_Z_EV, touch->pressure);
	if (touch->sync & SYNC_CONTACTS)
		wsmouse_evq_put(evq, ABS_W_EV, touch->contacts);
	if ((touch->sync & SYNC_TOUCH_WIDTH)
	    && (input->flags & TPAD_NATIVE_MODE))
		wsmouse_evq_put(evq, WSCONS_EVENT_TOUCH_WIDTH, touch->width);
}

static inline void
clear_sync_flags(struct wsmouseinput *input)
{
	int i;

	input->btn.sync = 0;
	input->sbtn.sync = 0;
	input->motion.sync = 0;
	input->touch.sync = 0;
	if (input->mt.frame) {
		input->mt.frame = 0;
		for (i = 0; i < MTS_SIZE; i++)
			input->mt.sync[i] = 0;
	}
}

void
wsmouse_input_sync(struct device *sc)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	struct evq_access evq;

	evq.evar = *input->evar;
	if (evq.evar == NULL)
		return;
	evq.put = evq.evar->put;
	evq.result = EVQ_RESULT_NONE;
	getnanotime(&evq.ts);

	add_mouse_randomness(input->btn.buttons
	    ^ input->motion.dx ^ input->motion.dy
	    ^ input->motion.x ^ input->motion.y
	    ^ input->motion.dz ^ input->motion.dw);

	if (input->mt.frame) {
		wsmouse_mt_update(input);
		wsmouse_mt_convert(sc);
	}
	if (input->touch.sync)
		wsmouse_touch_update(input);

	if (input->flags & TPAD_COMPAT_MODE)
		wstpad_compat_convert(input, &evq);

	if (input->flags & RESYNC) {
		input->flags &= ~RESYNC;
		input->motion.sync &= SYNC_POSITION;
		input->motion.x_delta = input->motion.y_delta = 0;
	}

	if (input->btn.sync)
		wsmouse_btn_sync(&input->btn, &evq);
	if (input->sbtn.sync)
		wsmouse_btn_sync(&input->sbtn, &evq);
	if (input->motion.sync)
		wsmouse_motion_sync(input, &evq);
	if (input->touch.sync)
		wsmouse_touch_sync(input, &evq);
	/* No MT events are generated yet. */

	if (evq.result == EVQ_RESULT_SUCCESS) {
		wsmouse_evq_put(&evq, WSCONS_EVENT_SYNC, 0);
		if (evq.result == EVQ_RESULT_SUCCESS) {
			evq.evar->put = evq.put;
			WSEVENT_WAKEUP(evq.evar);
		}
	}

	if (evq.result != EVQ_RESULT_OVERFLOW)
		clear_sync_flags(input);
	else
		input->flags |= RESYNC;
}

int
wsmouse_id_to_slot(struct device *sc, int id)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	struct mt_state *mt = &input->mt;
	int slot;

	if (mt->num_slots == 0)
		return (-1);

	FOREACHBIT(mt->touches, slot) {
		if (mt->slots[slot].id == id)
			return slot;
	}
	slot = ffs(~(mt->touches | mt->frame)) - 1;
	if (slot >= 0 && slot < mt->num_slots) {
		mt->frame |= 1 << slot;
		mt->slots[slot].id = id;
		return (slot);
	} else {
		return (-1);
	}
}

/*
 * Find a minimum-weight matching for an m-by-n matrix.
 *
 * m must be greater than or equal to n. The size of the buffer must be
 * at least 3m + 3n.
 *
 * On return, the first m elements of the buffer contain the row-to-
 * column mappings, i.e., buffer[i] is the column index for row i, or -1
 * if there is no assignment for that row (which may happen if n < m).
 *
 * Wrong results because of overflows will not occur with input values
 * in the range of 0 to INT_MAX / 2 inclusive.
 *
 * The function applies the Dinic-Kronrod algorithm. It is not modern or
 * popular, but it seems to be a good choice for small matrices at least.
 * The original form of the algorithm is modified as follows: There is no
 * initial search for row minima, the initial assignments are in a
 * "virtual" column with the index -1 and zero values. This permits inputs
 * with n < m, and it simplifies the reassignments.
 */
void
wsmouse_matching(int *matrix, int m, int n, int *buffer)
{
	int i, j, k, d, e, row, col, delta;
	int *p;
	int *r2c = buffer;	/* row-to-column assignments */
	int *red = r2c + m;	/* reduced values of the assignments */
	int *mc = red + m;	/* row-wise minimal elements of cs */
	int *cs = mc + m;	/* the column set */
	int *c2r = cs + n;	/* column-to-row assignments in cs */
	int *cd = c2r + n;	/* column deltas (reduction) */

	for (p = r2c; p < red; *p++ = -1) {}
	for (; p < mc; *p++ = 0) {}
	for (col = 0; col < n; col++) {
		delta = INT_MAX;
		for (i = 0, p = matrix + col; i < m; i++, p += n) {
			d = *p - red[i];
			if (d < delta || (d == delta && r2c[i] < 0)) {
				delta = d;
				row = i;
			}
		}
		cd[col] = delta;
		if (r2c[row] < 0) {
			r2c[row] = col;
			continue;
		}
		for (p = mc; p < cs; *p++ = col) {}
		for (k = 0; (j = r2c[row]) >= 0;) {
			cs[k++] = j;
			c2r[j] = row;
			mc[row] -= n;
			delta = INT_MAX;
			for (i = 0, p = matrix; i < m; i++, p += n)
				if (mc[i] >= 0) {
					d = p[mc[i]] - cd[mc[i]];
					e = p[j] - cd[j];
					if (e < d) {
						d = e;
						mc[i] = j;
					}
					d -= red[i];
					if (d < delta || (d == delta
					    && r2c[i] < 0)) {
						delta = d;
						row = i;
					}
				}
			cd[col] += delta;
			for (i = 0; i < k; i++) {
				cd[cs[i]] += delta;
				red[c2r[cs[i]]] -= delta;
			}
		}
		for (j = mc[row]; (r2c[row] = j) != col;) {
			row = c2r[j];
			j = mc[row] + n;
		}
	}
}

void
wsmouse_mtframe(struct device *sc, struct mtpoint *pt, int size)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	struct mt_state *mt = &input->mt;
	int i, j, m, n, dx, dy, slot, maxdist;
	int *p, *r2c, *c2r;
	u_int touches;

	if (mt->num_slots == 0 || mt->matrix == NULL)
		return;

	size = imax(0, imin(size, mt->num_slots));
	p = mt->matrix;
	touches = mt->touches;
	if (mt->num_touches >= size) {
		FOREACHBIT(touches, slot)
			for (i = 0; i < size; i++) {
				dx = pt[i].x - mt->slots[slot].x;
				dy = pt[i].y - mt->slots[slot].y;
				*p++ = dx * dx + dy * dy;
			}
		m = mt->num_touches;
		n = size;
	} else {
		for (i = 0; i < size; i++)
			FOREACHBIT(touches, slot) {
				dx = pt[i].x - mt->slots[slot].x;
				dy = pt[i].y - mt->slots[slot].y;
				*p++ = dx * dx + dy * dy;
			}
		m = size;
		n = mt->num_touches;
	}
	wsmouse_matching(mt->matrix, m, n, p);

	r2c = p;
	c2r = p + m;
	maxdist = input->filter.tracking_maxdist;
	maxdist = (maxdist ? maxdist * maxdist : INT_MAX);
	for (i = 0, p = mt->matrix; i < m; i++, p += n)
		if ((j = r2c[i]) >= 0) {
			if (p[j] <= maxdist)
				c2r[j] = i;
			else
				c2r[j] = r2c[i] = -1;
		}

	p = (n == size ? c2r : r2c);
	for (i = 0; i < size; i++)
		if (*p++ < 0) {
			slot = ffs(~(mt->touches | mt->frame)) - 1;
			if (slot < 0 || slot >= mt->num_slots)
				break;
			wsmouse_mtstate(sc, slot,
			    pt[i].x, pt[i].y, pt[i].pressure);
			pt[i].slot = slot;
		}

	p = (n == size ? r2c : c2r);
	FOREACHBIT(touches, slot)
		if ((i = *p++) >= 0) {
			wsmouse_mtstate(sc, slot,
			    pt[i].x, pt[i].y, pt[i].pressure);
			pt[i].slot = slot;
		} else {
			wsmouse_mtstate(sc, slot, 0, 0, 0);
		}
}

static inline void
free_mt_slots(struct wsmouseinput *input)
{
	int n, size;

	if ((n = input->mt.num_slots)) {
		size = n * sizeof(struct mt_slot);
		if (input->flags & MT_TRACKING)
			size += MATRIX_SIZE(n);
		input->mt.num_slots = 0;
		free(input->mt.slots, M_DEVBUF, size);
		input->mt.slots = NULL;
		input->mt.matrix = NULL;
	}
}

/* Allocate the MT slots and, if necessary, the buffers for MT tracking. */
int
wsmouse_mt_init(struct device *sc, int num_slots, int tracking)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	int n, size;

	if (num_slots == input->mt.num_slots
	    && (!tracking == ((input->flags & MT_TRACKING) == 0)))
		return (0);

	free_mt_slots(input);

	if (tracking)
		input->flags |= MT_TRACKING;
	else
		input->flags &= ~MT_TRACKING;
	n = imin(imax(num_slots, 0), WSMOUSE_MT_SLOTS_MAX);
	if (n) {
		size = n * sizeof(struct mt_slot);
		if (input->flags & MT_TRACKING)
			size += MATRIX_SIZE(n);
		input->mt.slots = malloc(size, M_DEVBUF, M_WAITOK | M_ZERO);
		if (input->mt.slots != NULL) {
			if (input->flags & MT_TRACKING)
				input->mt.matrix = (int *)
				    (input->mt.slots + n);
			input->mt.num_slots = n;
			return (0);
		}
	}
	return (-1);
}

int
wsmouse_get_params(struct device *sc,
    struct wsmouse_param *params, u_int nparams)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	int i, key, error = 0;

	for (i = 0; i < nparams; i++) {
		key = params[i].key;
		switch (key) {
		case WSMOUSECFG_DX_SCALE:
			params[i].value = input->filter.h.scale;
			break;
		case WSMOUSECFG_DY_SCALE:
			params[i].value = input->filter.v.scale;
			break;
		case WSMOUSECFG_PRESSURE_LO:
			params[i].value = input->filter.pressure_lo;
			break;
		case WSMOUSECFG_PRESSURE_HI:
			params[i].value = input->filter.pressure_hi;
			break;
		case WSMOUSECFG_TRKMAXDIST:
			params[i].value = input->filter.tracking_maxdist;
			break;
		case WSMOUSECFG_SWAPXY:
			params[i].value = input->filter.swapxy;
			break;
		case WSMOUSECFG_X_INV:
			params[i].value = input->filter.h.inv;
			break;
		case WSMOUSECFG_Y_INV:
			params[i].value = input->filter.v.inv;
			break;
		case WSMOUSECFG_DX_MAX:
			params[i].value = input->filter.h.dmax;
			break;
		case WSMOUSECFG_DY_MAX:
			params[i].value = input->filter.v.dmax;
			break;
		case WSMOUSECFG_X_HYSTERESIS:
			params[i].value = input->filter.h.hysteresis;
			break;
		case WSMOUSECFG_Y_HYSTERESIS:
			params[i].value = input->filter.v.hysteresis;
			break;
		case WSMOUSECFG_DECELERATION:
			params[i].value = input->filter.dclr;
			break;
		default:
			error = wstpad_get_param(input, key, &params[i].value);
			if (error != 0)
				return (error);
			break;
		}
	}

	return (0);
}

int
wsmouse_set_params(struct device *sc,
    const struct wsmouse_param *params, u_int nparams)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	int i, val, key, needreset = 0, error = 0;

	for (i = 0; i < nparams; i++) {
		key = params[i].key;
		val = params[i].value;
		switch (params[i].key) {
		case WSMOUSECFG_PRESSURE_LO:
			input->filter.pressure_lo = val;
			if (val > input->filter.pressure_hi)
				input->filter.pressure_hi = val;
			input->touch.min_pressure = input->filter.pressure_hi;
			break;
		case WSMOUSECFG_PRESSURE_HI:
			input->filter.pressure_hi = val;
			if (val < input->filter.pressure_lo)
				input->filter.pressure_lo = val;
			input->touch.min_pressure = val;
			break;
		case WSMOUSECFG_X_HYSTERESIS:
			input->filter.h.hysteresis = val;
			input->filter.h.acc = 0;
			break;
		case WSMOUSECFG_Y_HYSTERESIS:
			input->filter.v.hysteresis = val;
			input->filter.v.acc = 0;
			break;
		case WSMOUSECFG_DECELERATION:
			input->filter.dclr = val;
			wstpad_init_deceleration(input);
			break;
		case WSMOUSECFG_DX_SCALE:
			input->filter.h.scale = val;
			break;
		case WSMOUSECFG_DY_SCALE:
			input->filter.v.scale = val;
			break;
		case WSMOUSECFG_TRKMAXDIST:
			input->filter.tracking_maxdist = val;
			break;
		case WSMOUSECFG_SWAPXY:
			input->filter.swapxy = val;
			break;
		case WSMOUSECFG_X_INV:
			input->filter.h.inv = val;
			break;
		case WSMOUSECFG_Y_INV:
			input->filter.v.inv = val;
			break;
		case WSMOUSECFG_DX_MAX:
			input->filter.h.dmax = val;
			break;
		case WSMOUSECFG_DY_MAX:
			input->filter.v.dmax = val;
			break;
		default:
			needreset = 1;
			error = wstpad_set_param(input, key, val);
			if (error != 0)
				return (error);
			break;
		}
	}

	/* Reset soft-states if touchpad parameters changed */
	if (needreset) {
		wstpad_reset(input);
		return (wstpad_configure(input));
	}

	return (0);
}

int
wsmouse_set_mode(struct device *sc, int mode)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;

	if (mode == WSMOUSE_COMPAT) {
		input->flags &= ~TPAD_NATIVE_MODE;
		input->flags |= TPAD_COMPAT_MODE;
		return (0);
	} else if (mode == WSMOUSE_NATIVE) {
		input->flags &= ~TPAD_COMPAT_MODE;
		input->flags |= TPAD_NATIVE_MODE;
		return (0);
	}
	return (-1);
}

struct wsmousehw *wsmouse_get_hw(struct device *sc)
{
	return &((struct wsmouse_softc *) sc)->sc_input.hw;
}

/*
 * Create a default configuration based on the hardware infos in the 'hw'
 * fields. The 'params' argument is optional, hardware drivers can use it
 * to modify the generic defaults. Up to now this function is only useful
 * for touchpads.
 */
int
wsmouse_configure(struct device *sc,
    struct wsmouse_param *params, u_int nparams)
{
	struct wsmouseinput *input = &((struct wsmouse_softc *) sc)->sc_input;
	int error;

	if (!(input->flags & CONFIGURED)) {
		if (input->hw.x_max && input->hw.y_max) {
			if (input->hw.flags & WSMOUSEHW_LR_DOWN) {
				input->filter.v.inv =
				    input->hw.y_max + input->hw.y_min;
			}
		}
		input->filter.ratio = 1 << 12;
		if (input->hw.h_res > 0 && input->hw.v_res > 0) {
			input->filter.ratio *= input->hw.h_res;
			input->filter.ratio /= input->hw.v_res;
		}
		if (wsmouse_mt_init(sc, input->hw.mt_slots,
		    (input->hw.flags & WSMOUSEHW_MT_TRACKING))) {
			printf("wsmouse_configure: "
			    "MT initialization failed.\n");
			return (-1);
		}
		if (IS_TOUCHPAD(input) && wstpad_configure(input)) {
			printf("wstpad_configure: "
			    "Initialization failed.\n");
			return (-1);
		}
		if (params != NULL) {
			if ((error = wsmouse_set_params(sc, params, nparams)))
				return (error);
		}
		input->flags |= CONFIGURED;
	}
	if (IS_TOUCHPAD(input))
		wsmouse_set_mode(sc, WSMOUSE_COMPAT);

	return (0);
}


void
wsmouse_input_reset(struct wsmouseinput *input)
{
	int num_slots, *matrix;
	struct mt_slot *slots;

	memset(&input->btn, 0, sizeof(struct btn_state));
	memset(&input->motion, 0, sizeof(struct motion_state));
	memset(&input->touch, 0, sizeof(struct touch_state));
	input->touch.min_pressure = input->filter.pressure_hi;
	if ((num_slots = input->mt.num_slots)) {
		slots = input->mt.slots;
		matrix = input->mt.matrix;
		memset(&input->mt, 0, sizeof(struct mt_state));
		memset(slots, 0, num_slots * sizeof(struct mt_slot));
		input->mt.num_slots = num_slots;
		input->mt.slots = slots;
		input->mt.matrix = matrix;
	}
	if (input->tp != NULL)
		wstpad_reset(input);
}

void
wsmouse_input_cleanup(struct wsmouseinput *input)
{
	free_mt_slots(input);
}