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