Linux-2.6.12-rc2
[safe/jmp/linux-2.6] / net / irda / irttp.c
1 /*********************************************************************
2  *                
3  * Filename:      irttp.c
4  * Version:       1.2
5  * Description:   Tiny Transport Protocol (TTP) implementation
6  * Status:        Stable
7  * Author:        Dag Brattli <dagb@cs.uit.no>
8  * Created at:    Sun Aug 31 20:14:31 1997
9  * Modified at:   Wed Jan  5 11:31:27 2000
10  * Modified by:   Dag Brattli <dagb@cs.uit.no>
11  * 
12  *     Copyright (c) 1998-2000 Dag Brattli <dagb@cs.uit.no>, 
13  *     All Rights Reserved.
14  *     Copyright (c) 2000-2003 Jean Tourrilhes <jt@hpl.hp.com>
15  *     
16  *     This program is free software; you can redistribute it and/or 
17  *     modify it under the terms of the GNU General Public License as 
18  *     published by the Free Software Foundation; either version 2 of 
19  *     the License, or (at your option) any later version.
20  *
21  *     Neither Dag Brattli nor University of Tromsø admit liability nor
22  *     provide warranty for any of this software. This material is 
23  *     provided "AS-IS" and at no charge.
24  *
25  ********************************************************************/
26
27 #include <linux/config.h>
28 #include <linux/skbuff.h>
29 #include <linux/init.h>
30 #include <linux/seq_file.h>
31
32 #include <asm/byteorder.h>
33 #include <asm/unaligned.h>
34
35 #include <net/irda/irda.h>
36 #include <net/irda/irlap.h>
37 #include <net/irda/irlmp.h>
38 #include <net/irda/parameters.h>
39 #include <net/irda/irttp.h>
40
41 static struct irttp_cb *irttp = NULL;
42
43 static void __irttp_close_tsap(struct tsap_cb *self);
44
45 static int irttp_data_indication(void *instance, void *sap, 
46                                  struct sk_buff *skb);
47 static int irttp_udata_indication(void *instance, void *sap, 
48                                   struct sk_buff *skb);
49 static void irttp_disconnect_indication(void *instance, void *sap,  
50                                         LM_REASON reason, struct sk_buff *);
51 static void irttp_connect_indication(void *instance, void *sap, 
52                                      struct qos_info *qos, __u32 max_sdu_size,
53                                      __u8 header_size, struct sk_buff *skb);
54 static void irttp_connect_confirm(void *instance, void *sap, 
55                                   struct qos_info *qos, __u32 max_sdu_size, 
56                                   __u8 header_size, struct sk_buff *skb);
57 static void irttp_run_tx_queue(struct tsap_cb *self);
58 static void irttp_run_rx_queue(struct tsap_cb *self);
59
60 static void irttp_flush_queues(struct tsap_cb *self);
61 static void irttp_fragment_skb(struct tsap_cb *self, struct sk_buff *skb);
62 static struct sk_buff *irttp_reassemble_skb(struct tsap_cb *self);
63 static void irttp_todo_expired(unsigned long data);
64 static int irttp_param_max_sdu_size(void *instance, irda_param_t *param, 
65                                     int get);
66
67 static void irttp_flow_indication(void *instance, void *sap, LOCAL_FLOW flow);
68 static void irttp_status_indication(void *instance,
69                                     LINK_STATUS link, LOCK_STATUS lock);
70
71 /* Information for parsing parameters in IrTTP */
72 static pi_minor_info_t pi_minor_call_table[] = {
73         { NULL, 0 },                                             /* 0x00 */
74         { irttp_param_max_sdu_size, PV_INTEGER | PV_BIG_ENDIAN } /* 0x01 */
75 };
76 static pi_major_info_t pi_major_call_table[] = {{ pi_minor_call_table, 2 }};
77 static pi_param_info_t param_info = { pi_major_call_table, 1, 0x0f, 4 };
78
79 /************************ GLOBAL PROCEDURES ************************/
80
81 /*
82  * Function irttp_init (void)
83  *
84  *    Initialize the IrTTP layer. Called by module initialization code
85  *
86  */
87 int __init irttp_init(void)
88 {
89         /* Initialize the irttp structure. */
90         if (irttp == NULL) {
91                 irttp = kmalloc(sizeof(struct irttp_cb), GFP_KERNEL);
92                 if (irttp == NULL)
93                         return -ENOMEM;
94         }
95         memset(irttp, 0, sizeof(struct irttp_cb));
96
97         irttp->magic = TTP_MAGIC;
98
99         irttp->tsaps = hashbin_new(HB_LOCK);
100         if (!irttp->tsaps) {
101                 IRDA_ERROR("%s: can't allocate IrTTP hashbin!\n",
102                            __FUNCTION__);
103                 return -ENOMEM;
104         }
105
106         return 0;
107 }
108
109 /*
110  * Function irttp_cleanup (void)
111  *
112  *    Called by module destruction/cleanup code
113  *
114  */
115 void __exit irttp_cleanup(void) 
116 {
117         /* Check for main structure */
118         IRDA_ASSERT(irttp != NULL, return;);
119         IRDA_ASSERT(irttp->magic == TTP_MAGIC, return;);
120
121         /*
122          *  Delete hashbin and close all TSAP instances in it
123          */
124         hashbin_delete(irttp->tsaps, (FREE_FUNC) __irttp_close_tsap);
125
126         irttp->magic = 0;
127
128         /* De-allocate main structure */
129         kfree(irttp);
130
131         irttp = NULL;
132 }
133
134 /*************************** SUBROUTINES ***************************/
135
136 /*
137  * Function irttp_start_todo_timer (self, timeout)
138  *
139  *    Start todo timer.
140  *
141  * Made it more effient and unsensitive to race conditions - Jean II
142  */
143 static inline void irttp_start_todo_timer(struct tsap_cb *self, int timeout)
144 {
145         /* Set new value for timer */
146         mod_timer(&self->todo_timer, jiffies + timeout);
147 }
148
149 /*
150  * Function irttp_todo_expired (data)
151  *
152  *    Todo timer has expired!
153  *
154  * One of the restriction of the timer is that it is run only on the timer
155  * interrupt which run every 10ms. This mean that even if you set the timer
156  * with a delay of 0, it may take up to 10ms before it's run.
157  * So, to minimise latency and keep cache fresh, we try to avoid using
158  * it as much as possible.
159  * Note : we can't use tasklets, because they can't be asynchronously
160  * killed (need user context), and we can't guarantee that here...
161  * Jean II
162  */
163 static void irttp_todo_expired(unsigned long data)
164 {
165         struct tsap_cb *self = (struct tsap_cb *) data;
166
167         /* Check that we still exist */
168         if (!self || self->magic != TTP_TSAP_MAGIC)
169                 return;
170
171         IRDA_DEBUG(4, "%s(instance=%p)\n", __FUNCTION__, self);
172
173         /* Try to make some progress, especially on Tx side - Jean II */
174         irttp_run_rx_queue(self);
175         irttp_run_tx_queue(self);
176
177         /* Check if time for disconnect */
178         if (test_bit(0, &self->disconnect_pend)) {
179                 /* Check if it's possible to disconnect yet */
180                 if (skb_queue_empty(&self->tx_queue)) {
181                         /* Make sure disconnect is not pending anymore */
182                         clear_bit(0, &self->disconnect_pend);   /* FALSE */
183
184                         /* Note : self->disconnect_skb may be NULL */
185                         irttp_disconnect_request(self, self->disconnect_skb,
186                                                  P_NORMAL);
187                         self->disconnect_skb = NULL;
188                 } else {
189                         /* Try again later */
190                         irttp_start_todo_timer(self, HZ/10);
191
192                         /* No reason to try and close now */
193                         return;
194                 }
195         }
196
197         /* Check if it's closing time */
198         if (self->close_pend)
199                 /* Finish cleanup */
200                 irttp_close_tsap(self);
201 }
202
203 /*
204  * Function irttp_flush_queues (self)
205  *
206  *     Flushes (removes all frames) in transitt-buffer (tx_list)
207  */
208 void irttp_flush_queues(struct tsap_cb *self)
209 {
210         struct sk_buff* skb;
211
212         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
213
214         IRDA_ASSERT(self != NULL, return;);
215         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
216
217         /* Deallocate frames waiting to be sent */
218         while ((skb = skb_dequeue(&self->tx_queue)) != NULL)
219                 dev_kfree_skb(skb);
220
221         /* Deallocate received frames */
222         while ((skb = skb_dequeue(&self->rx_queue)) != NULL)
223                 dev_kfree_skb(skb);
224
225         /* Deallocate received fragments */
226         while ((skb = skb_dequeue(&self->rx_fragments)) != NULL)
227                 dev_kfree_skb(skb);
228 }
229
230 /*
231  * Function irttp_reassemble (self)
232  *
233  *    Makes a new (continuous) skb of all the fragments in the fragment
234  *    queue
235  *
236  */
237 static struct sk_buff *irttp_reassemble_skb(struct tsap_cb *self)
238 {
239         struct sk_buff *skb, *frag;
240         int n = 0;  /* Fragment index */
241
242         IRDA_ASSERT(self != NULL, return NULL;);
243         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return NULL;);
244
245         IRDA_DEBUG(2, "%s(), self->rx_sdu_size=%d\n", __FUNCTION__,
246                    self->rx_sdu_size);
247
248         skb = dev_alloc_skb(TTP_HEADER + self->rx_sdu_size);
249         if (!skb)
250                 return NULL;
251
252         /*
253          * Need to reserve space for TTP header in case this skb needs to
254          * be requeued in case delivery failes
255          */
256         skb_reserve(skb, TTP_HEADER);
257         skb_put(skb, self->rx_sdu_size);
258
259         /*
260          *  Copy all fragments to a new buffer
261          */
262         while ((frag = skb_dequeue(&self->rx_fragments)) != NULL) {
263                 memcpy(skb->data+n, frag->data, frag->len);
264                 n += frag->len;
265
266                 dev_kfree_skb(frag);
267         }
268
269         IRDA_DEBUG(2,
270                    "%s(), frame len=%d, rx_sdu_size=%d, rx_max_sdu_size=%d\n",
271                    __FUNCTION__, n, self->rx_sdu_size, self->rx_max_sdu_size);
272         /* Note : irttp_run_rx_queue() calculate self->rx_sdu_size
273          * by summing the size of all fragments, so we should always
274          * have n == self->rx_sdu_size, except in cases where we
275          * droped the last fragment (when self->rx_sdu_size exceed
276          * self->rx_max_sdu_size), where n < self->rx_sdu_size.
277          * Jean II */
278         IRDA_ASSERT(n <= self->rx_sdu_size, n = self->rx_sdu_size;);
279
280         /* Set the new length */
281         skb_trim(skb, n);
282
283         self->rx_sdu_size = 0;
284
285         return skb;
286 }
287
288 /*
289  * Function irttp_fragment_skb (skb)
290  *
291  *    Fragments a frame and queues all the fragments for transmission
292  *
293  */
294 static inline void irttp_fragment_skb(struct tsap_cb *self,
295                                       struct sk_buff *skb)
296 {
297         struct sk_buff *frag;
298         __u8 *frame;
299
300         IRDA_DEBUG(2, "%s()\n", __FUNCTION__);
301
302         IRDA_ASSERT(self != NULL, return;);
303         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
304         IRDA_ASSERT(skb != NULL, return;);
305
306         /*
307          *  Split frame into a number of segments
308          */
309         while (skb->len > self->max_seg_size) {
310                 IRDA_DEBUG(2, "%s(), fragmenting ...\n", __FUNCTION__);
311
312                 /* Make new segment */
313                 frag = dev_alloc_skb(self->max_seg_size+self->max_header_size);
314                 if (!frag)
315                         return;
316
317                 skb_reserve(frag, self->max_header_size);
318
319                 /* Copy data from the original skb into this fragment. */
320                 memcpy(skb_put(frag, self->max_seg_size), skb->data,
321                        self->max_seg_size);
322
323                 /* Insert TTP header, with the more bit set */
324                 frame = skb_push(frag, TTP_HEADER);
325                 frame[0] = TTP_MORE;
326
327                 /* Hide the copied data from the original skb */
328                 skb_pull(skb, self->max_seg_size);
329
330                 /* Queue fragment */
331                 skb_queue_tail(&self->tx_queue, frag);
332         }
333         /* Queue what is left of the original skb */
334         IRDA_DEBUG(2, "%s(), queuing last segment\n", __FUNCTION__);
335
336         frame = skb_push(skb, TTP_HEADER);
337         frame[0] = 0x00; /* Clear more bit */
338
339         /* Queue fragment */
340         skb_queue_tail(&self->tx_queue, skb);
341 }
342
343 /*
344  * Function irttp_param_max_sdu_size (self, param)
345  *
346  *    Handle the MaxSduSize parameter in the connect frames, this function
347  *    will be called both when this parameter needs to be inserted into, and
348  *    extracted from the connect frames
349  */
350 static int irttp_param_max_sdu_size(void *instance, irda_param_t *param,
351                                     int get)
352 {
353         struct tsap_cb *self;
354
355         self = (struct tsap_cb *) instance;
356
357         IRDA_ASSERT(self != NULL, return -1;);
358         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
359
360         if (get)
361                 param->pv.i = self->tx_max_sdu_size;
362         else
363                 self->tx_max_sdu_size = param->pv.i;
364
365         IRDA_DEBUG(1, "%s(), MaxSduSize=%d\n", __FUNCTION__, param->pv.i);
366
367         return 0;
368 }
369
370 /*************************** CLIENT CALLS ***************************/
371 /************************** LMP CALLBACKS **************************/
372 /* Everything is happily mixed up. Waiting for next clean up - Jean II */
373
374 /*
375  * Function irttp_open_tsap (stsap, notify)
376  *
377  *    Create TSAP connection endpoint,
378  */
379 struct tsap_cb *irttp_open_tsap(__u8 stsap_sel, int credit, notify_t *notify)
380 {
381         struct tsap_cb *self;
382         struct lsap_cb *lsap;
383         notify_t ttp_notify;
384
385         IRDA_ASSERT(irttp != NULL, return NULL;);
386         IRDA_ASSERT(irttp->magic == TTP_MAGIC, return NULL;);
387
388         /* The IrLMP spec (IrLMP 1.1 p10) says that we have the right to
389          * use only 0x01-0x6F. Of course, we can use LSAP_ANY as well.
390          * JeanII */
391         if((stsap_sel != LSAP_ANY) &&
392            ((stsap_sel < 0x01) || (stsap_sel >= 0x70))) {
393                 IRDA_DEBUG(0, "%s(), invalid tsap!\n", __FUNCTION__);
394                 return NULL;
395         }
396
397         self = kmalloc(sizeof(struct tsap_cb), GFP_ATOMIC);
398         if (self == NULL) {
399                 IRDA_DEBUG(0, "%s(), unable to kmalloc!\n", __FUNCTION__);
400                 return NULL;
401         }
402         memset(self, 0, sizeof(struct tsap_cb));
403         spin_lock_init(&self->lock);
404
405         /* Initialise todo timer */
406         init_timer(&self->todo_timer);
407         self->todo_timer.data     = (unsigned long) self;
408         self->todo_timer.function = &irttp_todo_expired;
409
410         /* Initialize callbacks for IrLMP to use */
411         irda_notify_init(&ttp_notify);
412         ttp_notify.connect_confirm = irttp_connect_confirm;
413         ttp_notify.connect_indication = irttp_connect_indication;
414         ttp_notify.disconnect_indication = irttp_disconnect_indication;
415         ttp_notify.data_indication = irttp_data_indication;
416         ttp_notify.udata_indication = irttp_udata_indication;
417         ttp_notify.flow_indication = irttp_flow_indication;
418         if(notify->status_indication != NULL)
419                 ttp_notify.status_indication = irttp_status_indication;
420         ttp_notify.instance = self;
421         strncpy(ttp_notify.name, notify->name, NOTIFY_MAX_NAME);
422
423         self->magic = TTP_TSAP_MAGIC;
424         self->connected = FALSE;
425
426         skb_queue_head_init(&self->rx_queue);
427         skb_queue_head_init(&self->tx_queue);
428         skb_queue_head_init(&self->rx_fragments);
429         /*
430          *  Create LSAP at IrLMP layer
431          */
432         lsap = irlmp_open_lsap(stsap_sel, &ttp_notify, 0);
433         if (lsap == NULL) {
434                 IRDA_WARNING("%s: unable to allocate LSAP!!\n", __FUNCTION__);
435                 return NULL;
436         }
437
438         /*
439          *  If user specified LSAP_ANY as source TSAP selector, then IrLMP
440          *  will replace it with whatever source selector which is free, so
441          *  the stsap_sel we have might not be valid anymore
442          */
443         self->stsap_sel = lsap->slsap_sel;
444         IRDA_DEBUG(4, "%s(), stsap_sel=%02x\n", __FUNCTION__, self->stsap_sel);
445
446         self->notify = *notify;
447         self->lsap = lsap;
448
449         hashbin_insert(irttp->tsaps, (irda_queue_t *) self, (long) self, NULL);
450
451         if (credit > TTP_RX_MAX_CREDIT)
452                 self->initial_credit = TTP_RX_MAX_CREDIT;
453         else
454                 self->initial_credit = credit;
455
456         return self;
457 }
458 EXPORT_SYMBOL(irttp_open_tsap);
459
460 /*
461  * Function irttp_close (handle)
462  *
463  *    Remove an instance of a TSAP. This function should only deal with the
464  *    deallocation of the TSAP, and resetting of the TSAPs values;
465  *
466  */
467 static void __irttp_close_tsap(struct tsap_cb *self)
468 {
469         /* First make sure we're connected. */
470         IRDA_ASSERT(self != NULL, return;);
471         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
472
473         irttp_flush_queues(self);
474
475         del_timer(&self->todo_timer);
476
477         /* This one won't be cleaned up if we are disconnect_pend + close_pend
478          * and we receive a disconnect_indication */
479         if (self->disconnect_skb)
480                 dev_kfree_skb(self->disconnect_skb);
481
482         self->connected = FALSE;
483         self->magic = ~TTP_TSAP_MAGIC;
484
485         kfree(self);
486 }
487
488 /*
489  * Function irttp_close (self)
490  *
491  *    Remove TSAP from list of all TSAPs and then deallocate all resources
492  *    associated with this TSAP
493  *
494  * Note : because we *free* the tsap structure, it is the responsibility
495  * of the caller to make sure we are called only once and to deal with
496  * possible race conditions. - Jean II
497  */
498 int irttp_close_tsap(struct tsap_cb *self)
499 {
500         struct tsap_cb *tsap;
501
502         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
503
504         IRDA_ASSERT(self != NULL, return -1;);
505         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
506
507         /* Make sure tsap has been disconnected */
508         if (self->connected) {
509                 /* Check if disconnect is not pending */
510                 if (!test_bit(0, &self->disconnect_pend)) {
511                         IRDA_WARNING("%s: TSAP still connected!\n",
512                                      __FUNCTION__);
513                         irttp_disconnect_request(self, NULL, P_NORMAL);
514                 }
515                 self->close_pend = TRUE;
516                 irttp_start_todo_timer(self, HZ/10);
517
518                 return 0; /* Will be back! */
519         }
520
521         tsap = hashbin_remove(irttp->tsaps, (long) self, NULL);
522
523         IRDA_ASSERT(tsap == self, return -1;);
524
525         /* Close corresponding LSAP */
526         if (self->lsap) {
527                 irlmp_close_lsap(self->lsap);
528                 self->lsap = NULL;
529         }
530
531         __irttp_close_tsap(self);
532
533         return 0;
534 }
535 EXPORT_SYMBOL(irttp_close_tsap);
536
537 /*
538  * Function irttp_udata_request (self, skb)
539  *
540  *    Send unreliable data on this TSAP
541  *
542  */
543 int irttp_udata_request(struct tsap_cb *self, struct sk_buff *skb)
544 {
545         IRDA_ASSERT(self != NULL, return -1;);
546         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
547         IRDA_ASSERT(skb != NULL, return -1;);
548
549         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
550
551         /* Check that nothing bad happens */
552         if ((skb->len == 0) || (!self->connected)) {
553                 IRDA_DEBUG(1, "%s(), No data, or not connected\n",
554                            __FUNCTION__);
555                 goto err;
556         }
557
558         if (skb->len > self->max_seg_size) {
559                 IRDA_DEBUG(1, "%s(), UData is to large for IrLAP!\n",
560                            __FUNCTION__);
561                 goto err;
562         }
563
564         irlmp_udata_request(self->lsap, skb);
565         self->stats.tx_packets++;
566
567         return 0;
568
569 err:
570         dev_kfree_skb(skb);
571         return -1;
572 }
573 EXPORT_SYMBOL(irttp_udata_request);
574
575
576 /*
577  * Function irttp_data_request (handle, skb)
578  *
579  *    Queue frame for transmission. If SAR is enabled, fragement the frame
580  *    and queue the fragments for transmission
581  */
582 int irttp_data_request(struct tsap_cb *self, struct sk_buff *skb)
583 {
584         __u8 *frame;
585         int ret;
586
587         IRDA_ASSERT(self != NULL, return -1;);
588         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
589         IRDA_ASSERT(skb != NULL, return -1;);
590
591         IRDA_DEBUG(2, "%s() : queue len = %d\n", __FUNCTION__,
592                    skb_queue_len(&self->tx_queue));
593
594         /* Check that nothing bad happens */
595         if ((skb->len == 0) || (!self->connected)) {
596                 IRDA_WARNING("%s: No data, or not connected\n", __FUNCTION__);
597                 ret = -ENOTCONN;
598                 goto err;
599         }
600
601         /*
602          *  Check if SAR is disabled, and the frame is larger than what fits
603          *  inside an IrLAP frame
604          */
605         if ((self->tx_max_sdu_size == 0) && (skb->len > self->max_seg_size)) {
606                 IRDA_ERROR("%s: SAR disabled, and data is to large for IrLAP!\n",
607                            __FUNCTION__);
608                 ret = -EMSGSIZE;
609                 goto err;
610         }
611
612         /*
613          *  Check if SAR is enabled, and the frame is larger than the
614          *  TxMaxSduSize
615          */
616         if ((self->tx_max_sdu_size != 0) &&
617             (self->tx_max_sdu_size != TTP_SAR_UNBOUND) &&
618             (skb->len > self->tx_max_sdu_size))
619         {
620                 IRDA_ERROR("%s: SAR enabled, but data is larger than TxMaxSduSize!\n",
621                            __FUNCTION__);
622                 ret = -EMSGSIZE;
623                 goto err;
624         }
625         /*
626          *  Check if transmit queue is full
627          */
628         if (skb_queue_len(&self->tx_queue) >= TTP_TX_MAX_QUEUE) {
629                 /*
630                  *  Give it a chance to empty itself
631                  */
632                 irttp_run_tx_queue(self);
633
634                 /* Drop packet. This error code should trigger the caller
635                  * to resend the data in the client code - Jean II */
636                 ret = -ENOBUFS;
637                 goto err;
638         }
639
640         /* Queue frame, or queue frame segments */
641         if ((self->tx_max_sdu_size == 0) || (skb->len < self->max_seg_size)) {
642                 /* Queue frame */
643                 IRDA_ASSERT(skb_headroom(skb) >= TTP_HEADER, return -1;);
644                 frame = skb_push(skb, TTP_HEADER);
645                 frame[0] = 0x00; /* Clear more bit */
646
647                 skb_queue_tail(&self->tx_queue, skb);
648         } else {
649                 /*
650                  *  Fragment the frame, this function will also queue the
651                  *  fragments, we don't care about the fact the transmit
652                  *  queue may be overfilled by all the segments for a little
653                  *  while
654                  */
655                 irttp_fragment_skb(self, skb);
656         }
657
658         /* Check if we can accept more data from client */
659         if ((!self->tx_sdu_busy) &&
660             (skb_queue_len(&self->tx_queue) > TTP_TX_HIGH_THRESHOLD)) {
661                 /* Tx queue filling up, so stop client. */
662                 if (self->notify.flow_indication) {
663                         self->notify.flow_indication(self->notify.instance,
664                                                      self, FLOW_STOP);
665                 }
666                 /* self->tx_sdu_busy is the state of the client.
667                  * Update state after notifying client to avoid
668                  * race condition with irttp_flow_indication().
669                  * If the queue empty itself after our test but before
670                  * we set the flag, we will fix ourselves below in
671                  * irttp_run_tx_queue().
672                  * Jean II */
673                 self->tx_sdu_busy = TRUE;
674         }
675
676         /* Try to make some progress */
677         irttp_run_tx_queue(self);
678
679         return 0;
680
681 err:
682         dev_kfree_skb(skb);
683         return ret;
684 }
685 EXPORT_SYMBOL(irttp_data_request);
686
687 /*
688  * Function irttp_run_tx_queue (self)
689  *
690  *    Transmit packets queued for transmission (if possible)
691  *
692  */
693 static void irttp_run_tx_queue(struct tsap_cb *self)
694 {
695         struct sk_buff *skb;
696         unsigned long flags;
697         int n;
698
699         IRDA_DEBUG(2, "%s() : send_credit = %d, queue_len = %d\n",
700                    __FUNCTION__,
701                    self->send_credit, skb_queue_len(&self->tx_queue));
702
703         /* Get exclusive access to the tx queue, otherwise don't touch it */
704         if (irda_lock(&self->tx_queue_lock) == FALSE)
705                 return;
706
707         /* Try to send out frames as long as we have credits
708          * and as long as LAP is not full. If LAP is full, it will
709          * poll us through irttp_flow_indication() - Jean II */
710         while ((self->send_credit > 0) &&
711                (!irlmp_lap_tx_queue_full(self->lsap)) &&
712                (skb = skb_dequeue(&self->tx_queue)))
713         {
714                 /*
715                  *  Since we can transmit and receive frames concurrently,
716                  *  the code below is a critical region and we must assure that
717                  *  nobody messes with the credits while we update them.
718                  */
719                 spin_lock_irqsave(&self->lock, flags);
720
721                 n = self->avail_credit;
722                 self->avail_credit = 0;
723
724                 /* Only room for 127 credits in frame */
725                 if (n > 127) {
726                         self->avail_credit = n-127;
727                         n = 127;
728                 }
729                 self->remote_credit += n;
730                 self->send_credit--;
731
732                 spin_unlock_irqrestore(&self->lock, flags);
733
734                 /*
735                  *  More bit must be set by the data_request() or fragment()
736                  *  functions
737                  */
738                 skb->data[0] |= (n & 0x7f);
739
740                 /* Detach from socket.
741                  * The current skb has a reference to the socket that sent
742                  * it (skb->sk). When we pass it to IrLMP, the skb will be
743                  * stored in in IrLAP (self->wx_list). When we are within
744                  * IrLAP, we lose the notion of socket, so we should not
745                  * have a reference to a socket. So, we drop it here.
746                  *
747                  * Why does it matter ?
748                  * When the skb is freed (kfree_skb), if it is associated
749                  * with a socket, it release buffer space on the socket
750                  * (through sock_wfree() and sock_def_write_space()).
751                  * If the socket no longer exist, we may crash. Hard.
752                  * When we close a socket, we make sure that associated packets
753                  * in IrTTP are freed. However, we have no way to cancel
754                  * the packet that we have passed to IrLAP. So, if a packet
755                  * remains in IrLAP (retry on the link or else) after we
756                  * close the socket, we are dead !
757                  * Jean II */
758                 if (skb->sk != NULL) {
759                         /* IrSOCK application, IrOBEX, ... */
760                         skb_orphan(skb);
761                 }
762                         /* IrCOMM over IrTTP, IrLAN, ... */
763
764                 /* Pass the skb to IrLMP - done */
765                 irlmp_data_request(self->lsap, skb);
766                 self->stats.tx_packets++;
767         }
768
769         /* Check if we can accept more frames from client.
770          * We don't want to wait until the todo timer to do that, and we
771          * can't use tasklets (grr...), so we are obliged to give control
772          * to client. That's ok, this test will be true not too often
773          * (max once per LAP window) and we are called from places
774          * where we can spend a bit of time doing stuff. - Jean II */
775         if ((self->tx_sdu_busy) &&
776             (skb_queue_len(&self->tx_queue) < TTP_TX_LOW_THRESHOLD) &&
777             (!self->close_pend))
778         {
779                 if (self->notify.flow_indication)
780                         self->notify.flow_indication(self->notify.instance,
781                                                      self, FLOW_START);
782
783                 /* self->tx_sdu_busy is the state of the client.
784                  * We don't really have a race here, but it's always safer
785                  * to update our state after the client - Jean II */
786                 self->tx_sdu_busy = FALSE;
787         }
788
789         /* Reset lock */
790         self->tx_queue_lock = 0;
791 }
792
793 /*
794  * Function irttp_give_credit (self)
795  *
796  *    Send a dataless flowdata TTP-PDU and give available credit to peer
797  *    TSAP
798  */
799 static inline void irttp_give_credit(struct tsap_cb *self)
800 {
801         struct sk_buff *tx_skb = NULL;
802         unsigned long flags;
803         int n;
804
805         IRDA_ASSERT(self != NULL, return;);
806         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
807
808         IRDA_DEBUG(4, "%s() send=%d,avail=%d,remote=%d\n",
809                    __FUNCTION__,
810                    self->send_credit, self->avail_credit, self->remote_credit);
811
812         /* Give credit to peer */
813         tx_skb = dev_alloc_skb(64);
814         if (!tx_skb)
815                 return;
816
817         /* Reserve space for LMP, and LAP header */
818         skb_reserve(tx_skb, self->max_header_size);
819
820         /*
821          *  Since we can transmit and receive frames concurrently,
822          *  the code below is a critical region and we must assure that
823          *  nobody messes with the credits while we update them.
824          */
825         spin_lock_irqsave(&self->lock, flags);
826
827         n = self->avail_credit;
828         self->avail_credit = 0;
829
830         /* Only space for 127 credits in frame */
831         if (n > 127) {
832                 self->avail_credit = n - 127;
833                 n = 127;
834         }
835         self->remote_credit += n;
836
837         spin_unlock_irqrestore(&self->lock, flags);
838
839         skb_put(tx_skb, 1);
840         tx_skb->data[0] = (__u8) (n & 0x7f);
841
842         irlmp_data_request(self->lsap, tx_skb);
843         self->stats.tx_packets++;
844 }
845
846 /*
847  * Function irttp_udata_indication (instance, sap, skb)
848  *
849  *    Received some unit-data (unreliable)
850  *
851  */
852 static int irttp_udata_indication(void *instance, void *sap,
853                                   struct sk_buff *skb)
854 {
855         struct tsap_cb *self;
856         int err;
857
858         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
859
860         self = (struct tsap_cb *) instance;
861
862         IRDA_ASSERT(self != NULL, return -1;);
863         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
864         IRDA_ASSERT(skb != NULL, return -1;);
865
866         self->stats.rx_packets++;
867
868         /* Just pass data to layer above */
869         if (self->notify.udata_indication) {
870                 err = self->notify.udata_indication(self->notify.instance,
871                                                     self,skb);
872                 /* Same comment as in irttp_do_data_indication() */
873                 if (!err) 
874                         return 0;
875         }
876         /* Either no handler, or handler returns an error */
877         dev_kfree_skb(skb);
878
879         return 0;
880 }
881
882 /*
883  * Function irttp_data_indication (instance, sap, skb)
884  *
885  *    Receive segment from IrLMP.
886  *
887  */
888 static int irttp_data_indication(void *instance, void *sap,
889                                  struct sk_buff *skb)
890 {
891         struct tsap_cb *self;
892         unsigned long flags;
893         int n;
894
895         self = (struct tsap_cb *) instance;
896
897         n = skb->data[0] & 0x7f;     /* Extract the credits */
898
899         self->stats.rx_packets++;
900
901         /*  Deal with inbound credit
902          *  Since we can transmit and receive frames concurrently,
903          *  the code below is a critical region and we must assure that
904          *  nobody messes with the credits while we update them.
905          */
906         spin_lock_irqsave(&self->lock, flags);
907         self->send_credit += n;
908         if (skb->len > 1)
909                 self->remote_credit--;
910         spin_unlock_irqrestore(&self->lock, flags);
911
912         /*
913          *  Data or dataless packet? Dataless frames contains only the
914          *  TTP_HEADER.
915          */
916         if (skb->len > 1) {
917                 /*
918                  *  We don't remove the TTP header, since we must preserve the
919                  *  more bit, so the defragment routing knows what to do
920                  */
921                 skb_queue_tail(&self->rx_queue, skb);
922         } else {
923                 /* Dataless flowdata TTP-PDU */
924                 dev_kfree_skb(skb);
925         }
926
927
928         /* Push data to the higher layer.
929          * We do it synchronously because running the todo timer for each
930          * receive packet would be too much overhead and latency.
931          * By passing control to the higher layer, we run the risk that
932          * it may take time or grab a lock. Most often, the higher layer
933          * will only put packet in a queue.
934          * Anyway, packets are only dripping through the IrDA, so we can
935          * have time before the next packet.
936          * Further, we are run from NET_BH, so the worse that can happen is
937          * us missing the optimal time to send back the PF bit in LAP.
938          * Jean II */
939         irttp_run_rx_queue(self);
940
941         /* We now give credits to peer in irttp_run_rx_queue().
942          * We need to send credit *NOW*, otherwise we are going
943          * to miss the next Tx window. The todo timer may take
944          * a while before it's run... - Jean II */
945
946         /*
947          * If the peer device has given us some credits and we didn't have
948          * anyone from before, then we need to shedule the tx queue.
949          * We need to do that because our Tx have stopped (so we may not
950          * get any LAP flow indication) and the user may be stopped as
951          * well. - Jean II
952          */
953         if (self->send_credit == n) {
954                 /* Restart pushing stuff to LAP */
955                 irttp_run_tx_queue(self);
956                 /* Note : we don't want to schedule the todo timer
957                  * because it has horrible latency. No tasklets
958                  * because the tasklet API is broken. - Jean II */
959         }
960
961         return 0;
962 }
963
964 /*
965  * Function irttp_status_indication (self, reason)
966  *
967  *    Status_indication, just pass to the higher layer...
968  *
969  */
970 static void irttp_status_indication(void *instance,
971                                     LINK_STATUS link, LOCK_STATUS lock)
972 {
973         struct tsap_cb *self;
974
975         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
976
977         self = (struct tsap_cb *) instance;
978
979         IRDA_ASSERT(self != NULL, return;);
980         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
981
982         /* Check if client has already closed the TSAP and gone away */
983         if (self->close_pend)
984                 return;
985
986         /*
987          *  Inform service user if he has requested it
988          */
989         if (self->notify.status_indication != NULL)
990                 self->notify.status_indication(self->notify.instance,
991                                                link, lock);
992         else
993                 IRDA_DEBUG(2, "%s(), no handler\n", __FUNCTION__);
994 }
995
996 /*
997  * Function irttp_flow_indication (self, reason)
998  *
999  *    Flow_indication : IrLAP tells us to send more data.
1000  *
1001  */
1002 static void irttp_flow_indication(void *instance, void *sap, LOCAL_FLOW flow)
1003 {
1004         struct tsap_cb *self;
1005
1006         self = (struct tsap_cb *) instance;
1007
1008         IRDA_ASSERT(self != NULL, return;);
1009         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1010
1011         IRDA_DEBUG(4, "%s(instance=%p)\n", __FUNCTION__, self);
1012
1013         /* We are "polled" directly from LAP, and the LAP want to fill
1014          * its Tx window. We want to do our best to send it data, so that
1015          * we maximise the window. On the other hand, we want to limit the
1016          * amount of work here so that LAP doesn't hang forever waiting
1017          * for packets. - Jean II */
1018
1019         /* Try to send some packets. Currently, LAP calls us every time
1020          * there is one free slot, so we will send only one packet.
1021          * This allow the scheduler to do its round robin - Jean II */
1022         irttp_run_tx_queue(self);
1023
1024         /* Note regarding the interraction with higher layer.
1025          * irttp_run_tx_queue() may call the client when its queue
1026          * start to empty, via notify.flow_indication(). Initially.
1027          * I wanted this to happen in a tasklet, to avoid client
1028          * grabbing the CPU, but we can't use tasklets safely. And timer
1029          * is definitely too slow.
1030          * This will happen only once per LAP window, and usually at
1031          * the third packet (unless window is smaller). LAP is still
1032          * doing mtt and sending first packet so it's sort of OK
1033          * to do that. Jean II */
1034
1035         /* If we need to send disconnect. try to do it now */
1036         if(self->disconnect_pend)
1037                 irttp_start_todo_timer(self, 0);
1038 }
1039
1040 /*
1041  * Function irttp_flow_request (self, command)
1042  *
1043  *    This function could be used by the upper layers to tell IrTTP to stop
1044  *    delivering frames if the receive queues are starting to get full, or
1045  *    to tell IrTTP to start delivering frames again.
1046  */
1047 void irttp_flow_request(struct tsap_cb *self, LOCAL_FLOW flow)
1048 {
1049         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1050
1051         IRDA_ASSERT(self != NULL, return;);
1052         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1053
1054         switch (flow) {
1055         case FLOW_STOP:
1056                 IRDA_DEBUG(1, "%s(), flow stop\n", __FUNCTION__);
1057                 self->rx_sdu_busy = TRUE;
1058                 break;
1059         case FLOW_START:
1060                 IRDA_DEBUG(1, "%s(), flow start\n", __FUNCTION__);
1061                 self->rx_sdu_busy = FALSE;
1062
1063                 /* Client say he can accept more data, try to free our
1064                  * queues ASAP - Jean II */
1065                 irttp_run_rx_queue(self);
1066
1067                 break;
1068         default:
1069                 IRDA_DEBUG(1, "%s(), Unknown flow command!\n", __FUNCTION__);
1070         }
1071 }
1072 EXPORT_SYMBOL(irttp_flow_request);
1073
1074 /*
1075  * Function irttp_connect_request (self, dtsap_sel, daddr, qos)
1076  *
1077  *    Try to connect to remote destination TSAP selector
1078  *
1079  */
1080 int irttp_connect_request(struct tsap_cb *self, __u8 dtsap_sel,
1081                           __u32 saddr, __u32 daddr,
1082                           struct qos_info *qos, __u32 max_sdu_size,
1083                           struct sk_buff *userdata)
1084 {
1085         struct sk_buff *tx_skb;
1086         __u8 *frame;
1087         __u8 n;
1088
1089         IRDA_DEBUG(4, "%s(), max_sdu_size=%d\n", __FUNCTION__, max_sdu_size);
1090
1091         IRDA_ASSERT(self != NULL, return -EBADR;);
1092         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return -EBADR;);
1093
1094         if (self->connected) {
1095                 if(userdata)
1096                         dev_kfree_skb(userdata);
1097                 return -EISCONN;
1098         }
1099
1100         /* Any userdata supplied? */
1101         if (userdata == NULL) {
1102                 tx_skb = dev_alloc_skb(64);
1103                 if (!tx_skb)
1104                         return -ENOMEM;
1105
1106                 /* Reserve space for MUX_CONTROL and LAP header */
1107                 skb_reserve(tx_skb, TTP_MAX_HEADER);
1108         } else {
1109                 tx_skb = userdata;
1110                 /*
1111                  *  Check that the client has reserved enough space for
1112                  *  headers
1113                  */
1114                 IRDA_ASSERT(skb_headroom(userdata) >= TTP_MAX_HEADER,
1115                         { dev_kfree_skb(userdata); return -1; } );
1116         }
1117
1118         /* Initialize connection parameters */
1119         self->connected = FALSE;
1120         self->avail_credit = 0;
1121         self->rx_max_sdu_size = max_sdu_size;
1122         self->rx_sdu_size = 0;
1123         self->rx_sdu_busy = FALSE;
1124         self->dtsap_sel = dtsap_sel;
1125
1126         n = self->initial_credit;
1127
1128         self->remote_credit = 0;
1129         self->send_credit = 0;
1130
1131         /*
1132          *  Give away max 127 credits for now
1133          */
1134         if (n > 127) {
1135                 self->avail_credit=n-127;
1136                 n = 127;
1137         }
1138
1139         self->remote_credit = n;
1140
1141         /* SAR enabled? */
1142         if (max_sdu_size > 0) {
1143                 IRDA_ASSERT(skb_headroom(tx_skb) >= (TTP_MAX_HEADER + TTP_SAR_HEADER),
1144                         { dev_kfree_skb(tx_skb); return -1; } );
1145
1146                 /* Insert SAR parameters */
1147                 frame = skb_push(tx_skb, TTP_HEADER+TTP_SAR_HEADER);
1148
1149                 frame[0] = TTP_PARAMETERS | n;
1150                 frame[1] = 0x04; /* Length */
1151                 frame[2] = 0x01; /* MaxSduSize */
1152                 frame[3] = 0x02; /* Value length */
1153
1154                 put_unaligned(cpu_to_be16((__u16) max_sdu_size),
1155                               (__u16 *)(frame+4));
1156         } else {
1157                 /* Insert plain TTP header */
1158                 frame = skb_push(tx_skb, TTP_HEADER);
1159
1160                 /* Insert initial credit in frame */
1161                 frame[0] = n & 0x7f;
1162         }
1163
1164         /* Connect with IrLMP. No QoS parameters for now */
1165         return irlmp_connect_request(self->lsap, dtsap_sel, saddr, daddr, qos,
1166                                      tx_skb);
1167 }
1168 EXPORT_SYMBOL(irttp_connect_request);
1169
1170 /*
1171  * Function irttp_connect_confirm (handle, qos, skb)
1172  *
1173  *    Sevice user confirms TSAP connection with peer.
1174  *
1175  */
1176 static void irttp_connect_confirm(void *instance, void *sap,
1177                                   struct qos_info *qos, __u32 max_seg_size,
1178                                   __u8 max_header_size, struct sk_buff *skb)
1179 {
1180         struct tsap_cb *self;
1181         int parameters;
1182         int ret;
1183         __u8 plen;
1184         __u8 n;
1185
1186         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
1187
1188         self = (struct tsap_cb *) instance;
1189
1190         IRDA_ASSERT(self != NULL, return;);
1191         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1192         IRDA_ASSERT(skb != NULL, return;);
1193
1194         self->max_seg_size = max_seg_size - TTP_HEADER;
1195         self->max_header_size = max_header_size + TTP_HEADER;
1196
1197         /*
1198          *  Check if we have got some QoS parameters back! This should be the
1199          *  negotiated QoS for the link.
1200          */
1201         if (qos) {
1202                 IRDA_DEBUG(4, "IrTTP, Negotiated BAUD_RATE: %02x\n",
1203                        qos->baud_rate.bits);
1204                 IRDA_DEBUG(4, "IrTTP, Negotiated BAUD_RATE: %d bps.\n",
1205                        qos->baud_rate.value);
1206         }
1207
1208         n = skb->data[0] & 0x7f;
1209
1210         IRDA_DEBUG(4, "%s(), Initial send_credit=%d\n", __FUNCTION__, n);
1211
1212         self->send_credit = n;
1213         self->tx_max_sdu_size = 0;
1214         self->connected = TRUE;
1215
1216         parameters = skb->data[0] & 0x80;
1217
1218         IRDA_ASSERT(skb->len >= TTP_HEADER, return;);
1219         skb_pull(skb, TTP_HEADER);
1220
1221         if (parameters) {
1222                 plen = skb->data[0];
1223
1224                 ret = irda_param_extract_all(self, skb->data+1,
1225                                              IRDA_MIN(skb->len-1, plen),
1226                                              &param_info);
1227
1228                 /* Any errors in the parameter list? */
1229                 if (ret < 0) {
1230                         IRDA_WARNING("%s: error extracting parameters\n",
1231                                      __FUNCTION__);
1232                         dev_kfree_skb(skb);
1233
1234                         /* Do not accept this connection attempt */
1235                         return;
1236                 }
1237                 /* Remove parameters */
1238                 skb_pull(skb, IRDA_MIN(skb->len, plen+1));
1239         }
1240
1241         IRDA_DEBUG(4, "%s() send=%d,avail=%d,remote=%d\n", __FUNCTION__,
1242               self->send_credit, self->avail_credit, self->remote_credit);
1243
1244         IRDA_DEBUG(2, "%s(), MaxSduSize=%d\n", __FUNCTION__,
1245                    self->tx_max_sdu_size);
1246
1247         if (self->notify.connect_confirm) {
1248                 self->notify.connect_confirm(self->notify.instance, self, qos,
1249                                              self->tx_max_sdu_size,
1250                                              self->max_header_size, skb);
1251         } else
1252                 dev_kfree_skb(skb);
1253 }
1254
1255 /*
1256  * Function irttp_connect_indication (handle, skb)
1257  *
1258  *    Some other device is connecting to this TSAP
1259  *
1260  */
1261 void irttp_connect_indication(void *instance, void *sap, struct qos_info *qos,
1262                               __u32 max_seg_size, __u8 max_header_size,
1263                               struct sk_buff *skb)
1264 {
1265         struct tsap_cb *self;
1266         struct lsap_cb *lsap;
1267         int parameters;
1268         int ret;
1269         __u8 plen;
1270         __u8 n;
1271
1272         self = (struct tsap_cb *) instance;
1273
1274         IRDA_ASSERT(self != NULL, return;);
1275         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1276         IRDA_ASSERT(skb != NULL, return;);
1277
1278         lsap = (struct lsap_cb *) sap;
1279
1280         self->max_seg_size = max_seg_size - TTP_HEADER;
1281         self->max_header_size = max_header_size+TTP_HEADER;
1282
1283         IRDA_DEBUG(4, "%s(), TSAP sel=%02x\n", __FUNCTION__, self->stsap_sel);
1284
1285         /* Need to update dtsap_sel if its equal to LSAP_ANY */
1286         self->dtsap_sel = lsap->dlsap_sel;
1287
1288         n = skb->data[0] & 0x7f;
1289
1290         self->send_credit = n;
1291         self->tx_max_sdu_size = 0;
1292
1293         parameters = skb->data[0] & 0x80;
1294
1295         IRDA_ASSERT(skb->len >= TTP_HEADER, return;);
1296         skb_pull(skb, TTP_HEADER);
1297
1298         if (parameters) {
1299                 plen = skb->data[0];
1300
1301                 ret = irda_param_extract_all(self, skb->data+1,
1302                                              IRDA_MIN(skb->len-1, plen),
1303                                              &param_info);
1304
1305                 /* Any errors in the parameter list? */
1306                 if (ret < 0) {
1307                         IRDA_WARNING("%s: error extracting parameters\n",
1308                                      __FUNCTION__);
1309                         dev_kfree_skb(skb);
1310
1311                         /* Do not accept this connection attempt */
1312                         return;
1313                 }
1314
1315                 /* Remove parameters */
1316                 skb_pull(skb, IRDA_MIN(skb->len, plen+1));
1317         }
1318
1319         if (self->notify.connect_indication) {
1320                 self->notify.connect_indication(self->notify.instance, self,
1321                                                 qos, self->tx_max_sdu_size,
1322                                                 self->max_header_size, skb);
1323         } else
1324                 dev_kfree_skb(skb);
1325 }
1326
1327 /*
1328  * Function irttp_connect_response (handle, userdata)
1329  *
1330  *    Service user is accepting the connection, just pass it down to
1331  *    IrLMP!
1332  *
1333  */
1334 int irttp_connect_response(struct tsap_cb *self, __u32 max_sdu_size,
1335                            struct sk_buff *userdata)
1336 {
1337         struct sk_buff *tx_skb;
1338         __u8 *frame;
1339         int ret;
1340         __u8 n;
1341
1342         IRDA_ASSERT(self != NULL, return -1;);
1343         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
1344
1345         IRDA_DEBUG(4, "%s(), Source TSAP selector=%02x\n", __FUNCTION__,
1346                    self->stsap_sel);
1347
1348         /* Any userdata supplied? */
1349         if (userdata == NULL) {
1350                 tx_skb = dev_alloc_skb(64);
1351                 if (!tx_skb)
1352                         return -ENOMEM;
1353
1354                 /* Reserve space for MUX_CONTROL and LAP header */
1355                 skb_reserve(tx_skb, TTP_MAX_HEADER);
1356         } else {
1357                 tx_skb = userdata;
1358                 /*
1359                  *  Check that the client has reserved enough space for
1360                  *  headers
1361                  */
1362                 IRDA_ASSERT(skb_headroom(userdata) >= TTP_MAX_HEADER,
1363                         { dev_kfree_skb(userdata); return -1; } );
1364         }
1365
1366         self->avail_credit = 0;
1367         self->remote_credit = 0;
1368         self->rx_max_sdu_size = max_sdu_size;
1369         self->rx_sdu_size = 0;
1370         self->rx_sdu_busy = FALSE;
1371
1372         n = self->initial_credit;
1373
1374         /* Frame has only space for max 127 credits (7 bits) */
1375         if (n > 127) {
1376                 self->avail_credit = n - 127;
1377                 n = 127;
1378         }
1379
1380         self->remote_credit = n;
1381         self->connected = TRUE;
1382
1383         /* SAR enabled? */
1384         if (max_sdu_size > 0) {
1385                 IRDA_ASSERT(skb_headroom(tx_skb) >= (TTP_MAX_HEADER + TTP_SAR_HEADER),
1386                         { dev_kfree_skb(tx_skb); return -1; } );
1387
1388                 /* Insert TTP header with SAR parameters */
1389                 frame = skb_push(tx_skb, TTP_HEADER+TTP_SAR_HEADER);
1390
1391                 frame[0] = TTP_PARAMETERS | n;
1392                 frame[1] = 0x04; /* Length */
1393
1394                 /* irda_param_insert(self, IRTTP_MAX_SDU_SIZE, frame+1,  */
1395 /*                                TTP_SAR_HEADER, &param_info) */
1396
1397                 frame[2] = 0x01; /* MaxSduSize */
1398                 frame[3] = 0x02; /* Value length */
1399
1400                 put_unaligned(cpu_to_be16((__u16) max_sdu_size),
1401                               (__u16 *)(frame+4));
1402         } else {
1403                 /* Insert TTP header */
1404                 frame = skb_push(tx_skb, TTP_HEADER);
1405
1406                 frame[0] = n & 0x7f;
1407         }
1408
1409         ret = irlmp_connect_response(self->lsap, tx_skb);
1410
1411         return ret;
1412 }
1413 EXPORT_SYMBOL(irttp_connect_response);
1414
1415 /*
1416  * Function irttp_dup (self, instance)
1417  *
1418  *    Duplicate TSAP, can be used by servers to confirm a connection on a
1419  *    new TSAP so it can keep listening on the old one.
1420  */
1421 struct tsap_cb *irttp_dup(struct tsap_cb *orig, void *instance)
1422 {
1423         struct tsap_cb *new;
1424         unsigned long flags;
1425
1426         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1427
1428         /* Protect our access to the old tsap instance */
1429         spin_lock_irqsave(&irttp->tsaps->hb_spinlock, flags);
1430
1431         /* Find the old instance */
1432         if (!hashbin_find(irttp->tsaps, (long) orig, NULL)) {
1433                 IRDA_DEBUG(0, "%s(), unable to find TSAP\n", __FUNCTION__);
1434                 spin_unlock_irqrestore(&irttp->tsaps->hb_spinlock, flags);
1435                 return NULL;
1436         }
1437
1438         /* Allocate a new instance */
1439         new = kmalloc(sizeof(struct tsap_cb), GFP_ATOMIC);
1440         if (!new) {
1441                 IRDA_DEBUG(0, "%s(), unable to kmalloc\n", __FUNCTION__);
1442                 spin_unlock_irqrestore(&irttp->tsaps->hb_spinlock, flags);
1443                 return NULL;
1444         }
1445         /* Dup */
1446         memcpy(new, orig, sizeof(struct tsap_cb));
1447
1448         /* We don't need the old instance any more */
1449         spin_unlock_irqrestore(&irttp->tsaps->hb_spinlock, flags);
1450
1451         /* Try to dup the LSAP (may fail if we were too slow) */
1452         new->lsap = irlmp_dup(orig->lsap, new);
1453         if (!new->lsap) {
1454                 IRDA_DEBUG(0, "%s(), dup failed!\n", __FUNCTION__);
1455                 kfree(new);
1456                 return NULL;
1457         }
1458
1459         /* Not everything should be copied */
1460         new->notify.instance = instance;
1461         init_timer(&new->todo_timer);
1462
1463         skb_queue_head_init(&new->rx_queue);
1464         skb_queue_head_init(&new->tx_queue);
1465         skb_queue_head_init(&new->rx_fragments);
1466
1467         /* This is locked */
1468         hashbin_insert(irttp->tsaps, (irda_queue_t *) new, (long) new, NULL);
1469
1470         return new;
1471 }
1472 EXPORT_SYMBOL(irttp_dup);
1473
1474 /*
1475  * Function irttp_disconnect_request (self)
1476  *
1477  *    Close this connection please! If priority is high, the queued data
1478  *    segments, if any, will be deallocated first
1479  *
1480  */
1481 int irttp_disconnect_request(struct tsap_cb *self, struct sk_buff *userdata,
1482                              int priority)
1483 {
1484         int ret;
1485
1486         IRDA_ASSERT(self != NULL, return -1;);
1487         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
1488
1489         /* Already disconnected? */
1490         if (!self->connected) {
1491                 IRDA_DEBUG(4, "%s(), already disconnected!\n", __FUNCTION__);
1492                 if (userdata)
1493                         dev_kfree_skb(userdata);
1494                 return -1;
1495         }
1496
1497         /* Disconnect already pending ?
1498          * We need to use an atomic operation to prevent reentry. This
1499          * function may be called from various context, like user, timer
1500          * for following a disconnect_indication() (i.e. net_bh).
1501          * Jean II */
1502         if(test_and_set_bit(0, &self->disconnect_pend)) {
1503                 IRDA_DEBUG(0, "%s(), disconnect already pending\n",
1504                            __FUNCTION__);
1505                 if (userdata)
1506                         dev_kfree_skb(userdata);
1507
1508                 /* Try to make some progress */
1509                 irttp_run_tx_queue(self);
1510                 return -1;
1511         }
1512
1513         /*
1514          *  Check if there is still data segments in the transmit queue
1515          */
1516         if (skb_queue_len(&self->tx_queue) > 0) {
1517                 if (priority == P_HIGH) {
1518                         /*
1519                          *  No need to send the queued data, if we are
1520                          *  disconnecting right now since the data will
1521                          *  not have any usable connection to be sent on
1522                          */
1523                         IRDA_DEBUG(1, "%s(): High priority!!()\n", __FUNCTION__);
1524                         irttp_flush_queues(self);
1525                 } else if (priority == P_NORMAL) {
1526                         /*
1527                          *  Must delay disconnect until after all data segments
1528                          *  have been sent and the tx_queue is empty
1529                          */
1530                         /* We'll reuse this one later for the disconnect */
1531                         self->disconnect_skb = userdata;  /* May be NULL */
1532
1533                         irttp_run_tx_queue(self);
1534
1535                         irttp_start_todo_timer(self, HZ/10);
1536                         return -1;
1537                 }
1538         }
1539         /* Note : we don't need to check if self->rx_queue is full and the
1540          * state of self->rx_sdu_busy because the disconnect response will
1541          * be sent at the LMP level (so even if the peer has its Tx queue
1542          * full of data). - Jean II */
1543
1544         IRDA_DEBUG(1, "%s(), Disconnecting ...\n", __FUNCTION__);
1545         self->connected = FALSE;
1546
1547         if (!userdata) {
1548                 struct sk_buff *tx_skb;
1549                 tx_skb = dev_alloc_skb(64);
1550                 if (!tx_skb)
1551                         return -ENOMEM;
1552
1553                 /*
1554                  *  Reserve space for MUX and LAP header
1555                  */
1556                 skb_reserve(tx_skb, TTP_MAX_HEADER);
1557
1558                 userdata = tx_skb;
1559         }
1560         ret = irlmp_disconnect_request(self->lsap, userdata);
1561
1562         /* The disconnect is no longer pending */
1563         clear_bit(0, &self->disconnect_pend);   /* FALSE */
1564
1565         return ret;
1566 }
1567 EXPORT_SYMBOL(irttp_disconnect_request);
1568
1569 /*
1570  * Function irttp_disconnect_indication (self, reason)
1571  *
1572  *    Disconnect indication, TSAP disconnected by peer?
1573  *
1574  */
1575 void irttp_disconnect_indication(void *instance, void *sap, LM_REASON reason,
1576                                  struct sk_buff *skb)
1577 {
1578         struct tsap_cb *self;
1579
1580         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
1581
1582         self = (struct tsap_cb *) instance;
1583
1584         IRDA_ASSERT(self != NULL, return;);
1585         IRDA_ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1586
1587         /* Prevent higher layer to send more data */
1588         self->connected = FALSE;
1589
1590         /* Check if client has already tried to close the TSAP */
1591         if (self->close_pend) {
1592                 /* In this case, the higher layer is probably gone. Don't
1593                  * bother it and clean up the remains - Jean II */
1594                 if (skb)
1595                         dev_kfree_skb(skb);
1596                 irttp_close_tsap(self);
1597                 return;
1598         }
1599
1600         /* If we are here, we assume that is the higher layer is still
1601          * waiting for the disconnect notification and able to process it,
1602          * even if he tried to disconnect. Otherwise, it would have already
1603          * attempted to close the tsap and self->close_pend would be TRUE.
1604          * Jean II */
1605
1606         /* No need to notify the client if has already tried to disconnect */
1607         if(self->notify.disconnect_indication)
1608                 self->notify.disconnect_indication(self->notify.instance, self,
1609                                                    reason, skb);
1610         else
1611                 if (skb)
1612                         dev_kfree_skb(skb);
1613 }
1614
1615 /*
1616  * Function irttp_do_data_indication (self, skb)
1617  *
1618  *    Try to deliver reassembled skb to layer above, and requeue it if that
1619  *    for some reason should fail. We mark rx sdu as busy to apply back
1620  *    pressure is necessary.
1621  */
1622 static void irttp_do_data_indication(struct tsap_cb *self, struct sk_buff *skb)
1623 {
1624         int err;
1625
1626         /* Check if client has already closed the TSAP and gone away */
1627         if (self->close_pend) {
1628                 dev_kfree_skb(skb);
1629                 return;
1630         }
1631
1632         err = self->notify.data_indication(self->notify.instance, self, skb);
1633
1634         /* Usually the layer above will notify that it's input queue is
1635          * starting to get filled by using the flow request, but this may
1636          * be difficult, so it can instead just refuse to eat it and just
1637          * give an error back
1638          */
1639         if (err) {
1640                 IRDA_DEBUG(0, "%s() requeueing skb!\n", __FUNCTION__);
1641
1642                 /* Make sure we take a break */
1643                 self->rx_sdu_busy = TRUE;
1644
1645                 /* Need to push the header in again */
1646                 skb_push(skb, TTP_HEADER);
1647                 skb->data[0] = 0x00; /* Make sure MORE bit is cleared */
1648
1649                 /* Put skb back on queue */
1650                 skb_queue_head(&self->rx_queue, skb);
1651         }
1652 }
1653
1654 /*
1655  * Function irttp_run_rx_queue (self)
1656  *
1657  *     Check if we have any frames to be transmitted, or if we have any
1658  *     available credit to give away.
1659  */
1660 void irttp_run_rx_queue(struct tsap_cb *self)
1661 {
1662         struct sk_buff *skb;
1663         int more = 0;
1664
1665         IRDA_DEBUG(2, "%s() send=%d,avail=%d,remote=%d\n", __FUNCTION__,
1666                    self->send_credit, self->avail_credit, self->remote_credit);
1667
1668         /* Get exclusive access to the rx queue, otherwise don't touch it */
1669         if (irda_lock(&self->rx_queue_lock) == FALSE)
1670                 return;
1671
1672         /*
1673          *  Reassemble all frames in receive queue and deliver them
1674          */
1675         while (!self->rx_sdu_busy && (skb = skb_dequeue(&self->rx_queue))) {
1676                 /* This bit will tell us if it's the last fragment or not */
1677                 more = skb->data[0] & 0x80;
1678
1679                 /* Remove TTP header */
1680                 skb_pull(skb, TTP_HEADER);
1681
1682                 /* Add the length of the remaining data */
1683                 self->rx_sdu_size += skb->len;
1684
1685                 /*
1686                  * If SAR is disabled, or user has requested no reassembly
1687                  * of received fragments then we just deliver them
1688                  * immediately. This can be requested by clients that
1689                  * implements byte streams without any message boundaries
1690                  */
1691                 if (self->rx_max_sdu_size == TTP_SAR_DISABLE) {
1692                         irttp_do_data_indication(self, skb);
1693                         self->rx_sdu_size = 0;
1694
1695                         continue;
1696                 }
1697
1698                 /* Check if this is a fragment, and not the last fragment */
1699                 if (more) {
1700                         /*
1701                          *  Queue the fragment if we still are within the
1702                          *  limits of the maximum size of the rx_sdu
1703                          */
1704                         if (self->rx_sdu_size <= self->rx_max_sdu_size) {
1705                                 IRDA_DEBUG(4, "%s(), queueing frag\n",
1706                                            __FUNCTION__);
1707                                 skb_queue_tail(&self->rx_fragments, skb);
1708                         } else {
1709                                 /* Free the part of the SDU that is too big */
1710                                 dev_kfree_skb(skb);
1711                         }
1712                         continue;
1713                 }
1714                 /*
1715                  *  This is the last fragment, so time to reassemble!
1716                  */
1717                 if ((self->rx_sdu_size <= self->rx_max_sdu_size) ||
1718                     (self->rx_max_sdu_size == TTP_SAR_UNBOUND))
1719                 {
1720                         /*
1721                          * A little optimizing. Only queue the fragment if
1722                          * there are other fragments. Since if this is the
1723                          * last and only fragment, there is no need to
1724                          * reassemble :-)
1725                          */
1726                         if (!skb_queue_empty(&self->rx_fragments)) {
1727                                 skb_queue_tail(&self->rx_fragments,
1728                                                skb);
1729
1730                                 skb = irttp_reassemble_skb(self);
1731                         }
1732
1733                         /* Now we can deliver the reassembled skb */
1734                         irttp_do_data_indication(self, skb);
1735                 } else {
1736                         IRDA_DEBUG(1, "%s(), Truncated frame\n", __FUNCTION__);
1737
1738                         /* Free the part of the SDU that is too big */
1739                         dev_kfree_skb(skb);
1740
1741                         /* Deliver only the valid but truncated part of SDU */
1742                         skb = irttp_reassemble_skb(self);
1743
1744                         irttp_do_data_indication(self, skb);
1745                 }
1746                 self->rx_sdu_size = 0;
1747         }
1748
1749         /*
1750          * It's not trivial to keep track of how many credits are available
1751          * by incrementing at each packet, because delivery may fail
1752          * (irttp_do_data_indication() may requeue the frame) and because
1753          * we need to take care of fragmentation.
1754          * We want the other side to send up to initial_credit packets.
1755          * We have some frames in our queues, and we have already allowed it
1756          * to send remote_credit.
1757          * No need to spinlock, write is atomic and self correcting...
1758          * Jean II
1759          */
1760         self->avail_credit = (self->initial_credit -
1761                               (self->remote_credit +
1762                                skb_queue_len(&self->rx_queue) +
1763                                skb_queue_len(&self->rx_fragments)));
1764
1765         /* Do we have too much credits to send to peer ? */
1766         if ((self->remote_credit <= TTP_RX_MIN_CREDIT) &&
1767             (self->avail_credit > 0)) {
1768                 /* Send explicit credit frame */
1769                 irttp_give_credit(self);
1770                 /* Note : do *NOT* check if tx_queue is non-empty, that
1771                  * will produce deadlocks. I repeat : send a credit frame
1772                  * even if we have something to send in our Tx queue.
1773                  * If we have credits, it means that our Tx queue is blocked.
1774                  *
1775                  * Let's suppose the peer can't keep up with our Tx. He will
1776                  * flow control us by not sending us any credits, and we
1777                  * will stop Tx and start accumulating credits here.
1778                  * Up to the point where the peer will stop its Tx queue,
1779                  * for lack of credits.
1780                  * Let's assume the peer application is single threaded.
1781                  * It will block on Tx and never consume any Rx buffer.
1782                  * Deadlock. Guaranteed. - Jean II
1783                  */
1784         }
1785
1786         /* Reset lock */
1787         self->rx_queue_lock = 0;
1788 }
1789
1790 #ifdef CONFIG_PROC_FS
1791 struct irttp_iter_state {
1792         int id;
1793 };
1794
1795 static void *irttp_seq_start(struct seq_file *seq, loff_t *pos)
1796 {
1797         struct irttp_iter_state *iter = seq->private;
1798         struct tsap_cb *self;
1799
1800         /* Protect our access to the tsap list */
1801         spin_lock_irq(&irttp->tsaps->hb_spinlock);
1802         iter->id = 0;
1803
1804         for (self = (struct tsap_cb *) hashbin_get_first(irttp->tsaps); 
1805              self != NULL;
1806              self = (struct tsap_cb *) hashbin_get_next(irttp->tsaps)) {
1807                 if (iter->id == *pos)
1808                         break;
1809                 ++iter->id;
1810         }
1811                 
1812         return self;
1813 }
1814
1815 static void *irttp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1816 {
1817         struct irttp_iter_state *iter = seq->private;
1818
1819         ++*pos;
1820         ++iter->id;
1821         return (void *) hashbin_get_next(irttp->tsaps);
1822 }
1823
1824 static void irttp_seq_stop(struct seq_file *seq, void *v)
1825 {
1826         spin_unlock_irq(&irttp->tsaps->hb_spinlock);
1827 }
1828
1829 static int irttp_seq_show(struct seq_file *seq, void *v)
1830 {
1831         const struct irttp_iter_state *iter = seq->private;
1832         const struct tsap_cb *self = v;
1833
1834         seq_printf(seq, "TSAP %d, ", iter->id);
1835         seq_printf(seq, "stsap_sel: %02x, ",
1836                    self->stsap_sel);
1837         seq_printf(seq, "dtsap_sel: %02x\n",
1838                    self->dtsap_sel);
1839         seq_printf(seq, "  connected: %s, ",
1840                    self->connected? "TRUE":"FALSE");
1841         seq_printf(seq, "avail credit: %d, ",
1842                    self->avail_credit);
1843         seq_printf(seq, "remote credit: %d, ",
1844                    self->remote_credit);
1845         seq_printf(seq, "send credit: %d\n",
1846                    self->send_credit);
1847         seq_printf(seq, "  tx packets: %ld, ",
1848                    self->stats.tx_packets);
1849         seq_printf(seq, "rx packets: %ld, ",
1850                    self->stats.rx_packets);
1851         seq_printf(seq, "tx_queue len: %d ",
1852                    skb_queue_len(&self->tx_queue));
1853         seq_printf(seq, "rx_queue len: %d\n",
1854                    skb_queue_len(&self->rx_queue));
1855         seq_printf(seq, "  tx_sdu_busy: %s, ",
1856                    self->tx_sdu_busy? "TRUE":"FALSE");
1857         seq_printf(seq, "rx_sdu_busy: %s\n",
1858                    self->rx_sdu_busy? "TRUE":"FALSE");
1859         seq_printf(seq, "  max_seg_size: %d, ",
1860                    self->max_seg_size);
1861         seq_printf(seq, "tx_max_sdu_size: %d, ",
1862                    self->tx_max_sdu_size);
1863         seq_printf(seq, "rx_max_sdu_size: %d\n",
1864                    self->rx_max_sdu_size);
1865
1866         seq_printf(seq, "  Used by (%s)\n\n",
1867                    self->notify.name);
1868         return 0;
1869 }
1870
1871 static struct seq_operations irttp_seq_ops = {
1872         .start  = irttp_seq_start,
1873         .next   = irttp_seq_next,
1874         .stop   = irttp_seq_stop,
1875         .show   = irttp_seq_show,
1876 };
1877
1878 static int irttp_seq_open(struct inode *inode, struct file *file)
1879 {
1880         struct seq_file *seq;
1881         int rc = -ENOMEM;
1882         struct irttp_iter_state *s;
1883        
1884         IRDA_ASSERT(irttp != NULL, return -EINVAL;);
1885
1886         s = kmalloc(sizeof(*s), GFP_KERNEL);
1887         if (!s)
1888                 goto out;
1889
1890         rc = seq_open(file, &irttp_seq_ops);
1891         if (rc)
1892                 goto out_kfree;
1893
1894         seq          = file->private_data;
1895         seq->private = s;
1896         memset(s, 0, sizeof(*s));
1897 out:
1898         return rc;
1899 out_kfree:
1900         kfree(s);
1901         goto out;
1902 }
1903
1904 struct file_operations irttp_seq_fops = {
1905         .owner          = THIS_MODULE,
1906         .open           = irttp_seq_open,
1907         .read           = seq_read,
1908         .llseek         = seq_lseek,
1909         .release        = seq_release_private,
1910 };
1911
1912 #endif /* PROC_FS */