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