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