Whamcloud - gitweb
5b11a27f49cad2ed39242ca50a3859a6fdf90363
[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         "name_encryption",      /* 0x8000000 */
652         NULL
653 };
654
655 void obd_connect_seq_flags2str(struct seq_file *m, __u64 flags, __u64 flags2,
656                                const char *sep)
657 {
658         bool first = true;
659         __u64 mask;
660         int i;
661
662         for (i = 0, mask = 1; i < 64; i++, mask <<= 1) {
663                 if (flags & mask) {
664                         seq_printf(m, "%s%s",
665                                    first ? "" : sep, obd_connect_names[i]);
666                         first = false;
667                 }
668         }
669
670         if (flags & ~(mask - 1)) {
671                 seq_printf(m, "%sunknown_%#llx",
672                            first ? "" : sep, flags & ~(mask - 1));
673                 first = false;
674         }
675
676         if (!(flags & OBD_CONNECT_FLAGS2) || flags2 == 0)
677                 return;
678
679         for (i = 64, mask = 1; obd_connect_names[i] != NULL; i++, mask <<= 1) {
680                 if (flags2 & mask) {
681                         seq_printf(m, "%s%s",
682                                    first ? "" : sep, obd_connect_names[i]);
683                         first = false;
684                 }
685         }
686
687         if (flags2 & ~(mask - 1)) {
688                 seq_printf(m, "%sunknown2_%#llx",
689                            first ? "" : sep, flags2 & ~(mask - 1));
690                 first = false;
691         }
692 }
693 EXPORT_SYMBOL(obd_connect_seq_flags2str);
694
695 int obd_connect_flags2str(char *page, int count, __u64 flags, __u64 flags2,
696                           const char *sep)
697 {
698         __u64 mask;
699         int i, ret = 0;
700
701         for (i = 0, mask = 1; i < 64; i++, mask <<= 1) {
702                 if (flags & mask)
703                         ret += snprintf(page + ret, count - ret, "%s%s",
704                                         ret ? sep : "", obd_connect_names[i]);
705         }
706
707         if (flags & ~(mask - 1))
708                 ret += snprintf(page + ret, count - ret,
709                                 "%sunknown_%#llx",
710                                 ret ? sep : "", flags & ~(mask - 1));
711
712         if (!(flags & OBD_CONNECT_FLAGS2) || flags2 == 0)
713                 return ret;
714
715         for (i = 64, mask = 1; obd_connect_names[i] != NULL; i++, mask <<= 1) {
716                 if (flags2 & mask)
717                         ret += snprintf(page + ret, count - ret, "%s%s",
718                                         ret ? sep : "", obd_connect_names[i]);
719         }
720
721         if (flags2 & ~(mask - 1))
722                 ret += snprintf(page + ret, count - ret,
723                                 "%sunknown2_%#llx",
724                                 ret ? sep : "", flags2 & ~(mask - 1));
725
726         return ret;
727 }
728 EXPORT_SYMBOL(obd_connect_flags2str);
729
730 void
731 obd_connect_data_seqprint(struct seq_file *m, struct obd_connect_data *ocd)
732 {
733         __u64 flags;
734
735         LASSERT(ocd != NULL);
736         flags = ocd->ocd_connect_flags;
737
738         seq_printf(m, "    connect_data:\n"
739                    "       flags: %#llx\n"
740                    "       instance: %u\n",
741                    ocd->ocd_connect_flags,
742                    ocd->ocd_instance);
743         if (flags & OBD_CONNECT_VERSION)
744                 seq_printf(m, "       target_version: %u.%u.%u.%u\n",
745                            OBD_OCD_VERSION_MAJOR(ocd->ocd_version),
746                            OBD_OCD_VERSION_MINOR(ocd->ocd_version),
747                            OBD_OCD_VERSION_PATCH(ocd->ocd_version),
748                            OBD_OCD_VERSION_FIX(ocd->ocd_version));
749         if (flags & OBD_CONNECT_MDS)
750                 seq_printf(m, "       mdt_index: %d\n", ocd->ocd_group);
751         if (flags & OBD_CONNECT_GRANT)
752                 seq_printf(m, "       initial_grant: %d\n", ocd->ocd_grant);
753         if (flags & OBD_CONNECT_INDEX)
754                 seq_printf(m, "       target_index: %u\n", ocd->ocd_index);
755         if (flags & OBD_CONNECT_BRW_SIZE)
756                 seq_printf(m, "       max_brw_size: %d\n", ocd->ocd_brw_size);
757         if (flags & OBD_CONNECT_IBITS)
758                 seq_printf(m, "       ibits_known: %#llx\n",
759                            ocd->ocd_ibits_known);
760         if (flags & OBD_CONNECT_GRANT_PARAM)
761                 seq_printf(m, "       grant_block_size: %d\n"
762                            "       grant_inode_size: %d\n"
763                            "       grant_max_extent_size: %d\n"
764                            "       grant_extent_tax: %d\n",
765                            1 << ocd->ocd_grant_blkbits,
766                            1 << ocd->ocd_grant_inobits,
767                            ocd->ocd_grant_max_blks << ocd->ocd_grant_blkbits,
768                            ocd->ocd_grant_tax_kb << 10);
769         if (flags & OBD_CONNECT_TRANSNO)
770                 seq_printf(m, "       first_transno: %#llx\n",
771                            ocd->ocd_transno);
772         if (flags & OBD_CONNECT_CKSUM)
773                 seq_printf(m, "       cksum_types: %#x\n",
774                            ocd->ocd_cksum_types);
775         if (flags & OBD_CONNECT_MAX_EASIZE)
776                 seq_printf(m, "       max_easize: %d\n", ocd->ocd_max_easize);
777         if (flags & OBD_CONNECT_MAXBYTES)
778                 seq_printf(m, "       max_object_bytes: %llu\n",
779                            ocd->ocd_maxbytes);
780         if (flags & OBD_CONNECT_MULTIMODRPCS)
781                 seq_printf(m, "       max_mod_rpcs: %hu\n",
782                            ocd->ocd_maxmodrpcs);
783 }
784
785 static void lprocfs_import_seq_show_locked(struct seq_file *m,
786                                            struct obd_device *obd,
787                                            struct obd_import *imp)
788 {
789         char nidstr[LNET_NIDSTR_SIZE];
790         struct lprocfs_counter ret;
791         struct lprocfs_counter_header *header;
792         struct obd_import_conn *conn;
793         struct obd_connect_data *ocd;
794         int j;
795         int k;
796         int rw = 0;
797
798         ocd = &imp->imp_connect_data;
799
800         seq_printf(m, "import:\n"
801                    "    name: %s\n"
802                    "    target: %s\n"
803                    "    state: %s\n"
804                    "    connect_flags: [ ",
805                    obd->obd_name,
806                    obd2cli_tgt(obd),
807                    ptlrpc_import_state_name(imp->imp_state));
808         obd_connect_seq_flags2str(m, imp->imp_connect_data.ocd_connect_flags,
809                                   imp->imp_connect_data.ocd_connect_flags2,
810                                   ", ");
811         seq_printf(m, " ]\n");
812         obd_connect_data_seqprint(m, ocd);
813         seq_printf(m, "    import_flags: [ ");
814         obd_import_flags2str(imp, m);
815
816         seq_printf(m, " ]\n"
817                    "    connection:\n"
818                    "       failover_nids: [ ");
819         spin_lock(&imp->imp_lock);
820         j = 0;
821         list_for_each_entry(conn, &imp->imp_conn_list, oic_item) {
822                 libcfs_nidstr_r(&conn->oic_conn->c_peer.nid,
823                                   nidstr, sizeof(nidstr));
824                 seq_printf(m, "%s%s", j ? ", " : "", nidstr);
825                 j++;
826         }
827         if (imp->imp_connection)
828                 libcfs_nidstr_r(&imp->imp_connection->c_peer.nid,
829                                   nidstr, sizeof(nidstr));
830         else
831                 strncpy(nidstr, "<none>", sizeof(nidstr));
832         seq_printf(m, " ]\n"
833                    "       current_connection: %s\n"
834                    "       connection_attempts: %u\n"
835                    "       generation: %u\n"
836                    "       in-progress_invalidations: %u\n"
837                    "       idle: %lld sec\n",
838                    nidstr,
839                    imp->imp_conn_cnt,
840                    imp->imp_generation,
841                    atomic_read(&imp->imp_inval_count),
842                    ktime_get_real_seconds() - imp->imp_last_reply_time);
843         spin_unlock(&imp->imp_lock);
844
845         if (!obd->obd_svc_stats)
846                 return;
847
848         header = &obd->obd_svc_stats->ls_cnt_header[PTLRPC_REQWAIT_CNTR];
849         lprocfs_stats_collect(obd->obd_svc_stats, PTLRPC_REQWAIT_CNTR, &ret);
850         if (ret.lc_count != 0)
851                 ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
852         else
853                 ret.lc_sum = 0;
854         seq_printf(m, "    rpcs:\n"
855                    "       inflight: %u\n"
856                    "       unregistering: %u\n"
857                    "       timeouts: %u\n"
858                    "       avg_waittime: %llu %s\n",
859                    atomic_read(&imp->imp_inflight),
860                    atomic_read(&imp->imp_unregistering),
861                    atomic_read(&imp->imp_timeouts),
862                    ret.lc_sum, header->lc_units);
863
864         k = 0;
865         for(j = 0; j < IMP_AT_MAX_PORTALS; j++) {
866                 if (imp->imp_at.iat_portal[j] == 0)
867                         break;
868                 k = max_t(unsigned int, k,
869                           at_get(&imp->imp_at.iat_service_estimate[j]));
870         }
871         seq_printf(m, "    service_estimates:\n"
872                    "       services: %u sec\n"
873                    "       network: %d sec\n",
874                    k,
875                    at_get(&imp->imp_at.iat_net_latency));
876
877         seq_printf(m, "    transactions:\n"
878                    "       last_replay: %llu\n"
879                    "       peer_committed: %llu\n"
880                    "       last_checked: %llu\n",
881                    imp->imp_last_replay_transno,
882                    imp->imp_peer_committed_transno,
883                    imp->imp_last_transno_checked);
884
885         /* avg data rates */
886         for (rw = 0; rw <= 1; rw++) {
887                 lprocfs_stats_collect(obd->obd_svc_stats,
888                                       PTLRPC_LAST_CNTR + BRW_READ_BYTES + rw,
889                                       &ret);
890                 if (ret.lc_sum > 0 && ret.lc_count > 0) {
891                         ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
892                         seq_printf(m, "    %s_data_averages:\n"
893                                    "       bytes_per_rpc: %llu\n",
894                                    rw ? "write" : "read",
895                                    ret.lc_sum);
896                 }
897                 k = (int)ret.lc_sum;
898                 j = opcode_offset(OST_READ + rw) + EXTRA_MAX_OPCODES;
899                 header = &obd->obd_svc_stats->ls_cnt_header[j];
900                 lprocfs_stats_collect(obd->obd_svc_stats, j, &ret);
901                 if (ret.lc_sum > 0 && ret.lc_count != 0) {
902                         ret.lc_sum = div64_s64(ret.lc_sum, ret.lc_count);
903                         seq_printf(m, "       %s_per_rpc: %llu\n",
904                                    header->lc_units, ret.lc_sum);
905                         j = (int)ret.lc_sum;
906                         if (j > 0)
907                                 seq_printf(m, "       MB_per_sec: %u.%.02u\n",
908                                            k / j, (100 * k / j) % 100);
909                 }
910         }
911 }
912
913 int lprocfs_import_seq_show(struct seq_file *m, void *data)
914 {
915         struct obd_device *obd = (struct obd_device *)data;
916         struct obd_import *imp;
917         int rv;
918
919         LASSERT(obd != NULL);
920         with_imp_locked(obd, imp, rv)
921                 lprocfs_import_seq_show_locked(m, obd, imp);
922         return rv;
923 }
924 EXPORT_SYMBOL(lprocfs_import_seq_show);
925
926 int lprocfs_state_seq_show(struct seq_file *m, void *data)
927 {
928         struct obd_device *obd = (struct obd_device *)data;
929         struct obd_import *imp;
930         int j, k;
931         int rc;
932
933         LASSERT(obd != NULL);
934         with_imp_locked(obd, imp, rc) {
935                 seq_printf(m, "current_state: %s\n",
936                            ptlrpc_import_state_name(imp->imp_state));
937                 seq_printf(m, "state_history:\n");
938                 k = imp->imp_state_hist_idx;
939                 for (j = 0; j < IMP_STATE_HIST_LEN; j++) {
940                         struct import_state_hist *ish =
941                                 &imp->imp_state_hist[(k + j) % IMP_STATE_HIST_LEN];
942                         if (ish->ish_state == 0)
943                                 continue;
944                         seq_printf(m, " - [ %lld, %s ]\n", (s64)ish->ish_time,
945                                    ptlrpc_import_state_name(ish->ish_state));
946                 }
947         }
948
949         return rc;
950 }
951 EXPORT_SYMBOL(lprocfs_state_seq_show);
952
953 int lprocfs_at_hist_helper(struct seq_file *m, struct adaptive_timeout *at)
954 {
955         int i;
956         for (i = 0; i < AT_BINS; i++)
957                 seq_printf(m, "%3u ", at->at_hist[i]);
958         seq_printf(m, "\n");
959         return 0;
960 }
961 EXPORT_SYMBOL(lprocfs_at_hist_helper);
962
963 /* See also ptlrpc_lprocfs_timeouts_show_seq */
964 static void lprocfs_timeouts_seq_show_locked(struct seq_file *m,
965                                              struct obd_device *obd,
966                                              struct obd_import *imp)
967 {
968         timeout_t cur_timeout, worst_timeout;
969         time64_t now, worst_timestamp;
970         int i;
971
972         LASSERT(obd != NULL);
973
974         now = ktime_get_real_seconds();
975
976         /* Some network health info for kicks */
977         seq_printf(m, "%-10s : %lld, %llds ago\n",
978                    "last reply", (s64)imp->imp_last_reply_time,
979                    (s64)(now - imp->imp_last_reply_time));
980
981         cur_timeout = at_get(&imp->imp_at.iat_net_latency);
982         worst_timeout = imp->imp_at.iat_net_latency.at_worst_timeout_ever;
983         worst_timestamp = imp->imp_at.iat_net_latency.at_worst_timestamp;
984         seq_printf(m, "%-10s : cur %3u  worst %3u (at %lld, %llds ago) ",
985                    "network", cur_timeout, worst_timeout, worst_timestamp,
986                    now - worst_timestamp);
987         lprocfs_at_hist_helper(m, &imp->imp_at.iat_net_latency);
988
989         for(i = 0; i < IMP_AT_MAX_PORTALS; i++) {
990                 struct adaptive_timeout *service_est;
991
992                 if (imp->imp_at.iat_portal[i] == 0)
993                         break;
994
995                 service_est = &imp->imp_at.iat_service_estimate[i];
996                 cur_timeout = at_get(service_est);
997                 worst_timeout = service_est->at_worst_timeout_ever;
998                 worst_timestamp = service_est->at_worst_timestamp;
999                 seq_printf(m, "portal %-2d  : cur %3u  worst %3u (at %lld, %llds ago) ",
1000                            imp->imp_at.iat_portal[i], cur_timeout,
1001                            worst_timeout, worst_timestamp,
1002                            now - worst_timestamp);
1003                 lprocfs_at_hist_helper(m, service_est);
1004         }
1005 }
1006
1007 int lprocfs_timeouts_seq_show(struct seq_file *m, void *data)
1008 {
1009         struct obd_device *obd = (struct obd_device *)data;
1010         struct obd_import *imp;
1011         int rc;
1012
1013         with_imp_locked(obd, imp, rc)
1014                 lprocfs_timeouts_seq_show_locked(m, obd, imp);
1015         return rc;
1016 }
1017 EXPORT_SYMBOL(lprocfs_timeouts_seq_show);
1018
1019 int lprocfs_connect_flags_seq_show(struct seq_file *m, void *data)
1020 {
1021         struct obd_device *obd = data;
1022         __u64 flags;
1023         __u64 flags2;
1024         struct obd_import *imp;
1025         int rc;
1026
1027         with_imp_locked(obd, imp, rc) {
1028                 flags = imp->imp_connect_data.ocd_connect_flags;
1029                 flags2 = imp->imp_connect_data.ocd_connect_flags2;
1030                 seq_printf(m, "flags=%#llx\n", flags);
1031                 seq_printf(m, "flags2=%#llx\n", flags2);
1032                 obd_connect_seq_flags2str(m, flags, flags2, "\n");
1033                 seq_printf(m, "\n");
1034         }
1035
1036         return rc;
1037 }
1038 EXPORT_SYMBOL(lprocfs_connect_flags_seq_show);
1039
1040 static const struct attribute *obd_def_uuid_attrs[] = {
1041         &lustre_attr_uuid.attr,
1042         NULL,
1043 };
1044
1045 static const struct attribute *obd_def_attrs[] = {
1046         &lustre_attr_blocksize.attr,
1047         &lustre_attr_kbytestotal.attr,
1048         &lustre_attr_kbytesfree.attr,
1049         &lustre_attr_kbytesavail.attr,
1050         &lustre_attr_filestotal.attr,
1051         &lustre_attr_filesfree.attr,
1052         &lustre_attr_uuid.attr,
1053         NULL,
1054 };
1055
1056 static void obd_sysfs_release(struct kobject *kobj)
1057 {
1058         struct obd_device *obd = container_of(kobj, struct obd_device,
1059                                               obd_kset.kobj);
1060
1061         complete(&obd->obd_kobj_unregister);
1062 }
1063
1064 int lprocfs_obd_setup(struct obd_device *obd, bool uuid_only)
1065 {
1066         struct ldebugfs_vars *debugfs_vars = NULL;
1067         int rc;
1068
1069         if (!obd || obd->obd_magic != OBD_DEVICE_MAGIC)
1070                 return -ENODEV;
1071
1072         rc = kobject_set_name(&obd->obd_kset.kobj, "%s", obd->obd_name);
1073         if (rc)
1074                 return rc;
1075
1076         obd->obd_ktype.sysfs_ops = &lustre_sysfs_ops;
1077         obd->obd_ktype.release = obd_sysfs_release;
1078
1079         obd->obd_kset.kobj.parent = &obd->obd_type->typ_kobj;
1080         obd->obd_kset.kobj.ktype = &obd->obd_ktype;
1081         init_completion(&obd->obd_kobj_unregister);
1082         rc = kset_register(&obd->obd_kset);
1083         if (rc)
1084                 return rc;
1085
1086         if (uuid_only)
1087                 obd->obd_attrs = obd_def_uuid_attrs;
1088         else
1089                 obd->obd_attrs = obd_def_attrs;
1090
1091         rc = sysfs_create_files(&obd->obd_kset.kobj, obd->obd_attrs);
1092         if (rc) {
1093                 kset_unregister(&obd->obd_kset);
1094                 return rc;
1095         }
1096
1097         if (!obd->obd_type->typ_procroot)
1098                 debugfs_vars = obd->obd_debugfs_vars;
1099         obd->obd_debugfs_entry = debugfs_create_dir(
1100                 obd->obd_name, obd->obd_type->typ_debugfs_entry);
1101         ldebugfs_add_vars(obd->obd_debugfs_entry, debugfs_vars, obd);
1102
1103         if (obd->obd_proc_entry || !obd->obd_type->typ_procroot)
1104                 GOTO(already_registered, rc);
1105
1106         obd->obd_proc_entry = lprocfs_register(obd->obd_name,
1107                                                obd->obd_type->typ_procroot,
1108                                                obd->obd_vars, obd);
1109         if (IS_ERR(obd->obd_proc_entry)) {
1110                 rc = PTR_ERR(obd->obd_proc_entry);
1111                 CERROR("error %d setting up lprocfs for %s\n",rc,obd->obd_name);
1112                 obd->obd_proc_entry = NULL;
1113
1114                 debugfs_remove_recursive(obd->obd_debugfs_entry);
1115                 obd->obd_debugfs_entry = NULL;
1116
1117                 sysfs_remove_files(&obd->obd_kset.kobj, obd->obd_attrs);
1118                 obd->obd_attrs = NULL;
1119                 kset_unregister(&obd->obd_kset);
1120                 return rc;
1121         }
1122 already_registered:
1123         return rc;
1124 }
1125 EXPORT_SYMBOL(lprocfs_obd_setup);
1126
1127 int lprocfs_obd_cleanup(struct obd_device *obd)
1128 {
1129         if (!obd)
1130                 return -EINVAL;
1131
1132         if (obd->obd_proc_exports_entry) {
1133                 /* Should be no exports left */
1134                 lprocfs_remove(&obd->obd_proc_exports_entry);
1135                 obd->obd_proc_exports_entry = NULL;
1136         }
1137
1138         if (obd->obd_proc_entry) {
1139                 lprocfs_remove(&obd->obd_proc_entry);
1140                 obd->obd_proc_entry = NULL;
1141         }
1142
1143         debugfs_remove_recursive(obd->obd_debugfs_entry);
1144         obd->obd_debugfs_entry = NULL;
1145
1146         /* obd device never allocated a kset */
1147         if (!obd->obd_kset.kobj.state_initialized)
1148                 return 0;
1149
1150         if (obd->obd_attrs) {
1151                 sysfs_remove_files(&obd->obd_kset.kobj, obd->obd_attrs);
1152                 obd->obd_attrs = NULL;
1153         }
1154
1155         kset_unregister(&obd->obd_kset);
1156         wait_for_completion(&obd->obd_kobj_unregister);
1157         return 0;
1158 }
1159 EXPORT_SYMBOL(lprocfs_obd_cleanup);
1160
1161 int lprocfs_stats_alloc_one(struct lprocfs_stats *stats, unsigned int cpuid)
1162 {
1163         struct lprocfs_counter *cntr;
1164         unsigned int percpusize;
1165         int rc = -ENOMEM;
1166         unsigned long flags = 0;
1167         int i;
1168
1169         LASSERT(stats->ls_percpu[cpuid] == NULL);
1170         LASSERT((stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU) == 0);
1171
1172         percpusize = lprocfs_stats_counter_size(stats);
1173         LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[cpuid], percpusize);
1174         if (stats->ls_percpu[cpuid]) {
1175                 rc = 0;
1176                 if (unlikely(stats->ls_biggest_alloc_num <= cpuid)) {
1177                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1178                                 spin_lock_irqsave(&stats->ls_lock, flags);
1179                         else
1180                                 spin_lock(&stats->ls_lock);
1181                         if (stats->ls_biggest_alloc_num <= cpuid)
1182                                 stats->ls_biggest_alloc_num = cpuid + 1;
1183                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) {
1184                                 spin_unlock_irqrestore(&stats->ls_lock, flags);
1185                         } else {
1186                                 spin_unlock(&stats->ls_lock);
1187                         }
1188                 }
1189                 /* initialize the ls_percpu[cpuid] non-zero counter */
1190                 for (i = 0; i < stats->ls_num; ++i) {
1191                         cntr = lprocfs_stats_counter_get(stats, cpuid, i);
1192                         cntr->lc_min = LC_MIN_INIT;
1193                 }
1194         }
1195         return rc;
1196 }
1197
1198 struct lprocfs_stats *lprocfs_alloc_stats(unsigned int num,
1199                                           enum lprocfs_stats_flags flags)
1200 {
1201         struct lprocfs_stats *stats;
1202         unsigned int num_entry;
1203         unsigned int percpusize = 0;
1204         int i;
1205
1206         if (num == 0)
1207                 return NULL;
1208
1209         if (lprocfs_no_percpu_stats != 0)
1210                 flags |= LPROCFS_STATS_FLAG_NOPERCPU;
1211
1212         if (flags & LPROCFS_STATS_FLAG_NOPERCPU)
1213                 num_entry = 1;
1214         else
1215                 num_entry = num_possible_cpus();
1216
1217         /* alloc percpu pointers for all possible cpu slots */
1218         LIBCFS_ALLOC(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1219         if (!stats)
1220                 return NULL;
1221
1222         stats->ls_num = num;
1223         stats->ls_flags = flags;
1224         spin_lock_init(&stats->ls_lock);
1225
1226         /* alloc num of counter headers */
1227         CFS_ALLOC_PTR_ARRAY(stats->ls_cnt_header, stats->ls_num);
1228         if (!stats->ls_cnt_header)
1229                 goto fail;
1230
1231         if ((flags & LPROCFS_STATS_FLAG_NOPERCPU) != 0) {
1232                 /* contains only one set counters */
1233                 percpusize = lprocfs_stats_counter_size(stats);
1234                 LIBCFS_ALLOC_ATOMIC(stats->ls_percpu[0], percpusize);
1235                 if (!stats->ls_percpu[0])
1236                         goto fail;
1237                 stats->ls_biggest_alloc_num = 1;
1238         } else if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0) {
1239                 /* alloc all percpu data, currently only obd_memory use this */
1240                 for (i = 0; i < num_entry; ++i)
1241                         if (lprocfs_stats_alloc_one(stats, i) < 0)
1242                                 goto fail;
1243         }
1244
1245         return stats;
1246
1247 fail:
1248         lprocfs_free_stats(&stats);
1249         return NULL;
1250 }
1251 EXPORT_SYMBOL(lprocfs_alloc_stats);
1252
1253 void lprocfs_free_stats(struct lprocfs_stats **statsh)
1254 {
1255         struct lprocfs_stats *stats = *statsh;
1256         unsigned int num_entry;
1257         unsigned int percpusize;
1258         unsigned int i;
1259
1260         if (!stats || stats->ls_num == 0)
1261                 return;
1262         *statsh = NULL;
1263
1264         if (stats->ls_flags & LPROCFS_STATS_FLAG_NOPERCPU)
1265                 num_entry = 1;
1266         else
1267                 num_entry = num_possible_cpus();
1268
1269         percpusize = lprocfs_stats_counter_size(stats);
1270         for (i = 0; i < num_entry; i++)
1271                 if (stats->ls_percpu[i])
1272                         LIBCFS_FREE(stats->ls_percpu[i], percpusize);
1273         if (stats->ls_cnt_header)
1274                 CFS_FREE_PTR_ARRAY(stats->ls_cnt_header, stats->ls_num);
1275         LIBCFS_FREE(stats, offsetof(typeof(*stats), ls_percpu[num_entry]));
1276 }
1277 EXPORT_SYMBOL(lprocfs_free_stats);
1278
1279 u64 lprocfs_stats_collector(struct lprocfs_stats *stats, int idx,
1280                             enum lprocfs_fields_flags field)
1281 {
1282         unsigned long flags = 0;
1283         unsigned int num_cpu;
1284         unsigned int i;
1285         u64 ret = 0;
1286
1287         LASSERT(stats);
1288
1289         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1290         for (i = 0; i < num_cpu; i++) {
1291                 struct lprocfs_counter *cntr;
1292
1293                 if (!stats->ls_percpu[i])
1294                         continue;
1295
1296                 cntr = lprocfs_stats_counter_get(stats, i, idx);
1297                 ret += lprocfs_read_helper(cntr, &stats->ls_cnt_header[idx],
1298                                            stats->ls_flags, field);
1299         }
1300         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1301         return ret;
1302 }
1303 EXPORT_SYMBOL(lprocfs_stats_collector);
1304
1305 void lprocfs_clear_stats(struct lprocfs_stats *stats)
1306 {
1307         struct lprocfs_counter *percpu_cntr;
1308         int i;
1309         int j;
1310         unsigned int num_entry;
1311         unsigned long flags = 0;
1312
1313         num_entry = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1314
1315         for (i = 0; i < num_entry; i++) {
1316                 if (!stats->ls_percpu[i])
1317                         continue;
1318                 for (j = 0; j < stats->ls_num; j++) {
1319                         percpu_cntr = lprocfs_stats_counter_get(stats, i, j);
1320                         percpu_cntr->lc_count           = 0;
1321                         percpu_cntr->lc_min             = LC_MIN_INIT;
1322                         percpu_cntr->lc_max             = 0;
1323                         percpu_cntr->lc_sumsquare       = 0;
1324                         percpu_cntr->lc_sum             = 0;
1325                         if (stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE)
1326                                 percpu_cntr->lc_sum_irq = 0;
1327                 }
1328         }
1329
1330         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1331 }
1332 EXPORT_SYMBOL(lprocfs_clear_stats);
1333
1334 static ssize_t lprocfs_stats_seq_write(struct file *file,
1335                                        const char __user *buf,
1336                                        size_t len, loff_t *off)
1337 {
1338         struct seq_file *seq = file->private_data;
1339         struct lprocfs_stats *stats = seq->private;
1340
1341         lprocfs_clear_stats(stats);
1342
1343         return len;
1344 }
1345
1346 static void *lprocfs_stats_seq_start(struct seq_file *p, loff_t *pos)
1347 {
1348         struct lprocfs_stats *stats = p->private;
1349
1350         return (*pos < stats->ls_num) ? pos : NULL;
1351 }
1352
1353 static void lprocfs_stats_seq_stop(struct seq_file *p, void *v)
1354 {
1355 }
1356
1357 static void *lprocfs_stats_seq_next(struct seq_file *p, void *v, loff_t *pos)
1358 {
1359         (*pos)++;
1360
1361         return lprocfs_stats_seq_start(p, pos);
1362 }
1363
1364 void lprocfs_stats_header(struct seq_file *seq, ktime_t now, ktime_t ts_init,
1365                           int width, const char *colon, bool show_units)
1366 {
1367         const char *units = show_units ? " secs.nsecs" : "";
1368         struct timespec64 ts;
1369
1370         ts = ktime_to_timespec64(now);
1371         seq_printf(seq, "%-*s%s %llu.%09lu%s\n", width,
1372                    "snapshot_time", colon, (s64)ts.tv_sec, ts.tv_nsec, units);
1373         ts = ktime_to_timespec64(ts_init);
1374         seq_printf(seq, "%-*s%s %llu.%09lu%s\n", width,
1375                    "start_time", colon, (s64)ts.tv_sec, ts.tv_nsec, units);
1376         ts = ktime_to_timespec64(ktime_sub(now, ts_init));
1377         seq_printf(seq, "%-*s%s %llu.%09lu%s\n", width,
1378                    "elapsed_time", colon, (s64)ts.tv_sec, ts.tv_nsec, units);
1379 }
1380 EXPORT_SYMBOL(lprocfs_stats_header);
1381
1382 /* seq file export of one lprocfs counter */
1383 static int lprocfs_stats_seq_show(struct seq_file *p, void *v)
1384 {
1385         struct lprocfs_stats *stats = p->private;
1386         struct lprocfs_counter_header *hdr;
1387         struct lprocfs_counter ctr;
1388         int idx = *(loff_t *)v;
1389
1390         if (idx == 0)
1391                 lprocfs_stats_header(p, ktime_get(), stats->ls_init, 25, "", 1);
1392
1393         hdr = &stats->ls_cnt_header[idx];
1394         lprocfs_stats_collect(stats, idx, &ctr);
1395
1396         if (ctr.lc_count == 0)
1397                 return 0;
1398
1399         seq_printf(p, "%-25s %lld samples [%s]", hdr->lc_name,
1400                    ctr.lc_count, hdr->lc_units);
1401
1402         if ((hdr->lc_config & LPROCFS_CNTR_AVGMINMAX) && ctr.lc_count > 0) {
1403                 seq_printf(p, " %lld %lld %lld",
1404                            ctr.lc_min, ctr.lc_max, ctr.lc_sum);
1405                 if (hdr->lc_config & LPROCFS_CNTR_STDDEV)
1406                         seq_printf(p, " %llu", ctr.lc_sumsquare);
1407         }
1408         seq_putc(p, '\n');
1409         return 0;
1410 }
1411
1412 static const struct seq_operations lprocfs_stats_seq_sops = {
1413         .start  = lprocfs_stats_seq_start,
1414         .stop   = lprocfs_stats_seq_stop,
1415         .next   = lprocfs_stats_seq_next,
1416         .show   = lprocfs_stats_seq_show,
1417 };
1418
1419 static int lprocfs_stats_seq_open(struct inode *inode, struct file *file)
1420 {
1421         struct seq_file *seq;
1422         int rc;
1423
1424         rc = seq_open(file, &lprocfs_stats_seq_sops);
1425         if (rc)
1426                 return rc;
1427         seq = file->private_data;
1428         seq->private = inode->i_private ? inode->i_private : PDE_DATA(inode);
1429         return 0;
1430 }
1431
1432 const struct file_operations ldebugfs_stats_seq_fops = {
1433         .owner   = THIS_MODULE,
1434         .open    = lprocfs_stats_seq_open,
1435         .read    = seq_read,
1436         .write   = lprocfs_stats_seq_write,
1437         .llseek  = seq_lseek,
1438         .release = lprocfs_seq_release,
1439 };
1440 EXPORT_SYMBOL(ldebugfs_stats_seq_fops);
1441
1442 static const struct proc_ops lprocfs_stats_seq_fops = {
1443         PROC_OWNER(THIS_MODULE)
1444         .proc_open      = lprocfs_stats_seq_open,
1445         .proc_read      = seq_read,
1446         .proc_write     = lprocfs_stats_seq_write,
1447         .proc_lseek     = seq_lseek,
1448         .proc_release   = lprocfs_seq_release,
1449 };
1450
1451 int lprocfs_register_stats(struct proc_dir_entry *root, const char *name,
1452                            struct lprocfs_stats *stats)
1453 {
1454         struct proc_dir_entry *entry;
1455         LASSERT(root != NULL);
1456
1457         entry = proc_create_data(name, 0644, root,
1458                                  &lprocfs_stats_seq_fops, stats);
1459         if (!entry)
1460                 return -ENOMEM;
1461         return 0;
1462 }
1463 EXPORT_SYMBOL(lprocfs_register_stats);
1464
1465 static const char *lprocfs_counter_config_units(const char *name,
1466                                          enum lprocfs_counter_config config)
1467 {
1468         const char *units;
1469
1470         switch (config & LPROCFS_TYPE_MASK) {
1471         default:
1472                 units = "reqs"; break;
1473         case LPROCFS_TYPE_BYTES:
1474                 units = "bytes"; break;
1475         case LPROCFS_TYPE_PAGES:
1476                 units = "pages"; break;
1477         case LPROCFS_TYPE_LOCKS:
1478                 units = "locks"; break;
1479         case LPROCFS_TYPE_LOCKSPS:
1480                 units = "locks/s"; break;
1481         case LPROCFS_TYPE_SECS:
1482                 units = "secs"; break;
1483         case LPROCFS_TYPE_USECS:
1484                 units = "usecs"; break;
1485         }
1486
1487         return units;
1488 }
1489
1490 void lprocfs_counter_init_units(struct lprocfs_stats *stats, int index,
1491                                 enum lprocfs_counter_config config,
1492                                 const char *name, const char *units)
1493 {
1494         struct lprocfs_counter_header *header;
1495         struct lprocfs_counter *percpu_cntr;
1496         unsigned long flags = 0;
1497         unsigned int i;
1498         unsigned int num_cpu;
1499
1500         LASSERT(stats != NULL);
1501
1502         header = &stats->ls_cnt_header[index];
1503         LASSERTF(header != NULL, "Failed to allocate stats header:[%d]%s/%s\n",
1504                  index, name, units);
1505
1506         header->lc_config = config;
1507         header->lc_name = name;
1508         header->lc_units = units;
1509
1510         num_cpu = lprocfs_stats_lock(stats, LPROCFS_GET_NUM_CPU, &flags);
1511         for (i = 0; i < num_cpu; ++i) {
1512                 if (!stats->ls_percpu[i])
1513                         continue;
1514                 percpu_cntr = lprocfs_stats_counter_get(stats, i, index);
1515                 percpu_cntr->lc_count           = 0;
1516                 percpu_cntr->lc_min             = LC_MIN_INIT;
1517                 percpu_cntr->lc_max             = 0;
1518                 percpu_cntr->lc_sumsquare       = 0;
1519                 percpu_cntr->lc_sum             = 0;
1520                 if ((stats->ls_flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1521                         percpu_cntr->lc_sum_irq = 0;
1522         }
1523         lprocfs_stats_unlock(stats, LPROCFS_GET_NUM_CPU, &flags);
1524 }
1525 EXPORT_SYMBOL(lprocfs_counter_init_units);
1526
1527 void lprocfs_counter_init(struct lprocfs_stats *stats, int index,
1528                           enum lprocfs_counter_config config,
1529                           const char *name)
1530 {
1531         lprocfs_counter_init_units(stats, index, config, name,
1532                                    lprocfs_counter_config_units(name, config));
1533 }
1534 EXPORT_SYMBOL(lprocfs_counter_init);
1535
1536 static const char * const mps_stats[] = {
1537         [LPROC_MD_CLOSE]                = "close",
1538         [LPROC_MD_CREATE]               = "create",
1539         [LPROC_MD_ENQUEUE]              = "enqueue",
1540         [LPROC_MD_GETATTR]              = "getattr",
1541         [LPROC_MD_INTENT_LOCK]          = "intent_lock",
1542         [LPROC_MD_LINK]                 = "link",
1543         [LPROC_MD_RENAME]               = "rename",
1544         [LPROC_MD_SETATTR]              = "setattr",
1545         [LPROC_MD_FSYNC]                = "fsync",
1546         [LPROC_MD_READ_PAGE]            = "read_page",
1547         [LPROC_MD_UNLINK]               = "unlink",
1548         [LPROC_MD_SETXATTR]             = "setxattr",
1549         [LPROC_MD_GETXATTR]             = "getxattr",
1550         [LPROC_MD_INTENT_GETATTR_ASYNC] = "intent_getattr_async",
1551         [LPROC_MD_REVALIDATE_LOCK]      = "revalidate_lock",
1552 };
1553
1554 int lprocfs_alloc_md_stats(struct obd_device *obd,
1555                            unsigned int num_private_stats)
1556 {
1557         struct lprocfs_stats *stats;
1558         unsigned int num_stats;
1559         int rc, i;
1560
1561         /*
1562          * TODO Ensure that this function is only used where
1563          * appropriate by adding an assertion to the effect that
1564          * obd->obd_type->typ_md_ops is not NULL. We can't do this now
1565          * because mdt_procfs_init() uses this function to allocate
1566          * the stats backing /proc/fs/lustre/mdt/.../md_stats but the
1567          * mdt layer does not use the md_ops interface. This is
1568          * confusing and a waste of memory. See LU-2484.
1569          */
1570         LASSERT(obd->obd_proc_entry != NULL);
1571         LASSERT(obd->obd_md_stats == NULL);
1572
1573         num_stats = ARRAY_SIZE(mps_stats) + num_private_stats;
1574         stats = lprocfs_alloc_stats(num_stats, 0);
1575         if (!stats)
1576                 return -ENOMEM;
1577
1578         for (i = 0; i < ARRAY_SIZE(mps_stats); i++) {
1579                 lprocfs_counter_init(stats, i, LPROCFS_TYPE_REQS,
1580                                      mps_stats[i]);
1581                 if (!stats->ls_cnt_header[i].lc_name) {
1582                         CERROR("Missing md_stat initializer md_op operation at offset %d. Aborting.\n",
1583                                i);
1584                         LBUG();
1585                 }
1586         }
1587
1588         rc = lprocfs_register_stats(obd->obd_proc_entry, "md_stats", stats);
1589         if (rc < 0) {
1590                 lprocfs_free_stats(&stats);
1591         } else {
1592                 obd->obd_md_stats = stats;
1593         }
1594
1595         return rc;
1596 }
1597 EXPORT_SYMBOL(lprocfs_alloc_md_stats);
1598
1599 void lprocfs_free_md_stats(struct obd_device *obd)
1600 {
1601         struct lprocfs_stats *stats = obd->obd_md_stats;
1602
1603         if (stats) {
1604                 obd->obd_md_stats = NULL;
1605                 lprocfs_free_stats(&stats);
1606         }
1607 }
1608 EXPORT_SYMBOL(lprocfs_free_md_stats);
1609
1610 void lprocfs_init_ldlm_stats(struct lprocfs_stats *ldlm_stats)
1611 {
1612         lprocfs_counter_init(ldlm_stats, LDLM_ENQUEUE - LDLM_FIRST_OPC,
1613                              LPROCFS_TYPE_REQS, "ldlm_enqueue");
1614         lprocfs_counter_init(ldlm_stats, LDLM_CONVERT - LDLM_FIRST_OPC,
1615                              LPROCFS_TYPE_REQS, "ldlm_convert");
1616         lprocfs_counter_init(ldlm_stats, LDLM_CANCEL - LDLM_FIRST_OPC,
1617                              LPROCFS_TYPE_REQS, "ldlm_cancel");
1618         lprocfs_counter_init(ldlm_stats, LDLM_BL_CALLBACK - LDLM_FIRST_OPC,
1619                              LPROCFS_TYPE_REQS, "ldlm_bl_callback");
1620         lprocfs_counter_init(ldlm_stats, LDLM_CP_CALLBACK - LDLM_FIRST_OPC,
1621                              LPROCFS_TYPE_REQS, "ldlm_cp_callback");
1622         lprocfs_counter_init(ldlm_stats, LDLM_GL_CALLBACK - LDLM_FIRST_OPC,
1623                              LPROCFS_TYPE_REQS, "ldlm_gl_callback");
1624 }
1625 EXPORT_SYMBOL(lprocfs_init_ldlm_stats);
1626
1627 __s64 lprocfs_read_helper(struct lprocfs_counter *lc,
1628                           struct lprocfs_counter_header *header,
1629                           enum lprocfs_stats_flags flags,
1630                           enum lprocfs_fields_flags field)
1631 {
1632         __s64 ret = 0;
1633
1634         if (!lc || !header)
1635                 RETURN(0);
1636
1637         switch (field) {
1638                 case LPROCFS_FIELDS_FLAGS_CONFIG:
1639                         ret = header->lc_config;
1640                         break;
1641                 case LPROCFS_FIELDS_FLAGS_SUM:
1642                         ret = lc->lc_sum;
1643                         if ((flags & LPROCFS_STATS_FLAG_IRQ_SAFE) != 0)
1644                                 ret += lc->lc_sum_irq;
1645                         break;
1646                 case LPROCFS_FIELDS_FLAGS_MIN:
1647                         ret = lc->lc_min;
1648                         break;
1649                 case LPROCFS_FIELDS_FLAGS_MAX:
1650                         ret = lc->lc_max;
1651                         break;
1652                 case LPROCFS_FIELDS_FLAGS_AVG:
1653                         ret = div64_u64((flags & LPROCFS_STATS_FLAG_IRQ_SAFE ?
1654                                          lc->lc_sum_irq : 0) + lc->lc_sum,
1655                                         lc->lc_count);
1656                         break;
1657                 case LPROCFS_FIELDS_FLAGS_SUMSQUARE:
1658                         ret = lc->lc_sumsquare;
1659                         break;
1660                 case LPROCFS_FIELDS_FLAGS_COUNT:
1661                         ret = lc->lc_count;
1662                         break;
1663                 default:
1664                         break;
1665         };
1666         RETURN(ret);
1667 }
1668 EXPORT_SYMBOL(lprocfs_read_helper);
1669
1670 /**
1671  * string_to_size - convert ASCII string representing a numerical
1672  *                  value with optional units to 64-bit binary value
1673  *
1674  * @size:       The numerical value extract out of @buffer
1675  * @buffer:     passed in string to parse
1676  * @count:      length of the @buffer
1677  *
1678  * This function returns a 64-bit binary value if @buffer contains a valid
1679  * numerical string. The string is parsed to 3 significant figures after
1680  * the decimal point. Support the string containing an optional units at
1681  * the end which can be base 2 or base 10 in value. If no units are given
1682  * the string is assumed to just a numerical value.
1683  *
1684  * Returns:     @count if the string is successfully parsed,
1685  *              -errno on invalid input strings. Error values:
1686  *
1687  *  - ``-EINVAL``: @buffer is not a proper numerical string
1688  *  - ``-EOVERFLOW``: results does not fit into 64 bits.
1689  *  - ``-E2BIG ``: @buffer is too large (not a valid number)
1690  */
1691 int string_to_size(u64 *size, const char *buffer, size_t count)
1692 {
1693         /* For string_get_size() it can support values above exabytes,
1694          * (ZiB, YiB) due to breaking the return value into a size and
1695          * bulk size to avoid 64 bit overflow. We don't break the size
1696          * up into block size units so we don't support ZiB or YiB.
1697          */
1698         static const char *const units_10[] = {
1699                 "kB", "MB", "GB", "TB", "PB", "EB",
1700         };
1701         static const char *const units_2[] = {
1702                 "K",  "M",  "G",  "T",  "P",  "E",
1703         };
1704         static const char *const *const units_str[] = {
1705                 [STRING_UNITS_2] = units_2,
1706                 [STRING_UNITS_10] = units_10,
1707         };
1708         static const unsigned int coeff[] = {
1709                 [STRING_UNITS_10] = 1000,
1710                 [STRING_UNITS_2] = 1024,
1711         };
1712         enum string_size_units unit = STRING_UNITS_2;
1713         u64 whole, blk_size = 1;
1714         char kernbuf[22], *end;
1715         size_t len = count;
1716         int rc;
1717         int i;
1718
1719         if (count >= sizeof(kernbuf)) {
1720                 CERROR("count %zd > buffer %zd\n", count, sizeof(kernbuf));
1721                 return -E2BIG;
1722         }
1723
1724         *size = 0;
1725         /* The "iB" suffix is optionally allowed for indicating base-2 numbers.
1726          * If suffix is only "B" and not "iB" then we treat it as base-10.
1727          */
1728         end = strstr(buffer, "B");
1729         if (end && *(end - 1) != 'i')
1730                 unit = STRING_UNITS_10;
1731
1732         i = unit == STRING_UNITS_2 ? ARRAY_SIZE(units_2) - 1 :
1733                                      ARRAY_SIZE(units_10) - 1;
1734         do {
1735                 end = strnstr(buffer, units_str[unit][i], count);
1736                 if (end) {
1737                         for (; i >= 0; i--)
1738                                 blk_size *= coeff[unit];
1739                         len = end - buffer;
1740                         break;
1741                 }
1742         } while (i--);
1743
1744         /* as 'B' is a substring of all units, we need to handle it
1745          * separately.
1746          */
1747         if (!end) {
1748                 /* 'B' is only acceptable letter at this point */
1749                 end = strnchr(buffer, count, 'B');
1750                 if (end) {
1751                         len = end - buffer;
1752
1753                         if (count - len > 2 ||
1754                             (count - len == 2 && strcmp(end, "B\n") != 0)) {
1755                                 CDEBUG(D_INFO, "unknown suffix '%s'\n", buffer);
1756                                 return -EINVAL;
1757                         }
1758                 }
1759                 /* kstrtoull will error out if it has non digits */
1760                 goto numbers_only;
1761         }
1762
1763         end = strnchr(buffer, count, '.');
1764         if (end) {
1765                 /* need to limit 3 decimal places */
1766                 char rem[4] = "000";
1767                 u64 frac = 0;
1768                 size_t off;
1769
1770                 len = end - buffer;
1771                 end++;
1772
1773                 /* limit to 3 decimal points */
1774                 off = min_t(size_t, 3, strspn(end, "0123456789"));
1775                 /* need to limit frac_d to a u32 */
1776                 memcpy(rem, end, off);
1777                 rc = kstrtoull(rem, 10, &frac);
1778                 if (rc)
1779                         return rc;
1780
1781                 if (fls64(frac) + fls64(blk_size) - 1 > 64)
1782                         return -EOVERFLOW;
1783
1784                 frac *= blk_size;
1785                 do_div(frac, 1000);
1786                 *size += frac;
1787         }
1788 numbers_only:
1789         snprintf(kernbuf, sizeof(kernbuf), "%.*s", (int)len, buffer);
1790         rc = kstrtoull(kernbuf, 10, &whole);
1791         if (rc)
1792                 return rc;
1793
1794         if (whole != 0 && fls64(whole) + fls64(blk_size) - 1 > 64)
1795                 return -EOVERFLOW;
1796
1797         *size += whole * blk_size;
1798
1799         return count;
1800 }
1801 EXPORT_SYMBOL(string_to_size);
1802
1803 /**
1804  * sysfs_memparse - parse a ASCII string to 64-bit binary value,
1805  *                  with optional units
1806  *
1807  * @buffer:     kernel pointer to input string
1808  * @count:      number of bytes in the input @buffer
1809  * @val:        (output) binary value returned to caller
1810  * @defunit:    default unit suffix to use if none is provided
1811  *
1812  * Parses a string into a number. The number stored at @buffer is
1813  * potentially suffixed with K, M, G, T, P, E. Besides these other
1814  * valid suffix units are shown in the string_to_size() function.
1815  * If the string lacks a suffix then the defunit is used. The defunit
1816  * should be given as a binary unit (e.g. MiB) as that is the standard
1817  * for tunables in Lustre. If no unit suffix is given (e.g. 'G'), then
1818  * it is assumed to be in binary units.
1819  *
1820  * Returns:     0 on success or -errno on failure.
1821  */
1822 int sysfs_memparse(const char *buffer, size_t count, u64 *val,
1823                    const char *defunit)
1824 {
1825         const char *param = buffer;
1826         char tmp_buf[23];
1827         int rc;
1828
1829         count = strlen(buffer);
1830         while (count > 0 && isspace(buffer[count - 1]))
1831                 count--;
1832
1833         if (!count)
1834                 RETURN(-EINVAL);
1835
1836         /* If there isn't already a unit on this value, append @defunit.
1837          * Units of 'B' don't affect the value, so don't bother adding.
1838          */
1839         if (!isalpha(buffer[count - 1]) && defunit[0] != 'B') {
1840                 if (count + 3 >= sizeof(tmp_buf)) {
1841                         CERROR("count %zd > size %zd\n", count, sizeof(param));
1842                         RETURN(-E2BIG);
1843                 }
1844
1845                 scnprintf(tmp_buf, sizeof(tmp_buf), "%.*s%s", (int)count,
1846                           buffer, defunit);
1847                 param = tmp_buf;
1848                 count = strlen(param);
1849         }
1850
1851         rc = string_to_size(val, param, count);
1852
1853         return rc < 0 ? rc : 0;
1854 }
1855 EXPORT_SYMBOL(sysfs_memparse);
1856
1857 char *lprocfs_strnstr(const char *s1, const char *s2, size_t len)
1858 {
1859         size_t l2;
1860
1861         l2 = strlen(s2);
1862         if (!l2)
1863                 return (char *)s1;
1864         while (len >= l2) {
1865                 len--;
1866                 if (!memcmp(s1, s2, l2))
1867                         return (char *)s1;
1868                 s1++;
1869         }
1870         return NULL;
1871 }
1872 EXPORT_SYMBOL(lprocfs_strnstr);
1873
1874 /**
1875  * Find the string \a name in the input \a buffer, and return a pointer to the
1876  * value immediately following \a name, reducing \a count appropriately.
1877  * If \a name is not found the original \a buffer is returned.
1878  */
1879 char *lprocfs_find_named_value(const char *buffer, const char *name,
1880                                 size_t *count)
1881 {
1882         char *val;
1883         size_t buflen = *count;
1884
1885         /* there is no strnstr() in rhel5 and ubuntu kernels */
1886         val = lprocfs_strnstr(buffer, name, buflen);
1887         if (!val)
1888                 return (char *)buffer;
1889
1890         val += strlen(name);                             /* skip prefix */
1891         while (val < buffer + buflen && isspace(*val)) /* skip separator */
1892                 val++;
1893
1894         *count = 0;
1895         while (val < buffer + buflen && isalnum(*val)) {
1896                 ++*count;
1897                 ++val;
1898         }
1899
1900         return val - *count;
1901 }
1902 EXPORT_SYMBOL(lprocfs_find_named_value);
1903
1904 int lprocfs_seq_create(struct proc_dir_entry *parent,
1905                        const char *name,
1906                        mode_t mode,
1907                        const struct proc_ops *seq_fops,
1908                        void *data)
1909 {
1910         struct proc_dir_entry *entry;
1911         ENTRY;
1912
1913         /* Disallow secretly (un)writable entries. */
1914         LASSERT(!seq_fops->proc_write == !(mode & 0222));
1915
1916         entry = proc_create_data(name, mode, parent, seq_fops, data);
1917
1918         if (!entry)
1919                 RETURN(-ENOMEM);
1920
1921         RETURN(0);
1922 }
1923 EXPORT_SYMBOL(lprocfs_seq_create);
1924
1925 int lprocfs_obd_seq_create(struct obd_device *obd,
1926                            const char *name,
1927                            mode_t mode,
1928                            const struct proc_ops *seq_fops,
1929                            void *data)
1930 {
1931         return lprocfs_seq_create(obd->obd_proc_entry, name,
1932                                   mode, seq_fops, data);
1933 }
1934 EXPORT_SYMBOL(lprocfs_obd_seq_create);
1935
1936 void lprocfs_oh_tally(struct obd_histogram *oh, unsigned int value)
1937 {
1938         if (value >= OBD_HIST_MAX)
1939                 value = OBD_HIST_MAX - 1;
1940
1941         spin_lock(&oh->oh_lock);
1942         oh->oh_buckets[value]++;
1943         spin_unlock(&oh->oh_lock);
1944 }
1945 EXPORT_SYMBOL(lprocfs_oh_tally);
1946
1947 void lprocfs_oh_tally_log2(struct obd_histogram *oh, unsigned int value)
1948 {
1949         unsigned int val = 0;
1950
1951         if (likely(value != 0))
1952                 val = min(fls(value - 1), OBD_HIST_MAX);
1953
1954         lprocfs_oh_tally(oh, val);
1955 }
1956 EXPORT_SYMBOL(lprocfs_oh_tally_log2);
1957
1958 unsigned long lprocfs_oh_sum(struct obd_histogram *oh)
1959 {
1960         unsigned long ret = 0;
1961         int i;
1962
1963         for (i = 0; i < OBD_HIST_MAX; i++)
1964                 ret +=  oh->oh_buckets[i];
1965         return ret;
1966 }
1967 EXPORT_SYMBOL(lprocfs_oh_sum);
1968
1969 void lprocfs_oh_clear(struct obd_histogram *oh)
1970 {
1971         spin_lock(&oh->oh_lock);
1972         memset(oh->oh_buckets, 0, sizeof(oh->oh_buckets));
1973         spin_unlock(&oh->oh_lock);
1974 }
1975 EXPORT_SYMBOL(lprocfs_oh_clear);
1976
1977 void lprocfs_oh_tally_pcpu(struct obd_hist_pcpu *oh,
1978                            unsigned int value)
1979 {
1980         if (value >= OBD_HIST_MAX)
1981                 value = OBD_HIST_MAX - 1;
1982
1983         percpu_counter_inc(&oh->oh_pc_buckets[value]);
1984 }
1985 EXPORT_SYMBOL(lprocfs_oh_tally_pcpu);
1986
1987 void lprocfs_oh_tally_log2_pcpu(struct obd_hist_pcpu *oh,
1988                                 unsigned int value)
1989 {
1990         unsigned int val = 0;
1991
1992         if (likely(value != 0))
1993                 val = min(fls(value - 1), OBD_HIST_MAX);
1994
1995         lprocfs_oh_tally_pcpu(oh, val);
1996 }
1997 EXPORT_SYMBOL(lprocfs_oh_tally_log2_pcpu);
1998
1999 unsigned long lprocfs_oh_counter_pcpu(struct obd_hist_pcpu *oh,
2000                                       unsigned int value)
2001 {
2002         return percpu_counter_sum(&oh->oh_pc_buckets[value]);
2003 }
2004 EXPORT_SYMBOL(lprocfs_oh_counter_pcpu);
2005
2006 unsigned long lprocfs_oh_sum_pcpu(struct obd_hist_pcpu *oh)
2007 {
2008         unsigned long ret = 0;
2009         int i;
2010
2011         for (i = 0; i < OBD_HIST_MAX; i++)
2012                 ret += percpu_counter_sum(&oh->oh_pc_buckets[i]);
2013
2014         return ret;
2015 }
2016 EXPORT_SYMBOL(lprocfs_oh_sum_pcpu);
2017
2018 int lprocfs_oh_alloc_pcpu(struct obd_hist_pcpu *oh)
2019 {
2020         int i, rc;
2021
2022         if (oh->oh_initialized)
2023                 return 0;
2024
2025         for (i = 0; i < OBD_HIST_MAX; i++) {
2026                 rc = percpu_counter_init(&oh->oh_pc_buckets[i], 0, GFP_KERNEL);
2027                 if (rc)
2028                         goto out;
2029         }
2030
2031         oh->oh_initialized = true;
2032
2033         return 0;
2034
2035 out:
2036         for (i--; i >= 0; i--)
2037                 percpu_counter_destroy(&oh->oh_pc_buckets[i]);
2038
2039         return rc;
2040 }
2041 EXPORT_SYMBOL(lprocfs_oh_alloc_pcpu);
2042
2043 void lprocfs_oh_clear_pcpu(struct obd_hist_pcpu *oh)
2044 {
2045         int i;
2046
2047         for (i = 0; i < OBD_HIST_MAX; i++)
2048                 percpu_counter_set(&oh->oh_pc_buckets[i], 0);
2049 }
2050 EXPORT_SYMBOL(lprocfs_oh_clear_pcpu);
2051
2052 void lprocfs_oh_release_pcpu(struct obd_hist_pcpu *oh)
2053 {
2054         int i;
2055
2056         if (!oh->oh_initialized)
2057                 return;
2058
2059         for (i = 0; i < OBD_HIST_MAX; i++)
2060                 percpu_counter_destroy(&oh->oh_pc_buckets[i]);
2061
2062         oh->oh_initialized = false;
2063 }
2064 EXPORT_SYMBOL(lprocfs_oh_release_pcpu);
2065
2066 ssize_t lustre_attr_show(struct kobject *kobj,
2067                          struct attribute *attr, char *buf)
2068 {
2069         struct lustre_attr *a = container_of(attr, struct lustre_attr, attr);
2070
2071         return a->show ? a->show(kobj, attr, buf) : 0;
2072 }
2073 EXPORT_SYMBOL_GPL(lustre_attr_show);
2074
2075 ssize_t lustre_attr_store(struct kobject *kobj, struct attribute *attr,
2076                           const char *buf, size_t len)
2077 {
2078         struct lustre_attr *a = container_of(attr, struct lustre_attr, attr);
2079
2080         return a->store ? a->store(kobj, attr, buf, len) : len;
2081 }
2082 EXPORT_SYMBOL_GPL(lustre_attr_store);
2083
2084 const struct sysfs_ops lustre_sysfs_ops = {
2085         .show  = lustre_attr_show,
2086         .store = lustre_attr_store,
2087 };
2088 EXPORT_SYMBOL_GPL(lustre_sysfs_ops);
2089
2090 int lprocfs_obd_max_pages_per_rpc_seq_show(struct seq_file *m, void *data)
2091 {
2092         struct obd_device *obd = data;
2093         struct client_obd *cli = &obd->u.cli;
2094
2095         spin_lock(&cli->cl_loi_list_lock);
2096         seq_printf(m, "%d\n", cli->cl_max_pages_per_rpc);
2097         spin_unlock(&cli->cl_loi_list_lock);
2098         return 0;
2099 }
2100 EXPORT_SYMBOL(lprocfs_obd_max_pages_per_rpc_seq_show);
2101
2102 ssize_t lprocfs_obd_max_pages_per_rpc_seq_write(struct file *file,
2103                                                 const char __user *buffer,
2104                                                 size_t count, loff_t *off)
2105 {
2106         struct seq_file *m = file->private_data;
2107         struct obd_device *obd = m->private;
2108         struct client_obd *cli = &obd->u.cli;
2109         struct obd_import *imp;
2110         struct obd_connect_data *ocd;
2111         int chunk_mask, rc;
2112         char kernbuf[22];
2113         u64 val;
2114
2115         if (count > sizeof(kernbuf) - 1)
2116                 return -EINVAL;
2117
2118         if (copy_from_user(kernbuf, buffer, count))
2119                 return -EFAULT;
2120
2121         kernbuf[count] = '\0';
2122
2123         rc = sysfs_memparse(kernbuf, count, &val, "B");
2124         if (rc)
2125                 return rc;
2126
2127         /* if the max_pages is specified in bytes, convert to pages */
2128         if (val >= ONE_MB_BRW_SIZE)
2129                 val >>= PAGE_SHIFT;
2130
2131         with_imp_locked(obd, imp, rc) {
2132                 ocd = &imp->imp_connect_data;
2133                 chunk_mask = ~((1 << (cli->cl_chunkbits - PAGE_SHIFT)) - 1);
2134                 /* max_pages_per_rpc must be chunk aligned */
2135                 val = (val + ~chunk_mask) & chunk_mask;
2136                 if (val == 0 || (ocd->ocd_brw_size != 0 &&
2137                                  val > ocd->ocd_brw_size >> PAGE_SHIFT)) {
2138                         rc = -ERANGE;
2139                 } else {
2140                         spin_lock(&cli->cl_loi_list_lock);
2141                         cli->cl_max_pages_per_rpc = val;
2142                         client_adjust_max_dirty(cli);
2143                         spin_unlock(&cli->cl_loi_list_lock);
2144                 }
2145         }
2146
2147         return rc ?: count;
2148 }
2149 EXPORT_SYMBOL(lprocfs_obd_max_pages_per_rpc_seq_write);
2150
2151 ssize_t short_io_bytes_show(struct kobject *kobj, struct attribute *attr,
2152                             char *buf)
2153 {
2154         struct obd_device *obd = container_of(kobj, struct obd_device,
2155                                               obd_kset.kobj);
2156         struct client_obd *cli = &obd->u.cli;
2157         int rc;
2158
2159         spin_lock(&cli->cl_loi_list_lock);
2160         rc = sprintf(buf, "%d\n", cli->cl_max_short_io_bytes);
2161         spin_unlock(&cli->cl_loi_list_lock);
2162         return rc;
2163 }
2164 EXPORT_SYMBOL(short_io_bytes_show);
2165
2166 /* Used to catch people who think they're specifying pages. */
2167 #define MIN_SHORT_IO_BYTES 64U
2168
2169 ssize_t short_io_bytes_store(struct kobject *kobj, struct attribute *attr,
2170                              const char *buffer, size_t count)
2171 {
2172         struct obd_device *obd = container_of(kobj, struct obd_device,
2173                                               obd_kset.kobj);
2174         struct client_obd *cli = &obd->u.cli;
2175         u64 val;
2176         int rc;
2177
2178         if (strcmp(buffer, "-1") == 0) {
2179                 val = OBD_DEF_SHORT_IO_BYTES;
2180         } else {
2181                 rc = sysfs_memparse(buffer, count, &val, "B");
2182                 if (rc)
2183                         GOTO(out, rc);
2184         }
2185
2186         if (val && (val < MIN_SHORT_IO_BYTES || val > LNET_MTU))
2187                 GOTO(out, rc = -ERANGE);
2188
2189         rc = count;
2190
2191         spin_lock(&cli->cl_loi_list_lock);
2192         cli->cl_max_short_io_bytes = min_t(u64, val, OST_MAX_SHORT_IO_BYTES);
2193         spin_unlock(&cli->cl_loi_list_lock);
2194
2195 out:
2196         return rc;
2197 }
2198 EXPORT_SYMBOL(short_io_bytes_store);
2199
2200 int lprocfs_wr_root_squash(const char __user *buffer, unsigned long count,
2201                            struct root_squash_info *squash, char *name)
2202 {
2203         int rc;
2204         char kernbuf[64], *tmp, *errmsg;
2205         unsigned long uid, gid;
2206         ENTRY;
2207
2208         if (count >= sizeof(kernbuf)) {
2209                 errmsg = "string too long";
2210                 GOTO(failed_noprint, rc = -EINVAL);
2211         }
2212         if (copy_from_user(kernbuf, buffer, count)) {
2213                 errmsg = "bad address";
2214                 GOTO(failed_noprint, rc = -EFAULT);
2215         }
2216         kernbuf[count] = '\0';
2217
2218         /* look for uid gid separator */
2219         tmp = strchr(kernbuf, ':');
2220         if (!tmp) {
2221                 errmsg = "needs uid:gid format";
2222                 GOTO(failed, rc = -EINVAL);
2223         }
2224         *tmp = '\0';
2225         tmp++;
2226
2227         /* parse uid */
2228         if (kstrtoul(kernbuf, 0, &uid) != 0) {
2229                 errmsg = "bad uid";
2230                 GOTO(failed, rc = -EINVAL);
2231         }
2232
2233         /* parse gid */
2234         if (kstrtoul(tmp, 0, &gid) != 0) {
2235                 errmsg = "bad gid";
2236                 GOTO(failed, rc = -EINVAL);
2237         }
2238
2239         squash->rsi_uid = uid;
2240         squash->rsi_gid = gid;
2241
2242         LCONSOLE_INFO("%s: root_squash is set to %u:%u\n",
2243                       name, squash->rsi_uid, squash->rsi_gid);
2244         RETURN(count);
2245
2246 failed:
2247         if (tmp) {
2248                 tmp--;
2249                 *tmp = ':';
2250         }
2251         CWARN("%s: failed to set root_squash to \"%s\", %s, rc = %d\n",
2252               name, kernbuf, errmsg, rc);
2253         RETURN(rc);
2254 failed_noprint:
2255         CWARN("%s: failed to set root_squash due to %s, rc = %d\n",
2256               name, errmsg, rc);
2257         RETURN(rc);
2258 }
2259 EXPORT_SYMBOL(lprocfs_wr_root_squash);
2260
2261
2262 int lprocfs_wr_nosquash_nids(const char __user *buffer, unsigned long count,
2263                              struct root_squash_info *squash, char *name)
2264 {
2265         int rc;
2266         char *kernbuf = NULL;
2267         char *errmsg;
2268         LIST_HEAD(tmp);
2269         int len = count;
2270         ENTRY;
2271
2272         if (count > 4096) {
2273                 errmsg = "string too long";
2274                 GOTO(failed, rc = -EINVAL);
2275         }
2276
2277         OBD_ALLOC(kernbuf, count + 1);
2278         if (!kernbuf) {
2279                 errmsg = "no memory";
2280                 GOTO(failed, rc = -ENOMEM);
2281         }
2282         if (copy_from_user(kernbuf, buffer, count)) {
2283                 errmsg = "bad address";
2284                 GOTO(failed, rc = -EFAULT);
2285         }
2286         kernbuf[count] = '\0';
2287
2288         if (count > 0 && kernbuf[count - 1] == '\n')
2289                 len = count - 1;
2290
2291         if ((len == 4 && strncmp(kernbuf, "NONE", len) == 0) ||
2292             (len == 5 && strncmp(kernbuf, "clear", len) == 0)) {
2293                 /* empty string is special case */
2294                 spin_lock(&squash->rsi_lock);
2295                 if (!list_empty(&squash->rsi_nosquash_nids))
2296                         cfs_free_nidlist(&squash->rsi_nosquash_nids);
2297                 spin_unlock(&squash->rsi_lock);
2298                 LCONSOLE_INFO("%s: nosquash_nids is cleared\n", name);
2299                 OBD_FREE(kernbuf, count + 1);
2300                 RETURN(count);
2301         }
2302
2303         if (cfs_parse_nidlist(kernbuf, count, &tmp) <= 0) {
2304                 errmsg = "can't parse";
2305                 GOTO(failed, rc = -EINVAL);
2306         }
2307         LCONSOLE_INFO("%s: nosquash_nids set to %s\n",
2308                       name, kernbuf);
2309         OBD_FREE(kernbuf, count + 1);
2310         kernbuf = NULL;
2311
2312         spin_lock(&squash->rsi_lock);
2313         if (!list_empty(&squash->rsi_nosquash_nids))
2314                 cfs_free_nidlist(&squash->rsi_nosquash_nids);
2315         list_splice(&tmp, &squash->rsi_nosquash_nids);
2316         spin_unlock(&squash->rsi_lock);
2317
2318         RETURN(count);
2319
2320 failed:
2321         if (kernbuf) {
2322                 CWARN("%s: failed to set nosquash_nids to \"%s\", %s rc = %d\n",
2323                       name, kernbuf, errmsg, rc);
2324                 OBD_FREE(kernbuf, count + 1);
2325         } else {
2326                 CWARN("%s: failed to set nosquash_nids due to %s rc = %d\n",
2327                       name, errmsg, rc);
2328         }
2329         RETURN(rc);
2330 }
2331 EXPORT_SYMBOL(lprocfs_wr_nosquash_nids);
2332
2333 #endif /* CONFIG_PROC_FS*/