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