Whamcloud - gitweb
b=2262
[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
281         /* This value may be changed at connect time in
282            ptlrpc_connect_interpret. */
283         cli->cl_max_pages_per_rpc = min((int)PTLRPC_MAX_BRW_PAGES,
284                                         (int)(1024 * 1024 >> CFS_PAGE_SHIFT));
285
286         if (!strcmp(name, LUSTRE_MDC_NAME)) {
287                 cli->cl_max_rpcs_in_flight = MDC_MAX_RIF_DEFAULT;
288         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 128 /* MB */) {
289                 cli->cl_max_rpcs_in_flight = 2;
290         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 256 /* MB */) {
291                 cli->cl_max_rpcs_in_flight = 3;
292         } else if (num_physpages >> (20 - CFS_PAGE_SHIFT) <= 512 /* MB */) {
293                 cli->cl_max_rpcs_in_flight = 4;
294         } else {
295                 cli->cl_max_rpcs_in_flight = OSC_MAX_RIF_DEFAULT;
296         }
297
298         rc = ldlm_get_ref(LDLM_NAMESPACE_CLIENT);
299         if (rc) {
300                 CERROR("ldlm_get_ref failed: %d\n", rc);
301                 GOTO(err, rc);
302         }
303
304         ptlrpc_init_client(rq_portal, rp_portal, name,
305                            &obddev->obd_ldlm_client);
306
307         imp = class_new_import(obddev);
308         if (imp == NULL)
309                 GOTO(err_ldlm, rc = -ENOENT);
310         imp->imp_client = &obddev->obd_ldlm_client;
311         imp->imp_connect_op = connect_op;
312         imp->imp_initial_recov = 1;
313         imp->imp_initial_recov_bk = 0;
314         CFS_INIT_LIST_HEAD(&imp->imp_pinger_chain);
315         memcpy(cli->cl_target_uuid.uuid, lustre_cfg_buf(lcfg, 1),
316                LUSTRE_CFG_BUFLEN(lcfg, 1));
317         class_import_put(imp);
318
319         rc = client_import_add_conn(imp, &server_uuid, 1);
320         if (rc) {
321                 CERROR("can't add initial connection\n");
322                 GOTO(err_import, rc);
323         }
324
325         cli->cl_import = imp;
326         /* cli->cl_max_mds_{easize,cookiesize} updated by mdc_init_ea_size() */
327         cli->cl_max_mds_easize = sizeof(struct lov_mds_md);
328         cli->cl_max_mds_cookiesize = sizeof(struct llog_cookie);
329
330         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
331                 if (!strcmp(lustre_cfg_string(lcfg, 3), "inactive")) {
332                         CDEBUG(D_HA, "marking %s %s->%s as inactive\n",
333                                name, obddev->obd_name,
334                                cli->cl_target_uuid.uuid);
335                         spin_lock(&imp->imp_lock);
336                         imp->imp_invalid = 1;
337                         spin_unlock(&imp->imp_lock);
338                 }
339         }
340
341         cli->cl_qchk_stat = CL_NOT_QUOTACHECKED;
342
343         RETURN(rc);
344
345 err_import:
346         class_destroy_import(imp);
347 err_ldlm:
348         ldlm_put_ref(LDLM_NAMESPACE_CLIENT, 0);
349 err:
350         RETURN(rc);
351
352 }
353
354 int client_obd_cleanup(struct obd_device *obddev)
355 {
356         ENTRY;
357         ldlm_put_ref(LDLM_NAMESPACE_CLIENT, obddev->obd_force);
358         RETURN(0);
359 }
360
361 /* ->o_connect() method for client side (OSC and MDC and MGC) */
362 int client_connect_import(const struct lu_env *env,
363                           struct lustre_handle *dlm_handle,
364                           struct obd_device *obd, struct obd_uuid *cluuid,
365                           struct obd_connect_data *data)
366 {
367         struct client_obd *cli = &obd->u.cli;
368         struct obd_import *imp = cli->cl_import;
369         struct obd_export *exp;
370         struct obd_connect_data *ocd;
371         int rc;
372         ENTRY;
373
374         mutex_down(&cli->cl_sem);
375         rc = class_connect(dlm_handle, obd, cluuid);
376         if (rc)
377                 GOTO(out_sem, rc);
378
379         cli->cl_conn_count++;
380         if (cli->cl_conn_count > 1)
381                 GOTO(out_sem, rc);
382         exp = class_conn2export(dlm_handle);
383
384         if (obd->obd_namespace != NULL)
385                 CERROR("already have namespace!\n");
386         obd->obd_namespace = ldlm_namespace_new(obd->obd_name,
387                                                 LDLM_NAMESPACE_CLIENT,
388                                                 LDLM_NAMESPACE_GREEDY);
389         if (obd->obd_namespace == NULL)
390                 GOTO(out_disco, rc = -ENOMEM);
391
392         imp->imp_dlm_handle = *dlm_handle;
393         rc = ptlrpc_init_import(imp);
394         if (rc != 0)
395                 GOTO(out_ldlm, rc);
396
397         rc = sptlrpc_import_get_sec(imp, NULL, cli->cl_sec_conf.sfc_rpc_flavor,
398                                     cli->cl_sec_conf.sfc_flags);
399         if (rc)
400                 GOTO(out_ldlm, rc);
401
402         ocd = &imp->imp_connect_data;
403         if (data) {
404                 *ocd = *data;
405                 imp->imp_connect_flags_orig = data->ocd_connect_flags;
406         }
407
408         rc = ptlrpc_connect_import(imp, NULL);
409         if (rc != 0) {
410                 LASSERT (imp->imp_state == LUSTRE_IMP_DISCON);
411                 GOTO(out_ldlm, rc);
412         }
413         LASSERT(exp->exp_connection);
414
415         if (data) {
416                 LASSERT((ocd->ocd_connect_flags & data->ocd_connect_flags) ==
417                         ocd->ocd_connect_flags);
418                 data->ocd_connect_flags = ocd->ocd_connect_flags;
419         }
420
421         ptlrpc_pinger_add_import(imp);
422
423         EXIT;
424
425         if (rc) {
426 out_ldlm:
427                 ldlm_namespace_free(obd->obd_namespace, 0);
428                 obd->obd_namespace = NULL;
429 out_disco:
430                 cli->cl_conn_count--;
431                 class_disconnect(exp);
432         } else {
433                 class_export_put(exp);
434         }
435 out_sem:
436         mutex_up(&cli->cl_sem);
437         return rc;
438 }
439
440 int client_disconnect_export(struct obd_export *exp)
441 {
442         struct obd_device *obd = class_exp2obd(exp);
443         struct client_obd *cli;
444         struct obd_import *imp;
445         int rc = 0, err;
446         ENTRY;
447
448         if (!obd) {
449                 CERROR("invalid export for disconnect: exp %p cookie "LPX64"\n",
450                        exp, exp ? exp->exp_handle.h_cookie : -1);
451                 RETURN(-EINVAL);
452         }
453
454         cli = &obd->u.cli;
455         imp = cli->cl_import;
456
457         mutex_down(&cli->cl_sem);
458         if (!cli->cl_conn_count) {
459                 CERROR("disconnecting disconnected device (%s)\n",
460                        obd->obd_name);
461                 GOTO(out_sem, rc = -EINVAL);
462         }
463
464         cli->cl_conn_count--;
465         if (cli->cl_conn_count)
466                 GOTO(out_no_disconnect, rc = 0);
467
468         /* Mark import deactivated now, so we don't try to reconnect if any
469          * of the cleanup RPCs fails (e.g. ldlm cancel, etc).  We don't
470          * fully deactivate the import, or that would drop all requests. */
471         spin_lock(&imp->imp_lock);
472         imp->imp_deactive = 1;
473         spin_unlock(&imp->imp_lock);
474         
475         /* Some non-replayable imports (MDS's OSCs) are pinged, so just
476          * delete it regardless.  (It's safe to delete an import that was
477          * never added.) */
478         (void)ptlrpc_pinger_del_import(imp);
479
480         if (obd->obd_namespace != NULL) {
481                 /* obd_force == local only */
482                 ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
483                                        obd->obd_force ? LDLM_FL_LOCAL_ONLY:0,
484                                        NULL);
485                 ldlm_namespace_free(obd->obd_namespace, obd->obd_force);
486                 obd->obd_namespace = NULL;
487         }
488
489         if (!obd->obd_force)
490                 rc = ptlrpc_disconnect_import(imp, 0);
491
492         ptlrpc_invalidate_import(imp);
493         ptlrpc_free_rq_pool(imp->imp_rq_pool);
494         destroy_import(imp);
495         cli->cl_import = NULL;
496
497         EXIT;
498  out_no_disconnect:
499         err = class_disconnect(exp);
500         if (!rc && err)
501                 rc = err;
502  out_sem:
503         mutex_up(&cli->cl_sem);
504         RETURN(rc);
505 }
506
507 /* --------------------------------------------------------------------------
508  * from old lib/target.c
509  * -------------------------------------------------------------------------- */
510
511 int target_handle_reconnect(struct lustre_handle *conn, struct obd_export *exp,
512                             struct obd_uuid *cluuid, int initial_conn)
513 {
514         ENTRY;
515         if (exp->exp_connection && exp->exp_imp_reverse && !initial_conn) {
516                 struct lustre_handle *hdl;
517                 hdl = &exp->exp_imp_reverse->imp_remote_handle;
518                 /* Might be a re-connect after a partition. */
519                 if (!memcmp(&conn->cookie, &hdl->cookie, sizeof conn->cookie)) {
520                         CWARN("%s: %s reconnecting\n", exp->exp_obd->obd_name,
521                               cluuid->uuid);
522                         conn->cookie = exp->exp_handle.h_cookie;
523                         /* target_handle_connect() treats EALREADY and
524                          * -EALREADY differently.  EALREADY means we are
525                          * doing a valid reconnect from the same client. */
526                         RETURN(EALREADY);
527                 } else {
528                         CERROR("%s reconnecting from %s, "
529                                "handle mismatch (ours "LPX64", theirs "
530                                LPX64")\n", cluuid->uuid,
531                                exp->exp_connection->c_remote_uuid.uuid,
532                                hdl->cookie, conn->cookie);
533                         memset(conn, 0, sizeof *conn);
534                         /* target_handle_connect() treats EALREADY and
535                          * -EALREADY differently.  -EALREADY is an error
536                          * (same UUID, different handle). */
537                         RETURN(-EALREADY);
538                 }
539         }
540
541         conn->cookie = exp->exp_handle.h_cookie;
542         CDEBUG(D_HA, "connect export for UUID '%s' at %p, cookie "LPX64"\n",
543                cluuid->uuid, exp, conn->cookie);
544         RETURN(0);
545 }
546
547 void target_client_add_cb(struct obd_device *obd, __u64 transno, void *cb_data,
548                           int error)
549 {
550         struct obd_export *exp = cb_data;
551
552         CDEBUG(D_HA, "%s: committing for initial connect of %s\n",
553                obd->obd_name, exp->exp_client_uuid.uuid);
554
555         spin_lock(&exp->exp_lock);
556         exp->exp_need_sync = 0;
557         spin_unlock(&exp->exp_lock);
558 }
559 EXPORT_SYMBOL(target_client_add_cb);
560
561 int target_handle_connect(struct ptlrpc_request *req)
562 {
563         struct obd_device *target, *targref = NULL;
564         struct obd_export *export = NULL;
565         struct obd_import *revimp;
566         struct lustre_handle conn;
567         struct obd_uuid tgtuuid;
568         struct obd_uuid cluuid;
569         struct obd_uuid remote_uuid;
570         struct list_head *p;
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         LASSERT_REQSWAB(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         LASSERT_REQSWAB(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         list_for_each(p, &target->obd_exports) {
692                 export = list_entry(p, struct obd_export, exp_obd_chain);
693                 if (obd_uuid_equals(&cluuid, &export->exp_client_uuid)) {
694                         if (export->exp_connecting) { /* bug 9635, et. al. */
695                                 CWARN("%s: exp %p already connecting\n",
696                                       export->exp_obd->obd_name, export);
697                                 export = NULL;
698                                 rc = -EALREADY;
699                                 break;
700                         }
701
702                         /* make darn sure this is coming from the same peer
703                          * if the UUIDs matched */
704                         if ((export->exp_connection != NULL) &&
705                             (strcmp(libcfs_nid2str(req->rq_peer.nid),
706                                     libcfs_nid2str(export->exp_connection->c_peer.nid)))) {
707                                 CWARN("%s: cookie %s seen on new NID %s when "
708                                       "existing NID %s is already connected\n",
709                                       target->obd_name, cluuid.uuid,
710                                       libcfs_nid2str(req->rq_peer.nid),
711                                       libcfs_nid2str(export->exp_connection->c_peer.nid));
712                                 export = NULL;
713                                 rc = -EALREADY;
714                                 break;
715                         }
716
717                         spin_lock(&export->exp_lock);
718                         export->exp_connecting = 1;
719                         spin_unlock(&export->exp_lock);
720                         spin_unlock(&target->obd_dev_lock);
721                         LASSERT(export->exp_obd == target);
722
723                         rc = target_handle_reconnect(&conn, export, &cluuid,
724                                                      initial_conn);
725                         break;
726                 }
727                 export = NULL;
728         }
729
730         /* If we found an export, we already unlocked. */
731         if (!export) {
732                 spin_unlock(&target->obd_dev_lock);
733                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_CONNECT, 2 * obd_timeout);
734         } else if (req->rq_export == NULL &&
735                    atomic_read(&export->exp_rpc_count) > 0) {
736                 CWARN("%s: refuse connection from %s/%s to 0x%p/%d\n",
737                       target->obd_name, cluuid.uuid,
738                       libcfs_nid2str(req->rq_peer.nid),
739                       export, atomic_read(&export->exp_refcount));
740                 GOTO(out, rc = -EBUSY);
741         } else if (req->rq_export != NULL &&
742                    (atomic_read(&export->exp_rpc_count) > 1)) {
743                 CWARN("%s: refuse reconnection from %s@%s to 0x%p/%d\n",
744                       target->obd_name, cluuid.uuid,
745                       libcfs_nid2str(req->rq_peer.nid),
746                       export, atomic_read(&export->exp_rpc_count));
747                 GOTO(out, rc = -EBUSY);
748         } else if (lustre_msg_get_conn_cnt(req->rq_reqmsg) == 1 &&
749                    !initial_conn) {
750                 CERROR("%s: NID %s (%s) reconnected with 1 conn_cnt; "
751                        "cookies not random?\n", target->obd_name,
752                        libcfs_nid2str(req->rq_peer.nid), cluuid.uuid);
753                 GOTO(out, rc = -EALREADY);
754         } else {
755                 OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_RECONNECT, 2 * obd_timeout);
756                 if (req->rq_export == NULL && initial_conn)
757                        export->exp_last_request_time = 
758                                max(export->exp_last_request_time,
759                                    (time_t)CURRENT_SECONDS);
760         }
761
762         /* We want to handle EALREADY but *not* -EALREADY from
763          * target_handle_reconnect(), return reconnection state in a flag */
764         if (rc == EALREADY) {
765                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECONNECT);
766                 rc = 0;
767         } else if (rc) {
768                 GOTO(out, rc);
769         }
770         /* Tell the client if we're in recovery. */
771         /* If this is the first client, start the recovery timer */
772         CWARN("%s: connection from %s@%s %st"LPU64" exp %p cur %ld last %ld\n",
773                target->obd_name, cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
774               target->obd_recovering ? "recovering/" : "", data->ocd_transno,
775               export, (long)CURRENT_SECONDS, 
776               export ? (long)export->exp_last_request_time : 0);
777
778
779         if (target->obd_recovering) {
780                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
781                 target_start_recovery_timer(target);
782         }
783
784         /* Tell the client if we support replayable requests */
785         if (target->obd_replayable)
786                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_REPLAYABLE);
787
788         if (export == NULL) {
789                 if (target->obd_recovering) {
790                         CERROR("%s: denying connection for new client %s (%s): "
791                                "%d clients in recovery for %lds\n",
792                                target->obd_name,
793                                libcfs_nid2str(req->rq_peer.nid), cluuid.uuid,
794                                target->obd_recoverable_clients,
795                                cfs_duration_sec(cfs_time_sub(cfs_timer_deadline(&target->obd_recovery_timer),
796                                                              cfs_time_current())));
797                         rc = -EBUSY;
798                 } else {
799 dont_check_exports:
800                         rc = obd_connect(req->rq_svc_thread->t_env,
801                                          &conn, target, &cluuid, data);
802                 }
803         } else {
804                 rc = obd_reconnect(export, target, &cluuid, data);
805         }
806         if (rc)
807                 GOTO(out, rc);
808         /* Return only the parts of obd_connect_data that we understand, so the
809          * client knows that we don't understand the rest. */
810         if (data)
811                 memcpy(lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
812                                       sizeof(*data)),
813                        data, sizeof(*data));
814
815         /* If all else goes well, this is our RPC return code. */
816         req->rq_status = 0;
817
818         lustre_msg_set_handle(req->rq_repmsg, &conn);
819
820         /* ownership of this export ref transfers to the request AFTER we
821          * drop any previous reference the request had, but we don't want
822          * that to go to zero before we get our new export reference. */
823         export = class_conn2export(&conn);
824         if (!export) {
825                 DEBUG_REQ(D_ERROR, req, "Missing export!");
826                 GOTO(out, rc = -ENODEV);
827         }
828
829         /* If the client and the server are the same node, we will already
830          * have an export that really points to the client's DLM export,
831          * because we have a shared handles table.
832          *
833          * XXX this will go away when shaver stops sending the "connect" handle
834          * in the real "remote handle" field of the request --phik 24 Apr 2003
835          */
836         if (req->rq_export != NULL)
837                 class_export_put(req->rq_export);
838
839         req->rq_export = export;
840
841         spin_lock(&export->exp_lock);
842         if (initial_conn) {
843                 lustre_msg_set_conn_cnt(req->rq_repmsg, export->exp_conn_cnt + 1);
844         } else if (export->exp_conn_cnt >= lustre_msg_get_conn_cnt(req->rq_reqmsg)) {
845                 spin_unlock(&export->exp_lock);
846                 CERROR("%s: %s already connected at higher conn_cnt: %d > %d\n",
847                        cluuid.uuid, libcfs_nid2str(req->rq_peer.nid),
848                        export->exp_conn_cnt,
849                        lustre_msg_get_conn_cnt(req->rq_reqmsg));
850
851                 GOTO(out, rc = -EALREADY);
852         }
853         export->exp_conn_cnt = lustre_msg_get_conn_cnt(req->rq_reqmsg);
854
855         /* request from liblustre?  Don't evict it for not pinging. */
856         if (lustre_msg_get_op_flags(req->rq_reqmsg) & MSG_CONNECT_LIBCLIENT) {
857                 export->exp_libclient = 1;
858                 spin_unlock(&export->exp_lock);
859                 
860                 spin_lock(&target->obd_dev_lock);
861                 list_del_init(&export->exp_obd_chain_timed);
862                 spin_unlock(&target->obd_dev_lock);
863         } else {
864                 spin_unlock(&export->exp_lock);
865         }
866
867         if (export->exp_connection != NULL)
868                 ptlrpc_put_connection(export->exp_connection);
869         export->exp_connection = ptlrpc_get_connection(req->rq_peer,
870                                                        req->rq_self,
871                                                        &remote_uuid);
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 (!exp_connect_lru_resize(req->rq_export))
1798                 RETURN(0);
1799         
1800         pl = ldlm_exp2pl(req->rq_export);
1801
1802         spin_lock(&pl->pl_lock);
1803         lustre_msg_set_slv(req->rq_repmsg, ldlm_pool_get_slv(pl));
1804         lustre_msg_set_limit(req->rq_repmsg, ldlm_pool_get_limit(pl));
1805         spin_unlock(&pl->pl_lock);
1806
1807         RETURN(0);
1808 }
1809
1810 int target_send_reply_msg(struct ptlrpc_request *req, int rc, int fail_id)
1811 {
1812         if (OBD_FAIL_CHECK(fail_id | OBD_FAIL_ONCE)) {
1813                 obd_fail_loc |= OBD_FAIL_ONCE | OBD_FAILED;
1814                 DEBUG_REQ(D_ERROR, req, "dropping reply");
1815                 return (-ECOMM);
1816         }
1817
1818         if (unlikely(rc)) {
1819                 DEBUG_REQ(D_ERROR, req, "processing error (%d)", rc);
1820                 req->rq_status = rc;
1821                 return (ptlrpc_error(req));
1822         } else {
1823                 DEBUG_REQ(D_NET, req, "sending reply");
1824         }
1825
1826         target_pack_pool_reply(req);
1827         return (ptlrpc_send_reply(req, 1));
1828 }
1829
1830 void target_send_reply(struct ptlrpc_request *req, int rc, int fail_id)
1831 {
1832         int                        netrc;
1833         struct ptlrpc_reply_state *rs;
1834         struct obd_device         *obd;
1835         struct obd_export         *exp;
1836         struct ptlrpc_service     *svc;
1837
1838         if (req->rq_no_reply)
1839                 return;
1840
1841         svc = req->rq_rqbd->rqbd_service;
1842         rs = req->rq_reply_state;
1843         if (rs == NULL || !rs->rs_difficult) {
1844                 /* no notifiers */
1845                 target_send_reply_msg (req, rc, fail_id);
1846                 return;
1847         }
1848
1849         /* must be an export if locks saved */
1850         LASSERT (req->rq_export != NULL);
1851         /* req/reply consistent */
1852         LASSERT (rs->rs_service == svc);
1853
1854         /* "fresh" reply */
1855         LASSERT (!rs->rs_scheduled);
1856         LASSERT (!rs->rs_scheduled_ever);
1857         LASSERT (!rs->rs_handled);
1858         LASSERT (!rs->rs_on_net);
1859         LASSERT (rs->rs_export == NULL);
1860         LASSERT (list_empty(&rs->rs_obd_list));
1861         LASSERT (list_empty(&rs->rs_exp_list));
1862
1863         exp = class_export_get (req->rq_export);
1864         obd = exp->exp_obd;
1865
1866         /* disable reply scheduling onto srv_reply_queue while I'm setting up */
1867         rs->rs_scheduled = 1;
1868         rs->rs_on_net    = 1;
1869         rs->rs_xid       = req->rq_xid;
1870         rs->rs_transno   = req->rq_transno;
1871         rs->rs_export    = exp;
1872
1873         spin_lock(&obd->obd_uncommitted_replies_lock);
1874
1875         if (rs->rs_transno > obd->obd_last_committed) {
1876                 /* not committed already */
1877                 list_add_tail (&rs->rs_obd_list,
1878                                &obd->obd_uncommitted_replies);
1879         }
1880
1881         spin_unlock (&obd->obd_uncommitted_replies_lock);
1882         spin_lock (&exp->exp_lock);
1883
1884         list_add_tail (&rs->rs_exp_list, &exp->exp_outstanding_replies);
1885
1886         spin_unlock(&exp->exp_lock);
1887
1888         netrc = target_send_reply_msg (req, rc, fail_id);
1889
1890         spin_lock(&svc->srv_lock);
1891
1892         svc->srv_n_difficult_replies++;
1893
1894         if (netrc != 0) {
1895                 /* error sending: reply is off the net.  Also we need +1
1896                  * reply ref until ptlrpc_server_handle_reply() is done
1897                  * with the reply state (if the send was successful, there
1898                  * would have been +1 ref for the net, which
1899                  * reply_out_callback leaves alone) */
1900                 rs->rs_on_net = 0;
1901                 ptlrpc_rs_addref(rs);
1902                 atomic_inc (&svc->srv_outstanding_replies);
1903         }
1904
1905         if (!rs->rs_on_net ||                   /* some notifier */
1906             list_empty(&rs->rs_exp_list) ||     /* completed already */
1907             list_empty(&rs->rs_obd_list)) {
1908                 list_add_tail (&rs->rs_list, &svc->srv_reply_queue);
1909                 cfs_waitq_signal (&svc->srv_waitq);
1910         } else {
1911                 list_add (&rs->rs_list, &svc->srv_active_replies);
1912                 rs->rs_scheduled = 0;           /* allow notifier to schedule */
1913         }
1914
1915         spin_unlock(&svc->srv_lock);
1916 }
1917
1918 int target_handle_ping(struct ptlrpc_request *req)
1919 {
1920         obd_ping(req->rq_export);
1921         return lustre_pack_reply(req, 1, NULL, NULL);
1922 }
1923
1924 void target_committed_to_req(struct ptlrpc_request *req)
1925 {
1926         struct obd_device *obd;
1927
1928         if (req == NULL || req->rq_export == NULL)
1929                 return;
1930
1931         obd = req->rq_export->exp_obd;
1932         if (obd == NULL)
1933                 return;
1934
1935         if (!obd->obd_no_transno && req->rq_repmsg != NULL)
1936                 lustre_msg_set_last_committed(req->rq_repmsg,
1937                                               obd->obd_last_committed);
1938         else
1939                 DEBUG_REQ(D_IOCTL, req, "not sending last_committed update");
1940
1941         CDEBUG(D_INFO, "last_committed "LPU64", transno "LPU64", xid "LPU64"\n",
1942                obd->obd_last_committed, req->rq_transno, req->rq_xid);
1943 }
1944
1945 EXPORT_SYMBOL(target_committed_to_req);
1946
1947 #ifdef HAVE_QUOTA_SUPPORT
1948 int target_handle_qc_callback(struct ptlrpc_request *req)
1949 {
1950         struct obd_quotactl *oqctl;
1951         struct client_obd *cli = &req->rq_export->exp_obd->u.cli;
1952
1953         oqctl = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*oqctl),
1954                                    lustre_swab_obd_quotactl);
1955         if (oqctl == NULL) {
1956                 CERROR("Can't unpack obd_quotactl\n");
1957                 RETURN(-EPROTO);
1958         }
1959
1960         cli->cl_qchk_stat = oqctl->qc_stat;
1961
1962         return 0;
1963 }
1964
1965 int target_handle_dqacq_callback(struct ptlrpc_request *req)
1966 {
1967 #ifdef __KERNEL__
1968         struct obd_device *obd = req->rq_export->exp_obd;
1969         struct obd_device *master_obd;
1970         struct lustre_quota_ctxt *qctxt;
1971         struct qunit_data *qdata;
1972         void* rep;
1973         struct qunit_data_old *qdata_old;
1974         int rc = 0;
1975         int repsize[2] = { sizeof(struct ptlrpc_body),
1976                            sizeof(struct qunit_data) };
1977         ENTRY;
1978
1979         rc = lustre_pack_reply(req, 2, repsize, NULL);
1980         if (rc) {
1981                 CERROR("packing reply failed!: rc = %d\n", rc);
1982                 RETURN(rc);
1983         }
1984         LASSERT(req->rq_export);
1985
1986         /* fixed for bug10707 */
1987         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
1988             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
1989                 CDEBUG(D_QUOTA, "qd_count is 64bit!\n");
1990                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
1991                                      sizeof(struct qunit_data));
1992                 LASSERT(rep);
1993                 qdata = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata),
1994                                            lustre_swab_qdata);
1995         } else {
1996                 CDEBUG(D_QUOTA, "qd_count is 32bit!\n");
1997                 rep = lustre_msg_buf(req->rq_repmsg, REPLY_REC_OFF,
1998                                      sizeof(struct qunit_data_old));
1999                 LASSERT(rep);
2000                 qdata_old = lustre_swab_reqbuf(req, REQ_REC_OFF, sizeof(*qdata_old),
2001                                                lustre_swab_qdata_old);
2002                 qdata = lustre_quota_old_to_new(qdata_old);
2003         }
2004
2005         if (qdata == NULL) {
2006                 CERROR("Can't unpack qunit_data\n");
2007                 RETURN(-EPROTO);
2008         }
2009
2010         /* we use the observer */
2011         LASSERT(obd->obd_observer && obd->obd_observer->obd_observer);
2012         master_obd = obd->obd_observer->obd_observer;
2013         qctxt = &master_obd->u.obt.obt_qctxt;
2014
2015         LASSERT(qctxt->lqc_handler);
2016         rc = qctxt->lqc_handler(master_obd, qdata,
2017                                 lustre_msg_get_opc(req->rq_reqmsg));
2018         if (rc && rc != -EDQUOT)
2019                 CDEBUG(rc == -EBUSY  ? D_QUOTA : D_ERROR,
2020                        "dqacq failed! (rc:%d)\n", rc);
2021
2022         /* the qd_count might be changed in lqc_handler */
2023         if ((req->rq_export->exp_connect_flags & OBD_CONNECT_QUOTA64) &&
2024             !OBD_FAIL_CHECK(OBD_FAIL_QUOTA_QD_COUNT_32BIT)) {
2025                 memcpy(rep,qdata,sizeof(*qdata));
2026         } else {
2027                 qdata_old = lustre_quota_new_to_old(qdata);
2028                 memcpy(rep,qdata_old,sizeof(*qdata_old));
2029         }
2030         req->rq_status = rc;
2031         rc = ptlrpc_reply(req);
2032
2033         RETURN(rc);
2034 #else
2035         return 0;
2036 #endif /* !__KERNEL__ */
2037 }
2038 #endif /* HAVE_QUOTA_SUPPORT */
2039
2040 ldlm_mode_t lck_compat_array[] = {
2041         [LCK_EX] LCK_COMPAT_EX,
2042         [LCK_PW] LCK_COMPAT_PW,
2043         [LCK_PR] LCK_COMPAT_PR,
2044         [LCK_CW] LCK_COMPAT_CW,
2045         [LCK_CR] LCK_COMPAT_CR,
2046         [LCK_NL] LCK_COMPAT_NL,
2047         [LCK_GROUP] LCK_COMPAT_GROUP
2048 };