Whamcloud - gitweb
Break, instead of panic, in the UML version of portals_debug_dumpstack.
[fs/lustre-release.git] / lustre / portals / libcfs / debug.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * Copyright (C) 2002 Cluster File Systems, Inc.
5  *   Author: Phil Schwan <phil@clusterfs.com>
6  *
7  *   This file is part of Lustre, http://www.lustre.org.
8  *
9  *   Lustre is free software; you can redistribute it and/or
10  *   modify it under the terms of version 2 of the GNU General Public
11  *   License as published by the Free Software Foundation.
12  *
13  *   Lustre is distributed in the hope that it will be useful,
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *   GNU General Public License for more details.
17  *
18  *   You should have received a copy of the GNU General Public License
19  *   along with Lustre; if not, write to the Free Software
20  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23 #ifndef EXPORT_SYMTAB
24 # define EXPORT_SYMTAB
25 #endif
26
27 #include <linux/config.h>
28 #include <linux/module.h>
29 #include <linux/kmod.h>
30 #include <linux/notifier.h>
31 #include <linux/kernel.h>
32 #include <linux/mm.h>
33 #include <linux/string.h>
34 #include <linux/stat.h>
35 #include <linux/errno.h>
36 #include <linux/smp_lock.h>
37 #include <linux/unistd.h>
38 #include <linux/interrupt.h>
39 #include <asm/system.h>
40 #include <asm/uaccess.h>
41 #include <linux/completion.h>
42
43 #include <linux/fs.h>
44 #include <linux/stat.h>
45 #include <asm/uaccess.h>
46 #include <asm/segment.h>
47 #include <linux/miscdevice.h>
48
49 # define DEBUG_SUBSYSTEM S_PORTALS
50
51 #include <linux/kp30.h>
52 #include <linux/portals_compat25.h>
53
54 #define DEBUG_OVERFLOW 1024
55 static char *debug_buf = NULL;
56 static unsigned long debug_size = 0;
57 static atomic_t debug_off_a = ATOMIC_INIT(0);
58 static int debug_wrapped;
59 wait_queue_head_t debug_ctlwq;
60 #define DAEMON_SND_SIZE      (64 << 10)
61
62 /*
63  * used by the daemon to keep track the offset into debug_buffer for the next
64  * write to the file.  Usually, the daemon is to write out buffer
65  * from debug_daemon_next_write upto debug_off
66  *  variable usage
67  *      Reader - portals_debug_msg()
68  *      Writer - portals_debug_daemon()
69  *               portals_debug_daemon_start() during daemon init time
70  *               portals_debug_daemon_continue() to reset to debug_off
71  *               portals_debug_clear_buffer() reset to debug_off for clear
72  *      Note that *_start(), *_continue() & *clear_buffer() should serialized;
73  */
74 static atomic_t   debug_daemon_next_write;
75
76 /*
77  * A debug_daemon can be in following states
78  *      stopped - stopped state means there is no debug_daemon running.
79  *                accordingly, it must be in paused state
80  *                a daemon is in !stopped && !paused state after
81  *                "lctl debug_daemon start" creates debug_daemon successfully
82  *                Variable Usage
83  *                      Reader - portals_debug_daemon()
84  *                               portals_debug_set_daemon() routines
85  *                      Writer - portals_debug_set_daemon() routines
86  *                              portals_debug_daemon() on IO error
87  *      paused -  a debug_daemon state is changed from !paused into paused
88  *                when "lctl debug_daemon paused" is issued
89  *                "lctl debug_daemon continue" gets a daemon into !paused mode
90  *                      Reader - portals_debug_set_daemon() routines
91  *                               portals_debug_msg()
92  *                      Writer - portals_debug_set_daemon() on init
93  *                               portals_debug_daemon()
94  *
95  *        Daemon  state diagram.
96  *                      (stopped, paused)
97  *                              |  <-- debug_daemon start
98  *                              V
99  *                      (!stopped, !paused)
100  *                              |  <-- debug_daemon pause
101  *                              V
102  *                      (!stopped, paused)
103  *                              |  <-- debug_daemon continue
104  *                              V
105  *                      (!stopped, !paused)
106  *                              |  <-- debug_daemon stop
107  *                              V
108  *                      (stopped, paused)
109  *      Overlapped - this is a state when CDEBUG is too fast for the daemon to
110  *                   write out the debug_bufferr.  That is, debug_off is to
111  *                   overlap debug_daemon_next_write;
112  *                     Reader - portals_debug_msg()
113  *                     Writer - portals_debug_msg()
114  */
115
116 /*
117  * Description on Trace Daemon Synchronization
118  *
119  * Three categories of code are synchronizing between each other
120  * 1.   lctl, portals_debug_set_daemon(), the user debug control code, 
121  *      as well as portals_debug_clear_buffer()
122  * 2.   CDEBUG, portals_debug_msg(), the debug put messages routine
123  * 3.   Daemon, portals_debug_daemon(), to write out debug log file
124  *
125  *
126  * Three different controls for synchronizations
127  *
128  * 1.   debug_daemon_semaphore
129  *      The usage of this semaphore is to serialize multiple lctl controls 
130  *      in manipulating debug daemon state.  The semaphore serves as the 
131  *      gatekeeper to allow only one user control thread, at any giving time, 
132  *      to access debug daemon state and keeps the other user control requests 
133  *      in wait state until the current control request is serviced.
134  *
135  * 2.   wait_queue_head_t lctl (paired with lctl_event flag)
136  *      Lctl event is the event between portals_debug_set_daemon() and 
137  *      portals_debug_daemon().  Lctl is an indicator for portals_debug_daemon()
138  *      to flush data out to file.  portals_debug_daemon() is to use lctl event
139  *      as signal channel to wakeup portals_debug_set_daemon() upon flush 
140  *      operation is done.
141  *
142  *      Producer :
143  *              portals_debug_daemon() uses to wake up 
144  *              portals_debug_set_daemon(), pause and stop, routines
145  *      Consumer :
146  *              portals_debug_set_daemon(), stop and pause operations, 
147  *              wait and sleep on the event
148  *
149  * 3.   wait_queue_head_t daemon (paired with daemon_event flag)
150  *      This is an event channel to wakeup portals_debug_daemon.  Daemon 
151  *      wakes up to run whenever there is an event posted.   Daemon handles 
152  *      2 types of operations . 1. Writes data out to debug file, 2. Flushes 
153  *      file and terminates base on lctl event. 
154  *      File operation -
155  *              Daemon is normally in a sleep state.  
156  *              Daemon is woken up through daemon event whenever CDEBUG is 
157  *              putting data over any 64K boundary. 
158  *      File flush and termination -
159  *              On portals_debug_daemon_stop/pause() operations, lctl control 
160  *              is to wake up daemon through daemon event.
161  *
162  *      We can't use sleep_on() and wake_up() to replace daemon event because 
163  *      portals_debug_daemon() must catch the wakeup operation posted by 
164  *      portals_debug_daemon_stop/pause().  Otherwise, stop and pause may 
165  *      stuck in lctl wait event.
166  *
167  *      Producer :
168  *           a. portals_debug_daemon_pause() and portals_debug_daemon_stop() 
169  *              uses the event to wake up portals_debug_daemon()
170  *           b. portals_debug_msg() uses the event to wake up 
171  *              portals_debug_daemon() whenever the data output is acrossing 
172  *              a 64K bytes boundary.
173  *      Consumer :
174  *              portals_debug_daemon() wakes up upon daemon event.
175  *
176  * Sequence for portals_debug_daemon_stop() operation
177  *
178  * _Portals_debug_daemon_stop()_          _Daemon_
179  *                                      Wait_event(daemon) or running
180  *      Paused = 1;
181  *      Wakeup_event (daemon)
182  *      Wait_event(lctl)
183  *                                      Set force_flush flag if lctlevnt
184  *                                      Flush data
185  *                                      Wakeup_event (lctl)
186  *                                      Wait_event(daemon)
187  *      Stopped = 1;
188  *      Wakeup_event (daemon)
189  *      Wait_event(lctl)
190  *                                      Exit daemon loop if (Stopped)
191  *                                      Wakeup_event (lctl)
192  *                                      Exit
193  *      Return to user application
194  *
195  *
196  * _Portals_debug_msg()_                  _Daemon_
197  *                                      Wait_event(daemon) or running
198  *      If (WriteStart<64K<WriteEnd)
199  *         Wakeup_event(daemon)
200  *                                      Do file IO
201  *                                      Wait_event(daemon)
202  */
203 struct debug_daemon_state {
204         unsigned long overlapped;
205         unsigned long stopped;
206         atomic_t paused;
207         unsigned long   lctl_event;     /* event for lctl */
208         wait_queue_head_t lctl;
209         unsigned long   daemon_event;   /* event for daemon */
210         wait_queue_head_t daemon;
211 };
212 static struct debug_daemon_state debug_daemon_state;
213 static DECLARE_MUTEX(debug_daemon_semaphore);
214
215 static loff_t daemon_file_size_limit;
216 char debug_daemon_file_path[1024] = "";
217
218 spinlock_t portals_debug_lock = SPIN_LOCK_UNLOCKED;
219 char debug_file_path[1024] = "/tmp/lustre-log";
220 char debug_file_name[1024];
221 int handled_panic; /* to avoid recursive calls to notifiers */
222 char portals_upcall[1024] = "/usr/lib/lustre/portals_upcall";
223
224
225 int portals_do_debug_dumplog(void *arg)
226 {
227         struct file *file;
228         void *journal_info;
229         int rc;
230         mm_segment_t oldfs;
231         unsigned long debug_off;
232
233         kportal_daemonize("");
234
235         reparent_to_init();
236         journal_info = current->journal_info;
237         current->journal_info = NULL;
238         sprintf(debug_file_name, "%s.%ld", debug_file_path, CURRENT_SECONDS);
239         file = filp_open(debug_file_name, O_CREAT|O_EXCL|O_RDWR, 0644);
240
241         if (!file || IS_ERR(file)) {
242                 CERROR("cannot open %s for dumping: %ld\n", debug_file_name,
243                        PTR_ERR(file));
244                 GOTO(out, PTR_ERR(file));
245         } else {
246                 printk(KERN_ALERT "LustreError: dumping log to %s ... writing ...\n",
247                        debug_file_name);
248         }
249
250         debug_off = atomic_read(&debug_off_a);
251         oldfs = get_fs();
252         set_fs(get_ds());
253         if (debug_wrapped) {
254                 rc = file->f_op->write(file, debug_buf + debug_off + 1,
255                                        debug_size-debug_off-1, &file->f_pos);
256                 rc += file->f_op->write(file, debug_buf, debug_off + 1,
257                                         &file->f_pos);
258         } else {
259                 rc = file->f_op->write(file, debug_buf, debug_off,&file->f_pos);
260         }
261         printk("LustreError: wrote %d bytes\n", rc);
262         set_fs(oldfs);
263
264         rc = file->f_op->fsync(file, file->f_dentry, 1);
265         if (rc)
266                 CERROR("sync returns %d\n", rc);
267         filp_close(file, 0);
268 out:
269         current->journal_info = journal_info;
270         wake_up(&debug_ctlwq);
271         return 0;
272 }
273
274 int portals_debug_daemon(void *arg)
275 {
276         struct file *file;
277         void *journal_info;
278         mm_segment_t oldfs;
279         unsigned long force_flush = 0;
280         unsigned long size, off, flags;
281         int rc;
282
283         kportal_daemonize("ldebug_daemon");
284         reparent_to_init();
285         journal_info = current->journal_info;
286         current->journal_info = NULL;
287
288         file = filp_open(debug_daemon_file_path,
289                          O_CREAT|O_TRUNC|O_RDWR|O_LARGEFILE, 0644);
290
291         if (!file || IS_ERR(file)) {
292                 CERROR("cannot open %s for logging", debug_daemon_file_path);
293                 GOTO(out1, PTR_ERR(file));
294         }
295         printk(KERN_INFO "daemon dumping log to %s\n", debug_daemon_file_path);
296
297         debug_daemon_state.overlapped = 0;
298         debug_daemon_state.stopped = 0;
299
300         spin_lock_irqsave(&portals_debug_lock, flags);
301         off = atomic_read(&debug_off_a) + 1;
302         if (debug_wrapped)
303                 off = (off >= debug_size)? 0 : off;
304         else
305                 off = 0;
306         atomic_set(&debug_daemon_next_write, off);
307         atomic_set(&debug_daemon_state.paused, 0);
308         spin_unlock_irqrestore(&portals_debug_lock, flags);
309
310         oldfs = get_fs();
311         set_fs(KERNEL_DS);
312         while (1) {
313                 unsigned long ending;
314                 unsigned long start, tail;
315                 long delta;
316
317                 debug_daemon_state.daemon_event = 0;
318
319                 ending = atomic_read(&debug_off_a);
320                 start = atomic_read(&debug_daemon_next_write);
321
322                 /* check if paused is imposed by lctl ? */
323                 force_flush = !debug_daemon_state.lctl_event;
324
325                 delta = ending - start;
326                 tail = debug_size - start;
327                 size = (delta >= 0) ? delta : tail;
328                 while (size && (force_flush || (delta < 0) ||
329                                 (size >= DAEMON_SND_SIZE))) {
330                         if (daemon_file_size_limit) {
331                                int ssize = daemon_file_size_limit - file->f_pos;
332                                if (size > ssize)
333                                         size = ssize;
334                         }
335
336                         rc = file->f_op->write(file, debug_buf+start,
337                                                size, &file->f_pos);
338                         if (rc < 0) {
339                                 printk(KERN_ALERT "LustreError: Debug_daemon "
340                                        "write error %d\n", rc);
341                                 goto out;
342                         }
343                         start += rc;
344                         delta = ending - start;
345                         tail = debug_size - start;
346                         if (tail == 0)
347                                 start = 0;
348                         if (delta >= 0)
349                                 size = delta;
350                         else
351                                 size = (tail == 0) ? ending : tail;
352                         if (daemon_file_size_limit == file->f_pos) {
353                                 // file wrapped around
354                                 file->f_pos = 0;
355                         }
356                 }
357                 atomic_set(&debug_daemon_next_write, start);
358                 if (force_flush) {
359                         rc = file->f_op->fsync(file, file->f_dentry, 1);
360                         if (rc < 0) {
361                                 printk(KERN_ALERT "LustreError: Debug_daemon "
362                                        "sync error %d\n", rc);
363                                 goto out;
364                         }
365                         if (debug_daemon_state.stopped)
366                                break;
367                         debug_daemon_state.lctl_event = 1;
368                         wake_up(&debug_daemon_state.lctl);
369                 }
370                 wait_event(debug_daemon_state.daemon,
371                            debug_daemon_state.daemon_event);
372                 }
373 out:
374         atomic_set(&debug_daemon_state.paused, 1);
375         debug_daemon_state.stopped = 1;
376         set_fs(oldfs);
377         filp_close(file, 0);
378         current->journal_info = journal_info;
379 out1:
380         debug_daemon_state.lctl_event = 1;
381         wake_up(&debug_daemon_state.lctl);
382         return 0;
383 }
384
385 void portals_debug_print(void)
386 {
387         unsigned long dumplen = 64 * 1024;
388         char *start1, *start2;
389         char *end1, *end2;
390         unsigned long debug_off = atomic_read(&debug_off_a);
391
392         start1 = debug_buf + debug_off - dumplen;
393         if (start1 < debug_buf) {
394                 start1 += debug_size;
395                 end1 = debug_buf + debug_size - 1;
396                 start2 = debug_buf;
397                 end2 = debug_buf + debug_off;
398         } else {
399                 end1 = debug_buf + debug_off;
400                 start2 = debug_buf + debug_off;
401                 end2 = debug_buf + debug_off;
402         }
403
404         while (start1 < end1) {
405                 int count = MIN(1024, end1 - start1);
406                 printk("LustreError: %*s", count, start1);
407                 start1 += 1024;
408         }
409         while (start2 < end2) {
410                 int count = MIN(1024, end2 - start2);
411                 printk("LustreError: %*s", count, start2);
412                 start2 += 1024;
413         }
414 }
415
416 void portals_debug_dumplog(void)
417 {
418         int rc;
419         ENTRY;
420
421         init_waitqueue_head(&debug_ctlwq);
422
423         rc = kernel_thread(portals_do_debug_dumplog,
424                            NULL, CLONE_VM | CLONE_FS | CLONE_FILES);
425         if (rc < 0) {
426                 printk(KERN_ERR "LustreError: cannot start log dump thread: "
427                        "%d\n", rc);
428                 return;
429         }
430         sleep_on(&debug_ctlwq);
431 }
432
433 int portals_debug_daemon_start(char *file, unsigned int size)
434 {
435         int rc;
436
437         if (!debug_daemon_state.stopped)
438                 return -EALREADY;
439
440         if (file != NULL)
441                 strncpy(debug_daemon_file_path, file, 1024);
442
443         init_waitqueue_head(&debug_daemon_state.lctl);
444         init_waitqueue_head(&debug_daemon_state.daemon);
445
446         daemon_file_size_limit = size << 20;
447
448         debug_daemon_state.lctl_event = 0;
449         rc = kernel_thread(portals_debug_daemon, NULL, 0);
450         if (rc < 0) {
451                 printk(KERN_ERR "LustreError: cannot start debug daemon thread\n");
452                 strncpy(debug_daemon_file_path, "\0", 1);
453                 return rc;
454         }
455         wait_event(debug_daemon_state.lctl, debug_daemon_state.lctl_event);
456         return 0;
457 }
458
459 int portals_debug_daemon_pause(void)
460 {
461         if (atomic_read(&debug_daemon_state.paused))
462                 return -EALREADY;
463
464         atomic_set(&debug_daemon_state.paused, 1);
465         debug_daemon_state.lctl_event = 0;
466         debug_daemon_state.daemon_event = 1;
467         wake_up(&debug_daemon_state.daemon);
468         wait_event(debug_daemon_state.lctl, debug_daemon_state.lctl_event);
469         return 0;
470 }
471
472 int portals_debug_daemon_continue(void)
473 {
474         if (!atomic_read(&debug_daemon_state.paused))
475                 return -EINVAL;
476         if (debug_daemon_state.stopped)
477                 return -EINVAL;
478
479         debug_daemon_state.overlapped = 0;
480         atomic_set(&debug_daemon_next_write, atomic_read(&debug_off_a));
481         atomic_set(&debug_daemon_state.paused, 0);
482         return 0;
483 }
484
485 int portals_debug_daemon_stop(void)
486 {
487         if (debug_daemon_state.stopped)
488                 return -EALREADY;
489
490         if (!atomic_read(&debug_daemon_state.paused))
491                 portals_debug_daemon_pause();
492
493         debug_daemon_state.lctl_event = 0;
494         debug_daemon_state.stopped = 1;
495
496         debug_daemon_state.daemon_event = 1;
497         wake_up(&debug_daemon_state.daemon);
498         wait_event(debug_daemon_state.lctl, debug_daemon_state.lctl_event);
499
500         debug_daemon_file_path[0] = '\0';
501         return 0;
502 }
503
504 int portals_debug_set_daemon(unsigned int cmd, unsigned int length,
505                              char *filename, unsigned int size)
506 {
507         int rc = -EINVAL;
508
509         down(&debug_daemon_semaphore);
510         switch (cmd) {
511                 case DEBUG_DAEMON_START:
512                         if (length && (filename[length -1] != '\0')) {
513                                 CERROR("Invalid filename for debug_daemon\n");
514                                 rc = -EINVAL;
515                                 break;
516                         }
517                         rc = portals_debug_daemon_start(filename, size);
518                         break;
519                 case DEBUG_DAEMON_STOP:
520                         rc = portals_debug_daemon_stop();
521                         break;
522                 case DEBUG_DAEMON_PAUSE:
523                         rc = portals_debug_daemon_pause();
524                         break;
525                 case DEBUG_DAEMON_CONTINUE:
526                         rc = portals_debug_daemon_continue();
527                         break;
528                 default:
529                         CERROR("unknown set_daemon cmd\n");
530         }
531         up(&debug_daemon_semaphore);
532         return rc;
533 }
534
535 static int panic_dumplog(struct notifier_block *self, unsigned long unused1,
536                          void *unused2)
537 {
538         if (handled_panic)
539                 return 0;
540         else
541                 handled_panic = 1;
542
543         if (in_interrupt()) {
544                 portals_debug_print();
545                 return 0;
546         }
547
548         while (current->lock_depth >= 0)
549                 unlock_kernel();
550         portals_debug_dumplog();
551         return 0;
552 }
553
554 static struct notifier_block lustre_panic_notifier = {
555         notifier_call :     panic_dumplog,
556         next :              NULL,
557         priority :          10000
558 };
559
560 int portals_debug_init(unsigned long bufsize)
561 {
562         unsigned long debug_off = atomic_read(&debug_off_a);
563         if (debug_buf != NULL)
564                 return -EALREADY;
565
566         atomic_set(&debug_daemon_state.paused, 1);
567         debug_daemon_state.stopped = 1;
568
569         debug_buf = vmalloc(bufsize + DEBUG_OVERFLOW);
570         if (debug_buf == NULL)
571                 return -ENOMEM;
572         memset(debug_buf, 0, debug_size);
573         debug_wrapped = 0;
574
575         //printk(KERN_INFO "Portals: allocated %lu byte debug buffer at %p.\n",
576                //bufsize, debug_buf);
577         atomic_set(&debug_off_a, debug_off);
578         notifier_chain_register(&panic_notifier_list, &lustre_panic_notifier);
579         debug_size = bufsize;
580
581         return 0;
582 }
583
584 int portals_debug_cleanup(void)
585 {
586         notifier_chain_unregister(&panic_notifier_list, &lustre_panic_notifier);
587         if (debug_buf == NULL)
588                 return -EINVAL;
589
590         down(&debug_daemon_semaphore);
591         portals_debug_daemon_stop();
592
593         vfree(debug_buf);
594         atomic_set(&debug_off_a, 0);
595         up(&debug_daemon_semaphore);
596
597         return 0;
598 }
599
600 int portals_debug_clear_buffer(void)
601 {
602         unsigned long flags;
603         unsigned long state;
604
605         if (debug_buf == NULL)
606                 return -EINVAL;
607
608         down(&debug_daemon_semaphore);
609         state = atomic_read(&debug_daemon_state.paused);
610         if (!state)
611                 portals_debug_daemon_pause();
612         spin_lock_irqsave(&portals_debug_lock, flags);
613         atomic_set(&debug_off_a, 0);
614         debug_wrapped = 0;
615         atomic_set(&debug_daemon_next_write, 0);
616         debug_daemon_state.overlapped = 0;
617         spin_unlock_irqrestore(&portals_debug_lock, flags);
618
619         if (!state)
620                 atomic_set(&debug_daemon_state.paused, 0);
621         up(&debug_daemon_semaphore);
622
623         return 0;
624 }
625
626 /* Debug markers, although printed by S_PORTALS
627  * should not be be marked as such.
628  */
629 #undef DEBUG_SUBSYSTEM
630 #define DEBUG_SUBSYSTEM S_UNDEFINED
631 int portals_debug_mark_buffer(char *text)
632 {
633         if (debug_buf == NULL)
634                 return -EINVAL;
635
636         CDEBUG(0, "********************************************************\n");
637         CWARN("DEBUG MARKER: %s\n", text);
638         CDEBUG(0, "********************************************************\n");
639
640         return 0;
641 }
642 #undef DEBUG_SUBSYSTEM
643 #define DEBUG_SUBSYSTEM S_PORTALS
644
645 /* this copies a snapshot of the debug buffer into an array of pages
646  * before doing the potentially blocking copy into userspace. it could
647  * be warning userspace if things wrap heavily while its off copying. */
648 __s32 portals_debug_copy_to_user(char *buf, unsigned long len)
649 {
650         int rc;
651         unsigned long total, debug_off, i, off, copied;
652         unsigned long flags;
653         struct page *page;
654         LIST_HEAD(my_pages);
655         struct list_head *pos, *n;
656
657         if (len < debug_size)
658                 return -ENOSPC;
659
660         for (i = 0 ; i < debug_size; i += PAGE_SIZE) {
661                 page = alloc_page(GFP_NOFS);
662                 if (page == NULL) {
663                         rc = -ENOMEM;
664                         goto cleanup;
665                 }
666                 list_add(&page->list, &my_pages);
667         }
668
669         spin_lock_irqsave(&portals_debug_lock, flags);
670         debug_off = atomic_read(&debug_off_a);
671
672         /* Sigh. If the buffer is empty, then skip to the end. */
673         if (debug_off == 0 && !debug_wrapped) {
674                 spin_unlock_irqrestore(&portals_debug_lock, flags);
675                 rc = 0;
676                 goto cleanup;
677         }
678
679         if (debug_wrapped) {
680                 off = debug_off + 1;
681                 total = debug_size;
682         } else {
683                 off = 0;
684                 total = debug_off;
685         }
686         copied = 0;
687         list_for_each(pos, &my_pages) {
688                 unsigned long to_copy;
689                 page = list_entry(pos, struct page, list);
690
691                 to_copy = min(total - off, PAGE_SIZE);
692                 if (to_copy == 0) {
693                         off = 0;
694                         to_copy = min(debug_size - off, PAGE_SIZE);
695                 }
696 finish_partial:
697                 memcpy(kmap(page), debug_buf + off, to_copy);
698                 kunmap(page);
699                 copied += to_copy;
700                 if (copied >= total)
701                         break;
702
703                 off += to_copy;
704                 if (off >= debug_size) {
705                         off = 0;
706                         if (to_copy != PAGE_SIZE) {
707                                 to_copy = PAGE_SIZE - to_copy;
708                                 goto finish_partial;
709                         }
710                 }
711         }
712
713         spin_unlock_irqrestore(&portals_debug_lock, flags);
714
715         off = 0;
716         list_for_each(pos, &my_pages) {
717                 unsigned long to_copy;
718                 page = list_entry(pos, struct page, list);
719
720                 to_copy = min(copied - off, PAGE_SIZE);
721                 rc = copy_to_user(buf + off, kmap(page), to_copy);
722                 kunmap(page);
723                 if (rc) {
724                         rc = -EFAULT;
725                         goto cleanup;
726                 }
727                 off += to_copy;
728                 if (off >= copied)
729                         break;
730         }
731         rc = copied;
732
733 cleanup:
734         list_for_each_safe(pos, n, &my_pages) {
735                 page = list_entry(pos, struct page, list);
736                 list_del(&page->list);
737                 __free_page(page);
738         }
739         return rc;
740 }
741
742 /* FIXME: I'm not very smart; someone smarter should make this better. */
743 void
744 portals_debug_msg(int subsys, int mask, char *file, const char *fn,
745                   const int line, unsigned long stack, char *format, ...)
746 {
747         va_list       ap;
748         unsigned long flags;
749         int           max_nob;
750         int           prefix_nob;
751         int           msg_nob;
752         struct timeval tv;
753         unsigned long base_offset;
754         unsigned long debug_off;
755
756         if (debug_buf == NULL) {
757                 printk("LustreError: portals_debug_msg: debug_buf is NULL!\n");
758                 return;
759         }
760
761         spin_lock_irqsave(&portals_debug_lock, flags);
762         debug_off = atomic_read(&debug_off_a);
763         if (!atomic_read(&debug_daemon_state.paused)) {
764                 unsigned long available;
765                 long delta;
766                 long v = atomic_read(&debug_daemon_next_write);
767
768                 delta = debug_off - v;
769                 available = (delta>=0) ? debug_size-delta : -delta;
770                 // Check if we still have enough debug buffer for CDEBUG
771                 if (available < DAEMON_SND_SIZE) {
772                         /* Drop CDEBUG packets until enough debug_buffer is
773                          * available */
774                         if (debug_daemon_state.overlapped)
775                                  goto out;
776                         /* If this is the first time, leave a marker in the
777                          * output */
778                         debug_daemon_state.overlapped = 1;
779                         format = "DEBUG MARKER: Debug buffer overlapped\n";
780                         printk(KERN_ERR "LustreError: debug daemon buffer "
781                                "overlapped\n");
782                 } else  /* More space just became available */
783                         debug_daemon_state.overlapped = 0;
784         }
785
786         max_nob = debug_size - debug_off + DEBUG_OVERFLOW;
787         if (max_nob <= 0) {
788                 spin_unlock_irqrestore(&portals_debug_lock, flags);
789                 printk("LustreError: logic error in portals_debug_msg: "
790                        "< 0 bytes to write\n");
791                 return;
792         }
793
794         /* NB since we pass a non-zero sized buffer (at least) on the first
795          * print, we can be assured that by the end of all the snprinting,
796          * we _do_ have a terminated buffer, even if our message got truncated.
797          */
798
799         do_gettimeofday(&tv);
800
801         prefix_nob = snprintf(debug_buf + debug_off, max_nob,
802                               "%06x:%06x:%d:%lu.%06lu:%lu:%d:",
803                               subsys, mask, smp_processor_id(),
804                               tv.tv_sec, tv.tv_usec, stack, current->pid);
805         max_nob -= prefix_nob;
806         if(*(format + strlen(format) - 1) != '\n')
807                 *(format + strlen(format)) = '\n';
808
809 #if defined(__arch_um__) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,4,20))
810         msg_nob = snprintf(debug_buf + debug_off + prefix_nob, max_nob,
811                            "%d:(%s:%d:%s()) ",
812                            current->thread.extern_pid, file, line, fn);
813 #elif defined(__arch_um__) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
814         msg_nob = snprintf(debug_buf + debug_off + prefix_nob, max_nob,
815                            "%d:(%s:%d:%s()) ",
816                            current->thread.mode.tt.extern_pid, file, line, fn);
817 #else
818         msg_nob = snprintf(debug_buf + debug_off + prefix_nob, max_nob,
819                            "%d:(%s:%d:%s()) ",
820                            current->pid, file, line, fn);
821 #endif
822
823         va_start(ap, format);
824         msg_nob += vsnprintf(debug_buf + debug_off + prefix_nob + msg_nob,
825                              max_nob, format, ap);
826         max_nob -= msg_nob;
827         va_end(ap);
828
829         /* Print to console, while msg is contiguous in debug_buf */
830         /* NB safely terminated see above */
831         if ((mask & D_EMERG) != 0)
832                 printk(KERN_EMERG "LustreError: %s",
833                        debug_buf + debug_off + prefix_nob);
834         else if ((mask & D_ERROR) != 0)
835                 printk(KERN_ERR "LustreError: %s",
836                        debug_buf + debug_off + prefix_nob);
837         else if ((mask & D_WARNING) != 0)
838                 printk(KERN_WARNING "Lustre: %s",
839                        debug_buf + debug_off + prefix_nob);
840         else if (portal_printk)
841                 printk("<%d>Lustre: %s", portal_printk,
842                        debug_buf+debug_off+prefix_nob);
843         base_offset = debug_off & 0xFFFF;
844
845         debug_off += prefix_nob + msg_nob;
846         if (debug_off > debug_size) {
847                 memcpy(debug_buf, debug_buf + debug_size,
848                        debug_off - debug_size + 1);
849                 debug_off -= debug_size;
850                 debug_wrapped = 1;
851         }
852
853         atomic_set(&debug_off_a, debug_off);
854         if (!atomic_read(&debug_daemon_state.paused) &&
855             ((base_offset+prefix_nob+msg_nob) >= DAEMON_SND_SIZE)) {
856                 debug_daemon_state.daemon_event = 1;
857                 wake_up(&debug_daemon_state.daemon);
858         }
859 out:
860         spin_unlock_irqrestore(&portals_debug_lock, flags);
861 }
862
863 void portals_debug_set_level(unsigned int debug_level)
864 {
865         printk("Lustre: Setting portals debug level to %08x\n", debug_level);
866         portal_debug = debug_level;
867 }
868
869 void portals_run_upcall(char **argv)
870 {
871         int   rc;
872         int   argc;
873         char *envp[] = {
874                 "HOME=/",
875                 "PATH=/sbin:/bin:/usr/sbin:/usr/bin",
876                 NULL};
877         ENTRY;
878
879         argv[0] = portals_upcall;
880         argc = 1;
881         while (argv[argc] != NULL)
882                 argc++;
883
884         LASSERT(argc >= 2);
885
886         rc = USERMODEHELPER(argv[0], argv, envp);
887         if (rc < 0) {
888                 CERROR("Error %d invoking portals upcall %s %s%s%s%s%s%s%s%s; "
889                        "check /proc/sys/portals/upcall\n",
890                        rc, argv[0], argv[1],
891                        argc < 3 ? "" : ",", argc < 3 ? "" : argv[2],
892                        argc < 4 ? "" : ",", argc < 4 ? "" : argv[3],
893                        argc < 5 ? "" : ",", argc < 5 ? "" : argv[4],
894                        argc < 6 ? "" : ",...");
895         } else {
896                 CERROR("Invoked portals upcall %s %s%s%s%s%s%s%s%s\n",
897                        argv[0], argv[1],
898                        argc < 3 ? "" : ",", argc < 3 ? "" : argv[2],
899                        argc < 4 ? "" : ",", argc < 4 ? "" : argv[3],
900                        argc < 5 ? "" : ",", argc < 5 ? "" : argv[4],
901                        argc < 6 ? "" : ",...");
902         }
903 }
904
905 void portals_run_lbug_upcall(char *file, const char *fn, const int line)
906 {
907         char *argv[6];
908         char buf[32];
909
910         ENTRY;
911         snprintf (buf, sizeof buf, "%d", line);
912
913         argv[1] = "LBUG";
914         argv[2] = file;
915         argv[3] = (char *)fn;
916         argv[4] = buf;
917         argv[5] = NULL;
918
919         portals_run_upcall (argv);
920 }
921
922 char *portals_nid2str(int nal, ptl_nid_t nid, char *str)
923 {
924         switch(nal){
925         case TCPNAL:
926                 /* userspace NAL */
927         case SOCKNAL:
928                 sprintf(str, "%u:%d.%d.%d.%d", (__u32)(nid >> 32),
929                         HIPQUAD(nid));
930                 break;
931         case QSWNAL:
932         case GMNAL:
933         case IBNAL:
934         case SCIMACNAL:
935                 sprintf(str, "%u:%u", (__u32)(nid >> 32), (__u32)nid);
936                 break;
937         default:
938                 return NULL;
939         }
940         return str;
941 }
942
943 #ifdef __KERNEL__
944 #include <linux/lustre_version.h>
945 #if (LUSTRE_KERNEL_VERSION >= 30)
946 #warning "FIXME: remove workaround when l30 is widely used"
947 char stack_backtrace[LUSTRE_TRACE_SIZE];
948 spinlock_t stack_backtrace_lock = SPIN_LOCK_UNLOCKED;
949
950 #if defined(__arch_um__)
951
952 extern int is_kernel_text_address(unsigned long addr);
953
954 char *portals_debug_dumpstack(void)
955 {
956         asm("int $3");
957 }
958
959 #elif defined(__i386__)
960
961 extern int is_kernel_text_address(unsigned long addr);
962 extern int lookup_symbol(unsigned long address, char *buf, int buflen);
963
964 char *portals_debug_dumpstack(void)
965 {
966         unsigned long esp = current->thread.esp;
967         unsigned long *stack = (unsigned long *)&esp;
968         int size;
969         unsigned long addr;
970         char *buf = stack_backtrace;
971         char *pbuf = buf;
972         static char buffer[512];
973         int rc = 0;
974
975         /* User space on another CPU? */
976         if ((esp ^ (unsigned long)current) & (PAGE_MASK<<1)){
977                 buf[0] = '\0';
978                 goto out;
979         }
980
981         size = sprintf(pbuf, " Call Trace: ");
982         pbuf += size;
983         while (((long) stack & (THREAD_SIZE-1)) != 0) {
984                 addr = *stack++;
985                 if (is_kernel_text_address(addr)) {
986                         rc = lookup_symbol(addr, buffer, 512);
987                         if (rc == -ENOSYS) {
988                                 if (buf + LUSTRE_TRACE_SIZE <= pbuf + 12)
989                                         break;
990                                 size = sprintf(pbuf, "[<%08lx>] ", addr);
991                         } else {
992                                 if (buf + LUSTRE_TRACE_SIZE
993                                             /* fix length + sizeof('\0') */
994                                     <= pbuf + strlen(buffer) + 28 + 1)
995                                         break;
996                                 size = sprintf(pbuf, "([<%08lx>] %s (0x%p)) ",
997                                                addr, buffer, stack-1);
998                         }
999                         pbuf += size;
1000                 }
1001         }
1002 out:
1003         return buf;
1004 }
1005
1006 #else /* !__arch_um__ && !__i386__ */
1007
1008 char *portals_debug_dumpstack(void)
1009 {
1010         char *buf = stack_backtrace;
1011         buf[0] = '\0';
1012         return buf;
1013 }
1014
1015 #endif /* __arch_um__ */
1016 EXPORT_SYMBOL(stack_backtrace_lock);
1017 EXPORT_SYMBOL(portals_debug_dumpstack);
1018 #endif /* LUSTRE_KERNEL_VERSION < 30 */
1019 #endif /* __KERNEL__ */
1020
1021 EXPORT_SYMBOL(portals_debug_dumplog);
1022 EXPORT_SYMBOL(portals_debug_msg);
1023 EXPORT_SYMBOL(portals_debug_set_level);
1024 EXPORT_SYMBOL(portals_run_upcall);
1025 EXPORT_SYMBOL(portals_run_lbug_upcall);
1026 EXPORT_SYMBOL(portals_nid2str);