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