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