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