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