1 // Copyright (c) 2017 Cisco and/or its affiliates.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 // +build !windows,!darwin
26 logger "github.com/sirupsen/logrus"
36 #include <sys/eventfd.h>
40 #ifndef MEMIF_HAVE_CANCEL_POLL_EVENT
41 // memif_cancel_poll_event that simply returns ErrUnsupported.
43 memif_cancel_poll_event ()
45 return 102; // ErrUnsupported
49 // govpp_memif_conn_args_t replaces fixed sized arrays with C-strings which
50 // are much easier to work with in cgo.
53 char *socket_filename;
55 uint8_t num_s2m_rings;
56 uint8_t num_m2s_rings;
58 uint8_t log2_ring_size;
60 uint32_t interface_id;
62 memif_interface_mode_t mode;
63 } govpp_memif_conn_args_t;
65 // govpp_memif_details_t replaces strings represented with (uint8_t *)
66 // to the standard and easy to work with in cgo: (char *)
72 char *remote_inst_name;
77 char *socket_filename;
78 uint8_t rx_queues_num;
79 uint8_t tx_queues_num;
80 memif_queue_details_t *rx_queues;
81 memif_queue_details_t *tx_queues;
83 } govpp_memif_details_t;
85 extern int go_on_connect_callback(void *privateCtx);
86 extern int go_on_disconnect_callback(void *privateCtx);
88 // Callbacks strip the connection handle away.
91 govpp_on_connect_callback(memif_conn_handle_t conn, void *private_ctx)
93 return go_on_connect_callback(private_ctx);
97 govpp_on_disconnect_callback(memif_conn_handle_t conn, void *private_ctx)
99 return go_on_disconnect_callback(private_ctx);
102 // govpp_memif_create uses govpp_memif_conn_args_t.
104 govpp_memif_create (memif_conn_handle_t *conn, govpp_memif_conn_args_t *go_args,
107 memif_conn_args_t args;
108 memset (&args, 0, sizeof (args));
109 args.socket_filename = (char *)go_args->socket_filename;
110 if (go_args->secret != NULL)
112 strncpy ((char *)args.secret, go_args->secret,
113 sizeof (args.secret) - 1);
115 args.num_s2m_rings = go_args->num_s2m_rings;
116 args.num_m2s_rings = go_args->num_m2s_rings;
117 args.buffer_size = go_args->buffer_size;
118 args.log2_ring_size = go_args->log2_ring_size;
119 args.is_master = go_args->is_master;
120 args.interface_id = go_args->interface_id;
121 if (go_args->interface_name != NULL)
123 strncpy ((char *)args.interface_name, go_args->interface_name,
124 sizeof(args.interface_name) - 1);
126 args.mode = go_args->mode;
128 return memif_create(conn, &args, govpp_on_connect_callback,
129 govpp_on_disconnect_callback, NULL,
133 // govpp_memif_get_details keeps reallocating buffer until it is large enough.
134 // The buffer is returned to be deallocated when it is no longer needed.
136 govpp_memif_get_details (memif_conn_handle_t conn, govpp_memif_details_t *govpp_md,
140 size_t buflen = 1 << 7;
141 char *buffer = NULL, *new_buffer = NULL;
142 memif_details_t md = {0};
145 // initial malloc (256 bytes) or realloc
147 new_buffer = realloc(buffer, buflen);
148 if (new_buffer == NULL)
151 return MEMIF_ERR_NOMEM;
154 // try to get details
155 rv = memif_get_details(conn, &md, buffer, buflen);
156 } while (rv == MEMIF_ERR_NOBUF_DET);
161 govpp_md->if_name = (char *)md.if_name;
162 govpp_md->inst_name = (char *)md.inst_name;
163 govpp_md->remote_if_name = (char *)md.remote_if_name;
164 govpp_md->remote_inst_name = (char *)md.remote_inst_name;
165 govpp_md->id = md.id;
166 govpp_md->secret = (char *)md.secret;
167 govpp_md->role = md.role;
168 govpp_md->mode = md.mode;
169 govpp_md->socket_filename = (char *)md.socket_filename;
170 govpp_md->rx_queues_num = md.rx_queues_num;
171 govpp_md->tx_queues_num = md.tx_queues_num;
172 govpp_md->rx_queues = md.rx_queues;
173 govpp_md->tx_queues = md.tx_queues;
174 govpp_md->link_up_down = md.link_up_down;
181 // Used to avoid cumbersome tricks that use unsafe.Pointer() + unsafe.Sizeof()
182 // or even cast C-array directly into Go-slice.
183 static memif_queue_details_t
184 govpp_get_rx_queue_details (govpp_memif_details_t *md, int index)
186 return md->rx_queues[index];
189 // Used to avoid cumbersome tricks that use unsafe.Pointer() + unsafe.Sizeof()
190 // or even cast C-array directly into Go-slice.
191 static memif_queue_details_t
192 govpp_get_tx_queue_details (govpp_memif_details_t *md, int index)
194 return md->tx_queues[index];
197 // Copy packet data into the selected buffer.
199 govpp_copy_packet_data(memif_buffer_t *buffers, int index, void *data, uint16_t size)
201 buffers[index].len = (size > buffers[index].len ? buffers[index].len : size);
202 memcpy(buffers[index].data, data, (size_t)buffers[index].len);
205 // Get packet data from the selected buffer.
206 // Used to avoid an ugly unsafe.Pointer() + unsafe.Sizeof().
208 govpp_get_packet_data(memif_buffer_t *buffers, int index, int *size)
210 *size = (int)buffers[index].len;
211 return buffers[index].data;
217 // IfMode represents the mode (layer/behaviour) in which the interface operates.
221 // IfModeEthernet tells memif to operate on the L2 layer.
222 IfModeEthernet IfMode = iota
224 // IfModeIP tells memif to operate on the L3 layer.
227 // IfModePuntInject tells memif to behave as Inject/Punt interface.
231 // RxMode is used to switch between polling and interrupt for RX.
235 // RxModeInterrupt tells libmemif to send interrupt signal when data are available.
236 RxModeInterrupt RxMode = iota
238 // RxModePolling means that the user needs to explicitly poll for data on RX
243 // RawPacketData represents raw packet data. libmemif doesn't care what the
244 // actual content is, it only manipulates with raw bytes.
245 type RawPacketData []byte
247 // MemifMeta is used to store a basic memif metadata needed for identification
248 // and connection establishment.
249 type MemifMeta struct {
250 // IfName is the interface name. Has to be unique across all created memifs.
251 // Interface name is truncated if needed to have no more than 32 characters.
254 // InstanceName identifies the endpoint. If omitted, the application
255 // name passed to Init() will be used instead.
256 // Instance name is truncated if needed to have no more than 32 characters.
259 // ConnID is a connection ID used to match opposite sides of the memif
263 // SocketFilename is the filename of the AF_UNIX socket through which
264 // the connection is established.
265 // The string is truncated if neede to fit into sockaddr_un.sun_path
266 // (108 characters on Linux).
267 SocketFilename string
269 // Secret must be the same on both sides for the authentication to succeed.
270 // Empty string is allowed.
271 // The secret is truncated if needed to have no more than 24 characters.
274 // IsMaster is set to true if memif operates in the Master mode.
277 // Mode is the mode (layer/behaviour) in which the memif operates.
281 // MemifShmSpecs is used to store the specification of the shared memory segment
282 // used by memif to send/receive packets.
283 type MemifShmSpecs struct {
284 // NumRxQueues is the number of Rx queues.
285 // Default is 1 (used if the value is 0).
288 // NumTxQueues is the number of Tx queues.
289 // Default is 1 (used if the value is 0).
292 // BufferSize is the size of the buffer to hold one packet, or a single
293 // fragment of a jumbo frame. Default is 2048 (used if the value is 0).
296 // Log2RingSize is the number of items in the ring represented through
297 // the logarithm base 2.
298 // Default is 10 (used if the value is 0).
302 // MemifConfig is the memif configuration.
303 // Used as the input argument to CreateInterface().
304 // It is the slave's config that mostly decides the parameters of the connection,
305 // but master may limit some of the quantities if needed (based on the memif
306 // protocol or master's configuration)
307 type MemifConfig struct {
312 // ConnUpdateCallback is a callback type declaration used with callbacks
313 // related to connection status changes.
314 type ConnUpdateCallback func(memif *Memif) (err error)
316 // MemifCallbacks is a container for all callbacks provided by memif.
317 // Any callback can be nil, in which case it will be simply skipped.
318 // Important: Do not call CreateInterface() or Memif.Close() from within a callback
319 // or a deadlock will occur. Instead send signal through a channel to another
320 // go routine which will be able to create/remove memif interface(s).
321 type MemifCallbacks struct {
322 // OnConnect is triggered when a connection for a given memif was established.
323 OnConnect ConnUpdateCallback
325 // OnDisconnect is triggered when a connection for a given memif was lost.
326 OnDisconnect ConnUpdateCallback
329 // Memif represents a single memif interface. It provides methods to send/receive
330 // packets in bursts in either the polling mode or in the interrupt mode with
331 // the help of golang channels.
335 // Per-library references
336 ifIndex int // index used in the Go-libmemif context (Context.memifs)
337 cHandle C.memif_conn_handle_t // handle used in C-libmemif
340 callbacks *MemifCallbacks
343 intCh chan uint8 // memif-global interrupt channel (value = queue ID)
344 queueIntCh []chan struct{} // per RX queue interrupt channel
347 ringSize int // number of items in each ring
348 stopQPollFd int // event file descriptor used to stop pollRxQueue-s
349 wg sync.WaitGroup // wait group for all pollRxQueue-s
350 rxQueueBufs []CPacketBuffers // an array of C-libmemif packet buffers for each RX queue
351 txQueueBufs []CPacketBuffers // an array of C-libmemif packet buffers for each TX queue
354 // MemifDetails provides a detailed runtime information about a memif interface.
355 type MemifDetails struct {
360 // MemifConnDetails provides a detailed runtime information about a memif
362 type MemifConnDetails struct {
363 // RemoteIfName is the name of the memif on the opposite side.
365 // RemoteInstanceName is the name of the endpoint on the opposite side.
366 RemoteInstanceName string
367 // HasLink is true if the connection has link (= is established and functional).
369 // RxQueues contains details for each Rx queue.
370 RxQueues []MemifQueueDetails
371 // TxQueues contains details for each Tx queue.
372 TxQueues []MemifQueueDetails
375 // MemifQueueDetails provides a detailed runtime information about a memif queue.
376 // Queue = Ring + the associated buffers (one directional).
377 type MemifQueueDetails struct {
378 // QueueID is the ID of the queue.
380 // RingSize is the number of slots in the ring (not logarithmic).
382 // BufferSize is the size of each buffer pointed to from the ring slots.
384 /* Further ring information TO-BE-ADDED when C-libmemif supports them. */
387 // CPacketBuffers stores an array of memif buffers for use with TxBurst or RxBurst.
388 type CPacketBuffers struct {
389 buffers *C.memif_buffer_t
393 // Context is a global Go-libmemif runtime context.
394 type Context struct {
397 memifs map[int] /* ifIndex */ *Memif /* slice of all active memif interfaces */
400 wg sync.WaitGroup /* wait-group for pollEvents() */
404 // logger used by the adapter.
407 // Global Go-libmemif context.
408 context = &Context{initialized: false}
411 // init initializes global logger, which logs debug level messages to stdout.
415 log.Level = logger.DebugLevel
418 // SetLogger changes the logger for Go-libmemif to the provided one.
419 // The logger is not used for logging of C-libmemif.
420 func SetLogger(l *logger.Logger) {
424 // Init initializes the libmemif library. Must by called exactly once and before
425 // any libmemif functions. Do not forget to call Cleanup() before exiting
427 // <appName> should be a human-readable string identifying your application.
428 // For example, VPP returns the version information ("show version" from VPP CLI).
429 func Init(appName string) error {
431 defer context.lock.Unlock()
433 if context.initialized {
434 return ErrAlreadyInit
437 log.Debug("Initializing libmemif library")
439 // Initialize C-libmemif.
442 errCode = int(C.memif_init(nil, nil, nil, nil))
444 appName := C.CString(appName)
445 defer C.free(unsafe.Pointer(appName))
446 errCode = int(C.memif_init(nil, appName, nil, nil))
448 err := getMemifError(errCode)
453 // Initialize the map of memory interfaces.
454 context.memifs = make(map[int]*Memif)
456 // Start event polling.
460 context.initialized = true
461 log.Debug("libmemif library was initialized")
465 // Cleanup cleans up all the resources allocated by libmemif.
466 func Cleanup() error {
468 defer context.lock.Unlock()
470 if !context.initialized {
474 log.Debug("Closing libmemif library")
476 // Delete all active interfaces.
477 for _, memif := range context.memifs {
481 // Stop the event loop (if supported by C-libmemif).
482 errCode := C.memif_cancel_poll_event()
483 err := getMemifError(int(errCode))
485 log.Debug("Waiting for pollEvents() to stop...")
487 log.Debug("pollEvents() has stopped...")
489 log.WithField("err", err).Debug("NOT Waiting for pollEvents to stop...")
492 // Run cleanup for C-libmemif.
493 err = getMemifError(int(C.memif_cleanup()))
495 context.initialized = false
496 log.Debug("libmemif library was closed")
501 // CreateInterface creates a new memif interface with the given configuration.
502 // The same callbacks can be used with multiple memifs. The first callback input
503 // argument (*Memif) can be used to tell which memif the callback was triggered for.
504 // The method is thread-safe.
505 func CreateInterface(config *MemifConfig, callbacks *MemifCallbacks) (memif *Memif, err error) {
507 defer context.lock.Unlock()
509 if !context.initialized {
510 return nil, ErrNotInit
513 log.WithField("ifName", config.IfName).Debug("Creating a new memif interface")
515 log2RingSize := config.Log2RingSize
516 if log2RingSize == 0 {
520 // Create memif-wrapper for Go-libmemif.
522 MemifMeta: config.MemifMeta,
523 callbacks: &MemifCallbacks{},
524 ifIndex: context.nextMemifIndex,
525 ringSize: 1 << log2RingSize,
528 // Initialize memif callbacks.
529 if callbacks != nil {
530 memif.callbacks.OnConnect = callbacks.OnConnect
531 memif.callbacks.OnDisconnect = callbacks.OnDisconnect
534 // Initialize memif-global interrupt channel.
535 memif.intCh = make(chan uint8, 1<<6)
537 // Initialize event file descriptor for stopping Rx/Tx queue polling.
538 memif.stopQPollFd = int(C.eventfd(0, C.EFD_NONBLOCK))
539 if memif.stopQPollFd < 0 {
540 return nil, ErrSyscall
543 // Initialize memif input arguments.
544 args := &C.govpp_memif_conn_args_t{}
545 // - socket file name
546 if config.SocketFilename != "" {
547 args.socket_filename = C.CString(config.SocketFilename)
548 defer C.free(unsafe.Pointer(args.socket_filename))
551 args.interface_id = C.uint32_t(config.ConnID)
553 if config.IfName != "" {
554 args.interface_name = C.CString(config.IfName)
555 defer C.free(unsafe.Pointer(args.interface_name))
560 args.mode = C.MEMIF_INTERFACE_MODE_ETHERNET
562 args.mode = C.MEMIF_INTERFACE_MODE_IP
563 case IfModePuntInject:
564 args.mode = C.MEMIF_INTERFACE_MODE_PUNT_INJECT
566 args.mode = C.MEMIF_INTERFACE_MODE_ETHERNET
569 if config.Secret != "" {
570 args.secret = C.CString(config.Secret)
571 defer C.free(unsafe.Pointer(args.secret))
573 // - master/slave flag + number of Rx/Tx queues
575 args.num_s2m_rings = C.uint8_t(config.NumRxQueues)
576 args.num_m2s_rings = C.uint8_t(config.NumTxQueues)
577 args.is_master = C.uint8_t(1)
579 args.num_s2m_rings = C.uint8_t(config.NumTxQueues)
580 args.num_m2s_rings = C.uint8_t(config.NumRxQueues)
581 args.is_master = C.uint8_t(0)
584 args.buffer_size = C.uint16_t(config.BufferSize)
585 // - log_2(ring size)
586 args.log2_ring_size = C.uint8_t(config.Log2RingSize)
588 // Create memif in C-libmemif.
589 errCode := C.govpp_memif_create(&memif.cHandle, args, unsafe.Pointer(uintptr(memif.ifIndex)))
590 err = getMemifError(int(errCode))
595 // Register the new memif.
596 context.memifs[memif.ifIndex] = memif
597 context.nextMemifIndex++
598 log.WithField("ifName", config.IfName).Debug("A new memif interface was created")
603 // GetInterruptChan returns a channel which is continuously being filled with
604 // IDs of queues with data ready to be received.
605 // Since there is only one interrupt signal sent for an entire burst of packets,
606 // an interrupt handling routine should repeatedly call RxBurst() until
607 // the function returns an empty slice of packets. This way it is ensured
608 // that there are no packets left on the queue unread when the interrupt signal
610 // The method is thread-safe.
611 func (memif *Memif) GetInterruptChan() (ch <-chan uint8 /* queue ID */) {
615 // GetQueueInterruptChan returns an empty-data channel which fires every time
616 // there are data to read on a given queue.
617 // It is only valid to call this function if memif is in the connected state.
618 // Channel is automatically closed when the connection goes down (but after
619 // the user provided callback OnDisconnect has executed).
620 // Since there is only one interrupt signal sent for an entire burst of packets,
621 // an interrupt handling routine should repeatedly call RxBurst() until
622 // the function returns an empty slice of packets. This way it is ensured
623 // that there are no packets left on the queue unread when the interrupt signal
625 // The method is thread-safe.
626 func (memif *Memif) GetQueueInterruptChan(queueID uint8) (ch <-chan struct{}, err error) {
627 if int(queueID) >= len(memif.queueIntCh) {
628 return nil, ErrQueueID
630 return memif.queueIntCh[queueID], nil
633 // SetRxMode allows to switch between the interrupt and the polling mode for Rx.
634 // The method is thread-safe.
635 func (memif *Memif) SetRxMode(queueID uint8, rxMode RxMode) (err error) {
636 var cRxMode C.memif_rx_mode_t
638 case RxModeInterrupt:
639 cRxMode = C.MEMIF_RX_MODE_INTERRUPT
641 cRxMode = C.MEMIF_RX_MODE_POLLING
643 cRxMode = C.MEMIF_RX_MODE_INTERRUPT
645 errCode := C.memif_set_rx_mode(memif.cHandle, cRxMode, C.uint16_t(queueID))
646 return getMemifError(int(errCode))
649 // GetDetails returns a detailed runtime information about this memif.
650 // The method is thread-safe.
651 func (memif *Memif) GetDetails() (details *MemifDetails, err error) {
652 cDetails := C.govpp_memif_details_t{}
655 // Get memif details from C-libmemif.
656 errCode := C.govpp_memif_get_details(memif.cHandle, &cDetails, &buf)
657 err = getMemifError(int(errCode))
661 defer C.free(unsafe.Pointer(buf))
663 // Convert details from C to Go.
664 details = &MemifDetails{}
666 details.IfName = C.GoString(cDetails.if_name)
667 details.InstanceName = C.GoString(cDetails.inst_name)
668 details.ConnID = uint32(cDetails.id)
669 details.SocketFilename = C.GoString(cDetails.socket_filename)
670 if cDetails.secret != nil {
671 details.Secret = C.GoString(cDetails.secret)
673 details.IsMaster = cDetails.role == C.uint8_t(0)
674 switch cDetails.mode {
675 case C.MEMIF_INTERFACE_MODE_ETHERNET:
676 details.Mode = IfModeEthernet
677 case C.MEMIF_INTERFACE_MODE_IP:
678 details.Mode = IfModeIP
679 case C.MEMIF_INTERFACE_MODE_PUNT_INJECT:
680 details.Mode = IfModePuntInject
682 details.Mode = IfModeEthernet
684 // - connection details:
685 details.RemoteIfName = C.GoString(cDetails.remote_if_name)
686 details.RemoteInstanceName = C.GoString(cDetails.remote_inst_name)
687 details.HasLink = cDetails.link_up_down == C.uint8_t(1)
690 for i = 0; i < uint8(cDetails.rx_queues_num); i++ {
691 cRxQueue := C.govpp_get_rx_queue_details(&cDetails, C.int(i))
692 queueDetails := MemifQueueDetails{
693 QueueID: uint8(cRxQueue.qid),
694 RingSize: uint32(cRxQueue.ring_size),
695 BufferSize: uint16(cRxQueue.buffer_size),
697 details.RxQueues = append(details.RxQueues, queueDetails)
700 for i = 0; i < uint8(cDetails.tx_queues_num); i++ {
701 cTxQueue := C.govpp_get_tx_queue_details(&cDetails, C.int(i))
702 queueDetails := MemifQueueDetails{
703 QueueID: uint8(cTxQueue.qid),
704 RingSize: uint32(cTxQueue.ring_size),
705 BufferSize: uint16(cTxQueue.buffer_size),
707 details.TxQueues = append(details.TxQueues, queueDetails)
713 // TxBurst is used to send multiple packets in one call into a selected queue.
714 // The actual number of packets sent may be smaller and is returned as <count>.
715 // The method is non-blocking even if the ring is full and no packet can be sent.
716 // It is only valid to call this function if memif is in the connected state.
717 // Multiple TxBurst-s can run concurrently provided that each targets a different
719 func (memif *Memif) TxBurst(queueID uint8, packets []RawPacketData) (count uint16, err error) {
720 var sentCount C.uint16_t
721 var allocated C.uint16_t
724 if len(packets) == 0 {
728 if int(queueID) >= len(memif.txQueueBufs) {
732 // The largest packet in the set determines the packet buffer size.
733 for _, packet := range packets {
734 if len(packet) > int(bufSize) {
735 bufSize = len(packet)
739 // Reallocate Tx buffers if needed to fit the input packets.
740 pb := memif.txQueueBufs[queueID]
741 bufCount := len(packets)
742 if pb.count < bufCount {
743 newBuffers := C.realloc(unsafe.Pointer(pb.buffers), C.size_t(bufCount*int(C.sizeof_memif_buffer_t)))
744 if newBuffers == nil {
745 // Realloc failed, <count> will be less than len(packets).
748 pb.buffers = (*C.memif_buffer_t)(newBuffers)
753 // Allocate ring slots.
754 cQueueID := C.uint16_t(queueID)
755 errCode := C.memif_buffer_alloc(memif.cHandle, cQueueID, pb.buffers, C.uint16_t(bufCount),
756 &allocated, C.uint32_t(bufSize))
757 err = getMemifError(int(errCode))
758 if err == ErrNoBufRing {
759 // Not enough ring slots, <count> will be less than bufCount.
766 // Copy packet data into the buffers.
767 for i := 0; i < int(allocated); i++ {
768 packetData := unsafe.Pointer(&packets[i][0])
769 C.govpp_copy_packet_data(pb.buffers, C.int(i), packetData, C.uint16_t(len(packets[i])))
772 errCode = C.memif_tx_burst(memif.cHandle, cQueueID, pb.buffers, allocated, &sentCount)
773 err = getMemifError(int(errCode))
777 count = uint16(sentCount)
782 // RxBurst is used to receive multiple packets in one call from a selected queue.
783 // <count> is the number of packets to receive. The actual number of packets
784 // received may be smaller. <count> effectively limits the maximum number
785 // of packets to receive in one burst (for a flat, predictable memory usage).
786 // The method is non-blocking even if there are no packets to receive.
787 // It is only valid to call this function if memif is in the connected state.
788 // Multiple RxBurst-s can run concurrently provided that each targets a different
790 func (memif *Memif) RxBurst(queueID uint8, count uint16) (packets []RawPacketData, err error) {
791 var recvCount C.uint16_t
797 if int(queueID) >= len(memif.rxQueueBufs) {
798 return packets, ErrQueueID
801 // Reallocate Rx buffers if needed to fit the output packets.
802 pb := memif.rxQueueBufs[queueID]
803 bufCount := int(count)
804 if pb.count < bufCount {
805 newBuffers := C.realloc(unsafe.Pointer(pb.buffers), C.size_t(bufCount*int(C.sizeof_memif_buffer_t)))
806 if newBuffers == nil {
807 // Realloc failed, len(<packets>) will be certainly less than <count>.
810 pb.buffers = (*C.memif_buffer_t)(newBuffers)
815 cQueueID := C.uint16_t(queueID)
816 errCode := C.memif_rx_burst(memif.cHandle, cQueueID, pb.buffers, C.uint16_t(bufCount), &recvCount)
817 err = getMemifError(int(errCode))
819 // More packets to read - the user is expected to run RxBurst() until there
820 // are no more packets to receive.
827 // Copy packet data into the instances of RawPacketData.
828 for i := 0; i < int(recvCount); i++ {
830 packetData := C.govpp_get_packet_data(pb.buffers, C.int(i), &packetSize)
831 packets = append(packets, C.GoBytes(packetData, packetSize))
835 errCode = C.memif_refill_queue(memif.cHandle, cQueueID, recvCount, 0)
837 err = getMemifError(int(errCode))
839 // Throw away packets to avoid duplicities.
846 // Close removes the memif interface. If the memif is in the connected state,
847 // the connection is first properly closed.
848 // Do not access memif after it is closed, let garbage collector to remove it.
849 func (memif *Memif) Close() error {
850 log.WithField("ifName", memif.IfName).Debug("Closing the memif interface")
852 // Delete memif from C-libmemif.
853 err := getMemifError(int(C.memif_delete(&memif.cHandle)))
856 // Close memif-global interrupt channel.
858 // Close file descriptor stopQPollFd.
859 C.close(C.int(memif.stopQPollFd))
863 defer context.lock.Unlock()
864 // Unregister the interface from the context.
865 delete(context.memifs, memif.ifIndex)
866 log.WithField("ifName", memif.IfName).Debug("memif interface was closed")
871 // initQueues allocates resources associated with Rx/Tx queues.
872 func (memif *Memif) initQueues() error {
873 // Get Rx/Tx queues count.
874 details, err := memif.GetDetails()
879 log.WithFields(logger.Fields{
880 "ifName": memif.IfName,
881 "Rx-count": len(details.RxQueues),
882 "Tx-count": len(details.TxQueues),
883 }).Debug("Initializing Rx/Tx queues.")
885 // Initialize interrupt channels.
887 for i = 0; i < len(details.RxQueues); i++ {
888 queueIntCh := make(chan struct{}, 1)
889 memif.queueIntCh = append(memif.queueIntCh, queueIntCh)
892 // Initialize Rx/Tx packet buffers.
893 for i = 0; i < len(details.RxQueues); i++ {
894 memif.rxQueueBufs = append(memif.rxQueueBufs, CPacketBuffers{})
896 errCode := C.memif_refill_queue(memif.cHandle, C.uint16_t(i), C.uint16_t(memif.ringSize-1), 0)
897 err = getMemifError(int(errCode))
899 log.Warn(err.Error())
903 for i = 0; i < len(details.TxQueues); i++ {
904 memif.txQueueBufs = append(memif.txQueueBufs, CPacketBuffers{})
910 // closeQueues deallocates all resources associated with Rx/Tx queues.
911 func (memif *Memif) closeQueues() {
912 log.WithFields(logger.Fields{
913 "ifName": memif.IfName,
914 "Rx-count": len(memif.rxQueueBufs),
915 "Tx-count": len(memif.txQueueBufs),
916 }).Debug("Closing Rx/Tx queues.")
918 // Close interrupt channels.
919 for _, ch := range memif.queueIntCh {
922 memif.queueIntCh = nil
924 // Deallocate Rx/Tx packet buffers.
925 for _, pb := range memif.rxQueueBufs {
926 C.free(unsafe.Pointer(pb.buffers))
928 memif.rxQueueBufs = nil
929 for _, pb := range memif.txQueueBufs {
930 C.free(unsafe.Pointer(pb.buffers))
932 memif.txQueueBufs = nil
935 // pollEvents repeatedly polls for a libmemif event.
937 defer context.wg.Done()
939 errCode := C.memif_poll_event(C.int(-1))
940 err := getMemifError(int(errCode))
941 if err == ErrPollCanceled {
947 // pollRxQueue repeatedly polls an Rx queue for interrupts.
948 func pollRxQueue(memif *Memif, queueID uint8) {
949 defer memif.wg.Done()
951 log.WithFields(logger.Fields{
952 "ifName": memif.IfName,
954 }).Debug("Started queue interrupt polling.")
957 errCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)
958 err := getMemifError(int(errCode))
960 log.WithField("err", err).Error("memif_get_queue_efd() failed")
964 // Create epoll file descriptor.
965 var event [1]syscall.EpollEvent
966 epFd, err := syscall.EpollCreate1(0)
968 log.WithField("err", err).Error("epoll_create1() failed")
971 defer syscall.Close(epFd)
973 // Add Rx queue interrupt file descriptor.
974 event[0].Events = syscall.EPOLLIN
975 event[0].Fd = int32(qfd)
976 if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {
977 log.WithField("err", err).Error("epoll_ctl() failed")
981 // Add file descriptor used to stop this go routine.
982 event[0].Events = syscall.EPOLLIN
983 event[0].Fd = int32(memif.stopQPollFd)
984 if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {
985 log.WithField("err", err).Error("epoll_ctl() failed")
989 // Poll for interrupts.
991 _, err := syscall.EpollWait(epFd, event[:], -1)
993 log.WithField("err", err).Error("epoll_wait() failed")
997 // Handle Rx Interrupt.
998 if event[0].Fd == int32(qfd) {
999 // Consume the interrupt event.
1000 buf := make([]byte, 8)
1001 _, err = syscall.Read(int(qfd), buf[:])
1003 log.WithField("err", err).Warn("read() failed")
1006 // Send signal to memif-global interrupt channel.
1008 case memif.intCh <- queueID:
1014 // Send signal to queue-specific interrupt channel.
1016 case memif.queueIntCh[queueID] <- struct{}{}:
1023 // Stop the go routine if requested.
1024 if event[0].Fd == int32(memif.stopQPollFd) {
1025 log.WithFields(logger.Fields{
1026 "ifName": memif.IfName,
1027 "queue-ID": queueID,
1028 }).Debug("Stopped queue interrupt polling.")
1034 //export go_on_connect_callback
1035 func go_on_connect_callback(privateCtx unsafe.Pointer) C.int {
1036 log.Debug("go_on_connect_callback BEGIN")
1037 defer log.Debug("go_on_connect_callback END")
1038 context.lock.RLock()
1039 defer context.lock.RUnlock()
1041 // Get memif reference.
1042 ifIndex := int(uintptr(privateCtx))
1043 memif, exists := context.memifs[ifIndex]
1045 return C.int(ErrNoConn.Code())
1048 // Initialize Rx/Tx queues.
1049 err := memif.initQueues()
1051 if memifErr, ok := err.(*MemifError); ok {
1052 return C.int(memifErr.Code())
1054 return C.int(ErrUnknown.Code())
1057 // Call the user callback.
1058 if memif.callbacks.OnConnect != nil {
1059 memif.callbacks.OnConnect(memif)
1062 // Start polling the RX queues for interrupts.
1063 for i := 0; i < len(memif.queueIntCh); i++ {
1065 go pollRxQueue(memif, uint8(i))
1071 //export go_on_disconnect_callback
1072 func go_on_disconnect_callback(privateCtx unsafe.Pointer) C.int {
1073 log.Debug("go_on_disconnect_callback BEGIN")
1074 defer log.Debug("go_on_disconnect_callback END")
1075 context.lock.RLock()
1076 defer context.lock.RUnlock()
1078 // Get memif reference.
1079 ifIndex := int(uintptr(privateCtx))
1080 memif, exists := context.memifs[ifIndex]
1086 // Stop polling the RX queues for interrupts.
1087 buf := make([]byte, 8)
1088 binary.PutUvarint(buf, 1)
1090 _, err := syscall.Write(memif.stopQPollFd, buf[:])
1092 return C.int(ErrSyscall.Code())
1096 // - remove the event
1097 _, err = syscall.Read(memif.stopQPollFd, buf[:])
1099 return C.int(ErrSyscall.Code())
1102 // Call the user callback.
1103 if memif.callbacks.OnDisconnect != nil {
1104 memif.callbacks.OnDisconnect(memif)
1107 // Close Rx/Tx queues.