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