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