Whamcloud - gitweb
6d0ed9ff6964192ee3f548bc4b17db000e651293
[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         struct dhms ts;
1144         int i;
1145
1146         LASSERT(obd != NULL);
1147         LPROCFS_CLIMP_CHECK(obd);
1148         imp = obd->u.cli.cl_import;
1149
1150         now = ktime_get_real_seconds();
1151
1152         /* Some network health info for kicks */
1153         s2dhms(&ts, now - imp->imp_last_reply_time);
1154         seq_printf(m, "%-10s : %lld, "DHMS_FMT" ago\n",
1155                    "last reply", (s64)imp->imp_last_reply_time, DHMS_VARS(&ts));
1156
1157         cur = at_get(&imp->imp_at.iat_net_latency);
1158         worst = imp->imp_at.iat_net_latency.at_worst_ever;
1159         worstt = imp->imp_at.iat_net_latency.at_worst_time;
1160         s2dhms(&ts, now - worstt);
1161         seq_printf(m, "%-10s : cur %3u  worst %3u (at %lld, "DHMS_FMT" ago) ",
1162                    "network", cur, worst, (s64)worstt, DHMS_VARS(&ts));
1163         lprocfs_at_hist_helper(m, &imp->imp_at.iat_net_latency);
1164
1165         for(i = 0; i < IMP_AT_MAX_PORTALS; i++) {
1166                 if (imp->imp_at.iat_portal[i] == 0)
1167                         break;
1168                 cur = at_get(&imp->imp_at.iat_service_estimate[i]);
1169                 worst = imp->imp_at.iat_service_estimate[i].at_worst_ever;
1170                 worstt = imp->imp_at.iat_service_estimate[i].at_worst_time;
1171                 s2dhms(&ts, now - worstt);
1172                 seq_printf(m, "portal %-2d  : cur %3u  worst %3u (at %lld, "
1173                            DHMS_FMT" ago) ", imp->imp_at.iat_portal[i],
1174                            cur, worst, (s64)worstt, DHMS_VARS(&ts));
1175                 lprocfs_at_hist_helper(m, &imp->imp_at.iat_service_estimate[i]);
1176         }
1177
1178         LPROCFS_CLIMP_EXIT(obd);
1179         return 0;
1180 }
1181 EXPORT_SYMBOL(lprocfs_timeouts_seq_show);
1182
1183 int lprocfs_connect_flags_seq_show(struct seq_file *m, void *data)
1184 {
1185         struct obd_device *obd = data;
1186         __u64 flags;
1187         __u64 flags2;
1188
1189         LPROCFS_CLIMP_CHECK(obd);
1190         flags = obd->u.cli.cl_import->imp_connect_data.ocd_connect_flags;
1191         flags2 = obd->u.cli.cl_import->imp_connect_data.ocd_connect_flags2;
1192         seq_printf(m, "flags=%#llx\n", flags);
1193         seq_printf(m, "flags2=%#llx\n", flags2);
1194         obd_connect_seq_flags2str(m, flags, flags2, "\n");
1195         seq_printf(m, "\n");
1196         LPROCFS_CLIMP_EXIT(obd);
1197         return 0;
1198 }
1199 EXPORT_SYMBOL(lprocfs_connect_flags_seq_show);
1200
1201 int
1202 lprocfs_obd_setup(struct obd_device *obd)
1203 {
1204         int rc = 0;
1205
1206         LASSERT(obd != NULL);
1207         LASSERT(obd->obd_magic == OBD_DEVICE_MAGIC);
1208         LASSERT(obd->obd_type->typ_procroot != NULL);
1209
1210         obd->obd_proc_entry = lprocfs_register(obd->obd_name,
1211                                                obd->obd_type->typ_procroot,
1212                                                obd->obd_vars, obd);
1213         if (IS_ERR(obd->obd_proc_entry)) {
1214                 rc = PTR_ERR(obd->obd_proc_entry);
1215                 CERROR("error %d setting up lprocfs for %s\n",rc,obd->obd_name);
1216                 obd->obd_proc_entry = NULL;
1217         }
1218         return rc;
1219 }
1220 EXPORT_SYMBOL(lprocfs_obd_setup);
1221
1222 int lprocfs_obd_cleanup(struct obd_device *obd)
1223 {
1224         if (!obd)
1225                 return -EINVAL;
1226         if (obd->obd_proc_exports_entry) {
1227                 /* Should be no exports left */
1228                 lprocfs_remove(&obd->obd_proc_exports_entry);
1229                 obd->obd_proc_exports_entry = NULL;
1230         }
1231         if (obd->obd_proc_entry) {
1232                 lprocfs_remove(&obd->obd_proc_entry);
1233                 obd->obd_proc_entry = NULL;
1234         }
1235         return 0;
1236 }
1237 EXPORT_SYMBOL(lprocfs_obd_cleanup);
1238
1239 int lprocfs_stats_alloc_one(struct lprocfs_stats *stats, unsigned int cpuid)
1240 {
1241         struct lprocfs_counter  *cntr;
1242         unsigned int            percpusize;
1243         int                     rc = -ENOMEM;
1244         unsigned long           flags = 0;
1245         int                     i;
1246
1247         LASSERT(stats->ls_percpu[cpuid] == NULL);
1248         LASSERT((stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU) == 0);
1249
1250         percpusize = lprocfs_stats_counter_size(stats);
1251         LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[cpuid], percpusize);
1252         if (stats->ls_percpu[cpuid] != NULL) {
1253                 rc = 0;
1254                 if (unlikely(stats->ls_biggest_alloc_num <= cpuid)) {
1255                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1256                                 spin_lock_irqsave(&stats->ls_lock, flags);
1257                         else
1258                                 spin_lock(&stats->ls_lock);
1259                         if (stats->ls_biggest_alloc_num <= cpuid)
1260                                 stats->ls_biggest_alloc_num = cpuid + 1;
1261                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) {
1262                                 spin_unlock_irqrestore(&stats->ls_lock, flags);
1263                         } else {
1264                                 spin_unlock(&stats->ls_lock);
1265                         }
1266                 }
1267                 /* initialize the ls_percpu[cpuid] non-zero counter */
1268                 for (i = 0; i < stats->ls_num; ++i) {
1269                         cntr = lprocfs_stats_counter_get(stats, cpuid, i);
1270                         cntr->lc_min = LC_MIN_INIT;
1271                 }
1272         }
1273         return rc;
1274 }
1275
1276 struct lprocfs_stats *lprocfs_alloc_stats(unsigned int num,
1277                                           enum lprocfs_stats_flags flags)
1278 {
1279         struct lprocfs_stats    *stats;
1280         unsigned int            num_entry;
1281         unsigned int            percpusize = 0;
1282         int                     i;
1283
1284         if (num == 0)
1285                 return NULL;
1286
1287         if (lprocfs_no_percpu_stats != 0)
1288                 flags |= LPROCFS_STATS_FLAG_NOPERCPU;
1289
1290         if (flags & LPROCFS_STATS_FLAG_NOPERCPU)
1291                 num_entry = 1;
1292         else
1293                 num_entry = num_possible_cpus();
1294
1295         /* alloc percpu pointers for all possible cpu slots */
1296         LIBCFS_ALLOC(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1297         if (stats == NULL)
1298                 return NULL;
1299
1300         stats->ls_num = num;
1301         stats->ls_flags = flags;
1302         spin_lock_init(&stats->ls_lock);
1303
1304         /* alloc num of counter headers */
1305         LIBCFS_ALLOC(stats->ls_cnt_header,
1306                      stats->ls_num * sizeof(struct lprocfs_counter_header));
1307         if (stats->ls_cnt_header == NULL)
1308                 goto fail;
1309
1310         if ((flags & LPROCFS_STATS_FLAG_NOPERCPU) != 0) {
1311                 /* contains only one set counters */
1312                 percpusize = lprocfs_stats_counter_size(stats);
1313                 LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[0], percpusize);
1314                 if (stats->ls_percpu[0] == NULL)
1315                         goto fail;
1316                 stats->ls_biggest_alloc_num = 1;
1317         } else if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0) {
1318                 /* alloc all percpu data, currently only obd_memory use this */
1319                 for (i = 0; i < num_entry; ++i)
1320                         if (lprocfs_stats_alloc_one(stats, i) < 0)
1321                                 goto fail;
1322         }
1323
1324         return stats;
1325
1326 fail:
1327         lprocfs_free_stats(&stats);
1328         return NULL;
1329 }
1330 EXPORT_SYMBOL(lprocfs_alloc_stats);
1331
1332 void lprocfs_free_stats(struct lprocfs_stats **statsh)
1333 {
1334         struct lprocfs_stats *stats = *statsh;
1335         unsigned int num_entry;
1336         unsigned int percpusize;
1337         unsigned int i;
1338
1339         if (stats == NULL || stats->ls_num == 0)
1340                 return;
1341         *statsh = NULL;
1342
1343         if (stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU)
1344                 num_entry = 1;
1345         else
1346                 num_entry = num_possible_cpus();
1347
1348         percpusize = lprocfs_stats_counter_size(stats);
1349         for (i = 0; i < num_entry; i++)
1350                 if (stats->ls_percpu[i] != NULL)
1351                         LIBCFS_FREE(stats->ls_percpu[i], percpusize);
1352         if (stats->ls_cnt_header != NULL)
1353                 LIBCFS_FREE(stats->ls_cnt_header, stats->ls_num *
1354                                         sizeof(struct lprocfs_counter_header));
1355         LIBCFS_FREE(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1356 }
1357 EXPORT_SYMBOL(lprocfs_free_stats);
1358
1359 u64 lprocfs_stats_collector(struct lprocfs_stats *stats, int idx,
1360                             enum lprocfs_fields_flags field)
1361 {
1362         unsigned long flags = 0;
1363         unsigned int num_cpu;
1364         unsigned int i;
1365         u64 ret = 0;
1366
1367         LASSERT(stats);
1368
1369         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1370         for (i = 0; i < num_cpu; i++) {
1371                 struct lprocfs_counter *cntr;
1372
1373                 if (!stats->ls_percpu[i])
1374                         continue;
1375
1376                 cntr = lprocfs_stats_counter_get(stats, i, idx);
1377                 ret += lprocfs_read_helper(cntr, &stats->ls_cnt_header[idx],
1378                                            stats->ls_flags, field);
1379         }
1380         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1381         return ret;
1382 }
1383 EXPORT_SYMBOL(lprocfs_stats_collector);
1384
1385 void lprocfs_clear_stats(struct lprocfs_stats *stats)
1386 {
1387         struct lprocfs_counter          *percpu_cntr;
1388         int                             i;
1389         int                             j;
1390         unsigned int                    num_entry;
1391         unsigned long                   flags = 0;
1392
1393         num_entry = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1394
1395         for (i = 0; i < num_entry; i++) {
1396                 if (stats->ls_percpu[i] == NULL)
1397                         continue;
1398                 for (j = 0; j < stats->ls_num; j++) {
1399                         percpu_cntr = lprocfs_stats_counter_get(stats, i, j);
1400                         percpu_cntr->lc_count           = 0;
1401                         percpu_cntr->lc_min             = LC_MIN_INIT;
1402                         percpu_cntr->lc_max             = 0;
1403                         percpu_cntr->lc_sumsquare       = 0;
1404                         percpu_cntr->lc_sum             = 0;
1405                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1406                                 percpu_cntr->lc_sum_irq = 0;
1407                 }
1408         }
1409
1410         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1411 }
1412 EXPORT_SYMBOL(lprocfs_clear_stats);
1413
1414 static ssize_t lprocfs_stats_seq_write(struct file *file,
1415                                        const char __user *buf,
1416                                        size_t len, loff_t *off)
1417 {
1418         struct seq_file *seq = file->private_data;
1419         struct lprocfs_stats *stats = seq->private;
1420
1421         lprocfs_clear_stats(stats);
1422
1423         return len;
1424 }
1425
1426 static void *lprocfs_stats_seq_start(struct seq_file *p, loff_t *pos)
1427 {
1428         struct lprocfs_stats *stats = p->private;
1429
1430         return (*pos < stats->ls_num) ? pos : NULL;
1431 }
1432
1433 static void lprocfs_stats_seq_stop(struct seq_file *p, void *v)
1434 {
1435 }
1436
1437 static void *lprocfs_stats_seq_next(struct seq_file *p, void *v, loff_t *pos)
1438 {
1439         (*pos)++;
1440
1441         return lprocfs_stats_seq_start(p, pos);
1442 }
1443
1444 /* seq file export of one lprocfs counter */
1445 static int lprocfs_stats_seq_show(struct seq_file *p, void *v)
1446 {
1447         struct lprocfs_stats            *stats  = p->private;
1448         struct lprocfs_counter_header   *hdr;
1449         struct lprocfs_counter           ctr;
1450         int                              idx    = *(loff_t *)v;
1451
1452         if (idx == 0) {
1453                 struct timespec64 now;
1454
1455                 ktime_get_real_ts64(&now);
1456                 seq_printf(p, "%-25s %llu.%09lu secs.nsecs\n",
1457                            "snapshot_time", (s64)now.tv_sec, now.tv_nsec);
1458         }
1459
1460         hdr = &stats->ls_cnt_header[idx];
1461         lprocfs_stats_collect(stats, idx, &ctr);
1462
1463         if (ctr.lc_count == 0)
1464                 return 0;
1465
1466         seq_printf(p, "%-25s %lld samples [%s]", hdr->lc_name,
1467                    ctr.lc_count, hdr->lc_units);
1468
1469         if ((hdr->lc_config & LPROCFS_CNTR_AVGMINMAX) && ctr.lc_count > 0) {
1470                 seq_printf(p, " %lld %lld %lld",
1471                            ctr.lc_min, ctr.lc_max, ctr.lc_sum);
1472                 if (hdr->lc_config & LPROCFS_CNTR_STDDEV)
1473                         seq_printf(p, " %llu", ctr.lc_sumsquare);
1474         }
1475         seq_putc(p, '\n');
1476         return 0;
1477 }
1478
1479 static const struct seq_operations lprocfs_stats_seq_sops = {
1480         .start  = lprocfs_stats_seq_start,
1481         .stop   = lprocfs_stats_seq_stop,
1482         .next   = lprocfs_stats_seq_next,
1483         .show   = lprocfs_stats_seq_show,
1484 };
1485
1486 static int lprocfs_stats_seq_open(struct inode *inode, struct file *file)
1487 {
1488         struct seq_file *seq;
1489         int rc;
1490
1491         rc = LPROCFS_ENTRY_CHECK(inode);
1492         if (rc < 0)
1493                 return rc;
1494
1495         rc = seq_open(file, &lprocfs_stats_seq_sops);
1496         if (rc)
1497                 return rc;
1498         seq = file->private_data;
1499         seq->private = inode->i_private ? : PDE_DATA(inode);
1500         return 0;
1501 }
1502
1503 static const struct file_operations lprocfs_stats_seq_fops = {
1504         .owner   = THIS_MODULE,
1505         .open    = lprocfs_stats_seq_open,
1506         .read    = seq_read,
1507         .write   = lprocfs_stats_seq_write,
1508         .llseek  = seq_lseek,
1509         .release = lprocfs_seq_release,
1510 };
1511
1512 int ldebugfs_register_stats(struct dentry *parent, const char *name,
1513                             struct lprocfs_stats *stats)
1514 {
1515         struct dentry *entry;
1516
1517         LASSERT(!IS_ERR_OR_NULL(parent));
1518
1519         entry = debugfs_create_file(name, 0644, parent, stats,
1520                                     &lprocfs_stats_seq_fops);
1521         if (IS_ERR_OR_NULL(entry))
1522                 return entry ? PTR_ERR(entry) : -ENOMEM;
1523
1524         return 0;
1525 }
1526 EXPORT_SYMBOL_GPL(ldebugfs_register_stats);
1527
1528 int lprocfs_register_stats(struct proc_dir_entry *root, const char *name,
1529                            struct lprocfs_stats *stats)
1530 {
1531         struct proc_dir_entry *entry;
1532         LASSERT(root != NULL);
1533
1534         entry = proc_create_data(name, 0644, root,
1535                                  &lprocfs_stats_seq_fops, stats);
1536         if (entry == NULL)
1537                 return -ENOMEM;
1538         return 0;
1539 }
1540 EXPORT_SYMBOL(lprocfs_register_stats);
1541
1542 void lprocfs_counter_init(struct lprocfs_stats *stats, int index,
1543                           unsigned conf, const char *name, const char *units)
1544 {
1545         struct lprocfs_counter_header   *header;
1546         struct lprocfs_counter          *percpu_cntr;
1547         unsigned long                   flags = 0;
1548         unsigned int                    i;
1549         unsigned int                    num_cpu;
1550
1551         LASSERT(stats != NULL);
1552
1553         header = &stats->ls_cnt_header[index];
1554         LASSERTF(header != NULL, "Failed to allocate stats header:[%d]%s/%s\n",
1555                  index, name, units);
1556
1557         header->lc_config = conf;
1558         header->lc_name   = name;
1559         header->lc_units  = units;
1560
1561         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1562         for (i = 0; i < num_cpu; ++i) {
1563                 if (stats->ls_percpu[i] == NULL)
1564                         continue;
1565                 percpu_cntr = lprocfs_stats_counter_get(stats, i, index);
1566                 percpu_cntr->lc_count           = 0;
1567                 percpu_cntr->lc_min             = LC_MIN_INIT;
1568                 percpu_cntr->lc_max             = 0;
1569                 percpu_cntr->lc_sumsquare       = 0;
1570                 percpu_cntr->lc_sum             = 0;
1571                 if ((stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1572                         percpu_cntr->lc_sum_irq = 0;
1573         }
1574         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1575 }
1576 EXPORT_SYMBOL(lprocfs_counter_init);
1577
1578 /* Note that we only init md counters for ops whose offset is less
1579  * than NUM_MD_STATS. This is explained in a comment in the definition
1580  * of struct md_ops. */
1581 #define LPROCFS_MD_OP_INIT(base, stats, op)                                    \
1582         do {                                                                   \
1583                 unsigned int _idx = base + MD_COUNTER_OFFSET(op);              \
1584                                                                                \
1585                 if (MD_COUNTER_OFFSET(op) < NUM_MD_STATS) {                    \
1586                         LASSERT(_idx < stats->ls_num);                         \
1587                         lprocfs_counter_init(stats, _idx, 0, #op, "reqs");     \
1588                 }                                                              \
1589         } while (0)
1590
1591 void lprocfs_init_mps_stats(int num_private_stats, struct lprocfs_stats *stats)
1592 {
1593         LPROCFS_MD_OP_INIT(num_private_stats, stats, get_root);
1594         LPROCFS_MD_OP_INIT(num_private_stats, stats, null_inode);
1595         LPROCFS_MD_OP_INIT(num_private_stats, stats, close);
1596         LPROCFS_MD_OP_INIT(num_private_stats, stats, create);
1597         LPROCFS_MD_OP_INIT(num_private_stats, stats, enqueue);
1598         LPROCFS_MD_OP_INIT(num_private_stats, stats, getattr);
1599         LPROCFS_MD_OP_INIT(num_private_stats, stats, getattr_name);
1600         LPROCFS_MD_OP_INIT(num_private_stats, stats, intent_lock);
1601         LPROCFS_MD_OP_INIT(num_private_stats, stats, link);
1602         LPROCFS_MD_OP_INIT(num_private_stats, stats, rename);
1603         LPROCFS_MD_OP_INIT(num_private_stats, stats, setattr);
1604         LPROCFS_MD_OP_INIT(num_private_stats, stats, fsync);
1605         LPROCFS_MD_OP_INIT(num_private_stats, stats, read_page);
1606         LPROCFS_MD_OP_INIT(num_private_stats, stats, unlink);
1607         LPROCFS_MD_OP_INIT(num_private_stats, stats, setxattr);
1608         LPROCFS_MD_OP_INIT(num_private_stats, stats, getxattr);
1609         LPROCFS_MD_OP_INIT(num_private_stats, stats, init_ea_size);
1610         LPROCFS_MD_OP_INIT(num_private_stats, stats, get_lustre_md);
1611         LPROCFS_MD_OP_INIT(num_private_stats, stats, free_lustre_md);
1612         LPROCFS_MD_OP_INIT(num_private_stats, stats, merge_attr);
1613         LPROCFS_MD_OP_INIT(num_private_stats, stats, set_open_replay_data);
1614         LPROCFS_MD_OP_INIT(num_private_stats, stats, clear_open_replay_data);
1615         LPROCFS_MD_OP_INIT(num_private_stats, stats, set_lock_data);
1616         LPROCFS_MD_OP_INIT(num_private_stats, stats, lock_match);
1617         LPROCFS_MD_OP_INIT(num_private_stats, stats, cancel_unused);
1618         LPROCFS_MD_OP_INIT(num_private_stats, stats, intent_getattr_async);
1619         LPROCFS_MD_OP_INIT(num_private_stats, stats, revalidate_lock);
1620 }
1621
1622 int lprocfs_alloc_md_stats(struct obd_device *obd,
1623                            unsigned int num_private_stats)
1624 {
1625         struct lprocfs_stats *stats;
1626         unsigned int num_stats;
1627         int rc, i;
1628
1629         CLASSERT(offsetof(struct md_ops, MD_STATS_FIRST_OP) == 0);
1630         CLASSERT(_MD_COUNTER_OFFSET(MD_STATS_FIRST_OP) == 0);
1631         CLASSERT(_MD_COUNTER_OFFSET(MD_STATS_LAST_OP) > 0);
1632
1633         /* TODO Ensure that this function is only used where
1634          * appropriate by adding an assertion to the effect that
1635          * obd->obd_type->typ_md_ops is not NULL. We can't do this now
1636          * because mdt_procfs_init() uses this function to allocate
1637          * the stats backing /proc/fs/lustre/mdt/.../md_stats but the
1638          * mdt layer does not use the md_ops interface. This is
1639          * confusing and a waste of memory. See LU-2484.
1640          */
1641         LASSERT(obd->obd_proc_entry != NULL);
1642         LASSERT(obd->obd_md_stats == NULL);
1643         LASSERT(obd->obd_md_cntr_base == 0);
1644
1645         num_stats = NUM_MD_STATS + num_private_stats;
1646         stats = lprocfs_alloc_stats(num_stats, 0);
1647         if (stats == NULL)
1648                 return -ENOMEM;
1649
1650         lprocfs_init_mps_stats(num_private_stats, stats);
1651
1652         for (i = num_private_stats; i < num_stats; i++) {
1653                 if (stats->ls_cnt_header[i].lc_name == NULL) {
1654                         CERROR("Missing md_stat initializer md_op "
1655                                "operation at offset %d. Aborting.\n",
1656                                i - num_private_stats);
1657                         LBUG();
1658                 }
1659         }
1660
1661         rc = lprocfs_register_stats(obd->obd_proc_entry, "md_stats", stats);
1662         if (rc < 0) {
1663                 lprocfs_free_stats(&stats);
1664         } else {
1665                 obd->obd_md_stats = stats;
1666                 obd->obd_md_cntr_base = num_private_stats;
1667         }
1668
1669         return rc;
1670 }
1671 EXPORT_SYMBOL(lprocfs_alloc_md_stats);
1672
1673 void lprocfs_free_md_stats(struct obd_device *obd)
1674 {
1675         struct lprocfs_stats *stats = obd->obd_md_stats;
1676
1677         if (stats != NULL) {
1678                 obd->obd_md_stats = NULL;
1679                 obd->obd_md_cntr_base = 0;
1680                 lprocfs_free_stats(&stats);
1681         }
1682 }
1683 EXPORT_SYMBOL(lprocfs_free_md_stats);
1684
1685 void lprocfs_init_ldlm_stats(struct lprocfs_stats *ldlm_stats)
1686 {
1687         lprocfs_counter_init(ldlm_stats,
1688                              LDLM_ENQUEUE - LDLM_FIRST_OPC,
1689                              0, "ldlm_enqueue", "reqs");
1690         lprocfs_counter_init(ldlm_stats,
1691                              LDLM_CONVERT - LDLM_FIRST_OPC,
1692                              0, "ldlm_convert", "reqs");
1693         lprocfs_counter_init(ldlm_stats,
1694                              LDLM_CANCEL - LDLM_FIRST_OPC,
1695                              0, "ldlm_cancel", "reqs");
1696         lprocfs_counter_init(ldlm_stats,
1697                              LDLM_BL_CALLBACK - LDLM_FIRST_OPC,
1698                              0, "ldlm_bl_callback", "reqs");
1699         lprocfs_counter_init(ldlm_stats,
1700                              LDLM_CP_CALLBACK - LDLM_FIRST_OPC,
1701                              0, "ldlm_cp_callback", "reqs");
1702         lprocfs_counter_init(ldlm_stats,
1703                              LDLM_GL_CALLBACK - LDLM_FIRST_OPC,
1704                              0, "ldlm_gl_callback", "reqs");
1705 }
1706 EXPORT_SYMBOL(lprocfs_init_ldlm_stats);
1707
1708 __s64 lprocfs_read_helper(struct lprocfs_counter *lc,
1709                           struct lprocfs_counter_header *header,
1710                           enum lprocfs_stats_flags flags,
1711                           enum lprocfs_fields_flags field)
1712 {
1713         __s64 ret = 0;
1714
1715         if (lc == NULL || header == NULL)
1716                 RETURN(0);
1717
1718         switch (field) {
1719                 case LPROCFS_FIELDS_FLAGS_CONFIG:
1720                         ret = header->lc_config;
1721                         break;
1722                 case LPROCFS_FIELDS_FLAGS_SUM:
1723                         ret = lc->lc_sum;
1724                         if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1725                                 ret += lc->lc_sum_irq;
1726                         break;
1727                 case LPROCFS_FIELDS_FLAGS_MIN:
1728                         ret = lc->lc_min;
1729                         break;
1730                 case LPROCFS_FIELDS_FLAGS_MAX:
1731                         ret = lc->lc_max;
1732                         break;
1733                 case LPROCFS_FIELDS_FLAGS_AVG:
1734                         ret = (lc->lc_max - lc->lc_min) / 2;
1735                         break;
1736                 case LPROCFS_FIELDS_FLAGS_SUMSQUARE:
1737                         ret = lc->lc_sumsquare;
1738                         break;
1739                 case LPROCFS_FIELDS_FLAGS_COUNT:
1740                         ret = lc->lc_count;
1741                         break;
1742                 default:
1743                         break;
1744         };
1745         RETURN(ret);
1746 }
1747 EXPORT_SYMBOL(lprocfs_read_helper);
1748
1749 int lprocfs_read_frac_helper(char *buffer, unsigned long count, long val,
1750                              int mult)
1751 {
1752         long decimal_val, frac_val;
1753         int prtn;
1754
1755         if (count < 10)
1756                 return -EINVAL;
1757
1758         decimal_val = val / mult;
1759         prtn = snprintf(buffer, count, "%ld", decimal_val);
1760         frac_val = val % mult;
1761
1762         if (prtn < (count - 4) && frac_val > 0) {
1763                 long temp_frac;
1764                 int i, temp_mult = 1, frac_bits = 0;
1765
1766                 temp_frac = frac_val * 10;
1767                 buffer[prtn++] = '.';
1768                 while (frac_bits < 2 && (temp_frac / mult) < 1 ) {
1769                         /* only reserved 2 bits fraction */
1770                         buffer[prtn++] ='0';
1771                         temp_frac *= 10;
1772                         frac_bits++;
1773                 }
1774                 /*
1775                  * Need to think these cases :
1776                  *      1. #echo x.00 > /proc/xxx       output result : x
1777                  *      2. #echo x.0x > /proc/xxx       output result : x.0x
1778                  *      3. #echo x.x0 > /proc/xxx       output result : x.x
1779                  *      4. #echo x.xx > /proc/xxx       output result : x.xx
1780                  *      Only reserved 2 bits fraction.
1781                  */
1782                 for (i = 0; i < (5 - prtn); i++)
1783                         temp_mult *= 10;
1784
1785                 frac_bits = min((int)count - prtn, 3 - frac_bits);
1786                 prtn += snprintf(buffer + prtn, frac_bits, "%ld",
1787                                  frac_val * temp_mult / mult);
1788
1789                 prtn--;
1790                 while(buffer[prtn] < '1' || buffer[prtn] > '9') {
1791                         prtn--;
1792                         if (buffer[prtn] == '.') {
1793                                 prtn--;
1794                                 break;
1795                         }
1796                 }
1797                 prtn++;
1798         }
1799         buffer[prtn++] ='\n';
1800         return prtn;
1801 }
1802 EXPORT_SYMBOL(lprocfs_read_frac_helper);
1803
1804 int lprocfs_seq_read_frac_helper(struct seq_file *m, long val, int mult)
1805 {
1806         long decimal_val, frac_val;
1807
1808         decimal_val = val / mult;
1809         seq_printf(m, "%ld", decimal_val);
1810         frac_val = val % mult;
1811
1812         if (frac_val > 0) {
1813                 frac_val *= 100;
1814                 frac_val /= mult;
1815         }
1816         if (frac_val > 0) {
1817                 /* Three cases: x0, xx, 0x */
1818                 if ((frac_val % 10) != 0)
1819                         seq_printf(m, ".%ld", frac_val);
1820                 else
1821                         seq_printf(m, ".%ld", frac_val / 10);
1822         }
1823
1824         seq_printf(m, "\n");
1825         return 0;
1826 }
1827 EXPORT_SYMBOL(lprocfs_seq_read_frac_helper);
1828
1829 /* Obtains the conversion factor for the unit specified */
1830 static int get_mult(char unit, __u64 *mult)
1831 {
1832         __u64 units = 1;
1833
1834         switch (unit) {
1835         /* peta, tera, giga, mega, and kilo */
1836         case 'p':
1837         case 'P':
1838                 units <<= 10;
1839         case 't':
1840         case 'T':
1841                 units <<= 10;
1842         case 'g':
1843         case 'G':
1844                 units <<= 10;
1845         case 'm':
1846         case 'M':
1847                 units <<= 10;
1848         case 'k':
1849         case 'K':
1850                 units <<= 10;
1851                 break;
1852         /* some tests expect % to be accepted */
1853         case '%':
1854                 units = 1;
1855                 break;
1856         default:
1857                 return -EINVAL;
1858         }
1859
1860         *mult = units;
1861
1862         return 0;
1863 }
1864
1865 /*
1866  * Ensures the numeric string is valid. The function provides the final
1867  * multiplier in the case a unit exists at the end of the string. It also
1868  * locates the start of the whole and fractional parts (if any). This
1869  * function modifies the string so kstrtoull can be used to parse both
1870  * the whole and fraction portions. This function also figures out
1871  * the base of the number.
1872  */
1873 static int preprocess_numeric_str(char *buffer, __u64 *mult, __u64 def_mult,
1874                                   bool allow_units, char **whole, char **frac,
1875                                   unsigned int *base)
1876 {
1877         bool hit_decimal = false;
1878         bool hit_unit = false;
1879         int rc = 0;
1880         char *start;
1881         *mult = def_mult;
1882         *whole = NULL;
1883         *frac = NULL;
1884         *base = 10;
1885
1886         /* a hex string if it starts with "0x" */
1887         if (buffer[0] == '0' && tolower(buffer[1]) == 'x') {
1888                 *base = 16;
1889                 buffer += 2;
1890         }
1891
1892         start = buffer;
1893
1894         while (*buffer) {
1895                 /* allow for a single new line before the null terminator */
1896                 if (*buffer == '\n') {
1897                         *buffer = '\0';
1898                         buffer++;
1899
1900                         if (*buffer)
1901                                 return -EINVAL;
1902
1903                         break;
1904                 }
1905
1906                 /* any chars after our unit indicates a malformed string */
1907                 if (hit_unit)
1908                         return -EINVAL;
1909
1910                 /* ensure we only hit one decimal */
1911                 if (*buffer == '.') {
1912                         if (hit_decimal)
1913                                 return -EINVAL;
1914
1915                         /* if past start, there's a whole part */
1916                         if (start != buffer)
1917                                 *whole = start;
1918
1919                         *buffer = '\0';
1920                         start = buffer + 1;
1921                         hit_decimal = true;
1922                 } else if (!isdigit(*buffer) &&
1923                            !(*base == 16 && isxdigit(*buffer))) {
1924                         if (allow_units) {
1925                                 /* if we allow units, attempt to get mult */
1926                                 hit_unit = true;
1927                                 rc = get_mult(*buffer, mult);
1928                                 if (rc)
1929                                         return rc;
1930
1931                                 /* string stops here, but keep processing */
1932                                 *buffer = '\0';
1933                         } else {
1934                                 /* bad string */
1935                                 return -EINVAL;
1936                         }
1937                 }
1938
1939                 buffer++;
1940         }
1941
1942         if (hit_decimal) {
1943                 /* hit a decimal, make sure there's a fractional part */
1944                 if (!*start)
1945                         return -EINVAL;
1946
1947                 *frac = start;
1948         } else {
1949                 /* didn't hit a decimal, but may have a whole part */
1950                 if (start != buffer && *start)
1951                         *whole = start;
1952         }
1953
1954         /* malformed string if we didn't get anything */
1955         if (!*frac && !*whole)
1956                 return -EINVAL;
1957
1958         return 0;
1959 }
1960
1961 /*
1962  * Parses a numeric string which can contain a whole and fraction portion
1963  * into a __u64. Accepts a multiplier to apply to the value parsed. Also
1964  * allows the string to have a unit at the end. The function handles
1965  * wrapping of the final unsigned value.
1966  */
1967 static int str_to_u64_parse(char *buffer, unsigned long count,
1968                             __u64 *val, __u64 def_mult, bool allow_units)
1969 {
1970         __u64 whole = 0;
1971         __u64 frac = 0;
1972         unsigned int frac_d = 1;
1973         __u64 wrap_indicator = ULLONG_MAX;
1974         int rc = 0;
1975         __u64 mult;
1976         char *strwhole;
1977         char *strfrac;
1978         unsigned int base = 10;
1979
1980         rc = preprocess_numeric_str(buffer, &mult, def_mult, allow_units,
1981                                     &strwhole, &strfrac, &base);
1982
1983         if (rc)
1984                 return rc;
1985
1986         if (mult == 0) {
1987                 *val = 0;
1988                 return 0;
1989         }
1990
1991         /* the multiplier limits how large the value can be */
1992         wrap_indicator /=  mult;
1993
1994         if (strwhole) {
1995                 rc = kstrtoull(strwhole, base, &whole);
1996                 if (rc)
1997                         return rc;
1998
1999                 if (whole > wrap_indicator)
2000                         return -ERANGE;
2001
2002                 whole *= mult;
2003         }
2004
2005         if (strfrac) {
2006                 if (strlen(strfrac) > 10)
2007                         strfrac[10] = '\0';
2008
2009                 rc = kstrtoull(strfrac, base, &frac);
2010                 if (rc)
2011                         return rc;
2012
2013                 /* determine power of fractional portion */
2014                 while (*strfrac) {
2015                         frac_d *= base;
2016                         strfrac++;
2017                 }
2018
2019                 /* fractional portion is too large to perform calculation */
2020                 if (frac > wrap_indicator)
2021                         return -ERANGE;
2022
2023                 frac *= mult;
2024                 do_div(frac, frac_d);
2025         }
2026
2027         /* check that the sum of whole and fraction fits in u64 */
2028         if (whole > (ULLONG_MAX - frac))
2029                 return -ERANGE;
2030
2031         *val = whole + frac;
2032
2033         return 0;
2034 }
2035
2036 /*
2037  * This function parses numeric/hex strings into __s64. It accepts a multiplier
2038  * which will apply to the value parsed. It also can allow the string to
2039  * have a unit as the last character. The function handles overflow/underflow
2040  * of the signed integer.
2041  */
2042 static int str_to_s64_internal(const char __user *buffer, unsigned long count,
2043                                __s64 *val, __u64 def_mult, bool allow_units)
2044 {
2045         char kernbuf[22];
2046         __u64 tmp;
2047         unsigned int offset = 0;
2048         int signed sign = 1;
2049         __u64 max = LLONG_MAX;
2050         int rc = 0;
2051
2052         if (count > (sizeof(kernbuf) - 1))
2053                 return -EINVAL;
2054
2055         if (copy_from_user(kernbuf, buffer, count))
2056                 return -EFAULT;
2057
2058         kernbuf[count] = '\0';
2059
2060         /* keep track of our sign */
2061         if (*kernbuf == '-') {
2062                 sign = -1;
2063                 offset++;
2064                 /* equivalent to max = -LLONG_MIN, avoids overflow */
2065                 max++;
2066         }
2067
2068         rc = str_to_u64_parse(kernbuf + offset, count - offset,
2069                               &tmp, def_mult, allow_units);
2070         if (rc)
2071                 return rc;
2072
2073         /* check for overflow/underflow */
2074         if (max < tmp)
2075                 return -ERANGE;
2076
2077         *val = (__s64)tmp * sign;
2078
2079         return 0;
2080 }
2081
2082 /**
2083  * Convert a user string into a signed 64 bit number. This function produces
2084  * an error when the value parsed from the string underflows or
2085  * overflows. This function accepts strings which contain digits and
2086  * optionally a decimal or hex strings which are prefixed with "0x".
2087  *
2088  * \param[in] buffer    string consisting of numbers and optionally a decimal
2089  * \param[in] count     buffer length
2090  * \param[in] val       if successful, the value represented by the string
2091  *
2092  * \retval              0 on success
2093  * \retval              negative number on error
2094  */
2095 int lprocfs_str_to_s64(const char __user *buffer, unsigned long count,
2096                        __s64 *val)
2097 {
2098         return str_to_s64_internal(buffer, count, val, 1, false);
2099 }
2100 EXPORT_SYMBOL(lprocfs_str_to_s64);
2101
2102 /**
2103  * Convert a user string into a signed 64 bit number. This function produces
2104  * an error when the value parsed from the string times multiplier underflows or
2105  * overflows. This function only accepts strings that contains digits, an
2106  * optional decimal, and a char representing a unit at the end. If a unit is
2107  * specified in the string, the multiplier provided by the caller is ignored.
2108  * This function can also accept hexadecimal strings which are prefixed with
2109  * "0x".
2110  *
2111  * \param[in] buffer    string consisting of numbers, a decimal, and a unit
2112  * \param[in] count     buffer length
2113  * \param[in] val       if successful, the value represented by the string
2114  * \param[in] defunit   default unit if string doesn't contain one
2115  *
2116  * \retval              0 on success
2117  * \retval              negative number on error
2118  */
2119 int lprocfs_str_with_units_to_s64(const char __user *buffer,
2120                                   unsigned long count, __s64 *val, char defunit)
2121 {
2122         __u64 mult = 1;
2123         int rc;
2124
2125         if (defunit != '1') {
2126                 rc = get_mult(defunit, &mult);
2127                 if (rc)
2128                         return rc;
2129         }
2130
2131         return str_to_s64_internal(buffer, count, val, mult, true);
2132 }
2133 EXPORT_SYMBOL(lprocfs_str_with_units_to_s64);
2134
2135 static char *lprocfs_strnstr(const char *s1, const char *s2, size_t len)
2136 {
2137         size_t l2;
2138
2139         l2 = strlen(s2);
2140         if (!l2)
2141                 return (char *)s1;
2142         while (len >= l2) {
2143                 len--;
2144                 if (!memcmp(s1, s2, l2))
2145                         return (char *)s1;
2146                 s1++;
2147         }
2148         return NULL;
2149 }
2150
2151 /**
2152  * Find the string \a name in the input \a buffer, and return a pointer to the
2153  * value immediately following \a name, reducing \a count appropriately.
2154  * If \a name is not found the original \a buffer is returned.
2155  */
2156 char *lprocfs_find_named_value(const char *buffer, const char *name,
2157                                 size_t *count)
2158 {
2159         char *val;
2160         size_t buflen = *count;
2161
2162         /* there is no strnstr() in rhel5 and ubuntu kernels */
2163         val = lprocfs_strnstr(buffer, name, buflen);
2164         if (val == NULL)
2165                 return (char *)buffer;
2166
2167         val += strlen(name);                             /* skip prefix */
2168         while (val < buffer + buflen && isspace(*val)) /* skip separator */
2169                 val++;
2170
2171         *count = 0;
2172         while (val < buffer + buflen && isalnum(*val)) {
2173                 ++*count;
2174                 ++val;
2175         }
2176
2177         return val - *count;
2178 }
2179 EXPORT_SYMBOL(lprocfs_find_named_value);
2180
2181 int ldebugfs_seq_create(struct dentry *parent, const char *name, umode_t mode,
2182                         const struct file_operations *seq_fops, void *data)
2183 {
2184         struct dentry *entry;
2185
2186         /* Disallow secretly (un)writable entries. */
2187         LASSERT((!seq_fops->write) == (!(mode & 0222)));
2188
2189         entry = debugfs_create_file(name, mode, parent, data, seq_fops);
2190         if (IS_ERR_OR_NULL(entry))
2191                 return entry ? PTR_ERR(entry) : -ENOMEM;
2192
2193         return 0;
2194 }
2195 EXPORT_SYMBOL_GPL(ldebugfs_seq_create);
2196
2197 int lprocfs_seq_create(struct proc_dir_entry *parent,
2198                        const char *name,
2199                        mode_t mode,
2200                        const struct file_operations *seq_fops,
2201                        void *data)
2202 {
2203         struct proc_dir_entry *entry;
2204         ENTRY;
2205
2206         /* Disallow secretly (un)writable entries. */
2207         LASSERT((seq_fops->write == NULL) == ((mode & 0222) == 0));
2208
2209         entry = proc_create_data(name, mode, parent, seq_fops, data);
2210
2211         if (entry == NULL)
2212                 RETURN(-ENOMEM);
2213
2214         RETURN(0);
2215 }
2216 EXPORT_SYMBOL(lprocfs_seq_create);
2217
2218 int lprocfs_obd_seq_create(struct obd_device *dev,
2219                            const char *name,
2220                            mode_t mode,
2221                            const struct file_operations *seq_fops,
2222                            void *data)
2223 {
2224         return (lprocfs_seq_create(dev->obd_proc_entry, name,
2225                                    mode, seq_fops, data));
2226 }
2227 EXPORT_SYMBOL(lprocfs_obd_seq_create);
2228
2229 void lprocfs_oh_tally(struct obd_histogram *oh, unsigned int value)
2230 {
2231         if (value >= OBD_HIST_MAX)
2232                 value = OBD_HIST_MAX - 1;
2233
2234         spin_lock(&oh->oh_lock);
2235         oh->oh_buckets[value]++;
2236         spin_unlock(&oh->oh_lock);
2237 }
2238 EXPORT_SYMBOL(lprocfs_oh_tally);
2239
2240 void lprocfs_oh_tally_log2(struct obd_histogram *oh, unsigned int value)
2241 {
2242         unsigned int val = 0;
2243
2244         if (likely(value != 0))
2245                 val = min(fls(value - 1), OBD_HIST_MAX);
2246
2247         lprocfs_oh_tally(oh, val);
2248 }
2249 EXPORT_SYMBOL(lprocfs_oh_tally_log2);
2250
2251 unsigned long lprocfs_oh_sum(struct obd_histogram *oh)
2252 {
2253         unsigned long ret = 0;
2254         int i;
2255
2256         for (i = 0; i < OBD_HIST_MAX; i++)
2257                 ret +=  oh->oh_buckets[i];
2258         return ret;
2259 }
2260 EXPORT_SYMBOL(lprocfs_oh_sum);
2261
2262 void lprocfs_oh_clear(struct obd_histogram *oh)
2263 {
2264         spin_lock(&oh->oh_lock);
2265         memset(oh->oh_buckets, 0, sizeof(oh->oh_buckets));
2266         spin_unlock(&oh->oh_lock);
2267 }
2268 EXPORT_SYMBOL(lprocfs_oh_clear);
2269
2270 ssize_t lustre_attr_show(struct kobject *kobj,
2271                          struct attribute *attr, char *buf)
2272 {
2273         struct lustre_attr *a = container_of(attr, struct lustre_attr, attr);
2274
2275         return a->show ? a->show(kobj, attr, buf) : 0;
2276 }
2277 EXPORT_SYMBOL_GPL(lustre_attr_show);
2278
2279 ssize_t lustre_attr_store(struct kobject *kobj, struct attribute *attr,
2280                           const char *buf, size_t len)
2281 {
2282         struct lustre_attr *a = container_of(attr, struct lustre_attr, attr);
2283
2284         return a->store ? a->store(kobj, attr, buf, len) : len;
2285 }
2286 EXPORT_SYMBOL_GPL(lustre_attr_store);
2287
2288 const struct sysfs_ops lustre_sysfs_ops = {
2289         .show  = lustre_attr_show,
2290         .store = lustre_attr_store,
2291 };
2292 EXPORT_SYMBOL_GPL(lustre_sysfs_ops);
2293
2294 int lprocfs_obd_rd_max_pages_per_rpc(char *page, char **start, off_t off,
2295                                      int count, int *eof, void *data)
2296 {
2297         struct obd_device *dev = data;
2298         struct client_obd *cli = &dev->u.cli;
2299         int rc;
2300
2301         spin_lock(&cli->cl_loi_list_lock);
2302         rc = snprintf(page, count, "%d\n", cli->cl_max_pages_per_rpc);
2303         spin_unlock(&cli->cl_loi_list_lock);
2304
2305         return rc;
2306 }
2307
2308 int lprocfs_obd_max_pages_per_rpc_seq_show(struct seq_file *m, void *data)
2309 {
2310         struct obd_device *dev = data;
2311         struct client_obd *cli = &dev->u.cli;
2312
2313         spin_lock(&cli->cl_loi_list_lock);
2314         seq_printf(m, "%d\n", cli->cl_max_pages_per_rpc);
2315         spin_unlock(&cli->cl_loi_list_lock);
2316         return 0;
2317 }
2318 EXPORT_SYMBOL(lprocfs_obd_max_pages_per_rpc_seq_show);
2319
2320 int lprocfs_wr_root_squash(const char __user *buffer, unsigned long count,
2321                            struct root_squash_info *squash, char *name)
2322 {
2323         int rc;
2324         char kernbuf[64], *tmp, *errmsg;
2325         unsigned long uid, gid;
2326         ENTRY;
2327
2328         if (count >= sizeof(kernbuf)) {
2329                 errmsg = "string too long";
2330                 GOTO(failed_noprint, rc = -EINVAL);
2331         }
2332         if (copy_from_user(kernbuf, buffer, count)) {
2333                 errmsg = "bad address";
2334                 GOTO(failed_noprint, rc = -EFAULT);
2335         }
2336         kernbuf[count] = '\0';
2337
2338         /* look for uid gid separator */
2339         tmp = strchr(kernbuf, ':');
2340         if (tmp == NULL) {
2341                 errmsg = "needs uid:gid format";
2342                 GOTO(failed, rc = -EINVAL);
2343         }
2344         *tmp = '\0';
2345         tmp++;
2346
2347         /* parse uid */
2348         if (kstrtoul(kernbuf, 0, &uid) != 0) {
2349                 errmsg = "bad uid";
2350                 GOTO(failed, rc = -EINVAL);
2351         }
2352
2353         /* parse gid */
2354         if (kstrtoul(tmp, 0, &gid) != 0) {
2355                 errmsg = "bad gid";
2356                 GOTO(failed, rc = -EINVAL);
2357         }
2358
2359         squash->rsi_uid = uid;
2360         squash->rsi_gid = gid;
2361
2362         LCONSOLE_INFO("%s: root_squash is set to %u:%u\n",
2363                       name, squash->rsi_uid, squash->rsi_gid);
2364         RETURN(count);
2365
2366 failed:
2367         if (tmp != NULL) {
2368                 tmp--;
2369                 *tmp = ':';
2370         }
2371         CWARN("%s: failed to set root_squash to \"%s\", %s, rc = %d\n",
2372               name, kernbuf, errmsg, rc);
2373         RETURN(rc);
2374 failed_noprint:
2375         CWARN("%s: failed to set root_squash due to %s, rc = %d\n",
2376               name, errmsg, rc);
2377         RETURN(rc);
2378 }
2379 EXPORT_SYMBOL(lprocfs_wr_root_squash);
2380
2381
2382 int lprocfs_wr_nosquash_nids(const char __user *buffer, unsigned long count,
2383                              struct root_squash_info *squash, char *name)
2384 {
2385         int rc;
2386         char *kernbuf = NULL;
2387         char *errmsg;
2388         struct list_head tmp;
2389         int len = count;
2390         ENTRY;
2391
2392         if (count > 4096) {
2393                 errmsg = "string too long";
2394                 GOTO(failed, rc = -EINVAL);
2395         }
2396
2397         OBD_ALLOC(kernbuf, count + 1);
2398         if (kernbuf == NULL) {
2399                 errmsg = "no memory";
2400                 GOTO(failed, rc = -ENOMEM);
2401         }
2402         if (copy_from_user(kernbuf, buffer, count)) {
2403                 errmsg = "bad address";
2404                 GOTO(failed, rc = -EFAULT);
2405         }
2406         kernbuf[count] = '\0';
2407
2408         if (count > 0 && kernbuf[count - 1] == '\n')
2409                 len = count - 1;
2410
2411         if ((len == 4 && strncmp(kernbuf, "NONE", len) == 0) ||
2412             (len == 5 && strncmp(kernbuf, "clear", len) == 0)) {
2413                 /* empty string is special case */
2414                 down_write(&squash->rsi_sem);
2415                 if (!list_empty(&squash->rsi_nosquash_nids))
2416                         cfs_free_nidlist(&squash->rsi_nosquash_nids);
2417                 up_write(&squash->rsi_sem);
2418                 LCONSOLE_INFO("%s: nosquash_nids is cleared\n", name);
2419                 OBD_FREE(kernbuf, count + 1);
2420                 RETURN(count);
2421         }
2422
2423         INIT_LIST_HEAD(&tmp);
2424         if (cfs_parse_nidlist(kernbuf, count, &tmp) <= 0) {
2425                 errmsg = "can't parse";
2426                 GOTO(failed, rc = -EINVAL);
2427         }
2428         LCONSOLE_INFO("%s: nosquash_nids set to %s\n",
2429                       name, kernbuf);
2430         OBD_FREE(kernbuf, count + 1);
2431         kernbuf = NULL;
2432
2433         down_write(&squash->rsi_sem);
2434         if (!list_empty(&squash->rsi_nosquash_nids))
2435                 cfs_free_nidlist(&squash->rsi_nosquash_nids);
2436         list_splice(&tmp, &squash->rsi_nosquash_nids);
2437         up_write(&squash->rsi_sem);
2438
2439         RETURN(count);
2440
2441 failed:
2442         if (kernbuf) {
2443                 CWARN("%s: failed to set nosquash_nids to \"%s\", %s rc = %d\n",
2444                       name, kernbuf, errmsg, rc);
2445                 OBD_FREE(kernbuf, count + 1);
2446         } else {
2447                 CWARN("%s: failed to set nosquash_nids due to %s rc = %d\n",
2448                       name, errmsg, rc);
2449         }
2450         RETURN(rc);
2451 }
2452 EXPORT_SYMBOL(lprocfs_wr_nosquash_nids);
2453
2454 #endif /* CONFIG_PROC_FS*/