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