xref: /linux/drivers/usb/serial/ftdi_sio.c (revision 13abf8130139c2ccd4962a7e5a8902be5e6cb5a7)
1 /*
2  * USB FTDI SIO driver
3  *
4  * 	Copyright (C) 1999 - 2001
5  * 	    Greg Kroah-Hartman (greg@kroah.com)
6  *          Bill Ryder (bryder@sgi.com)
7  *	Copyright (C) 2002
8  *	    Kuba Ober (kuba@mareimbrium.org)
9  *
10  * 	This program is free software; you can redistribute it and/or modify
11  * 	it under the terms of the GNU General Public License as published by
12  * 	the Free Software Foundation; either version 2 of the License, or
13  * 	(at your option) any later version.
14  *
15  * See Documentation/usb/usb-serial.txt for more information on using this driver
16  *
17  * See http://ftdi-usb-sio.sourceforge.net for upto date testing info
18  *	and extra documentation
19  *
20  * (21/Jul/2004) Ian Abbott
21  *      Incorporated Steven Turner's code to add support for the FT2232C chip.
22  *      The prelimilary port to the 2.6 kernel was by Rus V. Brushkoff.  I have
23  *      fixed a couple of things.
24  *
25  * (27/May/2004) Ian Abbott
26  *      Improved throttling code, mostly stolen from the WhiteHEAT driver.
27  *
28  * (26/Mar/2004) Jan Capek
29  *      Added PID's for ICD-U20/ICD-U40 - incircuit PIC debuggers from CCS Inc.
30  *
31  * (09/Feb/2004) Ian Abbott
32  *      Changed full name of USB-UIRT device to avoid "/" character.
33  *      Added FTDI's alternate PID (0x6006) for FT232/245 devices.
34  *      Added PID for "ELV USB Module UO100" from Stefan Frings.
35  *
36  * (21/Oct/2003) Ian Abbott
37  *      Renamed some VID/PID macros for Matrix Orbital and Perle Systems
38  *      devices.  Removed Matrix Orbital and Perle Systems devices from the
39  *      8U232AM device table, but left them in the FT232BM table, as they are
40  *      known to use only FT232BM.
41  *
42  * (17/Oct/2003) Scott Allen
43  *      Added vid/pid for Perle Systems UltraPort USB serial converters
44  *
45  * (21/Sep/2003) Ian Abbott
46  *      Added VID/PID for Omnidirectional Control Technology US101 USB to
47  *      RS-232 adapter (also rebadged as Dick Smith Electronics XH6381).
48  *      VID/PID supplied by Donald Gordon.
49  *
50  * (19/Aug/2003) Ian Abbott
51  *      Freed urb's transfer buffer in write bulk callback.
52  *      Omitted some paranoid checks in write bulk callback that don't matter.
53  *      Scheduled work in write bulk callback regardless of port's open count.
54  *
55  * (05/Aug/2003) Ian Abbott
56  *      Added VID/PID for ID TECH IDT1221U USB to RS-232 adapter.
57  *      VID/PID provided by Steve Briggs.
58  *
59  * (23/Jul/2003) Ian Abbott
60  *      Added PIDs for CrystalFontz 547, 633, 631, 635, 640 and 640 from
61  *      Wayne Wylupski.
62  *
63  * (10/Jul/2003) David Glance
64  *      Added PID for DSS-20 SyncStation cradle for Sony-Ericsson P800.
65  *
66  * (27/Jun/2003) Ian Abbott
67  *	Reworked the urb handling logic.  We have no more pool, but dynamically
68  *	allocate the urb and the transfer buffer on the fly.  In testing this
69  *	does not incure any measurable overhead.  This also relies on the fact
70  *	that we have proper reference counting logic for urbs.  I nicked this
71  *	from Greg KH's Visor driver.
72  *
73  * (23/Jun/2003) Ian Abbott
74  *      Reduced flip buffer pushes and corrected a data length test in
75  *      ftdi_read_bulk_callback.
76  *      Defererence pointers after any paranoid checks, not before.
77  *
78  * (21/Jun/2003) Erik Nygren
79  *      Added support for Home Electronics Tira-1 IR transceiver using FT232BM chip.
80  *      See <http://www.home-electro.com/tira1.htm>.  Only operates properly
81  *      at 100000 and RTS-CTS, so set custom divisor mode on startup.
82  *      Also force the Tira-1 and USB-UIRT to only use their custom baud rates.
83  *
84  * (18/Jun/2003) Ian Abbott
85  *      Added Device ID of the USB relais from Rudolf Gugler (backported from
86  *      Philipp G�hring's patch for 2.5.x kernel).
87  *      Moved read transfer buffer reallocation into startup function.
88  *      Free existing write urb and transfer buffer in startup function.
89  *      Only use urbs in write urb pool that were successfully allocated.
90  *      Moved some constant macros out of functions.
91  *      Minor whitespace and comment changes.
92  *
93  * (12/Jun/2003) David Norwood
94  *      Added support for USB-UIRT IR transceiver using 8U232AM chip.
95  *      See <http://home.earthlink.net/~jrhees/USBUIRT/index.htm>.  Only
96  *      operates properly at 312500, so set custom divisor mode on startup.
97  *
98  * (12/Jun/2003) Ian Abbott
99  *      Added Sealevel SeaLINK+ 210x, 220x, 240x, 280x vid/pids from Tuan Hoang
100  *      - I've eliminated some that don't seem to exist!
101  *      Added Home Electronics Tira-1 IR transceiver pid from Chris Horn
102  *      Some whitespace/coding-style cleanups
103  *
104  * (11/Jun/2003) Ian Abbott
105  *      Fixed unsafe spinlock usage in ftdi_write
106  *
107  * (24/Feb/2003) Richard Shooter
108  *      Increase read buffer size to improve read speeds at higher baud rates
109  *      (specifically tested with up to 1Mb/sec at 1.5M baud)
110  *
111  * (23/Feb/2003) John Wilkins
112  *      Added Xon/xoff flow control (activating support in the ftdi device)
113  *      Added vid/pid for Videonetworks/Homechoice (UK ISP)
114  *
115  * (23/Feb/2003) Bill Ryder
116  *      Added matrix orb device vid/pids from Wayne Wylupski
117  *
118  * (19/Feb/2003) Ian Abbott
119  *      For TIOCSSERIAL, set alt_speed to 0 when ASYNC_SPD_MASK value has
120  *      changed to something other than ASYNC_SPD_HI, ASYNC_SPD_VHI,
121  *      ASYNC_SPD_SHI or ASYNC_SPD_WARP.  Also, unless ASYNC_SPD_CUST is in
122  *      force, don't bother changing baud rate when custom_divisor has changed.
123  *
124  * (18/Feb/2003) Ian Abbott
125  *      Fixed TIOCMGET handling to include state of DTR and RTS, the state
126  *      of which are now saved by set_dtr() and set_rts().
127  *      Fixed improper storage class for buf in set_dtr() and set_rts().
128  *      Added FT232BM chip type and support for its extra baud rates (compared
129  *      to FT8U232AM).
130  *      Took account of special case divisor values for highest baud rates of
131  *      FT8U232AM and FT232BM.
132  *      For TIOCSSERIAL, forced alt_speed to 0 when ASYNC_SPD_CUST kludge used,
133  *      as previous alt_speed setting is now stale.
134  *      Moved startup code common between the startup routines for the
135  *      different chip types into a common subroutine.
136  *
137  * (17/Feb/2003) Bill Ryder
138  *      Added write urb buffer pool on a per device basis
139  *      Added more checking for open file on callbacks (fixed OOPS)
140  *      Added CrystalFontz 632 and 634 PIDs
141  *         (thanx to CrystalFontz for the sample devices - they flushed out
142  *           some driver bugs)
143  *      Minor debugging message changes
144  *      Added throttle, unthrottle and chars_in_buffer functions
145  *      Fixed FTDI_SIO (the original device) bug
146  *      Fixed some shutdown handling
147  *
148  *
149  *
150  *
151  * (07/Jun/2002) Kuba Ober
152  *	Changed FTDI_SIO_BASE_BAUD_TO_DIVISOR macro into ftdi_baud_to_divisor
153  *	function. It was getting too complex.
154  *	Fix the divisor calculation logic which was setting divisor of 0.125
155  *	instead of 0.5 for fractional parts of divisor equal to 5/8, 6/8, 7/8.
156  *	Also make it bump up the divisor to next integer in case of 7/8 - it's
157  *	a better approximation.
158  *
159  * (25/Jul/2002) Bill Ryder inserted Dmitri's TIOCMIWAIT patch
160  *      Not tested by me but it doesn't break anything I use.
161  *
162  * (04/Jan/2002) Kuba Ober
163  *	Implemented 38400 baudrate kludge, where it can be substituted with other
164  *	  values. That's the only way to set custom baudrates.
165  *	Implemented TIOCSSERIAL, TIOCGSERIAL ioctl's so that setserial is happy.
166  *	FIXME: both baudrate things should eventually go to usbserial.c as other
167  *	  devices may need that functionality too. Actually, it can probably be
168  *	  merged in serial.c somehow - too many drivers repeat this code over
169  *	  and over.
170  *	Fixed baudrate forgetfulness - open() used to reset baudrate to 9600 every time.
171  *	Divisors for baudrates are calculated by a macro.
172  *	Small code cleanups. Ugly whitespace changes for Plato's sake only ;-].
173  *
174  * (04/Nov/2001) Bill Ryder
175  *	Fixed bug in read_bulk_callback where incorrect urb buffer was used.
176  *	Cleaned up write offset calculation
177  *	Added write_room since default values can be incorrect for sio
178  *	Changed write_bulk_callback to use same queue_task as other drivers
179  *        (the previous version caused panics)
180  *	Removed port iteration code since the device only has one I/O port and it
181  *	  was wrong anyway.
182  *
183  * (31/May/2001) gkh
184  *	Switched from using spinlock to a semaphore, which fixes lots of problems.
185  *
186  * (23/May/2001)   Bill Ryder
187  *	Added runtime debug patch (thanx Tyson D Sawyer).
188  *	Cleaned up comments for 8U232
189  *	Added parity, framing and overrun error handling
190  *	Added receive break handling.
191  *
192  * (04/08/2001) gb
193  *	Identify version on module load.
194  *
195  * (18/March/2001) Bill Ryder
196  *	(Not released)
197  *	Added send break handling. (requires kernel patch too)
198  *	Fixed 8U232AM hardware RTS/CTS etc status reporting.
199  *	Added flipbuf fix copied from generic device
200  *
201  * (12/3/2000) Bill Ryder
202  *	Added support for 8U232AM device.
203  *	Moved PID and VIDs into header file only.
204  *	Turned on low-latency for the tty (device will do high baudrates)
205  *	Added shutdown routine to close files when device removed.
206  *	More debug and error message cleanups.
207  *
208  * (11/13/2000) Bill Ryder
209  *	Added spinlock protected open code and close code.
210  *	Multiple opens work (sort of - see webpage mentioned above).
211  *	Cleaned up comments. Removed multiple PID/VID definitions.
212  *	Factorised cts/dtr code
213  *	Made use of __FUNCTION__ in dbg's
214  *
215  * (11/01/2000) Adam J. Richter
216  *	usb_device_id table support
217  *
218  * (10/05/2000) gkh
219  *	Fixed bug with urb->dev not being set properly, now that the usb
220  *	core needs it.
221  *
222  * (09/11/2000) gkh
223  *	Removed DEBUG #ifdefs with call to usb_serial_debug_data
224  *
225  * (07/19/2000) gkh
226  *	Added module_init and module_exit functions to handle the fact that this
227  *	driver is a loadable module now.
228  *
229  * (04/04/2000) Bill Ryder
230  *	Fixed bugs in TCGET/TCSET ioctls (by removing them - they are
231  *        handled elsewhere in the tty io driver chain).
232  *
233  * (03/30/2000) Bill Ryder
234  *	Implemented lots of ioctls
235  *	Fixed a race condition in write
236  *	Changed some dbg's to errs
237  *
238  * (03/26/2000) gkh
239  *	Split driver up into device specific pieces.
240  *
241  */
242 
243 /* Bill Ryder - bryder@sgi.com - wrote the FTDI_SIO implementation */
244 /* Thanx to FTDI for so kindly providing details of the protocol required */
245 /*   to talk to the device */
246 /* Thanx to gkh and the rest of the usb dev group for all code I have assimilated :-) */
247 
248 #include <linux/config.h>
249 #include <linux/kernel.h>
250 #include <linux/errno.h>
251 #include <linux/init.h>
252 #include <linux/slab.h>
253 #include <linux/tty.h>
254 #include <linux/tty_driver.h>
255 #include <linux/tty_flip.h>
256 #include <linux/module.h>
257 #include <linux/spinlock.h>
258 #include <asm/uaccess.h>
259 #include <linux/usb.h>
260 #include <linux/serial.h>
261 #include "usb-serial.h"
262 #include "ftdi_sio.h"
263 
264 /*
265  * Version Information
266  */
267 #define DRIVER_VERSION "v1.4.3"
268 #define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com>, Bill Ryder <bryder@sgi.com>, Kuba Ober <kuba@mareimbrium.org>"
269 #define DRIVER_DESC "USB FTDI Serial Converters Driver"
270 
271 static int debug;
272 
273 /* struct ftdi_sio_quirk is used by devices requiring special attention. */
274 struct ftdi_sio_quirk {
275 	void (*setup)(struct usb_serial *); /* Special settings during startup. */
276 };
277 
278 static void  ftdi_USB_UIRT_setup	(struct usb_serial *serial);
279 static void  ftdi_HE_TIRA1_setup	(struct usb_serial *serial);
280 
281 static struct ftdi_sio_quirk ftdi_USB_UIRT_quirk = {
282 	.setup = ftdi_USB_UIRT_setup,
283 };
284 
285 static struct ftdi_sio_quirk ftdi_HE_TIRA1_quirk = {
286 	.setup = ftdi_HE_TIRA1_setup,
287 };
288 
289 /*
290  * The 8U232AM has the same API as the sio except for:
291  * - it can support MUCH higher baudrates; up to:
292  *   o 921600 for RS232 and 2000000 for RS422/485 at 48MHz
293  *   o 230400 at 12MHz
294  *   so .. 8U232AM's baudrate setting codes are different
295  * - it has a two byte status code.
296  * - it returns characters every 16ms (the FTDI does it every 40ms)
297  *
298  * the bcdDevice value is used to differentiate FT232BM and FT245BM from
299  * the earlier FT8U232AM and FT8U232BM.  For now, include all known VID/PID
300  * combinations in both tables.
301  * FIXME: perhaps bcdDevice can also identify 12MHz FT8U232AM devices,
302  * but I don't know if those ever went into mass production. [Ian Abbott]
303  */
304 
305 
306 
307 static struct usb_device_id id_table_combined [] = {
308 	{ USB_DEVICE(FTDI_VID, FTDI_IRTRANS_PID) },
309 	{ USB_DEVICE(FTDI_VID, FTDI_SIO_PID) },
310 	{ USB_DEVICE(FTDI_VID, FTDI_8U232AM_PID) },
311 	{ USB_DEVICE(FTDI_VID, FTDI_8U232AM_ALT_PID) },
312 	{ USB_DEVICE(FTDI_VID, FTDI_8U2232C_PID) },
313 	{ USB_DEVICE(FTDI_VID, FTDI_RELAIS_PID) },
314 	{ USB_DEVICE(INTERBIOMETRICS_VID, INTERBIOMETRICS_IOBOARD_PID) },
315 	{ USB_DEVICE(INTERBIOMETRICS_VID, INTERBIOMETRICS_MINI_IOBOARD_PID) },
316 	{ USB_DEVICE(FTDI_VID, FTDI_XF_632_PID) },
317 	{ USB_DEVICE(FTDI_VID, FTDI_XF_634_PID) },
318 	{ USB_DEVICE(FTDI_VID, FTDI_XF_547_PID) },
319 	{ USB_DEVICE(FTDI_VID, FTDI_XF_633_PID) },
320 	{ USB_DEVICE(FTDI_VID, FTDI_XF_631_PID) },
321 	{ USB_DEVICE(FTDI_VID, FTDI_XF_635_PID) },
322 	{ USB_DEVICE(FTDI_VID, FTDI_XF_640_PID) },
323 	{ USB_DEVICE(FTDI_VID, FTDI_XF_642_PID) },
324 	{ USB_DEVICE(FTDI_VID, FTDI_DSS20_PID) },
325 	{ USB_DEVICE(FTDI_NF_RIC_VID, FTDI_NF_RIC_PID) },
326 	{ USB_DEVICE(FTDI_VID, FTDI_VNHCPCUSB_D_PID) },
327 	{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_0_PID) },
328 	{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_1_PID) },
329 	{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_2_PID) },
330 	{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_3_PID) },
331 	{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_4_PID) },
332 	{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_5_PID) },
333 	{ USB_DEVICE(FTDI_VID, FTDI_MTXORB_6_PID) },
334 	{ USB_DEVICE(FTDI_VID, FTDI_PERLE_ULTRAPORT_PID) },
335 	{ USB_DEVICE(FTDI_VID, FTDI_PIEGROUP_PID) },
336 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2101_PID) },
337 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2102_PID) },
338 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2103_PID) },
339 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2104_PID) },
340 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2201_1_PID) },
341 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2201_2_PID) },
342 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2202_1_PID) },
343 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2202_2_PID) },
344 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2203_1_PID) },
345 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2203_2_PID) },
346 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_1_PID) },
347 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_2_PID) },
348 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_3_PID) },
349 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2401_4_PID) },
350 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_1_PID) },
351 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_2_PID) },
352 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_3_PID) },
353 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2402_4_PID) },
354 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_1_PID) },
355 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_2_PID) },
356 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_3_PID) },
357 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2403_4_PID) },
358 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_1_PID) },
359 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_2_PID) },
360 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_3_PID) },
361 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_4_PID) },
362 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_5_PID) },
363 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_6_PID) },
364 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_7_PID) },
365 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2801_8_PID) },
366 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_1_PID) },
367 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_2_PID) },
368 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_3_PID) },
369 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_4_PID) },
370 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_5_PID) },
371 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_6_PID) },
372 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_7_PID) },
373 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2802_8_PID) },
374 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_1_PID) },
375 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_2_PID) },
376 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_3_PID) },
377 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_4_PID) },
378 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_5_PID) },
379 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_6_PID) },
380 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_7_PID) },
381 	{ USB_DEVICE(SEALEVEL_VID, SEALEVEL_2803_8_PID) },
382 	{ USB_DEVICE(IDTECH_VID, IDTECH_IDT1221U_PID) },
383 	{ USB_DEVICE(OCT_VID, OCT_US101_PID) },
384 	{ USB_DEVICE(FTDI_VID, FTDI_HE_TIRA1_PID),
385 		.driver_info = (kernel_ulong_t)&ftdi_HE_TIRA1_quirk },
386 	{ USB_DEVICE(FTDI_VID, FTDI_USB_UIRT_PID),
387 		.driver_info = (kernel_ulong_t)&ftdi_USB_UIRT_quirk },
388 	{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_1) },
389 	{ USB_DEVICE(FTDI_VID, PROTEGO_R2X0) },
390 	{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_3) },
391 	{ USB_DEVICE(FTDI_VID, PROTEGO_SPECIAL_4) },
392 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E808_PID) },
393 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E809_PID) },
394 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80A_PID) },
395 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80B_PID) },
396 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80C_PID) },
397 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80D_PID) },
398 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80E_PID) },
399 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E80F_PID) },
400 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E888_PID) },
401 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E889_PID) },
402 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88A_PID) },
403 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88B_PID) },
404 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88C_PID) },
405 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88D_PID) },
406 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88E_PID) },
407 	{ USB_DEVICE(FTDI_VID, FTDI_GUDEADS_E88F_PID) },
408 	{ USB_DEVICE(FTDI_VID, FTDI_ELV_UO100_PID) },
409 	{ USB_DEVICE(FTDI_VID, FTDI_ELV_UM100_PID) },
410  	{ USB_DEVICE(FTDI_VID, LINX_SDMUSBQSS_PID) },
411  	{ USB_DEVICE(FTDI_VID, LINX_MASTERDEVEL2_PID) },
412  	{ USB_DEVICE(FTDI_VID, LINX_FUTURE_0_PID) },
413  	{ USB_DEVICE(FTDI_VID, LINX_FUTURE_1_PID) },
414  	{ USB_DEVICE(FTDI_VID, LINX_FUTURE_2_PID) },
415  	{ USB_DEVICE(FTDI_VID, FTDI_CCSICDU20_0_PID) },
416  	{ USB_DEVICE(FTDI_VID, FTDI_CCSICDU40_1_PID) },
417 	{ USB_DEVICE(FTDI_VID, INSIDE_ACCESSO) },
418 	{ USB_DEVICE(INTREPID_VID, INTREPID_VALUECAN_PID) },
419 	{ USB_DEVICE(INTREPID_VID, INTREPID_NEOVI_PID) },
420 	{ USB_DEVICE(FALCOM_VID, FALCOM_TWIST_PID) },
421 	{ USB_DEVICE(FTDI_VID, FTDI_SUUNTO_SPORTS_PID) },
422 	{ USB_DEVICE(FTDI_VID, FTDI_RM_CANVIEW_PID) },
423 	{ USB_DEVICE(BANDB_VID, BANDB_USOTL4_PID) },
424 	{ USB_DEVICE(BANDB_VID, BANDB_USTL4_PID) },
425 	{ USB_DEVICE(BANDB_VID, BANDB_USO9ML2_PID) },
426 	{ USB_DEVICE(FTDI_VID, EVER_ECO_PRO_CDS) },
427 	{ USB_DEVICE(FTDI_VID, FTDI_4N_GALAXY_DE_0_PID) },
428 	{ USB_DEVICE(FTDI_VID, FTDI_4N_GALAXY_DE_1_PID) },
429 	{ USB_DEVICE(FTDI_VID, FTDI_4N_GALAXY_DE_2_PID) },
430 	{ USB_DEVICE(MOBILITY_VID, MOBILITY_USB_SERIAL_PID) },
431 	{ USB_DEVICE(FTDI_VID, FTDI_ACTIVE_ROBOTS_PID) },
432 	{ USB_DEVICE(FTDI_VID, FTDI_MHAM_Y6_PID) },
433 	{ USB_DEVICE(FTDI_VID, FTDI_MHAM_Y8_PID) },
434 	{ USB_DEVICE(EVOLUTION_VID, EVOLUTION_ER1_PID) },
435 	{ }						/* Terminating entry */
436 };
437 
438 MODULE_DEVICE_TABLE (usb, id_table_combined);
439 
440 static struct usb_driver ftdi_driver = {
441 	.name =		"ftdi_sio",
442 	.probe =	usb_serial_probe,
443 	.disconnect =	usb_serial_disconnect,
444 	.id_table =	id_table_combined,
445 };
446 
447 static char *ftdi_chip_name[] = {
448 	[SIO] = "SIO",	/* the serial part of FT8U100AX */
449 	[FT8U232AM] = "FT8U232AM",
450 	[FT232BM] = "FT232BM",
451 	[FT2232C] = "FT2232C",
452 };
453 
454 
455 /* Constants for read urb and write urb */
456 #define BUFSZ 512
457 #define PKTSZ 64
458 
459 /* rx_flags */
460 #define THROTTLED		0x01
461 #define ACTUALLY_THROTTLED	0x02
462 
463 struct ftdi_private {
464 	ftdi_chip_type_t chip_type;
465 				/* type of the device, either SIO or FT8U232AM */
466 	int baud_base;		/* baud base clock for divisor setting */
467 	int custom_divisor;	/* custom_divisor kludge, this is for baud_base (different from what goes to the chip!) */
468 	__u16 last_set_data_urb_value ;
469 				/* the last data state set - needed for doing a break */
470         int write_offset;       /* This is the offset in the usb data block to write the serial data -
471 				 * it is different between devices
472 				 */
473 	int flags;		/* some ASYNC_xxxx flags are supported */
474 	unsigned long last_dtr_rts;	/* saved modem control outputs */
475         wait_queue_head_t delta_msr_wait; /* Used for TIOCMIWAIT */
476  	char prev_status, diff_status;        /* Used for TIOCMIWAIT */
477 	__u8 rx_flags;		/* receive state flags (throttling) */
478 	spinlock_t rx_lock;	/* spinlock for receive state */
479 	struct work_struct rx_work;
480 	int rx_processed;
481 
482 	__u16 interface;	/* FT2232C port interface (0 for FT232/245) */
483 
484 	int force_baud;		/* if non-zero, force the baud rate to this value */
485 	int force_rtscts;	/* if non-zero, force RTS-CTS to always be enabled */
486 };
487 
488 /* Used for TIOCMIWAIT */
489 #define FTDI_STATUS_B0_MASK	(FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
490 #define FTDI_STATUS_B1_MASK	(FTDI_RS_BI)
491 /* End TIOCMIWAIT */
492 
493 #define FTDI_IMPL_ASYNC_FLAGS = ( ASYNC_SPD_HI | ASYNC_SPD_VHI \
494  ASYNC_SPD_CUST | ASYNC_SPD_SHI | ASYNC_SPD_WARP )
495 
496 /* function prototypes for a FTDI serial converter */
497 static int  ftdi_sio_probe	(struct usb_serial *serial, const struct usb_device_id *id);
498 static int  ftdi_sio_attach		(struct usb_serial *serial);
499 static void ftdi_shutdown		(struct usb_serial *serial);
500 static int  ftdi_open			(struct usb_serial_port *port, struct file *filp);
501 static void ftdi_close			(struct usb_serial_port *port, struct file *filp);
502 static int  ftdi_write			(struct usb_serial_port *port, const unsigned char *buf, int count);
503 static int  ftdi_write_room		(struct usb_serial_port *port);
504 static int  ftdi_chars_in_buffer	(struct usb_serial_port *port);
505 static void ftdi_write_bulk_callback	(struct urb *urb, struct pt_regs *regs);
506 static void ftdi_read_bulk_callback	(struct urb *urb, struct pt_regs *regs);
507 static void ftdi_process_read		(void *param);
508 static void ftdi_set_termios		(struct usb_serial_port *port, struct termios * old);
509 static int  ftdi_tiocmget               (struct usb_serial_port *port, struct file *file);
510 static int  ftdi_tiocmset		(struct usb_serial_port *port, struct file * file, unsigned int set, unsigned int clear);
511 static int  ftdi_ioctl			(struct usb_serial_port *port, struct file * file, unsigned int cmd, unsigned long arg);
512 static void ftdi_break_ctl		(struct usb_serial_port *port, int break_state );
513 static void ftdi_throttle		(struct usb_serial_port *port);
514 static void ftdi_unthrottle		(struct usb_serial_port *port);
515 
516 static unsigned short int ftdi_232am_baud_base_to_divisor (int baud, int base);
517 static unsigned short int ftdi_232am_baud_to_divisor (int baud);
518 static __u32 ftdi_232bm_baud_base_to_divisor (int baud, int base);
519 static __u32 ftdi_232bm_baud_to_divisor (int baud);
520 
521 static struct usb_serial_device_type ftdi_sio_device = {
522 	.owner =		THIS_MODULE,
523 	.name =			"FTDI USB Serial Device",
524 	.short_name =		"ftdi_sio",
525 	.id_table =		id_table_combined,
526 	.num_interrupt_in =	0,
527 	.num_bulk_in =		1,
528 	.num_bulk_out =		1,
529 	.num_ports =		1,
530 	.probe =		ftdi_sio_probe,
531 	.open =			ftdi_open,
532 	.close =		ftdi_close,
533 	.throttle =		ftdi_throttle,
534 	.unthrottle =		ftdi_unthrottle,
535 	.write =		ftdi_write,
536 	.write_room =		ftdi_write_room,
537 	.chars_in_buffer =	ftdi_chars_in_buffer,
538 	.read_bulk_callback =	ftdi_read_bulk_callback,
539 	.write_bulk_callback =	ftdi_write_bulk_callback,
540 	.tiocmget =             ftdi_tiocmget,
541 	.tiocmset =             ftdi_tiocmset,
542 	.ioctl =		ftdi_ioctl,
543 	.set_termios =		ftdi_set_termios,
544 	.break_ctl =		ftdi_break_ctl,
545 	.attach =		ftdi_sio_attach,
546 	.shutdown =		ftdi_shutdown,
547 };
548 
549 
550 #define WDR_TIMEOUT 5000 /* default urb timeout */
551 #define WDR_SHORT_TIMEOUT 1000	/* shorter urb timeout */
552 
553 /* High and low are for DTR, RTS etc etc */
554 #define HIGH 1
555 #define LOW 0
556 
557 /*
558  * ***************************************************************************
559  * Utlity functions
560  * ***************************************************************************
561  */
562 
563 static unsigned short int ftdi_232am_baud_base_to_divisor(int baud, int base)
564 {
565 	unsigned short int divisor;
566 	int divisor3 = base / 2 / baud; // divisor shifted 3 bits to the left
567 	if ((divisor3 & 0x7) == 7) divisor3 ++; // round x.7/8 up to x+1
568 	divisor = divisor3 >> 3;
569 	divisor3 &= 0x7;
570 	if (divisor3 == 1) divisor |= 0xc000; else // 0.125
571 	if (divisor3 >= 4) divisor |= 0x4000; else // 0.5
572 	if (divisor3 != 0) divisor |= 0x8000;      // 0.25
573 	if (divisor == 1) divisor = 0;	/* special case for maximum baud rate */
574 	return divisor;
575 }
576 
577 static unsigned short int ftdi_232am_baud_to_divisor(int baud)
578 {
579 	 return(ftdi_232am_baud_base_to_divisor(baud, 48000000));
580 }
581 
582 static __u32 ftdi_232bm_baud_base_to_divisor(int baud, int base)
583 {
584 	static const unsigned char divfrac[8] = { 0, 3, 2, 4, 1, 5, 6, 7 };
585 	__u32 divisor;
586 	int divisor3 = base / 2 / baud; // divisor shifted 3 bits to the left
587 	divisor = divisor3 >> 3;
588 	divisor |= (__u32)divfrac[divisor3 & 0x7] << 14;
589 	/* Deal with special cases for highest baud rates. */
590 	if (divisor == 1) divisor = 0; else	// 1.0
591 	if (divisor == 0x4001) divisor = 1;	// 1.5
592 	return divisor;
593 }
594 
595 static __u32 ftdi_232bm_baud_to_divisor(int baud)
596 {
597 	 return(ftdi_232bm_baud_base_to_divisor(baud, 48000000));
598 }
599 
600 #define set_mctrl(port, set)		update_mctrl((port), (set), 0)
601 #define clear_mctrl(port, clear)	update_mctrl((port), 0, (clear))
602 
603 static int update_mctrl(struct usb_serial_port *port, unsigned int set, unsigned int clear)
604 {
605 	struct ftdi_private *priv = usb_get_serial_port_data(port);
606 	char *buf;
607 	unsigned urb_value;
608 	int rv;
609 
610 	if (((set | clear) & (TIOCM_DTR | TIOCM_RTS)) == 0) {
611 		dbg("%s - DTR|RTS not being set|cleared", __FUNCTION__);
612 		return 0;	/* no change */
613 	}
614 
615 	buf = kmalloc(1, GFP_NOIO);
616 	if (!buf) {
617 		return -ENOMEM;
618 	}
619 
620 	clear &= ~set;	/* 'set' takes precedence over 'clear' */
621 	urb_value = 0;
622 	if (clear & TIOCM_DTR)
623 		urb_value |= FTDI_SIO_SET_DTR_LOW;
624 	if (clear & TIOCM_RTS)
625 		urb_value |= FTDI_SIO_SET_RTS_LOW;
626 	if (set & TIOCM_DTR)
627 		urb_value |= FTDI_SIO_SET_DTR_HIGH;
628 	if (set & TIOCM_RTS)
629 		urb_value |= FTDI_SIO_SET_RTS_HIGH;
630 	rv = usb_control_msg(port->serial->dev,
631 			       usb_sndctrlpipe(port->serial->dev, 0),
632 			       FTDI_SIO_SET_MODEM_CTRL_REQUEST,
633 			       FTDI_SIO_SET_MODEM_CTRL_REQUEST_TYPE,
634 			       urb_value, priv->interface,
635 			       buf, 0, WDR_TIMEOUT);
636 
637 	kfree(buf);
638 	if (rv < 0) {
639 		err("%s Error from MODEM_CTRL urb: DTR %s, RTS %s",
640 				__FUNCTION__,
641 				(set & TIOCM_DTR) ? "HIGH" :
642 				(clear & TIOCM_DTR) ? "LOW" : "unchanged",
643 				(set & TIOCM_RTS) ? "HIGH" :
644 				(clear & TIOCM_RTS) ? "LOW" : "unchanged");
645 	} else {
646 		dbg("%s - DTR %s, RTS %s", __FUNCTION__,
647 				(set & TIOCM_DTR) ? "HIGH" :
648 				(clear & TIOCM_DTR) ? "LOW" : "unchanged",
649 				(set & TIOCM_RTS) ? "HIGH" :
650 				(clear & TIOCM_RTS) ? "LOW" : "unchanged");
651 		priv->last_dtr_rts = (priv->last_dtr_rts & ~clear) | set;
652 	}
653 	return rv;
654 }
655 
656 
657 static __u32 get_ftdi_divisor(struct usb_serial_port * port);
658 
659 
660 static int change_speed(struct usb_serial_port *port)
661 {
662 	struct ftdi_private *priv = usb_get_serial_port_data(port);
663 	char *buf;
664         __u16 urb_value;
665 	__u16 urb_index;
666 	__u32 urb_index_value;
667 	int rv;
668 
669 	buf = kmalloc(1, GFP_NOIO);
670 	if (!buf)
671 		return -ENOMEM;
672 
673 	urb_index_value = get_ftdi_divisor(port);
674 	urb_value = (__u16)urb_index_value;
675 	urb_index = (__u16)(urb_index_value >> 16);
676 	if (priv->interface) {	/* FT2232C */
677 		urb_index = (__u16)((urb_index << 8) | priv->interface);
678 	}
679 
680 	rv = usb_control_msg(port->serial->dev,
681 			    usb_sndctrlpipe(port->serial->dev, 0),
682 			    FTDI_SIO_SET_BAUDRATE_REQUEST,
683 			    FTDI_SIO_SET_BAUDRATE_REQUEST_TYPE,
684 			    urb_value, urb_index,
685 			    buf, 0, WDR_SHORT_TIMEOUT);
686 
687 	kfree(buf);
688 	return rv;
689 }
690 
691 
692 static __u32 get_ftdi_divisor(struct usb_serial_port * port)
693 { /* get_ftdi_divisor */
694 	struct ftdi_private *priv = usb_get_serial_port_data(port);
695 	__u32 div_value = 0;
696 	int div_okay = 1;
697 	int baud;
698 
699 	/*
700 	 * The logic involved in setting the baudrate can be cleanly split in 3 steps.
701 	 * Obtaining the actual baud rate is a little tricky since unix traditionally
702 	 * somehow ignored the possibility to set non-standard baud rates.
703 	 * 1. Standard baud rates are set in tty->termios->c_cflag
704 	 * 2. If these are not enough, you can set any speed using alt_speed as follows:
705 	 *    - set tty->termios->c_cflag speed to B38400
706 	 *    - set your real speed in tty->alt_speed; it gets ignored when
707 	 *      alt_speed==0, (or)
708 	 *    - call TIOCSSERIAL ioctl with (struct serial_struct) set as follows:
709 	 *      flags & ASYNC_SPD_MASK == ASYNC_SPD_[HI, VHI, SHI, WARP], this just
710 	 *      sets alt_speed to (HI: 57600, VHI: 115200, SHI: 230400, WARP: 460800)
711 	 * ** Steps 1, 2 are done courtesy of tty_get_baud_rate
712 	 * 3. You can also set baud rate by setting custom divisor as follows
713 	 *    - set tty->termios->c_cflag speed to B38400
714 	 *    - call TIOCSSERIAL ioctl with (struct serial_struct) set as follows:
715 	 *      o flags & ASYNC_SPD_MASK == ASYNC_SPD_CUST
716 	 *      o custom_divisor set to baud_base / your_new_baudrate
717 	 * ** Step 3 is done courtesy of code borrowed from serial.c - I should really
718 	 *    spend some time and separate+move this common code to serial.c, it is
719 	 *    replicated in nearly every serial driver you see.
720 	 */
721 
722 	/* 1. Get the baud rate from the tty settings, this observes alt_speed hack */
723 
724 	baud = tty_get_baud_rate(port->tty);
725 	dbg("%s - tty_get_baud_rate reports speed %d", __FUNCTION__, baud);
726 
727 	/* 2. Observe async-compatible custom_divisor hack, update baudrate if needed */
728 
729 	if (baud == 38400 &&
730 	    ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST) &&
731 	     (priv->custom_divisor)) {
732 		baud = priv->baud_base / priv->custom_divisor;
733 		dbg("%s - custom divisor %d sets baud rate to %d", __FUNCTION__, priv->custom_divisor, baud);
734 	}
735 
736 	/* 3. Convert baudrate to device-specific divisor */
737 
738 	if (!baud) baud = 9600;
739 	switch(priv->chip_type) {
740 	case SIO: /* SIO chip */
741 		switch(baud) {
742 		case 300: div_value = ftdi_sio_b300; break;
743 		case 600: div_value = ftdi_sio_b600; break;
744 		case 1200: div_value = ftdi_sio_b1200; break;
745 		case 2400: div_value = ftdi_sio_b2400; break;
746 		case 4800: div_value = ftdi_sio_b4800; break;
747 		case 9600: div_value = ftdi_sio_b9600; break;
748 		case 19200: div_value = ftdi_sio_b19200; break;
749 		case 38400: div_value = ftdi_sio_b38400; break;
750 		case 57600: div_value = ftdi_sio_b57600;  break;
751 		case 115200: div_value = ftdi_sio_b115200; break;
752 		} /* baud */
753 		if (div_value == 0) {
754   			dbg("%s - Baudrate (%d) requested is not supported", __FUNCTION__,  baud);
755 			div_value = ftdi_sio_b9600;
756 			div_okay = 0;
757 		}
758 		break;
759 	case FT8U232AM: /* 8U232AM chip */
760 		if (baud <= 3000000) {
761 			div_value = ftdi_232am_baud_to_divisor(baud);
762 		} else {
763 	                dbg("%s - Baud rate too high!", __FUNCTION__);
764 			div_value = ftdi_232am_baud_to_divisor(9600);
765 			div_okay = 0;
766 		}
767 		break;
768 	case FT232BM: /* FT232BM chip */
769 	case FT2232C: /* FT2232C chip */
770 		if (baud <= 3000000) {
771 			div_value = ftdi_232bm_baud_to_divisor(baud);
772 		} else {
773 	                dbg("%s - Baud rate too high!", __FUNCTION__);
774 			div_value = ftdi_232bm_baud_to_divisor(9600);
775 			div_okay = 0;
776 		}
777 		break;
778 	} /* priv->chip_type */
779 
780 	if (div_okay) {
781 		dbg("%s - Baud rate set to %d (divisor 0x%lX) on chip %s",
782 			__FUNCTION__, baud, (unsigned long)div_value,
783 			ftdi_chip_name[priv->chip_type]);
784 	}
785 
786 	return(div_value);
787 }
788 
789 
790 static int get_serial_info(struct usb_serial_port * port, struct serial_struct __user * retinfo)
791 {
792 	struct ftdi_private *priv = usb_get_serial_port_data(port);
793 	struct serial_struct tmp;
794 
795 	if (!retinfo)
796 		return -EFAULT;
797 	memset(&tmp, 0, sizeof(tmp));
798 	tmp.flags = priv->flags;
799 	tmp.baud_base = priv->baud_base;
800 	tmp.custom_divisor = priv->custom_divisor;
801 	if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
802 		return -EFAULT;
803 	return 0;
804 } /* get_serial_info */
805 
806 
807 static int set_serial_info(struct usb_serial_port * port, struct serial_struct __user * newinfo)
808 { /* set_serial_info */
809 	struct ftdi_private *priv = usb_get_serial_port_data(port);
810 	struct serial_struct new_serial;
811 	struct ftdi_private old_priv;
812 
813 	if (copy_from_user(&new_serial, newinfo, sizeof(new_serial)))
814 		return -EFAULT;
815 	old_priv = * priv;
816 
817 	/* Do error checking and permission checking */
818 
819 	if (!capable(CAP_SYS_ADMIN)) {
820 		if (((new_serial.flags & ~ASYNC_USR_MASK) !=
821 		     (priv->flags & ~ASYNC_USR_MASK)))
822 			return -EPERM;
823 		priv->flags = ((priv->flags & ~ASYNC_USR_MASK) |
824 			       (new_serial.flags & ASYNC_USR_MASK));
825 		priv->custom_divisor = new_serial.custom_divisor;
826 		goto check_and_exit;
827 	}
828 
829 	if ((new_serial.baud_base != priv->baud_base) &&
830 	    (new_serial.baud_base < 9600))
831 		return -EINVAL;
832 
833 	/* Make the changes - these are privileged changes! */
834 
835 	priv->flags = ((priv->flags & ~ASYNC_FLAGS) |
836 	               (new_serial.flags & ASYNC_FLAGS));
837 	priv->custom_divisor = new_serial.custom_divisor;
838 
839 	port->tty->low_latency = (priv->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
840 
841 check_and_exit:
842 	if ((old_priv.flags & ASYNC_SPD_MASK) !=
843 	     (priv->flags & ASYNC_SPD_MASK)) {
844 		if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_HI)
845 			port->tty->alt_speed = 57600;
846 		else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_VHI)
847 			port->tty->alt_speed = 115200;
848 		else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_SHI)
849 			port->tty->alt_speed = 230400;
850 		else if ((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_WARP)
851 			port->tty->alt_speed = 460800;
852 		else
853 			port->tty->alt_speed = 0;
854 	}
855 	if (((old_priv.flags & ASYNC_SPD_MASK) !=
856 	     (priv->flags & ASYNC_SPD_MASK)) ||
857 	    (((priv->flags & ASYNC_SPD_MASK) == ASYNC_SPD_CUST) &&
858 	     (old_priv.custom_divisor != priv->custom_divisor))) {
859 		change_speed(port);
860 	}
861 
862 	return (0);
863 
864 } /* set_serial_info */
865 
866 
867 /* Determine type of FTDI chip based on USB config and descriptor. */
868 static void ftdi_determine_type(struct usb_serial_port *port)
869 {
870 	struct ftdi_private *priv = usb_get_serial_port_data(port);
871 	struct usb_serial *serial = port->serial;
872 	struct usb_device *udev = serial->dev;
873 	unsigned version;
874 	unsigned interfaces;
875 
876 	/* Assume it is not the original SIO device for now. */
877 	priv->baud_base = 48000000 / 16;
878 	priv->write_offset = 0;
879 
880 	version = le16_to_cpu(udev->descriptor.bcdDevice);
881 	interfaces = udev->actconfig->desc.bNumInterfaces;
882 	dbg("%s: bcdDevice = 0x%x, bNumInterfaces = %u", __FUNCTION__,
883 			version, interfaces);
884 	if (interfaces > 1) {
885 		int inter;
886 
887 		/* Multiple interfaces.  Assume FT2232C. */
888 		priv->chip_type = FT2232C;
889 		/* Determine interface code. */
890 		inter = serial->interface->altsetting->desc.bInterfaceNumber;
891 		if (inter == 0) {
892 			priv->interface = PIT_SIOA;
893 		} else {
894 			priv->interface = PIT_SIOB;
895 		}
896 		/* BM-type devices have a bug where bcdDevice gets set
897 		 * to 0x200 when iSerialNumber is 0.  */
898 		if (version < 0x500) {
899 			dbg("%s: something fishy - bcdDevice too low for multi-interface device",
900 					__FUNCTION__);
901 		}
902 	} else if (version < 0x200) {
903 		/* Old device.  Assume its the original SIO. */
904 		priv->chip_type = SIO;
905 		priv->baud_base = 12000000 / 16;
906 		priv->write_offset = 1;
907 	} else if (version < 0x400) {
908 		/* Assume its an FT8U232AM (or FT8U245AM) */
909 		/* (It might be a BM because of the iSerialNumber bug,
910 		 * but it will still work as an AM device.) */
911 		priv->chip_type = FT8U232AM;
912 	} else {
913 		/* Assume its an FT232BM (or FT245BM) */
914 		priv->chip_type = FT232BM;
915 	}
916 	info("Detected %s", ftdi_chip_name[priv->chip_type]);
917 }
918 
919 
920 /*
921  * ***************************************************************************
922  * Sysfs Attribute
923  * ***************************************************************************
924  */
925 
926 static ssize_t show_latency_timer(struct device *dev, struct device_attribute *attr, char *buf)
927 {
928 	struct usb_serial_port *port = to_usb_serial_port(dev);
929 	struct ftdi_private *priv = usb_get_serial_port_data(port);
930 	struct usb_device *udev;
931 	unsigned short latency = 0;
932 	int rv = 0;
933 
934 	udev = to_usb_device(dev);
935 
936 	dbg("%s",__FUNCTION__);
937 
938 	rv = usb_control_msg(udev,
939 			     usb_rcvctrlpipe(udev, 0),
940 			     FTDI_SIO_GET_LATENCY_TIMER_REQUEST,
941 			     FTDI_SIO_GET_LATENCY_TIMER_REQUEST_TYPE,
942 			     0, priv->interface,
943 			     (char*) &latency, 1, WDR_TIMEOUT);
944 
945 	if (rv < 0) {
946 		dev_err(dev, "Unable to read latency timer: %i", rv);
947 		return -EIO;
948 	}
949 	return sprintf(buf, "%i\n", latency);
950 }
951 
952 /* Write a new value of the latency timer, in units of milliseconds. */
953 static ssize_t store_latency_timer(struct device *dev, struct device_attribute *attr, const char *valbuf,
954 				   size_t count)
955 {
956 	struct usb_serial_port *port = to_usb_serial_port(dev);
957 	struct ftdi_private *priv = usb_get_serial_port_data(port);
958 	struct usb_device *udev;
959 	char buf[1];
960 	int v = simple_strtoul(valbuf, NULL, 10);
961 	int rv = 0;
962 
963 	udev = to_usb_device(dev);
964 
965 	dbg("%s: setting latency timer = %i", __FUNCTION__, v);
966 
967 	rv = usb_control_msg(udev,
968 			     usb_sndctrlpipe(udev, 0),
969 			     FTDI_SIO_SET_LATENCY_TIMER_REQUEST,
970 			     FTDI_SIO_SET_LATENCY_TIMER_REQUEST_TYPE,
971 			     v, priv->interface,
972 			     buf, 0, WDR_TIMEOUT);
973 
974 	if (rv < 0) {
975 		dev_err(dev, "Unable to write latency timer: %i", rv);
976 		return -EIO;
977 	}
978 
979 	return count;
980 }
981 
982 /* Write an event character directly to the FTDI register.  The ASCII
983    value is in the low 8 bits, with the enable bit in the 9th bit. */
984 static ssize_t store_event_char(struct device *dev, struct device_attribute *attr, const char *valbuf,
985 				size_t count)
986 {
987 	struct usb_serial_port *port = to_usb_serial_port(dev);
988 	struct ftdi_private *priv = usb_get_serial_port_data(port);
989 	struct usb_device *udev;
990 	char buf[1];
991 	int v = simple_strtoul(valbuf, NULL, 10);
992 	int rv = 0;
993 
994 	udev = to_usb_device(dev);
995 
996 	dbg("%s: setting event char = %i", __FUNCTION__, v);
997 
998 	rv = usb_control_msg(udev,
999 			     usb_sndctrlpipe(udev, 0),
1000 			     FTDI_SIO_SET_EVENT_CHAR_REQUEST,
1001 			     FTDI_SIO_SET_EVENT_CHAR_REQUEST_TYPE,
1002 			     v, priv->interface,
1003 			     buf, 0, WDR_TIMEOUT);
1004 
1005 	if (rv < 0) {
1006 		dbg("Unable to write event character: %i", rv);
1007 		return -EIO;
1008 	}
1009 
1010 	return count;
1011 }
1012 
1013 static DEVICE_ATTR(latency_timer, S_IWUSR | S_IRUGO, show_latency_timer, store_latency_timer);
1014 static DEVICE_ATTR(event_char, S_IWUSR, NULL, store_event_char);
1015 
1016 static void create_sysfs_attrs(struct usb_serial *serial)
1017 {
1018 	struct ftdi_private *priv;
1019 	struct usb_device *udev;
1020 
1021 	dbg("%s",__FUNCTION__);
1022 
1023 	priv = usb_get_serial_port_data(serial->port[0]);
1024 	udev = serial->dev;
1025 
1026 	/* XXX I've no idea if the original SIO supports the event_char
1027 	 * sysfs parameter, so I'm playing it safe.  */
1028 	if (priv->chip_type != SIO) {
1029 		dbg("sysfs attributes for %s", ftdi_chip_name[priv->chip_type]);
1030 		device_create_file(&udev->dev, &dev_attr_event_char);
1031 		if (priv->chip_type == FT232BM || priv->chip_type == FT2232C) {
1032 			device_create_file(&udev->dev, &dev_attr_latency_timer);
1033 		}
1034 	}
1035 }
1036 
1037 static void remove_sysfs_attrs(struct usb_serial *serial)
1038 {
1039 	struct ftdi_private *priv;
1040 	struct usb_device *udev;
1041 
1042 	dbg("%s",__FUNCTION__);
1043 
1044 	priv = usb_get_serial_port_data(serial->port[0]);
1045 	udev = serial->dev;
1046 
1047 	/* XXX see create_sysfs_attrs */
1048 	if (priv->chip_type != SIO) {
1049 		device_remove_file(&udev->dev, &dev_attr_event_char);
1050 		if (priv->chip_type == FT232BM || priv->chip_type == FT2232C) {
1051 			device_remove_file(&udev->dev, &dev_attr_latency_timer);
1052 		}
1053 	}
1054 
1055 }
1056 
1057 /*
1058  * ***************************************************************************
1059  * FTDI driver specific functions
1060  * ***************************************************************************
1061  */
1062 
1063 /* Probe function to check for special devices */
1064 static int ftdi_sio_probe (struct usb_serial *serial, const struct usb_device_id *id)
1065 {
1066 	usb_set_serial_data(serial, (void *)id->driver_info);
1067 
1068 	return (0);
1069 }
1070 
1071 /* attach subroutine */
1072 static int ftdi_sio_attach (struct usb_serial *serial)
1073 {
1074 	struct usb_serial_port *port = serial->port[0];
1075 	struct ftdi_private *priv;
1076 	struct ftdi_sio_quirk *quirk;
1077 
1078 	dbg("%s",__FUNCTION__);
1079 
1080 	priv = kmalloc(sizeof(struct ftdi_private), GFP_KERNEL);
1081 	if (!priv){
1082 		err("%s- kmalloc(%Zd) failed.", __FUNCTION__, sizeof(struct ftdi_private));
1083 		return -ENOMEM;
1084 	}
1085 	memset(priv, 0, sizeof(*priv));
1086 
1087 	spin_lock_init(&priv->rx_lock);
1088         init_waitqueue_head(&priv->delta_msr_wait);
1089 	/* This will push the characters through immediately rather
1090 	   than queue a task to deliver them */
1091 	priv->flags = ASYNC_LOW_LATENCY;
1092 
1093 	/* Increase the size of read buffers */
1094 	kfree(port->bulk_in_buffer);
1095 	port->bulk_in_buffer = kmalloc (BUFSZ, GFP_KERNEL);
1096 	if (!port->bulk_in_buffer) {
1097 		kfree (priv);
1098 		return -ENOMEM;
1099 	}
1100 	if (port->read_urb) {
1101 		port->read_urb->transfer_buffer = port->bulk_in_buffer;
1102 		port->read_urb->transfer_buffer_length = BUFSZ;
1103 	}
1104 
1105 	INIT_WORK(&priv->rx_work, ftdi_process_read, port);
1106 
1107 	/* Free port's existing write urb and transfer buffer. */
1108 	if (port->write_urb) {
1109 		usb_free_urb (port->write_urb);
1110 		port->write_urb = NULL;
1111 	}
1112 	kfree(port->bulk_out_buffer);
1113 	port->bulk_out_buffer = NULL;
1114 
1115 	usb_set_serial_port_data(serial->port[0], priv);
1116 
1117 	ftdi_determine_type (serial->port[0]);
1118 	create_sysfs_attrs(serial);
1119 
1120 	/* Check for device requiring special set up. */
1121 	quirk = (struct ftdi_sio_quirk *)usb_get_serial_data(serial);
1122 	if (quirk && quirk->setup) {
1123 		quirk->setup(serial);
1124 	}
1125 
1126 	return (0);
1127 } /* ftdi_sio_attach */
1128 
1129 
1130 /* Setup for the USB-UIRT device, which requires hardwired
1131  * baudrate (38400 gets mapped to 312500) */
1132 /* Called from usbserial:serial_probe */
1133 static void ftdi_USB_UIRT_setup (struct usb_serial *serial)
1134 {
1135 	struct ftdi_private *priv;
1136 
1137 	dbg("%s",__FUNCTION__);
1138 
1139 	priv = usb_get_serial_port_data(serial->port[0]);
1140 	priv->flags |= ASYNC_SPD_CUST;
1141 	priv->custom_divisor = 77;
1142 	priv->force_baud = B38400;
1143 } /* ftdi_USB_UIRT_setup */
1144 
1145 /* Setup for the HE-TIRA1 device, which requires hardwired
1146  * baudrate (38400 gets mapped to 100000) and RTS-CTS enabled.  */
1147 static void ftdi_HE_TIRA1_setup (struct usb_serial *serial)
1148 {
1149 	struct ftdi_private *priv;
1150 
1151 	dbg("%s",__FUNCTION__);
1152 
1153 	priv = usb_get_serial_port_data(serial->port[0]);
1154 	priv->flags |= ASYNC_SPD_CUST;
1155 	priv->custom_divisor = 240;
1156 	priv->force_baud = B38400;
1157 	priv->force_rtscts = 1;
1158 } /* ftdi_HE_TIRA1_setup */
1159 
1160 
1161 /* ftdi_shutdown is called from usbserial:usb_serial_disconnect
1162  *   it is called when the usb device is disconnected
1163  *
1164  *   usbserial:usb_serial_disconnect
1165  *      calls __serial_close for each open of the port
1166  *      shutdown is called then (ie ftdi_shutdown)
1167  */
1168 
1169 
1170 static void ftdi_shutdown (struct usb_serial *serial)
1171 { /* ftdi_shutdown */
1172 
1173 	struct usb_serial_port *port = serial->port[0];
1174 	struct ftdi_private *priv = usb_get_serial_port_data(port);
1175 
1176 	dbg("%s", __FUNCTION__);
1177 
1178 	remove_sysfs_attrs(serial);
1179 
1180 	/* all open ports are closed at this point
1181          *    (by usbserial.c:__serial_close, which calls ftdi_close)
1182 	 */
1183 
1184 	if (priv) {
1185 		usb_set_serial_port_data(port, NULL);
1186 		kfree(priv);
1187 	}
1188 } /* ftdi_shutdown */
1189 
1190 
1191 static int  ftdi_open (struct usb_serial_port *port, struct file *filp)
1192 { /* ftdi_open */
1193 	struct termios tmp_termios;
1194 	struct usb_device *dev = port->serial->dev;
1195 	struct ftdi_private *priv = usb_get_serial_port_data(port);
1196 	unsigned long flags;
1197 
1198 	int result = 0;
1199 	char buf[1]; /* Needed for the usb_control_msg I think */
1200 
1201 	dbg("%s", __FUNCTION__);
1202 
1203 
1204 	port->tty->low_latency = (priv->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
1205 
1206 	/* No error checking for this (will get errors later anyway) */
1207 	/* See ftdi_sio.h for description of what is reset */
1208 	usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1209 			FTDI_SIO_RESET_REQUEST, FTDI_SIO_RESET_REQUEST_TYPE,
1210 			FTDI_SIO_RESET_SIO,
1211 			priv->interface, buf, 0, WDR_TIMEOUT);
1212 
1213 	/* Termios defaults are set by usb_serial_init. We don't change
1214 	   port->tty->termios - this would loose speed settings, etc.
1215 	   This is same behaviour as serial.c/rs_open() - Kuba */
1216 
1217 	/* ftdi_set_termios  will send usb control messages */
1218 	ftdi_set_termios(port, &tmp_termios);
1219 
1220 	/* FIXME: Flow control might be enabled, so it should be checked -
1221 	   we have no control of defaults! */
1222 	/* Turn on RTS and DTR since we are not flow controlling by default */
1223 	set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
1224 
1225 	/* Not throttled */
1226 	spin_lock_irqsave(&priv->rx_lock, flags);
1227 	priv->rx_flags &= ~(THROTTLED | ACTUALLY_THROTTLED);
1228 	spin_unlock_irqrestore(&priv->rx_lock, flags);
1229 
1230 	/* Start reading from the device */
1231 	priv->rx_processed = 0;
1232 	usb_fill_bulk_urb(port->read_urb, dev,
1233 		      usb_rcvbulkpipe(dev, port->bulk_in_endpointAddress),
1234 		      port->read_urb->transfer_buffer, port->read_urb->transfer_buffer_length,
1235 		      ftdi_read_bulk_callback, port);
1236 	result = usb_submit_urb(port->read_urb, GFP_KERNEL);
1237 	if (result)
1238 		err("%s - failed submitting read urb, error %d", __FUNCTION__, result);
1239 
1240 
1241 	return result;
1242 } /* ftdi_open */
1243 
1244 
1245 
1246 /*
1247  * usbserial:__serial_close  only calls ftdi_close if the point is open
1248  *
1249  *   This only gets called when it is the last close
1250  *
1251  *
1252  */
1253 
1254 static void ftdi_close (struct usb_serial_port *port, struct file *filp)
1255 { /* ftdi_close */
1256 	unsigned int c_cflag = port->tty->termios->c_cflag;
1257 	struct ftdi_private *priv = usb_get_serial_port_data(port);
1258 	char buf[1];
1259 
1260 	dbg("%s", __FUNCTION__);
1261 
1262 	if (c_cflag & HUPCL){
1263 		/* Disable flow control */
1264 		if (usb_control_msg(port->serial->dev,
1265 				    usb_sndctrlpipe(port->serial->dev, 0),
1266 				    FTDI_SIO_SET_FLOW_CTRL_REQUEST,
1267 				    FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1268 				    0, priv->interface, buf, 0,
1269 				    WDR_TIMEOUT) < 0) {
1270 			err("error from flowcontrol urb");
1271 		}
1272 
1273 		/* drop RTS and DTR */
1274 		clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
1275 	} /* Note change no line if hupcl is off */
1276 
1277 	/* cancel any scheduled reading */
1278 	cancel_delayed_work(&priv->rx_work);
1279 	flush_scheduled_work();
1280 
1281 	/* shutdown our bulk read */
1282 	if (port->read_urb)
1283 		usb_kill_urb(port->read_urb);
1284 } /* ftdi_close */
1285 
1286 
1287 
1288 /* The SIO requires the first byte to have:
1289  *  B0 1
1290  *  B1 0
1291  *  B2..7 length of message excluding byte 0
1292  *
1293  * The new devices do not require this byte
1294  */
1295 static int ftdi_write (struct usb_serial_port *port,
1296 			   const unsigned char *buf, int count)
1297 { /* ftdi_write */
1298 	struct ftdi_private *priv = usb_get_serial_port_data(port);
1299 	struct urb *urb;
1300 	unsigned char *buffer;
1301 	int data_offset ;       /* will be 1 for the SIO and 0 otherwise */
1302 	int status;
1303 	int transfer_size;
1304 
1305 	dbg("%s port %d, %d bytes", __FUNCTION__, port->number, count);
1306 
1307 	if (count == 0) {
1308 		dbg("write request of 0 bytes");
1309 		return 0;
1310 	}
1311 
1312 	data_offset = priv->write_offset;
1313         dbg("data_offset set to %d",data_offset);
1314 
1315 	/* Determine total transfer size */
1316 	transfer_size = count;
1317 	if (data_offset > 0) {
1318 		/* Original sio needs control bytes too... */
1319 		transfer_size += (data_offset *
1320 				((count + (PKTSZ - 1 - data_offset)) /
1321 				 (PKTSZ - data_offset)));
1322 	}
1323 
1324 	buffer = kmalloc (transfer_size, GFP_ATOMIC);
1325 	if (!buffer) {
1326 		err("%s ran out of kernel memory for urb ...", __FUNCTION__);
1327 		return -ENOMEM;
1328 	}
1329 
1330 	urb = usb_alloc_urb(0, GFP_ATOMIC);
1331 	if (!urb) {
1332 		err("%s - no more free urbs", __FUNCTION__);
1333 		kfree (buffer);
1334 		return -ENOMEM;
1335 	}
1336 
1337 	/* Copy data */
1338 	if (data_offset > 0) {
1339 		/* Original sio requires control byte at start of each packet. */
1340 		int user_pktsz = PKTSZ - data_offset;
1341 		int todo = count;
1342 		unsigned char *first_byte = buffer;
1343 		const unsigned char *current_position = buf;
1344 
1345 		while (todo > 0) {
1346 			if (user_pktsz > todo) {
1347 				user_pktsz = todo;
1348 			}
1349 			/* Write the control byte at the front of the packet*/
1350 			*first_byte = 1 | ((user_pktsz) << 2);
1351 			/* Copy data for packet */
1352 			memcpy (first_byte + data_offset,
1353 				current_position, user_pktsz);
1354 			first_byte += user_pktsz + data_offset;
1355 			current_position += user_pktsz;
1356 			todo -= user_pktsz;
1357 		}
1358 	} else {
1359 		/* No control byte required. */
1360 		/* Copy in the data to send */
1361 		memcpy (buffer, buf, count);
1362 	}
1363 
1364 	usb_serial_debug_data(debug, &port->dev, __FUNCTION__, transfer_size, buffer);
1365 
1366 	/* fill the buffer and send it */
1367 	usb_fill_bulk_urb(urb, port->serial->dev,
1368 		      usb_sndbulkpipe(port->serial->dev, port->bulk_out_endpointAddress),
1369 		      buffer, transfer_size,
1370 		      ftdi_write_bulk_callback, port);
1371 
1372 	status = usb_submit_urb(urb, GFP_ATOMIC);
1373 	if (status) {
1374 		err("%s - failed submitting write urb, error %d", __FUNCTION__, status);
1375 		count = status;
1376 		kfree (buffer);
1377 	}
1378 
1379 	/* we are done with this urb, so let the host driver
1380 	 * really free it when it is finished with it */
1381 	usb_free_urb (urb);
1382 
1383 	dbg("%s write returning: %d", __FUNCTION__, count);
1384 	return count;
1385 } /* ftdi_write */
1386 
1387 
1388 /* This function may get called when the device is closed */
1389 
1390 static void ftdi_write_bulk_callback (struct urb *urb, struct pt_regs *regs)
1391 {
1392 	struct usb_serial_port *port = (struct usb_serial_port *)urb->context;
1393 
1394 	/* free up the transfer buffer, as usb_free_urb() does not do this */
1395 	kfree (urb->transfer_buffer);
1396 
1397 	dbg("%s - port %d", __FUNCTION__, port->number);
1398 
1399 	if (urb->status) {
1400 		dbg("nonzero write bulk status received: %d", urb->status);
1401 		return;
1402 	}
1403 
1404 	schedule_work(&port->work);
1405 } /* ftdi_write_bulk_callback */
1406 
1407 
1408 static int ftdi_write_room( struct usb_serial_port *port )
1409 {
1410 	dbg("%s - port %d", __FUNCTION__, port->number);
1411 
1412 	/*
1413 	 * We really can take anything the user throws at us
1414 	 * but let's pick a nice big number to tell the tty
1415 	 * layer that we have lots of free space
1416 	 */
1417 	return 2048;
1418 } /* ftdi_write_room */
1419 
1420 
1421 static int ftdi_chars_in_buffer (struct usb_serial_port *port)
1422 { /* ftdi_chars_in_buffer */
1423 	dbg("%s - port %d", __FUNCTION__, port->number);
1424 
1425 	/*
1426 	 * We can't really account for how much data we
1427 	 * have sent out, but hasn't made it through to the
1428 	 * device, so just tell the tty layer that everything
1429 	 * is flushed.
1430 	 */
1431 	return 0;
1432 } /* ftdi_chars_in_buffer */
1433 
1434 
1435 
1436 static void ftdi_read_bulk_callback (struct urb *urb, struct pt_regs *regs)
1437 { /* ftdi_read_bulk_callback */
1438 	struct usb_serial_port *port = (struct usb_serial_port *)urb->context;
1439 	struct tty_struct *tty;
1440 	struct ftdi_private *priv;
1441 
1442 	if (urb->number_of_packets > 0) {
1443 		err("%s transfer_buffer_length %d actual_length %d number of packets %d",__FUNCTION__,
1444 		    urb->transfer_buffer_length, urb->actual_length, urb->number_of_packets );
1445 		err("%s transfer_flags %x ", __FUNCTION__,urb->transfer_flags );
1446 	}
1447 
1448 	dbg("%s - port %d", __FUNCTION__, port->number);
1449 
1450 	if (port->open_count <= 0)
1451 		return;
1452 
1453 	tty = port->tty;
1454 	if (!tty) {
1455 		dbg("%s - bad tty pointer - exiting",__FUNCTION__);
1456 		return;
1457 	}
1458 
1459 	priv = usb_get_serial_port_data(port);
1460 	if (!priv) {
1461 		dbg("%s - bad port private data pointer - exiting", __FUNCTION__);
1462 		return;
1463 	}
1464 
1465 	if (urb != port->read_urb) {
1466 		err("%s - Not my urb!", __FUNCTION__);
1467 	}
1468 
1469 	if (urb->status) {
1470 		/* This will happen at close every time so it is a dbg not an err */
1471 		dbg("(this is ok on close) nonzero read bulk status received: %d", urb->status);
1472 		return;
1473 	}
1474 
1475 	ftdi_process_read(port);
1476 
1477 } /* ftdi_read_bulk_callback */
1478 
1479 
1480 static void ftdi_process_read (void *param)
1481 { /* ftdi_process_read */
1482 	struct usb_serial_port *port = (struct usb_serial_port*)param;
1483 	struct urb *urb;
1484 	struct tty_struct *tty;
1485 	struct ftdi_private *priv;
1486 	char error_flag;
1487        	unsigned char *data;
1488 
1489 	int i;
1490 	int result;
1491 	int need_flip;
1492 	int packet_offset;
1493 	unsigned long flags;
1494 
1495 	dbg("%s - port %d", __FUNCTION__, port->number);
1496 
1497 	if (port->open_count <= 0)
1498 		return;
1499 
1500 	tty = port->tty;
1501 	if (!tty) {
1502 		dbg("%s - bad tty pointer - exiting",__FUNCTION__);
1503 		return;
1504 	}
1505 
1506 	priv = usb_get_serial_port_data(port);
1507 	if (!priv) {
1508 		dbg("%s - bad port private data pointer - exiting", __FUNCTION__);
1509 		return;
1510 	}
1511 
1512 	urb = port->read_urb;
1513 	if (!urb) {
1514 		dbg("%s - bad read_urb pointer - exiting", __FUNCTION__);
1515 		return;
1516 	}
1517 
1518 	data = urb->transfer_buffer;
1519 
1520 	if (priv->rx_processed) {
1521 		dbg("%s - already processed: %d bytes, %d remain", __FUNCTION__,
1522 				priv->rx_processed,
1523 				urb->actual_length - priv->rx_processed);
1524 	} else {
1525 		/* The first two bytes of every read packet are status */
1526 		if (urb->actual_length > 2) {
1527 			usb_serial_debug_data(debug, &port->dev, __FUNCTION__, urb->actual_length, data);
1528 		} else {
1529 			dbg("Status only: %03oo %03oo",data[0],data[1]);
1530 		}
1531 	}
1532 
1533 
1534 	/* TO DO -- check for hung up line and handle appropriately: */
1535 	/*   send hangup  */
1536 	/* See acm.c - you do a tty_hangup  - eg tty_hangup(tty) */
1537 	/* if CD is dropped and the line is not CLOCAL then we should hangup */
1538 
1539 	need_flip = 0;
1540 	for (packet_offset = priv->rx_processed; packet_offset < urb->actual_length; packet_offset += PKTSZ) {
1541 		int length;
1542 
1543 		/* Compare new line status to the old one, signal if different */
1544 		/* N.B. packet may be processed more than once, but differences
1545 		 * are only processed once.  */
1546 		if (priv != NULL) {
1547 			char new_status = data[packet_offset+0] & FTDI_STATUS_B0_MASK;
1548 			if (new_status != priv->prev_status) {
1549 				priv->diff_status |= new_status ^ priv->prev_status;
1550 				wake_up_interruptible(&priv->delta_msr_wait);
1551 				priv->prev_status = new_status;
1552 			}
1553 		}
1554 
1555 		length = min(PKTSZ, urb->actual_length-packet_offset)-2;
1556 		if (length < 0) {
1557 			err("%s - bad packet length: %d", __FUNCTION__, length+2);
1558 			length = 0;
1559 		}
1560 
1561 		/* have to make sure we don't overflow the buffer
1562 		   with tty_insert_flip_char's */
1563 		if (tty->flip.count+length > TTY_FLIPBUF_SIZE) {
1564 			tty_flip_buffer_push(tty);
1565 			need_flip = 0;
1566 
1567 			if (tty->flip.count != 0) {
1568 				/* flip didn't work, this happens when ftdi_process_read() is
1569 				 * called from ftdi_unthrottle, because TTY_DONT_FLIP is set */
1570 				dbg("%s - flip buffer push failed", __FUNCTION__);
1571 				break;
1572 			}
1573 		}
1574 		if (priv->rx_flags & THROTTLED) {
1575 			dbg("%s - throttled", __FUNCTION__);
1576 			break;
1577 		}
1578 		if (tty->ldisc.receive_room(tty)-tty->flip.count < length) {
1579 			/* break out & wait for throttling/unthrottling to happen */
1580 			dbg("%s - receive room low", __FUNCTION__);
1581 			break;
1582 		}
1583 
1584 		/* Handle errors and break */
1585 		error_flag = TTY_NORMAL;
1586 		/* Although the device uses a bitmask and hence can have multiple */
1587 		/* errors on a packet - the order here sets the priority the */
1588 		/* error is returned to the tty layer  */
1589 
1590 		if ( data[packet_offset+1] & FTDI_RS_OE ) {
1591 			error_flag = TTY_OVERRUN;
1592 			dbg("OVERRRUN error");
1593 		}
1594 		if ( data[packet_offset+1] & FTDI_RS_BI ) {
1595 			error_flag = TTY_BREAK;
1596 			dbg("BREAK received");
1597 		}
1598 		if ( data[packet_offset+1] & FTDI_RS_PE ) {
1599 			error_flag = TTY_PARITY;
1600 			dbg("PARITY error");
1601 		}
1602 		if ( data[packet_offset+1] & FTDI_RS_FE ) {
1603 			error_flag = TTY_FRAME;
1604 			dbg("FRAMING error");
1605 		}
1606 		if (length > 0) {
1607 			for (i = 2; i < length+2; i++) {
1608 				/* Note that the error flag is duplicated for
1609 				   every character received since we don't know
1610 				   which character it applied to */
1611 				tty_insert_flip_char(tty, data[packet_offset+i], error_flag);
1612 			}
1613 			need_flip = 1;
1614 		}
1615 
1616 #ifdef NOT_CORRECT_BUT_KEEPING_IT_FOR_NOW
1617 		/* if a parity error is detected you get status packets forever
1618 		   until a character is sent without a parity error.
1619 		   This doesn't work well since the application receives a never
1620 		   ending stream of bad data - even though new data hasn't been sent.
1621 		   Therefore I (bill) have taken this out.
1622 		   However - this might make sense for framing errors and so on
1623 		   so I am leaving the code in for now.
1624 		*/
1625 		else {
1626 			if (error_flag != TTY_NORMAL){
1627 				dbg("error_flag is not normal");
1628 				/* In this case it is just status - if that is an error send a bad character */
1629 				if(tty->flip.count >= TTY_FLIPBUF_SIZE) {
1630 					tty_flip_buffer_push(tty);
1631 				}
1632 				tty_insert_flip_char(tty, 0xff, error_flag);
1633 				need_flip = 1;
1634 			}
1635 		}
1636 #endif
1637 	} /* "for(packet_offset=0..." */
1638 
1639 	/* Low latency */
1640 	if (need_flip) {
1641 		tty_flip_buffer_push(tty);
1642 	}
1643 
1644 	if (packet_offset < urb->actual_length) {
1645 		/* not completely processed - record progress */
1646 		priv->rx_processed = packet_offset;
1647 		dbg("%s - incomplete, %d bytes processed, %d remain",
1648 				__FUNCTION__, packet_offset,
1649 				urb->actual_length - packet_offset);
1650 		/* check if we were throttled while processing */
1651 		spin_lock_irqsave(&priv->rx_lock, flags);
1652 		if (priv->rx_flags & THROTTLED) {
1653 			priv->rx_flags |= ACTUALLY_THROTTLED;
1654 			spin_unlock_irqrestore(&priv->rx_lock, flags);
1655 			dbg("%s - deferring remainder until unthrottled",
1656 					__FUNCTION__);
1657 			return;
1658 		}
1659 		spin_unlock_irqrestore(&priv->rx_lock, flags);
1660 		/* if the port is closed stop trying to read */
1661 		if (port->open_count > 0){
1662 			/* delay processing of remainder */
1663 			schedule_delayed_work(&priv->rx_work, 1);
1664 		} else {
1665 			dbg("%s - port is closed", __FUNCTION__);
1666 		}
1667 		return;
1668 	}
1669 
1670 	/* urb is completely processed */
1671 	priv->rx_processed = 0;
1672 
1673 	/* if the port is closed stop trying to read */
1674 	if (port->open_count > 0){
1675 		/* Continue trying to always read  */
1676 		usb_fill_bulk_urb(port->read_urb, port->serial->dev,
1677 			      usb_rcvbulkpipe(port->serial->dev, port->bulk_in_endpointAddress),
1678 			      port->read_urb->transfer_buffer, port->read_urb->transfer_buffer_length,
1679 			      ftdi_read_bulk_callback, port);
1680 
1681 		result = usb_submit_urb(port->read_urb, GFP_ATOMIC);
1682 		if (result)
1683 			err("%s - failed resubmitting read urb, error %d", __FUNCTION__, result);
1684 	}
1685 
1686 	return;
1687 } /* ftdi_process_read */
1688 
1689 
1690 static void ftdi_break_ctl( struct usb_serial_port *port, int break_state )
1691 {
1692 	struct ftdi_private *priv = usb_get_serial_port_data(port);
1693 	__u16 urb_value = 0;
1694 	char buf[1];
1695 
1696 	/* break_state = -1 to turn on break, and 0 to turn off break */
1697 	/* see drivers/char/tty_io.c to see it used */
1698 	/* last_set_data_urb_value NEVER has the break bit set in it */
1699 
1700 	if (break_state) {
1701 		urb_value = priv->last_set_data_urb_value | FTDI_SIO_SET_BREAK;
1702 	} else {
1703 		urb_value = priv->last_set_data_urb_value;
1704 	}
1705 
1706 
1707 	if (usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0),
1708 			    FTDI_SIO_SET_DATA_REQUEST,
1709 			    FTDI_SIO_SET_DATA_REQUEST_TYPE,
1710 			    urb_value , priv->interface,
1711 			    buf, 0, WDR_TIMEOUT) < 0) {
1712 		err("%s FAILED to enable/disable break state (state was %d)", __FUNCTION__,break_state);
1713 	}
1714 
1715 	dbg("%s break state is %d - urb is %d", __FUNCTION__,break_state, urb_value);
1716 
1717 }
1718 
1719 
1720 /* old_termios contains the original termios settings and tty->termios contains
1721  * the new setting to be used
1722  * WARNING: set_termios calls this with old_termios in kernel space
1723  */
1724 
1725 static void ftdi_set_termios (struct usb_serial_port *port, struct termios *old_termios)
1726 { /* ftdi_termios */
1727 	struct usb_device *dev = port->serial->dev;
1728 	unsigned int cflag = port->tty->termios->c_cflag;
1729 	struct ftdi_private *priv = usb_get_serial_port_data(port);
1730 	__u16 urb_value; /* will hold the new flags */
1731 	char buf[1]; /* Perhaps I should dynamically alloc this? */
1732 
1733 	// Added for xon/xoff support
1734 	unsigned int iflag = port->tty->termios->c_iflag;
1735 	unsigned char vstop;
1736 	unsigned char vstart;
1737 
1738 	dbg("%s", __FUNCTION__);
1739 
1740 	/* Force baud rate if this device requires it, unless it is set to B0. */
1741 	if (priv->force_baud && ((port->tty->termios->c_cflag & CBAUD) != B0)) {
1742 		dbg("%s: forcing baud rate for this device", __FUNCTION__);
1743 		port->tty->termios->c_cflag &= ~CBAUD;
1744 		port->tty->termios->c_cflag |= priv->force_baud;
1745 	}
1746 
1747 	/* Force RTS-CTS if this device requires it. */
1748 	if (priv->force_rtscts) {
1749 		dbg("%s: forcing rtscts for this device", __FUNCTION__);
1750 		port->tty->termios->c_cflag |= CRTSCTS;
1751 	}
1752 
1753 	cflag = port->tty->termios->c_cflag;
1754 
1755 	/* FIXME -For this cut I don't care if the line is really changing or
1756 	   not  - so just do the change regardless  - should be able to
1757 	   compare old_termios and tty->termios */
1758 	/* NOTE These routines can get interrupted by
1759 	   ftdi_sio_read_bulk_callback  - need to examine what this
1760            means - don't see any problems yet */
1761 
1762 	/* Set number of data bits, parity, stop bits */
1763 
1764 	urb_value = 0;
1765 	urb_value |= (cflag & CSTOPB ? FTDI_SIO_SET_DATA_STOP_BITS_2 :
1766 		      FTDI_SIO_SET_DATA_STOP_BITS_1);
1767 	urb_value |= (cflag & PARENB ?
1768 		      (cflag & PARODD ? FTDI_SIO_SET_DATA_PARITY_ODD :
1769 		       FTDI_SIO_SET_DATA_PARITY_EVEN) :
1770 		      FTDI_SIO_SET_DATA_PARITY_NONE);
1771 	if (cflag & CSIZE) {
1772 		switch (cflag & CSIZE) {
1773 		case CS5: urb_value |= 5; dbg("Setting CS5"); break;
1774 		case CS6: urb_value |= 6; dbg("Setting CS6"); break;
1775 		case CS7: urb_value |= 7; dbg("Setting CS7"); break;
1776 		case CS8: urb_value |= 8; dbg("Setting CS8"); break;
1777 		default:
1778 			err("CSIZE was set but not CS5-CS8");
1779 		}
1780 	}
1781 
1782 	/* This is needed by the break command since it uses the same command - but is
1783 	 *  or'ed with this value  */
1784 	priv->last_set_data_urb_value = urb_value;
1785 
1786 	if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1787 			    FTDI_SIO_SET_DATA_REQUEST,
1788 			    FTDI_SIO_SET_DATA_REQUEST_TYPE,
1789 			    urb_value , priv->interface,
1790 			    buf, 0, WDR_SHORT_TIMEOUT) < 0) {
1791 		err("%s FAILED to set databits/stopbits/parity", __FUNCTION__);
1792 	}
1793 
1794 	/* Now do the baudrate */
1795 	if ((cflag & CBAUD) == B0 ) {
1796 		/* Disable flow control */
1797 		if (usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1798 				    FTDI_SIO_SET_FLOW_CTRL_REQUEST,
1799 				    FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1800 				    0, priv->interface,
1801 				    buf, 0, WDR_TIMEOUT) < 0) {
1802 			err("%s error from disable flowcontrol urb", __FUNCTION__);
1803 		}
1804 		/* Drop RTS and DTR */
1805 		clear_mctrl(port, TIOCM_DTR | TIOCM_RTS);
1806 	} else {
1807 		/* set the baudrate determined before */
1808 		if (change_speed(port)) {
1809 			err("%s urb failed to set baurdrate", __FUNCTION__);
1810 		}
1811 		/* Ensure  RTS and DTR are raised */
1812 		set_mctrl(port, TIOCM_DTR | TIOCM_RTS);
1813 	}
1814 
1815 	/* Set flow control */
1816 	/* Note device also supports DTR/CD (ugh) and Xon/Xoff in hardware */
1817 	if (cflag & CRTSCTS) {
1818 		dbg("%s Setting to CRTSCTS flow control", __FUNCTION__);
1819 		if (usb_control_msg(dev,
1820 				    usb_sndctrlpipe(dev, 0),
1821 				    FTDI_SIO_SET_FLOW_CTRL_REQUEST,
1822 				    FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1823 				    0 , (FTDI_SIO_RTS_CTS_HS | priv->interface),
1824 				    buf, 0, WDR_TIMEOUT) < 0) {
1825 			err("urb failed to set to rts/cts flow control");
1826 		}
1827 
1828 	} else {
1829 		/*
1830 		 * Xon/Xoff code
1831 		 *
1832 		 * Check the IXOFF status in the iflag component of the termios structure
1833 		 * if IXOFF is not set, the pre-xon/xoff code is executed.
1834 		*/
1835 		if (iflag & IXOFF) {
1836 			dbg("%s  request to enable xonxoff iflag=%04x",__FUNCTION__,iflag);
1837 			// Try to enable the XON/XOFF on the ftdi_sio
1838 			// Set the vstart and vstop -- could have been done up above where
1839 			// a lot of other dereferencing is done but that would be very
1840 			// inefficient as vstart and vstop are not always needed
1841 			vstart=port->tty->termios->c_cc[VSTART];
1842 			vstop=port->tty->termios->c_cc[VSTOP];
1843 			urb_value=(vstop << 8) | (vstart);
1844 
1845 			if (usb_control_msg(dev,
1846 					    usb_sndctrlpipe(dev, 0),
1847 					    FTDI_SIO_SET_FLOW_CTRL_REQUEST,
1848 					    FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1849 					    urb_value , (FTDI_SIO_XON_XOFF_HS
1850 							 | priv->interface),
1851 					    buf, 0, WDR_TIMEOUT) < 0) {
1852 				err("urb failed to set to xon/xoff flow control");
1853 			}
1854 		} else {
1855 			/* else clause to only run if cfag ! CRTSCTS and iflag ! XOFF */
1856 			/* CHECKME Assuming XON/XOFF handled by tty stack - not by device */
1857 			dbg("%s Turning off hardware flow control", __FUNCTION__);
1858 			if (usb_control_msg(dev,
1859 					    usb_sndctrlpipe(dev, 0),
1860 					    FTDI_SIO_SET_FLOW_CTRL_REQUEST,
1861 					    FTDI_SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1862 					    0, priv->interface,
1863 					    buf, 0, WDR_TIMEOUT) < 0) {
1864 				err("urb failed to clear flow control");
1865 			}
1866 		}
1867 
1868 	}
1869 	return;
1870 } /* ftdi_termios */
1871 
1872 
1873 static int ftdi_tiocmget (struct usb_serial_port *port, struct file *file)
1874 {
1875 	struct ftdi_private *priv = usb_get_serial_port_data(port);
1876 	unsigned char buf[2];
1877 	int ret;
1878 
1879 	dbg("%s TIOCMGET", __FUNCTION__);
1880 	switch (priv->chip_type) {
1881 	case SIO:
1882 		/* Request the status from the device */
1883 		if ((ret = usb_control_msg(port->serial->dev,
1884 					   usb_rcvctrlpipe(port->serial->dev, 0),
1885 					   FTDI_SIO_GET_MODEM_STATUS_REQUEST,
1886 					   FTDI_SIO_GET_MODEM_STATUS_REQUEST_TYPE,
1887 					   0, 0,
1888 					   buf, 1, WDR_TIMEOUT)) < 0 ) {
1889 			err("%s Could not get modem status of device - err: %d", __FUNCTION__,
1890 			    ret);
1891 			return(ret);
1892 		}
1893 		break;
1894 	case FT8U232AM:
1895 	case FT232BM:
1896 	case FT2232C:
1897 		/* the 8U232AM returns a two byte value (the sio is a 1 byte value) - in the same
1898 		   format as the data returned from the in point */
1899 		if ((ret = usb_control_msg(port->serial->dev,
1900 					   usb_rcvctrlpipe(port->serial->dev, 0),
1901 					   FTDI_SIO_GET_MODEM_STATUS_REQUEST,
1902 					   FTDI_SIO_GET_MODEM_STATUS_REQUEST_TYPE,
1903 					   0, priv->interface,
1904 					   buf, 2, WDR_TIMEOUT)) < 0 ) {
1905 			err("%s Could not get modem status of device - err: %d", __FUNCTION__,
1906 			    ret);
1907 			return(ret);
1908 		}
1909 		break;
1910 	default:
1911 		return -EFAULT;
1912 		break;
1913 	}
1914 
1915 	return  (buf[0] & FTDI_SIO_DSR_MASK ? TIOCM_DSR : 0) |
1916 		(buf[0] & FTDI_SIO_CTS_MASK ? TIOCM_CTS : 0) |
1917 		(buf[0]  & FTDI_SIO_RI_MASK  ? TIOCM_RI  : 0) |
1918 		(buf[0]  & FTDI_SIO_RLSD_MASK ? TIOCM_CD  : 0) |
1919 		priv->last_dtr_rts;
1920 }
1921 
1922 static int ftdi_tiocmset(struct usb_serial_port *port, struct file * file, unsigned int set, unsigned int clear)
1923 {
1924 	dbg("%s TIOCMSET", __FUNCTION__);
1925 	return update_mctrl(port, set, clear);
1926 }
1927 
1928 
1929 static int ftdi_ioctl (struct usb_serial_port *port, struct file * file, unsigned int cmd, unsigned long arg)
1930 {
1931 	struct ftdi_private *priv = usb_get_serial_port_data(port);
1932 
1933 	dbg("%s cmd 0x%04x", __FUNCTION__, cmd);
1934 
1935 	/* Based on code from acm.c and others */
1936 	switch (cmd) {
1937 
1938 	case TIOCGSERIAL: /* gets serial port data */
1939 		return get_serial_info(port, (struct serial_struct __user *) arg);
1940 
1941 	case TIOCSSERIAL: /* sets serial port data */
1942 		return set_serial_info(port, (struct serial_struct __user *) arg);
1943 
1944 	/*
1945 	 * Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
1946 	 * - mask passed in arg for lines of interest
1947 	 *   (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
1948 	 * Caller should use TIOCGICOUNT to see which one it was.
1949 	 *
1950 	 * This code is borrowed from linux/drivers/char/serial.c
1951 	 */
1952 	case TIOCMIWAIT:
1953 		while (priv != NULL) {
1954 			interruptible_sleep_on(&priv->delta_msr_wait);
1955 			/* see if a signal did it */
1956 			if (signal_pending(current))
1957 				return -ERESTARTSYS;
1958 			else {
1959 				char diff = priv->diff_status;
1960 
1961 				if (diff == 0) {
1962 					return -EIO; /* no change => error */
1963 				}
1964 
1965 				/* Consume all events */
1966 				priv->diff_status = 0;
1967 
1968 				/* Return 0 if caller wanted to know about these bits */
1969 				if ( ((arg & TIOCM_RNG) && (diff & FTDI_RS0_RI)) ||
1970 				     ((arg & TIOCM_DSR) && (diff & FTDI_RS0_DSR)) ||
1971 				     ((arg & TIOCM_CD)  && (diff & FTDI_RS0_RLSD)) ||
1972 				     ((arg & TIOCM_CTS) && (diff & FTDI_RS0_CTS)) ) {
1973 					return 0;
1974 				}
1975 				/*
1976 				 * Otherwise caller can't care less about what happened,
1977 				 * and so we continue to wait for more events.
1978 				 */
1979 			}
1980 		}
1981 		return(0);
1982 		break;
1983 	default:
1984 		break;
1985 
1986 	}
1987 
1988 
1989 	/* This is not necessarily an error - turns out the higher layers will do
1990 	 *  some ioctls itself (see comment above)
1991 	 */
1992 	dbg("%s arg not supported - it was 0x%04x - check /usr/include/asm/ioctls.h", __FUNCTION__, cmd);
1993 
1994 	return(-ENOIOCTLCMD);
1995 } /* ftdi_ioctl */
1996 
1997 
1998 static void ftdi_throttle (struct usb_serial_port *port)
1999 {
2000 	struct ftdi_private *priv = usb_get_serial_port_data(port);
2001 	unsigned long flags;
2002 
2003 	dbg("%s - port %d", __FUNCTION__, port->number);
2004 
2005 	spin_lock_irqsave(&priv->rx_lock, flags);
2006 	priv->rx_flags |= THROTTLED;
2007 	spin_unlock_irqrestore(&priv->rx_lock, flags);
2008 }
2009 
2010 
2011 static void ftdi_unthrottle (struct usb_serial_port *port)
2012 {
2013 	struct ftdi_private *priv = usb_get_serial_port_data(port);
2014 	int actually_throttled;
2015 	unsigned long flags;
2016 
2017 	dbg("%s - port %d", __FUNCTION__, port->number);
2018 
2019 	spin_lock_irqsave(&priv->rx_lock, flags);
2020 	actually_throttled = priv->rx_flags & ACTUALLY_THROTTLED;
2021 	priv->rx_flags &= ~(THROTTLED | ACTUALLY_THROTTLED);
2022 	spin_unlock_irqrestore(&priv->rx_lock, flags);
2023 
2024 	if (actually_throttled)
2025 		schedule_work(&priv->rx_work);
2026 }
2027 
2028 static int __init ftdi_init (void)
2029 {
2030 	int retval;
2031 
2032 	dbg("%s", __FUNCTION__);
2033 	retval = usb_serial_register(&ftdi_sio_device);
2034 	if (retval)
2035 		goto failed_sio_register;
2036 	retval = usb_register(&ftdi_driver);
2037 	if (retval)
2038 		goto failed_usb_register;
2039 
2040 	info(DRIVER_VERSION ":" DRIVER_DESC);
2041 	return 0;
2042 failed_usb_register:
2043 	usb_serial_deregister(&ftdi_sio_device);
2044 failed_sio_register:
2045 	return retval;
2046 }
2047 
2048 
2049 static void __exit ftdi_exit (void)
2050 {
2051 
2052 	dbg("%s", __FUNCTION__);
2053 
2054 	usb_deregister (&ftdi_driver);
2055 	usb_serial_deregister (&ftdi_sio_device);
2056 
2057 }
2058 
2059 
2060 module_init(ftdi_init);
2061 module_exit(ftdi_exit);
2062 
2063 MODULE_AUTHOR( DRIVER_AUTHOR );
2064 MODULE_DESCRIPTION( DRIVER_DESC );
2065 MODULE_LICENSE("GPL");
2066 
2067 module_param(debug, bool, S_IRUGO | S_IWUSR);
2068 MODULE_PARM_DESC(debug, "Debug enabled or not");
2069 
2070