xref: /illumos-gate/usr/src/lib/libc/port/gen/posix_fallocate.c (revision 89b2a9fbeabf42fa54594df0e5927bcc50a07cc9)
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 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include "lint.h"
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 
35 /*
36  * Return the proper Posix error number for a failed (EINVAL) fcntl() operation.
37  */
38 static int
39 fallocate_errno(int fd)
40 {
41 	struct stat64 statb;
42 	int error;
43 
44 	if (fstat64(fd, &statb) != 0)		/* can't happen? */
45 		error = EBADF;
46 	else if (S_ISFIFO(statb.st_mode))	/* pipe or FIFO */
47 		error = ESPIPE;
48 	else if (!S_ISREG(statb.st_mode))	/* not a regular file */
49 		error = ENODEV;
50 	else			/* the file system doesn't support F_ALLOCSP */
51 		error = EINVAL;
52 
53 	return (error);
54 }
55 
56 int
57 posix_fallocate(int fd, off_t offset, off_t len)
58 {
59 	struct flock lck;
60 	int error;
61 
62 	if (offset < 0 || len <= 0)
63 		return (EINVAL);
64 
65 	lck.l_whence = 0;
66 	lck.l_start = offset;
67 	lck.l_len = len;
68 	lck.l_type = F_WRLCK;
69 
70 	if (fcntl(fd, F_ALLOCSP, &lck) == -1) {
71 		if ((error = errno) == EINVAL)
72 			error = fallocate_errno(fd);
73 		else if (error == EOVERFLOW)
74 			error = EFBIG;
75 		return (error);
76 	}
77 	return (0);
78 }
79 
80 #if !defined(_LP64)
81 
82 int
83 posix_fallocate64(int fd, off64_t offset, off64_t len)
84 {
85 	struct flock64 lck;
86 	int error;
87 
88 	if (offset < 0 || len <= 0)
89 		return (EINVAL);
90 
91 	lck.l_whence = 0;
92 	lck.l_start = offset;
93 	lck.l_len = len;
94 	lck.l_type = F_WRLCK;
95 
96 	if (fcntl(fd, F_ALLOCSP64, &lck) == -1) {
97 		if ((error = errno) == EINVAL)
98 			error = fallocate_errno(fd);
99 		else if (error == EOVERFLOW)
100 			error = EFBIG;
101 		return (error);
102 	}
103 	return (0);
104 }
105 
106 #endif
107