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