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