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