btrfs-progs: check for negative return value from ioctl
[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 size = sizeof(struct btrfs_chunk) * (*info_count+1);
67                         struct chunk_info *res = realloc(*info_ptr, size);
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 += sh->len;
189
190                         sk->min_objectid = sh->objectid;
191                         sk->min_type = sh->type;
192                         sk->min_offset = sh->offset+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 occuped 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
341         sargs = load_space_info(fd, path);
342         if (!sargs) {
343                 ret = 1;
344                 goto exit;
345         }
346
347         r_total_size = 0;
348         for (i = 0; i < devcount; i++) {
349                 r_total_size += devinfo[i].size;
350                 if (!devinfo[i].device_size)
351                         r_total_missing += devinfo[i].size;
352         }
353
354         if (r_total_size == 0) {
355                 error("cannot get space info on '%s': %s",
356                         path, strerror(errno));
357
358                 ret = 1;
359                 goto exit;
360         }
361         get_raid56_used(fd, chunkinfo, chunkcount, &raid5_used, &raid6_used);
362
363         for (i = 0; i < sargs->total_spaces; i++) {
364                 int ratio;
365                 u64 flags = sargs->spaces[i].flags;
366
367                 /*
368                  * The raid5/raid6 ratio depends by the stripes number
369                  * used by every chunk. It is computed separately
370                  */
371                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
372                         ratio = 1;
373                 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
374                         ratio = 2;
375                 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
376                         ratio = 0;
377                 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
378                         ratio = 0;
379                 else if (flags & BTRFS_BLOCK_GROUP_DUP)
380                         ratio = 2;
381                 else if (flags & BTRFS_BLOCK_GROUP_RAID10)
382                         ratio = 2;
383                 else
384                         ratio = 1;
385
386                 if (!ratio)
387                         warning("RAID56 detected, not implemented");
388
389                 if (ratio > max_data_ratio)
390                         max_data_ratio = ratio;
391
392                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV) {
393                         l_global_reserve = sargs->spaces[i].total_bytes;
394                         l_global_reserve_used = sargs->spaces[i].used_bytes;
395                 }
396                 if ((flags & (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA))
397                         == (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA)) {
398                         warning("MIXED blockgroups not handled");
399                 }
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_metadata_chunks + r_system_chunks;
418         r_total_used = r_data_used + r_metadata_used + r_system_used;
419         r_total_unused = r_total_size - r_total_chunks;
420
421         /* Raw / Logical = raid factor, >= 1 */
422         data_ratio = (double)r_data_chunks / l_data_chunks;
423         metadata_ratio = (double)r_metadata_chunks / l_metadata_chunks;
424
425 #if 0
426         /* add the raid5/6 allocated space */
427         total_chunks += raid5_used + raid6_used;
428 #endif
429
430         /*
431          * We're able to fill at least DATA for the unused space
432          *
433          * With mixed raid levels, this gives a rough estimate but more
434          * accurate than just counting the logical free space
435          * (l_data_chunks - l_data_used)
436          *
437          * In non-mixed case there's no difference.
438          */
439         free_estimated = (r_data_chunks - r_data_used) / data_ratio;
440         free_min = free_estimated;
441
442         /* Chop unallocatable space */
443         /* FIXME: must be applied per device */
444         if (r_total_unused >= MIN_UNALOCATED_THRESH) {
445                 free_estimated += r_total_unused / data_ratio;
446                 /* Match the calculation of 'df', use the highest raid ratio */
447                 free_min += r_total_unused / max_data_ratio;
448         }
449
450         if (unit_mode != UNITS_HUMAN)
451                 width = 18;
452
453         printf("Overall:\n");
454
455         printf("    Device size:\t\t%*s\n", width,
456                 pretty_size_mode(r_total_size, unit_mode));
457         printf("    Device allocated:\t\t%*s\n", width,
458                 pretty_size_mode(r_total_chunks, unit_mode));
459         printf("    Device unallocated:\t\t%*s\n", width,
460                 pretty_size_mode(r_total_unused, unit_mode));
461         printf("    Device missing:\t\t%*s\n", width,
462                 pretty_size_mode(r_total_missing, unit_mode));
463         printf("    Used:\t\t\t%*s\n", width,
464                 pretty_size_mode(r_total_used, unit_mode));
465         printf("    Free (estimated):\t\t%*s\t(",
466                 width,
467                 pretty_size_mode(free_estimated, unit_mode));
468         printf("min: %s)\n", pretty_size_mode(free_min, unit_mode));
469         printf("    Data ratio:\t\t\t%*.2f\n",
470                 width, data_ratio);
471         printf("    Metadata ratio:\t\t%*.2f\n",
472                 width, metadata_ratio);
473         printf("    Global reserve:\t\t%*s\t(used: %s)\n", width,
474                 pretty_size_mode(l_global_reserve, unit_mode),
475                 pretty_size_mode(l_global_reserve_used, unit_mode));
476
477 exit:
478
479         if (sargs)
480                 free(sargs);
481
482         return ret;
483 }
484
485 /*
486  *  Helper to sort the device_info structure
487  */
488 static int cmp_device_info(const void *a, const void *b)
489 {
490         return strcmp(((struct device_info *)a)->path,
491                         ((struct device_info *)b)->path);
492 }
493
494 /*
495  *  This function loads the device_info structure and put them in an array
496  */
497 static int load_device_info(int fd, struct device_info **device_info_ptr,
498                            int *device_info_count)
499 {
500         int ret, i, ndevs;
501         struct btrfs_ioctl_fs_info_args fi_args;
502         struct btrfs_ioctl_dev_info_args dev_info;
503         struct device_info *info;
504
505         *device_info_count = 0;
506         *device_info_ptr = NULL;
507
508         ret = ioctl(fd, BTRFS_IOC_FS_INFO, &fi_args);
509         if (ret < 0) {
510                 if (errno == EPERM)
511                         return -errno;
512                 error("cannot get filesystem info: %s",
513                                 strerror(errno));
514                 return 1;
515         }
516
517         info = calloc(fi_args.num_devices, sizeof(struct device_info));
518         if (!info) {
519                 error("not enough memory");
520                 return 1;
521         }
522
523         for (i = 0, ndevs = 0 ; i <= fi_args.max_id ; i++) {
524                 BUG_ON(ndevs >= fi_args.num_devices);
525                 memset(&dev_info, 0, sizeof(dev_info));
526                 ret = get_device_info(fd, i, &dev_info);
527
528                 if (ret == -ENODEV)
529                         continue;
530                 if (ret) {
531                         error("cannot get info about device devid=%d", i);
532                         free(info);
533                         return ret;
534                 }
535
536                 info[ndevs].devid = dev_info.devid;
537                 if (!dev_info.path[0]) {
538                         strcpy(info[ndevs].path, "missing");
539                 } else {
540                         strcpy(info[ndevs].path, (char *)dev_info.path);
541                         info[ndevs].device_size =
542                                 get_partition_size((char *)dev_info.path);
543                 }
544                 info[ndevs].size = dev_info.total_bytes;
545                 ++ndevs;
546         }
547
548         BUG_ON(ndevs != fi_args.num_devices);
549         qsort(info, fi_args.num_devices,
550                 sizeof(struct device_info), cmp_device_info);
551
552         *device_info_count = fi_args.num_devices;
553         *device_info_ptr = info;
554
555         return 0;
556 }
557
558 int load_chunk_and_device_info(int fd, struct chunk_info **chunkinfo,
559                 int *chunkcount, struct device_info **devinfo, int *devcount)
560 {
561         int ret;
562
563         ret = load_chunk_info(fd, chunkinfo, chunkcount);
564         if (ret == -EPERM) {
565                 warning(
566 "cannot read detailed chunk info, RAID5/6 numbers will be incorrect, run as root");
567         } else if (ret) {
568                 return ret;
569         }
570
571         ret = load_device_info(fd, devinfo, devcount);
572         if (ret == -EPERM) {
573                 warning(
574                 "cannot get filesystem info from ioctl(FS_INFO), run as root");
575                 ret = 0;
576         }
577
578         return ret;
579 }
580
581 /*
582  *  This function computes the size of a chunk in a disk
583  */
584 static u64 calc_chunk_size(struct chunk_info *ci)
585 {
586         if (ci->type & BTRFS_BLOCK_GROUP_RAID0)
587                 return ci->size / ci->num_stripes;
588         else if (ci->type & BTRFS_BLOCK_GROUP_RAID1)
589                 return ci->size ;
590         else if (ci->type & BTRFS_BLOCK_GROUP_DUP)
591                 return ci->size ;
592         else if (ci->type & BTRFS_BLOCK_GROUP_RAID5)
593                 return ci->size / (ci->num_stripes -1);
594         else if (ci->type & BTRFS_BLOCK_GROUP_RAID6)
595                 return ci->size / (ci->num_stripes -2);
596         else if (ci->type & BTRFS_BLOCK_GROUP_RAID10)
597                 return ci->size / ci->num_stripes;
598         return ci->size;
599 }
600
601 /*
602  *  This function print the results of the command "btrfs fi usage"
603  *  in tabular format
604  */
605 static void _cmd_filesystem_usage_tabular(unsigned unit_mode,
606                                         struct btrfs_ioctl_space_args *sargs,
607                                         struct chunk_info *chunks_info_ptr,
608                                         int chunks_info_count,
609                                         struct device_info *device_info_ptr,
610                                         int device_info_count)
611 {
612         int i;
613         u64 total_unused = 0;
614         struct string_table *matrix = NULL;
615         int  ncols, nrows;
616         int col;
617         int unallocated_col;
618         int spaceinfos_col;
619         const int vhdr_skip = 3;        /* amount of vertical header space */
620
621         /* id, path, unallocated */
622         ncols = 3;
623         spaceinfos_col = 2;
624         /* Properly count the real space infos */
625         for (i = 0; i < sargs->total_spaces; i++) {
626                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
627                         continue;
628                 ncols++;
629         }
630
631         /* 2 for header, empty line, devices, ===, total, used */
632         nrows = vhdr_skip + device_info_count + 1 + 2;
633
634         matrix = table_create(ncols, nrows);
635         if (!matrix) {
636                 error("not enough memory");
637                 return;
638         }
639
640         /*
641          * We have to skip the global block reserve everywhere as it's an
642          * artificial blockgroup
643          */
644
645         /* header */
646         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
647                 u64 flags = sargs->spaces[i].flags;
648
649                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
650                         continue;
651
652                 table_printf(matrix, col, 0, "<%s",
653                                 btrfs_group_type_str(flags));
654                 table_printf(matrix, col, 1, "<%s",
655                                 btrfs_group_profile_str(flags));
656                 col++;
657         }
658         unallocated_col = col;
659
660         table_printf(matrix, 0, 1, "<Id");
661         table_printf(matrix, 1, 1, "<Path");
662         table_printf(matrix, unallocated_col, 1, "<Unallocated");
663
664         /* body */
665         for (i = 0; i < device_info_count; i++) {
666                 int k;
667                 char *p;
668
669                 u64  total_allocated = 0, unused;
670
671                 p = strrchr(device_info_ptr[i].path, '/');
672                 if (!p)
673                         p = device_info_ptr[i].path;
674                 else
675                         p++;
676
677                 table_printf(matrix, 0, vhdr_skip + i, ">%llu",
678                                 device_info_ptr[i].devid);
679                 table_printf(matrix, 1, vhdr_skip + i, "<%s",
680                                 device_info_ptr[i].path);
681
682                 for (col = spaceinfos_col, k = 0; k < sargs->total_spaces; k++) {
683                         u64     flags = sargs->spaces[k].flags;
684                         u64 devid = device_info_ptr[i].devid;
685                         int     j;
686                         u64 size = 0;
687
688                         if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
689                                 continue;
690
691                         for (j = 0 ; j < chunks_info_count ; j++) {
692                                 if (chunks_info_ptr[j].type != flags )
693                                                 continue;
694                                 if (chunks_info_ptr[j].devid != devid)
695                                                 continue;
696
697                                 size += calc_chunk_size(chunks_info_ptr+j);
698                         }
699
700                         if (size)
701                                 table_printf(matrix, col, vhdr_skip+ i,
702                                         ">%s", pretty_size_mode(size, unit_mode));
703                         else
704                                 table_printf(matrix, col, vhdr_skip + i, ">-");
705
706                         total_allocated += size;
707                         col++;
708                 }
709
710                 unused = get_partition_size(device_info_ptr[i].path)
711                                 - total_allocated;
712
713                 table_printf(matrix, unallocated_col, vhdr_skip + i,
714                                ">%s", pretty_size_mode(unused, unit_mode));
715                 total_unused += unused;
716
717         }
718
719         for (i = 0; i < spaceinfos_col; i++) {
720                 table_printf(matrix, i, vhdr_skip - 1, "*-");
721                 table_printf(matrix, i, vhdr_skip + device_info_count, "*-");
722         }
723
724         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
725                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
726                         continue;
727
728                 table_printf(matrix, col, vhdr_skip - 1, "*-");
729                 table_printf(matrix, col, vhdr_skip + device_info_count, "*-");
730                 col++;
731         }
732         /* One for Unallocated */
733         table_printf(matrix, col, vhdr_skip - 1, "*-");
734         table_printf(matrix, col, vhdr_skip + device_info_count, "*-");
735
736         /* footer */
737         table_printf(matrix, 1, vhdr_skip + device_info_count + 1, "<Total");
738         for (i = 0, col = spaceinfos_col; i < sargs->total_spaces; i++) {
739                 if (sargs->spaces[i].flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
740                         continue;
741
742                 table_printf(matrix, col++, vhdr_skip + device_info_count + 1,
743                         ">%s",
744                         pretty_size_mode(sargs->spaces[i].total_bytes, unit_mode));
745         }
746
747         table_printf(matrix, unallocated_col, vhdr_skip + device_info_count + 1,
748                         ">%s", pretty_size_mode(total_unused, unit_mode));
749
750         table_printf(matrix, 1, vhdr_skip + device_info_count + 2, "<Used");
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 + device_info_count + 2,
756                         ">%s",
757                         pretty_size_mode(sargs->spaces[i].used_bytes, unit_mode));
758         }
759
760         table_dump(matrix);
761         table_free(matrix);
762 }
763
764 /*
765  *  This function prints the unused space per every disk
766  */
767 static void print_unused(struct chunk_info *info_ptr,
768                           int info_count,
769                           struct device_info *device_info_ptr,
770                           int device_info_count,
771                           unsigned unit_mode)
772 {
773         int i;
774         for (i = 0; i < device_info_count; i++) {
775                 int     j;
776                 u64     total = 0;
777
778                 for (j = 0; j < info_count; j++)
779                         if (info_ptr[j].devid == device_info_ptr[i].devid)
780                                 total += calc_chunk_size(info_ptr+j);
781
782                 printf("   %s\t%10s\n",
783                         device_info_ptr[i].path,
784                         pretty_size_mode(device_info_ptr[i].size - total,
785                                 unit_mode));
786         }
787 }
788
789 /*
790  *  This function prints the allocated chunk per every disk
791  */
792 static void print_chunk_device(u64 chunk_type,
793                                 struct chunk_info *chunks_info_ptr,
794                                 int chunks_info_count,
795                                 struct device_info *device_info_ptr,
796                                 int device_info_count,
797                                 unsigned unit_mode)
798 {
799         int i;
800
801         for (i = 0; i < device_info_count; i++) {
802                 int     j;
803                 u64     total = 0;
804
805                 for (j = 0; j < chunks_info_count; j++) {
806
807                         if (chunks_info_ptr[j].type != chunk_type)
808                                 continue;
809                         if (chunks_info_ptr[j].devid != device_info_ptr[i].devid)
810                                 continue;
811
812                         total += calc_chunk_size(&(chunks_info_ptr[j]));
813                         //total += chunks_info_ptr[j].size;
814                 }
815
816                 if (total > 0)
817                         printf("   %s\t%10s\n",
818                                 device_info_ptr[i].path,
819                                 pretty_size_mode(total, unit_mode));
820         }
821 }
822
823 /*
824  *  This function print the results of the command "btrfs fi usage"
825  *  in linear format
826  */
827 static void _cmd_filesystem_usage_linear(unsigned unit_mode,
828                                         struct btrfs_ioctl_space_args *sargs,
829                                         struct chunk_info *info_ptr,
830                                         int info_count,
831                                         struct device_info *device_info_ptr,
832                                         int device_info_count)
833 {
834         int i;
835
836         for (i = 0; i < sargs->total_spaces; i++) {
837                 const char *description;
838                 const char *r_mode;
839                 u64 flags = sargs->spaces[i].flags;
840
841                 if (flags & BTRFS_SPACE_INFO_GLOBAL_RSV)
842                         continue;
843
844                 description = btrfs_group_type_str(flags);
845                 r_mode = btrfs_group_profile_str(flags);
846
847                 printf("%s,%s: Size:%s, ",
848                         description,
849                         r_mode,
850                         pretty_size_mode(sargs->spaces[i].total_bytes,
851                                 unit_mode));
852                 printf("Used:%s\n",
853                         pretty_size_mode(sargs->spaces[i].used_bytes, unit_mode));
854                 print_chunk_device(flags, info_ptr, info_count,
855                                 device_info_ptr, device_info_count, unit_mode);
856                 printf("\n");
857         }
858
859         printf("Unallocated:\n");
860         print_unused(info_ptr, info_count, device_info_ptr, device_info_count,
861                         unit_mode);
862 }
863
864 static int print_filesystem_usage_by_chunk(int fd,
865                 struct chunk_info *chunkinfo, int chunkcount,
866                 struct device_info *devinfo, int devcount,
867                 char *path, unsigned unit_mode, int tabular)
868 {
869         struct btrfs_ioctl_space_args *sargs;
870         int ret = 0;
871
872         if (!chunkinfo)
873                 return 0;
874
875         sargs = load_space_info(fd, path);
876         if (!sargs) {
877                 ret = 1;
878                 goto out;
879         }
880
881         if (tabular)
882                 _cmd_filesystem_usage_tabular(unit_mode, sargs, chunkinfo,
883                                 chunkcount, devinfo, devcount);
884         else
885                 _cmd_filesystem_usage_linear(unit_mode, sargs, chunkinfo,
886                                 chunkcount, devinfo, devcount);
887
888         free(sargs);
889 out:
890         return ret;
891 }
892
893 const char * const cmd_filesystem_usage_usage[] = {
894         "btrfs filesystem usage [options] <path> [<path>..]",
895         "Show detailed information about internal filesystem usage .",
896         HELPINFO_UNITS_SHORT_LONG,
897         "-T                 show data in tabular format",
898         NULL
899 };
900
901 int cmd_filesystem_usage(int argc, char **argv)
902 {
903         int ret = 0;
904         unsigned unit_mode;
905         int i;
906         int more_than_one = 0;
907         int tabular = 0;
908
909         unit_mode = get_unit_mode_from_arg(&argc, argv, 1);
910
911         optind = 1;
912         while (1) {
913                 int c;
914
915                 c = getopt(argc, argv, "T");
916                 if (c < 0)
917                         break;
918
919                 switch (c) {
920                 case 'T':
921                         tabular = 1;
922                         break;
923                 default:
924                         usage(cmd_filesystem_usage_usage);
925                 }
926         }
927
928         if (check_argc_min(argc - optind, 1))
929                 usage(cmd_filesystem_usage_usage);
930
931         for (i = optind; i < argc; i++) {
932                 int fd;
933                 DIR *dirstream = NULL;
934                 struct chunk_info *chunkinfo = NULL;
935                 struct device_info *devinfo = NULL;
936                 int chunkcount = 0;
937                 int devcount = 0;
938
939                 fd = btrfs_open_dir(argv[i], &dirstream, 1);
940                 if (fd < 0) {
941                         ret = 1;
942                         goto out;
943                 }
944                 if (more_than_one)
945                         printf("\n");
946
947                 ret = load_chunk_and_device_info(fd, &chunkinfo, &chunkcount,
948                                 &devinfo, &devcount);
949                 if (ret)
950                         goto cleanup;
951
952                 ret = print_filesystem_usage_overall(fd, chunkinfo, chunkcount,
953                                 devinfo, devcount, argv[i], unit_mode);
954                 if (ret)
955                         goto cleanup;
956                 printf("\n");
957                 ret = print_filesystem_usage_by_chunk(fd, chunkinfo, chunkcount,
958                                 devinfo, devcount, argv[i], unit_mode, tabular);
959 cleanup:
960                 close_file_or_dir(fd, dirstream);
961                 free(chunkinfo);
962                 free(devinfo);
963
964                 if (ret)
965                         goto out;
966                 more_than_one = 1;
967         }
968
969 out:
970         return !!ret;
971 }
972
973 void print_device_chunks(int fd, struct device_info *devinfo,
974                 struct chunk_info *chunks_info_ptr,
975                 int chunks_info_count, unsigned unit_mode)
976 {
977         int i;
978         u64 allocated = 0;
979
980         for (i = 0 ; i < chunks_info_count ; i++) {
981                 const char *description;
982                 const char *r_mode;
983                 u64 flags;
984                 u64 size;
985
986                 if (chunks_info_ptr[i].devid != devinfo->devid)
987                         continue;
988
989                 flags = chunks_info_ptr[i].type;
990
991                 description = btrfs_group_type_str(flags);
992                 r_mode = btrfs_group_profile_str(flags);
993                 size = calc_chunk_size(chunks_info_ptr+i);
994                 printf("   %s,%s:%*s%10s\n",
995                         description,
996                         r_mode,
997                         (int)(20 - strlen(description) - strlen(r_mode)), "",
998                         pretty_size_mode(size, unit_mode));
999
1000                 allocated += size;
1001
1002         }
1003         printf("   Unallocated: %*s%10s\n",
1004                 (int)(20 - strlen("Unallocated")), "",
1005                 pretty_size_mode(devinfo->size - allocated, unit_mode));
1006 }
1007
1008 void print_device_sizes(int fd, struct device_info *devinfo, unsigned unit_mode)
1009 {
1010         printf("   Device size: %*s%10s\n",
1011                 (int)(20 - strlen("Device size")), "",
1012                 pretty_size_mode(devinfo->device_size, unit_mode));
1013 #if 0
1014         /*
1015          * The term has not seen an agreement and we don't want to change it
1016          * once it's in non-development branches or even released.
1017          */
1018         printf("   FS occupied: %*s%10s\n",
1019                 (int)(20 - strlen("FS occupied")), "",
1020                 pretty_size_mode(devinfo->size, unit_mode));
1021 #endif
1022 }