]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - usr.bin/du/du.c
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / usr.bin / du / du.c
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Newcomb.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1989, 1993, 1994\n\
36         The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38
39 #ifndef lint
40 #if 0
41 static const char sccsid[] = "@(#)du.c  8.5 (Berkeley) 5/4/95";
42 #endif
43 #endif /* not lint */
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/queue.h>
49 #include <sys/stat.h>
50
51 #include <err.h>
52 #include <errno.h>
53 #include <fnmatch.h>
54 #include <fts.h>
55 #include <libutil.h>
56 #include <locale.h>
57 #include <stdint.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <sysexits.h>
62 #include <unistd.h>
63
64 SLIST_HEAD(ignhead, ignentry) ignores;
65 struct ignentry {
66         char                    *mask;
67         SLIST_ENTRY(ignentry)   next;
68 };
69
70 static int      linkchk(FTSENT *);
71 static void     usage(void);
72 static void     prthumanval(int64_t);
73 static void     ignoreadd(const char *);
74 static void     ignoreclean(void);
75 static int      ignorep(FTSENT *);
76 static void     siginfo(int __unused);
77
78 static int      nodumpflag = 0;
79 static int      Aflag;
80 static long     blocksize, cblocksize;
81 static volatile sig_atomic_t info;
82
83 int
84 main(int argc, char *argv[])
85 {
86         FTS             *fts;
87         FTSENT          *p;
88         off_t           savednumber, curblocks;
89         off_t           threshold, threshold_sign;
90         int             ftsoptions;
91         int             listall;
92         int             depth;
93         int             Hflag, Lflag, aflag, sflag, dflag, cflag;
94         int             hflag, lflag, ch, notused, rval;
95         char            **save;
96         static char     dot[] = ".";
97
98         setlocale(LC_ALL, "");
99
100         Hflag = Lflag = aflag = sflag = dflag = cflag = hflag =
101             lflag = Aflag = 0;
102
103         save = argv;
104         ftsoptions = FTS_PHYSICAL;
105         savednumber = 0;
106         threshold = 0;
107         threshold_sign = 1;
108         cblocksize = DEV_BSIZE;
109         blocksize = 0;
110         depth = INT_MAX;
111         SLIST_INIT(&ignores);
112
113         while ((ch = getopt(argc, argv, "AB:HI:LPasd:cghklmnrt:x")) != -1)
114                 switch (ch) {
115                 case 'A':
116                         Aflag = 1;
117                         break;
118                 case 'B':
119                         errno = 0;
120                         cblocksize = atoi(optarg);
121                         if (errno == ERANGE || cblocksize <= 0) {
122                                 warnx("invalid argument to option B: %s",
123                                     optarg);
124                                 usage();
125                         }
126                         break;
127                 case 'H':
128                         Hflag = 1;
129                         Lflag = 0;
130                         break;
131                 case 'I':
132                         ignoreadd(optarg);
133                         break;
134                 case 'L':
135                         Lflag = 1;
136                         Hflag = 0;
137                         break;
138                 case 'P':
139                         Hflag = Lflag = 0;
140                         break;
141                 case 'a':
142                         aflag = 1;
143                         break;
144                 case 's':
145                         sflag = 1;
146                         break;
147                 case 'd':
148                         dflag = 1;
149                         errno = 0;
150                         depth = atoi(optarg);
151                         if (errno == ERANGE || depth < 0) {
152                                 warnx("invalid argument to option d: %s",
153                                     optarg);
154                                 usage();
155                         }
156                         break;
157                 case 'c':
158                         cflag = 1;
159                         break;
160                 case 'g':
161                         hflag = 0;
162                         blocksize = 1073741824;
163                         break;
164                 case 'h':
165                         hflag = 1;
166                         break;
167                 case 'k':
168                         hflag = 0;
169                         blocksize = 1024;
170                         break;
171                 case 'l':
172                         lflag = 1;
173                         break;
174                 case 'm':
175                         hflag = 0;
176                         blocksize = 1048576;
177                         break;
178                 case 'n':
179                         nodumpflag = 1;
180                         break;
181                 case 'r':                /* Compatibility. */
182                         break;
183                 case 't' :
184                         if (expand_number(optarg, &threshold) != 0 ||
185                             threshold == 0) {
186                                 warnx("invalid threshold: %s", optarg);
187                                 usage();
188                         } else if (threshold < 0)
189                                 threshold_sign = -1;
190                         break;
191                 case 'x':
192                         ftsoptions |= FTS_XDEV;
193                         break;
194                 case '?':
195                 default:
196                         usage();
197                         /* NOTREACHED */
198                 }
199
200         argc -= optind;
201         argv += optind;
202
203         /*
204          * XXX
205          * Because of the way that fts(3) works, logical walks will not count
206          * the blocks actually used by symbolic links.  We rationalize this by
207          * noting that users computing logical sizes are likely to do logical
208          * copies, so not counting the links is correct.  The real reason is
209          * that we'd have to re-implement the kernel's symbolic link traversing
210          * algorithm to get this right.  If, for example, you have relative
211          * symbolic links referencing other relative symbolic links, it gets
212          * very nasty, very fast.  The bottom line is that it's documented in
213          * the man page, so it's a feature.
214          */
215
216         if (Hflag)
217                 ftsoptions |= FTS_COMFOLLOW;
218         if (Lflag) {
219                 ftsoptions &= ~FTS_PHYSICAL;
220                 ftsoptions |= FTS_LOGICAL;
221         }
222
223         if (!Aflag && (cblocksize % DEV_BSIZE) != 0)
224                 cblocksize = howmany(cblocksize, DEV_BSIZE) * DEV_BSIZE;
225
226         listall = 0;
227
228         if (aflag) {
229                 if (sflag || dflag)
230                         usage();
231                 listall = 1;
232         } else if (sflag) {
233                 if (dflag)
234                         usage();
235                 depth = 0;
236         }
237
238         if (!*argv) {
239                 argv = save;
240                 argv[0] = dot;
241                 argv[1] = NULL;
242         }
243
244         if (blocksize == 0)
245                 (void)getbsize(&notused, &blocksize);
246
247         if (!Aflag) {
248                 cblocksize /= DEV_BSIZE;
249                 blocksize /= DEV_BSIZE;
250         }
251
252         if (threshold != 0)
253                 threshold = howmany(threshold / DEV_BSIZE * cblocksize,
254                     blocksize);
255
256         rval = 0;
257
258         (void)signal(SIGINFO, siginfo);
259
260         if ((fts = fts_open(argv, ftsoptions, NULL)) == NULL)
261                 err(1, "fts_open");
262
263         while ((p = fts_read(fts)) != NULL) {
264                 switch (p->fts_info) {
265                 case FTS_D:                     /* Ignore. */
266                         if (ignorep(p))
267                                 fts_set(fts, p, FTS_SKIP);
268                         break;
269                 case FTS_DP:
270                         if (ignorep(p))
271                                 break;
272
273                         curblocks = Aflag ?
274                             howmany(p->fts_statp->st_size, cblocksize) :
275                             howmany(p->fts_statp->st_blocks, cblocksize);
276                         p->fts_parent->fts_bignum += p->fts_bignum +=
277                             curblocks;
278
279                         if (p->fts_level <= depth && threshold <=
280                             threshold_sign * howmany(p->fts_bignum *
281                             cblocksize, blocksize)) {
282                                 if (hflag) {
283                                         prthumanval(p->fts_bignum);
284                                         (void)printf("\t%s\n", p->fts_path);
285                                 } else {
286                                         (void)printf("%jd\t%s\n",
287                                             (intmax_t)howmany(p->fts_bignum *
288                                             cblocksize, blocksize),
289                                             p->fts_path);
290                                 }
291                         }
292                         if (info) {
293                                 info = 0;
294                                 (void)printf("\t%s\n", p->fts_path);
295                         }
296                         break;
297                 case FTS_DC:                    /* Ignore. */
298                         break;
299                 case FTS_DNR:                   /* Warn, continue. */
300                 case FTS_ERR:
301                 case FTS_NS:
302                         warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
303                         rval = 1;
304                         break;
305                 default:
306                         if (ignorep(p))
307                                 break;
308
309                         if (lflag == 0 && p->fts_statp->st_nlink > 1 &&
310                             linkchk(p))
311                                 break;
312
313                         curblocks = Aflag ?
314                             howmany(p->fts_statp->st_size, cblocksize) :
315                             howmany(p->fts_statp->st_blocks, cblocksize);
316
317                         if (listall || p->fts_level == 0) {
318                                 if (hflag) {
319                                         prthumanval(curblocks);
320                                         (void)printf("\t%s\n", p->fts_path);
321                                 } else {
322                                         (void)printf("%jd\t%s\n",
323                                             (intmax_t)howmany(curblocks *
324                                             cblocksize, blocksize),
325                                             p->fts_path);
326                                 }
327                         }
328
329                         p->fts_parent->fts_bignum += curblocks;
330                 }
331                 savednumber = p->fts_parent->fts_bignum;
332         }
333
334         if (errno)
335                 err(1, "fts_read");
336
337         if (cflag) {
338                 if (hflag) {
339                         prthumanval(savednumber);
340                         (void)printf("\ttotal\n");
341                 } else {
342                         (void)printf("%jd\ttotal\n", (intmax_t)howmany(
343                             savednumber * cblocksize, blocksize));
344                 }
345         }
346
347         ignoreclean();
348         exit(rval);
349 }
350
351 static int
352 linkchk(FTSENT *p)
353 {
354         struct links_entry {
355                 struct links_entry *next;
356                 struct links_entry *previous;
357                 int      links;
358                 dev_t    dev;
359                 ino_t    ino;
360         };
361         static const size_t links_hash_initial_size = 8192;
362         static struct links_entry **buckets;
363         static struct links_entry *free_list;
364         static size_t number_buckets;
365         static unsigned long number_entries;
366         static char stop_allocating;
367         struct links_entry *le, **new_buckets;
368         struct stat *st;
369         size_t i, new_size;
370         int hash;
371
372         st = p->fts_statp;
373
374         /* If necessary, initialize the hash table. */
375         if (buckets == NULL) {
376                 number_buckets = links_hash_initial_size;
377                 buckets = malloc(number_buckets * sizeof(buckets[0]));
378                 if (buckets == NULL)
379                         errx(1, "No memory for hardlink detection");
380                 for (i = 0; i < number_buckets; i++)
381                         buckets[i] = NULL;
382         }
383
384         /* If the hash table is getting too full, enlarge it. */
385         if (number_entries > number_buckets * 10 && !stop_allocating) {
386                 new_size = number_buckets * 2;
387                 new_buckets = malloc(new_size * sizeof(struct links_entry *));
388
389                 /* Try releasing the free list to see if that helps. */
390                 if (new_buckets == NULL && free_list != NULL) {
391                         while (free_list != NULL) {
392                                 le = free_list;
393                                 free_list = le->next;
394                                 free(le);
395                         }
396                         new_buckets = malloc(new_size *
397                             sizeof(new_buckets[0]));
398                 }
399
400                 if (new_buckets == NULL) {
401                         stop_allocating = 1;
402                         warnx("No more memory for tracking hard links");
403                 } else {
404                         memset(new_buckets, 0,
405                             new_size * sizeof(struct links_entry *));
406                         for (i = 0; i < number_buckets; i++) {
407                                 while (buckets[i] != NULL) {
408                                         /* Remove entry from old bucket. */
409                                         le = buckets[i];
410                                         buckets[i] = le->next;
411
412                                         /* Add entry to new bucket. */
413                                         hash = (le->dev ^ le->ino) % new_size;
414
415                                         if (new_buckets[hash] != NULL)
416                                                 new_buckets[hash]->previous =
417                                                     le;
418                                         le->next = new_buckets[hash];
419                                         le->previous = NULL;
420                                         new_buckets[hash] = le;
421                                 }
422                         }
423                         free(buckets);
424                         buckets = new_buckets;
425                         number_buckets = new_size;
426                 }
427         }
428
429         /* Try to locate this entry in the hash table. */
430         hash = ( st->st_dev ^ st->st_ino ) % number_buckets;
431         for (le = buckets[hash]; le != NULL; le = le->next) {
432                 if (le->dev == st->st_dev && le->ino == st->st_ino) {
433                         /*
434                          * Save memory by releasing an entry when we've seen
435                          * all of it's links.
436                          */
437                         if (--le->links <= 0) {
438                                 if (le->previous != NULL)
439                                         le->previous->next = le->next;
440                                 if (le->next != NULL)
441                                         le->next->previous = le->previous;
442                                 if (buckets[hash] == le)
443                                         buckets[hash] = le->next;
444                                 number_entries--;
445                                 /* Recycle this node through the free list */
446                                 if (stop_allocating) {
447                                         free(le);
448                                 } else {
449                                         le->next = free_list;
450                                         free_list = le;
451                                 }
452                         }
453                         return (1);
454                 }
455         }
456
457         if (stop_allocating)
458                 return (0);
459
460         /* Add this entry to the links cache. */
461         if (free_list != NULL) {
462                 /* Pull a node from the free list if we can. */
463                 le = free_list;
464                 free_list = le->next;
465         } else
466                 /* Malloc one if we have to. */
467                 le = malloc(sizeof(struct links_entry));
468         if (le == NULL) {
469                 stop_allocating = 1;
470                 warnx("No more memory for tracking hard links");
471                 return (0);
472         }
473         le->dev = st->st_dev;
474         le->ino = st->st_ino;
475         le->links = st->st_nlink - 1;
476         number_entries++;
477         le->next = buckets[hash];
478         le->previous = NULL;
479         if (buckets[hash] != NULL)
480                 buckets[hash]->previous = le;
481         buckets[hash] = le;
482         return (0);
483 }
484
485 static void
486 prthumanval(int64_t bytes)
487 {
488         char buf[5];
489
490         bytes *= cblocksize;
491         if (!Aflag)
492                 bytes *= DEV_BSIZE;
493
494         humanize_number(buf, sizeof(buf), bytes, "", HN_AUTOSCALE,
495             HN_B | HN_NOSPACE | HN_DECIMAL);
496
497         (void)printf("%4s", buf);
498 }
499
500 static void
501 usage(void)
502 {
503         (void)fprintf(stderr,
504                 "usage: du [-Aclnx] [-H | -L | -P] [-h | -k | -m ] "
505                 "[-a | -s | -d depth] [-B blocksize] [-I mask] "
506                 "[-t threshold] [file ...]\n");
507         exit(EX_USAGE);
508 }
509
510 static void
511 ignoreadd(const char *mask)
512 {
513         struct ignentry *ign;
514
515         ign = calloc(1, sizeof(*ign));
516         if (ign == NULL)
517                 errx(1, "cannot allocate memory");
518         ign->mask = strdup(mask);
519         if (ign->mask == NULL)
520                 errx(1, "cannot allocate memory");
521         SLIST_INSERT_HEAD(&ignores, ign, next);
522 }
523
524 static void
525 ignoreclean(void)
526 {
527         struct ignentry *ign;
528         
529         while (!SLIST_EMPTY(&ignores)) {
530                 ign = SLIST_FIRST(&ignores);
531                 SLIST_REMOVE_HEAD(&ignores, next);
532                 free(ign->mask);
533                 free(ign);
534         }
535 }
536
537 static int
538 ignorep(FTSENT *ent)
539 {
540         struct ignentry *ign;
541
542         if (nodumpflag && (ent->fts_statp->st_flags & UF_NODUMP))
543                 return 1;
544         SLIST_FOREACH(ign, &ignores, next)
545                 if (fnmatch(ign->mask, ent->fts_name, 0) != FNM_NOMATCH)
546                         return 1;
547         return 0;
548 }
549
550 static void
551 siginfo(int sig __unused)
552 {
553
554         info = 1;
555 }