Whamcloud - gitweb
LU-14688 mdt: changelog purge deletes plain llog
[fs/lustre-release.git] / libcfs / libcfs / libcfs_string.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * String manipulation functions.
32  *
33  * libcfs/libcfs/libcfs_string.c
34  *
35  * Author: Nathan Rutman <nathan.rutman@sun.com>
36  */
37
38 #include <linux/ctype.h>
39 #include <libcfs/libcfs.h>
40 #include <libcfs/libcfs_string.h>
41
42 /* Convert a text string to a bitmask */
43 int cfs_str2mask(const char *str, const char *(*bit2str)(int bit),
44                  int *oldmask, int minmask, int allmask)
45 {
46         const char *debugstr;
47         char op = 0;
48         int newmask = minmask, i, len, found = 0;
49
50         ENTRY;
51         /* <str> must be a list of tokens separated by whitespace
52          * and optionally an operator ('+' or '-').  If an operator
53          * appears first in <str>, '*oldmask' is used as the starting point
54          * (relative), otherwise minmask is used (absolute).  An operator
55          * applies to all following tokens up to the next operator.
56          */
57         while (*str != 0) {
58                 while (isspace(*str))
59                         str++;
60                 if (*str == 0)
61                         break;
62                 if (*str == '+' || *str == '-') {
63                         op = *str++;
64                         if (!found)
65                                 /* only if first token is relative */
66                                 newmask = *oldmask;
67                         while (isspace(*str))
68                                 str++;
69                         if (*str == 0)          /* trailing op */
70                                 return -EINVAL;
71                 }
72
73                 /* find token length */
74                 for (len = 0; str[len] != 0 && !isspace(str[len]) &&
75                      str[len] != '+' && str[len] != '-'; len++);
76
77                 /* match token */
78                 found = 0;
79                 for (i = 0; i < 32; i++) {
80                         debugstr = bit2str(i);
81                         if (debugstr != NULL &&
82                             strlen(debugstr) == len &&
83                             strncasecmp(str, debugstr, len) == 0) {
84                                 if (op == '-')
85                                         newmask &= ~BIT(i);
86                                 else
87                                         newmask |= BIT(i);
88                                 found = 1;
89                                 break;
90                         }
91                 }
92                 if (!found && len == 3 &&
93                     (strncasecmp(str, "ALL", len) == 0)) {
94                         if (op == '-')
95                                 newmask = minmask;
96                         else
97                                 newmask = allmask;
98                         found = 1;
99                 }
100                 if (!found) {
101                         CWARN("unknown mask '%.*s'.\n"
102                               "mask usage: [+|-]<all|type> ...\n", len, str);
103                         return -EINVAL;
104                 }
105                 str += len;
106         }
107
108         *oldmask = newmask;
109         return 0;
110 }
111 EXPORT_SYMBOL(cfs_str2mask);
112
113 /**
114  * Extracts tokens from strings.
115  *
116  * Looks for \a delim in string \a next, sets \a res to point to
117  * substring before the delimiter, sets \a next right after the found
118  * delimiter.
119  *
120  * \retval 1 if \a res points to a string of non-whitespace characters
121  * \retval 0 otherwise
122  */
123 int
124 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
125 {
126         char *end;
127
128         if (next->ls_str == NULL)
129                 return 0;
130
131         /* skip leading white spaces */
132         while (next->ls_len) {
133                 if (!isspace(*next->ls_str))
134                         break;
135                 next->ls_str++;
136                 next->ls_len--;
137         }
138
139         if (next->ls_len == 0) /* whitespaces only */
140                 return 0;
141
142         if (*next->ls_str == delim) {
143                 /* first non-writespace is the delimiter */
144                 return 0;
145         }
146
147         res->ls_str = next->ls_str;
148         end = memchr(next->ls_str, delim, next->ls_len);
149         if (end == NULL) {
150                 /* there is no the delimeter in the string */
151                 end = next->ls_str + next->ls_len;
152                 next->ls_str = NULL;
153         } else {
154                 next->ls_str = end + 1;
155                 next->ls_len -= (end - res->ls_str + 1);
156         }
157
158         /* skip ending whitespaces */
159         while (--end != res->ls_str) {
160                 if (!isspace(*end))
161                         break;
162         }
163
164         res->ls_len = end - res->ls_str + 1;
165         return 1;
166 }
167 EXPORT_SYMBOL(cfs_gettok);
168
169 /**
170  * Converts string to integer.
171  *
172  * Accepts decimal and hexadecimal number recordings.
173  *
174  * \retval 1 if first \a nob chars of \a str convert to decimal or
175  * hexadecimal integer in the range [\a min, \a max]
176  * \retval 0 otherwise
177  */
178 int
179 cfs_str2num_check(char *str, int nob, unsigned *num,
180                   unsigned min, unsigned max)
181 {
182         bool all_numbers = true;
183         char *endp, cache;
184         int len;
185         int rc;
186
187         endp = strim(str);
188         /**
189          * kstrouint can only handle strings composed
190          * of only numbers. We need to scan the string
191          * passed in for the first non-digit character
192          * and end the string at that location. If we
193          * don't find any non-digit character we still
194          * need to place a '\0' at position len since
195          * we are not interested in the rest of the
196          * string which is longer than len in size.
197          * After we are done the character at the
198          * position we placed '\0' must be restored.
199          */
200         len = min((int)strlen(endp), nob);
201         for (; endp < str + len; endp++) {
202                 if (!isxdigit(*endp) && *endp != '-' &&
203                     *endp != '+') {
204                         all_numbers = false;
205                         break;
206                 }
207         }
208
209         /* Eat trailing space */
210         if (!all_numbers && isspace(*endp)) {
211                 all_numbers = true;
212                 endp--;
213         }
214
215         cache = *endp;
216         *endp = '\0';
217
218         rc = kstrtouint(str, 0, num);
219         *endp = cache;
220         if (rc || !all_numbers)
221                 return 0;
222
223         return (*num >= min && *num <= max);
224 }
225 EXPORT_SYMBOL(cfs_str2num_check);
226
227 /**
228  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
229  * \a src should only have a single token which can be \<number\> or  \*
230  *
231  * \retval pointer to allocated range_expr and initialized
232  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
233  `* src parses to
234  * \<number\> |
235  * \<number\> '-' \<number\> |
236  * \<number\> '-' \<number\> '/' \<number\>
237  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
238  * -ENOMEM will be returned.
239  */
240 static int
241 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
242                      int bracketed, struct cfs_range_expr **expr)
243 {
244         struct cfs_range_expr *re;
245         struct cfs_lstr tok;
246
247         LIBCFS_ALLOC(re, sizeof(*re));
248         if (re == NULL)
249                 return -ENOMEM;
250
251         if (src->ls_len == 1 && src->ls_str[0] == '*') {
252                 re->re_lo = min;
253                 re->re_hi = max;
254                 re->re_stride = 1;
255                 goto out;
256         }
257
258         if (cfs_str2num_check(src->ls_str, src->ls_len,
259                               &re->re_lo, min, max)) {
260                 /* <number> is parsed */
261                 re->re_hi = re->re_lo;
262                 re->re_stride = 1;
263                 goto out;
264         }
265
266         if (!bracketed || !cfs_gettok(src, '-', &tok))
267                 goto failed;
268
269         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
270                                &re->re_lo, min, max))
271                 goto failed;
272
273         /* <number> - */
274         if (cfs_str2num_check(src->ls_str, src->ls_len,
275                               &re->re_hi, min, max)) {
276                 /* <number> - <number> is parsed */
277                 re->re_stride = 1;
278                 goto out;
279         }
280
281         /* go to check <number> '-' <number> '/' <number> */
282         if (cfs_gettok(src, '/', &tok)) {
283                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
284                                        &re->re_hi, min, max))
285                         goto failed;
286
287                 /* <number> - <number> / ... */
288                 if (cfs_str2num_check(src->ls_str, src->ls_len,
289                                       &re->re_stride, min, max)) {
290                         /* <number> - <number> / <number> is parsed */
291                         goto out;
292                 }
293         }
294
295 out:
296         *expr = re;
297         return 0;
298
299 failed:
300         LIBCFS_FREE(re, sizeof(*re));
301         return -EINVAL;
302 }
303
304 /**
305  * Print the range expression \a re into specified \a buffer.
306  * If \a bracketed is true, expression does not need additional
307  * brackets.
308  *
309  * \retval number of characters written
310  */
311 static int
312 cfs_range_expr_print(char *buffer, int count, struct cfs_range_expr *expr,
313                      bool bracketed)
314 {
315         int i;
316         char s[] = "[";
317         char e[] = "]";
318
319         if (bracketed)
320                 s[0] = e[0] = '\0';
321
322         if (expr->re_lo == expr->re_hi)
323                 i = scnprintf(buffer, count, "%u", expr->re_lo);
324         else if (expr->re_stride == 1)
325                 i = scnprintf(buffer, count, "%s%u-%u%s",
326                               s, expr->re_lo, expr->re_hi, e);
327         else
328                 i = scnprintf(buffer, count, "%s%u-%u/%u%s",
329                               s, expr->re_lo, expr->re_hi,
330                               expr->re_stride, e);
331         return i;
332 }
333
334 /**
335  * Print a list of range expressions (\a expr_list) into specified \a buffer.
336  * If the list contains several expressions, separate them with comma
337  * and surround the list with brackets.
338  *
339  * \retval number of characters written
340  */
341 int
342 cfs_expr_list_print(char *buffer, int count, struct cfs_expr_list *expr_list)
343 {
344         struct cfs_range_expr *expr;
345         int i = 0, j = 0;
346         int numexprs = 0;
347
348         if (count <= 0)
349                 return 0;
350
351         list_for_each_entry(expr, &expr_list->el_exprs, re_link)
352                 numexprs++;
353
354         if (numexprs > 1)
355                 i += scnprintf(buffer + i, count - i, "[");
356
357         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
358                 if (j++ != 0)
359                         i += scnprintf(buffer + i, count - i, ",");
360                 i += cfs_range_expr_print(buffer + i, count - i, expr,
361                                           numexprs > 1);
362         }
363
364         if (numexprs > 1)
365                 i += scnprintf(buffer + i, count - i, "]");
366
367         return i;
368 }
369 EXPORT_SYMBOL(cfs_expr_list_print);
370
371 /**
372  * Matches value (\a value) against ranges expression list \a expr_list.
373  *
374  * \retval 1 if \a value matches
375  * \retval 0 otherwise
376  */
377 int
378 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
379 {
380         struct cfs_range_expr *expr;
381
382         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
383                 if (value >= expr->re_lo && value <= expr->re_hi &&
384                     ((value - expr->re_lo) % expr->re_stride) == 0)
385                         return 1;
386         }
387
388         return 0;
389 }
390 EXPORT_SYMBOL(cfs_expr_list_match);
391
392 /**
393  * Convert express list (\a expr_list) to an array of all matched values
394  *
395  * \retval N N is total number of all matched values
396  * \retval 0 if expression list is empty
397  * \retval < 0 for failure
398  */
399 int
400 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
401 {
402         struct cfs_range_expr *expr;
403         __u32 *val;
404         int count = 0;
405         int i;
406
407         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
408                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
409                         if (((i - expr->re_lo) % expr->re_stride) == 0)
410                                 count++;
411                 }
412         }
413
414         if (count == 0) /* empty expression list */
415                 return 0;
416
417         if (count > max) {
418                 CERROR("Number of values %d exceeds max allowed %d\n",
419                        max, count);
420                 return -EINVAL;
421         }
422
423         CFS_ALLOC_PTR_ARRAY(val, count);
424         if (val == NULL)
425                 return -ENOMEM;
426
427         count = 0;
428         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
429                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
430                         if (((i - expr->re_lo) % expr->re_stride) == 0)
431                                 val[count++] = i;
432                 }
433         }
434
435         *valpp = val;
436         return count;
437 }
438 EXPORT_SYMBOL(cfs_expr_list_values);
439
440 void
441 cfs_expr_list_values_free(__u32 *values, int num)
442 {
443         /* This array is allocated by LIBCFS_ALLOC(), so it shouldn't be freed
444          * by OBD_FREE() if it's called by module other than libcfs & LNet,
445          * otherwise we will see fake memory leak */
446         CFS_FREE_PTR_ARRAY(values, num);
447 }
448 EXPORT_SYMBOL(cfs_expr_list_values_free);
449
450 /**
451  * Frees cfs_range_expr structures of \a expr_list.
452  *
453  * \retval none
454  */
455 void
456 cfs_expr_list_free(struct cfs_expr_list *expr_list)
457 {
458         while (!list_empty(&expr_list->el_exprs)) {
459                 struct cfs_range_expr *expr;
460
461                 expr = list_entry(expr_list->el_exprs.next,
462                                       struct cfs_range_expr, re_link);
463                 list_del(&expr->re_link);
464                 LIBCFS_FREE(expr, sizeof(*expr));
465         }
466
467         LIBCFS_FREE(expr_list, sizeof(*expr_list));
468 }
469 EXPORT_SYMBOL(cfs_expr_list_free);
470
471 /**
472  * Parses \<cfs_expr_list\> token of the syntax.
473  *
474  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
475  * \retval -errno otherwise
476  */
477 int
478 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
479                     struct cfs_expr_list **elpp)
480 {
481         struct cfs_expr_list *expr_list;
482         struct cfs_range_expr *expr;
483         struct cfs_lstr src;
484         int rc;
485
486         LIBCFS_ALLOC(expr_list, sizeof(*expr_list));
487         if (expr_list == NULL)
488                 return -ENOMEM;
489
490         src.ls_str = str;
491         src.ls_len = len;
492
493         INIT_LIST_HEAD(&expr_list->el_exprs);
494
495         if (src.ls_str[0] == '[' &&
496             src.ls_str[src.ls_len - 1] == ']') {
497                 src.ls_str++;
498                 src.ls_len -= 2;
499
500                 rc = -EINVAL;
501                 while (src.ls_str != NULL) {
502                         struct cfs_lstr tok;
503
504                         if (!cfs_gettok(&src, ',', &tok)) {
505                                 rc = -EINVAL;
506                                 break;
507                         }
508
509                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
510                         if (rc != 0)
511                                 break;
512
513                         list_add_tail(&expr->re_link, &expr_list->el_exprs);
514                 }
515         } else {
516                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
517                 if (rc == 0)
518                         list_add_tail(&expr->re_link, &expr_list->el_exprs);
519         }
520
521         if (rc != 0)
522                 cfs_expr_list_free(expr_list);
523         else
524                 *elpp = expr_list;
525
526         return rc;
527 }
528 EXPORT_SYMBOL(cfs_expr_list_parse);
529
530 /**
531  * Frees cfs_expr_list structures of \a list.
532  *
533  * For each struct cfs_expr_list structure found on \a list it frees
534  * range_expr list attached to it and frees the cfs_expr_list itself.
535  *
536  * \retval none
537  */
538 void
539 cfs_expr_list_free_list(struct list_head *list)
540 {
541         struct cfs_expr_list *el;
542
543         while (!list_empty(list)) {
544                 el = list_entry(list->next,
545                                     struct cfs_expr_list, el_link);
546                 list_del(&el->el_link);
547                 cfs_expr_list_free(el);
548         }
549 }
550 EXPORT_SYMBOL(cfs_expr_list_free_list);