Whamcloud - gitweb
6268019f67135bb9236ac7182775c77db7a14037
[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  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/ldlm/ldlm_lockd.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Phil Schwan <phil@clusterfs.com>
40  */
41
42 #ifndef EXPORT_SYMTAB
43 # define EXPORT_SYMTAB
44 #endif
45 #define DEBUG_SUBSYSTEM S_LDLM
46
47 #ifdef __KERNEL__
48 # include <libcfs/libcfs.h>
49 #else
50 # include <liblustre.h>
51 #endif
52
53 #include <lustre_dlm.h>
54 #include <obd_class.h>
55 #include <libcfs/list.h>
56 #include "ldlm_internal.h"
57
58 #ifdef __KERNEL__
59 static int ldlm_num_threads;
60 CFS_MODULE_PARM(ldlm_num_threads, "i", int, 0444,
61                 "number of DLM service threads to start");
62 #endif
63
64 extern cfs_mem_cache_t *ldlm_resource_slab;
65 extern cfs_mem_cache_t *ldlm_lock_slab;
66 static cfs_semaphore_t  ldlm_ref_sem;
67 static int ldlm_refcount;
68
69 /* LDLM state */
70
71 static struct ldlm_state *ldlm_state;
72
73 inline cfs_time_t round_timeout(cfs_time_t timeout)
74 {
75         return cfs_time_seconds((int)cfs_duration_sec(cfs_time_sub(timeout, 0)) + 1);
76 }
77
78 /* timeout for initial callback (AST) reply (bz10399) */
79 static inline unsigned int ldlm_get_rq_timeout(void)
80 {
81         /* Non-AT value */
82         unsigned int timeout = min(ldlm_timeout, obd_timeout / 3);
83
84         return timeout < 1 ? 1 : timeout;
85 }
86
87 #ifdef __KERNEL__
88 /* w_l_spinlock protects both waiting_locks_list and expired_lock_thread */
89 static cfs_spinlock_t waiting_locks_spinlock;   /* BH lock (timer) */
90 static cfs_list_t waiting_locks_list;
91 static cfs_timer_t waiting_locks_timer;
92
93 static struct expired_lock_thread {
94         cfs_waitq_t               elt_waitq;
95         int                       elt_state;
96         int                       elt_dump;
97         cfs_list_t                elt_expired_locks;
98 } expired_lock_thread;
99 #endif
100
101 #define ELT_STOPPED   0
102 #define ELT_READY     1
103 #define ELT_TERMINATE 2
104
105 struct ldlm_bl_pool {
106         cfs_spinlock_t          blp_lock;
107
108         /*
109          * blp_prio_list is used for callbacks that should be handled
110          * as a priority. It is used for LDLM_FL_DISCARD_DATA requests.
111          * see bug 13843
112          */
113         cfs_list_t              blp_prio_list;
114
115         /*
116          * blp_list is used for all other callbacks which are likely
117          * to take longer to process.
118          */
119         cfs_list_t              blp_list;
120
121         cfs_waitq_t             blp_waitq;
122         cfs_completion_t        blp_comp;
123         cfs_atomic_t            blp_num_threads;
124         cfs_atomic_t            blp_busy_threads;
125         int                     blp_min_threads;
126         int                     blp_max_threads;
127 };
128
129 struct ldlm_bl_work_item {
130         cfs_list_t              blwi_entry;
131         struct ldlm_namespace  *blwi_ns;
132         struct ldlm_lock_desc   blwi_ld;
133         struct ldlm_lock       *blwi_lock;
134         cfs_list_t              blwi_head;
135         int                     blwi_count;
136 };
137
138 #ifdef __KERNEL__
139
140 static inline int have_expired_locks(void)
141 {
142         int need_to_run;
143
144         ENTRY;
145         cfs_spin_lock_bh(&waiting_locks_spinlock);
146         need_to_run = !cfs_list_empty(&expired_lock_thread.elt_expired_locks);
147         cfs_spin_unlock_bh(&waiting_locks_spinlock);
148
149         RETURN(need_to_run);
150 }
151
152 static int expired_lock_main(void *arg)
153 {
154         cfs_list_t *expired = &expired_lock_thread.elt_expired_locks;
155         struct l_wait_info lwi = { 0 };
156         int do_dump;
157
158         ENTRY;
159         cfs_daemonize("ldlm_elt");
160
161         expired_lock_thread.elt_state = ELT_READY;
162         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
163
164         while (1) {
165                 l_wait_event(expired_lock_thread.elt_waitq,
166                              have_expired_locks() ||
167                              expired_lock_thread.elt_state == ELT_TERMINATE,
168                              &lwi);
169
170                 cfs_spin_lock_bh(&waiting_locks_spinlock);
171                 if (expired_lock_thread.elt_dump) {
172                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
173
174                         /* from waiting_locks_callback, but not in timer */
175                         libcfs_debug_dumplog();
176                         libcfs_run_lbug_upcall(__FILE__,
177                                                 "waiting_locks_callback",
178                                                 expired_lock_thread.elt_dump);
179
180                         cfs_spin_lock_bh(&waiting_locks_spinlock);
181                         expired_lock_thread.elt_dump = 0;
182                 }
183
184                 do_dump = 0;
185
186                 while (!cfs_list_empty(expired)) {
187                         struct obd_export *export;
188                         struct ldlm_lock *lock;
189
190                         lock = cfs_list_entry(expired->next, struct ldlm_lock,
191                                           l_pending_chain);
192                         if ((void *)lock < LP_POISON + CFS_PAGE_SIZE &&
193                             (void *)lock >= LP_POISON) {
194                                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
195                                 CERROR("free lock on elt list %p\n", lock);
196                                 LBUG();
197                         }
198                         cfs_list_del_init(&lock->l_pending_chain);
199                         if ((void *)lock->l_export < LP_POISON + CFS_PAGE_SIZE &&
200                             (void *)lock->l_export >= LP_POISON) {
201                                 CERROR("lock with free export on elt list %p\n",
202                                        lock->l_export);
203                                 lock->l_export = NULL;
204                                 LDLM_ERROR(lock, "free export");
205                                 /* release extra ref grabbed by
206                                  * ldlm_add_waiting_lock() or
207                                  * ldlm_failed_ast() */
208                                 LDLM_LOCK_RELEASE(lock);
209                                 continue;
210                         }
211                         export = class_export_lock_get(lock->l_export, lock);
212                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
213
214                         do_dump++;
215                         class_fail_export(export);
216                         class_export_lock_put(export, lock);
217
218                         /* release extra ref grabbed by ldlm_add_waiting_lock()
219                          * or ldlm_failed_ast() */
220                         LDLM_LOCK_RELEASE(lock);
221
222                         cfs_spin_lock_bh(&waiting_locks_spinlock);
223                 }
224                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
225
226                 if (do_dump && obd_dump_on_eviction) {
227                         CERROR("dump the log upon eviction\n");
228                         libcfs_debug_dumplog();
229                 }
230
231                 if (expired_lock_thread.elt_state == ELT_TERMINATE)
232                         break;
233         }
234
235         expired_lock_thread.elt_state = ELT_STOPPED;
236         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
237         RETURN(0);
238 }
239
240 static int ldlm_add_waiting_lock(struct ldlm_lock *lock);
241
242 /**
243  * Check if there is a request in the export request list
244  * which prevents the lock canceling.
245  */
246 static int ldlm_lock_busy(struct ldlm_lock *lock)
247 {
248         struct ptlrpc_request *req;
249         int match = 0;
250         ENTRY;
251
252         if (lock->l_export == NULL)
253                 return 0;
254
255         cfs_spin_lock(&lock->l_export->exp_lock);
256         cfs_list_for_each_entry(req, &lock->l_export->exp_queued_rpc,
257                                 rq_exp_list) {
258                 if (req->rq_ops->hpreq_lock_match) {
259                         match = req->rq_ops->hpreq_lock_match(req, lock);
260                         if (match)
261                                 break;
262                 }
263         }
264         cfs_spin_unlock(&lock->l_export->exp_lock);
265         RETURN(match);
266 }
267
268 /* This is called from within a timer interrupt and cannot schedule */
269 static void waiting_locks_callback(unsigned long unused)
270 {
271         struct ldlm_lock *lock, *last = NULL;
272
273 repeat:
274         cfs_spin_lock_bh(&waiting_locks_spinlock);
275         while (!cfs_list_empty(&waiting_locks_list)) {
276                 lock = cfs_list_entry(waiting_locks_list.next, struct ldlm_lock,
277                                       l_pending_chain);
278                 if (cfs_time_after(lock->l_callback_timeout,
279                                    cfs_time_current()) ||
280                     (lock->l_req_mode == LCK_GROUP))
281                         break;
282
283                 if (ptlrpc_check_suspend()) {
284                         /* there is a case when we talk to one mds, holding
285                          * lock from another mds. this way we easily can get
286                          * here, if second mds is being recovered. so, we
287                          * suspend timeouts. bug 6019 */
288
289                         LDLM_ERROR(lock, "recharge timeout: %s@%s nid %s ",
290                                    lock->l_export->exp_client_uuid.uuid,
291                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
292                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
293
294                         cfs_list_del_init(&lock->l_pending_chain);
295                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
296                         ldlm_add_waiting_lock(lock);
297                         goto repeat;
298                 }
299
300                 /* if timeout overlaps the activation time of suspended timeouts
301                  * then extend it to give a chance for client to reconnect */
302                 if (cfs_time_before(cfs_time_sub(lock->l_callback_timeout,
303                                                  cfs_time_seconds(obd_timeout)/2),
304                                     ptlrpc_suspend_wakeup_time())) {
305                         LDLM_ERROR(lock, "extend timeout due to recovery: %s@%s nid %s ",
306                                    lock->l_export->exp_client_uuid.uuid,
307                                    lock->l_export->exp_connection->c_remote_uuid.uuid,
308                                    libcfs_nid2str(lock->l_export->exp_connection->c_peer.nid));
309
310                         cfs_list_del_init(&lock->l_pending_chain);
311                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
312                         ldlm_add_waiting_lock(lock);
313                         goto repeat;
314                 }
315
316                 /* Check if we need to prolong timeout */
317                 if (!OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT) &&
318                     ldlm_lock_busy(lock)) {
319                         int cont = 1;
320
321                         if (lock->l_pending_chain.next == &waiting_locks_list)
322                                 cont = 0;
323
324                         LDLM_LOCK_GET(lock);
325
326                         cfs_spin_unlock_bh(&waiting_locks_spinlock);
327                         LDLM_DEBUG(lock, "prolong the busy lock");
328                         ldlm_refresh_waiting_lock(lock,
329                                                   ldlm_get_enq_timeout(lock));
330                         cfs_spin_lock_bh(&waiting_locks_spinlock);
331
332                         if (!cont) {
333                                 LDLM_LOCK_RELEASE(lock);
334                                 break;
335                         }
336
337                         LDLM_LOCK_RELEASE(lock);
338                         continue;
339                 }
340                 lock->l_resource->lr_namespace->ns_timeouts++;
341                 LDLM_ERROR(lock, "lock callback timer expired after %lds: "
342                            "evicting client at %s ",
343                            cfs_time_current_sec()- lock->l_last_activity,
344                            libcfs_nid2str(
345                                    lock->l_export->exp_connection->c_peer.nid));
346
347                 last = lock;
348
349                 /* no needs to take an extra ref on the lock since it was in
350                  * the waiting_locks_list and ldlm_add_waiting_lock()
351                  * already grabbed a ref */
352                 cfs_list_del(&lock->l_pending_chain);
353                 cfs_list_add(&lock->l_pending_chain,
354                              &expired_lock_thread.elt_expired_locks);
355         }
356
357         if (!cfs_list_empty(&expired_lock_thread.elt_expired_locks)) {
358                 if (obd_dump_on_timeout)
359                         expired_lock_thread.elt_dump = __LINE__;
360
361                 cfs_waitq_signal(&expired_lock_thread.elt_waitq);
362         }
363
364         /*
365          * Make sure the timer will fire again if we have any locks
366          * left.
367          */
368         if (!cfs_list_empty(&waiting_locks_list)) {
369                 cfs_time_t timeout_rounded;
370                 lock = cfs_list_entry(waiting_locks_list.next, struct ldlm_lock,
371                                       l_pending_chain);
372                 timeout_rounded = (cfs_time_t)round_timeout(lock->l_callback_timeout);
373                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
374         }
375         cfs_spin_unlock_bh(&waiting_locks_spinlock);
376 }
377
378 /*
379  * Indicate that we're waiting for a client to call us back cancelling a given
380  * lock.  We add it to the pending-callback chain, and schedule the lock-timeout
381  * timer to fire appropriately.  (We round up to the next second, to avoid
382  * floods of timer firings during periods of high lock contention and traffic).
383  * As done by ldlm_add_waiting_lock(), the caller must grab a lock reference
384  * if it has been added to the waiting list (1 is returned).
385  *
386  * Called with the namespace lock held.
387  */
388 static int __ldlm_add_waiting_lock(struct ldlm_lock *lock, int seconds)
389 {
390         cfs_time_t timeout;
391         cfs_time_t timeout_rounded;
392
393         if (!cfs_list_empty(&lock->l_pending_chain))
394                 return 0;
395
396         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT) ||
397             OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
398                 seconds = 1;
399
400         timeout = cfs_time_shift(seconds);
401         if (likely(cfs_time_after(timeout, lock->l_callback_timeout)))
402                 lock->l_callback_timeout = timeout;
403
404         timeout_rounded = round_timeout(lock->l_callback_timeout);
405
406         if (cfs_time_before(timeout_rounded,
407                             cfs_timer_deadline(&waiting_locks_timer)) ||
408             !cfs_timer_is_armed(&waiting_locks_timer)) {
409                 cfs_timer_arm(&waiting_locks_timer, timeout_rounded);
410         }
411         /* if the new lock has a shorter timeout than something earlier on
412            the list, we'll wait the longer amount of time; no big deal. */
413         /* FIFO */
414         cfs_list_add_tail(&lock->l_pending_chain, &waiting_locks_list);
415         return 1;
416 }
417
418 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
419 {
420         int ret;
421         int timeout = ldlm_get_enq_timeout(lock);
422
423         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
424
425         cfs_spin_lock_bh(&waiting_locks_spinlock);
426         if (lock->l_destroyed) {
427                 static cfs_time_t next;
428                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
429                 LDLM_ERROR(lock, "not waiting on destroyed lock (bug 5653)");
430                 if (cfs_time_after(cfs_time_current(), next)) {
431                         next = cfs_time_shift(14400);
432                         libcfs_debug_dumpstack(NULL);
433                 }
434                 return 0;
435         }
436
437         ret = __ldlm_add_waiting_lock(lock, timeout);
438         if (ret)
439                 /* grab ref on the lock if it has been added to the
440                  * waiting list */
441                 LDLM_LOCK_GET(lock);
442         cfs_spin_unlock_bh(&waiting_locks_spinlock);
443
444         LDLM_DEBUG(lock, "%sadding to wait list(timeout: %d, AT: %s)",
445                    ret == 0 ? "not re-" : "", timeout,
446                    AT_OFF ? "off" : "on");
447         return ret;
448 }
449
450 /*
451  * Remove a lock from the pending list, likely because it had its cancellation
452  * callback arrive without incident.  This adjusts the lock-timeout timer if
453  * needed.  Returns 0 if the lock wasn't pending after all, 1 if it was.
454  * As done by ldlm_del_waiting_lock(), the caller must release the lock
455  * reference when the lock is removed from any list (1 is returned).
456  *
457  * Called with namespace lock held.
458  */
459 static int __ldlm_del_waiting_lock(struct ldlm_lock *lock)
460 {
461         cfs_list_t *list_next;
462
463         if (cfs_list_empty(&lock->l_pending_chain))
464                 return 0;
465
466         list_next = lock->l_pending_chain.next;
467         if (lock->l_pending_chain.prev == &waiting_locks_list) {
468                 /* Removing the head of the list, adjust timer. */
469                 if (list_next == &waiting_locks_list) {
470                         /* No more, just cancel. */
471                         cfs_timer_disarm(&waiting_locks_timer);
472                 } else {
473                         struct ldlm_lock *next;
474                         next = cfs_list_entry(list_next, struct ldlm_lock,
475                                               l_pending_chain);
476                         cfs_timer_arm(&waiting_locks_timer,
477                                       round_timeout(next->l_callback_timeout));
478                 }
479         }
480         cfs_list_del_init(&lock->l_pending_chain);
481
482         return 1;
483 }
484
485 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
486 {
487         int ret;
488
489         if (lock->l_export == NULL) {
490                 /* We don't have a "waiting locks list" on clients. */
491                 CDEBUG(D_DLMTRACE, "Client lock %p : no-op\n", lock);
492                 return 0;
493         }
494
495         cfs_spin_lock_bh(&waiting_locks_spinlock);
496         ret = __ldlm_del_waiting_lock(lock);
497         cfs_spin_unlock_bh(&waiting_locks_spinlock);
498         if (ret)
499                 /* release lock ref if it has indeed been removed
500                  * from a list */
501                 LDLM_LOCK_RELEASE(lock);
502
503         LDLM_DEBUG(lock, "%s", ret == 0 ? "wasn't waiting" : "removed");
504         return ret;
505 }
506
507 /*
508  * Prolong the lock
509  *
510  * Called with namespace lock held.
511  */
512 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
513 {
514         if (lock->l_export == NULL) {
515                 /* We don't have a "waiting locks list" on clients. */
516                 LDLM_DEBUG(lock, "client lock: no-op");
517                 return 0;
518         }
519
520         cfs_spin_lock_bh(&waiting_locks_spinlock);
521
522         if (cfs_list_empty(&lock->l_pending_chain)) {
523                 cfs_spin_unlock_bh(&waiting_locks_spinlock);
524                 LDLM_DEBUG(lock, "wasn't waiting");
525                 return 0;
526         }
527
528         /* we remove/add the lock to the waiting list, so no needs to
529          * release/take a lock reference */
530         __ldlm_del_waiting_lock(lock);
531         __ldlm_add_waiting_lock(lock, timeout);
532         cfs_spin_unlock_bh(&waiting_locks_spinlock);
533
534         LDLM_DEBUG(lock, "refreshed");
535         return 1;
536 }
537 #else /* !__KERNEL__ */
538
539 static int ldlm_add_waiting_lock(struct ldlm_lock *lock)
540 {
541         LASSERT(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK));
542         RETURN(1);
543 }
544
545 int ldlm_del_waiting_lock(struct ldlm_lock *lock)
546 {
547         RETURN(0);
548 }
549
550 int ldlm_refresh_waiting_lock(struct ldlm_lock *lock, int timeout)
551 {
552         RETURN(0);
553 }
554 #endif /* __KERNEL__ */
555
556 static void ldlm_failed_ast(struct ldlm_lock *lock, int rc,
557                             const char *ast_type)
558 {
559         LCONSOLE_ERROR_MSG(0x138, "%s: A client on nid %s was evicted due "
560                            "to a lock %s callback time out: rc %d\n",
561                            lock->l_export->exp_obd->obd_name,
562                            obd_export_nid2str(lock->l_export), ast_type, rc);
563
564         if (obd_dump_on_timeout)
565                 libcfs_debug_dumplog();
566 #ifdef __KERNEL__
567         cfs_spin_lock_bh(&waiting_locks_spinlock);
568         if (__ldlm_del_waiting_lock(lock) == 0)
569                 /* the lock was not in any list, grab an extra ref before adding
570                  * the lock to the expired list */
571                 LDLM_LOCK_GET(lock);
572         cfs_list_add(&lock->l_pending_chain,
573                      &expired_lock_thread.elt_expired_locks);
574         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
575         cfs_spin_unlock_bh(&waiting_locks_spinlock);
576 #else
577         class_fail_export(lock->l_export);
578 #endif
579 }
580
581 static int ldlm_handle_ast_error(struct ldlm_lock *lock,
582                                  struct ptlrpc_request *req, int rc,
583                                  const char *ast_type)
584 {
585         lnet_process_id_t peer = req->rq_import->imp_connection->c_peer;
586
587         if (rc == -ETIMEDOUT || rc == -EINTR || rc == -ENOTCONN) {
588                 LASSERT(lock->l_export);
589                 if (lock->l_export->exp_libclient) {
590                         LDLM_DEBUG(lock, "%s AST to liblustre client (nid %s)"
591                                    " timeout, just cancelling lock", ast_type,
592                                    libcfs_nid2str(peer.nid));
593                         ldlm_lock_cancel(lock);
594                         rc = -ERESTART;
595                 } else if (lock->l_flags & LDLM_FL_CANCEL) {
596                         LDLM_DEBUG(lock, "%s AST timeout from nid %s, but "
597                                    "cancel was received (AST reply lost?)",
598                                    ast_type, libcfs_nid2str(peer.nid));
599                         ldlm_lock_cancel(lock);
600                         rc = -ERESTART;
601                 } else {
602                         ldlm_del_waiting_lock(lock);
603                         ldlm_failed_ast(lock, rc, ast_type);
604                 }
605         } else if (rc) {
606                 if (rc == -EINVAL)
607                         LDLM_DEBUG(lock, "client (nid %s) returned %d"
608                                " from %s AST - normal race",
609                                libcfs_nid2str(peer.nid),
610                                req->rq_repmsg ?
611                                lustre_msg_get_status(req->rq_repmsg) : -1,
612                                ast_type);
613                 else
614                         LDLM_ERROR(lock, "client (nid %s) returned %d "
615                                    "from %s AST", libcfs_nid2str(peer.nid),
616                                    (req->rq_repmsg != NULL) ?
617                                    lustre_msg_get_status(req->rq_repmsg) : 0,
618                                    ast_type);
619                 ldlm_lock_cancel(lock);
620                 /* Server-side AST functions are called from ldlm_reprocess_all,
621                  * which needs to be told to please restart its reprocessing. */
622                 rc = -ERESTART;
623         }
624
625         return rc;
626 }
627
628 static int ldlm_cb_interpret(const struct lu_env *env,
629                              struct ptlrpc_request *req, void *data, int rc)
630 {
631         struct ldlm_cb_set_arg *arg;
632         struct ldlm_lock *lock;
633         ENTRY;
634
635         LASSERT(data != NULL);
636
637         arg = req->rq_async_args.pointer_arg[0];
638         lock = req->rq_async_args.pointer_arg[1];
639         LASSERT(lock != NULL);
640         if (rc != 0) {
641                 /* If client canceled the lock but the cancel has not
642                  * been received yet, we need to update lvbo to have the
643                  * proper attributes cached. */
644                 if (rc == -EINVAL && arg->type == LDLM_BL_CALLBACK)
645                         ldlm_res_lvbo_update(lock->l_resource, NULL, 1);
646                 rc = ldlm_handle_ast_error(lock, req, rc,
647                                            arg->type == LDLM_BL_CALLBACK
648                                            ? "blocking" : "completion");
649         }
650
651         LDLM_LOCK_RELEASE(lock);
652
653         if (rc == -ERESTART)
654                 cfs_atomic_set(&arg->restart, 1);
655
656         RETURN(0);
657 }
658
659 static inline int ldlm_bl_and_cp_ast_fini(struct ptlrpc_request *req,
660                                           struct ldlm_cb_set_arg *arg,
661                                           struct ldlm_lock *lock,
662                                           int instant_cancel)
663 {
664         int rc = 0;
665         ENTRY;
666
667         if (unlikely(instant_cancel)) {
668                 rc = ptl_send_rpc(req, 1);
669                 ptlrpc_req_finished(req);
670                 if (rc == 0)
671                         /* If we cancelled the lock, we need to restart
672                          * ldlm_reprocess_queue */
673                         cfs_atomic_set(&arg->restart, 1);
674         } else {
675                 LDLM_LOCK_GET(lock);
676                 ptlrpc_set_add_req(arg->set, req);
677         }
678
679         RETURN(rc);
680 }
681
682 /**
683  * Check if there are requests in the export request list which prevent
684  * the lock canceling and make these requests high priority ones.
685  */
686 static void ldlm_lock_reorder_req(struct ldlm_lock *lock)
687 {
688         struct ptlrpc_request *req;
689         ENTRY;
690
691         if (lock->l_export == NULL) {
692                 LDLM_DEBUG(lock, "client lock: no-op");
693                 RETURN_EXIT;
694         }
695
696         cfs_spin_lock(&lock->l_export->exp_lock);
697         cfs_list_for_each_entry(req, &lock->l_export->exp_queued_rpc,
698                                 rq_exp_list) {
699                 if (!req->rq_hp && req->rq_ops->hpreq_lock_match &&
700                     req->rq_ops->hpreq_lock_match(req, lock))
701                         ptlrpc_hpreq_reorder(req);
702         }
703         cfs_spin_unlock(&lock->l_export->exp_lock);
704         EXIT;
705 }
706
707 /*
708  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
709  * enqueued server lock conflicts with given one.
710  *
711  * Sends blocking ast rpc to the client owning that lock; arms timeout timer
712  * to wait for client response.
713  */
714 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
715                              struct ldlm_lock_desc *desc,
716                              void *data, int flag)
717 {
718         struct ldlm_cb_set_arg *arg = data;
719         struct ldlm_request    *body;
720         struct ptlrpc_request  *req;
721         int                     instant_cancel = 0;
722         int                     rc = 0;
723         ENTRY;
724
725         if (flag == LDLM_CB_CANCELING)
726                 /* Don't need to do anything here. */
727                 RETURN(0);
728
729         LASSERT(lock);
730         LASSERT(data != NULL);
731         if (lock->l_export->exp_obd->obd_recovering != 0) {
732                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
733                 ldlm_lock_dump(D_ERROR, lock, 0);
734         }
735
736         ldlm_lock_reorder_req(lock);
737
738         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
739                                         &RQF_LDLM_BL_CALLBACK,
740                                         LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK);
741         if (req == NULL)
742                 RETURN(-ENOMEM);
743
744         req->rq_async_args.pointer_arg[0] = arg;
745         req->rq_async_args.pointer_arg[1] = lock;
746         req->rq_interpret_reply = ldlm_cb_interpret;
747         req->rq_no_resend = 1;
748
749         lock_res(lock->l_resource);
750         if (lock->l_granted_mode != lock->l_req_mode) {
751                 /* this blocking AST will be communicated as part of the
752                  * completion AST instead */
753                 unlock_res(lock->l_resource);
754                 ptlrpc_req_finished(req);
755                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
756                 RETURN(0);
757         }
758
759         if (lock->l_destroyed) {
760                 /* What's the point? */
761                 unlock_res(lock->l_resource);
762                 ptlrpc_req_finished(req);
763                 RETURN(0);
764         }
765
766         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
767                 instant_cancel = 1;
768
769         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
770         body->lock_handle[0] = lock->l_remote_handle;
771         body->lock_desc = *desc;
772         body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
773
774         LDLM_DEBUG(lock, "server preparing blocking AST");
775
776         ptlrpc_request_set_replen(req);
777         if (instant_cancel) {
778                 unlock_res(lock->l_resource);
779                 ldlm_lock_cancel(lock);
780         } else {
781                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
782                 ldlm_add_waiting_lock(lock);
783                 unlock_res(lock->l_resource);
784         }
785
786         req->rq_send_state = LUSTRE_IMP_FULL;
787         /* ptlrpc_request_alloc_pack already set timeout */
788         if (AT_OFF)
789                 req->rq_timeout = ldlm_get_rq_timeout();
790
791         if (lock->l_export && lock->l_export->exp_nid_stats &&
792             lock->l_export->exp_nid_stats->nid_ldlm_stats)
793                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
794                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
795
796         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
797
798         RETURN(rc);
799 }
800
801 int ldlm_server_completion_ast(struct ldlm_lock *lock, int flags, void *data)
802 {
803         struct ldlm_cb_set_arg *arg = data;
804         struct ldlm_request    *body;
805         struct ptlrpc_request  *req;
806         long                    total_enqueue_wait;
807         int                     instant_cancel = 0;
808         int                     rc = 0;
809         ENTRY;
810
811         LASSERT(lock != NULL);
812         LASSERT(data != NULL);
813
814         total_enqueue_wait = cfs_time_sub(cfs_time_current_sec(),
815                                           lock->l_last_activity);
816
817         req = ptlrpc_request_alloc(lock->l_export->exp_imp_reverse,
818                                     &RQF_LDLM_CP_CALLBACK);
819         if (req == NULL)
820                 RETURN(-ENOMEM);
821
822         lock_res_and_lock(lock);
823         if (lock->l_resource->lr_lvb_len)
824                  req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT,
825                                       lock->l_resource->lr_lvb_len);
826         unlock_res_and_lock(lock);
827
828         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
829         if (rc) {
830                 ptlrpc_request_free(req);
831                 RETURN(rc);
832         }
833
834         req->rq_async_args.pointer_arg[0] = arg;
835         req->rq_async_args.pointer_arg[1] = lock;
836         req->rq_interpret_reply = ldlm_cb_interpret;
837         req->rq_no_resend = 1;
838         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
839
840         body->lock_handle[0] = lock->l_remote_handle;
841         body->lock_flags = flags;
842         ldlm_lock2desc(lock, &body->lock_desc);
843         if (lock->l_resource->lr_lvb_len) {
844                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
845
846                 lock_res_and_lock(lock);
847                 memcpy(lvb, lock->l_resource->lr_lvb_data,
848                        lock->l_resource->lr_lvb_len);
849                 unlock_res_and_lock(lock);
850         }
851
852         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
853                    total_enqueue_wait);
854
855         /* Server-side enqueue wait time estimate, used in
856             __ldlm_add_waiting_lock to set future enqueue timers */
857         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
858                 at_measured(&lock->l_resource->lr_namespace->ns_at_estimate,
859                             total_enqueue_wait);
860         else
861                 /* bz18618. Don't add lock enqueue time we spend waiting for a
862                    previous callback to fail. Locks waiting legitimately will
863                    get extended by ldlm_refresh_waiting_lock regardless of the
864                    estimate, so it's okay to underestimate here. */
865                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
866                        "It is likely that a previous callback timed out.",
867                        total_enqueue_wait,
868                        at_get(&lock->l_resource->lr_namespace->ns_at_estimate));
869
870         ptlrpc_request_set_replen(req);
871
872         req->rq_send_state = LUSTRE_IMP_FULL;
873         /* ptlrpc_request_pack already set timeout */
874         if (AT_OFF)
875                 req->rq_timeout = ldlm_get_rq_timeout();
876
877         /* We only send real blocking ASTs after the lock is granted */
878         lock_res_and_lock(lock);
879         if (lock->l_flags & LDLM_FL_AST_SENT) {
880                 body->lock_flags |= LDLM_FL_AST_SENT;
881                 /* copy ast flags like LDLM_FL_DISCARD_DATA */
882                 body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
883
884                 /* We might get here prior to ldlm_handle_enqueue setting
885                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
886                  * into waiting list, but this is safe and similar code in
887                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
888                  * that would not only cancel the lock, but will also remove
889                  * it from waiting list */
890                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
891                         unlock_res_and_lock(lock);
892                         ldlm_lock_cancel(lock);
893                         instant_cancel = 1;
894                         lock_res_and_lock(lock);
895                 } else {
896                         /* start the lock-timeout clock */
897                         ldlm_add_waiting_lock(lock);
898                 }
899         }
900         unlock_res_and_lock(lock);
901
902         if (lock->l_export && lock->l_export->exp_nid_stats &&
903             lock->l_export->exp_nid_stats->nid_ldlm_stats)
904                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
905                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
906
907         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
908
909         RETURN(rc);
910 }
911
912 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
913 {
914         struct ldlm_resource  *res = lock->l_resource;
915         struct ldlm_request   *body;
916         struct ptlrpc_request *req;
917         int                    rc;
918         ENTRY;
919
920         LASSERT(lock != NULL);
921
922         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
923                                         &RQF_LDLM_GL_CALLBACK,
924                                         LUSTRE_DLM_VERSION, LDLM_GL_CALLBACK);
925
926         if (req == NULL)
927                 RETURN(-ENOMEM);
928
929         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
930         body->lock_handle[0] = lock->l_remote_handle;
931         ldlm_lock2desc(lock, &body->lock_desc);
932
933         lock_res_and_lock(lock);
934         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
935                              lock->l_resource->lr_lvb_len);
936         unlock_res_and_lock(lock);
937         res = lock->l_resource;
938         ptlrpc_request_set_replen(req);
939
940
941         req->rq_send_state = LUSTRE_IMP_FULL;
942         /* ptlrpc_request_alloc_pack already set timeout */
943         if (AT_OFF)
944                 req->rq_timeout = ldlm_get_rq_timeout();
945
946         if (lock->l_export && lock->l_export->exp_nid_stats &&
947             lock->l_export->exp_nid_stats->nid_ldlm_stats)
948                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
949                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
950
951         rc = ptlrpc_queue_wait(req);
952         if (rc == -ELDLM_NO_LOCK_DATA)
953                 LDLM_DEBUG(lock, "lost race - client has a lock but no inode");
954         else if (rc != 0)
955                 rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
956         else
957                 rc = ldlm_res_lvbo_update(res, req, 1);
958
959         ptlrpc_req_finished(req);
960         if (rc == -ERESTART)
961                 ldlm_reprocess_all(res);
962
963         RETURN(rc);
964 }
965
966 #ifdef __KERNEL__
967 extern unsigned long long lu_time_stamp_get(void);
968 #else
969 #define lu_time_stamp_get() time(NULL)
970 #endif
971
972 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
973                        struct lprocfs_stats *srv_stats)
974 {
975         int lock_type = 0, op = 0;
976
977         lock_type = dlm_req->lock_desc.l_resource.lr_type;
978
979         switch (lock_type) {
980         case LDLM_PLAIN:
981                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
982                 break;
983         case LDLM_EXTENT:
984                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
985                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
986                 else
987                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
988                 break;
989         case LDLM_FLOCK:
990                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
991                 break;
992         case LDLM_IBITS:
993                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
994                 break;
995         default:
996                 op = 0;
997                 break;
998         }
999
1000         if (op)
1001                 lprocfs_counter_incr(srv_stats, op);
1002
1003         return;
1004 }
1005
1006 /*
1007  * Main server-side entry point into LDLM. This is called by ptlrpc service
1008  * threads to carry out client lock enqueueing requests.
1009  */
1010 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1011                          struct ptlrpc_request *req,
1012                          const struct ldlm_request *dlm_req,
1013                          const struct ldlm_callback_suite *cbs)
1014 {
1015         struct ldlm_reply *dlm_rep;
1016         __u32 flags;
1017         ldlm_error_t err = ELDLM_OK;
1018         struct ldlm_lock *lock = NULL;
1019         void *cookie = NULL;
1020         int rc = 0;
1021         ENTRY;
1022
1023         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1024
1025         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1026         flags = dlm_req->lock_flags;
1027
1028         LASSERT(req->rq_export);
1029
1030         if (req->rq_rqbd->rqbd_service->srv_stats)
1031                 ldlm_svc_get_eopc(dlm_req,
1032                                   req->rq_rqbd->rqbd_service->srv_stats);
1033
1034         if (req->rq_export && req->rq_export->exp_nid_stats &&
1035             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1036                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1037                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1038
1039         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1040                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1041                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1042                           dlm_req->lock_desc.l_resource.lr_type);
1043                 GOTO(out, rc = -EFAULT);
1044         }
1045
1046         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1047                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1048                      dlm_req->lock_desc.l_req_mode &
1049                      (dlm_req->lock_desc.l_req_mode-1))) {
1050                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1051                           dlm_req->lock_desc.l_req_mode);
1052                 GOTO(out, rc = -EFAULT);
1053         }
1054
1055         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
1056                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1057                              LDLM_PLAIN)) {
1058                         DEBUG_REQ(D_ERROR, req,
1059                                   "PLAIN lock request from IBITS client?");
1060                         GOTO(out, rc = -EPROTO);
1061                 }
1062         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1063                             LDLM_IBITS)) {
1064                 DEBUG_REQ(D_ERROR, req,
1065                           "IBITS lock request from unaware client?");
1066                 GOTO(out, rc = -EPROTO);
1067         }
1068
1069 #if 0
1070         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1071            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1072            ibits for mgc/mgs) */
1073
1074         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1075          * inodebits lock if client does not support them. */
1076         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
1077             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1078                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1079                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1080                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1081                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1082                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1083         }
1084 #endif
1085
1086         if (unlikely(flags & LDLM_FL_REPLAY)) {
1087                 /* Find an existing lock in the per-export lock hash */
1088                 lock = cfs_hash_lookup(req->rq_export->exp_lock_hash,
1089                                        (void *)&dlm_req->lock_handle[0]);
1090                 if (lock != NULL) {
1091                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1092                                   LPX64, lock->l_handle.h_cookie);
1093                         GOTO(existing_lock, rc = 0);
1094                 }
1095         }
1096
1097         /* The lock's callback data might be set in the policy function */
1098         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1099                                 dlm_req->lock_desc.l_resource.lr_type,
1100                                 dlm_req->lock_desc.l_req_mode,
1101                                 cbs, NULL, 0);
1102
1103         if (!lock)
1104                 GOTO(out, rc = -ENOMEM);
1105
1106         lock->l_last_activity = cfs_time_current_sec();
1107         lock->l_remote_handle = dlm_req->lock_handle[0];
1108         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1109
1110         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1111         /* Don't enqueue a lock onto the export if it has already
1112          * been evicted.  Cancel it now instead. (bug 3822) */
1113         if (req->rq_export->exp_failed) {
1114                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1115                 GOTO(out, rc = -ENOTCONN);
1116         }
1117
1118         lock->l_export = class_export_lock_get(req->rq_export, lock);
1119         if (lock->l_export->exp_lock_hash)
1120                 cfs_hash_add(lock->l_export->exp_lock_hash,
1121                              &lock->l_remote_handle,
1122                              &lock->l_exp_hash);
1123
1124 existing_lock:
1125
1126         if (flags & LDLM_FL_HAS_INTENT) {
1127                 /* In this case, the reply buffer is allocated deep in
1128                  * local_lock_enqueue by the policy function. */
1129                 cookie = req;
1130         } else {
1131                 lock_res_and_lock(lock);
1132                 if (lock->l_resource->lr_lvb_len) {
1133                         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1134                                              RCL_SERVER,
1135                                              lock->l_resource->lr_lvb_len);
1136                 }
1137                 unlock_res_and_lock(lock);
1138
1139                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1140                         GOTO(out, rc = -ENOMEM);
1141
1142                 rc = req_capsule_server_pack(&req->rq_pill);
1143                 if (rc)
1144                         GOTO(out, rc);
1145         }
1146
1147         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1148                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1149         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1150                 lock->l_req_extent = lock->l_policy_data.l_extent;
1151
1152         err = ldlm_lock_enqueue(ns, &lock, cookie, (int *)&flags);
1153         if (err)
1154                 GOTO(out, err);
1155
1156         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1157         dlm_rep->lock_flags = flags;
1158
1159         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1160         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1161
1162         /* We never send a blocking AST until the lock is granted, but
1163          * we can tell it right now */
1164         lock_res_and_lock(lock);
1165
1166         /* Now take into account flags to be inherited from original lock
1167            request both in reply to client and in our own lock flags. */
1168         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1169         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1170
1171         /* Don't move a pending lock onto the export if it has already
1172          * been evicted.  Cancel it now instead. (bug 5683) */
1173         if (unlikely(req->rq_export->exp_failed ||
1174                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1175                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1176                 rc = -ENOTCONN;
1177         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1178                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
1179                 if (lock->l_granted_mode == lock->l_req_mode) {
1180                         /*
1181                          * Only cancel lock if it was granted, because it would
1182                          * be destroyed immediately and would never be granted
1183                          * in the future, causing timeouts on client.  Not
1184                          * granted lock will be cancelled immediately after
1185                          * sending completion AST.
1186                          */
1187                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1188                                 unlock_res_and_lock(lock);
1189                                 ldlm_lock_cancel(lock);
1190                                 lock_res_and_lock(lock);
1191                         } else
1192                                 ldlm_add_waiting_lock(lock);
1193                 }
1194         }
1195         /* Make sure we never ever grant usual metadata locks to liblustre
1196            clients */
1197         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1198             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1199              req->rq_export->exp_libclient) {
1200                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1201                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1202                         CERROR("Granting sync lock to libclient. "
1203                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1204                                dlm_req->lock_flags, dlm_rep->lock_flags,
1205                                lock->l_flags);
1206                         LDLM_ERROR(lock, "sync lock");
1207                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1208                                 struct ldlm_intent *it;
1209
1210                                 it = req_capsule_client_get(&req->rq_pill,
1211                                                             &RMF_LDLM_INTENT);
1212                                 if (it != NULL) {
1213                                         CERROR("This is intent %s ("LPU64")\n",
1214                                                ldlm_it2str(it->opc), it->opc);
1215                                 }
1216                         }
1217                 }
1218         }
1219
1220         unlock_res_and_lock(lock);
1221
1222         EXIT;
1223  out:
1224         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1225         if (!req->rq_packed_final) {
1226                 err = lustre_pack_reply(req, 1, NULL, NULL);
1227                 if (rc == 0)
1228                         rc = err;
1229         }
1230
1231         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1232          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1233         if (lock) {
1234                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1235                            "(err=%d, rc=%d)", err, rc);
1236
1237                 lock_res_and_lock(lock);
1238                 if (rc == 0) {
1239                         if (lock->l_resource->lr_lvb_len > 0) {
1240                                 void *lvb;
1241
1242                                 lvb = req_capsule_server_get(&req->rq_pill,
1243                                                              &RMF_DLM_LVB);
1244                                 LASSERTF(lvb != NULL, "req %p, lock %p\n",
1245                                          req, lock);
1246
1247                                 memcpy(lvb, lock->l_resource->lr_lvb_data,
1248                                        lock->l_resource->lr_lvb_len);
1249                         }
1250                 } else {
1251                         ldlm_resource_unlink_lock(lock);
1252                         ldlm_lock_destroy_nolock(lock);
1253                 }
1254                 unlock_res_and_lock(lock);
1255
1256                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1257                         ldlm_reprocess_all(lock->l_resource);
1258
1259                 LDLM_LOCK_RELEASE(lock);
1260         }
1261
1262         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1263                           lock, rc);
1264
1265         return rc;
1266 }
1267
1268 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1269                         ldlm_completion_callback completion_callback,
1270                         ldlm_blocking_callback blocking_callback,
1271                         ldlm_glimpse_callback glimpse_callback)
1272 {
1273         struct ldlm_request *dlm_req;
1274         struct ldlm_callback_suite cbs = {
1275                 .lcs_completion = completion_callback,
1276                 .lcs_blocking   = blocking_callback,
1277                 .lcs_glimpse    = glimpse_callback
1278         };
1279         int rc;
1280
1281         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1282         if (dlm_req != NULL) {
1283                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1284                                           req, dlm_req, &cbs);
1285         } else {
1286                 rc = -EFAULT;
1287         }
1288         return rc;
1289 }
1290
1291 int ldlm_handle_convert0(struct ptlrpc_request *req,
1292                          const struct ldlm_request *dlm_req)
1293 {
1294         struct ldlm_reply *dlm_rep;
1295         struct ldlm_lock *lock;
1296         int rc;
1297         ENTRY;
1298
1299         if (req->rq_export && req->rq_export->exp_nid_stats &&
1300             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1301                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1302                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1303
1304         rc = req_capsule_server_pack(&req->rq_pill);
1305         if (rc)
1306                 RETURN(rc);
1307
1308         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1309         dlm_rep->lock_flags = dlm_req->lock_flags;
1310
1311         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1312         if (!lock) {
1313                 req->rq_status = EINVAL;
1314         } else {
1315                 void *res = NULL;
1316
1317                 LDLM_DEBUG(lock, "server-side convert handler START");
1318
1319                 lock->l_last_activity = cfs_time_current_sec();
1320                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1321                                         &dlm_rep->lock_flags);
1322                 if (res) {
1323                         if (ldlm_del_waiting_lock(lock))
1324                                 LDLM_DEBUG(lock, "converted waiting lock");
1325                         req->rq_status = 0;
1326                 } else {
1327                         req->rq_status = EDEADLOCK;
1328                 }
1329         }
1330
1331         if (lock) {
1332                 if (!req->rq_status)
1333                         ldlm_reprocess_all(lock->l_resource);
1334                 LDLM_DEBUG(lock, "server-side convert handler END");
1335                 LDLM_LOCK_PUT(lock);
1336         } else
1337                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1338
1339         RETURN(0);
1340 }
1341
1342 int ldlm_handle_convert(struct ptlrpc_request *req)
1343 {
1344         int rc;
1345         struct ldlm_request *dlm_req;
1346
1347         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1348         if (dlm_req != NULL) {
1349                 rc = ldlm_handle_convert0(req, dlm_req);
1350         } else {
1351                 CERROR ("Can't unpack dlm_req\n");
1352                 rc = -EFAULT;
1353         }
1354         return rc;
1355 }
1356
1357 /* Cancel all the locks whos handles are packed into ldlm_request */
1358 int ldlm_request_cancel(struct ptlrpc_request *req,
1359                         const struct ldlm_request *dlm_req, int first)
1360 {
1361         struct ldlm_resource *res, *pres = NULL;
1362         struct ldlm_lock *lock;
1363         int i, count, done = 0;
1364         ENTRY;
1365
1366         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1367         if (first >= count)
1368                 RETURN(0);
1369
1370         /* There is no lock on the server at the replay time,
1371          * skip lock cancelling to make replay tests to pass. */
1372         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1373                 RETURN(0);
1374
1375         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1376                           "starting at %d", count, first);
1377
1378         for (i = first; i < count; i++) {
1379                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1380                 if (!lock) {
1381                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1382                                           "lock (cookie "LPU64")",
1383                                           dlm_req->lock_handle[i].cookie);
1384                         continue;
1385                 }
1386
1387                 res = lock->l_resource;
1388                 done++;
1389
1390                 if (res != pres) {
1391                         if (pres != NULL) {
1392                                 ldlm_reprocess_all(pres);
1393                                 LDLM_RESOURCE_DELREF(pres);
1394                                 ldlm_resource_putref(pres);
1395                         }
1396                         if (res != NULL) {
1397                                 ldlm_resource_getref(res);
1398                                 LDLM_RESOURCE_ADDREF(res);
1399                                 ldlm_res_lvbo_update(res, NULL, 1);
1400                         }
1401                         pres = res;
1402                 }
1403                 ldlm_lock_cancel(lock);
1404                 LDLM_LOCK_PUT(lock);
1405         }
1406         if (pres != NULL) {
1407                 ldlm_reprocess_all(pres);
1408                 LDLM_RESOURCE_DELREF(pres);
1409                 ldlm_resource_putref(pres);
1410         }
1411         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1412         RETURN(done);
1413 }
1414
1415 int ldlm_handle_cancel(struct ptlrpc_request *req)
1416 {
1417         struct ldlm_request *dlm_req;
1418         int rc;
1419         ENTRY;
1420
1421         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1422         if (dlm_req == NULL) {
1423                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1424                 RETURN(-EFAULT);
1425         }
1426
1427         if (req->rq_export && req->rq_export->exp_nid_stats &&
1428             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1429                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1430                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1431
1432         rc = req_capsule_server_pack(&req->rq_pill);
1433         if (rc)
1434                 RETURN(rc);
1435
1436         if (!ldlm_request_cancel(req, dlm_req, 0))
1437                 req->rq_status = ESTALE;
1438
1439         if (ptlrpc_reply(req) != 0)
1440                 LBUG();
1441
1442         RETURN(0);
1443 }
1444
1445 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1446                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1447 {
1448         int do_ast;
1449         ENTRY;
1450
1451         LDLM_DEBUG(lock, "client blocking AST callback handler");
1452
1453         lock_res_and_lock(lock);
1454         lock->l_flags |= LDLM_FL_CBPENDING;
1455
1456         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1457                 lock->l_flags |= LDLM_FL_CANCEL;
1458
1459         do_ast = (!lock->l_readers && !lock->l_writers);
1460         unlock_res_and_lock(lock);
1461
1462         if (do_ast) {
1463                 CDEBUG(D_DLMTRACE, "Lock %p already unused, calling callback (%p)\n",
1464                        lock, lock->l_blocking_ast);
1465                 if (lock->l_blocking_ast != NULL)
1466                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1467                                              LDLM_CB_BLOCKING);
1468         } else {
1469                 CDEBUG(D_DLMTRACE, "Lock %p is referenced, will be cancelled later\n",
1470                        lock);
1471         }
1472
1473         LDLM_DEBUG(lock, "client blocking callback handler END");
1474         LDLM_LOCK_RELEASE(lock);
1475         EXIT;
1476 }
1477
1478 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1479                                     struct ldlm_namespace *ns,
1480                                     struct ldlm_request *dlm_req,
1481                                     struct ldlm_lock *lock)
1482 {
1483         CFS_LIST_HEAD(ast_list);
1484         ENTRY;
1485
1486         LDLM_DEBUG(lock, "client completion callback handler START");
1487
1488         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1489                 int to = cfs_time_seconds(1);
1490                 while (to > 0) {
1491                         cfs_schedule_timeout_and_set_state(
1492                                 CFS_TASK_INTERRUPTIBLE, to);
1493                         if (lock->l_granted_mode == lock->l_req_mode ||
1494                             lock->l_destroyed)
1495                                 break;
1496                 }
1497         }
1498
1499         lock_res_and_lock(lock);
1500         if (lock->l_destroyed ||
1501             lock->l_granted_mode == lock->l_req_mode) {
1502                 /* bug 11300: the lock has already been granted */
1503                 unlock_res_and_lock(lock);
1504                 LDLM_DEBUG(lock, "Double grant race happened");
1505                 LDLM_LOCK_RELEASE(lock);
1506                 EXIT;
1507                 return;
1508         }
1509
1510         /* If we receive the completion AST before the actual enqueue returned,
1511          * then we might need to switch lock modes, resources, or extents. */
1512         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1513                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1514                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1515         }
1516
1517         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1518                 lock->l_policy_data = dlm_req->lock_desc.l_policy_data;
1519                 LDLM_DEBUG(lock, "completion AST, new policy data");
1520         }
1521
1522         ldlm_resource_unlink_lock(lock);
1523         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1524                    &lock->l_resource->lr_name,
1525                    sizeof(lock->l_resource->lr_name)) != 0) {
1526                 unlock_res_and_lock(lock);
1527                 if (ldlm_lock_change_resource(ns, lock,
1528                                 &dlm_req->lock_desc.l_resource.lr_name) != 0) {
1529                         LDLM_ERROR(lock, "Failed to allocate resource");
1530                         LDLM_LOCK_RELEASE(lock);
1531                         EXIT;
1532                         return;
1533                 }
1534                 LDLM_DEBUG(lock, "completion AST, new resource");
1535                 CERROR("change resource!\n");
1536                 lock_res_and_lock(lock);
1537         }
1538
1539         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1540                 /* BL_AST locks are not needed in lru.
1541                  * let ldlm_cancel_lru() be fast. */
1542                 ldlm_lock_remove_from_lru(lock);
1543                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1544                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1545         }
1546
1547         if (lock->l_lvb_len) {
1548                 if (req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB,
1549                                          RCL_CLIENT) < lock->l_lvb_len) {
1550                         LDLM_ERROR(lock, "completion AST did not contain "
1551                                    "expected LVB!");
1552                 } else {
1553                         void *lvb = req_capsule_client_get(&req->rq_pill,
1554                                                            &RMF_DLM_LVB);
1555                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1556                 }
1557         }
1558
1559         ldlm_grant_lock(lock, &ast_list);
1560         unlock_res_and_lock(lock);
1561
1562         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1563
1564         ldlm_run_ast_work(&ast_list, LDLM_WORK_CP_AST);
1565
1566         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1567                           lock);
1568         LDLM_LOCK_RELEASE(lock);
1569         EXIT;
1570 }
1571
1572 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1573                                     struct ldlm_namespace *ns,
1574                                     struct ldlm_request *dlm_req,
1575                                     struct ldlm_lock *lock)
1576 {
1577         int rc = -ENOSYS;
1578         ENTRY;
1579
1580         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1581
1582         if (lock->l_glimpse_ast != NULL)
1583                 rc = lock->l_glimpse_ast(lock, req);
1584
1585         if (req->rq_repmsg != NULL) {
1586                 ptlrpc_reply(req);
1587         } else {
1588                 req->rq_status = rc;
1589                 ptlrpc_error(req);
1590         }
1591
1592         lock_res_and_lock(lock);
1593         if (lock->l_granted_mode == LCK_PW &&
1594             !lock->l_readers && !lock->l_writers &&
1595             cfs_time_after(cfs_time_current(),
1596                            cfs_time_add(lock->l_last_used,
1597                                         cfs_time_seconds(10)))) {
1598                 unlock_res_and_lock(lock);
1599                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1600                         ldlm_handle_bl_callback(ns, NULL, lock);
1601
1602                 EXIT;
1603                 return;
1604         }
1605         unlock_res_and_lock(lock);
1606         LDLM_LOCK_RELEASE(lock);
1607         EXIT;
1608 }
1609
1610 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1611 {
1612         if (req->rq_no_reply)
1613                 return 0;
1614
1615         req->rq_status = rc;
1616         if (!req->rq_packed_final) {
1617                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1618                 if (rc)
1619                         return rc;
1620         }
1621         return ptlrpc_reply(req);
1622 }
1623
1624 #ifdef __KERNEL__
1625 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1626                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1627                              cfs_list_t *cancels, int count)
1628 {
1629         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1630         struct ldlm_bl_work_item *blwi;
1631         ENTRY;
1632
1633         if (cancels && count == 0)
1634                 RETURN(0);
1635
1636         OBD_ALLOC(blwi, sizeof(*blwi));
1637         if (blwi == NULL)
1638                 RETURN(-ENOMEM);
1639
1640         blwi->blwi_ns = ns;
1641         if (ld != NULL)
1642                 blwi->blwi_ld = *ld;
1643         if (count) {
1644                 cfs_list_add(&blwi->blwi_head, cancels);
1645                 cfs_list_del_init(cancels);
1646                 blwi->blwi_count = count;
1647         } else {
1648                 blwi->blwi_lock = lock;
1649         }
1650         cfs_spin_lock(&blp->blp_lock);
1651         if (lock && lock->l_flags & LDLM_FL_DISCARD_DATA) {
1652                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1653                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1654         } else {
1655                 /* other blocking callbacks are added to the regular list */
1656                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1657         }
1658         cfs_waitq_signal(&blp->blp_waitq);
1659         cfs_spin_unlock(&blp->blp_lock);
1660
1661         RETURN(0);
1662 }
1663 #endif
1664
1665 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1666                            struct ldlm_lock *lock)
1667 {
1668 #ifdef __KERNEL__
1669         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0));
1670 #else
1671         RETURN(-ENOSYS);
1672 #endif
1673 }
1674
1675 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1676                            cfs_list_t *cancels, int count)
1677 {
1678 #ifdef __KERNEL__
1679         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count));
1680 #else
1681         RETURN(-ENOSYS);
1682 #endif
1683 }
1684
1685 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
1686 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
1687 {
1688         struct obd_device *obd = req->rq_export->exp_obd;
1689         char *key;
1690         void *val;
1691         int keylen, vallen;
1692         int rc = -ENOSYS;
1693         ENTRY;
1694
1695         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
1696
1697         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
1698
1699         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
1700         if (key == NULL) {
1701                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
1702                 RETURN(-EFAULT);
1703         }
1704         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
1705                                       RCL_CLIENT);
1706         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
1707         if (val == NULL) {
1708                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
1709                 RETURN(-EFAULT);
1710         }
1711         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
1712                                       RCL_CLIENT);
1713
1714         /* We are responsible for swabbing contents of val */
1715
1716         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
1717                 /* Pass it on to mdc (the "export" in this case) */
1718                 rc = obd_set_info_async(req->rq_export,
1719                                         sizeof(KEY_HSM_COPYTOOL_SEND),
1720                                         KEY_HSM_COPYTOOL_SEND,
1721                                         vallen, val, NULL);
1722         else
1723                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
1724
1725         return rc;
1726 }
1727
1728 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
1729                                         const char *msg, int rc)
1730 {
1731         CWARN("%s: [pid %d] [xid x"LPU64"] [nid %s] [opc %d] [rc %d].\n",
1732               msg, lustre_msg_get_status(req->rq_reqmsg),
1733               req->rq_xid, libcfs_id2str(req->rq_peer),
1734               lustre_msg_get_opc(req->rq_reqmsg), rc);
1735         if (req->rq_no_reply)
1736                 CWARN("No reply was sent, maybe cause bug 21636.\n");
1737         else if (rc)
1738                 CWARN("Send reply failed, maybe cause bug 21636.\n");
1739 }
1740
1741 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
1742 static int ldlm_callback_handler(struct ptlrpc_request *req)
1743 {
1744         struct ldlm_namespace *ns;
1745         struct ldlm_request *dlm_req;
1746         struct ldlm_lock *lock;
1747         int rc;
1748         ENTRY;
1749
1750         /* Requests arrive in sender's byte order.  The ptlrpc service
1751          * handler has already checked and, if necessary, byte-swapped the
1752          * incoming request message body, but I am responsible for the
1753          * message buffers. */
1754
1755         /* do nothing for sec context finalize */
1756         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
1757                 RETURN(0);
1758
1759         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1760
1761         if (req->rq_export == NULL) {
1762                 rc = ldlm_callback_reply(req, -ENOTCONN);
1763                 ldlm_callback_errmsg(req, "Operate on unconnected server", rc);
1764                 RETURN(0);
1765         }
1766
1767         LASSERT(req->rq_export != NULL);
1768         LASSERT(req->rq_export->exp_obd != NULL);
1769
1770         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1771         case LDLM_BL_CALLBACK:
1772                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK))
1773                         RETURN(0);
1774                 break;
1775         case LDLM_CP_CALLBACK:
1776                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK))
1777                         RETURN(0);
1778                 break;
1779         case LDLM_GL_CALLBACK:
1780                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK))
1781                         RETURN(0);
1782                 break;
1783         case LDLM_SET_INFO:
1784                 rc = ldlm_handle_setinfo(req);
1785                 ldlm_callback_reply(req, rc);
1786                 RETURN(0);
1787         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1788                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
1789                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
1790                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
1791                         RETURN(0);
1792                 rc = llog_origin_handle_cancel(req);
1793                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
1794                         RETURN(0);
1795                 ldlm_callback_reply(req, rc);
1796                 RETURN(0);
1797         case OBD_QC_CALLBACK:
1798                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
1799                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
1800                         RETURN(0);
1801                 rc = target_handle_qc_callback(req);
1802                 ldlm_callback_reply(req, rc);
1803                 RETURN(0);
1804         case QUOTA_DQACQ:
1805         case QUOTA_DQREL:
1806                 /* reply in handler */
1807                 req_capsule_set(&req->rq_pill, &RQF_MDS_QUOTA_DQACQ);
1808                 rc = target_handle_dqacq_callback(req);
1809                 RETURN(0);
1810         case LLOG_ORIGIN_HANDLE_CREATE:
1811                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
1812                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1813                         RETURN(0);
1814                 rc = llog_origin_handle_create(req);
1815                 ldlm_callback_reply(req, rc);
1816                 RETURN(0);
1817         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1818                 req_capsule_set(&req->rq_pill,
1819                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
1820                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1821                         RETURN(0);
1822                 rc = llog_origin_handle_next_block(req);
1823                 ldlm_callback_reply(req, rc);
1824                 RETURN(0);
1825         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1826                 req_capsule_set(&req->rq_pill,
1827                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
1828                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1829                         RETURN(0);
1830                 rc = llog_origin_handle_read_header(req);
1831                 ldlm_callback_reply(req, rc);
1832                 RETURN(0);
1833         case LLOG_ORIGIN_HANDLE_CLOSE:
1834                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1835                         RETURN(0);
1836                 rc = llog_origin_handle_close(req);
1837                 ldlm_callback_reply(req, rc);
1838                 RETURN(0);
1839         default:
1840                 CERROR("unknown opcode %u\n",
1841                        lustre_msg_get_opc(req->rq_reqmsg));
1842                 ldlm_callback_reply(req, -EPROTO);
1843                 RETURN(0);
1844         }
1845
1846         ns = req->rq_export->exp_obd->obd_namespace;
1847         LASSERT(ns != NULL);
1848
1849         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1850
1851         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1852         if (dlm_req == NULL) {
1853                 rc = ldlm_callback_reply(req, -EPROTO);
1854                 ldlm_callback_errmsg(req, "Operate without parameter", rc);
1855                 RETURN(0);
1856         }
1857
1858         /* Force a known safe race, send a cancel to the server for a lock
1859          * which the server has already started a blocking callback on. */
1860         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
1861             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1862                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
1863                 if (rc < 0)
1864                         CERROR("ldlm_cli_cancel: %d\n", rc);
1865         }
1866
1867         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
1868         if (!lock) {
1869                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1870                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1871                 rc = ldlm_callback_reply(req, -EINVAL);
1872                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc);
1873                 RETURN(0);
1874         }
1875
1876         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
1877             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
1878                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
1879
1880         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1881         lock_res_and_lock(lock);
1882         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1883         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1884                 /* If somebody cancels lock and cache is already dropped,
1885                  * or lock is failed before cp_ast received on client,
1886                  * we can tell the server we have no lock. Otherwise, we
1887                  * should send cancel after dropping the cache. */
1888                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
1889                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
1890                     (lock->l_flags & LDLM_FL_FAILED)) {
1891                         LDLM_DEBUG(lock, "callback on lock "
1892                                    LPX64" - lock disappeared\n",
1893                                    dlm_req->lock_handle[0].cookie);
1894                         unlock_res_and_lock(lock);
1895                         LDLM_LOCK_RELEASE(lock);
1896                         rc = ldlm_callback_reply(req, -EINVAL);
1897                         ldlm_callback_errmsg(req, "Operate on stale lock", rc);
1898                         RETURN(0);
1899                 }
1900                 /* BL_AST locks are not needed in lru.
1901                  * let ldlm_cancel_lru() be fast. */
1902                 ldlm_lock_remove_from_lru(lock);
1903                 lock->l_flags |= LDLM_FL_BL_AST;
1904         }
1905         unlock_res_and_lock(lock);
1906
1907         /* We want the ost thread to get this reply so that it can respond
1908          * to ost requests (write cache writeback) that might be triggered
1909          * in the callback.
1910          *
1911          * But we'd also like to be able to indicate in the reply that we're
1912          * cancelling right now, because it's unused, or have an intent result
1913          * in the reply, so we might have to push the responsibility for sending
1914          * the reply down into the AST handlers, alas. */
1915
1916         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1917         case LDLM_BL_CALLBACK:
1918                 CDEBUG(D_INODE, "blocking ast\n");
1919                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
1920                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
1921                         rc = ldlm_callback_reply(req, 0);
1922                         if (req->rq_no_reply || rc)
1923                                 ldlm_callback_errmsg(req, "Normal process", rc);
1924                 }
1925                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
1926                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
1927                 break;
1928         case LDLM_CP_CALLBACK:
1929                 CDEBUG(D_INODE, "completion ast\n");
1930                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
1931                 ldlm_callback_reply(req, 0);
1932                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
1933                 break;
1934         case LDLM_GL_CALLBACK:
1935                 CDEBUG(D_INODE, "glimpse ast\n");
1936                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
1937                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
1938                 break;
1939         default:
1940                 LBUG();                         /* checked above */
1941         }
1942
1943         RETURN(0);
1944 }
1945
1946 static int ldlm_cancel_handler(struct ptlrpc_request *req)
1947 {
1948         int rc;
1949         ENTRY;
1950
1951         /* Requests arrive in sender's byte order.  The ptlrpc service
1952          * handler has already checked and, if necessary, byte-swapped the
1953          * incoming request message body, but I am responsible for the
1954          * message buffers. */
1955
1956         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1957
1958         if (req->rq_export == NULL) {
1959                 struct ldlm_request *dlm_req;
1960
1961                 CERROR("operation %d from %s with bad export cookie "LPU64"\n",
1962                        lustre_msg_get_opc(req->rq_reqmsg),
1963                        libcfs_id2str(req->rq_peer),
1964                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
1965
1966                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
1967                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1968                         dlm_req = req_capsule_client_get(&req->rq_pill,
1969                                                          &RMF_DLM_REQ);
1970                         if (dlm_req != NULL)
1971                                 ldlm_lock_dump_handle(D_ERROR,
1972                                                       &dlm_req->lock_handle[0]);
1973                 }
1974                 ldlm_callback_reply(req, -ENOTCONN);
1975                 RETURN(0);
1976         }
1977
1978         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1979
1980         /* XXX FIXME move this back to mds/handler.c, bug 249 */
1981         case LDLM_CANCEL:
1982                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
1983                 CDEBUG(D_INODE, "cancel\n");
1984                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL))
1985                         RETURN(0);
1986                 rc = ldlm_handle_cancel(req);
1987                 if (rc)
1988                         break;
1989                 RETURN(0);
1990         case OBD_LOG_CANCEL:
1991                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
1992                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
1993                         RETURN(0);
1994                 rc = llog_origin_handle_cancel(req);
1995                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
1996                         RETURN(0);
1997                 ldlm_callback_reply(req, rc);
1998                 RETURN(0);
1999         default:
2000                 CERROR("invalid opcode %d\n",
2001                        lustre_msg_get_opc(req->rq_reqmsg));
2002                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2003                 ldlm_callback_reply(req, -EINVAL);
2004         }
2005
2006         RETURN(0);
2007 }
2008
2009 void ldlm_revoke_lock_cb(void *obj, void *data)
2010 {
2011         cfs_list_t         *rpc_list = data;
2012         struct ldlm_lock   *lock = obj;
2013
2014         lock_res_and_lock(lock);
2015
2016         if (lock->l_req_mode != lock->l_granted_mode) {
2017                 unlock_res_and_lock(lock);
2018                 return;
2019         }
2020
2021         LASSERT(lock->l_resource);
2022         if (lock->l_resource->lr_type != LDLM_IBITS &&
2023             lock->l_resource->lr_type != LDLM_PLAIN) {
2024                 unlock_res_and_lock(lock);
2025                 return;
2026         }
2027
2028         if (lock->l_flags & LDLM_FL_AST_SENT) {
2029                 unlock_res_and_lock(lock);
2030                 return;
2031         }
2032
2033         LASSERT(lock->l_blocking_ast);
2034         LASSERT(!lock->l_blocking_lock);
2035
2036         lock->l_flags |= LDLM_FL_AST_SENT;
2037         if (lock->l_export && lock->l_export->exp_lock_hash &&
2038             !cfs_hlist_unhashed(&lock->l_exp_hash))
2039                 cfs_hash_del(lock->l_export->exp_lock_hash,
2040                              &lock->l_remote_handle, &lock->l_exp_hash);
2041         cfs_list_add_tail(&lock->l_rk_ast, rpc_list);
2042         LDLM_LOCK_GET(lock);
2043
2044         unlock_res_and_lock(lock);
2045 }
2046
2047 void ldlm_revoke_export_locks(struct obd_export *exp)
2048 {
2049         cfs_list_t  rpc_list;
2050         ENTRY;
2051
2052         CFS_INIT_LIST_HEAD(&rpc_list);
2053         cfs_hash_for_each_empty(exp->exp_lock_hash,
2054                                 ldlm_revoke_lock_cb, &rpc_list);
2055         ldlm_run_ast_work(&rpc_list, LDLM_WORK_REVOKE_AST);
2056
2057         EXIT;
2058 }
2059
2060 #ifdef __KERNEL__
2061 static struct ldlm_bl_work_item *ldlm_bl_get_work(struct ldlm_bl_pool *blp)
2062 {
2063         struct ldlm_bl_work_item *blwi = NULL;
2064         static unsigned int num_bl = 0;
2065
2066         cfs_spin_lock(&blp->blp_lock);
2067         /* process a request from the blp_list at least every blp_num_threads */
2068         if (!cfs_list_empty(&blp->blp_list) &&
2069             (cfs_list_empty(&blp->blp_prio_list) || num_bl == 0))
2070                 blwi = cfs_list_entry(blp->blp_list.next,
2071                                       struct ldlm_bl_work_item, blwi_entry);
2072         else
2073                 if (!cfs_list_empty(&blp->blp_prio_list))
2074                         blwi = cfs_list_entry(blp->blp_prio_list.next,
2075                                               struct ldlm_bl_work_item,
2076                                               blwi_entry);
2077
2078         if (blwi) {
2079                 if (++num_bl >= cfs_atomic_read(&blp->blp_num_threads))
2080                         num_bl = 0;
2081                 cfs_list_del(&blwi->blwi_entry);
2082         }
2083         cfs_spin_unlock(&blp->blp_lock);
2084
2085         return blwi;
2086 }
2087
2088 /* This only contains temporary data until the thread starts */
2089 struct ldlm_bl_thread_data {
2090         char                    bltd_name[CFS_CURPROC_COMM_MAX];
2091         struct ldlm_bl_pool     *bltd_blp;
2092         cfs_completion_t        bltd_comp;
2093         int                     bltd_num;
2094 };
2095
2096 static int ldlm_bl_thread_main(void *arg);
2097
2098 static int ldlm_bl_thread_start(struct ldlm_bl_pool *blp)
2099 {
2100         struct ldlm_bl_thread_data bltd = { .bltd_blp = blp };
2101         int rc;
2102
2103         cfs_init_completion(&bltd.bltd_comp);
2104         rc = cfs_kernel_thread(ldlm_bl_thread_main, &bltd, 0);
2105         if (rc < 0) {
2106                 CERROR("cannot start LDLM thread ldlm_bl_%02d: rc %d\n",
2107                        cfs_atomic_read(&blp->blp_num_threads), rc);
2108                 return rc;
2109         }
2110         cfs_wait_for_completion(&bltd.bltd_comp);
2111
2112         return 0;
2113 }
2114
2115 static int ldlm_bl_thread_main(void *arg)
2116 {
2117         struct ldlm_bl_pool *blp;
2118         ENTRY;
2119
2120         {
2121                 struct ldlm_bl_thread_data *bltd = arg;
2122
2123                 blp = bltd->bltd_blp;
2124
2125                 bltd->bltd_num =
2126                         cfs_atomic_inc_return(&blp->blp_num_threads) - 1;
2127                 cfs_atomic_inc(&blp->blp_busy_threads);
2128
2129                 snprintf(bltd->bltd_name, sizeof(bltd->bltd_name) - 1,
2130                         "ldlm_bl_%02d", bltd->bltd_num);
2131                 cfs_daemonize(bltd->bltd_name);
2132
2133                 cfs_complete(&bltd->bltd_comp);
2134                 /* cannot use bltd after this, it is only on caller's stack */
2135         }
2136
2137         while (1) {
2138                 struct l_wait_info lwi = { 0 };
2139                 struct ldlm_bl_work_item *blwi = NULL;
2140
2141                 blwi = ldlm_bl_get_work(blp);
2142
2143                 if (blwi == NULL) {
2144                         int busy;
2145
2146                         cfs_atomic_dec(&blp->blp_busy_threads);
2147                         l_wait_event_exclusive(blp->blp_waitq,
2148                                          (blwi = ldlm_bl_get_work(blp)) != NULL,
2149                                          &lwi);
2150                         busy = cfs_atomic_inc_return(&blp->blp_busy_threads);
2151
2152                         if (blwi->blwi_ns == NULL)
2153                                 /* added by ldlm_cleanup() */
2154                                 break;
2155
2156                         /* Not fatal if racy and have a few too many threads */
2157                         if (unlikely(busy < blp->blp_max_threads &&
2158                             busy >= cfs_atomic_read(&blp->blp_num_threads)))
2159                                 /* discard the return value, we tried */
2160                                 ldlm_bl_thread_start(blp);
2161                 } else {
2162                         if (blwi->blwi_ns == NULL)
2163                                 /* added by ldlm_cleanup() */
2164                                 break;
2165                 }
2166
2167                 if (blwi->blwi_count) {
2168                         /* The special case when we cancel locks in lru
2169                          * asynchronously, we pass the list of locks here.
2170                          * Thus lock is marked LDLM_FL_CANCELING, and already
2171                          * canceled locally. */
2172                         ldlm_cli_cancel_list(&blwi->blwi_head,
2173                                              blwi->blwi_count, NULL, 0);
2174                 } else {
2175                         ldlm_handle_bl_callback(blwi->blwi_ns, &blwi->blwi_ld,
2176                                                 blwi->blwi_lock);
2177                 }
2178                 OBD_FREE(blwi, sizeof(*blwi));
2179         }
2180
2181         cfs_atomic_dec(&blp->blp_busy_threads);
2182         cfs_atomic_dec(&blp->blp_num_threads);
2183         cfs_complete(&blp->blp_comp);
2184         RETURN(0);
2185 }
2186
2187 #endif
2188
2189 static int ldlm_setup(void);
2190 static int ldlm_cleanup(void);
2191
2192 int ldlm_get_ref(void)
2193 {
2194         int rc = 0;
2195         ENTRY;
2196         cfs_mutex_down(&ldlm_ref_sem);
2197         if (++ldlm_refcount == 1) {
2198                 rc = ldlm_setup();
2199                 if (rc)
2200                         ldlm_refcount--;
2201         }
2202         cfs_mutex_up(&ldlm_ref_sem);
2203
2204         RETURN(rc);
2205 }
2206
2207 void ldlm_put_ref(void)
2208 {
2209         ENTRY;
2210         cfs_mutex_down(&ldlm_ref_sem);
2211         if (ldlm_refcount == 1) {
2212                 int rc = ldlm_cleanup();
2213                 if (rc)
2214                         CERROR("ldlm_cleanup failed: %d\n", rc);
2215                 else
2216                         ldlm_refcount--;
2217         } else {
2218                 ldlm_refcount--;
2219         }
2220         cfs_mutex_up(&ldlm_ref_sem);
2221
2222         EXIT;
2223 }
2224
2225 /*
2226  * Export handle<->lock hash operations.
2227  */
2228 static unsigned
2229 ldlm_export_lock_hash(cfs_hash_t *hs, void *key, unsigned mask)
2230 {
2231         return cfs_hash_u64_hash(((struct lustre_handle *)key)->cookie, mask);
2232 }
2233
2234 static void *
2235 ldlm_export_lock_key(cfs_hlist_node_t *hnode)
2236 {
2237         struct ldlm_lock *lock;
2238         ENTRY;
2239
2240         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2241         RETURN(&lock->l_remote_handle);
2242 }
2243
2244 static int
2245 ldlm_export_lock_compare(void *key, cfs_hlist_node_t *hnode)
2246 {
2247         ENTRY;
2248         RETURN(lustre_handle_equal(ldlm_export_lock_key(hnode), key));
2249 }
2250
2251 static void *
2252 ldlm_export_lock_get(cfs_hlist_node_t *hnode)
2253 {
2254         struct ldlm_lock *lock;
2255         ENTRY;
2256
2257         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2258         LDLM_LOCK_GET(lock);
2259
2260         RETURN(lock);
2261 }
2262
2263 static void *
2264 ldlm_export_lock_put(cfs_hlist_node_t *hnode)
2265 {
2266         struct ldlm_lock *lock;
2267         ENTRY;
2268
2269         lock = cfs_hlist_entry(hnode, struct ldlm_lock, l_exp_hash);
2270         LDLM_LOCK_RELEASE(lock);
2271
2272         RETURN(lock);
2273 }
2274
2275 static cfs_hash_ops_t ldlm_export_lock_ops = {
2276         .hs_hash    = ldlm_export_lock_hash,
2277         .hs_key     = ldlm_export_lock_key,
2278         .hs_compare = ldlm_export_lock_compare,
2279         .hs_get     = ldlm_export_lock_get,
2280         .hs_put     = ldlm_export_lock_put
2281 };
2282
2283 int ldlm_init_export(struct obd_export *exp)
2284 {
2285         ENTRY;
2286
2287         exp->exp_lock_hash =
2288                 cfs_hash_create(obd_uuid2str(&exp->exp_client_uuid),
2289                                 HASH_EXP_LOCK_CUR_BITS, HASH_EXP_LOCK_MAX_BITS,
2290                                 &ldlm_export_lock_ops, CFS_HASH_REHASH);
2291
2292         if (!exp->exp_lock_hash)
2293                 RETURN(-ENOMEM);
2294
2295         RETURN(0);
2296 }
2297 EXPORT_SYMBOL(ldlm_init_export);
2298
2299 void ldlm_destroy_export(struct obd_export *exp)
2300 {
2301         ENTRY;
2302         cfs_hash_putref(exp->exp_lock_hash);
2303         exp->exp_lock_hash = NULL;
2304         EXIT;
2305 }
2306 EXPORT_SYMBOL(ldlm_destroy_export);
2307
2308 static int ldlm_setup(void)
2309 {
2310         struct ldlm_bl_pool *blp;
2311         int rc = 0;
2312         int ldlm_min_threads = LDLM_THREADS_AUTO_MIN;
2313         int ldlm_max_threads = LDLM_THREADS_AUTO_MAX;
2314 #ifdef __KERNEL__
2315         int i;
2316 #endif
2317         ENTRY;
2318
2319         if (ldlm_state != NULL)
2320                 RETURN(-EALREADY);
2321
2322         OBD_ALLOC(ldlm_state, sizeof(*ldlm_state));
2323         if (ldlm_state == NULL)
2324                 RETURN(-ENOMEM);
2325
2326 #ifdef LPROCFS
2327         rc = ldlm_proc_setup();
2328         if (rc != 0)
2329                 GOTO(out_free, rc);
2330 #endif
2331
2332 #ifdef __KERNEL__
2333         if (ldlm_num_threads) {
2334                 /* If ldlm_num_threads is set, it is the min and the max. */
2335                 if (ldlm_num_threads > LDLM_THREADS_AUTO_MAX)
2336                         ldlm_num_threads = LDLM_THREADS_AUTO_MAX;
2337                 if (ldlm_num_threads < LDLM_THREADS_AUTO_MIN)
2338                         ldlm_num_threads = LDLM_THREADS_AUTO_MIN;
2339                 ldlm_min_threads = ldlm_max_threads = ldlm_num_threads;
2340         }
2341 #endif
2342
2343         ldlm_state->ldlm_cb_service =
2344                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2345                                 LDLM_MAXREPSIZE, LDLM_CB_REQUEST_PORTAL,
2346                                 LDLM_CB_REPLY_PORTAL, 2,
2347                                 ldlm_callback_handler, "ldlm_cbd",
2348                                 ldlm_svc_proc_dir, NULL,
2349                                 ldlm_min_threads, ldlm_max_threads,
2350                                 "ldlm_cb",
2351                                 LCT_MD_THREAD|LCT_DT_THREAD, NULL);
2352
2353         if (!ldlm_state->ldlm_cb_service) {
2354                 CERROR("failed to start service\n");
2355                 GOTO(out_proc, rc = -ENOMEM);
2356         }
2357
2358         ldlm_state->ldlm_cancel_service =
2359                 ptlrpc_init_svc(LDLM_NBUFS, LDLM_BUFSIZE, LDLM_MAXREQSIZE,
2360                                 LDLM_MAXREPSIZE, LDLM_CANCEL_REQUEST_PORTAL,
2361                                 LDLM_CANCEL_REPLY_PORTAL, 6,
2362                                 ldlm_cancel_handler, "ldlm_canceld",
2363                                 ldlm_svc_proc_dir, NULL,
2364                                 ldlm_min_threads, ldlm_max_threads,
2365                                 "ldlm_cn",
2366                                 LCT_MD_THREAD|LCT_DT_THREAD|LCT_CL_THREAD,
2367                                 NULL);
2368
2369         if (!ldlm_state->ldlm_cancel_service) {
2370                 CERROR("failed to start service\n");
2371                 GOTO(out_proc, rc = -ENOMEM);
2372         }
2373
2374         OBD_ALLOC(blp, sizeof(*blp));
2375         if (blp == NULL)
2376                 GOTO(out_proc, rc = -ENOMEM);
2377         ldlm_state->ldlm_bl_pool = blp;
2378
2379         cfs_spin_lock_init(&blp->blp_lock);
2380         CFS_INIT_LIST_HEAD(&blp->blp_list);
2381         CFS_INIT_LIST_HEAD(&blp->blp_prio_list);
2382         cfs_waitq_init(&blp->blp_waitq);
2383         cfs_atomic_set(&blp->blp_num_threads, 0);
2384         cfs_atomic_set(&blp->blp_busy_threads, 0);
2385         blp->blp_min_threads = ldlm_min_threads;
2386         blp->blp_max_threads = ldlm_max_threads;
2387
2388 #ifdef __KERNEL__
2389         for (i = 0; i < blp->blp_min_threads; i++) {
2390                 rc = ldlm_bl_thread_start(blp);
2391                 if (rc < 0)
2392                         GOTO(out_thread, rc);
2393         }
2394
2395         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cancel_service);
2396         if (rc)
2397                 GOTO(out_thread, rc);
2398
2399         rc = ptlrpc_start_threads(NULL, ldlm_state->ldlm_cb_service);
2400         if (rc)
2401                 GOTO(out_thread, rc);
2402
2403         CFS_INIT_LIST_HEAD(&expired_lock_thread.elt_expired_locks);
2404         expired_lock_thread.elt_state = ELT_STOPPED;
2405         cfs_waitq_init(&expired_lock_thread.elt_waitq);
2406
2407         CFS_INIT_LIST_HEAD(&waiting_locks_list);
2408         cfs_spin_lock_init(&waiting_locks_spinlock);
2409         cfs_timer_init(&waiting_locks_timer, waiting_locks_callback, 0);
2410
2411         rc = cfs_kernel_thread(expired_lock_main, NULL, CLONE_VM | CLONE_FILES);
2412         if (rc < 0) {
2413                 CERROR("Cannot start ldlm expired-lock thread: %d\n", rc);
2414                 GOTO(out_thread, rc);
2415         }
2416
2417         cfs_wait_event(expired_lock_thread.elt_waitq,
2418                        expired_lock_thread.elt_state == ELT_READY);
2419 #endif
2420
2421 #ifdef __KERNEL__
2422         rc = ldlm_pools_init();
2423         if (rc)
2424                 GOTO(out_thread, rc);
2425 #endif
2426         RETURN(0);
2427
2428 #ifdef __KERNEL__
2429  out_thread:
2430         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2431         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2432 #endif
2433
2434  out_proc:
2435 #ifdef LPROCFS
2436         ldlm_proc_cleanup();
2437  out_free:
2438 #endif
2439         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2440         ldlm_state = NULL;
2441         return rc;
2442 }
2443
2444 static int ldlm_cleanup(void)
2445 {
2446 #ifdef __KERNEL__
2447         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
2448 #endif
2449         ENTRY;
2450
2451         if (!cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_SERVER)) ||
2452             !cfs_list_empty(ldlm_namespace_list(LDLM_NAMESPACE_CLIENT))) {
2453                 CERROR("ldlm still has namespaces; clean these up first.\n");
2454                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_SERVER, D_DLMTRACE);
2455                 ldlm_dump_all_namespaces(LDLM_NAMESPACE_CLIENT, D_DLMTRACE);
2456                 RETURN(-EBUSY);
2457         }
2458
2459 #ifdef __KERNEL__
2460         ldlm_pools_fini();
2461 #endif
2462
2463 #ifdef __KERNEL__
2464         while (cfs_atomic_read(&blp->blp_num_threads) > 0) {
2465                 struct ldlm_bl_work_item blwi = { .blwi_ns = NULL };
2466
2467                 cfs_init_completion(&blp->blp_comp);
2468
2469                 cfs_spin_lock(&blp->blp_lock);
2470                 cfs_list_add_tail(&blwi.blwi_entry, &blp->blp_list);
2471                 cfs_waitq_signal(&blp->blp_waitq);
2472                 cfs_spin_unlock(&blp->blp_lock);
2473
2474                 cfs_wait_for_completion(&blp->blp_comp);
2475         }
2476         OBD_FREE(blp, sizeof(*blp));
2477
2478         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2479         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2480         ldlm_proc_cleanup();
2481
2482         expired_lock_thread.elt_state = ELT_TERMINATE;
2483         cfs_waitq_signal(&expired_lock_thread.elt_waitq);
2484         cfs_wait_event(expired_lock_thread.elt_waitq,
2485                        expired_lock_thread.elt_state == ELT_STOPPED);
2486 #else
2487         ptlrpc_unregister_service(ldlm_state->ldlm_cb_service);
2488         ptlrpc_unregister_service(ldlm_state->ldlm_cancel_service);
2489 #endif
2490
2491         OBD_FREE(ldlm_state, sizeof(*ldlm_state));
2492         ldlm_state = NULL;
2493
2494         RETURN(0);
2495 }
2496
2497 int __init ldlm_init(void)
2498 {
2499         cfs_init_mutex(&ldlm_ref_sem);
2500         cfs_init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_SERVER));
2501         cfs_init_mutex(ldlm_namespace_lock(LDLM_NAMESPACE_CLIENT));
2502         ldlm_resource_slab = cfs_mem_cache_create("ldlm_resources",
2503                                                sizeof(struct ldlm_resource), 0,
2504                                                CFS_SLAB_HWCACHE_ALIGN);
2505         if (ldlm_resource_slab == NULL)
2506                 return -ENOMEM;
2507
2508         ldlm_lock_slab = cfs_mem_cache_create("ldlm_locks",
2509                               sizeof(struct ldlm_lock), 0,
2510                               CFS_SLAB_HWCACHE_ALIGN | CFS_SLAB_DESTROY_BY_RCU);
2511         if (ldlm_lock_slab == NULL) {
2512                 cfs_mem_cache_destroy(ldlm_resource_slab);
2513                 return -ENOMEM;
2514         }
2515
2516         ldlm_interval_slab = cfs_mem_cache_create("interval_node",
2517                                         sizeof(struct ldlm_interval),
2518                                         0, CFS_SLAB_HWCACHE_ALIGN);
2519         if (ldlm_interval_slab == NULL) {
2520                 cfs_mem_cache_destroy(ldlm_resource_slab);
2521                 cfs_mem_cache_destroy(ldlm_lock_slab);
2522                 return -ENOMEM;
2523         }
2524 #if LUSTRE_TRACKS_LOCK_EXP_REFS
2525         class_export_dump_hook = ldlm_dump_export_locks;
2526 #endif
2527         return 0;
2528 }
2529
2530 void __exit ldlm_exit(void)
2531 {
2532         int rc;
2533         if (ldlm_refcount)
2534                 CERROR("ldlm_refcount is %d in ldlm_exit!\n", ldlm_refcount);
2535         rc = cfs_mem_cache_destroy(ldlm_resource_slab);
2536         LASSERTF(rc == 0, "couldn't free ldlm resource slab\n");
2537 #ifdef __KERNEL__
2538         /* ldlm_lock_put() use RCU to call ldlm_lock_free, so need call
2539          * synchronize_rcu() to wait a grace period elapsed, so that
2540          * ldlm_lock_free() get a chance to be called. */
2541         synchronize_rcu();
2542 #endif
2543         rc = cfs_mem_cache_destroy(ldlm_lock_slab);
2544         LASSERTF(rc == 0, "couldn't free ldlm lock slab\n");
2545         rc = cfs_mem_cache_destroy(ldlm_interval_slab);
2546         LASSERTF(rc == 0, "couldn't free interval node slab\n");
2547 }
2548
2549 /* ldlm_extent.c */
2550 EXPORT_SYMBOL(ldlm_extent_shift_kms);
2551
2552 /* ldlm_lock.c */
2553 EXPORT_SYMBOL(ldlm_get_processing_policy);
2554 EXPORT_SYMBOL(ldlm_lock2desc);
2555 EXPORT_SYMBOL(ldlm_register_intent);
2556 EXPORT_SYMBOL(ldlm_lockname);
2557 EXPORT_SYMBOL(ldlm_typename);
2558 EXPORT_SYMBOL(ldlm_lock2handle);
2559 EXPORT_SYMBOL(__ldlm_handle2lock);
2560 EXPORT_SYMBOL(ldlm_lock_get);
2561 EXPORT_SYMBOL(ldlm_lock_put);
2562 EXPORT_SYMBOL(ldlm_lock_match);
2563 EXPORT_SYMBOL(ldlm_lock_cancel);
2564 EXPORT_SYMBOL(ldlm_lock_addref);
2565 EXPORT_SYMBOL(ldlm_lock_addref_try);
2566 EXPORT_SYMBOL(ldlm_lock_decref);
2567 EXPORT_SYMBOL(ldlm_lock_decref_and_cancel);
2568 EXPORT_SYMBOL(ldlm_lock_change_resource);
2569 EXPORT_SYMBOL(ldlm_it2str);
2570 EXPORT_SYMBOL(ldlm_lock_dump);
2571 EXPORT_SYMBOL(ldlm_lock_dump_handle);
2572 EXPORT_SYMBOL(ldlm_reprocess_all_ns);
2573 EXPORT_SYMBOL(ldlm_lock_allow_match_locked);
2574 EXPORT_SYMBOL(ldlm_lock_allow_match);
2575 EXPORT_SYMBOL(ldlm_lock_downgrade);
2576 EXPORT_SYMBOL(ldlm_lock_convert);
2577
2578 /* ldlm_request.c */
2579 EXPORT_SYMBOL(ldlm_completion_ast_async);
2580 EXPORT_SYMBOL(ldlm_blocking_ast_nocheck);
2581 EXPORT_SYMBOL(ldlm_completion_ast);
2582 EXPORT_SYMBOL(ldlm_blocking_ast);
2583 EXPORT_SYMBOL(ldlm_glimpse_ast);
2584 EXPORT_SYMBOL(ldlm_expired_completion_wait);
2585 EXPORT_SYMBOL(ldlm_prep_enqueue_req);
2586 EXPORT_SYMBOL(ldlm_prep_elc_req);
2587 EXPORT_SYMBOL(ldlm_cli_convert);
2588 EXPORT_SYMBOL(ldlm_cli_enqueue);
2589 EXPORT_SYMBOL(ldlm_cli_enqueue_fini);
2590 EXPORT_SYMBOL(ldlm_cli_enqueue_local);
2591 EXPORT_SYMBOL(ldlm_cli_cancel);
2592 EXPORT_SYMBOL(ldlm_cli_cancel_unused);
2593 EXPORT_SYMBOL(ldlm_cli_cancel_unused_resource);
2594 EXPORT_SYMBOL(ldlm_cli_cancel_req);
2595 EXPORT_SYMBOL(ldlm_replay_locks);
2596 EXPORT_SYMBOL(ldlm_resource_foreach);
2597 EXPORT_SYMBOL(ldlm_namespace_foreach);
2598 EXPORT_SYMBOL(ldlm_namespace_foreach_res);
2599 EXPORT_SYMBOL(ldlm_resource_iterate);
2600 EXPORT_SYMBOL(ldlm_cancel_resource_local);
2601 EXPORT_SYMBOL(ldlm_cli_cancel_list);
2602
2603 /* ldlm_lockd.c */
2604 EXPORT_SYMBOL(ldlm_server_blocking_ast);
2605 EXPORT_SYMBOL(ldlm_server_completion_ast);
2606 EXPORT_SYMBOL(ldlm_server_glimpse_ast);
2607 EXPORT_SYMBOL(ldlm_handle_enqueue);
2608 EXPORT_SYMBOL(ldlm_handle_enqueue0);
2609 EXPORT_SYMBOL(ldlm_handle_cancel);
2610 EXPORT_SYMBOL(ldlm_request_cancel);
2611 EXPORT_SYMBOL(ldlm_handle_convert);
2612 EXPORT_SYMBOL(ldlm_handle_convert0);
2613 EXPORT_SYMBOL(ldlm_del_waiting_lock);
2614 EXPORT_SYMBOL(ldlm_get_ref);
2615 EXPORT_SYMBOL(ldlm_put_ref);
2616 EXPORT_SYMBOL(ldlm_refresh_waiting_lock);
2617 EXPORT_SYMBOL(ldlm_revoke_export_locks);
2618
2619 /* ldlm_resource.c */
2620 EXPORT_SYMBOL(ldlm_namespace_new);
2621 EXPORT_SYMBOL(ldlm_namespace_cleanup);
2622 EXPORT_SYMBOL(ldlm_namespace_free);
2623 EXPORT_SYMBOL(ldlm_namespace_dump);
2624 EXPORT_SYMBOL(ldlm_dump_all_namespaces);
2625 EXPORT_SYMBOL(ldlm_resource_get);
2626 EXPORT_SYMBOL(ldlm_resource_putref);
2627 EXPORT_SYMBOL(ldlm_resource_unlink_lock);
2628
2629 /* ldlm_lib.c */
2630 EXPORT_SYMBOL(client_import_add_conn);
2631 EXPORT_SYMBOL(client_import_del_conn);
2632 EXPORT_SYMBOL(client_obd_setup);
2633 EXPORT_SYMBOL(client_obd_cleanup);
2634 EXPORT_SYMBOL(client_connect_import);
2635 EXPORT_SYMBOL(client_disconnect_export);
2636 EXPORT_SYMBOL(server_disconnect_export);
2637 EXPORT_SYMBOL(target_stop_recovery_thread);
2638 EXPORT_SYMBOL(target_handle_connect);
2639 EXPORT_SYMBOL(target_cleanup_recovery);
2640 EXPORT_SYMBOL(target_destroy_export);
2641 EXPORT_SYMBOL(target_cancel_recovery_timer);
2642 EXPORT_SYMBOL(target_send_reply);
2643 EXPORT_SYMBOL(target_queue_recovery_request);
2644 EXPORT_SYMBOL(target_handle_ping);
2645 EXPORT_SYMBOL(target_pack_pool_reply);
2646 EXPORT_SYMBOL(target_handle_disconnect);
2647
2648 /* l_lock.c */
2649 EXPORT_SYMBOL(lock_res_and_lock);
2650 EXPORT_SYMBOL(unlock_res_and_lock);