xref: /freebsd/sys/contrib/openzfs/tests/zfs-tests/cmd/file/file_fadvise.c (revision 1bb8b1d7e190d75597d31ab87364a058e8ef8c5b)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 /*
29  * Copyright (c) 2022 by Information2 Software, Inc. All rights reserved.
30  */
31 
32 #include "file_common.h"
33 #include <sys/types.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <string.h>
37 
38 /*
39  * Call fadvise to prefetch data
40  */
41 static const char *execname = "file_fadvise";
42 
43 static void
44 usage(void)
45 {
46 	(void) fprintf(stderr,
47 	    "usage: %s -f filename -a advise \n", execname);
48 }
49 
50 int
51 main(int argc, char *argv[])
52 {
53 	char *filename = NULL;
54 	int advise = 0;
55 	int fd, ch;
56 	int	err = 0;
57 
58 	while ((ch = getopt(argc, argv, "a:f:")) != EOF) {
59 		switch (ch) {
60 		case 'a':
61 			advise = atoll(optarg);
62 			break;
63 		case 'f':
64 			filename = optarg;
65 			break;
66 		case '?':
67 			(void) printf("unknown arg %c\n", optopt);
68 			usage();
69 			break;
70 		}
71 	}
72 
73 	if (!filename) {
74 		(void) printf("Filename not specified (-f <file>)\n");
75 		err++;
76 	}
77 
78 	if (advise < POSIX_FADV_NORMAL || advise > POSIX_FADV_NOREUSE) {
79 		(void) printf("advise is invalid\n");
80 		err++;
81 	}
82 
83 	if (err) {
84 		usage(); /* no return */
85 		return (1);
86 	}
87 
88 	if ((fd = open(filename, O_RDWR, 0666)) < 0) {
89 		perror("open");
90 		return (1);
91 	}
92 
93 	if (posix_fadvise(fd, 0, 0, advise) != 0) {
94 		perror("posix_fadvise");
95 		close(fd);
96 		return (1);
97 	}
98 
99 	close(fd);
100 
101 	return (0);
102 }
103