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