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