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