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