xref: /freebsd/sys/contrib/openzfs/tests/zfs-tests/cmd/file/file_fadvise.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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 https://opensource.org/licenses/CDDL-1.0.
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) 2022 by Information2 Software, Inc. 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 <string.h>
36 
37 /*
38  * Call fadvise to prefetch data
39  */
40 static const char *execname = "file_fadvise";
41 
42 static void
43 usage(void)
44 {
45 	(void) fprintf(stderr,
46 	    "usage: %s -f filename -a advise \n", execname);
47 }
48 
49 int
50 main(int argc, char *argv[])
51 {
52 	char *filename = NULL;
53 	int advise = 0;
54 	int fd, ch;
55 	int	err = 0;
56 
57 	while ((ch = getopt(argc, argv, "a:f:")) != EOF) {
58 		switch (ch) {
59 		case 'a':
60 			advise = atoll(optarg);
61 			break;
62 		case 'f':
63 			filename = optarg;
64 			break;
65 		case '?':
66 			(void) printf("unknown arg %c\n", optopt);
67 			usage();
68 			break;
69 		}
70 	}
71 
72 	if (!filename) {
73 		(void) printf("Filename not specified (-f <file>)\n");
74 		err++;
75 	}
76 
77 	if (advise < POSIX_FADV_NORMAL || advise > POSIX_FADV_NOREUSE) {
78 		(void) printf("advise is invalid\n");
79 		err++;
80 	}
81 
82 	if (err) {
83 		usage(); /* no return */
84 		return (1);
85 	}
86 
87 	if ((fd = open(filename, O_RDWR, 0666)) < 0) {
88 		perror("open");
89 		return (1);
90 	}
91 
92 	if (posix_fadvise(fd, 0, 0, advise) != 0) {
93 		perror("posix_fadvise");
94 		close(fd);
95 		return (1);
96 	}
97 
98 	close(fd);
99 
100 	return (0);
101 }
102