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