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