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