1 // SPDX-License-Identifier: GPL-2.0-only 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 #include "../../../kselftest.h" 7 #include <libvfio.h> 8 9 static bool is_bdf(const char *str) 10 { 11 unsigned int s, b, d, f; 12 int length, count; 13 14 count = sscanf(str, "%4x:%2x:%2x.%2x%n", &s, &b, &d, &f, &length); 15 return count == 4 && length == strlen(str); 16 } 17 18 static char **get_bdfs_cmdline(int *argc, char *argv[], int *nr_bdfs) 19 { 20 int i; 21 22 for (i = *argc - 1; i > 0 && is_bdf(argv[i]); i--) 23 continue; 24 25 i++; 26 *nr_bdfs = *argc - i; 27 *argc -= *nr_bdfs; 28 29 return *nr_bdfs ? &argv[i] : NULL; 30 } 31 32 static char *get_bdf_env(void) 33 { 34 char *bdf; 35 36 bdf = getenv("VFIO_SELFTESTS_BDF"); 37 if (!bdf) 38 return NULL; 39 40 VFIO_ASSERT_TRUE(is_bdf(bdf), "Invalid BDF: %s\n", bdf); 41 return bdf; 42 } 43 44 char **vfio_selftests_get_bdfs(int *argc, char *argv[], int *nr_bdfs) 45 { 46 static char *env_bdf; 47 char **bdfs; 48 49 bdfs = get_bdfs_cmdline(argc, argv, nr_bdfs); 50 if (bdfs) 51 return bdfs; 52 53 env_bdf = get_bdf_env(); 54 if (env_bdf) { 55 *nr_bdfs = 1; 56 return &env_bdf; 57 } 58 59 fprintf(stderr, "Unable to determine which device(s) to use, skipping test.\n"); 60 fprintf(stderr, "\n"); 61 fprintf(stderr, "To pass the device address via environment variable:\n"); 62 fprintf(stderr, "\n"); 63 fprintf(stderr, " export VFIO_SELFTESTS_BDF=\"segment:bus:device.function\"\n"); 64 fprintf(stderr, " %s [options]\n", argv[0]); 65 fprintf(stderr, "\n"); 66 fprintf(stderr, "To pass the device address(es) via argv:\n"); 67 fprintf(stderr, "\n"); 68 fprintf(stderr, " %s [options] segment:bus:device.function ...\n", argv[0]); 69 fprintf(stderr, "\n"); 70 exit(KSFT_SKIP); 71 } 72 73 const char *vfio_selftests_get_bdf(int *argc, char *argv[]) 74 { 75 int nr_bdfs; 76 77 return vfio_selftests_get_bdfs(argc, argv, &nr_bdfs)[0]; 78 } 79