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