aboutsummaryrefslogtreecommitdiffstats
path: root/src/osmo-bts-trx/trx_if.c
blob: 166cfe6d0a8a2fffca19712795553fdb9f3608f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
/*
 * OpenBTS-style TRX interface/protocol handling
 *
 * This file contains the BTS-side implementation of the OpenBTS-style
 * UDP TRX protocol.  It manages the clock, control + burst-data UDP
 * sockets and their respective protocol encoding/parsing.
 *
 * Copyright (C) 2013  Andreas Eversberg <jolly@eversberg.eu>
 * Copyright (C) 2016-2017  Harald Welte <laforge@gnumonks.org>
 * Copyright (C) 2019  Vadim Yanitskiy <axilirator@gmail.com>
 *
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include <netinet/in.h>

#include <osmocom/core/select.h>
#include <osmocom/core/socket.h>
#include <osmocom/core/timer.h>
#include <osmocom/core/talloc.h>
#include <osmocom/core/bits.h>

#include <osmo-bts/phy_link.h>
#include <osmo-bts/logging.h>
#include <osmo-bts/bts.h>
#include <osmo-bts/scheduler.h>

#include "l1_if.h"
#include "trx_if.h"

int transceiver_available = 0;

/*
 * socket helper functions
 */

/*! convenience wrapper to open socket + fill in osmo_fd */
static int trx_udp_open(void *priv, struct osmo_fd *ofd, const char *host_local,
			uint16_t port_local, const char *host_remote, uint16_t port_remote,
			int (*cb)(struct osmo_fd *fd, unsigned int what))
{
	int rc;

	/* Init */
	ofd->fd = -1;
	ofd->cb = cb;
	ofd->data = priv;

	/* Listen / Binds + Connect */
	rc = osmo_sock_init2_ofd(ofd, AF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, host_local, port_local,
				host_remote, port_remote, OSMO_SOCK_F_BIND | OSMO_SOCK_F_CONNECT);
	if (rc < 0)
		return rc;

	return 0;
}

/* close socket + unregister osmo_fd */
static void trx_udp_close(struct osmo_fd *ofd)
{
	if (ofd->fd >= 0) {
		osmo_fd_unregister(ofd);
		close(ofd->fd);
		ofd->fd = -1;
	}
}


/*
 * TRX clock socket
 */

/* get clock from clock socket */
static int trx_clk_read_cb(struct osmo_fd *ofd, unsigned int what)
{
	struct phy_link *plink = ofd->data;
	struct phy_instance *pinst = phy_instance_by_num(plink, 0);
	char buf[1500];
	int len;
	uint32_t fn;

	OSMO_ASSERT(pinst);

	len = recv(ofd->fd, buf, sizeof(buf) - 1, 0);
	if (len <= 0)
		return len;
	buf[len] = '\0';

	if (!!strncmp(buf, "IND CLOCK ", 10)) {
		LOGPPHI(pinst, DTRX, LOGL_NOTICE,
			"Unknown message on clock port: %s\n", buf);
		return 0;
	}

	if (sscanf(buf, "IND CLOCK %u", &fn) != 1) {
		LOGPPHI(pinst, DTRX, LOGL_ERROR, "Unable to parse '%s'\n", buf);
		return 0;
	}

	LOGPPHI(pinst, DTRX, LOGL_INFO, "Clock indication: fn=%u\n", fn);

	if (fn >= GSM_HYPERFRAME) {
		fn %= GSM_HYPERFRAME;
		LOGPPHI(pinst, DTRX, LOGL_ERROR, "Indicated clock's FN is not "
			"wrapping correctly, correcting to fn=%u\n", fn);
	}

	/* inform core TRX clock handling code that a FN has been received */
	trx_sched_clock(pinst->trx->bts, fn);

	return 0;
}


/*
 * TRX ctrl socket
 */

/* send first ctrl message and start timer */
static void trx_ctrl_send(struct trx_l1h *l1h)
{
	struct trx_ctrl_msg *tcm;
	char buf[1500];
	int len;

	/* get first command */
	if (llist_empty(&l1h->trx_ctrl_list))
		return;
	tcm = llist_entry(l1h->trx_ctrl_list.next, struct trx_ctrl_msg, list);

	len = snprintf(buf, sizeof(buf), "CMD %s%s%s", tcm->cmd, tcm->params_len ? " ":"", tcm->params);
	OSMO_ASSERT(len < sizeof(buf));

	LOGPPHI(l1h->phy_inst, DTRX, LOGL_DEBUG, "Sending control '%s'\n", buf);
	/* send command */
	send(l1h->trx_ofd_ctrl.fd, buf, len+1, 0);

	/* start timer */
	osmo_timer_schedule(&l1h->trx_ctrl_timer, 2, 0);
}

/* send first ctrl message and start timer */
static void trx_ctrl_timer_cb(void *data)
{
	struct trx_l1h *l1h = data;
	struct trx_ctrl_msg *tcm = NULL;

	/* get first command */
	OSMO_ASSERT(!llist_empty(&l1h->trx_ctrl_list));
	tcm = llist_entry(l1h->trx_ctrl_list.next, struct trx_ctrl_msg, list);

	LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE, "No satisfactory response from transceiver(CMD %s%s%s)\n",
		tcm->cmd, tcm->params_len ? " ":"", tcm->params);

	trx_ctrl_send(l1h);
}

void trx_if_init(struct trx_l1h *l1h)
{
	l1h->trx_ctrl_timer.cb = trx_ctrl_timer_cb;
	l1h->trx_ctrl_timer.data = l1h;
}

/*! Send a new TRX control command.
 *  \param[inout] l1h TRX Layer1 handle to which to send command
 *  \param[in] criticial
 *  \param[in] cb callback function to be called when valid response is
 *  		  received. Type of cb depends on type of message.
 *  \param[in] cmd zero-terminated string containing command
 *  \param[in] fmt Format string (+ variable list of arguments)
 *  \returns 0 on success; negative on error
 *
 *  The new ocommand will be added to the end of the control command
 *  queue.
 */
static int trx_ctrl_cmd_cb(struct trx_l1h *l1h, int critical, void *cb, const char *cmd,
	const char *fmt, ...)
{
	struct trx_ctrl_msg *tcm;
	struct trx_ctrl_msg *prev = NULL;
	va_list ap;
	int pending;

	if (!transceiver_available &&
	    !(!strcmp(cmd, "POWEROFF") || !strcmp(cmd, "POWERON"))) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR, "CTRL %s ignored: No clock from "
			"transceiver, please fix!\n", cmd);
		return -EIO;
	}

	pending = !llist_empty(&l1h->trx_ctrl_list);

	/* create message */
	tcm = talloc_zero(tall_bts_ctx, struct trx_ctrl_msg);
	if (!tcm)
		return -ENOMEM;
	snprintf(tcm->cmd, sizeof(tcm->cmd)-1, "%s", cmd);
	tcm->cmd[sizeof(tcm->cmd)-1] = '\0';
	tcm->cmd_len = strlen(tcm->cmd);
	if (fmt && fmt[0]) {
		va_start(ap, fmt);
		vsnprintf(tcm->params, sizeof(tcm->params) - 1, fmt, ap);
		va_end(ap);
		tcm->params[sizeof(tcm->params)-1] = '\0';
		tcm->params_len = strlen(tcm->params);
	} else {
		tcm->params[0] ='\0';
		tcm->params_len = 0;
	}
	tcm->critical = critical;
	tcm->cb = cb;

	/* Avoid adding consecutive duplicate messages, eg: two consecutive POWEROFF */
	if(pending)
		prev = llist_entry(l1h->trx_ctrl_list.prev, struct trx_ctrl_msg, list);

	if (!pending ||
	    !(strcmp(tcm->cmd, prev->cmd) == 0 && strcmp(tcm->params, prev->params) == 0)) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_INFO, "Enqueuing TRX control command 'CMD %s%s%s'\n",
			tcm->cmd, tcm->params_len ? " ":"", tcm->params);
		llist_add_tail(&tcm->list, &l1h->trx_ctrl_list);
	}

	/* send message, if we didn't already have pending messages */
	if (!pending)
		trx_ctrl_send(l1h);

	return 0;
}
#define trx_ctrl_cmd(l1h, critical, cmd, fmt, ...) trx_ctrl_cmd_cb(l1h, critical, NULL, cmd, fmt, ##__VA_ARGS__)

/*! Send "POWEROFF" command to TRX */
int trx_if_cmd_poweroff(struct trx_l1h *l1h)
{
	struct phy_instance *pinst = l1h->phy_inst;
	if (pinst->num == 0)
		return trx_ctrl_cmd(l1h, 1, "POWEROFF", "");
	else
		return 0;
}

/*! Send "POWERON" command to TRX */
int trx_if_cmd_poweron(struct trx_l1h *l1h)
{
	struct phy_instance *pinst = l1h->phy_inst;
	if (pinst->num == 0)
		return trx_ctrl_cmd(l1h, 1, "POWERON", "");
	else
		return 0;
}

/*! Send "SETFORMAT" command to TRX: change TRXD header format version */
int trx_if_cmd_setformat(struct trx_l1h *l1h, uint8_t ver)
{
	LOGPPHI(l1h->phy_inst, DTRX, LOGL_INFO,
		"Requesting TRXD header format version %u\n", ver);

	return trx_ctrl_cmd(l1h, 0, "SETFORMAT", "%u", ver);
}

/*! Send "SETTSC" command to TRX */
int trx_if_cmd_settsc(struct trx_l1h *l1h, uint8_t tsc)
{
	struct phy_instance *pinst = l1h->phy_inst;
	if (pinst->phy_link->u.osmotrx.use_legacy_setbsic)
		return 0;

	return trx_ctrl_cmd(l1h, 1, "SETTSC", "%d", tsc);
}

/*! Send "SETBSIC" command to TRX */
int trx_if_cmd_setbsic(struct trx_l1h *l1h, uint8_t bsic)
{
	struct phy_instance *pinst = l1h->phy_inst;
	if (!pinst->phy_link->u.osmotrx.use_legacy_setbsic)
		return 0;

	return trx_ctrl_cmd(l1h, 1, "SETBSIC", "%d", bsic);
}

/*! Send "SETRXGAIN" command to TRX */
int trx_if_cmd_setrxgain(struct trx_l1h *l1h, int db)
{
	return trx_ctrl_cmd(l1h, 0, "SETRXGAIN", "%d", db);
}

/*! Send "SETPOWER" command to TRX */
int trx_if_cmd_setpower(struct trx_l1h *l1h, int db)
{
	return trx_ctrl_cmd(l1h, 0, "SETPOWER", "%d", db);
}

/*! Send "SETMAXDLY" command to TRX, i.e. maximum delay for RACH bursts */
int trx_if_cmd_setmaxdly(struct trx_l1h *l1h, int dly)
{
	return trx_ctrl_cmd(l1h, 0, "SETMAXDLY", "%d", dly);
}

/*! Send "SETMAXDLYNB" command to TRX, i.e. maximum delay for normal bursts */
int trx_if_cmd_setmaxdlynb(struct trx_l1h *l1h, int dly)
{
	return trx_ctrl_cmd(l1h, 0, "SETMAXDLYNB", "%d", dly);
}

/*! Send "SETSLOT" command to TRX: Configure Channel Combination for TS */
int trx_if_cmd_setslot(struct trx_l1h *l1h, uint8_t tn, uint8_t type, trx_if_cmd_setslot_cb *cb)
{
	return trx_ctrl_cmd_cb(l1h, 1, cb, "SETSLOT", "%d %d", tn, type);
}

/*! Send "RXTUNE" command to TRX: Tune Receiver to given ARFCN */
int trx_if_cmd_rxtune(struct trx_l1h *l1h, uint16_t arfcn)
{
	struct phy_instance *pinst = l1h->phy_inst;
	uint16_t freq10;

	if (pinst->trx->bts->band == GSM_BAND_1900)
		arfcn |= ARFCN_PCS;

	freq10 = gsm_arfcn2freq10(arfcn, 1); /* RX = uplink */
	if (freq10 == 0xffff) {
		LOGPPHI(pinst, DTRX, LOGL_ERROR, "Arfcn %d not defined.\n",
			arfcn & ~ARFCN_FLAG_MASK);
		return -ENOTSUP;
	}

	return trx_ctrl_cmd(l1h, 1, "RXTUNE", "%d", freq10 * 100);
}

/*! Send "TXTUNE" command to TRX: Tune Transmitter to given ARFCN */
int trx_if_cmd_txtune(struct trx_l1h *l1h, uint16_t arfcn)
{
	struct phy_instance *pinst = l1h->phy_inst;
	uint16_t freq10;

	if (pinst->trx->bts->band == GSM_BAND_1900)
		arfcn |= ARFCN_PCS;

	freq10 = gsm_arfcn2freq10(arfcn, 0); /* TX = downlink */
	if (freq10 == 0xffff) {
		LOGPPHI(pinst, DTRX, LOGL_ERROR, "Arfcn %d not defined.\n",
			arfcn & ~ARFCN_FLAG_MASK);
		return -ENOTSUP;
	}

	return trx_ctrl_cmd(l1h, 1, "TXTUNE", "%d", freq10 * 100);
}

/*! Send "HANDOVER" command to TRX: Enable handover RACH Detection on timeslot/sub-slot */
int trx_if_cmd_handover(struct trx_l1h *l1h, uint8_t tn, uint8_t ss)
{
	return trx_ctrl_cmd(l1h, 1, "HANDOVER", "%d %d", tn, ss);
}

/*! Send "NOHANDOVER" command to TRX: Disable handover RACH Detection on timeslot/sub-slot */
int trx_if_cmd_nohandover(struct trx_l1h *l1h, uint8_t tn, uint8_t ss)
{
	return trx_ctrl_cmd(l1h, 1, "NOHANDOVER", "%d %d", tn, ss);
}

struct trx_ctrl_rsp {
	char cmd[50];
	char params[100];
	int status;
	void *cb;
};

static int parse_rsp(const char *buf_in, size_t len_in, struct trx_ctrl_rsp *rsp)
{
	char *p, *k;

	if (strncmp(buf_in, "RSP ", 4))
		goto parse_err;

	/* Get the RSP cmd name */
	if (!(p = strchr(buf_in + 4, ' ')))
		goto parse_err;

	if (p - buf_in >= sizeof(rsp->cmd)) {
		LOGP(DTRX, LOGL_ERROR, "cmd buffer too small %lu >= %lu\n",
			p - buf_in, sizeof(rsp->cmd));
		goto parse_err;
	}

	rsp->cmd[0] = '\0';
	strncat(rsp->cmd, buf_in + 4, p - buf_in - 4);

	/* Now comes the status code of the response */
	p++;
	if (sscanf(p, "%d", &rsp->status) != 1)
		goto parse_err;

	/* Now copy back the parameters */
	k = strchr(p, ' ');
	if (k)
		k++;
	else
		k = p + strlen(p);

	if (strlen(k) >= sizeof(rsp->params)) {
		LOGP(DTRX, LOGL_ERROR, "params buffer too small %lu >= %lu\n",
			strlen(k), sizeof(rsp->params));
		goto parse_err;
	}
	rsp->params[0] = '\0';
	strcat(rsp->params, k);
	return 0;

parse_err:
	LOGP(DTRX, LOGL_NOTICE, "Unknown message on ctrl port: %s\n",
		buf_in);
	return -1;
}

static bool cmd_matches_rsp(struct trx_ctrl_msg *tcm, struct trx_ctrl_rsp *rsp)
{
	if (strcmp(tcm->cmd, rsp->cmd))
		return false;

	/* For SETSLOT we also need to check if it's the response for the
	   specific timeslot. For other commands such as SETRXGAIN, it is
	   expected that they can return different values */
	if (strcmp(tcm->cmd, "SETSLOT") == 0 && strcmp(tcm->params, rsp->params))
		return false;
	else if (strcmp(tcm->cmd, "SETFORMAT") == 0 && strcmp(tcm->params, rsp->params))
		return false;

	return true;
}

static int trx_ctrl_rx_rsp_setslot(struct trx_l1h *l1h, struct trx_ctrl_rsp *rsp)
{
	trx_if_cmd_setslot_cb *cb = (trx_if_cmd_setslot_cb*) rsp->cb;
	struct phy_instance *pinst = l1h->phy_inst;
	unsigned int tn, ts_type;

	if (rsp->status)
		LOGPPHI(pinst, DTRX, LOGL_ERROR, "transceiver SETSLOT failed with status %d\n",
			rsp->status);

	/* Since message was already validated against CMD we sent, we know format
	 * of params is: "<TN> <TS_TYPE>" */
	if (sscanf(rsp->params, "%u %u", &tn, &ts_type) < 2) {
		LOGPPHI(pinst, DTRX, LOGL_ERROR, "transceiver SETSLOT unable to parse params\n");
		return -EINVAL;
	}

	if (cb)
		cb(l1h, tn, ts_type, rsp->status);

	return rsp->status == 0 ? 0 : -EINVAL;
}

/* TRXD header format negotiation handler.
 *
 * If the transceiver does not support the format negotiation, it would
 * reject SETFORMAT with 'RSP ERR 1'. If the requested version is not
 * supported by the transceiver, status code of the response message
 * should indicate a preferred (basically, the latest) version.
 */
static int trx_ctrl_rx_rsp_setformat(struct trx_l1h *l1h,
				     struct trx_ctrl_rsp *rsp)
{
	/* Old transceivers reject 'SETFORMAT' with 'RSP ERR 1' */
	if (strcmp(rsp->cmd, "SETFORMAT") != 0) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE,
			"Transceiver rejected the format negotiation command, "
			"using legacy TRXD header format version (0)\n");
		l1h->config.trxd_hdr_ver_use = 0;
		return 0;
	}

	/* Status shall indicate a proper version supported by the transceiver */
	if (rsp->status < 0 || rsp->status > l1h->config.trxd_hdr_ver_req) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR,
			"Transceiver indicated an out of range "
			"header format version %d (requested %u)\n",
			rsp->status, l1h->config.trxd_hdr_ver_req);
		return -EINVAL;
	}

	/* Transceiver may suggest a lower version (than requested) */
	if (rsp->status == l1h->config.trxd_hdr_ver_req) {
		l1h->config.trxd_hdr_ver_use = rsp->status;
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_INFO,
			"Using TRXD header format version %u\n",
			l1h->config.trxd_hdr_ver_use);
	} else {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_DEBUG,
			"Transceiver suggests TRXD header version %u (requested %u)\n",
			rsp->status, l1h->config.trxd_hdr_ver_req);
		/* Send another SETFORMAT with suggested version */
		l1h->config.trxd_hdr_ver_req = rsp->status;
		trx_if_cmd_setformat(l1h, rsp->status);
	}

	return 0;
}

/* -EINVAL: unrecoverable error, exit BTS
 * N > 0: try sending originating command again after N seconds
 * 0: Done with response, get originating command out from send queue
 */
static int trx_ctrl_rx_rsp(struct trx_l1h *l1h,
			   struct trx_ctrl_rsp *rsp,
			   struct trx_ctrl_msg *tcm)
{
	struct phy_instance *pinst = l1h->phy_inst;

	/* If TRX fails, try again after 1 sec */
	if (strcmp(rsp->cmd, "POWERON") == 0) {
		if (rsp->status == 0) {
			if (pinst->phy_link->state != PHY_LINK_CONNECTED)
				phy_link_state_set(pinst->phy_link, PHY_LINK_CONNECTED);
			return 0;
		} else {
			LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE,
				"transceiver rejected POWERON command (%d), re-trying in a few seconds\n",
				rsp->status);
			if (pinst->phy_link->state != PHY_LINK_SHUTDOWN)
				phy_link_state_set(pinst->phy_link, PHY_LINK_SHUTDOWN);
			return 5;
		}
	} else if (strcmp(rsp->cmd, "SETSLOT") == 0) {
		return trx_ctrl_rx_rsp_setslot(l1h, rsp);
	/* We may get 'RSP ERR 1' if 'SETFORMAT' is not supported,
	 * so that's why we should use tcm instead of rsp. */
	} else if (strcmp(tcm->cmd, "SETFORMAT") == 0) {
		return trx_ctrl_rx_rsp_setformat(l1h, rsp);
	}

	if (rsp->status) {
		LOGPPHI(l1h->phy_inst, DTRX, tcm->critical ? LOGL_FATAL : LOGL_NOTICE,
			"transceiver rejected TRX command with response: '%s%s%s %d'\n",
			rsp->cmd, rsp->params[0] != '\0' ? " ":"",
			rsp->params, rsp->status);
		if (tcm->critical)
			return -EINVAL;
	}
	return 0;
}

/*! Get + parse response from TRX ctrl socket */
static int trx_ctrl_read_cb(struct osmo_fd *ofd, unsigned int what)
{
	struct trx_l1h *l1h = ofd->data;
	struct phy_instance *pinst = l1h->phy_inst;
	char buf[1500];
	struct trx_ctrl_rsp rsp;
	int len, rc;
	struct trx_ctrl_msg *tcm;

	len = recv(ofd->fd, buf, sizeof(buf) - 1, 0);
	if (len <= 0)
		return len;
	buf[len] = '\0';

	if (parse_rsp(buf, len, &rsp) < 0)
		return 0;

	LOGPPHI(l1h->phy_inst, DTRX, LOGL_INFO, "Response message: '%s'\n", buf);

	/* abort timer and send next message, if any */
	if (osmo_timer_pending(&l1h->trx_ctrl_timer))
		osmo_timer_del(&l1h->trx_ctrl_timer);

	/* get command for response message */
	if (llist_empty(&l1h->trx_ctrl_list)) {
		/* RSP from a retransmission, skip it */
		if (l1h->last_acked && cmd_matches_rsp(l1h->last_acked, &rsp)) {
			LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE, "Discarding duplicated RSP "
				"from old CMD '%s'\n", buf);
			return 0;
		}
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE, "Response message without command\n");
		return -EINVAL;
	}
	tcm = llist_entry(l1h->trx_ctrl_list.next, struct trx_ctrl_msg,
		list);

	/* check if response matches command */
	if (!cmd_matches_rsp(tcm, &rsp)) {
		/* RSP from a retransmission, skip it */
		if (l1h->last_acked && cmd_matches_rsp(l1h->last_acked, &rsp)) {
			LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE, "Discarding duplicated RSP "
				"from old CMD '%s'\n", buf);
			return 0;
		}
		LOGPPHI(l1h->phy_inst, DTRX, (tcm->critical) ? LOGL_FATAL : LOGL_NOTICE,
			"Response message '%s' does not match command "
			"message 'CMD %s%s%s'\n",
			buf, tcm->cmd, tcm->params_len ? " ":"", tcm->params);

		/* We may get 'RSP ERR 1' for non-critical commands */
		if (tcm->critical)
			goto rsp_error;
	}

	rsp.cb = tcm->cb;

	/* check for response code */
	rc = trx_ctrl_rx_rsp(l1h, &rsp, tcm);
	if (rc == -EINVAL)
		goto rsp_error;

	/* re-schedule last cmd in rc seconds time */
	if (rc > 0) {
		osmo_timer_schedule(&l1h->trx_ctrl_timer, rc, 0);
		return 0;
	}

	/* remove command from list, save it to last_acked and removed previous last_acked */
	llist_del(&tcm->list);
	talloc_free(l1h->last_acked);
	l1h->last_acked = tcm;

	trx_ctrl_send(l1h);

	return 0;

rsp_error:
	bts_shutdown(pinst->trx->bts, "TRX-CTRL-MSG: CRITICAL");
	/* keep tcm list, so process is stopped */
	return -EIO;
}


/*
 * TRX burst data socket
 */

/* Maximum DATA message length (header + burst) */
#define TRX_DATA_MSG_MAX_LEN	512

/* Common header length: 1/2 VER + 1/2 TDMA TN + 4 TDMA FN */
#define TRX_CHDR_LEN		(1 + 4)
/* Uplink v0 header length: 1 RSSI + 2 ToA256 */
#define TRX_UL_V0HDR_LEN	(TRX_CHDR_LEN + 1 + 2)
/* Uplink v1 header length: + 1 MTS + 2 C/I */
#define TRX_UL_V1HDR_LEN	(TRX_UL_V0HDR_LEN + 1 + 2)

/* TRXD header dissector for version 0 */
static int trx_data_handle_hdr_v0(struct trx_l1h *l1h,
				  struct trx_ul_burst_ind *bi,
				  const uint8_t *buf, size_t buf_len)
{
	/* Make sure we have enough data */
	if (buf_len < TRX_UL_V0HDR_LEN) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR,
			"Short read on TRXD, missing version 0 header "
			"(len=%zu vs expected %d)\n", buf_len, TRX_UL_V0HDR_LEN);
		return -EIO;
	}

	bi->tn = buf[0] & 0b111;
	bi->fn = osmo_load32be(buf + 1);
	bi->rssi = -(int8_t)buf[5];
	bi->toa256 = (int16_t) osmo_load16be(buf + 6);

	if (bi->fn >= GSM_HYPERFRAME) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR,
			"Illegal TDMA fn=%u\n", bi->fn);
		return -EINVAL;
	}

	return TRX_UL_V0HDR_LEN;
}

/* TRXD header dissector for version 0x01 */
static int trx_data_handle_hdr_v1(struct trx_l1h *l1h,
				  struct trx_ul_burst_ind *bi,
				  const uint8_t *buf, size_t buf_len)
{
	uint8_t mts;
	int rc;

	/* Make sure we have enough data */
	if (buf_len < TRX_UL_V1HDR_LEN) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR,
			"Short read on TRXD, missing version 1 header "
			"(len=%zu vs expected %d)\n", buf_len, TRX_UL_V1HDR_LEN);
		return -EIO;
	}

	/* Parse v0 specific part */
	rc = trx_data_handle_hdr_v0(l1h, bi, buf, buf_len);
	if (rc < 0)
		return rc;

	/* Move closer to the v1 specific part */
	buf_len -= rc;
	buf += rc;

	/* IDLE / NOPE frame indication */
	if (buf[0] & (1 << 7)) {
		bi->flags |= TRX_BI_F_NOPE_IND;
		return TRX_UL_V1HDR_LEN;
	}

	/* Modulation info and TSC set */
	mts = (buf[0] >> 3) & 0b1111;
	if ((mts & 0b1100) == 0x00) {
		bi->bt = TRX_BURST_GMSK;
		bi->tsc_set = mts & 0b11;
		bi->flags |= TRX_BI_F_MOD_TYPE;
	} else if ((mts & 0b0100) == 0b0100) {
		bi->bt = TRX_BURST_8PSK;
		bi->tsc_set = mts & 0b1;
		bi->flags |= TRX_BI_F_MOD_TYPE;
	} else {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR,
			"Indicated modulation 0x%02x is not supported\n", mts & 0b1110);
		return -ENOTSUP;
	}

	/* Training Sequence Code */
	bi->tsc = buf[0] & 0b111;
	bi->flags |= TRX_BI_F_TS_INFO;

	/* C/I: Carrier-to-Interference ratio (in centiBels) */
	bi->ci_cb = (int16_t) osmo_load16be(buf + 1);
	bi->flags |= TRX_BI_F_CI_CB;

	return TRX_UL_V1HDR_LEN;
}

/* TRXD burst handler for header version 0 */
static int trx_data_handle_burst_v0(struct trx_l1h *l1h,
				    struct trx_ul_burst_ind *bi,
				    const uint8_t *buf, size_t buf_len)
{
	size_t i;

	/* Verify burst length */
	switch (buf_len) {
	/* Legacy transceivers append two padding bytes */
	case EGPRS_BURST_LEN + 2:
	case GSM_BURST_LEN + 2:
		bi->burst_len = buf_len - 2;
		break;
	case EGPRS_BURST_LEN:
	case GSM_BURST_LEN:
		bi->burst_len = buf_len;
		break;

	default:
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE,
			"Rx TRXD message with odd burst length %zu\n", buf_len);
		return -EINVAL;
	}

	/* Convert unsigned soft-bits [254..0] to soft-bits [-127..127] */
	for (i = 0; i < bi->burst_len; i++) {
		if (buf[i] == 255)
			bi->burst[i] = -127;
		else
			bi->burst[i] = 127 - buf[i];
	}

	return 0;
}

/* TRXD burst handler for header version 1 */
static int trx_data_handle_burst_v1(struct trx_l1h *l1h,
				    struct trx_ul_burst_ind *bi,
				    const uint8_t *buf, size_t buf_len)
{
	/* Modulation types defined in 3GPP TS 45.002 */
	static const size_t bl[] = {
		[TRX_BURST_GMSK] = 148, /* 1 bit per symbol */
		[TRX_BURST_8PSK] = 444, /* 3 bits per symbol */
	};

	/* Verify burst length */
	if (bl[bi->bt] != buf_len) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE,
			"Rx TRXD message with odd burst length %zu, "
			"expected %zu\n", buf_len, bl[bi->bt]);
		return -EINVAL;
	}

	/* The burst format is the same as for version 0.
	 * NOTE: other modulation types to be handled separately. */
	return trx_data_handle_burst_v0(l1h, bi, buf, buf_len);
}

static const char *trx_data_desc_msg(const struct trx_ul_burst_ind *bi)
{
	struct osmo_strbuf sb;
	static char buf[256];

	/* Modulation types defined in 3GPP TS 45.002 */
	static const char *mod_names[] = {
		[TRX_BURST_GMSK] = "GMSK",
		[TRX_BURST_8PSK] = "8-PSK",
	};

	/* Initialize the string buffer */
	sb = (struct osmo_strbuf) { .buf = buf, .len = sizeof(buf) };

	/* Common TDMA parameters */
	OSMO_STRBUF_PRINTF(sb, "tn=%u fn=%u", bi->tn, bi->fn);

	/* Nothing else to print for NOPE.ind */
	if (bi->flags & TRX_BI_F_NOPE_IND)
		return buf;

	/* RSSI and ToA256 */
	OSMO_STRBUF_PRINTF(sb, " rssi=%d toa256=%d", bi->rssi, bi->toa256);

	/* Modulation and TSC set */
	if (bi->flags & TRX_BI_F_MOD_TYPE)
		OSMO_STRBUF_PRINTF(sb, " mod=%s", mod_names[bi->bt]);

	/* Training Sequence Code */
	if (bi->flags & TRX_BI_F_TS_INFO)
		OSMO_STRBUF_PRINTF(sb, " set=%u tsc=%u", bi->tsc_set, bi->tsc);

	/* C/I: Carrier-to-Interference ratio (in centiBels) */
	if (bi->flags & TRX_BI_F_CI_CB)
		OSMO_STRBUF_PRINTF(sb, " C/I=%d cB", bi->ci_cb);

	/* Burst length */
	OSMO_STRBUF_PRINTF(sb, " burst_len=%zu", bi->burst_len);

	return buf;
}

/* Parse TRXD message from transceiver, compose an UL burst indication.
 *
 * This message contains a demodulated Uplink burst with fixed-size
 * header preceding the burst bits. The header consists of the common
 * and message specific part.
 *
 *   +---------------+-----------------+------------+
 *   | common header | specific header | burst bits |
 *   +---------------+-----------------+------------+
 *
 * Common header is the same as for Downlink message:
 *
 *   +-----------------+----------------+-------------------+
 *   | VER (1/2 octet) | TN (1/2 octet) | FN (4 octets, BE) |
 *   +-----------------+----------------+-------------------+
 *
 * and among with TDMA parameters, contains the version indicator:
 *
 *   +-----------------+------------------------+
 *   | 7 6 5 4 3 2 1 0 | bit numbers            |
 *   +-----------------+------------------------+
 *   | X X X X . . . . | header version (0..15) |
 *   +-----------------+------------------------+
 *   | . . . . . X X X | TDMA TN (0..7)         |
 *   +-----------------+------------------------+
 *   | . . . . X . . . | RESERVED (0)           |
 *   +-----------------+------------------------+
 *
 * which is encoded in 4 MSB bits of the first octet, which used to be
 * zero-initialized due to the value range of TDMA TN. Therefore, the
 * old header format has implicit version 0x00.
 *
 * The message specific header has the following structure:
 *
 * == Version 0x00
 *
 *   +------+-----+--------------------+
 *   | RSSI | ToA | soft-bits (254..0) |
 *   +------+-----+--------------------+
 *
 * == Version 0x01
 *
 *   +------+-----+-----+-----+--------------------+
 *   | RSSI | ToA | MTS | C/I | soft-bits (254..0) |
 *   +------+-----+-----+-----+--------------------+
 *
 * where:
 *
 *   - RSSI (1 octet) - Received Signal Strength Indication
 *     encoded without the negative sign.
 *   - ToA (2 octets) - Timing of Arrival in units of 1/256
 *     of symbol (big endian).
 *   - MTS (1 octet)  - Modulation and Training Sequence info.
 *   - C/I (2 octets) - Carrier-to-Interference ratio (big endian).
 *
 * == Coding of MTS: Modulation and Training Sequence info
 *
 * 3GPP TS 45.002 version 15.1.0 defines several modulation types,
 * and a few sets of training sequences for each type. The most
 * common are GMSK and 8-PSK (which is used in EDGE).
 *
 *   +-----------------+---------------------------------------+
 *   | 7 6 5 4 3 2 1 0 | bit numbers (value range)             |
 *   +-----------------+---------------------------------------+
 *   | . . . . . X X X | Training Sequence Code (0..7)         |
 *   +-----------------+---------------------------------------+
 *   | . X X X X . . . | Modulation, TS set number (see below) |
 *   +-----------------+---------------------------------------+
 *   | X . . . . . . . | IDLE / nope frame indication (0 or 1) |
 *   +-----------------+---------------------------------------+
 *
 * The bit number 7 (MSB) is set to high when either nothing has been
 * detected, or during IDLE frames, so we can deliver noise levels,
 * and avoid clock gaps on the L1 side. Other bits are ignored,
 * and should be set to low (0) in this case. L16 shall be set to 0x00.
 *
 * == Coding of modulation and TS set number
 *
 * GMSK has 4 sets of training sequences (see tables 5.2.3a-d),
 * while 8-PSK (see tables 5.2.3f-g) and the others have 2 sets.
 * Access and Synchronization bursts also have several synch.
 * sequences.
 *
 *   +-----------------+---------------------------------------+
 *   | 7 6 5 4 3 2 1 0 | bit numbers (value range)             |
 *   +-----------------+---------------------------------------+
 *   | . 0 0 X X . . . | GMSK, 4 TS sets (0..3)                |
 *   +-----------------+---------------------------------------+
 *   | . 0 1 0 X . . . | 8-PSK, 2 TS sets (0..1)               |
 *   +-----------------+---------------------------------------+
 *   | . 0 1 1 X . . . | AQPSK, 2 TS sets (0..1)               |
 *   +-----------------+---------------------------------------+
 *   | . 1 0 0 X . . . | 16QAM, 2 TS sets (0..1)               |
 *   +-----------------+---------------------------------------+
 *   | . 1 0 1 X . . . | 32QAM, 2 TS sets (0..1)               |
 *   +-----------------+---------------------------------------+
 *   | . 1 1 1 X . . . | RESERVED (0)                          |
 *   +-----------------+---------------------------------------+
 *
 * NOTE: we only support GMSK and 8-PSK.
 *
 * == C/I: Carrier-to-Interference ratio
 *
 * The C/I value can be computed from the training sequence of each
 * burst, where we can compare the "ideal" training sequence with
 * the actual training sequence and then express that in centiBels.
 *
 * == Coding of the burst bits
 *
 * Unlike to be transmitted bursts, the received bursts are designated
 * using the soft-bits notation, so the receiver can indicate its
 * assurance from 0 to -127 that a given bit is 1, and from 0 to +127
 * that a given bit is 0.
 *
 * Each soft-bit (-127..127) of the burst is encoded as an unsigned
 * value in range (254..0) respectively using the constant shift.
 *
 */
static int trx_data_read_cb(struct osmo_fd *ofd, unsigned int what)
{
	struct trx_l1h *l1h = ofd->data;
	uint8_t buf[TRX_DATA_MSG_MAX_LEN];
	struct trx_ul_burst_ind bi;
	ssize_t hdr_len, buf_len;
	uint8_t hdr_ver;
	int rc;

	buf_len = recv(ofd->fd, buf, sizeof(buf), 0);
	if (buf_len <= 0) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR,
			"recv() failed on TRXD with rc=%zd\n", buf_len);
		return buf_len;
	}

	/* Pre-clean (initialize) the flags */
	bi.flags = 0x00;

	/* Parse the header depending on its version */
	hdr_ver = buf[0] >> 4;
	switch (hdr_ver) {
	case 0:
		/* Legacy protocol has no version indicator */
		hdr_len = trx_data_handle_hdr_v0(l1h, &bi, buf, buf_len);
		break;
	case 1:
		hdr_len = trx_data_handle_hdr_v1(l1h, &bi, buf, buf_len);
		break;
	default:
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR,
			"TRXD header version %u is not supported\n", hdr_ver);
		return -ENOTSUP;
	}

	/* Header parsing error */
	if (hdr_len < 0)
		return hdr_len;

	/* TODO: we can use NOPE indications to get noise levels on IDLE
	 * TDMA frames, and properly drive scheduler if nothing has been
	 * detected on non-IDLE channels. */
	if (bi.flags & TRX_BI_F_NOPE_IND) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_DEBUG,
			"IDLE / NOPE indications are not (yet) supported\n");
		return -ENOTSUP;
	}

	/* We're done with the header now */
	buf_len -= hdr_len;

	/* Handle burst bits */
	switch (hdr_ver) {
	case 0:
		rc = trx_data_handle_burst_v0(l1h, &bi, buf + hdr_len, buf_len);
		break;
	case 1:
		rc = trx_data_handle_burst_v1(l1h, &bi, buf + hdr_len, buf_len);
		break;
	default:
		/* Shall not happen, just to make GCC happy */
		OSMO_ASSERT(0);
	}

	/* Burst parsing error */
	if (rc < 0)
		return rc;

	/* Print header & burst info */
	LOGPPHI(l1h->phy_inst, DTRX, LOGL_DEBUG, "Rx %s (hdr_ver=%u): %s\n",
		(bi.flags & TRX_BI_F_NOPE_IND) ? "NOPE.ind" : "UL burst",
		hdr_ver, trx_data_desc_msg(&bi));

	/* feed received burst into scheduler code */
	trx_sched_ul_burst(&l1h->l1s, &bi);

	return 0;
}

/*! Send burst data for given FN/timeslot to TRX
 *  \param[inout] l1h TRX Layer1 handle referring to TX
 *  \param[in] tn Timeslot Number (0..7)
 *  \param[in] fn GSM Frame Number
 *  \param[in] pwr Transmit Power to use
 *  \param[in] bits Unpacked bits to be transmitted
 *  \param[in] nbits Number of \a bits
 *  \returns 0 on success; negative on error */
int trx_if_send_burst(struct trx_l1h *l1h, uint8_t tn, uint32_t fn, uint8_t pwr,
	const ubit_t *bits, uint16_t nbits)
{
	uint8_t hdr_ver = l1h->config.trxd_hdr_ver_use;
	uint8_t buf[TRX_DATA_MSG_MAX_LEN];

	if ((nbits != GSM_BURST_LEN) && (nbits != EGPRS_BURST_LEN)) {
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR, "Tx burst length %u invalid\n", nbits);
		return -1;
	}

	LOGPPHI(l1h->phy_inst, DTRX, LOGL_DEBUG,
		"Tx burst (hdr_ver=%u): tn=%u fn=%u pwr=%u\n",
		hdr_ver, tn, fn, pwr);

	switch (hdr_ver) {
	case 0:
	case 1:
		/* Both versions have the same header format */
		break;

	default:
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR,
			"Requested TRXD header version %u is not supported\n", hdr_ver);
		return -ENOTSUP;
	}

	buf[0] = ((hdr_ver & 0x0f) << 4) | tn;
	buf[1] = (fn >> 24) & 0xff;
	buf[2] = (fn >> 16) & 0xff;
	buf[3] = (fn >>  8) & 0xff;
	buf[4] = (fn >>  0) & 0xff;
	buf[5] = pwr;

	/* copy ubits {0,1} */
	memcpy(buf + 6, bits, nbits);

	/* we must be sure that we have clock, and we have sent all control
	 * data */
	if (transceiver_available && llist_empty(&l1h->trx_ctrl_list)) {
		send(l1h->trx_ofd_data.fd, buf, nbits + 6, 0);
	} else
		LOGPPHI(l1h->phy_inst, DTRX, LOGL_ERROR, "Ignoring TX data, transceiver offline.\n");

	return 0;
}


/*
 * open/close
 */

/*! flush (delete) all pending control messages */
void trx_if_flush(struct trx_l1h *l1h)
{
	struct trx_ctrl_msg *tcm;

	/* free ctrl message list */
	while (!llist_empty(&l1h->trx_ctrl_list)) {
		tcm = llist_entry(l1h->trx_ctrl_list.next, struct trx_ctrl_msg,
			list);
		llist_del(&tcm->list);
		talloc_free(tcm);
	}
	talloc_free(l1h->last_acked);
}

/*! close the TRX for given handle (data + control socket) */
void trx_if_close(struct trx_l1h *l1h)
{
	LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE, "Close transceiver\n");

	trx_if_flush(l1h);

	/* close sockets */
	trx_udp_close(&l1h->trx_ofd_ctrl);
	trx_udp_close(&l1h->trx_ofd_data);
}

/*! compute UDP port number used for TRX protocol */
static uint16_t compute_port(struct phy_instance *pinst, int remote, int is_data)
{
	struct phy_link *plink = pinst->phy_link;
	uint16_t inc = 1;

	if (is_data)
		inc = 2;

	if (remote)
		return plink->u.osmotrx.base_port_remote + (pinst->num << 1) + inc;
	else
		return plink->u.osmotrx.base_port_local + (pinst->num << 1) + inc;
}

/*! open a TRX interface. creates contro + data sockets */
static int trx_if_open(struct trx_l1h *l1h)
{
	struct phy_instance *pinst = l1h->phy_inst;
	struct phy_link *plink = pinst->phy_link;
	int rc;

	LOGPPHI(l1h->phy_inst, DTRX, LOGL_NOTICE, "Open transceiver\n");

	/* initialize ctrl queue */
	INIT_LLIST_HEAD(&l1h->trx_ctrl_list);

	/* open sockets */
	rc = trx_udp_open(l1h, &l1h->trx_ofd_ctrl,
			  plink->u.osmotrx.local_ip,
			  compute_port(pinst, 0, 0),
			  plink->u.osmotrx.remote_ip,
			  compute_port(pinst, 1, 0), trx_ctrl_read_cb);
	if (rc < 0)
		goto err;
	rc = trx_udp_open(l1h, &l1h->trx_ofd_data,
			  plink->u.osmotrx.local_ip,
			  compute_port(pinst, 0, 1),
			  plink->u.osmotrx.remote_ip,
			  compute_port(pinst, 1, 1), trx_data_read_cb);
	if (rc < 0)
		goto err;

	/* enable all slots */
	l1h->config.slotmask = 0xff;

	/* FIXME: why was this only for TRX0 ? */
	//if (l1h->trx->nr == 0)
	trx_if_cmd_poweroff(l1h);

	return 0;

err:
	trx_if_close(l1h);
	return rc;
}

/*! close the control + burst data sockets for one phy_instance */
static void trx_phy_inst_close(struct phy_instance *pinst)
{
	struct trx_l1h *l1h = pinst->u.osmotrx.hdl;

	trx_if_close(l1h);
	trx_sched_exit(&l1h->l1s);
}

/*! open the control + burst data sockets for one phy_instance */
static int trx_phy_inst_open(struct phy_instance *pinst)
{
	struct trx_l1h *l1h;
	int rc;

	l1h = pinst->u.osmotrx.hdl;
	if (!l1h)
		return -EINVAL;

	rc = trx_sched_init(&l1h->l1s, pinst->trx);
	if (rc < 0) {
		LOGPPHI(l1h->phy_inst, DL1C, LOGL_FATAL, "Cannot initialize scheduler\n");
		return -EIO;
	}

	rc = trx_if_open(l1h);
	if (rc < 0) {
		LOGPPHI(l1h->phy_inst, DL1C, LOGL_FATAL, "Cannot open TRX interface\n");
		trx_phy_inst_close(pinst);
		return -EIO;
	}

	return 0;
}

/*! open the PHY link using TRX protocol */
int bts_model_phy_link_open(struct phy_link *plink)
{
	struct phy_instance *pinst;
	int rc;

	phy_link_state_set(plink, PHY_LINK_CONNECTING);

	/* open the shared/common clock socket */
	rc = trx_udp_open(plink, &plink->u.osmotrx.trx_ofd_clk,
			  plink->u.osmotrx.local_ip,
			  plink->u.osmotrx.base_port_local,
			  plink->u.osmotrx.remote_ip,
			  plink->u.osmotrx.base_port_remote,
			  trx_clk_read_cb);
	if (rc < 0) {
		phy_link_state_set(plink, PHY_LINK_SHUTDOWN);
		return -1;
	}

	/* open the individual instances with their ctrl+data sockets */
	llist_for_each_entry(pinst, &plink->instances, list) {
		if (trx_phy_inst_open(pinst) < 0)
			goto cleanup;
	}
	/* FIXME: is there better way to check/report TRX availability? */
	transceiver_available = 1;
	return 0;

cleanup:
	phy_link_state_set(plink, PHY_LINK_SHUTDOWN);
	llist_for_each_entry(pinst, &plink->instances, list) {
		if (pinst->u.osmotrx.hdl) {
			trx_if_close(pinst->u.osmotrx.hdl);
			pinst->u.osmotrx.hdl = NULL;
		}
	}
	trx_udp_close(&plink->u.osmotrx.trx_ofd_clk);
	return -1;
}

/*! determine if the TRX for given handle is powered up */
int trx_if_powered(struct trx_l1h *l1h)
{
	return l1h->config.poweron;
}