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