Merge branch 'for-next' of git://git.kernel.org/pub/scm/linux/kernel/git/jikos/trivial
[pandora-kernel.git] / net / irda / irnet / irnet_ppp.c
1 /*
2  *      IrNET protocol module : Synchronous PPP over an IrDA socket.
3  *
4  *              Jean II - HPL `00 - <jt@hpl.hp.com>
5  *
6  * This file implement the PPP interface and /dev/irnet character device.
7  * The PPP interface hook to the ppp_generic module, handle all our
8  *      relationship to the PPP code in the kernel (and by extension to pppd),
9  *      and exchange PPP frames with this module (send/receive).
10  * The /dev/irnet device is used primarily for 2 functions :
11  *      1) as a stub for pppd (the ppp daemon), so that we can appropriately
12  *      generate PPP sessions (we pretend we are a tty).
13  *      2) as a control channel (write commands, read events)
14  */
15
16 #include <linux/sched.h>
17 #include <linux/slab.h>
18 #include <linux/smp_lock.h>
19 #include "irnet_ppp.h"          /* Private header */
20 /* Please put other headers in irnet.h - Thanks */
21
22 /* Generic PPP callbacks (to call us) */
23 static const struct ppp_channel_ops irnet_ppp_ops = {
24         .start_xmit = ppp_irnet_send,
25         .ioctl = ppp_irnet_ioctl
26 };
27
28 /************************* CONTROL CHANNEL *************************/
29 /*
30  * When a pppd instance is not active on /dev/irnet, it acts as a control
31  * channel.
32  * Writing allow to set up the IrDA destination of the IrNET channel,
33  * and any application may be read events happening in IrNET...
34  */
35
36 /*------------------------------------------------------------------*/
37 /*
38  * Write is used to send a command to configure a IrNET channel
39  * before it is open by pppd. The syntax is : "command argument"
40  * Currently there is only two defined commands :
41  *      o name : set the requested IrDA nickname of the IrNET peer.
42  *      o addr : set the requested IrDA address of the IrNET peer.
43  * Note : the code is crude, but effective...
44  */
45 static inline ssize_t
46 irnet_ctrl_write(irnet_socket * ap,
47                  const char __user *buf,
48                  size_t         count)
49 {
50   char          command[IRNET_MAX_COMMAND];
51   char *        start;          /* Current command being processed */
52   char *        next;           /* Next command to process */
53   int           length;         /* Length of current command */
54
55   DENTER(CTRL_TRACE, "(ap=0x%p, count=%Zd)\n", ap, count);
56
57   /* Check for overflow... */
58   DABORT(count >= IRNET_MAX_COMMAND, -ENOMEM,
59          CTRL_ERROR, "Too much data !!!\n");
60
61   /* Get the data in the driver */
62   if(copy_from_user(command, buf, count))
63     {
64       DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
65       return -EFAULT;
66     }
67
68   /* Safe terminate the string */
69   command[count] = '\0';
70   DEBUG(CTRL_INFO, "Command line received is ``%s'' (%Zd).\n",
71         command, count);
72
73   /* Check every commands in the command line */
74   next = command;
75   while(next != NULL)
76     {
77       /* Look at the next command */
78       start = next;
79
80         /* Scrap whitespaces before the command */
81         start = skip_spaces(start);
82
83       /* ',' is our command separator */
84       next = strchr(start, ',');
85       if(next)
86         {
87           *next = '\0';                 /* Terminate command */
88           length = next - start;        /* Length */
89           next++;                       /* Skip the '\0' */
90         }
91       else
92         length = strlen(start);
93
94       DEBUG(CTRL_INFO, "Found command ``%s'' (%d).\n", start, length);
95
96       /* Check if we recognised one of the known command
97        * We can't use "switch" with strings, so hack with "continue" */
98
99       /* First command : name -> Requested IrDA nickname */
100       if(!strncmp(start, "name", 4))
101         {
102           /* Copy the name only if is included and not "any" */
103           if((length > 5) && (strcmp(start + 5, "any")))
104             {
105               /* Strip out trailing whitespaces */
106               while(isspace(start[length - 1]))
107                 length--;
108
109               /* Copy the name for later reuse */
110               memcpy(ap->rname, start + 5, length - 5);
111               ap->rname[length - 5] = '\0';
112             }
113           else
114             ap->rname[0] = '\0';
115           DEBUG(CTRL_INFO, "Got rname = ``%s''\n", ap->rname);
116
117           /* Restart the loop */
118           continue;
119         }
120
121       /* Second command : addr, daddr -> Requested IrDA destination address
122        * Also process : saddr -> Requested IrDA source address */
123       if((!strncmp(start, "addr", 4)) ||
124          (!strncmp(start, "daddr", 5)) ||
125          (!strncmp(start, "saddr", 5)))
126         {
127           __u32         addr = DEV_ADDR_ANY;
128
129           /* Copy the address only if is included and not "any" */
130           if((length > 5) && (strcmp(start + 5, "any")))
131             {
132               char *    begp = start + 5;
133               char *    endp;
134
135               /* Scrap whitespaces before the command */
136               begp = skip_spaces(begp);
137
138               /* Convert argument to a number (last arg is the base) */
139               addr = simple_strtoul(begp, &endp, 16);
140               /* Has it worked  ? (endp should be start + length) */
141               DABORT(endp <= (start + 5), -EINVAL,
142                      CTRL_ERROR, "Invalid address.\n");
143             }
144           /* Which type of address ? */
145           if(start[0] == 's')
146             {
147               /* Save it */
148               ap->rsaddr = addr;
149               DEBUG(CTRL_INFO, "Got rsaddr = %08x\n", ap->rsaddr);
150             }
151           else
152             {
153               /* Save it */
154               ap->rdaddr = addr;
155               DEBUG(CTRL_INFO, "Got rdaddr = %08x\n", ap->rdaddr);
156             }
157
158           /* Restart the loop */
159           continue;
160         }
161
162       /* Other possible command : connect N (number of retries) */
163
164       /* No command matched -> Failed... */
165       DABORT(1, -EINVAL, CTRL_ERROR, "Not a recognised IrNET command.\n");
166     }
167
168   /* Success : we have parsed all commands successfully */
169   return count;
170 }
171
172 #ifdef INITIAL_DISCOVERY
173 /*------------------------------------------------------------------*/
174 /*
175  * Function irnet_get_discovery_log (self)
176  *
177  *    Query the content on the discovery log if not done
178  *
179  * This function query the current content of the discovery log
180  * at the startup of the event channel and save it in the internal struct.
181  */
182 static void
183 irnet_get_discovery_log(irnet_socket *  ap)
184 {
185   __u16         mask = irlmp_service_to_hint(S_LAN);
186
187   /* Ask IrLMP for the current discovery log */
188   ap->discoveries = irlmp_get_discoveries(&ap->disco_number, mask,
189                                           DISCOVERY_DEFAULT_SLOTS);
190
191   /* Check if the we got some results */
192   if(ap->discoveries == NULL)
193     ap->disco_number = -1;
194
195   DEBUG(CTRL_INFO, "Got the log (0x%p), size is %d\n",
196         ap->discoveries, ap->disco_number);
197 }
198
199 /*------------------------------------------------------------------*/
200 /*
201  * Function irnet_read_discovery_log (self, event)
202  *
203  *    Read the content on the discovery log
204  *
205  * This function dump the current content of the discovery log
206  * at the startup of the event channel.
207  * Return 1 if wrote an event on the control channel...
208  *
209  * State of the ap->disco_XXX variables :
210  * Socket creation :  discoveries = NULL ; disco_index = 0 ; disco_number = 0
211  * While reading :    discoveries = ptr  ; disco_index = X ; disco_number = Y
212  * After reading :    discoveries = NULL ; disco_index = Y ; disco_number = -1
213  */
214 static inline int
215 irnet_read_discovery_log(irnet_socket * ap,
216                          char *         event)
217 {
218   int           done_event = 0;
219
220   DENTER(CTRL_TRACE, "(ap=0x%p, event=0x%p)\n",
221          ap, event);
222
223   /* Test if we have some work to do or we have already finished */
224   if(ap->disco_number == -1)
225     {
226       DEBUG(CTRL_INFO, "Already done\n");
227       return 0;
228     }
229
230   /* Test if it's the first time and therefore we need to get the log */
231   if(ap->discoveries == NULL)
232     irnet_get_discovery_log(ap);
233
234   /* Check if we have more item to dump */
235   if(ap->disco_index < ap->disco_number)
236     {
237       /* Write an event */
238       sprintf(event, "Found %08x (%s) behind %08x {hints %02X-%02X}\n",
239               ap->discoveries[ap->disco_index].daddr,
240               ap->discoveries[ap->disco_index].info,
241               ap->discoveries[ap->disco_index].saddr,
242               ap->discoveries[ap->disco_index].hints[0],
243               ap->discoveries[ap->disco_index].hints[1]);
244       DEBUG(CTRL_INFO, "Writing discovery %d : %s\n",
245             ap->disco_index, ap->discoveries[ap->disco_index].info);
246
247       /* We have an event */
248       done_event = 1;
249       /* Next discovery */
250       ap->disco_index++;
251     }
252
253   /* Check if we have done the last item */
254   if(ap->disco_index >= ap->disco_number)
255     {
256       /* No more items : remove the log and signal termination */
257       DEBUG(CTRL_INFO, "Cleaning up log (0x%p)\n",
258             ap->discoveries);
259       if(ap->discoveries != NULL)
260         {
261           /* Cleanup our copy of the discovery log */
262           kfree(ap->discoveries);
263           ap->discoveries = NULL;
264         }
265       ap->disco_number = -1;
266     }
267
268   return done_event;
269 }
270 #endif /* INITIAL_DISCOVERY */
271
272 /*------------------------------------------------------------------*/
273 /*
274  * Read is used to get IrNET events
275  */
276 static inline ssize_t
277 irnet_ctrl_read(irnet_socket *  ap,
278                 struct file *   file,
279                 char __user *   buf,
280                 size_t          count)
281 {
282   DECLARE_WAITQUEUE(wait, current);
283   char          event[64];      /* Max event is 61 char */
284   ssize_t       ret = 0;
285
286   DENTER(CTRL_TRACE, "(ap=0x%p, count=%Zd)\n", ap, count);
287
288   /* Check if we can write an event out in one go */
289   DABORT(count < sizeof(event), -EOVERFLOW, CTRL_ERROR, "Buffer to small.\n");
290
291 #ifdef INITIAL_DISCOVERY
292   /* Check if we have read the log */
293   if(irnet_read_discovery_log(ap, event))
294     {
295       /* We have an event !!! Copy it to the user */
296       if(copy_to_user(buf, event, strlen(event)))
297         {
298           DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
299           return -EFAULT;
300         }
301
302       DEXIT(CTRL_TRACE, "\n");
303       return strlen(event);
304     }
305 #endif /* INITIAL_DISCOVERY */
306
307   /* Put ourselves on the wait queue to be woken up */
308   add_wait_queue(&irnet_events.rwait, &wait);
309   current->state = TASK_INTERRUPTIBLE;
310   for(;;)
311     {
312       /* If there is unread events */
313       ret = 0;
314       if(ap->event_index != irnet_events.index)
315         break;
316       ret = -EAGAIN;
317       if(file->f_flags & O_NONBLOCK)
318         break;
319       ret = -ERESTARTSYS;
320       if(signal_pending(current))
321         break;
322       /* Yield and wait to be woken up */
323       schedule();
324     }
325   current->state = TASK_RUNNING;
326   remove_wait_queue(&irnet_events.rwait, &wait);
327
328   /* Did we got it ? */
329   if(ret != 0)
330     {
331       /* No, return the error code */
332       DEXIT(CTRL_TRACE, " - ret %Zd\n", ret);
333       return ret;
334     }
335
336   /* Which event is it ? */
337   switch(irnet_events.log[ap->event_index].event)
338     {
339     case IRNET_DISCOVER:
340       sprintf(event, "Discovered %08x (%s) behind %08x {hints %02X-%02X}\n",
341               irnet_events.log[ap->event_index].daddr,
342               irnet_events.log[ap->event_index].name,
343               irnet_events.log[ap->event_index].saddr,
344               irnet_events.log[ap->event_index].hints.byte[0],
345               irnet_events.log[ap->event_index].hints.byte[1]);
346       break;
347     case IRNET_EXPIRE:
348       sprintf(event, "Expired %08x (%s) behind %08x {hints %02X-%02X}\n",
349               irnet_events.log[ap->event_index].daddr,
350               irnet_events.log[ap->event_index].name,
351               irnet_events.log[ap->event_index].saddr,
352               irnet_events.log[ap->event_index].hints.byte[0],
353               irnet_events.log[ap->event_index].hints.byte[1]);
354       break;
355     case IRNET_CONNECT_TO:
356       sprintf(event, "Connected to %08x (%s) on ppp%d\n",
357               irnet_events.log[ap->event_index].daddr,
358               irnet_events.log[ap->event_index].name,
359               irnet_events.log[ap->event_index].unit);
360       break;
361     case IRNET_CONNECT_FROM:
362       sprintf(event, "Connection from %08x (%s) on ppp%d\n",
363               irnet_events.log[ap->event_index].daddr,
364               irnet_events.log[ap->event_index].name,
365               irnet_events.log[ap->event_index].unit);
366       break;
367     case IRNET_REQUEST_FROM:
368       sprintf(event, "Request from %08x (%s) behind %08x\n",
369               irnet_events.log[ap->event_index].daddr,
370               irnet_events.log[ap->event_index].name,
371               irnet_events.log[ap->event_index].saddr);
372       break;
373     case IRNET_NOANSWER_FROM:
374       sprintf(event, "No-answer from %08x (%s) on ppp%d\n",
375               irnet_events.log[ap->event_index].daddr,
376               irnet_events.log[ap->event_index].name,
377               irnet_events.log[ap->event_index].unit);
378       break;
379     case IRNET_BLOCKED_LINK:
380       sprintf(event, "Blocked link with %08x (%s) on ppp%d\n",
381               irnet_events.log[ap->event_index].daddr,
382               irnet_events.log[ap->event_index].name,
383               irnet_events.log[ap->event_index].unit);
384       break;
385     case IRNET_DISCONNECT_FROM:
386       sprintf(event, "Disconnection from %08x (%s) on ppp%d\n",
387               irnet_events.log[ap->event_index].daddr,
388               irnet_events.log[ap->event_index].name,
389               irnet_events.log[ap->event_index].unit);
390       break;
391     case IRNET_DISCONNECT_TO:
392       sprintf(event, "Disconnected to %08x (%s)\n",
393               irnet_events.log[ap->event_index].daddr,
394               irnet_events.log[ap->event_index].name);
395       break;
396     default:
397       sprintf(event, "Bug\n");
398     }
399   /* Increment our event index */
400   ap->event_index = (ap->event_index + 1) % IRNET_MAX_EVENTS;
401
402   DEBUG(CTRL_INFO, "Event is :%s", event);
403
404   /* Copy it to the user */
405   if(copy_to_user(buf, event, strlen(event)))
406     {
407       DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
408       return -EFAULT;
409     }
410
411   DEXIT(CTRL_TRACE, "\n");
412   return strlen(event);
413 }
414
415 /*------------------------------------------------------------------*/
416 /*
417  * Poll : called when someone do a select on /dev/irnet.
418  * Just check if there are new events...
419  */
420 static inline unsigned int
421 irnet_ctrl_poll(irnet_socket *  ap,
422                 struct file *   file,
423                 poll_table *    wait)
424 {
425   unsigned int mask;
426
427   DENTER(CTRL_TRACE, "(ap=0x%p)\n", ap);
428
429   poll_wait(file, &irnet_events.rwait, wait);
430   mask = POLLOUT | POLLWRNORM;
431   /* If there is unread events */
432   if(ap->event_index != irnet_events.index)
433     mask |= POLLIN | POLLRDNORM;
434 #ifdef INITIAL_DISCOVERY
435   if(ap->disco_number != -1)
436     {
437       /* Test if it's the first time and therefore we need to get the log */
438       if(ap->discoveries == NULL)
439         irnet_get_discovery_log(ap);
440       /* Recheck */
441       if(ap->disco_number != -1)
442         mask |= POLLIN | POLLRDNORM;
443     }
444 #endif /* INITIAL_DISCOVERY */
445
446   DEXIT(CTRL_TRACE, " - mask=0x%X\n", mask);
447   return mask;
448 }
449
450
451 /*********************** FILESYSTEM CALLBACKS ***********************/
452 /*
453  * Implement the usual open, read, write functions that will be called
454  * by the file system when some action is performed on /dev/irnet.
455  * Most of those actions will in fact be performed by "pppd" or
456  * the control channel, we just act as a redirector...
457  */
458
459 /*------------------------------------------------------------------*/
460 /*
461  * Open : when somebody open /dev/irnet
462  * We basically create a new instance of irnet and initialise it.
463  */
464 static int
465 dev_irnet_open(struct inode *   inode,
466                struct file *    file)
467 {
468   struct irnet_socket * ap;
469   int                   err;
470
471   DENTER(FS_TRACE, "(file=0x%p)\n", file);
472
473 #ifdef SECURE_DEVIRNET
474   /* This could (should?) be enforced by the permissions on /dev/irnet. */
475   if(!capable(CAP_NET_ADMIN))
476     return -EPERM;
477 #endif /* SECURE_DEVIRNET */
478
479   /* Allocate a private structure for this IrNET instance */
480   ap = kzalloc(sizeof(*ap), GFP_KERNEL);
481   DABORT(ap == NULL, -ENOMEM, FS_ERROR, "Can't allocate struct irnet...\n");
482
483   /* initialize the irnet structure */
484   ap->file = file;
485
486   /* PPP channel setup */
487   ap->ppp_open = 0;
488   ap->chan.private = ap;
489   ap->chan.ops = &irnet_ppp_ops;
490   ap->chan.mtu = (2048 - TTP_MAX_HEADER - 2 - PPP_HDRLEN);
491   ap->chan.hdrlen = 2 + TTP_MAX_HEADER;         /* for A/C + Max IrDA hdr */
492   /* PPP parameters */
493   ap->mru = (2048 - TTP_MAX_HEADER - 2 - PPP_HDRLEN);
494   ap->xaccm[0] = ~0U;
495   ap->xaccm[3] = 0x60000000U;
496   ap->raccm = ~0U;
497
498   /* Setup the IrDA part... */
499   err = irda_irnet_create(ap);
500   if(err)
501     {
502       DERROR(FS_ERROR, "Can't setup IrDA link...\n");
503       kfree(ap);
504
505       return err;
506     }
507
508   /* For the control channel */
509   ap->event_index = irnet_events.index; /* Cancel all past events */
510
511   mutex_init(&ap->lock);
512
513   /* Put our stuff where we will be able to find it later */
514   file->private_data = ap;
515
516   DEXIT(FS_TRACE, " - ap=0x%p\n", ap);
517
518   return 0;
519 }
520
521
522 /*------------------------------------------------------------------*/
523 /*
524  * Close : when somebody close /dev/irnet
525  * Destroy the instance of /dev/irnet
526  */
527 static int
528 dev_irnet_close(struct inode *  inode,
529                 struct file *   file)
530 {
531   irnet_socket *        ap = file->private_data;
532
533   DENTER(FS_TRACE, "(file=0x%p, ap=0x%p)\n",
534          file, ap);
535   DABORT(ap == NULL, 0, FS_ERROR, "ap is NULL !!!\n");
536
537   /* Detach ourselves */
538   file->private_data = NULL;
539
540   /* Close IrDA stuff */
541   irda_irnet_destroy(ap);
542
543   /* Disconnect from the generic PPP layer if not already done */
544   if(ap->ppp_open)
545     {
546       DERROR(FS_ERROR, "Channel still registered - deregistering !\n");
547       ap->ppp_open = 0;
548       ppp_unregister_channel(&ap->chan);
549     }
550
551   kfree(ap);
552
553   DEXIT(FS_TRACE, "\n");
554   return 0;
555 }
556
557 /*------------------------------------------------------------------*/
558 /*
559  * Write does nothing.
560  * (we receive packet from ppp_generic through ppp_irnet_send())
561  */
562 static ssize_t
563 dev_irnet_write(struct file *   file,
564                 const char __user *buf,
565                 size_t          count,
566                 loff_t *        ppos)
567 {
568   irnet_socket *        ap = file->private_data;
569
570   DPASS(FS_TRACE, "(file=0x%p, ap=0x%p, count=%Zd)\n",
571         file, ap, count);
572   DABORT(ap == NULL, -ENXIO, FS_ERROR, "ap is NULL !!!\n");
573
574   /* If we are connected to ppp_generic, let it handle the job */
575   if(ap->ppp_open)
576     return -EAGAIN;
577   else
578     return irnet_ctrl_write(ap, buf, count);
579 }
580
581 /*------------------------------------------------------------------*/
582 /*
583  * Read doesn't do much either.
584  * (pppd poll us, but ultimately reads through /dev/ppp)
585  */
586 static ssize_t
587 dev_irnet_read(struct file *    file,
588                char __user *    buf,
589                size_t           count,
590                loff_t *         ppos)
591 {
592   irnet_socket *        ap = file->private_data;
593
594   DPASS(FS_TRACE, "(file=0x%p, ap=0x%p, count=%Zd)\n",
595         file, ap, count);
596   DABORT(ap == NULL, -ENXIO, FS_ERROR, "ap is NULL !!!\n");
597
598   /* If we are connected to ppp_generic, let it handle the job */
599   if(ap->ppp_open)
600     return -EAGAIN;
601   else
602     return irnet_ctrl_read(ap, file, buf, count);
603 }
604
605 /*------------------------------------------------------------------*/
606 /*
607  * Poll : called when someone do a select on /dev/irnet
608  */
609 static unsigned int
610 dev_irnet_poll(struct file *    file,
611                poll_table *     wait)
612 {
613   irnet_socket *        ap = file->private_data;
614   unsigned int          mask;
615
616   DENTER(FS_TRACE, "(file=0x%p, ap=0x%p)\n",
617          file, ap);
618
619   mask = POLLOUT | POLLWRNORM;
620   DABORT(ap == NULL, mask, FS_ERROR, "ap is NULL !!!\n");
621
622   /* If we are connected to ppp_generic, let it handle the job */
623   if(!ap->ppp_open)
624     mask |= irnet_ctrl_poll(ap, file, wait);
625
626   DEXIT(FS_TRACE, " - mask=0x%X\n", mask);
627   return mask;
628 }
629
630 /*------------------------------------------------------------------*/
631 /*
632  * IOCtl : Called when someone does some ioctls on /dev/irnet
633  * This is the way pppd configure us and control us while the PPP
634  * instance is active.
635  */
636 static long
637 dev_irnet_ioctl(
638                 struct file *   file,
639                 unsigned int    cmd,
640                 unsigned long   arg)
641 {
642   irnet_socket *        ap = file->private_data;
643   int                   err;
644   int                   val;
645   void __user *argp = (void __user *)arg;
646
647   DENTER(FS_TRACE, "(file=0x%p, ap=0x%p, cmd=0x%X)\n",
648          file, ap, cmd);
649
650   /* Basic checks... */
651   DASSERT(ap != NULL, -ENXIO, PPP_ERROR, "ap is NULL...\n");
652 #ifdef SECURE_DEVIRNET
653   if(!capable(CAP_NET_ADMIN))
654     return -EPERM;
655 #endif /* SECURE_DEVIRNET */
656
657   err = -EFAULT;
658   switch(cmd)
659     {
660       /* Set discipline (should be N_SYNC_PPP or N_TTY) */
661     case TIOCSETD:
662       if(get_user(val, (int __user *)argp))
663         break;
664       if((val == N_SYNC_PPP) || (val == N_PPP))
665         {
666           DEBUG(FS_INFO, "Entering PPP discipline.\n");
667           /* PPP channel setup (ap->chan in configured in dev_irnet_open())*/
668           if (mutex_lock_interruptible(&ap->lock))
669                   return -EINTR;
670
671           err = ppp_register_channel(&ap->chan);
672           if(err == 0)
673             {
674               /* Our ppp side is active */
675               ap->ppp_open = 1;
676
677               DEBUG(FS_INFO, "Trying to establish a connection.\n");
678               /* Setup the IrDA link now - may fail... */
679               irda_irnet_connect(ap);
680             }
681           else
682             DERROR(FS_ERROR, "Can't setup PPP channel...\n");
683
684           mutex_unlock(&ap->lock);
685         }
686       else
687         {
688           /* In theory, should be N_TTY */
689           DEBUG(FS_INFO, "Exiting PPP discipline.\n");
690           /* Disconnect from the generic PPP layer */
691           if (mutex_lock_interruptible(&ap->lock))
692                   return -EINTR;
693
694           if(ap->ppp_open)
695             {
696               ap->ppp_open = 0;
697               ppp_unregister_channel(&ap->chan);
698             }
699           else
700             DERROR(FS_ERROR, "Channel not registered !\n");
701           err = 0;
702
703           mutex_unlock(&ap->lock);
704         }
705       break;
706
707       /* Query PPP channel and unit number */
708     case PPPIOCGCHAN:
709       if (mutex_lock_interruptible(&ap->lock))
710               return -EINTR;
711
712       if(ap->ppp_open && !put_user(ppp_channel_index(&ap->chan),
713                                                 (int __user *)argp))
714         err = 0;
715
716       mutex_unlock(&ap->lock);
717       break;
718     case PPPIOCGUNIT:
719       if (mutex_lock_interruptible(&ap->lock))
720               return -EINTR;
721
722       if(ap->ppp_open && !put_user(ppp_unit_number(&ap->chan),
723                                                 (int __user *)argp))
724         err = 0;
725
726       mutex_unlock(&ap->lock);
727       break;
728
729       /* All these ioctls can be passed both directly and from ppp_generic,
730        * so we just deal with them in one place...
731        */
732     case PPPIOCGFLAGS:
733     case PPPIOCSFLAGS:
734     case PPPIOCGASYNCMAP:
735     case PPPIOCSASYNCMAP:
736     case PPPIOCGRASYNCMAP:
737     case PPPIOCSRASYNCMAP:
738     case PPPIOCGXASYNCMAP:
739     case PPPIOCSXASYNCMAP:
740     case PPPIOCGMRU:
741     case PPPIOCSMRU:
742       DEBUG(FS_INFO, "Standard PPP ioctl.\n");
743       if(!capable(CAP_NET_ADMIN))
744         err = -EPERM;
745       else {
746         if (mutex_lock_interruptible(&ap->lock))
747               return -EINTR;
748
749         err = ppp_irnet_ioctl(&ap->chan, cmd, arg);
750
751         mutex_unlock(&ap->lock);
752       }
753       break;
754
755       /* TTY IOCTLs : Pretend that we are a tty, to keep pppd happy */
756       /* Get termios */
757     case TCGETS:
758       DEBUG(FS_INFO, "Get termios.\n");
759       if (mutex_lock_interruptible(&ap->lock))
760               return -EINTR;
761
762 #ifndef TCGETS2
763       if(!kernel_termios_to_user_termios((struct termios __user *)argp, &ap->termios))
764         err = 0;
765 #else
766       if(kernel_termios_to_user_termios_1((struct termios __user *)argp, &ap->termios))
767         err = 0;
768 #endif
769
770       mutex_unlock(&ap->lock);
771       break;
772       /* Set termios */
773     case TCSETSF:
774       DEBUG(FS_INFO, "Set termios.\n");
775       if (mutex_lock_interruptible(&ap->lock))
776               return -EINTR;
777
778 #ifndef TCGETS2
779       if(!user_termios_to_kernel_termios(&ap->termios, (struct termios __user *)argp))
780         err = 0;
781 #else
782       if(!user_termios_to_kernel_termios_1(&ap->termios, (struct termios __user *)argp))
783         err = 0;
784 #endif
785
786       mutex_unlock(&ap->lock);
787       break;
788
789       /* Set DTR/RTS */
790     case TIOCMBIS:
791     case TIOCMBIC:
792       /* Set exclusive/non-exclusive mode */
793     case TIOCEXCL:
794     case TIOCNXCL:
795       DEBUG(FS_INFO, "TTY compatibility.\n");
796       err = 0;
797       break;
798
799     case TCGETA:
800       DEBUG(FS_INFO, "TCGETA\n");
801       break;
802
803     case TCFLSH:
804       DEBUG(FS_INFO, "TCFLSH\n");
805       /* Note : this will flush buffers in PPP, so it *must* be done
806        * We should also worry that we don't accept junk here and that
807        * we get rid of our own buffers */
808 #ifdef FLUSH_TO_PPP
809       if (mutex_lock_interruptible(&ap->lock))
810               return -EINTR;
811       ppp_output_wakeup(&ap->chan);
812       mutex_unlock(&ap->lock);
813 #endif /* FLUSH_TO_PPP */
814       err = 0;
815       break;
816
817     case FIONREAD:
818       DEBUG(FS_INFO, "FIONREAD\n");
819       val = 0;
820       if(put_user(val, (int __user *)argp))
821         break;
822       err = 0;
823       break;
824
825     default:
826       DERROR(FS_ERROR, "Unsupported ioctl (0x%X)\n", cmd);
827       err = -ENOTTY;
828     }
829
830   DEXIT(FS_TRACE, " - err = 0x%X\n", err);
831   return err;
832 }
833
834 /************************** PPP CALLBACKS **************************/
835 /*
836  * This are the functions that the generic PPP driver in the kernel
837  * will call to communicate to us.
838  */
839
840 /*------------------------------------------------------------------*/
841 /*
842  * Prepare the ppp frame for transmission over the IrDA socket.
843  * We make sure that the header space is enough, and we change ppp header
844  * according to flags passed by pppd.
845  * This is not a callback, but just a helper function used in ppp_irnet_send()
846  */
847 static inline struct sk_buff *
848 irnet_prepare_skb(irnet_socket *        ap,
849                   struct sk_buff *      skb)
850 {
851   unsigned char *       data;
852   int                   proto;          /* PPP protocol */
853   int                   islcp;          /* Protocol == LCP */
854   int                   needaddr;       /* Need PPP address */
855
856   DENTER(PPP_TRACE, "(ap=0x%p, skb=0x%p)\n",
857          ap, skb);
858
859   /* Extract PPP protocol from the frame */
860   data  = skb->data;
861   proto = (data[0] << 8) + data[1];
862
863   /* LCP packets with codes between 1 (configure-request)
864    * and 7 (code-reject) must be sent as though no options
865    * have been negotiated. */
866   islcp = (proto == PPP_LCP) && (1 <= data[2]) && (data[2] <= 7);
867
868   /* compress protocol field if option enabled */
869   if((data[0] == 0) && (ap->flags & SC_COMP_PROT) && (!islcp))
870     skb_pull(skb,1);
871
872   /* Check if we need address/control fields */
873   needaddr = 2*((ap->flags & SC_COMP_AC) == 0 || islcp);
874
875   /* Is the skb headroom large enough to contain all IrDA-headers? */
876   if((skb_headroom(skb) < (ap->max_header_size + needaddr)) ||
877       (skb_shared(skb)))
878     {
879       struct sk_buff *  new_skb;
880
881       DEBUG(PPP_INFO, "Reallocating skb\n");
882
883       /* Create a new skb */
884       new_skb = skb_realloc_headroom(skb, ap->max_header_size + needaddr);
885
886       /* We have to free the original skb anyway */
887       dev_kfree_skb(skb);
888
889       /* Did the realloc succeed ? */
890       DABORT(new_skb == NULL, NULL, PPP_ERROR, "Could not realloc skb\n");
891
892       /* Use the new skb instead */
893       skb = new_skb;
894     }
895
896   /* prepend address/control fields if necessary */
897   if(needaddr)
898     {
899       skb_push(skb, 2);
900       skb->data[0] = PPP_ALLSTATIONS;
901       skb->data[1] = PPP_UI;
902     }
903
904   DEXIT(PPP_TRACE, "\n");
905
906   return skb;
907 }
908
909 /*------------------------------------------------------------------*/
910 /*
911  * Send a packet to the peer over the IrTTP connection.
912  * Returns 1 iff the packet was accepted.
913  * Returns 0 iff packet was not consumed.
914  * If the packet was not accepted, we will call ppp_output_wakeup
915  * at some later time to reactivate flow control in ppp_generic.
916  */
917 static int
918 ppp_irnet_send(struct ppp_channel *     chan,
919                struct sk_buff *         skb)
920 {
921   irnet_socket *        self = (struct irnet_socket *) chan->private;
922   int                   ret;
923
924   DENTER(PPP_TRACE, "(channel=0x%p, ap/self=0x%p)\n",
925          chan, self);
926
927   /* Check if things are somewhat valid... */
928   DASSERT(self != NULL, 0, PPP_ERROR, "Self is NULL !!!\n");
929
930   /* Check if we are connected */
931   if(!(test_bit(0, &self->ttp_open)))
932     {
933 #ifdef CONNECT_IN_SEND
934       /* Let's try to connect one more time... */
935       /* Note : we won't be connected after this call, but we should be
936        * ready for next packet... */
937       /* If we are already connecting, this will fail */
938       irda_irnet_connect(self);
939 #endif /* CONNECT_IN_SEND */
940
941       DEBUG(PPP_INFO, "IrTTP not ready ! (%ld-%ld)\n",
942             self->ttp_open, self->ttp_connect);
943
944       /* Note : we can either drop the packet or block the packet.
945        *
946        * Blocking the packet allow us a better connection time,
947        * because by calling ppp_output_wakeup() we can have
948        * ppp_generic resending the LCP request immediately to us,
949        * rather than waiting for one of pppd periodic transmission of
950        * LCP request.
951        *
952        * On the other hand, if we block all packet, all those periodic
953        * transmissions of pppd accumulate in ppp_generic, creating a
954        * backlog of LCP request. When we eventually connect later on,
955        * we have to transmit all this backlog before we can connect
956        * proper (if we don't timeout before).
957        *
958        * The current strategy is as follow :
959        * While we are attempting to connect, we block packets to get
960        * a better connection time.
961        * If we fail to connect, we drain the queue and start dropping packets
962        */
963 #ifdef BLOCK_WHEN_CONNECT
964       /* If we are attempting to connect */
965       if(test_bit(0, &self->ttp_connect))
966         {
967           /* Blocking packet, ppp_generic will retry later */
968           return 0;
969         }
970 #endif /* BLOCK_WHEN_CONNECT */
971
972       /* Dropping packet, pppd will retry later */
973       dev_kfree_skb(skb);
974       return 1;
975     }
976
977   /* Check if the queue can accept any packet, otherwise block */
978   if(self->tx_flow != FLOW_START)
979     DRETURN(0, PPP_INFO, "IrTTP queue full (%d skbs)...\n",
980             skb_queue_len(&self->tsap->tx_queue));
981
982   /* Prepare ppp frame for transmission */
983   skb = irnet_prepare_skb(self, skb);
984   DABORT(skb == NULL, 1, PPP_ERROR, "Prepare skb for Tx failed.\n");
985
986   /* Send the packet to IrTTP */
987   ret = irttp_data_request(self->tsap, skb);
988   if(ret < 0)
989     {
990       /*
991        * > IrTTPs tx queue is full, so we just have to
992        * > drop the frame! You might think that we should
993        * > just return -1 and don't deallocate the frame,
994        * > but that is dangerous since it's possible that
995        * > we have replaced the original skb with a new
996        * > one with larger headroom, and that would really
997        * > confuse do_dev_queue_xmit() in dev.c! I have
998        * > tried :-) DB
999        * Correction : we verify the flow control above (self->tx_flow),
1000        * so we come here only if IrTTP doesn't like the packet (empty,
1001        * too large, IrTTP not connected). In those rare cases, it's ok
1002        * to drop it, we don't want to see it here again...
1003        * Jean II
1004        */
1005       DERROR(PPP_ERROR, "IrTTP doesn't like this packet !!! (0x%X)\n", ret);
1006       /* irttp_data_request already free the packet */
1007     }
1008
1009   DEXIT(PPP_TRACE, "\n");
1010   return 1;     /* Packet has been consumed */
1011 }
1012
1013 /*------------------------------------------------------------------*/
1014 /*
1015  * Take care of the ioctls that ppp_generic doesn't want to deal with...
1016  * Note : we are also called from dev_irnet_ioctl().
1017  */
1018 static int
1019 ppp_irnet_ioctl(struct ppp_channel *    chan,
1020                 unsigned int            cmd,
1021                 unsigned long           arg)
1022 {
1023   irnet_socket *        ap = (struct irnet_socket *) chan->private;
1024   int                   err;
1025   int                   val;
1026   u32                   accm[8];
1027   void __user *argp = (void __user *)arg;
1028
1029   DENTER(PPP_TRACE, "(channel=0x%p, ap=0x%p, cmd=0x%X)\n",
1030          chan, ap, cmd);
1031
1032   /* Basic checks... */
1033   DASSERT(ap != NULL, -ENXIO, PPP_ERROR, "ap is NULL...\n");
1034
1035   err = -EFAULT;
1036   switch(cmd)
1037     {
1038       /* PPP flags */
1039     case PPPIOCGFLAGS:
1040       val = ap->flags | ap->rbits;
1041       if(put_user(val, (int __user *) argp))
1042         break;
1043       err = 0;
1044       break;
1045     case PPPIOCSFLAGS:
1046       if(get_user(val, (int __user *) argp))
1047         break;
1048       ap->flags = val & ~SC_RCV_BITS;
1049       ap->rbits = val & SC_RCV_BITS;
1050       err = 0;
1051       break;
1052
1053       /* Async map stuff - all dummy to please pppd */
1054     case PPPIOCGASYNCMAP:
1055       if(put_user(ap->xaccm[0], (u32 __user *) argp))
1056         break;
1057       err = 0;
1058       break;
1059     case PPPIOCSASYNCMAP:
1060       if(get_user(ap->xaccm[0], (u32 __user *) argp))
1061         break;
1062       err = 0;
1063       break;
1064     case PPPIOCGRASYNCMAP:
1065       if(put_user(ap->raccm, (u32 __user *) argp))
1066         break;
1067       err = 0;
1068       break;
1069     case PPPIOCSRASYNCMAP:
1070       if(get_user(ap->raccm, (u32 __user *) argp))
1071         break;
1072       err = 0;
1073       break;
1074     case PPPIOCGXASYNCMAP:
1075       if(copy_to_user(argp, ap->xaccm, sizeof(ap->xaccm)))
1076         break;
1077       err = 0;
1078       break;
1079     case PPPIOCSXASYNCMAP:
1080       if(copy_from_user(accm, argp, sizeof(accm)))
1081         break;
1082       accm[2] &= ~0x40000000U;          /* can't escape 0x5e */
1083       accm[3] |= 0x60000000U;           /* must escape 0x7d, 0x7e */
1084       memcpy(ap->xaccm, accm, sizeof(ap->xaccm));
1085       err = 0;
1086       break;
1087
1088       /* Max PPP frame size */
1089     case PPPIOCGMRU:
1090       if(put_user(ap->mru, (int __user *) argp))
1091         break;
1092       err = 0;
1093       break;
1094     case PPPIOCSMRU:
1095       if(get_user(val, (int __user *) argp))
1096         break;
1097       if(val < PPP_MRU)
1098         val = PPP_MRU;
1099       ap->mru = val;
1100       err = 0;
1101       break;
1102
1103     default:
1104       DEBUG(PPP_INFO, "Unsupported ioctl (0x%X)\n", cmd);
1105       err = -ENOIOCTLCMD;
1106     }
1107
1108   DEXIT(PPP_TRACE, " - err = 0x%X\n", err);
1109   return err;
1110 }
1111
1112 /************************** INITIALISATION **************************/
1113 /*
1114  * Module initialisation and all that jazz...
1115  */
1116
1117 /*------------------------------------------------------------------*/
1118 /*
1119  * Hook our device callbacks in the filesystem, to connect our code
1120  * to /dev/irnet
1121  */
1122 static inline int __init
1123 ppp_irnet_init(void)
1124 {
1125   int err = 0;
1126
1127   DENTER(MODULE_TRACE, "()\n");
1128
1129   /* Allocate ourselves as a minor in the misc range */
1130   err = misc_register(&irnet_misc_device);
1131
1132   DEXIT(MODULE_TRACE, "\n");
1133   return err;
1134 }
1135
1136 /*------------------------------------------------------------------*/
1137 /*
1138  * Cleanup at exit...
1139  */
1140 static inline void __exit
1141 ppp_irnet_cleanup(void)
1142 {
1143   DENTER(MODULE_TRACE, "()\n");
1144
1145   /* De-allocate /dev/irnet minor in misc range */
1146   misc_deregister(&irnet_misc_device);
1147
1148   DEXIT(MODULE_TRACE, "\n");
1149 }
1150
1151 /*------------------------------------------------------------------*/
1152 /*
1153  * Module main entry point
1154  */
1155 static int __init
1156 irnet_init(void)
1157 {
1158   int err;
1159
1160   /* Initialise both parts... */
1161   err = irda_irnet_init();
1162   if(!err)
1163     err = ppp_irnet_init();
1164   return err;
1165 }
1166
1167 /*------------------------------------------------------------------*/
1168 /*
1169  * Module exit
1170  */
1171 static void __exit
1172 irnet_cleanup(void)
1173 {
1174   irda_irnet_cleanup();
1175   ppp_irnet_cleanup();
1176 }
1177
1178 /*------------------------------------------------------------------*/
1179 /*
1180  * Module magic
1181  */
1182 module_init(irnet_init);
1183 module_exit(irnet_cleanup);
1184 MODULE_AUTHOR("Jean Tourrilhes <jt@hpl.hp.com>");
1185 MODULE_DESCRIPTION("IrNET : Synchronous PPP over IrDA");
1186 MODULE_LICENSE("GPL");
1187 MODULE_ALIAS_CHARDEV(10, 187);