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