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