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