Whamcloud - gitweb
LU-15317 libcfs: Remove D_TTY
[fs/lustre-release.git] / libcfs / libcfs / tracefile.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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * libcfs/libcfs/tracefile.c
32  *
33  * Author: Zach Brown <zab@clusterfs.com>
34  * Author: Phil Schwan <phil@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_LNET
38 #include "tracefile.h"
39
40 #include <linux/ctype.h>
41 #include <linux/fs.h>
42 #include <linux/kthread.h>
43 #include <linux/pagemap.h>
44 #include <linux/poll.h>
45 #include <linux/uaccess.h>
46 #include <libcfs/linux/linux-fs.h>
47 #include <libcfs/libcfs.h>
48
49
50 enum cfs_trace_buf_type {
51         CFS_TCD_TYPE_PROC = 0,
52         CFS_TCD_TYPE_SOFTIRQ,
53         CFS_TCD_TYPE_IRQ,
54         CFS_TCD_TYPE_CNT
55 };
56
57 union cfs_trace_data_union (*cfs_trace_data[CFS_TCD_TYPE_CNT])[NR_CPUS] __cacheline_aligned;
58
59 /* Pages containing records already processed by daemon.
60  * Link via ->lru, use size in ->private
61  */
62 static LIST_HEAD(daemon_pages);
63 static long daemon_pages_count;
64 static long daemon_pages_max;
65
66 char cfs_tracefile[TRACEFILE_NAME_SIZE];
67 long long cfs_tracefile_size = CFS_TRACEFILE_SIZE;
68
69 struct task_struct *tctl_task;
70
71 static atomic_t cfs_tage_allocated = ATOMIC_INIT(0);
72 static DECLARE_RWSEM(cfs_tracefile_sem);
73
74 /* trace file lock routines */
75 /* The walking argument indicates the locking comes from all tcd types
76  * iterator and we must lock it and dissable local irqs to avoid deadlocks
77  * with other interrupt locks that might be happening. See LU-1311
78  * for details.
79  */
80 int cfs_trace_lock_tcd(struct cfs_trace_cpu_data *tcd, int walking)
81         __acquires(&tcd->tcd_lock)
82 {
83         __LASSERT(tcd->tcd_type < CFS_TCD_TYPE_CNT);
84         if (tcd->tcd_type == CFS_TCD_TYPE_IRQ)
85                 spin_lock_irqsave(&tcd->tcd_lock, tcd->tcd_lock_flags);
86         else if (tcd->tcd_type == CFS_TCD_TYPE_SOFTIRQ)
87                 spin_lock_bh(&tcd->tcd_lock);
88         else if (unlikely(walking))
89                 spin_lock_irq(&tcd->tcd_lock);
90         else
91                 spin_lock(&tcd->tcd_lock);
92         return 1;
93 }
94
95 void cfs_trace_unlock_tcd(struct cfs_trace_cpu_data *tcd, int walking)
96         __releases(&tcd->tcd_lock)
97 {
98         __LASSERT(tcd->tcd_type < CFS_TCD_TYPE_CNT);
99         if (tcd->tcd_type == CFS_TCD_TYPE_IRQ)
100                 spin_unlock_irqrestore(&tcd->tcd_lock, tcd->tcd_lock_flags);
101         else if (tcd->tcd_type == CFS_TCD_TYPE_SOFTIRQ)
102                 spin_unlock_bh(&tcd->tcd_lock);
103         else if (unlikely(walking))
104                 spin_unlock_irq(&tcd->tcd_lock);
105         else
106                 spin_unlock(&tcd->tcd_lock);
107 }
108
109 #define cfs_tcd_for_each(tcd, i, j)                                     \
110         for (i = 0; i < CFS_TCD_TYPE_CNT && cfs_trace_data[i]; i++)     \
111                 for (j = 0, ((tcd) = &(*cfs_trace_data[i])[j].tcd);     \
112                      j < num_possible_cpus();                           \
113                      j++, (tcd) = &(*cfs_trace_data[i])[j].tcd)
114
115 #define cfs_tcd_for_each_type_lock(tcd, i, cpu)                         \
116         for (i = 0; i < CFS_TCD_TYPE_CNT && cfs_trace_data[i] &&        \
117              (tcd = &(*cfs_trace_data[i])[cpu].tcd) &&                  \
118              cfs_trace_lock_tcd(tcd, 1); cfs_trace_unlock_tcd(tcd, 1), i++)
119
120 enum cfs_trace_buf_type cfs_trace_buf_idx_get(void)
121 {
122         if (in_irq())
123                 return CFS_TCD_TYPE_IRQ;
124         if (in_softirq())
125                 return CFS_TCD_TYPE_SOFTIRQ;
126         return CFS_TCD_TYPE_PROC;
127 }
128
129 static inline struct cfs_trace_cpu_data *
130 cfs_trace_get_tcd(void)
131 {
132         struct cfs_trace_cpu_data *tcd =
133                 &(*cfs_trace_data[cfs_trace_buf_idx_get()])[get_cpu()].tcd;
134
135         cfs_trace_lock_tcd(tcd, 0);
136
137         return tcd;
138 }
139
140 static inline void cfs_trace_put_tcd(struct cfs_trace_cpu_data *tcd)
141 {
142         cfs_trace_unlock_tcd(tcd, 0);
143
144         put_cpu();
145 }
146
147 static inline struct cfs_trace_page *
148 cfs_tage_from_list(struct list_head *list)
149 {
150         return list_entry(list, struct cfs_trace_page, linkage);
151 }
152
153 static struct cfs_trace_page *cfs_tage_alloc(gfp_t gfp)
154 {
155         struct page            *page;
156         struct cfs_trace_page *tage;
157
158         /* My caller is trying to free memory */
159         if (!in_interrupt() && (current->flags & PF_MEMALLOC))
160                 return NULL;
161
162         /*
163          * Don't spam console with allocation failures: they will be reported
164          * by upper layer anyway.
165          */
166         gfp |= __GFP_NOWARN;
167         page = alloc_page(gfp);
168         if (page == NULL)
169                 return NULL;
170
171         tage = kmalloc(sizeof(*tage), gfp);
172         if (tage == NULL) {
173                 __free_page(page);
174                 return NULL;
175         }
176
177         tage->page = page;
178         atomic_inc(&cfs_tage_allocated);
179         return tage;
180 }
181
182 static void cfs_tage_free(struct cfs_trace_page *tage)
183 {
184         __LASSERT(tage != NULL);
185         __LASSERT(tage->page != NULL);
186
187         __free_page(tage->page);
188         kfree(tage);
189         atomic_dec(&cfs_tage_allocated);
190 }
191
192 static void cfs_tage_to_tail(struct cfs_trace_page *tage,
193                              struct list_head *queue)
194 {
195         __LASSERT(tage != NULL);
196         __LASSERT(queue != NULL);
197
198         list_move_tail(&tage->linkage, queue);
199 }
200
201 /* return a page that has 'len' bytes left at the end */
202 static struct cfs_trace_page *
203 cfs_trace_get_tage_try(struct cfs_trace_cpu_data *tcd, unsigned long len)
204 {
205         struct cfs_trace_page *tage;
206         struct task_struct *tsk;
207
208         if (tcd->tcd_cur_pages > 0) {
209                 __LASSERT(!list_empty(&tcd->tcd_pages));
210                 tage = cfs_tage_from_list(tcd->tcd_pages.prev);
211                 if (tage->used + len <= PAGE_SIZE)
212                         return tage;
213         }
214
215         if (tcd->tcd_cur_pages < tcd->tcd_max_pages) {
216                 if (tcd->tcd_cur_stock_pages > 0) {
217                         tage = cfs_tage_from_list(tcd->tcd_stock_pages.prev);
218                         --tcd->tcd_cur_stock_pages;
219                         list_del_init(&tage->linkage);
220                 } else {
221                         tage = cfs_tage_alloc(GFP_ATOMIC);
222                         if (unlikely(tage == NULL)) {
223                                 if ((!(current->flags & PF_MEMALLOC) ||
224                                      in_interrupt()) && printk_ratelimit())
225                                         pr_warn("Lustre: cannot allocate a tage (%ld)\n",
226                                                 tcd->tcd_cur_pages);
227                                 return NULL;
228                         }
229                 }
230
231                 tage->used = 0;
232                 tage->cpu = smp_processor_id();
233                 tage->type = tcd->tcd_type;
234                 list_add_tail(&tage->linkage, &tcd->tcd_pages);
235                 tcd->tcd_cur_pages++;
236
237                 tsk = tctl_task;
238                 if (tcd->tcd_cur_pages > 8 && tsk)
239                         /*
240                          * wake up tracefiled to process some pages.
241                          */
242                         wake_up_process(tsk);
243
244                 return tage;
245         }
246         return NULL;
247 }
248
249 static void cfs_tcd_shrink(struct cfs_trace_cpu_data *tcd)
250 {
251         int pgcount = tcd->tcd_cur_pages / 10;
252         struct page_collection pc;
253         struct cfs_trace_page *tage;
254         struct cfs_trace_page *tmp;
255
256         /*
257          * XXX nikita: do NOT call portals_debug_msg() (CDEBUG/ENTRY/EXIT)
258          * from here: this will lead to infinite recursion.
259          */
260
261         if (printk_ratelimit())
262                 pr_warn("Lustre: debug daemon buffer overflowed; discarding 10%% of pages (%d of %ld)\n",
263                         pgcount + 1, tcd->tcd_cur_pages);
264
265         INIT_LIST_HEAD(&pc.pc_pages);
266
267         list_for_each_entry_safe(tage, tmp, &tcd->tcd_pages, linkage) {
268                 if (pgcount-- == 0)
269                         break;
270
271                 list_del(&tage->linkage);
272                 cfs_tage_free(tage);
273                 tcd->tcd_cur_pages--;
274         }
275 }
276
277 /* return a page that has 'len' bytes left at the end */
278 static struct cfs_trace_page *cfs_trace_get_tage(struct cfs_trace_cpu_data *tcd,
279                                                  unsigned long len)
280 {
281         struct cfs_trace_page *tage;
282
283         /*
284          * XXX nikita: do NOT call portals_debug_msg() (CDEBUG/ENTRY/EXIT)
285          * from here: this will lead to infinite recursion.
286          */
287
288         if (len > PAGE_SIZE) {
289                 pr_err("LustreError: cowardly refusing to write %lu bytes in a page\n",
290                        len);
291                 return NULL;
292         }
293
294         tage = cfs_trace_get_tage_try(tcd, len);
295         if (tage != NULL)
296                 return tage;
297         if (tctl_task)
298                 cfs_tcd_shrink(tcd);
299         if (tcd->tcd_cur_pages > 0) {
300                 tage = cfs_tage_from_list(tcd->tcd_pages.next);
301                 tage->used = 0;
302                 cfs_tage_to_tail(tage, &tcd->tcd_pages);
303         }
304         return tage;
305 }
306
307 static void cfs_set_ptldebug_header(struct ptldebug_header *header,
308                                     struct libcfs_debug_msg_data *msgdata,
309                                     unsigned long stack)
310 {
311         struct timespec64 ts;
312
313         ktime_get_real_ts64(&ts);
314
315         header->ph_subsys = msgdata->msg_subsys;
316         header->ph_mask = msgdata->msg_mask;
317         header->ph_cpu_id = smp_processor_id();
318         header->ph_type = cfs_trace_buf_idx_get();
319         /* y2038 safe since all user space treats this as unsigned, but
320          * will overflow in 2106
321          */
322         header->ph_sec = (u32)ts.tv_sec;
323         header->ph_usec = ts.tv_nsec / NSEC_PER_USEC;
324         header->ph_stack = stack;
325         header->ph_pid = current->pid;
326         header->ph_line_num = msgdata->msg_line;
327         header->ph_extern_pid = 0;
328 }
329
330 static void cfs_vprint_to_console(struct ptldebug_header *hdr, int mask,
331                                   struct va_format *vaf, const char *file,
332                                   const char *fn)
333 {
334         char *prefix = "Lustre";
335
336         if (hdr->ph_subsys == S_LND || hdr->ph_subsys == S_LNET)
337                 prefix = "LNet";
338
339         if (mask & D_CONSOLE) {
340                 if (mask & D_EMERG)
341                         pr_emerg("%sError: %pV", prefix, vaf);
342                 else if (mask & D_ERROR)
343                         pr_err("%sError: %pV", prefix, vaf);
344                 else if (mask & D_WARNING)
345                         pr_warn("%s: %pV", prefix, vaf);
346                 else if (mask & libcfs_printk)
347                         pr_info("%s: %pV", prefix, vaf);
348         } else {
349                 if (mask & D_EMERG)
350                         pr_emerg("%sError: %d:%d:(%s:%d:%s()) %pV", prefix,
351                                  hdr->ph_pid, hdr->ph_extern_pid, file,
352                                  hdr->ph_line_num, fn, vaf);
353                 else if (mask & D_ERROR)
354                         pr_err("%sError: %d:%d:(%s:%d:%s()) %pV", prefix,
355                                hdr->ph_pid, hdr->ph_extern_pid, file,
356                                hdr->ph_line_num, fn, vaf);
357                 else if (mask & D_WARNING)
358                         pr_warn("%s: %d:%d:(%s:%d:%s()) %pV", prefix,
359                                 hdr->ph_pid, hdr->ph_extern_pid, file,
360                                 hdr->ph_line_num, fn, vaf);
361                 else if (mask & (D_CONSOLE | libcfs_printk))
362                         pr_info("%s: %pV", prefix, vaf);
363         }
364 }
365
366 static void cfs_print_to_console(struct ptldebug_header *hdr, int mask,
367                                  const char *file, const char *fn,
368                                  const char *fmt, ...)
369 {
370         struct va_format vaf;
371         va_list args;
372
373         va_start(args, fmt);
374         vaf.fmt = fmt;
375         vaf.va = &args;
376         cfs_vprint_to_console(hdr, mask, &vaf, file, fn);
377 }
378
379 int libcfs_debug_msg(struct libcfs_debug_msg_data *msgdata,
380                      const char *format, ...)
381 {
382         struct cfs_trace_cpu_data *tcd = NULL;
383         struct ptldebug_header header = {0};
384         struct cfs_trace_page *tage;
385         /* string_buf is used only if tcd != NULL, and is always set then */
386         char *string_buf = NULL;
387         char *debug_buf;
388         int known_size;
389         int needed = 85; /* seeded with average message length */
390         int max_nob;
391         va_list ap;
392         int retry;
393         int mask = msgdata->msg_mask;
394         char *file = (char *)msgdata->msg_file;
395         struct cfs_debug_limit_state *cdls = msgdata->msg_cdls;
396
397         if (strchr(file, '/'))
398                 file = strrchr(file, '/') + 1;
399
400         tcd = cfs_trace_get_tcd();
401
402         /* cfs_trace_get_tcd() grabs a lock, which disables preemption and
403          * pins us to a particular CPU.  This avoids an smp_processor_id()
404          * warning on Linux when debugging is enabled.
405          */
406         cfs_set_ptldebug_header(&header, msgdata, CDEBUG_STACK());
407
408         if (!tcd)                /* arch may not log in IRQ context */
409                 goto console;
410
411         if (tcd->tcd_cur_pages == 0)
412                 header.ph_flags |= PH_FLAG_FIRST_RECORD;
413
414         if (tcd->tcd_shutting_down) {
415                 cfs_trace_put_tcd(tcd);
416                 tcd = NULL;
417                 goto console;
418         }
419
420         known_size = strlen(file) + 1;
421         if (msgdata->msg_fn)
422                 known_size += strlen(msgdata->msg_fn) + 1;
423
424         if (libcfs_debug_binary)
425                 known_size += sizeof(header);
426
427         /*
428          * May perform an additional pass to update 'needed' and increase
429          * tage buffer size to match vsnprintf reported size required
430          * On the second pass (retry=1) use vscnprintf [which returns
431          * number of bytes written not including the terminating nul]
432          * to clarify `needed` is used as number of bytes written
433          * for the remainder of this function
434          */
435         for (retry = 0; retry < 2; retry++) {
436                 tage = cfs_trace_get_tage(tcd, needed + known_size + 1);
437                 if (!tage) {
438                         if (needed + known_size > PAGE_SIZE)
439                                 mask |= D_ERROR;
440
441                         cfs_trace_put_tcd(tcd);
442                         tcd = NULL;
443                         goto console;
444                 }
445
446                 string_buf = (char *)page_address(tage->page) +
447                              tage->used + known_size;
448
449                 max_nob = PAGE_SIZE - tage->used - known_size;
450                 if (max_nob <= 0) {
451                         pr_emerg("LustreError: negative max_nob: %d\n",
452                                  max_nob);
453                         mask |= D_ERROR;
454                         cfs_trace_put_tcd(tcd);
455                         tcd = NULL;
456                         goto console;
457                 }
458
459                 va_start(ap, format);
460                 if (retry)
461                         needed = vscnprintf(string_buf, max_nob, format, ap);
462                 else
463                         needed = vsnprintf(string_buf, max_nob, format, ap);
464                 va_end(ap);
465
466                 if (needed < max_nob) /* well. printing ok.. */
467                         break;
468         }
469
470         /* `needed` is actual bytes written to string_buf */
471         if (*(string_buf + needed - 1) != '\n') {
472                 pr_info("Lustre: format at %s:%d:%s doesn't end in newline\n",
473                         file, msgdata->msg_line, msgdata->msg_fn);
474         }
475
476         header.ph_len = known_size + needed;
477         debug_buf = (char *)page_address(tage->page) + tage->used;
478
479         if (libcfs_debug_binary) {
480                 memcpy(debug_buf, &header, sizeof(header));
481                 tage->used += sizeof(header);
482                 debug_buf += sizeof(header);
483         }
484
485         strlcpy(debug_buf, file, PAGE_SIZE - tage->used);
486         tage->used += strlen(file) + 1;
487         debug_buf += strlen(file) + 1;
488
489         if (msgdata->msg_fn) {
490                 strlcpy(debug_buf, msgdata->msg_fn, PAGE_SIZE - tage->used);
491                 tage->used += strlen(msgdata->msg_fn) + 1;
492                 debug_buf += strlen(msgdata->msg_fn) + 1;
493         }
494
495         __LASSERT(debug_buf == string_buf);
496
497         tage->used += needed;
498         __LASSERT(tage->used <= PAGE_SIZE);
499
500 console:
501         if ((mask & libcfs_printk) == 0) {
502                 /* no console output requested */
503                 if (tcd != NULL)
504                         cfs_trace_put_tcd(tcd);
505                 return 1;
506         }
507
508         if (cdls != NULL) {
509                 if (libcfs_console_ratelimit &&
510                     cdls->cdls_next != 0 &&     /* not first time ever */
511                     time_before(jiffies, cdls->cdls_next)) {
512                         /* skipping a console message */
513                         cdls->cdls_count++;
514                         if (tcd != NULL)
515                                 cfs_trace_put_tcd(tcd);
516                         return 1;
517                 }
518
519                 if (time_after(jiffies, cdls->cdls_next +
520                                         libcfs_console_max_delay +
521                                         cfs_time_seconds(10))) {
522                         /* last timeout was a long time ago */
523                         cdls->cdls_delay /= libcfs_console_backoff * 4;
524                 } else {
525                         cdls->cdls_delay *= libcfs_console_backoff;
526                 }
527
528                 if (cdls->cdls_delay < libcfs_console_min_delay)
529                         cdls->cdls_delay = libcfs_console_min_delay;
530                 else if (cdls->cdls_delay > libcfs_console_max_delay)
531                         cdls->cdls_delay = libcfs_console_max_delay;
532
533                 /* ensure cdls_next is never zero after it's been seen */
534                 cdls->cdls_next = (jiffies + cdls->cdls_delay) | 1;
535         }
536
537         if (tcd) {
538                 cfs_print_to_console(&header, mask, file, msgdata->msg_fn,
539                                      "%s", string_buf);
540                 cfs_trace_put_tcd(tcd);
541         } else {
542                 struct va_format vaf;
543
544                 va_start(ap, format);
545                 vaf.fmt = format;
546                 vaf.va = &ap;
547                 cfs_vprint_to_console(&header, mask,
548                                       &vaf, file, msgdata->msg_fn);
549                 va_end(ap);
550         }
551
552         if (cdls != NULL && cdls->cdls_count != 0) {
553                 cfs_print_to_console(&header, mask, file,
554                                      msgdata->msg_fn,
555                                      "Skipped %d previous similar message%s\n",
556                                      cdls->cdls_count,
557                                      (cdls->cdls_count > 1) ? "s" : "");
558
559                 cdls->cdls_count = 0;
560         }
561
562         return 0;
563 }
564 EXPORT_SYMBOL(libcfs_debug_msg);
565
566 void
567 cfs_trace_assertion_failed(const char *str,
568                            struct libcfs_debug_msg_data *msgdata)
569 {
570         struct ptldebug_header hdr;
571
572         libcfs_panic_in_progress = 1;
573         libcfs_catastrophe = 1;
574         smp_mb();
575
576         cfs_set_ptldebug_header(&hdr, msgdata, CDEBUG_STACK());
577
578         cfs_print_to_console(&hdr, D_EMERG, msgdata->msg_file, msgdata->msg_fn,
579                              "%s", str);
580
581         panic("Lustre debug assertion failure\n");
582
583         /* not reached */
584 }
585
586 static void
587 panic_collect_pages(struct page_collection *pc)
588 {
589         /* Do the collect_pages job on a single CPU: assumes that all other
590          * CPUs have been stopped during a panic.  If this isn't true for some
591          * arch, this will have to be implemented separately in each arch.  */
592         int                        i;
593         int                        j;
594         struct cfs_trace_cpu_data *tcd;
595
596         INIT_LIST_HEAD(&pc->pc_pages);
597
598         cfs_tcd_for_each(tcd, i, j) {
599                 list_splice_init(&tcd->tcd_pages, &pc->pc_pages);
600                 tcd->tcd_cur_pages = 0;
601         }
602 }
603
604 static void collect_pages_on_all_cpus(struct page_collection *pc)
605 {
606         struct cfs_trace_cpu_data *tcd;
607         int i, cpu;
608
609         for_each_possible_cpu(cpu) {
610                 cfs_tcd_for_each_type_lock(tcd, i, cpu) {
611                         list_splice_init(&tcd->tcd_pages, &pc->pc_pages);
612                         tcd->tcd_cur_pages = 0;
613                 }
614         }
615 }
616
617 static void collect_pages(struct page_collection *pc)
618 {
619         INIT_LIST_HEAD(&pc->pc_pages);
620
621         if (libcfs_panic_in_progress)
622                 panic_collect_pages(pc);
623         else
624                 collect_pages_on_all_cpus(pc);
625 }
626
627 static void put_pages_back_on_all_cpus(struct page_collection *pc)
628 {
629         struct cfs_trace_cpu_data *tcd;
630         struct list_head *cur_head;
631         struct cfs_trace_page *tage;
632         struct cfs_trace_page *tmp;
633         int i, cpu;
634
635         for_each_possible_cpu(cpu) {
636                 cfs_tcd_for_each_type_lock(tcd, i, cpu) {
637                         cur_head = tcd->tcd_pages.next;
638
639                         list_for_each_entry_safe(tage, tmp, &pc->pc_pages,
640                                                  linkage) {
641
642                                 __LASSERT_TAGE_INVARIANT(tage);
643
644                                 if (tage->cpu != cpu || tage->type != i)
645                                         continue;
646
647                                 cfs_tage_to_tail(tage, cur_head);
648                                 tcd->tcd_cur_pages++;
649                         }
650                 }
651         }
652 }
653
654 static void put_pages_back(struct page_collection *pc)
655 {
656         if (!libcfs_panic_in_progress)
657                 put_pages_back_on_all_cpus(pc);
658 }
659
660 #ifdef LNET_DUMP_ON_PANIC
661 void cfs_trace_debug_print(void)
662 {
663         struct page_collection pc;
664         struct cfs_trace_page *tage;
665         struct cfs_trace_page *tmp;
666         struct page *page;
667
668         collect_pages(&pc);
669         list_for_each_entry_safe(tage, tmp, &pc.pc_pages, linkage) {
670                 char *p, *file, *fn;
671
672                 __LASSERT_TAGE_INVARIANT(tage);
673
674                 page = tage->page;
675                 p = page_address(page);
676                 while (p < ((char *)page_address(page) + tage->used)) {
677                         struct ptldebug_header *hdr;
678                         int len;
679                         hdr = (void *)p;
680                         p += sizeof(*hdr);
681                         file = p;
682                         p += strlen(file) + 1;
683                         fn = p;
684                         p += strlen(fn) + 1;
685                         len = hdr->ph_len - (int)(p - (char *)hdr);
686
687                         cfs_print_to_console(hdr, D_EMERG, file, fn,
688                                              "%.*s", len, p);
689
690                         p += len;
691                 }
692
693                 list_del(&tage->linkage);
694                 cfs_tage_free(tage);
695         }
696         down_write(&cfs_tracefile_sem);
697         while ((page = list_first_entry_or_null(&daemon_pages,
698                                                 struct page, lru)) != NULL) {
699                 char *p, *file, *fn;
700
701                 p = page_address(page);
702                 while (p < ((char *)page_address(page) + page->private)) {
703                         struct ptldebug_header *hdr;
704                         int len;
705
706                         hdr = (void *)p;
707                         p += sizeof(*hdr);
708                         file = p;
709                         p += strlen(file) + 1;
710                         fn = p;
711                         p += strlen(fn) + 1;
712                         len = hdr->ph_len - (int)(p - (char *)hdr);
713
714                         cfs_print_to_console(hdr, D_EMERG, file, fn,
715                                              "%.*s", len, p);
716
717                         p += len;
718                 }
719                 list_del_init(&page->lru);
720                 daemon_pages_count -= 1;
721                 put_page(page);
722         }
723         up_write(&cfs_tracefile_sem);
724 }
725 #endif /* LNET_DUMP_ON_PANIC */
726
727 int cfs_tracefile_dump_all_pages(char *filename)
728 {
729         struct page_collection pc;
730         struct file *filp;
731         struct cfs_trace_page *tage;
732         struct cfs_trace_page *tmp;
733         char *buf;
734         struct page *page;
735         int rc;
736
737         down_write(&cfs_tracefile_sem);
738
739         filp = filp_open(filename, O_CREAT|O_EXCL|O_WRONLY|O_LARGEFILE, 0600);
740         if (IS_ERR(filp)) {
741                 rc = PTR_ERR(filp);
742                 filp = NULL;
743                 pr_err("LustreError: can't open %s for dump: rc = %d\n",
744                        filename, rc);
745                 goto out;
746         }
747
748         collect_pages(&pc);
749         if (list_empty(&pc.pc_pages)) {
750                 rc = 0;
751                 goto close;
752         }
753
754         /* ok, for now, just write the pages.  in the future we'll be building
755          * iobufs with the pages and calling generic_direct_IO */
756         list_for_each_entry_safe(tage, tmp, &pc.pc_pages, linkage) {
757
758                 __LASSERT_TAGE_INVARIANT(tage);
759
760                 buf = kmap(tage->page);
761                 rc = cfs_kernel_write(filp, buf, tage->used, &filp->f_pos);
762                 kunmap(tage->page);
763                 if (rc != (int)tage->used) {
764                         pr_warn("Lustre: wanted to write %u but wrote %d\n",
765                                 tage->used, rc);
766                         put_pages_back(&pc);
767                         __LASSERT(list_empty(&pc.pc_pages));
768                         break;
769                 }
770                 list_del(&tage->linkage);
771                 cfs_tage_free(tage);
772         }
773         while ((page = list_first_entry_or_null(&daemon_pages,
774                                                 struct page, lru)) != NULL) {
775                 buf = page_address(page);
776                 rc = cfs_kernel_write(filp, buf, page->private, &filp->f_pos);
777                 if (rc != (int)page->private) {
778                         pr_warn("Lustre: wanted to write %u but wrote %d\n",
779                                 (int)page->private, rc);
780                         break;
781                 }
782                 list_del(&page->lru);
783                 daemon_pages_count -= 1;
784                 put_page(page);
785         }
786         rc = vfs_fsync_range(filp, 0, LLONG_MAX, 1);
787         if (rc)
788                 pr_err("LustreError: sync returns: rc = %d\n", rc);
789 close:
790         filp_close(filp, NULL);
791 out:
792         up_write(&cfs_tracefile_sem);
793         return rc;
794 }
795
796 void cfs_trace_flush_pages(void)
797 {
798         struct page_collection pc;
799         struct cfs_trace_page *tage;
800         struct page *page;
801
802         collect_pages(&pc);
803         while (!list_empty(&pc.pc_pages)) {
804                 tage = list_first_entry(&pc.pc_pages,
805                                         struct cfs_trace_page, linkage);
806                 __LASSERT_TAGE_INVARIANT(tage);
807
808                 list_del(&tage->linkage);
809                 cfs_tage_free(tage);
810         }
811
812         down_write(&cfs_tracefile_sem);
813         while ((page = list_first_entry_or_null(&daemon_pages,
814                                                 struct page, lru)) != NULL) {
815                 list_del(&page->lru);
816                 daemon_pages_count -= 1;
817                 put_page(page);
818         }
819         up_write(&cfs_tracefile_sem);
820 }
821
822 int cfs_trace_copyout_string(char __user *usr_buffer, int usr_buffer_nob,
823                              const char *knl_buffer, char *append)
824 {
825         /* NB if 'append' != NULL, it's a single character to append to the
826          * copied out string - usually "\n", for /proc entries and "" (i.e. a
827          * terminating zero byte) for sysctl entries */
828         int   nob = strlen(knl_buffer);
829
830         if (nob > usr_buffer_nob)
831                 nob = usr_buffer_nob;
832
833         if (copy_to_user(usr_buffer, knl_buffer, nob))
834                 return -EFAULT;
835
836         if (append != NULL && nob < usr_buffer_nob) {
837                 if (copy_to_user(usr_buffer + nob, append, 1))
838                         return -EFAULT;
839
840                 nob++;
841         }
842
843         return nob;
844 }
845 EXPORT_SYMBOL(cfs_trace_copyout_string);
846
847 int cfs_trace_dump_debug_buffer_usrstr(void __user *usr_str, int usr_str_nob)
848 {
849         char *str;
850         char *path;
851         int rc;
852
853         str = memdup_user_nul(usr_str, usr_str_nob);
854         if (IS_ERR(str))
855                 return PTR_ERR(str);
856
857         path = strim(str);
858         if (path[0] != '/')
859                 rc = -EINVAL;
860         else
861                 rc = cfs_tracefile_dump_all_pages(path);
862         kfree(str);
863
864         return rc;
865 }
866
867 int cfs_trace_daemon_command(char *str)
868 {
869         int       rc = 0;
870
871         down_write(&cfs_tracefile_sem);
872
873         if (strcmp(str, "stop") == 0) {
874                 up_write(&cfs_tracefile_sem);
875                 cfs_trace_stop_thread();
876                 down_write(&cfs_tracefile_sem);
877                 memset(cfs_tracefile, 0, sizeof(cfs_tracefile));
878
879         } else if (strncmp(str, "size=", 5) == 0) {
880                 unsigned long tmp;
881
882                 rc = kstrtoul(str + 5, 10, &tmp);
883                 if (!rc) {
884                         if (tmp < 10 || tmp > 20480)
885                                 cfs_tracefile_size = CFS_TRACEFILE_SIZE;
886                         else
887                                 cfs_tracefile_size = tmp << 20;
888                 }
889         } else if (strlen(str) >= sizeof(cfs_tracefile)) {
890                 rc = -ENAMETOOLONG;
891         } else if (str[0] != '/') {
892                 rc = -EINVAL;
893         } else {
894                 strcpy(cfs_tracefile, str);
895
896                 pr_info("Lustre: debug daemon will attempt to start writing to %s (%lukB max)\n",
897                         cfs_tracefile, (long)(cfs_tracefile_size >> 10));
898
899                 cfs_trace_start_thread();
900         }
901
902         up_write(&cfs_tracefile_sem);
903         return rc;
904 }
905
906 int cfs_trace_daemon_command_usrstr(void __user *usr_str, int usr_str_nob)
907 {
908         char *str;
909         int   rc;
910
911         str = memdup_user_nul(usr_str, usr_str_nob);
912         if (IS_ERR(str))
913                 return PTR_ERR(str);
914
915         rc = cfs_trace_daemon_command(strim(str));
916         kfree(str);
917
918         return rc;
919 }
920
921 int cfs_trace_set_debug_mb(int mb)
922 {
923         int i;
924         int j;
925         unsigned long pages;
926         unsigned long total_mb = (cfs_totalram_pages() >> (20 - PAGE_SHIFT));
927         unsigned long limit = max_t(unsigned long, 512, (total_mb * 4) / 5);
928         struct cfs_trace_cpu_data *tcd;
929
930         if (mb < num_possible_cpus()) {
931                 pr_warn("Lustre: %d MB is too small for debug buffer size, setting it to %d MB.\n",
932                         mb, num_possible_cpus());
933                 mb = num_possible_cpus();
934         }
935
936         if (mb > limit) {
937                 pr_warn("Lustre: %d MB is too large for debug buffer size, setting it to %lu MB.\n",
938                         mb, limit);
939                 mb = limit;
940         }
941
942         mb /= num_possible_cpus();
943         pages = mb << (20 - PAGE_SHIFT);
944
945         down_write(&cfs_tracefile_sem);
946
947         cfs_tcd_for_each(tcd, i, j)
948                 tcd->tcd_max_pages = (pages * tcd->tcd_pages_factor) / 100;
949
950         daemon_pages_max = pages;
951         up_write(&cfs_tracefile_sem);
952
953         return mb;
954 }
955
956 int cfs_trace_get_debug_mb(void)
957 {
958         int i;
959         int j;
960         struct cfs_trace_cpu_data *tcd;
961         int total_pages = 0;
962
963         down_read(&cfs_tracefile_sem);
964
965         cfs_tcd_for_each(tcd, i, j)
966                 total_pages += tcd->tcd_max_pages;
967
968         up_read(&cfs_tracefile_sem);
969
970         return (total_pages >> (20 - PAGE_SHIFT)) + 1;
971 }
972
973 static int tracefiled(void *arg)
974 {
975         struct page_collection pc;
976         struct cfs_trace_page *tage;
977         struct cfs_trace_page *tmp;
978         struct file *filp;
979         char *buf;
980         int last_loop = 0;
981         int rc;
982
983         while (!last_loop) {
984                 LIST_HEAD(for_daemon_pages);
985                 int for_daemon_pages_count = 0;
986                 schedule_timeout_interruptible(cfs_time_seconds(1));
987                 if (kthread_should_stop())
988                         last_loop = 1;
989                 collect_pages(&pc);
990                 if (list_empty(&pc.pc_pages))
991                         continue;
992
993                 filp = NULL;
994                 down_read(&cfs_tracefile_sem);
995                 if (cfs_tracefile[0] != 0) {
996                         filp = filp_open(cfs_tracefile,
997                                          O_CREAT | O_RDWR | O_LARGEFILE,
998                                          0600);
999                         if (IS_ERR(filp)) {
1000                                 rc = PTR_ERR(filp);
1001                                 filp = NULL;
1002                                 pr_warn("Lustre: couldn't open %s: rc = %d\n",
1003                                         cfs_tracefile, rc);
1004                         }
1005                 }
1006                 up_read(&cfs_tracefile_sem);
1007
1008                 list_for_each_entry_safe(tage, tmp, &pc.pc_pages, linkage) {
1009                         __LASSERT_TAGE_INVARIANT(tage);
1010
1011                         if (filp) {
1012                                 struct dentry *de = file_dentry(filp);
1013                                 static loff_t f_pos;
1014
1015                                 if (f_pos >= (off_t)cfs_tracefile_size)
1016                                         f_pos = 0;
1017                                 else if (f_pos > i_size_read(de->d_inode))
1018                                         f_pos = i_size_read(de->d_inode);
1019
1020                                 buf = kmap(tage->page);
1021                                 rc = cfs_kernel_write(filp, buf, tage->used,
1022                                                       &f_pos);
1023                                 kunmap(tage->page);
1024                                 if (rc != (int)tage->used) {
1025                                         pr_warn("Lustre: wanted to write %u but wrote %d\n",
1026                                                 tage->used, rc);
1027                                         put_pages_back(&pc);
1028                                         __LASSERT(list_empty(&pc.pc_pages));
1029                                         break;
1030                                 }
1031                         }
1032                         list_del_init(&tage->linkage);
1033                         list_add_tail(&tage->page->lru, &for_daemon_pages);
1034                         for_daemon_pages_count += 1;
1035
1036                         tage->page->private = (int)tage->used;
1037                         kfree(tage);
1038                         atomic_dec(&cfs_tage_allocated);
1039                 }
1040
1041                 if (filp)
1042                         filp_close(filp, NULL);
1043
1044                 down_write(&cfs_tracefile_sem);
1045                 list_splice_tail(&for_daemon_pages, &daemon_pages);
1046                 daemon_pages_count += for_daemon_pages_count;
1047                 while (daemon_pages_count > daemon_pages_max) {
1048                         struct page *p = list_first_entry(&daemon_pages,
1049                                                           struct page, lru);
1050                         list_del(&p->lru);
1051                         put_page(p);
1052                         daemon_pages_count -= 1;
1053                 }
1054                 up_write(&cfs_tracefile_sem);
1055
1056                 if (!list_empty(&pc.pc_pages)) {
1057                         int i;
1058
1059                         pr_alert("Lustre: trace pages aren't empty\n");
1060                         pr_err("Lustre: total cpus(%d): ", num_possible_cpus());
1061                         for (i = 0; i < num_possible_cpus(); i++)
1062                                 if (cpu_online(i))
1063                                         pr_cont("%d(on) ", i);
1064                                 else
1065                                         pr_cont("%d(off) ", i);
1066                         pr_cont("\n");
1067
1068                         i = 0;
1069                         list_for_each_entry_safe(tage, tmp, &pc.pc_pages,
1070                                                  linkage)
1071                                 pr_err("Lustre: page %d belongs to cpu %d\n",
1072                                        ++i, tage->cpu);
1073                         pr_err("Lustre: There are %d pages unwritten\n", i);
1074                 }
1075                 __LASSERT(list_empty(&pc.pc_pages));
1076         }
1077
1078         return 0;
1079 }
1080
1081 int cfs_trace_start_thread(void)
1082 {
1083         struct task_struct *tsk;
1084         int rc = 0;
1085
1086         if (tctl_task)
1087                 return 0;
1088
1089         tsk = kthread_create(tracefiled, NULL, "ktracefiled");
1090         if (IS_ERR(tsk))
1091                 rc = -ECHILD;
1092         else if (cmpxchg(&tctl_task, NULL, tsk) != NULL)
1093                 /* already running */
1094                 kthread_stop(tsk);
1095         else
1096                 wake_up_process(tsk);
1097
1098         return rc;
1099 }
1100
1101 void cfs_trace_stop_thread(void)
1102 {
1103         struct task_struct *tsk;
1104
1105         tsk = xchg(&tctl_task, NULL);
1106         if (tsk) {
1107                 pr_info("Lustre: shutting down debug daemon thread...\n");
1108                 kthread_stop(tsk);
1109         }
1110 }
1111
1112 /* percents to share the total debug memory for each type */
1113 static unsigned int pages_factor[CFS_TCD_TYPE_CNT] = {
1114         80, /* 80% pages for CFS_TCD_TYPE_PROC */
1115         10, /* 10% pages for CFS_TCD_TYPE_SOFTIRQ */
1116         10  /* 10% pages for CFS_TCD_TYPE_IRQ */
1117 };
1118
1119 int cfs_tracefile_init(int max_pages)
1120 {
1121         struct cfs_trace_cpu_data *tcd;
1122         int i;
1123         int j;
1124
1125         /* initialize trace_data */
1126         memset(cfs_trace_data, 0, sizeof(cfs_trace_data));
1127         for (i = 0; i < CFS_TCD_TYPE_CNT; i++) {
1128                 cfs_trace_data[i] =
1129                         kmalloc_array(num_possible_cpus(),
1130                                       sizeof(union cfs_trace_data_union),
1131                                       GFP_KERNEL);
1132                 if (!cfs_trace_data[i])
1133                         goto out_trace_data;
1134         }
1135
1136         /* arch related info initialized */
1137         cfs_tcd_for_each(tcd, i, j) {
1138                 int factor = pages_factor[i];
1139
1140                 spin_lock_init(&tcd->tcd_lock);
1141                 tcd->tcd_pages_factor = factor;
1142                 tcd->tcd_type = i;
1143                 tcd->tcd_cpu = j;
1144
1145                 INIT_LIST_HEAD(&tcd->tcd_pages);
1146                 INIT_LIST_HEAD(&tcd->tcd_stock_pages);
1147                 tcd->tcd_cur_pages = 0;
1148                 tcd->tcd_cur_stock_pages = 0;
1149                 tcd->tcd_max_pages = (max_pages * factor) / 100;
1150                 LASSERT(tcd->tcd_max_pages > 0);
1151                 tcd->tcd_shutting_down = 0;
1152         }
1153         daemon_pages_max = max_pages;
1154
1155         return 0;
1156
1157 out_trace_data:
1158         for (i = 0; cfs_trace_data[i]; i++) {
1159                 kfree(cfs_trace_data[i]);
1160                 cfs_trace_data[i] = NULL;
1161         }
1162         pr_err("lnet: Not enough memory\n");
1163         return -ENOMEM;
1164 }
1165
1166 static void trace_cleanup_on_all_cpus(void)
1167 {
1168         struct cfs_trace_cpu_data *tcd;
1169         struct cfs_trace_page *tage;
1170         int i, cpu;
1171
1172         for_each_possible_cpu(cpu) {
1173                 cfs_tcd_for_each_type_lock(tcd, i, cpu) {
1174                         if (!tcd->tcd_pages_factor)
1175                                 /* Not initialised */
1176                                 continue;
1177                         tcd->tcd_shutting_down = 1;
1178
1179                         while (!list_empty(&tcd->tcd_pages)) {
1180                                 tage = list_first_entry(&tcd->tcd_pages,
1181                                                         struct cfs_trace_page,
1182                                                         linkage);
1183                                 __LASSERT_TAGE_INVARIANT(tage);
1184
1185                                 list_del(&tage->linkage);
1186                                 cfs_tage_free(tage);
1187                         }
1188                         tcd->tcd_cur_pages = 0;
1189                 }
1190         }
1191 }
1192
1193 static void cfs_trace_cleanup(void)
1194 {
1195         struct page_collection pc;
1196         int i;
1197
1198         INIT_LIST_HEAD(&pc.pc_pages);
1199
1200         trace_cleanup_on_all_cpus();
1201
1202         for (i = 0; i < CFS_TCD_TYPE_CNT && cfs_trace_data[i]; i++) {
1203                 kfree(cfs_trace_data[i]);
1204                 cfs_trace_data[i] = NULL;
1205         }
1206 }
1207
1208 void cfs_tracefile_exit(void)
1209 {
1210         cfs_trace_stop_thread();
1211         cfs_trace_flush_pages();
1212         cfs_trace_cleanup();
1213 }