1/*	$NetBSD: du.c,v 1.33 2008/07/30 22:03:40 dsl Exp $	*/
2
3/*
4 * Copyright (c) 1989, 1993, 1994
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Chris Newcomb.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#include <sys/cdefs.h>
36#ifndef lint
37__COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\
38 The Regents of the University of California.  All rights reserved.");
39#endif /* not lint */
40
41#ifndef lint
42#if 0
43static char sccsid[] = "@(#)du.c	8.5 (Berkeley) 5/4/95";
44#else
45__RCSID("$NetBSD: du.c,v 1.33 2008/07/30 22:03:40 dsl Exp $");
46#endif
47#endif /* not lint */
48
49#include <sys/types.h>
50#include <sys/stat.h>
51
52#include <dirent.h>
53#include <err.h>
54#include <errno.h>
55#include <fts.h>
56#include <util.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60#include <unistd.h>
61#include <limits.h>
62
63int	linkchk(dev_t, ino_t);
64void	prstat(const char *, int64_t);
65void	usage(void);
66
67long blocksize;
68
69#define howmany(x, y)   (((x)+((y)-1))/(y))
70
71int
72du_main(int argc, char *argv[])
73{
74	FTS *fts;
75	FTSENT *p;
76	int64_t totalblocks;
77	int ftsoptions, listfiles;
78	int depth;
79	int Hflag, Lflag, aflag, ch, cflag, dflag, gkmflag, nflag, rval, sflag;
80	const char *noargv[2];
81
82	Hflag = Lflag = aflag = cflag = dflag = gkmflag = sflag = 0;
83	totalblocks = 0;
84	ftsoptions = FTS_PHYSICAL;
85	depth = INT_MAX;
86	while ((ch = getopt(argc, argv, "HLPacd:ghkmnrsx")) != -1)
87		switch (ch) {
88		case 'H':
89			Hflag = 1;
90			Lflag = 0;
91			break;
92		case 'L':
93			Lflag = 1;
94			Hflag = 0;
95			break;
96		case 'P':
97			Hflag = Lflag = 0;
98			break;
99		case 'a':
100			aflag = 1;
101			break;
102		case 'c':
103			cflag = 1;
104			break;
105		case 'd':
106			dflag = 1;
107			depth = atoi(optarg);
108			if (depth < 0 || depth > SHRT_MAX) {
109				warnx("invalid argument to option d: %s",
110					optarg);
111				usage();
112			}
113			break;
114		case 'g':
115			blocksize = 1024 * 1024 * 1024;
116			gkmflag = 1;
117			break;
118		case 'k':
119			blocksize = 1024;
120			gkmflag = 1;
121			break;
122		case 'm':
123			blocksize = 1024 * 1024;
124			gkmflag = 1;
125			break;
126		case 'r':
127			break;
128		case 's':
129			sflag = 1;
130			break;
131		case 'x':
132			ftsoptions |= FTS_XDEV;
133			break;
134		case '?':
135		default:
136			usage();
137		}
138	argc -= optind;
139	argv += optind;
140
141	/*
142	 * XXX
143	 * Because of the way that fts(3) works, logical walks will not count
144	 * the blocks actually used by symbolic links.  We rationalize this by
145	 * noting that users computing logical sizes are likely to do logical
146	 * copies, so not counting the links is correct.  The real reason is
147	 * that we'd have to re-implement the kernel's symbolic link traversing
148	 * algorithm to get this right.  If, for example, you have relative
149	 * symbolic links referencing other relative symbolic links, it gets
150	 * very nasty, very fast.  The bottom line is that it's documented in
151	 * the man page, so it's a feature.
152	 */
153	if (Hflag)
154		ftsoptions |= FTS_COMFOLLOW;
155	if (Lflag) {
156		ftsoptions &= ~FTS_PHYSICAL;
157		ftsoptions |= FTS_LOGICAL;
158	}
159
160	listfiles = 0;
161	if (aflag) {
162		if (sflag || dflag)
163			usage();
164		listfiles = 1;
165	} else if (sflag) {
166		if (dflag)
167			usage();
168		depth = 0;
169	}
170
171	if (!*argv) {
172		noargv[0] = ".";
173		noargv[1] = NULL;
174		argv = __UNCONST(noargv);
175	}
176
177	if (!gkmflag)
178		blocksize = 512;
179	blocksize /= 512;
180
181	if ((fts = fts_open(argv, ftsoptions, NULL)) == NULL)
182		err(1, "fts_open `%s'", *argv);
183
184	for (rval = 0; (p = fts_read(fts)) != NULL;) {
185		switch (p->fts_info) {
186		case FTS_D:			/* Ignore. */
187			break;
188		case FTS_DP:
189			p->fts_parent->fts_number +=
190			    p->fts_number += p->fts_statp->st_blocks;
191			if (cflag)
192				totalblocks += p->fts_statp->st_blocks;
193			/*
194			 * If listing each directory, or not listing files
195			 * or directories and this is post-order of the
196			 * root of a traversal, display the total.
197			 */
198			if (p->fts_level <= depth
199			    || (!listfiles && !p->fts_level))
200				prstat(p->fts_path, p->fts_number);
201			break;
202		case FTS_DC:			/* Ignore. */
203			break;
204		case FTS_DNR:			/* Warn, continue. */
205		case FTS_ERR:
206		case FTS_NS:
207			warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
208			rval = 1;
209			break;
210		default:
211			if (p->fts_statp->st_nlink > 1 &&
212			    linkchk(p->fts_statp->st_dev, p->fts_statp->st_ino))
213				break;
214			/*
215			 * If listing each file, or a non-directory file was
216			 * the root of a traversal, display the total.
217			 */
218			if (listfiles || !p->fts_level)
219				prstat(p->fts_path, p->fts_statp->st_blocks);
220			p->fts_parent->fts_number += p->fts_statp->st_blocks;
221			if (cflag)
222				totalblocks += p->fts_statp->st_blocks;
223		}
224	}
225	if (errno)
226		err(1, "fts_read");
227	if (cflag)
228		prstat("total", totalblocks);
229	exit(rval);
230}
231
232void
233prstat(const char *fname, int64_t blocks)
234{
235	(void)printf("%lld\t%s\n",
236	    (long long)howmany(blocks, (int64_t)blocksize),
237	    fname);
238}
239
240int
241linkchk(dev_t dev, ino_t ino)
242{
243	static struct entry {
244		dev_t	dev;
245		ino_t	ino;
246	} *htable;
247	static int htshift;  /* log(allocated size) */
248	static int htmask;   /* allocated size - 1 */
249	static int htused;   /* 2*number of insertions */
250	static int sawzero;  /* Whether zero is in table or not */
251	int h, h2;
252	uint64_t tmp;
253	/* this constant is (1<<64)/((1+sqrt(5))/2)
254	 * aka (word size)/(golden ratio)
255	 */
256	const uint64_t HTCONST = 11400714819323198485ULL;
257	const int HTBITS = CHAR_BIT * sizeof(tmp);
258
259	/* Never store zero in hashtable */
260	if (dev == 0 && ino == 0) {
261		h = sawzero;
262		sawzero = 1;
263		return h;
264	}
265
266	/* Extend hash table if necessary, keep load under 0.5 */
267	if (htused<<1 >= htmask) {
268		struct entry *ohtable;
269
270		if (!htable)
271			htshift = 10;   /* starting hashtable size */
272		else
273			htshift++;   /* exponential hashtable growth */
274
275		htmask  = (1 << htshift) - 1;
276		htused = 0;
277
278		ohtable = htable;
279		htable = calloc(htmask+1, sizeof(*htable));
280		if (!htable)
281			err(1, "calloc");
282
283		/* populate newly allocated hashtable */
284		if (ohtable) {
285			int i;
286			for (i = 0; i <= htmask>>1; i++)
287				if (ohtable[i].ino || ohtable[i].dev)
288					linkchk(ohtable[i].dev, ohtable[i].ino);
289			free(ohtable);
290		}
291	}
292
293	/* multiplicative hashing */
294	tmp = dev;
295	tmp <<= HTBITS>>1;
296	tmp |=  ino;
297	tmp *= HTCONST;
298	h  = tmp >> (HTBITS - htshift);
299	h2 = 1 | ( tmp >> (HTBITS - (htshift<<1) - 1)); /* must be odd */
300
301	/* open address hashtable search with double hash probing */
302	while (htable[h].ino || htable[h].dev) {
303		if ((htable[h].ino == ino) && (htable[h].dev == dev))
304			return 1;
305		h = (h + h2) & htmask;
306	}
307
308	/* Insert the current entry into hashtable */
309	htable[h].dev = dev;
310	htable[h].ino = ino;
311	htused++;
312	return 0;
313}
314
315void
316usage(void)
317{
318
319	(void)fprintf(stderr,
320		"usage: du [-H | -L | -P] [-a | -d depth | -s] [-cgkmrx] [file ...]\n");
321	exit(1);
322}
323