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