btrfs-progs: send-stream: use proper type for read return value
[platform/upstream/btrfs-progs.git] / cmds-fi-usage.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public
4  * License v2 as published by the Free Software Foundation.
5  *
6  * This program is distributed in the hope that it will be useful,
7  * but WITHOUT ANY WARRANTY; without even the implied warranty of
8  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9  * General Public License for more details.
10  *
11  * You should have received a copy of the GNU General Public
12  * License along with this program; if not, write to the
13  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
14  * Boston, MA 021110-1307, USA.
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <sys/ioctl.h>
22 #include <errno.h>
23 #include <stdarg.h>
24 #include <getopt.h>
25
26 #include "utils.h"
27 #include "kerncompat.h"
28 #include "ctree.h"
29 #include "string-table.h"
30 #include "cmds-fi-usage.h"
31 #include "commands.h"
32
33 #include "version.h"
34
35 /*
36  * Add the chunk info to the chunk_info list
37  */
38 static int add_info_to_list(struct chunk_info **info_ptr,
39                         int *info_count,
40                         struct btrfs_chunk *chunk)
41 {
42
43         u64 type = btrfs_stack_chunk_type(chunk);
44         u64 size = btrfs_stack_chunk_length(chunk);
45         int num_stripes = btrfs_stack_chunk_num_stripes(chunk);
46         int j;
47
48         for (j = 0 ; j < num_stripes ; j++) {
49                 int i;
50                 struct chunk_info *p = NULL;
51                 struct btrfs_stripe *stripe;
52                 u64    devid;
53
54                 stripe = btrfs_stripe_nr(chunk, j);
55                 devid = btrfs_stack_stripe_devid(stripe);
56
57                 for (i = 0 ; i < *info_count ; i++)
58                         if ((*info_ptr)[i].type == type &&
59                             (*info_ptr)[i].devid == devid &&
60                             (*info_ptr)[i].num_stripes == num_stripes ) {
61                                 p = (*info_ptr) + i;
62                                 break;
63                         }
64
65                 if (!p) {
66                         int tmp = sizeof(struct btrfs_chunk) * (*info_count + 1);
67                         struct chunk_info *res = realloc(*info_ptr, tmp);
68
69                         if (!res) {
70                                 free(*info_ptr);
71                                 error("not enough memory");
72                                 return -ENOMEM;
73                         }
74
75                         *info_ptr = res;
76                         p = res + *info_count;
77                         (*info_count)++;
78
79                         p->devid = devid;
80                         p->type = type;
81                         p->size = 0;
82                         p->num_stripes = num_stripes;
83                 }
84
85                 p->size += size;
86
87         }
88
89         return 0;
90
91 }
92
93 /*
94  *  Helper to sort the chunk type
95  */
96 static int cmp_chunk_block_group(u64 f1, u64 f2)
97 {
98
99         u64 mask;
100
101         if ((f1 & BTRFS_BLOCK_GROUP_TYPE_MASK) ==
102                 (f2 & BTRFS_BLOCK_GROUP_TYPE_MASK))
103                         mask = BTRFS_BLOCK_GROUP_PROFILE_MASK;
104         else if (f2 & BTRFS_BLOCK_GROUP_SYSTEM)
105                         return -1;
106         else if (f1 & BTRFS_BLOCK_GROUP_SYSTEM)
107                         return +1;
108         else
109                         mask = BTRFS_BLOCK_GROUP_TYPE_MASK;
110
111         if ((f1 & mask) > (f2 & mask))
112                 return +1;
113         else if ((f1 & mask) < (f2 & mask))
114                 return -1;
115         else
116                 return 0;
117 }
118
119 /*
120  * Helper to sort the chunk
121  */
122 static int cmp_chunk_info(const void *a, const void *b)
123 {
124         return cmp_chunk_block_group(
125                 ((struct chunk_info *)a)->type,
126                 ((struct chunk_info *)b)->type);
127 }
128
129 static int load_chunk_info(int fd, struct chunk_info **info_ptr, int *info_count)
130 {
131         int ret;
132         struct btrfs_ioctl_search_args args;
133         struct btrfs_ioctl_search_key *sk = &args.key;
134         struct btrfs_ioctl_search_header *sh;
135         unsigned long off = 0;
136         int i, e;
137
138         memset(&args, 0, sizeof(args));
139
140         /*
141          * there may be more than one ROOT_ITEM key if there are
142          * snapshots pending deletion, we have to loop through
143          * them.
144          */
145         sk->tree_id = BTRFS_CHUNK_TREE_OBJECTID;
146
147         sk->min_objectid = 0;
148         sk->max_objectid = (u64)-1;
149         sk->max_type = 0;
150         sk->min_type = (u8)-1;
151         sk->min_offset = 0;
152         sk->max_offset = (u64)-1;
153         sk->min_transid = 0;
154         sk->max_transid = (u64)-1;
155         sk->nr_items = 4096;
156
157         while (1) {
158                 ret = ioctl(fd, BTRFS_IOC_TREE_SEARCH, &args);
159                 e = errno;
160                 if (e == EPERM)
161                         return -e;
162
163                 if (ret < 0) {
164                         error("cannot look up chunk tree info: %s",
165                                 strerror(e));
166                         return 1;
167                 }
168                 /* the ioctl returns the number of item it found in nr_items */
169
170                 if (sk->nr_items == 0)
171                         break;
172
173                 off = 0;
174                 for (i = 0; i < sk->nr_items; i++) {
175                         struct btrfs_chunk *item;
176                         sh = (struct btrfs_ioctl_search_header *)(args.buf +
177                                                                   off);
178
179                         off += sizeof(*sh);
180                         item = (struct btrfs_chunk *)(args.buf + off);
181
182                         ret = add_info_to_list(info_ptr, info_count, item);
183                         if (ret) {
184                                 *info_ptr = NULL;
185                                 return 1;
186                         }
187
188                         off += btrfs_search_header_len(sh);
189
190                         sk->min_objectid = btrfs_search_header_objectid(sh);
191                         sk->min_type = btrfs_search_header_type(sh);
192                         sk->min_offset = btrfs_search_header_offset(sh)+1;
193
194                 }
195                 if (!sk->min_offset)    /* overflow */
196                         sk->min_type++;
197                 else
198                         continue;
199
200                 if (!sk->min_type)
201                         sk->min_objectid++;
202                  else
203                         continue;
204
205                 if (!sk->min_objectid)
206                         break;
207         }
208
209         qsort(*info_ptr, *info_count, sizeof(struct chunk_info),
210                 cmp_chunk_info);
211
212         return 0;
213 }
214
215 /*
216  * Helper to sort the struct btrfs_ioctl_space_info
217  */
218 static int cmp_btrfs_ioctl_space_info(const void *a, const void *b)
219 {
220         return cmp_chunk_block_group(
221                 ((struct btrfs_ioctl_space_info *)a)->flags,
222                 ((struct btrfs_ioctl_space_info *)b)->flags);
223 }
224
225 /*
226  * This function load all the information about the space usage
227  */
228 static struct btrfs_ioctl_space_args *load_space_info(int fd, char *path)
229 {
230         struct btrfs_ioctl_space_args *sargs = NULL, *sargs_orig = NULL;
231         int ret, count;
232
233         sargs_orig = sargs = calloc(1, sizeof(struct btrfs_ioctl_space_args));
234         if (!sargs) {
235                 error("not enough memory");
236                 return NULL;
237         }
238
239         sargs->space_slots = 0;
240         sargs->total_spaces = 0;
241
242         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
243         if (ret < 0) {
244                 error("cannot get space info on '%s': %s", path,
245                         strerror(errno));
246                 free(sargs);
247                 return NULL;
248         }
249         if (!sargs->total_spaces) {
250                 free(sargs);
251                 printf("No chunks found\n");
252                 return NULL;
253         }
254
255         count = sargs->total_spaces;
256
257         sargs = realloc(sargs, sizeof(struct btrfs_ioctl_space_args) +
258                         (count * sizeof(struct btrfs_ioctl_space_info)));
259         if (!sargs) {
260                 free(sargs_orig);
261                 error("not enough memory");
262                 return NULL;
263         }
264
265         sargs->space_slots = count;
266         sargs->total_spaces = 0;
267
268         ret = ioctl(fd, BTRFS_IOC_SPACE_INFO, sargs);
269         if (ret < 0) {
270                 error("cannot get space info with %u slots: %s",
271                         count, strerror(errno));
272                 free(sargs);
273                 return NULL;
274         }
275
276         qsort(&(sargs->spaces), count, sizeof(struct btrfs_ioctl_space_info),
277                 cmp_btrfs_ioctl_space_info);
278
279         return sargs;
280 }
281
282 /*
283  * This function computes the space occupied by a *single* RAID5/RAID6 chunk.
284  * The computation is performed on the basis of the number of stripes
285  * which compose the chunk, which could be different from the number of devices
286  * if a disk is added later.
287  */
288 static void get_raid56_used(int fd, struct chunk_info *chunks, int chunkcount,
289                 u64 *raid5_used, u64 *raid6_used)
290 {
291         struct chunk_info *info_ptr = chunks;
292         *raid5_used = 0;
293         *raid6_used = 0;
294
295         while (chunkcount-- > 0) {
296                 if (info_ptr->type & BTRFS_BLOCK_GROUP_RAID5)
297                         (*raid5_used) += info_ptr->size / (info_ptr->num_stripes - 1);
298                 if (info_ptr->type & BTRFS_BLOCK_GROUP_RAID6)
299                         (*raid6_used) += info_ptr->size / (info_ptr->num_stripes - 2);
300                 info_ptr++;
301         }
302 }
303
304 #define MIN_UNALOCATED_THRESH   (16 * 1024 * 1024)
305 static int print_filesystem_usage_overall(int fd, struct chunk_info *chunkinfo,
306                 int chunkcount, struct device_info *devinfo, int devcount,
307                 char *path, unsigned unit_mode)
308 {
309         struct btrfs_ioctl_space_args *sargs = NULL;
310         int i;
311         int ret = 0;
312         int width = 10;         /* default 10 for human units */
313         /*
314          * r_* prefix is for raw data
315          * l_* is for logical
316          */
317         u64 r_total_size = 0;   /* filesystem size, sum of device sizes */
318         u64 r_total_chunks = 0; /* sum of chunks sizes on disk(s) */
319         u64 r_total_used = 0;
320         u64 r_total_unused = 0;
321         u64 r_total_missing = 0;        /* sum of missing devices size */
322         u64 r_data_used = 0;
323         u64 r_data_chunks = 0;
324         u64 l_data_chunks = 0;
325         u64 r_metadata_used = 0;
326         u64 r_metadata_chunks = 0;
327         u64 l_metadata_chunks = 0;
328         u64 r_system_used = 0;
329         u64 r_system_chunks = 0;
330         double data_ratio;
331         double metadata_ratio;
332         /* logical */
333         u64 raid5_used = 0;
334         u64 raid6_used = 0;
335         u64 l_global_reserve = 0;
336         u64 l_global_reserve_used = 0;
337         u64 free_estimated = 0;
338         u64 free_min = 0;
339         int max_data_ratio = 1;
340         int mixed = 0;
341
342         sargs = load_space_info(fd, path);
343         if (!sargs) {
344                 ret = 1;
345                 goto exit;
346         }
347
348         r_total_size = 0;
349         for (i = 0; i < devcount; i++) {
350                 r_total_size += devinfo[i].size;
351                 if (!devinfo[i].device_size)
352                         r_total_missing += devinfo[i].size;
353         }
354
355         if (r_total_size == 0) {
356                 error("cannot get space info on '%s': %s",
357                         path, strerror(errno));
358
359                 ret = 1;
360                 goto exit;
361         }
362         get_raid56_used(fd, chunkinfo, chunkcount, &raid5_used, &raid6_used);
363
364         for (i = 0; i < sargs->total_spaces; i++) {
365                 int ratio;
366                 u64 flags = sargs->spaces[i].flags;
367
368                 /*
369                  * The raid5/raid6 ratio depends by the stripes number
370                  * used by every chunk. It is computed separately
371                  */
372                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
373                         ratio = 1;
374                 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
375                         ratio = 2;
376                 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
377                         ratio = 0;
378                 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
379                         ratio = 0;
380                 else if (flags & BTRFS_BLOCK_GROUP_DUP)
381                         ratio = 2;
382                 else if (flags & BTRFS_BLOCK_GROUP_RAID10)
383                         ratio = 2;
384                 else
385                         ratio = 1;
386
387                 if (!ratio)
388                         warning("RAID56 detected, not implemented");
389
390                 if (ratio > max_data_ratio)
391                         max_data_ratio = ratio;
392
393                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV) {
394                         l_global_reserve = sargs->spaces[i].total_bytes;
395                         l_global_reserve_used = sargs->spaces[i].used_bytes;
396                 }
397                 if ((flags & (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA))
398                     == (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA)) {
399                         mixed = 1;
400                 }
401                 if (flags & BTRFS_BLOCK_GROUP_DATA) {
402                         r_data_used += sargs->spaces[i].used_bytes * ratio;
403                         r_data_chunks += sargs->spaces[i].total_bytes * ratio;
404                         l_data_chunks += sargs->spaces[i].total_bytes;
405                 }
406                 if (flags & BTRFS_BLOCK_GROUP_METADATA) {
407                         r_metadata_used += sargs->spaces[i].used_bytes * ratio;
408                         r_metadata_chunks += sargs->spaces[i].total_bytes * ratio;
409                         l_metadata_chunks += sargs->spaces[i].total_bytes;
410                 }
411                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM) {
412                         r_system_used += sargs->spaces[i].used_bytes * ratio;
413                         r_system_chunks += sargs->spaces[i].total_bytes * ratio;
414                 }
415         }
416
417         r_total_chunks = r_data_chunks + r_system_chunks;
418         r_total_used = r_data_used + r_system_used;
419         if (!mixed) {
420                 r_total_chunks += r_metadata_chunks;
421                 r_total_used += r_metadata_used;
422         }
423         r_total_unused = r_total_size - r_total_chunks;
424
425         /* Raw / Logical = raid factor, >= 1 */
426         data_ratio = (double)r_data_chunks / l_data_chunks;
427         if (mixed)
428                 metadata_ratio = data_ratio;
429         else
430                 metadata_ratio = (double)r_metadata_chunks / l_metadata_chunks;
431
432 #if 0
433         /* add the raid5/6 allocated space */
434         total_chunks += raid5_used + raid6_used;
435 #endif
436
437         /*
438          * We're able to fill at least DATA for the unused space
439          *
440          * With mixed raid levels, this gives a rough estimate but more
441          * accurate than just counting the logical free space
442          * (l_data_chunks - l_data_used)
443          *
444          * In non-mixed case there's no difference.
445          */
446         free_estimated = (r_data_chunks - r_data_used) / data_ratio;
447         /*
448          * For mixed-bg the metadata are left out in calculations thus global
449          * reserve would be lost. Part of it could be permanently allocated,
450          * we have to subtract the used bytes so we don't go under zero free.
451          */
452         if (mixed)
453                 free_estimated -= l_global_reserve - l_global_reserve_used;
454         free_min = free_estimated;
455
456         /* Chop unallocatable space */
457         /* FIXME: must be applied per device */
458         if (r_total_unused >= MIN_UNALOCATED_THRESH) {
459                 free_estimated += r_total_unused / data_ratio;
460                 /* Match the calculation of 'df', use the highest raid ratio */
461                 free_min += r_total_unused / max_data_ratio;
462         }
463
464         if (unit_mode != UNITS_HUMAN)
465                 width = 18;
466
467         printf("Overall:\n");
468
469         printf("    Device size:\t\t%*s\n", width,
470                 pretty_size_mode(r_total_size, unit_mode));
471         printf("    Device allocated:\t\t%*s\n", width,
472                 pretty_size_mode(r_total_chunks, unit_mode));
473         printf("    Device unallocated:\t\t%*s\n", width,
474                 pretty_size_mode(r_total_unused, unit_mode));
475         printf("    Device missing:\t\t%*s\n", width,
476                 pretty_size_mode(r_total_missing, unit_mode));
477         printf("    Used:\t\t\t%*s\n", width,
478                 pretty_size_mode(r_total_used, unit_mode));
479         printf("    Free (estimated):\t\t%*s\t(",
480                 width,
481                 pretty_size_mode(free_estimated, unit_mode));
482         printf("min: %s)\n", pretty_size_mode(free_min, unit_mode));
483         printf("    Data ratio:\t\t\t%*.2f\n",
484                 width, data_ratio);
485         printf("    Metadata ratio:\t\t%*.2f\n",
486                 width, metadata_ratio);
487         printf("    Global reserve:\t\t%*s\t(used: %s)\n", width,
488                 pretty_size_mode(l_global_reserve, unit_mode),
489                 pretty_size_mode(l_global_reserve_used, unit_mode));
490
491 exit:
492
493         if (sargs)
494                 free(sargs);
495
496         return ret;
497 }
498
499 /*
500  *  Helper to sort the device_info structure
501  */
502 static int cmp_device_info(const void *a, const void *b)
503 {
504         return strcmp(((struct device_info *)a)->path,
505                         ((struct device_info *)b)->path);
506 }
507
508 /*
509  *  This function loads the device_info structure and put them in an array
510  */
511 static int load_device_info(int fd, struct device_info **device_info_ptr,
512                            int *device_info_count)
513 {
514         int ret, i, ndevs;
515         struct btrfs_ioctl_fs_info_args fi_args;
516         struct btrfs_ioctl_dev_info_args dev_info;
517         struct device_info *info;
518
519         *device_info_count = 0;
520         *device_info_ptr = NULL;
521
522         ret = ioctl(fd, BTRFS_IOC_FS_INFO, &fi_args);
523         if (ret < 0) {
524                 if (errno == EPERM)
525                         return -errno;
526                 error("cannot get filesystem info: %s",
527                                 strerror(errno));
528                 return 1;
529         }
530
531         info = calloc(fi_args.num_devices, sizeof(struct device_info));
532         if (!info) {
533                 error("not enough memory");
534                 return 1;
535         }
536
537         for (i = 0, ndevs = 0 ; i <= fi_args.max_id ; i++) {
538                 if (ndevs >= fi_args.num_devices) {
539                         error("unexpected number of devices: %d >= %llu", ndevs,
540                                 (unsigned long long)fi_args.num_devices);
541                         goto out;
542                 }
543                 memset(&dev_info, 0, sizeof(dev_info));
544                 ret = get_device_info(fd, i, &dev_info);
545
546                 if (ret == -ENODEV)
547                         continue;
548                 if (ret) {
549                         error("cannot get info about device devid=%d", i);
550                         goto out;
551                 }
552
553                 info[ndevs].devid = dev_info.devid;
554                 if (!dev_info.path[0]) {
555                         strcpy(info[ndevs].path, "missing");
556                 } else {
557                         strcpy(info[ndevs].path, (char *)dev_info.path);
558                         info[ndevs].device_size =
559                                 get_partition_size((char *)dev_info.path);
560                 }
561                 info[ndevs].size = dev_info.total_bytes;
562                 ++ndevs;
563         }
564
565         if (ndevs != fi_args.num_devices) {
566                 error("unexpected number of devices: %d != %llu", ndevs,
567                                 (unsigned long long)fi_args.num_devices);
568                 goto out;
569         }
570
571         qsort(info, fi_args.num_devices,
572                 sizeof(struct device_info), cmp_device_info);
573
574         *device_info_count = fi_args.num_devices;
575         *device_info_ptr = info;
576
577         return 0;
578
579 out:
580         free(info);
581         return ret;
582 }
583
584 int load_chunk_and_device_info(int fd, struct chunk_info **chunkinfo,
585                 int *chunkcount, struct device_info **devinfo, int *devcount)
586 {
587         int ret;
588
589         ret = load_chunk_info(fd, chunkinfo, chunkcount);
590         if (ret == -EPERM) {
591                 warning(
592 "cannot read detailed chunk info, RAID5/6 numbers will be incorrect, run as root");
593         } else if (ret) {
594                 return ret;
595         }
596
597         ret = load_device_info(fd, devinfo, devcount);
598         if (ret == -EPERM) {
599                 warning(
600                 "cannot get filesystem info from ioctl(FS_INFO), run as root");
601                 ret = 0;
602         }
603
604         return ret;
605 }
606
607 /*
608  *  This function computes the size of a chunk in a disk
609  */
610 static u64 calc_chunk_size(struct chunk_info *ci)
611 {
612         if (ci->type & BTRFS_BLOCK_GROUP_RAID0)
613                 return ci->size / ci->num_stripes;
614         else if (ci->type & BTRFS_BLOCK_GROUP_RAID1)
615                 return ci->size ;
616         else if (ci->type & BTRFS_BLOCK_GROUP_DUP)
617                 return ci->size ;
618         else if (ci->type & BTRFS_BLOCK_GROUP_RAID5)
619                 return ci->size / (ci->num_stripes -1);
620         else if (ci->type & BTRFS_BLOCK_GROUP_RAID6)
621                 return ci->size / (ci->num_stripes -2);
622         else if (ci->type & BTRFS_BLOCK_GROUP_RAID10)
623                 return ci->size / ci->num_stripes;
624         return ci->size;
625 }
626
627 /*
628  *  This function print the results of the command "btrfs fi usage"
629  *  in tabular format
630  */
631 static void _cmd_filesystem_usage_tabular(unsigned unit_mode,
632                                         struct btrfs_ioctl_space_args *sargs,
633                                         struct chunk_info *chunks_info_ptr,
634                                         int chunks_info_count,
635                                         struct device_info *device_info_ptr,
636                                         int device_info_count)
637 {
638         int i;
639         u64 total_unused = 0;
640         struct string_table *matrix = NULL;
641         int  ncols, nrows;
642         int col;
643         int unallocated_col;
644         int spaceinfos_col;
645         const int vhdr_skip = 3;        /* amount of vertical header space */
646
647         /* id, path, unallocated */
648         ncols = 3;
649         spaceinfos_col = 2;
650         /* Properly count the real space infos */
651         for (i = 0; i < sargs->total_spaces; i++) {
652                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
653                         continue;
654                 ncols++;
655         }
656
657         /* 2 for header, empty line, devices, ===, total, used */
658         nrows = vhdr_skip + device_info_count + 1 + 2;
659
660         matrix = table_create(ncols, nrows);
661         if (!matrix) {
662                 error("not enough memory");
663                 return;
664         }
665
666         /*
667          * We have to skip the global block reserve everywhere as it's an
668          * artificial blockgroup
669          */
670
671         /* header */
672         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
673                 u64 flags = sargs->spaces[i].flags;
674
675                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
676                         continue;
677
678                 table_printf(matrix, col, 0, "<%s",
679                                 btrfs_group_type_str(flags));
680                 table_printf(matrix, col, 1, "<%s",
681                                 btrfs_group_profile_str(flags));
682                 col++;
683         }
684         unallocated_col = col;
685
686         table_printf(matrix, 0, 1, "<Id");
687         table_printf(matrix, 1, 1, "<Path");
688         table_printf(matrix, unallocated_col, 1, "<Unallocated");
689
690         /* body */
691         for (i = 0; i < device_info_count; i++) {
692                 int k;
693                 char *p;
694
695                 u64  total_allocated = 0, unused;
696
697                 p = strrchr(device_info_ptr[i].path, '/');
698                 if (!p)
699                         p = device_info_ptr[i].path;
700                 else
701                         p++;
702
703                 table_printf(matrix, 0, vhdr_skip + i, ">%llu",
704                                 device_info_ptr[i].devid);
705                 table_printf(matrix, 1, vhdr_skip + i, "<%s",
706                                 device_info_ptr[i].path);
707
708                 for (col = spaceinfos_col, k = 0; k < sargs->total_spaces; k++) {
709                         u64     flags = sargs->spaces[k].flags;
710                         u64 devid = device_info_ptr[i].devid;
711                         int     j;
712                         u64 size = 0;
713
714                         if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
715                                 continue;
716
717                         for (j = 0 ; j < chunks_info_count ; j++) {
718                                 if (chunks_info_ptr[j].type != flags )
719                                                 continue;
720                                 if (chunks_info_ptr[j].devid != devid)
721                                                 continue;
722
723                                 size += calc_chunk_size(chunks_info_ptr+j);
724                         }
725
726                         if (size)
727                                 table_printf(matrix, col, vhdr_skip+ i,
728                                         ">%s", pretty_size_mode(size, unit_mode));
729                         else
730                                 table_printf(matrix, col, vhdr_skip + i, ">-");
731
732                         total_allocated += size;
733                         col++;
734                 }
735
736                 unused = get_partition_size(device_info_ptr[i].path)
737                                 - total_allocated;
738
739                 table_printf(matrix, unallocated_col, vhdr_skip + i,
740                                ">%s", pretty_size_mode(unused, unit_mode));
741                 total_unused += unused;
742
743         }
744
745         for (i = 0; i < spaceinfos_col; i++) {
746                 table_printf(matrix, i, vhdr_skip - 1, "*-");
747                 table_printf(matrix, i, vhdr_skip + device_info_count, "*-");
748         }
749
750         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
751                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
752                         continue;
753
754                 table_printf(matrix, col, vhdr_skip - 1, "*-");
755                 table_printf(matrix, col, vhdr_skip + device_info_count, "*-");
756                 col++;
757         }
758         /* One for Unallocated */
759         table_printf(matrix, col, vhdr_skip - 1, "*-");
760         table_printf(matrix, col, vhdr_skip + device_info_count, "*-");
761
762         /* footer */
763         table_printf(matrix, 1, vhdr_skip + device_info_count + 1, "<Total");
764         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
765                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
766                         continue;
767
768                 table_printf(matrix, col++, vhdr_skip + device_info_count + 1,
769                         ">%s",
770                         pretty_size_mode(sargs->spaces[i].total_bytes, unit_mode));
771         }
772
773         table_printf(matrix, unallocated_col, vhdr_skip + device_info_count + 1,
774                         ">%s", pretty_size_mode(total_unused, unit_mode));
775
776         table_printf(matrix, 1, vhdr_skip + device_info_count + 2, "<Used");
777         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
778                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
779                         continue;
780
781                 table_printf(matrix, col++, vhdr_skip + device_info_count + 2,
782                         ">%s",
783                         pretty_size_mode(sargs->spaces[i].used_bytes, unit_mode));
784         }
785
786         table_dump(matrix);
787         table_free(matrix);
788 }
789
790 /*
791  *  This function prints the unused space per every disk
792  */
793 static void print_unused(struct chunk_info *info_ptr,
794                           int info_count,
795                           struct device_info *device_info_ptr,
796                           int device_info_count,
797                           unsigned unit_mode)
798 {
799         int i;
800         for (i = 0; i < device_info_count; i++) {
801                 int     j;
802                 u64     total = 0;
803
804                 for (j = 0; j < info_count; j++)
805                         if (info_ptr[j].devid == device_info_ptr[i].devid)
806                                 total += calc_chunk_size(info_ptr+j);
807
808                 printf("   %s\t%10s\n",
809                         device_info_ptr[i].path,
810                         pretty_size_mode(device_info_ptr[i].size - total,
811                                 unit_mode));
812         }
813 }
814
815 /*
816  *  This function prints the allocated chunk per every disk
817  */
818 static void print_chunk_device(u64 chunk_type,
819                                 struct chunk_info *chunks_info_ptr,
820                                 int chunks_info_count,
821                                 struct device_info *device_info_ptr,
822                                 int device_info_count,
823                                 unsigned unit_mode)
824 {
825         int i;
826
827         for (i = 0; i < device_info_count; i++) {
828                 int     j;
829                 u64     total = 0;
830
831                 for (j = 0; j < chunks_info_count; j++) {
832
833                         if (chunks_info_ptr[j].type != chunk_type)
834                                 continue;
835                         if (chunks_info_ptr[j].devid != device_info_ptr[i].devid)
836                                 continue;
837
838                         total += calc_chunk_size(&(chunks_info_ptr[j]));
839                         //total += chunks_info_ptr[j].size;
840                 }
841
842                 if (total > 0)
843                         printf("   %s\t%10s\n",
844                                 device_info_ptr[i].path,
845                                 pretty_size_mode(total, unit_mode));
846         }
847 }
848
849 /*
850  *  This function print the results of the command "btrfs fi usage"
851  *  in linear format
852  */
853 static void _cmd_filesystem_usage_linear(unsigned unit_mode,
854                                         struct btrfs_ioctl_space_args *sargs,
855                                         struct chunk_info *info_ptr,
856                                         int info_count,
857                                         struct device_info *device_info_ptr,
858                                         int device_info_count)
859 {
860         int i;
861
862         for (i = 0; i < sargs->total_spaces; i++) {
863                 const char *description;
864                 const char *r_mode;
865                 u64 flags = sargs->spaces[i].flags;
866
867                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
868                         continue;
869
870                 description = btrfs_group_type_str(flags);
871                 r_mode = btrfs_group_profile_str(flags);
872
873                 printf("%s,%s: Size:%s, ",
874                         description,
875                         r_mode,
876                         pretty_size_mode(sargs->spaces[i].total_bytes,
877                                 unit_mode));
878                 printf("Used:%s\n",
879                         pretty_size_mode(sargs->spaces[i].used_bytes, unit_mode));
880                 print_chunk_device(flags, info_ptr, info_count,
881                                 device_info_ptr, device_info_count, unit_mode);
882                 printf("\n");
883         }
884
885         printf("Unallocated:\n");
886         print_unused(info_ptr, info_count, device_info_ptr, device_info_count,
887                         unit_mode);
888 }
889
890 static int print_filesystem_usage_by_chunk(int fd,
891                 struct chunk_info *chunkinfo, int chunkcount,
892                 struct device_info *devinfo, int devcount,
893                 char *path, unsigned unit_mode, int tabular)
894 {
895         struct btrfs_ioctl_space_args *sargs;
896         int ret = 0;
897
898         if (!chunkinfo)
899                 return 0;
900
901         sargs = load_space_info(fd, path);
902         if (!sargs) {
903                 ret = 1;
904                 goto out;
905         }
906
907         if (tabular)
908                 _cmd_filesystem_usage_tabular(unit_mode, sargs, chunkinfo,
909                                 chunkcount, devinfo, devcount);
910         else
911                 _cmd_filesystem_usage_linear(unit_mode, sargs, chunkinfo,
912                                 chunkcount, devinfo, devcount);
913
914         free(sargs);
915 out:
916         return ret;
917 }
918
919 const char * const cmd_filesystem_usage_usage[] = {
920         "btrfs filesystem usage [options] <path> [<path>..]",
921         "Show detailed information about internal filesystem usage .",
922         HELPINFO_UNITS_SHORT_LONG,
923         "-T                 show data in tabular format",
924         NULL
925 };
926
927 int cmd_filesystem_usage(int argc, char **argv)
928 {
929         int ret = 0;
930         unsigned unit_mode;
931         int i;
932         int more_than_one = 0;
933         int tabular = 0;
934
935         unit_mode = get_unit_mode_from_arg(&argc, argv, 1);
936
937         while (1) {
938                 int c;
939
940                 c = getopt(argc, argv, "T");
941                 if (c < 0)
942                         break;
943
944                 switch (c) {
945                 case 'T':
946                         tabular = 1;
947                         break;
948                 default:
949                         usage(cmd_filesystem_usage_usage);
950                 }
951         }
952
953         if (check_argc_min(argc - optind, 1))
954                 usage(cmd_filesystem_usage_usage);
955
956         for (i = optind; i < argc; i++) {
957                 int fd;
958                 DIR *dirstream = NULL;
959                 struct chunk_info *chunkinfo = NULL;
960                 struct device_info *devinfo = NULL;
961                 int chunkcount = 0;
962                 int devcount = 0;
963
964                 fd = btrfs_open_dir(argv[i], &dirstream, 1);
965                 if (fd < 0) {
966                         ret = 1;
967                         goto out;
968                 }
969                 if (more_than_one)
970                         printf("\n");
971
972                 ret = load_chunk_and_device_info(fd, &chunkinfo, &chunkcount,
973                                 &devinfo, &devcount);
974                 if (ret)
975                         goto cleanup;
976
977                 ret = print_filesystem_usage_overall(fd, chunkinfo, chunkcount,
978                                 devinfo, devcount, argv[i], unit_mode);
979                 if (ret)
980                         goto cleanup;
981                 printf("\n");
982                 ret = print_filesystem_usage_by_chunk(fd, chunkinfo, chunkcount,
983                                 devinfo, devcount, argv[i], unit_mode, tabular);
984 cleanup:
985                 close_file_or_dir(fd, dirstream);
986                 free(chunkinfo);
987                 free(devinfo);
988
989                 if (ret)
990                         goto out;
991                 more_than_one = 1;
992         }
993
994 out:
995         return !!ret;
996 }
997
998 void print_device_chunks(int fd, struct device_info *devinfo,
999                 struct chunk_info *chunks_info_ptr,
1000                 int chunks_info_count, unsigned unit_mode)
1001 {
1002         int i;
1003         u64 allocated = 0;
1004
1005         for (i = 0 ; i < chunks_info_count ; i++) {
1006                 const char *description;
1007                 const char *r_mode;
1008                 u64 flags;
1009                 u64 size;
1010
1011                 if (chunks_info_ptr[i].devid != devinfo->devid)
1012                         continue;
1013
1014                 flags = chunks_info_ptr[i].type;
1015
1016                 description = btrfs_group_type_str(flags);
1017                 r_mode = btrfs_group_profile_str(flags);
1018                 size = calc_chunk_size(chunks_info_ptr+i);
1019                 printf("   %s,%s:%*s%10s\n",
1020                         description,
1021                         r_mode,
1022                         (int)(20 - strlen(description) - strlen(r_mode)), "",
1023                         pretty_size_mode(size, unit_mode));
1024
1025                 allocated += size;
1026
1027         }
1028         printf("   Unallocated: %*s%10s\n",
1029                 (int)(20 - strlen("Unallocated")), "",
1030                 pretty_size_mode(devinfo->size - allocated, unit_mode));
1031 }
1032
1033 void print_device_sizes(int fd, struct device_info *devinfo, unsigned unit_mode)
1034 {
1035         printf("   Device size: %*s%10s\n",
1036                 (int)(20 - strlen("Device size")), "",
1037                 pretty_size_mode(devinfo->device_size, unit_mode));
1038         printf("   Device slack: %*s%10s\n",
1039                 (int)(20 - strlen("Device slack")), "",
1040                 pretty_size_mode(devinfo->device_size - devinfo->size,
1041                         unit_mode));
1042 }