target/fw/layer1: correctly initialize afc_retries
[osmocom-bb.git] / src / target / firmware / layer1 / prim_fbsb.c
1 /* Layer 1 - FCCH and SCH burst handling */
2
3 /* (C) 2010 by Harald Welte <laforge@gnumonks.org>
4  *
5  * All Rights Reserved
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  */
22
23 #include <stdint.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <errno.h>
28
29 #include <defines.h>
30 #include <debug.h>
31 #include <memory.h>
32 #include <byteorder.h>
33 #include <osmocore/gsm_utils.h>
34 #include <osmocore/msgb.h>
35 #include <calypso/dsp_api.h>
36 #include <calypso/irq.h>
37 #include <calypso/tpu.h>
38 #include <calypso/tsp.h>
39 #include <calypso/dsp.h>
40 #include <calypso/timer.h>
41 #include <comm/sercomm.h>
42
43 #include <layer1/sync.h>
44 #include <layer1/afc.h>
45 #include <layer1/tdma_sched.h>
46 #include <layer1/mframe_sched.h>
47 #include <layer1/tpu_window.h>
48 #include <layer1/l23_api.h>
49
50 #include <l1ctl_proto.h>
51
52 #define FB0_RETRY_COUNT         3
53 #define AFC_RETRY_COUNT         30
54
55 extern uint16_t rf_arfcn; // TODO
56
57 struct mon_state {
58         uint32_t fnr_report;    /* frame number when DSP reported it */
59         int attempt;            /* which attempt was this ? */
60
61         int16_t toa;
62         uint16_t pm;
63         uint16_t angle;
64         uint16_t snr;
65
66         /* computed values */
67         int16_t freq_diff;
68
69         /* Sync Burst (SB) */
70         uint8_t bsic;
71         struct gsm_time time;
72 };
73
74 struct l1a_fb_state {
75         struct mon_state mon;
76         struct l1ctl_fbsb_req req;
77         int16_t initial_freq_err;
78         uint8_t fb_retries;
79         uint8_t afc_retries;
80 };
81
82 static struct l1a_fb_state fbs;
83 static struct mon_state *last_fb = &fbs.mon;
84
85 static void dump_mon_state(struct mon_state *fb)
86 {
87 #if 0
88         printf("(%u:%u): TOA=%5u, Power=%4ddBm, Angle=%5dHz, "
89                 "SNR=%04x(%d.%u) OFFSET=%u SYNCHRO=%u\n",
90                 fb->fnr_report, fb->attempt, fb->toa,
91                 agc_inp_dbm8_by_pm(fb->pm)/8, ANGLE_TO_FREQ(fb->angle),
92                 fb->snr, l1s_snr_int(fb->snr), l1s_snr_fract(fb->snr),
93                 tpu_get_offset(), tpu_get_synchro());
94 #else
95         printf("(%u:%u): TOA=%5u, Power=%4ddBm, Angle=%5dHz\n",
96                 fb->fnr_report, fb->attempt, fb->toa,
97                 agc_inp_dbm8_by_pm(fb->pm)/8, ANGLE_TO_FREQ(fb->angle));
98 #endif
99 }
100
101 static int l1ctl_fbsb_resp(uint8_t res)
102 {
103         struct msgb *msg;
104         struct l1ctl_fbsb_conf *resp;
105
106         msg = l1_create_l2_msg(L1CTL_FBSB_CONF, fbs.mon.time.fn,
107                                 l1s_snr_int(fbs.mon.snr),
108                                 fbs.req.band_arfcn);
109         if (!msg)
110                 return -ENOMEM;
111
112         resp = (struct l1ctl_fbsb_conf *) msgb_put(msg, sizeof(*resp));
113         resp->initial_freq_err = htons(fbs.initial_freq_err);
114         resp->result = res;
115         resp->bsic = fbs.mon.bsic;
116
117         /* no need to set BSIC, as it is never used here */
118         l1_queue_for_l2(msg);
119
120         return 0;
121 }
122
123 /* SCH Burst Detection ********************************************************/
124
125 /* determine the GSM time and BSIC from a Sync Burst */
126 static uint8_t l1s_decode_sb(struct gsm_time *time, uint32_t sb)
127 {
128         uint8_t bsic = (sb >> 2) & 0x3f;
129         uint8_t t3p;
130
131         memset(time, 0, sizeof(*time));
132
133         /* TS 05.02 Chapter 3.3.2.2.1 SCH Frame Numbers */
134         time->t1 = ((sb >> 23) & 1) | ((sb >> 7) & 0x1fe) | ((sb << 9) & 0x600);
135         time->t2 = (sb >> 18) & 0x1f;
136         t3p = ((sb >> 24) & 1) | ((sb >> 15) & 6);
137         time->t3 = t3p*10 + 1;
138
139         /* TS 05.02 Chapter 4.3.3 TDMA frame number */
140         time->fn = gsm_gsmtime2fn(time);
141
142         time->tc = (time->fn / 51) % 8;
143
144         return bsic;
145 }
146
147 static void read_sb_result(struct mon_state *st, int attempt)
148 {
149         st->toa = dsp_api.db_r->a_serv_demod[D_TOA];
150         st->pm = dsp_api.db_r->a_serv_demod[D_PM]>>3;
151         st->angle = dsp_api.db_r->a_serv_demod[D_ANGLE];
152         st->snr = dsp_api.db_r->a_serv_demod[D_SNR];
153
154         st->freq_diff = ANGLE_TO_FREQ(st->angle);
155         st->fnr_report = l1s.current_time.fn;
156         st->attempt = attempt;
157
158         dump_mon_state(st);
159
160         if (st->snr > AFC_SNR_THRESHOLD)
161                 afc_input(st->freq_diff, rf_arfcn, 1);
162         else
163                 afc_input(st->freq_diff, rf_arfcn, 0);
164
165         dsp_api.r_page_used = 1;
166 }
167
168 /* Note: When we get the SB response, it is 2 TDMA frames after the SB
169  * actually happened, as it is a "C W W R" task */
170 #define SB2_LATENCY     2
171
172 static int l1s_sbdet_resp(__unused uint8_t p1, uint8_t attempt,
173                           __unused uint16_t p3)
174 {
175         uint32_t sb;
176         int qbits, fn_offset;
177         struct l1_cell_info *cinfo = &l1s.serving_cell;
178         int fnr_delta, bits_delta;
179         struct l1ctl_sync_new_ccch_resp *l1;
180         struct msgb *msg;
181
182         putchart('s');
183
184         if (dsp_api.db_r->a_sch[0] & (1<<B_SCH_CRC)) {
185                 /* mark READ page as being used */
186                 dsp_api.r_page_used = 1;
187
188                 /* after 2nd attempt, we failed */
189                 if (attempt == 2) {
190                         last_fb->attempt = 13;
191                         l1s_compl_sched(L1_COMPL_FB);
192                 }
193
194                 /* after 1st attempt, we simply wait for 2nd */
195                 return 0;
196         }
197
198         printf("SB%d ", attempt);
199         read_sb_result(last_fb, attempt);
200
201         sb = dsp_api.db_r->a_sch[3] | dsp_api.db_r->a_sch[4] << 16;
202         fbs.mon.bsic = l1s_decode_sb(&fbs.mon.time, sb);
203         printf("=> SB 0x%08x: BSIC=%u ", sb, fbs.mon.bsic);
204         l1s_time_dump(&fbs.mon.time);
205
206         l1s.serving_cell.bsic = fbs.mon.bsic;
207
208         /* calculate synchronisation value (TODO: only complete for qbits) */
209         last_fb->toa -= 23;
210         qbits = last_fb->toa * 4;
211         fn_offset = l1s.current_time.fn; // TODO
212
213         if (qbits > QBITS_PER_TDMA) {
214                 qbits -= QBITS_PER_TDMA;
215                 fn_offset -= 1;
216         } else if (qbits < 0)  {
217                 qbits += QBITS_PER_TDMA;
218                 fn_offset += 1;
219         }
220
221         fnr_delta = last_fb->fnr_report - attempt;
222         bits_delta = fnr_delta * BITS_PER_TDMA;
223
224         cinfo->fn_offset = fnr_delta;
225         cinfo->time_alignment = qbits;
226         cinfo->arfcn = rf_arfcn;
227
228         if (last_fb->toa > bits_delta)
229                 printf("=> DSP reports SB in bit that is %d bits in the "
230                         "future?!?\n", last_fb->toa - bits_delta);
231         else
232                 printf(" qbits=%u\n", qbits);
233
234         synchronize_tdma(&l1s.serving_cell);
235
236         /* if we have recived a SYNC burst, update our local GSM time */
237         gsm_fn2gsmtime(&l1s.current_time, fbs.mon.time.fn + SB2_LATENCY);
238         /* compute next time from new current time */
239         l1s.next_time = l1s.current_time;
240         l1s_time_inc(&l1s.next_time, 1);
241
242         /* If we call tdma_sched_reset(), which is only needed if there
243          * are further l1s_sbdet_resp() scheduled, we will bring
244          * dsp_api.db_r and dsp_api.db_w out of sync because we changed
245          * dsp_api.db_w for l1s_sbdet_cmd() and canceled
246          * l1s_sbdet_resp() which would change dsp_api.db_r. The DSP
247          * however expects dsp_api.db_w and dsp_api.db_r to be in sync
248          * (either "0 - 0" or "1 - 1"). So we have to bring dsp_api.db_w
249          * and dsp_api.db_r into sync again, otherwise NB reading will
250          * complain. We probably don't need the Abort command and could
251          * just bring dsp_api.db_w and dsp_api.db_r into sync.  */
252         if (attempt != 2) {
253                 tdma_sched_reset();
254                 l1s_dsp_abort();
255         }
256
257         l1s_reset_hw();
258         /* enable the MF Task for BCCH reading */
259         mframe_enable(MF_TASK_BCCH_NORM);
260         if (l1s.serving_cell.ccch_mode == CCCH_MODE_COMBINED)
261                 mframe_enable(MF_TASK_CCCH_COMB);
262         else if (l1s.serving_cell.ccch_mode == CCCH_MODE_NON_COMBINED)
263                 mframe_enable(MF_TASK_CCCH);
264
265         l1s_compl_sched(L1_COMPL_FB);
266
267         return 0;
268 }
269
270 static int l1s_sbdet_cmd(__unused uint8_t p1, __unused uint8_t p2,
271                          __unused uint16_t p3)
272 {
273         putchart('S');
274
275         fbs.mon.bsic = 0;
276         fbs.mon.time.fn = 0;
277
278         dsp_api.db_w->d_task_md = SB_DSP_TASK;
279         dsp_api.ndb->d_fb_mode = 0; /* wideband search */
280
281         /* Program TPU */
282         l1s_rx_win_ctrl(rf_arfcn, L1_RXWIN_SB, 0);
283
284         return 0;
285 }
286
287 /* This is how it is done by the TSM30 */
288 static const struct tdma_sched_item sb_sched_set[] = {
289         SCHED_ITEM_DT(l1s_sbdet_cmd, 0, 0, 1),  SCHED_END_FRAME(),
290         SCHED_ITEM_DT(l1s_sbdet_cmd, 0, 0, 2),  SCHED_END_FRAME(),
291                                                 SCHED_END_FRAME(),
292         SCHED_ITEM(l1s_sbdet_resp, -4, 0, 1),   SCHED_END_FRAME(),
293         SCHED_ITEM(l1s_sbdet_resp, -4, 0, 2),   SCHED_END_FRAME(),
294         SCHED_END_SET()
295 };
296
297 void l1s_sb_test(uint8_t base_fn)
298 {
299         tdma_schedule_set(base_fn, sb_sched_set, 0);
300 }
301 /* FCCH Burst *****************************************************************/
302
303 static int read_fb_result(struct mon_state *st, int attempt)
304 {
305         st->toa = dsp_api.ndb->a_sync_demod[D_TOA];
306         st->pm = dsp_api.ndb->a_sync_demod[D_PM]>>3;
307         st->angle = dsp_api.ndb->a_sync_demod[D_ANGLE];
308         st->snr = dsp_api.ndb->a_sync_demod[D_SNR];
309
310         //last_fb->angle = clip_int16(last_fb->angle, AFC_MAX_ANGLE);
311         st->freq_diff = ANGLE_TO_FREQ(last_fb->angle);
312         st->fnr_report = l1s.current_time.fn;
313         st->attempt = attempt;
314
315         dump_mon_state(st);
316
317         dsp_api.ndb->d_fb_det = 0;
318         dsp_api.ndb->a_sync_demod[D_TOA] = 0; /* TSM30 does it (really needed ?) */
319
320         /* Update AFC with current frequency offset */
321         afc_correct(st->freq_diff, rf_arfcn);
322
323         //tpu_dsp_frameirq_enable();
324         return 1;
325 }
326
327 static void fbinfo2cellinfo(struct l1_cell_info *cinfo,
328                             const struct mon_state *mon)
329 {
330         int ntdma, qbits, fn_offset, fnr_delta, bits_delta;
331
332         /* FIXME: where did this magic 23 come from? */
333         last_fb->toa -= 23;
334
335         if (last_fb->toa < 0) {
336                 qbits = (last_fb->toa + BITS_PER_TDMA) * 4;
337                 ntdma = -1;
338         } else {
339                 ntdma = (last_fb->toa) / BITS_PER_TDMA;
340                 qbits = (last_fb->toa - ntdma * BITS_PER_TDMA) * 4;
341         }
342
343         fn_offset = l1s.current_time.fn - last_fb->attempt + ntdma;
344         fnr_delta = last_fb->fnr_report - last_fb->attempt;
345         bits_delta = fnr_delta * BITS_PER_TDMA;
346
347         cinfo->fn_offset = fnr_delta;
348         cinfo->time_alignment = qbits;
349         cinfo->arfcn = rf_arfcn;
350
351         if (last_fb->toa > bits_delta)
352                 printf("=> DSP reports FB in bit that is %d bits in "
353                         "the future?!?\n", last_fb->toa - bits_delta);
354         else {
355                 int fb_fnr = (last_fb->fnr_report - last_fb->attempt)
356                                 + last_fb->toa/BITS_PER_TDMA;
357                 printf("=>FB @ FNR %u fn_offset=%d qbits=%u\n",
358                         fb_fnr, fn_offset, qbits);
359         }
360 }
361
362 /* scheduler callback to issue a FB detection task to the DSP */
363 static int l1s_fbdet_cmd(__unused uint8_t p1, __unused uint8_t p2,
364                          uint16_t fb_mode)
365 {
366         if (fb_mode == 0) {
367                 putchart('F');
368         } else {
369                 putchart('V');
370         }
371
372         l1s.fb.mode = fb_mode;
373
374         /* Tell the RF frontend to set the gain appropriately */
375         rffe_set_gain(-85, CAL_DSP_TGT_BB_LVL);
376
377         /* Program DSP */
378         dsp_api.db_w->d_task_md = FB_DSP_TASK;  /* maybe with I/Q swap? */
379         dsp_api.ndb->d_fb_mode = fb_mode;
380
381         /* Program TPU */
382         l1s_rx_win_ctrl(fbs.req.band_arfcn, L1_RXWIN_FB, 0);
383
384         return 0;
385 }
386
387 #if 0
388 #define FB0_SNR_THRESH  2000
389 #define FB1_SNR_THRESH  3000
390 #else
391 #define FB0_SNR_THRESH  0
392 #define FB1_SNR_THRESH  0
393 #endif
394
395 static const struct tdma_sched_item fb_sched_set[];
396
397 /* scheduler callback to check for a FB detection response */
398 static int l1s_fbdet_resp(__unused uint8_t p1, uint8_t attempt,
399                           uint16_t fb_mode)
400 {
401         putchart('f');
402
403         if (!dsp_api.ndb->d_fb_det) {
404                 /* we did not detect a FB */
405
406                 /* attempt < 12, do nothing */
407                 if (attempt < 12)
408                         return 0;
409
410                 /* attempt >= 12, we simply don't find one */
411
412                 /* If we don't reset here, we get DSP DMA errors */
413                 tdma_sched_reset();
414
415                 if (fbs.fb_retries < FB0_RETRY_COUNT) {
416                         /* retry once more */
417                         tdma_schedule_set(1, fb_sched_set, 0);
418                         fbs.fb_retries++;
419                 } else {
420                         last_fb->attempt = 13;
421                         l1s_compl_sched(L1_COMPL_FB);
422                 }
423
424                 return 0;
425         }
426
427         /* We found a frequency burst, reset everything */
428         l1s_reset_hw();
429
430         printf("FB%u ", dsp_api.ndb->d_fb_mode);
431         read_fb_result(last_fb, attempt);
432
433         /* if this is the first success, save freq err */
434         if (!fbs.initial_freq_err)
435                 fbs.initial_freq_err = last_fb->freq_diff;
436
437         /* If we don't reset here, we get DSP DMA errors */
438         tdma_sched_reset();
439
440         /* Immediately schedule further TDMA tasklets, if requested. Doing
441          * this directly from L1S means we can do this quickly without any
442          * additional delays */
443         if (fb_mode == 0) {
444                 if (fbs.req.flags & L1CTL_FBSB_F_FB1) {
445                         /* If we don't reset here, we get DSP DMA errors */
446                         tdma_sched_reset();
447                         /* FIXME: don't only use the last but an average */
448                         if (abs(last_fb->freq_diff) < fbs.req.freq_err_thresh1 &&
449                             last_fb->snr > FB0_SNR_THRESH) {
450                                 /* continue with FB1 task in DSP */
451                                 tdma_schedule_set(1, fb_sched_set, 1);
452                         } else {
453                                 if (fbs.afc_retries < AFC_RETRY_COUNT) {
454                                         tdma_schedule_set(1, fb_sched_set, 0);
455                                         fbs.afc_retries++;
456                                 } else {
457                                         /* Abort */
458                                         last_fb->attempt = 13;
459                                         l1s_compl_sched(L1_COMPL_FB);
460                                 }
461                         }
462                 } else
463                         l1s_compl_sched(L1_COMPL_FB);
464         } else if (fb_mode == 1) {
465                 if (fbs.req.flags & L1CTL_FBSB_F_SB) {
466
467         int ntdma, qbits;
468         /* FIXME: where did this magic 23 come from? */
469         last_fb->toa -= 23;
470
471         if (last_fb->toa < 0) {
472                 qbits = (last_fb->toa + BITS_PER_TDMA) * 4;
473                 ntdma = -1;
474         } else {
475                 ntdma = (last_fb->toa) / BITS_PER_TDMA;
476                 qbits = (last_fb->toa - ntdma * BITS_PER_TDMA) * 4;
477         }
478
479
480                         int fn_offset = l1s.current_time.fn - last_fb->attempt + ntdma;
481                         int delay = fn_offset + 11 - l1s.current_time.fn - 1;
482                         printf("  fn_offset=%d (fn=%u + attempt=%u + ntdma = %d)\m",
483                                 fn_offset, l1s.current_time.fn, last_fb->attempt, ntdma);
484                         printf("  delay=%d (fn_offset=%d + 11 - fn=%u - 1\n", delay,
485                                 fn_offset, l1s.current_time.fn);
486                         printf("  scheduling next FB/SB detection task with delay %u\n", delay);
487                         if (abs(last_fb->freq_diff) < fbs.req.freq_err_thresh2 &&
488                             last_fb->snr > FB1_SNR_THRESH) {
489                                 /* synchronize before reading SB */
490                                 fbinfo2cellinfo(&l1s.serving_cell, last_fb);
491                                 synchronize_tdma(&l1s.serving_cell);
492                                 tdma_schedule_set(delay, sb_sched_set, 0);
493                         } else
494                                 tdma_schedule_set(delay, fb_sched_set, 1);
495                 } else
496                         l1s_compl_sched(L1_COMPL_FB);
497         }
498
499         return 0;
500 }
501
502 /* FB detection */
503 static const struct tdma_sched_item fb_sched_set[] = {
504         SCHED_ITEM_DT(l1s_fbdet_cmd, 0, 0, 0),  SCHED_END_FRAME(),
505                                                 SCHED_END_FRAME(),
506         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 1),   SCHED_END_FRAME(),
507         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 2),   SCHED_END_FRAME(),
508         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 3),   SCHED_END_FRAME(),
509         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 4),   SCHED_END_FRAME(),
510         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 5),   SCHED_END_FRAME(),
511         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 6),   SCHED_END_FRAME(),
512         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 7),   SCHED_END_FRAME(),
513         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 8),   SCHED_END_FRAME(),
514         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 9),   SCHED_END_FRAME(),
515         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 10),  SCHED_END_FRAME(),
516         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 11),  SCHED_END_FRAME(),
517         SCHED_ITEM(l1s_fbdet_resp, -4, 0, 12),  SCHED_END_FRAME(),
518         SCHED_END_SET()
519 };
520
521 /* Asynchronous completion handler for FB detection */
522 static void l1a_fb_compl(__unused enum l1_compl c)
523 {
524         struct l1_cell_info *cinfo = &l1s.serving_cell;
525
526         if (last_fb->attempt >= 13) {
527                 /* FB detection failed, signal this via L1CTL */
528                 return l1ctl_fbsb_resp(255);
529         }
530
531         /* FIME: use l1s.neigh_cell[fbs.cinfo_idx] */
532         fbinfo2cellinfo(&l1s.serving_cell, last_fb);
533
534         /* send FBSB_CONF success message via L1CTL */
535         l1ctl_fbsb_resp(0);
536 }
537
538 void l1s_fbsb_req(uint8_t base_fn, struct l1ctl_fbsb_req *req)
539 {
540         /* copy + endian convert request data */
541         fbs.req.band_arfcn = ntohs(req->band_arfcn);
542         fbs.req.timeout = ntohs(req->timeout);
543         fbs.req.freq_err_thresh1 = ntohs(req->freq_err_thresh1);
544         fbs.req.freq_err_thresh2 = ntohs(req->freq_err_thresh2);
545         fbs.req.num_freqerr_avg = req->num_freqerr_avg;
546         fbs.req.flags = req->flags;
547         fbs.req.sync_info_idx = req->sync_info_idx;
548
549         /* clear initial frequency error */
550         fbs.initial_freq_err = 0;
551         fbs.fb_retries = 0;
552         fbs.afc_retries = 0;
553
554         /* Make sure we start at a 'center' AFCDAC output value */
555         afc_reset();
556
557         if (fbs.req.flags & L1CTL_FBSB_F_FB0)
558                 tdma_schedule_set(base_fn, fb_sched_set, 0);
559         else if (fbs.req.flags & L1CTL_FBSB_F_FB1)
560                 tdma_schedule_set(base_fn, fb_sched_set, 0);
561         else if (fbs.req.flags & L1CTL_FBSB_F_SB)
562                 tdma_schedule_set(base_fn, sb_sched_set, 0);
563
564 }
565
566 static __attribute__ ((constructor)) void l1s_prim_fbsb_init(void)
567 {
568         l1s.completion[L1_COMPL_FB] = &l1a_fb_compl;
569 }