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