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