]> git.proxmox.com Git - mirror_zfs.git/blob - tests/zfs-tests/cmd/randfree_file/randfree_file.c
8e7487c41e779e60e69e73dbf8937261c5ce12db
[mirror_zfs.git] / tests / zfs-tests / cmd / randfree_file / randfree_file.c
1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * 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.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22 /*
23 * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
25 */
26
27 /*
28 * Copyright (c) 2012 by Delphix. All rights reserved.
29 */
30
31 #include "../file_common.h"
32 #include <sys/types.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <linux/falloc.h>
36
37 /*
38 * Create a file with assigned size and then free the specified
39 * section of the file
40 */
41
42 static void usage(char *progname);
43
44 static void
45 usage(char *progname)
46 {
47 (void) fprintf(stderr,
48 "usage: %s [-l filesize] [-s start-offset]"
49 "[-n section-len] filename\n", progname);
50 exit(1);
51 }
52
53 int
54 main(int argc, char *argv[])
55 {
56 char *filename = NULL;
57 char *buf;
58 size_t filesize = 0;
59 off_t start_off = 0;
60 off_t off_len = 0;
61 int fd, ch;
62 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
63
64 while ((ch = getopt(argc, argv, "l:s:n:")) != EOF) {
65 switch (ch) {
66 case 'l':
67 filesize = atoll(optarg);
68 break;
69 case 's':
70 start_off = atoll(optarg);
71 break;
72 case 'n':
73 off_len = atoll(optarg);
74 break;
75 default:
76 usage(argv[0]);
77 break;
78 }
79 }
80
81 if (optind == argc - 1)
82 filename = argv[optind];
83 else
84 usage(argv[0]);
85
86 buf = (char *)malloc(filesize);
87
88 if ((fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, mode)) < 0) {
89 perror("open");
90 return (1);
91 }
92 if (write(fd, buf, filesize) < filesize) {
93 perror("write");
94 return (1);
95 }
96
97 if (fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
98 start_off, off_len) < 0) {
99 perror("fallocate");
100 return (1);
101 }
102
103 free(buf);
104 return (0);
105 }