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