xref: /netbsd-src/sys/dev/usb/u3g.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: u3g.c,v 1.16 2010/08/07 20:43:46 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 2009 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
22  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 /*
32  * Copyright (c) 2008 AnyWi Technologies
33  *   Author: Andrea Guzzo <aguzzo@anywi.com>
34  *   * based on uark.c 1.1 2006/08/14 08:30:22 jsg *
35  *   * parts from ubsa.c 183348 2008-09-25 12:00:56Z phk *
36  *
37  * Permission to use, copy, modify, and distribute this software for any
38  * purpose with or without fee is hereby granted, provided that the above
39  * copyright notice and this permission notice appear in all copies.
40  *
41  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
42  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
43  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
44  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
45  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
46  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
47  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
48  *
49  * $FreeBSD$
50  */
51 
52 #include <sys/cdefs.h>
53 __KERNEL_RCSID(0, "$NetBSD: u3g.c,v 1.16 2010/08/07 20:43:46 christos Exp $");
54 
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/kernel.h>
58 #include <sys/malloc.h>
59 #include <sys/bus.h>
60 #include <sys/conf.h>
61 #include <sys/tty.h>
62 
63 #include <dev/usb/usb.h>
64 #include <dev/usb/usbdi.h>
65 #include <dev/usb/usbdivar.h>
66 #include <dev/usb/usbdi_util.h>
67 
68 #include <dev/usb/ucomvar.h>
69 
70 #include "usbdevs.h"
71 
72 /*
73  * We read/write data from/to the device in 4KB chunks to maximise
74  * performance.
75  */
76 #define U3G_BUFF_SIZE	4096
77 
78 /*
79  * Some 3G devices (the Huawei E160/E220 springs to mind here) buffer up
80  * data internally even when the USB pipes are closed. So on first open,
81  * we can receive a large chunk of stale data.
82  *
83  * This causes a real problem because the default TTYDEF_LFLAG (applied
84  * on first open) has the ECHO flag set, resulting in all the stale data
85  * being echoed straight back to the device by the tty(4) layer. Some
86  * devices (again, the Huawei E160/E220 for example) react to this spew
87  * by going catatonic.
88  *
89  * All this happens before the application gets a chance to disable ECHO.
90  *
91  * We work around this by ignoring all data received from the device for
92  * a period of two seconds, or until the application starts sending data -
93  * whichever comes first.
94  */
95 #define	U3G_PURGE_SECS	2
96 
97 /*
98  * Define bits for the virtual modem control pins.
99  * The input pin states are reported via the interrupt pipe on some devices.
100  */
101 #define	U3G_OUTPIN_DTR	(1u << 0)
102 #define	U3G_OUTPIN_RTS	(1u << 1)
103 #define	U3G_INPIN_DCD	(1u << 0)
104 #define	U3G_INPIN_DSR	(1u << 1)
105 #define	U3G_INPIN_RI	(1u << 3)
106 
107 /*
108  * USB request to set the output pin status
109  */
110 #define	U3G_SET_PIN	0x22
111 
112 struct u3g_softc {
113 	device_t		sc_dev;
114 	usbd_device_handle	sc_udev;
115 	bool			sc_dying;	/* We're going away */
116 
117 	device_t		sc_ucom;	/* Child ucom(4) handle */
118 	int			sc_ifaceno;	/* Device interface number */
119 
120 	bool			sc_open;	/* Device is in use */
121 	bool			sc_purging;	/* Purging stale data */
122 	struct timeval		sc_purge_start;	/* Control duration of purge */
123 
124 	u_char			sc_msr;		/* Emulated 'msr' */
125 	uint16_t		sc_outpins;	/* Output pin state */
126 
127 	usbd_pipe_handle	sc_intr_pipe;	/* Interrupt pipe */
128 	u_char			*sc_intr_buff;	/* Interrupt buffer */
129 };
130 
131 /*
132  * The device driver has two personalities. The first uses the 'usbdevif'
133  * interface attribute so that a match will claim the entire USB device
134  * for itself. This is used for when a device needs to be mode-switched
135  * and ensures any other interfaces present cannot be claimed by other
136  * drivers while the mode-switch is in progress.
137  *
138  * The second personality uses the 'usbifif' interface attribute so that
139  * it can claim the 3G modem interfaces for itself, leaving others (such
140  * as the mass storage interfaces on some devices) for other drivers.
141  */
142 static int u3ginit_match(device_t, cfdata_t, void *);
143 static void u3ginit_attach(device_t, device_t, void *);
144 static int u3ginit_detach(device_t, int);
145 
146 CFATTACH_DECL2_NEW(u3ginit, 0, u3ginit_match,
147     u3ginit_attach, u3ginit_detach, NULL, NULL, NULL);
148 
149 
150 static int u3g_match(device_t, cfdata_t, void *);
151 static void u3g_attach(device_t, device_t, void *);
152 static int u3g_detach(device_t, int);
153 static int u3g_activate(device_t, enum devact);
154 static void u3g_childdet(device_t, device_t);
155 
156 CFATTACH_DECL2_NEW(u3g, sizeof(struct u3g_softc), u3g_match,
157     u3g_attach, u3g_detach, u3g_activate, NULL, u3g_childdet);
158 
159 
160 static void u3g_intr(usbd_xfer_handle, usbd_private_handle, usbd_status);
161 static void u3g_get_status(void *, int, u_char *, u_char *);
162 static void u3g_set(void *, int, int, int);
163 static int  u3g_open(void *, int);
164 static void u3g_close(void *, int);
165 static void u3g_read(void *, int, u_char **, uint32_t *);
166 static void u3g_write(void *, int, u_char *, u_char *, u_int32_t *);
167 
168 struct ucom_methods u3g_methods = {
169 	u3g_get_status,
170 	u3g_set,
171 	NULL,
172 	NULL,
173 	u3g_open,
174 	u3g_close,
175 	u3g_read,
176 	u3g_write,
177 };
178 
179 /*
180  * Allegedly supported devices
181  */
182 static const struct usb_devno u3g_devs[] = {
183         { USB_VENDOR_DELL, USB_PRODUCT_DELL_W5500 },
184 	/* OEM: Huawei */
185 	{ USB_VENDOR_HUAWEI, USB_PRODUCT_HUAWEI_E220 },
186 	{ USB_VENDOR_HUAWEI, USB_PRODUCT_HUAWEI_K3765 },
187 	{ USB_VENDOR_HUAWEI, USB_PRODUCT_HUAWEI_MOBILE },
188 	/* OEM: Merlin */
189 	{ USB_VENDOR_MERLIN, USB_PRODUCT_MERLIN_V620 },
190 	/* OEM: Novatel */
191 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_ES620 },
192 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_MC950D },
193 #if 0
194 	/* These are matched in u3ginit_match() */
195 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_MC950D_DRIVER },
196 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_U760_DRIVER },
197 #endif
198 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_MERLINU740 },
199 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_MERLINV620 },
200 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_S720 },
201 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_U720 },
202 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_U727 },
203 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_U740_2 },
204 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_U760 },
205 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_U870 },
206 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_V740 },
207 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_X950D },
208 	{ USB_VENDOR_NOVATEL2, USB_PRODUCT_NOVATEL2_XU870 },
209 	/* OEM: Option N.V. */
210 	{ USB_VENDOR_OPTIONNV, USB_PRODUCT_OPTIONNV_QUADPLUSUMTS },
211 	{ USB_VENDOR_OPTIONNV, USB_PRODUCT_OPTIONNV_HSDPA },
212 	{ USB_VENDOR_OPTIONNV, USB_PRODUCT_OPTIONNV_GTMAXHSUPA },
213 	/* OEM: Qualcomm, Inc. */
214 	{ USB_VENDOR_QUALCOMMINC, USB_PRODUCT_QUALCOMMINC_CDMA_MSM },
215 	{ USB_VENDOR_QUALCOMMINC, USB_PRODUCT_QUALCOMMINC_ZTE_MF626 },
216 
217 	/* OEM: Sierra Wireless: */
218 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC595U },
219 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC597E },
220 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC875U },
221 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC880 },
222 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC880E },
223 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC880U },
224 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC881 },
225 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC881E },
226 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AC881U },
227 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AIRCARD580 },
228 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AIRCARD595 },
229 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_AIRCARD875 },
230 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_C597 },
231 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_EM5625 },
232 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC5720 },
233 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC5720_2 },
234 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC5725 },
235 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC8755 },
236 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC8755_2 },
237 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC8755_3 },
238 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC8765 },
239 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC8775_2 },
240 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC8780 },
241 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC8781 },
242 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MINI5725 },
243 	{ USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_USB305 },
244 };
245 
246 static int
247 send_bulkmsg(usbd_device_handle dev, char *cmd, size_t cmdlen)
248 {
249 	usbd_interface_handle iface;
250 	usb_interface_descriptor_t *id;
251 	usb_endpoint_descriptor_t *ed;
252 	usbd_pipe_handle pipe;
253 	usbd_xfer_handle xfer;
254 	int err, i;
255 
256 	/* Move the device into the configured state. */
257 	err = usbd_set_config_index(dev, 0, 0);
258 	if (err) {
259 		aprint_error("u3g: failed to set configuration index\n");
260 		return UMATCH_NONE;
261 	}
262 
263 	err = usbd_device2interface_handle(dev, 0, &iface);
264 	if (err != 0) {
265 		aprint_error("u3ginit: failed to get interface\n");
266 		return UMATCH_NONE;
267 	}
268 
269 	id = usbd_get_interface_descriptor(iface);
270 	ed = NULL;
271 	for (i = 0 ; i < id->bNumEndpoints ; i++) {
272 		ed = usbd_interface2endpoint_descriptor(iface, i);
273 		if (ed == NULL)
274 			continue;
275 		if (UE_GET_DIR(ed->bEndpointAddress) != UE_DIR_OUT)
276 			continue;
277 		if ((ed->bmAttributes & UE_XFERTYPE) == UE_BULK)
278 			break;
279 	}
280 
281 	if (i == id->bNumEndpoints)
282 		return UMATCH_NONE;
283 
284 	err = usbd_open_pipe(iface, ed->bEndpointAddress,
285 	    USBD_EXCLUSIVE_USE, &pipe);
286 	if (err != 0) {
287 		aprint_error("u3ginit: failed to open bulk transfer pipe %d\n",
288 		    ed->bEndpointAddress);
289 		return UMATCH_NONE;
290 	}
291 
292 	xfer = usbd_alloc_xfer(dev);
293 	if (xfer != NULL) {
294 		usbd_setup_xfer(xfer, pipe, NULL, cmd, cmdlen,
295 		    USBD_SYNCHRONOUS, USBD_DEFAULT_TIMEOUT, NULL);
296 
297 		err = usbd_transfer(xfer);
298 
299 #if 0 /* XXXpooka: at least my huawei "fails" this always, but still detaches */
300 		if (err)
301 			aprint_error("u3ginit: transfer failed\n");
302 #else
303 		err = 0;
304 #endif
305 		usbd_free_xfer(xfer);
306 	} else {
307 		aprint_error("u3ginit: failed to allocate xfer\n");
308 		err = USBD_NOMEM;
309 	}
310 
311 	usbd_abort_pipe(pipe);
312 	usbd_close_pipe(pipe);
313 
314 	return (err == USBD_NORMAL_COMPLETION ? UMATCH_HIGHEST : UMATCH_NONE);
315 }
316 
317 static int
318 u3g_novatel_reinit(usbd_device_handle dev)
319 {
320 	unsigned char cmd[31];
321 
322 	memset(cmd, 0, sizeof(cmd));
323 	/* Byte 0..3: Command Block Wrapper (CBW) signature */
324 	cmd[0] = 0x55;
325 	cmd[1] = 0x53;
326 	cmd[2] = 0x42;
327 	cmd[3] = 0x43;
328 	/* 4..7: CBW Tag, has to unique, but only a single transfer used. */
329 	cmd[4] = 0x01;
330 	/* 8..11: CBW Transfer Length, no data here */
331 	/* 12: CBW Flag: output, so 0 */
332 	/* 13: CBW Lun: 0 */
333 	/* 14: CBW Length */
334 	cmd[14] = 0x06;
335 	/* Rest is the SCSI payload */
336 	/* 0: SCSI START/STOP opcode */
337 	cmd[15] = 0x1b;
338 	/* 1..3 unused */
339 	/* 4 Load/Eject command */
340 	cmd[19] = 0x02;
341 	/* 5: unused */
342 
343 	return send_bulkmsg(dev, cmd, sizeof(cmd));
344 }
345 
346 static int
347 u3g_huawei_reinit(usbd_device_handle dev)
348 {
349 	/*
350 	 * The Huawei device presents itself as a umass device with Windows
351 	 * drivers on it. After installation of the driver, it reinits into a
352 	 * 3G serial device.
353 	 */
354 	usb_device_request_t req;
355 	usb_config_descriptor_t *cdesc;
356 
357 	/* Get the config descriptor */
358 	cdesc = usbd_get_config_descriptor(dev);
359 	if (cdesc == NULL) {
360 		usb_device_descriptor_t dd;
361 
362 		if (usbd_get_device_desc(dev, &dd) != 0)
363 			return (UMATCH_NONE);
364 
365 		if (dd.bNumConfigurations != 1)
366 			return (UMATCH_NONE);
367 
368 		if (usbd_set_config_index(dev, 0, 1) != 0)
369 			return (UMATCH_NONE);
370 
371 		cdesc = usbd_get_config_descriptor(dev);
372 
373 		if (cdesc == NULL)
374 			return (UMATCH_NONE);
375 	}
376 
377 	/*
378 	 * One iface means umass mode, more than 1 (4 usually) means 3G mode.
379 	 *
380 	 * XXX: We should check the first interface's device class just to be
381 	 * sure. If it's a mass storage device, then we can be fairly certain
382 	 * it needs a mode-switch.
383 	 */
384 	if (cdesc->bNumInterface > 1)
385 		return (UMATCH_NONE);
386 
387 	req.bmRequestType = UT_WRITE_DEVICE;
388 	req.bRequest = UR_SET_FEATURE;
389 	USETW(req.wValue, UF_DEVICE_REMOTE_WAKEUP);
390 	USETW(req.wIndex, UHF_PORT_SUSPEND);
391 	USETW(req.wLength, 0);
392 
393 	(void) usbd_do_request(dev, &req, 0);
394 
395 	return (UMATCH_HIGHEST); /* Prevent umass from attaching */
396 }
397 
398 static int
399 u3g_huawei_k3765_reinit(usbd_device_handle dev)
400 {
401 	unsigned char cmd[31];
402 
403 	/* magic string adapted from some webpage */
404 	memset(cmd, 0, sizeof(cmd));
405 	cmd[0] = 0x55;
406 	cmd[1] = 0x53;
407 	cmd[2] = 0x42;
408 	cmd[3] = 0x43;
409 	cmd[15]= 0x11;
410 	cmd[16]= 0x06;
411 
412 	return send_bulkmsg(dev, cmd, sizeof(cmd));
413 }
414 
415 static int
416 u3g_sierra_reinit(usbd_device_handle dev)
417 {
418 	/* Some Sierra devices presents themselves as a umass device with
419 	 * Windows drivers on it. After installation of the driver, it
420 	 * reinits into a * 3G serial device.
421 	 */
422 	usb_device_request_t req;
423 
424 	req.bmRequestType = UT_VENDOR;
425 	req.bRequest = UR_SET_INTERFACE;
426 	USETW(req.wValue, UF_DEVICE_REMOTE_WAKEUP);
427 	USETW(req.wIndex, UHF_PORT_CONNECTION);
428 	USETW(req.wLength, 0);
429 
430 	(void) usbd_do_request(dev, &req, 0);
431 
432 	return (UMATCH_HIGHEST); /* Match to prevent umass from attaching */
433 }
434 
435 /*
436  * First personality:
437  *
438  * Claim the entire device if a mode-switch is required.
439  */
440 
441 static int
442 u3ginit_match(device_t parent, cfdata_t match, void *aux)
443 {
444 	struct usb_attach_arg *uaa = aux;
445 
446 	/*
447 	 * Huawei changes product when it is configured as a modem.
448 	 */
449 	switch (uaa->vendor) {
450 	case USB_VENDOR_HUAWEI:
451 		if (uaa->product == USB_PRODUCT_HUAWEI_K3765)
452 			return UMATCH_NONE;
453 
454 		switch (uaa->product) {
455 		case USB_PRODUCT_HUAWEI_E1750INIT:
456 		case USB_PRODUCT_HUAWEI_K3765INIT:
457 			return u3g_huawei_k3765_reinit(uaa->device);
458 			break;
459 		default:
460 			return u3g_huawei_reinit(uaa->device);
461 			break;
462 		}
463 		break;
464 
465 	case USB_VENDOR_NOVATEL2:
466 		switch (uaa->product){
467 		case USB_PRODUCT_NOVATEL2_MC950D_DRIVER:
468 		case USB_PRODUCT_NOVATEL2_U760_DRIVER:
469 			return u3g_novatel_reinit(uaa->device);
470 			break;
471 		default:
472 			break;
473 		}
474 		break;
475 
476 	case USB_VENDOR_SIERRA:
477 		if (uaa->product == USB_PRODUCT_SIERRA_INSTALLER)
478 			return u3g_sierra_reinit(uaa->device);
479 		break;
480 
481 	case USB_VENDOR_QUALCOMMINC:
482 		if (uaa->product == USB_PRODUCT_QUALCOMMINC_ZTE_STOR)
483 			return u3g_novatel_reinit(uaa->device);
484 		break;
485 
486 	default:
487 		break;
488 	}
489 
490 	return UMATCH_NONE;
491 }
492 
493 static void
494 u3ginit_attach(device_t parent, device_t self, void *aux)
495 {
496 	struct usb_attach_arg *uaa = aux;
497 
498 	aprint_naive("\n");
499 	aprint_normal(": Switching to 3G mode\n");
500 
501 	if (uaa->vendor == USB_VENDOR_NOVATEL2) {
502 		switch (uaa->product) {
503 	    	case USB_PRODUCT_NOVATEL2_MC950D_DRIVER:
504 	    	case USB_PRODUCT_NOVATEL2_U760_DRIVER:
505 			/* About to disappear... */
506 			return;
507 			break;
508 		default:
509 			break;
510 		}
511 	}
512 
513 	/* Move the device into the configured state. */
514 	(void) usbd_set_config_index(uaa->device, 0, 1);
515 }
516 
517 static int
518 u3ginit_detach(device_t self, int flags)
519 {
520 
521 	return (0);
522 }
523 
524 
525 /*
526  * Second personality:
527  *
528  * Claim only those interfaces required for 3G modem operation.
529  */
530 
531 static int
532 u3g_match(device_t parent, cfdata_t match, void *aux)
533 {
534 	struct usbif_attach_arg *uaa = aux;
535 	usbd_interface_handle iface;
536 	usb_interface_descriptor_t *id;
537 	usbd_status error;
538 
539 	if (!usb_lookup(u3g_devs, uaa->vendor, uaa->product))
540 		return (UMATCH_NONE);
541 
542 	error = usbd_device2interface_handle(uaa->device, uaa->ifaceno, &iface);
543 	if (error) {
544 		printf("u3g_match: failed to get interface, err=%s\n",
545 		    usbd_errstr(error));
546 		return (UMATCH_NONE);
547 	}
548 
549 	id = usbd_get_interface_descriptor(iface);
550 	if (id == NULL) {
551 		printf("u3g_match: failed to get interface descriptor\n");
552 		return (UMATCH_NONE);
553 	}
554 
555 	/*
556 	 * 3G modems generally report vendor-specific class
557 	 *
558 	 * XXX: this may be too generalised.
559 	 */
560 	return ((id->bInterfaceClass == UICLASS_VENDOR) ?
561 	    UMATCH_VENDOR_PRODUCT : UMATCH_NONE);
562 }
563 
564 static void
565 u3g_attach(device_t parent, device_t self, void *aux)
566 {
567 	struct u3g_softc *sc = device_private(self);
568 	struct usbif_attach_arg *uaa = aux;
569 	usbd_device_handle dev = uaa->device;
570 	usbd_interface_handle iface;
571 	usb_interface_descriptor_t *id;
572 	usb_endpoint_descriptor_t *ed;
573 	struct ucom_attach_args uca;
574 	usbd_status error;
575 	int n, intr_address, intr_size;
576 
577 	aprint_naive("\n");
578 	aprint_normal("\n");
579 
580 	sc->sc_dev = self;
581 	sc->sc_dying = false;
582 	sc->sc_udev = dev;
583 
584 	error = usbd_device2interface_handle(dev, uaa->ifaceno, &iface);
585 	if (error) {
586 		aprint_error_dev(self, "failed to get interface, err=%s\n",
587 		    usbd_errstr(error));
588 		return;
589 	}
590 
591 	id = usbd_get_interface_descriptor(iface);
592 
593 	uca.info = "3G Modem";
594 	uca.ibufsize = U3G_BUFF_SIZE;
595 	uca.obufsize = U3G_BUFF_SIZE;
596 	uca.ibufsizepad = U3G_BUFF_SIZE;
597 	uca.portno = uaa->ifaceno;
598 	uca.opkthdrlen = 0;
599 	uca.device = dev;
600 	uca.iface = iface;
601 	uca.methods = &u3g_methods;
602 	uca.arg = sc;
603 	uca.bulkin = uca.bulkout = -1;
604 
605 	sc->sc_outpins = 0;
606 	sc->sc_msr = UMSR_DSR | UMSR_CTS | UMSR_DCD;
607 	sc->sc_ifaceno = uaa->ifaceno;
608 	sc->sc_open = false;
609 	sc->sc_purging = false;
610 
611 	intr_address = -1;
612 	intr_size = 0;
613 
614 	for (n = 0; n < id->bNumEndpoints; n++) {
615 		ed = usbd_interface2endpoint_descriptor(iface, n);
616 		if (ed == NULL) {
617 			aprint_error_dev(self, "no endpoint descriptor "
618 			    "for %d (interface: %d)\n", n, sc->sc_ifaceno);
619 			sc->sc_dying = true;
620 			return;
621 		}
622 
623 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
624 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT) {
625 			intr_address = ed->bEndpointAddress;
626 			intr_size = UGETW(ed->wMaxPacketSize);
627 		} else
628 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
629 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
630 			uca.bulkin = ed->bEndpointAddress;
631 		} else
632 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
633 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
634 			uca.bulkout = ed->bEndpointAddress;
635 		}
636 	}
637 
638 	if (uca.bulkin == -1) {
639 		aprint_error_dev(self, "Missing bulk in for interface %d\n",
640 		    sc->sc_ifaceno);
641 		sc->sc_dying = true;
642 		return;
643 	}
644 
645 	if (uca.bulkout == -1) {
646 		aprint_error_dev(self, "Missing bulk out for interface %d\n",
647 		    sc->sc_ifaceno);
648 		sc->sc_dying = true;
649 		return;
650 	}
651 
652 	sc->sc_ucom = config_found_sm_loc(self, "ucombus",
653 	    NULL, &uca, ucomprint, ucomsubmatch);
654 
655 	/*
656 	 * If the interface has an interrupt pipe, open it immediately so
657 	 * that we can track input pin state changes regardless of whether
658 	 * the tty(4) device is open or not.
659 	 */
660 	if (intr_address != -1) {
661 		sc->sc_intr_buff = malloc(intr_size, M_USBDEV, M_WAITOK);
662 		error = usbd_open_pipe_intr(iface, intr_address,
663 		    USBD_SHORT_XFER_OK, &sc->sc_intr_pipe, sc, sc->sc_intr_buff,
664 		    intr_size, u3g_intr, 100);
665 		if (error) {
666 			aprint_error_dev(self, "cannot open interrupt pipe "
667 			    "(addr %d)\n", intr_address);
668 			return;
669 		}
670 	} else {
671 		sc->sc_intr_pipe = NULL;
672 		sc->sc_intr_buff = NULL;
673 	}
674 
675 	if (!pmf_device_register(self, NULL, NULL))
676 		aprint_error_dev(self, "couldn't establish power handler\n");
677 }
678 
679 static int
680 u3g_detach(device_t self, int flags)
681 {
682 	struct u3g_softc *sc = device_private(self);
683 	int rv;
684 
685 	if (sc->sc_dying)
686 		return 0;
687 
688 	pmf_device_deregister(self);
689 
690 	if (sc->sc_ucom != NULL) {
691 		rv = config_detach(sc->sc_ucom, flags);
692 		if (rv != 0) {
693 			aprint_verbose_dev(self, "Can't deallocate "
694 			    "port (%d)", rv);
695 		}
696 	}
697 
698 	if (sc->sc_intr_pipe != NULL) {
699 		(void) usbd_abort_pipe(sc->sc_intr_pipe);
700 		(void) usbd_close_pipe(sc->sc_intr_pipe);
701 		sc->sc_intr_pipe = NULL;
702 	}
703 	if (sc->sc_intr_buff != NULL) {
704 		free(sc->sc_intr_buff, M_USBDEV);
705 		sc->sc_intr_buff = NULL;
706 	}
707 
708 	return (0);
709 }
710 
711 static void
712 u3g_childdet(device_t self, device_t child)
713 {
714 	struct u3g_softc *sc = device_private(self);
715 
716 	if (sc->sc_ucom == child)
717 		sc->sc_ucom = NULL;
718 }
719 
720 static int
721 u3g_activate(device_t self, enum devact act)
722 {
723 	struct u3g_softc *sc = device_private(self);
724 	int rv;
725 
726 	switch (act) {
727 	case DVACT_DEACTIVATE:
728 		if (sc->sc_ucom != NULL && config_deactivate(sc->sc_ucom))
729 			rv = -1;
730 		else
731 			rv = 0;
732 		break;
733 
734 	default:
735 		rv = 0;
736 		break;
737 	}
738 
739 	return (rv);
740 }
741 
742 static void
743 u3g_intr(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
744 {
745 	struct u3g_softc *sc = (struct u3g_softc *)priv;
746 	u_char *buf;
747 
748 	if (sc->sc_dying)
749 		return;
750 
751 	if (status != USBD_NORMAL_COMPLETION) {
752 		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
753 			return;
754 		usbd_clear_endpoint_stall_async(sc->sc_intr_pipe);
755 		return;
756 	}
757 
758 	buf = sc->sc_intr_buff;
759 	if (buf[0] == 0xa1 && buf[1] == 0x20) {
760 		u_char msr;
761 
762 		msr = sc->sc_msr & ~(UMSR_DCD | UMSR_DSR | UMSR_RI);
763 
764 		if (buf[8] & U3G_INPIN_DCD)
765 			msr |= UMSR_DCD;
766 
767 		if (buf[8] & U3G_INPIN_DSR)
768 			msr |= UMSR_DSR;
769 
770 		if (buf[8] & U3G_INPIN_RI)
771 			msr |= UMSR_RI;
772 
773 		if (msr != sc->sc_msr) {
774 			sc->sc_msr = msr;
775 			if (sc->sc_open)
776 				ucom_status_change(device_private(sc->sc_ucom));
777 		}
778 	}
779 }
780 
781 /*ARGSUSED*/
782 static void
783 u3g_get_status(void *arg, int portno, u_char *lsr, u_char *msr)
784 {
785 	struct u3g_softc *sc = arg;
786 
787 	if (lsr != NULL)
788 		*lsr = 0;	/* LSR isn't supported */
789 	if (msr != NULL)
790 		*msr = sc->sc_msr;
791 }
792 
793 /*ARGSUSED*/
794 static void
795 u3g_set(void *arg, int portno, int reg, int onoff)
796 {
797 	struct u3g_softc *sc = arg;
798 	usb_device_request_t req;
799 	uint16_t mask, new_state;
800 	usbd_status err;
801 
802 	if (sc->sc_dying)
803 		return;
804 
805 	switch (reg) {
806 	case UCOM_SET_DTR:
807 		mask = U3G_OUTPIN_DTR;
808 		break;
809 	case UCOM_SET_RTS:
810 		mask = U3G_OUTPIN_RTS;
811 		break;
812 	default:
813 		return;
814 	}
815 
816 	new_state = sc->sc_outpins & ~mask;
817 	if (onoff)
818 		new_state |= mask;
819 
820 	if (new_state == sc->sc_outpins)
821 		return;
822 
823 	sc->sc_outpins = new_state;
824 
825 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
826 	req.bRequest = U3G_SET_PIN;
827 	USETW(req.wValue, new_state);
828 	USETW(req.wIndex, sc->sc_ifaceno);
829 	USETW(req.wLength, 0);
830 
831 	err = usbd_do_request(sc->sc_udev, &req, 0);
832 	if (err == USBD_STALLED)
833 		usbd_clear_endpoint_stall(sc->sc_udev->default_pipe);
834 }
835 
836 /*ARGSUSED*/
837 static int
838 u3g_open(void *arg, int portno)
839 {
840 	struct u3g_softc *sc = arg;
841 	usb_device_request_t req;
842 	usb_endpoint_descriptor_t *ed;
843 	usb_interface_descriptor_t *id;
844 	usbd_interface_handle ih;
845 	usbd_status err;
846 	int i;
847 
848 	if (sc->sc_dying)
849 		return (0);
850 
851 	err = usbd_device2interface_handle(sc->sc_udev, portno, &ih);
852 	if (err)
853 		return (EIO);
854 
855 	id = usbd_get_interface_descriptor(ih);
856 
857 	for (i = 0; i < id->bNumEndpoints; i++) {
858 		ed = usbd_interface2endpoint_descriptor(ih, i);
859 		if (ed == NULL)
860 			return (EIO);
861 
862 		if (UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
863 			/* Issue ENDPOINT_HALT request */
864 			req.bmRequestType = UT_WRITE_ENDPOINT;
865 			req.bRequest = UR_CLEAR_FEATURE;
866 			USETW(req.wValue, UF_ENDPOINT_HALT);
867 			USETW(req.wIndex, ed->bEndpointAddress);
868 			USETW(req.wLength, 0);
869 			err = usbd_do_request(sc->sc_udev, &req, 0);
870 			if (err)
871 				return (EIO);
872 		}
873 	}
874 
875 	sc->sc_open = true;
876 	sc->sc_purging = true;
877 	getmicrotime(&sc->sc_purge_start);
878 
879 	return (0);
880 }
881 
882 /*ARGSUSED*/
883 static void
884 u3g_close(void *arg, int portno)
885 {
886 	struct u3g_softc *sc = arg;
887 
888 	sc->sc_open = false;
889 }
890 
891 /*ARGSUSED*/
892 static void
893 u3g_read(void *arg, int portno, u_char **cpp, uint32_t *ccp)
894 {
895 	struct u3g_softc *sc = arg;
896 	struct timeval curr_tv, diff_tv;
897 
898 	/*
899 	 * If we're not purging input data following first open, do nothing.
900 	 */
901 	if (sc->sc_purging == false)
902 		return;
903 
904 	/*
905 	 * Otherwise check if the purge timeout has expired
906 	 */
907 	getmicrotime(&curr_tv);
908 	timersub(&curr_tv, &sc->sc_purge_start, &diff_tv);
909 
910 	if (diff_tv.tv_sec >= U3G_PURGE_SECS) {
911 		/* Timeout expired. */
912 		sc->sc_purging = false;
913 	} else {
914 		/* Still purging. Adjust the caller's byte count. */
915 		*ccp = 0;
916 	}
917 }
918 
919 /*ARGSUSED*/
920 static void
921 u3g_write(void *arg, int portno, u_char *to, u_char *from, u_int32_t *count)
922 {
923 	struct u3g_softc *sc = arg;
924 
925 	/*
926 	 * Stop purging as soon as the first data is written to the device.
927 	 */
928 	sc->sc_purging = false;
929 	memcpy(to, from, *count);
930 }
931