Whamcloud - gitweb
LU-10235 mdt: mdt_create: check EEXIST without lock
[fs/lustre-release.git] / lustre / obdclass / lprocfs_status.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) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/obdclass/lprocfs_status.c
33  *
34  * Author: Hariharan Thantry <thantry@users.sourceforge.net>
35  */
36
37 #define DEBUG_SUBSYSTEM S_CLASS
38
39 #include <obd_class.h>
40 #include <lprocfs_status.h>
41
42 #ifdef CONFIG_PROC_FS
43
44 static int lprocfs_no_percpu_stats = 0;
45 module_param(lprocfs_no_percpu_stats, int, 0644);
46 MODULE_PARM_DESC(lprocfs_no_percpu_stats, "Do not alloc percpu data for lprocfs stats");
47
48 #define MAX_STRING_SIZE 128
49
50 int lprocfs_single_release(struct inode *inode, struct file *file)
51 {
52         return single_release(inode, file);
53 }
54 EXPORT_SYMBOL(lprocfs_single_release);
55
56 int lprocfs_seq_release(struct inode *inode, struct file *file)
57 {
58         return seq_release(inode, file);
59 }
60 EXPORT_SYMBOL(lprocfs_seq_release);
61
62 struct dentry *ldebugfs_add_simple(struct dentry *root,
63                                    char *name, void *data,
64                                    const struct file_operations *fops)
65 {
66         struct dentry *entry;
67         umode_t mode = 0;
68
69         if (!root || !name || !fops)
70                 return ERR_PTR(-EINVAL);
71
72         if (fops->read)
73                 mode = 0444;
74         if (fops->write)
75                 mode |= 0200;
76         entry = debugfs_create_file(name, mode, root, data, fops);
77         if (IS_ERR_OR_NULL(entry)) {
78                 CERROR("LprocFS: No memory to create <debugfs> entry %s", name);
79                 return entry ?: ERR_PTR(-ENOMEM);
80         }
81         return entry;
82 }
83 EXPORT_SYMBOL(ldebugfs_add_simple);
84
85 struct proc_dir_entry *
86 lprocfs_add_simple(struct proc_dir_entry *root, char *name,
87                    void *data, const struct file_operations *fops)
88 {
89         struct proc_dir_entry *proc;
90         mode_t mode = 0;
91
92         if (!root || !name || !fops)
93                 return ERR_PTR(-EINVAL);
94
95         if (fops->read)
96                 mode = 0444;
97         if (fops->write)
98                 mode |= 0200;
99         proc = proc_create_data(name, mode, root, fops, data);
100         if (!proc) {
101                 CERROR("LprocFS: No memory to create /proc entry %s\n",
102                        name);
103                 return ERR_PTR(-ENOMEM);
104         }
105         return proc;
106 }
107 EXPORT_SYMBOL(lprocfs_add_simple);
108
109 struct proc_dir_entry *lprocfs_add_symlink(const char *name,
110                                            struct proc_dir_entry *parent,
111                                            const char *format, ...)
112 {
113         struct proc_dir_entry *entry;
114         char *dest;
115         va_list ap;
116
117         if (!parent || !format)
118                 return NULL;
119
120         OBD_ALLOC_WAIT(dest, MAX_STRING_SIZE + 1);
121         if (!dest)
122                 return NULL;
123
124         va_start(ap, format);
125         vsnprintf(dest, MAX_STRING_SIZE, format, ap);
126         va_end(ap);
127
128         entry = proc_symlink(name, parent, dest);
129         if (!entry)
130                 CERROR("LprocFS: Could not create symbolic link from "
131                        "%s to %s\n", name, dest);
132
133         OBD_FREE(dest, MAX_STRING_SIZE + 1);
134         return entry;
135 }
136 EXPORT_SYMBOL(lprocfs_add_symlink);
137
138 static const struct file_operations lprocfs_generic_fops = { };
139
140 int ldebugfs_add_vars(struct dentry *parent, struct lprocfs_vars *list,
141                       void *data)
142 {
143         if (IS_ERR_OR_NULL(parent) || IS_ERR_OR_NULL(list))
144                 return -EINVAL;
145
146         while (list->name) {
147                 struct dentry *entry;
148                 umode_t mode = 0;
149
150                 if (list->proc_mode != 0000) {
151                         mode = list->proc_mode;
152                 } else if (list->fops) {
153                         if (list->fops->read)
154                                 mode = 0444;
155                         if (list->fops->write)
156                                 mode |= 0200;
157                 }
158                 entry = debugfs_create_file(list->name, mode, parent,
159                                             list->data ? : data,
160                                             list->fops ? : &lprocfs_generic_fops);
161                 if (IS_ERR_OR_NULL(entry))
162                         return entry ? PTR_ERR(entry) : -ENOMEM;
163                 list++;
164         }
165         return 0;
166 }
167 EXPORT_SYMBOL_GPL(ldebugfs_add_vars);
168
169 /**
170  * Add /proc entries.
171  *
172  * \param root [in]  The parent proc entry on which new entry will be added.
173  * \param list [in]  Array of proc entries to be added.
174  * \param data [in]  The argument to be passed when entries read/write routines
175  *                   are called through /proc file.
176  *
177  * \retval 0   on success
178  *         < 0 on error
179  */
180 int
181 lprocfs_add_vars(struct proc_dir_entry *root, struct lprocfs_vars *list,
182                  void *data)
183 {
184         if (!root || !list)
185                 return -EINVAL;
186
187         while (list->name) {
188                 struct proc_dir_entry *proc;
189                 mode_t mode = 0;
190
191                 if (list->proc_mode != 0000) {
192                         mode = list->proc_mode;
193                 } else if (list->fops) {
194                         if (list->fops->read)
195                                 mode = 0444;
196                         if (list->fops->write)
197                                 mode |= 0200;
198                 }
199                 proc = proc_create_data(list->name, mode, root,
200                                         list->fops ?: &lprocfs_generic_fops,
201                                         list->data ?: data);
202                 if (!proc)
203                         return -ENOMEM;
204                 list++;
205         }
206         return 0;
207 }
208 EXPORT_SYMBOL(lprocfs_add_vars);
209
210 #ifndef HAVE_REMOVE_PROC_SUBTREE
211 /* for b=10866, global variable */
212 DECLARE_RWSEM(_lprocfs_lock);
213 EXPORT_SYMBOL(_lprocfs_lock);
214
215 static void lprocfs_remove_nolock(struct proc_dir_entry **proot)
216 {
217         struct proc_dir_entry *root = *proot;
218         struct proc_dir_entry *temp = root;
219         struct proc_dir_entry *rm_entry;
220         struct proc_dir_entry *parent;
221
222         *proot = NULL;
223         if (!root || IS_ERR(root))
224                 return;
225
226         parent = root->parent;
227         LASSERT(parent != NULL);
228
229         while (1) {
230                 while (temp->subdir)
231                         temp = temp->subdir;
232
233                 rm_entry = temp;
234                 temp = temp->parent;
235
236                 /*
237                  * Memory corruption once caused this to fail, and
238                  * without this LASSERT we would loop here forever.
239                  */
240                 LASSERTF(strlen(rm_entry->name) == rm_entry->namelen,
241                          "0x%p  %s/%s len %d\n", rm_entry, temp->name,
242                          rm_entry->name, (int)strlen(rm_entry->name));
243
244                 remove_proc_entry(rm_entry->name, temp);
245                 if (temp == parent)
246                         break;
247         }
248 }
249
250 int remove_proc_subtree(const char *name, struct proc_dir_entry *parent)
251 {
252         struct proc_dir_entry *t = NULL;
253         struct proc_dir_entry **p;
254         int len, busy = 0;
255
256         LASSERT(parent != NULL);
257         len = strlen(name);
258
259         down_write(&_lprocfs_lock);
260         /* lookup target name */
261         for (p = &parent->subdir; *p; p = &(*p)->next) {
262                 if ((*p)->namelen != len)
263                         continue;
264                 if (memcmp(name, (*p)->name, len))
265                         continue;
266                 t = *p;
267                 break;
268         }
269
270         if (t) {
271                 /* verify it's empty: do not count "num_refs" */
272                 for (p = &t->subdir; *p; p = &(*p)->next) {
273                         if ((*p)->namelen != strlen("num_refs")) {
274                                 busy = 1;
275                                 break;
276                         }
277                         if (memcmp("num_refs", (*p)->name,
278                                    strlen("num_refs"))) {
279                                 busy = 1;
280                                 break;
281                         }
282                 }
283         }
284
285         if (busy == 0)
286                 lprocfs_remove_nolock(&t);
287
288         up_write(&_lprocfs_lock);
289         return 0;
290 }
291 #endif /* !HAVE_REMOVE_PROC_SUBTREE */
292
293 #ifndef HAVE_PROC_REMOVE
294 void proc_remove(struct proc_dir_entry *de)
295 {
296 #ifndef HAVE_REMOVE_PROC_SUBTREE
297         down_write(&_lprocfs_lock); /* search vs remove race */
298         lprocfs_remove_nolock(&de);
299         up_write(&_lprocfs_lock);
300 #else
301         if (de)
302                 remove_proc_subtree(de->name, de->parent);
303 #endif
304 }
305 #endif
306
307 void lprocfs_remove(struct proc_dir_entry **rooth)
308 {
309         proc_remove(*rooth);
310         *rooth = NULL;
311 }
312 EXPORT_SYMBOL(lprocfs_remove);
313
314 void lprocfs_remove_proc_entry(const char *name, struct proc_dir_entry *parent)
315 {
316         LASSERT(parent != NULL);
317         remove_proc_entry(name, parent);
318 }
319 EXPORT_SYMBOL(lprocfs_remove_proc_entry);
320
321 struct dentry *ldebugfs_register(const char *name, struct dentry *parent,
322                                  struct lprocfs_vars *list, void *data)
323 {
324         struct dentry *entry;
325
326         entry = debugfs_create_dir(name, parent);
327         if (IS_ERR_OR_NULL(entry)) {
328                 entry = entry ?: ERR_PTR(-ENOMEM);
329                 goto out;
330         }
331
332         if (!IS_ERR_OR_NULL(list)) {
333                 int rc;
334
335                 rc = ldebugfs_add_vars(entry, list, data);
336                 if (rc) {
337                         debugfs_remove(entry);
338                         entry = ERR_PTR(rc);
339                 }
340         }
341 out:
342         return entry;
343 }
344 EXPORT_SYMBOL_GPL(ldebugfs_register);
345
346 struct proc_dir_entry *
347 lprocfs_register(const char *name, struct proc_dir_entry *parent,
348                  struct lprocfs_vars *list, void *data)
349 {
350         struct proc_dir_entry *newchild;
351
352         newchild = proc_mkdir(name, parent);
353         if (!newchild)
354                 return ERR_PTR(-ENOMEM);
355
356         if (list) {
357                 int rc = lprocfs_add_vars(newchild, list, data);
358                 if (rc) {
359                         lprocfs_remove(&newchild);
360                         return ERR_PTR(rc);
361                 }
362         }
363         return newchild;
364 }
365 EXPORT_SYMBOL(lprocfs_register);
366
367 /* Generic callbacks */
368 int lprocfs_uuid_seq_show(struct seq_file *m, void *data)
369 {
370         struct obd_device *obd = data;
371
372         LASSERT(obd != NULL);
373         seq_printf(m, "%s\n", obd->obd_uuid.uuid);
374         return 0;
375 }
376 EXPORT_SYMBOL(lprocfs_uuid_seq_show);
377
378 static ssize_t uuid_show(struct kobject *kobj, struct attribute *attr,
379                          char *buf)
380 {
381         struct obd_device *obd = container_of(kobj, struct obd_device,
382                                               obd_kset.kobj);
383
384         return sprintf(buf, "%s\n", obd->obd_uuid.uuid);
385 }
386 LUSTRE_RO_ATTR(uuid);
387
388 static ssize_t blocksize_show(struct kobject *kobj, struct attribute *attr,
389                               char *buf)
390 {
391         struct obd_device *obd = container_of(kobj, struct obd_device,
392                                               obd_kset.kobj);
393         struct obd_statfs osfs;
394         int rc;
395
396         rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
397                         ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS,
398                         OBD_STATFS_NODELAY);
399         if (!rc)
400                 return sprintf(buf, "%u\n", osfs.os_bsize);
401
402         return rc;
403 }
404 LUSTRE_RO_ATTR(blocksize);
405
406 static ssize_t kbytestotal_show(struct kobject *kobj, struct attribute *attr,
407                                 char *buf)
408 {
409         struct obd_device *obd = container_of(kobj, struct obd_device,
410                                               obd_kset.kobj);
411         struct obd_statfs osfs;
412         int rc;
413
414         rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
415                         ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS,
416                         OBD_STATFS_NODELAY);
417         if (!rc) {
418                 u32 blk_size = osfs.os_bsize >> 10;
419                 u64 result = osfs.os_blocks;
420
421                 result *= rounddown_pow_of_two(blk_size ?: 1);
422                 return sprintf(buf, "%llu\n", result);
423         }
424
425         return rc;
426 }
427 LUSTRE_RO_ATTR(kbytestotal);
428
429 static ssize_t kbytesfree_show(struct kobject *kobj, struct attribute *attr,
430                                char *buf)
431 {
432         struct obd_device *obd = container_of(kobj, struct obd_device,
433                                               obd_kset.kobj);
434         struct obd_statfs osfs;
435         int rc;
436
437         rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
438                         ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS,
439                         OBD_STATFS_NODELAY);
440         if (!rc) {
441                 u32 blk_size = osfs.os_bsize >> 10;
442                 u64 result = osfs.os_bfree;
443
444                 while (blk_size >>= 1)
445                         result <<= 1;
446
447                 return sprintf(buf, "%llu\n", result);
448         }
449
450         return rc;
451 }
452 LUSTRE_RO_ATTR(kbytesfree);
453
454 static ssize_t kbytesavail_show(struct kobject *kobj, struct attribute *attr,
455                                 char *buf)
456 {
457         struct obd_device *obd = container_of(kobj, struct obd_device,
458                                               obd_kset.kobj);
459         struct obd_statfs osfs;
460         int rc;
461
462         rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
463                         ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS,
464                         OBD_STATFS_NODELAY);
465         if (!rc) {
466                 u32 blk_size = osfs.os_bsize >> 10;
467                 u64 result = osfs.os_bavail;
468
469                 while (blk_size >>= 1)
470                         result <<= 1;
471
472                 return sprintf(buf, "%llu\n", result);
473         }
474
475         return rc;
476 }
477 LUSTRE_RO_ATTR(kbytesavail);
478
479 static ssize_t filestotal_show(struct kobject *kobj, struct attribute *attr,
480                                char *buf)
481 {
482         struct obd_device *obd = container_of(kobj, struct obd_device,
483                                               obd_kset.kobj);
484         struct obd_statfs osfs;
485         int rc;
486
487         rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
488                         ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS,
489                         OBD_STATFS_NODELAY);
490         if (!rc)
491                 return sprintf(buf, "%llu\n", osfs.os_files);
492
493         return rc;
494 }
495 LUSTRE_RO_ATTR(filestotal);
496
497 static ssize_t filesfree_show(struct kobject *kobj, struct attribute *attr,
498                               char *buf)
499 {
500         struct obd_device *obd = container_of(kobj, struct obd_device,
501                                               obd_kset.kobj);
502         struct obd_statfs osfs;
503         int rc;
504
505         rc = obd_statfs(NULL, obd->obd_self_export, &osfs,
506                         ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS,
507                         OBD_STATFS_NODELAY);
508         if (!rc)
509                 return sprintf(buf, "%llu\n", osfs.os_ffree);
510
511         return rc;
512 }
513 LUSTRE_RO_ATTR(filesfree);
514
515 ssize_t conn_uuid_show(struct kobject *kobj, struct attribute *attr, char *buf)
516 {
517         struct obd_device *obd = container_of(kobj, struct obd_device,
518                                               obd_kset.kobj);
519         struct obd_import *imp;
520         struct ptlrpc_connection *conn;
521         ssize_t count;
522
523         with_imp_locked(obd, imp, count) {
524                 conn = imp->imp_connection;
525                 if (conn)
526                         count = sprintf(buf, "%s\n", conn->c_remote_uuid.uuid);
527                 else
528                         count = sprintf(buf, "%s\n", "<none>");
529         }
530
531         return count;
532 }
533 EXPORT_SYMBOL(conn_uuid_show);
534
535 int lprocfs_server_uuid_seq_show(struct seq_file *m, void *data)
536 {
537         struct obd_device *obd = data;
538         struct obd_import *imp;
539         char *imp_state_name = NULL;
540         int rc = 0;
541
542         LASSERT(obd != NULL);
543         with_imp_locked(obd, imp, rc) {
544                 imp_state_name = ptlrpc_import_state_name(imp->imp_state);
545                 seq_printf(m, "%s\t%s%s\n", obd2cli_tgt(obd), imp_state_name,
546                            imp->imp_deactive ? "\tDEACTIVATED" : "");
547         }
548
549         return rc;
550 }
551 EXPORT_SYMBOL(lprocfs_server_uuid_seq_show);
552
553 /** add up per-cpu counters */
554
555 /**
556  * Lock statistics structure for access, possibly only on this CPU.
557  *
558  * The statistics struct may be allocated with per-CPU structures for
559  * efficient concurrent update (usually only on server-wide stats), or
560  * as a single global struct (e.g. for per-client or per-job statistics),
561  * so the required locking depends on the type of structure allocated.
562  *
563  * For per-CPU statistics, pin the thread to the current cpuid so that
564  * will only access the statistics for that CPU.  If the stats structure
565  * for the current CPU has not been allocated (or previously freed),
566  * allocate it now.  The per-CPU statistics do not need locking since
567  * the thread is pinned to the CPU during update.
568  *
569  * For global statistics, lock the stats structure to prevent concurrent update.
570  *
571  * \param[in] stats     statistics structure to lock
572  * \param[in] opc       type of operation:
573  *                      LPROCFS_GET_SMP_ID: "lock" and return current CPU index
574  *                              for incrementing statistics for that CPU
575  *                      LPROCFS_GET_NUM_CPU: "lock" and return number of used
576  *                              CPU indices to iterate over all indices
577  * \param[out] flags    CPU interrupt saved state for IRQ-safe locking
578  *
579  * \retval cpuid of current thread or number of allocated structs
580  * \retval negative on error (only for opc LPROCFS_GET_SMP_ID + per-CPU stats)
581  */
582 int lprocfs_stats_lock(struct lprocfs_stats *stats,
583                        enum lprocfs_stats_lock_ops opc,
584                        unsigned long *flags)
585 {
586         if (stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU) {
587                 if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
588                         spin_lock_irqsave(&stats->ls_lock, *flags);
589                 else
590                         spin_lock(&stats->ls_lock);
591                 return opc == LPROCFS_GET_NUM_CPU ? 1 : 0;
592         }
593
594         switch (opc) {
595         case LPROCFS_GET_SMP_ID: {
596                 unsigned int cpuid = get_cpu();
597
598                 if (unlikely(!stats->ls_percpu[cpuid])) {
599                         int rc = lprocfs_stats_alloc_one(stats, cpuid);
600
601                         if (rc < 0) {
602                                 put_cpu();
603                                 return rc;
604                         }
605                 }
606                 return cpuid;
607         }
608         case LPROCFS_GET_NUM_CPU:
609                 return stats->ls_biggest_alloc_num;
610         default:
611                 LBUG();
612         }
613 }
614
615 /**
616  * Unlock statistics structure after access.
617  *
618  * Unlock the lock acquired via lprocfs_stats_lock() for global statistics,
619  * or unpin this thread from the current cpuid for per-CPU statistics.
620  *
621  * This function must be called using the same arguments as used when calling
622  * lprocfs_stats_lock() so that the correct operation can be performed.
623  *
624  * \param[in] stats     statistics structure to unlock
625  * \param[in] opc       type of operation (current cpuid or number of structs)
626  * \param[in] flags     CPU interrupt saved state for IRQ-safe locking
627  */
628 void lprocfs_stats_unlock(struct lprocfs_stats *stats,
629                           enum lprocfs_stats_lock_ops opc,
630                           unsigned long *flags)
631 {
632         if (stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU) {
633                 if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
634                         spin_unlock_irqrestore(&stats->ls_lock, *flags);
635                 else
636                         spin_unlock(&stats->ls_lock);
637         } else if (opc == LPROCFS_GET_SMP_ID) {
638                 put_cpu();
639         }
640 }
641
642 /** add up per-cpu counters */
643 void lprocfs_stats_collect(struct lprocfs_stats *stats, int idx,
644                            struct lprocfs_counter *cnt)
645 {
646         unsigned int num_entry;
647         struct lprocfs_counter *percpu_cntr;
648         int i;
649         unsigned long flags = 0;
650
651         memset(cnt, 0, sizeof(*cnt));
652
653         if (!stats) {
654                 /* set count to 1 to avoid divide-by-zero errs in callers */
655                 cnt->lc_count = 1;
656                 return;
657         }
658
659         cnt->lc_min = LC_MIN_INIT;
660
661         num_entry = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
662
663         for (i = 0; i < num_entry; i++) {
664                 if (!stats->ls_percpu[i])
665                         continue;
666                 percpu_cntr = lprocfs_stats_counter_get(stats, i, idx);
667
668                 cnt->lc_count += percpu_cntr->lc_count;
669                 cnt->lc_sum += percpu_cntr->lc_sum;
670                 if (percpu_cntr->lc_min < cnt->lc_min)
671                         cnt->lc_min = percpu_cntr->lc_min;
672                 if (percpu_cntr->lc_max > cnt->lc_max)
673                         cnt->lc_max = percpu_cntr->lc_max;
674                 cnt->lc_sumsquare += percpu_cntr->lc_sumsquare;
675         }
676
677         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
678 }
679
680 static void obd_import_flags2str(struct obd_import *imp, struct seq_file *m)
681 {
682         bool first = true;
683
684         if (imp->imp_obd->obd_no_recov) {
685                 seq_printf(m, "no_recov");
686                 first = false;
687         }
688
689         flag2str(imp, invalid);
690         flag2str(imp, deactive);
691         flag2str(imp, replayable);
692         flag2str(imp, delayed_recovery);
693         flag2str(imp, vbr_failed);
694         flag2str(imp, pingable);
695         flag2str(imp, resend_replay);
696         flag2str(imp, no_pinger_recover);
697         flag2str(imp, connect_tried);
698 }
699
700 static const char *obd_connect_names[] = {
701         /* flags names  */
702         "read_only",
703         "lov_index",
704         "connect_from_mds",
705         "write_grant",
706         "server_lock",
707         "version",
708         "request_portal",
709         "acl",
710         "xattr",
711         "create_on_write",
712         "truncate_lock",
713         "initial_transno",
714         "inode_bit_locks",
715         "barrier",
716         "getattr_by_fid",
717         "no_oh_for_devices",
718         "remote_client",
719         "remote_client_by_force",
720         "max_byte_per_rpc",
721         "64bit_qdata",
722         "mds_capability",
723         "oss_capability",
724         "early_lock_cancel",
725         "som",
726         "adaptive_timeouts",
727         "lru_resize",
728         "mds_mds_connection",
729         "real_conn",
730         "change_qunit_size",
731         "alt_checksum_algorithm",
732         "fid_is_enabled",
733         "version_recovery",
734         "pools",
735         "grant_shrink",
736         "skip_orphan",
737         "large_ea",
738         "full20",
739         "layout_lock",
740         "64bithash",
741         "object_max_bytes",
742         "imp_recov",
743         "jobstats",
744         "umask",
745         "einprogress",
746         "grant_param",
747         "flock_owner",
748         "lvb_type",
749         "nanoseconds_times",
750         "lightweight_conn",
751         "short_io",
752         "pingless",
753         "flock_deadlock",
754         "disp_stripe",
755         "open_by_fid",
756         "lfsck",
757         "unknown",
758         "unlink_close",
759         "multi_mod_rpcs",
760         "dir_stripe",
761         "subtree",
762         "lockahead",
763         "bulk_mbits",
764         "compact_obdo",
765         "second_flags",
766         /* flags2 names */
767         "file_secctx",  /* 0x01 */
768         "lockaheadv2",  /* 0x02 */
769         "dir_migrate",  /* 0x04 */
770         "sum_statfs",   /* 0x08 */
771         "overstriping", /* 0x10 */
772         "flr",          /* 0x20 */
773         "wbc",          /* 0x40 */
774         "lock_convert",  /* 0x80 */
775         "archive_id_array",     /* 0x100 */
776         "increasing_xid",       /* 0x200 */
777         "selinux_policy",       /* 0x400 */
778         "lsom",                 /* 0x800 */
779         "pcc",                  /* 0x1000 */
780         "crush",                /* 0x2000 */
781         "async_discard",        /* 0x4000 */
782         "client_encryption",    /* 0x8000 */
783         NULL
784 };
785
786 void obd_connect_seq_flags2str(struct seq_file *m, __u64 flags, __u64 flags2,
787                                const char *sep)
788 {
789         bool first = true;
790         __u64 mask;
791         int i;
792
793         for (i = 0, mask = 1; i < 64; i++, mask <<= 1) {
794                 if (flags & mask) {
795                         seq_printf(m, "%s%s",
796                                    first ? "" : sep, obd_connect_names[i]);
797                         first = false;
798                 }
799         }
800
801         if (flags & ~(mask - 1)) {
802                 seq_printf(m, "%sunknown_%#llx",
803                            first ? "" : sep, flags & ~(mask - 1));
804                 first = false;
805         }
806
807         if (!(flags & OBD_CONNECT_FLAGS2) || flags2 == 0)
808                 return;
809
810         for (i = 64, mask = 1; obd_connect_names[i] != NULL; i++, mask <<= 1) {
811                 if (flags2 & mask) {
812                         seq_printf(m, "%s%s",
813                                    first ? "" : sep, obd_connect_names[i]);
814                         first = false;
815                 }
816         }
817
818         if (flags2 & ~(mask - 1)) {
819                 seq_printf(m, "%sunknown2_%#llx",
820                            first ? "" : sep, flags2 & ~(mask - 1));
821                 first = false;
822         }
823 }
824 EXPORT_SYMBOL(obd_connect_seq_flags2str);
825
826 int obd_connect_flags2str(char *page, int count, __u64 flags, __u64 flags2,
827                           const char *sep)
828 {
829         __u64 mask;
830         int i, ret = 0;
831
832         for (i = 0, mask = 1; i < 64; i++, mask <<= 1) {
833                 if (flags & mask)
834                         ret += snprintf(page + ret, count - ret, "%s%s",
835                                         ret ? sep : "", obd_connect_names[i]);
836         }
837
838         if (flags & ~(mask - 1))
839                 ret += snprintf(page + ret, count - ret,
840                                 "%sunknown_%#llx",
841                                 ret ? sep : "", flags & ~(mask - 1));
842
843         if (!(flags & OBD_CONNECT_FLAGS2) || flags2 == 0)
844                 return ret;
845
846         for (i = 64, mask = 1; obd_connect_names[i] != NULL; i++, mask <<= 1) {
847                 if (flags2 & mask)
848                         ret += snprintf(page + ret, count - ret, "%s%s",
849                                         ret ? sep : "", obd_connect_names[i]);
850         }
851
852         if (flags2 & ~(mask - 1))
853                 ret += snprintf(page + ret, count - ret,
854                                 "%sunknown2_%#llx",
855                                 ret ? sep : "", flags2 & ~(mask - 1));
856
857         return ret;
858 }
859 EXPORT_SYMBOL(obd_connect_flags2str);
860
861 void
862 obd_connect_data_seqprint(struct seq_file *m, struct obd_connect_data *ocd)
863 {
864         __u64 flags;
865
866         LASSERT(ocd != NULL);
867         flags = ocd->ocd_connect_flags;
868
869         seq_printf(m, "    connect_data:\n"
870                    "       flags: %#llx\n"
871                    "       instance: %u\n",
872                    ocd->ocd_connect_flags,
873                    ocd->ocd_instance);
874         if (flags & OBD_CONNECT_VERSION)
875                 seq_printf(m, "       target_version: %u.%u.%u.%u\n",
876                            OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
877                            OBD_OCD_VERSION_MINOR(ocd->ocd_version),
878                            OBD_OCD_VERSION_PATCH(ocd->ocd_version),
879                            OBD_OCD_VERSION_FIX(ocd->ocd_version));
880         if (flags & OBD_CONNECT_MDS)
881                 seq_printf(m, "       mdt_index: %d\n", ocd->ocd_group);
882         if (flags & OBD_CONNECT_GRANT)
883                 seq_printf(m, "       initial_grant: %d\n", ocd->ocd_grant);
884         if (flags & OBD_CONNECT_INDEX)
885                 seq_printf(m, "       target_index: %u\n", ocd->ocd_index);
886         if (flags & OBD_CONNECT_BRW_SIZE)
887                 seq_printf(m, "       max_brw_size: %d\n", ocd->ocd_brw_size);
888         if (flags & OBD_CONNECT_IBITS)
889                 seq_printf(m, "       ibits_known: %#llx\n",
890                            ocd->ocd_ibits_known);
891         if (flags & OBD_CONNECT_GRANT_PARAM)
892                 seq_printf(m, "       grant_block_size: %d\n"
893                            "       grant_inode_size: %d\n"
894                            "       grant_max_extent_size: %d\n"
895                            "       grant_extent_tax: %d\n",
896                            1 << ocd->ocd_grant_blkbits,
897                            1 << ocd->ocd_grant_inobits,
898                            ocd->ocd_grant_max_blks << ocd->ocd_grant_blkbits,
899                            ocd->ocd_grant_tax_kb << 10);
900         if (flags & OBD_CONNECT_TRANSNO)
901                 seq_printf(m, "       first_transno: %#llx\n",
902                            ocd->ocd_transno);
903         if (flags & OBD_CONNECT_CKSUM)
904                 seq_printf(m, "       cksum_types: %#x\n",
905                            ocd->ocd_cksum_types);
906         if (flags & OBD_CONNECT_MAX_EASIZE)
907                 seq_printf(m, "       max_easize: %d\n", ocd->ocd_max_easize);
908         if (flags & OBD_CONNECT_MAXBYTES)
909                 seq_printf(m, "       max_object_bytes: %llu\n",
910                            ocd->ocd_maxbytes);
911         if (flags & OBD_CONNECT_MULTIMODRPCS)
912                 seq_printf(m, "       max_mod_rpcs: %hu\n",
913                            ocd->ocd_maxmodrpcs);
914 }
915
916 static void lprocfs_import_seq_show_locked(struct seq_file *m,
917                                            struct obd_device *obd,
918                                            struct obd_import *imp)
919 {
920         char nidstr[LNET_NIDSTR_SIZE];
921         struct lprocfs_counter ret;
922         struct lprocfs_counter_header *header;
923         struct obd_import_conn *conn;
924         struct obd_connect_data *ocd;
925         int j;
926         int k;
927         int rw = 0;
928
929         ocd = &imp->imp_connect_data;
930
931         seq_printf(m, "import:\n"
932                    "    name: %s\n"
933                    "    target: %s\n"
934                    "    state: %s\n"
935                    "    connect_flags: [ ",
936                    obd->obd_name,
937                    obd2cli_tgt(obd),
938                    ptlrpc_import_state_name(imp->imp_state));
939         obd_connect_seq_flags2str(m, imp->imp_connect_data.ocd_connect_flags,
940                                   imp->imp_connect_data.ocd_connect_flags2,
941                                   ", ");
942         seq_printf(m, " ]\n");
943         obd_connect_data_seqprint(m, ocd);
944         seq_printf(m, "    import_flags: [ ");
945         obd_import_flags2str(imp, m);
946
947         seq_printf(m, " ]\n"
948                    "    connection:\n"
949                    "       failover_nids: [ ");
950         spin_lock(&imp->imp_lock);
951         j = 0;
952         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
953                 libcfs_nid2str_r(conn->oic_conn->c_peer.nid,
954                                  nidstr, sizeof(nidstr));
955                 seq_printf(m, "%s%s", j ? ", " : "", nidstr);
956                 j++;
957         }
958         if (imp->imp_connection)
959                 libcfs_nid2str_r(imp->imp_connection->c_peer.nid,
960                                  nidstr, sizeof(nidstr));
961         else
962                 strncpy(nidstr, "<none>", sizeof(nidstr));
963         seq_printf(m, " ]\n"
964                    "       current_connection: %s\n"
965                    "       connection_attempts: %u\n"
966                    "       generation: %u\n"
967                    "       in-progress_invalidations: %u\n"
968                    "       idle: %lld sec\n",
969                    nidstr,
970                    imp->imp_conn_cnt,
971                    imp->imp_generation,
972                    atomic_read(&imp->imp_inval_count),
973                    ktime_get_real_seconds() - imp->imp_last_reply_time);
974         spin_unlock(&imp->imp_lock);
975
976         if (!obd->obd_svc_stats)
977                 return;
978
979         header = &obd->obd_svc_stats->ls_cnt_header[PTLRPC_REQWAIT_CNTR];
980         lprocfs_stats_collect(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR, &ret);
981         if (ret.lc_count != 0)
982                 ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
983         else
984                 ret.lc_sum = 0;
985         seq_printf(m, "    rpcs:\n"
986                    "       inflight: %u\n"
987                    "       unregistering: %u\n"
988                    "       timeouts: %u\n"
989                    "       avg_waittime: %llu %s\n",
990                    atomic_read(&imp->imp_inflight),
991                    atomic_read(&imp->imp_unregistering),
992                    atomic_read(&imp->imp_timeouts),
993                    ret.lc_sum, header->lc_units);
994
995         k = 0;
996         for(j = 0; j < IMP_AT_MAX_PORTALS; j++) {
997                 if (imp->imp_at.iat_portal[j] == 0)
998                         break;
999                 k = max_t(unsigned int, k,
1000                           at_get(&imp->imp_at.iat_service_estimate[j]));
1001         }
1002         seq_printf(m, "    service_estimates:\n"
1003                    "       services: %u sec\n"
1004                    "       network: %u sec\n",
1005                    k,
1006                    at_get(&imp->imp_at.iat_net_latency));
1007
1008         seq_printf(m, "    transactions:\n"
1009                    "       last_replay: %llu\n"
1010                    "       peer_committed: %llu\n"
1011                    "       last_checked: %llu\n",
1012                    imp->imp_last_replay_transno,
1013                    imp->imp_peer_committed_transno,
1014                    imp->imp_last_transno_checked);
1015
1016         /* avg data rates */
1017         for (rw = 0; rw <= 1; rw++) {
1018                 lprocfs_stats_collect(obd->obd_svc_stats,
1019                                       PTLRPC_LAST_CNTR + BRW_READ_BYTES + rw,
1020                                       &ret);
1021                 if (ret.lc_sum > 0 && ret.lc_count > 0) {
1022                         ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
1023                         seq_printf(m, "    %s_data_averages:\n"
1024                                    "       bytes_per_rpc: %llu\n",
1025                                    rw ? "write" : "read",
1026                                    ret.lc_sum);
1027                 }
1028                 k = (int)ret.lc_sum;
1029                 j = opcode_offset(OST_READ + rw) + EXTRA_MAX_OPCODES;
1030                 header = &obd->obd_svc_stats->ls_cnt_header[j];
1031                 lprocfs_stats_collect(obd->obd_svc_stats, j, &ret);
1032                 if (ret.lc_sum > 0 && ret.lc_count != 0) {
1033                         ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
1034                         seq_printf(m, "       %s_per_rpc: %llu\n",
1035                                    header->lc_units, ret.lc_sum);
1036                         j = (int)ret.lc_sum;
1037                         if (j > 0)
1038                                 seq_printf(m, "       MB_per_sec: %u.%.02u\n",
1039                                            k / j, (100 * k / j) % 100);
1040                 }
1041         }
1042 }
1043
1044 int lprocfs_import_seq_show(struct seq_file *m, void *data)
1045 {
1046         struct obd_device *obd = (struct obd_device *)data;
1047         struct obd_import *imp;
1048         int rv;
1049
1050         LASSERT(obd != NULL);
1051         with_imp_locked(obd, imp, rv)
1052                 lprocfs_import_seq_show_locked(m, obd, imp);
1053         return rv;
1054 }
1055 EXPORT_SYMBOL(lprocfs_import_seq_show);
1056
1057 int lprocfs_state_seq_show(struct seq_file *m, void *data)
1058 {
1059         struct obd_device *obd = (struct obd_device *)data;
1060         struct obd_import *imp;
1061         int j, k;
1062         int rc;
1063
1064         LASSERT(obd != NULL);
1065         with_imp_locked(obd, imp, rc) {
1066                 seq_printf(m, "current_state: %s\n",
1067                            ptlrpc_import_state_name(imp->imp_state));
1068                 seq_printf(m, "state_history:\n");
1069                 k = imp->imp_state_hist_idx;
1070                 for (j = 0; j < IMP_STATE_HIST_LEN; j++) {
1071                         struct import_state_hist *ish =
1072                                 &imp->imp_state_hist[(k + j) % IMP_STATE_HIST_LEN];
1073                         if (ish->ish_state == 0)
1074                                 continue;
1075                         seq_printf(m, " - [ %lld, %s ]\n", (s64)ish->ish_time,
1076                                    ptlrpc_import_state_name(ish->ish_state));
1077                 }
1078         }
1079
1080         return rc;
1081 }
1082 EXPORT_SYMBOL(lprocfs_state_seq_show);
1083
1084 int lprocfs_at_hist_helper(struct seq_file *m, struct adaptive_timeout *at)
1085 {
1086         int i;
1087         for (i = 0; i < AT_BINS; i++)
1088                 seq_printf(m, "%3u ", at->at_hist[i]);
1089         seq_printf(m, "\n");
1090         return 0;
1091 }
1092 EXPORT_SYMBOL(lprocfs_at_hist_helper);
1093
1094 /* See also ptlrpc_lprocfs_timeouts_show_seq */
1095 static void lprocfs_timeouts_seq_show_locked(struct seq_file *m,
1096                                              struct obd_device *obd,
1097                                              struct obd_import *imp)
1098 {
1099         unsigned int cur, worst;
1100         time64_t now, worstt;
1101         int i;
1102
1103         LASSERT(obd != NULL);
1104
1105         now = ktime_get_real_seconds();
1106
1107         /* Some network health info for kicks */
1108         seq_printf(m, "%-10s : %lld, %llds ago\n",
1109                    "last reply", (s64)imp->imp_last_reply_time,
1110                    (s64)(now - imp->imp_last_reply_time));
1111
1112         cur = at_get(&imp->imp_at.iat_net_latency);
1113         worst = imp->imp_at.iat_net_latency.at_worst_ever;
1114         worstt = imp->imp_at.iat_net_latency.at_worst_time;
1115         seq_printf(m, "%-10s : cur %3u  worst %3u (at %lld, %llds ago) ",
1116                    "network", cur, worst, (s64)worstt, (s64)(now - worstt));
1117         lprocfs_at_hist_helper(m, &imp->imp_at.iat_net_latency);
1118
1119         for(i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1120                 if (imp->imp_at.iat_portal[i] == 0)
1121                         break;
1122                 cur = at_get(&imp->imp_at.iat_service_estimate[i]);
1123                 worst = imp->imp_at.iat_service_estimate[i].at_worst_ever;
1124                 worstt = imp->imp_at.iat_service_estimate[i].at_worst_time;
1125                 seq_printf(m, "portal %-2d  : cur %3u  worst %3u (at %lld, %llds ago) ",
1126                            imp->imp_at.iat_portal[i], cur, worst, (s64)worstt,
1127                            (s64)(now - worstt));
1128                 lprocfs_at_hist_helper(m, &imp->imp_at.iat_service_estimate[i]);
1129         }
1130 }
1131
1132 int lprocfs_timeouts_seq_show(struct seq_file *m, void *data)
1133 {
1134         struct obd_device *obd = (struct obd_device *)data;
1135         struct obd_import *imp;
1136         int rc;
1137
1138         with_imp_locked(obd, imp, rc)
1139                 lprocfs_timeouts_seq_show_locked(m, obd, imp);
1140         return rc;
1141 }
1142 EXPORT_SYMBOL(lprocfs_timeouts_seq_show);
1143
1144 int lprocfs_connect_flags_seq_show(struct seq_file *m, void *data)
1145 {
1146         struct obd_device *obd = data;
1147         __u64 flags;
1148         __u64 flags2;
1149         struct obd_import *imp;
1150         int rc;
1151
1152         with_imp_locked(obd, imp, rc) {
1153                 flags = imp->imp_connect_data.ocd_connect_flags;
1154                 flags2 = imp->imp_connect_data.ocd_connect_flags2;
1155                 seq_printf(m, "flags=%#llx\n", flags);
1156                 seq_printf(m, "flags2=%#llx\n", flags2);
1157                 obd_connect_seq_flags2str(m, flags, flags2, "\n");
1158                 seq_printf(m, "\n");
1159         }
1160
1161         return rc;
1162 }
1163 EXPORT_SYMBOL(lprocfs_connect_flags_seq_show);
1164
1165 static const struct attribute *obd_def_uuid_attrs[] = {
1166         &lustre_attr_uuid.attr,
1167         NULL,
1168 };
1169
1170 static const struct attribute *obd_def_attrs[] = {
1171         &lustre_attr_blocksize.attr,
1172         &lustre_attr_kbytestotal.attr,
1173         &lustre_attr_kbytesfree.attr,
1174         &lustre_attr_kbytesavail.attr,
1175         &lustre_attr_filestotal.attr,
1176         &lustre_attr_filesfree.attr,
1177         &lustre_attr_uuid.attr,
1178         NULL,
1179 };
1180
1181 static void obd_sysfs_release(struct kobject *kobj)
1182 {
1183         struct obd_device *obd = container_of(kobj, struct obd_device,
1184                                               obd_kset.kobj);
1185
1186         complete(&obd->obd_kobj_unregister);
1187 }
1188
1189 int lprocfs_obd_setup(struct obd_device *obd, bool uuid_only)
1190 {
1191         struct lprocfs_vars *debugfs_vars = NULL;
1192         int rc;
1193
1194         if (!obd || obd->obd_magic != OBD_DEVICE_MAGIC)
1195                 return -ENODEV;
1196
1197         rc = kobject_set_name(&obd->obd_kset.kobj, "%s", obd->obd_name);
1198         if (rc)
1199                 return rc;
1200
1201         obd->obd_ktype.sysfs_ops = &lustre_sysfs_ops;
1202         obd->obd_ktype.release = obd_sysfs_release;
1203
1204         obd->obd_kset.kobj.parent = &obd->obd_type->typ_kobj;
1205         obd->obd_kset.kobj.ktype = &obd->obd_ktype;
1206         init_completion(&obd->obd_kobj_unregister);
1207         rc = kset_register(&obd->obd_kset);
1208         if (rc)
1209                 return rc;
1210
1211         if (uuid_only)
1212                 obd->obd_attrs = obd_def_uuid_attrs;
1213         else
1214                 obd->obd_attrs = obd_def_attrs;
1215
1216         rc = sysfs_create_files(&obd->obd_kset.kobj, obd->obd_attrs);
1217         if (rc) {
1218                 kset_unregister(&obd->obd_kset);
1219                 return rc;
1220         }
1221
1222         if (!obd->obd_type->typ_procroot)
1223                 debugfs_vars = obd->obd_vars;
1224         obd->obd_debugfs_entry = ldebugfs_register(obd->obd_name,
1225                                                    obd->obd_type->typ_debugfs_entry,
1226                                                    debugfs_vars, obd);
1227         if (IS_ERR_OR_NULL(obd->obd_debugfs_entry)) {
1228                 rc = obd->obd_debugfs_entry ? PTR_ERR(obd->obd_debugfs_entry)
1229                                             : -ENOMEM;
1230                 CERROR("error %d setting up debugfs for %s\n",
1231                        rc, obd->obd_name);
1232                 obd->obd_debugfs_entry = NULL;
1233
1234                 sysfs_remove_files(&obd->obd_kset.kobj, obd->obd_attrs);
1235                 obd->obd_attrs = NULL;
1236                 kset_unregister(&obd->obd_kset);
1237                 return rc;
1238         }
1239
1240         if (obd->obd_proc_entry || !obd->obd_type->typ_procroot)
1241                 GOTO(already_registered, rc);
1242
1243         obd->obd_proc_entry = lprocfs_register(obd->obd_name,
1244                                                obd->obd_type->typ_procroot,
1245                                                obd->obd_vars, obd);
1246         if (IS_ERR(obd->obd_proc_entry)) {
1247                 rc = PTR_ERR(obd->obd_proc_entry);
1248                 CERROR("error %d setting up lprocfs for %s\n",rc,obd->obd_name);
1249                 obd->obd_proc_entry = NULL;
1250
1251                 debugfs_remove_recursive(obd->obd_debugfs_entry);
1252                 obd->obd_debugfs_entry = NULL;
1253
1254                 sysfs_remove_files(&obd->obd_kset.kobj, obd->obd_attrs);
1255                 obd->obd_attrs = NULL;
1256                 kset_unregister(&obd->obd_kset);
1257                 return rc;
1258         }
1259 already_registered:
1260         return rc;
1261 }
1262 EXPORT_SYMBOL(lprocfs_obd_setup);
1263
1264 int lprocfs_obd_cleanup(struct obd_device *obd)
1265 {
1266         if (!obd)
1267                 return -EINVAL;
1268
1269         if (obd->obd_proc_exports_entry) {
1270                 /* Should be no exports left */
1271                 lprocfs_remove(&obd->obd_proc_exports_entry);
1272                 obd->obd_proc_exports_entry = NULL;
1273         }
1274
1275         if (obd->obd_proc_entry) {
1276                 lprocfs_remove(&obd->obd_proc_entry);
1277                 obd->obd_proc_entry = NULL;
1278         }
1279
1280         debugfs_remove_recursive(obd->obd_debugfs_entry);
1281         obd->obd_debugfs_entry = NULL;
1282
1283         /* obd device never allocated a kset */
1284         if (!obd->obd_kset.kobj.state_initialized)
1285                 return 0;
1286
1287         if (obd->obd_attrs) {
1288                 sysfs_remove_files(&obd->obd_kset.kobj, obd->obd_attrs);
1289                 obd->obd_attrs = NULL;
1290         }
1291
1292         kset_unregister(&obd->obd_kset);
1293         wait_for_completion(&obd->obd_kobj_unregister);
1294         return 0;
1295 }
1296 EXPORT_SYMBOL(lprocfs_obd_cleanup);
1297
1298 int lprocfs_stats_alloc_one(struct lprocfs_stats *stats, unsigned int cpuid)
1299 {
1300         struct lprocfs_counter *cntr;
1301         unsigned int percpusize;
1302         int rc = -ENOMEM;
1303         unsigned long flags = 0;
1304         int i;
1305
1306         LASSERT(stats->ls_percpu[cpuid] == NULL);
1307         LASSERT((stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU) == 0);
1308
1309         percpusize = lprocfs_stats_counter_size(stats);
1310         LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[cpuid], percpusize);
1311         if (stats->ls_percpu[cpuid]) {
1312                 rc = 0;
1313                 if (unlikely(stats->ls_biggest_alloc_num <= cpuid)) {
1314                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1315                                 spin_lock_irqsave(&stats->ls_lock, flags);
1316                         else
1317                                 spin_lock(&stats->ls_lock);
1318                         if (stats->ls_biggest_alloc_num <= cpuid)
1319                                 stats->ls_biggest_alloc_num = cpuid + 1;
1320                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) {
1321                                 spin_unlock_irqrestore(&stats->ls_lock, flags);
1322                         } else {
1323                                 spin_unlock(&stats->ls_lock);
1324                         }
1325                 }
1326                 /* initialize the ls_percpu[cpuid] non-zero counter */
1327                 for (i = 0; i < stats->ls_num; ++i) {
1328                         cntr = lprocfs_stats_counter_get(stats, cpuid, i);
1329                         cntr->lc_min = LC_MIN_INIT;
1330                 }
1331         }
1332         return rc;
1333 }
1334
1335 struct lprocfs_stats *lprocfs_alloc_stats(unsigned int num,
1336                                           enum lprocfs_stats_flags flags)
1337 {
1338         struct lprocfs_stats *stats;
1339         unsigned int num_entry;
1340         unsigned int percpusize = 0;
1341         int i;
1342
1343         if (num == 0)
1344                 return NULL;
1345
1346         if (lprocfs_no_percpu_stats != 0)
1347                 flags |= LPROCFS_STATS_FLAG_NOPERCPU;
1348
1349         if (flags & LPROCFS_STATS_FLAG_NOPERCPU)
1350                 num_entry = 1;
1351         else
1352                 num_entry = num_possible_cpus();
1353
1354         /* alloc percpu pointers for all possible cpu slots */
1355         LIBCFS_ALLOC(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1356         if (!stats)
1357                 return NULL;
1358
1359         stats->ls_num = num;
1360         stats->ls_flags = flags;
1361         spin_lock_init(&stats->ls_lock);
1362
1363         /* alloc num of counter headers */
1364         LIBCFS_ALLOC(stats->ls_cnt_header,
1365                      stats->ls_num * sizeof(struct lprocfs_counter_header));
1366         if (!stats->ls_cnt_header)
1367                 goto fail;
1368
1369         if ((flags & LPROCFS_STATS_FLAG_NOPERCPU) != 0) {
1370                 /* contains only one set counters */
1371                 percpusize = lprocfs_stats_counter_size(stats);
1372                 LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[0], percpusize);
1373                 if (!stats->ls_percpu[0])
1374                         goto fail;
1375                 stats->ls_biggest_alloc_num = 1;
1376         } else if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0) {
1377                 /* alloc all percpu data, currently only obd_memory use this */
1378                 for (i = 0; i < num_entry; ++i)
1379                         if (lprocfs_stats_alloc_one(stats, i) < 0)
1380                                 goto fail;
1381         }
1382
1383         return stats;
1384
1385 fail:
1386         lprocfs_free_stats(&stats);
1387         return NULL;
1388 }
1389 EXPORT_SYMBOL(lprocfs_alloc_stats);
1390
1391 void lprocfs_free_stats(struct lprocfs_stats **statsh)
1392 {
1393         struct lprocfs_stats *stats = *statsh;
1394         unsigned int num_entry;
1395         unsigned int percpusize;
1396         unsigned int i;
1397
1398         if (!stats || stats->ls_num == 0)
1399                 return;
1400         *statsh = NULL;
1401
1402         if (stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU)
1403                 num_entry = 1;
1404         else
1405                 num_entry = num_possible_cpus();
1406
1407         percpusize = lprocfs_stats_counter_size(stats);
1408         for (i = 0; i < num_entry; i++)
1409                 if (stats->ls_percpu[i])
1410                         LIBCFS_FREE(stats->ls_percpu[i], percpusize);
1411         if (stats->ls_cnt_header)
1412                 LIBCFS_FREE(stats->ls_cnt_header, stats->ls_num *
1413                                         sizeof(struct lprocfs_counter_header));
1414         LIBCFS_FREE(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1415 }
1416 EXPORT_SYMBOL(lprocfs_free_stats);
1417
1418 u64 lprocfs_stats_collector(struct lprocfs_stats *stats, int idx,
1419                             enum lprocfs_fields_flags field)
1420 {
1421         unsigned long flags = 0;
1422         unsigned int num_cpu;
1423         unsigned int i;
1424         u64 ret = 0;
1425
1426         LASSERT(stats);
1427
1428         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1429         for (i = 0; i < num_cpu; i++) {
1430                 struct lprocfs_counter *cntr;
1431
1432                 if (!stats->ls_percpu[i])
1433                         continue;
1434
1435                 cntr = lprocfs_stats_counter_get(stats, i, idx);
1436                 ret += lprocfs_read_helper(cntr, &stats->ls_cnt_header[idx],
1437                                            stats->ls_flags, field);
1438         }
1439         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1440         return ret;
1441 }
1442 EXPORT_SYMBOL(lprocfs_stats_collector);
1443
1444 void lprocfs_clear_stats(struct lprocfs_stats *stats)
1445 {
1446         struct lprocfs_counter *percpu_cntr;
1447         int i;
1448         int j;
1449         unsigned int num_entry;
1450         unsigned long flags = 0;
1451
1452         num_entry = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1453
1454         for (i = 0; i < num_entry; i++) {
1455                 if (!stats->ls_percpu[i])
1456                         continue;
1457                 for (j = 0; j < stats->ls_num; j++) {
1458                         percpu_cntr = lprocfs_stats_counter_get(stats, i, j);
1459                         percpu_cntr->lc_count           = 0;
1460                         percpu_cntr->lc_min             = LC_MIN_INIT;
1461                         percpu_cntr->lc_max             = 0;
1462                         percpu_cntr->lc_sumsquare       = 0;
1463                         percpu_cntr->lc_sum             = 0;
1464                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1465                                 percpu_cntr->lc_sum_irq = 0;
1466                 }
1467         }
1468
1469         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1470 }
1471 EXPORT_SYMBOL(lprocfs_clear_stats);
1472
1473 static ssize_t lprocfs_stats_seq_write(struct file *file,
1474                                        const char __user *buf,
1475                                        size_t len, loff_t *off)
1476 {
1477         struct seq_file *seq = file->private_data;
1478         struct lprocfs_stats *stats = seq->private;
1479
1480         lprocfs_clear_stats(stats);
1481
1482         return len;
1483 }
1484
1485 static void *lprocfs_stats_seq_start(struct seq_file *p, loff_t *pos)
1486 {
1487         struct lprocfs_stats *stats = p->private;
1488
1489         return (*pos < stats->ls_num) ? pos : NULL;
1490 }
1491
1492 static void lprocfs_stats_seq_stop(struct seq_file *p, void *v)
1493 {
1494 }
1495
1496 static void *lprocfs_stats_seq_next(struct seq_file *p, void *v, loff_t *pos)
1497 {
1498         (*pos)++;
1499
1500         return lprocfs_stats_seq_start(p, pos);
1501 }
1502
1503 /* seq file export of one lprocfs counter */
1504 static int lprocfs_stats_seq_show(struct seq_file *p, void *v)
1505 {
1506         struct lprocfs_stats *stats = p->private;
1507         struct lprocfs_counter_header *hdr;
1508         struct lprocfs_counter ctr;
1509         int idx = *(loff_t *)v;
1510
1511         if (idx == 0) {
1512                 struct timespec64 now;
1513
1514                 ktime_get_real_ts64(&now);
1515                 seq_printf(p, "%-25s %llu.%09lu secs.nsecs\n",
1516                            "snapshot_time", (s64)now.tv_sec, now.tv_nsec);
1517         }
1518
1519         hdr = &stats->ls_cnt_header[idx];
1520         lprocfs_stats_collect(stats, idx, &ctr);
1521
1522         if (ctr.lc_count == 0)
1523                 return 0;
1524
1525         seq_printf(p, "%-25s %lld samples [%s]", hdr->lc_name,
1526                    ctr.lc_count, hdr->lc_units);
1527
1528         if ((hdr->lc_config & LPROCFS_CNTR_AVGMINMAX) && ctr.lc_count > 0) {
1529                 seq_printf(p, " %lld %lld %lld",
1530                            ctr.lc_min, ctr.lc_max, ctr.lc_sum);
1531                 if (hdr->lc_config & LPROCFS_CNTR_STDDEV)
1532                         seq_printf(p, " %llu", ctr.lc_sumsquare);
1533         }
1534         seq_putc(p, '\n');
1535         return 0;
1536 }
1537
1538 static const struct seq_operations lprocfs_stats_seq_sops = {
1539         .start  = lprocfs_stats_seq_start,
1540         .stop   = lprocfs_stats_seq_stop,
1541         .next   = lprocfs_stats_seq_next,
1542         .show   = lprocfs_stats_seq_show,
1543 };
1544
1545 static int lprocfs_stats_seq_open(struct inode *inode, struct file *file)
1546 {
1547         struct seq_file *seq;
1548         int rc;
1549
1550         rc = LPROCFS_ENTRY_CHECK(inode);
1551         if (rc < 0)
1552                 return rc;
1553
1554         rc = seq_open(file, &lprocfs_stats_seq_sops);
1555         if (rc)
1556                 return rc;
1557         seq = file->private_data;
1558         seq->private = inode->i_private ? inode->i_private : PDE_DATA(inode);
1559         return 0;
1560 }
1561
1562 static const struct file_operations lprocfs_stats_seq_fops = {
1563         .owner   = THIS_MODULE,
1564         .open    = lprocfs_stats_seq_open,
1565         .read    = seq_read,
1566         .write   = lprocfs_stats_seq_write,
1567         .llseek  = seq_lseek,
1568         .release = lprocfs_seq_release,
1569 };
1570
1571 int ldebugfs_register_stats(struct dentry *parent, const char *name,
1572                             struct lprocfs_stats *stats)
1573 {
1574         struct dentry *entry;
1575
1576         LASSERT(!IS_ERR_OR_NULL(parent));
1577
1578         entry = debugfs_create_file(name, 0644, parent, stats,
1579                                     &lprocfs_stats_seq_fops);
1580         if (IS_ERR_OR_NULL(entry))
1581                 return entry ? PTR_ERR(entry) : -ENOMEM;
1582
1583         return 0;
1584 }
1585 EXPORT_SYMBOL_GPL(ldebugfs_register_stats);
1586
1587 int lprocfs_register_stats(struct proc_dir_entry *root, const char *name,
1588                            struct lprocfs_stats *stats)
1589 {
1590         struct proc_dir_entry *entry;
1591         LASSERT(root != NULL);
1592
1593         entry = proc_create_data(name, 0644, root,
1594                                  &lprocfs_stats_seq_fops, stats);
1595         if (!entry)
1596                 return -ENOMEM;
1597         return 0;
1598 }
1599 EXPORT_SYMBOL(lprocfs_register_stats);
1600
1601 void lprocfs_counter_init(struct lprocfs_stats *stats, int index,
1602                           unsigned conf, const char *name, const char *units)
1603 {
1604         struct lprocfs_counter_header *header;
1605         struct lprocfs_counter *percpu_cntr;
1606         unsigned long flags = 0;
1607         unsigned int i;
1608         unsigned int num_cpu;
1609
1610         LASSERT(stats != NULL);
1611
1612         header = &stats->ls_cnt_header[index];
1613         LASSERTF(header != NULL, "Failed to allocate stats header:[%d]%s/%s\n",
1614                  index, name, units);
1615
1616         header->lc_config = conf;
1617         header->lc_name   = name;
1618         header->lc_units  = units;
1619
1620         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1621         for (i = 0; i < num_cpu; ++i) {
1622                 if (!stats->ls_percpu[i])
1623                         continue;
1624                 percpu_cntr = lprocfs_stats_counter_get(stats, i, index);
1625                 percpu_cntr->lc_count           = 0;
1626                 percpu_cntr->lc_min             = LC_MIN_INIT;
1627                 percpu_cntr->lc_max             = 0;
1628                 percpu_cntr->lc_sumsquare       = 0;
1629                 percpu_cntr->lc_sum             = 0;
1630                 if ((stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1631                         percpu_cntr->lc_sum_irq = 0;
1632         }
1633         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1634 }
1635 EXPORT_SYMBOL(lprocfs_counter_init);
1636
1637 static const char * const mps_stats[] = {
1638         [LPROC_MD_CLOSE]                = "close",
1639         [LPROC_MD_CREATE]               = "create",
1640         [LPROC_MD_ENQUEUE]              = "enqueue",
1641         [LPROC_MD_GETATTR]              = "getattr",
1642         [LPROC_MD_INTENT_LOCK]          = "intent_lock",
1643         [LPROC_MD_LINK]                 = "link",
1644         [LPROC_MD_RENAME]               = "rename",
1645         [LPROC_MD_SETATTR]              = "setattr",
1646         [LPROC_MD_FSYNC]                = "fsync",
1647         [LPROC_MD_READ_PAGE]            = "read_page",
1648         [LPROC_MD_UNLINK]               = "unlink",
1649         [LPROC_MD_SETXATTR]             = "setxattr",
1650         [LPROC_MD_GETXATTR]             = "getxattr",
1651         [LPROC_MD_INTENT_GETATTR_ASYNC] = "intent_getattr_async",
1652         [LPROC_MD_REVALIDATE_LOCK]      = "revalidate_lock",
1653 };
1654
1655 int lprocfs_alloc_md_stats(struct obd_device *obd,
1656                            unsigned int num_private_stats)
1657 {
1658         struct lprocfs_stats *stats;
1659         unsigned int num_stats;
1660         int rc, i;
1661
1662         /*
1663          * TODO Ensure that this function is only used where
1664          * appropriate by adding an assertion to the effect that
1665          * obd->obd_type->typ_md_ops is not NULL. We can't do this now
1666          * because mdt_procfs_init() uses this function to allocate
1667          * the stats backing /proc/fs/lustre/mdt/.../md_stats but the
1668          * mdt layer does not use the md_ops interface. This is
1669          * confusing and a waste of memory. See LU-2484.
1670          */
1671         LASSERT(obd->obd_proc_entry != NULL);
1672         LASSERT(obd->obd_md_stats == NULL);
1673
1674         num_stats = ARRAY_SIZE(mps_stats) + num_private_stats;
1675         stats = lprocfs_alloc_stats(num_stats, 0);
1676         if (!stats)
1677                 return -ENOMEM;
1678
1679         for (i = 0; i < ARRAY_SIZE(mps_stats); i++) {
1680                 lprocfs_counter_init(stats, i, 0, mps_stats[i], "reqs");
1681                 if (!stats->ls_cnt_header[i].lc_name) {
1682                         CERROR("Missing md_stat initializer md_op operation at offset %d. Aborting.\n",
1683                                i);
1684                         LBUG();
1685                 }
1686         }
1687
1688         rc = lprocfs_register_stats(obd->obd_proc_entry, "md_stats", stats);
1689         if (rc < 0) {
1690                 lprocfs_free_stats(&stats);
1691         } else {
1692                 obd->obd_md_stats = stats;
1693         }
1694
1695         return rc;
1696 }
1697 EXPORT_SYMBOL(lprocfs_alloc_md_stats);
1698
1699 void lprocfs_free_md_stats(struct obd_device *obd)
1700 {
1701         struct lprocfs_stats *stats = obd->obd_md_stats;
1702
1703         if (stats) {
1704                 obd->obd_md_stats = NULL;
1705                 lprocfs_free_stats(&stats);
1706         }
1707 }
1708 EXPORT_SYMBOL(lprocfs_free_md_stats);
1709
1710 void lprocfs_init_ldlm_stats(struct lprocfs_stats *ldlm_stats)
1711 {
1712         lprocfs_counter_init(ldlm_stats,
1713                              LDLM_ENQUEUE - LDLM_FIRST_OPC,
1714                              0, "ldlm_enqueue", "reqs");
1715         lprocfs_counter_init(ldlm_stats,
1716                              LDLM_CONVERT - LDLM_FIRST_OPC,
1717                              0, "ldlm_convert", "reqs");
1718         lprocfs_counter_init(ldlm_stats,
1719                              LDLM_CANCEL - LDLM_FIRST_OPC,
1720                              0, "ldlm_cancel", "reqs");
1721         lprocfs_counter_init(ldlm_stats,
1722                              LDLM_BL_CALLBACK - LDLM_FIRST_OPC,
1723                              0, "ldlm_bl_callback", "reqs");
1724         lprocfs_counter_init(ldlm_stats,
1725                              LDLM_CP_CALLBACK - LDLM_FIRST_OPC,
1726                              0, "ldlm_cp_callback", "reqs");
1727         lprocfs_counter_init(ldlm_stats,
1728                              LDLM_GL_CALLBACK - LDLM_FIRST_OPC,
1729                              0, "ldlm_gl_callback", "reqs");
1730 }
1731 EXPORT_SYMBOL(lprocfs_init_ldlm_stats);
1732
1733 __s64 lprocfs_read_helper(struct lprocfs_counter *lc,
1734                           struct lprocfs_counter_header *header,
1735                           enum lprocfs_stats_flags flags,
1736                           enum lprocfs_fields_flags field)
1737 {
1738         __s64 ret = 0;
1739
1740         if (!lc || !header)
1741                 RETURN(0);
1742
1743         switch (field) {
1744                 case LPROCFS_FIELDS_FLAGS_CONFIG:
1745                         ret = header->lc_config;
1746                         break;
1747                 case LPROCFS_FIELDS_FLAGS_SUM:
1748                         ret = lc->lc_sum;
1749                         if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1750                                 ret += lc->lc_sum_irq;
1751                         break;
1752                 case LPROCFS_FIELDS_FLAGS_MIN:
1753                         ret = lc->lc_min;
1754                         break;
1755                 case LPROCFS_FIELDS_FLAGS_MAX:
1756                         ret = lc->lc_max;
1757                         break;
1758                 case LPROCFS_FIELDS_FLAGS_AVG:
1759                         ret = (lc->lc_max - lc->lc_min) / 2;
1760                         break;
1761                 case LPROCFS_FIELDS_FLAGS_SUMSQUARE:
1762                         ret = lc->lc_sumsquare;
1763                         break;
1764                 case LPROCFS_FIELDS_FLAGS_COUNT:
1765                         ret = lc->lc_count;
1766                         break;
1767                 default:
1768                         break;
1769         };
1770         RETURN(ret);
1771 }
1772 EXPORT_SYMBOL(lprocfs_read_helper);
1773
1774 /**
1775  * string_to_size - convert ASCII string representing a numerical
1776  *                  value with optional units to 64-bit binary value
1777  *
1778  * @size:       The numerical value extract out of @buffer
1779  * @buffer:     passed in string to parse
1780  * @count:      length of the @buffer
1781  *
1782  * This function returns a 64-bit binary value if @buffer contains a valid
1783  * numerical string. The string is parsed to 3 significant figures after
1784  * the decimal point. Support the string containing an optional units at
1785  * the end which can be base 2 or base 10 in value. If no units are given
1786  * the string is assumed to just a numerical value.
1787  *
1788  * Returns:     @count if the string is successfully parsed,
1789  *              -errno on invalid input strings. Error values:
1790  *
1791  *  - ``-EINVAL``: @buffer is not a proper numerical string
1792  *  - ``-EOVERFLOW``: results does not fit into 64 bits.
1793  *  - ``-E2BIG ``: @buffer is not large
1794  */
1795 int string_to_size(u64 *size, const char *buffer, size_t count)
1796 {
1797         /* For string_get_size() it can support values above exabytes,
1798          * (ZiB, YiB) due to breaking the return value into a size and
1799          * bulk size to avoid 64 bit overflow. We don't break the size
1800          * up into block size units so we don't support ZiB or YiB.
1801          */
1802         static const char *const units_10[] = {
1803                 "kB", "MB", "GB", "TB", "PB", "EB"
1804         };
1805         static const char *const units_2[] = {
1806                 "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"
1807         };
1808         static const char *const *const units_str[] = {
1809                 [STRING_UNITS_2] = units_2,
1810                 [STRING_UNITS_10] = units_10,
1811         };
1812         static const unsigned int coeff[] = {
1813                 [STRING_UNITS_10] = 1000,
1814                 [STRING_UNITS_2] = 1024,
1815         };
1816         enum string_size_units unit;
1817         u64 whole, blk_size = 1;
1818         char kernbuf[22], *end;
1819         size_t len = count;
1820         int rc;
1821         int i;
1822
1823         if (count >= sizeof(kernbuf))
1824                 return -E2BIG;
1825
1826         *size = 0;
1827         /* 'iB' is used for based 2 numbers. If @buffer contains only a 'B'
1828          * or only numbers then we treat it as a direct number which doesn't
1829          * matter if its STRING_UNITS_2 or STRING_UNIT_10.
1830          */
1831         unit = strstr(buffer, "iB") ? STRING_UNITS_2 : STRING_UNITS_10;
1832         i = unit == STRING_UNITS_2 ? ARRAY_SIZE(units_2) - 1 :
1833                                      ARRAY_SIZE(units_10) - 1;
1834         do {
1835                 end = strstr(buffer, units_str[unit][i]);
1836                 if (end) {
1837                         for (; i >= 0; i--)
1838                                 blk_size *= coeff[unit];
1839                         len -= strlen(end);
1840                         break;
1841                 }
1842         } while (i--);
1843
1844         /* as 'B' is a substring of all units, we need to handle it
1845          * separately.
1846          */
1847         if (!end) {
1848                 /* 'B' is only acceptable letter at this point */
1849                 end = strchr(buffer, 'B');
1850                 if (end) {
1851                         len -= strlen(end);
1852
1853                         if (count - len > 2 ||
1854                             (count - len == 2 && strcmp(end, "B\n") != 0))
1855                                 return -EINVAL;
1856                 }
1857                 /* kstrtoull will error out if it has non digits */
1858                 goto numbers_only;
1859         }
1860
1861         end = strchr(buffer, '.');
1862         if (end) {
1863                 /* need to limit 3 decimal places */
1864                 char rem[4] = "000";
1865                 u64 frac = 0;
1866                 size_t off;
1867
1868                 len = end - buffer;
1869                 end++;
1870
1871                 /* limit to 3 decimal points */
1872                 off = min_t(size_t, 3, strspn(end, "0123456789"));
1873                 /* need to limit frac_d to a u32 */
1874                 memcpy(rem, end, off);
1875                 rc = kstrtoull(rem, 10, &frac);
1876                 if (rc)
1877                         return rc;
1878
1879                 if (fls64(frac) + fls64(blk_size) - 1 > 64)
1880                         return -EOVERFLOW;
1881
1882                 frac *= blk_size;
1883                 do_div(frac, 1000);
1884                 *size += frac;
1885         }
1886 numbers_only:
1887         snprintf(kernbuf, sizeof(kernbuf), "%.*s", (int)len, buffer);
1888         rc = kstrtoull(kernbuf, 10, &whole);
1889         if (rc)
1890                 return rc;
1891
1892         if (whole != 0 && fls64(whole) + fls64(blk_size) - 1 > 64)
1893                 return -EOVERFLOW;
1894
1895         *size += whole * blk_size;
1896
1897         return count;
1898 }
1899 EXPORT_SYMBOL(string_to_size);
1900
1901 /**
1902  * sysfs_memparse - parse a ASCII string to 64-bit binary value,
1903  *                  with optional units
1904  *
1905  * @buffer:     kernel pointer to input string
1906  * @count:      number of bytes in the input @buffer
1907  * @val:        (output) binary value returned to caller
1908  * @defunit:    default unit suffix to use if none is provided
1909  *
1910  * Parses a string into a number. The number stored at @buffer is
1911  * potentially suffixed with K, M, G, T, P, E. Besides these other
1912  * valid suffix units are shown in the string_to_size() function.
1913  * If the string lacks a suffix then the defunit is used. The defunit
1914  * should be given as a binary unit (e.g. MiB) as that is the standard
1915  * for tunables in Lustre. If no unit suffix is given (e.g. 'G'), then
1916  * it is assumed to be in binary units.
1917  *
1918  * Returns:     0 on success or -errno on failure.
1919  */
1920 int sysfs_memparse(const char *buffer, size_t count, u64 *val,
1921                    const char *defunit)
1922 {
1923         char param[23];
1924         int rc;
1925
1926         if (count >= sizeof(param))
1927                 return -E2BIG;
1928
1929         count = strlen(buffer);
1930         if (count && buffer[count - 1] == '\n')
1931                 count--;
1932
1933         if (!count)
1934                 return -EINVAL;
1935
1936         if (isalpha(buffer[count - 1])) {
1937                 if (buffer[count - 1] != 'B') {
1938                         scnprintf(param, sizeof(param), "%.*siB",
1939                                   (int)count, buffer);
1940                 } else {
1941                         memcpy(param, buffer, sizeof(param));
1942                 }
1943         } else {
1944                 scnprintf(param, sizeof(param), "%.*s%s", (int)count,
1945                           buffer, defunit);
1946         }
1947
1948         rc = string_to_size(val, param, strlen(param));
1949         return rc < 0 ? rc : 0;
1950 }
1951 EXPORT_SYMBOL(sysfs_memparse);
1952
1953 /* Obtains the conversion factor for the unit specified */
1954 static int get_mult(char unit, __u64 *mult)
1955 {
1956         __u64 units = 1;
1957
1958         switch (unit) {
1959         /* peta, tera, giga, mega, and kilo */
1960         case 'p':
1961         case 'P':
1962                 units <<= 10;
1963                 /* fallthrough */
1964         case 't':
1965         case 'T':
1966                 units <<= 10;
1967                 /* fallthrough */
1968         case 'g':
1969         case 'G':
1970                 units <<= 10;
1971                 /* fallthrough */
1972         case 'm':
1973         case 'M':
1974                 units <<= 10;
1975                 /* fallthrough */
1976         case 'k':
1977         case 'K':
1978                 units <<= 10;
1979                 break;
1980         /* some tests expect % to be accepted */
1981         case '%':
1982                 units = 1;
1983                 break;
1984         default:
1985                 return -EINVAL;
1986         }
1987
1988         *mult = units;
1989
1990         return 0;
1991 }
1992
1993 /*
1994  * Ensures the numeric string is valid. The function provides the final
1995  * multiplier in the case a unit exists at the end of the string. It also
1996  * locates the start of the whole and fractional parts (if any). This
1997  * function modifies the string so kstrtoull can be used to parse both
1998  * the whole and fraction portions. This function also figures out
1999  * the base of the number.
2000  */
2001 static int preprocess_numeric_str(char *buffer, __u64 *mult, __u64 def_mult,
2002                                   bool allow_units, char **whole, char **frac,
2003                                   unsigned int *base)
2004 {
2005         bool hit_decimal = false;
2006         bool hit_unit = false;
2007         int rc = 0;
2008         char *start;
2009         *mult = def_mult;
2010         *whole = NULL;
2011         *frac = NULL;
2012         *base = 10;
2013
2014         /* a hex string if it starts with "0x" */
2015         if (buffer[0] == '0' && tolower(buffer[1]) == 'x') {
2016                 *base = 16;
2017                 buffer += 2;
2018         }
2019
2020         start = buffer;
2021
2022         while (*buffer) {
2023                 /* allow for a single new line before the null terminator */
2024                 if (*buffer == '\n') {
2025                         *buffer = '\0';
2026                         buffer++;
2027
2028                         if (*buffer)
2029                                 return -EINVAL;
2030
2031                         break;
2032                 }
2033
2034                 /* any chars after our unit indicates a malformed string */
2035                 if (hit_unit)
2036                         return -EINVAL;
2037
2038                 /* ensure we only hit one decimal */
2039                 if (*buffer == '.') {
2040                         if (hit_decimal)
2041                                 return -EINVAL;
2042
2043                         /* if past start, there's a whole part */
2044                         if (start != buffer)
2045                                 *whole = start;
2046
2047                         *buffer = '\0';
2048                         start = buffer + 1;
2049                         hit_decimal = true;
2050                 } else if (!isdigit(*buffer) &&
2051                            !(*base == 16 && isxdigit(*buffer))) {
2052                         if (allow_units) {
2053                                 /* if we allow units, attempt to get mult */
2054                                 hit_unit = true;
2055                                 rc = get_mult(*buffer, mult);
2056                                 if (rc)
2057                                         return rc;
2058
2059                                 /* string stops here, but keep processing */
2060                                 *buffer = '\0';
2061                         } else {
2062                                 /* bad string */
2063                                 return -EINVAL;
2064                         }
2065                 }
2066
2067                 buffer++;
2068         }
2069
2070         if (hit_decimal) {
2071                 /* hit a decimal, make sure there's a fractional part */
2072                 if (!*start)
2073                         return -EINVAL;
2074
2075                 *frac = start;
2076         } else {
2077                 /* didn't hit a decimal, but may have a whole part */
2078                 if (start != buffer && *start)
2079                         *whole = start;
2080         }
2081
2082         /* malformed string if we didn't get anything */
2083         if (!*frac && !*whole)
2084                 return -EINVAL;
2085
2086         return 0;
2087 }
2088
2089 /*
2090  * Parses a numeric string which can contain a whole and fraction portion
2091  * into a __u64. Accepts a multiplier to apply to the value parsed. Also
2092  * allows the string to have a unit at the end. The function handles
2093  * wrapping of the final unsigned value.
2094  */
2095 static int str_to_u64_parse(char *buffer, unsigned long count,
2096                             __u64 *val, __u64 def_mult, bool allow_units)
2097 {
2098         __u64 whole = 0;
2099         __u64 frac = 0;
2100         unsigned int frac_d = 1;
2101         __u64 wrap_indicator = ULLONG_MAX;
2102         int rc = 0;
2103         __u64 mult;
2104         char *strwhole;
2105         char *strfrac;
2106         unsigned int base = 10;
2107
2108         rc = preprocess_numeric_str(buffer, &mult, def_mult, allow_units,
2109                                     &strwhole, &strfrac, &base);
2110
2111         if (rc)
2112                 return rc;
2113
2114         if (mult == 0) {
2115                 *val = 0;
2116                 return 0;
2117         }
2118
2119         /* the multiplier limits how large the value can be */
2120         wrap_indicator = div64_u64(wrap_indicator, mult);
2121
2122         if (strwhole) {
2123                 rc = kstrtoull(strwhole, base, &whole);
2124                 if (rc)
2125                         return rc;
2126
2127                 if (whole > wrap_indicator)
2128                         return -ERANGE;
2129
2130                 whole *= mult;
2131         }
2132
2133         if (strfrac) {
2134                 if (strlen(strfrac) > 10)
2135                         strfrac[10] = '\0';
2136
2137                 rc = kstrtoull(strfrac, base, &frac);
2138                 if (rc)
2139                         return rc;
2140
2141                 /* determine power of fractional portion */
2142                 while (*strfrac) {
2143                         frac_d *= base;
2144                         strfrac++;
2145                 }
2146
2147                 /* fractional portion is too large to perform calculation */
2148                 if (frac > wrap_indicator)
2149                         return -ERANGE;
2150
2151                 frac *= mult;
2152                 do_div(frac, frac_d);
2153         }
2154
2155         /* check that the sum of whole and fraction fits in u64 */
2156         if (whole > (ULLONG_MAX - frac))
2157                 return -ERANGE;
2158
2159         *val = whole + frac;
2160
2161         return 0;
2162 }
2163
2164 /*
2165  * This function parses numeric/hex strings into __s64. It accepts a multiplier
2166  * which will apply to the value parsed. It also can allow the string to
2167  * have a unit as the last character. The function handles overflow/underflow
2168  * of the signed integer.
2169  */
2170 int lu_str_to_s64(char *buffer, unsigned long count, __s64 *val, char defunit)
2171 {
2172         __u64 mult = 1;
2173         __u64 tmp;
2174         unsigned int offset = 0;
2175         int signed sign = 1;
2176         __u64 max = LLONG_MAX;
2177         int rc = 0;
2178
2179         if (defunit != '1') {
2180                 rc = get_mult(defunit, &mult);
2181                 if (rc)
2182                         return rc;
2183         }
2184
2185         /* keep track of our sign */
2186         if (*buffer == '-') {
2187                 sign = -1;
2188                 offset++;
2189                 /* equivalent to max = -LLONG_MIN, avoids overflow */
2190                 max++;
2191         }
2192
2193         rc = str_to_u64_parse(buffer + offset, count - offset,
2194                               &tmp, mult, true);
2195         if (rc)
2196                 return rc;
2197
2198         /* check for overflow/underflow */
2199         if (max < tmp)
2200                 return -ERANGE;
2201
2202         *val = (__s64)tmp * sign;
2203
2204         return 0;
2205 }
2206 EXPORT_SYMBOL(lu_str_to_s64);
2207
2208 /* identical to s64 version, but does not handle overflow */
2209 static int str_to_u64_internal(const char __user *buffer, unsigned long count,
2210                                __u64 *val, __u64 def_mult, bool allow_units)
2211 {
2212         char kernbuf[22];
2213         unsigned int offset = 0;
2214         int rc = 0;
2215
2216         if (count > (sizeof(kernbuf) - 1))
2217                 return -EINVAL;
2218
2219         if (copy_from_user(kernbuf, buffer, count))
2220                 return -EFAULT;
2221
2222         kernbuf[count] = '\0';
2223
2224         rc = str_to_u64_parse(kernbuf + offset, count - offset,
2225                               val, def_mult, allow_units);
2226         if (rc)
2227                 return rc;
2228
2229         return 0;
2230 }
2231 /**
2232  * Convert a user string into a signed 64 bit number. This function produces
2233  * an error when the value parsed from the string times multiplier underflows or
2234  * overflows. This function only accepts strings that contains digits, an
2235  * optional decimal, and a char representing a unit at the end. If a unit is
2236  * specified in the string, the multiplier provided by the caller is ignored.
2237  * This function can also accept hexadecimal strings which are prefixed with
2238  * "0x".
2239  *
2240  * \param[in] buffer    string consisting of numbers, a decimal, and a unit
2241  * \param[in] count     buffer length
2242  * \param[in] val       if successful, the value represented by the string
2243  * \param[in] defunit   default unit if string doesn't contain one
2244  *
2245  * \retval              0 on success
2246  * \retval              negative number on error
2247  */
2248 int lprocfs_str_with_units_to_s64(const char __user *buffer,
2249                                   unsigned long count, __s64 *val, char defunit)
2250 {
2251         char kernbuf[22];
2252
2253         if (count > (sizeof(kernbuf) - 1))
2254                 return -EINVAL;
2255
2256         if (copy_from_user(kernbuf, buffer, count))
2257                 return -EFAULT;
2258
2259         kernbuf[count] = '\0';
2260
2261         return lu_str_to_s64(kernbuf, count, val, defunit);
2262 }
2263 EXPORT_SYMBOL(lprocfs_str_with_units_to_s64);
2264
2265 /* identical to s64 version above, but does not handle overflow */
2266 int lprocfs_str_with_units_to_u64(const char __user *buffer,
2267                                   unsigned long count, __u64 *val, char defunit)
2268 {
2269         __u64 mult = 1;
2270         int rc;
2271
2272         if (defunit != '1') {
2273                 rc = get_mult(defunit, &mult);
2274                 if (rc)
2275                         return rc;
2276         }
2277
2278         return str_to_u64_internal(buffer, count, val, mult, true);
2279 }
2280 EXPORT_SYMBOL(lprocfs_str_with_units_to_u64);
2281
2282 char *lprocfs_strnstr(const char *s1, const char *s2, size_t len)
2283 {
2284         size_t l2;
2285
2286         l2 = strlen(s2);
2287         if (!l2)
2288                 return (char *)s1;
2289         while (len >= l2) {
2290                 len--;
2291                 if (!memcmp(s1, s2, l2))
2292                         return (char *)s1;
2293                 s1++;
2294         }
2295         return NULL;
2296 }
2297 EXPORT_SYMBOL(lprocfs_strnstr);
2298
2299 /**
2300  * Find the string \a name in the input \a buffer, and return a pointer to the
2301  * value immediately following \a name, reducing \a count appropriately.
2302  * If \a name is not found the original \a buffer is returned.
2303  */
2304 char *lprocfs_find_named_value(const char *buffer, const char *name,
2305                                 size_t *count)
2306 {
2307         char *val;
2308         size_t buflen = *count;
2309
2310         /* there is no strnstr() in rhel5 and ubuntu kernels */
2311         val = lprocfs_strnstr(buffer, name, buflen);
2312         if (!val)
2313                 return (char *)buffer;
2314
2315         val += strlen(name);                             /* skip prefix */
2316         while (val < buffer + buflen && isspace(*val)) /* skip separator */
2317                 val++;
2318
2319         *count = 0;
2320         while (val < buffer + buflen && isalnum(*val)) {
2321                 ++*count;
2322                 ++val;
2323         }
2324
2325         return val - *count;
2326 }
2327 EXPORT_SYMBOL(lprocfs_find_named_value);
2328
2329 int ldebugfs_seq_create(struct dentry *parent, const char *name, umode_t mode,
2330                         const struct file_operations *seq_fops, void *data)
2331 {
2332         struct dentry *entry;
2333
2334         /* Disallow secretly (un)writable entries. */
2335         LASSERT((!seq_fops->write) == (!(mode & 0222)));
2336
2337         entry = debugfs_create_file(name, mode, parent, data, seq_fops);
2338         if (IS_ERR_OR_NULL(entry))
2339                 return entry ? PTR_ERR(entry) : -ENOMEM;
2340
2341         return 0;
2342 }
2343 EXPORT_SYMBOL_GPL(ldebugfs_seq_create);
2344
2345 int lprocfs_seq_create(struct proc_dir_entry *parent,
2346                        const char *name,
2347                        mode_t mode,
2348                        const struct file_operations *seq_fops,
2349                        void *data)
2350 {
2351         struct proc_dir_entry *entry;
2352         ENTRY;
2353
2354         /* Disallow secretly (un)writable entries. */
2355         LASSERT((seq_fops->write == NULL) == ((mode & 0222) == 0));
2356
2357         entry = proc_create_data(name, mode, parent, seq_fops, data);
2358
2359         if (!entry)
2360                 RETURN(-ENOMEM);
2361
2362         RETURN(0);
2363 }
2364 EXPORT_SYMBOL(lprocfs_seq_create);
2365
2366 int lprocfs_obd_seq_create(struct obd_device *dev,
2367                            const char *name,
2368                            mode_t mode,
2369                            const struct file_operations *seq_fops,
2370                            void *data)
2371 {
2372         return (lprocfs_seq_create(dev->obd_proc_entry, name,
2373                                    mode, seq_fops, data));
2374 }
2375 EXPORT_SYMBOL(lprocfs_obd_seq_create);
2376
2377 void lprocfs_oh_tally(struct obd_histogram *oh, unsigned int value)
2378 {
2379         if (value >= OBD_HIST_MAX)
2380                 value = OBD_HIST_MAX - 1;
2381
2382         spin_lock(&oh->oh_lock);
2383         oh->oh_buckets[value]++;
2384         spin_unlock(&oh->oh_lock);
2385 }
2386 EXPORT_SYMBOL(lprocfs_oh_tally);
2387
2388 void lprocfs_oh_tally_log2(struct obd_histogram *oh, unsigned int value)
2389 {
2390         unsigned int val = 0;
2391
2392         if (likely(value != 0))
2393                 val = min(fls(value - 1), OBD_HIST_MAX);
2394
2395         lprocfs_oh_tally(oh, val);
2396 }
2397 EXPORT_SYMBOL(lprocfs_oh_tally_log2);
2398
2399 unsigned long lprocfs_oh_sum(struct obd_histogram *oh)
2400 {
2401         unsigned long ret = 0;
2402         int i;
2403
2404         for (i = 0; i < OBD_HIST_MAX; i++)
2405                 ret +=  oh->oh_buckets[i];
2406         return ret;
2407 }
2408 EXPORT_SYMBOL(lprocfs_oh_sum);
2409
2410 void lprocfs_oh_clear(struct obd_histogram *oh)
2411 {
2412         spin_lock(&oh->oh_lock);
2413         memset(oh->oh_buckets, 0, sizeof(oh->oh_buckets));
2414         spin_unlock(&oh->oh_lock);
2415 }
2416 EXPORT_SYMBOL(lprocfs_oh_clear);
2417
2418 ssize_t lustre_attr_show(struct kobject *kobj,
2419                          struct attribute *attr, char *buf)
2420 {
2421         struct lustre_attr *a = container_of(attr, struct lustre_attr, attr);
2422
2423         return a->show ? a->show(kobj, attr, buf) : 0;
2424 }
2425 EXPORT_SYMBOL_GPL(lustre_attr_show);
2426
2427 ssize_t lustre_attr_store(struct kobject *kobj, struct attribute *attr,
2428                           const char *buf, size_t len)
2429 {
2430         struct lustre_attr *a = container_of(attr, struct lustre_attr, attr);
2431
2432         return a->store ? a->store(kobj, attr, buf, len) : len;
2433 }
2434 EXPORT_SYMBOL_GPL(lustre_attr_store);
2435
2436 const struct sysfs_ops lustre_sysfs_ops = {
2437         .show  = lustre_attr_show,
2438         .store = lustre_attr_store,
2439 };
2440 EXPORT_SYMBOL_GPL(lustre_sysfs_ops);
2441
2442 int lprocfs_obd_max_pages_per_rpc_seq_show(struct seq_file *m, void *data)
2443 {
2444         struct obd_device *dev = data;
2445         struct client_obd *cli = &dev->u.cli;
2446
2447         spin_lock(&cli->cl_loi_list_lock);
2448         seq_printf(m, "%d\n", cli->cl_max_pages_per_rpc);
2449         spin_unlock(&cli->cl_loi_list_lock);
2450         return 0;
2451 }
2452 EXPORT_SYMBOL(lprocfs_obd_max_pages_per_rpc_seq_show);
2453
2454 ssize_t lprocfs_obd_max_pages_per_rpc_seq_write(struct file *file,
2455                                                 const char __user *buffer,
2456                                                 size_t count, loff_t *off)
2457 {
2458         struct seq_file *m = file->private_data;
2459         struct obd_device *dev = m->private;
2460         struct client_obd *cli = &dev->u.cli;
2461         struct obd_import *imp;
2462         struct obd_connect_data *ocd;
2463         int chunk_mask, rc;
2464         s64 val;
2465
2466         rc = lprocfs_str_with_units_to_s64(buffer, count, &val, '1');
2467         if (rc)
2468                 return rc;
2469         if (val < 0)
2470                 return -ERANGE;
2471
2472         /* if the max_pages is specified in bytes, convert to pages */
2473         if (val >= ONE_MB_BRW_SIZE)
2474                 val >>= PAGE_SHIFT;
2475
2476         with_imp_locked(dev, imp, rc) {
2477                 ocd = &imp->imp_connect_data;
2478                 chunk_mask = ~((1 << (cli->cl_chunkbits - PAGE_SHIFT)) - 1);
2479                 /* max_pages_per_rpc must be chunk aligned */
2480                 val = (val + ~chunk_mask) & chunk_mask;
2481                 if (val == 0 || (ocd->ocd_brw_size != 0 &&
2482                                  val > ocd->ocd_brw_size >> PAGE_SHIFT)) {
2483                         rc = -ERANGE;
2484                 } else {
2485                         spin_lock(&cli->cl_loi_list_lock);
2486                         cli->cl_max_pages_per_rpc = val;
2487                         client_adjust_max_dirty(cli);
2488                         spin_unlock(&cli->cl_loi_list_lock);
2489                 }
2490         }
2491
2492         return rc ?: count;
2493 }
2494 EXPORT_SYMBOL(lprocfs_obd_max_pages_per_rpc_seq_write);
2495
2496 ssize_t short_io_bytes_show(struct kobject *kobj, struct attribute *attr,
2497                             char *buf)
2498 {
2499         struct obd_device *dev = container_of(kobj, struct obd_device,
2500                                               obd_kset.kobj);
2501         struct client_obd *cli = &dev->u.cli;
2502         int rc;
2503
2504         spin_lock(&cli->cl_loi_list_lock);
2505         rc = sprintf(buf, "%d\n", cli->cl_max_short_io_bytes);
2506         spin_unlock(&cli->cl_loi_list_lock);
2507         return rc;
2508 }
2509 EXPORT_SYMBOL(short_io_bytes_show);
2510
2511 /* Used to catch people who think they're specifying pages. */
2512 #define MIN_SHORT_IO_BYTES 64U
2513
2514 ssize_t short_io_bytes_store(struct kobject *kobj, struct attribute *attr,
2515                              const char *buffer, size_t count)
2516 {
2517         struct obd_device *dev = container_of(kobj, struct obd_device,
2518                                               obd_kset.kobj);
2519         struct client_obd *cli = &dev->u.cli;
2520         char kernbuf[32];
2521         s64 val;
2522         int rc;
2523
2524         if (count >= sizeof(kernbuf))
2525                 return -EINVAL;
2526
2527         memcpy(kernbuf, buffer, count);
2528         kernbuf[count] = '\0';
2529         rc = lu_str_to_s64(kernbuf, count, &val, '1');
2530         if (rc)
2531                 GOTO(out, rc);
2532
2533         if (val == -1)
2534                 val = OBD_DEF_SHORT_IO_BYTES;
2535
2536         if (val && (val < MIN_SHORT_IO_BYTES || val > LNET_MTU))
2537                 GOTO(out, rc = -ERANGE);
2538
2539         rc = count;
2540
2541         spin_lock(&cli->cl_loi_list_lock);
2542         cli->cl_max_short_io_bytes = min_t(u64, val, OST_MAX_SHORT_IO_BYTES);
2543         spin_unlock(&cli->cl_loi_list_lock);
2544
2545 out:
2546         return rc;
2547 }
2548 EXPORT_SYMBOL(short_io_bytes_store);
2549
2550 int lprocfs_wr_root_squash(const char __user *buffer, unsigned long count,
2551                            struct root_squash_info *squash, char *name)
2552 {
2553         int rc;
2554         char kernbuf[64], *tmp, *errmsg;
2555         unsigned long uid, gid;
2556         ENTRY;
2557
2558         if (count >= sizeof(kernbuf)) {
2559                 errmsg = "string too long";
2560                 GOTO(failed_noprint, rc = -EINVAL);
2561         }
2562         if (copy_from_user(kernbuf, buffer, count)) {
2563                 errmsg = "bad address";
2564                 GOTO(failed_noprint, rc = -EFAULT);
2565         }
2566         kernbuf[count] = '\0';
2567
2568         /* look for uid gid separator */
2569         tmp = strchr(kernbuf, ':');
2570         if (!tmp) {
2571                 errmsg = "needs uid:gid format";
2572                 GOTO(failed, rc = -EINVAL);
2573         }
2574         *tmp = '\0';
2575         tmp++;
2576
2577         /* parse uid */
2578         if (kstrtoul(kernbuf, 0, &uid) != 0) {
2579                 errmsg = "bad uid";
2580                 GOTO(failed, rc = -EINVAL);
2581         }
2582
2583         /* parse gid */
2584         if (kstrtoul(tmp, 0, &gid) != 0) {
2585                 errmsg = "bad gid";
2586                 GOTO(failed, rc = -EINVAL);
2587         }
2588
2589         squash->rsi_uid = uid;
2590         squash->rsi_gid = gid;
2591
2592         LCONSOLE_INFO("%s: root_squash is set to %u:%u\n",
2593                       name, squash->rsi_uid, squash->rsi_gid);
2594         RETURN(count);
2595
2596 failed:
2597         if (tmp) {
2598                 tmp--;
2599                 *tmp = ':';
2600         }
2601         CWARN("%s: failed to set root_squash to \"%s\", %s, rc = %d\n",
2602               name, kernbuf, errmsg, rc);
2603         RETURN(rc);
2604 failed_noprint:
2605         CWARN("%s: failed to set root_squash due to %s, rc = %d\n",
2606               name, errmsg, rc);
2607         RETURN(rc);
2608 }
2609 EXPORT_SYMBOL(lprocfs_wr_root_squash);
2610
2611
2612 int lprocfs_wr_nosquash_nids(const char __user *buffer, unsigned long count,
2613                              struct root_squash_info *squash, char *name)
2614 {
2615         int rc;
2616         char *kernbuf = NULL;
2617         char *errmsg;
2618         LIST_HEAD(tmp);
2619         int len = count;
2620         ENTRY;
2621
2622         if (count > 4096) {
2623                 errmsg = "string too long";
2624                 GOTO(failed, rc = -EINVAL);
2625         }
2626
2627         OBD_ALLOC(kernbuf, count + 1);
2628         if (!kernbuf) {
2629                 errmsg = "no memory";
2630                 GOTO(failed, rc = -ENOMEM);
2631         }
2632         if (copy_from_user(kernbuf, buffer, count)) {
2633                 errmsg = "bad address";
2634                 GOTO(failed, rc = -EFAULT);
2635         }
2636         kernbuf[count] = '\0';
2637
2638         if (count > 0 && kernbuf[count - 1] == '\n')
2639                 len = count - 1;
2640
2641         if ((len == 4 && strncmp(kernbuf, "NONE", len) == 0) ||
2642             (len == 5 && strncmp(kernbuf, "clear", len) == 0)) {
2643                 /* empty string is special case */
2644                 spin_lock(&squash->rsi_lock);
2645                 if (!list_empty(&squash->rsi_nosquash_nids))
2646                         cfs_free_nidlist(&squash->rsi_nosquash_nids);
2647                 spin_unlock(&squash->rsi_lock);
2648                 LCONSOLE_INFO("%s: nosquash_nids is cleared\n", name);
2649                 OBD_FREE(kernbuf, count + 1);
2650                 RETURN(count);
2651         }
2652
2653         if (cfs_parse_nidlist(kernbuf, count, &tmp) <= 0) {
2654                 errmsg = "can't parse";
2655                 GOTO(failed, rc = -EINVAL);
2656         }
2657         LCONSOLE_INFO("%s: nosquash_nids set to %s\n",
2658                       name, kernbuf);
2659         OBD_FREE(kernbuf, count + 1);
2660         kernbuf = NULL;
2661
2662         spin_lock(&squash->rsi_lock);
2663         if (!list_empty(&squash->rsi_nosquash_nids))
2664                 cfs_free_nidlist(&squash->rsi_nosquash_nids);
2665         list_splice(&tmp, &squash->rsi_nosquash_nids);
2666         spin_unlock(&squash->rsi_lock);
2667
2668         RETURN(count);
2669
2670 failed:
2671         if (kernbuf) {
2672                 CWARN("%s: failed to set nosquash_nids to \"%s\", %s rc = %d\n",
2673                       name, kernbuf, errmsg, rc);
2674                 OBD_FREE(kernbuf, count + 1);
2675         } else {
2676                 CWARN("%s: failed to set nosquash_nids due to %s rc = %d\n",
2677                       name, errmsg, rc);
2678         }
2679         RETURN(rc);
2680 }
2681 EXPORT_SYMBOL(lprocfs_wr_nosquash_nids);
2682
2683 #endif /* CONFIG_PROC_FS*/