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