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