port more changes to make PCI work
[linux-2.4.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("%s(), can't allocate IrTTP hashbin!\n", __FUNCTION__);
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, "%s(instance=%p)\n", __FUNCTION__, 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, "%s()\n", __FUNCTION__);
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, "%s(), self->rx_sdu_size=%d\n", __FUNCTION__,
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, "%s(), frame len=%d\n", __FUNCTION__, n);
266
267         IRDA_DEBUG(2, "%s(), rx_sdu_size=%d\n", __FUNCTION__, 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, "%s()\n", __FUNCTION__);
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, "%s(), fragmenting ...\n", __FUNCTION__);
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, "%s(), queuing last segment\n", __FUNCTION__);
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, "%s(), MaxSduSize=%d\n", __FUNCTION__, 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, "%s(), invalid tsap!\n", __FUNCTION__);
384                 return NULL;
385         }
386
387         self = kmalloc(sizeof(struct tsap_cb), GFP_ATOMIC);
388         if (self == NULL) {
389                 IRDA_DEBUG(0, "%s(), unable to kmalloc!\n", __FUNCTION__);
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("%s(), unable to allocate LSAP!!\n", __FUNCTION__);
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, "%s(), stsap_sel=%02x\n", __FUNCTION__, 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, "%s()\n", __FUNCTION__);
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("%s(), TSAP still connected!\n", __FUNCTION__);
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, "%s()\n", __FUNCTION__);
537
538         /* Check that nothing bad happens */
539         if ((skb->len == 0) || (!self->connected)) {
540                 IRDA_DEBUG(1, "%s(), No data, or not connected\n", __FUNCTION__);
541                 return -1;
542         }
543         
544         if (skb->len > self->max_seg_size) {
545                 IRDA_DEBUG(1, "%s(), UData is to large for IrLAP!\n", __FUNCTION__);
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, "%s : queue len = %d\n", __FUNCTION__,
570                    skb_queue_len(&self->tx_queue));
571
572         /* Check that nothing bad happens */
573         if ((skb->len == 0) || (!self->connected)) {
574                 WARNING("%s(), No data, or not connected\n", __FUNCTION__);
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("%s(), SAR disabled, and data is to large for IrLAP!\n", __FUNCTION__);
584                 return -EMSGSIZE;
585         }
586
587         /* 
588          *  Check if SAR is enabled, and the frame is larger than the 
589          *  TxMaxSduSize 
590          */
591         if ((self->tx_max_sdu_size != 0) && 
592             (self->tx_max_sdu_size != TTP_SAR_UNBOUND) && 
593             (skb->len > self->tx_max_sdu_size))
594         {
595                 ERROR("%s(), SAR enabled, "
596                       "but data is larger than TxMaxSduSize!\n", __FUNCTION__);
597                 return -EMSGSIZE;
598         }
599         /* 
600          *  Check if transmit queue is full
601          */
602         if (skb_queue_len(&self->tx_queue) >= TTP_TX_MAX_QUEUE) {
603                 /*
604                  *  Give it a chance to empty itself
605                  */
606                 irttp_run_tx_queue(self);
607
608                 /* Drop packet. This error code should trigger the caller
609                  * to requeue the packet in the client code - Jean II */
610                 return -ENOBUFS;
611         }
612        
613         /* Queue frame, or queue frame segments */
614         if ((self->tx_max_sdu_size == 0) || (skb->len < self->max_seg_size)) {
615                 /* Queue frame */
616                 ASSERT(skb_headroom(skb) >= TTP_HEADER, return -1;);
617                 frame = skb_push(skb, TTP_HEADER);
618                 frame[0] = 0x00; /* Clear more bit */
619                 
620                 skb_queue_tail(&self->tx_queue, skb);
621         } else {
622                 /*
623                  *  Fragment the frame, this function will also queue the
624                  *  fragments, we don't care about the fact the transmit
625                  *  queue may be overfilled by all the segments for a little
626                  *  while
627                  */
628                 irttp_fragment_skb(self, skb);
629         }
630
631         /* Check if we can accept more data from client */
632         if ((!self->tx_sdu_busy) && 
633             (skb_queue_len(&self->tx_queue) > TTP_TX_HIGH_THRESHOLD)) {
634                 /* Tx queue filling up, so stop client. */
635                 if (self->notify.flow_indication) {
636                         self->notify.flow_indication(self->notify.instance, 
637                                                      self, FLOW_STOP);
638                 }
639                 /* self->tx_sdu_busy is the state of the client.
640                  * Update state after notifying client to avoid
641                  * race condition with irttp_flow_indication().
642                  * If the queue empty itself after our test but before
643                  * we set the flag, we will fix ourselves below in
644                  * irttp_run_tx_queue().
645                  * Jean II */
646                 self->tx_sdu_busy = TRUE;
647         }
648         
649         /* Try to make some progress */
650         irttp_run_tx_queue(self);
651
652         return 0;
653 }
654
655 /*
656  * Function irttp_run_tx_queue (self)
657  *
658  *    Transmit packets queued for transmission (if possible)
659  *
660  */
661 static void irttp_run_tx_queue(struct tsap_cb *self) 
662 {
663         struct sk_buff *skb;
664         unsigned long flags;
665         int n;
666
667         IRDA_DEBUG(2, "%s() : send_credit = %d, queue_len = %d\n", __FUNCTION__,
668                    self->send_credit, skb_queue_len(&self->tx_queue));
669
670         /* Get exclusive access to the tx queue, otherwise don't touch it */
671         if (irda_lock(&self->tx_queue_lock) == FALSE)
672                 return;
673
674         /* Try to send out frames as long as we have credits
675          * and as long as LAP is not full. If LAP is full, it will
676          * poll us through irttp_flow_indication() - Jean II */
677         while ((self->send_credit > 0) &&
678                (!irlmp_lap_tx_queue_full(self->lsap)) &&
679                (skb = skb_dequeue(&self->tx_queue)))
680         {
681                 /*
682                  *  Since we can transmit and receive frames concurrently, 
683                  *  the code below is a critical region and we must assure that
684                  *  nobody messes with the credits while we update them.
685                  */
686                 spin_lock_irqsave(&self->lock, flags);
687
688                 n = self->avail_credit;
689                 self->avail_credit = 0;
690                 
691                 /* Only room for 127 credits in frame */
692                 if (n > 127) {
693                         self->avail_credit = n-127;
694                         n = 127;
695                 }
696                 self->remote_credit += n;
697                 self->send_credit--;
698
699                 spin_unlock_irqrestore(&self->lock, flags);
700
701                 /* 
702                  *  More bit must be set by the data_request() or fragment() 
703                  *  functions
704                  */
705                 skb->data[0] |= (n & 0x7f);
706                 
707                 /* Detach from socket.
708                  * The current skb has a reference to the socket that sent
709                  * it (skb->sk). When we pass it to IrLMP, the skb will be
710                  * stored in in IrLAP (self->wx_list). When we are within
711                  * IrLAP, we loose the notion of socket, so we should not
712                  * have a reference to a socket. So, we drop it here.
713                  * 
714                  * Why does it matter ?
715                  * When the skb is freed (kfree_skb), if it is associated
716                  * with a socket, it release buffer space on the socket
717                  * (through sock_wfree() and sock_def_write_space()).
718                  * If the socket no longer exist, we may crash. Hard.
719                  * When we close a socket, we make sure that associated packets
720                  * in IrTTP are freed. However, we have no way to cancel
721                  * the packet that we have passed to IrLAP. So, if a packet
722                  * remains in IrLAP (retry on the link or else) after we
723                  * close the socket, we are dead !
724                  * Jean II */
725                 if (skb->sk != NULL) {
726                         /* IrSOCK application, IrOBEX, ... */
727                         skb_orphan(skb);
728                 }
729                         /* IrCOMM over IrTTP, IrLAN, ... */
730
731                 /* Pass the skb to IrLMP - done */
732                 irlmp_data_request(self->lsap, skb);
733                 self->stats.tx_packets++;
734         }
735
736         /* Check if we can accept more frames from client.
737          * We don't want to wait until the todo timer to do that, and we
738          * can't use tasklets (grr...), so we are obliged to give control
739          * to client. That's ok, this test will be true not too often
740          * (max once per LAP window) and we are called from places
741          * where we can spend a bit of time doing stuff. - Jean II */
742         if ((self->tx_sdu_busy) && 
743             (skb_queue_len(&self->tx_queue) < TTP_TX_LOW_THRESHOLD) &&
744             (!self->close_pend))
745         {
746                 if (self->notify.flow_indication)
747                         self->notify.flow_indication(self->notify.instance,
748                                                      self, FLOW_START);
749
750                 /* self->tx_sdu_busy is the state of the client.
751                  * We don't really have a race here, but it's always safer
752                  * to update our state after the client - Jean II */
753                 self->tx_sdu_busy = FALSE;
754         }
755
756         /* Reset lock */
757         self->tx_queue_lock = 0;
758 }
759
760 /*
761  * Function irttp_give_credit (self)
762  *
763  *    Send a dataless flowdata TTP-PDU and give available credit to peer
764  *    TSAP
765  */
766 static inline void irttp_give_credit(struct tsap_cb *self) 
767 {
768         struct sk_buff *tx_skb = NULL;
769         unsigned long flags;
770         int n;
771
772         ASSERT(self != NULL, return;);
773         ASSERT(self->magic == TTP_TSAP_MAGIC, return;); 
774
775         IRDA_DEBUG(4, "%s() send=%d,avail=%d,remote=%d\n", __FUNCTION__,
776                    self->send_credit, self->avail_credit, self->remote_credit);
777
778         /* Give credit to peer */
779         tx_skb = dev_alloc_skb(64);
780         if (!tx_skb)
781                 return;
782
783         /* Reserve space for LMP, and LAP header */
784         skb_reserve(tx_skb, self->max_header_size);
785
786         /*
787          *  Since we can transmit and receive frames concurrently, 
788          *  the code below is a critical region and we must assure that
789          *  nobody messes with the credits while we update them.
790          */
791         spin_lock_irqsave(&self->lock, flags);
792
793         n = self->avail_credit;
794         self->avail_credit = 0;
795         
796         /* Only space for 127 credits in frame */
797         if (n > 127) {
798                 self->avail_credit = n - 127;
799                 n = 127;
800         }
801         self->remote_credit += n;
802
803         spin_unlock_irqrestore(&self->lock, flags);
804
805         skb_put(tx_skb, 1);
806         tx_skb->data[0] = (__u8) (n & 0x7f);
807         
808         irlmp_data_request(self->lsap, tx_skb);
809         self->stats.tx_packets++;
810 }
811
812 /*
813  * Function irttp_udata_indication (instance, sap, skb)
814  *
815  *    Received some unit-data (unreliable)
816  *
817  */
818 static int irttp_udata_indication(void *instance, void *sap, 
819                                   struct sk_buff *skb) 
820 {
821         struct tsap_cb *self;
822
823         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
824
825         self = (struct tsap_cb *) instance;
826
827         ASSERT(self != NULL, return -1;);
828         ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
829         ASSERT(skb != NULL, return -1;);
830
831         /* Just pass data to layer above */
832         if (self->notify.udata_indication)
833                 self->notify.udata_indication(self->notify.instance, self,skb);
834         else
835                 dev_kfree_skb(skb);
836
837         self->stats.rx_packets++;
838
839         return 0;
840 }
841
842 /*
843  * Function irttp_data_indication (instance, sap, skb)
844  *
845  *    Receive segment from IrLMP. 
846  *
847  */
848 static int irttp_data_indication(void *instance, void *sap, 
849                                  struct sk_buff *skb)
850 {
851         struct tsap_cb *self;
852         unsigned long flags;
853         int n;
854
855         self = (struct tsap_cb *) instance;
856
857         n = skb->data[0] & 0x7f;     /* Extract the credits */
858
859         self->stats.rx_packets++;
860
861         /*  Deal with inbound credit
862          *  Since we can transmit and receive frames concurrently, 
863          *  the code below is a critical region and we must assure that
864          *  nobody messes with the credits while we update them.
865          */
866         spin_lock_irqsave(&self->lock, flags);
867         self->send_credit += n;
868         if (skb->len > 1)
869                 self->remote_credit--;
870         spin_unlock_irqrestore(&self->lock, flags);
871
872         /* 
873          *  Data or dataless packet? Dataless frames contains only the 
874          *  TTP_HEADER. 
875          */
876         if (skb->len > 1) {
877                 /* 
878                  *  We don't remove the TTP header, since we must preserve the
879                  *  more bit, so the defragment routing knows what to do
880                  */
881                 skb_queue_tail(&self->rx_queue, skb);
882         } else {
883                 /* Dataless flowdata TTP-PDU */
884                 dev_kfree_skb(skb);
885         }
886
887
888         /* Push data to the higher layer.
889          * We do it synchronously because running the todo timer for each
890          * receive packet would be too much overhead and latency.
891          * By passing control to the higher layer, we run the risk that
892          * it may take time or grab a lock. Most often, the higher layer
893          * will only put packet in a queue.
894          * Anyway, packets are only dripping through the IrDA, so we can
895          * have time before the next packet.
896          * Further, we are run from NET_BH, so the worse that can happen is
897          * us missing the optimal time to send back the PF bit in LAP.
898          * Jean II */
899         irttp_run_rx_queue(self);
900
901         /* We now give credits to peer in irttp_run_rx_queue().
902          * We need to send credit *NOW*, otherwise we are going
903          * to miss the next Tx window. The todo timer may take
904          * a while before it's run... - Jean II */
905
906         /* 
907          * If the peer device has given us some credits and we didn't have
908          * anyone from before, then we need to shedule the tx queue.
909          * We need to do that because our Tx have stopped (so we may not
910          * get any LAP flow indication) and the user may be stopped as
911          * well. - Jean II
912          */
913         if (self->send_credit == n) {
914                 /* Restart pushing stuff to LAP */
915                 irttp_run_tx_queue(self);
916                 /* Note : we don't want to schedule the todo timer
917                  * because it has horrible latency. No tasklets
918                  * because the tasklet API is broken. - Jean II */
919         }
920
921         return 0;
922 }
923
924 /*
925  * Function irttp_status_indication (self, reason)
926  *
927  *    Status_indication, just pass to the higher layer...
928  *
929  */
930 void irttp_status_indication(void *instance,
931                              LINK_STATUS link, LOCK_STATUS lock)
932 {
933         struct tsap_cb *self;
934
935         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
936
937         self = (struct tsap_cb *) instance;
938         
939         ASSERT(self != NULL, return;);
940         ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
941         
942         /*
943          *  Inform service user if he has requested it
944          */
945         if (self->notify.status_indication != NULL)
946                 self->notify.status_indication(self->notify.instance, 
947                                                link, lock);
948         else
949                 IRDA_DEBUG(2, "%s(), no handler\n", __FUNCTION__);
950 }
951
952 /*
953  * Function irttp_flow_indication (self, reason)
954  *
955  *    Flow_indication : IrLAP tells us to send more data.
956  *
957  */
958 void irttp_flow_indication(void *instance, void *sap, LOCAL_FLOW flow)
959 {
960         struct tsap_cb *self;
961
962         self = (struct tsap_cb *) instance;
963         
964         ASSERT(self != NULL, return;);
965         ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
966         
967         IRDA_DEBUG(4, "%s(instance=%p)\n", __FUNCTION__, self);
968
969         /* We are "polled" directly from LAP, and the LAP want to fill
970          * its Tx window. We want to do our best to send it data, so that
971          * we maximise the window. On the other hand, we want to limit the
972          * amount of work here so that LAP doesn't hang forever waiting
973          * for packets. - Jean II */
974
975         /* Try to send some packets. Currently, LAP calls us every time
976          * there is one free slot, so we will send only one packet.
977          * This allow the scheduler to do its round robin - Jean II */
978         irttp_run_tx_queue(self);
979
980         /* Note regarding the interraction with higher layer.
981          * irttp_run_tx_queue() may call the client when its queue
982          * start to empty, via notify.flow_indication(). Initially.
983          * I wanted this to happen in a tasklet, to avoid client
984          * grabbing the CPU, but we can't use tasklets safely. And timer
985          * is definitely too slow.
986          * This will happen only once per LAP window, and usually at
987          * the third packet (unless window is smaller). LAP is still
988          * doing mtt and sending first packet so it's sort of OK
989          * to do that. Jean II */
990
991         /* If we need to send disconnect. try to do it now */
992         if(self->disconnect_pend)
993                 irttp_start_todo_timer(self, 0);
994 }
995
996 /*
997  * Function irttp_flow_request (self, command)
998  *
999  *    This funtion could be used by the upper layers to tell IrTTP to stop
1000  *    delivering frames if the receive queues are starting to get full, or 
1001  *    to tell IrTTP to start delivering frames again.
1002  */
1003 void irttp_flow_request(struct tsap_cb *self, LOCAL_FLOW flow)
1004 {
1005         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1006
1007         ASSERT(self != NULL, return;);
1008         ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1009
1010         switch (flow) {
1011         case FLOW_STOP:
1012                 IRDA_DEBUG(1, "%s(), flow stop\n", __FUNCTION__);
1013                 self->rx_sdu_busy = TRUE;
1014                 break;
1015         case FLOW_START:
1016                 IRDA_DEBUG(1, "%s(), flow start\n", __FUNCTION__);
1017                 self->rx_sdu_busy = FALSE;
1018                 
1019                 /* Client say he can accept more data, try to free our
1020                  * queues ASAP - Jean II */
1021                 irttp_run_rx_queue(self);
1022
1023                 break;
1024         default:
1025                 IRDA_DEBUG(1, "%s(), Unknown flow command!\n", __FUNCTION__);
1026         }
1027 }
1028         
1029 /*
1030  * Function irttp_connect_request (self, dtsap_sel, daddr, qos)
1031  *
1032  *    Try to connect to remote destination TSAP selector
1033  *
1034  */
1035 int irttp_connect_request(struct tsap_cb *self, __u8 dtsap_sel, 
1036                           __u32 saddr, __u32 daddr,
1037                           struct qos_info *qos, __u32 max_sdu_size, 
1038                           struct sk_buff *userdata) 
1039 {
1040         struct sk_buff *skb;
1041         __u8 *frame;
1042         __u8 n;
1043         
1044         IRDA_DEBUG(4, "%s(), max_sdu_size=%d\n", __FUNCTION__, max_sdu_size); 
1045         
1046         ASSERT(self != NULL, return -EBADR;);
1047         ASSERT(self->magic == TTP_TSAP_MAGIC, return -EBADR;);
1048
1049         if (self->connected)
1050                 return -EISCONN;
1051         
1052         /* Any userdata supplied? */
1053         if (userdata == NULL) {
1054                 skb = dev_alloc_skb(64);
1055                 if (!skb) 
1056                         return -ENOMEM;
1057                 
1058                 /* Reserve space for MUX_CONTROL and LAP header */
1059                 skb_reserve(skb, TTP_MAX_HEADER);
1060         } else {
1061                 skb = userdata;
1062                 /*  
1063                  *  Check that the client has reserved enough space for 
1064                  *  headers
1065                  */
1066                 ASSERT(skb_headroom(userdata) >= TTP_MAX_HEADER, return -1;);
1067         }
1068
1069         /* Initialize connection parameters */
1070         self->connected = FALSE;
1071         self->avail_credit = 0;
1072         self->rx_max_sdu_size = max_sdu_size;
1073         self->rx_sdu_size = 0;
1074         self->rx_sdu_busy = FALSE;
1075         self->dtsap_sel = dtsap_sel;
1076
1077         n = self->initial_credit;
1078
1079         self->remote_credit = 0;
1080         self->send_credit = 0;
1081         
1082         /*
1083          *  Give away max 127 credits for now
1084          */
1085         if (n > 127) {
1086                 self->avail_credit=n-127;
1087                 n = 127;
1088         }
1089
1090         self->remote_credit = n;
1091
1092         /* SAR enabled? */
1093         if (max_sdu_size > 0) {
1094                 ASSERT(skb_headroom(skb) >= (TTP_MAX_HEADER + TTP_SAR_HEADER), 
1095                        return -1;);
1096
1097                 /* Insert SAR parameters */
1098                 frame = skb_push(skb, TTP_HEADER+TTP_SAR_HEADER);
1099                 
1100                 frame[0] = TTP_PARAMETERS | n; 
1101                 frame[1] = 0x04; /* Length */
1102                 frame[2] = 0x01; /* MaxSduSize */
1103                 frame[3] = 0x02; /* Value length */
1104
1105                 put_unaligned(cpu_to_be16((__u16) max_sdu_size), 
1106                               (__u16 *)(frame+4));
1107         } else {
1108                 /* Insert plain TTP header */
1109                 frame = skb_push(skb, TTP_HEADER);
1110                 
1111                 /* Insert initial credit in frame */
1112                 frame[0] = n & 0x7f;
1113         }
1114
1115         /* Connect with IrLMP. No QoS parameters for now */
1116         return irlmp_connect_request(self->lsap, dtsap_sel, saddr, daddr, qos, 
1117                                      skb);
1118 }
1119
1120 /*
1121  * Function irttp_connect_confirm (handle, qos, skb)
1122  *
1123  *    Sevice user confirms TSAP connection with peer. 
1124  *
1125  */
1126 static void irttp_connect_confirm(void *instance, void *sap, 
1127                                   struct qos_info *qos, __u32 max_seg_size,
1128                                   __u8 max_header_size, struct sk_buff *skb) 
1129 {
1130         struct tsap_cb *self;
1131         int parameters;
1132         int ret;
1133         __u8 plen;
1134         __u8 n;
1135
1136         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
1137         
1138         self = (struct tsap_cb *) instance;
1139
1140         ASSERT(self != NULL, return;);
1141         ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1142         ASSERT(skb != NULL, return;);
1143
1144         self->max_seg_size = max_seg_size - TTP_HEADER;
1145         self->max_header_size = max_header_size + TTP_HEADER;
1146
1147         /*
1148          *  Check if we have got some QoS parameters back! This should be the
1149          *  negotiated QoS for the link.
1150          */
1151         if (qos) {
1152                 IRDA_DEBUG(4, "IrTTP, Negotiated BAUD_RATE: %02x\n", 
1153                        qos->baud_rate.bits);                    
1154                 IRDA_DEBUG(4, "IrTTP, Negotiated BAUD_RATE: %d bps.\n", 
1155                        qos->baud_rate.value);
1156         }
1157
1158         n = skb->data[0] & 0x7f;
1159         
1160         IRDA_DEBUG(4, "%s(), Initial send_credit=%d\n", __FUNCTION__, n);
1161         
1162         self->send_credit = n;
1163         self->tx_max_sdu_size = 0;
1164         self->connected = TRUE;
1165
1166         parameters = skb->data[0] & 0x80;       
1167
1168         ASSERT(skb->len >= TTP_HEADER, return;);
1169         skb_pull(skb, TTP_HEADER);
1170
1171         if (parameters) {
1172                 plen = skb->data[0];
1173
1174                 ret = irda_param_extract_all(self, skb->data+1,
1175                                              IRDA_MIN(skb->len-1, plen), 
1176                                              &param_info);
1177
1178                 /* Any errors in the parameter list? */
1179                 if (ret < 0) {
1180                         WARNING("%s(), error extracting parameters\n", __FUNCTION__);
1181                         dev_kfree_skb(skb);
1182
1183                         /* Do not accept this connection attempt */
1184                         return;
1185                 }
1186                 /* Remove parameters */
1187                 skb_pull(skb, IRDA_MIN(skb->len, plen+1));
1188         }
1189         
1190         IRDA_DEBUG(4, "%s() send=%d,avail=%d,remote=%d\n", __FUNCTION__,
1191               self->send_credit, self->avail_credit, self->remote_credit);
1192
1193         IRDA_DEBUG(2, "%s(), MaxSduSize=%d\n", __FUNCTION__, self->tx_max_sdu_size);
1194
1195         if (self->notify.connect_confirm) {
1196                 self->notify.connect_confirm(self->notify.instance, self, qos,
1197                                              self->tx_max_sdu_size,
1198                                              self->max_header_size, skb);
1199         }
1200 }
1201
1202 /*
1203  * Function irttp_connect_indication (handle, skb)
1204  *
1205  *    Some other device is connecting to this TSAP
1206  *
1207  */
1208 void irttp_connect_indication(void *instance, void *sap, struct qos_info *qos,
1209                               __u32 max_seg_size, __u8 max_header_size, 
1210                               struct sk_buff *skb) 
1211 {
1212         struct tsap_cb *self;
1213         struct lsap_cb *lsap;
1214         int parameters;
1215         int ret;
1216         __u8 plen;
1217         __u8 n;
1218
1219         self = (struct tsap_cb *) instance;
1220
1221         ASSERT(self != NULL, return;);
1222         ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1223         ASSERT(skb != NULL, return;);
1224
1225         lsap = (struct lsap_cb *) sap;
1226
1227         self->max_seg_size = max_seg_size - TTP_HEADER;;
1228         self->max_header_size = max_header_size+TTP_HEADER;
1229
1230         IRDA_DEBUG(4, "%s(), TSAP sel=%02x\n", __FUNCTION__, self->stsap_sel);
1231
1232         /* Need to update dtsap_sel if its equal to LSAP_ANY */
1233         self->dtsap_sel = lsap->dlsap_sel;
1234
1235         n = skb->data[0] & 0x7f;
1236
1237         self->send_credit = n;
1238         self->tx_max_sdu_size = 0;
1239         
1240         parameters = skb->data[0] & 0x80;
1241
1242         ASSERT(skb->len >= TTP_HEADER, return;);
1243         skb_pull(skb, TTP_HEADER);
1244
1245         if (parameters) {
1246                 plen = skb->data[0];
1247                 
1248                 ret = irda_param_extract_all(self, skb->data+1,
1249                                              IRDA_MIN(skb->len-1, plen), 
1250                                              &param_info);
1251
1252                 /* Any errors in the parameter list? */
1253                 if (ret < 0) {
1254                         WARNING("%s(), error extracting parameters\n", __FUNCTION__);
1255                         dev_kfree_skb(skb);
1256                         
1257                         /* Do not accept this connection attempt */
1258                         return;
1259                 }
1260
1261                 /* Remove parameters */
1262                 skb_pull(skb, IRDA_MIN(skb->len, plen+1));
1263         }
1264
1265         if (self->notify.connect_indication) {
1266                 self->notify.connect_indication(self->notify.instance, self, 
1267                                                 qos, self->tx_max_sdu_size, 
1268                                                 self->max_header_size, skb);
1269         } else
1270                 dev_kfree_skb(skb);
1271 }
1272
1273 /*
1274  * Function irttp_connect_response (handle, userdata)
1275  *
1276  *    Service user is accepting the connection, just pass it down to
1277  *    IrLMP!
1278  * 
1279  */
1280 int irttp_connect_response(struct tsap_cb *self, __u32 max_sdu_size, 
1281                            struct sk_buff *userdata)
1282 {
1283         struct sk_buff *skb;
1284         __u8 *frame;
1285         int ret;
1286         __u8 n;
1287
1288         ASSERT(self != NULL, return -1;);
1289         ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
1290
1291         IRDA_DEBUG(4, "%s(), Source TSAP selector=%02x\n", __FUNCTION__,
1292                    self->stsap_sel);
1293         
1294         /* Any userdata supplied? */
1295         if (userdata == NULL) {
1296                 skb = dev_alloc_skb(64);
1297                 if (!skb)
1298                         return -ENOMEM;
1299
1300                 /* Reserve space for MUX_CONTROL and LAP header */
1301                 skb_reserve(skb, TTP_MAX_HEADER);
1302         } else {
1303                 skb = userdata;
1304                 /*  
1305                  *  Check that the client has reserved enough space for 
1306                  *  headers
1307                  */
1308                 ASSERT(skb_headroom(skb) >= TTP_MAX_HEADER, return -1;);
1309         }
1310         
1311         self->avail_credit = 0;
1312         self->remote_credit = 0;
1313         self->rx_max_sdu_size = max_sdu_size;
1314         self->rx_sdu_size = 0;
1315         self->rx_sdu_busy = FALSE;
1316
1317         n = self->initial_credit;
1318
1319         /* Frame has only space for max 127 credits (7 bits) */
1320         if (n > 127) {
1321                 self->avail_credit = n - 127;
1322                 n = 127;
1323         }
1324
1325         self->remote_credit = n;
1326         self->connected = TRUE;
1327
1328         /* SAR enabled? */
1329         if (max_sdu_size > 0) {
1330                 ASSERT(skb_headroom(skb) >= (TTP_MAX_HEADER+TTP_SAR_HEADER), 
1331                        return -1;);
1332                 
1333                 /* Insert TTP header with SAR parameters */
1334                 frame = skb_push(skb, TTP_HEADER+TTP_SAR_HEADER);
1335                 
1336                 frame[0] = TTP_PARAMETERS | n;
1337                 frame[1] = 0x04; /* Length */
1338
1339                 /* irda_param_insert(self, IRTTP_MAX_SDU_SIZE, frame+1,  */
1340 /*                                TTP_SAR_HEADER, &param_info) */
1341                 
1342                 frame[2] = 0x01; /* MaxSduSize */
1343                 frame[3] = 0x02; /* Value length */
1344
1345                 put_unaligned(cpu_to_be16((__u16) max_sdu_size), 
1346                               (__u16 *)(frame+4));
1347         } else {
1348                 /* Insert TTP header */
1349                 frame = skb_push(skb, TTP_HEADER);
1350                 
1351                 frame[0] = n & 0x7f;
1352         }
1353          
1354         ret = irlmp_connect_response(self->lsap, skb);
1355
1356         return ret;
1357 }
1358
1359 /*
1360  * Function irttp_dup (self, instance)
1361  *
1362  *    Duplicate TSAP, can be used by servers to confirm a connection on a
1363  *    new TSAP so it can keep listening on the old one.
1364  */
1365 struct tsap_cb *irttp_dup(struct tsap_cb *orig, void *instance) 
1366 {
1367         struct tsap_cb *new;
1368
1369         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1370
1371         if (!hashbin_find(irttp->tsaps, (int) orig, NULL)) {
1372                 IRDA_DEBUG(0, "%s(), unable to find TSAP\n", __FUNCTION__);
1373                 return NULL;
1374         }
1375         new = kmalloc(sizeof(struct tsap_cb), GFP_ATOMIC);
1376         if (!new) {
1377                 IRDA_DEBUG(0, "%s(), unable to kmalloc\n", __FUNCTION__);
1378                 return NULL;
1379         }
1380         /* Dup */
1381         memcpy(new, orig, sizeof(struct tsap_cb));
1382         new->notify.instance = instance;
1383         new->lsap = irlmp_dup(orig->lsap, new);
1384
1385         /* Not everything should be copied */
1386         init_timer(&new->todo_timer);
1387
1388         skb_queue_head_init(&new->rx_queue);
1389         skb_queue_head_init(&new->tx_queue);
1390         skb_queue_head_init(&new->rx_fragments);
1391
1392         hashbin_insert(irttp->tsaps, (irda_queue_t *) new, (int) new, NULL);
1393
1394         return new;
1395 }
1396
1397 /*
1398  * Function irttp_disconnect_request (self)
1399  *
1400  *    Close this connection please! If priority is high, the queued data 
1401  *    segments, if any, will be deallocated first
1402  *
1403  */
1404 int irttp_disconnect_request(struct tsap_cb *self, struct sk_buff *userdata, 
1405                              int priority)
1406 {
1407         struct sk_buff *skb;
1408         int ret;
1409
1410         ASSERT(self != NULL, return -1;);
1411         ASSERT(self->magic == TTP_TSAP_MAGIC, return -1;);
1412
1413         /* Already disconnected? */
1414         if (!self->connected) {
1415                 IRDA_DEBUG(4, "%s(), already disconnected!\n", __FUNCTION__);
1416                 if (userdata)
1417                         dev_kfree_skb(userdata);
1418                 return -1;
1419         }
1420
1421         /* Disconnect already pending ?
1422          * We need to use an atomic operation to prevent reentry. This
1423          * function may be called from various context, like user, timer
1424          * for following a disconnect_indication() (i.e. net_bh).
1425          * Jean II */
1426         if(test_and_set_bit(0, &self->disconnect_pend)) {
1427                 IRDA_DEBUG(0, "%s(), disconnect already pending\n", __FUNCTION__);
1428                 if (userdata)
1429                         dev_kfree_skb(userdata);
1430
1431                 /* Try to make some progress */
1432                 irttp_run_tx_queue(self);
1433                 return -1;
1434         }
1435
1436         /*
1437          *  Check if there is still data segments in the transmit queue
1438          */
1439         if (skb_queue_len(&self->tx_queue) > 0) {
1440                 if (priority == P_HIGH) {
1441                         /* 
1442                          *  No need to send the queued data, if we are 
1443                          *  disconnecting right now since the data will
1444                          *  not have any usable connection to be sent on
1445                          */
1446                         IRDA_DEBUG(1, "%s High priority!!()\n", __FUNCTION__);
1447                         irttp_flush_queues(self);
1448                 } else if (priority == P_NORMAL) {
1449                         /* 
1450                          *  Must delay disconnect until after all data segments
1451                          *  have been sent and the tx_queue is empty
1452                          */
1453                         /* We'll reuse this one later for the disconnect */
1454                         self->disconnect_skb = userdata;  /* May be NULL */
1455
1456                         irttp_run_tx_queue(self);
1457
1458                         irttp_start_todo_timer(self, HZ/10);
1459                         return -1;
1460                 }
1461         }
1462         /* Note : we don't need to check if self->rx_queue is full and the
1463          * state of self->rx_sdu_busy because the disconnect response will
1464          * be sent at the LMP level (so even if the peer has its Tx queue
1465          * full of data). - Jean II */
1466
1467         IRDA_DEBUG(1, "%s(), Disconnecting ...\n", __FUNCTION__);
1468         self->connected = FALSE;
1469
1470         if (!userdata) {
1471                 skb = dev_alloc_skb(64);
1472                 if (!skb)
1473                         return -ENOMEM;
1474                 
1475                 /* 
1476                  *  Reserve space for MUX and LAP header 
1477                  */
1478                 skb_reserve(skb, TTP_MAX_HEADER);
1479                 
1480                 userdata = skb;
1481         }
1482         ret = irlmp_disconnect_request(self->lsap, userdata);
1483
1484         /* The disconnect is no longer pending */
1485         clear_bit(0, &self->disconnect_pend);   /* FALSE */
1486
1487         return ret;
1488 }
1489
1490 /*
1491  * Function irttp_disconnect_indication (self, reason)
1492  *
1493  *    Disconnect indication, TSAP disconnected by peer?
1494  *
1495  */
1496 void irttp_disconnect_indication(void *instance, void *sap, LM_REASON reason, 
1497                                  struct sk_buff *skb) 
1498 {
1499         struct tsap_cb *self;
1500
1501         IRDA_DEBUG(4, "%s()\n", __FUNCTION__);
1502
1503         self = (struct tsap_cb *) instance;
1504         
1505         ASSERT(self != NULL, return;);
1506         ASSERT(self->magic == TTP_TSAP_MAGIC, return;);
1507         
1508         /* Prevent higher layer to send more data */
1509         self->connected = FALSE;
1510         
1511         /* Check if client has already tried to close the TSAP */
1512         if (self->close_pend) {
1513                 /* In this case, the higher layer is probably gone. Don't
1514                  * bother it and clean up the remains - Jean II */
1515                 if (skb)
1516                         dev_kfree_skb(skb);
1517                 irttp_close_tsap(self);
1518                 return;
1519         }
1520
1521         /* If we are here, we assume that is the higher layer is still
1522          * waiting for the disconnect notification and able to process it,
1523          * even if he tried to disconnect. Otherwise, it would have already
1524          * attempted to close the tsap and self->close_pend would be TRUE.
1525          * Jean II */
1526
1527         /* No need to notify the client if has already tried to disconnect */
1528         if(self->notify.disconnect_indication)
1529                 self->notify.disconnect_indication(self->notify.instance, self,
1530                                                    reason, skb);
1531         else
1532                 if (skb)
1533                         dev_kfree_skb(skb);
1534 }
1535
1536 /*
1537  * Function irttp_do_data_indication (self, skb)
1538  *
1539  *    Try to deliver reassebled skb to layer above, and requeue it if that
1540  *    for some reason should fail. We mark rx sdu as busy to apply back
1541  *    pressure is necessary.
1542  */
1543 void irttp_do_data_indication(struct tsap_cb *self, struct sk_buff *skb)
1544 {
1545         int err;
1546
1547         /* Check if client has already tried to close the TSAP */
1548         if (self->close_pend) {
1549                 dev_kfree_skb(skb);
1550                 return;
1551         }
1552
1553         err = self->notify.data_indication(self->notify.instance, self, skb);
1554
1555         /* Usually the layer above will notify that it's input queue is
1556          * starting to get filled by using the flow request, but this may
1557          * be difficult, so it can instead just refuse to eat it and just
1558          * give an error back 
1559          */
1560         if (err == -ENOMEM) {
1561                 IRDA_DEBUG(0, "%s() requeueing skb!\n", __FUNCTION__);
1562
1563                 /* Make sure we take a break */
1564                 self->rx_sdu_busy = TRUE;
1565                 
1566                 /* Need to push the header in again */
1567                 skb_push(skb, TTP_HEADER);
1568                 skb->data[0] = 0x00; /* Make sure MORE bit is cleared */
1569                 
1570                 /* Put skb back on queue */
1571                 skb_queue_head(&self->rx_queue, skb);
1572         }
1573 }
1574
1575 /*
1576  * Function irttp_run_rx_queue (self)
1577  *
1578  *     Check if we have any frames to be transmitted, or if we have any
1579  *     available credit to give away.
1580  */
1581 void irttp_run_rx_queue(struct tsap_cb *self) 
1582 {
1583         struct sk_buff *skb;
1584         int more = 0;
1585
1586         IRDA_DEBUG(2, "%s() send=%d,avail=%d,remote=%d\n", __FUNCTION__,
1587                    self->send_credit, self->avail_credit, self->remote_credit);
1588
1589         /* Get exclusive access to the rx queue, otherwise don't touch it */
1590         if (irda_lock(&self->rx_queue_lock) == FALSE)
1591                 return;
1592         
1593         /*
1594          *  Reassemble all frames in receive queue and deliver them
1595          */
1596         while (!self->rx_sdu_busy && (skb = skb_dequeue(&self->rx_queue))) {
1597                 /* This bit will tell us if it's the last fragment or not */
1598                 more = skb->data[0] & 0x80;
1599
1600                 /* Remove TTP header */
1601                 skb_pull(skb, TTP_HEADER);
1602
1603                 /* Add the length of the remaining data */
1604                 self->rx_sdu_size += skb->len;
1605
1606                 /*  
1607                  * If SAR is disabled, or user has requested no reassembly
1608                  * of received fragments then we just deliver them
1609                  * immediately. This can be requested by clients that
1610                  * implements byte streams without any message boundaries
1611                  */
1612                 if (self->rx_max_sdu_size == TTP_SAR_DISABLE) {
1613                         irttp_do_data_indication(self, skb);
1614                         self->rx_sdu_size = 0;
1615
1616                         continue;
1617                 }
1618
1619                 /* Check if this is a fragment, and not the last fragment */
1620                 if (more) {
1621                         /*  
1622                          *  Queue the fragment if we still are within the 
1623                          *  limits of the maximum size of the rx_sdu
1624                          */
1625                         if (self->rx_sdu_size <= self->rx_max_sdu_size) {
1626                                 IRDA_DEBUG(4, "%s(), queueing frag\n", __FUNCTION__);
1627                                 skb_queue_tail(&self->rx_fragments, skb);
1628                         } else {
1629                                 /* Free the part of the SDU that is too big */
1630                                 dev_kfree_skb(skb);
1631                         }
1632                         continue;
1633                 }
1634                 /*
1635                  *  This is the last fragment, so time to reassemble!
1636                  */
1637                 if ((self->rx_sdu_size <= self->rx_max_sdu_size) ||
1638                     (self->rx_max_sdu_size == TTP_SAR_UNBOUND)) 
1639                 {
1640                         /* 
1641                          * A little optimizing. Only queue the fragment if
1642                          * there are other fragments. Since if this is the
1643                          * last and only fragment, there is no need to
1644                          * reassemble :-) 
1645                          */
1646                         if (!skb_queue_empty(&self->rx_fragments)) {
1647                                 skb_queue_tail(&self->rx_fragments, 
1648                                                skb);
1649                                 
1650                                 skb = irttp_reassemble_skb(self);
1651                         }
1652                         
1653                         /* Now we can deliver the reassembled skb */
1654                         irttp_do_data_indication(self, skb);
1655                 } else {
1656                         IRDA_DEBUG(1, "%s(), Truncated frame\n", __FUNCTION__);
1657                         
1658                         /* Free the part of the SDU that is too big */
1659                         dev_kfree_skb(skb);
1660
1661                         /* Deliver only the valid but truncated part of SDU */
1662                         skb = irttp_reassemble_skb(self);
1663                         
1664                         irttp_do_data_indication(self, skb);
1665                 }
1666                 self->rx_sdu_size = 0;
1667         }
1668
1669         /*
1670          * It's not trivial to keep track of how many credits are available
1671          * by incrementing at each packet, because delivery may fail 
1672          * (irttp_do_data_indication() may requeue the frame) and because
1673          * we need to take care of fragmentation.
1674          * We want the other side to send up to initial_credit packets.
1675          * We have some frames in our queues, and we have already allowed it
1676          * to send remote_credit.
1677          * No need to spinlock, write is atomic and self correcting...
1678          * Jean II
1679          */
1680         self->avail_credit = (self->initial_credit -
1681                               (self->remote_credit +
1682                                skb_queue_len(&self->rx_queue) +
1683                                skb_queue_len(&self->rx_fragments)));
1684
1685         /* Do we have too much credits to send to peer ? */
1686         if ((self->remote_credit <= TTP_RX_MIN_CREDIT) &&
1687             (self->avail_credit > 0)) {
1688                 /* Send explicit credit frame */
1689                 irttp_give_credit(self);
1690                 /* Note : do *NOT* check if tx_queue is non-empty, that
1691                  * will produce deadlocks. I repeat : send a credit frame
1692                  * even if we have something to send in our Tx queue.
1693                  * If we have credits, it means that our Tx queue is blocked.
1694                  *
1695                  * Let's suppose the peer can't keep up with our Tx. He will
1696                  * flow control us by not sending us any credits, and we
1697                  * will stop Tx and start accumulating credits here.
1698                  * Up to the point where the peer will stop its Tx queue,
1699                  * for lack of credits.
1700                  * Let's assume the peer application is single threaded.
1701                  * It will block on Tx and never consume any Rx buffer.
1702                  * Deadlock. Guaranteed. - Jean II
1703                  */
1704         }
1705
1706         /* Reset lock */
1707         self->rx_queue_lock = 0;
1708 }
1709
1710 #ifdef CONFIG_PROC_FS
1711 /*
1712  * Function irttp_proc_read (buf, start, offset, len, unused)
1713  *
1714  *    Give some info to the /proc file system
1715  */
1716 int irttp_proc_read(char *buf, char **start, off_t offset, int len)
1717 {
1718         struct tsap_cb *self;
1719         unsigned long flags;
1720         int i = 0;
1721         
1722         ASSERT(irttp != NULL, return 0;);
1723         
1724         len = 0;
1725         
1726         save_flags(flags);
1727         cli();
1728
1729         self = (struct tsap_cb *) hashbin_get_first(irttp->tsaps);
1730         while (self != NULL) {
1731                 if (!self || self->magic != TTP_TSAP_MAGIC)
1732                         break;
1733
1734                 len += sprintf(buf+len, "TSAP %d, ", i++);
1735                 len += sprintf(buf+len, "stsap_sel: %02x, ", 
1736                                self->stsap_sel);
1737                 len += sprintf(buf+len, "dtsap_sel: %02x\n", 
1738                                self->dtsap_sel);
1739                 len += sprintf(buf+len, "  connected: %s, ",
1740                                self->connected? "TRUE":"FALSE");
1741                 len += sprintf(buf+len, "avail credit: %d, ",
1742                                self->avail_credit);
1743                 len += sprintf(buf+len, "remote credit: %d, ",
1744                                self->remote_credit);
1745                 len += sprintf(buf+len, "send credit: %d\n",
1746                                self->send_credit);
1747                 len += sprintf(buf+len, "  tx packets: %ld, ",
1748                                self->stats.tx_packets);
1749                 len += sprintf(buf+len, "rx packets: %ld, ",
1750                                self->stats.rx_packets);
1751                 len += sprintf(buf+len, "tx_queue len: %d ", 
1752                                skb_queue_len(&self->tx_queue));
1753                 len += sprintf(buf+len, "rx_queue len: %d\n", 
1754                                skb_queue_len(&self->rx_queue));
1755                 len += sprintf(buf+len, "  tx_sdu_busy: %s, ",
1756                                self->tx_sdu_busy? "TRUE":"FALSE");
1757                 len += sprintf(buf+len, "rx_sdu_busy: %s\n",
1758                                self->rx_sdu_busy? "TRUE":"FALSE");
1759                 len += sprintf(buf+len, "  max_seg_size: %d, ",
1760                                self->max_seg_size);
1761                 len += sprintf(buf+len, "tx_max_sdu_size: %d, ",
1762                                self->tx_max_sdu_size);
1763                 len += sprintf(buf+len, "rx_max_sdu_size: %d\n",
1764                                self->rx_max_sdu_size);
1765
1766                 len += sprintf(buf+len, "  Used by (%s)\n", 
1767                                 self->notify.name);
1768
1769                 len += sprintf(buf+len, "\n");
1770                 
1771                 self = (struct tsap_cb *) hashbin_get_next(irttp->tsaps);
1772         }
1773         restore_flags(flags);
1774
1775         return len;
1776 }
1777
1778 #endif /* PROC_FS */