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