Path: blob/main/sys/contrib/openzfs/tests/zfs-tests/cmd/file/randfree_file.c
48676 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 https://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 2007 Sun Microsystems, Inc. All rights reserved.24* Use is subject to license terms.25*/2627/*28* Copyright (c) 2012 by Delphix. All rights reserved.29*/3031#include "file_common.h"32#include <sys/types.h>33#include <unistd.h>34#include <fcntl.h>35#include <string.h>36#include <linux/falloc.h>3738/*39* Create a file with assigned size and then free the specified40* section of the file41*/4243static void usage(char *progname);4445static void46usage(char *progname)47{48(void) fprintf(stderr,49"usage: %s [-l filesize] [-s start-offset]"50"[-n section-len] filename\n", progname);51exit(1);52}5354int55main(int argc, char *argv[])56{57char *filename = NULL;58char *buf = NULL;59size_t filesize = 0;60off_t start_off = 0;61off_t off_len = 0;62int fd, ch;63mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;6465while ((ch = getopt(argc, argv, "l:s:n:")) != EOF) {66switch (ch) {67case 'l':68filesize = atoll(optarg);69break;70case 's':71start_off = atoll(optarg);72break;73case 'n':74off_len = atoll(optarg);75break;76default:77usage(argv[0]);78break;79}80}8182if (optind == argc - 1)83filename = argv[optind];84else85usage(argv[0]);8687if ((fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, mode)) < 0) {88perror("open");89return (1);90}9192buf = (char *)calloc(1, filesize);93if (buf == NULL) {94perror("write");95close(fd);96return (1);97}98memset(buf, 'c', filesize);99100if (write(fd, buf, filesize) < filesize) {101free(buf);102perror("write");103close(fd);104return (1);105}106107free(buf);108109#if defined(FALLOC_FL_PUNCH_HOLE) && defined(FALLOC_FL_KEEP_SIZE)110if (fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,111start_off, off_len) < 0) {112perror("fallocate");113close(fd);114return (1);115}116#else /* !(defined(FALLOC_FL_PUNCH_HOLE) && defined(FALLOC_FL_KEEP_SIZE)) */117{118perror("FALLOC_FL_PUNCH_HOLE unsupported");119close(fd);120return (1);121}122#endif /* defined(FALLOC_FL_PUNCH_HOLE) && defined(FALLOC_FL_KEEP_SIZE) */123close(fd);124return (0);125}126127128