xref: /titanic_50/usr/src/lib/libbc/libc/compat/common/lockf.c (revision 672986541be54a7a471bb088e60780c37e371d7e)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
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  * Copyright 1989 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*      Copyright (c) 1984 AT&T */
28 /*        All Rights Reserved   */
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <errno.h>
35 #include <sys/syscall.h>
36 
37 /*
38  * convert lockf() into fcntl() for SystemV compatibility
39  */
40 
41 /* New SVR4 values */
42 #define SV_GETLK	5
43 #define SV_SETLK	6
44 #define SV_SETLKW	7
45 
46 int
47 lockf(int fildes, int function, long size)
48 {
49 	struct flock ld;
50 	int cmd;
51 
52 	cmd = SV_SETLK;		/* assume non-blocking operation */
53 	ld.l_type = F_WRLCK;	/* lockf() only deals with exclusive locks */
54 	ld.l_whence = 1;	/* lock always starts at current position */
55 	if (size < 0) {
56 		ld.l_start = size;
57 		ld.l_len = -size;
58 	} else {
59 		ld.l_start = 0L;
60 		ld.l_len = size;
61 	}
62 
63 	switch (function) {
64 	case F_TEST:
65 		if (_syscall(SYS_fcntl, fildes, SV_GETLK, &ld) != -1) {
66 			if (ld.l_type == F_UNLCK) {
67 				ld.l_pid = ld.l_xxx;
68 					/* l_pid is the last field in the
69 					   SVr3 flock structure */
70 				return (0);
71 			} else
72 				errno = EACCES;		/* EAGAIN ?? */
73 		}
74 		return (-1);
75 
76 	default:
77 		errno = EINVAL;
78 		return (-1);
79 
80 			/* the rest fall thru to the fcntl() at the end */
81 	case F_ULOCK:
82 		ld.l_type = F_UNLCK;
83 		break;
84 
85 	case F_LOCK:
86 		cmd = SV_SETLKW;	/* block, if not available */
87 		break;
88 
89 	case F_TLOCK:
90 		break;
91 	}
92 	if (_syscall(SYS_fcntl, fildes, cmd, &ld) == -1) {
93 		switch (errno) {
94 		/* this hack is purported to be for /usr/group compatibility */
95 		case ENOLCK:
96 			errno = EDEADLK;
97 		}
98 		return(-1);
99 	} else {
100 		ld.l_pid = ld.l_xxx;	/* l_pid is the last field in the
101 					   SVr3 flock structure */
102 		return(0);
103 	}
104 }
105