aboutsummaryrefslogtreecommitdiffstats
path: root/extras/libmemif/adapter.go
blob: a74c5cf6da77684b05e846ca2005ffb59fafad41 (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
// Copyright (c) 2017 Cisco and/or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//	 http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build !windows,!darwin

package libmemif

import (
	"encoding/binary"
	"os"
	"sync"
	"syscall"
	"unsafe"

	logger "github.com/sirupsen/logrus"
)

/*
#cgo LDFLAGS: -lmemif

#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/eventfd.h>
#include <libmemif.h>

// Feature tests.
#ifndef MEMIF_HAVE_CANCEL_POLL_EVENT
// memif_cancel_poll_event that simply returns ErrUnsupported.
static int
memif_cancel_poll_event ()
{
	return 102; // ErrUnsupported
}
#endif

// govpp_memif_conn_args_t replaces fixed sized arrays with C-strings which
// are much easier to work with in cgo.
typedef struct
{
	char *socket_filename;
	char *secret;
	uint8_t num_s2m_rings;
	uint8_t num_m2s_rings;
	uint16_t buffer_size;
	uint8_t log2_ring_size;
	uint8_t is_master;
	uint32_t interface_id;
	char *interface_name;
	memif_interface_mode_t mode;
} govpp_memif_conn_args_t;

// govpp_memif_details_t replaces strings represented with (uint8_t *)
// to the standard and easy to work with in cgo: (char *)
typedef struct
{
	char *if_name;
	char *inst_name;
	char *remote_if_name;
	char *remote_inst_name;
	uint32_t id;
	char *secret;
	uint8_t role;
	uint8_t mode;
	char *socket_filename;
	uint8_t rx_queues_num;
	uint8_t tx_queues_num;
	memif_queue_details_t *rx_queues;
	memif_queue_details_t *tx_queues;
	uint8_t link_up_down;
} govpp_memif_details_t;

extern int go_on_connect_callback(void *privateCtx);
extern int go_on_disconnect_callback(void *privateCtx);

// Callbacks strip the connection handle away.

static int
govpp_on_connect_callback(memif_conn_handle_t conn, void *private_ctx)
{
	return go_on_connect_callback(private_ctx);
}

static int
govpp_on_disconnect_callback(memif_conn_handle_t conn, void *private_ctx)
{
	return go_on_disconnect_callback(private_ctx);
}

// govpp_memif_create uses govpp_memif_conn_args_t.
static int
govpp_memif_create (memif_conn_handle_t *conn, govpp_memif_conn_args_t *go_args,
                    void *private_ctx)
{
	memif_conn_args_t args;
	memset (&args, 0, sizeof (args));
	args.socket_filename = (char *)go_args->socket_filename;
	if (go_args->secret != NULL)
	{
		strncpy ((char *)args.secret, go_args->secret,
				 sizeof (args.secret) - 1);
	}
	args.num_s2m_rings = go_args->num_s2m_rings;
	args.num_m2s_rings = go_args->num_m2s_rings;
	args.buffer_size = go_args->buffer_size;
	args.log2_ring_size = go_args->log2_ring_size;
	args.is_master = go_args->is_master;
	args.interface_id = go_args->interface_id;
	if (go_args->interface_name != NULL)
	{
		strncpy ((char *)args.interface_name, go_args->interface_name,
				 sizeof(args.interface_name) - 1);
	}
	args.mode = go_args->mode;

	return memif_create(conn, &args, govpp_on_connect_callback,
						govpp_on_disconnect_callback, NULL,
						private_ctx);
}

// govpp_memif_get_details keeps reallocating buffer until it is large enough.
// The buffer is returned to be deallocated when it is no longer needed.
static int
govpp_memif_get_details (memif_conn_handle_t conn, govpp_memif_details_t *govpp_md,
                         char **buf)
{
	int rv = 0;
	size_t buflen = 1 << 7;
	char *buffer = NULL, *new_buffer = NULL;
	memif_details_t md = {0};

	do {
		// initial malloc (256 bytes) or realloc
		buflen <<= 1;
		new_buffer = realloc(buffer, buflen);
		if (new_buffer == NULL)
		{
			free(buffer);
			return MEMIF_ERR_NOMEM;
		}
		buffer = new_buffer;
		// try to get details
		rv = memif_get_details(conn, &md, buffer, buflen);
	} while (rv == MEMIF_ERR_NOBUF_DET);

	if (rv == 0)
	{
		*buf = buffer;
		govpp_md->if_name = (char *)md.if_name;
		govpp_md->inst_name = (char *)md.inst_name;
		govpp_md->remote_if_name = (char *)md.remote_if_name;
		govpp_md->remote_inst_name = (char *)md.remote_inst_name;
		govpp_md->id = md.id;
		govpp_md->secret = (char *)md.secret;
		govpp_md->role = md.role;
		govpp_md->mode = md.mode;
		govpp_md->socket_filename = (char *)md.socket_filename;
		govpp_md->rx_queues_num = md.rx_queues_num;
		govpp_md->tx_queues_num = md.tx_queues_num;
		govpp_md->rx_queues = md.rx_queues;
		govpp_md->tx_queues = md.tx_queues;
		govpp_md->link_up_down = md.link_up_down;
	}
	else
		free(buffer);
	return rv;
}

// Used to avoid cumbersome tricks that use unsafe.Pointer() + unsafe.Sizeof()
// or even cast C-array directly into Go-slice.
static memif_queue_details_t
govpp_get_rx_queue_details (govpp_memif_details_t *md, int index)
{
	return md->rx_queues[index];
}

// Used to avoid cumbersome tricks that use unsafe.Pointer() + unsafe.Sizeof()
// or even cast C-array directly into Go-slice.
static memif_queue_details_t
govpp_get_tx_queue_details (govpp_memif_details_t *md, int index)
{
	return md->tx_queues[index];
}

// Copy packet data into the selected buffer.
static void
govpp_copy_packet_data(memif_buffer_t *buffers, int index, void *data, uint16_t size)
{
	buffers[index].len = (size > buffers[index].len ? buffers[index].len : size);
	memcpy(buffers[index].data, data, (size_t)buffers[index].len);
}

// Get packet data from the selected buffer.
// Used to avoid an ugly unsafe.Pointer() + unsafe.Sizeof().
static void *
govpp_get_packet_data(memif_buffer_t *buffers, int index, int *size)
{
	*size = (int)buffers[index].len;
	return buffers[index].data;
}

*/
import "C"

// IfMode represents the mode (layer/behaviour) in which the interface operates.
type IfMode int

const (
	// IfModeEthernet tells memif to operate on the L2 layer.
	IfModeEthernet IfMode = iota

	// IfModeIP tells memif to operate on the L3 layer.
	IfModeIP

	// IfModePuntInject tells memif to behave as Inject/Punt interface.
	IfModePuntInject
)

// RxMode is used to switch between polling and interrupt for RX.
type RxMode int

const (
	// RxModeInterrupt tells libmemif to send interrupt signal when data are available.
	RxModeInterrupt RxMode = iota

	// RxModePolling means that the user needs to explicitly poll for data on RX
	// queues.
	RxModePolling
)

// RawPacketData represents raw packet data. libmemif doesn't care what the
// actual content is, it only manipulates with raw bytes.
type RawPacketData []byte

// MemifMeta is used to store a basic memif metadata needed for identification
// and connection establishment.
type MemifMeta struct {
	// IfName is the interface name. Has to be unique across all created memifs.
	// Interface name is truncated if needed to have no more than 32 characters.
	IfName string

	// InstanceName identifies the endpoint. If omitted, the application
	// name passed to Init() will be used instead.
	// Instance name is truncated if needed to have no more than 32 characters.
	InstanceName string

	// ConnID is a connection ID used to match opposite sides of the memif
	// connection.
	ConnID uint32

	// SocketFilename is the filename of the AF_UNIX socket through which
	// the connection is established.
	// The string is truncated if neede to fit into sockaddr_un.sun_path
	// (108 characters on Linux).
	SocketFilename string

	// Secret must be the same on both sides for the authentication to succeed.
	// Empty string is allowed.
	// The secret is truncated if needed to have no more than 24 characters.
	Secret string

	// IsMaster is set to true if memif operates in the Master mode.
	IsMaster bool

	// Mode is the mode (layer/behaviour) in which the memif operates.
	Mode IfMode
}

// MemifShmSpecs is used to store the specification of the shared memory segment
// used by memif to send/receive packets.
type MemifShmSpecs struct {
	// NumRxQueues is the number of Rx queues.
	// Default is 1 (used if the value is 0).
	NumRxQueues uint8

	// NumTxQueues is the number of Tx queues.
	// Default is 1 (used if the value is 0).
	NumTxQueues uint8

	// BufferSize is the size of the buffer to hold one packet, or a single
	// fragment of a jumbo frame. Default is 2048 (used if the value is 0).
	BufferSize uint16

	// Log2RingSize is the number of items in the ring represented through
	// the logarithm base 2.
	// Default is 10 (used if the value is 0).
	Log2RingSize uint8
}

// MemifConfig is the memif configuration.
// Used as the input argument to CreateInterface().
// It is the slave's config that mostly decides the parameters of the connection,
// but master may limit some of the quantities if needed (based on the memif
// protocol or master's configuration)
type MemifConfig struct {
	MemifMeta
	MemifShmSpecs
}

// ConnUpdateCallback is a callback type declaration used with callbacks
// related to connection status changes.
type ConnUpdateCallback func(memif *Memif) (err error)

// MemifCallbacks is a container for all callbacks provided by memif.
// Any callback can be nil, in which case it will be simply skipped.
// Important: Do not call CreateInterface() or Memif.Close() from within a callback
// or a deadlock will occur. Instead send signal through a channel to another
// go routine which will be able to create/remove memif interface(s).
type MemifCallbacks struct {
	// OnConnect is triggered when a connection for a given memif was established.
	OnConnect ConnUpdateCallback

	// OnDisconnect is triggered when a connection for a given memif was lost.
	OnDisconnect ConnUpdateCallback
}

// Memif represents a single memif interface. It provides methods to send/receive
// packets in bursts in either the polling mode or in the interrupt mode with
// the help of golang channels.
type Memif struct {
	MemifMeta

	// Per-library references
	ifIndex int                   // index used in the Go-libmemif context (Context.memifs)
	cHandle C.memif_conn_handle_t // handle used in C-libmemif

	// Callbacks
	callbacks *MemifCallbacks

	// Interrupt
	intCh      chan uint8      // memif-global interrupt channel (value = queue ID)
	queueIntCh []chan struct{} // per RX queue interrupt channel

	// Rx/Tx queues
	ringSize    int              // number of items in each ring
	stopQPollFd int              // event file descriptor used to stop pollRxQueue-s
	wg          sync.WaitGroup   // wait group for all pollRxQueue-s
	rxQueueBufs []CPacketBuffers // an array of C-libmemif packet buffers for each RX queue
	txQueueBufs []CPacketBuffers // an array of C-libmemif packet buffers for each TX queue
}

// MemifDetails provides a detailed runtime information about a memif interface.
type MemifDetails struct {
	MemifMeta
	MemifConnDetails
}

// MemifConnDetails provides a detailed runtime information about a memif
// connection.
type MemifConnDetails struct {
	// RemoteIfName is the name of the memif on the opposite side.
	RemoteIfName string
	// RemoteInstanceName is the name of the endpoint on the opposite side.
	RemoteInstanceName string
	// HasLink is true if the connection has link (= is established and functional).
	HasLink bool
	// RxQueues contains details for each Rx queue.
	RxQueues []MemifQueueDetails
	// TxQueues contains details for each Tx queue.
	TxQueues []MemifQueueDetails
}

// MemifQueueDetails provides a detailed runtime information about a memif queue.
// Queue = Ring + the associated buffers (one directional).
type MemifQueueDetails struct {
	// QueueID is the ID of the queue.
	QueueID uint8
	// RingSize is the number of slots in the ring (not logarithmic).
	RingSize uint32
	// BufferSize is the size of each buffer pointed to from the ring slots.
	BufferSize uint16
	/* Further ring information TO-BE-ADDED when C-libmemif supports them. */
}

// CPacketBuffers stores an array of memif buffers for use with TxBurst or RxBurst.
type CPacketBuffers struct {
	buffers *C.memif_buffer_t
	count   int
}

// Context is a global Go-libmemif runtime context.
type Context struct {
	lock           sync.RWMutex
	initialized    bool
	memifs         map[int] /* ifIndex */ *Memif /* slice of all active memif interfaces */
	nextMemifIndex int

	wg sync.WaitGroup /* wait-group for pollEvents() */
}

var (
	// logger used by the adapter.
	log *logger.Logger

	// Global Go-libmemif context.
	context = &Context{initialized: false}
)

// init initializes global logger, which logs debug level messages to stdout.
func init() {
	log = logger.New()
	log.Out = os.Stdout
	log.Level = logger.DebugLevel
}

// SetLogger changes the logger for Go-libmemif to the provided one.
// The logger is not used for logging of C-libmemif.
func SetLogger(l *logger.Logger) {
	log = l
}

// Init initializes the libmemif library. Must by called exactly once and before
// any libmemif functions. Do not forget to call Cleanup() before exiting
// your application.
// <appName> should be a human-readable string identifying your application.
// For example, VPP returns the version information ("show version" from VPP CLI).
func Init(appName string) error {
	context.lock.Lock()
	defer context.lock.Unlock()

	if context.initialized {
		return ErrAlreadyInit
	}

	log.Debug("Initializing libmemif library")

	// Initialize C-libmemif.
	var errCode int
	if appName == "" {
		errCode = int(C.memif_init(nil, nil, nil, nil))
	} else {
		appName := C.CString(appName)
		defer C.free(unsafe.Pointer(appName))
		errCode = int(C.memif_init(nil, appName, nil, nil))
	}
	err := getMemifError(errCode)
	if err != nil {
		return err
	}

	// Initialize the map of memory interfaces.
	context.memifs = make(map[int]*Memif)

	// Start event polling.
	context.wg.Add(1)
	go pollEvents()

	context.initialized = true
	log.Debug("libmemif library was initialized")
	return err
}

// Cleanup cleans up all the resources allocated by libmemif.
func Cleanup() error {
	context.lock.Lock()
	defer context.lock.Unlock()

	if !context.initialized {
		return ErrNotInit
	}

	log.Debug("Closing libmemif library")

	// Delete all active interfaces.
	for _, memif := range context.memifs {
		memif.Close()
	}

	// Stop the event loop (if supported by C-libmemif).
	errCode := C.memif_cancel_poll_event()
	err := getMemifError(int(errCode))
	if err == nil {
		log.Debug("Waiting for pollEvents() to stop...")
		context.wg.Wait()
		log.Debug("pollEvents() has stopped...")
	} else {
		log.WithField("err", err).Debug("NOT Waiting for pollEvents to stop...")
	}

	// Run cleanup for C-libmemif.
	err = getMemifError(int(C.memif_cleanup()))
	if err == nil {
		context.initialized = false
		log.Debug("libmemif library was closed")
	}
	return err
}

// CreateInterface creates a new memif interface with the given configuration.
// The same callbacks can be used with multiple memifs. The first callback input
// argument (*Memif) can be used to tell which memif the callback was triggered for.
// The method is thread-safe.
func CreateInterface(config *MemifConfig, callbacks *MemifCallbacks) (memif *Memif, err error) {
	context.lock.Lock()
	defer context.lock.Unlock()

	if !context.initialized {
		return nil, ErrNotInit
	}

	log.WithField("ifName", config.IfName).Debug("Creating a new memif interface")

	log2RingSize := config.Log2RingSize
	if log2RingSize == 0 {
		log2RingSize = 10
	}

	// Create memif-wrapper for Go-libmemif.
	memif = &Memif{
		MemifMeta: config.MemifMeta,
		callbacks: &MemifCallbacks{},
		ifIndex:   context.nextMemifIndex,
		ringSize:  1 << log2RingSize,
	}

	// Initialize memif callbacks.
	if callbacks != nil {
		memif.callbacks.OnConnect = callbacks.OnConnect
		memif.callbacks.OnDisconnect = callbacks.OnDisconnect
	}

	// Initialize memif-global interrupt channel.
	memif.intCh = make(chan uint8, 1<<6)

	// Initialize event file descriptor for stopping Rx/Tx queue polling.
	memif.stopQPollFd = int(C.eventfd(0, C.EFD_NONBLOCK))
	if memif.stopQPollFd < 0 {
		return nil, ErrSyscall
	}

	// Initialize memif input arguments.
	args := &C.govpp_memif_conn_args_t{}
	// - socket file name
	if config.SocketFilename != "" {
		args.socket_filename = C.CString(config.SocketFilename)
		defer C.free(unsafe.Pointer(args.socket_filename))
	}
	// - interface ID
	args.interface_id = C.uint32_t(config.ConnID)
	// - interface name
	if config.IfName != "" {
		args.interface_name = C.CString(config.IfName)
		defer C.free(unsafe.Pointer(args.interface_name))
	}
	// - mode
	switch config.Mode {
	case IfModeEthernet:
		args.mode = C.MEMIF_INTERFACE_MODE_ETHERNET
	case IfModeIP:
		args.mode = C.MEMIF_INTERFACE_MODE_IP
	case IfModePuntInject:
		args.mode = C.MEMIF_INTERFACE_MODE_PUNT_INJECT
	default:
		args.mode = C.MEMIF_INTERFACE_MODE_ETHERNET
	}
	// - secret
	if config.Secret != "" {
		args.secret = C.CString(config.Secret)
		defer C.free(unsafe.Pointer(args.secret))
	}
	// - master/slave flag + number of Rx/Tx queues
	if config.IsMaster {
		args.num_s2m_rings = C.uint8_t(config.NumRxQueues)
		args.num_m2s_rings = C.uint8_t(config.NumTxQueues)
		args.is_master = C.uint8_t(1)
	} else {
		args.num_s2m_rings = C.uint8_t(config.NumTxQueues)
		args.num_m2s_rings = C.uint8_t(config.NumRxQueues)
		args.is_master = C.uint8_t(0)
	}
	// - buffer size
	args.buffer_size = C.uint16_t(config.BufferSize)
	// - log_2(ring size)
	args.log2_ring_size = C.uint8_t(config.Log2RingSize)

	// Create memif in C-libmemif.
	errCode := C.govpp_memif_create(&memif.cHandle, args, unsafe.Pointer(uintptr(memif.ifIndex)))
	err = getMemifError(int(errCode))
	if err != nil {
		return nil, err
	}

	// Register the new memif.
	context.memifs[memif.ifIndex] = memif
	context.nextMemifIndex++
	log.WithField("ifName", config.IfName).Debug("A new memif interface was created")

	return memif, nil
}

// GetInterruptChan returns a channel which is continuously being filled with
// IDs of queues with data ready to be received.
// Since there is only one interrupt signal sent for an entire burst of packets,
// an interrupt handling routine should repeatedly call RxBurst() until
// the function returns an empty slice of packets. This way it is ensured
// that there are no packets left on the queue unread when the interrupt signal
// is cleared.
// The method is thread-safe.
func (memif *Memif) GetInterruptChan() (ch <-chan uint8 /* queue ID */) {
	return memif.intCh
}

// GetQueueInterruptChan returns an empty-data channel which fires every time
// there are data to read on a given queue.
// It is only valid to call this function if memif is in the connected state.
// Channel is automatically closed when the connection goes down (but after
// the user provided callback OnDisconnect has executed).
// Since there is only one interrupt signal sent for an entire burst of packets,
// an interrupt handling routine should repeatedly call RxBurst() until
// the function returns an empty slice of packets. This way it is ensured
// that there are no packets left on the queue unread when the interrupt signal
// is cleared.
// The method is thread-safe.
func (memif *Memif) GetQueueInterruptChan(queueID uint8) (ch <-chan struct{}, err error) {
	if int(queueID) >= len(memif.queueIntCh) {
		return nil, ErrQueueID
	}
	return memif.queueIntCh[queueID], nil
}

// SetRxMode allows to switch between the interrupt and the polling mode for Rx.
// The method is thread-safe.
func (memif *Memif) SetRxMode(queueID uint8, rxMode RxMode) (err error) {
	var cRxMode C.memif_rx_mode_t
	switch rxMode {
	case RxModeInterrupt:
		cRxMode = C.MEMIF_RX_MODE_INTERRUPT
	case RxModePolling:
		cRxMode = C.MEMIF_RX_MODE_POLLING
	default:
		cRxMode = C.MEMIF_RX_MODE_INTERRUPT
	}
	errCode := C.memif_set_rx_mode(memif.cHandle, cRxMode, C.uint16_t(queueID))
	return getMemifError(int(errCode))
}

// GetDetails returns a detailed runtime information about this memif.
// The method is thread-safe.
func (memif *Memif) GetDetails() (details *MemifDetails, err error) {
	cDetails := C.govpp_memif_details_t{}
	var buf *C.char

	// Get memif details from C-libmemif.
	errCode := C.govpp_memif_get_details(memif.cHandle, &cDetails, &buf)
	err = getMemifError(int(errCode))
	if err != nil {
		return nil, err
	}
	defer C.free(unsafe.Pointer(buf))

	// Convert details from C to Go.
	details = &MemifDetails{}
	// - metadata:
	details.IfName = C.GoString(cDetails.if_name)
	details.InstanceName = C.GoString(cDetails.inst_name)
	details.ConnID = uint32(cDetails.id)
	details.SocketFilename = C.GoString(cDetails.socket_filename)
	if cDetails.secret != nil {
		details.Secret = C.GoString(cDetails.secret)
	}
	details.IsMaster = cDetails.role == C.uint8_t(0)
	switch cDetails.mode {
	case C.MEMIF_INTERFACE_MODE_ETHERNET:
		details.Mode = IfModeEthernet
	case C.MEMIF_INTERFACE_MODE_IP:
		details.Mode = IfModeIP
	case C.MEMIF_INTERFACE_MODE_PUNT_INJECT:
		details.Mode = IfModePuntInject
	default:
		details.Mode = IfModeEthernet
	}
	// - connection details:
	details.RemoteIfName = C.GoString(cDetails.remote_if_name)
	details.RemoteInstanceName = C.GoString(cDetails.remote_inst_name)
	details.HasLink = cDetails.link_up_down == C.uint8_t(1)
	// - RX queues:
	var i uint8
	for i = 0; i < uint8(cDetails.rx_queues_num); i++ {
		cRxQueue := C.govpp_get_rx_queue_details(&cDetails, C.int(i))
		queueDetails := MemifQueueDetails{
			QueueID:    uint8(cRxQueue.qid),
			RingSize:   uint32(cRxQueue.ring_size),
			BufferSize: uint16(cRxQueue.buffer_size),
		}
		details.RxQueues = append(details.RxQueues, queueDetails)
	}
	// - TX queues:
	for i = 0; i < uint8(cDetails.tx_queues_num); i++ {
		cTxQueue := C.govpp_get_tx_queue_details(&cDetails, C.int(i))
		queueDetails := MemifQueueDetails{
			QueueID:    uint8(cTxQueue.qid),
			RingSize:   uint32(cTxQueue.ring_size),
			BufferSize: uint16(cTxQueue.buffer_size),
		}
		details.TxQueues = append(details.TxQueues, queueDetails)
	}

	return details, nil
}

// TxBurst is used to send multiple packets in one call into a selected queue.
// The actual number of packets sent may be smaller and is returned as <count>.
// The method is non-blocking even if the ring is full and no packet can be sent.
// It is only valid to call this function if memif is in the connected state.
// Multiple TxBurst-s can run concurrently provided that each targets a different
// TX queue.
func (memif *Memif) TxBurst(queueID uint8, packets []RawPacketData) (count uint16, err error) {
	var sentCount C.uint16_t
	var allocated C.uint16_t
	var bufSize int

	if len(packets) == 0 {
		return 0, nil
	}

	if int(queueID) >= len(memif.txQueueBufs) {
		return 0, ErrQueueID
	}

	// The largest packet in the set determines the packet buffer size.
	for _, packet := range packets {
		if len(packet) > int(bufSize) {
			bufSize = len(packet)
		}
	}

	// Reallocate Tx buffers if needed to fit the input packets.
	pb := memif.txQueueBufs[queueID]
	bufCount := len(packets)
	if pb.count < bufCount {
		newBuffers := C.realloc(unsafe.Pointer(pb.buffers), C.size_t(bufCount*int(C.sizeof_memif_buffer_t)))
		if newBuffers == nil {
			// Realloc failed, <count> will be less than len(packets).
			bufCount = pb.count
		} else {
			pb.buffers = (*C.memif_buffer_t)(newBuffers)
			pb.count = bufCount
		}
	}

	// Allocate ring slots.
	cQueueID := C.uint16_t(queueID)
	errCode := C.memif_buffer_alloc(memif.cHandle, cQueueID, pb.buffers, C.uint16_t(bufCount),
		&allocated, C.uint32_t(bufSize))
	err = getMemifError(int(errCode))
	if err == ErrNoBufRing {
		// Not enough ring slots, <count> will be less than bufCount.
		err = nil
	}
	if err != nil {
		return 0, err
	}

	// Copy packet data into the buffers.
	for i := 0; i < int(allocated); i++ {
		packetData := unsafe.Pointer(&packets[i][0])
		C.govpp_copy_packet_data(pb.buffers, C.int(i), packetData, C.uint16_t(len(packets[i])))
	}

	errCode = C.memif_tx_burst(memif.cHandle, cQueueID, pb.buffers, allocated, &sentCount)
	err = getMemifError(int(errCode))
	if err != nil {
		return 0, err
	}
	count = uint16(sentCount)

	return count, nil
}

// RxBurst is used to receive multiple packets in one call from a selected queue.
// <count> is the number of packets to receive. The actual number of packets
// received may be smaller. <count> effectively limits the maximum number
// of packets to receive in one burst (for a flat, predictable memory usage).
// The method is non-blocking even if there are no packets to receive.
// It is only valid to call this function if memif is in the connected state.
// Multiple RxBurst-s can run concurrently provided that each targets a different
// Rx queue.
func (memif *Memif) RxBurst(queueID uint8, count uint16) (packets []RawPacketData, err error) {
	var recvCount C.uint16_t

	if count == 0 {
		return packets, nil
	}

	if int(queueID) >= len(memif.rxQueueBufs) {
		return packets, ErrQueueID
	}

	// Reallocate Rx buffers if needed to fit the output packets.
	pb := memif.rxQueueBufs[queueID]
	bufCount := int(count)
	if pb.count < bufCount {
		newBuffers := C.realloc(unsafe.Pointer(pb.buffers), C.size_t(bufCount*int(C.sizeof_memif_buffer_t)))
		if newBuffers == nil {
			// Realloc failed, len(<packets>) will be certainly less than <count>.
			bufCount = pb.count
		} else {
			pb.buffers = (*C.memif_buffer_t)(newBuffers)
			pb.count = bufCount
		}
	}

	cQueueID := C.uint16_t(queueID)
	errCode := C.memif_rx_burst(memif.cHandle, cQueueID, pb.buffers, C.uint16_t(bufCount), &recvCount)
	err = getMemifError(int(errCode))
	if err == ErrNoBuf {
		// More packets to read - the user is expected to run RxBurst() until there
		// are no more packets to receive.
		err = nil
	}
	if err != nil {
		return packets, err
	}

	// Copy packet data into the instances of RawPacketData.
	for i := 0; i < int(recvCount); i++ {
		var packetSize C.int
		packetData := C.govpp_get_packet_data(pb.buffers, C.int(i), &packetSize)
		packets = append(packets, C.GoBytes(packetData, packetSize))
	}

	if recvCount > 0 {
		errCode = C.memif_refill_queue(memif.cHandle, cQueueID, recvCount, 0)
	}
	err = getMemifError(int(errCode))
	if err != nil {
		// Throw away packets to avoid duplicities.
		packets = nil
	}

	return packets, err
}

// Close removes the memif interface. If the memif is in the connected state,
// the connection is first properly closed.
// Do not access memif after it is closed, let garbage collector to remove it.
func (memif *Memif) Close() error {
	log.WithField("ifName", memif.IfName).Debug("Closing the memif interface")

	// Delete memif from C-libmemif.
	err := getMemifError(int(C.memif_delete(&memif.cHandle)))

	if err != nil {
		// Close memif-global interrupt channel.
		close(memif.intCh)
		// Close file descriptor stopQPollFd.
		C.close(C.int(memif.stopQPollFd))
	}

	context.lock.Lock()
	defer context.lock.Unlock()
	// Unregister the interface from the context.
	delete(context.memifs, memif.ifIndex)
	log.WithField("ifName", memif.IfName).Debug("memif interface was closed")

	return err
}

// initQueues allocates resources associated with Rx/Tx queues.
func (memif *Memif) initQueues() error {
	// Get Rx/Tx queues count.
	details, err := memif.GetDetails()
	if err != nil {
		return err
	}

	log.WithFields(logger.Fields{
		"ifName":   memif.IfName,
		"Rx-count": len(details.RxQueues),
		"Tx-count": len(details.TxQueues),
	}).Debug("Initializing Rx/Tx queues.")

	// Initialize interrupt channels.
	var i int
	for i = 0; i < len(details.RxQueues); i++ {
		queueIntCh := make(chan struct{}, 1)
		memif.queueIntCh = append(memif.queueIntCh, queueIntCh)
	}

	// Initialize Rx/Tx packet buffers.
	for i = 0; i < len(details.RxQueues); i++ {
		memif.rxQueueBufs = append(memif.rxQueueBufs, CPacketBuffers{})
		if !memif.IsMaster {
			errCode := C.memif_refill_queue(memif.cHandle, C.uint16_t(i), C.uint16_t(memif.ringSize-1), 0)
			err = getMemifError(int(errCode))
			if err != nil {
				log.Warn(err.Error())
			}
		}
	}
	for i = 0; i < len(details.TxQueues); i++ {
		memif.txQueueBufs = append(memif.txQueueBufs, CPacketBuffers{})
	}

	return nil
}

// closeQueues deallocates all resources associated with Rx/Tx queues.
func (memif *Memif) closeQueues() {
	log.WithFields(logger.Fields{
		"ifName":   memif.IfName,
		"Rx-count": len(memif.rxQueueBufs),
		"Tx-count": len(memif.txQueueBufs),
	}).Debug("Closing Rx/Tx queues.")

	// Close interrupt channels.
	for _, ch := range memif.queueIntCh {
		close(ch)
	}
	memif.queueIntCh = nil

	// Deallocate Rx/Tx packet buffers.
	for _, pb := range memif.rxQueueBufs {
		C.free(unsafe.Pointer(pb.buffers))
	}
	memif.rxQueueBufs = nil
	for _, pb := range memif.txQueueBufs {
		C.free(unsafe.Pointer(pb.buffers))
	}
	memif.txQueueBufs = nil
}

// pollEvents repeatedly polls for a libmemif event.
func pollEvents() {
	defer context.wg.Done()
	for {
		errCode := C.memif_poll_event(C.int(-1))
		err := getMemifError(int(errCode))
		if err == ErrPollCanceled {
			return
		}
	}
}

// pollRxQueue repeatedly polls an Rx queue for interrupts.
func pollRxQueue(memif *Memif, queueID uint8) {
	defer memif.wg.Done()

	log.WithFields(logger.Fields{
		"ifName":   memif.IfName,
		"queue-ID": queueID,
	}).Debug("Started queue interrupt polling.")

	var qfd C.int
	errCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)
	err := getMemifError(int(errCode))
	if err != nil {
		log.WithField("err", err).Error("memif_get_queue_efd() failed")
		return
	}

	// Create epoll file descriptor.
	var event [1]syscall.EpollEvent
	epFd, err := syscall.EpollCreate1(0)
	if err != nil {
		log.WithField("err", err).Error("epoll_create1() failed")
		return
	}
	defer syscall.Close(epFd)

	// Add Rx queue interrupt file descriptor.
	event[0].Events = syscall.EPOLLIN
	event[0].Fd = int32(qfd)
	if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {
		log.WithField("err", err).Error("epoll_ctl() failed")
		return
	}

	// Add file descriptor used to stop this go routine.
	event[0].Events = syscall.EPOLLIN
	event[0].Fd = int32(memif.stopQPollFd)
	if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {
		log.WithField("err", err).Error("epoll_ctl() failed")
		return
	}

	// Poll for interrupts.
	for {
		_, err := syscall.EpollWait(epFd, event[:], -1)
		if err != nil {
			log.WithField("err", err).Error("epoll_wait() failed")
			return
		}

		// Handle Rx Interrupt.
		if event[0].Fd == int32(qfd) {
			// Consume the interrupt event.
			buf := make([]byte, 8)
			_, err = syscall.Read(int(qfd), buf[:])
			if err != nil {
				log.WithField("err", err).Warn("read() failed")
			}

			// Send signal to memif-global interrupt channel.
			select {
			case memif.intCh <- queueID:
				break
			default:
				break
			}

			// Send signal to queue-specific interrupt channel.
			select {
			case memif.queueIntCh[queueID] <- struct{}{}:
				break
			default:
				break
			}
		}

		// Stop the go routine if requested.
		if event[0].Fd == int32(memif.stopQPollFd) {
			log.WithFields(logger.Fields{
				"ifName":   memif.IfName,
				"queue-ID": queueID,
			}).Debug("Stopped queue interrupt polling.")
			return
		}
	}
}

//export go_on_connect_callback
func go_on_connect_callback(privateCtx unsafe.Pointer) C.int {
	log.Debug("go_on_connect_callback BEGIN")
	defer log.Debug("go_on_connect_callback END")
	context.lock.RLock()
	defer context.lock.RUnlock()

	// Get memif reference.
	ifIndex := int(uintptr(privateCtx))
	memif, exists := context.memifs[ifIndex]
	if !exists {
		return C.int(ErrNoConn.Code())
	}

	// Initialize Rx/Tx queues.
	err := memif.initQueues()
	if err != nil {
		if memifErr, ok := err.(*MemifError); ok {
			return C.int(memifErr.Code())
		}
		return C.int(ErrUnknown.Code())
	}

	// Call the user callback.
	if memif.callbacks.OnConnect != nil {
		memif.callbacks.OnConnect(memif)
	}

	// Start polling the RX queues for interrupts.
	for i := 0; i < len(memif.queueIntCh); i++ {
		memif.wg.Add(1)
		go pollRxQueue(memif, uint8(i))
	}

	return C.int(0)
}

//export go_on_disconnect_callback
func go_on_disconnect_callback(privateCtx unsafe.Pointer) C.int {
	log.Debug("go_on_disconnect_callback BEGIN")
	defer log.Debug("go_on_disconnect_callback END")
	context.lock.RLock()
	defer context.lock.RUnlock()

	// Get memif reference.
	ifIndex := int(uintptr(privateCtx))
	memif, exists := context.memifs[ifIndex]
	if !exists {
		// Already closed.
		return C.int(0)
	}

	// Stop polling the RX queues for interrupts.
	buf := make([]byte, 8)
	binary.PutUvarint(buf, 1)
	// - add an event
	_, err := syscall.Write(memif.stopQPollFd, buf[:])
	if err != nil {
		return C.int(ErrSyscall.Code())
	}
	// - wait
	memif.wg.Wait()
	// - remove the event
	_, err = syscall.Read(memif.stopQPollFd, buf[:])
	if err != nil {
		return C.int(ErrSyscall.Code())
	}

	// Call the user callback.
	if memif.callbacks.OnDisconnect != nil {
		memif.callbacks.OnDisconnect(memif)
	}

	// Close Rx/Tx queues.
	memif.closeQueues()

	return C.int(0)
}