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