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