aboutsummaryrefslogtreecommitdiffstats
path: root/target/linux
diff options
context:
space:
mode:
authorDavid Bauer <mail@david-bauer.net>2021-06-21 23:27:56 +0200
committerDavid Bauer <mail@david-bauer.net>2021-06-30 21:39:59 +0200
commit6cf1dfd7e1d6b5c6a94b87eb065408bb489574c0 (patch)
tree97589f0e10aed5adb6eedda6b00e9405f91dfdbf /target/linux
parentde499573006ab4f32ded9fd66a62ec5e0c183e8a (diff)
downloadupstream-6cf1dfd7e1d6b5c6a94b87eb065408bb489574c0.tar.gz
upstream-6cf1dfd7e1d6b5c6a94b87eb065408bb489574c0.tar.bz2
upstream-6cf1dfd7e1d6b5c6a94b87eb065408bb489574c0.zip
ath79: add support for Teltonika RUT230 v1
This commit adds support for the Teltonika RUT230 v1, a Atheros AR9331 based router with a Quectel UC20 UMTS modem. Hardware -------- Atheros AR9331 16 MB SPI-NOR XTX XT25F128B 64M DDR2 memory Atheros AR9331 1T1R 802.11bgn Wireless Boootloader: pepe2k U-Boot mod Hardware-Revision ----------------- There are two board revisions of the RUT230, a v0 and v1. A HW version is silkscreened on the top of the PCBs front side as well as shown in the Teltonika UI. However, this looks to be a different identifier, as the GPl dump shows this silkscreened / UI shown version are internally treated identically. Th following mapping has been obtained from the latest GPl dump. HW Ver 01 - 04 --> v0 HW Ver > 05 --> v1 My board was a HW Ver 09 and is treated as a v1. Installation ------------ While attaching power, hold down the reset button and release it after the signal LEDs flashed 3 times. Attach your Computer with the devices LAN port and assign yourself the IPv4 address 192.168.1.10/24. Open a web browser, navigate to 192.168.1.1. Upload the OpenWrt factory image. The device will install OpenWrt and automatically reboots afterwards. You can use the smae procedure with the stock firmware to return back to the vendor firmware. Signed-off-by: David Bauer <mail@david-bauer.net>
Diffstat (limited to 'target/linux')
-rw-r--r--target/linux/ath79/dts/ar9331_teltonika_rut230-v1.dts193
-rw-r--r--target/linux/ath79/generic/base-files/etc/board.d/01_leds4
-rw-r--r--target/linux/ath79/image/generic.mk35
3 files changed, 230 insertions, 2 deletions
diff --git a/target/linux/ath79/dts/ar9331_teltonika_rut230-v1.dts b/target/linux/ath79/dts/ar9331_teltonika_rut230-v1.dts
new file mode 100644
index 0000000000..c394cf1cb8
--- /dev/null
+++ b/target/linux/ath79/dts/ar9331_teltonika_rut230-v1.dts
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: GPL-2.0-or-later OR MIT
+
+#include "ar9331.dtsi"
+
+#include <dt-bindings/gpio/gpio.h>
+#include <dt-bindings/input/input.h>
+
+/ {
+ model = "Teltonika RUT230 v1";
+ compatible = "teltonika,rut230-v1", "qca,ar9331";
+
+ aliases {
+ label-mac-device = &wmac;
+ led-boot = &led_ss0;
+ led-failsafe = &led_ss0;
+ led-upgrade = &led_ss0;
+ };
+
+ keys {
+ compatible = "gpio-keys";
+
+ reset {
+ label = "reset";
+ linux,code = <KEY_RESTART>;
+ gpios = <&gpio 22 GPIO_ACTIVE_HIGH>;
+ debounce-interval = <60>;
+ };
+
+ input {
+ label = "input";
+ linux,code = <BTN_0>;
+ gpios = <&gpio 16 GPIO_ACTIVE_LOW>;
+ debounce-interval = <60>;
+ };
+
+ sim-tray {
+ label = "sim-tray";
+ linux,code = <BTN_1>;
+ gpios = <&gpio 20 GPIO_ACTIVE_LOW>;
+ debounce-interval = <60>;
+ };
+ };
+
+ leds {
+ compatible = "gpio-leds";
+ pinctrl-names = "default";
+ pinctrl-0 = <&switch_led_disable_pins>;
+
+ led_ss0: signal-strength-0 {
+ label = "green:signal-strength-0";
+ gpios = <&gpio 23 GPIO_ACTIVE_HIGH>;
+ };
+
+ signal-strength-1 {
+ label = "green:signal-strength-1";
+ gpios = <&gpio 7 GPIO_ACTIVE_HIGH>;
+ };
+
+ signal-strength-2 {
+ label = "green:signal-strength-2";
+ gpios = <&gpio 6 GPIO_ACTIVE_HIGH>;
+ };
+
+ signal-strength-3 {
+ label = "green:signal-strength-3";
+ gpios = <&gpio 26 GPIO_ACTIVE_HIGH>;
+ };
+
+ signal-strength-4 {
+ label = "green:signal-strength4";
+ gpios = <&gpio 27 GPIO_ACTIVE_HIGH>;
+ };
+
+ 2g {
+ label = "green:2g";
+ gpios = <&gpio 8 GPIO_ACTIVE_HIGH>;
+ };
+
+ 3g {
+ label = "green:3g";
+ gpios = <&gpio 24 GPIO_ACTIVE_HIGH>;
+ };
+
+ lan {
+ label = "green:lan";
+ gpios = <&gpio 14 GPIO_ACTIVE_LOW>;
+ /* GPIO 13 - ACTIVE HIGH for hwrev 0 */
+ };
+
+ wan {
+ label = "green:wan";
+ gpios = <&gpio 17 GPIO_ACTIVE_LOW>;
+ /* GPIO 14 - ACTIVE HIGH for hwrev 0 */
+ };
+
+ /* 4G LED - GPIO21 ACTIVE_HIGH for RUT240 */
+ };
+
+ reg_usb_vbus: reg_usb_vbus {
+ compatible = "regulator-fixed";
+ regulator-name = "usb_vbus";
+ regulator-min-microvolt = <5000000>;
+ regulator-max-microvolt = <5000000>;
+ gpio = <&gpio 19 GPIO_ACTIVE_HIGH>;
+ enable-active-high;
+ };
+};
+
+&eth0 {
+ status = "okay";
+
+ mtd-mac-address = <&config 0x0>;
+};
+
+&eth1 {
+ status = "okay";
+
+ mtd-mac-address = <&config 0x0>;
+ mtd-mac-address-increment = <1>;
+};
+
+&spi {
+ status = "okay";
+
+ flash@0 {
+ compatible = "jedec,spi-nor";
+ reg = <0>;
+ spi-max-frequency = <30000000>;
+
+ partitions {
+ compatible = "fixed-partitions";
+ #address-cells = <1>;
+ #size-cells = <1>;
+
+ partition@0 {
+ label = "u-boot";
+ reg = <0x0 0x20000>;
+ read-only;
+ };
+
+ config: partition@20000 {
+ label = "config";
+ reg = <0x20000 0x10000>;
+ read-only;
+ };
+
+ art: partition@30000 {
+ label = "art";
+ reg = <0x30000 0x10000>;
+ read-only;
+ };
+
+ partition@40000 {
+ compatible = "tplink,firmware";
+ label = "firmware";
+ reg = <0x40000 0xf30000>;
+ };
+
+ partition@f70000 {
+ label = "event-log";
+ reg = <0xf70000 0x90000>;
+ read-only;
+ };
+ };
+ };
+};
+
+&usb {
+ dr_mode = "host";
+ vbus-supply = <&reg_usb_vbus>;
+ status = "okay";
+};
+
+&gpio {
+ modem-power {
+ gpio-hog;
+ output-low;
+ gpios = <18 GPIO_ACTIVE_HIGH>;
+ line-name = "modem-power";
+ };
+};
+
+&usb_phy {
+ status = "okay";
+};
+
+&wmac {
+ status = "okay";
+
+ mtd-cal-data = <&art 0x1000>;
+ mtd-mac-address = <&config 0x0>;
+ mtd-mac-address-increment = <2>;
+};
diff --git a/target/linux/ath79/generic/base-files/etc/board.d/01_leds b/target/linux/ath79/generic/base-files/etc/board.d/01_leds
index d8e3d65967..c844c70e46 100644
--- a/target/linux/ath79/generic/base-files/etc/board.d/01_leds
+++ b/target/linux/ath79/generic/base-files/etc/board.d/01_leds
@@ -276,6 +276,10 @@ qihoo,c301)
samsung,wam250)
ucidef_set_led_netdev "lan" "LAN" "white:lan" "eth0"
;;
+teltonika,rut230-v1)
+ ucidef_set_led_netdev "wan" "WAN" "green:wan" "eth1"
+ ucidef_set_led_switch "lan" "LAN" "green:lan" "switch0" "0x04"
+ ;;
tplink,archer-a7-v5|\
tplink,archer-c7-v4|\
tplink,archer-c7-v5)
diff --git a/target/linux/ath79/image/generic.mk b/target/linux/ath79/image/generic.mk
index 9d0be2b86b..ab875bd220 100644
--- a/target/linux/ath79/image/generic.mk
+++ b/target/linux/ath79/image/generic.mk
@@ -142,11 +142,20 @@ define Build/teltonika-fw-fake-checksum
# from begin of the firmware file) with 16 bytes stored just before
# 0xdeadc0de marker. Values are only compared, MD5 sum is not verified.
let \
- offs="$$(stat -c%s $@) - 20"; \
+ offs="$$(stat -c%s $@) - $(1)"; \
dd if=$@ bs=1 count=16 skip=76 |\
dd of=$@ bs=1 count=16 seek=$$offs conv=notrunc
endef
+define Build/teltonika-v1-header
+ $(STAGING_DIR_HOST)/bin/mktplinkfw \
+ -c -H $(TPLINK_HWID) -W $(TPLINK_HWREV) -L $(KERNEL_LOADADDR) \
+ -E $(if $(KERNEL_ENTRY),$(KERNEL_ENTRY),$(KERNEL_LOADADDR)) \
+ -m $(TPLINK_HEADER_VERSION) -N "$(VERSION_DIST)" -V "RUT2xx " \
+ -k $@ -o $@.new $(1)
+ @mv $@.new $@
+endef
+
define Build/wrgg-pad-rootfs
$(STAGING_DIR_HOST)/bin/padjffs2 $(IMAGE_ROOTFS) -c 64 >>$@
endef
@@ -2182,6 +2191,28 @@ define Device/telco_t1
endef
TARGET_DEVICES += telco_t1
+define Device/teltonika_rut230-v1
+ SOC := ar9331
+ DEVICE_VENDOR := Teltonika
+ DEVICE_MODEL := RUT230
+ DEVICE_VARIANT := v1
+ DEVICE_PACKAGES := kmod-usb-chipidea2 kmod-usb-acm kmod-usb-net-qmi-wwan \
+ uqmi -uboot-envtools
+ IMAGE_SIZE := 15552k
+ TPLINK_HWID := 0x32200002
+ TPLINK_HWREV := 0x1
+ TPLINK_HEADER_VERSION := 1
+ KERNEL := kernel-bin | append-dtb | lzma | teltonika-v1-header
+ KERNEL_INITRAMFS := kernel-bin | append-dtb | lzma | uImage lzma
+ IMAGES += factory.bin
+ IMAGE/factory.bin := append-kernel | pad-to $$$$(BLOCKSIZE) | append-rootfs |\
+ pad-rootfs | pad-extra 64 | teltonika-fw-fake-checksum 54 | check-size
+ IMAGE/sysupgrade.bin := append-kernel | pad-to $$$$(BLOCKSIZE) |\
+ append-rootfs | pad-rootfs | append-metadata |\
+ check-size
+endef
+TARGET_DEVICES += teltonika_rut230-v1
+
define Device/teltonika_rut955
SOC := ar9344
DEVICE_VENDOR := Teltonika
@@ -2196,7 +2227,7 @@ define Device/teltonika_rut955
KERNEL_INITRAMFS := kernel-bin | append-dtb | lzma | uImage lzma
IMAGES += factory.bin
IMAGE/factory.bin := append-kernel | pad-to $$$$(BLOCKSIZE) | append-rootfs |\
- pad-rootfs | teltonika-fw-fake-checksum | append-string master |\
+ pad-rootfs | teltonika-fw-fake-checksum 20 | append-string master |\
append-md5sum-bin | check-size
IMAGE/sysupgrade.bin := append-kernel | pad-to $$$$(BLOCKSIZE) |\
append-rootfs | pad-rootfs | append-metadata |\
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
/*
 * xenpm.c: list the power information of the available processors
 * Copyright (c) 2008, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU General Public License,
 * version 2, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place - Suite 330, Boston, MA 02111-1307 USA.
 */
#define MAX_NR_CPU 512

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <signal.h>

#include <xenctrl.h>
#include <inttypes.h>
#include <sys/time.h>

#define ARRAY_SIZE(a) (sizeof (a) / sizeof ((a)[0]))

#define CPUFREQ_TURBO_DISABLED      -1
#define CPUFREQ_TURBO_UNSUPPORTED   0
#define CPUFREQ_TURBO_ENABLED       1

static xc_interface *xc_handle;
static int max_cpu_nr;

/* help message */
void show_help(void)
{
    fprintf(stderr,
            "xen power management control tool\n\n"
            "usage: xenpm <command> [args]\n\n"
            "xenpm command list:\n\n"
            " get-cpuidle-states    [cpuid]       list cpu idle info of CPU <cpuid> or all\n"
            " get-cpufreq-states    [cpuid]       list cpu freq info of CPU <cpuid> or all\n"
            " get-cpufreq-para      [cpuid]       list cpu freq parameter of CPU <cpuid> or all\n"
            " set-scaling-maxfreq   [cpuid] <HZ>  set max cpu frequency <HZ> on CPU <cpuid>\n"
            "                                     or all CPUs\n"
            " set-scaling-minfreq   [cpuid] <HZ>  set min cpu frequency <HZ> on CPU <cpuid>\n"
            "                                     or all CPUs\n"
            " set-scaling-speed     [cpuid] <num> set scaling speed on CPU <cpuid> or all\n"
            "                                     it is used in userspace governor.\n"
            " set-scaling-governor  [cpuid] <gov> set scaling governor on CPU <cpuid> or all\n"
            "                                     as userspace/performance/powersave/ondemand\n"
            " set-sampling-rate     [cpuid] <num> set sampling rate on CPU <cpuid> or all\n"
            "                                     it is used in ondemand governor.\n"
            " set-up-threshold      [cpuid] <num> set up threshold on CPU <cpuid> or all\n"
            "                                     it is used in ondemand governor.\n"
            " get-cpu-topology                    get thread/core/socket topology info\n"
            " set-sched-smt           enable|disable enable/disable scheduler smt power saving\n"
            " set-vcpu-migration-delay      <num> set scheduler vcpu migration delay in us\n"
            " get-vcpu-migration-delay            get scheduler vcpu migration delay\n"
            " set-max-cstate        <num>         set the C-State limitation (<num> >= 0)\n"
            " start [seconds]                     start collect Cx/Px statistics,\n"
            "                                     output after CTRL-C or SIGINT or several seconds.\n"
            " enable-turbo-mode     [cpuid]       enable Turbo Mode for processors that support it.\n"
            " disable-turbo-mode    [cpuid]       disable Turbo Mode for processors that support it.\n"
            );
}
/* wrapper function */
void help_func(int argc, char *argv[])
{
    show_help();
}

static void print_cxstat(int cpuid, struct xc_cx_stat *cxstat)
{
    int i;

    printf("cpu id               : %d\n", cpuid);
    printf("total C-states       : %d\n", cxstat->nr);
    printf("idle time(ms)        : %"PRIu64"\n",
           cxstat->idle_time/1000000UL);
    for ( i = 0; i < cxstat->nr; i++ )
    {
        printf("C%d                   : transition [%020"PRIu64"]\n",
               i, cxstat->triggers[i]);
        printf("                       residency  [%020"PRIu64" ms]\n",
               cxstat->residencies[i]/1000000UL);
    }
    printf("pc3                  : [%020"PRIu64" ms]\n"
           "pc6                  : [%020"PRIu64" ms]\n"
           "pc7                  : [%020"PRIu64" ms]\n",
           cxstat->pc3/1000000UL, cxstat->pc6/1000000UL, cxstat->pc7/1000000UL);
    printf("cc3                  : [%020"PRIu64" ms]\n"
           "cc6                  : [%020"PRIu64" ms]\n",
           cxstat->cc3/1000000UL, cxstat->cc6/1000000UL);
    printf("\n");
}

/* show cpu idle information on CPU cpuid */
static int get_cxstat_by_cpuid(xc_interface *xc_handle, int cpuid, struct xc_cx_stat *cxstat)
{
    int ret = 0;
    int max_cx_num = 0;

    ret = xc_pm_get_max_cx(xc_handle, cpuid, &max_cx_num);
    if ( ret )
        return errno;

    if ( !cxstat )
        return -EINVAL;

    cxstat->triggers = malloc(max_cx_num * sizeof(uint64_t));
    if ( !cxstat->triggers )
        return -ENOMEM;
    cxstat->residencies = malloc(max_cx_num * sizeof(uint64_t));
    if ( !cxstat->residencies )
    {
        free(cxstat->triggers);
        return -ENOMEM;
    }

    ret = xc_pm_get_cxstat(xc_handle, cpuid, cxstat);
    if( ret )
    {
        int temp = errno;
        free(cxstat->triggers);
        free(cxstat->residencies);
        cxstat->triggers = NULL;
        cxstat->residencies = NULL;
        return temp;
    }

    return 0;
}

static int show_max_cstate(xc_interface *xc_handle)
{
    int ret = 0;
    uint32_t value;

    if ( (ret = xc_get_cpuidle_max_cstate(xc_handle, &value)) )
        return ret;

    printf("Max C-state: C%d\n\n", value);
    return 0;
}

static int show_cxstat_by_cpuid(xc_interface *xc_handle, int cpuid)
{
    int ret = 0;
    struct xc_cx_stat cxstatinfo;

    ret = get_cxstat_by_cpuid(xc_handle, cpuid, &cxstatinfo);
    if ( ret )
        return ret;

    print_cxstat(cpuid, &cxstatinfo);

    free(cxstatinfo.triggers);
    free(cxstatinfo.residencies);
    return 0;
}

void cxstat_func(int argc, char *argv[])
{
    int cpuid = -1;

    if ( argc > 0 && sscanf(argv[0], "%d", &cpuid) != 1 )
        cpuid = -1;

    if ( cpuid >= max_cpu_nr )
        cpuid = -1;

    show_max_cstate(xc_handle);

    if ( cpuid < 0 )
    {
        /* show cxstates on all cpus */
        int i;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( show_cxstat_by_cpuid(xc_handle, i) == -ENODEV )
                break;
    }
    else
        show_cxstat_by_cpuid(xc_handle, cpuid);
}

static void print_pxstat(int cpuid, struct xc_px_stat *pxstat)
{
    int i;

    printf("cpu id               : %d\n", cpuid);
    printf("total P-states       : %d\n", pxstat->total);
    printf("usable P-states      : %d\n", pxstat->usable);
    printf("current frequency    : %"PRIu64" MHz\n",
           pxstat->pt[pxstat->cur].freq);
    for ( i = 0; i < pxstat->total; i++ )
    {
        if ( pxstat->cur == i )
            printf("*P%d", i);
        else
            printf("P%d ", i);
        printf("                  : freq       [%04"PRIu64" MHz]\n",
               pxstat->pt[i].freq);
        printf("                       transition [%020"PRIu64"]\n",
               pxstat->pt[i].count);
        printf("                       residency  [%020"PRIu64" ms]\n",
               pxstat->pt[i].residency/1000000UL);
    }
    printf("\n");
}

/* show cpu frequency information on CPU cpuid */
static int get_pxstat_by_cpuid(xc_interface *xc_handle, int cpuid, struct xc_px_stat *pxstat)
{
    int ret = 0;
    int max_px_num = 0;

    ret = xc_pm_get_max_px(xc_handle, cpuid, &max_px_num);
    if ( ret )
        return errno;

    if ( !pxstat)
        return -EINVAL;

    pxstat->trans_pt = malloc(max_px_num * max_px_num *
                              sizeof(uint64_t));
    if ( !pxstat->trans_pt )
        return -ENOMEM;
    pxstat->pt = malloc(max_px_num * sizeof(struct xc_px_val));
    if ( !pxstat->pt )
    {
        free(pxstat->trans_pt);
        return -ENOMEM;
    }

    ret = xc_pm_get_pxstat(xc_handle, cpuid, pxstat);
    if( ret )
    {
        int temp = errno;
        free(pxstat->trans_pt);
        free(pxstat->pt);
        pxstat->trans_pt = NULL;
        pxstat->pt = NULL;
        return temp;
    }

    return 0;
}

/* show cpu actual average freq information on CPU cpuid */
static int get_avgfreq_by_cpuid(xc_interface *xc_handle, int cpuid, int *avgfreq)
{
    int ret = 0;

    ret = xc_get_cpufreq_avgfreq(xc_handle, cpuid, avgfreq);
    if ( ret )
    {
        return errno;
    }

    return 0;
}

static int show_pxstat_by_cpuid(xc_interface *xc_handle, int cpuid)
{
    int ret = 0;
    struct xc_px_stat pxstatinfo;

    ret = get_pxstat_by_cpuid(xc_handle, cpuid, &pxstatinfo);
    if ( ret )
        return ret;

    print_pxstat(cpuid, &pxstatinfo);

    free(pxstatinfo.trans_pt);
    free(pxstatinfo.pt);
    return 0;
}

void pxstat_func(int argc, char *argv[])
{
    int cpuid = -1;

    if ( argc > 0 && sscanf(argv[0], "%d", &cpuid) != 1 )
        cpuid = -1;

    if ( cpuid >= max_cpu_nr )
        cpuid = -1;

    if ( cpuid < 0 )
    {
        /* show pxstates on all cpus */
        int i;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( show_pxstat_by_cpuid(xc_handle, i) == -ENODEV )
                break;
    }
    else
        show_pxstat_by_cpuid(xc_handle, cpuid);
}

static uint64_t usec_start, usec_end;
static struct xc_cx_stat *cxstat, *cxstat_start, *cxstat_end;
static struct xc_px_stat *pxstat, *pxstat_start, *pxstat_end;
static int *avgfreq;
static uint64_t *sum, *sum_cx, *sum_px;

static void signal_int_handler(int signo)
{
    int i, j, k, ret;
    struct timeval tv;
    int cx_cap = 0, px_cap = 0;
    uint32_t cpu_to_core[MAX_NR_CPU];
    uint32_t cpu_to_socket[MAX_NR_CPU];
    uint32_t cpu_to_node[MAX_NR_CPU];
    xc_topologyinfo_t info = { 0 };

    if ( gettimeofday(&tv, NULL) == -1 )
    {
        fprintf(stderr, "failed to get timeofday\n");
        return ;
    }
    usec_end = tv.tv_sec * 1000000UL + tv.tv_usec;

    if ( get_cxstat_by_cpuid(xc_handle, 0, NULL) != -ENODEV )
    {
        cx_cap = 1;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( !get_cxstat_by_cpuid(xc_handle, i, &cxstat_end[i]) )
                for ( j = 0; j < cxstat_end[i].nr; j++ )
                    sum_cx[i] += cxstat_end[i].residencies[j] -
                                 cxstat_start[i].residencies[j];
    }

    if ( get_pxstat_by_cpuid(xc_handle, 0, NULL) != -ENODEV )
    {
        px_cap = 1;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( !get_pxstat_by_cpuid(xc_handle, i , &pxstat_end[i]) )
                for ( j = 0; j < pxstat_end[i].total; j++ )
                    sum_px[i] += pxstat_end[i].pt[j].residency -
                                 pxstat_start[i].pt[j].residency;
    }

    for ( i = 0; i < max_cpu_nr; i++ )
        get_avgfreq_by_cpuid(xc_handle, i, &avgfreq[i]);

    printf("Elapsed time (ms): %"PRIu64"\n", (usec_end - usec_start) / 1000UL);
    for ( i = 0; i < max_cpu_nr; i++ )
    {
        uint64_t res, triggers;
        double avg_res;

        printf("\nCPU%d:\tResidency(ms)\t\tAvg Res(ms)\n",i);
        if ( cx_cap && sum_cx[i] > 0 )
        {
            for ( j = 0; j < cxstat_end[i].nr; j++ )
            {
                res = cxstat_end[i].residencies[j] -
                    cxstat_start[i].residencies[j];
                triggers = cxstat_end[i].triggers[j] -
                    cxstat_start[i].triggers[j];
                avg_res = (triggers==0) ? 0: (double)res/triggers/1000000.0;
                printf("  C%d\t%"PRIu64"\t(%5.2f%%)\t%.2f\n", j, res/1000000UL,
                        100 * res / (double)sum_cx[i], avg_res );
            }
            printf("\n");
        }
        if ( px_cap && sum_px[i]>0 )
        {
            for ( j = 0; j < pxstat_end[i].total; j++ )
            {
                res = pxstat_end[i].pt[j].residency -
                    pxstat_start[i].pt[j].residency;
                printf("  P%d\t%"PRIu64"\t(%5.2f%%)\n", j,
                        res / 1000000UL, 100UL * res / (double)sum_px[i]);
            }
        }
    }

    set_xen_guest_handle(info.cpu_to_core, cpu_to_core);
    set_xen_guest_handle(info.cpu_to_socket, cpu_to_socket);
    set_xen_guest_handle(info.cpu_to_node, cpu_to_node);
    info.max_cpu_index = MAX_NR_CPU - 1;

    ret = xc_topologyinfo(xc_handle, &info);
    if ( !ret )
    {
        uint32_t socket_ids[MAX_NR_CPU];
        uint32_t core_ids[MAX_NR_CPU];
        uint32_t socket_nr = 0;
        uint32_t core_nr = 0;

        if ( info.max_cpu_index > MAX_NR_CPU - 1 )
            info.max_cpu_index = MAX_NR_CPU - 1;
        /* check validity */
        for ( i = 0; i <= info.max_cpu_index; i++ )
        {
            if ( cpu_to_core[i] == INVALID_TOPOLOGY_ID ||
                 cpu_to_socket[i] == INVALID_TOPOLOGY_ID )
                break;
        }
        if ( i > info.max_cpu_index )
        {
            /* find socket nr & core nr per socket */
            for ( i = 0; i <= info.max_cpu_index; i++ )
            {
                for ( j = 0; j < socket_nr; j++ )
                    if ( cpu_to_socket[i] == socket_ids[j] )
                        break;
                if ( j == socket_nr )
                {
                    socket_ids[j] = cpu_to_socket[i];
                    socket_nr++;
                }

                for ( j = 0; j < core_nr; j++ )
                    if ( cpu_to_core[i] == core_ids[j] )
                        break;
                if ( j == core_nr )
                {
                    core_ids[j] = cpu_to_core[i];
                    core_nr++;
                }
            }

            /* print out CC? and PC? */
            for ( i = 0; i < socket_nr; i++ )
            {
                uint64_t res;
                for ( j = 0; j <= info.max_cpu_index; j++ )
                {
                    if ( cpu_to_socket[j] == socket_ids[i] )
                        break;
                }
                printf("Socket %d\n", socket_ids[i]);
                res = cxstat_end[j].pc3 - cxstat_start[j].pc3;
                printf("\tPC3\t%"PRIu64" ms\t%.2f%%\n",  res / 1000000UL, 
                       100UL * res / (double)sum_cx[j]);
                res = cxstat_end[j].pc6 - cxstat_start[j].pc6;
                printf("\tPC6\t%"PRIu64" ms\t%.2f%%\n",  res / 1000000UL, 
                       100UL * res / (double)sum_cx[j]);
                res = cxstat_end[j].pc7 - cxstat_start[j].pc7;
                printf("\tPC7\t%"PRIu64" ms\t%.2f%%\n",  res / 1000000UL, 
                       100UL * res / (double)sum_cx[j]);
                for ( k = 0; k < core_nr; k++ )
                {
                    for ( j = 0; j <= info.max_cpu_index; j++ )
                    {
                        if ( cpu_to_socket[j] == socket_ids[i] &&
                             cpu_to_core[j] == core_ids[k] )
                            break;
                    }
                    printf("\t Core %d CPU %d\n", core_ids[k], j);
                    res = cxstat_end[j].cc3 - cxstat_start[j].cc3;
                    printf("\t\tCC3\t%"PRIu64" ms\t%.2f%%\n",  res / 1000000UL, 
                           100UL * res / (double)sum_cx[j]);
                    res = cxstat_end[j].cc6 - cxstat_start[j].cc6;
                    printf("\t\tCC6\t%"PRIu64" ms\t%.2f%%\n",  res / 1000000UL, 
                           100UL * res / (double)sum_cx[j]);
                    printf("\n");

                }
            }
        }
        printf("  Avg freq\t%d\tKHz\n", avgfreq[i]);
    }

    /* some clean up and then exits */
    for ( i = 0; i < 2 * max_cpu_nr; i++ )
    {
        free(cxstat[i].triggers);
        free(cxstat[i].residencies);
        free(pxstat[i].trans_pt);
        free(pxstat[i].pt);
    }
    free(cxstat);
    free(pxstat);
    free(sum);
    free(avgfreq);
    xc_interface_close(xc_handle);
    exit(0);
}

void start_gather_func(int argc, char *argv[])
{
    int i;
    struct timeval tv;
    int timeout = 0;

    if ( argc == 1 )
    {
        sscanf(argv[0], "%d", &timeout);
        if ( timeout <= 0 )
            fprintf(stderr, "failed to set timeout seconds, falling back...\n");
        else
            printf("Timeout set to %d seconds\n", timeout);
    }

    if ( gettimeofday(&tv, NULL) == -1 )
    {
        fprintf(stderr, "failed to get timeofday\n");
        return ;
    }
    usec_start = tv.tv_sec * 1000000UL + tv.tv_usec;

    sum = malloc(sizeof(uint64_t) * 2 * max_cpu_nr);
    if ( sum == NULL )
        return ;
    cxstat = malloc(sizeof(struct xc_cx_stat) * 2 * max_cpu_nr);
    if ( cxstat == NULL )
    {
        free(sum);
        return ;
    }
    pxstat = malloc(sizeof(struct xc_px_stat) * 2 * max_cpu_nr);
    if ( pxstat == NULL )
    {
        free(sum);
        free(cxstat);
        return ;
    }
    avgfreq = malloc(sizeof(int) * max_cpu_nr);
    if ( avgfreq == NULL )
    {
        free(sum);
        free(cxstat);
        free(pxstat);
        return ;
    }
    memset(sum, 0, sizeof(uint64_t) * 2 * max_cpu_nr);
    memset(cxstat, 0, sizeof(struct xc_cx_stat) * 2 * max_cpu_nr);
    memset(pxstat, 0, sizeof(struct xc_px_stat) * 2 * max_cpu_nr);
    memset(avgfreq, 0, sizeof(int) * max_cpu_nr);
    sum_cx = sum;
    sum_px = sum + max_cpu_nr;
    cxstat_start = cxstat;
    cxstat_end = cxstat + max_cpu_nr;
    pxstat_start = pxstat;
    pxstat_end = pxstat + max_cpu_nr;

    if ( get_cxstat_by_cpuid(xc_handle, 0, NULL) == -ENODEV &&
         get_pxstat_by_cpuid(xc_handle, 0, NULL) == -ENODEV )
    {
        fprintf(stderr, "Xen cpu idle and frequency is disabled!\n");
        return ;
    }

    for ( i = 0; i < max_cpu_nr; i++ )
    {
        get_cxstat_by_cpuid(xc_handle, i, &cxstat_start[i]);
        get_pxstat_by_cpuid(xc_handle, i, &pxstat_start[i]);
        get_avgfreq_by_cpuid(xc_handle, i, &avgfreq[i]);
    }

    if (signal(SIGINT, signal_int_handler) == SIG_ERR)
    {
        fprintf(stderr, "failed to set signal int handler\n");
        free(sum);
        free(pxstat);
        free(cxstat);
        free(avgfreq);
        return ;
    }

    if ( timeout > 0 )
    {
        if ( signal(SIGALRM, signal_int_handler) == SIG_ERR )
        {
            fprintf(stderr, "failed to set signal alarm handler\n");
            free(sum);
            free(pxstat);
            free(cxstat);
            free(avgfreq);
            return ;
        }
        alarm(timeout);
    }

    printf("Start sampling, waiting for CTRL-C or SIGINT or SIGALARM signal ...\n");

    pause();
}

/* print out parameters about cpu frequency */
static void print_cpufreq_para(int cpuid, struct xc_get_cpufreq_para *p_cpufreq)
{
    int i;

    printf("cpu id               : %d\n", cpuid);

    printf("affected_cpus        :");
    for ( i = 0; i < p_cpufreq->cpu_num; i++ )
        printf(" %d", p_cpufreq->affected_cpus[i]);
    printf("\n");

    printf("cpuinfo frequency    : max [%u] min [%u] cur [%u]\n",
           p_cpufreq->cpuinfo_max_freq,
           p_cpufreq->cpuinfo_min_freq,
           p_cpufreq->cpuinfo_cur_freq);

    printf("scaling_driver       : %s\n", p_cpufreq->scaling_driver);

    printf("scaling_avail_gov    : %s\n",
           p_cpufreq->scaling_available_governors);

    printf("current_governor     : %s\n", p_cpufreq->scaling_governor);
    if ( !strncmp(p_cpufreq->scaling_governor,
                  "userspace", CPUFREQ_NAME_LEN) )
    {
        printf("  userspace specific :\n");
        printf("    scaling_setspeed : %u\n",
               p_cpufreq->u.userspace.scaling_setspeed);
    }
    else if ( !strncmp(p_cpufreq->scaling_governor,
                       "ondemand", CPUFREQ_NAME_LEN) )
    {
        printf("  ondemand specific  :\n");
        printf("    sampling_rate    : max [%u] min [%u] cur [%u]\n",
               p_cpufreq->u.ondemand.sampling_rate_max,
               p_cpufreq->u.ondemand.sampling_rate_min,
               p_cpufreq->u.ondemand.sampling_rate);
        printf("    up_threshold     : %u\n",
               p_cpufreq->u.ondemand.up_threshold);
    }

    printf("scaling_avail_freq   :");
    for ( i = 0; i < p_cpufreq->freq_num; i++ )
        if ( p_cpufreq->scaling_available_frequencies[i] ==
             p_cpufreq->scaling_cur_freq )
            printf(" *%d", p_cpufreq->scaling_available_frequencies[i]);
        else
            printf(" %d", p_cpufreq->scaling_available_frequencies[i]);
    printf("\n");

    printf("scaling frequency    : max [%u] min [%u] cur [%u]\n",
           p_cpufreq->scaling_max_freq,
           p_cpufreq->scaling_min_freq,
           p_cpufreq->scaling_cur_freq);
    if (p_cpufreq->turbo_enabled != CPUFREQ_TURBO_UNSUPPORTED) {
           printf("turbo mode           : ");
           if (p_cpufreq->turbo_enabled == CPUFREQ_TURBO_ENABLED)
               printf("enabled\n");
           else
               printf("disabled\n");
    }
    printf("\n");
}

/* show cpu frequency parameters information on CPU cpuid */
static int show_cpufreq_para_by_cpuid(xc_interface *xc_handle, int cpuid)
{
    int ret = 0;
    struct xc_get_cpufreq_para cpufreq_para, *p_cpufreq = &cpufreq_para;

    p_cpufreq->cpu_num = 0;
    p_cpufreq->freq_num = 0;
    p_cpufreq->gov_num = 0;
    p_cpufreq->affected_cpus = NULL;
    p_cpufreq->scaling_available_frequencies = NULL;
    p_cpufreq->scaling_available_governors = NULL;
    p_cpufreq->turbo_enabled = 0;

    do
    {
        free(p_cpufreq->affected_cpus);
        free(p_cpufreq->scaling_available_frequencies);
        free(p_cpufreq->scaling_available_governors);

        p_cpufreq->affected_cpus = NULL;
        p_cpufreq->scaling_available_frequencies = NULL;
        p_cpufreq->scaling_available_governors = NULL;

        if (!(p_cpufreq->affected_cpus =
              malloc(p_cpufreq->cpu_num * sizeof(uint32_t))))
        {
            fprintf(stderr,
                    "[CPU%d] failed to malloc for affected_cpus\n",
                    cpuid);
            ret = -ENOMEM;
            goto out;
        }
        if (!(p_cpufreq->scaling_available_frequencies =
              malloc(p_cpufreq->freq_num * sizeof(uint32_t))))
        {
            fprintf(stderr,
                    "[CPU%d] failed to malloc for scaling_available_frequencies\n",
                    cpuid);
            ret = -ENOMEM;
            goto out;
        }
        if (!(p_cpufreq->scaling_available_governors =
              malloc(p_cpufreq->gov_num * CPUFREQ_NAME_LEN * sizeof(char))))
        {
            fprintf(stderr,
                    "[CPU%d] failed to malloc for scaling_available_governors\n",
                    cpuid);
            ret = -ENOMEM;
            goto out;
        }

        ret = xc_get_cpufreq_para(xc_handle, cpuid, p_cpufreq);
    } while ( ret && errno == EAGAIN );

    if ( ret == 0 )
        print_cpufreq_para(cpuid, p_cpufreq);
    else if ( errno == ENODEV )
    {
        ret = -ENODEV;
        fprintf(stderr, "Xen cpufreq is not enabled!\n");
    }
    else
        fprintf(stderr,
                "[CPU%d] failed to get cpufreq parameter\n",
                cpuid);

out:
    free(p_cpufreq->scaling_available_governors);
    free(p_cpufreq->scaling_available_frequencies);
    free(p_cpufreq->affected_cpus);

    return ret;
}

void cpufreq_para_func(int argc, char *argv[])
{
    int cpuid = -1;

    if ( argc > 0 && sscanf(argv[0], "%d", &cpuid) != 1 )
        cpuid = -1;

    if ( cpuid >= max_cpu_nr )
        cpuid = -1;

    if ( cpuid < 0 )
    {
        /* show cpu freqency information on all cpus */
        int i;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( show_cpufreq_para_by_cpuid(xc_handle, i) == -ENODEV )
                break;
    }
    else
        show_cpufreq_para_by_cpuid(xc_handle, cpuid);
}

void scaling_max_freq_func(int argc, char *argv[])
{
    int cpuid = -1, freq = -1;

    if ( (argc >= 2 && (sscanf(argv[1], "%d", &freq) != 1 ||
                        sscanf(argv[0], "%d", &cpuid) != 1)) ||
         (argc == 1 && sscanf(argv[0], "%d", &freq) != 1 ) ||
         argc == 0 )
    {
        fprintf(stderr, "failed to set scaling max freq\n");
        return ;
    }

    if ( cpuid < 0 )
    {
        int i;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( xc_set_cpufreq_para(xc_handle, i, SCALING_MAX_FREQ, freq) )
                fprintf(stderr, "[CPU%d] failed to set scaling max freq\n", i);
    }
    else
    {
        if ( xc_set_cpufreq_para(xc_handle, cpuid, SCALING_MAX_FREQ, freq) )
            fprintf(stderr, "failed to set scaling max freq\n");
    }
}

void scaling_min_freq_func(int argc, char *argv[])
{
    int cpuid = -1, freq = -1;

    if ( (argc >= 2 && (sscanf(argv[1], "%d", &freq) != 1 ||
                        sscanf(argv[0], "%d", &cpuid) != 1) ) ||
         (argc == 1 && sscanf(argv[0], "%d", &freq) != 1 ) ||
         argc == 0 )
    {
        fprintf(stderr, "failed to set scaling min freq\n");
        return ;
    }

    if ( cpuid < 0 )
    {
        int i;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( xc_set_cpufreq_para(xc_handle, i, SCALING_MIN_FREQ, freq) )
                fprintf(stderr, "[CPU%d] failed to set scaling min freq\n", i);
    }
    else
    {
        if ( xc_set_cpufreq_para(xc_handle, cpuid, SCALING_MIN_FREQ, freq) )
            fprintf(stderr, "failed to set scaling min freq\n");
    }
}

void scaling_speed_func(int argc, char *argv[])
{
    int cpuid = -1, speed = -1;

    if ( (argc >= 2 && (sscanf(argv[1], "%d", &speed) != 1 ||
                        sscanf(argv[0], "%d", &cpuid) != 1) ) ||
         (argc == 1 && sscanf(argv[0], "%d", &speed) != 1 ) ||
         argc == 0 )
    {
        fprintf(stderr, "failed to set scaling speed\n");
        return ;
    }

    if ( cpuid < 0 )
    {
        int i;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( xc_set_cpufreq_para(xc_handle, i, SCALING_SETSPEED, speed) )
                fprintf(stderr, "[CPU%d] failed to set scaling speed\n", i);
    }
    else
    {
        if ( xc_set_cpufreq_para(xc_handle, cpuid, SCALING_SETSPEED, speed) )
            fprintf(stderr, "failed to set scaling speed\n");
    }
}

void scaling_sampling_rate_func(int argc, char *argv[])
{
    int cpuid = -1, rate = -1;

    if ( (argc >= 2 && (sscanf(argv[1], "%d", &rate) != 1 ||
                        sscanf(argv[0], "%d", &cpuid) != 1) ) ||
         (argc == 1 && sscanf(argv[0], "%d", &rate) != 1 ) ||
         argc == 0 )
    {
        fprintf(stderr, "failed to set scaling sampling rate\n");
        return ;
    }

    if ( cpuid < 0 )
    {
        int i;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( xc_set_cpufreq_para(xc_handle, i, SAMPLING_RATE, rate) )
                fprintf(stderr,
                        "[CPU%d] failed to set scaling sampling rate\n", i);
    }
    else
    {
        if ( xc_set_cpufreq_para(xc_handle, cpuid, SAMPLING_RATE, rate) )
            fprintf(stderr, "failed to set scaling sampling rate\n");
    }
}

void scaling_up_threshold_func(int argc, char *argv[])
{
    int cpuid = -1, threshold = -1;

    if ( (argc >= 2 && (sscanf(argv[1], "%d", &threshold) != 1 ||
                        sscanf(argv[0], "%d", &cpuid) != 1) ) ||
         (argc == 1 && sscanf(argv[0], "%d", &threshold) != 1 ) ||
         argc == 0 )
    {
        fprintf(stderr, "failed to set up scaling threshold\n");
        return ;
    }

    if ( cpuid < 0 )
    {
        int i;
        for ( i = 0; i < max_cpu_nr; i++ )
            if ( xc_set_cpufreq_para(xc_handle, i, UP_THRESHOLD, threshold) )
                fprintf(stderr,
                        "[CPU%d] failed to set up scaling threshold\n", i);
    }
    else
    {
        if ( xc_set_cpufreq_para(xc_handle, cpuid, UP_THRESHOLD, threshold) )
            fprintf(stderr, "failed to set up scaling threshold\n");