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