Path: blob/main/sys/contrib/openzfs/tests/zfs-tests/cmd/mmap_ftruncate.c
48529 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* Common Development and Distribution License (the "License").6* You may not use this file except in compliance with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or http://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/2122/*23* Copyright (c) 2025, Klara, Inc.24*/2526/*27* Tests async writeback behaviour. Creates a file, maps it into memory, and28* dirties every page within it. Then, calls ftruncate() to collapse the file29* back down to 0. This causes the kernel to begin writeback on the dirty30* pages so they can be freed, before it can complete the ftruncate() call.31* None of these are sync operations, so they should avoid the various "force32* flush" codepaths.33*/3435#include <unistd.h>36#include <fcntl.h>37#include <sys/stat.h>38#include <sys/mman.h>39#include <stdlib.h>40#include <stdio.h>4142#define _pdfail(f, l, s) \43do { perror("[" f "#" #l "] " s); exit(2); } while (0)44#define pdfail(str) _pdfail(__FILE__, __LINE__, str)4546int47main(int argc, char **argv) {48if (argc != 3) {49printf("usage: mmap_ftruncate <file> <size>\n");50exit(2);51}5253const char *file = argv[1];5455char *end;56off_t sz = strtoull(argv[2], &end, 0);57if (end == argv[2] || *end != '\0' || sz == 0) {58fprintf(stderr, "E: invalid size");59exit(2);60}6162int fd = open(file, O_CREAT|O_TRUNC|O_RDWR, S_IRUSR|S_IWUSR);63if (fd < 0)64pdfail("open");6566if (ftruncate(fd, sz) < 0)67pdfail("ftruncate");6869char *p = mmap(NULL, sz, PROT_WRITE, MAP_SHARED, fd, 0);70if (p == MAP_FAILED)71pdfail("mmap");7273for (off_t off = 0; off < sz; off += 4096)74p[off] = 1;7576if (ftruncate(fd, 0) < 0)77pdfail("ftruncate");7879if (munmap(p, sz) < 0)80pdfail("munmap");8182close(fd);83return (0);84}858687