]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/staging/lustre/lnet/libcfs/tracefile.c
staging: lustre: libcfs: Prevent harmless read underflow
[linux.git] / drivers / staging / lustre / lnet / libcfs / tracefile.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * GPL HEADER START
4  *
5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 only,
9  * as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License version 2 for more details (a copy is included
15  * in the LICENSE file that accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License
18  * version 2 along with this program; If not, see
19  * http://www.gnu.org/licenses/gpl-2.0.html
20  *
21  * GPL HEADER END
22  */
23 /*
24  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Use is subject to license terms.
26  *
27  * Copyright (c) 2012, Intel Corporation.
28  */
29 /*
30  * This file is part of Lustre, http://www.lustre.org/
31  * Lustre is a trademark of Sun Microsystems, Inc.
32  *
33  * libcfs/libcfs/tracefile.c
34  *
35  * Author: Zach Brown <zab@clusterfs.com>
36  * Author: Phil Schwan <phil@clusterfs.com>
37  */
38
39 #define DEBUG_SUBSYSTEM S_LNET
40 #define LUSTRE_TRACEFILE_PRIVATE
41 #define pr_fmt(fmt) "Lustre: " fmt
42 #include "tracefile.h"
43
44 #include <linux/libcfs/libcfs.h>
45
46 /* XXX move things up to the top, comment */
47 union cfs_trace_data_union (*cfs_trace_data[TCD_MAX_TYPES])[NR_CPUS] __cacheline_aligned;
48
49 char cfs_tracefile[TRACEFILE_NAME_SIZE];
50 long long cfs_tracefile_size = CFS_TRACEFILE_SIZE;
51 static struct tracefiled_ctl trace_tctl;
52 static DEFINE_MUTEX(cfs_trace_thread_mutex);
53 static int thread_running;
54
55 static atomic_t cfs_tage_allocated = ATOMIC_INIT(0);
56
57 struct page_collection {
58         struct list_head        pc_pages;
59         /*
60          * if this flag is set, collect_pages() will spill both
61          * ->tcd_daemon_pages and ->tcd_pages to the ->pc_pages. Otherwise,
62          * only ->tcd_pages are spilled.
63          */
64         int                     pc_want_daemon_pages;
65 };
66
67 struct tracefiled_ctl {
68         struct completion       tctl_start;
69         struct completion       tctl_stop;
70         wait_queue_head_t       tctl_waitq;
71         pid_t                   tctl_pid;
72         atomic_t                tctl_shutdown;
73 };
74
75 /*
76  * small data-structure for each page owned by tracefiled.
77  */
78 struct cfs_trace_page {
79         /*
80          * page itself
81          */
82         struct page             *page;
83         /*
84          * linkage into one of the lists in trace_data_union or
85          * page_collection
86          */
87         struct list_head        linkage;
88         /*
89          * number of bytes used within this page
90          */
91         unsigned int            used;
92         /*
93          * cpu that owns this page
94          */
95         unsigned short          cpu;
96         /*
97          * type(context) of this page
98          */
99         unsigned short          type;
100 };
101
102 static void put_pages_on_tcd_daemon_list(struct page_collection *pc,
103                                          struct cfs_trace_cpu_data *tcd);
104
105 static inline struct cfs_trace_page *
106 cfs_tage_from_list(struct list_head *list)
107 {
108         return list_entry(list, struct cfs_trace_page, linkage);
109 }
110
111 static struct cfs_trace_page *cfs_tage_alloc(gfp_t gfp)
112 {
113         struct page *page;
114         struct cfs_trace_page *tage;
115
116         /* My caller is trying to free memory */
117         if (!in_interrupt() && memory_pressure_get())
118                 return NULL;
119
120         /*
121          * Don't spam console with allocation failures: they will be reported
122          * by upper layer anyway.
123          */
124         gfp |= __GFP_NOWARN;
125         page = alloc_page(gfp);
126         if (!page)
127                 return NULL;
128
129         tage = kmalloc(sizeof(*tage), gfp);
130         if (!tage) {
131                 __free_page(page);
132                 return NULL;
133         }
134
135         tage->page = page;
136         atomic_inc(&cfs_tage_allocated);
137         return tage;
138 }
139
140 static void cfs_tage_free(struct cfs_trace_page *tage)
141 {
142         __free_page(tage->page);
143         kfree(tage);
144         atomic_dec(&cfs_tage_allocated);
145 }
146
147 static void cfs_tage_to_tail(struct cfs_trace_page *tage,
148                              struct list_head *queue)
149 {
150         list_move_tail(&tage->linkage, queue);
151 }
152
153 int cfs_trace_refill_stock(struct cfs_trace_cpu_data *tcd, gfp_t gfp,
154                            struct list_head *stock)
155 {
156         int i;
157
158         /*
159          * XXX nikita: do NOT call portals_debug_msg() (CDEBUG/ENTRY/EXIT)
160          * from here: this will lead to infinite recursion.
161          */
162
163         for (i = 0; i + tcd->tcd_cur_stock_pages < TCD_STOCK_PAGES ; ++i) {
164                 struct cfs_trace_page *tage;
165
166                 tage = cfs_tage_alloc(gfp);
167                 if (!tage)
168                         break;
169                 list_add_tail(&tage->linkage, stock);
170         }
171         return i;
172 }
173
174 /* return a page that has 'len' bytes left at the end */
175 static struct cfs_trace_page *
176 cfs_trace_get_tage_try(struct cfs_trace_cpu_data *tcd, unsigned long len)
177 {
178         struct cfs_trace_page *tage;
179
180         if (tcd->tcd_cur_pages > 0) {
181                 __LASSERT(!list_empty(&tcd->tcd_pages));
182                 tage = cfs_tage_from_list(tcd->tcd_pages.prev);
183                 if (tage->used + len <= PAGE_SIZE)
184                         return tage;
185         }
186
187         if (tcd->tcd_cur_pages < tcd->tcd_max_pages) {
188                 if (tcd->tcd_cur_stock_pages > 0) {
189                         tage = cfs_tage_from_list(tcd->tcd_stock_pages.prev);
190                         --tcd->tcd_cur_stock_pages;
191                         list_del_init(&tage->linkage);
192                 } else {
193                         tage = cfs_tage_alloc(GFP_ATOMIC);
194                         if (unlikely(!tage)) {
195                                 if (!memory_pressure_get() || in_interrupt())
196                                         pr_warn_ratelimited("cannot allocate a tage (%ld)\n",
197                                                             tcd->tcd_cur_pages);
198                                 return NULL;
199                         }
200                 }
201
202                 tage->used = 0;
203                 tage->cpu = smp_processor_id();
204                 tage->type = tcd->tcd_type;
205                 list_add_tail(&tage->linkage, &tcd->tcd_pages);
206                 tcd->tcd_cur_pages++;
207
208                 if (tcd->tcd_cur_pages > 8 && thread_running) {
209                         struct tracefiled_ctl *tctl = &trace_tctl;
210                         /*
211                          * wake up tracefiled to process some pages.
212                          */
213                         wake_up(&tctl->tctl_waitq);
214                 }
215                 return tage;
216         }
217         return NULL;
218 }
219
220 static void cfs_tcd_shrink(struct cfs_trace_cpu_data *tcd)
221 {
222         int pgcount = tcd->tcd_cur_pages / 10;
223         struct page_collection pc;
224         struct cfs_trace_page *tage;
225         struct cfs_trace_page *tmp;
226
227         /*
228          * XXX nikita: do NOT call portals_debug_msg() (CDEBUG/ENTRY/EXIT)
229          * from here: this will lead to infinite recursion.
230          */
231
232         pr_warn_ratelimited("debug daemon buffer overflowed; discarding 10%% of pages (%d of %ld)\n",
233                             pgcount + 1, tcd->tcd_cur_pages);
234
235         INIT_LIST_HEAD(&pc.pc_pages);
236
237         list_for_each_entry_safe(tage, tmp, &tcd->tcd_pages, linkage) {
238                 if (!pgcount--)
239                         break;
240
241                 list_move_tail(&tage->linkage, &pc.pc_pages);
242                 tcd->tcd_cur_pages--;
243         }
244         put_pages_on_tcd_daemon_list(&pc, tcd);
245 }
246
247 /* return a page that has 'len' bytes left at the end */
248 static struct cfs_trace_page *cfs_trace_get_tage(struct cfs_trace_cpu_data *tcd,
249                                                  unsigned long len)
250 {
251         struct cfs_trace_page *tage;
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 (len > PAGE_SIZE) {
259                 pr_err("cowardly refusing to write %lu bytes in a page\n", len);
260                 return NULL;
261         }
262
263         tage = cfs_trace_get_tage_try(tcd, len);
264         if (tage)
265                 return tage;
266         if (thread_running)
267                 cfs_tcd_shrink(tcd);
268         if (tcd->tcd_cur_pages > 0) {
269                 tage = cfs_tage_from_list(tcd->tcd_pages.next);
270                 tage->used = 0;
271                 cfs_tage_to_tail(tage, &tcd->tcd_pages);
272         }
273         return tage;
274 }
275
276 int libcfs_debug_msg(struct libcfs_debug_msg_data *msgdata,
277                      const char *format, ...)
278 {
279         va_list args;
280         int rc;
281
282         va_start(args, format);
283         rc = libcfs_debug_vmsg2(msgdata, format, args, NULL);
284         va_end(args);
285
286         return rc;
287 }
288 EXPORT_SYMBOL(libcfs_debug_msg);
289
290 int libcfs_debug_vmsg2(struct libcfs_debug_msg_data *msgdata,
291                        const char *format1, va_list args,
292                        const char *format2, ...)
293 {
294         struct cfs_trace_cpu_data *tcd = NULL;
295         struct ptldebug_header header = { 0 };
296         struct cfs_trace_page *tage;
297         /* string_buf is used only if tcd != NULL, and is always set then */
298         char *string_buf = NULL;
299         char *debug_buf;
300         int known_size;
301         int needed = 85; /* average message length */
302         int max_nob;
303         va_list ap;
304         int depth;
305         int i;
306         int remain;
307         int mask = msgdata->msg_mask;
308         const char *file = kbasename(msgdata->msg_file);
309         struct cfs_debug_limit_state *cdls = msgdata->msg_cdls;
310
311         tcd = cfs_trace_get_tcd();
312
313         /* cfs_trace_get_tcd() grabs a lock, which disables preemption and
314          * pins us to a particular CPU.  This avoids an smp_processor_id()
315          * warning on Linux when debugging is enabled.
316          */
317         cfs_set_ptldebug_header(&header, msgdata, CDEBUG_STACK());
318
319         if (!tcd)               /* arch may not log in IRQ context */
320                 goto console;
321
322         if (!tcd->tcd_cur_pages)
323                 header.ph_flags |= PH_FLAG_FIRST_RECORD;
324
325         if (tcd->tcd_shutting_down) {
326                 cfs_trace_put_tcd(tcd);
327                 tcd = NULL;
328                 goto console;
329         }
330
331         depth = __current_nesting_level();
332         known_size = strlen(file) + 1 + depth;
333         if (msgdata->msg_fn)
334                 known_size += strlen(msgdata->msg_fn) + 1;
335
336         if (libcfs_debug_binary)
337                 known_size += sizeof(header);
338
339         /*
340          * '2' used because vsnprintf return real size required for output
341          * _without_ terminating NULL.
342          * if needed is to small for this format.
343          */
344         for (i = 0; i < 2; i++) {
345                 tage = cfs_trace_get_tage(tcd, needed + known_size + 1);
346                 if (!tage) {
347                         if (needed + known_size > PAGE_SIZE)
348                                 mask |= D_ERROR;
349
350                         cfs_trace_put_tcd(tcd);
351                         tcd = NULL;
352                         goto console;
353                 }
354
355                 string_buf = (char *)page_address(tage->page) +
356                                         tage->used + known_size;
357
358                 max_nob = PAGE_SIZE - tage->used - known_size;
359                 if (max_nob <= 0) {
360                         pr_emerg("negative max_nob: %d\n", max_nob);
361                         mask |= D_ERROR;
362                         cfs_trace_put_tcd(tcd);
363                         tcd = NULL;
364                         goto console;
365                 }
366
367                 needed = 0;
368                 if (format1) {
369                         va_copy(ap, args);
370                         needed = vsnprintf(string_buf, max_nob, format1, ap);
371                         va_end(ap);
372                 }
373
374                 if (format2) {
375                         remain = max_nob - needed;
376                         if (remain < 0)
377                                 remain = 0;
378
379                         va_start(ap, format2);
380                         needed += vsnprintf(string_buf + needed, remain,
381                                             format2, ap);
382                         va_end(ap);
383                 }
384
385                 if (needed < max_nob) /* well. printing ok.. */
386                         break;
387         }
388
389         if (*(string_buf + needed - 1) != '\n')
390                 pr_info("format at %s:%d:%s doesn't end in newline\n", file,
391                         msgdata->msg_line, msgdata->msg_fn);
392
393         header.ph_len = known_size + needed;
394         debug_buf = (char *)page_address(tage->page) + tage->used;
395
396         if (libcfs_debug_binary) {
397                 memcpy(debug_buf, &header, sizeof(header));
398                 tage->used += sizeof(header);
399                 debug_buf += sizeof(header);
400         }
401
402         /* indent message according to the nesting level */
403         while (depth-- > 0) {
404                 *(debug_buf++) = '.';
405                 ++tage->used;
406         }
407
408         strcpy(debug_buf, file);
409         tage->used += strlen(file) + 1;
410         debug_buf += strlen(file) + 1;
411
412         if (msgdata->msg_fn) {
413                 strcpy(debug_buf, msgdata->msg_fn);
414                 tage->used += strlen(msgdata->msg_fn) + 1;
415                 debug_buf += strlen(msgdata->msg_fn) + 1;
416         }
417
418         __LASSERT(debug_buf == string_buf);
419
420         tage->used += needed;
421         __LASSERT(tage->used <= PAGE_SIZE);
422
423 console:
424         if (!(mask & libcfs_printk)) {
425                 /* no console output requested */
426                 if (tcd)
427                         cfs_trace_put_tcd(tcd);
428                 return 1;
429         }
430
431         if (cdls) {
432                 if (libcfs_console_ratelimit &&
433                     cdls->cdls_next &&          /* not first time ever */
434                     !cfs_time_after(cfs_time_current(), cdls->cdls_next)) {
435                         /* skipping a console message */
436                         cdls->cdls_count++;
437                         if (tcd)
438                                 cfs_trace_put_tcd(tcd);
439                         return 1;
440                 }
441
442                 if (cfs_time_after(cfs_time_current(),
443                                    cdls->cdls_next + libcfs_console_max_delay +
444                                    cfs_time_seconds(10))) {
445                         /* last timeout was a long time ago */
446                         cdls->cdls_delay /= libcfs_console_backoff * 4;
447                 } else {
448                         cdls->cdls_delay *= libcfs_console_backoff;
449                 }
450
451                 if (cdls->cdls_delay < libcfs_console_min_delay)
452                         cdls->cdls_delay = libcfs_console_min_delay;
453                 else if (cdls->cdls_delay > libcfs_console_max_delay)
454                         cdls->cdls_delay = libcfs_console_max_delay;
455
456                 /* ensure cdls_next is never zero after it's been seen */
457                 cdls->cdls_next = (cfs_time_current() + cdls->cdls_delay) | 1;
458         }
459
460         if (tcd) {
461                 cfs_print_to_console(&header, mask, string_buf, needed, file,
462                                      msgdata->msg_fn);
463                 cfs_trace_put_tcd(tcd);
464         } else {
465                 string_buf = cfs_trace_get_console_buffer();
466
467                 needed = 0;
468                 if (format1) {
469                         va_copy(ap, args);
470                         needed = vsnprintf(string_buf,
471                                            CFS_TRACE_CONSOLE_BUFFER_SIZE,
472                                            format1, ap);
473                         va_end(ap);
474                 }
475                 if (format2) {
476                         remain = CFS_TRACE_CONSOLE_BUFFER_SIZE - needed;
477                         if (remain > 0) {
478                                 va_start(ap, format2);
479                                 needed += vsnprintf(string_buf + needed, remain,
480                                                     format2, ap);
481                                 va_end(ap);
482                         }
483                 }
484                 cfs_print_to_console(&header, mask,
485                                      string_buf, needed, file, msgdata->msg_fn);
486
487                 put_cpu();
488         }
489
490         if (cdls && cdls->cdls_count) {
491                 string_buf = cfs_trace_get_console_buffer();
492
493                 needed = snprintf(string_buf, CFS_TRACE_CONSOLE_BUFFER_SIZE,
494                                   "Skipped %d previous similar message%s\n",
495                                   cdls->cdls_count,
496                                   (cdls->cdls_count > 1) ? "s" : "");
497
498                 cfs_print_to_console(&header, mask,
499                                      string_buf, needed, file, msgdata->msg_fn);
500
501                 put_cpu();
502                 cdls->cdls_count = 0;
503         }
504
505         return 0;
506 }
507 EXPORT_SYMBOL(libcfs_debug_vmsg2);
508
509 void
510 cfs_trace_assertion_failed(const char *str,
511                            struct libcfs_debug_msg_data *msgdata)
512 {
513         struct ptldebug_header hdr;
514
515         libcfs_panic_in_progress = 1;
516         libcfs_catastrophe = 1;
517         mb();
518
519         cfs_set_ptldebug_header(&hdr, msgdata, CDEBUG_STACK());
520
521         cfs_print_to_console(&hdr, D_EMERG, str, strlen(str),
522                              msgdata->msg_file, msgdata->msg_fn);
523
524         panic("Lustre debug assertion failure\n");
525
526         /* not reached */
527 }
528
529 static void
530 panic_collect_pages(struct page_collection *pc)
531 {
532         /* Do the collect_pages job on a single CPU: assumes that all other
533          * CPUs have been stopped during a panic.  If this isn't true for some
534          * arch, this will have to be implemented separately in each arch.
535          */
536         struct cfs_trace_cpu_data *tcd;
537         int i;
538         int j;
539
540         INIT_LIST_HEAD(&pc->pc_pages);
541
542         cfs_tcd_for_each(tcd, i, j) {
543                 list_splice_init(&tcd->tcd_pages, &pc->pc_pages);
544                 tcd->tcd_cur_pages = 0;
545
546                 if (pc->pc_want_daemon_pages) {
547                         list_splice_init(&tcd->tcd_daemon_pages, &pc->pc_pages);
548                         tcd->tcd_cur_daemon_pages = 0;
549                 }
550         }
551 }
552
553 static void collect_pages_on_all_cpus(struct page_collection *pc)
554 {
555         struct cfs_trace_cpu_data *tcd;
556         int i, cpu;
557
558         for_each_possible_cpu(cpu) {
559                 cfs_tcd_for_each_type_lock(tcd, i, cpu) {
560                         list_splice_init(&tcd->tcd_pages, &pc->pc_pages);
561                         tcd->tcd_cur_pages = 0;
562                         if (pc->pc_want_daemon_pages) {
563                                 list_splice_init(&tcd->tcd_daemon_pages,
564                                                  &pc->pc_pages);
565                                 tcd->tcd_cur_daemon_pages = 0;
566                         }
567                 }
568         }
569 }
570
571 static void collect_pages(struct page_collection *pc)
572 {
573         INIT_LIST_HEAD(&pc->pc_pages);
574
575         if (libcfs_panic_in_progress)
576                 panic_collect_pages(pc);
577         else
578                 collect_pages_on_all_cpus(pc);
579 }
580
581 static void put_pages_back_on_all_cpus(struct page_collection *pc)
582 {
583         struct cfs_trace_cpu_data *tcd;
584         struct list_head *cur_head;
585         struct cfs_trace_page *tage;
586         struct cfs_trace_page *tmp;
587         int i, cpu;
588
589         for_each_possible_cpu(cpu) {
590                 cfs_tcd_for_each_type_lock(tcd, i, cpu) {
591                         cur_head = tcd->tcd_pages.next;
592
593                         list_for_each_entry_safe(tage, tmp, &pc->pc_pages,
594                                                  linkage) {
595                                 __LASSERT_TAGE_INVARIANT(tage);
596
597                                 if (tage->cpu != cpu || tage->type != i)
598                                         continue;
599
600                                 cfs_tage_to_tail(tage, cur_head);
601                                 tcd->tcd_cur_pages++;
602                         }
603                 }
604         }
605 }
606
607 static void put_pages_back(struct page_collection *pc)
608 {
609         if (!libcfs_panic_in_progress)
610                 put_pages_back_on_all_cpus(pc);
611 }
612
613 /* Add pages to a per-cpu debug daemon ringbuffer.  This buffer makes sure that
614  * we have a good amount of data at all times for dumping during an LBUG, even
615  * if we have been steadily writing (and otherwise discarding) pages via the
616  * debug daemon.
617  */
618 static void put_pages_on_tcd_daemon_list(struct page_collection *pc,
619                                          struct cfs_trace_cpu_data *tcd)
620 {
621         struct cfs_trace_page *tage;
622         struct cfs_trace_page *tmp;
623
624         list_for_each_entry_safe(tage, tmp, &pc->pc_pages, linkage) {
625                 __LASSERT_TAGE_INVARIANT(tage);
626
627                 if (tage->cpu != tcd->tcd_cpu || tage->type != tcd->tcd_type)
628                         continue;
629
630                 cfs_tage_to_tail(tage, &tcd->tcd_daemon_pages);
631                 tcd->tcd_cur_daemon_pages++;
632
633                 if (tcd->tcd_cur_daemon_pages > tcd->tcd_max_pages) {
634                         struct cfs_trace_page *victim;
635
636                         __LASSERT(!list_empty(&tcd->tcd_daemon_pages));
637                         victim = cfs_tage_from_list(tcd->tcd_daemon_pages.next);
638
639                         __LASSERT_TAGE_INVARIANT(victim);
640
641                         list_del(&victim->linkage);
642                         cfs_tage_free(victim);
643                         tcd->tcd_cur_daemon_pages--;
644                 }
645         }
646 }
647
648 static void put_pages_on_daemon_list(struct page_collection *pc)
649 {
650         struct cfs_trace_cpu_data *tcd;
651         int i, cpu;
652
653         for_each_possible_cpu(cpu) {
654                 cfs_tcd_for_each_type_lock(tcd, i, cpu)
655                         put_pages_on_tcd_daemon_list(pc, tcd);
656         }
657 }
658
659 void cfs_trace_debug_print(void)
660 {
661         struct page_collection pc;
662         struct cfs_trace_page *tage;
663         struct cfs_trace_page *tmp;
664
665         pc.pc_want_daemon_pages = 1;
666         collect_pages(&pc);
667         list_for_each_entry_safe(tage, tmp, &pc.pc_pages, linkage) {
668                 char *p, *file, *fn;
669                 struct page *page;
670
671                 __LASSERT_TAGE_INVARIANT(tage);
672
673                 page = tage->page;
674                 p = page_address(page);
675                 while (p < ((char *)page_address(page) + tage->used)) {
676                         struct ptldebug_header *hdr;
677                         int len;
678
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, p, len, file, fn);
688
689                         p += len;
690                 }
691
692                 list_del(&tage->linkage);
693                 cfs_tage_free(tage);
694         }
695 }
696
697 int cfs_tracefile_dump_all_pages(char *filename)
698 {
699         struct page_collection pc;
700         struct file *filp;
701         struct cfs_trace_page *tage;
702         struct cfs_trace_page *tmp;
703         char *buf;
704         mm_segment_t __oldfs;
705         int rc;
706
707         cfs_tracefile_write_lock();
708
709         filp = filp_open(filename, O_CREAT | O_EXCL | O_WRONLY | O_LARGEFILE,
710                          0600);
711         if (IS_ERR(filp)) {
712                 rc = PTR_ERR(filp);
713                 filp = NULL;
714                 pr_err("LustreError: can't open %s for dump: rc %d\n",
715                        filename, rc);
716                 goto out;
717         }
718
719         pc.pc_want_daemon_pages = 1;
720         collect_pages(&pc);
721         if (list_empty(&pc.pc_pages)) {
722                 rc = 0;
723                 goto close;
724         }
725         __oldfs = get_fs();
726         set_fs(get_ds());
727
728         /* ok, for now, just write the pages.  in the future we'll be building
729          * iobufs with the pages and calling generic_direct_IO
730          */
731         list_for_each_entry_safe(tage, tmp, &pc.pc_pages, linkage) {
732                 __LASSERT_TAGE_INVARIANT(tage);
733
734                 buf = kmap(tage->page);
735                 rc = kernel_write(filp, buf, tage->used, &filp->f_pos);
736                 kunmap(tage->page);
737
738                 if (rc != (int)tage->used) {
739                         pr_warn("wanted to write %u but wrote %d\n", tage->used,
740                                 rc);
741                         put_pages_back(&pc);
742                         __LASSERT(list_empty(&pc.pc_pages));
743                         break;
744                 }
745                 list_del(&tage->linkage);
746                 cfs_tage_free(tage);
747         }
748         set_fs(__oldfs);
749         rc = vfs_fsync(filp, 1);
750         if (rc)
751                 pr_err("sync returns %d\n", rc);
752 close:
753         filp_close(filp, NULL);
754 out:
755         cfs_tracefile_write_unlock();
756         return rc;
757 }
758
759 void cfs_trace_flush_pages(void)
760 {
761         struct page_collection pc;
762         struct cfs_trace_page *tage;
763         struct cfs_trace_page *tmp;
764
765         pc.pc_want_daemon_pages = 1;
766         collect_pages(&pc);
767         list_for_each_entry_safe(tage, tmp, &pc.pc_pages, linkage) {
768                 __LASSERT_TAGE_INVARIANT(tage);
769
770                 list_del(&tage->linkage);
771                 cfs_tage_free(tage);
772         }
773 }
774
775 int cfs_trace_copyin_string(char *knl_buffer, int knl_buffer_nob,
776                             const char __user *usr_buffer, int usr_buffer_nob)
777 {
778         int nob;
779
780         if (usr_buffer_nob > knl_buffer_nob)
781                 return -EOVERFLOW;
782
783         if (copy_from_user((void *)knl_buffer,
784                            usr_buffer, usr_buffer_nob))
785                 return -EFAULT;
786
787         nob = strnlen(knl_buffer, usr_buffer_nob);
788         while (--nob >= 0)                    /* strip trailing whitespace */
789                 if (!isspace(knl_buffer[nob]))
790                         break;
791
792         if (nob < 0)                        /* empty string */
793                 return -EINVAL;
794
795         if (nob == knl_buffer_nob)            /* no space to terminate */
796                 return -EOVERFLOW;
797
798         knl_buffer[nob + 1] = 0;                /* terminate */
799         return 0;
800 }
801 EXPORT_SYMBOL(cfs_trace_copyin_string);
802
803 int cfs_trace_copyout_string(char __user *usr_buffer, int usr_buffer_nob,
804                              const char *knl_buffer, char *append)
805 {
806         /*
807          * NB if 'append' != NULL, it's a single character to append to the
808          * copied out string - usually "\n" or "" (i.e. a terminating zero byte)
809          */
810         int nob = strlen(knl_buffer);
811
812         if (nob > usr_buffer_nob)
813                 nob = usr_buffer_nob;
814
815         if (copy_to_user(usr_buffer, knl_buffer, nob))
816                 return -EFAULT;
817
818         if (append && nob < usr_buffer_nob) {
819                 if (copy_to_user(usr_buffer + nob, append, 1))
820                         return -EFAULT;
821
822                 nob++;
823         }
824
825         return nob;
826 }
827 EXPORT_SYMBOL(cfs_trace_copyout_string);
828
829 int cfs_trace_allocate_string_buffer(char **str, int nob)
830 {
831         if (nob > 2 * PAGE_SIZE)            /* string must be "sensible" */
832                 return -EINVAL;
833
834         *str = kmalloc(nob, GFP_KERNEL | __GFP_ZERO);
835         if (!*str)
836                 return -ENOMEM;
837
838         return 0;
839 }
840
841 int cfs_trace_dump_debug_buffer_usrstr(void __user *usr_str, int usr_str_nob)
842 {
843         char *str;
844         int rc;
845
846         rc = cfs_trace_allocate_string_buffer(&str, usr_str_nob + 1);
847         if (rc)
848                 return rc;
849
850         rc = cfs_trace_copyin_string(str, usr_str_nob + 1,
851                                      usr_str, usr_str_nob);
852         if (rc)
853                 goto out;
854
855         if (str[0] != '/') {
856                 rc = -EINVAL;
857                 goto out;
858         }
859         rc = cfs_tracefile_dump_all_pages(str);
860 out:
861         kfree(str);
862         return rc;
863 }
864
865 int cfs_trace_daemon_command(char *str)
866 {
867         int rc = 0;
868
869         cfs_tracefile_write_lock();
870
871         if (!strcmp(str, "stop")) {
872                 cfs_tracefile_write_unlock();
873                 cfs_trace_stop_thread();
874                 cfs_tracefile_write_lock();
875                 memset(cfs_tracefile, 0, sizeof(cfs_tracefile));
876
877         } else if (!strncmp(str, "size=", 5)) {
878                 unsigned long tmp;
879
880                 rc = kstrtoul(str + 5, 10, &tmp);
881                 if (!rc) {
882                         if (tmp < 10 || tmp > 20480)
883                                 cfs_tracefile_size = CFS_TRACEFILE_SIZE;
884                         else
885                                 cfs_tracefile_size = tmp << 20;
886                 }
887         } else if (strlen(str) >= sizeof(cfs_tracefile)) {
888                 rc = -ENAMETOOLONG;
889         } else if (str[0] != '/') {
890                 rc = -EINVAL;
891         } else {
892                 strcpy(cfs_tracefile, str);
893
894                 pr_info("debug daemon will attempt to start writing to %s (%lukB max)\n",
895                         cfs_tracefile,
896                         (long)(cfs_tracefile_size >> 10));
897
898                 cfs_trace_start_thread();
899         }
900
901         cfs_tracefile_write_unlock();
902         return rc;
903 }
904
905 int cfs_trace_daemon_command_usrstr(void __user *usr_str, int usr_str_nob)
906 {
907         char *str;
908         int rc;
909
910         rc = cfs_trace_allocate_string_buffer(&str, usr_str_nob + 1);
911         if (rc)
912                 return rc;
913
914         rc = cfs_trace_copyin_string(str, usr_str_nob + 1,
915                                      usr_str, usr_str_nob);
916         if (!rc)
917                 rc = cfs_trace_daemon_command(str);
918
919         kfree(str);
920         return rc;
921 }
922
923 int cfs_trace_set_debug_mb(int mb)
924 {
925         int i;
926         int j;
927         int pages;
928         int limit = cfs_trace_max_debug_mb();
929         struct cfs_trace_cpu_data *tcd;
930
931         if (mb < num_possible_cpus()) {
932                 pr_warn("%d MB is too small for debug buffer size, setting it to %d MB.\n",
933                         mb, num_possible_cpus());
934                 mb = num_possible_cpus();
935         }
936
937         if (mb > limit) {
938                 pr_warn("%d MB is too large for debug buffer size, setting it to %d MB.\n",
939                         mb, limit);
940                 mb = limit;
941         }
942
943         mb /= num_possible_cpus();
944         pages = mb << (20 - PAGE_SHIFT);
945
946         cfs_tracefile_write_lock();
947
948         cfs_tcd_for_each(tcd, i, j)
949                 tcd->tcd_max_pages = (pages * tcd->tcd_pages_factor) / 100;
950
951         cfs_tracefile_write_unlock();
952
953         return 0;
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         cfs_tracefile_read_lock();
964
965         cfs_tcd_for_each(tcd, i, j)
966                 total_pages += tcd->tcd_max_pages;
967
968         cfs_tracefile_read_unlock();
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 tracefiled_ctl *tctl = arg;
977         struct cfs_trace_page *tage;
978         struct cfs_trace_page *tmp;
979         struct file *filp;
980         char *buf;
981         int last_loop = 0;
982         int rc;
983
984         /* we're started late enough that we pick up init's fs context */
985         /* this is so broken in uml?  what on earth is going on? */
986
987         complete(&tctl->tctl_start);
988
989         while (1) {
990                 wait_queue_entry_t __wait;
991
992                 pc.pc_want_daemon_pages = 0;
993                 collect_pages(&pc);
994                 if (list_empty(&pc.pc_pages))
995                         goto end_loop;
996
997                 filp = NULL;
998                 cfs_tracefile_read_lock();
999                 if (cfs_tracefile[0]) {
1000                         filp = filp_open(cfs_tracefile,
1001                                          O_CREAT | O_RDWR | O_LARGEFILE,
1002                                          0600);
1003                         if (IS_ERR(filp)) {
1004                                 rc = PTR_ERR(filp);
1005                                 filp = NULL;
1006                                 pr_warn("couldn't open %s: %d\n", cfs_tracefile,
1007                                         rc);
1008                         }
1009                 }
1010                 cfs_tracefile_read_unlock();
1011                 if (!filp) {
1012                         put_pages_on_daemon_list(&pc);
1013                         __LASSERT(list_empty(&pc.pc_pages));
1014                         goto end_loop;
1015                 }
1016
1017                 list_for_each_entry_safe(tage, tmp, &pc.pc_pages, linkage) {
1018                         static loff_t f_pos;
1019
1020                         __LASSERT_TAGE_INVARIANT(tage);
1021
1022                         if (f_pos >= (off_t)cfs_tracefile_size)
1023                                 f_pos = 0;
1024                         else if (f_pos > i_size_read(file_inode(filp)))
1025                                 f_pos = i_size_read(file_inode(filp));
1026
1027                         buf = kmap(tage->page);
1028                         rc = kernel_write(filp, buf, tage->used, &f_pos);
1029                         kunmap(tage->page);
1030
1031                         if (rc != (int)tage->used) {
1032                                 pr_warn("wanted to write %u but wrote %d\n",
1033                                         tage->used, rc);
1034                                 put_pages_back(&pc);
1035                                 __LASSERT(list_empty(&pc.pc_pages));
1036                                 break;
1037                         }
1038                 }
1039
1040                 filp_close(filp, NULL);
1041                 put_pages_on_daemon_list(&pc);
1042                 if (!list_empty(&pc.pc_pages)) {
1043                         int i;
1044
1045                         pr_alert("trace pages aren't empty\n");
1046                         pr_err("total cpus(%d): ", num_possible_cpus());
1047                         for (i = 0; i < num_possible_cpus(); i++)
1048                                 if (cpu_online(i))
1049                                         pr_cont("%d(on) ", i);
1050                                 else
1051                                         pr_cont("%d(off) ", i);
1052                         pr_cont("\n");
1053
1054                         i = 0;
1055                         list_for_each_entry_safe(tage, tmp, &pc.pc_pages,
1056                                                  linkage)
1057                                 pr_err("page %d belongs to cpu %d\n",
1058                                        ++i, tage->cpu);
1059                         pr_err("There are %d pages unwritten\n", i);
1060                 }
1061                 __LASSERT(list_empty(&pc.pc_pages));
1062 end_loop:
1063                 if (atomic_read(&tctl->tctl_shutdown)) {
1064                         if (!last_loop) {
1065                                 last_loop = 1;
1066                                 continue;
1067                         } else {
1068                                 break;
1069                         }
1070                 }
1071                 init_waitqueue_entry(&__wait, current);
1072                 add_wait_queue(&tctl->tctl_waitq, &__wait);
1073                 set_current_state(TASK_INTERRUPTIBLE);
1074                 schedule_timeout(cfs_time_seconds(1));
1075                 remove_wait_queue(&tctl->tctl_waitq, &__wait);
1076         }
1077         complete(&tctl->tctl_stop);
1078         return 0;
1079 }
1080
1081 int cfs_trace_start_thread(void)
1082 {
1083         struct tracefiled_ctl *tctl = &trace_tctl;
1084         struct task_struct *task;
1085         int rc = 0;
1086
1087         mutex_lock(&cfs_trace_thread_mutex);
1088         if (thread_running)
1089                 goto out;
1090
1091         init_completion(&tctl->tctl_start);
1092         init_completion(&tctl->tctl_stop);
1093         init_waitqueue_head(&tctl->tctl_waitq);
1094         atomic_set(&tctl->tctl_shutdown, 0);
1095
1096         task = kthread_run(tracefiled, tctl, "ktracefiled");
1097         if (IS_ERR(task)) {
1098                 rc = PTR_ERR(task);
1099                 goto out;
1100         }
1101
1102         wait_for_completion(&tctl->tctl_start);
1103         thread_running = 1;
1104 out:
1105         mutex_unlock(&cfs_trace_thread_mutex);
1106         return rc;
1107 }
1108
1109 void cfs_trace_stop_thread(void)
1110 {
1111         struct tracefiled_ctl *tctl = &trace_tctl;
1112
1113         mutex_lock(&cfs_trace_thread_mutex);
1114         if (thread_running) {
1115                 pr_info("shutting down debug daemon thread...\n");
1116                 atomic_set(&tctl->tctl_shutdown, 1);
1117                 wait_for_completion(&tctl->tctl_stop);
1118                 thread_running = 0;
1119         }
1120         mutex_unlock(&cfs_trace_thread_mutex);
1121 }
1122
1123 int cfs_tracefile_init(int max_pages)
1124 {
1125         struct cfs_trace_cpu_data *tcd;
1126         int i;
1127         int j;
1128         int rc;
1129         int factor;
1130
1131         rc = cfs_tracefile_init_arch();
1132         if (rc)
1133                 return rc;
1134
1135         cfs_tcd_for_each(tcd, i, j) {
1136                 /* tcd_pages_factor is initialized int tracefile_init_arch. */
1137                 factor = tcd->tcd_pages_factor;
1138                 INIT_LIST_HEAD(&tcd->tcd_pages);
1139                 INIT_LIST_HEAD(&tcd->tcd_stock_pages);
1140                 INIT_LIST_HEAD(&tcd->tcd_daemon_pages);
1141                 tcd->tcd_cur_pages = 0;
1142                 tcd->tcd_cur_stock_pages = 0;
1143                 tcd->tcd_cur_daemon_pages = 0;
1144                 tcd->tcd_max_pages = (max_pages * factor) / 100;
1145                 LASSERT(tcd->tcd_max_pages > 0);
1146                 tcd->tcd_shutting_down = 0;
1147         }
1148
1149         return 0;
1150 }
1151
1152 static void trace_cleanup_on_all_cpus(void)
1153 {
1154         struct cfs_trace_cpu_data *tcd;
1155         struct cfs_trace_page *tage;
1156         struct cfs_trace_page *tmp;
1157         int i, cpu;
1158
1159         for_each_possible_cpu(cpu) {
1160                 cfs_tcd_for_each_type_lock(tcd, i, cpu) {
1161                         tcd->tcd_shutting_down = 1;
1162
1163                         list_for_each_entry_safe(tage, tmp, &tcd->tcd_pages,
1164                                                  linkage) {
1165                                 __LASSERT_TAGE_INVARIANT(tage);
1166
1167                                 list_del(&tage->linkage);
1168                                 cfs_tage_free(tage);
1169                         }
1170
1171                         tcd->tcd_cur_pages = 0;
1172                 }
1173         }
1174 }
1175
1176 static void cfs_trace_cleanup(void)
1177 {
1178         struct page_collection pc;
1179
1180         INIT_LIST_HEAD(&pc.pc_pages);
1181
1182         trace_cleanup_on_all_cpus();
1183
1184         cfs_tracefile_fini_arch();
1185 }
1186
1187 void cfs_tracefile_exit(void)
1188 {
1189         cfs_trace_stop_thread();
1190         cfs_trace_cleanup();
1191 }