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