// SPDX-License-Identifier: GPL-2.0-only12#include <linux/bitmap.h>3#include <linux/ctype.h>4#include <linux/errno.h>5#include <linux/err.h>6#include <linux/export.h>7#include <linux/hex.h>8#include <linux/kernel.h>9#include <linux/mm.h>10#include <linux/string.h>1112#include "kstrtox.h"1314/**15* bitmap_parse_user - convert an ASCII hex string in a user buffer into a bitmap16*17* @ubuf: pointer to user buffer containing string.18* @ulen: buffer size in bytes. If string is smaller than this19* then it must be terminated with a \0.20* @maskp: pointer to bitmap array that will contain result.21* @nmaskbits: size of bitmap, in bits.22*/23int bitmap_parse_user(const char __user *ubuf,24unsigned int ulen, unsigned long *maskp,25int nmaskbits)26{27char *buf;28int ret;2930buf = memdup_user_nul(ubuf, ulen);31if (IS_ERR(buf))32return PTR_ERR(buf);3334ret = bitmap_parse(buf, UINT_MAX, maskp, nmaskbits);3536kfree(buf);37return ret;38}39EXPORT_SYMBOL(bitmap_parse_user);4041/**42* bitmap_print_to_pagebuf - convert bitmap to list or hex format ASCII string43* @list: indicates whether the bitmap must be list44* @buf: page aligned buffer into which string is placed45* @maskp: pointer to bitmap to convert46* @nmaskbits: size of bitmap, in bits47*48* Output format is a comma-separated list of decimal numbers and49* ranges if list is specified or hex digits grouped into comma-separated50* sets of 8 digits/set. Returns the number of characters written to buf.51*52* It is assumed that @buf is a pointer into a PAGE_SIZE, page-aligned53* area and that sufficient storage remains at @buf to accommodate the54* bitmap_print_to_pagebuf() output. Returns the number of characters55* actually printed to @buf, excluding terminating '\0'.56*/57int bitmap_print_to_pagebuf(bool list, char *buf, const unsigned long *maskp,58int nmaskbits)59{60ptrdiff_t len = PAGE_SIZE - offset_in_page(buf);6162return list ? scnprintf(buf, len, "%*pbl\n", nmaskbits, maskp) :63scnprintf(buf, len, "%*pb\n", nmaskbits, maskp);64}65EXPORT_SYMBOL(bitmap_print_to_pagebuf);6667/**68* bitmap_print_to_buf - convert bitmap to list or hex format ASCII string69* @list: indicates whether the bitmap must be list70* true: print in decimal list format71* false: print in hexadecimal bitmask format72* @buf: buffer into which string is placed73* @maskp: pointer to bitmap to convert74* @nmaskbits: size of bitmap, in bits75* @off: in the string from which we are copying, We copy to @buf76* @count: the maximum number of bytes to print77*/78static int bitmap_print_to_buf(bool list, char *buf, const unsigned long *maskp,79int nmaskbits, loff_t off, size_t count)80{81const char *fmt = list ? "%*pbl\n" : "%*pb\n";82ssize_t size;83void *data;8485data = kasprintf(GFP_KERNEL, fmt, nmaskbits, maskp);86if (!data)87return -ENOMEM;8889size = memory_read_from_buffer(buf, count, &off, data, strlen(data) + 1);90kfree(data);9192return size;93}9495/**96* bitmap_print_bitmask_to_buf - convert bitmap to hex bitmask format ASCII string97* @buf: buffer into which string is placed98* @maskp: pointer to bitmap to convert99* @nmaskbits: size of bitmap, in bits100* @off: in the string from which we are copying, We copy to @buf101* @count: the maximum number of bytes to print102*103* The bitmap_print_to_pagebuf() is used indirectly via its cpumap wrapper104* cpumap_print_to_pagebuf() or directly by drivers to export hexadecimal105* bitmask and decimal list to userspace by sysfs ABI.106* Drivers might be using a normal attribute for this kind of ABIs. A107* normal attribute typically has show entry as below::108*109* static ssize_t example_attribute_show(struct device *dev,110* struct device_attribute *attr, char *buf)111* {112* ...113* return bitmap_print_to_pagebuf(true, buf, &mask, nr_trig_max);114* }115*116* show entry of attribute has no offset and count parameters and this117* means the file is limited to one page only.118* bitmap_print_to_pagebuf() API works terribly well for this kind of119* normal attribute with buf parameter and without offset, count::120*121* bitmap_print_to_pagebuf(bool list, char *buf, const unsigned long *maskp,122* int nmaskbits)123* {124* }125*126* The problem is once we have a large bitmap, we have a chance to get a127* bitmask or list more than one page. Especially for list, it could be128* as complex as 0,3,5,7,9,... We have no simple way to know it exact size.129* It turns out bin_attribute is a way to break this limit. bin_attribute130* has show entry as below::131*132* static ssize_t133* example_bin_attribute_show(struct file *filp, struct kobject *kobj,134* struct bin_attribute *attr, char *buf,135* loff_t offset, size_t count)136* {137* ...138* }139*140* With the new offset and count parameters, this makes sysfs ABI be able141* to support file size more than one page. For example, offset could be142* >= 4096.143* bitmap_print_bitmask_to_buf(), bitmap_print_list_to_buf() wit their144* cpumap wrapper cpumap_print_bitmask_to_buf(), cpumap_print_list_to_buf()145* make those drivers be able to support large bitmask and list after they146* move to use bin_attribute. In result, we have to pass the corresponding147* parameters such as off, count from bin_attribute show entry to this API.148*149* The role of cpumap_print_bitmask_to_buf() and cpumap_print_list_to_buf()150* is similar with cpumap_print_to_pagebuf(), the difference is that151* bitmap_print_to_pagebuf() mainly serves sysfs attribute with the assumption152* the destination buffer is exactly one page and won't be more than one page.153* cpumap_print_bitmask_to_buf() and cpumap_print_list_to_buf(), on the other154* hand, mainly serves bin_attribute which doesn't work with exact one page,155* and it can break the size limit of converted decimal list and hexadecimal156* bitmask.157*158* WARNING!159*160* This function is not a replacement for sprintf() or bitmap_print_to_pagebuf().161* It is intended to workaround sysfs limitations discussed above and should be162* used carefully in general case for the following reasons:163*164* - Time complexity is O(nbits^2/count), comparing to O(nbits) for snprintf().165* - Memory complexity is O(nbits), comparing to O(1) for snprintf().166* - @off and @count are NOT offset and number of bits to print.167* - If printing part of bitmap as list, the resulting string is not a correct168* list representation of bitmap. Particularly, some bits within or out of169* related interval may be erroneously set or unset. The format of the string170* may be broken, so bitmap_parselist-like parser may fail parsing it.171* - If printing the whole bitmap as list by parts, user must ensure the order172* of calls of the function such that the offset is incremented linearly.173* - If printing the whole bitmap as list by parts, user must keep bitmap174* unchanged between the very first and very last call. Otherwise concatenated175* result may be incorrect, and format may be broken.176*177* Returns the number of characters actually printed to @buf178*/179int bitmap_print_bitmask_to_buf(char *buf, const unsigned long *maskp,180int nmaskbits, loff_t off, size_t count)181{182return bitmap_print_to_buf(false, buf, maskp, nmaskbits, off, count);183}184EXPORT_SYMBOL(bitmap_print_bitmask_to_buf);185186/**187* bitmap_print_list_to_buf - convert bitmap to decimal list format ASCII string188* @buf: buffer into which string is placed189* @maskp: pointer to bitmap to convert190* @nmaskbits: size of bitmap, in bits191* @off: in the string from which we are copying, We copy to @buf192* @count: the maximum number of bytes to print193*194* Everything is same with the above bitmap_print_bitmask_to_buf() except195* the print format.196*/197int bitmap_print_list_to_buf(char *buf, const unsigned long *maskp,198int nmaskbits, loff_t off, size_t count)199{200return bitmap_print_to_buf(true, buf, maskp, nmaskbits, off, count);201}202EXPORT_SYMBOL(bitmap_print_list_to_buf);203204/*205* Region 9-38:4/10 describes the following bitmap structure:206* 0 9 12 18 38 N207* .........****......****......****..................208* ^ ^ ^ ^ ^209* start off group_len end nbits210*/211struct region {212unsigned int start;213unsigned int off;214unsigned int group_len;215unsigned int end;216unsigned int nbits;217};218219static void bitmap_set_region(const struct region *r, unsigned long *bitmap)220{221unsigned int start;222223for (start = r->start; start <= r->end; start += r->group_len)224bitmap_set(bitmap, start, min(r->end - start + 1, r->off));225}226227static int bitmap_check_region(const struct region *r)228{229if (r->start > r->end || r->group_len == 0 || r->off > r->group_len)230return -EINVAL;231232if (r->end >= r->nbits)233return -ERANGE;234235return 0;236}237238static const char *bitmap_getnum(const char *str, unsigned int *num,239unsigned int lastbit)240{241unsigned long long n;242unsigned int len;243244if (str[0] == 'N') {245*num = lastbit;246return str + 1;247}248249len = _parse_integer(str, 10, &n);250if (!len)251return ERR_PTR(-EINVAL);252if (len & KSTRTOX_OVERFLOW || n != (unsigned int)n)253return ERR_PTR(-EOVERFLOW);254255*num = n;256return str + len;257}258259static inline bool end_of_str(char c)260{261return c == '\0' || c == '\n';262}263264static inline bool __end_of_region(char c)265{266return isspace(c) || c == ',';267}268269static inline bool end_of_region(char c)270{271return __end_of_region(c) || end_of_str(c);272}273274/*275* The format allows commas and whitespaces at the beginning276* of the region.277*/278static const char *bitmap_find_region(const char *str)279{280while (__end_of_region(*str))281str++;282283return end_of_str(*str) ? NULL : str;284}285286static const char *bitmap_find_region_reverse(const char *start, const char *end)287{288while (start <= end && __end_of_region(*end))289end--;290291return end;292}293294static const char *bitmap_parse_region(const char *str, struct region *r)295{296unsigned int lastbit = r->nbits - 1;297298if (!strncasecmp(str, "all", 3)) {299r->start = 0;300r->end = lastbit;301str += 3;302303goto check_pattern;304}305306str = bitmap_getnum(str, &r->start, lastbit);307if (IS_ERR(str))308return str;309310if (end_of_region(*str))311goto no_end;312313if (*str != '-')314return ERR_PTR(-EINVAL);315316str = bitmap_getnum(str + 1, &r->end, lastbit);317if (IS_ERR(str))318return str;319320check_pattern:321if (end_of_region(*str))322goto no_pattern;323324if (*str != ':')325return ERR_PTR(-EINVAL);326327str = bitmap_getnum(str + 1, &r->off, lastbit);328if (IS_ERR(str))329return str;330331if (*str != '/')332return ERR_PTR(-EINVAL);333334return bitmap_getnum(str + 1, &r->group_len, lastbit);335336no_end:337r->end = r->start;338no_pattern:339r->off = r->end + 1;340r->group_len = r->end + 1;341342return end_of_str(*str) ? NULL : str;343}344345/**346* bitmap_parselist - convert list format ASCII string to bitmap347* @buf: read user string from this buffer; must be terminated348* with a \0 or \n.349* @maskp: write resulting mask here350* @nmaskbits: number of bits in mask to be written351*352* Input format is a comma-separated list of decimal numbers and353* ranges. Consecutively set bits are shown as two hyphen-separated354* decimal numbers, the smallest and largest bit numbers set in355* the range.356* Optionally each range can be postfixed to denote that only parts of it357* should be set. The range will divided to groups of specific size.358* From each group will be used only defined amount of bits.359* Syntax: range:used_size/group_size360* Example: 0-1023:2/256 ==> 0,1,256,257,512,513,768,769361* The value 'N' can be used as a dynamically substituted token for the362* maximum allowed value; i.e (nmaskbits - 1). Keep in mind that it is363* dynamic, so if system changes cause the bitmap width to change, such364* as more cores in a CPU list, then any ranges using N will also change.365*366* Returns: 0 on success, -errno on invalid input strings. Error values:367*368* - ``-EINVAL``: wrong region format369* - ``-EINVAL``: invalid character in string370* - ``-ERANGE``: bit number specified too large for mask371* - ``-EOVERFLOW``: integer overflow in the input parameters372*/373int bitmap_parselist(const char *buf, unsigned long *maskp, int nmaskbits)374{375struct region r;376long ret;377378r.nbits = nmaskbits;379bitmap_zero(maskp, r.nbits);380381while (buf) {382buf = bitmap_find_region(buf);383if (buf == NULL)384return 0;385386buf = bitmap_parse_region(buf, &r);387if (IS_ERR(buf))388return PTR_ERR(buf);389390ret = bitmap_check_region(&r);391if (ret)392return ret;393394bitmap_set_region(&r, maskp);395}396397return 0;398}399EXPORT_SYMBOL(bitmap_parselist);400401402/**403* bitmap_parselist_user() - convert user buffer's list format ASCII404* string to bitmap405*406* @ubuf: pointer to user buffer containing string.407* @ulen: buffer size in bytes. If string is smaller than this408* then it must be terminated with a \0.409* @maskp: pointer to bitmap array that will contain result.410* @nmaskbits: size of bitmap, in bits.411*412* Wrapper for bitmap_parselist(), providing it with user buffer.413*/414int bitmap_parselist_user(const char __user *ubuf,415unsigned int ulen, unsigned long *maskp,416int nmaskbits)417{418char *buf;419int ret;420421buf = memdup_user_nul(ubuf, ulen);422if (IS_ERR(buf))423return PTR_ERR(buf);424425ret = bitmap_parselist(buf, maskp, nmaskbits);426427kfree(buf);428return ret;429}430EXPORT_SYMBOL(bitmap_parselist_user);431432static const char *bitmap_get_x32_reverse(const char *start,433const char *end, u32 *num)434{435u32 ret = 0;436int c, i;437438for (i = 0; i < 32; i += 4) {439c = hex_to_bin(*end--);440if (c < 0)441return ERR_PTR(-EINVAL);442443ret |= c << i;444445if (start > end || __end_of_region(*end))446goto out;447}448449if (hex_to_bin(*end--) >= 0)450return ERR_PTR(-EOVERFLOW);451out:452*num = ret;453return end;454}455456/**457* bitmap_parse - convert an ASCII hex string into a bitmap.458* @start: pointer to buffer containing string.459* @buflen: buffer size in bytes. If string is smaller than this460* then it must be terminated with a \0 or \n. In that case,461* UINT_MAX may be provided instead of string length.462* @maskp: pointer to bitmap array that will contain result.463* @nmaskbits: size of bitmap, in bits.464*465* Commas group hex digits into chunks. Each chunk defines exactly 32466* bits of the resultant bitmask. No chunk may specify a value larger467* than 32 bits (%-EOVERFLOW), and if a chunk specifies a smaller value468* then leading 0-bits are prepended. %-EINVAL is returned for illegal469* characters. Grouping such as "1,,5", ",44", "," or "" is allowed.470* Leading, embedded and trailing whitespace accepted.471*/472int bitmap_parse(const char *start, unsigned int buflen,473unsigned long *maskp, int nmaskbits)474{475const char *end = strnchrnul(start, buflen, '\n') - 1;476int chunks = BITS_TO_U32(nmaskbits);477u32 *bitmap = (u32 *)maskp;478int unset_bit;479int chunk;480481for (chunk = 0; ; chunk++) {482end = bitmap_find_region_reverse(start, end);483if (start > end)484break;485486if (!chunks--)487return -EOVERFLOW;488489#if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)490end = bitmap_get_x32_reverse(start, end, &bitmap[chunk ^ 1]);491#else492end = bitmap_get_x32_reverse(start, end, &bitmap[chunk]);493#endif494if (IS_ERR(end))495return PTR_ERR(end);496}497498unset_bit = (BITS_TO_U32(nmaskbits) - chunks) * 32;499if (unset_bit < nmaskbits) {500bitmap_clear(maskp, unset_bit, nmaskbits - unset_bit);501return 0;502}503504if (find_next_bit(maskp, unset_bit, nmaskbits) != unset_bit)505return -EOVERFLOW;506507return 0;508}509EXPORT_SYMBOL(bitmap_parse);510511512