Home | History | Annotate | Line # | Download | only in usb
uatp.c revision 1.10.2.3
      1 /*	$NetBSD: uatp.c,v 1.10.2.3 2018/08/08 10:17:11 martin 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.10.2.3 2018/08/08 10:17:11 martin 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/hid.h>
    174 #include <dev/usb/usbhid.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 	kcondvar_t sc_tap_cv;		/* Signalled by untap callout.  */
    518 	enum uatp_tap_state sc_tap_state;	/* Current tap state.  */
    519 	unsigned int sc_tapping_fingers;	/* No. fingers tapping.  */
    520 	unsigned int sc_tapped_fingers;	/* No. fingers of last tap.  */
    521 	struct timeval sc_tap_timer;	/* Timer for tap state transitions.  */
    522 	uint32_t sc_buttons;		/* Physical buttons pressed.  */
    523 	uint32_t sc_all_buttons;	/* Buttons pressed or tapped.  */
    524 
    525 #if UATP_DEBUG
    526 	uint32_t sc_debug_flags;	/* Debugging output enabled.  */
    527 #endif
    528 };
    529 
    530 struct uatp_descriptor {
    531 	uint16_t vendor;
    532 	uint16_t product;
    533 	const char *description;
    534 	const struct uatp_parameters *parameters;
    535 };
    536 
    537 struct uatp_parameters {
    538 	unsigned int x_ratio;		/* Screen width / trackpad width.  */
    539 	unsigned int x_sensors;		/* Number of horizontal sensors.  */
    540 	unsigned int x_sensors_17;	/* XXX Same, on a 17" laptop.  */
    541 	unsigned int y_ratio;		/* Screen height / trackpad height.  */
    542 	unsigned int y_sensors;		/* Number of vertical sensors.  */
    543 	unsigned int input_size;	/* Size in bytes of input packets.  */
    544 
    545 	/* Device-specific initialization routine.  May be null.  */
    546 	void (*initialize)(struct uatp_softc *);
    547 
    548 	/* Device-specific finalization routine.  May be null.  May fail.  */
    549 	int (*finalize)(struct uatp_softc *);
    550 
    551 	/* Tests whether this is a base sample.  Second argument is
    552 	 * input_size bytes long.  */
    553 	bool (*base_sample)(const struct uatp_softc *, const uint8_t *);
    554 
    555 	/* Reads a sensor sample from an input packet.  First argument
    556 	 * is UATP_MAX_X_SENSORS bytes long; second, UATP_MAX_Y_SENSORS
    557 	 * bytes; third, input_size bytes.  */
    558 	void (*read_sample)(uint8_t *, uint8_t *, const uint8_t *);
    559 
    560 	/* Accumulates sensor state in sc->sc_acc.  */
    561 	void (*accumulate)(struct uatp_softc *);
    562 
    563 	/* Called on spurious interrupts to reset.  May be null.  */
    564 	void (*reset)(struct uatp_softc *);
    565 };
    566 
    567 /* Known device parameters */
    568 
    569 static const struct uatp_parameters fountain_parameters = {
    570 	.x_ratio	= 64,	.x_sensors = 16,	.x_sensors_17 = 26,
    571 	.y_ratio	= 43,	.y_sensors = 16,
    572 	.input_size	= 81,
    573 	.initialize	= NULL,
    574 	.finalize	= NULL,
    575 	.base_sample	= base_sample_softc_flag,
    576 	.read_sample	= read_sample_1,
    577 	.accumulate	= accumulate_sample_1,
    578 	.reset		= NULL,
    579 };
    580 
    581 static const struct uatp_parameters geyser_1_parameters = {
    582 	.x_ratio	= 64,	.x_sensors = 16,	.x_sensors_17 = 26,
    583 	.y_ratio	= 43,	.y_sensors = 16,
    584 	.input_size	= 81,
    585 	.initialize	= NULL,
    586 	.finalize	= NULL,
    587 	.base_sample	= base_sample_softc_flag,
    588 	.read_sample	= read_sample_1,
    589 	.accumulate	= accumulate_sample_1,
    590 	.reset		= NULL,
    591 };
    592 
    593 static const struct uatp_parameters geyser_2_parameters = {
    594 	.x_ratio	= 64,	.x_sensors = 15,	.x_sensors_17 = 20,
    595 	.y_ratio	= 43,	.y_sensors = 9,
    596 	.input_size	= 64,
    597 	.initialize	= NULL,
    598 	.finalize	= NULL,
    599 	.base_sample	= base_sample_softc_flag,
    600 	.read_sample	= read_sample_2,
    601 	.accumulate	= accumulate_sample_1,
    602 	.reset		= NULL,
    603 };
    604 
    605 /*
    606  * The Geyser 3 and Geyser 4 share parameters.  They also present
    607  * generic USB HID mice on a different report id, so we have smaller
    608  * packets by one byte (uhidev handles multiplexing report ids) and
    609  * extra initialization work to switch the mode from generic USB HID
    610  * mouse to Apple trackpad.
    611  */
    612 
    613 static const struct uatp_parameters geyser_3_4_parameters = {
    614 	.x_ratio	= 64,	.x_sensors = 20, /* XXX */ .x_sensors_17 = 0,
    615 	.y_ratio	= 64,	.y_sensors = 9,
    616 	.input_size	= 63,	/* 64, minus one for the report id.  */
    617 	.initialize	= geyser34_initialize,
    618 	.finalize	= geyser34_finalize,
    619 	.base_sample	= base_sample_input_flag,
    620 	.read_sample	= read_sample_2,
    621 	.accumulate	= accumulate_sample_2,
    622 	.reset		= geyser34_deferred_reset,
    623 };
    624 
    625 /* Known device models */
    626 
    627 #define APPLE_TRACKPAD(PRODUCT, DESCRIPTION, PARAMETERS)		\
    628 	{								\
    629 		.vendor = USB_VENDOR_APPLE,				\
    630 		.product = (PRODUCT),					\
    631 		.description = "Apple " DESCRIPTION " trackpad",	\
    632 		.parameters = (& (PARAMETERS)),				\
    633 	}
    634 
    635 #define POWERBOOK_TRACKPAD(PRODUCT, PARAMETERS)				\
    636 	APPLE_TRACKPAD(PRODUCT, "PowerBook/iBook", PARAMETERS)
    637 #define MACBOOK_TRACKPAD(PRODUCT, PARAMETERS)				\
    638 	APPLE_TRACKPAD(PRODUCT, "MacBook/MacBook Pro", PARAMETERS)
    639 
    640 static const struct uatp_descriptor uatp_descriptors[] =
    641 {
    642 	POWERBOOK_TRACKPAD(0x020e, fountain_parameters),
    643 	POWERBOOK_TRACKPAD(0x020f, fountain_parameters),
    644 	POWERBOOK_TRACKPAD(0x030a, fountain_parameters),
    645 
    646 	POWERBOOK_TRACKPAD(0x030b, geyser_1_parameters),
    647 
    648 	POWERBOOK_TRACKPAD(0x0214, geyser_2_parameters),
    649 	POWERBOOK_TRACKPAD(0x0215, geyser_2_parameters),
    650 	POWERBOOK_TRACKPAD(0x0216, geyser_2_parameters),
    651 
    652 	MACBOOK_TRACKPAD(0x0217, geyser_3_4_parameters), /* 3 */
    653 	MACBOOK_TRACKPAD(0x0218, geyser_3_4_parameters), /* 3 */
    654 	MACBOOK_TRACKPAD(0x0219, geyser_3_4_parameters), /* 3 */
    655 
    656 	MACBOOK_TRACKPAD(0x021a, geyser_3_4_parameters), /* 4 */
    657 	MACBOOK_TRACKPAD(0x021b, geyser_3_4_parameters), /* 4 */
    658 	MACBOOK_TRACKPAD(0x021c, geyser_3_4_parameters), /* 4 */
    659 
    660 	MACBOOK_TRACKPAD(0x0229, geyser_3_4_parameters), /* 4 */
    661 	MACBOOK_TRACKPAD(0x022a, geyser_3_4_parameters), /* 4 */
    662 	MACBOOK_TRACKPAD(0x022b, geyser_3_4_parameters), /* 4 */
    663 };
    664 
    665 #undef MACBOOK_TRACKPAD
    666 #undef POWERBOOK_TRACKPAD
    667 #undef APPLE_TRACKPAD
    668 
    669 /* Miscellaneous utilities */
    670 
    671 static const struct uatp_descriptor *
    672 find_uatp_descriptor(const struct uhidev_attach_arg *uha)
    673 {
    674 	unsigned int i;
    675 
    676 	for (i = 0; i < __arraycount(uatp_descriptors); i++)
    677 		if ((uha->uiaa->uiaa_vendor == uatp_descriptors[i].vendor) &&
    678 		    (uha->uiaa->uiaa_product == uatp_descriptors[i].product))
    679 			return &uatp_descriptors[i];
    680 
    681 	return NULL;
    682 }
    683 
    684 static device_t
    685 uatp_dev(const struct uatp_softc *sc)
    686 {
    687 	return sc->sc_hdev.sc_dev;
    688 }
    689 
    690 static uint8_t *
    691 uatp_x_sample(struct uatp_softc *sc)
    692 {
    693 	return &sc->sc_sample[0];
    694 }
    695 
    696 static uint8_t *
    697 uatp_y_sample(struct uatp_softc *sc)
    698 {
    699 	return &sc->sc_sample[UATP_MAX_X_SENSORS];
    700 }
    701 
    702 static int *
    703 uatp_x_acc(struct uatp_softc *sc)
    704 {
    705 	return &sc->sc_acc[0];
    706 }
    707 
    708 static int *
    709 uatp_y_acc(struct uatp_softc *sc)
    710 {
    711 	return &sc->sc_acc[UATP_MAX_X_SENSORS];
    712 }
    713 
    714 static void
    715 uatp_clear_position(struct uatp_softc *sc)
    716 {
    717 	memset(sc->sc_acc, 0, sizeof(sc->sc_acc));
    718 	sc->sc_motion_timer = 0;
    719 	sc->sc_x_raw = sc->sc_x_smoothed = -1;
    720 	sc->sc_y_raw = sc->sc_y_smoothed = -1;
    721 	sc->sc_z_raw = sc->sc_z_smoothed = -1;
    722 	sc->sc_w_raw = sc->sc_w_smoothed = -1;
    723 	sc->sc_x_remainder = 0;
    724 	sc->sc_y_remainder = 0;
    725 	sc->sc_z_remainder = 0;
    726 	sc->sc_w_remainder = 0;
    727 	sc->sc_track_distance = 0;
    728 }
    729 
    730 static unsigned int
    731 uatp_x_sensors(const struct uatp_softc *sc)
    732 {
    733 	if ((0 < sc->sc_knobs.x_sensors) &&
    734 	    (sc->sc_knobs.x_sensors <= UATP_MAX_X_SENSORS))
    735 		return sc->sc_knobs.x_sensors;
    736 	else
    737 		return sc->sc_parameters->x_sensors;
    738 }
    739 
    740 static unsigned int
    741 uatp_y_sensors(const struct uatp_softc *sc)
    742 {
    743 	if ((0 < sc->sc_knobs.y_sensors) &&
    744 	    (sc->sc_knobs.y_sensors <= UATP_MAX_Y_SENSORS))
    745 		return sc->sc_knobs.y_sensors;
    746 	else
    747 		return sc->sc_parameters->y_sensors;
    748 }
    749 
    750 static unsigned int
    751 uatp_x_ratio(const struct uatp_softc *sc)
    752 {
    753 	/* XXX Reject bogus values in sysctl.  */
    754 	if ((0 < sc->sc_knobs.x_ratio) &&
    755 	    (sc->sc_knobs.x_ratio <= UATP_MAX_X_RATIO))
    756 		return sc->sc_knobs.x_ratio;
    757 	else
    758 		return sc->sc_parameters->x_ratio;
    759 }
    760 
    761 static unsigned int
    762 uatp_y_ratio(const struct uatp_softc *sc)
    763 {
    764 	/* XXX Reject bogus values in sysctl.  */
    765 	if ((0 < sc->sc_knobs.y_ratio) &&
    766 	    (sc->sc_knobs.y_ratio <= UATP_MAX_Y_RATIO))
    767 		return sc->sc_knobs.y_ratio;
    768 	else
    769 		return sc->sc_parameters->y_ratio;
    770 }
    771 
    772 static unsigned int
    773 uatp_old_raw_weight(const struct uatp_softc *sc)
    774 {
    775 	/* XXX Reject bogus values in sysctl.  */
    776 	if (sc->sc_knobs.old_raw_weight <= UATP_MAX_WEIGHT)
    777 		return sc->sc_knobs.old_raw_weight;
    778 	else
    779 		return 0;
    780 }
    781 
    782 static unsigned int
    783 uatp_old_smoothed_weight(const struct uatp_softc *sc)
    784 {
    785 	/* XXX Reject bogus values in sysctl.  */
    786 	if (sc->sc_knobs.old_smoothed_weight <= UATP_MAX_WEIGHT)
    787 		return sc->sc_knobs.old_smoothed_weight;
    788 	else
    789 		return 0;
    790 }
    791 
    792 static unsigned int
    793 uatp_new_raw_weight(const struct uatp_softc *sc)
    794 {
    795 	/* XXX Reject bogus values in sysctl.  */
    796 	if ((0 < sc->sc_knobs.new_raw_weight) &&
    797 	    (sc->sc_knobs.new_raw_weight <= UATP_MAX_WEIGHT))
    798 		return sc->sc_knobs.new_raw_weight;
    799 	else
    800 		return 1;
    801 }
    802 
    803 static int
    804 scale_motion(const struct uatp_softc *sc, int delta, int *remainder,
    805     const unsigned int *multiplier, const unsigned int *divisor)
    806 {
    807 	int product;
    808 
    809 	/* XXX Limit the divisor?  */
    810 	if (((*multiplier) == 0) ||
    811 	    ((*multiplier) > UATP_MAX_MOTION_MULTIPLIER) ||
    812 	    ((*divisor) == 0))
    813 		DPRINTF(sc, UATP_DEBUG_ACCEL,
    814 		    ("bad knobs; %d (+ %d) --> %d, rem 0\n",
    815 			delta, *remainder, (delta + (*remainder))));
    816 	else
    817 		DPRINTF(sc, UATP_DEBUG_ACCEL,
    818 		    ("scale %d (+ %d) by %u/%u --> %d, rem %d\n",
    819 			delta, *remainder,
    820 			(*multiplier), (*divisor),
    821 			(((delta + (*remainder)) * ((int) (*multiplier)))
    822 			    / ((int) (*divisor))),
    823 			(((delta + (*remainder)) * ((int) (*multiplier)))
    824 			    % ((int) (*divisor)))));
    825 
    826 	if (sc->sc_knobs.motion_remainder)
    827 		delta += *remainder;
    828 	*remainder = 0;
    829 
    830 	if (((*multiplier) == 0) ||
    831 	    ((*multiplier) > UATP_MAX_MOTION_MULTIPLIER) ||
    832 	    ((*divisor) == 0))
    833 		return delta;
    834 
    835 	product = (delta * ((int) (*multiplier)));
    836 	*remainder = (product % ((int) (*divisor)));
    837 	return product / ((int) (*divisor));
    838 }
    839 
    840 static int
    841 uatp_scale_motion(const struct uatp_softc *sc, int delta, int *remainder)
    842 {
    843 	return scale_motion(sc, delta, remainder,
    844 	    &sc->sc_knobs.motion_multiplier,
    845 	    &sc->sc_knobs.motion_divisor);
    846 }
    847 
    848 static int
    849 uatp_scale_fast_motion(const struct uatp_softc *sc, int delta, int *remainder)
    850 {
    851 	return scale_motion(sc, delta, remainder,
    852 	    &sc->sc_knobs.fast_motion_multiplier,
    853 	    &sc->sc_knobs.fast_motion_divisor);
    854 }
    855 
    856 /* Driver goop */
    857 
    858 CFATTACH_DECL2_NEW(uatp, sizeof(struct uatp_softc), uatp_match, uatp_attach,
    859     uatp_detach, uatp_activate, NULL, uatp_childdet);
    860 
    861 static const struct wsmouse_accessops uatp_accessops = {
    862 	.enable = uatp_enable,
    863 	.disable = uatp_disable,
    864 	.ioctl = uatp_ioctl,
    865 };
    866 
    867 static int
    868 uatp_match(device_t parent, cfdata_t match, void *aux)
    869 {
    870 	const struct uhidev_attach_arg *uha = aux;
    871 	void *report_descriptor;
    872 	int report_size, input_size;
    873 	const struct uatp_descriptor *uatp_descriptor;
    874 
    875 	aprint_debug("%s: vendor 0x%04x, product 0x%04x\n", __func__,
    876 	    (unsigned int)uha->uiaa->uiaa_vendor,
    877 	    (unsigned int)uha->uiaa->uiaa_product);
    878 	aprint_debug("%s: class 0x%04x, subclass 0x%04x, proto 0x%04x\n",
    879 	    __func__,
    880 	    (unsigned int)uha->uiaa->uiaa_class,
    881 	    (unsigned int)uha->uiaa->uiaa_subclass,
    882 	    (unsigned int)uha->uiaa->uiaa_proto);
    883 
    884 	uhidev_get_report_desc(uha->parent, &report_descriptor, &report_size);
    885 	input_size = hid_report_size(report_descriptor, report_size,
    886 	    hid_input, uha->reportid);
    887 	aprint_debug("%s: reportid %d, input size %d\n", __func__,
    888 	    (int)uha->reportid, input_size);
    889 
    890 	/*
    891 	 * Keyboards, trackpads, and eject buttons share common vendor
    892 	 * and product ids, but not protocols: only the trackpad
    893 	 * reports a mouse protocol.
    894 	 */
    895 	if (uha->uiaa->uiaa_proto != UIPROTO_MOUSE)
    896 		return UMATCH_NONE;
    897 
    898 	/* Check for a known vendor/product id.  */
    899 	uatp_descriptor = find_uatp_descriptor(uha);
    900 	if (uatp_descriptor == NULL) {
    901 		aprint_debug("%s: unknown vendor/product id\n", __func__);
    902 		return UMATCH_NONE;
    903 	}
    904 
    905 	/* Check for the expected input size.  */
    906 	if ((input_size < 0) ||
    907 	    ((unsigned int)input_size !=
    908 		uatp_descriptor->parameters->input_size)) {
    909 		aprint_debug("%s: expected input size %u\n", __func__,
    910 		    uatp_descriptor->parameters->input_size);
    911 		return UMATCH_NONE;
    912 	}
    913 
    914 	return UMATCH_VENDOR_PRODUCT_CONF_IFACE;
    915 }
    916 
    917 static void
    918 uatp_attach(device_t parent, device_t self, void *aux)
    919 {
    920 	struct uatp_softc *sc = device_private(self);
    921 	const struct uhidev_attach_arg *uha = aux;
    922 	const struct uatp_descriptor *uatp_descriptor;
    923 	void *report_descriptor;
    924 	int report_size, input_size;
    925 	struct wsmousedev_attach_args a;
    926 
    927 	/* Set up uhidev state.  (Why doesn't uhidev do most of this?)  */
    928 	sc->sc_hdev.sc_dev = self;
    929 	sc->sc_hdev.sc_intr = uatp_intr;
    930 	sc->sc_hdev.sc_parent = uha->parent;
    931 	sc->sc_hdev.sc_report_id = uha->reportid;
    932 
    933 	/* Identify ourselves to dmesg.  */
    934 	uatp_descriptor = find_uatp_descriptor(uha);
    935 	KASSERT(uatp_descriptor != NULL);
    936 	aprint_normal(": %s\n", uatp_descriptor->description);
    937 	aprint_naive(": %s\n", uatp_descriptor->description);
    938 	aprint_verbose_dev(self,
    939 	    "vendor 0x%04x, product 0x%04x, report id %d\n",
    940 	    (unsigned int)uha->uiaa->uiaa_vendor,
    941 	    (unsigned int)uha->uiaa->uiaa_product,
    942 	    (int)uha->reportid);
    943 
    944 	uhidev_get_report_desc(uha->parent, &report_descriptor, &report_size);
    945 	input_size = hid_report_size(report_descriptor, report_size, hid_input,
    946 	    uha->reportid);
    947 	KASSERT(0 < input_size);
    948 	sc->sc_input_size = input_size;
    949 
    950 	/* Initialize model-specific parameters.  */
    951 	sc->sc_parameters = uatp_descriptor->parameters;
    952 	KASSERT((int)sc->sc_parameters->input_size == input_size);
    953 	KASSERT(sc->sc_parameters->x_sensors <= UATP_MAX_X_SENSORS);
    954 	KASSERT(sc->sc_parameters->x_ratio <= UATP_MAX_X_RATIO);
    955 	KASSERT(sc->sc_parameters->y_sensors <= UATP_MAX_Y_SENSORS);
    956 	KASSERT(sc->sc_parameters->y_ratio <= UATP_MAX_Y_RATIO);
    957 	aprint_verbose_dev(self,
    958 	    "%u x sensors, scaled by %u for %u points on screen\n",
    959 	    sc->sc_parameters->x_sensors, sc->sc_parameters->x_ratio,
    960 	    sc->sc_parameters->x_sensors * sc->sc_parameters->x_ratio);
    961 	aprint_verbose_dev(self,
    962 	    "%u y sensors, scaled by %u for %u points on screen\n",
    963 	    sc->sc_parameters->y_sensors, sc->sc_parameters->y_ratio,
    964 	    sc->sc_parameters->y_sensors * sc->sc_parameters->y_ratio);
    965 	if (sc->sc_parameters->initialize)
    966 		sc->sc_parameters->initialize(sc);
    967 
    968 	/* Register with pmf.  Nothing special for suspend/resume.  */
    969 	if (!pmf_device_register(self, NULL, NULL))
    970 		aprint_error_dev(self, "couldn't establish power handler\n");
    971 
    972 	/* Initialize knobs and create sysctl subtree to tweak them.  */
    973 	sc->sc_knobs = default_knobs;
    974 	uatp_setup_sysctl(sc);
    975 
    976 	/* Initialize tapping.  */
    977 	tap_initialize(sc);
    978 
    979 	/* Attach wsmouse.  */
    980 	a.accessops = &uatp_accessops;
    981 	a.accesscookie = sc;
    982 	sc->sc_wsmousedev = config_found_ia(self, "wsmousedev", &a,
    983 	    wsmousedevprint);
    984 }
    985 
    986 /* Sysctl setup */
    987 
    988 static void
    989 uatp_setup_sysctl(struct uatp_softc *sc)
    990 {
    991 	int error;
    992 
    993 	error = sysctl_createv(&sc->sc_log, 0, NULL, &sc->sc_node, 0,
    994 	    CTLTYPE_NODE, device_xname(uatp_dev(sc)),
    995 	    SYSCTL_DESCR("uatp configuration knobs"),
    996 	    NULL, 0, NULL, 0,
    997 	    CTL_HW, CTL_CREATE, CTL_EOL);
    998 	if (error != 0) {
    999 		aprint_error_dev(uatp_dev(sc),
   1000 		    "unable to set up sysctl tree hw.%s: %d\n",
   1001 		    device_xname(uatp_dev(sc)), error);
   1002 		goto err;
   1003 	}
   1004 
   1005 #if UATP_DEBUG
   1006 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_debug_flags, "debug",
   1007 		"uatp(4) debug flags"))
   1008 		goto err;
   1009 #endif
   1010 
   1011 	/*
   1012 	 * Button emulation.
   1013 	 */
   1014 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.two_finger_buttons,
   1015 		"two_finger_buttons",
   1016 		"buttons to emulate with two fingers on trackpad"))
   1017 		goto err;
   1018 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.three_finger_buttons,
   1019 		"three_finger_buttons",
   1020 		"buttons to emulate with three fingers on trackpad"))
   1021 		goto err;
   1022 
   1023 #if 0
   1024 	/*
   1025 	 * Edge scrolling.
   1026 	 */
   1027 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.top_edge, "top_edge",
   1028 		"width of top edge for edge scrolling"))
   1029 		goto err;
   1030 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.bottom_edge,
   1031 		"bottom_edge", "width of bottom edge for edge scrolling"))
   1032 		goto err;
   1033 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.left_edge, "left_edge",
   1034 		"width of left edge for edge scrolling"))
   1035 		goto err;
   1036 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.right_edge, "right_edge",
   1037 		"width of right edge for edge scrolling"))
   1038 		goto err;
   1039 #endif
   1040 
   1041 	/*
   1042 	 * Multifinger tracking.
   1043 	 */
   1044 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.multifinger_track,
   1045 		"multifinger_track",
   1046 		"0 to ignore multiple fingers, 1 to reset, 2 to scroll"))
   1047 		goto err;
   1048 
   1049 	/*
   1050 	 * Sensor parameters.
   1051 	 */
   1052 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.x_sensors, "x_sensors",
   1053 		"number of x sensors"))
   1054 		goto err;
   1055 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.x_ratio, "x_ratio",
   1056 		"screen width to trackpad width ratio"))
   1057 		goto err;
   1058 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.y_sensors, "y_sensors",
   1059 		"number of y sensors"))
   1060 		goto err;
   1061 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.y_ratio, "y_ratio",
   1062 		"screen height to trackpad height ratio"))
   1063 		goto err;
   1064 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.sensor_threshold,
   1065 		"sensor_threshold", "sensor threshold"))
   1066 		goto err;
   1067 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.sensor_normalizer,
   1068 		"sensor_normalizer", "sensor normalizer"))
   1069 		goto err;
   1070 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.palm_width,
   1071 		"palm_width", "lower bound on width/height of palm"))
   1072 		goto err;
   1073 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.old_raw_weight,
   1074 		"old_raw_weight", "weight of old raw position"))
   1075 		goto err;
   1076 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.old_smoothed_weight,
   1077 		"old_smoothed_weight", "weight of old smoothed position"))
   1078 		goto err;
   1079 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.new_raw_weight,
   1080 		"new_raw_weight", "weight of new raw position"))
   1081 		goto err;
   1082 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_remainder,
   1083 		"motion_remainder", "remember motion division remainder"))
   1084 		goto err;
   1085 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_threshold,
   1086 		"motion_threshold", "threshold before finger moves cursor"))
   1087 		goto err;
   1088 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_multiplier,
   1089 		"motion_multiplier", "numerator of motion scale"))
   1090 		goto err;
   1091 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_divisor,
   1092 		"motion_divisor", "divisor of motion scale"))
   1093 		goto err;
   1094 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_threshold,
   1095 		"fast_motion_threshold", "threshold before fast motion"))
   1096 		goto err;
   1097 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_multiplier,
   1098 		"fast_motion_multiplier", "numerator of fast motion scale"))
   1099 		goto err;
   1100 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_divisor,
   1101 		"fast_motion_divisor", "divisor of fast motion scale"))
   1102 		goto err;
   1103 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_per_direction,
   1104 		"fast_per_direction", "don't frobnitz the veeblefitzer!"))
   1105 		goto err;
   1106 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_delay,
   1107 		"motion_delay", "number of packets before motion kicks in"))
   1108 		goto err;
   1109 
   1110 	/*
   1111 	 * Tapping.
   1112 	 */
   1113 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.tap_limit_msec,
   1114 		"tap_limit_msec", "milliseconds before a touch is not a tap"))
   1115 		goto err;
   1116 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.double_tap_limit_msec,
   1117 		"double_tap_limit_msec",
   1118 		"milliseconds before a second tap keeps the button down"))
   1119 		goto err;
   1120 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.one_finger_tap_buttons,
   1121 		"one_finger_tap_buttons", "buttons for one-finger taps"))
   1122 		goto err;
   1123 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.two_finger_tap_buttons,
   1124 		"two_finger_tap_buttons", "buttons for two-finger taps"))
   1125 		goto err;
   1126 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.three_finger_tap_buttons,
   1127 		"three_finger_tap_buttons", "buttons for three-finger taps"))
   1128 		goto err;
   1129 	if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.tap_track_distance_limit,
   1130 		"tap_track_distance_limit",
   1131 		"maximum distance^2 of tracking during tap"))
   1132 		goto err;
   1133 
   1134 	return;
   1135 
   1136 err:
   1137 	sysctl_teardown(&sc->sc_log);
   1138 	sc->sc_node = NULL;
   1139 }
   1140 
   1141 static bool
   1142 uatp_setup_sysctl_knob(struct uatp_softc *sc, int *ptr, const char *name,
   1143     const char *description)
   1144 {
   1145 	int error;
   1146 
   1147 	error = sysctl_createv(&sc->sc_log, 0, NULL, NULL, CTLFLAG_READWRITE,
   1148 	    CTLTYPE_INT, name, SYSCTL_DESCR(description),
   1149 	    NULL, 0, ptr, 0,
   1150 	    CTL_HW, sc->sc_node->sysctl_num, CTL_CREATE, CTL_EOL);
   1151 	if (error != 0) {
   1152 		aprint_error_dev(uatp_dev(sc),
   1153 		    "unable to setup sysctl node hw.%s.%s: %d\n",
   1154 		    device_xname(uatp_dev(sc)), name, error);
   1155 		return false;
   1156 	}
   1157 
   1158 	return true;
   1159 }
   1160 
   1161 /* More driver goop */
   1162 
   1163 static void
   1164 uatp_childdet(device_t self, device_t child)
   1165 {
   1166 	struct uatp_softc *sc = device_private(self);
   1167 
   1168 	DPRINTF(sc, UATP_DEBUG_MISC, ("detaching child %s\n",
   1169 	    device_xname(child)));
   1170 
   1171 	/* Our only child is the wsmouse device.  */
   1172 	if (child == sc->sc_wsmousedev)
   1173 		sc->sc_wsmousedev = NULL;
   1174 }
   1175 
   1176 static int
   1177 uatp_detach(device_t self, int flags)
   1178 {
   1179 	struct uatp_softc *sc = device_private(self);
   1180 
   1181 	DPRINTF(sc, UATP_DEBUG_MISC, ("detaching with flags %d\n", flags));
   1182 
   1183         if (sc->sc_status & UATP_ENABLED) {
   1184 		aprint_error_dev(uatp_dev(sc), "can't detach while enabled\n");
   1185 		return EBUSY;
   1186         }
   1187 
   1188 	if (sc->sc_parameters->finalize) {
   1189 		int error = sc->sc_parameters->finalize(sc);
   1190 		if (error != 0)
   1191 			return error;
   1192 	}
   1193 
   1194 	pmf_device_deregister(self);
   1195 
   1196 	sysctl_teardown(&sc->sc_log);
   1197 	sc->sc_node = NULL;
   1198 
   1199 	tap_finalize(sc);
   1200 
   1201 	return config_detach_children(self, flags);
   1202 }
   1203 
   1204 static int
   1205 uatp_activate(device_t self, enum devact act)
   1206 {
   1207 	struct uatp_softc *sc = device_private(self);
   1208 
   1209 	DPRINTF(sc, UATP_DEBUG_MISC, ("act %d\n", (int)act));
   1210 
   1211 	if (act != DVACT_DEACTIVATE)
   1212 		return EOPNOTSUPP;
   1213 
   1214 	sc->sc_status |= UATP_DYING;
   1215 
   1216 	return 0;
   1217 }
   1218 
   1219 /* wsmouse routines */
   1220 
   1221 static int
   1222 uatp_enable(void *v)
   1223 {
   1224 	struct uatp_softc *sc = v;
   1225 
   1226 	DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("enabling wsmouse\n"));
   1227 
   1228 	/* Refuse to enable if we've been deactivated.  */
   1229 	if (sc->sc_status & UATP_DYING) {
   1230 		DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("busy dying\n"));
   1231 		return EIO;
   1232 	}
   1233 
   1234 	/* Refuse to enable if we already are enabled.  */
   1235 	if (sc->sc_status & UATP_ENABLED) {
   1236 		DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("already enabled\n"));
   1237 		return EBUSY;
   1238 	}
   1239 
   1240 	sc->sc_status |= UATP_ENABLED;
   1241 	sc->sc_status &=~ UATP_VALID;
   1242 	sc->sc_input_index = 0;
   1243 	tap_enable(sc);
   1244 	uatp_clear_position(sc);
   1245 
   1246 	DPRINTF(sc, UATP_DEBUG_MISC, ("uhidev_open(%p)\n", &sc->sc_hdev));
   1247 	return uhidev_open(&sc->sc_hdev);
   1248 }
   1249 
   1250 static void
   1251 uatp_disable(void *v)
   1252 {
   1253 	struct uatp_softc *sc = v;
   1254 
   1255 	DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("disabling wsmouse\n"));
   1256 
   1257 	if (!(sc->sc_status & UATP_ENABLED)) {
   1258 		DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("not enabled\n"));
   1259 		return;
   1260 	}
   1261 
   1262 	tap_disable(sc);
   1263 	sc->sc_status &=~ UATP_ENABLED;
   1264 
   1265 	DPRINTF(sc, UATP_DEBUG_MISC, ("uhidev_close(%p)\n", &sc->sc_hdev));
   1266 	uhidev_close(&sc->sc_hdev);
   1267 }
   1268 
   1269 static int
   1270 uatp_ioctl(void *v, unsigned long cmd, void *data, int flag, struct lwp *p)
   1271 {
   1272 
   1273 	DPRINTF((struct uatp_softc*)v, UATP_DEBUG_IOCTL,
   1274 	    ("cmd %lx, data %p, flag %x, lwp %p\n", cmd, data, flag, p));
   1275 
   1276 	/* XXX Implement any relevant wsmouse(4) ioctls.  */
   1277 	return EPASSTHROUGH;
   1278 }
   1279 
   1280 /*
   1281  * The Geyser 3 and 4 models talk the generic USB HID mouse protocol by
   1282  * default.  This mode switch makes them give raw sensor data instead
   1283  * so that we can implement tapping, two-finger scrolling, &c.
   1284  */
   1285 
   1286 #define GEYSER34_RAW_MODE		0x04
   1287 #define GEYSER34_MODE_REPORT_ID		0
   1288 #define GEYSER34_MODE_INTERFACE		0
   1289 #define GEYSER34_MODE_PACKET_SIZE	8
   1290 
   1291 static void
   1292 geyser34_enable_raw_mode(struct uatp_softc *sc)
   1293 {
   1294 	struct usbd_device *udev = sc->sc_hdev.sc_parent->sc_udev;
   1295 	usb_device_request_t req;
   1296 	usbd_status status;
   1297 	uint8_t report[GEYSER34_MODE_PACKET_SIZE];
   1298 
   1299 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
   1300 	req.bRequest = UR_GET_REPORT;
   1301 	USETW2(req.wValue, UHID_FEATURE_REPORT, GEYSER34_MODE_REPORT_ID);
   1302 	USETW(req.wIndex, GEYSER34_MODE_INTERFACE);
   1303 	USETW(req.wLength, GEYSER34_MODE_PACKET_SIZE);
   1304 
   1305 	DPRINTF(sc, UATP_DEBUG_RESET, ("get feature report\n"));
   1306 	status = usbd_do_request(udev, &req, report);
   1307 	if (status != USBD_NORMAL_COMPLETION) {
   1308 		aprint_error_dev(uatp_dev(sc),
   1309 		    "error reading feature report: %s\n", usbd_errstr(status));
   1310 		return;
   1311 	}
   1312 
   1313 #if UATP_DEBUG
   1314 	if (sc->sc_debug_flags & UATP_DEBUG_RESET) {
   1315 		unsigned int i;
   1316 		DPRINTF(sc, UATP_DEBUG_RESET, ("old feature report:"));
   1317 		for (i = 0; i < GEYSER34_MODE_PACKET_SIZE; i++)
   1318 			printf(" %02x", (unsigned int)report[i]);
   1319 		printf("\n");
   1320 		/* Doing this twice is harmless here and lets this be
   1321 		 * one ifdef.  */
   1322 		report[0] = GEYSER34_RAW_MODE;
   1323 		DPRINTF(sc, UATP_DEBUG_RESET, ("new feature report:"));
   1324 		for (i = 0; i < GEYSER34_MODE_PACKET_SIZE; i++)
   1325 			printf(" %02x", (unsigned int)report[i]);
   1326 		printf("\n");
   1327 	}
   1328 #endif
   1329 
   1330 	report[0] = GEYSER34_RAW_MODE;
   1331 
   1332 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
   1333 	req.bRequest = UR_SET_REPORT;
   1334 	USETW2(req.wValue, UHID_FEATURE_REPORT, GEYSER34_MODE_REPORT_ID);
   1335 	USETW(req.wIndex, GEYSER34_MODE_INTERFACE);
   1336 	USETW(req.wLength, GEYSER34_MODE_PACKET_SIZE);
   1337 
   1338 	DPRINTF(sc, UATP_DEBUG_RESET, ("set feature report\n"));
   1339 	status = usbd_do_request(udev, &req, report);
   1340 	if (status != USBD_NORMAL_COMPLETION) {
   1341 		aprint_error_dev(uatp_dev(sc),
   1342 		    "error writing feature report: %s\n", usbd_errstr(status));
   1343 		return;
   1344 	}
   1345 }
   1346 
   1347 /*
   1348  * The Geyser 3 and 4 need to be reset periodically after we detect a
   1349  * continual flow of spurious interrupts.  We use a USB task for this.
   1350  */
   1351 
   1352 static void
   1353 geyser34_initialize(struct uatp_softc *sc)
   1354 {
   1355 
   1356 	DPRINTF(sc, UATP_DEBUG_MISC, ("initializing\n"));
   1357 	geyser34_enable_raw_mode(sc);
   1358 	usb_init_task(&sc->sc_reset_task, &geyser34_reset_task, sc, 0);
   1359 }
   1360 
   1361 static int
   1362 geyser34_finalize(struct uatp_softc *sc)
   1363 {
   1364 
   1365 	DPRINTF(sc, UATP_DEBUG_MISC, ("finalizing\n"));
   1366 	usb_rem_task_wait(sc->sc_hdev.sc_parent->sc_udev, &sc->sc_reset_task,
   1367 	    USB_TASKQ_DRIVER, NULL);
   1368 
   1369 	return 0;
   1370 }
   1371 
   1372 static void
   1373 geyser34_deferred_reset(struct uatp_softc *sc)
   1374 {
   1375 
   1376 	DPRINTF(sc, UATP_DEBUG_RESET, ("deferring reset\n"));
   1377 	usb_add_task(sc->sc_hdev.sc_parent->sc_udev, &sc->sc_reset_task,
   1378 	    USB_TASKQ_DRIVER);
   1379 }
   1380 
   1381 static void
   1382 geyser34_reset_task(void *arg)
   1383 {
   1384 	struct uatp_softc *sc = arg;
   1385 
   1386 	DPRINTF(sc, UATP_DEBUG_RESET, ("resetting\n"));
   1387 
   1388 	/* Reset by putting it into raw mode.  Not sure why.  */
   1389 	geyser34_enable_raw_mode(sc);
   1390 }
   1391 
   1392 /* Interrupt handler */
   1393 
   1394 static void
   1395 uatp_intr(struct uhidev *addr, void *ibuf, unsigned int len)
   1396 {
   1397 	struct uatp_softc *sc = (struct uatp_softc *)addr;
   1398 	uint8_t *input;
   1399 	int dx, dy, dz, dw;
   1400 	uint32_t buttons;
   1401 
   1402 	DPRINTF(sc, UATP_DEBUG_INTR, ("softc %p, ibuf %p, len %u\n",
   1403 	    addr, ibuf, len));
   1404 
   1405 	/*
   1406 	 * Some devices break packets up into chunks, so we accumulate
   1407 	 * input up to the expected packet length, or if it would
   1408 	 * overflow, discard the whole packet and start over.
   1409 	 */
   1410 	if (sc->sc_input_size < len) {
   1411 		aprint_error_dev(uatp_dev(sc),
   1412 		    "discarding %u-byte input packet\n", len);
   1413 		sc->sc_input_index = 0;
   1414 		return;
   1415 	} else if (sc->sc_input_size < (sc->sc_input_index + len)) {
   1416 		aprint_error_dev(uatp_dev(sc), "discarding %u-byte input\n",
   1417 		    (sc->sc_input_index + len));
   1418 		sc->sc_input_index = 0;
   1419 		return;
   1420 	}
   1421 
   1422 #if UATP_DEBUG
   1423 	if (sc->sc_debug_flags & UATP_DEBUG_INTR) {
   1424 		unsigned int i;
   1425 		uint8_t *bytes = ibuf;
   1426 		DPRINTF(sc, UATP_DEBUG_INTR, ("raw"));
   1427 		for (i = 0; i < len; i++)
   1428 			printf(" %02x", (unsigned int)bytes[i]);
   1429 		printf("\n");
   1430 	}
   1431 #endif
   1432 
   1433 	memcpy(&sc->sc_input[sc->sc_input_index], ibuf, len);
   1434 	sc->sc_input_index += len;
   1435 	if (sc->sc_input_index != sc->sc_input_size) {
   1436 		/* Wait until packet is complete.  */
   1437 		aprint_verbose_dev(uatp_dev(sc), "partial packet: %u bytes\n",
   1438 		    len);
   1439 		return;
   1440 	}
   1441 
   1442 	/* Clear the buffer and process the now complete packet.  */
   1443 	sc->sc_input_index = 0;
   1444 	input = sc->sc_input;
   1445 
   1446 	/* The last byte's first bit is set iff the button is pressed.
   1447 	 * XXX Left button should have a name.  */
   1448 	buttons = ((input[sc->sc_input_size - 1] & UATP_STATUS_BUTTON)
   1449 	    ? 1 : 0);
   1450 
   1451 	/* Read the sample.  */
   1452 	memset(uatp_x_sample(sc), 0, UATP_MAX_X_SENSORS);
   1453 	memset(uatp_y_sample(sc), 0, UATP_MAX_Y_SENSORS);
   1454 	sc->sc_parameters->read_sample(uatp_x_sample(sc), uatp_y_sample(sc),
   1455 	    input);
   1456 
   1457 #if UATP_DEBUG
   1458 	if (sc->sc_debug_flags & UATP_DEBUG_INTR) {
   1459 		unsigned int i;
   1460 		DPRINTF(sc, UATP_DEBUG_INTR, ("x sensors"));
   1461 		for (i = 0; i < uatp_x_sensors(sc); i++)
   1462 			printf(" %02x", (unsigned int)uatp_x_sample(sc)[i]);
   1463 		printf("\n");
   1464 		DPRINTF(sc, UATP_DEBUG_INTR, ("y sensors"));
   1465 		for (i = 0; i < uatp_y_sensors(sc); i++)
   1466 			printf(" %02x", (unsigned int)uatp_y_sample(sc)[i]);
   1467 		printf("\n");
   1468 	} else if ((sc->sc_debug_flags & UATP_DEBUG_STATUS) &&
   1469 		(input[sc->sc_input_size - 1] &~
   1470 		    (UATP_STATUS_BUTTON | UATP_STATUS_BASE |
   1471 			UATP_STATUS_POST_RESET)))
   1472 		DPRINTF(sc, UATP_DEBUG_STATUS, ("status byte: %02x\n",
   1473 		    input[sc->sc_input_size - 1]));
   1474 #endif
   1475 
   1476 	/*
   1477 	 * If this is a base sample, initialize the state to interpret
   1478 	 * subsequent samples relative to it, and stop here.
   1479 	 */
   1480 	if (sc->sc_parameters->base_sample(sc, input)) {
   1481 		DPRINTF(sc, UATP_DEBUG_PARSE,
   1482 		    ("base sample, buttons %"PRIx32"\n", buttons));
   1483 		/* XXX Should the valid bit ever be reset?  */
   1484 		sc->sc_status |= UATP_VALID;
   1485 		uatp_clear_position(sc);
   1486 		memcpy(sc->sc_base, sc->sc_sample, sizeof(sc->sc_base));
   1487 		/* XXX Perform 17" size detection like Linux?  */
   1488 		return;
   1489 	}
   1490 
   1491 	/* If not, accumulate the change in the sensors.  */
   1492 	sc->sc_parameters->accumulate(sc);
   1493 
   1494 #if UATP_DEBUG
   1495 	if (sc->sc_debug_flags & UATP_DEBUG_ACCUMULATE) {
   1496 		unsigned int i;
   1497 		DPRINTF(sc, UATP_DEBUG_ACCUMULATE, ("accumulated x state:"));
   1498 		for (i = 0; i < uatp_x_sensors(sc); i++)
   1499 			printf(" %02x", (unsigned int)uatp_x_acc(sc)[i]);
   1500 		printf("\n");
   1501 		DPRINTF(sc, UATP_DEBUG_ACCUMULATE, ("accumulated y state:"));
   1502 		for (i = 0; i < uatp_y_sensors(sc); i++)
   1503 			printf(" %02x", (unsigned int)uatp_y_acc(sc)[i]);
   1504 		printf("\n");
   1505 	}
   1506 #endif
   1507 
   1508 	/* Compute the change in coordinates and buttons.  */
   1509 	dx = dy = dz = dw = 0;
   1510 	if ((!interpret_input(sc, &dx, &dy, &dz, &dw, &buttons)) &&
   1511 	    /* If there's no input because we're releasing a button,
   1512 	     * then it's not spurious.  XXX Mutex?  */
   1513 	    (sc->sc_buttons == 0)) {
   1514 		DPRINTF(sc, UATP_DEBUG_SPURINTR, ("spurious interrupt\n"));
   1515 		if (sc->sc_parameters->reset)
   1516 			sc->sc_parameters->reset(sc);
   1517 		return;
   1518 	}
   1519 
   1520 	/* Report to wsmouse.  */
   1521 	DPRINTF(sc, UATP_DEBUG_INTR,
   1522 	    ("buttons %"PRIx32", dx %d, dy %d, dz %d, dw %d\n",
   1523 		buttons, dx, dy, dz, dw));
   1524 	mutex_enter(&sc->sc_tap_mutex);
   1525 	uatp_input(sc, buttons, dx, dy, dz, dw);
   1526 	mutex_exit(&sc->sc_tap_mutex);
   1527 }
   1528 
   1529 /*
   1530  * Different ways to discern the base sample initializing the state.
   1531  * `base_sample_softc_flag' uses a state flag stored in the softc;
   1532  * `base_sample_input_flag' checks a flag at the end of the input
   1533  * packet.
   1534  */
   1535 
   1536 static bool
   1537 base_sample_softc_flag(const struct uatp_softc *sc, const uint8_t *input)
   1538 {
   1539 	return !(sc->sc_status & UATP_VALID);
   1540 }
   1541 
   1542 static bool
   1543 base_sample_input_flag(const struct uatp_softc *sc, const uint8_t *input)
   1544 {
   1545 	/* XXX Should we also check the valid flag?  */
   1546 	return !!(input[sc->sc_input_size - 1] & UATP_STATUS_BASE);
   1547 }
   1548 
   1549 /*
   1550  * Pick apart the horizontal sensors from the vertical sensors.
   1551  * Different models interleave them in different orders.
   1552  */
   1553 
   1554 static void
   1555 read_sample_1(uint8_t *x, uint8_t *y, const uint8_t *input)
   1556 {
   1557 	unsigned int i;
   1558 
   1559 	for (i = 0; i < 8; i++) {
   1560 		x[i] = input[5 * i + 2];
   1561 		x[i + 8] = input[5 * i + 4];
   1562 		x[i + 16] = input[5 * i + 42];
   1563 		if (i < 2)
   1564 			x[i + 24] = input[5 * i + 44];
   1565 
   1566 		y[i] = input[5 * i + 1];
   1567 		y[i + 8] = input[5 * i + 3];
   1568 	}
   1569 }
   1570 
   1571 static void
   1572 read_sample_2(uint8_t *x, uint8_t *y, const uint8_t *input)
   1573 {
   1574 	unsigned int i, j;
   1575 
   1576 	for (i = 0, j = 19; i < 20; i += 2, j += 3) {
   1577 		x[i] = input[j];
   1578 		x[i + 1] = input[j + 1];
   1579 	}
   1580 
   1581 	for (i = 0, j = 1; i < 9; i += 2, j += 3) {
   1582 		y[i] = input[j];
   1583 		y[i + 1] = input[j + 1];
   1584 	}
   1585 }
   1586 
   1587 static void
   1588 accumulate_sample_1(struct uatp_softc *sc)
   1589 {
   1590 	unsigned int i;
   1591 
   1592 	for (i = 0; i < UATP_SENSORS; i++) {
   1593 		sc->sc_acc[i] += (int8_t)(sc->sc_sample[i] - sc->sc_base[i]);
   1594 		if (sc->sc_acc[i] < 0) {
   1595 			sc->sc_acc[i] = 0;
   1596 		} else if (UATP_MAX_ACC < sc->sc_acc[i]) {
   1597 			DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
   1598 			    ("overflow %d\n", sc->sc_acc[i]));
   1599 			sc->sc_acc[i] = UATP_MAX_ACC;
   1600 		}
   1601 	}
   1602 
   1603 	memcpy(sc->sc_base, sc->sc_sample, sizeof(sc->sc_base));
   1604 }
   1605 
   1606 static void
   1607 accumulate_sample_2(struct uatp_softc *sc)
   1608 {
   1609 	unsigned int i;
   1610 
   1611 	for (i = 0; i < UATP_SENSORS; i++) {
   1612 		sc->sc_acc[i] = (int8_t)(sc->sc_sample[i] - sc->sc_base[i]);
   1613 		if (sc->sc_acc[i] < -0x80) {
   1614 			DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
   1615 			    ("underflow %u - %u = %d\n",
   1616 				(unsigned int)sc->sc_sample[i],
   1617 				(unsigned int)sc->sc_base[i],
   1618 				sc->sc_acc[i]));
   1619 			sc->sc_acc[i] += 0x100;
   1620 		}
   1621 		if (0x7f < sc->sc_acc[i]) {
   1622 			DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
   1623 			    ("overflow %u - %u = %d\n",
   1624 				(unsigned int)sc->sc_sample[i],
   1625 				(unsigned int)sc->sc_base[i],
   1626 				sc->sc_acc[i]));
   1627 			sc->sc_acc[i] -= 0x100;
   1628 		}
   1629 		if (sc->sc_acc[i] < 0)
   1630 			sc->sc_acc[i] = 0;
   1631 	}
   1632 }
   1633 
   1634 /*
   1635  * Report input to wsmouse, if there is anything interesting to report.
   1636  * We must take into consideration the current tap-and-drag button
   1637  * state.
   1638  */
   1639 
   1640 static void
   1641 uatp_input(struct uatp_softc *sc, uint32_t buttons,
   1642     int dx, int dy, int dz, int dw)
   1643 {
   1644 	uint32_t all_buttons;
   1645 
   1646 	KASSERT(mutex_owned(&sc->sc_tap_mutex));
   1647 	all_buttons = buttons | uatp_tapped_buttons(sc);
   1648 
   1649 	if ((sc->sc_wsmousedev != NULL) &&
   1650 	    ((dx != 0) || (dy != 0) || (dz != 0) || (dw != 0) ||
   1651 		(all_buttons != sc->sc_all_buttons))) {
   1652 		int s = spltty();
   1653 		DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("wsmouse input:"
   1654 		    " buttons %"PRIx32", dx %d, dy %d, dz %d, dw %d\n",
   1655 		    all_buttons, dx, -dy, dz, -dw));
   1656 		wsmouse_input(sc->sc_wsmousedev, all_buttons, dx, -dy, dz, -dw,
   1657 		    WSMOUSE_INPUT_DELTA);
   1658 		splx(s);
   1659 	}
   1660 	sc->sc_buttons = buttons;
   1661 	sc->sc_all_buttons = all_buttons;
   1662 }
   1663 
   1664 /*
   1665  * Interpret the current tap state to decide whether the tap buttons
   1666  * are currently pressed.
   1667  */
   1668 
   1669 static uint32_t
   1670 uatp_tapped_buttons(struct uatp_softc *sc)
   1671 {
   1672 	KASSERT(mutex_owned(&sc->sc_tap_mutex));
   1673 	switch (sc->sc_tap_state) {
   1674 	case TAP_STATE_INITIAL:
   1675 	case TAP_STATE_TAPPING:
   1676 		return 0;
   1677 
   1678 	case TAP_STATE_TAPPED:
   1679 	case TAP_STATE_DOUBLE_TAPPING:
   1680 	case TAP_STATE_DRAGGING_DOWN:
   1681 	case TAP_STATE_DRAGGING_UP:
   1682 	case TAP_STATE_TAPPING_IN_DRAG:
   1683 		CHECK((0 < sc->sc_tapped_fingers), return 0);
   1684 		switch (sc->sc_tapped_fingers) {
   1685 		case 1: return sc->sc_knobs.one_finger_tap_buttons;
   1686 		case 2: return sc->sc_knobs.two_finger_tap_buttons;
   1687 		case 3:
   1688 		default: return sc->sc_knobs.three_finger_tap_buttons;
   1689 		}
   1690 
   1691 	default:
   1692 		aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
   1693 		    __func__, sc->sc_tap_state);
   1694 		return 0;
   1695 	}
   1696 }
   1697 
   1698 /*
   1699  * Interpret the current input state to find a difference in all the
   1700  * relevant coordinates and buttons to pass on to wsmouse, and update
   1701  * any internal driver state necessary to interpret subsequent input
   1702  * relative to this one.
   1703  */
   1704 
   1705 static bool
   1706 interpret_input(struct uatp_softc *sc, int *dx, int *dy, int *dz, int *dw,
   1707     uint32_t *buttons)
   1708 {
   1709 	unsigned int x_pressure, x_raw, x_fingers;
   1710 	unsigned int y_pressure, y_raw, y_fingers;
   1711 	unsigned int fingers;
   1712 
   1713 	x_pressure = interpret_dimension(sc, uatp_x_acc(sc),
   1714 	    uatp_x_sensors(sc), uatp_x_ratio(sc), &x_raw, &x_fingers);
   1715 	y_pressure = interpret_dimension(sc, uatp_y_acc(sc),
   1716 	    uatp_y_sensors(sc), uatp_y_ratio(sc), &y_raw, &y_fingers);
   1717 
   1718 	DPRINTF(sc, UATP_DEBUG_PARSE,
   1719 	    ("x %u @ %u, %uf; y %u @ %u, %uf; buttons %"PRIx32"\n",
   1720 		x_pressure, x_raw, x_fingers,
   1721 		y_pressure, y_raw, y_fingers,
   1722 		*buttons));
   1723 
   1724 	if ((x_pressure == 0) && (y_pressure == 0)) {
   1725 		bool ok;
   1726 		/* No fingers: clear position and maybe report a tap.  */
   1727 		DPRINTF(sc, UATP_DEBUG_INTR,
   1728 		    ("no position detected; clearing position\n"));
   1729 		if (*buttons == 0) {
   1730 			ok = tap_released(sc);
   1731 		} else {
   1732 			tap_reset(sc);
   1733 			/* Button pressed: interrupt is not spurious.  */
   1734 			ok = true;
   1735 		}
   1736 		/*
   1737 		 * Don't clear the position until after tap_released,
   1738 		 * which needs to know the track distance.
   1739 		 */
   1740 		uatp_clear_position(sc);
   1741 		return ok;
   1742 	} else if ((x_pressure == 0) || (y_pressure == 0)) {
   1743 		/* XXX What to do here?  */
   1744 		DPRINTF(sc, UATP_DEBUG_INTR,
   1745 		    ("pressure in only one dimension; ignoring\n"));
   1746 		return true;
   1747 	} else if ((x_pressure == 1) && (y_pressure == 1)) {
   1748 		fingers = max(x_fingers, y_fingers);
   1749 		CHECK((0 < fingers), return false);
   1750 		if (*buttons == 0)
   1751 			tap_touched(sc, fingers);
   1752 		else if (fingers == 1)
   1753 			tap_reset(sc);
   1754 		else		/* Multiple fingers, button pressed.  */
   1755 			*buttons = emulated_buttons(sc, fingers);
   1756 		update_position(sc, fingers, x_raw, y_raw, dx, dy, dz, dw);
   1757 		return true;
   1758 	} else {
   1759 		/* Palm detected in either or both of the dimensions.  */
   1760 		DPRINTF(sc, UATP_DEBUG_INTR, ("palm detected; ignoring\n"));
   1761 		return true;
   1762 	}
   1763 }
   1764 
   1765 /*
   1766  * Interpret the accumulated sensor state along one dimension to find
   1767  * the number, mean position, and pressure of fingers.  Returns 0 to
   1768  * indicate no pressure, returns 1 and sets *position and *fingers to
   1769  * indicate fingers, and returns 2 to indicate palm.
   1770  *
   1771  * XXX Give symbolic names to the return values.
   1772  */
   1773 
   1774 static unsigned int
   1775 interpret_dimension(struct uatp_softc *sc, const int *acc,
   1776     unsigned int n_sensors, unsigned int ratio,
   1777     unsigned int *position, unsigned int *fingers)
   1778 {
   1779 	unsigned int i, v, n_fingers, sum;
   1780 	unsigned int total[UATP_MAX_SENSORS];
   1781 	unsigned int weighted[UATP_MAX_SENSORS];
   1782 	unsigned int sensor_threshold = sc->sc_knobs.sensor_threshold;
   1783 	unsigned int sensor_normalizer = sc->sc_knobs.sensor_normalizer;
   1784 	unsigned int width = 0;	/* GCC is not smart enough.  */
   1785 	unsigned int palm_width = sc->sc_knobs.palm_width;
   1786 	enum { none, nondecreasing, decreasing } state = none;
   1787 
   1788 	if (sensor_threshold < sensor_normalizer)
   1789 		sensor_normalizer = sensor_threshold;
   1790 	if (palm_width == 0)	/* Effectively disable palm detection.  */
   1791 		palm_width = UATP_MAX_POSITION;
   1792 
   1793 #define CHECK_(condition) CHECK(condition, return 0)
   1794 
   1795 	/*
   1796 	 * Arithmetic bounds:
   1797 	 * . n_sensors is at most UATP_MAX_SENSORS,
   1798 	 * . n_fingers is at most UATP_MAX_SENSORS,
   1799 	 * . i is at most UATP_MAX_SENSORS,
   1800 	 * . sc->sc_acc[i] is at most UATP_MAX_ACC,
   1801 	 * . i * sc->sc_acc[i] is at most UATP_MAX_SENSORS * UATP_MAX_ACC,
   1802 	 * . each total[j] is at most UATP_MAX_SENSORS * UATP_MAX_ACC,
   1803 	 * . each weighted[j] is at most UATP_MAX_SENSORS^2 * UATP_MAX_ACC,
   1804 	 * . ratio is at most UATP_MAX_RATIO,
   1805 	 * . each weighted[j] * ratio is at most
   1806 	 *     UATP_MAX_SENSORS^2 * UATP_MAX_ACC * UATP_MAX_RATIO,
   1807 	 *   which is #x5fa0000 with the current values of the constants,
   1808 	 *   and
   1809 	 * . the sum of the positions is at most
   1810 	 *     UATP_MAX_SENSORS * UATP_MAX_POSITION,
   1811 	 *   which is #x60000 with the current values of the constants.
   1812 	 * Hence all of the arithmetic here fits in int (and thus also
   1813 	 * unsigned int).  If you change the constants, though, you
   1814 	 * must update the analysis.
   1815 	 */
   1816 	__CTASSERT(0x5fa0000 == (UATP_MAX_SENSORS * UATP_MAX_SENSORS *
   1817 		UATP_MAX_ACC * UATP_MAX_RATIO));
   1818 	__CTASSERT(0x60000 == (UATP_MAX_SENSORS * UATP_MAX_POSITION));
   1819 	CHECK_(n_sensors <= UATP_MAX_SENSORS);
   1820 	CHECK_(ratio <= UATP_MAX_RATIO);
   1821 
   1822 	/*
   1823 	 * Detect each finger by looking for a consecutive sequence of
   1824 	 * increasing and then decreasing pressures above the sensor
   1825 	 * threshold.  Compute the finger's position as the weighted
   1826 	 * average of positions, weighted by the pressure at that
   1827 	 * position.  Finally, return the average finger position.
   1828 	 */
   1829 
   1830 	n_fingers = 0;
   1831 	memset(weighted, 0, sizeof(weighted));
   1832 	memset(total, 0, sizeof(total));
   1833 
   1834 	for (i = 0; i < n_sensors; i++) {
   1835 		CHECK_(0 <= acc[i]);
   1836 		v = acc[i];
   1837 
   1838 		/* Ignore values outside a sensible interval.  */
   1839 		if (v <= sensor_threshold) {
   1840 			state = none;
   1841 			continue;
   1842 		} else if (UATP_MAX_ACC < v) {
   1843 			aprint_verbose_dev(uatp_dev(sc),
   1844 			    "ignoring large accumulated sensor state: %u\n",
   1845 			    v);
   1846 			continue;
   1847 		}
   1848 
   1849 		switch (state) {
   1850 		case none:
   1851 			n_fingers += 1;
   1852 			CHECK_(n_fingers <= n_sensors);
   1853 			state = nondecreasing;
   1854 			width = 1;
   1855 			break;
   1856 
   1857 		case nondecreasing:
   1858 		case decreasing:
   1859 			CHECK_(0 < i);
   1860 			CHECK_(0 <= acc[i - 1]);
   1861 			width += 1;
   1862 			if (palm_width <= (width * ratio)) {
   1863 				DPRINTF(sc, UATP_DEBUG_PALM,
   1864 				    ("palm detected\n"));
   1865 				return 2;
   1866 			} else if ((state == nondecreasing) &&
   1867 			    ((unsigned int)acc[i - 1] > v)) {
   1868 				state = decreasing;
   1869 			} else if ((state == decreasing) &&
   1870 			    ((unsigned int)acc[i - 1] < v)) {
   1871 				n_fingers += 1;
   1872 				CHECK_(n_fingers <= n_sensors);
   1873 				state = nondecreasing;
   1874 				width = 1;
   1875 			}
   1876 			break;
   1877 
   1878 		default:
   1879 			aprint_error_dev(uatp_dev(sc),
   1880 			    "bad finger detection state: %d", state);
   1881 			return 0;
   1882 		}
   1883 
   1884 		v -= sensor_normalizer;
   1885 		total[n_fingers - 1] += v;
   1886 		weighted[n_fingers - 1] += (i * v);
   1887 		CHECK_(total[n_fingers - 1] <=
   1888 		    (UATP_MAX_SENSORS * UATP_MAX_ACC));
   1889 		CHECK_(weighted[n_fingers - 1] <=
   1890 		    (UATP_MAX_SENSORS * UATP_MAX_SENSORS * UATP_MAX_ACC));
   1891 	}
   1892 
   1893 	if (n_fingers == 0)
   1894 		return 0;
   1895 
   1896 	sum = 0;
   1897 	for (i = 0; i < n_fingers; i++) {
   1898 		DPRINTF(sc, UATP_DEBUG_PARSE,
   1899 		    ("finger at %u\n", ((weighted[i] * ratio) / total[i])));
   1900 		sum += ((weighted[i] * ratio) / total[i]);
   1901 		CHECK_(sum <= UATP_MAX_SENSORS * UATP_MAX_POSITION);
   1902 	}
   1903 
   1904 	*fingers = n_fingers;
   1905 	*position = (sum / n_fingers);
   1906 	return 1;
   1907 
   1908 #undef CHECK_
   1909 }
   1910 
   1911 /* Tapping */
   1912 
   1913 /*
   1914  * There is a very hairy state machine for detecting taps.  At every
   1915  * touch, we record the maximum number of fingers touched, and don't
   1916  * reset it to zero until the finger is released.
   1917  *
   1918  * INITIAL STATE
   1919  * (no tapping fingers; no tapped fingers)
   1920  * - On touch, go to TAPPING STATE.
   1921  * - On any other input, remain in INITIAL STATE.
   1922  *
   1923  * TAPPING STATE: Finger touched; might be tap.
   1924  * (tapping fingers; no tapped fingers)
   1925  * - On release within the tap limit, go to TAPPED STATE.
   1926  * - On release after the tap limit, go to INITIAL STATE.
   1927  * - On any other input, remain in TAPPING STATE.
   1928  *
   1929  * TAPPED STATE: Finger recently tapped, and might double-tap.
   1930  * (no tapping fingers; tapped fingers)
   1931  * - On touch within the double-tap limit, go to DOUBLE-TAPPING STATE.
   1932  * - On touch after the double-tap limit, go to TAPPING STATE.
   1933  * - On no event after the double-tap limit, go to INITIAL STATE.
   1934  * - On any other input, remain in TAPPED STATE.
   1935  *
   1936  * DOUBLE-TAPPING STATE: Finger touched soon after tap; might be double-tap.
   1937  * (tapping fingers; tapped fingers)
   1938  * - On release within the tap limit, release button and go to TAPPED STATE.
   1939  * - On release after the tap limit, go to DRAGGING UP STATE.
   1940  * - On touch after the tap limit, go to DRAGGING DOWN STATE.
   1941  * - On any other input, remain in DOUBLE-TAPPING STATE.
   1942  *
   1943  * DRAGGING DOWN STATE: Finger has double-tapped and is dragging, not tapping.
   1944  * (no tapping fingers; tapped fingers)
   1945  * - On release, go to DRAGGING UP STATE.
   1946  * - On any other input, remain in DRAGGING DOWN STATE.
   1947  *
   1948  * DRAGGING UP STATE: Finger has double-tapped and is up.
   1949  * (no tapping fingers; tapped fingers)
   1950  * - On touch, go to TAPPING IN DRAG STATE.
   1951  * - On any other input, remain in DRAGGING UP STATE.
   1952  *
   1953  * TAPPING IN DRAG STATE: Tap-dancing while cross-dressed.
   1954  * (tapping fingers; tapped fingers)
   1955  * - On release within the tap limit, go to TAPPED STATE.
   1956  * - On release after the tap limit, go to DRAGGING UP STATE.
   1957  * - On any other input, remain in TAPPING IN DRAG STATE.
   1958  *
   1959  * Warning:  The graph of states is split into two components, those
   1960  * with tapped fingers and those without.  The only path from any state
   1961  * without tapped fingers to a state with tapped fingers must pass
   1962  * through TAPPED STATE.  Also, the only transitions into TAPPED STATE
   1963  * must be from states with tapping fingers, which become the tapped
   1964  * fingers.  If you edit the state machine, you must either preserve
   1965  * these properties, or globally transform the state machine to avoid
   1966  * the bad consequences of violating these properties.
   1967  */
   1968 
   1969 static void
   1970 uatp_tap_limit(const struct uatp_softc *sc, struct timeval *limit)
   1971 {
   1972 	unsigned int msec = sc->sc_knobs.tap_limit_msec;
   1973 	limit->tv_sec = 0;
   1974 	limit->tv_usec = ((msec < 1000) ? (1000 * msec) : 100000);
   1975 }
   1976 
   1977 #if UATP_DEBUG
   1978 
   1979 #  define TAP_DEBUG_PRE(sc)	tap_debug((sc), __func__, "")
   1980 #  define TAP_DEBUG_POST(sc)	tap_debug((sc), __func__, " ->")
   1981 
   1982 static void
   1983 tap_debug(struct uatp_softc *sc, const char *caller, const char *prefix)
   1984 {
   1985 	char buffer[128];
   1986 	const char *state;
   1987 
   1988 	KASSERT(mutex_owned(&sc->sc_tap_mutex));
   1989 	switch (sc->sc_tap_state) {
   1990 	case TAP_STATE_INITIAL:		state = "initial";		break;
   1991 	case TAP_STATE_TAPPING:		state = "tapping";		break;
   1992 	case TAP_STATE_TAPPED:		state = "tapped";		break;
   1993 	case TAP_STATE_DOUBLE_TAPPING:	state = "double-tapping";	break;
   1994 	case TAP_STATE_DRAGGING_DOWN:	state = "dragging-down";	break;
   1995 	case TAP_STATE_DRAGGING_UP:	state = "dragging-up";		break;
   1996 	case TAP_STATE_TAPPING_IN_DRAG:	state = "tapping-in-drag";	break;
   1997 	default:
   1998 		snprintf(buffer, sizeof(buffer), "unknown (%d)",
   1999 		    sc->sc_tap_state);
   2000 		state = buffer;
   2001 		break;
   2002 	}
   2003 
   2004 	DPRINTF(sc, UATP_DEBUG_TAP,
   2005 	    ("%s:%s state %s, %u tapping, %u tapped\n",
   2006 		caller, prefix, state,
   2007 		sc->sc_tapping_fingers, sc->sc_tapped_fingers));
   2008 }
   2009 
   2010 #else	/* !UATP_DEBUG */
   2011 
   2012 #  define TAP_DEBUG_PRE(sc)	do {} while (0)
   2013 #  define TAP_DEBUG_POST(sc)	do {} while (0)
   2014 
   2015 #endif
   2016 
   2017 static void
   2018 tap_initialize(struct uatp_softc *sc)
   2019 {
   2020 	callout_init(&sc->sc_untap_callout, 0);
   2021 	callout_setfunc(&sc->sc_untap_callout, untap_callout, sc);
   2022 	mutex_init(&sc->sc_tap_mutex, MUTEX_DEFAULT, IPL_SOFTUSB);
   2023 	cv_init(&sc->sc_tap_cv, "uatptap");
   2024 }
   2025 
   2026 static void
   2027 tap_finalize(struct uatp_softc *sc)
   2028 {
   2029 	/* XXX Can the callout still be scheduled here?  */
   2030 	callout_destroy(&sc->sc_untap_callout);
   2031 	mutex_destroy(&sc->sc_tap_mutex);
   2032 	cv_destroy(&sc->sc_tap_cv);
   2033 }
   2034 
   2035 static void
   2036 tap_enable(struct uatp_softc *sc)
   2037 {
   2038 	mutex_enter(&sc->sc_tap_mutex);
   2039 	tap_transition_initial(sc);
   2040 	sc->sc_buttons = 0;	/* XXX Not the right place?  */
   2041 	sc->sc_all_buttons = 0;
   2042 	mutex_exit(&sc->sc_tap_mutex);
   2043 }
   2044 
   2045 static void
   2046 tap_disable(struct uatp_softc *sc)
   2047 {
   2048 	/* Reset tapping, and wait for any callouts to complete.  */
   2049 	tap_reset_wait(sc);
   2050 }
   2051 
   2052 /*
   2053  * Reset tap state.  If the untap callout has just fired, it may signal
   2054  * a harmless button release event before this returns.
   2055  */
   2056 
   2057 static void
   2058 tap_reset(struct uatp_softc *sc)
   2059 {
   2060 	callout_stop(&sc->sc_untap_callout);
   2061 	mutex_enter(&sc->sc_tap_mutex);
   2062 	tap_transition_initial(sc);
   2063 	mutex_exit(&sc->sc_tap_mutex);
   2064 }
   2065 
   2066 /* Reset, but don't return until the callout is done running.  */
   2067 
   2068 static void
   2069 tap_reset_wait(struct uatp_softc *sc)
   2070 {
   2071 	bool fired = callout_stop(&sc->sc_untap_callout);
   2072 
   2073 	mutex_enter(&sc->sc_tap_mutex);
   2074 	if (fired)
   2075 		while (sc->sc_tap_state == TAP_STATE_TAPPED)
   2076 			if (cv_timedwait(&sc->sc_tap_cv, &sc->sc_tap_mutex,
   2077 				mstohz(1000))) {
   2078 				aprint_error_dev(uatp_dev(sc),
   2079 				    "tap timeout\n");
   2080 				break;
   2081 			}
   2082 	if (sc->sc_tap_state == TAP_STATE_TAPPED)
   2083 		aprint_error_dev(uatp_dev(sc), "%s error\n", __func__);
   2084 	tap_transition_initial(sc);
   2085 	mutex_exit(&sc->sc_tap_mutex);
   2086 }
   2087 
   2088 static const struct timeval zero_timeval;
   2089 
   2090 static void
   2091 tap_transition(struct uatp_softc *sc, enum uatp_tap_state tap_state,
   2092     const struct timeval *start_time,
   2093     unsigned int tapping_fingers, unsigned int tapped_fingers)
   2094 {
   2095 	KASSERT(mutex_owned(&sc->sc_tap_mutex));
   2096 	sc->sc_tap_state = tap_state;
   2097 	sc->sc_tap_timer = *start_time;
   2098 	sc->sc_tapping_fingers = tapping_fingers;
   2099 	sc->sc_tapped_fingers = tapped_fingers;
   2100 }
   2101 
   2102 static void
   2103 tap_transition_initial(struct uatp_softc *sc)
   2104 {
   2105 	/*
   2106 	 * No checks.  This state is always kosher, and sometimes a
   2107 	 * fallback in case of failure.
   2108 	 */
   2109 	tap_transition(sc, TAP_STATE_INITIAL, &zero_timeval, 0, 0);
   2110 }
   2111 
   2112 /* Touch transitions */
   2113 
   2114 static void
   2115 tap_transition_tapping(struct uatp_softc *sc, const struct timeval *start_time,
   2116     unsigned int fingers)
   2117 {
   2118 	CHECK((sc->sc_tapping_fingers <= fingers),
   2119 	    do { tap_transition_initial(sc); return; } while (0));
   2120 	tap_transition(sc, TAP_STATE_TAPPING, start_time, fingers, 0);
   2121 }
   2122 
   2123 static void
   2124 tap_transition_double_tapping(struct uatp_softc *sc,
   2125     const struct timeval *start_time, unsigned int fingers)
   2126 {
   2127 	CHECK((sc->sc_tapping_fingers <= fingers),
   2128 	    do { tap_transition_initial(sc); return; } while (0));
   2129 	CHECK((0 < sc->sc_tapped_fingers),
   2130 	    do { tap_transition_initial(sc); return; } while (0));
   2131 	tap_transition(sc, TAP_STATE_DOUBLE_TAPPING, start_time, fingers,
   2132 	    sc->sc_tapped_fingers);
   2133 }
   2134 
   2135 static void
   2136 tap_transition_dragging_down(struct uatp_softc *sc)
   2137 {
   2138 	CHECK((0 < sc->sc_tapped_fingers),
   2139 	    do { tap_transition_initial(sc); return; } while (0));
   2140 	tap_transition(sc, TAP_STATE_DRAGGING_DOWN, &zero_timeval, 0,
   2141 	    sc->sc_tapped_fingers);
   2142 }
   2143 
   2144 static void
   2145 tap_transition_tapping_in_drag(struct uatp_softc *sc,
   2146     const struct timeval *start_time, unsigned int fingers)
   2147 {
   2148 	CHECK((sc->sc_tapping_fingers <= fingers),
   2149 	    do { tap_transition_initial(sc); return; } while (0));
   2150 	CHECK((0 < sc->sc_tapped_fingers),
   2151 	    do { tap_transition_initial(sc); return; } while (0));
   2152 	tap_transition(sc, TAP_STATE_TAPPING_IN_DRAG, start_time, fingers,
   2153 	    sc->sc_tapped_fingers);
   2154 }
   2155 
   2156 /* Release transitions */
   2157 
   2158 static void
   2159 tap_transition_tapped(struct uatp_softc *sc, const struct timeval *start_time)
   2160 {
   2161 	/*
   2162 	 * The fingers that were tapping -- of which there must have
   2163 	 * been at least one -- are now the fingers that have tapped,
   2164 	 * and there are no longer fingers tapping.
   2165 	 */
   2166 	CHECK((0 < sc->sc_tapping_fingers),
   2167 	    do { tap_transition_initial(sc); return; } while (0));
   2168 	tap_transition(sc, TAP_STATE_TAPPED, start_time, 0,
   2169 	    sc->sc_tapping_fingers);
   2170 	schedule_untap(sc);
   2171 }
   2172 
   2173 static void
   2174 tap_transition_dragging_up(struct uatp_softc *sc)
   2175 {
   2176 	CHECK((0 < sc->sc_tapped_fingers),
   2177 	    do { tap_transition_initial(sc); return; } while (0));
   2178 	tap_transition(sc, TAP_STATE_DRAGGING_UP, &zero_timeval, 0,
   2179 	    sc->sc_tapped_fingers);
   2180 }
   2181 
   2182 static void
   2183 tap_touched(struct uatp_softc *sc, unsigned int fingers)
   2184 {
   2185 	struct timeval now, diff, limit;
   2186 
   2187 	CHECK((0 < fingers), return);
   2188 	callout_stop(&sc->sc_untap_callout);
   2189 	mutex_enter(&sc->sc_tap_mutex);
   2190 	TAP_DEBUG_PRE(sc);
   2191 	/*
   2192 	 * Guarantee that the number of tapping fingers never decreases
   2193 	 * except when it is reset to zero on release.
   2194 	 */
   2195 	if (fingers < sc->sc_tapping_fingers)
   2196 		fingers = sc->sc_tapping_fingers;
   2197 	switch (sc->sc_tap_state) {
   2198 	case TAP_STATE_INITIAL:
   2199 		getmicrouptime(&now);
   2200 		tap_transition_tapping(sc, &now, fingers);
   2201 		break;
   2202 
   2203 	case TAP_STATE_TAPPING:
   2204 		/*
   2205 		 * Number of fingers may have increased, so transition
   2206 		 * even though we're already in TAPPING.
   2207 		 */
   2208 		tap_transition_tapping(sc, &sc->sc_tap_timer, fingers);
   2209 		break;
   2210 
   2211 	case TAP_STATE_TAPPED:
   2212 		getmicrouptime(&now);
   2213 		/*
   2214 		 * If the double-tap time limit has passed, it's the
   2215 		 * callout's responsibility to handle that event, so we
   2216 		 * assume the limit has not passed yet.
   2217 		 */
   2218 		tap_transition_double_tapping(sc, &now, fingers);
   2219 		break;
   2220 
   2221 	case TAP_STATE_DOUBLE_TAPPING:
   2222 		getmicrouptime(&now);
   2223 		timersub(&now, &sc->sc_tap_timer, &diff);
   2224 		uatp_tap_limit(sc, &limit);
   2225 		if (timercmp(&diff, &limit, >) ||
   2226 		    (sc->sc_track_distance >
   2227 			sc->sc_knobs.tap_track_distance_limit))
   2228 			tap_transition_dragging_down(sc);
   2229 		break;
   2230 
   2231 	case TAP_STATE_DRAGGING_DOWN:
   2232 		break;
   2233 
   2234 	case TAP_STATE_DRAGGING_UP:
   2235 		getmicrouptime(&now);
   2236 		tap_transition_tapping_in_drag(sc, &now, fingers);
   2237 		break;
   2238 
   2239 	case TAP_STATE_TAPPING_IN_DRAG:
   2240 		/*
   2241 		 * Number of fingers may have increased, so transition
   2242 		 * even though we're already in TAPPING IN DRAG.
   2243 		 */
   2244 		tap_transition_tapping_in_drag(sc, &sc->sc_tap_timer, fingers);
   2245 		break;
   2246 
   2247 	default:
   2248 		aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
   2249 		    __func__, sc->sc_tap_state);
   2250 		tap_transition_initial(sc);
   2251 		break;
   2252 	}
   2253 	TAP_DEBUG_POST(sc);
   2254 	mutex_exit(&sc->sc_tap_mutex);
   2255 }
   2256 
   2257 static bool
   2258 tap_released(struct uatp_softc *sc)
   2259 {
   2260 	struct timeval now, diff, limit;
   2261 	void (*non_tapped_transition)(struct uatp_softc *);
   2262 	bool ok, temporary_release;
   2263 
   2264 	mutex_enter(&sc->sc_tap_mutex);
   2265 	TAP_DEBUG_PRE(sc);
   2266 	switch (sc->sc_tap_state) {
   2267 	case TAP_STATE_INITIAL:
   2268 	case TAP_STATE_TAPPED:
   2269 	case TAP_STATE_DRAGGING_UP:
   2270 		/* Spurious interrupt: fingers are already off.  */
   2271 		ok = false;
   2272 		break;
   2273 
   2274 	case TAP_STATE_TAPPING:
   2275 		temporary_release = false;
   2276 		non_tapped_transition = &tap_transition_initial;
   2277 		goto maybe_tap;
   2278 
   2279 	case TAP_STATE_DOUBLE_TAPPING:
   2280 		temporary_release = true;
   2281 		non_tapped_transition = &tap_transition_dragging_up;
   2282 		goto maybe_tap;
   2283 
   2284 	case TAP_STATE_TAPPING_IN_DRAG:
   2285 		temporary_release = false;
   2286 		non_tapped_transition = &tap_transition_dragging_up;
   2287 		goto maybe_tap;
   2288 
   2289 	maybe_tap:
   2290 		getmicrouptime(&now);
   2291 		timersub(&now, &sc->sc_tap_timer, &diff);
   2292 		uatp_tap_limit(sc, &limit);
   2293 		if (timercmp(&diff, &limit, <=) &&
   2294 		    (sc->sc_track_distance <=
   2295 			sc->sc_knobs.tap_track_distance_limit)) {
   2296 			if (temporary_release) {
   2297 				/*
   2298 				 * XXX Kludge: Temporarily transition
   2299 				 * to a tap state that uatp_input will
   2300 				 * interpret as `no buttons tapped',
   2301 				 * saving the tapping fingers.  There
   2302 				 * should instead be a separate routine
   2303 				 * uatp_input_untapped.
   2304 				 */
   2305 				unsigned int fingers = sc->sc_tapping_fingers;
   2306 				tap_transition_initial(sc);
   2307 				uatp_input(sc, 0, 0, 0, 0, 0);
   2308 				sc->sc_tapping_fingers = fingers;
   2309 			}
   2310 			tap_transition_tapped(sc, &now);
   2311 		} else {
   2312 			(*non_tapped_transition)(sc);
   2313 		}
   2314 		ok = true;
   2315 		break;
   2316 
   2317 	case TAP_STATE_DRAGGING_DOWN:
   2318 		tap_transition_dragging_up(sc);
   2319 		ok = true;
   2320 		break;
   2321 
   2322 	default:
   2323 		aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
   2324 		    __func__, sc->sc_tap_state);
   2325 		tap_transition_initial(sc);
   2326 		ok = false;
   2327 		break;
   2328 	}
   2329 	TAP_DEBUG_POST(sc);
   2330 	mutex_exit(&sc->sc_tap_mutex);
   2331 	return ok;
   2332 }
   2333 
   2334 /* Untapping: Releasing the button after a tap */
   2335 
   2336 static void
   2337 schedule_untap(struct uatp_softc *sc)
   2338 {
   2339 	unsigned int ms = sc->sc_knobs.double_tap_limit_msec;
   2340 	if (ms <= 1000)
   2341 		callout_schedule(&sc->sc_untap_callout, mstohz(ms));
   2342 	else			/* XXX Reject bogus values in sysctl.  */
   2343 		aprint_error_dev(uatp_dev(sc),
   2344 		    "double-tap delay too long: %ums\n", ms);
   2345 }
   2346 
   2347 static void
   2348 untap_callout(void *arg)
   2349 {
   2350 	struct uatp_softc *sc = arg;
   2351 
   2352 	mutex_enter(&sc->sc_tap_mutex);
   2353 	TAP_DEBUG_PRE(sc);
   2354 	switch (sc->sc_tap_state) {
   2355 	case TAP_STATE_TAPPED:
   2356 		tap_transition_initial(sc);
   2357 		/*
   2358 		 * XXX Kludge: Call uatp_input after the state transition
   2359 		 * to make sure that it will actually release the button.
   2360 		 */
   2361 		uatp_input(sc, 0, 0, 0, 0, 0);
   2362 
   2363 	case TAP_STATE_INITIAL:
   2364 	case TAP_STATE_TAPPING:
   2365 	case TAP_STATE_DOUBLE_TAPPING:
   2366 	case TAP_STATE_DRAGGING_UP:
   2367 	case TAP_STATE_DRAGGING_DOWN:
   2368 	case TAP_STATE_TAPPING_IN_DRAG:
   2369 		/*
   2370 		 * Somebody else got in and changed the state before we
   2371 		 * untapped.  Let them take over; do nothing here.
   2372 		 */
   2373 		break;
   2374 
   2375 	default:
   2376 		aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
   2377 		    __func__, sc->sc_tap_state);
   2378 		tap_transition_initial(sc);
   2379 		/* XXX Just in case...?  */
   2380 		uatp_input(sc, 0, 0, 0, 0, 0);
   2381 		break;
   2382 	}
   2383 	TAP_DEBUG_POST(sc);
   2384 	/* XXX Broadcast only if state was TAPPED?  */
   2385 	cv_broadcast(&sc->sc_tap_cv);
   2386 	mutex_exit(&sc->sc_tap_mutex);
   2387 }
   2388 
   2389 /*
   2390  * Emulate different buttons if the user holds down n fingers while
   2391  * pressing the physical button.  (This is unrelated to tapping.)
   2392  */
   2393 
   2394 static uint32_t
   2395 emulated_buttons(struct uatp_softc *sc, unsigned int fingers)
   2396 {
   2397 	CHECK((1 < fingers), return 0);
   2398 
   2399 	switch (fingers) {
   2400 	case 2:
   2401 		DPRINTF(sc, UATP_DEBUG_EMUL_BUTTON,
   2402 		    ("2-finger emulated button: %"PRIx32"\n",
   2403 			sc->sc_knobs.two_finger_buttons));
   2404 		return sc->sc_knobs.two_finger_buttons;
   2405 
   2406 	case 3:
   2407 	default:
   2408 		DPRINTF(sc, UATP_DEBUG_EMUL_BUTTON,
   2409 		    ("3-finger emulated button: %"PRIx32"\n",
   2410 			sc->sc_knobs.three_finger_buttons));
   2411 		return sc->sc_knobs.three_finger_buttons;
   2412 	}
   2413 }
   2414 
   2415 /*
   2416  * Update the position known to the driver based on the position and
   2417  * number of fingers.  dx, dy, dz, and dw are expected to hold zero;
   2418  * update_position may store nonzero changes in position in them.
   2419  */
   2420 
   2421 static void
   2422 update_position(struct uatp_softc *sc, unsigned int fingers,
   2423     unsigned int x_raw, unsigned int y_raw,
   2424     int *dx, int *dy, int *dz, int *dw)
   2425 {
   2426 	CHECK((0 < fingers), return);
   2427 
   2428 	if ((fingers == 1) || (sc->sc_knobs.multifinger_track == 1))
   2429 		move_mouse(sc, x_raw, y_raw, dx, dy);
   2430 	else if (sc->sc_knobs.multifinger_track == 2)
   2431 		scroll_wheel(sc, x_raw, y_raw, dz, dw);
   2432 }
   2433 
   2434 /*
   2435  * XXX Scrolling needs to use a totally different motion model.
   2436  */
   2437 
   2438 static void
   2439 move_mouse(struct uatp_softc *sc, unsigned int x_raw, unsigned int y_raw,
   2440     int *dx, int *dy)
   2441 {
   2442 	move(sc, "mouse", x_raw, y_raw, &sc->sc_x_raw, &sc->sc_y_raw,
   2443 	    &sc->sc_x_smoothed, &sc->sc_y_smoothed,
   2444 	    &sc->sc_x_remainder, &sc->sc_y_remainder,
   2445 	    dx, dy);
   2446 }
   2447 
   2448 static void
   2449 scroll_wheel(struct uatp_softc *sc, unsigned int x_raw, unsigned int y_raw,
   2450     int *dz, int *dw)
   2451 {
   2452 	move(sc, "scroll", x_raw, y_raw, &sc->sc_z_raw, &sc->sc_w_raw,
   2453 	    &sc->sc_z_smoothed, &sc->sc_w_smoothed,
   2454 	    &sc->sc_z_remainder, &sc->sc_w_remainder,
   2455 	    dz, dw);
   2456 }
   2457 
   2458 static void
   2459 move(struct uatp_softc *sc, const char *ctx, unsigned int a, unsigned int b,
   2460     int *a_raw, int *b_raw,
   2461     int *a_smoothed, int *b_smoothed,
   2462     unsigned int *a_remainder, unsigned int *b_remainder,
   2463     int *da, int *db)
   2464 {
   2465 #define CHECK_(condition) CHECK(condition, return)
   2466 
   2467 	int old_a_raw = *a_raw, old_a_smoothed = *a_smoothed;
   2468 	int old_b_raw = *b_raw, old_b_smoothed = *b_smoothed;
   2469 	unsigned int a_dist, b_dist, dist_squared;
   2470 	bool a_fast, b_fast;
   2471 
   2472 	/*
   2473 	 * Make sure the quadratics in motion_below_threshold and
   2474 	 * tracking distance don't overflow int arithmetic.
   2475 	 */
   2476 	__CTASSERT(0x12000000 == (2 * UATP_MAX_POSITION * UATP_MAX_POSITION));
   2477 
   2478 	CHECK_(a <= UATP_MAX_POSITION);
   2479 	CHECK_(b <= UATP_MAX_POSITION);
   2480 	*a_raw = a;
   2481 	*b_raw = b;
   2482 	if ((old_a_raw < 0) || (old_b_raw < 0)) {
   2483 		DPRINTF(sc, UATP_DEBUG_MOVE,
   2484 		    ("initialize %s position (%d, %d) -> (%d, %d)\n", ctx,
   2485 			old_a_raw, old_b_raw, a, b));
   2486 		return;
   2487 	}
   2488 
   2489 	if ((old_a_smoothed < 0) || (old_b_smoothed < 0)) {
   2490 		/* XXX Does this make sense?  */
   2491 		old_a_smoothed = old_a_raw;
   2492 		old_b_smoothed = old_b_raw;
   2493 	}
   2494 
   2495 	CHECK_(0 <= old_a_raw);
   2496 	CHECK_(0 <= old_b_raw);
   2497 	CHECK_(old_a_raw <= UATP_MAX_POSITION);
   2498 	CHECK_(old_b_raw <= UATP_MAX_POSITION);
   2499 	CHECK_(0 <= old_a_smoothed);
   2500 	CHECK_(0 <= old_b_smoothed);
   2501 	CHECK_(old_a_smoothed <= UATP_MAX_POSITION);
   2502 	CHECK_(old_b_smoothed <= UATP_MAX_POSITION);
   2503 	CHECK_(0 <= *a_raw);
   2504 	CHECK_(0 <= *b_raw);
   2505 	CHECK_(*a_raw <= UATP_MAX_POSITION);
   2506 	CHECK_(*b_raw <= UATP_MAX_POSITION);
   2507 	*a_smoothed = smooth(sc, old_a_raw, old_a_smoothed, *a_raw);
   2508 	*b_smoothed = smooth(sc, old_b_raw, old_b_smoothed, *b_raw);
   2509 	CHECK_(0 <= *a_smoothed);
   2510 	CHECK_(0 <= *b_smoothed);
   2511 	CHECK_(*a_smoothed <= UATP_MAX_POSITION);
   2512 	CHECK_(*b_smoothed <= UATP_MAX_POSITION);
   2513 
   2514 	if (sc->sc_motion_timer < sc->sc_knobs.motion_delay) {
   2515 		DPRINTF(sc, UATP_DEBUG_MOVE, ("delay motion %u\n",
   2516 			sc->sc_motion_timer));
   2517 		sc->sc_motion_timer += 1;
   2518 		return;
   2519 	}
   2520 
   2521 	/* XXX Use raw distances or smoothed distances?  Acceleration?  */
   2522 	if (*a_smoothed < old_a_smoothed)
   2523 		a_dist = old_a_smoothed - *a_smoothed;
   2524 	else
   2525 		a_dist = *a_smoothed - old_a_smoothed;
   2526 
   2527 	if (*b_smoothed < old_b_smoothed)
   2528 		b_dist = old_b_smoothed - *b_smoothed;
   2529 	else
   2530 		b_dist = *b_smoothed - old_b_smoothed;
   2531 
   2532 	dist_squared = (a_dist * a_dist) + (b_dist * b_dist);
   2533 	if (dist_squared < ((2 * UATP_MAX_POSITION * UATP_MAX_POSITION)
   2534 		- sc->sc_track_distance))
   2535 		sc->sc_track_distance += dist_squared;
   2536 	else
   2537 		sc->sc_track_distance = (2 * UATP_MAX_POSITION *
   2538 		    UATP_MAX_POSITION);
   2539 	DPRINTF(sc, UATP_DEBUG_TRACK_DIST, ("finger has tracked %u units^2\n",
   2540 		sc->sc_track_distance));
   2541 
   2542 	/*
   2543 	 * The checks above guarantee that the differences here are at
   2544 	 * most UATP_MAX_POSITION in magnitude, since both minuend and
   2545 	 * subtrahend are nonnegative and at most UATP_MAX_POSITION.
   2546 	 */
   2547 	if (motion_below_threshold(sc, sc->sc_knobs.motion_threshold,
   2548 		(int)(*a_smoothed - old_a_smoothed),
   2549 		(int)(*b_smoothed - old_b_smoothed))) {
   2550 		DPRINTF(sc, UATP_DEBUG_MOVE,
   2551 		    ("%s motion too small: (%d, %d) -> (%d, %d)\n", ctx,
   2552 			old_a_smoothed, old_b_smoothed,
   2553 			*a_smoothed, *b_smoothed));
   2554 		return;
   2555 	}
   2556 	if (sc->sc_knobs.fast_per_direction == 0) {
   2557 		a_fast = b_fast = !motion_below_threshold(sc,
   2558 		    sc->sc_knobs.fast_motion_threshold,
   2559 		    (int)(*a_smoothed - old_a_smoothed),
   2560 		    (int)(*b_smoothed - old_b_smoothed));
   2561 	} else {
   2562 		a_fast = !motion_below_threshold(sc,
   2563 		    sc->sc_knobs.fast_motion_threshold,
   2564 		    (int)(*a_smoothed - old_a_smoothed),
   2565 		    0);
   2566 		b_fast = !motion_below_threshold(sc,
   2567 		    sc->sc_knobs.fast_motion_threshold,
   2568 		    0,
   2569 		    (int)(*b_smoothed - old_b_smoothed));
   2570 	}
   2571 	*da = accelerate(sc, old_a_raw, *a_raw, old_a_smoothed, *a_smoothed,
   2572 	    a_fast, a_remainder);
   2573 	*db = accelerate(sc, old_b_raw, *b_raw, old_b_smoothed, *b_smoothed,
   2574 	    b_fast, b_remainder);
   2575 	DPRINTF(sc, UATP_DEBUG_MOVE,
   2576 	    ("update %s position (%d, %d) -> (%d, %d), move by (%d, %d)\n",
   2577 		ctx, old_a_smoothed, old_b_smoothed, *a_smoothed, *b_smoothed,
   2578 		*da, *db));
   2579 
   2580 #undef CHECK_
   2581 }
   2582 
   2583 static int
   2584 smooth(struct uatp_softc *sc, unsigned int old_raw, unsigned int old_smoothed,
   2585     unsigned int raw)
   2586 {
   2587 #define CHECK_(condition) CHECK(condition, return old_raw)
   2588 
   2589 	/*
   2590 	 * Arithmetic bounds:
   2591 	 * . the weights are at most UATP_MAX_WEIGHT;
   2592 	 * . the positions are at most UATP_MAX_POSITION; and so
   2593 	 * . the numerator of the average is at most
   2594 	 *     3 * UATP_MAX_WEIGHT * UATP_MAX_POSITION,
   2595 	 *   which is #x477000, fitting comfortably in an int.
   2596 	 */
   2597 	__CTASSERT(0x477000 == (3 * UATP_MAX_WEIGHT * UATP_MAX_POSITION));
   2598 	unsigned int old_raw_weight = uatp_old_raw_weight(sc);
   2599 	unsigned int old_smoothed_weight = uatp_old_smoothed_weight(sc);
   2600 	unsigned int new_raw_weight = uatp_new_raw_weight(sc);
   2601 	CHECK_(old_raw_weight <= UATP_MAX_WEIGHT);
   2602 	CHECK_(old_smoothed_weight <= UATP_MAX_WEIGHT);
   2603 	CHECK_(new_raw_weight <= UATP_MAX_WEIGHT);
   2604 	CHECK_(old_raw <= UATP_MAX_POSITION);
   2605 	CHECK_(old_smoothed <= UATP_MAX_POSITION);
   2606 	CHECK_(raw <= UATP_MAX_POSITION);
   2607 	return (((old_raw_weight * old_raw) +
   2608 		(old_smoothed_weight * old_smoothed) +
   2609 		(new_raw_weight * raw))
   2610 	    / (old_raw_weight + old_smoothed_weight + new_raw_weight));
   2611 
   2612 #undef CHECK_
   2613 }
   2614 
   2615 static bool
   2616 motion_below_threshold(struct uatp_softc *sc, unsigned int threshold,
   2617     int x, int y)
   2618 {
   2619 	unsigned int x_squared, y_squared;
   2620 
   2621 	/* Caller guarantees the multiplication will not overflow.  */
   2622 	KASSERT(-UATP_MAX_POSITION <= x);
   2623 	KASSERT(-UATP_MAX_POSITION <= y);
   2624 	KASSERT(x <= UATP_MAX_POSITION);
   2625 	KASSERT(y <= UATP_MAX_POSITION);
   2626 	__CTASSERT(0x12000000 == (2 * UATP_MAX_POSITION * UATP_MAX_POSITION));
   2627 
   2628 	x_squared = (x * x);
   2629 	y_squared = (y * y);
   2630 
   2631 	return (x_squared + y_squared) < threshold;
   2632 }
   2633 
   2634 static int
   2635 accelerate(struct uatp_softc *sc, unsigned int old_raw, unsigned int raw,
   2636     unsigned int old_smoothed, unsigned int smoothed, bool fast,
   2637     int *remainder)
   2638 {
   2639 #define CHECK_(condition) CHECK(condition, return 0)
   2640 
   2641 	/* Guarantee that the scaling won't overflow.  */
   2642 	__CTASSERT(0x30000 ==
   2643 	    (UATP_MAX_POSITION * UATP_MAX_MOTION_MULTIPLIER));
   2644 
   2645 	CHECK_(old_raw <= UATP_MAX_POSITION);
   2646 	CHECK_(raw <= UATP_MAX_POSITION);
   2647 	CHECK_(old_smoothed <= UATP_MAX_POSITION);
   2648 	CHECK_(smoothed <= UATP_MAX_POSITION);
   2649 
   2650 	return (fast ? uatp_scale_fast_motion : uatp_scale_motion)
   2651 	    (sc, (((int) smoothed) - ((int) old_smoothed)), remainder);
   2652 
   2653 #undef CHECK_
   2654 }
   2655 
   2656 MODULE(MODULE_CLASS_DRIVER, uatp, NULL);
   2657 
   2658 #ifdef _MODULE
   2659 #include "ioconf.c"
   2660 #endif
   2661 
   2662 static int
   2663 uatp_modcmd(modcmd_t cmd, void *aux)
   2664 {
   2665 	int error = 0;
   2666 
   2667 	switch (cmd) {
   2668 	case MODULE_CMD_INIT:
   2669 #ifdef _MODULE
   2670 		error = config_init_component(cfdriver_ioconf_uatp,
   2671 		    cfattach_ioconf_uatp, cfdata_ioconf_uatp);
   2672 #endif
   2673 		return error;
   2674 	case MODULE_CMD_FINI:
   2675 #ifdef _MODULE
   2676 		error = config_fini_component(cfdriver_ioconf_uatp,
   2677 		    cfattach_ioconf_uatp, cfdata_ioconf_uatp);
   2678 #endif
   2679 		return error;
   2680 	default:
   2681 		return ENOTTY;
   2682 	}
   2683 }
   2684