1 #include "units.h" 2 #include <inttypes.h> 3 #include <limits.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <linux/kernel.h> 7 #include <linux/time64.h> 8 9 unsigned long parse_tag_value(const char *str, struct parse_tag *tags) 10 { 11 struct parse_tag *i = tags; 12 13 while (i->tag) { 14 char *s = strchr(str, i->tag); 15 16 if (s) { 17 unsigned long int value; 18 char *endptr; 19 20 value = strtoul(str, &endptr, 10); 21 if (s != endptr) 22 break; 23 24 if (value > ULONG_MAX / i->mult) 25 break; 26 value *= i->mult; 27 return value; 28 } 29 i++; 30 } 31 32 return (unsigned long) -1; 33 } 34 35 unsigned long convert_unit(unsigned long value, char *unit) 36 { 37 *unit = ' '; 38 39 if (value > 1000) { 40 value /= 1000; 41 *unit = 'K'; 42 } 43 44 if (value > 1000) { 45 value /= 1000; 46 *unit = 'M'; 47 } 48 49 if (value > 1000) { 50 value /= 1000; 51 *unit = 'G'; 52 } 53 54 return value; 55 } 56 57 int unit_number__scnprintf(char *buf, size_t size, u64 n) 58 { 59 char unit[4] = "BKMG"; 60 int i = 0; 61 62 while (((n / 1024) > 1) && (i < 3)) { 63 n /= 1024; 64 i++; 65 } 66 67 return scnprintf(buf, size, "%" PRIu64 "%c", n, unit[i]); 68 } 69