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