import of ftp.dlink.com/GPL/DSMG-600_reB/ppclinux.tar.gz
[linux-2.4.21-pre4.git] / net / irda / af_irda.c
1 /*********************************************************************
2  *                
3  * Filename:      af_irda.c
4  * Version:       0.9
5  * Description:   IrDA sockets implementation
6  * Status:        Stable
7  * Author:        Dag Brattli <dagb@cs.uit.no>
8  * Created at:    Sun May 31 10:12:43 1998
9  * Modified at:   Sat Dec 25 21:10:23 1999
10  * Modified by:   Dag Brattli <dag@brattli.net>
11  * Sources:       af_netroom.c, af_ax25.c, af_rose.c, af_x25.c etc.
12  * 
13  *     Copyright (c) 1999 Dag Brattli <dagb@cs.uit.no>
14  *     Copyright (c) 1999-2001 Jean Tourrilhes <jt@hpl.hp.com>
15  *     All Rights Reserved.
16  *
17  *     This program is free software; you can redistribute it and/or 
18  *     modify it under the terms of the GNU General Public License as 
19  *     published by the Free Software Foundation; either version 2 of 
20  *     the License, or (at your option) any later version.
21  * 
22  *     This program is distributed in the hope that it will be useful,
23  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
24  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25  *     GNU General Public License for more details.
26  * 
27  *     You should have received a copy of the GNU General Public License 
28  *     along with this program; if not, write to the Free Software 
29  *     Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
30  *     MA 02111-1307 USA
31  *
32  *     Linux-IrDA now supports four different types of IrDA sockets:
33  *
34  *     o SOCK_STREAM:    TinyTP connections with SAR disabled. The
35  *                       max SDU size is 0 for conn. of this type
36  *     o SOCK_SEQPACKET: TinyTP connections with SAR enabled. TTP may 
37  *                       fragment the messages, but will preserve
38  *                       the message boundaries
39  *     o SOCK_DGRAM:     IRDAPROTO_UNITDATA: TinyTP connections with Unitdata 
40  *                       (unreliable) transfers
41  *                       IRDAPROTO_ULTRA: Connectionless and unreliable data
42  *     
43  ********************************************************************/
44
45 #include <linux/config.h>
46 #include <linux/module.h>
47 #include <linux/types.h>
48 #include <linux/socket.h>
49 #include <linux/sockios.h>
50 #include <linux/init.h>
51 #include <linux/if_arp.h>
52 #include <linux/net.h>
53 #include <linux/irda.h>
54 #include <linux/poll.h>
55
56 #include <asm/uaccess.h>
57
58 #include <net/sock.h>
59
60 #include <net/irda/irda.h>
61 #include <net/irda/iriap.h>
62 #include <net/irda/irias_object.h>
63 #include <net/irda/irlmp.h>
64 #include <net/irda/irttp.h>
65 #include <net/irda/discovery.h>
66
67 extern int  irda_init(void);
68 extern void irda_cleanup(void);
69 extern int  irlap_driver_rcv(struct sk_buff *, struct net_device *, 
70                              struct packet_type *);
71
72 static int irda_create(struct socket *sock, int protocol);
73
74 static struct proto_ops irda_stream_ops;
75 static struct proto_ops irda_seqpacket_ops;
76 static struct proto_ops irda_dgram_ops;
77
78 #ifdef CONFIG_IRDA_ULTRA
79 static struct proto_ops irda_ultra_ops;
80 #define ULTRA_MAX_DATA 382
81 #endif /* CONFIG_IRDA_ULTRA */
82
83 #define IRDA_MAX_HEADER (TTP_MAX_HEADER)
84
85 #ifdef CONFIG_IRDA_DEBUG
86 __u32 irda_debug = IRDA_DEBUG_LEVEL;
87 #endif
88
89 /*
90  * Function irda_data_indication (instance, sap, skb)
91  *
92  *    Received some data from TinyTP. Just queue it on the receive queue
93  *
94  */
95 static int irda_data_indication(void *instance, void *sap, struct sk_buff *skb)
96 {
97         struct irda_sock *self;
98         struct sock *sk;
99         int err;
100
101         IRDA_DEBUG(3, __FUNCTION__ "()\n");
102
103         self = (struct irda_sock *) instance;
104         ASSERT(self != NULL, return -1;);
105
106         sk = self->sk;
107         ASSERT(sk != NULL, return -1;);
108
109         err = sock_queue_rcv_skb(sk, skb);
110         if (err) {
111                 IRDA_DEBUG(1, __FUNCTION__ "(), error: no more mem!\n");
112                 self->rx_flow = FLOW_STOP;
113
114                 /* When we return error, TTP will need to requeue the skb */
115                 return err;
116         }
117
118         return 0;
119 }
120
121 /*
122  * Function irda_disconnect_indication (instance, sap, reason, skb)
123  *
124  *    Connection has been closed. Check reason to find out why
125  *
126  */
127 static void irda_disconnect_indication(void *instance, void *sap, 
128                                        LM_REASON reason, struct sk_buff *skb)
129 {
130         struct irda_sock *self;
131         struct sock *sk;
132
133         self = (struct irda_sock *) instance;
134
135         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
136
137         /* Don't care about it, but let's not leak it */
138         if(skb)
139                 dev_kfree_skb(skb);
140
141         sk = self->sk;
142         if (sk == NULL)
143                 return;
144
145         /* Prevent race conditions with irda_release() and irda_shutdown() */
146         if ((!sk->dead) && (sk->state != TCP_CLOSE)) {
147                 sk->state     = TCP_CLOSE;
148                 sk->err       = ECONNRESET;
149                 sk->shutdown |= SEND_SHUTDOWN;
150
151                 sk->state_change(sk);
152                 sk->dead = 1;   /* Uh-oh... Should use sock_orphan ? */
153
154                 /* Close our TSAP.
155                  * If we leave it open, IrLMP put it back into the list of
156                  * unconnected LSAPs. The problem is that any incoming request
157                  * can then be matched to this socket (and it will be, because
158                  * it is at the head of the list). This would prevent any
159                  * listening socket waiting on the same TSAP to get those
160                  * requests. Some apps forget to close sockets, or hang to it
161                  * a bit too long, so we may stay in this dead state long
162                  * enough to be noticed...
163                  * Note : all socket function do check sk->state, so we are
164                  * safe...
165                  * Jean II
166                  */
167                 if (self->tsap) {
168                         irttp_close_tsap(self->tsap);
169                         self->tsap = NULL;
170                 }
171         }
172
173         /* Note : once we are there, there is not much you want to do
174          * with the socket anymore, apart from closing it.
175          * For example, bind() and connect() won't reset sk->err,
176          * sk->shutdown and sk->dead to valid values...
177          * Jean II
178          */
179 }
180
181 /*
182  * Function irda_connect_confirm (instance, sap, qos, max_sdu_size, skb)
183  *
184  *    Connections has been confirmed by the remote device
185  *
186  */
187 static void irda_connect_confirm(void *instance, void *sap, 
188                                  struct qos_info *qos,
189                                  __u32 max_sdu_size, __u8 max_header_size, 
190                                  struct sk_buff *skb)
191 {
192         struct irda_sock *self;
193         struct sock *sk;
194
195         self = (struct irda_sock *) instance;
196
197         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
198
199         sk = self->sk;
200         if (sk == NULL)
201                 return;
202
203         /* How much header space do we need to reserve */
204         self->max_header_size = max_header_size;
205
206         /* IrTTP max SDU size in transmit direction */
207         self->max_sdu_size_tx = max_sdu_size;
208
209         /* Find out what the largest chunk of data that we can transmit is */
210         switch (sk->type) {
211         case SOCK_STREAM:
212                 if (max_sdu_size != 0) {
213                         ERROR(__FUNCTION__ "(), max_sdu_size must be 0\n");
214                         return;
215                 }
216                 self->max_data_size = irttp_get_max_seg_size(self->tsap);
217                 break;
218         case SOCK_SEQPACKET:
219                 if (max_sdu_size == 0) {
220                         ERROR(__FUNCTION__ "(), max_sdu_size cannot be 0\n");
221                         return;
222                 }
223                 self->max_data_size = max_sdu_size;
224                 break;
225         default:
226                 self->max_data_size = irttp_get_max_seg_size(self->tsap);
227         };
228
229         IRDA_DEBUG(2, __FUNCTION__ "(), max_data_size=%d\n", 
230                    self->max_data_size);
231
232         memcpy(&self->qos_tx, qos, sizeof(struct qos_info));
233         dev_kfree_skb(skb);
234         // Should be ??? skb_queue_tail(&sk->receive_queue, skb);
235
236         /* We are now connected! */
237         sk->state = TCP_ESTABLISHED;
238         sk->state_change(sk);
239 }
240
241 /*
242  * Function irda_connect_indication(instance, sap, qos, max_sdu_size, userdata)
243  *
244  *    Incoming connection
245  *
246  */
247 static void irda_connect_indication(void *instance, void *sap, 
248                                     struct qos_info *qos, __u32 max_sdu_size,
249                                     __u8 max_header_size, struct sk_buff *skb)
250 {
251         struct irda_sock *self;
252         struct sock *sk;
253
254         self = (struct irda_sock *) instance;
255
256         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
257
258         sk = self->sk;
259         if (sk == NULL)
260                 return;
261
262         /* How much header space do we need to reserve */
263         self->max_header_size = max_header_size;
264
265         /* IrTTP max SDU size in transmit direction */
266         self->max_sdu_size_tx = max_sdu_size;   
267
268         /* Find out what the largest chunk of data that we can transmit is */
269         switch (sk->type) {
270         case SOCK_STREAM:
271                 if (max_sdu_size != 0) {
272                         ERROR(__FUNCTION__ "(), max_sdu_size must be 0\n");
273                         return;
274                 }
275                 self->max_data_size = irttp_get_max_seg_size(self->tsap);
276                 break;
277         case SOCK_SEQPACKET:
278                 if (max_sdu_size == 0) {
279                         ERROR(__FUNCTION__ "(), max_sdu_size cannot be 0\n");
280                         return;
281                 }
282                 self->max_data_size = max_sdu_size;
283                 break;
284         default:
285                 self->max_data_size = irttp_get_max_seg_size(self->tsap);
286         };
287
288         IRDA_DEBUG(2, __FUNCTION__ "(), max_data_size=%d\n", 
289                    self->max_data_size);
290
291         memcpy(&self->qos_tx, qos, sizeof(struct qos_info));
292         
293         skb_queue_tail(&sk->receive_queue, skb);
294         sk->state_change(sk);
295 }
296
297 /*
298  * Function irda_connect_response (handle)
299  *
300  *    Accept incoming connection
301  *
302  */
303 void irda_connect_response(struct irda_sock *self)
304 {
305         struct sk_buff *skb;
306
307         IRDA_DEBUG(2, __FUNCTION__ "()\n");
308
309         ASSERT(self != NULL, return;);
310
311         skb = dev_alloc_skb(64);
312         if (skb == NULL) {
313                 IRDA_DEBUG(0, __FUNCTION__ "() Unable to allocate sk_buff!\n");
314                 return;
315         }
316
317         /* Reserve space for MUX_CONTROL and LAP header */
318         skb_reserve(skb, IRDA_MAX_HEADER);
319
320         irttp_connect_response(self->tsap, self->max_sdu_size_rx, skb);
321 }
322
323 /*
324  * Function irda_flow_indication (instance, sap, flow)
325  *
326  *    Used by TinyTP to tell us if it can accept more data or not
327  *
328  */
329 static void irda_flow_indication(void *instance, void *sap, LOCAL_FLOW flow) 
330 {
331         struct irda_sock *self;
332         struct sock *sk;
333
334         IRDA_DEBUG(2, __FUNCTION__ "()\n");
335         
336         self = (struct irda_sock *) instance;
337         ASSERT(self != NULL, return;);
338
339         sk = self->sk;
340         ASSERT(sk != NULL, return;);
341         
342         switch (flow) {
343         case FLOW_STOP:
344                 IRDA_DEBUG(1, __FUNCTION__ "(), IrTTP wants us to slow down\n");
345                 self->tx_flow = flow;
346                 break;
347         case FLOW_START:
348                 self->tx_flow = flow;
349                 IRDA_DEBUG(1, __FUNCTION__ 
350                            "(), IrTTP wants us to start again\n");
351                 wake_up_interruptible(sk->sleep);
352                 break;
353         default:
354                 IRDA_DEBUG( 0, __FUNCTION__ "(), Unknown flow command!\n");
355                 /* Unknown flow command, better stop */
356                 self->tx_flow = flow;
357                 break;
358         }
359 }
360
361 /*
362  * Function irda_getvalue_confirm (obj_id, value, priv)
363  *
364  *    Got answer from remote LM-IAS, just pass object to requester...
365  *
366  * Note : duplicate from above, but we need our own version that
367  * doesn't touch the dtsap_sel and save the full value structure...
368  */
369 static void irda_getvalue_confirm(int result, __u16 obj_id, 
370                                           struct ias_value *value, void *priv)
371 {
372         struct irda_sock *self;
373         
374         self = (struct irda_sock *) priv;
375         if (!self) {
376                 WARNING(__FUNCTION__ "(), lost myself!\n");
377                 return;
378         }
379
380         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
381
382         /* We probably don't need to make any more queries */
383         iriap_close(self->iriap);
384         self->iriap = NULL;
385
386         /* Check if request succeeded */
387         if (result != IAS_SUCCESS) {
388                 IRDA_DEBUG(1, __FUNCTION__ "(), IAS query failed! (%d)\n",
389                            result);
390
391                 self->errno = result;   /* We really need it later */
392
393                 /* Wake up any processes waiting for result */
394                 wake_up_interruptible(&self->query_wait);
395
396                 return;
397         }
398
399         /* Pass the object to the caller (so the caller must delete it) */
400         self->ias_result = value;
401         self->errno = 0;
402
403         /* Wake up any processes waiting for result */
404         wake_up_interruptible(&self->query_wait);
405 }
406
407 /*
408  * Function irda_selective_discovery_indication (discovery)
409  *
410  *    Got a selective discovery indication from IrLMP.
411  *
412  * IrLMP is telling us that this node is matching our hint bit
413  * filter. Check if it's a newly discovered node (or if node changed its
414  * hint bits), and then wake up any process waiting for answer...
415  */
416 static void irda_selective_discovery_indication(discovery_t *discovery,
417                                                 DISCOVERY_MODE mode,
418                                                 void *priv)
419 {
420         struct irda_sock *self;
421         
422         IRDA_DEBUG(2, __FUNCTION__ "()\n");
423
424         self = (struct irda_sock *) priv;
425         if (!self) {
426                 WARNING(__FUNCTION__ "(), lost myself!\n");
427                 return;
428         }
429
430         /* Check if node is discovered is a new one or an old one.
431          * We check when how long ago this node was discovered, with a
432          * coarse timeout (we may miss some discovery events or be delayed).
433          * Note : by doing this test here, we avoid waking up a process ;-)
434          */
435         if((jiffies - discovery->first_timestamp) >
436            (sysctl_discovery_timeout * HZ)) {
437                 return;         /* Too old, not interesting -> goodbye */
438         }
439
440         /* Pass parameter to the caller */
441         self->cachediscovery = discovery;
442
443         /* Wake up process if its waiting for device to be discovered */
444         wake_up_interruptible(&self->query_wait);
445 }
446
447 /*
448  * Function irda_discovery_timeout (priv)
449  *
450  *    Timeout in the selective discovery process
451  *
452  * We were waiting for a node to be discovered, but nothing has come up
453  * so far. Wake up the user and tell him that we failed...
454  */
455 static void irda_discovery_timeout(u_long priv)
456 {
457         struct irda_sock *self;
458         
459         IRDA_DEBUG(2, __FUNCTION__ "()\n");
460
461         self = (struct irda_sock *) priv;
462         ASSERT(self != NULL, return;);
463
464         /* Nothing for the caller */
465         self->cachelog = NULL;
466         self->cachediscovery = NULL;
467         self->errno = -ETIME;
468
469         /* Wake up process if its still waiting... */
470         wake_up_interruptible(&self->query_wait);
471 }
472
473 /*
474  * Function irda_open_tsap (self)
475  *
476  *    Open local Transport Service Access Point (TSAP)
477  *
478  */
479 static int irda_open_tsap(struct irda_sock *self, __u8 tsap_sel, char *name)
480 {
481         notify_t notify;
482
483         if (self->tsap) {
484                 WARNING(__FUNCTION__ "(), busy!\n");
485                 return -EBUSY;
486         }
487         
488         /* Initialize callbacks to be used by the IrDA stack */
489         irda_notify_init(&notify);
490         notify.connect_confirm       = irda_connect_confirm;
491         notify.connect_indication    = irda_connect_indication;
492         notify.disconnect_indication = irda_disconnect_indication;
493         notify.data_indication       = irda_data_indication;
494         notify.udata_indication      = irda_data_indication;
495         notify.flow_indication       = irda_flow_indication;
496         notify.instance = self;
497         strncpy(notify.name, name, NOTIFY_MAX_NAME);
498
499         self->tsap = irttp_open_tsap(tsap_sel, DEFAULT_INITIAL_CREDIT,
500                                      &notify);  
501         if (self->tsap == NULL) {
502                 IRDA_DEBUG( 0, __FUNCTION__ "(), Unable to allocate TSAP!\n");
503                 return -ENOMEM;
504         }
505         /* Remember which TSAP selector we actually got */
506         self->stsap_sel = self->tsap->stsap_sel;
507
508         return 0;
509 }
510
511 /*
512  * Function irda_open_lsap (self)
513  *
514  *    Open local Link Service Access Point (LSAP). Used for opening Ultra
515  *    sockets
516  */
517 #ifdef CONFIG_IRDA_ULTRA
518 static int irda_open_lsap(struct irda_sock *self, int pid)
519 {
520         notify_t notify;
521
522         if (self->lsap) {
523                 WARNING(__FUNCTION__ "(), busy!\n");
524                 return -EBUSY;
525         }
526         
527         /* Initialize callbacks to be used by the IrDA stack */
528         irda_notify_init(&notify);
529         notify.udata_indication = irda_data_indication;
530         notify.instance = self;
531         strncpy(notify.name, "Ultra", NOTIFY_MAX_NAME);
532
533         self->lsap = irlmp_open_lsap(LSAP_CONNLESS, &notify, pid);      
534         if (self->lsap == NULL) {
535                 IRDA_DEBUG( 0, __FUNCTION__ "(), Unable to allocate LSAP!\n");
536                 return -ENOMEM;
537         }
538
539         return 0;
540 }
541 #endif /* CONFIG_IRDA_ULTRA */
542
543 /*
544  * Function irda_find_lsap_sel (self, name)
545  *
546  *    Try to lookup LSAP selector in remote LM-IAS
547  *
548  * Basically, we start a IAP query, and then go to sleep. When the query
549  * return, irda_getvalue_confirm will wake us up, and we can examine the
550  * result of the query...
551  * Note that in some case, the query fail even before we go to sleep,
552  * creating some races...
553  */
554 static int irda_find_lsap_sel(struct irda_sock *self, char *name)
555 {
556         IRDA_DEBUG(2, __FUNCTION__ "(%p, %s)\n", self, name);
557
558         ASSERT(self != NULL, return -1;);
559
560         if (self->iriap) {
561                 WARNING(__FUNCTION__ "(), busy with a previous query\n");
562                 return -EBUSY;
563         }
564
565         self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self,
566                                  irda_getvalue_confirm);
567         if(self->iriap == NULL)
568                 return -ENOMEM;
569
570         /* Treat unexpected signals as disconnect */
571         self->errno = -EHOSTUNREACH;
572
573         /* Query remote LM-IAS */
574         iriap_getvaluebyclass_request(self->iriap, self->saddr, self->daddr,
575                                       name, "IrDA:TinyTP:LsapSel");
576         /* Wait for answer (if not already failed) */
577         if(self->iriap != NULL)
578                 interruptible_sleep_on(&self->query_wait);
579
580         /* Check what happened */
581         if (self->errno)
582         {
583                 /* Requested object/attribute doesn't exist */
584                 if((self->errno == IAS_CLASS_UNKNOWN) ||
585                    (self->errno == IAS_ATTRIB_UNKNOWN))
586                         return (-EADDRNOTAVAIL);
587                 else
588                         return (-EHOSTUNREACH);
589         }
590
591         /* Get the remote TSAP selector */
592         switch (self->ias_result->type) {
593         case IAS_INTEGER:
594                 IRDA_DEBUG(4, __FUNCTION__ "() int=%d\n",
595                            self->ias_result->t.integer);
596                 
597                 if (self->ias_result->t.integer != -1)
598                         self->dtsap_sel = self->ias_result->t.integer;
599                 else 
600                         self->dtsap_sel = 0;
601                 break;
602         default:
603                 self->dtsap_sel = 0;
604                 IRDA_DEBUG(0, __FUNCTION__ "(), bad type!\n");
605                 break;
606         }
607         if (self->ias_result)
608                 irias_delete_value(self->ias_result);
609
610         if (self->dtsap_sel)
611                 return 0;
612
613         return -EADDRNOTAVAIL;
614 }
615
616 /*
617  * Function irda_discover_daddr_and_lsap_sel (self, name)
618  *
619  *    This try to find a device with the requested service.
620  *
621  * It basically look into the discovery log. For each address in the list,
622  * it queries the LM-IAS of the device to find if this device offer
623  * the requested service.
624  * If there is more than one node supporting the service, we complain
625  * to the user (it should move devices around).
626  * The, we set both the destination address and the lsap selector to point
627  * on the service on the unique device we have found.
628  *
629  * Note : this function fails if there is more than one device in range,
630  * because IrLMP doesn't disconnect the LAP when the last LSAP is closed.
631  * Moreover, we would need to wait the LAP disconnection...
632  */
633 static int irda_discover_daddr_and_lsap_sel(struct irda_sock *self, char *name)
634 {
635         struct irda_device_info *discoveries;   /* Copy of the discovery log */
636         int     number;                 /* Number of nodes in the log */
637         int     i;
638         int     err = -ENETUNREACH;
639         __u32   daddr = DEV_ADDR_ANY;   /* Address we found the service on */
640         __u8    dtsap_sel = 0x0;        /* TSAP associated with it */
641
642         IRDA_DEBUG(2, __FUNCTION__ "(), name=%s\n", name);
643
644         ASSERT(self != NULL, return -1;);
645
646         /* Ask lmp for the current discovery log
647          * Note : we have to use irlmp_get_discoveries(), as opposed
648          * to play with the cachelog directly, because while we are
649          * making our ias query, le log might change... */
650         discoveries = irlmp_get_discoveries(&number, self->mask, self->nslots);
651         /* Check if the we got some results */
652         if (discoveries == NULL)
653                 return -ENETUNREACH;    /* No nodes discovered */
654
655         /* 
656          * Now, check all discovered devices (if any), and connect
657          * client only about the services that the client is
658          * interested in...
659          */
660         for(i = 0; i < number; i++) {
661                 /* Try the address in the log */
662                 self->daddr = discoveries[i].daddr;
663                 self->saddr = 0x0;
664                 IRDA_DEBUG(1, __FUNCTION__ "(), trying daddr = %08x\n",
665                            self->daddr);
666
667                 /* Query remote LM-IAS for this service */
668                 err = irda_find_lsap_sel(self, name);
669                 switch (err) {
670                 case 0:
671                         /* We found the requested service */
672                         if(daddr != DEV_ADDR_ANY) {
673                                 IRDA_DEBUG(1, __FUNCTION__
674                                            "(), discovered service ''%s'' in two different devices !!!\n",
675                                            name);
676                                 self->daddr = DEV_ADDR_ANY;
677                                 kfree(discoveries);
678                                 return(-ENOTUNIQ);
679                         }
680                         /* First time we found that one, save it ! */
681                         daddr = self->daddr;
682                         dtsap_sel = self->dtsap_sel;
683                         break;
684                 case -EADDRNOTAVAIL:
685                         /* Requested service simply doesn't exist on this node */
686                         break;
687                 default:
688                         /* Something bad did happen :-( */
689                         IRDA_DEBUG(0, __FUNCTION__
690                                    "(), unexpected IAS query failure\n");
691                         self->daddr = DEV_ADDR_ANY;
692                         kfree(discoveries);
693                         return(-EHOSTUNREACH);
694                         break;
695                 }
696         }
697         /* Cleanup our copy of the discovery log */
698         kfree(discoveries);
699
700         /* Check out what we found */
701         if(daddr == DEV_ADDR_ANY) {
702                 IRDA_DEBUG(1, __FUNCTION__
703                            "(), cannot discover service ''%s'' in any device !!!\n",
704                            name);
705                 self->daddr = DEV_ADDR_ANY;
706                 return(-EADDRNOTAVAIL);
707         }
708
709         /* Revert back to discovered device & service */
710         self->daddr = daddr;
711         self->saddr = 0x0;
712         self->dtsap_sel = dtsap_sel;
713
714         IRDA_DEBUG(1, __FUNCTION__ 
715                    "(), discovered requested service ''%s'' at address %08x\n",
716                    name, self->daddr);
717
718         return 0;
719 }
720
721 /*
722  * Function irda_getname (sock, uaddr, uaddr_len, peer)
723  *
724  *    Return the our own, or peers socket address (sockaddr_irda)
725  *
726  */
727 static int irda_getname(struct socket *sock, struct sockaddr *uaddr,
728                         int *uaddr_len, int peer)
729 {
730         struct sockaddr_irda saddr;
731         struct sock *sk = sock->sk;
732         struct irda_sock *self = sk->protinfo.irda;
733
734         if (peer) {
735                 if (sk->state != TCP_ESTABLISHED)
736                         return -ENOTCONN;
737                 
738                 saddr.sir_family = AF_IRDA;
739                 saddr.sir_lsap_sel = self->dtsap_sel;
740                 saddr.sir_addr = self->daddr;
741         } else {
742                 saddr.sir_family = AF_IRDA;
743                 saddr.sir_lsap_sel = self->stsap_sel;
744                 saddr.sir_addr = self->saddr;
745         }
746         
747         IRDA_DEBUG(1, __FUNCTION__ "(), tsap_sel = %#x\n", saddr.sir_lsap_sel);
748         IRDA_DEBUG(1, __FUNCTION__ "(), addr = %08x\n", saddr.sir_addr);
749
750         /* uaddr_len come to us uninitialised */
751         *uaddr_len = sizeof (struct sockaddr_irda);
752         memcpy(uaddr, &saddr, *uaddr_len);
753
754         return 0;
755 }
756
757 /*
758  * Function irda_listen (sock, backlog)
759  *
760  *    Just move to the listen state
761  *
762  */
763 static int irda_listen(struct socket *sock, int backlog)
764 {
765         struct sock *sk = sock->sk;
766
767         IRDA_DEBUG(2, __FUNCTION__ "()\n");
768
769         if ((sk->type != SOCK_STREAM) && (sk->type != SOCK_SEQPACKET) &&
770             (sk->type != SOCK_DGRAM))
771                 return -EOPNOTSUPP;
772
773         if (sk->state != TCP_LISTEN) {
774                 sk->max_ack_backlog = backlog;
775                 sk->state           = TCP_LISTEN;
776                 
777                 return 0;
778         }
779         
780         return -EOPNOTSUPP;
781 }
782
783 /*
784  * Function irda_bind (sock, uaddr, addr_len)
785  *
786  *    Used by servers to register their well known TSAP
787  *
788  */
789 static int irda_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
790 {
791         struct sock *sk = sock->sk;
792         struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr;
793         struct irda_sock *self;
794         int err;
795
796         self = sk->protinfo.irda;
797         ASSERT(self != NULL, return -1;);
798
799         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
800
801         if (addr_len != sizeof(struct sockaddr_irda))
802                 return -EINVAL;
803
804 #ifdef CONFIG_IRDA_ULTRA
805         /* Special care for Ultra sockets */
806         if ((sk->type == SOCK_DGRAM) && (sk->protocol == IRDAPROTO_ULTRA)) {
807                 self->pid = addr->sir_lsap_sel;
808                 if (self->pid & 0x80) {
809                         IRDA_DEBUG(0, __FUNCTION__ 
810                                    "(), extension in PID not supp!\n");
811                         return -EOPNOTSUPP;
812                 }
813                 err = irda_open_lsap(self, self->pid);
814                 if (err < 0)
815                         return err;
816                 
817                 self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER;
818                 self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER;
819
820                 /* Pretend we are connected */
821                 sock->state = SS_CONNECTED;
822                 sk->state   = TCP_ESTABLISHED;
823
824                 return 0;
825         }
826 #endif /* CONFIG_IRDA_ULTRA */
827
828         err = irda_open_tsap(self, addr->sir_lsap_sel, addr->sir_name);
829         if (err < 0)
830                 return err;
831         
832         /*  Register with LM-IAS */
833         self->ias_obj = irias_new_object(addr->sir_name, jiffies);
834         irias_add_integer_attrib(self->ias_obj, "IrDA:TinyTP:LsapSel", 
835                                  self->stsap_sel, IAS_KERNEL_ATTR);
836         irias_insert_object(self->ias_obj);
837         
838         return 0;
839 }
840
841 /*
842  * Function irda_accept (sock, newsock, flags)
843  *
844  *    Wait for incoming connection
845  *
846  */
847 static int irda_accept(struct socket *sock, struct socket *newsock, int flags)
848 {
849         struct irda_sock *self, *new;
850         struct sock *sk = sock->sk;
851         struct sock *newsk;
852         struct sk_buff *skb;
853         int err;
854
855         IRDA_DEBUG(2, __FUNCTION__ "()\n");
856
857         self = sk->protinfo.irda;
858         ASSERT(self != NULL, return -1;);
859
860         err = irda_create(newsock, sk->protocol);
861         if (err)
862                 return err;
863
864         if (sock->state != SS_UNCONNECTED)
865                 return -EINVAL;
866
867         if ((sk = sock->sk) == NULL)
868                 return -EINVAL;
869
870         if ((sk->type != SOCK_STREAM) && (sk->type != SOCK_SEQPACKET) &&
871             (sk->type != SOCK_DGRAM))
872                 return -EOPNOTSUPP;
873
874         if (sk->state != TCP_LISTEN) 
875                 return -EINVAL;
876
877         /*
878          *      The read queue this time is holding sockets ready to use
879          *      hooked into the SABM we saved
880          */
881         do {
882                 if ((skb = skb_dequeue(&sk->receive_queue)) == NULL) {
883                         if (flags & O_NONBLOCK)
884                                 return -EWOULDBLOCK;
885
886                         interruptible_sleep_on(sk->sleep);
887                         if (signal_pending(current)) 
888                                 return -ERESTARTSYS;
889                 }
890         } while (skb == NULL);
891
892         newsk = newsock->sk;
893         newsk->state = TCP_ESTABLISHED;
894
895         new = newsk->protinfo.irda;
896         ASSERT(new != NULL, return -1;);
897
898         /* Now attach up the new socket */
899         new->tsap = irttp_dup(self->tsap, new);
900         if (!new->tsap) {
901                 IRDA_DEBUG(0, __FUNCTION__ "(), dup failed!\n");
902                 return -1;
903         }
904                 
905         new->stsap_sel = new->tsap->stsap_sel;
906         new->dtsap_sel = new->tsap->dtsap_sel;
907         new->saddr = irttp_get_saddr(new->tsap);
908         new->daddr = irttp_get_daddr(new->tsap);
909
910         new->max_sdu_size_tx = self->max_sdu_size_tx;
911         new->max_sdu_size_rx = self->max_sdu_size_rx;
912         new->max_data_size   = self->max_data_size;
913         new->max_header_size = self->max_header_size;
914
915         memcpy(&new->qos_tx, &self->qos_tx, sizeof(struct qos_info));
916
917         /* Clean up the original one to keep it in listen state */
918         irttp_listen(self->tsap);
919
920         skb->sk = NULL;
921         skb->destructor = NULL;
922         kfree_skb(skb);
923         sk->ack_backlog--;
924
925         newsock->state = SS_CONNECTED;
926
927         irda_connect_response(new);
928
929         return 0;
930 }
931
932 /*
933  * Function irda_connect (sock, uaddr, addr_len, flags)
934  *
935  *    Connect to a IrDA device
936  *
937  * The main difference with a "standard" connect is that with IrDA we need
938  * to resolve the service name into a TSAP selector (in TCP, port number
939  * doesn't have to be resolved).
940  * Because of this service name resoltion, we can offer "auto-connect",
941  * where we connect to a service without specifying a destination address.
942  *
943  * Note : by consulting "errno", the user space caller may learn the cause
944  * of the failure. Most of them are visible in the function, others may come
945  * from subroutines called and are listed here :
946  *      o EBUSY : already processing a connect
947  *      o EHOSTUNREACH : bad addr->sir_addr argument
948  *      o EADDRNOTAVAIL : bad addr->sir_name argument
949  *      o ENOTUNIQ : more than one node has addr->sir_name (auto-connect)
950  *      o ENETUNREACH : no node found on the network (auto-connect)
951  */
952 static int irda_connect(struct socket *sock, struct sockaddr *uaddr,
953                         int addr_len, int flags)
954 {
955         struct sock *sk = sock->sk;
956         struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr;
957         struct irda_sock *self;
958         int err;
959
960         self = sk->protinfo.irda;
961         
962         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
963
964         /* Don't allow connect for Ultra sockets */
965         if ((sk->type == SOCK_DGRAM) && (sk->protocol == IRDAPROTO_ULTRA))
966                 return -ESOCKTNOSUPPORT;
967
968         if (sk->state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) {
969                 sock->state = SS_CONNECTED;
970                 return 0;   /* Connect completed during a ERESTARTSYS event */
971         }
972         
973         if (sk->state == TCP_CLOSE && sock->state == SS_CONNECTING) {
974                 sock->state = SS_UNCONNECTED;
975                 return -ECONNREFUSED;
976         }
977         
978         if (sk->state == TCP_ESTABLISHED)
979                 return -EISCONN;      /* No reconnect on a seqpacket socket */
980         
981         sk->state   = TCP_CLOSE;        
982         sock->state = SS_UNCONNECTED;
983
984         if (addr_len != sizeof(struct sockaddr_irda))
985                 return -EINVAL;
986
987         /* Check if user supplied any destination device address */
988         if ((!addr->sir_addr) || (addr->sir_addr == DEV_ADDR_ANY)) {
989                 /* Try to find one suitable */
990                 err = irda_discover_daddr_and_lsap_sel(self, addr->sir_name);
991                 if (err) {
992                         IRDA_DEBUG(0, __FUNCTION__ 
993                                    "(), auto-connect failed!\n");
994                         return err;
995                 }
996         } else {
997                 /* Use the one provided by the user */
998                 self->daddr = addr->sir_addr;
999                 IRDA_DEBUG(1, __FUNCTION__ "(), daddr = %08x\n", self->daddr);
1000                 
1001                 /* Query remote LM-IAS */
1002                 err = irda_find_lsap_sel(self, addr->sir_name);
1003                 if (err) {
1004                         IRDA_DEBUG(0, __FUNCTION__ "(), connect failed!\n");
1005                         return err;
1006                 }
1007         }
1008
1009         /* Check if we have opened a local TSAP */
1010         if (!self->tsap)
1011                 irda_open_tsap(self, LSAP_ANY, addr->sir_name);
1012         
1013         /* Move to connecting socket, start sending Connect Requests */
1014         sock->state = SS_CONNECTING;
1015         sk->state   = TCP_SYN_SENT;
1016
1017         /* Connect to remote device */
1018         err = irttp_connect_request(self->tsap, self->dtsap_sel, 
1019                                     self->saddr, self->daddr, NULL, 
1020                                     self->max_sdu_size_rx, NULL);
1021         if (err) {
1022                 IRDA_DEBUG(0, __FUNCTION__ "(), connect failed!\n");
1023                 return err;
1024         }
1025
1026         /* Now the loop */
1027         if (sk->state != TCP_ESTABLISHED && (flags & O_NONBLOCK))
1028                 return -EINPROGRESS;
1029
1030         /* Here, there is a race condition : the state may change between
1031          * our test and the sleep, via irda_connect_confirm().
1032          * The way to workaround that is to sleep with a timeout, so that
1033          * we don't sleep forever and check the state when waking up.
1034          * 50ms is plenty good enough, because the LAP is already connected.
1035          * Jean II */
1036         while (sk->state == TCP_SYN_SENT) {
1037                 interruptible_sleep_on_timeout(sk->sleep, HZ/20);
1038                 if (signal_pending(current)) {
1039                         return -ERESTARTSYS;
1040                 }
1041         }
1042         
1043         if (sk->state != TCP_ESTABLISHED) {
1044                 sock->state = SS_UNCONNECTED;
1045                 return sock_error(sk);  /* Always set at this point */
1046         }
1047         
1048         sock->state = SS_CONNECTED;
1049         
1050         /* At this point, IrLMP has assigned our source address */
1051         self->saddr = irttp_get_saddr(self->tsap);
1052
1053         return 0;
1054 }
1055
1056 /*
1057  * Function irda_create (sock, protocol)
1058  *
1059  *    Create IrDA socket
1060  *
1061  */
1062 static int irda_create(struct socket *sock, int protocol)
1063 {
1064         struct sock *sk;
1065         struct irda_sock *self;
1066
1067         IRDA_DEBUG(2, __FUNCTION__ "()\n");
1068         
1069         /* Check for valid socket type */
1070         switch (sock->type) {
1071         case SOCK_STREAM:     /* For TTP connections with SAR disabled */
1072         case SOCK_SEQPACKET:  /* For TTP connections with SAR enabled */
1073         case SOCK_DGRAM:      /* For TTP Unitdata or LMP Ultra transfers */
1074                 break;
1075         default:
1076                 return -ESOCKTNOSUPPORT;
1077         }
1078
1079         /* Allocate networking socket */
1080         if ((sk = sk_alloc(PF_IRDA, GFP_ATOMIC, 1)) == NULL)
1081                 return -ENOMEM;
1082
1083         /* Allocate IrDA socket */
1084         self = kmalloc(sizeof(struct irda_sock), GFP_ATOMIC);
1085         if (self == NULL) {
1086                 sk_free(sk);
1087                 return -ENOMEM;
1088         }
1089         memset(self, 0, sizeof(struct irda_sock));
1090
1091         IRDA_DEBUG(2, __FUNCTION__ "() : self is %p\n", self);
1092
1093         init_waitqueue_head(&self->query_wait);
1094
1095         /* Initialise networking socket struct */ 
1096         sock_init_data(sock, sk);       /* Note : set sk->refcnt to 1 */
1097         sk->family = PF_IRDA;
1098         sk->protocol = protocol;
1099         /* Link networking socket and IrDA socket structs together */
1100         sk->protinfo.irda = self;
1101         self->sk = sk;
1102
1103         switch (sock->type) {
1104         case SOCK_STREAM:
1105                 sock->ops = &irda_stream_ops;
1106                 self->max_sdu_size_rx = TTP_SAR_DISABLE;
1107                 break;
1108         case SOCK_SEQPACKET:
1109                 sock->ops = &irda_seqpacket_ops;
1110                 self->max_sdu_size_rx = TTP_SAR_UNBOUND;
1111                 break;
1112         case SOCK_DGRAM:
1113                 switch (protocol) {
1114 #ifdef CONFIG_IRDA_ULTRA
1115                 case IRDAPROTO_ULTRA:
1116                         sock->ops = &irda_ultra_ops;
1117                         break;
1118 #endif /* CONFIG_IRDA_ULTRA */
1119                 case IRDAPROTO_UNITDATA:
1120                         sock->ops = &irda_dgram_ops;
1121                         /* We let Unitdata conn. be like seqpack conn. */
1122                         self->max_sdu_size_rx = TTP_SAR_UNBOUND;
1123                         break;
1124                 default:
1125                         ERROR(__FUNCTION__ "(), protocol not supported!\n");
1126                         return -ESOCKTNOSUPPORT;
1127                 }
1128                 break;
1129         default:
1130                 return -ESOCKTNOSUPPORT;
1131         }               
1132
1133         /* Register as a client with IrLMP */
1134         self->ckey = irlmp_register_client(0, NULL, NULL, NULL);
1135         self->mask = 0xffff;
1136         self->rx_flow = self->tx_flow = FLOW_START;
1137         self->nslots = DISCOVERY_DEFAULT_SLOTS;
1138         self->daddr = DEV_ADDR_ANY;     /* Until we get connected */
1139         self->saddr = 0x0;              /* so IrLMP assign us any link */
1140
1141         MOD_INC_USE_COUNT;
1142
1143         return 0;
1144 }
1145
1146 /*
1147  * Function irda_destroy_socket (self)
1148  *
1149  *    Destroy socket
1150  *
1151  */
1152 void irda_destroy_socket(struct irda_sock *self)
1153 {
1154         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
1155
1156         ASSERT(self != NULL, return;);
1157
1158         /* Unregister with IrLMP */
1159         irlmp_unregister_client(self->ckey);
1160         irlmp_unregister_service(self->skey);
1161
1162         /* Unregister with LM-IAS */
1163         if (self->ias_obj) {
1164                 irias_delete_object(self->ias_obj);
1165                 self->ias_obj = NULL;
1166         }
1167
1168         if (self->iriap) {
1169                 iriap_close(self->iriap);
1170                 self->iriap = NULL;
1171         }
1172
1173         if (self->tsap) {
1174                 irttp_disconnect_request(self->tsap, NULL, P_NORMAL);
1175                 irttp_close_tsap(self->tsap);
1176                 self->tsap = NULL;
1177         }
1178 #ifdef CONFIG_IRDA_ULTRA
1179         if (self->lsap) {
1180                 irlmp_close_lsap(self->lsap);
1181                 self->lsap = NULL;
1182         }
1183 #endif /* CONFIG_IRDA_ULTRA */
1184         kfree(self);
1185         MOD_DEC_USE_COUNT;
1186         
1187         return;
1188 }
1189
1190 /*
1191  * Function irda_release (sock)
1192  *
1193  *    
1194  *
1195  */
1196 static int irda_release(struct socket *sock)
1197 {
1198         struct sock *sk = sock->sk;
1199         
1200         IRDA_DEBUG(2, __FUNCTION__ "()\n");
1201
1202         if (sk == NULL) 
1203                 return 0;
1204         
1205         sk->state       = TCP_CLOSE;
1206         sk->shutdown   |= SEND_SHUTDOWN;
1207         sk->state_change(sk);
1208
1209         /* Destroy IrDA socket */
1210         irda_destroy_socket(sk->protinfo.irda);
1211         /* Prevent sock_def_destruct() to create havoc */
1212         sk->protinfo.irda = NULL;
1213
1214         sock_orphan(sk);
1215         sock->sk   = NULL;      
1216
1217         /* Purge queues (see sock_init_data()) */
1218         skb_queue_purge(&sk->receive_queue);
1219
1220         /* Destroy networking socket if we are the last reference on it,
1221          * i.e. if(sk->refcnt == 0) -> sk_free(sk) */
1222         sock_put(sk);
1223
1224         /* Notes on socket locking and deallocation... - Jean II
1225          * In theory we should put pairs of sock_hold() / sock_put() to
1226          * prevent the socket to be destroyed whenever there is an
1227          * outstanding request or outstanding incomming packet or event.
1228          *
1229          * 1) This may include IAS request, both in connect and getsockopt.
1230          * Unfortunately, the situation is a bit more messy than it looks,
1231          * because we close iriap and kfree(self) above.
1232          * 
1233          * 2) This may include selective discovery in getsockopt.
1234          * Same stuff as above, irlmp registration and self are gone.
1235          *
1236          * Probably 1 and 2 may not matter, because it's all triggered
1237          * by a process and the socket layer already prevent the
1238          * socket to go away while a process is holding it, through
1239          * sockfd_put() and fput()...
1240          *
1241          * 3) This may include deferred TSAP closure. In particular,
1242          * we may receive a late irda_disconnect_indication()
1243          * Fortunately, (tsap_cb *)->close_pend should protect us
1244          * from that.
1245          *
1246          * I did some testing on SMP, and it looks solid. And the socket
1247          * memory leak is now gone... - Jean II
1248          */
1249
1250         return 0;
1251 }
1252
1253 /*
1254  * Function irda_sendmsg (sock, msg, len, scm)
1255  *
1256  *    Send message down to TinyTP. This function is used for both STREAM and
1257  *    SEQPACK services. This is possible since it forces the client to 
1258  *    fragment the message if necessary
1259  */
1260 static int irda_sendmsg(struct socket *sock, struct msghdr *msg, int len, 
1261                         struct scm_cookie *scm)
1262 {
1263         struct sock *sk = sock->sk;
1264         struct irda_sock *self;
1265         struct sk_buff *skb;
1266         unsigned char *asmptr;
1267         int err;
1268
1269         IRDA_DEBUG(4, __FUNCTION__ "(), len=%d\n", len);
1270
1271         /* Note : socket.c set MSG_EOR on SEQPACKET sockets */
1272         if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_EOR))
1273                 return -EINVAL;
1274
1275         if (sk->shutdown & SEND_SHUTDOWN) {
1276                 send_sig(SIGPIPE, current, 0);
1277                 return -EPIPE;
1278         }
1279
1280         if (sk->state != TCP_ESTABLISHED)
1281                 return -ENOTCONN;
1282
1283         self = sk->protinfo.irda;
1284         ASSERT(self != NULL, return -1;);
1285
1286         /* Check if IrTTP is wants us to slow down */
1287         while (self->tx_flow == FLOW_STOP) {
1288                 IRDA_DEBUG(2, __FUNCTION__ "(), IrTTP is busy, going to sleep!\n");
1289                 interruptible_sleep_on(sk->sleep);
1290                 
1291                 /* Check if we are still connected */
1292                 if (sk->state != TCP_ESTABLISHED)
1293                         return -ENOTCONN;
1294                 /* Handle signals */
1295                 if (signal_pending(current)) 
1296                         return -ERESTARTSYS;
1297         }
1298
1299         /* Check that we don't send out to big frames */
1300         if (len > self->max_data_size) {
1301                 IRDA_DEBUG(2, __FUNCTION__ 
1302                            "(), Chopping frame from %d to %d bytes!\n", len, 
1303                            self->max_data_size);
1304                 len = self->max_data_size;
1305         }
1306
1307         skb = sock_alloc_send_skb(sk, len + self->max_header_size, 
1308                                   msg->msg_flags & MSG_DONTWAIT, &err);
1309         if (!skb)
1310                 return -ENOBUFS;
1311
1312         skb_reserve(skb, self->max_header_size);
1313         
1314         asmptr = skb->h.raw = skb_put(skb, len);
1315         memcpy_fromiovec(asmptr, msg->msg_iov, len);
1316
1317         /* 
1318          * Just send the message to TinyTP, and let it deal with possible 
1319          * errors. No need to duplicate all that here
1320          */
1321         err = irttp_data_request(self->tsap, skb);
1322         if (err) {
1323                 IRDA_DEBUG(0, __FUNCTION__ "(), err=%d\n", err);
1324                 return err;
1325         }
1326         /* Tell client how much data we actually sent */
1327         return len;
1328 }
1329
1330 /*
1331  * Function irda_recvmsg_dgram (sock, msg, size, flags, scm)
1332  *
1333  *    Try to receive message and copy it to user. The frame is discarded
1334  *    after being read, regardless of how much the user actually read
1335  */
1336 static int irda_recvmsg_dgram(struct socket *sock, struct msghdr *msg, 
1337                               int size, int flags, struct scm_cookie *scm)
1338 {
1339         struct irda_sock *self;
1340         struct sock *sk = sock->sk;
1341         struct sk_buff *skb;
1342         int copied, err;
1343
1344         IRDA_DEBUG(4, __FUNCTION__ "()\n");
1345
1346         self = sk->protinfo.irda;
1347         ASSERT(self != NULL, return -1;);
1348
1349         skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, 
1350                                 flags & MSG_DONTWAIT, &err);
1351         if (!skb)
1352                 return err;
1353
1354         skb->h.raw = skb->data;
1355         copied     = skb->len;
1356         
1357         if (copied > size) {
1358                 IRDA_DEBUG(2, __FUNCTION__ 
1359                            "(), Received truncated frame (%d < %d)!\n",
1360                            copied, size);
1361                 copied = size;
1362                 msg->msg_flags |= MSG_TRUNC;
1363         }
1364         skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1365
1366         skb_free_datagram(sk, skb);
1367
1368         /*
1369          *  Check if we have previously stopped IrTTP and we know
1370          *  have more free space in our rx_queue. If so tell IrTTP
1371          *  to start delivering frames again before our rx_queue gets
1372          *  empty
1373          */
1374         if (self->rx_flow == FLOW_STOP) {
1375                 if ((atomic_read(&sk->rmem_alloc) << 2) <= sk->rcvbuf) {
1376                         IRDA_DEBUG(2, __FUNCTION__ "(), Starting IrTTP\n");
1377                         self->rx_flow = FLOW_START;
1378                         irttp_flow_request(self->tsap, FLOW_START);
1379                 }
1380         }
1381
1382         return copied;
1383 }
1384
1385 /*
1386  * Function irda_data_wait (sk)
1387  *
1388  *    Sleep until data has arrive. But check for races..
1389  *
1390  */
1391 static void irda_data_wait(struct sock *sk)
1392 {
1393         if (!skb_peek(&sk->receive_queue)) {
1394                 set_bit(SOCK_ASYNC_WAITDATA, &sk->socket->flags);
1395                 interruptible_sleep_on(sk->sleep);
1396                 clear_bit(SOCK_ASYNC_WAITDATA, &sk->socket->flags);
1397         }
1398 }
1399
1400 /*
1401  * Function irda_recvmsg_stream (sock, msg, size, flags, scm)
1402  *
1403  *    
1404  *
1405  */
1406 static int irda_recvmsg_stream(struct socket *sock, struct msghdr *msg, 
1407                                int size, int flags, struct scm_cookie *scm)
1408 {
1409         struct irda_sock *self;
1410         struct sock *sk = sock->sk;
1411         int noblock = flags & MSG_DONTWAIT;
1412         int copied = 0;
1413         int target = 1;
1414
1415         IRDA_DEBUG(3, __FUNCTION__ "()\n");
1416
1417         self = sk->protinfo.irda;
1418         ASSERT(self != NULL, return -1;);
1419
1420         if (sock->flags & __SO_ACCEPTCON) 
1421                 return(-EINVAL);
1422
1423         if (flags & MSG_OOB)
1424                 return -EOPNOTSUPP;
1425
1426         if (flags & MSG_WAITALL)
1427                 target = size;
1428                 
1429         msg->msg_namelen = 0;
1430
1431         do {
1432                 int chunk;
1433                 struct sk_buff *skb;
1434
1435                 skb=skb_dequeue(&sk->receive_queue);
1436                 if (skb==NULL) {
1437                         if (copied >= target)
1438                                 break;
1439                         
1440                         /*
1441                          *      POSIX 1003.1g mandates this order.
1442                          */
1443                         
1444                         if (sk->err) {
1445                                 return sock_error(sk);
1446                         }
1447
1448                         if (sk->shutdown & RCV_SHUTDOWN)
1449                                 break;
1450
1451                         if (noblock)
1452                                 return -EAGAIN;
1453                         irda_data_wait(sk);
1454                         if (signal_pending(current))
1455                                 return -ERESTARTSYS;
1456                         continue;
1457                 }
1458
1459                 chunk = min_t(unsigned int, skb->len, size);
1460                 if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) {
1461                         skb_queue_head(&sk->receive_queue, skb);
1462                         if (copied == 0)
1463                                 copied = -EFAULT;
1464                         break;
1465                 }
1466                 copied += chunk;
1467                 size -= chunk;
1468
1469                 /* Mark read part of skb as used */
1470                 if (!(flags & MSG_PEEK)) {
1471                         skb_pull(skb, chunk);
1472
1473                         /* put the skb back if we didn't use it up.. */
1474                         if (skb->len) {
1475                                 IRDA_DEBUG(1, __FUNCTION__ "(), back on q!\n");
1476                                 skb_queue_head(&sk->receive_queue, skb);
1477                                 break;
1478                         }
1479
1480                         kfree_skb(skb);                 
1481                 } else {
1482                         IRDA_DEBUG(0, __FUNCTION__ "() questionable!?\n");
1483
1484                         /* put message back and return */
1485                         skb_queue_head(&sk->receive_queue, skb);
1486                         break;
1487                 }
1488         } while (size);
1489
1490         /*
1491          *  Check if we have previously stopped IrTTP and we know
1492          *  have more free space in our rx_queue. If so tell IrTTP
1493          *  to start delivering frames again before our rx_queue gets
1494          *  empty
1495          */
1496         if (self->rx_flow == FLOW_STOP) {
1497                 if ((atomic_read(&sk->rmem_alloc) << 2) <= sk->rcvbuf) {
1498                         IRDA_DEBUG(2, __FUNCTION__ "(), Starting IrTTP\n");
1499                         self->rx_flow = FLOW_START;
1500                         irttp_flow_request(self->tsap, FLOW_START);
1501                 }
1502         }
1503
1504         return copied;
1505 }
1506
1507 /*
1508  * Function irda_sendmsg_dgram (sock, msg, len, scm)
1509  *
1510  *    Send message down to TinyTP for the unreliable sequenced
1511  *    packet service...
1512  *
1513  */
1514 static int irda_sendmsg_dgram(struct socket *sock, struct msghdr *msg,
1515                               int len, struct scm_cookie *scm)
1516 {
1517         struct sock *sk = sock->sk;
1518         struct irda_sock *self;
1519         struct sk_buff *skb;
1520         unsigned char *asmptr;
1521         int err;
1522         
1523         IRDA_DEBUG(4, __FUNCTION__ "(), len=%d\n", len);
1524         
1525         if (msg->msg_flags & ~MSG_DONTWAIT)
1526                 return -EINVAL;
1527
1528         if (sk->shutdown & SEND_SHUTDOWN) {
1529                 send_sig(SIGPIPE, current, 0);
1530                 return -EPIPE;
1531         }
1532
1533         if (sk->state != TCP_ESTABLISHED)
1534                 return -ENOTCONN;
1535
1536         self = sk->protinfo.irda;
1537         ASSERT(self != NULL, return -1;);
1538
1539         /*  
1540          * Check that we don't send out to big frames. This is an unreliable 
1541          * service, so we have no fragmentation and no coalescence 
1542          */
1543         if (len > self->max_data_size) {
1544                 IRDA_DEBUG(0, __FUNCTION__ "(), Warning to much data! "
1545                            "Chopping frame from %d to %d bytes!\n", len, 
1546                            self->max_data_size);
1547                 len = self->max_data_size;
1548         }
1549
1550         skb = sock_alloc_send_skb(sk, len + self->max_header_size, 
1551                                   msg->msg_flags & MSG_DONTWAIT, &err);
1552         if (!skb)
1553                 return -ENOBUFS;
1554
1555         skb_reserve(skb, self->max_header_size);
1556         
1557         IRDA_DEBUG(4, __FUNCTION__ "(), appending user data\n");
1558         asmptr = skb->h.raw = skb_put(skb, len);
1559         memcpy_fromiovec(asmptr, msg->msg_iov, len);
1560
1561         /* 
1562          * Just send the message to TinyTP, and let it deal with possible 
1563          * errors. No need to duplicate all that here
1564          */
1565         err = irttp_udata_request(self->tsap, skb);
1566         if (err) {
1567                 IRDA_DEBUG(0, __FUNCTION__ "(), err=%d\n", err);
1568                 return err;
1569         }
1570         return len;
1571 }
1572
1573 /*
1574  * Function irda_sendmsg_ultra (sock, msg, len, scm)
1575  *
1576  *    Send message down to IrLMP for the unreliable Ultra
1577  *    packet service...
1578  */
1579 #ifdef CONFIG_IRDA_ULTRA
1580 static int irda_sendmsg_ultra(struct socket *sock, struct msghdr *msg,
1581                               int len, struct scm_cookie *scm)
1582 {
1583         struct sock *sk = sock->sk;
1584         struct irda_sock *self;
1585         struct sk_buff *skb;
1586         unsigned char *asmptr;
1587         int err;
1588         
1589         IRDA_DEBUG(4, __FUNCTION__ "(), len=%d\n", len);
1590         
1591         if (msg->msg_flags & ~MSG_DONTWAIT)
1592                 return -EINVAL;
1593
1594         if (sk->shutdown & SEND_SHUTDOWN) {
1595                 send_sig(SIGPIPE, current, 0);
1596                 return -EPIPE;
1597         }
1598
1599         self = sk->protinfo.irda;
1600         ASSERT(self != NULL, return -1;);
1601
1602         /*  
1603          * Check that we don't send out to big frames. This is an unreliable 
1604          * service, so we have no fragmentation and no coalescence 
1605          */
1606         if (len > self->max_data_size) {
1607                 IRDA_DEBUG(0, __FUNCTION__ "(), Warning to much data! "
1608                            "Chopping frame from %d to %d bytes!\n", len, 
1609                            self->max_data_size);
1610                 len = self->max_data_size;
1611         }
1612
1613         skb = sock_alloc_send_skb(sk, len + self->max_header_size, 
1614                                   msg->msg_flags & MSG_DONTWAIT, &err);
1615         if (!skb)
1616                 return -ENOBUFS;
1617
1618         skb_reserve(skb, self->max_header_size);
1619         
1620         IRDA_DEBUG(4, __FUNCTION__ "(), appending user data\n");
1621         asmptr = skb->h.raw = skb_put(skb, len);
1622         memcpy_fromiovec(asmptr, msg->msg_iov, len);
1623
1624         err = irlmp_connless_data_request(self->lsap, skb);
1625         if (err) {
1626                 IRDA_DEBUG(0, __FUNCTION__ "(), err=%d\n", err);
1627                 return err;
1628         }
1629         return len;
1630 }
1631 #endif /* CONFIG_IRDA_ULTRA */
1632
1633 /*
1634  * Function irda_shutdown (sk, how)
1635  *
1636  *    
1637  *
1638  */
1639 static int irda_shutdown(struct socket *sock, int how)
1640 {
1641         struct irda_sock *self;
1642         struct sock *sk = sock->sk;
1643
1644         self = sk->protinfo.irda;
1645         ASSERT(self != NULL, return -1;);
1646
1647         IRDA_DEBUG(1, __FUNCTION__ "(%p)\n", self);
1648
1649         sk->state       = TCP_CLOSE;
1650         sk->shutdown   |= SEND_SHUTDOWN;
1651         sk->state_change(sk);
1652
1653         if (self->iriap) {
1654                 iriap_close(self->iriap);
1655                 self->iriap = NULL;
1656         }
1657
1658         if (self->tsap) {
1659                 irttp_disconnect_request(self->tsap, NULL, P_NORMAL);
1660                 irttp_close_tsap(self->tsap);
1661                 self->tsap = NULL;
1662         }
1663
1664         /* A few cleanup so the socket look as good as new... */
1665         self->rx_flow = self->tx_flow = FLOW_START;     /* needed ??? */
1666         self->daddr = DEV_ADDR_ANY;     /* Until we get re-connected */
1667         self->saddr = 0x0;              /* so IrLMP assign us any link */
1668
1669         return 0;
1670 }
1671
1672 /*
1673  * Function irda_poll (file, sock, wait)
1674  *
1675  *    
1676  *
1677  */
1678 static unsigned int irda_poll(struct file * file, struct socket *sock, 
1679                               poll_table *wait)
1680 {
1681         struct sock *sk = sock->sk;
1682         unsigned int mask;
1683         struct irda_sock *self;
1684
1685         IRDA_DEBUG(4, __FUNCTION__ "()\n");
1686
1687         self = sk->protinfo.irda;
1688         poll_wait(file, sk->sleep, wait);
1689         mask = 0;
1690
1691         /* Exceptional events? */
1692         if (sk->err)
1693                 mask |= POLLERR;
1694         if (sk->shutdown & RCV_SHUTDOWN) {
1695                 IRDA_DEBUG(0, __FUNCTION__ "(), POLLHUP\n");
1696                 mask |= POLLHUP;
1697         }
1698
1699         /* Readable? */
1700         if (!skb_queue_empty(&sk->receive_queue)) {
1701                 IRDA_DEBUG(4, "Socket is readable\n");
1702                 mask |= POLLIN | POLLRDNORM;
1703         }
1704
1705         /* Connection-based need to check for termination and startup */
1706         switch (sk->type) {
1707         case SOCK_STREAM:
1708                 if (sk->state == TCP_CLOSE) {
1709                         IRDA_DEBUG(0, __FUNCTION__ "(), POLLHUP\n");
1710                         mask |= POLLHUP;
1711                 }
1712
1713                 if (sk->state == TCP_ESTABLISHED) {
1714                         if ((self->tx_flow == FLOW_START) && 
1715                             sock_writeable(sk))
1716                         {
1717                                 mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
1718                         }
1719                 }
1720                 break;
1721         case SOCK_SEQPACKET:
1722                 if ((self->tx_flow == FLOW_START) && 
1723                     sock_writeable(sk))
1724                 {       
1725                         mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
1726                 }
1727                 break;
1728         case SOCK_DGRAM:
1729                 if (sock_writeable(sk))
1730                         mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
1731                 break;
1732         default:
1733                 break;
1734         }               
1735         return mask;
1736 }
1737
1738 /*
1739  * Function irda_ioctl (sock, cmd, arg)
1740  *
1741  *    
1742  *
1743  */
1744 static int irda_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
1745 {
1746         struct sock *sk = sock->sk;
1747
1748         IRDA_DEBUG(4, __FUNCTION__ "(), cmd=%#x\n", cmd);
1749         
1750         switch (cmd) {
1751         case TIOCOUTQ: {
1752                 long amount;
1753                 amount = sk->sndbuf - atomic_read(&sk->wmem_alloc);
1754                 if (amount < 0)
1755                         amount = 0;
1756                 if (put_user(amount, (unsigned int *)arg))
1757                         return -EFAULT;
1758                 return 0;
1759         }
1760         
1761         case TIOCINQ: {
1762                 struct sk_buff *skb;
1763                 long amount = 0L;
1764                 /* These two are safe on a single CPU system as only user tasks fiddle here */
1765                 if ((skb = skb_peek(&sk->receive_queue)) != NULL)
1766                         amount = skb->len;
1767                 if (put_user(amount, (unsigned int *)arg))
1768                         return -EFAULT;
1769                 return 0;
1770         }
1771         
1772         case SIOCGSTAMP:
1773                 if (sk != NULL) {
1774                         if (sk->stamp.tv_sec == 0)
1775                                 return -ENOENT;
1776                         if (copy_to_user((void *)arg, &sk->stamp, 
1777                                          sizeof(struct timeval)))
1778                                 return -EFAULT;
1779                         return 0;
1780                 }
1781                 return -EINVAL;
1782                 
1783         case SIOCGIFADDR:
1784         case SIOCSIFADDR:
1785         case SIOCGIFDSTADDR:
1786         case SIOCSIFDSTADDR:
1787         case SIOCGIFBRDADDR:
1788         case SIOCSIFBRDADDR:
1789         case SIOCGIFNETMASK:
1790         case SIOCSIFNETMASK:
1791         case SIOCGIFMETRIC:
1792         case SIOCSIFMETRIC:
1793                 return -EINVAL;         
1794         default:
1795                 IRDA_DEBUG(1, __FUNCTION__ "(), doing device ioctl!\n");
1796                 return dev_ioctl(cmd, (void *) arg);
1797         }
1798
1799         /*NOTREACHED*/
1800         return 0;
1801 }
1802
1803 /*
1804  * Function irda_setsockopt (sock, level, optname, optval, optlen)
1805  *
1806  *    Set some options for the socket
1807  *
1808  */
1809 static int irda_setsockopt(struct socket *sock, int level, int optname, 
1810                            char *optval, int optlen)
1811 {
1812         struct sock *sk = sock->sk;
1813         struct irda_sock *self;
1814         struct irda_ias_set    *ias_opt;
1815         struct ias_object      *ias_obj;
1816         struct ias_attrib *     ias_attr;       /* Attribute in IAS object */
1817         int opt;
1818         
1819         self = sk->protinfo.irda;
1820         ASSERT(self != NULL, return -1;);
1821
1822         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
1823
1824         if (level != SOL_IRLMP)
1825                 return -ENOPROTOOPT;
1826                 
1827         switch (optname) {
1828         case IRLMP_IAS_SET:
1829                 /* The user want to add an attribute to an existing IAS object
1830                  * (in the IAS database) or to create a new object with this
1831                  * attribute.
1832                  * We first query IAS to know if the object exist, and then
1833                  * create the right attribute...
1834                  */
1835
1836                 if (optlen != sizeof(struct irda_ias_set))
1837                         return -EINVAL;
1838         
1839                 ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
1840                 if (ias_opt == NULL)
1841                         return -ENOMEM;
1842
1843                 /* Copy query to the driver. */
1844                 if (copy_from_user(ias_opt, (char *)optval, optlen)) {
1845                         kfree(ias_opt);
1846                         return -EFAULT;
1847                 }
1848
1849                 /* Find the object we target.
1850                  * If the user gives us an empty string, we use the object
1851                  * associated with this socket. This will workaround
1852                  * duplicated class name - Jean II */
1853                 if(ias_opt->irda_class_name[0] == '\0') {
1854                         if(self->ias_obj == NULL) {
1855                                 kfree(ias_opt);
1856                                 return -EINVAL;
1857                         }
1858                         ias_obj = self->ias_obj;
1859                 } else
1860                         ias_obj = irias_find_object(ias_opt->irda_class_name);
1861
1862                 /* Only ROOT can mess with the global IAS database.
1863                  * Users can only add attributes to the object associated
1864                  * with the socket they own - Jean II */
1865                 if((!capable(CAP_NET_ADMIN)) &&
1866                    ((ias_obj == NULL) || (ias_obj != self->ias_obj))) {
1867                         kfree(ias_opt);
1868                         return -EPERM;
1869                 }
1870
1871                 /* If the object doesn't exist, create it */
1872                 if(ias_obj == (struct ias_object *) NULL) {
1873                         /* Create a new object */
1874                         ias_obj = irias_new_object(ias_opt->irda_class_name,
1875                                                    jiffies);
1876                 }
1877
1878                 /* Do we have the attribute already ? */
1879                 if(irias_find_attrib(ias_obj, ias_opt->irda_attrib_name)) {
1880                         kfree(ias_opt);
1881                         return -EINVAL;
1882                 }
1883
1884                 /* Look at the type */
1885                 switch(ias_opt->irda_attrib_type) {
1886                 case IAS_INTEGER:
1887                         /* Add an integer attribute */
1888                         irias_add_integer_attrib(
1889                                 ias_obj,
1890                                 ias_opt->irda_attrib_name, 
1891                                 ias_opt->attribute.irda_attrib_int,
1892                                 IAS_USER_ATTR);
1893                         break;
1894                 case IAS_OCT_SEQ:
1895                         /* Check length */
1896                         if(ias_opt->attribute.irda_attrib_octet_seq.len >
1897                            IAS_MAX_OCTET_STRING) {
1898                                 kfree(ias_opt);
1899                                 return -EINVAL;
1900                         }
1901                         /* Add an octet sequence attribute */
1902                         irias_add_octseq_attrib(
1903                               ias_obj,
1904                               ias_opt->irda_attrib_name, 
1905                               ias_opt->attribute.irda_attrib_octet_seq.octet_seq,
1906                               ias_opt->attribute.irda_attrib_octet_seq.len,
1907                               IAS_USER_ATTR);
1908                         break;
1909                 case IAS_STRING:
1910                         /* Should check charset & co */
1911                         /* Check length */
1912                         if(ias_opt->attribute.irda_attrib_string.len >
1913                            IAS_MAX_STRING) {
1914                                 kfree(ias_opt);
1915                                 return -EINVAL;
1916                         }
1917                         /* NULL terminate the string (avoid troubles) */
1918                         ias_opt->attribute.irda_attrib_string.string[ias_opt->attribute.irda_attrib_string.len] = '\0';
1919                         /* Add a string attribute */
1920                         irias_add_string_attrib(
1921                                 ias_obj,
1922                                 ias_opt->irda_attrib_name, 
1923                                 ias_opt->attribute.irda_attrib_string.string,
1924                                 IAS_USER_ATTR);
1925                         break;
1926                 default :
1927                         kfree(ias_opt);
1928                         return -EINVAL;
1929                 }
1930                 irias_insert_object(ias_obj);
1931                 kfree(ias_opt);
1932                 break;
1933         case IRLMP_IAS_DEL:
1934                 /* The user want to delete an object from our local IAS
1935                  * database. We just need to query the IAS, check is the
1936                  * object is not owned by the kernel and delete it.
1937                  */
1938
1939                 if (optlen != sizeof(struct irda_ias_set))
1940                         return -EINVAL;
1941         
1942                 ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
1943                 if (ias_opt == NULL)
1944                         return -ENOMEM;
1945         
1946                 /* Copy query to the driver. */
1947                 if (copy_from_user(ias_opt, (char *)optval, optlen)) {
1948                         kfree(ias_opt);
1949                         return -EFAULT;
1950                 }
1951
1952                 /* Find the object we target.
1953                  * If the user gives us an empty string, we use the object
1954                  * associated with this socket. This will workaround
1955                  * duplicated class name - Jean II */
1956                 if(ias_opt->irda_class_name[0] == '\0')
1957                         ias_obj = self->ias_obj;
1958                 else
1959                         ias_obj = irias_find_object(ias_opt->irda_class_name);
1960                 if(ias_obj == (struct ias_object *) NULL) {
1961                         kfree(ias_opt);
1962                         return -EINVAL;
1963                 }
1964
1965                 /* Only ROOT can mess with the global IAS database.
1966                  * Users can only del attributes from the object associated
1967                  * with the socket they own - Jean II */
1968                 if((!capable(CAP_NET_ADMIN)) &&
1969                    ((ias_obj == NULL) || (ias_obj != self->ias_obj))) {
1970                         kfree(ias_opt);
1971                         return -EPERM;
1972                 }
1973
1974                 /* Find the attribute (in the object) we target */
1975                 ias_attr = irias_find_attrib(ias_obj,
1976                                              ias_opt->irda_attrib_name); 
1977                 if(ias_attr == (struct ias_attrib *) NULL) {
1978                         kfree(ias_opt);
1979                         return -EINVAL;
1980                 }
1981
1982                 /* Check is the user space own the object */
1983                 if(ias_attr->value->owner != IAS_USER_ATTR) {
1984                         IRDA_DEBUG(1, __FUNCTION__ 
1985                                    "(), attempting to delete a kernel attribute\n");
1986                         kfree(ias_opt);
1987                         return -EPERM;
1988                 }
1989
1990                 /* Remove the attribute (and maybe the object) */
1991                 irias_delete_attrib(ias_obj, ias_attr);
1992                 kfree(ias_opt);
1993                 break;
1994         case IRLMP_MAX_SDU_SIZE:
1995                 if (optlen < sizeof(int))
1996                         return -EINVAL;
1997         
1998                 if (get_user(opt, (int *)optval))
1999                         return -EFAULT;
2000                 
2001                 /* Only possible for a seqpacket service (TTP with SAR) */
2002                 if (sk->type != SOCK_SEQPACKET) {
2003                         IRDA_DEBUG(2, __FUNCTION__ 
2004                                    "(), setting max_sdu_size = %d\n", opt);
2005                         self->max_sdu_size_rx = opt;
2006                 } else {
2007                         WARNING(__FUNCTION__ 
2008                                 "(), not allowed to set MAXSDUSIZE for this "
2009                                 "socket type!\n");
2010                         return -ENOPROTOOPT;
2011                 }
2012                 break;
2013         case IRLMP_HINTS_SET:
2014                 if (optlen < sizeof(int))
2015                         return -EINVAL;
2016         
2017                 if (get_user(opt, (int *)optval))
2018                         return -EFAULT;
2019
2020                 /* Unregister any old registration */
2021                 if (self->skey)
2022                         irlmp_unregister_service(self->skey);
2023
2024                 self->skey = irlmp_register_service((__u16) opt);
2025                 break;
2026         case IRLMP_HINT_MASK_SET:
2027                 /* As opposed to the previous case which set the hint bits
2028                  * that we advertise, this one set the filter we use when
2029                  * making a discovery (nodes which don't match any hint
2030                  * bit in the mask are not reported).
2031                  */
2032                 if (optlen < sizeof(int))
2033                         return -EINVAL;
2034         
2035                 if (get_user(opt, (int *)optval))
2036                         return -EFAULT;
2037
2038                 /* Set the new hint mask */
2039                 self->mask = (__u16) opt;
2040                 /* Mask out extension bits */
2041                 self->mask &= 0x7f7f;
2042                 /* Check if no bits */
2043                 if(!self->mask)
2044                         self->mask = 0xFFFF;
2045
2046                 break;
2047         default:
2048                 return -ENOPROTOOPT;
2049         }
2050         return 0;
2051 }
2052
2053 /*
2054  * Function irda_extract_ias_value(ias_opt, ias_value)
2055  *
2056  *    Translate internal IAS value structure to the user space representation
2057  *
2058  * The external representation of IAS values, as we exchange them with
2059  * user space program is quite different from the internal representation,
2060  * as stored in the IAS database (because we need a flat structure for
2061  * crossing kernel boundary).
2062  * This function transform the former in the latter. We also check
2063  * that the value type is valid.
2064  */
2065 static int irda_extract_ias_value(struct irda_ias_set *ias_opt,
2066                                   struct ias_value *ias_value)
2067 {
2068         /* Look at the type */
2069         switch (ias_value->type) {
2070         case IAS_INTEGER:
2071                 /* Copy the integer */
2072                 ias_opt->attribute.irda_attrib_int = ias_value->t.integer;
2073                 break;
2074         case IAS_OCT_SEQ:
2075                 /* Set length */
2076                 ias_opt->attribute.irda_attrib_octet_seq.len = ias_value->len;
2077                 /* Copy over */
2078                 memcpy(ias_opt->attribute.irda_attrib_octet_seq.octet_seq,
2079                        ias_value->t.oct_seq, ias_value->len);
2080                 break;
2081         case IAS_STRING:
2082                 /* Set length */
2083                 ias_opt->attribute.irda_attrib_string.len = ias_value->len;
2084                 ias_opt->attribute.irda_attrib_string.charset = ias_value->charset;
2085                 /* Copy over */
2086                 memcpy(ias_opt->attribute.irda_attrib_string.string,
2087                        ias_value->t.string, ias_value->len);
2088                 /* NULL terminate the string (avoid troubles) */
2089                 ias_opt->attribute.irda_attrib_string.string[ias_value->len] = '\0';
2090                 break;
2091         case IAS_MISSING:
2092         default :
2093                 return -EINVAL;
2094         }
2095         
2096         /* Copy type over */
2097         ias_opt->irda_attrib_type = ias_value->type;
2098         
2099         return 0;
2100 }
2101
2102 /*
2103  * Function irda_getsockopt (sock, level, optname, optval, optlen)
2104  *
2105  *    
2106  *
2107  */
2108 static int irda_getsockopt(struct socket *sock, int level, int optname, 
2109                            char *optval, int *optlen)
2110 {
2111         struct sock *sk = sock->sk;
2112         struct irda_sock *self;
2113         struct irda_device_list list;
2114         struct irda_device_info *discoveries;
2115         struct irda_ias_set *   ias_opt;        /* IAS get/query params */
2116         struct ias_object *     ias_obj;        /* Object in IAS */
2117         struct ias_attrib *     ias_attr;       /* Attribute in IAS object */
2118         int daddr = DEV_ADDR_ANY;       /* Dest address for IAS queries */
2119         int val = 0;
2120         int len = 0;
2121         int err;
2122         int offset, total;
2123
2124         self = sk->protinfo.irda;
2125
2126         IRDA_DEBUG(2, __FUNCTION__ "(%p)\n", self);
2127
2128         if (level != SOL_IRLMP)
2129                 return -ENOPROTOOPT;
2130
2131         if (get_user(len, optlen))
2132                 return -EFAULT;
2133
2134         if(len < 0)
2135                 return -EINVAL;
2136                 
2137         switch (optname) {
2138         case IRLMP_ENUMDEVICES:
2139                 /* Ask lmp for the current discovery log */
2140                 discoveries = irlmp_get_discoveries(&list.len, self->mask,
2141                                                     self->nslots);
2142                 /* Check if the we got some results */
2143                 if (discoveries == NULL)
2144                         return -EAGAIN;         /* Didn't find any devices */
2145                 err = 0;
2146
2147                 /* Write total list length back to client */
2148                 if (copy_to_user(optval, &list, 
2149                                  sizeof(struct irda_device_list) -
2150                                  sizeof(struct irda_device_info)))
2151                         err = -EFAULT;
2152
2153                 /* Offset to first device entry */
2154                 offset = sizeof(struct irda_device_list) - 
2155                         sizeof(struct irda_device_info);
2156
2157                 /* Copy the list itself - watch for overflow */
2158                 if(list.len > 2048)
2159                 {
2160                         err = -EINVAL;
2161                         goto bed;
2162                 }
2163                 total = offset + (list.len * sizeof(struct irda_device_info));
2164                 if (total > len)
2165                         total = len;
2166                 if (copy_to_user(optval+offset, discoveries, total - offset))
2167                         err = -EFAULT;
2168
2169                 /* Write total number of bytes used back to client */
2170                 if (put_user(total, optlen))
2171                         err = -EFAULT;
2172 bed:
2173                 /* Free up our buffer */
2174                 kfree(discoveries);
2175                 if (err)
2176                         return err;
2177                 break;
2178         case IRLMP_MAX_SDU_SIZE:
2179                 val = self->max_data_size;
2180                 len = sizeof(int);
2181                 if (put_user(len, optlen))
2182                         return -EFAULT;
2183                 
2184                 if (copy_to_user(optval, &val, len))
2185                         return -EFAULT;
2186                 break;
2187         case IRLMP_IAS_GET:
2188                 /* The user want an object from our local IAS database.
2189                  * We just need to query the IAS and return the value
2190                  * that we found */
2191
2192                 /* Check that the user has allocated the right space for us */
2193                 if (len != sizeof(struct irda_ias_set))
2194                         return -EINVAL;
2195
2196                 ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
2197                 if (ias_opt == NULL)
2198                         return -ENOMEM;
2199
2200                 /* Copy query to the driver. */
2201                 if (copy_from_user((char *) ias_opt, (char *)optval, len)) {
2202                         kfree(ias_opt);
2203                         return -EFAULT;
2204                 }
2205
2206                 /* Find the object we target.
2207                  * If the user gives us an empty string, we use the object
2208                  * associated with this socket. This will workaround
2209                  * duplicated class name - Jean II */
2210                 if(ias_opt->irda_class_name[0] == '\0')
2211                         ias_obj = self->ias_obj;
2212                 else
2213                         ias_obj = irias_find_object(ias_opt->irda_class_name);
2214                 if(ias_obj == (struct ias_object *) NULL) {
2215                         kfree(ias_opt);
2216                         return -EINVAL;
2217                 }
2218
2219                 /* Find the attribute (in the object) we target */
2220                 ias_attr = irias_find_attrib(ias_obj,
2221                                              ias_opt->irda_attrib_name); 
2222                 if(ias_attr == (struct ias_attrib *) NULL) {
2223                         kfree(ias_opt);
2224                         return -EINVAL;
2225                 }
2226
2227                 /* Translate from internal to user structure */
2228                 err = irda_extract_ias_value(ias_opt, ias_attr->value);
2229                 if(err) {
2230                         kfree(ias_opt);
2231                         return err;
2232                 }
2233
2234                 /* Copy reply to the user */
2235                 if (copy_to_user((char *)optval, (char *) ias_opt,
2236                                  sizeof(struct irda_ias_set))) {
2237                         kfree(ias_opt);
2238                         return -EFAULT;
2239                 }
2240                 /* Note : don't need to put optlen, we checked it */
2241                 kfree(ias_opt);
2242                 break;
2243         case IRLMP_IAS_QUERY:
2244                 /* The user want an object from a remote IAS database.
2245                  * We need to use IAP to query the remote database and
2246                  * then wait for the answer to come back. */
2247
2248                 /* Check that the user has allocated the right space for us */
2249                 if (len != sizeof(struct irda_ias_set))
2250                         return -EINVAL;
2251
2252                 ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
2253                 if (ias_opt == NULL)
2254                         return -ENOMEM;
2255
2256                 /* Copy query to the driver. */
2257                 if (copy_from_user((char *) ias_opt, (char *)optval, len)) {
2258                         kfree(ias_opt);
2259                         return -EFAULT;
2260                 }
2261
2262                 /* At this point, there are two cases...
2263                  * 1) the socket is connected - that's the easy case, we
2264                  *      just query the device we are connected to...
2265                  * 2) the socket is not connected - the user doesn't want
2266                  *      to connect and/or may not have a valid service name
2267                  *      (so can't create a fake connection). In this case,
2268                  *      we assume that the user pass us a valid destination
2269                  *      address in the requesting structure...
2270                  */
2271                 if(self->daddr != DEV_ADDR_ANY) {
2272                         /* We are connected - reuse known daddr */
2273                         daddr = self->daddr;
2274                 } else {
2275                         /* We are not connected, we must specify a valid
2276                          * destination address */
2277                         daddr = ias_opt->daddr;
2278                         if((!daddr) || (daddr == DEV_ADDR_ANY)) {
2279                                 kfree(ias_opt);
2280                                 return -EINVAL;
2281                         }
2282                 }
2283
2284                 /* Check that we can proceed with IAP */
2285                 if (self->iriap) {
2286                         WARNING(__FUNCTION__
2287                                 "(), busy with a previous query\n");
2288                         kfree(ias_opt);
2289                         return -EBUSY;
2290                 }
2291
2292                 self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self,
2293                                          irda_getvalue_confirm);
2294
2295                 /* Treat unexpected signals as disconnect */
2296                 self->errno = -EHOSTUNREACH;
2297
2298                 /* Query remote LM-IAS */
2299                 iriap_getvaluebyclass_request(self->iriap,
2300                                               self->saddr, daddr,
2301                                               ias_opt->irda_class_name,
2302                                               ias_opt->irda_attrib_name);
2303                 /* Wait for answer (if not already failed) */
2304                 if(self->iriap != NULL)
2305                         interruptible_sleep_on(&self->query_wait);
2306                 /* Check what happened */
2307                 if (self->errno)
2308                 {
2309                         kfree(ias_opt);
2310                         /* Requested object/attribute doesn't exist */
2311                         if((self->errno == IAS_CLASS_UNKNOWN) ||
2312                            (self->errno == IAS_ATTRIB_UNKNOWN))
2313                                 return (-EADDRNOTAVAIL);
2314                         else
2315                                 return (-EHOSTUNREACH);
2316                 }
2317
2318                 /* Translate from internal to user structure */
2319                 err = irda_extract_ias_value(ias_opt, self->ias_result);
2320                 if (self->ias_result)
2321                         irias_delete_value(self->ias_result);
2322                 if (err) {
2323                         kfree(ias_opt);
2324                         return err;
2325                 }
2326
2327                 /* Copy reply to the user */
2328                 if (copy_to_user((char *)optval, (char *) ias_opt,
2329                                  sizeof(struct irda_ias_set))) {
2330                         kfree(ias_opt);
2331                         return -EFAULT;
2332                 }
2333                 /* Note : don't need to put optlen, we checked it */
2334                 kfree(ias_opt);
2335                 break;
2336         case IRLMP_WAITDEVICE:
2337                 /* This function is just another way of seeing life ;-)
2338                  * IRLMP_ENUMDEVICES assumes that you have a static network,
2339                  * and that you just want to pick one of the devices present.
2340                  * On the other hand, in here we assume that no device is
2341                  * present and that at some point in the future a device will
2342                  * come into range. When this device arrive, we just wake
2343                  * up the caller, so that he has time to connect to it before
2344                  * the device goes away...
2345                  * Note : once the node has been discovered for more than a
2346                  * few second, it won't trigger this function, unless it
2347                  * goes away and come back changes its hint bits (so we
2348                  * might call it IRLMP_WAITNEWDEVICE).
2349                  */
2350
2351                 /* Check that the user is passing us an int */
2352                 if (len != sizeof(int))
2353                         return -EINVAL;
2354                 /* Get timeout in ms (max time we block the caller) */
2355                 if (get_user(val, (int *)optval))
2356                         return -EFAULT;
2357
2358                 /* Tell IrLMP we want to be notified */
2359                 irlmp_update_client(self->ckey, self->mask,
2360                                     irda_selective_discovery_indication,
2361                                     NULL, (void *) self);
2362                 
2363                 /* Do some discovery (and also return cached results) */
2364                 irlmp_discovery_request(self->nslots);
2365                 
2366                 /* Wait until a node is discovered */
2367                 if (!self->cachediscovery) {
2368                         IRDA_DEBUG(1, __FUNCTION__ 
2369                                    "(), nothing discovered yet, going to sleep...\n");
2370
2371                         /* Set watchdog timer to expire in <val> ms. */
2372                         self->watchdog.function = irda_discovery_timeout;
2373                         self->watchdog.data = (unsigned long) self;
2374                         self->watchdog.expires = jiffies + (val * HZ/1000);
2375                         add_timer(&(self->watchdog));
2376
2377                         /* Wait for IR-LMP to call us back */
2378                         interruptible_sleep_on(&self->query_wait);
2379
2380                         /* If watchdog is still activated, kill it! */
2381                         if(timer_pending(&(self->watchdog)))
2382                                 del_timer(&(self->watchdog));
2383
2384                         IRDA_DEBUG(1, __FUNCTION__ 
2385                                    "(), ...waking up !\n");
2386                 }
2387                 else
2388                         IRDA_DEBUG(1, __FUNCTION__ 
2389                                    "(), found immediately !\n");
2390
2391                 /* Tell IrLMP that we have been notified */
2392                 irlmp_update_client(self->ckey, self->mask, NULL, NULL, NULL);
2393
2394                 /* Check if the we got some results */
2395                 if (!self->cachediscovery)
2396                         return -EAGAIN;         /* Didn't find any devices */
2397                 /* Cleanup */
2398                 self->cachediscovery = NULL;
2399
2400                 /* Note : We don't return anything to the user.
2401                  * We could return the device that triggered the wake up,
2402                  * but it's probably better to force the user to query
2403                  * the whole discovery log and let him pick one device...
2404                  */
2405                 break;
2406         default:
2407                 return -ENOPROTOOPT;
2408         }
2409         
2410         return 0;
2411 }
2412
2413 static struct net_proto_family irda_family_ops =
2414 {
2415         PF_IRDA,
2416         irda_create
2417 };
2418
2419 static struct proto_ops SOCKOPS_WRAPPED(irda_stream_ops) = {
2420         family:         PF_IRDA,
2421         
2422         release:        irda_release,
2423         bind:           irda_bind,
2424         connect:        irda_connect,
2425         socketpair:     sock_no_socketpair,
2426         accept:         irda_accept,
2427         getname:        irda_getname,
2428         poll:           irda_poll,
2429         ioctl:          irda_ioctl,
2430         listen:         irda_listen,
2431         shutdown:       irda_shutdown,
2432         setsockopt:     irda_setsockopt,
2433         getsockopt:     irda_getsockopt,
2434         sendmsg:        irda_sendmsg,
2435         recvmsg:        irda_recvmsg_stream,
2436         mmap:           sock_no_mmap,
2437         sendpage:       sock_no_sendpage,
2438 };
2439
2440 static struct proto_ops SOCKOPS_WRAPPED(irda_seqpacket_ops) = {
2441         family:         PF_IRDA,
2442         
2443         release:        irda_release,
2444         bind:           irda_bind,
2445         connect:        irda_connect,
2446         socketpair:     sock_no_socketpair,
2447         accept:         irda_accept,
2448         getname:        irda_getname,
2449         poll:           datagram_poll,
2450         ioctl:          irda_ioctl,
2451         listen:         irda_listen,
2452         shutdown:       irda_shutdown,
2453         setsockopt:     irda_setsockopt,
2454         getsockopt:     irda_getsockopt,
2455         sendmsg:        irda_sendmsg,
2456         recvmsg:        irda_recvmsg_dgram,
2457         mmap:           sock_no_mmap,
2458         sendpage:       sock_no_sendpage,
2459 };
2460
2461 static struct proto_ops SOCKOPS_WRAPPED(irda_dgram_ops) = {
2462         family:         PF_IRDA,
2463        
2464         release:        irda_release,
2465         bind:           irda_bind,
2466         connect:        irda_connect,
2467         socketpair:     sock_no_socketpair,
2468         accept:         irda_accept,
2469         getname:        irda_getname,
2470         poll:           datagram_poll,
2471         ioctl:          irda_ioctl,
2472         listen:         irda_listen,
2473         shutdown:       irda_shutdown,
2474         setsockopt:     irda_setsockopt,
2475         getsockopt:     irda_getsockopt,
2476         sendmsg:        irda_sendmsg_dgram,
2477         recvmsg:        irda_recvmsg_dgram,
2478         mmap:           sock_no_mmap,
2479         sendpage:       sock_no_sendpage,
2480 };
2481
2482 #ifdef CONFIG_IRDA_ULTRA
2483 static struct proto_ops SOCKOPS_WRAPPED(irda_ultra_ops) = {
2484         family:         PF_IRDA,
2485        
2486         release:        irda_release,
2487         bind:           irda_bind,
2488         connect:        sock_no_connect,
2489         socketpair:     sock_no_socketpair,
2490         accept:         sock_no_accept,
2491         getname:        irda_getname,
2492         poll:           datagram_poll,
2493         ioctl:          irda_ioctl,
2494         listen:         sock_no_listen,
2495         shutdown:       irda_shutdown,
2496         setsockopt:     irda_setsockopt,
2497         getsockopt:     irda_getsockopt,
2498         sendmsg:        irda_sendmsg_ultra,
2499         recvmsg:        irda_recvmsg_dgram,
2500         mmap:           sock_no_mmap,
2501         sendpage:       sock_no_sendpage,
2502 };
2503 #endif /* CONFIG_IRDA_ULTRA */
2504
2505 #include <linux/smp_lock.h>
2506 SOCKOPS_WRAP(irda_stream, PF_IRDA);
2507 SOCKOPS_WRAP(irda_seqpacket, PF_IRDA);
2508 SOCKOPS_WRAP(irda_dgram, PF_IRDA);
2509 #ifdef CONFIG_IRDA_ULTRA
2510 SOCKOPS_WRAP(irda_ultra, PF_IRDA);
2511 #endif /* CONFIG_IRDA_ULTRA */
2512
2513 /*
2514  * Function irda_device_event (this, event, ptr)
2515  *
2516  *    Called when a device is taken up or down
2517  *
2518  */
2519 static int irda_device_event(struct notifier_block *this, unsigned long event,
2520                              void *ptr)
2521 {
2522         struct net_device *dev = (struct net_device *) ptr;
2523         
2524         /* Reject non IrDA devices */
2525         if (dev->type != ARPHRD_IRDA) 
2526                 return NOTIFY_DONE;
2527         
2528         switch (event) {
2529         case NETDEV_UP:
2530                 IRDA_DEBUG(3, __FUNCTION__ "(), NETDEV_UP\n");
2531                 /* irda_dev_device_up(dev); */
2532                 break;
2533         case NETDEV_DOWN:
2534                 IRDA_DEBUG(3, __FUNCTION__ "(), NETDEV_DOWN\n");
2535                 /* irda_kill_by_device(dev); */
2536                 /* irda_rt_device_down(dev); */
2537                 /* irda_dev_device_down(dev); */
2538                 break;
2539         default:
2540                 break;
2541         }
2542
2543         return NOTIFY_DONE;
2544 }
2545
2546 static struct packet_type irda_packet_type = 
2547 {
2548         0,      /* MUTTER ntohs(ETH_P_IRDA),*/
2549         NULL,
2550         irlap_driver_rcv,
2551         NULL,
2552         NULL,
2553 };
2554
2555 static struct notifier_block irda_dev_notifier = {
2556         irda_device_event,
2557         NULL,
2558         0
2559 };
2560
2561 /*
2562  * Function irda_proc_modcount (inode, fill)
2563  *
2564  *    Use by the proc file system functions to prevent the irda module
2565  *    being removed while the use is standing in the net/irda directory
2566  */
2567 void irda_proc_modcount(struct inode *inode, int fill)
2568 {
2569 #ifdef MODULE
2570 #ifdef CONFIG_PROC_FS
2571         if (fill)
2572                 MOD_INC_USE_COUNT;
2573         else
2574                 MOD_DEC_USE_COUNT;
2575 #endif /* CONFIG_PROC_FS */
2576 #endif /* MODULE */
2577 }
2578
2579 /*
2580  * Function irda_proto_init (pro)
2581  *
2582  *    Initialize IrDA protocol layer
2583  *
2584  */
2585 int __init irda_proto_init(void)
2586 {
2587         sock_register(&irda_family_ops);
2588
2589         irda_packet_type.type = htons(ETH_P_IRDA);
2590         dev_add_pack(&irda_packet_type);
2591
2592         register_netdevice_notifier(&irda_dev_notifier);
2593
2594         irda_init();
2595 #ifdef MODULE
2596         irda_device_init();  /* Called by init/main.c when non-modular */
2597 #endif
2598         return 0;
2599 }
2600 #ifdef MODULE
2601 module_init(irda_proto_init);   /* If non-module, called from init/main.c */
2602 #endif
2603
2604 /*
2605  * Function irda_proto_cleanup (void)
2606  *
2607  *    Remove IrDA protocol layer
2608  *
2609  */
2610 #ifdef MODULE
2611 void irda_proto_cleanup(void)
2612 {
2613         irda_packet_type.type = htons(ETH_P_IRDA);
2614         dev_remove_pack(&irda_packet_type);
2615
2616         unregister_netdevice_notifier(&irda_dev_notifier);
2617         
2618         sock_unregister(PF_IRDA);
2619         irda_cleanup();
2620         
2621         return;
2622 }
2623 module_exit(irda_proto_cleanup);
2624  
2625 MODULE_AUTHOR("Dag Brattli <dagb@cs.uit.no>");
2626 MODULE_DESCRIPTION("The Linux IrDA Protocol Subsystem"); 
2627 MODULE_LICENSE("GPL");
2628 #ifdef CONFIG_IRDA_DEBUG
2629 MODULE_PARM(irda_debug, "1l");
2630 #endif
2631 #endif /* MODULE */