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 with splitting when necessary
199 govpp_copy_packet_data(memif_buffer_t *buffers, uint16_t allocated, int bufIndex, void *packetData, uint16_t packetSize)
204 buffers[bufIndex].len = (packetSize > buffers[bufIndex].len ? buffers[bufIndex].len : packetSize);
205 void * curData = (packetData + dataOffset);
206 memcpy(buffers[bufIndex].data, curData, (size_t)buffers[bufIndex].len);
207 dataOffset += buffers[bufIndex].len;
209 packetSize -= buffers[bufIndex].len;
210 } while(packetSize > 0 && bufIndex < allocated && buffers[bufIndex].flags & MEMIF_BUFFER_FLAG_NEXT > 0);
213 // Get packet data from the selected buffer.
214 // Used to avoid an ugly unsafe.Pointer() + unsafe.Sizeof().
216 govpp_get_packet_data(memif_buffer_t *buffers, int index, int *size)
218 *size = (int)buffers[index].len;
219 return buffers[index].data;
222 // Checks if memif buffer is chained
224 govpp_is_buffer_chained(memif_buffer_t *buffers, int index)
226 return buffers[index].flags & MEMIF_BUFFER_FLAG_NEXT;
229 // Allocate memif buffers and return pointer to next free buffer
231 govpp_memif_buffer_alloc(memif_conn_handle_t conn, uint16_t qid,
232 memif_buffer_t * bufs, uint16_t offset, memif_buffer_t ** nextFreeBuf,
233 uint16_t count, uint16_t * count_out, uint16_t size)
235 memif_buffer_t * offsetBufs = (bufs + offset);
236 int err = memif_buffer_alloc(conn, qid, offsetBufs, count, count_out, size);
237 *count_out += offset;
238 *nextFreeBuf = offsetBufs;
245 // IfMode represents the mode (layer/behaviour) in which the interface operates.
249 // IfModeEthernet tells memif to operate on the L2 layer.
250 IfModeEthernet IfMode = iota
252 // IfModeIP tells memif to operate on the L3 layer.
255 // IfModePuntInject tells memif to behave as Inject/Punt interface.
259 // RxMode is used to switch between polling and interrupt for RX.
263 // RxModeInterrupt tells libmemif to send interrupt signal when data are available.
264 RxModeInterrupt RxMode = iota
266 // RxModePolling means that the user needs to explicitly poll for data on RX
271 // RawPacketData represents raw packet data. libmemif doesn't care what the
272 // actual content is, it only manipulates with raw bytes.
273 type RawPacketData []byte
275 // MemifMeta is used to store a basic memif metadata needed for identification
276 // and connection establishment.
277 type MemifMeta struct {
278 // IfName is the interface name. Has to be unique across all created memifs.
279 // Interface name is truncated if needed to have no more than 32 characters.
282 // InstanceName identifies the endpoint. If omitted, the application
283 // name passed to Init() will be used instead.
284 // Instance name is truncated if needed to have no more than 32 characters.
287 // ConnID is a connection ID used to match opposite sides of the memif
291 // SocketFilename is the filename of the AF_UNIX socket through which
292 // the connection is established.
293 // The string is truncated if neede to fit into sockaddr_un.sun_path
294 // (108 characters on Linux).
295 SocketFilename string
297 // Secret must be the same on both sides for the authentication to succeed.
298 // Empty string is allowed.
299 // The secret is truncated if needed to have no more than 24 characters.
302 // IsMaster is set to true if memif operates in the Master mode.
305 // Mode is the mode (layer/behaviour) in which the memif operates.
309 // MemifShmSpecs is used to store the specification of the shared memory segment
310 // used by memif to send/receive packets.
311 type MemifShmSpecs struct {
312 // NumRxQueues is the number of Rx queues.
313 // Default is 1 (used if the value is 0).
316 // NumTxQueues is the number of Tx queues.
317 // Default is 1 (used if the value is 0).
320 // BufferSize is the size of the buffer to hold one packet, or a single
321 // fragment of a jumbo frame. Default is 2048 (used if the value is 0).
324 // Log2RingSize is the number of items in the ring represented through
325 // the logarithm base 2.
326 // Default is 10 (used if the value is 0).
330 // MemifConfig is the memif configuration.
331 // Used as the input argument to CreateInterface().
332 // It is the slave's config that mostly decides the parameters of the connection,
333 // but master may limit some of the quantities if needed (based on the memif
334 // protocol or master's configuration)
335 type MemifConfig struct {
340 // ConnUpdateCallback is a callback type declaration used with callbacks
341 // related to connection status changes.
342 type ConnUpdateCallback func(memif *Memif) (err error)
344 // MemifCallbacks is a container for all callbacks provided by memif.
345 // Any callback can be nil, in which case it will be simply skipped.
346 // Important: Do not call CreateInterface() or Memif.Close() from within a callback
347 // or a deadlock will occur. Instead send signal through a channel to another
348 // go routine which will be able to create/remove memif interface(s).
349 type MemifCallbacks struct {
350 // OnConnect is triggered when a connection for a given memif was established.
351 OnConnect ConnUpdateCallback
353 // OnDisconnect is triggered when a connection for a given memif was lost.
354 OnDisconnect ConnUpdateCallback
357 // Memif represents a single memif interface. It provides methods to send/receive
358 // packets in bursts in either the polling mode or in the interrupt mode with
359 // the help of golang channels.
363 // Per-library references
364 ifIndex int // index used in the Go-libmemif context (Context.memifs)
365 cHandle C.memif_conn_handle_t // handle used in C-libmemif
368 callbacks *MemifCallbacks
371 intCh chan uint8 // memif-global interrupt channel (value = queue ID)
372 queueIntCh []chan struct{} // per RX queue interrupt channel
375 ringSize int // number of items in each ring
376 bufferSize int // max buffer size
377 stopQPollFd int // event file descriptor used to stop pollRxQueue-s
378 wg sync.WaitGroup // wait group for all pollRxQueue-s
379 rxQueueBufs []CPacketBuffers // an array of C-libmemif packet buffers for each RX queue
380 txQueueBufs []CPacketBuffers // an array of C-libmemif packet buffers for each TX queue
383 // MemifDetails provides a detailed runtime information about a memif interface.
384 type MemifDetails struct {
389 // MemifConnDetails provides a detailed runtime information about a memif
391 type MemifConnDetails struct {
392 // RemoteIfName is the name of the memif on the opposite side.
394 // RemoteInstanceName is the name of the endpoint on the opposite side.
395 RemoteInstanceName string
396 // HasLink is true if the connection has link (= is established and functional).
398 // RxQueues contains details for each Rx queue.
399 RxQueues []MemifQueueDetails
400 // TxQueues contains details for each Tx queue.
401 TxQueues []MemifQueueDetails
404 // MemifQueueDetails provides a detailed runtime information about a memif queue.
405 // Queue = Ring + the associated buffers (one directional).
406 type MemifQueueDetails struct {
407 // QueueID is the ID of the queue.
409 // RingSize is the number of slots in the ring (not logarithmic).
411 // BufferSize is the size of each buffer pointed to from the ring slots.
413 /* Further ring information TO-BE-ADDED when C-libmemif supports them. */
416 // CPacketBuffers stores an array of memif buffers for use with TxBurst or RxBurst.
417 type CPacketBuffers struct {
418 buffers *C.memif_buffer_t
420 rxChainBuf []RawPacketData
423 // Context is a global Go-libmemif runtime context.
424 type Context struct {
427 memifs map[int] /* ifIndex */ *Memif /* slice of all active memif interfaces */
430 wg sync.WaitGroup /* wait-group for pollEvents() */
433 type txPacketBuffer struct {
434 packets []RawPacketData
439 // logger used by the adapter.
442 // Global Go-libmemif context.
443 context = &Context{initialized: false}
446 // init initializes global logger, which logs debug level messages to stdout.
450 log.Level = logger.DebugLevel
453 // SetLogger changes the logger for Go-libmemif to the provided one.
454 // The logger is not used for logging of C-libmemif.
455 func SetLogger(l *logger.Logger) {
459 // Init initializes the libmemif library. Must by called exactly once and before
460 // any libmemif functions. Do not forget to call Cleanup() before exiting
462 // <appName> should be a human-readable string identifying your application.
463 // For example, VPP returns the version information ("show version" from VPP CLI).
464 func Init(appName string) error {
466 defer context.lock.Unlock()
468 if context.initialized {
469 return ErrAlreadyInit
472 log.Debug("Initializing libmemif library")
474 // Initialize C-libmemif.
477 errCode = int(C.memif_init(nil, nil, nil, nil, nil))
479 appName := C.CString(appName)
480 defer C.free(unsafe.Pointer(appName))
481 errCode = int(C.memif_init(nil, appName, nil, nil, nil))
483 err := getMemifError(errCode)
488 // Initialize the map of memory interfaces.
489 context.memifs = make(map[int]*Memif)
491 // Start event polling.
495 context.initialized = true
496 log.Debug("libmemif library was initialized")
500 // Cleanup cleans up all the resources allocated by libmemif.
501 func Cleanup() error {
503 defer context.lock.Unlock()
505 if !context.initialized {
509 log.Debug("Closing libmemif library")
511 // Delete all active interfaces.
512 for _, memif := range context.memifs {
516 // Stop the event loop (if supported by C-libmemif).
517 errCode := C.memif_cancel_poll_event()
518 err := getMemifError(int(errCode))
520 log.Debug("Waiting for pollEvents() to stop...")
522 log.Debug("pollEvents() has stopped...")
524 log.WithField("err", err).Debug("NOT Waiting for pollEvents to stop...")
527 // Run cleanup for C-libmemif.
528 err = getMemifError(int(C.memif_cleanup()))
530 context.initialized = false
531 log.Debug("libmemif library was closed")
536 // CreateInterface creates a new memif interface with the given configuration.
537 // The same callbacks can be used with multiple memifs. The first callback input
538 // argument (*Memif) can be used to tell which memif the callback was triggered for.
539 // The method is thread-safe.
540 func CreateInterface(config *MemifConfig, callbacks *MemifCallbacks) (memif *Memif, err error) {
542 defer context.lock.Unlock()
544 if !context.initialized {
545 return nil, ErrNotInit
548 log.WithField("ifName", config.IfName).Debug("Creating a new memif interface")
550 log2RingSize := config.Log2RingSize
551 if log2RingSize == 0 {
555 bufferSize := config.BufferSize
560 // Create memif-wrapper for Go-libmemif.
562 MemifMeta: config.MemifMeta,
563 callbacks: &MemifCallbacks{},
564 ifIndex: context.nextMemifIndex,
565 ringSize: 1 << log2RingSize,
566 bufferSize: int(bufferSize),
569 // Initialize memif callbacks.
570 if callbacks != nil {
571 memif.callbacks.OnConnect = callbacks.OnConnect
572 memif.callbacks.OnDisconnect = callbacks.OnDisconnect
575 // Initialize memif-global interrupt channel.
576 memif.intCh = make(chan uint8, 1<<6)
578 // Initialize event file descriptor for stopping Rx/Tx queue polling.
579 memif.stopQPollFd = int(C.eventfd(0, C.EFD_NONBLOCK))
580 if memif.stopQPollFd < 0 {
581 return nil, ErrSyscall
584 // Initialize memif input arguments.
585 args := &C.govpp_memif_conn_args_t{}
586 // - socket file name
587 if config.SocketFilename != "" {
588 args.socket_filename = C.CString(config.SocketFilename)
589 defer C.free(unsafe.Pointer(args.socket_filename))
592 args.interface_id = C.uint32_t(config.ConnID)
594 if config.IfName != "" {
595 args.interface_name = C.CString(config.IfName)
596 defer C.free(unsafe.Pointer(args.interface_name))
601 args.mode = C.MEMIF_INTERFACE_MODE_ETHERNET
603 args.mode = C.MEMIF_INTERFACE_MODE_IP
604 case IfModePuntInject:
605 args.mode = C.MEMIF_INTERFACE_MODE_PUNT_INJECT
607 args.mode = C.MEMIF_INTERFACE_MODE_ETHERNET
610 if config.Secret != "" {
611 args.secret = C.CString(config.Secret)
612 defer C.free(unsafe.Pointer(args.secret))
614 // - master/slave flag + number of Rx/Tx queues
616 args.num_s2m_rings = C.uint8_t(config.NumRxQueues)
617 args.num_m2s_rings = C.uint8_t(config.NumTxQueues)
618 args.is_master = C.uint8_t(1)
620 args.num_s2m_rings = C.uint8_t(config.NumTxQueues)
621 args.num_m2s_rings = C.uint8_t(config.NumRxQueues)
622 args.is_master = C.uint8_t(0)
625 args.buffer_size = C.uint16_t(config.BufferSize)
626 // - log_2(ring size)
627 args.log2_ring_size = C.uint8_t(config.Log2RingSize)
629 // Create memif in C-libmemif.
630 errCode := C.govpp_memif_create(&memif.cHandle, args, unsafe.Pointer(uintptr(memif.ifIndex)))
631 err = getMemifError(int(errCode))
636 // Register the new memif.
637 context.memifs[memif.ifIndex] = memif
638 context.nextMemifIndex++
639 log.WithField("ifName", config.IfName).Debug("A new memif interface was created")
644 // GetInterruptChan returns a channel which is continuously being filled with
645 // IDs of queues with data ready to be received.
646 // Since there is only one interrupt signal sent for an entire burst of packets,
647 // an interrupt handling routine should repeatedly call RxBurst() until
648 // the function returns an empty slice of packets. This way it is ensured
649 // that there are no packets left on the queue unread when the interrupt signal
651 // The method is thread-safe.
652 func (memif *Memif) GetInterruptChan() (ch <-chan uint8 /* queue ID */) {
656 // GetQueueInterruptChan returns an empty-data channel which fires every time
657 // there are data to read on a given queue.
658 // It is only valid to call this function if memif is in the connected state.
659 // Channel is automatically closed when the connection goes down (but after
660 // the user provided callback OnDisconnect has executed).
661 // Since there is only one interrupt signal sent for an entire burst of packets,
662 // an interrupt handling routine should repeatedly call RxBurst() until
663 // the function returns an empty slice of packets. This way it is ensured
664 // that there are no packets left on the queue unread when the interrupt signal
666 // The method is thread-safe.
667 func (memif *Memif) GetQueueInterruptChan(queueID uint8) (ch <-chan struct{}, err error) {
668 if int(queueID) >= len(memif.queueIntCh) {
669 return nil, ErrQueueID
671 return memif.queueIntCh[queueID], nil
674 // SetRxMode allows to switch between the interrupt and the polling mode for Rx.
675 // The method is thread-safe.
676 func (memif *Memif) SetRxMode(queueID uint8, rxMode RxMode) (err error) {
677 var cRxMode C.memif_rx_mode_t
679 case RxModeInterrupt:
680 cRxMode = C.MEMIF_RX_MODE_INTERRUPT
682 cRxMode = C.MEMIF_RX_MODE_POLLING
684 cRxMode = C.MEMIF_RX_MODE_INTERRUPT
686 errCode := C.memif_set_rx_mode(memif.cHandle, cRxMode, C.uint16_t(queueID))
687 return getMemifError(int(errCode))
690 // GetDetails returns a detailed runtime information about this memif.
691 // The method is thread-safe.
692 func (memif *Memif) GetDetails() (details *MemifDetails, err error) {
693 cDetails := C.govpp_memif_details_t{}
696 // Get memif details from C-libmemif.
697 errCode := C.govpp_memif_get_details(memif.cHandle, &cDetails, &buf)
698 err = getMemifError(int(errCode))
702 defer C.free(unsafe.Pointer(buf))
704 // Convert details from C to Go.
705 details = &MemifDetails{}
707 details.IfName = C.GoString(cDetails.if_name)
708 details.InstanceName = C.GoString(cDetails.inst_name)
709 details.ConnID = uint32(cDetails.id)
710 details.SocketFilename = C.GoString(cDetails.socket_filename)
711 if cDetails.secret != nil {
712 details.Secret = C.GoString(cDetails.secret)
714 details.IsMaster = cDetails.role == C.uint8_t(0)
715 switch cDetails.mode {
716 case C.MEMIF_INTERFACE_MODE_ETHERNET:
717 details.Mode = IfModeEthernet
718 case C.MEMIF_INTERFACE_MODE_IP:
719 details.Mode = IfModeIP
720 case C.MEMIF_INTERFACE_MODE_PUNT_INJECT:
721 details.Mode = IfModePuntInject
723 details.Mode = IfModeEthernet
725 // - connection details:
726 details.RemoteIfName = C.GoString(cDetails.remote_if_name)
727 details.RemoteInstanceName = C.GoString(cDetails.remote_inst_name)
728 details.HasLink = cDetails.link_up_down == C.uint8_t(1)
731 for i = 0; i < uint8(cDetails.rx_queues_num); i++ {
732 cRxQueue := C.govpp_get_rx_queue_details(&cDetails, C.int(i))
733 queueDetails := MemifQueueDetails{
734 QueueID: uint8(cRxQueue.qid),
735 RingSize: uint32(cRxQueue.ring_size),
736 BufferSize: uint16(cRxQueue.buffer_size),
738 details.RxQueues = append(details.RxQueues, queueDetails)
741 for i = 0; i < uint8(cDetails.tx_queues_num); i++ {
742 cTxQueue := C.govpp_get_tx_queue_details(&cDetails, C.int(i))
743 queueDetails := MemifQueueDetails{
744 QueueID: uint8(cTxQueue.qid),
745 RingSize: uint32(cTxQueue.ring_size),
746 BufferSize: uint16(cTxQueue.buffer_size),
748 details.TxQueues = append(details.TxQueues, queueDetails)
754 // TxBurst is used to send multiple packets in one call into a selected queue.
755 // The actual number of packets sent may be smaller and is returned as <count>.
756 // The method is non-blocking even if the ring is full and no packet can be sent.
757 // It is only valid to call this function if memif is in the connected state.
758 // Multiple TxBurst-s can run concurrently provided that each targets a different
760 func (memif *Memif) TxBurst(queueID uint8, packets []RawPacketData) (count uint16, err error) {
761 if len(packets) == 0 {
765 if int(queueID) >= len(memif.txQueueBufs) {
770 var buffers []*txPacketBuffer
771 cQueueID := C.uint16_t(queueID)
773 for _, packet := range packets {
774 packetLen := len(packet)
775 log.Debugf("%v - preparing packet with len %v", cQueueID, packetLen)
777 if packetLen > memif.bufferSize {
778 // Create jumbo buffer
779 buffer := &txPacketBuffer{
781 packets: []RawPacketData{packet},
784 buffers = append(buffers, buffer)
786 // Increment bufCount by number of splits in this jumbo
787 bufCount += (buffer.size + memif.bufferSize - 1) / memif.bufferSize
789 buffersLen := len(buffers)
791 // This is very first buffer so there is no data to append to, prepare empty one
793 buffers = []*txPacketBuffer{{}}
797 lastBuffer := buffers[buffersLen-1]
799 // Last buffer is jumbo buffer, create new buffer
800 if lastBuffer.size > memif.bufferSize {
801 lastBuffer = &txPacketBuffer{}
802 buffers = append(buffers, lastBuffer)
805 // Determine buffer size by max packet size in buffer
806 if packetLen > lastBuffer.size {
807 lastBuffer.size = packetLen
810 lastBuffer.packets = append(lastBuffer.packets, packet)
815 // Reallocate Tx buffers if needed to fit the input packets.
816 log.Debugf("%v - total buffer to allocate count %v", cQueueID, bufCount)
817 pb := &memif.txQueueBufs[queueID]
818 if pb.count < bufCount {
819 newBuffers := C.realloc(unsafe.Pointer(pb.buffers), C.size_t(bufCount*int(C.sizeof_memif_buffer_t)))
820 if newBuffers == nil {
821 // Realloc failed, <count> will be less than len(packets).
824 pb.buffers = (*C.memif_buffer_t)(newBuffers)
829 // Allocate ring slots.
830 var allocated C.uint16_t
831 var subCount C.uint16_t
832 for _, buffer := range buffers {
833 packetCount := C.uint16_t(len(buffer.packets))
834 isJumbo := buffer.size > memif.bufferSize
836 log.Debugf("%v - trying to send max buff size %v, packets len %v, buffer len %v, jumbo %v",
837 cQueueID, buffer.size, len(buffer.packets), packetCount, isJumbo)
839 var nextFreeBuff *C.memif_buffer_t
840 startOffset := allocated
841 errCode := C.govpp_memif_buffer_alloc(memif.cHandle, cQueueID, pb.buffers, startOffset, &nextFreeBuff,
842 packetCount, &allocated, C.uint16_t(buffer.size))
844 err = getMemifError(int(errCode))
845 endEarly := err == ErrNoBufRing
847 // Not enough ring slots, <count> will be less than packetCount.
854 // Copy packet data into the buffers.
855 nowAllocated := allocated - startOffset
856 toFill := nowAllocated
858 // If this is not jumbo frame, only 1 packet needs to be copied each iteration
862 // Iterate over all packets and try to fill them into allocated buffers
863 // If packet is jumbo frame, continue filling to allocated buffers until no buffer is left
864 for i, packet := range buffer.packets {
865 if i >= int(nowAllocated) {
866 // There was less allocated buffers than actual packet count so exit early
870 packetData := unsafe.Pointer(&packet[0])
871 C.govpp_copy_packet_data(nextFreeBuff, toFill, C.int(i), packetData, C.uint16_t(len(packet)))
874 if isJumbo && nowAllocated > 0 {
875 // If we successfully allocated required amount of buffers for entire jumbo to be sent
876 // simply sub entire amount of jumbo frame packets and leave only 1 so sender will think
877 // it only sent 1 packet so it does not need to know anything about jumbo frames
878 subCount += nowAllocated - 1
881 // If we do not have enough buffers left to allocate, simply end here to avoid packet loss and try
882 // to handle it next burst
888 var sentCount C.uint16_t
889 errCode := C.memif_tx_burst(memif.cHandle, cQueueID, pb.buffers, allocated, &sentCount)
890 err = getMemifError(int(errCode))
895 // Prevent negative values
896 realSent := uint16(sentCount) - uint16(subCount)
897 if subCount > sentCount {
901 log.Debugf("%v - sent %v total allocated buffs %v", cQueueID, sentCount, allocated)
905 // RxBurst is used to receive multiple packets in one call from a selected queue.
906 // <count> is the number of packets to receive. The actual number of packets
907 // received may be smaller. <count> effectively limits the maximum number
908 // of packets to receive in one burst (for a flat, predictable memory usage).
909 // The method is non-blocking even if there are no packets to receive.
910 // It is only valid to call this function if memif is in the connected state.
911 // Multiple RxBurst-s can run concurrently provided that each targets a different
913 func (memif *Memif) RxBurst(queueID uint8, count uint16) (packets []RawPacketData, err error) {
914 var recvCount C.uint16_t
920 if int(queueID) >= len(memif.rxQueueBufs) {
921 return packets, ErrQueueID
924 // Reallocate Rx buffers if needed to fit the output packets.
925 pb := &memif.rxQueueBufs[queueID]
926 bufCount := int(count)
927 if pb.count < bufCount {
928 newBuffers := C.realloc(unsafe.Pointer(pb.buffers), C.size_t(bufCount*int(C.sizeof_memif_buffer_t)))
929 if newBuffers == nil {
930 // Realloc failed, len(<packets>) will be certainly less than <count>.
933 pb.buffers = (*C.memif_buffer_t)(newBuffers)
938 cQueueID := C.uint16_t(queueID)
939 errCode := C.memif_rx_burst(memif.cHandle, cQueueID, pb.buffers, C.uint16_t(bufCount), &recvCount)
940 err = getMemifError(int(errCode))
942 // More packets to read - the user is expected to run RxBurst() until there
943 // are no more packets to receive.
950 chained := len(pb.rxChainBuf) > 0
952 // We had stored data from previous burst because last buffer in previous burst was chained
953 // so we need to continue appending to this data
954 packets = pb.rxChainBuf
958 // Copy packet data into the instances of RawPacketData.
959 for i := 0; i < int(recvCount); i++ {
961 packetData := C.govpp_get_packet_data(pb.buffers, C.int(i), &packetSize)
962 packetBytes := C.GoBytes(packetData, packetSize)
965 // We have chained buffers, so start merging packet data with last read packet
966 prevPacket := packets[len(packets)-1]
967 packets[len(packets)-1] = append(prevPacket, packetBytes...)
969 packets = append(packets, packetBytes)
972 // Mark last buffer as chained based on property on current buffer so next buffers
973 // will try to append data to this one in case we got jumbo frame
974 chained = C.govpp_is_buffer_chained(pb.buffers, C.int(i)) > 0
978 errCode = C.memif_refill_queue(memif.cHandle, cQueueID, recvCount, 0)
980 err = getMemifError(int(errCode))
982 // Throw away packets to avoid duplicities.
987 // We did not had enough space to process all chained buffers to the end so simply tell
988 // reader that it should not process any packets here and save them for next burst
989 // to finish reading the buffer chain
990 pb.rxChainBuf = packets
998 // Close removes the memif interface. If the memif is in the connected state,
999 // the connection is first properly closed.
1000 // Do not access memif after it is closed, let garbage collector to remove it.
1001 func (memif *Memif) Close() error {
1002 log.WithField("ifName", memif.IfName).Debug("Closing the memif interface")
1004 // Delete memif from C-libmemif.
1005 err := getMemifError(int(C.memif_delete(&memif.cHandle)))
1008 // Close memif-global interrupt channel.
1010 // Close file descriptor stopQPollFd.
1011 C.close(C.int(memif.stopQPollFd))
1015 defer context.lock.Unlock()
1016 // Unregister the interface from the context.
1017 delete(context.memifs, memif.ifIndex)
1018 log.WithField("ifName", memif.IfName).Debug("memif interface was closed")
1023 // initQueues allocates resources associated with Rx/Tx queues.
1024 func (memif *Memif) initQueues() error {
1025 // Get Rx/Tx queues count.
1026 details, err := memif.GetDetails()
1031 log.WithFields(logger.Fields{
1032 "ifName": memif.IfName,
1033 "Rx-count": len(details.RxQueues),
1034 "Tx-count": len(details.TxQueues),
1035 }).Debug("Initializing Rx/Tx queues.")
1037 // Initialize interrupt channels.
1039 for i = 0; i < len(details.RxQueues); i++ {
1040 queueIntCh := make(chan struct{}, 1)
1041 memif.queueIntCh = append(memif.queueIntCh, queueIntCh)
1044 // Initialize Rx/Tx packet buffers.
1045 for i = 0; i < len(details.RxQueues); i++ {
1046 memif.rxQueueBufs = append(memif.rxQueueBufs, CPacketBuffers{})
1047 if !memif.IsMaster {
1048 errCode := C.memif_refill_queue(memif.cHandle, C.uint16_t(i), C.uint16_t(memif.ringSize-1), 0)
1049 err = getMemifError(int(errCode))
1051 log.Warn(err.Error())
1055 for i = 0; i < len(details.TxQueues); i++ {
1056 memif.txQueueBufs = append(memif.txQueueBufs, CPacketBuffers{})
1062 // closeQueues deallocates all resources associated with Rx/Tx queues.
1063 func (memif *Memif) closeQueues() {
1064 log.WithFields(logger.Fields{
1065 "ifName": memif.IfName,
1066 "Rx-count": len(memif.rxQueueBufs),
1067 "Tx-count": len(memif.txQueueBufs),
1068 }).Debug("Closing Rx/Tx queues.")
1070 // Close interrupt channels.
1071 for _, ch := range memif.queueIntCh {
1074 memif.queueIntCh = nil
1076 // Deallocate Rx/Tx packet buffers.
1077 for _, pb := range memif.rxQueueBufs {
1078 C.free(unsafe.Pointer(pb.buffers))
1080 memif.rxQueueBufs = nil
1081 for _, pb := range memif.txQueueBufs {
1082 C.free(unsafe.Pointer(pb.buffers))
1084 memif.txQueueBufs = nil
1087 // pollEvents repeatedly polls for a libmemif event.
1089 defer context.wg.Done()
1091 errCode := C.memif_poll_event(C.int(-1))
1092 err := getMemifError(int(errCode))
1093 if err == ErrPollCanceled {
1099 // pollRxQueue repeatedly polls an Rx queue for interrupts.
1100 func pollRxQueue(memif *Memif, queueID uint8) {
1101 defer memif.wg.Done()
1103 log.WithFields(logger.Fields{
1104 "ifName": memif.IfName,
1105 "queue-ID": queueID,
1106 }).Debug("Started queue interrupt polling.")
1109 errCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)
1110 err := getMemifError(int(errCode))
1112 log.WithField("err", err).Error("memif_get_queue_efd() failed")
1116 // Create epoll file descriptor.
1117 var event [1]syscall.EpollEvent
1118 epFd, err := syscall.EpollCreate1(0)
1120 log.WithField("err", err).Error("epoll_create1() failed")
1123 defer syscall.Close(epFd)
1125 // Add Rx queue interrupt file descriptor.
1126 event[0].Events = syscall.EPOLLIN
1127 event[0].Fd = int32(qfd)
1128 if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {
1129 log.WithField("err", err).Error("epoll_ctl() failed")
1133 // Add file descriptor used to stop this go routine.
1134 event[0].Events = syscall.EPOLLIN
1135 event[0].Fd = int32(memif.stopQPollFd)
1136 if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {
1137 log.WithField("err", err).Error("epoll_ctl() failed")
1141 // Poll for interrupts.
1143 _, err := syscall.EpollWait(epFd, event[:], -1)
1145 log.WithField("err", err).Error("epoll_wait() failed")
1149 // Handle Rx Interrupt.
1150 if event[0].Fd == int32(qfd) {
1151 // Consume the interrupt event.
1152 buf := make([]byte, 8)
1153 _, err = syscall.Read(int(qfd), buf[:])
1155 log.WithField("err", err).Warn("read() failed")
1158 // Send signal to memif-global interrupt channel.
1160 case memif.intCh <- queueID:
1166 // Send signal to queue-specific interrupt channel.
1168 case memif.queueIntCh[queueID] <- struct{}{}:
1175 // Stop the go routine if requested.
1176 if event[0].Fd == int32(memif.stopQPollFd) {
1177 log.WithFields(logger.Fields{
1178 "ifName": memif.IfName,
1179 "queue-ID": queueID,
1180 }).Debug("Stopped queue interrupt polling.")
1186 //export go_on_connect_callback
1187 func go_on_connect_callback(privateCtx unsafe.Pointer) C.int {
1188 log.Debug("go_on_connect_callback BEGIN")
1189 defer log.Debug("go_on_connect_callback END")
1190 context.lock.RLock()
1191 defer context.lock.RUnlock()
1193 // Get memif reference.
1194 ifIndex := int(uintptr(privateCtx))
1195 memif, exists := context.memifs[ifIndex]
1197 return C.int(ErrNoConn.Code())
1200 // Initialize Rx/Tx queues.
1201 err := memif.initQueues()
1203 if memifErr, ok := err.(*MemifError); ok {
1204 return C.int(memifErr.Code())
1206 return C.int(ErrUnknown.Code())
1209 // Call the user callback.
1210 if memif.callbacks.OnConnect != nil {
1211 memif.callbacks.OnConnect(memif)
1214 // Start polling the RX queues for interrupts.
1215 for i := 0; i < len(memif.queueIntCh); i++ {
1217 go pollRxQueue(memif, uint8(i))
1223 //export go_on_disconnect_callback
1224 func go_on_disconnect_callback(privateCtx unsafe.Pointer) C.int {
1225 log.Debug("go_on_disconnect_callback BEGIN")
1226 defer log.Debug("go_on_disconnect_callback END")
1227 context.lock.RLock()
1228 defer context.lock.RUnlock()
1230 // Get memif reference.
1231 ifIndex := int(uintptr(privateCtx))
1232 memif, exists := context.memifs[ifIndex]
1238 // Stop polling the RX queues for interrupts.
1239 buf := make([]byte, 8)
1240 binary.PutUvarint(buf, 1)
1242 _, err := syscall.Write(memif.stopQPollFd, buf[:])
1244 return C.int(ErrSyscall.Code())
1248 // - remove the event
1249 _, err = syscall.Read(memif.stopQPollFd, buf[:])
1251 return C.int(ErrSyscall.Code())
1254 // Call the user callback.
1255 if memif.callbacks.OnDisconnect != nil {
1256 memif.callbacks.OnDisconnect(memif)
1259 // Close Rx/Tx queues.