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