Whamcloud - gitweb
d5facc4b8eabaaa06defb80565f719b56a485cce
[fs/lustre-release.git] / lustre / ldlm / ldlm_lib.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (c) 2003 Cluster File Systems, Inc.
5  *
6  *   This file is part of the Lustre file system, http://www.lustre.org
7  *   Lustre is a trademark of Cluster File Systems, Inc.
8  *
9  *   You may have signed or agreed to another license before downloading
10  *   this software.  If so, you are bound by the terms and conditions
11  *   of that agreement, and the following does not apply to you.  See the
12  *   LICENSE file included with this distribution for more information.
13  *
14  *   If you did not agree to a different license, then this copy of Lustre
15  *   is open source software; you can redistribute it and/or modify it
16  *   under the terms of version 2 of the GNU General Public License as
17  *   published by the Free Software Foundation.
18  *
19  *   In either case, Lustre is distributed in the hope that it will be
20  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
21  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   license text for more details.
23  */
24
25 #ifndef EXPORT_SYMTAB
26 # define EXPORT_SYMTAB
27 #endif
28 #define DEBUG_SUBSYSTEM S_LDLM
29
30 #ifdef __KERNEL__
31 # include <libcfs/libcfs.h>
32 #else
33 # include <liblustre.h>
34 #endif
35 #include <obd.h>
36 #include <lustre_mds.h>
37 #include <lustre_dlm.h>
38 #include <lustre_net.h>
39 #include <lustre_sec.h>
40
41 /* @priority: if non-zero, move the selected to the list head
42  * @create: if zero, only search in existed connections
43  */
44 static int import_set_conn(struct obd_import *imp, struct obd_uuid *uuid,
45                            int priority, int create)
46 {
47         struct ptlrpc_connection *ptlrpc_conn;
48         struct obd_import_conn *imp_conn = NULL, *item;
49         int rc = 0;
50         ENTRY;
51
52         if (!create && !priority) {
53                 CDEBUG(D_HA, "Nothing to do\n");
54                 RETURN(-EINVAL);
55         }
56
57         ptlrpc_conn = ptlrpc_uuid_to_connection(uuid);
58         if (!ptlrpc_conn) {
59                 CDEBUG(D_HA, "can't find connection %s\n", uuid->uuid);
60                 RETURN (-ENOENT);
61         }
62
63         if (create) {
64                 OBD_ALLOC(imp_conn, sizeof(*imp_conn));
65                 if (!imp_conn) {
66                         GOTO(out_put, rc = -ENOMEM);
67                 }
68         }
69
70         spin_lock(&imp->imp_lock);
71         list_for_each_entry(item, &imp->imp_conn_list, oic_item) {
72                 if (obd_uuid_equals(uuid, &item->oic_uuid)) {
73                         if (priority) {
74                                 list_del(&item->oic_item);
75                                 list_add(&item->oic_item, &imp->imp_conn_list);
76                                 item->oic_last_attempt = 0;
77                         }
78                         CDEBUG(D_HA, "imp %p@%s: found existing conn %s%s\n",
79                                imp, imp->imp_obd->obd_name, uuid->uuid,
80                                (priority ? ", moved to head" : ""));
81                         spin_unlock(&imp->imp_lock);
82                         GOTO(out_free, rc = 0);
83                 }
84         }
85         /* not found */
86         if (create) {
87                 imp_conn->oic_conn = ptlrpc_conn;
88                 imp_conn->oic_uuid = *uuid;
89                 item->oic_last_attempt = 0;
90                 if (priority)
91                         list_add(&imp_conn->oic_item, &imp->imp_conn_list);
92                 else
93                         list_add_tail(&imp_conn->oic_item, &imp->imp_conn_list);
94                 CDEBUG(D_HA, "imp %p@%s: add connection %s at %s\n",
95                        imp, imp->imp_obd->obd_name, uuid->uuid,
96                        (priority ? "head" : "tail"));
97         } else {
98                 spin_unlock(&imp->imp_lock);
99                 GOTO(out_free, rc = -ENOENT);
100         }
101
102         spin_unlock(&imp->imp_lock);
103         RETURN(0);
104 out_free:
105         if (imp_conn)
106                 OBD_FREE(imp_conn, sizeof(*imp_conn));
107 out_put:
108         ptlrpc_put_connection(ptlrpc_conn);
109         RETURN(rc);
110 }
111
112 int import_set_conn_priority(struct obd_import *imp, struct obd_uuid *uuid)
113 {
114         return import_set_conn(imp, uuid, 1, 0);
115 }
116
117 int client_import_add_conn(struct obd_import *imp, struct obd_uuid *uuid,
118                            int priority)
119 {
120         return import_set_conn(imp, uuid, priority, 1);
121 }
122
123 int client_import_del_conn(struct obd_import *imp, struct obd_uuid *uuid)
124 {
125         struct obd_import_conn *imp_conn;
126         struct obd_export *dlmexp;
127         int rc = -ENOENT;
128         ENTRY;
129
130         spin_lock(&imp->imp_lock);
131         if (list_empty(&imp->imp_conn_list)) {
132                 LASSERT(!imp->imp_connection);
133                 GOTO(out, rc);
134         }
135
136         list_for_each_entry(imp_conn, &imp->imp_conn_list, oic_item) {
137                 if (!obd_uuid_equals(uuid, &imp_conn->oic_uuid))
138                         continue;
139                 LASSERT(imp_conn->oic_conn);
140
141                 /* is current conn? */
142                 if (imp_conn == imp->imp_conn_current) {
143                         LASSERT(imp_conn->oic_conn == imp->imp_connection);
144
145                         if (imp->imp_state != LUSTRE_IMP_CLOSED &&
146                             imp->imp_state != LUSTRE_IMP_DISCON) {
147                                 CERROR("can't remove current connection\n");
148                                 GOTO(out, rc = -EBUSY);
149                         }
150
151                         ptlrpc_put_connection(imp->imp_connection);
152                         imp->imp_connection = NULL;
153
154                         dlmexp = class_conn2export(&imp->imp_dlm_handle);
155                         if (dlmexp && dlmexp->exp_connection) {
156                                 LASSERT(dlmexp->exp_connection ==
157                                         imp_conn->oic_conn);
158                                 ptlrpc_put_connection(dlmexp->exp_connection);
159                                 dlmexp->exp_connection = NULL;
160                         }
161                 }
162
163                 list_del(&imp_conn->oic_item);
164                 ptlrpc_put_connection(imp_conn->oic_conn);
165                 OBD_FREE(imp_conn, sizeof(*imp_conn));
166                 CDEBUG(D_HA, "imp %p@%s: remove connection %s\n",
167                        imp, imp->imp_obd->obd_name, uuid->uuid);
168                 rc = 0;
169                 break;
170         }
171 out:
172         spin_unlock(&imp->imp_lock);
173         if (rc == -ENOENT)
174                 CERROR("connection %s not found\n", uuid->uuid);
175         RETURN(rc);
176 }
177
178 static void destroy_import(struct obd_import *imp)
179 {
180         /* drop security policy instance after all rpc finished/aborted
181          * to let all busy credentials be released.
182          */
183         class_import_get(imp);
184         class_destroy_import(imp);
185         sptlrpc_import_put_sec(imp);
186         class_import_put(imp);
187 }
188
189 /* configure an RPC client OBD device
190  *
191  * lcfg parameters:
192  * 1 - client UUID
193  * 2 - server UUID
194  * 3 - inactive-on-startup
195  */
196 int client_obd_setup(struct obd_device *obddev, struct lustre_cfg *lcfg)
197 {
198         struct client_obd *cli = &obddev->u.cli;
199         struct obd_import *imp;
200         struct obd_uuid server_uuid;
201         int rq_portal, rp_portal, connect_op;
202         char *name = obddev->obd_type->typ_name;
203         int rc;
204         ENTRY;
205
206         /* In a more perfect world, we would hang a ptlrpc_client off of
207          * obd_type and just use the values from there. */
208         if (!strcmp(name, LUSTRE_OSC_NAME)) {
209                 rq_portal = OST_REQUEST_PORTAL;
210                 rp_portal = OSC_REPLY_PORTAL;
211                 connect_op = OST_CONNECT;
212         } else if (!strcmp(name, LUSTRE_MDC_NAME)) {
213                 rq_portal = MDS_REQUEST_PORTAL;
214                 rp_portal = MDC_REPLY_PORTAL;
215                 connect_op = MDS_CONNECT;
216         } else if (!strcmp(name, LUSTRE_MGC_NAME)) {
217                 rq_portal = MGS_REQUEST_PORTAL;
218                 rp_portal = MGC_REPLY_PORTAL;
219                 connect_op = MGS_CONNECT;
220         } else {
221                 CERROR("unknown client OBD type \"%s\", can't setup\n",
222                        name);
223                 RETURN(-EINVAL);
224         }
225
226         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
227                 CERROR("requires a TARGET UUID\n");
228                 RETURN(-EINVAL);
229         }
230
231         if (LUSTRE_CFG_BUFLEN(lcfg, 1) > 37) {
232                 CERROR("client UUID must be less than 38 characters\n");
233                 RETURN(-EINVAL);
234         }
235
236         if (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1) {
237                 CERROR("setup requires a SERVER UUID\n");
238                 RETURN(-EINVAL);
239         }
240
241         if (LUSTRE_CFG_BUFLEN(lcfg, 2) > 37) {
242                 CERROR("target UUID must be less than 38 characters\n");
243                 RETURN(-EINVAL);
244         }
245
246         sema_init(&cli->cl_sem, 1);
247         sema_init(&cli->cl_mgc_sem, 1);
248         cli->cl_sec_conf.sfc_rpc_flavor = SPTLRPC_FLVR_NULL;
249         cli->cl_sec_conf.sfc_bulk_csum = BULK_CSUM_ALG_NULL;
250         cli->cl_sec_conf.sfc_bulk_priv = BULK_PRIV_ALG_NULL;
251         cli->cl_sec_conf.sfc_flags = 0;
252         cli->cl_conn_count = 0;
253         memcpy(server_uuid.uuid, lustre_cfg_buf(lcfg, 2),
254                min_t(unsigned int, LUSTRE_CFG_BUFLEN(lcfg, 2),
255                      sizeof(server_uuid)));
256
257         cli->cl_dirty = 0;
258         cli->cl_avail_grant = 0;
259         /* FIXME: should limit this for the sum of all cl_dirty_max */
260         cli->cl_dirty_max = OSC_MAX_DIRTY_DEFAULT * 1024 * 1024;
261         if (cli->cl_dirty_max >> CFS_PAGE_SHIFT > num_physpages / 8)
262                 cli->cl_dirty_max = num_physpages << (CFS_PAGE_SHIFT - 3);
263         CFS_INIT_LIST_HEAD(&cli->cl_cache_waiters);
264         CFS_INIT_LIST_HEAD(&cli->cl_loi_ready_list);
265         CFS_INIT_LIST_HEAD(&cli->cl_loi_write_list);
266         CFS_INIT_LIST_HEAD(&cli->cl_loi_read_list);
267         client_obd_list_lock_init(&cli->cl_loi_list_lock);
268         cli->cl_r_in_flight = 0;
269         cli->cl_w_in_flight = 0;
270
271         spin_lock_init(&cli->cl_read_rpc_hist.oh_lock);
272         spin_lock_init(&cli->cl_write_rpc_hist.oh_lock);
273         spin_lock_init(&cli->cl_read_page_hist.oh_lock);
274         spin_lock_init(&cli->cl_write_page_hist.oh_lock);
275         spin_lock_init(&cli->cl_read_offset_hist.oh_lock);
276         spin_lock_init(&cli->cl_write_offset_hist.oh_lock);
277
278         /* This value may be changed at connect time in
279            ptlrpc_connect_interpret. */
280         cli->cl_max_pages_per_rpc = min((int)PTLRPC_MAX_BRW_PAGES,
281                                         (int)(1024 * 1024 >> CFS_PAGE_SHIFT));
282
283         if (!strcmp(name, LUSTRE_MDC_NAME)) {
284                 cli->cl_max_rpcs_in_flight = MDC_MAX_RIF_DEFAULT;
285         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 128 /* MB */) {
286                 cli->cl_max_rpcs_in_flight = 2;
287         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 256 /* MB */) {
288                 cli->cl_max_rpcs_in_flight = 3;
289         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 512 /* MB */) {
290                 cli->cl_max_rpcs_in_flight = 4;
291         } else {
292                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT;
293         }
294
295         rc = ldlm_get_ref();
296         if (rc) {
297                 CERROR("ldlm_get_ref failed: %d\n", rc);
298                 GOTO(err, rc);
299         }
300
301         ptlrpc_init_client(rq_portal, rp_portal, name,
302                            &obddev->obd_ldlm_client);
303
304         imp = class_new_import(obddev);
305         if (imp == NULL)
306                 GOTO(err_ldlm, rc = -ENOENT);
307         imp->imp_client = &obddev->obd_ldlm_client;
308         imp->imp_connect_op = connect_op;
309         imp->imp_initial_recov = 1;
310         imp->imp_initial_recov_bk = 0;
311         CFS_INIT_LIST_HEAD(&imp->imp_pinger_chain);
312         memcpy(cli->cl_target_uuid.uuid, lustre_cfg_buf(lcfg, 1),
313                LUSTRE_CFG_BUFLEN(lcfg, 1));
314         class_import_put(imp);
315
316         rc = client_import_add_conn(imp, &server_uuid, 1);
317         if (rc) {
318                 CERROR("can't add initial connection\n");
319                 GOTO(err_import, rc);
320         }
321
322         cli->cl_import = imp;
323         /* cli->cl_max_mds_{easize,cookiesize} updated by mdc_init_ea_size() */
324         cli->cl_max_mds_easize = sizeof(struct lov_mds_md);
325         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
326
327         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
328                 if (!strcmp(lustre_cfg_string(lcfg, 3), "inactive")) {
329                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
330                                name, obddev->obd_name,
331                                cli->cl_target_uuid.uuid);
332                         spin_lock(&imp->imp_lock);
333                         imp->imp_invalid = 1;
334                         spin_unlock(&imp->imp_lock);
335                 }
336         }
337
338         cli->cl_qchk_stat = CL_NOT_QUOTACHECKED;
339
340         RETURN(rc);
341
342 err_import:
343         class_destroy_import(imp);
344 err_ldlm:
345         ldlm_put_ref(0);
346 err:
347         RETURN(rc);
348
349 }
350
351 int client_obd_cleanup(struct obd_device *obddev)
352 {
353         ENTRY;
354         ldlm_put_ref(obddev->obd_force);
355
356         RETURN(0);
357 }
358
359 /* ->o_connect() method for client side (OSC and MDC and MGC) */
360 int client_connect_import(const struct lu_env *env,
361                           struct lustre_handle *dlm_handle,
362                           struct obd_device *obd, struct obd_uuid *cluuid,
363                           struct obd_connect_data *data)
364 {
365         struct client_obd *cli = &obd->u.cli;
366         struct obd_import *imp = cli->cl_import;
367         struct obd_export *exp;
368         struct obd_connect_data *ocd;
369         int rc;
370         ENTRY;
371
372         mutex_down(&cli->cl_sem);
373         rc = class_connect(dlm_handle, obd, cluuid);
374         if (rc)
375                 GOTO(out_sem, rc);
376
377         cli->cl_conn_count++;
378         if (cli->cl_conn_count > 1)
379                 GOTO(out_sem, rc);
380         exp = class_conn2export(dlm_handle);
381
382         if (obd->obd_namespace != NULL)
383                 CERROR("already have namespace!\n");
384         obd->obd_namespace = ldlm_namespace_new(obd->obd_name,
385                                                 LDLM_NAMESPACE_CLIENT);
386         if (obd->obd_namespace == NULL)
387                 GOTO(out_disco, rc = -ENOMEM);
388
389         imp->imp_dlm_handle = *dlm_handle;
390         rc = ptlrpc_init_import(imp);
391         if (rc != 0)
392                 GOTO(out_ldlm, rc);
393
394         rc = sptlrpc_import_get_sec(imp, NULL, cli->cl_sec_conf.sfc_rpc_flavor,
395                                     cli->cl_sec_conf.sfc_flags);
396         if (rc)
397                 GOTO(out_ldlm, rc);
398
399         ocd = &imp->imp_connect_data;
400         if (data) {
401                 *ocd = *data;
402                 imp->imp_connect_flags_orig = data->ocd_connect_flags;
403         }
404
405         rc = ptlrpc_connect_import(imp, NULL);
406         if (rc != 0) {
407                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
408                 GOTO(out_ldlm, rc);
409         }
410         LASSERT(exp->exp_connection);
411
412         if (data) {
413                 LASSERT((ocd->ocd_connect_flags & data->ocd_connect_flags) ==
414                         ocd->ocd_connect_flags);
415                 data->ocd_connect_flags = ocd->ocd_connect_flags;
416         }
417
418         ptlrpc_pinger_add_import(imp);
419
420         EXIT;
421
422         if (rc) {
423 out_ldlm:
424                 ldlm_namespace_free(obd->obd_namespace, 0);
425                 obd->obd_namespace = NULL;
426 out_disco:
427                 cli->cl_conn_count--;
428                 class_disconnect(exp);
429         } else {
430                 class_export_put(exp);
431         }
432 out_sem:
433         mutex_up(&cli->cl_sem);
434         return rc;
435 }
436
437 int client_disconnect_export(struct obd_export *exp)
438 {
439         struct obd_device *obd = class_exp2obd(exp);
440         struct client_obd *cli;
441         struct obd_import *imp;
442         int rc = 0, err;
443         ENTRY;
444
445         if (!obd) {
446                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
447                        exp, exp ? exp->exp_handle.h_cookie : -1);
448                 RETURN(-EINVAL);
449         }
450
451         cli = &obd->u.cli;
452         imp = cli->cl_import;
453
454         mutex_down(&cli->cl_sem);
455         if (!cli->cl_conn_count) {
456                 CERROR("disconnecting disconnected device (%s)\n",
457                        obd->obd_name);
458                 GOTO(out_sem, rc = -EINVAL);
459         }
460
461         cli->cl_conn_count--;
462         if (cli->cl_conn_count)
463                 GOTO(out_no_disconnect, rc = 0);
464
465         /* Mark import deactivated now, so we don't try to reconnect if any
466          * of the cleanup RPCs fails (e.g. ldlm cancel, etc).  We don't
467          * fully deactivate the import, or that would drop all requests. */
468         spin_lock(&imp->imp_lock);
469         imp->imp_deactive = 1;
470         spin_unlock(&imp->imp_lock);
471         
472         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
473          * delete it regardless.  (It's safe to delete an import that was
474          * never added.) */
475         (void)ptlrpc_pinger_del_import(imp);
476
477         if (obd->obd_namespace != NULL) {
478                 /* obd_force == local only */
479                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
480                                        obd->obd_force ? LDLM_FL_LOCAL_ONLY:0,
481                                        NULL);
482                 ldlm_namespace_free(obd->obd_namespace, obd->obd_force);
483                 obd->obd_namespace = NULL;
484         }
485
486         if (!obd->obd_force)
487                 rc = ptlrpc_disconnect_import(imp, 0);
488
489         ptlrpc_invalidate_import(imp);
490         ptlrpc_free_rq_pool(imp->imp_rq_pool);
491         destroy_import(imp);
492         cli->cl_import = NULL;
493
494         EXIT;
495  out_no_disconnect:
496         err = class_disconnect(exp);
497         if (!rc && err)
498                 rc = err;
499  out_sem:
500         mutex_up(&cli->cl_sem);
501         RETURN(rc);
502 }
503
504 /* --------------------------------------------------------------------------
505  * from old lib/target.c
506  * -------------------------------------------------------------------------- */
507
508 int target_handle_reconnect(struct lustre_handle *conn, struct obd_export *exp,
509                             struct obd_uuid *cluuid, int initial_conn)
510 {
511         ENTRY;
512         if (exp->exp_connection && exp->exp_imp_reverse && !initial_conn) {
513                 struct lustre_handle *hdl;
514                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
515                 /* Might be a re-connect after a partition. */
516                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
517                         CWARN("%s: %s reconnecting\n", exp->exp_obd->obd_name,
518                               cluuid->uuid);
519                         conn->cookie = exp->exp_handle.h_cookie;
520                         /* target_handle_connect() treats EALREADY and
521                          * -EALREADY differently.  EALREADY means we are
522                          * doing a valid reconnect from the same client. */
523                         RETURN(EALREADY);
524                 } else {
525                         CERROR("%s reconnecting from %s, "
526                                "handle mismatch (ours "LPX64", theirs "
527                                LPX64")\n", cluuid->uuid,
528                                exp->exp_connection->c_remote_uuid.uuid,
529                                hdl->cookie, conn->cookie);
530                         memset(conn, 0, sizeof *conn);
531                         /* target_handle_connect() treats EALREADY and
532                          * -EALREADY differently.  -EALREADY is an error
533                          * (same UUID, different handle). */
534                         RETURN(-EALREADY);
535                 }
536         }
537
538         conn->cookie = exp->exp_handle.h_cookie;
539         CDEBUG(D_HA, "connect export for UUID '%s' at %p, cookie "LPX64"\n",
540                cluuid->uuid, exp, conn->cookie);
541         RETURN(0);
542 }
543
544 void target_client_add_cb(struct obd_device *obd, __u64 transno, void *cb_data,
545                           int error)
546 {
547         struct obd_export *exp = cb_data;
548
549         CDEBUG(D_HA, "%s: committing for initial connect of %s\n",
550                obd->obd_name, exp->exp_client_uuid.uuid);
551
552         spin_lock(&exp->exp_lock);
553         exp->exp_need_sync = 0;
554         spin_unlock(&exp->exp_lock);
555 }
556 EXPORT_SYMBOL(target_client_add_cb);
557
558 int target_handle_connect(struct ptlrpc_request *req)
559 {
560         struct obd_device *target, *targref = NULL;
561         struct obd_export *export = NULL;
562         struct obd_import *revimp;
563         struct lustre_handle conn;
564         struct obd_uuid tgtuuid;
565         struct obd_uuid cluuid;
566         struct obd_uuid remote_uuid;
567         struct list_head *p;
568         char *str, *tmp;
569         int rc = 0;
570         int initial_conn = 0;
571         struct obd_connect_data *data;
572         int size[2] = { sizeof(struct ptlrpc_body), sizeof(*data) };
573         ENTRY;
574
575         OBD_RACE(OBD_FAIL_TGT_CONN_RACE);
576
577         LASSERT_REQSWAB(req, REQ_REC_OFF);
578         str = lustre_msg_string(req->rq_reqmsg, REQ_REC_OFF, sizeof(tgtuuid)-1);
579         if (str == NULL) {
580                 DEBUG_REQ(D_ERROR, req, "bad target UUID for connect");
581                 GOTO(out, rc = -EINVAL);
582         }
583
584         obd_str2uuid (&tgtuuid, str);
585         target = class_uuid2obd(&tgtuuid);
586         if (!target)
587                 target = class_name2obd(str);
588
589         if (!target || target->obd_stopping || !target->obd_set_up) {
590                 LCONSOLE_ERROR_MSG(0x137, "UUID '%s' is not available "
591                                    " for connect (%s)\n", str,
592                                    !target ? "no target" :
593                                    (target->obd_stopping ? "stopping" :
594                                    "not set up"));
595                 GOTO(out, rc = -ENODEV);
596         }
597
598         if (target->obd_no_conn) {
599                 LCONSOLE_WARN("%s: temporarily refusing client connection "
600                               "from %s\n", target->obd_name, 
601                               libcfs_nid2str(req->rq_peer.nid));
602                 GOTO(out, rc = -EAGAIN);
603         }
604
605         /* Make sure the target isn't cleaned up while we're here. Yes,
606            there's still a race between the above check and our incref here.
607            Really, class_uuid2obd should take the ref. */
608         targref = class_incref(target);
609
610         LASSERT_REQSWAB(req, REQ_REC_OFF + 1);
611         str = lustre_msg_string(req->rq_reqmsg, REQ_REC_OFF + 1,
612                                 sizeof(cluuid) - 1);
613         if (str == NULL) {
614                 DEBUG_REQ(D_ERROR, req, "bad client UUID for connect");
615                 GOTO(out, rc = -EINVAL);
616         }
617
618         obd_str2uuid (&cluuid, str);
619
620         /* XXX extract a nettype and format accordingly */
621         switch (sizeof(lnet_nid_t)) {
622                 /* NB the casts only avoid compiler warnings */
623         case 8:
624                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
625                          "NET_"LPX64"_UUID", (__u64)req->rq_peer.nid);
626                 break;
627         case 4:
628                 snprintf(remote_uuid.uuid, sizeof remote_uuid,
629                          "NET_%x_UUID", (__u32)req->rq_peer.nid);
630                 break;
631         default:
632                 LBUG();
633         }
634
635         tmp = lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF + 2, sizeof conn);
636         if (tmp == NULL)
637                 GOTO(out, rc = -EPROTO);
638
639         memcpy(&conn, tmp, sizeof conn);
640
641         data = lustre_swab_reqbuf(req, REQ_REC_OFF + 3, sizeof(*data),
642                                   lustre_swab_connect);
643
644         if (!data)
645                 GOTO(out, rc = -EPROTO);
646
647         rc = lustre_pack_reply(req, 2, size, NULL);
648         if (rc)
649                 GOTO(out, rc);
650
651         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
652                 if (!data) {
653                         DEBUG_REQ(D_WARNING, req, "Refusing old (unversioned) "
654                                   "libclient connection attempt");
655                         GOTO(out, rc = -EPROTO);
656                 } else if (data->ocd_version < LUSTRE_VERSION_CODE -
657                                                LUSTRE_VERSION_ALLOWED_OFFSET ||
658                            data->ocd_version > LUSTRE_VERSION_CODE +
659                                                LUSTRE_VERSION_ALLOWED_OFFSET) {
660                         DEBUG_REQ(D_WARNING, req, "Refusing %s (%d.%d.%d.%d) "
661                                   "libclient connection attempt",
662                                   data->ocd_version < LUSTRE_VERSION_CODE ?
663                                   "old" : "new",
664                                   OBD_OCD_VERSION_MAJOR(data->ocd_version),
665                                   OBD_OCD_VERSION_MINOR(data->ocd_version),
666                                   OBD_OCD_VERSION_PATCH(data->ocd_version),
667                                   OBD_OCD_VERSION_FIX(data->ocd_version));
668                         data = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
669                                               offsetof(typeof(*data),
670                                                        ocd_version) +
671                                               sizeof(data->ocd_version));
672                         if (data) {
673                                 data->ocd_connect_flags = OBD_CONNECT_VERSION;
674                                 data->ocd_version = LUSTRE_VERSION_CODE;
675                         }
676                         GOTO(out, rc = -EPROTO);
677                 }
678         }
679
680         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_INITIAL)
681                 initial_conn = 1;
682
683         /* lctl gets a backstage, all-access pass. */
684         if (obd_uuid_equals(&cluuid, &target->obd_uuid))
685                 goto dont_check_exports;
686
687         spin_lock(&target->obd_dev_lock);
688         list_for_each(p, &target->obd_exports) {
689                 export = list_entry(p, struct obd_export, exp_obd_chain);
690                 if (obd_uuid_equals(&cluuid, &export->exp_client_uuid)) {
691                         if (export->exp_connecting) { /* bug 9635, et. al. */
692                                 CWARN("%s: exp %p already connecting\n",
693                                       export->exp_obd->obd_name, export);
694                                 export = NULL;
695                                 rc = -EALREADY;
696                                 break;
697                         }
698
699                         /* make darn sure this is coming from the same peer
700                          * if the UUIDs matched */
701                         if ((export->exp_connection != NULL) &&
702                             (strcmp(libcfs_nid2str(req->rq_peer.nid),
703                                     libcfs_nid2str(export->exp_connection->c_peer.nid)))) {
704                                 CWARN("%s: cookie %s seen on new NID %s when "
705                                       "existing NID %s is already connected\n",
706                                       target->obd_name, cluuid.uuid,
707                                       libcfs_nid2str(req->rq_peer.nid),
708                                       libcfs_nid2str(export->exp_connection->c_peer.nid));
709                                 export = NULL;
710                                 rc = -EALREADY;
711                                 break;
712                         }
713
714                         spin_lock(&export->exp_lock);
715                         export->exp_connecting = 1;
716                         spin_unlock(&export->exp_lock);
717                         spin_unlock(&target->obd_dev_lock);
718                         LASSERT(export->exp_obd == target);
719
720                         rc = target_handle_reconnect(&conn, export, &cluuid,
721                                                      initial_conn);
722                         break;
723                 }
724                 export = NULL;
725         }
726
727         /* If we found an export, we already unlocked. */
728         if (!export) {
729                 spin_unlock(&target->obd_dev_lock);
730                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
731         } else if (req->rq_export == NULL &&
732                    atomic_read(&export->exp_rpc_count) > 0) {
733                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
734                       target->obd_name, cluuid.uuid,
735                       libcfs_nid2str(req->rq_peer.nid),
736                       export, atomic_read(&export->exp_refcount));
737                 GOTO(out, rc = -EBUSY);
738         } else if (req->rq_export != NULL &&
739                    (atomic_read(&export->exp_rpc_count) > 1)) {
740                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
741                       target->obd_name, cluuid.uuid,
742                       libcfs_nid2str(req->rq_peer.nid),
743                       export, atomic_read(&export->exp_rpc_count));
744                 GOTO(out, rc = -EBUSY);
745         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1 &&
746                    !initial_conn) {
747                 CERROR("%s: NID %s (%s) reconnected with 1 conn_cnt; "
748                        "cookies not random?\n", target->obd_name,
749                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
750                 GOTO(out, rc = -EALREADY);
751         } else {
752                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
753                 if (req->rq_export == NULL && initial_conn)
754                        export->exp_last_request_time = 
755                                max(export->exp_last_request_time,
756                                    (time_t)CURRENT_SECONDS);
757         }
758
759         /* We want to handle EALREADY but *not* -EALREADY from
760          * target_handle_reconnect(), return reconnection state in a flag */
761         if (rc == EALREADY) {
762                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
763                 rc = 0;
764         } else if (rc) {
765                 GOTO(out, rc);
766         }
767         /* Tell the client if we're in recovery. */
768         /* If this is the first client, start the recovery timer */
769         CWARN("%s: connection from %s@%s %st"LPU64" exp %p cur %ld last %ld\n",
770                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
771               target->obd_recovering ? "recovering/" : "", data->ocd_transno,
772               export, (long)CURRENT_SECONDS, 
773               export ? (long)export->exp_last_request_time : 0);
774
775
776         if (target->obd_recovering) {
777                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
778                 target_start_recovery_timer(target);
779         }
780
781         /* Tell the client if we support replayable requests */
782         if (target->obd_replayable)
783                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
784
785         if (export == NULL) {
786                 if (target->obd_recovering) {
787                         CERROR("%s: denying connection for new client %s (%s): "
788                                "%d clients in recovery for %lds\n",
789                                target->obd_name,
790                                libcfs_nid2str(req->rq_peer.nid), cluuid.uuid,
791                                target->obd_recoverable_clients,
792                                cfs_duration_sec(cfs_time_sub(cfs_timer_deadline(&target->obd_recovery_timer),
793                                                              cfs_time_current())));
794                         rc = -EBUSY;
795                 } else {
796 dont_check_exports:
797                         rc = obd_connect(req->rq_svc_thread->t_env,
798                                          &conn, target, &cluuid, data);
799                 }
800         } else {
801                 rc = obd_reconnect(export, target, &cluuid, data);
802         }
803         if (rc)
804                 GOTO(out, rc);
805         /* Return only the parts of obd_connect_data that we understand, so the
806          * client knows that we don't understand the rest. */
807         if (data)
808                 memcpy(lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
809                                       sizeof(*data)),
810                        data, sizeof(*data));
811
812         /* If all else goes well, this is our RPC return code. */
813         req->rq_status = 0;
814
815         lustre_msg_set_handle(req->rq_repmsg, &conn);
816
817         /* ownership of this export ref transfers to the request AFTER we
818          * drop any previous reference the request had, but we don't want
819          * that to go to zero before we get our new export reference. */
820         export = class_conn2export(&conn);
821         if (!export) {
822                 DEBUG_REQ(D_ERROR, req, "Missing export!");
823                 GOTO(out, rc = -ENODEV);
824         }
825
826         /* If the client and the server are the same node, we will already
827          * have an export that really points to the client's DLM export,
828          * because we have a shared handles table.
829          *
830          * XXX this will go away when shaver stops sending the "connect" handle
831          * in the real "remote handle" field of the request --phik 24 Apr 2003
832          */
833         if (req->rq_export != NULL)
834                 class_export_put(req->rq_export);
835
836         req->rq_export = export;
837
838         spin_lock(&export->exp_lock);
839         if (initial_conn) {
840                 lustre_msg_set_conn_cnt(req->rq_repmsg, export->exp_conn_cnt + 1);
841         } else if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
842                 spin_unlock(&export->exp_lock);
843                 CERROR("%s: %s already connected at higher conn_cnt: %d > %d\n",
844                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
845                        export->exp_conn_cnt,
846                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
847
848                 GOTO(out, rc = -EALREADY);
849         }
850         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
851
852         /* request from liblustre?  Don't evict it for not pinging. */
853         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
854                 export->exp_libclient = 1;
855                 spin_unlock(&export->exp_lock);
856                 
857                 spin_lock(&target->obd_dev_lock);
858                 list_del_init(&export->exp_obd_chain_timed);
859                 spin_unlock(&target->obd_dev_lock);
860         } else {
861                 spin_unlock(&export->exp_lock);
862         }
863
864         if (export->exp_connection != NULL)
865                 ptlrpc_put_connection(export->exp_connection);
866         export->exp_connection = ptlrpc_get_connection(req->rq_peer,
867                                                        req->rq_self,
868                                                        &remote_uuid);
869
870         if (lustre_msg_get_op_flags(req->rq_repmsg) & MSG_CONNECT_RECONNECT) {
871                 LASSERT(export->exp_imp_reverse);
872                 sptlrpc_svc_install_rvs_ctx(export->exp_imp_reverse,
873                                             req->rq_svc_ctx);
874                 GOTO(out, rc = 0);
875         }
876
877         spin_lock_bh(&target->obd_processing_task_lock);
878         if (target->obd_recovering && !export->exp_in_recovery) {
879                 spin_lock(&export->exp_lock);
880                 export->exp_in_recovery = 1;
881                 export->exp_req_replay_needed = 1;
882                 export->exp_lock_replay_needed = 1;                
883                 spin_unlock(&export->exp_lock);
884                 if ((lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_TRANSNO)
885                      && data->ocd_transno < target->obd_next_recovery_transno)
886                         target->obd_next_recovery_transno = data->ocd_transno;
887                 target->obd_connected_clients++;
888                 /* each connected client is counted as recoverable */
889                 target->obd_recoverable_clients++;
890                 atomic_inc(&target->obd_req_replay_clients);
891                 atomic_inc(&target->obd_lock_replay_clients);
892                 if (target->obd_connected_clients == 
893                     target->obd_max_recoverable_clients)
894                         wake_up(&target->obd_next_transno_waitq);
895         }
896         spin_unlock_bh(&target->obd_processing_task_lock);
897         memcpy(&conn,
898                lustre_msg_buf(req->rq_reqmsg, REQ_REC_OFF + 2, sizeof conn),
899                sizeof conn);
900
901         if (export->exp_imp_reverse != NULL) {
902                 /* destroyed import can be still referenced in ctxt */
903                 obd_set_info_async(export, strlen(KEY_REVIMP_UPD), 
904                                    KEY_REVIMP_UPD, 0, NULL, NULL);
905                 destroy_import(export->exp_imp_reverse);
906         }
907
908         /* for the rest part, we return -ENOTCONN in case of errors
909          * in order to let client initialize connection again.
910          */
911         revimp = export->exp_imp_reverse = class_new_import(target);
912         if (!revimp) {
913                 CERROR("fail to alloc new reverse import.\n");
914                 GOTO(out, rc = -ENOTCONN);
915         }
916
917         revimp->imp_connection = ptlrpc_connection_addref(export->exp_connection);
918         revimp->imp_client = &export->exp_obd->obd_ldlm_client;
919         revimp->imp_remote_handle = conn;
920         revimp->imp_dlm_fake = 1;
921         revimp->imp_state = LUSTRE_IMP_FULL;
922
923         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_NEXT_VER) {
924                 revimp->imp_msg_magic = LUSTRE_MSG_MAGIC_V2;
925                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_NEXT_VER);
926         }
927
928         rc = sptlrpc_import_get_sec(revimp, req->rq_svc_ctx,
929                                     req->rq_sec_flavor, 0);
930         if (rc) {
931                 CERROR("Failed to get sec for reverse import: %d\n", rc);
932                 export->exp_imp_reverse = NULL;
933                 class_destroy_import(revimp);
934         }
935
936         class_import_put(revimp);
937 out:
938         if (export) {
939                 spin_lock(&export->exp_lock);
940                 export->exp_connecting = 0;
941                 spin_unlock(&export->exp_lock);
942         }
943         if (targref)
944                 class_decref(targref);
945         if (rc)
946                 req->rq_status = rc;
947         RETURN(rc);
948 }
949
950 int target_handle_disconnect(struct ptlrpc_request *req)
951 {
952         int rc;
953         ENTRY;
954
955         rc = lustre_pack_reply(req, 1, NULL, NULL);
956         if (rc)
957                 RETURN(rc);
958
959         /* keep the rq_export around so we can send the reply */
960         req->rq_status = obd_disconnect(class_export_get(req->rq_export));
961         
962         RETURN(0);
963 }
964
965 void target_destroy_export(struct obd_export *exp)
966 {
967         /* exports created from last_rcvd data, and "fake"
968            exports created by lctl don't have an import */
969         if (exp->exp_imp_reverse != NULL)
970                 destroy_import(exp->exp_imp_reverse);
971
972         /* We cancel locks at disconnect time, but this will catch any locks
973          * granted in a race with recovery-induced disconnect. */
974         if (exp->exp_obd->obd_namespace != NULL)
975                 ldlm_cancel_locks_for_export(exp);
976 }
977
978 /*
979  * Recovery functions
980  */
981
982 struct ptlrpc_request *ptlrpc_clone_req( struct ptlrpc_request *orig_req)
983 {
984         struct ptlrpc_request *copy_req;
985         struct lustre_msg *copy_reqmsg;
986         struct ptlrpc_user_desc *udesc = NULL;
987
988         OBD_ALLOC_PTR(copy_req);
989         if (!copy_req)
990                 return NULL;
991         OBD_ALLOC(copy_reqmsg, orig_req->rq_reqlen);
992         if (!copy_reqmsg){
993                 OBD_FREE_PTR(copy_req);
994                 return NULL;
995         }
996
997         if (orig_req->rq_user_desc) {
998                 int ngroups = orig_req->rq_user_desc->pud_ngroups;
999
1000                 OBD_ALLOC(udesc, sptlrpc_user_desc_size(ngroups));
1001                 if (!udesc) {
1002                         OBD_FREE(copy_reqmsg, orig_req->rq_reqlen);
1003                         OBD_FREE_PTR(copy_req);
1004                         return NULL;
1005                 }
1006                 memcpy(udesc, orig_req->rq_user_desc,
1007                        sptlrpc_user_desc_size(ngroups));
1008         }
1009
1010         *copy_req = *orig_req;
1011         memcpy(copy_reqmsg, orig_req->rq_reqmsg, orig_req->rq_reqlen);
1012         copy_req->rq_reqmsg = copy_reqmsg;
1013         copy_req->rq_user_desc = udesc;
1014
1015         class_export_get(copy_req->rq_export);
1016         CFS_INIT_LIST_HEAD(&copy_req->rq_list);
1017         sptlrpc_svc_ctx_addref(copy_req);
1018
1019         if (copy_req->rq_reply_state) {
1020                 /* the copied req takes over the reply state */
1021                 orig_req->rq_reply_state = NULL;
1022                 /* to catch further access */
1023                 orig_req->rq_repmsg = NULL;
1024                 orig_req->rq_replen = 0;
1025         }
1026
1027         return copy_req;
1028 }
1029
1030 void ptlrpc_free_clone( struct ptlrpc_request *req)
1031 {
1032         if (req->rq_reply_state) {
1033                 ptlrpc_rs_decref(req->rq_reply_state);
1034                 req->rq_reply_state = NULL;
1035         }
1036
1037         sptlrpc_svc_ctx_decref(req);
1038         class_export_put(req->rq_export);
1039         list_del(&req->rq_list);
1040
1041         if (req->rq_user_desc) {
1042                 int ngroups = req->rq_user_desc->pud_ngroups;
1043                 OBD_FREE(req->rq_user_desc, sptlrpc_user_desc_size(ngroups));
1044         }
1045         OBD_FREE(req->rq_reqmsg, req->rq_reqlen);
1046         OBD_FREE_PTR(req);
1047 }
1048
1049 #ifdef __KERNEL__
1050 static void target_finish_recovery(struct obd_device *obd)
1051 {
1052         ENTRY;
1053         LCONSOLE_INFO("%s: sending delayed replies to recovered clients\n",
1054                       obd->obd_name);
1055
1056         ldlm_reprocess_all_ns(obd->obd_namespace);
1057
1058         /* when recovery finished, cleanup orphans on mds and ost */
1059         if (OBT(obd) && OBP(obd, postrecov)) {
1060                 int rc = OBP(obd, postrecov)(obd);
1061                 LCONSOLE_WARN("%s: recovery %s: rc %d\n", obd->obd_name,
1062                               rc < 0 ? "failed" : "complete", rc);
1063         }
1064
1065         obd->obd_recovery_end = CURRENT_SECONDS;
1066         EXIT;
1067 }
1068
1069 static void abort_req_replay_queue(struct obd_device *obd)
1070 {
1071         struct ptlrpc_request *req, *n;
1072
1073         list_for_each_entry_safe(req, n, &obd->obd_req_replay_queue, rq_list) {
1074                 DEBUG_REQ(D_WARNING, req, "aborted:");
1075                 req->rq_status = -ENOTCONN;
1076                 if (ptlrpc_error(req)) {
1077                         DEBUG_REQ(D_ERROR, req,
1078                                   "failed abort_req_reply; skipping");
1079                 }
1080                 ptlrpc_free_clone(req);
1081         }
1082 }
1083
1084 static void abort_lock_replay_queue(struct obd_device *obd)
1085 {
1086         struct ptlrpc_request *req, *n;
1087
1088         list_for_each_entry_safe(req, n, &obd->obd_lock_replay_queue, rq_list){
1089                 DEBUG_REQ(D_ERROR, req, "aborted:");
1090                 req->rq_status = -ENOTCONN;
1091                 if (ptlrpc_error(req)) { 
1092                         DEBUG_REQ(D_ERROR, req,
1093                                   "failed abort_lock_reply; skipping");
1094                 }
1095                 ptlrpc_free_clone(req);
1096         }
1097 }
1098 #endif
1099
1100 /* Called from a cleanup function if the device is being cleaned up
1101    forcefully.  The exports should all have been disconnected already,
1102    the only thing left to do is
1103      - clear the recovery flags
1104      - cancel the timer
1105      - free queued requests and replies, but don't send replies
1106    Because the obd_stopping flag is set, no new requests should be received.
1107
1108 */
1109 void target_cleanup_recovery(struct obd_device *obd)
1110 {
1111         struct ptlrpc_request *req, *n;
1112         ENTRY;
1113
1114         LASSERT(obd->obd_stopping);
1115
1116         spin_lock_bh(&obd->obd_processing_task_lock);
1117         if (!obd->obd_recovering) {
1118                 spin_unlock_bh(&obd->obd_processing_task_lock);
1119                 EXIT;
1120                 return;
1121         }
1122         obd->obd_recovering = obd->obd_abort_recovery = 0;
1123         target_cancel_recovery_timer(obd);
1124         spin_unlock_bh(&obd->obd_processing_task_lock);
1125
1126         list_for_each_entry_safe(req, n, &obd->obd_req_replay_queue, rq_list) {
1127                 LASSERT (req->rq_reply_state == 0);
1128                 ptlrpc_free_clone(req);
1129         }
1130         list_for_each_entry_safe(req, n, &obd->obd_lock_replay_queue, rq_list){
1131                 LASSERT (req->rq_reply_state == 0);
1132                 ptlrpc_free_clone(req);
1133         }
1134         list_for_each_entry_safe(req, n, &obd->obd_final_req_queue, rq_list) {
1135                 LASSERT (req->rq_reply_state == 0);
1136                 ptlrpc_free_clone(req);
1137         }
1138
1139         EXIT;
1140 }
1141
1142 static void target_recovery_expired(unsigned long castmeharder)
1143 {
1144         struct obd_device *obd = (struct obd_device *)castmeharder;
1145         CERROR("%s: recovery timed out, aborting\n", obd->obd_name);
1146         spin_lock_bh(&obd->obd_processing_task_lock);
1147         if (obd->obd_recovering)
1148                 obd->obd_abort_recovery = 1;
1149         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1150         spin_unlock_bh(&obd->obd_processing_task_lock);
1151 }
1152
1153
1154 /* obd_processing_task_lock should be held */
1155 void target_cancel_recovery_timer(struct obd_device *obd)
1156 {
1157         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1158         cfs_timer_disarm(&obd->obd_recovery_timer);
1159 }
1160
1161 static void reset_recovery_timer(struct obd_device *obd)
1162 {
1163         spin_lock_bh(&obd->obd_processing_task_lock);
1164         if (!obd->obd_recovering) {
1165                 spin_unlock_bh(&obd->obd_processing_task_lock);
1166                 return;
1167         }
1168         cfs_timer_arm(&obd->obd_recovery_timer,
1169                       cfs_time_shift(OBD_RECOVERY_TIMEOUT));
1170         spin_unlock_bh(&obd->obd_processing_task_lock);
1171         CDEBUG(D_HA, "%s: timer will expire in %u seconds\n", obd->obd_name,
1172                OBD_RECOVERY_TIMEOUT);
1173         /* Only used for lprocfs_status */
1174         obd->obd_recovery_end = CURRENT_SECONDS + OBD_RECOVERY_TIMEOUT;
1175 }
1176
1177
1178 /* Only start it the first time called */
1179 void target_start_recovery_timer(struct obd_device *obd)
1180 {
1181         spin_lock_bh(&obd->obd_processing_task_lock);
1182         if (obd->obd_recovery_handler
1183             || timer_pending((struct timer_list *)&obd->obd_recovery_timer)) {
1184                 spin_unlock_bh(&obd->obd_processing_task_lock);
1185                 return;
1186         }
1187         CWARN("%s: starting recovery timer (%us)\n", obd->obd_name,
1188               OBD_RECOVERY_TIMEOUT);
1189         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1190         spin_unlock_bh(&obd->obd_processing_task_lock);
1191
1192         reset_recovery_timer(obd);
1193 }
1194
1195 #ifdef __KERNEL__
1196 static int check_for_next_transno(struct obd_device *obd)
1197 {
1198         struct ptlrpc_request *req = NULL;
1199         int wake_up = 0, connected, completed, queue_len, max;
1200         __u64 next_transno, req_transno;
1201         ENTRY;
1202         spin_lock_bh(&obd->obd_processing_task_lock);
1203
1204         if (!list_empty(&obd->obd_req_replay_queue)) {
1205                 req = list_entry(obd->obd_req_replay_queue.next,
1206                                  struct ptlrpc_request, rq_list);
1207                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1208         } else {
1209                 req_transno = 0;
1210         }
1211
1212         max = obd->obd_max_recoverable_clients;
1213         connected = obd->obd_connected_clients;
1214         completed = connected - obd->obd_recoverable_clients;
1215         queue_len = obd->obd_requests_queued_for_recovery;
1216         next_transno = obd->obd_next_recovery_transno;
1217
1218         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1219                "req_transno: "LPU64", next_transno: "LPU64"\n",
1220                max, connected, completed, queue_len, req_transno, next_transno);
1221
1222         if (obd->obd_abort_recovery) {
1223                 CDEBUG(D_HA, "waking for aborted recovery\n");
1224                 wake_up = 1;
1225         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1226                 CDEBUG(D_HA, "waking for completed recovery\n");
1227                 wake_up = 1;
1228         } else if (req_transno == next_transno) {
1229                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1230                 wake_up = 1;
1231         } else if (queue_len + completed == max) {
1232                 /* handle gaps occured due to lost reply. It is allowed gaps
1233                  * because all clients are connected and there will be resend
1234                  * for missed transaction */
1235                 LASSERTF(req_transno >= next_transno,
1236                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1237                          req_transno, next_transno);
1238
1239                 CDEBUG(req_transno > obd->obd_last_committed ? D_ERROR : D_HA,
1240                        "waking for skipped transno (skip: "LPD64
1241                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1242                        next_transno, queue_len, completed, connected, req_transno);
1243                 obd->obd_next_recovery_transno = req_transno;
1244                 wake_up = 1;
1245         } else if (queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1246                 /* some clients haven't connected in time, but we can try
1247                  * to replay requests that demand on already committed ones
1248                  * also, we can replay first non-committed transation */
1249                 LASSERT(req_transno != 0);
1250                 if (req_transno == obd->obd_last_committed + 1) {
1251                         obd->obd_next_recovery_transno = req_transno;
1252                 } else if (req_transno > obd->obd_last_committed) {
1253                         /* can't continue recovery: have no needed transno */
1254                         obd->obd_abort_recovery = 1;
1255                         CDEBUG(D_ERROR, "abort due to missed clients. max: %d, "
1256                                "connected: %d, completed: %d, queue_len: %d, "
1257                                "req_transno: "LPU64", next_transno: "LPU64"\n",
1258                                max, connected, completed, queue_len,
1259                                req_transno, next_transno);
1260                 }
1261                 wake_up = 1;
1262         }
1263
1264         spin_unlock_bh(&obd->obd_processing_task_lock);
1265         return wake_up;
1266 }
1267
1268 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1269 {
1270         struct l_wait_info lwi = { 0 };
1271         struct ptlrpc_request *req;
1272
1273         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1274                obd->obd_next_recovery_transno);
1275         l_wait_event(obd->obd_next_transno_waitq,
1276                      check_for_next_transno(obd), &lwi);
1277
1278         spin_lock_bh(&obd->obd_processing_task_lock);
1279         if (obd->obd_abort_recovery) {
1280                 req = NULL;
1281         } else if (!list_empty(&obd->obd_req_replay_queue)) {
1282                 req = list_entry(obd->obd_req_replay_queue.next,
1283                                  struct ptlrpc_request, rq_list);
1284                 list_del_init(&req->rq_list);
1285                 obd->obd_requests_queued_for_recovery--;
1286         } else {
1287                 req = NULL;
1288         }
1289         spin_unlock_bh(&obd->obd_processing_task_lock);
1290         RETURN(req);
1291 }
1292
1293 static int check_for_next_lock(struct obd_device *obd)
1294 {
1295         struct ptlrpc_request *req = NULL;
1296         int wake_up = 0;
1297
1298         spin_lock_bh(&obd->obd_processing_task_lock);
1299         if (!list_empty(&obd->obd_lock_replay_queue)) {
1300                 req = list_entry(obd->obd_lock_replay_queue.next,
1301                                  struct ptlrpc_request, rq_list);
1302                 CDEBUG(D_HA, "waking for next lock\n");
1303                 wake_up = 1;
1304         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1305                 CDEBUG(D_HA, "waking for completed lock replay\n");
1306                 wake_up = 1;
1307         } else if (obd->obd_abort_recovery) {
1308                 CDEBUG(D_HA, "waking for aborted recovery\n");
1309                 wake_up = 1;
1310         }
1311         spin_unlock_bh(&obd->obd_processing_task_lock);
1312
1313         return wake_up;
1314 }
1315
1316 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1317 {
1318         struct l_wait_info lwi = { 0 };
1319         struct ptlrpc_request *req;
1320
1321         CDEBUG(D_HA, "Waiting for lock\n");
1322         l_wait_event(obd->obd_next_transno_waitq,
1323                      check_for_next_lock(obd), &lwi);
1324
1325         spin_lock_bh(&obd->obd_processing_task_lock);
1326         if (obd->obd_abort_recovery) {
1327                 req = NULL;
1328         } else if (!list_empty(&obd->obd_lock_replay_queue)) {
1329                 req = list_entry(obd->obd_lock_replay_queue.next,
1330                                  struct ptlrpc_request, rq_list);
1331                 list_del_init(&req->rq_list);
1332         } else {
1333                 req = NULL;
1334         }
1335         spin_unlock_bh(&obd->obd_processing_task_lock);
1336         return req;
1337 }
1338
1339 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1340 {
1341         struct ptlrpc_request *req;
1342
1343         spin_lock_bh(&obd->obd_processing_task_lock);
1344         if (!list_empty(&obd->obd_final_req_queue)) {
1345                 req = list_entry(obd->obd_final_req_queue.next,
1346                                  struct ptlrpc_request, rq_list);
1347                 list_del_init(&req->rq_list);
1348         } else {
1349                 req = NULL;
1350         }
1351         spin_unlock_bh(&obd->obd_processing_task_lock);
1352         return req;
1353 }
1354
1355 static inline int req_replay_done(struct obd_export *exp)
1356 {
1357         return (exp->exp_req_replay_needed == 0);
1358 }
1359
1360 static inline int lock_replay_done(struct obd_export *exp)
1361 {
1362         return (exp->exp_lock_replay_needed == 0);
1363 }
1364
1365 static inline int connect_done(struct obd_export *exp)
1366 {
1367         return (exp->exp_in_recovery != 0);
1368 }
1369
1370 static int check_for_clients(struct obd_device *obd)
1371 {
1372         if (obd->obd_abort_recovery)
1373                 return 1;
1374         LASSERT(obd->obd_connected_clients <= obd->obd_max_recoverable_clients);
1375         if (obd->obd_no_conn == 0 &&
1376             obd->obd_connected_clients == obd->obd_max_recoverable_clients)
1377                 return 1;
1378         return 0;
1379 }
1380
1381 static int handle_recovery_req(struct ptlrpc_thread *thread,
1382                                struct ptlrpc_request *req,
1383                                svc_handler_t handler)
1384 {
1385         int rc;
1386         ENTRY;
1387
1388         rc = lu_context_init(&req->rq_session, LCT_SESSION);
1389         if (rc) {
1390                 CERROR("Failure to initialize session: %d\n", rc);
1391                 return rc;
1392         }
1393         req->rq_session.lc_thread = thread;
1394         lu_context_enter(&req->rq_session);
1395         req->rq_svc_thread = thread;
1396         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
1397
1398         (void)handler(req);
1399
1400         lu_context_exit(&req->rq_session);
1401         lu_context_fini(&req->rq_session);
1402         /* don't reset timer for final stage */
1403         if (!req_replay_done(req->rq_export) ||
1404             !lock_replay_done(req->rq_export))
1405                 reset_recovery_timer(class_exp2obd(req->rq_export));
1406         ptlrpc_free_clone(req);
1407         RETURN(0);
1408 }
1409
1410 static int target_recovery_thread(void *arg)
1411 {
1412         struct obd_device *obd = arg;
1413         struct ptlrpc_request *req;
1414         struct target_recovery_data *trd = &obd->obd_recovery_data;
1415         struct l_wait_info lwi = { 0 };
1416         unsigned long delta;
1417         unsigned long flags;
1418         struct lu_env env;
1419         struct ptlrpc_thread fake_svc_thread, *thread = &fake_svc_thread;
1420         __u32 recov_ctx_tags = LCT_MD_THREAD;
1421         int rc = 0;
1422         ENTRY;
1423
1424         cfs_daemonize("tgt_recov");
1425
1426         SIGNAL_MASK_LOCK(current, flags);
1427         sigfillset(&current->blocked);
1428         RECALC_SIGPENDING;
1429         SIGNAL_MASK_UNLOCK(current, flags);
1430
1431         rc = lu_context_init(&env.le_ctx, recov_ctx_tags);
1432         if (rc)
1433                 RETURN(rc);
1434
1435         thread->t_env = &env;
1436         env.le_ctx.lc_thread = thread;
1437
1438         CERROR("%s: started recovery thread pid %d\n", obd->obd_name,
1439                current->pid);
1440         trd->trd_processing_task = current->pid;
1441
1442         obd->obd_recovering = 1;
1443         complete(&trd->trd_starting);
1444
1445         /* first of all, we have to know the first transno to replay */
1446         obd->obd_abort_recovery = 0;
1447         l_wait_event(obd->obd_next_transno_waitq,
1448                      check_for_clients(obd), &lwi);
1449
1450         spin_lock_bh(&obd->obd_processing_task_lock);
1451         target_cancel_recovery_timer(obd);
1452         spin_unlock_bh(&obd->obd_processing_task_lock);
1453
1454         /* If some clients haven't connected in time, evict them */
1455         if (obd->obd_abort_recovery) {
1456                 CWARN("Some clients haven't connect in time (%d/%d),"
1457                        "evict them\n", obd->obd_connected_clients,
1458                        obd->obd_max_recoverable_clients);
1459                 obd->obd_abort_recovery = obd->obd_stopping;
1460                 class_disconnect_stale_exports(obd, connect_done);
1461         }
1462         /* next stage: replay requests */
1463         delta = jiffies;
1464         obd->obd_req_replaying = 1;
1465         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
1466               atomic_read(&obd->obd_req_replay_clients),
1467               obd->obd_next_recovery_transno);
1468         while ((req = target_next_replay_req(obd))) {
1469                 LASSERT(trd->trd_processing_task == current->pid);
1470                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
1471                           lustre_msg_get_transno(req->rq_reqmsg),
1472                           libcfs_nid2str(req->rq_peer.nid));
1473
1474                 handle_recovery_req(thread, req,
1475                                     trd->trd_recovery_handler);
1476                 obd->obd_replayed_requests++;
1477                 spin_lock_bh(&obd->obd_processing_task_lock);
1478                 obd->obd_next_recovery_transno++;
1479                 spin_unlock_bh(&obd->obd_processing_task_lock);
1480         }
1481
1482         spin_lock_bh(&obd->obd_processing_task_lock);
1483         target_cancel_recovery_timer(obd);
1484         spin_unlock_bh(&obd->obd_processing_task_lock);
1485
1486         /* If some clients haven't replayed requests in time, evict them */
1487         if (obd->obd_abort_recovery) {
1488                 CDEBUG(D_ERROR, "req replay timed out, aborting ...\n");
1489                 obd->obd_abort_recovery = obd->obd_stopping;
1490                 class_disconnect_stale_exports(obd, req_replay_done);
1491                 abort_req_replay_queue(obd);
1492         }
1493         /* The second stage: replay locks */
1494         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
1495                atomic_read(&obd->obd_lock_replay_clients));
1496         while ((req = target_next_replay_lock(obd))) {
1497                 LASSERT(trd->trd_processing_task == current->pid);
1498                 DEBUG_REQ(D_HA|D_WARNING, req, "processing lock from %s: ",
1499                           libcfs_nid2str(req->rq_peer.nid));
1500                 handle_recovery_req(thread, req,
1501                                     trd->trd_recovery_handler);
1502                 obd->obd_replayed_locks++;
1503         }
1504
1505         spin_lock_bh(&obd->obd_processing_task_lock);
1506         target_cancel_recovery_timer(obd);
1507         spin_unlock_bh(&obd->obd_processing_task_lock);
1508         /* If some clients haven't replayed requests in time, evict them */
1509         if (obd->obd_abort_recovery) {
1510                 int stale;
1511                 CERROR("lock replay timed out, aborting ...\n");
1512                 obd->obd_abort_recovery = obd->obd_stopping;
1513                 stale = class_disconnect_stale_exports(obd, lock_replay_done);
1514                 abort_lock_replay_queue(obd);
1515         }
1516
1517         /* We drop recoverying flag to forward all new requests
1518          * to regular mds_handle() since now */
1519         spin_lock_bh(&obd->obd_processing_task_lock);
1520         obd->obd_recovering = obd->obd_abort_recovery = 0;
1521         spin_unlock_bh(&obd->obd_processing_task_lock);
1522         /* The third stage: reply on final pings */
1523         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
1524         while ((req = target_next_final_ping(obd))) {
1525                 LASSERT(trd->trd_processing_task == current->pid);
1526                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
1527                           libcfs_nid2str(req->rq_peer.nid));
1528                 handle_recovery_req(thread, req,
1529                                     trd->trd_recovery_handler);
1530         }
1531
1532         delta = (jiffies - delta) / HZ;
1533         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
1534               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
1535         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
1536         LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
1537         if (delta > obd_timeout * 2) {
1538                 CWARN("too long recovery - read logs\n");
1539                 libcfs_debug_dumplog();
1540         }
1541
1542         target_finish_recovery(obd);
1543
1544         lu_env_fini(&env);
1545         trd->trd_processing_task = 0;
1546         complete(&trd->trd_finishing);
1547         RETURN(rc);
1548 }
1549
1550 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1551 {
1552         int rc = 0;
1553         struct target_recovery_data *trd = &obd->obd_recovery_data;
1554
1555         memset(trd, 0, sizeof(*trd));
1556         init_completion(&trd->trd_starting);
1557         init_completion(&trd->trd_finishing);
1558         trd->trd_recovery_handler = handler;
1559
1560         if (kernel_thread(target_recovery_thread, obd, 0) > 0) {
1561                 wait_for_completion(&trd->trd_starting);
1562                 LASSERT(obd->obd_recovering != 0);
1563         } else
1564                 rc = -ECHILD;
1565
1566         return rc;
1567 }
1568
1569 void target_stop_recovery_thread(struct obd_device *obd)
1570 {
1571         spin_lock_bh(&obd->obd_processing_task_lock);
1572         if (obd->obd_recovery_data.trd_processing_task > 0) {
1573                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1574                 CERROR("%s: Aborting recovery\n", obd->obd_name);
1575                 obd->obd_abort_recovery = 1;
1576                 wake_up(&obd->obd_next_transno_waitq);
1577                 spin_unlock_bh(&obd->obd_processing_task_lock);
1578                 wait_for_completion(&trd->trd_finishing);
1579         } else {
1580                 spin_unlock_bh(&obd->obd_processing_task_lock);
1581         }
1582 }
1583
1584 void target_recovery_fini(struct obd_device *obd)
1585 {
1586         class_disconnect_exports(obd);
1587         target_stop_recovery_thread(obd);
1588         target_cleanup_recovery(obd);
1589 }
1590 EXPORT_SYMBOL(target_recovery_fini);
1591
1592 void target_recovery_init(struct obd_device *obd, svc_handler_t handler)
1593 {
1594         if (obd->obd_max_recoverable_clients == 0)
1595                 return;
1596         
1597         CWARN("RECOVERY: service %s, %d recoverable clients, "
1598               "last_transno "LPU64"\n", obd->obd_name,
1599               obd->obd_max_recoverable_clients, obd->obd_last_committed);
1600         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
1601         target_start_recovery_thread(obd, handler);
1602         obd->obd_recovery_start = CURRENT_SECONDS;
1603         /* Only used for lprocfs_status */
1604         obd->obd_recovery_end = obd->obd_recovery_start + OBD_RECOVERY_TIMEOUT;
1605 }
1606 EXPORT_SYMBOL(target_recovery_init);
1607
1608 #endif
1609
1610 int target_process_req_flags(struct obd_device *obd, struct ptlrpc_request *req)
1611 {
1612         struct obd_export *exp = req->rq_export;
1613         LASSERT(exp != NULL);
1614         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1615                 /* client declares he's ready to replay locks */
1616                 spin_lock_bh(&obd->obd_processing_task_lock);
1617                 if (exp->exp_req_replay_needed) {
1618                         LASSERT(atomic_read(&obd->obd_req_replay_clients) > 0);
1619                         spin_lock(&exp->exp_lock);
1620                         exp->exp_req_replay_needed = 0;
1621                         spin_unlock(&exp->exp_lock);
1622                         atomic_dec(&obd->obd_req_replay_clients);
1623                         LASSERT(obd->obd_recoverable_clients > 0);
1624                         obd->obd_recoverable_clients--;
1625                         if (atomic_read(&obd->obd_req_replay_clients) == 0)
1626                                 CDEBUG(D_HA, "all clients have replayed reqs\n");
1627                         wake_up(&obd->obd_next_transno_waitq);
1628                 }
1629                 spin_unlock_bh(&obd->obd_processing_task_lock);
1630         }
1631         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1632                 /* client declares he's ready to complete recovery
1633                  * so, we put the request on th final queue */
1634                 spin_lock_bh(&obd->obd_processing_task_lock);
1635                 if (exp->exp_lock_replay_needed) {
1636                         LASSERT(atomic_read(&obd->obd_lock_replay_clients) > 0);
1637                         spin_lock(&exp->exp_lock);
1638                         exp->exp_lock_replay_needed = 0;
1639                         spin_unlock(&exp->exp_lock);
1640                         atomic_dec(&obd->obd_lock_replay_clients);
1641                         if (atomic_read(&obd->obd_lock_replay_clients) == 0)
1642                                 CDEBUG(D_HA, "all clients have replayed locks\n");
1643                         wake_up(&obd->obd_next_transno_waitq);
1644                 }
1645                 spin_unlock_bh(&obd->obd_processing_task_lock);
1646         }
1647
1648         return 0;
1649 }
1650
1651 int target_queue_recovery_request(struct ptlrpc_request *req,
1652                                   struct obd_device *obd)
1653 {
1654         struct list_head *tmp;
1655         int inserted = 0;
1656         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1657
1658         ENTRY;
1659
1660         if (obd->obd_recovery_data.trd_processing_task == cfs_curproc_pid()) {
1661                 /* Processing the queue right now, don't re-add. */
1662                 RETURN(1);
1663         }
1664
1665         target_process_req_flags(obd, req);
1666
1667         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1668                 /* client declares he's ready to complete recovery
1669                  * so, we put the request on th final queue */
1670                 req = ptlrpc_clone_req(req);
1671                 if (req == NULL)
1672                         RETURN(-ENOMEM);
1673                 DEBUG_REQ(D_HA, req, "queue final req");
1674                 spin_lock_bh(&obd->obd_processing_task_lock);
1675                 if (obd->obd_recovering)
1676                         list_add_tail(&req->rq_list, &obd->obd_final_req_queue);
1677                 else {
1678                         spin_unlock_bh(&obd->obd_processing_task_lock);
1679                         ptlrpc_free_clone(req);
1680                         if (obd->obd_stopping) {
1681                                 RETURN(-ENOTCONN);
1682                         } else {
1683                                 RETURN(1);
1684                         }
1685                 }
1686                 spin_unlock_bh(&obd->obd_processing_task_lock);
1687                 RETURN(0);
1688         }
1689         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1690                 /* client declares he's ready to replay locks */
1691                 req = ptlrpc_clone_req(req);
1692                 if (req == NULL)
1693                         RETURN(-ENOMEM);
1694                 DEBUG_REQ(D_HA, req, "queue lock replay req");
1695                 spin_lock_bh(&obd->obd_processing_task_lock);
1696                 LASSERT(obd->obd_recovering);
1697                 /* usually due to recovery abort */
1698                 if (!req->rq_export->exp_in_recovery) {
1699                         spin_unlock_bh(&obd->obd_processing_task_lock);
1700                         ptlrpc_free_clone(req);
1701                         RETURN(-ENOTCONN);
1702                 }
1703                 LASSERT(req->rq_export->exp_lock_replay_needed);
1704                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
1705                 spin_unlock_bh(&obd->obd_processing_task_lock);
1706                 wake_up(&obd->obd_next_transno_waitq);
1707                 RETURN(0);
1708         }
1709
1710         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1711          * (i.e. buflens etc are in my own byte order), but type-dependent
1712          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1713
1714         if (!transno) {
1715                 CFS_INIT_LIST_HEAD(&req->rq_list);
1716                 DEBUG_REQ(D_HA, req, "not queueing");
1717                 RETURN(1);
1718         }
1719
1720         spin_lock_bh(&obd->obd_processing_task_lock);
1721
1722         /* If we're processing the queue, we want don't want to queue this
1723          * message.
1724          *
1725          * Also, if this request has a transno less than the one we're waiting
1726          * for, we should process it now.  It could (and currently always will)
1727          * be an open request for a descriptor that was opened some time ago.
1728          *
1729          * Also, a resent, replayed request that has already been
1730          * handled will pass through here and be processed immediately.
1731          */
1732         CWARN("Next recovery transno: "LPU64", current: "LPU64", replaying: %i\n",
1733               obd->obd_next_recovery_transno, transno, obd->obd_req_replaying);
1734         if (transno < obd->obd_next_recovery_transno && obd->obd_req_replaying) {
1735                 /* Processing the queue right now, don't re-add. */
1736                 LASSERT(list_empty(&req->rq_list));
1737                 spin_unlock_bh(&obd->obd_processing_task_lock);
1738                 RETURN(1);
1739         }
1740         spin_unlock_bh(&obd->obd_processing_task_lock);
1741
1742         /* A resent, replayed request that is still on the queue; just drop it.
1743            The queued request will handle this. */
1744         if ((lustre_msg_get_flags(req->rq_reqmsg) & (MSG_RESENT|MSG_REPLAY)) ==
1745             (MSG_RESENT | MSG_REPLAY)) {
1746                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1747                 RETURN(0);
1748         }
1749
1750         req = ptlrpc_clone_req(req);
1751         if (req == NULL)
1752                 RETURN(-ENOMEM);
1753
1754         spin_lock_bh(&obd->obd_processing_task_lock);
1755         LASSERT(obd->obd_recovering);
1756         if (!req->rq_export->exp_in_recovery) {
1757                 spin_unlock_bh(&obd->obd_processing_task_lock);
1758                 ptlrpc_free_clone(req);
1759                 RETURN(-ENOTCONN);
1760         }
1761         LASSERT(req->rq_export->exp_req_replay_needed);
1762
1763         /* XXX O(n^2) */
1764         list_for_each(tmp, &obd->obd_req_replay_queue) {
1765                 struct ptlrpc_request *reqiter =
1766                         list_entry(tmp, struct ptlrpc_request, rq_list);
1767
1768                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
1769                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1770                         inserted = 1;
1771                         break;
1772                 }
1773         }
1774
1775         if (!inserted)
1776                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
1777
1778         obd->obd_requests_queued_for_recovery++;
1779         wake_up(&obd->obd_next_transno_waitq);
1780         spin_unlock_bh(&obd->obd_processing_task_lock);
1781         RETURN(0);
1782
1783 }
1784
1785 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1786 {
1787         return req->rq_export->exp_obd;
1788 }
1789
1790 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
1791 {
1792         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1793                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1794                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1795                 return (-ECOMM);
1796         }
1797
1798         if (unlikely(rc)) {
1799                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1800                 req->rq_status = rc;
1801                 return (ptlrpc_error(req));
1802         } else {
1803                 DEBUG_REQ(D_NET, req, "sending reply");
1804         }
1805
1806         return (ptlrpc_send_reply(req, 1));
1807 }
1808
1809 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1810 {
1811         int                        netrc;
1812         struct ptlrpc_reply_state *rs;
1813         struct obd_device         *obd;
1814         struct obd_export         *exp;
1815         struct ptlrpc_service     *svc;
1816
1817         svc = req->rq_rqbd->rqbd_service;
1818         rs = req->rq_reply_state;
1819         if (rs == NULL || !rs->rs_difficult) {
1820                 /* no notifiers */
1821                 target_send_reply_msg (req, rc, fail_id);
1822                 return;
1823         }
1824
1825         /* must be an export if locks saved */
1826         LASSERT (req->rq_export != NULL);
1827         /* req/reply consistent */
1828         LASSERT (rs->rs_service == svc);
1829
1830         /* "fresh" reply */
1831         LASSERT (!rs->rs_scheduled);
1832         LASSERT (!rs->rs_scheduled_ever);
1833         LASSERT (!rs->rs_handled);
1834         LASSERT (!rs->rs_on_net);
1835         LASSERT (rs->rs_export == NULL);
1836         LASSERT (list_empty(&rs->rs_obd_list));
1837         LASSERT (list_empty(&rs->rs_exp_list));
1838
1839         exp = class_export_get (req->rq_export);
1840         obd = exp->exp_obd;
1841
1842         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1843         rs->rs_scheduled = 1;
1844         rs->rs_on_net    = 1;
1845         rs->rs_xid       = req->rq_xid;
1846         rs->rs_transno   = req->rq_transno;
1847         rs->rs_export    = exp;
1848
1849         spin_lock(&obd->obd_uncommitted_replies_lock);
1850
1851         if (rs->rs_transno > obd->obd_last_committed) {
1852                 /* not committed already */
1853                 list_add_tail (&rs->rs_obd_list,
1854                                &obd->obd_uncommitted_replies);
1855         }
1856
1857         spin_unlock (&obd->obd_uncommitted_replies_lock);
1858         spin_lock (&exp->exp_lock);
1859
1860         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1861
1862         spin_unlock(&exp->exp_lock);
1863
1864         netrc = target_send_reply_msg (req, rc, fail_id);
1865
1866         spin_lock(&svc->srv_lock);
1867
1868         svc->srv_n_difficult_replies++;
1869
1870         if (netrc != 0) {
1871                 /* error sending: reply is off the net.  Also we need +1
1872                  * reply ref until ptlrpc_server_handle_reply() is done
1873                  * with the reply state (if the send was successful, there
1874                  * would have been +1 ref for the net, which
1875                  * reply_out_callback leaves alone) */
1876                 rs->rs_on_net = 0;
1877                 ptlrpc_rs_addref(rs);
1878                 atomic_inc (&svc->srv_outstanding_replies);
1879         }
1880
1881         if (!rs->rs_on_net ||                   /* some notifier */
1882             list_empty(&rs->rs_exp_list) ||     /* completed already */
1883             list_empty(&rs->rs_obd_list)) {
1884                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1885                 cfs_waitq_signal (&svc->srv_waitq);
1886         } else {
1887                 list_add (&rs->rs_list, &svc->srv_active_replies);
1888                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1889         }
1890
1891         spin_unlock(&svc->srv_lock);
1892 }
1893
1894 int target_handle_ping(struct ptlrpc_request *req)
1895 {
1896         obd_ping(req->rq_export);
1897         return lustre_pack_reply(req, 1, NULL, NULL);
1898 }
1899
1900 void target_committed_to_req(struct ptlrpc_request *req)
1901 {
1902         struct obd_device *obd;
1903
1904         if (req == NULL || req->rq_export == NULL)
1905                 return;
1906
1907         obd = req->rq_export->exp_obd;
1908         if (obd == NULL)
1909                 return;
1910
1911         if (!obd->obd_no_transno && req->rq_repmsg != NULL)
1912                 lustre_msg_set_last_committed(req->rq_repmsg,
1913                                               obd->obd_last_committed);
1914         else
1915                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update");
1916
1917         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
1918                obd->obd_last_committed, req->rq_transno, req->rq_xid);
1919 }
1920
1921 EXPORT_SYMBOL(target_committed_to_req);
1922
1923 #ifdef HAVE_QUOTA_SUPPORT
1924 int target_handle_qc_callback(struct ptlrpc_request *req)
1925 {
1926         struct obd_quotactl *oqctl;
1927         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
1928
1929         oqctl = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*oqctl),
1930                                    lustre_swab_obd_quotactl);
1931         if (oqctl == NULL) {
1932                 CERROR("Can't unpack obd_quotactl\n");
1933                 RETURN(-EPROTO);
1934         }
1935
1936         cli->cl_qchk_stat = oqctl->qc_stat;
1937
1938         return 0;
1939 }
1940
1941 int target_handle_dqacq_callback(struct ptlrpc_request *req)
1942 {
1943 #ifdef __KERNEL__
1944         struct obd_device *obd = req->rq_export->exp_obd;
1945         struct obd_device *master_obd;
1946         struct lustre_quota_ctxt *qctxt;
1947         struct qunit_data *qdata;
1948         void* rep;
1949         struct qunit_data_old *qdata_old;
1950         int rc = 0;
1951         int repsize[2] = { sizeof(struct ptlrpc_body),
1952                            sizeof(struct qunit_data) };
1953         ENTRY;
1954
1955         rc = lustre_pack_reply(req, 2, repsize, NULL);
1956         if (rc) {
1957                 CERROR("packing reply failed!: rc = %d\n", rc);
1958                 RETURN(rc);
1959         }
1960         LASSERT(req->rq_export);
1961
1962         /* fixed for bug10707 */
1963         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
1964             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
1965                 CDEBUG(D_QUOTA, "qd_count is 64bit!\n");
1966                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
1967                                      sizeof(struct qunit_data));
1968                 LASSERT(rep);
1969                 qdata = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata),
1970                                            lustre_swab_qdata);
1971         } else {
1972                 CDEBUG(D_QUOTA, "qd_count is 32bit!\n");
1973                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
1974                                      sizeof(struct qunit_data_old));
1975                 LASSERT(rep);
1976                 qdata_old = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata_old),
1977                                                lustre_swab_qdata_old);
1978                 qdata = lustre_quota_old_to_new(qdata_old);
1979         }
1980
1981         if (qdata == NULL) {
1982                 CERROR("Can't unpack qunit_data\n");
1983                 RETURN(-EPROTO);
1984         }
1985
1986         /* we use the observer */
1987         LASSERT(obd->obd_observer && obd->obd_observer->obd_observer);
1988         master_obd = obd->obd_observer->obd_observer;
1989         qctxt = &master_obd->u.obt.obt_qctxt;
1990
1991         LASSERT(qctxt->lqc_handler);
1992         rc = qctxt->lqc_handler(master_obd, qdata,
1993                                 lustre_msg_get_opc(req->rq_reqmsg));
1994         if (rc && rc != -EDQUOT)
1995                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
1996                        "dqacq failed! (rc:%d)\n", rc);
1997
1998         /* the qd_count might be changed in lqc_handler */
1999         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2000             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2001                 memcpy(rep,qdata,sizeof(*qdata));
2002         } else {
2003                 qdata_old = lustre_quota_new_to_old(qdata);
2004                 memcpy(rep,qdata_old,sizeof(*qdata_old));
2005         }
2006         req->rq_status = rc;
2007         rc = ptlrpc_reply(req);
2008
2009         RETURN(rc);
2010 #else
2011         return 0;
2012 #endif /* !__KERNEL__ */
2013 }
2014 #endif /* HAVE_QUOTA_SUPPORT */
2015
2016 ldlm_mode_t lck_compat_array[] = {
2017         [LCK_EX] LCK_COMPAT_EX,
2018         [LCK_PW] LCK_COMPAT_PW,
2019         [LCK_PR] LCK_COMPAT_PR,
2020         [LCK_CW] LCK_COMPAT_CW,
2021         [LCK_CR] LCK_COMPAT_CR,
2022         [LCK_NL] LCK_COMPAT_NL,
2023         [LCK_GROUP] LCK_COMPAT_GROUP
2024 };