trex_stateless_dp_core.cpp revision 131be7a0
1/*
2 Itay Marom
3 Hanoch Haim
4 Cisco Systems, Inc.
5*/
6
7/*
8Copyright (c) 2015-2016 Cisco Systems, Inc.
9
10Licensed under the Apache License, Version 2.0 (the "License");
11you may not use this file except in compliance with the License.
12You may obtain a copy of the License at
13
14    http://www.apache.org/licenses/LICENSE-2.0
15
16Unless required by applicable law or agreed to in writing, software
17distributed under the License is distributed on an "AS IS" BASIS,
18WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19See the License for the specific language governing permissions and
20limitations under the License.
21*/
22#include "bp_sim.h"
23#include "trex_stateless_dp_core.h"
24#include "trex_stateless_messaging.h"
25#include "trex_stream.h"
26#include "trex_stream_node.h"
27#include "trex_streams_compiler.h"
28#include "mbuf.h"
29
30
31
32
33void CGenNodeStateless::cache_mbuf_array_init(){
34    m_cache_size=0;
35    m_cache_array_cnt=0;
36}
37
38
39
40void CGenNodeStateless::cache_mbuf_array_copy(CGenNodeCacheMbuf *obj,
41                                              uint16_t size){
42
43    int i;
44    cache_mbuf_array_alloc(size);
45    for (i=0; i<size; i++) {
46        cache_mbuf_array_set(i,obj->m_array[i]);
47    }
48    cache_mbuf_array_set_const_mbuf(obj->m_mbuf_const);
49}
50
51
52rte_mbuf_t ** CGenNodeStateless::cache_mbuf_array_alloc(uint16_t size){
53
54    uint32_t buf_size = CGenNodeCacheMbuf::get_object_size(size);
55    /* TBD  replace with align, zero API */
56    m_cache_mbuf = (void *)malloc(buf_size);
57    assert(m_cache_mbuf);
58    memset(m_cache_mbuf,0,buf_size);
59
60    m_flags |= SL_NODE_CONST_MBUF_CACHE_ARRAY;
61    m_cache_size=size;
62    m_cache_array_cnt=0;
63    return ((rte_mbuf_t **)m_cache_mbuf);
64}
65
66void CGenNodeStateless::cache_mbuf_array_free(){
67
68    assert(m_cache_mbuf);
69    int i;
70    for (i=0; i<(int)m_cache_size; i++) {
71        rte_mbuf_t * m=cache_mbuf_array_get((uint16_t)i);
72        assert(m);
73        rte_pktmbuf_free(m);
74    }
75
76    /* free the const */
77    rte_mbuf_t * m=cache_mbuf_array_get_const_mbuf() ;
78    if (m) {
79        rte_pktmbuf_free(m);
80    }
81
82    free(m_cache_mbuf);
83    m_cache_mbuf=0;
84}
85
86
87rte_mbuf_t * CGenNodeStateless::cache_mbuf_array_get(uint16_t index){
88
89    CGenNodeCacheMbuf *p =(CGenNodeCacheMbuf *) m_cache_mbuf;
90    return (p->m_array[index]);
91}
92
93void CGenNodeStateless::cache_mbuf_array_set_const_mbuf(rte_mbuf_t * m){
94    CGenNodeCacheMbuf *p =(CGenNodeCacheMbuf *) m_cache_mbuf;
95    p->m_mbuf_const=m;
96}
97
98rte_mbuf_t * CGenNodeStateless::cache_mbuf_array_get_const_mbuf(){
99    CGenNodeCacheMbuf *p =(CGenNodeCacheMbuf *) m_cache_mbuf;
100    return (p->m_mbuf_const);
101}
102
103
104void CGenNodeStateless::cache_mbuf_array_set(uint16_t index,
105                                             rte_mbuf_t * m){
106    CGenNodeCacheMbuf *p =(CGenNodeCacheMbuf *) m_cache_mbuf;
107    p->m_array[index]=m;
108}
109
110
111void CDpOneStream::Delete(CFlowGenListPerThread   * core){
112    assert(m_node->get_state() == CGenNodeStateless::ss_INACTIVE);
113    core->free_node((CGenNode *)m_node);
114    delete m_dp_stream;
115    m_node=0;
116    m_dp_stream=0;
117}
118
119void CDpOneStream::DeleteOnlyStream(){
120    assert(m_dp_stream);
121    delete m_dp_stream;
122    m_dp_stream=0;
123}
124
125int CGenNodeStateless::get_stream_id(){
126    if (m_state ==CGenNodeStateless::ss_FREE_RESUSE) {
127        return (-1); // not valid
128    }
129    assert(m_ref_stream_info);
130    return ((int)m_ref_stream_info->m_stream_id);
131}
132
133
134void CGenNodeStateless::DumpHeader(FILE *fd){
135    fprintf(fd," pkt_id, time, port , action , state, stream_id , stype , m-burst# , burst# \n");
136
137}
138void CGenNodeStateless::Dump(FILE *fd){
139    fprintf(fd," %2.4f, %3lu, %s,%s, %3d, %s, %3lu, %3lu  \n",
140            m_time,
141            (ulong)m_port_id,
142            "s-pkt", //action
143            get_stream_state_str(m_state ).c_str(),
144            get_stream_id(),   //stream_id
145            TrexStream::get_stream_type_str(m_stream_type).c_str(), //stype
146            (ulong)m_multi_bursts,
147            (ulong)m_single_burst
148            );
149}
150
151
152
153void CGenNodeStateless::refresh_vm_bss(){
154    if ( m_vm_flow_var ) {
155        StreamVmDp  * vm_s=m_ref_stream_info->m_vm_dp;
156        assert(vm_s);
157        memcpy(m_vm_flow_var,vm_s->get_bss(),vm_s->get_bss_size());
158
159        if ( vm_s->is_random_seed() ){
160            /* if we have random seed for this program */
161            if (m_ref_stream_info->m_random_seed) {
162                set_random_seed(m_ref_stream_info->m_random_seed);
163            }
164        }
165    }
166}
167
168
169/**
170 * this function called when stream restart after it was inactive
171 */
172void CGenNodeStateless::refresh(){
173
174    /* refill the stream info */
175    m_single_burst    = m_single_burst_refill;
176    m_multi_bursts    = m_ref_stream_info->m_num_bursts;
177    m_state           = CGenNodeStateless::ss_ACTIVE;
178
179    /* refresh init value */
180#if 0
181    /* TBD should add a JSON varible for that */
182    refresh_vm_bss();
183#endif
184}
185
186
187void CGenNodeCommand::free_command(){
188
189    assert(m_cmd);
190    m_cmd->on_node_remove();
191    delete m_cmd;
192}
193
194
195std::string CGenNodeStateless::get_stream_state_str(stream_state_t stream_state){
196    std::string res;
197
198    switch (stream_state) {
199    case CGenNodeStateless::ss_FREE_RESUSE :
200         res="FREE    ";
201        break;
202    case CGenNodeStateless::ss_INACTIVE :
203        res="INACTIVE ";
204        break;
205    case CGenNodeStateless::ss_ACTIVE :
206        res="ACTIVE   ";
207        break;
208    default:
209        res="Unknow   ";
210    };
211    return(res);
212}
213
214/*
215 * Allocate mbuf for flow stat (and latency) info sending
216 * m - Original mbuf (can be complicated mbuf data structure)
217 * fsp_head - return pointer in which the flow stat info should be filled
218 * is_const - is the given mbuf const
219 * return new mbuf structure in which the fsp_head can be written. If needed, orginal mbuf is freed.
220 */
221rte_mbuf_t * CGenNodeStateless::alloc_flow_stat_mbuf(rte_mbuf_t *m, struct flow_stat_payload_header *&fsp_head
222                                                     , bool is_const) {
223    rte_mbuf_t *m_ret = NULL, *m_lat = NULL;
224    uint16_t fsp_head_size = sizeof(struct flow_stat_payload_header);
225
226    if (is_const) {
227        // const mbuf case
228        if (rte_pktmbuf_data_len(m) > 128) {
229            m_ret = CGlobalInfo::pktmbuf_alloc_small(get_socket_id());
230            assert(m_ret);
231            // alloc mbuf just for the latency header
232            m_lat = CGlobalInfo::pktmbuf_alloc( get_socket_id(), fsp_head_size);
233            assert(m_lat);
234            fsp_head = (struct flow_stat_payload_header *)rte_pktmbuf_append(m_lat, fsp_head_size);
235            rte_pktmbuf_attach(m_ret, m);
236            rte_pktmbuf_trim(m_ret, sizeof(struct flow_stat_payload_header));
237            utl_rte_pktmbuf_add_after2(m_ret, m_lat);
238            // ref count was updated when we took the (const) mbuf, and again in rte_pktmbuf_attach
239            // so need do decrease now, to avoid leak.
240            rte_pktmbuf_refcnt_update(m, -1);
241            return m_ret;
242        } else {
243            // Short packet. Just copy all bytes.
244            m_ret = CGlobalInfo::pktmbuf_alloc( get_socket_id(), rte_pktmbuf_data_len(m) );
245            assert(m_ret);
246            char *p = rte_pktmbuf_mtod(m, char*);
247            char *p_new = rte_pktmbuf_append(m_ret, rte_pktmbuf_data_len(m));
248            memcpy(p_new , p, rte_pktmbuf_data_len(m));
249            fsp_head = (struct flow_stat_payload_header *)(p_new + rte_pktmbuf_data_len(m) - fsp_head_size);
250            rte_pktmbuf_free(m);
251            return m_ret;
252        }
253    } else {
254        // Field engine (vm)
255        if (rte_pktmbuf_is_contiguous(m)) {
256            // one, r/w mbuf
257            char *p = rte_pktmbuf_mtod(m, char*);
258            fsp_head = (struct flow_stat_payload_header *)(p + rte_pktmbuf_data_len(m) - fsp_head_size);
259            return m;
260        } else {
261            // r/w --> read only. Should do something like:
262            // Alloc indirect,. make r/w->indirect point to read_only) -> new fsp_header
263            // for the mean time, just copy the entire packet.
264            m_ret = CGlobalInfo::pktmbuf_alloc( get_socket_id(), rte_pktmbuf_pkt_len(m) );
265            assert(m_ret);
266            char *p_new = rte_pktmbuf_append(m_ret, rte_pktmbuf_pkt_len(m));
267            rte_mbuf_t *m_free = m;
268            while (m != NULL) {
269                char *p = rte_pktmbuf_mtod(m, char*);
270                memcpy(p_new, p, m->data_len);
271                p_new += m->data_len;
272                m = m->next;
273            }
274            p_new = rte_pktmbuf_mtod(m_ret, char*);
275            fsp_head = (struct flow_stat_payload_header *)(p_new + rte_pktmbuf_data_len(m_ret) - fsp_head_size);
276            rte_pktmbuf_free(m_free);
277            return m_ret;
278        }
279    }
280}
281
282// test the const case of alloc_flow_stat_mbuf. The more complicated non const case is tested in the simulation.
283bool CGenNodeStateless::alloc_flow_stat_mbuf_test_const() {
284    rte_mbuf_t *m, *m_test;
285    uint16_t sizes[2] = {64, 500};
286    uint16_t size;
287    struct flow_stat_payload_header *fsp_head;
288    char *p;
289
290    set_socket_id(0);
291    for (int test_num = 0; test_num < sizeof(sizes)/sizeof(sizes[0]); test_num++) {
292        size = sizes[test_num];
293        m = CGlobalInfo::pktmbuf_alloc(get_socket_id(), size);
294        p = rte_pktmbuf_append(m, size);
295        for (int i = 0; i < size; i++) {
296            p[i] = (char)i;
297        }
298        m_test = alloc_flow_stat_mbuf(m, fsp_head, true);
299        p = rte_pktmbuf_mtod(m_test, char*);
300        assert(rte_pktmbuf_pkt_len(m_test) == size);
301        for (int i = 0; i < rte_pktmbuf_pkt_len(m_test) - sizeof(*fsp_head); i++) {
302            assert(p[i] == (char)i);
303        }
304        // verify fsp_head points correctly
305        if (size > 128) { // should match threshould in alloc_flow_stat_mbuf
306            assert(rte_pktmbuf_data_len(m_test) == size - sizeof(*fsp_head));
307            assert(rte_pktmbuf_data_len(m_test->next) == sizeof(*fsp_head));
308            assert((char *)fsp_head == rte_pktmbuf_mtod((m_test->next), char*));
309        } else {
310            assert(rte_pktmbuf_data_len(m_test) == size);
311            assert (((char *)fsp_head) + sizeof (*fsp_head) == p + rte_pktmbuf_data_len(m_test));
312        }
313        rte_pktmbuf_free(m_test);
314    }
315    return true;
316}
317
318rte_mbuf_t   * CGenNodeStateless::alloc_node_with_vm(){
319
320    rte_mbuf_t        * m;
321    /* alloc small packet buffer*/
322    uint16_t prefix_size = prefix_header_size();
323    m = CGlobalInfo::pktmbuf_alloc( get_socket_id(), prefix_size );
324    if (m==0) {
325        return (m);
326    }
327    /* TBD remove this, should handle cases of error */
328    assert(m);
329    char *p=rte_pktmbuf_append(m, prefix_size);
330    memcpy( p ,m_original_packet_data_prefix, prefix_size);
331
332
333    /* run the VM program */
334    StreamDPVmInstructionsRunner runner;
335
336    runner.run( (uint32_t*)m_vm_flow_var,
337                m_vm_program_size,
338                m_vm_program,
339                m_vm_flow_var,
340                (uint8_t*)p);
341
342    uint16_t pkt_new_size=runner.get_new_pkt_size();
343    if ( likely( pkt_new_size == 0) ) {
344        /* no packet size change */
345        rte_mbuf_t * m_const = get_const_mbuf();
346        if (  m_const != NULL) {
347            utl_rte_pktmbuf_add_after(m,m_const);
348        }
349        return (m);
350    }
351
352    /* packet size change there are a few changes */
353    rte_mbuf_t * m_const = get_const_mbuf();
354    if ( (m_const == 0 ) || (pkt_new_size<=prefix_size) ) {
355        /* one mbuf , just trim it */
356        m->data_len = pkt_new_size;
357        m->pkt_len  = pkt_new_size;
358        return (m);
359    }
360
361    rte_mbuf_t * mi= CGlobalInfo::pktmbuf_alloc_small(get_socket_id());
362    assert(mi);
363    rte_pktmbuf_attach(mi,m_const);
364    utl_rte_pktmbuf_add_after2(m,mi);
365
366    if ( pkt_new_size < m->pkt_len) {
367        /* need to trim it */
368        mi->data_len = (pkt_new_size - prefix_size);
369        m->pkt_len   = pkt_new_size;
370    }
371    return (m);
372}
373
374void CGenNodeStateless::free_stl_vm_buf(){
375        rte_mbuf_t * m ;
376         m=get_const_mbuf();
377         if (m) {
378             rte_pktmbuf_free(m); /* reduce the ref counter */
379             /* clear the const marker */
380             clear_const_mbuf();
381         }
382
383         free_prefix_header();
384
385         if (m_vm_flow_var) {
386             /* free flow var */
387             free(m_vm_flow_var);
388             m_vm_flow_var=0;
389         }
390}
391
392
393
394void CGenNodeStateless::free_stl_node(){
395
396    if ( is_cache_mbuf_array() ){
397        /* do we have cache of mbuf pre allocated */
398        cache_mbuf_array_free();
399    }else{
400        /* if we have cache mbuf free it */
401        rte_mbuf_t * m=get_cache_mbuf();
402        if (m) {
403                rte_pktmbuf_free(m);
404                m_cache_mbuf=0;
405        }
406    }
407    free_stl_vm_buf();
408}
409
410
411bool TrexStatelessDpPerPort::update_number_of_active_streams(uint32_t d){
412    m_active_streams-=d; /* reduce the number of streams */
413    if (m_active_streams == 0) {
414        return (true);
415    }
416    return (false);
417}
418
419bool TrexStatelessDpPerPort::resume_traffic(uint8_t port_id){
420
421    /* we are working with continues streams so we must be in transmit mode */
422    assert(m_state == TrexStatelessDpPerPort::ppSTATE_PAUSE);
423
424    for (auto dp_stream : m_active_nodes) {
425        CGenNodeStateless * node =dp_stream.m_node;
426        assert(node->get_port_id() == port_id);
427        assert(node->is_pause() == true);
428        node->set_pause(false);
429    }
430    m_state = TrexStatelessDpPerPort::ppSTATE_TRANSMITTING;
431    return (true);
432}
433
434bool TrexStatelessDpPerPort::update_traffic(uint8_t port_id, double factor) {
435
436    assert( (m_state == TrexStatelessDpPerPort::ppSTATE_TRANSMITTING ||
437            (m_state == TrexStatelessDpPerPort::ppSTATE_PAUSE)) );
438
439    for (auto dp_stream : m_active_nodes) {
440        CGenNodeStateless * node = dp_stream.m_node;
441        assert(node->get_port_id() == port_id);
442
443        node->update_rate(factor);
444    }
445
446    return (true);
447}
448
449bool TrexStatelessDpPerPort::pause_traffic(uint8_t port_id){
450
451    /* we are working with continues streams so we must be in transmit mode */
452    assert(m_state == TrexStatelessDpPerPort::ppSTATE_TRANSMITTING);
453
454    for (auto dp_stream : m_active_nodes) {
455        CGenNodeStateless * node =dp_stream.m_node;
456        assert(node->get_port_id() == port_id);
457        assert(node->is_pause() == false);
458        node->set_pause(true);
459    }
460    m_state = TrexStatelessDpPerPort::ppSTATE_PAUSE;
461    return (true);
462}
463
464bool TrexStatelessDpPerPort::push_pcap(uint8_t port_id,
465                                       const std::string &pcap_filename,
466                                       double ipg_usec,
467                                       double speedup,
468                                       uint32_t count) {
469
470    /* push pcap can only happen on an idle port from the core prespective */
471    assert(m_state == TrexStatelessDpPerPort::ppSTATE_IDLE);
472
473    CGenNodePCAP *pcap_node = m_core->allocate_pcap_node();
474    if (!pcap_node) {
475        return (false);
476    }
477
478    pkt_dir_t dir          = m_core->m_node_gen.m_v_if->port_id_to_dir(port_id);
479    socket_id_t socket_id  = m_core->m_node_gen.m_socket_id;
480
481    uint8_t mac_addr[12];
482    m_core->m_node_gen.m_v_if->update_mac_addr_from_global_cfg(dir, mac_addr);
483
484    bool rc = pcap_node->create(port_id,
485                                dir,
486                                socket_id,
487                                mac_addr,
488                                pcap_filename,
489                                ipg_usec,
490                                speedup,
491                                count);
492    if (!rc) {
493        m_core->free_node((CGenNode *)pcap_node);
494        return (false);
495    }
496
497    /* schedule the node for now */
498    pcap_node->m_time = m_core->m_cur_time_sec;
499    m_core->m_node_gen.add_node((CGenNode *)pcap_node);
500
501    /* hold a pointer to the node */
502    assert(m_active_pcap_node == NULL);
503    m_active_pcap_node = pcap_node;
504
505    m_state = TrexStatelessDpPerPort::ppSTATE_PCAP_TX;
506    return (true);
507}
508
509
510bool TrexStatelessDpPerPort::stop_traffic(uint8_t  port_id,
511                                          bool     stop_on_id,
512                                          int      event_id){
513
514
515    if (m_state == TrexStatelessDpPerPort::ppSTATE_IDLE) {
516        assert(m_active_streams==0);
517        return false;
518    }
519
520    /* there could be race of stop after stop */
521    if ( stop_on_id ) {
522        if (event_id != m_event_id){
523            /* we can't stop it is an old message */
524            return false;
525        }
526    }
527
528    for (auto dp_stream : m_active_nodes) {
529        CGenNodeStateless * node =dp_stream.m_node;
530        assert(node->get_port_id() == port_id);
531        if ( node->get_state() == CGenNodeStateless::ss_ACTIVE) {
532            node->mark_for_free();
533            m_active_streams--;
534            dp_stream.DeleteOnlyStream();
535
536        }else{
537            dp_stream.Delete(m_core);
538        }
539    }
540
541    /* check for active PCAP node */
542    if (m_active_pcap_node) {
543        /* when got async stop from outside or duration */
544        if (m_active_pcap_node->is_active()) {
545            m_active_pcap_node->mark_for_free();
546        } else {
547            /* graceful stop - node was put out by the scheduler */
548            m_core->free_node( (CGenNode *)m_active_pcap_node);
549        }
550
551        m_active_pcap_node = NULL;
552    }
553
554    /* active stream should be zero */
555    assert(m_active_streams==0);
556    m_active_nodes.clear();
557    m_state=TrexStatelessDpPerPort::ppSTATE_IDLE;
558    return (true);
559}
560
561
562void TrexStatelessDpPerPort::create(CFlowGenListPerThread   *  core){
563    m_core=core;
564    m_state=TrexStatelessDpPerPort::ppSTATE_IDLE;
565    m_active_streams=0;
566    m_active_nodes.clear();
567    m_active_pcap_node = NULL;
568}
569
570
571
572void
573TrexStatelessDpCore::create(uint8_t thread_id, CFlowGenListPerThread *core) {
574    m_thread_id = thread_id;
575    m_core = core;
576    m_local_port_offset = 2*core->getDualPortId();
577
578    CMessagingManager * cp_dp = CMsgIns::Ins()->getCpDp();
579
580    m_ring_from_cp = cp_dp->getRingCpToDp(thread_id);
581    m_ring_to_cp   = cp_dp->getRingDpToCp(thread_id);
582
583    m_state = STATE_IDLE;
584
585    int i;
586    for (i=0; i<NUM_PORTS_PER_CORE; i++) {
587        m_ports[i].create(core);
588    }
589}
590
591
592/* move to the next stream, old stream move to INACTIVE */
593bool TrexStatelessDpCore::set_stateless_next_node(CGenNodeStateless * cur_node,
594                                                  CGenNodeStateless * next_node){
595
596    assert(cur_node);
597    TrexStatelessDpPerPort * lp_port = get_port_db(cur_node->m_port_id);
598    bool schedule =false;
599
600    bool to_stop_port=false;
601
602    if (next_node == NULL) {
603        /* there is no next stream , reduce the number of active streams*/
604        to_stop_port = lp_port->update_number_of_active_streams(1);
605
606    }else{
607        uint8_t state=next_node->get_state();
608
609        /* can't be FREE_RESUSE */
610        assert(state != CGenNodeStateless::ss_FREE_RESUSE);
611        if (state == CGenNodeStateless::ss_INACTIVE ) {
612
613            if (cur_node->m_action_counter > 0) {
614                cur_node->m_action_counter--;
615                if (cur_node->m_action_counter==0) {
616                    to_stop_port = lp_port->update_number_of_active_streams(1);
617                }else{
618                    /* refill start info and scedule, no update in active streams  */
619                    next_node->refresh();
620                    schedule = true;
621                }
622            }else{
623                /* refill start info and scedule, no update in active streams  */
624                next_node->refresh();
625                schedule = true;
626            }
627
628        }else{
629            to_stop_port = lp_port->update_number_of_active_streams(1);
630        }
631    }
632
633    if ( to_stop_port ) {
634        /* call stop port explictly to move the state */
635        stop_traffic(cur_node->m_port_id,false,0);
636    }
637
638    return ( schedule );
639}
640
641
642
643/**
644 * in idle state loop, the processor most of the time sleeps
645 * and periodically checks for messages
646 *
647 * @author imarom (01-Nov-15)
648 */
649void
650TrexStatelessDpCore::idle_state_loop() {
651
652    const int SHORT_DELAY_MS    = 2;
653    const int LONG_DELAY_MS     = 50;
654    const int DEEP_SLEEP_LIMIT  = 2000;
655
656    int counter = 0;
657
658    while (m_state == STATE_IDLE) {
659        m_core->m_node_gen.m_v_if->flush_dp_rx_queue();
660        bool had_msg = periodic_check_for_cp_messages();
661        if (had_msg) {
662            counter = 0;
663            continue;
664        }
665
666        /* enter deep sleep only if enough time had passed */
667        if (counter < DEEP_SLEEP_LIMIT) {
668            delay(SHORT_DELAY_MS);
669            counter++;
670        } else {
671            delay(LONG_DELAY_MS);
672        }
673
674    }
675}
676
677
678
679void TrexStatelessDpCore::quit_main_loop(){
680    m_core->set_terminate_mode(true); /* mark it as terminated */
681    m_state = STATE_TERMINATE;
682    add_global_duration(0.0001);
683}
684
685
686/**
687 * scehduler runs when traffic exists
688 * it will return when no more transmitting is done on this
689 * core
690 *
691 * @author imarom (01-Nov-15)
692 */
693void
694TrexStatelessDpCore::start_scheduler() {
695    /* creates a maintenace job using the scheduler */
696    CGenNode * node_sync = m_core->create_node() ;
697    node_sync->m_type = CGenNode::FLOW_SYNC;
698    node_sync->m_time = m_core->m_cur_time_sec + SYNC_TIME_OUT;
699    m_core->m_node_gen.add_node(node_sync);
700
701    double old_offset = 0.0;
702    m_core->m_node_gen.flush_file(-1, 0.0, false, m_core, old_offset);
703    /* bail out in case of terminate */
704    if (m_state != TrexStatelessDpCore::STATE_TERMINATE) {
705        m_core->m_node_gen.close_file(m_core);
706        m_state = STATE_IDLE; /* we exit from all ports and we have nothing to do, we move to IDLE state */
707    }
708}
709
710
711void
712TrexStatelessDpCore::run_once(){
713
714    idle_state_loop();
715
716    if ( m_state == STATE_TERMINATE ){
717        return;
718    }
719
720    start_scheduler();
721}
722
723
724
725
726void
727TrexStatelessDpCore::start() {
728
729    while (true) {
730        run_once();
731
732        if ( m_core->is_terminated_by_master() ) {
733            break;
734        }
735    }
736}
737
738/* only if both port are idle we can exit */
739void
740TrexStatelessDpCore::schedule_exit(){
741
742    CGenNodeCommand *node = (CGenNodeCommand *)m_core->create_node() ;
743
744    node->m_type = CGenNode::COMMAND;
745
746    node->m_cmd = new TrexStatelessDpCanQuit();
747
748    /* make sure it will be scheduled after the current node */
749    node->m_time = m_core->m_cur_time_sec ;
750
751    m_core->m_node_gen.add_node((CGenNode *)node);
752}
753
754
755void
756TrexStatelessDpCore::add_global_duration(double duration){
757    if (duration > 0.0) {
758        CGenNode *node = m_core->create_node() ;
759
760        node->m_type = CGenNode::EXIT_SCHED;
761
762        /* make sure it will be scheduled after the current node */
763        node->m_time = m_core->m_cur_time_sec + duration ;
764
765        m_core->m_node_gen.add_node(node);
766    }
767}
768
769/* add per port exit */
770void
771TrexStatelessDpCore::add_port_duration(double duration,
772                                       uint8_t port_id,
773                                       int event_id){
774    if (duration > 0.0) {
775        CGenNodeCommand *node = (CGenNodeCommand *)m_core->create_node() ;
776
777        node->m_type = CGenNode::COMMAND;
778
779        /* make sure it will be scheduled after the current node */
780        node->m_time = m_core->m_cur_time_sec + duration ;
781
782        TrexStatelessDpStop * cmd=new TrexStatelessDpStop(port_id);
783
784
785        /* test this */
786        m_core->m_non_active_nodes++;
787        cmd->set_core_ptr(m_core);
788        cmd->set_event_id(event_id);
789        cmd->set_wait_for_event_id(true);
790
791        node->m_cmd = cmd;
792
793        m_core->m_node_gen.add_node((CGenNode *)node);
794    }
795}
796
797
798void TrexStatelessDpCore::update_mac_addr(TrexStream * stream,
799                                          CGenNodeStateless *node,
800                                          pkt_dir_t dir,
801                                          char *raw_pkt){
802    bool              ov_src = stream->get_override_src_mac_by_pkt_data();
803    TrexStream::stream_dst_mac_t  ov_dst = stream->get_override_dst_mac_mode();
804
805
806    if ( (ov_src == true) && (ov_dst == TrexStream::stPKT) ) {
807        /* nothing to do, take from the packet both */
808        return;
809    }
810
811        /* take from cfg_file */
812    if ( (ov_src == false) &&
813         (ov_dst == TrexStream::stCFG_FILE) ){
814
815          m_core->m_node_gen.m_v_if->update_mac_addr_from_global_cfg(dir,(uint8_t*)raw_pkt);
816          return;
817    }
818
819    /* save the pkt*/
820    char tmp_pkt[12];
821    memcpy(tmp_pkt,raw_pkt,12);
822
823    m_core->m_node_gen.m_v_if->update_mac_addr_from_global_cfg(dir,(uint8_t*)raw_pkt);
824
825    if ((ov_src == true) && (ov_dst == TrexStream::stCFG_FILE)) {
826        memcpy(raw_pkt+6,tmp_pkt+6,6);
827    }
828
829    if ((ov_src == false) && (ov_dst == TrexStream::stPKT)) {
830        memcpy(raw_pkt,tmp_pkt,6);
831    }
832}
833
834
835void TrexStatelessDpCore::replay_vm_into_cache(TrexStream * stream,
836                                               CGenNodeStateless *node){
837
838    uint16_t      cache_size = stream->m_cache_size;
839    assert(cache_size>0);
840    rte_mbuf_t * m=0;
841
842    uint32_t buf_size = CGenNodeCacheMbuf::get_object_size(cache_size);
843    CGenNodeCacheMbuf * p = (CGenNodeCacheMbuf *)malloc(buf_size);
844    assert(p);
845    memset(p,0,buf_size);
846
847    int i;
848    for (i=0; i<cache_size; i++) {
849        p->m_array[i] =  node->alloc_node_with_vm();
850    }
851    /* save const */
852    m=node->get_const_mbuf();
853    if (m) {
854        p->m_mbuf_const=m;
855        rte_pktmbuf_refcnt_update(m,1);
856    }
857
858    /* free all VM and const mbuf */
859    node->free_stl_vm_buf();
860
861    /* copy to local node meory */
862    node->cache_mbuf_array_copy(p,cache_size);
863
864    /* free the memory */
865    free(p);
866}
867
868
869void
870TrexStatelessDpCore::add_stream(TrexStatelessDpPerPort * lp_port,
871                                TrexStream * stream,
872                                TrexStreamsCompiledObj *comp) {
873
874    CGenNodeStateless *node = m_core->create_node_sl();
875
876    node->cache_mbuf_array_init();
877    node->m_batch_size=0;
878
879    /* add periodic */
880    node->m_cache_mbuf=0;
881    node->m_type = CGenNode::STATELESS_PKT;
882
883    node->m_action_counter = stream->m_action_count;
884
885    /* clone the stream from control plane memory to DP memory */
886    node->m_ref_stream_info = stream->clone();
887    /* no need for this memory anymore on the control plane memory */
888    stream->release_dp_object();
889
890    node->m_next_stream=0; /* will be fixed later */
891
892    if ( stream->m_self_start ){
893        /* if self start it is in active mode */
894        node->m_state =CGenNodeStateless::ss_ACTIVE;
895        lp_port->m_active_streams++;
896    }else{
897        node->m_state =CGenNodeStateless::ss_INACTIVE;
898    }
899
900    node->m_time = m_core->m_cur_time_sec + stream->get_start_delay_sec();
901
902    pkt_dir_t dir = m_core->m_node_gen.m_v_if->port_id_to_dir(stream->m_port_id);
903    node->m_flags = 0;
904    node->m_src_port =0;
905    node->m_original_packet_data_prefix = 0;
906
907    if (stream->m_rx_check.m_enabled) {
908        node->set_stat_needed();
909        uint8_t hw_id = stream->m_rx_check.m_hw_id;
910        assert (hw_id < MAX_FLOW_STATS + MAX_FLOW_STATS_PAYLOAD);
911        node->set_stat_hw_id(hw_id);
912    }
913
914    /* set socket id */
915    node->set_socket_id(m_core->m_node_gen.m_socket_id);
916
917    /* build a mbuf from a packet */
918
919    uint16_t pkt_size = stream->m_pkt.len;
920    const uint8_t *stream_pkt = stream->m_pkt.binary;
921
922    node->m_pause =0;
923    node->m_stream_type = stream->m_type;
924    node->m_next_time_offset = 1.0 / stream->get_pps();
925    node->m_null_stream = (stream->m_null_stream ? 1 : 0);
926
927    /* stateless specific fields */
928    switch ( stream->m_type ) {
929
930    case TrexStream::stCONTINUOUS :
931        node->m_single_burst=0;
932        node->m_single_burst_refill=0;
933        node->m_multi_bursts=0;
934        break;
935
936    case TrexStream::stSINGLE_BURST :
937        node->m_stream_type             = TrexStream::stMULTI_BURST;
938        node->m_single_burst            = stream->m_burst_total_pkts;
939        node->m_single_burst_refill     = stream->m_burst_total_pkts;
940        node->m_multi_bursts            = 1;  /* single burst in multi burst of 1 */
941        break;
942
943    case TrexStream::stMULTI_BURST :
944        node->m_single_burst        = stream->m_burst_total_pkts;
945        node->m_single_burst_refill = stream->m_burst_total_pkts;
946        node->m_multi_bursts        = stream->m_num_bursts;
947        break;
948    default:
949
950        assert(0);
951    };
952
953    node->m_port_id = stream->m_port_id;
954
955    /* set dir 0 or 1 client or server */
956    node->set_mbuf_cache_dir(dir);
957
958
959    if (node->m_ref_stream_info->getDpVm() == NULL) {
960        /* no VM */
961
962        node->m_vm_flow_var =  NULL;
963        node->m_vm_program  =  NULL;
964        node->m_vm_program_size =0;
965
966                /* allocate const mbuf */
967        rte_mbuf_t *m = CGlobalInfo::pktmbuf_alloc(node->get_socket_id(), pkt_size);
968        assert(m);
969
970        char *p = rte_pktmbuf_append(m, pkt_size);
971        assert(p);
972        /* copy the packet */
973        memcpy(p,stream_pkt,pkt_size);
974
975        update_mac_addr(stream,node,dir,p);
976
977        /* set the packet as a readonly */
978        node->set_cache_mbuf(m);
979
980        node->m_original_packet_data_prefix =0;
981    }else{
982
983        /* set the program */
984        TrexStream * local_mem_stream = node->m_ref_stream_info;
985
986        StreamVmDp  * lpDpVm = local_mem_stream->getDpVm();
987
988        node->m_vm_flow_var      = lpDpVm->clone_bss(); /* clone the flow var */
989        node->m_vm_program       = lpDpVm->get_program(); /* same ref to the program */
990        node->m_vm_program_size  = lpDpVm->get_program_size();
991
992
993        /* set the random seed if was set */
994        if ( lpDpVm->is_random_seed() ){
995            /* if we have random seed for this program */
996            if (stream->m_random_seed) {
997                node->set_random_seed(stream->m_random_seed);
998            }
999        }
1000
1001        /* we need to copy the object */
1002        if ( pkt_size > lpDpVm->get_prefix_size() ) {
1003            /* we need const packet */
1004            uint16_t const_pkt_size  = pkt_size - lpDpVm->get_prefix_size() ;
1005            rte_mbuf_t *m = CGlobalInfo::pktmbuf_alloc(node->get_socket_id(), const_pkt_size );
1006            assert(m);
1007
1008            char *p = rte_pktmbuf_append(m, const_pkt_size);
1009            assert(p);
1010
1011            /* copy packet data */
1012            memcpy(p,(stream_pkt + lpDpVm->get_prefix_size()),const_pkt_size);
1013
1014            node->set_const_mbuf(m);
1015        }
1016
1017
1018        if ( lpDpVm->is_pkt_size_var() ) {
1019            // mark the node as varible size
1020            node->set_var_pkt_size();
1021        }
1022
1023
1024        if (lpDpVm->get_prefix_size() > pkt_size ) {
1025            lpDpVm->set_prefix_size(pkt_size);
1026        }
1027
1028        /* copy the headr */
1029        uint16_t header_size = lpDpVm->get_prefix_size();
1030        assert(header_size);
1031        node->alloc_prefix_header(header_size);
1032        uint8_t *p=node->m_original_packet_data_prefix;
1033        assert(p);
1034
1035        memcpy(p,stream_pkt , header_size);
1036
1037        update_mac_addr(stream,node,dir,(char *)p);
1038
1039        if (stream->m_cache_size > 0 ) {
1040            /* we need to create cache of objects */
1041            replay_vm_into_cache(stream, node);
1042        }
1043    }
1044
1045
1046    CDpOneStream one_stream;
1047
1048    one_stream.m_dp_stream = node->m_ref_stream_info;
1049    one_stream.m_node =node;
1050
1051    lp_port->m_active_nodes.push_back(one_stream);
1052
1053    /* schedule only if active */
1054    if (node->m_state == CGenNodeStateless::ss_ACTIVE) {
1055        m_core->m_node_gen.add_node((CGenNode *)node);
1056    }
1057}
1058
1059void
1060TrexStatelessDpCore::start_traffic(TrexStreamsCompiledObj *obj,
1061                                   double duration,
1062                                   int event_id) {
1063
1064
1065    TrexStatelessDpPerPort * lp_port=get_port_db(obj->get_port_id());
1066    lp_port->m_active_streams = 0;
1067    lp_port->set_event_id(event_id);
1068
1069    /* update cur time */
1070    if ( CGlobalInfo::is_realtime()  ){
1071        m_core->m_cur_time_sec = now_sec() + SCHD_OFFSET_DTIME ;
1072    }
1073
1074    /* no nodes in the list */
1075    assert(lp_port->m_active_nodes.size()==0);
1076
1077    for (auto single_stream : obj->get_objects()) {
1078        /* all commands should be for the same port */
1079        assert(obj->get_port_id() == single_stream.m_stream->m_port_id);
1080        add_stream(lp_port,single_stream.m_stream,obj);
1081    }
1082
1083    uint32_t nodes = lp_port->m_active_nodes.size();
1084    /* find next stream */
1085    assert(nodes == obj->get_objects().size());
1086
1087    int cnt=0;
1088
1089    /* set the next_stream pointer  */
1090    for (auto single_stream : obj->get_objects()) {
1091
1092        if (single_stream.m_stream->is_dp_next_stream() ) {
1093            int stream_id = single_stream.m_stream->m_next_stream_id;
1094            assert(stream_id<nodes);
1095            /* point to the next stream , stream_id is fixed */
1096            lp_port->m_active_nodes[cnt].m_node->m_next_stream = lp_port->m_active_nodes[stream_id].m_node ;
1097        }
1098        cnt++;
1099    }
1100
1101    lp_port->m_state =TrexStatelessDpPerPort::ppSTATE_TRANSMITTING;
1102    m_state = TrexStatelessDpCore::STATE_TRANSMITTING;
1103
1104
1105    if ( duration > 0.0 ){
1106        add_port_duration( duration ,obj->get_port_id(),event_id );
1107    }
1108
1109}
1110
1111
1112bool TrexStatelessDpCore::are_all_ports_idle(){
1113
1114    bool res=true;
1115    int i;
1116    for (i=0; i<NUM_PORTS_PER_CORE; i++) {
1117        if ( m_ports[i].m_state != TrexStatelessDpPerPort::ppSTATE_IDLE ){
1118            res=false;
1119        }
1120    }
1121    return (res);
1122}
1123
1124
1125void
1126TrexStatelessDpCore::resume_traffic(uint8_t port_id){
1127
1128    TrexStatelessDpPerPort * lp_port = get_port_db(port_id);
1129
1130    lp_port->resume_traffic(port_id);
1131}
1132
1133
1134void
1135TrexStatelessDpCore::pause_traffic(uint8_t port_id){
1136
1137    TrexStatelessDpPerPort * lp_port = get_port_db(port_id);
1138
1139    lp_port->pause_traffic(port_id);
1140}
1141
1142void
1143TrexStatelessDpCore::push_pcap(uint8_t port_id,
1144                               int event_id,
1145                               const std::string &pcap_filename,
1146                               double ipg_usec,
1147                               double speedup,
1148                               uint32_t count,
1149                               double duration) {
1150
1151    TrexStatelessDpPerPort * lp_port = get_port_db(port_id);
1152
1153    lp_port->set_event_id(event_id);
1154
1155    /* delegate the command to the port */
1156    bool rc = lp_port->push_pcap(port_id, pcap_filename, ipg_usec, speedup, count);
1157    if (!rc) {
1158        /* report back that we stopped */
1159        CNodeRing *ring = CMsgIns::Ins()->getCpDp()->getRingDpToCp(m_core->m_thread_id);
1160        TrexStatelessDpToCpMsgBase *event_msg = new TrexDpPortEventMsg(m_core->m_thread_id,
1161                                                                       port_id,
1162                                                                       event_id,
1163                                                                       false);
1164        ring->Enqueue((CGenNode *)event_msg);
1165        return;
1166    }
1167
1168
1169    if (duration > 0.0) {
1170        add_port_duration(duration, port_id, event_id);
1171    }
1172
1173     m_state = TrexStatelessDpCore::STATE_PCAP_TX;
1174}
1175
1176void
1177TrexStatelessDpCore::update_traffic(uint8_t port_id, double factor) {
1178
1179    TrexStatelessDpPerPort * lp_port = get_port_db(port_id);
1180
1181    lp_port->update_traffic(port_id, factor);
1182}
1183
1184
1185void
1186TrexStatelessDpCore::stop_traffic(uint8_t  port_id,
1187                                  bool     stop_on_id,
1188                                  int      event_id) {
1189    /* we cannot remove nodes not from the top of the queue so
1190       for every active node - make sure next time
1191       the scheduler invokes it, it will be free */
1192
1193    TrexStatelessDpPerPort * lp_port = get_port_db(port_id);
1194    if ( lp_port->stop_traffic(port_id,stop_on_id,event_id) == false){
1195        return;
1196    }
1197
1198    /* flush the TX queue before sending done message to the CP */
1199    m_core->flush_tx_queue();
1200
1201    CNodeRing *ring = CMsgIns::Ins()->getCpDp()->getRingDpToCp(m_core->m_thread_id);
1202    TrexStatelessDpToCpMsgBase *event_msg = new TrexDpPortEventMsg(m_core->m_thread_id,
1203                                                                   port_id,
1204                                                                   lp_port->get_event_id());
1205    ring->Enqueue((CGenNode *)event_msg);
1206
1207}
1208
1209/**
1210 * handle a message from CP to DP
1211 *
1212 */
1213void
1214TrexStatelessDpCore::handle_cp_msg(TrexStatelessCpToDpMsgBase *msg) {
1215    msg->handle(this);
1216    delete msg;
1217}
1218
1219void
1220TrexStatelessDpCore::barrier(uint8_t port_id, int event_id) {
1221
1222    CNodeRing *ring = CMsgIns::Ins()->getCpDp()->getRingDpToCp(m_core->m_thread_id);
1223    TrexStatelessDpToCpMsgBase *event_msg = new TrexDpPortEventMsg(m_core->m_thread_id,
1224                                                                   port_id,
1225                                                                   event_id);
1226    ring->Enqueue((CGenNode *)event_msg);
1227}
1228
1229
1230/**
1231 * PCAP node
1232 */
1233bool CGenNodePCAP::create(uint8_t port_id,
1234                          pkt_dir_t dir,
1235                          socket_id_t socket_id,
1236                          const uint8_t *mac_addr,
1237                          const std::string &pcap_filename,
1238                          double ipg_usec,
1239                          double speedup,
1240                          uint32_t count) {
1241    std::stringstream ss;
1242
1243    m_type       = CGenNode::PCAP_PKT;
1244    m_flags      = 0;
1245    m_src_port   = 0;
1246    m_port_id    = port_id;
1247    m_count      = count;
1248
1249    /* mark this node as slow path */
1250    set_slow_path(true);
1251
1252    if (ipg_usec != -1) {
1253        /* fixed IPG */
1254        m_ipg_sec = usec_to_sec(ipg_usec / speedup);
1255        m_speedup = 0;
1256    } else {
1257        /* packet IPG */
1258        m_ipg_sec = -1;
1259        m_speedup  = speedup;
1260    }
1261
1262    /* copy MAC addr info */
1263    memcpy(m_mac_addr, mac_addr, 12);
1264
1265    /* set the dir */
1266    set_mbuf_dir(dir);
1267    set_socket_id(socket_id);
1268
1269    /* create the PCAP reader */
1270    m_reader = CCapReaderFactory::CreateReader((char *)pcap_filename.c_str(), 0, ss);
1271    if (!m_reader) {
1272        return false;
1273    }
1274
1275    m_raw_packet = new CCapPktRaw();
1276    if ( m_reader->ReadPacket(m_raw_packet) == false ){
1277        /* handle error */
1278        delete m_reader;
1279        return (false);
1280    }
1281
1282    /* this is the reference time */
1283    //m_base_time = m_raw_packet->get_time();
1284    m_last_pkt_time = m_raw_packet->get_time();
1285
1286    /* ready */
1287    m_state = PCAP_ACTIVE;
1288
1289    return true;
1290}
1291
1292/**
1293 * cleanup for PCAP node
1294 *
1295 * @author imarom (08-May-16)
1296 */
1297void CGenNodePCAP::destroy() {
1298
1299    if (m_raw_packet) {
1300        delete m_raw_packet;
1301        m_raw_packet = NULL;
1302    }
1303
1304    if (m_reader) {
1305        delete m_reader;
1306        m_reader = NULL;
1307    }
1308
1309    m_state = PCAP_INVALID;
1310}
1311
1312