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 static void target_recovery_expired(unsigned long castmeharder)
1235 {
1236         struct obd_device *obd = (struct obd_device *)castmeharder;
1237         LCONSOLE_WARN("%s: recovery timed out; %d clients never reconnected "
1238                       "after %lds (%d clients did)\n",
1239                       obd->obd_name, obd->obd_recoverable_clients,
1240                       cfs_time_current_sec()- obd->obd_recovery_start,
1241                       obd->obd_connected_clients);
1242         spin_lock_bh(&obd->obd_processing_task_lock);
1243         if (obd->obd_recovering)
1244                 obd->obd_abort_recovery = 1;
1245         cfs_waitq_signal(&obd->obd_next_transno_waitq);
1246         spin_unlock_bh(&obd->obd_processing_task_lock);
1247 }
1248
1249
1250 /* obd_processing_task_lock should be held */
1251 void target_cancel_recovery_timer(struct obd_device *obd)
1252 {
1253         CDEBUG(D_HA, "%s: cancel recovery timer\n", obd->obd_name);
1254         cfs_timer_disarm(&obd->obd_recovery_timer);
1255 }
1256   
1257 /* extend = 1 means require at least "duration" seconds left in the timer,
1258    extend = 0 means set the total duration (start_recovery_timer) */
1259 static void reset_recovery_timer(struct obd_device *obd, int duration,
1260                                  int extend)
1261 {
1262         cfs_time_t now = cfs_time_current_sec();
1263         cfs_duration_t left;
1264
1265         spin_lock_bh(&obd->obd_processing_task_lock);
1266         if (!obd->obd_recovering || obd->obd_abort_recovery) {
1267                 spin_unlock_bh(&obd->obd_processing_task_lock);
1268                 return;
1269         }
1270
1271         left = cfs_time_sub(obd->obd_recovery_end, now);
1272
1273         if (extend && (duration > left))
1274                 obd->obd_recovery_timeout += duration - left;
1275         else if (!extend && (duration > obd->obd_recovery_timeout))
1276                 /* Track the client's largest expected replay time */
1277                 obd->obd_recovery_timeout = duration;
1278 #ifdef CRAY_XT3
1279         /* 
1280          * If total recovery time already exceed the 
1281          * obd_recovery_max_time, then CRAY XT3 will 
1282          * abort the recovery
1283          */
1284         if(obd->obd_recovery_timeout > obd->obd_recovery_max_time)
1285                 obd->obd_recovery_timeout = obd->obd_recovery_max_time;
1286 #endif
1287         obd->obd_recovery_end = obd->obd_recovery_start + 
1288                                 obd->obd_recovery_timeout;
1289         if (!cfs_timer_is_armed(&obd->obd_recovery_timer) ||
1290             cfs_time_before(now, obd->obd_recovery_end)) {
1291                 left = cfs_time_sub(obd->obd_recovery_end, now);
1292                 cfs_timer_arm(&obd->obd_recovery_timer, cfs_time_shift(left));
1293         }
1294         spin_unlock_bh(&obd->obd_processing_task_lock);
1295         CDEBUG(D_HA, "%s: recovery timer will expire in %u seconds\n",
1296                obd->obd_name, (unsigned)left);
1297 }
1298
1299 static void resume_recovery_timer(struct obd_device *obd)
1300 {
1301         LASSERT(!cfs_timer_is_armed(&obd->obd_recovery_timer));
1302
1303         /* to be safe, make it at least OBD_RECOVERY_FACTOR * obd_timeout */
1304         reset_recovery_timer(obd, OBD_RECOVERY_FACTOR * obd_timeout, 1);
1305 }
1306
1307 static void check_and_start_recovery_timer(struct obd_device *obd)
1308 {
1309         spin_lock_bh(&obd->obd_processing_task_lock);
1310         if (cfs_timer_is_armed(&obd->obd_recovery_timer)) {
1311                 spin_unlock_bh(&obd->obd_processing_task_lock);
1312                 return;
1313         }
1314         CWARN("%s: starting recovery timer\n", obd->obd_name);
1315         obd->obd_recovery_start = cfs_time_current_sec();
1316         /* minimum */
1317         obd->obd_recovery_timeout = OBD_RECOVERY_FACTOR * obd_timeout;
1318         spin_unlock_bh(&obd->obd_processing_task_lock);
1319
1320         reset_recovery_timer(obd, obd->obd_recovery_timeout, 0);
1321 }
1322
1323 /* Reset the timer with each new client connection */
1324 /*
1325  * This timer is actually reconnect_timer, which is for making sure 
1326  * the total recovery window is at least as big as my reconnect 
1327  * attempt timing. So the initial recovery time_out will be set to
1328  * OBD_RECOVERY_FACTOR * obd_timeout. If the timeout coming
1329  * from client is bigger than this, then the recovery time_out will
1330  * be extend to make sure the client could be reconnected, in the 
1331  * process, the timeout from the new client should be ignored.
1332  */
1333
1334 static void
1335 target_start_and_reset_recovery_timer(struct obd_device *obd,
1336                                       struct ptlrpc_request *req,
1337                                       int new_client)
1338 {
1339         int req_timeout = OBD_RECOVERY_FACTOR * 
1340                           lustre_msg_get_timeout(req->rq_reqmsg);
1341
1342         check_and_start_recovery_timer(obd);
1343
1344         if (req_timeout > obd->obd_recovery_timeout && !new_client)
1345                 reset_recovery_timer(obd, req_timeout, 0);
1346 }
1347
1348 #ifdef __KERNEL__
1349 static int check_for_next_transno(struct obd_device *obd)
1350 {
1351         struct ptlrpc_request *req = NULL;
1352         int wake_up = 0, connected, completed, queue_len, max;
1353         __u64 next_transno, req_transno;
1354         ENTRY;
1355         spin_lock_bh(&obd->obd_processing_task_lock);
1356
1357         if (!list_empty(&obd->obd_req_replay_queue)) {
1358                 req = list_entry(obd->obd_req_replay_queue.next,
1359                                  struct ptlrpc_request, rq_list);
1360                 req_transno = lustre_msg_get_transno(req->rq_reqmsg);
1361         } else {
1362                 req_transno = 0;
1363         }
1364
1365         max = obd->obd_max_recoverable_clients;
1366         connected = obd->obd_connected_clients;
1367         completed = connected - obd->obd_recoverable_clients;
1368         queue_len = obd->obd_requests_queued_for_recovery;
1369         next_transno = obd->obd_next_recovery_transno;
1370
1371         CDEBUG(D_HA, "max: %d, connected: %d, completed: %d, queue_len: %d, "
1372                "req_transno: "LPU64", next_transno: "LPU64"\n",
1373                max, connected, completed, queue_len, req_transno, next_transno);
1374
1375         if (obd->obd_abort_recovery) {
1376                 CDEBUG(D_HA, "waking for aborted recovery\n");
1377                 wake_up = 1;
1378         } else if (atomic_read(&obd->obd_req_replay_clients) == 0) {
1379                 CDEBUG(D_HA, "waking for completed recovery\n");
1380                 wake_up = 1;
1381         } else if (req_transno == next_transno) {
1382                 CDEBUG(D_HA, "waking for next ("LPD64")\n", next_transno);
1383                 wake_up = 1;
1384         } else if (queue_len + completed == max) {
1385                 /* handle gaps occured due to lost reply. It is allowed gaps
1386                  * because all clients are connected and there will be resend
1387                  * for missed transaction */
1388                 LASSERTF(req_transno >= next_transno,
1389                          "req_transno: "LPU64", next_transno: "LPU64"\n",
1390                          req_transno, next_transno);
1391
1392                 CDEBUG(req_transno > obd->obd_last_committed ? D_ERROR : D_HA,
1393                        "waking for skipped transno (skip: "LPD64
1394                        ", ql: %d, comp: %d, conn: %d, next: "LPD64")\n",
1395                        next_transno, queue_len, completed, connected, req_transno);
1396                 obd->obd_next_recovery_transno = req_transno;
1397                 wake_up = 1;
1398         } else if (queue_len == atomic_read(&obd->obd_req_replay_clients)) {
1399                 /* some clients haven't connected in time, but we can try
1400                  * to replay requests that demand on already committed ones
1401                  * also, we can replay first non-committed transation */
1402                 LASSERT(req_transno != 0);
1403                 if (req_transno == obd->obd_last_committed + 1) {
1404                         obd->obd_next_recovery_transno = req_transno;
1405                 } else if (req_transno > obd->obd_last_committed) {
1406                         /* can't continue recovery: have no needed transno */
1407                         obd->obd_abort_recovery = 1;
1408                         CDEBUG(D_ERROR, "abort due to missed clients. max: %d, "
1409                                "connected: %d, completed: %d, queue_len: %d, "
1410                                "req_transno: "LPU64", next_transno: "LPU64"\n",
1411                                max, connected, completed, queue_len,
1412                                req_transno, next_transno);
1413                 }
1414                 wake_up = 1;
1415         }
1416
1417         spin_unlock_bh(&obd->obd_processing_task_lock);
1418         return wake_up;
1419 }
1420
1421 static struct ptlrpc_request *target_next_replay_req(struct obd_device *obd)
1422 {
1423         struct l_wait_info lwi = { 0 };
1424         struct ptlrpc_request *req;
1425
1426         CDEBUG(D_HA, "Waiting for transno "LPD64"\n",
1427                obd->obd_next_recovery_transno);
1428         l_wait_event(obd->obd_next_transno_waitq,
1429                      check_for_next_transno(obd), &lwi);
1430
1431         spin_lock_bh(&obd->obd_processing_task_lock);
1432         if (obd->obd_abort_recovery) {
1433                 req = NULL;
1434         } else if (!list_empty(&obd->obd_req_replay_queue)) {
1435                 req = list_entry(obd->obd_req_replay_queue.next,
1436                                  struct ptlrpc_request, rq_list);
1437                 target_exp_dequeue_req_replay(req);
1438                 list_del_init(&req->rq_list);
1439                 obd->obd_requests_queued_for_recovery--;
1440         } else {
1441                 req = NULL;
1442         }
1443         spin_unlock_bh(&obd->obd_processing_task_lock);
1444         RETURN(req);
1445 }
1446
1447 static int check_for_next_lock(struct obd_device *obd)
1448 {
1449         struct ptlrpc_request *req = NULL;
1450         int wake_up = 0;
1451
1452         spin_lock_bh(&obd->obd_processing_task_lock);
1453         if (!list_empty(&obd->obd_lock_replay_queue)) {
1454                 req = list_entry(obd->obd_lock_replay_queue.next,
1455                                  struct ptlrpc_request, rq_list);
1456                 CDEBUG(D_HA, "waking for next lock\n");
1457                 wake_up = 1;
1458         } else if (atomic_read(&obd->obd_lock_replay_clients) == 0) {
1459                 CDEBUG(D_HA, "waking for completed lock replay\n");
1460                 wake_up = 1;
1461         } else if (obd->obd_abort_recovery) {
1462                 CDEBUG(D_HA, "waking for aborted recovery\n");
1463                 wake_up = 1;
1464         }
1465         spin_unlock_bh(&obd->obd_processing_task_lock);
1466
1467         return wake_up;
1468 }
1469
1470 static struct ptlrpc_request *target_next_replay_lock(struct obd_device *obd)
1471 {
1472         struct l_wait_info lwi = { 0 };
1473         struct ptlrpc_request *req;
1474
1475         CDEBUG(D_HA, "Waiting for lock\n");
1476         l_wait_event(obd->obd_next_transno_waitq,
1477                      check_for_next_lock(obd), &lwi);
1478
1479         spin_lock_bh(&obd->obd_processing_task_lock);
1480         if (obd->obd_abort_recovery) {
1481                 req = NULL;
1482         } else if (!list_empty(&obd->obd_lock_replay_queue)) {
1483                 req = list_entry(obd->obd_lock_replay_queue.next,
1484                                  struct ptlrpc_request, rq_list);
1485                 list_del_init(&req->rq_list);
1486         } else {
1487                 req = NULL;
1488         }
1489         spin_unlock_bh(&obd->obd_processing_task_lock);
1490         return req;
1491 }
1492
1493 static struct ptlrpc_request *target_next_final_ping(struct obd_device *obd)
1494 {
1495         struct ptlrpc_request *req;
1496
1497         spin_lock_bh(&obd->obd_processing_task_lock);
1498         if (!list_empty(&obd->obd_final_req_queue)) {
1499                 req = list_entry(obd->obd_final_req_queue.next,
1500                                  struct ptlrpc_request, rq_list);
1501                 list_del_init(&req->rq_list);
1502         } else {
1503                 req = NULL;
1504         }
1505         spin_unlock_bh(&obd->obd_processing_task_lock);
1506         return req;
1507 }
1508
1509 static inline int req_replay_done(struct obd_export *exp)
1510 {
1511         return (exp->exp_req_replay_needed == 0);
1512 }
1513
1514 static inline int lock_replay_done(struct obd_export *exp)
1515 {
1516         return (exp->exp_lock_replay_needed == 0);
1517 }
1518
1519 static inline int connect_done(struct obd_export *exp)
1520 {
1521         return (exp->exp_in_recovery != 0);
1522 }
1523
1524 static int check_for_clients(struct obd_device *obd)
1525 {
1526         if (obd->obd_abort_recovery)
1527                 return 1;
1528         LASSERT(obd->obd_connected_clients <= obd->obd_max_recoverable_clients);
1529         if (obd->obd_no_conn == 0 &&
1530             obd->obd_connected_clients == obd->obd_max_recoverable_clients)
1531                 return 1;
1532         return 0;
1533 }
1534
1535 static int handle_recovery_req(struct ptlrpc_thread *thread,
1536                                struct ptlrpc_request *req,
1537                                svc_handler_t handler)
1538 {
1539         int rc;
1540         ENTRY;
1541
1542         rc = lu_context_init(&req->rq_session, LCT_SESSION);
1543         if (rc) {
1544                 CERROR("Failure to initialize session: %d\n", rc);
1545                 return rc;
1546         }
1547         req->rq_session.lc_thread = thread;
1548         lu_context_enter(&req->rq_session);
1549         req->rq_svc_thread = thread;
1550         req->rq_svc_thread->t_env->le_ses = &req->rq_session;
1551
1552         /* thread context */
1553         lu_context_enter(&thread->t_env->le_ctx);
1554         (void)handler(req);
1555         lu_context_exit(&thread->t_env->le_ctx);
1556
1557         lu_context_exit(&req->rq_session);
1558         lu_context_fini(&req->rq_session);
1559         /* don't reset timer for final stage */
1560         if (!req_replay_done(req->rq_export) ||
1561             !lock_replay_done(req->rq_export))
1562                 reset_recovery_timer(class_exp2obd(req->rq_export),
1563                        OBD_RECOVERY_FACTOR * AT_OFF ? obd_timeout :
1564                        at_get(&req->rq_rqbd->rqbd_service->srv_at_estimate), 1);
1565         ptlrpc_free_clone(req);
1566         RETURN(0);
1567 }
1568
1569 static int target_recovery_thread(void *arg)
1570 {
1571         struct obd_device *obd = arg;
1572         struct ptlrpc_request *req;
1573         struct target_recovery_data *trd = &obd->obd_recovery_data;
1574         struct l_wait_info lwi = { 0 };
1575         unsigned long delta;
1576         unsigned long flags;
1577         struct lu_env env;
1578         struct ptlrpc_thread fake_svc_thread, *thread = &fake_svc_thread;
1579         __u32 recov_ctx_tags = LCT_MD_THREAD;
1580         int rc = 0;
1581         ENTRY;
1582
1583         cfs_daemonize("tgt_recov");
1584
1585         SIGNAL_MASK_LOCK(current, flags);
1586         sigfillset(&current->blocked);
1587         RECALC_SIGPENDING;
1588         SIGNAL_MASK_UNLOCK(current, flags);
1589
1590         rc = lu_context_init(&env.le_ctx, recov_ctx_tags);
1591         if (rc)
1592                 RETURN(rc);
1593
1594         thread->t_env = &env;
1595         env.le_ctx.lc_thread = thread;
1596
1597         CERROR("%s: started recovery thread pid %d\n", obd->obd_name,
1598                current->pid);
1599         trd->trd_processing_task = current->pid;
1600
1601         obd->obd_recovering = 1;
1602         complete(&trd->trd_starting);
1603
1604         /* first of all, we have to know the first transno to replay */
1605         obd->obd_abort_recovery = 0;
1606         l_wait_event(obd->obd_next_transno_waitq,
1607                      check_for_clients(obd), &lwi);
1608
1609         spin_lock_bh(&obd->obd_processing_task_lock);
1610         target_cancel_recovery_timer(obd);
1611         spin_unlock_bh(&obd->obd_processing_task_lock);
1612
1613         /* If some clients haven't connected in time, evict them */
1614         if (obd->obd_abort_recovery) {
1615                 CWARN("Some clients haven't connect in time (%d/%d),"
1616                        "evict them\n", obd->obd_connected_clients,
1617                        obd->obd_max_recoverable_clients);
1618                 obd->obd_abort_recovery = obd->obd_stopping;
1619                 class_disconnect_stale_exports(obd, connect_done);
1620         }
1621         /* next stage: replay requests */
1622         delta = jiffies;
1623         obd->obd_req_replaying = 1;
1624         CDEBUG(D_INFO, "1: request replay stage - %d clients from t"LPU64"\n",
1625               atomic_read(&obd->obd_req_replay_clients),
1626               obd->obd_next_recovery_transno);
1627         resume_recovery_timer(obd);
1628         while ((req = target_next_replay_req(obd))) {
1629                 LASSERT(trd->trd_processing_task == current->pid);
1630                 DEBUG_REQ(D_HA, req, "processing t"LPD64" from %s",
1631                           lustre_msg_get_transno(req->rq_reqmsg),
1632                           libcfs_nid2str(req->rq_peer.nid));
1633                 handle_recovery_req(thread, req,
1634                                     trd->trd_recovery_handler);
1635                 obd->obd_replayed_requests++;
1636                 spin_lock_bh(&obd->obd_processing_task_lock);
1637                 obd->obd_next_recovery_transno++;
1638                 spin_unlock_bh(&obd->obd_processing_task_lock);
1639         }
1640
1641         spin_lock_bh(&obd->obd_processing_task_lock);
1642         target_cancel_recovery_timer(obd);
1643         spin_unlock_bh(&obd->obd_processing_task_lock);
1644
1645         /* If some clients haven't replayed requests in time, evict them */
1646         if (obd->obd_abort_recovery) {
1647                 CDEBUG(D_ERROR, "req replay timed out, aborting ...\n");
1648                 obd->obd_abort_recovery = obd->obd_stopping;
1649                 class_disconnect_stale_exports(obd, req_replay_done);
1650                 abort_req_replay_queue(obd);
1651         }
1652
1653         /* The second stage: replay locks */
1654         CDEBUG(D_INFO, "2: lock replay stage - %d clients\n",
1655                atomic_read(&obd->obd_lock_replay_clients));
1656         resume_recovery_timer(obd);
1657         while ((req = target_next_replay_lock(obd))) {
1658                 LASSERT(trd->trd_processing_task == current->pid);
1659                 DEBUG_REQ(D_HA|D_WARNING, req, "processing lock from %s: ",
1660                           libcfs_nid2str(req->rq_peer.nid));
1661                 handle_recovery_req(thread, req,
1662                                     trd->trd_recovery_handler);
1663                 obd->obd_replayed_locks++;
1664         }
1665
1666         spin_lock_bh(&obd->obd_processing_task_lock);
1667         target_cancel_recovery_timer(obd);
1668         spin_unlock_bh(&obd->obd_processing_task_lock);
1669         /* If some clients haven't replayed requests in time, evict them */
1670         if (obd->obd_abort_recovery) {
1671                 int stale;
1672                 CERROR("lock replay timed out, aborting ...\n");
1673                 obd->obd_abort_recovery = obd->obd_stopping;
1674                 stale = class_disconnect_stale_exports(obd, lock_replay_done);
1675                 abort_lock_replay_queue(obd);
1676         }
1677
1678         /* We drop recoverying flag to forward all new requests
1679          * to regular mds_handle() since now */
1680         spin_lock_bh(&obd->obd_processing_task_lock);
1681         obd->obd_recovering = obd->obd_abort_recovery = 0;
1682         spin_unlock_bh(&obd->obd_processing_task_lock);
1683         /* The third stage: reply on final pings */
1684         CDEBUG(D_INFO, "3: final stage - process recovery completion pings\n");
1685         while ((req = target_next_final_ping(obd))) {
1686                 LASSERT(trd->trd_processing_task == current->pid);
1687                 DEBUG_REQ(D_HA, req, "processing final ping from %s: ",
1688                           libcfs_nid2str(req->rq_peer.nid));
1689                 handle_recovery_req(thread, req,
1690                                     trd->trd_recovery_handler);
1691         }
1692
1693         delta = (jiffies - delta) / HZ;
1694         CDEBUG(D_INFO,"4: recovery completed in %lus - %d/%d reqs/locks\n",
1695               delta, obd->obd_replayed_requests, obd->obd_replayed_locks);
1696         LASSERT(atomic_read(&obd->obd_req_replay_clients) == 0);
1697         LASSERT(atomic_read(&obd->obd_lock_replay_clients) == 0);
1698         if (delta > obd_timeout * 2) {
1699                 CWARN("too long recovery - read logs\n");
1700                 libcfs_debug_dumplog();
1701         }
1702
1703         target_finish_recovery(obd);
1704
1705         lu_context_fini(&env.le_ctx);
1706         trd->trd_processing_task = 0;
1707         complete(&trd->trd_finishing);
1708         RETURN(rc);
1709 }
1710
1711 int target_start_recovery_thread(struct obd_device *obd, svc_handler_t handler)
1712 {
1713         int rc = 0;
1714         struct target_recovery_data *trd = &obd->obd_recovery_data;
1715
1716         memset(trd, 0, sizeof(*trd));
1717         init_completion(&trd->trd_starting);
1718         init_completion(&trd->trd_finishing);
1719         trd->trd_recovery_handler = handler;
1720
1721         if (kernel_thread(target_recovery_thread, obd, 0) > 0) {
1722                 wait_for_completion(&trd->trd_starting);
1723                 LASSERT(obd->obd_recovering != 0);
1724         } else
1725                 rc = -ECHILD;
1726
1727         return rc;
1728 }
1729
1730 void target_stop_recovery_thread(struct obd_device *obd)
1731 {
1732         spin_lock_bh(&obd->obd_processing_task_lock);
1733         if (obd->obd_recovery_data.trd_processing_task > 0) {
1734                 struct target_recovery_data *trd = &obd->obd_recovery_data;
1735                 CERROR("%s: Aborting recovery\n", obd->obd_name);
1736                 obd->obd_abort_recovery = 1;
1737                 wake_up(&obd->obd_next_transno_waitq);
1738                 spin_unlock_bh(&obd->obd_processing_task_lock);
1739                 wait_for_completion(&trd->trd_finishing);
1740         } else {
1741                 spin_unlock_bh(&obd->obd_processing_task_lock);
1742         }
1743 }
1744
1745 void target_recovery_fini(struct obd_device *obd)
1746 {
1747         class_disconnect_exports(obd);
1748         target_stop_recovery_thread(obd);
1749         target_cleanup_recovery(obd);
1750 }
1751 EXPORT_SYMBOL(target_recovery_fini);
1752
1753 void target_recovery_init(struct obd_device *obd, svc_handler_t handler)
1754 {
1755         if (obd->obd_max_recoverable_clients == 0)
1756                 return;
1757
1758         CWARN("RECOVERY: service %s, %d recoverable clients, "
1759               "last_transno "LPU64"\n", obd->obd_name,
1760               obd->obd_max_recoverable_clients, obd->obd_last_committed);
1761         obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
1762         obd->obd_recovery_start = 0;
1763         obd->obd_recovery_end = 0;
1764         obd->obd_recovery_timeout = OBD_RECOVERY_FACTOR * obd_timeout;
1765         /* bz13079: this should be set to desired value for ost but not for mds */
1766         obd->obd_recovery_max_time = OBD_RECOVERY_MAX_TIME;
1767         cfs_timer_init(&obd->obd_recovery_timer, target_recovery_expired, obd);
1768         target_start_recovery_thread(obd, handler);
1769 }
1770 EXPORT_SYMBOL(target_recovery_init);
1771
1772 #endif
1773
1774 int target_process_req_flags(struct obd_device *obd, struct ptlrpc_request *req)
1775 {
1776         struct obd_export *exp = req->rq_export;
1777         LASSERT(exp != NULL);
1778         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1779                 /* client declares he's ready to replay locks */
1780                 spin_lock_bh(&obd->obd_processing_task_lock);
1781                 if (exp->exp_req_replay_needed) {
1782                         LASSERT(atomic_read(&obd->obd_req_replay_clients) > 0);
1783                         spin_lock(&exp->exp_lock);
1784                         exp->exp_req_replay_needed = 0;
1785                         spin_unlock(&exp->exp_lock);
1786                         atomic_dec(&obd->obd_req_replay_clients);
1787                         LASSERT(obd->obd_recoverable_clients > 0);
1788                         obd->obd_recoverable_clients--;
1789                         if (atomic_read(&obd->obd_req_replay_clients) == 0)
1790                                 CDEBUG(D_HA, "all clients have replayed reqs\n");
1791                         wake_up(&obd->obd_next_transno_waitq);
1792                 }
1793                 spin_unlock_bh(&obd->obd_processing_task_lock);
1794         }
1795         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1796                 /* client declares he's ready to complete recovery
1797                  * so, we put the request on th final queue */
1798                 spin_lock_bh(&obd->obd_processing_task_lock);
1799                 if (exp->exp_lock_replay_needed) {
1800                         LASSERT(atomic_read(&obd->obd_lock_replay_clients) > 0);
1801                         spin_lock(&exp->exp_lock);
1802                         exp->exp_lock_replay_needed = 0;
1803                         spin_unlock(&exp->exp_lock);
1804                         atomic_dec(&obd->obd_lock_replay_clients);
1805                         if (atomic_read(&obd->obd_lock_replay_clients) == 0)
1806                                 CDEBUG(D_HA, "all clients have replayed locks\n");
1807                         wake_up(&obd->obd_next_transno_waitq);
1808                 }
1809                 spin_unlock_bh(&obd->obd_processing_task_lock);
1810         }
1811
1812         return 0;
1813 }
1814
1815 int target_queue_recovery_request(struct ptlrpc_request *req,
1816                                   struct obd_device *obd)
1817 {
1818         struct list_head *tmp;
1819         int inserted = 0;
1820         __u64 transno = lustre_msg_get_transno(req->rq_reqmsg);
1821
1822         ENTRY;
1823
1824         if (obd->obd_recovery_data.trd_processing_task == cfs_curproc_pid()) {
1825                 /* Processing the queue right now, don't re-add. */
1826                 RETURN(1);
1827         }
1828
1829         target_process_req_flags(obd, req);
1830
1831         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_LOCK_REPLAY_DONE) {
1832                 /* client declares he's ready to complete recovery
1833                  * so, we put the request on th final queue */
1834                 req = ptlrpc_clone_req(req);
1835                 if (req == NULL)
1836                         RETURN(-ENOMEM);
1837                 DEBUG_REQ(D_HA, req, "queue final req");
1838                 spin_lock_bh(&obd->obd_processing_task_lock);
1839                 if (obd->obd_recovering)
1840                         list_add_tail(&req->rq_list, &obd->obd_final_req_queue);
1841                 else {
1842                         spin_unlock_bh(&obd->obd_processing_task_lock);
1843                         ptlrpc_free_clone(req);
1844                         if (obd->obd_stopping) {
1845                                 RETURN(-ENOTCONN);
1846                         } else {
1847                                 RETURN(1);
1848                         }
1849                 }
1850                 spin_unlock_bh(&obd->obd_processing_task_lock);
1851                 RETURN(0);
1852         }
1853         if (lustre_msg_get_flags(req->rq_reqmsg) & MSG_REQ_REPLAY_DONE) {
1854                 /* client declares he's ready to replay locks */
1855                 req = ptlrpc_clone_req(req);
1856                 if (req == NULL)
1857                         RETURN(-ENOMEM);
1858                 DEBUG_REQ(D_HA, req, "queue lock replay req");
1859                 spin_lock_bh(&obd->obd_processing_task_lock);
1860                 LASSERT(obd->obd_recovering);
1861                 /* usually due to recovery abort */
1862                 if (!req->rq_export->exp_in_recovery) {
1863                         spin_unlock_bh(&obd->obd_processing_task_lock);
1864                         ptlrpc_free_clone(req);
1865                         RETURN(-ENOTCONN);
1866                 }
1867                 LASSERT(req->rq_export->exp_lock_replay_needed);
1868                 list_add_tail(&req->rq_list, &obd->obd_lock_replay_queue);
1869                 spin_unlock_bh(&obd->obd_processing_task_lock);
1870                 wake_up(&obd->obd_next_transno_waitq);
1871                 RETURN(0);
1872         }
1873
1874         /* CAVEAT EMPTOR: The incoming request message has been swabbed
1875          * (i.e. buflens etc are in my own byte order), but type-dependent
1876          * buffers (eg mds_body, ost_body etc) have NOT been swabbed. */
1877
1878         if (!transno) {
1879                 CFS_INIT_LIST_HEAD(&req->rq_list);
1880                 DEBUG_REQ(D_HA, req, "not queueing");
1881                 RETURN(1);
1882         }
1883
1884         spin_lock_bh(&obd->obd_processing_task_lock);
1885
1886         /* If we're processing the queue, we want don't want to queue this
1887          * message.
1888          *
1889          * Also, if this request has a transno less than the one we're waiting
1890          * for, we should process it now.  It could (and currently always will)
1891          * be an open request for a descriptor that was opened some time ago.
1892          *
1893          * Also, a resent, replayed request that has already been
1894          * handled will pass through here and be processed immediately.
1895          */
1896         CWARN("Next recovery transno: "LPU64", current: "LPU64", replaying: %i\n",
1897               obd->obd_next_recovery_transno, transno, obd->obd_req_replaying);
1898         if (transno < obd->obd_next_recovery_transno && obd->obd_req_replaying) {
1899                 /* Processing the queue right now, don't re-add. */
1900                 LASSERT(list_empty(&req->rq_list));
1901                 spin_unlock_bh(&obd->obd_processing_task_lock);
1902                 RETURN(1);
1903         }
1904         spin_unlock_bh(&obd->obd_processing_task_lock);
1905
1906         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_DROP))
1907                 RETURN(0);
1908
1909         req = ptlrpc_clone_req(req);
1910         if (req == NULL)
1911                 RETURN(-ENOMEM);
1912
1913         spin_lock_bh(&obd->obd_processing_task_lock);
1914         LASSERT(obd->obd_recovering);
1915         if (!req->rq_export->exp_in_recovery) {
1916                 spin_unlock_bh(&obd->obd_processing_task_lock);
1917                 ptlrpc_free_clone(req);
1918                 RETURN(-ENOTCONN);
1919         }
1920         LASSERT(req->rq_export->exp_req_replay_needed);
1921
1922         if (target_exp_enqueue_req_replay(req)) {
1923                 spin_unlock_bh(&obd->obd_processing_task_lock);
1924                 DEBUG_REQ(D_ERROR, req, "dropping resent queued req");
1925                 ptlrpc_free_clone(req);
1926                 RETURN(0);
1927         }
1928
1929         /* XXX O(n^2) */
1930         list_for_each(tmp, &obd->obd_req_replay_queue) {
1931                 struct ptlrpc_request *reqiter =
1932                         list_entry(tmp, struct ptlrpc_request, rq_list);
1933
1934                 if (lustre_msg_get_transno(reqiter->rq_reqmsg) > transno) {
1935                         list_add_tail(&req->rq_list, &reqiter->rq_list);
1936                         inserted = 1;
1937                         break;
1938                 }
1939
1940                 if (unlikely(lustre_msg_get_transno(reqiter->rq_reqmsg) ==
1941                              transno)) {
1942                         DEBUG_REQ(D_ERROR, req, "dropping replay: transno "
1943                                   "has been claimed by another client");
1944                         spin_unlock_bh(&obd->obd_processing_task_lock);
1945                         target_exp_dequeue_req_replay(req);
1946                         ptlrpc_free_clone(req);
1947                         RETURN(0);
1948                 }
1949         }
1950
1951         if (!inserted)
1952                 list_add_tail(&req->rq_list, &obd->obd_req_replay_queue);
1953
1954         obd->obd_requests_queued_for_recovery++;
1955         wake_up(&obd->obd_next_transno_waitq);
1956         spin_unlock_bh(&obd->obd_processing_task_lock);
1957         RETURN(0);
1958 }
1959
1960 struct obd_device * target_req2obd(struct ptlrpc_request *req)
1961 {
1962         return req->rq_export->exp_obd;
1963 }
1964
1965 static inline struct ldlm_pool *ldlm_exp2pl(struct obd_export *exp)
1966 {
1967         LASSERT(exp != NULL);
1968         return &exp->exp_obd->obd_namespace->ns_pool;
1969 }
1970
1971 /**
1972  * Packs current SLV and Limit into \a req.
1973  */
1974 int target_pack_pool_reply(struct ptlrpc_request *req)
1975 {
1976         struct obd_device *obd;
1977         ENTRY;
1978    
1979         /* 
1980          * Check that we still have all structures alive as this may 
1981          * be some late rpc in shutdown time.
1982          */
1983         if (unlikely(!req->rq_export || !req->rq_export->exp_obd ||
1984                      !exp_connect_lru_resize(req->rq_export))) {
1985                 lustre_msg_set_slv(req->rq_repmsg, 0);
1986                 lustre_msg_set_limit(req->rq_repmsg, 0);
1987                 RETURN(0);
1988         }
1989
1990         /* 
1991          * OBD is alive here as export is alive, which we checked above. 
1992          */
1993         obd = req->rq_export->exp_obd;
1994
1995         read_lock(&obd->obd_pool_lock);
1996         lustre_msg_set_slv(req->rq_repmsg, obd->obd_pool_slv);
1997         lustre_msg_set_limit(req->rq_repmsg, obd->obd_pool_limit);
1998         read_unlock(&obd->obd_pool_lock);
1999
2000         RETURN(0);
2001 }
2002
2003 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
2004 {
2005         if (OBD_FAIL_CHECK_ORSET(fail_id & ~OBD_FAIL_ONCE, OBD_FAIL_ONCE)) {
2006                 DEBUG_REQ(D_ERROR, req, "dropping reply");
2007                 return (-ECOMM);
2008         }
2009
2010         if (unlikely(rc)) {
2011                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
2012                 req->rq_status = rc;
2013                 return (ptlrpc_send_error(req, 1));
2014         } else {
2015                 DEBUG_REQ(D_NET, req, "sending reply");
2016         }
2017
2018         return (ptlrpc_send_reply(req, PTLRPC_REPLY_MAYBE_DIFFICULT));
2019 }
2020
2021 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
2022 {
2023         int                        netrc;
2024         struct ptlrpc_reply_state *rs;
2025         struct obd_device         *obd;
2026         struct obd_export         *exp;
2027         struct ptlrpc_service     *svc;
2028
2029         if (req->rq_no_reply)
2030                 return;
2031
2032         svc = req->rq_rqbd->rqbd_service;
2033         rs = req->rq_reply_state;
2034         if (rs == NULL || !rs->rs_difficult) {
2035                 /* no notifiers */
2036                 target_send_reply_msg (req, rc, fail_id);
2037                 return;
2038         }
2039
2040         /* must be an export if locks saved */
2041         LASSERT (req->rq_export != NULL);
2042         /* req/reply consistent */
2043         LASSERT (rs->rs_service == svc);
2044
2045         /* "fresh" reply */
2046         LASSERT (!rs->rs_scheduled);
2047         LASSERT (!rs->rs_scheduled_ever);
2048         LASSERT (!rs->rs_handled);
2049         LASSERT (!rs->rs_on_net);
2050         LASSERT (rs->rs_export == NULL);
2051         LASSERT (list_empty(&rs->rs_obd_list));
2052         LASSERT (list_empty(&rs->rs_exp_list));
2053
2054         exp = class_export_get (req->rq_export);
2055         obd = exp->exp_obd;
2056
2057         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
2058         rs->rs_scheduled = 1;
2059         rs->rs_on_net    = 1;
2060         rs->rs_xid       = req->rq_xid;
2061         rs->rs_transno   = req->rq_transno;
2062         rs->rs_export    = exp;
2063
2064         spin_lock(&obd->obd_uncommitted_replies_lock);
2065
2066         if (rs->rs_transno > obd->obd_last_committed) {
2067                 /* not committed already */
2068                 list_add_tail (&rs->rs_obd_list,
2069                                &obd->obd_uncommitted_replies);
2070         }
2071
2072         spin_unlock (&obd->obd_uncommitted_replies_lock);
2073         spin_lock (&exp->exp_lock);
2074
2075         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
2076
2077         spin_unlock(&exp->exp_lock);
2078
2079         netrc = target_send_reply_msg (req, rc, fail_id);
2080
2081         spin_lock(&svc->srv_lock);
2082
2083         svc->srv_n_difficult_replies++;
2084
2085         if (netrc != 0) {
2086                 /* error sending: reply is off the net.  Also we need +1
2087                  * reply ref until ptlrpc_server_handle_reply() is done
2088                  * with the reply state (if the send was successful, there
2089                  * would have been +1 ref for the net, which
2090                  * reply_out_callback leaves alone) */
2091                 rs->rs_on_net = 0;
2092                 ptlrpc_rs_addref(rs);
2093                 atomic_inc (&svc->srv_outstanding_replies);
2094         }
2095
2096         if (!rs->rs_on_net ||                   /* some notifier */
2097             list_empty(&rs->rs_exp_list) ||     /* completed already */
2098             list_empty(&rs->rs_obd_list)) {
2099                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
2100                 cfs_waitq_signal (&svc->srv_waitq);
2101         } else {
2102                 list_add (&rs->rs_list, &svc->srv_active_replies);
2103                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
2104         }
2105
2106         spin_unlock(&svc->srv_lock);
2107 }
2108
2109 int target_handle_ping(struct ptlrpc_request *req)
2110 {
2111         obd_ping(req->rq_export);
2112         return req_capsule_server_pack(&req->rq_pill);
2113 }
2114
2115 void target_committed_to_req(struct ptlrpc_request *req)
2116 {
2117         struct obd_device *obd;
2118
2119         if (req == NULL || req->rq_export == NULL)
2120                 return;
2121
2122         obd = req->rq_export->exp_obd;
2123         if (obd == NULL)
2124                 return;
2125
2126         if (!obd->obd_no_transno && req->rq_repmsg != NULL)
2127                 lustre_msg_set_last_committed(req->rq_repmsg,
2128                                               obd->obd_last_committed);
2129         else
2130                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update (%d/"
2131                           "%d)", obd->obd_no_transno, req->rq_repmsg == NULL);
2132
2133         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
2134                obd->obd_last_committed, req->rq_transno, req->rq_xid);
2135 }
2136
2137 EXPORT_SYMBOL(target_committed_to_req);
2138
2139 #ifdef HAVE_QUOTA_SUPPORT
2140 int target_handle_qc_callback(struct ptlrpc_request *req)
2141 {
2142         struct obd_quotactl *oqctl;
2143         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
2144
2145         oqctl = req_capsule_client_get(&req->rq_pill, &RMF_OBD_QUOTACTL);
2146         if (oqctl == NULL)
2147                 RETURN(-EPROTO);
2148
2149         cli->cl_qchk_stat = oqctl->qc_stat;
2150
2151         return 0;
2152 }
2153
2154 int target_handle_dqacq_callback(struct ptlrpc_request *req)
2155 {
2156 #ifdef __KERNEL__
2157         struct obd_device *obd = req->rq_export->exp_obd;
2158         struct obd_device *master_obd;
2159         struct lustre_quota_ctxt *qctxt;
2160         struct qunit_data *qdata;
2161         void* rep;
2162         struct qunit_data_old *qdata_old;
2163         int rc = 0;
2164         ENTRY;
2165
2166         rc = req_capsule_server_pack(&req->rq_pill);
2167         if (rc) {
2168                 CERROR("packing reply failed!: rc = %d\n", rc);
2169                 RETURN(rc);
2170         }
2171
2172         LASSERT(req->rq_export);
2173
2174         /* fixed for bug10707 */
2175         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2176             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2177                 CDEBUG(D_QUOTA, "qd_count is 64bit!\n");
2178                 rep = req_capsule_server_get(&req->rq_pill,
2179                                              &RMF_QUNIT_DATA);
2180                 LASSERT(rep);
2181                 qdata = req_capsule_client_swab_get(&req->rq_pill,
2182                                                     &RMF_QUNIT_DATA,
2183                                           (void*)lustre_swab_qdata);
2184         } else {
2185                 CDEBUG(D_QUOTA, "qd_count is 32bit!\n");
2186                 rep = req_capsule_server_get(&req->rq_pill, &RMF_QUNIT_DATA);
2187                 LASSERT(rep);
2188                 qdata_old = req_capsule_client_swab_get(&req->rq_pill,
2189                                                         &RMF_QUNIT_DATA,
2190                                            (void*)lustre_swab_qdata_old);
2191                 qdata = lustre_quota_old_to_new(qdata_old);
2192         }
2193
2194         if (qdata == NULL)
2195                 RETURN(-EPROTO);
2196
2197         /* we use the observer */
2198         LASSERT(obd->obd_observer && obd->obd_observer->obd_observer);
2199         master_obd = obd->obd_observer->obd_observer;
2200         qctxt = &master_obd->u.obt.obt_qctxt;
2201
2202         LASSERT(qctxt->lqc_handler);
2203         rc = qctxt->lqc_handler(master_obd, qdata,
2204                                 lustre_msg_get_opc(req->rq_reqmsg));
2205         if (rc && rc != -EDQUOT)
2206                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
2207                        "dqacq failed! (rc:%d)\n", rc);
2208
2209         /* the qd_count might be changed in lqc_handler */
2210         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2211             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2212                 memcpy(rep, qdata, sizeof(*qdata));
2213         } else {
2214                 qdata_old = lustre_quota_new_to_old(qdata);
2215                 memcpy(rep, qdata_old, sizeof(*qdata_old));
2216         }
2217         req->rq_status = rc;
2218         rc = ptlrpc_reply(req);
2219
2220         RETURN(rc);
2221 #else
2222         return 0;
2223 #endif /* !__KERNEL__ */
2224 }
2225 #endif /* HAVE_QUOTA_SUPPORT */
2226
2227 ldlm_mode_t lck_compat_array[] = {
2228         [LCK_EX] LCK_COMPAT_EX,
2229         [LCK_PW] LCK_COMPAT_PW,
2230         [LCK_PR] LCK_COMPAT_PR,
2231         [LCK_CW] LCK_COMPAT_CW,
2232         [LCK_CR] LCK_COMPAT_CR,
2233         [LCK_NL] LCK_COMPAT_NL,
2234         [LCK_GROUP] LCK_COMPAT_GROUP
2235 };