Whamcloud - gitweb
b=2252
[fs/lustre-release.git] / lustre / portals / include / linux / kp30.h
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  */
4 #ifndef _KP30_INCLUDED
5 #define _KP30_INCLUDED
6
7 #define PORTAL_DEBUG
8
9 #ifndef offsetof
10 # define offsetof(typ,memb)     ((int)((char *)&(((typ *)0)->memb)))
11 #endif
12
13 #define LOWEST_BIT_SET(x)       ((x) & ~((x) - 1))
14
15 /*
16  *  Debugging
17  */
18 extern unsigned int portal_subsystem_debug;
19 extern unsigned int portal_stack;
20 extern unsigned int portal_debug;
21 extern unsigned int portal_printk;
22 extern unsigned int portal_cerror;
23 /* Debugging subsystems (32 bits, non-overlapping) */
24 #define S_UNDEFINED    (1 << 0)
25 #define S_MDC          (1 << 1)
26 #define S_MDS          (1 << 2)
27 #define S_OSC          (1 << 3)
28 #define S_OST          (1 << 4)
29 #define S_CLASS        (1 << 5)
30 #define S_LOG          (1 << 6)
31 #define S_LLITE        (1 << 7)
32 #define S_RPC          (1 << 8)
33 #define S_MGMT         (1 << 9)
34 #define S_PORTALS     (1 << 10)
35 #define S_SOCKNAL     (1 << 11)
36 #define S_QSWNAL      (1 << 12)
37 #define S_PINGER      (1 << 13)
38 #define S_FILTER      (1 << 14)
39 #define S_PTLBD       (1 << 15)
40 #define S_ECHO        (1 << 16)
41 #define S_LDLM        (1 << 17)
42 #define S_LOV         (1 << 18)
43 #define S_GMNAL       (1 << 19)
44 #define S_PTLROUTER   (1 << 20)
45 #define S_COBD        (1 << 21)
46 #define S_IBNAL       (1 << 22)
47
48 /* If you change these values, please keep portals/utils/debug.c
49  * up to date! */
50
51 /* Debugging masks (32 bits, non-overlapping) */
52 #define D_TRACE     (1 << 0) /* ENTRY/EXIT markers */
53 #define D_INODE     (1 << 1)
54 #define D_SUPER     (1 << 2)
55 #define D_EXT2      (1 << 3) /* anything from ext2_debug */
56 #define D_MALLOC    (1 << 4) /* print malloc, free information */
57 #define D_CACHE     (1 << 5) /* cache-related items */
58 #define D_INFO      (1 << 6) /* general information */
59 #define D_IOCTL     (1 << 7) /* ioctl related information */
60 #define D_BLOCKS    (1 << 8) /* ext2 block allocation */
61 #define D_NET       (1 << 9) /* network communications */
62 #define D_WARNING   (1 << 10) /* CWARN(...) == CDEBUG (D_WARNING, ...) */
63 #define D_BUFFS     (1 << 11)
64 #define D_OTHER     (1 << 12)
65 #define D_DENTRY    (1 << 13)
66 #define D_PORTALS   (1 << 14) /* ENTRY/EXIT markers */
67 #define D_PAGE      (1 << 15) /* bulk page handling */
68 #define D_DLMTRACE  (1 << 16)
69 #define D_ERROR     (1 << 17) /* CERROR(...) == CDEBUG (D_ERROR, ...) */
70 #define D_EMERG     (1 << 18) /* CEMERG(...) == CDEBUG (D_EMERG, ...) */
71 #define D_HA        (1 << 19) /* recovery and failover */
72 #define D_RPCTRACE  (1 << 20) /* for distributed debugging */
73 #define D_VFSTRACE  (1 << 21)
74 #define D_READA     (1 << 22) /* read-ahead */
75
76 #ifdef __KERNEL__
77 # include <linux/sched.h> /* THREAD_SIZE */
78 #else 
79 # ifndef THREAD_SIZE /* x86_64 has THREAD_SIZE in userspace */
80 #  define THREAD_SIZE 8192
81 # endif
82 #endif
83
84 #define LUSTRE_TRACE_SIZE (THREAD_SIZE >> 5)
85
86 #ifdef __KERNEL__
87 # ifdef  __ia64__
88 #  define CDEBUG_STACK (THREAD_SIZE -                                      \
89                         ((unsigned long)__builtin_dwarf_cfa() &            \
90                          (THREAD_SIZE - 1)))
91 # else
92 #  define CDEBUG_STACK (THREAD_SIZE -                                      \
93                         ((unsigned long)__builtin_frame_address(0) &       \
94                          (THREAD_SIZE - 1)))
95 # endif
96
97 #define CHECK_STACK(stack)                                                    \
98         do {                                                                  \
99                 if ((stack) > 3*THREAD_SIZE/4 && (stack) > portal_stack) {    \
100                         portals_debug_msg(DEBUG_SUBSYSTEM, D_ERROR,           \
101                                           __FILE__, __FUNCTION__, __LINE__,   \
102                                           (stack),                            \
103                                           "maximum lustre stack %u\n",        \
104                                           portal_stack = (stack));            \
105                       /*panic("LBUG");*/                                      \
106                 }                                                             \
107         } while (0)
108 #else /* __KERNEL__ */
109 #define CHECK_STACK(stack) do { } while(0)
110 #define CDEBUG_STACK (0L)
111 #endif /* __KERNEL__ */
112
113 #if 1
114 #define CDEBUG(mask, format, a...)                                            \
115 do {                                                                          \
116         if (portal_cerror == 0)                                               \
117                 break;                                                        \
118         CHECK_STACK(CDEBUG_STACK);                                            \
119         if (!(mask) || ((mask) & (D_ERROR | D_EMERG | D_WARNING)) ||          \
120             (portal_debug & (mask) &&                                         \
121              portal_subsystem_debug & DEBUG_SUBSYSTEM))                       \
122                 portals_debug_msg(DEBUG_SUBSYSTEM, mask,                      \
123                                   __FILE__, __FUNCTION__, __LINE__,           \
124                                   CDEBUG_STACK, format, ## a);                \
125 } while (0)
126
127 #define CWARN(format, a...) CDEBUG(D_WARNING, format, ## a)
128 #define CERROR(format, a...) CDEBUG(D_ERROR, format, ## a)
129 #define CEMERG(format, a...) CDEBUG(D_EMERG, format, ## a)
130
131 #define GOTO(label, rc)                                                 \
132 do {                                                                    \
133         long GOTO__ret = (long)(rc);                                    \
134         CDEBUG(D_TRACE,"Process leaving via %s (rc=%lu : %ld : %lx)\n", \
135                #label, (unsigned long)GOTO__ret, (signed long)GOTO__ret,\
136                (signed long)GOTO__ret);                                 \
137         goto label;                                                     \
138 } while (0)
139
140 #define RETURN(rc)                                                      \
141 do {                                                                    \
142         typeof(rc) RETURN__ret = (rc);                                  \
143         CDEBUG(D_TRACE, "Process leaving (rc=%lu : %ld : %lx)\n",       \
144                (long)RETURN__ret, (long)RETURN__ret, (long)RETURN__ret);\
145         return RETURN__ret;                                             \
146 } while (0)
147
148 #define ENTRY                                                           \
149 do {                                                                    \
150         CDEBUG(D_TRACE, "Process entered\n");                           \
151 } while (0)
152
153 #define EXIT                                                            \
154 do {                                                                    \
155         CDEBUG(D_TRACE, "Process leaving\n");                           \
156 } while(0)
157 #else
158 #define CDEBUG(mask, format, a...)      do { } while (0)
159 #define CWARN(format, a...)             do { } while (0)
160 #define CERROR(format, a...)            printk("<3>" format, ## a)
161 #define CEMERG(format, a...)            printk("<0>" format, ## a)
162 #define GOTO(label, rc)                 do { (void)(rc); goto label; } while (0)
163 #define RETURN(rc)                      return (rc)
164 #define ENTRY                           do { } while (0)
165 #define EXIT                            do { } while (0)
166 #endif
167
168 #ifdef __KERNEL__
169 # include <linux/vmalloc.h>
170 # include <linux/time.h>
171 # include <linux/slab.h>
172 # include <linux/interrupt.h>
173 # include <linux/highmem.h>
174 # include <linux/module.h>
175 # include <linux/version.h>
176 # include <portals/lib-nal.h>
177 # include <linux/smp_lock.h>
178 # include <asm/atomic.h>
179
180 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
181 #define schedule_work schedule_task
182 #define prepare_work(wq,cb,cbdata)                                            \
183 do {                                                                          \
184         INIT_TQUEUE((wq), 0, 0);                                              \
185         PREPARE_TQUEUE((wq), (cb), (cbdata));                                 \
186 } while (0)
187
188 #define ll_invalidate_inode_pages invalidate_inode_pages
189 #define PageUptodate Page_Uptodate
190 #define our_recalc_sigpending(current) recalc_sigpending(current)
191 #define num_online_cpus() smp_num_cpus
192 static inline void our_cond_resched(void)
193 {
194         if (current->need_resched)
195                schedule ();
196 }
197 #define work_struct_t       struct tq_struct 
198
199 #else
200
201 #define prepare_work(wq,cb,cbdata)                                            \
202 do {                                                                          \
203         INIT_WORK((wq), (void *)(cb), (void *)(cbdata));                      \
204 } while (0)
205 #define ll_invalidate_inode_pages(inode) invalidate_inode_pages((inode)->i_mapping)
206 #define wait_on_page wait_on_page_locked
207 #define our_recalc_sigpending(current) recalc_sigpending()
208 #define strtok(a,b) strpbrk(a, b)
209 static inline void our_cond_resched(void)
210 {
211         cond_resched();
212 }
213 #define work_struct_t      struct work_struct
214
215 #endif /* LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0) */
216
217 #ifdef PORTAL_DEBUG
218 extern void kportal_assertion_failed(char *expr, char *file, const char *func,
219                                      const int line);
220 #define LASSERT(e) ((e) ? 0 : kportal_assertion_failed( #e , __FILE__,  \
221                                                         __FUNCTION__, __LINE__))
222 /* it would be great to dump_stack() here, but some kernels
223  * export it as show_stack() and I can't be bothered to
224  * proprely engage in that dance right now */ 
225 #define LASSERTF(cond, fmt...)                                                \
226         do {                                                                  \
227                 if (unlikely(!(cond))) {                                      \
228                         portals_debug_msg(0, D_EMERG,  __FILE__, __FUNCTION__,\
229                                           __LINE__,  CDEBUG_STACK,            \
230                                           "ASSERTION(" #cond ") failed:" fmt);\
231                         LBUG();                                               \
232                 }                                                             \
233         } while (0)
234                                 
235 #else
236 #define LASSERT(e)
237 #define LASSERTF(cond, fmt...) do { } while (0)
238 #endif
239
240 #ifdef __arch_um__
241 #define LBUG_WITH_LOC(file, func, line)                                 \
242 do {                                                                    \
243         CEMERG("LBUG - trying to dump log to /tmp/lustre-log\n");       \
244         portals_debug_dumplog();                                        \
245         portals_run_lbug_upcall(file, func, line);                      \
246         panic("LBUG");                                                  \
247 } while (0)
248 #else
249 #define LBUG_WITH_LOC(file, func, line)                                 \
250 do {                                                                    \
251         CEMERG("LBUG\n");                                               \
252         portals_debug_dumplog();                                        \
253         portals_run_lbug_upcall(file, func, line);                      \
254         set_task_state(current, TASK_UNINTERRUPTIBLE);                  \
255         schedule();                                                     \
256 } while (0)
257 #endif /* __arch_um__ */
258
259 #define LBUG() LBUG_WITH_LOC(__FILE__, __FUNCTION__, __LINE__)
260
261 /*
262  * Memory
263  */
264 #ifdef PORTAL_DEBUG
265 extern atomic_t portal_kmemory;
266
267 # define portal_kmem_inc(ptr, size)                                           \
268 do {                                                                          \
269         atomic_add(size, &portal_kmemory);                                    \
270 } while (0)
271
272 # define portal_kmem_dec(ptr, size) do {                                      \
273         atomic_sub(size, &portal_kmemory);                                    \
274 } while (0)
275
276 #else
277 # define portal_kmem_inc(ptr, size) do {} while (0)
278 # define portal_kmem_dec(ptr, size) do {} while (0)
279 #endif /* PORTAL_DEBUG */
280
281 #define PORTAL_VMALLOC_SIZE        16384
282
283 #define PORTAL_ALLOC_GFP(ptr, size, mask)                                 \
284 do {                                                                      \
285         LASSERT (!in_interrupt());                                        \
286         if ((size) > PORTAL_VMALLOC_SIZE)                                 \
287                 (ptr) = vmalloc(size);                                    \
288         else                                                              \
289                 (ptr) = kmalloc((size), (mask));                          \
290         if ((ptr) == NULL) {                                              \
291                 CERROR("PORTALS: out of memory at %s:%d (tried to alloc '"\
292                        #ptr "' = %d)\n", __FILE__, __LINE__, (int)(size));\
293                 CERROR("PORTALS: %d total bytes allocated by portals\n",  \
294                        atomic_read(&portal_kmemory));                     \
295         } else {                                                          \
296                 portal_kmem_inc((ptr), (size));                           \
297                 memset((ptr), 0, (size));                                 \
298         }                                                                 \
299         CDEBUG(D_MALLOC, "kmalloced '" #ptr "': %d at %p (tot %d).\n",    \
300                (int)(size), (ptr), atomic_read (&portal_kmemory));        \
301 } while (0)
302
303 #define PORTAL_ALLOC(ptr, size) \
304         PORTAL_ALLOC_GFP(ptr, size, GFP_NOFS)
305
306 #define PORTAL_ALLOC_ATOMIC(ptr, size) \
307         PORTAL_ALLOC_GFP(ptr, size, GFP_ATOMIC)
308
309 #define PORTAL_FREE(ptr, size)                                          \
310 do {                                                                    \
311         int s = (size);                                                 \
312         if ((ptr) == NULL) {                                            \
313                 CERROR("PORTALS: free NULL '" #ptr "' (%d bytes) at "   \
314                        "%s:%d\n", s, __FILE__, __LINE__);               \
315                 break;                                                  \
316         }                                                               \
317         if (s > PORTAL_VMALLOC_SIZE)                                    \
318                 vfree(ptr);                                             \
319         else                                                            \
320                 kfree(ptr);                                             \
321         portal_kmem_dec((ptr), s);                                      \
322         CDEBUG(D_MALLOC, "kfreed '" #ptr "': %d at %p (tot %d).\n",     \
323                s, (ptr), atomic_read(&portal_kmemory));                 \
324 } while (0)
325
326 #define PORTAL_SLAB_ALLOC(ptr, slab, size)                                \
327 do {                                                                      \
328         LASSERT(!in_interrupt());                                         \
329         (ptr) = kmem_cache_alloc((slab), SLAB_NOFS);                      \
330         if ((ptr) == NULL) {                                              \
331                 CERROR("PORTALS: out of memory at %s:%d (tried to alloc"  \
332                        " '" #ptr "' from slab '" #slab "')\n", __FILE__,  \
333                        __LINE__);                                         \
334                 CERROR("PORTALS: %d total bytes allocated by portals\n",  \
335                        atomic_read(&portal_kmemory));                     \
336         } else {                                                          \
337                 portal_kmem_inc((ptr), (size));                           \
338                 memset((ptr), 0, (size));                                 \
339         }                                                                 \
340         CDEBUG(D_MALLOC, "kmalloced '" #ptr "': %d at %p (tot %d).\n",    \
341                (int)(size), (ptr), atomic_read(&portal_kmemory));         \
342 } while (0)
343
344 #define PORTAL_SLAB_FREE(ptr, slab, size)                               \
345 do {                                                                    \
346         int s = (size);                                                 \
347         if ((ptr) == NULL) {                                            \
348                 CERROR("PORTALS: free NULL '" #ptr "' (%d bytes) at "   \
349                        "%s:%d\n", s, __FILE__, __LINE__);               \
350                 break;                                                  \
351         }                                                               \
352         memset((ptr), 0x5a, s);                                         \
353         kmem_cache_free((slab), ptr);                                   \
354         portal_kmem_dec((ptr), s);                                      \
355         CDEBUG(D_MALLOC, "kfreed '" #ptr "': %d at %p (tot %d).\n",     \
356                s, (ptr), atomic_read (&portal_kmemory));                \
357 } while (0)
358
359 /* ------------------------------------------------------------------- */
360
361 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
362
363 #define PORTAL_SYMBOL_REGISTER(x) inter_module_register(#x, THIS_MODULE, &x)
364 #define PORTAL_SYMBOL_UNREGISTER(x) inter_module_unregister(#x)
365
366 #define PORTAL_SYMBOL_GET(x) ((typeof(&x))inter_module_get(#x))
367 #define PORTAL_SYMBOL_PUT(x) inter_module_put(#x)
368
369 #define PORTAL_MODULE_USE       MOD_INC_USE_COUNT
370 #define PORTAL_MODULE_UNUSE     MOD_DEC_USE_COUNT
371 #else
372
373 #define PORTAL_SYMBOL_REGISTER(x)
374 #define PORTAL_SYMBOL_UNREGISTER(x)
375
376 #define PORTAL_SYMBOL_GET(x) symbol_get(x)
377 #define PORTAL_SYMBOL_PUT(x) symbol_put(x)
378
379 #define PORTAL_MODULE_USE       try_module_get(THIS_MODULE)
380 #define PORTAL_MODULE_UNUSE     module_put(THIS_MODULE)
381
382 #endif
383
384 /******************************************************************************/
385 /* Kernel Portals Router interface */
386
387 typedef void (*kpr_fwd_callback_t)(void *arg, int error); // completion callback
388
389 /* space for routing targets to stash "stuff" in a forwarded packet */
390 typedef union {
391         long long        _alignment;
392         void            *_space[16];            /* scale with CPU arch */
393 } kprfd_scratch_t;
394
395 /* Kernel Portals Routing Forwarded message Descriptor */
396 typedef struct {
397         struct list_head     kprfd_list;        /* stash in queues (routing target can use) */
398         ptl_nid_t            kprfd_target_nid;  /* final destination NID */
399         ptl_nid_t            kprfd_gateway_nid; /* gateway NID */
400         int                  kprfd_nob;         /* # message bytes (including header) */
401         int                  kprfd_niov;        /* # message frags (including header) */
402         struct iovec        *kprfd_iov;         /* message fragments */
403         void                *kprfd_router_arg;  // originating NAL's router arg
404         kpr_fwd_callback_t   kprfd_callback;    /* completion callback */
405         void                *kprfd_callback_arg; /* completion callback arg */
406         kprfd_scratch_t      kprfd_scratch;    // scratchpad for routing targets
407 } kpr_fwd_desc_t;
408
409 typedef void  (*kpr_fwd_t)(void *arg, kpr_fwd_desc_t *fwd);
410 typedef void  (*kpr_notify_t)(void *arg, ptl_nid_t peer, int alive);
411
412 /* NAL's routing interface (Kernel Portals Routing Nal Interface) */
413 typedef const struct {
414         int             kprni_nalid;    /* NAL's id */
415         void           *kprni_arg;      /* Arg to pass when calling into NAL */
416         kpr_fwd_t       kprni_fwd;      /* NAL's forwarding entrypoint */
417         kpr_notify_t    kprni_notify;   /* NAL's notification entrypoint */
418 } kpr_nal_interface_t;
419
420 /* Router's routing interface (Kernel Portals Routing Router Interface) */
421 typedef const struct {
422         /* register the calling NAL with the router and get back the handle for
423          * subsequent calls */
424         int     (*kprri_register) (kpr_nal_interface_t *nal_interface,
425                                    void **router_arg);
426
427         /* ask the router to find a gateway that forwards to 'nid' and is a
428          * peer of the calling NAL; assume caller will send 'nob' bytes of
429          * payload there */
430         int     (*kprri_lookup) (void *router_arg, ptl_nid_t nid, int nob,
431                                  ptl_nid_t *gateway_nid);
432
433         /* hand a packet over to the router for forwarding */
434         kpr_fwd_t kprri_fwd_start;
435
436         /* hand a packet back to the router for completion */
437         void    (*kprri_fwd_done) (void *router_arg, kpr_fwd_desc_t *fwd,
438                                    int error);
439
440         /* notify the router about peer state */
441         void    (*kprri_notify) (void *router_arg, ptl_nid_t peer,
442                                  int alive, time_t when);
443
444         /* the calling NAL is shutting down */
445         void    (*kprri_shutdown) (void *router_arg);
446
447         /* deregister the calling NAL with the router */
448         void    (*kprri_deregister) (void *router_arg);
449
450 } kpr_router_interface_t;
451
452 /* Convenient struct for NAL to stash router interface/args */
453 typedef struct {
454         kpr_router_interface_t  *kpr_interface;
455         void                    *kpr_arg;
456 } kpr_router_t;
457
458 /* Router's control interface (Kernel Portals Routing Control Interface) */
459 typedef const struct {
460         int     (*kprci_add_route)(int gateway_nal, ptl_nid_t gateway_nid,
461                                    ptl_nid_t lo_nid, ptl_nid_t hi_nid);
462         int     (*kprci_del_route)(int gateway_nal, ptl_nid_t gateway_nid,
463                                    ptl_nid_t lo_nid, ptl_nid_t hi_nid);
464         int     (*kprci_get_route)(int index, int *gateway_nal,
465                                    ptl_nid_t *gateway,
466                                    ptl_nid_t *lo_nid, ptl_nid_t *hi_nid,
467                                    int *alive);
468         int     (*kprci_notify)(int gateway_nal, ptl_nid_t gateway_nid, 
469                                 int alive, time_t when);
470 } kpr_control_interface_t;
471
472 extern kpr_control_interface_t  kpr_control_interface;
473 extern kpr_router_interface_t   kpr_router_interface;
474
475 static inline int
476 kpr_register (kpr_router_t *router, kpr_nal_interface_t *nalif)
477 {
478         int    rc;
479
480         router->kpr_interface = PORTAL_SYMBOL_GET (kpr_router_interface);
481         if (router->kpr_interface == NULL)
482                 return (-ENOENT);
483
484         rc = (router->kpr_interface)->kprri_register (nalif, &router->kpr_arg);
485         if (rc != 0)
486                 router->kpr_interface = NULL;
487
488         PORTAL_SYMBOL_PUT (kpr_router_interface);
489         return (rc);
490 }
491
492 static inline int
493 kpr_routing (kpr_router_t *router)
494 {
495         return (router->kpr_interface != NULL);
496 }
497
498 static inline int
499 kpr_lookup (kpr_router_t *router, ptl_nid_t nid, int nob, ptl_nid_t *gateway_nid)
500 {
501         if (!kpr_routing (router))
502                 return (-ENETUNREACH);
503
504         return (router->kpr_interface->kprri_lookup(router->kpr_arg, nid, nob,
505                                                     gateway_nid));
506 }
507
508 static inline void
509 kpr_fwd_init (kpr_fwd_desc_t *fwd, ptl_nid_t nid,
510               int nob, int niov, struct iovec *iov,
511               kpr_fwd_callback_t callback, void *callback_arg)
512 {
513         fwd->kprfd_target_nid   = nid;
514         fwd->kprfd_gateway_nid  = nid;
515         fwd->kprfd_nob          = nob;
516         fwd->kprfd_niov         = niov;
517         fwd->kprfd_iov          = iov;
518         fwd->kprfd_callback     = callback;
519         fwd->kprfd_callback_arg = callback_arg;
520 }
521
522 static inline void
523 kpr_fwd_start (kpr_router_t *router, kpr_fwd_desc_t *fwd)
524 {
525         if (!kpr_routing (router))
526                 fwd->kprfd_callback (fwd->kprfd_callback_arg, -ENETUNREACH);
527         else
528                 router->kpr_interface->kprri_fwd_start (router->kpr_arg, fwd);
529 }
530
531 static inline void
532 kpr_fwd_done (kpr_router_t *router, kpr_fwd_desc_t *fwd, int error)
533 {
534         LASSERT (kpr_routing (router));
535         router->kpr_interface->kprri_fwd_done (router->kpr_arg, fwd, error);
536 }
537
538 static inline void
539 kpr_notify (kpr_router_t *router, 
540             ptl_nid_t peer, int alive, time_t when)
541 {
542         if (!kpr_routing (router))
543                 return;
544         
545         router->kpr_interface->kprri_notify(router->kpr_arg, peer, alive, when);
546 }
547
548 static inline void
549 kpr_shutdown (kpr_router_t *router)
550 {
551         if (kpr_routing (router))
552                 router->kpr_interface->kprri_shutdown (router->kpr_arg);
553 }
554
555 static inline void
556 kpr_deregister (kpr_router_t *router)
557 {
558         if (!kpr_routing (router))
559                 return;
560         router->kpr_interface->kprri_deregister (router->kpr_arg);
561         router->kpr_interface = NULL;
562 }
563
564 /******************************************************************************/
565
566 #ifdef PORTALS_PROFILING
567 #define prof_enum(FOO) PROF__##FOO
568 enum {
569         prof_enum(our_recvmsg),
570         prof_enum(our_sendmsg),
571         prof_enum(socknal_recv),
572         prof_enum(lib_parse),
573         prof_enum(conn_list_walk),
574         prof_enum(memcpy),
575         prof_enum(lib_finalize),
576         prof_enum(pingcli_time),
577         prof_enum(gmnal_send),
578         prof_enum(gmnal_recv),
579         MAX_PROFS
580 };
581
582 struct prof_ent {
583         char *str;
584         /* hrmph.  wrap-tastic. */
585         u32       starts;
586         u32       finishes;
587         cycles_t  total_cycles;
588         cycles_t  start;
589         cycles_t  end;
590 };
591
592 extern struct prof_ent prof_ents[MAX_PROFS];
593
594 #define PROF_START(FOO)                                         \
595         do {                                                    \
596                 struct prof_ent *pe = &prof_ents[PROF__##FOO];  \
597                 pe->starts++;                                   \
598                 pe->start = get_cycles();                       \
599         } while (0)
600
601 #define PROF_FINISH(FOO)                                        \
602         do {                                                    \
603                 struct prof_ent *pe = &prof_ents[PROF__##FOO];  \
604                 pe->finishes++;                                 \
605                 pe->end = get_cycles();                         \
606                 pe->total_cycles += (pe->end - pe->start);      \
607         } while (0)
608 #else /* !PORTALS_PROFILING */
609 #define PROF_START(FOO) do {} while(0)
610 #define PROF_FINISH(FOO) do {} while(0)
611 #endif /* PORTALS_PROFILING */
612
613 /* debug.c */
614 extern spinlock_t stack_backtrace_lock;
615
616 char *portals_debug_dumpstack(void);
617 void portals_run_upcall(char **argv);
618 void portals_run_lbug_upcall(char * file, const char *fn, const int line);
619 void portals_debug_dumplog(void);
620 int portals_debug_init(unsigned long bufsize);
621 int portals_debug_cleanup(void);
622 int portals_debug_clear_buffer(void);
623 int portals_debug_mark_buffer(char *text);
624 int portals_debug_set_daemon(unsigned int cmd, unsigned int length,
625                              char *file, unsigned int size);
626 __s32 portals_debug_copy_to_user(char *buf, unsigned long len);
627 #if (__GNUC__)
628 /* Use the special GNU C __attribute__ hack to have the compiler check the
629  * printf style argument string against the actual argument count and
630  * types.
631  */
632 #ifdef printf
633 # warning printf has been defined as a macro...
634 # undef printf
635 #endif
636 void portals_debug_msg(int subsys, int mask, char *file, const char *fn,
637                        const int line, unsigned long stack,
638                        char *format, ...)
639         __attribute__ ((format (printf, 7, 8)));
640 #else
641 void portals_debug_msg(int subsys, int mask, char *file, const char *fn,
642                        const int line, unsigned long stack,
643                        const char *format, ...);
644 #endif /* __GNUC__ */
645 void portals_debug_set_level(unsigned int debug_level);
646
647 # define fprintf(a, format, b...) CDEBUG(D_OTHER, format , ## b)
648 # define printf(format, b...) CDEBUG(D_OTHER, format , ## b)
649 # define time(a) CURRENT_TIME
650
651 extern void kportal_daemonize (char *name);
652 extern void kportal_blockallsigs (void);
653
654 #else  /* !__KERNEL__ */
655 # include <stdio.h>
656 # include <stdlib.h>
657 #ifndef __CYGWIN__
658 # include <stdint.h>
659 #else
660 # include <cygwin-ioctl.h>
661 #endif
662 # include <unistd.h>
663 # include <time.h>
664 # include <asm/types.h>
665 # ifndef DEBUG_SUBSYSTEM
666 #  define DEBUG_SUBSYSTEM S_UNDEFINED
667 # endif
668 # ifdef PORTAL_DEBUG
669 #  undef NDEBUG
670 #  include <assert.h>
671 #  define LASSERT(e)     assert(e)
672 #  define LASSERTF(cond, args...)     assert(cond)
673 # else
674 #  define LASSERT(e)
675 #  define LASSERTF(cond, args...) do { } while (0)
676 # endif
677 # define printk(format, args...) printf (format, ## args)
678 # define PORTAL_ALLOC(ptr, size) do { (ptr) = malloc(size); } while (0);
679 # define PORTAL_FREE(a, b) do { free(a); } while (0);
680 # define portals_debug_msg(subsys, mask, file, fn, line, stack, format, a...) \
681     printf("%02x:%06x (@%lu %s:%s,l. %d %d %lu): " format,                    \
682            (subsys), (mask), (long)time(0), file, fn, line,                   \
683            getpid() , stack, ## a);
684 #endif
685
686 /* support decl needed both by kernel and liblustre */
687 char *portals_nid2str(int nal, ptl_nid_t nid, char *str);
688
689 #ifndef CURRENT_TIME
690 # define CURRENT_TIME time(0)
691 #endif
692
693 /******************************************************************************/
694 /* Light-weight trace 
695  * Support for temporary event tracing with minimal Heisenberg effect. */
696 #define LWT_SUPPORT  0
697
698 #define LWT_MEMORY   (64<<20)
699 #define LWT_MAX_CPUS 4
700
701 typedef struct {
702         cycles_t    lwte_when;
703         char       *lwte_where;
704         void       *lwte_task;
705         long        lwte_p1;
706         long        lwte_p2;
707         long        lwte_p3;
708         long        lwte_p4;
709 #if BITS_PER_LONG > 32
710         long        lwte_pad;
711 #endif
712 } lwt_event_t;
713
714 #if LWT_SUPPORT
715 #ifdef __KERNEL__
716 #define LWT_EVENTS_PER_PAGE (PAGE_SIZE / sizeof (lwt_event_t))
717
718 typedef struct _lwt_page {
719         struct list_head     lwtp_list;
720         struct page         *lwtp_page;
721         lwt_event_t         *lwtp_events;
722 } lwt_page_t;
723
724 typedef struct {
725         int                lwtc_current_index;
726         lwt_page_t        *lwtc_current_page;
727 } lwt_cpu_t;
728
729 extern int       lwt_enabled;
730 extern lwt_cpu_t lwt_cpus[];
731
732 extern int  lwt_init (void);
733 extern void lwt_fini (void);
734 extern int  lwt_lookup_string (int *size, char *knlptr,
735                                char *usrptr, int usrsize);
736 extern int  lwt_control (int enable, int clear);
737 extern int  lwt_snapshot (cycles_t *now, int *ncpu, int *total_size,
738                           void *user_ptr, int user_size);
739
740 /* Note that we _don't_ define LWT_EVENT at all if LWT_SUPPORT isn't set.
741  * This stuff is meant for finding specific problems; it never stays in
742  * production code... */
743
744 #define LWTSTR(n)       #n
745 #define LWTWHERE(f,l)   f ":" LWTSTR(l)
746
747 #define LWT_EVENT(p1, p2, p3, p4)                                       \
748 do {                                                                    \
749         unsigned long    flags;                                         \
750         lwt_cpu_t       *cpu;                                           \
751         lwt_page_t      *p;                                             \
752         lwt_event_t     *e;                                             \
753                                                                         \
754         local_irq_save (flags);                                         \
755                                                                         \
756         if (lwt_enabled) {                                              \
757                 cpu = &lwt_cpus[smp_processor_id()];                    \
758                 p = cpu->lwtc_current_page;                             \
759                 e = &p->lwtp_events[cpu->lwtc_current_index++];         \
760                                                                         \
761                 if (cpu->lwtc_current_index >= LWT_EVENTS_PER_PAGE) {   \
762                         cpu->lwtc_current_page =                        \
763                                 list_entry (p->lwtp_list.next,          \
764                                             lwt_page_t, lwtp_list);     \
765                         cpu->lwtc_current_index = 0;                    \
766                 }                                                       \
767                                                                         \
768                 e->lwte_when  = get_cycles();                           \
769                 e->lwte_where = LWTWHERE(__FILE__,__LINE__);            \
770                 e->lwte_task  = current;                                \
771                 e->lwte_p1    = (long)(p1);                             \
772                 e->lwte_p2    = (long)(p2);                             \
773                 e->lwte_p3    = (long)(p3);                             \
774                 e->lwte_p4    = (long)(p4);                             \
775         }                                                               \
776                                                                         \
777         local_irq_restore (flags);                                      \
778 } while (0)
779 #else  /* __KERNEL__ */
780 #define LWT_EVENT(p1,p2,p3,p4)     /* no userland implementation yet */
781 #endif /* __KERNEL__ */
782 #endif /* LWT_SUPPORT */
783
784 struct portals_device_userstate
785 {
786         int          pdu_memhog_pages;
787         struct page *pdu_memhog_root_page;
788 };
789
790 #include <linux/portals_lib.h>
791
792 /*
793  * USER LEVEL STUFF BELOW
794  */
795
796 #define PORTALS_CFG_VERSION 0x00010001;
797
798 struct portals_cfg {
799         __u32 pcfg_version;
800         __u32 pcfg_command;
801
802         __u32 pcfg_nal;
803         __u32 pcfg_flags;
804
805         __u32 pcfg_gw_nal;
806         __u64 pcfg_nid;
807         __u64 pcfg_nid2;
808         __u64 pcfg_nid3;
809         __u32 pcfg_id;
810         __u32 pcfg_misc;
811         __u32 pcfg_fd;
812         __u32 pcfg_count;
813         __u32 pcfg_size;
814         __u32 pcfg_wait;
815
816         __u32 pcfg_plen1; /* buffers in userspace */
817         char *pcfg_pbuf1;
818         __u32 pcfg_plen2; /* buffers in userspace */
819         char *pcfg_pbuf2;
820 };
821
822 #define PCFG_INIT(pcfg, cmd)                            \
823 do {                                                    \
824         memset(&pcfg, 0, sizeof(pcfg));                 \
825         pcfg.pcfg_version = PORTALS_CFG_VERSION;        \
826         pcfg.pcfg_command = (cmd);                      \
827                                                         \
828 } while (0)
829
830 #define PORTAL_IOCTL_VERSION 0x00010007
831 #define PING_SYNC       0
832 #define PING_ASYNC      1
833
834 struct portal_ioctl_data {
835         __u32 ioc_len;
836         __u32 ioc_version;
837         __u64 ioc_nid;
838         __u64 ioc_nid2;
839         __u64 ioc_nid3;
840         __u32 ioc_count;
841         __u32 ioc_nal;
842         __u32 ioc_nal_cmd;
843         __u32 ioc_fd;
844         __u32 ioc_id;
845
846         __u32 ioc_flags;
847         __u32 ioc_size;
848
849         __u32 ioc_wait;
850         __u32 ioc_timeout;
851         __u32 ioc_misc;
852
853         __u32 ioc_inllen1;
854         char *ioc_inlbuf1;
855         __u32 ioc_inllen2;
856         char *ioc_inlbuf2;
857
858         __u32 ioc_plen1; /* buffers in userspace */
859         char *ioc_pbuf1;
860         __u32 ioc_plen2; /* buffers in userspace */
861         char *ioc_pbuf2;
862
863         char ioc_bulk[0];
864 };
865
866 struct portal_ioctl_hdr {
867         __u32 ioc_len;
868         __u32 ioc_version;
869 };
870
871 struct portals_debug_ioctl_data
872 {
873         struct portal_ioctl_hdr hdr;
874         unsigned int subs;
875         unsigned int debug;
876 };
877
878 #define PORTAL_IOC_INIT(data)                           \
879 do {                                                    \
880         memset(&data, 0, sizeof(data));                 \
881         data.ioc_version = PORTAL_IOCTL_VERSION;        \
882         data.ioc_len = sizeof(data);                    \
883 } while (0)
884
885 /* FIXME check conflict with lustre_lib.h */
886 #define PTL_IOC_DEBUG_MASK             _IOWR('f', 250, long)
887
888 static inline int portal_ioctl_packlen(struct portal_ioctl_data *data)
889 {
890         int len = sizeof(*data);
891         len += size_round(data->ioc_inllen1);
892         len += size_round(data->ioc_inllen2);
893         return len;
894 }
895
896 static inline int portal_ioctl_is_invalid(struct portal_ioctl_data *data)
897 {
898         if (data->ioc_len > (1<<30)) {
899                 CERROR ("PORTALS ioctl: ioc_len larger than 1<<30\n");
900                 return 1;
901         }
902         if (data->ioc_inllen1 > (1<<30)) {
903                 CERROR ("PORTALS ioctl: ioc_inllen1 larger than 1<<30\n");
904                 return 1;
905         }
906         if (data->ioc_inllen2 > (1<<30)) {
907                 CERROR ("PORTALS ioctl: ioc_inllen2 larger than 1<<30\n");
908                 return 1;
909         }
910         if (data->ioc_inlbuf1 && !data->ioc_inllen1) {
911                 CERROR ("PORTALS ioctl: inlbuf1 pointer but 0 length\n");
912                 return 1;
913         }
914         if (data->ioc_inlbuf2 && !data->ioc_inllen2) {
915                 CERROR ("PORTALS ioctl: inlbuf2 pointer but 0 length\n");
916                 return 1;
917         }
918         if (data->ioc_pbuf1 && !data->ioc_plen1) {
919                 CERROR ("PORTALS ioctl: pbuf1 pointer but 0 length\n");
920                 return 1;
921         }
922         if (data->ioc_pbuf2 && !data->ioc_plen2) {
923                 CERROR ("PORTALS ioctl: pbuf2 pointer but 0 length\n");
924                 return 1;
925         }
926         if (data->ioc_plen1 && !data->ioc_pbuf1) {
927                 CERROR ("PORTALS ioctl: plen1 nonzero but no pbuf1 pointer\n");
928                 return 1;
929         }
930         if (data->ioc_plen2 && !data->ioc_pbuf2) {
931                 CERROR ("PORTALS ioctl: plen2 nonzero but no pbuf2 pointer\n");
932                 return 1;
933         }
934         if (portal_ioctl_packlen(data) != data->ioc_len ) {
935                 CERROR ("PORTALS ioctl: packlen != ioc_len\n");
936                 return 1;
937         }
938         if (data->ioc_inllen1 &&
939             data->ioc_bulk[data->ioc_inllen1 - 1] != '\0') {
940                 CERROR ("PORTALS ioctl: inlbuf1 not 0 terminated\n");
941                 return 1;
942         }
943         if (data->ioc_inllen2 &&
944             data->ioc_bulk[size_round(data->ioc_inllen1) +
945                            data->ioc_inllen2 - 1] != '\0') {
946                 CERROR ("PORTALS ioctl: inlbuf2 not 0 terminated\n");
947                 return 1;
948         }
949         return 0;
950 }
951
952 #ifndef __KERNEL__
953 static inline int portal_ioctl_pack(struct portal_ioctl_data *data, char **pbuf,
954                                     int max)
955 {
956         char *ptr;
957         struct portal_ioctl_data *overlay;
958         data->ioc_len = portal_ioctl_packlen(data);
959         data->ioc_version = PORTAL_IOCTL_VERSION;
960
961         if (*pbuf && portal_ioctl_packlen(data) > max)
962                 return 1;
963         if (*pbuf == NULL) {
964                 *pbuf = malloc(data->ioc_len);
965         }
966         if (!*pbuf)
967                 return 1;
968         overlay = (struct portal_ioctl_data *)*pbuf;
969         memcpy(*pbuf, data, sizeof(*data));
970
971         ptr = overlay->ioc_bulk;
972         if (data->ioc_inlbuf1)
973                 LOGL(data->ioc_inlbuf1, data->ioc_inllen1, ptr);
974         if (data->ioc_inlbuf2)
975                 LOGL(data->ioc_inlbuf2, data->ioc_inllen2, ptr);
976         if (portal_ioctl_is_invalid(overlay))
977                 return 1;
978
979         return 0;
980 }
981 #else
982 #include <asm/uaccess.h>
983
984 /* buffer MUST be at least the size of portal_ioctl_hdr */
985 static inline int portal_ioctl_getdata(char *buf, char *end, void *arg)
986 {
987         struct portal_ioctl_hdr *hdr;
988         struct portal_ioctl_data *data;
989         int err;
990         ENTRY;
991
992         hdr = (struct portal_ioctl_hdr *)buf;
993         data = (struct portal_ioctl_data *)buf;
994
995         err = copy_from_user(buf, (void *)arg, sizeof(*hdr));
996         if ( err ) {
997                 EXIT;
998                 return err;
999         }
1000
1001         if (hdr->ioc_version != PORTAL_IOCTL_VERSION) {
1002                 CERROR ("PORTALS: version mismatch kernel vs application\n");
1003                 return -EINVAL;
1004         }
1005
1006         if (hdr->ioc_len + buf >= end) {
1007                 CERROR ("PORTALS: user buffer exceeds kernel buffer\n");
1008                 return -EINVAL;
1009         }
1010
1011
1012         if (hdr->ioc_len < sizeof(struct portal_ioctl_data)) {
1013                 CERROR ("PORTALS: user buffer too small for ioctl\n");
1014                 return -EINVAL;
1015         }
1016
1017         err = copy_from_user(buf, (void *)arg, hdr->ioc_len);
1018         if ( err ) {
1019                 EXIT;
1020                 return err;
1021         }
1022
1023         if (portal_ioctl_is_invalid(data)) {
1024                 CERROR ("PORTALS: ioctl not correctly formatted\n");
1025                 return -EINVAL;
1026         }
1027
1028         if (data->ioc_inllen1) {
1029                 data->ioc_inlbuf1 = &data->ioc_bulk[0];
1030         }
1031
1032         if (data->ioc_inllen2) {
1033                 data->ioc_inlbuf2 = &data->ioc_bulk[0] +
1034                         size_round(data->ioc_inllen1);
1035         }
1036
1037         EXIT;
1038         return 0;
1039 }
1040 #endif
1041
1042 /* ioctls for manipulating snapshots 30- */
1043 #define IOC_PORTAL_TYPE                   'e'
1044 #define IOC_PORTAL_MIN_NR                 30
1045
1046 #define IOC_PORTAL_PING                    _IOWR('e', 30, long)
1047 #define IOC_PORTAL_GET_DEBUG               _IOWR('e', 31, long)
1048 #define IOC_PORTAL_CLEAR_DEBUG             _IOWR('e', 32, long)
1049 #define IOC_PORTAL_MARK_DEBUG              _IOWR('e', 33, long)
1050 #define IOC_PORTAL_PANIC                   _IOWR('e', 34, long)
1051 #define IOC_PORTAL_NAL_CMD                 _IOWR('e', 35, long)
1052 #define IOC_PORTAL_GET_NID                 _IOWR('e', 36, long)
1053 #define IOC_PORTAL_FAIL_NID                _IOWR('e', 37, long)
1054 #define IOC_PORTAL_SET_DAEMON              _IOWR('e', 38, long)
1055 #define IOC_PORTAL_LWT_CONTROL             _IOWR('e', 39, long)
1056 #define IOC_PORTAL_LWT_SNAPSHOT            _IOWR('e', 40, long)
1057 #define IOC_PORTAL_LWT_LOOKUP_STRING       _IOWR('e', 41, long)
1058 #define IOC_PORTAL_MEMHOG                  _IOWR('e', 42, long)
1059 #define IOC_PORTAL_MAX_NR                             42
1060
1061 enum {
1062         QSWNAL  =  1,
1063         SOCKNAL,
1064         GMNAL,
1065         TOENAL,
1066         TCPNAL,
1067         SCIMACNAL,
1068         ROUTER,
1069         IBNAL,
1070         NAL_ENUM_END_MARKER
1071 };
1072
1073 #ifdef __KERNEL__
1074 extern ptl_handle_ni_t  kqswnal_ni;
1075 extern ptl_handle_ni_t  ksocknal_ni;
1076 extern ptl_handle_ni_t  ktoenal_ni;
1077 extern ptl_handle_ni_t  kgmnal_ni;
1078 extern ptl_handle_ni_t  kibnal_ni;
1079 extern ptl_handle_ni_t  kscimacnal_ni;
1080 #endif
1081
1082 #define PTL_NALFMT_SIZE         16
1083
1084 #define NAL_MAX_NR (NAL_ENUM_END_MARKER - 1)
1085
1086 #define NAL_CMD_REGISTER_PEER_FD     100
1087 #define NAL_CMD_CLOSE_CONNECTION     101
1088 #define NAL_CMD_REGISTER_MYNID       102
1089 #define NAL_CMD_PUSH_CONNECTION      103
1090 #define NAL_CMD_GET_CONN             104
1091 #define NAL_CMD_DEL_AUTOCONN         105
1092 #define NAL_CMD_ADD_AUTOCONN         106
1093 #define NAL_CMD_GET_AUTOCONN         107
1094 #define NAL_CMD_GET_TXDESC           108
1095 #define NAL_CMD_ADD_ROUTE            109
1096 #define NAL_CMD_DEL_ROUTE            110
1097 #define NAL_CMD_GET_ROUTE            111
1098 #define NAL_CMD_NOTIFY_ROUTER        112
1099
1100 enum {
1101         DEBUG_DAEMON_START       =  1,
1102         DEBUG_DAEMON_STOP        =  2,
1103         DEBUG_DAEMON_PAUSE       =  3,
1104         DEBUG_DAEMON_CONTINUE    =  4,
1105 };
1106
1107 /* XXX remove to lustre ASAP */
1108 struct lustre_peer {
1109         ptl_nid_t       peer_nid;
1110         ptl_handle_ni_t peer_ni;
1111 };
1112
1113
1114 /* module.c */
1115 typedef int (*nal_cmd_handler_t)(struct portals_cfg *, void * private);
1116 int kportal_nal_register(int nal, nal_cmd_handler_t handler, void * private);
1117 int kportal_nal_unregister(int nal);
1118
1119 enum cfg_record_type {
1120         PORTALS_CFG_TYPE = 1,
1121         LUSTRE_CFG_TYPE = 123,
1122 };
1123
1124 typedef int (*cfg_record_cb_t)(enum cfg_record_type, int len, void *data);
1125 int kportal_nal_cmd(struct portals_cfg *);
1126
1127 ptl_handle_ni_t *kportal_get_ni (int nal);
1128 void kportal_put_ni (int nal);
1129
1130 #ifdef __CYGWIN__
1131 # ifndef BITS_PER_LONG
1132 #  if (~0UL) == 0xffffffffUL
1133 #   define BITS_PER_LONG 32
1134 #  else
1135 #   define BITS_PER_LONG 64
1136 #  endif
1137 # endif
1138 #endif
1139
1140 #if defined(__x86_64__)
1141 # define LPU64 "%Lu"
1142 # define LPD64 "%Ld"
1143 # define LPX64 "%#Lx"
1144 # define LPSZ  "%lu"
1145 # define LPSSZ "%ld"
1146 #elif (BITS_PER_LONG == 32 || __WORDSIZE == 32)
1147 # define LPU64 "%Lu"
1148 # define LPD64 "%Ld"
1149 # define LPX64 "%#Lx"
1150 # define LPSZ  "%u"
1151 # define LPSSZ "%d"
1152 #elif (BITS_PER_LONG == 64 || __WORDSIZE == 64)
1153 # define LPU64 "%lu"
1154 # define LPD64 "%ld"
1155 # define LPX64 "%#lx"
1156 # define LPSZ  "%lu"
1157 # define LPSSZ "%ld"
1158 #endif
1159 #ifndef LPU64
1160 # error "No word size defined"
1161 #endif
1162
1163 #endif