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