xref: /freebsd/sys/dev/usb/input/atp.c (revision 5022f21bd974c740b9052f149fb31745dc602965)
1 /*-
2  * Copyright (c) 2009 Rohit Grover
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/malloc.h>
34 #include <sys/module.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/bus.h>
38 #include <sys/conf.h>
39 #include <sys/fcntl.h>
40 #include <sys/file.h>
41 #include <sys/selinfo.h>
42 #include <sys/poll.h>
43 #include <sys/sysctl.h>
44 #include <sys/uio.h>
45 
46 #include <dev/usb/usb.h>
47 #include <dev/usb/usbdi.h>
48 #include <dev/usb/usbdi_util.h>
49 #include <dev/usb/usbhid.h>
50 #include "usbdevs.h"
51 
52 #define USB_DEBUG_VAR atp_debug
53 #include <dev/usb/usb_debug.h>
54 
55 #include <sys/mouse.h>
56 
57 #define ATP_DRIVER_NAME "atp"
58 
59 /*
60  * Driver specific options: the following options may be set by
61  * `options' statements in the kernel configuration file.
62  */
63 
64 /* The multiplier used to translate sensor reported positions to mickeys. */
65 #ifndef ATP_SCALE_FACTOR
66 #define ATP_SCALE_FACTOR 48
67 #endif
68 
69 /*
70  * This is the age (in microseconds) beyond which a touch is
71  * considered to be a slide; and therefore a tap event isn't registered.
72  */
73 #ifndef ATP_TOUCH_TIMEOUT
74 #define ATP_TOUCH_TIMEOUT 125000
75 #endif
76 
77 /*
78  * A double-tap followed by a single-finger slide is treated as a
79  * special gesture. The driver responds to this gesture by assuming a
80  * virtual button-press for the lifetime of the slide. The following
81  * threshold is the maximum time gap (in microseconds) between the two
82  * tap events preceding the slide for such a gesture.
83  */
84 #ifndef ATP_DOUBLE_TAP_N_DRAG_THRESHOLD
85 #define ATP_DOUBLE_TAP_N_DRAG_THRESHOLD 200000
86 #endif
87 
88 /*
89  * The device provides us only with pressure readings from an array of
90  * X and Y sensors; for our algorithms, we need to interpret groups
91  * (typically pairs) of X and Y readings as being related to a single
92  * finger stroke. We can relate X and Y readings based on their times
93  * of incidence. The coincidence window should be at least 10000us
94  * since it is used against values from getmicrotime(), which has a
95  * precision of around 10ms.
96  */
97 #ifndef ATP_COINCIDENCE_THRESHOLD
98 #define ATP_COINCIDENCE_THRESHOLD  40000 /* unit: microseconds */
99 #if ATP_COINCIDENCE_THRESHOLD > 100000
100 #error "ATP_COINCIDENCE_THRESHOLD too large"
101 #endif
102 #endif /* #ifndef ATP_COINCIDENCE_THRESHOLD */
103 
104 /*
105  * The wait duration (in microseconds) after losing a touch contact
106  * before zombied strokes are reaped and turned into button events.
107  */
108 #define ATP_ZOMBIE_STROKE_REAP_WINDOW   50000
109 #if ATP_ZOMBIE_STROKE_REAP_WINDOW > 100000
110 #error "ATP_ZOMBIE_STROKE_REAP_WINDOW too large"
111 #endif
112 
113 /* end of driver specific options */
114 
115 
116 /* Tunables */
117 SYSCTL_NODE(_hw_usb, OID_AUTO, atp, CTLFLAG_RW, 0, "USB atp");
118 
119 #if USB_DEBUG
120 enum atp_log_level {
121 	ATP_LLEVEL_DISABLED = 0,
122 	ATP_LLEVEL_ERROR,
123 	ATP_LLEVEL_DEBUG,       /* for troubleshooting */
124 	ATP_LLEVEL_INFO,        /* for diagnostics */
125 };
126 static int atp_debug = ATP_LLEVEL_ERROR; /* the default is to only log errors */
127 SYSCTL_INT(_hw_usb_atp, OID_AUTO, debug, CTLFLAG_RW,
128     &atp_debug, ATP_LLEVEL_ERROR, "ATP debug level");
129 #endif /* #if USB_DEBUG */
130 
131 static u_int atp_touch_timeout = ATP_TOUCH_TIMEOUT;
132 SYSCTL_INT(_hw_usb_atp, OID_AUTO, touch_timeout, CTLFLAG_RW, &atp_touch_timeout,
133     125000, "age threshold (in micros) for a touch");
134 
135 static u_int atp_double_tap_threshold = ATP_DOUBLE_TAP_N_DRAG_THRESHOLD;
136 SYSCTL_INT(_hw_usb_atp, OID_AUTO, double_tap_threshold, CTLFLAG_RW,
137     &atp_double_tap_threshold, ATP_DOUBLE_TAP_N_DRAG_THRESHOLD,
138     "maximum time (in micros) between a double-tap");
139 
140 static u_int atp_mickeys_scale_factor = ATP_SCALE_FACTOR;
141 static int atp_sysctl_scale_factor_handler(SYSCTL_HANDLER_ARGS);
142 SYSCTL_PROC(_hw_usb_atp, OID_AUTO, scale_factor, CTLTYPE_UINT | CTLFLAG_RW,
143     &atp_mickeys_scale_factor, sizeof(atp_mickeys_scale_factor),
144     atp_sysctl_scale_factor_handler, "IU", "movement scale factor");
145 
146 static u_int atp_small_movement_threshold = ATP_SCALE_FACTOR >> 3;
147 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, small_movement, CTLFLAG_RW,
148     &atp_small_movement_threshold, ATP_SCALE_FACTOR >> 3,
149     "the small movement black-hole for filtering noise");
150 /*
151  * The movement threshold for a stroke; this is the maximum difference
152  * in position which will be resolved as a continuation of a stroke
153  * component.
154  */
155 static u_int atp_max_delta_mickeys = ((3 * ATP_SCALE_FACTOR) >> 1);
156 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, max_delta_mickeys, CTLFLAG_RW,
157     &atp_max_delta_mickeys, ((3 * ATP_SCALE_FACTOR) >> 1),
158     "max. mickeys-delta which will match against an existing stroke");
159 /*
160  * Strokes which accumulate at least this amount of absolute movement
161  * from the aggregate of their components are considered as
162  * slides. Unit: mickeys.
163  */
164 static u_int atp_slide_min_movement = (ATP_SCALE_FACTOR >> 3);
165 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, slide_min_movement, CTLFLAG_RW,
166     &atp_slide_min_movement, (ATP_SCALE_FACTOR >> 3),
167     "strokes with at least this amt. of movement are considered slides");
168 
169 /*
170  * The minimum age of a stroke for it to be considered mature; this
171  * helps filter movements (noise) from immature strokes. Units: interrupts.
172  */
173 static u_int atp_stroke_maturity_threshold = 2;
174 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, stroke_maturity_threshold, CTLFLAG_RW,
175     &atp_stroke_maturity_threshold, 2,
176     "the minimum age of a stroke for it to be considered mature");
177 
178 /* Accept pressure readings from sensors only if above this value. */
179 static u_int atp_sensor_noise_threshold = 2;
180 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, sensor_noise_threshold, CTLFLAG_RW,
181     &atp_sensor_noise_threshold, 2,
182     "accept pressure readings from sensors only if above this value");
183 
184 /* Ignore pressure spans with cumulative press. below this value. */
185 static u_int atp_pspan_min_cum_pressure = 10;
186 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, pspan_min_cum_pressure, CTLFLAG_RW,
187     &atp_pspan_min_cum_pressure, 10,
188     "ignore pressure spans with cumulative press. below this value");
189 
190 /* Maximum allowed width for pressure-spans.*/
191 static u_int atp_pspan_max_width = 4;
192 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, pspan_max_width, CTLFLAG_RW,
193     &atp_pspan_max_width, 4,
194     "maximum allowed width (in sensors) for pressure-spans");
195 
196 /* We support three payload protocols */
197 typedef enum {
198 	ATP_PROT_GEYSER1,
199 	ATP_PROT_GEYSER2,
200 	ATP_PROT_GEYSER3,
201 } atp_protocol;
202 
203 /* Define the various flavours of devices supported by this driver. */
204 enum {
205 	ATP_DEV_PARAMS_0,
206 	ATP_DEV_PARAMS_PBOOK,
207 	ATP_DEV_PARAMS_PBOOK_15A,
208 	ATP_DEV_PARAMS_PBOOK_17,
209 	ATP_N_DEV_PARAMS
210 };
211 struct atp_dev_params {
212 	u_int            data_len;   /* for sensor data */
213 	u_int            n_xsensors;
214 	u_int            n_ysensors;
215 	atp_protocol     prot;
216 } atp_dev_params[ATP_N_DEV_PARAMS] = {
217 	[ATP_DEV_PARAMS_0] = {
218 		.data_len   = 64,
219 		.n_xsensors = 20,
220 		.n_ysensors = 10,
221 		.prot       = ATP_PROT_GEYSER3
222 	},
223 	[ATP_DEV_PARAMS_PBOOK] = {
224 		.data_len   = 81,
225 		.n_xsensors = 16,
226 		.n_ysensors = 16,
227 		.prot       = ATP_PROT_GEYSER1
228 	},
229 	[ATP_DEV_PARAMS_PBOOK_15A] = {
230 		.data_len   = 64,
231 		.n_xsensors = 15,
232 		.n_ysensors = 9,
233 		.prot       = ATP_PROT_GEYSER2
234 	},
235 	[ATP_DEV_PARAMS_PBOOK_17] = {
236 		.data_len   = 81,
237 		.n_xsensors = 26,
238 		.n_ysensors = 16,
239 		.prot       = ATP_PROT_GEYSER1
240 	},
241 };
242 
243 static const struct usb_device_id atp_devs[] = {
244 	/* Core Duo MacBook & MacBook Pro */
245 	{ USB_VPI(USB_VENDOR_APPLE, 0x0217, ATP_DEV_PARAMS_0) },
246 	{ USB_VPI(USB_VENDOR_APPLE, 0x0218, ATP_DEV_PARAMS_0) },
247 	{ USB_VPI(USB_VENDOR_APPLE, 0x0219, ATP_DEV_PARAMS_0) },
248 
249 	/* Core2 Duo MacBook & MacBook Pro */
250 	{ USB_VPI(USB_VENDOR_APPLE, 0x021a, ATP_DEV_PARAMS_0) },
251 	{ USB_VPI(USB_VENDOR_APPLE, 0x021b, ATP_DEV_PARAMS_0) },
252 	{ USB_VPI(USB_VENDOR_APPLE, 0x021c, ATP_DEV_PARAMS_0) },
253 
254 	/* Core2 Duo MacBook3,1 */
255 	{ USB_VPI(USB_VENDOR_APPLE, 0x0229, ATP_DEV_PARAMS_0) },
256 	{ USB_VPI(USB_VENDOR_APPLE, 0x022a, ATP_DEV_PARAMS_0) },
257 	{ USB_VPI(USB_VENDOR_APPLE, 0x022b, ATP_DEV_PARAMS_0) },
258 
259 	/* 12 inch PowerBook and iBook */
260 	{ USB_VPI(USB_VENDOR_APPLE, 0x030a, ATP_DEV_PARAMS_PBOOK) },
261 	{ USB_VPI(USB_VENDOR_APPLE, 0x030b, ATP_DEV_PARAMS_PBOOK) },
262 
263 	/* 15 inch PowerBook */
264 	{ USB_VPI(USB_VENDOR_APPLE, 0x020e, ATP_DEV_PARAMS_PBOOK) },
265 	{ USB_VPI(USB_VENDOR_APPLE, 0x020f, ATP_DEV_PARAMS_PBOOK) },
266 	{ USB_VPI(USB_VENDOR_APPLE, 0x0215, ATP_DEV_PARAMS_PBOOK_15A) },
267 
268 	/* 17 inch PowerBook */
269 	{ USB_VPI(USB_VENDOR_APPLE, 0x020d, ATP_DEV_PARAMS_PBOOK_17) },
270 
271 };
272 
273 /*
274  * The following structure captures the state of a pressure span along
275  * an axis. Each contact with the touchpad results in separate
276  * pressure spans along the two axes.
277  */
278 typedef struct atp_pspan {
279 	u_int width;   /* in units of sensors */
280 	u_int cum;     /* cumulative compression (from all sensors) */
281 	u_int cog;     /* center of gravity */
282 	u_int loc;     /* location (scaled using the mickeys factor) */
283 	boolean_t matched; /* to track pspans as they match against strokes. */
284 } atp_pspan;
285 
286 typedef enum atp_stroke_type {
287 	ATP_STROKE_TOUCH,
288 	ATP_STROKE_SLIDE,
289 } atp_stroke_type;
290 
291 #define ATP_MAX_PSPANS_PER_AXIS 3
292 
293 typedef struct atp_stroke_component {
294 	/* Fields encapsulating the pressure-span. */
295 	u_int loc;              /* location (scaled) */
296 	u_int cum_pressure;     /* cumulative compression */
297 	u_int max_cum_pressure; /* max cumulative compression */
298 	boolean_t matched; /*to track components as they match against pspans.*/
299 
300 	/* Fields containing information about movement. */
301 	int   delta_mickeys;    /* change in location (un-smoothened movement)*/
302 	int   pending;          /* cum. of pending short movements */
303 	int   movement;         /* current smoothened movement */
304 } atp_stroke_component;
305 
306 typedef enum atp_axis {
307 	X = 0,
308 	Y = 1
309 } atp_axis;
310 
311 #define ATP_MAX_STROKES         (2 * ATP_MAX_PSPANS_PER_AXIS)
312 
313 /*
314  * The following structure captures a finger contact with the
315  * touchpad. A stroke comprises two p-span components and some state.
316  */
317 typedef struct atp_stroke {
318 	atp_stroke_type      type;
319 	struct timeval       ctime; /* create time; for coincident siblings. */
320 	u_int                age;   /*
321 				     * Unit: interrupts; we maintain
322 				     * this value in addition to
323 				     * 'ctime' in order to avoid the
324 				     * expensive call to microtime()
325 				     * at every interrupt.
326 				     */
327 
328 	atp_stroke_component components[2];
329 	u_int                velocity_squared; /*
330 						* Average magnitude (squared)
331 						* of recent velocity.
332 						*/
333 	u_int                cum_movement; /* cum. absolute movement so far */
334 
335 	uint32_t             flags;  /* the state of this stroke */
336 #define ATSF_ZOMBIE          0x1
337 } atp_stroke;
338 
339 #define ATP_FIFO_BUF_SIZE        8 /* bytes */
340 #define ATP_FIFO_QUEUE_MAXLEN   50 /* units */
341 
342 enum {
343 	ATP_INTR_DT,
344 	ATP_RESET,
345 	ATP_N_TRANSFER,
346 };
347 
348 struct atp_softc {
349 	device_t               sc_dev;
350 	struct usb_device     *sc_usb_device;
351 #define MODE_LENGTH 8
352 	char                   sc_mode_bytes[MODE_LENGTH]; /* device mode */
353 	struct mtx             sc_mutex; /* for synchronization */
354 	struct usb_xfer       *sc_xfer[ATP_N_TRANSFER];
355 	struct usb_fifo_sc     sc_fifo;
356 
357 	struct atp_dev_params *sc_params;
358 
359 	mousehw_t              sc_hw;
360 	mousemode_t            sc_mode;
361 	u_int                  sc_pollrate;
362 	mousestatus_t          sc_status;
363 	u_int                  sc_state;
364 #define ATP_ENABLED            0x01
365 #define ATP_ZOMBIES_EXIST      0x02
366 #define ATP_DOUBLE_TAP_DRAG    0x04
367 #define ATP_VALID              0x08
368 
369 	u_int                  sc_left_margin;
370 	u_int                  sc_right_margin;
371 
372 	atp_stroke             sc_strokes[ATP_MAX_STROKES];
373 	u_int                  sc_n_strokes;
374 
375 	int8_t                *sensor_data; /* from interrupt packet */
376 	int                   *base_x;      /* base sensor readings */
377 	int                   *base_y;
378 	int                   *cur_x;       /* current sensor readings */
379 	int                   *cur_y;
380 	int                   *pressure_x;  /* computed pressures */
381 	int                   *pressure_y;
382 
383 	u_int                  sc_idlecount; /* preceding idle interrupts */
384 #define ATP_IDLENESS_THRESHOLD 10
385 
386 	struct timeval         sc_reap_time;
387 	struct timeval         sc_reap_ctime; /*ctime of siblings to be reaped*/
388 };
389 
390 /*
391  * The last byte of the sensor data contains status bits; the
392  * following values define the meanings of these bits.
393  */
394 enum atp_status_bits {
395 	ATP_STATUS_BUTTON      = (uint8_t)0x01, /* The button was pressed */
396 	ATP_STATUS_BASE_UPDATE = (uint8_t)0x04, /* Data from an untouched pad.*/
397 };
398 
399 typedef enum interface_mode {
400 	RAW_SENSOR_MODE = (uint8_t)0x04,
401 	HID_MODE        = (uint8_t)0x08
402 } interface_mode;
403 
404 /*
405  * function prototypes
406  */
407 static usb_fifo_cmd_t   atp_start_read;
408 static usb_fifo_cmd_t   atp_stop_read;
409 static usb_fifo_open_t  atp_open;
410 static usb_fifo_close_t atp_close;
411 static usb_fifo_ioctl_t atp_ioctl;
412 
413 static struct usb_fifo_methods atp_fifo_methods = {
414 	.f_open       = &atp_open,
415 	.f_close      = &atp_close,
416 	.f_ioctl      = &atp_ioctl,
417 	.f_start_read = &atp_start_read,
418 	.f_stop_read  = &atp_stop_read,
419 	.basename[0]  = ATP_DRIVER_NAME,
420 };
421 
422 /* device initialization and shutdown */
423 static usb_error_t   atp_req_get_report(struct usb_device *udev, void *data);
424 static int           atp_set_device_mode(device_t dev, interface_mode mode);
425 static void          atp_reset_callback(struct usb_xfer *, usb_error_t);
426 static int           atp_enable(struct atp_softc *sc);
427 static void          atp_disable(struct atp_softc *sc);
428 static int           atp_softc_populate(struct atp_softc *);
429 static void          atp_softc_unpopulate(struct atp_softc *);
430 
431 /* sensor interpretation */
432 static __inline void atp_interpret_sensor_data(const int8_t *, u_int, atp_axis,
433 			 int *, atp_protocol);
434 static __inline void atp_get_pressures(int *, const int *, const int *, int);
435 static void          atp_detect_pspans(int *, u_int, u_int, atp_pspan *,
436 			 u_int *);
437 
438 /* movement detection */
439 static boolean_t     atp_match_stroke_component(atp_stroke_component *,
440 			 const atp_pspan *);
441 static void          atp_match_strokes_against_pspans(struct atp_softc *,
442 			 atp_axis, atp_pspan *, u_int, u_int);
443 static boolean_t     atp_update_strokes(struct atp_softc *,
444 			 atp_pspan *, u_int, atp_pspan *, u_int);
445 static __inline void atp_add_stroke(struct atp_softc *, const atp_pspan *,
446 			 const atp_pspan *);
447 static void          atp_add_new_strokes(struct atp_softc *, atp_pspan *,
448 			 u_int, atp_pspan *, u_int);
449 static void          atp_advance_stroke_state(struct atp_softc *,
450 			 atp_stroke *, boolean_t *);
451 static void          atp_terminate_stroke(struct atp_softc *, u_int);
452 static __inline boolean_t atp_stroke_has_small_movement(const atp_stroke *);
453 static __inline void atp_update_pending_mickeys(atp_stroke_component *);
454 static void          atp_compute_smoothening_scale_ratio(atp_stroke *, int *,
455 			 int *);
456 static boolean_t     atp_compute_stroke_movement(atp_stroke *);
457 
458 /* tap detection */
459 static __inline void atp_setup_reap_time(struct atp_softc *, struct timeval *);
460 static void          atp_reap_zombies(struct atp_softc *, u_int *, u_int *);
461 
462 /* updating fifo */
463 static void          atp_reset_buf(struct atp_softc *sc);
464 static void          atp_add_to_queue(struct atp_softc *, int, int, uint32_t);
465 
466 
467 usb_error_t
468 atp_req_get_report(struct usb_device *udev, void *data)
469 {
470 	struct usb_device_request req;
471 
472 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
473 	req.bRequest = UR_GET_REPORT;
474 	USETW2(req.wValue, (uint8_t)0x03 /* type */, (uint8_t)0x00 /* id */);
475 	USETW(req.wIndex, 0);
476 	USETW(req.wLength, MODE_LENGTH);
477 
478 	return (usbd_do_request(udev, NULL /* mutex */, &req, data));
479 }
480 
481 static int
482 atp_set_device_mode(device_t dev, interface_mode mode)
483 {
484 	struct atp_softc     *sc;
485 	usb_device_request_t  req;
486 	usb_error_t           err;
487 
488 	if ((mode != RAW_SENSOR_MODE) && (mode != HID_MODE))
489 		return (ENXIO);
490 
491 	sc = device_get_softc(dev);
492 
493 	sc->sc_mode_bytes[0] = mode;
494 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
495 	req.bRequest = UR_SET_REPORT;
496 	USETW2(req.wValue, (uint8_t)0x03 /* type */, (uint8_t)0x00 /* id */);
497 	USETW(req.wIndex, 0);
498 	USETW(req.wLength, MODE_LENGTH);
499 	err = usbd_do_request(sc->sc_usb_device, NULL, &req, sc->sc_mode_bytes);
500 	if (err != USB_ERR_NORMAL_COMPLETION)
501 		return (ENXIO);
502 
503 	return (0);
504 }
505 
506 void
507 atp_reset_callback(struct usb_xfer *xfer, usb_error_t error)
508 {
509 	usb_device_request_t   req;
510 	struct usb_page_cache *pc;
511 	struct atp_softc      *sc = usbd_xfer_softc(xfer);
512 
513 	switch (USB_GET_STATE(xfer)) {
514 	case USB_ST_SETUP:
515 		sc->sc_mode_bytes[0] = RAW_SENSOR_MODE;
516 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
517 		req.bRequest = UR_SET_REPORT;
518 		USETW2(req.wValue,
519 		    (uint8_t)0x03 /* type */, (uint8_t)0x00 /* id */);
520 		USETW(req.wIndex, 0);
521 		USETW(req.wLength, MODE_LENGTH);
522 
523 		pc = usbd_xfer_get_frame(xfer, 0);
524 		usbd_copy_in(pc, 0, &req, sizeof(req));
525 		pc = usbd_xfer_get_frame(xfer, 1);
526 		usbd_copy_in(pc, 0, sc->sc_mode_bytes, MODE_LENGTH);
527 
528 		usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
529 		usbd_xfer_set_frame_len(xfer, 1, MODE_LENGTH);
530 		usbd_xfer_set_frames(xfer, 2);
531 		usbd_transfer_submit(xfer);
532 		break;
533 
534 	case USB_ST_TRANSFERRED:
535 	default:
536 		break;
537 	}
538 }
539 
540 static int
541 atp_enable(struct atp_softc *sc)
542 {
543 	/* Allocate the dynamic buffers */
544 	if (atp_softc_populate(sc) != 0) {
545 		atp_softc_unpopulate(sc);
546 		return (ENOMEM);
547 	}
548 
549 	/* reset status */
550 	memset(sc->sc_strokes, 0, sizeof(sc->sc_strokes));
551 	sc->sc_n_strokes = 0;
552 	memset(&sc->sc_status, 0, sizeof(sc->sc_status));
553 	sc->sc_idlecount = 0;
554 	sc->sc_state |= ATP_ENABLED;
555 
556 	DPRINTFN(ATP_LLEVEL_INFO, "enabled atp\n");
557 	return (0);
558 }
559 
560 static void
561 atp_disable(struct atp_softc *sc)
562 {
563 	atp_softc_unpopulate(sc);
564 
565 	sc->sc_state &= ~(ATP_ENABLED | ATP_VALID);
566 	DPRINTFN(ATP_LLEVEL_INFO, "disabled atp\n");
567 }
568 
569 /* Allocate dynamic memory for some fields in softc. */
570 static int
571 atp_softc_populate(struct atp_softc *sc)
572 {
573 	const struct atp_dev_params *params = sc->sc_params;
574 
575 	if (params == NULL) {
576 		DPRINTF("params uninitialized!\n");
577 		return (ENXIO);
578 	}
579 	if (params->data_len) {
580 		sc->sensor_data = malloc(params->data_len * sizeof(int8_t),
581 		    M_USB, M_WAITOK);
582 		if (sc->sensor_data == NULL) {
583 			DPRINTF("mem for sensor_data\n");
584 			return (ENXIO);
585 		}
586 	}
587 
588 	if (params->n_xsensors != 0) {
589 		sc->base_x = malloc(params->n_xsensors * sizeof(*(sc->base_x)),
590 		    M_USB, M_WAITOK);
591 		if (sc->base_x == NULL) {
592 			DPRINTF("mem for sc->base_x\n");
593 			return (ENXIO);
594 		}
595 
596 		sc->cur_x = malloc(params->n_xsensors * sizeof(*(sc->cur_x)),
597 		    M_USB, M_WAITOK);
598 		if (sc->cur_x == NULL) {
599 			DPRINTF("mem for sc->cur_x\n");
600 			return (ENXIO);
601 		}
602 
603 		sc->pressure_x =
604 			malloc(params->n_xsensors * sizeof(*(sc->pressure_x)),
605 			    M_USB, M_WAITOK);
606 		if (sc->pressure_x == NULL) {
607 			DPRINTF("mem. for pressure_x\n");
608 			return (ENXIO);
609 		}
610 	}
611 
612 	if (params->n_ysensors != 0) {
613 		sc->base_y = malloc(params->n_ysensors * sizeof(*(sc->base_y)),
614 		    M_USB, M_WAITOK);
615 		if (sc->base_y == NULL) {
616 			DPRINTF("mem for base_y\n");
617 			return (ENXIO);
618 		}
619 
620 		sc->cur_y = malloc(params->n_ysensors * sizeof(*(sc->cur_y)),
621 		    M_USB, M_WAITOK);
622 		if (sc->cur_y == NULL) {
623 			DPRINTF("mem for cur_y\n");
624 			return (ENXIO);
625 		}
626 
627 		sc->pressure_y =
628 			malloc(params->n_ysensors * sizeof(*(sc->pressure_y)),
629 			    M_USB, M_WAITOK);
630 		if (sc->pressure_y == NULL) {
631 			DPRINTF("mem. for pressure_y\n");
632 			return (ENXIO);
633 		}
634 	}
635 
636 	return (0);
637 }
638 
639 /* Free dynamic memory allocated for some fields in softc. */
640 static void
641 atp_softc_unpopulate(struct atp_softc *sc)
642 {
643 	const struct atp_dev_params *params = sc->sc_params;
644 
645 	if (params == NULL) {
646 		return;
647 	}
648 	if (params->n_xsensors != 0) {
649 		if (sc->base_x != NULL) {
650 			free(sc->base_x, M_USB);
651 			sc->base_x = NULL;
652 		}
653 
654 		if (sc->cur_x != NULL) {
655 			free(sc->cur_x, M_USB);
656 			sc->cur_x = NULL;
657 		}
658 
659 		if (sc->pressure_x != NULL) {
660 			free(sc->pressure_x, M_USB);
661 			sc->pressure_x = NULL;
662 		}
663 	}
664 	if (params->n_ysensors != 0) {
665 		if (sc->base_y != NULL) {
666 			free(sc->base_y, M_USB);
667 			sc->base_y = NULL;
668 		}
669 
670 		if (sc->cur_y != NULL) {
671 			free(sc->cur_y, M_USB);
672 			sc->cur_y = NULL;
673 		}
674 
675 		if (sc->pressure_y != NULL) {
676 			free(sc->pressure_y, M_USB);
677 			sc->pressure_y = NULL;
678 		}
679 	}
680 	if (sc->sensor_data != NULL) {
681 		free(sc->sensor_data, M_USB);
682 		sc->sensor_data = NULL;
683 	}
684 }
685 
686 /*
687  * Interpret the data from the X and Y pressure sensors. This function
688  * is called separately for the X and Y sensor arrays. The data in the
689  * USB packet is laid out in the following manner:
690  *
691  * sensor_data:
692  *            --,--,Y1,Y2,--,Y3,Y4,--,Y5,...,Y10, ... X1,X2,--,X3,X4
693  *  indices:   0  1  2  3  4  5  6  7  8 ...  15  ... 20 21 22 23 24
694  *
695  * '--' (in the above) indicates that the value is unimportant.
696  *
697  * Information about the above layout was obtained from the
698  * implementation of the AppleTouch driver in Linux.
699  *
700  * parameters:
701  *   sensor_data
702  *       raw sensor data from the USB packet.
703  *   num
704  *       The number of elements in the array 'arr'.
705  *   axis
706  *       Axis of data to fetch
707  *   arr
708  *       The array to be initialized with the readings.
709  *   prot
710  *       The protocol to use to interpret the data
711  */
712 static __inline void
713 atp_interpret_sensor_data(const int8_t *sensor_data, u_int num, atp_axis axis,
714     int	*arr, atp_protocol prot)
715 {
716 	u_int i;
717 	u_int di;   /* index into sensor data */
718 
719 	switch (prot) {
720 	case ATP_PROT_GEYSER1:
721 		/*
722 		 * For Geyser 1, the sensors are laid out in pairs
723 		 * every 5 bytes.
724 		 */
725 		for (i = 0, di = (axis == Y) ? 1 : 2; i < 8; di += 5, i++) {
726 			arr[i] = sensor_data[di];
727 			arr[i+8] = sensor_data[di+2];
728 			if (axis == X && num > 16)
729 				arr[i+16] = sensor_data[di+40];
730 		}
731 
732 		break;
733 	case ATP_PROT_GEYSER2:
734 	case ATP_PROT_GEYSER3:
735 		for (i = 0, di = (axis == Y) ? 2 : 20; i < num; /* empty */ ) {
736 			arr[i++] = sensor_data[di++];
737 			arr[i++] = sensor_data[di++];
738 			di++;
739 		}
740 		break;
741 	}
742 }
743 
744 static __inline void
745 atp_get_pressures(int *p, const int *cur, const int *base, int n)
746 {
747 	int i;
748 
749 	for (i = 0; i < n; i++) {
750 		p[i] = cur[i] - base[i];
751 		if (p[i] > 127)
752 			p[i] -= 256;
753 		if (p[i] < -127)
754 			p[i] += 256;
755 		if (p[i] < 0)
756 			p[i] = 0;
757 
758 		/*
759 		 * Shave off pressures below the noise-pressure
760 		 * threshold; this will reduce the contribution from
761 		 * lower pressure readings.
762 		 */
763 		if (p[i] <= atp_sensor_noise_threshold)
764 			p[i] = 0; /* filter away noise */
765 		else
766 			p[i] -= atp_sensor_noise_threshold;
767 	}
768 }
769 
770 static void
771 atp_detect_pspans(int *p, u_int num_sensors,
772     u_int       max_spans, /* max # of pspans permitted */
773     atp_pspan  *spans,     /* finger spans */
774     u_int      *nspans_p)  /* num spans detected */
775 {
776 	u_int i;
777 	int   maxp;             /* max pressure seen within a span */
778 	u_int num_spans = 0;
779 
780 	enum atp_pspan_state {
781 		ATP_PSPAN_INACTIVE,
782 		ATP_PSPAN_INCREASING,
783 		ATP_PSPAN_DECREASING,
784 	} state; /* state of the pressure span */
785 
786 	/*
787 	 * The following is a simple state machine to track
788 	 * the phase of the pressure span.
789 	 */
790 	memset(spans, 0, max_spans * sizeof(atp_pspan));
791 	maxp = 0;
792 	state = ATP_PSPAN_INACTIVE;
793 	for (i = 0; i < num_sensors; i++) {
794 		if (num_spans >= max_spans)
795 			break;
796 
797 		if (p[i] == 0) {
798 			if (state == ATP_PSPAN_INACTIVE) {
799 				/*
800 				 * There is no pressure information for this
801 				 * sensor, and we aren't tracking a finger.
802 				 */
803 				continue;
804 			} else {
805 				state = ATP_PSPAN_INACTIVE;
806 				maxp = 0;
807 				num_spans++;
808 			}
809 		} else {
810 			switch (state) {
811 			case ATP_PSPAN_INACTIVE:
812 				state = ATP_PSPAN_INCREASING;
813 				maxp  = p[i];
814 				break;
815 
816 			case ATP_PSPAN_INCREASING:
817 				if (p[i] > maxp)
818 					maxp = p[i];
819 				else if (p[i] <= (maxp >> 1))
820 					state = ATP_PSPAN_DECREASING;
821 				break;
822 
823 			case ATP_PSPAN_DECREASING:
824 				if (p[i] > p[i - 1]) {
825 					/*
826 					 * This is the beginning of
827 					 * another span; change state
828 					 * to give the appearance that
829 					 * we're starting from an
830 					 * inactive span, and then
831 					 * re-process this reading in
832 					 * the next iteration.
833 					 */
834 					num_spans++;
835 					state = ATP_PSPAN_INACTIVE;
836 					maxp  = 0;
837 					i--;
838 					continue;
839 				}
840 				break;
841 			}
842 
843 			/* Update the finger span with this reading. */
844 			spans[num_spans].width++;
845 			spans[num_spans].cum += p[i];
846 			spans[num_spans].cog += p[i] * (i + 1);
847 		}
848 	}
849 	if (state != ATP_PSPAN_INACTIVE)
850 		num_spans++;    /* close the last finger span */
851 
852 	/* post-process the spans */
853 	for (i = 0; i < num_spans; i++) {
854 		/* filter away unwanted pressure spans */
855 		if ((spans[i].cum < atp_pspan_min_cum_pressure) ||
856 		    (spans[i].width > atp_pspan_max_width)) {
857 			if ((i + 1) < num_spans) {
858 				memcpy(&spans[i], &spans[i + 1],
859 				    (num_spans - i - 1) * sizeof(atp_pspan));
860 				i--;
861 			}
862 			num_spans--;
863 			continue;
864 		}
865 
866 		/* compute this span's representative location */
867 		spans[i].loc = spans[i].cog * atp_mickeys_scale_factor /
868 			spans[i].cum;
869 
870 		spans[i].matched = FALSE; /* not yet matched against a stroke */
871 	}
872 
873 	*nspans_p = num_spans;
874 }
875 
876 /*
877  * Match a pressure-span against a stroke-component. If there is a
878  * match, update the component's state and return TRUE.
879  */
880 static boolean_t
881 atp_match_stroke_component(atp_stroke_component *component,
882     const atp_pspan *pspan)
883 {
884 	int delta_mickeys = pspan->loc - component->loc;
885 
886 	if (abs(delta_mickeys) > atp_max_delta_mickeys)
887 		return (FALSE); /* the finger span is too far out; no match */
888 
889 	component->loc          = pspan->loc;
890 	component->cum_pressure = pspan->cum;
891 	if (pspan->cum > component->max_cum_pressure)
892 		component->max_cum_pressure = pspan->cum;
893 
894 	/*
895 	 * If the cumulative pressure drops below a quarter of the max,
896 	 * then disregard the component's movement.
897 	 */
898 	if (component->cum_pressure < (component->max_cum_pressure >> 2))
899 		delta_mickeys = 0;
900 
901 	component->delta_mickeys = delta_mickeys;
902 	return (TRUE);
903 }
904 
905 static void
906 atp_match_strokes_against_pspans(struct atp_softc *sc, atp_axis axis,
907     atp_pspan *pspans, u_int n_pspans, u_int repeat_count)
908 {
909 	u_int i, j;
910 	u_int repeat_index = 0;
911 
912 	/* Determine the index of the multi-span. */
913 	if (repeat_count) {
914 		u_int cum = 0;
915 		for (i = 0; i < n_pspans; i++) {
916 			if (pspans[i].cum > cum) {
917 				repeat_index = i;
918 				cum = pspans[i].cum;
919 			}
920 		}
921 	}
922 
923 	for (i = 0; i < sc->sc_n_strokes; i++) {
924 		atp_stroke *stroke  = &sc->sc_strokes[i];
925 		if (stroke->components[axis].matched)
926 			continue; /* skip matched components */
927 
928 		for (j = 0; j < n_pspans; j++) {
929 			if (pspans[j].matched)
930 				continue; /* skip matched pspans */
931 
932 			if (atp_match_stroke_component(
933 				    &stroke->components[axis], &pspans[j])) {
934 				/* There is a match. */
935 				stroke->components[axis].matched = TRUE;
936 
937 				/* Take care to repeat at the multi-span. */
938 				if ((repeat_count > 0) && (j == repeat_index))
939 					repeat_count--;
940 				else
941 					pspans[j].matched = TRUE;
942 
943 				break; /* skip to the next stroke */
944 			}
945 		} /* loop over pspans */
946 	} /* loop over strokes */
947 }
948 
949 /*
950  * Update strokes by matching against current pressure-spans.
951  * Return TRUE if any movement is detected.
952  */
953 static boolean_t
954 atp_update_strokes(struct atp_softc *sc, atp_pspan *pspans_x,
955     u_int n_xpspans, atp_pspan *pspans_y, u_int n_ypspans)
956 {
957 	u_int       i, j;
958 	atp_stroke *stroke;
959 	boolean_t   movement = FALSE;
960 	u_int       repeat_count = 0;
961 
962 	/* Reset X and Y components of all strokes as unmatched. */
963 	for (i = 0; i < sc->sc_n_strokes; i++) {
964 		stroke = &sc->sc_strokes[i];
965 		stroke->components[X].matched = FALSE;
966 		stroke->components[Y].matched = FALSE;
967 	}
968 
969 	/*
970 	 * Usually, the X and Y pspans come in pairs (the common case
971 	 * being a single pair). It is possible, however, that
972 	 * multiple contacts resolve to a single pspan along an
973 	 * axis, as illustrated in the following:
974 	 *
975 	 *   F = finger-contact
976 	 *
977 	 *                pspan  pspan
978 	 *        +-----------------------+
979 	 *        |         .      .      |
980 	 *        |         .      .      |
981 	 *        |         .      .      |
982 	 *        |         .      .      |
983 	 *  pspan |.........F......F      |
984 	 *        |                       |
985 	 *        |                       |
986 	 *        |                       |
987 	 *        +-----------------------+
988 	 *
989 	 *
990 	 * The above case can be detected by a difference in the
991 	 * number of X and Y pspans. When this happens, X and Y pspans
992 	 * aren't easy to pair or match against strokes.
993 	 *
994 	 * When X and Y pspans differ in number, the axis with the
995 	 * smaller number of pspans is regarded as having a repeating
996 	 * pspan (or a multi-pspan)--in the above illustration, the
997 	 * Y-axis has a repeating pspan. Our approach is to try to
998 	 * match the multi-pspan repeatedly against strokes. The
999 	 * difference between the number of X and Y pspans gives us a
1000 	 * crude repeat_count for matching multi-pspans--i.e. the
1001 	 * multi-pspan along the Y axis (above) has a repeat_count of 1.
1002 	 */
1003 	repeat_count = abs(n_xpspans - n_ypspans);
1004 
1005 	atp_match_strokes_against_pspans(sc, X, pspans_x, n_xpspans,
1006 	    (((repeat_count != 0) && ((n_xpspans < n_ypspans))) ?
1007 		repeat_count : 0));
1008 	atp_match_strokes_against_pspans(sc, Y, pspans_y, n_ypspans,
1009 	    (((repeat_count != 0) && (n_ypspans < n_xpspans)) ?
1010 		repeat_count : 0));
1011 
1012 	/* Update the state of strokes based on the above pspan matches. */
1013 	for (i = 0; i < sc->sc_n_strokes; i++) {
1014 		stroke = &sc->sc_strokes[i];
1015 		if (stroke->components[X].matched &&
1016 		    stroke->components[Y].matched) {
1017 			atp_advance_stroke_state(sc, stroke, &movement);
1018 		} else {
1019 			/*
1020 			 * At least one component of this stroke
1021 			 * didn't match against current pspans;
1022 			 * terminate it.
1023 			 */
1024 			atp_terminate_stroke(sc, i);
1025 		}
1026 	}
1027 
1028 	/* Add new strokes for pairs of unmatched pspans */
1029 	for (i = 0; i < n_xpspans; i++) {
1030 		if (pspans_x[i].matched == FALSE) break;
1031 	}
1032 	for (j = 0; j < n_ypspans; j++) {
1033 		if (pspans_y[j].matched == FALSE) break;
1034 	}
1035 	if ((i < n_xpspans) && (j < n_ypspans)) {
1036 #if USB_DEBUG
1037 		if (atp_debug >= ATP_LLEVEL_INFO) {
1038 			printf("unmatched pspans:");
1039 			for (; i < n_xpspans; i++) {
1040 				if (pspans_x[i].matched)
1041 					continue;
1042 				printf(" X:[loc:%u,cum:%u]",
1043 				    pspans_x[i].loc, pspans_x[i].cum);
1044 			}
1045 			for (; j < n_ypspans; j++) {
1046 				if (pspans_y[j].matched)
1047 					continue;
1048 				printf(" Y:[loc:%u,cum:%u]",
1049 				    pspans_y[j].loc, pspans_y[j].cum);
1050 			}
1051 			printf("\n");
1052 		}
1053 #endif /* #if USB_DEBUG */
1054 		if ((n_xpspans == 1) && (n_ypspans == 1))
1055 			/* The common case of a single pair of new pspans. */
1056 			atp_add_stroke(sc, &pspans_x[0], &pspans_y[0]);
1057 		else
1058 			atp_add_new_strokes(sc,
1059 			    pspans_x, n_xpspans,
1060 			    pspans_y, n_ypspans);
1061 	}
1062 
1063 #if USB_DEBUG
1064 	if (atp_debug >= ATP_LLEVEL_INFO) {
1065 		for (i = 0; i < sc->sc_n_strokes; i++) {
1066 			atp_stroke *stroke = &sc->sc_strokes[i];
1067 
1068 			printf(" %s%clc:%u,dm:%d,pnd:%d,mv:%d%c"
1069 			    ",%clc:%u,dm:%d,pnd:%d,mv:%d%c",
1070 			    (stroke->flags & ATSF_ZOMBIE) ? "zomb:" : "",
1071 			    (stroke->type == ATP_STROKE_TOUCH) ? '[' : '<',
1072 			    stroke->components[X].loc,
1073 			    stroke->components[X].delta_mickeys,
1074 			    stroke->components[X].pending,
1075 			    stroke->components[X].movement,
1076 			    (stroke->type == ATP_STROKE_TOUCH) ? ']' : '>',
1077 			    (stroke->type == ATP_STROKE_TOUCH) ? '[' : '<',
1078 			    stroke->components[Y].loc,
1079 			    stroke->components[Y].delta_mickeys,
1080 			    stroke->components[Y].pending,
1081 			    stroke->components[Y].movement,
1082 			    (stroke->type == ATP_STROKE_TOUCH) ? ']' : '>');
1083 		}
1084 		if (sc->sc_n_strokes)
1085 			printf("\n");
1086 	}
1087 #endif /* #if USB_DEBUG */
1088 
1089 	return (movement);
1090 }
1091 
1092 /* Initialize a stroke using a pressure-span. */
1093 static __inline void
1094 atp_add_stroke(struct atp_softc *sc, const atp_pspan *pspan_x,
1095     const atp_pspan *pspan_y)
1096 {
1097 	atp_stroke *stroke;
1098 
1099 	if (sc->sc_n_strokes >= ATP_MAX_STROKES)
1100 		return;
1101 	stroke = &sc->sc_strokes[sc->sc_n_strokes];
1102 
1103 	memset(stroke, 0, sizeof(atp_stroke));
1104 
1105 	/*
1106 	 * Strokes begin as potential touches. If a stroke survives
1107 	 * longer than a threshold, or if it records significant
1108 	 * cumulative movement, then it is considered a 'slide'.
1109 	 */
1110 	stroke->type = ATP_STROKE_TOUCH;
1111 	microtime(&stroke->ctime);
1112 	stroke->age  = 1;       /* Unit: interrupts */
1113 
1114 	stroke->components[X].loc              = pspan_x->loc;
1115 	stroke->components[X].cum_pressure     = pspan_x->cum;
1116 	stroke->components[X].max_cum_pressure = pspan_x->cum;
1117 	stroke->components[X].matched          = TRUE;
1118 
1119 	stroke->components[Y].loc              = pspan_y->loc;
1120 	stroke->components[Y].cum_pressure     = pspan_y->cum;
1121 	stroke->components[Y].max_cum_pressure = pspan_y->cum;
1122 	stroke->components[Y].matched          = TRUE;
1123 
1124 	sc->sc_n_strokes++;
1125 	if (sc->sc_n_strokes > 1) {
1126 		/* Reset double-tap-n-drag if we have more than one strokes. */
1127 		sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG;
1128 	}
1129 
1130 	DPRINTFN(ATP_LLEVEL_INFO, "[%u,%u], time: %u,%ld\n",
1131 	    stroke->components[X].loc,
1132 	    stroke->components[Y].loc,
1133 	    (unsigned int)stroke->ctime.tv_sec,
1134 	    (unsigned long int)stroke->ctime.tv_usec);
1135 }
1136 
1137 static void
1138 atp_add_new_strokes(struct atp_softc *sc, atp_pspan *pspans_x,
1139     u_int n_xpspans, atp_pspan *pspans_y, u_int n_ypspans)
1140 {
1141 	int       i, j;
1142 	atp_pspan spans[2][ATP_MAX_PSPANS_PER_AXIS];
1143 	u_int     nspans[2];
1144 
1145 	/* Copy unmatched pspans into the local arrays. */
1146 	for (i = 0, nspans[X] = 0; i < n_xpspans; i++) {
1147 		if (pspans_x[i].matched == FALSE) {
1148 			spans[X][nspans[X]] = pspans_x[i];
1149 			nspans[X]++;
1150 		}
1151 	}
1152 	for (j = 0, nspans[Y] = 0; j < n_ypspans; j++) {
1153 		if (pspans_y[j].matched == FALSE) {
1154 			spans[Y][nspans[Y]] = pspans_y[j];
1155 			nspans[Y]++;
1156 		}
1157 	}
1158 
1159 	if (nspans[X] == nspans[Y]) {
1160 		/* Create new strokes from pairs of unmatched pspans */
1161 		for (i = 0, j = 0; (i < nspans[X]) && (j < nspans[Y]); i++, j++)
1162 			atp_add_stroke(sc, &spans[X][i], &spans[Y][j]);
1163 	} else {
1164 		u_int    cum = 0;
1165 		atp_axis repeat_axis;      /* axis with multi-pspans */
1166 		u_int    repeat_count;     /* repeat count for the multi-pspan*/
1167 		u_int    repeat_index = 0; /* index of the multi-span */
1168 
1169 		repeat_axis  = (nspans[X] > nspans[Y]) ? Y : X;
1170 		repeat_count = abs(nspans[X] - nspans[Y]);
1171 		for (i = 0; i < nspans[repeat_axis]; i++) {
1172 			if (spans[repeat_axis][i].cum > cum) {
1173 				repeat_index = i;
1174 				cum = spans[repeat_axis][i].cum;
1175 			}
1176 		}
1177 
1178 		/* Create new strokes from pairs of unmatched pspans */
1179 		i = 0, j = 0;
1180 		for (; (i < nspans[X]) && (j < nspans[Y]); i++, j++) {
1181 			atp_add_stroke(sc, &spans[X][i], &spans[Y][j]);
1182 
1183 			/* Take care to repeat at the multi-pspan. */
1184 			if (repeat_count > 0) {
1185 				if ((repeat_axis == X) &&
1186 				    (repeat_index == i)) {
1187 					i--; /* counter loop increment */
1188 					repeat_count--;
1189 				} else if ((repeat_axis == Y) &&
1190 				    (repeat_index == j)) {
1191 					j--; /* counter loop increment */
1192 					repeat_count--;
1193 				}
1194 			}
1195 		}
1196 	}
1197 }
1198 
1199 /*
1200  * Advance the state of this stroke--and update the out-parameter
1201  * 'movement' as a side-effect.
1202  */
1203 void
1204 atp_advance_stroke_state(struct atp_softc *sc, atp_stroke *stroke,
1205     boolean_t *movement)
1206 {
1207 	stroke->age++;
1208 	if (stroke->age <= atp_stroke_maturity_threshold) {
1209 		/* Avoid noise from immature strokes. */
1210 		stroke->components[X].delta_mickeys = 0;
1211 		stroke->components[Y].delta_mickeys = 0;
1212 	}
1213 
1214 	/* Revitalize stroke if it had previously been marked as a zombie. */
1215 	if (stroke->flags & ATSF_ZOMBIE)
1216 		stroke->flags &= ~ATSF_ZOMBIE;
1217 
1218 	if (atp_compute_stroke_movement(stroke))
1219 		*movement = TRUE;
1220 
1221 	/* Convert touch strokes to slides upon detecting movement or age. */
1222 	if (stroke->type == ATP_STROKE_TOUCH) {
1223 		struct timeval tdiff;
1224 
1225 		/* Compute the stroke's age. */
1226 		getmicrotime(&tdiff);
1227 		if (timevalcmp(&tdiff, &stroke->ctime, >))
1228 			timevalsub(&tdiff, &stroke->ctime);
1229 		else {
1230 			/*
1231 			 * If we are here, it is because getmicrotime
1232 			 * reported the current time as being behind
1233 			 * the stroke's start time; getmicrotime can
1234 			 * be imprecise.
1235 			 */
1236 			tdiff.tv_sec  = 0;
1237 			tdiff.tv_usec = 0;
1238 		}
1239 
1240 		if ((tdiff.tv_sec > (atp_touch_timeout / 1000000)) ||
1241 		    ((tdiff.tv_sec == (atp_touch_timeout / 1000000)) &&
1242 			(tdiff.tv_usec > atp_touch_timeout)) ||
1243 		    (stroke->cum_movement >= atp_slide_min_movement)) {
1244 			/* Switch this stroke to being a slide. */
1245 			stroke->type = ATP_STROKE_SLIDE;
1246 
1247 			/* Are we at the beginning of a double-click-n-drag? */
1248 			if ((sc->sc_n_strokes == 1) &&
1249 			    ((sc->sc_state & ATP_ZOMBIES_EXIST) == 0) &&
1250 			    timevalcmp(&stroke->ctime, &sc->sc_reap_time, >)) {
1251 				struct timeval delta;
1252 				struct timeval window = {
1253 					atp_double_tap_threshold / 1000000,
1254 					atp_double_tap_threshold % 1000000
1255 				};
1256 
1257 				delta = stroke->ctime;
1258 				timevalsub(&delta, &sc->sc_reap_time);
1259 				if (timevalcmp(&delta, &window, <=))
1260 					sc->sc_state |= ATP_DOUBLE_TAP_DRAG;
1261 			}
1262 		}
1263 	}
1264 }
1265 
1266 /*
1267  * Terminate a stroke. While SLIDE strokes are dropped, TOUCH strokes
1268  * are retained as zombies so as to reap all their siblings together;
1269  * this helps establish the number of fingers involved in the tap.
1270  */
1271 static void
1272 atp_terminate_stroke(struct atp_softc *sc,
1273     u_int index) /* index of the stroke to be terminated */
1274 {
1275 	atp_stroke *s = &sc->sc_strokes[index];
1276 
1277 	if (s->flags & ATSF_ZOMBIE) {
1278 		return;
1279 	}
1280 
1281 	if ((s->type == ATP_STROKE_TOUCH) &&
1282 	    (s->age > atp_stroke_maturity_threshold)) {
1283 		s->flags |= ATSF_ZOMBIE;
1284 
1285 		/* If no zombies exist, then prepare to reap zombies later. */
1286 		if ((sc->sc_state & ATP_ZOMBIES_EXIST) == 0) {
1287 			atp_setup_reap_time(sc, &s->ctime);
1288 			sc->sc_state |= ATP_ZOMBIES_EXIST;
1289 		}
1290 	} else {
1291 		/* Drop this stroke. */
1292 		memcpy(&sc->sc_strokes[index], &sc->sc_strokes[index + 1],
1293 		    (sc->sc_n_strokes - index - 1) * sizeof(atp_stroke));
1294 		sc->sc_n_strokes--;
1295 
1296 		/*
1297 		 * Reset the double-click-n-drag at the termination of
1298 		 * any slide stroke.
1299 		 */
1300 		sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG;
1301 	}
1302 }
1303 
1304 static __inline boolean_t
1305 atp_stroke_has_small_movement(const atp_stroke *stroke)
1306 {
1307 	return ((abs(stroke->components[X].delta_mickeys) <=
1308 		atp_small_movement_threshold) &&
1309 	    (abs(stroke->components[Y].delta_mickeys) <=
1310 		atp_small_movement_threshold));
1311 }
1312 
1313 /*
1314  * Accumulate delta_mickeys into the component's 'pending' bucket; if
1315  * the aggregate exceeds the small_movement_threshold, then retain
1316  * delta_mickeys for later.
1317  */
1318 static __inline void
1319 atp_update_pending_mickeys(atp_stroke_component *component)
1320 {
1321 	component->pending += component->delta_mickeys;
1322 	if (abs(component->pending) <= atp_small_movement_threshold)
1323 		component->delta_mickeys = 0;
1324 	else {
1325 		/*
1326 		 * Penalise pending mickeys for having accumulated
1327 		 * over short deltas. This operation has the effect of
1328 		 * scaling down the cumulative contribution of short
1329 		 * movements.
1330 		 */
1331 		component->pending -= (component->delta_mickeys << 1);
1332 	}
1333 }
1334 
1335 
1336 static void
1337 atp_compute_smoothening_scale_ratio(atp_stroke *stroke, int *numerator,
1338     int *denominator)
1339 {
1340 	int   dxdt;
1341 	int   dydt;
1342 	u_int vel_squared; /* Square of the velocity vector's magnitude. */
1343 	u_int vel_squared_smooth;
1344 
1345 	/* Table holding (10 * sqrt(x)) for x between 1 and 256. */
1346 	static uint8_t sqrt_table[256] = {
1347 		10, 14, 17, 20, 22, 24, 26, 28,
1348 		30, 31, 33, 34, 36, 37, 38, 40,
1349 		41, 42, 43, 44, 45, 46, 47, 48,
1350 		50, 50, 51, 52, 53, 54, 55, 56,
1351 		57, 58, 59, 60, 60, 61, 62, 63,
1352 		64, 64, 65, 66, 67, 67, 68, 69,
1353 		70, 70, 71, 72, 72, 73, 74, 74,
1354 		75, 76, 76, 77, 78, 78, 79, 80,
1355 		80, 81, 81, 82, 83, 83, 84, 84,
1356 		85, 86, 86, 87, 87, 88, 88, 89,
1357 		90, 90, 91, 91, 92, 92, 93, 93,
1358 		94, 94, 95, 95, 96, 96, 97, 97,
1359 		98, 98, 99, 100, 100, 100, 101, 101,
1360 		102, 102, 103, 103, 104, 104, 105, 105,
1361 		106, 106, 107, 107, 108, 108, 109, 109,
1362 		110, 110, 110, 111, 111, 112, 112, 113,
1363 		113, 114, 114, 114, 115, 115, 116, 116,
1364 		117, 117, 117, 118, 118, 119, 119, 120,
1365 		120, 120, 121, 121, 122, 122, 122, 123,
1366 		123, 124, 124, 124, 125, 125, 126, 126,
1367 		126, 127, 127, 128, 128, 128, 129, 129,
1368 		130, 130, 130, 131, 131, 131, 132, 132,
1369 		133, 133, 133, 134, 134, 134, 135, 135,
1370 		136, 136, 136, 137, 137, 137, 138, 138,
1371 		138, 139, 139, 140, 140, 140, 141, 141,
1372 		141, 142, 142, 142, 143, 143, 143, 144,
1373 		144, 144, 145, 145, 145, 146, 146, 146,
1374 		147, 147, 147, 148, 148, 148, 149, 149,
1375 		150, 150, 150, 150, 151, 151, 151, 152,
1376 		152, 152, 153, 153, 153, 154, 154, 154,
1377 		155, 155, 155, 156, 156, 156, 157, 157,
1378 		157, 158, 158, 158, 159, 159, 159, 160
1379 	};
1380 	const u_int N = sizeof(sqrt_table) / sizeof(sqrt_table[0]);
1381 
1382 	dxdt = stroke->components[X].delta_mickeys;
1383 	dydt = stroke->components[Y].delta_mickeys;
1384 
1385 	*numerator = 0, *denominator = 0; /* default values. */
1386 
1387 	/* Compute a smoothened magnitude_squared of the stroke's velocity. */
1388 	vel_squared = dxdt * dxdt + dydt * dydt;
1389 	vel_squared_smooth = (3 * stroke->velocity_squared + vel_squared) >> 2;
1390 	stroke->velocity_squared = vel_squared_smooth; /* retained as history */
1391 	if ((vel_squared == 0) || (vel_squared_smooth == 0))
1392 		return; /* returning (numerator == 0) will imply zero movement*/
1393 
1394 	/*
1395 	 * In order to determine the overall movement scale factor,
1396 	 * we're actually interested in the effect of smoothening upon
1397 	 * the *magnitude* of velocity; i.e. we need to compute the
1398 	 * square-root of (vel_squared_smooth / vel_squared) in the
1399 	 * form of a numerator and denominator.
1400 	 */
1401 
1402 	/* Keep within the bounds of the square-root table. */
1403 	while ((vel_squared > N) || (vel_squared_smooth > N)) {
1404 		/* Dividing uniformly by 2 won't disturb the final ratio. */
1405 		vel_squared        >>= 1;
1406 		vel_squared_smooth >>= 1;
1407 	}
1408 
1409 	*numerator   = sqrt_table[vel_squared_smooth - 1];
1410 	*denominator = sqrt_table[vel_squared - 1];
1411 }
1412 
1413 /*
1414  * Compute a smoothened value for the stroke's movement from
1415  * delta_mickeys in the X and Y components.
1416  */
1417 static boolean_t
1418 atp_compute_stroke_movement(atp_stroke *stroke)
1419 {
1420 	int   num;              /* numerator of scale ratio */
1421 	int   denom;            /* denominator of scale ratio */
1422 
1423 	/*
1424 	 * Short movements are added first to the 'pending' bucket,
1425 	 * and then acted upon only when their aggregate exceeds a
1426 	 * threshold. This has the effect of filtering away movement
1427 	 * noise.
1428 	 */
1429 	if (atp_stroke_has_small_movement(stroke)) {
1430 		atp_update_pending_mickeys(&stroke->components[X]);
1431 		atp_update_pending_mickeys(&stroke->components[Y]);
1432 	} else {                /* large movement */
1433 		/* clear away any pending mickeys if there are large movements*/
1434 		stroke->components[X].pending = 0;
1435 		stroke->components[Y].pending = 0;
1436 	}
1437 
1438 	/* Get the scale ratio and smoothen movement. */
1439 	atp_compute_smoothening_scale_ratio(stroke, &num, &denom);
1440 	if ((num == 0) || (denom == 0)) {
1441 		stroke->components[X].movement = 0;
1442 		stroke->components[Y].movement = 0;
1443 		stroke->velocity_squared >>= 1; /* Erode velocity_squared. */
1444 	} else {
1445 		stroke->components[X].movement =
1446 			(stroke->components[X].delta_mickeys * num) / denom;
1447 		stroke->components[Y].movement =
1448 			(stroke->components[Y].delta_mickeys * num) / denom;
1449 
1450 		stroke->cum_movement +=
1451 			abs(stroke->components[X].movement) +
1452 			abs(stroke->components[Y].movement);
1453 	}
1454 
1455 	return ((stroke->components[X].movement != 0) ||
1456 	    (stroke->components[Y].movement != 0));
1457 }
1458 
1459 static __inline void
1460 atp_setup_reap_time(struct atp_softc *sc, struct timeval *tvp)
1461 {
1462 	struct timeval reap_window = {
1463 		ATP_ZOMBIE_STROKE_REAP_WINDOW / 1000000,
1464 		ATP_ZOMBIE_STROKE_REAP_WINDOW % 1000000
1465 	};
1466 
1467 	microtime(&sc->sc_reap_time);
1468 	timevaladd(&sc->sc_reap_time, &reap_window);
1469 
1470 	sc->sc_reap_ctime = *tvp; /* ctime to reap */
1471 }
1472 
1473 static void
1474 atp_reap_zombies(struct atp_softc *sc, u_int *n_reaped, u_int *reaped_xlocs)
1475 {
1476 	u_int       i;
1477 	atp_stroke *stroke;
1478 
1479 	*n_reaped = 0;
1480 	for (i = 0; i < sc->sc_n_strokes; i++) {
1481 		struct timeval  tdiff;
1482 
1483 		stroke = &sc->sc_strokes[i];
1484 
1485 		if ((stroke->flags & ATSF_ZOMBIE) == 0)
1486 			continue;
1487 
1488 		/* Compare this stroke's ctime with the ctime being reaped. */
1489 		if (timevalcmp(&stroke->ctime, &sc->sc_reap_ctime, >=)) {
1490 			tdiff = stroke->ctime;
1491 			timevalsub(&tdiff, &sc->sc_reap_ctime);
1492 		} else {
1493 			tdiff = sc->sc_reap_ctime;
1494 			timevalsub(&tdiff, &stroke->ctime);
1495 		}
1496 
1497 		if ((tdiff.tv_sec > (ATP_COINCIDENCE_THRESHOLD / 1000000)) ||
1498 		    ((tdiff.tv_sec == (ATP_COINCIDENCE_THRESHOLD / 1000000)) &&
1499 		     (tdiff.tv_usec > (ATP_COINCIDENCE_THRESHOLD % 1000000)))) {
1500 			continue; /* Skip non-siblings. */
1501 		}
1502 
1503 		/*
1504 		 * Reap this sibling zombie stroke.
1505 		 */
1506 
1507 		if (reaped_xlocs != NULL)
1508 			reaped_xlocs[*n_reaped] = stroke->components[X].loc;
1509 
1510 		/* Erase the stroke from the sc. */
1511 		memcpy(&stroke[i], &stroke[i + 1],
1512 		    (sc->sc_n_strokes - i - 1) * sizeof(atp_stroke));
1513 		sc->sc_n_strokes--;
1514 
1515 		*n_reaped += 1;
1516 		--i; /* Decr. i to keep it unchanged for the next iteration */
1517 	}
1518 
1519 	DPRINTFN(ATP_LLEVEL_INFO, "reaped %u zombies\n", *n_reaped);
1520 
1521 	/* There could still be zombies remaining in the system. */
1522 	for (i = 0; i < sc->sc_n_strokes; i++) {
1523 		stroke = &sc->sc_strokes[i];
1524 		if (stroke->flags & ATSF_ZOMBIE) {
1525 			DPRINTFN(ATP_LLEVEL_INFO, "zombies remain!\n");
1526 			atp_setup_reap_time(sc, &stroke->ctime);
1527 			return;
1528 		}
1529 	}
1530 
1531 	/* If we reach here, then no more zombies remain. */
1532 	sc->sc_state &= ~ATP_ZOMBIES_EXIST;
1533 }
1534 
1535 
1536 /* Device methods. */
1537 static device_probe_t  atp_probe;
1538 static device_attach_t atp_attach;
1539 static device_detach_t atp_detach;
1540 static usb_callback_t  atp_intr;
1541 
1542 static const struct usb_config atp_config[ATP_N_TRANSFER] = {
1543 	[ATP_INTR_DT] = {
1544 		.type      = UE_INTERRUPT,
1545 		.endpoint  = UE_ADDR_ANY,
1546 		.direction = UE_DIR_IN,
1547 		.flags = {
1548 			.pipe_bof = 1,
1549 			.short_xfer_ok = 1,
1550 		},
1551 		.bufsize   = 0, /* use wMaxPacketSize */
1552 		.callback  = &atp_intr,
1553 	},
1554 	[ATP_RESET] = {
1555 		.type      = UE_CONTROL,
1556 		.endpoint  = 0, /* Control pipe */
1557 		.direction = UE_DIR_ANY,
1558 		.bufsize = sizeof(struct usb_device_request) + MODE_LENGTH,
1559 		.callback  = &atp_reset_callback,
1560 		.interval = 0,  /* no pre-delay */
1561 	},
1562 };
1563 
1564 static int
1565 atp_probe(device_t self)
1566 {
1567 	struct usb_attach_arg *uaa = device_get_ivars(self);
1568 
1569 	if (uaa->usb_mode != USB_MODE_HOST)
1570 		return (ENXIO);
1571 
1572 	if ((uaa->info.bInterfaceClass != UICLASS_HID) ||
1573 	    (uaa->info.bInterfaceProtocol != UIPROTO_MOUSE))
1574 		return (ENXIO);
1575 
1576 	return (usbd_lookup_id_by_uaa(atp_devs, sizeof(atp_devs), uaa));
1577 }
1578 
1579 static int
1580 atp_attach(device_t dev)
1581 {
1582 	struct atp_softc      *sc = device_get_softc(dev);
1583 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1584 	usb_error_t            err;
1585 
1586 	DPRINTFN(ATP_LLEVEL_INFO, "sc=%p\n", sc);
1587 
1588 	sc->sc_dev        = dev;
1589 	sc->sc_usb_device = uaa->device;
1590 
1591 	/*
1592 	 * By default the touchpad behaves like an HID device, sending
1593 	 * packets with reportID = 2. Such reports contain only
1594 	 * limited information--they encode movement deltas and button
1595 	 * events,--but do not include data from the pressure
1596 	 * sensors. The device input mode can be switched from HID
1597 	 * reports to raw sensor data using vendor-specific USB
1598 	 * control commands; but first the mode must be read.
1599 	 */
1600 	err = atp_req_get_report(sc->sc_usb_device, sc->sc_mode_bytes);
1601 	if (err != USB_ERR_NORMAL_COMPLETION) {
1602 		DPRINTF("failed to read device mode (%d)\n", err);
1603 		return (ENXIO);
1604 	}
1605 
1606 	if (atp_set_device_mode(dev, RAW_SENSOR_MODE) != 0) {
1607 		DPRINTF("failed to set mode to 'RAW_SENSOR' (%d)\n", err);
1608 		return (ENXIO);
1609 	}
1610 
1611 	mtx_init(&sc->sc_mutex, "atpmtx", NULL, MTX_DEF | MTX_RECURSE);
1612 
1613 	err = usbd_transfer_setup(uaa->device,
1614 	    &uaa->info.bIfaceIndex, sc->sc_xfer, atp_config,
1615 	    ATP_N_TRANSFER, sc, &sc->sc_mutex);
1616 
1617 	if (err) {
1618 		DPRINTF("error=%s\n", usbd_errstr(err));
1619 		goto detach;
1620 	}
1621 
1622 	if (usb_fifo_attach(sc->sc_usb_device, sc, &sc->sc_mutex,
1623 		&atp_fifo_methods, &sc->sc_fifo,
1624 		device_get_unit(dev), 0 - 1, uaa->info.bIfaceIndex,
1625 		UID_ROOT, GID_OPERATOR, 0644)) {
1626 		goto detach;
1627 	}
1628 
1629 	device_set_usb_desc(dev);
1630 
1631 	sc->sc_params           = &atp_dev_params[uaa->driver_info];
1632 
1633 	sc->sc_hw.buttons       = 3;
1634 	sc->sc_hw.iftype        = MOUSE_IF_USB;
1635 	sc->sc_hw.type          = MOUSE_PAD;
1636 	sc->sc_hw.model         = MOUSE_MODEL_GENERIC;
1637 	sc->sc_hw.hwid          = 0;
1638 	sc->sc_mode.protocol    = MOUSE_PROTO_MSC;
1639 	sc->sc_mode.rate        = -1;
1640 	sc->sc_mode.resolution  = MOUSE_RES_UNKNOWN;
1641 	sc->sc_mode.accelfactor = 0;
1642 	sc->sc_mode.level       = 0;
1643 	sc->sc_mode.packetsize  = MOUSE_MSC_PACKETSIZE;
1644 	sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
1645 	sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
1646 
1647 	sc->sc_state            = 0;
1648 
1649 	sc->sc_left_margin  = atp_mickeys_scale_factor;
1650 	sc->sc_right_margin = (sc->sc_params->n_xsensors - 1) *
1651 		atp_mickeys_scale_factor;
1652 
1653 	return (0);
1654 
1655 detach:
1656 	atp_detach(dev);
1657 	return (ENOMEM);
1658 }
1659 
1660 static int
1661 atp_detach(device_t dev)
1662 {
1663 	struct atp_softc *sc;
1664 
1665 	sc = device_get_softc(dev);
1666 	if (sc->sc_state & ATP_ENABLED) {
1667 		mtx_lock(&sc->sc_mutex);
1668 		atp_disable(sc);
1669 		mtx_unlock(&sc->sc_mutex);
1670 	}
1671 
1672 	usb_fifo_detach(&sc->sc_fifo);
1673 
1674 	usbd_transfer_unsetup(sc->sc_xfer, ATP_N_TRANSFER);
1675 
1676 	mtx_destroy(&sc->sc_mutex);
1677 
1678 	return (0);
1679 }
1680 
1681 static void
1682 atp_intr(struct usb_xfer *xfer, usb_error_t error)
1683 {
1684 	struct atp_softc      *sc = usbd_xfer_softc(xfer);
1685 	int                    len;
1686 	struct usb_page_cache *pc;
1687 	uint8_t                status_bits;
1688 	atp_pspan  pspans_x[ATP_MAX_PSPANS_PER_AXIS];
1689 	atp_pspan  pspans_y[ATP_MAX_PSPANS_PER_AXIS];
1690 	u_int      n_xpspans = 0, n_ypspans = 0;
1691 	u_int      reaped_xlocs[ATP_MAX_STROKES];
1692 	u_int      tap_fingers = 0;
1693 
1694 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
1695 
1696 	switch (USB_GET_STATE(xfer)) {
1697 	case USB_ST_TRANSFERRED:
1698 		if (len > sc->sc_params->data_len) {
1699 			DPRINTFN(ATP_LLEVEL_ERROR,
1700 			    "truncating large packet from %u to %u bytes\n",
1701 			    len, sc->sc_params->data_len);
1702 			len = sc->sc_params->data_len;
1703 		}
1704 		if (len < sc->sc_params->data_len)
1705 			goto tr_setup;
1706 
1707 		pc = usbd_xfer_get_frame(xfer, 0);
1708 		usbd_copy_out(pc, 0, sc->sensor_data, sc->sc_params->data_len);
1709 
1710 		/* Interpret sensor data */
1711 		atp_interpret_sensor_data(sc->sensor_data,
1712 		    sc->sc_params->n_xsensors, X, sc->cur_x,
1713 		    sc->sc_params->prot);
1714 		atp_interpret_sensor_data(sc->sensor_data,
1715 		    sc->sc_params->n_ysensors, Y,  sc->cur_y,
1716 		    sc->sc_params->prot);
1717 
1718 		/*
1719 		 * If this is the initial update (from an untouched
1720 		 * pad), we should set the base values for the sensor
1721 		 * data; deltas with respect to these base values can
1722 		 * be used as pressure readings subsequently.
1723 		 */
1724 		status_bits = sc->sensor_data[sc->sc_params->data_len - 1];
1725 		if ((sc->sc_params->prot == ATP_PROT_GEYSER3 &&
1726 		    (status_bits & ATP_STATUS_BASE_UPDATE)) ||
1727 		    !(sc->sc_state & ATP_VALID)) {
1728 			memcpy(sc->base_x, sc->cur_x,
1729 			    sc->sc_params->n_xsensors * sizeof(*(sc->base_x)));
1730 			memcpy(sc->base_y, sc->cur_y,
1731 			    sc->sc_params->n_ysensors * sizeof(*(sc->base_y)));
1732 			sc->sc_state |= ATP_VALID;
1733 			goto tr_setup;
1734 		}
1735 
1736 		/* Get pressure readings and detect p-spans for both axes. */
1737 		atp_get_pressures(sc->pressure_x, sc->cur_x, sc->base_x,
1738 		    sc->sc_params->n_xsensors);
1739 		atp_detect_pspans(sc->pressure_x, sc->sc_params->n_xsensors,
1740 		    ATP_MAX_PSPANS_PER_AXIS,
1741 		    pspans_x, &n_xpspans);
1742 		atp_get_pressures(sc->pressure_y, sc->cur_y, sc->base_y,
1743 		    sc->sc_params->n_ysensors);
1744 		atp_detect_pspans(sc->pressure_y, sc->sc_params->n_ysensors,
1745 		    ATP_MAX_PSPANS_PER_AXIS,
1746 		    pspans_y, &n_ypspans);
1747 
1748 		/* Update strokes with new pspans to detect movements. */
1749 		sc->sc_status.flags &= ~MOUSE_POSCHANGED;
1750 		if (atp_update_strokes(sc,
1751 			pspans_x, n_xpspans,
1752 			pspans_y, n_ypspans))
1753 			sc->sc_status.flags |= MOUSE_POSCHANGED;
1754 
1755 		/* Reap zombies if it is time. */
1756 		if (sc->sc_state & ATP_ZOMBIES_EXIST) {
1757 			struct timeval now;
1758 
1759 			getmicrotime(&now);
1760 			if (timevalcmp(&now, &sc->sc_reap_time, >=))
1761 				atp_reap_zombies(sc, &tap_fingers,
1762 				    reaped_xlocs);
1763 		}
1764 
1765 		sc->sc_status.flags &= ~MOUSE_STDBUTTONSCHANGED;
1766 		sc->sc_status.obutton = sc->sc_status.button;
1767 
1768 		/* Get the state of the physical buttton. */
1769 		sc->sc_status.button = (status_bits & ATP_STATUS_BUTTON) ?
1770 			MOUSE_BUTTON1DOWN : 0;
1771 		if (sc->sc_status.button != 0) {
1772 			/* Reset DOUBLE_TAP_N_DRAG if the button is pressed. */
1773 			sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG;
1774 		} else if (sc->sc_state & ATP_DOUBLE_TAP_DRAG) {
1775 			/* Assume a button-press with DOUBLE_TAP_N_DRAG. */
1776 			sc->sc_status.button = MOUSE_BUTTON1DOWN;
1777 		}
1778 
1779 		sc->sc_status.flags |=
1780 			sc->sc_status.button ^ sc->sc_status.obutton;
1781 		if (sc->sc_status.flags & MOUSE_STDBUTTONSCHANGED) {
1782 			DPRINTFN(ATP_LLEVEL_INFO, "button %s\n",
1783 			    ((sc->sc_status.button & MOUSE_BUTTON1DOWN) ?
1784 				"pressed" : "released"));
1785 		} else if ((sc->sc_status.obutton == 0) &&
1786 		    (sc->sc_status.button == 0) &&
1787 		    (tap_fingers != 0)) {
1788 			/* Ignore single-finger taps at the edges. */
1789 			if ((tap_fingers == 1) &&
1790 			    ((reaped_xlocs[0] <= sc->sc_left_margin) ||
1791 				(reaped_xlocs[0] > sc->sc_right_margin))) {
1792 				tap_fingers = 0;
1793 			}
1794 			DPRINTFN(ATP_LLEVEL_INFO,
1795 			    "tap_fingers: %u\n", tap_fingers);
1796 		}
1797 
1798 		if (sc->sc_status.flags &
1799 		    (MOUSE_POSCHANGED | MOUSE_STDBUTTONSCHANGED)) {
1800 			int   dx, dy;
1801 			u_int n_movements;
1802 
1803 			dx = 0, dy = 0, n_movements = 0;
1804 			for (u_int i = 0; i < sc->sc_n_strokes; i++) {
1805 				atp_stroke *stroke = &sc->sc_strokes[i];
1806 
1807 				if ((stroke->components[X].movement) ||
1808 				    (stroke->components[Y].movement)) {
1809 					dx += stroke->components[X].movement;
1810 					dy += stroke->components[Y].movement;
1811 					n_movements++;
1812 				}
1813 			}
1814 			/*
1815 			 * Disregard movement if multiple
1816 			 * strokes record motion.
1817 			 */
1818 			if (n_movements != 1)
1819 				dx = 0, dy = 0;
1820 
1821 			sc->sc_status.dx += dx;
1822 			sc->sc_status.dy += dy;
1823 			atp_add_to_queue(sc, dx, -dy, sc->sc_status.button);
1824 		}
1825 
1826 		if (tap_fingers != 0) {
1827 			/* Add a pair of events (button-down and button-up). */
1828 			switch (tap_fingers) {
1829 			case 1: atp_add_to_queue(sc, 0, 0, MOUSE_BUTTON1DOWN);
1830 				break;
1831 			case 2: atp_add_to_queue(sc, 0, 0, MOUSE_BUTTON2DOWN);
1832 				break;
1833 			case 3: atp_add_to_queue(sc, 0, 0, MOUSE_BUTTON3DOWN);
1834 				break;
1835 			default: break;/* handle taps of only up to 3 fingers */
1836 			}
1837 			atp_add_to_queue(sc, 0, 0, 0); /* button release */
1838 		}
1839 
1840 		/*
1841 		 * The device continues to trigger interrupts at a
1842 		 * fast rate even after touchpad activity has
1843 		 * stopped. Upon detecting that the device has
1844 		 * remained idle beyond a threshold, we reinitialize
1845 		 * it to silence the interrupts.
1846 		 */
1847 		if ((sc->sc_status.flags  == 0) &&
1848 		    (sc->sc_n_strokes     == 0) &&
1849 		    (sc->sc_status.button == 0)) {
1850 			sc->sc_idlecount++;
1851 			if (sc->sc_idlecount >= ATP_IDLENESS_THRESHOLD) {
1852 				DPRINTFN(ATP_LLEVEL_INFO, "idle\n");
1853 
1854 				/*
1855 				 * Use the last frame before we go idle for
1856 				 * calibration on pads which do not send
1857 				 * calibration frames.
1858 				 */
1859 				if (sc->sc_params->prot < ATP_PROT_GEYSER3) {
1860 					memcpy(sc->base_x, sc->cur_x,
1861 					    sc->sc_params->n_xsensors *
1862 					    sizeof(*(sc->base_x)));
1863 					memcpy(sc->base_y, sc->cur_y,
1864 					    sc->sc_params->n_ysensors *
1865 					    sizeof(*(sc->base_y)));
1866 				}
1867 
1868 				sc->sc_idlecount = 0;
1869 				usbd_transfer_start(sc->sc_xfer[ATP_RESET]);
1870 			}
1871 		} else {
1872 			sc->sc_idlecount = 0;
1873 		}
1874 
1875 	case USB_ST_SETUP:
1876 	tr_setup:
1877 		/* check if we can put more data into the FIFO */
1878 		if (usb_fifo_put_bytes_max(
1879 			    sc->sc_fifo.fp[USB_FIFO_RX]) != 0) {
1880 			usbd_xfer_set_frame_len(xfer, 0,
1881 			    sc->sc_params->data_len);
1882 			usbd_transfer_submit(xfer);
1883 		}
1884 		break;
1885 
1886 	default:                        /* Error */
1887 		if (error != USB_ERR_CANCELLED) {
1888 			/* try clear stall first */
1889 			usbd_xfer_set_stall(xfer);
1890 			goto tr_setup;
1891 		}
1892 		break;
1893 	}
1894 
1895 	return;
1896 }
1897 
1898 static void
1899 atp_add_to_queue(struct atp_softc *sc, int dx, int dy, uint32_t buttons_in)
1900 {
1901 	uint32_t buttons_out;
1902 	uint8_t  buf[8];
1903 
1904 	dx = imin(dx,  254); dx = imax(dx, -256);
1905 	dy = imin(dy,  254); dy = imax(dy, -256);
1906 
1907 	buttons_out = MOUSE_MSC_BUTTONS;
1908 	if (buttons_in & MOUSE_BUTTON1DOWN)
1909 		buttons_out &= ~MOUSE_MSC_BUTTON1UP;
1910 	else if (buttons_in & MOUSE_BUTTON2DOWN)
1911 		buttons_out &= ~MOUSE_MSC_BUTTON2UP;
1912 	else if (buttons_in & MOUSE_BUTTON3DOWN)
1913 		buttons_out &= ~MOUSE_MSC_BUTTON3UP;
1914 
1915 	DPRINTFN(ATP_LLEVEL_INFO, "dx=%d, dy=%d, buttons=%x\n",
1916 	    dx, dy, buttons_out);
1917 
1918 	/* Encode the mouse data in standard format; refer to mouse(4) */
1919 	buf[0] = sc->sc_mode.syncmask[1];
1920 	buf[0] |= buttons_out;
1921 	buf[1] = dx >> 1;
1922 	buf[2] = dy >> 1;
1923 	buf[3] = dx - (dx >> 1);
1924 	buf[4] = dy - (dy >> 1);
1925 	/* Encode extra bytes for level 1 */
1926 	if (sc->sc_mode.level == 1) {
1927 		buf[5] = 0;                    /* dz */
1928 		buf[6] = 0;                    /* dz - (dz / 2) */
1929 		buf[7] = MOUSE_SYS_EXTBUTTONS; /* Extra buttons all up. */
1930 	}
1931 
1932 	usb_fifo_put_data_linear(sc->sc_fifo.fp[USB_FIFO_RX], buf,
1933 	    sc->sc_mode.packetsize, 1);
1934 }
1935 
1936 static void
1937 atp_reset_buf(struct atp_softc *sc)
1938 {
1939 	/* reset read queue */
1940 	usb_fifo_reset(sc->sc_fifo.fp[USB_FIFO_RX]);
1941 }
1942 
1943 static void
1944 atp_start_read(struct usb_fifo *fifo)
1945 {
1946 	struct atp_softc *sc = usb_fifo_softc(fifo);
1947 	int rate;
1948 
1949 	/* Check if we should override the default polling interval */
1950 	rate = sc->sc_pollrate;
1951 	/* Range check rate */
1952 	if (rate > 1000)
1953 		rate = 1000;
1954 	/* Check for set rate */
1955 	if ((rate > 0) && (sc->sc_xfer[ATP_INTR_DT] != NULL)) {
1956 		/* Stop current transfer, if any */
1957 		usbd_transfer_stop(sc->sc_xfer[ATP_INTR_DT]);
1958 		/* Set new interval */
1959 		usbd_xfer_set_interval(sc->sc_xfer[ATP_INTR_DT], 1000 / rate);
1960 		/* Only set pollrate once */
1961 		sc->sc_pollrate = 0;
1962 	}
1963 
1964 	usbd_transfer_start(sc->sc_xfer[ATP_INTR_DT]);
1965 }
1966 
1967 static void
1968 atp_stop_read(struct usb_fifo *fifo)
1969 {
1970 	struct atp_softc *sc = usb_fifo_softc(fifo);
1971 
1972 	usbd_transfer_stop(sc->sc_xfer[ATP_INTR_DT]);
1973 }
1974 
1975 
1976 static int
1977 atp_open(struct usb_fifo *fifo, int fflags)
1978 {
1979 	DPRINTFN(ATP_LLEVEL_INFO, "\n");
1980 
1981 	if (fflags & FREAD) {
1982 		struct atp_softc *sc = usb_fifo_softc(fifo);
1983 		int rc;
1984 
1985 		if (sc->sc_state & ATP_ENABLED)
1986 			return (EBUSY);
1987 
1988 		if (usb_fifo_alloc_buffer(fifo,
1989 			ATP_FIFO_BUF_SIZE, ATP_FIFO_QUEUE_MAXLEN)) {
1990 			return (ENOMEM);
1991 		}
1992 
1993 		rc = atp_enable(sc);
1994 		if (rc != 0) {
1995 			usb_fifo_free_buffer(fifo);
1996 			return (rc);
1997 		}
1998 	}
1999 
2000 	return (0);
2001 }
2002 
2003 static void
2004 atp_close(struct usb_fifo *fifo, int fflags)
2005 {
2006 	if (fflags & FREAD) {
2007 		struct atp_softc *sc = usb_fifo_softc(fifo);
2008 
2009 		atp_disable(sc);
2010 		usb_fifo_free_buffer(fifo);
2011 	}
2012 }
2013 
2014 int
2015 atp_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags)
2016 {
2017 	struct atp_softc *sc = usb_fifo_softc(fifo);
2018 	mousemode_t mode;
2019 	int error = 0;
2020 
2021 	mtx_lock(&sc->sc_mutex);
2022 
2023 	switch(cmd) {
2024 	case MOUSE_GETHWINFO:
2025 		*(mousehw_t *)addr = sc->sc_hw;
2026 		break;
2027 	case MOUSE_GETMODE:
2028 		*(mousemode_t *)addr = sc->sc_mode;
2029 		break;
2030 	case MOUSE_SETMODE:
2031 		mode = *(mousemode_t *)addr;
2032 
2033 		if (mode.level == -1)
2034 			/* Don't change the current setting */
2035 			;
2036 		else if ((mode.level < 0) || (mode.level > 1)) {
2037 			error = EINVAL;
2038 			goto done;
2039 		}
2040 		sc->sc_mode.level = mode.level;
2041 		sc->sc_pollrate   = mode.rate;
2042 		sc->sc_hw.buttons = 3;
2043 
2044 		if (sc->sc_mode.level == 0) {
2045 			sc->sc_mode.protocol = MOUSE_PROTO_MSC;
2046 			sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
2047 			sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
2048 			sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
2049 		} else if (sc->sc_mode.level == 1) {
2050 			sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE;
2051 			sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE;
2052 			sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
2053 			sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC;
2054 		}
2055 		atp_reset_buf(sc);
2056 		break;
2057 	case MOUSE_GETLEVEL:
2058 		*(int *)addr = sc->sc_mode.level;
2059 		break;
2060 	case MOUSE_SETLEVEL:
2061 		if (*(int *)addr < 0 || *(int *)addr > 1) {
2062 			error = EINVAL;
2063 			goto done;
2064 		}
2065 		sc->sc_mode.level = *(int *)addr;
2066 		sc->sc_hw.buttons = 3;
2067 
2068 		if (sc->sc_mode.level == 0) {
2069 			sc->sc_mode.protocol = MOUSE_PROTO_MSC;
2070 			sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
2071 			sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
2072 			sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
2073 		} else if (sc->sc_mode.level == 1) {
2074 			sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE;
2075 			sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE;
2076 			sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
2077 			sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC;
2078 		}
2079 		atp_reset_buf(sc);
2080 		break;
2081 	case MOUSE_GETSTATUS: {
2082 		mousestatus_t *status = (mousestatus_t *)addr;
2083 
2084 		*status = sc->sc_status;
2085 		sc->sc_status.obutton = sc->sc_status.button;
2086 		sc->sc_status.button  = 0;
2087 		sc->sc_status.dx = 0;
2088 		sc->sc_status.dy = 0;
2089 		sc->sc_status.dz = 0;
2090 
2091 		if (status->dx || status->dy || status->dz)
2092 			status->flags |= MOUSE_POSCHANGED;
2093 		if (status->button != status->obutton)
2094 			status->flags |= MOUSE_BUTTONSCHANGED;
2095 		break;
2096 	}
2097 	default:
2098 		error = ENOTTY;
2099 	}
2100 
2101 done:
2102 	mtx_unlock(&sc->sc_mutex);
2103 	return (error);
2104 }
2105 
2106 static int
2107 atp_sysctl_scale_factor_handler(SYSCTL_HANDLER_ARGS)
2108 {
2109 	int error;
2110 	u_int tmp;
2111 	u_int prev_mickeys_scale_factor;
2112 
2113 	prev_mickeys_scale_factor = atp_mickeys_scale_factor;
2114 
2115 	tmp = atp_mickeys_scale_factor;
2116 	error = sysctl_handle_int(oidp, &tmp, 0, req);
2117 	if (error != 0 || req->newptr == NULL)
2118 		return (error);
2119 
2120 	if (tmp == prev_mickeys_scale_factor)
2121 		return (0);     /* no change */
2122 
2123 	atp_mickeys_scale_factor = tmp;
2124 	DPRINTFN(ATP_LLEVEL_INFO, "%s: resetting mickeys_scale_factor to %u\n",
2125 	    ATP_DRIVER_NAME, tmp);
2126 
2127 	/* Update dependent thresholds. */
2128 	if (atp_small_movement_threshold == (prev_mickeys_scale_factor >> 3))
2129 		atp_small_movement_threshold = atp_mickeys_scale_factor >> 3;
2130 	if (atp_max_delta_mickeys == ((3 * prev_mickeys_scale_factor) >> 1))
2131 		atp_max_delta_mickeys = ((3 * atp_mickeys_scale_factor) >>1);
2132 	if (atp_slide_min_movement == (prev_mickeys_scale_factor >> 3))
2133 		atp_slide_min_movement = atp_mickeys_scale_factor >> 3;
2134 
2135 	return (0);
2136 }
2137 
2138 static device_method_t atp_methods[] = {
2139 	/* Device interface */
2140 	DEVMETHOD(device_probe,  atp_probe),
2141 	DEVMETHOD(device_attach, atp_attach),
2142 	DEVMETHOD(device_detach, atp_detach),
2143 	{ 0, 0 }
2144 };
2145 
2146 static driver_t atp_driver = {
2147 	ATP_DRIVER_NAME,
2148 	atp_methods,
2149 	sizeof(struct atp_softc)
2150 };
2151 
2152 static devclass_t atp_devclass;
2153 
2154 DRIVER_MODULE(atp, uhub, atp_driver, atp_devclass, NULL, 0);
2155 MODULE_DEPEND(atp, usb, 1, 1, 1);
2156