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