xref: /openbmc/linux/drivers/tty/n_gsm.c (revision a583bf18)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * n_gsm.c GSM 0710 tty multiplexor
4  * Copyright (c) 2009/10 Intel Corporation
5  *
6  *	* THIS IS A DEVELOPMENT SNAPSHOT IT IS NOT A FINAL RELEASE *
7  *
8  * TO DO:
9  *	Mostly done:	ioctls for setting modes/timing
10  *	Partly done:	hooks so you can pull off frames to non tty devs
11  *	Restart DLCI 0 when it closes ?
12  *	Improve the tx engine
13  *	Resolve tx side locking by adding a queue_head and routing
14  *		all control traffic via it
15  *	General tidy/document
16  *	Review the locking/move to refcounts more (mux now moved to an
17  *		alloc/free model ready)
18  *	Use newest tty open/close port helpers and install hooks
19  *	What to do about power functions ?
20  *	Termios setting and negotiation
21  *	Do we need a 'which mux are you' ioctl to correlate mux and tty sets
22  *
23  */
24 
25 #include <linux/types.h>
26 #include <linux/major.h>
27 #include <linux/errno.h>
28 #include <linux/signal.h>
29 #include <linux/fcntl.h>
30 #include <linux/sched/signal.h>
31 #include <linux/interrupt.h>
32 #include <linux/tty.h>
33 #include <linux/ctype.h>
34 #include <linux/mm.h>
35 #include <linux/string.h>
36 #include <linux/slab.h>
37 #include <linux/poll.h>
38 #include <linux/bitops.h>
39 #include <linux/file.h>
40 #include <linux/uaccess.h>
41 #include <linux/module.h>
42 #include <linux/timer.h>
43 #include <linux/tty_flip.h>
44 #include <linux/tty_driver.h>
45 #include <linux/serial.h>
46 #include <linux/kfifo.h>
47 #include <linux/skbuff.h>
48 #include <net/arp.h>
49 #include <linux/ip.h>
50 #include <linux/netdevice.h>
51 #include <linux/etherdevice.h>
52 #include <linux/gsmmux.h>
53 #include "tty.h"
54 
55 static int debug;
56 module_param(debug, int, 0600);
57 
58 /* Defaults: these are from the specification */
59 
60 #define T1	10		/* 100mS */
61 #define T2	34		/* 333mS */
62 #define N2	3		/* Retry 3 times */
63 
64 /* Use long timers for testing at low speed with debug on */
65 #ifdef DEBUG_TIMING
66 #define T1	100
67 #define T2	200
68 #endif
69 
70 /*
71  * Semi-arbitrary buffer size limits. 0710 is normally run with 32-64 byte
72  * limits so this is plenty
73  */
74 #define MAX_MRU 1500
75 #define MAX_MTU 1500
76 /* SOF, ADDR, CTRL, LEN1, LEN2, ..., FCS, EOF */
77 #define PROT_OVERHEAD 7
78 #define	GSM_NET_TX_TIMEOUT (HZ*10)
79 
80 /*
81  *	struct gsm_mux_net	-	network interface
82  *
83  *	Created when net interface is initialized.
84  */
85 struct gsm_mux_net {
86 	struct kref ref;
87 	struct gsm_dlci *dlci;
88 };
89 
90 /*
91  *	Each block of data we have queued to go out is in the form of
92  *	a gsm_msg which holds everything we need in a link layer independent
93  *	format
94  */
95 
96 struct gsm_msg {
97 	struct list_head list;
98 	u8 addr;		/* DLCI address + flags */
99 	u8 ctrl;		/* Control byte + flags */
100 	unsigned int len;	/* Length of data block (can be zero) */
101 	unsigned char *data;	/* Points into buffer but not at the start */
102 	unsigned char buffer[];
103 };
104 
105 enum gsm_dlci_state {
106 	DLCI_CLOSED,
107 	DLCI_OPENING,		/* Sending SABM not seen UA */
108 	DLCI_OPEN,		/* SABM/UA complete */
109 	DLCI_CLOSING,		/* Sending DISC not seen UA/DM */
110 };
111 
112 enum gsm_dlci_mode {
113 	DLCI_MODE_ABM,		/* Normal Asynchronous Balanced Mode */
114 	DLCI_MODE_ADM,		/* Asynchronous Disconnected Mode */
115 };
116 
117 /*
118  *	Each active data link has a gsm_dlci structure associated which ties
119  *	the link layer to an optional tty (if the tty side is open). To avoid
120  *	complexity right now these are only ever freed up when the mux is
121  *	shut down.
122  *
123  *	At the moment we don't free DLCI objects until the mux is torn down
124  *	this avoid object life time issues but might be worth review later.
125  */
126 
127 struct gsm_dlci {
128 	struct gsm_mux *gsm;
129 	int addr;
130 	enum gsm_dlci_state state;
131 	struct mutex mutex;
132 
133 	/* Link layer */
134 	enum gsm_dlci_mode mode;
135 	spinlock_t lock;	/* Protects the internal state */
136 	struct timer_list t1;	/* Retransmit timer for SABM and UA */
137 	int retries;
138 	/* Uplink tty if active */
139 	struct tty_port port;	/* The tty bound to this DLCI if there is one */
140 #define TX_SIZE		4096    /* Must be power of 2. */
141 	struct kfifo fifo;	/* Queue fifo for the DLCI */
142 	int adaption;		/* Adaption layer in use */
143 	int prev_adaption;
144 	u32 modem_rx;		/* Our incoming virtual modem lines */
145 	u32 modem_tx;		/* Our outgoing modem lines */
146 	bool dead;		/* Refuse re-open */
147 	/* Flow control */
148 	bool throttled;		/* Private copy of throttle state */
149 	bool constipated;	/* Throttle status for outgoing */
150 	/* Packetised I/O */
151 	struct sk_buff *skb;	/* Frame being sent */
152 	struct sk_buff_head skb_list;	/* Queued frames */
153 	/* Data handling callback */
154 	void (*data)(struct gsm_dlci *dlci, const u8 *data, int len);
155 	void (*prev_data)(struct gsm_dlci *dlci, const u8 *data, int len);
156 	struct net_device *net; /* network interface, if created */
157 };
158 
159 /* DLCI 0, 62/63 are special or reserved see gsmtty_open */
160 
161 #define NUM_DLCI		64
162 
163 /*
164  *	DLCI 0 is used to pass control blocks out of band of the data
165  *	flow (and with a higher link priority). One command can be outstanding
166  *	at a time and we use this structure to manage them. They are created
167  *	and destroyed by the user context, and updated by the receive paths
168  *	and timers
169  */
170 
171 struct gsm_control {
172 	u8 cmd;		/* Command we are issuing */
173 	u8 *data;	/* Data for the command in case we retransmit */
174 	int len;	/* Length of block for retransmission */
175 	int done;	/* Done flag */
176 	int error;	/* Error if any */
177 };
178 
179 enum gsm_mux_state {
180 	GSM_SEARCH,
181 	GSM_START,
182 	GSM_ADDRESS,
183 	GSM_CONTROL,
184 	GSM_LEN,
185 	GSM_DATA,
186 	GSM_FCS,
187 	GSM_OVERRUN,
188 	GSM_LEN0,
189 	GSM_LEN1,
190 	GSM_SSOF,
191 };
192 
193 /*
194  *	Each GSM mux we have is represented by this structure. If we are
195  *	operating as an ldisc then we use this structure as our ldisc
196  *	state. We need to sort out lifetimes and locking with respect
197  *	to the gsm mux array. For now we don't free DLCI objects that
198  *	have been instantiated until the mux itself is terminated.
199  *
200  *	To consider further: tty open versus mux shutdown.
201  */
202 
203 struct gsm_mux {
204 	struct tty_struct *tty;		/* The tty our ldisc is bound to */
205 	spinlock_t lock;
206 	struct mutex mutex;
207 	unsigned int num;
208 	struct kref ref;
209 
210 	/* Events on the GSM channel */
211 	wait_queue_head_t event;
212 
213 	/* Bits for GSM mode decoding */
214 
215 	/* Framing Layer */
216 	unsigned char *buf;
217 	enum gsm_mux_state state;
218 	unsigned int len;
219 	unsigned int address;
220 	unsigned int count;
221 	bool escape;
222 	int encoding;
223 	u8 control;
224 	u8 fcs;
225 	u8 *txframe;			/* TX framing buffer */
226 
227 	/* Method for the receiver side */
228 	void (*receive)(struct gsm_mux *gsm, u8 ch);
229 
230 	/* Link Layer */
231 	unsigned int mru;
232 	unsigned int mtu;
233 	int initiator;			/* Did we initiate connection */
234 	bool dead;			/* Has the mux been shut down */
235 	struct gsm_dlci *dlci[NUM_DLCI];
236 	int old_c_iflag;		/* termios c_iflag value before attach */
237 	bool constipated;		/* Asked by remote to shut up */
238 
239 	spinlock_t tx_lock;
240 	unsigned int tx_bytes;		/* TX data outstanding */
241 #define TX_THRESH_HI		8192
242 #define TX_THRESH_LO		2048
243 	struct list_head tx_list;	/* Pending data packets */
244 
245 	/* Control messages */
246 	struct timer_list t2_timer;	/* Retransmit timer for commands */
247 	int cretries;			/* Command retry counter */
248 	struct gsm_control *pending_cmd;/* Our current pending command */
249 	spinlock_t control_lock;	/* Protects the pending command */
250 
251 	/* Configuration */
252 	int adaption;		/* 1 or 2 supported */
253 	u8 ftype;		/* UI or UIH */
254 	int t1, t2;		/* Timers in 1/100th of a sec */
255 	int n2;			/* Retry count */
256 
257 	/* Statistics (not currently exposed) */
258 	unsigned long bad_fcs;
259 	unsigned long malformed;
260 	unsigned long io_error;
261 	unsigned long bad_size;
262 	unsigned long unsupported;
263 };
264 
265 
266 /*
267  *	Mux objects - needed so that we can translate a tty index into the
268  *	relevant mux and DLCI.
269  */
270 
271 #define MAX_MUX		4			/* 256 minors */
272 static struct gsm_mux *gsm_mux[MAX_MUX];	/* GSM muxes */
273 static DEFINE_SPINLOCK(gsm_mux_lock);
274 
275 static struct tty_driver *gsm_tty_driver;
276 
277 /*
278  *	This section of the driver logic implements the GSM encodings
279  *	both the basic and the 'advanced'. Reliable transport is not
280  *	supported.
281  */
282 
283 #define CR			0x02
284 #define EA			0x01
285 #define	PF			0x10
286 
287 /* I is special: the rest are ..*/
288 #define RR			0x01
289 #define UI			0x03
290 #define RNR			0x05
291 #define REJ			0x09
292 #define DM			0x0F
293 #define SABM			0x2F
294 #define DISC			0x43
295 #define UA			0x63
296 #define	UIH			0xEF
297 
298 /* Channel commands */
299 #define CMD_NSC			0x09
300 #define CMD_TEST		0x11
301 #define CMD_PSC			0x21
302 #define CMD_RLS			0x29
303 #define CMD_FCOFF		0x31
304 #define CMD_PN			0x41
305 #define CMD_RPN			0x49
306 #define CMD_FCON		0x51
307 #define CMD_CLD			0x61
308 #define CMD_SNC			0x69
309 #define CMD_MSC			0x71
310 
311 /* Virtual modem bits */
312 #define MDM_FC			0x01
313 #define MDM_RTC			0x02
314 #define MDM_RTR			0x04
315 #define MDM_IC			0x20
316 #define MDM_DV			0x40
317 
318 #define GSM0_SOF		0xF9
319 #define GSM1_SOF		0x7E
320 #define GSM1_ESCAPE		0x7D
321 #define GSM1_ESCAPE_BITS	0x20
322 #define XON			0x11
323 #define XOFF			0x13
324 #define ISO_IEC_646_MASK	0x7F
325 
326 static const struct tty_port_operations gsm_port_ops;
327 
328 /*
329  *	CRC table for GSM 0710
330  */
331 
332 static const u8 gsm_fcs8[256] = {
333 	0x00, 0x91, 0xE3, 0x72, 0x07, 0x96, 0xE4, 0x75,
334 	0x0E, 0x9F, 0xED, 0x7C, 0x09, 0x98, 0xEA, 0x7B,
335 	0x1C, 0x8D, 0xFF, 0x6E, 0x1B, 0x8A, 0xF8, 0x69,
336 	0x12, 0x83, 0xF1, 0x60, 0x15, 0x84, 0xF6, 0x67,
337 	0x38, 0xA9, 0xDB, 0x4A, 0x3F, 0xAE, 0xDC, 0x4D,
338 	0x36, 0xA7, 0xD5, 0x44, 0x31, 0xA0, 0xD2, 0x43,
339 	0x24, 0xB5, 0xC7, 0x56, 0x23, 0xB2, 0xC0, 0x51,
340 	0x2A, 0xBB, 0xC9, 0x58, 0x2D, 0xBC, 0xCE, 0x5F,
341 	0x70, 0xE1, 0x93, 0x02, 0x77, 0xE6, 0x94, 0x05,
342 	0x7E, 0xEF, 0x9D, 0x0C, 0x79, 0xE8, 0x9A, 0x0B,
343 	0x6C, 0xFD, 0x8F, 0x1E, 0x6B, 0xFA, 0x88, 0x19,
344 	0x62, 0xF3, 0x81, 0x10, 0x65, 0xF4, 0x86, 0x17,
345 	0x48, 0xD9, 0xAB, 0x3A, 0x4F, 0xDE, 0xAC, 0x3D,
346 	0x46, 0xD7, 0xA5, 0x34, 0x41, 0xD0, 0xA2, 0x33,
347 	0x54, 0xC5, 0xB7, 0x26, 0x53, 0xC2, 0xB0, 0x21,
348 	0x5A, 0xCB, 0xB9, 0x28, 0x5D, 0xCC, 0xBE, 0x2F,
349 	0xE0, 0x71, 0x03, 0x92, 0xE7, 0x76, 0x04, 0x95,
350 	0xEE, 0x7F, 0x0D, 0x9C, 0xE9, 0x78, 0x0A, 0x9B,
351 	0xFC, 0x6D, 0x1F, 0x8E, 0xFB, 0x6A, 0x18, 0x89,
352 	0xF2, 0x63, 0x11, 0x80, 0xF5, 0x64, 0x16, 0x87,
353 	0xD8, 0x49, 0x3B, 0xAA, 0xDF, 0x4E, 0x3C, 0xAD,
354 	0xD6, 0x47, 0x35, 0xA4, 0xD1, 0x40, 0x32, 0xA3,
355 	0xC4, 0x55, 0x27, 0xB6, 0xC3, 0x52, 0x20, 0xB1,
356 	0xCA, 0x5B, 0x29, 0xB8, 0xCD, 0x5C, 0x2E, 0xBF,
357 	0x90, 0x01, 0x73, 0xE2, 0x97, 0x06, 0x74, 0xE5,
358 	0x9E, 0x0F, 0x7D, 0xEC, 0x99, 0x08, 0x7A, 0xEB,
359 	0x8C, 0x1D, 0x6F, 0xFE, 0x8B, 0x1A, 0x68, 0xF9,
360 	0x82, 0x13, 0x61, 0xF0, 0x85, 0x14, 0x66, 0xF7,
361 	0xA8, 0x39, 0x4B, 0xDA, 0xAF, 0x3E, 0x4C, 0xDD,
362 	0xA6, 0x37, 0x45, 0xD4, 0xA1, 0x30, 0x42, 0xD3,
363 	0xB4, 0x25, 0x57, 0xC6, 0xB3, 0x22, 0x50, 0xC1,
364 	0xBA, 0x2B, 0x59, 0xC8, 0xBD, 0x2C, 0x5E, 0xCF
365 };
366 
367 #define INIT_FCS	0xFF
368 #define GOOD_FCS	0xCF
369 
370 static int gsmld_output(struct gsm_mux *gsm, u8 *data, int len);
371 static int gsm_modem_update(struct gsm_dlci *dlci, u8 brk);
372 
373 /**
374  *	gsm_fcs_add	-	update FCS
375  *	@fcs: Current FCS
376  *	@c: Next data
377  *
378  *	Update the FCS to include c. Uses the algorithm in the specification
379  *	notes.
380  */
381 
382 static inline u8 gsm_fcs_add(u8 fcs, u8 c)
383 {
384 	return gsm_fcs8[fcs ^ c];
385 }
386 
387 /**
388  *	gsm_fcs_add_block	-	update FCS for a block
389  *	@fcs: Current FCS
390  *	@c: buffer of data
391  *	@len: length of buffer
392  *
393  *	Update the FCS to include c. Uses the algorithm in the specification
394  *	notes.
395  */
396 
397 static inline u8 gsm_fcs_add_block(u8 fcs, u8 *c, int len)
398 {
399 	while (len--)
400 		fcs = gsm_fcs8[fcs ^ *c++];
401 	return fcs;
402 }
403 
404 /**
405  *	gsm_read_ea		-	read a byte into an EA
406  *	@val: variable holding value
407  *	@c: byte going into the EA
408  *
409  *	Processes one byte of an EA. Updates the passed variable
410  *	and returns 1 if the EA is now completely read
411  */
412 
413 static int gsm_read_ea(unsigned int *val, u8 c)
414 {
415 	/* Add the next 7 bits into the value */
416 	*val <<= 7;
417 	*val |= c >> 1;
418 	/* Was this the last byte of the EA 1 = yes*/
419 	return c & EA;
420 }
421 
422 /**
423  *	gsm_encode_modem	-	encode modem data bits
424  *	@dlci: DLCI to encode from
425  *
426  *	Returns the correct GSM encoded modem status bits (6 bit field) for
427  *	the current status of the DLCI and attached tty object
428  */
429 
430 static u8 gsm_encode_modem(const struct gsm_dlci *dlci)
431 {
432 	u8 modembits = 0;
433 	/* FC is true flow control not modem bits */
434 	if (dlci->throttled)
435 		modembits |= MDM_FC;
436 	if (dlci->modem_tx & TIOCM_DTR)
437 		modembits |= MDM_RTC;
438 	if (dlci->modem_tx & TIOCM_RTS)
439 		modembits |= MDM_RTR;
440 	if (dlci->modem_tx & TIOCM_RI)
441 		modembits |= MDM_IC;
442 	if (dlci->modem_tx & TIOCM_CD || dlci->gsm->initiator)
443 		modembits |= MDM_DV;
444 	return modembits;
445 }
446 
447 /**
448  *	gsm_print_packet	-	display a frame for debug
449  *	@hdr: header to print before decode
450  *	@addr: address EA from the frame
451  *	@cr: C/R bit seen as initiator
452  *	@control: control including PF bit
453  *	@data: following data bytes
454  *	@dlen: length of data
455  *
456  *	Displays a packet in human readable format for debugging purposes. The
457  *	style is based on amateur radio LAP-B dump display.
458  */
459 
460 static void gsm_print_packet(const char *hdr, int addr, int cr,
461 					u8 control, const u8 *data, int dlen)
462 {
463 	if (!(debug & 1))
464 		return;
465 
466 	pr_info("%s %d) %c: ", hdr, addr, "RC"[cr]);
467 
468 	switch (control & ~PF) {
469 	case SABM:
470 		pr_cont("SABM");
471 		break;
472 	case UA:
473 		pr_cont("UA");
474 		break;
475 	case DISC:
476 		pr_cont("DISC");
477 		break;
478 	case DM:
479 		pr_cont("DM");
480 		break;
481 	case UI:
482 		pr_cont("UI");
483 		break;
484 	case UIH:
485 		pr_cont("UIH");
486 		break;
487 	default:
488 		if (!(control & 0x01)) {
489 			pr_cont("I N(S)%d N(R)%d",
490 				(control & 0x0E) >> 1, (control & 0xE0) >> 5);
491 		} else switch (control & 0x0F) {
492 			case RR:
493 				pr_cont("RR(%d)", (control & 0xE0) >> 5);
494 				break;
495 			case RNR:
496 				pr_cont("RNR(%d)", (control & 0xE0) >> 5);
497 				break;
498 			case REJ:
499 				pr_cont("REJ(%d)", (control & 0xE0) >> 5);
500 				break;
501 			default:
502 				pr_cont("[%02X]", control);
503 		}
504 	}
505 
506 	if (control & PF)
507 		pr_cont("(P)");
508 	else
509 		pr_cont("(F)");
510 
511 	print_hex_dump_bytes("", DUMP_PREFIX_NONE, data, dlen);
512 }
513 
514 
515 /*
516  *	Link level transmission side
517  */
518 
519 /**
520  *	gsm_stuff_frame	-	bytestuff a packet
521  *	@input: input buffer
522  *	@output: output buffer
523  *	@len: length of input
524  *
525  *	Expand a buffer by bytestuffing it. The worst case size change
526  *	is doubling and the caller is responsible for handing out
527  *	suitable sized buffers.
528  */
529 
530 static int gsm_stuff_frame(const u8 *input, u8 *output, int len)
531 {
532 	int olen = 0;
533 	while (len--) {
534 		if (*input == GSM1_SOF || *input == GSM1_ESCAPE
535 		    || (*input & ISO_IEC_646_MASK) == XON
536 		    || (*input & ISO_IEC_646_MASK) == XOFF) {
537 			*output++ = GSM1_ESCAPE;
538 			*output++ = *input++ ^ GSM1_ESCAPE_BITS;
539 			olen++;
540 		} else
541 			*output++ = *input++;
542 		olen++;
543 	}
544 	return olen;
545 }
546 
547 /**
548  *	gsm_send	-	send a control frame
549  *	@gsm: our GSM mux
550  *	@addr: address for control frame
551  *	@cr: command/response bit seen as initiator
552  *	@control:  control byte including PF bit
553  *
554  *	Format up and transmit a control frame. These do not go via the
555  *	queueing logic as they should be transmitted ahead of data when
556  *	they are needed.
557  *
558  *	FIXME: Lock versus data TX path
559  */
560 
561 static void gsm_send(struct gsm_mux *gsm, int addr, int cr, int control)
562 {
563 	int len;
564 	u8 cbuf[10];
565 	u8 ibuf[3];
566 	int ocr;
567 
568 	/* toggle C/R coding if not initiator */
569 	ocr = cr ^ (gsm->initiator ? 0 : 1);
570 
571 	switch (gsm->encoding) {
572 	case 0:
573 		cbuf[0] = GSM0_SOF;
574 		cbuf[1] = (addr << 2) | (ocr << 1) | EA;
575 		cbuf[2] = control;
576 		cbuf[3] = EA;	/* Length of data = 0 */
577 		cbuf[4] = 0xFF - gsm_fcs_add_block(INIT_FCS, cbuf + 1, 3);
578 		cbuf[5] = GSM0_SOF;
579 		len = 6;
580 		break;
581 	case 1:
582 	case 2:
583 		/* Control frame + packing (but not frame stuffing) in mode 1 */
584 		ibuf[0] = (addr << 2) | (ocr << 1) | EA;
585 		ibuf[1] = control;
586 		ibuf[2] = 0xFF - gsm_fcs_add_block(INIT_FCS, ibuf, 2);
587 		/* Stuffing may double the size worst case */
588 		len = gsm_stuff_frame(ibuf, cbuf + 1, 3);
589 		/* Now add the SOF markers */
590 		cbuf[0] = GSM1_SOF;
591 		cbuf[len + 1] = GSM1_SOF;
592 		/* FIXME: we can omit the lead one in many cases */
593 		len += 2;
594 		break;
595 	default:
596 		WARN_ON(1);
597 		return;
598 	}
599 	gsmld_output(gsm, cbuf, len);
600 	if (!gsm->initiator) {
601 		cr = cr & gsm->initiator;
602 		control = control & ~PF;
603 	}
604 	gsm_print_packet("-->", addr, cr, control, NULL, 0);
605 }
606 
607 /**
608  *	gsm_response	-	send a control response
609  *	@gsm: our GSM mux
610  *	@addr: address for control frame
611  *	@control:  control byte including PF bit
612  *
613  *	Format up and transmit a link level response frame.
614  */
615 
616 static inline void gsm_response(struct gsm_mux *gsm, int addr, int control)
617 {
618 	gsm_send(gsm, addr, 0, control);
619 }
620 
621 /**
622  *	gsm_command	-	send a control command
623  *	@gsm: our GSM mux
624  *	@addr: address for control frame
625  *	@control:  control byte including PF bit
626  *
627  *	Format up and transmit a link level command frame.
628  */
629 
630 static inline void gsm_command(struct gsm_mux *gsm, int addr, int control)
631 {
632 	gsm_send(gsm, addr, 1, control);
633 }
634 
635 /* Data transmission */
636 
637 #define HDR_LEN		6	/* ADDR CTRL [LEN.2] DATA FCS */
638 
639 /**
640  *	gsm_data_alloc		-	allocate data frame
641  *	@gsm: GSM mux
642  *	@addr: DLCI address
643  *	@len: length excluding header and FCS
644  *	@ctrl: control byte
645  *
646  *	Allocate a new data buffer for sending frames with data. Space is left
647  *	at the front for header bytes but that is treated as an implementation
648  *	detail and not for the high level code to use
649  */
650 
651 static struct gsm_msg *gsm_data_alloc(struct gsm_mux *gsm, u8 addr, int len,
652 								u8 ctrl)
653 {
654 	struct gsm_msg *m = kmalloc(sizeof(struct gsm_msg) + len + HDR_LEN,
655 								GFP_ATOMIC);
656 	if (m == NULL)
657 		return NULL;
658 	m->data = m->buffer + HDR_LEN - 1;	/* Allow for FCS */
659 	m->len = len;
660 	m->addr = addr;
661 	m->ctrl = ctrl;
662 	INIT_LIST_HEAD(&m->list);
663 	return m;
664 }
665 
666 /**
667  *	gsm_data_kick		-	poke the queue
668  *	@gsm: GSM Mux
669  *	@dlci: DLCI sending the data
670  *
671  *	The tty device has called us to indicate that room has appeared in
672  *	the transmit queue. Ram more data into the pipe if we have any
673  *	If we have been flow-stopped by a CMD_FCOFF, then we can only
674  *	send messages on DLCI0 until CMD_FCON
675  *
676  *	FIXME: lock against link layer control transmissions
677  */
678 
679 static void gsm_data_kick(struct gsm_mux *gsm, struct gsm_dlci *dlci)
680 {
681 	struct gsm_msg *msg, *nmsg;
682 	int len;
683 
684 	list_for_each_entry_safe(msg, nmsg, &gsm->tx_list, list) {
685 		if (gsm->constipated && msg->addr)
686 			continue;
687 		if (gsm->encoding != 0) {
688 			gsm->txframe[0] = GSM1_SOF;
689 			len = gsm_stuff_frame(msg->data,
690 						gsm->txframe + 1, msg->len);
691 			gsm->txframe[len + 1] = GSM1_SOF;
692 			len += 2;
693 		} else {
694 			gsm->txframe[0] = GSM0_SOF;
695 			memcpy(gsm->txframe + 1 , msg->data, msg->len);
696 			gsm->txframe[msg->len + 1] = GSM0_SOF;
697 			len = msg->len + 2;
698 		}
699 
700 		if (debug & 4)
701 			print_hex_dump_bytes("gsm_data_kick: ",
702 					     DUMP_PREFIX_OFFSET,
703 					     gsm->txframe, len);
704 		if (gsmld_output(gsm, gsm->txframe, len) <= 0)
705 			break;
706 		/* FIXME: Can eliminate one SOF in many more cases */
707 		gsm->tx_bytes -= msg->len;
708 
709 		list_del(&msg->list);
710 		kfree(msg);
711 
712 		if (dlci) {
713 			tty_port_tty_wakeup(&dlci->port);
714 		} else {
715 			int i = 0;
716 
717 			for (i = 0; i < NUM_DLCI; i++)
718 				if (gsm->dlci[i])
719 					tty_port_tty_wakeup(&gsm->dlci[i]->port);
720 		}
721 	}
722 }
723 
724 /**
725  *	__gsm_data_queue		-	queue a UI or UIH frame
726  *	@dlci: DLCI sending the data
727  *	@msg: message queued
728  *
729  *	Add data to the transmit queue and try and get stuff moving
730  *	out of the mux tty if not already doing so. The Caller must hold
731  *	the gsm tx lock.
732  */
733 
734 static void __gsm_data_queue(struct gsm_dlci *dlci, struct gsm_msg *msg)
735 {
736 	struct gsm_mux *gsm = dlci->gsm;
737 	u8 *dp = msg->data;
738 	u8 *fcs = dp + msg->len;
739 
740 	/* Fill in the header */
741 	if (gsm->encoding == 0) {
742 		if (msg->len < 128)
743 			*--dp = (msg->len << 1) | EA;
744 		else {
745 			*--dp = (msg->len >> 7);	/* bits 7 - 15 */
746 			*--dp = (msg->len & 127) << 1;	/* bits 0 - 6 */
747 		}
748 	}
749 
750 	*--dp = msg->ctrl;
751 	if (gsm->initiator)
752 		*--dp = (msg->addr << 2) | 2 | EA;
753 	else
754 		*--dp = (msg->addr << 2) | EA;
755 	*fcs = gsm_fcs_add_block(INIT_FCS, dp , msg->data - dp);
756 	/* Ugly protocol layering violation */
757 	if (msg->ctrl == UI || msg->ctrl == (UI|PF))
758 		*fcs = gsm_fcs_add_block(*fcs, msg->data, msg->len);
759 	*fcs = 0xFF - *fcs;
760 
761 	gsm_print_packet("Q> ", msg->addr, gsm->initiator, msg->ctrl,
762 							msg->data, msg->len);
763 
764 	/* Move the header back and adjust the length, also allow for the FCS
765 	   now tacked on the end */
766 	msg->len += (msg->data - dp) + 1;
767 	msg->data = dp;
768 
769 	/* Add to the actual output queue */
770 	list_add_tail(&msg->list, &gsm->tx_list);
771 	gsm->tx_bytes += msg->len;
772 	gsm_data_kick(gsm, dlci);
773 }
774 
775 /**
776  *	gsm_data_queue		-	queue a UI or UIH frame
777  *	@dlci: DLCI sending the data
778  *	@msg: message queued
779  *
780  *	Add data to the transmit queue and try and get stuff moving
781  *	out of the mux tty if not already doing so. Take the
782  *	the gsm tx lock and dlci lock.
783  */
784 
785 static void gsm_data_queue(struct gsm_dlci *dlci, struct gsm_msg *msg)
786 {
787 	unsigned long flags;
788 	spin_lock_irqsave(&dlci->gsm->tx_lock, flags);
789 	__gsm_data_queue(dlci, msg);
790 	spin_unlock_irqrestore(&dlci->gsm->tx_lock, flags);
791 }
792 
793 /**
794  *	gsm_dlci_data_output	-	try and push data out of a DLCI
795  *	@gsm: mux
796  *	@dlci: the DLCI to pull data from
797  *
798  *	Pull data from a DLCI and send it into the transmit queue if there
799  *	is data. Keep to the MRU of the mux. This path handles the usual tty
800  *	interface which is a byte stream with optional modem data.
801  *
802  *	Caller must hold the tx_lock of the mux.
803  */
804 
805 static int gsm_dlci_data_output(struct gsm_mux *gsm, struct gsm_dlci *dlci)
806 {
807 	struct gsm_msg *msg;
808 	u8 *dp;
809 	int len, total_size, size;
810 	int h = dlci->adaption - 1;
811 
812 	total_size = 0;
813 	while (1) {
814 		len = kfifo_len(&dlci->fifo);
815 		if (len == 0)
816 			return total_size;
817 
818 		/* MTU/MRU count only the data bits */
819 		if (len > gsm->mtu)
820 			len = gsm->mtu;
821 
822 		size = len + h;
823 
824 		msg = gsm_data_alloc(gsm, dlci->addr, size, gsm->ftype);
825 		/* FIXME: need a timer or something to kick this so it can't
826 		   get stuck with no work outstanding and no buffer free */
827 		if (msg == NULL)
828 			return -ENOMEM;
829 		dp = msg->data;
830 		switch (dlci->adaption) {
831 		case 1:	/* Unstructured */
832 			break;
833 		case 2:	/* Unstructed with modem bits.
834 		Always one byte as we never send inline break data */
835 			*dp++ = (gsm_encode_modem(dlci) << 1) | EA;
836 			break;
837 		}
838 		WARN_ON(kfifo_out_locked(&dlci->fifo, dp , len, &dlci->lock) != len);
839 		__gsm_data_queue(dlci, msg);
840 		total_size += size;
841 	}
842 	/* Bytes of data we used up */
843 	return total_size;
844 }
845 
846 /**
847  *	gsm_dlci_data_output_framed  -	try and push data out of a DLCI
848  *	@gsm: mux
849  *	@dlci: the DLCI to pull data from
850  *
851  *	Pull data from a DLCI and send it into the transmit queue if there
852  *	is data. Keep to the MRU of the mux. This path handles framed data
853  *	queued as skbuffs to the DLCI.
854  *
855  *	Caller must hold the tx_lock of the mux.
856  */
857 
858 static int gsm_dlci_data_output_framed(struct gsm_mux *gsm,
859 						struct gsm_dlci *dlci)
860 {
861 	struct gsm_msg *msg;
862 	u8 *dp;
863 	int len, size;
864 	int last = 0, first = 0;
865 	int overhead = 0;
866 
867 	/* One byte per frame is used for B/F flags */
868 	if (dlci->adaption == 4)
869 		overhead = 1;
870 
871 	/* dlci->skb is locked by tx_lock */
872 	if (dlci->skb == NULL) {
873 		dlci->skb = skb_dequeue_tail(&dlci->skb_list);
874 		if (dlci->skb == NULL)
875 			return 0;
876 		first = 1;
877 	}
878 	len = dlci->skb->len + overhead;
879 
880 	/* MTU/MRU count only the data bits */
881 	if (len > gsm->mtu) {
882 		if (dlci->adaption == 3) {
883 			/* Over long frame, bin it */
884 			dev_kfree_skb_any(dlci->skb);
885 			dlci->skb = NULL;
886 			return 0;
887 		}
888 		len = gsm->mtu;
889 	} else
890 		last = 1;
891 
892 	size = len + overhead;
893 	msg = gsm_data_alloc(gsm, dlci->addr, size, gsm->ftype);
894 
895 	/* FIXME: need a timer or something to kick this so it can't
896 	   get stuck with no work outstanding and no buffer free */
897 	if (msg == NULL) {
898 		skb_queue_tail(&dlci->skb_list, dlci->skb);
899 		dlci->skb = NULL;
900 		return -ENOMEM;
901 	}
902 	dp = msg->data;
903 
904 	if (dlci->adaption == 4) { /* Interruptible framed (Packetised Data) */
905 		/* Flag byte to carry the start/end info */
906 		*dp++ = last << 7 | first << 6 | 1;	/* EA */
907 		len--;
908 	}
909 	memcpy(dp, dlci->skb->data, len);
910 	skb_pull(dlci->skb, len);
911 	__gsm_data_queue(dlci, msg);
912 	if (last) {
913 		dev_kfree_skb_any(dlci->skb);
914 		dlci->skb = NULL;
915 	}
916 	return size;
917 }
918 
919 /**
920  *	gsm_dlci_modem_output	-	try and push modem status out of a DLCI
921  *	@gsm: mux
922  *	@dlci: the DLCI to pull modem status from
923  *	@brk: break signal
924  *
925  *	Push an empty frame in to the transmit queue to update the modem status
926  *	bits and to transmit an optional break.
927  *
928  *	Caller must hold the tx_lock of the mux.
929  */
930 
931 static int gsm_dlci_modem_output(struct gsm_mux *gsm, struct gsm_dlci *dlci,
932 				 u8 brk)
933 {
934 	u8 *dp = NULL;
935 	struct gsm_msg *msg;
936 	int size = 0;
937 
938 	/* for modem bits without break data */
939 	switch (dlci->adaption) {
940 	case 1: /* Unstructured */
941 		break;
942 	case 2: /* Unstructured with modem bits. */
943 		size++;
944 		if (brk > 0)
945 			size++;
946 		break;
947 	default:
948 		pr_err("%s: unsupported adaption %d\n", __func__,
949 		       dlci->adaption);
950 		return -EINVAL;
951 	}
952 
953 	msg = gsm_data_alloc(gsm, dlci->addr, size, gsm->ftype);
954 	if (!msg) {
955 		pr_err("%s: gsm_data_alloc error", __func__);
956 		return -ENOMEM;
957 	}
958 	dp = msg->data;
959 	switch (dlci->adaption) {
960 	case 1: /* Unstructured */
961 		break;
962 	case 2: /* Unstructured with modem bits. */
963 		if (brk == 0) {
964 			*dp++ = (gsm_encode_modem(dlci) << 1) | EA;
965 		} else {
966 			*dp++ = gsm_encode_modem(dlci) << 1;
967 			*dp++ = (brk << 4) | 2 | EA; /* Length, Break, EA */
968 		}
969 		break;
970 	default:
971 		/* Handled above */
972 		break;
973 	}
974 
975 	__gsm_data_queue(dlci, msg);
976 	return size;
977 }
978 
979 /**
980  *	gsm_dlci_data_sweep		-	look for data to send
981  *	@gsm: the GSM mux
982  *
983  *	Sweep the GSM mux channels in priority order looking for ones with
984  *	data to send. We could do with optimising this scan a bit. We aim
985  *	to fill the queue totally or up to TX_THRESH_HI bytes. Once we hit
986  *	TX_THRESH_LO we get called again
987  *
988  *	FIXME: We should round robin between groups and in theory you can
989  *	renegotiate DLCI priorities with optional stuff. Needs optimising.
990  */
991 
992 static void gsm_dlci_data_sweep(struct gsm_mux *gsm)
993 {
994 	int len;
995 	/* Priority ordering: We should do priority with RR of the groups */
996 	int i = 1;
997 
998 	while (i < NUM_DLCI) {
999 		struct gsm_dlci *dlci;
1000 
1001 		if (gsm->tx_bytes > TX_THRESH_HI)
1002 			break;
1003 		dlci = gsm->dlci[i];
1004 		if (dlci == NULL || dlci->constipated) {
1005 			i++;
1006 			continue;
1007 		}
1008 		if (dlci->adaption < 3 && !dlci->net)
1009 			len = gsm_dlci_data_output(gsm, dlci);
1010 		else
1011 			len = gsm_dlci_data_output_framed(gsm, dlci);
1012 		if (len < 0)
1013 			break;
1014 		/* DLCI empty - try the next */
1015 		if (len == 0)
1016 			i++;
1017 	}
1018 }
1019 
1020 /**
1021  *	gsm_dlci_data_kick	-	transmit if possible
1022  *	@dlci: DLCI to kick
1023  *
1024  *	Transmit data from this DLCI if the queue is empty. We can't rely on
1025  *	a tty wakeup except when we filled the pipe so we need to fire off
1026  *	new data ourselves in other cases.
1027  */
1028 
1029 static void gsm_dlci_data_kick(struct gsm_dlci *dlci)
1030 {
1031 	unsigned long flags;
1032 	int sweep;
1033 
1034 	if (dlci->constipated)
1035 		return;
1036 
1037 	spin_lock_irqsave(&dlci->gsm->tx_lock, flags);
1038 	/* If we have nothing running then we need to fire up */
1039 	sweep = (dlci->gsm->tx_bytes < TX_THRESH_LO);
1040 	if (dlci->gsm->tx_bytes == 0) {
1041 		if (dlci->net)
1042 			gsm_dlci_data_output_framed(dlci->gsm, dlci);
1043 		else
1044 			gsm_dlci_data_output(dlci->gsm, dlci);
1045 	}
1046 	if (sweep)
1047 		gsm_dlci_data_sweep(dlci->gsm);
1048 	spin_unlock_irqrestore(&dlci->gsm->tx_lock, flags);
1049 }
1050 
1051 /*
1052  *	Control message processing
1053  */
1054 
1055 
1056 /**
1057  *	gsm_control_reply	-	send a response frame to a control
1058  *	@gsm: gsm channel
1059  *	@cmd: the command to use
1060  *	@data: data to follow encoded info
1061  *	@dlen: length of data
1062  *
1063  *	Encode up and queue a UI/UIH frame containing our response.
1064  */
1065 
1066 static void gsm_control_reply(struct gsm_mux *gsm, int cmd, const u8 *data,
1067 					int dlen)
1068 {
1069 	struct gsm_msg *msg;
1070 	msg = gsm_data_alloc(gsm, 0, dlen + 2, gsm->ftype);
1071 	if (msg == NULL)
1072 		return;
1073 	msg->data[0] = (cmd & 0xFE) << 1 | EA;	/* Clear C/R */
1074 	msg->data[1] = (dlen << 1) | EA;
1075 	memcpy(msg->data + 2, data, dlen);
1076 	gsm_data_queue(gsm->dlci[0], msg);
1077 }
1078 
1079 /**
1080  *	gsm_process_modem	-	process received modem status
1081  *	@tty: virtual tty bound to the DLCI
1082  *	@dlci: DLCI to affect
1083  *	@modem: modem bits (full EA)
1084  *	@slen: number of signal octets
1085  *
1086  *	Used when a modem control message or line state inline in adaption
1087  *	layer 2 is processed. Sort out the local modem state and throttles
1088  */
1089 
1090 static void gsm_process_modem(struct tty_struct *tty, struct gsm_dlci *dlci,
1091 							u32 modem, int slen)
1092 {
1093 	int  mlines = 0;
1094 	u8 brk = 0;
1095 	int fc;
1096 
1097 	/* The modem status command can either contain one octet (V.24 signals)
1098 	 * or two octets (V.24 signals + break signals). This is specified in
1099 	 * section 5.4.6.3.7 of the 07.10 mux spec.
1100 	 */
1101 
1102 	if (slen == 1)
1103 		modem = modem & 0x7f;
1104 	else {
1105 		brk = modem & 0x7f;
1106 		modem = (modem >> 7) & 0x7f;
1107 	}
1108 
1109 	/* Flow control/ready to communicate */
1110 	fc = (modem & MDM_FC) || !(modem & MDM_RTR);
1111 	if (fc && !dlci->constipated) {
1112 		/* Need to throttle our output on this device */
1113 		dlci->constipated = true;
1114 	} else if (!fc && dlci->constipated) {
1115 		dlci->constipated = false;
1116 		gsm_dlci_data_kick(dlci);
1117 	}
1118 
1119 	/* Map modem bits */
1120 	if (modem & MDM_RTC)
1121 		mlines |= TIOCM_DSR | TIOCM_DTR;
1122 	if (modem & MDM_RTR)
1123 		mlines |= TIOCM_RTS | TIOCM_CTS;
1124 	if (modem & MDM_IC)
1125 		mlines |= TIOCM_RI;
1126 	if (modem & MDM_DV)
1127 		mlines |= TIOCM_CD;
1128 
1129 	/* Carrier drop -> hangup */
1130 	if (tty) {
1131 		if ((mlines & TIOCM_CD) == 0 && (dlci->modem_rx & TIOCM_CD))
1132 			if (!C_CLOCAL(tty))
1133 				tty_hangup(tty);
1134 	}
1135 	if (brk & 0x01)
1136 		tty_insert_flip_char(&dlci->port, 0, TTY_BREAK);
1137 	dlci->modem_rx = mlines;
1138 }
1139 
1140 /**
1141  *	gsm_control_modem	-	modem status received
1142  *	@gsm: GSM channel
1143  *	@data: data following command
1144  *	@clen: command length
1145  *
1146  *	We have received a modem status control message. This is used by
1147  *	the GSM mux protocol to pass virtual modem line status and optionally
1148  *	to indicate break signals. Unpack it, convert to Linux representation
1149  *	and if need be stuff a break message down the tty.
1150  */
1151 
1152 static void gsm_control_modem(struct gsm_mux *gsm, const u8 *data, int clen)
1153 {
1154 	unsigned int addr = 0;
1155 	unsigned int modem = 0;
1156 	struct gsm_dlci *dlci;
1157 	int len = clen;
1158 	int slen;
1159 	const u8 *dp = data;
1160 	struct tty_struct *tty;
1161 
1162 	while (gsm_read_ea(&addr, *dp++) == 0) {
1163 		len--;
1164 		if (len == 0)
1165 			return;
1166 	}
1167 	/* Must be at least one byte following the EA */
1168 	len--;
1169 	if (len <= 0)
1170 		return;
1171 
1172 	addr >>= 1;
1173 	/* Closed port, or invalid ? */
1174 	if (addr == 0 || addr >= NUM_DLCI || gsm->dlci[addr] == NULL)
1175 		return;
1176 	dlci = gsm->dlci[addr];
1177 
1178 	slen = len;
1179 	while (gsm_read_ea(&modem, *dp++) == 0) {
1180 		len--;
1181 		if (len == 0)
1182 			return;
1183 	}
1184 	len--;
1185 	tty = tty_port_tty_get(&dlci->port);
1186 	gsm_process_modem(tty, dlci, modem, slen - len);
1187 	if (tty) {
1188 		tty_wakeup(tty);
1189 		tty_kref_put(tty);
1190 	}
1191 	gsm_control_reply(gsm, CMD_MSC, data, clen);
1192 }
1193 
1194 /**
1195  *	gsm_control_rls		-	remote line status
1196  *	@gsm: GSM channel
1197  *	@data: data bytes
1198  *	@clen: data length
1199  *
1200  *	The modem sends us a two byte message on the control channel whenever
1201  *	it wishes to send us an error state from the virtual link. Stuff
1202  *	this into the uplink tty if present
1203  */
1204 
1205 static void gsm_control_rls(struct gsm_mux *gsm, const u8 *data, int clen)
1206 {
1207 	struct tty_port *port;
1208 	unsigned int addr = 0;
1209 	u8 bits;
1210 	int len = clen;
1211 	const u8 *dp = data;
1212 
1213 	while (gsm_read_ea(&addr, *dp++) == 0) {
1214 		len--;
1215 		if (len == 0)
1216 			return;
1217 	}
1218 	/* Must be at least one byte following ea */
1219 	len--;
1220 	if (len <= 0)
1221 		return;
1222 	addr >>= 1;
1223 	/* Closed port, or invalid ? */
1224 	if (addr == 0 || addr >= NUM_DLCI || gsm->dlci[addr] == NULL)
1225 		return;
1226 	/* No error ? */
1227 	bits = *dp;
1228 	if ((bits & 1) == 0)
1229 		return;
1230 
1231 	port = &gsm->dlci[addr]->port;
1232 
1233 	if (bits & 2)
1234 		tty_insert_flip_char(port, 0, TTY_OVERRUN);
1235 	if (bits & 4)
1236 		tty_insert_flip_char(port, 0, TTY_PARITY);
1237 	if (bits & 8)
1238 		tty_insert_flip_char(port, 0, TTY_FRAME);
1239 
1240 	tty_flip_buffer_push(port);
1241 
1242 	gsm_control_reply(gsm, CMD_RLS, data, clen);
1243 }
1244 
1245 static void gsm_dlci_begin_close(struct gsm_dlci *dlci);
1246 
1247 /**
1248  *	gsm_control_message	-	DLCI 0 control processing
1249  *	@gsm: our GSM mux
1250  *	@command:  the command EA
1251  *	@data: data beyond the command/length EAs
1252  *	@clen: length
1253  *
1254  *	Input processor for control messages from the other end of the link.
1255  *	Processes the incoming request and queues a response frame or an
1256  *	NSC response if not supported
1257  */
1258 
1259 static void gsm_control_message(struct gsm_mux *gsm, unsigned int command,
1260 						const u8 *data, int clen)
1261 {
1262 	u8 buf[1];
1263 	unsigned long flags;
1264 
1265 	switch (command) {
1266 	case CMD_CLD: {
1267 		struct gsm_dlci *dlci = gsm->dlci[0];
1268 		/* Modem wishes to close down */
1269 		if (dlci) {
1270 			dlci->dead = true;
1271 			gsm->dead = true;
1272 			gsm_dlci_begin_close(dlci);
1273 		}
1274 		}
1275 		break;
1276 	case CMD_TEST:
1277 		/* Modem wishes to test, reply with the data */
1278 		gsm_control_reply(gsm, CMD_TEST, data, clen);
1279 		break;
1280 	case CMD_FCON:
1281 		/* Modem can accept data again */
1282 		gsm->constipated = false;
1283 		gsm_control_reply(gsm, CMD_FCON, NULL, 0);
1284 		/* Kick the link in case it is idling */
1285 		spin_lock_irqsave(&gsm->tx_lock, flags);
1286 		gsm_data_kick(gsm, NULL);
1287 		spin_unlock_irqrestore(&gsm->tx_lock, flags);
1288 		break;
1289 	case CMD_FCOFF:
1290 		/* Modem wants us to STFU */
1291 		gsm->constipated = true;
1292 		gsm_control_reply(gsm, CMD_FCOFF, NULL, 0);
1293 		break;
1294 	case CMD_MSC:
1295 		/* Out of band modem line change indicator for a DLCI */
1296 		gsm_control_modem(gsm, data, clen);
1297 		break;
1298 	case CMD_RLS:
1299 		/* Out of band error reception for a DLCI */
1300 		gsm_control_rls(gsm, data, clen);
1301 		break;
1302 	case CMD_PSC:
1303 		/* Modem wishes to enter power saving state */
1304 		gsm_control_reply(gsm, CMD_PSC, NULL, 0);
1305 		break;
1306 		/* Optional unsupported commands */
1307 	case CMD_PN:	/* Parameter negotiation */
1308 	case CMD_RPN:	/* Remote port negotiation */
1309 	case CMD_SNC:	/* Service negotiation command */
1310 	default:
1311 		/* Reply to bad commands with an NSC */
1312 		buf[0] = command;
1313 		gsm_control_reply(gsm, CMD_NSC, buf, 1);
1314 		break;
1315 	}
1316 }
1317 
1318 /**
1319  *	gsm_control_response	-	process a response to our control
1320  *	@gsm: our GSM mux
1321  *	@command: the command (response) EA
1322  *	@data: data beyond the command/length EA
1323  *	@clen: length
1324  *
1325  *	Process a response to an outstanding command. We only allow a single
1326  *	control message in flight so this is fairly easy. All the clean up
1327  *	is done by the caller, we just update the fields, flag it as done
1328  *	and return
1329  */
1330 
1331 static void gsm_control_response(struct gsm_mux *gsm, unsigned int command,
1332 						const u8 *data, int clen)
1333 {
1334 	struct gsm_control *ctrl;
1335 	unsigned long flags;
1336 
1337 	spin_lock_irqsave(&gsm->control_lock, flags);
1338 
1339 	ctrl = gsm->pending_cmd;
1340 	/* Does the reply match our command */
1341 	command |= 1;
1342 	if (ctrl != NULL && (command == ctrl->cmd || command == CMD_NSC)) {
1343 		/* Our command was replied to, kill the retry timer */
1344 		del_timer(&gsm->t2_timer);
1345 		gsm->pending_cmd = NULL;
1346 		/* Rejected by the other end */
1347 		if (command == CMD_NSC)
1348 			ctrl->error = -EOPNOTSUPP;
1349 		ctrl->done = 1;
1350 		wake_up(&gsm->event);
1351 	}
1352 	spin_unlock_irqrestore(&gsm->control_lock, flags);
1353 }
1354 
1355 /**
1356  *	gsm_control_transmit	-	send control packet
1357  *	@gsm: gsm mux
1358  *	@ctrl: frame to send
1359  *
1360  *	Send out a pending control command (called under control lock)
1361  */
1362 
1363 static void gsm_control_transmit(struct gsm_mux *gsm, struct gsm_control *ctrl)
1364 {
1365 	struct gsm_msg *msg = gsm_data_alloc(gsm, 0, ctrl->len + 2, gsm->ftype);
1366 	if (msg == NULL)
1367 		return;
1368 	msg->data[0] = (ctrl->cmd << 1) | CR | EA;	/* command */
1369 	msg->data[1] = (ctrl->len << 1) | EA;
1370 	memcpy(msg->data + 2, ctrl->data, ctrl->len);
1371 	gsm_data_queue(gsm->dlci[0], msg);
1372 }
1373 
1374 /**
1375  *	gsm_control_retransmit	-	retransmit a control frame
1376  *	@t: timer contained in our gsm object
1377  *
1378  *	Called off the T2 timer expiry in order to retransmit control frames
1379  *	that have been lost in the system somewhere. The control_lock protects
1380  *	us from colliding with another sender or a receive completion event.
1381  *	In that situation the timer may still occur in a small window but
1382  *	gsm->pending_cmd will be NULL and we just let the timer expire.
1383  */
1384 
1385 static void gsm_control_retransmit(struct timer_list *t)
1386 {
1387 	struct gsm_mux *gsm = from_timer(gsm, t, t2_timer);
1388 	struct gsm_control *ctrl;
1389 	unsigned long flags;
1390 	spin_lock_irqsave(&gsm->control_lock, flags);
1391 	ctrl = gsm->pending_cmd;
1392 	if (ctrl) {
1393 		if (gsm->cretries == 0) {
1394 			gsm->pending_cmd = NULL;
1395 			ctrl->error = -ETIMEDOUT;
1396 			ctrl->done = 1;
1397 			spin_unlock_irqrestore(&gsm->control_lock, flags);
1398 			wake_up(&gsm->event);
1399 			return;
1400 		}
1401 		gsm->cretries--;
1402 		gsm_control_transmit(gsm, ctrl);
1403 		mod_timer(&gsm->t2_timer, jiffies + gsm->t2 * HZ / 100);
1404 	}
1405 	spin_unlock_irqrestore(&gsm->control_lock, flags);
1406 }
1407 
1408 /**
1409  *	gsm_control_send	-	send a control frame on DLCI 0
1410  *	@gsm: the GSM channel
1411  *	@command: command  to send including CR bit
1412  *	@data: bytes of data (must be kmalloced)
1413  *	@clen: length of the block to send
1414  *
1415  *	Queue and dispatch a control command. Only one command can be
1416  *	active at a time. In theory more can be outstanding but the matching
1417  *	gets really complicated so for now stick to one outstanding.
1418  */
1419 
1420 static struct gsm_control *gsm_control_send(struct gsm_mux *gsm,
1421 		unsigned int command, u8 *data, int clen)
1422 {
1423 	struct gsm_control *ctrl = kzalloc(sizeof(struct gsm_control),
1424 						GFP_KERNEL);
1425 	unsigned long flags;
1426 	if (ctrl == NULL)
1427 		return NULL;
1428 retry:
1429 	wait_event(gsm->event, gsm->pending_cmd == NULL);
1430 	spin_lock_irqsave(&gsm->control_lock, flags);
1431 	if (gsm->pending_cmd != NULL) {
1432 		spin_unlock_irqrestore(&gsm->control_lock, flags);
1433 		goto retry;
1434 	}
1435 	ctrl->cmd = command;
1436 	ctrl->data = data;
1437 	ctrl->len = clen;
1438 	gsm->pending_cmd = ctrl;
1439 
1440 	/* If DLCI0 is in ADM mode skip retries, it won't respond */
1441 	if (gsm->dlci[0]->mode == DLCI_MODE_ADM)
1442 		gsm->cretries = 0;
1443 	else
1444 		gsm->cretries = gsm->n2;
1445 
1446 	mod_timer(&gsm->t2_timer, jiffies + gsm->t2 * HZ / 100);
1447 	gsm_control_transmit(gsm, ctrl);
1448 	spin_unlock_irqrestore(&gsm->control_lock, flags);
1449 	return ctrl;
1450 }
1451 
1452 /**
1453  *	gsm_control_wait	-	wait for a control to finish
1454  *	@gsm: GSM mux
1455  *	@control: control we are waiting on
1456  *
1457  *	Waits for the control to complete or time out. Frees any used
1458  *	resources and returns 0 for success, or an error if the remote
1459  *	rejected or ignored the request.
1460  */
1461 
1462 static int gsm_control_wait(struct gsm_mux *gsm, struct gsm_control *control)
1463 {
1464 	int err;
1465 	wait_event(gsm->event, control->done == 1);
1466 	err = control->error;
1467 	kfree(control);
1468 	return err;
1469 }
1470 
1471 
1472 /*
1473  *	DLCI level handling: Needs krefs
1474  */
1475 
1476 /*
1477  *	State transitions and timers
1478  */
1479 
1480 /**
1481  *	gsm_dlci_close		-	a DLCI has closed
1482  *	@dlci: DLCI that closed
1483  *
1484  *	Perform processing when moving a DLCI into closed state. If there
1485  *	is an attached tty this is hung up
1486  */
1487 
1488 static void gsm_dlci_close(struct gsm_dlci *dlci)
1489 {
1490 	unsigned long flags;
1491 
1492 	del_timer(&dlci->t1);
1493 	if (debug & 8)
1494 		pr_debug("DLCI %d goes closed.\n", dlci->addr);
1495 	dlci->state = DLCI_CLOSED;
1496 	if (dlci->addr != 0) {
1497 		tty_port_tty_hangup(&dlci->port, false);
1498 		spin_lock_irqsave(&dlci->lock, flags);
1499 		kfifo_reset(&dlci->fifo);
1500 		spin_unlock_irqrestore(&dlci->lock, flags);
1501 		/* Ensure that gsmtty_open() can return. */
1502 		tty_port_set_initialized(&dlci->port, 0);
1503 		wake_up_interruptible(&dlci->port.open_wait);
1504 	} else
1505 		dlci->gsm->dead = true;
1506 	wake_up(&dlci->gsm->event);
1507 	/* A DLCI 0 close is a MUX termination so we need to kick that
1508 	   back to userspace somehow */
1509 }
1510 
1511 /**
1512  *	gsm_dlci_open		-	a DLCI has opened
1513  *	@dlci: DLCI that opened
1514  *
1515  *	Perform processing when moving a DLCI into open state.
1516  */
1517 
1518 static void gsm_dlci_open(struct gsm_dlci *dlci)
1519 {
1520 	/* Note that SABM UA .. SABM UA first UA lost can mean that we go
1521 	   open -> open */
1522 	del_timer(&dlci->t1);
1523 	/* This will let a tty open continue */
1524 	dlci->state = DLCI_OPEN;
1525 	if (debug & 8)
1526 		pr_debug("DLCI %d goes open.\n", dlci->addr);
1527 	/* Send current modem state */
1528 	if (dlci->addr)
1529 		gsm_modem_update(dlci, 0);
1530 	wake_up(&dlci->gsm->event);
1531 }
1532 
1533 /**
1534  *	gsm_dlci_t1		-	T1 timer expiry
1535  *	@t: timer contained in the DLCI that opened
1536  *
1537  *	The T1 timer handles retransmits of control frames (essentially of
1538  *	SABM and DISC). We resend the command until the retry count runs out
1539  *	in which case an opening port goes back to closed and a closing port
1540  *	is simply put into closed state (any further frames from the other
1541  *	end will get a DM response)
1542  *
1543  *	Some control dlci can stay in ADM mode with other dlci working just
1544  *	fine. In that case we can just keep the control dlci open after the
1545  *	DLCI_OPENING retries time out.
1546  */
1547 
1548 static void gsm_dlci_t1(struct timer_list *t)
1549 {
1550 	struct gsm_dlci *dlci = from_timer(dlci, t, t1);
1551 	struct gsm_mux *gsm = dlci->gsm;
1552 
1553 	switch (dlci->state) {
1554 	case DLCI_OPENING:
1555 		dlci->retries--;
1556 		if (dlci->retries) {
1557 			gsm_command(dlci->gsm, dlci->addr, SABM|PF);
1558 			mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100);
1559 		} else if (!dlci->addr && gsm->control == (DM | PF)) {
1560 			if (debug & 8)
1561 				pr_info("DLCI %d opening in ADM mode.\n",
1562 					dlci->addr);
1563 			dlci->mode = DLCI_MODE_ADM;
1564 			gsm_dlci_open(dlci);
1565 		} else {
1566 			gsm_dlci_begin_close(dlci); /* prevent half open link */
1567 		}
1568 
1569 		break;
1570 	case DLCI_CLOSING:
1571 		dlci->retries--;
1572 		if (dlci->retries) {
1573 			gsm_command(dlci->gsm, dlci->addr, DISC|PF);
1574 			mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100);
1575 		} else
1576 			gsm_dlci_close(dlci);
1577 		break;
1578 	default:
1579 		pr_debug("%s: unhandled state: %d\n", __func__, dlci->state);
1580 		break;
1581 	}
1582 }
1583 
1584 /**
1585  *	gsm_dlci_begin_open	-	start channel open procedure
1586  *	@dlci: DLCI to open
1587  *
1588  *	Commence opening a DLCI from the Linux side. We issue SABM messages
1589  *	to the modem which should then reply with a UA or ADM, at which point
1590  *	we will move into open state. Opening is done asynchronously with retry
1591  *	running off timers and the responses.
1592  */
1593 
1594 static void gsm_dlci_begin_open(struct gsm_dlci *dlci)
1595 {
1596 	struct gsm_mux *gsm = dlci->gsm;
1597 	if (dlci->state == DLCI_OPEN || dlci->state == DLCI_OPENING)
1598 		return;
1599 	dlci->retries = gsm->n2;
1600 	dlci->state = DLCI_OPENING;
1601 	gsm_command(dlci->gsm, dlci->addr, SABM|PF);
1602 	mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100);
1603 }
1604 
1605 /**
1606  *	gsm_dlci_begin_close	-	start channel open procedure
1607  *	@dlci: DLCI to open
1608  *
1609  *	Commence closing a DLCI from the Linux side. We issue DISC messages
1610  *	to the modem which should then reply with a UA, at which point we
1611  *	will move into closed state. Closing is done asynchronously with retry
1612  *	off timers. We may also receive a DM reply from the other end which
1613  *	indicates the channel was already closed.
1614  */
1615 
1616 static void gsm_dlci_begin_close(struct gsm_dlci *dlci)
1617 {
1618 	struct gsm_mux *gsm = dlci->gsm;
1619 	if (dlci->state == DLCI_CLOSED || dlci->state == DLCI_CLOSING)
1620 		return;
1621 	dlci->retries = gsm->n2;
1622 	dlci->state = DLCI_CLOSING;
1623 	gsm_command(dlci->gsm, dlci->addr, DISC|PF);
1624 	mod_timer(&dlci->t1, jiffies + gsm->t1 * HZ / 100);
1625 }
1626 
1627 /**
1628  *	gsm_dlci_data		-	data arrived
1629  *	@dlci: channel
1630  *	@data: block of bytes received
1631  *	@clen: length of received block
1632  *
1633  *	A UI or UIH frame has arrived which contains data for a channel
1634  *	other than the control channel. If the relevant virtual tty is
1635  *	open we shovel the bits down it, if not we drop them.
1636  */
1637 
1638 static void gsm_dlci_data(struct gsm_dlci *dlci, const u8 *data, int clen)
1639 {
1640 	/* krefs .. */
1641 	struct tty_port *port = &dlci->port;
1642 	struct tty_struct *tty;
1643 	unsigned int modem = 0;
1644 	int len = clen;
1645 	int slen = 0;
1646 
1647 	if (debug & 16)
1648 		pr_debug("%d bytes for tty\n", len);
1649 	switch (dlci->adaption)  {
1650 	/* Unsupported types */
1651 	case 4:		/* Packetised interruptible data */
1652 		break;
1653 	case 3:		/* Packetised uininterruptible voice/data */
1654 		break;
1655 	case 2:		/* Asynchronous serial with line state in each frame */
1656 		while (gsm_read_ea(&modem, *data++) == 0) {
1657 			len--;
1658 			slen++;
1659 			if (len == 0)
1660 				return;
1661 		}
1662 		len--;
1663 		slen++;
1664 		tty = tty_port_tty_get(port);
1665 		if (tty) {
1666 			gsm_process_modem(tty, dlci, modem, slen);
1667 			tty_wakeup(tty);
1668 			tty_kref_put(tty);
1669 		}
1670 		fallthrough;
1671 	case 1:		/* Line state will go via DLCI 0 controls only */
1672 	default:
1673 		tty_insert_flip_string(port, data, len);
1674 		tty_flip_buffer_push(port);
1675 	}
1676 }
1677 
1678 /**
1679  *	gsm_dlci_command	-	data arrived on control channel
1680  *	@dlci: channel
1681  *	@data: block of bytes received
1682  *	@len: length of received block
1683  *
1684  *	A UI or UIH frame has arrived which contains data for DLCI 0 the
1685  *	control channel. This should contain a command EA followed by
1686  *	control data bytes. The command EA contains a command/response bit
1687  *	and we divide up the work accordingly.
1688  */
1689 
1690 static void gsm_dlci_command(struct gsm_dlci *dlci, const u8 *data, int len)
1691 {
1692 	/* See what command is involved */
1693 	unsigned int command = 0;
1694 	while (len-- > 0) {
1695 		if (gsm_read_ea(&command, *data++) == 1) {
1696 			int clen = *data++;
1697 			len--;
1698 			/* FIXME: this is properly an EA */
1699 			clen >>= 1;
1700 			/* Malformed command ? */
1701 			if (clen > len)
1702 				return;
1703 			if (command & 1)
1704 				gsm_control_message(dlci->gsm, command,
1705 								data, clen);
1706 			else
1707 				gsm_control_response(dlci->gsm, command,
1708 								data, clen);
1709 			return;
1710 		}
1711 	}
1712 }
1713 
1714 /*
1715  *	Allocate/Free DLCI channels
1716  */
1717 
1718 /**
1719  *	gsm_dlci_alloc		-	allocate a DLCI
1720  *	@gsm: GSM mux
1721  *	@addr: address of the DLCI
1722  *
1723  *	Allocate and install a new DLCI object into the GSM mux.
1724  *
1725  *	FIXME: review locking races
1726  */
1727 
1728 static struct gsm_dlci *gsm_dlci_alloc(struct gsm_mux *gsm, int addr)
1729 {
1730 	struct gsm_dlci *dlci = kzalloc(sizeof(struct gsm_dlci), GFP_ATOMIC);
1731 	if (dlci == NULL)
1732 		return NULL;
1733 	spin_lock_init(&dlci->lock);
1734 	mutex_init(&dlci->mutex);
1735 	if (kfifo_alloc(&dlci->fifo, TX_SIZE, GFP_KERNEL) < 0) {
1736 		kfree(dlci);
1737 		return NULL;
1738 	}
1739 
1740 	skb_queue_head_init(&dlci->skb_list);
1741 	timer_setup(&dlci->t1, gsm_dlci_t1, 0);
1742 	tty_port_init(&dlci->port);
1743 	dlci->port.ops = &gsm_port_ops;
1744 	dlci->gsm = gsm;
1745 	dlci->addr = addr;
1746 	dlci->adaption = gsm->adaption;
1747 	dlci->state = DLCI_CLOSED;
1748 	if (addr)
1749 		dlci->data = gsm_dlci_data;
1750 	else
1751 		dlci->data = gsm_dlci_command;
1752 	gsm->dlci[addr] = dlci;
1753 	return dlci;
1754 }
1755 
1756 /**
1757  *	gsm_dlci_free		-	free DLCI
1758  *	@port: tty port for DLCI to free
1759  *
1760  *	Free up a DLCI.
1761  *
1762  *	Can sleep.
1763  */
1764 static void gsm_dlci_free(struct tty_port *port)
1765 {
1766 	struct gsm_dlci *dlci = container_of(port, struct gsm_dlci, port);
1767 
1768 	del_timer_sync(&dlci->t1);
1769 	dlci->gsm->dlci[dlci->addr] = NULL;
1770 	kfifo_free(&dlci->fifo);
1771 	while ((dlci->skb = skb_dequeue(&dlci->skb_list)))
1772 		dev_kfree_skb(dlci->skb);
1773 	kfree(dlci);
1774 }
1775 
1776 static inline void dlci_get(struct gsm_dlci *dlci)
1777 {
1778 	tty_port_get(&dlci->port);
1779 }
1780 
1781 static inline void dlci_put(struct gsm_dlci *dlci)
1782 {
1783 	tty_port_put(&dlci->port);
1784 }
1785 
1786 static void gsm_destroy_network(struct gsm_dlci *dlci);
1787 
1788 /**
1789  *	gsm_dlci_release		-	release DLCI
1790  *	@dlci: DLCI to destroy
1791  *
1792  *	Release a DLCI. Actual free is deferred until either
1793  *	mux is closed or tty is closed - whichever is last.
1794  *
1795  *	Can sleep.
1796  */
1797 static void gsm_dlci_release(struct gsm_dlci *dlci)
1798 {
1799 	struct tty_struct *tty = tty_port_tty_get(&dlci->port);
1800 	if (tty) {
1801 		mutex_lock(&dlci->mutex);
1802 		gsm_destroy_network(dlci);
1803 		mutex_unlock(&dlci->mutex);
1804 
1805 		/* We cannot use tty_hangup() because in tty_kref_put() the tty
1806 		 * driver assumes that the hangup queue is free and reuses it to
1807 		 * queue release_one_tty() -> NULL pointer panic in
1808 		 * process_one_work().
1809 		 */
1810 		tty_vhangup(tty);
1811 
1812 		tty_port_tty_set(&dlci->port, NULL);
1813 		tty_kref_put(tty);
1814 	}
1815 	dlci->state = DLCI_CLOSED;
1816 	dlci_put(dlci);
1817 }
1818 
1819 /*
1820  *	LAPBish link layer logic
1821  */
1822 
1823 /**
1824  *	gsm_queue		-	a GSM frame is ready to process
1825  *	@gsm: pointer to our gsm mux
1826  *
1827  *	At this point in time a frame has arrived and been demangled from
1828  *	the line encoding. All the differences between the encodings have
1829  *	been handled below us and the frame is unpacked into the structures.
1830  *	The fcs holds the header FCS but any data FCS must be added here.
1831  */
1832 
1833 static void gsm_queue(struct gsm_mux *gsm)
1834 {
1835 	struct gsm_dlci *dlci;
1836 	u8 cr;
1837 	int address;
1838 
1839 	if (gsm->fcs != GOOD_FCS) {
1840 		gsm->bad_fcs++;
1841 		if (debug & 4)
1842 			pr_debug("BAD FCS %02x\n", gsm->fcs);
1843 		return;
1844 	}
1845 	address = gsm->address >> 1;
1846 	if (address >= NUM_DLCI)
1847 		goto invalid;
1848 
1849 	cr = gsm->address & 1;		/* C/R bit */
1850 	cr ^= gsm->initiator ? 0 : 1;	/* Flip so 1 always means command */
1851 
1852 	gsm_print_packet("<--", address, cr, gsm->control, gsm->buf, gsm->len);
1853 
1854 	dlci = gsm->dlci[address];
1855 
1856 	switch (gsm->control) {
1857 	case SABM|PF:
1858 		if (cr == 1)
1859 			goto invalid;
1860 		if (dlci == NULL)
1861 			dlci = gsm_dlci_alloc(gsm, address);
1862 		if (dlci == NULL)
1863 			return;
1864 		if (dlci->dead)
1865 			gsm_response(gsm, address, DM|PF);
1866 		else {
1867 			gsm_response(gsm, address, UA|PF);
1868 			gsm_dlci_open(dlci);
1869 		}
1870 		break;
1871 	case DISC|PF:
1872 		if (cr == 1)
1873 			goto invalid;
1874 		if (dlci == NULL || dlci->state == DLCI_CLOSED) {
1875 			gsm_response(gsm, address, DM|PF);
1876 			return;
1877 		}
1878 		/* Real close complete */
1879 		gsm_response(gsm, address, UA|PF);
1880 		gsm_dlci_close(dlci);
1881 		break;
1882 	case UA|PF:
1883 		if (cr == 0 || dlci == NULL)
1884 			break;
1885 		switch (dlci->state) {
1886 		case DLCI_CLOSING:
1887 			gsm_dlci_close(dlci);
1888 			break;
1889 		case DLCI_OPENING:
1890 			gsm_dlci_open(dlci);
1891 			break;
1892 		default:
1893 			pr_debug("%s: unhandled state: %d\n", __func__,
1894 					dlci->state);
1895 			break;
1896 		}
1897 		break;
1898 	case DM:	/* DM can be valid unsolicited */
1899 	case DM|PF:
1900 		if (cr)
1901 			goto invalid;
1902 		if (dlci == NULL)
1903 			return;
1904 		gsm_dlci_close(dlci);
1905 		break;
1906 	case UI:
1907 	case UI|PF:
1908 	case UIH:
1909 	case UIH|PF:
1910 #if 0
1911 		if (cr)
1912 			goto invalid;
1913 #endif
1914 		if (dlci == NULL || dlci->state != DLCI_OPEN) {
1915 			gsm_command(gsm, address, DM|PF);
1916 			return;
1917 		}
1918 		dlci->data(dlci, gsm->buf, gsm->len);
1919 		break;
1920 	default:
1921 		goto invalid;
1922 	}
1923 	return;
1924 invalid:
1925 	gsm->malformed++;
1926 	return;
1927 }
1928 
1929 
1930 /**
1931  *	gsm0_receive	-	perform processing for non-transparency
1932  *	@gsm: gsm data for this ldisc instance
1933  *	@c: character
1934  *
1935  *	Receive bytes in gsm mode 0
1936  */
1937 
1938 static void gsm0_receive(struct gsm_mux *gsm, unsigned char c)
1939 {
1940 	unsigned int len;
1941 
1942 	switch (gsm->state) {
1943 	case GSM_SEARCH:	/* SOF marker */
1944 		if (c == GSM0_SOF) {
1945 			gsm->state = GSM_ADDRESS;
1946 			gsm->address = 0;
1947 			gsm->len = 0;
1948 			gsm->fcs = INIT_FCS;
1949 		}
1950 		break;
1951 	case GSM_ADDRESS:	/* Address EA */
1952 		gsm->fcs = gsm_fcs_add(gsm->fcs, c);
1953 		if (gsm_read_ea(&gsm->address, c))
1954 			gsm->state = GSM_CONTROL;
1955 		break;
1956 	case GSM_CONTROL:	/* Control Byte */
1957 		gsm->fcs = gsm_fcs_add(gsm->fcs, c);
1958 		gsm->control = c;
1959 		gsm->state = GSM_LEN0;
1960 		break;
1961 	case GSM_LEN0:		/* Length EA */
1962 		gsm->fcs = gsm_fcs_add(gsm->fcs, c);
1963 		if (gsm_read_ea(&gsm->len, c)) {
1964 			if (gsm->len > gsm->mru) {
1965 				gsm->bad_size++;
1966 				gsm->state = GSM_SEARCH;
1967 				break;
1968 			}
1969 			gsm->count = 0;
1970 			if (!gsm->len)
1971 				gsm->state = GSM_FCS;
1972 			else
1973 				gsm->state = GSM_DATA;
1974 			break;
1975 		}
1976 		gsm->state = GSM_LEN1;
1977 		break;
1978 	case GSM_LEN1:
1979 		gsm->fcs = gsm_fcs_add(gsm->fcs, c);
1980 		len = c;
1981 		gsm->len |= len << 7;
1982 		if (gsm->len > gsm->mru) {
1983 			gsm->bad_size++;
1984 			gsm->state = GSM_SEARCH;
1985 			break;
1986 		}
1987 		gsm->count = 0;
1988 		if (!gsm->len)
1989 			gsm->state = GSM_FCS;
1990 		else
1991 			gsm->state = GSM_DATA;
1992 		break;
1993 	case GSM_DATA:		/* Data */
1994 		gsm->buf[gsm->count++] = c;
1995 		if (gsm->count == gsm->len) {
1996 			/* Calculate final FCS for UI frames over all data */
1997 			if ((gsm->control & ~PF) != UIH) {
1998 				gsm->fcs = gsm_fcs_add_block(gsm->fcs, gsm->buf,
1999 							     gsm->count);
2000 			}
2001 			gsm->state = GSM_FCS;
2002 		}
2003 		break;
2004 	case GSM_FCS:		/* FCS follows the packet */
2005 		gsm->fcs = gsm_fcs_add(gsm->fcs, c);
2006 		gsm->state = GSM_SSOF;
2007 		break;
2008 	case GSM_SSOF:
2009 		gsm->state = GSM_SEARCH;
2010 		if (c == GSM0_SOF)
2011 			gsm_queue(gsm);
2012 		else
2013 			gsm->bad_size++;
2014 		break;
2015 	default:
2016 		pr_debug("%s: unhandled state: %d\n", __func__, gsm->state);
2017 		break;
2018 	}
2019 }
2020 
2021 /**
2022  *	gsm1_receive	-	perform processing for non-transparency
2023  *	@gsm: gsm data for this ldisc instance
2024  *	@c: character
2025  *
2026  *	Receive bytes in mode 1 (Advanced option)
2027  */
2028 
2029 static void gsm1_receive(struct gsm_mux *gsm, unsigned char c)
2030 {
2031 	/* handle XON/XOFF */
2032 	if ((c & ISO_IEC_646_MASK) == XON) {
2033 		gsm->constipated = true;
2034 		return;
2035 	} else if ((c & ISO_IEC_646_MASK) == XOFF) {
2036 		gsm->constipated = false;
2037 		/* Kick the link in case it is idling */
2038 		gsm_data_kick(gsm, NULL);
2039 		return;
2040 	}
2041 	if (c == GSM1_SOF) {
2042 		/* EOF is only valid in frame if we have got to the data state */
2043 		if (gsm->state == GSM_DATA) {
2044 			if (gsm->count < 1) {
2045 				/* Missing FSC */
2046 				gsm->malformed++;
2047 				gsm->state = GSM_START;
2048 				return;
2049 			}
2050 			/* Remove the FCS from data */
2051 			gsm->count--;
2052 			if ((gsm->control & ~PF) != UIH) {
2053 				/* Calculate final FCS for UI frames over all
2054 				 * data but FCS
2055 				 */
2056 				gsm->fcs = gsm_fcs_add_block(gsm->fcs, gsm->buf,
2057 							     gsm->count);
2058 			}
2059 			/* Add the FCS itself to test against GOOD_FCS */
2060 			gsm->fcs = gsm_fcs_add(gsm->fcs, gsm->buf[gsm->count]);
2061 			gsm->len = gsm->count;
2062 			gsm_queue(gsm);
2063 			gsm->state  = GSM_START;
2064 			return;
2065 		}
2066 		/* Any partial frame was a runt so go back to start */
2067 		if (gsm->state != GSM_START) {
2068 			if (gsm->state != GSM_SEARCH)
2069 				gsm->malformed++;
2070 			gsm->state = GSM_START;
2071 		}
2072 		/* A SOF in GSM_START means we are still reading idling or
2073 		   framing bytes */
2074 		return;
2075 	}
2076 
2077 	if (c == GSM1_ESCAPE) {
2078 		gsm->escape = true;
2079 		return;
2080 	}
2081 
2082 	/* Only an unescaped SOF gets us out of GSM search */
2083 	if (gsm->state == GSM_SEARCH)
2084 		return;
2085 
2086 	if (gsm->escape) {
2087 		c ^= GSM1_ESCAPE_BITS;
2088 		gsm->escape = false;
2089 	}
2090 	switch (gsm->state) {
2091 	case GSM_START:		/* First byte after SOF */
2092 		gsm->address = 0;
2093 		gsm->state = GSM_ADDRESS;
2094 		gsm->fcs = INIT_FCS;
2095 		fallthrough;
2096 	case GSM_ADDRESS:	/* Address continuation */
2097 		gsm->fcs = gsm_fcs_add(gsm->fcs, c);
2098 		if (gsm_read_ea(&gsm->address, c))
2099 			gsm->state = GSM_CONTROL;
2100 		break;
2101 	case GSM_CONTROL:	/* Control Byte */
2102 		gsm->fcs = gsm_fcs_add(gsm->fcs, c);
2103 		gsm->control = c;
2104 		gsm->count = 0;
2105 		gsm->state = GSM_DATA;
2106 		break;
2107 	case GSM_DATA:		/* Data */
2108 		if (gsm->count > gsm->mru) {	/* Allow one for the FCS */
2109 			gsm->state = GSM_OVERRUN;
2110 			gsm->bad_size++;
2111 		} else
2112 			gsm->buf[gsm->count++] = c;
2113 		break;
2114 	case GSM_OVERRUN:	/* Over-long - eg a dropped SOF */
2115 		break;
2116 	default:
2117 		pr_debug("%s: unhandled state: %d\n", __func__, gsm->state);
2118 		break;
2119 	}
2120 }
2121 
2122 /**
2123  *	gsm_error		-	handle tty error
2124  *	@gsm: ldisc data
2125  *
2126  *	Handle an error in the receipt of data for a frame. Currently we just
2127  *	go back to hunting for a SOF.
2128  *
2129  *	FIXME: better diagnostics ?
2130  */
2131 
2132 static void gsm_error(struct gsm_mux *gsm)
2133 {
2134 	gsm->state = GSM_SEARCH;
2135 	gsm->io_error++;
2136 }
2137 
2138 /**
2139  *	gsm_cleanup_mux		-	generic GSM protocol cleanup
2140  *	@gsm: our mux
2141  *	@disc: disconnect link?
2142  *
2143  *	Clean up the bits of the mux which are the same for all framing
2144  *	protocols. Remove the mux from the mux table, stop all the timers
2145  *	and then shut down each device hanging up the channels as we go.
2146  */
2147 
2148 static void gsm_cleanup_mux(struct gsm_mux *gsm, bool disc)
2149 {
2150 	int i;
2151 	struct gsm_dlci *dlci = gsm->dlci[0];
2152 	struct gsm_msg *txq, *ntxq;
2153 
2154 	gsm->dead = true;
2155 	mutex_lock(&gsm->mutex);
2156 
2157 	if (dlci) {
2158 		if (disc && dlci->state != DLCI_CLOSED) {
2159 			gsm_dlci_begin_close(dlci);
2160 			wait_event(gsm->event, dlci->state == DLCI_CLOSED);
2161 		}
2162 		dlci->dead = true;
2163 	}
2164 
2165 	/* Finish outstanding timers, making sure they are done */
2166 	del_timer_sync(&gsm->t2_timer);
2167 
2168 	/* Free up any link layer users and finally the control channel */
2169 	for (i = NUM_DLCI - 1; i >= 0; i--)
2170 		if (gsm->dlci[i])
2171 			gsm_dlci_release(gsm->dlci[i]);
2172 	mutex_unlock(&gsm->mutex);
2173 	/* Now wipe the queues */
2174 	tty_ldisc_flush(gsm->tty);
2175 	list_for_each_entry_safe(txq, ntxq, &gsm->tx_list, list)
2176 		kfree(txq);
2177 	INIT_LIST_HEAD(&gsm->tx_list);
2178 }
2179 
2180 /**
2181  *	gsm_activate_mux	-	generic GSM setup
2182  *	@gsm: our mux
2183  *
2184  *	Set up the bits of the mux which are the same for all framing
2185  *	protocols. Add the mux to the mux table so it can be opened and
2186  *	finally kick off connecting to DLCI 0 on the modem.
2187  */
2188 
2189 static int gsm_activate_mux(struct gsm_mux *gsm)
2190 {
2191 	struct gsm_dlci *dlci;
2192 
2193 	timer_setup(&gsm->t2_timer, gsm_control_retransmit, 0);
2194 	init_waitqueue_head(&gsm->event);
2195 	spin_lock_init(&gsm->control_lock);
2196 	spin_lock_init(&gsm->tx_lock);
2197 
2198 	if (gsm->encoding == 0)
2199 		gsm->receive = gsm0_receive;
2200 	else
2201 		gsm->receive = gsm1_receive;
2202 
2203 	dlci = gsm_dlci_alloc(gsm, 0);
2204 	if (dlci == NULL)
2205 		return -ENOMEM;
2206 	gsm->dead = false;		/* Tty opens are now permissible */
2207 	return 0;
2208 }
2209 
2210 /**
2211  *	gsm_free_mux		-	free up a mux
2212  *	@gsm: mux to free
2213  *
2214  *	Dispose of allocated resources for a dead mux
2215  */
2216 static void gsm_free_mux(struct gsm_mux *gsm)
2217 {
2218 	int i;
2219 
2220 	for (i = 0; i < MAX_MUX; i++) {
2221 		if (gsm == gsm_mux[i]) {
2222 			gsm_mux[i] = NULL;
2223 			break;
2224 		}
2225 	}
2226 	mutex_destroy(&gsm->mutex);
2227 	kfree(gsm->txframe);
2228 	kfree(gsm->buf);
2229 	kfree(gsm);
2230 }
2231 
2232 /**
2233  *	gsm_free_muxr		-	free up a mux
2234  *	@ref: kreference to the mux to free
2235  *
2236  *	Dispose of allocated resources for a dead mux
2237  */
2238 static void gsm_free_muxr(struct kref *ref)
2239 {
2240 	struct gsm_mux *gsm = container_of(ref, struct gsm_mux, ref);
2241 	gsm_free_mux(gsm);
2242 }
2243 
2244 static inline void mux_get(struct gsm_mux *gsm)
2245 {
2246 	unsigned long flags;
2247 
2248 	spin_lock_irqsave(&gsm_mux_lock, flags);
2249 	kref_get(&gsm->ref);
2250 	spin_unlock_irqrestore(&gsm_mux_lock, flags);
2251 }
2252 
2253 static inline void mux_put(struct gsm_mux *gsm)
2254 {
2255 	unsigned long flags;
2256 
2257 	spin_lock_irqsave(&gsm_mux_lock, flags);
2258 	kref_put(&gsm->ref, gsm_free_muxr);
2259 	spin_unlock_irqrestore(&gsm_mux_lock, flags);
2260 }
2261 
2262 static inline unsigned int mux_num_to_base(struct gsm_mux *gsm)
2263 {
2264 	return gsm->num * NUM_DLCI;
2265 }
2266 
2267 static inline unsigned int mux_line_to_num(unsigned int line)
2268 {
2269 	return line / NUM_DLCI;
2270 }
2271 
2272 /**
2273  *	gsm_alloc_mux		-	allocate a mux
2274  *
2275  *	Creates a new mux ready for activation.
2276  */
2277 
2278 static struct gsm_mux *gsm_alloc_mux(void)
2279 {
2280 	int i;
2281 	struct gsm_mux *gsm = kzalloc(sizeof(struct gsm_mux), GFP_KERNEL);
2282 	if (gsm == NULL)
2283 		return NULL;
2284 	gsm->buf = kmalloc(MAX_MRU + 1, GFP_KERNEL);
2285 	if (gsm->buf == NULL) {
2286 		kfree(gsm);
2287 		return NULL;
2288 	}
2289 	gsm->txframe = kmalloc(2 * (MAX_MTU + PROT_OVERHEAD - 1), GFP_KERNEL);
2290 	if (gsm->txframe == NULL) {
2291 		kfree(gsm->buf);
2292 		kfree(gsm);
2293 		return NULL;
2294 	}
2295 	spin_lock_init(&gsm->lock);
2296 	mutex_init(&gsm->mutex);
2297 	kref_init(&gsm->ref);
2298 	INIT_LIST_HEAD(&gsm->tx_list);
2299 
2300 	gsm->t1 = T1;
2301 	gsm->t2 = T2;
2302 	gsm->n2 = N2;
2303 	gsm->ftype = UIH;
2304 	gsm->adaption = 1;
2305 	gsm->encoding = 1;
2306 	gsm->mru = 64;	/* Default to encoding 1 so these should be 64 */
2307 	gsm->mtu = 64;
2308 	gsm->dead = true;	/* Avoid early tty opens */
2309 
2310 	/* Store the instance to the mux array or abort if no space is
2311 	 * available.
2312 	 */
2313 	spin_lock(&gsm_mux_lock);
2314 	for (i = 0; i < MAX_MUX; i++) {
2315 		if (!gsm_mux[i]) {
2316 			gsm_mux[i] = gsm;
2317 			gsm->num = i;
2318 			break;
2319 		}
2320 	}
2321 	spin_unlock(&gsm_mux_lock);
2322 	if (i == MAX_MUX) {
2323 		mutex_destroy(&gsm->mutex);
2324 		kfree(gsm->txframe);
2325 		kfree(gsm->buf);
2326 		kfree(gsm);
2327 		return NULL;
2328 	}
2329 
2330 	return gsm;
2331 }
2332 
2333 static void gsm_copy_config_values(struct gsm_mux *gsm,
2334 				   struct gsm_config *c)
2335 {
2336 	memset(c, 0, sizeof(*c));
2337 	c->adaption = gsm->adaption;
2338 	c->encapsulation = gsm->encoding;
2339 	c->initiator = gsm->initiator;
2340 	c->t1 = gsm->t1;
2341 	c->t2 = gsm->t2;
2342 	c->t3 = 0;	/* Not supported */
2343 	c->n2 = gsm->n2;
2344 	if (gsm->ftype == UIH)
2345 		c->i = 1;
2346 	else
2347 		c->i = 2;
2348 	pr_debug("Ftype %d i %d\n", gsm->ftype, c->i);
2349 	c->mru = gsm->mru;
2350 	c->mtu = gsm->mtu;
2351 	c->k = 0;
2352 }
2353 
2354 static int gsm_config(struct gsm_mux *gsm, struct gsm_config *c)
2355 {
2356 	int ret = 0;
2357 	int need_close = 0;
2358 	int need_restart = 0;
2359 
2360 	/* Stuff we don't support yet - UI or I frame transport, windowing */
2361 	if ((c->adaption != 1 && c->adaption != 2) || c->k)
2362 		return -EOPNOTSUPP;
2363 	/* Check the MRU/MTU range looks sane */
2364 	if (c->mru > MAX_MRU || c->mtu > MAX_MTU || c->mru < 8 || c->mtu < 8)
2365 		return -EINVAL;
2366 	if (c->n2 > 255)
2367 		return -EINVAL;
2368 	if (c->encapsulation > 1)	/* Basic, advanced, no I */
2369 		return -EINVAL;
2370 	if (c->initiator > 1)
2371 		return -EINVAL;
2372 	if (c->i == 0 || c->i > 2)	/* UIH and UI only */
2373 		return -EINVAL;
2374 	/*
2375 	 * See what is needed for reconfiguration
2376 	 */
2377 
2378 	/* Timing fields */
2379 	if (c->t1 != 0 && c->t1 != gsm->t1)
2380 		need_restart = 1;
2381 	if (c->t2 != 0 && c->t2 != gsm->t2)
2382 		need_restart = 1;
2383 	if (c->encapsulation != gsm->encoding)
2384 		need_restart = 1;
2385 	if (c->adaption != gsm->adaption)
2386 		need_restart = 1;
2387 	/* Requires care */
2388 	if (c->initiator != gsm->initiator)
2389 		need_close = 1;
2390 	if (c->mru != gsm->mru)
2391 		need_restart = 1;
2392 	if (c->mtu != gsm->mtu)
2393 		need_restart = 1;
2394 
2395 	/*
2396 	 * Close down what is needed, restart and initiate the new
2397 	 * configuration. On the first time there is no DLCI[0]
2398 	 * and closing or cleaning up is not necessary.
2399 	 */
2400 	if (need_close || need_restart)
2401 		gsm_cleanup_mux(gsm, true);
2402 
2403 	gsm->initiator = c->initiator;
2404 	gsm->mru = c->mru;
2405 	gsm->mtu = c->mtu;
2406 	gsm->encoding = c->encapsulation;
2407 	gsm->adaption = c->adaption;
2408 	gsm->n2 = c->n2;
2409 
2410 	if (c->i == 1)
2411 		gsm->ftype = UIH;
2412 	else if (c->i == 2)
2413 		gsm->ftype = UI;
2414 
2415 	if (c->t1)
2416 		gsm->t1 = c->t1;
2417 	if (c->t2)
2418 		gsm->t2 = c->t2;
2419 
2420 	/*
2421 	 * FIXME: We need to separate activation/deactivation from adding
2422 	 * and removing from the mux array
2423 	 */
2424 	if (gsm->dead) {
2425 		ret = gsm_activate_mux(gsm);
2426 		if (ret)
2427 			return ret;
2428 		if (gsm->initiator)
2429 			gsm_dlci_begin_open(gsm->dlci[0]);
2430 	}
2431 	return 0;
2432 }
2433 
2434 /**
2435  *	gsmld_output		-	write to link
2436  *	@gsm: our mux
2437  *	@data: bytes to output
2438  *	@len: size
2439  *
2440  *	Write a block of data from the GSM mux to the data channel. This
2441  *	will eventually be serialized from above but at the moment isn't.
2442  */
2443 
2444 static int gsmld_output(struct gsm_mux *gsm, u8 *data, int len)
2445 {
2446 	if (tty_write_room(gsm->tty) < len) {
2447 		set_bit(TTY_DO_WRITE_WAKEUP, &gsm->tty->flags);
2448 		return -ENOSPC;
2449 	}
2450 	if (debug & 4)
2451 		print_hex_dump_bytes("gsmld_output: ", DUMP_PREFIX_OFFSET,
2452 				     data, len);
2453 	return gsm->tty->ops->write(gsm->tty, data, len);
2454 }
2455 
2456 /**
2457  *	gsmld_attach_gsm	-	mode set up
2458  *	@tty: our tty structure
2459  *	@gsm: our mux
2460  *
2461  *	Set up the MUX for basic mode and commence connecting to the
2462  *	modem. Currently called from the line discipline set up but
2463  *	will need moving to an ioctl path.
2464  */
2465 
2466 static int gsmld_attach_gsm(struct tty_struct *tty, struct gsm_mux *gsm)
2467 {
2468 	unsigned int base;
2469 	int ret, i;
2470 
2471 	gsm->tty = tty_kref_get(tty);
2472 	/* Turn off tty XON/XOFF handling to handle it explicitly. */
2473 	gsm->old_c_iflag = tty->termios.c_iflag;
2474 	tty->termios.c_iflag &= (IXON | IXOFF);
2475 	ret =  gsm_activate_mux(gsm);
2476 	if (ret != 0)
2477 		tty_kref_put(gsm->tty);
2478 	else {
2479 		/* Don't register device 0 - this is the control channel and not
2480 		   a usable tty interface */
2481 		base = mux_num_to_base(gsm); /* Base for this MUX */
2482 		for (i = 1; i < NUM_DLCI; i++) {
2483 			struct device *dev;
2484 
2485 			dev = tty_register_device(gsm_tty_driver,
2486 							base + i, NULL);
2487 			if (IS_ERR(dev)) {
2488 				for (i--; i >= 1; i--)
2489 					tty_unregister_device(gsm_tty_driver,
2490 								base + i);
2491 				return PTR_ERR(dev);
2492 			}
2493 		}
2494 	}
2495 	return ret;
2496 }
2497 
2498 
2499 /**
2500  *	gsmld_detach_gsm	-	stop doing 0710 mux
2501  *	@tty: tty attached to the mux
2502  *	@gsm: mux
2503  *
2504  *	Shutdown and then clean up the resources used by the line discipline
2505  */
2506 
2507 static void gsmld_detach_gsm(struct tty_struct *tty, struct gsm_mux *gsm)
2508 {
2509 	unsigned int base = mux_num_to_base(gsm); /* Base for this MUX */
2510 	int i;
2511 
2512 	WARN_ON(tty != gsm->tty);
2513 	for (i = 1; i < NUM_DLCI; i++)
2514 		tty_unregister_device(gsm_tty_driver, base + i);
2515 	/* Restore tty XON/XOFF handling. */
2516 	gsm->tty->termios.c_iflag = gsm->old_c_iflag;
2517 	tty_kref_put(gsm->tty);
2518 	gsm->tty = NULL;
2519 }
2520 
2521 static void gsmld_receive_buf(struct tty_struct *tty, const unsigned char *cp,
2522 			      const char *fp, int count)
2523 {
2524 	struct gsm_mux *gsm = tty->disc_data;
2525 	char flags = TTY_NORMAL;
2526 
2527 	if (debug & 4)
2528 		print_hex_dump_bytes("gsmld_receive: ", DUMP_PREFIX_OFFSET,
2529 				     cp, count);
2530 
2531 	for (; count; count--, cp++) {
2532 		if (fp)
2533 			flags = *fp++;
2534 		switch (flags) {
2535 		case TTY_NORMAL:
2536 			gsm->receive(gsm, *cp);
2537 			break;
2538 		case TTY_OVERRUN:
2539 		case TTY_BREAK:
2540 		case TTY_PARITY:
2541 		case TTY_FRAME:
2542 			gsm_error(gsm);
2543 			break;
2544 		default:
2545 			WARN_ONCE(1, "%s: unknown flag %d\n",
2546 			       tty_name(tty), flags);
2547 			break;
2548 		}
2549 	}
2550 	/* FASYNC if needed ? */
2551 	/* If clogged call tty_throttle(tty); */
2552 }
2553 
2554 /**
2555  *	gsmld_flush_buffer	-	clean input queue
2556  *	@tty:	terminal device
2557  *
2558  *	Flush the input buffer. Called when the line discipline is
2559  *	being closed, when the tty layer wants the buffer flushed (eg
2560  *	at hangup).
2561  */
2562 
2563 static void gsmld_flush_buffer(struct tty_struct *tty)
2564 {
2565 }
2566 
2567 /**
2568  *	gsmld_close		-	close the ldisc for this tty
2569  *	@tty: device
2570  *
2571  *	Called from the terminal layer when this line discipline is
2572  *	being shut down, either because of a close or becsuse of a
2573  *	discipline change. The function will not be called while other
2574  *	ldisc methods are in progress.
2575  */
2576 
2577 static void gsmld_close(struct tty_struct *tty)
2578 {
2579 	struct gsm_mux *gsm = tty->disc_data;
2580 
2581 	/* The ldisc locks and closes the port before calling our close. This
2582 	 * means we have no way to do a proper disconnect. We will not bother
2583 	 * to do one.
2584 	 */
2585 	gsm_cleanup_mux(gsm, false);
2586 
2587 	gsmld_detach_gsm(tty, gsm);
2588 
2589 	gsmld_flush_buffer(tty);
2590 	/* Do other clean up here */
2591 	mux_put(gsm);
2592 }
2593 
2594 /**
2595  *	gsmld_open		-	open an ldisc
2596  *	@tty: terminal to open
2597  *
2598  *	Called when this line discipline is being attached to the
2599  *	terminal device. Can sleep. Called serialized so that no
2600  *	other events will occur in parallel. No further open will occur
2601  *	until a close.
2602  */
2603 
2604 static int gsmld_open(struct tty_struct *tty)
2605 {
2606 	struct gsm_mux *gsm;
2607 	int ret;
2608 
2609 	if (tty->ops->write == NULL)
2610 		return -EINVAL;
2611 
2612 	/* Attach our ldisc data */
2613 	gsm = gsm_alloc_mux();
2614 	if (gsm == NULL)
2615 		return -ENOMEM;
2616 
2617 	tty->disc_data = gsm;
2618 	tty->receive_room = 65536;
2619 
2620 	/* Attach the initial passive connection */
2621 	gsm->encoding = 1;
2622 
2623 	ret = gsmld_attach_gsm(tty, gsm);
2624 	if (ret != 0) {
2625 		gsm_cleanup_mux(gsm, false);
2626 		mux_put(gsm);
2627 	}
2628 	return ret;
2629 }
2630 
2631 /**
2632  *	gsmld_write_wakeup	-	asynchronous I/O notifier
2633  *	@tty: tty device
2634  *
2635  *	Required for the ptys, serial driver etc. since processes
2636  *	that attach themselves to the master and rely on ASYNC
2637  *	IO must be woken up
2638  */
2639 
2640 static void gsmld_write_wakeup(struct tty_struct *tty)
2641 {
2642 	struct gsm_mux *gsm = tty->disc_data;
2643 	unsigned long flags;
2644 
2645 	/* Queue poll */
2646 	clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
2647 	spin_lock_irqsave(&gsm->tx_lock, flags);
2648 	gsm_data_kick(gsm, NULL);
2649 	if (gsm->tx_bytes < TX_THRESH_LO) {
2650 		gsm_dlci_data_sweep(gsm);
2651 	}
2652 	spin_unlock_irqrestore(&gsm->tx_lock, flags);
2653 }
2654 
2655 /**
2656  *	gsmld_read		-	read function for tty
2657  *	@tty: tty device
2658  *	@file: file object
2659  *	@buf: userspace buffer pointer
2660  *	@nr: size of I/O
2661  *	@cookie: unused
2662  *	@offset: unused
2663  *
2664  *	Perform reads for the line discipline. We are guaranteed that the
2665  *	line discipline will not be closed under us but we may get multiple
2666  *	parallel readers and must handle this ourselves. We may also get
2667  *	a hangup. Always called in user context, may sleep.
2668  *
2669  *	This code must be sure never to sleep through a hangup.
2670  */
2671 
2672 static ssize_t gsmld_read(struct tty_struct *tty, struct file *file,
2673 			  unsigned char *buf, size_t nr,
2674 			  void **cookie, unsigned long offset)
2675 {
2676 	return -EOPNOTSUPP;
2677 }
2678 
2679 /**
2680  *	gsmld_write		-	write function for tty
2681  *	@tty: tty device
2682  *	@file: file object
2683  *	@buf: userspace buffer pointer
2684  *	@nr: size of I/O
2685  *
2686  *	Called when the owner of the device wants to send a frame
2687  *	itself (or some other control data). The data is transferred
2688  *	as-is and must be properly framed and checksummed as appropriate
2689  *	by userspace. Frames are either sent whole or not at all as this
2690  *	avoids pain user side.
2691  */
2692 
2693 static ssize_t gsmld_write(struct tty_struct *tty, struct file *file,
2694 			   const unsigned char *buf, size_t nr)
2695 {
2696 	int space = tty_write_room(tty);
2697 	if (space >= nr)
2698 		return tty->ops->write(tty, buf, nr);
2699 	set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
2700 	return -ENOBUFS;
2701 }
2702 
2703 /**
2704  *	gsmld_poll		-	poll method for N_GSM0710
2705  *	@tty: terminal device
2706  *	@file: file accessing it
2707  *	@wait: poll table
2708  *
2709  *	Called when the line discipline is asked to poll() for data or
2710  *	for special events. This code is not serialized with respect to
2711  *	other events save open/close.
2712  *
2713  *	This code must be sure never to sleep through a hangup.
2714  *	Called without the kernel lock held - fine
2715  */
2716 
2717 static __poll_t gsmld_poll(struct tty_struct *tty, struct file *file,
2718 							poll_table *wait)
2719 {
2720 	__poll_t mask = 0;
2721 	struct gsm_mux *gsm = tty->disc_data;
2722 
2723 	poll_wait(file, &tty->read_wait, wait);
2724 	poll_wait(file, &tty->write_wait, wait);
2725 	if (tty_hung_up_p(file))
2726 		mask |= EPOLLHUP;
2727 	if (!tty_is_writelocked(tty) && tty_write_room(tty) > 0)
2728 		mask |= EPOLLOUT | EPOLLWRNORM;
2729 	if (gsm->dead)
2730 		mask |= EPOLLHUP;
2731 	return mask;
2732 }
2733 
2734 static int gsmld_ioctl(struct tty_struct *tty, unsigned int cmd,
2735 		       unsigned long arg)
2736 {
2737 	struct gsm_config c;
2738 	struct gsm_mux *gsm = tty->disc_data;
2739 	unsigned int base;
2740 
2741 	switch (cmd) {
2742 	case GSMIOC_GETCONF:
2743 		gsm_copy_config_values(gsm, &c);
2744 		if (copy_to_user((void __user *)arg, &c, sizeof(c)))
2745 			return -EFAULT;
2746 		return 0;
2747 	case GSMIOC_SETCONF:
2748 		if (copy_from_user(&c, (void __user *)arg, sizeof(c)))
2749 			return -EFAULT;
2750 		return gsm_config(gsm, &c);
2751 	case GSMIOC_GETFIRST:
2752 		base = mux_num_to_base(gsm);
2753 		return put_user(base + 1, (__u32 __user *)arg);
2754 	default:
2755 		return n_tty_ioctl_helper(tty, cmd, arg);
2756 	}
2757 }
2758 
2759 /*
2760  *	Network interface
2761  *
2762  */
2763 
2764 static int gsm_mux_net_open(struct net_device *net)
2765 {
2766 	pr_debug("%s called\n", __func__);
2767 	netif_start_queue(net);
2768 	return 0;
2769 }
2770 
2771 static int gsm_mux_net_close(struct net_device *net)
2772 {
2773 	netif_stop_queue(net);
2774 	return 0;
2775 }
2776 
2777 static void dlci_net_free(struct gsm_dlci *dlci)
2778 {
2779 	if (!dlci->net) {
2780 		WARN_ON(1);
2781 		return;
2782 	}
2783 	dlci->adaption = dlci->prev_adaption;
2784 	dlci->data = dlci->prev_data;
2785 	free_netdev(dlci->net);
2786 	dlci->net = NULL;
2787 }
2788 static void net_free(struct kref *ref)
2789 {
2790 	struct gsm_mux_net *mux_net;
2791 	struct gsm_dlci *dlci;
2792 
2793 	mux_net = container_of(ref, struct gsm_mux_net, ref);
2794 	dlci = mux_net->dlci;
2795 
2796 	if (dlci->net) {
2797 		unregister_netdev(dlci->net);
2798 		dlci_net_free(dlci);
2799 	}
2800 }
2801 
2802 static inline void muxnet_get(struct gsm_mux_net *mux_net)
2803 {
2804 	kref_get(&mux_net->ref);
2805 }
2806 
2807 static inline void muxnet_put(struct gsm_mux_net *mux_net)
2808 {
2809 	kref_put(&mux_net->ref, net_free);
2810 }
2811 
2812 static netdev_tx_t gsm_mux_net_start_xmit(struct sk_buff *skb,
2813 				      struct net_device *net)
2814 {
2815 	struct gsm_mux_net *mux_net = netdev_priv(net);
2816 	struct gsm_dlci *dlci = mux_net->dlci;
2817 	muxnet_get(mux_net);
2818 
2819 	skb_queue_head(&dlci->skb_list, skb);
2820 	net->stats.tx_packets++;
2821 	net->stats.tx_bytes += skb->len;
2822 	gsm_dlci_data_kick(dlci);
2823 	/* And tell the kernel when the last transmit started. */
2824 	netif_trans_update(net);
2825 	muxnet_put(mux_net);
2826 	return NETDEV_TX_OK;
2827 }
2828 
2829 /* called when a packet did not ack after watchdogtimeout */
2830 static void gsm_mux_net_tx_timeout(struct net_device *net, unsigned int txqueue)
2831 {
2832 	/* Tell syslog we are hosed. */
2833 	dev_dbg(&net->dev, "Tx timed out.\n");
2834 
2835 	/* Update statistics */
2836 	net->stats.tx_errors++;
2837 }
2838 
2839 static void gsm_mux_rx_netchar(struct gsm_dlci *dlci,
2840 				const unsigned char *in_buf, int size)
2841 {
2842 	struct net_device *net = dlci->net;
2843 	struct sk_buff *skb;
2844 	struct gsm_mux_net *mux_net = netdev_priv(net);
2845 	muxnet_get(mux_net);
2846 
2847 	/* Allocate an sk_buff */
2848 	skb = dev_alloc_skb(size + NET_IP_ALIGN);
2849 	if (!skb) {
2850 		/* We got no receive buffer. */
2851 		net->stats.rx_dropped++;
2852 		muxnet_put(mux_net);
2853 		return;
2854 	}
2855 	skb_reserve(skb, NET_IP_ALIGN);
2856 	skb_put_data(skb, in_buf, size);
2857 
2858 	skb->dev = net;
2859 	skb->protocol = htons(ETH_P_IP);
2860 
2861 	/* Ship it off to the kernel */
2862 	netif_rx(skb);
2863 
2864 	/* update out statistics */
2865 	net->stats.rx_packets++;
2866 	net->stats.rx_bytes += size;
2867 	muxnet_put(mux_net);
2868 	return;
2869 }
2870 
2871 static void gsm_mux_net_init(struct net_device *net)
2872 {
2873 	static const struct net_device_ops gsm_netdev_ops = {
2874 		.ndo_open		= gsm_mux_net_open,
2875 		.ndo_stop		= gsm_mux_net_close,
2876 		.ndo_start_xmit		= gsm_mux_net_start_xmit,
2877 		.ndo_tx_timeout		= gsm_mux_net_tx_timeout,
2878 	};
2879 
2880 	net->netdev_ops = &gsm_netdev_ops;
2881 
2882 	/* fill in the other fields */
2883 	net->watchdog_timeo = GSM_NET_TX_TIMEOUT;
2884 	net->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
2885 	net->type = ARPHRD_NONE;
2886 	net->tx_queue_len = 10;
2887 }
2888 
2889 
2890 /* caller holds the dlci mutex */
2891 static void gsm_destroy_network(struct gsm_dlci *dlci)
2892 {
2893 	struct gsm_mux_net *mux_net;
2894 
2895 	pr_debug("destroy network interface\n");
2896 	if (!dlci->net)
2897 		return;
2898 	mux_net = netdev_priv(dlci->net);
2899 	muxnet_put(mux_net);
2900 }
2901 
2902 
2903 /* caller holds the dlci mutex */
2904 static int gsm_create_network(struct gsm_dlci *dlci, struct gsm_netconfig *nc)
2905 {
2906 	char *netname;
2907 	int retval = 0;
2908 	struct net_device *net;
2909 	struct gsm_mux_net *mux_net;
2910 
2911 	if (!capable(CAP_NET_ADMIN))
2912 		return -EPERM;
2913 
2914 	/* Already in a non tty mode */
2915 	if (dlci->adaption > 2)
2916 		return -EBUSY;
2917 
2918 	if (nc->protocol != htons(ETH_P_IP))
2919 		return -EPROTONOSUPPORT;
2920 
2921 	if (nc->adaption != 3 && nc->adaption != 4)
2922 		return -EPROTONOSUPPORT;
2923 
2924 	pr_debug("create network interface\n");
2925 
2926 	netname = "gsm%d";
2927 	if (nc->if_name[0] != '\0')
2928 		netname = nc->if_name;
2929 	net = alloc_netdev(sizeof(struct gsm_mux_net), netname,
2930 			   NET_NAME_UNKNOWN, gsm_mux_net_init);
2931 	if (!net) {
2932 		pr_err("alloc_netdev failed\n");
2933 		return -ENOMEM;
2934 	}
2935 	net->mtu = dlci->gsm->mtu;
2936 	net->min_mtu = 8;
2937 	net->max_mtu = dlci->gsm->mtu;
2938 	mux_net = netdev_priv(net);
2939 	mux_net->dlci = dlci;
2940 	kref_init(&mux_net->ref);
2941 	strncpy(nc->if_name, net->name, IFNAMSIZ); /* return net name */
2942 
2943 	/* reconfigure dlci for network */
2944 	dlci->prev_adaption = dlci->adaption;
2945 	dlci->prev_data = dlci->data;
2946 	dlci->adaption = nc->adaption;
2947 	dlci->data = gsm_mux_rx_netchar;
2948 	dlci->net = net;
2949 
2950 	pr_debug("register netdev\n");
2951 	retval = register_netdev(net);
2952 	if (retval) {
2953 		pr_err("network register fail %d\n", retval);
2954 		dlci_net_free(dlci);
2955 		return retval;
2956 	}
2957 	return net->ifindex;	/* return network index */
2958 }
2959 
2960 /* Line discipline for real tty */
2961 static struct tty_ldisc_ops tty_ldisc_packet = {
2962 	.owner		 = THIS_MODULE,
2963 	.num		 = N_GSM0710,
2964 	.name            = "n_gsm",
2965 	.open            = gsmld_open,
2966 	.close           = gsmld_close,
2967 	.flush_buffer    = gsmld_flush_buffer,
2968 	.read            = gsmld_read,
2969 	.write           = gsmld_write,
2970 	.ioctl           = gsmld_ioctl,
2971 	.poll            = gsmld_poll,
2972 	.receive_buf     = gsmld_receive_buf,
2973 	.write_wakeup    = gsmld_write_wakeup
2974 };
2975 
2976 /*
2977  *	Virtual tty side
2978  */
2979 
2980 /**
2981  *	gsm_modem_upd_via_data	-	send modem bits via convergence layer
2982  *	@dlci: channel
2983  *	@brk: break signal
2984  *
2985  *	Send an empty frame to signal mobile state changes and to transmit the
2986  *	break signal for adaption 2.
2987  */
2988 
2989 static void gsm_modem_upd_via_data(struct gsm_dlci *dlci, u8 brk)
2990 {
2991 	struct gsm_mux *gsm = dlci->gsm;
2992 	unsigned long flags;
2993 
2994 	if (dlci->state != DLCI_OPEN || dlci->adaption != 2)
2995 		return;
2996 
2997 	spin_lock_irqsave(&gsm->tx_lock, flags);
2998 	gsm_dlci_modem_output(gsm, dlci, brk);
2999 	spin_unlock_irqrestore(&gsm->tx_lock, flags);
3000 }
3001 
3002 /**
3003  *	gsm_modem_upd_via_msc	-	send modem bits via control frame
3004  *	@dlci: channel
3005  *	@brk: break signal
3006  */
3007 
3008 static int gsm_modem_upd_via_msc(struct gsm_dlci *dlci, u8 brk)
3009 {
3010 	u8 modembits[3];
3011 	struct gsm_control *ctrl;
3012 	int len = 2;
3013 
3014 	if (dlci->gsm->encoding != 0)
3015 		return 0;
3016 
3017 	modembits[0] = (dlci->addr << 2) | 2 | EA;  /* DLCI, Valid, EA */
3018 	if (!brk) {
3019 		modembits[1] = (gsm_encode_modem(dlci) << 1) | EA;
3020 	} else {
3021 		modembits[1] = gsm_encode_modem(dlci) << 1;
3022 		modembits[2] = (brk << 4) | 2 | EA; /* Length, Break, EA */
3023 		len++;
3024 	}
3025 	ctrl = gsm_control_send(dlci->gsm, CMD_MSC, modembits, len);
3026 	if (ctrl == NULL)
3027 		return -ENOMEM;
3028 	return gsm_control_wait(dlci->gsm, ctrl);
3029 }
3030 
3031 /**
3032  *	gsm_modem_update	-	send modem status line state
3033  *	@dlci: channel
3034  *	@brk: break signal
3035  */
3036 
3037 static int gsm_modem_update(struct gsm_dlci *dlci, u8 brk)
3038 {
3039 	if (dlci->adaption == 2) {
3040 		/* Send convergence layer type 2 empty data frame. */
3041 		gsm_modem_upd_via_data(dlci, brk);
3042 		return 0;
3043 	} else if (dlci->gsm->encoding == 0) {
3044 		/* Send as MSC control message. */
3045 		return gsm_modem_upd_via_msc(dlci, brk);
3046 	}
3047 
3048 	/* Modem status lines are not supported. */
3049 	return -EPROTONOSUPPORT;
3050 }
3051 
3052 static int gsm_carrier_raised(struct tty_port *port)
3053 {
3054 	struct gsm_dlci *dlci = container_of(port, struct gsm_dlci, port);
3055 	struct gsm_mux *gsm = dlci->gsm;
3056 
3057 	/* Not yet open so no carrier info */
3058 	if (dlci->state != DLCI_OPEN)
3059 		return 0;
3060 	if (debug & 2)
3061 		return 1;
3062 
3063 	/*
3064 	 * Basic mode with control channel in ADM mode may not respond
3065 	 * to CMD_MSC at all and modem_rx is empty.
3066 	 */
3067 	if (gsm->encoding == 0 && gsm->dlci[0]->mode == DLCI_MODE_ADM &&
3068 	    !dlci->modem_rx)
3069 		return 1;
3070 
3071 	return dlci->modem_rx & TIOCM_CD;
3072 }
3073 
3074 static void gsm_dtr_rts(struct tty_port *port, int onoff)
3075 {
3076 	struct gsm_dlci *dlci = container_of(port, struct gsm_dlci, port);
3077 	unsigned int modem_tx = dlci->modem_tx;
3078 	if (onoff)
3079 		modem_tx |= TIOCM_DTR | TIOCM_RTS;
3080 	else
3081 		modem_tx &= ~(TIOCM_DTR | TIOCM_RTS);
3082 	if (modem_tx != dlci->modem_tx) {
3083 		dlci->modem_tx = modem_tx;
3084 		gsm_modem_update(dlci, 0);
3085 	}
3086 }
3087 
3088 static const struct tty_port_operations gsm_port_ops = {
3089 	.carrier_raised = gsm_carrier_raised,
3090 	.dtr_rts = gsm_dtr_rts,
3091 	.destruct = gsm_dlci_free,
3092 };
3093 
3094 static int gsmtty_install(struct tty_driver *driver, struct tty_struct *tty)
3095 {
3096 	struct gsm_mux *gsm;
3097 	struct gsm_dlci *dlci;
3098 	unsigned int line = tty->index;
3099 	unsigned int mux = mux_line_to_num(line);
3100 	bool alloc = false;
3101 	int ret;
3102 
3103 	line = line & 0x3F;
3104 
3105 	if (mux >= MAX_MUX)
3106 		return -ENXIO;
3107 	/* FIXME: we need to lock gsm_mux for lifetimes of ttys eventually */
3108 	if (gsm_mux[mux] == NULL)
3109 		return -EUNATCH;
3110 	if (line == 0 || line > 61)	/* 62/63 reserved */
3111 		return -ECHRNG;
3112 	gsm = gsm_mux[mux];
3113 	if (gsm->dead)
3114 		return -EL2HLT;
3115 	/* If DLCI 0 is not yet fully open return an error.
3116 	This is ok from a locking
3117 	perspective as we don't have to worry about this
3118 	if DLCI0 is lost */
3119 	mutex_lock(&gsm->mutex);
3120 	if (gsm->dlci[0] && gsm->dlci[0]->state != DLCI_OPEN) {
3121 		mutex_unlock(&gsm->mutex);
3122 		return -EL2NSYNC;
3123 	}
3124 	dlci = gsm->dlci[line];
3125 	if (dlci == NULL) {
3126 		alloc = true;
3127 		dlci = gsm_dlci_alloc(gsm, line);
3128 	}
3129 	if (dlci == NULL) {
3130 		mutex_unlock(&gsm->mutex);
3131 		return -ENOMEM;
3132 	}
3133 	ret = tty_port_install(&dlci->port, driver, tty);
3134 	if (ret) {
3135 		if (alloc)
3136 			dlci_put(dlci);
3137 		mutex_unlock(&gsm->mutex);
3138 		return ret;
3139 	}
3140 
3141 	dlci_get(dlci);
3142 	dlci_get(gsm->dlci[0]);
3143 	mux_get(gsm);
3144 	tty->driver_data = dlci;
3145 	mutex_unlock(&gsm->mutex);
3146 
3147 	return 0;
3148 }
3149 
3150 static int gsmtty_open(struct tty_struct *tty, struct file *filp)
3151 {
3152 	struct gsm_dlci *dlci = tty->driver_data;
3153 	struct tty_port *port = &dlci->port;
3154 	struct gsm_mux *gsm = dlci->gsm;
3155 
3156 	port->count++;
3157 	tty_port_tty_set(port, tty);
3158 
3159 	dlci->modem_rx = 0;
3160 	/* We could in theory open and close before we wait - eg if we get
3161 	   a DM straight back. This is ok as that will have caused a hangup */
3162 	tty_port_set_initialized(port, 1);
3163 	/* Start sending off SABM messages */
3164 	if (gsm->initiator)
3165 		gsm_dlci_begin_open(dlci);
3166 	/* And wait for virtual carrier */
3167 	return tty_port_block_til_ready(port, tty, filp);
3168 }
3169 
3170 static void gsmtty_close(struct tty_struct *tty, struct file *filp)
3171 {
3172 	struct gsm_dlci *dlci = tty->driver_data;
3173 
3174 	if (dlci == NULL)
3175 		return;
3176 	if (dlci->state == DLCI_CLOSED)
3177 		return;
3178 	mutex_lock(&dlci->mutex);
3179 	gsm_destroy_network(dlci);
3180 	mutex_unlock(&dlci->mutex);
3181 	if (tty_port_close_start(&dlci->port, tty, filp) == 0)
3182 		return;
3183 	gsm_dlci_begin_close(dlci);
3184 	if (tty_port_initialized(&dlci->port) && C_HUPCL(tty))
3185 		tty_port_lower_dtr_rts(&dlci->port);
3186 	tty_port_close_end(&dlci->port, tty);
3187 	tty_port_tty_set(&dlci->port, NULL);
3188 	return;
3189 }
3190 
3191 static void gsmtty_hangup(struct tty_struct *tty)
3192 {
3193 	struct gsm_dlci *dlci = tty->driver_data;
3194 	if (dlci->state == DLCI_CLOSED)
3195 		return;
3196 	tty_port_hangup(&dlci->port);
3197 	gsm_dlci_begin_close(dlci);
3198 }
3199 
3200 static int gsmtty_write(struct tty_struct *tty, const unsigned char *buf,
3201 								    int len)
3202 {
3203 	int sent;
3204 	struct gsm_dlci *dlci = tty->driver_data;
3205 	if (dlci->state == DLCI_CLOSED)
3206 		return -EINVAL;
3207 	/* Stuff the bytes into the fifo queue */
3208 	sent = kfifo_in_locked(&dlci->fifo, buf, len, &dlci->lock);
3209 	/* Need to kick the channel */
3210 	gsm_dlci_data_kick(dlci);
3211 	return sent;
3212 }
3213 
3214 static unsigned int gsmtty_write_room(struct tty_struct *tty)
3215 {
3216 	struct gsm_dlci *dlci = tty->driver_data;
3217 	if (dlci->state == DLCI_CLOSED)
3218 		return 0;
3219 	return kfifo_avail(&dlci->fifo);
3220 }
3221 
3222 static unsigned int gsmtty_chars_in_buffer(struct tty_struct *tty)
3223 {
3224 	struct gsm_dlci *dlci = tty->driver_data;
3225 	if (dlci->state == DLCI_CLOSED)
3226 		return 0;
3227 	return kfifo_len(&dlci->fifo);
3228 }
3229 
3230 static void gsmtty_flush_buffer(struct tty_struct *tty)
3231 {
3232 	struct gsm_dlci *dlci = tty->driver_data;
3233 	unsigned long flags;
3234 
3235 	if (dlci->state == DLCI_CLOSED)
3236 		return;
3237 	/* Caution needed: If we implement reliable transport classes
3238 	   then the data being transmitted can't simply be junked once
3239 	   it has first hit the stack. Until then we can just blow it
3240 	   away */
3241 	spin_lock_irqsave(&dlci->lock, flags);
3242 	kfifo_reset(&dlci->fifo);
3243 	spin_unlock_irqrestore(&dlci->lock, flags);
3244 	/* Need to unhook this DLCI from the transmit queue logic */
3245 }
3246 
3247 static void gsmtty_wait_until_sent(struct tty_struct *tty, int timeout)
3248 {
3249 	/* The FIFO handles the queue so the kernel will do the right
3250 	   thing waiting on chars_in_buffer before calling us. No work
3251 	   to do here */
3252 }
3253 
3254 static int gsmtty_tiocmget(struct tty_struct *tty)
3255 {
3256 	struct gsm_dlci *dlci = tty->driver_data;
3257 	if (dlci->state == DLCI_CLOSED)
3258 		return -EINVAL;
3259 	return dlci->modem_rx;
3260 }
3261 
3262 static int gsmtty_tiocmset(struct tty_struct *tty,
3263 	unsigned int set, unsigned int clear)
3264 {
3265 	struct gsm_dlci *dlci = tty->driver_data;
3266 	unsigned int modem_tx = dlci->modem_tx;
3267 
3268 	if (dlci->state == DLCI_CLOSED)
3269 		return -EINVAL;
3270 	modem_tx &= ~clear;
3271 	modem_tx |= set;
3272 
3273 	if (modem_tx != dlci->modem_tx) {
3274 		dlci->modem_tx = modem_tx;
3275 		return gsm_modem_update(dlci, 0);
3276 	}
3277 	return 0;
3278 }
3279 
3280 
3281 static int gsmtty_ioctl(struct tty_struct *tty,
3282 			unsigned int cmd, unsigned long arg)
3283 {
3284 	struct gsm_dlci *dlci = tty->driver_data;
3285 	struct gsm_netconfig nc;
3286 	int index;
3287 
3288 	if (dlci->state == DLCI_CLOSED)
3289 		return -EINVAL;
3290 	switch (cmd) {
3291 	case GSMIOC_ENABLE_NET:
3292 		if (copy_from_user(&nc, (void __user *)arg, sizeof(nc)))
3293 			return -EFAULT;
3294 		nc.if_name[IFNAMSIZ-1] = '\0';
3295 		/* return net interface index or error code */
3296 		mutex_lock(&dlci->mutex);
3297 		index = gsm_create_network(dlci, &nc);
3298 		mutex_unlock(&dlci->mutex);
3299 		if (copy_to_user((void __user *)arg, &nc, sizeof(nc)))
3300 			return -EFAULT;
3301 		return index;
3302 	case GSMIOC_DISABLE_NET:
3303 		if (!capable(CAP_NET_ADMIN))
3304 			return -EPERM;
3305 		mutex_lock(&dlci->mutex);
3306 		gsm_destroy_network(dlci);
3307 		mutex_unlock(&dlci->mutex);
3308 		return 0;
3309 	default:
3310 		return -ENOIOCTLCMD;
3311 	}
3312 }
3313 
3314 static void gsmtty_set_termios(struct tty_struct *tty, struct ktermios *old)
3315 {
3316 	struct gsm_dlci *dlci = tty->driver_data;
3317 	if (dlci->state == DLCI_CLOSED)
3318 		return;
3319 	/* For the moment its fixed. In actual fact the speed information
3320 	   for the virtual channel can be propogated in both directions by
3321 	   the RPN control message. This however rapidly gets nasty as we
3322 	   then have to remap modem signals each way according to whether
3323 	   our virtual cable is null modem etc .. */
3324 	tty_termios_copy_hw(&tty->termios, old);
3325 }
3326 
3327 static void gsmtty_throttle(struct tty_struct *tty)
3328 {
3329 	struct gsm_dlci *dlci = tty->driver_data;
3330 	if (dlci->state == DLCI_CLOSED)
3331 		return;
3332 	if (C_CRTSCTS(tty))
3333 		dlci->modem_tx &= ~TIOCM_RTS;
3334 	dlci->throttled = true;
3335 	/* Send an MSC with RTS cleared */
3336 	gsm_modem_update(dlci, 0);
3337 }
3338 
3339 static void gsmtty_unthrottle(struct tty_struct *tty)
3340 {
3341 	struct gsm_dlci *dlci = tty->driver_data;
3342 	if (dlci->state == DLCI_CLOSED)
3343 		return;
3344 	if (C_CRTSCTS(tty))
3345 		dlci->modem_tx |= TIOCM_RTS;
3346 	dlci->throttled = false;
3347 	/* Send an MSC with RTS set */
3348 	gsm_modem_update(dlci, 0);
3349 }
3350 
3351 static int gsmtty_break_ctl(struct tty_struct *tty, int state)
3352 {
3353 	struct gsm_dlci *dlci = tty->driver_data;
3354 	int encode = 0;	/* Off */
3355 	if (dlci->state == DLCI_CLOSED)
3356 		return -EINVAL;
3357 
3358 	if (state == -1)	/* "On indefinitely" - we can't encode this
3359 				    properly */
3360 		encode = 0x0F;
3361 	else if (state > 0) {
3362 		encode = state / 200;	/* mS to encoding */
3363 		if (encode > 0x0F)
3364 			encode = 0x0F;	/* Best effort */
3365 	}
3366 	return gsm_modem_update(dlci, encode);
3367 }
3368 
3369 static void gsmtty_cleanup(struct tty_struct *tty)
3370 {
3371 	struct gsm_dlci *dlci = tty->driver_data;
3372 	struct gsm_mux *gsm = dlci->gsm;
3373 
3374 	dlci_put(dlci);
3375 	dlci_put(gsm->dlci[0]);
3376 	mux_put(gsm);
3377 }
3378 
3379 /* Virtual ttys for the demux */
3380 static const struct tty_operations gsmtty_ops = {
3381 	.install		= gsmtty_install,
3382 	.open			= gsmtty_open,
3383 	.close			= gsmtty_close,
3384 	.write			= gsmtty_write,
3385 	.write_room		= gsmtty_write_room,
3386 	.chars_in_buffer	= gsmtty_chars_in_buffer,
3387 	.flush_buffer		= gsmtty_flush_buffer,
3388 	.ioctl			= gsmtty_ioctl,
3389 	.throttle		= gsmtty_throttle,
3390 	.unthrottle		= gsmtty_unthrottle,
3391 	.set_termios		= gsmtty_set_termios,
3392 	.hangup			= gsmtty_hangup,
3393 	.wait_until_sent	= gsmtty_wait_until_sent,
3394 	.tiocmget		= gsmtty_tiocmget,
3395 	.tiocmset		= gsmtty_tiocmset,
3396 	.break_ctl		= gsmtty_break_ctl,
3397 	.cleanup		= gsmtty_cleanup,
3398 };
3399 
3400 
3401 
3402 static int __init gsm_init(void)
3403 {
3404 	/* Fill in our line protocol discipline, and register it */
3405 	int status = tty_register_ldisc(&tty_ldisc_packet);
3406 	if (status != 0) {
3407 		pr_err("n_gsm: can't register line discipline (err = %d)\n",
3408 								status);
3409 		return status;
3410 	}
3411 
3412 	gsm_tty_driver = tty_alloc_driver(256, TTY_DRIVER_REAL_RAW |
3413 			TTY_DRIVER_DYNAMIC_DEV | TTY_DRIVER_HARDWARE_BREAK);
3414 	if (IS_ERR(gsm_tty_driver)) {
3415 		pr_err("gsm_init: tty allocation failed.\n");
3416 		status = PTR_ERR(gsm_tty_driver);
3417 		goto err_unreg_ldisc;
3418 	}
3419 	gsm_tty_driver->driver_name	= "gsmtty";
3420 	gsm_tty_driver->name		= "gsmtty";
3421 	gsm_tty_driver->major		= 0;	/* Dynamic */
3422 	gsm_tty_driver->minor_start	= 0;
3423 	gsm_tty_driver->type		= TTY_DRIVER_TYPE_SERIAL;
3424 	gsm_tty_driver->subtype	= SERIAL_TYPE_NORMAL;
3425 	gsm_tty_driver->init_termios	= tty_std_termios;
3426 	/* Fixme */
3427 	gsm_tty_driver->init_termios.c_lflag &= ~ECHO;
3428 	tty_set_operations(gsm_tty_driver, &gsmtty_ops);
3429 
3430 	if (tty_register_driver(gsm_tty_driver)) {
3431 		pr_err("gsm_init: tty registration failed.\n");
3432 		status = -EBUSY;
3433 		goto err_put_driver;
3434 	}
3435 	pr_debug("gsm_init: loaded as %d,%d.\n",
3436 			gsm_tty_driver->major, gsm_tty_driver->minor_start);
3437 	return 0;
3438 err_put_driver:
3439 	tty_driver_kref_put(gsm_tty_driver);
3440 err_unreg_ldisc:
3441 	tty_unregister_ldisc(&tty_ldisc_packet);
3442 	return status;
3443 }
3444 
3445 static void __exit gsm_exit(void)
3446 {
3447 	tty_unregister_ldisc(&tty_ldisc_packet);
3448 	tty_unregister_driver(gsm_tty_driver);
3449 	tty_driver_kref_put(gsm_tty_driver);
3450 }
3451 
3452 module_init(gsm_init);
3453 module_exit(gsm_exit);
3454 
3455 
3456 MODULE_LICENSE("GPL");
3457 MODULE_ALIAS_LDISC(N_GSM0710);
3458