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