python_code
stringlengths
0
1.8M
repo_name
stringclasses
7 values
file_path
stringlengths
5
99
// SPDX-License-Identifier: GPL-2.0-or-later /* * sysfs.c sysfs ABI access functions for TMON program * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * Author: Jacob Pan <[email protected]> */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <dirent.h> #include <libintl.h> #include <limits.h> #include <ctype.h> #include <time.h> #include <syslog.h> #include <sys/time.h> #include <errno.h> #include "tmon.h" struct tmon_platform_data ptdata; const char *trip_type_name[] = { "critical", "hot", "passive", "active", }; int sysfs_set_ulong(char *path, char *filename, unsigned long val) { FILE *fd; int ret = -1; char filepath[PATH_MAX + 2]; /* NUL and '/' */ snprintf(filepath, sizeof(filepath), "%s/%s", path, filename); fd = fopen(filepath, "w"); if (!fd) { syslog(LOG_ERR, "Err: open %s: %s\n", __func__, filepath); return ret; } ret = fprintf(fd, "%lu", val); fclose(fd); return 0; } /* history of thermal data, used for control algo */ #define NR_THERMAL_RECORDS 3 struct thermal_data_record trec[NR_THERMAL_RECORDS]; int cur_thermal_record; /* index to the trec array */ static int sysfs_get_ulong(char *path, char *filename, unsigned long *p_ulong) { FILE *fd; int ret = -1; char filepath[PATH_MAX + 2]; /* NUL and '/' */ snprintf(filepath, sizeof(filepath), "%s/%s", path, filename); fd = fopen(filepath, "r"); if (!fd) { syslog(LOG_ERR, "Err: open %s: %s\n", __func__, filepath); return ret; } ret = fscanf(fd, "%lu", p_ulong); fclose(fd); return 0; } static int sysfs_get_string(char *path, char *filename, char *str) { FILE *fd; int ret = -1; char filepath[PATH_MAX + 2]; /* NUL and '/' */ snprintf(filepath, sizeof(filepath), "%s/%s", path, filename); fd = fopen(filepath, "r"); if (!fd) { syslog(LOG_ERR, "Err: open %s: %s\n", __func__, filepath); return ret; } ret = fscanf(fd, "%256s", str); fclose(fd); return ret; } /* get states of the cooling device instance */ static int probe_cdev(struct cdev_info *cdi, char *path) { sysfs_get_string(path, "type", cdi->type); sysfs_get_ulong(path, "max_state", &cdi->max_state); sysfs_get_ulong(path, "cur_state", &cdi->cur_state); syslog(LOG_INFO, "%s: %s: type %s, max %lu, curr %lu inst %d\n", __func__, path, cdi->type, cdi->max_state, cdi->cur_state, cdi->instance); return 0; } static int str_to_trip_type(char *name) { int i; for (i = 0; i < NR_THERMAL_TRIP_TYPE; i++) { if (!strcmp(name, trip_type_name[i])) return i; } return -ENOENT; } /* scan and fill in trip point info for a thermal zone and trip point id */ static int get_trip_point_data(char *tz_path, int tzid, int tpid) { char filename[256]; char temp_str[256]; int trip_type; if (tpid >= MAX_NR_TRIP) return -EINVAL; /* check trip point type */ snprintf(filename, sizeof(filename), "trip_point_%d_type", tpid); sysfs_get_string(tz_path, filename, temp_str); trip_type = str_to_trip_type(temp_str); if (trip_type < 0) { syslog(LOG_ERR, "%s:%s no matching type\n", __func__, temp_str); return -ENOENT; } ptdata.tzi[tzid].tp[tpid].type = trip_type; syslog(LOG_INFO, "%s:tz:%d tp:%d:type:%s type id %d\n", __func__, tzid, tpid, temp_str, trip_type); /* TODO: check attribute */ return 0; } /* return instance id for file format such as trip_point_4_temp */ static int get_instance_id(char *name, int pos, int skip) { char *ch; int i = 0; ch = strtok(name, "_"); while (ch != NULL) { ++i; syslog(LOG_INFO, "%s:%s:%s:%d", __func__, name, ch, i); ch = strtok(NULL, "_"); if (pos == i) return atol(ch + skip); } return -1; } /* Find trip point info of a thermal zone */ static int find_tzone_tp(char *tz_name, char *d_name, struct tz_info *tzi, int tz_id) { int tp_id; unsigned long temp_ulong; if (strstr(d_name, "trip_point") && strstr(d_name, "temp")) { /* check if trip point temp is non-zero * ignore 0/invalid trip points */ sysfs_get_ulong(tz_name, d_name, &temp_ulong); if (temp_ulong < MAX_TEMP_KC) { tzi->nr_trip_pts++; /* found a valid trip point */ tp_id = get_instance_id(d_name, 2, 0); syslog(LOG_DEBUG, "tzone %s trip %d temp %lu tpnode %s", tz_name, tp_id, temp_ulong, d_name); if (tp_id < 0 || tp_id >= MAX_NR_TRIP) { syslog(LOG_ERR, "Failed to find TP inst %s\n", d_name); return -1; } get_trip_point_data(tz_name, tz_id, tp_id); tzi->tp[tp_id].temp = temp_ulong; } } return 0; } /* check cooling devices for binding info. */ static int find_tzone_cdev(struct dirent *nl, char *tz_name, struct tz_info *tzi, int tz_id, int cid) { unsigned long trip_instance = 0; char cdev_name_linked[256]; char cdev_name[PATH_MAX]; char cdev_trip_name[PATH_MAX]; int cdev_id; if (nl->d_type == DT_LNK) { syslog(LOG_DEBUG, "TZ%d: cdev: %s cid %d\n", tz_id, nl->d_name, cid); tzi->nr_cdev++; if (tzi->nr_cdev > ptdata.nr_cooling_dev) { syslog(LOG_ERR, "Err: Too many cdev? %d\n", tzi->nr_cdev); return -EINVAL; } /* find the link to real cooling device record binding */ snprintf(cdev_name, sizeof(cdev_name) - 2, "%s/%s", tz_name, nl->d_name); memset(cdev_name_linked, 0, sizeof(cdev_name_linked)); if (readlink(cdev_name, cdev_name_linked, sizeof(cdev_name_linked) - 1) != -1) { cdev_id = get_instance_id(cdev_name_linked, 1, sizeof("device") - 1); syslog(LOG_DEBUG, "cdev %s linked to %s : %d\n", cdev_name, cdev_name_linked, cdev_id); tzi->cdev_binding |= (1 << cdev_id); /* find the trip point in which the cdev is binded to * in this tzone */ snprintf(cdev_trip_name, sizeof(cdev_trip_name) - 1, "%s%s", nl->d_name, "_trip_point"); sysfs_get_ulong(tz_name, cdev_trip_name, &trip_instance); /* validate trip point range, e.g. trip could return -1 * when passive is enabled */ if (trip_instance > MAX_NR_TRIP) trip_instance = 0; tzi->trip_binding[cdev_id] |= 1 << trip_instance; syslog(LOG_DEBUG, "cdev %s -> trip:%lu: 0x%lx %d\n", cdev_name, trip_instance, tzi->trip_binding[cdev_id], cdev_id); } return 0; } return -ENODEV; } /***************************************************************************** * Before calling scan_tzones, thermal sysfs must be probed to determine * the number of thermal zones and cooling devices. * We loop through each thermal zone and fill in tz_info struct, i.e. * ptdata.tzi[] root@jacob-chiefriver:~# tree -d /sys/class/thermal/thermal_zone0 /sys/class/thermal/thermal_zone0 |-- cdev0 -> ../cooling_device4 |-- cdev1 -> ../cooling_device3 |-- cdev10 -> ../cooling_device7 |-- cdev11 -> ../cooling_device6 |-- cdev12 -> ../cooling_device5 |-- cdev2 -> ../cooling_device2 |-- cdev3 -> ../cooling_device1 |-- cdev4 -> ../cooling_device0 |-- cdev5 -> ../cooling_device12 |-- cdev6 -> ../cooling_device11 |-- cdev7 -> ../cooling_device10 |-- cdev8 -> ../cooling_device9 |-- cdev9 -> ../cooling_device8 |-- device -> ../../../LNXSYSTM:00/device:62/LNXTHERM:00 |-- power `-- subsystem -> ../../../../class/thermal *****************************************************************************/ static int scan_tzones(void) { DIR *dir; struct dirent **namelist; char tz_name[256]; int i, j, n, k = 0; if (!ptdata.nr_tz_sensor) return -1; for (i = 0; i <= ptdata.max_tz_instance; i++) { memset(tz_name, 0, sizeof(tz_name)); snprintf(tz_name, 256, "%s/%s%d", THERMAL_SYSFS, TZONE, i); dir = opendir(tz_name); if (!dir) { syslog(LOG_INFO, "Thermal zone %s skipped\n", tz_name); continue; } /* keep track of valid tzones */ n = scandir(tz_name, &namelist, 0, alphasort); if (n < 0) syslog(LOG_ERR, "scandir failed in %s", tz_name); else { sysfs_get_string(tz_name, "type", ptdata.tzi[k].type); ptdata.tzi[k].instance = i; /* detect trip points and cdev attached to this tzone */ j = 0; /* index for cdev */ ptdata.tzi[k].nr_cdev = 0; ptdata.tzi[k].nr_trip_pts = 0; while (n--) { char *temp_str; if (find_tzone_tp(tz_name, namelist[n]->d_name, &ptdata.tzi[k], k)) break; temp_str = strstr(namelist[n]->d_name, "cdev"); if (!temp_str) { free(namelist[n]); continue; } if (!find_tzone_cdev(namelist[n], tz_name, &ptdata.tzi[k], i, j)) j++; /* increment cdev index */ free(namelist[n]); } free(namelist); } /*TODO: reverse trip points */ closedir(dir); syslog(LOG_INFO, "TZ %d has %d cdev\n", i, ptdata.tzi[k].nr_cdev); k++; } return 0; } static int scan_cdevs(void) { DIR *dir; struct dirent **namelist; char cdev_name[256]; int i, n, k = 0; if (!ptdata.nr_cooling_dev) { fprintf(stderr, "No cooling devices found\n"); return 0; } for (i = 0; i <= ptdata.max_cdev_instance; i++) { memset(cdev_name, 0, sizeof(cdev_name)); snprintf(cdev_name, 256, "%s/%s%d", THERMAL_SYSFS, CDEV, i); dir = opendir(cdev_name); if (!dir) { syslog(LOG_INFO, "Cooling dev %s skipped\n", cdev_name); /* there is a gap in cooling device id, check again * for the same index. */ continue; } n = scandir(cdev_name, &namelist, 0, alphasort); if (n < 0) syslog(LOG_ERR, "scandir failed in %s", cdev_name); else { sysfs_get_string(cdev_name, "type", ptdata.cdi[k].type); ptdata.cdi[k].instance = i; if (strstr(ptdata.cdi[k].type, ctrl_cdev)) { ptdata.cdi[k].flag |= CDEV_FLAG_IN_CONTROL; syslog(LOG_DEBUG, "control cdev id %d\n", i); } while (n--) free(namelist[n]); free(namelist); } closedir(dir); k++; } return 0; } int probe_thermal_sysfs(void) { DIR *dir; struct dirent **namelist; int n; dir = opendir(THERMAL_SYSFS); if (!dir) { fprintf(stderr, "\nNo thermal sysfs, exit\n"); return -1; } n = scandir(THERMAL_SYSFS, &namelist, 0, alphasort); if (n < 0) syslog(LOG_ERR, "scandir failed in thermal sysfs"); else { /* detect number of thermal zones and cooling devices */ while (n--) { int inst; if (strstr(namelist[n]->d_name, CDEV)) { inst = get_instance_id(namelist[n]->d_name, 1, sizeof("device") - 1); /* keep track of the max cooling device since * there may be gaps. */ if (inst > ptdata.max_cdev_instance) ptdata.max_cdev_instance = inst; syslog(LOG_DEBUG, "found cdev: %s %d %d\n", namelist[n]->d_name, ptdata.nr_cooling_dev, ptdata.max_cdev_instance); ptdata.nr_cooling_dev++; } else if (strstr(namelist[n]->d_name, TZONE)) { inst = get_instance_id(namelist[n]->d_name, 1, sizeof("zone") - 1); if (inst > ptdata.max_tz_instance) ptdata.max_tz_instance = inst; syslog(LOG_DEBUG, "found tzone: %s %d %d\n", namelist[n]->d_name, ptdata.nr_tz_sensor, ptdata.max_tz_instance); ptdata.nr_tz_sensor++; } free(namelist[n]); } free(namelist); } syslog(LOG_INFO, "found %d tzone(s), %d cdev(s), target zone %d\n", ptdata.nr_tz_sensor, ptdata.nr_cooling_dev, target_thermal_zone); closedir(dir); if (!ptdata.nr_tz_sensor) { fprintf(stderr, "\nNo thermal zones found, exit\n\n"); return -1; } ptdata.tzi = calloc(ptdata.max_tz_instance+1, sizeof(struct tz_info)); if (!ptdata.tzi) { fprintf(stderr, "Err: allocate tz_info\n"); return -1; } /* we still show thermal zone information if there is no cdev */ if (ptdata.nr_cooling_dev) { ptdata.cdi = calloc(ptdata.max_cdev_instance + 1, sizeof(struct cdev_info)); if (!ptdata.cdi) { free(ptdata.tzi); fprintf(stderr, "Err: allocate cdev_info\n"); return -1; } } /* now probe tzones */ if (scan_tzones()) return -1; if (scan_cdevs()) return -1; return 0; } /* convert sysfs zone instance to zone array index */ int zone_instance_to_index(int zone_inst) { int i; for (i = 0; i < ptdata.nr_tz_sensor; i++) if (ptdata.tzi[i].instance == zone_inst) return i; return -ENOENT; } /* read temperature of all thermal zones */ int update_thermal_data() { int i; int next_thermal_record = cur_thermal_record + 1; char tz_name[256]; static unsigned long samples; if (!ptdata.nr_tz_sensor) { syslog(LOG_ERR, "No thermal zones found!\n"); return -1; } /* circular buffer for keeping historic data */ if (next_thermal_record >= NR_THERMAL_RECORDS) next_thermal_record = 0; gettimeofday(&trec[next_thermal_record].tv, NULL); if (tmon_log) { fprintf(tmon_log, "%lu ", ++samples); fprintf(tmon_log, "%3.1f ", p_param.t_target); } for (i = 0; i < ptdata.nr_tz_sensor; i++) { memset(tz_name, 0, sizeof(tz_name)); snprintf(tz_name, 256, "%s/%s%d", THERMAL_SYSFS, TZONE, ptdata.tzi[i].instance); sysfs_get_ulong(tz_name, "temp", &trec[next_thermal_record].temp[i]); if (tmon_log) fprintf(tmon_log, "%lu ", trec[next_thermal_record].temp[i] / 1000); } cur_thermal_record = next_thermal_record; for (i = 0; i < ptdata.nr_cooling_dev; i++) { char cdev_name[256]; unsigned long val; snprintf(cdev_name, 256, "%s/%s%d", THERMAL_SYSFS, CDEV, ptdata.cdi[i].instance); probe_cdev(&ptdata.cdi[i], cdev_name); val = ptdata.cdi[i].cur_state; if (val > 1000000) val = 0; if (tmon_log) fprintf(tmon_log, "%lu ", val); } if (tmon_log) { fprintf(tmon_log, "\n"); fflush(tmon_log); } return 0; } void set_ctrl_state(unsigned long state) { char ctrl_cdev_path[256]; int i; unsigned long cdev_state; if (no_control) return; /* set all ctrl cdev to the same state */ for (i = 0; i < ptdata.nr_cooling_dev; i++) { if (ptdata.cdi[i].flag & CDEV_FLAG_IN_CONTROL) { if (ptdata.cdi[i].max_state < 10) { strcpy(ctrl_cdev, "None."); return; } /* scale to percentage of max_state */ cdev_state = state * ptdata.cdi[i].max_state/100; syslog(LOG_DEBUG, "ctrl cdev %d set state %lu scaled to %lu\n", ptdata.cdi[i].instance, state, cdev_state); snprintf(ctrl_cdev_path, 256, "%s/%s%d", THERMAL_SYSFS, CDEV, ptdata.cdi[i].instance); syslog(LOG_DEBUG, "ctrl cdev path %s", ctrl_cdev_path); sysfs_set_ulong(ctrl_cdev_path, "cur_state", cdev_state); } } } void get_ctrl_state(unsigned long *state) { char ctrl_cdev_path[256]; int ctrl_cdev_id = -1; int i; /* TODO: take average of all ctrl types. also consider change based on * uevent. Take the first reading for now. */ for (i = 0; i < ptdata.nr_cooling_dev; i++) { if (ptdata.cdi[i].flag & CDEV_FLAG_IN_CONTROL) { ctrl_cdev_id = ptdata.cdi[i].instance; syslog(LOG_INFO, "ctrl cdev %d get state\n", ptdata.cdi[i].instance); break; } } if (ctrl_cdev_id == -1) { *state = 0; return; } snprintf(ctrl_cdev_path, 256, "%s/%s%d", THERMAL_SYSFS, CDEV, ctrl_cdev_id); sysfs_get_ulong(ctrl_cdev_path, "cur_state", state); } void free_thermal_data(void) { free(ptdata.tzi); free(ptdata.cdi); }
linux-master
tools/thermal/tmon/sysfs.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * pid.c PID controller for testing cooling devices * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * Author Name Jacob Pan <[email protected]> */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <sys/types.h> #include <dirent.h> #include <libintl.h> #include <ctype.h> #include <assert.h> #include <time.h> #include <limits.h> #include <math.h> #include <sys/stat.h> #include <syslog.h> #include "tmon.h" /************************************************************************** * PID (Proportional-Integral-Derivative) controller is commonly used in * linear control system, consider the process. * G(s) = U(s)/E(s) * kp = proportional gain * ki = integral gain * kd = derivative gain * Ts * We use type C Alan Bradley equation which takes set point off the * output dependency in P and D term. * * y[k] = y[k-1] - kp*(x[k] - x[k-1]) + Ki*Ts*e[k] - Kd*(x[k] * - 2*x[k-1]+x[k-2])/Ts * * ***********************************************************************/ struct pid_params p_param; /* cached data from previous loop */ static double xk_1, xk_2; /* input temperature x[k-#] */ /* * TODO: make PID parameters tuned automatically, * 1. use CPU burn to produce open loop unit step response * 2. calculate PID based on Ziegler-Nichols rule * * add a flag for tuning PID */ int init_thermal_controller(void) { /* init pid params */ p_param.ts = ticktime; /* TODO: get it from TUI tuning tab */ p_param.kp = .36; p_param.ki = 5.0; p_param.kd = 0.19; p_param.t_target = target_temp_user; return 0; } void controller_reset(void) { /* TODO: relax control data when not over thermal limit */ syslog(LOG_DEBUG, "TC inactive, relax p-state\n"); p_param.y_k = 0.0; xk_1 = 0.0; xk_2 = 0.0; set_ctrl_state(0); } /* To be called at time interval Ts. Type C PID controller. * y[k] = y[k-1] - kp*(x[k] - x[k-1]) + Ki*Ts*e[k] - Kd*(x[k] * - 2*x[k-1]+x[k-2])/Ts * TODO: add low pass filter for D term */ #define GUARD_BAND (2) void controller_handler(const double xk, double *yk) { double ek; double p_term, i_term, d_term; ek = p_param.t_target - xk; /* error */ if (ek >= 3.0) { syslog(LOG_DEBUG, "PID: %3.1f Below set point %3.1f, stop\n", xk, p_param.t_target); controller_reset(); *yk = 0.0; return; } /* compute intermediate PID terms */ p_term = -p_param.kp * (xk - xk_1); i_term = p_param.kp * p_param.ki * p_param.ts * ek; d_term = -p_param.kp * p_param.kd * (xk - 2 * xk_1 + xk_2) / p_param.ts; /* compute output */ *yk += p_term + i_term + d_term; /* update sample data */ xk_1 = xk; xk_2 = xk_1; /* clamp output adjustment range */ if (*yk < -LIMIT_HIGH) *yk = -LIMIT_HIGH; else if (*yk > -LIMIT_LOW) *yk = -LIMIT_LOW; p_param.y_k = *yk; set_ctrl_state(lround(fabs(p_param.y_k))); }
linux-master
tools/thermal/tmon/pid.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * tmon.c Thermal Monitor (TMON) main function and entry point * * Copyright (C) 2012 Intel Corporation. All rights reserved. * * Author: Jacob Pan <[email protected]> */ #include <getopt.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <ncurses.h> #include <ctype.h> #include <time.h> #include <signal.h> #include <limits.h> #include <sys/time.h> #include <pthread.h> #include <math.h> #include <stdarg.h> #include <syslog.h> #include "tmon.h" unsigned long ticktime = 1; /* seconds */ unsigned long no_control = 1; /* monitoring only or use cooling device for * temperature control. */ double time_elapsed = 0.0; unsigned long target_temp_user = 65; /* can be select by tui later */ int dialogue_on; int tmon_exit; static short daemon_mode; static int logging; /* for recording thermal data to a file */ static int debug_on; FILE *tmon_log; /*cooling device used for the PID controller */ char ctrl_cdev[CDEV_NAME_SIZE] = "None"; int target_thermal_zone; /* user selected target zone instance */ static void start_daemon_mode(void); pthread_t event_tid; pthread_mutex_t input_lock; void usage(void) { printf("Usage: tmon [OPTION...]\n"); printf(" -c, --control cooling device in control\n"); printf(" -d, --daemon run as daemon, no TUI\n"); printf(" -g, --debug debug message in syslog\n"); printf(" -h, --help show this help message\n"); printf(" -l, --log log data to /var/tmp/tmon.log\n"); printf(" -t, --time-interval sampling time interval, > 1 sec.\n"); printf(" -T, --target-temp initial target temperature\n"); printf(" -v, --version show version\n"); printf(" -z, --zone target thermal zone id\n"); exit(0); } void version(void) { printf("TMON version %s\n", VERSION); exit(EXIT_SUCCESS); } static void tmon_cleanup(void) { syslog(LOG_INFO, "TMON exit cleanup\n"); fflush(stdout); refresh(); if (tmon_log) fclose(tmon_log); if (event_tid) { pthread_mutex_lock(&input_lock); pthread_cancel(event_tid); pthread_mutex_unlock(&input_lock); pthread_mutex_destroy(&input_lock); } closelog(); /* relax control knobs, undo throttling */ set_ctrl_state(0); keypad(stdscr, FALSE); echo(); nocbreak(); close_windows(); endwin(); free_thermal_data(); exit(1); } static void tmon_sig_handler(int sig) { syslog(LOG_INFO, "TMON caught signal %d\n", sig); refresh(); switch (sig) { case SIGTERM: printf("sigterm, exit and clean up\n"); fflush(stdout); break; case SIGKILL: printf("sigkill, exit and clean up\n"); fflush(stdout); break; case SIGINT: printf("ctrl-c, exit and clean up\n"); fflush(stdout); break; default: break; } tmon_exit = true; } static void start_syslog(void) { if (debug_on) setlogmask(LOG_UPTO(LOG_DEBUG)); else setlogmask(LOG_UPTO(LOG_ERR)); openlog("tmon.log", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL0); syslog(LOG_NOTICE, "TMON started by User %d", getuid()); } static void prepare_logging(void) { int i; struct stat logstat; if (!logging) return; /* open local data log file */ tmon_log = fopen(TMON_LOG_FILE, "w+"); if (!tmon_log) { syslog(LOG_ERR, "failed to open log file %s\n", TMON_LOG_FILE); return; } if (lstat(TMON_LOG_FILE, &logstat) < 0) { syslog(LOG_ERR, "Unable to stat log file %s\n", TMON_LOG_FILE); fclose(tmon_log); tmon_log = NULL; return; } /* The log file must be a regular file owned by us */ if (S_ISLNK(logstat.st_mode)) { syslog(LOG_ERR, "Log file is a symlink. Will not log\n"); fclose(tmon_log); tmon_log = NULL; return; } if (logstat.st_uid != getuid()) { syslog(LOG_ERR, "We don't own the log file. Not logging\n"); fclose(tmon_log); tmon_log = NULL; return; } fprintf(tmon_log, "#----------- THERMAL SYSTEM CONFIG -------------\n"); for (i = 0; i < ptdata.nr_tz_sensor; i++) { char binding_str[33]; /* size of long + 1 */ int j; memset(binding_str, 0, sizeof(binding_str)); for (j = 0; j < 32; j++) binding_str[j] = (ptdata.tzi[i].cdev_binding & (1 << j)) ? '1' : '0'; fprintf(tmon_log, "#thermal zone %s%02d cdevs binding: %32s\n", ptdata.tzi[i].type, ptdata.tzi[i].instance, binding_str); for (j = 0; j < ptdata.tzi[i].nr_trip_pts; j++) { fprintf(tmon_log, "#\tTP%02d type:%s, temp:%lu\n", j, trip_type_name[ptdata.tzi[i].tp[j].type], ptdata.tzi[i].tp[j].temp); } } for (i = 0; i < ptdata.nr_cooling_dev; i++) fprintf(tmon_log, "#cooling devices%02d: %s\n", i, ptdata.cdi[i].type); fprintf(tmon_log, "#---------- THERMAL DATA LOG STARTED -----------\n"); fprintf(tmon_log, "Samples TargetTemp "); for (i = 0; i < ptdata.nr_tz_sensor; i++) { fprintf(tmon_log, "%s%d ", ptdata.tzi[i].type, ptdata.tzi[i].instance); } for (i = 0; i < ptdata.nr_cooling_dev; i++) fprintf(tmon_log, "%s%d ", ptdata.cdi[i].type, ptdata.cdi[i].instance); fprintf(tmon_log, "\n"); } static struct option opts[] = { { "control", 1, NULL, 'c' }, { "daemon", 0, NULL, 'd' }, { "time-interval", 1, NULL, 't' }, { "target-temp", 1, NULL, 'T' }, { "log", 0, NULL, 'l' }, { "help", 0, NULL, 'h' }, { "version", 0, NULL, 'v' }, { "debug", 0, NULL, 'g' }, { 0, 0, NULL, 0 } }; int main(int argc, char **argv) { int err = 0; int id2 = 0, c; double yk = 0.0, temp; /* controller output */ int target_tz_index; if (geteuid() != 0) { printf("TMON needs to be run as root\n"); exit(EXIT_FAILURE); } while ((c = getopt_long(argc, argv, "c:dlht:T:vgz:", opts, &id2)) != -1) { switch (c) { case 'c': no_control = 0; strncpy(ctrl_cdev, optarg, CDEV_NAME_SIZE); break; case 'd': start_daemon_mode(); printf("Run TMON in daemon mode\n"); break; case 't': ticktime = strtod(optarg, NULL); if (ticktime < 1) ticktime = 1; break; case 'T': temp = strtod(optarg, NULL); if (temp < 0) { fprintf(stderr, "error: temperature must be positive\n"); return 1; } target_temp_user = temp; break; case 'l': printf("Logging data to /var/tmp/tmon.log\n"); logging = 1; break; case 'h': usage(); break; case 'v': version(); break; case 'g': debug_on = 1; break; case 'z': target_thermal_zone = strtod(optarg, NULL); break; default: break; } } if (pthread_mutex_init(&input_lock, NULL) != 0) { fprintf(stderr, "\n mutex init failed, exit\n"); return 1; } start_syslog(); if (signal(SIGINT, tmon_sig_handler) == SIG_ERR) syslog(LOG_DEBUG, "Cannot handle SIGINT\n"); if (signal(SIGTERM, tmon_sig_handler) == SIG_ERR) syslog(LOG_DEBUG, "Cannot handle SIGTERM\n"); if (probe_thermal_sysfs()) { pthread_mutex_destroy(&input_lock); closelog(); return -1; } initialize_curses(); setup_windows(); signal(SIGWINCH, resize_handler); show_title_bar(); show_sensors_w(); show_cooling_device(); update_thermal_data(); show_data_w(); prepare_logging(); init_thermal_controller(); nodelay(stdscr, TRUE); err = pthread_create(&event_tid, NULL, &handle_tui_events, NULL); if (err != 0) { printf("\ncan't create thread :[%s]", strerror(err)); tmon_cleanup(); exit(EXIT_FAILURE); } /* validate range of user selected target zone, default to the first * instance if out of range */ target_tz_index = zone_instance_to_index(target_thermal_zone); if (target_tz_index < 0) { target_thermal_zone = ptdata.tzi[0].instance; syslog(LOG_ERR, "target zone is not found, default to %d\n", target_thermal_zone); } while (1) { sleep(ticktime); show_title_bar(); show_sensors_w(); update_thermal_data(); if (!dialogue_on) { show_data_w(); show_cooling_device(); } time_elapsed += ticktime; controller_handler(trec[0].temp[target_tz_index] / 1000, &yk); trec[0].pid_out_pct = yk; if (!dialogue_on) show_control_w(); if (tmon_exit) break; } tmon_cleanup(); return 0; } static void start_daemon_mode(void) { daemon_mode = 1; /* fork */ pid_t sid, pid = fork(); if (pid < 0) exit(EXIT_FAILURE); else if (pid > 0) /* kill parent */ exit(EXIT_SUCCESS); /* disable TUI, it may not be necessary, but saves some resource */ disable_tui(); /* change the file mode mask */ umask(S_IWGRP | S_IWOTH); /* new SID for the daemon process */ sid = setsid(); if (sid < 0) exit(EXIT_FAILURE); /* change working directory */ if ((chdir("/")) < 0) exit(EXIT_FAILURE); sleep(10); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); }
linux-master
tools/thermal/tmon/tmon.c
// SPDX-License-Identifier: GPL-2.0 /* * cgroup_event_listener.c - Simple listener of cgroup events * * Copyright (C) Kirill A. Shutemov <[email protected]> */ #include <assert.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <libgen.h> #include <limits.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/eventfd.h> #define USAGE_STR "Usage: cgroup_event_listener <path-to-control-file> <args>" int main(int argc, char **argv) { int efd = -1; int cfd = -1; int event_control = -1; char event_control_path[PATH_MAX]; char line[LINE_MAX]; int ret; if (argc != 3) errx(1, "%s", USAGE_STR); cfd = open(argv[1], O_RDONLY); if (cfd == -1) err(1, "Cannot open %s", argv[1]); ret = snprintf(event_control_path, PATH_MAX, "%s/cgroup.event_control", dirname(argv[1])); if (ret >= PATH_MAX) errx(1, "Path to cgroup.event_control is too long"); event_control = open(event_control_path, O_WRONLY); if (event_control == -1) err(1, "Cannot open %s", event_control_path); efd = eventfd(0, 0); if (efd == -1) err(1, "eventfd() failed"); ret = snprintf(line, LINE_MAX, "%d %d %s", efd, cfd, argv[2]); if (ret >= LINE_MAX) errx(1, "Arguments string is too long"); ret = write(event_control, line, strlen(line) + 1); if (ret == -1) err(1, "Cannot write to cgroup.event_control"); while (1) { uint64_t result; ret = read(efd, &result, sizeof(result)); if (ret == -1) { if (errno == EINTR) continue; err(1, "Cannot read from eventfd"); } assert(ret == sizeof(result)); ret = access(event_control_path, W_OK); if ((ret == -1) && (errno == ENOENT)) { puts("The cgroup seems to have removed."); break; } if (ret == -1) err(1, "cgroup.event_control is not accessible any more"); printf("%s %s: crossed\n", argv[1], argv[2]); } return 0; }
linux-master
tools/cgroup/cgroup_event_listener.c
// SPDX-License-Identifier: GPL-2.0 /* * led_hw_brightness_mon.c * * This program monitors LED brightness level changes having its origin * in hardware/firmware, i.e. outside of kernel control. * A timestamp and brightness value is printed each time the brightness changes. * * Usage: led_hw_brightness_mon <device-name> * * <device-name> is the name of the LED class device to be monitored. Pressing * CTRL+C will exit. */ #include <errno.h> #include <fcntl.h> #include <poll.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <linux/uleds.h> int main(int argc, char const *argv[]) { int fd, ret; char brightness_file_path[LED_MAX_NAME_SIZE + 11]; struct pollfd pollfd; struct timespec ts; char buf[11]; if (argc != 2) { fprintf(stderr, "Requires <device-name> argument\n"); return 1; } snprintf(brightness_file_path, LED_MAX_NAME_SIZE, "/sys/class/leds/%s/brightness_hw_changed", argv[1]); fd = open(brightness_file_path, O_RDONLY); if (fd == -1) { printf("Failed to open %s file\n", brightness_file_path); return 1; } /* * read may fail if no hw brightness change has occurred so far, * but it is required to avoid spurious poll notifications in * the opposite case. */ read(fd, buf, sizeof(buf)); pollfd.fd = fd; pollfd.events = POLLPRI; while (1) { ret = poll(&pollfd, 1, -1); if (ret == -1) { printf("Failed to poll %s file (%d)\n", brightness_file_path, ret); ret = 1; break; } clock_gettime(CLOCK_MONOTONIC, &ts); ret = read(fd, buf, sizeof(buf)); if (ret < 0) break; ret = lseek(pollfd.fd, 0, SEEK_SET); if (ret < 0) { printf("lseek failed (%d)\n", ret); break; } printf("[%ld.%09ld] %d\n", ts.tv_sec, ts.tv_nsec, atoi(buf)); } close(fd); return ret; }
linux-master
tools/leds/led_hw_brightness_mon.c
// SPDX-License-Identifier: GPL-2.0 /* * uledmon.c * * This program creates a new userspace LED class device and monitors it. A * timestamp and brightness value is printed each time the brightness changes. * * Usage: uledmon <device-name> * * <device-name> is the name of the LED class device to be created. Pressing * CTRL+C will exit. */ #include <fcntl.h> #include <stdio.h> #include <string.h> #include <time.h> #include <unistd.h> #include <linux/uleds.h> int main(int argc, char const *argv[]) { struct uleds_user_dev uleds_dev; int fd, ret; int brightness; struct timespec ts; if (argc != 2) { fprintf(stderr, "Requires <device-name> argument\n"); return 1; } strncpy(uleds_dev.name, argv[1], LED_MAX_NAME_SIZE); uleds_dev.max_brightness = 100; fd = open("/dev/uleds", O_RDWR); if (fd == -1) { perror("Failed to open /dev/uleds"); return 1; } ret = write(fd, &uleds_dev, sizeof(uleds_dev)); if (ret == -1) { perror("Failed to write to /dev/uleds"); close(fd); return 1; } while (1) { ret = read(fd, &brightness, sizeof(brightness)); if (ret == -1) { perror("Failed to read from /dev/uleds"); close(fd); return 1; } clock_gettime(CLOCK_MONOTONIC, &ts); printf("[%ld.%09ld] %u\n", ts.tv_sec, ts.tv_nsec, brightness); } close(fd); return 0; }
linux-master
tools/leds/uledmon.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Test that /proc/loadavg correctly reports last pid in pid namespace. */ #include <errno.h> #include <sched.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/wait.h> int main(void) { pid_t pid; int wstatus; if (unshare(CLONE_NEWPID) == -1) { if (errno == ENOSYS || errno == EPERM) return 4; return 1; } pid = fork(); if (pid == -1) return 1; if (pid == 0) { char buf[128], *p; int fd; ssize_t rv; fd = open("/proc/loadavg" , O_RDONLY); if (fd == -1) return 1; rv = read(fd, buf, sizeof(buf)); if (rv < 3) return 1; p = buf + rv; /* pid 1 */ if (!(p[-3] == ' ' && p[-2] == '1' && p[-1] == '\n')) return 1; pid = fork(); if (pid == -1) return 1; if (pid == 0) return 0; if (waitpid(pid, NULL, 0) == -1) return 1; lseek(fd, 0, SEEK_SET); rv = read(fd, buf, sizeof(buf)); if (rv < 3) return 1; p = buf + rv; /* pid 2 */ if (!(p[-3] == ' ' && p[-2] == '2' && p[-1] == '\n')) return 1; return 0; } if (waitpid(pid, &wstatus, 0) == -1) return 1; if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0) return 0; return 1; }
linux-master
tools/testing/selftests/proc/proc-loadavg-001.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> int main(void) { char buf[64]; int fd; fd = open("/proc/self/wchan", O_RDONLY); if (fd == -1) { if (errno == ENOENT) return 4; return 1; } buf[0] = '\0'; if (read(fd, buf, sizeof(buf)) != 1) return 1; if (buf[0] != '0') return 1; return 0; }
linux-master
tools/testing/selftests/proc/proc-self-wchan.c
/* * Copyright (c) 2019 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Fork and exec tiny 1 page executable which precisely controls its VM. * Test /proc/$PID/maps * Test /proc/$PID/smaps * Test /proc/$PID/smaps_rollup * Test /proc/$PID/statm * * FIXME require CONFIG_TMPFS which can be disabled * FIXME test other values from "smaps" * FIXME support other archs */ #undef NDEBUG #include <assert.h> #include <errno.h> #include <sched.h> #include <signal.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/mount.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <fcntl.h> #include <unistd.h> #include <sys/syscall.h> #include <sys/uio.h> #include <linux/kdev_t.h> #include <sys/time.h> #include <sys/resource.h> #include "../kselftest.h" static inline long sys_execveat(int dirfd, const char *pathname, char **argv, char **envp, int flags) { return syscall(SYS_execveat, dirfd, pathname, argv, envp, flags); } static void make_private_tmp(void) { if (unshare(CLONE_NEWNS) == -1) { if (errno == ENOSYS || errno == EPERM) { exit(4); } exit(1); } if (mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL) == -1) { exit(1); } if (mount(NULL, "/tmp", "tmpfs", 0, NULL) == -1) { exit(1); } } static pid_t pid = -1; static void ate(void) { if (pid > 0) { kill(pid, SIGTERM); } } struct elf64_hdr { uint8_t e_ident[16]; uint16_t e_type; uint16_t e_machine; uint32_t e_version; uint64_t e_entry; uint64_t e_phoff; uint64_t e_shoff; uint32_t e_flags; uint16_t e_ehsize; uint16_t e_phentsize; uint16_t e_phnum; uint16_t e_shentsize; uint16_t e_shnum; uint16_t e_shstrndx; }; struct elf64_phdr { uint32_t p_type; uint32_t p_flags; uint64_t p_offset; uint64_t p_vaddr; uint64_t p_paddr; uint64_t p_filesz; uint64_t p_memsz; uint64_t p_align; }; #ifdef __x86_64__ #define PAGE_SIZE 4096 #define VADDR (1UL << 32) #define MAPS_OFFSET 73 #define syscall 0x0f, 0x05 #define mov_rdi(x) \ 0x48, 0xbf, \ (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff, \ ((x)>>32)&0xff, ((x)>>40)&0xff, ((x)>>48)&0xff, ((x)>>56)&0xff #define mov_rsi(x) \ 0x48, 0xbe, \ (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff, \ ((x)>>32)&0xff, ((x)>>40)&0xff, ((x)>>48)&0xff, ((x)>>56)&0xff #define mov_eax(x) \ 0xb8, (x)&0xff, ((x)>>8)&0xff, ((x)>>16)&0xff, ((x)>>24)&0xff static const uint8_t payload[] = { /* Casually unmap stack, vDSO and everything else. */ /* munmap */ mov_rdi(VADDR + 4096), mov_rsi((1ULL << 47) - 4096 - VADDR - 4096), mov_eax(11), syscall, /* Ping parent. */ /* write(0, &c, 1); */ 0x31, 0xff, /* xor edi, edi */ 0x48, 0x8d, 0x35, 0x00, 0x00, 0x00, 0x00, /* lea rsi, [rip] */ 0xba, 0x01, 0x00, 0x00, 0x00, /* mov edx, 1 */ mov_eax(1), syscall, /* 1: pause(); */ mov_eax(34), syscall, 0xeb, 0xf7, /* jmp 1b */ }; static int make_exe(const uint8_t *payload, size_t len) { struct elf64_hdr h; struct elf64_phdr ph; struct iovec iov[3] = { {&h, sizeof(struct elf64_hdr)}, {&ph, sizeof(struct elf64_phdr)}, {(void *)payload, len}, }; int fd, fd1; char buf[64]; memset(&h, 0, sizeof(h)); h.e_ident[0] = 0x7f; h.e_ident[1] = 'E'; h.e_ident[2] = 'L'; h.e_ident[3] = 'F'; h.e_ident[4] = 2; h.e_ident[5] = 1; h.e_ident[6] = 1; h.e_ident[7] = 0; h.e_type = 2; h.e_machine = 0x3e; h.e_version = 1; h.e_entry = VADDR + sizeof(struct elf64_hdr) + sizeof(struct elf64_phdr); h.e_phoff = sizeof(struct elf64_hdr); h.e_shoff = 0; h.e_flags = 0; h.e_ehsize = sizeof(struct elf64_hdr); h.e_phentsize = sizeof(struct elf64_phdr); h.e_phnum = 1; h.e_shentsize = 0; h.e_shnum = 0; h.e_shstrndx = 0; memset(&ph, 0, sizeof(ph)); ph.p_type = 1; ph.p_flags = (1<<2)|1; ph.p_offset = 0; ph.p_vaddr = VADDR; ph.p_paddr = 0; ph.p_filesz = sizeof(struct elf64_hdr) + sizeof(struct elf64_phdr) + len; ph.p_memsz = sizeof(struct elf64_hdr) + sizeof(struct elf64_phdr) + len; ph.p_align = 4096; fd = openat(AT_FDCWD, "/tmp", O_WRONLY|O_EXCL|O_TMPFILE, 0700); if (fd == -1) { exit(1); } if (writev(fd, iov, 3) != sizeof(struct elf64_hdr) + sizeof(struct elf64_phdr) + len) { exit(1); } /* Avoid ETXTBSY on exec. */ snprintf(buf, sizeof(buf), "/proc/self/fd/%u", fd); fd1 = open(buf, O_RDONLY|O_CLOEXEC); close(fd); return fd1; } #endif /* * 0: vsyscall VMA doesn't exist vsyscall=none * 1: vsyscall VMA is --xp vsyscall=xonly * 2: vsyscall VMA is r-xp vsyscall=emulate */ static volatile int g_vsyscall; static const char *str_vsyscall; static const char str_vsyscall_0[] = ""; static const char str_vsyscall_1[] = "ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]\n"; static const char str_vsyscall_2[] = "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]\n"; #ifdef __x86_64__ static void sigaction_SIGSEGV(int _, siginfo_t *__, void *___) { _exit(g_vsyscall); } /* * vsyscall page can't be unmapped, probe it directly. */ static void vsyscall(void) { pid_t pid; int wstatus; pid = fork(); if (pid < 0) { fprintf(stderr, "fork, errno %d\n", errno); exit(1); } if (pid == 0) { struct rlimit rlim = {0, 0}; (void)setrlimit(RLIMIT_CORE, &rlim); /* Hide "segfault at ffffffffff600000" messages. */ struct sigaction act; memset(&act, 0, sizeof(struct sigaction)); act.sa_flags = SA_SIGINFO; act.sa_sigaction = sigaction_SIGSEGV; (void)sigaction(SIGSEGV, &act, NULL); g_vsyscall = 0; /* gettimeofday(NULL, NULL); */ uint64_t rax = 0xffffffffff600000; asm volatile ( "call *%[rax]" : [rax] "+a" (rax) : "D" (NULL), "S" (NULL) : "rcx", "r11" ); g_vsyscall = 1; *(volatile int *)0xffffffffff600000UL; g_vsyscall = 2; exit(g_vsyscall); } waitpid(pid, &wstatus, 0); if (WIFEXITED(wstatus)) { g_vsyscall = WEXITSTATUS(wstatus); } else { fprintf(stderr, "error: wstatus %08x\n", wstatus); exit(1); } } int main(void) { int pipefd[2]; int exec_fd; vsyscall(); switch (g_vsyscall) { case 0: str_vsyscall = str_vsyscall_0; break; case 1: str_vsyscall = str_vsyscall_1; break; case 2: str_vsyscall = str_vsyscall_2; break; default: abort(); } atexit(ate); make_private_tmp(); /* Reserve fd 0 for 1-byte pipe ping from child. */ close(0); if (open("/", O_RDONLY|O_DIRECTORY|O_PATH) != 0) { return 1; } exec_fd = make_exe(payload, sizeof(payload)); if (pipe(pipefd) == -1) { return 1; } if (dup2(pipefd[1], 0) != 0) { return 1; } pid = fork(); if (pid == -1) { return 1; } if (pid == 0) { sys_execveat(exec_fd, "", NULL, NULL, AT_EMPTY_PATH); return 1; } char _; if (read(pipefd[0], &_, 1) != 1) { return 1; } struct stat st; if (fstat(exec_fd, &st) == -1) { return 1; } /* Generate "head -n1 /proc/$PID/maps" */ char buf0[256]; memset(buf0, ' ', sizeof(buf0)); int len = snprintf(buf0, sizeof(buf0), "%08lx-%08lx r-xp 00000000 %02lx:%02lx %llu", VADDR, VADDR + PAGE_SIZE, MAJOR(st.st_dev), MINOR(st.st_dev), (unsigned long long)st.st_ino); buf0[len] = ' '; snprintf(buf0 + MAPS_OFFSET, sizeof(buf0) - MAPS_OFFSET, "/tmp/#%llu (deleted)\n", (unsigned long long)st.st_ino); /* Test /proc/$PID/maps */ { const size_t len = strlen(buf0) + strlen(str_vsyscall); char buf[256]; ssize_t rv; int fd; snprintf(buf, sizeof(buf), "/proc/%u/maps", pid); fd = open(buf, O_RDONLY); if (fd == -1) { return 1; } rv = read(fd, buf, sizeof(buf)); assert(rv == len); assert(memcmp(buf, buf0, strlen(buf0)) == 0); if (g_vsyscall > 0) { assert(memcmp(buf + strlen(buf0), str_vsyscall, strlen(str_vsyscall)) == 0); } } /* Test /proc/$PID/smaps */ { char buf[4096]; ssize_t rv; int fd; snprintf(buf, sizeof(buf), "/proc/%u/smaps", pid); fd = open(buf, O_RDONLY); if (fd == -1) { return 1; } rv = read(fd, buf, sizeof(buf)); assert(0 <= rv && rv <= sizeof(buf)); assert(rv >= strlen(buf0)); assert(memcmp(buf, buf0, strlen(buf0)) == 0); #define RSS1 "Rss: 4 kB\n" #define RSS2 "Rss: 0 kB\n" #define PSS1 "Pss: 4 kB\n" #define PSS2 "Pss: 0 kB\n" assert(memmem(buf, rv, RSS1, strlen(RSS1)) || memmem(buf, rv, RSS2, strlen(RSS2))); assert(memmem(buf, rv, PSS1, strlen(PSS1)) || memmem(buf, rv, PSS2, strlen(PSS2))); static const char *S[] = { "Size: 4 kB\n", "KernelPageSize: 4 kB\n", "MMUPageSize: 4 kB\n", "Anonymous: 0 kB\n", "AnonHugePages: 0 kB\n", "Shared_Hugetlb: 0 kB\n", "Private_Hugetlb: 0 kB\n", "Locked: 0 kB\n", }; int i; for (i = 0; i < ARRAY_SIZE(S); i++) { assert(memmem(buf, rv, S[i], strlen(S[i]))); } if (g_vsyscall > 0) { assert(memmem(buf, rv, str_vsyscall, strlen(str_vsyscall))); } } /* Test /proc/$PID/smaps_rollup */ { char bufr[256]; memset(bufr, ' ', sizeof(bufr)); len = snprintf(bufr, sizeof(bufr), "%08lx-%08lx ---p 00000000 00:00 0", VADDR, VADDR + PAGE_SIZE); bufr[len] = ' '; snprintf(bufr + MAPS_OFFSET, sizeof(bufr) - MAPS_OFFSET, "[rollup]\n"); char buf[1024]; ssize_t rv; int fd; snprintf(buf, sizeof(buf), "/proc/%u/smaps_rollup", pid); fd = open(buf, O_RDONLY); if (fd == -1) { return 1; } rv = read(fd, buf, sizeof(buf)); assert(0 <= rv && rv <= sizeof(buf)); assert(rv >= strlen(bufr)); assert(memcmp(buf, bufr, strlen(bufr)) == 0); assert(memmem(buf, rv, RSS1, strlen(RSS1)) || memmem(buf, rv, RSS2, strlen(RSS2))); assert(memmem(buf, rv, PSS1, strlen(PSS1)) || memmem(buf, rv, PSS2, strlen(PSS2))); static const char *S[] = { "Anonymous: 0 kB\n", "AnonHugePages: 0 kB\n", "Shared_Hugetlb: 0 kB\n", "Private_Hugetlb: 0 kB\n", "Locked: 0 kB\n", }; int i; for (i = 0; i < ARRAY_SIZE(S); i++) { assert(memmem(buf, rv, S[i], strlen(S[i]))); } } /* Test /proc/$PID/statm */ { char buf[64]; ssize_t rv; int fd; snprintf(buf, sizeof(buf), "/proc/%u/statm", pid); fd = open(buf, O_RDONLY); if (fd == -1) { return 1; } rv = read(fd, buf, sizeof(buf)); assert(rv == 7 * 2); assert(buf[0] == '1'); /* ->total_vm */ assert(buf[1] == ' '); assert(buf[2] == '0' || buf[2] == '1'); /* rss */ assert(buf[3] == ' '); assert(buf[4] == '0' || buf[2] == '1'); /* file rss */ assert(buf[5] == ' '); assert(buf[6] == '1'); /* ELF executable segments */ assert(buf[7] == ' '); assert(buf[8] == '0'); assert(buf[9] == ' '); assert(buf[10] == '0'); /* ->data_vm + ->stack_vm */ assert(buf[11] == ' '); assert(buf[12] == '0'); assert(buf[13] == '\n'); } return 0; } #else int main(void) { return 4; } #endif
linux-master
tools/testing/selftests/proc/proc-pid-vm.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test that boottime value in /proc/uptime and CLOCK_BOOTTIME increment // monotonically. We don't test idle time monotonicity due to broken iowait // task counting, cf: comment above get_cpu_idle_time_us() #undef NDEBUG #include <assert.h> #include <stdint.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "proc-uptime.h" int main(void) { uint64_t start, u0, u1, c0, c1; int fd; fd = open("/proc/uptime", O_RDONLY); assert(fd >= 0); u0 = proc_uptime(fd); start = u0; c0 = clock_boottime(); do { u1 = proc_uptime(fd); c1 = clock_boottime(); /* Is /proc/uptime monotonic ? */ assert(u1 >= u0); /* Is CLOCK_BOOTTIME monotonic ? */ assert(c1 >= c0); /* Is CLOCK_BOOTTIME VS /proc/uptime monotonic ? */ assert(c0 >= u0); u0 = u1; c0 = c1; } while (u1 - start < 100); return 0; }
linux-master
tools/testing/selftests/proc/proc-uptime-001.c
/* * Copyright (c) 2021 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Test that "mount -t proc -o subset=pid" hides everything but pids, * /proc/self and /proc/thread-self. */ #undef NDEBUG #include <assert.h> #include <errno.h> #include <sched.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <sys/mount.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> #include <unistd.h> #include <stdio.h> static inline bool streq(const char *a, const char *b) { return strcmp(a, b) == 0; } static void make_private_proc(void) { if (unshare(CLONE_NEWNS) == -1) { if (errno == ENOSYS || errno == EPERM) { exit(4); } exit(1); } if (mount(NULL, "/", NULL, MS_PRIVATE|MS_REC, NULL) == -1) { exit(1); } if (mount(NULL, "/proc", "proc", 0, "subset=pid") == -1) { exit(1); } } static bool string_is_pid(const char *s) { while (1) { switch (*s++) { case '0':case '1':case '2':case '3':case '4': case '5':case '6':case '7':case '8':case '9': continue; case '\0': return true; default: return false; } } } int main(void) { make_private_proc(); DIR *d = opendir("/proc"); assert(d); struct dirent *de; bool dot = false; bool dot_dot = false; bool self = false; bool thread_self = false; while ((de = readdir(d))) { if (streq(de->d_name, ".")) { assert(!dot); dot = true; assert(de->d_type == DT_DIR); } else if (streq(de->d_name, "..")) { assert(!dot_dot); dot_dot = true; assert(de->d_type == DT_DIR); } else if (streq(de->d_name, "self")) { assert(!self); self = true; assert(de->d_type == DT_LNK); } else if (streq(de->d_name, "thread-self")) { assert(!thread_self); thread_self = true; assert(de->d_type == DT_LNK); } else { if (!string_is_pid(de->d_name)) { fprintf(stderr, "d_name '%s'\n", de->d_name); assert(0); } assert(de->d_type == DT_DIR); } } char c; int rv = readlink("/proc/cpuinfo", &c, 1); assert(rv == -1 && errno == ENOENT); int fd = open("/proc/cpuinfo", O_RDONLY); assert(fd == -1 && errno == ENOENT); return 0; }
linux-master
tools/testing/selftests/proc/proc-subset-pid.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Test readlink /proc/self/map_files/... */ #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> #include <stdlib.h> static void pass(const char *fmt, unsigned long a, unsigned long b) { char name[64]; char buf[64]; snprintf(name, sizeof(name), fmt, a, b); if (readlink(name, buf, sizeof(buf)) == -1) exit(1); } static void fail(const char *fmt, unsigned long a, unsigned long b) { char name[64]; char buf[64]; snprintf(name, sizeof(name), fmt, a, b); if (readlink(name, buf, sizeof(buf)) == -1 && errno == ENOENT) return; exit(1); } int main(void) { const unsigned int PAGE_SIZE = sysconf(_SC_PAGESIZE); void *p; int fd; unsigned long a, b; fd = open("/dev/zero", O_RDONLY); if (fd == -1) return 1; p = mmap(NULL, PAGE_SIZE, PROT_NONE, MAP_PRIVATE|MAP_FILE, fd, 0); if (p == MAP_FAILED) return 1; a = (unsigned long)p; b = (unsigned long)p + PAGE_SIZE; pass("/proc/self/map_files/%lx-%lx", a, b); fail("/proc/self/map_files/ %lx-%lx", a, b); fail("/proc/self/map_files/%lx -%lx", a, b); fail("/proc/self/map_files/%lx- %lx", a, b); fail("/proc/self/map_files/%lx-%lx ", a, b); fail("/proc/self/map_files/0%lx-%lx", a, b); fail("/proc/self/map_files/%lx-0%lx", a, b); if (sizeof(long) == 4) { fail("/proc/self/map_files/100000000%lx-%lx", a, b); fail("/proc/self/map_files/%lx-100000000%lx", a, b); } else if (sizeof(long) == 8) { fail("/proc/self/map_files/10000000000000000%lx-%lx", a, b); fail("/proc/self/map_files/%lx-10000000000000000%lx", a, b); } else return 1; return 0; }
linux-master
tools/testing/selftests/proc/proc-self-map-files-001.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test that open(/proc/*/fd/*) opens the same file. #undef NDEBUG #include <assert.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(void) { int fd0, fd1, fd2; struct stat st0, st1, st2; char buf[64]; int rv; fd0 = open("/", O_DIRECTORY|O_RDONLY); assert(fd0 >= 0); snprintf(buf, sizeof(buf), "/proc/self/fd/%u", fd0); fd1 = open(buf, O_RDONLY); assert(fd1 >= 0); snprintf(buf, sizeof(buf), "/proc/thread-self/fd/%u", fd0); fd2 = open(buf, O_RDONLY); assert(fd2 >= 0); rv = fstat(fd0, &st0); assert(rv == 0); rv = fstat(fd1, &st1); assert(rv == 0); rv = fstat(fd2, &st2); assert(rv == 0); assert(st0.st_dev == st1.st_dev); assert(st0.st_ino == st1.st_ino); assert(st0.st_dev == st2.st_dev); assert(st0.st_ino == st2.st_ino); return 0; }
linux-master
tools/testing/selftests/proc/fd-002-posix-eq.c
/* * Copyright © 2019 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Test that setns(CLONE_NEWNET) points to new /proc/net content even * if old one is in dcache. * * FIXME /proc/net/unix is under CONFIG_UNIX which can be disabled. */ #undef NDEBUG #include <assert.h> #include <errno.h> #include <sched.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/socket.h> static pid_t pid = -1; static void f(void) { if (pid > 0) { kill(pid, SIGTERM); } } int main(void) { int fd[2]; char _ = 0; int nsfd; atexit(f); /* Check for priviledges and syscall availability straight away. */ if (unshare(CLONE_NEWNET) == -1) { if (errno == ENOSYS || errno == EPERM) { return 4; } return 1; } /* Distinguisher between two otherwise empty net namespaces. */ if (socket(AF_UNIX, SOCK_STREAM, 0) == -1) { return 1; } if (pipe(fd) == -1) { return 1; } pid = fork(); if (pid == -1) { return 1; } if (pid == 0) { if (unshare(CLONE_NEWNET) == -1) { return 1; } if (write(fd[1], &_, 1) != 1) { return 1; } pause(); return 0; } if (read(fd[0], &_, 1) != 1) { return 1; } { char buf[64]; snprintf(buf, sizeof(buf), "/proc/%u/ns/net", pid); nsfd = open(buf, O_RDONLY); if (nsfd == -1) { return 1; } } /* Reliably pin dentry into dcache. */ (void)open("/proc/net/unix", O_RDONLY); if (setns(nsfd, CLONE_NEWNET) == -1) { return 1; } kill(pid, SIGTERM); pid = 0; { char buf[4096]; ssize_t rv; int fd; fd = open("/proc/net/unix", O_RDONLY); if (fd == -1) { return 1; } #define S "Num RefCount Protocol Flags Type St Inode Path\n" rv = read(fd, buf, sizeof(buf)); assert(rv == strlen(S)); assert(memcmp(buf, S, strlen(S)) == 0); } return 0; }
linux-master
tools/testing/selftests/proc/setns-dcache.c
/* * Copyright © 2020 Alexey Gladkov <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <sys/mount.h> #include <sys/types.h> #include <sys/stat.h> int main(void) { struct stat proc_st1, proc_st2; char procbuff[] = "/tmp/proc.XXXXXX/meminfo"; char procdir1[] = "/tmp/proc.XXXXXX"; char procdir2[] = "/tmp/proc.XXXXXX"; assert(mkdtemp(procdir1) != NULL); assert(mkdtemp(procdir2) != NULL); assert(!mount("proc", procdir1, "proc", 0, "hidepid=1")); assert(!mount("proc", procdir2, "proc", 0, "hidepid=2")); snprintf(procbuff, sizeof(procbuff), "%s/meminfo", procdir1); assert(!stat(procbuff, &proc_st1)); snprintf(procbuff, sizeof(procbuff), "%s/meminfo", procdir2); assert(!stat(procbuff, &proc_st2)); umount(procdir1); umount(procdir2); assert(proc_st1.st_dev != proc_st2.st_dev); return 0; }
linux-master
tools/testing/selftests/proc/proc-multiple-procfs.c
/* * Copyright © 2019 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Test that setns(CLONE_NEWIPC) points to new /proc/sysvipc content even * if old one is in dcache. */ #undef NDEBUG #include <assert.h> #include <errno.h> #include <stdio.h> #include <sched.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ipc.h> #include <sys/shm.h> static pid_t pid = -1; static void f(void) { if (pid > 0) { kill(pid, SIGTERM); } } int main(void) { int fd[2]; char _ = 0; int nsfd; atexit(f); /* Check for priviledges and syscall availability straight away. */ if (unshare(CLONE_NEWIPC) == -1) { if (errno == ENOSYS || errno == EPERM) { return 4; } return 1; } /* Distinguisher between two otherwise empty IPC namespaces. */ if (shmget(IPC_PRIVATE, 1, IPC_CREAT) == -1) { return 1; } if (pipe(fd) == -1) { return 1; } pid = fork(); if (pid == -1) { return 1; } if (pid == 0) { if (unshare(CLONE_NEWIPC) == -1) { return 1; } if (write(fd[1], &_, 1) != 1) { return 1; } pause(); return 0; } if (read(fd[0], &_, 1) != 1) { return 1; } { char buf[64]; snprintf(buf, sizeof(buf), "/proc/%u/ns/ipc", pid); nsfd = open(buf, O_RDONLY); if (nsfd == -1) { return 1; } } /* Reliably pin dentry into dcache. */ (void)open("/proc/sysvipc/shm", O_RDONLY); if (setns(nsfd, CLONE_NEWIPC) == -1) { return 1; } kill(pid, SIGTERM); pid = 0; { char buf[4096]; ssize_t rv; int fd; fd = open("/proc/sysvipc/shm", O_RDONLY); if (fd == -1) { return 1; } #define S32 " key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n" #define S64 " key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n" rv = read(fd, buf, sizeof(buf)); if (rv == strlen(S32)) { assert(memcmp(buf, S32, strlen(S32)) == 0); } else if (rv == strlen(S64)) { assert(memcmp(buf, S64, strlen(S64)) == 0); } else { assert(0); } } return 0; }
linux-master
tools/testing/selftests/proc/setns-sysvipc.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test that boottime value in /proc/uptime and CLOCK_BOOTTIME increment // monotonically while shifting across CPUs. We don't test idle time // monotonicity due to broken iowait task counting, cf: comment above // get_cpu_idle_time_us() #undef NDEBUG #include <assert.h> #include <errno.h> #include <unistd.h> #include <sys/syscall.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "proc-uptime.h" static inline int sys_sched_getaffinity(pid_t pid, unsigned int len, unsigned long *m) { return syscall(SYS_sched_getaffinity, pid, len, m); } static inline int sys_sched_setaffinity(pid_t pid, unsigned int len, unsigned long *m) { return syscall(SYS_sched_setaffinity, pid, len, m); } int main(void) { uint64_t u0, u1, c0, c1; unsigned int len; unsigned long *m; unsigned int cpu; int fd; /* find out "nr_cpu_ids" */ m = NULL; len = 0; do { len += sizeof(unsigned long); free(m); m = malloc(len); } while (sys_sched_getaffinity(0, len, m) == -1 && errno == EINVAL); fd = open("/proc/uptime", O_RDONLY); assert(fd >= 0); u0 = proc_uptime(fd); c0 = clock_boottime(); for (cpu = 0; cpu < len * 8; cpu++) { memset(m, 0, len); m[cpu / (8 * sizeof(unsigned long))] |= 1UL << (cpu % (8 * sizeof(unsigned long))); /* CPU might not exist, ignore error */ sys_sched_setaffinity(0, len, m); u1 = proc_uptime(fd); c1 = clock_boottime(); /* Is /proc/uptime monotonic ? */ assert(u1 >= u0); /* Is CLOCK_BOOTTIME monotonic ? */ assert(c1 >= c0); /* Is CLOCK_BOOTTIME VS /proc/uptime monotonic ? */ assert(c0 >= u0); u0 = u1; c0 = c1; } return 0; }
linux-master
tools/testing/selftests/proc/proc-uptime-002.c
/* * Copyright © 2020 Alexey Gladkov <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <assert.h> #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <linux/mount.h> #include <linux/unistd.h> static inline int fsopen(const char *fsname, unsigned int flags) { return syscall(__NR_fsopen, fsname, flags); } static inline int fsconfig(int fd, unsigned int cmd, const char *key, const void *val, int aux) { return syscall(__NR_fsconfig, fd, cmd, key, val, aux); } int main(void) { int fsfd, ret; int hidepid = 2; assert((fsfd = fsopen("proc", 0)) != -1); ret = fsconfig(fsfd, FSCONFIG_SET_BINARY, "hidepid", &hidepid, 0); assert(ret == -1); assert(errno == EINVAL); assert(!fsconfig(fsfd, FSCONFIG_SET_STRING, "hidepid", "2", 0)); assert(!fsconfig(fsfd, FSCONFIG_SET_STRING, "hidepid", "invisible", 0)); assert(!close(fsfd)); return 0; }
linux-master
tools/testing/selftests/proc/proc-fsconfig-hidepid.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test // 1) read and lseek on every file in /proc // 2) readlink of every symlink in /proc // 3) recursively (1) + (2) for every directory in /proc // 4) write to /proc/*/clear_refs and /proc/*/task/*/clear_refs // 5) write to /proc/sysrq-trigger #undef NDEBUG #include <assert.h> #include <errno.h> #include <sys/types.h> #include <dirent.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/vfs.h> #include <fcntl.h> #include <unistd.h> #include "proc.h" static void f_reg(DIR *d, const char *filename) { char buf[4096]; int fd; ssize_t rv; /* read from /proc/kmsg can block */ fd = openat(dirfd(d), filename, O_RDONLY|O_NONBLOCK); if (fd == -1) return; /* struct proc_ops::proc_lseek is mandatory if file is seekable. */ (void)lseek(fd, 0, SEEK_SET); rv = read(fd, buf, sizeof(buf)); assert((0 <= rv && rv <= sizeof(buf)) || rv == -1); close(fd); } static void f_reg_write(DIR *d, const char *filename, const char *buf, size_t len) { int fd; ssize_t rv; fd = openat(dirfd(d), filename, O_WRONLY); if (fd == -1) return; rv = write(fd, buf, len); assert((0 <= rv && rv <= len) || rv == -1); close(fd); } static void f_lnk(DIR *d, const char *filename) { char buf[4096]; ssize_t rv; rv = readlinkat(dirfd(d), filename, buf, sizeof(buf)); assert((0 <= rv && rv <= sizeof(buf)) || rv == -1); } static void f(DIR *d, unsigned int level) { struct dirent *de; de = xreaddir(d); assert(de->d_type == DT_DIR); assert(streq(de->d_name, ".")); de = xreaddir(d); assert(de->d_type == DT_DIR); assert(streq(de->d_name, "..")); while ((de = xreaddir(d))) { assert(!streq(de->d_name, ".")); assert(!streq(de->d_name, "..")); switch (de->d_type) { DIR *dd; int fd; case DT_REG: if (level == 0 && streq(de->d_name, "sysrq-trigger")) { f_reg_write(d, de->d_name, "h", 1); } else if (level == 1 && streq(de->d_name, "clear_refs")) { f_reg_write(d, de->d_name, "1", 1); } else if (level == 3 && streq(de->d_name, "clear_refs")) { f_reg_write(d, de->d_name, "1", 1); } else { f_reg(d, de->d_name); } break; case DT_DIR: fd = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY); if (fd == -1) continue; dd = fdopendir(fd); if (!dd) continue; f(dd, level + 1); closedir(dd); break; case DT_LNK: f_lnk(d, de->d_name); break; default: assert(0); } } } int main(void) { DIR *d; struct statfs sfs; d = opendir("/proc"); if (!d) return 4; /* Ensure /proc is proc. */ if (fstatfs(dirfd(d), &sfs) == -1) { return 1; } if (sfs.f_type != 0x9fa0) { fprintf(stderr, "error: unexpected f_type %lx\n", (long)sfs.f_type); return 2; } f(d, 0); return 0; }
linux-master
tools/testing/selftests/proc/read.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test that /proc/self gives correct TGID. #undef NDEBUG #include <assert.h> #include <stdio.h> #include <unistd.h> #include "proc.h" int main(void) { char buf1[64], buf2[64]; pid_t pid; ssize_t rv; pid = sys_getpid(); snprintf(buf1, sizeof(buf1), "%u", pid); rv = readlink("/proc/self", buf2, sizeof(buf2)); assert(rv == strlen(buf1)); buf2[rv] = '\0'; assert(streq(buf1, buf2)); return 0; }
linux-master
tools/testing/selftests/proc/self.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Test readlink /proc/self/map_files/... with minimum address. */ #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> #include <stdlib.h> static void pass(const char *fmt, unsigned long a, unsigned long b) { char name[64]; char buf[64]; snprintf(name, sizeof(name), fmt, a, b); if (readlink(name, buf, sizeof(buf)) == -1) exit(1); } static void fail(const char *fmt, unsigned long a, unsigned long b) { char name[64]; char buf[64]; snprintf(name, sizeof(name), fmt, a, b); if (readlink(name, buf, sizeof(buf)) == -1 && errno == ENOENT) return; exit(1); } int main(void) { const int PAGE_SIZE = sysconf(_SC_PAGESIZE); /* * va_max must be enough bigger than vm.mmap_min_addr, which is * 64KB/32KB by default. (depends on CONFIG_LSM_MMAP_MIN_ADDR) */ const unsigned long va_max = 1UL << 20; unsigned long va; void *p; int fd; unsigned long a, b; fd = open("/dev/zero", O_RDONLY); if (fd == -1) return 1; for (va = 0; va < va_max; va += PAGE_SIZE) { p = mmap((void *)va, PAGE_SIZE, PROT_NONE, MAP_PRIVATE|MAP_FILE|MAP_FIXED, fd, 0); if (p == (void *)va) break; } if (va == va_max) { fprintf(stderr, "error: mmap doesn't like you\n"); return 1; } a = (unsigned long)p; b = (unsigned long)p + PAGE_SIZE; pass("/proc/self/map_files/%lx-%lx", a, b); fail("/proc/self/map_files/ %lx-%lx", a, b); fail("/proc/self/map_files/%lx -%lx", a, b); fail("/proc/self/map_files/%lx- %lx", a, b); fail("/proc/self/map_files/%lx-%lx ", a, b); fail("/proc/self/map_files/0%lx-%lx", a, b); fail("/proc/self/map_files/%lx-0%lx", a, b); if (sizeof(long) == 4) { fail("/proc/self/map_files/100000000%lx-%lx", a, b); fail("/proc/self/map_files/%lx-100000000%lx", a, b); } else if (sizeof(long) == 8) { fail("/proc/self/map_files/10000000000000000%lx-%lx", a, b); fail("/proc/self/map_files/%lx-10000000000000000%lx", a, b); } else return 1; return 0; }
linux-master
tools/testing/selftests/proc/proc-self-map-files-002.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test /proc/*/fd lookup. #undef NDEBUG #include <assert.h> #include <dirent.h> #include <errno.h> #include <limits.h> #include <sched.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "proc.h" /* lstat(2) has more "coverage" in case non-symlink pops up somehow. */ static void test_lookup_pass(const char *pathname) { struct stat st; ssize_t rv; memset(&st, 0, sizeof(struct stat)); rv = lstat(pathname, &st); assert(rv == 0); assert(S_ISLNK(st.st_mode)); } static void test_lookup_fail(const char *pathname) { struct stat st; ssize_t rv; rv = lstat(pathname, &st); assert(rv == -1 && errno == ENOENT); } static void test_lookup(unsigned int fd) { char buf[64]; unsigned int c; unsigned int u; int i; snprintf(buf, sizeof(buf), "/proc/self/fd/%u", fd); test_lookup_pass(buf); /* leading junk */ for (c = 1; c <= 255; c++) { if (c == '/') continue; snprintf(buf, sizeof(buf), "/proc/self/fd/%c%u", c, fd); test_lookup_fail(buf); } /* trailing junk */ for (c = 1; c <= 255; c++) { if (c == '/') continue; snprintf(buf, sizeof(buf), "/proc/self/fd/%u%c", fd, c); test_lookup_fail(buf); } for (i = INT_MIN; i < INT_MIN + 1024; i++) { snprintf(buf, sizeof(buf), "/proc/self/fd/%d", i); test_lookup_fail(buf); } for (i = -1024; i < 0; i++) { snprintf(buf, sizeof(buf), "/proc/self/fd/%d", i); test_lookup_fail(buf); } for (u = INT_MAX - 1024; u <= (unsigned int)INT_MAX + 1024; u++) { snprintf(buf, sizeof(buf), "/proc/self/fd/%u", u); test_lookup_fail(buf); } for (u = UINT_MAX - 1024; u != 0; u++) { snprintf(buf, sizeof(buf), "/proc/self/fd/%u", u); test_lookup_fail(buf); } } int main(void) { struct dirent *de; unsigned int fd, target_fd; if (unshare(CLONE_FILES) == -1) return 1; /* Wipe fdtable. */ do { DIR *d; d = opendir("/proc/self/fd"); if (!d) return 1; de = xreaddir(d); assert(de->d_type == DT_DIR); assert(streq(de->d_name, ".")); de = xreaddir(d); assert(de->d_type == DT_DIR); assert(streq(de->d_name, "..")); next: de = xreaddir(d); if (de) { unsigned long long fd_ull; unsigned int fd; char *end; assert(de->d_type == DT_LNK); fd_ull = xstrtoull(de->d_name, &end); assert(*end == '\0'); assert(fd_ull == (unsigned int)fd_ull); fd = fd_ull; if (fd == dirfd(d)) goto next; close(fd); } closedir(d); } while (de); /* Now fdtable is clean. */ fd = open("/", O_PATH|O_DIRECTORY); assert(fd == 0); test_lookup(fd); close(fd); /* Clean again! */ fd = open("/", O_PATH|O_DIRECTORY); assert(fd == 0); /* Default RLIMIT_NOFILE-1 */ target_fd = 1023; while (target_fd > 0) { if (dup2(fd, target_fd) == target_fd) break; target_fd /= 2; } assert(target_fd > 0); close(fd); test_lookup(target_fd); close(target_fd); return 0; }
linux-master
tools/testing/selftests/proc/fd-001-lookup.c
#if defined __amd64__ || defined __i386__ /* * Copyright (c) 2022 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Create a process without mappings by unmapping everything at once and * holding it with ptrace(2). See what happens to * * /proc/${pid}/maps * /proc/${pid}/numa_maps * /proc/${pid}/smaps * /proc/${pid}/smaps_rollup */ #undef NDEBUG #include <assert.h> #include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/ptrace.h> #include <sys/resource.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #ifdef __amd64__ #define TEST_VSYSCALL #endif /* * 0: vsyscall VMA doesn't exist vsyscall=none * 1: vsyscall VMA is --xp vsyscall=xonly * 2: vsyscall VMA is r-xp vsyscall=emulate */ static volatile int g_vsyscall; static const char *g_proc_pid_maps_vsyscall; static const char *g_proc_pid_smaps_vsyscall; static const char proc_pid_maps_vsyscall_0[] = ""; static const char proc_pid_maps_vsyscall_1[] = "ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]\n"; static const char proc_pid_maps_vsyscall_2[] = "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]\n"; static const char proc_pid_smaps_vsyscall_0[] = ""; static const char proc_pid_smaps_vsyscall_1[] = "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]\n" "Size: 4 kB\n" "KernelPageSize: 4 kB\n" "MMUPageSize: 4 kB\n" "Rss: 0 kB\n" "Pss: 0 kB\n" "Pss_Dirty: 0 kB\n" "Shared_Clean: 0 kB\n" "Shared_Dirty: 0 kB\n" "Private_Clean: 0 kB\n" "Private_Dirty: 0 kB\n" "Referenced: 0 kB\n" "Anonymous: 0 kB\n" "LazyFree: 0 kB\n" "AnonHugePages: 0 kB\n" "ShmemPmdMapped: 0 kB\n" "FilePmdMapped: 0 kB\n" "Shared_Hugetlb: 0 kB\n" "Private_Hugetlb: 0 kB\n" "Swap: 0 kB\n" "SwapPss: 0 kB\n" "Locked: 0 kB\n" "THPeligible: 0\n" /* * "ProtectionKey:" field is conditional. It is possible to check it as well, * but I don't have such machine. */ ; static const char proc_pid_smaps_vsyscall_2[] = "ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]\n" "Size: 4 kB\n" "KernelPageSize: 4 kB\n" "MMUPageSize: 4 kB\n" "Rss: 0 kB\n" "Pss: 0 kB\n" "Pss_Dirty: 0 kB\n" "Shared_Clean: 0 kB\n" "Shared_Dirty: 0 kB\n" "Private_Clean: 0 kB\n" "Private_Dirty: 0 kB\n" "Referenced: 0 kB\n" "Anonymous: 0 kB\n" "LazyFree: 0 kB\n" "AnonHugePages: 0 kB\n" "ShmemPmdMapped: 0 kB\n" "FilePmdMapped: 0 kB\n" "Shared_Hugetlb: 0 kB\n" "Private_Hugetlb: 0 kB\n" "Swap: 0 kB\n" "SwapPss: 0 kB\n" "Locked: 0 kB\n" "THPeligible: 0\n" /* * "ProtectionKey:" field is conditional. It is possible to check it as well, * but I'm too tired. */ ; static void sigaction_SIGSEGV(int _, siginfo_t *__, void *___) { _exit(EXIT_FAILURE); } #ifdef TEST_VSYSCALL static void sigaction_SIGSEGV_vsyscall(int _, siginfo_t *__, void *___) { _exit(g_vsyscall); } /* * vsyscall page can't be unmapped, probe it directly. */ static void vsyscall(void) { pid_t pid; int wstatus; pid = fork(); if (pid < 0) { fprintf(stderr, "fork, errno %d\n", errno); exit(1); } if (pid == 0) { setrlimit(RLIMIT_CORE, &(struct rlimit){}); /* Hide "segfault at ffffffffff600000" messages. */ struct sigaction act = {}; act.sa_flags = SA_SIGINFO; act.sa_sigaction = sigaction_SIGSEGV_vsyscall; sigaction(SIGSEGV, &act, NULL); g_vsyscall = 0; /* gettimeofday(NULL, NULL); */ uint64_t rax = 0xffffffffff600000; asm volatile ( "call *%[rax]" : [rax] "+a" (rax) : "D" (NULL), "S" (NULL) : "rcx", "r11" ); g_vsyscall = 1; *(volatile int *)0xffffffffff600000UL; g_vsyscall = 2; exit(g_vsyscall); } waitpid(pid, &wstatus, 0); if (WIFEXITED(wstatus)) { g_vsyscall = WEXITSTATUS(wstatus); } else { fprintf(stderr, "error: vsyscall wstatus %08x\n", wstatus); exit(1); } } #endif static int test_proc_pid_maps(pid_t pid) { char buf[4096]; snprintf(buf, sizeof(buf), "/proc/%u/maps", pid); int fd = open(buf, O_RDONLY); if (fd == -1) { perror("open /proc/${pid}/maps"); return EXIT_FAILURE; } else { ssize_t rv = read(fd, buf, sizeof(buf)); close(fd); if (g_vsyscall == 0) { assert(rv == 0); } else { size_t len = strlen(g_proc_pid_maps_vsyscall); assert(rv == len); assert(memcmp(buf, g_proc_pid_maps_vsyscall, len) == 0); } return EXIT_SUCCESS; } } static int test_proc_pid_numa_maps(pid_t pid) { char buf[4096]; snprintf(buf, sizeof(buf), "/proc/%u/numa_maps", pid); int fd = open(buf, O_RDONLY); if (fd == -1) { if (errno == ENOENT) { /* * /proc/${pid}/numa_maps is under CONFIG_NUMA, * it doesn't necessarily exist. */ return EXIT_SUCCESS; } perror("open /proc/${pid}/numa_maps"); return EXIT_FAILURE; } else { ssize_t rv = read(fd, buf, sizeof(buf)); close(fd); assert(rv == 0); return EXIT_SUCCESS; } } static int test_proc_pid_smaps(pid_t pid) { char buf[4096]; snprintf(buf, sizeof(buf), "/proc/%u/smaps", pid); int fd = open(buf, O_RDONLY); if (fd == -1) { if (errno == ENOENT) { /* * /proc/${pid}/smaps is under CONFIG_PROC_PAGE_MONITOR, * it doesn't necessarily exist. */ return EXIT_SUCCESS; } perror("open /proc/${pid}/smaps"); return EXIT_FAILURE; } else { ssize_t rv = read(fd, buf, sizeof(buf)); close(fd); if (g_vsyscall == 0) { assert(rv == 0); } else { size_t len = strlen(g_proc_pid_maps_vsyscall); /* TODO "ProtectionKey:" */ assert(rv > len); assert(memcmp(buf, g_proc_pid_maps_vsyscall, len) == 0); } return EXIT_SUCCESS; } } static const char g_smaps_rollup[] = "00000000-00000000 ---p 00000000 00:00 0 [rollup]\n" "Rss: 0 kB\n" "Pss: 0 kB\n" "Pss_Dirty: 0 kB\n" "Pss_Anon: 0 kB\n" "Pss_File: 0 kB\n" "Pss_Shmem: 0 kB\n" "Shared_Clean: 0 kB\n" "Shared_Dirty: 0 kB\n" "Private_Clean: 0 kB\n" "Private_Dirty: 0 kB\n" "Referenced: 0 kB\n" "Anonymous: 0 kB\n" "KSM: 0 kB\n" "LazyFree: 0 kB\n" "AnonHugePages: 0 kB\n" "ShmemPmdMapped: 0 kB\n" "FilePmdMapped: 0 kB\n" "Shared_Hugetlb: 0 kB\n" "Private_Hugetlb: 0 kB\n" "Swap: 0 kB\n" "SwapPss: 0 kB\n" "Locked: 0 kB\n" ; static int test_proc_pid_smaps_rollup(pid_t pid) { char buf[4096]; snprintf(buf, sizeof(buf), "/proc/%u/smaps_rollup", pid); int fd = open(buf, O_RDONLY); if (fd == -1) { if (errno == ENOENT) { /* * /proc/${pid}/smaps_rollup is under CONFIG_PROC_PAGE_MONITOR, * it doesn't necessarily exist. */ return EXIT_SUCCESS; } perror("open /proc/${pid}/smaps_rollup"); return EXIT_FAILURE; } else { ssize_t rv = read(fd, buf, sizeof(buf)); close(fd); assert(rv == sizeof(g_smaps_rollup) - 1); assert(memcmp(buf, g_smaps_rollup, sizeof(g_smaps_rollup) - 1) == 0); return EXIT_SUCCESS; } } int main(void) { int rv = EXIT_SUCCESS; #ifdef TEST_VSYSCALL vsyscall(); #endif switch (g_vsyscall) { case 0: g_proc_pid_maps_vsyscall = proc_pid_maps_vsyscall_0; g_proc_pid_smaps_vsyscall = proc_pid_smaps_vsyscall_0; break; case 1: g_proc_pid_maps_vsyscall = proc_pid_maps_vsyscall_1; g_proc_pid_smaps_vsyscall = proc_pid_smaps_vsyscall_1; break; case 2: g_proc_pid_maps_vsyscall = proc_pid_maps_vsyscall_2; g_proc_pid_smaps_vsyscall = proc_pid_smaps_vsyscall_2; break; default: abort(); } pid_t pid = fork(); if (pid == -1) { perror("fork"); return EXIT_FAILURE; } else if (pid == 0) { rv = ptrace(PTRACE_TRACEME, 0, NULL, NULL); if (rv != 0) { if (errno == EPERM) { fprintf(stderr, "Did you know? ptrace(PTRACE_TRACEME) doesn't work under strace.\n" ); kill(getppid(), SIGTERM); return EXIT_FAILURE; } perror("ptrace PTRACE_TRACEME"); return EXIT_FAILURE; } /* * Hide "segfault at ..." messages. Signal handler won't run. */ struct sigaction act = {}; act.sa_flags = SA_SIGINFO; act.sa_sigaction = sigaction_SIGSEGV; sigaction(SIGSEGV, &act, NULL); #ifdef __amd64__ munmap(NULL, ((size_t)1 << 47) - 4096); #elif defined __i386__ { size_t len; for (len = -4096;; len -= 4096) { munmap(NULL, len); } } #else #error "implement 'unmap everything'" #endif return EXIT_FAILURE; } else { /* * TODO find reliable way to signal parent that munmap(2) completed. * Child can't do it directly because it effectively doesn't exist * anymore. Looking at child's VM files isn't 100% reliable either: * due to a bug they may not become empty or empty-like. */ sleep(1); if (rv == EXIT_SUCCESS) { rv = test_proc_pid_maps(pid); } if (rv == EXIT_SUCCESS) { rv = test_proc_pid_numa_maps(pid); } if (rv == EXIT_SUCCESS) { rv = test_proc_pid_smaps(pid); } if (rv == EXIT_SUCCESS) { rv = test_proc_pid_smaps_rollup(pid); } /* * TODO test /proc/${pid}/statm, task_statm() * ->start_code, ->end_code aren't updated by munmap(). * Output can be "0 0 0 2 0 0 0\n" where "2" can be anything. */ /* Cut the rope. */ int wstatus; waitpid(pid, &wstatus, 0); assert(WIFSTOPPED(wstatus)); assert(WSTOPSIG(wstatus) == SIGSEGV); } return rv; } #else int main(void) { return 4; } #endif
linux-master
tools/testing/selftests/proc/proc-empty-vm.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test that /proc/thread-self gives correct TGID/PID. #undef NDEBUG #include <assert.h> #include <sched.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> #include <sys/wait.h> #include "proc.h" int f(void *arg) { char buf1[64], buf2[64]; pid_t pid, tid; ssize_t rv; pid = sys_getpid(); tid = sys_gettid(); snprintf(buf1, sizeof(buf1), "%u/task/%u", pid, tid); rv = readlink("/proc/thread-self", buf2, sizeof(buf2)); assert(rv == strlen(buf1)); buf2[rv] = '\0'; assert(streq(buf1, buf2)); if (arg) exit(0); return 0; } int main(void) { const int PAGE_SIZE = sysconf(_SC_PAGESIZE); pid_t pid; void *stack; /* main thread */ f((void *)0); stack = mmap(NULL, 2 * PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); assert(stack != MAP_FAILED); /* side thread */ pid = clone(f, stack + PAGE_SIZE, CLONE_THREAD|CLONE_SIGHAND|CLONE_VM, (void *)1); assert(pid > 0); pause(); return 0; }
linux-master
tools/testing/selftests/proc/thread-self.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test that /proc/$KERNEL_THREAD/fd/ is empty. #undef NDEBUG #include <sys/syscall.h> #include <assert.h> #include <dirent.h> #include <limits.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "proc.h" #define PF_KHTREAD 0x00200000 /* * Test for kernel threadness atomically with openat(). * * Return /proc/$PID/fd descriptor if process is kernel thread. * Return -1 if a process is userspace process. */ static int kernel_thread_fd(unsigned int pid) { unsigned int flags = 0; char buf[4096]; int dir_fd, fd; ssize_t rv; snprintf(buf, sizeof(buf), "/proc/%u", pid); dir_fd = open(buf, O_RDONLY|O_DIRECTORY); if (dir_fd == -1) return -1; /* * Believe it or not, struct task_struct::flags is directly exposed * to userspace! */ fd = openat(dir_fd, "stat", O_RDONLY); if (fd == -1) { close(dir_fd); return -1; } rv = read(fd, buf, sizeof(buf)); close(fd); if (0 < rv && rv <= sizeof(buf)) { unsigned long long flags_ull; char *p, *end; int i; assert(buf[rv - 1] == '\n'); buf[rv - 1] = '\0'; /* Search backwards: ->comm can contain whitespace and ')'. */ for (i = 0; i < 43; i++) { p = strrchr(buf, ' '); assert(p); *p = '\0'; } p = strrchr(buf, ' '); assert(p); flags_ull = xstrtoull(p + 1, &end); assert(*end == '\0'); assert(flags_ull == (unsigned int)flags_ull); flags = flags_ull; } fd = -1; if (flags & PF_KHTREAD) { fd = openat(dir_fd, "fd", O_RDONLY|O_DIRECTORY); } close(dir_fd); return fd; } static void test_readdir(int fd) { DIR *d; struct dirent *de; d = fdopendir(fd); assert(d); de = xreaddir(d); assert(streq(de->d_name, ".")); assert(de->d_type == DT_DIR); de = xreaddir(d); assert(streq(de->d_name, "..")); assert(de->d_type == DT_DIR); de = xreaddir(d); assert(!de); } static inline int sys_statx(int dirfd, const char *pathname, int flags, unsigned int mask, void *stx) { return syscall(SYS_statx, dirfd, pathname, flags, mask, stx); } static void test_lookup_fail(int fd, const char *pathname) { char stx[256] __attribute__((aligned(8))); int rv; rv = sys_statx(fd, pathname, AT_SYMLINK_NOFOLLOW, 0, (void *)stx); assert(rv == -1 && errno == ENOENT); } static void test_lookup(int fd) { char buf[64]; unsigned int u; int i; for (i = INT_MIN; i < INT_MIN + 1024; i++) { snprintf(buf, sizeof(buf), "%d", i); test_lookup_fail(fd, buf); } for (i = -1024; i < 1024; i++) { snprintf(buf, sizeof(buf), "%d", i); test_lookup_fail(fd, buf); } for (u = INT_MAX - 1024; u < (unsigned int)INT_MAX + 1024; u++) { snprintf(buf, sizeof(buf), "%u", u); test_lookup_fail(fd, buf); } for (u = UINT_MAX - 1024; u != 0; u++) { snprintf(buf, sizeof(buf), "%u", u); test_lookup_fail(fd, buf); } } int main(void) { unsigned int pid; int fd; /* * In theory this will loop indefinitely if kernel threads are exiled * from /proc. * * Start with kthreadd. */ pid = 2; while ((fd = kernel_thread_fd(pid)) == -1 && pid < 1024) { pid++; } /* EACCES if run as non-root. */ if (pid >= 1024) return 1; test_readdir(fd); test_lookup(fd); return 0; }
linux-master
tools/testing/selftests/proc/fd-003-kthread.c
/* * Copyright (c) 2021 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // Test that /proc/*/task never contains "0". #include <sys/types.h> #include <dirent.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> static pid_t pid = -1; static void atexit_hook(void) { if (pid > 0) { kill(pid, SIGKILL); } } static void *f(void *_) { return NULL; } static void sigalrm(int _) { exit(0); } int main(void) { pid = fork(); if (pid == 0) { /* child */ while (1) { pthread_t pth; pthread_create(&pth, NULL, f, NULL); pthread_join(pth, NULL); } } else if (pid > 0) { /* parent */ atexit(atexit_hook); char buf[64]; snprintf(buf, sizeof(buf), "/proc/%u/task", pid); signal(SIGALRM, sigalrm); alarm(1); while (1) { DIR *d = opendir(buf); struct dirent *de; while ((de = readdir(d))) { if (strcmp(de->d_name, "0") == 0) { exit(1); } } closedir(d); } return 0; } else { perror("fork"); return 1; } }
linux-master
tools/testing/selftests/proc/proc-tid0.c
/* * Copyright © 2018 Alexey Dobriyan <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <unistd.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdio.h> static inline ssize_t sys_read(int fd, void *buf, size_t len) { return syscall(SYS_read, fd, buf, len); } int main(void) { char buf1[64]; char buf2[64]; int fd; ssize_t rv; fd = open("/proc/self/syscall", O_RDONLY); if (fd == -1) { if (errno == ENOENT) return 4; return 1; } /* Do direct system call as libc can wrap anything. */ snprintf(buf1, sizeof(buf1), "%ld 0x%lx 0x%lx 0x%lx", (long)SYS_read, (long)fd, (long)buf2, (long)sizeof(buf2)); memset(buf2, 0, sizeof(buf2)); rv = sys_read(fd, buf2, sizeof(buf2)); if (rv < 0) return 1; if (rv < strlen(buf1)) return 1; if (strncmp(buf1, buf2, strlen(buf1)) != 0) return 1; return 0; }
linux-master
tools/testing/selftests/proc/proc-self-syscall.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <sched.h> #include <stdio.h> #include <stdbool.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include "log.h" #include "timens.h" #define OFFSET (36000) struct thread_args { char *tst_name; struct timespec *now; }; static void *tcheck(void *_args) { struct thread_args *args = _args; struct timespec *now = args->now, tst; int i; for (i = 0; i < 2; i++) { _gettime(CLOCK_MONOTONIC, &tst, i); if (abs(tst.tv_sec - now->tv_sec) > 5) { pr_fail("%s: in-thread: unexpected value: %ld (%ld)\n", args->tst_name, tst.tv_sec, now->tv_sec); return (void *)1UL; } } return NULL; } static int check_in_thread(char *tst_name, struct timespec *now) { struct thread_args args = { .tst_name = tst_name, .now = now, }; pthread_t th; void *retval; if (pthread_create(&th, NULL, tcheck, &args)) return pr_perror("thread"); if (pthread_join(th, &retval)) return pr_perror("pthread_join"); return !(retval == NULL); } static int check(char *tst_name, struct timespec *now) { struct timespec tst; int i; for (i = 0; i < 2; i++) { _gettime(CLOCK_MONOTONIC, &tst, i); if (abs(tst.tv_sec - now->tv_sec) > 5) return pr_fail("%s: unexpected value: %ld (%ld)\n", tst_name, tst.tv_sec, now->tv_sec); } if (check_in_thread(tst_name, now)) return 1; ksft_test_result_pass("%s\n", tst_name); return 0; } int main(int argc, char *argv[]) { struct timespec now; int status; pid_t pid; if (argc > 1) { char *endptr; ksft_cnt.ksft_pass = 1; now.tv_sec = strtoul(argv[1], &endptr, 0); if (*endptr != 0) return pr_perror("strtoul"); return check("child after exec", &now); } nscheck(); ksft_set_plan(4); clock_gettime(CLOCK_MONOTONIC, &now); if (unshare_timens()) return 1; if (_settime(CLOCK_MONOTONIC, OFFSET)) return 1; if (check("parent before vfork", &now)) return 1; pid = vfork(); if (pid < 0) return pr_perror("fork"); if (pid == 0) { char now_str[64]; char *cargv[] = {"exec", now_str, NULL}; char *cenv[] = {NULL}; /* Check for proper vvar offsets after execve. */ snprintf(now_str, sizeof(now_str), "%ld", now.tv_sec + OFFSET); execve("/proc/self/exe", cargv, cenv); pr_perror("execve"); _exit(1); } if (waitpid(pid, &status, 0) != pid) return pr_perror("waitpid"); if (status) ksft_exit_fail(); ksft_inc_pass_cnt(); ksft_test_result_pass("wait for child\n"); /* Check that we are still in the source timens. */ if (check("parent after vfork", &now)) return 1; ksft_exit_pass(); return 0; }
linux-master
tools/testing/selftests/timens/vfork_exec.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <sched.h> #include <sys/timerfd.h> #include <sys/syscall.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <pthread.h> #include <signal.h> #include <string.h> #include "log.h" #include "timens.h" void test_sig(int sig) { if (sig == SIGUSR2) pthread_exit(NULL); } struct thread_args { struct timespec *now, *rem; pthread_mutex_t *lock; int clockid; int abs; }; void *call_nanosleep(void *_args) { struct thread_args *args = _args; clock_nanosleep(args->clockid, args->abs ? TIMER_ABSTIME : 0, args->now, args->rem); pthread_mutex_unlock(args->lock); return NULL; } int run_test(int clockid, int abs) { struct timespec now = {}, rem; struct thread_args args = { .now = &now, .rem = &rem, .clockid = clockid}; struct timespec start; pthread_mutex_t lock; pthread_t thread; int j, ok, ret; signal(SIGUSR1, test_sig); signal(SIGUSR2, test_sig); pthread_mutex_init(&lock, NULL); pthread_mutex_lock(&lock); if (clock_gettime(clockid, &start) == -1) { if (errno == EINVAL && check_skip(clockid)) return 0; return pr_perror("clock_gettime"); } if (abs) { now.tv_sec = start.tv_sec; now.tv_nsec = start.tv_nsec; } now.tv_sec += 3600; args.abs = abs; args.lock = &lock; ret = pthread_create(&thread, NULL, call_nanosleep, &args); if (ret != 0) { pr_err("Unable to create a thread: %s", strerror(ret)); return 1; } /* Wait when the thread will call clock_nanosleep(). */ ok = 0; for (j = 0; j < 8; j++) { /* The maximum timeout is about 5 seconds. */ usleep(10000 << j); /* Try to interrupt clock_nanosleep(). */ pthread_kill(thread, SIGUSR1); usleep(10000 << j); /* Check whether clock_nanosleep() has been interrupted or not. */ if (pthread_mutex_trylock(&lock) == 0) { /**/ ok = 1; break; } } if (!ok) pthread_kill(thread, SIGUSR2); pthread_join(thread, NULL); pthread_mutex_destroy(&lock); if (!ok) { ksft_test_result_pass("clockid: %d abs:%d timeout\n", clockid, abs); return 1; } if (rem.tv_sec < 3300 || rem.tv_sec > 3900) { pr_fail("clockid: %d abs: %d remain: %ld\n", clockid, abs, rem.tv_sec); return 1; } ksft_test_result_pass("clockid: %d abs:%d\n", clockid, abs); return 0; } int main(int argc, char *argv[]) { int ret, nsfd; nscheck(); ksft_set_plan(4); check_supported_timers(); if (unshare_timens()) return 1; if (_settime(CLOCK_MONOTONIC, 7 * 24 * 3600)) return 1; if (_settime(CLOCK_BOOTTIME, 9 * 24 * 3600)) return 1; nsfd = open("/proc/self/ns/time_for_children", O_RDONLY); if (nsfd < 0) return pr_perror("Unable to open timens_for_children"); if (setns(nsfd, CLONE_NEWTIME)) return pr_perror("Unable to set timens"); ret = 0; ret |= run_test(CLOCK_MONOTONIC, 0); ret |= run_test(CLOCK_MONOTONIC, 1); ret |= run_test(CLOCK_BOOTTIME_ALARM, 0); ret |= run_test(CLOCK_BOOTTIME_ALARM, 1); if (ret) ksft_exit_fail(); ksft_exit_pass(); return ret; }
linux-master
tools/testing/selftests/timens/clock_nanosleep.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <sched.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <signal.h> #include "log.h" #include "timens.h" int run_test(int clockid, struct timespec now) { struct itimerspec new_value; long long elapsed; timer_t fd; int i; if (check_skip(clockid)) return 0; for (i = 0; i < 2; i++) { struct sigevent sevp = {.sigev_notify = SIGEV_NONE}; int flags = 0; new_value.it_value.tv_sec = 3600; new_value.it_value.tv_nsec = 0; new_value.it_interval.tv_sec = 1; new_value.it_interval.tv_nsec = 0; if (i == 1) { new_value.it_value.tv_sec += now.tv_sec; new_value.it_value.tv_nsec += now.tv_nsec; } if (timer_create(clockid, &sevp, &fd) == -1) { if (errno == ENOSYS) { ksft_test_result_skip("Posix Clocks & timers are supported\n"); return 0; } return pr_perror("timerfd_create"); } if (i == 1) flags |= TIMER_ABSTIME; if (timer_settime(fd, flags, &new_value, NULL) == -1) return pr_perror("timerfd_settime"); if (timer_gettime(fd, &new_value) == -1) return pr_perror("timerfd_gettime"); elapsed = new_value.it_value.tv_sec; if (abs(elapsed - 3600) > 60) { ksft_test_result_fail("clockid: %d elapsed: %lld\n", clockid, elapsed); return 1; } } ksft_test_result_pass("clockid=%d\n", clockid); return 0; } int main(int argc, char *argv[]) { int ret, status, len, fd; char buf[4096]; pid_t pid; struct timespec btime_now, mtime_now; nscheck(); check_supported_timers(); ksft_set_plan(3); clock_gettime(CLOCK_MONOTONIC, &mtime_now); clock_gettime(CLOCK_BOOTTIME, &btime_now); if (unshare_timens()) return 1; len = snprintf(buf, sizeof(buf), "%d %d 0\n%d %d 0", CLOCK_MONOTONIC, 70 * 24 * 3600, CLOCK_BOOTTIME, 9 * 24 * 3600); fd = open("/proc/self/timens_offsets", O_WRONLY); if (fd < 0) return pr_perror("/proc/self/timens_offsets"); if (write(fd, buf, len) != len) return pr_perror("/proc/self/timens_offsets"); close(fd); mtime_now.tv_sec += 70 * 24 * 3600; btime_now.tv_sec += 9 * 24 * 3600; pid = fork(); if (pid < 0) return pr_perror("Unable to fork"); if (pid == 0) { ret = 0; ret |= run_test(CLOCK_BOOTTIME, btime_now); ret |= run_test(CLOCK_MONOTONIC, mtime_now); ret |= run_test(CLOCK_BOOTTIME_ALARM, btime_now); if (ret) ksft_exit_fail(); ksft_exit_pass(); return ret; } if (waitpid(pid, &status, 0) != pid) return pr_perror("Unable to wait the child process"); if (WIFEXITED(status)) return WEXITSTATUS(status); return 1; }
linux-master
tools/testing/selftests/timens/timer.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <sched.h> #include <stdio.h> #include <stdbool.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <string.h> #include "log.h" #include "timens.h" #define OFFSET (36000) int main(int argc, char *argv[]) { struct timespec now, tst; int status, i; pid_t pid; if (argc > 1) { if (sscanf(argv[1], "%ld", &now.tv_sec) != 1) return pr_perror("sscanf"); for (i = 0; i < 2; i++) { _gettime(CLOCK_MONOTONIC, &tst, i); if (abs(tst.tv_sec - now.tv_sec) > 5) return pr_fail("%ld %ld\n", now.tv_sec, tst.tv_sec); } return 0; } nscheck(); ksft_set_plan(1); clock_gettime(CLOCK_MONOTONIC, &now); if (unshare_timens()) return 1; if (_settime(CLOCK_MONOTONIC, OFFSET)) return 1; for (i = 0; i < 2; i++) { _gettime(CLOCK_MONOTONIC, &tst, i); if (abs(tst.tv_sec - now.tv_sec) > 5) return pr_fail("%ld %ld\n", now.tv_sec, tst.tv_sec); } if (argc > 1) return 0; pid = fork(); if (pid < 0) return pr_perror("fork"); if (pid == 0) { char now_str[64]; char *cargv[] = {"exec", now_str, NULL}; char *cenv[] = {NULL}; /* Check that a child process is in the new timens. */ for (i = 0; i < 2; i++) { _gettime(CLOCK_MONOTONIC, &tst, i); if (abs(tst.tv_sec - now.tv_sec - OFFSET) > 5) return pr_fail("%ld %ld\n", now.tv_sec + OFFSET, tst.tv_sec); } /* Check for proper vvar offsets after execve. */ snprintf(now_str, sizeof(now_str), "%ld", now.tv_sec + OFFSET); execve("/proc/self/exe", cargv, cenv); return pr_perror("execve"); } if (waitpid(pid, &status, 0) != pid) return pr_perror("waitpid"); if (status) ksft_exit_fail(); ksft_test_result_pass("exec\n"); ksft_exit_pass(); return 0; }
linux-master
tools/testing/selftests/timens/exec.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <sched.h> #include <time.h> #include <stdio.h> #include <unistd.h> #include <sys/syscall.h> #include <dlfcn.h> #include "log.h" #include "timens.h" typedef int (*vgettime_t)(clockid_t, struct timespec *); vgettime_t vdso_clock_gettime; static void fill_function_pointers(void) { void *vdso = dlopen("linux-vdso.so.1", RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD); if (!vdso) vdso = dlopen("linux-gate.so.1", RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD); if (!vdso) vdso = dlopen("linux-vdso32.so.1", RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD); if (!vdso) vdso = dlopen("linux-vdso64.so.1", RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD); if (!vdso) { pr_err("[WARN]\tfailed to find vDSO\n"); return; } vdso_clock_gettime = (vgettime_t)dlsym(vdso, "__vdso_clock_gettime"); if (!vdso_clock_gettime) vdso_clock_gettime = (vgettime_t)dlsym(vdso, "__kernel_clock_gettime"); if (!vdso_clock_gettime) pr_err("Warning: failed to find clock_gettime in vDSO\n"); } static void test(clock_t clockid, char *clockstr, bool in_ns) { struct timespec tp, start; long i = 0; const int timeout = 3; vdso_clock_gettime(clockid, &start); tp = start; for (tp = start; start.tv_sec + timeout > tp.tv_sec || (start.tv_sec + timeout == tp.tv_sec && start.tv_nsec > tp.tv_nsec); i++) { vdso_clock_gettime(clockid, &tp); } ksft_test_result_pass("%s:\tclock: %10s\tcycles:\t%10ld\n", in_ns ? "ns" : "host", clockstr, i); } int main(int argc, char *argv[]) { time_t offset = 10; int nsfd; ksft_set_plan(8); fill_function_pointers(); test(CLOCK_MONOTONIC, "monotonic", false); test(CLOCK_MONOTONIC_COARSE, "monotonic-coarse", false); test(CLOCK_MONOTONIC_RAW, "monotonic-raw", false); test(CLOCK_BOOTTIME, "boottime", false); nscheck(); if (unshare_timens()) return 1; nsfd = open("/proc/self/ns/time_for_children", O_RDONLY); if (nsfd < 0) return pr_perror("Can't open a time namespace"); if (_settime(CLOCK_MONOTONIC, offset)) return 1; if (_settime(CLOCK_BOOTTIME, offset)) return 1; if (setns(nsfd, CLONE_NEWTIME)) return pr_perror("setns"); test(CLOCK_MONOTONIC, "monotonic", true); test(CLOCK_MONOTONIC_COARSE, "monotonic-coarse", true); test(CLOCK_MONOTONIC_RAW, "monotonic-raw", true); test(CLOCK_BOOTTIME, "boottime", true); ksft_exit_pass(); return 0; }
linux-master
tools/testing/selftests/timens/gettime_perf.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <sched.h> #include <sys/timerfd.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include "log.h" #include "timens.h" static int tclock_gettime(clock_t clockid, struct timespec *now) { if (clockid == CLOCK_BOOTTIME_ALARM) clockid = CLOCK_BOOTTIME; return clock_gettime(clockid, now); } int run_test(int clockid, struct timespec now) { struct itimerspec new_value; long long elapsed; int fd, i; if (check_skip(clockid)) return 0; if (tclock_gettime(clockid, &now)) return pr_perror("clock_gettime(%d)", clockid); for (i = 0; i < 2; i++) { int flags = 0; new_value.it_value.tv_sec = 3600; new_value.it_value.tv_nsec = 0; new_value.it_interval.tv_sec = 1; new_value.it_interval.tv_nsec = 0; if (i == 1) { new_value.it_value.tv_sec += now.tv_sec; new_value.it_value.tv_nsec += now.tv_nsec; } fd = timerfd_create(clockid, 0); if (fd == -1) return pr_perror("timerfd_create(%d)", clockid); if (i == 1) flags |= TFD_TIMER_ABSTIME; if (timerfd_settime(fd, flags, &new_value, NULL)) return pr_perror("timerfd_settime(%d)", clockid); if (timerfd_gettime(fd, &new_value)) return pr_perror("timerfd_gettime(%d)", clockid); elapsed = new_value.it_value.tv_sec; if (abs(elapsed - 3600) > 60) { ksft_test_result_fail("clockid: %d elapsed: %lld\n", clockid, elapsed); return 1; } close(fd); } ksft_test_result_pass("clockid=%d\n", clockid); return 0; } int main(int argc, char *argv[]) { int ret, status, len, fd; char buf[4096]; pid_t pid; struct timespec btime_now, mtime_now; nscheck(); check_supported_timers(); ksft_set_plan(3); clock_gettime(CLOCK_MONOTONIC, &mtime_now); clock_gettime(CLOCK_BOOTTIME, &btime_now); if (unshare_timens()) return 1; len = snprintf(buf, sizeof(buf), "%d %d 0\n%d %d 0", CLOCK_MONOTONIC, 70 * 24 * 3600, CLOCK_BOOTTIME, 9 * 24 * 3600); fd = open("/proc/self/timens_offsets", O_WRONLY); if (fd < 0) return pr_perror("/proc/self/timens_offsets"); if (write(fd, buf, len) != len) return pr_perror("/proc/self/timens_offsets"); close(fd); mtime_now.tv_sec += 70 * 24 * 3600; btime_now.tv_sec += 9 * 24 * 3600; pid = fork(); if (pid < 0) return pr_perror("Unable to fork"); if (pid == 0) { ret = 0; ret |= run_test(CLOCK_BOOTTIME, btime_now); ret |= run_test(CLOCK_MONOTONIC, mtime_now); ret |= run_test(CLOCK_BOOTTIME_ALARM, btime_now); if (ret) ksft_exit_fail(); ksft_exit_pass(); return ret; } if (waitpid(pid, &status, 0) != pid) return pr_perror("Unable to wait the child process"); if (WIFEXITED(status)) return WEXITSTATUS(status); return 1; }
linux-master
tools/testing/selftests/timens/timerfd.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <sched.h> #include <stdio.h> #include <stdbool.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <string.h> #include "log.h" #include "timens.h" /* * Test shouldn't be run for a day, so add 10 days to child * time and check parent's time to be in the same day. */ #define DAY_IN_SEC (60*60*24) #define TEN_DAYS_IN_SEC (10*DAY_IN_SEC) struct test_clock { clockid_t id; char *name; /* * off_id is -1 if a clock has own offset, or it contains an index * which contains a right offset of this clock. */ int off_id; time_t offset; }; #define ct(clock, off_id) { clock, #clock, off_id } static struct test_clock clocks[] = { ct(CLOCK_BOOTTIME, -1), ct(CLOCK_BOOTTIME_ALARM, 1), ct(CLOCK_MONOTONIC, -1), ct(CLOCK_MONOTONIC_COARSE, 1), ct(CLOCK_MONOTONIC_RAW, 1), }; #undef ct static int child_ns, parent_ns = -1; static int switch_ns(int fd) { if (setns(fd, CLONE_NEWTIME)) { pr_perror("setns()"); return -1; } return 0; } static int init_namespaces(void) { char path[] = "/proc/self/ns/time_for_children"; struct stat st1, st2; if (parent_ns == -1) { parent_ns = open(path, O_RDONLY); if (parent_ns <= 0) return pr_perror("Unable to open %s", path); } if (fstat(parent_ns, &st1)) return pr_perror("Unable to stat the parent timens"); if (unshare_timens()) return -1; child_ns = open(path, O_RDONLY); if (child_ns <= 0) return pr_perror("Unable to open %s", path); if (fstat(child_ns, &st2)) return pr_perror("Unable to stat the timens"); if (st1.st_ino == st2.st_ino) return pr_perror("The same child_ns after CLONE_NEWTIME"); return 0; } static int test_gettime(clockid_t clock_index, bool raw_syscall, time_t offset) { struct timespec child_ts_new, parent_ts_old, cur_ts; char *entry = raw_syscall ? "syscall" : "vdso"; double precision = 0.0; if (check_skip(clocks[clock_index].id)) return 0; switch (clocks[clock_index].id) { case CLOCK_MONOTONIC_COARSE: case CLOCK_MONOTONIC_RAW: precision = -2.0; break; } if (switch_ns(parent_ns)) return pr_err("switch_ns(%d)", child_ns); if (_gettime(clocks[clock_index].id, &parent_ts_old, raw_syscall)) return -1; child_ts_new.tv_nsec = parent_ts_old.tv_nsec; child_ts_new.tv_sec = parent_ts_old.tv_sec + offset; if (switch_ns(child_ns)) return pr_err("switch_ns(%d)", child_ns); if (_gettime(clocks[clock_index].id, &cur_ts, raw_syscall)) return -1; if (difftime(cur_ts.tv_sec, child_ts_new.tv_sec) < precision) { ksft_test_result_fail( "Child's %s (%s) time has not changed: %lu -> %lu [%lu]\n", clocks[clock_index].name, entry, parent_ts_old.tv_sec, child_ts_new.tv_sec, cur_ts.tv_sec); return -1; } if (switch_ns(parent_ns)) return pr_err("switch_ns(%d)", parent_ns); if (_gettime(clocks[clock_index].id, &cur_ts, raw_syscall)) return -1; if (difftime(cur_ts.tv_sec, parent_ts_old.tv_sec) > DAY_IN_SEC) { ksft_test_result_fail( "Parent's %s (%s) time has changed: %lu -> %lu [%lu]\n", clocks[clock_index].name, entry, parent_ts_old.tv_sec, child_ts_new.tv_sec, cur_ts.tv_sec); /* Let's play nice and put it closer to original */ clock_settime(clocks[clock_index].id, &cur_ts); return -1; } ksft_test_result_pass("Passed for %s (%s)\n", clocks[clock_index].name, entry); return 0; } int main(int argc, char *argv[]) { unsigned int i; time_t offset; int ret = 0; nscheck(); check_supported_timers(); ksft_set_plan(ARRAY_SIZE(clocks) * 2); if (init_namespaces()) return 1; /* Offsets have to be set before tasks enter the namespace. */ for (i = 0; i < ARRAY_SIZE(clocks); i++) { if (clocks[i].off_id != -1) continue; offset = TEN_DAYS_IN_SEC + i * 1000; clocks[i].offset = offset; if (_settime(clocks[i].id, offset)) return 1; } for (i = 0; i < ARRAY_SIZE(clocks); i++) { if (clocks[i].off_id != -1) offset = clocks[clocks[i].off_id].offset; else offset = clocks[i].offset; ret |= test_gettime(i, true, offset); ret |= test_gettime(i, false, offset); } if (ret) ksft_exit_fail(); ksft_exit_pass(); return !!ret; }
linux-master
tools/testing/selftests/timens/timens.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <math.h> #include <sched.h> #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include "log.h" #include "timens.h" /* * Test shouldn't be run for a day, so add 10 days to child * time and check parent's time to be in the same day. */ #define MAX_TEST_TIME_SEC (60*5) #define DAY_IN_SEC (60*60*24) #define TEN_DAYS_IN_SEC (10*DAY_IN_SEC) static int child_ns, parent_ns; static int switch_ns(int fd) { if (setns(fd, CLONE_NEWTIME)) return pr_perror("setns()"); return 0; } static int init_namespaces(void) { char path[] = "/proc/self/ns/time_for_children"; struct stat st1, st2; parent_ns = open(path, O_RDONLY); if (parent_ns <= 0) return pr_perror("Unable to open %s", path); if (fstat(parent_ns, &st1)) return pr_perror("Unable to stat the parent timens"); if (unshare_timens()) return -1; child_ns = open(path, O_RDONLY); if (child_ns <= 0) return pr_perror("Unable to open %s", path); if (fstat(child_ns, &st2)) return pr_perror("Unable to stat the timens"); if (st1.st_ino == st2.st_ino) return pr_err("The same child_ns after CLONE_NEWTIME"); if (_settime(CLOCK_BOOTTIME, TEN_DAYS_IN_SEC)) return -1; return 0; } static int read_proc_uptime(struct timespec *uptime) { unsigned long up_sec, up_nsec; FILE *proc; proc = fopen("/proc/uptime", "r"); if (proc == NULL) { pr_perror("Unable to open /proc/uptime"); return -1; } if (fscanf(proc, "%lu.%02lu", &up_sec, &up_nsec) != 2) { if (errno) { pr_perror("fscanf"); return -errno; } pr_err("failed to parse /proc/uptime"); return -1; } fclose(proc); uptime->tv_sec = up_sec; uptime->tv_nsec = up_nsec; return 0; } static int read_proc_stat_btime(unsigned long long *boottime_sec) { FILE *proc; char line_buf[2048]; proc = fopen("/proc/stat", "r"); if (proc == NULL) { pr_perror("Unable to open /proc/stat"); return -1; } while (fgets(line_buf, 2048, proc)) { if (sscanf(line_buf, "btime %llu", boottime_sec) != 1) continue; fclose(proc); return 0; } if (errno) { pr_perror("fscanf"); fclose(proc); return -errno; } pr_err("failed to parse /proc/stat"); fclose(proc); return -1; } static int check_uptime(void) { struct timespec uptime_new, uptime_old; time_t uptime_expected; double prec = MAX_TEST_TIME_SEC; if (switch_ns(parent_ns)) return pr_err("switch_ns(%d)", parent_ns); if (read_proc_uptime(&uptime_old)) return 1; if (switch_ns(child_ns)) return pr_err("switch_ns(%d)", child_ns); if (read_proc_uptime(&uptime_new)) return 1; uptime_expected = uptime_old.tv_sec + TEN_DAYS_IN_SEC; if (fabs(difftime(uptime_new.tv_sec, uptime_expected)) > prec) { pr_fail("uptime in /proc/uptime: old %ld, new %ld [%ld]", uptime_old.tv_sec, uptime_new.tv_sec, uptime_old.tv_sec + TEN_DAYS_IN_SEC); return 1; } ksft_test_result_pass("Passed for /proc/uptime\n"); return 0; } static int check_stat_btime(void) { unsigned long long btime_new, btime_old; unsigned long long btime_expected; if (switch_ns(parent_ns)) return pr_err("switch_ns(%d)", parent_ns); if (read_proc_stat_btime(&btime_old)) return 1; if (switch_ns(child_ns)) return pr_err("switch_ns(%d)", child_ns); if (read_proc_stat_btime(&btime_new)) return 1; btime_expected = btime_old - TEN_DAYS_IN_SEC; if (btime_new != btime_expected) { pr_fail("btime in /proc/stat: old %llu, new %llu [%llu]", btime_old, btime_new, btime_expected); return 1; } ksft_test_result_pass("Passed for /proc/stat btime\n"); return 0; } int main(int argc, char *argv[]) { int ret = 0; nscheck(); ksft_set_plan(2); if (init_namespaces()) return 1; ret |= check_uptime(); ret |= check_stat_btime(); if (ret) ksft_exit_fail(); ksft_exit_pass(); return ret; }
linux-master
tools/testing/selftests/timens/procfs.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <sched.h> #include <linux/unistd.h> #include <linux/futex.h> #include <stdio.h> #include <string.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "log.h" #include "timens.h" #define NSEC_PER_SEC 1000000000ULL static int run_test(int clockid) { int futex_op = FUTEX_WAIT_BITSET; struct timespec timeout, end; int val = 0; if (clockid == CLOCK_REALTIME) futex_op |= FUTEX_CLOCK_REALTIME; clock_gettime(clockid, &timeout); timeout.tv_nsec += NSEC_PER_SEC / 10; // 100ms if (timeout.tv_nsec > NSEC_PER_SEC) { timeout.tv_sec++; timeout.tv_nsec -= NSEC_PER_SEC; } if (syscall(__NR_futex, &val, futex_op, 0, &timeout, 0, FUTEX_BITSET_MATCH_ANY) >= 0) { ksft_test_result_fail("futex didn't return ETIMEDOUT\n"); return 1; } if (errno != ETIMEDOUT) { ksft_test_result_fail("futex didn't return ETIMEDOUT: %s\n", strerror(errno)); return 1; } clock_gettime(clockid, &end); if (end.tv_sec < timeout.tv_sec || (end.tv_sec == timeout.tv_sec && end.tv_nsec < timeout.tv_nsec)) { ksft_test_result_fail("futex slept less than 100ms\n"); return 1; } ksft_test_result_pass("futex with the %d clockid\n", clockid); return 0; } int main(int argc, char *argv[]) { int status, len, fd; char buf[4096]; pid_t pid; struct timespec mtime_now; nscheck(); ksft_set_plan(2); clock_gettime(CLOCK_MONOTONIC, &mtime_now); if (unshare_timens()) return 1; len = snprintf(buf, sizeof(buf), "%d %d 0", CLOCK_MONOTONIC, 70 * 24 * 3600); fd = open("/proc/self/timens_offsets", O_WRONLY); if (fd < 0) return pr_perror("/proc/self/timens_offsets"); if (write(fd, buf, len) != len) return pr_perror("/proc/self/timens_offsets"); close(fd); pid = fork(); if (pid < 0) return pr_perror("Unable to fork"); if (pid == 0) { int ret = 0; ret |= run_test(CLOCK_REALTIME); ret |= run_test(CLOCK_MONOTONIC); if (ret) ksft_exit_fail(); ksft_exit_pass(); return 0; } if (waitpid(pid, &status, 0) != pid) return pr_perror("Unable to wait the child process"); if (WIFEXITED(status)) return WEXITSTATUS(status); return 1; }
linux-master
tools/testing/selftests/timens/futex.c
// SPDX-License-Identifier: GPL-2.0-or-later /****************************************************************************** * * Copyright © International Business Machines Corp., 2009 * * DESCRIPTION * Block on a futex and wait for timeout. * * AUTHOR * Darren Hart <[email protected]> * * HISTORY * 2009-Nov-6: Initial version by Darren Hart <[email protected]> * 2021-Apr-26: More test cases by André Almeida <[email protected]> * *****************************************************************************/ #include <pthread.h> #include "futextest.h" #include "futex2test.h" #include "logging.h" #define TEST_NAME "futex-wait-timeout" static long timeout_ns = 100000; /* 100us default timeout */ static futex_t futex_pi; static pthread_barrier_t barrier; void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -t N Timeout in nanoseconds (default: 100,000)\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } /* * Get a PI lock and hold it forever, so the main thread lock_pi will block * and we can test the timeout */ void *get_pi_lock(void *arg) { int ret; volatile futex_t lock = 0; ret = futex_lock_pi(&futex_pi, NULL, 0, 0); if (ret != 0) error("futex_lock_pi failed\n", ret); pthread_barrier_wait(&barrier); /* Blocks forever */ ret = futex_wait(&lock, 0, NULL, 0); error("futex_wait failed\n", ret); return NULL; } /* * Check if the function returned the expected error */ static void test_timeout(int res, int *ret, char *test_name, int err) { if (!res || errno != err) { ksft_test_result_fail("%s returned %d\n", test_name, res < 0 ? errno : res); *ret = RET_FAIL; } else { ksft_test_result_pass("%s succeeds\n", test_name); } } /* * Calculate absolute timeout and correct overflow */ static int futex_get_abs_timeout(clockid_t clockid, struct timespec *to, long timeout_ns) { if (clock_gettime(clockid, to)) { error("clock_gettime failed\n", errno); return errno; } to->tv_nsec += timeout_ns; if (to->tv_nsec >= 1000000000) { to->tv_sec++; to->tv_nsec -= 1000000000; } return 0; } int main(int argc, char *argv[]) { futex_t f1 = FUTEX_INITIALIZER; int res, ret = RET_PASS; struct timespec to; pthread_t thread; int c; struct futex_waitv waitv = { .uaddr = (uintptr_t)&f1, .val = f1, .flags = FUTEX_32, .__reserved = 0 }; while ((c = getopt(argc, argv, "cht:v:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 't': timeout_ns = atoi(optarg); break; case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(9); ksft_print_msg("%s: Block on a futex and wait for timeout\n", basename(argv[0])); ksft_print_msg("\tArguments: timeout=%ldns\n", timeout_ns); pthread_barrier_init(&barrier, NULL, 2); pthread_create(&thread, NULL, get_pi_lock, NULL); /* initialize relative timeout */ to.tv_sec = 0; to.tv_nsec = timeout_ns; res = futex_wait(&f1, f1, &to, 0); test_timeout(res, &ret, "futex_wait relative", ETIMEDOUT); /* FUTEX_WAIT_BITSET with CLOCK_REALTIME */ if (futex_get_abs_timeout(CLOCK_REALTIME, &to, timeout_ns)) return RET_FAIL; res = futex_wait_bitset(&f1, f1, &to, 1, FUTEX_CLOCK_REALTIME); test_timeout(res, &ret, "futex_wait_bitset realtime", ETIMEDOUT); /* FUTEX_WAIT_BITSET with CLOCK_MONOTONIC */ if (futex_get_abs_timeout(CLOCK_MONOTONIC, &to, timeout_ns)) return RET_FAIL; res = futex_wait_bitset(&f1, f1, &to, 1, 0); test_timeout(res, &ret, "futex_wait_bitset monotonic", ETIMEDOUT); /* FUTEX_WAIT_REQUEUE_PI with CLOCK_REALTIME */ if (futex_get_abs_timeout(CLOCK_REALTIME, &to, timeout_ns)) return RET_FAIL; res = futex_wait_requeue_pi(&f1, f1, &futex_pi, &to, FUTEX_CLOCK_REALTIME); test_timeout(res, &ret, "futex_wait_requeue_pi realtime", ETIMEDOUT); /* FUTEX_WAIT_REQUEUE_PI with CLOCK_MONOTONIC */ if (futex_get_abs_timeout(CLOCK_MONOTONIC, &to, timeout_ns)) return RET_FAIL; res = futex_wait_requeue_pi(&f1, f1, &futex_pi, &to, 0); test_timeout(res, &ret, "futex_wait_requeue_pi monotonic", ETIMEDOUT); /* Wait until the other thread calls futex_lock_pi() */ pthread_barrier_wait(&barrier); pthread_barrier_destroy(&barrier); /* * FUTEX_LOCK_PI with CLOCK_REALTIME * Due to historical reasons, FUTEX_LOCK_PI supports only realtime * clock, but requires the caller to not set CLOCK_REALTIME flag. * * If you call FUTEX_LOCK_PI with a monotonic clock, it'll be * interpreted as a realtime clock, and (unless you mess your machine's * time or your time machine) the monotonic clock value is always * smaller than realtime and the syscall will timeout immediately. */ if (futex_get_abs_timeout(CLOCK_REALTIME, &to, timeout_ns)) return RET_FAIL; res = futex_lock_pi(&futex_pi, &to, 0, 0); test_timeout(res, &ret, "futex_lock_pi realtime", ETIMEDOUT); /* Test operations that don't support FUTEX_CLOCK_REALTIME */ res = futex_lock_pi(&futex_pi, NULL, 0, FUTEX_CLOCK_REALTIME); test_timeout(res, &ret, "futex_lock_pi invalid timeout flag", ENOSYS); /* futex_waitv with CLOCK_MONOTONIC */ if (futex_get_abs_timeout(CLOCK_MONOTONIC, &to, timeout_ns)) return RET_FAIL; res = futex_waitv(&waitv, 1, 0, &to, CLOCK_MONOTONIC); test_timeout(res, &ret, "futex_waitv monotonic", ETIMEDOUT); /* futex_waitv with CLOCK_REALTIME */ if (futex_get_abs_timeout(CLOCK_REALTIME, &to, timeout_ns)) return RET_FAIL; res = futex_waitv(&waitv, 1, 0, &to, CLOCK_REALTIME); test_timeout(res, &ret, "futex_waitv realtime", ETIMEDOUT); ksft_print_cnts(); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_wait_timeout.c
// SPDX-License-Identifier: GPL-2.0-or-later /****************************************************************************** * * Copyright © International Business Machines Corp., 2006-2008 * * DESCRIPTION * This test exercises the futex_wait_requeue_pi() signal handling both * before and after the requeue. The first should be restarted by the * kernel. The latter should return EWOULDBLOCK to the waiter. * * AUTHORS * Darren Hart <[email protected]> * * HISTORY * 2008-May-5: Initial version by Darren Hart <[email protected]> * *****************************************************************************/ #include <errno.h> #include <getopt.h> #include <limits.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "atomic.h" #include "futextest.h" #include "logging.h" #define TEST_NAME "futex-requeue-pi-signal-restart" #define DELAY_US 100 futex_t f1 = FUTEX_INITIALIZER; futex_t f2 = FUTEX_INITIALIZER; atomic_t requeued = ATOMIC_INITIALIZER; int waiter_ret = 0; void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } int create_rt_thread(pthread_t *pth, void*(*func)(void *), void *arg, int policy, int prio) { struct sched_param schedp; pthread_attr_t attr; int ret; pthread_attr_init(&attr); memset(&schedp, 0, sizeof(schedp)); ret = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); if (ret) { error("pthread_attr_setinheritsched\n", ret); return -1; } ret = pthread_attr_setschedpolicy(&attr, policy); if (ret) { error("pthread_attr_setschedpolicy\n", ret); return -1; } schedp.sched_priority = prio; ret = pthread_attr_setschedparam(&attr, &schedp); if (ret) { error("pthread_attr_setschedparam\n", ret); return -1; } ret = pthread_create(pth, &attr, func, arg); if (ret) { error("pthread_create\n", ret); return -1; } return 0; } void handle_signal(int signo) { info("signal received %s requeue\n", requeued.val ? "after" : "prior to"); } void *waiterfn(void *arg) { unsigned int old_val; int res; waiter_ret = RET_PASS; info("Waiter running\n"); info("Calling FUTEX_LOCK_PI on f2=%x @ %p\n", f2, &f2); old_val = f1; res = futex_wait_requeue_pi(&f1, old_val, &(f2), NULL, FUTEX_PRIVATE_FLAG); if (!requeued.val || errno != EWOULDBLOCK) { fail("unexpected return from futex_wait_requeue_pi: %d (%s)\n", res, strerror(errno)); info("w2:futex: %x\n", f2); if (!res) futex_unlock_pi(&f2, FUTEX_PRIVATE_FLAG); waiter_ret = RET_FAIL; } info("Waiter exiting with %d\n", waiter_ret); pthread_exit(NULL); } int main(int argc, char *argv[]) { unsigned int old_val; struct sigaction sa; pthread_t waiter; int c, res, ret = RET_PASS; while ((c = getopt(argc, argv, "chv:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(1); ksft_print_msg("%s: Test signal handling during requeue_pi\n", basename(argv[0])); ksft_print_msg("\tArguments: <none>\n"); sa.sa_handler = handle_signal; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if (sigaction(SIGUSR1, &sa, NULL)) { error("sigaction\n", errno); exit(1); } info("m1:f2: %x\n", f2); info("Creating waiter\n"); res = create_rt_thread(&waiter, waiterfn, NULL, SCHED_FIFO, 1); if (res) { error("Creating waiting thread failed", res); ret = RET_ERROR; goto out; } info("Calling FUTEX_LOCK_PI on f2=%x @ %p\n", f2, &f2); info("m2:f2: %x\n", f2); futex_lock_pi(&f2, 0, 0, FUTEX_PRIVATE_FLAG); info("m3:f2: %x\n", f2); while (1) { /* * signal the waiter before requeue, waiter should automatically * restart futex_wait_requeue_pi() in the kernel. Wait for the * waiter to block on f1 again. */ info("Issuing SIGUSR1 to waiter\n"); pthread_kill(waiter, SIGUSR1); usleep(DELAY_US); info("Requeueing waiter via FUTEX_CMP_REQUEUE_PI\n"); old_val = f1; res = futex_cmp_requeue_pi(&f1, old_val, &(f2), 1, 0, FUTEX_PRIVATE_FLAG); /* * If res is non-zero, we either requeued the waiter or hit an * error, break out and handle it. If it is zero, then the * signal may have hit before the waiter was blocked on f1. * Try again. */ if (res > 0) { atomic_set(&requeued, 1); break; } else if (res < 0) { error("FUTEX_CMP_REQUEUE_PI failed\n", errno); ret = RET_ERROR; break; } } info("m4:f2: %x\n", f2); /* * Signal the waiter after requeue, waiter should return from * futex_wait_requeue_pi() with EWOULDBLOCK. Join the thread here so the * futex_unlock_pi() can't happen before the signal wakeup is detected * in the kernel. */ info("Issuing SIGUSR1 to waiter\n"); pthread_kill(waiter, SIGUSR1); info("Waiting for waiter to return\n"); pthread_join(waiter, NULL); info("Calling FUTEX_UNLOCK_PI on mutex=%x @ %p\n", f2, &f2); futex_unlock_pi(&f2, FUTEX_PRIVATE_FLAG); info("m5:f2: %x\n", f2); out: if (ret == RET_PASS && waiter_ret) ret = waiter_ret; print_result(TEST_NAME, ret); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_requeue_pi_signal_restart.c
// SPDX-License-Identifier: GPL-2.0-or-later /****************************************************************************** * * Copyright FUJITSU LIMITED 2010 * Copyright KOSAKI Motohiro <[email protected]> * * DESCRIPTION * Internally, Futex has two handling mode, anon and file. The private file * mapping is special. At first it behave as file, but after write anything * it behave as anon. This test is intent to test such case. * * AUTHOR * KOSAKI Motohiro <[email protected]> * * HISTORY * 2010-Jan-6: Initial version by KOSAKI Motohiro <[email protected]> * *****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <syscall.h> #include <unistd.h> #include <errno.h> #include <linux/futex.h> #include <pthread.h> #include <libgen.h> #include <signal.h> #include "logging.h" #include "futextest.h" #define TEST_NAME "futex-wait-private-mapped-file" #define PAGE_SZ 4096 char pad[PAGE_SZ] = {1}; futex_t val = 1; char pad2[PAGE_SZ] = {1}; #define WAKE_WAIT_US 3000000 struct timespec wait_timeout = { .tv_sec = 5, .tv_nsec = 0}; void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } void *thr_futex_wait(void *arg) { int ret; info("futex wait\n"); ret = futex_wait(&val, 1, &wait_timeout, 0); if (ret && errno != EWOULDBLOCK && errno != ETIMEDOUT) { error("futex error.\n", errno); print_result(TEST_NAME, RET_ERROR); exit(RET_ERROR); } if (ret && errno == ETIMEDOUT) fail("waiter timedout\n"); info("futex_wait: ret = %d, errno = %d\n", ret, errno); return NULL; } int main(int argc, char **argv) { pthread_t thr; int ret = RET_PASS; int res; int c; while ((c = getopt(argc, argv, "chv:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(1); ksft_print_msg( "%s: Test the futex value of private file mappings in FUTEX_WAIT\n", basename(argv[0])); ret = pthread_create(&thr, NULL, thr_futex_wait, NULL); if (ret < 0) { fprintf(stderr, "pthread_create error\n"); ret = RET_ERROR; goto out; } info("wait a while\n"); usleep(WAKE_WAIT_US); val = 2; res = futex_wake(&val, 1, 0); info("futex_wake %d\n", res); if (res != 1) { fail("FUTEX_WAKE didn't find the waiting thread.\n"); ret = RET_FAIL; } info("join\n"); pthread_join(thr, NULL); out: print_result(TEST_NAME, ret); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_wait_private_mapped_file.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright Collabora Ltd., 2021 * * futex cmp requeue test by André Almeida <[email protected]> */ #include <pthread.h> #include <sys/shm.h> #include <sys/mman.h> #include <fcntl.h> #include "logging.h" #include "futextest.h" #define TEST_NAME "futex-wait" #define timeout_ns 30000000 #define WAKE_WAIT_US 10000 #define SHM_PATH "futex_shm_file" void *futex; void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } static void *waiterfn(void *arg) { struct timespec to; unsigned int flags = 0; if (arg) flags = *((unsigned int *) arg); to.tv_sec = 0; to.tv_nsec = timeout_ns; if (futex_wait(futex, 0, &to, flags)) printf("waiter failed errno %d\n", errno); return NULL; } int main(int argc, char *argv[]) { int res, ret = RET_PASS, fd, c, shm_id; u_int32_t f_private = 0, *shared_data; unsigned int flags = FUTEX_PRIVATE_FLAG; pthread_t waiter; void *shm; futex = &f_private; while ((c = getopt(argc, argv, "cht:v:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(3); ksft_print_msg("%s: Test futex_wait\n", basename(argv[0])); /* Testing a private futex */ info("Calling private futex_wait on futex: %p\n", futex); if (pthread_create(&waiter, NULL, waiterfn, (void *) &flags)) error("pthread_create failed\n", errno); usleep(WAKE_WAIT_US); info("Calling private futex_wake on futex: %p\n", futex); res = futex_wake(futex, 1, FUTEX_PRIVATE_FLAG); if (res != 1) { ksft_test_result_fail("futex_wake private returned: %d %s\n", errno, strerror(errno)); ret = RET_FAIL; } else { ksft_test_result_pass("futex_wake private succeeds\n"); } /* Testing an anon page shared memory */ shm_id = shmget(IPC_PRIVATE, 4096, IPC_CREAT | 0666); if (shm_id < 0) { perror("shmget"); exit(1); } shared_data = shmat(shm_id, NULL, 0); *shared_data = 0; futex = shared_data; info("Calling shared (page anon) futex_wait on futex: %p\n", futex); if (pthread_create(&waiter, NULL, waiterfn, NULL)) error("pthread_create failed\n", errno); usleep(WAKE_WAIT_US); info("Calling shared (page anon) futex_wake on futex: %p\n", futex); res = futex_wake(futex, 1, 0); if (res != 1) { ksft_test_result_fail("futex_wake shared (page anon) returned: %d %s\n", errno, strerror(errno)); ret = RET_FAIL; } else { ksft_test_result_pass("futex_wake shared (page anon) succeeds\n"); } /* Testing a file backed shared memory */ fd = open(SHM_PATH, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd < 0) { perror("open"); exit(1); } if (ftruncate(fd, sizeof(f_private))) { perror("ftruncate"); exit(1); } shm = mmap(NULL, sizeof(f_private), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (shm == MAP_FAILED) { perror("mmap"); exit(1); } memcpy(shm, &f_private, sizeof(f_private)); futex = shm; info("Calling shared (file backed) futex_wait on futex: %p\n", futex); if (pthread_create(&waiter, NULL, waiterfn, NULL)) error("pthread_create failed\n", errno); usleep(WAKE_WAIT_US); info("Calling shared (file backed) futex_wake on futex: %p\n", futex); res = futex_wake(shm, 1, 0); if (res != 1) { ksft_test_result_fail("futex_wake shared (file backed) returned: %d %s\n", errno, strerror(errno)); ret = RET_FAIL; } else { ksft_test_result_pass("futex_wake shared (file backed) succeeds\n"); } /* Freeing resources */ shmdt(shared_data); munmap(shm, sizeof(f_private)); remove(SHM_PATH); close(fd); ksft_print_cnts(); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_wait.c
// SPDX-License-Identifier: GPL-2.0-or-later /****************************************************************************** * * Copyright © International Business Machines Corp., 2009 * * DESCRIPTION * Test if FUTEX_WAIT op returns -EWOULDBLOCK if the futex value differs * from the expected one. * * AUTHOR * Gowrishankar <[email protected]> * * HISTORY * 2009-Nov-14: Initial version by Gowrishankar <[email protected]> * *****************************************************************************/ #include <errno.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "futextest.h" #include "futex2test.h" #include "logging.h" #define TEST_NAME "futex-wait-wouldblock" #define timeout_ns 100000 void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } int main(int argc, char *argv[]) { struct timespec to = {.tv_sec = 0, .tv_nsec = timeout_ns}; futex_t f1 = FUTEX_INITIALIZER; int res, ret = RET_PASS; int c; struct futex_waitv waitv = { .uaddr = (uintptr_t)&f1, .val = f1+1, .flags = FUTEX_32, .__reserved = 0 }; while ((c = getopt(argc, argv, "cht:v:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(2); ksft_print_msg("%s: Test the unexpected futex value in FUTEX_WAIT\n", basename(argv[0])); info("Calling futex_wait on f1: %u @ %p with val=%u\n", f1, &f1, f1+1); res = futex_wait(&f1, f1+1, &to, FUTEX_PRIVATE_FLAG); if (!res || errno != EWOULDBLOCK) { ksft_test_result_fail("futex_wait returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_wait\n"); } if (clock_gettime(CLOCK_MONOTONIC, &to)) { error("clock_gettime failed\n", errno); return errno; } to.tv_nsec += timeout_ns; if (to.tv_nsec >= 1000000000) { to.tv_sec++; to.tv_nsec -= 1000000000; } info("Calling futex_waitv on f1: %u @ %p with val=%u\n", f1, &f1, f1+1); res = futex_waitv(&waitv, 1, 0, &to, CLOCK_MONOTONIC); if (!res || errno != EWOULDBLOCK) { ksft_test_result_pass("futex_waitv returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_waitv\n"); } ksft_print_cnts(); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_wait_wouldblock.c
// SPDX-License-Identifier: GPL-2.0-or-later /****************************************************************************** * * Copyright FUJITSU LIMITED 2010 * Copyright KOSAKI Motohiro <[email protected]> * * DESCRIPTION * Wait on uninitialized heap. It shold be zero and FUTEX_WAIT should * return immediately. This test is intent to test zero page handling in * futex. * * AUTHOR * KOSAKI Motohiro <[email protected]> * * HISTORY * 2010-Jan-6: Initial version by KOSAKI Motohiro <[email protected]> * *****************************************************************************/ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <syscall.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <linux/futex.h> #include <libgen.h> #include "logging.h" #include "futextest.h" #define TEST_NAME "futex-wait-uninitialized-heap" #define WAIT_US 5000000 static int child_blocked = 1; static int child_ret; void *buf; void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } void *wait_thread(void *arg) { int res; child_ret = RET_PASS; res = futex_wait(buf, 1, NULL, 0); child_blocked = 0; if (res != 0 && errno != EWOULDBLOCK) { error("futex failure\n", errno); child_ret = RET_ERROR; } pthread_exit(NULL); } int main(int argc, char **argv) { int c, ret = RET_PASS; long page_size; pthread_t thr; while ((c = getopt(argc, argv, "chv:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } page_size = sysconf(_SC_PAGESIZE); buf = mmap(NULL, page_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); if (buf == (void *)-1) { error("mmap\n", errno); exit(1); } ksft_print_header(); ksft_set_plan(1); ksft_print_msg("%s: Test the uninitialized futex value in FUTEX_WAIT\n", basename(argv[0])); ret = pthread_create(&thr, NULL, wait_thread, NULL); if (ret) { error("pthread_create\n", errno); ret = RET_ERROR; goto out; } info("waiting %dus for child to return\n", WAIT_US); usleep(WAIT_US); ret = child_ret; if (child_blocked) { fail("child blocked in kernel\n"); ret = RET_FAIL; } out: print_result(TEST_NAME, ret); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_wait_uninitialized_heap.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * futex_waitv() test by André Almeida <[email protected]> * * Copyright 2021 Collabora Ltd. */ #include <errno.h> #include <error.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <pthread.h> #include <stdint.h> #include <sys/shm.h> #include "futextest.h" #include "futex2test.h" #include "logging.h" #define TEST_NAME "futex-wait" #define WAKE_WAIT_US 10000 #define NR_FUTEXES 30 static struct futex_waitv waitv[NR_FUTEXES]; u_int32_t futexes[NR_FUTEXES] = {0}; void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } void *waiterfn(void *arg) { struct timespec to; int res; /* setting absolute timeout for futex2 */ if (clock_gettime(CLOCK_MONOTONIC, &to)) error("gettime64 failed\n", errno); to.tv_sec++; res = futex_waitv(waitv, NR_FUTEXES, 0, &to, CLOCK_MONOTONIC); if (res < 0) { ksft_test_result_fail("futex_waitv returned: %d %s\n", errno, strerror(errno)); } else if (res != NR_FUTEXES - 1) { ksft_test_result_fail("futex_waitv returned: %d, expecting %d\n", res, NR_FUTEXES - 1); } return NULL; } int main(int argc, char *argv[]) { pthread_t waiter; int res, ret = RET_PASS; struct timespec to; int c, i; while ((c = getopt(argc, argv, "cht:v:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(7); ksft_print_msg("%s: Test FUTEX_WAITV\n", basename(argv[0])); for (i = 0; i < NR_FUTEXES; i++) { waitv[i].uaddr = (uintptr_t)&futexes[i]; waitv[i].flags = FUTEX_32 | FUTEX_PRIVATE_FLAG; waitv[i].val = 0; waitv[i].__reserved = 0; } /* Private waitv */ if (pthread_create(&waiter, NULL, waiterfn, NULL)) error("pthread_create failed\n", errno); usleep(WAKE_WAIT_US); res = futex_wake(u64_to_ptr(waitv[NR_FUTEXES - 1].uaddr), 1, FUTEX_PRIVATE_FLAG); if (res != 1) { ksft_test_result_fail("futex_wake private returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_waitv private\n"); } /* Shared waitv */ for (i = 0; i < NR_FUTEXES; i++) { int shm_id = shmget(IPC_PRIVATE, 4096, IPC_CREAT | 0666); if (shm_id < 0) { perror("shmget"); exit(1); } unsigned int *shared_data = shmat(shm_id, NULL, 0); *shared_data = 0; waitv[i].uaddr = (uintptr_t)shared_data; waitv[i].flags = FUTEX_32; waitv[i].val = 0; waitv[i].__reserved = 0; } if (pthread_create(&waiter, NULL, waiterfn, NULL)) error("pthread_create failed\n", errno); usleep(WAKE_WAIT_US); res = futex_wake(u64_to_ptr(waitv[NR_FUTEXES - 1].uaddr), 1, 0); if (res != 1) { ksft_test_result_fail("futex_wake shared returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_waitv shared\n"); } for (i = 0; i < NR_FUTEXES; i++) shmdt(u64_to_ptr(waitv[i].uaddr)); /* Testing a waiter without FUTEX_32 flag */ waitv[0].flags = FUTEX_PRIVATE_FLAG; if (clock_gettime(CLOCK_MONOTONIC, &to)) error("gettime64 failed\n", errno); to.tv_sec++; res = futex_waitv(waitv, NR_FUTEXES, 0, &to, CLOCK_MONOTONIC); if (res == EINVAL) { ksft_test_result_fail("futex_waitv private returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_waitv without FUTEX_32\n"); } /* Testing a waiter with an unaligned address */ waitv[0].flags = FUTEX_PRIVATE_FLAG | FUTEX_32; waitv[0].uaddr = 1; if (clock_gettime(CLOCK_MONOTONIC, &to)) error("gettime64 failed\n", errno); to.tv_sec++; res = futex_waitv(waitv, NR_FUTEXES, 0, &to, CLOCK_MONOTONIC); if (res == EINVAL) { ksft_test_result_fail("futex_wake private returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_waitv with an unaligned address\n"); } /* Testing a NULL address for waiters.uaddr */ waitv[0].uaddr = 0x00000000; if (clock_gettime(CLOCK_MONOTONIC, &to)) error("gettime64 failed\n", errno); to.tv_sec++; res = futex_waitv(waitv, NR_FUTEXES, 0, &to, CLOCK_MONOTONIC); if (res == EINVAL) { ksft_test_result_fail("futex_waitv private returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_waitv NULL address in waitv.uaddr\n"); } /* Testing a NULL address for *waiters */ if (clock_gettime(CLOCK_MONOTONIC, &to)) error("gettime64 failed\n", errno); to.tv_sec++; res = futex_waitv(NULL, NR_FUTEXES, 0, &to, CLOCK_MONOTONIC); if (res == EINVAL) { ksft_test_result_fail("futex_waitv private returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_waitv NULL address in *waiters\n"); } /* Testing an invalid clockid */ if (clock_gettime(CLOCK_MONOTONIC, &to)) error("gettime64 failed\n", errno); to.tv_sec++; res = futex_waitv(NULL, NR_FUTEXES, 0, &to, CLOCK_TAI); if (res == EINVAL) { ksft_test_result_fail("futex_waitv private returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_waitv invalid clockid\n"); } ksft_print_cnts(); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_waitv.c
// SPDX-License-Identifier: GPL-2.0-or-later /****************************************************************************** * * Copyright © International Business Machines Corp., 2006-2008 * * DESCRIPTION * This test excercises the futex syscall op codes needed for requeuing * priority inheritance aware POSIX condition variables and mutexes. * * AUTHORS * Sripathi Kodi <[email protected]> * Darren Hart <[email protected]> * * HISTORY * 2008-Jan-13: Initial version by Sripathi Kodi <[email protected]> * 2009-Nov-6: futex test adaptation by Darren Hart <[email protected]> * *****************************************************************************/ #include <errno.h> #include <limits.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include "atomic.h" #include "futextest.h" #include "logging.h" #define TEST_NAME "futex-requeue-pi" #define MAX_WAKE_ITERS 1000 #define THREAD_MAX 10 #define SIGNAL_PERIOD_US 100 atomic_t waiters_blocked = ATOMIC_INITIALIZER; atomic_t waiters_woken = ATOMIC_INITIALIZER; futex_t f1 = FUTEX_INITIALIZER; futex_t f2 = FUTEX_INITIALIZER; futex_t wake_complete = FUTEX_INITIALIZER; /* Test option defaults */ static long timeout_ns; static int broadcast; static int owner; static int locked; struct thread_arg { long id; struct timespec *timeout; int lock; int ret; }; #define THREAD_ARG_INITIALIZER { 0, NULL, 0, 0 } void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -b Broadcast wakeup (all waiters)\n"); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -l Lock the pi futex across requeue\n"); printf(" -o Use a third party pi futex owner during requeue (cancels -l)\n"); printf(" -t N Timeout in nanoseconds (default: 0)\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } int create_rt_thread(pthread_t *pth, void*(*func)(void *), void *arg, int policy, int prio) { int ret; struct sched_param schedp; pthread_attr_t attr; pthread_attr_init(&attr); memset(&schedp, 0, sizeof(schedp)); ret = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); if (ret) { error("pthread_attr_setinheritsched\n", ret); return -1; } ret = pthread_attr_setschedpolicy(&attr, policy); if (ret) { error("pthread_attr_setschedpolicy\n", ret); return -1; } schedp.sched_priority = prio; ret = pthread_attr_setschedparam(&attr, &schedp); if (ret) { error("pthread_attr_setschedparam\n", ret); return -1; } ret = pthread_create(pth, &attr, func, arg); if (ret) { error("pthread_create\n", ret); return -1; } return 0; } void *waiterfn(void *arg) { struct thread_arg *args = (struct thread_arg *)arg; futex_t old_val; info("Waiter %ld: running\n", args->id); /* Each thread sleeps for a different amount of time * This is to avoid races, because we don't lock the * external mutex here */ usleep(1000 * (long)args->id); old_val = f1; atomic_inc(&waiters_blocked); info("Calling futex_wait_requeue_pi: %p (%u) -> %p\n", &f1, f1, &f2); args->ret = futex_wait_requeue_pi(&f1, old_val, &f2, args->timeout, FUTEX_PRIVATE_FLAG); info("waiter %ld woke with %d %s\n", args->id, args->ret, args->ret < 0 ? strerror(errno) : ""); atomic_inc(&waiters_woken); if (args->ret < 0) { if (args->timeout && errno == ETIMEDOUT) args->ret = 0; else { args->ret = RET_ERROR; error("futex_wait_requeue_pi\n", errno); } futex_lock_pi(&f2, NULL, 0, FUTEX_PRIVATE_FLAG); } futex_unlock_pi(&f2, FUTEX_PRIVATE_FLAG); info("Waiter %ld: exiting with %d\n", args->id, args->ret); pthread_exit((void *)&args->ret); } void *broadcast_wakerfn(void *arg) { struct thread_arg *args = (struct thread_arg *)arg; int nr_requeue = INT_MAX; int task_count = 0; futex_t old_val; int nr_wake = 1; int i = 0; info("Waker: waiting for waiters to block\n"); while (waiters_blocked.val < THREAD_MAX) usleep(1000); usleep(1000); info("Waker: Calling broadcast\n"); if (args->lock) { info("Calling FUTEX_LOCK_PI on mutex=%x @ %p\n", f2, &f2); futex_lock_pi(&f2, NULL, 0, FUTEX_PRIVATE_FLAG); } continue_requeue: old_val = f1; args->ret = futex_cmp_requeue_pi(&f1, old_val, &f2, nr_wake, nr_requeue, FUTEX_PRIVATE_FLAG); if (args->ret < 0) { args->ret = RET_ERROR; error("FUTEX_CMP_REQUEUE_PI failed\n", errno); } else if (++i < MAX_WAKE_ITERS) { task_count += args->ret; if (task_count < THREAD_MAX - waiters_woken.val) goto continue_requeue; } else { error("max broadcast iterations (%d) reached with %d/%d tasks woken or requeued\n", 0, MAX_WAKE_ITERS, task_count, THREAD_MAX); args->ret = RET_ERROR; } futex_wake(&wake_complete, 1, FUTEX_PRIVATE_FLAG); if (args->lock) futex_unlock_pi(&f2, FUTEX_PRIVATE_FLAG); if (args->ret > 0) args->ret = task_count; info("Waker: exiting with %d\n", args->ret); pthread_exit((void *)&args->ret); } void *signal_wakerfn(void *arg) { struct thread_arg *args = (struct thread_arg *)arg; unsigned int old_val; int nr_requeue = 0; int task_count = 0; int nr_wake = 1; int i = 0; info("Waker: waiting for waiters to block\n"); while (waiters_blocked.val < THREAD_MAX) usleep(1000); usleep(1000); while (task_count < THREAD_MAX && waiters_woken.val < THREAD_MAX) { info("task_count: %d, waiters_woken: %d\n", task_count, waiters_woken.val); if (args->lock) { info("Calling FUTEX_LOCK_PI on mutex=%x @ %p\n", f2, &f2); futex_lock_pi(&f2, NULL, 0, FUTEX_PRIVATE_FLAG); } info("Waker: Calling signal\n"); /* cond_signal */ old_val = f1; args->ret = futex_cmp_requeue_pi(&f1, old_val, &f2, nr_wake, nr_requeue, FUTEX_PRIVATE_FLAG); if (args->ret < 0) args->ret = -errno; info("futex: %x\n", f2); if (args->lock) { info("Calling FUTEX_UNLOCK_PI on mutex=%x @ %p\n", f2, &f2); futex_unlock_pi(&f2, FUTEX_PRIVATE_FLAG); } info("futex: %x\n", f2); if (args->ret < 0) { error("FUTEX_CMP_REQUEUE_PI failed\n", errno); args->ret = RET_ERROR; break; } task_count += args->ret; usleep(SIGNAL_PERIOD_US); i++; /* we have to loop at least THREAD_MAX times */ if (i > MAX_WAKE_ITERS + THREAD_MAX) { error("max signaling iterations (%d) reached, giving up on pending waiters.\n", 0, MAX_WAKE_ITERS + THREAD_MAX); args->ret = RET_ERROR; break; } } futex_wake(&wake_complete, 1, FUTEX_PRIVATE_FLAG); if (args->ret >= 0) args->ret = task_count; info("Waker: exiting with %d\n", args->ret); info("Waker: waiters_woken: %d\n", waiters_woken.val); pthread_exit((void *)&args->ret); } void *third_party_blocker(void *arg) { struct thread_arg *args = (struct thread_arg *)arg; int ret2 = 0; args->ret = futex_lock_pi(&f2, NULL, 0, FUTEX_PRIVATE_FLAG); if (args->ret) goto out; args->ret = futex_wait(&wake_complete, wake_complete, NULL, FUTEX_PRIVATE_FLAG); ret2 = futex_unlock_pi(&f2, FUTEX_PRIVATE_FLAG); out: if (args->ret || ret2) { error("third_party_blocker() futex error", 0); args->ret = RET_ERROR; } pthread_exit((void *)&args->ret); } int unit_test(int broadcast, long lock, int third_party_owner, long timeout_ns) { void *(*wakerfn)(void *) = signal_wakerfn; struct thread_arg blocker_arg = THREAD_ARG_INITIALIZER; struct thread_arg waker_arg = THREAD_ARG_INITIALIZER; pthread_t waiter[THREAD_MAX], waker, blocker; struct timespec ts, *tsp = NULL; struct thread_arg args[THREAD_MAX]; int *waiter_ret; int i, ret = RET_PASS; if (timeout_ns) { time_t secs; info("timeout_ns = %ld\n", timeout_ns); ret = clock_gettime(CLOCK_MONOTONIC, &ts); secs = (ts.tv_nsec + timeout_ns) / 1000000000; ts.tv_nsec = ((int64_t)ts.tv_nsec + timeout_ns) % 1000000000; ts.tv_sec += secs; info("ts.tv_sec = %ld\n", ts.tv_sec); info("ts.tv_nsec = %ld\n", ts.tv_nsec); tsp = &ts; } if (broadcast) wakerfn = broadcast_wakerfn; if (third_party_owner) { if (create_rt_thread(&blocker, third_party_blocker, (void *)&blocker_arg, SCHED_FIFO, 1)) { error("Creating third party blocker thread failed\n", errno); ret = RET_ERROR; goto out; } } atomic_set(&waiters_woken, 0); for (i = 0; i < THREAD_MAX; i++) { args[i].id = i; args[i].timeout = tsp; info("Starting thread %d\n", i); if (create_rt_thread(&waiter[i], waiterfn, (void *)&args[i], SCHED_FIFO, 1)) { error("Creating waiting thread failed\n", errno); ret = RET_ERROR; goto out; } } waker_arg.lock = lock; if (create_rt_thread(&waker, wakerfn, (void *)&waker_arg, SCHED_FIFO, 1)) { error("Creating waker thread failed\n", errno); ret = RET_ERROR; goto out; } /* Wait for threads to finish */ /* Store the first error or failure encountered in waiter_ret */ waiter_ret = &args[0].ret; for (i = 0; i < THREAD_MAX; i++) pthread_join(waiter[i], *waiter_ret ? NULL : (void **)&waiter_ret); if (third_party_owner) pthread_join(blocker, NULL); pthread_join(waker, NULL); out: if (!ret) { if (*waiter_ret) ret = *waiter_ret; else if (waker_arg.ret < 0) ret = waker_arg.ret; else if (blocker_arg.ret) ret = blocker_arg.ret; } return ret; } int main(int argc, char *argv[]) { int c, ret; while ((c = getopt(argc, argv, "bchlot:v:")) != -1) { switch (c) { case 'b': broadcast = 1; break; case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'l': locked = 1; break; case 'o': owner = 1; locked = 0; break; case 't': timeout_ns = atoi(optarg); break; case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(1); ksft_print_msg("%s: Test requeue functionality\n", basename(argv[0])); ksft_print_msg( "\tArguments: broadcast=%d locked=%d owner=%d timeout=%ldns\n", broadcast, locked, owner, timeout_ns); /* * FIXME: unit_test is obsolete now that we parse options and the * various style of runs are done by run.sh - simplify the code and move * unit_test into main() */ ret = unit_test(broadcast, locked, owner, timeout_ns); print_result(TEST_NAME, ret); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_requeue_pi.c
// SPDX-License-Identifier: GPL-2.0-or-later /****************************************************************************** * * Copyright © International Business Machines Corp., 2009 * * DESCRIPTION * 1. Block a thread using FUTEX_WAIT * 2. Attempt to use FUTEX_CMP_REQUEUE_PI on the futex from 1. * 3. The kernel must detect the mismatch and return -EINVAL. * * AUTHOR * Darren Hart <[email protected]> * * HISTORY * 2009-Nov-9: Initial version by Darren Hart <[email protected]> * *****************************************************************************/ #include <errno.h> #include <getopt.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "futextest.h" #include "logging.h" #define TEST_NAME "futex-requeue-pi-mismatched-ops" futex_t f1 = FUTEX_INITIALIZER; futex_t f2 = FUTEX_INITIALIZER; int child_ret = 0; void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } void *blocking_child(void *arg) { child_ret = futex_wait(&f1, f1, NULL, FUTEX_PRIVATE_FLAG); if (child_ret < 0) { child_ret = -errno; error("futex_wait\n", errno); } return (void *)&child_ret; } int main(int argc, char *argv[]) { int ret = RET_PASS; pthread_t child; int c; while ((c = getopt(argc, argv, "chv:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(1); ksft_print_msg("%s: Detect mismatched requeue_pi operations\n", basename(argv[0])); if (pthread_create(&child, NULL, blocking_child, NULL)) { error("pthread_create\n", errno); ret = RET_ERROR; goto out; } /* Allow the child to block in the kernel. */ sleep(1); /* * The kernel should detect the waiter did not setup the * q->requeue_pi_key and return -EINVAL. If it does not, * it likely gave the lock to the child, which is now hung * in the kernel. */ ret = futex_cmp_requeue_pi(&f1, f1, &f2, 1, 0, FUTEX_PRIVATE_FLAG); if (ret < 0) { if (errno == EINVAL) { /* * The kernel correctly detected the mismatched * requeue_pi target and aborted. Wake the child with * FUTEX_WAKE. */ ret = futex_wake(&f1, 1, FUTEX_PRIVATE_FLAG); if (ret == 1) { ret = RET_PASS; } else if (ret < 0) { error("futex_wake\n", errno); ret = RET_ERROR; } else { error("futex_wake did not wake the child\n", 0); ret = RET_ERROR; } } else { error("futex_cmp_requeue_pi\n", errno); ret = RET_ERROR; } } else if (ret > 0) { fail("futex_cmp_requeue_pi failed to detect the mismatch\n"); ret = RET_FAIL; } else { error("futex_cmp_requeue_pi found no waiters\n", 0); ret = RET_ERROR; } pthread_join(child, NULL); if (!ret) ret = child_ret; out: /* If the kernel crashes, we shouldn't return at all. */ print_result(TEST_NAME, ret); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_requeue_pi_mismatched_ops.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright Collabora Ltd., 2021 * * futex cmp requeue test by André Almeida <[email protected]> */ #include <pthread.h> #include <limits.h> #include "logging.h" #include "futextest.h" #define TEST_NAME "futex-requeue" #define timeout_ns 30000000 #define WAKE_WAIT_US 10000 volatile futex_t *f1; void usage(char *prog) { printf("Usage: %s\n", prog); printf(" -c Use color\n"); printf(" -h Display this help message\n"); printf(" -v L Verbosity level: %d=QUIET %d=CRITICAL %d=INFO\n", VQUIET, VCRITICAL, VINFO); } void *waiterfn(void *arg) { struct timespec to; to.tv_sec = 0; to.tv_nsec = timeout_ns; if (futex_wait(f1, *f1, &to, 0)) printf("waiter failed errno %d\n", errno); return NULL; } int main(int argc, char *argv[]) { pthread_t waiter[10]; int res, ret = RET_PASS; int c, i; volatile futex_t _f1 = 0; volatile futex_t f2 = 0; f1 = &_f1; while ((c = getopt(argc, argv, "cht:v:")) != -1) { switch (c) { case 'c': log_color(1); break; case 'h': usage(basename(argv[0])); exit(0); case 'v': log_verbosity(atoi(optarg)); break; default: usage(basename(argv[0])); exit(1); } } ksft_print_header(); ksft_set_plan(2); ksft_print_msg("%s: Test futex_requeue\n", basename(argv[0])); /* * Requeue a waiter from f1 to f2, and wake f2. */ if (pthread_create(&waiter[0], NULL, waiterfn, NULL)) error("pthread_create failed\n", errno); usleep(WAKE_WAIT_US); info("Requeuing 1 futex from f1 to f2\n"); res = futex_cmp_requeue(f1, 0, &f2, 0, 1, 0); if (res != 1) { ksft_test_result_fail("futex_requeue simple returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } info("Waking 1 futex at f2\n"); res = futex_wake(&f2, 1, 0); if (res != 1) { ksft_test_result_fail("futex_requeue simple returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_requeue simple succeeds\n"); } /* * Create 10 waiters at f1. At futex_requeue, wake 3 and requeue 7. * At futex_wake, wake INT_MAX (should be exactly 7). */ for (i = 0; i < 10; i++) { if (pthread_create(&waiter[i], NULL, waiterfn, NULL)) error("pthread_create failed\n", errno); } usleep(WAKE_WAIT_US); info("Waking 3 futexes at f1 and requeuing 7 futexes from f1 to f2\n"); res = futex_cmp_requeue(f1, 0, &f2, 3, 7, 0); if (res != 10) { ksft_test_result_fail("futex_requeue many returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } info("Waking INT_MAX futexes at f2\n"); res = futex_wake(&f2, INT_MAX, 0); if (res != 7) { ksft_test_result_fail("futex_requeue many returned: %d %s\n", res ? errno : res, res ? strerror(errno) : ""); ret = RET_FAIL; } else { ksft_test_result_pass("futex_requeue many succeeds\n"); } ksft_print_cnts(); return ret; }
linux-master
tools/testing/selftests/futex/functional/futex_requeue.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Author: Alexey Gladkov <[email protected]> */ #define _GNU_SOURCE #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/prctl.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sched.h> #include <signal.h> #include <limits.h> #include <fcntl.h> #include <errno.h> #include <err.h> #define NR_CHILDS 2 static char *service_prog; static uid_t user = 60000; static uid_t group = 60000; static void setrlimit_nproc(rlim_t n) { pid_t pid = getpid(); struct rlimit limit = { .rlim_cur = n, .rlim_max = n }; warnx("(pid=%d): Setting RLIMIT_NPROC=%ld", pid, n); if (setrlimit(RLIMIT_NPROC, &limit) < 0) err(EXIT_FAILURE, "(pid=%d): setrlimit(RLIMIT_NPROC)", pid); } static pid_t fork_child(void) { pid_t pid = fork(); if (pid < 0) err(EXIT_FAILURE, "fork"); if (pid > 0) return pid; pid = getpid(); warnx("(pid=%d): New process starting ...", pid); if (prctl(PR_SET_PDEATHSIG, SIGKILL) < 0) err(EXIT_FAILURE, "(pid=%d): prctl(PR_SET_PDEATHSIG)", pid); signal(SIGUSR1, SIG_DFL); warnx("(pid=%d): Changing to uid=%d, gid=%d", pid, user, group); if (setgid(group) < 0) err(EXIT_FAILURE, "(pid=%d): setgid(%d)", pid, group); if (setuid(user) < 0) err(EXIT_FAILURE, "(pid=%d): setuid(%d)", pid, user); warnx("(pid=%d): Service running ...", pid); warnx("(pid=%d): Unshare user namespace", pid); if (unshare(CLONE_NEWUSER) < 0) err(EXIT_FAILURE, "unshare(CLONE_NEWUSER)"); char *const argv[] = { "service", NULL }; char *const envp[] = { "I_AM_SERVICE=1", NULL }; warnx("(pid=%d): Executing real service ...", pid); execve(service_prog, argv, envp); err(EXIT_FAILURE, "(pid=%d): execve", pid); } int main(int argc, char **argv) { size_t i; pid_t child[NR_CHILDS]; int wstatus[NR_CHILDS]; int childs = NR_CHILDS; pid_t pid; if (getenv("I_AM_SERVICE")) { pause(); exit(EXIT_SUCCESS); } service_prog = argv[0]; pid = getpid(); warnx("(pid=%d) Starting testcase", pid); /* * This rlimit is not a problem for root because it can be exceeded. */ setrlimit_nproc(1); for (i = 0; i < NR_CHILDS; i++) { child[i] = fork_child(); wstatus[i] = 0; usleep(250000); } while (1) { for (i = 0; i < NR_CHILDS; i++) { if (child[i] <= 0) continue; errno = 0; pid_t ret = waitpid(child[i], &wstatus[i], WNOHANG); if (!ret || (!WIFEXITED(wstatus[i]) && !WIFSIGNALED(wstatus[i]))) continue; if (ret < 0 && errno != ECHILD) warn("(pid=%d): waitpid(%d)", pid, child[i]); child[i] *= -1; childs -= 1; } if (!childs) break; usleep(250000); for (i = 0; i < NR_CHILDS; i++) { if (child[i] <= 0) continue; kill(child[i], SIGUSR1); } } for (i = 0; i < NR_CHILDS; i++) { if (WIFEXITED(wstatus[i])) warnx("(pid=%d): pid %d exited, status=%d", pid, -child[i], WEXITSTATUS(wstatus[i])); else if (WIFSIGNALED(wstatus[i])) warnx("(pid=%d): pid %d killed by signal %d", pid, -child[i], WTERMSIG(wstatus[i])); if (WIFSIGNALED(wstatus[i]) && WTERMSIG(wstatus[i]) == SIGUSR1) continue; warnx("(pid=%d): Test failed", pid); exit(EXIT_FAILURE); } warnx("(pid=%d): Test passed", pid); exit(EXIT_SUCCESS); }
linux-master
tools/testing/selftests/rlimits/rlimits-per-userns.c
// SPDX-License-Identifier: GPL-2.0 /* Test triggering of loading of firmware from different mount * namespaces. Expect firmware to be always loaded from the mount * namespace of PID 1. */ #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <sched.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #ifndef CLONE_NEWNS # define CLONE_NEWNS 0x00020000 #endif static char *fw_path = NULL; static void die(char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); if (fw_path) unlink(fw_path); umount("/lib/firmware"); exit(EXIT_FAILURE); } static void trigger_fw(const char *fw_name, const char *sys_path) { int fd; fd = open(sys_path, O_WRONLY); if (fd < 0) die("open failed: %s\n", strerror(errno)); if (write(fd, fw_name, strlen(fw_name)) != strlen(fw_name)) exit(EXIT_FAILURE); close(fd); } static void setup_fw(const char *fw_path) { int fd; const char fw[] = "ABCD0123"; fd = open(fw_path, O_WRONLY | O_CREAT, 0600); if (fd < 0) die("open failed: %s\n", strerror(errno)); if (write(fd, fw, sizeof(fw) -1) != sizeof(fw) -1) die("write failed: %s\n", strerror(errno)); close(fd); } static bool test_fw_in_ns(const char *fw_name, const char *sys_path, bool block_fw_in_parent_ns) { pid_t child; if (block_fw_in_parent_ns) if (mount("test", "/lib/firmware", "tmpfs", MS_RDONLY, NULL) == -1) die("blocking firmware in parent ns failed\n"); child = fork(); if (child == -1) { die("fork failed: %s\n", strerror(errno)); } if (child != 0) { /* parent */ pid_t pid; int status; pid = waitpid(child, &status, 0); if (pid == -1) { die("waitpid failed: %s\n", strerror(errno)); } if (pid != child) { die("waited for %d got %d\n", child, pid); } if (!WIFEXITED(status)) { die("child did not terminate cleanly\n"); } if (block_fw_in_parent_ns) umount("/lib/firmware"); return WEXITSTATUS(status) == EXIT_SUCCESS; } if (unshare(CLONE_NEWNS) != 0) { die("unshare(CLONE_NEWNS) failed: %s\n", strerror(errno)); } if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) == -1) die("remount root in child ns failed\n"); if (!block_fw_in_parent_ns) { if (mount("test", "/lib/firmware", "tmpfs", MS_RDONLY, NULL) == -1) die("blocking firmware in child ns failed\n"); } else umount("/lib/firmware"); trigger_fw(fw_name, sys_path); exit(EXIT_SUCCESS); } int main(int argc, char **argv) { const char *fw_name = "test-firmware.bin"; char *sys_path; if (argc != 2) die("usage: %s sys_path\n", argv[0]); /* Mount tmpfs to /lib/firmware so we don't have to assume that it is writable for us.*/ if (mount("test", "/lib/firmware", "tmpfs", 0, NULL) == -1) die("mounting tmpfs to /lib/firmware failed\n"); sys_path = argv[1]; if (asprintf(&fw_path, "/lib/firmware/%s", fw_name) < 0) die("error: failed to build full fw_path\n"); setup_fw(fw_path); setvbuf(stdout, NULL, _IONBF, 0); /* Positive case: firmware in PID1 mount namespace */ printf("Testing with firmware in parent namespace (assumed to be same file system as PID1)\n"); if (!test_fw_in_ns(fw_name, sys_path, false)) die("error: failed to access firmware\n"); /* Negative case: firmware in child mount namespace, expected to fail */ printf("Testing with firmware in child namespace\n"); if (test_fw_in_ns(fw_name, sys_path, true)) die("error: firmware access did not fail\n"); unlink(fw_path); free(fw_path); umount("/lib/firmware"); exit(EXIT_SUCCESS); }
linux-master
tools/testing/selftests/firmware/fw_namespace.c
// SPDX-License-Identifier: LGPL-2.1 /* * rseq.c * * Copyright (C) 2016 Mathieu Desnoyers <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; only * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #define _GNU_SOURCE #include <errno.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <syscall.h> #include <assert.h> #include <signal.h> #include <limits.h> #include <dlfcn.h> #include <stddef.h> #include <sys/auxv.h> #include <linux/auxvec.h> #include <linux/compiler.h> #include "../kselftest.h" #include "rseq.h" /* * Define weak versions to play nice with binaries that are statically linked * against a libc that doesn't support registering its own rseq. */ __weak ptrdiff_t __rseq_offset; __weak unsigned int __rseq_size; __weak unsigned int __rseq_flags; static const ptrdiff_t *libc_rseq_offset_p = &__rseq_offset; static const unsigned int *libc_rseq_size_p = &__rseq_size; static const unsigned int *libc_rseq_flags_p = &__rseq_flags; /* Offset from the thread pointer to the rseq area. */ ptrdiff_t rseq_offset; /* * Size of the registered rseq area. 0 if the registration was * unsuccessful. */ unsigned int rseq_size = -1U; /* Flags used during rseq registration. */ unsigned int rseq_flags; /* * rseq feature size supported by the kernel. 0 if the registration was * unsuccessful. */ unsigned int rseq_feature_size = -1U; static int rseq_ownership; static int rseq_reg_success; /* At least one rseq registration has succeded. */ /* Allocate a large area for the TLS. */ #define RSEQ_THREAD_AREA_ALLOC_SIZE 1024 /* Original struct rseq feature size is 20 bytes. */ #define ORIG_RSEQ_FEATURE_SIZE 20 /* Original struct rseq allocation size is 32 bytes. */ #define ORIG_RSEQ_ALLOC_SIZE 32 static __thread struct rseq_abi __rseq_abi __attribute__((tls_model("initial-exec"), aligned(RSEQ_THREAD_AREA_ALLOC_SIZE))) = { .cpu_id = RSEQ_ABI_CPU_ID_UNINITIALIZED, }; static int sys_rseq(struct rseq_abi *rseq_abi, uint32_t rseq_len, int flags, uint32_t sig) { return syscall(__NR_rseq, rseq_abi, rseq_len, flags, sig); } static int sys_getcpu(unsigned *cpu, unsigned *node) { return syscall(__NR_getcpu, cpu, node, NULL); } int rseq_available(void) { int rc; rc = sys_rseq(NULL, 0, 0, 0); if (rc != -1) abort(); switch (errno) { case ENOSYS: return 0; case EINVAL: return 1; default: abort(); } } int rseq_register_current_thread(void) { int rc; if (!rseq_ownership) { /* Treat libc's ownership as a successful registration. */ return 0; } rc = sys_rseq(&__rseq_abi, rseq_size, 0, RSEQ_SIG); if (rc) { if (RSEQ_READ_ONCE(rseq_reg_success)) { /* Incoherent success/failure within process. */ abort(); } return -1; } assert(rseq_current_cpu_raw() >= 0); RSEQ_WRITE_ONCE(rseq_reg_success, 1); return 0; } int rseq_unregister_current_thread(void) { int rc; if (!rseq_ownership) { /* Treat libc's ownership as a successful unregistration. */ return 0; } rc = sys_rseq(&__rseq_abi, rseq_size, RSEQ_ABI_FLAG_UNREGISTER, RSEQ_SIG); if (rc) return -1; return 0; } static unsigned int get_rseq_feature_size(void) { unsigned long auxv_rseq_feature_size, auxv_rseq_align; auxv_rseq_align = getauxval(AT_RSEQ_ALIGN); assert(!auxv_rseq_align || auxv_rseq_align <= RSEQ_THREAD_AREA_ALLOC_SIZE); auxv_rseq_feature_size = getauxval(AT_RSEQ_FEATURE_SIZE); assert(!auxv_rseq_feature_size || auxv_rseq_feature_size <= RSEQ_THREAD_AREA_ALLOC_SIZE); if (auxv_rseq_feature_size) return auxv_rseq_feature_size; else return ORIG_RSEQ_FEATURE_SIZE; } static __attribute__((constructor)) void rseq_init(void) { /* * If the libc's registered rseq size isn't already valid, it may be * because the binary is dynamically linked and not necessarily due to * libc not having registered a restartable sequence. Try to find the * symbols if that's the case. */ if (!*libc_rseq_size_p) { libc_rseq_offset_p = dlsym(RTLD_NEXT, "__rseq_offset"); libc_rseq_size_p = dlsym(RTLD_NEXT, "__rseq_size"); libc_rseq_flags_p = dlsym(RTLD_NEXT, "__rseq_flags"); } if (libc_rseq_size_p && libc_rseq_offset_p && libc_rseq_flags_p && *libc_rseq_size_p != 0) { /* rseq registration owned by glibc */ rseq_offset = *libc_rseq_offset_p; rseq_size = *libc_rseq_size_p; rseq_flags = *libc_rseq_flags_p; rseq_feature_size = get_rseq_feature_size(); if (rseq_feature_size > rseq_size) rseq_feature_size = rseq_size; return; } rseq_ownership = 1; if (!rseq_available()) { rseq_size = 0; rseq_feature_size = 0; return; } rseq_offset = (void *)&__rseq_abi - rseq_thread_pointer(); rseq_flags = 0; rseq_feature_size = get_rseq_feature_size(); if (rseq_feature_size == ORIG_RSEQ_FEATURE_SIZE) rseq_size = ORIG_RSEQ_ALLOC_SIZE; else rseq_size = RSEQ_THREAD_AREA_ALLOC_SIZE; } static __attribute__((destructor)) void rseq_exit(void) { if (!rseq_ownership) return; rseq_offset = 0; rseq_size = -1U; rseq_feature_size = -1U; rseq_ownership = 0; } int32_t rseq_fallback_current_cpu(void) { int32_t cpu; cpu = sched_getcpu(); if (cpu < 0) { perror("sched_getcpu()"); abort(); } return cpu; } int32_t rseq_fallback_current_node(void) { uint32_t cpu_id, node_id; int ret; ret = sys_getcpu(&cpu_id, &node_id); if (ret) { perror("sys_getcpu()"); return ret; } return (int32_t) node_id; }
linux-master
tools/testing/selftests/rseq/rseq.c
// SPDX-License-Identifier: LGPL-2.1 #define _GNU_SOURCE #include <assert.h> #include <linux/membarrier.h> #include <pthread.h> #include <sched.h> #include <stdatomic.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syscall.h> #include <unistd.h> #include <poll.h> #include <sys/types.h> #include <signal.h> #include <errno.h> #include <stddef.h> #include <stdbool.h> static inline pid_t rseq_gettid(void) { return syscall(__NR_gettid); } #define NR_INJECT 9 static int loop_cnt[NR_INJECT + 1]; static int loop_cnt_1 asm("asm_loop_cnt_1") __attribute__((used)); static int loop_cnt_2 asm("asm_loop_cnt_2") __attribute__((used)); static int loop_cnt_3 asm("asm_loop_cnt_3") __attribute__((used)); static int loop_cnt_4 asm("asm_loop_cnt_4") __attribute__((used)); static int loop_cnt_5 asm("asm_loop_cnt_5") __attribute__((used)); static int loop_cnt_6 asm("asm_loop_cnt_6") __attribute__((used)); static int opt_modulo, verbose; static int opt_yield, opt_signal, opt_sleep, opt_disable_rseq, opt_threads = 200, opt_disable_mod = 0, opt_test = 's'; static long long opt_reps = 5000; static __thread __attribute__((tls_model("initial-exec"))) unsigned int signals_delivered; #ifndef BENCHMARK static __thread __attribute__((tls_model("initial-exec"), unused)) unsigned int yield_mod_cnt, nr_abort; #define printf_verbose(fmt, ...) \ do { \ if (verbose) \ printf(fmt, ## __VA_ARGS__); \ } while (0) #ifdef __i386__ #define INJECT_ASM_REG "eax" #define RSEQ_INJECT_CLOBBER \ , INJECT_ASM_REG #define RSEQ_INJECT_ASM(n) \ "mov asm_loop_cnt_" #n ", %%" INJECT_ASM_REG "\n\t" \ "test %%" INJECT_ASM_REG ",%%" INJECT_ASM_REG "\n\t" \ "jz 333f\n\t" \ "222:\n\t" \ "dec %%" INJECT_ASM_REG "\n\t" \ "jnz 222b\n\t" \ "333:\n\t" #elif defined(__x86_64__) #define INJECT_ASM_REG_P "rax" #define INJECT_ASM_REG "eax" #define RSEQ_INJECT_CLOBBER \ , INJECT_ASM_REG_P \ , INJECT_ASM_REG #define RSEQ_INJECT_ASM(n) \ "lea asm_loop_cnt_" #n "(%%rip), %%" INJECT_ASM_REG_P "\n\t" \ "mov (%%" INJECT_ASM_REG_P "), %%" INJECT_ASM_REG "\n\t" \ "test %%" INJECT_ASM_REG ",%%" INJECT_ASM_REG "\n\t" \ "jz 333f\n\t" \ "222:\n\t" \ "dec %%" INJECT_ASM_REG "\n\t" \ "jnz 222b\n\t" \ "333:\n\t" #elif defined(__s390__) #define RSEQ_INJECT_INPUT \ , [loop_cnt_1]"m"(loop_cnt[1]) \ , [loop_cnt_2]"m"(loop_cnt[2]) \ , [loop_cnt_3]"m"(loop_cnt[3]) \ , [loop_cnt_4]"m"(loop_cnt[4]) \ , [loop_cnt_5]"m"(loop_cnt[5]) \ , [loop_cnt_6]"m"(loop_cnt[6]) #define INJECT_ASM_REG "r12" #define RSEQ_INJECT_CLOBBER \ , INJECT_ASM_REG #define RSEQ_INJECT_ASM(n) \ "l %%" INJECT_ASM_REG ", %[loop_cnt_" #n "]\n\t" \ "ltr %%" INJECT_ASM_REG ", %%" INJECT_ASM_REG "\n\t" \ "je 333f\n\t" \ "222:\n\t" \ "ahi %%" INJECT_ASM_REG ", -1\n\t" \ "jnz 222b\n\t" \ "333:\n\t" #elif defined(__ARMEL__) #define RSEQ_INJECT_INPUT \ , [loop_cnt_1]"m"(loop_cnt[1]) \ , [loop_cnt_2]"m"(loop_cnt[2]) \ , [loop_cnt_3]"m"(loop_cnt[3]) \ , [loop_cnt_4]"m"(loop_cnt[4]) \ , [loop_cnt_5]"m"(loop_cnt[5]) \ , [loop_cnt_6]"m"(loop_cnt[6]) #define INJECT_ASM_REG "r4" #define RSEQ_INJECT_CLOBBER \ , INJECT_ASM_REG #define RSEQ_INJECT_ASM(n) \ "ldr " INJECT_ASM_REG ", %[loop_cnt_" #n "]\n\t" \ "cmp " INJECT_ASM_REG ", #0\n\t" \ "beq 333f\n\t" \ "222:\n\t" \ "subs " INJECT_ASM_REG ", #1\n\t" \ "bne 222b\n\t" \ "333:\n\t" #elif defined(__AARCH64EL__) #define RSEQ_INJECT_INPUT \ , [loop_cnt_1] "Qo" (loop_cnt[1]) \ , [loop_cnt_2] "Qo" (loop_cnt[2]) \ , [loop_cnt_3] "Qo" (loop_cnt[3]) \ , [loop_cnt_4] "Qo" (loop_cnt[4]) \ , [loop_cnt_5] "Qo" (loop_cnt[5]) \ , [loop_cnt_6] "Qo" (loop_cnt[6]) #define INJECT_ASM_REG RSEQ_ASM_TMP_REG32 #define RSEQ_INJECT_ASM(n) \ " ldr " INJECT_ASM_REG ", %[loop_cnt_" #n "]\n" \ " cbz " INJECT_ASM_REG ", 333f\n" \ "222:\n" \ " sub " INJECT_ASM_REG ", " INJECT_ASM_REG ", #1\n" \ " cbnz " INJECT_ASM_REG ", 222b\n" \ "333:\n" #elif defined(__PPC__) #define RSEQ_INJECT_INPUT \ , [loop_cnt_1]"m"(loop_cnt[1]) \ , [loop_cnt_2]"m"(loop_cnt[2]) \ , [loop_cnt_3]"m"(loop_cnt[3]) \ , [loop_cnt_4]"m"(loop_cnt[4]) \ , [loop_cnt_5]"m"(loop_cnt[5]) \ , [loop_cnt_6]"m"(loop_cnt[6]) #define INJECT_ASM_REG "r18" #define RSEQ_INJECT_CLOBBER \ , INJECT_ASM_REG #define RSEQ_INJECT_ASM(n) \ "lwz %%" INJECT_ASM_REG ", %[loop_cnt_" #n "]\n\t" \ "cmpwi %%" INJECT_ASM_REG ", 0\n\t" \ "beq 333f\n\t" \ "222:\n\t" \ "subic. %%" INJECT_ASM_REG ", %%" INJECT_ASM_REG ", 1\n\t" \ "bne 222b\n\t" \ "333:\n\t" #elif defined(__mips__) #define RSEQ_INJECT_INPUT \ , [loop_cnt_1]"m"(loop_cnt[1]) \ , [loop_cnt_2]"m"(loop_cnt[2]) \ , [loop_cnt_3]"m"(loop_cnt[3]) \ , [loop_cnt_4]"m"(loop_cnt[4]) \ , [loop_cnt_5]"m"(loop_cnt[5]) \ , [loop_cnt_6]"m"(loop_cnt[6]) #define INJECT_ASM_REG "$5" #define RSEQ_INJECT_CLOBBER \ , INJECT_ASM_REG #define RSEQ_INJECT_ASM(n) \ "lw " INJECT_ASM_REG ", %[loop_cnt_" #n "]\n\t" \ "beqz " INJECT_ASM_REG ", 333f\n\t" \ "222:\n\t" \ "addiu " INJECT_ASM_REG ", -1\n\t" \ "bnez " INJECT_ASM_REG ", 222b\n\t" \ "333:\n\t" #elif defined(__riscv) #define RSEQ_INJECT_INPUT \ , [loop_cnt_1]"m"(loop_cnt[1]) \ , [loop_cnt_2]"m"(loop_cnt[2]) \ , [loop_cnt_3]"m"(loop_cnt[3]) \ , [loop_cnt_4]"m"(loop_cnt[4]) \ , [loop_cnt_5]"m"(loop_cnt[5]) \ , [loop_cnt_6]"m"(loop_cnt[6]) #define INJECT_ASM_REG "t1" #define RSEQ_INJECT_CLOBBER \ , INJECT_ASM_REG #define RSEQ_INJECT_ASM(n) \ "lw " INJECT_ASM_REG ", %[loop_cnt_" #n "]\n\t" \ "beqz " INJECT_ASM_REG ", 333f\n\t" \ "222:\n\t" \ "addi " INJECT_ASM_REG "," INJECT_ASM_REG ", -1\n\t" \ "bnez " INJECT_ASM_REG ", 222b\n\t" \ "333:\n\t" #else #error unsupported target #endif #define RSEQ_INJECT_FAILED \ nr_abort++; #define RSEQ_INJECT_C(n) \ { \ int loc_i, loc_nr_loops = loop_cnt[n]; \ \ for (loc_i = 0; loc_i < loc_nr_loops; loc_i++) { \ rseq_barrier(); \ } \ if (loc_nr_loops == -1 && opt_modulo) { \ if (yield_mod_cnt == opt_modulo - 1) { \ if (opt_sleep > 0) \ poll(NULL, 0, opt_sleep); \ if (opt_yield) \ sched_yield(); \ if (opt_signal) \ raise(SIGUSR1); \ yield_mod_cnt = 0; \ } else { \ yield_mod_cnt++; \ } \ } \ } #else #define printf_verbose(fmt, ...) #endif /* BENCHMARK */ #include "rseq.h" static enum rseq_mo opt_mo = RSEQ_MO_RELAXED; #ifdef RSEQ_ARCH_HAS_OFFSET_DEREF_ADDV #define TEST_MEMBARRIER static int sys_membarrier(int cmd, int flags, int cpu_id) { return syscall(__NR_membarrier, cmd, flags, cpu_id); } #endif #ifdef BUILDOPT_RSEQ_PERCPU_MM_CID # define RSEQ_PERCPU RSEQ_PERCPU_MM_CID static int get_current_cpu_id(void) { return rseq_current_mm_cid(); } static bool rseq_validate_cpu_id(void) { return rseq_mm_cid_available(); } # ifdef TEST_MEMBARRIER /* * Membarrier does not currently support targeting a mm_cid, so * issue the barrier on all cpus. */ static int rseq_membarrier_expedited(int cpu) { return sys_membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED_RSEQ, 0, 0); } # endif /* TEST_MEMBARRIER */ #else # define RSEQ_PERCPU RSEQ_PERCPU_CPU_ID static int get_current_cpu_id(void) { return rseq_cpu_start(); } static bool rseq_validate_cpu_id(void) { return rseq_current_cpu_raw() >= 0; } # ifdef TEST_MEMBARRIER static int rseq_membarrier_expedited(int cpu) { return sys_membarrier(MEMBARRIER_CMD_PRIVATE_EXPEDITED_RSEQ, MEMBARRIER_CMD_FLAG_CPU, cpu); } # endif /* TEST_MEMBARRIER */ #endif struct percpu_lock_entry { intptr_t v; } __attribute__((aligned(128))); struct percpu_lock { struct percpu_lock_entry c[CPU_SETSIZE]; }; struct test_data_entry { intptr_t count; } __attribute__((aligned(128))); struct spinlock_test_data { struct percpu_lock lock; struct test_data_entry c[CPU_SETSIZE]; }; struct spinlock_thread_test_data { struct spinlock_test_data *data; long long reps; int reg; }; struct inc_test_data { struct test_data_entry c[CPU_SETSIZE]; }; struct inc_thread_test_data { struct inc_test_data *data; long long reps; int reg; }; struct percpu_list_node { intptr_t data; struct percpu_list_node *next; }; struct percpu_list_entry { struct percpu_list_node *head; } __attribute__((aligned(128))); struct percpu_list { struct percpu_list_entry c[CPU_SETSIZE]; }; #define BUFFER_ITEM_PER_CPU 100 struct percpu_buffer_node { intptr_t data; }; struct percpu_buffer_entry { intptr_t offset; intptr_t buflen; struct percpu_buffer_node **array; } __attribute__((aligned(128))); struct percpu_buffer { struct percpu_buffer_entry c[CPU_SETSIZE]; }; #define MEMCPY_BUFFER_ITEM_PER_CPU 100 struct percpu_memcpy_buffer_node { intptr_t data1; uint64_t data2; }; struct percpu_memcpy_buffer_entry { intptr_t offset; intptr_t buflen; struct percpu_memcpy_buffer_node *array; } __attribute__((aligned(128))); struct percpu_memcpy_buffer { struct percpu_memcpy_buffer_entry c[CPU_SETSIZE]; }; /* A simple percpu spinlock. Grabs lock on current cpu. */ static int rseq_this_cpu_lock(struct percpu_lock *lock) { int cpu; for (;;) { int ret; cpu = get_current_cpu_id(); if (cpu < 0) { fprintf(stderr, "pid: %d: tid: %d, cpu: %d: cid: %d\n", getpid(), (int) rseq_gettid(), rseq_current_cpu_raw(), cpu); abort(); } ret = rseq_cmpeqv_storev(RSEQ_MO_RELAXED, RSEQ_PERCPU, &lock->c[cpu].v, 0, 1, cpu); if (rseq_likely(!ret)) break; /* Retry if comparison fails or rseq aborts. */ } /* * Acquire semantic when taking lock after control dependency. * Matches rseq_smp_store_release(). */ rseq_smp_acquire__after_ctrl_dep(); return cpu; } static void rseq_percpu_unlock(struct percpu_lock *lock, int cpu) { assert(lock->c[cpu].v == 1); /* * Release lock, with release semantic. Matches * rseq_smp_acquire__after_ctrl_dep(). */ rseq_smp_store_release(&lock->c[cpu].v, 0); } void *test_percpu_spinlock_thread(void *arg) { struct spinlock_thread_test_data *thread_data = arg; struct spinlock_test_data *data = thread_data->data; long long i, reps; if (!opt_disable_rseq && thread_data->reg && rseq_register_current_thread()) abort(); reps = thread_data->reps; for (i = 0; i < reps; i++) { int cpu = rseq_this_cpu_lock(&data->lock); data->c[cpu].count++; rseq_percpu_unlock(&data->lock, cpu); #ifndef BENCHMARK if (i != 0 && !(i % (reps / 10))) printf_verbose("tid %d: count %lld\n", (int) rseq_gettid(), i); #endif } printf_verbose("tid %d: number of rseq abort: %d, signals delivered: %u\n", (int) rseq_gettid(), nr_abort, signals_delivered); if (!opt_disable_rseq && thread_data->reg && rseq_unregister_current_thread()) abort(); return NULL; } /* * A simple test which implements a sharded counter using a per-cpu * lock. Obviously real applications might prefer to simply use a * per-cpu increment; however, this is reasonable for a test and the * lock can be extended to synchronize more complicated operations. */ void test_percpu_spinlock(void) { const int num_threads = opt_threads; int i, ret; uint64_t sum; pthread_t test_threads[num_threads]; struct spinlock_test_data data; struct spinlock_thread_test_data thread_data[num_threads]; memset(&data, 0, sizeof(data)); for (i = 0; i < num_threads; i++) { thread_data[i].reps = opt_reps; if (opt_disable_mod <= 0 || (i % opt_disable_mod)) thread_data[i].reg = 1; else thread_data[i].reg = 0; thread_data[i].data = &data; ret = pthread_create(&test_threads[i], NULL, test_percpu_spinlock_thread, &thread_data[i]); if (ret) { errno = ret; perror("pthread_create"); abort(); } } for (i = 0; i < num_threads; i++) { ret = pthread_join(test_threads[i], NULL); if (ret) { errno = ret; perror("pthread_join"); abort(); } } sum = 0; for (i = 0; i < CPU_SETSIZE; i++) sum += data.c[i].count; assert(sum == (uint64_t)opt_reps * num_threads); } void *test_percpu_inc_thread(void *arg) { struct inc_thread_test_data *thread_data = arg; struct inc_test_data *data = thread_data->data; long long i, reps; if (!opt_disable_rseq && thread_data->reg && rseq_register_current_thread()) abort(); reps = thread_data->reps; for (i = 0; i < reps; i++) { int ret; do { int cpu; cpu = get_current_cpu_id(); ret = rseq_addv(RSEQ_MO_RELAXED, RSEQ_PERCPU, &data->c[cpu].count, 1, cpu); } while (rseq_unlikely(ret)); #ifndef BENCHMARK if (i != 0 && !(i % (reps / 10))) printf_verbose("tid %d: count %lld\n", (int) rseq_gettid(), i); #endif } printf_verbose("tid %d: number of rseq abort: %d, signals delivered: %u\n", (int) rseq_gettid(), nr_abort, signals_delivered); if (!opt_disable_rseq && thread_data->reg && rseq_unregister_current_thread()) abort(); return NULL; } void test_percpu_inc(void) { const int num_threads = opt_threads; int i, ret; uint64_t sum; pthread_t test_threads[num_threads]; struct inc_test_data data; struct inc_thread_test_data thread_data[num_threads]; memset(&data, 0, sizeof(data)); for (i = 0; i < num_threads; i++) { thread_data[i].reps = opt_reps; if (opt_disable_mod <= 0 || (i % opt_disable_mod)) thread_data[i].reg = 1; else thread_data[i].reg = 0; thread_data[i].data = &data; ret = pthread_create(&test_threads[i], NULL, test_percpu_inc_thread, &thread_data[i]); if (ret) { errno = ret; perror("pthread_create"); abort(); } } for (i = 0; i < num_threads; i++) { ret = pthread_join(test_threads[i], NULL); if (ret) { errno = ret; perror("pthread_join"); abort(); } } sum = 0; for (i = 0; i < CPU_SETSIZE; i++) sum += data.c[i].count; assert(sum == (uint64_t)opt_reps * num_threads); } void this_cpu_list_push(struct percpu_list *list, struct percpu_list_node *node, int *_cpu) { int cpu; for (;;) { intptr_t *targetptr, newval, expect; int ret; cpu = get_current_cpu_id(); /* Load list->c[cpu].head with single-copy atomicity. */ expect = (intptr_t)RSEQ_READ_ONCE(list->c[cpu].head); newval = (intptr_t)node; targetptr = (intptr_t *)&list->c[cpu].head; node->next = (struct percpu_list_node *)expect; ret = rseq_cmpeqv_storev(RSEQ_MO_RELAXED, RSEQ_PERCPU, targetptr, expect, newval, cpu); if (rseq_likely(!ret)) break; /* Retry if comparison fails or rseq aborts. */ } if (_cpu) *_cpu = cpu; } /* * Unlike a traditional lock-less linked list; the availability of a * rseq primitive allows us to implement pop without concerns over * ABA-type races. */ struct percpu_list_node *this_cpu_list_pop(struct percpu_list *list, int *_cpu) { struct percpu_list_node *node = NULL; int cpu; for (;;) { struct percpu_list_node *head; intptr_t *targetptr, expectnot, *load; long offset; int ret; cpu = get_current_cpu_id(); targetptr = (intptr_t *)&list->c[cpu].head; expectnot = (intptr_t)NULL; offset = offsetof(struct percpu_list_node, next); load = (intptr_t *)&head; ret = rseq_cmpnev_storeoffp_load(RSEQ_MO_RELAXED, RSEQ_PERCPU, targetptr, expectnot, offset, load, cpu); if (rseq_likely(!ret)) { node = head; break; } if (ret > 0) break; /* Retry if rseq aborts. */ } if (_cpu) *_cpu = cpu; return node; } /* * __percpu_list_pop is not safe against concurrent accesses. Should * only be used on lists that are not concurrently modified. */ struct percpu_list_node *__percpu_list_pop(struct percpu_list *list, int cpu) { struct percpu_list_node *node; node = list->c[cpu].head; if (!node) return NULL; list->c[cpu].head = node->next; return node; } void *test_percpu_list_thread(void *arg) { long long i, reps; struct percpu_list *list = (struct percpu_list *)arg; if (!opt_disable_rseq && rseq_register_current_thread()) abort(); reps = opt_reps; for (i = 0; i < reps; i++) { struct percpu_list_node *node; node = this_cpu_list_pop(list, NULL); if (opt_yield) sched_yield(); /* encourage shuffling */ if (node) this_cpu_list_push(list, node, NULL); } printf_verbose("tid %d: number of rseq abort: %d, signals delivered: %u\n", (int) rseq_gettid(), nr_abort, signals_delivered); if (!opt_disable_rseq && rseq_unregister_current_thread()) abort(); return NULL; } /* Simultaneous modification to a per-cpu linked list from many threads. */ void test_percpu_list(void) { const int num_threads = opt_threads; int i, j, ret; uint64_t sum = 0, expected_sum = 0; struct percpu_list list; pthread_t test_threads[num_threads]; cpu_set_t allowed_cpus; memset(&list, 0, sizeof(list)); /* Generate list entries for every usable cpu. */ sched_getaffinity(0, sizeof(allowed_cpus), &allowed_cpus); for (i = 0; i < CPU_SETSIZE; i++) { if (!CPU_ISSET(i, &allowed_cpus)) continue; for (j = 1; j <= 100; j++) { struct percpu_list_node *node; expected_sum += j; node = malloc(sizeof(*node)); assert(node); node->data = j; node->next = list.c[i].head; list.c[i].head = node; } } for (i = 0; i < num_threads; i++) { ret = pthread_create(&test_threads[i], NULL, test_percpu_list_thread, &list); if (ret) { errno = ret; perror("pthread_create"); abort(); } } for (i = 0; i < num_threads; i++) { ret = pthread_join(test_threads[i], NULL); if (ret) { errno = ret; perror("pthread_join"); abort(); } } for (i = 0; i < CPU_SETSIZE; i++) { struct percpu_list_node *node; if (!CPU_ISSET(i, &allowed_cpus)) continue; while ((node = __percpu_list_pop(&list, i))) { sum += node->data; free(node); } } /* * All entries should now be accounted for (unless some external * actor is interfering with our allowed affinity while this * test is running). */ assert(sum == expected_sum); } bool this_cpu_buffer_push(struct percpu_buffer *buffer, struct percpu_buffer_node *node, int *_cpu) { bool result = false; int cpu; for (;;) { intptr_t *targetptr_spec, newval_spec; intptr_t *targetptr_final, newval_final; intptr_t offset; int ret; cpu = get_current_cpu_id(); offset = RSEQ_READ_ONCE(buffer->c[cpu].offset); if (offset == buffer->c[cpu].buflen) break; newval_spec = (intptr_t)node; targetptr_spec = (intptr_t *)&buffer->c[cpu].array[offset]; newval_final = offset + 1; targetptr_final = &buffer->c[cpu].offset; ret = rseq_cmpeqv_trystorev_storev(opt_mo, RSEQ_PERCPU, targetptr_final, offset, targetptr_spec, newval_spec, newval_final, cpu); if (rseq_likely(!ret)) { result = true; break; } /* Retry if comparison fails or rseq aborts. */ } if (_cpu) *_cpu = cpu; return result; } struct percpu_buffer_node *this_cpu_buffer_pop(struct percpu_buffer *buffer, int *_cpu) { struct percpu_buffer_node *head; int cpu; for (;;) { intptr_t *targetptr, newval; intptr_t offset; int ret; cpu = get_current_cpu_id(); /* Load offset with single-copy atomicity. */ offset = RSEQ_READ_ONCE(buffer->c[cpu].offset); if (offset == 0) { head = NULL; break; } head = RSEQ_READ_ONCE(buffer->c[cpu].array[offset - 1]); newval = offset - 1; targetptr = (intptr_t *)&buffer->c[cpu].offset; ret = rseq_cmpeqv_cmpeqv_storev(RSEQ_MO_RELAXED, RSEQ_PERCPU, targetptr, offset, (intptr_t *)&buffer->c[cpu].array[offset - 1], (intptr_t)head, newval, cpu); if (rseq_likely(!ret)) break; /* Retry if comparison fails or rseq aborts. */ } if (_cpu) *_cpu = cpu; return head; } /* * __percpu_buffer_pop is not safe against concurrent accesses. Should * only be used on buffers that are not concurrently modified. */ struct percpu_buffer_node *__percpu_buffer_pop(struct percpu_buffer *buffer, int cpu) { struct percpu_buffer_node *head; intptr_t offset; offset = buffer->c[cpu].offset; if (offset == 0) return NULL; head = buffer->c[cpu].array[offset - 1]; buffer->c[cpu].offset = offset - 1; return head; } void *test_percpu_buffer_thread(void *arg) { long long i, reps; struct percpu_buffer *buffer = (struct percpu_buffer *)arg; if (!opt_disable_rseq && rseq_register_current_thread()) abort(); reps = opt_reps; for (i = 0; i < reps; i++) { struct percpu_buffer_node *node; node = this_cpu_buffer_pop(buffer, NULL); if (opt_yield) sched_yield(); /* encourage shuffling */ if (node) { if (!this_cpu_buffer_push(buffer, node, NULL)) { /* Should increase buffer size. */ abort(); } } } printf_verbose("tid %d: number of rseq abort: %d, signals delivered: %u\n", (int) rseq_gettid(), nr_abort, signals_delivered); if (!opt_disable_rseq && rseq_unregister_current_thread()) abort(); return NULL; } /* Simultaneous modification to a per-cpu buffer from many threads. */ void test_percpu_buffer(void) { const int num_threads = opt_threads; int i, j, ret; uint64_t sum = 0, expected_sum = 0; struct percpu_buffer buffer; pthread_t test_threads[num_threads]; cpu_set_t allowed_cpus; memset(&buffer, 0, sizeof(buffer)); /* Generate list entries for every usable cpu. */ sched_getaffinity(0, sizeof(allowed_cpus), &allowed_cpus); for (i = 0; i < CPU_SETSIZE; i++) { if (!CPU_ISSET(i, &allowed_cpus)) continue; /* Worse-case is every item in same CPU. */ buffer.c[i].array = malloc(sizeof(*buffer.c[i].array) * CPU_SETSIZE * BUFFER_ITEM_PER_CPU); assert(buffer.c[i].array); buffer.c[i].buflen = CPU_SETSIZE * BUFFER_ITEM_PER_CPU; for (j = 1; j <= BUFFER_ITEM_PER_CPU; j++) { struct percpu_buffer_node *node; expected_sum += j; /* * We could theoretically put the word-sized * "data" directly in the buffer. However, we * want to model objects that would not fit * within a single word, so allocate an object * for each node. */ node = malloc(sizeof(*node)); assert(node); node->data = j; buffer.c[i].array[j - 1] = node; buffer.c[i].offset++; } } for (i = 0; i < num_threads; i++) { ret = pthread_create(&test_threads[i], NULL, test_percpu_buffer_thread, &buffer); if (ret) { errno = ret; perror("pthread_create"); abort(); } } for (i = 0; i < num_threads; i++) { ret = pthread_join(test_threads[i], NULL); if (ret) { errno = ret; perror("pthread_join"); abort(); } } for (i = 0; i < CPU_SETSIZE; i++) { struct percpu_buffer_node *node; if (!CPU_ISSET(i, &allowed_cpus)) continue; while ((node = __percpu_buffer_pop(&buffer, i))) { sum += node->data; free(node); } free(buffer.c[i].array); } /* * All entries should now be accounted for (unless some external * actor is interfering with our allowed affinity while this * test is running). */ assert(sum == expected_sum); } bool this_cpu_memcpy_buffer_push(struct percpu_memcpy_buffer *buffer, struct percpu_memcpy_buffer_node item, int *_cpu) { bool result = false; int cpu; for (;;) { intptr_t *targetptr_final, newval_final, offset; char *destptr, *srcptr; size_t copylen; int ret; cpu = get_current_cpu_id(); /* Load offset with single-copy atomicity. */ offset = RSEQ_READ_ONCE(buffer->c[cpu].offset); if (offset == buffer->c[cpu].buflen) break; destptr = (char *)&buffer->c[cpu].array[offset]; srcptr = (char *)&item; /* copylen must be <= 4kB. */ copylen = sizeof(item); newval_final = offset + 1; targetptr_final = &buffer->c[cpu].offset; ret = rseq_cmpeqv_trymemcpy_storev( opt_mo, RSEQ_PERCPU, targetptr_final, offset, destptr, srcptr, copylen, newval_final, cpu); if (rseq_likely(!ret)) { result = true; break; } /* Retry if comparison fails or rseq aborts. */ } if (_cpu) *_cpu = cpu; return result; } bool this_cpu_memcpy_buffer_pop(struct percpu_memcpy_buffer *buffer, struct percpu_memcpy_buffer_node *item, int *_cpu) { bool result = false; int cpu; for (;;) { intptr_t *targetptr_final, newval_final, offset; char *destptr, *srcptr; size_t copylen; int ret; cpu = get_current_cpu_id(); /* Load offset with single-copy atomicity. */ offset = RSEQ_READ_ONCE(buffer->c[cpu].offset); if (offset == 0) break; destptr = (char *)item; srcptr = (char *)&buffer->c[cpu].array[offset - 1]; /* copylen must be <= 4kB. */ copylen = sizeof(*item); newval_final = offset - 1; targetptr_final = &buffer->c[cpu].offset; ret = rseq_cmpeqv_trymemcpy_storev(RSEQ_MO_RELAXED, RSEQ_PERCPU, targetptr_final, offset, destptr, srcptr, copylen, newval_final, cpu); if (rseq_likely(!ret)) { result = true; break; } /* Retry if comparison fails or rseq aborts. */ } if (_cpu) *_cpu = cpu; return result; } /* * __percpu_memcpy_buffer_pop is not safe against concurrent accesses. Should * only be used on buffers that are not concurrently modified. */ bool __percpu_memcpy_buffer_pop(struct percpu_memcpy_buffer *buffer, struct percpu_memcpy_buffer_node *item, int cpu) { intptr_t offset; offset = buffer->c[cpu].offset; if (offset == 0) return false; memcpy(item, &buffer->c[cpu].array[offset - 1], sizeof(*item)); buffer->c[cpu].offset = offset - 1; return true; } void *test_percpu_memcpy_buffer_thread(void *arg) { long long i, reps; struct percpu_memcpy_buffer *buffer = (struct percpu_memcpy_buffer *)arg; if (!opt_disable_rseq && rseq_register_current_thread()) abort(); reps = opt_reps; for (i = 0; i < reps; i++) { struct percpu_memcpy_buffer_node item; bool result; result = this_cpu_memcpy_buffer_pop(buffer, &item, NULL); if (opt_yield) sched_yield(); /* encourage shuffling */ if (result) { if (!this_cpu_memcpy_buffer_push(buffer, item, NULL)) { /* Should increase buffer size. */ abort(); } } } printf_verbose("tid %d: number of rseq abort: %d, signals delivered: %u\n", (int) rseq_gettid(), nr_abort, signals_delivered); if (!opt_disable_rseq && rseq_unregister_current_thread()) abort(); return NULL; } /* Simultaneous modification to a per-cpu buffer from many threads. */ void test_percpu_memcpy_buffer(void) { const int num_threads = opt_threads; int i, j, ret; uint64_t sum = 0, expected_sum = 0; struct percpu_memcpy_buffer buffer; pthread_t test_threads[num_threads]; cpu_set_t allowed_cpus; memset(&buffer, 0, sizeof(buffer)); /* Generate list entries for every usable cpu. */ sched_getaffinity(0, sizeof(allowed_cpus), &allowed_cpus); for (i = 0; i < CPU_SETSIZE; i++) { if (!CPU_ISSET(i, &allowed_cpus)) continue; /* Worse-case is every item in same CPU. */ buffer.c[i].array = malloc(sizeof(*buffer.c[i].array) * CPU_SETSIZE * MEMCPY_BUFFER_ITEM_PER_CPU); assert(buffer.c[i].array); buffer.c[i].buflen = CPU_SETSIZE * MEMCPY_BUFFER_ITEM_PER_CPU; for (j = 1; j <= MEMCPY_BUFFER_ITEM_PER_CPU; j++) { expected_sum += 2 * j + 1; /* * We could theoretically put the word-sized * "data" directly in the buffer. However, we * want to model objects that would not fit * within a single word, so allocate an object * for each node. */ buffer.c[i].array[j - 1].data1 = j; buffer.c[i].array[j - 1].data2 = j + 1; buffer.c[i].offset++; } } for (i = 0; i < num_threads; i++) { ret = pthread_create(&test_threads[i], NULL, test_percpu_memcpy_buffer_thread, &buffer); if (ret) { errno = ret; perror("pthread_create"); abort(); } } for (i = 0; i < num_threads; i++) { ret = pthread_join(test_threads[i], NULL); if (ret) { errno = ret; perror("pthread_join"); abort(); } } for (i = 0; i < CPU_SETSIZE; i++) { struct percpu_memcpy_buffer_node item; if (!CPU_ISSET(i, &allowed_cpus)) continue; while (__percpu_memcpy_buffer_pop(&buffer, &item, i)) { sum += item.data1; sum += item.data2; } free(buffer.c[i].array); } /* * All entries should now be accounted for (unless some external * actor is interfering with our allowed affinity while this * test is running). */ assert(sum == expected_sum); } static void test_signal_interrupt_handler(int signo) { signals_delivered++; } static int set_signal_handler(void) { int ret = 0; struct sigaction sa; sigset_t sigset; ret = sigemptyset(&sigset); if (ret < 0) { perror("sigemptyset"); return ret; } sa.sa_handler = test_signal_interrupt_handler; sa.sa_mask = sigset; sa.sa_flags = 0; ret = sigaction(SIGUSR1, &sa, NULL); if (ret < 0) { perror("sigaction"); return ret; } printf_verbose("Signal handler set for SIGUSR1\n"); return ret; } /* Test MEMBARRIER_CMD_PRIVATE_RESTART_RSEQ_ON_CPU membarrier command. */ #ifdef TEST_MEMBARRIER struct test_membarrier_thread_args { int stop; intptr_t percpu_list_ptr; }; /* Worker threads modify data in their "active" percpu lists. */ void *test_membarrier_worker_thread(void *arg) { struct test_membarrier_thread_args *args = (struct test_membarrier_thread_args *)arg; const int iters = opt_reps; int i; if (rseq_register_current_thread()) { fprintf(stderr, "Error: rseq_register_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); abort(); } /* Wait for initialization. */ while (!atomic_load(&args->percpu_list_ptr)) {} for (i = 0; i < iters; ++i) { int ret; do { int cpu = get_current_cpu_id(); ret = rseq_offset_deref_addv(RSEQ_MO_RELAXED, RSEQ_PERCPU, &args->percpu_list_ptr, sizeof(struct percpu_list_entry) * cpu, 1, cpu); } while (rseq_unlikely(ret)); } if (rseq_unregister_current_thread()) { fprintf(stderr, "Error: rseq_unregister_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); abort(); } return NULL; } void test_membarrier_init_percpu_list(struct percpu_list *list) { int i; memset(list, 0, sizeof(*list)); for (i = 0; i < CPU_SETSIZE; i++) { struct percpu_list_node *node; node = malloc(sizeof(*node)); assert(node); node->data = 0; node->next = NULL; list->c[i].head = node; } } void test_membarrier_free_percpu_list(struct percpu_list *list) { int i; for (i = 0; i < CPU_SETSIZE; i++) free(list->c[i].head); } /* * The manager thread swaps per-cpu lists that worker threads see, * and validates that there are no unexpected modifications. */ void *test_membarrier_manager_thread(void *arg) { struct test_membarrier_thread_args *args = (struct test_membarrier_thread_args *)arg; struct percpu_list list_a, list_b; intptr_t expect_a = 0, expect_b = 0; int cpu_a = 0, cpu_b = 0; if (rseq_register_current_thread()) { fprintf(stderr, "Error: rseq_register_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); abort(); } /* Init lists. */ test_membarrier_init_percpu_list(&list_a); test_membarrier_init_percpu_list(&list_b); atomic_store(&args->percpu_list_ptr, (intptr_t)&list_a); while (!atomic_load(&args->stop)) { /* list_a is "active". */ cpu_a = rand() % CPU_SETSIZE; /* * As list_b is "inactive", we should never see changes * to list_b. */ if (expect_b != atomic_load(&list_b.c[cpu_b].head->data)) { fprintf(stderr, "Membarrier test failed\n"); abort(); } /* Make list_b "active". */ atomic_store(&args->percpu_list_ptr, (intptr_t)&list_b); if (rseq_membarrier_expedited(cpu_a) && errno != ENXIO /* missing CPU */) { perror("sys_membarrier"); abort(); } /* * Cpu A should now only modify list_b, so the values * in list_a should be stable. */ expect_a = atomic_load(&list_a.c[cpu_a].head->data); cpu_b = rand() % CPU_SETSIZE; /* * As list_a is "inactive", we should never see changes * to list_a. */ if (expect_a != atomic_load(&list_a.c[cpu_a].head->data)) { fprintf(stderr, "Membarrier test failed\n"); abort(); } /* Make list_a "active". */ atomic_store(&args->percpu_list_ptr, (intptr_t)&list_a); if (rseq_membarrier_expedited(cpu_b) && errno != ENXIO /* missing CPU*/) { perror("sys_membarrier"); abort(); } /* Remember a value from list_b. */ expect_b = atomic_load(&list_b.c[cpu_b].head->data); } test_membarrier_free_percpu_list(&list_a); test_membarrier_free_percpu_list(&list_b); if (rseq_unregister_current_thread()) { fprintf(stderr, "Error: rseq_unregister_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); abort(); } return NULL; } void test_membarrier(void) { const int num_threads = opt_threads; struct test_membarrier_thread_args thread_args; pthread_t worker_threads[num_threads]; pthread_t manager_thread; int i, ret; if (sys_membarrier(MEMBARRIER_CMD_REGISTER_PRIVATE_EXPEDITED_RSEQ, 0, 0)) { perror("sys_membarrier"); abort(); } thread_args.stop = 0; thread_args.percpu_list_ptr = 0; ret = pthread_create(&manager_thread, NULL, test_membarrier_manager_thread, &thread_args); if (ret) { errno = ret; perror("pthread_create"); abort(); } for (i = 0; i < num_threads; i++) { ret = pthread_create(&worker_threads[i], NULL, test_membarrier_worker_thread, &thread_args); if (ret) { errno = ret; perror("pthread_create"); abort(); } } for (i = 0; i < num_threads; i++) { ret = pthread_join(worker_threads[i], NULL); if (ret) { errno = ret; perror("pthread_join"); abort(); } } atomic_store(&thread_args.stop, 1); ret = pthread_join(manager_thread, NULL); if (ret) { errno = ret; perror("pthread_join"); abort(); } } #else /* TEST_MEMBARRIER */ void test_membarrier(void) { fprintf(stderr, "rseq_offset_deref_addv is not implemented on this architecture. " "Skipping membarrier test.\n"); } #endif static void show_usage(int argc, char **argv) { printf("Usage : %s <OPTIONS>\n", argv[0]); printf("OPTIONS:\n"); printf(" [-1 loops] Number of loops for delay injection 1\n"); printf(" [-2 loops] Number of loops for delay injection 2\n"); printf(" [-3 loops] Number of loops for delay injection 3\n"); printf(" [-4 loops] Number of loops for delay injection 4\n"); printf(" [-5 loops] Number of loops for delay injection 5\n"); printf(" [-6 loops] Number of loops for delay injection 6\n"); printf(" [-7 loops] Number of loops for delay injection 7 (-1 to enable -m)\n"); printf(" [-8 loops] Number of loops for delay injection 8 (-1 to enable -m)\n"); printf(" [-9 loops] Number of loops for delay injection 9 (-1 to enable -m)\n"); printf(" [-m N] Yield/sleep/kill every modulo N (default 0: disabled) (>= 0)\n"); printf(" [-y] Yield\n"); printf(" [-k] Kill thread with signal\n"); printf(" [-s S] S: =0: disabled (default), >0: sleep time (ms)\n"); printf(" [-t N] Number of threads (default 200)\n"); printf(" [-r N] Number of repetitions per thread (default 5000)\n"); printf(" [-d] Disable rseq system call (no initialization)\n"); printf(" [-D M] Disable rseq for each M threads\n"); printf(" [-T test] Choose test: (s)pinlock, (l)ist, (b)uffer, (m)emcpy, (i)ncrement, membarrie(r)\n"); printf(" [-M] Push into buffer and memcpy buffer with memory barriers.\n"); printf(" [-v] Verbose output.\n"); printf(" [-h] Show this help.\n"); printf("\n"); } int main(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (argv[i][0] != '-') continue; switch (argv[i][1]) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (argc < i + 2) { show_usage(argc, argv); goto error; } loop_cnt[argv[i][1] - '0'] = atol(argv[i + 1]); i++; break; case 'm': if (argc < i + 2) { show_usage(argc, argv); goto error; } opt_modulo = atol(argv[i + 1]); if (opt_modulo < 0) { show_usage(argc, argv); goto error; } i++; break; case 's': if (argc < i + 2) { show_usage(argc, argv); goto error; } opt_sleep = atol(argv[i + 1]); if (opt_sleep < 0) { show_usage(argc, argv); goto error; } i++; break; case 'y': opt_yield = 1; break; case 'k': opt_signal = 1; break; case 'd': opt_disable_rseq = 1; break; case 'D': if (argc < i + 2) { show_usage(argc, argv); goto error; } opt_disable_mod = atol(argv[i + 1]); if (opt_disable_mod < 0) { show_usage(argc, argv); goto error; } i++; break; case 't': if (argc < i + 2) { show_usage(argc, argv); goto error; } opt_threads = atol(argv[i + 1]); if (opt_threads < 0) { show_usage(argc, argv); goto error; } i++; break; case 'r': if (argc < i + 2) { show_usage(argc, argv); goto error; } opt_reps = atoll(argv[i + 1]); if (opt_reps < 0) { show_usage(argc, argv); goto error; } i++; break; case 'h': show_usage(argc, argv); goto end; case 'T': if (argc < i + 2) { show_usage(argc, argv); goto error; } opt_test = *argv[i + 1]; switch (opt_test) { case 's': case 'l': case 'i': case 'b': case 'm': case 'r': break; default: show_usage(argc, argv); goto error; } i++; break; case 'v': verbose = 1; break; case 'M': opt_mo = RSEQ_MO_RELEASE; break; default: show_usage(argc, argv); goto error; } } loop_cnt_1 = loop_cnt[1]; loop_cnt_2 = loop_cnt[2]; loop_cnt_3 = loop_cnt[3]; loop_cnt_4 = loop_cnt[4]; loop_cnt_5 = loop_cnt[5]; loop_cnt_6 = loop_cnt[6]; if (set_signal_handler()) goto error; if (!opt_disable_rseq && rseq_register_current_thread()) goto error; if (!opt_disable_rseq && !rseq_validate_cpu_id()) { fprintf(stderr, "Error: cpu id getter unavailable\n"); goto error; } switch (opt_test) { case 's': printf_verbose("spinlock\n"); test_percpu_spinlock(); break; case 'l': printf_verbose("linked list\n"); test_percpu_list(); break; case 'b': printf_verbose("buffer\n"); test_percpu_buffer(); break; case 'm': printf_verbose("memcpy buffer\n"); test_percpu_memcpy_buffer(); break; case 'i': printf_verbose("counter increment\n"); test_percpu_inc(); break; case 'r': printf_verbose("membarrier\n"); test_membarrier(); break; } if (!opt_disable_rseq && rseq_unregister_current_thread()) abort(); end: return 0; error: return -1; }
linux-master
tools/testing/selftests/rseq/param_test.c
// SPDX-License-Identifier: LGPL-2.1 #define _GNU_SOURCE #include <assert.h> #include <pthread.h> #include <sched.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include "../kselftest.h" #include "rseq.h" #ifdef BUILDOPT_RSEQ_PERCPU_MM_CID # define RSEQ_PERCPU RSEQ_PERCPU_MM_CID static int get_current_cpu_id(void) { return rseq_current_mm_cid(); } static bool rseq_validate_cpu_id(void) { return rseq_mm_cid_available(); } #else # define RSEQ_PERCPU RSEQ_PERCPU_CPU_ID static int get_current_cpu_id(void) { return rseq_cpu_start(); } static bool rseq_validate_cpu_id(void) { return rseq_current_cpu_raw() >= 0; } #endif struct percpu_lock_entry { intptr_t v; } __attribute__((aligned(128))); struct percpu_lock { struct percpu_lock_entry c[CPU_SETSIZE]; }; struct test_data_entry { intptr_t count; } __attribute__((aligned(128))); struct spinlock_test_data { struct percpu_lock lock; struct test_data_entry c[CPU_SETSIZE]; int reps; }; struct percpu_list_node { intptr_t data; struct percpu_list_node *next; }; struct percpu_list_entry { struct percpu_list_node *head; } __attribute__((aligned(128))); struct percpu_list { struct percpu_list_entry c[CPU_SETSIZE]; }; /* A simple percpu spinlock. Returns the cpu lock was acquired on. */ int rseq_this_cpu_lock(struct percpu_lock *lock) { int cpu; for (;;) { int ret; cpu = get_current_cpu_id(); ret = rseq_cmpeqv_storev(RSEQ_MO_RELAXED, RSEQ_PERCPU, &lock->c[cpu].v, 0, 1, cpu); if (rseq_likely(!ret)) break; /* Retry if comparison fails or rseq aborts. */ } /* * Acquire semantic when taking lock after control dependency. * Matches rseq_smp_store_release(). */ rseq_smp_acquire__after_ctrl_dep(); return cpu; } void rseq_percpu_unlock(struct percpu_lock *lock, int cpu) { assert(lock->c[cpu].v == 1); /* * Release lock, with release semantic. Matches * rseq_smp_acquire__after_ctrl_dep(). */ rseq_smp_store_release(&lock->c[cpu].v, 0); } void *test_percpu_spinlock_thread(void *arg) { struct spinlock_test_data *data = arg; int i, cpu; if (rseq_register_current_thread()) { fprintf(stderr, "Error: rseq_register_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); abort(); } for (i = 0; i < data->reps; i++) { cpu = rseq_this_cpu_lock(&data->lock); data->c[cpu].count++; rseq_percpu_unlock(&data->lock, cpu); } if (rseq_unregister_current_thread()) { fprintf(stderr, "Error: rseq_unregister_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); abort(); } return NULL; } /* * A simple test which implements a sharded counter using a per-cpu * lock. Obviously real applications might prefer to simply use a * per-cpu increment; however, this is reasonable for a test and the * lock can be extended to synchronize more complicated operations. */ void test_percpu_spinlock(void) { const int num_threads = 200; int i; uint64_t sum; pthread_t test_threads[num_threads]; struct spinlock_test_data data; memset(&data, 0, sizeof(data)); data.reps = 5000; for (i = 0; i < num_threads; i++) pthread_create(&test_threads[i], NULL, test_percpu_spinlock_thread, &data); for (i = 0; i < num_threads; i++) pthread_join(test_threads[i], NULL); sum = 0; for (i = 0; i < CPU_SETSIZE; i++) sum += data.c[i].count; assert(sum == (uint64_t)data.reps * num_threads); } void this_cpu_list_push(struct percpu_list *list, struct percpu_list_node *node, int *_cpu) { int cpu; for (;;) { intptr_t *targetptr, newval, expect; int ret; cpu = get_current_cpu_id(); /* Load list->c[cpu].head with single-copy atomicity. */ expect = (intptr_t)RSEQ_READ_ONCE(list->c[cpu].head); newval = (intptr_t)node; targetptr = (intptr_t *)&list->c[cpu].head; node->next = (struct percpu_list_node *)expect; ret = rseq_cmpeqv_storev(RSEQ_MO_RELAXED, RSEQ_PERCPU, targetptr, expect, newval, cpu); if (rseq_likely(!ret)) break; /* Retry if comparison fails or rseq aborts. */ } if (_cpu) *_cpu = cpu; } /* * Unlike a traditional lock-less linked list; the availability of a * rseq primitive allows us to implement pop without concerns over * ABA-type races. */ struct percpu_list_node *this_cpu_list_pop(struct percpu_list *list, int *_cpu) { for (;;) { struct percpu_list_node *head; intptr_t *targetptr, expectnot, *load; long offset; int ret, cpu; cpu = get_current_cpu_id(); targetptr = (intptr_t *)&list->c[cpu].head; expectnot = (intptr_t)NULL; offset = offsetof(struct percpu_list_node, next); load = (intptr_t *)&head; ret = rseq_cmpnev_storeoffp_load(RSEQ_MO_RELAXED, RSEQ_PERCPU, targetptr, expectnot, offset, load, cpu); if (rseq_likely(!ret)) { if (_cpu) *_cpu = cpu; return head; } if (ret > 0) return NULL; /* Retry if rseq aborts. */ } } /* * __percpu_list_pop is not safe against concurrent accesses. Should * only be used on lists that are not concurrently modified. */ struct percpu_list_node *__percpu_list_pop(struct percpu_list *list, int cpu) { struct percpu_list_node *node; node = list->c[cpu].head; if (!node) return NULL; list->c[cpu].head = node->next; return node; } void *test_percpu_list_thread(void *arg) { int i; struct percpu_list *list = (struct percpu_list *)arg; if (rseq_register_current_thread()) { fprintf(stderr, "Error: rseq_register_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); abort(); } for (i = 0; i < 100000; i++) { struct percpu_list_node *node; node = this_cpu_list_pop(list, NULL); sched_yield(); /* encourage shuffling */ if (node) this_cpu_list_push(list, node, NULL); } if (rseq_unregister_current_thread()) { fprintf(stderr, "Error: rseq_unregister_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); abort(); } return NULL; } /* Simultaneous modification to a per-cpu linked list from many threads. */ void test_percpu_list(void) { int i, j; uint64_t sum = 0, expected_sum = 0; struct percpu_list list; pthread_t test_threads[200]; cpu_set_t allowed_cpus; memset(&list, 0, sizeof(list)); /* Generate list entries for every usable cpu. */ sched_getaffinity(0, sizeof(allowed_cpus), &allowed_cpus); for (i = 0; i < CPU_SETSIZE; i++) { if (!CPU_ISSET(i, &allowed_cpus)) continue; for (j = 1; j <= 100; j++) { struct percpu_list_node *node; expected_sum += j; node = malloc(sizeof(*node)); assert(node); node->data = j; node->next = list.c[i].head; list.c[i].head = node; } } for (i = 0; i < 200; i++) pthread_create(&test_threads[i], NULL, test_percpu_list_thread, &list); for (i = 0; i < 200; i++) pthread_join(test_threads[i], NULL); for (i = 0; i < CPU_SETSIZE; i++) { struct percpu_list_node *node; if (!CPU_ISSET(i, &allowed_cpus)) continue; while ((node = __percpu_list_pop(&list, i))) { sum += node->data; free(node); } } /* * All entries should now be accounted for (unless some external * actor is interfering with our allowed affinity while this * test is running). */ assert(sum == expected_sum); } int main(int argc, char **argv) { if (rseq_register_current_thread()) { fprintf(stderr, "Error: rseq_register_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); goto error; } if (!rseq_validate_cpu_id()) { fprintf(stderr, "Error: cpu id getter unavailable\n"); goto error; } printf("spinlock\n"); test_percpu_spinlock(); printf("percpu_list\n"); test_percpu_list(); if (rseq_unregister_current_thread()) { fprintf(stderr, "Error: rseq_unregister_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); goto error; } return 0; error: return -1; }
linux-master
tools/testing/selftests/rseq/basic_percpu_ops_test.c
// SPDX-License-Identifier: LGPL-2.1 /* * Basic test coverage for critical regions and rseq_current_cpu(). */ #define _GNU_SOURCE #include <assert.h> #include <sched.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <sys/time.h> #include "rseq.h" void test_cpu_pointer(void) { cpu_set_t affinity, test_affinity; int i; sched_getaffinity(0, sizeof(affinity), &affinity); CPU_ZERO(&test_affinity); for (i = 0; i < CPU_SETSIZE; i++) { if (CPU_ISSET(i, &affinity)) { int node; CPU_SET(i, &test_affinity); sched_setaffinity(0, sizeof(test_affinity), &test_affinity); assert(sched_getcpu() == i); assert(rseq_current_cpu() == i); assert(rseq_current_cpu_raw() == i); assert(rseq_cpu_start() == i); node = rseq_fallback_current_node(); assert(rseq_current_node_id() == node); CPU_CLR(i, &test_affinity); } } sched_setaffinity(0, sizeof(affinity), &affinity); } int main(int argc, char **argv) { if (rseq_register_current_thread()) { fprintf(stderr, "Error: rseq_register_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); goto init_thread_error; } printf("testing current cpu\n"); test_cpu_pointer(); if (rseq_unregister_current_thread()) { fprintf(stderr, "Error: rseq_unregister_current_thread(...) failed(%d): %s\n", errno, strerror(errno)); goto init_thread_error; } return 0; init_thread_error: return -1; }
linux-master
tools/testing/selftests/rseq/basic_test.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <stdio.h> #include <errno.h> #include <pwd.h> #include <grp.h> #include <string.h> #include <syscall.h> #include <sys/capability.h> #include <sys/types.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/wait.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <stdbool.h> #include <stdarg.h> /* * NOTES about this test: * - requries libcap-dev to be installed on test system * - requires securityfs to me mounted at /sys/kernel/security, e.g.: * mount -n -t securityfs -o nodev,noexec,nosuid securityfs /sys/kernel/security * - needs CONFIG_SECURITYFS and CONFIG_SAFESETID to be enabled */ #ifndef CLONE_NEWUSER # define CLONE_NEWUSER 0x10000000 #endif #define ROOT_UGID 0 #define RESTRICTED_PARENT_UGID 1 #define ALLOWED_CHILD1_UGID 2 #define ALLOWED_CHILD2_UGID 3 #define NO_POLICY_UGID 4 #define UGID_POLICY_STRING "1:2\n1:3\n2:2\n3:3\n" char* add_uid_whitelist_policy_file = "/sys/kernel/security/safesetid/uid_allowlist_policy"; char* add_gid_whitelist_policy_file = "/sys/kernel/security/safesetid/gid_allowlist_policy"; static void die(char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); exit(EXIT_FAILURE); } static bool vmaybe_write_file(bool enoent_ok, char *filename, char *fmt, va_list ap) { char buf[4096]; int fd; ssize_t written; int buf_len; buf_len = vsnprintf(buf, sizeof(buf), fmt, ap); if (buf_len < 0) { printf("vsnprintf failed: %s\n", strerror(errno)); return false; } if (buf_len >= sizeof(buf)) { printf("vsnprintf output truncated\n"); return false; } fd = open(filename, O_WRONLY); if (fd < 0) { if ((errno == ENOENT) && enoent_ok) return true; return false; } written = write(fd, buf, buf_len); if (written != buf_len) { if (written >= 0) { printf("short write to %s\n", filename); return false; } else { printf("write to %s failed: %s\n", filename, strerror(errno)); return false; } } if (close(fd) != 0) { printf("close of %s failed: %s\n", filename, strerror(errno)); return false; } return true; } static bool write_file(char *filename, char *fmt, ...) { va_list ap; bool ret; va_start(ap, fmt); ret = vmaybe_write_file(false, filename, fmt, ap); va_end(ap); return ret; } static void ensure_user_exists(uid_t uid) { struct passwd p; FILE *fd; char name_str[10]; if (getpwuid(uid) == NULL) { memset(&p,0x00,sizeof(p)); fd=fopen("/etc/passwd","a"); if (fd == NULL) die("couldn't open file\n"); if (fseek(fd, 0, SEEK_END)) die("couldn't fseek\n"); snprintf(name_str, 10, "user %d", uid); p.pw_name=name_str; p.pw_uid=uid; p.pw_gid=uid; p.pw_gecos="Test account"; p.pw_dir="/dev/null"; p.pw_shell="/bin/false"; int value = putpwent(&p,fd); if (value != 0) die("putpwent failed\n"); if (fclose(fd)) die("fclose failed\n"); } } static void ensure_group_exists(gid_t gid) { struct group g; FILE *fd; char name_str[10]; if (getgrgid(gid) == NULL) { memset(&g,0x00,sizeof(g)); fd=fopen("/etc/group","a"); if (fd == NULL) die("couldn't open group file\n"); if (fseek(fd, 0, SEEK_END)) die("couldn't fseek group file\n"); snprintf(name_str, 10, "group %d", gid); g.gr_name=name_str; g.gr_gid=gid; g.gr_passwd=NULL; g.gr_mem=NULL; int value = putgrent(&g,fd); if (value != 0) die("putgrent failed\n"); if (fclose(fd)) die("fclose failed\n"); } } static void ensure_securityfs_mounted(void) { int fd = open(add_uid_whitelist_policy_file, O_WRONLY); if (fd < 0) { if (errno == ENOENT) { // Need to mount securityfs if (mount("securityfs", "/sys/kernel/security", "securityfs", 0, NULL) < 0) die("mounting securityfs failed\n"); } else { die("couldn't find securityfs for unknown reason\n"); } } else { if (close(fd) != 0) { die("close of %s failed: %s\n", add_uid_whitelist_policy_file, strerror(errno)); } } } static void write_uid_policies() { static char *policy_str = UGID_POLICY_STRING; ssize_t written; int fd; fd = open(add_uid_whitelist_policy_file, O_WRONLY); if (fd < 0) die("can't open add_uid_whitelist_policy file\n"); written = write(fd, policy_str, strlen(policy_str)); if (written != strlen(policy_str)) { if (written >= 0) { die("short write to %s\n", add_uid_whitelist_policy_file); } else { die("write to %s failed: %s\n", add_uid_whitelist_policy_file, strerror(errno)); } } if (close(fd) != 0) { die("close of %s failed: %s\n", add_uid_whitelist_policy_file, strerror(errno)); } } static void write_gid_policies() { static char *policy_str = UGID_POLICY_STRING; ssize_t written; int fd; fd = open(add_gid_whitelist_policy_file, O_WRONLY); if (fd < 0) die("can't open add_gid_whitelist_policy file\n"); written = write(fd, policy_str, strlen(policy_str)); if (written != strlen(policy_str)) { if (written >= 0) { die("short write to %s\n", add_gid_whitelist_policy_file); } else { die("write to %s failed: %s\n", add_gid_whitelist_policy_file, strerror(errno)); } } if (close(fd) != 0) { die("close of %s failed: %s\n", add_gid_whitelist_policy_file, strerror(errno)); } } static bool test_userns(bool expect_success) { uid_t uid; char map_file_name[32]; size_t sz = sizeof(map_file_name); pid_t cpid; bool success; uid = getuid(); int clone_flags = CLONE_NEWUSER; cpid = syscall(SYS_clone, clone_flags, NULL); if (cpid == -1) { printf("clone failed"); return false; } if (cpid == 0) { /* Code executed by child */ // Give parent 1 second to write map file sleep(1); exit(EXIT_SUCCESS); } else { /* Code executed by parent */ if(snprintf(map_file_name, sz, "/proc/%d/uid_map", cpid) < 0) { printf("preparing file name string failed"); return false; } success = write_file(map_file_name, "0 %d 1", uid); return success == expect_success; } printf("should not reach here"); return false; } static void test_setuid(uid_t child_uid, bool expect_success) { pid_t cpid, w; int wstatus; cpid = fork(); if (cpid == -1) { die("fork\n"); } if (cpid == 0) { /* Code executed by child */ if (setuid(child_uid) < 0) exit(EXIT_FAILURE); if (getuid() == child_uid) exit(EXIT_SUCCESS); else exit(EXIT_FAILURE); } else { /* Code executed by parent */ do { w = waitpid(cpid, &wstatus, WUNTRACED | WCONTINUED); if (w == -1) { die("waitpid\n"); } if (WIFEXITED(wstatus)) { if (WEXITSTATUS(wstatus) == EXIT_SUCCESS) { if (expect_success) { return; } else { die("unexpected success\n"); } } else { if (expect_success) { die("unexpected failure\n"); } else { return; } } } else if (WIFSIGNALED(wstatus)) { if (WTERMSIG(wstatus) == 9) { if (expect_success) die("killed unexpectedly\n"); else return; } else { die("unexpected signal: %d\n", wstatus); } } else { die("unexpected status: %d\n", wstatus); } } while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus)); } die("should not reach here\n"); } static void test_setgid(gid_t child_gid, bool expect_success) { pid_t cpid, w; int wstatus; cpid = fork(); if (cpid == -1) { die("fork\n"); } if (cpid == 0) { /* Code executed by child */ if (setgid(child_gid) < 0) exit(EXIT_FAILURE); if (getgid() == child_gid) exit(EXIT_SUCCESS); else exit(EXIT_FAILURE); } else { /* Code executed by parent */ do { w = waitpid(cpid, &wstatus, WUNTRACED | WCONTINUED); if (w == -1) { die("waitpid\n"); } if (WIFEXITED(wstatus)) { if (WEXITSTATUS(wstatus) == EXIT_SUCCESS) { if (expect_success) { return; } else { die("unexpected success\n"); } } else { if (expect_success) { die("unexpected failure\n"); } else { return; } } } else if (WIFSIGNALED(wstatus)) { if (WTERMSIG(wstatus) == 9) { if (expect_success) die("killed unexpectedly\n"); else return; } else { die("unexpected signal: %d\n", wstatus); } } else { die("unexpected status: %d\n", wstatus); } } while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus)); } die("should not reach here\n"); } static void test_setgroups(gid_t* child_groups, size_t len, bool expect_success) { pid_t cpid, w; int wstatus; gid_t groupset[len]; int i, j; cpid = fork(); if (cpid == -1) { die("fork\n"); } if (cpid == 0) { /* Code executed by child */ if (setgroups(len, child_groups) != 0) exit(EXIT_FAILURE); if (getgroups(len, groupset) != len) exit(EXIT_FAILURE); for (i = 0; i < len; i++) { for (j = 0; j < len; j++) { if (child_groups[i] == groupset[j]) break; if (j == len - 1) exit(EXIT_FAILURE); } } exit(EXIT_SUCCESS); } else { /* Code executed by parent */ do { w = waitpid(cpid, &wstatus, WUNTRACED | WCONTINUED); if (w == -1) { die("waitpid\n"); } if (WIFEXITED(wstatus)) { if (WEXITSTATUS(wstatus) == EXIT_SUCCESS) { if (expect_success) { return; } else { die("unexpected success\n"); } } else { if (expect_success) { die("unexpected failure\n"); } else { return; } } } else if (WIFSIGNALED(wstatus)) { if (WTERMSIG(wstatus) == 9) { if (expect_success) die("killed unexpectedly\n"); else return; } else { die("unexpected signal: %d\n", wstatus); } } else { die("unexpected status: %d\n", wstatus); } } while (!WIFEXITED(wstatus) && !WIFSIGNALED(wstatus)); } die("should not reach here\n"); } static void ensure_users_exist(void) { ensure_user_exists(ROOT_UGID); ensure_user_exists(RESTRICTED_PARENT_UGID); ensure_user_exists(ALLOWED_CHILD1_UGID); ensure_user_exists(ALLOWED_CHILD2_UGID); ensure_user_exists(NO_POLICY_UGID); } static void ensure_groups_exist(void) { ensure_group_exists(ROOT_UGID); ensure_group_exists(RESTRICTED_PARENT_UGID); ensure_group_exists(ALLOWED_CHILD1_UGID); ensure_group_exists(ALLOWED_CHILD2_UGID); ensure_group_exists(NO_POLICY_UGID); } static void drop_caps(bool setid_retained) { cap_value_t cap_values[] = {CAP_SETUID, CAP_SETGID}; cap_t caps; caps = cap_get_proc(); if (setid_retained) cap_set_flag(caps, CAP_EFFECTIVE, 2, cap_values, CAP_SET); else cap_clear(caps); cap_set_proc(caps); cap_free(caps); } int main(int argc, char **argv) { ensure_groups_exist(); ensure_users_exist(); ensure_securityfs_mounted(); write_uid_policies(); write_gid_policies(); if (prctl(PR_SET_KEEPCAPS, 1L)) die("Error with set keepcaps\n"); // First test to make sure we can write userns mappings from a non-root // user that doesn't have any restrictions (as long as it has // CAP_SETUID); if (setgid(NO_POLICY_UGID) < 0) die("Error with set gid(%d)\n", NO_POLICY_UGID); if (setuid(NO_POLICY_UGID) < 0) die("Error with set uid(%d)\n", NO_POLICY_UGID); // Take away all but setid caps drop_caps(true); // Need PR_SET_DUMPABLE flag set so we can write /proc/[pid]/uid_map // from non-root parent process. if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0)) die("Error with set dumpable\n"); if (!test_userns(true)) { die("test_userns failed when it should work\n"); } // Now switch to a user/group with restrictions if (setgid(RESTRICTED_PARENT_UGID) < 0) die("Error with set gid(%d)\n", RESTRICTED_PARENT_UGID); if (setuid(RESTRICTED_PARENT_UGID) < 0) die("Error with set uid(%d)\n", RESTRICTED_PARENT_UGID); test_setuid(ROOT_UGID, false); test_setuid(ALLOWED_CHILD1_UGID, true); test_setuid(ALLOWED_CHILD2_UGID, true); test_setuid(NO_POLICY_UGID, false); test_setgid(ROOT_UGID, false); test_setgid(ALLOWED_CHILD1_UGID, true); test_setgid(ALLOWED_CHILD2_UGID, true); test_setgid(NO_POLICY_UGID, false); gid_t allowed_supp_groups[2] = {ALLOWED_CHILD1_UGID, ALLOWED_CHILD2_UGID}; gid_t disallowed_supp_groups[2] = {ROOT_UGID, NO_POLICY_UGID}; test_setgroups(allowed_supp_groups, 2, true); test_setgroups(disallowed_supp_groups, 2, false); if (!test_userns(false)) { die("test_userns worked when it should fail\n"); } // Now take away all caps drop_caps(false); test_setuid(2, false); test_setuid(3, false); test_setuid(4, false); test_setgid(2, false); test_setgid(3, false); test_setgid(4, false); // NOTE: this test doesn't clean up users that were created in // /etc/passwd or flush policies that were added to the LSM. printf("test successful!\n"); return EXIT_SUCCESS; }
linux-master
tools/testing/selftests/safesetid/safesetid-test.c
// SPDX-License-Identifier: GPL-2.0-only /* * Exercise /dev/mem mmap cases that have been troublesome in the past * * (c) Copyright 2007 Hewlett-Packard Development Company, L.P. * Bjorn Helgaas <[email protected]> */ #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <fcntl.h> #include <fnmatch.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <linux/pci.h> int sum; static int map_mem(char *path, off_t offset, size_t length, int touch) { int fd, rc; void *addr; int *c; fd = open(path, O_RDWR); if (fd == -1) { perror(path); return -1; } if (fnmatch("/proc/bus/pci/*", path, 0) == 0) { rc = ioctl(fd, PCIIOC_MMAP_IS_MEM); if (rc == -1) perror("PCIIOC_MMAP_IS_MEM ioctl"); } addr = mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, offset); if (addr == MAP_FAILED) return 1; if (touch) { c = (int *) addr; while (c < (int *) (addr + length)) sum += *c++; } rc = munmap(addr, length); if (rc == -1) { perror("munmap"); return -1; } close(fd); return 0; } static int scan_tree(char *path, char *file, off_t offset, size_t length, int touch) { struct dirent **namelist; char *name, *path2; int i, n, r, rc = 0, result = 0; struct stat buf; n = scandir(path, &namelist, 0, alphasort); if (n < 0) { perror("scandir"); return -1; } for (i = 0; i < n; i++) { name = namelist[i]->d_name; if (fnmatch(".", name, 0) == 0) goto skip; if (fnmatch("..", name, 0) == 0) goto skip; path2 = malloc(strlen(path) + strlen(name) + 3); strcpy(path2, path); strcat(path2, "/"); strcat(path2, name); if (fnmatch(file, name, 0) == 0) { rc = map_mem(path2, offset, length, touch); if (rc == 0) fprintf(stderr, "PASS: %s 0x%lx-0x%lx is %s\n", path2, offset, offset + length, touch ? "readable" : "mappable"); else if (rc > 0) fprintf(stderr, "PASS: %s 0x%lx-0x%lx not mappable\n", path2, offset, offset + length); else { fprintf(stderr, "FAIL: %s 0x%lx-0x%lx not accessible\n", path2, offset, offset + length); return rc; } } else { r = lstat(path2, &buf); if (r == 0 && S_ISDIR(buf.st_mode)) { rc = scan_tree(path2, file, offset, length, touch); if (rc < 0) return rc; } } result |= rc; free(path2); skip: free(namelist[i]); } free(namelist); return result; } char buf[1024]; static int read_rom(char *path) { int fd, rc; size_t size = 0; fd = open(path, O_RDWR); if (fd == -1) { perror(path); return -1; } rc = write(fd, "1", 2); if (rc <= 0) { close(fd); perror("write"); return -1; } do { rc = read(fd, buf, sizeof(buf)); if (rc > 0) size += rc; } while (rc > 0); close(fd); return size; } static int scan_rom(char *path, char *file) { struct dirent **namelist; char *name, *path2; int i, n, r, rc = 0, result = 0; struct stat buf; n = scandir(path, &namelist, 0, alphasort); if (n < 0) { perror("scandir"); return -1; } for (i = 0; i < n; i++) { name = namelist[i]->d_name; if (fnmatch(".", name, 0) == 0) goto skip; if (fnmatch("..", name, 0) == 0) goto skip; path2 = malloc(strlen(path) + strlen(name) + 3); strcpy(path2, path); strcat(path2, "/"); strcat(path2, name); if (fnmatch(file, name, 0) == 0) { rc = read_rom(path2); /* * It's OK if the ROM is unreadable. Maybe there * is no ROM, or some other error occurred. The * important thing is that no MCA happened. */ if (rc > 0) fprintf(stderr, "PASS: %s read %d bytes\n", path2, rc); else { fprintf(stderr, "PASS: %s not readable\n", path2); return rc; } } else { r = lstat(path2, &buf); if (r == 0 && S_ISDIR(buf.st_mode)) { rc = scan_rom(path2, file); if (rc < 0) return rc; } } result |= rc; free(path2); skip: free(namelist[i]); } free(namelist); return result; } int main(void) { int rc; if (map_mem("/dev/mem", 0, 0xA0000, 1) == 0) fprintf(stderr, "PASS: /dev/mem 0x0-0xa0000 is readable\n"); else fprintf(stderr, "FAIL: /dev/mem 0x0-0xa0000 not accessible\n"); /* * It's not safe to blindly read the VGA frame buffer. If you know * how to poke the card the right way, it should respond, but it's * not safe in general. Many machines, e.g., Intel chipsets, cover * up a non-responding card by just returning -1, but others will * report the failure as a machine check. */ if (map_mem("/dev/mem", 0xA0000, 0x20000, 0) == 0) fprintf(stderr, "PASS: /dev/mem 0xa0000-0xc0000 is mappable\n"); else fprintf(stderr, "FAIL: /dev/mem 0xa0000-0xc0000 not accessible\n"); if (map_mem("/dev/mem", 0xC0000, 0x40000, 1) == 0) fprintf(stderr, "PASS: /dev/mem 0xc0000-0x100000 is readable\n"); else fprintf(stderr, "FAIL: /dev/mem 0xc0000-0x100000 not accessible\n"); /* * Often you can map all the individual pieces above (0-0xA0000, * 0xA0000-0xC0000, and 0xC0000-0x100000), but can't map the whole * thing at once. This is because the individual pieces use different * attributes, and there's no single attribute supported over the * whole region. */ rc = map_mem("/dev/mem", 0, 1024*1024, 0); if (rc == 0) fprintf(stderr, "PASS: /dev/mem 0x0-0x100000 is mappable\n"); else if (rc > 0) fprintf(stderr, "PASS: /dev/mem 0x0-0x100000 not mappable\n"); else fprintf(stderr, "FAIL: /dev/mem 0x0-0x100000 not accessible\n"); scan_tree("/sys/class/pci_bus", "legacy_mem", 0, 0xA0000, 1); scan_tree("/sys/class/pci_bus", "legacy_mem", 0xA0000, 0x20000, 0); scan_tree("/sys/class/pci_bus", "legacy_mem", 0xC0000, 0x40000, 1); scan_tree("/sys/class/pci_bus", "legacy_mem", 0, 1024*1024, 0); scan_rom("/sys/devices", "rom"); scan_tree("/proc/bus/pci", "??.?", 0, 0xA0000, 1); scan_tree("/proc/bus/pci", "??.?", 0xA0000, 0x20000, 0); scan_tree("/proc/bus/pci", "??.?", 0xC0000, 0x40000, 1); scan_tree("/proc/bus/pci", "??.?", 0, 1024*1024, 0); return rc; }
linux-master
tools/testing/selftests/ia64/aliasing-test.c
// SPDX-License-Identifier: GPL-2.0 /* * Stas Sergeev <[email protected]> * * test sigaltstack(SS_ONSTACK | SS_AUTODISARM) * If that succeeds, then swapcontext() can be used inside sighandler safely. * */ #define _GNU_SOURCE #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <ucontext.h> #include <alloca.h> #include <string.h> #include <assert.h> #include <errno.h> #include <sys/auxv.h> #include "../kselftest.h" #include "current_stack_pointer.h" #ifndef SS_AUTODISARM #define SS_AUTODISARM (1U << 31) #endif #ifndef AT_MINSIGSTKSZ #define AT_MINSIGSTKSZ 51 #endif static unsigned int stack_size; static void *sstack, *ustack; static ucontext_t uc, sc; static const char *msg = "[OK]\tStack preserved"; static const char *msg2 = "[FAIL]\tStack corrupted"; struct stk_data { char msg[128]; int flag; }; void my_usr1(int sig, siginfo_t *si, void *u) { char *aa; int err; stack_t stk; struct stk_data *p; if (sp < (unsigned long)sstack || sp >= (unsigned long)sstack + stack_size) { ksft_exit_fail_msg("SP is not on sigaltstack\n"); } /* put some data on stack. other sighandler will try to overwrite it */ aa = alloca(1024); assert(aa); p = (struct stk_data *)(aa + 512); strcpy(p->msg, msg); p->flag = 1; ksft_print_msg("[RUN]\tsignal USR1\n"); err = sigaltstack(NULL, &stk); if (err) { ksft_exit_fail_msg("sigaltstack() - %s\n", strerror(errno)); exit(EXIT_FAILURE); } if (stk.ss_flags != SS_DISABLE) ksft_test_result_fail("tss_flags=%x, should be SS_DISABLE\n", stk.ss_flags); else ksft_test_result_pass( "sigaltstack is disabled in sighandler\n"); swapcontext(&sc, &uc); ksft_print_msg("%s\n", p->msg); if (!p->flag) { ksft_exit_fail_msg("[RUN]\tAborting\n"); exit(EXIT_FAILURE); } } void my_usr2(int sig, siginfo_t *si, void *u) { char *aa; struct stk_data *p; ksft_print_msg("[RUN]\tsignal USR2\n"); aa = alloca(1024); /* dont run valgrind on this */ /* try to find the data stored by previous sighandler */ p = memmem(aa, 1024, msg, strlen(msg)); if (p) { ksft_test_result_fail("sigaltstack re-used\n"); /* corrupt the data */ strcpy(p->msg, msg2); /* tell other sighandler that his data is corrupted */ p->flag = 0; } } static void switch_fn(void) { ksft_print_msg("[RUN]\tswitched to user ctx\n"); raise(SIGUSR2); setcontext(&sc); } int main(void) { struct sigaction act; stack_t stk; int err; /* Make sure more than the required minimum. */ stack_size = getauxval(AT_MINSIGSTKSZ) + SIGSTKSZ; ksft_print_msg("[NOTE]\tthe stack size is %lu\n", stack_size); ksft_print_header(); ksft_set_plan(3); sigemptyset(&act.sa_mask); act.sa_flags = SA_ONSTACK | SA_SIGINFO; act.sa_sigaction = my_usr1; sigaction(SIGUSR1, &act, NULL); act.sa_sigaction = my_usr2; sigaction(SIGUSR2, &act, NULL); sstack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0); if (sstack == MAP_FAILED) { ksft_exit_fail_msg("mmap() - %s\n", strerror(errno)); return EXIT_FAILURE; } err = sigaltstack(NULL, &stk); if (err) { ksft_exit_fail_msg("sigaltstack() - %s\n", strerror(errno)); exit(EXIT_FAILURE); } if (stk.ss_flags == SS_DISABLE) { ksft_test_result_pass( "Initial sigaltstack state was SS_DISABLE\n"); } else { ksft_exit_fail_msg("Initial sigaltstack state was %x; " "should have been SS_DISABLE\n", stk.ss_flags); return EXIT_FAILURE; } stk.ss_sp = sstack; stk.ss_size = stack_size; stk.ss_flags = SS_ONSTACK | SS_AUTODISARM; err = sigaltstack(&stk, NULL); if (err) { if (errno == EINVAL) { ksft_test_result_skip( "[NOTE]\tThe running kernel doesn't support SS_AUTODISARM\n"); /* * If test cases for the !SS_AUTODISARM variant were * added, we could still run them. We don't have any * test cases like that yet, so just exit and report * success. */ return 0; } else { ksft_exit_fail_msg( "sigaltstack(SS_ONSTACK | SS_AUTODISARM) %s\n", strerror(errno)); return EXIT_FAILURE; } } ustack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0); if (ustack == MAP_FAILED) { ksft_exit_fail_msg("mmap() - %s\n", strerror(errno)); return EXIT_FAILURE; } getcontext(&uc); uc.uc_link = NULL; uc.uc_stack.ss_sp = ustack; uc.uc_stack.ss_size = stack_size; makecontext(&uc, switch_fn, 0); raise(SIGUSR1); err = sigaltstack(NULL, &stk); if (err) { ksft_exit_fail_msg("sigaltstack() - %s\n", strerror(errno)); exit(EXIT_FAILURE); } if (stk.ss_flags != SS_AUTODISARM) { ksft_exit_fail_msg("ss_flags=%x, should be SS_AUTODISARM\n", stk.ss_flags); exit(EXIT_FAILURE); } ksft_test_result_pass( "sigaltstack is still SS_AUTODISARM after signal\n"); ksft_exit_pass(); return 0; }
linux-master
tools/testing/selftests/sigaltstack/sas.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <sched.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/mount.h> #include <sys/wait.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <stdbool.h> #include <stdarg.h> #include <sys/syscall.h> #include "../kselftest_harness.h" #ifndef CLONE_NEWNS #define CLONE_NEWNS 0x00020000 #endif #ifndef CLONE_NEWUSER #define CLONE_NEWUSER 0x10000000 #endif #ifndef MS_SHARED #define MS_SHARED (1 << 20) #endif #ifndef MS_PRIVATE #define MS_PRIVATE (1<<18) #endif #ifndef MOVE_MOUNT_SET_GROUP #define MOVE_MOUNT_SET_GROUP 0x00000100 #endif #ifndef MOVE_MOUNT_F_EMPTY_PATH #define MOVE_MOUNT_F_EMPTY_PATH 0x00000004 #endif #ifndef MOVE_MOUNT_T_EMPTY_PATH #define MOVE_MOUNT_T_EMPTY_PATH 0x00000040 #endif static ssize_t write_nointr(int fd, const void *buf, size_t count) { ssize_t ret; do { ret = write(fd, buf, count); } while (ret < 0 && errno == EINTR); return ret; } static int write_file(const char *path, const void *buf, size_t count) { int fd; ssize_t ret; fd = open(path, O_WRONLY | O_CLOEXEC | O_NOCTTY | O_NOFOLLOW); if (fd < 0) return -1; ret = write_nointr(fd, buf, count); close(fd); if (ret < 0 || (size_t)ret != count) return -1; return 0; } static int create_and_enter_userns(void) { uid_t uid; gid_t gid; char map[100]; uid = getuid(); gid = getgid(); if (unshare(CLONE_NEWUSER)) return -1; if (write_file("/proc/self/setgroups", "deny", sizeof("deny") - 1) && errno != ENOENT) return -1; snprintf(map, sizeof(map), "0 %d 1", uid); if (write_file("/proc/self/uid_map", map, strlen(map))) return -1; snprintf(map, sizeof(map), "0 %d 1", gid); if (write_file("/proc/self/gid_map", map, strlen(map))) return -1; if (setgid(0)) return -1; if (setuid(0)) return -1; return 0; } static int prepare_unpriv_mountns(void) { if (create_and_enter_userns()) return -1; if (unshare(CLONE_NEWNS)) return -1; if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0)) return -1; return 0; } static char *get_field(char *src, int nfields) { int i; char *p = src; for (i = 0; i < nfields; i++) { while (*p && *p != ' ' && *p != '\t') p++; if (!*p) break; p++; } return p; } static void null_endofword(char *word) { while (*word && *word != ' ' && *word != '\t') word++; *word = '\0'; } static bool is_shared_mount(const char *path) { size_t len = 0; char *line = NULL; FILE *f = NULL; f = fopen("/proc/self/mountinfo", "re"); if (!f) return false; while (getline(&line, &len, f) != -1) { char *opts, *target; target = get_field(line, 4); if (!target) continue; opts = get_field(target, 2); if (!opts) continue; null_endofword(target); if (strcmp(target, path) != 0) continue; null_endofword(opts); if (strstr(opts, "shared:")) return true; } free(line); fclose(f); return false; } /* Attempt to de-conflict with the selftests tree. */ #ifndef SKIP #define SKIP(s, ...) XFAIL(s, ##__VA_ARGS__) #endif #define SET_GROUP_FROM "/tmp/move_mount_set_group_supported_from" #define SET_GROUP_TO "/tmp/move_mount_set_group_supported_to" static bool move_mount_set_group_supported(void) { int ret; if (mount("testing", "/tmp", "tmpfs", MS_NOATIME | MS_NODEV, "size=100000,mode=700")) return -1; if (mount(NULL, "/tmp", NULL, MS_PRIVATE, 0)) return -1; if (mkdir(SET_GROUP_FROM, 0777)) return -1; if (mkdir(SET_GROUP_TO, 0777)) return -1; if (mount("testing", SET_GROUP_FROM, "tmpfs", MS_NOATIME | MS_NODEV, "size=100000,mode=700")) return -1; if (mount(SET_GROUP_FROM, SET_GROUP_TO, NULL, MS_BIND, NULL)) return -1; if (mount(NULL, SET_GROUP_FROM, NULL, MS_SHARED, 0)) return -1; ret = syscall(SYS_move_mount, AT_FDCWD, SET_GROUP_FROM, AT_FDCWD, SET_GROUP_TO, MOVE_MOUNT_SET_GROUP); umount2("/tmp", MNT_DETACH); return ret >= 0; } FIXTURE(move_mount_set_group) { }; #define SET_GROUP_A "/tmp/A" FIXTURE_SETUP(move_mount_set_group) { bool ret; ASSERT_EQ(prepare_unpriv_mountns(), 0); ret = move_mount_set_group_supported(); ASSERT_GE(ret, 0); if (!ret) SKIP(return, "move_mount(MOVE_MOUNT_SET_GROUP) is not supported"); umount2("/tmp", MNT_DETACH); ASSERT_EQ(mount("testing", "/tmp", "tmpfs", MS_NOATIME | MS_NODEV, "size=100000,mode=700"), 0); ASSERT_EQ(mkdir(SET_GROUP_A, 0777), 0); ASSERT_EQ(mount("testing", SET_GROUP_A, "tmpfs", MS_NOATIME | MS_NODEV, "size=100000,mode=700"), 0); } FIXTURE_TEARDOWN(move_mount_set_group) { bool ret; ret = move_mount_set_group_supported(); ASSERT_GE(ret, 0); if (!ret) SKIP(return, "move_mount(MOVE_MOUNT_SET_GROUP) is not supported"); umount2("/tmp", MNT_DETACH); } #define __STACK_SIZE (8 * 1024 * 1024) static pid_t do_clone(int (*fn)(void *), void *arg, int flags) { void *stack; stack = malloc(__STACK_SIZE); if (!stack) return -ENOMEM; #ifdef __ia64__ return __clone2(fn, stack, __STACK_SIZE, flags | SIGCHLD, arg, NULL); #else return clone(fn, stack + __STACK_SIZE, flags | SIGCHLD, arg, NULL); #endif } static int wait_for_pid(pid_t pid) { int status, ret; again: ret = waitpid(pid, &status, 0); if (ret == -1) { if (errno == EINTR) goto again; return -1; } if (!WIFEXITED(status)) return -1; return WEXITSTATUS(status); } struct child_args { int unsfd; int mntnsfd; bool shared; int mntfd; }; static int get_nestedns_mount_cb(void *data) { struct child_args *ca = (struct child_args *)data; int ret; ret = prepare_unpriv_mountns(); if (ret) return 1; if (ca->shared) { ret = mount(NULL, SET_GROUP_A, NULL, MS_SHARED, 0); if (ret) return 1; } ret = open("/proc/self/ns/user", O_RDONLY); if (ret < 0) return 1; ca->unsfd = ret; ret = open("/proc/self/ns/mnt", O_RDONLY); if (ret < 0) return 1; ca->mntnsfd = ret; ret = open(SET_GROUP_A, O_RDONLY); if (ret < 0) return 1; ca->mntfd = ret; return 0; } TEST_F(move_mount_set_group, complex_sharing_copying) { struct child_args ca_from = { .shared = true, }; struct child_args ca_to = { .shared = false, }; pid_t pid; bool ret; ret = move_mount_set_group_supported(); ASSERT_GE(ret, 0); if (!ret) SKIP(return, "move_mount(MOVE_MOUNT_SET_GROUP) is not supported"); pid = do_clone(get_nestedns_mount_cb, (void *)&ca_from, CLONE_VFORK | CLONE_VM | CLONE_FILES); ASSERT_GT(pid, 0); ASSERT_EQ(wait_for_pid(pid), 0); pid = do_clone(get_nestedns_mount_cb, (void *)&ca_to, CLONE_VFORK | CLONE_VM | CLONE_FILES); ASSERT_GT(pid, 0); ASSERT_EQ(wait_for_pid(pid), 0); ASSERT_EQ(syscall(SYS_move_mount, ca_from.mntfd, "", ca_to.mntfd, "", MOVE_MOUNT_SET_GROUP | MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_EMPTY_PATH), 0); ASSERT_EQ(setns(ca_to.mntnsfd, CLONE_NEWNS), 0); ASSERT_EQ(is_shared_mount(SET_GROUP_A), 1); } TEST_HARNESS_MAIN
linux-master
tools/testing/selftests/move_mount_set_group/move_mount_set_group_test.c
// SPDX-License-Identifier: GPL-2.0 #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <linux/limits.h> #include "../kselftest.h" #define MIN_TTY_PATH_LEN 8 static bool tty_valid(char *tty) { if (strlen(tty) < MIN_TTY_PATH_LEN) return false; if (strncmp(tty, "/dev/tty", MIN_TTY_PATH_LEN) == 0 || strncmp(tty, "/dev/pts", MIN_TTY_PATH_LEN) == 0) return true; return false; } static int write_dev_tty(void) { FILE *f; int r = 0; f = fopen("/dev/tty", "r+"); if (!f) return -errno; r = fprintf(f, "hello, world!\n"); if (r != strlen("hello, world!\n")) r = -EIO; fclose(f); return r; } int main(int argc, char **argv) { int r; char tty[PATH_MAX] = {}; struct stat st1, st2; ksft_print_header(); ksft_set_plan(1); r = readlink("/proc/self/fd/0", tty, PATH_MAX); if (r < 0) ksft_exit_fail_msg("readlink on /proc/self/fd/0 failed: %m\n"); if (!tty_valid(tty)) ksft_exit_skip("invalid tty path '%s'\n", tty); r = stat(tty, &st1); if (r < 0) ksft_exit_fail_msg("stat failed on tty path '%s': %m\n", tty); /* We need to wait at least 8 seconds in order to observe timestamp change */ /* https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=fbf47635315ab308c9b58a1ea0906e711a9228de */ sleep(10); r = write_dev_tty(); if (r < 0) ksft_exit_fail_msg("failed to write to /dev/tty: %s\n", strerror(-r)); r = stat(tty, &st2); if (r < 0) ksft_exit_fail_msg("stat failed on tty path '%s': %m\n", tty); /* We wrote to the terminal so timestamps should have been updated */ if (st1.st_atim.tv_sec == st2.st_atim.tv_sec && st1.st_mtim.tv_sec == st2.st_mtim.tv_sec) { ksft_test_result_fail("tty timestamps not updated\n"); ksft_exit_fail(); } ksft_test_result_pass( "timestamps of terminal '%s' updated after write to /dev/tty\n", tty); return EXIT_SUCCESS; }
linux-master
tools/testing/selftests/tty/tty_tstamp_update.c
// SPDX-License-Identifier: GPL-2.0 #include <math.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/timeb.h> #include <sched.h> #include <errno.h> int main(int argc, char **argv) { int cpu, fd; long long msr; char msr_file_name[64]; if (argc != 2) return 1; errno = 0; cpu = strtol(argv[1], (char **) NULL, 10); if (errno) return 1; sprintf(msr_file_name, "/dev/cpu/%d/msr", cpu); fd = open(msr_file_name, O_RDONLY); if (fd == -1) { perror("Failed to open"); return 1; } pread(fd, &msr, sizeof(msr), 0x199); printf("msr 0x199: 0x%llx\n", msr); return 0; }
linux-master
tools/testing/selftests/intel_pstate/msr.c
// SPDX-License-Identifier: GPL-2.0 #include <math.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/timeb.h> #include <sched.h> #include <errno.h> #include <string.h> #include <time.h> #include "../kselftest.h" #define MSEC_PER_SEC 1000L #define NSEC_PER_MSEC 1000000L void usage(char *name) { printf ("Usage: %s cpunum\n", name); } int main(int argc, char **argv) { unsigned int i, cpu, fd; char msr_file_name[64]; long long tsc, old_tsc, new_tsc; long long aperf, old_aperf, new_aperf; long long mperf, old_mperf, new_mperf; struct timespec before, after; long long int start, finish, total; cpu_set_t cpuset; if (argc != 2) { usage(argv[0]); return 1; } errno = 0; cpu = strtol(argv[1], (char **) NULL, 10); if (errno) { usage(argv[0]); return 1; } sprintf(msr_file_name, "/dev/cpu/%d/msr", cpu); fd = open(msr_file_name, O_RDONLY); if (fd == -1) { printf("/dev/cpu/%d/msr: %s\n", cpu, strerror(errno)); return KSFT_SKIP; } CPU_ZERO(&cpuset); CPU_SET(cpu, &cpuset); if (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset)) { perror("Failed to set cpu affinity"); return 1; } if (clock_gettime(CLOCK_MONOTONIC, &before) < 0) { perror("clock_gettime"); return 1; } pread(fd, &old_tsc, sizeof(old_tsc), 0x10); pread(fd, &old_aperf, sizeof(old_mperf), 0xe7); pread(fd, &old_mperf, sizeof(old_aperf), 0xe8); for (i=0; i<0x8fffffff; i++) { sqrt(i); } if (clock_gettime(CLOCK_MONOTONIC, &after) < 0) { perror("clock_gettime"); return 1; } pread(fd, &new_tsc, sizeof(new_tsc), 0x10); pread(fd, &new_aperf, sizeof(new_mperf), 0xe7); pread(fd, &new_mperf, sizeof(new_aperf), 0xe8); tsc = new_tsc-old_tsc; aperf = new_aperf-old_aperf; mperf = new_mperf-old_mperf; start = before.tv_sec*MSEC_PER_SEC + before.tv_nsec/NSEC_PER_MSEC; finish = after.tv_sec*MSEC_PER_SEC + after.tv_nsec/NSEC_PER_MSEC; total = finish - start; printf("runTime: %4.2f\n", 1.0*total/MSEC_PER_SEC); printf("freq: %7.0f\n", tsc / (1.0*aperf / (1.0 * mperf)) / total); return 0; }
linux-master
tools/testing/selftests/intel_pstate/aperf.c
#include <errno.h> #include <error.h> #include <getopt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <sys/socket.h> #include <sys/select.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include <net/if.h> #include <asm/types.h> #include <linux/net_tstamp.h> #include <linux/errqueue.h> #include "../kselftest.h" struct options { int so_timestamp; int so_timestampns; int so_timestamping; }; struct tstamps { bool tstamp; bool tstampns; bool swtstamp; bool hwtstamp; }; struct socket_type { char *friendly_name; int type; int protocol; bool enabled; }; struct test_case { struct options sockopt; struct tstamps expected; bool enabled; bool warn_on_fail; }; struct sof_flag { int mask; char *name; }; static struct sof_flag sof_flags[] = { #define SOF_FLAG(f) { f, #f } SOF_FLAG(SOF_TIMESTAMPING_SOFTWARE), SOF_FLAG(SOF_TIMESTAMPING_RX_SOFTWARE), SOF_FLAG(SOF_TIMESTAMPING_RX_HARDWARE), }; static struct socket_type socket_types[] = { { "ip", SOCK_RAW, IPPROTO_EGP }, { "udp", SOCK_DGRAM, IPPROTO_UDP }, { "tcp", SOCK_STREAM, IPPROTO_TCP }, }; static struct test_case test_cases[] = { { {}, {} }, { { .so_timestamp = 1 }, { .tstamp = true } }, { { .so_timestampns = 1 }, { .tstampns = true } }, { { .so_timestamp = 1, .so_timestampns = 1 }, { .tstampns = true } }, { { .so_timestamping = SOF_TIMESTAMPING_RX_SOFTWARE }, {} }, { /* Loopback device does not support hw timestamps. */ { .so_timestamping = SOF_TIMESTAMPING_RX_HARDWARE }, {} }, { { .so_timestamping = SOF_TIMESTAMPING_SOFTWARE }, .warn_on_fail = true }, { { .so_timestamping = SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_RX_HARDWARE }, {} }, { { .so_timestamping = SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_RX_SOFTWARE }, { .swtstamp = true } }, { { .so_timestamp = 1, .so_timestamping = SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_RX_SOFTWARE }, { .tstamp = true, .swtstamp = true } }, }; static struct option long_options[] = { { "list_tests", no_argument, 0, 'l' }, { "test_num", required_argument, 0, 'n' }, { "op_size", required_argument, 0, 's' }, { "tcp", no_argument, 0, 't' }, { "udp", no_argument, 0, 'u' }, { "ip", no_argument, 0, 'i' }, { "strict", no_argument, 0, 'S' }, { "ipv4", no_argument, 0, '4' }, { "ipv6", no_argument, 0, '6' }, { NULL, 0, NULL, 0 }, }; static int next_port = 19999; static int op_size = 10 * 1024; void print_test_case(struct test_case *t) { int f = 0; printf("sockopts {"); if (t->sockopt.so_timestamp) printf(" SO_TIMESTAMP "); if (t->sockopt.so_timestampns) printf(" SO_TIMESTAMPNS "); if (t->sockopt.so_timestamping) { printf(" SO_TIMESTAMPING: {"); for (f = 0; f < ARRAY_SIZE(sof_flags); f++) if (t->sockopt.so_timestamping & sof_flags[f].mask) printf(" %s |", sof_flags[f].name); printf("}"); } printf("} expected cmsgs: {"); if (t->expected.tstamp) printf(" SCM_TIMESTAMP "); if (t->expected.tstampns) printf(" SCM_TIMESTAMPNS "); if (t->expected.swtstamp || t->expected.hwtstamp) { printf(" SCM_TIMESTAMPING {"); if (t->expected.swtstamp) printf("0"); if (t->expected.swtstamp && t->expected.hwtstamp) printf(","); if (t->expected.hwtstamp) printf("2"); printf("}"); } printf("}\n"); } void do_send(int src) { int r; char *buf = malloc(op_size); memset(buf, 'z', op_size); r = write(src, buf, op_size); if (r < 0) error(1, errno, "Failed to sendmsg"); free(buf); } bool do_recv(int rcv, int read_size, struct tstamps expected) { const int CMSG_SIZE = 1024; struct scm_timestamping *ts; struct tstamps actual = {}; char cmsg_buf[CMSG_SIZE]; struct iovec recv_iov; struct cmsghdr *cmsg; bool failed = false; struct msghdr hdr; int flags = 0; int r; memset(&hdr, 0, sizeof(hdr)); hdr.msg_iov = &recv_iov; hdr.msg_iovlen = 1; recv_iov.iov_base = malloc(read_size); recv_iov.iov_len = read_size; hdr.msg_control = cmsg_buf; hdr.msg_controllen = sizeof(cmsg_buf); r = recvmsg(rcv, &hdr, flags); if (r < 0) error(1, errno, "Failed to recvmsg"); if (r != read_size) error(1, 0, "Only received %d bytes of payload.", r); if (hdr.msg_flags & (MSG_TRUNC | MSG_CTRUNC)) error(1, 0, "Message was truncated."); for (cmsg = CMSG_FIRSTHDR(&hdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&hdr, cmsg)) { if (cmsg->cmsg_level != SOL_SOCKET) error(1, 0, "Unexpected cmsg_level %d", cmsg->cmsg_level); switch (cmsg->cmsg_type) { case SCM_TIMESTAMP: actual.tstamp = true; break; case SCM_TIMESTAMPNS: actual.tstampns = true; break; case SCM_TIMESTAMPING: ts = (struct scm_timestamping *)CMSG_DATA(cmsg); actual.swtstamp = !!ts->ts[0].tv_sec; if (ts->ts[1].tv_sec != 0) error(0, 0, "ts[1] should not be set."); actual.hwtstamp = !!ts->ts[2].tv_sec; break; default: error(1, 0, "Unexpected cmsg_type %d", cmsg->cmsg_type); } } #define VALIDATE(field) \ do { \ if (expected.field != actual.field) { \ if (expected.field) \ error(0, 0, "Expected " #field " to be set."); \ else \ error(0, 0, \ "Expected " #field " to not be set."); \ failed = true; \ } \ } while (0) VALIDATE(tstamp); VALIDATE(tstampns); VALIDATE(swtstamp); VALIDATE(hwtstamp); #undef VALIDATE free(recv_iov.iov_base); return failed; } void config_so_flags(int rcv, struct options o) { int on = 1; if (setsockopt(rcv, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) error(1, errno, "Failed to enable SO_REUSEADDR"); if (o.so_timestamp && setsockopt(rcv, SOL_SOCKET, SO_TIMESTAMP, &o.so_timestamp, sizeof(o.so_timestamp)) < 0) error(1, errno, "Failed to enable SO_TIMESTAMP"); if (o.so_timestampns && setsockopt(rcv, SOL_SOCKET, SO_TIMESTAMPNS, &o.so_timestampns, sizeof(o.so_timestampns)) < 0) error(1, errno, "Failed to enable SO_TIMESTAMPNS"); if (o.so_timestamping && setsockopt(rcv, SOL_SOCKET, SO_TIMESTAMPING, &o.so_timestamping, sizeof(o.so_timestamping)) < 0) error(1, errno, "Failed to set SO_TIMESTAMPING"); } bool run_test_case(struct socket_type *s, int test_num, char ip_version, bool strict) { union { struct sockaddr_in6 addr6; struct sockaddr_in addr4; struct sockaddr addr_un; } addr; int read_size = op_size; int src, dst, rcv, port; socklen_t addr_size; bool failed = false; port = (s->type == SOCK_RAW) ? 0 : next_port++; memset(&addr, 0, sizeof(addr)); if (ip_version == '4') { addr.addr4.sin_family = AF_INET; addr.addr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.addr4.sin_port = htons(port); addr_size = sizeof(addr.addr4); if (s->type == SOCK_RAW) read_size += 20; /* for IPv4 header */ } else { addr.addr6.sin6_family = AF_INET6; addr.addr6.sin6_addr = in6addr_loopback; addr.addr6.sin6_port = htons(port); addr_size = sizeof(addr.addr6); } printf("Starting testcase %d over ipv%c...\n", test_num, ip_version); src = socket(addr.addr_un.sa_family, s->type, s->protocol); if (src < 0) error(1, errno, "Failed to open src socket"); dst = socket(addr.addr_un.sa_family, s->type, s->protocol); if (dst < 0) error(1, errno, "Failed to open dst socket"); if (bind(dst, &addr.addr_un, addr_size) < 0) error(1, errno, "Failed to bind to port %d", port); if (s->type == SOCK_STREAM && (listen(dst, 1) < 0)) error(1, errno, "Failed to listen"); if (connect(src, &addr.addr_un, addr_size) < 0) error(1, errno, "Failed to connect"); if (s->type == SOCK_STREAM) { rcv = accept(dst, NULL, NULL); if (rcv < 0) error(1, errno, "Failed to accept"); close(dst); } else { rcv = dst; } config_so_flags(rcv, test_cases[test_num].sockopt); usleep(20000); /* setsockopt for SO_TIMESTAMPING is asynchronous */ do_send(src); failed = do_recv(rcv, read_size, test_cases[test_num].expected); close(rcv); close(src); if (failed) { printf("FAILURE in testcase %d over ipv%c ", test_num, ip_version); print_test_case(&test_cases[test_num]); if (!strict && test_cases[test_num].warn_on_fail) failed = false; } return failed; } int main(int argc, char **argv) { bool all_protocols = true; bool all_tests = true; bool cfg_ipv4 = false; bool cfg_ipv6 = false; bool strict = false; int arg_index = 0; int failures = 0; int s, t, opt; while ((opt = getopt_long(argc, argv, "", long_options, &arg_index)) != -1) { switch (opt) { case 'l': for (t = 0; t < ARRAY_SIZE(test_cases); t++) { printf("%d\t", t); print_test_case(&test_cases[t]); } return 0; case 'n': t = atoi(optarg); if (t >= ARRAY_SIZE(test_cases)) error(1, 0, "Invalid test case: %d", t); all_tests = false; test_cases[t].enabled = true; break; case 's': op_size = atoi(optarg); break; case 't': all_protocols = false; socket_types[2].enabled = true; break; case 'u': all_protocols = false; socket_types[1].enabled = true; break; case 'i': all_protocols = false; socket_types[0].enabled = true; break; case 'S': strict = true; break; case '4': cfg_ipv4 = true; break; case '6': cfg_ipv6 = true; break; default: error(1, 0, "Failed to parse parameters."); } } for (s = 0; s < ARRAY_SIZE(socket_types); s++) { if (!all_protocols && !socket_types[s].enabled) continue; printf("Testing %s...\n", socket_types[s].friendly_name); for (t = 0; t < ARRAY_SIZE(test_cases); t++) { if (!all_tests && !test_cases[t].enabled) continue; if (cfg_ipv4 || !cfg_ipv6) if (run_test_case(&socket_types[s], t, '4', strict)) failures++; if (cfg_ipv6 || !cfg_ipv4) if (run_test_case(&socket_types[s], t, '6', strict)) failures++; } } if (!failures) printf("PASSED.\n"); return failures; }
linux-master
tools/testing/selftests/net/rxtimestamp.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2013 Google Inc. * Author: Willem de Bruijn ([email protected]) * * A basic test of packet socket fanout behavior. * * Control: * - create fanout fails as expected with illegal flag combinations * - join fanout fails as expected with diverging types or flags * * Datapath: * Open a pair of packet sockets and a pair of INET sockets, send a known * number of packets across the two INET sockets and count the number of * packets enqueued onto the two packet sockets. * * The test currently runs for * - PACKET_FANOUT_HASH * - PACKET_FANOUT_HASH with PACKET_FANOUT_FLAG_ROLLOVER * - PACKET_FANOUT_LB * - PACKET_FANOUT_CPU * - PACKET_FANOUT_ROLLOVER * - PACKET_FANOUT_CBPF * - PACKET_FANOUT_EBPF * * Todo: * - functionality: PACKET_FANOUT_FLAG_DEFRAG */ #define _GNU_SOURCE /* for sched_setaffinity */ #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <linux/unistd.h> /* for __NR_bpf */ #include <linux/filter.h> #include <linux/bpf.h> #include <linux/if_packet.h> #include <net/if.h> #include <net/ethernet.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <poll.h> #include <sched.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "psock_lib.h" #include "../kselftest.h" #define RING_NUM_FRAMES 20 static uint32_t cfg_max_num_members; /* Open a socket in a given fanout mode. * @return -1 if mode is bad, a valid socket otherwise */ static int sock_fanout_open(uint16_t typeflags, uint16_t group_id) { struct sockaddr_ll addr = {0}; struct fanout_args args; int fd, val, err; fd = socket(PF_PACKET, SOCK_RAW, 0); if (fd < 0) { perror("socket packet"); exit(1); } pair_udp_setfilter(fd); addr.sll_family = AF_PACKET; addr.sll_protocol = htons(ETH_P_IP); addr.sll_ifindex = if_nametoindex("lo"); if (addr.sll_ifindex == 0) { perror("if_nametoindex"); exit(1); } if (bind(fd, (void *) &addr, sizeof(addr))) { perror("bind packet"); exit(1); } if (cfg_max_num_members) { args.id = group_id; args.type_flags = typeflags; args.max_num_members = cfg_max_num_members; err = setsockopt(fd, SOL_PACKET, PACKET_FANOUT, &args, sizeof(args)); } else { val = (((int) typeflags) << 16) | group_id; err = setsockopt(fd, SOL_PACKET, PACKET_FANOUT, &val, sizeof(val)); } if (err) { if (close(fd)) { perror("close packet"); exit(1); } return -1; } return fd; } static void sock_fanout_set_cbpf(int fd) { struct sock_filter bpf_filter[] = { BPF_STMT(BPF_LD | BPF_B | BPF_ABS, 80), /* ldb [80] */ BPF_STMT(BPF_RET | BPF_A, 0), /* ret A */ }; struct sock_fprog bpf_prog; bpf_prog.filter = bpf_filter; bpf_prog.len = ARRAY_SIZE(bpf_filter); if (setsockopt(fd, SOL_PACKET, PACKET_FANOUT_DATA, &bpf_prog, sizeof(bpf_prog))) { perror("fanout data cbpf"); exit(1); } } static void sock_fanout_getopts(int fd, uint16_t *typeflags, uint16_t *group_id) { int sockopt; socklen_t sockopt_len = sizeof(sockopt); if (getsockopt(fd, SOL_PACKET, PACKET_FANOUT, &sockopt, &sockopt_len)) { perror("failed to getsockopt"); exit(1); } *typeflags = sockopt >> 16; *group_id = sockopt & 0xfffff; } static void sock_fanout_set_ebpf(int fd) { static char log_buf[65536]; const int len_off = __builtin_offsetof(struct __sk_buff, len); struct bpf_insn prog[] = { { BPF_ALU64 | BPF_MOV | BPF_X, 6, 1, 0, 0 }, { BPF_LDX | BPF_W | BPF_MEM, 0, 6, len_off, 0 }, { BPF_JMP | BPF_JGE | BPF_K, 0, 0, 1, DATA_LEN }, { BPF_JMP | BPF_JA | BPF_K, 0, 0, 4, 0 }, { BPF_LD | BPF_B | BPF_ABS, 0, 0, 0, 0x50 }, { BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 2, DATA_CHAR }, { BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1, DATA_CHAR_1 }, { BPF_ALU | BPF_MOV | BPF_K, 0, 0, 0, 0 }, { BPF_JMP | BPF_EXIT, 0, 0, 0, 0 } }; union bpf_attr attr; int pfd; memset(&attr, 0, sizeof(attr)); attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; attr.insns = (unsigned long) prog; attr.insn_cnt = ARRAY_SIZE(prog); attr.license = (unsigned long) "GPL"; attr.log_buf = (unsigned long) log_buf, attr.log_size = sizeof(log_buf), attr.log_level = 1, pfd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr)); if (pfd < 0) { perror("bpf"); fprintf(stderr, "bpf verifier:\n%s\n", log_buf); exit(1); } if (setsockopt(fd, SOL_PACKET, PACKET_FANOUT_DATA, &pfd, sizeof(pfd))) { perror("fanout data ebpf"); exit(1); } if (close(pfd)) { perror("close ebpf"); exit(1); } } static char *sock_fanout_open_ring(int fd) { struct tpacket_req req = { .tp_block_size = getpagesize(), .tp_frame_size = getpagesize(), .tp_block_nr = RING_NUM_FRAMES, .tp_frame_nr = RING_NUM_FRAMES, }; char *ring; int val = TPACKET_V2; if (setsockopt(fd, SOL_PACKET, PACKET_VERSION, (void *) &val, sizeof(val))) { perror("packetsock ring setsockopt version"); exit(1); } if (setsockopt(fd, SOL_PACKET, PACKET_RX_RING, (void *) &req, sizeof(req))) { perror("packetsock ring setsockopt"); exit(1); } ring = mmap(0, req.tp_block_size * req.tp_block_nr, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (ring == MAP_FAILED) { perror("packetsock ring mmap"); exit(1); } return ring; } static int sock_fanout_read_ring(int fd, void *ring) { struct tpacket2_hdr *header = ring; int count = 0; while (count < RING_NUM_FRAMES && header->tp_status & TP_STATUS_USER) { count++; header = ring + (count * getpagesize()); } return count; } static int sock_fanout_read(int fds[], char *rings[], const int expect[]) { int ret[2]; ret[0] = sock_fanout_read_ring(fds[0], rings[0]); ret[1] = sock_fanout_read_ring(fds[1], rings[1]); fprintf(stderr, "info: count=%d,%d, expect=%d,%d\n", ret[0], ret[1], expect[0], expect[1]); if ((!(ret[0] == expect[0] && ret[1] == expect[1])) && (!(ret[0] == expect[1] && ret[1] == expect[0]))) { fprintf(stderr, "warning: incorrect queue lengths\n"); return 1; } return 0; } /* Test illegal mode + flag combination */ static void test_control_single(void) { fprintf(stderr, "test: control single socket\n"); if (sock_fanout_open(PACKET_FANOUT_ROLLOVER | PACKET_FANOUT_FLAG_ROLLOVER, 0) != -1) { fprintf(stderr, "ERROR: opened socket with dual rollover\n"); exit(1); } } /* Test illegal group with different modes or flags */ static void test_control_group(void) { int fds[2]; fprintf(stderr, "test: control multiple sockets\n"); fds[0] = sock_fanout_open(PACKET_FANOUT_HASH, 0); if (fds[0] == -1) { fprintf(stderr, "ERROR: failed to open HASH socket\n"); exit(1); } if (sock_fanout_open(PACKET_FANOUT_HASH | PACKET_FANOUT_FLAG_DEFRAG, 0) != -1) { fprintf(stderr, "ERROR: joined group with wrong flag defrag\n"); exit(1); } if (sock_fanout_open(PACKET_FANOUT_HASH | PACKET_FANOUT_FLAG_ROLLOVER, 0) != -1) { fprintf(stderr, "ERROR: joined group with wrong flag ro\n"); exit(1); } if (sock_fanout_open(PACKET_FANOUT_CPU, 0) != -1) { fprintf(stderr, "ERROR: joined group with wrong mode\n"); exit(1); } fds[1] = sock_fanout_open(PACKET_FANOUT_HASH, 0); if (fds[1] == -1) { fprintf(stderr, "ERROR: failed to join group\n"); exit(1); } if (close(fds[1]) || close(fds[0])) { fprintf(stderr, "ERROR: closing sockets\n"); exit(1); } } /* Test illegal max_num_members values */ static void test_control_group_max_num_members(void) { int fds[3]; fprintf(stderr, "test: control multiple sockets, max_num_members\n"); /* expected failure on greater than PACKET_FANOUT_MAX */ cfg_max_num_members = (1 << 16) + 1; if (sock_fanout_open(PACKET_FANOUT_HASH, 0) != -1) { fprintf(stderr, "ERROR: max_num_members > PACKET_FANOUT_MAX\n"); exit(1); } cfg_max_num_members = 256; fds[0] = sock_fanout_open(PACKET_FANOUT_HASH, 0); if (fds[0] == -1) { fprintf(stderr, "ERROR: failed open\n"); exit(1); } /* expected failure on joining group with different max_num_members */ cfg_max_num_members = 257; if (sock_fanout_open(PACKET_FANOUT_HASH, 0) != -1) { fprintf(stderr, "ERROR: set different max_num_members\n"); exit(1); } /* success on joining group with same max_num_members */ cfg_max_num_members = 256; fds[1] = sock_fanout_open(PACKET_FANOUT_HASH, 0); if (fds[1] == -1) { fprintf(stderr, "ERROR: failed to join group\n"); exit(1); } /* success on joining group with max_num_members unspecified */ cfg_max_num_members = 0; fds[2] = sock_fanout_open(PACKET_FANOUT_HASH, 0); if (fds[2] == -1) { fprintf(stderr, "ERROR: failed to join group\n"); exit(1); } if (close(fds[2]) || close(fds[1]) || close(fds[0])) { fprintf(stderr, "ERROR: closing sockets\n"); exit(1); } } /* Test creating a unique fanout group ids */ static void test_unique_fanout_group_ids(void) { int fds[3]; uint16_t typeflags, first_group_id, second_group_id; fprintf(stderr, "test: unique ids\n"); fds[0] = sock_fanout_open(PACKET_FANOUT_HASH | PACKET_FANOUT_FLAG_UNIQUEID, 0); if (fds[0] == -1) { fprintf(stderr, "ERROR: failed to create a unique id group.\n"); exit(1); } sock_fanout_getopts(fds[0], &typeflags, &first_group_id); if (typeflags != PACKET_FANOUT_HASH) { fprintf(stderr, "ERROR: unexpected typeflags %x\n", typeflags); exit(1); } if (sock_fanout_open(PACKET_FANOUT_CPU, first_group_id) != -1) { fprintf(stderr, "ERROR: joined group with wrong type.\n"); exit(1); } fds[1] = sock_fanout_open(PACKET_FANOUT_HASH, first_group_id); if (fds[1] == -1) { fprintf(stderr, "ERROR: failed to join previously created group.\n"); exit(1); } fds[2] = sock_fanout_open(PACKET_FANOUT_HASH | PACKET_FANOUT_FLAG_UNIQUEID, 0); if (fds[2] == -1) { fprintf(stderr, "ERROR: failed to create a second unique id group.\n"); exit(1); } sock_fanout_getopts(fds[2], &typeflags, &second_group_id); if (sock_fanout_open(PACKET_FANOUT_HASH | PACKET_FANOUT_FLAG_UNIQUEID, second_group_id) != -1) { fprintf(stderr, "ERROR: specified a group id when requesting unique id\n"); exit(1); } if (close(fds[0]) || close(fds[1]) || close(fds[2])) { fprintf(stderr, "ERROR: closing sockets\n"); exit(1); } } static int test_datapath(uint16_t typeflags, int port_off, const int expect1[], const int expect2[]) { const int expect0[] = { 0, 0 }; char *rings[2]; uint8_t type = typeflags & 0xFF; int fds[2], fds_udp[2][2], ret; fprintf(stderr, "\ntest: datapath 0x%hx ports %hu,%hu\n", typeflags, (uint16_t)PORT_BASE, (uint16_t)(PORT_BASE + port_off)); fds[0] = sock_fanout_open(typeflags, 0); fds[1] = sock_fanout_open(typeflags, 0); if (fds[0] == -1 || fds[1] == -1) { fprintf(stderr, "ERROR: failed open\n"); exit(1); } if (type == PACKET_FANOUT_CBPF) sock_fanout_set_cbpf(fds[0]); else if (type == PACKET_FANOUT_EBPF) sock_fanout_set_ebpf(fds[0]); rings[0] = sock_fanout_open_ring(fds[0]); rings[1] = sock_fanout_open_ring(fds[1]); pair_udp_open(fds_udp[0], PORT_BASE); pair_udp_open(fds_udp[1], PORT_BASE + port_off); sock_fanout_read(fds, rings, expect0); /* Send data, but not enough to overflow a queue */ pair_udp_send(fds_udp[0], 15); pair_udp_send_char(fds_udp[1], 5, DATA_CHAR_1); ret = sock_fanout_read(fds, rings, expect1); /* Send more data, overflow the queue */ pair_udp_send_char(fds_udp[0], 15, DATA_CHAR_1); /* TODO: ensure consistent order between expect1 and expect2 */ ret |= sock_fanout_read(fds, rings, expect2); if (munmap(rings[1], RING_NUM_FRAMES * getpagesize()) || munmap(rings[0], RING_NUM_FRAMES * getpagesize())) { fprintf(stderr, "close rings\n"); exit(1); } if (close(fds_udp[1][1]) || close(fds_udp[1][0]) || close(fds_udp[0][1]) || close(fds_udp[0][0]) || close(fds[1]) || close(fds[0])) { fprintf(stderr, "close datapath\n"); exit(1); } return ret; } static int set_cpuaffinity(int cpuid) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(cpuid, &mask); if (sched_setaffinity(0, sizeof(mask), &mask)) { if (errno != EINVAL) { fprintf(stderr, "setaffinity %d\n", cpuid); exit(1); } return 1; } return 0; } int main(int argc, char **argv) { const int expect_hash[2][2] = { { 15, 5 }, { 20, 5 } }; const int expect_hash_rb[2][2] = { { 15, 5 }, { 20, 15 } }; const int expect_lb[2][2] = { { 10, 10 }, { 18, 17 } }; const int expect_rb[2][2] = { { 15, 5 }, { 20, 15 } }; const int expect_cpu0[2][2] = { { 20, 0 }, { 20, 0 } }; const int expect_cpu1[2][2] = { { 0, 20 }, { 0, 20 } }; const int expect_bpf[2][2] = { { 15, 5 }, { 15, 20 } }; const int expect_uniqueid[2][2] = { { 20, 20}, { 20, 20 } }; int port_off = 2, tries = 20, ret; test_control_single(); test_control_group(); test_control_group_max_num_members(); test_unique_fanout_group_ids(); /* PACKET_FANOUT_MAX */ cfg_max_num_members = 1 << 16; /* find a set of ports that do not collide onto the same socket */ ret = test_datapath(PACKET_FANOUT_HASH, port_off, expect_hash[0], expect_hash[1]); while (ret) { fprintf(stderr, "info: trying alternate ports (%d)\n", tries); ret = test_datapath(PACKET_FANOUT_HASH, ++port_off, expect_hash[0], expect_hash[1]); if (!--tries) { fprintf(stderr, "too many collisions\n"); return 1; } } ret |= test_datapath(PACKET_FANOUT_HASH | PACKET_FANOUT_FLAG_ROLLOVER, port_off, expect_hash_rb[0], expect_hash_rb[1]); ret |= test_datapath(PACKET_FANOUT_LB, port_off, expect_lb[0], expect_lb[1]); ret |= test_datapath(PACKET_FANOUT_ROLLOVER, port_off, expect_rb[0], expect_rb[1]); ret |= test_datapath(PACKET_FANOUT_CBPF, port_off, expect_bpf[0], expect_bpf[1]); ret |= test_datapath(PACKET_FANOUT_EBPF, port_off, expect_bpf[0], expect_bpf[1]); set_cpuaffinity(0); ret |= test_datapath(PACKET_FANOUT_CPU, port_off, expect_cpu0[0], expect_cpu0[1]); if (!set_cpuaffinity(1)) /* TODO: test that choice alternates with previous */ ret |= test_datapath(PACKET_FANOUT_CPU, port_off, expect_cpu1[0], expect_cpu1[1]); ret |= test_datapath(PACKET_FANOUT_FLAG_UNIQUEID, port_off, expect_uniqueid[0], expect_uniqueid[1]); if (ret) return 1; printf("OK. All tests passed\n"); return 0; }
linux-master
tools/testing/selftests/net/psock_fanout.c
// SPDX-License-Identifier: GPL-2.0 /* Test program for SIOC{G,S}HWTSTAMP * Copyright 2013 Solarflare Communications * Author: Ben Hutchings */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <linux/if.h> #include <linux/net_tstamp.h> #include <linux/sockios.h> #include "kselftest.h" static int lookup_value(const char **names, int size, const char *name) { int value; for (value = 0; value < size; value++) if (names[value] && strcasecmp(names[value], name) == 0) return value; return -1; } static const char * lookup_name(const char **names, int size, int value) { return (value >= 0 && value < size) ? names[value] : NULL; } static void list_names(FILE *f, const char **names, int size) { int value; for (value = 0; value < size; value++) if (names[value]) fprintf(f, " %s\n", names[value]); } static const char *tx_types[] = { #define TX_TYPE(name) [HWTSTAMP_TX_ ## name] = #name TX_TYPE(OFF), TX_TYPE(ON), TX_TYPE(ONESTEP_SYNC) #undef TX_TYPE }; #define N_TX_TYPES ((int)(ARRAY_SIZE(tx_types))) static const char *rx_filters[] = { #define RX_FILTER(name) [HWTSTAMP_FILTER_ ## name] = #name RX_FILTER(NONE), RX_FILTER(ALL), RX_FILTER(SOME), RX_FILTER(PTP_V1_L4_EVENT), RX_FILTER(PTP_V1_L4_SYNC), RX_FILTER(PTP_V1_L4_DELAY_REQ), RX_FILTER(PTP_V2_L4_EVENT), RX_FILTER(PTP_V2_L4_SYNC), RX_FILTER(PTP_V2_L4_DELAY_REQ), RX_FILTER(PTP_V2_L2_EVENT), RX_FILTER(PTP_V2_L2_SYNC), RX_FILTER(PTP_V2_L2_DELAY_REQ), RX_FILTER(PTP_V2_EVENT), RX_FILTER(PTP_V2_SYNC), RX_FILTER(PTP_V2_DELAY_REQ), #undef RX_FILTER }; #define N_RX_FILTERS ((int)(ARRAY_SIZE(rx_filters))) static void usage(void) { fputs("Usage: hwtstamp_config if_name [tx_type rx_filter]\n" "tx_type is any of (case-insensitive):\n", stderr); list_names(stderr, tx_types, N_TX_TYPES); fputs("rx_filter is any of (case-insensitive):\n", stderr); list_names(stderr, rx_filters, N_RX_FILTERS); } int main(int argc, char **argv) { struct ifreq ifr; struct hwtstamp_config config; const char *name; int sock; if ((argc != 2 && argc != 4) || (strlen(argv[1]) >= IFNAMSIZ)) { usage(); return 2; } if (argc == 4) { config.flags = 0; config.tx_type = lookup_value(tx_types, N_TX_TYPES, argv[2]); config.rx_filter = lookup_value(rx_filters, N_RX_FILTERS, argv[3]); if (config.tx_type < 0 || config.rx_filter < 0) { usage(); return 2; } } sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) { perror("socket"); return 1; } strcpy(ifr.ifr_name, argv[1]); ifr.ifr_data = (caddr_t)&config; if (ioctl(sock, (argc == 2) ? SIOCGHWTSTAMP : SIOCSHWTSTAMP, &ifr)) { perror("ioctl"); return 1; } printf("flags = %#x\n", config.flags); name = lookup_name(tx_types, N_TX_TYPES, config.tx_type); if (name) printf("tx_type = %s\n", name); else printf("tx_type = %d\n", config.tx_type); name = lookup_name(rx_filters, N_RX_FILTERS, config.rx_filter); if (name) printf("rx_filter = %s\n", name); else printf("rx_filter = %d\n", config.rx_filter); return 0; }
linux-master
tools/testing/selftests/net/hwtstamp_config.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */ /* Test listening on the same port 443 with multiple VIPS. * Each VIP:443 will have multiple sk listening on by using * SO_REUSEPORT. */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <error.h> #include <errno.h> #include <time.h> #include <arpa/inet.h> #define IP6_LADDR_START "2401:dead::1" #define IP6_LPORT 443 #define NSEC_PER_SEC 1000000000L #define NSEC_PER_USEC 1000L static unsigned int nr_socks_per_vip; static unsigned int nr_vips; static int *bind_reuseport_sock6(void) { int *lfds, *cur_fd, err, optvalue = 1; struct sockaddr_in6 sa6 = {}; unsigned int i, j; sa6.sin6_family = AF_INET6; sa6.sin6_port = htons(IP6_LPORT); err = inet_pton(AF_INET6, IP6_LADDR_START, &sa6.sin6_addr); if (err != 1) error(1, err, "inet_pton(%s)", IP6_LADDR_START); lfds = malloc(nr_vips * nr_socks_per_vip * sizeof(lfds[0])); if (!lfds) error(1, errno, "cannot alloc array of lfds"); cur_fd = lfds; for (i = 0; i < nr_vips; i++) { for (j = 0; j < nr_socks_per_vip; j++) { *cur_fd = socket(AF_INET6, SOCK_STREAM, 0); if (*cur_fd == -1) error(1, errno, "lfds[%u,%u] = socket(AF_INET6)", i, j); err = setsockopt(*cur_fd, SOL_SOCKET, SO_REUSEPORT, &optvalue, sizeof(optvalue)); if (err) error(1, errno, "setsockopt(lfds[%u,%u], SO_REUSEPORT)", i, j); err = bind(*cur_fd, (struct sockaddr *)&sa6, sizeof(sa6)); if (err) error(1, errno, "bind(lfds[%u,%u])", i, j); cur_fd++; } sa6.sin6_addr.s6_addr32[3]++; } return lfds; } int main(int argc, const char *argv[]) { struct timespec start_ts, end_ts; unsigned long start_ns, end_ns; unsigned int nr_lsocks; int *lfds, i, err; if (argc != 3 || atoi(argv[1]) <= 0 || atoi(argv[2]) <= 0) error(1, 0, "Usage: %s <nr_vips> <nr_socks_per_vip>\n", argv[0]); nr_vips = atoi(argv[1]); nr_socks_per_vip = atoi(argv[2]); nr_lsocks = nr_vips * nr_socks_per_vip; lfds = bind_reuseport_sock6(); clock_gettime(CLOCK_MONOTONIC, &start_ts); for (i = 0; i < nr_lsocks; i++) { err = listen(lfds[i], 0); if (err) error(1, errno, "listen(lfds[%d])", i); } clock_gettime(CLOCK_MONOTONIC, &end_ts); start_ns = start_ts.tv_sec * NSEC_PER_SEC + start_ts.tv_nsec; end_ns = end_ts.tv_sec * NSEC_PER_SEC + end_ts.tv_nsec; printf("listen %d socks took %lu.%lu\n", nr_lsocks, (end_ns - start_ns) / NSEC_PER_SEC, (end_ns - start_ns) / NSEC_PER_USEC); for (i = 0; i < nr_lsocks; i++) close(lfds[i]); free(lfds); return 0; }
linux-master
tools/testing/selftests/net/stress_reuseport_listen.c
// SPDX-License-Identifier: GPL-2.0 /* Test hardware checksum offload: Rx + Tx, IPv4 + IPv6, TCP + UDP. * * The test runs on two machines to exercise the NIC. For this reason it * is not integrated in kselftests. * * CMD=$((./csum -[46] -[tu] -S $SADDR -D $DADDR -[RT] -r 1 $EXTRA_ARGS)) * * Rx: * * The sender sends packets with a known checksum field using PF_INET(6) * SOCK_RAW sockets. * * good packet: $CMD [-t] * bad packet: $CMD [-t] -E * * The receiver reads UDP packets with a UDP socket. This is not an * option for TCP packets ('-t'). Optionally insert an iptables filter * to avoid these entering the real protocol stack. * * The receiver also reads all packets with a PF_PACKET socket, to * observe whether both good and bad packets arrive on the host. And to * read the optional TP_STATUS_CSUM_VALID bit. This requires setting * option PACKET_AUXDATA, and works only for CHECKSUM_UNNECESSARY. * * Tx: * * The sender needs to build CHECKSUM_PARTIAL packets to exercise tx * checksum offload. * * The sender can sends packets with a UDP socket. * * Optionally crafts a packet that sums up to zero to verify that the * device writes negative zero 0xFFFF in this case to distinguish from * 0x0000 (checksum disabled), as required by RFC 768. Hit this case * by choosing a specific source port. * * good packet: $CMD -U * zero csum: $CMD -U -Z * * The sender can also build packets with PF_PACKET with PACKET_VNET_HDR, * to cover more protocols. PF_PACKET requires passing src and dst mac * addresses. * * good packet: $CMD -s $smac -d $dmac -p [-t] * * Argument '-z' sends UDP packets with a 0x000 checksum disabled field, * to verify that the NIC passes these packets unmodified. * * Argument '-e' adds a transport mode encapsulation header between * network and transport header. This will fail for devices that parse * headers. Should work on devices that implement protocol agnostic tx * checksum offload (NETIF_F_HW_CSUM). * * Argument '-r $SEED' optionally randomizes header, payload and length * to increase coverage between packets sent. SEED 1 further chooses a * different seed for each run (and logs this for reproducibility). It * is advised to enable this for extra coverage in continuous testing. */ #define _GNU_SOURCE #include <arpa/inet.h> #include <asm/byteorder.h> #include <errno.h> #include <error.h> #include <linux/filter.h> #include <linux/if_packet.h> #include <linux/ipv6.h> #include <linux/virtio_net.h> #include <net/ethernet.h> #include <net/if.h> #include <netinet/if_ether.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <poll.h> #include <sched.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include "kselftest.h" static bool cfg_bad_csum; static int cfg_family = PF_INET6; static int cfg_num_pkt = 4; static bool cfg_do_rx = true; static bool cfg_do_tx = true; static bool cfg_encap; static char *cfg_ifname = "eth0"; static char *cfg_mac_dst; static char *cfg_mac_src; static int cfg_proto = IPPROTO_UDP; static int cfg_payload_char = 'a'; static int cfg_payload_len = 100; static uint16_t cfg_port_dst = 34000; static uint16_t cfg_port_src = 33000; static uint16_t cfg_port_src_encap = 33001; static unsigned int cfg_random_seed; static int cfg_rcvbuf = 1 << 22; /* be able to queue large cfg_num_pkt */ static bool cfg_send_pfpacket; static bool cfg_send_udp; static int cfg_timeout_ms = 2000; static bool cfg_zero_disable; /* skip checksum: set to zero (udp only) */ static bool cfg_zero_sum; /* create packet that adds up to zero */ static struct sockaddr_in cfg_daddr4 = {.sin_family = AF_INET}; static struct sockaddr_in cfg_saddr4 = {.sin_family = AF_INET}; static struct sockaddr_in6 cfg_daddr6 = {.sin6_family = AF_INET6}; static struct sockaddr_in6 cfg_saddr6 = {.sin6_family = AF_INET6}; #define ENC_HEADER_LEN (sizeof(struct udphdr) + sizeof(struct udp_encap_hdr)) #define MAX_HEADER_LEN (sizeof(struct ipv6hdr) + ENC_HEADER_LEN + sizeof(struct tcphdr)) #define MAX_PAYLOAD_LEN 1024 /* Trivial demo encap. Stand-in for transport layer protocols like ESP or PSP */ struct udp_encap_hdr { uint8_t nexthdr; uint8_t padding[3]; }; /* Ipaddrs, for pseudo csum. Global var is ugly, pass through funcs was worse */ static void *iph_addr_p; static unsigned long gettimeofday_ms(void) { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000UL) + (tv.tv_usec / 1000UL); } static uint32_t checksum_nofold(char *data, size_t len, uint32_t sum) { uint16_t *words = (uint16_t *)data; int i; for (i = 0; i < len / 2; i++) sum += words[i]; if (len & 1) sum += ((unsigned char *)data)[len - 1]; return sum; } static uint16_t checksum_fold(void *data, size_t len, uint32_t sum) { sum = checksum_nofold(data, len, sum); while (sum > 0xFFFF) sum = (sum & 0xFFFF) + (sum >> 16); return ~sum; } static uint16_t checksum(void *th, uint16_t proto, size_t len) { uint32_t sum; int alen; alen = cfg_family == PF_INET6 ? 32 : 8; sum = checksum_nofold(iph_addr_p, alen, 0); sum += htons(proto); sum += htons(len); /* With CHECKSUM_PARTIAL kernel expects non-inverted pseudo csum */ if (cfg_do_tx && cfg_send_pfpacket) return ~checksum_fold(NULL, 0, sum); else return checksum_fold(th, len, sum); } static void *build_packet_ipv4(void *_iph, uint8_t proto, unsigned int len) { struct iphdr *iph = _iph; memset(iph, 0, sizeof(*iph)); iph->version = 4; iph->ihl = 5; iph->ttl = 8; iph->protocol = proto; iph->saddr = cfg_saddr4.sin_addr.s_addr; iph->daddr = cfg_daddr4.sin_addr.s_addr; iph->tot_len = htons(sizeof(*iph) + len); iph->check = checksum_fold(iph, sizeof(*iph), 0); iph_addr_p = &iph->saddr; return iph + 1; } static void *build_packet_ipv6(void *_ip6h, uint8_t proto, unsigned int len) { struct ipv6hdr *ip6h = _ip6h; memset(ip6h, 0, sizeof(*ip6h)); ip6h->version = 6; ip6h->payload_len = htons(len); ip6h->nexthdr = proto; ip6h->hop_limit = 64; ip6h->saddr = cfg_saddr6.sin6_addr; ip6h->daddr = cfg_daddr6.sin6_addr; iph_addr_p = &ip6h->saddr; return ip6h + 1; } static void *build_packet_udp(void *_uh) { struct udphdr *uh = _uh; uh->source = htons(cfg_port_src); uh->dest = htons(cfg_port_dst); uh->len = htons(sizeof(*uh) + cfg_payload_len); uh->check = 0; /* choose source port so that uh->check adds up to zero */ if (cfg_zero_sum) { uh->source = 0; uh->source = checksum(uh, IPPROTO_UDP, sizeof(*uh) + cfg_payload_len); fprintf(stderr, "tx: changing sport: %hu -> %hu\n", cfg_port_src, ntohs(uh->source)); cfg_port_src = ntohs(uh->source); } if (cfg_zero_disable) uh->check = 0; else uh->check = checksum(uh, IPPROTO_UDP, sizeof(*uh) + cfg_payload_len); if (cfg_bad_csum) uh->check = ~uh->check; fprintf(stderr, "tx: sending checksum: 0x%x\n", uh->check); return uh + 1; } static void *build_packet_tcp(void *_th) { struct tcphdr *th = _th; th->source = htons(cfg_port_src); th->dest = htons(cfg_port_dst); th->doff = 5; th->check = 0; th->check = checksum(th, IPPROTO_TCP, sizeof(*th) + cfg_payload_len); if (cfg_bad_csum) th->check = ~th->check; fprintf(stderr, "tx: sending checksum: 0x%x\n", th->check); return th + 1; } static char *build_packet_udp_encap(void *_uh) { struct udphdr *uh = _uh; struct udp_encap_hdr *eh = _uh + sizeof(*uh); /* outer dst == inner dst, to simplify BPF filter * outer src != inner src, to demultiplex on recv */ uh->dest = htons(cfg_port_dst); uh->source = htons(cfg_port_src_encap); uh->check = 0; uh->len = htons(sizeof(*uh) + sizeof(*eh) + sizeof(struct tcphdr) + cfg_payload_len); eh->nexthdr = IPPROTO_TCP; return build_packet_tcp(eh + 1); } static char *build_packet(char *buf, int max_len, int *len) { uint8_t proto; char *off; int tlen; if (cfg_random_seed) { int *buf32 = (void *)buf; int i; for (i = 0; i < (max_len / sizeof(int)); i++) buf32[i] = rand(); } else { memset(buf, cfg_payload_char, max_len); } if (cfg_proto == IPPROTO_UDP) tlen = sizeof(struct udphdr) + cfg_payload_len; else tlen = sizeof(struct tcphdr) + cfg_payload_len; if (cfg_encap) { proto = IPPROTO_UDP; tlen += ENC_HEADER_LEN; } else { proto = cfg_proto; } if (cfg_family == PF_INET) off = build_packet_ipv4(buf, proto, tlen); else off = build_packet_ipv6(buf, proto, tlen); if (cfg_encap) off = build_packet_udp_encap(off); else if (cfg_proto == IPPROTO_UDP) off = build_packet_udp(off); else off = build_packet_tcp(off); /* only pass the payload, but still compute headers for cfg_zero_sum */ if (cfg_send_udp) { *len = cfg_payload_len; return off; } *len = off - buf + cfg_payload_len; return buf; } static int open_inet(int ipproto, int protocol) { int fd; fd = socket(cfg_family, ipproto, protocol); if (fd == -1) error(1, errno, "socket inet"); if (cfg_family == PF_INET6) { /* may have been updated by cfg_zero_sum */ cfg_saddr6.sin6_port = htons(cfg_port_src); if (bind(fd, (void *)&cfg_saddr6, sizeof(cfg_saddr6))) error(1, errno, "bind dgram 6"); if (connect(fd, (void *)&cfg_daddr6, sizeof(cfg_daddr6))) error(1, errno, "connect dgram 6"); } else { /* may have been updated by cfg_zero_sum */ cfg_saddr4.sin_port = htons(cfg_port_src); if (bind(fd, (void *)&cfg_saddr4, sizeof(cfg_saddr4))) error(1, errno, "bind dgram 4"); if (connect(fd, (void *)&cfg_daddr4, sizeof(cfg_daddr4))) error(1, errno, "connect dgram 4"); } return fd; } static int open_packet(void) { int fd, one = 1; fd = socket(PF_PACKET, SOCK_RAW, 0); if (fd == -1) error(1, errno, "socket packet"); if (setsockopt(fd, SOL_PACKET, PACKET_VNET_HDR, &one, sizeof(one))) error(1, errno, "setsockopt packet_vnet_ndr"); return fd; } static void send_inet(int fd, const char *buf, int len) { int ret; ret = write(fd, buf, len); if (ret == -1) error(1, errno, "write"); if (ret != len) error(1, 0, "write: %d", ret); } static void eth_str_to_addr(const char *str, unsigned char *eth) { if (sscanf(str, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &eth[0], &eth[1], &eth[2], &eth[3], &eth[4], &eth[5]) != 6) error(1, 0, "cannot parse mac addr %s", str); } static void send_packet(int fd, const char *buf, int len) { struct virtio_net_hdr vh = {0}; struct sockaddr_ll addr = {0}; struct msghdr msg = {0}; struct ethhdr eth; struct iovec iov[3]; int ret; addr.sll_family = AF_PACKET; addr.sll_halen = ETH_ALEN; addr.sll_ifindex = if_nametoindex(cfg_ifname); if (!addr.sll_ifindex) error(1, errno, "if_nametoindex %s", cfg_ifname); vh.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; if (cfg_family == PF_INET6) { vh.csum_start = sizeof(struct ethhdr) + sizeof(struct ipv6hdr); addr.sll_protocol = htons(ETH_P_IPV6); } else { vh.csum_start = sizeof(struct ethhdr) + sizeof(struct iphdr); addr.sll_protocol = htons(ETH_P_IP); } if (cfg_encap) vh.csum_start += ENC_HEADER_LEN; if (cfg_proto == IPPROTO_TCP) { vh.csum_offset = __builtin_offsetof(struct tcphdr, check); vh.hdr_len = vh.csum_start + sizeof(struct tcphdr); } else { vh.csum_offset = __builtin_offsetof(struct udphdr, check); vh.hdr_len = vh.csum_start + sizeof(struct udphdr); } eth_str_to_addr(cfg_mac_src, eth.h_source); eth_str_to_addr(cfg_mac_dst, eth.h_dest); eth.h_proto = addr.sll_protocol; iov[0].iov_base = &vh; iov[0].iov_len = sizeof(vh); iov[1].iov_base = &eth; iov[1].iov_len = sizeof(eth); iov[2].iov_base = (void *)buf; iov[2].iov_len = len; msg.msg_iov = iov; msg.msg_iovlen = ARRAY_SIZE(iov); msg.msg_name = &addr; msg.msg_namelen = sizeof(addr); ret = sendmsg(fd, &msg, 0); if (ret == -1) error(1, errno, "sendmsg packet"); if (ret != sizeof(vh) + sizeof(eth) + len) error(1, errno, "sendmsg packet: %u", ret); } static int recv_prepare_udp(void) { int fd; fd = socket(cfg_family, SOCK_DGRAM, 0); if (fd == -1) error(1, errno, "socket r"); if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &cfg_rcvbuf, sizeof(cfg_rcvbuf))) error(1, errno, "setsockopt SO_RCVBUF r"); if (cfg_family == PF_INET6) { if (bind(fd, (void *)&cfg_daddr6, sizeof(cfg_daddr6))) error(1, errno, "bind r"); } else { if (bind(fd, (void *)&cfg_daddr4, sizeof(cfg_daddr4))) error(1, errno, "bind r"); } return fd; } /* Filter out all traffic that is not cfg_proto with our destination port. * * Otherwise background noise may cause PF_PACKET receive queue overflow, * dropping the expected packets and failing the test. */ static void __recv_prepare_packet_filter(int fd, int off_nexthdr, int off_dport) { struct sock_filter filter[] = { BPF_STMT(BPF_LD + BPF_B + BPF_ABS, SKF_AD_OFF + SKF_AD_PKTTYPE), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, PACKET_HOST, 0, 4), BPF_STMT(BPF_LD + BPF_B + BPF_ABS, off_nexthdr), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, cfg_encap ? IPPROTO_UDP : cfg_proto, 0, 2), BPF_STMT(BPF_LD + BPF_H + BPF_ABS, off_dport), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, cfg_port_dst, 1, 0), BPF_STMT(BPF_RET + BPF_K, 0), BPF_STMT(BPF_RET + BPF_K, 0xFFFF), }; struct sock_fprog prog = {}; prog.filter = filter; prog.len = ARRAY_SIZE(filter); if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog))) error(1, errno, "setsockopt filter"); } static void recv_prepare_packet_filter(int fd) { const int off_dport = offsetof(struct tcphdr, dest); /* same for udp */ if (cfg_family == AF_INET) __recv_prepare_packet_filter(fd, offsetof(struct iphdr, protocol), sizeof(struct iphdr) + off_dport); else __recv_prepare_packet_filter(fd, offsetof(struct ipv6hdr, nexthdr), sizeof(struct ipv6hdr) + off_dport); } static void recv_prepare_packet_bind(int fd) { struct sockaddr_ll laddr = {0}; laddr.sll_family = AF_PACKET; if (cfg_family == PF_INET) laddr.sll_protocol = htons(ETH_P_IP); else laddr.sll_protocol = htons(ETH_P_IPV6); laddr.sll_ifindex = if_nametoindex(cfg_ifname); if (!laddr.sll_ifindex) error(1, 0, "if_nametoindex %s", cfg_ifname); if (bind(fd, (void *)&laddr, sizeof(laddr))) error(1, errno, "bind pf_packet"); } static int recv_prepare_packet(void) { int fd, one = 1; fd = socket(PF_PACKET, SOCK_DGRAM, 0); if (fd == -1) error(1, errno, "socket p"); if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &cfg_rcvbuf, sizeof(cfg_rcvbuf))) error(1, errno, "setsockopt SO_RCVBUF p"); /* enable auxdata to recv checksum status (valid vs unknown) */ if (setsockopt(fd, SOL_PACKET, PACKET_AUXDATA, &one, sizeof(one))) error(1, errno, "setsockopt auxdata"); /* install filter to restrict packet flow to match */ recv_prepare_packet_filter(fd); /* bind to address family to start packet flow */ recv_prepare_packet_bind(fd); return fd; } static int recv_udp(int fd) { static char buf[MAX_PAYLOAD_LEN]; int ret, count = 0; while (1) { ret = recv(fd, buf, sizeof(buf), MSG_DONTWAIT); if (ret == -1 && errno == EAGAIN) break; if (ret == -1) error(1, errno, "recv r"); fprintf(stderr, "rx: udp: len=%u\n", ret); count++; } return count; } static int recv_verify_csum(void *th, int len, uint16_t sport, uint16_t csum_field) { uint16_t csum; csum = checksum(th, cfg_proto, len); fprintf(stderr, "rx: pkt: sport=%hu len=%u csum=0x%hx verify=0x%hx\n", sport, len, csum_field, csum); /* csum must be zero unless cfg_bad_csum indicates bad csum */ if (csum && !cfg_bad_csum) { fprintf(stderr, "pkt: bad csum\n"); return 1; } else if (cfg_bad_csum && !csum) { fprintf(stderr, "pkt: good csum, while bad expected\n"); return 1; } if (cfg_zero_sum && csum_field != 0xFFFF) { fprintf(stderr, "pkt: zero csum: field should be 0xFFFF, is 0x%hx\n", csum_field); return 1; } return 0; } static int recv_verify_packet_tcp(void *th, int len) { struct tcphdr *tcph = th; if (len < sizeof(*tcph) || tcph->dest != htons(cfg_port_dst)) return -1; return recv_verify_csum(th, len, ntohs(tcph->source), tcph->check); } static int recv_verify_packet_udp_encap(void *th, int len) { struct udp_encap_hdr *eh = th; if (len < sizeof(*eh) || eh->nexthdr != IPPROTO_TCP) return -1; return recv_verify_packet_tcp(eh + 1, len - sizeof(*eh)); } static int recv_verify_packet_udp(void *th, int len) { struct udphdr *udph = th; if (len < sizeof(*udph)) return -1; if (udph->dest != htons(cfg_port_dst)) return -1; if (udph->source == htons(cfg_port_src_encap)) return recv_verify_packet_udp_encap(udph + 1, len - sizeof(*udph)); return recv_verify_csum(th, len, ntohs(udph->source), udph->check); } static int recv_verify_packet_ipv4(void *nh, int len) { struct iphdr *iph = nh; uint16_t proto = cfg_encap ? IPPROTO_UDP : cfg_proto; if (len < sizeof(*iph) || iph->protocol != proto) return -1; iph_addr_p = &iph->saddr; if (proto == IPPROTO_TCP) return recv_verify_packet_tcp(iph + 1, len - sizeof(*iph)); else return recv_verify_packet_udp(iph + 1, len - sizeof(*iph)); } static int recv_verify_packet_ipv6(void *nh, int len) { struct ipv6hdr *ip6h = nh; uint16_t proto = cfg_encap ? IPPROTO_UDP : cfg_proto; if (len < sizeof(*ip6h) || ip6h->nexthdr != proto) return -1; iph_addr_p = &ip6h->saddr; if (proto == IPPROTO_TCP) return recv_verify_packet_tcp(ip6h + 1, len - sizeof(*ip6h)); else return recv_verify_packet_udp(ip6h + 1, len - sizeof(*ip6h)); } /* return whether auxdata includes TP_STATUS_CSUM_VALID */ static bool recv_verify_packet_csum(struct msghdr *msg) { struct tpacket_auxdata *aux = NULL; struct cmsghdr *cm; if (msg->msg_flags & MSG_CTRUNC) error(1, 0, "cmsg: truncated"); for (cm = CMSG_FIRSTHDR(msg); cm; cm = CMSG_NXTHDR(msg, cm)) { if (cm->cmsg_level != SOL_PACKET || cm->cmsg_type != PACKET_AUXDATA) error(1, 0, "cmsg: level=%d type=%d\n", cm->cmsg_level, cm->cmsg_type); if (cm->cmsg_len != CMSG_LEN(sizeof(struct tpacket_auxdata))) error(1, 0, "cmsg: len=%lu expected=%lu", cm->cmsg_len, CMSG_LEN(sizeof(struct tpacket_auxdata))); aux = (void *)CMSG_DATA(cm); } if (!aux) error(1, 0, "cmsg: no auxdata"); return aux->tp_status & TP_STATUS_CSUM_VALID; } static int recv_packet(int fd) { static char _buf[MAX_HEADER_LEN + MAX_PAYLOAD_LEN]; unsigned long total = 0, bad_csums = 0, bad_validations = 0; char ctrl[CMSG_SPACE(sizeof(struct tpacket_auxdata))]; struct pkt *buf = (void *)_buf; struct msghdr msg = {0}; struct iovec iov; int len, ret; iov.iov_base = _buf; iov.iov_len = sizeof(_buf); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = ctrl; msg.msg_controllen = sizeof(ctrl); while (1) { msg.msg_flags = 0; len = recvmsg(fd, &msg, MSG_DONTWAIT); if (len == -1 && errno == EAGAIN) break; if (len == -1) error(1, errno, "recv p"); if (cfg_family == PF_INET6) ret = recv_verify_packet_ipv6(buf, len); else ret = recv_verify_packet_ipv4(buf, len); if (ret == -1 /* skip: non-matching */) continue; total++; if (ret == 1) bad_csums++; /* Fail if kernel returns valid for known bad csum. * Do not fail if kernel does not validate a good csum: * Absence of validation does not imply invalid. */ if (recv_verify_packet_csum(&msg) && cfg_bad_csum) { fprintf(stderr, "cmsg: expected bad csum, pf_packet returns valid\n"); bad_validations++; } } if (bad_csums || bad_validations) error(1, 0, "rx: errors at pf_packet: total=%lu bad_csums=%lu bad_valids=%lu\n", total, bad_csums, bad_validations); return total; } static void parse_args(int argc, char *const argv[]) { const char *daddr = NULL, *saddr = NULL; int c; while ((c = getopt(argc, argv, "46d:D:eEi:l:L:n:r:PRs:S:tTuUzZ")) != -1) { switch (c) { case '4': cfg_family = PF_INET; break; case '6': cfg_family = PF_INET6; break; case 'd': cfg_mac_dst = optarg; break; case 'D': daddr = optarg; break; case 'e': cfg_encap = true; break; case 'E': cfg_bad_csum = true; break; case 'i': cfg_ifname = optarg; break; case 'l': cfg_payload_len = strtol(optarg, NULL, 0); break; case 'L': cfg_timeout_ms = strtol(optarg, NULL, 0) * 1000; break; case 'n': cfg_num_pkt = strtol(optarg, NULL, 0); break; case 'r': cfg_random_seed = strtol(optarg, NULL, 0); break; case 'P': cfg_send_pfpacket = true; break; case 'R': /* only Rx: used with two machine tests */ cfg_do_tx = false; break; case 's': cfg_mac_src = optarg; break; case 'S': saddr = optarg; break; case 't': cfg_proto = IPPROTO_TCP; break; case 'T': /* only Tx: used with two machine tests */ cfg_do_rx = false; break; case 'u': cfg_proto = IPPROTO_UDP; break; case 'U': /* send using real udp socket, * to exercise tx checksum offload */ cfg_send_udp = true; break; case 'z': cfg_zero_disable = true; break; case 'Z': cfg_zero_sum = true; break; default: error(1, 0, "unknown arg %c", c); } } if (!daddr || !saddr) error(1, 0, "Must pass -D <daddr> and -S <saddr>"); if (cfg_do_tx && cfg_send_pfpacket && (!cfg_mac_src || !cfg_mac_dst)) error(1, 0, "Transmit with pf_packet requires mac addresses"); if (cfg_payload_len > MAX_PAYLOAD_LEN) error(1, 0, "Payload length exceeds max"); if (cfg_proto != IPPROTO_UDP && (cfg_zero_sum || cfg_zero_disable)) error(1, 0, "Only UDP supports zero csum"); if (cfg_zero_sum && !cfg_send_udp) error(1, 0, "Zero checksum conversion requires -U for tx csum offload"); if (cfg_zero_sum && cfg_bad_csum) error(1, 0, "Cannot combine zero checksum conversion and invalid checksum"); if (cfg_zero_sum && cfg_random_seed) error(1, 0, "Cannot combine zero checksum conversion with randomization"); if (cfg_family == PF_INET6) { cfg_saddr6.sin6_port = htons(cfg_port_src); cfg_daddr6.sin6_port = htons(cfg_port_dst); if (inet_pton(cfg_family, daddr, &cfg_daddr6.sin6_addr) != 1) error(1, errno, "Cannot parse ipv6 -D"); if (inet_pton(cfg_family, saddr, &cfg_saddr6.sin6_addr) != 1) error(1, errno, "Cannot parse ipv6 -S"); } else { cfg_saddr4.sin_port = htons(cfg_port_src); cfg_daddr4.sin_port = htons(cfg_port_dst); if (inet_pton(cfg_family, daddr, &cfg_daddr4.sin_addr) != 1) error(1, errno, "Cannot parse ipv4 -D"); if (inet_pton(cfg_family, saddr, &cfg_saddr4.sin_addr) != 1) error(1, errno, "Cannot parse ipv4 -S"); } if (cfg_do_tx && cfg_random_seed) { /* special case: time-based seed */ if (cfg_random_seed == 1) cfg_random_seed = (unsigned int)gettimeofday_ms(); srand(cfg_random_seed); fprintf(stderr, "randomization seed: %u\n", cfg_random_seed); } } static void do_tx(void) { static char _buf[MAX_HEADER_LEN + MAX_PAYLOAD_LEN]; char *buf; int fd, len, i; buf = build_packet(_buf, sizeof(_buf), &len); if (cfg_send_pfpacket) fd = open_packet(); else if (cfg_send_udp) fd = open_inet(SOCK_DGRAM, 0); else fd = open_inet(SOCK_RAW, IPPROTO_RAW); for (i = 0; i < cfg_num_pkt; i++) { if (cfg_send_pfpacket) send_packet(fd, buf, len); else send_inet(fd, buf, len); /* randomize each packet individually to increase coverage */ if (cfg_random_seed) { cfg_payload_len = rand() % MAX_PAYLOAD_LEN; buf = build_packet(_buf, sizeof(_buf), &len); } } if (close(fd)) error(1, errno, "close tx"); } static void do_rx(int fdp, int fdr) { unsigned long count_udp = 0, count_pkt = 0; long tleft, tstop; struct pollfd pfd; tstop = gettimeofday_ms() + cfg_timeout_ms; tleft = cfg_timeout_ms; do { pfd.events = POLLIN; pfd.fd = fdp; if (poll(&pfd, 1, tleft) == -1) error(1, errno, "poll"); if (pfd.revents & POLLIN) count_pkt += recv_packet(fdp); if (cfg_proto == IPPROTO_UDP) count_udp += recv_udp(fdr); tleft = tstop - gettimeofday_ms(); } while (tleft > 0); if (close(fdr)) error(1, errno, "close r"); if (close(fdp)) error(1, errno, "close p"); if (count_pkt < cfg_num_pkt) error(1, 0, "rx: missing packets at pf_packet: %lu < %u", count_pkt, cfg_num_pkt); if (cfg_proto == IPPROTO_UDP) { if (cfg_bad_csum && count_udp) error(1, 0, "rx: unexpected packets at udp"); if (!cfg_bad_csum && !count_udp) error(1, 0, "rx: missing packets at udp"); } } int main(int argc, char *const argv[]) { int fdp = -1, fdr = -1; /* -1 to silence -Wmaybe-uninitialized */ parse_args(argc, argv); /* open receive sockets before transmitting */ if (cfg_do_rx) { fdp = recv_prepare_packet(); fdr = recv_prepare_udp(); } if (cfg_do_tx) do_tx(); if (cfg_do_rx) do_rx(fdp, fdr); fprintf(stderr, "OK\n"); return 0; }
linux-master
tools/testing/selftests/net/csum.c
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause // Copyright (c) 2023 Cloudflare /* Test IP_LOCAL_PORT_RANGE socket option: IPv4 + IPv6, TCP + UDP. * * Tests assume that net.ipv4.ip_local_port_range is [40000, 49999]. * Don't run these directly but with ip_local_port_range.sh script. */ #include <fcntl.h> #include <netinet/ip.h> #include "../kselftest_harness.h" #ifndef IP_LOCAL_PORT_RANGE #define IP_LOCAL_PORT_RANGE 51 #endif static __u32 pack_port_range(__u16 lo, __u16 hi) { return (hi << 16) | (lo << 0); } static void unpack_port_range(__u32 range, __u16 *lo, __u16 *hi) { *lo = range & 0xffff; *hi = range >> 16; } static int get_so_domain(int fd) { int domain, err; socklen_t len; len = sizeof(domain); err = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domain, &len); if (err) return -1; return domain; } static int bind_to_loopback_any_port(int fd) { union { struct sockaddr sa; struct sockaddr_in v4; struct sockaddr_in6 v6; } addr; socklen_t addr_len; memset(&addr, 0, sizeof(addr)); switch (get_so_domain(fd)) { case AF_INET: addr.v4.sin_family = AF_INET; addr.v4.sin_port = htons(0); addr.v4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr_len = sizeof(addr.v4); break; case AF_INET6: addr.v6.sin6_family = AF_INET6; addr.v6.sin6_port = htons(0); addr.v6.sin6_addr = in6addr_loopback; addr_len = sizeof(addr.v6); break; default: return -1; } return bind(fd, &addr.sa, addr_len); } static int get_sock_port(int fd) { union { struct sockaddr sa; struct sockaddr_in v4; struct sockaddr_in6 v6; } addr; socklen_t addr_len; int err; addr_len = sizeof(addr); memset(&addr, 0, sizeof(addr)); err = getsockname(fd, &addr.sa, &addr_len); if (err) return -1; switch (addr.sa.sa_family) { case AF_INET: return ntohs(addr.v4.sin_port); case AF_INET6: return ntohs(addr.v6.sin6_port); default: errno = EAFNOSUPPORT; return -1; } } static int get_ip_local_port_range(int fd, __u32 *range) { socklen_t len; __u32 val; int err; len = sizeof(val); err = getsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &val, &len); if (err) return -1; *range = val; return 0; } FIXTURE(ip_local_port_range) {}; FIXTURE_SETUP(ip_local_port_range) { } FIXTURE_TEARDOWN(ip_local_port_range) { } FIXTURE_VARIANT(ip_local_port_range) { int so_domain; int so_type; int so_protocol; }; FIXTURE_VARIANT_ADD(ip_local_port_range, ip4_tcp) { .so_domain = AF_INET, .so_type = SOCK_STREAM, .so_protocol = 0, }; FIXTURE_VARIANT_ADD(ip_local_port_range, ip4_udp) { .so_domain = AF_INET, .so_type = SOCK_DGRAM, .so_protocol = 0, }; FIXTURE_VARIANT_ADD(ip_local_port_range, ip4_stcp) { .so_domain = AF_INET, .so_type = SOCK_STREAM, .so_protocol = IPPROTO_SCTP, }; FIXTURE_VARIANT_ADD(ip_local_port_range, ip6_tcp) { .so_domain = AF_INET6, .so_type = SOCK_STREAM, .so_protocol = 0, }; FIXTURE_VARIANT_ADD(ip_local_port_range, ip6_udp) { .so_domain = AF_INET6, .so_type = SOCK_DGRAM, .so_protocol = 0, }; FIXTURE_VARIANT_ADD(ip_local_port_range, ip6_stcp) { .so_domain = AF_INET6, .so_type = SOCK_STREAM, .so_protocol = IPPROTO_SCTP, }; TEST_F(ip_local_port_range, invalid_option_value) { __u16 val16; __u32 val32; __u64 val64; int fd, err; fd = socket(variant->so_domain, variant->so_type, variant->so_protocol); ASSERT_GE(fd, 0) TH_LOG("socket failed"); /* Too few bytes */ val16 = 40000; err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &val16, sizeof(val16)); EXPECT_TRUE(err) TH_LOG("expected setsockopt(IP_LOCAL_PORT_RANGE) to fail"); EXPECT_EQ(errno, EINVAL); /* Empty range: low port > high port */ val32 = pack_port_range(40222, 40111); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &val32, sizeof(val32)); EXPECT_TRUE(err) TH_LOG("expected setsockopt(IP_LOCAL_PORT_RANGE) to fail"); EXPECT_EQ(errno, EINVAL); /* Too many bytes */ val64 = pack_port_range(40333, 40444); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &val64, sizeof(val64)); EXPECT_TRUE(err) TH_LOG("expected setsockopt(IP_LOCAL_PORT_RANGE) to fail"); EXPECT_EQ(errno, EINVAL); err = close(fd); ASSERT_TRUE(!err) TH_LOG("close failed"); } TEST_F(ip_local_port_range, port_range_out_of_netns_range) { const struct test { __u16 range_lo; __u16 range_hi; } tests[] = { { 30000, 39999 }, /* socket range below netns range */ { 50000, 59999 }, /* socket range above netns range */ }; const struct test *t; for (t = tests; t < tests + ARRAY_SIZE(tests); t++) { /* Bind a couple of sockets, not just one, to check * that the range wasn't clamped to a single port from * the netns range. That is [40000, 40000] or [49999, * 49999], respectively for each test case. */ int fds[2], i; TH_LOG("lo %5hu, hi %5hu", t->range_lo, t->range_hi); for (i = 0; i < ARRAY_SIZE(fds); i++) { int fd, err, port; __u32 range; fd = socket(variant->so_domain, variant->so_type, variant->so_protocol); ASSERT_GE(fd, 0) TH_LOG("#%d: socket failed", i); range = pack_port_range(t->range_lo, t->range_hi); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &range, sizeof(range)); ASSERT_TRUE(!err) TH_LOG("#%d: setsockopt(IP_LOCAL_PORT_RANGE) failed", i); err = bind_to_loopback_any_port(fd); ASSERT_TRUE(!err) TH_LOG("#%d: bind failed", i); /* Check that socket port range outside of ephemeral range is ignored */ port = get_sock_port(fd); ASSERT_GE(port, 40000) TH_LOG("#%d: expected port within netns range", i); ASSERT_LE(port, 49999) TH_LOG("#%d: expected port within netns range", i); fds[i] = fd; } for (i = 0; i < ARRAY_SIZE(fds); i++) ASSERT_TRUE(close(fds[i]) == 0) TH_LOG("#%d: close failed", i); } } TEST_F(ip_local_port_range, single_port_range) { const struct test { __u16 range_lo; __u16 range_hi; __u16 expected; } tests[] = { /* single port range within ephemeral range */ { 45000, 45000, 45000 }, /* first port in the ephemeral range (clamp from above) */ { 0, 40000, 40000 }, /* last port in the ephemeral range (clamp from below) */ { 49999, 0, 49999 }, }; const struct test *t; for (t = tests; t < tests + ARRAY_SIZE(tests); t++) { int fd, err, port; __u32 range; TH_LOG("lo %5hu, hi %5hu, expected %5hu", t->range_lo, t->range_hi, t->expected); fd = socket(variant->so_domain, variant->so_type, variant->so_protocol); ASSERT_GE(fd, 0) TH_LOG("socket failed"); range = pack_port_range(t->range_lo, t->range_hi); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &range, sizeof(range)); ASSERT_TRUE(!err) TH_LOG("setsockopt(IP_LOCAL_PORT_RANGE) failed"); err = bind_to_loopback_any_port(fd); ASSERT_TRUE(!err) TH_LOG("bind failed"); port = get_sock_port(fd); ASSERT_EQ(port, t->expected) TH_LOG("unexpected local port"); err = close(fd); ASSERT_TRUE(!err) TH_LOG("close failed"); } } TEST_F(ip_local_port_range, exhaust_8_port_range) { __u8 port_set = 0; int i, fd, err; __u32 range; __u16 port; int fds[8]; for (i = 0; i < ARRAY_SIZE(fds); i++) { fd = socket(variant->so_domain, variant->so_type, variant->so_protocol); ASSERT_GE(fd, 0) TH_LOG("socket failed"); range = pack_port_range(40000, 40007); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &range, sizeof(range)); ASSERT_TRUE(!err) TH_LOG("setsockopt(IP_LOCAL_PORT_RANGE) failed"); err = bind_to_loopback_any_port(fd); ASSERT_TRUE(!err) TH_LOG("bind failed"); port = get_sock_port(fd); ASSERT_GE(port, 40000) TH_LOG("expected port within sockopt range"); ASSERT_LE(port, 40007) TH_LOG("expected port within sockopt range"); port_set |= 1 << (port - 40000); fds[i] = fd; } /* Check that all every port from the test range is in use */ ASSERT_EQ(port_set, 0xff) TH_LOG("expected all ports to be busy"); /* Check that bind() fails because the whole range is busy */ fd = socket(variant->so_domain, variant->so_type, variant->so_protocol); ASSERT_GE(fd, 0) TH_LOG("socket failed"); range = pack_port_range(40000, 40007); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &range, sizeof(range)); ASSERT_TRUE(!err) TH_LOG("setsockopt(IP_LOCAL_PORT_RANGE) failed"); err = bind_to_loopback_any_port(fd); ASSERT_TRUE(err) TH_LOG("expected bind to fail"); ASSERT_EQ(errno, EADDRINUSE); err = close(fd); ASSERT_TRUE(!err) TH_LOG("close failed"); for (i = 0; i < ARRAY_SIZE(fds); i++) { err = close(fds[i]); ASSERT_TRUE(!err) TH_LOG("close failed"); } } TEST_F(ip_local_port_range, late_bind) { union { struct sockaddr sa; struct sockaddr_in v4; struct sockaddr_in6 v6; } addr; socklen_t addr_len; const int one = 1; int fd, err; __u32 range; __u16 port; if (variant->so_protocol == IPPROTO_SCTP) SKIP(return, "SCTP doesn't support IP_BIND_ADDRESS_NO_PORT"); fd = socket(variant->so_domain, variant->so_type, 0); ASSERT_GE(fd, 0) TH_LOG("socket failed"); range = pack_port_range(40100, 40199); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &range, sizeof(range)); ASSERT_TRUE(!err) TH_LOG("setsockopt(IP_LOCAL_PORT_RANGE) failed"); err = setsockopt(fd, SOL_IP, IP_BIND_ADDRESS_NO_PORT, &one, sizeof(one)); ASSERT_TRUE(!err) TH_LOG("setsockopt(IP_BIND_ADDRESS_NO_PORT) failed"); err = bind_to_loopback_any_port(fd); ASSERT_TRUE(!err) TH_LOG("bind failed"); port = get_sock_port(fd); ASSERT_EQ(port, 0) TH_LOG("getsockname failed"); /* Invalid destination */ memset(&addr, 0, sizeof(addr)); switch (variant->so_domain) { case AF_INET: addr.v4.sin_family = AF_INET; addr.v4.sin_port = htons(0); addr.v4.sin_addr.s_addr = htonl(INADDR_ANY); addr_len = sizeof(addr.v4); break; case AF_INET6: addr.v6.sin6_family = AF_INET6; addr.v6.sin6_port = htons(0); addr.v6.sin6_addr = in6addr_any; addr_len = sizeof(addr.v6); break; default: ASSERT_TRUE(false) TH_LOG("unsupported socket domain"); } /* connect() doesn't need to succeed for late bind to happen */ connect(fd, &addr.sa, addr_len); port = get_sock_port(fd); ASSERT_GE(port, 40100); ASSERT_LE(port, 40199); err = close(fd); ASSERT_TRUE(!err) TH_LOG("close failed"); } TEST_F(ip_local_port_range, get_port_range) { __u16 lo, hi; __u32 range; int fd, err; fd = socket(variant->so_domain, variant->so_type, variant->so_protocol); ASSERT_GE(fd, 0) TH_LOG("socket failed"); /* Get range before it will be set */ err = get_ip_local_port_range(fd, &range); ASSERT_TRUE(!err) TH_LOG("getsockopt(IP_LOCAL_PORT_RANGE) failed"); unpack_port_range(range, &lo, &hi); ASSERT_EQ(lo, 0) TH_LOG("unexpected low port"); ASSERT_EQ(hi, 0) TH_LOG("unexpected high port"); range = pack_port_range(12345, 54321); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &range, sizeof(range)); ASSERT_TRUE(!err) TH_LOG("setsockopt(IP_LOCAL_PORT_RANGE) failed"); /* Get range after it has been set */ err = get_ip_local_port_range(fd, &range); ASSERT_TRUE(!err) TH_LOG("getsockopt(IP_LOCAL_PORT_RANGE) failed"); unpack_port_range(range, &lo, &hi); ASSERT_EQ(lo, 12345) TH_LOG("unexpected low port"); ASSERT_EQ(hi, 54321) TH_LOG("unexpected high port"); /* Unset the port range */ range = pack_port_range(0, 0); err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE, &range, sizeof(range)); ASSERT_TRUE(!err) TH_LOG("setsockopt(IP_LOCAL_PORT_RANGE) failed"); /* Get range after it has been unset */ err = get_ip_local_port_range(fd, &range); ASSERT_TRUE(!err) TH_LOG("getsockopt(IP_LOCAL_PORT_RANGE) failed"); unpack_port_range(range, &lo, &hi); ASSERT_EQ(lo, 0) TH_LOG("unexpected low port"); ASSERT_EQ(hi, 0) TH_LOG("unexpected high port"); err = close(fd); ASSERT_TRUE(!err) TH_LOG("close failed"); } TEST_HARNESS_MAIN
linux-master
tools/testing/selftests/net/ip_local_port_range.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2018 Google Inc. * Author: Soheil Hassas Yeganeh ([email protected]) * * Simple example on how to use TCP_INQ and TCP_CM_INQ. */ #define _GNU_SOURCE #include <error.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <pthread.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #ifndef TCP_INQ #define TCP_INQ 36 #endif #ifndef TCP_CM_INQ #define TCP_CM_INQ TCP_INQ #endif #define BUF_SIZE 8192 #define CMSG_SIZE 32 static int family = AF_INET6; static socklen_t addr_len = sizeof(struct sockaddr_in6); static int port = 4974; static void setup_loopback_addr(int family, struct sockaddr_storage *sockaddr) { struct sockaddr_in6 *addr6 = (void *) sockaddr; struct sockaddr_in *addr4 = (void *) sockaddr; switch (family) { case PF_INET: memset(addr4, 0, sizeof(*addr4)); addr4->sin_family = AF_INET; addr4->sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr4->sin_port = htons(port); break; case PF_INET6: memset(addr6, 0, sizeof(*addr6)); addr6->sin6_family = AF_INET6; addr6->sin6_addr = in6addr_loopback; addr6->sin6_port = htons(port); break; default: error(1, 0, "illegal family"); } } void *start_server(void *arg) { int server_fd = (int)(unsigned long)arg; struct sockaddr_in addr; socklen_t addrlen = sizeof(addr); char *buf; int fd; int r; buf = malloc(BUF_SIZE); for (;;) { fd = accept(server_fd, (struct sockaddr *)&addr, &addrlen); if (fd == -1) { perror("accept"); break; } do { r = send(fd, buf, BUF_SIZE, 0); } while (r < 0 && errno == EINTR); if (r < 0) perror("send"); if (r != BUF_SIZE) fprintf(stderr, "can only send %d bytes\n", r); /* TCP_INQ can overestimate in-queue by one byte if we send * the FIN packet. Sleep for 1 second, so that the client * likely invoked recvmsg(). */ sleep(1); close(fd); } free(buf); close(server_fd); pthread_exit(0); } int main(int argc, char *argv[]) { struct sockaddr_storage listen_addr, addr; int c, one = 1, inq = -1; pthread_t server_thread; char cmsgbuf[CMSG_SIZE]; struct iovec iov[1]; struct cmsghdr *cm; struct msghdr msg; int server_fd, fd; char *buf; while ((c = getopt(argc, argv, "46p:")) != -1) { switch (c) { case '4': family = PF_INET; addr_len = sizeof(struct sockaddr_in); break; case '6': family = PF_INET6; addr_len = sizeof(struct sockaddr_in6); break; case 'p': port = atoi(optarg); break; } } server_fd = socket(family, SOCK_STREAM, 0); if (server_fd < 0) error(1, errno, "server socket"); setup_loopback_addr(family, &listen_addr); if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) error(1, errno, "setsockopt(SO_REUSEADDR)"); if (bind(server_fd, (const struct sockaddr *)&listen_addr, addr_len) == -1) error(1, errno, "bind"); if (listen(server_fd, 128) == -1) error(1, errno, "listen"); if (pthread_create(&server_thread, NULL, start_server, (void *)(unsigned long)server_fd) != 0) error(1, errno, "pthread_create"); fd = socket(family, SOCK_STREAM, 0); if (fd < 0) error(1, errno, "client socket"); setup_loopback_addr(family, &addr); if (connect(fd, (const struct sockaddr *)&addr, addr_len) == -1) error(1, errno, "connect"); if (setsockopt(fd, SOL_TCP, TCP_INQ, &one, sizeof(one)) != 0) error(1, errno, "setsockopt(TCP_INQ)"); msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_iov = iov; msg.msg_iovlen = 1; msg.msg_control = cmsgbuf; msg.msg_controllen = sizeof(cmsgbuf); msg.msg_flags = 0; buf = malloc(BUF_SIZE); iov[0].iov_base = buf; iov[0].iov_len = BUF_SIZE / 2; if (recvmsg(fd, &msg, 0) != iov[0].iov_len) error(1, errno, "recvmsg"); if (msg.msg_flags & MSG_CTRUNC) error(1, 0, "control message is truncated"); for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) if (cm->cmsg_level == SOL_TCP && cm->cmsg_type == TCP_CM_INQ) inq = *((int *) CMSG_DATA(cm)); if (inq != BUF_SIZE - iov[0].iov_len) { fprintf(stderr, "unexpected inq: %d\n", inq); exit(1); } printf("PASSED\n"); free(buf); close(fd); return 0; }
linux-master
tools/testing/selftests/net/tcp_inq.c
// SPDX-License-Identifier: GPL-2.0 /* Test IPV6_FLOWINFO cmsg on send and recv */ #define _GNU_SOURCE #include <arpa/inet.h> #include <asm/byteorder.h> #include <error.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/icmpv6.h> #include <linux/in6.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> /* uapi/glibc weirdness may leave this undefined */ #ifndef IPV6_FLOWINFO #define IPV6_FLOWINFO 11 #endif #ifndef IPV6_FLOWLABEL_MGR #define IPV6_FLOWLABEL_MGR 32 #endif #ifndef IPV6_FLOWINFO_SEND #define IPV6_FLOWINFO_SEND 33 #endif #define FLOWLABEL_WILDCARD ((uint32_t) -1) static const char cfg_data[] = "a"; static uint32_t cfg_label = 1; static bool use_ping; static bool use_flowinfo_send; static struct icmp6hdr icmp6 = { .icmp6_type = ICMPV6_ECHO_REQUEST }; static struct sockaddr_in6 addr = { .sin6_family = AF_INET6, .sin6_addr = IN6ADDR_LOOPBACK_INIT, }; static void do_send(int fd, bool with_flowlabel, uint32_t flowlabel) { char control[CMSG_SPACE(sizeof(flowlabel))] = {0}; struct msghdr msg = {0}; struct iovec iov = { .iov_base = (char *)cfg_data, .iov_len = sizeof(cfg_data) }; int ret; if (use_ping) { iov.iov_base = &icmp6; iov.iov_len = sizeof(icmp6); } msg.msg_iov = &iov; msg.msg_iovlen = 1; if (use_flowinfo_send) { msg.msg_name = &addr; msg.msg_namelen = sizeof(addr); } else if (with_flowlabel) { struct cmsghdr *cm; cm = (void *)control; cm->cmsg_len = CMSG_LEN(sizeof(flowlabel)); cm->cmsg_level = SOL_IPV6; cm->cmsg_type = IPV6_FLOWINFO; *(uint32_t *)CMSG_DATA(cm) = htonl(flowlabel); msg.msg_control = control; msg.msg_controllen = sizeof(control); } ret = sendmsg(fd, &msg, 0); if (ret == -1) error(1, errno, "send"); if (with_flowlabel) fprintf(stderr, "sent with label %u\n", flowlabel); else fprintf(stderr, "sent without label\n"); } static void do_recv(int fd, bool with_flowlabel, uint32_t expect) { char control[CMSG_SPACE(sizeof(expect))]; char data[sizeof(cfg_data)]; struct msghdr msg = {0}; struct iovec iov = {0}; struct cmsghdr *cm; uint32_t flowlabel; int ret; iov.iov_base = data; iov.iov_len = sizeof(data); msg.msg_iov = &iov; msg.msg_iovlen = 1; memset(control, 0, sizeof(control)); msg.msg_control = control; msg.msg_controllen = sizeof(control); ret = recvmsg(fd, &msg, 0); if (ret == -1) error(1, errno, "recv"); if (use_ping) goto parse_cmsg; if (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC)) error(1, 0, "recv: truncated"); if (ret != sizeof(cfg_data)) error(1, 0, "recv: length mismatch"); if (memcmp(data, cfg_data, sizeof(data))) error(1, 0, "recv: data mismatch"); parse_cmsg: cm = CMSG_FIRSTHDR(&msg); if (with_flowlabel) { if (!cm) error(1, 0, "recv: missing cmsg"); if (CMSG_NXTHDR(&msg, cm)) error(1, 0, "recv: too many cmsg"); if (cm->cmsg_level != SOL_IPV6 || cm->cmsg_type != IPV6_FLOWINFO) error(1, 0, "recv: unexpected cmsg level or type"); flowlabel = ntohl(*(uint32_t *)CMSG_DATA(cm)); fprintf(stderr, "recv with label %u\n", flowlabel); if (expect != FLOWLABEL_WILDCARD && expect != flowlabel) { fprintf(stderr, "recv: incorrect flowlabel %u != %u\n", flowlabel, expect); error(1, 0, "recv: flowlabel is wrong"); } } else { fprintf(stderr, "recv without label\n"); } } static bool get_autoflowlabel_enabled(void) { int fd, ret; char val; fd = open("/proc/sys/net/ipv6/auto_flowlabels", O_RDONLY); if (fd == -1) error(1, errno, "open sysctl"); ret = read(fd, &val, 1); if (ret == -1) error(1, errno, "read sysctl"); if (ret == 0) error(1, 0, "read sysctl: 0"); if (close(fd)) error(1, errno, "close sysctl"); return val == '1'; } static void flowlabel_get(int fd, uint32_t label, uint8_t share, uint16_t flags) { struct in6_flowlabel_req req = { .flr_action = IPV6_FL_A_GET, .flr_label = htonl(label), .flr_flags = flags, .flr_share = share, }; /* do not pass IPV6_ADDR_ANY or IPV6_ADDR_MAPPED */ req.flr_dst.s6_addr[0] = 0xfd; req.flr_dst.s6_addr[15] = 0x1; if (setsockopt(fd, SOL_IPV6, IPV6_FLOWLABEL_MGR, &req, sizeof(req))) error(1, errno, "setsockopt flowlabel get"); } static void parse_opts(int argc, char **argv) { int c; while ((c = getopt(argc, argv, "l:ps")) != -1) { switch (c) { case 'l': cfg_label = strtoul(optarg, NULL, 0); break; case 'p': use_ping = true; break; case 's': use_flowinfo_send = true; break; default: error(1, 0, "%s: parse error", argv[0]); } } } int main(int argc, char **argv) { const int one = 1; int fdt, fdr; int prot = 0; addr.sin6_port = htons(8000); parse_opts(argc, argv); if (use_ping) { fprintf(stderr, "attempting to use ping sockets\n"); prot = IPPROTO_ICMPV6; } fdt = socket(PF_INET6, SOCK_DGRAM, prot); if (fdt == -1) error(1, errno, "socket t"); fdr = use_ping ? fdt : socket(PF_INET6, SOCK_DGRAM, 0); if (fdr == -1) error(1, errno, "socket r"); if (connect(fdt, (void *)&addr, sizeof(addr))) error(1, errno, "connect"); if (!use_ping && bind(fdr, (void *)&addr, sizeof(addr))) error(1, errno, "bind"); flowlabel_get(fdt, cfg_label, IPV6_FL_S_EXCL, IPV6_FL_F_CREATE); if (setsockopt(fdr, SOL_IPV6, IPV6_FLOWINFO, &one, sizeof(one))) error(1, errno, "setsockopt flowinfo"); if (get_autoflowlabel_enabled()) { fprintf(stderr, "send no label: recv auto flowlabel\n"); do_send(fdt, false, 0); do_recv(fdr, true, FLOWLABEL_WILDCARD); } else { fprintf(stderr, "send no label: recv no label (auto off)\n"); do_send(fdt, false, 0); do_recv(fdr, false, 0); } if (use_flowinfo_send) { fprintf(stderr, "using IPV6_FLOWINFO_SEND to send label\n"); addr.sin6_flowinfo = htonl(cfg_label); if (setsockopt(fdt, SOL_IPV6, IPV6_FLOWINFO_SEND, &one, sizeof(one)) == -1) error(1, errno, "setsockopt flowinfo_send"); } fprintf(stderr, "send label\n"); do_send(fdt, true, cfg_label); do_recv(fdr, true, cfg_label); if (close(fdr)) error(1, errno, "close r"); if (!use_ping && close(fdt)) error(1, errno, "close t"); return 0; }
linux-master
tools/testing/selftests/net/ipv6_flowlabel.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <arpa/inet.h> #include <error.h> #include <errno.h> #include <limits.h> #include <linux/errqueue.h> #include <linux/if_packet.h> #include <linux/socket.h> #include <linux/sockios.h> #include <net/ethernet.h> #include <net/if.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <poll.h> #include <sched.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #ifndef UDP_GRO #define UDP_GRO 104 #endif static int cfg_port = 8000; static bool cfg_tcp; static bool cfg_verify; static bool cfg_read_all; static bool cfg_gro_segment; static int cfg_family = PF_INET6; static int cfg_alen = sizeof(struct sockaddr_in6); static int cfg_expected_pkt_nr; static int cfg_expected_pkt_len; static int cfg_expected_gso_size; static int cfg_connect_timeout_ms; static int cfg_rcv_timeout_ms; static struct sockaddr_storage cfg_bind_addr; static bool interrupted; static unsigned long packets, bytes; static void sigint_handler(int signum) { if (signum == SIGINT) interrupted = true; } static void setup_sockaddr(int domain, const char *str_addr, void *sockaddr) { struct sockaddr_in6 *addr6 = (void *) sockaddr; struct sockaddr_in *addr4 = (void *) sockaddr; switch (domain) { case PF_INET: addr4->sin_family = AF_INET; addr4->sin_port = htons(cfg_port); if (inet_pton(AF_INET, str_addr, &(addr4->sin_addr)) != 1) error(1, 0, "ipv4 parse error: %s", str_addr); break; case PF_INET6: addr6->sin6_family = AF_INET6; addr6->sin6_port = htons(cfg_port); if (inet_pton(AF_INET6, str_addr, &(addr6->sin6_addr)) != 1) error(1, 0, "ipv6 parse error: %s", str_addr); break; default: error(1, 0, "illegal domain"); } } static unsigned long gettimeofday_ms(void) { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); } static void do_poll(int fd, int timeout_ms) { struct pollfd pfd; int ret; pfd.events = POLLIN; pfd.revents = 0; pfd.fd = fd; do { ret = poll(&pfd, 1, 10); if (interrupted) break; if (ret == -1) error(1, errno, "poll"); if (ret == 0) { if (!timeout_ms) continue; timeout_ms -= 10; if (timeout_ms <= 0) { interrupted = true; break; } /* no events and more time to wait, do poll again */ continue; } if (pfd.revents != POLLIN) error(1, errno, "poll: 0x%x expected 0x%x\n", pfd.revents, POLLIN); } while (!ret); } static int do_socket(bool do_tcp) { int fd, val; fd = socket(cfg_family, cfg_tcp ? SOCK_STREAM : SOCK_DGRAM, 0); if (fd == -1) error(1, errno, "socket"); val = 1 << 21; if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val))) error(1, errno, "setsockopt rcvbuf"); val = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val))) error(1, errno, "setsockopt reuseport"); if (bind(fd, (void *)&cfg_bind_addr, cfg_alen)) error(1, errno, "bind"); if (do_tcp) { int accept_fd = fd; if (listen(accept_fd, 1)) error(1, errno, "listen"); do_poll(accept_fd, cfg_connect_timeout_ms); if (interrupted) exit(0); fd = accept(accept_fd, NULL, NULL); if (fd == -1) error(1, errno, "accept"); if (close(accept_fd)) error(1, errno, "close accept fd"); } return fd; } /* Flush all outstanding bytes for the tcp receive queue */ static void do_flush_tcp(int fd) { int ret; while (true) { /* MSG_TRUNC flushes up to len bytes */ ret = recv(fd, NULL, 1 << 21, MSG_TRUNC | MSG_DONTWAIT); if (ret == -1 && errno == EAGAIN) return; if (ret == -1) error(1, errno, "flush"); if (ret == 0) { /* client detached */ exit(0); } packets++; bytes += ret; } } static char sanitized_char(char val) { return (val >= 'a' && val <= 'z') ? val : '.'; } static void do_verify_udp(const char *data, int len) { char cur = data[0]; int i; /* verify contents */ if (cur < 'a' || cur > 'z') error(1, 0, "data initial byte out of range"); for (i = 1; i < len; i++) { if (cur == 'z') cur = 'a'; else cur++; if (data[i] != cur) error(1, 0, "data[%d]: len %d, %c(%hhu) != %c(%hhu)\n", i, len, sanitized_char(data[i]), data[i], sanitized_char(cur), cur); } } static int recv_msg(int fd, char *buf, int len, int *gso_size) { char control[CMSG_SPACE(sizeof(int))] = {0}; struct msghdr msg = {0}; struct iovec iov = {0}; struct cmsghdr *cmsg; int ret; iov.iov_base = buf; iov.iov_len = len; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = control; msg.msg_controllen = sizeof(control); *gso_size = -1; ret = recvmsg(fd, &msg, MSG_TRUNC | MSG_DONTWAIT); if (ret != -1) { for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) { if (cmsg->cmsg_level == SOL_UDP && cmsg->cmsg_type == UDP_GRO) { *gso_size = *(int *)CMSG_DATA(cmsg); break; } } } return ret; } /* Flush all outstanding datagrams. Verify first few bytes of each. */ static void do_flush_udp(int fd) { static char rbuf[ETH_MAX_MTU]; int ret, len, gso_size = 0, budget = 256; len = cfg_read_all ? sizeof(rbuf) : 0; while (budget--) { /* MSG_TRUNC will make return value full datagram length */ if (!cfg_expected_gso_size) ret = recv(fd, rbuf, len, MSG_TRUNC | MSG_DONTWAIT); else ret = recv_msg(fd, rbuf, len, &gso_size); if (ret == -1 && errno == EAGAIN) break; if (ret == -1) error(1, errno, "recv"); if (cfg_expected_pkt_len && ret != cfg_expected_pkt_len) error(1, 0, "recv: bad packet len, got %d," " expected %d\n", ret, cfg_expected_pkt_len); if (len && cfg_verify) { if (ret == 0) error(1, errno, "recv: 0 byte datagram\n"); do_verify_udp(rbuf, ret); } if (cfg_expected_gso_size && cfg_expected_gso_size != gso_size) error(1, 0, "recv: bad gso size, got %d, expected %d " "(-1 == no gso cmsg))\n", gso_size, cfg_expected_gso_size); packets++; bytes += ret; if (cfg_expected_pkt_nr && packets >= cfg_expected_pkt_nr) break; } } static void usage(const char *filepath) { error(1, 0, "Usage: %s [-C connect_timeout] [-Grtv] [-b addr] [-p port]" " [-l pktlen] [-n packetnr] [-R rcv_timeout] [-S gsosize]", filepath); } static void parse_opts(int argc, char **argv) { const char *bind_addr = NULL; int c; while ((c = getopt(argc, argv, "4b:C:Gl:n:p:rR:S:tv")) != -1) { switch (c) { case '4': cfg_family = PF_INET; cfg_alen = sizeof(struct sockaddr_in); break; case 'b': bind_addr = optarg; break; case 'C': cfg_connect_timeout_ms = strtoul(optarg, NULL, 0); break; case 'G': cfg_gro_segment = true; break; case 'l': cfg_expected_pkt_len = strtoul(optarg, NULL, 0); break; case 'n': cfg_expected_pkt_nr = strtoul(optarg, NULL, 0); break; case 'p': cfg_port = strtoul(optarg, NULL, 0); break; case 'r': cfg_read_all = true; break; case 'R': cfg_rcv_timeout_ms = strtoul(optarg, NULL, 0); break; case 'S': cfg_expected_gso_size = strtol(optarg, NULL, 0); break; case 't': cfg_tcp = true; break; case 'v': cfg_verify = true; cfg_read_all = true; break; default: exit(1); } } if (!bind_addr) bind_addr = cfg_family == PF_INET6 ? "::" : "0.0.0.0"; setup_sockaddr(cfg_family, bind_addr, &cfg_bind_addr); if (optind != argc) usage(argv[0]); if (cfg_tcp && cfg_verify) error(1, 0, "TODO: implement verify mode for tcp"); } static void do_recv(void) { int timeout_ms = cfg_tcp ? cfg_rcv_timeout_ms : cfg_connect_timeout_ms; unsigned long tnow, treport; int fd; fd = do_socket(cfg_tcp); if (cfg_gro_segment && !cfg_tcp) { int val = 1; if (setsockopt(fd, IPPROTO_UDP, UDP_GRO, &val, sizeof(val))) error(1, errno, "setsockopt UDP_GRO"); } treport = gettimeofday_ms() + 1000; do { do_poll(fd, timeout_ms); if (cfg_tcp) do_flush_tcp(fd); else do_flush_udp(fd); tnow = gettimeofday_ms(); if (tnow > treport) { if (packets) fprintf(stderr, "%s rx: %6lu MB/s %8lu calls/s\n", cfg_tcp ? "tcp" : "udp", bytes >> 20, packets); bytes = packets = 0; treport = tnow + 1000; } timeout_ms = cfg_rcv_timeout_ms; } while (!interrupted); if (cfg_expected_pkt_nr && (packets != cfg_expected_pkt_nr)) error(1, 0, "wrong packet number! got %ld, expected %d\n", packets, cfg_expected_pkt_nr); if (close(fd)) error(1, errno, "close"); } int main(int argc, char **argv) { parse_opts(argc, argv); signal(SIGINT, sigint_handler); do_recv(); return 0; }
linux-master
tools/testing/selftests/net/udpgso_bench_rx.c
// SPDX-License-Identifier: GPL-2.0 /* * Test functionality of BPF filters with SO_REUSEPORT. Same test as * in reuseport_bpf_cpu, only as one socket per NUMA node. */ #define _GNU_SOURCE #include <arpa/inet.h> #include <errno.h> #include <error.h> #include <linux/filter.h> #include <linux/bpf.h> #include <linux/in.h> #include <linux/unistd.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <numa.h> #include "../kselftest.h" static const int PORT = 8888; static void build_rcv_group(int *rcv_fd, size_t len, int family, int proto) { struct sockaddr_storage addr; struct sockaddr_in *addr4; struct sockaddr_in6 *addr6; size_t i; int opt; switch (family) { case AF_INET: addr4 = (struct sockaddr_in *)&addr; addr4->sin_family = AF_INET; addr4->sin_addr.s_addr = htonl(INADDR_ANY); addr4->sin_port = htons(PORT); break; case AF_INET6: addr6 = (struct sockaddr_in6 *)&addr; addr6->sin6_family = AF_INET6; addr6->sin6_addr = in6addr_any; addr6->sin6_port = htons(PORT); break; default: error(1, 0, "Unsupported family %d", family); } for (i = 0; i < len; ++i) { rcv_fd[i] = socket(family, proto, 0); if (rcv_fd[i] < 0) error(1, errno, "failed to create receive socket"); opt = 1; if (setsockopt(rcv_fd[i], SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT"); if (bind(rcv_fd[i], (struct sockaddr *)&addr, sizeof(addr))) error(1, errno, "failed to bind receive socket"); if (proto == SOCK_STREAM && listen(rcv_fd[i], len * 10)) error(1, errno, "failed to listen on receive port"); } } static void attach_bpf(int fd) { static char bpf_log_buf[65536]; static const char bpf_license[] = ""; int bpf_fd; const struct bpf_insn prog[] = { /* R0 = bpf_get_numa_node_id() */ { BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_numa_node_id }, /* return R0 */ { BPF_JMP | BPF_EXIT, 0, 0, 0, 0 } }; union bpf_attr attr; memset(&attr, 0, sizeof(attr)); attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; attr.insn_cnt = ARRAY_SIZE(prog); attr.insns = (unsigned long) &prog; attr.license = (unsigned long) &bpf_license; attr.log_buf = (unsigned long) &bpf_log_buf; attr.log_size = sizeof(bpf_log_buf); attr.log_level = 1; bpf_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr)); if (bpf_fd < 0) error(1, errno, "ebpf error. log:\n%s\n", bpf_log_buf); if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_REUSEPORT_EBPF, &bpf_fd, sizeof(bpf_fd))) error(1, errno, "failed to set SO_ATTACH_REUSEPORT_EBPF"); close(bpf_fd); } static void send_from_node(int node_id, int family, int proto) { struct sockaddr_storage saddr, daddr; struct sockaddr_in *saddr4, *daddr4; struct sockaddr_in6 *saddr6, *daddr6; int fd; switch (family) { case AF_INET: saddr4 = (struct sockaddr_in *)&saddr; saddr4->sin_family = AF_INET; saddr4->sin_addr.s_addr = htonl(INADDR_ANY); saddr4->sin_port = 0; daddr4 = (struct sockaddr_in *)&daddr; daddr4->sin_family = AF_INET; daddr4->sin_addr.s_addr = htonl(INADDR_LOOPBACK); daddr4->sin_port = htons(PORT); break; case AF_INET6: saddr6 = (struct sockaddr_in6 *)&saddr; saddr6->sin6_family = AF_INET6; saddr6->sin6_addr = in6addr_any; saddr6->sin6_port = 0; daddr6 = (struct sockaddr_in6 *)&daddr; daddr6->sin6_family = AF_INET6; daddr6->sin6_addr = in6addr_loopback; daddr6->sin6_port = htons(PORT); break; default: error(1, 0, "Unsupported family %d", family); } if (numa_run_on_node(node_id) < 0) error(1, errno, "failed to pin to node"); fd = socket(family, proto, 0); if (fd < 0) error(1, errno, "failed to create send socket"); if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr))) error(1, errno, "failed to bind send socket"); if (connect(fd, (struct sockaddr *)&daddr, sizeof(daddr))) error(1, errno, "failed to connect send socket"); if (send(fd, "a", 1, 0) < 0) error(1, errno, "failed to send message"); close(fd); } static void receive_on_node(int *rcv_fd, int len, int epfd, int node_id, int proto) { struct epoll_event ev; int i, fd; char buf[8]; i = epoll_wait(epfd, &ev, 1, -1); if (i < 0) error(1, errno, "epoll_wait failed"); if (proto == SOCK_STREAM) { fd = accept(ev.data.fd, NULL, NULL); if (fd < 0) error(1, errno, "failed to accept"); i = recv(fd, buf, sizeof(buf), 0); close(fd); } else { i = recv(ev.data.fd, buf, sizeof(buf), 0); } if (i < 0) error(1, errno, "failed to recv"); for (i = 0; i < len; ++i) if (ev.data.fd == rcv_fd[i]) break; if (i == len) error(1, 0, "failed to find socket"); fprintf(stderr, "send node %d, receive socket %d\n", node_id, i); if (node_id != i) error(1, 0, "node id/receive socket mismatch"); } static void test(int *rcv_fd, int len, int family, int proto) { struct epoll_event ev; int epfd, node; build_rcv_group(rcv_fd, len, family, proto); attach_bpf(rcv_fd[0]); epfd = epoll_create(1); if (epfd < 0) error(1, errno, "failed to create epoll"); for (node = 0; node < len; ++node) { ev.events = EPOLLIN; ev.data.fd = rcv_fd[node]; if (epoll_ctl(epfd, EPOLL_CTL_ADD, rcv_fd[node], &ev)) error(1, errno, "failed to register sock epoll"); } /* Forward iterate */ for (node = 0; node < len; ++node) { if (!numa_bitmask_isbitset(numa_nodes_ptr, node)) continue; send_from_node(node, family, proto); receive_on_node(rcv_fd, len, epfd, node, proto); } /* Reverse iterate */ for (node = len - 1; node >= 0; --node) { if (!numa_bitmask_isbitset(numa_nodes_ptr, node)) continue; send_from_node(node, family, proto); receive_on_node(rcv_fd, len, epfd, node, proto); } close(epfd); for (node = 0; node < len; ++node) close(rcv_fd[node]); } int main(void) { int *rcv_fd, nodes; if (numa_available() < 0) ksft_exit_skip("no numa api support\n"); nodes = numa_max_node() + 1; rcv_fd = calloc(nodes, sizeof(int)); if (!rcv_fd) error(1, 0, "failed to allocate array"); fprintf(stderr, "---- IPv4 UDP ----\n"); test(rcv_fd, nodes, AF_INET, SOCK_DGRAM); fprintf(stderr, "---- IPv6 UDP ----\n"); test(rcv_fd, nodes, AF_INET6, SOCK_DGRAM); fprintf(stderr, "---- IPv4 TCP ----\n"); test(rcv_fd, nodes, AF_INET, SOCK_STREAM); fprintf(stderr, "---- IPv6 TCP ----\n"); test(rcv_fd, nodes, AF_INET6, SOCK_STREAM); free(rcv_fd); fprintf(stderr, "SUCCESS\n"); return 0; }
linux-master
tools/testing/selftests/net/reuseport_bpf_numa.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <stddef.h> #include <arpa/inet.h> #include <error.h> #include <errno.h> #include <net/if.h> #include <linux/in.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <netinet/if_ether.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/udp.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #ifndef ETH_MAX_MTU #define ETH_MAX_MTU 0xFFFFU #endif #ifndef UDP_SEGMENT #define UDP_SEGMENT 103 #endif #ifndef UDP_MAX_SEGMENTS #define UDP_MAX_SEGMENTS (1 << 6UL) #endif #define CONST_MTU_TEST 1500 #define CONST_HDRLEN_V4 (sizeof(struct iphdr) + sizeof(struct udphdr)) #define CONST_HDRLEN_V6 (sizeof(struct ip6_hdr) + sizeof(struct udphdr)) #define CONST_MSS_V4 (CONST_MTU_TEST - CONST_HDRLEN_V4) #define CONST_MSS_V6 (CONST_MTU_TEST - CONST_HDRLEN_V6) #define CONST_MAX_SEGS_V4 (ETH_MAX_MTU / CONST_MSS_V4) #define CONST_MAX_SEGS_V6 (ETH_MAX_MTU / CONST_MSS_V6) static bool cfg_do_ipv4; static bool cfg_do_ipv6; static bool cfg_do_connected; static bool cfg_do_connectionless; static bool cfg_do_msgmore; static bool cfg_do_setsockopt; static int cfg_specific_test_id = -1; static const char cfg_ifname[] = "lo"; static unsigned short cfg_port = 9000; static char buf[ETH_MAX_MTU]; struct testcase { int tlen; /* send() buffer size, may exceed mss */ bool tfail; /* send() call is expected to fail */ int gso_len; /* mss after applying gso */ int r_num_mss; /* recv(): number of calls of full mss */ int r_len_last; /* recv(): size of last non-mss dgram, if any */ }; const struct in6_addr addr6 = IN6ADDR_LOOPBACK_INIT; const struct in_addr addr4 = { .s_addr = __constant_htonl(INADDR_LOOPBACK + 2) }; struct testcase testcases_v4[] = { { /* no GSO: send a single byte */ .tlen = 1, .r_len_last = 1, }, { /* no GSO: send a single MSS */ .tlen = CONST_MSS_V4, .r_num_mss = 1, }, { /* no GSO: send a single MSS + 1B: fail */ .tlen = CONST_MSS_V4 + 1, .tfail = true, }, { /* send a single MSS: will fall back to no GSO */ .tlen = CONST_MSS_V4, .gso_len = CONST_MSS_V4, .r_num_mss = 1, }, { /* send a single MSS + 1B */ .tlen = CONST_MSS_V4 + 1, .gso_len = CONST_MSS_V4, .r_num_mss = 1, .r_len_last = 1, }, { /* send exactly 2 MSS */ .tlen = CONST_MSS_V4 * 2, .gso_len = CONST_MSS_V4, .r_num_mss = 2, }, { /* send 2 MSS + 1B */ .tlen = (CONST_MSS_V4 * 2) + 1, .gso_len = CONST_MSS_V4, .r_num_mss = 2, .r_len_last = 1, }, { /* send MAX segs */ .tlen = (ETH_MAX_MTU / CONST_MSS_V4) * CONST_MSS_V4, .gso_len = CONST_MSS_V4, .r_num_mss = (ETH_MAX_MTU / CONST_MSS_V4), }, { /* send MAX bytes */ .tlen = ETH_MAX_MTU - CONST_HDRLEN_V4, .gso_len = CONST_MSS_V4, .r_num_mss = CONST_MAX_SEGS_V4, .r_len_last = ETH_MAX_MTU - CONST_HDRLEN_V4 - (CONST_MAX_SEGS_V4 * CONST_MSS_V4), }, { /* send MAX + 1: fail */ .tlen = ETH_MAX_MTU - CONST_HDRLEN_V4 + 1, .gso_len = CONST_MSS_V4, .tfail = true, }, { /* send a single 1B MSS: will fall back to no GSO */ .tlen = 1, .gso_len = 1, .r_num_mss = 1, }, { /* send 2 1B segments */ .tlen = 2, .gso_len = 1, .r_num_mss = 2, }, { /* send 2B + 2B + 1B segments */ .tlen = 5, .gso_len = 2, .r_num_mss = 2, .r_len_last = 1, }, { /* send max number of min sized segments */ .tlen = UDP_MAX_SEGMENTS, .gso_len = 1, .r_num_mss = UDP_MAX_SEGMENTS, }, { /* send max number + 1 of min sized segments: fail */ .tlen = UDP_MAX_SEGMENTS + 1, .gso_len = 1, .tfail = true, }, { /* EOL */ } }; #ifndef IP6_MAX_MTU #define IP6_MAX_MTU (ETH_MAX_MTU + sizeof(struct ip6_hdr)) #endif struct testcase testcases_v6[] = { { /* no GSO: send a single byte */ .tlen = 1, .r_len_last = 1, }, { /* no GSO: send a single MSS */ .tlen = CONST_MSS_V6, .r_num_mss = 1, }, { /* no GSO: send a single MSS + 1B: fail */ .tlen = CONST_MSS_V6 + 1, .tfail = true, }, { /* send a single MSS: will fall back to no GSO */ .tlen = CONST_MSS_V6, .gso_len = CONST_MSS_V6, .r_num_mss = 1, }, { /* send a single MSS + 1B */ .tlen = CONST_MSS_V6 + 1, .gso_len = CONST_MSS_V6, .r_num_mss = 1, .r_len_last = 1, }, { /* send exactly 2 MSS */ .tlen = CONST_MSS_V6 * 2, .gso_len = CONST_MSS_V6, .r_num_mss = 2, }, { /* send 2 MSS + 1B */ .tlen = (CONST_MSS_V6 * 2) + 1, .gso_len = CONST_MSS_V6, .r_num_mss = 2, .r_len_last = 1, }, { /* send MAX segs */ .tlen = (IP6_MAX_MTU / CONST_MSS_V6) * CONST_MSS_V6, .gso_len = CONST_MSS_V6, .r_num_mss = (IP6_MAX_MTU / CONST_MSS_V6), }, { /* send MAX bytes */ .tlen = IP6_MAX_MTU - CONST_HDRLEN_V6, .gso_len = CONST_MSS_V6, .r_num_mss = CONST_MAX_SEGS_V6, .r_len_last = IP6_MAX_MTU - CONST_HDRLEN_V6 - (CONST_MAX_SEGS_V6 * CONST_MSS_V6), }, { /* send MAX + 1: fail */ .tlen = IP6_MAX_MTU - CONST_HDRLEN_V6 + 1, .gso_len = CONST_MSS_V6, .tfail = true, }, { /* send a single 1B MSS: will fall back to no GSO */ .tlen = 1, .gso_len = 1, .r_num_mss = 1, }, { /* send 2 1B segments */ .tlen = 2, .gso_len = 1, .r_num_mss = 2, }, { /* send 2B + 2B + 1B segments */ .tlen = 5, .gso_len = 2, .r_num_mss = 2, .r_len_last = 1, }, { /* send max number of min sized segments */ .tlen = UDP_MAX_SEGMENTS, .gso_len = 1, .r_num_mss = UDP_MAX_SEGMENTS, }, { /* send max number + 1 of min sized segments: fail */ .tlen = UDP_MAX_SEGMENTS + 1, .gso_len = 1, .tfail = true, }, { /* EOL */ } }; static unsigned int get_device_mtu(int fd, const char *ifname) { struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, ifname); if (ioctl(fd, SIOCGIFMTU, &ifr)) error(1, errno, "ioctl get mtu"); return ifr.ifr_mtu; } static void __set_device_mtu(int fd, const char *ifname, unsigned int mtu) { struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); ifr.ifr_mtu = mtu; strcpy(ifr.ifr_name, ifname); if (ioctl(fd, SIOCSIFMTU, &ifr)) error(1, errno, "ioctl set mtu"); } static void set_device_mtu(int fd, int mtu) { int val; val = get_device_mtu(fd, cfg_ifname); fprintf(stderr, "device mtu (orig): %u\n", val); __set_device_mtu(fd, cfg_ifname, mtu); val = get_device_mtu(fd, cfg_ifname); if (val != mtu) error(1, 0, "unable to set device mtu to %u\n", val); fprintf(stderr, "device mtu (test): %u\n", val); } static void set_pmtu_discover(int fd, bool is_ipv4) { int level, name, val; if (is_ipv4) { level = SOL_IP; name = IP_MTU_DISCOVER; val = IP_PMTUDISC_DO; } else { level = SOL_IPV6; name = IPV6_MTU_DISCOVER; val = IPV6_PMTUDISC_DO; } if (setsockopt(fd, level, name, &val, sizeof(val))) error(1, errno, "setsockopt path mtu"); } static unsigned int get_path_mtu(int fd, bool is_ipv4) { socklen_t vallen; unsigned int mtu; int ret; vallen = sizeof(mtu); if (is_ipv4) ret = getsockopt(fd, SOL_IP, IP_MTU, &mtu, &vallen); else ret = getsockopt(fd, SOL_IPV6, IPV6_MTU, &mtu, &vallen); if (ret) error(1, errno, "getsockopt mtu"); fprintf(stderr, "path mtu (read): %u\n", mtu); return mtu; } /* very wordy version of system("ip route add dev lo mtu 1500 127.0.0.3/32") */ static void set_route_mtu(int mtu, bool is_ipv4) { struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK }; struct nlmsghdr *nh; struct rtattr *rta; struct rtmsg *rt; char data[NLMSG_ALIGN(sizeof(*nh)) + NLMSG_ALIGN(sizeof(*rt)) + NLMSG_ALIGN(RTA_LENGTH(sizeof(addr6))) + NLMSG_ALIGN(RTA_LENGTH(sizeof(int))) + NLMSG_ALIGN(RTA_LENGTH(0) + RTA_LENGTH(sizeof(int)))]; int fd, ret, alen, off = 0; alen = is_ipv4 ? sizeof(addr4) : sizeof(addr6); fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (fd == -1) error(1, errno, "socket netlink"); memset(data, 0, sizeof(data)); nh = (void *)data; nh->nlmsg_type = RTM_NEWROUTE; nh->nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE; off += NLMSG_ALIGN(sizeof(*nh)); rt = (void *)(data + off); rt->rtm_family = is_ipv4 ? AF_INET : AF_INET6; rt->rtm_table = RT_TABLE_MAIN; rt->rtm_dst_len = alen << 3; rt->rtm_protocol = RTPROT_BOOT; rt->rtm_scope = RT_SCOPE_UNIVERSE; rt->rtm_type = RTN_UNICAST; off += NLMSG_ALIGN(sizeof(*rt)); rta = (void *)(data + off); rta->rta_type = RTA_DST; rta->rta_len = RTA_LENGTH(alen); if (is_ipv4) memcpy(RTA_DATA(rta), &addr4, alen); else memcpy(RTA_DATA(rta), &addr6, alen); off += NLMSG_ALIGN(rta->rta_len); rta = (void *)(data + off); rta->rta_type = RTA_OIF; rta->rta_len = RTA_LENGTH(sizeof(int)); *((int *)(RTA_DATA(rta))) = 1; //if_nametoindex("lo"); off += NLMSG_ALIGN(rta->rta_len); /* MTU is a subtype in a metrics type */ rta = (void *)(data + off); rta->rta_type = RTA_METRICS; rta->rta_len = RTA_LENGTH(0) + RTA_LENGTH(sizeof(int)); off += NLMSG_ALIGN(rta->rta_len); /* now fill MTU subtype. Note that it fits within above rta_len */ rta = (void *)(((char *) rta) + RTA_LENGTH(0)); rta->rta_type = RTAX_MTU; rta->rta_len = RTA_LENGTH(sizeof(int)); *((int *)(RTA_DATA(rta))) = mtu; nh->nlmsg_len = off; ret = sendto(fd, data, off, 0, (void *)&nladdr, sizeof(nladdr)); if (ret != off) error(1, errno, "send netlink: %uB != %uB\n", ret, off); if (close(fd)) error(1, errno, "close netlink"); fprintf(stderr, "route mtu (test): %u\n", mtu); } static bool __send_one(int fd, struct msghdr *msg, int flags) { int ret; ret = sendmsg(fd, msg, flags); if (ret == -1 && (errno == EMSGSIZE || errno == ENOMEM || errno == EINVAL)) return false; if (ret == -1) error(1, errno, "sendmsg"); if (ret != msg->msg_iov->iov_len) error(1, 0, "sendto: %d != %llu", ret, (unsigned long long)msg->msg_iov->iov_len); if (msg->msg_flags) error(1, 0, "sendmsg: return flags 0x%x\n", msg->msg_flags); return true; } static bool send_one(int fd, int len, int gso_len, struct sockaddr *addr, socklen_t alen) { char control[CMSG_SPACE(sizeof(uint16_t))] = {0}; struct msghdr msg = {0}; struct iovec iov = {0}; struct cmsghdr *cm; iov.iov_base = buf; iov.iov_len = len; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_name = addr; msg.msg_namelen = alen; if (gso_len && !cfg_do_setsockopt) { msg.msg_control = control; msg.msg_controllen = sizeof(control); cm = CMSG_FIRSTHDR(&msg); cm->cmsg_level = SOL_UDP; cm->cmsg_type = UDP_SEGMENT; cm->cmsg_len = CMSG_LEN(sizeof(uint16_t)); *((uint16_t *) CMSG_DATA(cm)) = gso_len; } /* If MSG_MORE, send 1 byte followed by remainder */ if (cfg_do_msgmore && len > 1) { iov.iov_len = 1; if (!__send_one(fd, &msg, MSG_MORE)) error(1, 0, "send 1B failed"); iov.iov_base++; iov.iov_len = len - 1; } return __send_one(fd, &msg, 0); } static int recv_one(int fd, int flags) { int ret; ret = recv(fd, buf, sizeof(buf), flags); if (ret == -1 && errno == EAGAIN && (flags & MSG_DONTWAIT)) return 0; if (ret == -1) error(1, errno, "recv"); return ret; } static void run_one(struct testcase *test, int fdt, int fdr, struct sockaddr *addr, socklen_t alen) { int i, ret, val, mss; bool sent; fprintf(stderr, "ipv%d tx:%d gso:%d %s\n", addr->sa_family == AF_INET ? 4 : 6, test->tlen, test->gso_len, test->tfail ? "(fail)" : ""); val = test->gso_len; if (cfg_do_setsockopt) { if (setsockopt(fdt, SOL_UDP, UDP_SEGMENT, &val, sizeof(val))) error(1, errno, "setsockopt udp segment"); } sent = send_one(fdt, test->tlen, test->gso_len, addr, alen); if (sent && test->tfail) error(1, 0, "send succeeded while expecting failure"); if (!sent && !test->tfail) error(1, 0, "send failed while expecting success"); if (!sent) return; if (test->gso_len) mss = test->gso_len; else mss = addr->sa_family == AF_INET ? CONST_MSS_V4 : CONST_MSS_V6; /* Recv all full MSS datagrams */ for (i = 0; i < test->r_num_mss; i++) { ret = recv_one(fdr, 0); if (ret != mss) error(1, 0, "recv.%d: %d != %d", i, ret, mss); } /* Recv the non-full last datagram, if tlen was not a multiple of mss */ if (test->r_len_last) { ret = recv_one(fdr, 0); if (ret != test->r_len_last) error(1, 0, "recv.%d: %d != %d (last)", i, ret, test->r_len_last); } /* Verify received all data */ ret = recv_one(fdr, MSG_DONTWAIT); if (ret) error(1, 0, "recv: unexpected datagram"); } static void run_all(int fdt, int fdr, struct sockaddr *addr, socklen_t alen) { struct testcase *tests, *test; tests = addr->sa_family == AF_INET ? testcases_v4 : testcases_v6; for (test = tests; test->tlen; test++) { /* if a specific test is given, then skip all others */ if (cfg_specific_test_id == -1 || cfg_specific_test_id == test - tests) run_one(test, fdt, fdr, addr, alen); } } static void run_test(struct sockaddr *addr, socklen_t alen) { struct timeval tv = { .tv_usec = 100 * 1000 }; int fdr, fdt, val; fdr = socket(addr->sa_family, SOCK_DGRAM, 0); if (fdr == -1) error(1, errno, "socket r"); if (bind(fdr, addr, alen)) error(1, errno, "bind"); /* Have tests fail quickly instead of hang */ if (setsockopt(fdr, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))) error(1, errno, "setsockopt rcv timeout"); fdt = socket(addr->sa_family, SOCK_DGRAM, 0); if (fdt == -1) error(1, errno, "socket t"); /* Do not fragment these datagrams: only succeed if GSO works */ set_pmtu_discover(fdt, addr->sa_family == AF_INET); if (cfg_do_connectionless) { set_device_mtu(fdt, CONST_MTU_TEST); run_all(fdt, fdr, addr, alen); } if (cfg_do_connected) { set_device_mtu(fdt, CONST_MTU_TEST + 100); set_route_mtu(CONST_MTU_TEST, addr->sa_family == AF_INET); if (connect(fdt, addr, alen)) error(1, errno, "connect"); val = get_path_mtu(fdt, addr->sa_family == AF_INET); if (val != CONST_MTU_TEST) error(1, 0, "bad path mtu %u\n", val); run_all(fdt, fdr, addr, 0 /* use connected addr */); } if (close(fdt)) error(1, errno, "close t"); if (close(fdr)) error(1, errno, "close r"); } static void run_test_v4(void) { struct sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_port = htons(cfg_port); addr.sin_addr = addr4; run_test((void *)&addr, sizeof(addr)); } static void run_test_v6(void) { struct sockaddr_in6 addr = {0}; addr.sin6_family = AF_INET6; addr.sin6_port = htons(cfg_port); addr.sin6_addr = addr6; run_test((void *)&addr, sizeof(addr)); } static void parse_opts(int argc, char **argv) { int c; while ((c = getopt(argc, argv, "46cCmst:")) != -1) { switch (c) { case '4': cfg_do_ipv4 = true; break; case '6': cfg_do_ipv6 = true; break; case 'c': cfg_do_connected = true; break; case 'C': cfg_do_connectionless = true; break; case 'm': cfg_do_msgmore = true; break; case 's': cfg_do_setsockopt = true; break; case 't': cfg_specific_test_id = strtoul(optarg, NULL, 0); break; default: error(1, 0, "%s: parse error", argv[0]); } } } int main(int argc, char **argv) { parse_opts(argc, argv); if (cfg_do_ipv4) run_test_v4(); if (cfg_do_ipv6) run_test_v6(); fprintf(stderr, "OK\n"); return 0; }
linux-master
tools/testing/selftests/net/udpgso.c
// SPDX-License-Identifier: GPL-2.0-only /* * This program demonstrates how the various time stamping features in * the Linux kernel work. It emulates the behavior of a PTP * implementation in stand-alone master mode by sending PTPv1 Sync * multicasts once every second. It looks for similar packets, but * beyond that doesn't actually implement PTP. * * Outgoing packets are time stamped with SO_TIMESTAMPING with or * without hardware support. * * Incoming packets are time stamped with SO_TIMESTAMPING with or * without hardware support, SIOCGSTAMP[NS] (per-socket time stamp) and * SO_TIMESTAMP[NS]. * * Copyright (C) 2009 Intel Corporation. * Author: Patrick Ohly <[email protected]> */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/time.h> #include <sys/socket.h> #include <sys/select.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include <net/if.h> #include <asm/types.h> #include <linux/net_tstamp.h> #include <linux/errqueue.h> #include <linux/sockios.h> #ifndef SO_TIMESTAMPING # define SO_TIMESTAMPING 37 # define SCM_TIMESTAMPING SO_TIMESTAMPING #endif #ifndef SO_TIMESTAMPNS # define SO_TIMESTAMPNS 35 #endif static void usage(const char *error) { if (error) printf("invalid option: %s\n", error); printf("timestamping <interface> [bind_phc_index] [option]*\n\n" "Options:\n" " IP_MULTICAST_LOOP - looping outgoing multicasts\n" " SO_TIMESTAMP - normal software time stamping, ms resolution\n" " SO_TIMESTAMPNS - more accurate software time stamping\n" " SOF_TIMESTAMPING_TX_HARDWARE - hardware time stamping of outgoing packets\n" " SOF_TIMESTAMPING_TX_SOFTWARE - software fallback for outgoing packets\n" " SOF_TIMESTAMPING_RX_HARDWARE - hardware time stamping of incoming packets\n" " SOF_TIMESTAMPING_RX_SOFTWARE - software fallback for incoming packets\n" " SOF_TIMESTAMPING_SOFTWARE - request reporting of software time stamps\n" " SOF_TIMESTAMPING_RAW_HARDWARE - request reporting of raw HW time stamps\n" " SOF_TIMESTAMPING_BIND_PHC - request to bind a PHC of PTP vclock\n" " SIOCGSTAMP - check last socket time stamp\n" " SIOCGSTAMPNS - more accurate socket time stamp\n" " PTPV2 - use PTPv2 messages\n"); exit(1); } static void bail(const char *error) { printf("%s: %s\n", error, strerror(errno)); exit(1); } static const unsigned char sync[] = { 0x00, 0x01, 0x00, 0x01, 0x5f, 0x44, 0x46, 0x4c, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, /* fake uuid */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x00, 0x01, 0x00, 0x37, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x49, 0x05, 0xcd, 0x01, 0x29, 0xb1, 0x8d, 0xb0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, /* fake uuid */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00, 0x04, 0x44, 0x46, 0x4c, 0x54, 0x00, 0x00, 0xf0, 0x60, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xf0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x44, 0x46, 0x4c, 0x54, 0x00, 0x01, /* fake uuid */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const unsigned char sync_v2[] = { 0x00, 0x02, 0x00, 0x2C, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; static void sendpacket(int sock, struct sockaddr *addr, socklen_t addr_len, int ptpv2) { size_t sync_len = ptpv2 ? sizeof(sync_v2) : sizeof(sync); const void *sync_p = ptpv2 ? sync_v2 : sync; struct timeval now; int res; res = sendto(sock, sync_p, sync_len, 0, addr, addr_len); gettimeofday(&now, 0); if (res < 0) printf("%s: %s\n", "send", strerror(errno)); else printf("%ld.%06ld: sent %d bytes\n", (long)now.tv_sec, (long)now.tv_usec, res); } static void printpacket(struct msghdr *msg, int res, char *data, int sock, int recvmsg_flags, int siocgstamp, int siocgstampns, int ptpv2) { struct sockaddr_in *from_addr = (struct sockaddr_in *)msg->msg_name; size_t sync_len = ptpv2 ? sizeof(sync_v2) : sizeof(sync); const void *sync_p = ptpv2 ? sync_v2 : sync; struct cmsghdr *cmsg; struct timeval tv; struct timespec ts; struct timeval now; gettimeofday(&now, 0); printf("%ld.%06ld: received %s data, %d bytes from %s, %zu bytes control messages\n", (long)now.tv_sec, (long)now.tv_usec, (recvmsg_flags & MSG_ERRQUEUE) ? "error" : "regular", res, inet_ntoa(from_addr->sin_addr), msg->msg_controllen); for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { printf(" cmsg len %zu: ", cmsg->cmsg_len); switch (cmsg->cmsg_level) { case SOL_SOCKET: printf("SOL_SOCKET "); switch (cmsg->cmsg_type) { case SO_TIMESTAMP: { struct timeval *stamp = (struct timeval *)CMSG_DATA(cmsg); printf("SO_TIMESTAMP %ld.%06ld", (long)stamp->tv_sec, (long)stamp->tv_usec); break; } case SO_TIMESTAMPNS: { struct timespec *stamp = (struct timespec *)CMSG_DATA(cmsg); printf("SO_TIMESTAMPNS %ld.%09ld", (long)stamp->tv_sec, (long)stamp->tv_nsec); break; } case SO_TIMESTAMPING: { struct timespec *stamp = (struct timespec *)CMSG_DATA(cmsg); printf("SO_TIMESTAMPING "); printf("SW %ld.%09ld ", (long)stamp->tv_sec, (long)stamp->tv_nsec); stamp++; /* skip deprecated HW transformed */ stamp++; printf("HW raw %ld.%09ld", (long)stamp->tv_sec, (long)stamp->tv_nsec); break; } default: printf("type %d", cmsg->cmsg_type); break; } break; case IPPROTO_IP: printf("IPPROTO_IP "); switch (cmsg->cmsg_type) { case IP_RECVERR: { struct sock_extended_err *err = (struct sock_extended_err *)CMSG_DATA(cmsg); printf("IP_RECVERR ee_errno '%s' ee_origin %d => %s", strerror(err->ee_errno), err->ee_origin, #ifdef SO_EE_ORIGIN_TIMESTAMPING err->ee_origin == SO_EE_ORIGIN_TIMESTAMPING ? "bounced packet" : "unexpected origin" #else "probably SO_EE_ORIGIN_TIMESTAMPING" #endif ); if (res < sync_len) printf(" => truncated data?!"); else if (!memcmp(sync_p, data + res - sync_len, sync_len)) printf(" => GOT OUR DATA BACK (HURRAY!)"); break; } case IP_PKTINFO: { struct in_pktinfo *pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg); printf("IP_PKTINFO interface index %u", pktinfo->ipi_ifindex); break; } default: printf("type %d", cmsg->cmsg_type); break; } break; default: printf("level %d type %d", cmsg->cmsg_level, cmsg->cmsg_type); break; } printf("\n"); } if (siocgstamp) { if (ioctl(sock, SIOCGSTAMP, &tv)) printf(" %s: %s\n", "SIOCGSTAMP", strerror(errno)); else printf("SIOCGSTAMP %ld.%06ld\n", (long)tv.tv_sec, (long)tv.tv_usec); } if (siocgstampns) { if (ioctl(sock, SIOCGSTAMPNS, &ts)) printf(" %s: %s\n", "SIOCGSTAMPNS", strerror(errno)); else printf("SIOCGSTAMPNS %ld.%09ld\n", (long)ts.tv_sec, (long)ts.tv_nsec); } } static void recvpacket(int sock, int recvmsg_flags, int siocgstamp, int siocgstampns, int ptpv2) { char data[256]; struct msghdr msg; struct iovec entry; struct sockaddr_in from_addr; struct { struct cmsghdr cm; char control[512]; } control; int res; memset(&msg, 0, sizeof(msg)); msg.msg_iov = &entry; msg.msg_iovlen = 1; entry.iov_base = data; entry.iov_len = sizeof(data); msg.msg_name = (caddr_t)&from_addr; msg.msg_namelen = sizeof(from_addr); msg.msg_control = &control; msg.msg_controllen = sizeof(control); res = recvmsg(sock, &msg, recvmsg_flags|MSG_DONTWAIT); if (res < 0) { printf("%s %s: %s\n", "recvmsg", (recvmsg_flags & MSG_ERRQUEUE) ? "error" : "regular", strerror(errno)); } else { printpacket(&msg, res, data, sock, recvmsg_flags, siocgstamp, siocgstampns, ptpv2); } } int main(int argc, char **argv) { int so_timestamp = 0; int so_timestampns = 0; int siocgstamp = 0; int siocgstampns = 0; int ip_multicast_loop = 0; int ptpv2 = 0; char *interface; int i; int enabled = 1; int sock; struct ifreq device; struct ifreq hwtstamp; struct hwtstamp_config hwconfig, hwconfig_requested; struct so_timestamping so_timestamping_get = { 0, 0 }; struct so_timestamping so_timestamping = { 0, 0 }; struct sockaddr_in addr; struct ip_mreq imr; struct in_addr iaddr; int val; socklen_t len; struct timeval next; size_t if_len; if (argc < 2) usage(0); interface = argv[1]; if_len = strlen(interface); if (if_len >= IFNAMSIZ) { printf("interface name exceeds IFNAMSIZ\n"); exit(1); } if (argc >= 3 && sscanf(argv[2], "%d", &so_timestamping.bind_phc) == 1) val = 3; else val = 2; for (i = val; i < argc; i++) { if (!strcasecmp(argv[i], "SO_TIMESTAMP")) so_timestamp = 1; else if (!strcasecmp(argv[i], "SO_TIMESTAMPNS")) so_timestampns = 1; else if (!strcasecmp(argv[i], "SIOCGSTAMP")) siocgstamp = 1; else if (!strcasecmp(argv[i], "SIOCGSTAMPNS")) siocgstampns = 1; else if (!strcasecmp(argv[i], "IP_MULTICAST_LOOP")) ip_multicast_loop = 1; else if (!strcasecmp(argv[i], "PTPV2")) ptpv2 = 1; else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_TX_HARDWARE")) so_timestamping.flags |= SOF_TIMESTAMPING_TX_HARDWARE; else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_TX_SOFTWARE")) so_timestamping.flags |= SOF_TIMESTAMPING_TX_SOFTWARE; else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_RX_HARDWARE")) so_timestamping.flags |= SOF_TIMESTAMPING_RX_HARDWARE; else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_RX_SOFTWARE")) so_timestamping.flags |= SOF_TIMESTAMPING_RX_SOFTWARE; else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_SOFTWARE")) so_timestamping.flags |= SOF_TIMESTAMPING_SOFTWARE; else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_RAW_HARDWARE")) so_timestamping.flags |= SOF_TIMESTAMPING_RAW_HARDWARE; else if (!strcasecmp(argv[i], "SOF_TIMESTAMPING_BIND_PHC")) so_timestamping.flags |= SOF_TIMESTAMPING_BIND_PHC; else usage(argv[i]); } sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sock < 0) bail("socket"); memset(&device, 0, sizeof(device)); memcpy(device.ifr_name, interface, if_len + 1); if (ioctl(sock, SIOCGIFADDR, &device) < 0) bail("getting interface IP address"); memset(&hwtstamp, 0, sizeof(hwtstamp)); memcpy(hwtstamp.ifr_name, interface, if_len + 1); hwtstamp.ifr_data = (void *)&hwconfig; memset(&hwconfig, 0, sizeof(hwconfig)); hwconfig.tx_type = (so_timestamping.flags & SOF_TIMESTAMPING_TX_HARDWARE) ? HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF; hwconfig.rx_filter = (so_timestamping.flags & SOF_TIMESTAMPING_RX_HARDWARE) ? ptpv2 ? HWTSTAMP_FILTER_PTP_V2_L4_SYNC : HWTSTAMP_FILTER_PTP_V1_L4_SYNC : HWTSTAMP_FILTER_NONE; hwconfig_requested = hwconfig; if (ioctl(sock, SIOCSHWTSTAMP, &hwtstamp) < 0) { if ((errno == EINVAL || errno == ENOTSUP) && hwconfig_requested.tx_type == HWTSTAMP_TX_OFF && hwconfig_requested.rx_filter == HWTSTAMP_FILTER_NONE) printf("SIOCSHWTSTAMP: disabling hardware time stamping not possible\n"); else bail("SIOCSHWTSTAMP"); } printf("SIOCSHWTSTAMP: tx_type %d requested, got %d; rx_filter %d requested, got %d\n", hwconfig_requested.tx_type, hwconfig.tx_type, hwconfig_requested.rx_filter, hwconfig.rx_filter); /* bind to PTP port */ addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(319 /* PTP event port */); if (bind(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) bail("bind"); if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, interface, if_len)) bail("bind device"); /* set multicast group for outgoing packets */ inet_aton("224.0.1.130", &iaddr); /* alternate PTP domain 1 */ addr.sin_addr = iaddr; imr.imr_multiaddr.s_addr = iaddr.s_addr; imr.imr_interface.s_addr = ((struct sockaddr_in *)&device.ifr_addr)->sin_addr.s_addr; if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &imr.imr_interface.s_addr, sizeof(struct in_addr)) < 0) bail("set multicast"); /* join multicast group, loop our own packet */ if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(struct ip_mreq)) < 0) bail("join multicast group"); if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, &ip_multicast_loop, sizeof(enabled)) < 0) { bail("loop multicast"); } /* set socket options for time stamping */ if (so_timestamp && setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &enabled, sizeof(enabled)) < 0) bail("setsockopt SO_TIMESTAMP"); if (so_timestampns && setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPNS, &enabled, sizeof(enabled)) < 0) bail("setsockopt SO_TIMESTAMPNS"); if (so_timestamping.flags && setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &so_timestamping, sizeof(so_timestamping)) < 0) bail("setsockopt SO_TIMESTAMPING"); /* request IP_PKTINFO for debugging purposes */ if (setsockopt(sock, SOL_IP, IP_PKTINFO, &enabled, sizeof(enabled)) < 0) printf("%s: %s\n", "setsockopt IP_PKTINFO", strerror(errno)); /* verify socket options */ len = sizeof(val); if (getsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, &val, &len) < 0) printf("%s: %s\n", "getsockopt SO_TIMESTAMP", strerror(errno)); else printf("SO_TIMESTAMP %d\n", val); if (getsockopt(sock, SOL_SOCKET, SO_TIMESTAMPNS, &val, &len) < 0) printf("%s: %s\n", "getsockopt SO_TIMESTAMPNS", strerror(errno)); else printf("SO_TIMESTAMPNS %d\n", val); len = sizeof(so_timestamping_get); if (getsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &so_timestamping_get, &len) < 0) { printf("%s: %s\n", "getsockopt SO_TIMESTAMPING", strerror(errno)); } else { printf("SO_TIMESTAMPING flags %d, bind phc %d\n", so_timestamping_get.flags, so_timestamping_get.bind_phc); if (so_timestamping_get.flags != so_timestamping.flags || so_timestamping_get.bind_phc != so_timestamping.bind_phc) printf(" not expected, flags %d, bind phc %d\n", so_timestamping.flags, so_timestamping.bind_phc); } /* send packets forever every five seconds */ gettimeofday(&next, 0); next.tv_sec = (next.tv_sec + 1) / 5 * 5; next.tv_usec = 0; while (1) { struct timeval now; struct timeval delta; long delta_us; int res; fd_set readfs, errorfs; gettimeofday(&now, 0); delta_us = (long)(next.tv_sec - now.tv_sec) * 1000000 + (long)(next.tv_usec - now.tv_usec); if (delta_us > 0) { /* continue waiting for timeout or data */ delta.tv_sec = delta_us / 1000000; delta.tv_usec = delta_us % 1000000; FD_ZERO(&readfs); FD_ZERO(&errorfs); FD_SET(sock, &readfs); FD_SET(sock, &errorfs); printf("%ld.%06ld: select %ldus\n", (long)now.tv_sec, (long)now.tv_usec, delta_us); res = select(sock + 1, &readfs, 0, &errorfs, &delta); gettimeofday(&now, 0); printf("%ld.%06ld: select returned: %d, %s\n", (long)now.tv_sec, (long)now.tv_usec, res, res < 0 ? strerror(errno) : "success"); if (res > 0) { if (FD_ISSET(sock, &readfs)) printf("ready for reading\n"); if (FD_ISSET(sock, &errorfs)) printf("has error\n"); recvpacket(sock, 0, siocgstamp, siocgstampns, ptpv2); recvpacket(sock, MSG_ERRQUEUE, siocgstamp, siocgstampns, ptpv2); } } else { /* write one packet */ sendpacket(sock, (struct sockaddr *)&addr, sizeof(addr), ptpv2); next.tv_sec += 5; continue; } } return 0; }
linux-master
tools/testing/selftests/net/timestamping.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <net/if.h> #include <linux/if_tun.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <linux/virtio_net.h> #include <netinet/ip.h> #include <netinet/udp.h> #include "../kselftest_harness.h" static const char param_dev_tap_name[] = "xmacvtap0"; static const char param_dev_dummy_name[] = "xdummy0"; static unsigned char param_hwaddr_src[] = { 0x00, 0xfe, 0x98, 0x14, 0x22, 0x42 }; static unsigned char param_hwaddr_dest[] = { 0x00, 0xfe, 0x98, 0x94, 0xd2, 0x43 }; #define MAX_RTNL_PAYLOAD (2048) #define PKT_DATA 0xCB #define TEST_PACKET_SZ (sizeof(struct virtio_net_hdr) + ETH_HLEN + ETH_MAX_MTU) static struct rtattr *rtattr_add(struct nlmsghdr *nh, unsigned short type, unsigned short len) { struct rtattr *rta = (struct rtattr *)((uint8_t *)nh + RTA_ALIGN(nh->nlmsg_len)); rta->rta_type = type; rta->rta_len = RTA_LENGTH(len); nh->nlmsg_len = RTA_ALIGN(nh->nlmsg_len) + RTA_ALIGN(rta->rta_len); return rta; } static struct rtattr *rtattr_begin(struct nlmsghdr *nh, unsigned short type) { return rtattr_add(nh, type, 0); } static void rtattr_end(struct nlmsghdr *nh, struct rtattr *attr) { uint8_t *end = (uint8_t *)nh + nh->nlmsg_len; attr->rta_len = end - (uint8_t *)attr; } static struct rtattr *rtattr_add_str(struct nlmsghdr *nh, unsigned short type, const char *s) { struct rtattr *rta = rtattr_add(nh, type, strlen(s)); memcpy(RTA_DATA(rta), s, strlen(s)); return rta; } static struct rtattr *rtattr_add_strsz(struct nlmsghdr *nh, unsigned short type, const char *s) { struct rtattr *rta = rtattr_add(nh, type, strlen(s) + 1); strcpy(RTA_DATA(rta), s); return rta; } static struct rtattr *rtattr_add_any(struct nlmsghdr *nh, unsigned short type, const void *arr, size_t len) { struct rtattr *rta = rtattr_add(nh, type, len); memcpy(RTA_DATA(rta), arr, len); return rta; } static int dev_create(const char *dev, const char *link_type, int (*fill_rtattr)(struct nlmsghdr *nh), int (*fill_info_data)(struct nlmsghdr *nh)) { struct { struct nlmsghdr nh; struct ifinfomsg info; unsigned char data[MAX_RTNL_PAYLOAD]; } req; struct rtattr *link_info, *info_data; int ret, rtnl; rtnl = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); if (rtnl < 0) { fprintf(stderr, "%s: socket %s\n", __func__, strerror(errno)); return 1; } memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.info)); req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE; req.nh.nlmsg_type = RTM_NEWLINK; req.info.ifi_family = AF_UNSPEC; req.info.ifi_type = 1; req.info.ifi_index = 0; req.info.ifi_flags = IFF_BROADCAST | IFF_UP; req.info.ifi_change = 0xffffffff; rtattr_add_str(&req.nh, IFLA_IFNAME, dev); if (fill_rtattr) { ret = fill_rtattr(&req.nh); if (ret) return ret; } link_info = rtattr_begin(&req.nh, IFLA_LINKINFO); rtattr_add_strsz(&req.nh, IFLA_INFO_KIND, link_type); if (fill_info_data) { info_data = rtattr_begin(&req.nh, IFLA_INFO_DATA); ret = fill_info_data(&req.nh); if (ret) return ret; rtattr_end(&req.nh, info_data); } rtattr_end(&req.nh, link_info); ret = send(rtnl, &req, req.nh.nlmsg_len, 0); if (ret < 0) fprintf(stderr, "%s: send %s\n", __func__, strerror(errno)); ret = (unsigned int)ret != req.nh.nlmsg_len; close(rtnl); return ret; } static int dev_delete(const char *dev) { struct { struct nlmsghdr nh; struct ifinfomsg info; unsigned char data[MAX_RTNL_PAYLOAD]; } req; int ret, rtnl; rtnl = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); if (rtnl < 0) { fprintf(stderr, "%s: socket %s\n", __func__, strerror(errno)); return 1; } memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.info)); req.nh.nlmsg_flags = NLM_F_REQUEST; req.nh.nlmsg_type = RTM_DELLINK; req.info.ifi_family = AF_UNSPEC; rtattr_add_str(&req.nh, IFLA_IFNAME, dev); ret = send(rtnl, &req, req.nh.nlmsg_len, 0); if (ret < 0) fprintf(stderr, "%s: send %s\n", __func__, strerror(errno)); ret = (unsigned int)ret != req.nh.nlmsg_len; close(rtnl); return ret; } static int macvtap_fill_rtattr(struct nlmsghdr *nh) { int ifindex; ifindex = if_nametoindex(param_dev_dummy_name); if (ifindex == 0) { fprintf(stderr, "%s: ifindex %s\n", __func__, strerror(errno)); return -errno; } rtattr_add_any(nh, IFLA_LINK, &ifindex, sizeof(ifindex)); rtattr_add_any(nh, IFLA_ADDRESS, param_hwaddr_src, ETH_ALEN); return 0; } static int opentap(const char *devname) { int ifindex; char buf[256]; int fd; struct ifreq ifr; ifindex = if_nametoindex(devname); if (ifindex == 0) { fprintf(stderr, "%s: ifindex %s\n", __func__, strerror(errno)); return -errno; } sprintf(buf, "/dev/tap%d", ifindex); fd = open(buf, O_RDWR | O_NONBLOCK); if (fd < 0) { fprintf(stderr, "%s: open %s\n", __func__, strerror(errno)); return -errno; } memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, devname); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR | IFF_MULTI_QUEUE; if (ioctl(fd, TUNSETIFF, &ifr, sizeof(ifr)) < 0) return -errno; return fd; } size_t build_eth(uint8_t *buf, uint16_t proto) { struct ethhdr *eth = (struct ethhdr *)buf; eth->h_proto = htons(proto); memcpy(eth->h_source, param_hwaddr_src, ETH_ALEN); memcpy(eth->h_dest, param_hwaddr_dest, ETH_ALEN); return ETH_HLEN; } static uint32_t add_csum(const uint8_t *buf, int len) { uint32_t sum = 0; uint16_t *sbuf = (uint16_t *)buf; while (len > 1) { sum += *sbuf++; len -= 2; } if (len) sum += *(uint8_t *)sbuf; return sum; } static uint16_t finish_ip_csum(uint32_t sum) { uint16_t lo = sum & 0xffff; uint16_t hi = sum >> 16; return ~(lo + hi); } static uint16_t build_ip_csum(const uint8_t *buf, int len, uint32_t sum) { sum += add_csum(buf, len); return finish_ip_csum(sum); } static int build_ipv4_header(uint8_t *buf, int payload_len) { struct iphdr *iph = (struct iphdr *)buf; iph->ihl = 5; iph->version = 4; iph->ttl = 8; iph->tot_len = htons(sizeof(*iph) + sizeof(struct udphdr) + payload_len); iph->id = htons(1337); iph->protocol = IPPROTO_UDP; iph->saddr = htonl((172 << 24) | (17 << 16) | 2); iph->daddr = htonl((172 << 24) | (17 << 16) | 1); iph->check = build_ip_csum(buf, iph->ihl << 2, 0); return iph->ihl << 2; } static int build_udp_packet(uint8_t *buf, int payload_len, bool csum_off) { const int ip4alen = sizeof(uint32_t); struct udphdr *udph = (struct udphdr *)buf; int len = sizeof(*udph) + payload_len; uint32_t sum = 0; udph->source = htons(22); udph->dest = htons(58822); udph->len = htons(len); memset(buf + sizeof(struct udphdr), PKT_DATA, payload_len); sum = add_csum(buf - 2 * ip4alen, 2 * ip4alen); sum += htons(IPPROTO_UDP) + udph->len; if (!csum_off) sum += add_csum(buf, len); udph->check = finish_ip_csum(sum); return sizeof(*udph) + payload_len; } size_t build_test_packet_valid_udp_gso(uint8_t *buf, size_t payload_len) { uint8_t *cur = buf; struct virtio_net_hdr *vh = (struct virtio_net_hdr *)buf; vh->hdr_len = ETH_HLEN + sizeof(struct iphdr) + sizeof(struct udphdr); vh->flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; vh->csum_start = ETH_HLEN + sizeof(struct iphdr); vh->csum_offset = __builtin_offsetof(struct udphdr, check); vh->gso_type = VIRTIO_NET_HDR_GSO_UDP; vh->gso_size = ETH_DATA_LEN - sizeof(struct iphdr); cur += sizeof(*vh); cur += build_eth(cur, ETH_P_IP); cur += build_ipv4_header(cur, payload_len); cur += build_udp_packet(cur, payload_len, true); return cur - buf; } size_t build_test_packet_valid_udp_csum(uint8_t *buf, size_t payload_len) { uint8_t *cur = buf; struct virtio_net_hdr *vh = (struct virtio_net_hdr *)buf; vh->flags = VIRTIO_NET_HDR_F_DATA_VALID; vh->gso_type = VIRTIO_NET_HDR_GSO_NONE; cur += sizeof(*vh); cur += build_eth(cur, ETH_P_IP); cur += build_ipv4_header(cur, payload_len); cur += build_udp_packet(cur, payload_len, false); return cur - buf; } size_t build_test_packet_crash_tap_invalid_eth_proto(uint8_t *buf, size_t payload_len) { uint8_t *cur = buf; struct virtio_net_hdr *vh = (struct virtio_net_hdr *)buf; vh->hdr_len = ETH_HLEN + sizeof(struct iphdr) + sizeof(struct udphdr); vh->flags = 0; vh->gso_type = VIRTIO_NET_HDR_GSO_UDP; vh->gso_size = ETH_DATA_LEN - sizeof(struct iphdr); cur += sizeof(*vh); cur += build_eth(cur, 0); cur += sizeof(struct iphdr) + sizeof(struct udphdr); cur += build_ipv4_header(cur, payload_len); cur += build_udp_packet(cur, payload_len, true); cur += payload_len; return cur - buf; } FIXTURE(tap) { int fd; }; FIXTURE_SETUP(tap) { int ret; ret = dev_create(param_dev_dummy_name, "dummy", NULL, NULL); EXPECT_EQ(ret, 0); ret = dev_create(param_dev_tap_name, "macvtap", macvtap_fill_rtattr, NULL); EXPECT_EQ(ret, 0); self->fd = opentap(param_dev_tap_name); ASSERT_GE(self->fd, 0); } FIXTURE_TEARDOWN(tap) { int ret; if (self->fd != -1) close(self->fd); ret = dev_delete(param_dev_tap_name); EXPECT_EQ(ret, 0); ret = dev_delete(param_dev_dummy_name); EXPECT_EQ(ret, 0); } TEST_F(tap, test_packet_valid_udp_gso) { uint8_t pkt[TEST_PACKET_SZ]; size_t off; int ret; memset(pkt, 0, sizeof(pkt)); off = build_test_packet_valid_udp_gso(pkt, 1021); ret = write(self->fd, pkt, off); ASSERT_EQ(ret, off); } TEST_F(tap, test_packet_valid_udp_csum) { uint8_t pkt[TEST_PACKET_SZ]; size_t off; int ret; memset(pkt, 0, sizeof(pkt)); off = build_test_packet_valid_udp_csum(pkt, 1024); ret = write(self->fd, pkt, off); ASSERT_EQ(ret, off); } TEST_F(tap, test_packet_crash_tap_invalid_eth_proto) { uint8_t pkt[TEST_PACKET_SZ]; size_t off; int ret; memset(pkt, 0, sizeof(pkt)); off = build_test_packet_crash_tap_invalid_eth_proto(pkt, 1024); ret = write(self->fd, pkt, off); ASSERT_EQ(ret, -1); ASSERT_EQ(errno, EINVAL); } TEST_HARNESS_MAIN
linux-master
tools/testing/selftests/net/tap.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2014 Google Inc. * Author: [email protected] (Willem de Bruijn) * * Test software tx timestamping, including * * - SCHED, SND and ACK timestamps * - RAW, UDP and TCP * - IPv4 and IPv6 * - various packet sizes (to test GSO and TSO) * * Consult the command line arguments for help on running * the various testcases. * * This test requires a dummy TCP server. * A simple `nc6 [-u] -l -p $DESTPORT` will do */ #define _GNU_SOURCE #include <arpa/inet.h> #include <asm/types.h> #include <error.h> #include <errno.h> #include <inttypes.h> #include <linux/errqueue.h> #include <linux/if_ether.h> #include <linux/if_packet.h> #include <linux/ipv6.h> #include <linux/net_tstamp.h> #include <netdb.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <netinet/tcp.h> #include <poll.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/ioctl.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #define NSEC_PER_USEC 1000L #define USEC_PER_SEC 1000000L #define NSEC_PER_SEC 1000000000LL /* command line parameters */ static int cfg_proto = SOCK_STREAM; static int cfg_ipproto = IPPROTO_TCP; static int cfg_num_pkts = 4; static int do_ipv4 = 1; static int do_ipv6 = 1; static int cfg_payload_len = 10; static int cfg_poll_timeout = 100; static int cfg_delay_snd; static int cfg_delay_ack; static int cfg_delay_tolerance_usec = 500; static bool cfg_show_payload; static bool cfg_do_pktinfo; static bool cfg_busy_poll; static int cfg_sleep_usec = 50 * 1000; static bool cfg_loop_nodata; static bool cfg_use_cmsg; static bool cfg_use_pf_packet; static bool cfg_use_epoll; static bool cfg_epollet; static bool cfg_do_listen; static uint16_t dest_port = 9000; static bool cfg_print_nsec; static struct sockaddr_in daddr; static struct sockaddr_in6 daddr6; static struct timespec ts_usr; static int saved_tskey = -1; static int saved_tskey_type = -1; struct timing_event { int64_t min; int64_t max; int64_t total; int count; }; static struct timing_event usr_enq; static struct timing_event usr_snd; static struct timing_event usr_ack; static bool test_failed; static int64_t timespec_to_ns64(struct timespec *ts) { return ts->tv_sec * NSEC_PER_SEC + ts->tv_nsec; } static int64_t timespec_to_us64(struct timespec *ts) { return ts->tv_sec * USEC_PER_SEC + ts->tv_nsec / NSEC_PER_USEC; } static void init_timing_event(struct timing_event *te) { te->min = INT64_MAX; te->max = 0; te->total = 0; te->count = 0; } static void add_timing_event(struct timing_event *te, struct timespec *t_start, struct timespec *t_end) { int64_t ts_delta = timespec_to_ns64(t_end) - timespec_to_ns64(t_start); te->count++; if (ts_delta < te->min) te->min = ts_delta; if (ts_delta > te->max) te->max = ts_delta; te->total += ts_delta; } static void validate_key(int tskey, int tstype) { int stepsize; /* compare key for each subsequent request * must only test for one type, the first one requested */ if (saved_tskey == -1) saved_tskey_type = tstype; else if (saved_tskey_type != tstype) return; stepsize = cfg_proto == SOCK_STREAM ? cfg_payload_len : 1; if (tskey != saved_tskey + stepsize) { fprintf(stderr, "ERROR: key %d, expected %d\n", tskey, saved_tskey + stepsize); test_failed = true; } saved_tskey = tskey; } static void validate_timestamp(struct timespec *cur, int min_delay) { int64_t cur64, start64; int max_delay; cur64 = timespec_to_us64(cur); start64 = timespec_to_us64(&ts_usr); max_delay = min_delay + cfg_delay_tolerance_usec; if (cur64 < start64 + min_delay || cur64 > start64 + max_delay) { fprintf(stderr, "ERROR: %" PRId64 " us expected between %d and %d\n", cur64 - start64, min_delay, max_delay); test_failed = true; } } static void __print_ts_delta_formatted(int64_t ts_delta) { if (cfg_print_nsec) fprintf(stderr, "%" PRId64 " ns", ts_delta); else fprintf(stderr, "%" PRId64 " us", ts_delta / NSEC_PER_USEC); } static void __print_timestamp(const char *name, struct timespec *cur, uint32_t key, int payload_len) { int64_t ts_delta; if (!(cur->tv_sec | cur->tv_nsec)) return; if (cfg_print_nsec) fprintf(stderr, " %s: %lu s %lu ns (seq=%u, len=%u)", name, cur->tv_sec, cur->tv_nsec, key, payload_len); else fprintf(stderr, " %s: %lu s %lu us (seq=%u, len=%u)", name, cur->tv_sec, cur->tv_nsec / NSEC_PER_USEC, key, payload_len); if (cur != &ts_usr) { ts_delta = timespec_to_ns64(cur) - timespec_to_ns64(&ts_usr); fprintf(stderr, " (USR +"); __print_ts_delta_formatted(ts_delta); fprintf(stderr, ")"); } fprintf(stderr, "\n"); } static void print_timestamp_usr(void) { if (clock_gettime(CLOCK_REALTIME, &ts_usr)) error(1, errno, "clock_gettime"); __print_timestamp(" USR", &ts_usr, 0, 0); } static void print_timestamp(struct scm_timestamping *tss, int tstype, int tskey, int payload_len) { const char *tsname; validate_key(tskey, tstype); switch (tstype) { case SCM_TSTAMP_SCHED: tsname = " ENQ"; validate_timestamp(&tss->ts[0], 0); add_timing_event(&usr_enq, &ts_usr, &tss->ts[0]); break; case SCM_TSTAMP_SND: tsname = " SND"; validate_timestamp(&tss->ts[0], cfg_delay_snd); add_timing_event(&usr_snd, &ts_usr, &tss->ts[0]); break; case SCM_TSTAMP_ACK: tsname = " ACK"; validate_timestamp(&tss->ts[0], cfg_delay_ack); add_timing_event(&usr_ack, &ts_usr, &tss->ts[0]); break; default: error(1, 0, "unknown timestamp type: %u", tstype); } __print_timestamp(tsname, &tss->ts[0], tskey, payload_len); } static void print_timing_event(char *name, struct timing_event *te) { if (!te->count) return; fprintf(stderr, " %s: count=%d", name, te->count); fprintf(stderr, ", avg="); __print_ts_delta_formatted((int64_t)(te->total / te->count)); fprintf(stderr, ", min="); __print_ts_delta_formatted(te->min); fprintf(stderr, ", max="); __print_ts_delta_formatted(te->max); fprintf(stderr, "\n"); } /* TODO: convert to check_and_print payload once API is stable */ static void print_payload(char *data, int len) { int i; if (!len) return; if (len > 70) len = 70; fprintf(stderr, "payload: "); for (i = 0; i < len; i++) fprintf(stderr, "%02hhx ", data[i]); fprintf(stderr, "\n"); } static void print_pktinfo(int family, int ifindex, void *saddr, void *daddr) { char sa[INET6_ADDRSTRLEN], da[INET6_ADDRSTRLEN]; fprintf(stderr, " pktinfo: ifindex=%u src=%s dst=%s\n", ifindex, saddr ? inet_ntop(family, saddr, sa, sizeof(sa)) : "unknown", daddr ? inet_ntop(family, daddr, da, sizeof(da)) : "unknown"); } static void __epoll(int epfd) { struct epoll_event events; int ret; memset(&events, 0, sizeof(events)); ret = epoll_wait(epfd, &events, 1, cfg_poll_timeout); if (ret != 1) error(1, errno, "epoll_wait"); } static void __poll(int fd) { struct pollfd pollfd; int ret; memset(&pollfd, 0, sizeof(pollfd)); pollfd.fd = fd; ret = poll(&pollfd, 1, cfg_poll_timeout); if (ret != 1) error(1, errno, "poll"); } static void __recv_errmsg_cmsg(struct msghdr *msg, int payload_len) { struct sock_extended_err *serr = NULL; struct scm_timestamping *tss = NULL; struct cmsghdr *cm; int batch = 0; for (cm = CMSG_FIRSTHDR(msg); cm && cm->cmsg_len; cm = CMSG_NXTHDR(msg, cm)) { if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_TIMESTAMPING) { tss = (void *) CMSG_DATA(cm); } else if ((cm->cmsg_level == SOL_IP && cm->cmsg_type == IP_RECVERR) || (cm->cmsg_level == SOL_IPV6 && cm->cmsg_type == IPV6_RECVERR) || (cm->cmsg_level == SOL_PACKET && cm->cmsg_type == PACKET_TX_TIMESTAMP)) { serr = (void *) CMSG_DATA(cm); if (serr->ee_errno != ENOMSG || serr->ee_origin != SO_EE_ORIGIN_TIMESTAMPING) { fprintf(stderr, "unknown ip error %d %d\n", serr->ee_errno, serr->ee_origin); serr = NULL; } } else if (cm->cmsg_level == SOL_IP && cm->cmsg_type == IP_PKTINFO) { struct in_pktinfo *info = (void *) CMSG_DATA(cm); print_pktinfo(AF_INET, info->ipi_ifindex, &info->ipi_spec_dst, &info->ipi_addr); } else if (cm->cmsg_level == SOL_IPV6 && cm->cmsg_type == IPV6_PKTINFO) { struct in6_pktinfo *info6 = (void *) CMSG_DATA(cm); print_pktinfo(AF_INET6, info6->ipi6_ifindex, NULL, &info6->ipi6_addr); } else fprintf(stderr, "unknown cmsg %d,%d\n", cm->cmsg_level, cm->cmsg_type); if (serr && tss) { print_timestamp(tss, serr->ee_info, serr->ee_data, payload_len); serr = NULL; tss = NULL; batch++; } } if (batch > 1) fprintf(stderr, "batched %d timestamps\n", batch); } static int recv_errmsg(int fd) { static char ctrl[1024 /* overprovision*/]; static struct msghdr msg; struct iovec entry; static char *data; int ret = 0; data = malloc(cfg_payload_len); if (!data) error(1, 0, "malloc"); memset(&msg, 0, sizeof(msg)); memset(&entry, 0, sizeof(entry)); memset(ctrl, 0, sizeof(ctrl)); entry.iov_base = data; entry.iov_len = cfg_payload_len; msg.msg_iov = &entry; msg.msg_iovlen = 1; msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_control = ctrl; msg.msg_controllen = sizeof(ctrl); ret = recvmsg(fd, &msg, MSG_ERRQUEUE); if (ret == -1 && errno != EAGAIN) error(1, errno, "recvmsg"); if (ret >= 0) { __recv_errmsg_cmsg(&msg, ret); if (cfg_show_payload) print_payload(data, cfg_payload_len); } free(data); return ret == -1; } static uint16_t get_ip_csum(const uint16_t *start, int num_words, unsigned long sum) { int i; for (i = 0; i < num_words; i++) sum += start[i]; while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16); return ~sum; } static uint16_t get_udp_csum(const struct udphdr *udph, int alen) { unsigned long pseudo_sum, csum_len; const void *csum_start = udph; pseudo_sum = htons(IPPROTO_UDP); pseudo_sum += udph->len; /* checksum ip(v6) addresses + udp header + payload */ csum_start -= alen * 2; csum_len = ntohs(udph->len) + alen * 2; return get_ip_csum(csum_start, csum_len >> 1, pseudo_sum); } static int fill_header_ipv4(void *p) { struct iphdr *iph = p; memset(iph, 0, sizeof(*iph)); iph->ihl = 5; iph->version = 4; iph->ttl = 2; iph->saddr = daddr.sin_addr.s_addr; /* set for udp csum calc */ iph->daddr = daddr.sin_addr.s_addr; iph->protocol = IPPROTO_UDP; /* kernel writes saddr, csum, len */ return sizeof(*iph); } static int fill_header_ipv6(void *p) { struct ipv6hdr *ip6h = p; memset(ip6h, 0, sizeof(*ip6h)); ip6h->version = 6; ip6h->payload_len = htons(sizeof(struct udphdr) + cfg_payload_len); ip6h->nexthdr = IPPROTO_UDP; ip6h->hop_limit = 64; ip6h->saddr = daddr6.sin6_addr; ip6h->daddr = daddr6.sin6_addr; /* kernel does not write saddr in case of ipv6 */ return sizeof(*ip6h); } static void fill_header_udp(void *p, bool is_ipv4) { struct udphdr *udph = p; udph->source = ntohs(dest_port + 1); /* spoof */ udph->dest = ntohs(dest_port); udph->len = ntohs(sizeof(*udph) + cfg_payload_len); udph->check = 0; udph->check = get_udp_csum(udph, is_ipv4 ? sizeof(struct in_addr) : sizeof(struct in6_addr)); } static void do_test(int family, unsigned int report_opt) { char control[CMSG_SPACE(sizeof(uint32_t))]; struct sockaddr_ll laddr; unsigned int sock_opt; struct cmsghdr *cmsg; struct msghdr msg; struct iovec iov; char *buf; int fd, i, val = 1, total_len, epfd = 0; init_timing_event(&usr_enq); init_timing_event(&usr_snd); init_timing_event(&usr_ack); total_len = cfg_payload_len; if (cfg_use_pf_packet || cfg_proto == SOCK_RAW) { total_len += sizeof(struct udphdr); if (cfg_use_pf_packet || cfg_ipproto == IPPROTO_RAW) { if (family == PF_INET) total_len += sizeof(struct iphdr); else total_len += sizeof(struct ipv6hdr); } /* special case, only rawv6_sendmsg: * pass proto in sin6_port if not connected * also see ANK comment in net/ipv4/raw.c */ daddr6.sin6_port = htons(cfg_ipproto); } buf = malloc(total_len); if (!buf) error(1, 0, "malloc"); fd = socket(cfg_use_pf_packet ? PF_PACKET : family, cfg_proto, cfg_ipproto); if (fd < 0) error(1, errno, "socket"); if (cfg_use_epoll) { struct epoll_event ev; memset(&ev, 0, sizeof(ev)); ev.data.fd = fd; if (cfg_epollet) ev.events |= EPOLLET; epfd = epoll_create(1); if (epfd <= 0) error(1, errno, "epoll_create"); if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev)) error(1, errno, "epoll_ctl"); } /* reset expected key on each new socket */ saved_tskey = -1; if (cfg_proto == SOCK_STREAM) { if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*) &val, sizeof(val))) error(1, 0, "setsockopt no nagle"); if (family == PF_INET) { if (connect(fd, (void *) &daddr, sizeof(daddr))) error(1, errno, "connect ipv4"); } else { if (connect(fd, (void *) &daddr6, sizeof(daddr6))) error(1, errno, "connect ipv6"); } } if (cfg_do_pktinfo) { if (family == AF_INET6) { if (setsockopt(fd, SOL_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val))) error(1, errno, "setsockopt pktinfo ipv6"); } else { if (setsockopt(fd, SOL_IP, IP_PKTINFO, &val, sizeof(val))) error(1, errno, "setsockopt pktinfo ipv4"); } } sock_opt = SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_OPT_CMSG | SOF_TIMESTAMPING_OPT_ID; if (!cfg_use_cmsg) sock_opt |= report_opt; if (cfg_loop_nodata) sock_opt |= SOF_TIMESTAMPING_OPT_TSONLY; if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPING, (char *) &sock_opt, sizeof(sock_opt))) error(1, 0, "setsockopt timestamping"); for (i = 0; i < cfg_num_pkts; i++) { memset(&msg, 0, sizeof(msg)); memset(buf, 'a' + i, total_len); if (cfg_use_pf_packet || cfg_proto == SOCK_RAW) { int off = 0; if (cfg_use_pf_packet || cfg_ipproto == IPPROTO_RAW) { if (family == PF_INET) off = fill_header_ipv4(buf); else off = fill_header_ipv6(buf); } fill_header_udp(buf + off, family == PF_INET); } print_timestamp_usr(); iov.iov_base = buf; iov.iov_len = total_len; if (cfg_proto != SOCK_STREAM) { if (cfg_use_pf_packet) { memset(&laddr, 0, sizeof(laddr)); laddr.sll_family = AF_PACKET; laddr.sll_ifindex = 1; laddr.sll_protocol = htons(family == AF_INET ? ETH_P_IP : ETH_P_IPV6); laddr.sll_halen = ETH_ALEN; msg.msg_name = (void *)&laddr; msg.msg_namelen = sizeof(laddr); } else if (family == PF_INET) { msg.msg_name = (void *)&daddr; msg.msg_namelen = sizeof(daddr); } else { msg.msg_name = (void *)&daddr6; msg.msg_namelen = sizeof(daddr6); } } msg.msg_iov = &iov; msg.msg_iovlen = 1; if (cfg_use_cmsg) { memset(control, 0, sizeof(control)); msg.msg_control = control; msg.msg_controllen = sizeof(control); cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SO_TIMESTAMPING; cmsg->cmsg_len = CMSG_LEN(sizeof(uint32_t)); *((uint32_t *) CMSG_DATA(cmsg)) = report_opt; } val = sendmsg(fd, &msg, 0); if (val != total_len) error(1, errno, "send"); /* wait for all errors to be queued, else ACKs arrive OOO */ if (cfg_sleep_usec) usleep(cfg_sleep_usec); if (!cfg_busy_poll) { if (cfg_use_epoll) __epoll(epfd); else __poll(fd); } while (!recv_errmsg(fd)) {} } print_timing_event("USR-ENQ", &usr_enq); print_timing_event("USR-SND", &usr_snd); print_timing_event("USR-ACK", &usr_ack); if (close(fd)) error(1, errno, "close"); free(buf); usleep(100 * NSEC_PER_USEC); } static void __attribute__((noreturn)) usage(const char *filepath) { fprintf(stderr, "\nUsage: %s [options] hostname\n" "\nwhere options are:\n" " -4: only IPv4\n" " -6: only IPv6\n" " -h: show this message\n" " -b: busy poll to read from error queue\n" " -c N: number of packets for each test\n" " -C: use cmsg to set tstamp recording options\n" " -e: use level-triggered epoll() instead of poll()\n" " -E: use event-triggered epoll() instead of poll()\n" " -F: poll()/epoll() waits forever for an event\n" " -I: request PKTINFO\n" " -l N: send N bytes at a time\n" " -L listen on hostname and port\n" " -n: set no-payload option\n" " -N: print timestamps and durations in nsec (instead of usec)\n" " -p N: connect to port N\n" " -P: use PF_PACKET\n" " -r: use raw\n" " -R: use raw (IP_HDRINCL)\n" " -S N: usec to sleep before reading error queue\n" " -t N: tolerance (usec) for timestamp validation\n" " -u: use udp\n" " -v: validate SND delay (usec)\n" " -V: validate ACK delay (usec)\n" " -x: show payload (up to 70 bytes)\n", filepath); exit(1); } static void parse_opt(int argc, char **argv) { int proto_count = 0; int c; while ((c = getopt(argc, argv, "46bc:CeEFhIl:LnNp:PrRS:t:uv:V:x")) != -1) { switch (c) { case '4': do_ipv6 = 0; break; case '6': do_ipv4 = 0; break; case 'b': cfg_busy_poll = true; break; case 'c': cfg_num_pkts = strtoul(optarg, NULL, 10); break; case 'C': cfg_use_cmsg = true; break; case 'e': cfg_use_epoll = true; break; case 'E': cfg_use_epoll = true; cfg_epollet = true; case 'F': cfg_poll_timeout = -1; break; case 'I': cfg_do_pktinfo = true; break; case 'l': cfg_payload_len = strtoul(optarg, NULL, 10); break; case 'L': cfg_do_listen = true; break; case 'n': cfg_loop_nodata = true; break; case 'N': cfg_print_nsec = true; break; case 'p': dest_port = strtoul(optarg, NULL, 10); break; case 'P': proto_count++; cfg_use_pf_packet = true; cfg_proto = SOCK_DGRAM; cfg_ipproto = 0; break; case 'r': proto_count++; cfg_proto = SOCK_RAW; cfg_ipproto = IPPROTO_UDP; break; case 'R': proto_count++; cfg_proto = SOCK_RAW; cfg_ipproto = IPPROTO_RAW; break; case 'S': cfg_sleep_usec = strtoul(optarg, NULL, 10); break; case 't': cfg_delay_tolerance_usec = strtoul(optarg, NULL, 10); break; case 'u': proto_count++; cfg_proto = SOCK_DGRAM; cfg_ipproto = IPPROTO_UDP; break; case 'v': cfg_delay_snd = strtoul(optarg, NULL, 10); break; case 'V': cfg_delay_ack = strtoul(optarg, NULL, 10); break; case 'x': cfg_show_payload = true; break; case 'h': default: usage(argv[0]); } } if (!cfg_payload_len) error(1, 0, "payload may not be nonzero"); if (cfg_proto != SOCK_STREAM && cfg_payload_len > 1472) error(1, 0, "udp packet might exceed expected MTU"); if (!do_ipv4 && !do_ipv6) error(1, 0, "pass -4 or -6, not both"); if (proto_count > 1) error(1, 0, "pass -P, -r, -R or -u, not multiple"); if (cfg_do_pktinfo && cfg_use_pf_packet) error(1, 0, "cannot ask for pktinfo over pf_packet"); if (cfg_busy_poll && cfg_use_epoll) error(1, 0, "pass epoll or busy_poll, not both"); if (optind != argc - 1) error(1, 0, "missing required hostname argument"); } static void resolve_hostname(const char *hostname) { struct addrinfo hints = { .ai_family = do_ipv4 ? AF_INET : AF_INET6 }; struct addrinfo *addrs, *cur; int have_ipv4 = 0, have_ipv6 = 0; retry: if (getaddrinfo(hostname, NULL, &hints, &addrs)) error(1, errno, "getaddrinfo"); cur = addrs; while (cur && !have_ipv4 && !have_ipv6) { if (!have_ipv4 && cur->ai_family == AF_INET) { memcpy(&daddr, cur->ai_addr, sizeof(daddr)); daddr.sin_port = htons(dest_port); have_ipv4 = 1; } else if (!have_ipv6 && cur->ai_family == AF_INET6) { memcpy(&daddr6, cur->ai_addr, sizeof(daddr6)); daddr6.sin6_port = htons(dest_port); have_ipv6 = 1; } cur = cur->ai_next; } if (addrs) freeaddrinfo(addrs); if (do_ipv6 && hints.ai_family != AF_INET6) { hints.ai_family = AF_INET6; goto retry; } do_ipv4 &= have_ipv4; do_ipv6 &= have_ipv6; } static void do_listen(int family, void *addr, int alen) { int fd, type; type = cfg_proto == SOCK_RAW ? SOCK_DGRAM : cfg_proto; fd = socket(family, type, 0); if (fd == -1) error(1, errno, "socket rx"); if (bind(fd, addr, alen)) error(1, errno, "bind rx"); if (type == SOCK_STREAM && listen(fd, 10)) error(1, errno, "listen rx"); /* leave fd open, will be closed on process exit. * this enables connect() to succeed and avoids icmp replies */ } static void do_main(int family) { fprintf(stderr, "family: %s %s\n", family == PF_INET ? "INET" : "INET6", cfg_use_pf_packet ? "(PF_PACKET)" : ""); fprintf(stderr, "test SND\n"); do_test(family, SOF_TIMESTAMPING_TX_SOFTWARE); fprintf(stderr, "test ENQ\n"); do_test(family, SOF_TIMESTAMPING_TX_SCHED); fprintf(stderr, "test ENQ + SND\n"); do_test(family, SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE); if (cfg_proto == SOCK_STREAM) { fprintf(stderr, "\ntest ACK\n"); do_test(family, SOF_TIMESTAMPING_TX_ACK); fprintf(stderr, "\ntest SND + ACK\n"); do_test(family, SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_TX_ACK); fprintf(stderr, "\ntest ENQ + SND + ACK\n"); do_test(family, SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_TX_ACK); } } const char *sock_names[] = { NULL, "TCP", "UDP", "RAW" }; int main(int argc, char **argv) { if (argc == 1) usage(argv[0]); parse_opt(argc, argv); resolve_hostname(argv[argc - 1]); fprintf(stderr, "protocol: %s\n", sock_names[cfg_proto]); fprintf(stderr, "payload: %u\n", cfg_payload_len); fprintf(stderr, "server port: %u\n", dest_port); fprintf(stderr, "\n"); if (do_ipv4) { if (cfg_do_listen) do_listen(PF_INET, &daddr, sizeof(daddr)); do_main(PF_INET); } if (do_ipv6) { if (cfg_do_listen) do_listen(PF_INET6, &daddr6, sizeof(daddr6)); do_main(PF_INET6); } return test_failed; }
linux-master
tools/testing/selftests/net/txtimestamp.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <sched.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> #ifndef SO_NETNS_COOKIE #define SO_NETNS_COOKIE 71 #endif #define pr_err(fmt, ...) \ ({ \ fprintf(stderr, "%s:%d:" fmt ": %m\n", \ __func__, __LINE__, ##__VA_ARGS__); \ 1; \ }) int main(int argc, char *argvp[]) { uint64_t cookie1, cookie2; socklen_t vallen; int sock1, sock2; sock1 = socket(AF_INET, SOCK_STREAM, 0); if (sock1 < 0) return pr_err("Unable to create TCP socket"); vallen = sizeof(cookie1); if (getsockopt(sock1, SOL_SOCKET, SO_NETNS_COOKIE, &cookie1, &vallen) != 0) return pr_err("getsockopt(SOL_SOCKET, SO_NETNS_COOKIE)"); if (!cookie1) return pr_err("SO_NETNS_COOKIE returned zero cookie"); if (unshare(CLONE_NEWNET)) return pr_err("unshare"); sock2 = socket(AF_INET, SOCK_STREAM, 0); if (sock2 < 0) return pr_err("Unable to create TCP socket"); vallen = sizeof(cookie2); if (getsockopt(sock2, SOL_SOCKET, SO_NETNS_COOKIE, &cookie2, &vallen) != 0) return pr_err("getsockopt(SOL_SOCKET, SO_NETNS_COOKIE)"); if (!cookie2) return pr_err("SO_NETNS_COOKIE returned zero cookie"); if (cookie1 == cookie2) return pr_err("SO_NETNS_COOKIE returned identical cookies for distinct ns"); close(sock1); close(sock2); return 0; }
linux-master
tools/testing/selftests/net/so_netns_cookie.c
// SPDX-License-Identifier: GPL-2.0 #include <arpa/inet.h> #include <error.h> #include <errno.h> #include <unistd.h> int main(void) { int fd1, fd2, one = 1; struct sockaddr_in6 bind_addr = { .sin6_family = AF_INET6, .sin6_port = htons(20000), .sin6_flowinfo = htonl(0), .sin6_addr = {}, .sin6_scope_id = 0, }; inet_pton(AF_INET6, "::", &bind_addr.sin6_addr); fd1 = socket(AF_INET6, SOCK_STREAM, IPPROTO_IP); if (fd1 < 0) { error(1, errno, "socket fd1"); return -1; } if (setsockopt(fd1, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { error(1, errno, "setsockopt(SO_REUSEADDR) fd1"); goto out_err1; } if (bind(fd1, (struct sockaddr *)&bind_addr, sizeof(bind_addr))) { error(1, errno, "bind fd1"); goto out_err1; } if (listen(fd1, 0)) { error(1, errno, "listen"); goto out_err1; } fd2 = socket(AF_INET6, SOCK_STREAM, IPPROTO_IP); if (fd2 < 0) { error(1, errno, "socket fd2"); goto out_err1; } if (connect(fd2, (struct sockaddr *)&bind_addr, sizeof(bind_addr))) { error(1, errno, "bind fd2"); goto out_err2; } close(fd2); close(fd1); return 0; out_err2: close(fd2); out_err1: close(fd1); return -1; }
linux-master
tools/testing/selftests/net/sk_connect_zero_addr.c
// SPDX-License-Identifier: GPL-2.0 /* nettest - used for functional tests of networking APIs * * Copyright (c) 2013-2019 David Ahern <[email protected]>. All rights reserved. */ #define _GNU_SOURCE #include <features.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/wait.h> #include <linux/tcp.h> #include <linux/udp.h> #include <arpa/inet.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netdb.h> #include <fcntl.h> #include <libgen.h> #include <limits.h> #include <sched.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> #include <errno.h> #include <getopt.h> #include <linux/xfrm.h> #include <linux/ipsec.h> #include <linux/pfkeyv2.h> #ifndef IPV6_UNICAST_IF #define IPV6_UNICAST_IF 76 #endif #ifndef IPV6_MULTICAST_IF #define IPV6_MULTICAST_IF 17 #endif #define DEFAULT_PORT 12345 #define NS_PREFIX "/run/netns/" #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif #ifndef MIN #define MIN(a, b) ((a) < (b) ? (a) : (b)) #endif struct sock_args { /* local address */ const char *local_addr_str; const char *client_local_addr_str; union { struct in_addr in; struct in6_addr in6; } local_addr; /* remote address */ const char *remote_addr_str; union { struct in_addr in; struct in6_addr in6; } remote_addr; int scope_id; /* remote scope; v6 send only */ struct in_addr grp; /* multicast group */ unsigned int has_local_ip:1, has_remote_ip:1, has_grp:1, has_expected_laddr:1, has_expected_raddr:1, bind_test_only:1, client_dontroute:1, server_dontroute:1; unsigned short port; int type; /* DGRAM, STREAM, RAW */ int protocol; int version; /* AF_INET/AF_INET6 */ int use_setsockopt; int use_freebind; int use_cmsg; uint8_t dsfield; const char *dev; const char *server_dev; int ifindex; const char *clientns; const char *serverns; const char *password; const char *client_pw; /* prefix for MD5 password */ const char *md5_prefix_str; union { struct sockaddr_in v4; struct sockaddr_in6 v6; } md5_prefix; unsigned int prefix_len; /* 0: default, -1: force off, +1: force on */ int bind_key_ifindex; /* expected addresses and device index for connection */ const char *expected_dev; const char *expected_server_dev; int expected_ifindex; /* local address */ const char *expected_laddr_str; union { struct in_addr in; struct in6_addr in6; } expected_laddr; /* remote address */ const char *expected_raddr_str; union { struct in_addr in; struct in6_addr in6; } expected_raddr; /* ESP in UDP encap test */ int use_xfrm; /* use send() and connect() instead of sendto */ int datagram_connect; }; static int server_mode; static unsigned int prog_timeout = 5; static unsigned int interactive; static int iter = 1; static char *msg = "Hello world!"; static int msglen; static int quiet; static int try_broadcast = 1; static char *timestamp(char *timebuf, int buflen) { time_t now; now = time(NULL); if (strftime(timebuf, buflen, "%T", localtime(&now)) == 0) { memset(timebuf, 0, buflen); strncpy(timebuf, "00:00:00", buflen-1); } return timebuf; } static void log_msg(const char *format, ...) { char timebuf[64]; va_list args; if (quiet) return; fprintf(stdout, "%s %s:", timestamp(timebuf, sizeof(timebuf)), server_mode ? "server" : "client"); va_start(args, format); vfprintf(stdout, format, args); va_end(args); fflush(stdout); } static void log_error(const char *format, ...) { char timebuf[64]; va_list args; if (quiet) return; fprintf(stderr, "%s %s:", timestamp(timebuf, sizeof(timebuf)), server_mode ? "server" : "client"); va_start(args, format); vfprintf(stderr, format, args); va_end(args); fflush(stderr); } static void log_err_errno(const char *fmt, ...) { char timebuf[64]; va_list args; if (quiet) return; fprintf(stderr, "%s %s: ", timestamp(timebuf, sizeof(timebuf)), server_mode ? "server" : "client"); va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); fprintf(stderr, ": %d: %s\n", errno, strerror(errno)); fflush(stderr); } static void log_address(const char *desc, struct sockaddr *sa) { char addrstr[64]; if (quiet) return; if (sa->sa_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *) sa; log_msg("%s %s:%d\n", desc, inet_ntop(AF_INET, &s->sin_addr, addrstr, sizeof(addrstr)), ntohs(s->sin_port)); } else if (sa->sa_family == AF_INET6) { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa; log_msg("%s [%s]:%d\n", desc, inet_ntop(AF_INET6, &s6->sin6_addr, addrstr, sizeof(addrstr)), ntohs(s6->sin6_port)); } fflush(stdout); } static int switch_ns(const char *ns) { char path[PATH_MAX]; int fd, ret; if (geteuid()) log_error("warning: likely need root to set netns %s!\n", ns); snprintf(path, sizeof(path), "%s%s", NS_PREFIX, ns); fd = open(path, 0); if (fd < 0) { log_err_errno("Failed to open netns path; can not switch netns"); return 1; } ret = setns(fd, CLONE_NEWNET); close(fd); return ret; } static int tcp_md5sig(int sd, void *addr, socklen_t alen, struct sock_args *args) { int keylen = strlen(args->password); struct tcp_md5sig md5sig = {}; int opt = TCP_MD5SIG; int rc; md5sig.tcpm_keylen = keylen; memcpy(md5sig.tcpm_key, args->password, keylen); if (args->prefix_len) { opt = TCP_MD5SIG_EXT; md5sig.tcpm_flags |= TCP_MD5SIG_FLAG_PREFIX; md5sig.tcpm_prefixlen = args->prefix_len; addr = &args->md5_prefix; } memcpy(&md5sig.tcpm_addr, addr, alen); if ((args->ifindex && args->bind_key_ifindex >= 0) || args->bind_key_ifindex >= 1) { opt = TCP_MD5SIG_EXT; md5sig.tcpm_flags |= TCP_MD5SIG_FLAG_IFINDEX; md5sig.tcpm_ifindex = args->ifindex; log_msg("TCP_MD5SIG_FLAG_IFINDEX set tcpm_ifindex=%d\n", md5sig.tcpm_ifindex); } else { log_msg("TCP_MD5SIG_FLAG_IFINDEX off\n", md5sig.tcpm_ifindex); } rc = setsockopt(sd, IPPROTO_TCP, opt, &md5sig, sizeof(md5sig)); if (rc < 0) { /* ENOENT is harmless. Returned when a password is cleared */ if (errno == ENOENT) rc = 0; else log_err_errno("setsockopt(TCP_MD5SIG)"); } return rc; } static int tcp_md5_remote(int sd, struct sock_args *args) { struct sockaddr_in sin = { .sin_family = AF_INET, }; struct sockaddr_in6 sin6 = { .sin6_family = AF_INET6, }; void *addr; int alen; switch (args->version) { case AF_INET: sin.sin_port = htons(args->port); sin.sin_addr = args->md5_prefix.v4.sin_addr; addr = &sin; alen = sizeof(sin); break; case AF_INET6: sin6.sin6_port = htons(args->port); sin6.sin6_addr = args->md5_prefix.v6.sin6_addr; addr = &sin6; alen = sizeof(sin6); break; default: log_error("unknown address family\n"); exit(1); } if (tcp_md5sig(sd, addr, alen, args)) return -1; return 0; } static int get_ifidx(const char *ifname) { struct ifreq ifdata; int sd, rc; if (!ifname || *ifname == '\0') return -1; memset(&ifdata, 0, sizeof(ifdata)); strcpy(ifdata.ifr_name, ifname); sd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); if (sd < 0) { log_err_errno("socket failed"); return -1; } rc = ioctl(sd, SIOCGIFINDEX, (char *)&ifdata); close(sd); if (rc != 0) { log_err_errno("ioctl(SIOCGIFINDEX) failed"); return -1; } return ifdata.ifr_ifindex; } static int bind_to_device(int sd, const char *name) { int rc; rc = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, name, strlen(name)+1); if (rc < 0) log_err_errno("setsockopt(SO_BINDTODEVICE)"); return rc; } static int get_bind_to_device(int sd, char *name, size_t len) { int rc; socklen_t optlen = len; name[0] = '\0'; rc = getsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, name, &optlen); if (rc < 0) log_err_errno("setsockopt(SO_BINDTODEVICE)"); return rc; } static int check_device(int sd, struct sock_args *args) { int ifindex = 0; char name[32]; if (get_bind_to_device(sd, name, sizeof(name))) *name = '\0'; else ifindex = get_ifidx(name); log_msg(" bound to device %s/%d\n", *name ? name : "<none>", ifindex); if (!args->expected_ifindex) return 0; if (args->expected_ifindex != ifindex) { log_error("Device index mismatch: expected %d have %d\n", args->expected_ifindex, ifindex); return 1; } log_msg("Device index matches: expected %d have %d\n", args->expected_ifindex, ifindex); return 0; } static int set_pktinfo_v4(int sd) { int one = 1; int rc; rc = setsockopt(sd, SOL_IP, IP_PKTINFO, &one, sizeof(one)); if (rc < 0 && rc != -ENOTSUP) log_err_errno("setsockopt(IP_PKTINFO)"); return rc; } static int set_recvpktinfo_v6(int sd) { int one = 1; int rc; rc = setsockopt(sd, SOL_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one)); if (rc < 0 && rc != -ENOTSUP) log_err_errno("setsockopt(IPV6_RECVPKTINFO)"); return rc; } static int set_recverr_v4(int sd) { int one = 1; int rc; rc = setsockopt(sd, SOL_IP, IP_RECVERR, &one, sizeof(one)); if (rc < 0 && rc != -ENOTSUP) log_err_errno("setsockopt(IP_RECVERR)"); return rc; } static int set_recverr_v6(int sd) { int one = 1; int rc; rc = setsockopt(sd, SOL_IPV6, IPV6_RECVERR, &one, sizeof(one)); if (rc < 0 && rc != -ENOTSUP) log_err_errno("setsockopt(IPV6_RECVERR)"); return rc; } static int set_unicast_if(int sd, int ifindex, int version) { int opt = IP_UNICAST_IF; int level = SOL_IP; int rc; ifindex = htonl(ifindex); if (version == AF_INET6) { opt = IPV6_UNICAST_IF; level = SOL_IPV6; } rc = setsockopt(sd, level, opt, &ifindex, sizeof(ifindex)); if (rc < 0) log_err_errno("setsockopt(IP_UNICAST_IF)"); return rc; } static int set_multicast_if(int sd, int ifindex) { struct ip_mreqn mreq = { .imr_ifindex = ifindex }; int rc; rc = setsockopt(sd, SOL_IP, IP_MULTICAST_IF, &mreq, sizeof(mreq)); if (rc < 0) log_err_errno("setsockopt(IP_MULTICAST_IF)"); return rc; } static int set_membership(int sd, uint32_t grp, uint32_t addr, int ifindex) { uint32_t if_addr = addr; struct ip_mreqn mreq; int rc; if (addr == htonl(INADDR_ANY) && !ifindex) { log_error("Either local address or device needs to be given for multicast membership\n"); return -1; } mreq.imr_multiaddr.s_addr = grp; mreq.imr_address.s_addr = if_addr; mreq.imr_ifindex = ifindex; rc = setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); if (rc < 0) { log_err_errno("setsockopt(IP_ADD_MEMBERSHIP)"); return -1; } return 0; } static int set_freebind(int sd, int version) { unsigned int one = 1; int rc = 0; switch (version) { case AF_INET: if (setsockopt(sd, SOL_IP, IP_FREEBIND, &one, sizeof(one))) { log_err_errno("setsockopt(IP_FREEBIND)"); rc = -1; } break; case AF_INET6: if (setsockopt(sd, SOL_IPV6, IPV6_FREEBIND, &one, sizeof(one))) { log_err_errno("setsockopt(IPV6_FREEBIND"); rc = -1; } break; } return rc; } static int set_broadcast(int sd) { unsigned int one = 1; int rc = 0; if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one)) != 0) { log_err_errno("setsockopt(SO_BROADCAST)"); rc = -1; } return rc; } static int set_reuseport(int sd) { unsigned int one = 1; int rc = 0; if (setsockopt(sd, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)) != 0) { log_err_errno("setsockopt(SO_REUSEPORT)"); rc = -1; } return rc; } static int set_reuseaddr(int sd) { unsigned int one = 1; int rc = 0; if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) != 0) { log_err_errno("setsockopt(SO_REUSEADDR)"); rc = -1; } return rc; } static int set_dsfield(int sd, int version, int dsfield) { if (!dsfield) return 0; switch (version) { case AF_INET: if (setsockopt(sd, SOL_IP, IP_TOS, &dsfield, sizeof(dsfield)) < 0) { log_err_errno("setsockopt(IP_TOS)"); return -1; } break; case AF_INET6: if (setsockopt(sd, SOL_IPV6, IPV6_TCLASS, &dsfield, sizeof(dsfield)) < 0) { log_err_errno("setsockopt(IPV6_TCLASS)"); return -1; } break; default: log_error("Invalid address family\n"); return -1; } return 0; } static int set_dontroute(int sd) { unsigned int one = 1; if (setsockopt(sd, SOL_SOCKET, SO_DONTROUTE, &one, sizeof(one)) < 0) { log_err_errno("setsockopt(SO_DONTROUTE)"); return -1; } return 0; } static int str_to_uint(const char *str, int min, int max, unsigned int *value) { int number; char *end; errno = 0; number = (unsigned int) strtoul(str, &end, 0); /* entire string should be consumed by conversion * and value should be between min and max */ if (((*end == '\0') || (*end == '\n')) && (end != str) && (errno != ERANGE) && (min <= number) && (number <= max)) { *value = number; return 0; } return -1; } static int resolve_devices(struct sock_args *args) { if (args->dev) { args->ifindex = get_ifidx(args->dev); if (args->ifindex < 0) { log_error("Invalid device name\n"); return 1; } } if (args->expected_dev) { unsigned int tmp; if (str_to_uint(args->expected_dev, 0, INT_MAX, &tmp) == 0) { args->expected_ifindex = (int)tmp; } else { args->expected_ifindex = get_ifidx(args->expected_dev); if (args->expected_ifindex < 0) { fprintf(stderr, "Invalid expected device\n"); return 1; } } } return 0; } static int expected_addr_match(struct sockaddr *sa, void *expected, const char *desc) { char addrstr[64]; int rc = 0; if (sa->sa_family == AF_INET) { struct sockaddr_in *s = (struct sockaddr_in *) sa; struct in_addr *exp_in = (struct in_addr *) expected; if (s->sin_addr.s_addr != exp_in->s_addr) { log_error("%s address does not match expected %s\n", desc, inet_ntop(AF_INET, exp_in, addrstr, sizeof(addrstr))); rc = 1; } } else if (sa->sa_family == AF_INET6) { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa; struct in6_addr *exp_in = (struct in6_addr *) expected; if (memcmp(&s6->sin6_addr, exp_in, sizeof(*exp_in))) { log_error("%s address does not match expected %s\n", desc, inet_ntop(AF_INET6, exp_in, addrstr, sizeof(addrstr))); rc = 1; } } else { log_error("%s address does not match expected - unknown family\n", desc); rc = 1; } if (!rc) log_msg("%s address matches expected\n", desc); return rc; } static int show_sockstat(int sd, struct sock_args *args) { struct sockaddr_in6 local_addr, remote_addr; socklen_t alen = sizeof(local_addr); struct sockaddr *sa; const char *desc; int rc = 0; desc = server_mode ? "server local:" : "client local:"; sa = (struct sockaddr *) &local_addr; if (getsockname(sd, sa, &alen) == 0) { log_address(desc, sa); if (args->has_expected_laddr) { rc = expected_addr_match(sa, &args->expected_laddr, "local"); } } else { log_err_errno("getsockname failed"); } sa = (struct sockaddr *) &remote_addr; desc = server_mode ? "server peer:" : "client peer:"; if (getpeername(sd, sa, &alen) == 0) { log_address(desc, sa); if (args->has_expected_raddr) { rc |= expected_addr_match(sa, &args->expected_raddr, "remote"); } } else { log_err_errno("getpeername failed"); } return rc; } enum addr_type { ADDR_TYPE_LOCAL, ADDR_TYPE_REMOTE, ADDR_TYPE_MCAST, ADDR_TYPE_EXPECTED_LOCAL, ADDR_TYPE_EXPECTED_REMOTE, ADDR_TYPE_MD5_PREFIX, }; static int convert_addr(struct sock_args *args, const char *_str, enum addr_type atype) { int pfx_len_max = args->version == AF_INET6 ? 128 : 32; int family = args->version; char *str, *dev, *sep; struct in6_addr *in6; struct in_addr *in; const char *desc; void *addr; int rc = 0; str = strdup(_str); if (!str) return -ENOMEM; switch (atype) { case ADDR_TYPE_LOCAL: desc = "local"; addr = &args->local_addr; break; case ADDR_TYPE_REMOTE: desc = "remote"; addr = &args->remote_addr; break; case ADDR_TYPE_MCAST: desc = "mcast grp"; addr = &args->grp; break; case ADDR_TYPE_EXPECTED_LOCAL: desc = "expected local"; addr = &args->expected_laddr; break; case ADDR_TYPE_EXPECTED_REMOTE: desc = "expected remote"; addr = &args->expected_raddr; break; case ADDR_TYPE_MD5_PREFIX: desc = "md5 prefix"; if (family == AF_INET) { args->md5_prefix.v4.sin_family = AF_INET; addr = &args->md5_prefix.v4.sin_addr; } else if (family == AF_INET6) { args->md5_prefix.v6.sin6_family = AF_INET6; addr = &args->md5_prefix.v6.sin6_addr; } else return 1; sep = strchr(str, '/'); if (sep) { *sep = '\0'; sep++; if (str_to_uint(sep, 1, pfx_len_max, &args->prefix_len) != 0) { fprintf(stderr, "Invalid port\n"); return 1; } } else { args->prefix_len = 0; } break; default: log_error("unknown address type\n"); exit(1); } switch (family) { case AF_INET: in = (struct in_addr *) addr; if (str) { if (inet_pton(AF_INET, str, in) == 0) { log_error("Invalid %s IP address\n", desc); rc = -1; goto out; } } else { in->s_addr = htonl(INADDR_ANY); } break; case AF_INET6: dev = strchr(str, '%'); if (dev) { *dev = '\0'; dev++; } in6 = (struct in6_addr *) addr; if (str) { if (inet_pton(AF_INET6, str, in6) == 0) { log_error("Invalid %s IPv6 address\n", desc); rc = -1; goto out; } } else { *in6 = in6addr_any; } if (dev) { args->scope_id = get_ifidx(dev); if (args->scope_id < 0) { log_error("Invalid scope on %s IPv6 address\n", desc); rc = -1; goto out; } } break; default: log_error("Invalid address family\n"); } out: free(str); return rc; } static int validate_addresses(struct sock_args *args) { if (args->local_addr_str && convert_addr(args, args->local_addr_str, ADDR_TYPE_LOCAL) < 0) return 1; if (args->remote_addr_str && convert_addr(args, args->remote_addr_str, ADDR_TYPE_REMOTE) < 0) return 1; if (args->md5_prefix_str && convert_addr(args, args->md5_prefix_str, ADDR_TYPE_MD5_PREFIX) < 0) return 1; if (args->expected_laddr_str && convert_addr(args, args->expected_laddr_str, ADDR_TYPE_EXPECTED_LOCAL)) return 1; if (args->expected_raddr_str && convert_addr(args, args->expected_raddr_str, ADDR_TYPE_EXPECTED_REMOTE)) return 1; return 0; } static int get_index_from_cmsg(struct msghdr *m) { struct cmsghdr *cm; int ifindex = 0; char buf[64]; for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(m); m->msg_controllen != 0 && cm; cm = (struct cmsghdr *)CMSG_NXTHDR(m, cm)) { if (cm->cmsg_level == SOL_IP && cm->cmsg_type == IP_PKTINFO) { struct in_pktinfo *pi; pi = (struct in_pktinfo *)(CMSG_DATA(cm)); inet_ntop(AF_INET, &pi->ipi_addr, buf, sizeof(buf)); ifindex = pi->ipi_ifindex; } else if (cm->cmsg_level == SOL_IPV6 && cm->cmsg_type == IPV6_PKTINFO) { struct in6_pktinfo *pi6; pi6 = (struct in6_pktinfo *)(CMSG_DATA(cm)); inet_ntop(AF_INET6, &pi6->ipi6_addr, buf, sizeof(buf)); ifindex = pi6->ipi6_ifindex; } } if (ifindex) { log_msg(" pktinfo: ifindex %d dest addr %s\n", ifindex, buf); } return ifindex; } static int send_msg_no_cmsg(int sd, void *addr, socklen_t alen) { int err; again: err = sendto(sd, msg, msglen, 0, addr, alen); if (err < 0) { if (errno == EACCES && try_broadcast) { try_broadcast = 0; if (!set_broadcast(sd)) goto again; errno = EACCES; } log_err_errno("sendto failed"); return 1; } return 0; } static int send_msg_cmsg(int sd, void *addr, socklen_t alen, int ifindex, int version) { unsigned char cmsgbuf[64]; struct iovec iov[2]; struct cmsghdr *cm; struct msghdr m; int err; iov[0].iov_base = msg; iov[0].iov_len = msglen; m.msg_iov = iov; m.msg_iovlen = 1; m.msg_name = (caddr_t)addr; m.msg_namelen = alen; memset(cmsgbuf, 0, sizeof(cmsgbuf)); cm = (struct cmsghdr *)cmsgbuf; m.msg_control = (caddr_t)cm; if (version == AF_INET) { struct in_pktinfo *pi; cm->cmsg_level = SOL_IP; cm->cmsg_type = IP_PKTINFO; cm->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); pi = (struct in_pktinfo *)(CMSG_DATA(cm)); pi->ipi_ifindex = ifindex; m.msg_controllen = cm->cmsg_len; } else if (version == AF_INET6) { struct in6_pktinfo *pi6; cm->cmsg_level = SOL_IPV6; cm->cmsg_type = IPV6_PKTINFO; cm->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); pi6 = (struct in6_pktinfo *)(CMSG_DATA(cm)); pi6->ipi6_ifindex = ifindex; m.msg_controllen = cm->cmsg_len; } again: err = sendmsg(sd, &m, 0); if (err < 0) { if (errno == EACCES && try_broadcast) { try_broadcast = 0; if (!set_broadcast(sd)) goto again; errno = EACCES; } log_err_errno("sendmsg failed"); return 1; } return 0; } static int send_msg(int sd, void *addr, socklen_t alen, struct sock_args *args) { if (args->type == SOCK_STREAM) { if (write(sd, msg, msglen) < 0) { log_err_errno("write failed sending msg to peer"); return 1; } } else if (args->datagram_connect) { if (send(sd, msg, msglen, 0) < 0) { log_err_errno("send failed sending msg to peer"); return 1; } } else if (args->ifindex && args->use_cmsg) { if (send_msg_cmsg(sd, addr, alen, args->ifindex, args->version)) return 1; } else { if (send_msg_no_cmsg(sd, addr, alen)) return 1; } log_msg("Sent message:\n"); log_msg(" %.24s%s\n", msg, msglen > 24 ? " ..." : ""); return 0; } static int socket_read_dgram(int sd, struct sock_args *args) { unsigned char addr[sizeof(struct sockaddr_in6)]; struct sockaddr *sa = (struct sockaddr *) addr; socklen_t alen = sizeof(addr); struct iovec iov[2]; struct msghdr m = { .msg_name = (caddr_t)addr, .msg_namelen = alen, .msg_iov = iov, .msg_iovlen = 1, }; unsigned char cmsgbuf[256]; struct cmsghdr *cm = (struct cmsghdr *)cmsgbuf; char buf[16*1024]; int ifindex; int len; iov[0].iov_base = (caddr_t)buf; iov[0].iov_len = sizeof(buf); memset(cmsgbuf, 0, sizeof(cmsgbuf)); m.msg_control = (caddr_t)cm; m.msg_controllen = sizeof(cmsgbuf); len = recvmsg(sd, &m, 0); if (len == 0) { log_msg("peer closed connection.\n"); return 0; } else if (len < 0) { log_msg("failed to read message: %d: %s\n", errno, strerror(errno)); return -1; } buf[len] = '\0'; log_address("Message from:", sa); log_msg(" %.24s%s\n", buf, len > 24 ? " ..." : ""); ifindex = get_index_from_cmsg(&m); if (args->expected_ifindex) { if (args->expected_ifindex != ifindex) { log_error("Device index mismatch: expected %d have %d\n", args->expected_ifindex, ifindex); return -1; } log_msg("Device index matches: expected %d have %d\n", args->expected_ifindex, ifindex); } if (!interactive && server_mode) { if (sa->sa_family == AF_INET6) { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa; struct in6_addr *in6 = &s6->sin6_addr; if (IN6_IS_ADDR_V4MAPPED(in6)) { const uint32_t *pa = (uint32_t *) &in6->s6_addr; struct in_addr in4; struct sockaddr_in *sin; sin = (struct sockaddr_in *) addr; pa += 3; in4.s_addr = *pa; sin->sin_addr = in4; sin->sin_family = AF_INET; if (send_msg_cmsg(sd, addr, alen, ifindex, AF_INET) < 0) goto out_err; } } again: iov[0].iov_len = len; if (args->version == AF_INET6) { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) sa; if (args->dev) { /* avoid PKTINFO conflicts with bindtodev */ if (sendto(sd, buf, len, 0, (void *) addr, alen) < 0) goto out_err; } else { /* kernel is allowing scope_id to be set to VRF * index for LLA. for sends to global address * reset scope id */ s6->sin6_scope_id = ifindex; if (sendmsg(sd, &m, 0) < 0) goto out_err; } } else { int err; err = sendmsg(sd, &m, 0); if (err < 0) { if (errno == EACCES && try_broadcast) { try_broadcast = 0; if (!set_broadcast(sd)) goto again; errno = EACCES; } goto out_err; } } log_msg("Sent message:\n"); log_msg(" %.24s%s\n", buf, len > 24 ? " ..." : ""); } return 1; out_err: log_err_errno("failed to send msg to peer"); return -1; } static int socket_read_stream(int sd) { char buf[1024]; int len; len = read(sd, buf, sizeof(buf)-1); if (len == 0) { log_msg("client closed connection.\n"); return 0; } else if (len < 0) { log_msg("failed to read message\n"); return -1; } buf[len] = '\0'; log_msg("Incoming message:\n"); log_msg(" %.24s%s\n", buf, len > 24 ? " ..." : ""); if (!interactive && server_mode) { if (write(sd, buf, len) < 0) { log_err_errno("failed to send buf"); return -1; } log_msg("Sent message:\n"); log_msg(" %.24s%s\n", buf, len > 24 ? " ..." : ""); } return 1; } static int socket_read(int sd, struct sock_args *args) { if (args->type == SOCK_STREAM) return socket_read_stream(sd); return socket_read_dgram(sd, args); } static int stdin_to_socket(int sd, int type, void *addr, socklen_t alen) { char buf[1024]; int len; if (fgets(buf, sizeof(buf), stdin) == NULL) return 0; len = strlen(buf); if (type == SOCK_STREAM) { if (write(sd, buf, len) < 0) { log_err_errno("failed to send buf"); return -1; } } else { int err; again: err = sendto(sd, buf, len, 0, addr, alen); if (err < 0) { if (errno == EACCES && try_broadcast) { try_broadcast = 0; if (!set_broadcast(sd)) goto again; errno = EACCES; } log_err_errno("failed to send msg to peer"); return -1; } } log_msg("Sent message:\n"); log_msg(" %.24s%s\n", buf, len > 24 ? " ..." : ""); return 1; } static void set_recv_attr(int sd, int version) { if (version == AF_INET6) { set_recvpktinfo_v6(sd); set_recverr_v6(sd); } else { set_pktinfo_v4(sd); set_recverr_v4(sd); } } static int msg_loop(int client, int sd, void *addr, socklen_t alen, struct sock_args *args) { struct timeval timeout = { .tv_sec = prog_timeout }, *ptval = NULL; fd_set rfds; int nfds; int rc; if (args->type != SOCK_STREAM) set_recv_attr(sd, args->version); if (msg) { msglen = strlen(msg); /* client sends first message */ if (client) { if (send_msg(sd, addr, alen, args)) return 1; } if (!interactive) { ptval = &timeout; if (!prog_timeout) timeout.tv_sec = 5; } } nfds = interactive ? MAX(fileno(stdin), sd) + 1 : sd + 1; while (1) { FD_ZERO(&rfds); FD_SET(sd, &rfds); if (interactive) FD_SET(fileno(stdin), &rfds); rc = select(nfds, &rfds, NULL, NULL, ptval); if (rc < 0) { if (errno == EINTR) continue; rc = 1; log_err_errno("select failed"); break; } else if (rc == 0) { log_error("Timed out waiting for response\n"); rc = 2; break; } if (FD_ISSET(sd, &rfds)) { rc = socket_read(sd, args); if (rc < 0) { rc = 1; break; } if (rc == 0) break; } rc = 0; if (FD_ISSET(fileno(stdin), &rfds)) { if (stdin_to_socket(sd, args->type, addr, alen) <= 0) break; } if (interactive) continue; if (iter != -1) { --iter; if (iter == 0) break; } log_msg("Going into quiet mode\n"); quiet = 1; if (client) { if (send_msg(sd, addr, alen, args)) { rc = 1; break; } } } return rc; } static int msock_init(struct sock_args *args, int server) { uint32_t if_addr = htonl(INADDR_ANY); struct sockaddr_in laddr = { .sin_family = AF_INET, .sin_port = htons(args->port), }; int one = 1; int sd; if (!server && args->has_local_ip) if_addr = args->local_addr.in.s_addr; sd = socket(PF_INET, SOCK_DGRAM, 0); if (sd < 0) { log_err_errno("socket"); return -1; } if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one)) < 0) { log_err_errno("Setting SO_REUSEADDR error"); goto out_err; } if (setsockopt(sd, SOL_SOCKET, SO_BROADCAST, (char *)&one, sizeof(one)) < 0) log_err_errno("Setting SO_BROADCAST error"); if (set_dsfield(sd, AF_INET, args->dsfield) != 0) goto out_err; if (server) { if (args->server_dontroute && set_dontroute(sd) != 0) goto out_err; } else { if (args->client_dontroute && set_dontroute(sd) != 0) goto out_err; } if (args->dev && bind_to_device(sd, args->dev) != 0) goto out_err; else if (args->use_setsockopt && set_multicast_if(sd, args->ifindex)) goto out_err; laddr.sin_addr.s_addr = if_addr; if (bind(sd, (struct sockaddr *) &laddr, sizeof(laddr)) < 0) { log_err_errno("bind failed"); goto out_err; } if (server && set_membership(sd, args->grp.s_addr, args->local_addr.in.s_addr, args->ifindex)) goto out_err; return sd; out_err: close(sd); return -1; } static int msock_server(struct sock_args *args) { return msock_init(args, 1); } static int msock_client(struct sock_args *args) { return msock_init(args, 0); } static int bind_socket(int sd, struct sock_args *args) { struct sockaddr_in serv_addr = { .sin_family = AF_INET, }; struct sockaddr_in6 serv6_addr = { .sin6_family = AF_INET6, }; void *addr; socklen_t alen; if (!args->has_local_ip && args->type == SOCK_RAW) return 0; switch (args->version) { case AF_INET: serv_addr.sin_port = htons(args->port); serv_addr.sin_addr = args->local_addr.in; addr = &serv_addr; alen = sizeof(serv_addr); break; case AF_INET6: serv6_addr.sin6_port = htons(args->port); serv6_addr.sin6_addr = args->local_addr.in6; addr = &serv6_addr; alen = sizeof(serv6_addr); break; default: log_error("Invalid address family\n"); return -1; } if (bind(sd, addr, alen) < 0) { log_err_errno("error binding socket"); return -1; } return 0; } static int config_xfrm_policy(int sd, struct sock_args *args) { struct xfrm_userpolicy_info policy = {}; int type = UDP_ENCAP_ESPINUDP; int xfrm_af = IP_XFRM_POLICY; int level = SOL_IP; if (args->type != SOCK_DGRAM) { log_error("Invalid socket type. Only DGRAM could be used for XFRM\n"); return 1; } policy.action = XFRM_POLICY_ALLOW; policy.sel.family = args->version; if (args->version == AF_INET6) { xfrm_af = IPV6_XFRM_POLICY; level = SOL_IPV6; } policy.dir = XFRM_POLICY_OUT; if (setsockopt(sd, level, xfrm_af, &policy, sizeof(policy)) < 0) return 1; policy.dir = XFRM_POLICY_IN; if (setsockopt(sd, level, xfrm_af, &policy, sizeof(policy)) < 0) return 1; if (setsockopt(sd, IPPROTO_UDP, UDP_ENCAP, &type, sizeof(type)) < 0) { log_err_errno("Failed to set xfrm encap"); return 1; } return 0; } static int lsock_init(struct sock_args *args) { long flags; int sd; sd = socket(args->version, args->type, args->protocol); if (sd < 0) { log_err_errno("Error opening socket"); return -1; } if (set_reuseaddr(sd) != 0) goto err; if (set_reuseport(sd) != 0) goto err; if (set_dsfield(sd, args->version, args->dsfield) != 0) goto err; if (args->server_dontroute && set_dontroute(sd) != 0) goto err; if (args->dev && bind_to_device(sd, args->dev) != 0) goto err; else if (args->use_setsockopt && set_unicast_if(sd, args->ifindex, args->version)) goto err; if (args->use_freebind && set_freebind(sd, args->version)) goto err; if (bind_socket(sd, args)) goto err; if (args->bind_test_only) goto out; if (args->type == SOCK_STREAM && listen(sd, 1) < 0) { log_err_errno("listen failed"); goto err; } flags = fcntl(sd, F_GETFL); if ((flags < 0) || (fcntl(sd, F_SETFL, flags|O_NONBLOCK) < 0)) { log_err_errno("Failed to set non-blocking option"); goto err; } if (fcntl(sd, F_SETFD, FD_CLOEXEC) < 0) log_err_errno("Failed to set close-on-exec flag"); if (args->use_xfrm && config_xfrm_policy(sd, args)) { log_err_errno("Failed to set xfrm policy"); goto err; } out: return sd; err: close(sd); return -1; } static void ipc_write(int fd, int message) { /* Not in both_mode, so there's no process to signal */ if (fd < 0) return; if (write(fd, &message, sizeof(message)) < 0) log_err_errno("Failed to send client status"); } static int do_server(struct sock_args *args, int ipc_fd) { /* ipc_fd = -1 if no parent process to signal */ struct timeval timeout = { .tv_sec = prog_timeout }, *ptval = NULL; unsigned char addr[sizeof(struct sockaddr_in6)] = {}; socklen_t alen = sizeof(addr); int lsd, csd = -1; fd_set rfds; int rc; if (args->serverns) { if (switch_ns(args->serverns)) { log_error("Could not set server netns to %s\n", args->serverns); goto err_exit; } log_msg("Switched server netns\n"); } args->dev = args->server_dev; args->expected_dev = args->expected_server_dev; if (resolve_devices(args) || validate_addresses(args)) goto err_exit; if (prog_timeout) ptval = &timeout; if (args->has_grp) lsd = msock_server(args); else lsd = lsock_init(args); if (lsd < 0) goto err_exit; if (args->bind_test_only) { close(lsd); ipc_write(ipc_fd, 1); return 0; } if (args->type != SOCK_STREAM) { ipc_write(ipc_fd, 1); rc = msg_loop(0, lsd, (void *) addr, alen, args); close(lsd); return rc; } if (args->password && tcp_md5_remote(lsd, args)) { close(lsd); goto err_exit; } ipc_write(ipc_fd, 1); while (1) { log_msg("waiting for client connection.\n"); FD_ZERO(&rfds); FD_SET(lsd, &rfds); rc = select(lsd+1, &rfds, NULL, NULL, ptval); if (rc == 0) { rc = 2; break; } if (rc < 0) { if (errno == EINTR) continue; log_err_errno("select failed"); break; } if (FD_ISSET(lsd, &rfds)) { csd = accept(lsd, (void *) addr, &alen); if (csd < 0) { log_err_errno("accept failed"); break; } rc = show_sockstat(csd, args); if (rc) break; rc = check_device(csd, args); if (rc) break; } rc = msg_loop(0, csd, (void *) addr, alen, args); close(csd); if (!interactive) break; } close(lsd); return rc; err_exit: ipc_write(ipc_fd, 0); return 1; } static int wait_for_connect(int sd) { struct timeval _tv = { .tv_sec = prog_timeout }, *tv = NULL; fd_set wfd; int val = 0, sz = sizeof(val); int rc; FD_ZERO(&wfd); FD_SET(sd, &wfd); if (prog_timeout) tv = &_tv; rc = select(FD_SETSIZE, NULL, &wfd, NULL, tv); if (rc == 0) { log_error("connect timed out\n"); return -2; } else if (rc < 0) { log_err_errno("select failed"); return -3; } if (getsockopt(sd, SOL_SOCKET, SO_ERROR, &val, (socklen_t *)&sz) < 0) { log_err_errno("getsockopt(SO_ERROR) failed"); return -4; } if (val != 0) { log_error("connect failed: %d: %s\n", val, strerror(val)); return -1; } return 0; } static int connectsock(void *addr, socklen_t alen, struct sock_args *args) { int sd, rc = -1; long flags; sd = socket(args->version, args->type, args->protocol); if (sd < 0) { log_err_errno("Failed to create socket"); return -1; } flags = fcntl(sd, F_GETFL); if ((flags < 0) || (fcntl(sd, F_SETFL, flags|O_NONBLOCK) < 0)) { log_err_errno("Failed to set non-blocking option"); goto err; } if (set_reuseport(sd) != 0) goto err; if (set_dsfield(sd, args->version, args->dsfield) != 0) goto err; if (args->client_dontroute && set_dontroute(sd) != 0) goto err; if (args->dev && bind_to_device(sd, args->dev) != 0) goto err; else if (args->use_setsockopt && set_unicast_if(sd, args->ifindex, args->version)) goto err; if (args->has_local_ip && bind_socket(sd, args)) goto err; if (args->type != SOCK_STREAM && !args->datagram_connect) goto out; if (args->password && tcp_md5sig(sd, addr, alen, args)) goto err; if (args->bind_test_only) goto out; if (connect(sd, addr, alen) < 0) { if (errno != EINPROGRESS) { log_err_errno("Failed to connect to remote host"); rc = -1; goto err; } rc = wait_for_connect(sd); if (rc < 0) goto err; } out: return sd; err: close(sd); return rc; } static int do_client(struct sock_args *args) { struct sockaddr_in sin = { .sin_family = AF_INET, }; struct sockaddr_in6 sin6 = { .sin6_family = AF_INET6, }; void *addr; int alen; int rc = 0; int sd; if (!args->has_remote_ip && !args->has_grp) { fprintf(stderr, "remote IP or multicast group not given\n"); return 1; } if (args->clientns) { if (switch_ns(args->clientns)) { log_error("Could not set client netns to %s\n", args->clientns); return 1; } log_msg("Switched client netns\n"); } args->local_addr_str = args->client_local_addr_str; if (resolve_devices(args) || validate_addresses(args)) return 1; if ((args->use_setsockopt || args->use_cmsg) && !args->ifindex) { fprintf(stderr, "Device binding not specified\n"); return 1; } if (args->use_setsockopt || args->use_cmsg) args->dev = NULL; switch (args->version) { case AF_INET: sin.sin_port = htons(args->port); if (args->has_grp) sin.sin_addr = args->grp; else sin.sin_addr = args->remote_addr.in; addr = &sin; alen = sizeof(sin); break; case AF_INET6: sin6.sin6_port = htons(args->port); sin6.sin6_addr = args->remote_addr.in6; sin6.sin6_scope_id = args->scope_id; addr = &sin6; alen = sizeof(sin6); break; } args->password = args->client_pw; if (args->has_grp) sd = msock_client(args); else sd = connectsock(addr, alen, args); if (sd < 0) return -sd; if (args->bind_test_only) goto out; if (args->type == SOCK_STREAM) { rc = show_sockstat(sd, args); if (rc != 0) goto out; } rc = msg_loop(1, sd, addr, alen, args); out: close(sd); return rc; } static char *random_msg(int len) { int i, n = 0, olen = len + 1; char *m; if (len <= 0) return NULL; m = malloc(olen); if (!m) return NULL; while (len > 26) { i = snprintf(m + n, olen - n, "%.26s", "abcdefghijklmnopqrstuvwxyz"); n += i; len -= i; } i = snprintf(m + n, olen - n, "%.*s", len, "abcdefghijklmnopqrstuvwxyz"); return m; } static int ipc_child(int fd, struct sock_args *args) { char *outbuf, *errbuf; int rc = 1; outbuf = malloc(4096); errbuf = malloc(4096); if (!outbuf || !errbuf) { fprintf(stderr, "server: Failed to allocate buffers for stdout and stderr\n"); goto out; } setbuffer(stdout, outbuf, 4096); setbuffer(stderr, errbuf, 4096); server_mode = 1; /* to tell log_msg in case we are in both_mode */ /* when running in both mode, address validation applies * solely to client side */ args->has_expected_laddr = 0; args->has_expected_raddr = 0; rc = do_server(args, fd); out: free(outbuf); free(errbuf); return rc; } static int ipc_parent(int cpid, int fd, struct sock_args *args) { int client_status; int status; int buf; /* do the client-side function here in the parent process, * waiting to be told when to continue */ if (read(fd, &buf, sizeof(buf)) <= 0) { log_err_errno("Failed to read IPC status from status"); return 1; } if (!buf) { log_error("Server failed; can not continue\n"); return 1; } log_msg("Server is ready\n"); client_status = do_client(args); log_msg("parent is done!\n"); if (kill(cpid, 0) == 0) kill(cpid, SIGKILL); wait(&status); return client_status; } #define GETOPT_STR "sr:l:c:Q:p:t:g:P:DRn:M:X:m:d:I:BN:O:SUCi6xL:0:1:2:3:Fbqf" #define OPT_FORCE_BIND_KEY_IFINDEX 1001 #define OPT_NO_BIND_KEY_IFINDEX 1002 #define OPT_CLIENT_DONTROUTE 1003 #define OPT_SERVER_DONTROUTE 1004 static struct option long_opts[] = { {"force-bind-key-ifindex", 0, 0, OPT_FORCE_BIND_KEY_IFINDEX}, {"no-bind-key-ifindex", 0, 0, OPT_NO_BIND_KEY_IFINDEX}, {"client-dontroute", 0, 0, OPT_CLIENT_DONTROUTE}, {"server-dontroute", 0, 0, OPT_SERVER_DONTROUTE}, {0, 0, 0, 0} }; static void print_usage(char *prog) { printf( "usage: %s OPTS\n" "Required:\n" " -r addr remote address to connect to (client mode only)\n" " -p port port to connect to (client mode)/listen on (server mode)\n" " (default: %d)\n" " -s server mode (default: client mode)\n" " -t timeout seconds (default: none)\n" "\n" "Optional:\n" " -B do both client and server via fork and IPC\n" " -N ns set client to network namespace ns (requires root)\n" " -O ns set server to network namespace ns (requires root)\n" " -F Restart server loop\n" " -6 IPv6 (default is IPv4)\n" " -P proto protocol for socket: icmp, ospf (default: none)\n" " -D|R datagram (D) / raw (R) socket (default stream)\n" " -l addr local address to bind to in server mode\n" " -c addr local address to bind to in client mode\n" " -Q dsfield DS Field value of the socket (the IP_TOS or\n" " IPV6_TCLASS socket option)\n" " -x configure XFRM policy on socket\n" "\n" " -d dev bind socket to given device name\n" " -I dev bind socket to given device name - server mode\n" " -S use setsockopt (IP_UNICAST_IF or IP_MULTICAST_IF)\n" " to set device binding\n" " -U Use connect() and send() for datagram sockets\n" " -f bind socket with the IP[V6]_FREEBIND option\n" " -C use cmsg and IP_PKTINFO to specify device binding\n" "\n" " -L len send random message of given length\n" " -n num number of times to send message\n" "\n" " -M password use MD5 sum protection\n" " -X password MD5 password for client mode\n" " -m prefix/len prefix and length to use for MD5 key\n" " --no-bind-key-ifindex: Force TCP_MD5SIG_FLAG_IFINDEX off\n" " --force-bind-key-ifindex: Force TCP_MD5SIG_FLAG_IFINDEX on\n" " (default: only if -I is passed)\n" " --client-dontroute: don't use gateways for client socket: send\n" " packets only if destination is on link (see\n" " SO_DONTROUTE in socket(7))\n" " --server-dontroute: don't use gateways for server socket: send\n" " packets only if destination is on link (see\n" " SO_DONTROUTE in socket(7))\n" "\n" " -g grp multicast group (e.g., 239.1.1.1)\n" " -i interactive mode (default is echo and terminate)\n" "\n" " -0 addr Expected local address\n" " -1 addr Expected remote address\n" " -2 dev Expected device name (or index) to receive packet\n" " -3 dev Expected device name (or index) to receive packets - server mode\n" "\n" " -b Bind test only.\n" " -q Be quiet. Run test without printing anything.\n" , prog, DEFAULT_PORT); } int main(int argc, char *argv[]) { struct sock_args args = { .version = AF_INET, .type = SOCK_STREAM, .port = DEFAULT_PORT, }; struct protoent *pe; int both_mode = 0; unsigned int tmp; int forever = 0; int fd[2]; int cpid; /* process inputs */ extern char *optarg; int rc = 0; /* * process input args */ while ((rc = getopt_long(argc, argv, GETOPT_STR, long_opts, NULL)) != -1) { switch (rc) { case 'B': both_mode = 1; break; case 's': server_mode = 1; break; case 'F': forever = 1; break; case 'l': args.has_local_ip = 1; args.local_addr_str = optarg; break; case 'r': args.has_remote_ip = 1; args.remote_addr_str = optarg; break; case 'c': args.has_local_ip = 1; args.client_local_addr_str = optarg; break; case 'Q': if (str_to_uint(optarg, 0, 255, &tmp) != 0) { fprintf(stderr, "Invalid DS Field\n"); return 1; } args.dsfield = tmp; break; case 'p': if (str_to_uint(optarg, 1, 65535, &tmp) != 0) { fprintf(stderr, "Invalid port\n"); return 1; } args.port = (unsigned short) tmp; break; case 't': if (str_to_uint(optarg, 0, INT_MAX, &prog_timeout) != 0) { fprintf(stderr, "Invalid timeout\n"); return 1; } break; case 'D': args.type = SOCK_DGRAM; break; case 'R': args.type = SOCK_RAW; args.port = 0; if (!args.protocol) args.protocol = IPPROTO_RAW; break; case 'P': pe = getprotobyname(optarg); if (pe) { args.protocol = pe->p_proto; } else { if (str_to_uint(optarg, 0, 0xffff, &tmp) != 0) { fprintf(stderr, "Invalid protocol\n"); return 1; } args.protocol = tmp; } break; case 'n': iter = atoi(optarg); break; case 'N': args.clientns = optarg; break; case 'O': args.serverns = optarg; break; case 'L': msg = random_msg(atoi(optarg)); break; case 'M': args.password = optarg; break; case OPT_FORCE_BIND_KEY_IFINDEX: args.bind_key_ifindex = 1; break; case OPT_NO_BIND_KEY_IFINDEX: args.bind_key_ifindex = -1; break; case OPT_CLIENT_DONTROUTE: args.client_dontroute = 1; break; case OPT_SERVER_DONTROUTE: args.server_dontroute = 1; break; case 'X': args.client_pw = optarg; break; case 'm': args.md5_prefix_str = optarg; break; case 'S': args.use_setsockopt = 1; break; case 'f': args.use_freebind = 1; break; case 'C': args.use_cmsg = 1; break; case 'd': args.dev = optarg; break; case 'I': args.server_dev = optarg; break; case 'i': interactive = 1; break; case 'g': args.has_grp = 1; if (convert_addr(&args, optarg, ADDR_TYPE_MCAST) < 0) return 1; args.type = SOCK_DGRAM; break; case '6': args.version = AF_INET6; break; case 'b': args.bind_test_only = 1; break; case '0': args.has_expected_laddr = 1; args.expected_laddr_str = optarg; break; case '1': args.has_expected_raddr = 1; args.expected_raddr_str = optarg; break; case '2': args.expected_dev = optarg; break; case '3': args.expected_server_dev = optarg; break; case 'q': quiet = 1; break; case 'x': args.use_xfrm = 1; break; case 'U': args.datagram_connect = 1; break; default: print_usage(argv[0]); return 1; } } if (args.password && ((!args.has_remote_ip && !args.md5_prefix_str) || args.type != SOCK_STREAM)) { log_error("MD5 passwords apply to TCP only and require a remote ip for the password\n"); return 1; } if (args.md5_prefix_str && !args.password) { log_error("Prefix range for MD5 protection specified without a password\n"); return 1; } if (iter == 0) { fprintf(stderr, "Invalid number of messages to send\n"); return 1; } if (args.type == SOCK_STREAM && !args.protocol) args.protocol = IPPROTO_TCP; if (args.type == SOCK_DGRAM && !args.protocol) args.protocol = IPPROTO_UDP; if ((args.type == SOCK_STREAM || args.type == SOCK_DGRAM) && args.port == 0) { fprintf(stderr, "Invalid port number\n"); return 1; } if ((both_mode || !server_mode) && !args.has_grp && !args.has_remote_ip && !args.has_local_ip) { fprintf(stderr, "Local (server mode) or remote IP (client IP) required\n"); return 1; } if (interactive) { prog_timeout = 0; msg = NULL; } if (both_mode) { if (pipe(fd) < 0) { perror("pipe"); exit(1); } cpid = fork(); if (cpid < 0) { perror("fork"); exit(1); } if (cpid) return ipc_parent(cpid, fd[0], &args); return ipc_child(fd[1], &args); } if (server_mode) { do { rc = do_server(&args, -1); } while (forever); return rc; } return do_client(&args); }
linux-master
tools/testing/selftests/net/nettest.c
// SPDX-License-Identifier: GPL-2.0 #include <arpa/inet.h> #include <error.h> #include <errno.h> #include <unistd.h> int main(void) { int fd1, fd2, one = 1; struct sockaddr_in6 bind_addr = { .sin6_family = AF_INET6, .sin6_port = htons(20000), .sin6_flowinfo = htonl(0), .sin6_addr = {}, .sin6_scope_id = 0, }; inet_pton(AF_INET6, "::", &bind_addr.sin6_addr); fd1 = socket(AF_INET6, SOCK_STREAM, IPPROTO_IP); if (fd1 < 0) { error(1, errno, "socket fd1"); return -1; } if (setsockopt(fd1, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { error(1, errno, "setsockopt(SO_REUSEADDR) fd1"); goto out_err1; } if (bind(fd1, (struct sockaddr *)&bind_addr, sizeof(bind_addr))) { error(1, errno, "bind fd1"); goto out_err1; } if (sendto(fd1, NULL, 0, MSG_FASTOPEN, (struct sockaddr *)&bind_addr, sizeof(bind_addr))) { error(1, errno, "sendto fd1"); goto out_err1; } fd2 = socket(AF_INET6, SOCK_STREAM, IPPROTO_IP); if (fd2 < 0) { error(1, errno, "socket fd2"); goto out_err1; } if (setsockopt(fd2, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { error(1, errno, "setsockopt(SO_REUSEADDR) fd2"); goto out_err2; } if (bind(fd2, (struct sockaddr *)&bind_addr, sizeof(bind_addr))) { error(1, errno, "bind fd2"); goto out_err2; } if (sendto(fd2, NULL, 0, MSG_FASTOPEN, (struct sockaddr *)&bind_addr, sizeof(bind_addr)) != -1) { error(1, errno, "sendto fd2"); goto out_err2; } if (listen(fd2, 0)) { error(1, errno, "listen"); goto out_err2; } close(fd2); close(fd1); return 0; out_err2: close(fd2); out_err1: close(fd1); return -1; }
linux-master
tools/testing/selftests/net/sk_bind_sendto_listen.c
// SPDX-License-Identifier: GPL-2.0 #include <stdio.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include "../kselftest.h" struct socket_testcase { int domain; int type; int protocol; /* 0 = valid file descriptor * -foo = error foo */ int expect; /* If non-zero, accept EAFNOSUPPORT to handle the case * of the protocol not being configured into the kernel. */ int nosupport_ok; }; static struct socket_testcase tests[] = { { AF_MAX, 0, 0, -EAFNOSUPPORT, 0 }, { AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 1 }, { AF_INET, SOCK_DGRAM, IPPROTO_TCP, -EPROTONOSUPPORT, 1 }, { AF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, 1 }, { AF_INET, SOCK_STREAM, IPPROTO_UDP, -EPROTONOSUPPORT, 1 }, }; #define ERR_STRING_SZ 64 static int run_tests(void) { char err_string1[ERR_STRING_SZ]; char err_string2[ERR_STRING_SZ]; int i, err; err = 0; for (i = 0; i < ARRAY_SIZE(tests); i++) { struct socket_testcase *s = &tests[i]; int fd; fd = socket(s->domain, s->type, s->protocol); if (fd < 0) { if (s->nosupport_ok && errno == EAFNOSUPPORT) continue; if (s->expect < 0 && errno == -s->expect) continue; strerror_r(-s->expect, err_string1, ERR_STRING_SZ); strerror_r(errno, err_string2, ERR_STRING_SZ); fprintf(stderr, "socket(%d, %d, %d) expected " "err (%s) got (%s)\n", s->domain, s->type, s->protocol, err_string1, err_string2); err = -1; break; } else { close(fd); if (s->expect < 0) { strerror_r(errno, err_string1, ERR_STRING_SZ); fprintf(stderr, "socket(%d, %d, %d) expected " "success got err (%s)\n", s->domain, s->type, s->protocol, err_string1); err = -1; break; } } } return err; } int main(void) { int err = run_tests(); return err; }
linux-master
tools/testing/selftests/net/socket.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <linux/if.h> #include <linux/if_tun.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <sys/ioctl.h> #include <sys/socket.h> #include "../kselftest_harness.h" static int tun_attach(int fd, char *dev) { struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, dev); ifr.ifr_flags = IFF_ATTACH_QUEUE; return ioctl(fd, TUNSETQUEUE, (void *) &ifr); } static int tun_detach(int fd, char *dev) { struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, dev); ifr.ifr_flags = IFF_DETACH_QUEUE; return ioctl(fd, TUNSETQUEUE, (void *) &ifr); } static int tun_alloc(char *dev) { struct ifreq ifr; int fd, err; fd = open("/dev/net/tun", O_RDWR); if (fd < 0) { fprintf(stderr, "can't open tun: %s\n", strerror(errno)); return fd; } memset(&ifr, 0, sizeof(ifr)); strcpy(ifr.ifr_name, dev); ifr.ifr_flags = IFF_TAP | IFF_NAPI | IFF_MULTI_QUEUE; err = ioctl(fd, TUNSETIFF, (void *) &ifr); if (err < 0) { fprintf(stderr, "can't TUNSETIFF: %s\n", strerror(errno)); close(fd); return err; } strcpy(dev, ifr.ifr_name); return fd; } static int tun_delete(char *dev) { struct { struct nlmsghdr nh; struct ifinfomsg ifm; unsigned char data[64]; } req; struct rtattr *rta; int ret, rtnl; rtnl = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); if (rtnl < 0) { fprintf(stderr, "can't open rtnl: %s\n", strerror(errno)); return 1; } memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_ALIGN(NLMSG_LENGTH(sizeof(req.ifm))); req.nh.nlmsg_flags = NLM_F_REQUEST; req.nh.nlmsg_type = RTM_DELLINK; req.ifm.ifi_family = AF_UNSPEC; rta = (struct rtattr *)(((char *)&req) + NLMSG_ALIGN(req.nh.nlmsg_len)); rta->rta_type = IFLA_IFNAME; rta->rta_len = RTA_LENGTH(IFNAMSIZ); req.nh.nlmsg_len += rta->rta_len; memcpy(RTA_DATA(rta), dev, IFNAMSIZ); ret = send(rtnl, &req, req.nh.nlmsg_len, 0); if (ret < 0) fprintf(stderr, "can't send: %s\n", strerror(errno)); ret = (unsigned int)ret != req.nh.nlmsg_len; close(rtnl); return ret; } FIXTURE(tun) { char ifname[IFNAMSIZ]; int fd, fd2; }; FIXTURE_SETUP(tun) { memset(self->ifname, 0, sizeof(self->ifname)); self->fd = tun_alloc(self->ifname); ASSERT_GE(self->fd, 0); self->fd2 = tun_alloc(self->ifname); ASSERT_GE(self->fd2, 0); } FIXTURE_TEARDOWN(tun) { if (self->fd >= 0) close(self->fd); if (self->fd2 >= 0) close(self->fd2); } TEST_F(tun, delete_detach_close) { EXPECT_EQ(tun_delete(self->ifname), 0); EXPECT_EQ(tun_detach(self->fd, self->ifname), -1); EXPECT_EQ(errno, 22); } TEST_F(tun, detach_delete_close) { EXPECT_EQ(tun_detach(self->fd, self->ifname), 0); EXPECT_EQ(tun_delete(self->ifname), 0); } TEST_F(tun, detach_close_delete) { EXPECT_EQ(tun_detach(self->fd, self->ifname), 0); close(self->fd); self->fd = -1; EXPECT_EQ(tun_delete(self->ifname), 0); } TEST_F(tun, reattach_delete_close) { EXPECT_EQ(tun_detach(self->fd, self->ifname), 0); EXPECT_EQ(tun_attach(self->fd, self->ifname), 0); EXPECT_EQ(tun_delete(self->ifname), 0); } TEST_F(tun, reattach_close_delete) { EXPECT_EQ(tun_detach(self->fd, self->ifname), 0); EXPECT_EQ(tun_attach(self->fd, self->ifname), 0); close(self->fd); self->fd = -1; EXPECT_EQ(tun_delete(self->ifname), 0); } TEST_HARNESS_MAIN
linux-master
tools/testing/selftests/net/tun.c
/* * Test functionality of BPF filters for SO_REUSEPORT. The tests below will use * a BPF program (both classic and extended) to read the first word from an * incoming packet (expected to be in network byte-order), calculate a modulus * of that number, and then dispatch the packet to the Nth socket using the * result. These tests are run for each supported address family and protocol. * Additionally, a few edge cases in the implementation are tested. */ #include <errno.h> #include <error.h> #include <fcntl.h> #include <linux/bpf.h> #include <linux/filter.h> #include <linux/unistd.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/resource.h> #include <unistd.h> #include "../kselftest.h" struct test_params { int recv_family; int send_family; int protocol; size_t recv_socks; uint16_t recv_port; uint16_t send_port_min; }; static size_t sockaddr_size(void) { return sizeof(struct sockaddr_storage); } static struct sockaddr *new_any_sockaddr(int family, uint16_t port) { struct sockaddr_storage *addr; struct sockaddr_in *addr4; struct sockaddr_in6 *addr6; addr = malloc(sizeof(struct sockaddr_storage)); memset(addr, 0, sizeof(struct sockaddr_storage)); switch (family) { case AF_INET: addr4 = (struct sockaddr_in *)addr; addr4->sin_family = AF_INET; addr4->sin_addr.s_addr = htonl(INADDR_ANY); addr4->sin_port = htons(port); break; case AF_INET6: addr6 = (struct sockaddr_in6 *)addr; addr6->sin6_family = AF_INET6; addr6->sin6_addr = in6addr_any; addr6->sin6_port = htons(port); break; default: error(1, 0, "Unsupported family %d", family); } return (struct sockaddr *)addr; } static struct sockaddr *new_loopback_sockaddr(int family, uint16_t port) { struct sockaddr *addr = new_any_sockaddr(family, port); struct sockaddr_in *addr4; struct sockaddr_in6 *addr6; switch (family) { case AF_INET: addr4 = (struct sockaddr_in *)addr; addr4->sin_addr.s_addr = htonl(INADDR_LOOPBACK); break; case AF_INET6: addr6 = (struct sockaddr_in6 *)addr; addr6->sin6_addr = in6addr_loopback; break; default: error(1, 0, "Unsupported family %d", family); } return addr; } static void attach_ebpf(int fd, uint16_t mod) { static char bpf_log_buf[65536]; static const char bpf_license[] = "GPL"; int bpf_fd; const struct bpf_insn prog[] = { /* BPF_MOV64_REG(BPF_REG_6, BPF_REG_1) */ { BPF_ALU64 | BPF_MOV | BPF_X, BPF_REG_6, BPF_REG_1, 0, 0 }, /* BPF_LD_ABS(BPF_W, 0) R0 = (uint32_t)skb[0] */ { BPF_LD | BPF_ABS | BPF_W, 0, 0, 0, 0 }, /* BPF_ALU64_IMM(BPF_MOD, BPF_REG_0, mod) */ { BPF_ALU64 | BPF_MOD | BPF_K, BPF_REG_0, 0, 0, mod }, /* BPF_EXIT_INSN() */ { BPF_JMP | BPF_EXIT, 0, 0, 0, 0 } }; union bpf_attr attr; memset(&attr, 0, sizeof(attr)); attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; attr.insn_cnt = ARRAY_SIZE(prog); attr.insns = (unsigned long) &prog; attr.license = (unsigned long) &bpf_license; attr.log_buf = (unsigned long) &bpf_log_buf; attr.log_size = sizeof(bpf_log_buf); attr.log_level = 1; attr.kern_version = 0; bpf_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &attr, sizeof(attr)); if (bpf_fd < 0) error(1, errno, "ebpf error. log:\n%s\n", bpf_log_buf); if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_REUSEPORT_EBPF, &bpf_fd, sizeof(bpf_fd))) error(1, errno, "failed to set SO_ATTACH_REUSEPORT_EBPF"); close(bpf_fd); } static void attach_cbpf(int fd, uint16_t mod) { struct sock_filter code[] = { /* A = (uint32_t)skb[0] */ { BPF_LD | BPF_W | BPF_ABS, 0, 0, 0 }, /* A = A % mod */ { BPF_ALU | BPF_MOD, 0, 0, mod }, /* return A */ { BPF_RET | BPF_A, 0, 0, 0 }, }; struct sock_fprog p = { .len = ARRAY_SIZE(code), .filter = code, }; if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_REUSEPORT_CBPF, &p, sizeof(p))) error(1, errno, "failed to set SO_ATTACH_REUSEPORT_CBPF"); } static void build_recv_group(const struct test_params p, int fd[], uint16_t mod, void (*attach_bpf)(int, uint16_t)) { struct sockaddr * const addr = new_any_sockaddr(p.recv_family, p.recv_port); int i, opt; for (i = 0; i < p.recv_socks; ++i) { fd[i] = socket(p.recv_family, p.protocol, 0); if (fd[i] < 0) error(1, errno, "failed to create recv %d", i); opt = 1; if (setsockopt(fd[i], SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT on %d", i); if (i == 0) attach_bpf(fd[i], mod); if (bind(fd[i], addr, sockaddr_size())) error(1, errno, "failed to bind recv socket %d", i); if (p.protocol == SOCK_STREAM) { opt = 4; if (setsockopt(fd[i], SOL_TCP, TCP_FASTOPEN, &opt, sizeof(opt))) error(1, errno, "failed to set TCP_FASTOPEN on %d", i); if (listen(fd[i], p.recv_socks * 10)) error(1, errno, "failed to listen on socket"); } } free(addr); } static void send_from(struct test_params p, uint16_t sport, char *buf, size_t len) { struct sockaddr * const saddr = new_any_sockaddr(p.send_family, sport); struct sockaddr * const daddr = new_loopback_sockaddr(p.send_family, p.recv_port); const int fd = socket(p.send_family, p.protocol, 0), one = 1; if (fd < 0) error(1, errno, "failed to create send socket"); if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) error(1, errno, "failed to set reuseaddr"); if (bind(fd, saddr, sockaddr_size())) error(1, errno, "failed to bind send socket"); if (sendto(fd, buf, len, MSG_FASTOPEN, daddr, sockaddr_size()) < 0) error(1, errno, "failed to send message"); close(fd); free(saddr); free(daddr); } static void test_recv_order(const struct test_params p, int fd[], int mod) { char recv_buf[8], send_buf[8]; struct msghdr msg; struct iovec recv_io = { recv_buf, 8 }; struct epoll_event ev; int epfd, conn, i, sport, expected; uint32_t data, ndata; epfd = epoll_create(1); if (epfd < 0) error(1, errno, "failed to create epoll"); for (i = 0; i < p.recv_socks; ++i) { ev.events = EPOLLIN; ev.data.fd = fd[i]; if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd[i], &ev)) error(1, errno, "failed to register sock %d epoll", i); } memset(&msg, 0, sizeof(msg)); msg.msg_iov = &recv_io; msg.msg_iovlen = 1; for (data = 0; data < p.recv_socks * 2; ++data) { sport = p.send_port_min + data; ndata = htonl(data); memcpy(send_buf, &ndata, sizeof(ndata)); send_from(p, sport, send_buf, sizeof(ndata)); i = epoll_wait(epfd, &ev, 1, -1); if (i < 0) error(1, errno, "epoll wait failed"); if (p.protocol == SOCK_STREAM) { conn = accept(ev.data.fd, NULL, NULL); if (conn < 0) error(1, errno, "error accepting"); i = recvmsg(conn, &msg, 0); close(conn); } else { i = recvmsg(ev.data.fd, &msg, 0); } if (i < 0) error(1, errno, "recvmsg error"); if (i != sizeof(ndata)) error(1, 0, "expected size %zd got %d", sizeof(ndata), i); for (i = 0; i < p.recv_socks; ++i) if (ev.data.fd == fd[i]) break; memcpy(&ndata, recv_buf, sizeof(ndata)); fprintf(stderr, "Socket %d: %d\n", i, ntohl(ndata)); expected = (sport % mod); if (i != expected) error(1, 0, "expected socket %d", expected); } } static void test_reuseport_ebpf(struct test_params p) { int i, fd[p.recv_socks]; fprintf(stderr, "Testing EBPF mod %zd...\n", p.recv_socks); build_recv_group(p, fd, p.recv_socks, attach_ebpf); test_recv_order(p, fd, p.recv_socks); p.send_port_min += p.recv_socks * 2; fprintf(stderr, "Reprograming, testing mod %zd...\n", p.recv_socks / 2); attach_ebpf(fd[0], p.recv_socks / 2); test_recv_order(p, fd, p.recv_socks / 2); for (i = 0; i < p.recv_socks; ++i) close(fd[i]); } static void test_reuseport_cbpf(struct test_params p) { int i, fd[p.recv_socks]; fprintf(stderr, "Testing CBPF mod %zd...\n", p.recv_socks); build_recv_group(p, fd, p.recv_socks, attach_cbpf); test_recv_order(p, fd, p.recv_socks); p.send_port_min += p.recv_socks * 2; fprintf(stderr, "Reprograming, testing mod %zd...\n", p.recv_socks / 2); attach_cbpf(fd[0], p.recv_socks / 2); test_recv_order(p, fd, p.recv_socks / 2); for (i = 0; i < p.recv_socks; ++i) close(fd[i]); } static void test_extra_filter(const struct test_params p) { struct sockaddr * const addr = new_any_sockaddr(p.recv_family, p.recv_port); int fd1, fd2, opt; fprintf(stderr, "Testing too many filters...\n"); fd1 = socket(p.recv_family, p.protocol, 0); if (fd1 < 0) error(1, errno, "failed to create socket 1"); fd2 = socket(p.recv_family, p.protocol, 0); if (fd2 < 0) error(1, errno, "failed to create socket 2"); opt = 1; if (setsockopt(fd1, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT on socket 1"); if (setsockopt(fd2, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT on socket 2"); attach_ebpf(fd1, 10); attach_ebpf(fd2, 10); if (bind(fd1, addr, sockaddr_size())) error(1, errno, "failed to bind recv socket 1"); if (!bind(fd2, addr, sockaddr_size()) || errno != EADDRINUSE) error(1, errno, "bind socket 2 should fail with EADDRINUSE"); free(addr); } static void test_filter_no_reuseport(const struct test_params p) { struct sockaddr * const addr = new_any_sockaddr(p.recv_family, p.recv_port); const char bpf_license[] = "GPL"; struct bpf_insn ecode[] = { { BPF_ALU64 | BPF_MOV | BPF_K, BPF_REG_0, 0, 0, 10 }, { BPF_JMP | BPF_EXIT, 0, 0, 0, 0 } }; struct sock_filter ccode[] = {{ BPF_RET | BPF_A, 0, 0, 0 }}; union bpf_attr eprog; struct sock_fprog cprog; int fd, bpf_fd; fprintf(stderr, "Testing filters on non-SO_REUSEPORT socket...\n"); memset(&eprog, 0, sizeof(eprog)); eprog.prog_type = BPF_PROG_TYPE_SOCKET_FILTER; eprog.insn_cnt = ARRAY_SIZE(ecode); eprog.insns = (unsigned long) &ecode; eprog.license = (unsigned long) &bpf_license; eprog.kern_version = 0; memset(&cprog, 0, sizeof(cprog)); cprog.len = ARRAY_SIZE(ccode); cprog.filter = ccode; bpf_fd = syscall(__NR_bpf, BPF_PROG_LOAD, &eprog, sizeof(eprog)); if (bpf_fd < 0) error(1, errno, "ebpf error"); fd = socket(p.recv_family, p.protocol, 0); if (fd < 0) error(1, errno, "failed to create socket 1"); if (bind(fd, addr, sockaddr_size())) error(1, errno, "failed to bind recv socket 1"); errno = 0; if (!setsockopt(fd, SOL_SOCKET, SO_ATTACH_REUSEPORT_EBPF, &bpf_fd, sizeof(bpf_fd)) || errno != EINVAL) error(1, errno, "setsockopt should have returned EINVAL"); errno = 0; if (!setsockopt(fd, SOL_SOCKET, SO_ATTACH_REUSEPORT_CBPF, &cprog, sizeof(cprog)) || errno != EINVAL) error(1, errno, "setsockopt should have returned EINVAL"); free(addr); } static void test_filter_without_bind(void) { int fd1, fd2, opt = 1; fprintf(stderr, "Testing filter add without bind...\n"); fd1 = socket(AF_INET, SOCK_DGRAM, 0); if (fd1 < 0) error(1, errno, "failed to create socket 1"); fd2 = socket(AF_INET, SOCK_DGRAM, 0); if (fd2 < 0) error(1, errno, "failed to create socket 2"); if (setsockopt(fd1, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT on socket 1"); if (setsockopt(fd2, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT on socket 2"); attach_ebpf(fd1, 10); attach_cbpf(fd2, 10); close(fd1); close(fd2); } void enable_fastopen(void) { int fd = open("/proc/sys/net/ipv4/tcp_fastopen", 0); int rw_mask = 3; /* bit 1: client side; bit-2 server side */ int val, size; char buf[16]; if (fd < 0) error(1, errno, "Unable to open tcp_fastopen sysctl"); if (read(fd, buf, sizeof(buf)) <= 0) error(1, errno, "Unable to read tcp_fastopen sysctl"); val = atoi(buf); close(fd); if ((val & rw_mask) != rw_mask) { fd = open("/proc/sys/net/ipv4/tcp_fastopen", O_RDWR); if (fd < 0) error(1, errno, "Unable to open tcp_fastopen sysctl for writing"); val |= rw_mask; size = snprintf(buf, 16, "%d", val); if (write(fd, buf, size) <= 0) error(1, errno, "Unable to write tcp_fastopen sysctl"); close(fd); } } static struct rlimit rlim_old; static __attribute__((constructor)) void main_ctor(void) { getrlimit(RLIMIT_MEMLOCK, &rlim_old); if (rlim_old.rlim_cur != RLIM_INFINITY) { struct rlimit rlim_new; rlim_new.rlim_cur = rlim_old.rlim_cur + (1UL << 20); rlim_new.rlim_max = rlim_old.rlim_max + (1UL << 20); setrlimit(RLIMIT_MEMLOCK, &rlim_new); } } static __attribute__((destructor)) void main_dtor(void) { setrlimit(RLIMIT_MEMLOCK, &rlim_old); } int main(void) { fprintf(stderr, "---- IPv4 UDP ----\n"); /* NOTE: UDP socket lookups traverse a different code path when there * are > 10 sockets in a group. Run the bpf test through both paths. */ test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET, .send_family = AF_INET, .protocol = SOCK_DGRAM, .recv_socks = 10, .recv_port = 8000, .send_port_min = 9000}); test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET, .send_family = AF_INET, .protocol = SOCK_DGRAM, .recv_socks = 20, .recv_port = 8000, .send_port_min = 9000}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET, .send_family = AF_INET, .protocol = SOCK_DGRAM, .recv_socks = 10, .recv_port = 8001, .send_port_min = 9020}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET, .send_family = AF_INET, .protocol = SOCK_DGRAM, .recv_socks = 20, .recv_port = 8001, .send_port_min = 9020}); test_extra_filter((struct test_params) { .recv_family = AF_INET, .protocol = SOCK_DGRAM, .recv_port = 8002}); test_filter_no_reuseport((struct test_params) { .recv_family = AF_INET, .protocol = SOCK_DGRAM, .recv_port = 8008}); fprintf(stderr, "---- IPv6 UDP ----\n"); test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET6, .protocol = SOCK_DGRAM, .recv_socks = 10, .recv_port = 8003, .send_port_min = 9040}); test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET6, .protocol = SOCK_DGRAM, .recv_socks = 20, .recv_port = 8003, .send_port_min = 9040}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET6, .protocol = SOCK_DGRAM, .recv_socks = 10, .recv_port = 8004, .send_port_min = 9060}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET6, .protocol = SOCK_DGRAM, .recv_socks = 20, .recv_port = 8004, .send_port_min = 9060}); test_extra_filter((struct test_params) { .recv_family = AF_INET6, .protocol = SOCK_DGRAM, .recv_port = 8005}); test_filter_no_reuseport((struct test_params) { .recv_family = AF_INET6, .protocol = SOCK_DGRAM, .recv_port = 8009}); fprintf(stderr, "---- IPv6 UDP w/ mapped IPv4 ----\n"); test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET, .protocol = SOCK_DGRAM, .recv_socks = 20, .recv_port = 8006, .send_port_min = 9080}); test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET, .protocol = SOCK_DGRAM, .recv_socks = 10, .recv_port = 8006, .send_port_min = 9080}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET, .protocol = SOCK_DGRAM, .recv_socks = 10, .recv_port = 8007, .send_port_min = 9100}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET, .protocol = SOCK_DGRAM, .recv_socks = 20, .recv_port = 8007, .send_port_min = 9100}); /* TCP fastopen is required for the TCP tests */ enable_fastopen(); fprintf(stderr, "---- IPv4 TCP ----\n"); test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET, .send_family = AF_INET, .protocol = SOCK_STREAM, .recv_socks = 10, .recv_port = 8008, .send_port_min = 9120}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET, .send_family = AF_INET, .protocol = SOCK_STREAM, .recv_socks = 10, .recv_port = 8009, .send_port_min = 9160}); test_extra_filter((struct test_params) { .recv_family = AF_INET, .protocol = SOCK_STREAM, .recv_port = 8010}); test_filter_no_reuseport((struct test_params) { .recv_family = AF_INET, .protocol = SOCK_STREAM, .recv_port = 8011}); fprintf(stderr, "---- IPv6 TCP ----\n"); test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET6, .protocol = SOCK_STREAM, .recv_socks = 10, .recv_port = 8012, .send_port_min = 9200}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET6, .protocol = SOCK_STREAM, .recv_socks = 10, .recv_port = 8013, .send_port_min = 9240}); test_extra_filter((struct test_params) { .recv_family = AF_INET6, .protocol = SOCK_STREAM, .recv_port = 8014}); test_filter_no_reuseport((struct test_params) { .recv_family = AF_INET6, .protocol = SOCK_STREAM, .recv_port = 8015}); fprintf(stderr, "---- IPv6 TCP w/ mapped IPv4 ----\n"); test_reuseport_ebpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET, .protocol = SOCK_STREAM, .recv_socks = 10, .recv_port = 8016, .send_port_min = 9320}); test_reuseport_cbpf((struct test_params) { .recv_family = AF_INET6, .send_family = AF_INET, .protocol = SOCK_STREAM, .recv_socks = 10, .recv_port = 8017, .send_port_min = 9360}); test_filter_without_bind(); fprintf(stderr, "SUCCESS\n"); return 0; }
linux-master
tools/testing/selftests/net/reuseport_bpf.c
// SPDX-License-Identifier: GPL-2.0 /* * This testsuite provides conformance testing for GRO coalescing. * * Test cases: * 1.data * Data packets of the same size and same header setup with correct * sequence numbers coalesce. The one exception being the last data * packet coalesced: it can be smaller than the rest and coalesced * as long as it is in the same flow. * 2.ack * Pure ACK does not coalesce. * 3.flags * Specific test cases: no packets with PSH, SYN, URG, RST set will * be coalesced. * 4.tcp * Packets with incorrect checksum, non-consecutive seqno and * different TCP header options shouldn't coalesce. Nit: given that * some extension headers have paddings, such as timestamp, headers * that are padding differently would not be coalesced. * 5.ip: * Packets with different (ECN, TTL, TOS) header, ip options or * ip fragments (ipv6) shouldn't coalesce. * 6.large: * Packets larger than GRO_MAX_SIZE packets shouldn't coalesce. * * MSS is defined as 4096 - header because if it is too small * (i.e. 1500 MTU - header), it will result in many packets, * increasing the "large" test case's flakiness. This is because * due to time sensitivity in the coalescing window, the receiver * may not coalesce all of the packets. * * Note the timing issue applies to all of the test cases, so some * flakiness is to be expected. * */ #define _GNU_SOURCE #include <arpa/inet.h> #include <errno.h> #include <error.h> #include <getopt.h> #include <linux/filter.h> #include <linux/if_packet.h> #include <linux/ipv6.h> #include <net/ethernet.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/tcp.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <unistd.h> #include "../kselftest.h" #define DPORT 8000 #define SPORT 1500 #define PAYLOAD_LEN 100 #define NUM_PACKETS 4 #define START_SEQ 100 #define START_ACK 100 #define ETH_P_NONE 0 #define TOTAL_HDR_LEN (ETH_HLEN + sizeof(struct ipv6hdr) + sizeof(struct tcphdr)) #define MSS (4096 - sizeof(struct tcphdr) - sizeof(struct ipv6hdr)) #define MAX_PAYLOAD (IP_MAXPACKET - sizeof(struct tcphdr) - sizeof(struct ipv6hdr)) #define NUM_LARGE_PKT (MAX_PAYLOAD / MSS) #define MAX_HDR_LEN (ETH_HLEN + sizeof(struct ipv6hdr) + sizeof(struct tcphdr)) static const char *addr6_src = "fdaa::2"; static const char *addr6_dst = "fdaa::1"; static const char *addr4_src = "192.168.1.200"; static const char *addr4_dst = "192.168.1.100"; static int proto = -1; static uint8_t src_mac[ETH_ALEN], dst_mac[ETH_ALEN]; static char *testname = "data"; static char *ifname = "eth0"; static char *smac = "aa:00:00:00:00:02"; static char *dmac = "aa:00:00:00:00:01"; static bool verbose; static bool tx_socket = true; static int tcp_offset = -1; static int total_hdr_len = -1; static int ethhdr_proto = -1; static void vlog(const char *fmt, ...) { va_list args; if (verbose) { va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); } } static void setup_sock_filter(int fd) { const int dport_off = tcp_offset + offsetof(struct tcphdr, dest); const int ethproto_off = offsetof(struct ethhdr, h_proto); int optlen = 0; int ipproto_off; int next_off; if (proto == PF_INET) next_off = offsetof(struct iphdr, protocol); else next_off = offsetof(struct ipv6hdr, nexthdr); ipproto_off = ETH_HLEN + next_off; if (strcmp(testname, "ip") == 0) { if (proto == PF_INET) optlen = sizeof(struct ip_timestamp); else optlen = sizeof(struct ip6_frag); } struct sock_filter filter[] = { BPF_STMT(BPF_LD + BPF_H + BPF_ABS, ethproto_off), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ntohs(ethhdr_proto), 0, 7), BPF_STMT(BPF_LD + BPF_B + BPF_ABS, ipproto_off), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_TCP, 0, 5), BPF_STMT(BPF_LD + BPF_H + BPF_ABS, dport_off), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, DPORT, 2, 0), BPF_STMT(BPF_LD + BPF_H + BPF_ABS, dport_off + optlen), BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, DPORT, 0, 1), BPF_STMT(BPF_RET + BPF_K, 0xFFFFFFFF), BPF_STMT(BPF_RET + BPF_K, 0), }; struct sock_fprog bpf = { .len = ARRAY_SIZE(filter), .filter = filter, }; if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf)) < 0) error(1, errno, "error setting filter"); } static uint32_t checksum_nofold(void *data, size_t len, uint32_t sum) { uint16_t *words = data; int i; for (i = 0; i < len / 2; i++) sum += words[i]; if (len & 1) sum += ((char *)data)[len - 1]; return sum; } static uint16_t checksum_fold(void *data, size_t len, uint32_t sum) { sum = checksum_nofold(data, len, sum); while (sum > 0xFFFF) sum = (sum & 0xFFFF) + (sum >> 16); return ~sum; } static uint16_t tcp_checksum(void *buf, int payload_len) { struct pseudo_header6 { struct in6_addr saddr; struct in6_addr daddr; uint16_t protocol; uint16_t payload_len; } ph6; struct pseudo_header4 { struct in_addr saddr; struct in_addr daddr; uint16_t protocol; uint16_t payload_len; } ph4; uint32_t sum = 0; if (proto == PF_INET6) { if (inet_pton(AF_INET6, addr6_src, &ph6.saddr) != 1) error(1, errno, "inet_pton6 source ip pseudo"); if (inet_pton(AF_INET6, addr6_dst, &ph6.daddr) != 1) error(1, errno, "inet_pton6 dest ip pseudo"); ph6.protocol = htons(IPPROTO_TCP); ph6.payload_len = htons(sizeof(struct tcphdr) + payload_len); sum = checksum_nofold(&ph6, sizeof(ph6), 0); } else if (proto == PF_INET) { if (inet_pton(AF_INET, addr4_src, &ph4.saddr) != 1) error(1, errno, "inet_pton source ip pseudo"); if (inet_pton(AF_INET, addr4_dst, &ph4.daddr) != 1) error(1, errno, "inet_pton dest ip pseudo"); ph4.protocol = htons(IPPROTO_TCP); ph4.payload_len = htons(sizeof(struct tcphdr) + payload_len); sum = checksum_nofold(&ph4, sizeof(ph4), 0); } return checksum_fold(buf, sizeof(struct tcphdr) + payload_len, sum); } static void read_MAC(uint8_t *mac_addr, char *mac) { if (sscanf(mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac_addr[0], &mac_addr[1], &mac_addr[2], &mac_addr[3], &mac_addr[4], &mac_addr[5]) != 6) error(1, 0, "sscanf"); } static void fill_datalinklayer(void *buf) { struct ethhdr *eth = buf; memcpy(eth->h_dest, dst_mac, ETH_ALEN); memcpy(eth->h_source, src_mac, ETH_ALEN); eth->h_proto = ethhdr_proto; } static void fill_networklayer(void *buf, int payload_len) { struct ipv6hdr *ip6h = buf; struct iphdr *iph = buf; if (proto == PF_INET6) { memset(ip6h, 0, sizeof(*ip6h)); ip6h->version = 6; ip6h->payload_len = htons(sizeof(struct tcphdr) + payload_len); ip6h->nexthdr = IPPROTO_TCP; ip6h->hop_limit = 8; if (inet_pton(AF_INET6, addr6_src, &ip6h->saddr) != 1) error(1, errno, "inet_pton source ip6"); if (inet_pton(AF_INET6, addr6_dst, &ip6h->daddr) != 1) error(1, errno, "inet_pton dest ip6"); } else if (proto == PF_INET) { memset(iph, 0, sizeof(*iph)); iph->version = 4; iph->ihl = 5; iph->ttl = 8; iph->protocol = IPPROTO_TCP; iph->tot_len = htons(sizeof(struct tcphdr) + payload_len + sizeof(struct iphdr)); iph->frag_off = htons(0x4000); /* DF = 1, MF = 0 */ if (inet_pton(AF_INET, addr4_src, &iph->saddr) != 1) error(1, errno, "inet_pton source ip"); if (inet_pton(AF_INET, addr4_dst, &iph->daddr) != 1) error(1, errno, "inet_pton dest ip"); iph->check = checksum_fold(buf, sizeof(struct iphdr), 0); } } static void fill_transportlayer(void *buf, int seq_offset, int ack_offset, int payload_len, int fin) { struct tcphdr *tcph = buf; memset(tcph, 0, sizeof(*tcph)); tcph->source = htons(SPORT); tcph->dest = htons(DPORT); tcph->seq = ntohl(START_SEQ + seq_offset); tcph->ack_seq = ntohl(START_ACK + ack_offset); tcph->ack = 1; tcph->fin = fin; tcph->doff = 5; tcph->window = htons(TCP_MAXWIN); tcph->urg_ptr = 0; tcph->check = tcp_checksum(tcph, payload_len); } static void write_packet(int fd, char *buf, int len, struct sockaddr_ll *daddr) { int ret = -1; ret = sendto(fd, buf, len, 0, (struct sockaddr *)daddr, sizeof(*daddr)); if (ret == -1) error(1, errno, "sendto failure"); if (ret != len) error(1, errno, "sendto wrong length"); } static void create_packet(void *buf, int seq_offset, int ack_offset, int payload_len, int fin) { memset(buf, 0, total_hdr_len); memset(buf + total_hdr_len, 'a', payload_len); fill_transportlayer(buf + tcp_offset, seq_offset, ack_offset, payload_len, fin); fill_networklayer(buf + ETH_HLEN, payload_len); fill_datalinklayer(buf); } /* send one extra flag, not first and not last pkt */ static void send_flags(int fd, struct sockaddr_ll *daddr, int psh, int syn, int rst, int urg) { static char flag_buf[MAX_HDR_LEN + PAYLOAD_LEN]; static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; int payload_len, pkt_size, flag, i; struct tcphdr *tcph; payload_len = PAYLOAD_LEN * psh; pkt_size = total_hdr_len + payload_len; flag = NUM_PACKETS / 2; create_packet(flag_buf, flag * payload_len, 0, payload_len, 0); tcph = (struct tcphdr *)(flag_buf + tcp_offset); tcph->psh = psh; tcph->syn = syn; tcph->rst = rst; tcph->urg = urg; tcph->check = 0; tcph->check = tcp_checksum(tcph, payload_len); for (i = 0; i < NUM_PACKETS + 1; i++) { if (i == flag) { write_packet(fd, flag_buf, pkt_size, daddr); continue; } create_packet(buf, i * PAYLOAD_LEN, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, total_hdr_len + PAYLOAD_LEN, daddr); } } /* Test for data of same length, smaller than previous * and of different lengths */ static void send_data_pkts(int fd, struct sockaddr_ll *daddr, int payload_len1, int payload_len2) { static char buf[ETH_HLEN + IP_MAXPACKET]; create_packet(buf, 0, 0, payload_len1, 0); write_packet(fd, buf, total_hdr_len + payload_len1, daddr); create_packet(buf, payload_len1, 0, payload_len2, 0); write_packet(fd, buf, total_hdr_len + payload_len2, daddr); } /* If incoming segments make tracked segment length exceed * legal IP datagram length, do not coalesce */ static void send_large(int fd, struct sockaddr_ll *daddr, int remainder) { static char pkts[NUM_LARGE_PKT][TOTAL_HDR_LEN + MSS]; static char last[TOTAL_HDR_LEN + MSS]; static char new_seg[TOTAL_HDR_LEN + MSS]; int i; for (i = 0; i < NUM_LARGE_PKT; i++) create_packet(pkts[i], i * MSS, 0, MSS, 0); create_packet(last, NUM_LARGE_PKT * MSS, 0, remainder, 0); create_packet(new_seg, (NUM_LARGE_PKT + 1) * MSS, 0, remainder, 0); for (i = 0; i < NUM_LARGE_PKT; i++) write_packet(fd, pkts[i], total_hdr_len + MSS, daddr); write_packet(fd, last, total_hdr_len + remainder, daddr); write_packet(fd, new_seg, total_hdr_len + remainder, daddr); } /* Pure acks and dup acks don't coalesce */ static void send_ack(int fd, struct sockaddr_ll *daddr) { static char buf[MAX_HDR_LEN]; create_packet(buf, 0, 0, 0, 0); write_packet(fd, buf, total_hdr_len, daddr); write_packet(fd, buf, total_hdr_len, daddr); create_packet(buf, 0, 1, 0, 0); write_packet(fd, buf, total_hdr_len, daddr); } static void recompute_packet(char *buf, char *no_ext, int extlen) { struct tcphdr *tcphdr = (struct tcphdr *)(buf + tcp_offset); struct ipv6hdr *ip6h = (struct ipv6hdr *)(buf + ETH_HLEN); struct iphdr *iph = (struct iphdr *)(buf + ETH_HLEN); memmove(buf, no_ext, total_hdr_len); memmove(buf + total_hdr_len + extlen, no_ext + total_hdr_len, PAYLOAD_LEN); tcphdr->doff = tcphdr->doff + (extlen / 4); tcphdr->check = 0; tcphdr->check = tcp_checksum(tcphdr, PAYLOAD_LEN + extlen); if (proto == PF_INET) { iph->tot_len = htons(ntohs(iph->tot_len) + extlen); iph->check = 0; iph->check = checksum_fold(iph, sizeof(struct iphdr), 0); } else { ip6h->payload_len = htons(ntohs(ip6h->payload_len) + extlen); } } static void tcp_write_options(char *buf, int kind, int ts) { struct tcp_option_ts { uint8_t kind; uint8_t len; uint32_t tsval; uint32_t tsecr; } *opt_ts = (void *)buf; struct tcp_option_window { uint8_t kind; uint8_t len; uint8_t shift; } *opt_window = (void *)buf; switch (kind) { case TCPOPT_NOP: buf[0] = TCPOPT_NOP; break; case TCPOPT_WINDOW: memset(opt_window, 0, sizeof(struct tcp_option_window)); opt_window->kind = TCPOPT_WINDOW; opt_window->len = TCPOLEN_WINDOW; opt_window->shift = 0; break; case TCPOPT_TIMESTAMP: memset(opt_ts, 0, sizeof(struct tcp_option_ts)); opt_ts->kind = TCPOPT_TIMESTAMP; opt_ts->len = TCPOLEN_TIMESTAMP; opt_ts->tsval = ts; opt_ts->tsecr = 0; break; default: error(1, 0, "unimplemented TCP option"); break; } } /* TCP with options is always a permutation of {TS, NOP, NOP}. * Implement different orders to verify coalescing stops. */ static void add_standard_tcp_options(char *buf, char *no_ext, int ts, int order) { switch (order) { case 0: tcp_write_options(buf + total_hdr_len, TCPOPT_NOP, 0); tcp_write_options(buf + total_hdr_len + 1, TCPOPT_NOP, 0); tcp_write_options(buf + total_hdr_len + 2 /* two NOP opts */, TCPOPT_TIMESTAMP, ts); break; case 1: tcp_write_options(buf + total_hdr_len, TCPOPT_NOP, 0); tcp_write_options(buf + total_hdr_len + 1, TCPOPT_TIMESTAMP, ts); tcp_write_options(buf + total_hdr_len + 1 + TCPOLEN_TIMESTAMP, TCPOPT_NOP, 0); break; case 2: tcp_write_options(buf + total_hdr_len, TCPOPT_TIMESTAMP, ts); tcp_write_options(buf + total_hdr_len + TCPOLEN_TIMESTAMP + 1, TCPOPT_NOP, 0); tcp_write_options(buf + total_hdr_len + TCPOLEN_TIMESTAMP + 2, TCPOPT_NOP, 0); break; default: error(1, 0, "unknown order"); break; } recompute_packet(buf, no_ext, TCPOLEN_TSTAMP_APPA); } /* Packets with invalid checksum don't coalesce. */ static void send_changed_checksum(int fd, struct sockaddr_ll *daddr) { static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; struct tcphdr *tcph = (struct tcphdr *)(buf + tcp_offset); int pkt_size = total_hdr_len + PAYLOAD_LEN; create_packet(buf, 0, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN, 0, PAYLOAD_LEN, 0); tcph->check = tcph->check - 1; write_packet(fd, buf, pkt_size, daddr); } /* Packets with non-consecutive sequence number don't coalesce.*/ static void send_changed_seq(int fd, struct sockaddr_ll *daddr) { static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; struct tcphdr *tcph = (struct tcphdr *)(buf + tcp_offset); int pkt_size = total_hdr_len + PAYLOAD_LEN; create_packet(buf, 0, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN, 0, PAYLOAD_LEN, 0); tcph->seq = ntohl(htonl(tcph->seq) + 1); tcph->check = 0; tcph->check = tcp_checksum(tcph, PAYLOAD_LEN); write_packet(fd, buf, pkt_size, daddr); } /* Packet with different timestamp option or different timestamps * don't coalesce. */ static void send_changed_ts(int fd, struct sockaddr_ll *daddr) { static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; static char extpkt[sizeof(buf) + TCPOLEN_TSTAMP_APPA]; int pkt_size = total_hdr_len + PAYLOAD_LEN + TCPOLEN_TSTAMP_APPA; create_packet(buf, 0, 0, PAYLOAD_LEN, 0); add_standard_tcp_options(extpkt, buf, 0, 0); write_packet(fd, extpkt, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN, 0, PAYLOAD_LEN, 0); add_standard_tcp_options(extpkt, buf, 0, 0); write_packet(fd, extpkt, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN * 2, 0, PAYLOAD_LEN, 0); add_standard_tcp_options(extpkt, buf, 100, 0); write_packet(fd, extpkt, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN * 3, 0, PAYLOAD_LEN, 0); add_standard_tcp_options(extpkt, buf, 100, 1); write_packet(fd, extpkt, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN * 4, 0, PAYLOAD_LEN, 0); add_standard_tcp_options(extpkt, buf, 100, 2); write_packet(fd, extpkt, pkt_size, daddr); } /* Packet with different tcp options don't coalesce. */ static void send_diff_opt(int fd, struct sockaddr_ll *daddr) { static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; static char extpkt1[sizeof(buf) + TCPOLEN_TSTAMP_APPA]; static char extpkt2[sizeof(buf) + TCPOLEN_MAXSEG]; int extpkt1_size = total_hdr_len + PAYLOAD_LEN + TCPOLEN_TSTAMP_APPA; int extpkt2_size = total_hdr_len + PAYLOAD_LEN + TCPOLEN_MAXSEG; create_packet(buf, 0, 0, PAYLOAD_LEN, 0); add_standard_tcp_options(extpkt1, buf, 0, 0); write_packet(fd, extpkt1, extpkt1_size, daddr); create_packet(buf, PAYLOAD_LEN, 0, PAYLOAD_LEN, 0); add_standard_tcp_options(extpkt1, buf, 0, 0); write_packet(fd, extpkt1, extpkt1_size, daddr); create_packet(buf, PAYLOAD_LEN * 2, 0, PAYLOAD_LEN, 0); tcp_write_options(extpkt2 + MAX_HDR_LEN, TCPOPT_NOP, 0); tcp_write_options(extpkt2 + MAX_HDR_LEN + 1, TCPOPT_WINDOW, 0); recompute_packet(extpkt2, buf, TCPOLEN_WINDOW + 1); write_packet(fd, extpkt2, extpkt2_size, daddr); } static void add_ipv4_ts_option(void *buf, void *optpkt) { struct ip_timestamp *ts = (struct ip_timestamp *)(optpkt + tcp_offset); int optlen = sizeof(struct ip_timestamp); struct iphdr *iph; if (optlen % 4) error(1, 0, "ipv4 timestamp length is not a multiple of 4B"); ts->ipt_code = IPOPT_TS; ts->ipt_len = optlen; ts->ipt_ptr = 5; ts->ipt_flg = IPOPT_TS_TSONLY; memcpy(optpkt, buf, tcp_offset); memcpy(optpkt + tcp_offset + optlen, buf + tcp_offset, sizeof(struct tcphdr) + PAYLOAD_LEN); iph = (struct iphdr *)(optpkt + ETH_HLEN); iph->ihl = 5 + (optlen / 4); iph->tot_len = htons(ntohs(iph->tot_len) + optlen); iph->check = 0; iph->check = checksum_fold(iph, sizeof(struct iphdr) + optlen, 0); } /* IPv4 options shouldn't coalesce */ static void send_ip_options(int fd, struct sockaddr_ll *daddr) { static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; static char optpkt[sizeof(buf) + sizeof(struct ip_timestamp)]; int optlen = sizeof(struct ip_timestamp); int pkt_size = total_hdr_len + PAYLOAD_LEN + optlen; create_packet(buf, 0, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, total_hdr_len + PAYLOAD_LEN, daddr); create_packet(buf, PAYLOAD_LEN * 1, 0, PAYLOAD_LEN, 0); add_ipv4_ts_option(buf, optpkt); write_packet(fd, optpkt, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN * 2, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, total_hdr_len + PAYLOAD_LEN, daddr); } /* IPv4 fragments shouldn't coalesce */ static void send_fragment4(int fd, struct sockaddr_ll *daddr) { static char buf[IP_MAXPACKET]; struct iphdr *iph = (struct iphdr *)(buf + ETH_HLEN); int pkt_size = total_hdr_len + PAYLOAD_LEN; create_packet(buf, 0, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, pkt_size, daddr); /* Once fragmented, packet would retain the total_len. * Tcp header is prepared as if rest of data is in follow-up frags, * but follow up frags aren't actually sent. */ memset(buf + total_hdr_len, 'a', PAYLOAD_LEN * 2); fill_transportlayer(buf + tcp_offset, PAYLOAD_LEN, 0, PAYLOAD_LEN * 2, 0); fill_networklayer(buf + ETH_HLEN, PAYLOAD_LEN); fill_datalinklayer(buf); iph->frag_off = htons(0x6000); // DF = 1, MF = 1 iph->check = 0; iph->check = checksum_fold(iph, sizeof(struct iphdr), 0); write_packet(fd, buf, pkt_size, daddr); } /* IPv4 packets with different ttl don't coalesce.*/ static void send_changed_ttl(int fd, struct sockaddr_ll *daddr) { int pkt_size = total_hdr_len + PAYLOAD_LEN; static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; struct iphdr *iph = (struct iphdr *)(buf + ETH_HLEN); create_packet(buf, 0, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN, 0, PAYLOAD_LEN, 0); iph->ttl = 7; iph->check = 0; iph->check = checksum_fold(iph, sizeof(struct iphdr), 0); write_packet(fd, buf, pkt_size, daddr); } /* Packets with different tos don't coalesce.*/ static void send_changed_tos(int fd, struct sockaddr_ll *daddr) { int pkt_size = total_hdr_len + PAYLOAD_LEN; static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; struct iphdr *iph = (struct iphdr *)(buf + ETH_HLEN); struct ipv6hdr *ip6h = (struct ipv6hdr *)(buf + ETH_HLEN); create_packet(buf, 0, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN, 0, PAYLOAD_LEN, 0); if (proto == PF_INET) { iph->tos = 1; iph->check = 0; iph->check = checksum_fold(iph, sizeof(struct iphdr), 0); } else if (proto == PF_INET6) { ip6h->priority = 0xf; } write_packet(fd, buf, pkt_size, daddr); } /* Packets with different ECN don't coalesce.*/ static void send_changed_ECN(int fd, struct sockaddr_ll *daddr) { int pkt_size = total_hdr_len + PAYLOAD_LEN; static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; struct iphdr *iph = (struct iphdr *)(buf + ETH_HLEN); create_packet(buf, 0, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, pkt_size, daddr); create_packet(buf, PAYLOAD_LEN, 0, PAYLOAD_LEN, 0); if (proto == PF_INET) { buf[ETH_HLEN + 1] ^= 0x2; // ECN set to 10 iph->check = 0; iph->check = checksum_fold(iph, sizeof(struct iphdr), 0); } else { buf[ETH_HLEN + 1] ^= 0x20; // ECN set to 10 } write_packet(fd, buf, pkt_size, daddr); } /* IPv6 fragments and packets with extensions don't coalesce.*/ static void send_fragment6(int fd, struct sockaddr_ll *daddr) { static char buf[MAX_HDR_LEN + PAYLOAD_LEN]; static char extpkt[MAX_HDR_LEN + PAYLOAD_LEN + sizeof(struct ip6_frag)]; struct ipv6hdr *ip6h = (struct ipv6hdr *)(buf + ETH_HLEN); struct ip6_frag *frag = (void *)(extpkt + tcp_offset); int extlen = sizeof(struct ip6_frag); int bufpkt_len = total_hdr_len + PAYLOAD_LEN; int extpkt_len = bufpkt_len + extlen; int i; for (i = 0; i < 2; i++) { create_packet(buf, PAYLOAD_LEN * i, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, bufpkt_len, daddr); } create_packet(buf, PAYLOAD_LEN * 2, 0, PAYLOAD_LEN, 0); memset(extpkt, 0, extpkt_len); ip6h->nexthdr = IPPROTO_FRAGMENT; ip6h->payload_len = htons(ntohs(ip6h->payload_len) + extlen); frag->ip6f_nxt = IPPROTO_TCP; memcpy(extpkt, buf, tcp_offset); memcpy(extpkt + tcp_offset + extlen, buf + tcp_offset, sizeof(struct tcphdr) + PAYLOAD_LEN); write_packet(fd, extpkt, extpkt_len, daddr); create_packet(buf, PAYLOAD_LEN * 3, 0, PAYLOAD_LEN, 0); write_packet(fd, buf, bufpkt_len, daddr); } static void bind_packetsocket(int fd) { struct sockaddr_ll daddr = {}; daddr.sll_family = AF_PACKET; daddr.sll_protocol = ethhdr_proto; daddr.sll_ifindex = if_nametoindex(ifname); if (daddr.sll_ifindex == 0) error(1, errno, "if_nametoindex"); if (bind(fd, (void *)&daddr, sizeof(daddr)) < 0) error(1, errno, "could not bind socket"); } static void set_timeout(int fd) { struct timeval timeout; timeout.tv_sec = 3; timeout.tv_usec = 0; if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) error(1, errno, "cannot set timeout, setsockopt failed"); } static void check_recv_pkts(int fd, int *correct_payload, int correct_num_pkts) { static char buffer[IP_MAXPACKET + ETH_HLEN + 1]; struct iphdr *iph = (struct iphdr *)(buffer + ETH_HLEN); struct ipv6hdr *ip6h = (struct ipv6hdr *)(buffer + ETH_HLEN); struct tcphdr *tcph; bool bad_packet = false; int tcp_ext_len = 0; int ip_ext_len = 0; int pkt_size = -1; int data_len = 0; int num_pkt = 0; int i; vlog("Expected {"); for (i = 0; i < correct_num_pkts; i++) vlog("%d ", correct_payload[i]); vlog("}, Total %d packets\nReceived {", correct_num_pkts); while (1) { pkt_size = recv(fd, buffer, IP_MAXPACKET + ETH_HLEN + 1, 0); if (pkt_size < 0) error(1, errno, "could not receive"); if (iph->version == 4) ip_ext_len = (iph->ihl - 5) * 4; else if (ip6h->version == 6 && ip6h->nexthdr != IPPROTO_TCP) ip_ext_len = sizeof(struct ip6_frag); tcph = (struct tcphdr *)(buffer + tcp_offset + ip_ext_len); if (tcph->fin) break; tcp_ext_len = (tcph->doff - 5) * 4; data_len = pkt_size - total_hdr_len - tcp_ext_len - ip_ext_len; /* Min ethernet frame payload is 46(ETH_ZLEN - ETH_HLEN) by RFC 802.3. * Ipv4/tcp packets without at least 6 bytes of data will be padded. * Packet sockets are protocol agnostic, and will not trim the padding. */ if (pkt_size == ETH_ZLEN && iph->version == 4) { data_len = ntohs(iph->tot_len) - sizeof(struct tcphdr) - sizeof(struct iphdr); } vlog("%d ", data_len); if (data_len != correct_payload[num_pkt]) { vlog("[!=%d]", correct_payload[num_pkt]); bad_packet = true; } num_pkt++; } vlog("}, Total %d packets.\n", num_pkt); if (num_pkt != correct_num_pkts) error(1, 0, "incorrect number of packets"); if (bad_packet) error(1, 0, "incorrect packet geometry"); printf("Test succeeded\n\n"); } static void gro_sender(void) { static char fin_pkt[MAX_HDR_LEN]; struct sockaddr_ll daddr = {}; int txfd = -1; txfd = socket(PF_PACKET, SOCK_RAW, IPPROTO_RAW); if (txfd < 0) error(1, errno, "socket creation"); memset(&daddr, 0, sizeof(daddr)); daddr.sll_ifindex = if_nametoindex(ifname); if (daddr.sll_ifindex == 0) error(1, errno, "if_nametoindex"); daddr.sll_family = AF_PACKET; memcpy(daddr.sll_addr, dst_mac, ETH_ALEN); daddr.sll_halen = ETH_ALEN; create_packet(fin_pkt, PAYLOAD_LEN * 2, 0, 0, 1); if (strcmp(testname, "data") == 0) { send_data_pkts(txfd, &daddr, PAYLOAD_LEN, PAYLOAD_LEN); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_data_pkts(txfd, &daddr, PAYLOAD_LEN, PAYLOAD_LEN / 2); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_data_pkts(txfd, &daddr, PAYLOAD_LEN / 2, PAYLOAD_LEN); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); } else if (strcmp(testname, "ack") == 0) { send_ack(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); } else if (strcmp(testname, "flags") == 0) { send_flags(txfd, &daddr, 1, 0, 0, 0); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_flags(txfd, &daddr, 0, 1, 0, 0); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_flags(txfd, &daddr, 0, 0, 1, 0); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_flags(txfd, &daddr, 0, 0, 0, 1); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); } else if (strcmp(testname, "tcp") == 0) { send_changed_checksum(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_changed_seq(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_changed_ts(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_diff_opt(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); } else if (strcmp(testname, "ip") == 0) { send_changed_ECN(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_changed_tos(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); if (proto == PF_INET) { /* Modified packets may be received out of order. * Sleep function added to enforce test boundaries * so that fin pkts are not received prior to other pkts. */ sleep(1); send_changed_ttl(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); sleep(1); send_ip_options(txfd, &daddr); sleep(1); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); sleep(1); send_fragment4(txfd, &daddr); sleep(1); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); } else if (proto == PF_INET6) { send_fragment6(txfd, &daddr); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); } } else if (strcmp(testname, "large") == 0) { /* 20 is the difference between min iphdr size * and min ipv6hdr size. Like MAX_HDR_SIZE, * MAX_PAYLOAD is defined with the larger header of the two. */ int offset = proto == PF_INET ? 20 : 0; int remainder = (MAX_PAYLOAD + offset) % MSS; send_large(txfd, &daddr, remainder); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); send_large(txfd, &daddr, remainder + 1); write_packet(txfd, fin_pkt, total_hdr_len, &daddr); } else { error(1, 0, "Unknown testcase"); } if (close(txfd)) error(1, errno, "socket close"); } static void gro_receiver(void) { static int correct_payload[NUM_PACKETS]; int rxfd = -1; rxfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_NONE)); if (rxfd < 0) error(1, 0, "socket creation"); setup_sock_filter(rxfd); set_timeout(rxfd); bind_packetsocket(rxfd); memset(correct_payload, 0, sizeof(correct_payload)); if (strcmp(testname, "data") == 0) { printf("pure data packet of same size: "); correct_payload[0] = PAYLOAD_LEN * 2; check_recv_pkts(rxfd, correct_payload, 1); printf("large data packets followed by a smaller one: "); correct_payload[0] = PAYLOAD_LEN * 1.5; check_recv_pkts(rxfd, correct_payload, 1); printf("small data packets followed by a larger one: "); correct_payload[0] = PAYLOAD_LEN / 2; correct_payload[1] = PAYLOAD_LEN; check_recv_pkts(rxfd, correct_payload, 2); } else if (strcmp(testname, "ack") == 0) { printf("duplicate ack and pure ack: "); check_recv_pkts(rxfd, correct_payload, 3); } else if (strcmp(testname, "flags") == 0) { correct_payload[0] = PAYLOAD_LEN * 3; correct_payload[1] = PAYLOAD_LEN * 2; printf("psh flag ends coalescing: "); check_recv_pkts(rxfd, correct_payload, 2); correct_payload[0] = PAYLOAD_LEN * 2; correct_payload[1] = 0; correct_payload[2] = PAYLOAD_LEN * 2; printf("syn flag ends coalescing: "); check_recv_pkts(rxfd, correct_payload, 3); printf("rst flag ends coalescing: "); check_recv_pkts(rxfd, correct_payload, 3); printf("urg flag ends coalescing: "); check_recv_pkts(rxfd, correct_payload, 3); } else if (strcmp(testname, "tcp") == 0) { correct_payload[0] = PAYLOAD_LEN; correct_payload[1] = PAYLOAD_LEN; correct_payload[2] = PAYLOAD_LEN; correct_payload[3] = PAYLOAD_LEN; printf("changed checksum does not coalesce: "); check_recv_pkts(rxfd, correct_payload, 2); printf("Wrong Seq number doesn't coalesce: "); check_recv_pkts(rxfd, correct_payload, 2); printf("Different timestamp doesn't coalesce: "); correct_payload[0] = PAYLOAD_LEN * 2; check_recv_pkts(rxfd, correct_payload, 4); printf("Different options doesn't coalesce: "); correct_payload[0] = PAYLOAD_LEN * 2; check_recv_pkts(rxfd, correct_payload, 2); } else if (strcmp(testname, "ip") == 0) { correct_payload[0] = PAYLOAD_LEN; correct_payload[1] = PAYLOAD_LEN; printf("different ECN doesn't coalesce: "); check_recv_pkts(rxfd, correct_payload, 2); printf("different tos doesn't coalesce: "); check_recv_pkts(rxfd, correct_payload, 2); if (proto == PF_INET) { printf("different ttl doesn't coalesce: "); check_recv_pkts(rxfd, correct_payload, 2); printf("ip options doesn't coalesce: "); correct_payload[2] = PAYLOAD_LEN; check_recv_pkts(rxfd, correct_payload, 3); printf("fragmented ip4 doesn't coalesce: "); check_recv_pkts(rxfd, correct_payload, 2); } else if (proto == PF_INET6) { /* GRO doesn't check for ipv6 hop limit when flushing. * Hence no corresponding test to the ipv4 case. */ printf("fragmented ip6 doesn't coalesce: "); correct_payload[0] = PAYLOAD_LEN * 2; check_recv_pkts(rxfd, correct_payload, 2); } } else if (strcmp(testname, "large") == 0) { int offset = proto == PF_INET ? 20 : 0; int remainder = (MAX_PAYLOAD + offset) % MSS; correct_payload[0] = (MAX_PAYLOAD + offset); correct_payload[1] = remainder; printf("Shouldn't coalesce if exceed IP max pkt size: "); check_recv_pkts(rxfd, correct_payload, 2); /* last segment sent individually, doesn't start new segment */ correct_payload[0] = correct_payload[0] - remainder; correct_payload[1] = remainder + 1; correct_payload[2] = remainder + 1; check_recv_pkts(rxfd, correct_payload, 3); } else { error(1, 0, "Test case error, should never trigger"); } if (close(rxfd)) error(1, 0, "socket close"); } static void parse_args(int argc, char **argv) { static const struct option opts[] = { { "daddr", required_argument, NULL, 'd' }, { "dmac", required_argument, NULL, 'D' }, { "iface", required_argument, NULL, 'i' }, { "ipv4", no_argument, NULL, '4' }, { "ipv6", no_argument, NULL, '6' }, { "rx", no_argument, NULL, 'r' }, { "saddr", required_argument, NULL, 's' }, { "smac", required_argument, NULL, 'S' }, { "test", required_argument, NULL, 't' }, { "verbose", no_argument, NULL, 'v' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "46d:D:i:rs:S:t:v", opts, NULL)) != -1) { switch (c) { case '4': proto = PF_INET; ethhdr_proto = htons(ETH_P_IP); break; case '6': proto = PF_INET6; ethhdr_proto = htons(ETH_P_IPV6); break; case 'd': addr4_dst = addr6_dst = optarg; break; case 'D': dmac = optarg; break; case 'i': ifname = optarg; break; case 'r': tx_socket = false; break; case 's': addr4_src = addr6_src = optarg; break; case 'S': smac = optarg; break; case 't': testname = optarg; break; case 'v': verbose = true; break; default: error(1, 0, "%s invalid option %c\n", __func__, c); break; } } } int main(int argc, char **argv) { parse_args(argc, argv); if (proto == PF_INET) { tcp_offset = ETH_HLEN + sizeof(struct iphdr); total_hdr_len = tcp_offset + sizeof(struct tcphdr); } else if (proto == PF_INET6) { tcp_offset = ETH_HLEN + sizeof(struct ipv6hdr); total_hdr_len = MAX_HDR_LEN; } else { error(1, 0, "Protocol family is not ipv4 or ipv6"); } read_MAC(src_mac, smac); read_MAC(dst_mac, dmac); if (tx_socket) gro_sender(); else gro_receiver(); fprintf(stderr, "Gro::%s test passed.\n", testname); return 0; }
linux-master
tools/testing/selftests/net/gro.c
/* SPDX-License-Identifier: MIT */ /* based on linux-kernel/tools/testing/selftests/net/msg_zerocopy.c */ #include <assert.h> #include <errno.h> #include <error.h> #include <fcntl.h> #include <limits.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <linux/errqueue.h> #include <linux/if_packet.h> #include <linux/io_uring.h> #include <linux/ipv6.h> #include <linux/socket.h> #include <linux/sockios.h> #include <net/ethernet.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/un.h> #include <sys/wait.h> #define NOTIF_TAG 0xfffffffULL #define NONZC_TAG 0 #define ZC_TAG 1 enum { MODE_NONZC = 0, MODE_ZC = 1, MODE_ZC_FIXED = 2, MODE_MIXED = 3, }; static bool cfg_cork = false; static int cfg_mode = MODE_ZC_FIXED; static int cfg_nr_reqs = 8; static int cfg_family = PF_UNSPEC; static int cfg_payload_len; static int cfg_port = 8000; static int cfg_runtime_ms = 4200; static socklen_t cfg_alen; static struct sockaddr_storage cfg_dst_addr; static char payload[IP_MAXPACKET] __attribute__((aligned(4096))); struct io_sq_ring { unsigned *head; unsigned *tail; unsigned *ring_mask; unsigned *ring_entries; unsigned *flags; unsigned *array; }; struct io_cq_ring { unsigned *head; unsigned *tail; unsigned *ring_mask; unsigned *ring_entries; struct io_uring_cqe *cqes; }; struct io_uring_sq { unsigned *khead; unsigned *ktail; unsigned *kring_mask; unsigned *kring_entries; unsigned *kflags; unsigned *kdropped; unsigned *array; struct io_uring_sqe *sqes; unsigned sqe_head; unsigned sqe_tail; size_t ring_sz; }; struct io_uring_cq { unsigned *khead; unsigned *ktail; unsigned *kring_mask; unsigned *kring_entries; unsigned *koverflow; struct io_uring_cqe *cqes; size_t ring_sz; }; struct io_uring { struct io_uring_sq sq; struct io_uring_cq cq; int ring_fd; }; #ifdef __alpha__ # ifndef __NR_io_uring_setup # define __NR_io_uring_setup 535 # endif # ifndef __NR_io_uring_enter # define __NR_io_uring_enter 536 # endif # ifndef __NR_io_uring_register # define __NR_io_uring_register 537 # endif #else /* !__alpha__ */ # ifndef __NR_io_uring_setup # define __NR_io_uring_setup 425 # endif # ifndef __NR_io_uring_enter # define __NR_io_uring_enter 426 # endif # ifndef __NR_io_uring_register # define __NR_io_uring_register 427 # endif #endif #if defined(__x86_64) || defined(__i386__) #define read_barrier() __asm__ __volatile__("":::"memory") #define write_barrier() __asm__ __volatile__("":::"memory") #else #define read_barrier() __sync_synchronize() #define write_barrier() __sync_synchronize() #endif static int io_uring_setup(unsigned int entries, struct io_uring_params *p) { return syscall(__NR_io_uring_setup, entries, p); } static int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete, unsigned int flags, sigset_t *sig) { return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, sig, _NSIG / 8); } static int io_uring_register_buffers(struct io_uring *ring, const struct iovec *iovecs, unsigned nr_iovecs) { int ret; ret = syscall(__NR_io_uring_register, ring->ring_fd, IORING_REGISTER_BUFFERS, iovecs, nr_iovecs); return (ret < 0) ? -errno : ret; } static int io_uring_mmap(int fd, struct io_uring_params *p, struct io_uring_sq *sq, struct io_uring_cq *cq) { size_t size; void *ptr; int ret; sq->ring_sz = p->sq_off.array + p->sq_entries * sizeof(unsigned); ptr = mmap(0, sq->ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQ_RING); if (ptr == MAP_FAILED) return -errno; sq->khead = ptr + p->sq_off.head; sq->ktail = ptr + p->sq_off.tail; sq->kring_mask = ptr + p->sq_off.ring_mask; sq->kring_entries = ptr + p->sq_off.ring_entries; sq->kflags = ptr + p->sq_off.flags; sq->kdropped = ptr + p->sq_off.dropped; sq->array = ptr + p->sq_off.array; size = p->sq_entries * sizeof(struct io_uring_sqe); sq->sqes = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQES); if (sq->sqes == MAP_FAILED) { ret = -errno; err: munmap(sq->khead, sq->ring_sz); return ret; } cq->ring_sz = p->cq_off.cqes + p->cq_entries * sizeof(struct io_uring_cqe); ptr = mmap(0, cq->ring_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_CQ_RING); if (ptr == MAP_FAILED) { ret = -errno; munmap(sq->sqes, p->sq_entries * sizeof(struct io_uring_sqe)); goto err; } cq->khead = ptr + p->cq_off.head; cq->ktail = ptr + p->cq_off.tail; cq->kring_mask = ptr + p->cq_off.ring_mask; cq->kring_entries = ptr + p->cq_off.ring_entries; cq->koverflow = ptr + p->cq_off.overflow; cq->cqes = ptr + p->cq_off.cqes; return 0; } static int io_uring_queue_init(unsigned entries, struct io_uring *ring, unsigned flags) { struct io_uring_params p; int fd, ret; memset(ring, 0, sizeof(*ring)); memset(&p, 0, sizeof(p)); p.flags = flags; fd = io_uring_setup(entries, &p); if (fd < 0) return fd; ret = io_uring_mmap(fd, &p, &ring->sq, &ring->cq); if (!ret) ring->ring_fd = fd; else close(fd); return ret; } static int io_uring_submit(struct io_uring *ring) { struct io_uring_sq *sq = &ring->sq; const unsigned mask = *sq->kring_mask; unsigned ktail, submitted, to_submit; int ret; read_barrier(); if (*sq->khead != *sq->ktail) { submitted = *sq->kring_entries; goto submit; } if (sq->sqe_head == sq->sqe_tail) return 0; ktail = *sq->ktail; to_submit = sq->sqe_tail - sq->sqe_head; for (submitted = 0; submitted < to_submit; submitted++) { read_barrier(); sq->array[ktail++ & mask] = sq->sqe_head++ & mask; } if (!submitted) return 0; if (*sq->ktail != ktail) { write_barrier(); *sq->ktail = ktail; write_barrier(); } submit: ret = io_uring_enter(ring->ring_fd, submitted, 0, IORING_ENTER_GETEVENTS, NULL); return ret < 0 ? -errno : ret; } static inline void io_uring_prep_send(struct io_uring_sqe *sqe, int sockfd, const void *buf, size_t len, int flags) { memset(sqe, 0, sizeof(*sqe)); sqe->opcode = (__u8) IORING_OP_SEND; sqe->fd = sockfd; sqe->addr = (unsigned long) buf; sqe->len = len; sqe->msg_flags = (__u32) flags; } static inline void io_uring_prep_sendzc(struct io_uring_sqe *sqe, int sockfd, const void *buf, size_t len, int flags, unsigned zc_flags) { io_uring_prep_send(sqe, sockfd, buf, len, flags); sqe->opcode = (__u8) IORING_OP_SEND_ZC; sqe->ioprio = zc_flags; } static struct io_uring_sqe *io_uring_get_sqe(struct io_uring *ring) { struct io_uring_sq *sq = &ring->sq; if (sq->sqe_tail + 1 - sq->sqe_head > *sq->kring_entries) return NULL; return &sq->sqes[sq->sqe_tail++ & *sq->kring_mask]; } static int io_uring_wait_cqe(struct io_uring *ring, struct io_uring_cqe **cqe_ptr) { struct io_uring_cq *cq = &ring->cq; const unsigned mask = *cq->kring_mask; unsigned head = *cq->khead; int ret; *cqe_ptr = NULL; do { read_barrier(); if (head != *cq->ktail) { *cqe_ptr = &cq->cqes[head & mask]; break; } ret = io_uring_enter(ring->ring_fd, 0, 1, IORING_ENTER_GETEVENTS, NULL); if (ret < 0) return -errno; } while (1); return 0; } static inline void io_uring_cqe_seen(struct io_uring *ring) { *(&ring->cq)->khead += 1; write_barrier(); } static unsigned long gettimeofday_ms(void) { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); } static void do_setsockopt(int fd, int level, int optname, int val) { if (setsockopt(fd, level, optname, &val, sizeof(val))) error(1, errno, "setsockopt %d.%d: %d", level, optname, val); } static int do_setup_tx(int domain, int type, int protocol) { int fd; fd = socket(domain, type, protocol); if (fd == -1) error(1, errno, "socket t"); do_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, 1 << 21); if (connect(fd, (void *) &cfg_dst_addr, cfg_alen)) error(1, errno, "connect"); return fd; } static void do_tx(int domain, int type, int protocol) { struct io_uring_sqe *sqe; struct io_uring_cqe *cqe; unsigned long packets = 0, bytes = 0; struct io_uring ring; struct iovec iov; uint64_t tstop; int i, fd, ret; int compl_cqes = 0; fd = do_setup_tx(domain, type, protocol); ret = io_uring_queue_init(512, &ring, 0); if (ret) error(1, ret, "io_uring: queue init"); iov.iov_base = payload; iov.iov_len = cfg_payload_len; ret = io_uring_register_buffers(&ring, &iov, 1); if (ret) error(1, ret, "io_uring: buffer registration"); tstop = gettimeofday_ms() + cfg_runtime_ms; do { if (cfg_cork) do_setsockopt(fd, IPPROTO_UDP, UDP_CORK, 1); for (i = 0; i < cfg_nr_reqs; i++) { unsigned zc_flags = 0; unsigned buf_idx = 0; unsigned mode = cfg_mode; unsigned msg_flags = MSG_WAITALL; if (cfg_mode == MODE_MIXED) mode = rand() % 3; sqe = io_uring_get_sqe(&ring); if (mode == MODE_NONZC) { io_uring_prep_send(sqe, fd, payload, cfg_payload_len, msg_flags); sqe->user_data = NONZC_TAG; } else { io_uring_prep_sendzc(sqe, fd, payload, cfg_payload_len, msg_flags, zc_flags); if (mode == MODE_ZC_FIXED) { sqe->ioprio |= IORING_RECVSEND_FIXED_BUF; sqe->buf_index = buf_idx; } sqe->user_data = ZC_TAG; } } ret = io_uring_submit(&ring); if (ret != cfg_nr_reqs) error(1, ret, "submit"); if (cfg_cork) do_setsockopt(fd, IPPROTO_UDP, UDP_CORK, 0); for (i = 0; i < cfg_nr_reqs; i++) { ret = io_uring_wait_cqe(&ring, &cqe); if (ret) error(1, ret, "wait cqe"); if (cqe->user_data != NONZC_TAG && cqe->user_data != ZC_TAG) error(1, -EINVAL, "invalid cqe->user_data"); if (cqe->flags & IORING_CQE_F_NOTIF) { if (cqe->flags & IORING_CQE_F_MORE) error(1, -EINVAL, "invalid notif flags"); if (compl_cqes <= 0) error(1, -EINVAL, "notification mismatch"); compl_cqes--; i--; io_uring_cqe_seen(&ring); continue; } if (cqe->flags & IORING_CQE_F_MORE) { if (cqe->user_data != ZC_TAG) error(1, cqe->res, "unexpected F_MORE"); compl_cqes++; } if (cqe->res >= 0) { packets++; bytes += cqe->res; } else if (cqe->res != -EAGAIN) { error(1, cqe->res, "send failed"); } io_uring_cqe_seen(&ring); } } while (gettimeofday_ms() < tstop); while (compl_cqes) { ret = io_uring_wait_cqe(&ring, &cqe); if (ret) error(1, ret, "wait cqe"); if (cqe->flags & IORING_CQE_F_MORE) error(1, -EINVAL, "invalid notif flags"); if (!(cqe->flags & IORING_CQE_F_NOTIF)) error(1, -EINVAL, "missing notif flag"); io_uring_cqe_seen(&ring); compl_cqes--; } fprintf(stderr, "tx=%lu (MB=%lu), tx/s=%lu (MB/s=%lu)\n", packets, bytes >> 20, packets / (cfg_runtime_ms / 1000), (bytes >> 20) / (cfg_runtime_ms / 1000)); if (close(fd)) error(1, errno, "close"); } static void do_test(int domain, int type, int protocol) { int i; for (i = 0; i < IP_MAXPACKET; i++) payload[i] = 'a' + (i % 26); do_tx(domain, type, protocol); } static void usage(const char *filepath) { error(1, 0, "Usage: %s (-4|-6) (udp|tcp) -D<dst_ip> [-s<payload size>] " "[-t<time s>] [-n<batch>] [-p<port>] [-m<mode>]", filepath); } static void parse_opts(int argc, char **argv) { const int max_payload_len = sizeof(payload) - sizeof(struct ipv6hdr) - sizeof(struct tcphdr) - 40 /* max tcp options */; struct sockaddr_in6 *addr6 = (void *) &cfg_dst_addr; struct sockaddr_in *addr4 = (void *) &cfg_dst_addr; char *daddr = NULL; int c; if (argc <= 1) usage(argv[0]); cfg_payload_len = max_payload_len; while ((c = getopt(argc, argv, "46D:p:s:t:n:c:m:")) != -1) { switch (c) { case '4': if (cfg_family != PF_UNSPEC) error(1, 0, "Pass one of -4 or -6"); cfg_family = PF_INET; cfg_alen = sizeof(struct sockaddr_in); break; case '6': if (cfg_family != PF_UNSPEC) error(1, 0, "Pass one of -4 or -6"); cfg_family = PF_INET6; cfg_alen = sizeof(struct sockaddr_in6); break; case 'D': daddr = optarg; break; case 'p': cfg_port = strtoul(optarg, NULL, 0); break; case 's': cfg_payload_len = strtoul(optarg, NULL, 0); break; case 't': cfg_runtime_ms = 200 + strtoul(optarg, NULL, 10) * 1000; break; case 'n': cfg_nr_reqs = strtoul(optarg, NULL, 0); break; case 'c': cfg_cork = strtol(optarg, NULL, 0); break; case 'm': cfg_mode = strtol(optarg, NULL, 0); break; } } switch (cfg_family) { case PF_INET: memset(addr4, 0, sizeof(*addr4)); addr4->sin_family = AF_INET; addr4->sin_port = htons(cfg_port); if (daddr && inet_pton(AF_INET, daddr, &(addr4->sin_addr)) != 1) error(1, 0, "ipv4 parse error: %s", daddr); break; case PF_INET6: memset(addr6, 0, sizeof(*addr6)); addr6->sin6_family = AF_INET6; addr6->sin6_port = htons(cfg_port); if (daddr && inet_pton(AF_INET6, daddr, &(addr6->sin6_addr)) != 1) error(1, 0, "ipv6 parse error: %s", daddr); break; default: error(1, 0, "illegal domain"); } if (cfg_payload_len > max_payload_len) error(1, 0, "-s: payload exceeds max (%d)", max_payload_len); if (optind != argc - 1) usage(argv[0]); } int main(int argc, char **argv) { const char *cfg_test = argv[argc - 1]; parse_opts(argc, argv); if (!strcmp(cfg_test, "tcp")) do_test(cfg_family, SOCK_STREAM, 0); else if (!strcmp(cfg_test, "udp")) do_test(cfg_family, SOCK_DGRAM, 0); else error(1, 0, "unknown cfg_test %s", cfg_test); return 0; }
linux-master
tools/testing/selftests/net/io_uring_zerocopy_tx.c
// SPDX-License-Identifier: GPL-2.0+ /* * Author: Justin Iurman ([email protected]) * * IOAM tester for IPv6, see ioam6.sh for details on each test case. */ #include <arpa/inet.h> #include <errno.h> #include <limits.h> #include <linux/const.h> #include <linux/if_ether.h> #include <linux/ioam6.h> #include <linux/ipv6.h> #include <stdlib.h> #include <string.h> #include <unistd.h> struct ioam_config { __u32 id; __u64 wide; __u16 ingr_id; __u16 egr_id; __u32 ingr_wide; __u32 egr_wide; __u32 ns_data; __u64 ns_wide; __u32 sc_id; __u8 hlim; char *sc_data; }; /* * Be careful if you modify structs below - everything MUST be kept synchronized * with configurations inside ioam6.sh and always reflect the same. */ static struct ioam_config node1 = { .id = 1, .wide = 11111111, .ingr_id = 0xffff, /* default value */ .egr_id = 101, .ingr_wide = 0xffffffff, /* default value */ .egr_wide = 101101, .ns_data = 0xdeadbee0, .ns_wide = 0xcafec0caf00dc0de, .sc_id = 777, .sc_data = "something that will be 4n-aligned", .hlim = 64, }; static struct ioam_config node2 = { .id = 2, .wide = 22222222, .ingr_id = 201, .egr_id = 202, .ingr_wide = 201201, .egr_wide = 202202, .ns_data = 0xdeadbee1, .ns_wide = 0xcafec0caf11dc0de, .sc_id = 666, .sc_data = "Hello there -Obi", .hlim = 63, }; static struct ioam_config node3 = { .id = 3, .wide = 33333333, .ingr_id = 301, .egr_id = 0xffff, /* default value */ .ingr_wide = 301301, .egr_wide = 0xffffffff, /* default value */ .ns_data = 0xdeadbee2, .ns_wide = 0xcafec0caf22dc0de, .sc_id = 0xffffff, /* default value */ .sc_data = NULL, .hlim = 62, }; enum { /********** * OUTPUT * **********/ TEST_OUT_UNDEF_NS, TEST_OUT_NO_ROOM, TEST_OUT_BIT0, TEST_OUT_BIT1, TEST_OUT_BIT2, TEST_OUT_BIT3, TEST_OUT_BIT4, TEST_OUT_BIT5, TEST_OUT_BIT6, TEST_OUT_BIT7, TEST_OUT_BIT8, TEST_OUT_BIT9, TEST_OUT_BIT10, TEST_OUT_BIT11, TEST_OUT_BIT22, TEST_OUT_FULL_SUPP_TRACE, /********* * INPUT * *********/ TEST_IN_UNDEF_NS, TEST_IN_NO_ROOM, TEST_IN_OFLAG, TEST_IN_BIT0, TEST_IN_BIT1, TEST_IN_BIT2, TEST_IN_BIT3, TEST_IN_BIT4, TEST_IN_BIT5, TEST_IN_BIT6, TEST_IN_BIT7, TEST_IN_BIT8, TEST_IN_BIT9, TEST_IN_BIT10, TEST_IN_BIT11, TEST_IN_BIT22, TEST_IN_FULL_SUPP_TRACE, /********** * GLOBAL * **********/ TEST_FWD_FULL_SUPP_TRACE, __TEST_MAX, }; static int check_ioam_header(int tid, struct ioam6_trace_hdr *ioam6h, __u32 trace_type, __u16 ioam_ns) { if (__be16_to_cpu(ioam6h->namespace_id) != ioam_ns || __be32_to_cpu(ioam6h->type_be32) != (trace_type << 8)) return 1; switch (tid) { case TEST_OUT_UNDEF_NS: case TEST_IN_UNDEF_NS: return ioam6h->overflow || ioam6h->nodelen != 1 || ioam6h->remlen != 1; case TEST_OUT_NO_ROOM: case TEST_IN_NO_ROOM: case TEST_IN_OFLAG: return !ioam6h->overflow || ioam6h->nodelen != 2 || ioam6h->remlen != 1; case TEST_OUT_BIT0: case TEST_IN_BIT0: case TEST_OUT_BIT1: case TEST_IN_BIT1: case TEST_OUT_BIT2: case TEST_IN_BIT2: case TEST_OUT_BIT3: case TEST_IN_BIT3: case TEST_OUT_BIT4: case TEST_IN_BIT4: case TEST_OUT_BIT5: case TEST_IN_BIT5: case TEST_OUT_BIT6: case TEST_IN_BIT6: case TEST_OUT_BIT7: case TEST_IN_BIT7: case TEST_OUT_BIT11: case TEST_IN_BIT11: return ioam6h->overflow || ioam6h->nodelen != 1 || ioam6h->remlen; case TEST_OUT_BIT8: case TEST_IN_BIT8: case TEST_OUT_BIT9: case TEST_IN_BIT9: case TEST_OUT_BIT10: case TEST_IN_BIT10: return ioam6h->overflow || ioam6h->nodelen != 2 || ioam6h->remlen; case TEST_OUT_BIT22: case TEST_IN_BIT22: return ioam6h->overflow || ioam6h->nodelen || ioam6h->remlen; case TEST_OUT_FULL_SUPP_TRACE: case TEST_IN_FULL_SUPP_TRACE: case TEST_FWD_FULL_SUPP_TRACE: return ioam6h->overflow || ioam6h->nodelen != 15 || ioam6h->remlen; default: break; } return 1; } static int check_ioam6_data(__u8 **p, struct ioam6_trace_hdr *ioam6h, const struct ioam_config cnf) { unsigned int len; __u8 aligned; __u64 raw64; __u32 raw32; if (ioam6h->type.bit0) { raw32 = __be32_to_cpu(*((__u32 *)*p)); if (cnf.hlim != (raw32 >> 24) || cnf.id != (raw32 & 0xffffff)) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit1) { raw32 = __be32_to_cpu(*((__u32 *)*p)); if (cnf.ingr_id != (raw32 >> 16) || cnf.egr_id != (raw32 & 0xffff)) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit2) *p += sizeof(__u32); if (ioam6h->type.bit3) *p += sizeof(__u32); if (ioam6h->type.bit4) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit5) { if (__be32_to_cpu(*((__u32 *)*p)) != cnf.ns_data) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit6) *p += sizeof(__u32); if (ioam6h->type.bit7) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit8) { raw64 = __be64_to_cpu(*((__u64 *)*p)); if (cnf.hlim != (raw64 >> 56) || cnf.wide != (raw64 & 0xffffffffffffff)) return 1; *p += sizeof(__u64); } if (ioam6h->type.bit9) { if (__be32_to_cpu(*((__u32 *)*p)) != cnf.ingr_wide) return 1; *p += sizeof(__u32); if (__be32_to_cpu(*((__u32 *)*p)) != cnf.egr_wide) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit10) { if (__be64_to_cpu(*((__u64 *)*p)) != cnf.ns_wide) return 1; *p += sizeof(__u64); } if (ioam6h->type.bit11) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit12) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit13) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit14) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit15) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit16) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit17) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit18) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit19) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit20) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit21) { if (__be32_to_cpu(*((__u32 *)*p)) != 0xffffffff) return 1; *p += sizeof(__u32); } if (ioam6h->type.bit22) { len = cnf.sc_data ? strlen(cnf.sc_data) : 0; aligned = cnf.sc_data ? __ALIGN_KERNEL(len, 4) : 0; raw32 = __be32_to_cpu(*((__u32 *)*p)); if (aligned != (raw32 >> 24) * 4 || cnf.sc_id != (raw32 & 0xffffff)) return 1; *p += sizeof(__u32); if (cnf.sc_data) { if (strncmp((char *)*p, cnf.sc_data, len)) return 1; *p += len; aligned -= len; while (aligned--) { if (**p != '\0') return 1; *p += sizeof(__u8); } } } return 0; } static int check_ioam_header_and_data(int tid, struct ioam6_trace_hdr *ioam6h, __u32 trace_type, __u16 ioam_ns) { __u8 *p; if (check_ioam_header(tid, ioam6h, trace_type, ioam_ns)) return 1; p = ioam6h->data + ioam6h->remlen * 4; switch (tid) { case TEST_OUT_BIT0: case TEST_OUT_BIT1: case TEST_OUT_BIT2: case TEST_OUT_BIT3: case TEST_OUT_BIT4: case TEST_OUT_BIT5: case TEST_OUT_BIT6: case TEST_OUT_BIT7: case TEST_OUT_BIT8: case TEST_OUT_BIT9: case TEST_OUT_BIT10: case TEST_OUT_BIT11: case TEST_OUT_BIT22: case TEST_OUT_FULL_SUPP_TRACE: return check_ioam6_data(&p, ioam6h, node1); case TEST_IN_BIT0: case TEST_IN_BIT1: case TEST_IN_BIT2: case TEST_IN_BIT3: case TEST_IN_BIT4: case TEST_IN_BIT5: case TEST_IN_BIT6: case TEST_IN_BIT7: case TEST_IN_BIT8: case TEST_IN_BIT9: case TEST_IN_BIT10: case TEST_IN_BIT11: case TEST_IN_BIT22: case TEST_IN_FULL_SUPP_TRACE: { __u32 tmp32 = node2.egr_wide; __u16 tmp16 = node2.egr_id; int res; node2.egr_id = 0xffff; node2.egr_wide = 0xffffffff; res = check_ioam6_data(&p, ioam6h, node2); node2.egr_id = tmp16; node2.egr_wide = tmp32; return res; } case TEST_FWD_FULL_SUPP_TRACE: if (check_ioam6_data(&p, ioam6h, node3)) return 1; if (check_ioam6_data(&p, ioam6h, node2)) return 1; return check_ioam6_data(&p, ioam6h, node1); default: break; } return 1; } static int str2id(const char *tname) { if (!strcmp("out_undef_ns", tname)) return TEST_OUT_UNDEF_NS; if (!strcmp("out_no_room", tname)) return TEST_OUT_NO_ROOM; if (!strcmp("out_bit0", tname)) return TEST_OUT_BIT0; if (!strcmp("out_bit1", tname)) return TEST_OUT_BIT1; if (!strcmp("out_bit2", tname)) return TEST_OUT_BIT2; if (!strcmp("out_bit3", tname)) return TEST_OUT_BIT3; if (!strcmp("out_bit4", tname)) return TEST_OUT_BIT4; if (!strcmp("out_bit5", tname)) return TEST_OUT_BIT5; if (!strcmp("out_bit6", tname)) return TEST_OUT_BIT6; if (!strcmp("out_bit7", tname)) return TEST_OUT_BIT7; if (!strcmp("out_bit8", tname)) return TEST_OUT_BIT8; if (!strcmp("out_bit9", tname)) return TEST_OUT_BIT9; if (!strcmp("out_bit10", tname)) return TEST_OUT_BIT10; if (!strcmp("out_bit11", tname)) return TEST_OUT_BIT11; if (!strcmp("out_bit22", tname)) return TEST_OUT_BIT22; if (!strcmp("out_full_supp_trace", tname)) return TEST_OUT_FULL_SUPP_TRACE; if (!strcmp("in_undef_ns", tname)) return TEST_IN_UNDEF_NS; if (!strcmp("in_no_room", tname)) return TEST_IN_NO_ROOM; if (!strcmp("in_oflag", tname)) return TEST_IN_OFLAG; if (!strcmp("in_bit0", tname)) return TEST_IN_BIT0; if (!strcmp("in_bit1", tname)) return TEST_IN_BIT1; if (!strcmp("in_bit2", tname)) return TEST_IN_BIT2; if (!strcmp("in_bit3", tname)) return TEST_IN_BIT3; if (!strcmp("in_bit4", tname)) return TEST_IN_BIT4; if (!strcmp("in_bit5", tname)) return TEST_IN_BIT5; if (!strcmp("in_bit6", tname)) return TEST_IN_BIT6; if (!strcmp("in_bit7", tname)) return TEST_IN_BIT7; if (!strcmp("in_bit8", tname)) return TEST_IN_BIT8; if (!strcmp("in_bit9", tname)) return TEST_IN_BIT9; if (!strcmp("in_bit10", tname)) return TEST_IN_BIT10; if (!strcmp("in_bit11", tname)) return TEST_IN_BIT11; if (!strcmp("in_bit22", tname)) return TEST_IN_BIT22; if (!strcmp("in_full_supp_trace", tname)) return TEST_IN_FULL_SUPP_TRACE; if (!strcmp("fwd_full_supp_trace", tname)) return TEST_FWD_FULL_SUPP_TRACE; return -1; } static int ipv6_addr_equal(const struct in6_addr *a1, const struct in6_addr *a2) { return ((a1->s6_addr32[0] ^ a2->s6_addr32[0]) | (a1->s6_addr32[1] ^ a2->s6_addr32[1]) | (a1->s6_addr32[2] ^ a2->s6_addr32[2]) | (a1->s6_addr32[3] ^ a2->s6_addr32[3])) == 0; } static int get_u32(__u32 *val, const char *arg, int base) { unsigned long res; char *ptr; if (!arg || !*arg) return -1; res = strtoul(arg, &ptr, base); if (!ptr || ptr == arg || *ptr) return -1; if (res == ULONG_MAX && errno == ERANGE) return -1; if (res > 0xFFFFFFFFUL) return -1; *val = res; return 0; } static int get_u16(__u16 *val, const char *arg, int base) { unsigned long res; char *ptr; if (!arg || !*arg) return -1; res = strtoul(arg, &ptr, base); if (!ptr || ptr == arg || *ptr) return -1; if (res == ULONG_MAX && errno == ERANGE) return -1; if (res > 0xFFFFUL) return -1; *val = res; return 0; } static int (*func[__TEST_MAX])(int, struct ioam6_trace_hdr *, __u32, __u16) = { [TEST_OUT_UNDEF_NS] = check_ioam_header, [TEST_OUT_NO_ROOM] = check_ioam_header, [TEST_OUT_BIT0] = check_ioam_header_and_data, [TEST_OUT_BIT1] = check_ioam_header_and_data, [TEST_OUT_BIT2] = check_ioam_header_and_data, [TEST_OUT_BIT3] = check_ioam_header_and_data, [TEST_OUT_BIT4] = check_ioam_header_and_data, [TEST_OUT_BIT5] = check_ioam_header_and_data, [TEST_OUT_BIT6] = check_ioam_header_and_data, [TEST_OUT_BIT7] = check_ioam_header_and_data, [TEST_OUT_BIT8] = check_ioam_header_and_data, [TEST_OUT_BIT9] = check_ioam_header_and_data, [TEST_OUT_BIT10] = check_ioam_header_and_data, [TEST_OUT_BIT11] = check_ioam_header_and_data, [TEST_OUT_BIT22] = check_ioam_header_and_data, [TEST_OUT_FULL_SUPP_TRACE] = check_ioam_header_and_data, [TEST_IN_UNDEF_NS] = check_ioam_header, [TEST_IN_NO_ROOM] = check_ioam_header, [TEST_IN_OFLAG] = check_ioam_header, [TEST_IN_BIT0] = check_ioam_header_and_data, [TEST_IN_BIT1] = check_ioam_header_and_data, [TEST_IN_BIT2] = check_ioam_header_and_data, [TEST_IN_BIT3] = check_ioam_header_and_data, [TEST_IN_BIT4] = check_ioam_header_and_data, [TEST_IN_BIT5] = check_ioam_header_and_data, [TEST_IN_BIT6] = check_ioam_header_and_data, [TEST_IN_BIT7] = check_ioam_header_and_data, [TEST_IN_BIT8] = check_ioam_header_and_data, [TEST_IN_BIT9] = check_ioam_header_and_data, [TEST_IN_BIT10] = check_ioam_header_and_data, [TEST_IN_BIT11] = check_ioam_header_and_data, [TEST_IN_BIT22] = check_ioam_header_and_data, [TEST_IN_FULL_SUPP_TRACE] = check_ioam_header_and_data, [TEST_FWD_FULL_SUPP_TRACE] = check_ioam_header_and_data, }; int main(int argc, char **argv) { int fd, size, hoplen, tid, ret = 1; struct in6_addr src, dst; struct ioam6_hdr *opt; struct ipv6hdr *ip6h; __u8 buffer[400], *p; __u16 ioam_ns; __u32 tr_type; if (argc != 7) goto out; tid = str2id(argv[2]); if (tid < 0 || !func[tid]) goto out; if (inet_pton(AF_INET6, argv[3], &src) != 1 || inet_pton(AF_INET6, argv[4], &dst) != 1) goto out; if (get_u32(&tr_type, argv[5], 16) || get_u16(&ioam_ns, argv[6], 0)) goto out; fd = socket(AF_PACKET, SOCK_DGRAM, __cpu_to_be16(ETH_P_IPV6)); if (!fd) goto out; if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, argv[1], strlen(argv[1]))) goto close; recv: size = recv(fd, buffer, sizeof(buffer), 0); if (size <= 0) goto close; ip6h = (struct ipv6hdr *)buffer; if (!ipv6_addr_equal(&ip6h->saddr, &src) || !ipv6_addr_equal(&ip6h->daddr, &dst)) goto recv; if (ip6h->nexthdr != IPPROTO_HOPOPTS) goto close; p = buffer + sizeof(*ip6h); hoplen = (p[1] + 1) << 3; p += sizeof(struct ipv6_hopopt_hdr); while (hoplen > 0) { opt = (struct ioam6_hdr *)p; if (opt->opt_type == IPV6_TLV_IOAM && opt->type == IOAM6_TYPE_PREALLOC) { p += sizeof(*opt); ret = func[tid](tid, (struct ioam6_trace_hdr *)p, tr_type, ioam_ns); break; } p += opt->opt_len + 2; hoplen -= opt->opt_len + 2; } close: close(fd); out: return ret; }
linux-master
tools/testing/selftests/net/ioam6_parser.c
// SPDX-License-Identifier: GPL-2.0 /* * ipsec.c - Check xfrm on veth inside a net-ns. * Copyright (c) 2018 Dmitry Safonov */ #define _GNU_SOURCE #include <arpa/inet.h> #include <asm/types.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/limits.h> #include <linux/netlink.h> #include <linux/random.h> #include <linux/rtnetlink.h> #include <linux/veth.h> #include <linux/xfrm.h> #include <netinet/in.h> #include <net/if.h> #include <sched.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "../kselftest.h" #define printk(fmt, ...) \ ksft_print_msg("%d[%u] " fmt "\n", getpid(), __LINE__, ##__VA_ARGS__) #define pr_err(fmt, ...) printk(fmt ": %m", ##__VA_ARGS__) #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)])) #define IPV4_STR_SZ 16 /* xxx.xxx.xxx.xxx is longest + \0 */ #define MAX_PAYLOAD 2048 #define XFRM_ALGO_KEY_BUF_SIZE 512 #define MAX_PROCESSES (1 << 14) /* /16 mask divided by /30 subnets */ #define INADDR_A ((in_addr_t) 0x0a000000) /* 10.0.0.0 */ #define INADDR_B ((in_addr_t) 0xc0a80000) /* 192.168.0.0 */ /* /30 mask for one veth connection */ #define PREFIX_LEN 30 #define child_ip(nr) (4*nr + 1) #define grchild_ip(nr) (4*nr + 2) #define VETH_FMT "ktst-%d" #define VETH_LEN 12 #define XFRM_ALGO_NR_KEYS 29 static int nsfd_parent = -1; static int nsfd_childa = -1; static int nsfd_childb = -1; static long page_size; /* * ksft_cnt is static in kselftest, so isn't shared with children. * We have to send a test result back to parent and count there. * results_fd is a pipe with test feedback from children. */ static int results_fd[2]; const unsigned int ping_delay_nsec = 50 * 1000 * 1000; const unsigned int ping_timeout = 300; const unsigned int ping_count = 100; const unsigned int ping_success = 80; struct xfrm_key_entry { char algo_name[35]; int key_len; }; struct xfrm_key_entry xfrm_key_entries[] = { {"digest_null", 0}, {"ecb(cipher_null)", 0}, {"cbc(des)", 64}, {"hmac(md5)", 128}, {"cmac(aes)", 128}, {"xcbc(aes)", 128}, {"cbc(cast5)", 128}, {"cbc(serpent)", 128}, {"hmac(sha1)", 160}, {"hmac(rmd160)", 160}, {"cbc(des3_ede)", 192}, {"hmac(sha256)", 256}, {"cbc(aes)", 256}, {"cbc(camellia)", 256}, {"cbc(twofish)", 256}, {"rfc3686(ctr(aes))", 288}, {"hmac(sha384)", 384}, {"cbc(blowfish)", 448}, {"hmac(sha512)", 512}, {"rfc4106(gcm(aes))-128", 160}, {"rfc4543(gcm(aes))-128", 160}, {"rfc4309(ccm(aes))-128", 152}, {"rfc4106(gcm(aes))-192", 224}, {"rfc4543(gcm(aes))-192", 224}, {"rfc4309(ccm(aes))-192", 216}, {"rfc4106(gcm(aes))-256", 288}, {"rfc4543(gcm(aes))-256", 288}, {"rfc4309(ccm(aes))-256", 280}, {"rfc7539(chacha20,poly1305)-128", 0} }; static void randomize_buffer(void *buf, size_t buflen) { int *p = (int *)buf; size_t words = buflen / sizeof(int); size_t leftover = buflen % sizeof(int); if (!buflen) return; while (words--) *p++ = rand(); if (leftover) { int tmp = rand(); memcpy(buf + buflen - leftover, &tmp, leftover); } return; } static int unshare_open(void) { const char *netns_path = "/proc/self/ns/net"; int fd; if (unshare(CLONE_NEWNET) != 0) { pr_err("unshare()"); return -1; } fd = open(netns_path, O_RDONLY); if (fd <= 0) { pr_err("open(%s)", netns_path); return -1; } return fd; } static int switch_ns(int fd) { if (setns(fd, CLONE_NEWNET)) { pr_err("setns()"); return -1; } return 0; } /* * Running the test inside a new parent net namespace to bother less * about cleanup on error-path. */ static int init_namespaces(void) { nsfd_parent = unshare_open(); if (nsfd_parent <= 0) return -1; nsfd_childa = unshare_open(); if (nsfd_childa <= 0) return -1; if (switch_ns(nsfd_parent)) return -1; nsfd_childb = unshare_open(); if (nsfd_childb <= 0) return -1; if (switch_ns(nsfd_parent)) return -1; return 0; } static int netlink_sock(int *sock, uint32_t *seq_nr, int proto) { if (*sock > 0) { seq_nr++; return 0; } *sock = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, proto); if (*sock <= 0) { pr_err("socket(AF_NETLINK)"); return -1; } randomize_buffer(seq_nr, sizeof(*seq_nr)); return 0; } static inline struct rtattr *rtattr_hdr(struct nlmsghdr *nh) { return (struct rtattr *)((char *)(nh) + RTA_ALIGN((nh)->nlmsg_len)); } static int rtattr_pack(struct nlmsghdr *nh, size_t req_sz, unsigned short rta_type, const void *payload, size_t size) { /* NLMSG_ALIGNTO == RTA_ALIGNTO, nlmsg_len already aligned */ struct rtattr *attr = rtattr_hdr(nh); size_t nl_size = RTA_ALIGN(nh->nlmsg_len) + RTA_LENGTH(size); if (req_sz < nl_size) { printk("req buf is too small: %zu < %zu", req_sz, nl_size); return -1; } nh->nlmsg_len = nl_size; attr->rta_len = RTA_LENGTH(size); attr->rta_type = rta_type; memcpy(RTA_DATA(attr), payload, size); return 0; } static struct rtattr *_rtattr_begin(struct nlmsghdr *nh, size_t req_sz, unsigned short rta_type, const void *payload, size_t size) { struct rtattr *ret = rtattr_hdr(nh); if (rtattr_pack(nh, req_sz, rta_type, payload, size)) return 0; return ret; } static inline struct rtattr *rtattr_begin(struct nlmsghdr *nh, size_t req_sz, unsigned short rta_type) { return _rtattr_begin(nh, req_sz, rta_type, 0, 0); } static inline void rtattr_end(struct nlmsghdr *nh, struct rtattr *attr) { char *nlmsg_end = (char *)nh + nh->nlmsg_len; attr->rta_len = nlmsg_end - (char *)attr; } static int veth_pack_peerb(struct nlmsghdr *nh, size_t req_sz, const char *peer, int ns) { struct ifinfomsg pi; struct rtattr *peer_attr; memset(&pi, 0, sizeof(pi)); pi.ifi_family = AF_UNSPEC; pi.ifi_change = 0xFFFFFFFF; peer_attr = _rtattr_begin(nh, req_sz, VETH_INFO_PEER, &pi, sizeof(pi)); if (!peer_attr) return -1; if (rtattr_pack(nh, req_sz, IFLA_IFNAME, peer, strlen(peer))) return -1; if (rtattr_pack(nh, req_sz, IFLA_NET_NS_FD, &ns, sizeof(ns))) return -1; rtattr_end(nh, peer_attr); return 0; } static int netlink_check_answer(int sock) { struct nlmsgerror { struct nlmsghdr hdr; int error; struct nlmsghdr orig_msg; } answer; if (recv(sock, &answer, sizeof(answer), 0) < 0) { pr_err("recv()"); return -1; } else if (answer.hdr.nlmsg_type != NLMSG_ERROR) { printk("expected NLMSG_ERROR, got %d", (int)answer.hdr.nlmsg_type); return -1; } else if (answer.error) { printk("NLMSG_ERROR: %d: %s", answer.error, strerror(-answer.error)); return answer.error; } return 0; } static int veth_add(int sock, uint32_t seq, const char *peera, int ns_a, const char *peerb, int ns_b) { uint16_t flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_EXCL | NLM_F_CREATE; struct { struct nlmsghdr nh; struct ifinfomsg info; char attrbuf[MAX_PAYLOAD]; } req; const char veth_type[] = "veth"; struct rtattr *link_info, *info_data; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.info)); req.nh.nlmsg_type = RTM_NEWLINK; req.nh.nlmsg_flags = flags; req.nh.nlmsg_seq = seq; req.info.ifi_family = AF_UNSPEC; req.info.ifi_change = 0xFFFFFFFF; if (rtattr_pack(&req.nh, sizeof(req), IFLA_IFNAME, peera, strlen(peera))) return -1; if (rtattr_pack(&req.nh, sizeof(req), IFLA_NET_NS_FD, &ns_a, sizeof(ns_a))) return -1; link_info = rtattr_begin(&req.nh, sizeof(req), IFLA_LINKINFO); if (!link_info) return -1; if (rtattr_pack(&req.nh, sizeof(req), IFLA_INFO_KIND, veth_type, sizeof(veth_type))) return -1; info_data = rtattr_begin(&req.nh, sizeof(req), IFLA_INFO_DATA); if (!info_data) return -1; if (veth_pack_peerb(&req.nh, sizeof(req), peerb, ns_b)) return -1; rtattr_end(&req.nh, info_data); rtattr_end(&req.nh, link_info); if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } return netlink_check_answer(sock); } static int ip4_addr_set(int sock, uint32_t seq, const char *intf, struct in_addr addr, uint8_t prefix) { uint16_t flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_EXCL | NLM_F_CREATE; struct { struct nlmsghdr nh; struct ifaddrmsg info; char attrbuf[MAX_PAYLOAD]; } req; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.info)); req.nh.nlmsg_type = RTM_NEWADDR; req.nh.nlmsg_flags = flags; req.nh.nlmsg_seq = seq; req.info.ifa_family = AF_INET; req.info.ifa_prefixlen = prefix; req.info.ifa_index = if_nametoindex(intf); #ifdef DEBUG { char addr_str[IPV4_STR_SZ] = {}; strncpy(addr_str, inet_ntoa(addr), IPV4_STR_SZ - 1); printk("ip addr set %s", addr_str); } #endif if (rtattr_pack(&req.nh, sizeof(req), IFA_LOCAL, &addr, sizeof(addr))) return -1; if (rtattr_pack(&req.nh, sizeof(req), IFA_ADDRESS, &addr, sizeof(addr))) return -1; if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } return netlink_check_answer(sock); } static int link_set_up(int sock, uint32_t seq, const char *intf) { struct { struct nlmsghdr nh; struct ifinfomsg info; char attrbuf[MAX_PAYLOAD]; } req; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.info)); req.nh.nlmsg_type = RTM_NEWLINK; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = seq; req.info.ifi_family = AF_UNSPEC; req.info.ifi_change = 0xFFFFFFFF; req.info.ifi_index = if_nametoindex(intf); req.info.ifi_flags = IFF_UP; req.info.ifi_change = IFF_UP; if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } return netlink_check_answer(sock); } static int ip4_route_set(int sock, uint32_t seq, const char *intf, struct in_addr src, struct in_addr dst) { struct { struct nlmsghdr nh; struct rtmsg rt; char attrbuf[MAX_PAYLOAD]; } req; unsigned int index = if_nametoindex(intf); memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.rt)); req.nh.nlmsg_type = RTM_NEWROUTE; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE; req.nh.nlmsg_seq = seq; req.rt.rtm_family = AF_INET; req.rt.rtm_dst_len = 32; req.rt.rtm_table = RT_TABLE_MAIN; req.rt.rtm_protocol = RTPROT_BOOT; req.rt.rtm_scope = RT_SCOPE_LINK; req.rt.rtm_type = RTN_UNICAST; if (rtattr_pack(&req.nh, sizeof(req), RTA_DST, &dst, sizeof(dst))) return -1; if (rtattr_pack(&req.nh, sizeof(req), RTA_PREFSRC, &src, sizeof(src))) return -1; if (rtattr_pack(&req.nh, sizeof(req), RTA_OIF, &index, sizeof(index))) return -1; if (send(sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } return netlink_check_answer(sock); } static int tunnel_set_route(int route_sock, uint32_t *route_seq, char *veth, struct in_addr tunsrc, struct in_addr tundst) { if (ip4_addr_set(route_sock, (*route_seq)++, "lo", tunsrc, PREFIX_LEN)) { printk("Failed to set ipv4 addr"); return -1; } if (ip4_route_set(route_sock, (*route_seq)++, veth, tunsrc, tundst)) { printk("Failed to set ipv4 route"); return -1; } return 0; } static int init_child(int nsfd, char *veth, unsigned int src, unsigned int dst) { struct in_addr intsrc = inet_makeaddr(INADDR_B, src); struct in_addr tunsrc = inet_makeaddr(INADDR_A, src); struct in_addr tundst = inet_makeaddr(INADDR_A, dst); int route_sock = -1, ret = -1; uint32_t route_seq; if (switch_ns(nsfd)) return -1; if (netlink_sock(&route_sock, &route_seq, NETLINK_ROUTE)) { printk("Failed to open netlink route socket in child"); return -1; } if (ip4_addr_set(route_sock, route_seq++, veth, intsrc, PREFIX_LEN)) { printk("Failed to set ipv4 addr"); goto err; } if (link_set_up(route_sock, route_seq++, veth)) { printk("Failed to bring up %s", veth); goto err; } if (tunnel_set_route(route_sock, &route_seq, veth, tunsrc, tundst)) { printk("Failed to add tunnel route on %s", veth); goto err; } ret = 0; err: close(route_sock); return ret; } #define ALGO_LEN 64 enum desc_type { CREATE_TUNNEL = 0, ALLOCATE_SPI, MONITOR_ACQUIRE, EXPIRE_STATE, EXPIRE_POLICY, SPDINFO_ATTRS, }; const char *desc_name[] = { "create tunnel", "alloc spi", "monitor acquire", "expire state", "expire policy", "spdinfo attributes", "" }; struct xfrm_desc { enum desc_type type; uint8_t proto; char a_algo[ALGO_LEN]; char e_algo[ALGO_LEN]; char c_algo[ALGO_LEN]; char ae_algo[ALGO_LEN]; unsigned int icv_len; /* unsigned key_len; */ }; enum msg_type { MSG_ACK = 0, MSG_EXIT, MSG_PING, MSG_XFRM_PREPARE, MSG_XFRM_ADD, MSG_XFRM_DEL, MSG_XFRM_CLEANUP, }; struct test_desc { enum msg_type type; union { struct { in_addr_t reply_ip; unsigned int port; } ping; struct xfrm_desc xfrm_desc; } body; }; struct test_result { struct xfrm_desc desc; unsigned int res; }; static void write_test_result(unsigned int res, struct xfrm_desc *d) { struct test_result tr = {}; ssize_t ret; tr.desc = *d; tr.res = res; ret = write(results_fd[1], &tr, sizeof(tr)); if (ret != sizeof(tr)) pr_err("Failed to write the result in pipe %zd", ret); } static void write_msg(int fd, struct test_desc *msg, bool exit_of_fail) { ssize_t bytes = write(fd, msg, sizeof(*msg)); /* Make sure that write/read is atomic to a pipe */ BUILD_BUG_ON(sizeof(struct test_desc) > PIPE_BUF); if (bytes < 0) { pr_err("write()"); if (exit_of_fail) exit(KSFT_FAIL); } if (bytes != sizeof(*msg)) { pr_err("sent part of the message %zd/%zu", bytes, sizeof(*msg)); if (exit_of_fail) exit(KSFT_FAIL); } } static void read_msg(int fd, struct test_desc *msg, bool exit_of_fail) { ssize_t bytes = read(fd, msg, sizeof(*msg)); if (bytes < 0) { pr_err("read()"); if (exit_of_fail) exit(KSFT_FAIL); } if (bytes != sizeof(*msg)) { pr_err("got incomplete message %zd/%zu", bytes, sizeof(*msg)); if (exit_of_fail) exit(KSFT_FAIL); } } static int udp_ping_init(struct in_addr listen_ip, unsigned int u_timeout, unsigned int *server_port, int sock[2]) { struct sockaddr_in server; struct timeval t = { .tv_sec = 0, .tv_usec = u_timeout }; socklen_t s_len = sizeof(server); sock[0] = socket(AF_INET, SOCK_DGRAM, 0); if (sock[0] < 0) { pr_err("socket()"); return -1; } server.sin_family = AF_INET; server.sin_port = 0; memcpy(&server.sin_addr.s_addr, &listen_ip, sizeof(struct in_addr)); if (bind(sock[0], (struct sockaddr *)&server, s_len)) { pr_err("bind()"); goto err_close_server; } if (getsockname(sock[0], (struct sockaddr *)&server, &s_len)) { pr_err("getsockname()"); goto err_close_server; } *server_port = ntohs(server.sin_port); if (setsockopt(sock[0], SOL_SOCKET, SO_RCVTIMEO, (const char *)&t, sizeof t)) { pr_err("setsockopt()"); goto err_close_server; } sock[1] = socket(AF_INET, SOCK_DGRAM, 0); if (sock[1] < 0) { pr_err("socket()"); goto err_close_server; } return 0; err_close_server: close(sock[0]); return -1; } static int udp_ping_send(int sock[2], in_addr_t dest_ip, unsigned int port, char *buf, size_t buf_len) { struct sockaddr_in server; const struct sockaddr *dest_addr = (struct sockaddr *)&server; char *sock_buf[buf_len]; ssize_t r_bytes, s_bytes; server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = dest_ip; s_bytes = sendto(sock[1], buf, buf_len, 0, dest_addr, sizeof(server)); if (s_bytes < 0) { pr_err("sendto()"); return -1; } else if (s_bytes != buf_len) { printk("send part of the message: %zd/%zu", s_bytes, sizeof(server)); return -1; } r_bytes = recv(sock[0], sock_buf, buf_len, 0); if (r_bytes < 0) { if (errno != EAGAIN) pr_err("recv()"); return -1; } else if (r_bytes == 0) { /* EOF */ printk("EOF on reply to ping"); return -1; } else if (r_bytes != buf_len || memcmp(buf, sock_buf, buf_len)) { printk("ping reply packet is corrupted %zd/%zu", r_bytes, buf_len); return -1; } return 0; } static int udp_ping_reply(int sock[2], in_addr_t dest_ip, unsigned int port, char *buf, size_t buf_len) { struct sockaddr_in server; const struct sockaddr *dest_addr = (struct sockaddr *)&server; char *sock_buf[buf_len]; ssize_t r_bytes, s_bytes; server.sin_family = AF_INET; server.sin_port = htons(port); server.sin_addr.s_addr = dest_ip; r_bytes = recv(sock[0], sock_buf, buf_len, 0); if (r_bytes < 0) { if (errno != EAGAIN) pr_err("recv()"); return -1; } if (r_bytes == 0) { /* EOF */ printk("EOF on reply to ping"); return -1; } if (r_bytes != buf_len || memcmp(buf, sock_buf, buf_len)) { printk("ping reply packet is corrupted %zd/%zu", r_bytes, buf_len); return -1; } s_bytes = sendto(sock[1], buf, buf_len, 0, dest_addr, sizeof(server)); if (s_bytes < 0) { pr_err("sendto()"); return -1; } else if (s_bytes != buf_len) { printk("send part of the message: %zd/%zu", s_bytes, sizeof(server)); return -1; } return 0; } typedef int (*ping_f)(int sock[2], in_addr_t dest_ip, unsigned int port, char *buf, size_t buf_len); static int do_ping(int cmd_fd, char *buf, size_t buf_len, struct in_addr from, bool init_side, int d_port, in_addr_t to, ping_f func) { struct test_desc msg; unsigned int s_port, i, ping_succeeded = 0; int ping_sock[2]; char to_str[IPV4_STR_SZ] = {}, from_str[IPV4_STR_SZ] = {}; if (udp_ping_init(from, ping_timeout, &s_port, ping_sock)) { printk("Failed to init ping"); return -1; } memset(&msg, 0, sizeof(msg)); msg.type = MSG_PING; msg.body.ping.port = s_port; memcpy(&msg.body.ping.reply_ip, &from, sizeof(from)); write_msg(cmd_fd, &msg, 0); if (init_side) { /* The other end sends ip to ping */ read_msg(cmd_fd, &msg, 0); if (msg.type != MSG_PING) return -1; to = msg.body.ping.reply_ip; d_port = msg.body.ping.port; } for (i = 0; i < ping_count ; i++) { struct timespec sleep_time = { .tv_sec = 0, .tv_nsec = ping_delay_nsec, }; ping_succeeded += !func(ping_sock, to, d_port, buf, page_size); nanosleep(&sleep_time, 0); } close(ping_sock[0]); close(ping_sock[1]); strncpy(to_str, inet_ntoa(*(struct in_addr *)&to), IPV4_STR_SZ - 1); strncpy(from_str, inet_ntoa(from), IPV4_STR_SZ - 1); if (ping_succeeded < ping_success) { printk("ping (%s) %s->%s failed %u/%u times", init_side ? "send" : "reply", from_str, to_str, ping_count - ping_succeeded, ping_count); return -1; } #ifdef DEBUG printk("ping (%s) %s->%s succeeded %u/%u times", init_side ? "send" : "reply", from_str, to_str, ping_succeeded, ping_count); #endif return 0; } static int xfrm_fill_key(char *name, char *buf, size_t buf_len, unsigned int *key_len) { int i; for (i = 0; i < XFRM_ALGO_NR_KEYS; i++) { if (strncmp(name, xfrm_key_entries[i].algo_name, ALGO_LEN) == 0) *key_len = xfrm_key_entries[i].key_len; } if (*key_len > buf_len) { printk("Can't pack a key - too big for buffer"); return -1; } randomize_buffer(buf, *key_len); return 0; } static int xfrm_state_pack_algo(struct nlmsghdr *nh, size_t req_sz, struct xfrm_desc *desc) { struct { union { struct xfrm_algo alg; struct xfrm_algo_aead aead; struct xfrm_algo_auth auth; } u; char buf[XFRM_ALGO_KEY_BUF_SIZE]; } alg = {}; size_t alen, elen, clen, aelen; unsigned short type; alen = strlen(desc->a_algo); elen = strlen(desc->e_algo); clen = strlen(desc->c_algo); aelen = strlen(desc->ae_algo); /* Verify desc */ switch (desc->proto) { case IPPROTO_AH: if (!alen || elen || clen || aelen) { printk("BUG: buggy ah desc"); return -1; } strncpy(alg.u.alg.alg_name, desc->a_algo, ALGO_LEN - 1); if (xfrm_fill_key(desc->a_algo, alg.u.alg.alg_key, sizeof(alg.buf), &alg.u.alg.alg_key_len)) return -1; type = XFRMA_ALG_AUTH; break; case IPPROTO_COMP: if (!clen || elen || alen || aelen) { printk("BUG: buggy comp desc"); return -1; } strncpy(alg.u.alg.alg_name, desc->c_algo, ALGO_LEN - 1); if (xfrm_fill_key(desc->c_algo, alg.u.alg.alg_key, sizeof(alg.buf), &alg.u.alg.alg_key_len)) return -1; type = XFRMA_ALG_COMP; break; case IPPROTO_ESP: if (!((alen && elen) ^ aelen) || clen) { printk("BUG: buggy esp desc"); return -1; } if (aelen) { alg.u.aead.alg_icv_len = desc->icv_len; strncpy(alg.u.aead.alg_name, desc->ae_algo, ALGO_LEN - 1); if (xfrm_fill_key(desc->ae_algo, alg.u.aead.alg_key, sizeof(alg.buf), &alg.u.aead.alg_key_len)) return -1; type = XFRMA_ALG_AEAD; } else { strncpy(alg.u.alg.alg_name, desc->e_algo, ALGO_LEN - 1); type = XFRMA_ALG_CRYPT; if (xfrm_fill_key(desc->e_algo, alg.u.alg.alg_key, sizeof(alg.buf), &alg.u.alg.alg_key_len)) return -1; if (rtattr_pack(nh, req_sz, type, &alg, sizeof(alg))) return -1; strncpy(alg.u.alg.alg_name, desc->a_algo, ALGO_LEN); type = XFRMA_ALG_AUTH; if (xfrm_fill_key(desc->a_algo, alg.u.alg.alg_key, sizeof(alg.buf), &alg.u.alg.alg_key_len)) return -1; } break; default: printk("BUG: unknown proto in desc"); return -1; } if (rtattr_pack(nh, req_sz, type, &alg, sizeof(alg))) return -1; return 0; } static inline uint32_t gen_spi(struct in_addr src) { return htonl(inet_lnaof(src)); } static int xfrm_state_add(int xfrm_sock, uint32_t seq, uint32_t spi, struct in_addr src, struct in_addr dst, struct xfrm_desc *desc) { struct { struct nlmsghdr nh; struct xfrm_usersa_info info; char attrbuf[MAX_PAYLOAD]; } req; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.info)); req.nh.nlmsg_type = XFRM_MSG_NEWSA; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = seq; /* Fill selector. */ memcpy(&req.info.sel.daddr, &dst, sizeof(dst)); memcpy(&req.info.sel.saddr, &src, sizeof(src)); req.info.sel.family = AF_INET; req.info.sel.prefixlen_d = PREFIX_LEN; req.info.sel.prefixlen_s = PREFIX_LEN; /* Fill id */ memcpy(&req.info.id.daddr, &dst, sizeof(dst)); /* Note: zero-spi cannot be deleted */ req.info.id.spi = spi; req.info.id.proto = desc->proto; memcpy(&req.info.saddr, &src, sizeof(src)); /* Fill lifteme_cfg */ req.info.lft.soft_byte_limit = XFRM_INF; req.info.lft.hard_byte_limit = XFRM_INF; req.info.lft.soft_packet_limit = XFRM_INF; req.info.lft.hard_packet_limit = XFRM_INF; req.info.family = AF_INET; req.info.mode = XFRM_MODE_TUNNEL; if (xfrm_state_pack_algo(&req.nh, sizeof(req), desc)) return -1; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } return netlink_check_answer(xfrm_sock); } static bool xfrm_usersa_found(struct xfrm_usersa_info *info, uint32_t spi, struct in_addr src, struct in_addr dst, struct xfrm_desc *desc) { if (memcmp(&info->sel.daddr, &dst, sizeof(dst))) return false; if (memcmp(&info->sel.saddr, &src, sizeof(src))) return false; if (info->sel.family != AF_INET || info->sel.prefixlen_d != PREFIX_LEN || info->sel.prefixlen_s != PREFIX_LEN) return false; if (info->id.spi != spi || info->id.proto != desc->proto) return false; if (memcmp(&info->id.daddr, &dst, sizeof(dst))) return false; if (memcmp(&info->saddr, &src, sizeof(src))) return false; if (info->lft.soft_byte_limit != XFRM_INF || info->lft.hard_byte_limit != XFRM_INF || info->lft.soft_packet_limit != XFRM_INF || info->lft.hard_packet_limit != XFRM_INF) return false; if (info->family != AF_INET || info->mode != XFRM_MODE_TUNNEL) return false; /* XXX: check xfrm algo, see xfrm_state_pack_algo(). */ return true; } static int xfrm_state_check(int xfrm_sock, uint32_t seq, uint32_t spi, struct in_addr src, struct in_addr dst, struct xfrm_desc *desc) { struct { struct nlmsghdr nh; char attrbuf[MAX_PAYLOAD]; } req; struct { struct nlmsghdr nh; union { struct xfrm_usersa_info info; int error; }; char attrbuf[MAX_PAYLOAD]; } answer; struct xfrm_address_filter filter = {}; bool found = false; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(0); req.nh.nlmsg_type = XFRM_MSG_GETSA; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP; req.nh.nlmsg_seq = seq; /* * Add dump filter by source address as there may be other tunnels * in this netns (if tests run in parallel). */ filter.family = AF_INET; filter.splen = 0x1f; /* 0xffffffff mask see addr_match() */ memcpy(&filter.saddr, &src, sizeof(src)); if (rtattr_pack(&req.nh, sizeof(req), XFRMA_ADDRESS_FILTER, &filter, sizeof(filter))) return -1; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } while (1) { if (recv(xfrm_sock, &answer, sizeof(answer), 0) < 0) { pr_err("recv()"); return -1; } if (answer.nh.nlmsg_type == NLMSG_ERROR) { printk("NLMSG_ERROR: %d: %s", answer.error, strerror(-answer.error)); return -1; } else if (answer.nh.nlmsg_type == NLMSG_DONE) { if (found) return 0; printk("didn't find allocated xfrm state in dump"); return -1; } else if (answer.nh.nlmsg_type == XFRM_MSG_NEWSA) { if (xfrm_usersa_found(&answer.info, spi, src, dst, desc)) found = true; } } } static int xfrm_set(int xfrm_sock, uint32_t *seq, struct in_addr src, struct in_addr dst, struct in_addr tunsrc, struct in_addr tundst, struct xfrm_desc *desc) { int err; err = xfrm_state_add(xfrm_sock, (*seq)++, gen_spi(src), src, dst, desc); if (err) { printk("Failed to add xfrm state"); return -1; } err = xfrm_state_add(xfrm_sock, (*seq)++, gen_spi(src), dst, src, desc); if (err) { printk("Failed to add xfrm state"); return -1; } /* Check dumps for XFRM_MSG_GETSA */ err = xfrm_state_check(xfrm_sock, (*seq)++, gen_spi(src), src, dst, desc); err |= xfrm_state_check(xfrm_sock, (*seq)++, gen_spi(src), dst, src, desc); if (err) { printk("Failed to check xfrm state"); return -1; } return 0; } static int xfrm_policy_add(int xfrm_sock, uint32_t seq, uint32_t spi, struct in_addr src, struct in_addr dst, uint8_t dir, struct in_addr tunsrc, struct in_addr tundst, uint8_t proto) { struct { struct nlmsghdr nh; struct xfrm_userpolicy_info info; char attrbuf[MAX_PAYLOAD]; } req; struct xfrm_user_tmpl tmpl; memset(&req, 0, sizeof(req)); memset(&tmpl, 0, sizeof(tmpl)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.info)); req.nh.nlmsg_type = XFRM_MSG_NEWPOLICY; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = seq; /* Fill selector. */ memcpy(&req.info.sel.daddr, &dst, sizeof(tundst)); memcpy(&req.info.sel.saddr, &src, sizeof(tunsrc)); req.info.sel.family = AF_INET; req.info.sel.prefixlen_d = PREFIX_LEN; req.info.sel.prefixlen_s = PREFIX_LEN; /* Fill lifteme_cfg */ req.info.lft.soft_byte_limit = XFRM_INF; req.info.lft.hard_byte_limit = XFRM_INF; req.info.lft.soft_packet_limit = XFRM_INF; req.info.lft.hard_packet_limit = XFRM_INF; req.info.dir = dir; /* Fill tmpl */ memcpy(&tmpl.id.daddr, &dst, sizeof(dst)); /* Note: zero-spi cannot be deleted */ tmpl.id.spi = spi; tmpl.id.proto = proto; tmpl.family = AF_INET; memcpy(&tmpl.saddr, &src, sizeof(src)); tmpl.mode = XFRM_MODE_TUNNEL; tmpl.aalgos = (~(uint32_t)0); tmpl.ealgos = (~(uint32_t)0); tmpl.calgos = (~(uint32_t)0); if (rtattr_pack(&req.nh, sizeof(req), XFRMA_TMPL, &tmpl, sizeof(tmpl))) return -1; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } return netlink_check_answer(xfrm_sock); } static int xfrm_prepare(int xfrm_sock, uint32_t *seq, struct in_addr src, struct in_addr dst, struct in_addr tunsrc, struct in_addr tundst, uint8_t proto) { if (xfrm_policy_add(xfrm_sock, (*seq)++, gen_spi(src), src, dst, XFRM_POLICY_OUT, tunsrc, tundst, proto)) { printk("Failed to add xfrm policy"); return -1; } if (xfrm_policy_add(xfrm_sock, (*seq)++, gen_spi(src), dst, src, XFRM_POLICY_IN, tunsrc, tundst, proto)) { printk("Failed to add xfrm policy"); return -1; } return 0; } static int xfrm_policy_del(int xfrm_sock, uint32_t seq, struct in_addr src, struct in_addr dst, uint8_t dir, struct in_addr tunsrc, struct in_addr tundst) { struct { struct nlmsghdr nh; struct xfrm_userpolicy_id id; char attrbuf[MAX_PAYLOAD]; } req; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.id)); req.nh.nlmsg_type = XFRM_MSG_DELPOLICY; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = seq; /* Fill id */ memcpy(&req.id.sel.daddr, &dst, sizeof(tundst)); memcpy(&req.id.sel.saddr, &src, sizeof(tunsrc)); req.id.sel.family = AF_INET; req.id.sel.prefixlen_d = PREFIX_LEN; req.id.sel.prefixlen_s = PREFIX_LEN; req.id.dir = dir; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } return netlink_check_answer(xfrm_sock); } static int xfrm_cleanup(int xfrm_sock, uint32_t *seq, struct in_addr src, struct in_addr dst, struct in_addr tunsrc, struct in_addr tundst) { if (xfrm_policy_del(xfrm_sock, (*seq)++, src, dst, XFRM_POLICY_OUT, tunsrc, tundst)) { printk("Failed to add xfrm policy"); return -1; } if (xfrm_policy_del(xfrm_sock, (*seq)++, dst, src, XFRM_POLICY_IN, tunsrc, tundst)) { printk("Failed to add xfrm policy"); return -1; } return 0; } static int xfrm_state_del(int xfrm_sock, uint32_t seq, uint32_t spi, struct in_addr src, struct in_addr dst, uint8_t proto) { struct { struct nlmsghdr nh; struct xfrm_usersa_id id; char attrbuf[MAX_PAYLOAD]; } req; xfrm_address_t saddr = {}; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.id)); req.nh.nlmsg_type = XFRM_MSG_DELSA; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = seq; memcpy(&req.id.daddr, &dst, sizeof(dst)); req.id.family = AF_INET; req.id.proto = proto; /* Note: zero-spi cannot be deleted */ req.id.spi = spi; memcpy(&saddr, &src, sizeof(src)); if (rtattr_pack(&req.nh, sizeof(req), XFRMA_SRCADDR, &saddr, sizeof(saddr))) return -1; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } return netlink_check_answer(xfrm_sock); } static int xfrm_delete(int xfrm_sock, uint32_t *seq, struct in_addr src, struct in_addr dst, struct in_addr tunsrc, struct in_addr tundst, uint8_t proto) { if (xfrm_state_del(xfrm_sock, (*seq)++, gen_spi(src), src, dst, proto)) { printk("Failed to remove xfrm state"); return -1; } if (xfrm_state_del(xfrm_sock, (*seq)++, gen_spi(src), dst, src, proto)) { printk("Failed to remove xfrm state"); return -1; } return 0; } static int xfrm_state_allocspi(int xfrm_sock, uint32_t *seq, uint32_t spi, uint8_t proto) { struct { struct nlmsghdr nh; struct xfrm_userspi_info spi; } req; struct { struct nlmsghdr nh; union { struct xfrm_usersa_info info; int error; }; } answer; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.spi)); req.nh.nlmsg_type = XFRM_MSG_ALLOCSPI; req.nh.nlmsg_flags = NLM_F_REQUEST; req.nh.nlmsg_seq = (*seq)++; req.spi.info.family = AF_INET; req.spi.min = spi; req.spi.max = spi; req.spi.info.id.proto = proto; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return KSFT_FAIL; } if (recv(xfrm_sock, &answer, sizeof(answer), 0) < 0) { pr_err("recv()"); return KSFT_FAIL; } else if (answer.nh.nlmsg_type == XFRM_MSG_NEWSA) { uint32_t new_spi = htonl(answer.info.id.spi); if (new_spi != spi) { printk("allocated spi is different from requested: %#x != %#x", new_spi, spi); return KSFT_FAIL; } return KSFT_PASS; } else if (answer.nh.nlmsg_type != NLMSG_ERROR) { printk("expected NLMSG_ERROR, got %d", (int)answer.nh.nlmsg_type); return KSFT_FAIL; } printk("NLMSG_ERROR: %d: %s", answer.error, strerror(-answer.error)); return (answer.error) ? KSFT_FAIL : KSFT_PASS; } static int netlink_sock_bind(int *sock, uint32_t *seq, int proto, uint32_t groups) { struct sockaddr_nl snl = {}; socklen_t addr_len; int ret = -1; snl.nl_family = AF_NETLINK; snl.nl_groups = groups; if (netlink_sock(sock, seq, proto)) { printk("Failed to open xfrm netlink socket"); return -1; } if (bind(*sock, (struct sockaddr *)&snl, sizeof(snl)) < 0) { pr_err("bind()"); goto out_close; } addr_len = sizeof(snl); if (getsockname(*sock, (struct sockaddr *)&snl, &addr_len) < 0) { pr_err("getsockname()"); goto out_close; } if (addr_len != sizeof(snl)) { printk("Wrong address length %d", addr_len); goto out_close; } if (snl.nl_family != AF_NETLINK) { printk("Wrong address family %d", snl.nl_family); goto out_close; } return 0; out_close: close(*sock); return ret; } static int xfrm_monitor_acquire(int xfrm_sock, uint32_t *seq, unsigned int nr) { struct { struct nlmsghdr nh; union { struct xfrm_user_acquire acq; int error; }; char attrbuf[MAX_PAYLOAD]; } req; struct xfrm_user_tmpl xfrm_tmpl = {}; int xfrm_listen = -1, ret = KSFT_FAIL; uint32_t seq_listen; if (netlink_sock_bind(&xfrm_listen, &seq_listen, NETLINK_XFRM, XFRMNLGRP_ACQUIRE)) return KSFT_FAIL; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.acq)); req.nh.nlmsg_type = XFRM_MSG_ACQUIRE; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = (*seq)++; req.acq.policy.sel.family = AF_INET; req.acq.aalgos = 0xfeed; req.acq.ealgos = 0xbaad; req.acq.calgos = 0xbabe; xfrm_tmpl.family = AF_INET; xfrm_tmpl.id.proto = IPPROTO_ESP; if (rtattr_pack(&req.nh, sizeof(req), XFRMA_TMPL, &xfrm_tmpl, sizeof(xfrm_tmpl))) goto out_close; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); goto out_close; } if (recv(xfrm_sock, &req, sizeof(req), 0) < 0) { pr_err("recv()"); goto out_close; } else if (req.nh.nlmsg_type != NLMSG_ERROR) { printk("expected NLMSG_ERROR, got %d", (int)req.nh.nlmsg_type); goto out_close; } if (req.error) { printk("NLMSG_ERROR: %d: %s", req.error, strerror(-req.error)); ret = req.error; goto out_close; } if (recv(xfrm_listen, &req, sizeof(req), 0) < 0) { pr_err("recv()"); goto out_close; } if (req.acq.aalgos != 0xfeed || req.acq.ealgos != 0xbaad || req.acq.calgos != 0xbabe) { printk("xfrm_user_acquire has changed %x %x %x", req.acq.aalgos, req.acq.ealgos, req.acq.calgos); goto out_close; } ret = KSFT_PASS; out_close: close(xfrm_listen); return ret; } static int xfrm_expire_state(int xfrm_sock, uint32_t *seq, unsigned int nr, struct xfrm_desc *desc) { struct { struct nlmsghdr nh; union { struct xfrm_user_expire expire; int error; }; } req; struct in_addr src, dst; int xfrm_listen = -1, ret = KSFT_FAIL; uint32_t seq_listen; src = inet_makeaddr(INADDR_B, child_ip(nr)); dst = inet_makeaddr(INADDR_B, grchild_ip(nr)); if (xfrm_state_add(xfrm_sock, (*seq)++, gen_spi(src), src, dst, desc)) { printk("Failed to add xfrm state"); return KSFT_FAIL; } if (netlink_sock_bind(&xfrm_listen, &seq_listen, NETLINK_XFRM, XFRMNLGRP_EXPIRE)) return KSFT_FAIL; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.expire)); req.nh.nlmsg_type = XFRM_MSG_EXPIRE; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = (*seq)++; memcpy(&req.expire.state.id.daddr, &dst, sizeof(dst)); req.expire.state.id.spi = gen_spi(src); req.expire.state.id.proto = desc->proto; req.expire.state.family = AF_INET; req.expire.hard = 0xff; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); goto out_close; } if (recv(xfrm_sock, &req, sizeof(req), 0) < 0) { pr_err("recv()"); goto out_close; } else if (req.nh.nlmsg_type != NLMSG_ERROR) { printk("expected NLMSG_ERROR, got %d", (int)req.nh.nlmsg_type); goto out_close; } if (req.error) { printk("NLMSG_ERROR: %d: %s", req.error, strerror(-req.error)); ret = req.error; goto out_close; } if (recv(xfrm_listen, &req, sizeof(req), 0) < 0) { pr_err("recv()"); goto out_close; } if (req.expire.hard != 0x1) { printk("expire.hard is not set: %x", req.expire.hard); goto out_close; } ret = KSFT_PASS; out_close: close(xfrm_listen); return ret; } static int xfrm_expire_policy(int xfrm_sock, uint32_t *seq, unsigned int nr, struct xfrm_desc *desc) { struct { struct nlmsghdr nh; union { struct xfrm_user_polexpire expire; int error; }; } req; struct in_addr src, dst, tunsrc, tundst; int xfrm_listen = -1, ret = KSFT_FAIL; uint32_t seq_listen; src = inet_makeaddr(INADDR_B, child_ip(nr)); dst = inet_makeaddr(INADDR_B, grchild_ip(nr)); tunsrc = inet_makeaddr(INADDR_A, child_ip(nr)); tundst = inet_makeaddr(INADDR_A, grchild_ip(nr)); if (xfrm_policy_add(xfrm_sock, (*seq)++, gen_spi(src), src, dst, XFRM_POLICY_OUT, tunsrc, tundst, desc->proto)) { printk("Failed to add xfrm policy"); return KSFT_FAIL; } if (netlink_sock_bind(&xfrm_listen, &seq_listen, NETLINK_XFRM, XFRMNLGRP_EXPIRE)) return KSFT_FAIL; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.expire)); req.nh.nlmsg_type = XFRM_MSG_POLEXPIRE; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = (*seq)++; /* Fill selector. */ memcpy(&req.expire.pol.sel.daddr, &dst, sizeof(tundst)); memcpy(&req.expire.pol.sel.saddr, &src, sizeof(tunsrc)); req.expire.pol.sel.family = AF_INET; req.expire.pol.sel.prefixlen_d = PREFIX_LEN; req.expire.pol.sel.prefixlen_s = PREFIX_LEN; req.expire.pol.dir = XFRM_POLICY_OUT; req.expire.hard = 0xff; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); goto out_close; } if (recv(xfrm_sock, &req, sizeof(req), 0) < 0) { pr_err("recv()"); goto out_close; } else if (req.nh.nlmsg_type != NLMSG_ERROR) { printk("expected NLMSG_ERROR, got %d", (int)req.nh.nlmsg_type); goto out_close; } if (req.error) { printk("NLMSG_ERROR: %d: %s", req.error, strerror(-req.error)); ret = req.error; goto out_close; } if (recv(xfrm_listen, &req, sizeof(req), 0) < 0) { pr_err("recv()"); goto out_close; } if (req.expire.hard != 0x1) { printk("expire.hard is not set: %x", req.expire.hard); goto out_close; } ret = KSFT_PASS; out_close: close(xfrm_listen); return ret; } static int xfrm_spdinfo_set_thresh(int xfrm_sock, uint32_t *seq, unsigned thresh4_l, unsigned thresh4_r, unsigned thresh6_l, unsigned thresh6_r, bool add_bad_attr) { struct { struct nlmsghdr nh; union { uint32_t unused; int error; }; char attrbuf[MAX_PAYLOAD]; } req; struct xfrmu_spdhthresh thresh; memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.unused)); req.nh.nlmsg_type = XFRM_MSG_NEWSPDINFO; req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nh.nlmsg_seq = (*seq)++; thresh.lbits = thresh4_l; thresh.rbits = thresh4_r; if (rtattr_pack(&req.nh, sizeof(req), XFRMA_SPD_IPV4_HTHRESH, &thresh, sizeof(thresh))) return -1; thresh.lbits = thresh6_l; thresh.rbits = thresh6_r; if (rtattr_pack(&req.nh, sizeof(req), XFRMA_SPD_IPV6_HTHRESH, &thresh, sizeof(thresh))) return -1; if (add_bad_attr) { BUILD_BUG_ON(XFRMA_IF_ID <= XFRMA_SPD_MAX + 1); if (rtattr_pack(&req.nh, sizeof(req), XFRMA_IF_ID, NULL, 0)) { pr_err("adding attribute failed: no space"); return -1; } } if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return -1; } if (recv(xfrm_sock, &req, sizeof(req), 0) < 0) { pr_err("recv()"); return -1; } else if (req.nh.nlmsg_type != NLMSG_ERROR) { printk("expected NLMSG_ERROR, got %d", (int)req.nh.nlmsg_type); return -1; } if (req.error) { printk("NLMSG_ERROR: %d: %s", req.error, strerror(-req.error)); return -1; } return 0; } static int xfrm_spdinfo_attrs(int xfrm_sock, uint32_t *seq) { struct { struct nlmsghdr nh; union { uint32_t unused; int error; }; char attrbuf[MAX_PAYLOAD]; } req; if (xfrm_spdinfo_set_thresh(xfrm_sock, seq, 32, 31, 120, 16, false)) { pr_err("Can't set SPD HTHRESH"); return KSFT_FAIL; } memset(&req, 0, sizeof(req)); req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.unused)); req.nh.nlmsg_type = XFRM_MSG_GETSPDINFO; req.nh.nlmsg_flags = NLM_F_REQUEST; req.nh.nlmsg_seq = (*seq)++; if (send(xfrm_sock, &req, req.nh.nlmsg_len, 0) < 0) { pr_err("send()"); return KSFT_FAIL; } if (recv(xfrm_sock, &req, sizeof(req), 0) < 0) { pr_err("recv()"); return KSFT_FAIL; } else if (req.nh.nlmsg_type == XFRM_MSG_NEWSPDINFO) { size_t len = NLMSG_PAYLOAD(&req.nh, sizeof(req.unused)); struct rtattr *attr = (void *)req.attrbuf; int got_thresh = 0; for (; RTA_OK(attr, len); attr = RTA_NEXT(attr, len)) { if (attr->rta_type == XFRMA_SPD_IPV4_HTHRESH) { struct xfrmu_spdhthresh *t = RTA_DATA(attr); got_thresh++; if (t->lbits != 32 || t->rbits != 31) { pr_err("thresh differ: %u, %u", t->lbits, t->rbits); return KSFT_FAIL; } } if (attr->rta_type == XFRMA_SPD_IPV6_HTHRESH) { struct xfrmu_spdhthresh *t = RTA_DATA(attr); got_thresh++; if (t->lbits != 120 || t->rbits != 16) { pr_err("thresh differ: %u, %u", t->lbits, t->rbits); return KSFT_FAIL; } } } if (got_thresh != 2) { pr_err("only %d thresh returned by XFRM_MSG_GETSPDINFO", got_thresh); return KSFT_FAIL; } } else if (req.nh.nlmsg_type != NLMSG_ERROR) { printk("expected NLMSG_ERROR, got %d", (int)req.nh.nlmsg_type); return KSFT_FAIL; } else { printk("NLMSG_ERROR: %d: %s", req.error, strerror(-req.error)); return -1; } /* Restore the default */ if (xfrm_spdinfo_set_thresh(xfrm_sock, seq, 32, 32, 128, 128, false)) { pr_err("Can't restore SPD HTHRESH"); return KSFT_FAIL; } /* * At this moment xfrm uses nlmsg_parse_deprecated(), which * implies NL_VALIDATE_LIBERAL - ignoring attributes with * (type > maxtype). nla_parse_depricated_strict() would enforce * it. Or even stricter nla_parse(). * Right now it's not expected to fail, but to be ignored. */ if (xfrm_spdinfo_set_thresh(xfrm_sock, seq, 32, 32, 128, 128, true)) return KSFT_PASS; return KSFT_PASS; } static int child_serv(int xfrm_sock, uint32_t *seq, unsigned int nr, int cmd_fd, void *buf, struct xfrm_desc *desc) { struct in_addr src, dst, tunsrc, tundst; struct test_desc msg; int ret = KSFT_FAIL; src = inet_makeaddr(INADDR_B, child_ip(nr)); dst = inet_makeaddr(INADDR_B, grchild_ip(nr)); tunsrc = inet_makeaddr(INADDR_A, child_ip(nr)); tundst = inet_makeaddr(INADDR_A, grchild_ip(nr)); /* UDP pinging without xfrm */ if (do_ping(cmd_fd, buf, page_size, src, true, 0, 0, udp_ping_send)) { printk("ping failed before setting xfrm"); return KSFT_FAIL; } memset(&msg, 0, sizeof(msg)); msg.type = MSG_XFRM_PREPARE; memcpy(&msg.body.xfrm_desc, desc, sizeof(*desc)); write_msg(cmd_fd, &msg, 1); if (xfrm_prepare(xfrm_sock, seq, src, dst, tunsrc, tundst, desc->proto)) { printk("failed to prepare xfrm"); goto cleanup; } memset(&msg, 0, sizeof(msg)); msg.type = MSG_XFRM_ADD; memcpy(&msg.body.xfrm_desc, desc, sizeof(*desc)); write_msg(cmd_fd, &msg, 1); if (xfrm_set(xfrm_sock, seq, src, dst, tunsrc, tundst, desc)) { printk("failed to set xfrm"); goto delete; } /* UDP pinging with xfrm tunnel */ if (do_ping(cmd_fd, buf, page_size, tunsrc, true, 0, 0, udp_ping_send)) { printk("ping failed for xfrm"); goto delete; } ret = KSFT_PASS; delete: /* xfrm delete */ memset(&msg, 0, sizeof(msg)); msg.type = MSG_XFRM_DEL; memcpy(&msg.body.xfrm_desc, desc, sizeof(*desc)); write_msg(cmd_fd, &msg, 1); if (xfrm_delete(xfrm_sock, seq, src, dst, tunsrc, tundst, desc->proto)) { printk("failed ping to remove xfrm"); ret = KSFT_FAIL; } cleanup: memset(&msg, 0, sizeof(msg)); msg.type = MSG_XFRM_CLEANUP; memcpy(&msg.body.xfrm_desc, desc, sizeof(*desc)); write_msg(cmd_fd, &msg, 1); if (xfrm_cleanup(xfrm_sock, seq, src, dst, tunsrc, tundst)) { printk("failed ping to cleanup xfrm"); ret = KSFT_FAIL; } return ret; } static int child_f(unsigned int nr, int test_desc_fd, int cmd_fd, void *buf) { struct xfrm_desc desc; struct test_desc msg; int xfrm_sock = -1; uint32_t seq; if (switch_ns(nsfd_childa)) exit(KSFT_FAIL); if (netlink_sock(&xfrm_sock, &seq, NETLINK_XFRM)) { printk("Failed to open xfrm netlink socket"); exit(KSFT_FAIL); } /* Check that seq sock is ready, just for sure. */ memset(&msg, 0, sizeof(msg)); msg.type = MSG_ACK; write_msg(cmd_fd, &msg, 1); read_msg(cmd_fd, &msg, 1); if (msg.type != MSG_ACK) { printk("Ack failed"); exit(KSFT_FAIL); } for (;;) { ssize_t received = read(test_desc_fd, &desc, sizeof(desc)); int ret; if (received == 0) /* EOF */ break; if (received != sizeof(desc)) { pr_err("read() returned %zd", received); exit(KSFT_FAIL); } switch (desc.type) { case CREATE_TUNNEL: ret = child_serv(xfrm_sock, &seq, nr, cmd_fd, buf, &desc); break; case ALLOCATE_SPI: ret = xfrm_state_allocspi(xfrm_sock, &seq, -1, desc.proto); break; case MONITOR_ACQUIRE: ret = xfrm_monitor_acquire(xfrm_sock, &seq, nr); break; case EXPIRE_STATE: ret = xfrm_expire_state(xfrm_sock, &seq, nr, &desc); break; case EXPIRE_POLICY: ret = xfrm_expire_policy(xfrm_sock, &seq, nr, &desc); break; case SPDINFO_ATTRS: ret = xfrm_spdinfo_attrs(xfrm_sock, &seq); break; default: printk("Unknown desc type %d", desc.type); exit(KSFT_FAIL); } write_test_result(ret, &desc); } close(xfrm_sock); msg.type = MSG_EXIT; write_msg(cmd_fd, &msg, 1); exit(KSFT_PASS); } static void grand_child_serv(unsigned int nr, int cmd_fd, void *buf, struct test_desc *msg, int xfrm_sock, uint32_t *seq) { struct in_addr src, dst, tunsrc, tundst; bool tun_reply; struct xfrm_desc *desc = &msg->body.xfrm_desc; src = inet_makeaddr(INADDR_B, grchild_ip(nr)); dst = inet_makeaddr(INADDR_B, child_ip(nr)); tunsrc = inet_makeaddr(INADDR_A, grchild_ip(nr)); tundst = inet_makeaddr(INADDR_A, child_ip(nr)); switch (msg->type) { case MSG_EXIT: exit(KSFT_PASS); case MSG_ACK: write_msg(cmd_fd, msg, 1); break; case MSG_PING: tun_reply = memcmp(&dst, &msg->body.ping.reply_ip, sizeof(in_addr_t)); /* UDP pinging without xfrm */ if (do_ping(cmd_fd, buf, page_size, tun_reply ? tunsrc : src, false, msg->body.ping.port, msg->body.ping.reply_ip, udp_ping_reply)) { printk("ping failed before setting xfrm"); } break; case MSG_XFRM_PREPARE: if (xfrm_prepare(xfrm_sock, seq, src, dst, tunsrc, tundst, desc->proto)) { xfrm_cleanup(xfrm_sock, seq, src, dst, tunsrc, tundst); printk("failed to prepare xfrm"); } break; case MSG_XFRM_ADD: if (xfrm_set(xfrm_sock, seq, src, dst, tunsrc, tundst, desc)) { xfrm_cleanup(xfrm_sock, seq, src, dst, tunsrc, tundst); printk("failed to set xfrm"); } break; case MSG_XFRM_DEL: if (xfrm_delete(xfrm_sock, seq, src, dst, tunsrc, tundst, desc->proto)) { xfrm_cleanup(xfrm_sock, seq, src, dst, tunsrc, tundst); printk("failed to remove xfrm"); } break; case MSG_XFRM_CLEANUP: if (xfrm_cleanup(xfrm_sock, seq, src, dst, tunsrc, tundst)) { printk("failed to cleanup xfrm"); } break; default: printk("got unknown msg type %d", msg->type); } } static int grand_child_f(unsigned int nr, int cmd_fd, void *buf) { struct test_desc msg; int xfrm_sock = -1; uint32_t seq; if (switch_ns(nsfd_childb)) exit(KSFT_FAIL); if (netlink_sock(&xfrm_sock, &seq, NETLINK_XFRM)) { printk("Failed to open xfrm netlink socket"); exit(KSFT_FAIL); } do { read_msg(cmd_fd, &msg, 1); grand_child_serv(nr, cmd_fd, buf, &msg, xfrm_sock, &seq); } while (1); close(xfrm_sock); exit(KSFT_FAIL); } static int start_child(unsigned int nr, char *veth, int test_desc_fd[2]) { int cmd_sock[2]; void *data_map; pid_t child; if (init_child(nsfd_childa, veth, child_ip(nr), grchild_ip(nr))) return -1; if (init_child(nsfd_childb, veth, grchild_ip(nr), child_ip(nr))) return -1; child = fork(); if (child < 0) { pr_err("fork()"); return -1; } else if (child) { /* in parent - selftest */ return switch_ns(nsfd_parent); } if (close(test_desc_fd[1])) { pr_err("close()"); return -1; } /* child */ data_map = mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if (data_map == MAP_FAILED) { pr_err("mmap()"); return -1; } randomize_buffer(data_map, page_size); if (socketpair(PF_LOCAL, SOCK_SEQPACKET, 0, cmd_sock)) { pr_err("socketpair()"); return -1; } child = fork(); if (child < 0) { pr_err("fork()"); return -1; } else if (child) { if (close(cmd_sock[0])) { pr_err("close()"); return -1; } return child_f(nr, test_desc_fd[0], cmd_sock[1], data_map); } if (close(cmd_sock[1])) { pr_err("close()"); return -1; } return grand_child_f(nr, cmd_sock[0], data_map); } static void exit_usage(char **argv) { printk("Usage: %s [nr_process]", argv[0]); exit(KSFT_FAIL); } static int __write_desc(int test_desc_fd, struct xfrm_desc *desc) { ssize_t ret; ret = write(test_desc_fd, desc, sizeof(*desc)); if (ret == sizeof(*desc)) return 0; pr_err("Writing test's desc failed %ld", ret); return -1; } static int write_desc(int proto, int test_desc_fd, char *a, char *e, char *c, char *ae) { struct xfrm_desc desc = {}; desc.type = CREATE_TUNNEL; desc.proto = proto; if (a) strncpy(desc.a_algo, a, ALGO_LEN - 1); if (e) strncpy(desc.e_algo, e, ALGO_LEN - 1); if (c) strncpy(desc.c_algo, c, ALGO_LEN - 1); if (ae) strncpy(desc.ae_algo, ae, ALGO_LEN - 1); return __write_desc(test_desc_fd, &desc); } int proto_list[] = { IPPROTO_AH, IPPROTO_COMP, IPPROTO_ESP }; char *ah_list[] = { "digest_null", "hmac(md5)", "hmac(sha1)", "hmac(sha256)", "hmac(sha384)", "hmac(sha512)", "hmac(rmd160)", "xcbc(aes)", "cmac(aes)" }; char *comp_list[] = { "deflate", #if 0 /* No compression backend realization */ "lzs", "lzjh" #endif }; char *e_list[] = { "ecb(cipher_null)", "cbc(des)", "cbc(des3_ede)", "cbc(cast5)", "cbc(blowfish)", "cbc(aes)", "cbc(serpent)", "cbc(camellia)", "cbc(twofish)", "rfc3686(ctr(aes))" }; char *ae_list[] = { #if 0 /* not implemented */ "rfc4106(gcm(aes))", "rfc4309(ccm(aes))", "rfc4543(gcm(aes))", "rfc7539esp(chacha20,poly1305)" #endif }; const unsigned int proto_plan = ARRAY_SIZE(ah_list) + ARRAY_SIZE(comp_list) \ + (ARRAY_SIZE(ah_list) * ARRAY_SIZE(e_list)) \ + ARRAY_SIZE(ae_list); static int write_proto_plan(int fd, int proto) { unsigned int i; switch (proto) { case IPPROTO_AH: for (i = 0; i < ARRAY_SIZE(ah_list); i++) { if (write_desc(proto, fd, ah_list[i], 0, 0, 0)) return -1; } break; case IPPROTO_COMP: for (i = 0; i < ARRAY_SIZE(comp_list); i++) { if (write_desc(proto, fd, 0, 0, comp_list[i], 0)) return -1; } break; case IPPROTO_ESP: for (i = 0; i < ARRAY_SIZE(ah_list); i++) { int j; for (j = 0; j < ARRAY_SIZE(e_list); j++) { if (write_desc(proto, fd, ah_list[i], e_list[j], 0, 0)) return -1; } } for (i = 0; i < ARRAY_SIZE(ae_list); i++) { if (write_desc(proto, fd, 0, 0, 0, ae_list[i])) return -1; } break; default: printk("BUG: Specified unknown proto %d", proto); return -1; } return 0; } /* * Some structures in xfrm uapi header differ in size between * 64-bit and 32-bit ABI: * * 32-bit UABI | 64-bit UABI * -------------------------------------|------------------------------------- * sizeof(xfrm_usersa_info) = 220 | sizeof(xfrm_usersa_info) = 224 * sizeof(xfrm_userpolicy_info) = 164 | sizeof(xfrm_userpolicy_info) = 168 * sizeof(xfrm_userspi_info) = 228 | sizeof(xfrm_userspi_info) = 232 * sizeof(xfrm_user_acquire) = 276 | sizeof(xfrm_user_acquire) = 280 * sizeof(xfrm_user_expire) = 224 | sizeof(xfrm_user_expire) = 232 * sizeof(xfrm_user_polexpire) = 168 | sizeof(xfrm_user_polexpire) = 176 * * Check the affected by the UABI difference structures. * Also, check translation for xfrm_set_spdinfo: it has it's own attributes * which needs to be correctly copied, but not translated. */ const unsigned int compat_plan = 5; static int write_compat_struct_tests(int test_desc_fd) { struct xfrm_desc desc = {}; desc.type = ALLOCATE_SPI; desc.proto = IPPROTO_AH; strncpy(desc.a_algo, ah_list[0], ALGO_LEN - 1); if (__write_desc(test_desc_fd, &desc)) return -1; desc.type = MONITOR_ACQUIRE; if (__write_desc(test_desc_fd, &desc)) return -1; desc.type = EXPIRE_STATE; if (__write_desc(test_desc_fd, &desc)) return -1; desc.type = EXPIRE_POLICY; if (__write_desc(test_desc_fd, &desc)) return -1; desc.type = SPDINFO_ATTRS; if (__write_desc(test_desc_fd, &desc)) return -1; return 0; } static int write_test_plan(int test_desc_fd) { unsigned int i; pid_t child; child = fork(); if (child < 0) { pr_err("fork()"); return -1; } if (child) { if (close(test_desc_fd)) printk("close(): %m"); return 0; } if (write_compat_struct_tests(test_desc_fd)) exit(KSFT_FAIL); for (i = 0; i < ARRAY_SIZE(proto_list); i++) { if (write_proto_plan(test_desc_fd, proto_list[i])) exit(KSFT_FAIL); } exit(KSFT_PASS); } static int children_cleanup(void) { unsigned ret = KSFT_PASS; while (1) { int status; pid_t p = wait(&status); if ((p < 0) && errno == ECHILD) break; if (p < 0) { pr_err("wait()"); return KSFT_FAIL; } if (!WIFEXITED(status)) { ret = KSFT_FAIL; continue; } if (WEXITSTATUS(status) == KSFT_FAIL) ret = KSFT_FAIL; } return ret; } typedef void (*print_res)(const char *, ...); static int check_results(void) { struct test_result tr = {}; struct xfrm_desc *d = &tr.desc; int ret = KSFT_PASS; while (1) { ssize_t received = read(results_fd[0], &tr, sizeof(tr)); print_res result; if (received == 0) /* EOF */ break; if (received != sizeof(tr)) { pr_err("read() returned %zd", received); return KSFT_FAIL; } switch (tr.res) { case KSFT_PASS: result = ksft_test_result_pass; break; case KSFT_FAIL: default: result = ksft_test_result_fail; ret = KSFT_FAIL; } result(" %s: [%u, '%s', '%s', '%s', '%s', %u]\n", desc_name[d->type], (unsigned int)d->proto, d->a_algo, d->e_algo, d->c_algo, d->ae_algo, d->icv_len); } return ret; } int main(int argc, char **argv) { unsigned int nr_process = 1; int route_sock = -1, ret = KSFT_SKIP; int test_desc_fd[2]; uint32_t route_seq; unsigned int i; if (argc > 2) exit_usage(argv); if (argc > 1) { char *endptr; errno = 0; nr_process = strtol(argv[1], &endptr, 10); if ((errno == ERANGE && (nr_process == LONG_MAX || nr_process == LONG_MIN)) || (errno != 0 && nr_process == 0) || (endptr == argv[1]) || (*endptr != '\0')) { printk("Failed to parse [nr_process]"); exit_usage(argv); } if (nr_process > MAX_PROCESSES || !nr_process) { printk("nr_process should be between [1; %u]", MAX_PROCESSES); exit_usage(argv); } } srand(time(NULL)); page_size = sysconf(_SC_PAGESIZE); if (page_size < 1) ksft_exit_skip("sysconf(): %m\n"); if (pipe2(test_desc_fd, O_DIRECT) < 0) ksft_exit_skip("pipe(): %m\n"); if (pipe2(results_fd, O_DIRECT) < 0) ksft_exit_skip("pipe(): %m\n"); if (init_namespaces()) ksft_exit_skip("Failed to create namespaces\n"); if (netlink_sock(&route_sock, &route_seq, NETLINK_ROUTE)) ksft_exit_skip("Failed to open netlink route socket\n"); for (i = 0; i < nr_process; i++) { char veth[VETH_LEN]; snprintf(veth, VETH_LEN, VETH_FMT, i); if (veth_add(route_sock, route_seq++, veth, nsfd_childa, veth, nsfd_childb)) { close(route_sock); ksft_exit_fail_msg("Failed to create veth device"); } if (start_child(i, veth, test_desc_fd)) { close(route_sock); ksft_exit_fail_msg("Child %u failed to start", i); } } if (close(route_sock) || close(test_desc_fd[0]) || close(results_fd[1])) ksft_exit_fail_msg("close(): %m"); ksft_set_plan(proto_plan + compat_plan); if (write_test_plan(test_desc_fd[1])) ksft_exit_fail_msg("Failed to write test plan to pipe"); ret = check_results(); if (children_cleanup() == KSFT_FAIL) exit(KSFT_FAIL); exit(ret); }
linux-master
tools/testing/selftests/net/ipsec.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright Amazon.com Inc. or its affiliates. */ #define _GNU_SOURCE #include <sched.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/sysinfo.h> #include "../kselftest_harness.h" #define CLIENT_PER_SERVER 32 /* More sockets, more reliable */ #define NR_SERVER self->nproc #define NR_CLIENT (CLIENT_PER_SERVER * NR_SERVER) FIXTURE(so_incoming_cpu) { int nproc; int *servers; union { struct sockaddr addr; struct sockaddr_in in_addr; }; socklen_t addrlen; }; enum when_to_set { BEFORE_REUSEPORT, BEFORE_LISTEN, AFTER_LISTEN, AFTER_ALL_LISTEN, }; FIXTURE_VARIANT(so_incoming_cpu) { int when_to_set; }; FIXTURE_VARIANT_ADD(so_incoming_cpu, before_reuseport) { .when_to_set = BEFORE_REUSEPORT, }; FIXTURE_VARIANT_ADD(so_incoming_cpu, before_listen) { .when_to_set = BEFORE_LISTEN, }; FIXTURE_VARIANT_ADD(so_incoming_cpu, after_listen) { .when_to_set = AFTER_LISTEN, }; FIXTURE_VARIANT_ADD(so_incoming_cpu, after_all_listen) { .when_to_set = AFTER_ALL_LISTEN, }; FIXTURE_SETUP(so_incoming_cpu) { self->nproc = get_nprocs(); ASSERT_LE(2, self->nproc); self->servers = malloc(sizeof(int) * NR_SERVER); ASSERT_NE(self->servers, NULL); self->in_addr.sin_family = AF_INET; self->in_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); self->in_addr.sin_port = htons(0); self->addrlen = sizeof(struct sockaddr_in); } FIXTURE_TEARDOWN(so_incoming_cpu) { int i; for (i = 0; i < NR_SERVER; i++) close(self->servers[i]); free(self->servers); } void set_so_incoming_cpu(struct __test_metadata *_metadata, int fd, int cpu) { int ret; ret = setsockopt(fd, SOL_SOCKET, SO_INCOMING_CPU, &cpu, sizeof(int)); ASSERT_EQ(ret, 0); } int create_server(struct __test_metadata *_metadata, FIXTURE_DATA(so_incoming_cpu) *self, const FIXTURE_VARIANT(so_incoming_cpu) *variant, int cpu) { int fd, ret; fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); ASSERT_NE(fd, -1); if (variant->when_to_set == BEFORE_REUSEPORT) set_so_incoming_cpu(_metadata, fd, cpu); ret = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &(int){1}, sizeof(int)); ASSERT_EQ(ret, 0); ret = bind(fd, &self->addr, self->addrlen); ASSERT_EQ(ret, 0); if (variant->when_to_set == BEFORE_LISTEN) set_so_incoming_cpu(_metadata, fd, cpu); /* We don't use CLIENT_PER_SERVER here not to block * this test at connect() if SO_INCOMING_CPU is broken. */ ret = listen(fd, NR_CLIENT); ASSERT_EQ(ret, 0); if (variant->when_to_set == AFTER_LISTEN) set_so_incoming_cpu(_metadata, fd, cpu); return fd; } void create_servers(struct __test_metadata *_metadata, FIXTURE_DATA(so_incoming_cpu) *self, const FIXTURE_VARIANT(so_incoming_cpu) *variant) { int i, ret; for (i = 0; i < NR_SERVER; i++) { self->servers[i] = create_server(_metadata, self, variant, i); if (i == 0) { ret = getsockname(self->servers[i], &self->addr, &self->addrlen); ASSERT_EQ(ret, 0); } } if (variant->when_to_set == AFTER_ALL_LISTEN) { for (i = 0; i < NR_SERVER; i++) set_so_incoming_cpu(_metadata, self->servers[i], i); } } void create_clients(struct __test_metadata *_metadata, FIXTURE_DATA(so_incoming_cpu) *self) { cpu_set_t cpu_set; int i, j, fd, ret; for (i = 0; i < NR_SERVER; i++) { CPU_ZERO(&cpu_set); CPU_SET(i, &cpu_set); ASSERT_EQ(CPU_COUNT(&cpu_set), 1); ASSERT_NE(CPU_ISSET(i, &cpu_set), 0); /* Make sure SYN will be processed on the i-th CPU * and finally distributed to the i-th listener. */ ret = sched_setaffinity(0, sizeof(cpu_set), &cpu_set); ASSERT_EQ(ret, 0); for (j = 0; j < CLIENT_PER_SERVER; j++) { fd = socket(AF_INET, SOCK_STREAM, 0); ASSERT_NE(fd, -1); ret = connect(fd, &self->addr, self->addrlen); ASSERT_EQ(ret, 0); close(fd); } } } void verify_incoming_cpu(struct __test_metadata *_metadata, FIXTURE_DATA(so_incoming_cpu) *self) { int i, j, fd, cpu, ret, total = 0; socklen_t len = sizeof(int); for (i = 0; i < NR_SERVER; i++) { for (j = 0; j < CLIENT_PER_SERVER; j++) { /* If we see -EAGAIN here, SO_INCOMING_CPU is broken */ fd = accept(self->servers[i], &self->addr, &self->addrlen); ASSERT_NE(fd, -1); ret = getsockopt(fd, SOL_SOCKET, SO_INCOMING_CPU, &cpu, &len); ASSERT_EQ(ret, 0); ASSERT_EQ(cpu, i); close(fd); total++; } } ASSERT_EQ(total, NR_CLIENT); TH_LOG("SO_INCOMING_CPU is very likely to be " "working correctly with %d sockets.", total); } TEST_F(so_incoming_cpu, test1) { create_servers(_metadata, self, variant); create_clients(_metadata, self); verify_incoming_cpu(_metadata, self); } TEST_F(so_incoming_cpu, test2) { int server; create_servers(_metadata, self, variant); /* No CPU specified */ server = create_server(_metadata, self, variant, -1); close(server); create_clients(_metadata, self); verify_incoming_cpu(_metadata, self); } TEST_F(so_incoming_cpu, test3) { int server, client; create_servers(_metadata, self, variant); /* No CPU specified */ server = create_server(_metadata, self, variant, -1); create_clients(_metadata, self); /* Never receive any requests */ client = accept(server, &self->addr, &self->addrlen); ASSERT_EQ(client, -1); verify_incoming_cpu(_metadata, self); } TEST_HARNESS_MAIN
linux-master
tools/testing/selftests/net/so_incoming_cpu.c
// SPDX-License-Identifier: GPL-2.0 /* Test that sockets listening on a specific address are preferred * over sockets listening on addr_any. */ #define _GNU_SOURCE #include <arpa/inet.h> #include <errno.h> #include <error.h> #include <linux/dccp.h> #include <linux/in.h> #include <linux/unistd.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #ifndef SOL_DCCP #define SOL_DCCP 269 #endif static const char *IP4_ADDR = "127.0.0.1"; static const char *IP6_ADDR = "::1"; static const char *IP4_MAPPED6 = "::ffff:127.0.0.1"; static const int PORT = 8888; static void build_rcv_fd(int family, int proto, int *rcv_fds, int count, const char *addr_str) { struct sockaddr_in addr4 = {0}; struct sockaddr_in6 addr6 = {0}; struct sockaddr *addr; int opt, i, sz; memset(&addr, 0, sizeof(addr)); switch (family) { case AF_INET: addr4.sin_family = family; if (!addr_str) addr4.sin_addr.s_addr = htonl(INADDR_ANY); else if (!inet_pton(family, addr_str, &addr4.sin_addr.s_addr)) error(1, errno, "inet_pton failed: %s", addr_str); addr4.sin_port = htons(PORT); sz = sizeof(addr4); addr = (struct sockaddr *)&addr4; break; case AF_INET6: addr6.sin6_family = AF_INET6; if (!addr_str) addr6.sin6_addr = in6addr_any; else if (!inet_pton(family, addr_str, &addr6.sin6_addr)) error(1, errno, "inet_pton failed: %s", addr_str); addr6.sin6_port = htons(PORT); sz = sizeof(addr6); addr = (struct sockaddr *)&addr6; break; default: error(1, 0, "Unsupported family %d", family); /* clang does not recognize error() above as terminating * the program, so it complains that saddr, sz are * not initialized when this code path is taken. Silence it. */ return; } for (i = 0; i < count; ++i) { rcv_fds[i] = socket(family, proto, 0); if (rcv_fds[i] < 0) error(1, errno, "failed to create receive socket"); opt = 1; if (setsockopt(rcv_fds[i], SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT"); if (bind(rcv_fds[i], addr, sz)) error(1, errno, "failed to bind receive socket"); if (proto == SOCK_STREAM && listen(rcv_fds[i], 10)) error(1, errno, "tcp: failed to listen on receive port"); else if (proto == SOCK_DCCP) { if (setsockopt(rcv_fds[i], SOL_DCCP, DCCP_SOCKOPT_SERVICE, &(int) {htonl(42)}, sizeof(int))) error(1, errno, "failed to setsockopt"); if (listen(rcv_fds[i], 10)) error(1, errno, "dccp: failed to listen on receive port"); } } } static int connect_and_send(int family, int proto) { struct sockaddr_in saddr4 = {0}; struct sockaddr_in daddr4 = {0}; struct sockaddr_in6 saddr6 = {0}; struct sockaddr_in6 daddr6 = {0}; struct sockaddr *saddr, *daddr; int fd, sz; switch (family) { case AF_INET: saddr4.sin_family = AF_INET; saddr4.sin_addr.s_addr = htonl(INADDR_ANY); saddr4.sin_port = 0; daddr4.sin_family = AF_INET; if (!inet_pton(family, IP4_ADDR, &daddr4.sin_addr.s_addr)) error(1, errno, "inet_pton failed: %s", IP4_ADDR); daddr4.sin_port = htons(PORT); sz = sizeof(saddr4); saddr = (struct sockaddr *)&saddr4; daddr = (struct sockaddr *)&daddr4; break; case AF_INET6: saddr6.sin6_family = AF_INET6; saddr6.sin6_addr = in6addr_any; daddr6.sin6_family = AF_INET6; if (!inet_pton(family, IP6_ADDR, &daddr6.sin6_addr)) error(1, errno, "inet_pton failed: %s", IP6_ADDR); daddr6.sin6_port = htons(PORT); sz = sizeof(saddr6); saddr = (struct sockaddr *)&saddr6; daddr = (struct sockaddr *)&daddr6; break; default: error(1, 0, "Unsupported family %d", family); /* clang does not recognize error() above as terminating * the program, so it complains that saddr, daddr, sz are * not initialized when this code path is taken. Silence it. */ return -1; } fd = socket(family, proto, 0); if (fd < 0) error(1, errno, "failed to create send socket"); if (proto == SOCK_DCCP && setsockopt(fd, SOL_DCCP, DCCP_SOCKOPT_SERVICE, &(int){htonl(42)}, sizeof(int))) error(1, errno, "failed to setsockopt"); if (bind(fd, saddr, sz)) error(1, errno, "failed to bind send socket"); if (connect(fd, daddr, sz)) error(1, errno, "failed to connect send socket"); if (send(fd, "a", 1, 0) < 0) error(1, errno, "failed to send message"); return fd; } static int receive_once(int epfd, int proto) { struct epoll_event ev; int i, fd; char buf[8]; i = epoll_wait(epfd, &ev, 1, 3); if (i < 0) error(1, errno, "epoll_wait failed"); if (proto == SOCK_STREAM || proto == SOCK_DCCP) { fd = accept(ev.data.fd, NULL, NULL); if (fd < 0) error(1, errno, "failed to accept"); i = recv(fd, buf, sizeof(buf), 0); close(fd); } else { i = recv(ev.data.fd, buf, sizeof(buf), 0); } if (i < 0) error(1, errno, "failed to recv"); return ev.data.fd; } static void test(int *rcv_fds, int count, int family, int proto, int fd) { struct epoll_event ev; int epfd, i, send_fd, recv_fd; epfd = epoll_create(1); if (epfd < 0) error(1, errno, "failed to create epoll"); ev.events = EPOLLIN; for (i = 0; i < count; ++i) { ev.data.fd = rcv_fds[i]; if (epoll_ctl(epfd, EPOLL_CTL_ADD, rcv_fds[i], &ev)) error(1, errno, "failed to register sock epoll"); } send_fd = connect_and_send(family, proto); recv_fd = receive_once(epfd, proto); if (recv_fd != fd) error(1, 0, "received on an unexpected socket"); close(send_fd); close(epfd); } static void run_one_test(int fam_send, int fam_rcv, int proto, const char *addr_str) { /* Below we test that a socket listening on a specific address * is always selected in preference over a socket listening * on addr_any. Bugs where this is not the case often result * in sockets created first or last to get picked. So below * we make sure that there are always addr_any sockets created * before and after a specific socket is created. */ int rcv_fds[10], i; build_rcv_fd(AF_INET, proto, rcv_fds, 2, NULL); build_rcv_fd(AF_INET6, proto, rcv_fds + 2, 2, NULL); build_rcv_fd(fam_rcv, proto, rcv_fds + 4, 1, addr_str); build_rcv_fd(AF_INET, proto, rcv_fds + 5, 2, NULL); build_rcv_fd(AF_INET6, proto, rcv_fds + 7, 2, NULL); test(rcv_fds, 9, fam_send, proto, rcv_fds[4]); for (i = 0; i < 9; ++i) close(rcv_fds[i]); fprintf(stderr, "pass\n"); } static void test_proto(int proto, const char *proto_str) { if (proto == SOCK_DCCP) { int test_fd; test_fd = socket(AF_INET, proto, 0); if (test_fd < 0) { if (errno == ESOCKTNOSUPPORT) { fprintf(stderr, "DCCP not supported: skipping DCCP tests\n"); return; } else error(1, errno, "failed to create a DCCP socket"); } close(test_fd); } fprintf(stderr, "%s IPv4 ... ", proto_str); run_one_test(AF_INET, AF_INET, proto, IP4_ADDR); fprintf(stderr, "%s IPv6 ... ", proto_str); run_one_test(AF_INET6, AF_INET6, proto, IP6_ADDR); fprintf(stderr, "%s IPv4 mapped to IPv6 ... ", proto_str); run_one_test(AF_INET, AF_INET6, proto, IP4_MAPPED6); } int main(void) { test_proto(SOCK_DGRAM, "UDP"); test_proto(SOCK_STREAM, "TCP"); test_proto(SOCK_DCCP, "DCCP"); fprintf(stderr, "SUCCESS\n"); return 0; }
linux-master
tools/testing/selftests/net/reuseport_addr_any.c
// SPDX-License-Identifier: GPL-2.0 /* * Test functionality of BPF filters with SO_REUSEPORT. This program creates * an SO_REUSEPORT receiver group containing one socket per CPU core. It then * creates a BPF program that will select a socket from this group based * on the core id that receives the packet. The sending code artificially * moves itself to run on different core ids and sends one message from * each core. Since these packets are delivered over loopback, they should * arrive on the same core that sent them. The receiving code then ensures * that the packet was received on the socket for the corresponding core id. * This entire process is done for several different core id permutations * and for each IPv4/IPv6 and TCP/UDP combination. */ #define _GNU_SOURCE #include <arpa/inet.h> #include <errno.h> #include <error.h> #include <linux/filter.h> #include <linux/in.h> #include <linux/unistd.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> static const int PORT = 8888; static void build_rcv_group(int *rcv_fd, size_t len, int family, int proto) { struct sockaddr_storage addr; struct sockaddr_in *addr4; struct sockaddr_in6 *addr6; size_t i; int opt; switch (family) { case AF_INET: addr4 = (struct sockaddr_in *)&addr; addr4->sin_family = AF_INET; addr4->sin_addr.s_addr = htonl(INADDR_ANY); addr4->sin_port = htons(PORT); break; case AF_INET6: addr6 = (struct sockaddr_in6 *)&addr; addr6->sin6_family = AF_INET6; addr6->sin6_addr = in6addr_any; addr6->sin6_port = htons(PORT); break; default: error(1, 0, "Unsupported family %d", family); } for (i = 0; i < len; ++i) { rcv_fd[i] = socket(family, proto, 0); if (rcv_fd[i] < 0) error(1, errno, "failed to create receive socket"); opt = 1; if (setsockopt(rcv_fd[i], SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT"); if (bind(rcv_fd[i], (struct sockaddr *)&addr, sizeof(addr))) error(1, errno, "failed to bind receive socket"); if (proto == SOCK_STREAM && listen(rcv_fd[i], len * 10)) error(1, errno, "failed to listen on receive port"); } } static void attach_bpf(int fd) { struct sock_filter code[] = { /* A = raw_smp_processor_id() */ { BPF_LD | BPF_W | BPF_ABS, 0, 0, SKF_AD_OFF + SKF_AD_CPU }, /* return A */ { BPF_RET | BPF_A, 0, 0, 0 }, }; struct sock_fprog p = { .len = 2, .filter = code, }; if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_REUSEPORT_CBPF, &p, sizeof(p))) error(1, errno, "failed to set SO_ATTACH_REUSEPORT_CBPF"); } static void send_from_cpu(int cpu_id, int family, int proto) { struct sockaddr_storage saddr, daddr; struct sockaddr_in *saddr4, *daddr4; struct sockaddr_in6 *saddr6, *daddr6; cpu_set_t cpu_set; int fd; switch (family) { case AF_INET: saddr4 = (struct sockaddr_in *)&saddr; saddr4->sin_family = AF_INET; saddr4->sin_addr.s_addr = htonl(INADDR_ANY); saddr4->sin_port = 0; daddr4 = (struct sockaddr_in *)&daddr; daddr4->sin_family = AF_INET; daddr4->sin_addr.s_addr = htonl(INADDR_LOOPBACK); daddr4->sin_port = htons(PORT); break; case AF_INET6: saddr6 = (struct sockaddr_in6 *)&saddr; saddr6->sin6_family = AF_INET6; saddr6->sin6_addr = in6addr_any; saddr6->sin6_port = 0; daddr6 = (struct sockaddr_in6 *)&daddr; daddr6->sin6_family = AF_INET6; daddr6->sin6_addr = in6addr_loopback; daddr6->sin6_port = htons(PORT); break; default: error(1, 0, "Unsupported family %d", family); } memset(&cpu_set, 0, sizeof(cpu_set)); CPU_SET(cpu_id, &cpu_set); if (sched_setaffinity(0, sizeof(cpu_set), &cpu_set) < 0) error(1, errno, "failed to pin to cpu"); fd = socket(family, proto, 0); if (fd < 0) error(1, errno, "failed to create send socket"); if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr))) error(1, errno, "failed to bind send socket"); if (connect(fd, (struct sockaddr *)&daddr, sizeof(daddr))) error(1, errno, "failed to connect send socket"); if (send(fd, "a", 1, 0) < 0) error(1, errno, "failed to send message"); close(fd); } static void receive_on_cpu(int *rcv_fd, int len, int epfd, int cpu_id, int proto) { struct epoll_event ev; int i, fd; char buf[8]; i = epoll_wait(epfd, &ev, 1, -1); if (i < 0) error(1, errno, "epoll_wait failed"); if (proto == SOCK_STREAM) { fd = accept(ev.data.fd, NULL, NULL); if (fd < 0) error(1, errno, "failed to accept"); i = recv(fd, buf, sizeof(buf), 0); close(fd); } else { i = recv(ev.data.fd, buf, sizeof(buf), 0); } if (i < 0) error(1, errno, "failed to recv"); for (i = 0; i < len; ++i) if (ev.data.fd == rcv_fd[i]) break; if (i == len) error(1, 0, "failed to find socket"); fprintf(stderr, "send cpu %d, receive socket %d\n", cpu_id, i); if (cpu_id != i) error(1, 0, "cpu id/receive socket mismatch"); } static void test(int *rcv_fd, int len, int family, int proto) { struct epoll_event ev; int epfd, cpu; build_rcv_group(rcv_fd, len, family, proto); attach_bpf(rcv_fd[0]); epfd = epoll_create(1); if (epfd < 0) error(1, errno, "failed to create epoll"); for (cpu = 0; cpu < len; ++cpu) { ev.events = EPOLLIN; ev.data.fd = rcv_fd[cpu]; if (epoll_ctl(epfd, EPOLL_CTL_ADD, rcv_fd[cpu], &ev)) error(1, errno, "failed to register sock epoll"); } /* Forward iterate */ for (cpu = 0; cpu < len; ++cpu) { send_from_cpu(cpu, family, proto); receive_on_cpu(rcv_fd, len, epfd, cpu, proto); } /* Reverse iterate */ for (cpu = len - 1; cpu >= 0; --cpu) { send_from_cpu(cpu, family, proto); receive_on_cpu(rcv_fd, len, epfd, cpu, proto); } /* Even cores */ for (cpu = 0; cpu < len; cpu += 2) { send_from_cpu(cpu, family, proto); receive_on_cpu(rcv_fd, len, epfd, cpu, proto); } /* Odd cores */ for (cpu = 1; cpu < len; cpu += 2) { send_from_cpu(cpu, family, proto); receive_on_cpu(rcv_fd, len, epfd, cpu, proto); } close(epfd); for (cpu = 0; cpu < len; ++cpu) close(rcv_fd[cpu]); } int main(void) { int *rcv_fd, cpus; cpus = sysconf(_SC_NPROCESSORS_ONLN); if (cpus <= 0) error(1, errno, "failed counting cpus"); rcv_fd = calloc(cpus, sizeof(int)); if (!rcv_fd) error(1, 0, "failed to allocate array"); fprintf(stderr, "---- IPv4 UDP ----\n"); test(rcv_fd, cpus, AF_INET, SOCK_DGRAM); fprintf(stderr, "---- IPv6 UDP ----\n"); test(rcv_fd, cpus, AF_INET6, SOCK_DGRAM); fprintf(stderr, "---- IPv4 TCP ----\n"); test(rcv_fd, cpus, AF_INET, SOCK_STREAM); fprintf(stderr, "---- IPv6 TCP ----\n"); test(rcv_fd, cpus, AF_INET6, SOCK_STREAM); free(rcv_fd); fprintf(stderr, "SUCCESS\n"); return 0; }
linux-master
tools/testing/selftests/net/reuseport_bpf_cpu.c
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2018 Google Inc. * Author: Eric Dumazet ([email protected]) * * Reference program demonstrating tcp mmap() usage, * and SO_RCVLOWAT hints for receiver. * * Note : NIC with header split is needed to use mmap() on TCP : * Each incoming frame must be a multiple of PAGE_SIZE bytes of TCP payload. * * How to use on loopback interface : * * ifconfig lo mtu 61512 # 15*4096 + 40 (ipv6 header) + 32 (TCP with TS option header) * tcp_mmap -s -z & * tcp_mmap -H ::1 -z * * Or leave default lo mtu, but use -M option to set TCP_MAXSEG option to (4096 + 12) * (4096 : page size on x86, 12: TCP TS option length) * tcp_mmap -s -z -M $((4096+12)) & * tcp_mmap -H ::1 -z -M $((4096+12)) * * Note: -z option on sender uses MSG_ZEROCOPY, which forces a copy when packets go through loopback interface. * We might use sendfile() instead, but really this test program is about mmap(), for receivers ;) * * $ ./tcp_mmap -s & # Without mmap() * $ for i in {1..4}; do ./tcp_mmap -H ::1 -z ; done * received 32768 MB (0 % mmap'ed) in 14.1157 s, 19.4732 Gbit * cpu usage user:0.057 sys:7.815, 240.234 usec per MB, 65531 c-switches * received 32768 MB (0 % mmap'ed) in 14.6833 s, 18.7204 Gbit * cpu usage user:0.043 sys:8.103, 248.596 usec per MB, 65524 c-switches * received 32768 MB (0 % mmap'ed) in 11.143 s, 24.6682 Gbit * cpu usage user:0.044 sys:6.576, 202.026 usec per MB, 65519 c-switches * received 32768 MB (0 % mmap'ed) in 14.9056 s, 18.4413 Gbit * cpu usage user:0.036 sys:8.193, 251.129 usec per MB, 65530 c-switches * $ kill %1 # kill tcp_mmap server * * $ ./tcp_mmap -s -z & # With mmap() * $ for i in {1..4}; do ./tcp_mmap -H ::1 -z ; done * received 32768 MB (99.9939 % mmap'ed) in 6.73792 s, 40.7956 Gbit * cpu usage user:0.045 sys:2.827, 87.6465 usec per MB, 65532 c-switches * received 32768 MB (99.9939 % mmap'ed) in 7.26732 s, 37.8238 Gbit * cpu usage user:0.037 sys:3.087, 95.3369 usec per MB, 65532 c-switches * received 32768 MB (99.9939 % mmap'ed) in 7.61661 s, 36.0893 Gbit * cpu usage user:0.046 sys:3.559, 110.016 usec per MB, 65529 c-switches * received 32768 MB (99.9939 % mmap'ed) in 7.43764 s, 36.9577 Gbit * cpu usage user:0.035 sys:3.467, 106.873 usec per MB, 65530 c-switches */ #define _GNU_SOURCE #include <pthread.h> #include <sys/types.h> #include <fcntl.h> #include <error.h> #include <sys/socket.h> #include <sys/mman.h> #include <sys/resource.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <time.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <poll.h> #include <linux/tcp.h> #include <assert.h> #include <openssl/pem.h> #ifndef MSG_ZEROCOPY #define MSG_ZEROCOPY 0x4000000 #endif #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif #define FILE_SZ (1ULL << 35) static int cfg_family = AF_INET6; static socklen_t cfg_alen = sizeof(struct sockaddr_in6); static int cfg_port = 8787; static int rcvbuf; /* Default: autotuning. Can be set with -r <integer> option */ static int sndbuf; /* Default: autotuning. Can be set with -w <integer> option */ static int zflg; /* zero copy option. (MSG_ZEROCOPY for sender, mmap() for receiver */ static int xflg; /* hash received data (simple xor) (-h option) */ static int keepflag; /* -k option: receiver shall keep all received file in memory (no munmap() calls) */ static int integrity; /* -i option: sender and receiver compute sha256 over the data.*/ static size_t chunk_size = 512*1024; static size_t map_align; unsigned long htotal; unsigned int digest_len; static inline void prefetch(const void *x) { #if defined(__x86_64__) asm volatile("prefetcht0 %P0" : : "m" (*(const char *)x)); #endif } void hash_zone(void *zone, unsigned int length) { unsigned long temp = htotal; while (length >= 8*sizeof(long)) { prefetch(zone + 384); temp ^= *(unsigned long *)zone; temp ^= *(unsigned long *)(zone + sizeof(long)); temp ^= *(unsigned long *)(zone + 2*sizeof(long)); temp ^= *(unsigned long *)(zone + 3*sizeof(long)); temp ^= *(unsigned long *)(zone + 4*sizeof(long)); temp ^= *(unsigned long *)(zone + 5*sizeof(long)); temp ^= *(unsigned long *)(zone + 6*sizeof(long)); temp ^= *(unsigned long *)(zone + 7*sizeof(long)); zone += 8*sizeof(long); length -= 8*sizeof(long); } while (length >= 1) { temp ^= *(unsigned char *)zone; zone += 1; length--; } htotal = temp; } #define ALIGN_UP(x, align_to) (((x) + ((align_to)-1)) & ~((align_to)-1)) #define ALIGN_PTR_UP(p, ptr_align_to) ((typeof(p))ALIGN_UP((unsigned long)(p), ptr_align_to)) static void *mmap_large_buffer(size_t need, size_t *allocated) { void *buffer; size_t sz; /* Attempt to use huge pages if possible. */ sz = ALIGN_UP(need, map_align); buffer = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0); if (buffer == (void *)-1) { sz = need; buffer = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0); if (buffer != (void *)-1) fprintf(stderr, "MAP_HUGETLB attempt failed, look at /sys/kernel/mm/hugepages for optimal performance\n"); } *allocated = sz; return buffer; } static uint32_t tcp_info_get_rcv_mss(int fd) { socklen_t sz = sizeof(struct tcp_info); struct tcp_info info; if (getsockopt(fd, IPPROTO_TCP, TCP_INFO, &info, &sz)) { fprintf(stderr, "Error fetching TCP_INFO\n"); return 0; } return info.tcpi_rcv_mss; } void *child_thread(void *arg) { unsigned char digest[SHA256_DIGEST_LENGTH]; unsigned long total_mmap = 0, total = 0; struct tcp_zerocopy_receive zc; unsigned char *buffer = NULL; unsigned long delta_usec; EVP_MD_CTX *ctx = NULL; int flags = MAP_SHARED; struct timeval t0, t1; void *raddr = NULL; void *addr = NULL; double throughput; struct rusage ru; size_t buffer_sz; int lu, fd; fd = (int)(unsigned long)arg; gettimeofday(&t0, NULL); fcntl(fd, F_SETFL, O_NDELAY); buffer = mmap_large_buffer(chunk_size, &buffer_sz); if (buffer == (void *)-1) { perror("mmap"); goto error; } if (zflg) { raddr = mmap(NULL, chunk_size + map_align, PROT_READ, flags, fd, 0); if (raddr == (void *)-1) { perror("mmap"); zflg = 0; } else { addr = ALIGN_PTR_UP(raddr, map_align); } } if (integrity) { ctx = EVP_MD_CTX_new(); if (!ctx) { perror("cannot enable SHA computing"); goto error; } EVP_DigestInit_ex(ctx, EVP_sha256(), NULL); } while (1) { struct pollfd pfd = { .fd = fd, .events = POLLIN, }; int sub; poll(&pfd, 1, 10000); if (zflg) { socklen_t zc_len = sizeof(zc); int res; memset(&zc, 0, sizeof(zc)); zc.address = (__u64)((unsigned long)addr); zc.length = min(chunk_size, FILE_SZ - total); res = getsockopt(fd, IPPROTO_TCP, TCP_ZEROCOPY_RECEIVE, &zc, &zc_len); if (res == -1) break; if (zc.length) { assert(zc.length <= chunk_size); if (integrity) EVP_DigestUpdate(ctx, addr, zc.length); total_mmap += zc.length; if (xflg) hash_zone(addr, zc.length); /* It is more efficient to unmap the pages right now, * instead of doing this in next TCP_ZEROCOPY_RECEIVE. */ madvise(addr, zc.length, MADV_DONTNEED); total += zc.length; } if (zc.recv_skip_hint) { assert(zc.recv_skip_hint <= chunk_size); lu = read(fd, buffer, min(zc.recv_skip_hint, FILE_SZ - total)); if (lu > 0) { if (integrity) EVP_DigestUpdate(ctx, buffer, lu); if (xflg) hash_zone(buffer, lu); total += lu; } if (lu == 0) goto end; } continue; } sub = 0; while (sub < chunk_size) { lu = read(fd, buffer + sub, min(chunk_size - sub, FILE_SZ - total)); if (lu == 0) goto end; if (lu < 0) break; if (integrity) EVP_DigestUpdate(ctx, buffer + sub, lu); if (xflg) hash_zone(buffer + sub, lu); total += lu; sub += lu; } } end: gettimeofday(&t1, NULL); delta_usec = (t1.tv_sec - t0.tv_sec) * 1000000 + t1.tv_usec - t0.tv_usec; if (integrity) { fcntl(fd, F_SETFL, 0); EVP_DigestFinal_ex(ctx, digest, &digest_len); lu = read(fd, buffer, SHA256_DIGEST_LENGTH); if (lu != SHA256_DIGEST_LENGTH) perror("Error: Cannot read SHA256\n"); if (memcmp(digest, buffer, SHA256_DIGEST_LENGTH)) fprintf(stderr, "Error: SHA256 of the data is not right\n"); else printf("\nSHA256 is correct\n"); } throughput = 0; if (delta_usec) throughput = total * 8.0 / (double)delta_usec / 1000.0; getrusage(RUSAGE_THREAD, &ru); if (total > 1024*1024) { unsigned long total_usec; unsigned long mb = total >> 20; total_usec = 1000000*ru.ru_utime.tv_sec + ru.ru_utime.tv_usec + 1000000*ru.ru_stime.tv_sec + ru.ru_stime.tv_usec; printf("received %lg MB (%lg %% mmap'ed) in %lg s, %lg Gbit\n" " cpu usage user:%lg sys:%lg, %lg usec per MB, %lu c-switches, rcv_mss %u\n", total / (1024.0 * 1024.0), 100.0*total_mmap/total, (double)delta_usec / 1000000.0, throughput, (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000.0, (double)ru.ru_stime.tv_sec + (double)ru.ru_stime.tv_usec / 1000000.0, (double)total_usec/mb, ru.ru_nvcsw, tcp_info_get_rcv_mss(fd)); } error: munmap(buffer, buffer_sz); close(fd); if (zflg) munmap(raddr, chunk_size + map_align); pthread_exit(0); } static void apply_rcvsnd_buf(int fd) { if (rcvbuf && setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) == -1) { perror("setsockopt SO_RCVBUF"); } if (sndbuf && setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)) == -1) { perror("setsockopt SO_SNDBUF"); } } static void setup_sockaddr(int domain, const char *str_addr, struct sockaddr_storage *sockaddr) { struct sockaddr_in6 *addr6 = (void *) sockaddr; struct sockaddr_in *addr4 = (void *) sockaddr; switch (domain) { case PF_INET: memset(addr4, 0, sizeof(*addr4)); addr4->sin_family = AF_INET; addr4->sin_port = htons(cfg_port); if (str_addr && inet_pton(AF_INET, str_addr, &(addr4->sin_addr)) != 1) error(1, 0, "ipv4 parse error: %s", str_addr); break; case PF_INET6: memset(addr6, 0, sizeof(*addr6)); addr6->sin6_family = AF_INET6; addr6->sin6_port = htons(cfg_port); if (str_addr && inet_pton(AF_INET6, str_addr, &(addr6->sin6_addr)) != 1) error(1, 0, "ipv6 parse error: %s", str_addr); break; default: error(1, 0, "illegal domain"); } } static void do_accept(int fdlisten) { pthread_attr_t attr; int rcvlowat; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); rcvlowat = chunk_size; if (setsockopt(fdlisten, SOL_SOCKET, SO_RCVLOWAT, &rcvlowat, sizeof(rcvlowat)) == -1) { perror("setsockopt SO_RCVLOWAT"); } apply_rcvsnd_buf(fdlisten); while (1) { struct sockaddr_in addr; socklen_t addrlen = sizeof(addr); pthread_t th; int fd, res; fd = accept(fdlisten, (struct sockaddr *)&addr, &addrlen); if (fd == -1) { perror("accept"); continue; } res = pthread_create(&th, &attr, child_thread, (void *)(unsigned long)fd); if (res) { errno = res; perror("pthread_create"); close(fd); } } } /* Each thread should reserve a big enough vma to avoid * spinlock collisions in ptl locks. * This size is 2MB on x86_64, and is exported in /proc/meminfo. */ static unsigned long default_huge_page_size(void) { FILE *f = fopen("/proc/meminfo", "r"); unsigned long hps = 0; size_t linelen = 0; char *line = NULL; if (!f) return 0; while (getline(&line, &linelen, f) > 0) { if (sscanf(line, "Hugepagesize: %lu kB", &hps) == 1) { hps <<= 10; break; } } free(line); fclose(f); return hps; } static void randomize(void *target, size_t count) { static int urandom = -1; ssize_t got; urandom = open("/dev/urandom", O_RDONLY); if (urandom < 0) { perror("open /dev/urandom"); exit(1); } got = read(urandom, target, count); if (got != count) { perror("read /dev/urandom"); exit(1); } } int main(int argc, char *argv[]) { unsigned char digest[SHA256_DIGEST_LENGTH]; struct sockaddr_storage listenaddr, addr; unsigned int max_pacing_rate = 0; EVP_MD_CTX *ctx = NULL; unsigned char *buffer; uint64_t total = 0; char *host = NULL; int fd, c, on = 1; size_t buffer_sz; int sflg = 0; int mss = 0; while ((c = getopt(argc, argv, "46p:svr:w:H:zxkP:M:C:a:i")) != -1) { switch (c) { case '4': cfg_family = PF_INET; cfg_alen = sizeof(struct sockaddr_in); break; case '6': cfg_family = PF_INET6; cfg_alen = sizeof(struct sockaddr_in6); break; case 'p': cfg_port = atoi(optarg); break; case 'H': host = optarg; break; case 's': /* server : listen for incoming connections */ sflg++; break; case 'r': rcvbuf = atoi(optarg); break; case 'w': sndbuf = atoi(optarg); break; case 'z': zflg = 1; break; case 'M': mss = atoi(optarg); break; case 'x': xflg = 1; break; case 'k': keepflag = 1; break; case 'P': max_pacing_rate = atoi(optarg) ; break; case 'C': chunk_size = atol(optarg); break; case 'a': map_align = atol(optarg); break; case 'i': integrity = 1; break; default: exit(1); } } if (!map_align) { map_align = default_huge_page_size(); /* if really /proc/meminfo is not helping, * we use the default x86_64 hugepagesize. */ if (!map_align) map_align = 2*1024*1024; } if (sflg) { int fdlisten = socket(cfg_family, SOCK_STREAM, 0); if (fdlisten == -1) { perror("socket"); exit(1); } apply_rcvsnd_buf(fdlisten); setsockopt(fdlisten, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); setup_sockaddr(cfg_family, host, &listenaddr); if (mss && setsockopt(fdlisten, IPPROTO_TCP, TCP_MAXSEG, &mss, sizeof(mss)) == -1) { perror("setsockopt TCP_MAXSEG"); exit(1); } if (bind(fdlisten, (const struct sockaddr *)&listenaddr, cfg_alen) == -1) { perror("bind"); exit(1); } if (listen(fdlisten, 128) == -1) { perror("listen"); exit(1); } do_accept(fdlisten); } buffer = mmap_large_buffer(chunk_size, &buffer_sz); if (buffer == (unsigned char *)-1) { perror("mmap"); exit(1); } fd = socket(cfg_family, SOCK_STREAM, 0); if (fd == -1) { perror("socket"); exit(1); } apply_rcvsnd_buf(fd); setup_sockaddr(cfg_family, host, &addr); if (mss && setsockopt(fd, IPPROTO_TCP, TCP_MAXSEG, &mss, sizeof(mss)) == -1) { perror("setsockopt TCP_MAXSEG"); exit(1); } if (connect(fd, (const struct sockaddr *)&addr, cfg_alen) == -1) { perror("connect"); exit(1); } if (max_pacing_rate && setsockopt(fd, SOL_SOCKET, SO_MAX_PACING_RATE, &max_pacing_rate, sizeof(max_pacing_rate)) == -1) perror("setsockopt SO_MAX_PACING_RATE"); if (zflg && setsockopt(fd, SOL_SOCKET, SO_ZEROCOPY, &on, sizeof(on)) == -1) { perror("setsockopt SO_ZEROCOPY, (-z option disabled)"); zflg = 0; } if (integrity) { randomize(buffer, buffer_sz); ctx = EVP_MD_CTX_new(); if (!ctx) { perror("cannot enable SHA computing"); exit(1); } EVP_DigestInit_ex(ctx, EVP_sha256(), NULL); } while (total < FILE_SZ) { size_t offset = total % chunk_size; int64_t wr = FILE_SZ - total; if (wr > chunk_size - offset) wr = chunk_size - offset; /* Note : we just want to fill the pipe with random bytes */ wr = send(fd, buffer + offset, (size_t)wr, zflg ? MSG_ZEROCOPY : 0); if (wr <= 0) break; if (integrity) EVP_DigestUpdate(ctx, buffer + offset, wr); total += wr; } if (integrity && total == FILE_SZ) { EVP_DigestFinal_ex(ctx, digest, &digest_len); send(fd, digest, (size_t)SHA256_DIGEST_LENGTH, 0); } close(fd); munmap(buffer, buffer_sz); return 0; }
linux-master
tools/testing/selftests/net/tcp_mmap.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright Amazon.com Inc. or its affiliates. */ #include <sys/socket.h> #include <netinet/in.h> #include "../kselftest_harness.h" FIXTURE(bind_timewait) { struct sockaddr_in addr; socklen_t addrlen; }; FIXTURE_VARIANT(bind_timewait) { __u32 addr_const; }; FIXTURE_VARIANT_ADD(bind_timewait, localhost) { .addr_const = INADDR_LOOPBACK }; FIXTURE_VARIANT_ADD(bind_timewait, addrany) { .addr_const = INADDR_ANY }; FIXTURE_SETUP(bind_timewait) { self->addr.sin_family = AF_INET; self->addr.sin_port = 0; self->addr.sin_addr.s_addr = htonl(variant->addr_const); self->addrlen = sizeof(self->addr); } FIXTURE_TEARDOWN(bind_timewait) { } void create_timewait_socket(struct __test_metadata *_metadata, FIXTURE_DATA(bind_timewait) *self) { int server_fd, client_fd, child_fd, ret; struct sockaddr_in addr; socklen_t addrlen; server_fd = socket(AF_INET, SOCK_STREAM, 0); ASSERT_GT(server_fd, 0); ret = bind(server_fd, (struct sockaddr *)&self->addr, self->addrlen); ASSERT_EQ(ret, 0); ret = listen(server_fd, 1); ASSERT_EQ(ret, 0); ret = getsockname(server_fd, (struct sockaddr *)&self->addr, &self->addrlen); ASSERT_EQ(ret, 0); client_fd = socket(AF_INET, SOCK_STREAM, 0); ASSERT_GT(client_fd, 0); ret = connect(client_fd, (struct sockaddr *)&self->addr, self->addrlen); ASSERT_EQ(ret, 0); addrlen = sizeof(addr); child_fd = accept(server_fd, (struct sockaddr *)&addr, &addrlen); ASSERT_GT(child_fd, 0); close(child_fd); close(client_fd); close(server_fd); } TEST_F(bind_timewait, 1) { int fd, ret; create_timewait_socket(_metadata, self); fd = socket(AF_INET, SOCK_STREAM, 0); ASSERT_GT(fd, 0); ret = bind(fd, (struct sockaddr *)&self->addr, self->addrlen); ASSERT_EQ(ret, -1); ASSERT_EQ(errno, EADDRINUSE); close(fd); } TEST_HARNESS_MAIN
linux-master
tools/testing/selftests/net/bind_timewait.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright Amazon.com Inc. or its affiliates. */ #include <sys/socket.h> #include <netinet/in.h> #include "../kselftest_harness.h" struct in6_addr in6addr_v4mapped_any = { .s6_addr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 0, 0, 0, 0 } }; struct in6_addr in6addr_v4mapped_loopback = { .s6_addr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 0, 0, 1 } }; FIXTURE(bind_wildcard) { struct sockaddr_in addr4; struct sockaddr_in6 addr6; }; FIXTURE_VARIANT(bind_wildcard) { const __u32 addr4_const; const struct in6_addr *addr6_const; int expected_errno; }; FIXTURE_VARIANT_ADD(bind_wildcard, v4_any_v6_any) { .addr4_const = INADDR_ANY, .addr6_const = &in6addr_any, .expected_errno = EADDRINUSE, }; FIXTURE_VARIANT_ADD(bind_wildcard, v4_any_v6_local) { .addr4_const = INADDR_ANY, .addr6_const = &in6addr_loopback, .expected_errno = 0, }; FIXTURE_VARIANT_ADD(bind_wildcard, v4_any_v6_v4mapped_any) { .addr4_const = INADDR_ANY, .addr6_const = &in6addr_v4mapped_any, .expected_errno = EADDRINUSE, }; FIXTURE_VARIANT_ADD(bind_wildcard, v4_any_v6_v4mapped_local) { .addr4_const = INADDR_ANY, .addr6_const = &in6addr_v4mapped_loopback, .expected_errno = EADDRINUSE, }; FIXTURE_VARIANT_ADD(bind_wildcard, v4_local_v6_any) { .addr4_const = INADDR_LOOPBACK, .addr6_const = &in6addr_any, .expected_errno = EADDRINUSE, }; FIXTURE_VARIANT_ADD(bind_wildcard, v4_local_v6_local) { .addr4_const = INADDR_LOOPBACK, .addr6_const = &in6addr_loopback, .expected_errno = 0, }; FIXTURE_VARIANT_ADD(bind_wildcard, v4_local_v6_v4mapped_any) { .addr4_const = INADDR_LOOPBACK, .addr6_const = &in6addr_v4mapped_any, .expected_errno = EADDRINUSE, }; FIXTURE_VARIANT_ADD(bind_wildcard, v4_local_v6_v4mapped_local) { .addr4_const = INADDR_LOOPBACK, .addr6_const = &in6addr_v4mapped_loopback, .expected_errno = EADDRINUSE, }; FIXTURE_SETUP(bind_wildcard) { self->addr4.sin_family = AF_INET; self->addr4.sin_port = htons(0); self->addr4.sin_addr.s_addr = htonl(variant->addr4_const); self->addr6.sin6_family = AF_INET6; self->addr6.sin6_port = htons(0); self->addr6.sin6_addr = *variant->addr6_const; } FIXTURE_TEARDOWN(bind_wildcard) { } void bind_sockets(struct __test_metadata *_metadata, FIXTURE_DATA(bind_wildcard) *self, int expected_errno, struct sockaddr *addr1, socklen_t addrlen1, struct sockaddr *addr2, socklen_t addrlen2) { int fd[2]; int ret; fd[0] = socket(addr1->sa_family, SOCK_STREAM, 0); ASSERT_GT(fd[0], 0); ret = bind(fd[0], addr1, addrlen1); ASSERT_EQ(ret, 0); ret = getsockname(fd[0], addr1, &addrlen1); ASSERT_EQ(ret, 0); ((struct sockaddr_in *)addr2)->sin_port = ((struct sockaddr_in *)addr1)->sin_port; fd[1] = socket(addr2->sa_family, SOCK_STREAM, 0); ASSERT_GT(fd[1], 0); ret = bind(fd[1], addr2, addrlen2); if (expected_errno) { ASSERT_EQ(ret, -1); ASSERT_EQ(errno, expected_errno); } else { ASSERT_EQ(ret, 0); } close(fd[1]); close(fd[0]); } TEST_F(bind_wildcard, v4_v6) { bind_sockets(_metadata, self, variant->expected_errno, (struct sockaddr *)&self->addr4, sizeof(self->addr4), (struct sockaddr *)&self->addr6, sizeof(self->addr6)); } TEST_F(bind_wildcard, v6_v4) { bind_sockets(_metadata, self, variant->expected_errno, (struct sockaddr *)&self->addr6, sizeof(self->addr6), (struct sockaddr *)&self->addr4, sizeof(self->addr4)); } TEST_HARNESS_MAIN
linux-master
tools/testing/selftests/net/bind_wildcard.c
/* * Test for the regression introduced by * * b9470c27607b ("inet: kill smallest_size and smallest_port") * * If we open an ipv4 socket on a port with reuseaddr we shouldn't reset the tb * when we open the ipv6 conterpart, which is what was happening previously. */ #include <errno.h> #include <error.h> #include <arpa/inet.h> #include <netinet/in.h> #include <stdbool.h> #include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #define PORT 9999 int open_port(int ipv6, int any) { int fd = -1; int reuseaddr = 1; int v6only = 1; int addrlen; int ret = -1; struct sockaddr *addr; int family = ipv6 ? AF_INET6 : AF_INET; struct sockaddr_in6 addr6 = { .sin6_family = AF_INET6, .sin6_port = htons(PORT), .sin6_addr = in6addr_any }; struct sockaddr_in addr4 = { .sin_family = AF_INET, .sin_port = htons(PORT), .sin_addr.s_addr = any ? htonl(INADDR_ANY) : inet_addr("127.0.0.1"), }; if (ipv6) { addr = (struct sockaddr*)&addr6; addrlen = sizeof(addr6); } else { addr = (struct sockaddr*)&addr4; addrlen = sizeof(addr4); } if ((fd = socket(family, SOCK_STREAM, IPPROTO_TCP)) < 0) { perror("socket"); goto out; } if (ipv6 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&v6only, sizeof(v6only)) < 0) { perror("setsockopt IPV6_V6ONLY"); goto out; } if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)) < 0) { perror("setsockopt SO_REUSEADDR"); goto out; } if (bind(fd, addr, addrlen) < 0) { perror("bind"); goto out; } if (any) return fd; if (listen(fd, 1) < 0) { perror("listen"); goto out; } return fd; out: close(fd); return ret; } int main(void) { int listenfd; int fd1, fd2; fprintf(stderr, "Opening 127.0.0.1:%d\n", PORT); listenfd = open_port(0, 0); if (listenfd < 0) error(1, errno, "Couldn't open listen socket"); fprintf(stderr, "Opening INADDR_ANY:%d\n", PORT); fd1 = open_port(0, 1); if (fd1 >= 0) error(1, 0, "Was allowed to create an ipv4 reuseport on a already bound non-reuseport socket"); fprintf(stderr, "Opening in6addr_any:%d\n", PORT); fd1 = open_port(1, 1); if (fd1 < 0) error(1, errno, "Couldn't open ipv6 reuseport"); fprintf(stderr, "Opening INADDR_ANY:%d\n", PORT); fd2 = open_port(0, 1); if (fd2 >= 0) error(1, 0, "Was allowed to create an ipv4 reuseport on a already bound non-reuseport socket"); close(fd1); fprintf(stderr, "Opening INADDR_ANY:%d after closing ipv6 socket\n", PORT); fd1 = open_port(0, 1); if (fd1 >= 0) error(1, 0, "Was allowed to create an ipv4 reuseport on an already bound non-reuseport socket with no ipv6"); fprintf(stderr, "Success"); return 0; }
linux-master
tools/testing/selftests/net/reuseaddr_conflict.c
// SPDX-License-Identifier: GPL-2.0 /* Test IPV6_FLOWINFO_MGR */ #define _GNU_SOURCE #include <arpa/inet.h> #include <error.h> #include <errno.h> #include <limits.h> #include <linux/in6.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> /* uapi/glibc weirdness may leave this undefined */ #ifndef IPV6_FLOWLABEL_MGR #define IPV6_FLOWLABEL_MGR 32 #endif /* from net/ipv6/ip6_flowlabel.c */ #define FL_MIN_LINGER 6 #define explain(x) \ do { if (cfg_verbose) fprintf(stderr, " " x "\n"); } while (0) #define __expect(x) \ do { \ if (!(x)) \ fprintf(stderr, "[OK] " #x "\n"); \ else \ error(1, 0, "[ERR] " #x " (line %d)", __LINE__); \ } while (0) #define expect_pass(x) __expect(x) #define expect_fail(x) __expect(!(x)) static bool cfg_long_running; static bool cfg_verbose; static int flowlabel_get(int fd, uint32_t label, uint8_t share, uint16_t flags) { struct in6_flowlabel_req req = { .flr_action = IPV6_FL_A_GET, .flr_label = htonl(label), .flr_flags = flags, .flr_share = share, }; /* do not pass IPV6_ADDR_ANY or IPV6_ADDR_MAPPED */ req.flr_dst.s6_addr[0] = 0xfd; req.flr_dst.s6_addr[15] = 0x1; return setsockopt(fd, SOL_IPV6, IPV6_FLOWLABEL_MGR, &req, sizeof(req)); } static int flowlabel_put(int fd, uint32_t label) { struct in6_flowlabel_req req = { .flr_action = IPV6_FL_A_PUT, .flr_label = htonl(label), }; return setsockopt(fd, SOL_IPV6, IPV6_FLOWLABEL_MGR, &req, sizeof(req)); } static void run_tests(int fd) { int wstatus; pid_t pid; explain("cannot get non-existent label"); expect_fail(flowlabel_get(fd, 1, IPV6_FL_S_ANY, 0)); explain("cannot put non-existent label"); expect_fail(flowlabel_put(fd, 1)); explain("cannot create label greater than 20 bits"); expect_fail(flowlabel_get(fd, 0x1FFFFF, IPV6_FL_S_ANY, IPV6_FL_F_CREATE)); explain("create a new label (FL_F_CREATE)"); expect_pass(flowlabel_get(fd, 1, IPV6_FL_S_ANY, IPV6_FL_F_CREATE)); explain("can get the label (without FL_F_CREATE)"); expect_pass(flowlabel_get(fd, 1, IPV6_FL_S_ANY, 0)); explain("can get it again with create flag set, too"); expect_pass(flowlabel_get(fd, 1, IPV6_FL_S_ANY, IPV6_FL_F_CREATE)); explain("cannot get it again with the exclusive (FL_FL_EXCL) flag"); expect_fail(flowlabel_get(fd, 1, IPV6_FL_S_ANY, IPV6_FL_F_CREATE | IPV6_FL_F_EXCL)); explain("can now put exactly three references"); expect_pass(flowlabel_put(fd, 1)); expect_pass(flowlabel_put(fd, 1)); expect_pass(flowlabel_put(fd, 1)); expect_fail(flowlabel_put(fd, 1)); explain("create a new exclusive label (FL_S_EXCL)"); expect_pass(flowlabel_get(fd, 2, IPV6_FL_S_EXCL, IPV6_FL_F_CREATE)); explain("cannot get it again in non-exclusive mode"); expect_fail(flowlabel_get(fd, 2, IPV6_FL_S_ANY, IPV6_FL_F_CREATE)); explain("cannot get it again in exclusive mode either"); expect_fail(flowlabel_get(fd, 2, IPV6_FL_S_EXCL, IPV6_FL_F_CREATE)); expect_pass(flowlabel_put(fd, 2)); if (cfg_long_running) { explain("cannot reuse the label, due to linger"); expect_fail(flowlabel_get(fd, 2, IPV6_FL_S_ANY, IPV6_FL_F_CREATE)); explain("after sleep, can reuse"); sleep(FL_MIN_LINGER * 2 + 1); expect_pass(flowlabel_get(fd, 2, IPV6_FL_S_ANY, IPV6_FL_F_CREATE)); } explain("create a new user-private label (FL_S_USER)"); expect_pass(flowlabel_get(fd, 3, IPV6_FL_S_USER, IPV6_FL_F_CREATE)); explain("cannot get it again in non-exclusive mode"); expect_fail(flowlabel_get(fd, 3, IPV6_FL_S_ANY, 0)); explain("cannot get it again in exclusive mode"); expect_fail(flowlabel_get(fd, 3, IPV6_FL_S_EXCL, 0)); explain("can get it again in user mode"); expect_pass(flowlabel_get(fd, 3, IPV6_FL_S_USER, 0)); explain("child process can get it too, but not after setuid(nobody)"); pid = fork(); if (pid == -1) error(1, errno, "fork"); if (!pid) { expect_pass(flowlabel_get(fd, 3, IPV6_FL_S_USER, 0)); if (setuid(USHRT_MAX)) fprintf(stderr, "[INFO] skip setuid child test\n"); else expect_fail(flowlabel_get(fd, 3, IPV6_FL_S_USER, 0)); exit(0); } if (wait(&wstatus) == -1) error(1, errno, "wait"); if (!WIFEXITED(wstatus) || WEXITSTATUS(wstatus) != 0) error(1, errno, "wait: unexpected child result"); explain("create a new process-private label (FL_S_PROCESS)"); expect_pass(flowlabel_get(fd, 4, IPV6_FL_S_PROCESS, IPV6_FL_F_CREATE)); explain("can get it again"); expect_pass(flowlabel_get(fd, 4, IPV6_FL_S_PROCESS, 0)); explain("child process cannot can get it"); pid = fork(); if (pid == -1) error(1, errno, "fork"); if (!pid) { expect_fail(flowlabel_get(fd, 4, IPV6_FL_S_PROCESS, 0)); exit(0); } if (wait(&wstatus) == -1) error(1, errno, "wait"); if (!WIFEXITED(wstatus) || WEXITSTATUS(wstatus) != 0) error(1, errno, "wait: unexpected child result"); } static void parse_opts(int argc, char **argv) { int c; while ((c = getopt(argc, argv, "lv")) != -1) { switch (c) { case 'l': cfg_long_running = true; break; case 'v': cfg_verbose = true; break; default: error(1, 0, "%s: parse error", argv[0]); } } } int main(int argc, char **argv) { int fd; parse_opts(argc, argv); fd = socket(PF_INET6, SOCK_DGRAM, 0); if (fd == -1) error(1, errno, "socket"); run_tests(fd); if (close(fd)) error(1, errno, "close"); return 0; }
linux-master
tools/testing/selftests/net/ipv6_flowlabel_mgr.c
/* Evaluate MSG_ZEROCOPY * * Send traffic between two processes over one of the supported * protocols and modes: * * PF_INET/PF_INET6 * - SOCK_STREAM * - SOCK_DGRAM * - SOCK_DGRAM with UDP_CORK * - SOCK_RAW * - SOCK_RAW with IP_HDRINCL * * PF_PACKET * - SOCK_DGRAM * - SOCK_RAW * * PF_RDS * - SOCK_SEQPACKET * * Start this program on two connected hosts, one in send mode and * the other with option '-r' to put it in receiver mode. * * If zerocopy mode ('-z') is enabled, the sender will verify that * the kernel queues completions on the error queue for all zerocopy * transfers. */ #define _GNU_SOURCE #include <arpa/inet.h> #include <error.h> #include <errno.h> #include <limits.h> #include <linux/errqueue.h> #include <linux/if_packet.h> #include <linux/ipv6.h> #include <linux/socket.h> #include <linux/sockios.h> #include <net/ethernet.h> #include <net/if.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <poll.h> #include <sched.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <linux/rds.h> #ifndef SO_EE_ORIGIN_ZEROCOPY #define SO_EE_ORIGIN_ZEROCOPY 5 #endif #ifndef SO_ZEROCOPY #define SO_ZEROCOPY 60 #endif #ifndef SO_EE_CODE_ZEROCOPY_COPIED #define SO_EE_CODE_ZEROCOPY_COPIED 1 #endif #ifndef MSG_ZEROCOPY #define MSG_ZEROCOPY 0x4000000 #endif static int cfg_cork; static bool cfg_cork_mixed; static int cfg_cpu = -1; /* default: pin to last cpu */ static int cfg_family = PF_UNSPEC; static int cfg_ifindex = 1; static int cfg_payload_len; static int cfg_port = 8000; static bool cfg_rx; static int cfg_runtime_ms = 4200; static int cfg_verbose; static int cfg_waittime_ms = 500; static bool cfg_zerocopy; static socklen_t cfg_alen; static struct sockaddr_storage cfg_dst_addr; static struct sockaddr_storage cfg_src_addr; static char payload[IP_MAXPACKET]; static long packets, bytes, completions, expected_completions; static int zerocopied = -1; static uint32_t next_completion; static unsigned long gettimeofday_ms(void) { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); } static uint16_t get_ip_csum(const uint16_t *start, int num_words) { unsigned long sum = 0; int i; for (i = 0; i < num_words; i++) sum += start[i]; while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16); return ~sum; } static int do_setcpu(int cpu) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(cpu, &mask); if (sched_setaffinity(0, sizeof(mask), &mask)) fprintf(stderr, "cpu: unable to pin, may increase variance.\n"); else if (cfg_verbose) fprintf(stderr, "cpu: %u\n", cpu); return 0; } static void do_setsockopt(int fd, int level, int optname, int val) { if (setsockopt(fd, level, optname, &val, sizeof(val))) error(1, errno, "setsockopt %d.%d: %d", level, optname, val); } static int do_poll(int fd, int events) { struct pollfd pfd; int ret; pfd.events = events; pfd.revents = 0; pfd.fd = fd; ret = poll(&pfd, 1, cfg_waittime_ms); if (ret == -1) error(1, errno, "poll"); return ret && (pfd.revents & events); } static int do_accept(int fd) { int fda = fd; fd = accept(fda, NULL, NULL); if (fd == -1) error(1, errno, "accept"); if (close(fda)) error(1, errno, "close listen sock"); return fd; } static void add_zcopy_cookie(struct msghdr *msg, uint32_t cookie) { struct cmsghdr *cm; if (!msg->msg_control) error(1, errno, "NULL cookie"); cm = (void *)msg->msg_control; cm->cmsg_len = CMSG_LEN(sizeof(cookie)); cm->cmsg_level = SOL_RDS; cm->cmsg_type = RDS_CMSG_ZCOPY_COOKIE; memcpy(CMSG_DATA(cm), &cookie, sizeof(cookie)); } static bool do_sendmsg(int fd, struct msghdr *msg, bool do_zerocopy, int domain) { int ret, len, i, flags; static uint32_t cookie; char ckbuf[CMSG_SPACE(sizeof(cookie))]; len = 0; for (i = 0; i < msg->msg_iovlen; i++) len += msg->msg_iov[i].iov_len; flags = MSG_DONTWAIT; if (do_zerocopy) { flags |= MSG_ZEROCOPY; if (domain == PF_RDS) { memset(&msg->msg_control, 0, sizeof(msg->msg_control)); msg->msg_controllen = CMSG_SPACE(sizeof(cookie)); msg->msg_control = (struct cmsghdr *)ckbuf; add_zcopy_cookie(msg, ++cookie); } } ret = sendmsg(fd, msg, flags); if (ret == -1 && errno == EAGAIN) return false; if (ret == -1) error(1, errno, "send"); if (cfg_verbose && ret != len) fprintf(stderr, "send: ret=%u != %u\n", ret, len); if (len) { packets++; bytes += ret; if (do_zerocopy && ret) expected_completions++; } if (do_zerocopy && domain == PF_RDS) { msg->msg_control = NULL; msg->msg_controllen = 0; } return true; } static void do_sendmsg_corked(int fd, struct msghdr *msg) { bool do_zerocopy = cfg_zerocopy; int i, payload_len, extra_len; /* split up the packet. for non-multiple, make first buffer longer */ payload_len = cfg_payload_len / cfg_cork; extra_len = cfg_payload_len - (cfg_cork * payload_len); do_setsockopt(fd, IPPROTO_UDP, UDP_CORK, 1); for (i = 0; i < cfg_cork; i++) { /* in mixed-frags mode, alternate zerocopy and copy frags * start with non-zerocopy, to ensure attach later works */ if (cfg_cork_mixed) do_zerocopy = (i & 1); msg->msg_iov[0].iov_len = payload_len + extra_len; extra_len = 0; do_sendmsg(fd, msg, do_zerocopy, (cfg_dst_addr.ss_family == AF_INET ? PF_INET : PF_INET6)); } do_setsockopt(fd, IPPROTO_UDP, UDP_CORK, 0); } static int setup_iph(struct iphdr *iph, uint16_t payload_len) { struct sockaddr_in *daddr = (void *) &cfg_dst_addr; struct sockaddr_in *saddr = (void *) &cfg_src_addr; memset(iph, 0, sizeof(*iph)); iph->version = 4; iph->tos = 0; iph->ihl = 5; iph->ttl = 2; iph->saddr = saddr->sin_addr.s_addr; iph->daddr = daddr->sin_addr.s_addr; iph->protocol = IPPROTO_EGP; iph->tot_len = htons(sizeof(*iph) + payload_len); iph->check = get_ip_csum((void *) iph, iph->ihl << 1); return sizeof(*iph); } static int setup_ip6h(struct ipv6hdr *ip6h, uint16_t payload_len) { struct sockaddr_in6 *daddr = (void *) &cfg_dst_addr; struct sockaddr_in6 *saddr = (void *) &cfg_src_addr; memset(ip6h, 0, sizeof(*ip6h)); ip6h->version = 6; ip6h->payload_len = htons(payload_len); ip6h->nexthdr = IPPROTO_EGP; ip6h->hop_limit = 2; ip6h->saddr = saddr->sin6_addr; ip6h->daddr = daddr->sin6_addr; return sizeof(*ip6h); } static void setup_sockaddr(int domain, const char *str_addr, struct sockaddr_storage *sockaddr) { struct sockaddr_in6 *addr6 = (void *) sockaddr; struct sockaddr_in *addr4 = (void *) sockaddr; switch (domain) { case PF_INET: memset(addr4, 0, sizeof(*addr4)); addr4->sin_family = AF_INET; addr4->sin_port = htons(cfg_port); if (str_addr && inet_pton(AF_INET, str_addr, &(addr4->sin_addr)) != 1) error(1, 0, "ipv4 parse error: %s", str_addr); break; case PF_INET6: memset(addr6, 0, sizeof(*addr6)); addr6->sin6_family = AF_INET6; addr6->sin6_port = htons(cfg_port); if (str_addr && inet_pton(AF_INET6, str_addr, &(addr6->sin6_addr)) != 1) error(1, 0, "ipv6 parse error: %s", str_addr); break; default: error(1, 0, "illegal domain"); } } static int do_setup_tx(int domain, int type, int protocol) { int fd; fd = socket(domain, type, protocol); if (fd == -1) error(1, errno, "socket t"); do_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, 1 << 21); if (cfg_zerocopy) do_setsockopt(fd, SOL_SOCKET, SO_ZEROCOPY, 1); if (domain != PF_PACKET && domain != PF_RDS) if (connect(fd, (void *) &cfg_dst_addr, cfg_alen)) error(1, errno, "connect"); if (domain == PF_RDS) { if (bind(fd, (void *) &cfg_src_addr, cfg_alen)) error(1, errno, "bind"); } return fd; } static uint32_t do_process_zerocopy_cookies(struct rds_zcopy_cookies *ck) { int i; if (ck->num > RDS_MAX_ZCOOKIES) error(1, 0, "Returned %d cookies, max expected %d\n", ck->num, RDS_MAX_ZCOOKIES); for (i = 0; i < ck->num; i++) if (cfg_verbose >= 2) fprintf(stderr, "%d\n", ck->cookies[i]); return ck->num; } static bool do_recvmsg_completion(int fd) { char cmsgbuf[CMSG_SPACE(sizeof(struct rds_zcopy_cookies))]; struct rds_zcopy_cookies *ck; struct cmsghdr *cmsg; struct msghdr msg; bool ret = false; memset(&msg, 0, sizeof(msg)); msg.msg_control = cmsgbuf; msg.msg_controllen = sizeof(cmsgbuf); if (recvmsg(fd, &msg, MSG_DONTWAIT)) return ret; if (msg.msg_flags & MSG_CTRUNC) error(1, errno, "recvmsg notification: truncated"); for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { if (cmsg->cmsg_level == SOL_RDS && cmsg->cmsg_type == RDS_CMSG_ZCOPY_COMPLETION) { ck = (struct rds_zcopy_cookies *)CMSG_DATA(cmsg); completions += do_process_zerocopy_cookies(ck); ret = true; break; } error(0, 0, "ignoring cmsg at level %d type %d\n", cmsg->cmsg_level, cmsg->cmsg_type); } return ret; } static bool do_recv_completion(int fd, int domain) { struct sock_extended_err *serr; struct msghdr msg = {}; struct cmsghdr *cm; uint32_t hi, lo, range; int ret, zerocopy; char control[100]; if (domain == PF_RDS) return do_recvmsg_completion(fd); msg.msg_control = control; msg.msg_controllen = sizeof(control); ret = recvmsg(fd, &msg, MSG_ERRQUEUE); if (ret == -1 && errno == EAGAIN) return false; if (ret == -1) error(1, errno, "recvmsg notification"); if (msg.msg_flags & MSG_CTRUNC) error(1, errno, "recvmsg notification: truncated"); cm = CMSG_FIRSTHDR(&msg); if (!cm) error(1, 0, "cmsg: no cmsg"); if (!((cm->cmsg_level == SOL_IP && cm->cmsg_type == IP_RECVERR) || (cm->cmsg_level == SOL_IPV6 && cm->cmsg_type == IPV6_RECVERR) || (cm->cmsg_level == SOL_PACKET && cm->cmsg_type == PACKET_TX_TIMESTAMP))) error(1, 0, "serr: wrong type: %d.%d", cm->cmsg_level, cm->cmsg_type); serr = (void *) CMSG_DATA(cm); if (serr->ee_origin != SO_EE_ORIGIN_ZEROCOPY) error(1, 0, "serr: wrong origin: %u", serr->ee_origin); if (serr->ee_errno != 0) error(1, 0, "serr: wrong error code: %u", serr->ee_errno); hi = serr->ee_data; lo = serr->ee_info; range = hi - lo + 1; /* Detect notification gaps. These should not happen often, if at all. * Gaps can occur due to drops, reordering and retransmissions. */ if (lo != next_completion) fprintf(stderr, "gap: %u..%u does not append to %u\n", lo, hi, next_completion); next_completion = hi + 1; zerocopy = !(serr->ee_code & SO_EE_CODE_ZEROCOPY_COPIED); if (zerocopied == -1) zerocopied = zerocopy; else if (zerocopied != zerocopy) { fprintf(stderr, "serr: inconsistent\n"); zerocopied = zerocopy; } if (cfg_verbose >= 2) fprintf(stderr, "completed: %u (h=%u l=%u)\n", range, hi, lo); completions += range; return true; } /* Read all outstanding messages on the errqueue */ static void do_recv_completions(int fd, int domain) { while (do_recv_completion(fd, domain)) {} } /* Wait for all remaining completions on the errqueue */ static void do_recv_remaining_completions(int fd, int domain) { int64_t tstop = gettimeofday_ms() + cfg_waittime_ms; while (completions < expected_completions && gettimeofday_ms() < tstop) { if (do_poll(fd, domain == PF_RDS ? POLLIN : POLLERR)) do_recv_completions(fd, domain); } if (completions < expected_completions) fprintf(stderr, "missing notifications: %lu < %lu\n", completions, expected_completions); } static void do_tx(int domain, int type, int protocol) { struct iovec iov[3] = { {0} }; struct sockaddr_ll laddr; struct msghdr msg = {0}; struct ethhdr eth; union { struct ipv6hdr ip6h; struct iphdr iph; } nh; uint64_t tstop; int fd; fd = do_setup_tx(domain, type, protocol); if (domain == PF_PACKET) { uint16_t proto = cfg_family == PF_INET ? ETH_P_IP : ETH_P_IPV6; /* sock_raw passes ll header as data */ if (type == SOCK_RAW) { memset(eth.h_dest, 0x06, ETH_ALEN); memset(eth.h_source, 0x02, ETH_ALEN); eth.h_proto = htons(proto); iov[0].iov_base = &eth; iov[0].iov_len = sizeof(eth); msg.msg_iovlen++; } /* both sock_raw and sock_dgram expect name */ memset(&laddr, 0, sizeof(laddr)); laddr.sll_family = AF_PACKET; laddr.sll_ifindex = cfg_ifindex; laddr.sll_protocol = htons(proto); laddr.sll_halen = ETH_ALEN; memset(laddr.sll_addr, 0x06, ETH_ALEN); msg.msg_name = &laddr; msg.msg_namelen = sizeof(laddr); } /* packet and raw sockets with hdrincl must pass network header */ if (domain == PF_PACKET || protocol == IPPROTO_RAW) { if (cfg_family == PF_INET) iov[1].iov_len = setup_iph(&nh.iph, cfg_payload_len); else iov[1].iov_len = setup_ip6h(&nh.ip6h, cfg_payload_len); iov[1].iov_base = (void *) &nh; msg.msg_iovlen++; } if (domain == PF_RDS) { msg.msg_name = &cfg_dst_addr; msg.msg_namelen = (cfg_dst_addr.ss_family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)); } iov[2].iov_base = payload; iov[2].iov_len = cfg_payload_len; msg.msg_iovlen++; msg.msg_iov = &iov[3 - msg.msg_iovlen]; tstop = gettimeofday_ms() + cfg_runtime_ms; do { if (cfg_cork) do_sendmsg_corked(fd, &msg); else do_sendmsg(fd, &msg, cfg_zerocopy, domain); while (!do_poll(fd, POLLOUT)) { if (cfg_zerocopy) do_recv_completions(fd, domain); } } while (gettimeofday_ms() < tstop); if (cfg_zerocopy) do_recv_remaining_completions(fd, domain); if (close(fd)) error(1, errno, "close"); fprintf(stderr, "tx=%lu (%lu MB) txc=%lu zc=%c\n", packets, bytes >> 20, completions, zerocopied == 1 ? 'y' : 'n'); } static int do_setup_rx(int domain, int type, int protocol) { int fd; /* If tx over PF_PACKET, rx over PF_INET(6)/SOCK_RAW, * to recv the only copy of the packet, not a clone */ if (domain == PF_PACKET) error(1, 0, "Use PF_INET/SOCK_RAW to read"); if (type == SOCK_RAW && protocol == IPPROTO_RAW) error(1, 0, "IPPROTO_RAW: not supported on Rx"); fd = socket(domain, type, protocol); if (fd == -1) error(1, errno, "socket r"); do_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, 1 << 21); do_setsockopt(fd, SOL_SOCKET, SO_RCVLOWAT, 1 << 16); do_setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, 1); if (bind(fd, (void *) &cfg_dst_addr, cfg_alen)) error(1, errno, "bind"); if (type == SOCK_STREAM) { if (listen(fd, 1)) error(1, errno, "listen"); fd = do_accept(fd); } return fd; } /* Flush all outstanding bytes for the tcp receive queue */ static void do_flush_tcp(int fd) { int ret; /* MSG_TRUNC flushes up to len bytes */ ret = recv(fd, NULL, 1 << 21, MSG_TRUNC | MSG_DONTWAIT); if (ret == -1 && errno == EAGAIN) return; if (ret == -1) error(1, errno, "flush"); if (!ret) return; packets++; bytes += ret; } /* Flush all outstanding datagrams. Verify first few bytes of each. */ static void do_flush_datagram(int fd, int type) { int ret, off = 0; char buf[64]; /* MSG_TRUNC will return full datagram length */ ret = recv(fd, buf, sizeof(buf), MSG_DONTWAIT | MSG_TRUNC); if (ret == -1 && errno == EAGAIN) return; /* raw ipv4 return with header, raw ipv6 without */ if (cfg_family == PF_INET && type == SOCK_RAW) { off += sizeof(struct iphdr); ret -= sizeof(struct iphdr); } if (ret == -1) error(1, errno, "recv"); if (ret != cfg_payload_len) error(1, 0, "recv: ret=%u != %u", ret, cfg_payload_len); if (ret > sizeof(buf) - off) ret = sizeof(buf) - off; if (memcmp(buf + off, payload, ret)) error(1, 0, "recv: data mismatch"); packets++; bytes += cfg_payload_len; } static void do_rx(int domain, int type, int protocol) { const int cfg_receiver_wait_ms = 400; uint64_t tstop; int fd; fd = do_setup_rx(domain, type, protocol); tstop = gettimeofday_ms() + cfg_runtime_ms + cfg_receiver_wait_ms; do { if (type == SOCK_STREAM) do_flush_tcp(fd); else do_flush_datagram(fd, type); do_poll(fd, POLLIN); } while (gettimeofday_ms() < tstop); if (close(fd)) error(1, errno, "close"); fprintf(stderr, "rx=%lu (%lu MB)\n", packets, bytes >> 20); } static void do_test(int domain, int type, int protocol) { int i; if (cfg_cork && (domain == PF_PACKET || type != SOCK_DGRAM)) error(1, 0, "can only cork udp sockets"); do_setcpu(cfg_cpu); for (i = 0; i < IP_MAXPACKET; i++) payload[i] = 'a' + (i % 26); if (cfg_rx) do_rx(domain, type, protocol); else do_tx(domain, type, protocol); } static void usage(const char *filepath) { error(1, 0, "Usage: %s [options] <test>", filepath); } static void parse_opts(int argc, char **argv) { const int max_payload_len = sizeof(payload) - sizeof(struct ipv6hdr) - sizeof(struct tcphdr) - 40 /* max tcp options */; int c; char *daddr = NULL, *saddr = NULL; char *cfg_test; cfg_payload_len = max_payload_len; while ((c = getopt(argc, argv, "46c:C:D:i:mp:rs:S:t:vz")) != -1) { switch (c) { case '4': if (cfg_family != PF_UNSPEC) error(1, 0, "Pass one of -4 or -6"); cfg_family = PF_INET; cfg_alen = sizeof(struct sockaddr_in); break; case '6': if (cfg_family != PF_UNSPEC) error(1, 0, "Pass one of -4 or -6"); cfg_family = PF_INET6; cfg_alen = sizeof(struct sockaddr_in6); break; case 'c': cfg_cork = strtol(optarg, NULL, 0); break; case 'C': cfg_cpu = strtol(optarg, NULL, 0); break; case 'D': daddr = optarg; break; case 'i': cfg_ifindex = if_nametoindex(optarg); if (cfg_ifindex == 0) error(1, errno, "invalid iface: %s", optarg); break; case 'm': cfg_cork_mixed = true; break; case 'p': cfg_port = strtoul(optarg, NULL, 0); break; case 'r': cfg_rx = true; break; case 's': cfg_payload_len = strtoul(optarg, NULL, 0); break; case 'S': saddr = optarg; break; case 't': cfg_runtime_ms = 200 + strtoul(optarg, NULL, 10) * 1000; break; case 'v': cfg_verbose++; break; case 'z': cfg_zerocopy = true; break; } } cfg_test = argv[argc - 1]; if (strcmp(cfg_test, "rds") == 0) { if (!daddr) error(1, 0, "-D <server addr> required for PF_RDS\n"); if (!cfg_rx && !saddr) error(1, 0, "-S <client addr> required for PF_RDS\n"); } setup_sockaddr(cfg_family, daddr, &cfg_dst_addr); setup_sockaddr(cfg_family, saddr, &cfg_src_addr); if (cfg_payload_len > max_payload_len) error(1, 0, "-s: payload exceeds max (%d)", max_payload_len); if (cfg_cork_mixed && (!cfg_zerocopy || !cfg_cork)) error(1, 0, "-m: cork_mixed requires corking and zerocopy"); if (optind != argc - 1) usage(argv[0]); } int main(int argc, char **argv) { const char *cfg_test; parse_opts(argc, argv); cfg_test = argv[argc - 1]; if (!strcmp(cfg_test, "packet")) do_test(PF_PACKET, SOCK_RAW, 0); else if (!strcmp(cfg_test, "packet_dgram")) do_test(PF_PACKET, SOCK_DGRAM, 0); else if (!strcmp(cfg_test, "raw")) do_test(cfg_family, SOCK_RAW, IPPROTO_EGP); else if (!strcmp(cfg_test, "raw_hdrincl")) do_test(cfg_family, SOCK_RAW, IPPROTO_RAW); else if (!strcmp(cfg_test, "tcp")) do_test(cfg_family, SOCK_STREAM, 0); else if (!strcmp(cfg_test, "udp")) do_test(cfg_family, SOCK_DGRAM, 0); else if (!strcmp(cfg_test, "rds")) do_test(PF_RDS, SOCK_SEQPACKET, 0); else error(1, 0, "unknown cfg_test %s", cfg_test); return 0; }
linux-master
tools/testing/selftests/net/msg_zerocopy.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <arpa/inet.h> #include <errno.h> #include <error.h> #include <linux/in.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/udp.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> static bool cfg_do_ipv4; static bool cfg_do_ipv6; static bool cfg_verbose; static bool cfg_overlap; static bool cfg_permissive; static unsigned short cfg_port = 9000; const struct in_addr addr4 = { .s_addr = __constant_htonl(INADDR_LOOPBACK + 2) }; const struct in6_addr addr6 = IN6ADDR_LOOPBACK_INIT; #define IP4_HLEN (sizeof(struct iphdr)) #define IP6_HLEN (sizeof(struct ip6_hdr)) #define UDP_HLEN (sizeof(struct udphdr)) /* IPv6 fragment header lenth. */ #define FRAG_HLEN 8 static int payload_len; static int max_frag_len; #define MSG_LEN_MAX 10000 /* Max UDP payload length. */ #define IP4_MF (1u << 13) /* IPv4 MF flag. */ #define IP6_MF (1) /* IPv6 MF flag. */ #define CSUM_MANGLED_0 (0xffff) static uint8_t udp_payload[MSG_LEN_MAX]; static uint8_t ip_frame[IP_MAXPACKET]; static uint32_t ip_id = 0xabcd; static int msg_counter; static int frag_counter; static unsigned int seed; /* Receive a UDP packet. Validate it matches udp_payload. */ static void recv_validate_udp(int fd_udp) { ssize_t ret; static uint8_t recv_buff[MSG_LEN_MAX]; ret = recv(fd_udp, recv_buff, payload_len, 0); msg_counter++; if (cfg_overlap) { if (ret == -1 && (errno == ETIMEDOUT || errno == EAGAIN)) return; /* OK */ if (!cfg_permissive) { if (ret != -1) error(1, 0, "recv: expected timeout; got %d", (int)ret); error(1, errno, "recv: expected timeout: %d", errno); } } if (ret == -1) error(1, errno, "recv: payload_len = %d max_frag_len = %d", payload_len, max_frag_len); if (ret != payload_len) error(1, 0, "recv: wrong size: %d vs %d", (int)ret, payload_len); if (memcmp(udp_payload, recv_buff, payload_len)) error(1, 0, "recv: wrong data"); } static uint32_t raw_checksum(uint8_t *buf, int len, uint32_t sum) { int i; for (i = 0; i < (len & ~1U); i += 2) { sum += (u_int16_t)ntohs(*((u_int16_t *)(buf + i))); if (sum > 0xffff) sum -= 0xffff; } if (i < len) { sum += buf[i] << 8; if (sum > 0xffff) sum -= 0xffff; } return sum; } static uint16_t udp_checksum(struct ip *iphdr, struct udphdr *udphdr) { uint32_t sum = 0; uint16_t res; sum = raw_checksum((uint8_t *)&iphdr->ip_src, 2 * sizeof(iphdr->ip_src), IPPROTO_UDP + (uint32_t)(UDP_HLEN + payload_len)); sum = raw_checksum((uint8_t *)udphdr, UDP_HLEN, sum); sum = raw_checksum((uint8_t *)udp_payload, payload_len, sum); res = 0xffff & ~sum; if (res) return htons(res); else return CSUM_MANGLED_0; } static uint16_t udp6_checksum(struct ip6_hdr *iphdr, struct udphdr *udphdr) { uint32_t sum = 0; uint16_t res; sum = raw_checksum((uint8_t *)&iphdr->ip6_src, 2 * sizeof(iphdr->ip6_src), IPPROTO_UDP); sum = raw_checksum((uint8_t *)&udphdr->len, sizeof(udphdr->len), sum); sum = raw_checksum((uint8_t *)udphdr, UDP_HLEN, sum); sum = raw_checksum((uint8_t *)udp_payload, payload_len, sum); res = 0xffff & ~sum; if (res) return htons(res); else return CSUM_MANGLED_0; } static void send_fragment(int fd_raw, struct sockaddr *addr, socklen_t alen, int offset, bool ipv6) { int frag_len; int res; int payload_offset = offset > 0 ? offset - UDP_HLEN : 0; uint8_t *frag_start = ipv6 ? ip_frame + IP6_HLEN + FRAG_HLEN : ip_frame + IP4_HLEN; if (offset == 0) { struct udphdr udphdr; udphdr.source = htons(cfg_port + 1); udphdr.dest = htons(cfg_port); udphdr.len = htons(UDP_HLEN + payload_len); udphdr.check = 0; if (ipv6) udphdr.check = udp6_checksum((struct ip6_hdr *)ip_frame, &udphdr); else udphdr.check = udp_checksum((struct ip *)ip_frame, &udphdr); memcpy(frag_start, &udphdr, UDP_HLEN); } if (ipv6) { struct ip6_hdr *ip6hdr = (struct ip6_hdr *)ip_frame; struct ip6_frag *fraghdr = (struct ip6_frag *)(ip_frame + IP6_HLEN); if (payload_len - payload_offset <= max_frag_len && offset > 0) { /* This is the last fragment. */ frag_len = FRAG_HLEN + payload_len - payload_offset; fraghdr->ip6f_offlg = htons(offset); } else { frag_len = FRAG_HLEN + max_frag_len; fraghdr->ip6f_offlg = htons(offset | IP6_MF); } ip6hdr->ip6_plen = htons(frag_len); if (offset == 0) memcpy(frag_start + UDP_HLEN, udp_payload, frag_len - FRAG_HLEN - UDP_HLEN); else memcpy(frag_start, udp_payload + payload_offset, frag_len - FRAG_HLEN); frag_len += IP6_HLEN; } else { struct ip *iphdr = (struct ip *)ip_frame; if (payload_len - payload_offset <= max_frag_len && offset > 0) { /* This is the last fragment. */ frag_len = IP4_HLEN + payload_len - payload_offset; iphdr->ip_off = htons(offset / 8); } else { frag_len = IP4_HLEN + max_frag_len; iphdr->ip_off = htons(offset / 8 | IP4_MF); } iphdr->ip_len = htons(frag_len); if (offset == 0) memcpy(frag_start + UDP_HLEN, udp_payload, frag_len - IP4_HLEN - UDP_HLEN); else memcpy(frag_start, udp_payload + payload_offset, frag_len - IP4_HLEN); } res = sendto(fd_raw, ip_frame, frag_len, 0, addr, alen); if (res < 0 && errno != EPERM) error(1, errno, "send_fragment"); if (res >= 0 && res != frag_len) error(1, 0, "send_fragment: %d vs %d", res, frag_len); frag_counter++; } static void send_udp_frags(int fd_raw, struct sockaddr *addr, socklen_t alen, bool ipv6) { struct ip *iphdr = (struct ip *)ip_frame; struct ip6_hdr *ip6hdr = (struct ip6_hdr *)ip_frame; int res; int offset; int frag_len; /* Send the UDP datagram using raw IP fragments: the 0th fragment * has the UDP header; other fragments are pieces of udp_payload * split in chunks of frag_len size. * * Odd fragments (1st, 3rd, 5th, etc.) are sent out first, then * even fragments (0th, 2nd, etc.) are sent out. */ if (ipv6) { struct ip6_frag *fraghdr = (struct ip6_frag *)(ip_frame + IP6_HLEN); ((struct sockaddr_in6 *)addr)->sin6_port = 0; memset(ip6hdr, 0, sizeof(*ip6hdr)); ip6hdr->ip6_flow = htonl(6<<28); /* Version. */ ip6hdr->ip6_nxt = IPPROTO_FRAGMENT; ip6hdr->ip6_hops = 255; ip6hdr->ip6_src = addr6; ip6hdr->ip6_dst = addr6; fraghdr->ip6f_nxt = IPPROTO_UDP; fraghdr->ip6f_reserved = 0; fraghdr->ip6f_ident = htonl(ip_id++); } else { memset(iphdr, 0, sizeof(*iphdr)); iphdr->ip_hl = 5; iphdr->ip_v = 4; iphdr->ip_tos = 0; iphdr->ip_id = htons(ip_id++); iphdr->ip_ttl = 0x40; iphdr->ip_p = IPPROTO_UDP; iphdr->ip_src.s_addr = htonl(INADDR_LOOPBACK); iphdr->ip_dst = addr4; iphdr->ip_sum = 0; } /* Occasionally test in-order fragments. */ if (!cfg_overlap && (rand() % 100 < 15)) { offset = 0; while (offset < (UDP_HLEN + payload_len)) { send_fragment(fd_raw, addr, alen, offset, ipv6); offset += max_frag_len; } return; } /* Occasionally test IPv4 "runs" (see net/ipv4/ip_fragment.c) */ if (!cfg_overlap && (rand() % 100 < 20) && (payload_len > 9 * max_frag_len)) { offset = 6 * max_frag_len; while (offset < (UDP_HLEN + payload_len)) { send_fragment(fd_raw, addr, alen, offset, ipv6); offset += max_frag_len; } offset = 3 * max_frag_len; while (offset < 6 * max_frag_len) { send_fragment(fd_raw, addr, alen, offset, ipv6); offset += max_frag_len; } offset = 0; while (offset < 3 * max_frag_len) { send_fragment(fd_raw, addr, alen, offset, ipv6); offset += max_frag_len; } return; } /* Odd fragments. */ offset = max_frag_len; while (offset < (UDP_HLEN + payload_len)) { send_fragment(fd_raw, addr, alen, offset, ipv6); /* IPv4 ignores duplicates, so randomly send a duplicate. */ if (rand() % 100 == 1) send_fragment(fd_raw, addr, alen, offset, ipv6); offset += 2 * max_frag_len; } if (cfg_overlap) { /* Send an extra random fragment. * * Duplicates and some fragments completely inside * previously sent fragments are dropped/ignored. So * random offset and frag_len can result in a dropped * fragment instead of a dropped queue/packet. Thus we * hard-code offset and frag_len. */ if (max_frag_len * 4 < payload_len || max_frag_len < 16) { /* not enough payload for random offset and frag_len. */ offset = 8; frag_len = UDP_HLEN + max_frag_len; } else { offset = rand() % (payload_len / 2); frag_len = 2 * max_frag_len + 1 + rand() % 256; } if (ipv6) { struct ip6_frag *fraghdr = (struct ip6_frag *)(ip_frame + IP6_HLEN); /* sendto() returns EINVAL if offset + frag_len is too small. */ /* In IPv6 if !!(frag_len % 8), the fragment is dropped. */ frag_len &= ~0x7; fraghdr->ip6f_offlg = htons(offset / 8 | IP6_MF); ip6hdr->ip6_plen = htons(frag_len); frag_len += IP6_HLEN; } else { frag_len += IP4_HLEN; iphdr->ip_off = htons(offset / 8 | IP4_MF); iphdr->ip_len = htons(frag_len); } res = sendto(fd_raw, ip_frame, frag_len, 0, addr, alen); if (res < 0 && errno != EPERM) error(1, errno, "sendto overlap: %d", frag_len); if (res >= 0 && res != frag_len) error(1, 0, "sendto overlap: %d vs %d", (int)res, frag_len); frag_counter++; } /* Event fragments. */ offset = 0; while (offset < (UDP_HLEN + payload_len)) { send_fragment(fd_raw, addr, alen, offset, ipv6); /* IPv4 ignores duplicates, so randomly send a duplicate. */ if (rand() % 100 == 1) send_fragment(fd_raw, addr, alen, offset, ipv6); offset += 2 * max_frag_len; } } static void run_test(struct sockaddr *addr, socklen_t alen, bool ipv6) { int fd_tx_raw, fd_rx_udp; /* Frag queue timeout is set to one second in the calling script; * socket timeout should be just a bit longer to avoid tests interfering * with each other. */ struct timeval tv = { .tv_sec = 1, .tv_usec = 10 }; int idx; int min_frag_len = 8; /* Initialize the payload. */ for (idx = 0; idx < MSG_LEN_MAX; ++idx) udp_payload[idx] = idx % 256; /* Open sockets. */ fd_tx_raw = socket(addr->sa_family, SOCK_RAW, IPPROTO_RAW); if (fd_tx_raw == -1) error(1, errno, "socket tx_raw"); fd_rx_udp = socket(addr->sa_family, SOCK_DGRAM, 0); if (fd_rx_udp == -1) error(1, errno, "socket rx_udp"); if (bind(fd_rx_udp, addr, alen)) error(1, errno, "bind"); /* Fail fast. */ if (setsockopt(fd_rx_udp, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))) error(1, errno, "setsockopt rcv timeout"); for (payload_len = min_frag_len; payload_len < MSG_LEN_MAX; payload_len += (rand() % 4096)) { if (cfg_verbose) printf("payload_len: %d\n", payload_len); if (cfg_overlap) { /* With overlaps, one send/receive pair below takes * at least one second (== timeout) to run, so there * is not enough test time to run a nested loop: * the full overlap test takes 20-30 seconds. */ max_frag_len = min_frag_len + rand() % (1500 - FRAG_HLEN - min_frag_len); send_udp_frags(fd_tx_raw, addr, alen, ipv6); recv_validate_udp(fd_rx_udp); } else { /* Without overlaps, each packet reassembly (== one * send/receive pair below) takes very little time to * run, so we can easily afford more thourough testing * with a nested loop: the full non-overlap test takes * less than one second). */ max_frag_len = min_frag_len; do { send_udp_frags(fd_tx_raw, addr, alen, ipv6); recv_validate_udp(fd_rx_udp); max_frag_len += 8 * (rand() % 8); } while (max_frag_len < (1500 - FRAG_HLEN) && max_frag_len <= payload_len); } } /* Cleanup. */ if (close(fd_tx_raw)) error(1, errno, "close tx_raw"); if (close(fd_rx_udp)) error(1, errno, "close rx_udp"); if (cfg_verbose) printf("processed %d messages, %d fragments\n", msg_counter, frag_counter); fprintf(stderr, "PASS\n"); } static void run_test_v4(void) { struct sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_port = htons(cfg_port); addr.sin_addr = addr4; run_test((void *)&addr, sizeof(addr), false /* !ipv6 */); } static void run_test_v6(void) { struct sockaddr_in6 addr = {0}; addr.sin6_family = AF_INET6; addr.sin6_port = htons(cfg_port); addr.sin6_addr = addr6; run_test((void *)&addr, sizeof(addr), true /* ipv6 */); } static void parse_opts(int argc, char **argv) { int c; while ((c = getopt(argc, argv, "46opv")) != -1) { switch (c) { case '4': cfg_do_ipv4 = true; break; case '6': cfg_do_ipv6 = true; break; case 'o': cfg_overlap = true; break; case 'p': cfg_permissive = true; break; case 'v': cfg_verbose = true; break; default: error(1, 0, "%s: parse error", argv[0]); } } } int main(int argc, char **argv) { parse_opts(argc, argv); seed = time(NULL); srand(seed); /* Print the seed to track/reproduce potential failures. */ printf("seed = %d\n", seed); if (cfg_do_ipv4) run_test_v4(); if (cfg_do_ipv6) run_test_v6(); return 0; }
linux-master
tools/testing/selftests/net/ip_defrag.c
// SPDX-License-Identifier: GPL-2.0 #define _GNU_SOURCE #include <arpa/inet.h> #include <errno.h> #include <error.h> #include <fcntl.h> #include <limits.h> #include <linux/filter.h> #include <linux/bpf.h> #include <linux/if_packet.h> #include <linux/if_vlan.h> #include <linux/virtio_net.h> #include <net/if.h> #include <net/ethernet.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <poll.h> #include <sched.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "psock_lib.h" static bool cfg_use_bind; static bool cfg_use_csum_off; static bool cfg_use_csum_off_bad; static bool cfg_use_dgram; static bool cfg_use_gso; static bool cfg_use_qdisc_bypass; static bool cfg_use_vlan; static bool cfg_use_vnet; static char *cfg_ifname = "lo"; static int cfg_mtu = 1500; static int cfg_payload_len = DATA_LEN; static int cfg_truncate_len = INT_MAX; static uint16_t cfg_port = 8000; /* test sending up to max mtu + 1 */ #define TEST_SZ (sizeof(struct virtio_net_hdr) + ETH_HLEN + ETH_MAX_MTU + 1) static char tbuf[TEST_SZ], rbuf[TEST_SZ]; static unsigned long add_csum_hword(const uint16_t *start, int num_u16) { unsigned long sum = 0; int i; for (i = 0; i < num_u16; i++) sum += start[i]; return sum; } static uint16_t build_ip_csum(const uint16_t *start, int num_u16, unsigned long sum) { sum += add_csum_hword(start, num_u16); while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16); return ~sum; } static int build_vnet_header(void *header) { struct virtio_net_hdr *vh = header; vh->hdr_len = ETH_HLEN + sizeof(struct iphdr) + sizeof(struct udphdr); if (cfg_use_csum_off) { vh->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM; vh->csum_start = ETH_HLEN + sizeof(struct iphdr); vh->csum_offset = __builtin_offsetof(struct udphdr, check); /* position check field exactly one byte beyond end of packet */ if (cfg_use_csum_off_bad) vh->csum_start += sizeof(struct udphdr) + cfg_payload_len - vh->csum_offset - 1; } if (cfg_use_gso) { vh->gso_type = VIRTIO_NET_HDR_GSO_UDP; vh->gso_size = cfg_mtu - sizeof(struct iphdr); } return sizeof(*vh); } static int build_eth_header(void *header) { struct ethhdr *eth = header; if (cfg_use_vlan) { uint16_t *tag = header + ETH_HLEN; eth->h_proto = htons(ETH_P_8021Q); tag[1] = htons(ETH_P_IP); return ETH_HLEN + 4; } eth->h_proto = htons(ETH_P_IP); return ETH_HLEN; } static int build_ipv4_header(void *header, int payload_len) { struct iphdr *iph = header; iph->ihl = 5; iph->version = 4; iph->ttl = 8; iph->tot_len = htons(sizeof(*iph) + sizeof(struct udphdr) + payload_len); iph->id = htons(1337); iph->protocol = IPPROTO_UDP; iph->saddr = htonl((172 << 24) | (17 << 16) | 2); iph->daddr = htonl((172 << 24) | (17 << 16) | 1); iph->check = build_ip_csum((void *) iph, iph->ihl << 1, 0); return iph->ihl << 2; } static int build_udp_header(void *header, int payload_len) { const int alen = sizeof(uint32_t); struct udphdr *udph = header; int len = sizeof(*udph) + payload_len; udph->source = htons(9); udph->dest = htons(cfg_port); udph->len = htons(len); if (cfg_use_csum_off) udph->check = build_ip_csum(header - (2 * alen), alen, htons(IPPROTO_UDP) + udph->len); else udph->check = 0; return sizeof(*udph); } static int build_packet(int payload_len) { int off = 0; off += build_vnet_header(tbuf); off += build_eth_header(tbuf + off); off += build_ipv4_header(tbuf + off, payload_len); off += build_udp_header(tbuf + off, payload_len); if (off + payload_len > sizeof(tbuf)) error(1, 0, "payload length exceeds max"); memset(tbuf + off, DATA_CHAR, payload_len); return off + payload_len; } static void do_bind(int fd) { struct sockaddr_ll laddr = {0}; laddr.sll_family = AF_PACKET; laddr.sll_protocol = htons(ETH_P_IP); laddr.sll_ifindex = if_nametoindex(cfg_ifname); if (!laddr.sll_ifindex) error(1, errno, "if_nametoindex"); if (bind(fd, (void *)&laddr, sizeof(laddr))) error(1, errno, "bind"); } static void do_send(int fd, char *buf, int len) { int ret; if (!cfg_use_vnet) { buf += sizeof(struct virtio_net_hdr); len -= sizeof(struct virtio_net_hdr); } if (cfg_use_dgram) { buf += ETH_HLEN; len -= ETH_HLEN; } if (cfg_use_bind) { ret = write(fd, buf, len); } else { struct sockaddr_ll laddr = {0}; laddr.sll_protocol = htons(ETH_P_IP); laddr.sll_ifindex = if_nametoindex(cfg_ifname); if (!laddr.sll_ifindex) error(1, errno, "if_nametoindex"); ret = sendto(fd, buf, len, 0, (void *)&laddr, sizeof(laddr)); } if (ret == -1) error(1, errno, "write"); if (ret != len) error(1, 0, "write: %u %u", ret, len); fprintf(stderr, "tx: %u\n", ret); } static int do_tx(void) { const int one = 1; int fd, len; fd = socket(PF_PACKET, cfg_use_dgram ? SOCK_DGRAM : SOCK_RAW, 0); if (fd == -1) error(1, errno, "socket t"); if (cfg_use_bind) do_bind(fd); if (cfg_use_qdisc_bypass && setsockopt(fd, SOL_PACKET, PACKET_QDISC_BYPASS, &one, sizeof(one))) error(1, errno, "setsockopt qdisc bypass"); if (cfg_use_vnet && setsockopt(fd, SOL_PACKET, PACKET_VNET_HDR, &one, sizeof(one))) error(1, errno, "setsockopt vnet"); len = build_packet(cfg_payload_len); if (cfg_truncate_len < len) len = cfg_truncate_len; do_send(fd, tbuf, len); if (close(fd)) error(1, errno, "close t"); return len; } static int setup_rx(void) { struct timeval tv = { .tv_usec = 100 * 1000 }; struct sockaddr_in raddr = {0}; int fd; fd = socket(PF_INET, SOCK_DGRAM, 0); if (fd == -1) error(1, errno, "socket r"); if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))) error(1, errno, "setsockopt rcv timeout"); raddr.sin_family = AF_INET; raddr.sin_port = htons(cfg_port); raddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(fd, (void *)&raddr, sizeof(raddr))) error(1, errno, "bind r"); return fd; } static void do_rx(int fd, int expected_len, char *expected) { int ret; ret = recv(fd, rbuf, sizeof(rbuf), 0); if (ret == -1) error(1, errno, "recv"); if (ret != expected_len) error(1, 0, "recv: %u != %u", ret, expected_len); if (memcmp(rbuf, expected, ret)) error(1, 0, "recv: data mismatch"); fprintf(stderr, "rx: %u\n", ret); } static int setup_sniffer(void) { struct timeval tv = { .tv_usec = 100 * 1000 }; int fd; fd = socket(PF_PACKET, SOCK_RAW, 0); if (fd == -1) error(1, errno, "socket p"); if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv))) error(1, errno, "setsockopt rcv timeout"); pair_udp_setfilter(fd); do_bind(fd); return fd; } static void parse_opts(int argc, char **argv) { int c; while ((c = getopt(argc, argv, "bcCdgl:qt:vV")) != -1) { switch (c) { case 'b': cfg_use_bind = true; break; case 'c': cfg_use_csum_off = true; break; case 'C': cfg_use_csum_off_bad = true; break; case 'd': cfg_use_dgram = true; break; case 'g': cfg_use_gso = true; break; case 'l': cfg_payload_len = strtoul(optarg, NULL, 0); break; case 'q': cfg_use_qdisc_bypass = true; break; case 't': cfg_truncate_len = strtoul(optarg, NULL, 0); break; case 'v': cfg_use_vnet = true; break; case 'V': cfg_use_vlan = true; break; default: error(1, 0, "%s: parse error", argv[0]); } } if (cfg_use_vlan && cfg_use_dgram) error(1, 0, "option vlan (-V) conflicts with dgram (-d)"); if (cfg_use_csum_off && !cfg_use_vnet) error(1, 0, "option csum offload (-c) requires vnet (-v)"); if (cfg_use_csum_off_bad && !cfg_use_csum_off) error(1, 0, "option csum bad (-C) requires csum offload (-c)"); if (cfg_use_gso && !cfg_use_csum_off) error(1, 0, "option gso (-g) requires csum offload (-c)"); } static void run_test(void) { int fdr, fds, total_len; fdr = setup_rx(); fds = setup_sniffer(); total_len = do_tx(); /* BPF filter accepts only this length, vlan changes MAC */ if (cfg_payload_len == DATA_LEN && !cfg_use_vlan) do_rx(fds, total_len - sizeof(struct virtio_net_hdr), tbuf + sizeof(struct virtio_net_hdr)); do_rx(fdr, cfg_payload_len, tbuf + total_len - cfg_payload_len); if (close(fds)) error(1, errno, "close s"); if (close(fdr)) error(1, errno, "close r"); } int main(int argc, char **argv) { parse_opts(argc, argv); if (system("ip link set dev lo mtu 1500")) error(1, errno, "ip link set mtu"); if (system("ip addr add dev lo 172.17.0.1/24")) error(1, errno, "ip addr add"); if (system("sysctl -w net.ipv4.conf.lo.accept_local=1")) error(1, errno, "sysctl lo.accept_local"); run_test(); fprintf(stderr, "OK\n\n"); return 0; }
linux-master
tools/testing/selftests/net/psock_snd.c
// SPDX-License-Identifier: GPL-2.0-or-later #include <errno.h> #include <error.h> #include <netdb.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <linux/errqueue.h> #include <linux/icmp.h> #include <linux/icmpv6.h> #include <linux/net_tstamp.h> #include <linux/types.h> #include <linux/udp.h> #include <sys/socket.h> #include "../kselftest.h" enum { ERN_SUCCESS = 0, /* Well defined errors, callers may depend on these */ ERN_SEND = 1, /* Informational, can reorder */ ERN_HELP, ERN_SEND_SHORT, ERN_SOCK_CREATE, ERN_RESOLVE, ERN_CMSG_WR, ERN_SOCKOPT, ERN_GETTIME, ERN_RECVERR, ERN_CMSG_RD, ERN_CMSG_RCV, }; struct option_cmsg_u32 { bool ena; unsigned int val; }; struct options { bool silent_send; const char *host; const char *service; unsigned int size; struct { unsigned int mark; unsigned int dontfrag; unsigned int tclass; unsigned int hlimit; } sockopt; struct { unsigned int family; unsigned int type; unsigned int proto; } sock; struct option_cmsg_u32 mark; struct { bool ena; unsigned int delay; } txtime; struct { bool ena; } ts; struct { struct option_cmsg_u32 dontfrag; struct option_cmsg_u32 tclass; struct option_cmsg_u32 hlimit; struct option_cmsg_u32 exthdr; } v6; } opt = { .size = 13, .sock = { .family = AF_UNSPEC, .type = SOCK_DGRAM, .proto = IPPROTO_UDP, }, }; static struct timespec time_start_real; static struct timespec time_start_mono; static void __attribute__((noreturn)) cs_usage(const char *bin) { printf("Usage: %s [opts] <dst host> <dst port / service>\n", bin); printf("Options:\n" "\t\t-s Silent send() failures\n" "\t\t-S send() size\n" "\t\t-4/-6 Force IPv4 / IPv6 only\n" "\t\t-p prot Socket protocol\n" "\t\t (u = UDP (default); i = ICMP; r = RAW)\n" "\n" "\t\t-m val Set SO_MARK with given value\n" "\t\t-M val Set SO_MARK via setsockopt\n" "\t\t-d val Set SO_TXTIME with given delay (usec)\n" "\t\t-t Enable time stamp reporting\n" "\t\t-f val Set don't fragment via cmsg\n" "\t\t-F val Set don't fragment via setsockopt\n" "\t\t-c val Set TCLASS via cmsg\n" "\t\t-C val Set TCLASS via setsockopt\n" "\t\t-l val Set HOPLIMIT via cmsg\n" "\t\t-L val Set HOPLIMIT via setsockopt\n" "\t\t-H type Add an IPv6 header option\n" "\t\t (h = HOP; d = DST; r = RTDST)" ""); exit(ERN_HELP); } static void cs_parse_args(int argc, char *argv[]) { int o; while ((o = getopt(argc, argv, "46sS:p:m:M:d:tf:F:c:C:l:L:H:")) != -1) { switch (o) { case 's': opt.silent_send = true; break; case 'S': opt.size = atoi(optarg); break; case '4': opt.sock.family = AF_INET; break; case '6': opt.sock.family = AF_INET6; break; case 'p': if (*optarg == 'u' || *optarg == 'U') { opt.sock.proto = IPPROTO_UDP; } else if (*optarg == 'i' || *optarg == 'I') { opt.sock.proto = IPPROTO_ICMP; } else if (*optarg == 'r') { opt.sock.type = SOCK_RAW; } else { printf("Error: unknown protocol: %s\n", optarg); cs_usage(argv[0]); } break; case 'm': opt.mark.ena = true; opt.mark.val = atoi(optarg); break; case 'M': opt.sockopt.mark = atoi(optarg); break; case 'd': opt.txtime.ena = true; opt.txtime.delay = atoi(optarg); break; case 't': opt.ts.ena = true; break; case 'f': opt.v6.dontfrag.ena = true; opt.v6.dontfrag.val = atoi(optarg); break; case 'F': opt.sockopt.dontfrag = atoi(optarg); break; case 'c': opt.v6.tclass.ena = true; opt.v6.tclass.val = atoi(optarg); break; case 'C': opt.sockopt.tclass = atoi(optarg); break; case 'l': opt.v6.hlimit.ena = true; opt.v6.hlimit.val = atoi(optarg); break; case 'L': opt.sockopt.hlimit = atoi(optarg); break; case 'H': opt.v6.exthdr.ena = true; switch (optarg[0]) { case 'h': opt.v6.exthdr.val = IPV6_HOPOPTS; break; case 'd': opt.v6.exthdr.val = IPV6_DSTOPTS; break; case 'r': opt.v6.exthdr.val = IPV6_RTHDRDSTOPTS; break; default: printf("Error: hdr type: %s\n", optarg); break; } break; } } if (optind != argc - 2) cs_usage(argv[0]); opt.host = argv[optind]; opt.service = argv[optind + 1]; } static void memrnd(void *s, size_t n) { int *dword = s; char *byte; for (; n >= 4; n -= 4) *dword++ = rand(); byte = (void *)dword; while (n--) *byte++ = rand(); } static void ca_write_cmsg_u32(char *cbuf, size_t cbuf_sz, size_t *cmsg_len, int level, int optname, struct option_cmsg_u32 *uopt) { struct cmsghdr *cmsg; if (!uopt->ena) return; cmsg = (struct cmsghdr *)(cbuf + *cmsg_len); *cmsg_len += CMSG_SPACE(sizeof(__u32)); if (cbuf_sz < *cmsg_len) error(ERN_CMSG_WR, EFAULT, "cmsg buffer too small"); cmsg->cmsg_level = level; cmsg->cmsg_type = optname; cmsg->cmsg_len = CMSG_LEN(sizeof(__u32)); *(__u32 *)CMSG_DATA(cmsg) = uopt->val; } static void cs_write_cmsg(int fd, struct msghdr *msg, char *cbuf, size_t cbuf_sz) { struct cmsghdr *cmsg; size_t cmsg_len; msg->msg_control = cbuf; cmsg_len = 0; ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len, SOL_SOCKET, SO_MARK, &opt.mark); ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len, SOL_IPV6, IPV6_DONTFRAG, &opt.v6.dontfrag); ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len, SOL_IPV6, IPV6_TCLASS, &opt.v6.tclass); ca_write_cmsg_u32(cbuf, cbuf_sz, &cmsg_len, SOL_IPV6, IPV6_HOPLIMIT, &opt.v6.hlimit); if (opt.txtime.ena) { struct sock_txtime so_txtime = { .clockid = CLOCK_MONOTONIC, }; __u64 txtime; if (setsockopt(fd, SOL_SOCKET, SO_TXTIME, &so_txtime, sizeof(so_txtime))) error(ERN_SOCKOPT, errno, "setsockopt TXTIME"); txtime = time_start_mono.tv_sec * (1000ULL * 1000 * 1000) + time_start_mono.tv_nsec + opt.txtime.delay * 1000; cmsg = (struct cmsghdr *)(cbuf + cmsg_len); cmsg_len += CMSG_SPACE(sizeof(txtime)); if (cbuf_sz < cmsg_len) error(ERN_CMSG_WR, EFAULT, "cmsg buffer too small"); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_TXTIME; cmsg->cmsg_len = CMSG_LEN(sizeof(txtime)); memcpy(CMSG_DATA(cmsg), &txtime, sizeof(txtime)); } if (opt.ts.ena) { __u32 val = SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_OPT_TSONLY; if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPING, &val, sizeof(val))) error(ERN_SOCKOPT, errno, "setsockopt TIMESTAMPING"); cmsg = (struct cmsghdr *)(cbuf + cmsg_len); cmsg_len += CMSG_SPACE(sizeof(__u32)); if (cbuf_sz < cmsg_len) error(ERN_CMSG_WR, EFAULT, "cmsg buffer too small"); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SO_TIMESTAMPING; cmsg->cmsg_len = CMSG_LEN(sizeof(__u32)); *(__u32 *)CMSG_DATA(cmsg) = SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE; } if (opt.v6.exthdr.ena) { cmsg = (struct cmsghdr *)(cbuf + cmsg_len); cmsg_len += CMSG_SPACE(8); if (cbuf_sz < cmsg_len) error(ERN_CMSG_WR, EFAULT, "cmsg buffer too small"); cmsg->cmsg_level = SOL_IPV6; cmsg->cmsg_type = opt.v6.exthdr.val; cmsg->cmsg_len = CMSG_LEN(8); *(__u64 *)CMSG_DATA(cmsg) = 0; } if (cmsg_len) msg->msg_controllen = cmsg_len; else msg->msg_control = NULL; } static const char *cs_ts_info2str(unsigned int info) { static const char *names[] = { [SCM_TSTAMP_SND] = "SND", [SCM_TSTAMP_SCHED] = "SCHED", [SCM_TSTAMP_ACK] = "ACK", }; if (info < ARRAY_SIZE(names)) return names[info]; return "unknown"; } static void cs_read_cmsg(int fd, struct msghdr *msg, char *cbuf, size_t cbuf_sz) { struct sock_extended_err *see; struct scm_timestamping *ts; struct cmsghdr *cmsg; int i, err; if (!opt.ts.ena) return; msg->msg_control = cbuf; msg->msg_controllen = cbuf_sz; while (true) { ts = NULL; see = NULL; memset(cbuf, 0, cbuf_sz); err = recvmsg(fd, msg, MSG_ERRQUEUE); if (err < 0) { if (errno == EAGAIN) break; error(ERN_RECVERR, errno, "recvmsg ERRQ"); } for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL; cmsg = CMSG_NXTHDR(msg, cmsg)) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SO_TIMESTAMPING_OLD) { if (cmsg->cmsg_len < sizeof(*ts)) error(ERN_CMSG_RD, EINVAL, "TS cmsg"); ts = (void *)CMSG_DATA(cmsg); } if ((cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_RECVERR) || (cmsg->cmsg_level == SOL_IPV6 && cmsg->cmsg_type == IPV6_RECVERR)) { if (cmsg->cmsg_len < sizeof(*see)) error(ERN_CMSG_RD, EINVAL, "sock_err cmsg"); see = (void *)CMSG_DATA(cmsg); } } if (!ts) error(ERN_CMSG_RCV, ENOENT, "TS cmsg not found"); if (!see) error(ERN_CMSG_RCV, ENOENT, "sock_err cmsg not found"); for (i = 0; i < 3; i++) { unsigned long long rel_time; if (!ts->ts[i].tv_sec && !ts->ts[i].tv_nsec) continue; rel_time = (ts->ts[i].tv_sec - time_start_real.tv_sec) * (1000ULL * 1000) + (ts->ts[i].tv_nsec - time_start_real.tv_nsec) / 1000; printf(" %5s ts%d %lluus\n", cs_ts_info2str(see->ee_info), i, rel_time); } } } static void ca_set_sockopts(int fd) { if (opt.sockopt.mark && setsockopt(fd, SOL_SOCKET, SO_MARK, &opt.sockopt.mark, sizeof(opt.sockopt.mark))) error(ERN_SOCKOPT, errno, "setsockopt SO_MARK"); if (opt.sockopt.dontfrag && setsockopt(fd, SOL_IPV6, IPV6_DONTFRAG, &opt.sockopt.dontfrag, sizeof(opt.sockopt.dontfrag))) error(ERN_SOCKOPT, errno, "setsockopt IPV6_DONTFRAG"); if (opt.sockopt.tclass && setsockopt(fd, SOL_IPV6, IPV6_TCLASS, &opt.sockopt.tclass, sizeof(opt.sockopt.tclass))) error(ERN_SOCKOPT, errno, "setsockopt IPV6_TCLASS"); if (opt.sockopt.hlimit && setsockopt(fd, SOL_IPV6, IPV6_UNICAST_HOPS, &opt.sockopt.hlimit, sizeof(opt.sockopt.hlimit))) error(ERN_SOCKOPT, errno, "setsockopt IPV6_HOPLIMIT"); } int main(int argc, char *argv[]) { struct addrinfo hints, *ai; struct iovec iov[1]; struct msghdr msg; char cbuf[1024]; char *buf; int err; int fd; cs_parse_args(argc, argv); buf = malloc(opt.size); memrnd(buf, opt.size); memset(&hints, 0, sizeof(hints)); hints.ai_family = opt.sock.family; ai = NULL; err = getaddrinfo(opt.host, opt.service, &hints, &ai); if (err) { fprintf(stderr, "Can't resolve address [%s]:%s\n", opt.host, opt.service); return ERN_SOCK_CREATE; } if (ai->ai_family == AF_INET6 && opt.sock.proto == IPPROTO_ICMP) opt.sock.proto = IPPROTO_ICMPV6; fd = socket(ai->ai_family, opt.sock.type, opt.sock.proto); if (fd < 0) { fprintf(stderr, "Can't open socket: %s\n", strerror(errno)); freeaddrinfo(ai); return ERN_RESOLVE; } if (opt.sock.proto == IPPROTO_ICMP) { buf[0] = ICMP_ECHO; buf[1] = 0; } else if (opt.sock.proto == IPPROTO_ICMPV6) { buf[0] = ICMPV6_ECHO_REQUEST; buf[1] = 0; } else if (opt.sock.type == SOCK_RAW) { struct udphdr hdr = { 1, 2, htons(opt.size), 0 }; struct sockaddr_in6 *sin6 = (void *)ai->ai_addr; memcpy(buf, &hdr, sizeof(hdr)); sin6->sin6_port = htons(opt.sock.proto); } ca_set_sockopts(fd); if (clock_gettime(CLOCK_REALTIME, &time_start_real)) error(ERN_GETTIME, errno, "gettime REALTIME"); if (clock_gettime(CLOCK_MONOTONIC, &time_start_mono)) error(ERN_GETTIME, errno, "gettime MONOTONIC"); iov[0].iov_base = buf; iov[0].iov_len = opt.size; memset(&msg, 0, sizeof(msg)); msg.msg_name = ai->ai_addr; msg.msg_namelen = ai->ai_addrlen; msg.msg_iov = iov; msg.msg_iovlen = 1; cs_write_cmsg(fd, &msg, cbuf, sizeof(cbuf)); err = sendmsg(fd, &msg, 0); if (err < 0) { if (!opt.silent_send) fprintf(stderr, "send failed: %s\n", strerror(errno)); err = ERN_SEND; goto err_out; } else if (err != (int)opt.size) { fprintf(stderr, "short send\n"); err = ERN_SEND_SHORT; goto err_out; } else { err = ERN_SUCCESS; } /* Make sure all timestamps have time to loop back */ usleep(opt.txtime.delay); cs_read_cmsg(fd, &msg, cbuf, sizeof(cbuf)); err_out: close(fd); freeaddrinfo(ai); return err; }
linux-master
tools/testing/selftests/net/cmsg_sender.c
// SPDX-License-Identifier: GPL-2.0-only /* * This code is taken from the Android Open Source Project and the author * (Maciej Żenczykowski) has gave permission to relicense it under the * GPLv2. Therefore this program is free software; * You can redistribute it and/or modify it under the terms of the GNU * General Public License version 2 as published by the Free Software * Foundation * The original headers, including the original license headers, are * included below for completeness. * * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <linux/bpf.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_packet.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/ipv6.h> #include <linux/pkt_cls.h> #include <linux/swab.h> #include <stdbool.h> #include <stdint.h> #include <linux/udp.h> #include <bpf/bpf_helpers.h> #include <bpf/bpf_endian.h> #define IP_DF 0x4000 // Flag: "Don't Fragment" SEC("schedcls/ingress6/nat_6") int sched_cls_ingress6_nat_6_prog(struct __sk_buff *skb) { const int l2_header_size = sizeof(struct ethhdr); void *data = (void *)(long)skb->data; const void *data_end = (void *)(long)skb->data_end; const struct ethhdr * const eth = data; // used iff is_ethernet const struct ipv6hdr * const ip6 = (void *)(eth + 1); // Require ethernet dst mac address to be our unicast address. if (skb->pkt_type != PACKET_HOST) return TC_ACT_OK; // Must be meta-ethernet IPv6 frame if (skb->protocol != bpf_htons(ETH_P_IPV6)) return TC_ACT_OK; // Must have (ethernet and) ipv6 header if (data + l2_header_size + sizeof(*ip6) > data_end) return TC_ACT_OK; // Ethertype - if present - must be IPv6 if (eth->h_proto != bpf_htons(ETH_P_IPV6)) return TC_ACT_OK; // IP version must be 6 if (ip6->version != 6) return TC_ACT_OK; // Maximum IPv6 payload length that can be translated to IPv4 if (bpf_ntohs(ip6->payload_len) > 0xFFFF - sizeof(struct iphdr)) return TC_ACT_OK; switch (ip6->nexthdr) { case IPPROTO_TCP: // For TCP & UDP the checksum neutrality of the chosen IPv6 case IPPROTO_UDP: // address means there is no need to update their checksums. case IPPROTO_GRE: // We do not need to bother looking at GRE/ESP headers, case IPPROTO_ESP: // since there is never a checksum to update. break; default: // do not know how to handle anything else return TC_ACT_OK; } struct ethhdr eth2; // used iff is_ethernet eth2 = *eth; // Copy over the ethernet header (src/dst mac) eth2.h_proto = bpf_htons(ETH_P_IP); // But replace the ethertype struct iphdr ip = { .version = 4, // u4 .ihl = sizeof(struct iphdr) / sizeof(__u32), // u4 .tos = (ip6->priority << 4) + (ip6->flow_lbl[0] >> 4), // u8 .tot_len = bpf_htons(bpf_ntohs(ip6->payload_len) + sizeof(struct iphdr)), // u16 .id = 0, // u16 .frag_off = bpf_htons(IP_DF), // u16 .ttl = ip6->hop_limit, // u8 .protocol = ip6->nexthdr, // u8 .check = 0, // u16 .saddr = 0x0201a8c0, // u32 .daddr = 0x0101a8c0, // u32 }; // Calculate the IPv4 one's complement checksum of the IPv4 header. __wsum sum4 = 0; for (int i = 0; i < sizeof(ip) / sizeof(__u16); ++i) sum4 += ((__u16 *)&ip)[i]; // Note that sum4 is guaranteed to be non-zero by virtue of ip.version == 4 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16 ip.check = (__u16)~sum4; // sum4 cannot be zero, so this is never 0xFFFF // Calculate the *negative* IPv6 16-bit one's complement checksum of the IPv6 header. __wsum sum6 = 0; // We'll end up with a non-zero sum due to ip6->version == 6 (which has '0' bits) for (int i = 0; i < sizeof(*ip6) / sizeof(__u16); ++i) sum6 += ~((__u16 *)ip6)[i]; // note the bitwise negation // Note that there is no L4 checksum update: we are relying on the checksum neutrality // of the ipv6 address chosen by netd's ClatdController. // Packet mutations begin - point of no return, but if this first modification fails // the packet is probably still pristine, so let clatd handle it. if (bpf_skb_change_proto(skb, bpf_htons(ETH_P_IP), 0)) return TC_ACT_OK; bpf_csum_update(skb, sum6); data = (void *)(long)skb->data; data_end = (void *)(long)skb->data_end; if (data + l2_header_size + sizeof(struct iphdr) > data_end) return TC_ACT_SHOT; struct ethhdr *new_eth = data; // Copy over the updated ethernet header *new_eth = eth2; // Copy over the new ipv4 header. *(struct iphdr *)(new_eth + 1) = ip; return bpf_redirect(skb->ifindex, BPF_F_INGRESS); } SEC("schedcls/egress4/snat4") int sched_cls_egress4_snat4_prog(struct __sk_buff *skb) { const int l2_header_size = sizeof(struct ethhdr); void *data = (void *)(long)skb->data; const void *data_end = (void *)(long)skb->data_end; const struct ethhdr *const eth = data; // used iff is_ethernet const struct iphdr *const ip4 = (void *)(eth + 1); // Must be meta-ethernet IPv4 frame if (skb->protocol != bpf_htons(ETH_P_IP)) return TC_ACT_OK; // Must have ipv4 header if (data + l2_header_size + sizeof(struct ipv6hdr) > data_end) return TC_ACT_OK; // Ethertype - if present - must be IPv4 if (eth->h_proto != bpf_htons(ETH_P_IP)) return TC_ACT_OK; // IP version must be 4 if (ip4->version != 4) return TC_ACT_OK; // We cannot handle IP options, just standard 20 byte == 5 dword minimal IPv4 header if (ip4->ihl != 5) return TC_ACT_OK; // Maximum IPv6 payload length that can be translated to IPv4 if (bpf_htons(ip4->tot_len) > 0xFFFF - sizeof(struct ipv6hdr)) return TC_ACT_OK; // Calculate the IPv4 one's complement checksum of the IPv4 header. __wsum sum4 = 0; for (int i = 0; i < sizeof(*ip4) / sizeof(__u16); ++i) sum4 += ((__u16 *)ip4)[i]; // Note that sum4 is guaranteed to be non-zero by virtue of ip4->version == 4 sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse u32 into range 1 .. 0x1FFFE sum4 = (sum4 & 0xFFFF) + (sum4 >> 16); // collapse any potential carry into u16 // for a correct checksum we should get *a* zero, but sum4 must be positive, ie 0xFFFF if (sum4 != 0xFFFF) return TC_ACT_OK; // Minimum IPv4 total length is the size of the header if (bpf_ntohs(ip4->tot_len) < sizeof(*ip4)) return TC_ACT_OK; // We are incapable of dealing with IPv4 fragments if (ip4->frag_off & ~bpf_htons(IP_DF)) return TC_ACT_OK; switch (ip4->protocol) { case IPPROTO_TCP: // For TCP & UDP the checksum neutrality of the chosen IPv6 case IPPROTO_GRE: // address means there is no need to update their checksums. case IPPROTO_ESP: // We do not need to bother looking at GRE/ESP headers, break; // since there is never a checksum to update. case IPPROTO_UDP: // See above comment, but must also have UDP header... if (data + sizeof(*ip4) + sizeof(struct udphdr) > data_end) return TC_ACT_OK; const struct udphdr *uh = (const struct udphdr *)(ip4 + 1); // If IPv4/UDP checksum is 0 then fallback to clatd so it can calculate the // checksum. Otherwise the network or more likely the NAT64 gateway might // drop the packet because in most cases IPv6/UDP packets with a zero checksum // are invalid. See RFC 6935. TODO: calculate checksum via bpf_csum_diff() if (!uh->check) return TC_ACT_OK; break; default: // do not know how to handle anything else return TC_ACT_OK; } struct ethhdr eth2; // used iff is_ethernet eth2 = *eth; // Copy over the ethernet header (src/dst mac) eth2.h_proto = bpf_htons(ETH_P_IPV6); // But replace the ethertype struct ipv6hdr ip6 = { .version = 6, // __u8:4 .priority = ip4->tos >> 4, // __u8:4 .flow_lbl = {(ip4->tos & 0xF) << 4, 0, 0}, // __u8[3] .payload_len = bpf_htons(bpf_ntohs(ip4->tot_len) - 20), // __be16 .nexthdr = ip4->protocol, // __u8 .hop_limit = ip4->ttl, // __u8 }; ip6.saddr.in6_u.u6_addr32[0] = bpf_htonl(0x20010db8); ip6.saddr.in6_u.u6_addr32[1] = 0; ip6.saddr.in6_u.u6_addr32[2] = 0; ip6.saddr.in6_u.u6_addr32[3] = bpf_htonl(1); ip6.daddr.in6_u.u6_addr32[0] = bpf_htonl(0x20010db8); ip6.daddr.in6_u.u6_addr32[1] = 0; ip6.daddr.in6_u.u6_addr32[2] = 0; ip6.daddr.in6_u.u6_addr32[3] = bpf_htonl(2); // Calculate the IPv6 16-bit one's complement checksum of the IPv6 header. __wsum sum6 = 0; // We'll end up with a non-zero sum due to ip6.version == 6 for (int i = 0; i < sizeof(ip6) / sizeof(__u16); ++i) sum6 += ((__u16 *)&ip6)[i]; // Packet mutations begin - point of no return, but if this first modification fails // the packet is probably still pristine, so let clatd handle it. if (bpf_skb_change_proto(skb, bpf_htons(ETH_P_IPV6), 0)) return TC_ACT_OK; // This takes care of updating the skb->csum field for a CHECKSUM_COMPLETE packet. // In such a case, skb->csum is a 16-bit one's complement sum of the entire payload, // thus we need to subtract out the ipv4 header's sum, and add in the ipv6 header's sum. // However, we've already verified the ipv4 checksum is correct and thus 0. // Thus we only need to add the ipv6 header's sum. // // bpf_csum_update() always succeeds if the skb is CHECKSUM_COMPLETE and returns an error // (-ENOTSUPP) if it isn't. So we just ignore the return code (see above for more details). bpf_csum_update(skb, sum6); // bpf_skb_change_proto() invalidates all pointers - reload them. data = (void *)(long)skb->data; data_end = (void *)(long)skb->data_end; // I cannot think of any valid way for this error condition to trigger, however I do // believe the explicit check is required to keep the in kernel ebpf verifier happy. if (data + l2_header_size + sizeof(ip6) > data_end) return TC_ACT_SHOT; struct ethhdr *new_eth = data; // Copy over the updated ethernet header *new_eth = eth2; // Copy over the new ipv4 header. *(struct ipv6hdr *)(new_eth + 1) = ip6; return TC_ACT_OK; } char _license[] SEC("license") = ("GPL");
linux-master
tools/testing/selftests/net/nat6to4.c
// SPDX-License-Identifier: GPL-2.0 /* * Test key rotation for TFO. * New keys are 'rotated' in two steps: * 1) Add new key as the 'backup' key 'behind' the primary key * 2) Make new key the primary by swapping the backup and primary keys * * The rotation is done in stages using multiple sockets bound * to the same port via SO_REUSEPORT. This simulates key rotation * behind say a load balancer. We verify that across the rotation * there are no cases in which a cookie is not accepted by verifying * that TcpExtTCPFastOpenPassiveFail remains 0. */ #define _GNU_SOURCE #include <arpa/inet.h> #include <errno.h> #include <error.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <unistd.h> #include <netinet/tcp.h> #include <fcntl.h> #include <time.h> #include "../kselftest.h" #ifndef TCP_FASTOPEN_KEY #define TCP_FASTOPEN_KEY 33 #endif #define N_LISTEN 10 #define PROC_FASTOPEN_KEY "/proc/sys/net/ipv4/tcp_fastopen_key" #define KEY_LENGTH 16 static bool do_ipv6; static bool do_sockopt; static bool do_rotate; static int key_len = KEY_LENGTH; static int rcv_fds[N_LISTEN]; static int proc_fd; static const char *IP4_ADDR = "127.0.0.1"; static const char *IP6_ADDR = "::1"; static const int PORT = 8891; static void get_keys(int fd, uint32_t *keys) { char buf[128]; socklen_t len = KEY_LENGTH * 2; if (do_sockopt) { if (getsockopt(fd, SOL_TCP, TCP_FASTOPEN_KEY, keys, &len)) error(1, errno, "Unable to get key"); return; } lseek(proc_fd, 0, SEEK_SET); if (read(proc_fd, buf, sizeof(buf)) <= 0) error(1, errno, "Unable to read %s", PROC_FASTOPEN_KEY); if (sscanf(buf, "%x-%x-%x-%x,%x-%x-%x-%x", keys, keys + 1, keys + 2, keys + 3, keys + 4, keys + 5, keys + 6, keys + 7) != 8) error(1, 0, "Unable to parse %s", PROC_FASTOPEN_KEY); } static void set_keys(int fd, uint32_t *keys) { char buf[128]; if (do_sockopt) { if (setsockopt(fd, SOL_TCP, TCP_FASTOPEN_KEY, keys, key_len)) error(1, errno, "Unable to set key"); return; } if (do_rotate) snprintf(buf, 128, "%08x-%08x-%08x-%08x,%08x-%08x-%08x-%08x", keys[0], keys[1], keys[2], keys[3], keys[4], keys[5], keys[6], keys[7]); else snprintf(buf, 128, "%08x-%08x-%08x-%08x", keys[0], keys[1], keys[2], keys[3]); lseek(proc_fd, 0, SEEK_SET); if (write(proc_fd, buf, sizeof(buf)) <= 0) error(1, errno, "Unable to write %s", PROC_FASTOPEN_KEY); } static void build_rcv_fd(int family, int proto, int *rcv_fds) { struct sockaddr_in addr4 = {0}; struct sockaddr_in6 addr6 = {0}; struct sockaddr *addr; int opt = 1, i, sz; int qlen = 100; uint32_t keys[8]; switch (family) { case AF_INET: addr4.sin_family = family; addr4.sin_addr.s_addr = htonl(INADDR_ANY); addr4.sin_port = htons(PORT); sz = sizeof(addr4); addr = (struct sockaddr *)&addr4; break; case AF_INET6: addr6.sin6_family = AF_INET6; addr6.sin6_addr = in6addr_any; addr6.sin6_port = htons(PORT); sz = sizeof(addr6); addr = (struct sockaddr *)&addr6; break; default: error(1, 0, "Unsupported family %d", family); /* clang does not recognize error() above as terminating * the program, so it complains that saddr, sz are * not initialized when this code path is taken. Silence it. */ return; } for (i = 0; i < ARRAY_SIZE(keys); i++) keys[i] = rand(); for (i = 0; i < N_LISTEN; i++) { rcv_fds[i] = socket(family, proto, 0); if (rcv_fds[i] < 0) error(1, errno, "failed to create receive socket"); if (setsockopt(rcv_fds[i], SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) error(1, errno, "failed to set SO_REUSEPORT"); if (bind(rcv_fds[i], addr, sz)) error(1, errno, "failed to bind receive socket"); if (setsockopt(rcv_fds[i], SOL_TCP, TCP_FASTOPEN, &qlen, sizeof(qlen))) error(1, errno, "failed to set TCP_FASTOPEN"); set_keys(rcv_fds[i], keys); if (proto == SOCK_STREAM && listen(rcv_fds[i], 10)) error(1, errno, "failed to listen on receive port"); } } static int connect_and_send(int family, int proto) { struct sockaddr_in saddr4 = {0}; struct sockaddr_in daddr4 = {0}; struct sockaddr_in6 saddr6 = {0}; struct sockaddr_in6 daddr6 = {0}; struct sockaddr *saddr, *daddr; int fd, sz, ret; char data[1]; switch (family) { case AF_INET: saddr4.sin_family = AF_INET; saddr4.sin_addr.s_addr = htonl(INADDR_ANY); saddr4.sin_port = 0; daddr4.sin_family = AF_INET; if (!inet_pton(family, IP4_ADDR, &daddr4.sin_addr.s_addr)) error(1, errno, "inet_pton failed: %s", IP4_ADDR); daddr4.sin_port = htons(PORT); sz = sizeof(saddr4); saddr = (struct sockaddr *)&saddr4; daddr = (struct sockaddr *)&daddr4; break; case AF_INET6: saddr6.sin6_family = AF_INET6; saddr6.sin6_addr = in6addr_any; daddr6.sin6_family = AF_INET6; if (!inet_pton(family, IP6_ADDR, &daddr6.sin6_addr)) error(1, errno, "inet_pton failed: %s", IP6_ADDR); daddr6.sin6_port = htons(PORT); sz = sizeof(saddr6); saddr = (struct sockaddr *)&saddr6; daddr = (struct sockaddr *)&daddr6; break; default: error(1, 0, "Unsupported family %d", family); /* clang does not recognize error() above as terminating * the program, so it complains that saddr, daddr, sz are * not initialized when this code path is taken. Silence it. */ return -1; } fd = socket(family, proto, 0); if (fd < 0) error(1, errno, "failed to create send socket"); if (bind(fd, saddr, sz)) error(1, errno, "failed to bind send socket"); data[0] = 'a'; ret = sendto(fd, data, 1, MSG_FASTOPEN, daddr, sz); if (ret != 1) error(1, errno, "failed to sendto"); return fd; } static bool is_listen_fd(int fd) { int i; for (i = 0; i < N_LISTEN; i++) { if (rcv_fds[i] == fd) return true; } return false; } static void rotate_key(int fd) { static int iter; static uint32_t new_key[4]; uint32_t keys[8]; uint32_t tmp_key[4]; int i; if (iter < N_LISTEN) { /* first set new key as backups */ if (iter == 0) { for (i = 0; i < ARRAY_SIZE(new_key); i++) new_key[i] = rand(); } get_keys(fd, keys); memcpy(keys + 4, new_key, KEY_LENGTH); set_keys(fd, keys); } else { /* swap the keys */ get_keys(fd, keys); memcpy(tmp_key, keys + 4, KEY_LENGTH); memcpy(keys + 4, keys, KEY_LENGTH); memcpy(keys, tmp_key, KEY_LENGTH); set_keys(fd, keys); } if (++iter >= (N_LISTEN * 2)) iter = 0; } static void run_one_test(int family) { struct epoll_event ev; int i, send_fd; int n_loops = 10000; int rotate_key_fd = 0; int key_rotate_interval = 50; int fd, epfd; char buf[1]; build_rcv_fd(family, SOCK_STREAM, rcv_fds); epfd = epoll_create(1); if (epfd < 0) error(1, errno, "failed to create epoll"); ev.events = EPOLLIN; for (i = 0; i < N_LISTEN; i++) { ev.data.fd = rcv_fds[i]; if (epoll_ctl(epfd, EPOLL_CTL_ADD, rcv_fds[i], &ev)) error(1, errno, "failed to register sock epoll"); } while (n_loops--) { send_fd = connect_and_send(family, SOCK_STREAM); if (do_rotate && ((n_loops % key_rotate_interval) == 0)) { rotate_key(rcv_fds[rotate_key_fd]); if (++rotate_key_fd >= N_LISTEN) rotate_key_fd = 0; } while (1) { i = epoll_wait(epfd, &ev, 1, -1); if (i < 0) error(1, errno, "epoll_wait failed"); if (is_listen_fd(ev.data.fd)) { fd = accept(ev.data.fd, NULL, NULL); if (fd < 0) error(1, errno, "failed to accept"); ev.data.fd = fd; if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev)) error(1, errno, "failed epoll add"); continue; } i = recv(ev.data.fd, buf, sizeof(buf), 0); if (i != 1) error(1, errno, "failed recv data"); if (epoll_ctl(epfd, EPOLL_CTL_DEL, ev.data.fd, NULL)) error(1, errno, "failed epoll del"); close(ev.data.fd); break; } close(send_fd); } for (i = 0; i < N_LISTEN; i++) close(rcv_fds[i]); } static void parse_opts(int argc, char **argv) { int c; while ((c = getopt(argc, argv, "46sr")) != -1) { switch (c) { case '4': do_ipv6 = false; break; case '6': do_ipv6 = true; break; case 's': do_sockopt = true; break; case 'r': do_rotate = true; key_len = KEY_LENGTH * 2; break; default: error(1, 0, "%s: parse error", argv[0]); } } } int main(int argc, char **argv) { parse_opts(argc, argv); proc_fd = open(PROC_FASTOPEN_KEY, O_RDWR); if (proc_fd < 0) error(1, errno, "Unable to open %s", PROC_FASTOPEN_KEY); srand(time(NULL)); if (do_ipv6) run_one_test(AF_INET6); else run_one_test(AF_INET); close(proc_fd); fprintf(stderr, "PASS\n"); return 0; }
linux-master
tools/testing/selftests/net/tcp_fastopen_backup_key.c
// SPDX-License-Identifier: GPL-2.0 /* * This times how long it takes to bind to a port when the port already * has multiple sockets in its bhash table. * * In the setup(), we populate the port's bhash table with * MAX_THREADS * MAX_CONNECTIONS number of entries. */ #include <unistd.h> #include <stdio.h> #include <netdb.h> #include <pthread.h> #include <string.h> #include <stdbool.h> #define MAX_THREADS 600 #define MAX_CONNECTIONS 40 static const char *setup_addr_v6 = "::1"; static const char *setup_addr_v4 = "127.0.0.1"; static const char *setup_addr; static const char *bind_addr; static const char *port; bool use_v6; int ret; static int fd_array[MAX_THREADS][MAX_CONNECTIONS]; static int bind_socket(int opt, const char *addr) { struct addrinfo *res, hint = {}; int sock_fd, reuse = 1, err; int domain = use_v6 ? AF_INET6 : AF_INET; sock_fd = socket(domain, SOCK_STREAM, 0); if (sock_fd < 0) { perror("socket fd err"); return sock_fd; } hint.ai_family = domain; hint.ai_socktype = SOCK_STREAM; err = getaddrinfo(addr, port, &hint, &res); if (err) { perror("getaddrinfo failed"); goto cleanup; } if (opt) { err = setsockopt(sock_fd, SOL_SOCKET, opt, &reuse, sizeof(reuse)); if (err) { perror("setsockopt failed"); goto cleanup; } } err = bind(sock_fd, res->ai_addr, res->ai_addrlen); if (err) { perror("failed to bind to port"); goto cleanup; } return sock_fd; cleanup: close(sock_fd); return err; } static void *setup(void *arg) { int sock_fd, i; int *array = (int *)arg; for (i = 0; i < MAX_CONNECTIONS; i++) { sock_fd = bind_socket(SO_REUSEADDR | SO_REUSEPORT, setup_addr); if (sock_fd < 0) { ret = sock_fd; pthread_exit(&ret); } array[i] = sock_fd; } return NULL; } int main(int argc, const char *argv[]) { int listener_fd, sock_fd, i, j; pthread_t tid[MAX_THREADS]; clock_t begin, end; if (argc != 4) { printf("Usage: listener <port> <ipv6 | ipv4> <bind-addr>\n"); return -1; } port = argv[1]; use_v6 = strcmp(argv[2], "ipv6") == 0; bind_addr = argv[3]; setup_addr = use_v6 ? setup_addr_v6 : setup_addr_v4; listener_fd = bind_socket(SO_REUSEADDR | SO_REUSEPORT, setup_addr); if (listen(listener_fd, 100) < 0) { perror("listen failed"); return -1; } /* Set up threads to populate the bhash table entry for the port */ for (i = 0; i < MAX_THREADS; i++) pthread_create(&tid[i], NULL, setup, fd_array[i]); for (i = 0; i < MAX_THREADS; i++) pthread_join(tid[i], NULL); if (ret) goto done; begin = clock(); /* Bind to the same port on a different address */ sock_fd = bind_socket(0, bind_addr); if (sock_fd < 0) goto done; end = clock(); printf("time spent = %f\n", (double)(end - begin) / CLOCKS_PER_SEC); /* clean up */ close(sock_fd); done: close(listener_fd); for (i = 0; i < MAX_THREADS; i++) { for (j = 0; i < MAX_THREADS; i++) close(fd_array[i][j]); } return 0; }
linux-master
tools/testing/selftests/net/bind_bhash.c
// SPDX-License-Identifier: GPL-2.0 /* * Verify that consecutive sends over packet tx_ring are mirrored * with their original content intact. */ #define _GNU_SOURCE #include <arpa/inet.h> #include <assert.h> #include <error.h> #include <errno.h> #include <fcntl.h> #include <linux/filter.h> #include <linux/if_packet.h> #include <net/ethernet.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <poll.h> #include <pthread.h> #include <sched.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <sys/utsname.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> const int eth_off = TPACKET_HDRLEN - sizeof(struct sockaddr_ll); const int cfg_frame_size = 1000; static void build_packet(void *buffer, size_t blen, char payload_char) { struct udphdr *udph; struct ethhdr *eth; struct iphdr *iph; size_t off = 0; memset(buffer, 0, blen); eth = buffer; eth->h_proto = htons(ETH_P_IP); off += sizeof(*eth); iph = buffer + off; iph->ttl = 8; iph->ihl = 5; iph->version = 4; iph->saddr = htonl(INADDR_LOOPBACK); iph->daddr = htonl(INADDR_LOOPBACK + 1); iph->protocol = IPPROTO_UDP; iph->tot_len = htons(blen - off); iph->check = 0; off += sizeof(*iph); udph = buffer + off; udph->dest = htons(8000); udph->source = htons(8001); udph->len = htons(blen - off); udph->check = 0; off += sizeof(*udph); memset(buffer + off, payload_char, blen - off); } static int setup_rx(void) { int fdr; fdr = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP)); if (fdr == -1) error(1, errno, "socket r"); return fdr; } static int setup_tx(char **ring) { struct sockaddr_ll laddr = {}; struct tpacket_req req = {}; int fdt; fdt = socket(PF_PACKET, SOCK_RAW, 0); if (fdt == -1) error(1, errno, "socket t"); laddr.sll_family = AF_PACKET; laddr.sll_protocol = htons(0); laddr.sll_ifindex = if_nametoindex("lo"); if (!laddr.sll_ifindex) error(1, errno, "if_nametoindex"); if (bind(fdt, (void *)&laddr, sizeof(laddr))) error(1, errno, "bind fdt"); req.tp_block_size = getpagesize(); req.tp_block_nr = 1; req.tp_frame_size = getpagesize(); req.tp_frame_nr = 1; if (setsockopt(fdt, SOL_PACKET, PACKET_TX_RING, (void *)&req, sizeof(req))) error(1, errno, "setsockopt ring"); *ring = mmap(0, req.tp_block_size * req.tp_block_nr, PROT_READ | PROT_WRITE, MAP_SHARED, fdt, 0); if (*ring == MAP_FAILED) error(1, errno, "mmap"); return fdt; } static void send_pkt(int fdt, void *slot, char payload_char) { struct tpacket_hdr *header = slot; int ret; while (header->tp_status != TP_STATUS_AVAILABLE) usleep(1000); build_packet(slot + eth_off, cfg_frame_size, payload_char); header->tp_len = cfg_frame_size; header->tp_status = TP_STATUS_SEND_REQUEST; ret = sendto(fdt, NULL, 0, 0, NULL, 0); if (ret == -1) error(1, errno, "kick tx"); } static int read_verify_pkt(int fdr, char payload_char) { char buf[100]; int ret; ret = read(fdr, buf, sizeof(buf)); if (ret != sizeof(buf)) error(1, errno, "read"); if (buf[60] != payload_char) { printf("wrong pattern: 0x%x != 0x%x\n", buf[60], payload_char); return 1; } printf("read: %c (0x%x)\n", buf[60], buf[60]); return 0; } int main(int argc, char **argv) { const char payload_patterns[] = "ab"; char *ring; int fdr, fdt, ret = 0; fdr = setup_rx(); fdt = setup_tx(&ring); send_pkt(fdt, ring, payload_patterns[0]); send_pkt(fdt, ring, payload_patterns[1]); ret |= read_verify_pkt(fdr, payload_patterns[0]); ret |= read_verify_pkt(fdr, payload_patterns[1]); if (close(fdt)) error(1, errno, "close t"); if (close(fdr)) error(1, errno, "close r"); return ret; }
linux-master
tools/testing/selftests/net/txring_overwrite.c