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