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