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