1/*	$NetBSD: uplcom.c,v 1.21 2001/11/13 06:24:56 lukem Exp $	*/
2
3#include <sys/cdefs.h>
4__FBSDID("$FreeBSD: stable/10/sys/dev/usb/serial/uplcom.c 339853 2018-10-29 12:11:27Z hselasky $");
5
6/*-
7 * Copyright (c) 2001-2003, 2005 Shunsuke Akiyama <akiyama@jp.FreeBSD.org>.
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32/*-
33 * Copyright (c) 2001 The NetBSD Foundation, Inc.
34 * All rights reserved.
35 *
36 * This code is derived from software contributed to The NetBSD Foundation
37 * by Ichiro FUKUHARA (ichiro@ichiro.org).
38 *
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
41 * are met:
42 * 1. Redistributions of source code must retain the above copyright
43 *    notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 *    notice, this list of conditions and the following disclaimer in the
46 *    documentation and/or other materials provided with the distribution.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
49 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
50 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
51 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
52 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
53 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
54 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
55 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
56 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
57 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
58 * POSSIBILITY OF SUCH DAMAGE.
59 */
60
61/*
62 * This driver supports several USB-to-RS232 serial adapters driven by
63 * Prolific PL-2303, PL-2303X and probably PL-2303HX USB-to-RS232
64 * bridge chip.  The adapters are sold under many different brand
65 * names.
66 *
67 * Datasheets are available at Prolific www site at
68 * http://www.prolific.com.tw.  The datasheets don't contain full
69 * programming information for the chip.
70 *
71 * PL-2303HX is probably programmed the same as PL-2303X.
72 *
73 * There are several differences between PL-2303 and PL-2303(H)X.
74 * PL-2303(H)X can do higher bitrate in bulk mode, has _probably_
75 * different command for controlling CRTSCTS and needs special
76 * sequence of commands for initialization which aren't also
77 * documented in the datasheet.
78 */
79
80#include <sys/stdint.h>
81#include <sys/stddef.h>
82#include <sys/param.h>
83#include <sys/queue.h>
84#include <sys/types.h>
85#include <sys/systm.h>
86#include <sys/kernel.h>
87#include <sys/bus.h>
88#include <sys/module.h>
89#include <sys/lock.h>
90#include <sys/mutex.h>
91#include <sys/condvar.h>
92#include <sys/sysctl.h>
93#include <sys/sx.h>
94#include <sys/unistd.h>
95#include <sys/callout.h>
96#include <sys/malloc.h>
97#include <sys/priv.h>
98
99#include <dev/usb/usb.h>
100#include <dev/usb/usbdi.h>
101#include <dev/usb/usbdi_util.h>
102#include <dev/usb/usb_cdc.h>
103#include "usbdevs.h"
104
105#define	USB_DEBUG_VAR uplcom_debug
106#include <dev/usb/usb_debug.h>
107#include <dev/usb/usb_process.h>
108
109#include <dev/usb/serial/usb_serial.h>
110
111#ifdef USB_DEBUG
112static int uplcom_debug = 0;
113
114static SYSCTL_NODE(_hw_usb, OID_AUTO, uplcom, CTLFLAG_RW, 0, "USB uplcom");
115SYSCTL_INT(_hw_usb_uplcom, OID_AUTO, debug, CTLFLAG_RW,
116    &uplcom_debug, 0, "Debug level");
117#endif
118
119#define	UPLCOM_MODVER			1	/* module version */
120
121#define	UPLCOM_CONFIG_INDEX		0
122#define	UPLCOM_IFACE_INDEX		0
123#define	UPLCOM_SECOND_IFACE_INDEX	1
124
125#ifndef UPLCOM_INTR_INTERVAL
126#define	UPLCOM_INTR_INTERVAL		0	/* default */
127#endif
128
129#define	UPLCOM_BULK_BUF_SIZE 1024	/* bytes */
130
131#define	UPLCOM_SET_REQUEST		0x01
132#define	UPLCOM_SET_CRTSCTS		0x41
133#define	UPLCOM_SET_CRTSCTS_PL2303X	0x61
134#define	RSAQ_STATUS_CTS			0x80
135#define	RSAQ_STATUS_OVERRUN_ERROR	0x40
136#define	RSAQ_STATUS_PARITY_ERROR	0x20
137#define	RSAQ_STATUS_FRAME_ERROR	0x10
138#define	RSAQ_STATUS_RING		0x08
139#define	RSAQ_STATUS_BREAK_ERROR	0x04
140#define	RSAQ_STATUS_DSR			0x02
141#define	RSAQ_STATUS_DCD			0x01
142
143#define	TYPE_PL2303			0
144#define	TYPE_PL2303HX			1
145#define	TYPE_PL2303HXD			2
146
147#define	UPLCOM_STATE_INDEX		8
148
149enum {
150	UPLCOM_BULK_DT_WR,
151	UPLCOM_BULK_DT_RD,
152	UPLCOM_INTR_DT_RD,
153	UPLCOM_N_TRANSFER,
154};
155
156struct uplcom_softc {
157	struct ucom_super_softc sc_super_ucom;
158	struct ucom_softc sc_ucom;
159
160	struct usb_xfer *sc_xfer[UPLCOM_N_TRANSFER];
161	struct usb_device *sc_udev;
162	struct mtx sc_mtx;
163
164	uint16_t sc_line;
165
166	uint8_t	sc_lsr;			/* local status register */
167	uint8_t	sc_msr;			/* uplcom status register */
168	uint8_t	sc_chiptype;		/* type of chip */
169	uint8_t	sc_ctrl_iface_no;
170	uint8_t	sc_data_iface_no;
171	uint8_t	sc_iface_index[2];
172};
173
174/* prototypes */
175
176static usb_error_t uplcom_reset(struct uplcom_softc *, struct usb_device *);
177static usb_error_t uplcom_pl2303_do(struct usb_device *, uint8_t, uint8_t,
178			uint16_t, uint16_t, uint16_t);
179static int	uplcom_pl2303_init(struct usb_device *, uint8_t);
180static void	uplcom_free(struct ucom_softc *);
181static void	uplcom_cfg_set_dtr(struct ucom_softc *, uint8_t);
182static void	uplcom_cfg_set_rts(struct ucom_softc *, uint8_t);
183static void	uplcom_cfg_set_break(struct ucom_softc *, uint8_t);
184static int	uplcom_pre_param(struct ucom_softc *, struct termios *);
185static void	uplcom_cfg_param(struct ucom_softc *, struct termios *);
186static void	uplcom_start_read(struct ucom_softc *);
187static void	uplcom_stop_read(struct ucom_softc *);
188static void	uplcom_start_write(struct ucom_softc *);
189static void	uplcom_stop_write(struct ucom_softc *);
190static void	uplcom_cfg_get_status(struct ucom_softc *, uint8_t *,
191		    uint8_t *);
192static void	uplcom_poll(struct ucom_softc *ucom);
193
194static device_probe_t uplcom_probe;
195static device_attach_t uplcom_attach;
196static device_detach_t uplcom_detach;
197static void uplcom_free_softc(struct uplcom_softc *);
198
199static usb_callback_t uplcom_intr_callback;
200static usb_callback_t uplcom_write_callback;
201static usb_callback_t uplcom_read_callback;
202
203static const struct usb_config uplcom_config_data[UPLCOM_N_TRANSFER] = {
204
205	[UPLCOM_BULK_DT_WR] = {
206		.type = UE_BULK,
207		.endpoint = UE_ADDR_ANY,
208		.direction = UE_DIR_OUT,
209		.bufsize = UPLCOM_BULK_BUF_SIZE,
210		.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
211		.callback = &uplcom_write_callback,
212		.if_index = 0,
213	},
214
215	[UPLCOM_BULK_DT_RD] = {
216		.type = UE_BULK,
217		.endpoint = UE_ADDR_ANY,
218		.direction = UE_DIR_IN,
219		.bufsize = UPLCOM_BULK_BUF_SIZE,
220		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
221		.callback = &uplcom_read_callback,
222		.if_index = 0,
223	},
224
225	[UPLCOM_INTR_DT_RD] = {
226		.type = UE_INTERRUPT,
227		.endpoint = UE_ADDR_ANY,
228		.direction = UE_DIR_IN,
229		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
230		.bufsize = 0,	/* use wMaxPacketSize */
231		.callback = &uplcom_intr_callback,
232		.if_index = 1,
233	},
234};
235
236static struct ucom_callback uplcom_callback = {
237	.ucom_cfg_get_status = &uplcom_cfg_get_status,
238	.ucom_cfg_set_dtr = &uplcom_cfg_set_dtr,
239	.ucom_cfg_set_rts = &uplcom_cfg_set_rts,
240	.ucom_cfg_set_break = &uplcom_cfg_set_break,
241	.ucom_cfg_param = &uplcom_cfg_param,
242	.ucom_pre_param = &uplcom_pre_param,
243	.ucom_start_read = &uplcom_start_read,
244	.ucom_stop_read = &uplcom_stop_read,
245	.ucom_start_write = &uplcom_start_write,
246	.ucom_stop_write = &uplcom_stop_write,
247	.ucom_poll = &uplcom_poll,
248	.ucom_free = &uplcom_free,
249};
250
251#define	UPLCOM_DEV(v,p)				\
252  { USB_VENDOR(USB_VENDOR_##v), USB_PRODUCT(USB_PRODUCT_##v##_##p) }
253
254static const STRUCT_USB_HOST_ID uplcom_devs[] = {
255	UPLCOM_DEV(ACERP, S81),			/* BenQ S81 phone */
256	UPLCOM_DEV(ADLINK, ND6530),		/* ADLINK ND-6530 USB-Serial */
257	UPLCOM_DEV(ALCATEL, OT535),		/* Alcatel One Touch 535/735 */
258	UPLCOM_DEV(ALCOR, AU9720),		/* Alcor AU9720 USB 2.0-RS232 */
259	UPLCOM_DEV(ANCHOR, SERIAL),		/* Anchor Serial adapter */
260	UPLCOM_DEV(ATEN, UC232A),		/* PLANEX USB-RS232 URS-03 */
261	UPLCOM_DEV(BELKIN, F5U257),		/* Belkin F5U257 USB to Serial */
262	UPLCOM_DEV(COREGA, CGUSBRS232R),	/* Corega CG-USBRS232R */
263	UPLCOM_DEV(EPSON, CRESSI_EDY),		/* Cressi Edy diving computer */
264	UPLCOM_DEV(EPSON, N2ITION3),		/* Zeagle N2iTion3 diving computer */
265	UPLCOM_DEV(ELECOM, UCSGT),		/* ELECOM UC-SGT Serial Adapter */
266	UPLCOM_DEV(ELECOM, UCSGT0),		/* ELECOM UC-SGT Serial Adapter */
267	UPLCOM_DEV(HAL, IMR001),		/* HAL Corporation Crossam2+USB */
268	UPLCOM_DEV(HP, LD220),			/* HP LD220 POS Display */
269	UPLCOM_DEV(IODATA, USBRSAQ),		/* I/O DATA USB-RSAQ */
270	UPLCOM_DEV(IODATA, USBRSAQ5),		/* I/O DATA USB-RSAQ5 */
271	UPLCOM_DEV(ITEGNO, WM1080A),		/* iTegno WM1080A GSM/GFPRS modem */
272	UPLCOM_DEV(ITEGNO, WM2080A),		/* iTegno WM2080A CDMA modem */
273	UPLCOM_DEV(LEADTEK, 9531),		/* Leadtek 9531 GPS */
274	UPLCOM_DEV(MICROSOFT, 700WX),		/* Microsoft Palm 700WX */
275	UPLCOM_DEV(MOBILEACTION, MA620),	/* Mobile Action MA-620 Infrared Adapter */
276	UPLCOM_DEV(NETINDEX, WS002IN),		/* Willcom W-S002IN */
277	UPLCOM_DEV(NOKIA2, CA42),		/* Nokia CA-42 cable */
278	UPLCOM_DEV(OTI, DKU5),			/* OTI DKU-5 cable */
279	UPLCOM_DEV(PANASONIC, TYTP50P6S),	/* Panasonic TY-TP50P6-S flat screen */
280	UPLCOM_DEV(PLX, CA42),			/* PLX CA-42 clone cable */
281	UPLCOM_DEV(PROLIFIC, ALLTRONIX_GPRS),	/* Alltronix ACM003U00 modem */
282	UPLCOM_DEV(PROLIFIC, ALDIGA_AL11U),	/* AlDiga AL-11U modem */
283	UPLCOM_DEV(PROLIFIC, DCU11),		/* DCU-11 Phone Cable */
284	UPLCOM_DEV(PROLIFIC, HCR331),		/* HCR331 Card Reader */
285	UPLCOM_DEV(PROLIFIC, MICROMAX_610U),	/* Micromax 610U modem */
286	UPLCOM_DEV(PROLIFIC, MOTOROLA),		/* Motorola cable */
287	UPLCOM_DEV(PROLIFIC, PHAROS),		/* Prolific Pharos */
288	UPLCOM_DEV(PROLIFIC, PL2303),		/* Generic adapter */
289	UPLCOM_DEV(PROLIFIC, RSAQ2),		/* I/O DATA USB-RSAQ2 */
290	UPLCOM_DEV(PROLIFIC, RSAQ3),		/* I/O DATA USB-RSAQ3 */
291	UPLCOM_DEV(PROLIFIC, UIC_MSR206),	/* UIC MSR206 Card Reader */
292	UPLCOM_DEV(PROLIFIC2, PL2303),		/* Prolific adapter */
293	UPLCOM_DEV(RADIOSHACK, USBCABLE),	/* Radio Shack USB Adapter */
294	UPLCOM_DEV(RATOC, REXUSB60),		/* RATOC REX-USB60 */
295	UPLCOM_DEV(SAGEM, USBSERIAL),		/* Sagem USB-Serial Controller */
296	UPLCOM_DEV(SAMSUNG, I330),		/* Samsung I330 phone cradle */
297	UPLCOM_DEV(SANWA, KB_USB2),		/* Sanwa KB-USB2 Multimeter cable */
298	UPLCOM_DEV(SIEMENS3, EF81),		/* Siemens EF81 */
299	UPLCOM_DEV(SIEMENS3, SX1),		/* Siemens SX1 */
300	UPLCOM_DEV(SIEMENS3, X65),		/* Siemens X65 */
301	UPLCOM_DEV(SIEMENS3, X75),		/* Siemens X75 */
302	UPLCOM_DEV(SITECOM, SERIAL),		/* Sitecom USB to Serial */
303	UPLCOM_DEV(SMART, PL2303),		/* SMART Technologies USB to Serial */
304	UPLCOM_DEV(SONY, QN3),			/* Sony QN3 phone cable */
305	UPLCOM_DEV(SONYERICSSON, DATAPILOT),	/* Sony Ericsson Datapilot */
306	UPLCOM_DEV(SONYERICSSON, DCU10),	/* Sony Ericsson DCU-10 Cable */
307	UPLCOM_DEV(SOURCENEXT, KEIKAI8),	/* SOURCENEXT KeikaiDenwa 8 */
308	UPLCOM_DEV(SOURCENEXT, KEIKAI8_CHG),	/* SOURCENEXT KeikaiDenwa 8 with charger */
309	UPLCOM_DEV(SPEEDDRAGON, MS3303H),	/* Speed Dragon USB-Serial */
310	UPLCOM_DEV(SYNTECH, CPT8001C),		/* Syntech CPT-8001C Barcode scanner */
311	UPLCOM_DEV(TDK, UHA6400),		/* TDK USB-PHS Adapter UHA6400 */
312	UPLCOM_DEV(TDK, UPA9664),		/* TDK USB-PHS Adapter UPA9664 */
313	UPLCOM_DEV(TRIPPLITE, U209),		/* Tripp-Lite U209-000-R USB to Serial */
314	UPLCOM_DEV(YCCABLE, PL2303),		/* YC Cable USB-Serial */
315};
316#undef UPLCOM_DEV
317
318static device_method_t uplcom_methods[] = {
319	DEVMETHOD(device_probe, uplcom_probe),
320	DEVMETHOD(device_attach, uplcom_attach),
321	DEVMETHOD(device_detach, uplcom_detach),
322	DEVMETHOD_END
323};
324
325static devclass_t uplcom_devclass;
326
327static driver_t uplcom_driver = {
328	.name = "uplcom",
329	.methods = uplcom_methods,
330	.size = sizeof(struct uplcom_softc),
331};
332
333DRIVER_MODULE(uplcom, uhub, uplcom_driver, uplcom_devclass, NULL, 0);
334MODULE_DEPEND(uplcom, ucom, 1, 1, 1);
335MODULE_DEPEND(uplcom, usb, 1, 1, 1);
336MODULE_VERSION(uplcom, UPLCOM_MODVER);
337
338static int
339uplcom_probe(device_t dev)
340{
341	struct usb_attach_arg *uaa = device_get_ivars(dev);
342
343	DPRINTFN(11, "\n");
344
345	if (uaa->usb_mode != USB_MODE_HOST) {
346		return (ENXIO);
347	}
348	if (uaa->info.bConfigIndex != UPLCOM_CONFIG_INDEX) {
349		return (ENXIO);
350	}
351	if (uaa->info.bIfaceIndex != UPLCOM_IFACE_INDEX) {
352		return (ENXIO);
353	}
354	return (usbd_lookup_id_by_uaa(uplcom_devs, sizeof(uplcom_devs), uaa));
355}
356
357static int
358uplcom_attach(device_t dev)
359{
360	struct usb_attach_arg *uaa = device_get_ivars(dev);
361	struct uplcom_softc *sc = device_get_softc(dev);
362	struct usb_interface *iface;
363	struct usb_interface_descriptor *id;
364	struct usb_device_descriptor *dd;
365	int error;
366
367	DPRINTFN(11, "\n");
368
369	device_set_usb_desc(dev);
370	mtx_init(&sc->sc_mtx, "uplcom", NULL, MTX_DEF);
371	ucom_ref(&sc->sc_super_ucom);
372
373	DPRINTF("sc = %p\n", sc);
374
375	sc->sc_udev = uaa->device;
376
377	dd = usbd_get_device_descriptor(sc->sc_udev);
378
379	switch (UGETW(dd->bcdDevice)) {
380	case 0x0300:
381		sc->sc_chiptype = TYPE_PL2303HX;
382		/* or TA, that is HX with external crystal */
383		break;
384	case 0x0400:
385		sc->sc_chiptype = TYPE_PL2303HXD;
386		/* or EA, that is HXD with ESD protection */
387		/* or RA, that has internal voltage level converter that works only up to 1Mbaud (!) */
388		break;
389	case 0x0500:
390		sc->sc_chiptype = TYPE_PL2303HXD;
391		/* in fact it's TB, that is HXD with external crystal */
392		break;
393	default:
394		/* NOTE: I have no info about the bcdDevice for the base PL2303 (up to 1.2Mbaud,
395		   only fixed rates) and for PL2303SA (8-pin chip, up to 115200 baud */
396		/* Determine the chip type.  This algorithm is taken from Linux. */
397		if (dd->bDeviceClass == 0x02)
398			sc->sc_chiptype = TYPE_PL2303;
399		else if (dd->bMaxPacketSize == 0x40)
400			sc->sc_chiptype = TYPE_PL2303HX;
401		else
402			sc->sc_chiptype = TYPE_PL2303;
403		break;
404	}
405
406	switch (sc->sc_chiptype) {
407	case TYPE_PL2303:
408		DPRINTF("chiptype: 2303\n");
409		break;
410	case TYPE_PL2303HX:
411		DPRINTF("chiptype: 2303HX/TA\n");
412		break;
413	case TYPE_PL2303HXD:
414		DPRINTF("chiptype: 2303HXD/TB/RA/EA\n");
415		break;
416	default:
417		DPRINTF("chiptype: unknown %d\n", sc->sc_chiptype);
418		break;
419	}
420
421	/*
422	 * USB-RSAQ1 has two interface
423	 *
424	 *  USB-RSAQ1       | USB-RSAQ2
425	 * -----------------+-----------------
426	 * Interface 0      |Interface 0
427	 *  Interrupt(0x81) | Interrupt(0x81)
428	 * -----------------+ BulkIN(0x02)
429	 * Interface 1	    | BulkOUT(0x83)
430	 *   BulkIN(0x02)   |
431	 *   BulkOUT(0x83)  |
432	 */
433
434	sc->sc_ctrl_iface_no = uaa->info.bIfaceNum;
435	sc->sc_iface_index[1] = UPLCOM_IFACE_INDEX;
436
437	iface = usbd_get_iface(uaa->device, UPLCOM_SECOND_IFACE_INDEX);
438	if (iface) {
439		id = usbd_get_interface_descriptor(iface);
440		if (id == NULL) {
441			device_printf(dev, "no interface descriptor (2)\n");
442			goto detach;
443		}
444		sc->sc_data_iface_no = id->bInterfaceNumber;
445		sc->sc_iface_index[0] = UPLCOM_SECOND_IFACE_INDEX;
446		usbd_set_parent_iface(uaa->device,
447		    UPLCOM_SECOND_IFACE_INDEX, uaa->info.bIfaceIndex);
448	} else {
449		sc->sc_data_iface_no = sc->sc_ctrl_iface_no;
450		sc->sc_iface_index[0] = UPLCOM_IFACE_INDEX;
451	}
452
453	error = usbd_transfer_setup(uaa->device,
454	    sc->sc_iface_index, sc->sc_xfer, uplcom_config_data,
455	    UPLCOM_N_TRANSFER, sc, &sc->sc_mtx);
456	if (error) {
457		DPRINTF("one or more missing USB endpoints, "
458		    "error=%s\n", usbd_errstr(error));
459		goto detach;
460	}
461	error = uplcom_reset(sc, uaa->device);
462	if (error) {
463		device_printf(dev, "reset failed, error=%s\n",
464		    usbd_errstr(error));
465		goto detach;
466	}
467
468	if (sc->sc_chiptype == TYPE_PL2303) {
469		/* HX variants seem to lock up after a clear stall request. */
470		mtx_lock(&sc->sc_mtx);
471		usbd_xfer_set_stall(sc->sc_xfer[UPLCOM_BULK_DT_WR]);
472		usbd_xfer_set_stall(sc->sc_xfer[UPLCOM_BULK_DT_RD]);
473		mtx_unlock(&sc->sc_mtx);
474	} else {
475		/* reset upstream data pipes */
476		if (uplcom_pl2303_do(sc->sc_udev, UT_WRITE_VENDOR_DEVICE,
477		    UPLCOM_SET_REQUEST, 8, 0, 0) ||
478		    uplcom_pl2303_do(sc->sc_udev, UT_WRITE_VENDOR_DEVICE,
479		    UPLCOM_SET_REQUEST, 9, 0, 0)) {
480			goto detach;
481		}
482	}
483
484	error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc,
485	    &uplcom_callback, &sc->sc_mtx);
486	if (error) {
487		goto detach;
488	}
489	/*
490	 * do the initialization during attach so that the system does not
491	 * sleep during open:
492	 */
493	if (uplcom_pl2303_init(uaa->device, sc->sc_chiptype)) {
494		device_printf(dev, "init failed\n");
495		goto detach;
496	}
497	ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev);
498
499	return (0);
500
501detach:
502	uplcom_detach(dev);
503	return (ENXIO);
504}
505
506static int
507uplcom_detach(device_t dev)
508{
509	struct uplcom_softc *sc = device_get_softc(dev);
510
511	DPRINTF("sc=%p\n", sc);
512
513	ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom);
514	usbd_transfer_unsetup(sc->sc_xfer, UPLCOM_N_TRANSFER);
515
516	device_claim_softc(dev);
517
518	uplcom_free_softc(sc);
519
520	return (0);
521}
522
523UCOM_UNLOAD_DRAIN(uplcom);
524
525static void
526uplcom_free_softc(struct uplcom_softc *sc)
527{
528	if (ucom_unref(&sc->sc_super_ucom)) {
529		mtx_destroy(&sc->sc_mtx);
530		device_free_softc(sc);
531	}
532}
533
534static void
535uplcom_free(struct ucom_softc *ucom)
536{
537	uplcom_free_softc(ucom->sc_parent);
538}
539
540static usb_error_t
541uplcom_reset(struct uplcom_softc *sc, struct usb_device *udev)
542{
543	struct usb_device_request req;
544
545	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
546	req.bRequest = UPLCOM_SET_REQUEST;
547	USETW(req.wValue, 0);
548	req.wIndex[0] = sc->sc_data_iface_no;
549	req.wIndex[1] = 0;
550	USETW(req.wLength, 0);
551
552	return (usbd_do_request(udev, NULL, &req, NULL));
553}
554
555static usb_error_t
556uplcom_pl2303_do(struct usb_device *udev, uint8_t req_type, uint8_t request,
557    uint16_t value, uint16_t index, uint16_t length)
558{
559	struct usb_device_request req;
560	usb_error_t err;
561	uint8_t buf[4];
562
563	req.bmRequestType = req_type;
564	req.bRequest = request;
565	USETW(req.wValue, value);
566	USETW(req.wIndex, index);
567	USETW(req.wLength, length);
568
569	err = usbd_do_request(udev, NULL, &req, buf);
570	if (err) {
571		DPRINTF("error=%s\n", usbd_errstr(err));
572		return (1);
573	}
574	return (0);
575}
576
577static int
578uplcom_pl2303_init(struct usb_device *udev, uint8_t chiptype)
579{
580	int err;
581
582	if (uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1)
583	    || uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x0404, 0, 0)
584	    || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1)
585	    || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8383, 0, 1)
586	    || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1)
587	    || uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x0404, 1, 0)
588	    || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1)
589	    || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8383, 0, 1)
590	    || uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0, 1, 0)
591	    || uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 1, 0, 0))
592		return (EIO);
593
594	if (chiptype != TYPE_PL2303)
595		err = uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 2, 0x44, 0);
596	else
597		err = uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 2, 0x24, 0);
598	if (err)
599		return (EIO);
600
601	return (0);
602}
603
604static void
605uplcom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff)
606{
607	struct uplcom_softc *sc = ucom->sc_parent;
608	struct usb_device_request req;
609
610	DPRINTF("onoff = %d\n", onoff);
611
612	if (onoff)
613		sc->sc_line |= UCDC_LINE_DTR;
614	else
615		sc->sc_line &= ~UCDC_LINE_DTR;
616
617	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
618	req.bRequest = UCDC_SET_CONTROL_LINE_STATE;
619	USETW(req.wValue, sc->sc_line);
620	req.wIndex[0] = sc->sc_data_iface_no;
621	req.wIndex[1] = 0;
622	USETW(req.wLength, 0);
623
624	ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
625	    &req, NULL, 0, 1000);
626}
627
628static void
629uplcom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff)
630{
631	struct uplcom_softc *sc = ucom->sc_parent;
632	struct usb_device_request req;
633
634	DPRINTF("onoff = %d\n", onoff);
635
636	if (onoff)
637		sc->sc_line |= UCDC_LINE_RTS;
638	else
639		sc->sc_line &= ~UCDC_LINE_RTS;
640
641	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
642	req.bRequest = UCDC_SET_CONTROL_LINE_STATE;
643	USETW(req.wValue, sc->sc_line);
644	req.wIndex[0] = sc->sc_data_iface_no;
645	req.wIndex[1] = 0;
646	USETW(req.wLength, 0);
647
648	ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
649	    &req, NULL, 0, 1000);
650}
651
652static void
653uplcom_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff)
654{
655	struct uplcom_softc *sc = ucom->sc_parent;
656	struct usb_device_request req;
657	uint16_t temp;
658
659	DPRINTF("onoff = %d\n", onoff);
660
661	temp = (onoff ? UCDC_BREAK_ON : UCDC_BREAK_OFF);
662
663	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
664	req.bRequest = UCDC_SEND_BREAK;
665	USETW(req.wValue, temp);
666	req.wIndex[0] = sc->sc_data_iface_no;
667	req.wIndex[1] = 0;
668	USETW(req.wLength, 0);
669
670	ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
671	    &req, NULL, 0, 1000);
672}
673
674/*
675 * NOTE: These baud rates are officially supported, they can be written
676 * directly into dwDTERate register.
677 *
678 * Free baudrate setting is not supported by the base PL2303, and on
679 * other models it requires writing a divisor value to dwDTERate instead
680 * of the raw baudrate. The formula for divisor calculation is not published
681 * by the vendor, so it is speculative, though the official product homepage
682 * refers to the Linux module source as a reference implementation.
683 */
684static const uint32_t uplcom_rates[] = {
685	/*
686	 * Basic 'standard' speed rates, supported by all models
687	 * NOTE: 900 and 56000 actually works as well
688	 */
689	75, 150, 300, 600, 900, 1200, 1800, 2400, 3600, 4800, 7200, 9600, 14400,
690	19200, 28800, 38400, 56000, 57600, 115200,
691	/*
692	 * Advanced speed rates up to 6Mbs, supported by HX/TA and HXD/TB/EA/RA
693     * NOTE: regardless of the spec, 256000 does not work
694	 */
695	128000, 134400, 161280, 201600, 230400, 268800, 403200, 460800, 614400,
696	806400, 921600, 1228800, 2457600, 3000000, 6000000,
697	/*
698	 * Advanced speed rates up to 12, supported by HXD/TB/EA/RA
699	 */
700	12000000
701};
702
703#define	N_UPLCOM_RATES	(sizeof(uplcom_rates)/sizeof(uplcom_rates[0]))
704
705static int
706uplcom_baud_supported(unsigned int speed)
707{
708	int i;
709	for (i = 0; i < N_UPLCOM_RATES; i++) {
710		if (uplcom_rates[i] == speed)
711			return 1;
712	}
713	return 0;
714}
715
716static int
717uplcom_pre_param(struct ucom_softc *ucom, struct termios *t)
718{
719	struct uplcom_softc *sc = ucom->sc_parent;
720
721	DPRINTF("\n");
722
723	/**
724	 * Check requested baud rate.
725	 *
726	 * The PL2303 can only set specific baud rates, up to 1228800 baud.
727	 * The PL2303HX can set any baud rate up to 6Mb.
728	 * The PL2303HX rev. D can set any baud rate up to 12Mb.
729	 *
730	 */
731
732	/* accept raw divisor data, if someone wants to do the math in user domain */
733	if (t->c_ospeed & 0x80000000)
734		return 0;
735	switch (sc->sc_chiptype) {
736		case TYPE_PL2303HXD:
737			if (t->c_ospeed <= 12000000)
738				return (0);
739			break;
740		case TYPE_PL2303HX:
741			if (t->c_ospeed <= 6000000)
742				return (0);
743			break;
744		default:
745			if (uplcom_baud_supported(t->c_ospeed))
746				return (0);
747			break;
748	}
749
750	DPRINTF("uplcom_param: bad baud rate (%d)\n", t->c_ospeed);
751	return (EIO);
752}
753
754static unsigned int
755uplcom_encode_baud_rate_divisor(uint8_t *buf, unsigned int baud)
756{
757	unsigned int baseline, mantissa, exponent;
758
759	/* Determine the baud rate divisor. This algorithm is taken from Linux. */
760	/*
761	 * Apparently the formula is:
762	 *   baudrate = baseline / (mantissa * 4^exponent)
763	 * where
764	 *   mantissa = buf[8:0]
765	 *   exponent = buf[11:9]
766	 */
767	if (baud == 0)
768		baud = 1;
769	baseline = 383385600;
770	mantissa = baseline / baud;
771	if (mantissa == 0)
772		mantissa = 1;
773	exponent = 0;
774	while (mantissa >= 512) {
775		if (exponent < 7) {
776			mantissa >>= 2;	/* divide by 4 */
777			exponent++;
778		} else {
779			/* Exponent is maxed. Trim mantissa and leave. This gives approx. 45.8 baud */
780			mantissa = 511;
781			break;
782		}
783	}
784
785	buf[3] = 0x80;
786	buf[2] = 0;
787	buf[1] = exponent << 1 | mantissa >> 8;
788	buf[0] = mantissa & 0xff;
789
790	/* Calculate and return the exact baud rate. */
791	baud = (baseline / mantissa) >> (exponent << 1);
792	DPRINTF("real baud rate will be %u\n", baud);
793
794	return baud;
795}
796static void
797uplcom_cfg_param(struct ucom_softc *ucom, struct termios *t)
798{
799	struct uplcom_softc *sc = ucom->sc_parent;
800	struct usb_cdc_line_state ls;
801	struct usb_device_request req;
802
803	DPRINTF("sc = %p\n", sc);
804
805	memset(&ls, 0, sizeof(ls));
806
807	/*
808	 * NOTE: If unsupported baud rates are set directly, the PL2303* uses 9600 baud.
809	 */
810	if ((t->c_ospeed & 0x80000000) || uplcom_baud_supported(t->c_ospeed))
811		USETDW(ls.dwDTERate, t->c_ospeed);
812	else
813		t->c_ospeed = uplcom_encode_baud_rate_divisor((uint8_t*)&ls.dwDTERate, t->c_ospeed);
814
815	if (t->c_cflag & CSTOPB) {
816		if ((t->c_cflag & CSIZE) == CS5) {
817			/*
818			 * NOTE: Comply with "real" UARTs / RS232:
819			 *       use 1.5 instead of 2 stop bits with 5 data bits
820			 */
821			ls.bCharFormat = UCDC_STOP_BIT_1_5;
822		} else {
823			ls.bCharFormat = UCDC_STOP_BIT_2;
824		}
825	} else {
826		ls.bCharFormat = UCDC_STOP_BIT_1;
827	}
828
829	if (t->c_cflag & PARENB) {
830		if (t->c_cflag & PARODD) {
831			ls.bParityType = UCDC_PARITY_ODD;
832		} else {
833			ls.bParityType = UCDC_PARITY_EVEN;
834		}
835	} else {
836		ls.bParityType = UCDC_PARITY_NONE;
837	}
838
839	switch (t->c_cflag & CSIZE) {
840	case CS5:
841		ls.bDataBits = 5;
842		break;
843	case CS6:
844		ls.bDataBits = 6;
845		break;
846	case CS7:
847		ls.bDataBits = 7;
848		break;
849	case CS8:
850		ls.bDataBits = 8;
851		break;
852	}
853
854	DPRINTF("rate=0x%08x fmt=%d parity=%d bits=%d\n",
855	    UGETDW(ls.dwDTERate), ls.bCharFormat,
856	    ls.bParityType, ls.bDataBits);
857
858	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
859	req.bRequest = UCDC_SET_LINE_CODING;
860	USETW(req.wValue, 0);
861	req.wIndex[0] = sc->sc_data_iface_no;
862	req.wIndex[1] = 0;
863	USETW(req.wLength, UCDC_LINE_STATE_LENGTH);
864
865	ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
866	    &req, &ls, 0, 1000);
867
868	if (t->c_cflag & CRTSCTS) {
869
870		DPRINTF("crtscts = on\n");
871
872		req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
873		req.bRequest = UPLCOM_SET_REQUEST;
874		USETW(req.wValue, 0);
875		if (sc->sc_chiptype != TYPE_PL2303)
876			USETW(req.wIndex, UPLCOM_SET_CRTSCTS_PL2303X);
877		else
878			USETW(req.wIndex, UPLCOM_SET_CRTSCTS);
879		USETW(req.wLength, 0);
880
881		ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
882		    &req, NULL, 0, 1000);
883	} else {
884		req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
885		req.bRequest = UPLCOM_SET_REQUEST;
886		USETW(req.wValue, 0);
887		USETW(req.wIndex, 0);
888		USETW(req.wLength, 0);
889		ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom,
890		    &req, NULL, 0, 1000);
891	}
892}
893
894static void
895uplcom_start_read(struct ucom_softc *ucom)
896{
897	struct uplcom_softc *sc = ucom->sc_parent;
898
899	/* start interrupt endpoint */
900	usbd_transfer_start(sc->sc_xfer[UPLCOM_INTR_DT_RD]);
901
902	/* start read endpoint */
903	usbd_transfer_start(sc->sc_xfer[UPLCOM_BULK_DT_RD]);
904}
905
906static void
907uplcom_stop_read(struct ucom_softc *ucom)
908{
909	struct uplcom_softc *sc = ucom->sc_parent;
910
911	/* stop interrupt endpoint */
912	usbd_transfer_stop(sc->sc_xfer[UPLCOM_INTR_DT_RD]);
913
914	/* stop read endpoint */
915	usbd_transfer_stop(sc->sc_xfer[UPLCOM_BULK_DT_RD]);
916}
917
918static void
919uplcom_start_write(struct ucom_softc *ucom)
920{
921	struct uplcom_softc *sc = ucom->sc_parent;
922
923	usbd_transfer_start(sc->sc_xfer[UPLCOM_BULK_DT_WR]);
924}
925
926static void
927uplcom_stop_write(struct ucom_softc *ucom)
928{
929	struct uplcom_softc *sc = ucom->sc_parent;
930
931	usbd_transfer_stop(sc->sc_xfer[UPLCOM_BULK_DT_WR]);
932}
933
934static void
935uplcom_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr)
936{
937	struct uplcom_softc *sc = ucom->sc_parent;
938
939	DPRINTF("\n");
940
941	*lsr = sc->sc_lsr;
942	*msr = sc->sc_msr;
943}
944
945static void
946uplcom_intr_callback(struct usb_xfer *xfer, usb_error_t error)
947{
948	struct uplcom_softc *sc = usbd_xfer_softc(xfer);
949	struct usb_page_cache *pc;
950	uint8_t buf[9];
951	int actlen;
952
953	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
954
955	switch (USB_GET_STATE(xfer)) {
956	case USB_ST_TRANSFERRED:
957
958		DPRINTF("actlen = %u\n", actlen);
959
960		if (actlen >= 9) {
961
962			pc = usbd_xfer_get_frame(xfer, 0);
963			usbd_copy_out(pc, 0, buf, sizeof(buf));
964
965			DPRINTF("status = 0x%02x\n", buf[UPLCOM_STATE_INDEX]);
966
967			sc->sc_lsr = 0;
968			sc->sc_msr = 0;
969
970			if (buf[UPLCOM_STATE_INDEX] & RSAQ_STATUS_CTS) {
971				sc->sc_msr |= SER_CTS;
972			}
973			if (buf[UPLCOM_STATE_INDEX] & RSAQ_STATUS_OVERRUN_ERROR) {
974				sc->sc_lsr |= ULSR_OE;
975			}
976			if (buf[UPLCOM_STATE_INDEX] & RSAQ_STATUS_PARITY_ERROR) {
977				sc->sc_lsr |= ULSR_PE;
978			}
979			if (buf[UPLCOM_STATE_INDEX] & RSAQ_STATUS_FRAME_ERROR) {
980				sc->sc_lsr |= ULSR_FE;
981			}
982			if (buf[UPLCOM_STATE_INDEX] & RSAQ_STATUS_RING) {
983				sc->sc_msr |= SER_RI;
984			}
985			if (buf[UPLCOM_STATE_INDEX] & RSAQ_STATUS_BREAK_ERROR) {
986				sc->sc_lsr |= ULSR_BI;
987			}
988			if (buf[UPLCOM_STATE_INDEX] & RSAQ_STATUS_DSR) {
989				sc->sc_msr |= SER_DSR;
990			}
991			if (buf[UPLCOM_STATE_INDEX] & RSAQ_STATUS_DCD) {
992				sc->sc_msr |= SER_DCD;
993			}
994			ucom_status_change(&sc->sc_ucom);
995		}
996	case USB_ST_SETUP:
997tr_setup:
998		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
999		usbd_transfer_submit(xfer);
1000		return;
1001
1002	default:			/* Error */
1003		if (error != USB_ERR_CANCELLED) {
1004			/* try to clear stall first */
1005			usbd_xfer_set_stall(xfer);
1006			goto tr_setup;
1007		}
1008		return;
1009	}
1010}
1011
1012static void
1013uplcom_write_callback(struct usb_xfer *xfer, usb_error_t error)
1014{
1015	struct uplcom_softc *sc = usbd_xfer_softc(xfer);
1016	struct usb_page_cache *pc;
1017	uint32_t actlen;
1018
1019	switch (USB_GET_STATE(xfer)) {
1020	case USB_ST_SETUP:
1021	case USB_ST_TRANSFERRED:
1022tr_setup:
1023		pc = usbd_xfer_get_frame(xfer, 0);
1024		if (ucom_get_data(&sc->sc_ucom, pc, 0,
1025		    UPLCOM_BULK_BUF_SIZE, &actlen)) {
1026
1027			DPRINTF("actlen = %d\n", actlen);
1028
1029			usbd_xfer_set_frame_len(xfer, 0, actlen);
1030			usbd_transfer_submit(xfer);
1031		}
1032		return;
1033
1034	default:			/* Error */
1035		if (error != USB_ERR_CANCELLED) {
1036			/* try to clear stall first */
1037			usbd_xfer_set_stall(xfer);
1038			goto tr_setup;
1039		}
1040		return;
1041	}
1042}
1043
1044static void
1045uplcom_read_callback(struct usb_xfer *xfer, usb_error_t error)
1046{
1047	struct uplcom_softc *sc = usbd_xfer_softc(xfer);
1048	struct usb_page_cache *pc;
1049	int actlen;
1050
1051	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1052
1053	switch (USB_GET_STATE(xfer)) {
1054	case USB_ST_TRANSFERRED:
1055		pc = usbd_xfer_get_frame(xfer, 0);
1056		ucom_put_data(&sc->sc_ucom, pc, 0, actlen);
1057
1058	case USB_ST_SETUP:
1059tr_setup:
1060		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1061		usbd_transfer_submit(xfer);
1062		return;
1063
1064	default:			/* Error */
1065		if (error != USB_ERR_CANCELLED) {
1066			/* try to clear stall first */
1067			usbd_xfer_set_stall(xfer);
1068			goto tr_setup;
1069		}
1070		return;
1071	}
1072}
1073
1074static void
1075uplcom_poll(struct ucom_softc *ucom)
1076{
1077	struct uplcom_softc *sc = ucom->sc_parent;
1078	usbd_transfer_poll(sc->sc_xfer, UPLCOM_N_TRANSFER);
1079}
1080