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