Back to home page

OSCL-LXR

 
 

    


0001 /* Copyright (c) 2013-2015 PLUMgrid, http://plumgrid.com
0002  *
0003  * This program is free software; you can redistribute it and/or
0004  * modify it under the terms of version 2 of the GNU General Public
0005  * License as published by the Free Software Foundation.
0006  */
0007 #include <linux/skbuff.h>
0008 #include <linux/netdevice.h>
0009 #include <linux/version.h>
0010 #include <uapi/linux/bpf.h>
0011 #include <bpf/bpf_helpers.h>
0012 #include <bpf/bpf_tracing.h>
0013 
0014 struct {
0015     __uint(type, BPF_MAP_TYPE_HASH);
0016     __type(key, long);
0017     __type(value, u64);
0018     __uint(max_entries, 4096);
0019 } my_map SEC(".maps");
0020 
0021 /* kprobe is NOT a stable ABI. If kernel internals change this bpf+kprobe
0022  * example will no longer be meaningful
0023  */
0024 SEC("kprobe/blk_mq_start_request")
0025 int bpf_prog1(struct pt_regs *ctx)
0026 {
0027     long rq = PT_REGS_PARM1(ctx);
0028     u64 val = bpf_ktime_get_ns();
0029 
0030     bpf_map_update_elem(&my_map, &rq, &val, BPF_ANY);
0031     return 0;
0032 }
0033 
0034 static unsigned int log2l(unsigned long long n)
0035 {
0036 #define S(k) if (n >= (1ull << k)) { i += k; n >>= k; }
0037     int i = -(n == 0);
0038     S(32); S(16); S(8); S(4); S(2); S(1);
0039     return i;
0040 #undef S
0041 }
0042 
0043 #define SLOTS 100
0044 
0045 struct {
0046     __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
0047     __uint(key_size, sizeof(u32));
0048     __uint(value_size, sizeof(u64));
0049     __uint(max_entries, SLOTS);
0050 } lat_map SEC(".maps");
0051 
0052 SEC("kprobe/blk_account_io_done")
0053 int bpf_prog2(struct pt_regs *ctx)
0054 {
0055     long rq = PT_REGS_PARM1(ctx);
0056     u64 *value, l, base;
0057     u32 index;
0058 
0059     value = bpf_map_lookup_elem(&my_map, &rq);
0060     if (!value)
0061         return 0;
0062 
0063     u64 cur_time = bpf_ktime_get_ns();
0064     u64 delta = cur_time - *value;
0065 
0066     bpf_map_delete_elem(&my_map, &rq);
0067 
0068     /* the lines below are computing index = log10(delta)*10
0069      * using integer arithmetic
0070      * index = 29 ~ 1 usec
0071      * index = 59 ~ 1 msec
0072      * index = 89 ~ 1 sec
0073      * index = 99 ~ 10sec or more
0074      * log10(x)*10 = log2(x)*10/log2(10) = log2(x)*3
0075      */
0076     l = log2l(delta);
0077     base = 1ll << l;
0078     index = (l * 64 + (delta - base) * 64 / base) * 3 / 64;
0079 
0080     if (index >= SLOTS)
0081         index = SLOTS - 1;
0082 
0083     value = bpf_map_lookup_elem(&lat_map, &index);
0084     if (value)
0085         *value += 1;
0086 
0087     return 0;
0088 }
0089 char _license[] SEC("license") = "GPL";
0090 u32 _version SEC("version") = LINUX_VERSION_CODE;