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