xref: /original-bsd/lib/libc/db/recno/rec_close.c (revision daedb501)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)rec_close.c	5.4 (Berkeley) 07/17/92";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/param.h>
13 #include <sys/uio.h>
14 #include <errno.h>
15 #include <db.h>
16 #include <unistd.h>
17 #include <stdio.h>
18 #include "recno.h"
19 
20 /*
21  * __REC_CLOSE -- Close a recno tree.
22  *
23  * Parameters:
24  *	dbp:	pointer to access method
25  *
26  * Returns:
27  *	RET_ERROR, RET_SUCCESS
28  */
29 int
30 __rec_close(dbp)
31 	DB *dbp;
32 {
33 	BTREE *t;
34 	int rval;
35 
36 	if (__rec_sync(dbp) == RET_ERROR)
37 		return (RET_ERROR);
38 
39 	/* Committed to closing. */
40 	t = dbp->internal;
41 	rval = t->bt_rfp == NULL ? close(t->bt_rfd) : fclose(t->bt_rfp);
42 
43 	if (__bt_close(dbp) == RET_ERROR)
44 		return (RET_ERROR);
45 
46 	return (rval ? RET_ERROR : RET_SUCCESS);
47 }
48 
49 /*
50  * __REC_SYNC -- sync the recno tree to disk.
51  *
52  * Parameters:
53  *	dbp:	pointer to access method
54  *
55  * Returns:
56  *	RET_SUCCESS, RET_ERROR.
57  *
58  * XXX
59  * Currently don't handle a key marked for deletion when the tree is synced.
60  * Should copy the page and write it out instead of the real page.
61  */
62 int
63 __rec_sync(dbp)
64 	const DB *dbp;
65 {
66 	struct iovec iov[2];
67 	BTREE *t;
68 	DBT data, key;
69 	off_t off;
70 	recno_t scursor, trec;
71 	int status;
72 
73 	t = dbp->internal;
74 
75 	if (ISSET(t, BTF_INMEM) || NOTSET(t, BTF_MODIFIED))
76 		return (RET_SUCCESS);
77 
78 	if (ISSET(t, BTF_RDONLY)) {
79 		errno = EPERM;
80 		return (RET_ERROR);
81 	}
82 
83 	/* Suck any remaining records into the tree. */
84 	if (t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR)
85 		return (RET_ERROR);
86 
87 	/* Rewind the file descriptor. */
88 	if (lseek(t->bt_rfd, (off_t)0, SEEK_SET) != 0L)
89 		return (RET_ERROR);
90 
91 	iov[1].iov_base = "\n";
92 	iov[1].iov_len = 1;
93 	scursor = t->bt_rcursor;
94 
95 	key.size = sizeof(recno_t);
96 	key.data = &trec;
97 
98 	status = (dbp->seq)(dbp, &key, &data, R_FIRST);
99         while (status == RET_SUCCESS) {
100 		iov[0].iov_base = data.data;
101 		iov[0].iov_len = data.size;
102 		if (writev(t->bt_rfd, iov, 2) != data.size + 1)
103 			return (RET_ERROR);
104                 status = (dbp->seq)(dbp, &key, &data, R_NEXT);
105         }
106 	t->bt_rcursor = scursor;
107 	if (status == RET_ERROR)
108 		return (RET_ERROR);
109 	if ((off = lseek(t->bt_rfd, (off_t)0, SEEK_CUR)) == -1)
110 		return (RET_ERROR);
111 	if (ftruncate(t->bt_rfd, off))
112 		return (RET_ERROR);
113 	UNSET(t, BTF_MODIFIED);
114 	return (RET_SUCCESS);
115 }
116