Whamcloud - gitweb
cleanup in ptlrpc code, related to ppc platform
[fs/lustre-release.git] / lustre / ldlm / ldlm_lockd.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * Copyright (C) 2002-2004 Cluster File Systems, Inc.
5  *   Author: Peter Braam <braam@clusterfs.com>
6  *   Author: Phil Schwan <phil@clusterfs.com>
7  *
8  *   This file is part of the Lustre file system, http://www.lustre.org
9  *   Lustre is a trademark of Cluster File Systems, Inc.
10  *
11  *   You may have signed or agreed to another license before downloading
12  *   this software.  If so, you are bound by the terms and conditions
13  *   of that agreement, and the following does not apply to you.  See the
14  *   LICENSE file included with this distribution for more information.
15  *
16  *   If you did not agree to a different license, then this copy of Lustre
17  *   is open source software; you can redistribute it and/or modify it
18  *   under the terms of version 2 of the GNU General Public License as
19  *   published by the Free Software Foundation.
20  *
21  *   In either case, Lustre is distributed in the hope that it will be
22  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
23  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  *   license text for more details.
25  */
26
27 #ifndef EXPORT_SYMTAB
28 # define EXPORT_SYMTAB
29 #endif
30 #define DEBUG_SUBSYSTEM S_LDLM
31
32 #ifdef __KERNEL__
33 # include <libcfs/libcfs.h>
34 #else
35 # include <liblustre.h>
36 #endif
37
38 #include <lustre_dlm.h>
39 #include <obd_class.h>
40 #include <libcfs/list.h>
41 #include "ldlm_internal.h"
42
43 #ifdef __KERNEL__
44 static int ldlm_num_threads;
45 CFS_MODULE_PARM(ldlm_num_threads, "i", int, 0444,
46                 "number of DLM service threads to start");
47 #endif
48
49 extern cfs_mem_cache_t *ldlm_resource_slab;
50 extern cfs_mem_cache_t *ldlm_lock_slab;
51 extern struct lustre_lock ldlm_handle_lock;
52
53 static struct semaphore ldlm_ref_sem;
54 static int ldlm_refcount;
55
56 static struct ldlm_state *ldlm_state;
57
58 inline cfs_time_t round_timeout(cfs_time_t timeout)
59 {
60         return cfs_time_seconds((int)cfs_duration_sec(cfs_time_sub(timeout, 0)) + 1);
61 }
62
63 /* timeout for initial callback (AST) reply (bz10399) */
64 static inline unsigned int ldlm_get_rq_timeout(void)
65 {
66         /* Non-AT value */
67         unsigned int timeout = min(ldlm_timeout, obd_timeout / 3);
68
69         return timeout < 1 ? 1 : timeout;
70 }
71
72 #ifdef __KERNEL__
73 /* w_l_spinlock protects both waiting_locks_list and expired_lock_thread */
74 static spinlock_t waiting_locks_spinlock;   /* BH lock (timer) */
75 static struct list_head waiting_locks_list;
76 static cfs_timer_t waiting_locks_timer;
77
78 static struct expired_lock_thread {
79         cfs_waitq_t               elt_waitq;
80         int                       elt_state;
81         int                       elt_dump;
82         struct list_head          elt_expired_locks;
83 } expired_lock_thread;
84 #endif
85
86 #define ELT_STOPPED   0
87 #define ELT_READY     1
88 #define ELT_TERMINATE 2
89
90 struct ldlm_bl_pool {
91         spinlock_t              blp_lock;
92
93         /*
94          * blp_prio_list is used for callbacks that should be handled
95          * as a priority. It is used for LDLM_FL_DISCARD_DATA requests.
96          * see bug 13843
97          */
98         struct list_head        blp_prio_list;
99
100         /*
101          * blp_list is used for all other callbacks which are likely
102          * to take longer to process.
103          */
104         struct list_head        blp_list;
105
106         cfs_waitq_t             blp_waitq;
107         struct completion       blp_comp;
108         atomic_t                blp_num_threads;
109         atomic_t                blp_busy_threads;
110         int                     blp_min_threads;
111         int                     blp_max_threads;
112 };
113
114 struct ldlm_bl_work_item {
115         struct list_head        blwi_entry;
116         struct ldlm_namespace   *blwi_ns;
117         struct ldlm_lock_desc   blwi_ld;
118         struct ldlm_lock        *blwi_lock;
119         struct list_head        blwi_head;
120         int                     blwi_count;
121 };
122
123 #ifdef __KERNEL__
124
125 static inline int have_expired_locks(void)
126 {
127         int need_to_run;
128
129         ENTRY;
130         spin_lock_bh(&waiting_locks_spinlock);
131         need_to_run = !list_empty(&expired_lock_thread.elt_expired_locks);
132         spin_unlock_bh(&waiting_locks_spinlock);
133
134         RETURN(need_to_run);
135 }
136
137 static int expired_lock_main(void *arg)
138 {
139         struct list_head *expired = &expired_lock_thread.elt_expired_locks;
140         struct l_wait_info lwi = { 0 };
141         int do_dump;
142
143         ENTRY;
144         cfs_daemonize("ldlm_elt");
145
146         expired_lock_thread.elt_state = ELT_READY;
147         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
148
149         while (1) {
150                 l_wait_event(expired_lock_thread.elt_waitq,
151                              have_expired_locks() ||
152                              expired_lock_thread.elt_state == ELT_TERMINATE,
153                              &lwi);
154
155                 spin_lock_bh(&waiting_locks_spinlock);
156                 if (expired_lock_thread.elt_dump) {
157                         spin_unlock_bh(&waiting_locks_spinlock);
158
159                         /* from waiting_locks_callback, but not in timer */
160                         libcfs_debug_dumplog();
161                         libcfs_run_lbug_upcall(__FILE__,
162                                                 "waiting_locks_callback",
163                                                 expired_lock_thread.elt_dump);
164
165                         spin_lock_bh(&waiting_locks_spinlock);
166                         expired_lock_thread.elt_dump = 0;
167                 }
168
169                 do_dump = 0;
170
171                 while (!list_empty(expired)) {
172                         struct obd_export *export;
173                         struct ldlm_lock *lock;
174
175                         lock = list_entry(expired->next, struct ldlm_lock,
176                                           l_pending_chain);
177                         if ((void *)lock < LP_POISON + CFS_PAGE_SIZE &&
178                             (void *)lock >= LP_POISON) {
179                                 spin_unlock_bh(&waiting_locks_spinlock);
180                                 CERROR("free lock on elt list %p\n", lock);
181                                 LBUG();
182                         }
183                         list_del_init(&lock->l_pending_chain);
184                         if ((void *)lock->l_export < LP_POISON + CFS_PAGE_SIZE &&
185                             (void *)lock->l_export >= LP_POISON) {
186                                 CERROR("lock with free export on elt list %p\n",
187                                        lock->l_export);
188                                 lock->l_export = NULL;
189                                 LDLM_ERROR(lock, "free export");
190                                 continue;
191                         }
192                         export = class_export_get(lock->l_export);
193                         spin_unlock_bh(&waiting_locks_spinlock);
194
195                         do_dump++;
196                         class_fail_export(export);
197                         class_export_put(export);
198                         spin_lock_bh(&waiting_locks_spinlock);
199                 }
200                 spin_unlock_bh(&waiting_locks_spinlock);
201
202                 if (do_dump && obd_dump_on_eviction) {
203                         CERROR("dump the log upon eviction\n");
204                         libcfs_debug_dumplog();
205                 }
206
207                 if (expired_lock_thread.elt_state == ELT_TERMINATE)
208                         break;
209         }
210
211         expired_lock_thread.elt_state = ELT_STOPPED;
212         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
213         RETURN(0);
214 }
215
216 /* This is called from within a timer interrupt and cannot schedule */
217 static void waiting_locks_callback(unsigned long unused)
218 {
219         struct ldlm_lock *lock, *last = NULL;
220
221         spin_lock_bh(&waiting_locks_spinlock);
222         while (!list_empty(&waiting_locks_list)) {
223                 lock = list_entry(waiting_locks_list.next, struct ldlm_lock,
224                                   l_pending_chain);
225
226                 if (cfs_time_after(lock->l_callback_timeout, cfs_time_current())
227                     || (lock->l_req_mode == LCK_GROUP))
228                         break;
229
230                 LDLM_ERROR(lock, "lock callback timer expired after %lds: "
231                            "evicting client at %s ",
232                            cfs_time_current_sec()- lock->l_enqueued_time.tv_sec,
233                            libcfs_nid2str(
234                                    lock->l_export->exp_connection->c_peer.nid));
235                 if (lock == last) {
236                         LDLM_ERROR(lock, "waiting on lock multiple times");
237                         CERROR("wll %p n/p %p/%p, l_pending %p n/p %p/%p\n",
238                                &waiting_locks_list,
239                                waiting_locks_list.next, waiting_locks_list.prev,
240                                &lock->l_pending_chain,
241                                lock->l_pending_chain.next,
242                                lock->l_pending_chain.prev);
243
244                         CFS_INIT_LIST_HEAD(&waiting_locks_list);    /* HACK */
245                         expired_lock_thread.elt_dump = __LINE__;
246
247                         /* LBUG(); */
248                         CEMERG("would be an LBUG, but isn't (bug 5653)\n");
249                         libcfs_debug_dumpstack(NULL);
250                         /*blocks* libcfs_debug_dumplog(); */
251                         /*blocks* libcfs_run_lbug_upcall(file, func, line); */
252                         break;
253                 }
254                 last = lock;
255
256                 list_del(&lock->l_pending_chain);
257                 list_add(&lock->l_pending_chain,
258                          &expired_lock_thread.elt_expired_locks);
259         }
260
261         if (!list_empty(&expired_lock_thread.elt_expired_locks)) {
262                 if (obd_dump_on_timeout)
263                         expired_lock_thread.elt_dump = __LINE__;
264
265                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
266         }
267
268         /*
269          * Make sure the timer will fire again if we have any locks
270          * left.
271          */
272         if (!list_empty(&waiting_locks_list)) {
273                 cfs_time_t timeout_rounded;
274                 lock = list_entry(waiting_locks_list.next, struct ldlm_lock,
275                                   l_pending_chain);
276                 timeout_rounded = (cfs_time_t)round_timeout(lock->l_callback_timeout);
277                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
278         }
279         spin_unlock_bh(&waiting_locks_spinlock);
280 }
281
282 /*
283  * Indicate that we're waiting for a client to call us back cancelling a given
284  * lock.  We add it to the pending-callback chain, and schedule the lock-timeout
285  * timer to fire appropriately.  (We round up to the next second, to avoid
286  * floods of timer firings during periods of high lock contention and traffic).
287  *
288  * Called with the namespace lock held.
289  */
290 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock)
291 {
292         int timeout;
293         cfs_time_t timeout_rounded;
294
295         if (!list_empty(&lock->l_pending_chain))
296                 return 0;
297
298         timeout = ldlm_get_enq_timeout(lock);
299
300         lock->l_callback_timeout = cfs_time_shift(timeout);
301
302         timeout_rounded = round_timeout(lock->l_callback_timeout);
303
304         if (cfs_time_before(timeout_rounded, 
305                             cfs_timer_deadline(&waiting_locks_timer)) ||
306             !cfs_timer_is_armed(&waiting_locks_timer)) {
307                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
308         }
309         /* if the new lock has a shorter timeout than something earlier on
310            the list, we'll wait the longer amount of time; no big deal. */
311         list_add_tail(&lock->l_pending_chain, &waiting_locks_list); /* FIFO */
312         return 1;
313 }
314
315 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
316 {
317         int ret;
318
319         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
320
321         spin_lock_bh(&waiting_locks_spinlock);
322         if (lock->l_destroyed) {
323                 static cfs_time_t next;
324                 spin_unlock_bh(&waiting_locks_spinlock);
325                 LDLM_ERROR(lock, "not waiting on destroyed lock (bug 5653)");
326                 if (cfs_time_after(cfs_time_current(), next)) {
327                         next = cfs_time_shift(14400);
328                         libcfs_debug_dumpstack(NULL);
329                 }
330                 return 0;
331         }
332
333         ret = __ldlm_add_waiting_lock(lock);
334         spin_unlock_bh(&waiting_locks_spinlock);
335
336         LDLM_DEBUG(lock, "%sadding to wait list",
337                    ret == 0 ? "not re-" : "");
338         return ret;
339 }
340
341 /*
342  * Remove a lock from the pending list, likely because it had its cancellation
343  * callback arrive without incident.  This adjusts the lock-timeout timer if
344  * needed.  Returns 0 if the lock wasn't pending after all, 1 if it was.
345  *
346  * Called with namespace lock held.
347  */
348 int __ldlm_del_waiting_lock(struct ldlm_lock *lock)
349 {
350         struct list_head *list_next;
351
352         if (list_empty(&lock->l_pending_chain))
353                 return 0;
354
355         list_next = lock->l_pending_chain.next;
356         if (lock->l_pending_chain.prev == &waiting_locks_list) {
357                 /* Removing the head of the list, adjust timer. */
358                 if (list_next == &waiting_locks_list) {
359                         /* No more, just cancel. */
360                         cfs_timer_disarm(&waiting_locks_timer);
361                 } else {
362                         struct ldlm_lock *next;
363                         next = list_entry(list_next, struct ldlm_lock,
364                                           l_pending_chain);
365                         cfs_timer_arm(&waiting_locks_timer,
366                                       round_timeout(next->l_callback_timeout));
367                 }
368         }
369         list_del_init(&lock->l_pending_chain);
370
371         return 1;
372 }
373
374 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
375 {
376         int ret;
377
378         if (lock->l_export == NULL) {
379                 /* We don't have a "waiting locks list" on clients. */
380                 LDLM_DEBUG(lock, "client lock: no-op");
381                 return 0;
382         }
383
384         spin_lock_bh(&waiting_locks_spinlock);
385         ret = __ldlm_del_waiting_lock(lock);
386         spin_unlock_bh(&waiting_locks_spinlock);
387
388         LDLM_DEBUG(lock, "%s", ret == 0 ? "wasn't waiting" : "removed");
389         return ret;
390 }
391
392 /*
393  * Prolong the lock
394  *
395  * Called with namespace lock held.
396  */
397 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock)
398 {
399         if (lock->l_export == NULL) {
400                 /* We don't have a "waiting locks list" on clients. */
401                 LDLM_DEBUG(lock, "client lock: no-op");
402                 return 0;
403         }
404
405         spin_lock_bh(&waiting_locks_spinlock);
406
407         if (list_empty(&lock->l_pending_chain)) {
408                 spin_unlock_bh(&waiting_locks_spinlock);
409                 LDLM_DEBUG(lock, "wasn't waiting");
410                 return 0;
411         }
412
413         __ldlm_del_waiting_lock(lock);
414         __ldlm_add_waiting_lock(lock);
415         spin_unlock_bh(&waiting_locks_spinlock);
416
417         LDLM_DEBUG(lock, "refreshed");
418         return 1;
419 }
420
421 #else /* !__KERNEL__ */
422
423 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
424 {
425         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
426         RETURN(1);
427 }
428
429 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
430 {
431         RETURN(0);
432 }
433
434 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock)
435 {
436         RETURN(0);
437 }
438 #endif /* __KERNEL__ */
439
440 static void ldlm_failed_ast(struct ldlm_lock *lock, int rc,
441                             const char *ast_type)
442 {
443         struct ptlrpc_connection *conn = lock->l_export->exp_connection;
444         char                     *str = libcfs_nid2str(conn->c_peer.nid);
445
446         LCONSOLE_ERROR_MSG(0x138, "%s: A client on nid %s was evicted due "
447                              "to a lock %s callback to %s timed out: rc %d\n",
448                              lock->l_export->exp_obd->obd_name, str,
449                              ast_type, obd_export_nid2str(lock->l_export), rc);
450
451         if (obd_dump_on_timeout)
452                 libcfs_debug_dumplog();
453         class_fail_export(lock->l_export);
454 }
455
456 static int ldlm_handle_ast_error(struct ldlm_lock *lock,
457                                  struct ptlrpc_request *req, int rc,
458                                  const char *ast_type)
459 {
460         lnet_process_id_t peer = req->rq_import->imp_connection->c_peer;
461
462         if (rc == -ETIMEDOUT || rc == -EINTR || rc == -ENOTCONN) {
463                 LASSERT(lock->l_export);
464                 if (lock->l_export->exp_libclient) {
465                         LDLM_DEBUG(lock, "%s AST to liblustre client (nid %s)"
466                                    " timeout, just cancelling lock", ast_type,
467                                    libcfs_nid2str(peer.nid));
468                         ldlm_lock_cancel(lock);
469                         rc = -ERESTART;
470                 } else if (lock->l_flags & LDLM_FL_CANCEL) {
471                         LDLM_DEBUG(lock, "%s AST timeout from nid %s, but "
472                                    "cancel was received (AST reply lost?)",
473                                    ast_type, libcfs_nid2str(peer.nid));
474                         ldlm_lock_cancel(lock);
475                         rc = -ERESTART;
476                 } else {
477                         ldlm_del_waiting_lock(lock);
478                         ldlm_failed_ast(lock, rc, ast_type);
479                 }
480         } else if (rc) {
481                 if (rc == -EINVAL)
482                         LDLM_DEBUG(lock, "client (nid %s) returned %d"
483                                    " from %s AST - normal race",
484                                    libcfs_nid2str(peer.nid),
485                                    lustre_msg_get_status(req->rq_repmsg),
486                                    ast_type);
487                 else
488                         LDLM_ERROR(lock, "client (nid %s) returned %d "
489                                    "from %s AST", libcfs_nid2str(peer.nid),
490                                    (req->rq_repmsg != NULL) ?
491                                    lustre_msg_get_status(req->rq_repmsg) : 0,
492                                    ast_type);
493                 ldlm_lock_cancel(lock);
494                 /* Server-side AST functions are called from ldlm_reprocess_all,
495                  * which needs to be told to please restart its reprocessing. */
496                 rc = -ERESTART;
497         }
498
499         return rc;
500 }
501
502 static int ldlm_cb_interpret(struct ptlrpc_request *req, void *data, int rc)
503 {
504         struct ldlm_cb_set_arg *arg;
505         struct ldlm_lock *lock;
506         ENTRY;
507
508         LASSERT(data != NULL);
509
510         arg = req->rq_async_args.pointer_arg[0];
511         lock = req->rq_async_args.pointer_arg[1];
512         LASSERT(lock != NULL);
513         if (rc != 0) {
514                 /* If client canceled the lock but the cancel has not
515                  * been recieved yet, we need to update lvbo to have the
516                  * proper attributes cached. */
517                 if (rc == -EINVAL && arg->type == LDLM_BL_CALLBACK)
518                         ldlm_res_lvbo_update(lock->l_resource, NULL,
519                                              0, 1);
520                 rc = ldlm_handle_ast_error(lock, req, rc,
521                                            arg->type == LDLM_BL_CALLBACK
522                                            ? "blocking" : "completion");
523         }
524
525         LDLM_LOCK_PUT(lock);
526
527         if (rc == -ERESTART)
528                 atomic_set(&arg->restart, 1);
529
530         RETURN(0);
531 }
532
533 static inline int ldlm_bl_and_cp_ast_fini(struct ptlrpc_request *req,
534                                           struct ldlm_cb_set_arg *arg,
535                                           struct ldlm_lock *lock,
536                                           int instant_cancel)
537 {
538         int rc = 0;
539         ENTRY;
540
541         if (unlikely(instant_cancel)) {
542                 rc = ptl_send_rpc(req, 1);
543                 ptlrpc_req_finished(req);
544                 if (rc == 0)
545                         /* If we cancelled the lock, we need to restart
546                          * ldlm_reprocess_queue */
547                         atomic_set(&arg->restart, 1);
548         } else {
549                 LDLM_LOCK_GET(lock);
550                 ptlrpc_set_add_req(arg->set, req);
551         }
552
553         RETURN(rc);
554 }
555
556 /*
557  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
558  * enqueued server lock conflicts with given one.
559  *
560  * Sends blocking ast rpc to the client owning that lock; arms timeout timer
561  * to wait for client response.
562  */
563 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
564                              struct ldlm_lock_desc *desc,
565                              void *data, int flag)
566 {
567         struct ldlm_cb_set_arg *arg = data;
568         struct ldlm_request *body;
569         struct ptlrpc_request *req;
570         int size[] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
571                        [DLM_LOCKREQ_OFF]     = sizeof(*body) };
572         int instant_cancel = 0, rc;
573         ENTRY;
574
575         if (flag == LDLM_CB_CANCELING) {
576                 /* Don't need to do anything here. */
577                 RETURN(0);
578         }
579
580         LASSERT(lock);
581         LASSERT(data != NULL);
582
583         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
584                               LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK, 2, size,
585                               NULL);
586         if (req == NULL)
587                 RETURN(-ENOMEM);
588
589         req->rq_async_args.pointer_arg[0] = arg;
590         req->rq_async_args.pointer_arg[1] = lock;
591         req->rq_interpret_reply = ldlm_cb_interpret;
592         req->rq_no_resend = 1;
593
594         lock_res(lock->l_resource);
595         if (lock->l_granted_mode != lock->l_req_mode) {
596                 /* this blocking AST will be communicated as part of the
597                  * completion AST instead */
598                 unlock_res(lock->l_resource);
599                 ptlrpc_req_finished(req);
600                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
601                 RETURN(0);
602         }
603
604         if (lock->l_destroyed) {
605                 /* What's the point? */
606                 unlock_res(lock->l_resource);
607                 ptlrpc_req_finished(req);
608                 RETURN(0);
609         }
610
611 #if 0
612         if (CURRENT_SECONDS - lock->l_export->exp_last_request_time > 30){
613                 unlock_res(lock->l_resource);
614                 ptlrpc_req_finished(req);
615                 ldlm_failed_ast(lock, -ETIMEDOUT, "Not-attempted blocking");
616                 RETURN(-ETIMEDOUT);
617         }
618 #endif
619
620         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
621                 instant_cancel = 1;
622
623         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
624         body->lock_handle[0] = lock->l_remote_handle;
625         body->lock_desc = *desc;
626         body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
627
628         LDLM_DEBUG(lock, "server preparing blocking AST");
629
630         ptlrpc_req_set_repsize(req, 1, NULL);
631         if (instant_cancel) {
632                 unlock_res(lock->l_resource);
633                 ldlm_lock_cancel(lock);
634         } else {
635                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
636                 ldlm_add_waiting_lock(lock);
637                 unlock_res(lock->l_resource);
638         }
639
640         req->rq_send_state = LUSTRE_IMP_FULL;
641         /* ptlrpc_prep_req already set timeout */
642         if (AT_OFF)
643                 req->rq_timeout = ldlm_get_rq_timeout();
644
645         if (lock->l_export && lock->l_export->exp_ldlm_stats)
646                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
647                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
648
649         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
650
651         RETURN(rc);
652 }
653
654 int ldlm_server_completion_ast(struct ldlm_lock *lock, int flags, void *data)
655 {
656         struct ldlm_cb_set_arg *arg = data;
657         struct ldlm_request *body;
658         struct ptlrpc_request *req;
659         struct timeval granted_time;
660         long total_enqueue_wait;
661         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
662                         [DLM_LOCKREQ_OFF]     = sizeof(*body) };
663         int rc, buffers = 2, instant_cancel = 0;
664         ENTRY;
665
666         LASSERT(lock != NULL);
667         LASSERT(data != NULL);
668
669         do_gettimeofday(&granted_time);
670         total_enqueue_wait = cfs_timeval_sub(&granted_time,
671                                              &lock->l_enqueued_time, NULL);
672
673         if (total_enqueue_wait / ONE_MILLION > obd_timeout)
674                 /* non-fatal with AT - change to LDLM_DEBUG? */
675                 LDLM_ERROR(lock, "enqueue wait took %luus from %lu",
676                            total_enqueue_wait, lock->l_enqueued_time.tv_sec);
677
678         lock_res_and_lock(lock);
679         if (lock->l_resource->lr_lvb_len) {
680                 size[DLM_REQ_REC_OFF] = lock->l_resource->lr_lvb_len;
681                 buffers = 3;
682         }
683         unlock_res_and_lock(lock);
684
685         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
686                               LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK, buffers,
687                               size, NULL);
688         if (req == NULL)
689                 RETURN(-ENOMEM);
690
691         req->rq_async_args.pointer_arg[0] = arg;
692         req->rq_async_args.pointer_arg[1] = lock;
693         req->rq_interpret_reply = ldlm_cb_interpret;
694         req->rq_no_resend = 1;
695
696         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
697         body->lock_handle[0] = lock->l_remote_handle;
698         body->lock_flags = flags;
699         ldlm_lock2desc(lock, &body->lock_desc);
700
701         if (buffers == 3) {
702                 void *lvb;
703
704                 lvb = lustre_msg_buf(req->rq_reqmsg, DLM_REQ_REC_OFF,
705                                      lock->l_resource->lr_lvb_len);
706                 lock_res_and_lock(lock);
707                 memcpy(lvb, lock->l_resource->lr_lvb_data,
708                        lock->l_resource->lr_lvb_len);
709                 unlock_res_and_lock(lock);
710         }
711
712         LDLM_DEBUG(lock, "server preparing completion AST (after %ldus wait)",
713                    total_enqueue_wait);
714
715         /* Server-side enqueue wait time estimate, used in
716             __ldlm_add_waiting_lock to set future enqueue timers */
717         at_add(&lock->l_resource->lr_namespace->ns_at_estimate,
718                total_enqueue_wait / ONE_MILLION);
719
720         ptlrpc_req_set_repsize(req, 1, NULL);
721
722         req->rq_send_state = LUSTRE_IMP_FULL;
723         /* ptlrpc_prep_req already set timeout */
724         if (AT_OFF)
725                 req->rq_timeout = ldlm_get_rq_timeout();
726
727         /* We only send real blocking ASTs after the lock is granted */
728         lock_res_and_lock(lock);
729         if (lock->l_flags & LDLM_FL_AST_SENT) {
730                 body->lock_flags |= LDLM_FL_AST_SENT;
731
732                 /* We might get here prior to ldlm_handle_enqueue setting
733                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
734                  * into waiting list, but this is safe and similar code in
735                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
736                  * that would not only cancel the lock, but will also remove
737                  * it from waiting list */
738                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
739                         unlock_res_and_lock(lock);
740                         ldlm_lock_cancel(lock);
741                         instant_cancel = 1;
742                         lock_res_and_lock(lock);
743                 } else {
744                         ldlm_add_waiting_lock(lock); /* start the lock-timeout
745                                                          clock */
746                 }
747         }
748         unlock_res_and_lock(lock);
749
750         if (lock->l_export && lock->l_export->exp_ldlm_stats)
751                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
752                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
753
754         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
755
756         RETURN(rc);
757 }
758
759 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
760 {
761         struct ldlm_resource *res = lock->l_resource;
762         struct ldlm_request *body;
763         struct ptlrpc_request *req;
764         int size[] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
765                        [DLM_LOCKREQ_OFF]     = sizeof(*body) };
766         int rc = 0;
767         ENTRY;
768
769         LASSERT(lock != NULL);
770
771         req = ptlrpc_prep_req(lock->l_export->exp_imp_reverse,
772                               LUSTRE_DLM_VERSION, LDLM_GL_CALLBACK, 2, size,
773                               NULL);
774         if (req == NULL)
775                 RETURN(-ENOMEM);
776
777         body = lustre_msg_buf(req->rq_reqmsg, DLM_LOCKREQ_OFF, sizeof(*body));
778         body->lock_handle[0] = lock->l_remote_handle;
779         ldlm_lock2desc(lock, &body->lock_desc);
780
781         lock_res_and_lock(lock);
782         size[REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
783         unlock_res_and_lock(lock);
784         res = lock->l_resource;
785         ptlrpc_req_set_repsize(req, 2, size);
786
787         req->rq_send_state = LUSTRE_IMP_FULL;
788         /* ptlrpc_prep_req already set timeout */
789         if (AT_OFF)
790                 req->rq_timeout = ldlm_get_rq_timeout();
791
792         if (lock->l_export && lock->l_export->exp_ldlm_stats)
793                 lprocfs_counter_incr(lock->l_export->exp_ldlm_stats,
794                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
795
796         rc = ptlrpc_queue_wait(req);
797         if (rc == -ELDLM_NO_LOCK_DATA)
798                 LDLM_DEBUG(lock, "lost race - client has a lock but no inode");
799         else if (rc != 0)
800                 rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
801         else
802                 rc = ldlm_res_lvbo_update(res, req,
803                                           REPLY_REC_OFF, 1);
804         ptlrpc_req_finished(req);
805         if (rc == -ERESTART)
806                 ldlm_reprocess_all(res);
807
808         RETURN(rc);
809 }
810
811 static struct ldlm_lock *
812 find_existing_lock(struct obd_export *exp, struct lustre_handle *remote_hdl)
813 {
814         struct list_head *iter;
815
816         spin_lock(&exp->exp_ldlm_data.led_lock);
817         list_for_each(iter, &exp->exp_ldlm_data.led_held_locks) {
818                 struct ldlm_lock *lock;
819                 lock = list_entry(iter, struct ldlm_lock, l_export_chain);
820                 if (lock->l_remote_handle.cookie == remote_hdl->cookie) {
821                         LDLM_LOCK_GET(lock);
822                         spin_unlock(&exp->exp_ldlm_data.led_lock);
823                         return lock;
824                 }
825         }
826         spin_unlock(&exp->exp_ldlm_data.led_lock);
827         return NULL;
828 }
829
830 static void ldlm_svc_get_eopc(struct ldlm_request *dlm_req,
831                        struct lprocfs_stats *srv_stats)
832 {
833         int lock_type = 0, op = 0;
834
835         lock_type = dlm_req->lock_desc.l_resource.lr_type;
836
837         switch (lock_type) {
838         case LDLM_PLAIN:
839                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
840                 break;
841         case LDLM_EXTENT:
842                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
843                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
844                 else
845                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
846                 break;
847         case LDLM_FLOCK:
848                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
849                 break;
850         case LDLM_IBITS:
851                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
852                 break;
853         default:
854                 op = 0;
855                 break;
856         }
857
858         if (op)
859                 lprocfs_counter_incr(srv_stats, op);
860
861         return ;
862 }
863
864 /*
865  * Main server-side entry point into LDLM. This is called by ptlrpc service
866  * threads to carry out client lock enqueueing requests.
867  */
868 int ldlm_handle_enqueue(struct ptlrpc_request *req,
869                         ldlm_completion_callback completion_callback,
870                         ldlm_blocking_callback blocking_callback,
871                         ldlm_glimpse_callback glimpse_callback)
872 {
873         struct obd_device *obddev = req->rq_export->exp_obd;
874         struct ldlm_reply *dlm_rep;
875         struct ldlm_request *dlm_req;
876         int size[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
877                         [DLM_LOCKREPLY_OFF]   = sizeof(*dlm_rep) };
878         int rc = 0;
879         __u32 flags;
880         ldlm_error_t err = ELDLM_OK;
881         struct ldlm_lock *lock = NULL;
882         void *cookie = NULL;
883         ENTRY;
884
885         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
886
887         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof(*dlm_req),
888                                      lustre_swab_ldlm_request);
889         if (dlm_req == NULL) {
890                 CERROR ("Can't unpack dlm_req\n");
891                 GOTO(out, rc = -EFAULT);
892         }
893
894         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
895         flags = dlm_req->lock_flags;
896
897         LASSERT(req->rq_export);
898
899         if (req->rq_rqbd->rqbd_service->srv_stats)
900                 ldlm_svc_get_eopc(dlm_req,
901                                   req->rq_rqbd->rqbd_service->srv_stats);
902
903         if (req->rq_export->exp_ldlm_stats)
904                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
905                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
906
907         if (dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
908             dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE) {
909                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
910                           dlm_req->lock_desc.l_resource.lr_type);
911                 GOTO(out, rc = -EFAULT);
912         }
913
914         if (dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
915             dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
916             dlm_req->lock_desc.l_req_mode & (dlm_req->lock_desc.l_req_mode-1)) {
917                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
918                           dlm_req->lock_desc.l_req_mode);
919                 GOTO(out, rc = -EFAULT);
920         }
921
922         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
923                 if (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN) {
924                         DEBUG_REQ(D_ERROR, req,
925                                   "PLAIN lock request from IBITS client?");
926                         GOTO(out, rc = -EPROTO);
927                 }
928         } else if (dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) {
929                 DEBUG_REQ(D_ERROR, req,
930                           "IBITS lock request from unaware client?");
931                 GOTO(out, rc = -EPROTO);
932         }
933
934 #if 0
935         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
936            against server's _CONNECT_SUPPORTED flags? (I don't want to use
937            ibits for mgc/mgs) */
938
939         /* INODEBITS_INTEROP: Perform conversion from plain lock to
940          * inodebits lock if client does not support them. */
941         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
942             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
943                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
944                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
945                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
946                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
947                         dlm_req->lock_desc.l_req_mode = LCK_CR;
948         }
949 #endif
950
951         if (flags & LDLM_FL_REPLAY) {
952                 lock = find_existing_lock(req->rq_export,
953                                           &dlm_req->lock_handle[0]);
954                 if (lock != NULL) {
955                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
956                                   LPX64, lock->l_handle.h_cookie);
957                         GOTO(existing_lock, rc = 0);
958                 }
959         }
960
961         /* The lock's callback data might be set in the policy function */
962         lock = ldlm_lock_create(obddev->obd_namespace,
963                                 dlm_req->lock_desc.l_resource.lr_name,
964                                 dlm_req->lock_desc.l_resource.lr_type,
965                                 dlm_req->lock_desc.l_req_mode,
966                                 blocking_callback, completion_callback,
967                                 glimpse_callback, NULL, 0);
968         if (!lock)
969                 GOTO(out, rc = -ENOMEM);
970
971         do_gettimeofday(&lock->l_enqueued_time);
972         lock->l_remote_handle = dlm_req->lock_handle[0];
973         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
974
975         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
976         /* Don't enqueue a lock onto the export if it has already
977          * been evicted.  Cancel it now instead. (bug 3822) */
978         if (req->rq_export->exp_failed) {
979                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
980                 GOTO(out, rc = -ENOTCONN);
981         }
982         lock->l_export = class_export_get(req->rq_export);
983         spin_lock(&lock->l_export->exp_ldlm_data.led_lock);
984         list_add(&lock->l_export_chain,
985                  &lock->l_export->exp_ldlm_data.led_held_locks);
986         spin_unlock(&lock->l_export->exp_ldlm_data.led_lock);
987
988 existing_lock:
989
990         if (flags & LDLM_FL_HAS_INTENT) {
991                 /* In this case, the reply buffer is allocated deep in
992                  * local_lock_enqueue by the policy function. */
993                 cookie = req;
994         } else {
995                 int buffers = 2;
996
997                 lock_res_and_lock(lock);
998                 if (lock->l_resource->lr_lvb_len) {
999                         size[DLM_REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
1000                         buffers = 3;
1001                 }
1002                 unlock_res_and_lock(lock);
1003
1004                 if (OBD_FAIL_CHECK_ONCE(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1005                         GOTO(out, rc = -ENOMEM);
1006
1007                 rc = lustre_pack_reply(req, buffers, size, NULL);
1008                 if (rc)
1009                         GOTO(out, rc);
1010         }
1011
1012         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1013                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1014         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1015                 lock->l_req_extent = lock->l_policy_data.l_extent;
1016
1017         err = ldlm_lock_enqueue(obddev->obd_namespace, &lock, cookie, (int *)&flags);
1018         if (err)
1019                 GOTO(out, err);
1020
1021         dlm_rep = lustre_msg_buf(req->rq_repmsg, DLM_LOCKREPLY_OFF,
1022                                  sizeof(*dlm_rep));
1023         dlm_rep->lock_flags = flags;
1024
1025         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1026         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1027
1028         /* We never send a blocking AST until the lock is granted, but
1029          * we can tell it right now */
1030         lock_res_and_lock(lock);
1031
1032         /* Now take into account flags to be inherited from original lock
1033            request both in reply to client and in our own lock flags. */
1034         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1035         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1036
1037         /* Don't move a pending lock onto the export if it has already
1038          * been evicted.  Cancel it now instead. (bug 5683) */
1039         if (req->rq_export->exp_failed ||
1040             OBD_FAIL_CHECK_ONCE(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT)) {
1041                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1042                 rc = -ENOTCONN;
1043         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1044                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
1045                 if (lock->l_granted_mode == lock->l_req_mode) {
1046                         /* Only cancel lock if it was granted, because it
1047                          * would be destroyed immediatelly and would never
1048                          * be granted in the future, causing timeouts on client.
1049                          * Not granted lock will be cancelled immediatelly after
1050                          * sending completion AST.
1051                          */
1052                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1053                                 unlock_res_and_lock(lock);
1054                                 ldlm_lock_cancel(lock);
1055                                 lock_res_and_lock(lock);
1056                         } else
1057                                 ldlm_add_waiting_lock(lock);
1058                 }
1059         }
1060         /* Make sure we never ever grant usual metadata locks to liblustre
1061            clients */
1062         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1063             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1064              req->rq_export->exp_libclient) {
1065                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1066                     !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
1067                         CERROR("Granting sync lock to libclient. "
1068                                "req fl %d, rep fl %d, lock fl %d\n",
1069                                dlm_req->lock_flags, dlm_rep->lock_flags,
1070                                lock->l_flags);
1071                         LDLM_ERROR(lock, "sync lock");
1072                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1073                                 struct ldlm_intent *it;
1074                                 it = lustre_msg_buf(req->rq_reqmsg,
1075                                                     DLM_INTENT_IT_OFF,
1076                                                     sizeof(*it));
1077                                 if (it != NULL) {
1078                                         CERROR("This is intent %s ("LPU64")\n",
1079                                                ldlm_it2str(it->opc), it->opc);
1080                                 }
1081                         }
1082                 }
1083         }
1084
1085         unlock_res_and_lock(lock);
1086
1087         EXIT;
1088  out:
1089         req->rq_status = rc ?: err;  /* return either error - bug 11190 */
1090         if (!req->rq_packed_final) {
1091                 err = lustre_pack_reply(req, 1, NULL, NULL);
1092                 if (rc == 0)
1093                         rc = err;
1094         }
1095
1096         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1097          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1098         if (lock) {
1099                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1100                            "(err=%d, rc=%d)", err, rc);
1101
1102                 if (rc == 0) {
1103                         lock_res_and_lock(lock);
1104                         size[DLM_REPLY_REC_OFF] = lock->l_resource->lr_lvb_len;
1105                         if (size[DLM_REPLY_REC_OFF] > 0) {
1106                                 void *lvb = lustre_msg_buf(req->rq_repmsg,
1107                                                        DLM_REPLY_REC_OFF,
1108                                                        size[DLM_REPLY_REC_OFF]);
1109                                 LASSERTF(lvb != NULL, "req %p, lock %p\n",
1110                                          req, lock);
1111
1112                                 memcpy(lvb, lock->l_resource->lr_lvb_data,
1113                                        size[DLM_REPLY_REC_OFF]);
1114                         }
1115                         unlock_res_and_lock(lock);
1116                 } else {
1117                         lock_res_and_lock(lock);
1118                         ldlm_resource_unlink_lock(lock);
1119                         ldlm_lock_destroy_nolock(lock);
1120                         unlock_res_and_lock(lock);
1121                 }
1122
1123                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1124                         ldlm_reprocess_all(lock->l_resource);
1125
1126                 LDLM_LOCK_PUT(lock);
1127         }
1128
1129         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1130                           lock, rc);
1131
1132         return rc;
1133 }
1134
1135 int ldlm_handle_convert(struct ptlrpc_request *req)
1136 {
1137         struct ldlm_request *dlm_req;
1138         struct ldlm_reply *dlm_rep;
1139         struct ldlm_lock *lock;
1140         int rc;
1141         int size[2] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
1142                         [DLM_LOCKREPLY_OFF]   = sizeof(*dlm_rep) };
1143         ENTRY;
1144
1145         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof(*dlm_req),
1146                                      lustre_swab_ldlm_request);
1147         if (dlm_req == NULL) {
1148                 CERROR ("Can't unpack dlm_req\n");
1149                 RETURN (-EFAULT);
1150         }
1151
1152         if (req->rq_export && req->rq_export->exp_ldlm_stats)
1153                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
1154                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1155
1156         rc = lustre_pack_reply(req, 2, size, NULL);
1157         if (rc)
1158                 RETURN(rc);
1159
1160         dlm_rep = lustre_msg_buf(req->rq_repmsg, DLM_LOCKREPLY_OFF,
1161                                  sizeof(*dlm_rep));
1162         dlm_rep->lock_flags = dlm_req->lock_flags;
1163
1164         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1165         if (!lock) {
1166                 req->rq_status = EINVAL;
1167         } else {
1168                 void *res = NULL;
1169
1170                 LDLM_DEBUG(lock, "server-side convert handler START");
1171
1172                 do_gettimeofday(&lock->l_enqueued_time);
1173                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1174                                         &dlm_rep->lock_flags);
1175                 if (res) {
1176                         if (ldlm_del_waiting_lock(lock))
1177                                 LDLM_DEBUG(lock, "converted waiting lock");
1178                         req->rq_status = 0;
1179                 } else {
1180                         req->rq_status = EDEADLOCK;
1181                 }
1182         }
1183
1184         if (lock) {
1185                 if (!req->rq_status)
1186                         ldlm_reprocess_all(lock->l_resource);
1187                 LDLM_DEBUG(lock, "server-side convert handler END");
1188                 LDLM_LOCK_PUT(lock);
1189         } else
1190                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1191
1192         RETURN(0);
1193 }
1194
1195 /* Cancel all the locks whos handles are packed into ldlm_request */
1196 int ldlm_request_cancel(struct ptlrpc_request *req,
1197                         struct ldlm_request *dlm_req, int first)
1198 {
1199         struct ldlm_resource *res, *pres = NULL;
1200         struct ldlm_lock *lock;
1201         int i, count, done = 0;
1202         ENTRY;
1203
1204         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1205         if (first >= count)
1206                 RETURN(0);
1207
1208         /* There is no lock on the server at the replay time,
1209          * skip lock cancelling to make replay tests to pass. */
1210         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1211                 RETURN(0);
1212
1213         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks",
1214                           count - first);
1215         for (i = first; i < count; i++) {
1216                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1217                 if (!lock) {
1218                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1219                                           "lock (cookie "LPU64")",
1220                                           dlm_req->lock_handle[i].cookie);
1221                         continue;
1222                 }
1223
1224                 done++;
1225                 res = lock->l_resource;
1226                 if (res != pres) {
1227                         if (pres != NULL) {
1228                                 ldlm_reprocess_all(pres);
1229                                 ldlm_resource_putref(pres);
1230                         }
1231                         if (res != NULL) {
1232                                 ldlm_resource_getref(res);
1233                                 ldlm_res_lvbo_update(res, NULL, 0, 1);
1234                         }
1235                         pres = res;
1236                 }
1237                 ldlm_lock_cancel(lock);
1238                 LDLM_LOCK_PUT(lock);
1239         }
1240         if (pres != NULL) {
1241                 ldlm_reprocess_all(pres);
1242                 ldlm_resource_putref(pres);
1243         }
1244         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1245         RETURN(done);
1246 }
1247
1248 int ldlm_handle_cancel(struct ptlrpc_request *req)
1249 {
1250         struct ldlm_request *dlm_req;
1251         int rc;
1252         ENTRY;
1253
1254         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof(*dlm_req),
1255                                      lustre_swab_ldlm_request);
1256         if (dlm_req == NULL) {
1257                 CERROR("bad request buffer for cancel\n");
1258                 RETURN(-EFAULT);
1259         }
1260
1261         if (req->rq_export && req->rq_export->exp_ldlm_stats)
1262                 lprocfs_counter_incr(req->rq_export->exp_ldlm_stats,
1263                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1264
1265         rc = lustre_pack_reply(req, 1, NULL, NULL);
1266         if (rc)
1267                 RETURN(rc);
1268
1269         if (!ldlm_request_cancel(req, dlm_req, 0))
1270                 req->rq_status = ESTALE;
1271
1272         if (ptlrpc_reply(req) != 0)
1273                 LBUG();
1274
1275         RETURN(0);
1276 }
1277
1278 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1279                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1280 {
1281         int do_ast;
1282         ENTRY;
1283
1284         LDLM_DEBUG(lock, "client blocking AST callback handler START");
1285
1286         lock_res_and_lock(lock);
1287         lock->l_flags |= LDLM_FL_CBPENDING;
1288
1289         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1290                 lock->l_flags |= LDLM_FL_CANCEL;
1291
1292         do_ast = (!lock->l_readers && !lock->l_writers);
1293         unlock_res_and_lock(lock);
1294
1295         if (do_ast) {
1296                 LDLM_DEBUG(lock, "already unused, calling "
1297                            "callback (%p)", lock->l_blocking_ast);
1298                 if (lock->l_blocking_ast != NULL)
1299                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1300                                              LDLM_CB_BLOCKING);
1301         } else {
1302                 LDLM_DEBUG(lock, "Lock still has references, will be"
1303                            " cancelled later");
1304         }
1305
1306         LDLM_DEBUG(lock, "client blocking callback handler END");
1307         LDLM_LOCK_PUT(lock);
1308         EXIT;
1309 }
1310
1311 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1312                                     struct ldlm_namespace *ns,
1313                                     struct ldlm_request *dlm_req,
1314                                     struct ldlm_lock *lock)
1315 {
1316         CFS_LIST_HEAD(ast_list);
1317         ENTRY;
1318
1319         LDLM_DEBUG(lock, "client completion callback handler START");
1320
1321         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1322                 int to = cfs_time_seconds(1);
1323                 while (to > 0) {
1324                         to = schedule_timeout(to);
1325                         if (lock->l_granted_mode == lock->l_req_mode ||
1326                             lock->l_destroyed)
1327                                 break;
1328                 }
1329         }
1330
1331         lock_res_and_lock(lock);
1332         if (lock->l_destroyed ||
1333             lock->l_granted_mode == lock->l_req_mode) {
1334                 /* bug 11300: the lock has already been granted */
1335                 unlock_res_and_lock(lock);
1336                 LDLM_DEBUG(lock, "Double grant race happened");
1337                 LDLM_LOCK_PUT(lock);
1338                 EXIT;
1339                 return;
1340         }
1341
1342         /* If we receive the completion AST before the actual enqueue returned,
1343          * then we might need to switch lock modes, resources, or extents. */
1344         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1345                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1346                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1347         }
1348
1349         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1350                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1351                 LDLM_DEBUG(lock, "completion AST, new policy data");
1352         }
1353
1354         ldlm_resource_unlink_lock(lock);
1355         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1356                    &lock->l_resource->lr_name,
1357                    sizeof(lock->l_resource->lr_name)) != 0) {
1358                 unlock_res_and_lock(lock);
1359                 if (ldlm_lock_change_resource(ns, lock, 
1360                                 dlm_req->lock_desc.l_resource.lr_name)) {
1361                         LDLM_ERROR(lock, "Failed to allocate resource");
1362                         LDLM_LOCK_PUT(lock);
1363                         EXIT;
1364                         return;
1365                 }
1366                 LDLM_DEBUG(lock, "completion AST, new resource");
1367                 CERROR("change resource!\n");
1368                 lock_res_and_lock(lock);
1369         }
1370
1371         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1372                 /* BL_AST locks are not needed in lru.
1373                  * let ldlm_cancel_lru() be fast. */
1374                 ldlm_lock_remove_from_lru(lock);
1375                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1376                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1377         }
1378
1379         if (lock->l_lvb_len) {
1380                 void *lvb;
1381                 lvb = lustre_swab_reqbuf(req, DLM_REQ_REC_OFF, lock->l_lvb_len,
1382                                          lock->l_lvb_swabber);
1383                 if (lvb == NULL) {
1384                         LDLM_ERROR(lock, "completion AST did not contain "
1385                                    "expected LVB!");
1386                 } else {
1387                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1388                 }
1389         }
1390
1391         ldlm_grant_lock(lock, &ast_list);
1392         unlock_res_and_lock(lock);
1393
1394         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1395
1396         ldlm_run_cp_ast_work(&ast_list);
1397
1398         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1399                           lock);
1400         LDLM_LOCK_PUT(lock);
1401         EXIT;
1402 }
1403
1404 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1405                                     struct ldlm_namespace *ns,
1406                                     struct ldlm_request *dlm_req,
1407                                     struct ldlm_lock *lock)
1408 {
1409         int rc = -ENOSYS;
1410         ENTRY;
1411
1412         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1413
1414         if (lock->l_glimpse_ast != NULL)
1415                 rc = lock->l_glimpse_ast(lock, req);
1416
1417         if (req->rq_repmsg != NULL) {
1418                 ptlrpc_reply(req);
1419         } else {
1420                 req->rq_status = rc;
1421                 ptlrpc_error(req);
1422         }
1423
1424         lock_res_and_lock(lock);
1425         if (lock->l_granted_mode == LCK_PW &&
1426             !lock->l_readers && !lock->l_writers &&
1427             cfs_time_after(cfs_time_current(),
1428                            cfs_time_add(lock->l_last_used, 
1429                                         cfs_time_seconds(10)))) {
1430                 unlock_res_and_lock(lock);
1431                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1432                         ldlm_handle_bl_callback(ns, NULL, lock);
1433
1434                 EXIT;
1435                 return;
1436         }
1437         unlock_res_and_lock(lock);
1438         LDLM_LOCK_PUT(lock);
1439         EXIT;
1440 }
1441
1442 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1443 {
1444         req->rq_status = rc;
1445         if (!req->rq_packed_final) {
1446                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1447                 if (rc)
1448                         return rc;
1449         }
1450         return ptlrpc_reply(req);
1451 }
1452
1453 #ifdef __KERNEL__
1454 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1455                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1456                              struct list_head *cancels, int count)
1457 {
1458         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1459         struct ldlm_bl_work_item *blwi;
1460         ENTRY;
1461
1462         if (cancels && count == 0)
1463                 RETURN(0);
1464
1465         OBD_ALLOC(blwi, sizeof(*blwi));
1466         if (blwi == NULL)
1467                 RETURN(-ENOMEM);
1468
1469         blwi->blwi_ns = ns;
1470         if (ld != NULL)
1471                 blwi->blwi_ld = *ld;
1472         if (count) {
1473                 list_add(&blwi->blwi_head, cancels);
1474                 list_del_init(cancels);
1475                 blwi->blwi_count = count;
1476         } else {
1477                 blwi->blwi_lock = lock;
1478         }
1479         spin_lock(&blp->blp_lock);
1480         if (lock && lock->l_flags & LDLM_FL_DISCARD_DATA) {
1481                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1482                 list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1483         } else {
1484                 /* other blocking callbacks are added to the regular list */
1485                 list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1486         }
1487         cfs_waitq_signal(&blp->blp_waitq);
1488         spin_unlock(&blp->blp_lock);
1489
1490         RETURN(0);
1491 }
1492 #endif
1493
1494 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1495                            struct ldlm_lock *lock)
1496 {
1497 #ifdef __KERNEL__
1498         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0));
1499 #else
1500         RETURN(-ENOSYS);
1501 #endif
1502 }
1503
1504 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1505                            struct list_head *cancels, int count)
1506 {
1507 #ifdef __KERNEL__
1508         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count));
1509 #else
1510         RETURN(-ENOSYS);
1511 #endif
1512 }
1513
1514 static int ldlm_callback_handler(struct ptlrpc_request *req)
1515 {
1516         struct ldlm_namespace *ns;
1517         struct ldlm_request *dlm_req;
1518         struct ldlm_lock *lock;
1519         int rc;
1520         ENTRY;
1521
1522         /* Requests arrive in sender's byte order.  The ptlrpc service
1523          * handler has already checked and, if necessary, byte-swapped the
1524          * incoming request message body, but I am responsible for the
1525          * message buffers. */
1526
1527         if (req->rq_export == NULL) {
1528                 struct ldlm_request *dlm_req;
1529
1530                 CDEBUG(D_RPCTRACE, "operation %d from %s with bad "
1531                        "export cookie "LPX64"; this is "
1532                        "normal if this node rebooted with a lock held\n",
1533                        lustre_msg_get_opc(req->rq_reqmsg),
1534                        libcfs_id2str(req->rq_peer),
1535                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
1536
1537                 dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF,
1538                                              sizeof(*dlm_req),
1539                                              lustre_swab_ldlm_request);
1540                 if (dlm_req != NULL)
1541                         CDEBUG(D_RPCTRACE, "--> lock cookie: "LPX64"\n",
1542                                dlm_req->lock_handle[0].cookie);
1543
1544                 ldlm_callback_reply(req, -ENOTCONN);
1545                 RETURN(0);
1546         }
1547
1548         LASSERT(req->rq_export != NULL);
1549         LASSERT(req->rq_export->exp_obd != NULL);
1550
1551         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1552         case LDLM_BL_CALLBACK:
1553                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_BL_CALLBACK, 0);
1554                 break;
1555         case LDLM_CP_CALLBACK:
1556                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_CP_CALLBACK, 0);
1557                 break;
1558         case LDLM_GL_CALLBACK:
1559                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_GL_CALLBACK, 0);
1560                 break;
1561         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1562                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOG_CANCEL_NET, 0);
1563                 rc = llog_origin_handle_cancel(req);
1564                 ldlm_callback_reply(req, rc);
1565                 RETURN(0);
1566         case OBD_QC_CALLBACK:
1567                 OBD_FAIL_RETURN(OBD_FAIL_OBD_QC_CALLBACK_NET, 0);
1568                 rc = target_handle_qc_callback(req);
1569                 ldlm_callback_reply(req, rc);
1570                 RETURN(0);
1571         case QUOTA_DQACQ:
1572         case QUOTA_DQREL:
1573                 /* reply in handler */
1574                 rc = target_handle_dqacq_callback(req);
1575                 RETURN(0);
1576         case LLOG_ORIGIN_HANDLE_CREATE:
1577                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1578                 rc = llog_origin_handle_create(req);
1579                 ldlm_callback_reply(req, rc);
1580                 RETURN(0);
1581         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1582                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1583                 rc = llog_origin_handle_next_block(req);
1584                 ldlm_callback_reply(req, rc);
1585                 RETURN(0);
1586         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1587                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1588                 rc = llog_origin_handle_read_header(req);
1589                 ldlm_callback_reply(req, rc);
1590                 RETURN(0);
1591         case LLOG_ORIGIN_HANDLE_CLOSE:
1592                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOGD_NET, 0);
1593                 rc = llog_origin_handle_close(req);
1594                 ldlm_callback_reply(req, rc);
1595                 RETURN(0);
1596         default:
1597                 CERROR("unknown opcode %u\n",
1598                        lustre_msg_get_opc(req->rq_reqmsg));
1599                 ldlm_callback_reply(req, -EPROTO);
1600                 RETURN(0);
1601         }
1602
1603         ns = req->rq_export->exp_obd->obd_namespace;
1604         LASSERT(ns != NULL);
1605
1606         dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF, sizeof(*dlm_req),
1607                                      lustre_swab_ldlm_request);
1608         if (dlm_req == NULL) {
1609                 CERROR ("can't unpack dlm_req\n");
1610                 ldlm_callback_reply(req, -EPROTO);
1611                 RETURN (0);
1612         }
1613
1614         /* Force a known safe race, send a cancel to the server for a lock
1615          * which the server has already started a blocking callback on. */
1616         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
1617             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1618                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
1619                 if (rc < 0)
1620                         CERROR("ldlm_cli_cancel: %d\n", rc);
1621         }
1622
1623         lock = ldlm_handle2lock_ns(ns, &dlm_req->lock_handle[0]);
1624         if (!lock) {
1625                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1626                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1627                 ldlm_callback_reply(req, -EINVAL);
1628                 RETURN(0);
1629         }
1630
1631         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1632         lock_res_and_lock(lock);
1633         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1634         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1635                 /* If somebody cancels locks and cache is already droped,
1636                  * we can tell the server we have no lock. Otherwise, we
1637                  * should send cancel after dropping the cache. */
1638                 if ((lock->l_flags & LDLM_FL_CANCELING) &&
1639                     (lock->l_flags & LDLM_FL_BL_DONE)) {
1640                         LDLM_DEBUG(lock, "callback on lock "
1641                                    LPX64" - lock disappeared\n",
1642                                    dlm_req->lock_handle[0].cookie);
1643                         unlock_res_and_lock(lock);
1644                         LDLM_LOCK_PUT(lock);
1645                         ldlm_callback_reply(req, -EINVAL);
1646                         RETURN(0);
1647                 }
1648                 /* BL_AST locks are not needed in lru.
1649                  * let ldlm_cancel_lru() be fast. */
1650                 ldlm_lock_remove_from_lru(lock);
1651                 lock->l_flags |= LDLM_FL_BL_AST;
1652         }
1653         unlock_res_and_lock(lock);
1654
1655         /* We want the ost thread to get this reply so that it can respond
1656          * to ost requests (write cache writeback) that might be triggered
1657          * in the callback.
1658          *
1659          * But we'd also like to be able to indicate in the reply that we're
1660          * cancelling right now, because it's unused, or have an intent result
1661          * in the reply, so we might have to push the responsibility for sending
1662          * the reply down into the AST handlers, alas. */
1663
1664         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1665         case LDLM_BL_CALLBACK:
1666                 CDEBUG(D_INODE, "blocking ast\n");
1667                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK))
1668                         ldlm_callback_reply(req, 0);
1669                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
1670                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
1671                 break;
1672         case LDLM_CP_CALLBACK:
1673                 CDEBUG(D_INODE, "completion ast\n");
1674                 ldlm_callback_reply(req, 0);
1675                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
1676                 break;
1677         case LDLM_GL_CALLBACK:
1678                 CDEBUG(D_INODE, "glimpse ast\n");
1679                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
1680                 break;
1681         default:
1682                 LBUG();                         /* checked above */
1683         }
1684
1685         RETURN(0);
1686 }
1687
1688 static int ldlm_cancel_handler(struct ptlrpc_request *req)
1689 {
1690         int rc;
1691         ENTRY;
1692
1693         /* Requests arrive in sender's byte order.  The ptlrpc service
1694          * handler has already checked and, if necessary, byte-swapped the
1695          * incoming request message body, but I am responsible for the
1696          * message buffers. */
1697
1698         if (req->rq_export == NULL) {
1699                 struct ldlm_request *dlm_req;
1700
1701                 CERROR("operation %d from %s with bad export cookie "LPU64"\n",
1702                        lustre_msg_get_opc(req->rq_reqmsg),
1703                        libcfs_id2str(req->rq_peer),
1704                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
1705
1706                 dlm_req = lustre_swab_reqbuf(req, DLM_LOCKREQ_OFF,
1707                                              sizeof(*dlm_req),
1708                                              lustre_swab_ldlm_request);
1709                 if (dlm_req != NULL)
1710                         ldlm_lock_dump_handle(D_ERROR,
1711                                               &dlm_req->lock_handle[0]);
1712
1713                 ldlm_callback_reply(req, -ENOTCONN);
1714                 RETURN(0);
1715         }
1716
1717         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1718
1719         /* XXX FIXME move this back to mds/handler.c, bug 249 */
1720         case LDLM_CANCEL:
1721                 CDEBUG(D_INODE, "cancel\n");
1722                 OBD_FAIL_RETURN(OBD_FAIL_LDLM_CANCEL, 0);
1723                 rc = ldlm_handle_cancel(req);
1724                 if (rc)
1725                         break;
1726                 RETURN(0);
1727         case OBD_LOG_CANCEL:
1728                 OBD_FAIL_RETURN(OBD_FAIL_OBD_LOG_CANCEL_NET, 0);
1729                 rc = llog_origin_handle_cancel(req);
1730                 ldlm_callback_reply(req, rc);
1731                 RETURN(0);
1732         default:
1733                 CERROR("invalid opcode %d\n",
1734                        lustre_msg_get_opc(req->rq_reqmsg));
1735                 ldlm_callback_reply(req, -EINVAL);
1736         }
1737
1738         RETURN(0);
1739 }
1740
1741 #ifdef __KERNEL__
1742 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
1743 {
1744         struct ldlm_bl_work_item *blwi = NULL;
1745         static unsigned int num_bl = 0;
1746
1747         spin_lock(&blp->blp_lock);
1748         /* process a request from the blp_list at least every blp_num_threads */
1749         if (!list_empty(&blp->blp_list) &&
1750             (list_empty(&blp->blp_prio_list) || num_bl == 0))
1751                 blwi = list_entry(blp->blp_list.next,
1752                                   struct ldlm_bl_work_item, blwi_entry);
1753         else
1754                 if (!list_empty(&blp->blp_prio_list))
1755                         blwi = list_entry(blp->blp_prio_list.next,
1756                                           struct ldlm_bl_work_item, blwi_entry);
1757
1758         if (blwi) {
1759                 if (++num_bl >= atomic_read(&blp->blp_num_threads))
1760                         num_bl = 0;
1761                 list_del(&blwi->blwi_entry);
1762         }
1763         spin_unlock(&blp->blp_lock);
1764
1765         return blwi;
1766 }
1767
1768 /* This only contains temporary data until the thread starts */
1769 struct ldlm_bl_thread_data {
1770         char                    bltd_name[CFS_CURPROC_COMM_MAX];
1771         struct ldlm_bl_pool     *bltd_blp;
1772         struct completion       bltd_comp;
1773         int                     bltd_num;
1774 };
1775
1776 static int ldlm_bl_thread_main(void *arg);
1777
1778 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
1779 {
1780         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
1781         int rc;
1782
1783         init_completion(&bltd.bltd_comp);
1784         rc = cfs_kernel_thread(ldlm_bl_thread_main, &bltd, 0);
1785         if (rc < 0) {
1786                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
1787                        atomic_read(&blp->blp_num_threads), rc);
1788                 return rc;
1789         }
1790         wait_for_completion(&bltd.bltd_comp);
1791
1792         return 0;
1793 }
1794
1795 static int ldlm_bl_thread_main(void *arg)
1796 {
1797         struct ldlm_bl_pool *blp;
1798         ENTRY;
1799
1800         {
1801                 struct ldlm_bl_thread_data *bltd = arg;
1802
1803                 blp = bltd->bltd_blp;
1804
1805                 bltd->bltd_num = atomic_inc_return(&blp->blp_num_threads) - 1;
1806                 atomic_inc(&blp->blp_busy_threads);
1807
1808                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
1809                         "ldlm_bl_%02d", bltd->bltd_num);
1810                 cfs_daemonize(bltd->bltd_name);
1811
1812                 complete(&bltd->bltd_comp);
1813                 /* cannot use bltd after this, it is only on caller's stack */
1814         }
1815
1816         while (1) {
1817                 struct l_wait_info lwi = { 0 };
1818                 struct ldlm_bl_work_item *blwi = NULL;
1819
1820                 blwi = ldlm_bl_get_work(blp);
1821
1822                 if (blwi == NULL) {
1823                         int busy;
1824
1825                         atomic_dec(&blp->blp_busy_threads);
1826                         l_wait_event_exclusive(blp->blp_waitq,
1827                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
1828                                          &lwi);
1829                         busy = atomic_inc_return(&blp->blp_busy_threads);
1830
1831                         if (blwi->blwi_ns == NULL)
1832                                 /* added by ldlm_cleanup() */
1833                                 break;
1834
1835                         /* Not fatal if racy and have a few too many threads */
1836                         if (unlikely(busy < blp->blp_max_threads &&
1837                                     busy >= atomic_read(&blp->blp_num_threads)))
1838                                 /* discard the return value, we tried */
1839                                 ldlm_bl_thread_start(blp);
1840                 } else {
1841                         if (blwi->blwi_ns == NULL)
1842                                 /* added by ldlm_cleanup() */
1843                                 break;
1844                 }
1845
1846                 if (blwi->blwi_count) {
1847                         /* The special case when we cancel locks in lru
1848                          * asynchronously, we pass the list of locks here.
1849                          * Thus lock is marked LDLM_FL_CANCELING, and already
1850                          * canceled locally. */
1851                         ldlm_cli_cancel_list(&blwi->blwi_head,
1852                                              blwi->blwi_count, NULL, 0);
1853                 } else {
1854                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
1855                                                 blwi->blwi_lock);
1856                 }
1857                 OBD_FREE(blwi, sizeof(*blwi));
1858         }
1859
1860         atomic_dec(&blp->blp_busy_threads);
1861         atomic_dec(&blp->blp_num_threads);
1862         complete(&blp->blp_comp);
1863         RETURN(0);
1864 }
1865
1866 #endif
1867
1868 static int ldlm_setup(void);
1869 static int ldlm_cleanup(void);
1870
1871 int ldlm_get_ref(void)
1872 {
1873         int rc = 0;
1874         ENTRY;
1875         mutex_down(&ldlm_ref_sem);
1876         if (++ldlm_refcount == 1) {
1877                 rc = ldlm_setup();
1878                 if (rc)
1879                         ldlm_refcount--;
1880         }
1881         mutex_up(&ldlm_ref_sem);
1882
1883         RETURN(rc);
1884 }
1885
1886 void ldlm_put_ref(void)
1887 {
1888         ENTRY;
1889         mutex_down(&ldlm_ref_sem);
1890         if (ldlm_refcount == 1) {
1891                 int rc = ldlm_cleanup();
1892                 if (rc)
1893                         CERROR("ldlm_cleanup failed: %d\n", rc);
1894                 else
1895                         ldlm_refcount--;
1896         } else {
1897                 ldlm_refcount--;
1898         }
1899         mutex_up(&ldlm_ref_sem);
1900
1901         EXIT;
1902 }
1903
1904 static int ldlm_setup(void)
1905 {
1906         struct ldlm_bl_pool *blp;
1907         int rc = 0;
1908         int ldlm_min_threads = LDLM_THREADS_AUTO_MIN;
1909         int ldlm_max_threads = LDLM_THREADS_AUTO_MAX;
1910 #ifdef __KERNEL__
1911         int i;
1912 #endif
1913         ENTRY;
1914
1915         if (ldlm_state != NULL)
1916                 RETURN(-EALREADY);
1917
1918         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
1919         if (ldlm_state == NULL)
1920                 RETURN(-ENOMEM);
1921
1922 #ifdef LPROCFS
1923         rc = ldlm_proc_setup();
1924         if (rc != 0)
1925                 GOTO(out_free, rc);
1926 #endif
1927
1928 #ifdef __KERNEL__
1929         if (ldlm_num_threads) {
1930                 /* If ldlm_num_threads is set, it is the min and the max. */
1931                 if (ldlm_num_threads > LDLM_THREADS_AUTO_MAX)
1932                         ldlm_num_threads = LDLM_THREADS_AUTO_MAX;
1933                 if (ldlm_num_threads < LDLM_THREADS_AUTO_MIN)
1934                         ldlm_num_threads = LDLM_THREADS_AUTO_MIN;
1935                 ldlm_min_threads = ldlm_max_threads = ldlm_num_threads;
1936         }
1937 #endif
1938
1939         ldlm_state->ldlm_cb_service =
1940                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
1941                                 LDLM_MAXREPSIZE, LDLM_CB_REQUEST_PORTAL,
1942                                 LDLM_CB_REPLY_PORTAL, 1800,
1943                                 ldlm_callback_handler, "ldlm_cbd",
1944                                 ldlm_svc_proc_dir, NULL,
1945                                 ldlm_min_threads, ldlm_max_threads,
1946                                 "ldlm_cb");
1947
1948         if (!ldlm_state->ldlm_cb_service) {
1949                 CERROR("failed to start service\n");
1950                 GOTO(out_proc, rc = -ENOMEM);
1951         }
1952
1953         ldlm_state->ldlm_cancel_service =
1954                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
1955                                 LDLM_MAXREPSIZE, LDLM_CANCEL_REQUEST_PORTAL,
1956                                 LDLM_CANCEL_REPLY_PORTAL, 6000,
1957                                 ldlm_cancel_handler, "ldlm_canceld",
1958                                 ldlm_svc_proc_dir, NULL,
1959                                 ldlm_min_threads, ldlm_max_threads,
1960                                 "ldlm_cn");
1961
1962         if (!ldlm_state->ldlm_cancel_service) {
1963                 CERROR("failed to start service\n");
1964                 GOTO(out_proc, rc = -ENOMEM);
1965         }
1966
1967         OBD_ALLOC(blp, sizeof(*blp));
1968         if (blp == NULL)
1969                 GOTO(out_proc, rc = -ENOMEM);
1970         ldlm_state->ldlm_bl_pool = blp;
1971
1972         spin_lock_init(&blp->blp_lock);
1973         CFS_INIT_LIST_HEAD(&blp->blp_list);
1974         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
1975         cfs_waitq_init(&blp->blp_waitq);
1976         atomic_set(&blp->blp_num_threads, 0);
1977         atomic_set(&blp->blp_busy_threads, 0);
1978         blp->blp_min_threads = ldlm_min_threads;
1979         blp->blp_max_threads = ldlm_max_threads;
1980
1981 #ifdef __KERNEL__
1982         for (i = 0; i < blp->blp_min_threads; i++) {
1983                 rc = ldlm_bl_thread_start(blp);
1984                 if (rc < 0)
1985                         GOTO(out_thread, rc);
1986         }
1987
1988         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cancel_service);
1989         if (rc)
1990                 GOTO(out_thread, rc);
1991
1992         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cb_service);
1993         if (rc)
1994                 GOTO(out_thread, rc);
1995
1996         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
1997         expired_lock_thread.elt_state = ELT_STOPPED;
1998         cfs_waitq_init(&expired_lock_thread.elt_waitq);
1999
2000         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2001         spin_lock_init(&waiting_locks_spinlock);
2002         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2003
2004         rc = cfs_kernel_thread(expired_lock_main, NULL, CLONE_VM | CLONE_FILES);
2005         if (rc < 0) {
2006                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2007                 GOTO(out_thread, rc);
2008         }
2009
2010         wait_event(expired_lock_thread.elt_waitq,
2011                    expired_lock_thread.elt_state == ELT_READY);
2012 #endif
2013
2014 #ifdef __KERNEL__
2015         rc = ldlm_pools_init();
2016         if (rc)
2017                 GOTO(out_thread, rc);
2018 #endif
2019
2020         RETURN(0);
2021
2022 #ifdef __KERNEL__
2023  out_thread:
2024         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2025         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2026 #endif
2027
2028  out_proc:
2029 #ifdef LPROCFS
2030         ldlm_proc_cleanup();
2031  out_free:
2032 #endif
2033         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2034         ldlm_state = NULL;
2035         return rc;
2036 }
2037
2038 static int ldlm_cleanup(void)
2039 {
2040 #ifdef __KERNEL__
2041         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2042 #endif
2043         ENTRY;
2044
2045         if (!list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) || 
2046             !list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2047                 CERROR("ldlm still has namespaces; clean these up first.\n");
2048                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2049                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2050                 RETURN(-EBUSY);
2051         }
2052
2053 #ifdef __KERNEL__
2054         ldlm_pools_fini();
2055 #endif
2056
2057 #ifdef __KERNEL__
2058         while (atomic_read(&blp->blp_num_threads) > 0) {
2059                 struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2060
2061                 init_completion(&blp->blp_comp);
2062
2063                 spin_lock(&blp->blp_lock);
2064                 list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2065                 cfs_waitq_signal(&blp->blp_waitq);
2066                 spin_unlock(&blp->blp_lock);
2067
2068                 wait_for_completion(&blp->blp_comp);
2069         }
2070         OBD_FREE(blp, sizeof(*blp));
2071
2072         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2073         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2074         ldlm_proc_cleanup();
2075
2076         expired_lock_thread.elt_state = ELT_TERMINATE;
2077         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
2078         wait_event(expired_lock_thread.elt_waitq,
2079                    expired_lock_thread.elt_state == ELT_STOPPED);
2080 #else
2081         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2082         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2083 #endif
2084
2085         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2086         ldlm_state = NULL;
2087
2088         RETURN(0);
2089 }
2090
2091 int __init ldlm_init(void)
2092 {
2093         init_mutex(&ldlm_ref_sem);
2094         init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
2095         init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
2096         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
2097                                                sizeof(struct ldlm_resource), 0,
2098                                                SLAB_HWCACHE_ALIGN);
2099         if (ldlm_resource_slab == NULL)
2100                 return -ENOMEM;
2101
2102         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
2103                                            sizeof(struct ldlm_lock), 0,
2104                                            SLAB_HWCACHE_ALIGN);
2105         if (ldlm_lock_slab == NULL) {
2106                 cfs_mem_cache_destroy(ldlm_resource_slab);
2107                 return -ENOMEM;
2108         }
2109
2110         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
2111                                         sizeof(struct ldlm_interval),
2112                                         0, SLAB_HWCACHE_ALIGN);
2113         if (ldlm_interval_slab == NULL) {
2114                 cfs_mem_cache_destroy(ldlm_resource_slab);
2115                 cfs_mem_cache_destroy(ldlm_lock_slab);
2116                 return -ENOMEM;
2117         }
2118
2119         return 0;
2120 }
2121
2122 void __exit ldlm_exit(void)
2123 {
2124         int rc;
2125         if (ldlm_refcount)
2126                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2127         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2128         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2129         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2130         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2131         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
2132         LASSERTF(rc == 0, "couldn't free interval node slab\n");
2133 }
2134
2135 /* ldlm_extent.c */
2136 EXPORT_SYMBOL(ldlm_extent_shift_kms);
2137
2138 /* ldlm_lock.c */
2139 EXPORT_SYMBOL(ldlm_get_processing_policy);
2140 EXPORT_SYMBOL(ldlm_lock2desc);
2141 EXPORT_SYMBOL(ldlm_register_intent);
2142 EXPORT_SYMBOL(ldlm_lockname);
2143 EXPORT_SYMBOL(ldlm_typename);
2144 EXPORT_SYMBOL(ldlm_lock2handle);
2145 EXPORT_SYMBOL(__ldlm_handle2lock);
2146 EXPORT_SYMBOL(ldlm_lock_get);
2147 EXPORT_SYMBOL(ldlm_lock_put);
2148 EXPORT_SYMBOL(ldlm_lock_fast_match);
2149 EXPORT_SYMBOL(ldlm_lock_fast_release);
2150 EXPORT_SYMBOL(ldlm_lock_match);
2151 EXPORT_SYMBOL(ldlm_lock_cancel);
2152 EXPORT_SYMBOL(ldlm_lock_addref);
2153 EXPORT_SYMBOL(ldlm_lock_decref);
2154 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
2155 EXPORT_SYMBOL(ldlm_lock_change_resource);
2156 EXPORT_SYMBOL(ldlm_lock_set_data);
2157 EXPORT_SYMBOL(ldlm_it2str);
2158 EXPORT_SYMBOL(ldlm_lock_dump);
2159 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2160 EXPORT_SYMBOL(ldlm_cancel_locks_for_export);
2161 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
2162 EXPORT_SYMBOL(ldlm_lock_allow_match);
2163
2164 /* ldlm_request.c */
2165 EXPORT_SYMBOL(ldlm_completion_ast);
2166 EXPORT_SYMBOL(ldlm_blocking_ast);
2167 EXPORT_SYMBOL(ldlm_glimpse_ast);
2168 EXPORT_SYMBOL(ldlm_expired_completion_wait);
2169 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
2170 EXPORT_SYMBOL(ldlm_prep_elc_req);
2171 EXPORT_SYMBOL(ldlm_cli_convert);
2172 EXPORT_SYMBOL(ldlm_cli_enqueue);
2173 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
2174 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
2175 EXPORT_SYMBOL(ldlm_cli_cancel);
2176 EXPORT_SYMBOL(ldlm_cli_cancel_unused);
2177 EXPORT_SYMBOL(ldlm_cli_cancel_req);
2178 EXPORT_SYMBOL(ldlm_cli_join_lru);
2179 EXPORT_SYMBOL(ldlm_replay_locks);
2180 EXPORT_SYMBOL(ldlm_resource_foreach);
2181 EXPORT_SYMBOL(ldlm_namespace_foreach);
2182 EXPORT_SYMBOL(ldlm_namespace_foreach_res);
2183 EXPORT_SYMBOL(ldlm_resource_iterate);
2184 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2185 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2186
2187 /* ldlm_lockd.c */
2188 EXPORT_SYMBOL(ldlm_server_blocking_ast);
2189 EXPORT_SYMBOL(ldlm_server_completion_ast);
2190 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
2191 EXPORT_SYMBOL(ldlm_handle_enqueue);
2192 EXPORT_SYMBOL(ldlm_handle_cancel);
2193 EXPORT_SYMBOL(ldlm_request_cancel);
2194 EXPORT_SYMBOL(ldlm_handle_convert);
2195 EXPORT_SYMBOL(ldlm_del_waiting_lock);
2196 EXPORT_SYMBOL(ldlm_get_ref);
2197 EXPORT_SYMBOL(ldlm_put_ref);
2198 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
2199
2200 /* ldlm_resource.c */
2201 EXPORT_SYMBOL(ldlm_namespace_new);
2202 EXPORT_SYMBOL(ldlm_namespace_cleanup);
2203 EXPORT_SYMBOL(ldlm_namespace_free);
2204 EXPORT_SYMBOL(ldlm_namespace_dump);
2205 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
2206 EXPORT_SYMBOL(ldlm_resource_get);
2207 EXPORT_SYMBOL(ldlm_resource_putref);
2208 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
2209
2210 /* ldlm_lib.c */
2211 EXPORT_SYMBOL(client_import_add_conn);
2212 EXPORT_SYMBOL(client_import_del_conn);
2213 EXPORT_SYMBOL(client_obd_setup);
2214 EXPORT_SYMBOL(client_obd_cleanup);
2215 EXPORT_SYMBOL(client_connect_import);
2216 EXPORT_SYMBOL(client_disconnect_export);
2217 EXPORT_SYMBOL(target_abort_recovery);
2218 EXPORT_SYMBOL(target_cleanup_recovery);
2219 EXPORT_SYMBOL(target_handle_connect);
2220 EXPORT_SYMBOL(target_destroy_export);
2221 EXPORT_SYMBOL(target_cancel_recovery_timer);
2222 EXPORT_SYMBOL(target_send_reply);
2223 EXPORT_SYMBOL(target_queue_recovery_request);
2224 EXPORT_SYMBOL(target_handle_ping);
2225 EXPORT_SYMBOL(target_pack_pool_reply);
2226 EXPORT_SYMBOL(target_handle_disconnect);
2227 EXPORT_SYMBOL(target_queue_last_replay_reply);
2228
2229 /* l_lock.c */
2230 EXPORT_SYMBOL(lock_res_and_lock);
2231 EXPORT_SYMBOL(unlock_res_and_lock);
2232