#!/usr/bin/env bpftrace

/* Script to obtain udp_sendmsg() latency histograms.
 * It will measure time between entry and exit and plot one histogram
 * for each destination port number, indicating the amount of time spent.
 *
 * Implemented 2025 by Vadim Yanitskiy <fixeria@osmocom.org>
 * SPDX-License-Identifier: CC0
 *
 * As no filtering on PID etc. is done, you will likely use this with 'bpftrace -p' like
 *
 *     bpftrace ./udp_sendmsg_delay.bt -p PID
 *
 * (where PID is the PID of the process, like osmo-bts-trx)
 */

BEGIN
{
  printf("Tracing udp_sendmsg() latency... Hit Ctrl-C to end.\n");
}

kprobe:udp_sendmsg
{
  $sk = (struct sock *)arg0;
  /* poor man's ntohs() */
  $dport  = ($sk->__sk_common.skc_dport & 0xff) << 8;
  $dport |= ($sk->__sk_common.skc_dport >> 8) & 0xff;

  @start[tid] = nsecs;
  @dport[tid] = $dport;
}

kretprobe:udp_sendmsg / @start[tid] /
{
  $delta_us = (nsecs - @start[tid]) / 1000;
  @latency[@dport[tid]] = hist($delta_us);

  delete(@start[tid]);
  delete(@dport[tid]);
}

/* vim:set ts=2 sw=2 et: */
