xref: /linux/lib/bitmap-str.c (revision d075c4dc0b3c8ed91a4f67ebdf3384aa59fd4fbb)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #include <linux/bitmap.h>
4 #include <linux/ctype.h>
5 #include <linux/errno.h>
6 #include <linux/err.h>
7 #include <linux/export.h>
8 #include <linux/hex.h>
9 #include <linux/kernel.h>
10 #include <linux/mm.h>
11 #include <linux/overflow.h>
12 #include <linux/string.h>
13 
14 #include "kstrtox.h"
15 
16 /**
17  * bitmap_parse_user - convert an ASCII hex string in a user buffer into a bitmap
18  *
19  * @ubuf: pointer to user buffer containing string.
20  * @ulen: buffer size in bytes.  If string is smaller than this
21  *    then it must be terminated with a \0.
22  * @maskp: pointer to bitmap array that will contain result.
23  * @nmaskbits: size of bitmap, in bits.
24  */
25 int bitmap_parse_user(const char __user *ubuf,
26 			unsigned int ulen, unsigned long *maskp,
27 			int nmaskbits)
28 {
29 	char *buf;
30 	int ret;
31 
32 	buf = memdup_user_nul(ubuf, ulen);
33 	if (IS_ERR(buf))
34 		return PTR_ERR(buf);
35 
36 	ret = bitmap_parse(buf, UINT_MAX, maskp, nmaskbits);
37 
38 	kfree(buf);
39 	return ret;
40 }
41 EXPORT_SYMBOL(bitmap_parse_user);
42 
43 /**
44  * bitmap_print_to_buf  - convert bitmap to list or hex format ASCII string
45  * @list: indicates whether the bitmap must be list
46  *      true:  print in decimal list format
47  *      false: print in hexadecimal bitmask format
48  * @buf: buffer into which string is placed
49  * @maskp: pointer to bitmap to convert
50  * @nmaskbits: size of bitmap, in bits
51  * @off: in the string from which we are copying, We copy to @buf
52  * @count: the maximum number of bytes to print
53  */
54 static int bitmap_print_to_buf(bool list, char *buf, const unsigned long *maskp,
55 		int nmaskbits, loff_t off, size_t count)
56 {
57 	const char *fmt = list ? "%*pbl\n" : "%*pb\n";
58 	ssize_t size;
59 	void *data;
60 
61 	data = kasprintf(GFP_KERNEL, fmt, nmaskbits, maskp);
62 	if (!data)
63 		return -ENOMEM;
64 
65 	size = memory_read_from_buffer(buf, count, &off, data, strlen(data) + 1);
66 	kfree(data);
67 
68 	return size;
69 }
70 
71 /**
72  * bitmap_print_bitmask_to_buf  - convert bitmap to hex bitmask format ASCII string
73  * @buf: buffer into which string is placed
74  * @maskp: pointer to bitmap to convert
75  * @nmaskbits: size of bitmap, in bits
76  * @off: in the string from which we are copying, We copy to @buf
77  * @count: the maximum number of bytes to print
78  *
79  * The sprintf("%*pb[l]") format is used by drivers to export hexadecimal
80  * bitmask and decimal list to userspace by sysfs ABI.
81  * Drivers might be using a normal attribute for this kind of ABIs. A
82  * normal attribute typically has show entry as below::
83  *
84  *   static ssize_t example_attribute_show(struct device *dev,
85  *		struct device_attribute *attr, char *buf)
86  *   {
87  *	...
88  *	return scnprintf(buf, PAGE_SIZE - offset_in_page(buf), nr_trig_max, &mask);
89  *   }
90  *
91  * show entry of attribute has no offset and count parameters and this
92  * means the file is limited to one page only.
93  *
94  * The problem is once we have a large bitmap, we have a chance to get a
95  * bitmask or list more than one page. Especially for list, it could be
96  * as complex as 0,3,5,7,9,... We have no simple way to know it exact size.
97  * It turns out bin_attribute is a way to break this limit. bin_attribute
98  * has show entry as below::
99  *
100  *   static ssize_t
101  *   example_bin_attribute_show(struct file *filp, struct kobject *kobj,
102  *		struct bin_attribute *attr, char *buf,
103  *		loff_t offset, size_t count)
104  *   {
105  *	...
106  *   }
107  *
108  * With the new offset and count parameters, this makes sysfs ABI be able
109  * to support file size more than one page. For example, offset could be
110  * >= 4096.
111  * bitmap_print_bitmask_to_buf(), bitmap_print_list_to_buf() wit their
112  * cpumap wrapper cpumap_print_bitmask_to_buf(), cpumap_print_list_to_buf()
113  * make those drivers be able to support large bitmask and list after they
114  * move to use bin_attribute. In result, we have to pass the corresponding
115  * parameters such as off, count from bin_attribute show entry to this API.
116  *
117  * The role of cpumap_print_bitmask_to_buf() and cpumap_print_list_to_buf()
118  * is similar to direct sysfs_emit("%*pb[l]") formatting, but the latter
119  * assumes the destination buffer is exactly one page and won't be more than
120  * one page.
121  * cpumap_print_bitmask_to_buf() and cpumap_print_list_to_buf(), on the other
122  * hand, mainly serves bin_attribute which doesn't work with exact one page,
123  * and it can break the size limit of converted decimal list and hexadecimal
124  * bitmask.
125  *
126  * WARNING!
127  *
128  * This function is not a replacement for sprintf().
129  *
130  * It is intended to workaround sysfs limitations discussed above and should be
131  * used carefully in general case for the following reasons:
132  *
133  *  - Time complexity is O(nbits^2/count), comparing to O(nbits) for snprintf().
134  *  - Memory complexity is O(nbits), comparing to O(1) for snprintf().
135  *  - @off and @count are NOT offset and number of bits to print.
136  *  - If printing part of bitmap as list, the resulting string is not a correct
137  *    list representation of bitmap. Particularly, some bits within or out of
138  *    related interval may be erroneously set or unset. The format of the string
139  *    may be broken, so bitmap_parselist-like parser may fail parsing it.
140  *  - If printing the whole bitmap as list by parts, user must ensure the order
141  *    of calls of the function such that the offset is incremented linearly.
142  *  - If printing the whole bitmap as list by parts, user must keep bitmap
143  *    unchanged between the very first and very last call. Otherwise concatenated
144  *    result may be incorrect, and format may be broken.
145  *
146  * Returns the number of characters actually printed to @buf
147  */
148 int bitmap_print_bitmask_to_buf(char *buf, const unsigned long *maskp,
149 				int nmaskbits, loff_t off, size_t count)
150 {
151 	return bitmap_print_to_buf(false, buf, maskp, nmaskbits, off, count);
152 }
153 EXPORT_SYMBOL(bitmap_print_bitmask_to_buf);
154 
155 /**
156  * bitmap_print_list_to_buf  - convert bitmap to decimal list format ASCII string
157  * @buf: buffer into which string is placed
158  * @maskp: pointer to bitmap to convert
159  * @nmaskbits: size of bitmap, in bits
160  * @off: in the string from which we are copying, We copy to @buf
161  * @count: the maximum number of bytes to print
162  *
163  * Everything is same with the above bitmap_print_bitmask_to_buf() except
164  * the print format.
165  */
166 int bitmap_print_list_to_buf(char *buf, const unsigned long *maskp,
167 			     int nmaskbits, loff_t off, size_t count)
168 {
169 	return bitmap_print_to_buf(true, buf, maskp, nmaskbits, off, count);
170 }
171 EXPORT_SYMBOL(bitmap_print_list_to_buf);
172 
173 /*
174  * Region 9-38:4/10 describes the following bitmap structure:
175  * 0	   9  12    18			38	     N
176  * .........****......****......****..................
177  *	    ^  ^     ^			 ^	     ^
178  *      start  off   group_len	       end	 nbits
179  */
180 struct region {
181 	unsigned int start;
182 	unsigned int off;
183 	unsigned int group_len;
184 	unsigned int end;
185 	unsigned int nbits;
186 };
187 
188 static void bitmap_set_region(const struct region *r, unsigned long *bitmap)
189 {
190 	unsigned int start = r->start;
191 
192 	do {
193 		bitmap_set(bitmap, start, min(r->end - start + 1, r->off));
194 	} while (!check_add_overflow(start, r->group_len, &start) &&
195 		 start <= r->end);
196 }
197 
198 static int bitmap_check_region(const struct region *r)
199 {
200 	if (r->start > r->end || r->group_len == 0 || r->off > r->group_len)
201 		return -EINVAL;
202 
203 	if (r->end >= r->nbits)
204 		return -ERANGE;
205 
206 	return 0;
207 }
208 
209 static const char *bitmap_getnum(const char *str, unsigned int *num,
210 				 unsigned int lastbit)
211 {
212 	unsigned long long n;
213 	unsigned int len;
214 
215 	if (str[0] == 'N') {
216 		*num = lastbit;
217 		return str + 1;
218 	}
219 
220 	len = _parse_integer(str, 10, &n);
221 	if (!len)
222 		return ERR_PTR(-EINVAL);
223 	if (len & KSTRTOX_OVERFLOW || n != (unsigned int)n)
224 		return ERR_PTR(-EOVERFLOW);
225 
226 	*num = n;
227 	return str + len;
228 }
229 
230 static inline bool end_of_str(char c)
231 {
232 	return c == '\0' || c == '\n';
233 }
234 
235 static inline bool __end_of_region(char c)
236 {
237 	return isspace(c) || c == ',';
238 }
239 
240 static inline bool end_of_region(char c)
241 {
242 	return __end_of_region(c) || end_of_str(c);
243 }
244 
245 /*
246  * The format allows commas and whitespaces at the beginning
247  * of the region.
248  */
249 static const char *bitmap_find_region(const char *str)
250 {
251 	while (__end_of_region(*str))
252 		str++;
253 
254 	return end_of_str(*str) ? NULL : str;
255 }
256 
257 static const char *bitmap_find_region_reverse(const char *start, const char *end)
258 {
259 	while (start <= end && __end_of_region(*end))
260 		end--;
261 
262 	return end;
263 }
264 
265 static const char *bitmap_parse_region(const char *str, struct region *r)
266 {
267 	unsigned int lastbit = r->nbits - 1;
268 
269 	if (!strncasecmp(str, "all", 3)) {
270 		r->start = 0;
271 		r->end = lastbit;
272 		str += 3;
273 
274 		goto check_pattern;
275 	}
276 
277 	str = bitmap_getnum(str, &r->start, lastbit);
278 	if (IS_ERR(str))
279 		return str;
280 
281 	if (end_of_region(*str))
282 		goto no_end;
283 
284 	if (*str != '-')
285 		return ERR_PTR(-EINVAL);
286 
287 	str = bitmap_getnum(str + 1, &r->end, lastbit);
288 	if (IS_ERR(str))
289 		return str;
290 
291 check_pattern:
292 	if (end_of_region(*str))
293 		goto no_pattern;
294 
295 	if (*str != ':')
296 		return ERR_PTR(-EINVAL);
297 
298 	str = bitmap_getnum(str + 1, &r->off, lastbit);
299 	if (IS_ERR(str))
300 		return str;
301 
302 	if (*str != '/')
303 		return ERR_PTR(-EINVAL);
304 
305 	str = bitmap_getnum(str + 1, &r->group_len, lastbit);
306 	if (IS_ERR(str))
307 		return str;
308 
309 	if (!end_of_region(*str))
310 		return ERR_PTR(-EINVAL);
311 
312 	return end_of_str(*str) ? NULL : str;
313 
314 no_end:
315 	r->end = r->start;
316 no_pattern:
317 	r->off = r->end + 1;
318 	r->group_len = r->end + 1;
319 
320 	return end_of_str(*str) ? NULL : str;
321 }
322 
323 /**
324  * bitmap_parselist - convert list format ASCII string to bitmap
325  * @buf: read user string from this buffer; must be terminated
326  *    with a \0 or \n.
327  * @maskp: write resulting mask here
328  * @nmaskbits: number of bits in mask to be written
329  *
330  * Input format is a comma-separated list of decimal numbers and
331  * ranges.  Consecutively set bits are shown as two hyphen-separated
332  * decimal numbers, the smallest and largest bit numbers set in
333  * the range.
334  * Optionally each range can be postfixed to denote that only parts of it
335  * should be set. The range will divided to groups of specific size.
336  * From each group will be used only defined amount of bits.
337  * Syntax: range:used_size/group_size
338  * Example: 0-1023:2/256 ==> 0,1,256,257,512,513,768,769
339  * The value 'N' can be used as a dynamically substituted token for the
340  * maximum allowed value; i.e (nmaskbits - 1).  Keep in mind that it is
341  * dynamic, so if system changes cause the bitmap width to change, such
342  * as more cores in a CPU list, then any ranges using N will also change.
343  *
344  * Returns: 0 on success, -errno on invalid input strings. Error values:
345  *
346  *   - ``-EINVAL``: wrong region format
347  *   - ``-EINVAL``: invalid character in string
348  *   - ``-ERANGE``: bit number specified too large for mask
349  *   - ``-EOVERFLOW``: integer overflow in the input parameters
350  */
351 int bitmap_parselist(const char *buf, unsigned long *maskp, int nmaskbits)
352 {
353 	struct region r;
354 	long ret;
355 
356 	r.nbits = nmaskbits;
357 	bitmap_zero(maskp, r.nbits);
358 
359 	while (buf) {
360 		buf = bitmap_find_region(buf);
361 		if (buf == NULL)
362 			return 0;
363 
364 		buf = bitmap_parse_region(buf, &r);
365 		if (IS_ERR(buf))
366 			return PTR_ERR(buf);
367 
368 		ret = bitmap_check_region(&r);
369 		if (ret)
370 			return ret;
371 
372 		bitmap_set_region(&r, maskp);
373 	}
374 
375 	return 0;
376 }
377 EXPORT_SYMBOL(bitmap_parselist);
378 
379 
380 /**
381  * bitmap_parselist_user() - convert user buffer's list format ASCII
382  * string to bitmap
383  *
384  * @ubuf: pointer to user buffer containing string.
385  * @ulen: buffer size in bytes.  If string is smaller than this
386  *    then it must be terminated with a \0.
387  * @maskp: pointer to bitmap array that will contain result.
388  * @nmaskbits: size of bitmap, in bits.
389  *
390  * Wrapper for bitmap_parselist(), providing it with user buffer.
391  */
392 int bitmap_parselist_user(const char __user *ubuf,
393 			unsigned int ulen, unsigned long *maskp,
394 			int nmaskbits)
395 {
396 	char *buf;
397 	int ret;
398 
399 	buf = memdup_user_nul(ubuf, ulen);
400 	if (IS_ERR(buf))
401 		return PTR_ERR(buf);
402 
403 	ret = bitmap_parselist(buf, maskp, nmaskbits);
404 
405 	kfree(buf);
406 	return ret;
407 }
408 EXPORT_SYMBOL(bitmap_parselist_user);
409 
410 static const char *bitmap_get_x32_reverse(const char *start,
411 					const char *end, u32 *num)
412 {
413 	u32 ret = 0;
414 	int c, i;
415 
416 	for (i = 0; i < 32; i += 4) {
417 		c = hex_to_bin(*end--);
418 		if (c < 0)
419 			return ERR_PTR(-EINVAL);
420 
421 		ret |= c << i;
422 
423 		if (start > end || __end_of_region(*end))
424 			goto out;
425 	}
426 
427 	/*
428 	 * Eight digits have been consumed and the next character is not a
429 	 * separator: another hex digit means the chunk does not fit in 32
430 	 * bits, anything else is an illegal character.
431 	 */
432 	return ERR_PTR(hex_to_bin(*end) >= 0 ? -EOVERFLOW : -EINVAL);
433 out:
434 	*num = ret;
435 	return end;
436 }
437 
438 /**
439  * bitmap_parse - convert an ASCII hex string into a bitmap.
440  * @start: pointer to buffer containing string.
441  * @buflen: buffer size in bytes.  If string is smaller than this
442  *    then it must be terminated with a \0 or \n. In that case,
443  *    UINT_MAX may be provided instead of string length.
444  * @maskp: pointer to bitmap array that will contain result.
445  * @nmaskbits: size of bitmap, in bits.
446  *
447  * Commas group hex digits into chunks.  Each chunk defines exactly 32
448  * bits of the resultant bitmask.  No chunk may specify a value larger
449  * than 32 bits (%-EOVERFLOW), and if a chunk specifies a smaller value
450  * then leading 0-bits are prepended.  %-EINVAL is returned for illegal
451  * characters. Grouping such as "1,,5", ",44", "," or "" is allowed.
452  * Leading, embedded and trailing whitespace accepted.
453  */
454 int bitmap_parse(const char *start, unsigned int buflen,
455 		unsigned long *maskp, int nmaskbits)
456 {
457 	const char *end = strnchrnul(start, buflen, '\n') - 1;
458 	int chunks = BITS_TO_U32(nmaskbits);
459 	u32 *bitmap = (u32 *)maskp;
460 	int unset_bit;
461 	int chunk;
462 
463 	for (chunk = 0; ; chunk++) {
464 		end = bitmap_find_region_reverse(start, end);
465 		if (start > end)
466 			break;
467 
468 		if (!chunks--)
469 			return -EOVERFLOW;
470 
471 #if defined(CONFIG_64BIT) && defined(__BIG_ENDIAN)
472 		end = bitmap_get_x32_reverse(start, end, &bitmap[chunk ^ 1]);
473 #else
474 		end = bitmap_get_x32_reverse(start, end, &bitmap[chunk]);
475 #endif
476 		if (IS_ERR(end))
477 			return PTR_ERR(end);
478 	}
479 
480 	unset_bit = (BITS_TO_U32(nmaskbits) - chunks) * 32;
481 	if (unset_bit < nmaskbits) {
482 		bitmap_clear(maskp, unset_bit, nmaskbits - unset_bit);
483 		return 0;
484 	}
485 
486 	if (find_next_bit(maskp, unset_bit, nmaskbits) != unset_bit)
487 		return -EOVERFLOW;
488 
489 	return 0;
490 }
491 EXPORT_SYMBOL(bitmap_parse);
492