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