Path: blob/main/tests/host_tools/change_net_config_space.c
1956 views
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.1// SPDX-License-Identifier: Apache-2.023// This is used by the `test_net_config_space.py` integration test, which writes4// into the microVM configured network device config space a new MAC address.56#include <fcntl.h>7#include <stdio.h>8#include <stdlib.h>9#include <stdint.h>10#include <sys/mman.h>11#include <sys/types.h>12#include <sys/stat.h>13#include <unistd.h>1415int show_usage() {16printf("Usage: ./change_net_config_space.bin [dev_addr_start] [mac_addr]\n");17printf("Example:\n");18printf("> ./change_net_config_space.bin 0xd00001000 0x060504030201\n");19return 0;20}2122int main(int argc, char *argv[]) {23int fd, i, offset;24uint8_t *map_base;25volatile uint8_t *virt_addr;2627uint64_t mapped_size, page_size, offset_in_page, target;28uint64_t width = 6;2930uint64_t config_offset = 0x100;31uint64_t device_start_addr = 0x00000000;32uint64_t mac = 0;3334if (argc != 3) {35return show_usage();36}3738device_start_addr = strtoull(argv[1], NULL, 0);39mac = strtoull(argv[2], NULL, 0);4041fd = open("/dev/mem", O_RDWR | O_SYNC);42if (fd < 0) {43perror("Failed to open '/dev/mem'.");44return 1;45}4647target = device_start_addr + config_offset;48// Get the page size.49mapped_size = page_size = getpagesize();50// Get the target address physical frame page offset.51offset_in_page = (unsigned) target & (page_size - 1);52/* If the data length goes out of the current page,53* double the needed map size. */54if (offset_in_page + width > page_size) {55/* This access spans pages.56* Must map two pages to make it possible. */57mapped_size *= 2;58}5960// Map the `/dev/mem` to virtual memory.61map_base = mmap(NULL,62mapped_size,63PROT_READ | PROT_WRITE,64MAP_SHARED,65fd,66target & ~(off_t)(page_size - 1));67if (map_base == MAP_FAILED) {68perror("Failed to mmap '/dev/mem'.");69return 2;70}7172// Write in the network device config space a new MAC.73virt_addr = (volatile uint8_t*) (map_base + offset_in_page);74*virt_addr = (uint8_t) (mac >> 40);75printf("%02x", *virt_addr);7677for (i = 1; i <= 5; i++) {78*(virt_addr + i) = (uint8_t) (mac >> (5 - i) * 8);79printf(":%02x", *(virt_addr + i));80}8182// Deallocate resources.83munmap(map_base, mapped_size);84close(fd);8586return 0;87}888990