xref: /netbsd-src/sys/dev/usb/uatp.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*	$NetBSD: uatp.c,v 1.26 2021/04/24 23:36:59 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 2011-2014 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Taylor R. Campbell.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * uatp(4) - USB Apple Trackpad
34  *
35  * The uatp driver talks the protocol of the USB trackpads found in
36  * Apple laptops since 2005, including PowerBooks, iBooks, MacBooks,
37  * and MacBook Pros.  Some of these also present generic USB HID mice
38  * on another USB report id, which the ums(4) driver can handle, but
39  * Apple's protocol gives more detailed sensor data that lets us detect
40  * multiple fingers to emulate multi-button mice and scroll wheels.
41  */
42 
43 /*
44  * Protocol
45  *
46  * The device has a set of horizontal sensors, each being a column at a
47  * particular position on the x axis that tells you whether there is
48  * pressure anywhere on that column, and vertical sensors, each being a
49  * row at a particular position on the y axis that tells you whether
50  * there is pressure anywhere on that row.
51  *
52  * Whenever the device senses anything, it emits a readout of all of
53  * the sensors, in some model-dependent order.  (For the order, see
54  * read_sample_1 and read_sample_2.)  Each sensor datum is an unsigned
55  * eight-bit quantity representing some measure of pressure.  (Of
56  * course, it really measures capacitance, not pressure, but we'll call
57  * it `pressure' here.)
58  */
59 
60 /*
61  * Interpretation
62  *
63  * To interpret the finger's position on the trackpad, the driver
64  * computes a weighted average over all possible positions, weighted by
65  * the pressure at that position.  The weighted average is computed in
66  * the dimensions of the screen, rather than the trackpad, in order to
67  * admit a finer resolution of positions than the trackpad grid.
68  *
69  * To update the finger's position smoothly on the trackpad, the driver
70  * computes a weighted average of the old raw position, the old
71  * smoothed position, and the new smoothed position.  The weights are
72  * given by the old_raw_weight, old_smoothed_weight, and new_raw_weight
73  * sysctl knobs.
74  *
75  * Finally, to move the cursor, the driver takes the difference between
76  * the old and new positions and accelerates it according to some
77  * heuristic knobs that need to be reworked.
78  *
79  * Finally, there are some bells & whistles to detect tapping and to
80  * emulate a three-button mouse by leaving two or three fingers on the
81  * trackpad while pressing the button.
82  */
83 
84 /*
85  * Future work
86  *
87  * With the raw sensor data available, we could implement fancier bells
88  * & whistles too, such as pinch-to-zoom.  However, wsmouse supports
89  * only four-dimensional mice with buttons, and we already use two
90  * dimensions for mousing and two dimensions for scrolling, so there's
91  * no straightforward way to report zooming and other gestures to the
92  * operating system.  Probably a better way to do this would be just to
93  * attach uhid(4) instead of uatp(4) and to read the raw sensors data
94  * yourself -- but that requires hairy mode switching for recent models
95  * (see geyser34_enable_raw_mode).
96  *
97  * XXX Rework the acceleration knobs.
98  * XXX Implement edge scrolling.
99  * XXX Fix sysctl setup; preserve knobs across suspend/resume.
100  *     (uatp0 detaches and reattaches across suspend/resume, so as
101  *     written, the sysctl tree is torn down and rebuilt, losing any
102  *     state the user may have set.)
103  * XXX Refactor motion state so I can understand it again.
104  *     Should make a struct uatp_motion for all that state.
105  * XXX Add hooks for ignoring trackpad input while typing.
106  */
107 
108 /*
109  * Classifying devices
110  *
111  * I have only one MacBook to test this driver, but the driver should
112  * be applicable to almost every Apple laptop made since the beginning
113  * of 2005, so the driver reports lots of debugging output to help to
114  * classify devices.  Boot with `boot -v' (verbose) and check the
115  * output of `dmesg | grep uatp' to answer the following questions:
116  *
117  * - What devices (vendor, product, class, subclass, proto, USB HID
118  *   report dump) fail to attach when you think they should work?
119  *     (vendor not apple, class not hid, proto not mouse)
120  *
121  * - What devices have an unknown product id?
122  *     `unknown vendor/product id'
123  *
124  * - What devices have the wrong screen-to-trackpad ratios?
125  *     `... x sensors, scaled by ... for ... points on screen'
126  *     `... y sensors, scaled by ... for ... points on screen'
127  *   You can tweak hw.uatp0.x_ratio and hw.uatp0.y_ratio to adjust
128  *   this, up to a maximum of 384 for each value.
129  *
130  * - What devices have the wrong input size?
131  *     `expected input size ... but got ... for Apple trackpad'
132  *
133  * - What devices give wrong-sized packets?
134  *     `discarding ...-byte input'
135  *
136  * - What devices split packets in chunks?
137  *     `partial packet: ... bytes'
138  *
139  * - What devices develop large sensor readouts?
140  *     `large sensor readout: ...'
141  *
142  * - What devices have the wrong number of sensors?  Are there parts of
143  *   your trackpad that the system doesn't seem to notice?  You can
144  *   tweak hw.uatp0.x_sensors and hw.uatp0.y_sensors, up to a maximum
145  *   of 32 for each value.
146  */
147 
148 #include <sys/cdefs.h>
149 __KERNEL_RCSID(0, "$NetBSD: uatp.c,v 1.26 2021/04/24 23:36:59 thorpej Exp $");
150 
151 #ifdef _KERNEL_OPT
152 #include "opt_usb.h"
153 #endif
154 
155 #include <sys/types.h>
156 #include <sys/param.h>
157 #include <sys/atomic.h>
158 #include <sys/device.h>
159 #include <sys/errno.h>
160 #include <sys/ioctl.h>
161 #include <sys/kernel.h>
162 #include <sys/module.h>
163 #include <sys/sysctl.h>
164 #include <sys/systm.h>
165 #include <sys/time.h>
166 
167 /* Order is important here...sigh...  */
168 #include <dev/usb/usb.h>
169 #include <dev/usb/usbdi.h>
170 #include <dev/usb/usbdi_util.h>
171 #include <dev/usb/usbdevs.h>
172 #include <dev/usb/uhidev.h>
173 #include <dev/usb/usbhid.h>
174 #include <dev/hid/hid.h>
175 
176 #include <dev/wscons/wsconsio.h>
177 #include <dev/wscons/wsmousevar.h>
178 
179 #define CHECK(condition, fail) do {					\
180 	if (! (condition)) {						\
181 		aprint_error_dev(uatp_dev(sc), "%s: check failed: %s\n",\
182 			__func__, #condition);				\
183 		fail;							\
184 	}								\
185 } while (0)
186 
187 #define UATP_DEBUG_ATTACH	__BIT(0)
188 #define UATP_DEBUG_MISC		__BIT(1)
189 #define UATP_DEBUG_WSMOUSE	__BIT(2)
190 #define UATP_DEBUG_IOCTL	__BIT(3)
191 #define UATP_DEBUG_RESET	__BIT(4)
192 #define UATP_DEBUG_INTR		__BIT(5)
193 #define UATP_DEBUG_PARSE	__BIT(6)
194 #define UATP_DEBUG_TAP		__BIT(7)
195 #define UATP_DEBUG_EMUL_BUTTON	__BIT(8)
196 #define UATP_DEBUG_ACCUMULATE	__BIT(9)
197 #define UATP_DEBUG_STATUS	__BIT(10)
198 #define UATP_DEBUG_SPURINTR	__BIT(11)
199 #define UATP_DEBUG_MOVE		__BIT(12)
200 #define UATP_DEBUG_ACCEL	__BIT(13)
201 #define UATP_DEBUG_TRACK_DIST	__BIT(14)
202 #define UATP_DEBUG_PALM		__BIT(15)
203 
204 /*
205  * Unconditionally enable the debug output so you don't have to
206  * recompile the kernel to diagnose it.  This is not a high-throughput
207  * NIC driver or anything that will be hurt by a few conditionals.
208  */
209 #define	UATP_DEBUG	1
210 
211 #if UATP_DEBUG
212 #  define DPRINTF(sc, flags, format) do {				\
213 	if ((flags) & (sc)->sc_debug_flags) {				\
214 		printf("%s: %s: ", device_xname(uatp_dev(sc)), __func__); \
215 		printf format;						\
216 	}								\
217 } while (0)
218 #else
219 #  define DPRINTF(sc, flags, format) do {} while (0)
220 #endif
221 
222 /* Maximum number of bytes in an incoming packet of sensor data.  */
223 #define UATP_MAX_INPUT_SIZE	81
224 
225 /* Maximum number of sensors in each dimension.  */
226 #define UATP_MAX_X_SENSORS	32
227 #define UATP_MAX_Y_SENSORS	32
228 #define UATP_MAX_SENSORS	32
229 #define UATP_SENSORS		(UATP_MAX_X_SENSORS + UATP_MAX_Y_SENSORS)
230 
231 /* Maximum accumulated sensor value.  */
232 #define UATP_MAX_ACC		0xff
233 
234 /* Maximum screen dimension to sensor dimension ratios.  */
235 #define UATP_MAX_X_RATIO	0x180
236 #define UATP_MAX_Y_RATIO	0x180
237 #define UATP_MAX_RATIO		0x180
238 
239 /* Maximum weight for positions in motion calculation.  */
240 #define UATP_MAX_WEIGHT		0x7f
241 
242 /* Maximum possible trackpad position in a single dimension.  */
243 #define UATP_MAX_POSITION	(UATP_MAX_SENSORS * UATP_MAX_RATIO)
244 
245 /* Bounds on acceleration.  */
246 #define UATP_MAX_MOTION_MULTIPLIER	16
247 
248 /* Status bits transmitted in the last byte of an input packet.  */
249 #define UATP_STATUS_BUTTON	__BIT(0)	/* Button pressed */
250 #define UATP_STATUS_BASE	__BIT(2)	/* Base sensor data */
251 #define UATP_STATUS_POST_RESET	__BIT(4)	/* Post-reset */
252 
253 /* Forward declarations */
254 
255 struct uatp_softc;		/* Device driver state.  */
256 struct uatp_descriptor;		/* Descriptor for a particular model.  */
257 struct uatp_parameters;		/* Parameters common to a set of models.  */
258 struct uatp_knobs;		/* User-settable configuration knobs.  */
259 enum uatp_tap_state {
260 	TAP_STATE_INITIAL,
261 	TAP_STATE_TAPPING,
262 	TAP_STATE_TAPPED,
263 	TAP_STATE_DOUBLE_TAPPING,
264 	TAP_STATE_DRAGGING_DOWN,
265 	TAP_STATE_DRAGGING_UP,
266 	TAP_STATE_TAPPING_IN_DRAG,
267 };
268 
269 static const struct uatp_descriptor *find_uatp_descriptor
270     (const struct uhidev_attach_arg *);
271 static device_t uatp_dev(const struct uatp_softc *);
272 static uint8_t *uatp_x_sample(struct uatp_softc *);
273 static uint8_t *uatp_y_sample(struct uatp_softc *);
274 static int *uatp_x_acc(struct uatp_softc *);
275 static int *uatp_y_acc(struct uatp_softc *);
276 static void uatp_clear_position(struct uatp_softc *);
277 static unsigned int uatp_x_sensors(const struct uatp_softc *);
278 static unsigned int uatp_y_sensors(const struct uatp_softc *);
279 static unsigned int uatp_x_ratio(const struct uatp_softc *);
280 static unsigned int uatp_y_ratio(const struct uatp_softc *);
281 static unsigned int uatp_old_raw_weight(const struct uatp_softc *);
282 static unsigned int uatp_old_smoothed_weight(const struct uatp_softc *);
283 static unsigned int uatp_new_raw_weight(const struct uatp_softc *);
284 static int scale_motion(const struct uatp_softc *, int, int *,
285     const unsigned int *, const unsigned int *);
286 static int uatp_scale_motion(const struct uatp_softc *, int, int *);
287 static int uatp_scale_fast_motion(const struct uatp_softc *, int, int *);
288 static int uatp_match(device_t, cfdata_t, void *);
289 static void uatp_attach(device_t, device_t, void *);
290 static void uatp_setup_sysctl(struct uatp_softc *);
291 static bool uatp_setup_sysctl_knob(struct uatp_softc *, int *, const char *,
292     const char *);
293 static void uatp_childdet(device_t, device_t);
294 static int uatp_detach(device_t, int);
295 static int uatp_activate(device_t, enum devact);
296 static int uatp_enable(void *);
297 static void uatp_disable(void *);
298 static int uatp_ioctl(void *, unsigned long, void *, int, struct lwp *);
299 static void geyser34_enable_raw_mode(struct uatp_softc *);
300 static void geyser34_initialize(struct uatp_softc *);
301 static int geyser34_finalize(struct uatp_softc *);
302 static void geyser34_deferred_reset(struct uatp_softc *);
303 static void geyser34_reset_task(void *);
304 static void uatp_intr(struct uhidev *, void *, unsigned int);
305 static bool base_sample_softc_flag(const struct uatp_softc *, const uint8_t *);
306 static bool base_sample_input_flag(const struct uatp_softc *, const uint8_t *);
307 static void read_sample_1(uint8_t *, uint8_t *, const uint8_t *);
308 static void read_sample_2(uint8_t *, uint8_t *, const uint8_t *);
309 static void accumulate_sample_1(struct uatp_softc *);
310 static void accumulate_sample_2(struct uatp_softc *);
311 static void uatp_input(struct uatp_softc *, uint32_t, int, int, int, int);
312 static uint32_t uatp_tapped_buttons(struct uatp_softc *);
313 static bool interpret_input(struct uatp_softc *, int *, int *, int *, int *,
314     uint32_t *);
315 static unsigned int interpret_dimension(struct uatp_softc *, const int *,
316     unsigned int, unsigned int, unsigned int *, unsigned int *);
317 static void tap_initialize(struct uatp_softc *);
318 static void tap_finalize(struct uatp_softc *);
319 static void tap_enable(struct uatp_softc *);
320 static void tap_disable(struct uatp_softc *);
321 static void tap_transition(struct uatp_softc *, enum uatp_tap_state,
322     const struct timeval *, unsigned int, unsigned int);
323 static void tap_transition_initial(struct uatp_softc *);
324 static void tap_transition_tapping(struct uatp_softc *, const struct timeval *,
325     unsigned int);
326 static void tap_transition_double_tapping(struct uatp_softc *,
327     const struct timeval *, unsigned int);
328 static void tap_transition_dragging_down(struct uatp_softc *);
329 static void tap_transition_tapping_in_drag(struct uatp_softc *,
330     const struct timeval *, unsigned int);
331 static void tap_transition_tapped(struct uatp_softc *, const struct timeval *);
332 static void tap_transition_dragging_up(struct uatp_softc *);
333 static void tap_reset(struct uatp_softc *);
334 static void tap_reset_wait(struct uatp_softc *);
335 static void tap_touched(struct uatp_softc *, unsigned int);
336 static bool tap_released(struct uatp_softc *);
337 static void schedule_untap(struct uatp_softc *);
338 static void untap_callout(void *);
339 static uint32_t emulated_buttons(struct uatp_softc *, unsigned int);
340 static void update_position(struct uatp_softc *, unsigned int,
341     unsigned int, unsigned int, int *, int *, int *, int *);
342 static void move_mouse(struct uatp_softc *, unsigned int, unsigned int,
343     int *, int *);
344 static void scroll_wheel(struct uatp_softc *, unsigned int, unsigned int,
345     int *, int *);
346 static void move(struct uatp_softc *, const char *, unsigned int, unsigned int,
347     int *, int *, int *, int *, unsigned int *, unsigned int *, int *, int *);
348 static int smooth(struct uatp_softc *, unsigned int, unsigned int,
349     unsigned int);
350 static bool motion_below_threshold(struct uatp_softc *, unsigned int,
351     int, int);
352 static int accelerate(struct uatp_softc *, unsigned int, unsigned int,
353     unsigned int, unsigned int, bool, int *);
354 
355 struct uatp_knobs {
356 	/*
357 	 * Button emulation.  What do we do when two or three fingers
358 	 * are on the trackpad when the user presses the button?
359 	 */
360 	unsigned int two_finger_buttons;
361 	unsigned int three_finger_buttons;
362 
363 #if 0
364 	/*
365 	 * Edge scrolling.
366 	 *
367 	 * XXX Implement this.  What units should these be in?
368 	 */
369 	unsigned int top_edge;
370 	unsigned int bottom_edge;
371 	unsigned int left_edge;
372 	unsigned int right_edge;
373 #endif
374 
375 	/*
376 	 * Multifinger tracking.  What do we do with multiple fingers?
377 	 * 0. Ignore them.
378 	 * 1. Try to interpret them as ordinary mousing.
379 	 * 2. Act like a two-dimensional scroll wheel.
380 	 */
381 	unsigned int multifinger_track;
382 
383 	/*
384 	 * Sensor parameters.
385 	 */
386 	unsigned int x_sensors;
387 	unsigned int x_ratio;
388 	unsigned int y_sensors;
389 	unsigned int y_ratio;
390 	unsigned int sensor_threshold;
391 	unsigned int sensor_normalizer;
392 	unsigned int palm_width;
393 	unsigned int old_raw_weight;
394 	unsigned int old_smoothed_weight;
395 	unsigned int new_raw_weight;
396 
397 	/*
398 	 * Motion parameters.
399 	 *
400 	 * XXX There should be a more principled model of acceleration.
401 	 */
402 	unsigned int motion_remainder;
403 	unsigned int motion_threshold;
404 	unsigned int motion_multiplier;
405 	unsigned int motion_divisor;
406 	unsigned int fast_motion_threshold;
407 	unsigned int fast_motion_multiplier;
408 	unsigned int fast_motion_divisor;
409 	unsigned int fast_per_direction;
410 	unsigned int motion_delay;
411 
412 	/*
413 	 * Tapping.
414 	 */
415 	unsigned int tap_limit_msec;
416 	unsigned int double_tap_limit_msec;
417 	unsigned int one_finger_tap_buttons;
418 	unsigned int two_finger_tap_buttons;
419 	unsigned int three_finger_tap_buttons;
420 	unsigned int tap_track_distance_limit;
421 };
422 
423 static const struct uatp_knobs default_knobs = {
424 	/*
425 	 * Button emulation.  Fingers on the trackpad don't change it
426 	 * by default -- it's still the left button.
427 	 *
428 	 * XXX The left button should have a name.
429 	 */
430 	 .two_finger_buttons	= 1,
431 	 .three_finger_buttons	= 1,
432 
433 #if 0
434 	/*
435 	 * Edge scrolling.  Off by default.
436 	 */
437 	.top_edge		= 0,
438 	.bottom_edge		= 0,
439 	.left_edge		= 0,
440 	.right_edge		= 0,
441 #endif
442 
443 	/*
444 	 * Multifinger tracking.  Ignore by default.
445 	 */
446 	 .multifinger_track	= 0,
447 
448 	/*
449 	 * Sensor parameters.
450 	 */
451 	.x_sensors		= 0,	/* default for model */
452 	.x_ratio		= 0,	/* default for model */
453 	.y_sensors		= 0,	/* default for model */
454 	.y_ratio		= 0,	/* default for model */
455 	.sensor_threshold	= 5,
456 	.sensor_normalizer	= 5,
457 	.palm_width		= 0,	/* palm detection disabled */
458 	.old_raw_weight		= 0,
459 	.old_smoothed_weight	= 5,
460 	.new_raw_weight		= 1,
461 
462 	/*
463 	 * Motion parameters.
464 	 */
465 	.motion_remainder	= 1,
466 	.motion_threshold	= 0,
467 	.motion_multiplier	= 1,
468 	.motion_divisor		= 1,
469 	.fast_motion_threshold	= 10,
470 	.fast_motion_multiplier	= 3,
471 	.fast_motion_divisor	= 2,
472 	.fast_per_direction	= 0,
473 	.motion_delay		= 4,
474 
475 	/*
476 	 * Tapping.  Disabled by default, with a reasonable time set
477 	 * nevertheless so that you can just set the buttons to enable
478 	 * it.
479 	 */
480 	.tap_limit_msec			= 100,
481 	.double_tap_limit_msec		= 200,
482 	.one_finger_tap_buttons		= 0,
483 	.two_finger_tap_buttons		= 0,
484 	.three_finger_tap_buttons	= 0,
485 	.tap_track_distance_limit	= 200,
486 };
487 
488 struct uatp_softc {
489 	struct uhidev sc_hdev;		/* USB parent.  */
490 	device_t sc_wsmousedev;		/* Attached wsmouse device.  */
491 	const struct uatp_parameters *sc_parameters;
492 	struct uatp_knobs sc_knobs;
493 	struct sysctllog *sc_log;	/* Log for sysctl knobs.  */
494 	const struct sysctlnode *sc_node;	/* Our sysctl node.  */
495 	unsigned int sc_input_size;	/* Input packet size.  */
496 	uint8_t sc_input[UATP_MAX_INPUT_SIZE];	/* Buffer for a packet.   */
497 	unsigned int sc_input_index;	/* Current index into sc_input.  */
498 	int sc_acc[UATP_SENSORS];	/* Accumulated sensor state.  */
499 	uint8_t sc_base[UATP_SENSORS];	/* Base sample.  */
500 	uint8_t sc_sample[UATP_SENSORS];/* Current sample.  */
501 	unsigned int sc_motion_timer;	/* XXX describe; motion_delay  */
502 	int sc_x_raw;			/* Raw horiz. mouse position.  */
503 	int sc_y_raw;			/* Raw vert. mouse position.  */
504 	int sc_z_raw;			/* Raw horiz. scroll position.  */
505 	int sc_w_raw;			/* Raw vert. scroll position.  */
506 	int sc_x_smoothed;		/* Smoothed horiz. mouse position.  */
507 	int sc_y_smoothed;		/* Smoothed vert. mouse position.  */
508 	int sc_z_smoothed;		/* Smoothed horiz. scroll position.  */
509 	int sc_w_smoothed;		/* Smoothed vert. scroll position.  */
510 	int sc_x_remainder;		/* Remainders from acceleration.  */
511 	int sc_y_remainder;
512 	int sc_z_remainder;
513 	int sc_w_remainder;
514 	unsigned int sc_track_distance;	/* Distance^2 finger has tracked,
515 					 * squared to avoid sqrt in kernel.  */
516 	uint32_t sc_status;		/* Status flags:  */
517 #define UATP_ENABLED	__BIT(0)	/* . Is the wsmouse enabled?  */
518 #define UATP_DYING	__BIT(1)	/* . Have we been deactivated?  */
519 #define UATP_VALID	__BIT(2)	/* . Do we have valid sensor data?  */
520 	struct usb_task sc_reset_task;	/* Task for resetting device.  */
521 
522 	callout_t sc_untap_callout;	/* Releases button after tap.  */
523 	kmutex_t sc_tap_mutex;		/* Protects the following fields.  */
524 	enum uatp_tap_state sc_tap_state;	/* Current tap state.  */
525 	unsigned int sc_tapping_fingers;	/* No. fingers tapping.  */
526 	unsigned int sc_tapped_fingers;	/* No. fingers of last tap.  */
527 	struct timeval sc_tap_timer;	/* Timer for tap state transitions.  */
528 	uint32_t sc_buttons;		/* Physical buttons pressed.  */
529 	uint32_t sc_all_buttons;	/* Buttons pressed or tapped.  */
530 
531 #if UATP_DEBUG
532 	uint32_t sc_debug_flags;	/* Debugging output enabled.  */
533 #endif
534 };
535 
536 struct uatp_descriptor {
537 	uint16_t vendor;
538 	uint16_t product;
539 	const char *description;
540 	const struct uatp_parameters *parameters;
541 };
542 
543 struct uatp_parameters {
544 	unsigned int x_ratio;		/* Screen width / trackpad width.  */
545 	unsigned int x_sensors;		/* Number of horizontal sensors.  */
546 	unsigned int x_sensors_17;	/* XXX Same, on a 17" laptop.  */
547 	unsigned int y_ratio;		/* Screen height / trackpad height.  */
548 	unsigned int y_sensors;		/* Number of vertical sensors.  */
549 	unsigned int input_size;	/* Size in bytes of input packets.  */
550 
551 	/* Device-specific initialization routine.  May be null.  */
552 	void (*initialize)(struct uatp_softc *);
553 
554 	/* Device-specific finalization routine.  May be null.  May fail.  */
555 	int (*finalize)(struct uatp_softc *);
556 
557 	/* Tests whether this is a base sample.  Second argument is
558 	 * input_size bytes long.  */
559 	bool (*base_sample)(const struct uatp_softc *, const uint8_t *);
560 
561 	/* Reads a sensor sample from an input packet.  First argument
562 	 * is UATP_MAX_X_SENSORS bytes long; second, UATP_MAX_Y_SENSORS
563 	 * bytes; third, input_size bytes.  */
564 	void (*read_sample)(uint8_t *, uint8_t *, const uint8_t *);
565 
566 	/* Accumulates sensor state in sc->sc_acc.  */
567 	void (*accumulate)(struct uatp_softc *);
568 
569 	/* Called on spurious interrupts to reset.  May be null.  */
570 	void (*reset)(struct uatp_softc *);
571 };
572 
573 /* Known device parameters */
574 
575 static const struct uatp_parameters fountain_parameters = {
576 	.x_ratio	= 64,	.x_sensors = 16,	.x_sensors_17 = 26,
577 	.y_ratio	= 43,	.y_sensors = 16,
578 	.input_size	= 81,
579 	.initialize	= NULL,
580 	.finalize	= NULL,
581 	.base_sample	= base_sample_softc_flag,
582 	.read_sample	= read_sample_1,
583 	.accumulate	= accumulate_sample_1,
584 	.reset		= NULL,
585 };
586 
587 static const struct uatp_parameters geyser_1_parameters = {
588 	.x_ratio	= 64,	.x_sensors = 16,	.x_sensors_17 = 26,
589 	.y_ratio	= 43,	.y_sensors = 16,
590 	.input_size	= 81,
591 	.initialize	= NULL,
592 	.finalize	= NULL,
593 	.base_sample	= base_sample_softc_flag,
594 	.read_sample	= read_sample_1,
595 	.accumulate	= accumulate_sample_1,
596 	.reset		= NULL,
597 };
598 
599 static const struct uatp_parameters geyser_2_parameters = {
600 	.x_ratio	= 64,	.x_sensors = 15,	.x_sensors_17 = 20,
601 	.y_ratio	= 43,	.y_sensors = 9,
602 	.input_size	= 64,
603 	.initialize	= NULL,
604 	.finalize	= NULL,
605 	.base_sample	= base_sample_softc_flag,
606 	.read_sample	= read_sample_2,
607 	.accumulate	= accumulate_sample_1,
608 	.reset		= NULL,
609 };
610 
611 /*
612  * The Geyser 3 and Geyser 4 share parameters.  They also present
613  * generic USB HID mice on a different report id, so we have smaller
614  * packets by one byte (uhidev handles multiplexing report ids) and
615  * extra initialization work to switch the mode from generic USB HID
616  * mouse to Apple trackpad.
617  */
618 
619 static const struct uatp_parameters geyser_3_4_parameters = {
620 	.x_ratio	= 64,	.x_sensors = 20, /* XXX */ .x_sensors_17 = 0,
621 	.y_ratio	= 64,	.y_sensors = 9,
622 	.input_size	= 63,	/* 64, minus one for the report id.  */
623 	.initialize	= geyser34_initialize,
624 	.finalize	= geyser34_finalize,
625 	.base_sample	= base_sample_input_flag,
626 	.read_sample	= read_sample_2,
627 	.accumulate	= accumulate_sample_2,
628 	.reset		= geyser34_deferred_reset,
629 };
630 
631 /* Known device models */
632 
633 #define APPLE_TRACKPAD(PRODUCT, DESCRIPTION, PARAMETERS)		\
634 	{								\
635 		.vendor = USB_VENDOR_APPLE,				\
636 		.product = (PRODUCT),					\
637 		.description = "Apple " DESCRIPTION " trackpad",	\
638 		.parameters = (& (PARAMETERS)),				\
639 	}
640 
641 #define POWERBOOK_TRACKPAD(PRODUCT, PARAMETERS)				\
642 	APPLE_TRACKPAD(PRODUCT, "PowerBook/iBook", PARAMETERS)
643 #define MACBOOK_TRACKPAD(PRODUCT, PARAMETERS)				\
644 	APPLE_TRACKPAD(PRODUCT, "MacBook/MacBook Pro", PARAMETERS)
645 
646 static const struct uatp_descriptor uatp_descriptors[] =
647 {
648 	POWERBOOK_TRACKPAD(0x020e, fountain_parameters),
649 	POWERBOOK_TRACKPAD(0x020f, fountain_parameters),
650 	POWERBOOK_TRACKPAD(0x030a, fountain_parameters),
651 
652 	POWERBOOK_TRACKPAD(0x030b, geyser_1_parameters),
653 
654 	POWERBOOK_TRACKPAD(0x0214, geyser_2_parameters),
655 	POWERBOOK_TRACKPAD(0x0215, geyser_2_parameters),
656 	POWERBOOK_TRACKPAD(0x0216, geyser_2_parameters),
657 
658 	MACBOOK_TRACKPAD(0x0217, geyser_3_4_parameters), /* 3 */
659 	MACBOOK_TRACKPAD(0x0218, geyser_3_4_parameters), /* 3 */
660 	MACBOOK_TRACKPAD(0x0219, geyser_3_4_parameters), /* 3 */
661 
662 	MACBOOK_TRACKPAD(0x021a, geyser_3_4_parameters), /* 4 */
663 	MACBOOK_TRACKPAD(0x021b, geyser_3_4_parameters), /* 4 */
664 	MACBOOK_TRACKPAD(0x021c, geyser_3_4_parameters), /* 4 */
665 
666 	MACBOOK_TRACKPAD(0x0229, geyser_3_4_parameters), /* 4 */
667 	MACBOOK_TRACKPAD(0x022a, geyser_3_4_parameters), /* 4 */
668 	MACBOOK_TRACKPAD(0x022b, geyser_3_4_parameters), /* 4 */
669 };
670 
671 #undef MACBOOK_TRACKPAD
672 #undef POWERBOOK_TRACKPAD
673 #undef APPLE_TRACKPAD
674 
675 /* Miscellaneous utilities */
676 
677 static const struct uatp_descriptor *
678 find_uatp_descriptor(const struct uhidev_attach_arg *uha)
679 {
680 	unsigned int i;
681 
682 	for (i = 0; i < __arraycount(uatp_descriptors); i++)
683 		if ((uha->uiaa->uiaa_vendor == uatp_descriptors[i].vendor) &&
684 		    (uha->uiaa->uiaa_product == uatp_descriptors[i].product))
685 			return &uatp_descriptors[i];
686 
687 	return NULL;
688 }
689 
690 static device_t
691 uatp_dev(const struct uatp_softc *sc)
692 {
693 	return sc->sc_hdev.sc_dev;
694 }
695 
696 static uint8_t *
697 uatp_x_sample(struct uatp_softc *sc)
698 {
699 	return &sc->sc_sample[0];
700 }
701 
702 static uint8_t *
703 uatp_y_sample(struct uatp_softc *sc)
704 {
705 	return &sc->sc_sample[UATP_MAX_X_SENSORS];
706 }
707 
708 static int *
709 uatp_x_acc(struct uatp_softc *sc)
710 {
711 	return &sc->sc_acc[0];
712 }
713 
714 static int *
715 uatp_y_acc(struct uatp_softc *sc)
716 {
717 	return &sc->sc_acc[UATP_MAX_X_SENSORS];
718 }
719 
720 static void
721 uatp_clear_position(struct uatp_softc *sc)
722 {
723 	memset(sc->sc_acc, 0, sizeof(sc->sc_acc));
724 	sc->sc_motion_timer = 0;
725 	sc->sc_x_raw = sc->sc_x_smoothed = -1;
726 	sc->sc_y_raw = sc->sc_y_smoothed = -1;
727 	sc->sc_z_raw = sc->sc_z_smoothed = -1;
728 	sc->sc_w_raw = sc->sc_w_smoothed = -1;
729 	sc->sc_x_remainder = 0;
730 	sc->sc_y_remainder = 0;
731 	sc->sc_z_remainder = 0;
732 	sc->sc_w_remainder = 0;
733 	sc->sc_track_distance = 0;
734 }
735 
736 static unsigned int
737 uatp_x_sensors(const struct uatp_softc *sc)
738 {
739 	if ((0 < sc->sc_knobs.x_sensors) &&
740 	    (sc->sc_knobs.x_sensors <= UATP_MAX_X_SENSORS))
741 		return sc->sc_knobs.x_sensors;
742 	else
743 		return sc->sc_parameters->x_sensors;
744 }
745 
746 static unsigned int
747 uatp_y_sensors(const struct uatp_softc *sc)
748 {
749 	if ((0 < sc->sc_knobs.y_sensors) &&
750 	    (sc->sc_knobs.y_sensors <= UATP_MAX_Y_SENSORS))
751 		return sc->sc_knobs.y_sensors;
752 	else
753 		return sc->sc_parameters->y_sensors;
754 }
755 
756 static unsigned int
757 uatp_x_ratio(const struct uatp_softc *sc)
758 {
759 	/* XXX Reject bogus values in sysctl.  */
760 	if ((0 < sc->sc_knobs.x_ratio) &&
761 	    (sc->sc_knobs.x_ratio <= UATP_MAX_X_RATIO))
762 		return sc->sc_knobs.x_ratio;
763 	else
764 		return sc->sc_parameters->x_ratio;
765 }
766 
767 static unsigned int
768 uatp_y_ratio(const struct uatp_softc *sc)
769 {
770 	/* XXX Reject bogus values in sysctl.  */
771 	if ((0 < sc->sc_knobs.y_ratio) &&
772 	    (sc->sc_knobs.y_ratio <= UATP_MAX_Y_RATIO))
773 		return sc->sc_knobs.y_ratio;
774 	else
775 		return sc->sc_parameters->y_ratio;
776 }
777 
778 static unsigned int
779 uatp_old_raw_weight(const struct uatp_softc *sc)
780 {
781 	/* XXX Reject bogus values in sysctl.  */
782 	if (sc->sc_knobs.old_raw_weight <= UATP_MAX_WEIGHT)
783 		return sc->sc_knobs.old_raw_weight;
784 	else
785 		return 0;
786 }
787 
788 static unsigned int
789 uatp_old_smoothed_weight(const struct uatp_softc *sc)
790 {
791 	/* XXX Reject bogus values in sysctl.  */
792 	if (sc->sc_knobs.old_smoothed_weight <= UATP_MAX_WEIGHT)
793 		return sc->sc_knobs.old_smoothed_weight;
794 	else
795 		return 0;
796 }
797 
798 static unsigned int
799 uatp_new_raw_weight(const struct uatp_softc *sc)
800 {
801 	/* XXX Reject bogus values in sysctl.  */
802 	if ((0 < sc->sc_knobs.new_raw_weight) &&
803 	    (sc->sc_knobs.new_raw_weight <= UATP_MAX_WEIGHT))
804 		return sc->sc_knobs.new_raw_weight;
805 	else
806 		return 1;
807 }
808 
809 static int
810 scale_motion(const struct uatp_softc *sc, int delta, int *remainder,
811     const unsigned int *multiplier, const unsigned int *divisor)
812 {
813 	int product;
814 
815 	/* XXX Limit the divisor?  */
816 	if (((*multiplier) == 0) ||
817 	    ((*multiplier) > UATP_MAX_MOTION_MULTIPLIER) ||
818 	    ((*divisor) == 0))
819 		DPRINTF(sc, UATP_DEBUG_ACCEL,
820 		    ("bad knobs; %d (+ %d) --> %d, rem 0\n",
821 			delta, *remainder, (delta + (*remainder))));
822 	else
823 		DPRINTF(sc, UATP_DEBUG_ACCEL,
824 		    ("scale %d (+ %d) by %u/%u --> %d, rem %d\n",
825 			delta, *remainder,
826 			(*multiplier), (*divisor),
827 			(((delta + (*remainder)) * ((int) (*multiplier)))
828 			    / ((int) (*divisor))),
829 			(((delta + (*remainder)) * ((int) (*multiplier)))
830 			    % ((int) (*divisor)))));
831 
832 	if (sc->sc_knobs.motion_remainder)
833 		delta += *remainder;
834 	*remainder = 0;
835 
836 	if (((*multiplier) == 0) ||
837 	    ((*multiplier) > UATP_MAX_MOTION_MULTIPLIER) ||
838 	    ((*divisor) == 0))
839 		return delta;
840 
841 	product = (delta * ((int) (*multiplier)));
842 	*remainder = (product % ((int) (*divisor)));
843 	return product / ((int) (*divisor));
844 }
845 
846 static int
847 uatp_scale_motion(const struct uatp_softc *sc, int delta, int *remainder)
848 {
849 	return scale_motion(sc, delta, remainder,
850 	    &sc->sc_knobs.motion_multiplier,
851 	    &sc->sc_knobs.motion_divisor);
852 }
853 
854 static int
855 uatp_scale_fast_motion(const struct uatp_softc *sc, int delta, int *remainder)
856 {
857 	return scale_motion(sc, delta, remainder,
858 	    &sc->sc_knobs.fast_motion_multiplier,
859 	    &sc->sc_knobs.fast_motion_divisor);
860 }
861 
862 /* Driver goop */
863 
864 CFATTACH_DECL2_NEW(uatp, sizeof(struct uatp_softc), uatp_match, uatp_attach,
865     uatp_detach, uatp_activate, NULL, uatp_childdet);
866 
867 static const struct wsmouse_accessops uatp_accessops = {
868 	.enable = uatp_enable,
869 	.disable = uatp_disable,
870 	.ioctl = uatp_ioctl,
871 };
872 
873 static int
874 uatp_match(device_t parent, cfdata_t match, void *aux)
875 {
876 	const struct uhidev_attach_arg *uha = aux;
877 	void *report_descriptor;
878 	int report_size, input_size;
879 	const struct uatp_descriptor *uatp_descriptor;
880 
881 	aprint_debug("%s: vendor 0x%04x, product 0x%04x\n", __func__,
882 	    (unsigned int)uha->uiaa->uiaa_vendor,
883 	    (unsigned int)uha->uiaa->uiaa_product);
884 	aprint_debug("%s: class 0x%04x, subclass 0x%04x, proto 0x%04x\n",
885 	    __func__,
886 	    (unsigned int)uha->uiaa->uiaa_class,
887 	    (unsigned int)uha->uiaa->uiaa_subclass,
888 	    (unsigned int)uha->uiaa->uiaa_proto);
889 
890 	uhidev_get_report_desc(uha->parent, &report_descriptor, &report_size);
891 	input_size = hid_report_size(report_descriptor, report_size,
892 	    hid_input, uha->reportid);
893 	aprint_debug("%s: reportid %d, input size %d\n", __func__,
894 	    (int)uha->reportid, input_size);
895 
896 	/*
897 	 * Keyboards, trackpads, and eject buttons share common vendor
898 	 * and product ids, but not protocols: only the trackpad
899 	 * reports a mouse protocol.
900 	 */
901 	if (uha->uiaa->uiaa_proto != UIPROTO_MOUSE)
902 		return UMATCH_NONE;
903 
904 	/* Check for a known vendor/product id.  */
905 	uatp_descriptor = find_uatp_descriptor(uha);
906 	if (uatp_descriptor == NULL) {
907 		aprint_debug("%s: unknown vendor/product id\n", __func__);
908 		return UMATCH_NONE;
909 	}
910 
911 	/* Check for the expected input size.  */
912 	if ((input_size < 0) ||
913 	    ((unsigned int)input_size !=
914 		uatp_descriptor->parameters->input_size)) {
915 		aprint_debug("%s: expected input size %u\n", __func__,
916 		    uatp_descriptor->parameters->input_size);
917 		return UMATCH_NONE;
918 	}
919 
920 	return UMATCH_VENDOR_PRODUCT_CONF_IFACE;
921 }
922 
923 static void
924 uatp_attach(device_t parent, device_t self, void *aux)
925 {
926 	struct uatp_softc *sc = device_private(self);
927 	const struct uhidev_attach_arg *uha = aux;
928 	const struct uatp_descriptor *uatp_descriptor;
929 	void *report_descriptor;
930 	int report_size, input_size;
931 	struct wsmousedev_attach_args a;
932 
933 	/* Set up uhidev state.  (Why doesn't uhidev do most of this?)  */
934 	sc->sc_hdev.sc_dev = self;
935 	sc->sc_hdev.sc_intr = uatp_intr;
936 	sc->sc_hdev.sc_parent = uha->parent;
937 	sc->sc_hdev.sc_report_id = uha->reportid;
938 
939 	/* Identify ourselves to dmesg.  */
940 	uatp_descriptor = find_uatp_descriptor(uha);
941 	KASSERT(uatp_descriptor != NULL);
942 	aprint_normal(": %s\n", uatp_descriptor->description);
943 	aprint_naive(": %s\n", uatp_descriptor->description);
944 	aprint_verbose_dev(self,
945 	    "vendor 0x%04x, product 0x%04x, report id %d\n",
946 	    (unsigned int)uha->uiaa->uiaa_vendor,
947 	    (unsigned int)uha->uiaa->uiaa_product,
948 	    (int)uha->reportid);
949 
950 	uhidev_get_report_desc(uha->parent, &report_descriptor, &report_size);
951 	input_size = hid_report_size(report_descriptor, report_size, hid_input,
952 	    uha->reportid);
953 	KASSERT(0 < input_size);
954 	sc->sc_input_size = input_size;
955 
956 	/* Initialize model-specific parameters.  */
957 	sc->sc_parameters = uatp_descriptor->parameters;
958 	KASSERT((int)sc->sc_parameters->input_size == input_size);
959 	KASSERT(sc->sc_parameters->x_sensors <= UATP_MAX_X_SENSORS);
960 	KASSERT(sc->sc_parameters->x_ratio <= UATP_MAX_X_RATIO);
961 	KASSERT(sc->sc_parameters->y_sensors <= UATP_MAX_Y_SENSORS);
962 	KASSERT(sc->sc_parameters->y_ratio <= UATP_MAX_Y_RATIO);
963 	aprint_verbose_dev(self,
964 	    "%u x sensors, scaled by %u for %u points on screen\n",
965 	    sc->sc_parameters->x_sensors, sc->sc_parameters->x_ratio,
966 	    sc->sc_parameters->x_sensors * sc->sc_parameters->x_ratio);
967 	aprint_verbose_dev(self,
968 	    "%u y sensors, scaled by %u for %u points on screen\n",
969 	    sc->sc_parameters->y_sensors, sc->sc_parameters->y_ratio,
970 	    sc->sc_parameters->y_sensors * sc->sc_parameters->y_ratio);
971 	if (sc->sc_parameters->initialize)
972 		sc->sc_parameters->initialize(sc);
973 
974 	/* Register with pmf.  Nothing special for suspend/resume.  */
975 	if (!pmf_device_register(self, NULL, NULL))
976 		aprint_error_dev(self, "couldn't establish power handler\n");
977 
978 	/* Initialize knobs and create sysctl subtree to tweak them.  */
979 	sc->sc_knobs = default_knobs;
980 	uatp_setup_sysctl(sc);
981 
982 	/* Initialize tapping.  */
983 	tap_initialize(sc);
984 
985 	/* Attach wsmouse.  */
986 	a.accessops = &uatp_accessops;
987 	a.accesscookie = sc;
988 	sc->sc_wsmousedev = config_found(self, &a, wsmousedevprint, CFARG_EOL);
989 }
990 
991 /* Sysctl setup */
992 
993 static void
994 uatp_setup_sysctl(struct uatp_softc *sc)
995 {
996 	int error;
997 
998 	error = sysctl_createv(&sc->sc_log, 0, NULL, &sc->sc_node, 0,
999 	    CTLTYPE_NODE, device_xname(uatp_dev(sc)),
1000 	    SYSCTL_DESCR("uatp configuration knobs"),
1001 	    NULL, 0, NULL, 0,
1002 	    CTL_HW, CTL_CREATE, CTL_EOL);
1003 	if (error != 0) {
1004 		aprint_error_dev(uatp_dev(sc),
1005 		    "unable to set up sysctl tree hw.%s: %d\n",
1006 		    device_xname(uatp_dev(sc)), error);
1007 		goto err;
1008 	}
1009 
1010 #if UATP_DEBUG
1011 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_debug_flags, "debug",
1012 		"uatp(4) debug flags"))
1013 		goto err;
1014 #endif
1015 
1016 	/*
1017 	 * Button emulation.
1018 	 */
1019 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.two_finger_buttons,
1020 		"two_finger_buttons",
1021 		"buttons to emulate with two fingers on trackpad"))
1022 		goto err;
1023 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.three_finger_buttons,
1024 		"three_finger_buttons",
1025 		"buttons to emulate with three fingers on trackpad"))
1026 		goto err;
1027 
1028 #if 0
1029 	/*
1030 	 * Edge scrolling.
1031 	 */
1032 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.top_edge, "top_edge",
1033 		"width of top edge for edge scrolling"))
1034 		goto err;
1035 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.bottom_edge,
1036 		"bottom_edge", "width of bottom edge for edge scrolling"))
1037 		goto err;
1038 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.left_edge, "left_edge",
1039 		"width of left edge for edge scrolling"))
1040 		goto err;
1041 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.right_edge, "right_edge",
1042 		"width of right edge for edge scrolling"))
1043 		goto err;
1044 #endif
1045 
1046 	/*
1047 	 * Multifinger tracking.
1048 	 */
1049 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.multifinger_track,
1050 		"multifinger_track",
1051 		"0 to ignore multiple fingers, 1 to reset, 2 to scroll"))
1052 		goto err;
1053 
1054 	/*
1055 	 * Sensor parameters.
1056 	 */
1057 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.x_sensors, "x_sensors",
1058 		"number of x sensors"))
1059 		goto err;
1060 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.x_ratio, "x_ratio",
1061 		"screen width to trackpad width ratio"))
1062 		goto err;
1063 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.y_sensors, "y_sensors",
1064 		"number of y sensors"))
1065 		goto err;
1066 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.y_ratio, "y_ratio",
1067 		"screen height to trackpad height ratio"))
1068 		goto err;
1069 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.sensor_threshold,
1070 		"sensor_threshold", "sensor threshold"))
1071 		goto err;
1072 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.sensor_normalizer,
1073 		"sensor_normalizer", "sensor normalizer"))
1074 		goto err;
1075 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.palm_width,
1076 		"palm_width", "lower bound on width/height of palm"))
1077 		goto err;
1078 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.old_raw_weight,
1079 		"old_raw_weight", "weight of old raw position"))
1080 		goto err;
1081 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.old_smoothed_weight,
1082 		"old_smoothed_weight", "weight of old smoothed position"))
1083 		goto err;
1084 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.new_raw_weight,
1085 		"new_raw_weight", "weight of new raw position"))
1086 		goto err;
1087 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_remainder,
1088 		"motion_remainder", "remember motion division remainder"))
1089 		goto err;
1090 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_threshold,
1091 		"motion_threshold", "threshold before finger moves cursor"))
1092 		goto err;
1093 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_multiplier,
1094 		"motion_multiplier", "numerator of motion scale"))
1095 		goto err;
1096 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_divisor,
1097 		"motion_divisor", "divisor of motion scale"))
1098 		goto err;
1099 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_threshold,
1100 		"fast_motion_threshold", "threshold before fast motion"))
1101 		goto err;
1102 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_multiplier,
1103 		"fast_motion_multiplier", "numerator of fast motion scale"))
1104 		goto err;
1105 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_divisor,
1106 		"fast_motion_divisor", "divisor of fast motion scale"))
1107 		goto err;
1108 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_per_direction,
1109 		"fast_per_direction", "don't frobnitz the veeblefitzer!"))
1110 		goto err;
1111 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_delay,
1112 		"motion_delay", "number of packets before motion kicks in"))
1113 		goto err;
1114 
1115 	/*
1116 	 * Tapping.
1117 	 */
1118 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.tap_limit_msec,
1119 		"tap_limit_msec", "milliseconds before a touch is not a tap"))
1120 		goto err;
1121 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.double_tap_limit_msec,
1122 		"double_tap_limit_msec",
1123 		"milliseconds before a second tap keeps the button down"))
1124 		goto err;
1125 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.one_finger_tap_buttons,
1126 		"one_finger_tap_buttons", "buttons for one-finger taps"))
1127 		goto err;
1128 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.two_finger_tap_buttons,
1129 		"two_finger_tap_buttons", "buttons for two-finger taps"))
1130 		goto err;
1131 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.three_finger_tap_buttons,
1132 		"three_finger_tap_buttons", "buttons for three-finger taps"))
1133 		goto err;
1134 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.tap_track_distance_limit,
1135 		"tap_track_distance_limit",
1136 		"maximum distance^2 of tracking during tap"))
1137 		goto err;
1138 
1139 	return;
1140 
1141 err:
1142 	sysctl_teardown(&sc->sc_log);
1143 	sc->sc_node = NULL;
1144 }
1145 
1146 static bool
1147 uatp_setup_sysctl_knob(struct uatp_softc *sc, int *ptr, const char *name,
1148     const char *description)
1149 {
1150 	int error;
1151 
1152 	error = sysctl_createv(&sc->sc_log, 0, NULL, NULL, CTLFLAG_READWRITE,
1153 	    CTLTYPE_INT, name, SYSCTL_DESCR(description),
1154 	    NULL, 0, ptr, 0,
1155 	    CTL_HW, sc->sc_node->sysctl_num, CTL_CREATE, CTL_EOL);
1156 	if (error != 0) {
1157 		aprint_error_dev(uatp_dev(sc),
1158 		    "unable to setup sysctl node hw.%s.%s: %d\n",
1159 		    device_xname(uatp_dev(sc)), name, error);
1160 		return false;
1161 	}
1162 
1163 	return true;
1164 }
1165 
1166 /* More driver goop */
1167 
1168 static void
1169 uatp_childdet(device_t self, device_t child)
1170 {
1171 	struct uatp_softc *sc = device_private(self);
1172 
1173 	DPRINTF(sc, UATP_DEBUG_MISC, ("detaching child %s\n",
1174 	    device_xname(child)));
1175 
1176 	/* Our only child is the wsmouse device.  */
1177 	if (child == sc->sc_wsmousedev)
1178 		sc->sc_wsmousedev = NULL;
1179 }
1180 
1181 static int
1182 uatp_detach(device_t self, int flags)
1183 {
1184 	struct uatp_softc *sc = device_private(self);
1185 
1186 	DPRINTF(sc, UATP_DEBUG_MISC, ("detaching with flags %d\n", flags));
1187 
1188         if (sc->sc_status & UATP_ENABLED) {
1189 		aprint_error_dev(uatp_dev(sc), "can't detach while enabled\n");
1190 		return EBUSY;
1191         }
1192 
1193 	if (sc->sc_parameters->finalize) {
1194 		int error = sc->sc_parameters->finalize(sc);
1195 		if (error != 0)
1196 			return error;
1197 	}
1198 
1199 	pmf_device_deregister(self);
1200 
1201 	sysctl_teardown(&sc->sc_log);
1202 	sc->sc_node = NULL;
1203 
1204 	tap_finalize(sc);
1205 
1206 	return config_detach_children(self, flags);
1207 }
1208 
1209 static int
1210 uatp_activate(device_t self, enum devact act)
1211 {
1212 	struct uatp_softc *sc = device_private(self);
1213 
1214 	DPRINTF(sc, UATP_DEBUG_MISC, ("act %d\n", (int)act));
1215 
1216 	if (act != DVACT_DEACTIVATE)
1217 		return EOPNOTSUPP;
1218 
1219 	sc->sc_status |= UATP_DYING;
1220 
1221 	return 0;
1222 }
1223 
1224 /* wsmouse routines */
1225 
1226 static int
1227 uatp_enable(void *v)
1228 {
1229 	struct uatp_softc *sc = v;
1230 
1231 	DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("enabling wsmouse\n"));
1232 
1233 	/* Refuse to enable if we've been deactivated.  */
1234 	if (sc->sc_status & UATP_DYING) {
1235 		DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("busy dying\n"));
1236 		return EIO;
1237 	}
1238 
1239 	/* Refuse to enable if we already are enabled.  */
1240 	if (sc->sc_status & UATP_ENABLED) {
1241 		DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("already enabled\n"));
1242 		return EBUSY;
1243 	}
1244 
1245 	sc->sc_status |= UATP_ENABLED;
1246 	sc->sc_status &=~ UATP_VALID;
1247 	sc->sc_input_index = 0;
1248 	tap_enable(sc);
1249 	uatp_clear_position(sc);
1250 
1251 	DPRINTF(sc, UATP_DEBUG_MISC, ("uhidev_open(%p)\n", &sc->sc_hdev));
1252 	return uhidev_open(&sc->sc_hdev);
1253 }
1254 
1255 static void
1256 uatp_disable(void *v)
1257 {
1258 	struct uatp_softc *sc = v;
1259 
1260 	DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("disabling wsmouse\n"));
1261 
1262 	if (!(sc->sc_status & UATP_ENABLED)) {
1263 		DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("not enabled\n"));
1264 		return;
1265 	}
1266 
1267 	tap_disable(sc);
1268 	sc->sc_status &=~ UATP_ENABLED;
1269 
1270 	DPRINTF(sc, UATP_DEBUG_MISC, ("uhidev_close(%p)\n", &sc->sc_hdev));
1271 	uhidev_close(&sc->sc_hdev);
1272 }
1273 
1274 static int
1275 uatp_ioctl(void *v, unsigned long cmd, void *data, int flag, struct lwp *p)
1276 {
1277 
1278 	DPRINTF((struct uatp_softc*)v, UATP_DEBUG_IOCTL,
1279 	    ("cmd %lx, data %p, flag %x, lwp %p\n", cmd, data, flag, p));
1280 
1281 	/* XXX Implement any relevant wsmouse(4) ioctls.  */
1282 	return EPASSTHROUGH;
1283 }
1284 
1285 /*
1286  * The Geyser 3 and 4 models talk the generic USB HID mouse protocol by
1287  * default.  This mode switch makes them give raw sensor data instead
1288  * so that we can implement tapping, two-finger scrolling, &c.
1289  */
1290 
1291 #define GEYSER34_RAW_MODE		0x04
1292 #define GEYSER34_MODE_REPORT_ID		0
1293 #define GEYSER34_MODE_INTERFACE		0
1294 #define GEYSER34_MODE_PACKET_SIZE	8
1295 
1296 static void
1297 geyser34_enable_raw_mode(struct uatp_softc *sc)
1298 {
1299 	struct usbd_device *udev = sc->sc_hdev.sc_parent->sc_udev;
1300 	usb_device_request_t req;
1301 	usbd_status status;
1302 	uint8_t report[GEYSER34_MODE_PACKET_SIZE];
1303 
1304 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
1305 	req.bRequest = UR_GET_REPORT;
1306 	USETW2(req.wValue, UHID_FEATURE_REPORT, GEYSER34_MODE_REPORT_ID);
1307 	USETW(req.wIndex, GEYSER34_MODE_INTERFACE);
1308 	USETW(req.wLength, GEYSER34_MODE_PACKET_SIZE);
1309 
1310 	DPRINTF(sc, UATP_DEBUG_RESET, ("get feature report\n"));
1311 	status = usbd_do_request(udev, &req, report);
1312 	if (status != USBD_NORMAL_COMPLETION) {
1313 		aprint_error_dev(uatp_dev(sc),
1314 		    "error reading feature report: %s\n", usbd_errstr(status));
1315 		return;
1316 	}
1317 
1318 #if UATP_DEBUG
1319 	if (sc->sc_debug_flags & UATP_DEBUG_RESET) {
1320 		unsigned int i;
1321 		DPRINTF(sc, UATP_DEBUG_RESET, ("old feature report:"));
1322 		for (i = 0; i < GEYSER34_MODE_PACKET_SIZE; i++)
1323 			printf(" %02x", (unsigned int)report[i]);
1324 		printf("\n");
1325 		/* Doing this twice is harmless here and lets this be
1326 		 * one ifdef.  */
1327 		report[0] = GEYSER34_RAW_MODE;
1328 		DPRINTF(sc, UATP_DEBUG_RESET, ("new feature report:"));
1329 		for (i = 0; i < GEYSER34_MODE_PACKET_SIZE; i++)
1330 			printf(" %02x", (unsigned int)report[i]);
1331 		printf("\n");
1332 	}
1333 #endif
1334 
1335 	report[0] = GEYSER34_RAW_MODE;
1336 
1337 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1338 	req.bRequest = UR_SET_REPORT;
1339 	USETW2(req.wValue, UHID_FEATURE_REPORT, GEYSER34_MODE_REPORT_ID);
1340 	USETW(req.wIndex, GEYSER34_MODE_INTERFACE);
1341 	USETW(req.wLength, GEYSER34_MODE_PACKET_SIZE);
1342 
1343 	DPRINTF(sc, UATP_DEBUG_RESET, ("set feature report\n"));
1344 	status = usbd_do_request(udev, &req, report);
1345 	if (status != USBD_NORMAL_COMPLETION) {
1346 		aprint_error_dev(uatp_dev(sc),
1347 		    "error writing feature report: %s\n", usbd_errstr(status));
1348 		return;
1349 	}
1350 }
1351 
1352 /*
1353  * The Geyser 3 and 4 need to be reset periodically after we detect a
1354  * continual flow of spurious interrupts.  We use a USB task for this.
1355  */
1356 
1357 static void
1358 geyser34_initialize(struct uatp_softc *sc)
1359 {
1360 
1361 	DPRINTF(sc, UATP_DEBUG_MISC, ("initializing\n"));
1362 	geyser34_enable_raw_mode(sc);
1363 	usb_init_task(&sc->sc_reset_task, &geyser34_reset_task, sc, 0);
1364 }
1365 
1366 static int
1367 geyser34_finalize(struct uatp_softc *sc)
1368 {
1369 
1370 	DPRINTF(sc, UATP_DEBUG_MISC, ("finalizing\n"));
1371 	usb_rem_task_wait(sc->sc_hdev.sc_parent->sc_udev, &sc->sc_reset_task,
1372 	    USB_TASKQ_DRIVER, NULL);
1373 
1374 	return 0;
1375 }
1376 
1377 static void
1378 geyser34_deferred_reset(struct uatp_softc *sc)
1379 {
1380 
1381 	DPRINTF(sc, UATP_DEBUG_RESET, ("deferring reset\n"));
1382 	usb_add_task(sc->sc_hdev.sc_parent->sc_udev, &sc->sc_reset_task,
1383 	    USB_TASKQ_DRIVER);
1384 }
1385 
1386 static void
1387 geyser34_reset_task(void *arg)
1388 {
1389 	struct uatp_softc *sc = arg;
1390 
1391 	DPRINTF(sc, UATP_DEBUG_RESET, ("resetting\n"));
1392 
1393 	/* Reset by putting it into raw mode.  Not sure why.  */
1394 	geyser34_enable_raw_mode(sc);
1395 }
1396 
1397 /* Interrupt handler */
1398 
1399 static void
1400 uatp_intr(struct uhidev *addr, void *ibuf, unsigned int len)
1401 {
1402 	struct uatp_softc *sc = (struct uatp_softc *)addr;
1403 	uint8_t *input;
1404 	int dx, dy, dz, dw;
1405 	uint32_t buttons;
1406 
1407 	DPRINTF(sc, UATP_DEBUG_INTR, ("softc %p, ibuf %p, len %u\n",
1408 	    addr, ibuf, len));
1409 
1410 	/*
1411 	 * Some devices break packets up into chunks, so we accumulate
1412 	 * input up to the expected packet length, or if it would
1413 	 * overflow, discard the whole packet and start over.
1414 	 */
1415 	if (sc->sc_input_size < len) {
1416 		aprint_error_dev(uatp_dev(sc),
1417 		    "discarding %u-byte input packet\n", len);
1418 		sc->sc_input_index = 0;
1419 		return;
1420 	} else if (sc->sc_input_size < (sc->sc_input_index + len)) {
1421 		aprint_error_dev(uatp_dev(sc), "discarding %u-byte input\n",
1422 		    (sc->sc_input_index + len));
1423 		sc->sc_input_index = 0;
1424 		return;
1425 	} else if (sc->sc_input_size == 81 && len == 17 &&
1426 	    sc->sc_input_index != 64) {
1427 		/*
1428 		 * Quirk of Fountain and Geyser 1 devices: a 17-byte
1429 		 * packet seems to mean the last one, but sometimes we
1430 		 * get desynchronized, so drop this one and start over
1431 		 * if we see a 17-byte packet that's not at the end.
1432 		 */
1433 		aprint_error_dev(uatp_dev(sc),
1434 		    "discarding 17-byte nonterminal input at %u\n",
1435 		    sc->sc_input_index);
1436 		sc->sc_input_index = 0;
1437 		return;
1438 	}
1439 
1440 #if UATP_DEBUG
1441 	if (sc->sc_debug_flags & UATP_DEBUG_INTR) {
1442 		unsigned int i;
1443 		uint8_t *bytes = ibuf;
1444 		DPRINTF(sc, UATP_DEBUG_INTR, ("raw"));
1445 		for (i = 0; i < len; i++)
1446 			printf(" %02x", (unsigned int)bytes[i]);
1447 		printf("\n");
1448 	}
1449 #endif
1450 
1451 	memcpy(&sc->sc_input[sc->sc_input_index], ibuf, len);
1452 	sc->sc_input_index += len;
1453 	if (sc->sc_input_index != sc->sc_input_size) {
1454 		/* Wait until packet is complete.  */
1455 		DPRINTF(sc, UATP_DEBUG_INTR, ("partial packet: %u bytes\n",
1456 		    len));
1457 		return;
1458 	}
1459 
1460 	/* Clear the buffer and process the now complete packet.  */
1461 	sc->sc_input_index = 0;
1462 	input = sc->sc_input;
1463 
1464 	/* The last byte's first bit is set iff the button is pressed.
1465 	 * XXX Left button should have a name.  */
1466 	buttons = ((input[sc->sc_input_size - 1] & UATP_STATUS_BUTTON)
1467 	    ? 1 : 0);
1468 
1469 	/* Read the sample.  */
1470 	memset(uatp_x_sample(sc), 0, UATP_MAX_X_SENSORS);
1471 	memset(uatp_y_sample(sc), 0, UATP_MAX_Y_SENSORS);
1472 	sc->sc_parameters->read_sample(uatp_x_sample(sc), uatp_y_sample(sc),
1473 	    input);
1474 
1475 #if UATP_DEBUG
1476 	if (sc->sc_debug_flags & UATP_DEBUG_INTR) {
1477 		unsigned int i;
1478 		DPRINTF(sc, UATP_DEBUG_INTR, ("x sensors"));
1479 		for (i = 0; i < uatp_x_sensors(sc); i++)
1480 			printf(" %02x", (unsigned int)uatp_x_sample(sc)[i]);
1481 		printf("\n");
1482 		DPRINTF(sc, UATP_DEBUG_INTR, ("y sensors"));
1483 		for (i = 0; i < uatp_y_sensors(sc); i++)
1484 			printf(" %02x", (unsigned int)uatp_y_sample(sc)[i]);
1485 		printf("\n");
1486 	} else if ((sc->sc_debug_flags & UATP_DEBUG_STATUS) &&
1487 		(input[sc->sc_input_size - 1] &~
1488 		    (UATP_STATUS_BUTTON | UATP_STATUS_BASE |
1489 			UATP_STATUS_POST_RESET)))
1490 		DPRINTF(sc, UATP_DEBUG_STATUS, ("status byte: %02x\n",
1491 		    input[sc->sc_input_size - 1]));
1492 #endif
1493 
1494 	/*
1495 	 * If this is a base sample, initialize the state to interpret
1496 	 * subsequent samples relative to it, and stop here.
1497 	 */
1498 	if (sc->sc_parameters->base_sample(sc, input)) {
1499 		DPRINTF(sc, UATP_DEBUG_PARSE,
1500 		    ("base sample, buttons %"PRIx32"\n", buttons));
1501 		/* XXX Should the valid bit ever be reset?  */
1502 		sc->sc_status |= UATP_VALID;
1503 		uatp_clear_position(sc);
1504 		memcpy(sc->sc_base, sc->sc_sample, sizeof(sc->sc_base));
1505 		/* XXX Perform 17" size detection like Linux?  */
1506 		return;
1507 	}
1508 
1509 	/* If not, accumulate the change in the sensors.  */
1510 	sc->sc_parameters->accumulate(sc);
1511 
1512 #if UATP_DEBUG
1513 	if (sc->sc_debug_flags & UATP_DEBUG_ACCUMULATE) {
1514 		unsigned int i;
1515 		DPRINTF(sc, UATP_DEBUG_ACCUMULATE, ("accumulated x state:"));
1516 		for (i = 0; i < uatp_x_sensors(sc); i++)
1517 			printf(" %02x", (unsigned int)uatp_x_acc(sc)[i]);
1518 		printf("\n");
1519 		DPRINTF(sc, UATP_DEBUG_ACCUMULATE, ("accumulated y state:"));
1520 		for (i = 0; i < uatp_y_sensors(sc); i++)
1521 			printf(" %02x", (unsigned int)uatp_y_acc(sc)[i]);
1522 		printf("\n");
1523 	}
1524 #endif
1525 
1526 	/* Compute the change in coordinates and buttons.  */
1527 	dx = dy = dz = dw = 0;
1528 	if ((!interpret_input(sc, &dx, &dy, &dz, &dw, &buttons)) &&
1529 	    /* If there's no input because we're releasing a button,
1530 	     * then it's not spurious.  XXX Mutex?  */
1531 	    (sc->sc_buttons == 0)) {
1532 		DPRINTF(sc, UATP_DEBUG_SPURINTR, ("spurious interrupt\n"));
1533 		if (sc->sc_parameters->reset)
1534 			sc->sc_parameters->reset(sc);
1535 		return;
1536 	}
1537 
1538 	/* Report to wsmouse.  */
1539 	DPRINTF(sc, UATP_DEBUG_INTR,
1540 	    ("buttons %"PRIx32", dx %d, dy %d, dz %d, dw %d\n",
1541 		buttons, dx, dy, dz, dw));
1542 	mutex_enter(&sc->sc_tap_mutex);
1543 	uatp_input(sc, buttons, dx, dy, dz, dw);
1544 	mutex_exit(&sc->sc_tap_mutex);
1545 }
1546 
1547 /*
1548  * Different ways to discern the base sample initializing the state.
1549  * `base_sample_softc_flag' uses a state flag stored in the softc;
1550  * `base_sample_input_flag' checks a flag at the end of the input
1551  * packet.
1552  */
1553 
1554 static bool
1555 base_sample_softc_flag(const struct uatp_softc *sc, const uint8_t *input)
1556 {
1557 	return !(sc->sc_status & UATP_VALID);
1558 }
1559 
1560 static bool
1561 base_sample_input_flag(const struct uatp_softc *sc, const uint8_t *input)
1562 {
1563 	/* XXX Should we also check the valid flag?  */
1564 	return !!(input[sc->sc_input_size - 1] & UATP_STATUS_BASE);
1565 }
1566 
1567 /*
1568  * Pick apart the horizontal sensors from the vertical sensors.
1569  * Different models interleave them in different orders.
1570  */
1571 
1572 static void
1573 read_sample_1(uint8_t *x, uint8_t *y, const uint8_t *input)
1574 {
1575 	unsigned int i;
1576 
1577 	for (i = 0; i < 8; i++) {
1578 		x[i] = input[5 * i + 2];
1579 		x[i + 8] = input[5 * i + 4];
1580 		x[i + 16] = input[5 * i + 42];
1581 		if (i < 2)
1582 			x[i + 24] = input[5 * i + 44];
1583 
1584 		y[i] = input[5 * i + 1];
1585 		y[i + 8] = input[5 * i + 3];
1586 	}
1587 }
1588 
1589 static void
1590 read_sample_2(uint8_t *x, uint8_t *y, const uint8_t *input)
1591 {
1592 	unsigned int i, j;
1593 
1594 	for (i = 0, j = 19; i < 20; i += 2, j += 3) {
1595 		x[i] = input[j];
1596 		x[i + 1] = input[j + 1];
1597 	}
1598 
1599 	for (i = 0, j = 1; i < 9; i += 2, j += 3) {
1600 		y[i] = input[j];
1601 		y[i + 1] = input[j + 1];
1602 	}
1603 }
1604 
1605 static void
1606 accumulate_sample_1(struct uatp_softc *sc)
1607 {
1608 	unsigned int i;
1609 
1610 	for (i = 0; i < UATP_SENSORS; i++) {
1611 		sc->sc_acc[i] += (int8_t)(sc->sc_sample[i] - sc->sc_base[i]);
1612 		if (sc->sc_acc[i] < 0) {
1613 			sc->sc_acc[i] = 0;
1614 		} else if (UATP_MAX_ACC < sc->sc_acc[i]) {
1615 			DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
1616 			    ("overflow %d\n", sc->sc_acc[i]));
1617 			sc->sc_acc[i] = UATP_MAX_ACC;
1618 		}
1619 	}
1620 
1621 	memcpy(sc->sc_base, sc->sc_sample, sizeof(sc->sc_base));
1622 }
1623 
1624 static void
1625 accumulate_sample_2(struct uatp_softc *sc)
1626 {
1627 	unsigned int i;
1628 
1629 	for (i = 0; i < UATP_SENSORS; i++) {
1630 		sc->sc_acc[i] = (int8_t)(sc->sc_sample[i] - sc->sc_base[i]);
1631 		if (sc->sc_acc[i] < -0x80) {
1632 			DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
1633 			    ("underflow %u - %u = %d\n",
1634 				(unsigned int)sc->sc_sample[i],
1635 				(unsigned int)sc->sc_base[i],
1636 				sc->sc_acc[i]));
1637 			sc->sc_acc[i] += 0x100;
1638 		}
1639 		if (0x7f < sc->sc_acc[i]) {
1640 			DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
1641 			    ("overflow %u - %u = %d\n",
1642 				(unsigned int)sc->sc_sample[i],
1643 				(unsigned int)sc->sc_base[i],
1644 				sc->sc_acc[i]));
1645 			sc->sc_acc[i] -= 0x100;
1646 		}
1647 		if (sc->sc_acc[i] < 0)
1648 			sc->sc_acc[i] = 0;
1649 	}
1650 }
1651 
1652 /*
1653  * Report input to wsmouse, if there is anything interesting to report.
1654  * We must take into consideration the current tap-and-drag button
1655  * state.
1656  */
1657 
1658 static void
1659 uatp_input(struct uatp_softc *sc, uint32_t buttons,
1660     int dx, int dy, int dz, int dw)
1661 {
1662 	uint32_t all_buttons;
1663 
1664 	KASSERT(mutex_owned(&sc->sc_tap_mutex));
1665 	all_buttons = buttons | uatp_tapped_buttons(sc);
1666 
1667 	if ((sc->sc_wsmousedev != NULL) &&
1668 	    ((dx != 0) || (dy != 0) || (dz != 0) || (dw != 0) ||
1669 		(all_buttons != sc->sc_all_buttons))) {
1670 		int s = spltty();
1671 		DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("wsmouse input:"
1672 		    " buttons %"PRIx32", dx %d, dy %d, dz %d, dw %d\n",
1673 		    all_buttons, dx, -dy, dz, -dw));
1674 		wsmouse_input(sc->sc_wsmousedev, all_buttons, dx, -dy, dz, -dw,
1675 		    WSMOUSE_INPUT_DELTA);
1676 		splx(s);
1677 	}
1678 	sc->sc_buttons = buttons;
1679 	sc->sc_all_buttons = all_buttons;
1680 }
1681 
1682 /*
1683  * Interpret the current tap state to decide whether the tap buttons
1684  * are currently pressed.
1685  */
1686 
1687 static uint32_t
1688 uatp_tapped_buttons(struct uatp_softc *sc)
1689 {
1690 	KASSERT(mutex_owned(&sc->sc_tap_mutex));
1691 	switch (sc->sc_tap_state) {
1692 	case TAP_STATE_INITIAL:
1693 	case TAP_STATE_TAPPING:
1694 		return 0;
1695 
1696 	case TAP_STATE_TAPPED:
1697 	case TAP_STATE_DOUBLE_TAPPING:
1698 	case TAP_STATE_DRAGGING_DOWN:
1699 	case TAP_STATE_DRAGGING_UP:
1700 	case TAP_STATE_TAPPING_IN_DRAG:
1701 		CHECK((0 < sc->sc_tapped_fingers), return 0);
1702 		switch (sc->sc_tapped_fingers) {
1703 		case 1: return sc->sc_knobs.one_finger_tap_buttons;
1704 		case 2: return sc->sc_knobs.two_finger_tap_buttons;
1705 		case 3:
1706 		default: return sc->sc_knobs.three_finger_tap_buttons;
1707 		}
1708 
1709 	default:
1710 		aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
1711 		    __func__, sc->sc_tap_state);
1712 		return 0;
1713 	}
1714 }
1715 
1716 /*
1717  * Interpret the current input state to find a difference in all the
1718  * relevant coordinates and buttons to pass on to wsmouse, and update
1719  * any internal driver state necessary to interpret subsequent input
1720  * relative to this one.
1721  */
1722 
1723 static bool
1724 interpret_input(struct uatp_softc *sc, int *dx, int *dy, int *dz, int *dw,
1725     uint32_t *buttons)
1726 {
1727 	unsigned int x_pressure, x_raw, x_fingers;
1728 	unsigned int y_pressure, y_raw, y_fingers;
1729 	unsigned int fingers;
1730 
1731 	x_pressure = interpret_dimension(sc, uatp_x_acc(sc),
1732 	    uatp_x_sensors(sc), uatp_x_ratio(sc), &x_raw, &x_fingers);
1733 	y_pressure = interpret_dimension(sc, uatp_y_acc(sc),
1734 	    uatp_y_sensors(sc), uatp_y_ratio(sc), &y_raw, &y_fingers);
1735 
1736 	DPRINTF(sc, UATP_DEBUG_PARSE,
1737 	    ("x %u @ %u, %uf; y %u @ %u, %uf; buttons %"PRIx32"\n",
1738 		x_pressure, x_raw, x_fingers,
1739 		y_pressure, y_raw, y_fingers,
1740 		*buttons));
1741 
1742 	if ((x_pressure == 0) && (y_pressure == 0)) {
1743 		bool ok;
1744 		/* No fingers: clear position and maybe report a tap.  */
1745 		DPRINTF(sc, UATP_DEBUG_INTR,
1746 		    ("no position detected; clearing position\n"));
1747 		if (*buttons == 0) {
1748 			ok = tap_released(sc);
1749 		} else {
1750 			tap_reset(sc);
1751 			/* Button pressed: interrupt is not spurious.  */
1752 			ok = true;
1753 		}
1754 		/*
1755 		 * Don't clear the position until after tap_released,
1756 		 * which needs to know the track distance.
1757 		 */
1758 		uatp_clear_position(sc);
1759 		return ok;
1760 	} else if ((x_pressure == 0) || (y_pressure == 0)) {
1761 		/* XXX What to do here?  */
1762 		DPRINTF(sc, UATP_DEBUG_INTR,
1763 		    ("pressure in only one dimension; ignoring\n"));
1764 		return true;
1765 	} else if ((x_pressure == 1) && (y_pressure == 1)) {
1766 		fingers = uimax(x_fingers, y_fingers);
1767 		CHECK((0 < fingers), return false);
1768 		if (*buttons == 0)
1769 			tap_touched(sc, fingers);
1770 		else if (fingers == 1)
1771 			tap_reset(sc);
1772 		else		/* Multiple fingers, button pressed.  */
1773 			*buttons = emulated_buttons(sc, fingers);
1774 		update_position(sc, fingers, x_raw, y_raw, dx, dy, dz, dw);
1775 		return true;
1776 	} else {
1777 		/* Palm detected in either or both of the dimensions.  */
1778 		DPRINTF(sc, UATP_DEBUG_INTR, ("palm detected; ignoring\n"));
1779 		return true;
1780 	}
1781 }
1782 
1783 /*
1784  * Interpret the accumulated sensor state along one dimension to find
1785  * the number, mean position, and pressure of fingers.  Returns 0 to
1786  * indicate no pressure, returns 1 and sets *position and *fingers to
1787  * indicate fingers, and returns 2 to indicate palm.
1788  *
1789  * XXX Give symbolic names to the return values.
1790  */
1791 
1792 static unsigned int
1793 interpret_dimension(struct uatp_softc *sc, const int *acc,
1794     unsigned int n_sensors, unsigned int ratio,
1795     unsigned int *position, unsigned int *fingers)
1796 {
1797 	unsigned int i, v, n_fingers, sum;
1798 	unsigned int total[UATP_MAX_SENSORS];
1799 	unsigned int weighted[UATP_MAX_SENSORS];
1800 	unsigned int sensor_threshold = sc->sc_knobs.sensor_threshold;
1801 	unsigned int sensor_normalizer = sc->sc_knobs.sensor_normalizer;
1802 	unsigned int width = 0;	/* GCC is not smart enough.  */
1803 	unsigned int palm_width = sc->sc_knobs.palm_width;
1804 	enum { none, nondecreasing, decreasing } state = none;
1805 
1806 	if (sensor_threshold < sensor_normalizer)
1807 		sensor_normalizer = sensor_threshold;
1808 	if (palm_width == 0)	/* Effectively disable palm detection.  */
1809 		palm_width = UATP_MAX_POSITION;
1810 
1811 #define CHECK_(condition) CHECK(condition, return 0)
1812 
1813 	/*
1814 	 * Arithmetic bounds:
1815 	 * . n_sensors is at most UATP_MAX_SENSORS,
1816 	 * . n_fingers is at most UATP_MAX_SENSORS,
1817 	 * . i is at most UATP_MAX_SENSORS,
1818 	 * . sc->sc_acc[i] is at most UATP_MAX_ACC,
1819 	 * . i * sc->sc_acc[i] is at most UATP_MAX_SENSORS * UATP_MAX_ACC,
1820 	 * . each total[j] is at most UATP_MAX_SENSORS * UATP_MAX_ACC,
1821 	 * . each weighted[j] is at most UATP_MAX_SENSORS^2 * UATP_MAX_ACC,
1822 	 * . ratio is at most UATP_MAX_RATIO,
1823 	 * . each weighted[j] * ratio is at most
1824 	 *     UATP_MAX_SENSORS^2 * UATP_MAX_ACC * UATP_MAX_RATIO,
1825 	 *   which is #x5fa0000 with the current values of the constants,
1826 	 *   and
1827 	 * . the sum of the positions is at most
1828 	 *     UATP_MAX_SENSORS * UATP_MAX_POSITION,
1829 	 *   which is #x60000 with the current values of the constants.
1830 	 * Hence all of the arithmetic here fits in int (and thus also
1831 	 * unsigned int).  If you change the constants, though, you
1832 	 * must update the analysis.
1833 	 */
1834 	__CTASSERT(0x5fa0000 == (UATP_MAX_SENSORS * UATP_MAX_SENSORS *
1835 		UATP_MAX_ACC * UATP_MAX_RATIO));
1836 	__CTASSERT(0x60000 == (UATP_MAX_SENSORS * UATP_MAX_POSITION));
1837 	CHECK_(n_sensors <= UATP_MAX_SENSORS);
1838 	CHECK_(ratio <= UATP_MAX_RATIO);
1839 
1840 	/*
1841 	 * Detect each finger by looking for a consecutive sequence of
1842 	 * increasing and then decreasing pressures above the sensor
1843 	 * threshold.  Compute the finger's position as the weighted
1844 	 * average of positions, weighted by the pressure at that
1845 	 * position.  Finally, return the average finger position.
1846 	 */
1847 
1848 	n_fingers = 0;
1849 	memset(weighted, 0, sizeof(weighted));
1850 	memset(total, 0, sizeof(total));
1851 
1852 	for (i = 0; i < n_sensors; i++) {
1853 		CHECK_(0 <= acc[i]);
1854 		v = acc[i];
1855 
1856 		/* Ignore values outside a sensible interval.  */
1857 		if (v <= sensor_threshold) {
1858 			state = none;
1859 			continue;
1860 		} else if (UATP_MAX_ACC < v) {
1861 			aprint_verbose_dev(uatp_dev(sc),
1862 			    "ignoring large accumulated sensor state: %u\n",
1863 			    v);
1864 			continue;
1865 		}
1866 
1867 		switch (state) {
1868 		case none:
1869 			n_fingers += 1;
1870 			CHECK_(n_fingers <= n_sensors);
1871 			state = nondecreasing;
1872 			width = 1;
1873 			break;
1874 
1875 		case nondecreasing:
1876 		case decreasing:
1877 			CHECK_(0 < i);
1878 			CHECK_(0 <= acc[i - 1]);
1879 			width += 1;
1880 			if (palm_width <= (width * ratio)) {
1881 				DPRINTF(sc, UATP_DEBUG_PALM,
1882 				    ("palm detected\n"));
1883 				return 2;
1884 			} else if ((state == nondecreasing) &&
1885 			    ((unsigned int)acc[i - 1] > v)) {
1886 				state = decreasing;
1887 			} else if ((state == decreasing) &&
1888 			    ((unsigned int)acc[i - 1] < v)) {
1889 				n_fingers += 1;
1890 				CHECK_(n_fingers <= n_sensors);
1891 				state = nondecreasing;
1892 				width = 1;
1893 			}
1894 			break;
1895 
1896 		default:
1897 			aprint_error_dev(uatp_dev(sc),
1898 			    "bad finger detection state: %d", state);
1899 			return 0;
1900 		}
1901 
1902 		v -= sensor_normalizer;
1903 		total[n_fingers - 1] += v;
1904 		weighted[n_fingers - 1] += (i * v);
1905 		CHECK_(total[n_fingers - 1] <=
1906 		    (UATP_MAX_SENSORS * UATP_MAX_ACC));
1907 		CHECK_(weighted[n_fingers - 1] <=
1908 		    (UATP_MAX_SENSORS * UATP_MAX_SENSORS * UATP_MAX_ACC));
1909 	}
1910 
1911 	if (n_fingers == 0)
1912 		return 0;
1913 
1914 	sum = 0;
1915 	for (i = 0; i < n_fingers; i++) {
1916 		DPRINTF(sc, UATP_DEBUG_PARSE,
1917 		    ("finger at %u\n", ((weighted[i] * ratio) / total[i])));
1918 		sum += ((weighted[i] * ratio) / total[i]);
1919 		CHECK_(sum <= UATP_MAX_SENSORS * UATP_MAX_POSITION);
1920 	}
1921 
1922 	*fingers = n_fingers;
1923 	*position = (sum / n_fingers);
1924 	return 1;
1925 
1926 #undef CHECK_
1927 }
1928 
1929 /* Tapping */
1930 
1931 /*
1932  * There is a very hairy state machine for detecting taps.  At every
1933  * touch, we record the maximum number of fingers touched, and don't
1934  * reset it to zero until the finger is released.
1935  *
1936  * INITIAL STATE
1937  * (no tapping fingers; no tapped fingers)
1938  * - On touch, go to TAPPING STATE.
1939  * - On any other input, remain in INITIAL STATE.
1940  *
1941  * TAPPING STATE: Finger touched; might be tap.
1942  * (tapping fingers; no tapped fingers)
1943  * - On release within the tap limit, go to TAPPED STATE.
1944  * - On release after the tap limit, go to INITIAL STATE.
1945  * - On any other input, remain in TAPPING STATE.
1946  *
1947  * TAPPED STATE: Finger recently tapped, and might double-tap.
1948  * (no tapping fingers; tapped fingers)
1949  * - On touch within the double-tap limit, go to DOUBLE-TAPPING STATE.
1950  * - On touch after the double-tap limit, go to TAPPING STATE.
1951  * - On no event after the double-tap limit, go to INITIAL STATE.
1952  * - On any other input, remain in TAPPED STATE.
1953  *
1954  * DOUBLE-TAPPING STATE: Finger touched soon after tap; might be double-tap.
1955  * (tapping fingers; tapped fingers)
1956  * - On release within the tap limit, release button and go to TAPPED STATE.
1957  * - On release after the tap limit, go to DRAGGING UP STATE.
1958  * - On touch after the tap limit, go to DRAGGING DOWN STATE.
1959  * - On any other input, remain in DOUBLE-TAPPING STATE.
1960  *
1961  * DRAGGING DOWN STATE: Finger has double-tapped and is dragging, not tapping.
1962  * (no tapping fingers; tapped fingers)
1963  * - On release, go to DRAGGING UP STATE.
1964  * - On any other input, remain in DRAGGING DOWN STATE.
1965  *
1966  * DRAGGING UP STATE: Finger has double-tapped and is up.
1967  * (no tapping fingers; tapped fingers)
1968  * - On touch, go to TAPPING IN DRAG STATE.
1969  * - On any other input, remain in DRAGGING UP STATE.
1970  *
1971  * TAPPING IN DRAG STATE: Tap-dancing while cross-dressed.
1972  * (tapping fingers; tapped fingers)
1973  * - On release within the tap limit, go to TAPPED STATE.
1974  * - On release after the tap limit, go to DRAGGING UP STATE.
1975  * - On any other input, remain in TAPPING IN DRAG STATE.
1976  *
1977  * Warning:  The graph of states is split into two components, those
1978  * with tapped fingers and those without.  The only path from any state
1979  * without tapped fingers to a state with tapped fingers must pass
1980  * through TAPPED STATE.  Also, the only transitions into TAPPED STATE
1981  * must be from states with tapping fingers, which become the tapped
1982  * fingers.  If you edit the state machine, you must either preserve
1983  * these properties, or globally transform the state machine to avoid
1984  * the bad consequences of violating these properties.
1985  */
1986 
1987 static void
1988 uatp_tap_limit(const struct uatp_softc *sc, struct timeval *limit)
1989 {
1990 	unsigned int msec = sc->sc_knobs.tap_limit_msec;
1991 	limit->tv_sec = 0;
1992 	limit->tv_usec = ((msec < 1000) ? (1000 * msec) : 100000);
1993 }
1994 
1995 #if UATP_DEBUG
1996 
1997 #  define TAP_DEBUG_PRE(sc)	tap_debug((sc), __func__, "")
1998 #  define TAP_DEBUG_POST(sc)	tap_debug((sc), __func__, " ->")
1999 
2000 static void
2001 tap_debug(struct uatp_softc *sc, const char *caller, const char *prefix)
2002 {
2003 	char buffer[128];
2004 	const char *state;
2005 
2006 	KASSERT(mutex_owned(&sc->sc_tap_mutex));
2007 	switch (sc->sc_tap_state) {
2008 	case TAP_STATE_INITIAL:		state = "initial";		break;
2009 	case TAP_STATE_TAPPING:		state = "tapping";		break;
2010 	case TAP_STATE_TAPPED:		state = "tapped";		break;
2011 	case TAP_STATE_DOUBLE_TAPPING:	state = "double-tapping";	break;
2012 	case TAP_STATE_DRAGGING_DOWN:	state = "dragging-down";	break;
2013 	case TAP_STATE_DRAGGING_UP:	state = "dragging-up";		break;
2014 	case TAP_STATE_TAPPING_IN_DRAG:	state = "tapping-in-drag";	break;
2015 	default:
2016 		snprintf(buffer, sizeof(buffer), "unknown (%d)",
2017 		    sc->sc_tap_state);
2018 		state = buffer;
2019 		break;
2020 	}
2021 
2022 	DPRINTF(sc, UATP_DEBUG_TAP,
2023 	    ("%s:%s state %s, %u tapping, %u tapped\n",
2024 		caller, prefix, state,
2025 		sc->sc_tapping_fingers, sc->sc_tapped_fingers));
2026 }
2027 
2028 #else	/* !UATP_DEBUG */
2029 
2030 #  define TAP_DEBUG_PRE(sc)	do {} while (0)
2031 #  define TAP_DEBUG_POST(sc)	do {} while (0)
2032 
2033 #endif
2034 
2035 static void
2036 tap_initialize(struct uatp_softc *sc)
2037 {
2038 	callout_init(&sc->sc_untap_callout, 0);
2039 	callout_setfunc(&sc->sc_untap_callout, untap_callout, sc);
2040 	mutex_init(&sc->sc_tap_mutex, MUTEX_DEFAULT, IPL_SOFTUSB);
2041 }
2042 
2043 static void
2044 tap_finalize(struct uatp_softc *sc)
2045 {
2046 	/* XXX Can the callout still be scheduled here?  */
2047 	callout_destroy(&sc->sc_untap_callout);
2048 	mutex_destroy(&sc->sc_tap_mutex);
2049 }
2050 
2051 static void
2052 tap_enable(struct uatp_softc *sc)
2053 {
2054 	mutex_enter(&sc->sc_tap_mutex);
2055 	tap_transition_initial(sc);
2056 	sc->sc_buttons = 0;	/* XXX Not the right place?  */
2057 	sc->sc_all_buttons = 0;
2058 	mutex_exit(&sc->sc_tap_mutex);
2059 }
2060 
2061 static void
2062 tap_disable(struct uatp_softc *sc)
2063 {
2064 	/* Reset tapping, and wait for any callouts to complete.  */
2065 	tap_reset_wait(sc);
2066 }
2067 
2068 /*
2069  * Reset tap state.  If the untap callout has just fired, it may signal
2070  * a harmless button release event before this returns.
2071  */
2072 
2073 static void
2074 tap_reset(struct uatp_softc *sc)
2075 {
2076 
2077 	callout_stop(&sc->sc_untap_callout);
2078 	mutex_enter(&sc->sc_tap_mutex);
2079 	tap_transition_initial(sc);
2080 	mutex_exit(&sc->sc_tap_mutex);
2081 }
2082 
2083 /* Reset, but don't return until the callout is done running.  */
2084 
2085 static void
2086 tap_reset_wait(struct uatp_softc *sc)
2087 {
2088 
2089 	callout_halt(&sc->sc_untap_callout, NULL);
2090 	mutex_enter(&sc->sc_tap_mutex);
2091 	tap_transition_initial(sc);
2092 	mutex_exit(&sc->sc_tap_mutex);
2093 }
2094 
2095 static const struct timeval zero_timeval;
2096 
2097 static void
2098 tap_transition(struct uatp_softc *sc, enum uatp_tap_state tap_state,
2099     const struct timeval *start_time,
2100     unsigned int tapping_fingers, unsigned int tapped_fingers)
2101 {
2102 	KASSERT(mutex_owned(&sc->sc_tap_mutex));
2103 	sc->sc_tap_state = tap_state;
2104 	sc->sc_tap_timer = *start_time;
2105 	sc->sc_tapping_fingers = tapping_fingers;
2106 	sc->sc_tapped_fingers = tapped_fingers;
2107 }
2108 
2109 static void
2110 tap_transition_initial(struct uatp_softc *sc)
2111 {
2112 	/*
2113 	 * No checks.  This state is always kosher, and sometimes a
2114 	 * fallback in case of failure.
2115 	 */
2116 	tap_transition(sc, TAP_STATE_INITIAL, &zero_timeval, 0, 0);
2117 }
2118 
2119 /* Touch transitions */
2120 
2121 static void
2122 tap_transition_tapping(struct uatp_softc *sc, const struct timeval *start_time,
2123     unsigned int fingers)
2124 {
2125 	CHECK((sc->sc_tapping_fingers <= fingers),
2126 	    do { tap_transition_initial(sc); return; } while (0));
2127 	tap_transition(sc, TAP_STATE_TAPPING, start_time, fingers, 0);
2128 }
2129 
2130 static void
2131 tap_transition_double_tapping(struct uatp_softc *sc,
2132     const struct timeval *start_time, unsigned int fingers)
2133 {
2134 	CHECK((sc->sc_tapping_fingers <= fingers),
2135 	    do { tap_transition_initial(sc); return; } while (0));
2136 	CHECK((0 < sc->sc_tapped_fingers),
2137 	    do { tap_transition_initial(sc); return; } while (0));
2138 	tap_transition(sc, TAP_STATE_DOUBLE_TAPPING, start_time, fingers,
2139 	    sc->sc_tapped_fingers);
2140 }
2141 
2142 static void
2143 tap_transition_dragging_down(struct uatp_softc *sc)
2144 {
2145 	CHECK((0 < sc->sc_tapped_fingers),
2146 	    do { tap_transition_initial(sc); return; } while (0));
2147 	tap_transition(sc, TAP_STATE_DRAGGING_DOWN, &zero_timeval, 0,
2148 	    sc->sc_tapped_fingers);
2149 }
2150 
2151 static void
2152 tap_transition_tapping_in_drag(struct uatp_softc *sc,
2153     const struct timeval *start_time, unsigned int fingers)
2154 {
2155 	CHECK((sc->sc_tapping_fingers <= fingers),
2156 	    do { tap_transition_initial(sc); return; } while (0));
2157 	CHECK((0 < sc->sc_tapped_fingers),
2158 	    do { tap_transition_initial(sc); return; } while (0));
2159 	tap_transition(sc, TAP_STATE_TAPPING_IN_DRAG, start_time, fingers,
2160 	    sc->sc_tapped_fingers);
2161 }
2162 
2163 /* Release transitions */
2164 
2165 static void
2166 tap_transition_tapped(struct uatp_softc *sc, const struct timeval *start_time)
2167 {
2168 	/*
2169 	 * The fingers that were tapping -- of which there must have
2170 	 * been at least one -- are now the fingers that have tapped,
2171 	 * and there are no longer fingers tapping.
2172 	 */
2173 	CHECK((0 < sc->sc_tapping_fingers),
2174 	    do { tap_transition_initial(sc); return; } while (0));
2175 	tap_transition(sc, TAP_STATE_TAPPED, start_time, 0,
2176 	    sc->sc_tapping_fingers);
2177 	schedule_untap(sc);
2178 }
2179 
2180 static void
2181 tap_transition_dragging_up(struct uatp_softc *sc)
2182 {
2183 	CHECK((0 < sc->sc_tapped_fingers),
2184 	    do { tap_transition_initial(sc); return; } while (0));
2185 	tap_transition(sc, TAP_STATE_DRAGGING_UP, &zero_timeval, 0,
2186 	    sc->sc_tapped_fingers);
2187 }
2188 
2189 static void
2190 tap_touched(struct uatp_softc *sc, unsigned int fingers)
2191 {
2192 	struct timeval now, diff, limit;
2193 
2194 	CHECK((0 < fingers), return);
2195 	callout_stop(&sc->sc_untap_callout);
2196 	mutex_enter(&sc->sc_tap_mutex);
2197 	TAP_DEBUG_PRE(sc);
2198 	/*
2199 	 * Guarantee that the number of tapping fingers never decreases
2200 	 * except when it is reset to zero on release.
2201 	 */
2202 	if (fingers < sc->sc_tapping_fingers)
2203 		fingers = sc->sc_tapping_fingers;
2204 	switch (sc->sc_tap_state) {
2205 	case TAP_STATE_INITIAL:
2206 		getmicrouptime(&now);
2207 		tap_transition_tapping(sc, &now, fingers);
2208 		break;
2209 
2210 	case TAP_STATE_TAPPING:
2211 		/*
2212 		 * Number of fingers may have increased, so transition
2213 		 * even though we're already in TAPPING.
2214 		 */
2215 		tap_transition_tapping(sc, &sc->sc_tap_timer, fingers);
2216 		break;
2217 
2218 	case TAP_STATE_TAPPED:
2219 		getmicrouptime(&now);
2220 		/*
2221 		 * If the double-tap time limit has passed, it's the
2222 		 * callout's responsibility to handle that event, so we
2223 		 * assume the limit has not passed yet.
2224 		 */
2225 		tap_transition_double_tapping(sc, &now, fingers);
2226 		break;
2227 
2228 	case TAP_STATE_DOUBLE_TAPPING:
2229 		getmicrouptime(&now);
2230 		timersub(&now, &sc->sc_tap_timer, &diff);
2231 		uatp_tap_limit(sc, &limit);
2232 		if (timercmp(&diff, &limit, >) ||
2233 		    (sc->sc_track_distance >
2234 			sc->sc_knobs.tap_track_distance_limit))
2235 			tap_transition_dragging_down(sc);
2236 		break;
2237 
2238 	case TAP_STATE_DRAGGING_DOWN:
2239 		break;
2240 
2241 	case TAP_STATE_DRAGGING_UP:
2242 		getmicrouptime(&now);
2243 		tap_transition_tapping_in_drag(sc, &now, fingers);
2244 		break;
2245 
2246 	case TAP_STATE_TAPPING_IN_DRAG:
2247 		/*
2248 		 * Number of fingers may have increased, so transition
2249 		 * even though we're already in TAPPING IN DRAG.
2250 		 */
2251 		tap_transition_tapping_in_drag(sc, &sc->sc_tap_timer, fingers);
2252 		break;
2253 
2254 	default:
2255 		aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
2256 		    __func__, sc->sc_tap_state);
2257 		tap_transition_initial(sc);
2258 		break;
2259 	}
2260 	TAP_DEBUG_POST(sc);
2261 	mutex_exit(&sc->sc_tap_mutex);
2262 }
2263 
2264 static bool
2265 tap_released(struct uatp_softc *sc)
2266 {
2267 	struct timeval now, diff, limit;
2268 	void (*non_tapped_transition)(struct uatp_softc *);
2269 	bool ok, temporary_release;
2270 
2271 	mutex_enter(&sc->sc_tap_mutex);
2272 	TAP_DEBUG_PRE(sc);
2273 	switch (sc->sc_tap_state) {
2274 	case TAP_STATE_INITIAL:
2275 	case TAP_STATE_TAPPED:
2276 	case TAP_STATE_DRAGGING_UP:
2277 		/* Spurious interrupt: fingers are already off.  */
2278 		ok = false;
2279 		break;
2280 
2281 	case TAP_STATE_TAPPING:
2282 		temporary_release = false;
2283 		non_tapped_transition = &tap_transition_initial;
2284 		goto maybe_tap;
2285 
2286 	case TAP_STATE_DOUBLE_TAPPING:
2287 		temporary_release = true;
2288 		non_tapped_transition = &tap_transition_dragging_up;
2289 		goto maybe_tap;
2290 
2291 	case TAP_STATE_TAPPING_IN_DRAG:
2292 		temporary_release = false;
2293 		non_tapped_transition = &tap_transition_dragging_up;
2294 		goto maybe_tap;
2295 
2296 	maybe_tap:
2297 		getmicrouptime(&now);
2298 		timersub(&now, &sc->sc_tap_timer, &diff);
2299 		uatp_tap_limit(sc, &limit);
2300 		if (timercmp(&diff, &limit, <=) &&
2301 		    (sc->sc_track_distance <=
2302 			sc->sc_knobs.tap_track_distance_limit)) {
2303 			if (temporary_release) {
2304 				/*
2305 				 * XXX Kludge: Temporarily transition
2306 				 * to a tap state that uatp_input will
2307 				 * interpret as `no buttons tapped',
2308 				 * saving the tapping fingers.  There
2309 				 * should instead be a separate routine
2310 				 * uatp_input_untapped.
2311 				 */
2312 				unsigned int fingers = sc->sc_tapping_fingers;
2313 				tap_transition_initial(sc);
2314 				uatp_input(sc, 0, 0, 0, 0, 0);
2315 				sc->sc_tapping_fingers = fingers;
2316 			}
2317 			tap_transition_tapped(sc, &now);
2318 		} else {
2319 			(*non_tapped_transition)(sc);
2320 		}
2321 		ok = true;
2322 		break;
2323 
2324 	case TAP_STATE_DRAGGING_DOWN:
2325 		tap_transition_dragging_up(sc);
2326 		ok = true;
2327 		break;
2328 
2329 	default:
2330 		aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
2331 		    __func__, sc->sc_tap_state);
2332 		tap_transition_initial(sc);
2333 		ok = false;
2334 		break;
2335 	}
2336 	TAP_DEBUG_POST(sc);
2337 	mutex_exit(&sc->sc_tap_mutex);
2338 	return ok;
2339 }
2340 
2341 /* Untapping: Releasing the button after a tap */
2342 
2343 static void
2344 schedule_untap(struct uatp_softc *sc)
2345 {
2346 	unsigned int ms = sc->sc_knobs.double_tap_limit_msec;
2347 	if (ms <= 1000)
2348 		callout_schedule(&sc->sc_untap_callout, mstohz(ms));
2349 	else			/* XXX Reject bogus values in sysctl.  */
2350 		aprint_error_dev(uatp_dev(sc),
2351 		    "double-tap delay too long: %ums\n", ms);
2352 }
2353 
2354 static void
2355 untap_callout(void *arg)
2356 {
2357 	struct uatp_softc *sc = arg;
2358 
2359 	mutex_enter(&sc->sc_tap_mutex);
2360 	TAP_DEBUG_PRE(sc);
2361 	switch (sc->sc_tap_state) {
2362 	case TAP_STATE_TAPPED:
2363 		tap_transition_initial(sc);
2364 		/*
2365 		 * XXX Kludge: Call uatp_input after the state transition
2366 		 * to make sure that it will actually release the button.
2367 		 */
2368 		uatp_input(sc, 0, 0, 0, 0, 0);
2369 
2370 	case TAP_STATE_INITIAL:
2371 	case TAP_STATE_TAPPING:
2372 	case TAP_STATE_DOUBLE_TAPPING:
2373 	case TAP_STATE_DRAGGING_UP:
2374 	case TAP_STATE_DRAGGING_DOWN:
2375 	case TAP_STATE_TAPPING_IN_DRAG:
2376 		/*
2377 		 * Somebody else got in and changed the state before we
2378 		 * untapped.  Let them take over; do nothing here.
2379 		 */
2380 		break;
2381 
2382 	default:
2383 		aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
2384 		    __func__, sc->sc_tap_state);
2385 		tap_transition_initial(sc);
2386 		/* XXX Just in case...?  */
2387 		uatp_input(sc, 0, 0, 0, 0, 0);
2388 		break;
2389 	}
2390 	TAP_DEBUG_POST(sc);
2391 	mutex_exit(&sc->sc_tap_mutex);
2392 }
2393 
2394 /*
2395  * Emulate different buttons if the user holds down n fingers while
2396  * pressing the physical button.  (This is unrelated to tapping.)
2397  */
2398 
2399 static uint32_t
2400 emulated_buttons(struct uatp_softc *sc, unsigned int fingers)
2401 {
2402 	CHECK((1 < fingers), return 0);
2403 
2404 	switch (fingers) {
2405 	case 2:
2406 		DPRINTF(sc, UATP_DEBUG_EMUL_BUTTON,
2407 		    ("2-finger emulated button: %"PRIx32"\n",
2408 			sc->sc_knobs.two_finger_buttons));
2409 		return sc->sc_knobs.two_finger_buttons;
2410 
2411 	case 3:
2412 	default:
2413 		DPRINTF(sc, UATP_DEBUG_EMUL_BUTTON,
2414 		    ("3-finger emulated button: %"PRIx32"\n",
2415 			sc->sc_knobs.three_finger_buttons));
2416 		return sc->sc_knobs.three_finger_buttons;
2417 	}
2418 }
2419 
2420 /*
2421  * Update the position known to the driver based on the position and
2422  * number of fingers.  dx, dy, dz, and dw are expected to hold zero;
2423  * update_position may store nonzero changes in position in them.
2424  */
2425 
2426 static void
2427 update_position(struct uatp_softc *sc, unsigned int fingers,
2428     unsigned int x_raw, unsigned int y_raw,
2429     int *dx, int *dy, int *dz, int *dw)
2430 {
2431 	CHECK((0 < fingers), return);
2432 
2433 	if ((fingers == 1) || (sc->sc_knobs.multifinger_track == 1))
2434 		move_mouse(sc, x_raw, y_raw, dx, dy);
2435 	else if (sc->sc_knobs.multifinger_track == 2)
2436 		scroll_wheel(sc, x_raw, y_raw, dz, dw);
2437 }
2438 
2439 /*
2440  * XXX Scrolling needs to use a totally different motion model.
2441  */
2442 
2443 static void
2444 move_mouse(struct uatp_softc *sc, unsigned int x_raw, unsigned int y_raw,
2445     int *dx, int *dy)
2446 {
2447 	move(sc, "mouse", x_raw, y_raw, &sc->sc_x_raw, &sc->sc_y_raw,
2448 	    &sc->sc_x_smoothed, &sc->sc_y_smoothed,
2449 	    &sc->sc_x_remainder, &sc->sc_y_remainder,
2450 	    dx, dy);
2451 }
2452 
2453 static void
2454 scroll_wheel(struct uatp_softc *sc, unsigned int x_raw, unsigned int y_raw,
2455     int *dz, int *dw)
2456 {
2457 	move(sc, "scroll", x_raw, y_raw, &sc->sc_z_raw, &sc->sc_w_raw,
2458 	    &sc->sc_z_smoothed, &sc->sc_w_smoothed,
2459 	    &sc->sc_z_remainder, &sc->sc_w_remainder,
2460 	    dz, dw);
2461 }
2462 
2463 static void
2464 move(struct uatp_softc *sc, const char *ctx, unsigned int a, unsigned int b,
2465     int *a_raw, int *b_raw,
2466     int *a_smoothed, int *b_smoothed,
2467     unsigned int *a_remainder, unsigned int *b_remainder,
2468     int *da, int *db)
2469 {
2470 #define CHECK_(condition) CHECK(condition, return)
2471 
2472 	int old_a_raw = *a_raw, old_a_smoothed = *a_smoothed;
2473 	int old_b_raw = *b_raw, old_b_smoothed = *b_smoothed;
2474 	unsigned int a_dist, b_dist, dist_squared;
2475 	bool a_fast, b_fast;
2476 
2477 	/*
2478 	 * Make sure the quadratics in motion_below_threshold and
2479 	 * tracking distance don't overflow int arithmetic.
2480 	 */
2481 	__CTASSERT(0x12000000 == (2 * UATP_MAX_POSITION * UATP_MAX_POSITION));
2482 
2483 	CHECK_(a <= UATP_MAX_POSITION);
2484 	CHECK_(b <= UATP_MAX_POSITION);
2485 	*a_raw = a;
2486 	*b_raw = b;
2487 	if ((old_a_raw < 0) || (old_b_raw < 0)) {
2488 		DPRINTF(sc, UATP_DEBUG_MOVE,
2489 		    ("initialize %s position (%d, %d) -> (%d, %d)\n", ctx,
2490 			old_a_raw, old_b_raw, a, b));
2491 		return;
2492 	}
2493 
2494 	if ((old_a_smoothed < 0) || (old_b_smoothed < 0)) {
2495 		/* XXX Does this make sense?  */
2496 		old_a_smoothed = old_a_raw;
2497 		old_b_smoothed = old_b_raw;
2498 	}
2499 
2500 	CHECK_(0 <= old_a_raw);
2501 	CHECK_(0 <= old_b_raw);
2502 	CHECK_(old_a_raw <= UATP_MAX_POSITION);
2503 	CHECK_(old_b_raw <= UATP_MAX_POSITION);
2504 	CHECK_(0 <= old_a_smoothed);
2505 	CHECK_(0 <= old_b_smoothed);
2506 	CHECK_(old_a_smoothed <= UATP_MAX_POSITION);
2507 	CHECK_(old_b_smoothed <= UATP_MAX_POSITION);
2508 	CHECK_(0 <= *a_raw);
2509 	CHECK_(0 <= *b_raw);
2510 	CHECK_(*a_raw <= UATP_MAX_POSITION);
2511 	CHECK_(*b_raw <= UATP_MAX_POSITION);
2512 	*a_smoothed = smooth(sc, old_a_raw, old_a_smoothed, *a_raw);
2513 	*b_smoothed = smooth(sc, old_b_raw, old_b_smoothed, *b_raw);
2514 	CHECK_(0 <= *a_smoothed);
2515 	CHECK_(0 <= *b_smoothed);
2516 	CHECK_(*a_smoothed <= UATP_MAX_POSITION);
2517 	CHECK_(*b_smoothed <= UATP_MAX_POSITION);
2518 
2519 	if (sc->sc_motion_timer < sc->sc_knobs.motion_delay) {
2520 		DPRINTF(sc, UATP_DEBUG_MOVE, ("delay motion %u\n",
2521 			sc->sc_motion_timer));
2522 		sc->sc_motion_timer += 1;
2523 		return;
2524 	}
2525 
2526 	/* XXX Use raw distances or smoothed distances?  Acceleration?  */
2527 	if (*a_smoothed < old_a_smoothed)
2528 		a_dist = old_a_smoothed - *a_smoothed;
2529 	else
2530 		a_dist = *a_smoothed - old_a_smoothed;
2531 
2532 	if (*b_smoothed < old_b_smoothed)
2533 		b_dist = old_b_smoothed - *b_smoothed;
2534 	else
2535 		b_dist = *b_smoothed - old_b_smoothed;
2536 
2537 	dist_squared = (a_dist * a_dist) + (b_dist * b_dist);
2538 	if (dist_squared < ((2 * UATP_MAX_POSITION * UATP_MAX_POSITION)
2539 		- sc->sc_track_distance))
2540 		sc->sc_track_distance += dist_squared;
2541 	else
2542 		sc->sc_track_distance = (2 * UATP_MAX_POSITION *
2543 		    UATP_MAX_POSITION);
2544 	DPRINTF(sc, UATP_DEBUG_TRACK_DIST, ("finger has tracked %u units^2\n",
2545 		sc->sc_track_distance));
2546 
2547 	/*
2548 	 * The checks above guarantee that the differences here are at
2549 	 * most UATP_MAX_POSITION in magnitude, since both minuend and
2550 	 * subtrahend are nonnegative and at most UATP_MAX_POSITION.
2551 	 */
2552 	if (motion_below_threshold(sc, sc->sc_knobs.motion_threshold,
2553 		(int)(*a_smoothed - old_a_smoothed),
2554 		(int)(*b_smoothed - old_b_smoothed))) {
2555 		DPRINTF(sc, UATP_DEBUG_MOVE,
2556 		    ("%s motion too small: (%d, %d) -> (%d, %d)\n", ctx,
2557 			old_a_smoothed, old_b_smoothed,
2558 			*a_smoothed, *b_smoothed));
2559 		return;
2560 	}
2561 	if (sc->sc_knobs.fast_per_direction == 0) {
2562 		a_fast = b_fast = !motion_below_threshold(sc,
2563 		    sc->sc_knobs.fast_motion_threshold,
2564 		    (int)(*a_smoothed - old_a_smoothed),
2565 		    (int)(*b_smoothed - old_b_smoothed));
2566 	} else {
2567 		a_fast = !motion_below_threshold(sc,
2568 		    sc->sc_knobs.fast_motion_threshold,
2569 		    (int)(*a_smoothed - old_a_smoothed),
2570 		    0);
2571 		b_fast = !motion_below_threshold(sc,
2572 		    sc->sc_knobs.fast_motion_threshold,
2573 		    0,
2574 		    (int)(*b_smoothed - old_b_smoothed));
2575 	}
2576 	*da = accelerate(sc, old_a_raw, *a_raw, old_a_smoothed, *a_smoothed,
2577 	    a_fast, a_remainder);
2578 	*db = accelerate(sc, old_b_raw, *b_raw, old_b_smoothed, *b_smoothed,
2579 	    b_fast, b_remainder);
2580 	DPRINTF(sc, UATP_DEBUG_MOVE,
2581 	    ("update %s position (%d, %d) -> (%d, %d), move by (%d, %d)\n",
2582 		ctx, old_a_smoothed, old_b_smoothed, *a_smoothed, *b_smoothed,
2583 		*da, *db));
2584 
2585 #undef CHECK_
2586 }
2587 
2588 static int
2589 smooth(struct uatp_softc *sc, unsigned int old_raw, unsigned int old_smoothed,
2590     unsigned int raw)
2591 {
2592 #define CHECK_(condition) CHECK(condition, return old_raw)
2593 
2594 	/*
2595 	 * Arithmetic bounds:
2596 	 * . the weights are at most UATP_MAX_WEIGHT;
2597 	 * . the positions are at most UATP_MAX_POSITION; and so
2598 	 * . the numerator of the average is at most
2599 	 *     3 * UATP_MAX_WEIGHT * UATP_MAX_POSITION,
2600 	 *   which is #x477000, fitting comfortably in an int.
2601 	 */
2602 	__CTASSERT(0x477000 == (3 * UATP_MAX_WEIGHT * UATP_MAX_POSITION));
2603 	unsigned int old_raw_weight = uatp_old_raw_weight(sc);
2604 	unsigned int old_smoothed_weight = uatp_old_smoothed_weight(sc);
2605 	unsigned int new_raw_weight = uatp_new_raw_weight(sc);
2606 	CHECK_(old_raw_weight <= UATP_MAX_WEIGHT);
2607 	CHECK_(old_smoothed_weight <= UATP_MAX_WEIGHT);
2608 	CHECK_(new_raw_weight <= UATP_MAX_WEIGHT);
2609 	CHECK_(old_raw <= UATP_MAX_POSITION);
2610 	CHECK_(old_smoothed <= UATP_MAX_POSITION);
2611 	CHECK_(raw <= UATP_MAX_POSITION);
2612 	return (((old_raw_weight * old_raw) +
2613 		(old_smoothed_weight * old_smoothed) +
2614 		(new_raw_weight * raw))
2615 	    / (old_raw_weight + old_smoothed_weight + new_raw_weight));
2616 
2617 #undef CHECK_
2618 }
2619 
2620 static bool
2621 motion_below_threshold(struct uatp_softc *sc, unsigned int threshold,
2622     int x, int y)
2623 {
2624 	unsigned int x_squared, y_squared;
2625 
2626 	/* Caller guarantees the multiplication will not overflow.  */
2627 	KASSERT(-UATP_MAX_POSITION <= x);
2628 	KASSERT(-UATP_MAX_POSITION <= y);
2629 	KASSERT(x <= UATP_MAX_POSITION);
2630 	KASSERT(y <= UATP_MAX_POSITION);
2631 	__CTASSERT(0x12000000 == (2 * UATP_MAX_POSITION * UATP_MAX_POSITION));
2632 
2633 	x_squared = (x * x);
2634 	y_squared = (y * y);
2635 
2636 	return (x_squared + y_squared) < threshold;
2637 }
2638 
2639 static int
2640 accelerate(struct uatp_softc *sc, unsigned int old_raw, unsigned int raw,
2641     unsigned int old_smoothed, unsigned int smoothed, bool fast,
2642     int *remainder)
2643 {
2644 #define CHECK_(condition) CHECK(condition, return 0)
2645 
2646 	/* Guarantee that the scaling won't overflow.  */
2647 	__CTASSERT(0x30000 ==
2648 	    (UATP_MAX_POSITION * UATP_MAX_MOTION_MULTIPLIER));
2649 
2650 	CHECK_(old_raw <= UATP_MAX_POSITION);
2651 	CHECK_(raw <= UATP_MAX_POSITION);
2652 	CHECK_(old_smoothed <= UATP_MAX_POSITION);
2653 	CHECK_(smoothed <= UATP_MAX_POSITION);
2654 
2655 	return (fast ? uatp_scale_fast_motion : uatp_scale_motion)
2656 	    (sc, (((int) smoothed) - ((int) old_smoothed)), remainder);
2657 
2658 #undef CHECK_
2659 }
2660 
2661 MODULE(MODULE_CLASS_DRIVER, uatp, NULL);
2662 
2663 #ifdef _MODULE
2664 #include "ioconf.c"
2665 #endif
2666 
2667 static int
2668 uatp_modcmd(modcmd_t cmd, void *aux)
2669 {
2670 	int error = 0;
2671 
2672 	switch (cmd) {
2673 	case MODULE_CMD_INIT:
2674 #ifdef _MODULE
2675 		error = config_init_component(cfdriver_ioconf_uatp,
2676 		    cfattach_ioconf_uatp, cfdata_ioconf_uatp);
2677 #endif
2678 		return error;
2679 	case MODULE_CMD_FINI:
2680 #ifdef _MODULE
2681 		error = config_fini_component(cfdriver_ioconf_uatp,
2682 		    cfattach_ioconf_uatp, cfdata_ioconf_uatp);
2683 #endif
2684 		return error;
2685 	default:
2686 		return ENOTTY;
2687 	}
2688 }
2689