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