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