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