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