2 *------------------------------------------------------------------
5 * Copyright (c) 2009 Cisco and/or its affiliates.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at:
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *------------------------------------------------------------------
24 #include <sys/types.h>
29 #include <vppinfra/vec.h>
30 #include <vppinfra/hash.h>
31 #include <vppinfra/pool.h>
32 #include <vppinfra/format.h>
33 #include <vppinfra/byte_order.h>
34 #include <vppinfra/elog.h>
36 #include <vlib/vlib.h>
37 #include <vlib/unix/unix.h>
38 #include <vlibapi/api.h>
39 #include <vlibmemory/api.h>
43 * @brief Binary API messaging via shared memory
44 * Low-level, primary provisioning interface
46 /*? %%clicmd:group_label Binary API CLI %% ?*/
47 /*? %%syscfg:group_label Binary API configuration %% ?*/
49 #define TRACE_VLIB_MEMORY_QUEUE 0
51 #include <vlibmemory/vl_memory_msg_enum.h> /* enumerate all vlib messages */
53 #define vl_typedefs /* define message structures */
54 #include <vlibmemory/vl_memory_api_h.h>
57 /* instantiate all the print functions we know about */
58 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
60 #include <vlibmemory/vl_memory_api_h.h>
64 vl_api_memclnt_create_t_print (vl_api_memclnt_create_t * a, void *handle)
66 vl_print (handle, "vl_api_memclnt_create_t:\n");
67 vl_print (handle, "name: %s\n", a->name);
68 vl_print (handle, "input_queue: 0x%wx\n", a->input_queue);
69 vl_print (handle, "context: %u\n", (unsigned) a->context);
70 vl_print (handle, "ctx_quota: %ld\n", (long) a->ctx_quota);
75 vl_api_memclnt_delete_t_print (vl_api_memclnt_delete_t * a, void *handle)
77 vl_print (handle, "vl_api_memclnt_delete_t:\n");
78 vl_print (handle, "index: %u\n", (unsigned) a->index);
79 vl_print (handle, "handle: 0x%wx\n", a->handle);
84 vl_api_trace_plugin_msg_ids_t_print (vl_api_trace_plugin_msg_ids_t * a,
87 vl_print (handle, "vl_api_trace_plugin_msg_ids: %s first %u last %u\n",
89 clib_host_to_net_u16 (a->first_msg_id),
90 clib_host_to_net_u16 (a->last_msg_id));
94 /* instantiate all the endian swap functions we know about */
96 #include <vlibmemory/vl_memory_api_h.h>
99 extern void vl_socket_api_send (vl_api_registration_t * rp, u8 * elem);
102 vl_msg_api_send (vl_api_registration_t * rp, u8 * elem)
104 if (PREDICT_FALSE (rp->registration_type > REGISTRATION_TYPE_SHMEM))
106 vl_socket_api_send (rp, elem);
110 vl_msg_api_send_shmem (rp->vl_input_queue, (u8 *) & elem);
115 vl_api_serialize_message_table (api_main_t * am, u8 * vector)
117 serialize_main_t _sm, *sm = &_sm;
119 u32 nmsg = hash_elts (am->msg_index_by_name_and_crc);
121 serialize_open_vector (sm, vector);
123 /* serialize the count */
124 serialize_integer (sm, nmsg, sizeof (u32));
127 hash_foreach_pair (hp, am->msg_index_by_name_and_crc,
129 serialize_likely_small_unsigned_integer (sm, hp->value[0]);
130 serialize_cstring (sm, (char *) hp->key);
134 return serialize_close_vector (sm);
138 * vl_api_memclnt_create_internal
142 vl_api_memclnt_create_internal (char *name, unix_shared_memory_queue_t * q)
144 vl_api_registration_t **regpp;
145 vl_api_registration_t *regp;
148 api_main_t *am = &api_main;
150 ASSERT (vlib_get_thread_index () == 0);
151 pool_get (am->vl_clients, regpp);
155 pthread_mutex_lock (&svm->mutex);
156 oldheap = svm_push_data_heap (svm);
157 *regpp = clib_mem_alloc (sizeof (vl_api_registration_t));
160 memset (regp, 0, sizeof (*regp));
161 regp->registration_type = REGISTRATION_TYPE_SHMEM;
162 regp->vl_api_registration_pool_index = regpp - am->vl_clients;
164 regp->shmem_hdr = am->shmem_hdr;
166 regp->vl_input_queue = q;
167 regp->name = format (0, "%s%c", name, 0);
169 pthread_mutex_unlock (&svm->mutex);
170 svm_pop_heap (oldheap);
171 return vl_msg_api_handle_from_index_and_epoch
172 (regp->vl_api_registration_pool_index,
173 am->shmem_hdr->application_restarts);
178 * vl_api_memclnt_create_t_handler
181 vl_api_memclnt_create_t_handler (vl_api_memclnt_create_t * mp)
183 vl_api_registration_t **regpp;
184 vl_api_registration_t *regp;
185 vl_api_memclnt_create_reply_t *rp;
187 unix_shared_memory_queue_t *q;
190 api_main_t *am = &api_main;
193 * This is tortured. Maintain a vlib-address-space private
194 * pool of client registrations. We use the shared-memory virtual
195 * address of client structure as a handle, to allow direct
196 * manipulation of context quota vbls from the client library.
198 * This scheme causes trouble w/ API message trace replay, since
199 * some random VA from clib_mem_alloc() certainly won't
200 * occur in the Linux sim. The (very) few places
201 * that care need to use the pool index.
203 * Putting the registration object(s) into a pool in shared memory and
204 * using the pool index as a handle seems like a great idea.
205 * Unfortunately, each and every reference to that pool would need
206 * to be protected by a mutex:
210 * convert pool index to
218 pool_get (am->vl_clients, regpp);
222 pthread_mutex_lock (&svm->mutex);
223 oldheap = svm_push_data_heap (svm);
224 *regpp = clib_mem_alloc (sizeof (vl_api_registration_t));
227 memset (regp, 0, sizeof (*regp));
228 regp->registration_type = REGISTRATION_TYPE_SHMEM;
229 regp->vl_api_registration_pool_index = regpp - am->vl_clients;
231 regp->shmem_hdr = am->shmem_hdr;
233 q = regp->vl_input_queue = (unix_shared_memory_queue_t *) (uword)
236 regp->name = format (0, "%s", mp->name);
237 vec_add1 (regp->name, 0);
239 if (am->serialized_message_table_in_shmem == 0)
240 am->serialized_message_table_in_shmem =
241 vl_api_serialize_message_table (am, 0);
243 pthread_mutex_unlock (&svm->mutex);
244 svm_pop_heap (oldheap);
246 rp = vl_msg_api_alloc (sizeof (*rp));
247 rp->_vl_msg_id = ntohs (VL_API_MEMCLNT_CREATE_REPLY);
248 rp->handle = (uword) regp;
249 rp->index = vl_msg_api_handle_from_index_and_epoch
250 (regp->vl_api_registration_pool_index,
251 am->shmem_hdr->application_restarts);
252 rp->context = mp->context;
253 rp->response = ntohl (rv);
255 pointer_to_uword (am->serialized_message_table_in_shmem);
257 vl_msg_api_send_shmem (q, (u8 *) & rp);
261 call_reaper_functions (u32 client_index)
263 clib_error_t *error = 0;
264 _vl_msg_api_function_list_elt_t *i;
266 i = api_main.reaper_function_registrations;
269 error = i->f (client_index);
271 clib_error_report (error);
272 i = i->next_init_function;
278 * vl_api_memclnt_delete_t_handler
281 vl_api_memclnt_delete_t_handler (vl_api_memclnt_delete_t * mp)
283 vl_api_registration_t **regpp;
284 vl_api_registration_t *regp;
285 vl_api_memclnt_delete_reply_t *rp;
288 api_main_t *am = &api_main;
289 u32 handle, client_index, epoch;
293 if (call_reaper_functions (handle))
296 epoch = vl_msg_api_handle_get_epoch (handle);
297 client_index = vl_msg_api_handle_get_index (handle);
299 if (epoch != (am->shmem_hdr->application_restarts & VL_API_EPOCH_MASK))
302 ("Stale clnt delete index %d old epoch %d cur epoch %d",
304 (am->shmem_hdr->application_restarts & VL_API_EPOCH_MASK));
308 regpp = am->vl_clients + client_index;
310 if (!pool_is_free (am->vl_clients, regpp))
315 int private_registration = 0;
318 * Note: the API message handling path will set am->vlib_rp
319 * as appropriate for pairwise / private memory segments
321 rp = vl_msg_api_alloc (sizeof (*rp));
322 rp->_vl_msg_id = ntohs (VL_API_MEMCLNT_DELETE_REPLY);
323 rp->handle = mp->handle;
326 vl_msg_api_send_shmem (regp->vl_input_queue, (u8 *) & rp);
328 if (client_index != regp->vl_api_registration_pool_index)
330 clib_warning ("mismatch client_index %d pool_index %d",
331 client_index, regp->vl_api_registration_pool_index);
332 vl_msg_api_free (rp);
336 /* For horizontal scaling, add a hash table... */
337 for (i = 0; i < vec_len (am->vlib_private_rps); i++)
339 /* Is this a pairwise / private API segment? */
340 if (am->vlib_private_rps[i] == svm)
342 /* Note: account for the memfd header page */
343 u64 virtual_base = svm->virtual_base - MMAP_PAGESIZE;
344 u64 virtual_size = svm->virtual_size + MMAP_PAGESIZE;
347 * Kill the registration pool element before we make
348 * the index vanish forever
350 pool_put_index (am->vl_clients,
351 regp->vl_api_registration_pool_index);
353 vec_delete (am->vlib_private_rps, 1, i);
354 /* Kill it, accounting for the memfd header page */
355 if (munmap ((void *) virtual_base, virtual_size) < 0)
356 clib_unix_warning ("munmap");
357 /* Reset the queue-length-address cache */
358 vec_reset_length (vl_api_queue_cursizes);
359 private_registration = 1;
364 /* No dangling references, please */
367 if (private_registration == 0)
369 pool_put_index (am->vl_clients,
370 regp->vl_api_registration_pool_index);
371 pthread_mutex_lock (&svm->mutex);
372 oldheap = svm_push_data_heap (svm);
373 /* Poison the old registration */
374 memset (regp, 0xF1, sizeof (*regp));
375 clib_mem_free (regp);
376 pthread_mutex_unlock (&svm->mutex);
377 svm_pop_heap (oldheap);
379 * These messages must be freed manually, since they're set up
380 * as "bounce" messages. In the private_registration == 1 case,
381 * we kill the shared-memory segment which contains the message
384 vl_msg_api_free (mp);
389 clib_warning ("unknown client ID %d", mp->index);
394 vl_api_get_first_msg_id_t_handler (vl_api_get_first_msg_id_t * mp)
396 vl_api_get_first_msg_id_reply_t *rmp;
397 unix_shared_memory_queue_t *q;
399 api_main_t *am = &api_main;
400 vl_api_msg_range_t *rp;
402 u16 first_msg_id = ~0;
403 int rv = -7; /* VNET_API_ERROR_INVALID_VALUE */
405 q = vl_api_client_index_to_input_queue (mp->client_index);
409 if (am->msg_range_by_name == 0)
412 strncpy ((char *) name, (char *) mp->name, ARRAY_LEN (name) - 1);
414 p = hash_get_mem (am->msg_range_by_name, name);
418 rp = vec_elt_at_index (am->msg_ranges, p[0]);
420 first_msg_id = rp->first_msg_id;
425 rmp = vl_msg_api_alloc (sizeof (*rmp));
426 rmp->_vl_msg_id = ntohs (VL_API_GET_FIRST_MSG_ID_REPLY);
427 rmp->context = mp->context;
428 rmp->retval = ntohl (rv);
429 rmp->first_msg_id = ntohs (first_msg_id);
430 vl_msg_api_send_shmem (q, (u8 *) & rmp);
434 * client answered a ping, stave off the grim reaper...
438 vl_api_memclnt_keepalive_reply_t_handler
439 (vl_api_memclnt_keepalive_reply_t * mp)
441 vl_api_registration_t *regp;
442 vlib_main_t *vm = vlib_get_main ();
444 regp = vl_api_client_index_to_registration (mp->context);
447 regp->last_heard = vlib_time_now (vm);
448 regp->unanswered_pings = 0;
451 clib_warning ("BUG: anonymous memclnt_keepalive_reply");
455 * We can send ourselves these messages if someone uses the
456 * builtin binary api test tool...
459 vl_api_memclnt_keepalive_t_handler (vl_api_memclnt_keepalive_t * mp)
461 vl_api_memclnt_keepalive_reply_t *rmp;
463 vl_shmem_hdr_t *shmem_hdr;
466 shmem_hdr = am->shmem_hdr;
468 rmp = vl_msg_api_alloc_as_if_client (sizeof (*rmp));
469 memset (rmp, 0, sizeof (*rmp));
470 rmp->_vl_msg_id = ntohs (VL_API_MEMCLNT_KEEPALIVE_REPLY);
471 rmp->context = mp->context;
472 vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *) & rmp);
476 vl_api_api_versions_t_handler (vl_api_api_versions_t * mp)
478 api_main_t *am = &api_main;
479 vl_api_api_versions_reply_t *rmp;
480 unix_shared_memory_queue_t *q;
481 u32 nmsg = vec_len (am->api_version_list);
482 int msg_size = sizeof (*rmp) + sizeof (rmp->api_versions[0]) * nmsg;
485 q = vl_api_client_index_to_input_queue (mp->client_index);
489 rmp = vl_msg_api_alloc (msg_size);
490 memset (rmp, 0, msg_size);
491 rmp->_vl_msg_id = ntohs (VL_API_API_VERSIONS_REPLY);
493 /* fill in the message */
494 rmp->context = mp->context;
495 rmp->count = htonl (nmsg);
497 for (i = 0; i < nmsg; ++i)
499 api_version_t *vl = &am->api_version_list[i];
500 rmp->api_versions[i].major = htonl (vl->major);
501 rmp->api_versions[i].minor = htonl (vl->minor);
502 rmp->api_versions[i].patch = htonl (vl->patch);
503 strncpy ((char *) rmp->api_versions[i].name, vl->name, 64 - 1);
506 vl_msg_api_send_shmem (q, (u8 *) & rmp);
510 #define foreach_vlib_api_msg \
511 _(MEMCLNT_CREATE, memclnt_create) \
512 _(MEMCLNT_DELETE, memclnt_delete) \
513 _(GET_FIRST_MSG_ID, get_first_msg_id) \
514 _(MEMCLNT_KEEPALIVE, memclnt_keepalive) \
515 _(MEMCLNT_KEEPALIVE_REPLY, memclnt_keepalive_reply) \
516 _(API_VERSIONS, api_versions)
522 memory_api_init (const char *region_name)
525 api_main_t *am = &api_main;
526 vl_msg_api_msg_config_t cfg;
527 vl_msg_api_msg_config_t *c = &cfg;
529 memset (c, 0, sizeof (*c));
531 if ((rv = vl_map_shmem (region_name, 1 /* is_vlib */ )) < 0)
534 #define _(N,n) do { \
535 c->id = VL_API_##N; \
537 c->handler = vl_api_##n##_t_handler; \
538 c->cleanup = vl_noop_handler; \
539 c->endian = vl_api_##n##_t_endian; \
540 c->print = vl_api_##n##_t_print; \
541 c->size = sizeof(vl_api_##n##_t); \
542 c->traced = 1; /* trace, so these msgs print */ \
543 c->replay = 0; /* don't replay client create/delete msgs */ \
544 c->message_bounce = 0; /* don't bounce this message */ \
545 vl_msg_api_config(c);} while (0);
547 foreach_vlib_api_msg;
551 * special-case freeing of memclnt_delete messages, so we can
552 * simply munmap pairwise / private API segments...
554 am->message_bounce[VL_API_MEMCLNT_DELETE] = 1;
555 am->is_mp_safe[VL_API_MEMCLNT_KEEPALIVE_REPLY] = 1;
560 #define foreach_histogram_bucket \
568 #define _(n) SLEEP_##n##_US,
569 foreach_histogram_bucket
574 static u64 vector_rate_histogram[SLEEP_N_BUCKETS];
576 static void memclnt_queue_callback (vlib_main_t * vm);
579 * Callback to send ourselves a plugin numbering-space trace msg
582 send_one_plugin_msg_ids_msg (u8 * name, u16 first_msg_id, u16 last_msg_id)
584 vl_api_trace_plugin_msg_ids_t *mp;
585 api_main_t *am = &api_main;
586 vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
587 unix_shared_memory_queue_t *q;
589 mp = vl_msg_api_alloc_as_if_client (sizeof (*mp));
590 memset (mp, 0, sizeof (*mp));
592 mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_TRACE_PLUGIN_MSG_IDS);
593 strncpy ((char *) mp->plugin_name, (char *) name,
594 sizeof (mp->plugin_name) - 1);
595 mp->first_msg_id = clib_host_to_net_u16 (first_msg_id);
596 mp->last_msg_id = clib_host_to_net_u16 (last_msg_id);
598 q = shmem_hdr->vl_input_queue;
600 vl_msg_api_send_shmem (q, (u8 *) & mp);
604 send_memclnt_keepalive (vl_api_registration_t * regp, f64 now)
606 vl_api_memclnt_keepalive_t *mp;
607 unix_shared_memory_queue_t *q;
608 api_main_t *am = &api_main;
609 svm_region_t *save_vlib_rp = am->vlib_rp;
610 vl_shmem_hdr_t *save_shmem_hdr = am->shmem_hdr;
612 q = regp->vl_input_queue;
615 * If the queue head is moving, assume that the client is processing
616 * messages and skip the ping. This heuristic may fail if the queue
617 * is in the same position as last time, net of wrapping; in which
618 * case, the client will receive a keepalive.
620 if (regp->last_queue_head != q->head)
622 regp->last_heard = now;
623 regp->unanswered_pings = 0;
624 regp->last_queue_head = q->head;
629 * push/pop shared memory segment, so this routine
630 * will work with "normal" as well as "private segment"
634 am->vlib_rp = regp->vlib_rp;
635 am->shmem_hdr = regp->shmem_hdr;
637 mp = vl_msg_api_alloc (sizeof (*mp));
638 memset (mp, 0, sizeof (*mp));
639 mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_MEMCLNT_KEEPALIVE);
640 mp->context = mp->client_index =
641 vl_msg_api_handle_from_index_and_epoch
642 (regp->vl_api_registration_pool_index,
643 am->shmem_hdr->application_restarts);
645 regp->unanswered_pings++;
647 /* Failure-to-send due to a stuffed queue is absolutely expected */
648 if (unix_shared_memory_queue_add (q, (u8 *) & mp, 1 /* nowait */ ))
649 vl_msg_api_free (mp);
651 am->vlib_rp = save_vlib_rp;
652 am->shmem_hdr = save_shmem_hdr;
656 dead_client_scan (api_main_t * am, vl_shmem_hdr_t * shm, f64 now)
659 vl_api_registration_t **regpp;
660 vl_api_registration_t *regp;
661 static u32 *dead_indices;
662 static u32 *confused_indices;
664 vec_reset_length (dead_indices);
665 vec_reset_length (confused_indices);
668 pool_foreach (regpp, am->vl_clients,
673 /* If we haven't heard from this client recently... */
674 if (regp->last_heard < (now - 10.0))
676 if (regp->unanswered_pings == 2)
678 unix_shared_memory_queue_t *q;
679 q = regp->vl_input_queue;
680 if (kill (q->consumer_pid, 0) >=0)
682 clib_warning ("REAPER: lazy binary API client '%s'",
684 regp->unanswered_pings = 0;
685 regp->last_heard = now;
689 clib_warning ("REAPER: binary API client '%s' died",
691 vec_add1(dead_indices, regpp - am->vl_clients);
695 send_memclnt_keepalive (regp, now);
698 regp->unanswered_pings = 0;
702 clib_warning ("NULL client registration index %d",
703 regpp - am->vl_clients);
704 vec_add1 (confused_indices, regpp - am->vl_clients);
708 /* This should "never happen," but if it does, fix it... */
709 if (PREDICT_FALSE (vec_len (confused_indices) > 0))
712 for (i = 0; i < vec_len (confused_indices); i++)
714 pool_put_index (am->vl_clients, confused_indices[i]);
718 if (PREDICT_FALSE (vec_len (dead_indices) > 0))
724 /* Allow the application to clean up its registrations */
725 for (i = 0; i < vec_len (dead_indices); i++)
727 regpp = pool_elt_at_index (am->vl_clients, dead_indices[i]);
732 handle = vl_msg_api_handle_from_index_and_epoch
733 (dead_indices[i], shm->application_restarts);
734 (void) call_reaper_functions (handle);
739 pthread_mutex_lock (&svm->mutex);
740 oldheap = svm_push_data_heap (svm);
742 for (i = 0; i < vec_len (dead_indices); i++)
744 regpp = pool_elt_at_index (am->vl_clients, dead_indices[i]);
747 /* Is this a pairwise SVM segment? */
748 if ((*regpp)->vlib_rp != svm)
751 svm_region_t *dead_rp = (*regpp)->vlib_rp;
752 /* Note: account for the memfd header page */
753 u64 virtual_base = dead_rp->virtual_base - MMAP_PAGESIZE;
754 u64 virtual_size = dead_rp->virtual_size + MMAP_PAGESIZE;
756 /* For horizontal scaling, add a hash table... */
757 for (i = 0; i < vec_len (am->vlib_private_rps); i++)
758 if (am->vlib_private_rps[i] == dead_rp)
760 vec_delete (am->vlib_private_rps, 1, i);
763 clib_warning ("private rp %llx AWOL", dead_rp);
766 /* Kill it, accounting for the memfd header page */
767 if (munmap ((void *) virtual_base, virtual_size) < 0)
768 clib_unix_warning ("munmap");
769 /* Reset the queue-length-address cache */
770 vec_reset_length (vl_api_queue_cursizes);
774 /* Poison the old registration */
775 memset (*regpp, 0xF3, sizeof (**regpp));
776 clib_mem_free (*regpp);
778 /* no dangling references, please */
783 svm_pop_heap (oldheap);
784 clib_warning ("Duplicate free, client index %d",
785 regpp - am->vl_clients);
786 oldheap = svm_push_data_heap (svm);
790 svm_client_scan_this_region_nolock (am->vlib_rp);
792 pthread_mutex_unlock (&svm->mutex);
793 svm_pop_heap (oldheap);
794 for (i = 0; i < vec_len (dead_indices); i++)
795 pool_put_index (am->vl_clients, dead_indices[i]);
801 memclnt_process (vlib_main_t * vm,
802 vlib_node_runtime_t * node, vlib_frame_t * f)
806 unix_shared_memory_queue_t *q;
809 api_main_t *am = &api_main;
810 f64 dead_client_scan_time;
811 f64 sleep_time, start_time;
813 clib_error_t *socksvr_api_init (vlib_main_t * vm);
816 vl_socket_args_for_process_t *a;
818 uword *event_data = 0;
819 int private_segment_rotor = 0;
820 svm_region_t *vlib_rp;
823 vlib_set_queue_signal_callback (vm, memclnt_queue_callback);
825 if ((rv = memory_api_init (am->region_name)) < 0)
827 clib_warning ("memory_api_init returned %d, quitting...", rv);
831 if ((error = socksvr_api_init (vm)))
833 clib_error_report (error);
834 clib_warning ("socksvr_api_init failed, quitting...");
840 q = shm->vl_input_queue;
842 /* Make a note so we can always find the primary region easily */
843 am->vlib_primary_rp = am->vlib_rp;
845 e = vlib_call_init_exit_functions
846 (vm, vm->api_init_function_registrations, 1 /* call_once */ );
848 clib_error_report (e);
851 dead_client_scan_time = vlib_time_now (vm) + 10.0;
854 * Send plugin message range messages for each plugin we loaded
856 for (i = 0; i < vec_len (am->msg_ranges); i++)
858 vl_api_msg_range_t *rp = am->msg_ranges + i;
859 send_one_plugin_msg_ids_msg (rp->name, rp->first_msg_id,
864 * Save the api message table snapshot, if configured
866 if (am->save_msg_table_filename)
870 u8 *serialized_message_table;
873 * Snapshoot the api message table.
875 if (strstr ((char *) am->save_msg_table_filename, "..")
876 || index ((char *) am->save_msg_table_filename, '/'))
878 clib_warning ("illegal save-message-table filename '%s'",
879 am->save_msg_table_filename);
883 chroot_file = format (0, "/tmp/%s%c", am->save_msg_table_filename, 0);
885 fd = creat ((char *) chroot_file, 0644);
889 clib_unix_warning ("creat");
893 serialized_message_table = vl_api_serialize_message_table (am, 0);
895 rv = write (fd, serialized_message_table,
896 vec_len (serialized_message_table));
898 if (rv != vec_len (serialized_message_table))
899 clib_unix_warning ("write");
903 clib_unix_warning ("close");
905 vec_free (chroot_file);
906 vec_free (serialized_message_table);
911 /* $$$ pay attention to frame size, control CPU usage */
918 * There's a reason for checking the queue before
919 * sleeping. If the vlib application crashes, it's entirely
920 * possible for a client to enqueue a connect request
921 * during the process restart interval.
923 * Unless some force of physics causes the new incarnation
924 * of the application to process the request, the client will
925 * sit and wait for Godot...
927 vector_rate = vlib_last_vector_length_per_node (vm);
928 start_time = vlib_time_now (vm);
931 pthread_mutex_lock (&q->mutex);
934 vm->api_queue_nonempty = 0;
935 pthread_mutex_unlock (&q->mutex);
937 if (TRACE_VLIB_MEMORY_QUEUE)
940 ELOG_TYPE_DECLARE (e) =
942 .format = "q-underflow: len %d",
950 ed = ELOG_DATA (&vm->elog_main, e);
957 headp = (i8 *) (q->data + sizeof (uword) * q->head);
958 clib_memcpy (&mp, headp, sizeof (uword));
961 need_broadcast = (q->cursize == q->maxsize / 2);
964 if (PREDICT_FALSE (q->head == q->maxsize))
966 pthread_mutex_unlock (&q->mutex);
968 (void) pthread_cond_broadcast (&q->condvar);
970 vl_msg_api_handler_with_vm_node (am, (void *) mp, vm, node);
972 /* Allow no more than 10us without a pause */
973 if (vlib_time_now (vm) > start_time + 10e-6)
975 int index = SLEEP_400_US;
976 if (vector_rate > 40.0)
978 else if (vector_rate > 20.0)
980 index = SLEEP_200_US;
983 else if (vector_rate >= 1.0)
985 index = SLEEP_100_US;
993 vector_rate_histogram[index] += 1;
999 * see if we have any private api shared-memory segments
1000 * If so, push required context variables, and process
1003 if (PREDICT_FALSE (vec_len (am->vlib_private_rps)))
1005 unix_shared_memory_queue_t *save_vlib_input_queue = q;
1006 vl_shmem_hdr_t *save_shmem_hdr = am->shmem_hdr;
1007 svm_region_t *save_vlib_rp = am->vlib_rp;
1009 vlib_rp = am->vlib_rp = am->vlib_private_rps[private_segment_rotor];
1011 am->shmem_hdr = (void *) vlib_rp->user_ctx;
1012 q = am->shmem_hdr->vl_input_queue;
1014 pthread_mutex_lock (&q->mutex);
1017 headp = (i8 *) (q->data + sizeof (uword) * q->head);
1018 clib_memcpy (&mp, headp, sizeof (uword));
1021 need_broadcast = (q->cursize == q->maxsize / 2);
1024 if (PREDICT_FALSE (q->head == q->maxsize))
1026 pthread_mutex_unlock (&q->mutex);
1029 (void) pthread_cond_broadcast (&q->condvar);
1031 vl_msg_api_handler_with_vm_node (am, (void *) mp, vm, node);
1034 pthread_mutex_unlock (&q->mutex);
1036 q = save_vlib_input_queue;
1037 am->shmem_hdr = save_shmem_hdr;
1038 am->vlib_rp = save_vlib_rp;
1040 private_segment_rotor++;
1041 if (private_segment_rotor >= vec_len (am->vlib_private_rps))
1042 private_segment_rotor = 0;
1045 vlib_process_wait_for_event_or_clock (vm, sleep_time);
1046 vec_reset_length (event_data);
1047 event_type = vlib_process_get_events (vm, &event_data);
1048 now = vlib_time_now (vm);
1052 case QUEUE_SIGNAL_EVENT:
1053 vm->queue_signal_pending = 0;
1056 case SOCKET_READ_EVENT:
1057 for (i = 0; i < vec_len (event_data); i++)
1059 a = pool_elt_at_index (socket_main.process_args, event_data[i]);
1060 vl_api_socket_process_msg (a->clib_file, a->regp,
1063 pool_put (socket_main.process_args, a);
1072 clib_warning ("unknown event type %d", event_type);
1076 if (now > dead_client_scan_time)
1078 dead_client_scan (am, shm, now);
1079 dead_client_scan_time = vlib_time_now (vm) + 10.0;
1082 if (TRACE_VLIB_MEMORY_QUEUE)
1085 ELOG_TYPE_DECLARE (e) = {
1086 .format = "q-awake: len %d",
1087 .format_args = "i4",
1094 ed = ELOG_DATA (&vm->elog_main, e);
1095 ed->len = q->cursize;
1102 VLIB_REGISTER_NODE (memclnt_node) =
1104 .function = memclnt_process,
1105 .type = VLIB_NODE_TYPE_PROCESS,
1106 .name = "api-rx-from-ring",
1107 .state = VLIB_NODE_STATE_DISABLED,
1112 static clib_error_t *
1113 vl_api_show_histogram_command (vlib_main_t * vm,
1114 unformat_input_t * input,
1115 vlib_cli_command_t * cli_cmd)
1117 u64 total_counts = 0;
1120 for (i = 0; i < SLEEP_N_BUCKETS; i++)
1122 total_counts += vector_rate_histogram[i];
1125 if (total_counts == 0)
1127 vlib_cli_output (vm, "No control-plane activity.");
1134 percent = ((f64) vector_rate_histogram[SLEEP_##n##_US]) \
1135 / (f64) total_counts; \
1137 vlib_cli_output (vm, "Sleep %3d us: %llu, %.2f%%",n, \
1138 vector_rate_histogram[SLEEP_##n##_US], \
1141 foreach_histogram_bucket;
1148 * Display the binary api sleep-time histogram
1151 VLIB_CLI_COMMAND (cli_show_api_histogram_command, static) =
1153 .path = "show api histogram",
1154 .short_help = "show api histogram",
1155 .function = vl_api_show_histogram_command,
1159 static clib_error_t *
1160 vl_api_clear_histogram_command (vlib_main_t * vm,
1161 unformat_input_t * input,
1162 vlib_cli_command_t * cli_cmd)
1166 for (i = 0; i < SLEEP_N_BUCKETS; i++)
1167 vector_rate_histogram[i] = 0;
1172 * Clear the binary api sleep-time histogram
1175 VLIB_CLI_COMMAND (cli_clear_api_histogram_command, static) =
1177 .path = "clear api histogram",
1178 .short_help = "clear api histogram",
1179 .function = vl_api_clear_histogram_command,
1183 volatile int **vl_api_queue_cursizes;
1186 memclnt_queue_callback (vlib_main_t * vm)
1189 api_main_t *am = &api_main;
1191 if (PREDICT_FALSE (vec_len (vl_api_queue_cursizes) !=
1192 1 + vec_len (am->vlib_private_rps)))
1194 vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
1195 unix_shared_memory_queue_t *q;
1200 q = shmem_hdr->vl_input_queue;
1204 vec_add1 (vl_api_queue_cursizes, &q->cursize);
1206 for (i = 0; i < vec_len (am->vlib_private_rps); i++)
1208 svm_region_t *vlib_rp = am->vlib_private_rps[i];
1210 shmem_hdr = (void *) vlib_rp->user_ctx;
1211 q = shmem_hdr->vl_input_queue;
1212 vec_add1 (vl_api_queue_cursizes, &q->cursize);
1216 for (i = 0; i < vec_len (vl_api_queue_cursizes); i++)
1218 if (*vl_api_queue_cursizes[i])
1220 vm->queue_signal_pending = 1;
1221 vm->api_queue_nonempty = 1;
1222 vlib_process_signal_event (vm, memclnt_node.index,
1223 /* event_type */ QUEUE_SIGNAL_EVENT,
1224 /* event_data */ 0);
1231 vl_enable_disable_memory_api (vlib_main_t * vm, int enable)
1233 vlib_node_set_state (vm, memclnt_node.index,
1235 ? VLIB_NODE_STATE_POLLING
1236 : VLIB_NODE_STATE_DISABLED));
1240 api_rx_from_node (vlib_main_t * vm,
1241 vlib_node_runtime_t * node, vlib_frame_t * frame)
1243 uword n_packets = frame->n_vectors;
1246 static u8 *long_msg;
1248 vec_validate (long_msg, 4095);
1249 n_left_from = frame->n_vectors;
1250 from = vlib_frame_args (frame);
1252 while (n_left_from > 0)
1260 b0 = vlib_get_buffer (vm, bi0);
1264 msg = b0->data + b0->current_data;
1265 msg_len = b0->current_length;
1266 if (b0->flags & VLIB_BUFFER_NEXT_PRESENT)
1268 ASSERT (long_msg != 0);
1269 _vec_len (long_msg) = 0;
1270 vec_add (long_msg, msg, msg_len);
1271 while (b0->flags & VLIB_BUFFER_NEXT_PRESENT)
1273 b0 = vlib_get_buffer (vm, b0->next_buffer);
1274 msg = b0->data + b0->current_data;
1275 msg_len = b0->current_length;
1276 vec_add (long_msg, msg, msg_len);
1280 vl_msg_api_handler_no_trace_no_free (msg);
1283 /* Free what we've been given. */
1284 vlib_buffer_free (vm, vlib_frame_args (frame), n_packets);
1290 VLIB_REGISTER_NODE (api_rx_from_node_node,static) = {
1291 .function = api_rx_from_node,
1292 .type = VLIB_NODE_TYPE_INTERNAL,
1294 .name = "api-rx-from-node",
1298 static clib_error_t *
1299 setup_memclnt_exit (vlib_main_t * vm)
1301 atexit (vl_unmap_shmem);
1305 VLIB_INIT_FUNCTION (setup_memclnt_exit);
1308 format_api_message_rings (u8 * s, va_list * args)
1310 api_main_t *am = va_arg (*args, api_main_t *);
1311 vl_shmem_hdr_t *shmem_hdr = va_arg (*args, vl_shmem_hdr_t *);
1312 int main_segment = va_arg (*args, int);
1317 return format (s, "%8s %8s %8s %8s %8s\n",
1318 "Owner", "Size", "Nitems", "Hits", "Misses");
1320 ap = shmem_hdr->vl_rings;
1322 for (i = 0; i < vec_len (shmem_hdr->vl_rings); i++)
1324 s = format (s, "%8s %8d %8d %8d %8d\n",
1325 "vlib", ap->size, ap->nitems, ap->hits, ap->misses);
1329 ap = shmem_hdr->client_rings;
1331 for (i = 0; i < vec_len (shmem_hdr->client_rings); i++)
1333 s = format (s, "%8s %8d %8d %8d %8d\n",
1334 "clnt", ap->size, ap->nitems, ap->hits, ap->misses);
1340 s = format (s, "%d ring miss fallback allocations\n", am->ring_misses);
1343 "%d application restarts, %d reclaimed msgs, %d garbage collects\n",
1344 shmem_hdr->application_restarts, shmem_hdr->restart_reclaims,
1345 shmem_hdr->garbage_collects);
1351 static clib_error_t *
1352 vl_api_ring_command (vlib_main_t * vm,
1353 unformat_input_t * input, vlib_cli_command_t * cli_cmd)
1356 vl_shmem_hdr_t *shmem_hdr;
1357 api_main_t *am = &api_main;
1359 /* First, dump the primary region rings.. */
1361 if (am->vlib_primary_rp == 0 || am->vlib_primary_rp->user_ctx == 0)
1363 vlib_cli_output (vm, "Shared memory segment not initialized...\n");
1367 shmem_hdr = (void *) am->vlib_primary_rp->user_ctx;
1369 vlib_cli_output (vm, "Main API segment rings:");
1371 vlib_cli_output (vm, "%U", format_api_message_rings, am,
1372 0 /* print header */ , 0 /* notused */ );
1374 vlib_cli_output (vm, "%U", format_api_message_rings, am,
1375 shmem_hdr, 1 /* main segment */ );
1377 for (i = 0; i < vec_len (am->vlib_private_rps); i++)
1379 svm_region_t *vlib_rp = am->vlib_private_rps[i];
1380 shmem_hdr = (void *) vlib_rp->user_ctx;
1381 vl_api_registration_t **regpp;
1382 vl_api_registration_t *regp = 0;
1384 /* For horizontal scaling, add a hash table... */
1386 pool_foreach (regpp, am->vl_clients,
1389 if (regp && regp->vlib_rp == vlib_rp)
1391 vlib_cli_output (vm, "%s segment rings:", regp->name);
1395 vlib_cli_output (vm, "regp %llx not found?", regp);
1399 vlib_cli_output (vm, "%U", format_api_message_rings, am,
1400 0 /* print header */ , 0 /* notused */ );
1401 vlib_cli_output (vm, "%U", format_api_message_rings, am,
1402 shmem_hdr, 0 /* main segment */ );
1408 void dump_socket_clients (vlib_main_t * vm, api_main_t * am)
1409 __attribute__ ((weak));
1412 dump_socket_clients (vlib_main_t * vm, api_main_t * am)
1416 static clib_error_t *
1417 vl_api_client_command (vlib_main_t * vm,
1418 unformat_input_t * input, vlib_cli_command_t * cli_cmd)
1420 vl_api_registration_t **regpp, *regp;
1421 unix_shared_memory_queue_t *q;
1423 api_main_t *am = &api_main;
1424 u32 *confused_indices = 0;
1426 if (!pool_elts (am->vl_clients))
1427 goto socket_clients;
1428 vlib_cli_output (vm, "Shared memory clients");
1429 vlib_cli_output (vm, "%16s %8s %14s %18s %s",
1430 "Name", "PID", "Queue Length", "Queue VA", "Health");
1433 pool_foreach (regpp, am->vl_clients,
1439 if (regp->unanswered_pings > 0)
1440 health = "questionable";
1444 q = regp->vl_input_queue;
1446 vlib_cli_output (vm, "%16s %8d %14d 0x%016llx %s\n",
1447 regp->name, q->consumer_pid, q->cursize,
1452 clib_warning ("NULL client registration index %d",
1453 regpp - am->vl_clients);
1454 vec_add1 (confused_indices, regpp - am->vl_clients);
1459 /* This should "never happen," but if it does, fix it... */
1460 if (PREDICT_FALSE (vec_len (confused_indices) > 0))
1463 for (i = 0; i < vec_len (confused_indices); i++)
1465 pool_put_index (am->vl_clients, confused_indices[i]);
1468 vec_free (confused_indices);
1470 if (am->missing_clients)
1471 vlib_cli_output (vm, "%u messages with missing clients",
1472 am->missing_clients);
1474 dump_socket_clients (vm, am);
1479 static clib_error_t *
1480 vl_api_status_command (vlib_main_t * vm,
1481 unformat_input_t * input, vlib_cli_command_t * cli_cmd)
1483 api_main_t *am = &api_main;
1485 // check if rx_trace and tx_trace are not null pointers
1487 if (am->rx_trace == 0)
1489 vlib_cli_output (vm, "RX Trace disabled\n");
1493 if (am->rx_trace->enabled == 0)
1494 vlib_cli_output (vm, "RX Trace disabled\n");
1496 vlib_cli_output (vm, "RX Trace enabled\n");
1499 if (am->tx_trace == 0)
1501 vlib_cli_output (vm, "TX Trace disabled\n");
1505 if (am->tx_trace->enabled == 0)
1506 vlib_cli_output (vm, "TX Trace disabled\n");
1508 vlib_cli_output (vm, "TX Trace enabled\n");
1515 VLIB_CLI_COMMAND (cli_show_api_command, static) =
1518 .short_help = "Show API information",
1523 * Display binary api message allocation ring statistics
1526 VLIB_CLI_COMMAND (cli_show_api_ring_command, static) =
1528 .path = "show api ring-stats",
1529 .short_help = "Message ring statistics",
1530 .function = vl_api_ring_command,
1535 * Display current api client connections
1538 VLIB_CLI_COMMAND (cli_show_api_clients_command, static) =
1540 .path = "show api clients",
1541 .short_help = "Client information",
1542 .function = vl_api_client_command,
1547 * Display the current api message tracing status
1550 VLIB_CLI_COMMAND (cli_show_api_status_command, static) =
1552 .path = "show api trace-status",
1553 .short_help = "Display API trace status",
1554 .function = vl_api_status_command,
1558 static clib_error_t *
1559 vl_api_message_table_command (vlib_main_t * vm,
1560 unformat_input_t * input,
1561 vlib_cli_command_t * cli_cmd)
1563 api_main_t *am = &api_main;
1567 if (unformat (input, "verbose"))
1572 vlib_cli_output (vm, "%-4s %s", "ID", "Name");
1574 vlib_cli_output (vm, "%-4s %-40s %6s %7s", "ID", "Name", "Bounce",
1577 for (i = 1; i < vec_len (am->msg_names); i++)
1581 vlib_cli_output (vm, "%-4d %s", i,
1582 am->msg_names[i] ? am->msg_names[i] :
1587 vlib_cli_output (vm, "%-4d %-40s %6d %7d", i,
1588 am->msg_names[i] ? am->msg_names[i] :
1589 " [no handler]", am->message_bounce[i],
1598 * Display the current api message decode tables
1601 VLIB_CLI_COMMAND (cli_show_api_message_table_command, static) =
1603 .path = "show api message-table",
1604 .short_help = "Message Table",
1605 .function = vl_api_message_table_command,
1609 static clib_error_t *
1610 vl_api_trace_command (vlib_main_t * vm,
1611 unformat_input_t * input, vlib_cli_command_t * cli_cmd)
1614 vl_api_trace_which_t which = VL_API_TRACE_RX;
1615 api_main_t *am = &api_main;
1617 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1619 if (unformat (input, "rx nitems %u", &nitems) || unformat (input, "rx"))
1621 else if (unformat (input, "tx nitems %u", &nitems)
1622 || unformat (input, "tx"))
1624 which = VL_API_TRACE_RX;
1627 else if (unformat (input, "on rx"))
1629 vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 1);
1631 else if (unformat (input, "on tx"))
1633 vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 1);
1635 else if (unformat (input, "on"))
1637 vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 1);
1639 else if (unformat (input, "off"))
1641 vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 0);
1642 vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 0);
1644 else if (unformat (input, "free"))
1646 vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 0);
1647 vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 0);
1648 vl_msg_api_trace_free (am, VL_API_TRACE_RX);
1649 vl_msg_api_trace_free (am, VL_API_TRACE_TX);
1651 else if (unformat (input, "debug on"))
1653 am->msg_print_flag = 1;
1655 else if (unformat (input, "debug off"))
1657 am->msg_print_flag = 0;
1660 return clib_error_return (0, "unknown input `%U'",
1661 format_unformat_error, input);
1666 if (vl_msg_api_trace_configure (am, which, nitems))
1668 vlib_cli_output (vm, "warning: trace configure error (%d, %d)",
1676 * Control the binary API trace mechanism
1679 VLIB_CLI_COMMAND (trace, static) =
1681 .path = "set api-trace [on][on tx][on rx][off][free][debug on][debug off]",
1682 .short_help = "API trace",
1683 .function = vl_api_trace_command,
1688 vlibmemory_init (vlib_main_t * vm)
1690 api_main_t *am = &api_main;
1691 svm_map_region_args_t _a, *a = &_a;
1692 clib_error_t *error;
1694 memset (a, 0, sizeof (*a));
1695 a->root_path = am->root_path;
1696 a->name = SVM_GLOBAL_REGION_NAME;
1697 a->baseva = (am->global_baseva != 0) ?
1698 am->global_baseva : SVM_GLOBAL_REGION_BASEVA;
1699 a->size = (am->global_size != 0) ? am->global_size : SVM_GLOBAL_REGION_SIZE;
1700 a->flags = SVM_FLAGS_NODATA;
1701 a->uid = am->api_uid;
1702 a->gid = am->api_gid;
1704 (am->global_pvt_heap_size !=
1705 0) ? am->global_pvt_heap_size : SVM_PVT_MHEAP_SIZE;
1707 svm_region_init_args (a);
1709 error = vlib_call_init_function (vm, vlibsocket_init);
1714 VLIB_INIT_FUNCTION (vlibmemory_init);
1717 vl_set_memory_region_name (const char *name)
1719 api_main_t *am = &api_main;
1721 am->region_name = name;
1725 range_compare (vl_api_msg_range_t * a0, vl_api_msg_range_t * a1)
1727 int len0, len1, clen;
1729 len0 = vec_len (a0->name);
1730 len1 = vec_len (a1->name);
1731 clen = len0 < len1 ? len0 : len1;
1732 return (strncmp ((char *) a0->name, (char *) a1->name, clen));
1736 format_api_msg_range (u8 * s, va_list * args)
1738 vl_api_msg_range_t *rp = va_arg (*args, vl_api_msg_range_t *);
1741 s = format (s, "%-50s%9s%9s", "Name", "First-ID", "Last-ID");
1743 s = format (s, "%-50s%9d%9d", rp->name, rp->first_msg_id,
1749 static clib_error_t *
1750 vl_api_show_plugin_command (vlib_main_t * vm,
1751 unformat_input_t * input,
1752 vlib_cli_command_t * cli_cmd)
1754 api_main_t *am = &api_main;
1755 vl_api_msg_range_t *rp = 0;
1758 if (vec_len (am->msg_ranges) == 0)
1760 vlib_cli_output (vm, "No plugin API message ranges configured...");
1764 rp = vec_dup (am->msg_ranges);
1766 vec_sort_with_function (rp, range_compare);
1768 vlib_cli_output (vm, "Plugin API message ID ranges...\n");
1769 vlib_cli_output (vm, "%U", format_api_msg_range, 0 /* header */ );
1771 for (i = 0; i < vec_len (rp); i++)
1772 vlib_cli_output (vm, "%U", format_api_msg_range, rp + i);
1780 * Display the plugin binary API message range table
1783 VLIB_CLI_COMMAND (cli_show_api_plugin_command, static) =
1785 .path = "show api plugin",
1786 .short_help = "show api plugin",
1787 .function = vl_api_show_plugin_command,
1792 vl_api_rpc_call_t_handler (vl_api_rpc_call_t * mp)
1794 vl_api_rpc_call_reply_t *rmp;
1797 vlib_main_t *vm = vlib_get_main ();
1799 if (mp->function == 0)
1802 clib_warning ("rpc NULL function pointer");
1807 if (mp->need_barrier_sync)
1808 vlib_worker_thread_barrier_sync (vm);
1810 fp = uword_to_pointer (mp->function, int (*)(void *));
1813 if (mp->need_barrier_sync)
1814 vlib_worker_thread_barrier_release (vm);
1819 unix_shared_memory_queue_t *q =
1820 vl_api_client_index_to_input_queue (mp->client_index);
1823 rmp = vl_msg_api_alloc_as_if_client (sizeof (*rmp));
1824 rmp->_vl_msg_id = ntohs (VL_API_RPC_CALL_REPLY);
1825 rmp->context = mp->context;
1827 vl_msg_api_send_shmem (q, (u8 *) & rmp);
1832 clib_warning ("multicast not yet implemented...");
1837 vl_api_rpc_call_reply_t_handler (vl_api_rpc_call_reply_t * mp)
1839 clib_warning ("unimplemented");
1843 vl_api_rpc_call_main_thread_inline (void *fp, u8 * data, u32 data_length,
1846 vl_api_rpc_call_t *mp;
1847 api_main_t *am = &api_main;
1848 vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
1849 unix_shared_memory_queue_t *q;
1851 /* Main thread: call the function directly */
1852 if ((force_rpc == 0) && (vlib_get_thread_index () == 0))
1854 vlib_main_t *vm = vlib_get_main ();
1855 void (*call_fp) (void *);
1857 vlib_worker_thread_barrier_sync (vm);
1862 vlib_worker_thread_barrier_release (vm);
1866 /* Any other thread, actually do an RPC call... */
1867 mp = vl_msg_api_alloc_as_if_client (sizeof (*mp) + data_length);
1869 memset (mp, 0, sizeof (*mp));
1870 clib_memcpy (mp->data, data, data_length);
1871 mp->_vl_msg_id = ntohs (VL_API_RPC_CALL);
1872 mp->function = pointer_to_uword (fp);
1873 mp->need_barrier_sync = 1;
1876 * Use the "normal" control-plane mechanism for the main thread.
1877 * Well, almost. if the main input queue is full, we cannot
1878 * block. Otherwise, we can expect a barrier sync timeout.
1880 q = shmem_hdr->vl_input_queue;
1882 while (pthread_mutex_trylock (&q->mutex))
1883 vlib_worker_thread_barrier_check ();
1885 while (PREDICT_FALSE (unix_shared_memory_queue_is_full (q)))
1887 pthread_mutex_unlock (&q->mutex);
1888 vlib_worker_thread_barrier_check ();
1889 while (pthread_mutex_trylock (&q->mutex))
1890 vlib_worker_thread_barrier_check ();
1893 vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
1895 pthread_mutex_unlock (&q->mutex);
1899 * Check if called from worker threads.
1900 * If so, make rpc call of fp through shmem.
1901 * Otherwise, call fp directly
1904 vl_api_rpc_call_main_thread (void *fp, u8 * data, u32 data_length)
1906 vl_api_rpc_call_main_thread_inline (fp, data, data_length, /*force_rpc */
1911 * Always make rpc call of fp through shmem, useful for calling from threads
1912 * not setup as worker threads, such as DPDK callback thread
1915 vl_api_force_rpc_call_main_thread (void *fp, u8 * data, u32 data_length)
1917 vl_api_rpc_call_main_thread_inline (fp, data, data_length, /*force_rpc */
1922 vl_api_trace_plugin_msg_ids_t_handler (vl_api_trace_plugin_msg_ids_t * mp)
1924 api_main_t *am = &api_main;
1925 vl_api_msg_range_t *rp;
1928 /* Noop (except for tracing) during normal operation */
1929 if (am->replay_in_progress == 0)
1932 p = hash_get_mem (am->msg_range_by_name, mp->plugin_name);
1935 clib_warning ("WARNING: traced plugin '%s' not in current image",
1940 rp = vec_elt_at_index (am->msg_ranges, p[0]);
1941 if (rp->first_msg_id != clib_net_to_host_u16 (mp->first_msg_id))
1943 clib_warning ("WARNING: traced plugin '%s' first message id %d not %d",
1944 mp->plugin_name, clib_net_to_host_u16 (mp->first_msg_id),
1948 if (rp->last_msg_id != clib_net_to_host_u16 (mp->last_msg_id))
1950 clib_warning ("WARNING: traced plugin '%s' last message id %d not %d",
1951 mp->plugin_name, clib_net_to_host_u16 (mp->last_msg_id),
1956 #define foreach_rpc_api_msg \
1957 _(RPC_CALL,rpc_call) \
1958 _(RPC_CALL_REPLY,rpc_call_reply)
1960 #define foreach_plugin_trace_msg \
1961 _(TRACE_PLUGIN_MSG_IDS,trace_plugin_msg_ids)
1964 * Set the rpc callback at our earliest possible convenience.
1965 * This avoids ordering issues between thread_init() -> start_workers and
1966 * an init function which we could define here. If we ever intend to use
1967 * vlib all by itself, we can't create a link-time dependency on
1968 * an init function here and a typical "call foo_init first"
1972 extern void *rpc_call_main_thread_cb_fn;
1974 static clib_error_t *
1975 rpc_api_hookup (vlib_main_t * vm)
1977 api_main_t *am = &api_main;
1979 vl_msg_api_set_handlers(VL_API_##N, #n, \
1980 vl_api_##n##_t_handler, \
1983 vl_api_##n##_t_print, \
1984 sizeof(vl_api_##n##_t), 0 /* do not trace */);
1985 foreach_rpc_api_msg;
1989 vl_msg_api_set_handlers(VL_API_##N, #n, \
1990 vl_api_##n##_t_handler, \
1993 vl_api_##n##_t_print, \
1994 sizeof(vl_api_##n##_t), 1 /* do trace */);
1995 foreach_plugin_trace_msg;
1998 /* No reason to halt the parade to create a trace record... */
1999 am->is_mp_safe[VL_API_TRACE_PLUGIN_MSG_IDS] = 1;
2000 rpc_call_main_thread_cb_fn = vl_api_rpc_call_main_thread;
2004 VLIB_API_INIT_FUNCTION (rpc_api_hookup);
2015 format_vl_msg_api_trace_status (u8 * s, va_list * args)
2017 api_main_t *am = va_arg (*args, api_main_t *);
2018 vl_api_trace_which_t which = va_arg (*args, vl_api_trace_which_t);
2024 case VL_API_TRACE_TX:
2026 trace_name = "TX trace";
2029 case VL_API_TRACE_RX:
2031 trace_name = "RX trace";
2040 s = format (s, "%s: not yet configured.\n", trace_name);
2044 s = format (s, "%s: used %d of %d items, %s enabled, %s wrapped\n",
2045 trace_name, vec_len (tp->traces), tp->nitems,
2046 tp->enabled ? "is" : "is not", tp->wrapped ? "has" : "has not");
2050 void vl_msg_api_custom_dump_configure (api_main_t * am)
2051 __attribute__ ((weak));
2053 vl_msg_api_custom_dump_configure (api_main_t * am)
2058 vl_msg_api_process_file (vlib_main_t * vm, u8 * filename,
2059 u32 first_index, u32 last_index,
2060 vl_api_replay_t which)
2062 vl_api_trace_file_header_t *hp;
2067 u8 endian_swap_needed = 0;
2068 api_main_t *am = &api_main;
2071 void **saved_print_handlers = 0;
2073 fd = open ((char *) filename, O_RDONLY);
2077 vlib_cli_output (vm, "Couldn't open %s\n", filename);
2081 if (fstat (fd, &statb) < 0)
2083 vlib_cli_output (vm, "Couldn't stat %s\n", filename);
2088 if (!(statb.st_mode & S_IFREG) || (statb.st_size < sizeof (*hp)))
2090 vlib_cli_output (vm, "File not plausible: %s\n", filename);
2095 file_size = statb.st_size;
2096 file_size = (file_size + 4095) & ~(4096);
2098 hp = mmap (0, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2100 if (hp == (vl_api_trace_file_header_t *) MAP_FAILED)
2102 vlib_cli_output (vm, "mmap failed: %s\n", filename);
2108 if ((clib_arch_is_little_endian && hp->endian == VL_API_BIG_ENDIAN)
2109 || (clib_arch_is_big_endian && hp->endian == VL_API_LITTLE_ENDIAN))
2110 endian_swap_needed = 1;
2112 if (endian_swap_needed)
2113 nitems = ntohl (hp->nitems);
2115 nitems = hp->nitems;
2117 if (last_index == (u32) ~ 0)
2119 last_index = nitems - 1;
2122 if (first_index >= nitems || last_index >= nitems)
2124 vlib_cli_output (vm, "Range (%d, %d) outside file range (0, %d)\n",
2125 first_index, last_index, nitems - 1);
2126 munmap (hp, file_size);
2130 vlib_cli_output (vm,
2131 "Note: wrapped/incomplete trace, results may vary\n");
2133 if (which == CUSTOM_DUMP)
2135 saved_print_handlers = (void **) vec_dup (am->msg_print_handlers);
2136 vl_msg_api_custom_dump_configure (am);
2140 msg = (u8 *) (hp + 1);
2142 for (i = 0; i < first_index; i++)
2148 size = clib_host_to_net_u32 (*(u32 *) msg);
2149 msg += sizeof (u32);
2151 if (clib_arch_is_little_endian)
2152 msg_id = ntohs (*((u16 *) msg));
2154 msg_id = *((u16 *) msg);
2156 cfgp = am->api_trace_cfg + msg_id;
2159 vlib_cli_output (vm, "Ugh: msg id %d no trace config\n", msg_id);
2160 munmap (hp, file_size);
2166 if (which == REPLAY)
2167 am->replay_in_progress = 1;
2169 for (; i <= last_index; i++)
2177 vlib_cli_output (vm, "---------- trace %d -----------\n", i);
2179 size = clib_host_to_net_u32 (*(u32 *) msg);
2180 msg += sizeof (u32);
2182 if (clib_arch_is_little_endian)
2183 msg_id = ntohs (*((u16 *) msg));
2185 msg_id = *((u16 *) msg);
2187 cfgp = am->api_trace_cfg + msg_id;
2190 vlib_cli_output (vm, "Ugh: msg id %d no trace config\n", msg_id);
2191 munmap (hp, file_size);
2193 am->replay_in_progress = 0;
2197 /* Copy the buffer (from the read-only mmap'ed file) */
2198 vec_validate (tmpbuf, size - 1 + sizeof (uword));
2199 clib_memcpy (tmpbuf + sizeof (uword), msg, size);
2200 memset (tmpbuf, 0xf, sizeof (uword));
2203 * Endian swap if needed. All msg data is supposed to be
2204 * in network byte order. All msg handlers are supposed to
2205 * know that. The generic message dumpers don't know that.
2206 * One could fix apigen, I suppose.
2208 if ((which == DUMP && clib_arch_is_little_endian) || endian_swap_needed)
2210 void (*endian_fp) (void *);
2211 if (msg_id >= vec_len (am->msg_endian_handlers)
2212 || (am->msg_endian_handlers[msg_id] == 0))
2214 vlib_cli_output (vm, "Ugh: msg id %d no endian swap\n", msg_id);
2215 munmap (hp, file_size);
2217 am->replay_in_progress = 0;
2220 endian_fp = am->msg_endian_handlers[msg_id];
2221 (*endian_fp) (tmpbuf + sizeof (uword));
2224 /* msg_id always in network byte order */
2225 if (clib_arch_is_little_endian)
2227 msg_idp = (u16 *) (tmpbuf + sizeof (uword));
2235 if (msg_id < vec_len (am->msg_print_handlers) &&
2236 am->msg_print_handlers[msg_id])
2238 u8 *(*print_fp) (void *, void *);
2240 print_fp = (void *) am->msg_print_handlers[msg_id];
2241 (*print_fp) (tmpbuf + sizeof (uword), vm);
2245 vlib_cli_output (vm, "Skipping msg id %d: no print fcn\n",
2252 if (msg_id < vec_len (am->msg_print_handlers) &&
2253 am->msg_print_handlers[msg_id])
2257 u8 *(*print_fp) (void *, void *);
2259 print_fp = (void *) am->msg_print_handlers[msg_id];
2261 vlib_cli_output (vm, "/*");
2263 (*print_fp) (tmpbuf + sizeof (uword), vm);
2264 vlib_cli_output (vm, "*/\n");
2266 s = format (0, "static u8 * vl_api_%s_%d[%d] = {",
2267 am->msg_names[msg_id], i,
2268 am->api_trace_cfg[msg_id].size);
2270 for (j = 0; j < am->api_trace_cfg[msg_id].size; j++)
2273 s = format (s, "\n ");
2274 s = format (s, "0x%02x,", tmpbuf[sizeof (uword) + j]);
2276 s = format (s, "\n};\n%c", 0);
2277 vlib_cli_output (vm, (char *) s);
2283 if (msg_id < vec_len (am->msg_print_handlers) &&
2284 am->msg_print_handlers[msg_id] && cfgp->replay_enable)
2286 void (*handler) (void *);
2288 handler = (void *) am->msg_handlers[msg_id];
2290 if (!am->is_mp_safe[msg_id])
2291 vl_msg_api_barrier_sync ();
2292 (*handler) (tmpbuf + sizeof (uword));
2293 if (!am->is_mp_safe[msg_id])
2294 vl_msg_api_barrier_release ();
2298 if (cfgp->replay_enable)
2299 vlib_cli_output (vm, "Skipping msg id %d: no handler\n",
2306 _vec_len (tmpbuf) = 0;
2310 if (saved_print_handlers)
2312 clib_memcpy (am->msg_print_handlers, saved_print_handlers,
2313 vec_len (am->msg_print_handlers) * sizeof (void *));
2314 vec_free (saved_print_handlers);
2317 munmap (hp, file_size);
2319 am->replay_in_progress = 0;
2322 static clib_error_t *
2323 api_trace_command_fn (vlib_main_t * vm,
2324 unformat_input_t * input, vlib_cli_command_t * cmd)
2326 u32 nitems = 256 << 10;
2327 api_main_t *am = &api_main;
2328 vl_api_trace_which_t which = VL_API_TRACE_RX;
2331 u32 last = (u32) ~ 0;
2335 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2337 if (unformat (input, "on") || unformat (input, "enable"))
2339 if (unformat (input, "nitems %d", &nitems))
2341 vl_msg_api_trace_configure (am, which, nitems);
2342 vl_msg_api_trace_onoff (am, which, 1 /* on */ );
2344 else if (unformat (input, "off"))
2346 vl_msg_api_trace_onoff (am, which, 0);
2348 else if (unformat (input, "save %s", &filename))
2350 u8 *chroot_filename;
2351 if (strstr ((char *) filename, "..")
2352 || index ((char *) filename, '/'))
2354 vlib_cli_output (vm, "illegal characters in filename '%s'",
2359 chroot_filename = format (0, "/tmp/%s%c", filename, 0);
2361 vec_free (filename);
2363 fp = fopen ((char *) chroot_filename, "w");
2366 vlib_cli_output (vm, "Couldn't create %s\n", chroot_filename);
2369 rv = vl_msg_api_trace_save (am, which, fp);
2372 vlib_cli_output (vm, "API Trace data not present\n");
2374 vlib_cli_output (vm, "File for writing is closed\n");
2376 vlib_cli_output (vm, "Error while writing header to file\n");
2378 vlib_cli_output (vm, "Error while writing trace to file\n");
2380 vlib_cli_output (vm,
2381 "Error while writing end of buffer trace to file\n");
2383 vlib_cli_output (vm,
2384 "Error while writing start of buffer trace to file\n");
2386 vlib_cli_output (vm, "Unkown error while saving: %d", rv);
2388 vlib_cli_output (vm, "API trace saved to %s\n", chroot_filename);
2389 vec_free (chroot_filename);
2391 else if (unformat (input, "dump %s", &filename))
2393 vl_msg_api_process_file (vm, filename, first, last, DUMP);
2395 else if (unformat (input, "custom-dump %s", &filename))
2397 vl_msg_api_process_file (vm, filename, first, last, CUSTOM_DUMP);
2399 else if (unformat (input, "replay %s", &filename))
2401 vl_msg_api_process_file (vm, filename, first, last, REPLAY);
2403 else if (unformat (input, "initializers %s", &filename))
2405 vl_msg_api_process_file (vm, filename, first, last, INITIALIZERS);
2407 else if (unformat (input, "tx"))
2409 which = VL_API_TRACE_TX;
2411 else if (unformat (input, "first %d", &first))
2415 else if (unformat (input, "last %d", &last))
2419 else if (unformat (input, "status"))
2421 vlib_cli_output (vm, "%U", format_vl_msg_api_trace_status,
2424 else if (unformat (input, "free"))
2426 vl_msg_api_trace_onoff (am, which, 0);
2427 vl_msg_api_trace_free (am, which);
2429 else if (unformat (input, "post-mortem-on"))
2430 vl_msg_api_post_mortem_dump_enable_disable (1 /* enable */ );
2431 else if (unformat (input, "post-mortem-off"))
2432 vl_msg_api_post_mortem_dump_enable_disable (0 /* enable */ );
2434 return clib_error_return (0, "unknown input `%U'",
2435 format_unformat_error, input);
2441 * Display, replay, or save a binary API trace
2445 VLIB_CLI_COMMAND (api_trace_command, static) =
2447 .path = "api trace",
2449 "api trace [on|off][dump|save|replay <file>][status][free][post-mortem-on]",
2450 .function = api_trace_command_fn,
2454 static clib_error_t *
2455 api_config_fn (vlib_main_t * vm, unformat_input_t * input)
2457 u32 nitems = 256 << 10;
2458 vl_api_trace_which_t which = VL_API_TRACE_RX;
2459 api_main_t *am = &api_main;
2461 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2463 if (unformat (input, "on") || unformat (input, "enable"))
2465 if (unformat (input, "nitems %d", &nitems))
2467 vl_msg_api_trace_configure (am, which, nitems);
2468 vl_msg_api_trace_onoff (am, which, 1 /* on */ );
2469 vl_msg_api_post_mortem_dump_enable_disable (1 /* enable */ );
2471 else if (unformat (input, "save-api-table %s",
2472 &am->save_msg_table_filename))
2475 return clib_error_return (0, "unknown input `%U'",
2476 format_unformat_error, input);
2482 * This module has three configuration parameters:
2483 * "on" or "enable" - enables binary api tracing
2484 * "nitems <nnn>" - sets the size of the circular buffer to <nnn>
2485 * "save-api-table <filename>" - dumps the API message table to /tmp/<filename>
2487 VLIB_CONFIG_FUNCTION (api_config_fn, "api-trace");
2489 static clib_error_t *
2490 api_queue_config_fn (vlib_main_t * vm, unformat_input_t * input)
2492 api_main_t *am = &api_main;
2495 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2497 if (unformat (input, "length %d", &nitems) ||
2498 (unformat (input, "len %d", &nitems)))
2501 am->vlib_input_queue_length = nitems;
2503 clib_warning ("vlib input queue length %d too small, ignored",
2507 return clib_error_return (0, "unknown input `%U'",
2508 format_unformat_error, input);
2513 VLIB_CONFIG_FUNCTION (api_queue_config_fn, "api-queue");
2516 extract_name (u8 * s)
2522 while (vec_len (rv) && rv[vec_len (rv)] != '_')
2525 rv[vec_len (rv)] = 0;
2531 extract_crc (u8 * s)
2538 for (i = vec_len (rv) - 1; i >= 0; i--)
2542 vec_delete (rv, i + 1, 0);
2556 } msg_table_unserialize_t;
2559 table_id_cmp (void *a1, void *a2)
2561 msg_table_unserialize_t *n1 = a1;
2562 msg_table_unserialize_t *n2 = a2;
2564 return (n1->msg_index - n2->msg_index);
2568 table_name_and_crc_cmp (void *a1, void *a2)
2570 msg_table_unserialize_t *n1 = a1;
2571 msg_table_unserialize_t *n2 = a2;
2573 return strcmp ((char *) n1->name_and_crc, (char *) n2->name_and_crc);
2576 static clib_error_t *
2577 dump_api_table_file_command_fn (vlib_main_t * vm,
2578 unformat_input_t * input,
2579 vlib_cli_command_t * cmd)
2582 api_main_t *am = &api_main;
2583 serialize_main_t _sm, *sm = &_sm;
2584 clib_error_t *error;
2588 int compare_current = 0;
2589 int numeric_sort = 0;
2590 msg_table_unserialize_t *table = 0, *item;
2592 u32 ndifferences = 0;
2594 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2596 if (unformat (input, "file %s", &filename))
2598 else if (unformat (input, "compare-current")
2599 || unformat (input, "compare"))
2600 compare_current = 1;
2601 else if (unformat (input, "numeric"))
2604 return clib_error_return (0, "unknown input `%U'",
2605 format_unformat_error, input);
2608 if (numeric_sort && compare_current)
2609 return clib_error_return
2610 (0, "Comparison and numeric sorting are incompatible");
2613 return clib_error_return (0, "File not specified");
2615 /* Load the serialized message table from the table dump */
2617 error = unserialize_open_clib_file (sm, (char *) filename);
2622 unserialize_integer (sm, &nmsgs, sizeof (u32));
2624 for (i = 0; i < nmsgs; i++)
2626 msg_index = unserialize_likely_small_unsigned_integer (sm);
2627 unserialize_cstring (sm, (char **) &name_and_crc);
2628 vec_add2 (table, item, 1);
2629 item->msg_index = msg_index;
2630 item->name_and_crc = name_and_crc;
2631 item->name = extract_name (name_and_crc);
2632 item->crc = extract_crc (name_and_crc);
2633 item->which = 0; /* file */
2635 serialize_close (sm);
2637 /* Compare with the current image? */
2638 if (compare_current)
2640 /* Append the current message table */
2641 u8 *tblv = vl_api_serialize_message_table (am, 0);
2643 serialize_open_vector (sm, tblv);
2644 unserialize_integer (sm, &nmsgs, sizeof (u32));
2646 for (i = 0; i < nmsgs; i++)
2648 msg_index = unserialize_likely_small_unsigned_integer (sm);
2649 unserialize_cstring (sm, (char **) &name_and_crc);
2651 vec_add2 (table, item, 1);
2652 item->msg_index = msg_index;
2653 item->name_and_crc = name_and_crc;
2654 item->name = extract_name (name_and_crc);
2655 item->crc = extract_crc (name_and_crc);
2656 item->which = 1; /* current_image */
2661 /* Sort the table. */
2663 vec_sort_with_function (table, table_id_cmp);
2665 vec_sort_with_function (table, table_name_and_crc_cmp);
2667 if (compare_current)
2672 * In this case, the recovered table will have two entries per
2673 * API message. So, if entries i and i+1 match, the message definitions
2674 * are identical. Otherwise, the crc is different, or a message is
2675 * present in only one of the tables.
2677 vlib_cli_output (vm, "%=60s %s", "Message Name", "Result");
2679 for (i = 0; i < vec_len (table);)
2681 /* Last message lonely? */
2682 if (i == vec_len (table) - 1)
2688 /* Identical pair? */
2690 ((char *) table[i].name_and_crc,
2691 (char *) table[i + 1].name_and_crc,
2692 vec_len (table[i].name_and_crc)))
2700 /* Only in one of two tables? */
2701 if (strncmp ((char *) table[i].name, (char *) table[i + 1].name,
2702 vec_len (table[i].name)))
2705 vlib_cli_output (vm, "%-60s only in %s",
2706 table[i].name, table[i].which ?
2711 /* In both tables, but with different signatures */
2712 vlib_cli_output (vm, "%-60s definition changed", table[i].name);
2715 if (ndifferences == 0)
2716 vlib_cli_output (vm, "No api message signature differences found.");
2718 vlib_cli_output (vm, "Found %u api message signature differences",
2723 /* Dump the table, sorted as shown above */
2724 vlib_cli_output (vm, "%=60s %=8s %=10s", "Message name", "MsgID", "CRC");
2726 for (i = 0; i < vec_len (table); i++)
2729 vlib_cli_output (vm, "%-60s %8u %10s", item->name,
2730 item->msg_index, item->crc);
2734 for (i = 0; i < vec_len (table); i++)
2736 vec_free (table[i].name_and_crc);
2737 vec_free (table[i].name);
2738 vec_free (table[i].crc);
2747 * Displays a serialized API message decode table, sorted by message name
2750 * @cliexstart{show api dump file <filename>}
2751 * Message name MsgID CRC
2752 * accept_session 407 8e2a127e
2753 * accept_session_reply 408 67d8c22a
2754 * add_node_next 549 e4202993
2755 * add_node_next_reply 550 e89d6eed
2761 * Compares a serialized API message decode table with the current image
2764 * @cliexstart{show api dump file <filename> compare}
2765 * ip_add_del_route definition changed
2766 * ip_table_add_del definition changed
2767 * l2_macs_event only in image
2768 * vnet_ip4_fib_counters only in file
2769 * vnet_ip4_nbr_counters only in file
2774 * Display a serialized API message decode table, compare a saved
2775 * decode table with the current image, to establish API differences.
2779 VLIB_CLI_COMMAND (dump_api_table_file, static) =
2781 .path = "show api dump",
2782 .short_help = "show api dump file <filename> [numeric | compare-current]",
2783 .function = dump_api_table_file_command_fn,
2788 * fd.io coding-style-patch-verification: ON
2791 * eval: (c-set-style "gnu")