c3a86b1878c7c65b4408d34afa8e190305b49273
[osmocom-bb.git] / src / host / layer23 / src / lapdm.c
1 /* GSM LAPDm (TS 04.06) implementation */
2
3 /* (C) 2010 by Harald Welte <laforge@gnumonks.org>
4  * (C) 2010 by Andreas Eversberg <jolly@eversberg.eu>
5  *
6  * All Rights Reserved
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  */
23
24 /* Notes on Buffering: rcv_buffer, tx_queue, tx_hist, send_buffer, send_queue
25  *
26  * RX data is stored in the rcv_buffer (pointer). If the message is complete, it
27  * is removed from rcv_buffer pointer and forwarded to L3. If the RX data is
28  * received while there is an incomplete rcv_buffer, it is appended to it.
29  *
30  * TX data is stored in the send_queue first. When transmitting a frame,
31  * the first message in the send_queue is moved to the send_buffer. There it
32  * resides until all fragments are acknowledged. Fragments to be sent by I
33  * frames are stored in the tx_hist buffer for resend, if required. Also the
34  * current fragment is copied into the tx_queue. There it resides until it is
35  * forwarded to layer 1.
36  *
37  * In case we have SAPI 0, we only have a window size of 1, so the unack-
38  * nowledged message resides always in the send_buffer. In case of a suspend,
39  * it can be written back to the first position of the send_queue.
40  *
41  * The layer 1 normally sends a PH-READY-TO-SEND. But because we use
42  * asynchronous transfer between layer 1 and layer 2 (serial link), we must
43  * send a frame before layer 1 reaches the right timeslot to send it. So we
44  * move the tx_queue to layer 1 when there is not already a pending frame, and
45  * wait until acknowledge after the frame has been sent. If we receive an
46  * acknowledge, we can send the next frame from the buffer, if any.
47  *
48  * The moving of tx_queue to layer 1 may also trigger T200, if desired. Also it
49  * will trigger next I frame, if possible.
50  *
51  */
52
53 #include <stdio.h>
54 #include <stdint.h>
55 #include <string.h>
56 #include <errno.h>
57
58 #include <osmocore/logging.h>
59 #include <osmocore/timer.h>
60 #include <osmocore/msgb.h>
61 #include <osmocore/tlv.h>
62 #include <osmocore/utils.h>
63 #include <osmocore/rsl.h>
64 #include <osmocore/protocol/gsm_04_08.h>
65 #include <osmocore/protocol/gsm_08_58.h>
66
67 #include <osmocom/osmocom_data.h>
68 #include <osmocom/l1ctl.h>
69 #include <osmocom/lapdm.h>
70 #include <osmocom/logging.h>
71
72 #include <l1a_l23_interface.h>
73
74 /* TS 04.06 Figure 4 / Section 3.2 */
75 #define LAPDm_LPD_NORMAL  0
76 #define LAPDm_LPD_SMSCB   1
77 #define LAPDm_SAPI_NORMAL 0
78 #define LAPDm_SAPI_SMS    3
79 #define LAPDm_ADDR(lpd, sapi, cr) ((((lpd) & 0x3) << 5) | (((sapi) & 0x7) << 2) | (((cr) & 0x1) << 1) | 0x1)
80
81 #define LAPDm_ADDR_SAPI(addr) (((addr) >> 2) & 0x7)
82 #define LAPDm_ADDR_CR(addr) (((addr) >> 1) & 0x1)
83 #define LAPDm_ADDR_EA(addr) ((addr) & 0x1)
84
85 /* TS 04.06 Table 3 / Section 3.4.3 */
86 #define LAPDm_CTRL_I(nr, ns, p) ((((nr) & 0x7) << 5) | (((p) & 0x1) << 4) | (((ns) & 0x7) << 1))
87 #define LAPDm_CTRL_S(nr, s, p)  ((((nr) & 0x7) << 5) | (((p) & 0x1) << 4) | (((s) & 0x3) << 2) | 0x1)
88 #define LAPDm_CTRL_U(u, p)      ((((u) & 0x1c) << (5-2)) | (((p) & 0x1) << 4) | (((u) & 0x3) << 2) | 0x3)
89
90 #define LAPDm_CTRL_is_I(ctrl)   (((ctrl) & 0x1) == 0)
91 #define LAPDm_CTRL_is_S(ctrl)   (((ctrl) & 0x3) == 1)
92 #define LAPDm_CTRL_is_U(ctrl)   (((ctrl) & 0x3) == 3)
93
94 #define LAPDm_CTRL_U_BITS(ctrl) ((((ctrl) & 0xC) >> 2) | ((ctrl) & 0xE0) >> 3)
95 #define LAPDm_CTRL_PF_BIT(ctrl) (((ctrl) >> 4) & 0x1)
96
97 #define LAPDm_CTRL_S_BITS(ctrl) (((ctrl) & 0xC) >> 2)
98
99 #define LAPDm_CTRL_I_Ns(ctrl)   (((ctrl) & 0xE) >> 1)
100 #define LAPDm_CTRL_Nr(ctrl)     (((ctrl) & 0xE0) >> 5)
101
102 /* TS 04.06 Table 4 / Section 3.8.1 */
103 #define LAPDm_U_SABM    0x7
104 #define LAPDm_U_DM      0x3
105 #define LAPDm_U_UI      0x0
106 #define LAPDm_U_DISC    0x8
107 #define LAPDm_U_UA      0xC
108
109 #define LAPDm_S_RR      0x0
110 #define LAPDm_S_RNR     0x1
111 #define LAPDm_S_REJ     0x2
112
113 #define LAPDm_LEN(len)  ((len << 2) | 0x1)
114 #define LAPDm_MORE      0x2
115
116 /* TS 04.06 Section 5.8.3 */
117 #define N201_AB_SACCH           18
118 #define N201_AB_SDCCH           20
119 #define N201_AB_FACCH           20
120 #define N201_Bbis               23
121 #define N201_Bter_SACCH         21
122 #define N201_Bter_SDCCH         23
123 #define N201_Bter_FACCH         23
124 #define N201_B4                 19
125
126 /* 5.8.2.1 N200 during establish and release */
127 #define N200_EST_REL            5
128 /* 5.8.2.1 N200 during timer recovery state */
129 #define N200_TR_SACCH           5
130 #define N200_TR_SDCCH           23
131 #define N200_TR_FACCH_FR        34
132 #define N200_TR_EFACCH_FR       48
133 #define N200_TR_FACCH_HR        29
134 /* FIXME: this depends on chan type */
135 #define N200    N200_TR_SACCH
136
137 #define CR_MS2BS_CMD    0
138 #define CR_MS2BS_RESP   1
139 #define CR_BS2MS_CMD    1
140 #define CR_BS2MS_RESP   0
141
142 /* Set T200 to 1 Second (OpenBTS uses 900ms) */
143 #define T200    1, 0
144
145 /* k value for each SAPI */
146 static uint8_t k_sapi[] = {1, 1, 1, 1, 1, 1, 1, 1};
147
148 enum lapdm_format {
149         LAPDm_FMT_A,
150         LAPDm_FMT_B,
151         LAPDm_FMT_Bbis,
152         LAPDm_FMT_Bter,
153         LAPDm_FMT_B4,
154 };
155
156 static void lapdm_t200_cb(void *data);
157 static int rslms_send_i(struct lapdm_msg_ctx *mctx);
158
159 /* UTILITY FUNCTIONS */
160
161 static inline uint8_t inc_mod8(uint8_t x)
162 {
163         return (x + 1) & 7;
164 }
165
166 static inline uint8_t add_mod8(uint8_t x, uint8_t y)
167 {
168         return (x + y) & 7;
169 }
170
171 static inline uint8_t sub_mod8(uint8_t x, uint8_t y)
172 {
173         return (x - y) & 7; /* handle negative results correctly */
174 }
175
176 static void lapdm_dl_init(struct lapdm_datalink *dl,
177                           struct lapdm_entity *entity)
178 {
179         memset(dl, 0, sizeof(*dl));
180         INIT_LLIST_HEAD(&dl->send_queue);
181         INIT_LLIST_HEAD(&dl->tx_queue);
182         dl->state = LAPDm_STATE_IDLE;
183         dl->t200.data = dl;
184         dl->t200.cb = &lapdm_t200_cb;
185         dl->entity = entity;
186 }
187
188 void lapdm_init(struct lapdm_entity *le, struct osmocom_ms *ms)
189 {
190         unsigned int i;
191
192         for (i = 0; i < ARRAY_SIZE(le->datalink); i++)
193                 lapdm_dl_init(&le->datalink[i], le);
194
195         le->ms = ms;
196 }
197
198 static void lapdm_dl_flush_send(struct lapdm_datalink *dl)
199 {
200         struct msgb *msg;
201
202         /* Flush send-queue */
203         while ((msg = msgb_dequeue(&dl->send_queue)))
204                 msgb_free(msg);
205
206         /* Clear send-buffer */
207         if (dl->send_buffer) {
208                 msgb_free(dl->send_buffer);
209                 dl->send_buffer = NULL;
210         }
211 }
212
213 static void lapdm_dl_flush_tx(struct lapdm_datalink *dl)
214 {
215         struct msgb *msg;
216         unsigned int i;
217
218         while ((msg = msgb_dequeue(&dl->tx_queue)))
219                 msgb_free(msg);
220         for (i = 0; i < 8; i++)
221                 dl->tx_length[i] = 0;
222 }
223
224 void lapdm_exit(struct lapdm_entity *le)
225 {
226         unsigned int i;
227         struct lapdm_datalink *dl;
228
229         for (i = 0; i < ARRAY_SIZE(le->datalink); i++) {
230                 dl = &le->datalink[i];
231                 lapdm_dl_flush_tx(dl);
232                 lapdm_dl_flush_send(dl);
233                 if (dl->rcv_buffer)
234                         msgb_free(dl->rcv_buffer);
235         }
236 }
237
238 static void lapdm_dl_newstate(struct lapdm_datalink *dl, uint32_t state)
239 {
240         LOGP(DLAPDM, LOGL_INFO, "new state %s -> %s\n",
241                 lapdm_state_names[dl->state], lapdm_state_names[state]);
242         
243         dl->state = state;
244 }
245
246 static struct lapdm_datalink *datalink_for_sapi(struct lapdm_entity *le, uint8_t sapi)
247 {
248         switch (sapi) {
249         case LAPDm_SAPI_NORMAL:
250                 return &le->datalink[0];
251         case LAPDm_SAPI_SMS:
252                 return &le->datalink[1];
253         default:
254                 return NULL;
255         }
256 }
257
258 /* remove the L2 header from a MSGB */
259 static inline unsigned char *msgb_pull_l2h(struct msgb *msg)
260 {
261         unsigned char *ret = msgb_pull(msg, msg->l3h - msg->l2h);
262         msg->l2h = NULL;
263         return ret;
264 }
265
266 /* Append padding (if required) */
267 static void lapdm_pad_msgb(struct msgb *msg, uint8_t n201)
268 {
269         int pad_len = n201 - msgb_l2len(msg);
270         uint8_t *data;
271
272         if (pad_len < 0) {
273                 LOGP(DLAPDM, LOGL_ERROR,
274                      "cannot pad message that is already too big!\n");
275                 return;
276         }
277
278         data = msgb_put(msg, pad_len);
279         memset(data, 0x2B, pad_len);
280 }
281
282 /* write a frame into the tx queue */
283 static int tx_ph_data_enqueue(struct lapdm_datalink *dl, struct msgb *msg,
284                                 uint8_t chan_nr, uint8_t link_id, uint8_t n201)
285 {
286         struct lapdm_entity *le = dl->entity;
287         struct osmocom_ms *ms = le->ms;
288
289         /* if there is a pending message, queue it */
290         if (le->tx_pending) {
291                 *msgb_push(msg, 1) = n201;
292                 *msgb_push(msg, 1) = link_id;
293                 *msgb_push(msg, 1) = chan_nr;
294                 msgb_enqueue(&dl->tx_queue, msg);
295                 return -EBUSY;
296         }
297
298         /* send the frame now */
299         le->tx_pending = 1;
300 #warning HACK: no confirm yet! (queue is always empty now)
301 le->tx_pending = 0;
302 printf("-> tx chan_nr 0x%x link_id 0x%x len %d data", chan_nr, link_id, msgb_l2len(msg));
303 int i;
304 for (i = 0; i < msgb_l2len(msg); i++)
305         printf(" %02x", msg->l2h[i]);
306 printf("\n");
307 //usleep(100000);
308         lapdm_pad_msgb(msg, n201);
309         return tx_ph_data_req(ms, msg, chan_nr, link_id);
310 }
311
312 /* get next frame from the tx queue. because the ms has multiple datalinks,
313  * each datalink's queue is read round-robin.
314  */
315 static int tx_ph_data_dequeue(struct lapdm_entity *le)
316 {
317         struct osmocom_ms *ms = le->ms;
318         struct lapdm_datalink *dl;
319         int last = le->last_tx_dequeue;
320         int i = last, n = ARRAY_SIZE(le->datalink);
321         struct msgb *msg;
322         uint8_t chan_nr, link_id, n201;
323
324         /* round-robin dequeue */
325         do {
326                 /* next */
327                 i = (i + 1) % n;
328                 dl = &le->datalink[i];
329                 if ((msg = msgb_dequeue(&dl->tx_queue)))
330                         break;
331         } while (i != last);
332
333         /* no message in all queues */
334         if (msg)
335                 return 0;
336
337         /* Pull chan_nr and link_id */
338         chan_nr = *msg->data;
339         msgb_pull(msg, 1);
340         link_id = *msg->data;
341         msgb_pull(msg, 1);
342         n201 = *msg->data;
343         msgb_pull(msg, 1);
344
345         /* Set last dequeue position */
346         le->last_tx_dequeue = i;
347
348         /* Pad the frame, we can transmit now */
349         le->tx_pending = 1;
350         lapdm_pad_msgb(msg, n201);
351         return tx_ph_data_req(ms, msg, chan_nr, link_id);
352 }
353
354 /* Take a Bbis format message from L1 and create RSLms UNIT DATA IND */
355 static int send_rslms_rll_l3(uint8_t msg_type, struct lapdm_msg_ctx *mctx,
356                              struct msgb *msg)
357 {
358         /* Add the RSL + RLL header */
359         rsl_rll_push_l3(msg, msg_type, mctx->chan_nr, mctx->link_id, 1);
360
361         /* send off the RSLms message to L3 */
362         return rslms_sendmsg(msg, mctx->dl->entity->ms);
363 }
364
365 static int send_rll_simple(uint8_t msg_type, struct lapdm_msg_ctx *mctx)
366 {
367         struct msgb *msg;
368
369         msg = rsl_rll_simple(msg_type, mctx->chan_nr, mctx->link_id, 1);
370
371         /* send off the RSLms message to L3 */
372         return rslms_sendmsg(msg, mctx->dl->entity->ms);
373 }
374
375 static int rsl_rll_error(uint8_t cause, struct lapdm_msg_ctx *mctx)
376 {
377         struct msgb *msg;
378
379         LOGP(DLAPDM, LOGL_NOTICE, "sending MDL-ERROR-IND %d\n", cause);
380         msg = rsl_rll_simple(RSL_MT_ERROR_IND, mctx->chan_nr, mctx->link_id, 1);
381         msg->l2h = msgb_put(msg, sizeof(struct abis_rsl_rll_hdr) + 1);
382         msg->l2h[0] = cause;
383         return rslms_sendmsg(msg, mctx->dl->entity->ms);
384 }
385
386 static int check_length_ind(struct lapdm_msg_ctx *mctx, uint8_t length_ind)
387 {
388         if (!(length_ind & 0x01)) {
389                 /* G.4.1 If the EL bit is set to "0", an MDL-ERROR-INDICATION
390                  * primitive with cause "frame not implemented" is sent to the
391                  * mobile management entity. */
392                 LOGP(DLAPDM, LOGL_NOTICE,
393                         "we don't support multi-octet length\n");
394                 rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
395                 return -EINVAL;
396         }
397         return 0;
398 }
399
400 static int lapdm_send_resend(struct lapdm_datalink *dl)
401 {
402         struct msgb *msg = msgb_alloc_headroom(23+10, 10, "LAPDm resend");
403         int length;
404
405         /* Resend SABM/DISC from tx_hist */
406         length = dl->tx_length[0];
407         msg->l2h = msgb_put(msg, length);
408         memcpy(msg->l2h, dl->tx_hist[dl->V_send], length);
409
410         return tx_ph_data_enqueue(dl, msg, dl->mctx.chan_nr, dl->mctx.link_id,
411                         dl->mctx.n201);
412 }
413
414 static int lapdm_send_ua(struct lapdm_msg_ctx *mctx, uint8_t len, uint8_t *data)
415 {
416         uint8_t sapi = mctx->link_id & 7;
417         uint8_t f_bit = LAPDm_CTRL_PF_BIT(mctx->ctrl);
418         struct msgb *msg = msgb_alloc_headroom(23+10, 10, "LAPDm UA");
419         msg->l2h = msgb_put(msg, 3 + len);
420
421         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_RESP);
422         msg->l2h[1] = LAPDm_CTRL_U(LAPDm_U_UA, f_bit);
423         msg->l2h[2] = LAPDm_LEN(len);
424         if (len)
425                 memcpy(msg->l2h + 3, data, len);
426
427         return tx_ph_data_enqueue(mctx->dl, msg, mctx->chan_nr, mctx->link_id,
428                         mctx->n201);
429 }
430
431 static int lapdm_send_dm(struct lapdm_msg_ctx *mctx)
432 {
433         uint8_t sapi = mctx->link_id & 7;
434         uint8_t f_bit = LAPDm_CTRL_PF_BIT(mctx->ctrl);
435         struct msgb *msg = msgb_alloc_headroom(23+10, 10, "LAPDm DM");
436         msg->l2h = msgb_put(msg, 3);
437
438         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_RESP);
439         msg->l2h[1] = LAPDm_CTRL_U(LAPDm_U_DM, f_bit);
440         msg->l2h[2] = 0;
441
442         return tx_ph_data_enqueue(mctx->dl, msg, mctx->chan_nr, mctx->link_id,
443                         mctx->n201);
444 }
445
446 static int lapdm_send_rr(struct lapdm_msg_ctx *mctx, uint8_t f_bit)
447 {
448         uint8_t sapi = mctx->link_id & 7;
449         struct msgb *msg = msgb_alloc_headroom(23+10, 10, "LAPDm RR");
450         msg->l2h = msgb_put(msg, 3);
451
452         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_RESP);
453         msg->l2h[1] = LAPDm_CTRL_S(mctx->dl->V_recv, LAPDm_S_RR, f_bit);
454         msg->l2h[2] = LAPDm_LEN(0);
455
456         return tx_ph_data_enqueue(mctx->dl, msg, mctx->chan_nr, mctx->link_id,
457                         mctx->n201);
458 }
459
460 static int lapdm_send_rnr(struct lapdm_msg_ctx *mctx, uint8_t f_bit)
461 {
462         uint8_t sapi = mctx->link_id & 7;
463         struct msgb *msg = msgb_alloc_headroom(23+10, 10, "LAPDm RNR");
464         msg->l2h = msgb_put(msg, 3);
465
466         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_RESP);
467         msg->l2h[1] = LAPDm_CTRL_S(mctx->dl->V_recv, LAPDm_S_RNR, f_bit);
468         msg->l2h[2] = LAPDm_LEN(0);
469
470         return tx_ph_data_enqueue(mctx->dl, msg, mctx->chan_nr, mctx->link_id,
471                         mctx->n201);
472 }
473
474 static int lapdm_send_rej(struct lapdm_msg_ctx *mctx, uint8_t f_bit)
475 {
476         uint8_t sapi = mctx->link_id & 7;
477         struct msgb *msg = msgb_alloc_headroom(23+10, 10, "LAPDm REJ");
478         msg->l2h = msgb_put(msg, 3);
479
480         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_RESP);
481         msg->l2h[1] = LAPDm_CTRL_S(mctx->dl->V_recv, LAPDm_S_REJ, f_bit);
482         msg->l2h[2] = LAPDm_LEN(0);
483
484         return tx_ph_data_enqueue(mctx->dl, msg, mctx->chan_nr, mctx->link_id,
485                         mctx->n201);
486 }
487
488 /* Timer callback on T200 expiry */
489 static void lapdm_t200_cb(void *data)
490 {
491         struct lapdm_datalink *dl = data;
492
493         LOGP(DLAPDM, LOGL_INFO, "lapdm_t200_cb(%p) state=%u\n", dl, dl->state);
494
495         switch (dl->state) {
496         case LAPDm_STATE_SABM_SENT:
497                 /* 5.4.1.3 */
498                 if (dl->retrans_ctr + 1 >= N200_EST_REL + 1) {
499                         /* send RELEASE INDICATION to L3 */
500                         send_rll_simple(RSL_MT_REL_IND, &dl->mctx);
501                         /* send MDL ERROR INIDCATION to L3 */
502                         rsl_rll_error(RLL_CAUSE_T200_EXPIRED, &dl->mctx);
503                         /* go back to idle state */
504                         lapdm_dl_newstate(dl, LAPDm_STATE_IDLE);
505                         /* NOTE: we must not change any other states or buffers
506                          * and queues, since we may reconnect after handover
507                          * failure. the buffered messages is replaced there */
508                         break;
509                 }
510                 /* retransmit SABM command */
511                 lapdm_send_resend(dl);
512                 /* increment re-transmission counter */
513                 dl->retrans_ctr++;
514                 /* restart T200 (PH-READY-TO-SEND) */
515                 bsc_schedule_timer(&dl->t200, T200);
516                 break;
517         case LAPDm_STATE_DISC_SENT:
518                 /* 5.4.4.3 */
519                 if (dl->retrans_ctr + 1 >= N200_EST_REL + 1) {
520                         /* send RELEASE INDICATION to L3 */
521                         send_rll_simple(RSL_MT_REL_CONF, &dl->mctx);
522                         /* send MDL ERROR INIDCATION to L3 */
523                         rsl_rll_error(RLL_CAUSE_T200_EXPIRED, &dl->mctx);
524                         /* go back to idle state */
525                         lapdm_dl_newstate(dl, LAPDm_STATE_IDLE);
526                         /* NOTE: we must not change any other states or buffers
527                          * and queues, since we may reconnect after handover
528                          * failure. the buffered messages is replaced there */
529                         break;
530                 }
531                 /* retransmit DISC command */
532                 lapdm_send_resend(dl);
533                 /* increment re-transmission counter */
534                 dl->retrans_ctr++;
535                 /* restart T200 (PH-READY-TO-SEND) */
536                 bsc_schedule_timer(&dl->t200, T200);
537                 break;
538         case LAPDm_STATE_MF_EST:
539                 /* 5.5.7 */
540                 dl->retrans_ctr = 0;
541                 lapdm_dl_newstate(dl, LAPDm_STATE_TIMER_RECOV);
542                 /* fall through */
543         case LAPDm_STATE_TIMER_RECOV:
544                 dl->retrans_ctr++;
545                 if (dl->retrans_ctr < N200) {
546                         /* retransmit I frame (V_s-1) with P=1, if any */
547                         if (dl->tx_length[dl->V_send - 1]) {
548                                 struct msgb *msg;
549                                 int length;
550
551                                 LOGP(DLAPDM, LOGL_INFO, "retransmit last frame "
552                                         "V(S)=%d\n", dl->V_send - 1);
553                                 /* Create I frame (segment) from tx_hist */
554                                 length = dl->tx_length[dl->V_send - 1];
555                                 msg = msgb_alloc_headroom(23+10, 10, "LAPDm I");
556                                 msg->l2h = msgb_put(msg, length);
557                                 memcpy(msg->l2h, dl->tx_hist[dl->V_send - 1],
558                                         length);
559                                 msg->l2h[1] = LAPDm_CTRL_I(dl->V_recv,
560                                                 dl->V_send - 1, 1); /* P=1 */
561                                 tx_ph_data_enqueue(dl, msg, dl->mctx.chan_nr,
562                                         dl->mctx.link_id, dl->mctx.n201);
563                         } else {
564                         /* OR send appropriate supervision frame with P=1 */
565                                 if (!dl->own_busy && !dl->seq_err_cond) {
566                                         lapdm_send_rr(&dl->mctx, 1);
567                                         /* NOTE: In case of sequence error
568                                          * condition, the REJ frame has been
569                                          * transmitted when entering the
570                                          * condition, so it has not be done
571                                          * here
572                                          */
573                                 } else if (dl->own_busy) {
574                                         lapdm_send_rnr(&dl->mctx, 1);
575                                 } else {
576                                         LOGP(DLAPDM, LOGL_INFO, "unhandled, "
577                                                 "pls. fix\n");
578                                 }
579                         }
580                         /* restart T200 (PH-READY-TO-SEND) */
581                         bsc_schedule_timer(&dl->t200, T200);
582                 } else {
583                         /* send MDL ERROR INIDCATION to L3 */
584                         rsl_rll_error(RLL_CAUSE_T200_EXPIRED, &dl->mctx);
585                 }
586                 break;
587         default:
588                 LOGP(DLAPDM, LOGL_INFO, "T200 expired in unexpected "
589                         "dl->state %u\n", dl->state);
590         }
591 }
592
593 /* 5.5.3.1: Common function to acknowlege frames up to the given N(R) value */
594 static void lapdm_acknowledge(struct lapdm_msg_ctx *mctx)
595 {
596         struct lapdm_datalink *dl = mctx->dl;
597         uint8_t nr = LAPDm_CTRL_Nr(mctx->ctrl);
598         int s = 0, rej = 0, t200_reset = 0;
599         int i;
600
601         /* supervisory frame ? */
602         if (LAPDm_CTRL_is_S(mctx->ctrl))
603                 s = 1;
604         /* REJ frame ? */
605         if (s && LAPDm_CTRL_S_BITS(mctx->ctrl) == LAPDm_S_REJ)
606                 rej = 1;
607
608         /* Flush all transmit buffers of acknowledged frames */
609         for (i = dl->V_ack; i != nr; i = inc_mod8(i)) {
610                 if (dl->tx_length[i]) {
611                         dl->tx_length[i] = 0;
612                         LOGP(DLAPDM, LOGL_INFO, "ack frame %d\n", i);
613                 }
614         }
615
616         if (dl->state != LAPDm_STATE_TIMER_RECOV) {
617                 /* When not in the timer recovery condition, the data
618                  * link layer entity shall reset the timer T200 on
619                  * receipt of a valid I frame with N(R) higher than V(A),
620                  * or an REJ with an N(R) equal to V(A). */
621                 if ((!rej && nr != dl->V_ack)
622                  || (rej && nr == dl->V_ack)) {
623                         LOGP(DLAPDM, LOGL_INFO, "reset t200\n");
624                         t200_reset = 1;
625                         bsc_del_timer(&dl->t200);
626                         /* 5.5.3.1 Note 1 + 2 imply timer recovery cond. */
627                 }
628                 /* 5.7.4: N(R) sequence error
629                  * N(R) is called valid, if and only if
630                  * (N(R)-V(A)) mod 8 <= (V(S)-V(A)) mod 8.
631                  */
632                 if (sub_mod8(nr, dl->V_ack) > sub_mod8(dl->V_send, dl->V_ack)) {
633                         LOGP(DLAPDM, LOGL_NOTICE, "N(R) sequence error\n");
634                         rsl_rll_error(RLL_CAUSE_SEQ_ERR, mctx);
635                 }
636         }
637
638         /* V(A) shall be set to the value of N(R) */
639         dl->V_ack = nr;
640
641         /* If T200 has been reset by the receipt of an I, RR or RNR frame,
642          * and if there are outstanding I frames, restart T200 */
643         if (t200_reset && !rej) {
644                 if (dl->tx_length[dl->V_send - 1]) {
645                         LOGP(DLAPDM, LOGL_INFO, "start T200, due to unacked I "
646                                 "frame(s)\n");
647                         bsc_schedule_timer(&dl->t200, T200);
648                 }
649         }
650 }
651
652 /* L1 -> L2 */
653
654 /* Receive a LAPDm U (Unnumbered) message from L1 */
655 static int lapdm_rx_u(struct msgb *msg, struct lapdm_msg_ctx *mctx)
656 {
657         struct lapdm_datalink *dl = mctx->dl;
658         uint8_t length;
659         int rc;
660         int rsl_msg;
661
662         switch (LAPDm_CTRL_U_BITS(mctx->ctrl)) {
663         case LAPDm_U_SABM:
664                 rsl_msg = RSL_MT_EST_IND;
665
666                 LOGP(DLAPDM, LOGL_INFO, "SABM received\n");
667                 /* 5.7.1 */
668                 dl->seq_err_cond = 0;
669                 /* G.2.2 Wrong value of the C/R bit */
670                 if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_RESP) {
671                         LOGP(DLAPDM, LOGL_NOTICE, "SABM response error\n");
672                         msgb_free(msg);
673                         rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
674                         return -EINVAL;
675                 }
676
677                 length = msg->l2h[2] >> 2;
678                 /* G.4.5 If SABM is received with L>N201 or with M bit
679                  * set, AN MDL-ERROR-INDICATION is sent to MM.
680                  */
681                 if ((msg->l2h[2] & LAPDm_MORE) || length + 3 > mctx->n201) {
682                         LOGP(DLAPDM, LOGL_NOTICE, "SABM too large error\n");
683                         msgb_free(msg);
684                         rsl_rll_error(RLL_CAUSE_UFRM_INC_PARAM, mctx);
685                         return -EIO;
686                 }
687
688                 /* Must be Format B */
689                 rc = check_length_ind(mctx, msg->l2h[2]);
690                 if (rc < 0) {
691                         msgb_free(msg);
692                         return rc;
693                 }
694                 switch (dl->state) {
695                 case LAPDm_STATE_IDLE:
696                         /* Set chan_nr and link_id for established connection */
697                         memset(&dl->mctx, 0, sizeof(dl->mctx));
698                         dl->mctx.dl = dl;
699                         dl->mctx.chan_nr = mctx->chan_nr;
700                         dl->mctx.link_id = mctx->link_id;
701                         break;
702                 case LAPDm_STATE_MF_EST:
703                         if (length == 0) {
704                                 rsl_msg = RSL_MT_EST_CONF;
705                                 break;
706                         }
707                         LOGP(DLAPDM, LOGL_INFO, "SABM command, multiple "
708                                 "frame established state\n");
709                         /* check for contention resoultion */
710                         if (dl->tx_hist[0][2] >> 2) {
711                                 LOGP(DLAPDM, LOGL_NOTICE, "SABM not allowed "
712                                         "during contention resolution\n");
713                                 rsl_rll_error(RLL_CAUSE_SABM_INFO_NOTALL, mctx);
714                         }
715                         msgb_free(msg);
716                         return 0;
717                 case LAPDm_STATE_DISC_SENT:
718                         /* 5.4.6.2 send DM with F=P */
719                         lapdm_send_dm(mctx);
720                         /* reset Timer T200 */
721                         bsc_del_timer(&dl->t200);
722                         msgb_free(msg);
723                         return send_rll_simple(RSL_MT_REL_CONF, mctx);
724                 default:
725                         lapdm_send_ua(mctx, length, msg->l2h + 3);
726                         msgb_free(msg);
727                         return 0;
728                 }
729                 /* send UA response */
730                 lapdm_send_ua(mctx, length, msg->l2h + 3);
731                 /* set Vs, Vr and Va to 0 */
732                 dl->V_send = dl->V_recv = dl->V_ack = 0;
733                 /* clear tx_hist */
734                 dl->tx_length[0] = 0;
735                 /* enter multiple-frame-established state */
736                 lapdm_dl_newstate(dl, LAPDm_STATE_MF_EST);
737                 /* send notification to L3 */
738                 if (length == 0) {
739                         /* 5.4.1.2 Normal establishment procedures */
740                         rc = send_rll_simple(rsl_msg, mctx);
741                         msgb_free(msg);
742                 } else {
743                         /* 5.4.1.4 Contention resolution establishment */
744                         msg->l3h = msg->l2h + 3;
745                         msgb_pull_l2h(msg);
746                         rc = send_rslms_rll_l3(rsl_msg, mctx, msg);
747                 }
748                 break;
749         case LAPDm_U_DM:
750                 LOGP(DLAPDM, LOGL_INFO, "DM received\n");
751                 /* G.2.2 Wrong value of the C/R bit */
752                 if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_CMD) {
753                         LOGP(DLAPDM, LOGL_NOTICE, "DM command error\n");
754                         msgb_free(msg);
755                         rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
756                         return -EINVAL;
757                 }
758                 if (!LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
759                         /* 5.4.1.2 DM responses with the F bit set to "0"
760                          * shall be ignored.
761                          */
762                         msgb_free(msg);
763                         return 0;
764                 }
765                 switch (dl->state) {
766                 case LAPDm_STATE_SABM_SENT:
767                         break;
768                 case LAPDm_STATE_MF_EST:
769                         if (LAPDm_CTRL_PF_BIT(mctx->ctrl) == 1) {
770                                 LOGP(DLAPDM, LOGL_INFO, "unsolicited DM "
771                                         "response\n");
772                                 rsl_rll_error(RLL_CAUSE_UNSOL_DM_RESP, mctx);
773                         } else {
774                                 LOGP(DLAPDM, LOGL_INFO, "unsolicited DM "
775                                         "response, multiple frame established "
776                                         "state\n");
777                                 rsl_rll_error(RLL_CAUSE_UNSOL_DM_RESP_MF, mctx);
778                         }
779                         msgb_free(msg);
780                         return 0;
781                 case LAPDm_STATE_TIMER_RECOV:
782                         /* DM is normal in case PF = 1 */
783                         if (LAPDm_CTRL_PF_BIT(mctx->ctrl) == 0) {
784                                 LOGP(DLAPDM, LOGL_INFO, "unsolicited DM "
785                                         "response, multiple frame established "
786                                         "state\n");
787                                 rsl_rll_error(RLL_CAUSE_UNSOL_DM_RESP_MF, mctx);
788                                 msgb_free(msg);
789                                 return 0;
790                         }
791                         break;
792                 case LAPDm_STATE_DISC_SENT:
793                         /* reset Timer T200 */
794                         bsc_del_timer(&dl->t200);
795                         /* go to idle state */
796                         lapdm_dl_newstate(dl, LAPDm_STATE_IDLE);
797                         rc = send_rll_simple(RSL_MT_REL_CONF, mctx);
798                         msgb_free(msg);
799                         return 0;
800                 case LAPDm_STATE_IDLE:
801                         /* 5.4.5 all other frame types shall be discarded */
802                 default:
803                         LOGP(DLAPDM, LOGL_INFO, "unsolicited DM response! "
804                                 "(discarding)\n");
805                         msgb_free(msg);
806                         return 0;
807                 }
808                 /* reset T200 */
809                 bsc_del_timer(&dl->t200);
810                 rc = send_rll_simple(RSL_MT_REL_IND, mctx);
811                 msgb_free(msg);
812                 break;
813         case LAPDm_U_UI:
814                 LOGP(DLAPDM, LOGL_INFO, "UI received\n");
815                 /* G.2.2 Wrong value of the C/R bit */
816                 if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_RESP) {
817                         LOGP(DLAPDM, LOGL_NOTICE, "UI indicates response "
818                                 "error\n");
819                         msgb_free(msg);
820                         rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
821                         return -EINVAL;
822                 }
823
824                 length = msg->l2h[2] >> 2;
825                 /* FIXME: G.4.5 If UI is received with L>N201 or with M bit
826                  * set, AN MDL-ERROR-INDICATION is sent to MM.
827                  */
828
829                 if (mctx->lapdm_fmt == LAPDm_FMT_B4) {
830                         length = N201_B4;
831                         msg->l3h = msg->l2h + 2;
832                 } else {
833                         rc = check_length_ind(mctx, msg->l2h[2]);
834                         if (rc < 0) {
835                                 msgb_free(msg);
836                                 return rc;
837                         }
838                         length = msg->l2h[2] >> 2;
839                         msg->l3h = msg->l2h + 3;
840                 }
841                 /* do some length checks */
842                 if (length == 0) {
843                         /* 5.3.3 UI frames received with the length indicator
844                          * set to "0" shall be ignored
845                          */
846                         LOGP(DLAPDM, LOGL_INFO, "length=0 (discarding)\n");
847                         msgb_free(msg);
848                         return 0;
849                 }
850                 switch (LAPDm_ADDR_SAPI(mctx->addr)) {
851                 case LAPDm_SAPI_NORMAL:
852                 case LAPDm_SAPI_SMS:
853                         break;
854                 default:
855                         /* 5.3.3 UI frames with invalid SAPI values shall be
856                          * discarded
857                          */
858                         LOGP(DLAPDM, LOGL_INFO, "sapi=%u (discarding)\n",
859                                 LAPDm_ADDR_SAPI(mctx->addr));
860                         msgb_free(msg);
861                         return 0;
862                 }
863                 msgb_pull_l2h(msg);
864                 rc = send_rslms_rll_l3(RSL_MT_UNIT_DATA_IND, mctx, msg);
865                 break;
866         case LAPDm_U_DISC:
867                 rsl_msg = RSL_MT_REL_IND;
868
869                 LOGP(DLAPDM, LOGL_INFO, "DISC received\n");
870                 /* flush buffers */
871                 lapdm_dl_flush_tx(dl);
872                 lapdm_dl_flush_send(dl);
873                 /* 5.7.1 */
874                 dl->seq_err_cond = 0;
875                 /* G.2.2 Wrong value of the C/R bit */
876                 if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_RESP) {
877                         LOGP(DLAPDM, LOGL_NOTICE, "DISC response error\n");
878                         msgb_free(msg);
879                         rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
880                         return -EINVAL;
881                 }
882                 length = msg->l2h[2] >> 2;
883                 if (length > 0 || msg->l2h[2] & 0x02) {
884                         /* G.4.4 If a DISC or DM frame is received with L>0 or
885                          * with the M bit set to "1", an MDL-ERROR-INDICATION
886                          * primitive with cause "U frame with incorrect
887                          * parameters" is sent to the mobile management entity. */
888                         LOGP(DLAPDM, LOGL_NOTICE,
889                                 "U frame iwth incorrect parameters ");
890                         msgb_free(msg);
891                         rsl_rll_error(RLL_CAUSE_UFRM_INC_PARAM, mctx);
892                         return -EIO;
893                 }
894                 msgb_free(msg);
895                 switch (dl->state) {
896                 case LAPDm_STATE_IDLE:
897                         LOGP(DLAPDM, LOGL_INFO, "DISC in idle state\n");
898                         /* send DM with F=P */
899                         return lapdm_send_dm(mctx);
900                 case LAPDm_STATE_SABM_SENT:
901                         LOGP(DLAPDM, LOGL_INFO, "DISC in SABM state\n");
902                         /* 5.4.6.2 send DM with F=P */
903                         lapdm_send_dm(mctx);
904                         /* reset Timer T200 */
905                         bsc_del_timer(&dl->t200);
906                         return send_rll_simple(RSL_MT_REL_IND, mctx);
907                 case LAPDm_STATE_MF_EST:
908                 case LAPDm_STATE_TIMER_RECOV:
909                         LOGP(DLAPDM, LOGL_INFO, "DISC in est state\n");
910                         break;
911                 case LAPDm_STATE_DISC_SENT:
912                         LOGP(DLAPDM, LOGL_INFO, "DISC in disc state\n");
913                         rsl_msg = RSL_MT_REL_CONF;
914                         break;
915                 default:
916                         lapdm_send_ua(mctx, length, msg->l2h + 3);
917                         return 0;
918                 }
919                 /* send UA response */
920                 lapdm_send_ua(mctx, length, msg->l2h + 3);
921                 /* reset Timer T200 */
922                 bsc_del_timer(&dl->t200);
923                 /* enter idle state */
924                 lapdm_dl_newstate(dl, LAPDm_STATE_IDLE);
925                 /* send notification to L3 */
926                 rc = send_rll_simple(rsl_msg, mctx);
927                 break;
928         case LAPDm_U_UA:
929                 LOGP(DLAPDM, LOGL_INFO, "UA received\n");
930                 /* G.2.2 Wrong value of the C/R bit */
931                 if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_CMD) {
932                         LOGP(DLAPDM, LOGL_NOTICE, "UA indicates command "
933                                 "error\n");
934                         msgb_free(msg);
935                         rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
936                         return -EINVAL;
937                 }
938
939                 length = msg->l2h[2] >> 2;
940                 /* G.4.5 If UA is received with L>N201 or with M bit
941                  * set, AN MDL-ERROR-INDICATION is sent to MM.
942                  */
943                 if ((msg->l2h[2] & LAPDm_MORE) || length + 3 > mctx->n201) {
944                         LOGP(DLAPDM, LOGL_NOTICE, "UA too large error\n");
945                         msgb_free(msg);
946                         rsl_rll_error(RLL_CAUSE_UFRM_INC_PARAM, mctx);
947                         return -EIO;
948                 }
949
950                 if (!LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
951                         /* 5.4.1.2 A UA response with the F bit set to "0"
952                          * shall be ignored.
953                          */
954                         LOGP(DLAPDM, LOGL_INFO, "F=0 (discarding)\n");
955                         msgb_free(msg);
956                         return 0;
957                 }
958                 switch (dl->state) {
959                 case LAPDm_STATE_SABM_SENT:
960                         break;
961                 case LAPDm_STATE_MF_EST:
962                 case LAPDm_STATE_TIMER_RECOV:
963                         LOGP(DLAPDM, LOGL_INFO, "unsolicited UA response! "
964                                 "(discarding)\n");
965                         rsl_rll_error(RLL_CAUSE_UNSOL_UA_RESP, mctx);
966                         msgb_free(msg);
967                         return 0;
968                 case LAPDm_STATE_DISC_SENT:
969                         LOGP(DLAPDM, LOGL_INFO, "UA in disconnect state\n");
970                         /* reset Timer T200 */
971                         bsc_del_timer(&dl->t200);
972                         /* go to idle state */
973                         lapdm_dl_newstate(dl, LAPDm_STATE_IDLE);
974                         rc = send_rll_simple(RSL_MT_REL_CONF, mctx);
975                         msgb_free(msg);
976                         return 0;
977                 case LAPDm_STATE_IDLE:
978                         /* 5.4.5 all other frame types shall be discarded */
979                 default:
980                         LOGP(DLAPDM, LOGL_INFO, "unsolicited UA response! "
981                                 "(discarding)\n");
982                         msgb_free(msg);
983                         return 0;
984                 }
985                 LOGP(DLAPDM, LOGL_INFO, "UA in SABM state\n");
986                 /* reset Timer T200 */
987                 bsc_del_timer(&dl->t200);
988                 /* compare UA with SABME if contention resolution is applied */
989                 if (dl->tx_hist[0][2] >> 2) {
990                         rc = check_length_ind(mctx, msg->l2h[2]);
991                         if (rc < 0) {
992                                 rc = send_rll_simple(RSL_MT_REL_IND, mctx);
993                                 msgb_free(msg);
994                                 /* go to idle state */
995                                 lapdm_dl_newstate(dl, LAPDm_STATE_IDLE);
996                                 return 0;
997                         }
998                         length = msg->l2h[2] >> 2;
999                         if (length != (dl->tx_hist[0][2] >> 2)
1000                          || !!memcmp(dl->tx_hist[0] + 3, msg->l2h + 3,
1001                                         length)) {
1002                                 LOGP(DLAPDM, LOGL_INFO, "UA response "
1003                                         "mismatches\n");
1004                                 rc = send_rll_simple(RSL_MT_REL_IND, mctx);
1005                                 msgb_free(msg);
1006                                 /* go to idle state */
1007                                 lapdm_dl_newstate(dl, LAPDm_STATE_IDLE);
1008                                 return 0;
1009                         }
1010                 }
1011                 /* set Vs, Vr and Va to 0 */
1012                 dl->V_send = dl->V_recv = dl->V_ack = 0;
1013                 /* clear tx_hist */
1014                 dl->tx_length[0] = 0;
1015                 /* enter multiple-frame-established state */
1016                 lapdm_dl_newstate(dl, LAPDm_STATE_MF_EST);
1017                 /* send outstanding frames, if any (resume / reconnect) */
1018                 rslms_send_i(mctx);
1019                 /* send notification to L3 */
1020                 rc = send_rll_simple(RSL_MT_EST_CONF, mctx);
1021                 msgb_free(msg);
1022                 break;
1023         default:
1024                 /* G.3.1 */
1025                 LOGP(DLAPDM, LOGL_NOTICE, "Unnumbered frame not allowed.\n");
1026                 msgb_free(msg);
1027                 rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
1028                 return -EINVAL;
1029         }
1030         return rc;
1031 }
1032
1033 /* Receive a LAPDm S (Supervisory) message from L1 */
1034 static int lapdm_rx_s(struct msgb *msg, struct lapdm_msg_ctx *mctx)
1035 {
1036         struct lapdm_datalink *dl = mctx->dl;
1037         uint8_t length;
1038
1039         length = msg->l2h[2] >> 2;
1040         if (length > 0 || msg->l2h[2] & 0x02) {
1041                 /* G.4.3 If a supervisory frame is received with L>0 or
1042                  * with the M bit set to "1", an MDL-ERROR-INDICATION
1043                  * primitive with cause "S frame with incorrect
1044                  * parameters" is sent to the mobile management entity. */
1045                 LOGP(DLAPDM, LOGL_NOTICE,
1046                                 "S frame with incorrect parameters\n");
1047                 msgb_free(msg);
1048                 rsl_rll_error(RLL_CAUSE_SFRM_INC_PARAM, mctx);
1049                 return -EIO;
1050         }
1051         /* 5.4.2.2: Inidcate error on supervisory reponse F=1 */
1052         if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_RESP
1053          && LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
1054                 LOGP(DLAPDM, LOGL_NOTICE, "S frame response with F=1 error\n");
1055                 rsl_rll_error(RLL_CAUSE_UNSOL_SPRV_RESP, mctx);
1056         }
1057
1058         switch (dl->state) {
1059         case LAPDm_STATE_IDLE:
1060                 /* if P=1, respond DM with F=1 (5.2.2) */
1061                 /* 5.4.5 all other frame types shall be discarded */
1062                 if (LAPDm_CTRL_PF_BIT(mctx->ctrl))
1063                         lapdm_send_dm(mctx); /* F=P */
1064                 /* fall though */
1065         case LAPDm_STATE_SABM_SENT:
1066         case LAPDm_STATE_DISC_SENT:
1067                 LOGP(DLAPDM, LOGL_NOTICE, "S frame ignored in this state\n");
1068                 msgb_free(msg);
1069                 return 0;
1070         }
1071         switch (LAPDm_CTRL_S_BITS(mctx->ctrl)) {
1072         case LAPDm_S_RR:
1073                 LOGP(DLAPDM, LOGL_INFO, "RR received\n");
1074                 /* 5.5.3.1: Acknowlege all tx frames up the the N(R)-1 */
1075                 lapdm_acknowledge(mctx);
1076
1077                 /* 5.5.3.2 */
1078                 if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_CMD
1079                  && LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
1080                         if (!dl->own_busy && !dl->seq_err_cond) {
1081                                 LOGP(DLAPDM, LOGL_NOTICE, "RR frame command with polling bit set and we are not busy, so we reply with RR frame\n");
1082                                 lapdm_send_rr(mctx, 1);
1083                                 /* NOTE: In case of sequence error condition,
1084                                  * the REJ frame has been transmitted when
1085                                  * entering the condition, so it has not be
1086                                  * done here
1087                                  */
1088                         } else if (dl->own_busy) {
1089                                 LOGP(DLAPDM, LOGL_NOTICE, "RR frame command with polling bit set and we are busy, so we reply with RR frame\n");
1090                                 lapdm_send_rnr(mctx, 1);
1091                         }
1092                 }
1093                 /* Send message, if possible due to acknowledged data */
1094                 rslms_send_i(mctx);
1095
1096                 break;
1097         case LAPDm_S_RNR:
1098                 LOGP(DLAPDM, LOGL_INFO, "RNR received\n");
1099                 /* 5.5.3.1: Acknowlege all tx frames up the the N(R)-1 */
1100                 lapdm_acknowledge(mctx);
1101
1102                 /* 5.5.5 */
1103                 /* Set peer receiver busy condition */
1104                 dl->peer_busy = 1;
1105
1106                 if (LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
1107                         if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_CMD) {
1108                                 if (!dl->own_busy) {
1109                                         LOGP(DLAPDM, LOGL_INFO, "RNR poll "
1110                                                 "command and we are not busy, "
1111                                                 "so we reply with RR final "
1112                                                 "response\n");
1113                                         /* Send RR with F=1 */
1114                                         lapdm_send_rr(mctx, 1);
1115                                 } else {
1116                                         LOGP(DLAPDM, LOGL_INFO, "RNR poll "
1117                                                 "command and we are busy, so "
1118                                                 "we reply with RNR final "
1119                                                 "response\n");
1120                                         /* Send RNR with F=1 */
1121                                         lapdm_send_rnr(mctx, 1);
1122                                 }
1123                         } else if (dl->state == LAPDm_STATE_TIMER_RECOV) {
1124                                 LOGP(DLAPDM, LOGL_INFO, "RNR poll response "
1125                                         "and we in timer recovery state, so "
1126                                         "we leave that state\n");
1127                                 /* Clear timer recovery condition */
1128                                 lapdm_dl_newstate(dl, LAPDm_STATE_MF_EST);
1129                                 /* V(S) to the N(R) in the RNR frame */
1130                                 dl->V_send = LAPDm_CTRL_Nr(mctx->ctrl);
1131                         }
1132                 } else
1133                         LOGP(DLAPDM, LOGL_INFO, "RNR not polling/final state "
1134                                 "received\n");
1135
1136                 /* Send message, if possible due to acknowledged data */
1137                 rslms_send_i(mctx);
1138
1139                 break;
1140         case LAPDm_S_REJ:
1141                 LOGP(DLAPDM, LOGL_INFO, "REJ received\n");
1142                 /* 5.5.3.1: Acknowlege all tx frames up the the N(R)-1 */
1143                 lapdm_acknowledge(mctx);
1144
1145                 /* 5.5.4.1 */
1146                 if (dl->state != LAPDm_STATE_TIMER_RECOV) {
1147                         /* Clear an existing peer receiver busy condition */
1148                         dl->peer_busy = 0;
1149                         /* V(S) and V(A) to the N(R) in the REJ frame */
1150                         dl->V_send = dl->V_ack = LAPDm_CTRL_Nr(mctx->ctrl);
1151                         /* reset Timer T200 */
1152                         bsc_del_timer(&dl->t200);
1153                         /* 5.5.3.2 */
1154                         if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_CMD
1155                          && LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
1156                                 if (!dl->own_busy && !dl->seq_err_cond) {
1157                                         LOGP(DLAPDM, LOGL_INFO, "REJ poll "
1158                                                 "command not in timer recovery "
1159                                                 "state and not in own busy "
1160                                                 "condition received, so we "
1161                                                 "respond with RR final "
1162                                                 "response\n");
1163                                         lapdm_send_rr(mctx, 1);
1164                                         /* NOTE: In case of sequence error
1165                                          * condition, the REJ frame has been
1166                                          * transmitted when entering the
1167                                          * condition, so it has not be done
1168                                          * here
1169                                          */
1170                                 } else if (dl->own_busy) {
1171                                         LOGP(DLAPDM, LOGL_INFO, "REJ poll "
1172                                                 "command not in timer recovery "
1173                                                 "state and in own busy "
1174                                                 "condition received, so we "
1175                                                 "respond with RNR final "
1176                                                 "response\n");
1177                                         lapdm_send_rnr(mctx, 1);
1178                                 }
1179                         } else
1180                                 LOGP(DLAPDM, LOGL_INFO, "REJ response or not "
1181                                         "polling command not in timer recovery "
1182                                         "state received\n");
1183                         /* send MDL ERROR INIDCATION to L3 */
1184                         if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_RESP
1185                          && LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
1186                                 rsl_rll_error(RLL_CAUSE_UNSOL_SPRV_RESP, mctx);
1187                         }
1188
1189                 } else if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_RESP
1190                         && LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
1191                         LOGP(DLAPDM, LOGL_INFO, "REJ poll response in timer "
1192                                 "recovery state received\n");
1193                         /* Clear an existing peer receiver busy condition */
1194                         dl->peer_busy = 0;
1195                         /* Clear timer recovery condition */
1196                         lapdm_dl_newstate(dl, LAPDm_STATE_MF_EST);
1197                         /* V(S) and V(A) to the N(R) in the REJ frame */
1198                         dl->V_send = dl->V_ack = LAPDm_CTRL_Nr(mctx->ctrl);
1199                         /* reset Timer T200 */
1200                         bsc_del_timer(&dl->t200);
1201                 } else {
1202                         /* Clear an existing peer receiver busy condition */
1203                         dl->peer_busy = 0;
1204                         /* V(S) and V(A) to the N(R) in the REJ frame */
1205                         dl->V_send = dl->V_ack = LAPDm_CTRL_Nr(mctx->ctrl);
1206                         /* 5.5.3.2 */
1207                         if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_CMD
1208                          && LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
1209                                 if (!dl->own_busy && !dl->seq_err_cond) {
1210                                         LOGP(DLAPDM, LOGL_INFO, "REJ poll "
1211                                                 "command in timer recovery "
1212                                                 "state and not in own busy "
1213                                                 "condition received, so we "
1214                                                 "respond with RR final "
1215                                                 "response\n");
1216                                         lapdm_send_rr(mctx, 1);
1217                                         /* NOTE: In case of sequence error
1218                                          * condition, the REJ frame has been
1219                                          * transmitted when entering the
1220                                          * condition, so it has not be done
1221                                          * here
1222                                          */
1223                                 } else if (dl->own_busy) {
1224                                         LOGP(DLAPDM, LOGL_INFO, "REJ poll "
1225                                                 "command in timer recovery "
1226                                                 "state and in own busy "
1227                                                 "condition received, so we "
1228                                                 "respond with RNR final "
1229                                                 "response\n");
1230                                         lapdm_send_rnr(mctx, 1);
1231                                 }
1232                         } else
1233                                 LOGP(DLAPDM, LOGL_INFO, "REJ response or not "
1234                                         "polling command in timer recovery "
1235                                         "state received\n");
1236                 }
1237
1238                 /* FIXME: 5.5.4.2 2) */
1239
1240                 /* Send message, if possible due to acknowledged data */
1241                 rslms_send_i(mctx);
1242
1243                 break;
1244         default:
1245                 /* G.3.1 */
1246                 LOGP(DLAPDM, LOGL_NOTICE, "Supervisory frame not allowed.\n");
1247                 msgb_free(msg);
1248                 rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
1249                 return -EINVAL;
1250         }
1251         msgb_free(msg);
1252         return 0;
1253 }
1254
1255 /* Receive a LAPDm I (Information) message from L1 */
1256 static int lapdm_rx_i(struct msgb *msg, struct lapdm_msg_ctx *mctx)
1257 {
1258         struct lapdm_datalink *dl = mctx->dl;
1259         //uint8_t nr = LAPDm_CTRL_Nr(mctx->ctrl);
1260         uint8_t ns = LAPDm_CTRL_I_Ns(mctx->ctrl);
1261         uint8_t length;
1262         int rc;
1263
1264         LOGP(DLAPDM, LOGL_NOTICE, "I received\n");
1265                 
1266         /* G.2.2 Wrong value of the C/R bit */
1267         if (LAPDm_ADDR_CR(mctx->addr) == CR_BS2MS_RESP) {
1268                 LOGP(DLAPDM, LOGL_NOTICE, "I frame response not allowed\n");
1269                 msgb_free(msg);
1270                 rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
1271                 return -EINVAL;
1272         }
1273
1274         length = msg->l2h[2] >> 2;
1275         if (length == 0 || length + 3 > mctx->n201) {
1276                 /* G.4.2 If the length indicator of an I frame is set
1277                  * to a numerical value L>N201 or L=0, an MDL-ERROR-INDICATION
1278                  * primitive with cause "I frame with incorrect length"
1279                  * is sent to the mobile management entity. */
1280                 LOGP(DLAPDM, LOGL_NOTICE, "I frame length not allowed\n");
1281                 msgb_free(msg);
1282                 rsl_rll_error(RLL_CAUSE_IFRM_INC_LEN, mctx);
1283                 return -EIO;
1284         }
1285
1286         /* G.4.2 If the numerical value of L is L<N201 and the M
1287          * bit is set to "1", then an MDL-ERROR-INDICATION primitive with
1288          * cause "I frame with incorrect use of M bit" is sent to the
1289          * mobile management entity. */
1290         if ((msg->l2h[2] & LAPDm_MORE) && length + 3 < mctx->n201) {
1291                 LOGP(DLAPDM, LOGL_NOTICE, "I frame with M bit too short\n");
1292                 msgb_free(msg);
1293                 rsl_rll_error(RLL_CAUSE_IFRM_INC_MBITS, mctx);
1294                 return -EIO;
1295         }
1296
1297         switch (dl->state) {
1298         case LAPDm_STATE_IDLE:
1299                 /* if P=1, respond DM with F=1 (5.2.2) */
1300                 /* 5.4.5 all other frame types shall be discarded */
1301                 if (LAPDm_CTRL_PF_BIT(mctx->ctrl))
1302                         lapdm_send_dm(mctx); /* F=P */
1303                 /* fall though */
1304         case LAPDm_STATE_SABM_SENT:
1305         case LAPDm_STATE_DISC_SENT:
1306                 LOGP(DLAPDM, LOGL_NOTICE, "I frame ignored in this state\n");
1307                 msgb_free(msg);
1308                 return 0;
1309         }
1310
1311         /* 5.7.1: N(s) sequence error */
1312         if (ns != dl->V_recv) {
1313                 LOGP(DLAPDM, LOGL_NOTICE, "N(S) sequence error: N(S)=%u, "
1314                      "V(R)=%u\n", ns, dl->V_recv);
1315                 /* discard data */
1316                 msgb_free(msg);
1317                 if (!dl->seq_err_cond) {
1318                         /* FIXME: help me understand what exactly todo here
1319                         dl->seq_err_cond = 1;
1320                         */
1321                         lapdm_send_rej(mctx, LAPDm_CTRL_PF_BIT(mctx->ctrl));
1322                 } else {
1323                 }
1324                 return -EIO;
1325         }
1326         dl->seq_err_cond = 0;
1327
1328         /* Increment receiver state */
1329         dl->V_recv = inc_mod8(dl->V_recv);
1330         LOGP(DLAPDM, LOGL_NOTICE, "incrementing V(R) to %u\n", dl->V_recv);
1331
1332         /* 5.5.3.1: Acknowlege all transmitted frames up the the N(R)-1 */
1333         lapdm_acknowledge(mctx); /* V(A) is also set here */
1334
1335         /* Only if we are not in own receiver busy condition */
1336         if (!dl->own_busy) {
1337                 /* if the frame carries a complete segment */
1338                 if (!(msg->l2h[2] & LAPDm_MORE)
1339                  && !dl->rcv_buffer) {
1340                         LOGP(DLAPDM, LOGL_INFO, "message in single I frame\n");
1341                         /* send a DATA INDICATION to L3 */
1342                         msg->l3h = msg->l2h + 3;
1343                         msgb_pull_l2h(msg);
1344                         rc = send_rslms_rll_l3(RSL_MT_DATA_IND, mctx, msg);
1345                 } else {
1346                         /* create rcv_buffer */
1347                         if (!dl->rcv_buffer) {
1348                                 LOGP(DLAPDM, LOGL_INFO, "message in multiple I "
1349                                         "frames (first message)\n");
1350                                 dl->rcv_buffer = msgb_alloc_headroom(200+10, 10,
1351                                                                 "LAPDm RX");
1352                                 dl->rcv_buffer->l3h = dl->rcv_buffer->data;
1353                         }
1354                         /* concat. rcv_buffer */
1355                         if (msgb_l3len(dl->rcv_buffer) + length > 200) {
1356                                 LOGP(DLAPDM, LOGL_NOTICE, "Received frame "
1357                                         "overflow!\n");
1358                         } else {
1359                                 memcpy(msgb_put(dl->rcv_buffer, length),
1360                                         msg->l2h + 3, length);
1361                         }
1362                         /* if the last segment was received */
1363                         if (!(msg->l2h[2] & LAPDm_MORE)) {
1364                                 LOGP(DLAPDM, LOGL_INFO, "message in multiple I "
1365                                         "frames (next message)\n");
1366                                 rc = send_rslms_rll_l3(RSL_MT_DATA_IND, mctx,
1367                                         dl->rcv_buffer);
1368                                 dl->rcv_buffer = NULL;
1369                         } else
1370                                 LOGP(DLAPDM, LOGL_INFO, "message in multiple I "
1371                                         "frames (last message)\n");
1372                         msgb_free(msg);
1373
1374                 }
1375         } else
1376                 LOGP(DLAPDM, LOGL_INFO, "I frame ignored during own receiver "
1377                         "busy condition\n");
1378
1379         /* Check for P bit */
1380         if (LAPDm_CTRL_PF_BIT(mctx->ctrl)) {
1381                 /* 5.5.2.1 */
1382                 /* check if we are not in own receiver busy */
1383                 if (!dl->own_busy) {
1384                         LOGP(DLAPDM, LOGL_INFO, "we are not busy, send RR\n");
1385                         /* Send RR with F=1 */
1386                         rc = lapdm_send_rr(mctx, 1);
1387                 } else {
1388                         LOGP(DLAPDM, LOGL_INFO, "we are busy, send RNR\n");
1389                         /* Send RNR with F=1 */
1390                         rc = lapdm_send_rnr(mctx, 1);
1391                 }
1392         } else {
1393                 /* 5.5.2.2 */
1394                 /* check if we are not in own receiver busy */
1395                 if (!dl->own_busy) {
1396                         /* NOTE: V(R) is already set above */
1397                         rc = rslms_send_i(mctx);
1398                         if (rc) {
1399                                 LOGP(DLAPDM, LOGL_INFO, "we are not busy and "
1400                                         "have no pending data, send RR\n");
1401                                 /* Send RR with F=0 */
1402                                 return lapdm_send_rr(mctx, 0);
1403                         }
1404                 } else {
1405                         LOGP(DLAPDM, LOGL_INFO, "we are busy, send RNR\n");
1406                         /* Send RNR with F=0 */
1407                         rc = lapdm_send_rnr(mctx, 0);
1408                 }
1409         }
1410
1411         /* Send message, if possible due to acknowledged data */
1412         rslms_send_i(mctx);
1413
1414         return rc;
1415 }
1416
1417 /* Receive a LAPDm message from L1 */
1418 static int lapdm_ph_data_ind(struct msgb *msg, struct lapdm_msg_ctx *mctx)
1419 {
1420         int rc;
1421
1422         /* G.2.3 EA bit set to "0" is not allowed in GSM */
1423         if (!LAPDm_ADDR_EA(mctx->addr)) {
1424                 LOGP(DLAPDM, LOGL_NOTICE, "EA bit 0 is not allowed in GSM\n");
1425                 msgb_free(msg);
1426                 rsl_rll_error(RLL_CAUSE_FRM_UNIMPL, mctx);
1427                 return -EINVAL;
1428         }
1429
1430         if (LAPDm_CTRL_is_U(mctx->ctrl))
1431                 rc = lapdm_rx_u(msg, mctx);
1432         else if (LAPDm_CTRL_is_S(mctx->ctrl))
1433                 rc = lapdm_rx_s(msg, mctx);
1434         else if (LAPDm_CTRL_is_I(mctx->ctrl))
1435                 rc = lapdm_rx_i(msg, mctx);
1436         else {
1437                 LOGP(DLAPDM, LOGL_NOTICE, "unknown LAPDm format\n");
1438                 msgb_free(msg);
1439                 rc = -EINVAL;
1440         }
1441         return rc;
1442 }
1443
1444 /* input into layer2 (from layer 1) */
1445 int l2_ph_data_ind(struct msgb *msg, struct lapdm_entity *le, struct l1ctl_info_dl *l1i)
1446 {
1447         uint8_t cbits = l1i->chan_nr >> 3;
1448         uint8_t sapi = l1i->link_id & 7;
1449         struct lapdm_msg_ctx mctx;
1450         int rc = 0;
1451
1452         /* when we reach here, we have a msgb with l2h pointing to the raw
1453          * 23byte mac block. The l1h has already been purged. */
1454
1455         mctx.dl = datalink_for_sapi(le, sapi);
1456         mctx.chan_nr = l1i->chan_nr;
1457         mctx.link_id = l1i->link_id;
1458         mctx.addr = mctx.ctrl = 0;
1459
1460         /* G.2.1 No action schall be taken on frames containing an unallocated
1461          * SAPI.
1462          */
1463         if (!mctx.dl) {
1464                 LOGP(DLAPDM, LOGL_NOTICE, "Received frame for unsupported "
1465                         "SAPI %d!\n", sapi);
1466                 return -EINVAL;
1467                 msgb_free(msg);
1468                 return -EIO;
1469         }
1470
1471         /* check for L1 chan_nr/link_id and determine LAPDm hdr format */
1472         if (cbits == 0x10 || cbits == 0x12) {
1473                 /* Format Bbis is used on BCCH and CCCH(PCH, NCH and AGCH) */
1474                 mctx.lapdm_fmt = LAPDm_FMT_Bbis;
1475                 mctx.n201 = N201_Bbis;
1476         } else {
1477                 if (mctx.link_id & 0x40) {
1478                         /* It was received from network on SACCH, thus
1479                          * lapdm_fmt must be B4 */
1480                         mctx.lapdm_fmt = LAPDm_FMT_B4;
1481                         mctx.n201 = N201_B4;
1482                         LOGP(DLAPDM, LOGL_INFO, "fmt=B4\n");
1483                         /* SACCH frames have a two-byte L1 header that
1484                          * OsmocomBB L1 doesn't strip */
1485                         msg->l2h += 2;
1486                 } else {
1487                         mctx.lapdm_fmt = LAPDm_FMT_B;
1488                         LOGP(DLAPDM, LOGL_INFO, "fmt=B\n");
1489                         mctx.n201 = 23; // FIXME: select correct size by chan.
1490                 }
1491         }
1492
1493         switch (mctx.lapdm_fmt) {
1494         case LAPDm_FMT_A:
1495         case LAPDm_FMT_B:
1496         case LAPDm_FMT_B4:
1497                 mctx.addr = msg->l2h[0];
1498                 if (!(mctx.addr & 0x01)) {
1499                         LOGP(DLAPDM, LOGL_ERROR, "we don't support "
1500                                 "multibyte addresses (discarding)\n");
1501                         msgb_free(msg);
1502                         return -EINVAL;
1503                 }
1504                 mctx.ctrl = msg->l2h[1];
1505                 /* obtain SAPI from address field */
1506                 mctx.link_id |= LAPDm_ADDR_SAPI(mctx.addr);
1507                 rc = lapdm_ph_data_ind(msg, &mctx);
1508                 break;
1509         case LAPDm_FMT_Bter:
1510                 /* FIXME */
1511                 msgb_free(msg);
1512                 break;
1513         case LAPDm_FMT_Bbis:
1514                 /* directly pass up to layer3 */
1515                 LOGP(DLAPDM, LOGL_INFO, "fmt=Bbis UI\n");
1516                 msg->l3h = msg->l2h;
1517                 msgb_pull_l2h(msg);
1518                 rc = send_rslms_rll_l3(RSL_MT_UNIT_DATA_IND, &mctx, msg);
1519                 break;
1520         default:
1521                 msgb_free(msg);
1522         }
1523
1524         return rc;
1525 }
1526
1527 /* L3 -> L2 / RSLMS -> LAPDm */
1528
1529 /* L3 requests establishment of data link */
1530 static int rslms_rx_rll_est_req(struct msgb *msg, struct lapdm_datalink *dl)
1531 {
1532         struct abis_rsl_rll_hdr *rllh = msgb_l2(msg);
1533         uint8_t chan_nr = rllh->chan_nr;
1534         uint8_t link_id = rllh->link_id;
1535         uint8_t sapi = rllh->link_id & 7;
1536         struct tlv_parsed tv;
1537         uint8_t length;
1538         uint8_t n201 = 23; //FIXME
1539
1540         /* Set chan_nr and link_id for established connection */
1541         memset(&dl->mctx, 0, sizeof(dl->mctx));
1542         dl->mctx.dl = dl;
1543         dl->mctx.n201 = n201;
1544         dl->mctx.chan_nr = chan_nr;
1545         dl->mctx.link_id = link_id;
1546
1547         rsl_tlv_parse(&tv, rllh->data, msgb_l2len(msg)-sizeof(*rllh));
1548         if (TLVP_PRESENT(&tv, RSL_IE_L3_INFO)) {
1549                 /* contention resolution establishment procedure */
1550                 if (sapi != 0) {
1551                         /* According to clause 6, the contention resolution
1552                          * procedure is only permitted with SAPI value 0 */
1553                         LOGP(DLAPDM, LOGL_ERROR, "SAPI != 0 but contention"
1554                                 "resolution (discarding)\n");
1555                         msgb_free(msg);
1556                         return send_rll_simple(RSL_MT_REL_IND, &dl->mctx);
1557                 }
1558                 /* transmit a SABM command with the P bit set to "1". The SABM
1559                  * command shall contain the layer 3 message unit */
1560                 length = TLVP_LEN(&tv, RSL_IE_L3_INFO);
1561                 LOGP(DLAPDM, LOGL_INFO, "perform establishment with content "
1562                         "(SAMB)\n");
1563         } else {
1564                 /* normal establishment procedure */
1565                 length = 0;
1566                 LOGP(DLAPDM, LOGL_INFO, "perform normal establishm. (SAMB)\n");
1567         }
1568
1569         /* check if the layer3 message length exceeds N201 */
1570         if (length + 3 > 21) { /* FIXME: do we know the channel N201? */
1571                 LOGP(DLAPDM, LOGL_ERROR, "frame too large: %d > N201(%d) "
1572                         "(discarding)\n", length + 3, 21);
1573                 msgb_free(msg);
1574                 return send_rll_simple(RSL_MT_REL_IND, &dl->mctx);
1575         }
1576
1577         /* Flush send-queue */
1578         /* Clear send-buffer */
1579         lapdm_dl_flush_send(dl);
1580
1581         /* Discard partly received L3 message */
1582         if (dl->rcv_buffer) {
1583                 msgb_free(dl->rcv_buffer);
1584                 dl->rcv_buffer = NULL;
1585         }
1586
1587         /* Remove RLL header from msgb */
1588         msgb_pull_l2h(msg);
1589
1590         /* Push LAPDm header on msgb */
1591         msg->l2h = msgb_push(msg, 3);
1592         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_CMD);
1593         msg->l2h[1] = LAPDm_CTRL_U(LAPDm_U_SABM, 1);
1594         msg->l2h[2] = LAPDm_LEN(length);
1595         /* Transmit-buffer carries exactly one segment */
1596         memcpy(dl->tx_hist[0], msg->l2h, 3 + length);
1597         dl->tx_length[0] = 3 + length;
1598         
1599         /* Set states */
1600         dl->own_busy = dl->peer_busy = 0;
1601         dl->retrans_ctr = 0;
1602         lapdm_dl_newstate(dl, LAPDm_STATE_SABM_SENT);
1603
1604         /* Tramsmit and start T200 */
1605         bsc_schedule_timer(&dl->t200, T200);
1606         return tx_ph_data_enqueue(dl, msg, chan_nr, link_id, n201);
1607 }
1608
1609 /* L3 requests transfer of unnumbered information */
1610 static int rslms_rx_rll_udata_req(struct msgb *msg, struct lapdm_datalink *dl)
1611 {
1612         struct abis_rsl_rll_hdr *rllh = msgb_l2(msg);
1613         uint8_t chan_nr = rllh->chan_nr;
1614         uint8_t link_id = rllh->link_id;
1615         uint8_t sapi = link_id & 7;
1616         struct tlv_parsed tv;
1617         int length;
1618         uint8_t n201 = 23; //FIXME
1619
1620         /* check if the layer3 message length exceeds N201 */
1621
1622         rsl_tlv_parse(&tv, rllh->data, msgb_l2len(msg)-sizeof(*rllh));
1623
1624         length = TLVP_LEN(&tv, RSL_IE_L3_INFO);
1625         /* check if the layer3 message length exceeds N201 */
1626         if (length + 3 > 18) { /* FIXME: do we know the channel N201? */
1627                 LOGP(DLAPDM, LOGL_ERROR, "frame too large: %d > N201(%d) "
1628                         "(discarding)\n", length + 3, 18);
1629                 msgb_free(msg);
1630                 return -EIO;
1631         }
1632
1633         LOGP(DLAPDM, LOGL_INFO, "sending unit data\n");
1634
1635         /* Remove RLL header from msgb */
1636         msgb_pull_l2h(msg);
1637
1638         /* Push LAPDm header on msgb */
1639         msg->l2h = msgb_push(msg, 3);
1640         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_CMD);
1641         msg->l2h[1] = LAPDm_CTRL_U(LAPDm_U_UI, 0);
1642         msg->l2h[2] = LAPDm_LEN(length);
1643         // FIXME: short L2 header support
1644
1645         /* Tramsmit */
1646         return tx_ph_data_enqueue(dl, msg, chan_nr, link_id, n201);
1647 }
1648
1649 /* L3 requests transfer of acknowledged information */
1650 static int rslms_rx_rll_data_req(struct msgb *msg, struct lapdm_datalink *dl)
1651 {
1652         struct abis_rsl_rll_hdr *rllh = msgb_l2(msg);
1653         struct tlv_parsed tv;
1654
1655         rsl_tlv_parse(&tv, rllh->data, msgb_l2len(msg)-sizeof(*rllh));
1656         if (!TLVP_PRESENT(&tv, RSL_IE_L3_INFO)) {
1657                 LOGP(DLAPDM, LOGL_ERROR, "data request without message error\n");
1658                 msgb_free(msg);
1659                 return -EINVAL;
1660         }
1661
1662         LOGP(DLAPDM, LOGL_INFO, "writing message to send-queue\n");
1663
1664         /* Remove the RSL/RLL header */
1665         msgb_pull_l2h(msg);
1666
1667         /* Write data into the send queue */
1668         msgb_enqueue(&dl->send_queue, msg);
1669
1670         /* Send message, if possible */
1671         rslms_send_i(&dl->mctx);
1672         return 0;
1673 }
1674
1675 /* Send next I frame from queued/buffered data */
1676 static int rslms_send_i(struct lapdm_msg_ctx *mctx)
1677 {
1678         struct lapdm_datalink *dl = mctx->dl;
1679         uint8_t chan_nr = mctx->chan_nr;
1680         uint8_t link_id = mctx->link_id;
1681         uint8_t sapi = link_id & 7;
1682         int k = k_sapi[sapi];
1683         struct msgb *msg;
1684         int length, left;
1685         int rc = -1; /* we sent nothing */
1686
1687         next_frame:
1688
1689         if (dl->peer_busy) {
1690                 LOGP(DLAPDM, LOGL_INFO, "peer busy, not sending\n");
1691                 return rc;
1692         }
1693
1694         if (dl->state == LAPDm_STATE_TIMER_RECOV) {
1695                 LOGP(DLAPDM, LOGL_INFO, "timer recovery, not sending\n");
1696                 return rc;
1697         }
1698
1699         /* If the send state variable V(S) is equal to V(A) plus k
1700          * (where k is the maximum number of outstanding I frames - see
1701          * subclause 5.8.4), the data link layer entity shall not transmit any
1702          * new I frames, but shall retransmit an I frame as a result
1703          * of the error recovery procedures as described in subclauses 5.5.4 and
1704          * 5.5.7. */
1705         if (dl->V_send == add_mod8(dl->V_ack, k)) {
1706                 LOGP(DLAPDM, LOGL_INFO, "k frames outstanding, not sending "
1707                         "more (k=%u V(S)=%u V(A)=%u)\n", k, dl->V_send,
1708                         dl->V_ack);
1709                 return rc;
1710         }
1711
1712         /* if we have no tx_hist yet, we create it */
1713         if (!dl->tx_length[dl->V_send]) {
1714                 /* Get next message into send-buffer, if any */
1715                 if (!dl->send_buffer) {
1716                         next_message:
1717                         dl->send_out = 0;
1718                         dl->send_buffer = msgb_dequeue(&dl->send_queue);
1719                         /* No more data to be sent */
1720                         if (!dl->send_buffer)
1721                                 return rc;
1722                         LOGP(DLAPDM, LOGL_INFO, "get message from "
1723                                 "send-queue\n");
1724                 }
1725
1726                 /* How much is left in the send-buffer? */
1727                 left = msgb_l3len(dl->send_buffer) - dl->send_out;
1728                 /* Segment, if data exceeds N201 */
1729                 length = left;
1730                 if (length > mctx->n201 - 3)
1731                         length = mctx->n201 - 3;
1732 printf("msg-len %d sent %d left %d N201 %d length %d first byte %02x\n", msgb_l3len(dl->send_buffer), dl->send_out, left, mctx->n201, length, dl->send_buffer->l3h[0]);
1733                 /* If message in send-buffer is completely sent */
1734                 if (left == 0) {
1735                         msgb_free(dl->send_buffer);
1736                         dl->send_buffer = NULL;
1737                         goto next_message;
1738                 }
1739
1740                 LOGP(DLAPDM, LOGL_INFO, "send I frame %sV(S)=%d\n",
1741                         (left > length) ? "segment " : "", dl->V_send);
1742
1743                 /* Create I frame (segment) and transmit-buffer content */
1744                 msg = msgb_alloc_headroom(23+10, 10, "LAPDm I");
1745                 msg->l2h = msgb_put(msg, 3 + length);
1746                 msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_CMD);
1747                 msg->l2h[1] = LAPDm_CTRL_I(dl->V_recv, dl->V_send, 0);
1748                 msg->l2h[2] = LAPDm_LEN(length);
1749                 if (left > length)
1750                         msg->l2h[2] |= LAPDm_MORE;
1751                 memcpy(msg->l2h + 3, dl->send_buffer->l3h + dl->send_out,
1752                         length);
1753                 memcpy(dl->tx_hist[dl->V_send], msg->l2h, 3 + length);
1754                 dl->tx_length[dl->V_send] = 3 + length;
1755                 /* Add length to track how much is already in the tx buffer */
1756                 dl->send_out += length;
1757         } else {
1758                 LOGP(DLAPDM, LOGL_INFO, "resend I frame from tx buffer "
1759                         "V(S)=%d\n", dl->V_send);
1760
1761                 /* Create I frame (segment) from tx_hist */
1762                 length = dl->tx_length[dl->V_send];
1763                 msg = msgb_alloc_headroom(23+10, 10, "LAPDm I");
1764                 msg->l2h = msgb_put(msg, length);
1765                 memcpy(msg->l2h, dl->tx_hist[dl->V_send], length);
1766                 msg->l2h[1] = LAPDm_CTRL_I(dl->V_recv, dl->V_send, 0);
1767         }
1768
1769         /* The value of the send state variable V(S) shall be incremented by 1
1770          * at the end of the transmission of the I frame */
1771         dl->V_send = inc_mod8(dl->V_send);
1772
1773         /* If timer T200 is not running at the time right before transmitting a
1774          * frame, when the PH-READY-TO-SEND primitive is received from the
1775          * physical layer., it shall be set. */
1776         if (!bsc_timer_pending(&dl->t200))
1777                 bsc_schedule_timer(&dl->t200, T200);
1778
1779         tx_ph_data_enqueue(dl, msg, chan_nr, link_id, mctx->n201);
1780
1781         rc = 0; /* we sent something */
1782         goto next_frame;
1783 }
1784
1785 /* L3 requests suspension of data link */
1786 static int rslms_rx_rll_susp_req(struct msgb *msg, struct lapdm_datalink *dl)
1787 {
1788         struct abis_rsl_rll_hdr *rllh = msgb_l2(msg);
1789         uint8_t sapi = rllh->link_id & 7;
1790
1791         if (sapi != 0) {
1792                 LOGP(DLAPDM, LOGL_ERROR, "SAPI != 0 while suspending\n");
1793                 msgb_free(msg);
1794                 return -EINVAL;
1795         }
1796
1797         LOGP(DLAPDM, LOGL_INFO, "perform suspension\n");
1798
1799         /* put back the send-buffer to the send-queue (first position) */
1800         if (dl->send_buffer) {
1801                 llist_add(&dl->send_buffer->list, &dl->send_queue);
1802                 dl->send_buffer = NULL;
1803         }
1804
1805         /* Clear transmit and send buffer, if any */
1806         lapdm_dl_flush_tx(dl);
1807         lapdm_dl_flush_send(dl);
1808
1809         msgb_free(msg);
1810
1811         return send_rll_simple(RSL_MT_SUSP_CONF, &dl->mctx);
1812 }
1813
1814 /* L3 requests resume of data link */
1815 static int rslms_rx_rll_res_req(struct msgb *msg, struct lapdm_datalink *dl)
1816 {
1817         struct abis_rsl_rll_hdr *rllh = msgb_l2(msg);
1818         uint8_t chan_nr = rllh->chan_nr;
1819         uint8_t link_id = rllh->link_id;
1820         uint8_t sapi = rllh->link_id & 7;
1821         struct tlv_parsed tv;
1822         uint8_t length;
1823         uint8_t n201 = 23; //FIXME
1824
1825         /* Set chan_nr and link_id for established connection */
1826         memset(&dl->mctx, 0, sizeof(dl->mctx));
1827         dl->mctx.dl = dl;
1828         dl->mctx.n201 = n201;
1829         dl->mctx.chan_nr = chan_nr;
1830         dl->mctx.link_id = link_id;
1831
1832         rsl_tlv_parse(&tv, rllh->data, msgb_l2len(msg)-sizeof(*rllh));
1833         if (!TLVP_PRESENT(&tv, RSL_IE_L3_INFO)) {
1834                 LOGP(DLAPDM, LOGL_ERROR, "resume without message error\n");
1835                 msgb_free(msg);
1836                 return send_rll_simple(RSL_MT_REL_IND, &dl->mctx);
1837         }
1838         length = TLVP_LEN(&tv, RSL_IE_L3_INFO);
1839
1840         LOGP(DLAPDM, LOGL_INFO, "perform re-establishment (SAMB)\n");
1841         
1842         /* Replace message in the send-buffer (reconnect) */
1843         if (dl->send_buffer)
1844                 msgb_free(dl->send_buffer);
1845         dl->send_buffer = msg;
1846
1847         /* Discard partly received L3 message */
1848         if (dl->rcv_buffer) {
1849                 msgb_free(dl->rcv_buffer);
1850                 dl->rcv_buffer = NULL;
1851         }
1852
1853         /* Create new msgb (old one is now free) */
1854         msg = msgb_alloc_headroom(23+10, 10, "LAPDm SABM");
1855         msg->l2h = msgb_put(msg, 3);
1856         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_CMD);
1857         msg->l2h[1] = LAPDm_CTRL_U(LAPDm_U_SABM, 1);
1858         msg->l2h[2] = LAPDm_LEN(0);
1859         /* Transmit-buffer carries exactly one segment */
1860         memcpy(dl->tx_hist[0], msg->l2h, 3);
1861         dl->tx_length[0] = 3;
1862
1863         /* Set states */
1864         dl->own_busy = dl->peer_busy = 0;
1865         dl->retrans_ctr = 0;
1866         lapdm_dl_newstate(dl, LAPDm_STATE_SABM_SENT);
1867
1868         /* Tramsmit and start T200 */
1869         bsc_schedule_timer(&dl->t200, T200);
1870         return tx_ph_data_enqueue(dl, msg, chan_nr, link_id, n201);
1871 }
1872
1873 /* L3 requests release of data link */
1874 static int rslms_rx_rll_rel_req(struct msgb *msg, struct lapdm_datalink *dl)
1875 {
1876         struct abis_rsl_rll_hdr *rllh = msgb_l2(msg);
1877         uint8_t chan_nr = rllh->chan_nr;
1878         uint8_t link_id = rllh->link_id;
1879         uint8_t sapi = rllh->link_id & 7;
1880         uint8_t mode = 0;
1881
1882         /* get release mode */
1883         if (rllh->data[0] == RSL_IE_RELEASE_MODE)
1884                 mode = rllh->data[1] & 1;
1885
1886         /* local release */
1887         if (mode) {
1888                 LOGP(DLAPDM, LOGL_INFO, "perform local release\n");
1889                 msgb_free(msg);
1890                 /* reset Timer T200 */
1891                 bsc_del_timer(&dl->t200);
1892                 /* enter idle state */
1893                 lapdm_dl_newstate(dl, LAPDm_STATE_IDLE);
1894                 /* send notification to L3 */
1895                 return send_rll_simple(RSL_MT_REL_CONF, &dl->mctx);
1896         } else
1897                 LOGP(DLAPDM, LOGL_INFO, "perform normal release (DISC)\n");
1898
1899         /* Create new msgb */
1900         msgb_pull_l2h(msg);
1901
1902         /* Push LAPDm header on msgb */
1903         msg->l2h = msgb_push(msg, 3);
1904         msg->l2h[0] = LAPDm_ADDR(LAPDm_LPD_NORMAL, sapi, CR_MS2BS_CMD);
1905         msg->l2h[1] = LAPDm_CTRL_U(LAPDm_U_DISC, 1);
1906         msg->l2h[2] = LAPDm_LEN(0);
1907         /* Transmit-buffer carries exactly one segment */
1908         memcpy(dl->tx_hist[0], msg->l2h, 3);
1909         dl->tx_length[0] = 3;
1910         
1911         /* Set states */
1912         dl->own_busy = dl->peer_busy = 0;
1913         dl->retrans_ctr = 0;
1914         lapdm_dl_newstate(dl, LAPDm_STATE_DISC_SENT);
1915
1916         /* Tramsmit and start T200 */
1917         bsc_schedule_timer(&dl->t200, T200);
1918         return tx_ph_data_enqueue(dl, msg, chan_nr, link_id, dl->mctx.n201);
1919 }
1920
1921 /* L3 requests release in idle state */
1922 static int rslms_rx_rll_rel_req_idle(struct msgb *msg, struct lapdm_datalink *dl)
1923 {
1924         msgb_free(msg);
1925
1926         /* send notification to L3 */
1927         return send_rll_simple(RSL_MT_REL_CONF, &dl->mctx);
1928 }
1929
1930 /* Names for Radio Link Layer Management */
1931 static const struct value_string rsl_msg_names[] = {
1932         { RSL_MT_DATA_REQ,              "RSL_MT_DATA_REQ" },
1933         { RSL_MT_DATA_IND,              "RSL_MT_DATA_IND" },
1934         { RSL_MT_ERROR_IND,             "RSL_MT_ERROR_IND" },
1935         { RSL_MT_EST_REQ,               "RSL_MT_EST_REQ" },
1936         { RSL_MT_EST_CONF,              "RSL_MT_EST_CONF" },
1937         { RSL_MT_EST_IND,               "RSL_MT_EST_IND" },
1938         { RSL_MT_EST_IND,               "RSL_MT_REL_REQ" },
1939         { RSL_MT_REL_REQ,               "RSL_MT_REL_REQ" },
1940         { RSL_MT_REL_CONF,              "RSL_MT_REL_CONF" },
1941         { RSL_MT_REL_IND,               "RSL_MT_REL_IND" },
1942         { RSL_MT_UNIT_DATA_REQ,         "RSL_MT_UNIT_DATA_REQ" },
1943         { RSL_MT_UNIT_DATA_IND,         "RSL_MT_UNIT_DATA_IND" },
1944         { RSL_MT_SUSP_REQ,              "RSL_MT_SUSP_REQ" },
1945         { RSL_MT_SUSP_CONF,             "RSL_MT_SUSP_CONF" },
1946         { RSL_MT_RES_REQ,               "RSL_MT_RES_REQ" },
1947         { RSL_MT_RECON_REQ,             "RSL_MT_RECON_REQ" },
1948         { 0,                            NULL }
1949 };
1950
1951 const char *get_rsl_name(int value)
1952 {
1953         return get_value_string(rsl_msg_names, value);
1954 }
1955
1956 const char *lapdm_state_names[] = {
1957         "LAPDm_STATE_NULL",
1958         "LAPDm_STATE_IDLE",
1959         "LAPDm_STATE_SABM_SENT",
1960         "LAPDm_STATE_MF_EST",
1961         "LAPDm_STATE_TIMER_RECOV",
1962         "LAPDm_STATE_OWN_RCVR_BUSY"
1963 };
1964
1965 /* statefull handling for RSLms RLL messages from L3 */
1966 static struct l2downstate {
1967         uint32_t        states;
1968         int             type;
1969         int             (*rout) (struct msgb *msg, struct lapdm_datalink *dl);
1970 } l2downstatelist[] = {
1971         /* create and send UI command */
1972         {ALL_STATES,
1973          RSL_MT_UNIT_DATA_REQ, rslms_rx_rll_udata_req},
1974
1975         /* create and send SABM command */
1976         {SBIT(LAPDm_STATE_IDLE),
1977          RSL_MT_EST_REQ, rslms_rx_rll_est_req},
1978
1979         /* create and send I command */
1980         {SBIT(LAPDm_STATE_MF_EST) |
1981          SBIT(LAPDm_STATE_TIMER_RECOV),
1982          RSL_MT_DATA_REQ, rslms_rx_rll_data_req},
1983
1984         /* suspend datalink */
1985         {SBIT(LAPDm_STATE_MF_EST) |
1986          SBIT(LAPDm_STATE_TIMER_RECOV),
1987          RSL_MT_SUSP_REQ, rslms_rx_rll_susp_req},
1988
1989         /* create and send SABM command (resume) */
1990         {SBIT(LAPDm_STATE_MF_EST) |
1991          SBIT(LAPDm_STATE_TIMER_RECOV),
1992          RSL_MT_RES_REQ, rslms_rx_rll_res_req},
1993
1994         /* create and send SABM command (reconnect) */
1995         {SBIT(LAPDm_STATE_MF_EST) |
1996          SBIT(LAPDm_STATE_TIMER_RECOV),
1997          RSL_MT_RECON_REQ, rslms_rx_rll_res_req},
1998
1999         /* create and send DISC command */
2000         {SBIT(LAPDm_STATE_SABM_SENT) |
2001          SBIT(LAPDm_STATE_MF_EST) |
2002          SBIT(LAPDm_STATE_TIMER_RECOV),
2003          RSL_MT_REL_REQ, rslms_rx_rll_rel_req},
2004
2005         /* release in idle state */
2006         {SBIT(LAPDm_STATE_IDLE),
2007          RSL_MT_REL_REQ, rslms_rx_rll_rel_req_idle},
2008
2009         /* FIXME: create and send DISC command */
2010 };
2011
2012 #define L2DOWNSLLEN \
2013         (sizeof(l2downstatelist) / sizeof(struct l2downstate))
2014
2015 /* incoming RSLms RLL message from L3 */
2016 static int rslms_rx_rll(struct msgb *msg, struct osmocom_ms *ms)
2017 {
2018         struct abis_rsl_rll_hdr *rllh = msgb_l2(msg);
2019         int msg_type = rllh->c.msg_type;
2020         uint8_t sapi = rllh->link_id & 7;
2021         struct lapdm_entity *le;
2022         struct lapdm_datalink *dl;
2023         int i, supported = 0;
2024         int rc = 0;
2025
2026         if (rllh->link_id & 0x40)
2027                 le = &ms->l2_entity.lapdm_acch;
2028         else
2029                 le = &ms->l2_entity.lapdm_dcch;
2030
2031         /* G.2.1 No action schall be taken on frames containing an unallocated
2032          * SAPI.
2033          */
2034         dl = datalink_for_sapi(le, sapi);
2035         if (!dl) {
2036                 LOGP(DRSL, LOGL_ERROR, "No instance for SAPI %d!\n", sapi);
2037                 return -EINVAL;
2038         }
2039
2040         LOGP(DRSL, LOGL_INFO, "(ms %s) RLL Message '%s' received in state %s\n",
2041                 ms->name, get_rsl_name(msg_type), lapdm_state_names[dl->state]);
2042
2043         /* find function for current state and message */
2044         for (i = 0; i < L2DOWNSLLEN; i++) {
2045                 if (msg_type == l2downstatelist[i].type)
2046                         supported = 1;
2047                 if ((msg_type == l2downstatelist[i].type)
2048                  && ((1 << dl->state) & l2downstatelist[i].states))
2049                         break;
2050         }
2051         if (!supported) {
2052                 LOGP(DRSL, LOGL_NOTICE, "Message unsupported.\n");
2053                 msgb_free(msg);
2054                 return 0;
2055         }
2056         if (i == L2DOWNSLLEN) {
2057                 LOGP(DRSL, LOGL_NOTICE, "Message unhandled at this state.\n");
2058                 msgb_free(msg);
2059                 return 0;
2060         }
2061
2062         rc = l2downstatelist[i].rout(msg, dl);
2063
2064         return rc;
2065 }
2066
2067 /* input into layer2 (from layer 3) */
2068 int rslms_recvmsg(struct msgb *msg, struct osmocom_ms *ms)
2069 {
2070         struct abis_rsl_common_hdr *rslh = msgb_l2(msg);
2071         int rc = 0;
2072
2073         switch (rslh->msg_discr & 0xfe) {
2074         case ABIS_RSL_MDISC_RLL:
2075                 rc = rslms_rx_rll(msg, ms);
2076                 break;
2077         default:
2078                 LOGP(DRSL, LOGL_ERROR, "unknown RSLms message "
2079                         "discriminator 0x%02x", rslh->msg_discr);
2080                 msgb_free(msg);
2081                 return -EINVAL;
2082         }
2083
2084         return rc;
2085 }
2086
2087 /* input function that L2 calls when sending messages up to L3 */
2088 int rslms_sendmsg(struct msgb *msg, struct osmocom_ms *ms)
2089 {
2090         if (!ms->l2_entity.msg_handler) {
2091                 msgb_free(msg);
2092                 return -EIO;
2093         }
2094
2095         /* call the layer2 message handler that is registered */
2096         return ms->l2_entity.msg_handler(msg, ms);
2097 }
2098
2099 /* register message handler for messages that are sent from L2->L3 */
2100 int osmol2_register_handler(struct osmocom_ms *ms, osmol2_cb_t cb)
2101 {
2102         ms->l2_entity.msg_handler = cb;
2103
2104         return 0;
2105 }