1/*
2 * PPP synchronous tty channel driver for Linux.
3 *
4 * This is a ppp channel driver that can be used with tty device drivers
5 * that are frame oriented, such as synchronous HDLC devices.
6 *
7 * Complete PPP frames without encoding/decoding are exchanged between
8 * the channel driver and the device driver.
9 *
10 * The async map IOCTL codes are implemented to keep the user mode
11 * applications happy if they call them. Synchronous PPP does not use
12 * the async maps.
13 *
14 * Copyright 1999 Paul Mackerras.
15 *
16 * Also touched by the grubby hands of Paul Fulghum paulkf@microgate.com
17 *
18 *  This program is free software; you can redistribute it and/or
19 *  modify it under the terms of the GNU General Public License
20 *  as published by the Free Software Foundation; either version
21 *  2 of the License, or (at your option) any later version.
22 *
23 * This driver provides the encapsulation and framing for sending
24 * and receiving PPP frames over sync serial lines.  It relies on
25 * the generic PPP layer to give it frames to send and to process
26 * received frames.  It implements the PPP line discipline.
27 *
28 * Part of the code in this driver was inspired by the old async-only
29 * PPP driver, written by Michael Callahan and Al Longyear, and
30 * subsequently hacked by Paul Mackerras.
31 *
32 * ==FILEVERSION 20040616==
33 */
34
35#include <linux/module.h>
36#include <linux/kernel.h>
37#include <linux/skbuff.h>
38#include <linux/tty.h>
39#include <linux/netdevice.h>
40#include <linux/poll.h>
41#include <linux/ppp_defs.h>
42#include <linux/ppp-ioctl.h>
43#include <linux/ppp_channel.h>
44#include <linux/spinlock.h>
45#include <linux/completion.h>
46#include <linux/init.h>
47#include <linux/interrupt.h>
48#include <linux/slab.h>
49#include <asm/unaligned.h>
50#include <asm/uaccess.h>
51
52#define PPP_VERSION	"2.4.2"
53
54/* Structure for storing local state. */
55struct syncppp {
56	struct tty_struct *tty;
57	unsigned int	flags;
58	unsigned int	rbits;
59	int		mru;
60	spinlock_t	xmit_lock;
61	spinlock_t	recv_lock;
62	unsigned long	xmit_flags;
63	u32		xaccm[8];
64	u32		raccm;
65	unsigned int	bytes_sent;
66	unsigned int	bytes_rcvd;
67
68	struct sk_buff	*tpkt;
69	unsigned long	last_xmit;
70
71	struct sk_buff_head rqueue;
72
73	struct tasklet_struct tsk;
74
75	atomic_t	refcnt;
76	struct completion dead_cmp;
77	struct ppp_channel chan;	/* interface to generic ppp layer */
78};
79
80/* Bit numbers in xmit_flags */
81#define XMIT_WAKEUP	0
82#define XMIT_FULL	1
83
84/* Bits in rbits */
85#define SC_RCV_BITS	(SC_RCV_B7_1|SC_RCV_B7_0|SC_RCV_ODDP|SC_RCV_EVNP)
86
87#define PPPSYNC_MAX_RQLEN	32	/* arbitrary */
88
89/*
90 * Prototypes.
91 */
92static struct sk_buff* ppp_sync_txmunge(struct syncppp *ap, struct sk_buff *);
93static int ppp_sync_send(struct ppp_channel *chan, struct sk_buff *skb);
94static int ppp_sync_ioctl(struct ppp_channel *chan, unsigned int cmd,
95			  unsigned long arg);
96static void ppp_sync_process(unsigned long arg);
97static int ppp_sync_push(struct syncppp *ap);
98static void ppp_sync_flush_output(struct syncppp *ap);
99static void ppp_sync_input(struct syncppp *ap, const unsigned char *buf,
100			   char *flags, int count);
101
102static const struct ppp_channel_ops sync_ops = {
103	.start_xmit = ppp_sync_send,
104	.ioctl      = ppp_sync_ioctl,
105};
106
107/*
108 * Utility procedure to print a buffer in hex/ascii
109 */
110static void
111ppp_print_buffer (const char *name, const __u8 *buf, int count)
112{
113	if (name != NULL)
114		printk(KERN_DEBUG "ppp_synctty: %s, count = %d\n", name, count);
115
116	print_hex_dump_bytes("", DUMP_PREFIX_NONE, buf, count);
117}
118
119
120/*
121 * Routines implementing the synchronous PPP line discipline.
122 */
123
124/*
125 * We have a potential race on dereferencing tty->disc_data,
126 * because the tty layer provides no locking at all - thus one
127 * cpu could be running ppp_synctty_receive while another
128 * calls ppp_synctty_close, which zeroes tty->disc_data and
129 * frees the memory that ppp_synctty_receive is using.  The best
130 * way to fix this is to use a rwlock in the tty struct, but for now
131 * we use a single global rwlock for all ttys in ppp line discipline.
132 *
133 * FIXME: Fixed in tty_io nowadays.
134 */
135static DEFINE_RWLOCK(disc_data_lock);
136
137static struct syncppp *sp_get(struct tty_struct *tty)
138{
139	struct syncppp *ap;
140
141	read_lock(&disc_data_lock);
142	ap = tty->disc_data;
143	if (ap != NULL)
144		atomic_inc(&ap->refcnt);
145	read_unlock(&disc_data_lock);
146	return ap;
147}
148
149static void sp_put(struct syncppp *ap)
150{
151	if (atomic_dec_and_test(&ap->refcnt))
152		complete(&ap->dead_cmp);
153}
154
155/*
156 * Called when a tty is put into sync-PPP line discipline.
157 */
158static int
159ppp_sync_open(struct tty_struct *tty)
160{
161	struct syncppp *ap;
162	int err;
163	int speed;
164
165	if (tty->ops->write == NULL)
166		return -EOPNOTSUPP;
167
168	ap = kzalloc(sizeof(*ap), GFP_KERNEL);
169	err = -ENOMEM;
170	if (!ap)
171		goto out;
172
173	/* initialize the syncppp structure */
174	ap->tty = tty;
175	ap->mru = PPP_MRU;
176	spin_lock_init(&ap->xmit_lock);
177	spin_lock_init(&ap->recv_lock);
178	ap->xaccm[0] = ~0U;
179	ap->xaccm[3] = 0x60000000U;
180	ap->raccm = ~0U;
181
182	skb_queue_head_init(&ap->rqueue);
183	tasklet_init(&ap->tsk, ppp_sync_process, (unsigned long) ap);
184
185	atomic_set(&ap->refcnt, 1);
186	init_completion(&ap->dead_cmp);
187
188	ap->chan.private = ap;
189	ap->chan.ops = &sync_ops;
190	ap->chan.mtu = PPP_MRU;
191	ap->chan.hdrlen = 2;	/* for A/C bytes */
192	speed = tty_get_baud_rate(tty);
193	ap->chan.speed = speed;
194	err = ppp_register_channel(&ap->chan);
195	if (err)
196		goto out_free;
197
198	tty->disc_data = ap;
199	tty->receive_room = 65536;
200	return 0;
201
202 out_free:
203	kfree(ap);
204 out:
205	return err;
206}
207
208/*
209 * Called when the tty is put into another line discipline
210 * or it hangs up.  We have to wait for any cpu currently
211 * executing in any of the other ppp_synctty_* routines to
212 * finish before we can call ppp_unregister_channel and free
213 * the syncppp struct.  This routine must be called from
214 * process context, not interrupt or softirq context.
215 */
216static void
217ppp_sync_close(struct tty_struct *tty)
218{
219	struct syncppp *ap;
220
221	write_lock_irq(&disc_data_lock);
222	ap = tty->disc_data;
223	tty->disc_data = NULL;
224	write_unlock_irq(&disc_data_lock);
225	if (!ap)
226		return;
227
228	/*
229	 * We have now ensured that nobody can start using ap from now
230	 * on, but we have to wait for all existing users to finish.
231	 * Note that ppp_unregister_channel ensures that no calls to
232	 * our channel ops (i.e. ppp_sync_send/ioctl) are in progress
233	 * by the time it returns.
234	 */
235	if (!atomic_dec_and_test(&ap->refcnt))
236		wait_for_completion(&ap->dead_cmp);
237	tasklet_kill(&ap->tsk);
238
239	ppp_unregister_channel(&ap->chan);
240	skb_queue_purge(&ap->rqueue);
241	kfree_skb(ap->tpkt);
242	kfree(ap);
243}
244
245/*
246 * Called on tty hangup in process context.
247 *
248 * Wait for I/O to driver to complete and unregister PPP channel.
249 * This is already done by the close routine, so just call that.
250 */
251static int ppp_sync_hangup(struct tty_struct *tty)
252{
253	ppp_sync_close(tty);
254	return 0;
255}
256
257/*
258 * Read does nothing - no data is ever available this way.
259 * Pppd reads and writes packets via /dev/ppp instead.
260 */
261static ssize_t
262ppp_sync_read(struct tty_struct *tty, struct file *file,
263	       unsigned char __user *buf, size_t count)
264{
265	return -EAGAIN;
266}
267
268/*
269 * Write on the tty does nothing, the packets all come in
270 * from the ppp generic stuff.
271 */
272static ssize_t
273ppp_sync_write(struct tty_struct *tty, struct file *file,
274		const unsigned char *buf, size_t count)
275{
276	return -EAGAIN;
277}
278
279static int
280ppp_synctty_ioctl(struct tty_struct *tty, struct file *file,
281		  unsigned int cmd, unsigned long arg)
282{
283	struct syncppp *ap = sp_get(tty);
284	int __user *p = (int __user *)arg;
285	int err, val;
286
287	if (!ap)
288		return -ENXIO;
289	err = -EFAULT;
290	switch (cmd) {
291	case PPPIOCGCHAN:
292		err = -EFAULT;
293		if (put_user(ppp_channel_index(&ap->chan), p))
294			break;
295		err = 0;
296		break;
297
298	case PPPIOCGUNIT:
299		err = -EFAULT;
300		if (put_user(ppp_unit_number(&ap->chan), p))
301			break;
302		err = 0;
303		break;
304
305	case TCFLSH:
306		/* flush our buffers and the serial port's buffer */
307		if (arg == TCIOFLUSH || arg == TCOFLUSH)
308			ppp_sync_flush_output(ap);
309		err = n_tty_ioctl_helper(tty, file, cmd, arg);
310		break;
311
312	case FIONREAD:
313		val = 0;
314		if (put_user(val, p))
315			break;
316		err = 0;
317		break;
318
319	default:
320		err = tty_mode_ioctl(tty, file, cmd, arg);
321		break;
322	}
323
324	sp_put(ap);
325	return err;
326}
327
328/* No kernel lock - fine */
329static unsigned int
330ppp_sync_poll(struct tty_struct *tty, struct file *file, poll_table *wait)
331{
332	return 0;
333}
334
335/* May sleep, don't call from interrupt level or with interrupts disabled */
336static void
337ppp_sync_receive(struct tty_struct *tty, const unsigned char *buf,
338		  char *cflags, int count)
339{
340	struct syncppp *ap = sp_get(tty);
341	unsigned long flags;
342
343	if (!ap)
344		return;
345	spin_lock_irqsave(&ap->recv_lock, flags);
346	ppp_sync_input(ap, buf, cflags, count);
347	spin_unlock_irqrestore(&ap->recv_lock, flags);
348	if (!skb_queue_empty(&ap->rqueue))
349		tasklet_schedule(&ap->tsk);
350	sp_put(ap);
351	tty_unthrottle(tty);
352}
353
354static void
355ppp_sync_wakeup(struct tty_struct *tty)
356{
357	struct syncppp *ap = sp_get(tty);
358
359	clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
360	if (!ap)
361		return;
362	set_bit(XMIT_WAKEUP, &ap->xmit_flags);
363	tasklet_schedule(&ap->tsk);
364	sp_put(ap);
365}
366
367
368static struct tty_ldisc_ops ppp_sync_ldisc = {
369	.owner	= THIS_MODULE,
370	.magic	= TTY_LDISC_MAGIC,
371	.name	= "pppsync",
372	.open	= ppp_sync_open,
373	.close	= ppp_sync_close,
374	.hangup	= ppp_sync_hangup,
375	.read	= ppp_sync_read,
376	.write	= ppp_sync_write,
377	.ioctl	= ppp_synctty_ioctl,
378	.poll	= ppp_sync_poll,
379	.receive_buf = ppp_sync_receive,
380	.write_wakeup = ppp_sync_wakeup,
381};
382
383static int __init
384ppp_sync_init(void)
385{
386	int err;
387
388	err = tty_register_ldisc(N_SYNC_PPP, &ppp_sync_ldisc);
389	if (err != 0)
390		printk(KERN_ERR "PPP_sync: error %d registering line disc.\n",
391		       err);
392	return err;
393}
394
395/*
396 * The following routines provide the PPP channel interface.
397 */
398static int
399ppp_sync_ioctl(struct ppp_channel *chan, unsigned int cmd, unsigned long arg)
400{
401	struct syncppp *ap = chan->private;
402	int err, val;
403	u32 accm[8];
404	void __user *argp = (void __user *)arg;
405	u32 __user *p = argp;
406
407	err = -EFAULT;
408	switch (cmd) {
409	case PPPIOCGFLAGS:
410		val = ap->flags | ap->rbits;
411		if (put_user(val, (int __user *) argp))
412			break;
413		err = 0;
414		break;
415	case PPPIOCSFLAGS:
416		if (get_user(val, (int __user *) argp))
417			break;
418		ap->flags = val & ~SC_RCV_BITS;
419		spin_lock_irq(&ap->recv_lock);
420		ap->rbits = val & SC_RCV_BITS;
421		spin_unlock_irq(&ap->recv_lock);
422		err = 0;
423		break;
424
425	case PPPIOCGASYNCMAP:
426		if (put_user(ap->xaccm[0], p))
427			break;
428		err = 0;
429		break;
430	case PPPIOCSASYNCMAP:
431		if (get_user(ap->xaccm[0], p))
432			break;
433		err = 0;
434		break;
435
436	case PPPIOCGRASYNCMAP:
437		if (put_user(ap->raccm, p))
438			break;
439		err = 0;
440		break;
441	case PPPIOCSRASYNCMAP:
442		if (get_user(ap->raccm, p))
443			break;
444		err = 0;
445		break;
446
447	case PPPIOCGXASYNCMAP:
448		if (copy_to_user(argp, ap->xaccm, sizeof(ap->xaccm)))
449			break;
450		err = 0;
451		break;
452	case PPPIOCSXASYNCMAP:
453		if (copy_from_user(accm, argp, sizeof(accm)))
454			break;
455		accm[2] &= ~0x40000000U;	/* can't escape 0x5e */
456		accm[3] |= 0x60000000U;		/* must escape 0x7d, 0x7e */
457		memcpy(ap->xaccm, accm, sizeof(ap->xaccm));
458		err = 0;
459		break;
460
461	case PPPIOCGMRU:
462		if (put_user(ap->mru, (int __user *) argp))
463			break;
464		err = 0;
465		break;
466	case PPPIOCSMRU:
467		if (get_user(val, (int __user *) argp))
468			break;
469		if (val < PPP_MRU)
470			val = PPP_MRU;
471		ap->mru = val;
472		err = 0;
473		break;
474
475	default:
476		err = -ENOTTY;
477	}
478	return err;
479}
480
481/*
482 * This is called at softirq level to deliver received packets
483 * to the ppp_generic code, and to tell the ppp_generic code
484 * if we can accept more output now.
485 */
486static void ppp_sync_process(unsigned long arg)
487{
488	struct syncppp *ap = (struct syncppp *) arg;
489	struct sk_buff *skb;
490
491	/* process received packets */
492	while ((skb = skb_dequeue(&ap->rqueue)) != NULL) {
493		if (skb->len == 0) {
494			/* zero length buffers indicate error */
495			ppp_input_error(&ap->chan, 0);
496			kfree_skb(skb);
497		}
498		else
499			ppp_input(&ap->chan, skb);
500	}
501
502	/* try to push more stuff out */
503	if (test_bit(XMIT_WAKEUP, &ap->xmit_flags) && ppp_sync_push(ap))
504		ppp_output_wakeup(&ap->chan);
505}
506
507/*
508 * Procedures for encapsulation and framing.
509 */
510
511static struct sk_buff*
512ppp_sync_txmunge(struct syncppp *ap, struct sk_buff *skb)
513{
514	int proto;
515	unsigned char *data;
516	int islcp;
517
518	data  = skb->data;
519	proto = get_unaligned_be16(data);
520
521	/* LCP packets with codes between 1 (configure-request)
522	 * and 7 (code-reject) must be sent as though no options
523	 * have been negotiated.
524	 */
525	islcp = proto == PPP_LCP && 1 <= data[2] && data[2] <= 7;
526
527	/* compress protocol field if option enabled */
528	if (data[0] == 0 && (ap->flags & SC_COMP_PROT) && !islcp)
529		skb_pull(skb,1);
530
531	/* prepend address/control fields if necessary */
532	if ((ap->flags & SC_COMP_AC) == 0 || islcp) {
533		if (skb_headroom(skb) < 2) {
534			struct sk_buff *npkt = dev_alloc_skb(skb->len + 2);
535			if (npkt == NULL) {
536				kfree_skb(skb);
537				return NULL;
538			}
539			skb_reserve(npkt,2);
540			skb_copy_from_linear_data(skb,
541				      skb_put(npkt, skb->len), skb->len);
542			consume_skb(skb);
543			skb = npkt;
544		}
545		skb_push(skb,2);
546		skb->data[0] = PPP_ALLSTATIONS;
547		skb->data[1] = PPP_UI;
548	}
549
550	ap->last_xmit = jiffies;
551
552	if (skb && ap->flags & SC_LOG_OUTPKT)
553		ppp_print_buffer ("send buffer", skb->data, skb->len);
554
555	return skb;
556}
557
558/*
559 * Transmit-side routines.
560 */
561
562/*
563 * Send a packet to the peer over an sync tty line.
564 * Returns 1 iff the packet was accepted.
565 * If the packet was not accepted, we will call ppp_output_wakeup
566 * at some later time.
567 */
568static int
569ppp_sync_send(struct ppp_channel *chan, struct sk_buff *skb)
570{
571	struct syncppp *ap = chan->private;
572
573	ppp_sync_push(ap);
574
575	if (test_and_set_bit(XMIT_FULL, &ap->xmit_flags))
576		return 0;	/* already full */
577	skb = ppp_sync_txmunge(ap, skb);
578	if (skb != NULL)
579		ap->tpkt = skb;
580	else
581		clear_bit(XMIT_FULL, &ap->xmit_flags);
582
583	ppp_sync_push(ap);
584	return 1;
585}
586
587/*
588 * Push as much data as possible out to the tty.
589 */
590static int
591ppp_sync_push(struct syncppp *ap)
592{
593	int sent, done = 0;
594	struct tty_struct *tty = ap->tty;
595	int tty_stuffed = 0;
596
597	if (!spin_trylock_bh(&ap->xmit_lock))
598		return 0;
599	for (;;) {
600		if (test_and_clear_bit(XMIT_WAKEUP, &ap->xmit_flags))
601			tty_stuffed = 0;
602		if (!tty_stuffed && ap->tpkt) {
603			set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
604			sent = tty->ops->write(tty, ap->tpkt->data, ap->tpkt->len);
605			if (sent < 0)
606				goto flush;	/* error, e.g. loss of CD */
607			if (sent < ap->tpkt->len) {
608				tty_stuffed = 1;
609			} else {
610				consume_skb(ap->tpkt);
611				ap->tpkt = NULL;
612				clear_bit(XMIT_FULL, &ap->xmit_flags);
613				done = 1;
614			}
615			continue;
616		}
617		/* haven't made any progress */
618		spin_unlock_bh(&ap->xmit_lock);
619		if (!(test_bit(XMIT_WAKEUP, &ap->xmit_flags) ||
620		      (!tty_stuffed && ap->tpkt)))
621			break;
622		if (!spin_trylock_bh(&ap->xmit_lock))
623			break;
624	}
625	return done;
626
627flush:
628	if (ap->tpkt) {
629		kfree_skb(ap->tpkt);
630		ap->tpkt = NULL;
631		clear_bit(XMIT_FULL, &ap->xmit_flags);
632		done = 1;
633	}
634	spin_unlock_bh(&ap->xmit_lock);
635	return done;
636}
637
638/*
639 * Flush output from our internal buffers.
640 * Called for the TCFLSH ioctl.
641 */
642static void
643ppp_sync_flush_output(struct syncppp *ap)
644{
645	int done = 0;
646
647	spin_lock_bh(&ap->xmit_lock);
648	if (ap->tpkt != NULL) {
649		kfree_skb(ap->tpkt);
650		ap->tpkt = NULL;
651		clear_bit(XMIT_FULL, &ap->xmit_flags);
652		done = 1;
653	}
654	spin_unlock_bh(&ap->xmit_lock);
655	if (done)
656		ppp_output_wakeup(&ap->chan);
657}
658
659/*
660 * Receive-side routines.
661 */
662
663/* called when the tty driver has data for us.
664 *
665 * Data is frame oriented: each call to ppp_sync_input is considered
666 * a whole frame. If the 1st flag byte is non-zero then the whole
667 * frame is considered to be in error and is tossed.
668 */
669static void
670ppp_sync_input(struct syncppp *ap, const unsigned char *buf,
671		char *flags, int count)
672{
673	struct sk_buff *skb;
674	unsigned char *p;
675
676	if (count == 0)
677		return;
678
679	if (ap->flags & SC_LOG_INPKT)
680		ppp_print_buffer ("receive buffer", buf, count);
681
682	/* stuff the chars in the skb */
683	skb = dev_alloc_skb(ap->mru + PPP_HDRLEN + 2);
684	if (!skb) {
685		printk(KERN_ERR "PPPsync: no memory (input pkt)\n");
686		goto err;
687	}
688	/* Try to get the payload 4-byte aligned */
689	if (buf[0] != PPP_ALLSTATIONS)
690		skb_reserve(skb, 2 + (buf[0] & 1));
691
692	if (flags && *flags) {
693		/* error flag set, ignore frame */
694		goto err;
695	} else if (count > skb_tailroom(skb)) {
696		/* packet overflowed MRU */
697		goto err;
698	}
699
700	p = skb_put(skb, count);
701	memcpy(p, buf, count);
702
703	/* strip address/control field if present */
704	p = skb->data;
705	if (p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
706		/* chop off address/control */
707		if (skb->len < 3)
708			goto err;
709		p = skb_pull(skb, 2);
710	}
711
712	/* decompress protocol field if compressed */
713	if (p[0] & 1) {
714		/* protocol is compressed */
715		skb_push(skb, 1)[0] = 0;
716	} else if (skb->len < 2)
717		goto err;
718
719	/* queue the frame to be processed */
720	skb_queue_tail(&ap->rqueue, skb);
721	return;
722
723err:
724	/* queue zero length packet as error indication */
725	if (skb || (skb = dev_alloc_skb(0))) {
726		skb_trim(skb, 0);
727		skb_queue_tail(&ap->rqueue, skb);
728	}
729}
730
731static void __exit
732ppp_sync_cleanup(void)
733{
734	if (tty_unregister_ldisc(N_SYNC_PPP) != 0)
735		printk(KERN_ERR "failed to unregister Sync PPP line discipline\n");
736}
737
738module_init(ppp_sync_init);
739module_exit(ppp_sync_cleanup);
740MODULE_LICENSE("GPL");
741MODULE_ALIAS_LDISC(N_SYNC_PPP);
742