Whamcloud - gitweb
5b9543e12da81c044f3a190c75d2c62c597fe34f
[fs/lustre-release.git] / libcfs / libcfs / tracefile.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * libcfs/libcfs/tracefile.c
37  *
38  * Author: Zach Brown <zab@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  */
41
42
43 #define DEBUG_SUBSYSTEM S_LNET
44 #define LUSTRE_TRACEFILE_PRIVATE
45 #include "tracefile.h"
46
47 #include <libcfs/libcfs.h>
48
49 /* XXX move things up to the top, comment */
50 union trace_data_union (*trace_data[TCD_MAX_TYPES])[NR_CPUS] __cacheline_aligned;
51
52 char tracefile[TRACEFILE_NAME_SIZE];
53 long long tracefile_size = TRACEFILE_SIZE;
54 static struct tracefiled_ctl trace_tctl;
55 struct semaphore trace_thread_sem;
56 static int thread_running = 0;
57
58 atomic_t tage_allocated = ATOMIC_INIT(0);
59
60 static void put_pages_on_tcd_daemon_list(struct page_collection *pc,
61                                          struct trace_cpu_data *tcd);
62
63 static inline struct trace_page *tage_from_list(struct list_head *list)
64 {
65         return list_entry(list, struct trace_page, linkage);
66 }
67
68 static struct trace_page *tage_alloc(int gfp)
69 {
70         cfs_page_t        *page;
71         struct trace_page *tage;
72
73         /*
74          * Don't spam console with allocation failures: they will be reported
75          * by upper layer anyway.
76          */
77         gfp |= CFS_ALLOC_NOWARN;
78         page = cfs_alloc_page(gfp);
79         if (page == NULL)
80                 return NULL;
81
82         tage = cfs_alloc(sizeof(*tage), gfp);
83         if (tage == NULL) {
84                 cfs_free_page(page);
85                 return NULL;
86         }
87
88         tage->page = page;
89         atomic_inc(&tage_allocated);
90         return tage;
91 }
92
93 static void tage_free(struct trace_page *tage)
94 {
95         __LASSERT(tage != NULL);
96         __LASSERT(tage->page != NULL);
97
98         cfs_free_page(tage->page);
99         cfs_free(tage);
100         atomic_dec(&tage_allocated);
101 }
102
103 static void tage_to_tail(struct trace_page *tage, struct list_head *queue)
104 {
105         __LASSERT(tage != NULL);
106         __LASSERT(queue != NULL);
107
108         list_move_tail(&tage->linkage, queue);
109 }
110
111 int trace_refill_stock(struct trace_cpu_data *tcd, int gfp,
112                        struct list_head *stock)
113 {
114         int i;
115
116         /*
117          * XXX nikita: do NOT call portals_debug_msg() (CDEBUG/ENTRY/EXIT)
118          * from here: this will lead to infinite recursion.
119          */
120
121         for (i = 0; i + tcd->tcd_cur_stock_pages < TCD_STOCK_PAGES ; ++ i) {
122                 struct trace_page *tage;
123
124                 tage = tage_alloc(gfp);
125                 if (tage == NULL)
126                         break;
127                 list_add_tail(&tage->linkage, stock);
128         }
129         return i;
130 }
131
132 /* return a page that has 'len' bytes left at the end */
133 static struct trace_page *trace_get_tage_try(struct trace_cpu_data *tcd,
134                                              unsigned long len)
135 {
136         struct trace_page *tage;
137
138         if (tcd->tcd_cur_pages > 0) {
139                 __LASSERT(!list_empty(&tcd->tcd_pages));
140                 tage = tage_from_list(tcd->tcd_pages.prev);
141                 if (tage->used + len <= CFS_PAGE_SIZE)
142                         return tage;
143         }
144
145         if (tcd->tcd_cur_pages < tcd->tcd_max_pages) {
146                 if (tcd->tcd_cur_stock_pages > 0) {
147                         tage = tage_from_list(tcd->tcd_stock_pages.prev);
148                         -- tcd->tcd_cur_stock_pages;
149                         list_del_init(&tage->linkage);
150                 } else {
151                         tage = tage_alloc(CFS_ALLOC_ATOMIC);
152                         if (tage == NULL) {
153                                 printk(KERN_WARNING
154                                        "failure to allocate a tage (%ld)\n",
155                                        tcd->tcd_cur_pages);
156                                 return NULL;
157                         }
158                 }
159
160                 tage->used = 0;
161                 tage->cpu = smp_processor_id();
162                 tage->type = tcd->tcd_type;
163                 list_add_tail(&tage->linkage, &tcd->tcd_pages);
164                 tcd->tcd_cur_pages++;
165
166                 if (tcd->tcd_cur_pages > 8 && thread_running) {
167                         struct tracefiled_ctl *tctl = &trace_tctl;
168                         /*
169                          * wake up tracefiled to process some pages.
170                          */
171                         cfs_waitq_signal(&tctl->tctl_waitq);
172                 }
173                 return tage;
174         }
175         return NULL;
176 }
177
178 static void tcd_shrink(struct trace_cpu_data *tcd)
179 {
180         int pgcount = tcd->tcd_cur_pages / 10;
181         struct page_collection pc;
182         struct trace_page *tage;
183         struct trace_page *tmp;
184
185         /*
186          * XXX nikita: do NOT call portals_debug_msg() (CDEBUG/ENTRY/EXIT)
187          * from here: this will lead to infinite recursion.
188          */
189
190         if (printk_ratelimit())
191                 printk(KERN_WARNING "debug daemon buffer overflowed; "
192                        "discarding 10%% of pages (%d of %ld)\n",
193                        pgcount + 1, tcd->tcd_cur_pages);
194
195         CFS_INIT_LIST_HEAD(&pc.pc_pages);
196         spin_lock_init(&pc.pc_lock);
197
198         cfs_list_for_each_entry_safe_typed(tage, tmp, &tcd->tcd_pages, 
199                                            struct trace_page, linkage) {
200                 if (pgcount-- == 0)
201                         break;
202
203                 list_move_tail(&tage->linkage, &pc.pc_pages);
204                 tcd->tcd_cur_pages--;
205         }
206         put_pages_on_tcd_daemon_list(&pc, tcd);
207 }
208
209 /* return a page that has 'len' bytes left at the end */
210 static struct trace_page *trace_get_tage(struct trace_cpu_data *tcd,
211                                          unsigned long len)
212 {
213         struct trace_page *tage;
214
215         /*
216          * XXX nikita: do NOT call portals_debug_msg() (CDEBUG/ENTRY/EXIT)
217          * from here: this will lead to infinite recursion.
218          */
219
220         if (len > CFS_PAGE_SIZE) {
221                 printk(KERN_ERR
222                        "cowardly refusing to write %lu bytes in a page\n", len);
223                 return NULL;
224         }
225
226         tage = trace_get_tage_try(tcd, len);
227         if (tage != NULL)
228                 return tage;
229         if (thread_running)
230                 tcd_shrink(tcd);
231         if (tcd->tcd_cur_pages > 0) {
232                 tage = tage_from_list(tcd->tcd_pages.next);
233                 tage->used = 0;
234                 tage_to_tail(tage, &tcd->tcd_pages);
235         }
236         return tage;
237 }
238
239 int libcfs_debug_vmsg2(cfs_debug_limit_state_t *cdls, int subsys, int mask,
240                        const char *file, const char *fn, const int line,
241                        const char *format1, va_list args,
242                        const char *format2, ...)
243 {
244         struct trace_cpu_data   *tcd = NULL;
245         struct ptldebug_header   header;
246         struct trace_page       *tage;
247         /* string_buf is used only if tcd != NULL, and is always set then */
248         char                    *string_buf = NULL;
249         char                    *debug_buf;
250         int                      known_size;
251         int                      needed = 85; /* average message length */
252         int                      max_nob;
253         va_list                  ap;
254         int                      depth;
255         int                      i;
256         int                      remain;
257
258         if (strchr(file, '/'))
259                 file = strrchr(file, '/') + 1;
260
261
262         set_ptldebug_header(&header, subsys, mask, line, CDEBUG_STACK());
263
264         tcd = trace_get_tcd();
265         if (tcd == NULL)                /* arch may not log in IRQ context */
266                 goto console;
267
268         if (tcd->tcd_shutting_down) {
269                 trace_put_tcd(tcd);
270                 tcd = NULL;
271                 goto console;
272         }
273
274         depth = __current_nesting_level();
275         known_size = strlen(file) + 1 + depth;
276         if (fn)
277                 known_size += strlen(fn) + 1;
278
279         if (libcfs_debug_binary)
280                 known_size += sizeof(header);
281
282         /*/
283          * '2' used because vsnprintf return real size required for output
284          * _without_ terminating NULL.
285          * if needed is to small for this format.
286          */
287         for (i = 0; i < 2; i++) {
288                 tage = trace_get_tage(tcd, needed + known_size + 1);
289                 if (tage == NULL) {
290                         if (needed + known_size > CFS_PAGE_SIZE)
291                                 mask |= D_ERROR;
292
293                         trace_put_tcd(tcd);
294                         tcd = NULL;
295                         goto console;
296                 }
297
298                 string_buf = (char *)cfs_page_address(tage->page) +
299                                         tage->used + known_size;
300
301                 max_nob = CFS_PAGE_SIZE - tage->used - known_size;
302                 if (max_nob <= 0) {
303                         printk(KERN_EMERG "negative max_nob: %i\n", max_nob);
304                         mask |= D_ERROR;
305                         trace_put_tcd(tcd);
306                         tcd = NULL;
307                         goto console;
308                 }
309
310                 needed = 0;
311                 if (format1) {
312                         va_copy(ap, args);
313                         needed = vsnprintf(string_buf, max_nob, format1, ap);
314                         va_end(ap);
315                 }
316
317                 if (format2) {
318                         remain = max_nob - needed;
319                         if (remain < 0)
320                                 remain = 0;
321
322                         va_start(ap, format2);
323                         needed += vsnprintf(string_buf + needed, remain,
324                                             format2, ap);
325                         va_end(ap);
326                 }
327
328                 if (needed < max_nob) /* well. printing ok.. */
329                         break;
330         }
331
332         if (*(string_buf+needed-1) != '\n')
333                 printk(KERN_INFO "format at %s:%d:%s doesn't end in newline\n",
334                        file, line, fn);
335
336         header.ph_len = known_size + needed;
337         debug_buf = (char *)cfs_page_address(tage->page) + tage->used;
338
339         if (libcfs_debug_binary) {
340                 memcpy(debug_buf, &header, sizeof(header));
341                 tage->used += sizeof(header);
342                 debug_buf += sizeof(header);
343         }
344
345         /* indent message according to the nesting level */
346         while (depth-- > 0) {
347                 *(debug_buf++) = '.';
348                 ++ tage->used;
349         }
350
351         strcpy(debug_buf, file);
352         tage->used += strlen(file) + 1;
353         debug_buf += strlen(file) + 1;
354
355         if (fn) {
356                 strcpy(debug_buf, fn);
357                 tage->used += strlen(fn) + 1;
358                 debug_buf += strlen(fn) + 1;
359         }
360
361         __LASSERT(debug_buf == string_buf);
362
363         tage->used += needed;
364         __LASSERT (tage->used <= CFS_PAGE_SIZE);
365
366 console:
367         if ((mask & libcfs_printk) == 0) {
368                 /* no console output requested */
369                 if (tcd != NULL)
370                         trace_put_tcd(tcd);
371                 return 1;
372         }
373
374         if (cdls != NULL) {
375                 if (libcfs_console_ratelimit &&
376                     cdls->cdls_next != 0 &&     /* not first time ever */
377                     !cfs_time_after(cfs_time_current(), cdls->cdls_next)) {
378                         /* skipping a console message */
379                         cdls->cdls_count++;
380                         if (tcd != NULL)
381                                 trace_put_tcd(tcd);
382                         return 1;
383                 }
384
385                 if (cfs_time_after(cfs_time_current(), cdls->cdls_next +
386                                                        libcfs_console_max_delay
387                                                        + cfs_time_seconds(10))) {
388                         /* last timeout was a long time ago */
389                         cdls->cdls_delay /= libcfs_console_backoff * 4;
390                 } else {
391                         cdls->cdls_delay *= libcfs_console_backoff;
392
393                         if (cdls->cdls_delay < libcfs_console_min_delay)
394                                 cdls->cdls_delay = libcfs_console_min_delay;
395                         else if (cdls->cdls_delay > libcfs_console_max_delay)
396                                 cdls->cdls_delay = libcfs_console_max_delay;
397                 }
398
399                 /* ensure cdls_next is never zero after it's been seen */
400                 cdls->cdls_next = (cfs_time_current() + cdls->cdls_delay) | 1;
401         }
402
403         if (tcd != NULL) {
404                 print_to_console(&header, mask, string_buf, needed, file, fn);
405                 trace_put_tcd(tcd);
406         } else {
407                 string_buf = trace_get_console_buffer();
408
409                 needed = 0;
410                 if (format1 != NULL) {
411                         va_copy(ap, args);
412                         needed = vsnprintf(string_buf, TRACE_CONSOLE_BUFFER_SIZE, format1, ap);
413                         va_end(ap);
414                 }
415                 if (format2 != NULL) {
416                         remain = TRACE_CONSOLE_BUFFER_SIZE - needed;
417                         if (remain > 0) {
418                                 va_start(ap, format2);
419                                 needed += vsnprintf(string_buf+needed, remain, format2, ap);
420                                 va_end(ap);
421                         }
422                 }
423                 print_to_console(&header, mask,
424                                  string_buf, needed, file, fn);
425
426                 trace_put_console_buffer(string_buf);
427         }
428
429         if (cdls != NULL && cdls->cdls_count != 0) {
430                 string_buf = trace_get_console_buffer();
431
432                 needed = snprintf(string_buf, TRACE_CONSOLE_BUFFER_SIZE,
433                          "Skipped %d previous similar message%s\n",
434                          cdls->cdls_count, (cdls->cdls_count > 1) ? "s" : "");
435
436                 print_to_console(&header, mask,
437                                  string_buf, needed, file, fn);
438
439                 trace_put_console_buffer(string_buf);
440                 cdls->cdls_count = 0;
441         }
442
443         return 0;
444 }
445 EXPORT_SYMBOL(libcfs_debug_vmsg2);
446
447 void
448 libcfs_assertion_failed(const char *expr, const char *file,
449                         const char *func, const int line)
450 {
451         libcfs_debug_msg(NULL, 0, D_EMERG, file, func, line,
452                          "ASSERTION(%s) failed\n", expr);
453         lbug_with_loc(file, func, line);
454 }
455 EXPORT_SYMBOL(libcfs_assertion_failed);
456
457 void
458 trace_assertion_failed(const char *str,
459                        const char *fn, const char *file, int line)
460 {
461         struct ptldebug_header hdr;
462
463         libcfs_panic_in_progress = 1;
464         libcfs_catastrophe = 1;
465         mb();
466
467         set_ptldebug_header(&hdr, DEBUG_SUBSYSTEM, D_EMERG, line,
468                             CDEBUG_STACK());
469
470         print_to_console(&hdr, D_EMERG, str, strlen(str), file, fn);
471
472         LIBCFS_PANIC("Lustre debug assertion failure\n");
473
474         /* not reached */
475 }
476
477 static void
478 panic_collect_pages(struct page_collection *pc)
479 {
480         /* Do the collect_pages job on a single CPU: assumes that all other
481          * CPUs have been stopped during a panic.  If this isn't true for some
482          * arch, this will have to be implemented separately in each arch.  */
483         int                    i;
484         int                    j;
485         struct trace_cpu_data *tcd;
486
487         CFS_INIT_LIST_HEAD(&pc->pc_pages);
488
489         tcd_for_each(tcd, i, j) {
490                 list_splice_init(&tcd->tcd_pages, &pc->pc_pages);
491                 tcd->tcd_cur_pages = 0;
492
493                 if (pc->pc_want_daemon_pages) {
494                         list_splice_init(&tcd->tcd_daemon_pages, &pc->pc_pages);
495                         tcd->tcd_cur_daemon_pages = 0;
496                 }
497         }
498 }
499
500 static void collect_pages_on_cpu(void *info)
501 {
502         struct trace_cpu_data *tcd;
503         struct page_collection *pc = info;
504         int i;
505
506         spin_lock(&pc->pc_lock);
507         tcd_for_each_type_lock(tcd, i) {
508                 list_splice_init(&tcd->tcd_pages, &pc->pc_pages);
509                 tcd->tcd_cur_pages = 0;
510                 if (pc->pc_want_daemon_pages) {
511                         list_splice_init(&tcd->tcd_daemon_pages, &pc->pc_pages);
512                         tcd->tcd_cur_daemon_pages = 0;
513                 }
514         }
515         spin_unlock(&pc->pc_lock);
516 }
517
518 static void collect_pages(struct page_collection *pc)
519 {
520         CFS_INIT_LIST_HEAD(&pc->pc_pages);
521
522         if (libcfs_panic_in_progress)
523                 panic_collect_pages(pc);
524         else
525                 trace_call_on_all_cpus(collect_pages_on_cpu, pc);
526 }
527
528 static void put_pages_back_on_cpu(void *info)
529 {
530         struct page_collection *pc = info;
531         struct trace_cpu_data *tcd;
532         struct list_head *cur_head;
533         struct trace_page *tage;
534         struct trace_page *tmp;
535         int i;
536
537         spin_lock(&pc->pc_lock);
538         tcd_for_each_type_lock(tcd, i) {
539                 cur_head = tcd->tcd_pages.next;
540
541                 cfs_list_for_each_entry_safe_typed(tage, tmp, &pc->pc_pages,
542                                                    struct trace_page, linkage) {
543
544                         __LASSERT_TAGE_INVARIANT(tage);
545
546                         if (tage->cpu != smp_processor_id() || tage->type != i)
547                                 continue;
548
549                         tage_to_tail(tage, cur_head);
550                         tcd->tcd_cur_pages++;
551                 }
552         }
553         spin_unlock(&pc->pc_lock);
554 }
555
556 static void put_pages_back(struct page_collection *pc)
557 {
558         if (!libcfs_panic_in_progress)
559                 trace_call_on_all_cpus(put_pages_back_on_cpu, pc);
560 }
561
562 /* Add pages to a per-cpu debug daemon ringbuffer.  This buffer makes sure that
563  * we have a good amount of data at all times for dumping during an LBUG, even
564  * if we have been steadily writing (and otherwise discarding) pages via the
565  * debug daemon. */
566 static void put_pages_on_tcd_daemon_list(struct page_collection *pc,
567                                          struct trace_cpu_data *tcd)
568 {
569         struct trace_page *tage;
570         struct trace_page *tmp;
571
572         spin_lock(&pc->pc_lock);
573         cfs_list_for_each_entry_safe_typed(tage, tmp, &pc->pc_pages,
574                                            struct trace_page, linkage) {
575
576                 __LASSERT_TAGE_INVARIANT(tage);
577
578                 if (tage->cpu != smp_processor_id() ||
579                     tage->type != tcd->tcd_type)
580                         continue;
581
582                 tage_to_tail(tage, &tcd->tcd_daemon_pages);
583                 tcd->tcd_cur_daemon_pages++;
584
585                 if (tcd->tcd_cur_daemon_pages > tcd->tcd_max_pages) {
586                         struct trace_page *victim;
587
588                         __LASSERT(!list_empty(&tcd->tcd_daemon_pages));
589                         victim = tage_from_list(tcd->tcd_daemon_pages.next);
590
591                         __LASSERT_TAGE_INVARIANT(victim);
592
593                         list_del(&victim->linkage);
594                         tage_free(victim);
595                         tcd->tcd_cur_daemon_pages--;
596                 }
597         }
598         spin_unlock(&pc->pc_lock);
599 }
600
601 static void put_pages_on_daemon_list_on_cpu(void *info)
602 {
603         struct trace_cpu_data *tcd;
604         int i;
605
606         tcd_for_each_type_lock(tcd, i)
607                 put_pages_on_tcd_daemon_list(info, tcd);
608 }
609
610 static void put_pages_on_daemon_list(struct page_collection *pc)
611 {
612         trace_call_on_all_cpus(put_pages_on_daemon_list_on_cpu, pc);
613 }
614
615 void trace_debug_print(void)
616 {
617         struct page_collection pc;
618         struct trace_page *tage;
619         struct trace_page *tmp;
620
621         spin_lock_init(&pc.pc_lock);
622
623         pc.pc_want_daemon_pages = 1;
624         collect_pages(&pc);
625         cfs_list_for_each_entry_safe_typed(tage, tmp, &pc.pc_pages,
626                                            struct trace_page, linkage) {
627                 char *p, *file, *fn;
628                 cfs_page_t *page;
629
630                 __LASSERT_TAGE_INVARIANT(tage);
631
632                 page = tage->page;
633                 p = cfs_page_address(page);
634                 while (p < ((char *)cfs_page_address(page) + tage->used)) {
635                         struct ptldebug_header *hdr;
636                         int len;
637                         hdr = (void *)p;
638                         p += sizeof(*hdr);
639                         file = p;
640                         p += strlen(file) + 1;
641                         fn = p;
642                         p += strlen(fn) + 1;
643                         len = hdr->ph_len - (int)(p - (char *)hdr);
644
645                         print_to_console(hdr, D_EMERG, p, len, file, fn);
646
647                         p += len;
648                 }
649
650                 list_del(&tage->linkage);
651                 tage_free(tage);
652         }
653 }
654
655 int tracefile_dump_all_pages(char *filename)
656 {
657         struct page_collection pc;
658         cfs_file_t *filp;
659         struct trace_page *tage;
660         struct trace_page *tmp;
661         int rc;
662
663         CFS_DECL_MMSPACE;
664
665         tracefile_write_lock();
666
667         filp = cfs_filp_open(filename,
668                              O_CREAT|O_EXCL|O_WRONLY|O_LARGEFILE, 0600, &rc);
669         if (!filp) {
670                 if (rc != -EEXIST)
671                         printk(KERN_ERR "LustreError: can't open %s for dump: rc %d\n",
672                                filename, rc);
673                 goto out;
674         }
675
676         spin_lock_init(&pc.pc_lock);
677         pc.pc_want_daemon_pages = 1;
678         collect_pages(&pc);
679         if (list_empty(&pc.pc_pages)) {
680                 rc = 0;
681                 goto close;
682         }
683
684         /* ok, for now, just write the pages.  in the future we'll be building
685          * iobufs with the pages and calling generic_direct_IO */
686         CFS_MMSPACE_OPEN;
687         cfs_list_for_each_entry_safe_typed(tage, tmp, &pc.pc_pages,
688                                            struct trace_page, linkage) {
689
690                 __LASSERT_TAGE_INVARIANT(tage);
691
692                 rc = cfs_filp_write(filp, cfs_page_address(tage->page),
693                                     tage->used, cfs_filp_poff(filp));
694                 if (rc != (int)tage->used) {
695                         printk(KERN_WARNING "wanted to write %u but wrote "
696                                "%d\n", tage->used, rc);
697                         put_pages_back(&pc);
698                         __LASSERT(list_empty(&pc.pc_pages));
699                         break;
700                 }
701                 list_del(&tage->linkage);
702                 tage_free(tage);
703         }
704         CFS_MMSPACE_CLOSE;
705         rc = cfs_filp_fsync(filp);
706         if (rc)
707                 printk(KERN_ERR "sync returns %d\n", rc);
708  close:
709         cfs_filp_close(filp);
710  out:
711         tracefile_write_unlock();
712         return rc;
713 }
714
715 void trace_flush_pages(void)
716 {
717         struct page_collection pc;
718         struct trace_page *tage;
719         struct trace_page *tmp;
720
721         spin_lock_init(&pc.pc_lock);
722
723         pc.pc_want_daemon_pages = 1;
724         collect_pages(&pc);
725         cfs_list_for_each_entry_safe_typed(tage, tmp, &pc.pc_pages,
726                                            struct trace_page, linkage) {
727
728                 __LASSERT_TAGE_INVARIANT(tage);
729
730                 list_del(&tage->linkage);
731                 tage_free(tage);
732         }
733 }
734
735 int trace_copyin_string(char *knl_buffer, int knl_buffer_nob,
736                         const char *usr_buffer, int usr_buffer_nob)
737 {
738         int    nob;
739
740         if (usr_buffer_nob > knl_buffer_nob)
741                 return -EOVERFLOW;
742
743         if (copy_from_user((void *)knl_buffer,
744                            (void *)usr_buffer, usr_buffer_nob))
745                 return -EFAULT;
746
747         nob = strnlen(knl_buffer, usr_buffer_nob);
748         while (nob-- >= 0)                      /* strip trailing whitespace */
749                 if (!isspace(knl_buffer[nob]))
750                         break;
751
752         if (nob < 0)                            /* empty string */
753                 return -EINVAL;
754
755         if (nob == knl_buffer_nob)              /* no space to terminate */
756                 return -EOVERFLOW;
757
758         knl_buffer[nob + 1] = 0;                /* terminate */
759         return 0;
760 }
761
762 int trace_copyout_string(char *usr_buffer, int usr_buffer_nob,
763                          const char *knl_buffer, char *append)
764 {
765         /* NB if 'append' != NULL, it's a single character to append to the
766          * copied out string - usually "\n", for /proc entries and "" (i.e. a
767          * terminating zero byte) for sysctl entries */
768         int   nob = strlen(knl_buffer);
769
770         if (nob > usr_buffer_nob)
771                 nob = usr_buffer_nob;
772
773         if (copy_to_user(usr_buffer, knl_buffer, nob))
774                 return -EFAULT;
775
776         if (append != NULL && nob < usr_buffer_nob) {
777                 if (copy_to_user(usr_buffer + nob, append, 1))
778                         return -EFAULT;
779
780                 nob++;
781         }
782
783         return nob;
784 }
785
786 int trace_allocate_string_buffer(char **str, int nob)
787 {
788         if (nob > 2 * CFS_PAGE_SIZE)            /* string must be "sensible" */
789                 return -EINVAL;
790
791         *str = cfs_alloc(nob, CFS_ALLOC_STD | CFS_ALLOC_ZERO);
792         if (*str == NULL)
793                 return -ENOMEM;
794
795         return 0;
796 }
797
798 void trace_free_string_buffer(char *str, int nob)
799 {
800         cfs_free(str);
801 }
802
803 int trace_dump_debug_buffer_usrstr(void *usr_str, int usr_str_nob)
804 {
805         char         *str;
806         int           rc;
807
808         rc = trace_allocate_string_buffer(&str, usr_str_nob + 1);
809         if (rc != 0)
810                 return rc;
811
812         rc = trace_copyin_string(str, usr_str_nob + 1,
813                                  usr_str, usr_str_nob);
814         if (rc != 0)
815                 goto out;
816
817 #if !defined(__WINNT__)
818         if (str[0] != '/') {
819                 rc = -EINVAL;
820                 goto out;
821         }
822 #endif
823         rc = tracefile_dump_all_pages(str);
824 out:
825         trace_free_string_buffer(str, usr_str_nob + 1);
826         return rc;
827 }
828
829 int trace_daemon_command(char *str)
830 {
831         int       rc = 0;
832
833         tracefile_write_lock();
834
835         if (strcmp(str, "stop") == 0) {
836                 trace_stop_thread();
837                 memset(tracefile, 0, sizeof(tracefile));
838
839         } else if (strncmp(str, "size=", 5) == 0) {
840                 tracefile_size = simple_strtoul(str + 5, NULL, 0);
841                 if (tracefile_size < 10 || tracefile_size > 20480)
842                         tracefile_size = TRACEFILE_SIZE;
843                 else
844                         tracefile_size <<= 20;
845
846         } else if (strlen(str) >= sizeof(tracefile)) {
847                 rc = -ENAMETOOLONG;
848 #ifndef __WINNT__
849         } else if (str[0] != '/') {
850                 rc = -EINVAL;
851 #endif
852         } else {
853                 strcpy(tracefile, str);
854
855                 printk(KERN_INFO "Lustre: debug daemon will attempt to start writing "
856                        "to %s (%lukB max)\n", tracefile,
857                        (long)(tracefile_size >> 10));
858
859                 trace_start_thread();
860         }
861
862         tracefile_write_unlock();
863         return rc;
864 }
865
866 int trace_daemon_command_usrstr(void *usr_str, int usr_str_nob)
867 {
868         char *str;
869         int   rc;
870
871         rc = trace_allocate_string_buffer(&str, usr_str_nob + 1);
872         if (rc != 0)
873                 return rc;
874
875         rc = trace_copyin_string(str, usr_str_nob + 1,
876                                  usr_str, usr_str_nob);
877         if (rc == 0)
878                 rc = trace_daemon_command(str);
879
880         trace_free_string_buffer(str, usr_str_nob + 1);
881         return rc;
882 }
883
884 int trace_set_debug_mb(int mb)
885 {
886         int i;
887         int j;
888         int pages;
889         int limit = trace_max_debug_mb();
890         struct trace_cpu_data *tcd;
891
892         if (mb < num_possible_cpus())
893                 return -EINVAL;
894
895         if (mb > limit) {
896                 printk(KERN_ERR "Lustre: Refusing to set debug buffer size to "
897                        "%dMB - limit is %d\n", mb, limit);
898                 return -EINVAL;
899         }
900
901         mb /= num_possible_cpus();
902         pages = mb << (20 - CFS_PAGE_SHIFT);
903
904         tracefile_write_lock();
905
906         tcd_for_each(tcd, i, j)
907                 tcd->tcd_max_pages = (pages * tcd->tcd_pages_factor) / 100;
908
909         tracefile_write_unlock();
910
911         return 0;
912 }
913
914 int trace_set_debug_mb_usrstr(void *usr_str, int usr_str_nob)
915 {
916         char     str[32];
917         int      rc;
918
919         rc = trace_copyin_string(str, sizeof(str), usr_str, usr_str_nob);
920         if (rc < 0)
921                 return rc;
922
923         return trace_set_debug_mb(simple_strtoul(str, NULL, 0));
924 }
925
926 int trace_get_debug_mb(void)
927 {
928         int i;
929         int j;
930         struct trace_cpu_data *tcd;
931         int total_pages = 0;
932
933         tracefile_read_lock();
934
935         tcd_for_each(tcd, i, j)
936                 total_pages += tcd->tcd_max_pages;
937
938         tracefile_read_unlock();
939
940         return (total_pages >> (20 - CFS_PAGE_SHIFT)) + 1;
941 }
942
943 static int tracefiled(void *arg)
944 {
945         struct page_collection pc;
946         struct tracefiled_ctl *tctl = arg;
947         struct trace_page *tage;
948         struct trace_page *tmp;
949         struct ptldebug_header *hdr;
950         cfs_file_t *filp;
951         int rc;
952
953         CFS_DECL_MMSPACE;
954
955         /* we're started late enough that we pick up init's fs context */
956         /* this is so broken in uml?  what on earth is going on? */
957         cfs_daemonize("ktracefiled");
958
959         spin_lock_init(&pc.pc_lock);
960         complete(&tctl->tctl_start);
961
962         while (1) {
963                 cfs_waitlink_t __wait;
964
965                 cfs_waitlink_init(&__wait);
966                 cfs_waitq_add(&tctl->tctl_waitq, &__wait);
967                 set_current_state(TASK_INTERRUPTIBLE);
968                 cfs_waitq_timedwait(&__wait, CFS_TASK_INTERRUPTIBLE,
969                                     cfs_time_seconds(1));
970                 cfs_waitq_del(&tctl->tctl_waitq, &__wait);
971
972                 if (atomic_read(&tctl->tctl_shutdown))
973                         break;
974
975                 pc.pc_want_daemon_pages = 0;
976                 collect_pages(&pc);
977                 if (list_empty(&pc.pc_pages))
978                         continue;
979
980                 filp = NULL;
981                 tracefile_read_lock();
982                 if (tracefile[0] != 0) {
983                         filp = cfs_filp_open(tracefile,
984                                              O_CREAT | O_RDWR | O_LARGEFILE,
985                                              0600, &rc);
986                         if (!(filp))
987                                 printk(KERN_WARNING "couldn't open %s: %d\n",
988                                        tracefile, rc);
989                 }
990                 tracefile_read_unlock();
991                 if (filp == NULL) {
992                         put_pages_on_daemon_list(&pc);
993                         __LASSERT(list_empty(&pc.pc_pages));
994                         continue;
995                 }
996
997                 CFS_MMSPACE_OPEN;
998
999                 /* mark the first header, so we can sort in chunks */
1000                 tage = tage_from_list(pc.pc_pages.next);
1001                 __LASSERT_TAGE_INVARIANT(tage);
1002
1003                 hdr = cfs_page_address(tage->page);
1004                 hdr->ph_flags |= PH_FLAG_FIRST_RECORD;
1005
1006                 cfs_list_for_each_entry_safe_typed(tage, tmp, &pc.pc_pages,
1007                                                    struct trace_page, linkage) {
1008                         static loff_t f_pos;
1009
1010                         __LASSERT_TAGE_INVARIANT(tage);
1011
1012                         if (f_pos >= (off_t)tracefile_size)
1013                                 f_pos = 0;
1014                         else if (f_pos > (off_t)cfs_filp_size(filp))
1015                                 f_pos = cfs_filp_size(filp);
1016
1017                         rc = cfs_filp_write(filp, cfs_page_address(tage->page),
1018                                             tage->used, &f_pos);
1019                         if (rc != (int)tage->used) {
1020                                 printk(KERN_WARNING "wanted to write %u but "
1021                                        "wrote %d\n", tage->used, rc);
1022                                 put_pages_back(&pc);
1023                                 __LASSERT(list_empty(&pc.pc_pages));
1024                         }
1025                 }
1026                 CFS_MMSPACE_CLOSE;
1027
1028                 cfs_filp_close(filp);
1029                 put_pages_on_daemon_list(&pc);
1030                 __LASSERT(list_empty(&pc.pc_pages));
1031         }
1032         complete(&tctl->tctl_stop);
1033         return 0;
1034 }
1035
1036 int trace_start_thread(void)
1037 {
1038         struct tracefiled_ctl *tctl = &trace_tctl;
1039         int rc = 0;
1040
1041         mutex_down(&trace_thread_sem);
1042         if (thread_running)
1043                 goto out;
1044
1045         init_completion(&tctl->tctl_start);
1046         init_completion(&tctl->tctl_stop);
1047         cfs_waitq_init(&tctl->tctl_waitq);
1048         atomic_set(&tctl->tctl_shutdown, 0);
1049
1050         if (cfs_kernel_thread(tracefiled, tctl, 0) < 0) {
1051                 rc = -ECHILD;
1052                 goto out;
1053         }
1054
1055         wait_for_completion(&tctl->tctl_start);
1056         thread_running = 1;
1057 out:
1058         mutex_up(&trace_thread_sem);
1059         return rc;
1060 }
1061
1062 void trace_stop_thread(void)
1063 {
1064         struct tracefiled_ctl *tctl = &trace_tctl;
1065
1066         mutex_down(&trace_thread_sem);
1067         if (thread_running) {
1068                 printk(KERN_INFO "Lustre: shutting down debug daemon thread...\n");
1069                 atomic_set(&tctl->tctl_shutdown, 1);
1070                 wait_for_completion(&tctl->tctl_stop);
1071                 thread_running = 0;
1072         }
1073         mutex_up(&trace_thread_sem);
1074 }
1075
1076 int tracefile_init(int max_pages)
1077 {
1078         struct trace_cpu_data *tcd;
1079         int                    i;
1080         int                    j;
1081         int                    rc;
1082         int                    factor;
1083
1084         rc = tracefile_init_arch();
1085         if (rc != 0)
1086                 return rc;
1087
1088         tcd_for_each(tcd, i, j) {
1089                 /* tcd_pages_factor is initialized int tracefile_init_arch. */
1090                 factor = tcd->tcd_pages_factor;
1091                 CFS_INIT_LIST_HEAD(&tcd->tcd_pages);
1092                 CFS_INIT_LIST_HEAD(&tcd->tcd_stock_pages);
1093                 CFS_INIT_LIST_HEAD(&tcd->tcd_daemon_pages);
1094                 tcd->tcd_cur_pages = 0;
1095                 tcd->tcd_cur_stock_pages = 0;
1096                 tcd->tcd_cur_daemon_pages = 0;
1097                 tcd->tcd_max_pages = (max_pages * factor) / 100;
1098                 LASSERT(tcd->tcd_max_pages > 0);
1099                 tcd->tcd_shutting_down = 0;
1100         }
1101
1102         return 0;
1103 }
1104
1105 static void trace_cleanup_on_cpu(void *info)
1106 {
1107         struct trace_cpu_data *tcd;
1108         struct trace_page *tage;
1109         struct trace_page *tmp;
1110         int i;
1111
1112         tcd_for_each_type_lock(tcd, i) {
1113                 tcd->tcd_shutting_down = 1;
1114
1115                 cfs_list_for_each_entry_safe_typed(tage, tmp, &tcd->tcd_pages,
1116                                                    struct trace_page, linkage) {
1117                         __LASSERT_TAGE_INVARIANT(tage);
1118
1119                         list_del(&tage->linkage);
1120                         tage_free(tage);
1121                 }
1122                 tcd->tcd_cur_pages = 0;
1123         }
1124 }
1125
1126 static void trace_cleanup(void)
1127 {
1128         struct page_collection pc;
1129
1130         CFS_INIT_LIST_HEAD(&pc.pc_pages);
1131         spin_lock_init(&pc.pc_lock);
1132
1133         trace_call_on_all_cpus(trace_cleanup_on_cpu, &pc);
1134
1135         tracefile_fini_arch();
1136 }
1137
1138 void tracefile_exit(void)
1139 {
1140         trace_stop_thread();
1141         trace_cleanup();
1142 }