Whamcloud - gitweb
LU-9859 libcfs: move cfs_expr_list_print to nidstrings.c
[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, int defmask)
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 or comma,
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) || *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] != '-' && str[len] != ',';
76                      len++);
77
78                 /* match token */
79                 found = 0;
80                 for (i = 0; i < 32; i++) {
81                         debugstr = bit2str(i);
82                         if (debugstr != NULL &&
83                             strlen(debugstr) == len &&
84                             strncasecmp(str, debugstr, len) == 0) {
85                                 if (op == '-')
86                                         newmask &= ~BIT(i);
87                                 else
88                                         newmask |= BIT(i);
89                                 found = 1;
90                                 break;
91                         }
92                 }
93                 if (!found && len == 3 &&
94                     (strncasecmp(str, "ALL", len) == 0)) {
95                         if (op == '-')
96                                 newmask = minmask;
97                         else
98                                 newmask = allmask;
99                         found = 1;
100                 }
101                 if (!found && strcasecmp(str, "DEFAULT") == 0) {
102                         if (op == '-')
103                                 newmask = (newmask & ~defmask) | minmask;
104                         else if (op == '+')
105                                 newmask |= defmask;
106                         else
107                                 newmask = defmask;
108                         found = 1;
109                 }
110                 if (!found) {
111                         CWARN("unknown mask '%.*s'.\n"
112                               "mask usage: [+|-]<all|type> ...\n", len, str);
113                         return -EINVAL;
114                 }
115                 str += len;
116         }
117
118         *oldmask = newmask;
119         return 0;
120 }
121 EXPORT_SYMBOL(cfs_str2mask);
122
123 /**
124  * Extracts tokens from strings.
125  *
126  * Looks for \a delim in string \a next, sets \a res to point to
127  * substring before the delimiter, sets \a next right after the found
128  * delimiter.
129  *
130  * \retval 1 if \a res points to a string of non-whitespace characters
131  * \retval 0 otherwise
132  */
133 int
134 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
135 {
136         char *end;
137
138         if (next->ls_str == NULL)
139                 return 0;
140
141         /* skip leading white spaces */
142         while (next->ls_len) {
143                 if (!isspace(*next->ls_str))
144                         break;
145                 next->ls_str++;
146                 next->ls_len--;
147         }
148
149         if (next->ls_len == 0) /* whitespaces only */
150                 return 0;
151
152         if (*next->ls_str == delim) {
153                 /* first non-writespace is the delimiter */
154                 return 0;
155         }
156
157         res->ls_str = next->ls_str;
158         end = memchr(next->ls_str, delim, next->ls_len);
159         if (end == NULL) {
160                 /* there is no the delimeter in the string */
161                 end = next->ls_str + next->ls_len;
162                 next->ls_str = NULL;
163                 next->ls_len = 0;
164         } else {
165                 next->ls_str = end + 1;
166                 next->ls_len -= (end - res->ls_str + 1);
167         }
168
169         /* skip ending whitespaces */
170         while (--end != res->ls_str) {
171                 if (!isspace(*end))
172                         break;
173         }
174
175         res->ls_len = end - res->ls_str + 1;
176         return 1;
177 }
178 EXPORT_SYMBOL(cfs_gettok);
179
180 /**
181  * Converts string to integer.
182  *
183  * Accepts decimal and hexadecimal number recordings.
184  *
185  * \retval 1 if first \a nob chars of \a str convert to decimal or
186  * hexadecimal integer in the range [\a min, \a max]
187  * \retval 0 otherwise
188  */
189 int
190 cfs_str2num_check(char *str, int nob, unsigned *num,
191                   unsigned min, unsigned max)
192 {
193         bool all_numbers = true;
194         char *endp, cache;
195         int len;
196         int rc;
197
198         endp = strim(str);
199         /**
200          * kstrouint can only handle strings composed
201          * of only numbers. We need to scan the string
202          * passed in for the first non-digit character
203          * and end the string at that location. If we
204          * don't find any non-digit character we still
205          * need to place a '\0' at position len since
206          * we are not interested in the rest of the
207          * string which is longer than len in size.
208          * After we are done the character at the
209          * position we placed '\0' must be restored.
210          */
211         len = min((int)strlen(endp), nob);
212         for (; endp < str + len; endp++) {
213                 if (!isxdigit(*endp) && *endp != '-' &&
214                     *endp != '+') {
215                         all_numbers = false;
216                         break;
217                 }
218         }
219
220         /* Eat trailing space */
221         if (!all_numbers && isspace(*endp)) {
222                 all_numbers = true;
223                 endp--;
224         }
225
226         cache = *endp;
227         *endp = '\0';
228
229         rc = kstrtouint(str, 0, num);
230         *endp = cache;
231         if (rc || !all_numbers)
232                 return 0;
233
234         return (*num >= min && *num <= max);
235 }
236 EXPORT_SYMBOL(cfs_str2num_check);
237
238 /**
239  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
240  * \a src should only have a single token which can be \<number\> or  \*
241  *
242  * \retval pointer to allocated range_expr and initialized
243  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
244  `* src parses to
245  * \<number\> |
246  * \<number\> '-' \<number\> |
247  * \<number\> '-' \<number\> '/' \<number\>
248  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
249  * -ENOMEM will be returned.
250  */
251 static int
252 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
253                      int bracketed, struct cfs_range_expr **expr)
254 {
255         struct cfs_range_expr *re;
256         struct cfs_lstr tok;
257
258         LIBCFS_ALLOC(re, sizeof(*re));
259         if (re == NULL)
260                 return -ENOMEM;
261
262         if (src->ls_len == 1 && src->ls_str[0] == '*') {
263                 re->re_lo = min;
264                 re->re_hi = max;
265                 re->re_stride = 1;
266                 goto out;
267         }
268
269         if (cfs_str2num_check(src->ls_str, src->ls_len,
270                               &re->re_lo, min, max)) {
271                 /* <number> is parsed */
272                 re->re_hi = re->re_lo;
273                 re->re_stride = 1;
274                 goto out;
275         }
276
277         if (!bracketed || !cfs_gettok(src, '-', &tok))
278                 goto failed;
279
280         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
281                                &re->re_lo, min, max))
282                 goto failed;
283
284         /* <number> - */
285         if (cfs_str2num_check(src->ls_str, src->ls_len,
286                               &re->re_hi, min, max)) {
287                 /* <number> - <number> is parsed */
288                 re->re_stride = 1;
289                 goto out;
290         }
291
292         /* go to check <number> '-' <number> '/' <number> */
293         if (cfs_gettok(src, '/', &tok)) {
294                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
295                                        &re->re_hi, min, max))
296                         goto failed;
297
298                 /* <number> - <number> / ... */
299                 if (cfs_str2num_check(src->ls_str, src->ls_len,
300                                       &re->re_stride, min, max)) {
301                         /* <number> - <number> / <number> is parsed */
302                         goto out;
303                 }
304         }
305
306 out:
307         *expr = re;
308         return 0;
309
310 failed:
311         LIBCFS_FREE(re, sizeof(*re));
312         return -EINVAL;
313 }
314
315 /**
316  * Matches value (\a value) against ranges expression list \a expr_list.
317  *
318  * \retval 1 if \a value matches
319  * \retval 0 otherwise
320  */
321 int
322 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
323 {
324         struct cfs_range_expr *expr;
325
326         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
327                 if (value >= expr->re_lo && value <= expr->re_hi &&
328                     ((value - expr->re_lo) % expr->re_stride) == 0)
329                         return 1;
330         }
331
332         return 0;
333 }
334 EXPORT_SYMBOL(cfs_expr_list_match);
335
336 /**
337  * Convert express list (\a expr_list) to an array of all matched values
338  *
339  * \retval N N is total number of all matched values
340  * \retval 0 if expression list is empty
341  * \retval < 0 for failure
342  */
343 int
344 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
345 {
346         struct cfs_range_expr *expr;
347         __u32 *val;
348         int count = 0;
349         int i;
350
351         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
352                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
353                         if (((i - expr->re_lo) % expr->re_stride) == 0)
354                                 count++;
355                 }
356         }
357
358         if (count == 0) /* empty expression list */
359                 return 0;
360
361         if (count > max) {
362                 CERROR("Number of values %d exceeds max allowed %d\n",
363                        max, count);
364                 return -EINVAL;
365         }
366
367         CFS_ALLOC_PTR_ARRAY(val, count);
368         if (val == NULL)
369                 return -ENOMEM;
370
371         count = 0;
372         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
373                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
374                         if (((i - expr->re_lo) % expr->re_stride) == 0)
375                                 val[count++] = i;
376                 }
377         }
378
379         *valpp = val;
380         return count;
381 }
382 EXPORT_SYMBOL(cfs_expr_list_values);
383
384 void
385 cfs_expr_list_values_free(__u32 *values, int num)
386 {
387         /* This array is allocated by LIBCFS_ALLOC(), so it shouldn't be freed
388          * by OBD_FREE() if it's called by module other than libcfs & LNet,
389          * otherwise we will see fake memory leak */
390         CFS_FREE_PTR_ARRAY(values, num);
391 }
392 EXPORT_SYMBOL(cfs_expr_list_values_free);
393
394 /**
395  * Frees cfs_range_expr structures of \a expr_list.
396  *
397  * \retval none
398  */
399 void
400 cfs_expr_list_free(struct cfs_expr_list *expr_list)
401 {
402         while (!list_empty(&expr_list->el_exprs)) {
403                 struct cfs_range_expr *expr;
404
405                 expr = list_first_entry(&expr_list->el_exprs,
406                                         struct cfs_range_expr, re_link);
407                 list_del(&expr->re_link);
408                 LIBCFS_FREE(expr, sizeof(*expr));
409         }
410
411         LIBCFS_FREE(expr_list, sizeof(*expr_list));
412 }
413 EXPORT_SYMBOL(cfs_expr_list_free);
414
415 /**
416  * Parses \<cfs_expr_list\> token of the syntax.
417  *
418  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
419  * \retval -errno otherwise
420  */
421 int
422 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
423                     struct cfs_expr_list **elpp)
424 {
425         struct cfs_expr_list *expr_list;
426         struct cfs_range_expr *expr;
427         struct cfs_lstr src;
428         int rc;
429
430         LIBCFS_ALLOC(expr_list, sizeof(*expr_list));
431         if (expr_list == NULL)
432                 return -ENOMEM;
433
434         src.ls_str = str;
435         src.ls_len = len;
436
437         INIT_LIST_HEAD(&expr_list->el_exprs);
438
439         if (src.ls_str[0] == '[' &&
440             src.ls_str[src.ls_len - 1] == ']') {
441                 src.ls_str++;
442                 src.ls_len -= 2;
443
444                 rc = -EINVAL;
445                 while (src.ls_str != NULL) {
446                         struct cfs_lstr tok;
447
448                         if (!cfs_gettok(&src, ',', &tok)) {
449                                 rc = -EINVAL;
450                                 break;
451                         }
452
453                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
454                         if (rc != 0)
455                                 break;
456
457                         list_add_tail(&expr->re_link, &expr_list->el_exprs);
458                 }
459         } else {
460                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
461                 if (rc == 0)
462                         list_add_tail(&expr->re_link, &expr_list->el_exprs);
463         }
464
465         if (rc != 0)
466                 cfs_expr_list_free(expr_list);
467         else
468                 *elpp = expr_list;
469
470         return rc;
471 }
472 EXPORT_SYMBOL(cfs_expr_list_parse);
473
474 /**
475  * Frees cfs_expr_list structures of \a list.
476  *
477  * For each struct cfs_expr_list structure found on \a list it frees
478  * range_expr list attached to it and frees the cfs_expr_list itself.
479  *
480  * \retval none
481  */
482 void
483 cfs_expr_list_free_list(struct list_head *list)
484 {
485         struct cfs_expr_list *el;
486
487         while (!list_empty(list)) {
488                 el = list_first_entry(list,
489                                       struct cfs_expr_list, el_link);
490                 list_del(&el->el_link);
491                 cfs_expr_list_free(el);
492         }
493 }
494 EXPORT_SYMBOL(cfs_expr_list_free_list);