Whamcloud - gitweb
LU-569: Make lu_object cache size adjustable
[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_cb_set_arg *arg = ca->ca_set_arg;
654         struct ldlm_lock *lock = ca->ca_lock;
655         ENTRY;
656
657         LASSERT(lock != NULL);
658         if (rc != 0) {
659                 rc = ldlm_handle_ast_error(lock, req, rc,
660                                            arg->type == LDLM_BL_CALLBACK
661                                            ? "blocking" : "completion");
662         }
663
664         LDLM_LOCK_RELEASE(lock);
665
666         if (rc == -ERESTART)
667                 cfs_atomic_set(&arg->restart, 1);
668
669         RETURN(0);
670 }
671
672 static inline int ldlm_bl_and_cp_ast_fini(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                         /* If we cancelled the lock, we need to restart
685                          * ldlm_reprocess_queue */
686                         cfs_atomic_set(&arg->restart, 1);
687         } else {
688                 LDLM_LOCK_GET(lock);
689                 ptlrpc_set_add_req(arg->set, req);
690         }
691
692         RETURN(rc);
693 }
694
695 /**
696  * Check if there are requests in the export request list which prevent
697  * the lock canceling and make these requests high priority ones.
698  */
699 static void ldlm_lock_reorder_req(struct ldlm_lock *lock)
700 {
701         struct ptlrpc_request *req;
702         ENTRY;
703
704         if (lock->l_export == NULL) {
705                 LDLM_DEBUG(lock, "client lock: no-op");
706                 RETURN_EXIT;
707         }
708
709         cfs_spin_lock_bh(&lock->l_export->exp_rpc_lock);
710         cfs_list_for_each_entry(req, &lock->l_export->exp_queued_rpc,
711                                 rq_exp_list) {
712                 if (!req->rq_hp && req->rq_ops->hpreq_lock_match &&
713                     req->rq_ops->hpreq_lock_match(req, lock))
714                         ptlrpc_hpreq_reorder(req);
715         }
716         cfs_spin_unlock_bh(&lock->l_export->exp_rpc_lock);
717         EXIT;
718 }
719
720 /*
721  * ->l_blocking_ast() method for server-side locks. This is invoked when newly
722  * enqueued server lock conflicts with given one.
723  *
724  * Sends blocking ast rpc to the client owning that lock; arms timeout timer
725  * to wait for client response.
726  */
727 int ldlm_server_blocking_ast(struct ldlm_lock *lock,
728                              struct ldlm_lock_desc *desc,
729                              void *data, int flag)
730 {
731         struct ldlm_cb_async_args *ca;
732         struct ldlm_cb_set_arg *arg = data;
733         struct ldlm_request    *body;
734         struct ptlrpc_request  *req;
735         int                     instant_cancel = 0;
736         int                     rc = 0;
737         ENTRY;
738
739         if (flag == LDLM_CB_CANCELING)
740                 /* Don't need to do anything here. */
741                 RETURN(0);
742
743         LASSERT(lock);
744         LASSERT(data != NULL);
745         if (lock->l_export->exp_obd->obd_recovering != 0) {
746                 LDLM_ERROR(lock, "BUG 6063: lock collide during recovery");
747                 ldlm_lock_dump(D_ERROR, lock, 0);
748         }
749
750         ldlm_lock_reorder_req(lock);
751
752         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
753                                         &RQF_LDLM_BL_CALLBACK,
754                                         LUSTRE_DLM_VERSION, LDLM_BL_CALLBACK);
755         if (req == NULL)
756                 RETURN(-ENOMEM);
757
758         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
759         ca = ptlrpc_req_async_args(req);
760         ca->ca_set_arg = arg;
761         ca->ca_lock = lock;
762
763         req->rq_interpret_reply = ldlm_cb_interpret;
764         req->rq_no_resend = 1;
765
766         lock_res(lock->l_resource);
767         if (lock->l_granted_mode != lock->l_req_mode) {
768                 /* this blocking AST will be communicated as part of the
769                  * completion AST instead */
770                 unlock_res(lock->l_resource);
771                 ptlrpc_req_finished(req);
772                 LDLM_DEBUG(lock, "lock not granted, not sending blocking AST");
773                 RETURN(0);
774         }
775
776         if (lock->l_destroyed) {
777                 /* What's the point? */
778                 unlock_res(lock->l_resource);
779                 ptlrpc_req_finished(req);
780                 RETURN(0);
781         }
782
783         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
784                 instant_cancel = 1;
785
786         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
787         body->lock_handle[0] = lock->l_remote_handle;
788         body->lock_desc = *desc;
789         body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
790
791         LDLM_DEBUG(lock, "server preparing blocking AST");
792
793         ptlrpc_request_set_replen(req);
794         if (instant_cancel) {
795                 unlock_res(lock->l_resource);
796                 ldlm_lock_cancel(lock);
797         } else {
798                 LASSERT(lock->l_granted_mode == lock->l_req_mode);
799                 ldlm_add_waiting_lock(lock);
800                 unlock_res(lock->l_resource);
801         }
802
803         req->rq_send_state = LUSTRE_IMP_FULL;
804         /* ptlrpc_request_alloc_pack already set timeout */
805         if (AT_OFF)
806                 req->rq_timeout = ldlm_get_rq_timeout();
807
808         if (lock->l_export && lock->l_export->exp_nid_stats &&
809             lock->l_export->exp_nid_stats->nid_ldlm_stats)
810                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
811                                      LDLM_BL_CALLBACK - LDLM_FIRST_OPC);
812
813         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
814
815         RETURN(rc);
816 }
817
818 int ldlm_server_completion_ast(struct ldlm_lock *lock, int flags, void *data)
819 {
820         struct ldlm_cb_set_arg *arg = data;
821         struct ldlm_request    *body;
822         struct ptlrpc_request  *req;
823         struct ldlm_cb_async_args *ca;
824         long                    total_enqueue_wait;
825         int                     instant_cancel = 0;
826         int                     rc = 0;
827         ENTRY;
828
829         LASSERT(lock != NULL);
830         LASSERT(data != NULL);
831
832         total_enqueue_wait = cfs_time_sub(cfs_time_current_sec(),
833                                           lock->l_last_activity);
834
835         req = ptlrpc_request_alloc(lock->l_export->exp_imp_reverse,
836                                     &RQF_LDLM_CP_CALLBACK);
837         if (req == NULL)
838                 RETURN(-ENOMEM);
839
840         /* server namespace, doesn't need lock */
841         if (lock->l_resource->lr_lvb_len) {
842                  req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_CLIENT,
843                                       lock->l_resource->lr_lvb_len);
844         }
845
846         rc = ptlrpc_request_pack(req, LUSTRE_DLM_VERSION, LDLM_CP_CALLBACK);
847         if (rc) {
848                 ptlrpc_request_free(req);
849                 RETURN(rc);
850         }
851
852         CLASSERT(sizeof(*ca) <= sizeof(req->rq_async_args));
853         ca = ptlrpc_req_async_args(req);
854         ca->ca_set_arg = arg;
855         ca->ca_lock = lock;
856
857         req->rq_interpret_reply = ldlm_cb_interpret;
858         req->rq_no_resend = 1;
859         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
860
861         body->lock_handle[0] = lock->l_remote_handle;
862         body->lock_flags = flags;
863         ldlm_lock2desc(lock, &body->lock_desc);
864         if (lock->l_resource->lr_lvb_len) {
865                 void *lvb = req_capsule_client_get(&req->rq_pill, &RMF_DLM_LVB);
866
867                 lock_res(lock->l_resource);
868                 memcpy(lvb, lock->l_resource->lr_lvb_data,
869                        lock->l_resource->lr_lvb_len);
870                 unlock_res(lock->l_resource);
871         }
872
873         LDLM_DEBUG(lock, "server preparing completion AST (after %lds wait)",
874                    total_enqueue_wait);
875
876         /* Server-side enqueue wait time estimate, used in
877             __ldlm_add_waiting_lock to set future enqueue timers */
878         if (total_enqueue_wait < ldlm_get_enq_timeout(lock))
879                 at_measured(ldlm_lock_to_ns_at(lock),
880                             total_enqueue_wait);
881         else
882                 /* bz18618. Don't add lock enqueue time we spend waiting for a
883                    previous callback to fail. Locks waiting legitimately will
884                    get extended by ldlm_refresh_waiting_lock regardless of the
885                    estimate, so it's okay to underestimate here. */
886                 LDLM_DEBUG(lock, "lock completed after %lus; estimate was %ds. "
887                        "It is likely that a previous callback timed out.",
888                        total_enqueue_wait,
889                        at_get(ldlm_lock_to_ns_at(lock)));
890
891         ptlrpc_request_set_replen(req);
892
893         req->rq_send_state = LUSTRE_IMP_FULL;
894         /* ptlrpc_request_pack already set timeout */
895         if (AT_OFF)
896                 req->rq_timeout = ldlm_get_rq_timeout();
897
898         /* We only send real blocking ASTs after the lock is granted */
899         lock_res_and_lock(lock);
900         if (lock->l_flags & LDLM_FL_AST_SENT) {
901                 body->lock_flags |= LDLM_FL_AST_SENT;
902                 /* copy ast flags like LDLM_FL_DISCARD_DATA */
903                 body->lock_flags |= (lock->l_flags & LDLM_AST_FLAGS);
904
905                 /* We might get here prior to ldlm_handle_enqueue setting
906                  * LDLM_FL_CANCEL_ON_BLOCK flag. Then we will put this lock
907                  * into waiting list, but this is safe and similar code in
908                  * ldlm_handle_enqueue will call ldlm_lock_cancel() still,
909                  * that would not only cancel the lock, but will also remove
910                  * it from waiting list */
911                 if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) {
912                         unlock_res_and_lock(lock);
913                         ldlm_lock_cancel(lock);
914                         instant_cancel = 1;
915                         lock_res_and_lock(lock);
916                 } else {
917                         /* start the lock-timeout clock */
918                         ldlm_add_waiting_lock(lock);
919                 }
920         }
921         unlock_res_and_lock(lock);
922
923         if (lock->l_export && lock->l_export->exp_nid_stats &&
924             lock->l_export->exp_nid_stats->nid_ldlm_stats)
925                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
926                                      LDLM_CP_CALLBACK - LDLM_FIRST_OPC);
927
928         rc = ldlm_bl_and_cp_ast_fini(req, arg, lock, instant_cancel);
929
930         RETURN(rc);
931 }
932
933 int ldlm_server_glimpse_ast(struct ldlm_lock *lock, void *data)
934 {
935         struct ldlm_resource  *res = lock->l_resource;
936         struct ldlm_request   *body;
937         struct ptlrpc_request *req;
938         int                    rc;
939         ENTRY;
940
941         LASSERT(lock != NULL);
942
943         req = ptlrpc_request_alloc_pack(lock->l_export->exp_imp_reverse,
944                                         &RQF_LDLM_GL_CALLBACK,
945                                         LUSTRE_DLM_VERSION, LDLM_GL_CALLBACK);
946
947         if (req == NULL)
948                 RETURN(-ENOMEM);
949
950         body = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
951         body->lock_handle[0] = lock->l_remote_handle;
952         ldlm_lock2desc(lock, &body->lock_desc);
953
954         /* server namespace, doesn't need lock */
955         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER,
956                              lock->l_resource->lr_lvb_len);
957         res = lock->l_resource;
958         ptlrpc_request_set_replen(req);
959
960
961         req->rq_send_state = LUSTRE_IMP_FULL;
962         /* ptlrpc_request_alloc_pack already set timeout */
963         if (AT_OFF)
964                 req->rq_timeout = ldlm_get_rq_timeout();
965
966         if (lock->l_export && lock->l_export->exp_nid_stats &&
967             lock->l_export->exp_nid_stats->nid_ldlm_stats)
968                 lprocfs_counter_incr(lock->l_export->exp_nid_stats->nid_ldlm_stats,
969                                      LDLM_GL_CALLBACK - LDLM_FIRST_OPC);
970
971         rc = ptlrpc_queue_wait(req);
972         /* Update the LVB from disk if the AST failed (this is a legal race)
973          *
974          * - Glimpse callback of local lock just return -ELDLM_NO_LOCK_DATA.
975          * - Glimpse callback of remote lock might return -ELDLM_NO_LOCK_DATA
976          *   when inode is cleared. LU-274
977          */
978         if (rc == -ELDLM_NO_LOCK_DATA) {
979                 LDLM_DEBUG(lock, "lost race - client has a lock but no inode");
980                 ldlm_res_lvbo_update(res, NULL, 1);
981         } else if (rc != 0) {
982                 rc = ldlm_handle_ast_error(lock, req, rc, "glimpse");
983         } else {
984                 rc = ldlm_res_lvbo_update(res, req, 1);
985         }
986
987         ptlrpc_req_finished(req);
988         if (rc == -ERESTART)
989                 ldlm_reprocess_all(res);
990
991         RETURN(rc);
992 }
993
994 #ifdef __KERNEL__
995 extern unsigned long long lu_time_stamp_get(void);
996 #else
997 #define lu_time_stamp_get() time(NULL)
998 #endif
999
1000 static void ldlm_svc_get_eopc(const struct ldlm_request *dlm_req,
1001                        struct lprocfs_stats *srv_stats)
1002 {
1003         int lock_type = 0, op = 0;
1004
1005         lock_type = dlm_req->lock_desc.l_resource.lr_type;
1006
1007         switch (lock_type) {
1008         case LDLM_PLAIN:
1009                 op = PTLRPC_LAST_CNTR + LDLM_PLAIN_ENQUEUE;
1010                 break;
1011         case LDLM_EXTENT:
1012                 if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT)
1013                         op = PTLRPC_LAST_CNTR + LDLM_GLIMPSE_ENQUEUE;
1014                 else
1015                         op = PTLRPC_LAST_CNTR + LDLM_EXTENT_ENQUEUE;
1016                 break;
1017         case LDLM_FLOCK:
1018                 op = PTLRPC_LAST_CNTR + LDLM_FLOCK_ENQUEUE;
1019                 break;
1020         case LDLM_IBITS:
1021                 op = PTLRPC_LAST_CNTR + LDLM_IBITS_ENQUEUE;
1022                 break;
1023         default:
1024                 op = 0;
1025                 break;
1026         }
1027
1028         if (op)
1029                 lprocfs_counter_incr(srv_stats, op);
1030
1031         return;
1032 }
1033
1034 /*
1035  * Main server-side entry point into LDLM. This is called by ptlrpc service
1036  * threads to carry out client lock enqueueing requests.
1037  */
1038 int ldlm_handle_enqueue0(struct ldlm_namespace *ns,
1039                          struct ptlrpc_request *req,
1040                          const struct ldlm_request *dlm_req,
1041                          const struct ldlm_callback_suite *cbs)
1042 {
1043         struct ldlm_reply *dlm_rep;
1044         __u32 flags;
1045         ldlm_error_t err = ELDLM_OK;
1046         struct ldlm_lock *lock = NULL;
1047         void *cookie = NULL;
1048         int rc = 0;
1049         ENTRY;
1050
1051         LDLM_DEBUG_NOLOCK("server-side enqueue handler START");
1052
1053         ldlm_request_cancel(req, dlm_req, LDLM_ENQUEUE_CANCEL_OFF);
1054         flags = dlm_req->lock_flags;
1055
1056         LASSERT(req->rq_export);
1057
1058         if (req->rq_rqbd->rqbd_service->srv_stats)
1059                 ldlm_svc_get_eopc(dlm_req,
1060                                   req->rq_rqbd->rqbd_service->srv_stats);
1061
1062         if (req->rq_export && req->rq_export->exp_nid_stats &&
1063             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1064                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1065                                      LDLM_ENQUEUE - LDLM_FIRST_OPC);
1066
1067         if (unlikely(dlm_req->lock_desc.l_resource.lr_type < LDLM_MIN_TYPE ||
1068                      dlm_req->lock_desc.l_resource.lr_type >= LDLM_MAX_TYPE)) {
1069                 DEBUG_REQ(D_ERROR, req, "invalid lock request type %d",
1070                           dlm_req->lock_desc.l_resource.lr_type);
1071                 GOTO(out, rc = -EFAULT);
1072         }
1073
1074         if (unlikely(dlm_req->lock_desc.l_req_mode <= LCK_MINMODE ||
1075                      dlm_req->lock_desc.l_req_mode >= LCK_MAXMODE ||
1076                      dlm_req->lock_desc.l_req_mode &
1077                      (dlm_req->lock_desc.l_req_mode-1))) {
1078                 DEBUG_REQ(D_ERROR, req, "invalid lock request mode %d",
1079                           dlm_req->lock_desc.l_req_mode);
1080                 GOTO(out, rc = -EFAULT);
1081         }
1082
1083         if (req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) {
1084                 if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1085                              LDLM_PLAIN)) {
1086                         DEBUG_REQ(D_ERROR, req,
1087                                   "PLAIN lock request from IBITS client?");
1088                         GOTO(out, rc = -EPROTO);
1089                 }
1090         } else if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
1091                             LDLM_IBITS)) {
1092                 DEBUG_REQ(D_ERROR, req,
1093                           "IBITS lock request from unaware client?");
1094                 GOTO(out, rc = -EPROTO);
1095         }
1096
1097 #if 0
1098         /* FIXME this makes it impossible to use LDLM_PLAIN locks -- check
1099            against server's _CONNECT_SUPPORTED flags? (I don't want to use
1100            ibits for mgc/mgs) */
1101
1102         /* INODEBITS_INTEROP: Perform conversion from plain lock to
1103          * inodebits lock if client does not support them. */
1104         if (!(req->rq_export->exp_connect_flags & OBD_CONNECT_IBITS) &&
1105             (dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN)) {
1106                 dlm_req->lock_desc.l_resource.lr_type = LDLM_IBITS;
1107                 dlm_req->lock_desc.l_policy_data.l_inodebits.bits =
1108                         MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
1109                 if (dlm_req->lock_desc.l_req_mode == LCK_PR)
1110                         dlm_req->lock_desc.l_req_mode = LCK_CR;
1111         }
1112 #endif
1113
1114         if (unlikely(flags & LDLM_FL_REPLAY)) {
1115                 /* Find an existing lock in the per-export lock hash */
1116                 lock = cfs_hash_lookup(req->rq_export->exp_lock_hash,
1117                                        (void *)&dlm_req->lock_handle[0]);
1118                 if (lock != NULL) {
1119                         DEBUG_REQ(D_DLMTRACE, req, "found existing lock cookie "
1120                                   LPX64, lock->l_handle.h_cookie);
1121                         GOTO(existing_lock, rc = 0);
1122                 }
1123         }
1124
1125         /* The lock's callback data might be set in the policy function */
1126         lock = ldlm_lock_create(ns, &dlm_req->lock_desc.l_resource.lr_name,
1127                                 dlm_req->lock_desc.l_resource.lr_type,
1128                                 dlm_req->lock_desc.l_req_mode,
1129                                 cbs, NULL, 0);
1130
1131         if (!lock)
1132                 GOTO(out, rc = -ENOMEM);
1133
1134         lock->l_last_activity = cfs_time_current_sec();
1135         lock->l_remote_handle = dlm_req->lock_handle[0];
1136         LDLM_DEBUG(lock, "server-side enqueue handler, new lock created");
1137
1138         OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_ENQUEUE_BLOCKED, obd_timeout * 2);
1139         /* Don't enqueue a lock onto the export if it is been disonnected
1140          * due to eviction (bug 3822) or server umount (bug 24324).
1141          * Cancel it now instead. */
1142         if (req->rq_export->exp_disconnected) {
1143                 LDLM_ERROR(lock, "lock on disconnected export %p",
1144                            req->rq_export);
1145                 GOTO(out, rc = -ENOTCONN);
1146         }
1147
1148         lock->l_export = class_export_lock_get(req->rq_export, lock);
1149         if (lock->l_export->exp_lock_hash)
1150                 cfs_hash_add(lock->l_export->exp_lock_hash,
1151                              &lock->l_remote_handle,
1152                              &lock->l_exp_hash);
1153
1154 existing_lock:
1155
1156         if (flags & LDLM_FL_HAS_INTENT) {
1157                 /* In this case, the reply buffer is allocated deep in
1158                  * local_lock_enqueue by the policy function. */
1159                 cookie = req;
1160         } else {
1161                 /* based on the assumption that lvb size never changes during
1162                  * resource life time otherwise it need resource->lr_lock's
1163                  * protection */
1164                 if (lock->l_resource->lr_lvb_len) {
1165                         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB,
1166                                              RCL_SERVER,
1167                                              lock->l_resource->lr_lvb_len);
1168                 }
1169
1170                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR))
1171                         GOTO(out, rc = -ENOMEM);
1172
1173                 rc = req_capsule_server_pack(&req->rq_pill);
1174                 if (rc)
1175                         GOTO(out, rc);
1176         }
1177
1178         if (dlm_req->lock_desc.l_resource.lr_type != LDLM_PLAIN)
1179                 ldlm_convert_policy_to_local(
1180                                           dlm_req->lock_desc.l_resource.lr_type,
1181                                           &dlm_req->lock_desc.l_policy_data,
1182                                           &lock->l_policy_data);
1183         if (dlm_req->lock_desc.l_resource.lr_type == LDLM_EXTENT)
1184                 lock->l_req_extent = lock->l_policy_data.l_extent;
1185
1186         err = ldlm_lock_enqueue(ns, &lock, cookie, (int *)&flags);
1187         if (err)
1188                 GOTO(out, err);
1189
1190         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1191         dlm_rep->lock_flags = flags;
1192
1193         ldlm_lock2desc(lock, &dlm_rep->lock_desc);
1194         ldlm_lock2handle(lock, &dlm_rep->lock_handle);
1195
1196         /* We never send a blocking AST until the lock is granted, but
1197          * we can tell it right now */
1198         lock_res_and_lock(lock);
1199
1200         /* Now take into account flags to be inherited from original lock
1201            request both in reply to client and in our own lock flags. */
1202         dlm_rep->lock_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1203         lock->l_flags |= dlm_req->lock_flags & LDLM_INHERIT_FLAGS;
1204
1205         /* Don't move a pending lock onto the export if it has already been
1206          * disconnected due to eviction (bug 5683) or server umount (bug 24324).
1207          * Cancel it now instead. */
1208         if (unlikely(req->rq_export->exp_disconnected ||
1209                      OBD_FAIL_CHECK(OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT))) {
1210                 LDLM_ERROR(lock, "lock on destroyed export %p", req->rq_export);
1211                 rc = -ENOTCONN;
1212         } else if (lock->l_flags & LDLM_FL_AST_SENT) {
1213                 dlm_rep->lock_flags |= LDLM_FL_AST_SENT;
1214                 if (lock->l_granted_mode == lock->l_req_mode) {
1215                         /*
1216                          * Only cancel lock if it was granted, because it would
1217                          * be destroyed immediately and would never be granted
1218                          * in the future, causing timeouts on client.  Not
1219                          * granted lock will be cancelled immediately after
1220                          * sending completion AST.
1221                          */
1222                         if (dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK) {
1223                                 unlock_res_and_lock(lock);
1224                                 ldlm_lock_cancel(lock);
1225                                 lock_res_and_lock(lock);
1226                         } else
1227                                 ldlm_add_waiting_lock(lock);
1228                 }
1229         }
1230         /* Make sure we never ever grant usual metadata locks to liblustre
1231            clients */
1232         if ((dlm_req->lock_desc.l_resource.lr_type == LDLM_PLAIN ||
1233             dlm_req->lock_desc.l_resource.lr_type == LDLM_IBITS) &&
1234              req->rq_export->exp_libclient) {
1235                 if (unlikely(!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK) ||
1236                              !(dlm_rep->lock_flags & LDLM_FL_CANCEL_ON_BLOCK))){
1237                         CERROR("Granting sync lock to libclient. "
1238                                "req fl %d, rep fl %d, lock fl "LPX64"\n",
1239                                dlm_req->lock_flags, dlm_rep->lock_flags,
1240                                lock->l_flags);
1241                         LDLM_ERROR(lock, "sync lock");
1242                         if (dlm_req->lock_flags & LDLM_FL_HAS_INTENT) {
1243                                 struct ldlm_intent *it;
1244
1245                                 it = req_capsule_client_get(&req->rq_pill,
1246                                                             &RMF_LDLM_INTENT);
1247                                 if (it != NULL) {
1248                                         CERROR("This is intent %s ("LPU64")\n",
1249                                                ldlm_it2str(it->opc), it->opc);
1250                                 }
1251                         }
1252                 }
1253         }
1254
1255         unlock_res_and_lock(lock);
1256
1257         EXIT;
1258  out:
1259         req->rq_status = rc ?: err; /* return either error - bug 11190 */
1260         if (!req->rq_packed_final) {
1261                 err = lustre_pack_reply(req, 1, NULL, NULL);
1262                 if (rc == 0)
1263                         rc = err;
1264         }
1265
1266         /* The LOCK_CHANGED code in ldlm_lock_enqueue depends on this
1267          * ldlm_reprocess_all.  If this moves, revisit that code. -phil */
1268         if (lock) {
1269                 LDLM_DEBUG(lock, "server-side enqueue handler, sending reply"
1270                            "(err=%d, rc=%d)", err, rc);
1271
1272                 if (rc == 0) {
1273                         if (lock->l_resource->lr_lvb_len > 0) {
1274                                 /* MDT path won't handle lr_lvb_data, so
1275                                  * lock/unlock better be contained in the
1276                                  * if block */
1277                                 void *lvb;
1278
1279                                 lvb = req_capsule_server_get(&req->rq_pill,
1280                                                              &RMF_DLM_LVB);
1281                                 LASSERTF(lvb != NULL, "req %p, lock %p\n",
1282                                          req, lock);
1283                                 lock_res(lock->l_resource);
1284                                 memcpy(lvb, lock->l_resource->lr_lvb_data,
1285                                        lock->l_resource->lr_lvb_len);
1286                                 unlock_res(lock->l_resource);
1287                         }
1288                 } else {
1289                         lock_res_and_lock(lock);
1290                         ldlm_resource_unlink_lock(lock);
1291                         ldlm_lock_destroy_nolock(lock);
1292                         unlock_res_and_lock(lock);
1293                 }
1294
1295                 if (!err && dlm_req->lock_desc.l_resource.lr_type != LDLM_FLOCK)
1296                         ldlm_reprocess_all(lock->l_resource);
1297
1298                 LDLM_LOCK_RELEASE(lock);
1299         }
1300
1301         LDLM_DEBUG_NOLOCK("server-side enqueue handler END (lock %p, rc %d)",
1302                           lock, rc);
1303
1304         return rc;
1305 }
1306
1307 int ldlm_handle_enqueue(struct ptlrpc_request *req,
1308                         ldlm_completion_callback completion_callback,
1309                         ldlm_blocking_callback blocking_callback,
1310                         ldlm_glimpse_callback glimpse_callback)
1311 {
1312         struct ldlm_request *dlm_req;
1313         struct ldlm_callback_suite cbs = {
1314                 .lcs_completion = completion_callback,
1315                 .lcs_blocking   = blocking_callback,
1316                 .lcs_glimpse    = glimpse_callback
1317         };
1318         int rc;
1319
1320         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1321         if (dlm_req != NULL) {
1322                 rc = ldlm_handle_enqueue0(req->rq_export->exp_obd->obd_namespace,
1323                                           req, dlm_req, &cbs);
1324         } else {
1325                 rc = -EFAULT;
1326         }
1327         return rc;
1328 }
1329
1330 int ldlm_handle_convert0(struct ptlrpc_request *req,
1331                          const struct ldlm_request *dlm_req)
1332 {
1333         struct ldlm_reply *dlm_rep;
1334         struct ldlm_lock *lock;
1335         int rc;
1336         ENTRY;
1337
1338         if (req->rq_export && req->rq_export->exp_nid_stats &&
1339             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1340                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1341                                      LDLM_CONVERT - LDLM_FIRST_OPC);
1342
1343         rc = req_capsule_server_pack(&req->rq_pill);
1344         if (rc)
1345                 RETURN(rc);
1346
1347         dlm_rep = req_capsule_server_get(&req->rq_pill, &RMF_DLM_REP);
1348         dlm_rep->lock_flags = dlm_req->lock_flags;
1349
1350         lock = ldlm_handle2lock(&dlm_req->lock_handle[0]);
1351         if (!lock) {
1352                 req->rq_status = EINVAL;
1353         } else {
1354                 void *res = NULL;
1355
1356                 LDLM_DEBUG(lock, "server-side convert handler START");
1357
1358                 lock->l_last_activity = cfs_time_current_sec();
1359                 res = ldlm_lock_convert(lock, dlm_req->lock_desc.l_req_mode,
1360                                         &dlm_rep->lock_flags);
1361                 if (res) {
1362                         if (ldlm_del_waiting_lock(lock))
1363                                 LDLM_DEBUG(lock, "converted waiting lock");
1364                         req->rq_status = 0;
1365                 } else {
1366                         req->rq_status = EDEADLOCK;
1367                 }
1368         }
1369
1370         if (lock) {
1371                 if (!req->rq_status)
1372                         ldlm_reprocess_all(lock->l_resource);
1373                 LDLM_DEBUG(lock, "server-side convert handler END");
1374                 LDLM_LOCK_PUT(lock);
1375         } else
1376                 LDLM_DEBUG_NOLOCK("server-side convert handler END");
1377
1378         RETURN(0);
1379 }
1380
1381 int ldlm_handle_convert(struct ptlrpc_request *req)
1382 {
1383         int rc;
1384         struct ldlm_request *dlm_req;
1385
1386         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1387         if (dlm_req != NULL) {
1388                 rc = ldlm_handle_convert0(req, dlm_req);
1389         } else {
1390                 CERROR ("Can't unpack dlm_req\n");
1391                 rc = -EFAULT;
1392         }
1393         return rc;
1394 }
1395
1396 /* Cancel all the locks whos handles are packed into ldlm_request */
1397 int ldlm_request_cancel(struct ptlrpc_request *req,
1398                         const struct ldlm_request *dlm_req, int first)
1399 {
1400         struct ldlm_resource *res, *pres = NULL;
1401         struct ldlm_lock *lock;
1402         int i, count, done = 0;
1403         ENTRY;
1404
1405         count = dlm_req->lock_count ? dlm_req->lock_count : 1;
1406         if (first >= count)
1407                 RETURN(0);
1408
1409         /* There is no lock on the server at the replay time,
1410          * skip lock cancelling to make replay tests to pass. */
1411         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1412                 RETURN(0);
1413
1414         LDLM_DEBUG_NOLOCK("server-side cancel handler START: %d locks, "
1415                           "starting at %d", count, first);
1416
1417         for (i = first; i < count; i++) {
1418                 lock = ldlm_handle2lock(&dlm_req->lock_handle[i]);
1419                 if (!lock) {
1420                         LDLM_DEBUG_NOLOCK("server-side cancel handler stale "
1421                                           "lock (cookie "LPU64")",
1422                                           dlm_req->lock_handle[i].cookie);
1423                         continue;
1424                 }
1425
1426                 res = lock->l_resource;
1427                 done++;
1428
1429                 if (res != pres) {
1430                         if (pres != NULL) {
1431                                 ldlm_reprocess_all(pres);
1432                                 LDLM_RESOURCE_DELREF(pres);
1433                                 ldlm_resource_putref(pres);
1434                         }
1435                         if (res != NULL) {
1436                                 ldlm_resource_getref(res);
1437                                 LDLM_RESOURCE_ADDREF(res);
1438                                 ldlm_res_lvbo_update(res, NULL, 1);
1439                         }
1440                         pres = res;
1441                 }
1442                 ldlm_lock_cancel(lock);
1443                 LDLM_LOCK_PUT(lock);
1444         }
1445         if (pres != NULL) {
1446                 ldlm_reprocess_all(pres);
1447                 LDLM_RESOURCE_DELREF(pres);
1448                 ldlm_resource_putref(pres);
1449         }
1450         LDLM_DEBUG_NOLOCK("server-side cancel handler END");
1451         RETURN(done);
1452 }
1453
1454 int ldlm_handle_cancel(struct ptlrpc_request *req)
1455 {
1456         struct ldlm_request *dlm_req;
1457         int rc;
1458         ENTRY;
1459
1460         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1461         if (dlm_req == NULL) {
1462                 CDEBUG(D_INFO, "bad request buffer for cancel\n");
1463                 RETURN(-EFAULT);
1464         }
1465
1466         if (req->rq_export && req->rq_export->exp_nid_stats &&
1467             req->rq_export->exp_nid_stats->nid_ldlm_stats)
1468                 lprocfs_counter_incr(req->rq_export->exp_nid_stats->nid_ldlm_stats,
1469                                      LDLM_CANCEL - LDLM_FIRST_OPC);
1470
1471         rc = req_capsule_server_pack(&req->rq_pill);
1472         if (rc)
1473                 RETURN(rc);
1474
1475         if (!ldlm_request_cancel(req, dlm_req, 0))
1476                 req->rq_status = ESTALE;
1477
1478         RETURN(ptlrpc_reply(req));
1479 }
1480
1481 void ldlm_handle_bl_callback(struct ldlm_namespace *ns,
1482                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock)
1483 {
1484         int do_ast;
1485         ENTRY;
1486
1487         LDLM_DEBUG(lock, "client blocking AST callback handler");
1488
1489         lock_res_and_lock(lock);
1490         lock->l_flags |= LDLM_FL_CBPENDING;
1491
1492         if (lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)
1493                 lock->l_flags |= LDLM_FL_CANCEL;
1494
1495         do_ast = (!lock->l_readers && !lock->l_writers);
1496         unlock_res_and_lock(lock);
1497
1498         if (do_ast) {
1499                 CDEBUG(D_DLMTRACE, "Lock %p already unused, calling callback (%p)\n",
1500                        lock, lock->l_blocking_ast);
1501                 if (lock->l_blocking_ast != NULL)
1502                         lock->l_blocking_ast(lock, ld, lock->l_ast_data,
1503                                              LDLM_CB_BLOCKING);
1504         } else {
1505                 CDEBUG(D_DLMTRACE, "Lock %p is referenced, will be cancelled later\n",
1506                        lock);
1507         }
1508
1509         LDLM_DEBUG(lock, "client blocking callback handler END");
1510         LDLM_LOCK_RELEASE(lock);
1511         EXIT;
1512 }
1513
1514 static void ldlm_handle_cp_callback(struct ptlrpc_request *req,
1515                                     struct ldlm_namespace *ns,
1516                                     struct ldlm_request *dlm_req,
1517                                     struct ldlm_lock *lock)
1518 {
1519         CFS_LIST_HEAD(ast_list);
1520         ENTRY;
1521
1522         LDLM_DEBUG(lock, "client completion callback handler START");
1523
1524         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE)) {
1525                 int to = cfs_time_seconds(1);
1526                 while (to > 0) {
1527                         cfs_schedule_timeout_and_set_state(
1528                                 CFS_TASK_INTERRUPTIBLE, to);
1529                         if (lock->l_granted_mode == lock->l_req_mode ||
1530                             lock->l_destroyed)
1531                                 break;
1532                 }
1533         }
1534
1535         lock_res_and_lock(lock);
1536         if (lock->l_destroyed ||
1537             lock->l_granted_mode == lock->l_req_mode) {
1538                 /* bug 11300: the lock has already been granted */
1539                 unlock_res_and_lock(lock);
1540                 LDLM_DEBUG(lock, "Double grant race happened");
1541                 LDLM_LOCK_RELEASE(lock);
1542                 EXIT;
1543                 return;
1544         }
1545
1546         /* If we receive the completion AST before the actual enqueue returned,
1547          * then we might need to switch lock modes, resources, or extents. */
1548         if (dlm_req->lock_desc.l_granted_mode != lock->l_req_mode) {
1549                 lock->l_req_mode = dlm_req->lock_desc.l_granted_mode;
1550                 LDLM_DEBUG(lock, "completion AST, new lock mode");
1551         }
1552
1553         if (lock->l_resource->lr_type != LDLM_PLAIN) {
1554                 ldlm_convert_policy_to_local(
1555                                           dlm_req->lock_desc.l_resource.lr_type,
1556                                           &dlm_req->lock_desc.l_policy_data,
1557                                           &lock->l_policy_data);
1558                 LDLM_DEBUG(lock, "completion AST, new policy data");
1559         }
1560
1561         ldlm_resource_unlink_lock(lock);
1562         if (memcmp(&dlm_req->lock_desc.l_resource.lr_name,
1563                    &lock->l_resource->lr_name,
1564                    sizeof(lock->l_resource->lr_name)) != 0) {
1565                 unlock_res_and_lock(lock);
1566                 if (ldlm_lock_change_resource(ns, lock,
1567                                 &dlm_req->lock_desc.l_resource.lr_name) != 0) {
1568                         LDLM_ERROR(lock, "Failed to allocate resource");
1569                         LDLM_LOCK_RELEASE(lock);
1570                         EXIT;
1571                         return;
1572                 }
1573                 LDLM_DEBUG(lock, "completion AST, new resource");
1574                 CERROR("change resource!\n");
1575                 lock_res_and_lock(lock);
1576         }
1577
1578         if (dlm_req->lock_flags & LDLM_FL_AST_SENT) {
1579                 /* BL_AST locks are not needed in lru.
1580                  * let ldlm_cancel_lru() be fast. */
1581                 ldlm_lock_remove_from_lru(lock);
1582                 lock->l_flags |= LDLM_FL_CBPENDING | LDLM_FL_BL_AST;
1583                 LDLM_DEBUG(lock, "completion AST includes blocking AST");
1584         }
1585
1586         if (lock->l_lvb_len) {
1587                 if (req_capsule_get_size(&req->rq_pill, &RMF_DLM_LVB,
1588                                          RCL_CLIENT) < lock->l_lvb_len) {
1589                         LDLM_ERROR(lock, "completion AST did not contain "
1590                                    "expected LVB!");
1591                 } else {
1592                         void *lvb = req_capsule_client_get(&req->rq_pill,
1593                                                            &RMF_DLM_LVB);
1594                         memcpy(lock->l_lvb_data, lvb, lock->l_lvb_len);
1595                 }
1596         }
1597
1598         ldlm_grant_lock(lock, &ast_list);
1599         unlock_res_and_lock(lock);
1600
1601         LDLM_DEBUG(lock, "callback handler finished, about to run_ast_work");
1602
1603         /* Let Enqueue to call osc_lock_upcall() and initialize
1604          * l_ast_data */
1605         OBD_FAIL_TIMEOUT(OBD_FAIL_OSC_CP_ENQ_RACE, 2);
1606
1607         ldlm_run_ast_work(&ast_list, LDLM_WORK_CP_AST);
1608
1609         LDLM_DEBUG_NOLOCK("client completion callback handler END (lock %p)",
1610                           lock);
1611         LDLM_LOCK_RELEASE(lock);
1612         EXIT;
1613 }
1614
1615 static void ldlm_handle_gl_callback(struct ptlrpc_request *req,
1616                                     struct ldlm_namespace *ns,
1617                                     struct ldlm_request *dlm_req,
1618                                     struct ldlm_lock *lock)
1619 {
1620         int rc = -ENOSYS;
1621         ENTRY;
1622
1623         LDLM_DEBUG(lock, "client glimpse AST callback handler");
1624
1625         if (lock->l_glimpse_ast != NULL)
1626                 rc = lock->l_glimpse_ast(lock, req);
1627
1628         if (req->rq_repmsg != NULL) {
1629                 ptlrpc_reply(req);
1630         } else {
1631                 req->rq_status = rc;
1632                 ptlrpc_error(req);
1633         }
1634
1635         lock_res_and_lock(lock);
1636         if (lock->l_granted_mode == LCK_PW &&
1637             !lock->l_readers && !lock->l_writers &&
1638             cfs_time_after(cfs_time_current(),
1639                            cfs_time_add(lock->l_last_used,
1640                                         cfs_time_seconds(10)))) {
1641                 unlock_res_and_lock(lock);
1642                 if (ldlm_bl_to_thread_lock(ns, NULL, lock))
1643                         ldlm_handle_bl_callback(ns, NULL, lock);
1644
1645                 EXIT;
1646                 return;
1647         }
1648         unlock_res_and_lock(lock);
1649         LDLM_LOCK_RELEASE(lock);
1650         EXIT;
1651 }
1652
1653 static int ldlm_callback_reply(struct ptlrpc_request *req, int rc)
1654 {
1655         if (req->rq_no_reply)
1656                 return 0;
1657
1658         req->rq_status = rc;
1659         if (!req->rq_packed_final) {
1660                 rc = lustre_pack_reply(req, 1, NULL, NULL);
1661                 if (rc)
1662                         return rc;
1663         }
1664         return ptlrpc_reply(req);
1665 }
1666
1667 #ifdef __KERNEL__
1668 static int __ldlm_bl_to_thread(struct ldlm_bl_work_item *blwi, int mode)
1669 {
1670         struct ldlm_bl_pool *blp = ldlm_state->ldlm_bl_pool;
1671         ENTRY;
1672
1673         cfs_spin_lock(&blp->blp_lock);
1674         if (blwi->blwi_lock && blwi->blwi_lock->l_flags & LDLM_FL_DISCARD_DATA) {
1675                 /* add LDLM_FL_DISCARD_DATA requests to the priority list */
1676                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_prio_list);
1677         } else {
1678                 /* other blocking callbacks are added to the regular list */
1679                 cfs_list_add_tail(&blwi->blwi_entry, &blp->blp_list);
1680         }
1681         cfs_spin_unlock(&blp->blp_lock);
1682
1683         cfs_waitq_signal(&blp->blp_waitq);
1684
1685         /* can not use blwi->blwi_mode as blwi could be already freed in
1686            LDLM_ASYNC mode */
1687         if (mode == LDLM_SYNC)
1688                 cfs_wait_for_completion(&blwi->blwi_comp);
1689
1690         RETURN(0);
1691 }
1692
1693 static inline void init_blwi(struct ldlm_bl_work_item *blwi,
1694                              struct ldlm_namespace *ns,
1695                              struct ldlm_lock_desc *ld,
1696                              cfs_list_t *cancels, int count,
1697                              struct ldlm_lock *lock,
1698                              int mode)
1699 {
1700         cfs_init_completion(&blwi->blwi_comp);
1701         CFS_INIT_LIST_HEAD(&blwi->blwi_head);
1702
1703         if (cfs_memory_pressure_get())
1704                 blwi->blwi_mem_pressure = 1;
1705
1706         blwi->blwi_ns = ns;
1707         blwi->blwi_mode = mode;
1708         if (ld != NULL)
1709                 blwi->blwi_ld = *ld;
1710         if (count) {
1711                 cfs_list_add(&blwi->blwi_head, cancels);
1712                 cfs_list_del_init(cancels);
1713                 blwi->blwi_count = count;
1714         } else {
1715                 blwi->blwi_lock = lock;
1716         }
1717 }
1718
1719 static int ldlm_bl_to_thread(struct ldlm_namespace *ns,
1720                              struct ldlm_lock_desc *ld, struct ldlm_lock *lock,
1721                              cfs_list_t *cancels, int count, int mode)
1722 {
1723         ENTRY;
1724
1725         if (cancels && count == 0)
1726                 RETURN(0);
1727
1728         if (mode == LDLM_SYNC) {
1729                 /* if it is synchronous call do minimum mem alloc, as it could
1730                  * be triggered from kernel shrinker
1731                  */
1732                 struct ldlm_bl_work_item blwi;
1733                 memset(&blwi, 0, sizeof(blwi));
1734                 init_blwi(&blwi, ns, ld, cancels, count, lock, LDLM_SYNC);
1735                 RETURN(__ldlm_bl_to_thread(&blwi, LDLM_SYNC));
1736         } else {
1737                 struct ldlm_bl_work_item *blwi;
1738                 OBD_ALLOC(blwi, sizeof(*blwi));
1739                 if (blwi == NULL)
1740                         RETURN(-ENOMEM);
1741                 init_blwi(blwi, ns, ld, cancels, count, lock, LDLM_ASYNC);
1742
1743                 RETURN(__ldlm_bl_to_thread(blwi, LDLM_ASYNC));
1744         }
1745 }
1746
1747 #endif
1748
1749 int ldlm_bl_to_thread_lock(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1750                            struct ldlm_lock *lock)
1751 {
1752 #ifdef __KERNEL__
1753         RETURN(ldlm_bl_to_thread(ns, ld, lock, NULL, 0, LDLM_ASYNC));
1754 #else
1755         RETURN(-ENOSYS);
1756 #endif
1757 }
1758
1759 int ldlm_bl_to_thread_list(struct ldlm_namespace *ns, struct ldlm_lock_desc *ld,
1760                            cfs_list_t *cancels, int count, int mode)
1761 {
1762 #ifdef __KERNEL__
1763         RETURN(ldlm_bl_to_thread(ns, ld, NULL, cancels, count, mode));
1764 #else
1765         RETURN(-ENOSYS);
1766 #endif
1767 }
1768
1769 /* Setinfo coming from Server (eg MDT) to Client (eg MDC)! */
1770 static int ldlm_handle_setinfo(struct ptlrpc_request *req)
1771 {
1772         struct obd_device *obd = req->rq_export->exp_obd;
1773         char *key;
1774         void *val;
1775         int keylen, vallen;
1776         int rc = -ENOSYS;
1777         ENTRY;
1778
1779         DEBUG_REQ(D_HSM, req, "%s: handle setinfo\n", obd->obd_name);
1780
1781         req_capsule_set(&req->rq_pill, &RQF_OBD_SET_INFO);
1782
1783         key = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_KEY);
1784         if (key == NULL) {
1785                 DEBUG_REQ(D_IOCTL, req, "no set_info key");
1786                 RETURN(-EFAULT);
1787         }
1788         keylen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_KEY,
1789                                       RCL_CLIENT);
1790         val = req_capsule_client_get(&req->rq_pill, &RMF_SETINFO_VAL);
1791         if (val == NULL) {
1792                 DEBUG_REQ(D_IOCTL, req, "no set_info val");
1793                 RETURN(-EFAULT);
1794         }
1795         vallen = req_capsule_get_size(&req->rq_pill, &RMF_SETINFO_VAL,
1796                                       RCL_CLIENT);
1797
1798         /* We are responsible for swabbing contents of val */
1799
1800         if (KEY_IS(KEY_HSM_COPYTOOL_SEND))
1801                 /* Pass it on to mdc (the "export" in this case) */
1802                 rc = obd_set_info_async(req->rq_export,
1803                                         sizeof(KEY_HSM_COPYTOOL_SEND),
1804                                         KEY_HSM_COPYTOOL_SEND,
1805                                         vallen, val, NULL);
1806         else
1807                 DEBUG_REQ(D_WARNING, req, "ignoring unknown key %s", key);
1808
1809         return rc;
1810 }
1811
1812 static inline void ldlm_callback_errmsg(struct ptlrpc_request *req,
1813                                         const char *msg, int rc,
1814                                         struct lustre_handle *handle)
1815 {
1816         DEBUG_REQ((req->rq_no_reply || rc) ? D_WARNING : D_DLMTRACE, req,
1817                   "%s: [nid %s] [rc %d] [lock "LPX64"]",
1818                   msg, libcfs_id2str(req->rq_peer), rc,
1819                   handle ? handle->cookie : 0);
1820         if (req->rq_no_reply)
1821                 CWARN("No reply was sent, maybe cause bug 21636.\n");
1822         else if (rc)
1823                 CWARN("Send reply failed, maybe cause bug 21636.\n");
1824 }
1825
1826 /* TODO: handle requests in a similar way as MDT: see mdt_handle_common() */
1827 static int ldlm_callback_handler(struct ptlrpc_request *req)
1828 {
1829         struct ldlm_namespace *ns;
1830         struct ldlm_request *dlm_req;
1831         struct ldlm_lock *lock;
1832         int rc;
1833         ENTRY;
1834
1835         /* Requests arrive in sender's byte order.  The ptlrpc service
1836          * handler has already checked and, if necessary, byte-swapped the
1837          * incoming request message body, but I am responsible for the
1838          * message buffers. */
1839
1840         /* do nothing for sec context finalize */
1841         if (lustre_msg_get_opc(req->rq_reqmsg) == SEC_CTX_FINI)
1842                 RETURN(0);
1843
1844         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
1845
1846         if (req->rq_export == NULL) {
1847                 rc = ldlm_callback_reply(req, -ENOTCONN);
1848                 ldlm_callback_errmsg(req, "Operate on unconnected server",
1849                                      rc, NULL);
1850                 RETURN(0);
1851         }
1852
1853         LASSERT(req->rq_export != NULL);
1854         LASSERT(req->rq_export->exp_obd != NULL);
1855
1856         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1857         case LDLM_BL_CALLBACK:
1858                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_BL_CALLBACK))
1859                         RETURN(0);
1860                 break;
1861         case LDLM_CP_CALLBACK:
1862                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CP_CALLBACK))
1863                         RETURN(0);
1864                 break;
1865         case LDLM_GL_CALLBACK:
1866                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_GL_CALLBACK))
1867                         RETURN(0);
1868                 break;
1869         case LDLM_SET_INFO:
1870                 rc = ldlm_handle_setinfo(req);
1871                 ldlm_callback_reply(req, rc);
1872                 RETURN(0);
1873         case OBD_LOG_CANCEL: /* remove this eventually - for 1.4.0 compat */
1874                 CERROR("shouldn't be handling OBD_LOG_CANCEL on DLM thread\n");
1875                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
1876                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
1877                         RETURN(0);
1878                 rc = llog_origin_handle_cancel(req);
1879                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
1880                         RETURN(0);
1881                 ldlm_callback_reply(req, rc);
1882                 RETURN(0);
1883         case OBD_QC_CALLBACK:
1884                 req_capsule_set(&req->rq_pill, &RQF_QC_CALLBACK);
1885                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_QC_CALLBACK_NET))
1886                         RETURN(0);
1887                 rc = target_handle_qc_callback(req);
1888                 ldlm_callback_reply(req, rc);
1889                 RETURN(0);
1890         case QUOTA_DQACQ:
1891         case QUOTA_DQREL:
1892                 /* reply in handler */
1893                 req_capsule_set(&req->rq_pill, &RQF_MDS_QUOTA_DQACQ);
1894                 rc = target_handle_dqacq_callback(req);
1895                 RETURN(0);
1896         case LLOG_ORIGIN_HANDLE_CREATE:
1897                 req_capsule_set(&req->rq_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
1898                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1899                         RETURN(0);
1900                 rc = llog_origin_handle_create(req);
1901                 ldlm_callback_reply(req, rc);
1902                 RETURN(0);
1903         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
1904                 req_capsule_set(&req->rq_pill,
1905                                 &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
1906                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1907                         RETURN(0);
1908                 rc = llog_origin_handle_next_block(req);
1909                 ldlm_callback_reply(req, rc);
1910                 RETURN(0);
1911         case LLOG_ORIGIN_HANDLE_READ_HEADER:
1912                 req_capsule_set(&req->rq_pill,
1913                                 &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
1914                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1915                         RETURN(0);
1916                 rc = llog_origin_handle_read_header(req);
1917                 ldlm_callback_reply(req, rc);
1918                 RETURN(0);
1919         case LLOG_ORIGIN_HANDLE_CLOSE:
1920                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOGD_NET))
1921                         RETURN(0);
1922                 rc = llog_origin_handle_close(req);
1923                 ldlm_callback_reply(req, rc);
1924                 RETURN(0);
1925         default:
1926                 CERROR("unknown opcode %u\n",
1927                        lustre_msg_get_opc(req->rq_reqmsg));
1928                 ldlm_callback_reply(req, -EPROTO);
1929                 RETURN(0);
1930         }
1931
1932         ns = req->rq_export->exp_obd->obd_namespace;
1933         LASSERT(ns != NULL);
1934
1935         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
1936
1937         dlm_req = req_capsule_client_get(&req->rq_pill, &RMF_DLM_REQ);
1938         if (dlm_req == NULL) {
1939                 rc = ldlm_callback_reply(req, -EPROTO);
1940                 ldlm_callback_errmsg(req, "Operate without parameter", rc,
1941                                      NULL);
1942                 RETURN(0);
1943         }
1944
1945         /* Force a known safe race, send a cancel to the server for a lock
1946          * which the server has already started a blocking callback on. */
1947         if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL_BL_CB_RACE) &&
1948             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1949                 rc = ldlm_cli_cancel(&dlm_req->lock_handle[0]);
1950                 if (rc < 0)
1951                         CERROR("ldlm_cli_cancel: %d\n", rc);
1952         }
1953
1954         lock = ldlm_handle2lock_long(&dlm_req->lock_handle[0], 0);
1955         if (!lock) {
1956                 CDEBUG(D_DLMTRACE, "callback on lock "LPX64" - lock "
1957                        "disappeared\n", dlm_req->lock_handle[0].cookie);
1958                 rc = ldlm_callback_reply(req, -EINVAL);
1959                 ldlm_callback_errmsg(req, "Operate with invalid parameter", rc,
1960                                      &dlm_req->lock_handle[0]);
1961                 RETURN(0);
1962         }
1963
1964         if ((lock->l_flags & LDLM_FL_FAIL_LOC) &&
1965             lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK)
1966                 OBD_RACE(OBD_FAIL_LDLM_CP_BL_RACE);
1967
1968         /* Copy hints/flags (e.g. LDLM_FL_DISCARD_DATA) from AST. */
1969         lock_res_and_lock(lock);
1970         lock->l_flags |= (dlm_req->lock_flags & LDLM_AST_FLAGS);
1971         if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_BL_CALLBACK) {
1972                 /* If somebody cancels lock and cache is already dropped,
1973                  * or lock is failed before cp_ast received on client,
1974                  * we can tell the server we have no lock. Otherwise, we
1975                  * should send cancel after dropping the cache. */
1976                 if (((lock->l_flags & LDLM_FL_CANCELING) &&
1977                     (lock->l_flags & LDLM_FL_BL_DONE)) ||
1978                     (lock->l_flags & LDLM_FL_FAILED)) {
1979                         LDLM_DEBUG(lock, "callback on lock "
1980                                    LPX64" - lock disappeared\n",
1981                                    dlm_req->lock_handle[0].cookie);
1982                         unlock_res_and_lock(lock);
1983                         LDLM_LOCK_RELEASE(lock);
1984                         rc = ldlm_callback_reply(req, -EINVAL);
1985                         ldlm_callback_errmsg(req, "Operate on stale lock", rc,
1986                                              &dlm_req->lock_handle[0]);
1987                         RETURN(0);
1988                 }
1989                 /* BL_AST locks are not needed in lru.
1990                  * let ldlm_cancel_lru() be fast. */
1991                 ldlm_lock_remove_from_lru(lock);
1992                 lock->l_flags |= LDLM_FL_BL_AST;
1993         }
1994         unlock_res_and_lock(lock);
1995
1996         /* We want the ost thread to get this reply so that it can respond
1997          * to ost requests (write cache writeback) that might be triggered
1998          * in the callback.
1999          *
2000          * But we'd also like to be able to indicate in the reply that we're
2001          * cancelling right now, because it's unused, or have an intent result
2002          * in the reply, so we might have to push the responsibility for sending
2003          * the reply down into the AST handlers, alas. */
2004
2005         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2006         case LDLM_BL_CALLBACK:
2007                 CDEBUG(D_INODE, "blocking ast\n");
2008                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_BL_CALLBACK);
2009                 if (!(lock->l_flags & LDLM_FL_CANCEL_ON_BLOCK)) {
2010                         rc = ldlm_callback_reply(req, 0);
2011                         if (req->rq_no_reply || rc)
2012                                 ldlm_callback_errmsg(req, "Normal process", rc,
2013                                                      &dlm_req->lock_handle[0]);
2014                 }
2015                 if (ldlm_bl_to_thread_lock(ns, &dlm_req->lock_desc, lock))
2016                         ldlm_handle_bl_callback(ns, &dlm_req->lock_desc, lock);
2017                 break;
2018         case LDLM_CP_CALLBACK:
2019                 CDEBUG(D_INODE, "completion ast\n");
2020                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_CP_CALLBACK);
2021                 ldlm_callback_reply(req, 0);
2022                 ldlm_handle_cp_callback(req, ns, dlm_req, lock);
2023                 break;
2024         case LDLM_GL_CALLBACK:
2025                 CDEBUG(D_INODE, "glimpse ast\n");
2026                 req_capsule_extend(&req->rq_pill, &RQF_LDLM_GL_CALLBACK);
2027                 ldlm_handle_gl_callback(req, ns, dlm_req, lock);
2028                 break;
2029         default:
2030                 LBUG();                         /* checked above */
2031         }
2032
2033         RETURN(0);
2034 }
2035
2036 static int ldlm_cancel_handler(struct ptlrpc_request *req)
2037 {
2038         int rc;
2039         ENTRY;
2040
2041         /* Requests arrive in sender's byte order.  The ptlrpc service
2042          * handler has already checked and, if necessary, byte-swapped the
2043          * incoming request message body, but I am responsible for the
2044          * message buffers. */
2045
2046         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2047
2048         if (req->rq_export == NULL) {
2049                 struct ldlm_request *dlm_req;
2050
2051                 CERROR("%s from %s arrived at %lu with bad export cookie "
2052                        LPU64"\n",
2053                        ll_opcode2str(lustre_msg_get_opc(req->rq_reqmsg)),
2054                        libcfs_nid2str(req->rq_peer.nid),
2055                        req->rq_arrival_time.tv_sec,
2056                        lustre_msg_get_handle(req->rq_reqmsg)->cookie);
2057
2058                 if (lustre_msg_get_opc(req->rq_reqmsg) == LDLM_CANCEL) {
2059                         req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2060                         dlm_req = req_capsule_client_get(&req->rq_pill,
2061                                                          &RMF_DLM_REQ);
2062                         if (dlm_req != NULL)
2063                                 ldlm_lock_dump_handle(D_ERROR,
2064                                                       &dlm_req->lock_handle[0]);
2065                 }
2066                 ldlm_callback_reply(req, -ENOTCONN);
2067                 RETURN(0);
2068         }
2069
2070         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2071
2072         /* XXX FIXME move this back to mds/handler.c, bug 249 */
2073         case LDLM_CANCEL:
2074                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CANCEL);
2075                 CDEBUG(D_INODE, "cancel\n");
2076                 if (OBD_FAIL_CHECK(OBD_FAIL_LDLM_CANCEL))
2077                         RETURN(0);
2078                 rc = ldlm_handle_cancel(req);
2079                 if (rc)
2080                         break;
2081                 RETURN(0);
2082         case OBD_LOG_CANCEL:
2083                 req_capsule_set(&req->rq_pill, &RQF_LOG_CANCEL);
2084                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_NET))
2085                         RETURN(0);
2086                 rc = llog_origin_handle_cancel(req);
2087                 if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LOG_CANCEL_REP))
2088                         RETURN(0);
2089                 ldlm_callback_reply(req, rc);
2090                 RETURN(0);
2091         default:
2092                 CERROR("invalid opcode %d\n",
2093                        lustre_msg_get_opc(req->rq_reqmsg));
2094                 req_capsule_set(&req->rq_pill, &RQF_LDLM_CALLBACK);
2095                 ldlm_callback_reply(req, -EINVAL);
2096         }
2097
2098         RETURN(0);
2099 }
2100
2101 int ldlm_revoke_lock_cb(cfs_hash_t *hs, cfs_hash_bd_t *bd,
2102                         cfs_hlist_node_t *hnode, void *data)
2103
2104 {
2105         cfs_list_t         *rpc_list = data;
2106         struct ldlm_lock   *lock = cfs_hash_object(hs, hnode);
2107
2108         lock_res_and_lock(lock);
2109
2110         if (lock->l_req_mode != lock->l_granted_mode) {
2111                 unlock_res_and_lock(lock);
2112                 return 0;
2113         }
2114
2115         LASSERT(lock->l_resource);
2116         if (lock->l_resource->lr_type != LDLM_IBITS &&
2117             lock->l_resource->lr_type != LDLM_PLAIN) {
2118                 unlock_res_and_lock(lock);
2119                 return 0;
2120         }
2121
2122         if (lock->l_flags & LDLM_FL_AST_SENT) {
2123                 unlock_res_and_lock(lock);
2124                 return 0;
2125         }
2126
2127         LASSERT(lock->l_blocking_ast);
2128         LASSERT(!lock->l_blocking_lock);
2129
2130         lock->l_flags |= LDLM_FL_AST_SENT;
2131         if (lock->l_export && lock->l_export->exp_lock_hash &&
2132             !cfs_hlist_unhashed(&lock->l_exp_hash))
2133                 cfs_hash_del(lock->l_export->exp_lock_hash,
2134                              &lock->l_remote_handle, &lock->l_exp_hash);
2135         cfs_list_add_tail(&lock->l_rk_ast, rpc_list);
2136         LDLM_LOCK_GET(lock);
2137
2138         unlock_res_and_lock(lock);
2139         return 0;
2140 }
2141
2142 void ldlm_revoke_export_locks(struct obd_export *exp)
2143 {
2144         cfs_list_t  rpc_list;
2145         ENTRY;
2146
2147         CFS_INIT_LIST_HEAD(&rpc_list);
2148         cfs_hash_for_each_empty(exp->exp_lock_hash,
2149                                 ldlm_revoke_lock_cb, &rpc_list);
2150         ldlm_run_ast_work(&rpc_list, 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);