tty: BKL pushdown
[pandora-kernel.git] / drivers / char / n_hdlc.c
1 /* generic HDLC line discipline for Linux
2  *
3  * Written by Paul Fulghum paulkf@microgate.com
4  * for Microgate Corporation
5  *
6  * Microgate and SyncLink are registered trademarks of Microgate Corporation
7  *
8  * Adapted from ppp.c, written by Michael Callahan <callahan@maths.ox.ac.uk>,
9  *      Al Longyear <longyear@netcom.com>,
10  *      Paul Mackerras <Paul.Mackerras@cs.anu.edu.au>
11  *
12  * Original release 01/11/99
13  * $Id: n_hdlc.c,v 4.8 2003/05/06 21:18:51 paulkf Exp $
14  *
15  * This code is released under the GNU General Public License (GPL)
16  *
17  * This module implements the tty line discipline N_HDLC for use with
18  * tty device drivers that support bit-synchronous HDLC communications.
19  *
20  * All HDLC data is frame oriented which means:
21  *
22  * 1. tty write calls represent one complete transmit frame of data
23  *    The device driver should accept the complete frame or none of 
24  *    the frame (busy) in the write method. Each write call should have
25  *    a byte count in the range of 2-65535 bytes (2 is min HDLC frame
26  *    with 1 addr byte and 1 ctrl byte). The max byte count of 65535
27  *    should include any crc bytes required. For example, when using
28  *    CCITT CRC32, 4 crc bytes are required, so the maximum size frame
29  *    the application may transmit is limited to 65531 bytes. For CCITT
30  *    CRC16, the maximum application frame size would be 65533.
31  *
32  *
33  * 2. receive callbacks from the device driver represents
34  *    one received frame. The device driver should bypass
35  *    the tty flip buffer and call the line discipline receive
36  *    callback directly to avoid fragmenting or concatenating
37  *    multiple frames into a single receive callback.
38  *
39  *    The HDLC line discipline queues the receive frames in separate
40  *    buffers so complete receive frames can be returned by the
41  *    tty read calls.
42  *
43  * 3. tty read calls returns an entire frame of data or nothing.
44  *    
45  * 4. all send and receive data is considered raw. No processing
46  *    or translation is performed by the line discipline, regardless
47  *    of the tty flags
48  *
49  * 5. When line discipline is queried for the amount of receive
50  *    data available (FIOC), 0 is returned if no data available,
51  *    otherwise the count of the next available frame is returned.
52  *    (instead of the sum of all received frame counts).
53  *
54  * These conventions allow the standard tty programming interface
55  * to be used for synchronous HDLC applications when used with
56  * this line discipline (or another line discipline that is frame
57  * oriented such as N_PPP).
58  *
59  * The SyncLink driver (synclink.c) implements both asynchronous
60  * (using standard line discipline N_TTY) and synchronous HDLC
61  * (using N_HDLC) communications, with the latter using the above
62  * conventions.
63  *
64  * This implementation is very basic and does not maintain
65  * any statistics. The main point is to enforce the raw data
66  * and frame orientation of HDLC communications.
67  *
68  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
69  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
70  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
71  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
72  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
73  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
74  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
75  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
76  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
77  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
78  * OF THE POSSIBILITY OF SUCH DAMAGE.
79  */
80
81 #define HDLC_MAGIC 0x239e
82 #define HDLC_VERSION "$Revision: 4.8 $"
83
84 #include <linux/module.h>
85 #include <linux/init.h>
86 #include <linux/kernel.h>
87 #include <linux/sched.h>
88 #include <linux/types.h>
89 #include <linux/fcntl.h>
90 #include <linux/interrupt.h>
91 #include <linux/ptrace.h>
92
93 #undef VERSION
94 #define VERSION(major,minor,patch) (((((major)<<8)+(minor))<<8)+(patch))
95
96 #include <linux/poll.h>
97 #include <linux/in.h>
98 #include <linux/ioctl.h>
99 #include <linux/slab.h>
100 #include <linux/tty.h>
101 #include <linux/errno.h>
102 #include <linux/string.h>       /* used in new tty drivers */
103 #include <linux/signal.h>       /* used in new tty drivers */
104 #include <linux/if.h>
105 #include <linux/bitops.h>
106
107 #include <asm/system.h>
108 #include <asm/termios.h>
109 #include <asm/uaccess.h>
110
111 /*
112  * Buffers for individual HDLC frames
113  */
114 #define MAX_HDLC_FRAME_SIZE 65535 
115 #define DEFAULT_RX_BUF_COUNT 10
116 #define MAX_RX_BUF_COUNT 60
117 #define DEFAULT_TX_BUF_COUNT 1
118
119 struct n_hdlc_buf {
120         struct n_hdlc_buf *link;
121         int               count;
122         char              buf[1];
123 };
124
125 #define N_HDLC_BUF_SIZE (sizeof(struct n_hdlc_buf) + maxframe)
126
127 struct n_hdlc_buf_list {
128         struct n_hdlc_buf *head;
129         struct n_hdlc_buf *tail;
130         int               count;
131         spinlock_t        spinlock;
132 };
133
134 /**
135  * struct n_hdlc - per device instance data structure
136  * @magic - magic value for structure
137  * @flags - miscellaneous control flags
138  * @tty - ptr to TTY structure
139  * @backup_tty - TTY to use if tty gets closed
140  * @tbusy - reentrancy flag for tx wakeup code
141  * @woke_up - FIXME: describe this field
142  * @tbuf - currently transmitting tx buffer
143  * @tx_buf_list - list of pending transmit frame buffers
144  * @rx_buf_list - list of received frame buffers
145  * @tx_free_buf_list - list unused transmit frame buffers
146  * @rx_free_buf_list - list unused received frame buffers
147  */
148 struct n_hdlc {
149         int                     magic;
150         __u32                   flags;
151         struct tty_struct       *tty;
152         struct tty_struct       *backup_tty;
153         int                     tbusy;
154         int                     woke_up;
155         struct n_hdlc_buf       *tbuf;
156         struct n_hdlc_buf_list  tx_buf_list;
157         struct n_hdlc_buf_list  rx_buf_list;
158         struct n_hdlc_buf_list  tx_free_buf_list;
159         struct n_hdlc_buf_list  rx_free_buf_list;
160 };
161
162 /*
163  * HDLC buffer list manipulation functions
164  */
165 static void n_hdlc_buf_list_init(struct n_hdlc_buf_list *list);
166 static void n_hdlc_buf_put(struct n_hdlc_buf_list *list,
167                            struct n_hdlc_buf *buf);
168 static struct n_hdlc_buf *n_hdlc_buf_get(struct n_hdlc_buf_list *list);
169
170 /* Local functions */
171
172 static struct n_hdlc *n_hdlc_alloc (void);
173
174 /* debug level can be set by insmod for debugging purposes */
175 #define DEBUG_LEVEL_INFO        1
176 static int debuglevel;
177
178 /* max frame size for memory allocations */
179 static int maxframe = 4096;
180
181 /* TTY callbacks */
182
183 static ssize_t n_hdlc_tty_read(struct tty_struct *tty, struct file *file,
184                            __u8 __user *buf, size_t nr);
185 static ssize_t n_hdlc_tty_write(struct tty_struct *tty, struct file *file,
186                             const unsigned char *buf, size_t nr);
187 static int n_hdlc_tty_ioctl(struct tty_struct *tty, struct file *file,
188                             unsigned int cmd, unsigned long arg);
189 static unsigned int n_hdlc_tty_poll(struct tty_struct *tty, struct file *filp,
190                                     poll_table *wait);
191 static int n_hdlc_tty_open(struct tty_struct *tty);
192 static void n_hdlc_tty_close(struct tty_struct *tty);
193 static void n_hdlc_tty_receive(struct tty_struct *tty, const __u8 *cp,
194                                char *fp, int count);
195 static void n_hdlc_tty_wakeup(struct tty_struct *tty);
196
197 #define bset(p,b)       ((p)[(b) >> 5] |= (1 << ((b) & 0x1f)))
198
199 #define tty2n_hdlc(tty) ((struct n_hdlc *) ((tty)->disc_data))
200 #define n_hdlc2tty(n_hdlc)      ((n_hdlc)->tty)
201
202 static struct tty_ldisc n_hdlc_ldisc = {
203         .owner          = THIS_MODULE,
204         .magic          = TTY_LDISC_MAGIC,
205         .name           = "hdlc",
206         .open           = n_hdlc_tty_open,
207         .close          = n_hdlc_tty_close,
208         .read           = n_hdlc_tty_read,
209         .write          = n_hdlc_tty_write,
210         .ioctl          = n_hdlc_tty_ioctl,
211         .poll           = n_hdlc_tty_poll,
212         .receive_buf    = n_hdlc_tty_receive,
213         .write_wakeup   = n_hdlc_tty_wakeup,
214 };
215
216 /**
217  * n_hdlc_release - release an n_hdlc per device line discipline info structure
218  * @n_hdlc - per device line discipline info structure
219  */
220 static void n_hdlc_release(struct n_hdlc *n_hdlc)
221 {
222         struct tty_struct *tty = n_hdlc2tty (n_hdlc);
223         struct n_hdlc_buf *buf;
224         
225         if (debuglevel >= DEBUG_LEVEL_INFO)     
226                 printk("%s(%d)n_hdlc_release() called\n",__FILE__,__LINE__);
227                 
228         /* Ensure that the n_hdlcd process is not hanging on select()/poll() */
229         wake_up_interruptible (&tty->read_wait);
230         wake_up_interruptible (&tty->write_wait);
231
232         if (tty->disc_data == n_hdlc)
233                 tty->disc_data = NULL;  /* Break the tty->n_hdlc link */
234
235         /* Release transmit and receive buffers */
236         for(;;) {
237                 buf = n_hdlc_buf_get(&n_hdlc->rx_free_buf_list);
238                 if (buf) {
239                         kfree(buf);
240                 } else
241                         break;
242         }
243         for(;;) {
244                 buf = n_hdlc_buf_get(&n_hdlc->tx_free_buf_list);
245                 if (buf) {
246                         kfree(buf);
247                 } else
248                         break;
249         }
250         for(;;) {
251                 buf = n_hdlc_buf_get(&n_hdlc->rx_buf_list);
252                 if (buf) {
253                         kfree(buf);
254                 } else
255                         break;
256         }
257         for(;;) {
258                 buf = n_hdlc_buf_get(&n_hdlc->tx_buf_list);
259                 if (buf) {
260                         kfree(buf);
261                 } else
262                         break;
263         }
264         kfree(n_hdlc->tbuf);
265         kfree(n_hdlc);
266         
267 }       /* end of n_hdlc_release() */
268
269 /**
270  * n_hdlc_tty_close - line discipline close
271  * @tty - pointer to tty info structure
272  *
273  * Called when the line discipline is changed to something
274  * else, the tty is closed, or the tty detects a hangup.
275  */
276 static void n_hdlc_tty_close(struct tty_struct *tty)
277 {
278         struct n_hdlc *n_hdlc = tty2n_hdlc (tty);
279
280         if (debuglevel >= DEBUG_LEVEL_INFO)     
281                 printk("%s(%d)n_hdlc_tty_close() called\n",__FILE__,__LINE__);
282                 
283         if (n_hdlc != NULL) {
284                 if (n_hdlc->magic != HDLC_MAGIC) {
285                         printk (KERN_WARNING"n_hdlc: trying to close unopened tty!\n");
286                         return;
287                 }
288 #if defined(TTY_NO_WRITE_SPLIT)
289                 clear_bit(TTY_NO_WRITE_SPLIT,&tty->flags);
290 #endif
291                 tty->disc_data = NULL;
292                 if (tty == n_hdlc->backup_tty)
293                         n_hdlc->backup_tty = NULL;
294                 if (tty != n_hdlc->tty)
295                         return;
296                 if (n_hdlc->backup_tty) {
297                         n_hdlc->tty = n_hdlc->backup_tty;
298                 } else {
299                         n_hdlc_release (n_hdlc);
300                 }
301         }
302         
303         if (debuglevel >= DEBUG_LEVEL_INFO)     
304                 printk("%s(%d)n_hdlc_tty_close() success\n",__FILE__,__LINE__);
305                 
306 }       /* end of n_hdlc_tty_close() */
307
308 /**
309  * n_hdlc_tty_open - called when line discipline changed to n_hdlc
310  * @tty - pointer to tty info structure
311  *
312  * Returns 0 if success, otherwise error code
313  */
314 static int n_hdlc_tty_open (struct tty_struct *tty)
315 {
316         struct n_hdlc *n_hdlc = tty2n_hdlc (tty);
317
318         if (debuglevel >= DEBUG_LEVEL_INFO)     
319                 printk("%s(%d)n_hdlc_tty_open() called (device=%s)\n",
320                 __FILE__,__LINE__,
321                 tty->name);
322                 
323         /* There should not be an existing table for this slot. */
324         if (n_hdlc) {
325                 printk (KERN_ERR"n_hdlc_tty_open:tty already associated!\n" );
326                 return -EEXIST;
327         }
328         
329         n_hdlc = n_hdlc_alloc();
330         if (!n_hdlc) {
331                 printk (KERN_ERR "n_hdlc_alloc failed\n");
332                 return -ENFILE;
333         }
334                 
335         tty->disc_data = n_hdlc;
336         n_hdlc->tty    = tty;
337         tty->receive_room = 65536;
338         
339 #if defined(TTY_NO_WRITE_SPLIT)
340         /* change tty_io write() to not split large writes into 8K chunks */
341         set_bit(TTY_NO_WRITE_SPLIT,&tty->flags);
342 #endif
343         
344         /* Flush any pending characters in the driver and discipline. */
345         
346         if (tty->ldisc.flush_buffer)
347                 tty->ldisc.flush_buffer (tty);
348
349         if (tty->driver->flush_buffer)
350                 tty->driver->flush_buffer (tty);
351                 
352         if (debuglevel >= DEBUG_LEVEL_INFO)     
353                 printk("%s(%d)n_hdlc_tty_open() success\n",__FILE__,__LINE__);
354                 
355         return 0;
356         
357 }       /* end of n_tty_hdlc_open() */
358
359 /**
360  * n_hdlc_send_frames - send frames on pending send buffer list
361  * @n_hdlc - pointer to ldisc instance data
362  * @tty - pointer to tty instance data
363  *
364  * Send frames on pending send buffer list until the driver does not accept a
365  * frame (busy) this function is called after adding a frame to the send buffer
366  * list and by the tty wakeup callback.
367  */
368 static void n_hdlc_send_frames(struct n_hdlc *n_hdlc, struct tty_struct *tty)
369 {
370         register int actual;
371         unsigned long flags;
372         struct n_hdlc_buf *tbuf;
373
374         if (debuglevel >= DEBUG_LEVEL_INFO)     
375                 printk("%s(%d)n_hdlc_send_frames() called\n",__FILE__,__LINE__);
376  check_again:
377                 
378         spin_lock_irqsave(&n_hdlc->tx_buf_list.spinlock, flags);
379         if (n_hdlc->tbusy) {
380                 n_hdlc->woke_up = 1;
381                 spin_unlock_irqrestore(&n_hdlc->tx_buf_list.spinlock, flags);
382                 return;
383         }
384         n_hdlc->tbusy = 1;
385         n_hdlc->woke_up = 0;
386         spin_unlock_irqrestore(&n_hdlc->tx_buf_list.spinlock, flags);
387
388         /* get current transmit buffer or get new transmit */
389         /* buffer from list of pending transmit buffers */
390                 
391         tbuf = n_hdlc->tbuf;
392         if (!tbuf)
393                 tbuf = n_hdlc_buf_get(&n_hdlc->tx_buf_list);
394                 
395         while (tbuf) {
396                 if (debuglevel >= DEBUG_LEVEL_INFO)     
397                         printk("%s(%d)sending frame %p, count=%d\n",
398                                 __FILE__,__LINE__,tbuf,tbuf->count);
399                         
400                 /* Send the next block of data to device */
401                 tty->flags |= (1 << TTY_DO_WRITE_WAKEUP);
402                 actual = tty->driver->write(tty, tbuf->buf, tbuf->count);
403
404                 /* rollback was possible and has been done */
405                 if (actual == -ERESTARTSYS) {
406                         n_hdlc->tbuf = tbuf;
407                         break;
408                 }
409                 /* if transmit error, throw frame away by */
410                 /* pretending it was accepted by driver */
411                 if (actual < 0)
412                         actual = tbuf->count;
413                 
414                 if (actual == tbuf->count) {
415                         if (debuglevel >= DEBUG_LEVEL_INFO)     
416                                 printk("%s(%d)frame %p completed\n",
417                                         __FILE__,__LINE__,tbuf);
418                                         
419                         /* free current transmit buffer */
420                         n_hdlc_buf_put(&n_hdlc->tx_free_buf_list, tbuf);
421                         
422                         /* this tx buffer is done */
423                         n_hdlc->tbuf = NULL;
424                         
425                         /* wait up sleeping writers */
426                         wake_up_interruptible(&tty->write_wait);
427         
428                         /* get next pending transmit buffer */
429                         tbuf = n_hdlc_buf_get(&n_hdlc->tx_buf_list);
430                 } else {
431                         if (debuglevel >= DEBUG_LEVEL_INFO)     
432                                 printk("%s(%d)frame %p pending\n",
433                                         __FILE__,__LINE__,tbuf);
434                                         
435                         /* buffer not accepted by driver */
436                         /* set this buffer as pending buffer */
437                         n_hdlc->tbuf = tbuf;
438                         break;
439                 }
440         }
441         
442         if (!tbuf)
443                 tty->flags  &= ~(1 << TTY_DO_WRITE_WAKEUP);
444         
445         /* Clear the re-entry flag */
446         spin_lock_irqsave(&n_hdlc->tx_buf_list.spinlock, flags);
447         n_hdlc->tbusy = 0;
448         spin_unlock_irqrestore(&n_hdlc->tx_buf_list.spinlock, flags); 
449         
450         if (n_hdlc->woke_up)
451           goto check_again;
452
453         if (debuglevel >= DEBUG_LEVEL_INFO)     
454                 printk("%s(%d)n_hdlc_send_frames() exit\n",__FILE__,__LINE__);
455                 
456 }       /* end of n_hdlc_send_frames() */
457
458 /**
459  * n_hdlc_tty_wakeup - Callback for transmit wakeup
460  * @tty - pointer to associated tty instance data
461  *
462  * Called when low level device driver can accept more send data.
463  */
464 static void n_hdlc_tty_wakeup(struct tty_struct *tty)
465 {
466         struct n_hdlc *n_hdlc = tty2n_hdlc(tty);
467
468         if (debuglevel >= DEBUG_LEVEL_INFO)     
469                 printk("%s(%d)n_hdlc_tty_wakeup() called\n",__FILE__,__LINE__);
470                 
471         if (!n_hdlc)
472                 return;
473
474         if (tty != n_hdlc->tty) {
475                 tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
476                 return;
477         }
478
479         n_hdlc_send_frames (n_hdlc, tty);
480                 
481 }       /* end of n_hdlc_tty_wakeup() */
482
483 /**
484  * n_hdlc_tty_receive - Called by tty driver when receive data is available
485  * @tty - pointer to tty instance data
486  * @data - pointer to received data
487  * @flags - pointer to flags for data
488  * @count - count of received data in bytes
489  *
490  * Called by tty low level driver when receive data is available. Data is
491  * interpreted as one HDLC frame.
492  */
493 static void n_hdlc_tty_receive(struct tty_struct *tty, const __u8 *data,
494                                char *flags, int count)
495 {
496         register struct n_hdlc *n_hdlc = tty2n_hdlc (tty);
497         register struct n_hdlc_buf *buf;
498
499         if (debuglevel >= DEBUG_LEVEL_INFO)     
500                 printk("%s(%d)n_hdlc_tty_receive() called count=%d\n",
501                         __FILE__,__LINE__, count);
502                 
503         /* This can happen if stuff comes in on the backup tty */
504         if (!n_hdlc || tty != n_hdlc->tty)
505                 return;
506                 
507         /* verify line is using HDLC discipline */
508         if (n_hdlc->magic != HDLC_MAGIC) {
509                 printk("%s(%d) line not using HDLC discipline\n",
510                         __FILE__,__LINE__);
511                 return;
512         }
513         
514         if ( count>maxframe ) {
515                 if (debuglevel >= DEBUG_LEVEL_INFO)     
516                         printk("%s(%d) rx count>maxframesize, data discarded\n",
517                                __FILE__,__LINE__);
518                 return;
519         }
520
521         /* get a free HDLC buffer */    
522         buf = n_hdlc_buf_get(&n_hdlc->rx_free_buf_list);
523         if (!buf) {
524                 /* no buffers in free list, attempt to allocate another rx buffer */
525                 /* unless the maximum count has been reached */
526                 if (n_hdlc->rx_buf_list.count < MAX_RX_BUF_COUNT)
527                         buf = kmalloc(N_HDLC_BUF_SIZE, GFP_ATOMIC);
528         }
529         
530         if (!buf) {
531                 if (debuglevel >= DEBUG_LEVEL_INFO)     
532                         printk("%s(%d) no more rx buffers, data discarded\n",
533                                __FILE__,__LINE__);
534                 return;
535         }
536                 
537         /* copy received data to HDLC buffer */
538         memcpy(buf->buf,data,count);
539         buf->count=count;
540
541         /* add HDLC buffer to list of received frames */
542         n_hdlc_buf_put(&n_hdlc->rx_buf_list, buf);
543         
544         /* wake up any blocked reads and perform async signalling */
545         wake_up_interruptible (&tty->read_wait);
546         if (n_hdlc->tty->fasync != NULL)
547                 kill_fasync (&n_hdlc->tty->fasync, SIGIO, POLL_IN);
548
549 }       /* end of n_hdlc_tty_receive() */
550
551 /**
552  * n_hdlc_tty_read - Called to retrieve one frame of data (if available)
553  * @tty - pointer to tty instance data
554  * @file - pointer to open file object
555  * @buf - pointer to returned data buffer
556  * @nr - size of returned data buffer
557  *      
558  * Returns the number of bytes returned or error code.
559  */
560 static ssize_t n_hdlc_tty_read(struct tty_struct *tty, struct file *file,
561                            __u8 __user *buf, size_t nr)
562 {
563         struct n_hdlc *n_hdlc = tty2n_hdlc(tty);
564         int ret;
565         struct n_hdlc_buf *rbuf;
566
567         if (debuglevel >= DEBUG_LEVEL_INFO)     
568                 printk("%s(%d)n_hdlc_tty_read() called\n",__FILE__,__LINE__);
569                 
570         /* Validate the pointers */
571         if (!n_hdlc)
572                 return -EIO;
573
574         /* verify user access to buffer */
575         if (!access_ok(VERIFY_WRITE, buf, nr)) {
576                 printk(KERN_WARNING "%s(%d) n_hdlc_tty_read() can't verify user "
577                 "buffer\n", __FILE__, __LINE__);
578                 return -EFAULT;
579         }
580
581         lock_kernel();
582
583         for (;;) {
584                 if (test_bit(TTY_OTHER_CLOSED, &tty->flags)) {
585                         unlock_kernel();
586                         return -EIO;
587                 }
588
589                 n_hdlc = tty2n_hdlc (tty);
590                 if (!n_hdlc || n_hdlc->magic != HDLC_MAGIC ||
591                          tty != n_hdlc->tty) {
592                         unlock_kernel();
593                         return 0;
594                 }
595
596                 rbuf = n_hdlc_buf_get(&n_hdlc->rx_buf_list);
597                 if (rbuf)
598                         break;
599                         
600                 /* no data */
601                 if (file->f_flags & O_NONBLOCK) {
602                         unlock_kernel();
603                         return -EAGAIN;
604                 }
605                         
606                 interruptible_sleep_on (&tty->read_wait);
607                 if (signal_pending(current)) {
608                         unlock_kernel();
609                         return -EINTR;
610                 }
611         }
612                 
613         if (rbuf->count > nr)
614                 /* frame too large for caller's buffer (discard frame) */
615                 ret = -EOVERFLOW;
616         else {
617                 /* Copy the data to the caller's buffer */
618                 if (copy_to_user(buf, rbuf->buf, rbuf->count))
619                         ret = -EFAULT;
620                 else
621                         ret = rbuf->count;
622         }
623         
624         /* return HDLC buffer to free list unless the free list */
625         /* count has exceeded the default value, in which case the */
626         /* buffer is freed back to the OS to conserve memory */
627         if (n_hdlc->rx_free_buf_list.count > DEFAULT_RX_BUF_COUNT)
628                 kfree(rbuf);
629         else    
630                 n_hdlc_buf_put(&n_hdlc->rx_free_buf_list,rbuf);
631         unlock_kernel();
632         return ret;
633         
634 }       /* end of n_hdlc_tty_read() */
635
636 /**
637  * n_hdlc_tty_write - write a single frame of data to device
638  * @tty - pointer to associated tty device instance data
639  * @file - pointer to file object data
640  * @data - pointer to transmit data (one frame)
641  * @count - size of transmit frame in bytes
642  *              
643  * Returns the number of bytes written (or error code).
644  */
645 static ssize_t n_hdlc_tty_write(struct tty_struct *tty, struct file *file,
646                             const unsigned char *data, size_t count)
647 {
648         struct n_hdlc *n_hdlc = tty2n_hdlc (tty);
649         int error = 0;
650         DECLARE_WAITQUEUE(wait, current);
651         struct n_hdlc_buf *tbuf;
652
653         if (debuglevel >= DEBUG_LEVEL_INFO)     
654                 printk("%s(%d)n_hdlc_tty_write() called count=%Zd\n",
655                         __FILE__,__LINE__,count);
656                 
657         /* Verify pointers */
658         if (!n_hdlc)
659                 return -EIO;
660
661         if (n_hdlc->magic != HDLC_MAGIC)
662                 return -EIO;
663
664         /* verify frame size */
665         if (count > maxframe ) {
666                 if (debuglevel & DEBUG_LEVEL_INFO)
667                         printk (KERN_WARNING
668                                 "n_hdlc_tty_write: truncating user packet "
669                                 "from %lu to %d\n", (unsigned long) count,
670                                 maxframe );
671                 count = maxframe;
672         }
673         
674         lock_kernel();
675
676         add_wait_queue(&tty->write_wait, &wait);
677         set_current_state(TASK_INTERRUPTIBLE);
678         
679         /* Allocate transmit buffer */
680         /* sleep until transmit buffer available */             
681         while (!(tbuf = n_hdlc_buf_get(&n_hdlc->tx_free_buf_list))) {
682                 schedule();
683                         
684                 n_hdlc = tty2n_hdlc (tty);
685                 if (!n_hdlc || n_hdlc->magic != HDLC_MAGIC || 
686                     tty != n_hdlc->tty) {
687                         printk("n_hdlc_tty_write: %p invalid after wait!\n", n_hdlc);
688                         error = -EIO;
689                         break;
690                 }
691                         
692                 if (signal_pending(current)) {
693                         error = -EINTR;
694                         break;
695                 }
696         }
697
698         set_current_state(TASK_RUNNING);
699         remove_wait_queue(&tty->write_wait, &wait);
700
701         if (!error) {           
702                 /* Retrieve the user's buffer */
703                 memcpy(tbuf->buf, data, count);
704
705                 /* Send the data */
706                 tbuf->count = error = count;
707                 n_hdlc_buf_put(&n_hdlc->tx_buf_list,tbuf);
708                 n_hdlc_send_frames(n_hdlc,tty);
709         }
710         unlock_kernel();
711         return error;
712         
713 }       /* end of n_hdlc_tty_write() */
714
715 /**
716  * n_hdlc_tty_ioctl - process IOCTL system call for the tty device.
717  * @tty - pointer to tty instance data
718  * @file - pointer to open file object for device
719  * @cmd - IOCTL command code
720  * @arg - argument for IOCTL call (cmd dependent)
721  *
722  * Returns command dependent result.
723  */
724 static int n_hdlc_tty_ioctl(struct tty_struct *tty, struct file *file,
725                             unsigned int cmd, unsigned long arg)
726 {
727         struct n_hdlc *n_hdlc = tty2n_hdlc (tty);
728         int error = 0;
729         int count;
730         unsigned long flags;
731         
732         if (debuglevel >= DEBUG_LEVEL_INFO)     
733                 printk("%s(%d)n_hdlc_tty_ioctl() called %d\n",
734                         __FILE__,__LINE__,cmd);
735                 
736         /* Verify the status of the device */
737         if (!n_hdlc || n_hdlc->magic != HDLC_MAGIC)
738                 return -EBADF;
739
740         switch (cmd) {
741         case FIONREAD:
742                 /* report count of read data available */
743                 /* in next available frame (if any) */
744                 spin_lock_irqsave(&n_hdlc->rx_buf_list.spinlock,flags);
745                 if (n_hdlc->rx_buf_list.head)
746                         count = n_hdlc->rx_buf_list.head->count;
747                 else
748                         count = 0;
749                 spin_unlock_irqrestore(&n_hdlc->rx_buf_list.spinlock,flags);
750                 error = put_user(count, (int __user *)arg);
751                 break;
752
753         case TIOCOUTQ:
754                 /* get the pending tx byte count in the driver */
755                 count = tty->driver->chars_in_buffer ?
756                                 tty->driver->chars_in_buffer(tty) : 0;
757                 /* add size of next output frame in queue */
758                 spin_lock_irqsave(&n_hdlc->tx_buf_list.spinlock,flags);
759                 if (n_hdlc->tx_buf_list.head)
760                         count += n_hdlc->tx_buf_list.head->count;
761                 spin_unlock_irqrestore(&n_hdlc->tx_buf_list.spinlock,flags);
762                 error = put_user(count, (int __user *)arg);
763                 break;
764
765         default:
766                 error = n_tty_ioctl (tty, file, cmd, arg);
767                 break;
768         }
769         return error;
770         
771 }       /* end of n_hdlc_tty_ioctl() */
772
773 /**
774  * n_hdlc_tty_poll - TTY callback for poll system call
775  * @tty - pointer to tty instance data
776  * @filp - pointer to open file object for device
777  * @poll_table - wait queue for operations
778  * 
779  * Determine which operations (read/write) will not block and return info
780  * to caller.
781  * Returns a bit mask containing info on which ops will not block.
782  */
783 static unsigned int n_hdlc_tty_poll(struct tty_struct *tty, struct file *filp,
784                                     poll_table *wait)
785 {
786         struct n_hdlc *n_hdlc = tty2n_hdlc (tty);
787         unsigned int mask = 0;
788
789         if (debuglevel >= DEBUG_LEVEL_INFO)     
790                 printk("%s(%d)n_hdlc_tty_poll() called\n",__FILE__,__LINE__);
791                 
792         if (n_hdlc && n_hdlc->magic == HDLC_MAGIC && tty == n_hdlc->tty) {
793                 /* queue current process into any wait queue that */
794                 /* may awaken in the future (read and write) */
795
796                 poll_wait(filp, &tty->read_wait, wait);
797                 poll_wait(filp, &tty->write_wait, wait);
798
799                 /* set bits for operations that won't block */
800                 if (n_hdlc->rx_buf_list.head)
801                         mask |= POLLIN | POLLRDNORM;    /* readable */
802                 if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
803                         mask |= POLLHUP;
804                 if (tty_hung_up_p(filp))
805                         mask |= POLLHUP;
806                 if (!tty_is_writelocked(tty) &&
807                                 n_hdlc->tx_free_buf_list.head)
808                         mask |= POLLOUT | POLLWRNORM;   /* writable */
809         }
810         return mask;
811 }       /* end of n_hdlc_tty_poll() */
812
813 /**
814  * n_hdlc_alloc - allocate an n_hdlc instance data structure
815  *
816  * Returns a pointer to newly created structure if success, otherwise %NULL
817  */
818 static struct n_hdlc *n_hdlc_alloc(void)
819 {
820         struct n_hdlc_buf *buf;
821         int i;
822         struct n_hdlc *n_hdlc = kmalloc(sizeof(*n_hdlc), GFP_KERNEL);
823
824         if (!n_hdlc)
825                 return NULL;
826
827         memset(n_hdlc, 0, sizeof(*n_hdlc));
828
829         n_hdlc_buf_list_init(&n_hdlc->rx_free_buf_list);
830         n_hdlc_buf_list_init(&n_hdlc->tx_free_buf_list);
831         n_hdlc_buf_list_init(&n_hdlc->rx_buf_list);
832         n_hdlc_buf_list_init(&n_hdlc->tx_buf_list);
833         
834         /* allocate free rx buffer list */
835         for(i=0;i<DEFAULT_RX_BUF_COUNT;i++) {
836                 buf = kmalloc(N_HDLC_BUF_SIZE, GFP_KERNEL);
837                 if (buf)
838                         n_hdlc_buf_put(&n_hdlc->rx_free_buf_list,buf);
839                 else if (debuglevel >= DEBUG_LEVEL_INFO)        
840                         printk("%s(%d)n_hdlc_alloc(), kalloc() failed for rx buffer %d\n",__FILE__,__LINE__, i);
841         }
842         
843         /* allocate free tx buffer list */
844         for(i=0;i<DEFAULT_TX_BUF_COUNT;i++) {
845                 buf = kmalloc(N_HDLC_BUF_SIZE, GFP_KERNEL);
846                 if (buf)
847                         n_hdlc_buf_put(&n_hdlc->tx_free_buf_list,buf);
848                 else if (debuglevel >= DEBUG_LEVEL_INFO)        
849                         printk("%s(%d)n_hdlc_alloc(), kalloc() failed for tx buffer %d\n",__FILE__,__LINE__, i);
850         }
851         
852         /* Initialize the control block */
853         n_hdlc->magic  = HDLC_MAGIC;
854         n_hdlc->flags  = 0;
855         
856         return n_hdlc;
857         
858 }       /* end of n_hdlc_alloc() */
859
860 /**
861  * n_hdlc_buf_list_init - initialize specified HDLC buffer list
862  * @list - pointer to buffer list
863  */
864 static void n_hdlc_buf_list_init(struct n_hdlc_buf_list *list)
865 {
866         memset(list, 0, sizeof(*list));
867         spin_lock_init(&list->spinlock);
868 }       /* end of n_hdlc_buf_list_init() */
869
870 /**
871  * n_hdlc_buf_put - add specified HDLC buffer to tail of specified list
872  * @list - pointer to buffer list
873  * @buf - pointer to buffer
874  */
875 static void n_hdlc_buf_put(struct n_hdlc_buf_list *list,
876                            struct n_hdlc_buf *buf)
877 {
878         unsigned long flags;
879         spin_lock_irqsave(&list->spinlock,flags);
880         
881         buf->link=NULL;
882         if (list->tail)
883                 list->tail->link = buf;
884         else
885                 list->head = buf;
886         list->tail = buf;
887         (list->count)++;
888         
889         spin_unlock_irqrestore(&list->spinlock,flags);
890         
891 }       /* end of n_hdlc_buf_put() */
892
893 /**
894  * n_hdlc_buf_get - remove and return an HDLC buffer from list
895  * @list - pointer to HDLC buffer list
896  * 
897  * Remove and return an HDLC buffer from the head of the specified HDLC buffer
898  * list.
899  * Returns a pointer to HDLC buffer if available, otherwise %NULL.
900  */
901 static struct n_hdlc_buf* n_hdlc_buf_get(struct n_hdlc_buf_list *list)
902 {
903         unsigned long flags;
904         struct n_hdlc_buf *buf;
905         spin_lock_irqsave(&list->spinlock,flags);
906         
907         buf = list->head;
908         if (buf) {
909                 list->head = buf->link;
910                 (list->count)--;
911         }
912         if (!list->head)
913                 list->tail = NULL;
914         
915         spin_unlock_irqrestore(&list->spinlock,flags);
916         return buf;
917         
918 }       /* end of n_hdlc_buf_get() */
919
920 static char hdlc_banner[] __initdata =
921         KERN_INFO "HDLC line discipline: version " HDLC_VERSION
922         ", maxframe=%u\n";
923 static char hdlc_register_ok[] __initdata =
924         KERN_INFO "N_HDLC line discipline registered.\n";
925 static char hdlc_register_fail[] __initdata =
926         KERN_ERR "error registering line discipline: %d\n";
927 static char hdlc_init_fail[] __initdata =
928         KERN_INFO "N_HDLC: init failure %d\n";
929
930 static int __init n_hdlc_init(void)
931 {
932         int status;
933
934         /* range check maxframe arg */
935         if (maxframe < 4096)
936                 maxframe = 4096;
937         else if (maxframe > 65535)
938                 maxframe = 65535;
939
940         printk(hdlc_banner, maxframe);
941
942         status = tty_register_ldisc(N_HDLC, &n_hdlc_ldisc);
943         if (!status)
944                 printk(hdlc_register_ok);
945         else
946                 printk(hdlc_register_fail, status);
947
948         if (status)
949                 printk(hdlc_init_fail, status);
950         return status;
951         
952 }       /* end of init_module() */
953
954 static char hdlc_unregister_ok[] __exitdata =
955         KERN_INFO "N_HDLC: line discipline unregistered\n";
956 static char hdlc_unregister_fail[] __exitdata =
957         KERN_ERR "N_HDLC: can't unregister line discipline (err = %d)\n";
958
959 static void __exit n_hdlc_exit(void)
960 {
961         /* Release tty registration of line discipline */
962         int status = tty_unregister_ldisc(N_HDLC);
963
964         if (status)
965                 printk(hdlc_unregister_fail, status);
966         else
967                 printk(hdlc_unregister_ok);
968 }
969
970 module_init(n_hdlc_init);
971 module_exit(n_hdlc_exit);
972
973 MODULE_LICENSE("GPL");
974 MODULE_AUTHOR("Paul Fulghum paulkf@microgate.com");
975 module_param(debuglevel, int, 0);
976 module_param(maxframe, int, 0);
977 MODULE_ALIAS_LDISC(N_HDLC);