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