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