Whamcloud - gitweb
LU-1907 build: avoid function resolution mistakes by Coverity
[fs/lustre-release.git] / lustre / mdt / mdt_handler.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Whamcloud, Inc.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/mdt/mdt_handler.c
37  *
38  * Lustre Metadata Target (mdt) request handler
39  *
40  * Author: Peter Braam <braam@clusterfs.com>
41  * Author: Andreas Dilger <adilger@clusterfs.com>
42  * Author: Phil Schwan <phil@clusterfs.com>
43  * Author: Mike Shaver <shaver@clusterfs.com>
44  * Author: Nikita Danilov <nikita@clusterfs.com>
45  * Author: Huang Hua <huanghua@clusterfs.com>
46  * Author: Yury Umanets <umka@clusterfs.com>
47  */
48
49 #define DEBUG_SUBSYSTEM S_MDS
50
51 #include <linux/module.h>
52 /*
53  * struct OBD_{ALLOC,FREE}*()
54  */
55 #include <obd_support.h>
56 /* struct ptlrpc_request */
57 #include <lustre_net.h>
58 /* struct obd_export */
59 #include <lustre_export.h>
60 /* struct obd_device */
61 #include <obd.h>
62 /* lu2dt_dev() */
63 #include <dt_object.h>
64 #include <lustre_mds.h>
65 #include <lustre_mdt.h>
66 #include <lustre_log.h>
67 #include "mdt_internal.h"
68 #ifdef HAVE_QUOTA_SUPPORT
69 # include <lustre_quota.h>
70 #endif
71 #include <lustre_acl.h>
72 #include <lustre_param.h>
73
74 mdl_mode_t mdt_mdl_lock_modes[] = {
75         [LCK_MINMODE] = MDL_MINMODE,
76         [LCK_EX]      = MDL_EX,
77         [LCK_PW]      = MDL_PW,
78         [LCK_PR]      = MDL_PR,
79         [LCK_CW]      = MDL_CW,
80         [LCK_CR]      = MDL_CR,
81         [LCK_NL]      = MDL_NL,
82         [LCK_GROUP]   = MDL_GROUP
83 };
84
85 ldlm_mode_t mdt_dlm_lock_modes[] = {
86         [MDL_MINMODE] = LCK_MINMODE,
87         [MDL_EX]      = LCK_EX,
88         [MDL_PW]      = LCK_PW,
89         [MDL_PR]      = LCK_PR,
90         [MDL_CW]      = LCK_CW,
91         [MDL_CR]      = LCK_CR,
92         [MDL_NL]      = LCK_NL,
93         [MDL_GROUP]   = LCK_GROUP
94 };
95
96 /*
97  * Initialized in mdt_mod_init().
98  */
99 static unsigned long mdt_num_threads;
100 CFS_MODULE_PARM(mdt_num_threads, "ul", ulong, 0444,
101                 "number of MDS service threads to start "
102                 "(deprecated in favor of mds_num_threads)");
103
104 static unsigned long mds_num_threads;
105 CFS_MODULE_PARM(mds_num_threads, "ul", ulong, 0444,
106                 "number of MDS service threads to start");
107
108 static char *mds_num_cpts;
109 CFS_MODULE_PARM(mds_num_cpts, "c", charp, 0444,
110                 "CPU partitions MDS threads should run on");
111
112 static unsigned long mds_rdpg_num_threads;
113 CFS_MODULE_PARM(mds_rdpg_num_threads, "ul", ulong, 0444,
114                 "number of MDS readpage service threads to start");
115
116 static char *mds_rdpg_num_cpts;
117 CFS_MODULE_PARM(mds_rdpg_num_cpts, "c", charp, 0444,
118                 "CPU partitions MDS readpage threads should run on");
119
120 /* NB: these two should be removed along with setattr service in the future */
121 static unsigned long mds_attr_num_threads;
122 CFS_MODULE_PARM(mds_attr_num_threads, "ul", ulong, 0444,
123                 "number of MDS setattr service threads to start");
124
125 static char *mds_attr_num_cpts;
126 CFS_MODULE_PARM(mds_attr_num_cpts, "c", charp, 0444,
127                 "CPU partitions MDS setattr threads should run on");
128
129 /* ptlrpc request handler for MDT. All handlers are
130  * grouped into several slices - struct mdt_opc_slice,
131  * and stored in an array - mdt_handlers[].
132  */
133 struct mdt_handler {
134         /* The name of this handler. */
135         const char *mh_name;
136         /* Fail id for this handler, checked at the beginning of this handler*/
137         int         mh_fail_id;
138         /* Operation code for this handler */
139         __u32       mh_opc;
140         /* flags are listed in enum mdt_handler_flags below. */
141         __u32       mh_flags;
142         /* The actual handler function to execute. */
143         int (*mh_act)(struct mdt_thread_info *info);
144         /* Request format for this request. */
145         const struct req_format *mh_fmt;
146 };
147
148 enum mdt_handler_flags {
149         /*
150          * struct mdt_body is passed in the incoming message, and object
151          * identified by this fid exists on disk.
152          *
153          * "habeo corpus" == "I have a body"
154          */
155         HABEO_CORPUS = (1 << 0),
156         /*
157          * struct ldlm_request is passed in the incoming message.
158          *
159          * "habeo clavis" == "I have a key"
160          */
161         HABEO_CLAVIS = (1 << 1),
162         /*
163          * this request has fixed reply format, so that reply message can be
164          * packed by generic code.
165          *
166          * "habeo refero" == "I have a reply"
167          */
168         HABEO_REFERO = (1 << 2),
169         /*
170          * this request will modify something, so check whether the filesystem
171          * is readonly or not, then return -EROFS to client asap if necessary.
172          *
173          * "mutabor" == "I shall modify"
174          */
175         MUTABOR      = (1 << 3)
176 };
177
178 struct mdt_opc_slice {
179         __u32               mos_opc_start;
180         int                 mos_opc_end;
181         struct mdt_handler *mos_hs;
182 };
183
184 static struct mdt_opc_slice mdt_regular_handlers[];
185 static struct mdt_opc_slice mdt_readpage_handlers[];
186 static struct mdt_opc_slice mdt_xmds_handlers[];
187 static struct mdt_opc_slice mdt_seq_handlers[];
188 static struct mdt_opc_slice mdt_fld_handlers[];
189
190 static struct mdt_device *mdt_dev(struct lu_device *d);
191 static int mdt_regular_handle(struct ptlrpc_request *req);
192 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags);
193 static int mdt_fid2path(const struct lu_env *env, struct mdt_device *mdt,
194                         struct getinfo_fid2path *fp);
195
196 static const struct lu_object_operations mdt_obj_ops;
197
198 /* Slab for MDT object allocation */
199 static cfs_mem_cache_t *mdt_object_kmem;
200
201 static struct lu_kmem_descr mdt_caches[] = {
202         {
203                 .ckd_cache = &mdt_object_kmem,
204                 .ckd_name  = "mdt_obj",
205                 .ckd_size  = sizeof(struct mdt_object)
206         },
207         {
208                 .ckd_cache = NULL
209         }
210 };
211
212 int mdt_get_disposition(struct ldlm_reply *rep, int flag)
213 {
214         if (!rep)
215                 return 0;
216         return (rep->lock_policy_res1 & flag);
217 }
218
219 void mdt_clear_disposition(struct mdt_thread_info *info,
220                            struct ldlm_reply *rep, int flag)
221 {
222         if (info)
223                 info->mti_opdata &= ~flag;
224         if (rep)
225                 rep->lock_policy_res1 &= ~flag;
226 }
227
228 void mdt_set_disposition(struct mdt_thread_info *info,
229                          struct ldlm_reply *rep, int flag)
230 {
231         if (info)
232                 info->mti_opdata |= flag;
233         if (rep)
234                 rep->lock_policy_res1 |= flag;
235 }
236
237 void mdt_lock_reg_init(struct mdt_lock_handle *lh, ldlm_mode_t lm)
238 {
239         lh->mlh_pdo_hash = 0;
240         lh->mlh_reg_mode = lm;
241         lh->mlh_type = MDT_REG_LOCK;
242 }
243
244 void mdt_lock_pdo_init(struct mdt_lock_handle *lh, ldlm_mode_t lm,
245                        const char *name, int namelen)
246 {
247         lh->mlh_reg_mode = lm;
248         lh->mlh_type = MDT_PDO_LOCK;
249
250         if (name != NULL && (name[0] != '\0')) {
251                 LASSERT(namelen > 0);
252                 lh->mlh_pdo_hash = full_name_hash(name, namelen);
253         } else {
254                 LASSERT(namelen == 0);
255                 lh->mlh_pdo_hash = 0ull;
256         }
257 }
258
259 static void mdt_lock_pdo_mode(struct mdt_thread_info *info, struct mdt_object *o,
260                               struct mdt_lock_handle *lh)
261 {
262         mdl_mode_t mode;
263         ENTRY;
264
265         /*
266          * Any dir access needs couple of locks:
267          *
268          * 1) on part of dir we gonna take lookup/modify;
269          *
270          * 2) on whole dir to protect it from concurrent splitting and/or to
271          * flush client's cache for readdir().
272          *
273          * so, for a given mode and object this routine decides what lock mode
274          * to use for lock #2:
275          *
276          * 1) if caller's gonna lookup in dir then we need to protect dir from
277          * being splitted only - LCK_CR
278          *
279          * 2) if caller's gonna modify dir then we need to protect dir from
280          * being splitted and to flush cache - LCK_CW
281          *
282          * 3) if caller's gonna modify dir and that dir seems ready for
283          * splitting then we need to protect it from any type of access
284          * (lookup/modify/split) - LCK_EX --bzzz
285          */
286
287         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
288         LASSERT(lh->mlh_pdo_mode == LCK_MINMODE);
289
290         /*
291          * Ask underlaying level its opinion about preferable PDO lock mode
292          * having access type passed as regular lock mode:
293          *
294          * - MDL_MINMODE means that lower layer does not want to specify lock
295          * mode;
296          *
297          * - MDL_NL means that no PDO lock should be taken. This is used in some
298          * cases. Say, for non-splittable directories no need to use PDO locks
299          * at all.
300          */
301         mode = mdo_lock_mode(info->mti_env, mdt_object_child(o),
302                              mdt_dlm_mode2mdl_mode(lh->mlh_reg_mode));
303
304         if (mode != MDL_MINMODE) {
305                 lh->mlh_pdo_mode = mdt_mdl_mode2dlm_mode(mode);
306         } else {
307                 /*
308                  * Lower layer does not want to specify locking mode. We do it
309                  * our selves. No special protection is needed, just flush
310                  * client's cache on modification and allow concurrent
311                  * mondification.
312                  */
313                 switch (lh->mlh_reg_mode) {
314                 case LCK_EX:
315                         lh->mlh_pdo_mode = LCK_EX;
316                         break;
317                 case LCK_PR:
318                         lh->mlh_pdo_mode = LCK_CR;
319                         break;
320                 case LCK_PW:
321                         lh->mlh_pdo_mode = LCK_CW;
322                         break;
323                 default:
324                         CERROR("Not expected lock type (0x%x)\n",
325                                (int)lh->mlh_reg_mode);
326                         LBUG();
327                 }
328         }
329
330         LASSERT(lh->mlh_pdo_mode != LCK_MINMODE);
331         EXIT;
332 }
333
334 static int mdt_getstatus(struct mdt_thread_info *info)
335 {
336         struct mdt_device *mdt  = info->mti_mdt;
337         struct md_device  *next = mdt->mdt_child;
338         struct mdt_body   *repbody;
339         int                rc;
340
341         ENTRY;
342
343         rc = mdt_check_ucred(info);
344         if (rc)
345                 RETURN(err_serious(rc));
346
347         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETSTATUS_PACK))
348                 RETURN(err_serious(-ENOMEM));
349
350         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
351         rc = next->md_ops->mdo_root_get(info->mti_env, next, &repbody->fid1);
352         if (rc != 0)
353                 RETURN(rc);
354
355         repbody->valid |= OBD_MD_FLID;
356
357         if (mdt->mdt_opts.mo_mds_capa &&
358             info->mti_exp->exp_connect_flags & OBD_CONNECT_MDS_CAPA) {
359                 struct mdt_object  *root;
360                 struct lustre_capa *capa;
361
362                 root = mdt_object_find(info->mti_env, mdt, &repbody->fid1);
363                 if (IS_ERR(root))
364                         RETURN(PTR_ERR(root));
365
366                 capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA1);
367                 LASSERT(capa);
368                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
369                 rc = mo_capa_get(info->mti_env, mdt_object_child(root), capa,
370                                  0);
371                 mdt_object_put(info->mti_env, root);
372                 if (rc == 0)
373                         repbody->valid |= OBD_MD_FLMDSCAPA;
374         }
375
376         RETURN(rc);
377 }
378
379 static int mdt_statfs(struct mdt_thread_info *info)
380 {
381         struct ptlrpc_request           *req = mdt_info_req(info);
382         struct md_device                *next = info->mti_mdt->mdt_child;
383         struct ptlrpc_service_part      *svcpt;
384         struct obd_statfs               *osfs;
385         int                             rc;
386
387         ENTRY;
388
389         svcpt = info->mti_pill->rc_req->rq_rqbd->rqbd_svcpt;
390
391         /* This will trigger a watchdog timeout */
392         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_STATFS_LCW_SLEEP,
393                          (MDT_SERVICE_WATCHDOG_FACTOR *
394                           at_get(&svcpt->scp_at_estimate)) + 1);
395
396         rc = mdt_check_ucred(info);
397         if (rc)
398                 RETURN(err_serious(rc));
399
400         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_STATFS_PACK))
401                 RETURN(err_serious(-ENOMEM));
402
403         osfs = req_capsule_server_get(info->mti_pill, &RMF_OBD_STATFS);
404         if (!osfs)
405                 RETURN(-EPROTO);
406
407         /** statfs information are cached in the mdt_device */
408         if (cfs_time_before_64(info->mti_mdt->mdt_osfs_age,
409                                cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS))) {
410                 /** statfs data is too old, get up-to-date one */
411                 rc = next->md_ops->mdo_statfs(info->mti_env, next, osfs);
412                 if (rc)
413                         RETURN(rc);
414                 cfs_spin_lock(&info->mti_mdt->mdt_osfs_lock);
415                 info->mti_mdt->mdt_osfs = *osfs;
416                 info->mti_mdt->mdt_osfs_age = cfs_time_current_64();
417                 cfs_spin_unlock(&info->mti_mdt->mdt_osfs_lock);
418         } else {
419                 /** use cached statfs data */
420                 cfs_spin_lock(&info->mti_mdt->mdt_osfs_lock);
421                 *osfs = info->mti_mdt->mdt_osfs;
422                 cfs_spin_unlock(&info->mti_mdt->mdt_osfs_lock);
423         }
424
425         if (rc == 0)
426                 mdt_counter_incr(req, LPROC_MDT_STATFS);
427
428         RETURN(rc);
429 }
430
431 /**
432  * Pack SOM attributes into the reply.
433  * Call under a DLM UPDATE lock.
434  */
435 static void mdt_pack_size2body(struct mdt_thread_info *info,
436                                struct mdt_object *mo)
437 {
438         struct mdt_body *b;
439         struct md_attr *ma = &info->mti_attr;
440
441         LASSERT(ma->ma_attr.la_valid & LA_MODE);
442         b = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
443
444         /* Check if Size-on-MDS is supported, if this is a regular file,
445          * if SOM is enabled on the object and if SOM cache exists and valid.
446          * Otherwise do not pack Size-on-MDS attributes to the reply. */
447         if (!(mdt_conn_flags(info) & OBD_CONNECT_SOM) ||
448             !S_ISREG(ma->ma_attr.la_mode) ||
449             !mdt_object_is_som_enabled(mo) ||
450             !(ma->ma_valid & MA_SOM))
451                 return;
452
453         b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
454         b->size = ma->ma_som->msd_size;
455         b->blocks = ma->ma_som->msd_blocks;
456 }
457
458 void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
459                         const struct lu_attr *attr, const struct lu_fid *fid)
460 {
461         struct md_attr *ma = &info->mti_attr;
462
463         LASSERT(ma->ma_valid & MA_INODE);
464
465         b->atime      = attr->la_atime;
466         b->mtime      = attr->la_mtime;
467         b->ctime      = attr->la_ctime;
468         b->mode       = attr->la_mode;
469         b->size       = attr->la_size;
470         b->blocks     = attr->la_blocks;
471         b->uid        = attr->la_uid;
472         b->gid        = attr->la_gid;
473         b->flags      = attr->la_flags;
474         b->nlink      = attr->la_nlink;
475         b->rdev       = attr->la_rdev;
476
477         /*XXX should pack the reply body according to lu_valid*/
478         b->valid |= OBD_MD_FLCTIME | OBD_MD_FLUID   |
479                     OBD_MD_FLGID   | OBD_MD_FLTYPE  |
480                     OBD_MD_FLMODE  | OBD_MD_FLNLINK | OBD_MD_FLFLAGS |
481                     OBD_MD_FLATIME | OBD_MD_FLMTIME ;
482
483         if (!S_ISREG(attr->la_mode)) {
484                 b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS | OBD_MD_FLRDEV;
485         } else if (ma->ma_need & MA_LOV && ma->ma_lmm_size == 0) {
486                 /* means no objects are allocated on osts. */
487                 LASSERT(!(ma->ma_valid & MA_LOV));
488                 /* just ignore blocks occupied by extend attributes on MDS */
489                 b->blocks = 0;
490                 /* if no object is allocated on osts, the size on mds is valid. b=22272 */
491                 b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
492         }
493
494         if (fid) {
495                 b->fid1 = *fid;
496                 b->valid |= OBD_MD_FLID;
497
498                 /* FIXME: these should be fixed when new igif ready.*/
499                 b->ino  =  fid_oid(fid);       /* 1.6 compatibility */
500                 b->generation = fid_ver(fid);  /* 1.6 compatibility */
501                 b->valid |= OBD_MD_FLGENER;    /* 1.6 compatibility */
502
503                 CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, size="LPU64"\n",
504                                 PFID(fid), b->nlink, b->mode, b->size);
505         }
506
507         if (info)
508                 mdt_body_reverse_idmap(info, b);
509
510         if (b->valid & OBD_MD_FLSIZE)
511                 CDEBUG(D_VFSTRACE, DFID": returning size %llu\n",
512                        PFID(fid), (unsigned long long)b->size);
513 }
514
515 static inline int mdt_body_has_lov(const struct lu_attr *la,
516                                    const struct mdt_body *body)
517 {
518         return ((S_ISREG(la->la_mode) && (body->valid & OBD_MD_FLEASIZE)) ||
519                 (S_ISDIR(la->la_mode) && (body->valid & OBD_MD_FLDIREA )) );
520 }
521
522 void mdt_client_compatibility(struct mdt_thread_info *info)
523 {
524         struct mdt_body       *body;
525         struct ptlrpc_request *req = mdt_info_req(info);
526         struct obd_export     *exp = req->rq_export;
527         struct md_attr        *ma = &info->mti_attr;
528         struct lu_attr        *la = &ma->ma_attr;
529         ENTRY;
530
531         if (exp->exp_connect_flags & OBD_CONNECT_LAYOUTLOCK)
532                 /* the client can deal with 16-bit lmm_stripe_count */
533                 RETURN_EXIT;
534
535         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
536
537         if (!mdt_body_has_lov(la, body))
538                 RETURN_EXIT;
539
540         /* now we have a reply with a lov for a client not compatible with the
541          * layout lock so we have to clean the layout generation number */
542         if (S_ISREG(la->la_mode))
543                 ma->ma_lmm->lmm_layout_gen = 0;
544         EXIT;
545 }
546
547
548 static int mdt_getattr_internal(struct mdt_thread_info *info,
549                                 struct mdt_object *o, int ma_need)
550 {
551         struct md_object        *next = mdt_object_child(o);
552         const struct mdt_body   *reqbody = info->mti_body;
553         struct ptlrpc_request   *req = mdt_info_req(info);
554         struct md_attr          *ma = &info->mti_attr;
555         struct lu_attr          *la = &ma->ma_attr;
556         struct req_capsule      *pill = info->mti_pill;
557         const struct lu_env     *env = info->mti_env;
558         struct mdt_body         *repbody;
559         struct lu_buf           *buffer = &info->mti_buf;
560         int                     rc;
561         ENTRY;
562
563         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK))
564                 RETURN(err_serious(-ENOMEM));
565
566         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
567
568         ma->ma_valid = 0;
569
570         rc = mdt_object_exists(o);
571         if (rc < 0) {
572                 /* This object is located on remote node.*/
573                 repbody->fid1 = *mdt_object_fid(o);
574                 repbody->valid = OBD_MD_FLID | OBD_MD_MDS;
575                 GOTO(out, rc = 0);
576         }
577
578         buffer->lb_buf = req_capsule_server_get(pill, &RMF_MDT_MD);
579         buffer->lb_len = req_capsule_get_size(pill, &RMF_MDT_MD, RCL_SERVER);
580
581         /* If it is dir object and client require MEA, then we got MEA */
582         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
583             reqbody->valid & OBD_MD_MEA) {
584                 /* Assumption: MDT_MD size is enough for lmv size. */
585                 ma->ma_lmv = buffer->lb_buf;
586                 ma->ma_lmv_size = buffer->lb_len;
587                 ma->ma_need = MA_LMV | MA_INODE;
588         } else {
589                 ma->ma_lmm = buffer->lb_buf;
590                 ma->ma_lmm_size = buffer->lb_len;
591                 ma->ma_need = MA_LOV | MA_INODE;
592         }
593
594         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
595             reqbody->valid & OBD_MD_FLDIREA  &&
596             lustre_msg_get_opc(req->rq_reqmsg) == MDS_GETATTR) {
597                 /* get default stripe info for this dir. */
598                 ma->ma_need |= MA_LOV_DEF;
599         }
600         ma->ma_need |= ma_need;
601         if (ma->ma_need & MA_SOM)
602                 ma->ma_som = &info->mti_u.som.data;
603
604         rc = mo_attr_get(env, next, ma);
605         if (unlikely(rc)) {
606                 CERROR("getattr error for "DFID": %d\n",
607                         PFID(mdt_object_fid(o)), rc);
608                 RETURN(rc);
609         }
610
611         if (likely(ma->ma_valid & MA_INODE))
612                 mdt_pack_attr2body(info, repbody, la, mdt_object_fid(o));
613         else
614                 RETURN(-EFAULT);
615
616         if (mdt_body_has_lov(la, reqbody)) {
617                 if (ma->ma_valid & MA_LOV) {
618                         LASSERT(ma->ma_lmm_size);
619                         mdt_dump_lmm(D_INFO, ma->ma_lmm);
620                         repbody->eadatasize = ma->ma_lmm_size;
621                         if (S_ISDIR(la->la_mode))
622                                 repbody->valid |= OBD_MD_FLDIREA;
623                         else
624                                 repbody->valid |= OBD_MD_FLEASIZE;
625                 }
626                 if (ma->ma_valid & MA_LMV) {
627                         LASSERT(S_ISDIR(la->la_mode));
628                         repbody->eadatasize = ma->ma_lmv_size;
629                         repbody->valid |= (OBD_MD_FLDIREA|OBD_MD_MEA);
630                 }
631         } else if (S_ISLNK(la->la_mode) &&
632                    reqbody->valid & OBD_MD_LINKNAME) {
633                 buffer->lb_buf = ma->ma_lmm;
634                 /* eadatasize from client includes NULL-terminator, so
635                  * there is no need to read it */
636                 buffer->lb_len = reqbody->eadatasize - 1;
637                 rc = mo_readlink(env, next, buffer);
638                 if (unlikely(rc <= 0)) {
639                         CERROR("readlink failed: %d\n", rc);
640                         rc = -EFAULT;
641                 } else {
642                         int print_limit = min_t(int, CFS_PAGE_SIZE - 128, rc);
643
644                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READLINK_EPROTO))
645                                 rc -= 2;
646                         repbody->valid |= OBD_MD_LINKNAME;
647                         /* we need to report back size with NULL-terminator
648                          * because client expects that */
649                         repbody->eadatasize = rc + 1;
650                         if (repbody->eadatasize != reqbody->eadatasize)
651                                 CERROR("Read shorter symlink %d, expected %d\n",
652                                        rc, reqbody->eadatasize - 1);
653                         /* NULL terminate */
654                         ((char *)ma->ma_lmm)[rc] = 0;
655
656                         /* If the total CDEBUG() size is larger than a page, it
657                          * will print a warning to the console, avoid this by
658                          * printing just the last part of the symlink. */
659                         CDEBUG(D_INODE, "symlink dest %s%.*s, len = %d\n",
660                                print_limit < rc ? "..." : "", print_limit,
661                                (char *)ma->ma_lmm + rc - print_limit, rc);
662                         rc = 0;
663                 }
664         }
665
666         if (reqbody->valid & OBD_MD_FLMODEASIZE) {
667                 repbody->max_cookiesize = info->mti_mdt->mdt_max_cookiesize;
668                 repbody->max_mdsize = info->mti_mdt->mdt_max_mdsize;
669                 repbody->valid |= OBD_MD_FLMODEASIZE;
670                 CDEBUG(D_INODE, "I am going to change the MAX_MD_SIZE & "
671                        "MAX_COOKIE to : %d:%d\n", repbody->max_mdsize,
672                        repbody->max_cookiesize);
673         }
674
675         if (exp_connect_rmtclient(info->mti_exp) &&
676             reqbody->valid & OBD_MD_FLRMTPERM) {
677                 void *buf = req_capsule_server_get(pill, &RMF_ACL);
678
679                 /* mdt_getattr_lock only */
680                 rc = mdt_pack_remote_perm(info, o, buf);
681                 if (rc) {
682                         repbody->valid &= ~OBD_MD_FLRMTPERM;
683                         repbody->aclsize = 0;
684                         RETURN(rc);
685                 } else {
686                         repbody->valid |= OBD_MD_FLRMTPERM;
687                         repbody->aclsize = sizeof(struct mdt_remote_perm);
688                 }
689         }
690 #ifdef CONFIG_FS_POSIX_ACL
691         else if ((req->rq_export->exp_connect_flags & OBD_CONNECT_ACL) &&
692                  (reqbody->valid & OBD_MD_FLACL)) {
693                 buffer->lb_buf = req_capsule_server_get(pill, &RMF_ACL);
694                 buffer->lb_len = req_capsule_get_size(pill,
695                                                       &RMF_ACL, RCL_SERVER);
696                 if (buffer->lb_len > 0) {
697                         rc = mo_xattr_get(env, next, buffer,
698                                           XATTR_NAME_ACL_ACCESS);
699                         if (rc < 0) {
700                                 if (rc == -ENODATA) {
701                                         repbody->aclsize = 0;
702                                         repbody->valid |= OBD_MD_FLACL;
703                                         rc = 0;
704                                 } else if (rc == -EOPNOTSUPP) {
705                                         rc = 0;
706                                 } else {
707                                         CERROR("got acl size: %d\n", rc);
708                                 }
709                         } else {
710                                 repbody->aclsize = rc;
711                                 repbody->valid |= OBD_MD_FLACL;
712                                 rc = 0;
713                         }
714                 }
715         }
716 #endif
717
718         if (reqbody->valid & OBD_MD_FLMDSCAPA &&
719             info->mti_mdt->mdt_opts.mo_mds_capa &&
720             info->mti_exp->exp_connect_flags & OBD_CONNECT_MDS_CAPA) {
721                 struct lustre_capa *capa;
722
723                 capa = req_capsule_server_get(pill, &RMF_CAPA1);
724                 LASSERT(capa);
725                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
726                 rc = mo_capa_get(env, next, capa, 0);
727                 if (rc)
728                         RETURN(rc);
729                 repbody->valid |= OBD_MD_FLMDSCAPA;
730         }
731
732 out:
733         if (rc == 0)
734                 mdt_counter_incr(req, LPROC_MDT_GETATTR);
735
736         RETURN(rc);
737 }
738
739 static int mdt_renew_capa(struct mdt_thread_info *info)
740 {
741         struct mdt_object  *obj = info->mti_object;
742         struct mdt_body    *body;
743         struct lustre_capa *capa, *c;
744         int rc;
745         ENTRY;
746
747         /* if object doesn't exist, or server has disabled capability,
748          * return directly, client will find body->valid OBD_MD_FLOSSCAPA
749          * flag not set.
750          */
751         if (!obj || !info->mti_mdt->mdt_opts.mo_oss_capa ||
752             !(info->mti_exp->exp_connect_flags & OBD_CONNECT_OSS_CAPA))
753                 RETURN(0);
754
755         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
756         LASSERT(body != NULL);
757
758         c = req_capsule_client_get(info->mti_pill, &RMF_CAPA1);
759         LASSERT(c);
760
761         capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA2);
762         LASSERT(capa);
763
764         *capa = *c;
765         rc = mo_capa_get(info->mti_env, mdt_object_child(obj), capa, 1);
766         if (rc == 0)
767                 body->valid |= OBD_MD_FLOSSCAPA;
768         RETURN(rc);
769 }
770
771 static int mdt_getattr(struct mdt_thread_info *info)
772 {
773         struct mdt_object       *obj = info->mti_object;
774         struct req_capsule      *pill = info->mti_pill;
775         struct mdt_body         *reqbody;
776         struct mdt_body         *repbody;
777         mode_t                   mode;
778         int rc, rc2;
779         ENTRY;
780
781         reqbody = req_capsule_client_get(pill, &RMF_MDT_BODY);
782         LASSERT(reqbody);
783
784         if (reqbody->valid & OBD_MD_FLOSSCAPA) {
785                 rc = req_capsule_server_pack(pill);
786                 if (unlikely(rc))
787                         RETURN(err_serious(rc));
788                 rc = mdt_renew_capa(info);
789                 GOTO(out_shrink, rc);
790         }
791
792         LASSERT(obj != NULL);
793         LASSERT(lu_object_assert_exists(&obj->mot_obj.mo_lu));
794
795         mode = lu_object_attr(&obj->mot_obj.mo_lu);
796
797         /* old clients may not report needed easize, use max value then */
798         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
799                              reqbody->eadatasize == 0 ?
800                              info->mti_mdt->mdt_max_mdsize :
801                              reqbody->eadatasize);
802
803         rc = req_capsule_server_pack(pill);
804         if (unlikely(rc != 0))
805                 RETURN(err_serious(rc));
806
807         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
808         LASSERT(repbody != NULL);
809         repbody->eadatasize = 0;
810         repbody->aclsize = 0;
811
812         if (reqbody->valid & OBD_MD_FLRMTPERM)
813                 rc = mdt_init_ucred(info, reqbody);
814         else
815                 rc = mdt_check_ucred(info);
816         if (unlikely(rc))
817                 GOTO(out_shrink, rc);
818
819         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
820         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
821
822         /*
823          * Don't check capability at all, because rename might getattr for
824          * remote obj, and at that time no capability is available.
825          */
826         mdt_set_capainfo(info, 1, &reqbody->fid1, BYPASS_CAPA);
827         rc = mdt_getattr_internal(info, obj, 0);
828         if (reqbody->valid & OBD_MD_FLRMTPERM)
829                 mdt_exit_ucred(info);
830         EXIT;
831 out_shrink:
832         mdt_client_compatibility(info);
833         rc2 = mdt_fix_reply(info);
834         if (rc == 0)
835                 rc = rc2;
836         return rc;
837 }
838
839 static int mdt_is_subdir(struct mdt_thread_info *info)
840 {
841         struct mdt_object     *o = info->mti_object;
842         struct req_capsule    *pill = info->mti_pill;
843         const struct mdt_body *body = info->mti_body;
844         struct mdt_body       *repbody;
845         int                    rc;
846         ENTRY;
847
848         LASSERT(o != NULL);
849
850         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
851
852         /*
853          * We save last checked parent fid to @repbody->fid1 for remote
854          * directory case.
855          */
856         LASSERT(fid_is_sane(&body->fid2));
857         LASSERT(mdt_object_exists(o) > 0);
858         rc = mdo_is_subdir(info->mti_env, mdt_object_child(o),
859                            &body->fid2, &repbody->fid1);
860         if (rc == 0 || rc == -EREMOTE)
861                 repbody->valid |= OBD_MD_FLID;
862
863         RETURN(rc);
864 }
865
866 static int mdt_raw_lookup(struct mdt_thread_info *info,
867                           struct mdt_object *parent,
868                           const struct lu_name *lname,
869                           struct ldlm_reply *ldlm_rep)
870 {
871         struct md_object *next = mdt_object_child(info->mti_object);
872         const struct mdt_body *reqbody = info->mti_body;
873         struct lu_fid *child_fid = &info->mti_tmp_fid1;
874         struct mdt_body *repbody;
875         int rc;
876         ENTRY;
877
878         if (reqbody->valid != OBD_MD_FLID)
879                 RETURN(0);
880
881         LASSERT(!info->mti_cross_ref);
882
883         /* Only got the fid of this obj by name */
884         fid_zero(child_fid);
885         rc = mdo_lookup(info->mti_env, next, lname, child_fid,
886                         &info->mti_spec);
887 #if 0
888         /* XXX is raw_lookup possible as intent operation? */
889         if (rc != 0) {
890                 if (rc == -ENOENT)
891                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
892                 RETURN(rc);
893         } else
894                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
895
896         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
897 #endif
898         if (rc == 0) {
899                 repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
900                 repbody->fid1 = *child_fid;
901                 repbody->valid = OBD_MD_FLID;
902         }
903         RETURN(1);
904 }
905
906 /*
907  * UPDATE lock should be taken against parent, and be release before exit;
908  * child_bits lock should be taken against child, and be returned back:
909  *            (1)normal request should release the child lock;
910  *            (2)intent request will grant the lock to client.
911  */
912 static int mdt_getattr_name_lock(struct mdt_thread_info *info,
913                                  struct mdt_lock_handle *lhc,
914                                  __u64 child_bits,
915                                  struct ldlm_reply *ldlm_rep)
916 {
917         struct ptlrpc_request  *req       = mdt_info_req(info);
918         struct mdt_body        *reqbody   = NULL;
919         struct mdt_object      *parent    = info->mti_object;
920         struct mdt_object      *child;
921         struct md_object       *next      = mdt_object_child(parent);
922         struct lu_fid          *child_fid = &info->mti_tmp_fid1;
923         struct lu_name         *lname     = NULL;
924         const char             *name      = NULL;
925         int                     namelen   = 0;
926         struct mdt_lock_handle *lhp       = NULL;
927         struct ldlm_lock       *lock;
928         struct ldlm_res_id     *res_id;
929         int                     is_resent;
930         int                     ma_need = 0;
931         int                     rc;
932
933         ENTRY;
934
935         is_resent = lustre_handle_is_used(&lhc->mlh_reg_lh);
936         LASSERT(ergo(is_resent,
937                      lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT));
938
939         LASSERT(parent != NULL);
940         name = req_capsule_client_get(info->mti_pill, &RMF_NAME);
941         if (name == NULL)
942                 RETURN(err_serious(-EFAULT));
943
944         namelen = req_capsule_get_size(info->mti_pill, &RMF_NAME,
945                                        RCL_CLIENT) - 1;
946         if (!info->mti_cross_ref) {
947                 /*
948                  * XXX: Check for "namelen == 0" is for getattr by fid
949                  * (OBD_CONNECT_ATTRFID), otherwise do not allow empty name,
950                  * that is the name must contain at least one character and
951                  * the terminating '\0'
952                  */
953                 if (namelen == 0) {
954                         reqbody = req_capsule_client_get(info->mti_pill,
955                                                          &RMF_MDT_BODY);
956                         if (unlikely(reqbody == NULL))
957                                 RETURN(err_serious(-EFAULT));
958
959                         if (unlikely(!fid_is_sane(&reqbody->fid2)))
960                                 RETURN(err_serious(-EINVAL));
961
962                         name = NULL;
963                         CDEBUG(D_INODE, "getattr with lock for "DFID"/"DFID", "
964                                "ldlm_rep = %p\n",
965                                PFID(mdt_object_fid(parent)),
966                                PFID(&reqbody->fid2), ldlm_rep);
967                 } else {
968                         lname = mdt_name(info->mti_env, (char *)name, namelen);
969                         CDEBUG(D_INODE, "getattr with lock for "DFID"/%s, "
970                                "ldlm_rep = %p\n", PFID(mdt_object_fid(parent)),
971                                name, ldlm_rep);
972                 }
973         }
974         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_EXECD);
975
976         rc = mdt_object_exists(parent);
977         if (unlikely(rc == 0)) {
978                 LU_OBJECT_DEBUG(D_INODE, info->mti_env,
979                                 &parent->mot_obj.mo_lu,
980                                 "Parent doesn't exist!\n");
981                 RETURN(-ESTALE);
982         } else if (!info->mti_cross_ref) {
983                 LASSERTF(rc > 0, "Parent "DFID" is on remote server\n",
984                          PFID(mdt_object_fid(parent)));
985         }
986         if (lname) {
987                 rc = mdt_raw_lookup(info, parent, lname, ldlm_rep);
988                 if (rc != 0) {
989                         if (rc > 0)
990                                 rc = 0;
991                         RETURN(rc);
992                 }
993         }
994
995         if (info->mti_cross_ref) {
996                 /* Only getattr on the child. Parent is on another node. */
997                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
998                 child = parent;
999                 CDEBUG(D_INODE, "partial getattr_name child_fid = "DFID", "
1000                        "ldlm_rep=%p\n", PFID(mdt_object_fid(child)), ldlm_rep);
1001
1002                 if (is_resent) {
1003                         /* Do not take lock for resent case. */
1004                         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1005                         LASSERTF(lock != NULL, "Invalid lock handle "LPX64"\n",
1006                                  lhc->mlh_reg_lh.cookie);
1007                         LASSERT(fid_res_name_eq(mdt_object_fid(child),
1008                                                 &lock->l_resource->lr_name));
1009                         LDLM_LOCK_PUT(lock);
1010                         rc = 0;
1011                 } else {
1012                         mdt_lock_handle_init(lhc);
1013                         mdt_lock_reg_init(lhc, LCK_PR);
1014
1015                         /*
1016                          * Object's name is on another MDS, no lookup lock is
1017                          * needed here but update is.
1018                          */
1019                         child_bits &= ~MDS_INODELOCK_LOOKUP;
1020                         child_bits |= MDS_INODELOCK_UPDATE;
1021
1022                         rc = mdt_object_lock(info, child, lhc, child_bits,
1023                                              MDT_LOCAL_LOCK);
1024                 }
1025                 if (rc == 0) {
1026                         /* Finally, we can get attr for child. */
1027                         mdt_set_capainfo(info, 0, mdt_object_fid(child),
1028                                          BYPASS_CAPA);
1029                         rc = mdt_getattr_internal(info, child, 0);
1030                         if (unlikely(rc != 0))
1031                                 mdt_object_unlock(info, child, lhc, 1);
1032                 }
1033                 RETURN(rc);
1034         }
1035
1036         if (lname) {
1037                 /* step 1: lock parent only if parent is a directory */
1038                 if (S_ISDIR(lu_object_attr(&parent->mot_obj.mo_lu))) {
1039                         lhp = &info->mti_lh[MDT_LH_PARENT];
1040                         mdt_lock_pdo_init(lhp, LCK_PR, name, namelen);
1041                         rc = mdt_object_lock(info, parent, lhp,
1042                                              MDS_INODELOCK_UPDATE,
1043                                              MDT_LOCAL_LOCK);
1044                         if (unlikely(rc != 0))
1045                                 RETURN(rc);
1046                 }
1047
1048                 /* step 2: lookup child's fid by name */
1049                 fid_zero(child_fid);
1050                 rc = mdo_lookup(info->mti_env, next, lname, child_fid,
1051                                 &info->mti_spec);
1052
1053                 if (rc != 0) {
1054                         if (rc == -ENOENT)
1055                                 mdt_set_disposition(info, ldlm_rep,
1056                                                     DISP_LOOKUP_NEG);
1057                         GOTO(out_parent, rc);
1058                 } else
1059                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1060         } else {
1061                 *child_fid = reqbody->fid2;
1062                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1063         }
1064
1065         /*
1066          *step 3: find the child object by fid & lock it.
1067          *        regardless if it is local or remote.
1068          */
1069         child = mdt_object_find(info->mti_env, info->mti_mdt, child_fid);
1070
1071         if (unlikely(IS_ERR(child)))
1072                 GOTO(out_parent, rc = PTR_ERR(child));
1073         if (is_resent) {
1074                 /* Do not take lock for resent case. */
1075                 lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1076                 LASSERTF(lock != NULL, "Invalid lock handle "LPX64"\n",
1077                          lhc->mlh_reg_lh.cookie);
1078
1079                 res_id = &lock->l_resource->lr_name;
1080                 if (!fid_res_name_eq(mdt_object_fid(child),
1081                                     &lock->l_resource->lr_name)) {
1082                          LASSERTF(fid_res_name_eq(mdt_object_fid(parent),
1083                                                  &lock->l_resource->lr_name),
1084                                  "Lock res_id: %lu/%lu/%lu, Fid: "DFID".\n",
1085                                  (unsigned long)res_id->name[0],
1086                                  (unsigned long)res_id->name[1],
1087                                  (unsigned long)res_id->name[2],
1088                                  PFID(mdt_object_fid(parent)));
1089                           CWARN("Although resent, but still not get child lock"
1090                                 "parent:"DFID" child:"DFID"\n",
1091                                 PFID(mdt_object_fid(parent)),
1092                                 PFID(mdt_object_fid(child)));
1093                           lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
1094                           LDLM_LOCK_PUT(lock);
1095                           GOTO(relock, 0);
1096                 }
1097                 LDLM_LOCK_PUT(lock);
1098                 rc = 0;
1099         } else {
1100 relock:
1101                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_RESEND, obd_timeout*2);
1102                 mdt_lock_handle_init(lhc);
1103                 if (child_bits == MDS_INODELOCK_LAYOUT)
1104                         mdt_lock_reg_init(lhc, LCK_CR);
1105                 else
1106                         mdt_lock_reg_init(lhc, LCK_PR);
1107
1108                 if (mdt_object_exists(child) == 0) {
1109                         LU_OBJECT_DEBUG(D_INODE, info->mti_env,
1110                                         &child->mot_obj.mo_lu,
1111                                         "Object doesn't exist!\n");
1112                         GOTO(out_child, rc = -ENOENT);
1113                 }
1114
1115                 if (!(child_bits & MDS_INODELOCK_UPDATE)) {
1116                         struct md_attr *ma = &info->mti_attr;
1117
1118                         ma->ma_valid = 0;
1119                         ma->ma_need = MA_INODE;
1120                         rc = mo_attr_get(info->mti_env,
1121                                          mdt_object_child(child), ma);
1122                         if (unlikely(rc != 0))
1123                                 GOTO(out_child, rc);
1124
1125                         /* layout lock is used only on regular files */
1126                         if ((ma->ma_valid & MA_INODE) &&
1127                             (ma->ma_attr.la_valid & LA_MODE) &&
1128                             !S_ISREG(ma->ma_attr.la_mode))
1129                                 child_bits &= ~MDS_INODELOCK_LAYOUT;
1130
1131                         /* If the file has not been changed for some time, we
1132                          * return not only a LOOKUP lock, but also an UPDATE
1133                          * lock and this might save us RPC on later STAT. For
1134                          * directories, it also let negative dentry starts
1135                          * working for this dir. */
1136                         if (ma->ma_valid & MA_INODE &&
1137                             ma->ma_attr.la_valid & LA_CTIME &&
1138                             info->mti_mdt->mdt_namespace->ns_ctime_age_limit +
1139                                 ma->ma_attr.la_ctime < cfs_time_current_sec())
1140                                 child_bits |= MDS_INODELOCK_UPDATE;
1141                 }
1142
1143                 rc = mdt_object_lock(info, child, lhc, child_bits,
1144                                      MDT_CROSS_LOCK);
1145
1146                 if (unlikely(rc != 0))
1147                         GOTO(out_child, rc);
1148         }
1149
1150         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1151         /* Get MA_SOM attributes if update lock is given. */
1152         if (lock &&
1153             lock->l_policy_data.l_inodebits.bits & MDS_INODELOCK_UPDATE &&
1154             S_ISREG(lu_object_attr(&mdt_object_child(child)->mo_lu)))
1155                 ma_need = MA_SOM;
1156
1157         /* finally, we can get attr for child. */
1158         mdt_set_capainfo(info, 1, child_fid, BYPASS_CAPA);
1159         rc = mdt_getattr_internal(info, child, ma_need);
1160         if (unlikely(rc != 0)) {
1161                 mdt_object_unlock(info, child, lhc, 1);
1162         } else if (lock) {
1163                 /* Debugging code. */
1164                 res_id = &lock->l_resource->lr_name;
1165                 LDLM_DEBUG(lock, "Returning lock to client");
1166                 LASSERTF(fid_res_name_eq(mdt_object_fid(child),
1167                                          &lock->l_resource->lr_name),
1168                          "Lock res_id: %lu/%lu/%lu, Fid: "DFID".\n",
1169                          (unsigned long)res_id->name[0],
1170                          (unsigned long)res_id->name[1],
1171                          (unsigned long)res_id->name[2],
1172                          PFID(mdt_object_fid(child)));
1173                 mdt_pack_size2body(info, child);
1174         }
1175         if (lock)
1176                 LDLM_LOCK_PUT(lock);
1177
1178         EXIT;
1179 out_child:
1180         mdt_object_put(info->mti_env, child);
1181 out_parent:
1182         if (lhp)
1183                 mdt_object_unlock(info, parent, lhp, 1);
1184         return rc;
1185 }
1186
1187 /* normal handler: should release the child lock */
1188 static int mdt_getattr_name(struct mdt_thread_info *info)
1189 {
1190         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_CHILD];
1191         struct mdt_body        *reqbody;
1192         struct mdt_body        *repbody;
1193         int rc, rc2;
1194         ENTRY;
1195
1196         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1197         LASSERT(reqbody != NULL);
1198         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1199         LASSERT(repbody != NULL);
1200
1201         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
1202         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
1203         repbody->eadatasize = 0;
1204         repbody->aclsize = 0;
1205
1206         rc = mdt_init_ucred(info, reqbody);
1207         if (unlikely(rc))
1208                 GOTO(out_shrink, rc);
1209
1210         rc = mdt_getattr_name_lock(info, lhc, MDS_INODELOCK_UPDATE, NULL);
1211         if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
1212                 ldlm_lock_decref(&lhc->mlh_reg_lh, lhc->mlh_reg_mode);
1213                 lhc->mlh_reg_lh.cookie = 0;
1214         }
1215         mdt_exit_ucred(info);
1216         EXIT;
1217 out_shrink:
1218         mdt_client_compatibility(info);
1219         rc2 = mdt_fix_reply(info);
1220         if (rc == 0)
1221                 rc = rc2;
1222         return rc;
1223 }
1224
1225 static const struct lu_device_operations mdt_lu_ops;
1226
1227 static int lu_device_is_mdt(struct lu_device *d)
1228 {
1229         return ergo(d != NULL && d->ld_ops != NULL, d->ld_ops == &mdt_lu_ops);
1230 }
1231
1232 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
1233                          void *karg, void *uarg);
1234
1235 static int mdt_set_info(struct mdt_thread_info *info)
1236 {
1237         struct ptlrpc_request *req = mdt_info_req(info);
1238         char *key;
1239         void *val;
1240         int keylen, vallen, rc = 0;
1241         ENTRY;
1242
1243         rc = req_capsule_server_pack(info->mti_pill);
1244         if (rc)
1245                 RETURN(rc);
1246
1247         key = req_capsule_client_get(info->mti_pill, &RMF_SETINFO_KEY);
1248         if (key == NULL) {
1249                 DEBUG_REQ(D_HA, req, "no set_info key");
1250                 RETURN(-EFAULT);
1251         }
1252
1253         keylen = req_capsule_get_size(info->mti_pill, &RMF_SETINFO_KEY,
1254                                       RCL_CLIENT);
1255
1256         val = req_capsule_client_get(info->mti_pill, &RMF_SETINFO_VAL);
1257         if (val == NULL) {
1258                 DEBUG_REQ(D_HA, req, "no set_info val");
1259                 RETURN(-EFAULT);
1260         }
1261
1262         vallen = req_capsule_get_size(info->mti_pill, &RMF_SETINFO_VAL,
1263                                       RCL_CLIENT);
1264
1265         /* Swab any part of val you need to here */
1266         if (KEY_IS(KEY_READ_ONLY)) {
1267                 req->rq_status = 0;
1268                 lustre_msg_set_status(req->rq_repmsg, 0);
1269
1270                 cfs_spin_lock(&req->rq_export->exp_lock);
1271                 if (*(__u32 *)val)
1272                         req->rq_export->exp_connect_flags |= OBD_CONNECT_RDONLY;
1273                 else
1274                         req->rq_export->exp_connect_flags &=~OBD_CONNECT_RDONLY;
1275                 cfs_spin_unlock(&req->rq_export->exp_lock);
1276
1277         } else if (KEY_IS(KEY_CHANGELOG_CLEAR)) {
1278                 struct changelog_setinfo *cs =
1279                         (struct changelog_setinfo *)val;
1280                 if (vallen != sizeof(*cs)) {
1281                         CERROR("Bad changelog_clear setinfo size %d\n", vallen);
1282                         RETURN(-EINVAL);
1283                 }
1284                 if (ptlrpc_req_need_swab(req)) {
1285                         __swab64s(&cs->cs_recno);
1286                         __swab32s(&cs->cs_id);
1287                 }
1288
1289                 rc = mdt_iocontrol(OBD_IOC_CHANGELOG_CLEAR, info->mti_exp,
1290                                    vallen, val, NULL);
1291                 lustre_msg_set_status(req->rq_repmsg, rc);
1292
1293         } else {
1294                 RETURN(-EINVAL);
1295         }
1296         RETURN(0);
1297 }
1298
1299 static int mdt_connect(struct mdt_thread_info *info)
1300 {
1301         int rc;
1302         struct ptlrpc_request *req;
1303
1304         req = mdt_info_req(info);
1305         rc = target_handle_connect(req);
1306         if (rc == 0) {
1307                 LASSERT(req->rq_export != NULL);
1308                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
1309                 rc = mdt_init_sec_level(info);
1310                 if (rc == 0)
1311                         rc = mdt_init_idmap(info);
1312                 if (rc != 0)
1313                         obd_disconnect(class_export_get(req->rq_export));
1314         } else {
1315                 rc = err_serious(rc);
1316         }
1317         return rc;
1318 }
1319
1320 static int mdt_disconnect(struct mdt_thread_info *info)
1321 {
1322         int rc;
1323         ENTRY;
1324
1325         rc = target_handle_disconnect(mdt_info_req(info));
1326         if (rc)
1327                 rc = err_serious(rc);
1328         RETURN(rc);
1329 }
1330
1331 static int mdt_sendpage(struct mdt_thread_info *info,
1332                         struct lu_rdpg *rdpg, int nob)
1333 {
1334         struct ptlrpc_request   *req = mdt_info_req(info);
1335         struct obd_export       *exp = req->rq_export;
1336         struct ptlrpc_bulk_desc *desc;
1337         struct l_wait_info      *lwi = &info->mti_u.rdpg.mti_wait_info;
1338         int                      tmpcount;
1339         int                      tmpsize;
1340         int                      i;
1341         int                      rc;
1342         ENTRY;
1343
1344         desc = ptlrpc_prep_bulk_exp(req, rdpg->rp_npages, BULK_PUT_SOURCE,
1345                                     MDS_BULK_PORTAL);
1346         if (desc == NULL)
1347                 RETURN(-ENOMEM);
1348
1349         if (!(exp->exp_connect_flags & OBD_CONNECT_BRW_SIZE))
1350                 /* old client requires reply size in it's PAGE_SIZE,
1351                  * which is rdpg->rp_count */
1352                 nob = rdpg->rp_count;
1353
1354         for (i = 0, tmpcount = nob; i < rdpg->rp_npages && tmpcount > 0;
1355              i++, tmpcount -= tmpsize) {
1356                 tmpsize = min_t(int, tmpcount, CFS_PAGE_SIZE);
1357                 ptlrpc_prep_bulk_page(desc, rdpg->rp_pages[i], 0, tmpsize);
1358         }
1359
1360         LASSERT(desc->bd_nob == nob);
1361         rc = target_bulk_io(exp, desc, lwi);
1362         ptlrpc_free_bulk(desc);
1363         RETURN(rc);
1364 }
1365
1366 #ifdef HAVE_SPLIT_SUPPORT
1367 /*
1368  * Retrieve dir entry from the page and insert it to the slave object, actually,
1369  * this should be in osd layer, but since it will not in the final product, so
1370  * just do it here and do not define more moo api anymore for this.
1371  */
1372 static int mdt_write_dir_page(struct mdt_thread_info *info, struct page *page,
1373                               int size)
1374 {
1375         struct mdt_object *object = info->mti_object;
1376         struct lu_fid *lf = &info->mti_tmp_fid2;
1377         struct md_attr *ma = &info->mti_attr;
1378         struct lu_dirpage *dp;
1379         struct lu_dirent *ent;
1380         int rc = 0, offset = 0;
1381         ENTRY;
1382
1383         /* Make sure we have at least one entry. */
1384         if (size == 0)
1385                 RETURN(-EINVAL);
1386
1387         /*
1388          * Disable trans for this name insert, since it will include many trans
1389          * for this.
1390          */
1391         info->mti_no_need_trans = 1;
1392         /*
1393          * When write_dir_page, no need update parent's ctime,
1394          * and no permission check for name_insert.
1395          */
1396         ma->ma_attr.la_ctime = 0;
1397         ma->ma_attr.la_valid = LA_MODE;
1398         ma->ma_valid = MA_INODE;
1399
1400         cfs_kmap(page);
1401         dp = page_address(page);
1402         offset = (int)((__u32)lu_dirent_start(dp) - (__u32)dp);
1403
1404         for (ent = lu_dirent_start(dp); ent != NULL;
1405              ent = lu_dirent_next(ent)) {
1406                 struct lu_name *lname;
1407                 char *name;
1408
1409                 if (le16_to_cpu(ent->lde_namelen) == 0)
1410                         continue;
1411
1412                 fid_le_to_cpu(lf, &ent->lde_fid);
1413                 if (le64_to_cpu(ent->lde_hash) & MAX_HASH_HIGHEST_BIT)
1414                         ma->ma_attr.la_mode = S_IFDIR;
1415                 else
1416                         ma->ma_attr.la_mode = 0;
1417                 OBD_ALLOC(name, le16_to_cpu(ent->lde_namelen) + 1);
1418                 if (name == NULL)
1419                         GOTO(out, rc = -ENOMEM);
1420
1421                 memcpy(name, ent->lde_name, le16_to_cpu(ent->lde_namelen));
1422                 lname = mdt_name(info->mti_env, name,
1423                                  le16_to_cpu(ent->lde_namelen));
1424                 ma->ma_attr_flags |= (MDS_PERM_BYPASS | MDS_QUOTA_IGNORE);
1425                 rc = mdo_name_insert(info->mti_env,
1426                                      md_object_next(&object->mot_obj),
1427                                      lname, lf, ma);
1428                 OBD_FREE(name, le16_to_cpu(ent->lde_namelen) + 1);
1429                 if (rc) {
1430                         CERROR("Can't insert %*.*s, rc %d\n",
1431                                le16_to_cpu(ent->lde_namelen),
1432                                le16_to_cpu(ent->lde_namelen),
1433                                ent->lde_name, rc);
1434                         GOTO(out, rc);
1435                 }
1436
1437                 offset += lu_dirent_size(ent);
1438                 if (offset >= size)
1439                         break;
1440         }
1441         EXIT;
1442 out:
1443         cfs_kunmap(page);
1444         return rc;
1445 }
1446
1447 static int mdt_bulk_timeout(void *data)
1448 {
1449         ENTRY;
1450
1451         CERROR("mdt bulk transfer timeout \n");
1452
1453         RETURN(1);
1454 }
1455
1456 static int mdt_writepage(struct mdt_thread_info *info)
1457 {
1458         struct ptlrpc_request   *req = mdt_info_req(info);
1459         struct mdt_body         *reqbody;
1460         struct l_wait_info      *lwi;
1461         struct ptlrpc_bulk_desc *desc;
1462         struct page             *page;
1463         int                rc;
1464         ENTRY;
1465
1466
1467         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1468         if (reqbody == NULL)
1469                 RETURN(err_serious(-EFAULT));
1470
1471         desc = ptlrpc_prep_bulk_exp(req, 1, BULK_GET_SINK, MDS_BULK_PORTAL);
1472         if (desc == NULL)
1473                 RETURN(err_serious(-ENOMEM));
1474
1475         /* allocate the page for the desc */
1476         page = cfs_alloc_page(CFS_ALLOC_STD);
1477         if (page == NULL)
1478                 GOTO(desc_cleanup, rc = -ENOMEM);
1479
1480         CDEBUG(D_INFO, "Received page offset %d size %d \n",
1481                (int)reqbody->size, (int)reqbody->nlink);
1482
1483         ptlrpc_prep_bulk_page(desc, page, (int)reqbody->size,
1484                               (int)reqbody->nlink);
1485
1486         rc = sptlrpc_svc_prep_bulk(req, desc);
1487         if (rc != 0)
1488                 GOTO(cleanup_page, rc);
1489         /*
1490          * Check if client was evicted while we were doing i/o before touching
1491          * network.
1492          */
1493         OBD_ALLOC_PTR(lwi);
1494         if (!lwi)
1495                 GOTO(cleanup_page, rc = -ENOMEM);
1496
1497         if (desc->bd_export->exp_failed)
1498                 rc = -ENOTCONN;
1499         else
1500                 rc = ptlrpc_start_bulk_transfer (desc);
1501         if (rc == 0) {
1502                 *lwi = LWI_TIMEOUT_INTERVAL(obd_timeout * CFS_HZ / 4, CFS_HZ,
1503                                             mdt_bulk_timeout, desc);
1504                 rc = l_wait_event(desc->bd_waitq, !ptlrpc_bulk_active(desc) ||
1505                                   desc->bd_export->exp_failed, lwi);
1506                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
1507                 if (rc == -ETIMEDOUT) {
1508                         DEBUG_REQ(D_ERROR, req, "timeout on bulk GET");
1509                         ptlrpc_abort_bulk(desc);
1510                 } else if (desc->bd_export->exp_failed) {
1511                         DEBUG_REQ(D_ERROR, req, "Eviction on bulk GET");
1512                         rc = -ENOTCONN;
1513                         ptlrpc_abort_bulk(desc);
1514                 } else if (!desc->bd_success ||
1515                            desc->bd_nob_transferred != desc->bd_nob) {
1516                         DEBUG_REQ(D_ERROR, req, "%s bulk GET %d(%d)",
1517                                   desc->bd_success ?
1518                                   "truncated" : "network error on",
1519                                   desc->bd_nob_transferred, desc->bd_nob);
1520                         /* XXX should this be a different errno? */
1521                         rc = -ETIMEDOUT;
1522                 }
1523         } else {
1524                 DEBUG_REQ(D_ERROR, req, "ptlrpc_bulk_get failed: rc %d", rc);
1525         }
1526         if (rc)
1527                 GOTO(cleanup_lwi, rc);
1528         rc = mdt_write_dir_page(info, page, reqbody->nlink);
1529
1530 cleanup_lwi:
1531         OBD_FREE_PTR(lwi);
1532 cleanup_page:
1533         cfs_free_page(page);
1534 desc_cleanup:
1535         ptlrpc_free_bulk(desc);
1536         RETURN(rc);
1537 }
1538 #endif
1539
1540 static int mdt_readpage(struct mdt_thread_info *info)
1541 {
1542         struct mdt_object *object = info->mti_object;
1543         struct lu_rdpg    *rdpg = &info->mti_u.rdpg.mti_rdpg;
1544         struct mdt_body   *reqbody;
1545         struct mdt_body   *repbody;
1546         int                rc;
1547         int                i;
1548         ENTRY;
1549
1550         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK))
1551                 RETURN(err_serious(-ENOMEM));
1552
1553         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1554         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1555         if (reqbody == NULL || repbody == NULL)
1556                 RETURN(err_serious(-EFAULT));
1557
1558         /*
1559          * prepare @rdpg before calling lower layers and transfer itself. Here
1560          * reqbody->size contains offset of where to start to read and
1561          * reqbody->nlink contains number bytes to read.
1562          */
1563         rdpg->rp_hash = reqbody->size;
1564         if (rdpg->rp_hash != reqbody->size) {
1565                 CERROR("Invalid hash: "LPX64" != "LPX64"\n",
1566                        rdpg->rp_hash, reqbody->size);
1567                 RETURN(-EFAULT);
1568         }
1569
1570         rdpg->rp_attrs = reqbody->mode;
1571         if (info->mti_exp->exp_connect_flags & OBD_CONNECT_64BITHASH)
1572                 rdpg->rp_attrs |= LUDA_64BITHASH;
1573         rdpg->rp_count  = min_t(unsigned int, reqbody->nlink,
1574                                 PTLRPC_MAX_BRW_SIZE);
1575         rdpg->rp_npages = (rdpg->rp_count + CFS_PAGE_SIZE - 1) >>
1576                           CFS_PAGE_SHIFT;
1577         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1578         if (rdpg->rp_pages == NULL)
1579                 RETURN(-ENOMEM);
1580
1581         for (i = 0; i < rdpg->rp_npages; ++i) {
1582                 rdpg->rp_pages[i] = cfs_alloc_page(CFS_ALLOC_STD);
1583                 if (rdpg->rp_pages[i] == NULL)
1584                         GOTO(free_rdpg, rc = -ENOMEM);
1585         }
1586
1587         /* call lower layers to fill allocated pages with directory data */
1588         rc = mo_readpage(info->mti_env, mdt_object_child(object), rdpg);
1589         if (rc < 0)
1590                 GOTO(free_rdpg, rc);
1591
1592         /* send pages to client */
1593         rc = mdt_sendpage(info, rdpg, rc);
1594
1595         EXIT;
1596 free_rdpg:
1597
1598         for (i = 0; i < rdpg->rp_npages; i++)
1599                 if (rdpg->rp_pages[i] != NULL)
1600                         cfs_free_page(rdpg->rp_pages[i]);
1601         OBD_FREE(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1602
1603         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1604                 RETURN(0);
1605
1606         return rc;
1607 }
1608
1609 static int mdt_reint_internal(struct mdt_thread_info *info,
1610                               struct mdt_lock_handle *lhc,
1611                               __u32 op)
1612 {
1613         struct req_capsule      *pill = info->mti_pill;
1614         struct md_quota         *mq = md_quota(info->mti_env);
1615         struct mdt_body         *repbody;
1616         int                      rc = 0, rc2;
1617         ENTRY;
1618
1619
1620         rc = mdt_reint_unpack(info, op);
1621         if (rc != 0) {
1622                 CERROR("Can't unpack reint, rc %d\n", rc);
1623                 RETURN(err_serious(rc));
1624         }
1625
1626         /* for replay (no_create) lmm is not needed, client has it already */
1627         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1628                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
1629                                      info->mti_rr.rr_eadatalen);
1630
1631         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1632                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
1633                                      info->mti_mdt->mdt_max_cookiesize);
1634
1635         rc = req_capsule_server_pack(pill);
1636         if (rc != 0) {
1637                 CERROR("Can't pack response, rc %d\n", rc);
1638                 RETURN(err_serious(rc));
1639         }
1640
1641         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
1642                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1643                 LASSERT(repbody);
1644                 repbody->eadatasize = 0;
1645                 repbody->aclsize = 0;
1646         }
1647
1648         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_REINT_DELAY, 10);
1649
1650         /* for replay no cookkie / lmm need, because client have this already */
1651         if (info->mti_spec.no_create)
1652                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1653                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
1654
1655         rc = mdt_init_ucred_reint(info);
1656         if (rc)
1657                 GOTO(out_shrink, rc);
1658
1659         rc = mdt_fix_attr_ucred(info, op);
1660         if (rc != 0)
1661                 GOTO(out_ucred, rc = err_serious(rc));
1662
1663         if (mdt_check_resent(info, mdt_reconstruct, lhc)) {
1664                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
1665                 GOTO(out_ucred, rc);
1666         }
1667         mq->mq_exp = info->mti_exp;
1668         rc = mdt_reint_rec(info, lhc);
1669         EXIT;
1670 out_ucred:
1671         mdt_exit_ucred(info);
1672 out_shrink:
1673         mdt_client_compatibility(info);
1674         rc2 = mdt_fix_reply(info);
1675         if (rc == 0)
1676                 rc = rc2;
1677         return rc;
1678 }
1679
1680 static long mdt_reint_opcode(struct mdt_thread_info *info,
1681                              const struct req_format **fmt)
1682 {
1683         struct mdt_rec_reint *rec;
1684         long opc;
1685
1686         opc = err_serious(-EFAULT);
1687         rec = req_capsule_client_get(info->mti_pill, &RMF_REC_REINT);
1688         if (rec != NULL) {
1689                 opc = rec->rr_opcode;
1690                 DEBUG_REQ(D_INODE, mdt_info_req(info), "reint opt = %ld", opc);
1691                 if (opc < REINT_MAX && fmt[opc] != NULL)
1692                         req_capsule_extend(info->mti_pill, fmt[opc]);
1693                 else {
1694                         CERROR("Unsupported opc: %ld\n", opc);
1695                         opc = err_serious(opc);
1696                 }
1697         }
1698         return opc;
1699 }
1700
1701 static int mdt_reint(struct mdt_thread_info *info)
1702 {
1703         long opc;
1704         int  rc;
1705
1706         static const struct req_format *reint_fmts[REINT_MAX] = {
1707                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
1708                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
1709                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
1710                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
1711                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
1712                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
1713                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR
1714         };
1715
1716         ENTRY;
1717
1718         opc = mdt_reint_opcode(info, reint_fmts);
1719         if (opc >= 0) {
1720                 /*
1721                  * No lock possible here from client to pass it to reint code
1722                  * path.
1723                  */
1724                 rc = mdt_reint_internal(info, NULL, opc);
1725         } else {
1726                 rc = opc;
1727         }
1728
1729         info->mti_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
1730         RETURN(rc);
1731 }
1732
1733 /* this should sync the whole device */
1734 static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
1735 {
1736         struct dt_device *dt = mdt->mdt_bottom;
1737         int rc;
1738         ENTRY;
1739
1740         rc = dt->dd_ops->dt_sync(env, dt);
1741         RETURN(rc);
1742 }
1743
1744 /* this should sync this object */
1745 static int mdt_object_sync(struct mdt_thread_info *info)
1746 {
1747         struct md_object *next;
1748         int rc;
1749         ENTRY;
1750
1751         if (!mdt_object_exists(info->mti_object)) {
1752                 CWARN("Non existing object  "DFID"!\n",
1753                       PFID(mdt_object_fid(info->mti_object)));
1754                 RETURN(-ESTALE);
1755         }
1756         next = mdt_object_child(info->mti_object);
1757         rc = mo_object_sync(info->mti_env, next);
1758
1759         RETURN(rc);
1760 }
1761
1762 static int mdt_sync(struct mdt_thread_info *info)
1763 {
1764         struct ptlrpc_request *req = mdt_info_req(info);
1765         struct req_capsule *pill = info->mti_pill;
1766         struct mdt_body *body;
1767         int rc;
1768         ENTRY;
1769
1770         /* The fid may be zero, so we req_capsule_set manually */
1771         req_capsule_set(pill, &RQF_MDS_SYNC);
1772
1773         body = req_capsule_client_get(pill, &RMF_MDT_BODY);
1774         if (body == NULL)
1775                 RETURN(err_serious(-EINVAL));
1776
1777         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
1778                 RETURN(err_serious(-ENOMEM));
1779
1780         if (fid_seq(&body->fid1) == 0) {
1781                 /* sync the whole device */
1782                 rc = req_capsule_server_pack(pill);
1783                 if (rc == 0)
1784                         rc = mdt_device_sync(info->mti_env, info->mti_mdt);
1785                 else
1786                         rc = err_serious(rc);
1787         } else {
1788                 /* sync an object */
1789                 rc = mdt_unpack_req_pack_rep(info, HABEO_CORPUS|HABEO_REFERO);
1790                 if (rc == 0) {
1791                         rc = mdt_object_sync(info);
1792                         if (rc == 0) {
1793                                 struct md_object *next;
1794                                 const struct lu_fid *fid;
1795                                 struct lu_attr *la = &info->mti_attr.ma_attr;
1796
1797                                 next = mdt_object_child(info->mti_object);
1798                                 info->mti_attr.ma_need = MA_INODE;
1799                                 info->mti_attr.ma_valid = 0;
1800                                 rc = mo_attr_get(info->mti_env, next,
1801                                                  &info->mti_attr);
1802                                 if (rc == 0) {
1803                                         body = req_capsule_server_get(pill,
1804                                                                 &RMF_MDT_BODY);
1805                                         fid = mdt_object_fid(info->mti_object);
1806                                         mdt_pack_attr2body(info, body, la, fid);
1807                                 }
1808                         }
1809                 } else
1810                         rc = err_serious(rc);
1811         }
1812         if (rc == 0)
1813                 mdt_counter_incr(req, LPROC_MDT_SYNC);
1814
1815         RETURN(rc);
1816 }
1817
1818 #ifdef HAVE_QUOTA_SUPPORT
1819 static int mdt_quotacheck_handle(struct mdt_thread_info *info)
1820 {
1821         struct obd_quotactl *oqctl;
1822         struct req_capsule *pill = info->mti_pill;
1823         struct obd_export *exp = info->mti_exp;
1824         struct md_quota *mq = md_quota(info->mti_env);
1825         struct md_device *next = info->mti_mdt->mdt_child;
1826         int rc;
1827         ENTRY;
1828
1829         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1830         if (oqctl == NULL)
1831                 RETURN(-EPROTO);
1832
1833         /* remote client has no permission for quotacheck */
1834         if (unlikely(exp_connect_rmtclient(exp)))
1835                 RETURN(-EPERM);
1836
1837         rc = req_capsule_server_pack(pill);
1838         if (rc)
1839                 RETURN(rc);
1840
1841         mq->mq_exp = exp;
1842         rc = next->md_ops->mdo_quota.mqo_check(info->mti_env, next,
1843                                                oqctl->qc_type);
1844         RETURN(rc);
1845 }
1846
1847 static int mdt_quotactl_handle(struct mdt_thread_info *info)
1848 {
1849         struct obd_quotactl *oqctl, *repoqc;
1850         struct req_capsule *pill = info->mti_pill;
1851         struct obd_export *exp = info->mti_exp;
1852         struct md_quota *mq = md_quota(info->mti_env);
1853         struct md_device *next = info->mti_mdt->mdt_child;
1854         const struct md_quota_operations *mqo = &next->md_ops->mdo_quota;
1855         int id, rc;
1856         ENTRY;
1857
1858         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
1859         if (oqctl == NULL)
1860                 RETURN(-EPROTO);
1861
1862         id = oqctl->qc_id;
1863         if (exp_connect_rmtclient(exp)) {
1864                 struct ptlrpc_request *req = mdt_info_req(info);
1865                 struct mdt_export_data *med = mdt_req2med(req);
1866                 struct lustre_idmap_table *idmap = med->med_idmap;
1867
1868                 if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
1869                              oqctl->qc_cmd != Q_GETINFO))
1870                         RETURN(-EPERM);
1871
1872
1873                 if (oqctl->qc_type == USRQUOTA)
1874                         id = lustre_idmap_lookup_uid(NULL, idmap, 0,
1875                                                      oqctl->qc_id);
1876                 else if (oqctl->qc_type == GRPQUOTA)
1877                         id = lustre_idmap_lookup_gid(NULL, idmap, 0,
1878                                                      oqctl->qc_id);
1879                 else
1880                         RETURN(-EINVAL);
1881
1882                 if (id == CFS_IDMAP_NOTFOUND) {
1883                         CDEBUG(D_QUOTA, "no mapping for id %u\n",
1884                                oqctl->qc_id);
1885                         RETURN(-EACCES);
1886                 }
1887         }
1888
1889         rc = req_capsule_server_pack(pill);
1890         if (rc)
1891                 RETURN(rc);
1892
1893         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
1894         LASSERT(repoqc != NULL);
1895
1896         mq->mq_exp = exp;
1897         switch (oqctl->qc_cmd) {
1898         case Q_QUOTAON:
1899                 rc = mqo->mqo_on(info->mti_env, next, oqctl->qc_type);
1900                 break;
1901         case Q_QUOTAOFF:
1902                 rc = mqo->mqo_off(info->mti_env, next, oqctl->qc_type);
1903                 break;
1904         case Q_SETINFO:
1905                 rc = mqo->mqo_setinfo(info->mti_env, next, oqctl->qc_type, id,
1906                                       &oqctl->qc_dqinfo);
1907                 break;
1908         case Q_GETINFO:
1909                 rc = mqo->mqo_getinfo(info->mti_env, next, oqctl->qc_type, id,
1910                                       &oqctl->qc_dqinfo);
1911                 break;
1912         case Q_SETQUOTA:
1913                 rc = mqo->mqo_setquota(info->mti_env, next, oqctl->qc_type, id,
1914                                        &oqctl->qc_dqblk);
1915                 break;
1916         case Q_GETQUOTA:
1917                 rc = mqo->mqo_getquota(info->mti_env, next, oqctl->qc_type, id,
1918                                        &oqctl->qc_dqblk);
1919                 break;
1920         case Q_GETOINFO:
1921                 rc = mqo->mqo_getoinfo(info->mti_env, next, oqctl->qc_type, id,
1922                                        &oqctl->qc_dqinfo);
1923                 break;
1924         case Q_GETOQUOTA:
1925                 rc = mqo->mqo_getoquota(info->mti_env, next, oqctl->qc_type, id,
1926                                         &oqctl->qc_dqblk);
1927                 break;
1928         case LUSTRE_Q_INVALIDATE:
1929                 rc = mqo->mqo_invalidate(info->mti_env, next, oqctl->qc_type);
1930                 break;
1931         case LUSTRE_Q_FINVALIDATE:
1932                 rc = mqo->mqo_finvalidate(info->mti_env, next, oqctl->qc_type);
1933                 break;
1934         default:
1935                 CERROR("unsupported mdt_quotactl command: %d\n",
1936                        oqctl->qc_cmd);
1937                 RETURN(-EFAULT);
1938         }
1939
1940         *repoqc = *oqctl;
1941         RETURN(rc);
1942 }
1943 #endif
1944
1945
1946 /*
1947  * OBD PING and other handlers.
1948  */
1949 static int mdt_obd_ping(struct mdt_thread_info *info)
1950 {
1951         int rc;
1952         ENTRY;
1953
1954         req_capsule_set(info->mti_pill, &RQF_OBD_PING);
1955
1956         rc = target_handle_ping(mdt_info_req(info));
1957         if (rc < 0)
1958                 rc = err_serious(rc);
1959         RETURN(rc);
1960 }
1961
1962 /*
1963  * OBD_IDX_READ handler
1964  */
1965 static int mdt_obd_idx_read(struct mdt_thread_info *info)
1966 {
1967         struct mdt_device       *mdt = info->mti_mdt;
1968         struct lu_rdpg          *rdpg = &info->mti_u.rdpg.mti_rdpg;
1969         struct idx_info         *req_ii, *rep_ii;
1970         int                      rc, i;
1971         ENTRY;
1972
1973         memset(rdpg, 0, sizeof(*rdpg));
1974         req_capsule_set(info->mti_pill, &RQF_OBD_IDX_READ);
1975
1976         /* extract idx_info buffer from request & reply */
1977         req_ii = req_capsule_client_get(info->mti_pill, &RMF_IDX_INFO);
1978         if (req_ii == NULL || req_ii->ii_magic != IDX_INFO_MAGIC)
1979                 RETURN(err_serious(-EPROTO));
1980
1981         rc = req_capsule_server_pack(info->mti_pill);
1982         if (rc)
1983                 RETURN(err_serious(rc));
1984
1985         rep_ii = req_capsule_server_get(info->mti_pill, &RMF_IDX_INFO);
1986         if (rep_ii == NULL)
1987                 RETURN(err_serious(-EFAULT));
1988         rep_ii->ii_magic = IDX_INFO_MAGIC;
1989
1990         /* extract hash to start with */
1991         rdpg->rp_hash = req_ii->ii_hash_start;
1992
1993         /* extract requested attributes */
1994         rdpg->rp_attrs = req_ii->ii_attrs;
1995
1996         /* check that fid packed in request is valid and supported */
1997         if (!fid_is_sane(&req_ii->ii_fid))
1998                 RETURN(-EINVAL);
1999         rep_ii->ii_fid = req_ii->ii_fid;
2000
2001         /* copy flags */
2002         rep_ii->ii_flags = req_ii->ii_flags;
2003
2004         /* compute number of pages to allocate, ii_count is the number of 4KB
2005          * containers */
2006         if (req_ii->ii_count <= 0)
2007                 GOTO(out, rc = -EFAULT);
2008         rdpg->rp_count = min_t(unsigned int, req_ii->ii_count << LU_PAGE_SHIFT,
2009                                PTLRPC_MAX_BRW_SIZE);
2010         rdpg->rp_npages = (rdpg->rp_count + CFS_PAGE_SIZE -1) >> CFS_PAGE_SHIFT;
2011
2012         /* allocate pages to store the containers */
2013         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof(rdpg->rp_pages[0]));
2014         if (rdpg->rp_pages == NULL)
2015                 GOTO(out, rc = -ENOMEM);
2016         for (i = 0; i < rdpg->rp_npages; i++) {
2017                 rdpg->rp_pages[i] = cfs_alloc_page(CFS_ALLOC_STD);
2018                 if (rdpg->rp_pages[i] == NULL)
2019                         GOTO(out, rc = -ENOMEM);
2020         }
2021
2022         /* populate pages with key/record pairs */
2023         rc = dt_index_read(info->mti_env, mdt->mdt_bottom, rep_ii, rdpg);
2024         if (rc < 0)
2025                 GOTO(out, rc);
2026
2027         LASSERTF(rc <= rdpg->rp_count, "dt_index_read() returned more than "
2028                  "asked %d > %d\n", rc, rdpg->rp_count);
2029
2030         /* send pages to client */
2031         rc = mdt_sendpage(info, rdpg, rc);
2032
2033         GOTO(out, rc);
2034 out:
2035         if (rdpg->rp_pages) {
2036                 for (i = 0; i < rdpg->rp_npages; i++)
2037                         if (rdpg->rp_pages[i])
2038                                 cfs_free_page(rdpg->rp_pages[i]);
2039                 OBD_FREE(rdpg->rp_pages,
2040                          rdpg->rp_npages * sizeof(rdpg->rp_pages[0]));
2041         }
2042         return rc;
2043 }
2044
2045 static int mdt_obd_log_cancel(struct mdt_thread_info *info)
2046 {
2047         return err_serious(-EOPNOTSUPP);
2048 }
2049
2050 static int mdt_obd_qc_callback(struct mdt_thread_info *info)
2051 {
2052         return err_serious(-EOPNOTSUPP);
2053 }
2054
2055
2056 /*
2057  * LLOG handlers.
2058  */
2059
2060 /** clone llog ctxt from child (mdd)
2061  * This allows remote llog (replicator) access.
2062  * We can either pass all llog RPCs (eg mdt_llog_create) on to child where the
2063  * context was originally set up, or we can handle them directly.
2064  * I choose the latter, but that means I need any llog
2065  * contexts set up by child to be accessable by the mdt.  So we clone the
2066  * context into our context list here.
2067  */
2068 static int mdt_llog_ctxt_clone(const struct lu_env *env, struct mdt_device *mdt,
2069                                int idx)
2070 {
2071         struct md_device  *next = mdt->mdt_child;
2072         struct llog_ctxt *ctxt;
2073         int rc;
2074
2075         if (!llog_ctxt_null(mdt2obd_dev(mdt), idx))
2076                 return 0;
2077
2078         rc = next->md_ops->mdo_llog_ctxt_get(env, next, idx, (void **)&ctxt);
2079         if (rc || ctxt == NULL) {
2080                 CERROR("Can't get mdd ctxt %d\n", rc);
2081                 return rc;
2082         }
2083
2084         rc = llog_group_set_ctxt(&mdt2obd_dev(mdt)->obd_olg, ctxt, idx);
2085         if (rc)
2086                 CERROR("Can't set mdt ctxt %d\n", rc);
2087
2088         return rc;
2089 }
2090
2091 static int mdt_llog_ctxt_unclone(const struct lu_env *env,
2092                                  struct mdt_device *mdt, int idx)
2093 {
2094         struct llog_ctxt *ctxt;
2095
2096         ctxt = llog_get_context(mdt2obd_dev(mdt), idx);
2097         if (ctxt == NULL)
2098                 return 0;
2099         /* Put once for the get we just did, and once for the clone */
2100         llog_ctxt_put(ctxt);
2101         llog_ctxt_put(ctxt);
2102         return 0;
2103 }
2104
2105 static int mdt_llog_create(struct mdt_thread_info *info)
2106 {
2107         int rc;
2108
2109         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
2110         rc = llog_origin_handle_open(mdt_info_req(info));
2111         return (rc < 0 ? err_serious(rc) : rc);
2112 }
2113
2114 static int mdt_llog_destroy(struct mdt_thread_info *info)
2115 {
2116         int rc;
2117
2118         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_DESTROY);
2119         rc = llog_origin_handle_destroy(mdt_info_req(info));
2120         return (rc < 0 ? err_serious(rc) : rc);
2121 }
2122
2123 static int mdt_llog_read_header(struct mdt_thread_info *info)
2124 {
2125         int rc;
2126
2127         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_READ_HEADER);
2128         rc = llog_origin_handle_read_header(mdt_info_req(info));
2129         return (rc < 0 ? err_serious(rc) : rc);
2130 }
2131
2132 static int mdt_llog_next_block(struct mdt_thread_info *info)
2133 {
2134         int rc;
2135
2136         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
2137         rc = llog_origin_handle_next_block(mdt_info_req(info));
2138         return (rc < 0 ? err_serious(rc) : rc);
2139 }
2140
2141 static int mdt_llog_prev_block(struct mdt_thread_info *info)
2142 {
2143         int rc;
2144
2145         req_capsule_set(info->mti_pill, &RQF_LLOG_ORIGIN_HANDLE_PREV_BLOCK);
2146         rc = llog_origin_handle_prev_block(mdt_info_req(info));
2147         return (rc < 0 ? err_serious(rc) : rc);
2148 }
2149
2150
2151 /*
2152  * DLM handlers.
2153  */
2154 static struct ldlm_callback_suite cbs = {
2155         .lcs_completion = ldlm_server_completion_ast,
2156         .lcs_blocking   = ldlm_server_blocking_ast,
2157         .lcs_glimpse    = NULL
2158 };
2159
2160 static int mdt_enqueue(struct mdt_thread_info *info)
2161 {
2162         struct ptlrpc_request *req;
2163         int rc;
2164
2165         /*
2166          * info->mti_dlm_req already contains swapped and (if necessary)
2167          * converted dlm request.
2168          */
2169         LASSERT(info->mti_dlm_req != NULL);
2170
2171         req = mdt_info_req(info);
2172         rc = ldlm_handle_enqueue0(info->mti_mdt->mdt_namespace,
2173                                   req, info->mti_dlm_req, &cbs);
2174         info->mti_fail_id = OBD_FAIL_LDLM_REPLY;
2175         return rc ? err_serious(rc) : req->rq_status;
2176 }
2177
2178 static int mdt_convert(struct mdt_thread_info *info)
2179 {
2180         int rc;
2181         struct ptlrpc_request *req;
2182
2183         LASSERT(info->mti_dlm_req);
2184         req = mdt_info_req(info);
2185         rc = ldlm_handle_convert0(req, info->mti_dlm_req);
2186         return rc ? err_serious(rc) : req->rq_status;
2187 }
2188
2189 static int mdt_bl_callback(struct mdt_thread_info *info)
2190 {
2191         CERROR("bl callbacks should not happen on MDS\n");
2192         LBUG();
2193         return err_serious(-EOPNOTSUPP);
2194 }
2195
2196 static int mdt_cp_callback(struct mdt_thread_info *info)
2197 {
2198         CERROR("cp callbacks should not happen on MDS\n");
2199         LBUG();
2200         return err_serious(-EOPNOTSUPP);
2201 }
2202
2203 /*
2204  * sec context handlers
2205  */
2206 static int mdt_sec_ctx_handle(struct mdt_thread_info *info)
2207 {
2208         int rc;
2209
2210         rc = mdt_handle_idmap(info);
2211
2212         if (unlikely(rc)) {
2213                 struct ptlrpc_request *req = mdt_info_req(info);
2214                 __u32                  opc;
2215
2216                 opc = lustre_msg_get_opc(req->rq_reqmsg);
2217                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
2218                         sptlrpc_svc_ctx_invalidate(req);
2219         }
2220
2221         CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
2222
2223         return rc;
2224 }
2225
2226 static struct mdt_object *mdt_obj(struct lu_object *o)
2227 {
2228         LASSERT(lu_device_is_mdt(o->lo_dev));
2229         return container_of0(o, struct mdt_object, mot_obj.mo_lu);
2230 }
2231
2232 struct mdt_object *mdt_object_new(const struct lu_env *env,
2233                                   struct mdt_device *d,
2234                                   const struct lu_fid *f)
2235 {
2236         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
2237         struct lu_object *o;
2238         struct mdt_object *m;
2239         ENTRY;
2240
2241         CDEBUG(D_INFO, "Allocate object for "DFID"\n", PFID(f));
2242         o = lu_object_find(env, &d->mdt_md_dev.md_lu_dev, f, &conf);
2243         if (unlikely(IS_ERR(o)))
2244                 m = (struct mdt_object *)o;
2245         else
2246                 m = mdt_obj(o);
2247         RETURN(m);
2248 }
2249
2250 struct mdt_object *mdt_object_find(const struct lu_env *env,
2251                                    struct mdt_device *d,
2252                                    const struct lu_fid *f)
2253 {
2254         struct lu_object *o;
2255         struct mdt_object *m;
2256         ENTRY;
2257
2258         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
2259         o = lu_object_find(env, &d->mdt_md_dev.md_lu_dev, f, NULL);
2260         if (unlikely(IS_ERR(o)))
2261                 m = (struct mdt_object *)o;
2262         else
2263                 m = mdt_obj(o);
2264         RETURN(m);
2265 }
2266
2267 /**
2268  * Asyncronous commit for mdt device.
2269  *
2270  * Pass asynchonous commit call down the MDS stack.
2271  *
2272  * \param env environment
2273  * \param mdt the mdt device
2274  */
2275 static void mdt_device_commit_async(const struct lu_env *env,
2276                                     struct mdt_device *mdt)
2277 {
2278         struct dt_device *dt = mdt->mdt_bottom;
2279         int rc;
2280
2281         rc = dt->dd_ops->dt_commit_async(env, dt);
2282         if (unlikely(rc != 0))
2283                 CWARN("async commit start failed with rc = %d", rc);
2284 }
2285
2286 /**
2287  * Mark the lock as "synchonous".
2288  *
2289  * Mark the lock to deffer transaction commit to the unlock time.
2290  *
2291  * \param lock the lock to mark as "synchonous"
2292  *
2293  * \see mdt_is_lock_sync
2294  * \see mdt_save_lock
2295  */
2296 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
2297 {
2298         lock->l_ast_data = (void*)1;
2299 }
2300
2301 /**
2302  * Check whehter the lock "synchonous" or not.
2303  *
2304  * \param lock the lock to check
2305  * \retval 1 the lock is "synchonous"
2306  * \retval 0 the lock isn't "synchronous"
2307  *
2308  * \see mdt_set_lock_sync
2309  * \see mdt_save_lock
2310  */
2311 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
2312 {
2313         return lock->l_ast_data != NULL;
2314 }
2315
2316 /**
2317  * Blocking AST for mdt locks.
2318  *
2319  * Starts transaction commit if in case of COS lock conflict or
2320  * deffers such a commit to the mdt_save_lock.
2321  *
2322  * \param lock the lock which blocks a request or cancelling lock
2323  * \param desc unused
2324  * \param data unused
2325  * \param flag indicates whether this cancelling or blocking callback
2326  * \retval 0
2327  * \see ldlm_blocking_ast_nocheck
2328  */
2329 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2330                      void *data, int flag)
2331 {
2332         struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
2333         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2334         int rc;
2335         ENTRY;
2336
2337         if (flag == LDLM_CB_CANCELING)
2338                 RETURN(0);
2339         lock_res_and_lock(lock);
2340         if (lock->l_blocking_ast != mdt_blocking_ast) {
2341                 unlock_res_and_lock(lock);
2342                 RETURN(0);
2343         }
2344         if (mdt_cos_is_enabled(mdt) &&
2345             lock->l_req_mode & (LCK_PW | LCK_EX) &&
2346             lock->l_blocking_lock != NULL &&
2347             lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
2348                 mdt_set_lock_sync(lock);
2349         }
2350         rc = ldlm_blocking_ast_nocheck(lock);
2351
2352         /* There is no lock conflict if l_blocking_lock == NULL,
2353          * it indicates a blocking ast sent from ldlm_lock_decref_internal
2354          * when the last reference to a local lock was released */
2355         if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
2356                 struct lu_env env;
2357
2358                 rc = lu_env_init(&env, LCT_LOCAL);
2359                 if (unlikely(rc != 0))
2360                         CWARN("lu_env initialization failed with rc = %d,"
2361                               "cannot start asynchronous commit\n", rc);
2362                 else
2363                         mdt_device_commit_async(&env, mdt);
2364                 lu_env_fini(&env);
2365         }
2366         RETURN(rc);
2367 }
2368
2369 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2370                     struct mdt_lock_handle *lh, __u64 ibits, int locality)
2371 {
2372         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
2373         ldlm_policy_data_t *policy = &info->mti_policy;
2374         struct ldlm_res_id *res_id = &info->mti_res_id;
2375         int rc;
2376         ENTRY;
2377
2378         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2379         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2380         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
2381         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
2382
2383         if (mdt_object_exists(o) < 0) {
2384                 if (locality == MDT_CROSS_LOCK) {
2385                         /* cross-ref object fix */
2386                         ibits &= ~MDS_INODELOCK_UPDATE;
2387                         ibits |= MDS_INODELOCK_LOOKUP;
2388                 } else {
2389                         LASSERT(!(ibits & MDS_INODELOCK_UPDATE));
2390                         LASSERT(ibits & MDS_INODELOCK_LOOKUP);
2391                 }
2392                 /* No PDO lock on remote object */
2393                 LASSERT(lh->mlh_type != MDT_PDO_LOCK);
2394         }
2395
2396         if (lh->mlh_type == MDT_PDO_LOCK) {
2397                 /* check for exists after object is locked */
2398                 if (mdt_object_exists(o) == 0) {
2399                         /* Non-existent object shouldn't have PDO lock */
2400                         RETURN(-ESTALE);
2401                 } else {
2402                         /* Non-dir object shouldn't have PDO lock */
2403                         if (!S_ISDIR(lu_object_attr(&o->mot_obj.mo_lu)))
2404                                 RETURN(-ENOTDIR);
2405                 }
2406         }
2407
2408         memset(policy, 0, sizeof(*policy));
2409         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2410
2411         /*
2412          * Take PDO lock on whole directory and build correct @res_id for lock
2413          * on part of directory.
2414          */
2415         if (lh->mlh_pdo_hash != 0) {
2416                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2417                 mdt_lock_pdo_mode(info, o, lh);
2418                 if (lh->mlh_pdo_mode != LCK_NL) {
2419                         /*
2420                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2421                          * is never going to be sent to client and we do not
2422                          * want it slowed down due to possible cancels.
2423                          */
2424                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2425                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2426                                           policy, res_id, LDLM_FL_ATOMIC_CB,
2427                                           &info->mti_exp->exp_handle.h_cookie);
2428                         if (unlikely(rc))
2429                                 RETURN(rc);
2430                 }
2431
2432                 /*
2433                  * Finish res_id initializing by name hash marking part of
2434                  * directory which is taking modification.
2435                  */
2436                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2437         }
2438
2439         policy->l_inodebits.bits = ibits;
2440
2441         /*
2442          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2443          * going to be sent to client. If it is - mdt_intent_policy() path will
2444          * fix it up and turn FL_LOCAL flag off.
2445          */
2446         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2447                           res_id, LDLM_FL_LOCAL_ONLY | LDLM_FL_ATOMIC_CB,
2448                           &info->mti_exp->exp_handle.h_cookie);
2449         if (rc)
2450                 mdt_object_unlock(info, o, lh, 1);
2451         else if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_PDO_LOCK)) &&
2452                  lh->mlh_pdo_hash != 0 &&
2453                  (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX)) {
2454                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
2455         }
2456
2457         RETURN(rc);
2458 }
2459
2460 /**
2461  * Save a lock within request object.
2462  *
2463  * Keep the lock referenced until whether client ACK or transaction
2464  * commit happens or release the lock immediately depending on input
2465  * parameters. If COS is ON, a write lock is converted to COS lock
2466  * before saving.
2467  *
2468  * \param info thead info object
2469  * \param h lock handle
2470  * \param mode lock mode
2471  * \param decref force immediate lock releasing
2472  */
2473 static
2474 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2475                    ldlm_mode_t mode, int decref)
2476 {
2477         ENTRY;
2478
2479         if (lustre_handle_is_used(h)) {
2480                 if (decref || !info->mti_has_trans ||
2481                     !(mode & (LCK_PW | LCK_EX))){
2482                         mdt_fid_unlock(h, mode);
2483                 } else {
2484                         struct mdt_device *mdt = info->mti_mdt;
2485                         struct ldlm_lock *lock = ldlm_handle2lock(h);
2486                         struct ptlrpc_request *req = mdt_info_req(info);
2487                         int no_ack = 0;
2488
2489                         LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
2490                                  h->cookie);
2491                         CDEBUG(D_HA, "request = %p reply state = %p"
2492                                " transno = "LPD64"\n",
2493                                req, req->rq_reply_state, req->rq_transno);
2494                         if (mdt_cos_is_enabled(mdt)) {
2495                                 no_ack = 1;
2496                                 ldlm_lock_downgrade(lock, LCK_COS);
2497                                 mode = LCK_COS;
2498                         }
2499                         ptlrpc_save_lock(req, h, mode, no_ack);
2500                         if (mdt_is_lock_sync(lock)) {
2501                                 CDEBUG(D_HA, "found sync-lock,"
2502                                        " async commit started\n");
2503                                 mdt_device_commit_async(info->mti_env,
2504                                                         mdt);
2505                         }
2506                         LDLM_LOCK_PUT(lock);
2507                 }
2508                 h->cookie = 0ull;
2509         }
2510
2511         EXIT;
2512 }
2513
2514 /**
2515  * Unlock mdt object.
2516  *
2517  * Immeditely release the regular lock and the PDO lock or save the
2518  * lock in reqeuest and keep them referenced until client ACK or
2519  * transaction commit.
2520  *
2521  * \param info thread info object
2522  * \param o mdt object
2523  * \param lh mdt lock handle referencing regular and PDO locks
2524  * \param decref force immediate lock releasing
2525  */
2526 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
2527                        struct mdt_lock_handle *lh, int decref)
2528 {
2529         ENTRY;
2530
2531         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
2532         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
2533
2534         EXIT;
2535 }
2536
2537 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
2538                                         const struct lu_fid *f,
2539                                         struct mdt_lock_handle *lh,
2540                                         __u64 ibits)
2541 {
2542         struct mdt_object *o;
2543
2544         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
2545         if (!IS_ERR(o)) {
2546                 int rc;
2547
2548                 rc = mdt_object_lock(info, o, lh, ibits,
2549                                      MDT_LOCAL_LOCK);
2550                 if (rc != 0) {
2551                         mdt_object_put(info->mti_env, o);
2552                         o = ERR_PTR(rc);
2553                 }
2554         }
2555         return o;
2556 }
2557
2558 void mdt_object_unlock_put(struct mdt_thread_info * info,
2559                            struct mdt_object * o,
2560                            struct mdt_lock_handle *lh,
2561                            int decref)
2562 {
2563         mdt_object_unlock(info, o, lh, decref);
2564         mdt_object_put(info->mti_env, o);
2565 }
2566
2567 static struct mdt_handler *mdt_handler_find(__u32 opc,
2568                                             struct mdt_opc_slice *supported)
2569 {
2570         struct mdt_opc_slice *s;
2571         struct mdt_handler   *h;
2572
2573         h = NULL;
2574         for (s = supported; s->mos_hs != NULL; s++) {
2575                 if (s->mos_opc_start <= opc && opc < s->mos_opc_end) {
2576                         h = s->mos_hs + (opc - s->mos_opc_start);
2577                         if (likely(h->mh_opc != 0))
2578                                 LASSERTF(h->mh_opc == opc,
2579                                          "opcode mismatch %d != %d\n",
2580                                          h->mh_opc, opc);
2581                         else
2582                                 h = NULL; /* unsupported opc */
2583                         break;
2584                 }
2585         }
2586         return h;
2587 }
2588
2589 static int mdt_lock_resname_compat(struct mdt_device *m,
2590                                    struct ldlm_request *req)
2591 {
2592         /* XXX something... later. */
2593         return 0;
2594 }
2595
2596 static int mdt_lock_reply_compat(struct mdt_device *m, struct ldlm_reply *rep)
2597 {
2598         /* XXX something... later. */
2599         return 0;
2600 }
2601
2602 /*
2603  * Generic code handling requests that have struct mdt_body passed in:
2604  *
2605  *  - extract mdt_body from request and save it in @info, if present;
2606  *
2607  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
2608  *  @info;
2609  *
2610  *  - if HABEO_CORPUS flag is set for this request type check whether object
2611  *  actually exists on storage (lu_object_exists()).
2612  *
2613  */
2614 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
2615 {
2616         const struct mdt_body    *body;
2617         struct mdt_object        *obj;
2618         const struct lu_env      *env;
2619         struct req_capsule       *pill;
2620         int                       rc;
2621         ENTRY;
2622
2623         env = info->mti_env;
2624         pill = info->mti_pill;
2625
2626         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
2627         if (body == NULL)
2628                 RETURN(-EFAULT);
2629
2630         if (!(body->valid & OBD_MD_FLID))
2631                 RETURN(0);
2632
2633         if (!fid_is_sane(&body->fid1)) {
2634                 CERROR("Invalid fid: "DFID"\n", PFID(&body->fid1));
2635                 RETURN(-EINVAL);
2636         }
2637
2638         /*
2639          * Do not get size or any capa fields before we check that request
2640          * contains capa actually. There are some requests which do not, for
2641          * instance MDS_IS_SUBDIR.
2642          */
2643         if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2644             req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT))
2645                 mdt_set_capainfo(info, 0, &body->fid1,
2646                                  req_capsule_client_get(pill, &RMF_CAPA1));
2647
2648         obj = mdt_object_find(env, info->mti_mdt, &body->fid1);
2649         if (!IS_ERR(obj)) {
2650                 if ((flags & HABEO_CORPUS) &&
2651                     !mdt_object_exists(obj)) {
2652                         mdt_object_put(env, obj);
2653                         /* for capability renew ENOENT will be handled in
2654                          * mdt_renew_capa */
2655                         if (body->valid & OBD_MD_FLOSSCAPA)
2656                                 rc = 0;
2657                         else
2658                                 rc = -ENOENT;
2659                 } else {
2660                         info->mti_object = obj;
2661                         rc = 0;
2662                 }
2663         } else
2664                 rc = PTR_ERR(obj);
2665
2666         RETURN(rc);
2667 }
2668
2669 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
2670 {
2671         struct req_capsule *pill = info->mti_pill;
2672         int rc;
2673         ENTRY;
2674
2675         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
2676                 rc = mdt_body_unpack(info, flags);
2677         else
2678                 rc = 0;
2679
2680         if (rc == 0 && (flags & HABEO_REFERO)) {
2681                 /* Pack reply. */
2682                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2683                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2684                                              info->mti_body->eadatasize);
2685                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2686                         req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER,
2687                                              info->mti_mdt->mdt_max_cookiesize);
2688
2689                 rc = req_capsule_server_pack(pill);
2690         }
2691         RETURN(rc);
2692 }
2693
2694 static int mdt_init_capa_ctxt(const struct lu_env *env, struct mdt_device *m)
2695 {
2696         struct md_device *next = m->mdt_child;
2697
2698         return next->md_ops->mdo_init_capa_ctxt(env, next,
2699                                                 m->mdt_opts.mo_mds_capa,
2700                                                 m->mdt_capa_timeout,
2701                                                 m->mdt_capa_alg,
2702                                                 m->mdt_capa_keys);
2703 }
2704
2705 /*
2706  * Invoke handler for this request opc. Also do necessary preprocessing
2707  * (according to handler ->mh_flags), and post-processing (setting of
2708  * ->last_{xid,committed}).
2709  */
2710 static int mdt_req_handle(struct mdt_thread_info *info,
2711                           struct mdt_handler *h, struct ptlrpc_request *req)
2712 {
2713         int   rc, serious = 0;
2714         __u32 flags;
2715
2716         ENTRY;
2717
2718         LASSERT(h->mh_act != NULL);
2719         LASSERT(h->mh_opc == lustre_msg_get_opc(req->rq_reqmsg));
2720         LASSERT(current->journal_info == NULL);
2721
2722         /*
2723          * Checking for various OBD_FAIL_$PREF_$OPC_NET codes. _Do_ not try
2724          * to put same checks into handlers like mdt_close(), mdt_reint(),
2725          * etc., without talking to mdt authors first. Checking same thing
2726          * there again is useless and returning 0 error without packing reply
2727          * is buggy! Handlers either pack reply or return error.
2728          *
2729          * We return 0 here and do not send any reply in order to emulate
2730          * network failure. Do not send any reply in case any of NET related
2731          * fail_id has occured.
2732          */
2733         if (OBD_FAIL_CHECK_ORSET(h->mh_fail_id, OBD_FAIL_ONCE))
2734                 RETURN(0);
2735
2736         rc = 0;
2737         flags = h->mh_flags;
2738         LASSERT(ergo(flags & (HABEO_CORPUS|HABEO_REFERO), h->mh_fmt != NULL));
2739
2740         if (h->mh_fmt != NULL) {
2741                 req_capsule_set(info->mti_pill, h->mh_fmt);
2742                 rc = mdt_unpack_req_pack_rep(info, flags);
2743         }
2744
2745         if (rc == 0 && flags & MUTABOR &&
2746             req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
2747                 /* should it be rq_status? */
2748                 rc = -EROFS;
2749
2750         if (rc == 0 && flags & HABEO_CLAVIS) {
2751                 struct ldlm_request *dlm_req;
2752
2753                 LASSERT(h->mh_fmt != NULL);
2754
2755                 dlm_req = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
2756                 if (dlm_req != NULL) {
2757                         if (unlikely(dlm_req->lock_desc.l_resource.lr_type ==
2758                                         LDLM_IBITS &&
2759                                      dlm_req->lock_desc.l_policy_data.\
2760                                         l_inodebits.bits == 0)) {
2761                                 /*
2762                                  * Lock without inodebits makes no sense and
2763                                  * will oops later in ldlm. If client miss to
2764                                  * set such bits, do not trigger ASSERTION.
2765                                  *
2766                                  * For liblustre flock case, it maybe zero.
2767                                  */
2768                                 rc = -EPROTO;
2769                         } else {
2770                                 if (info->mti_mdt->mdt_opts.mo_compat_resname)
2771                                         rc = mdt_lock_resname_compat(
2772                                                                 info->mti_mdt,
2773                                                                 dlm_req);
2774                                 info->mti_dlm_req = dlm_req;
2775                         }
2776                 } else {
2777                         rc = -EFAULT;
2778                 }
2779         }
2780
2781         /* capability setting changed via /proc, needs reinitialize ctxt */
2782         if (info->mti_mdt && info->mti_mdt->mdt_capa_conf) {
2783                 mdt_init_capa_ctxt(info->mti_env, info->mti_mdt);
2784                 info->mti_mdt->mdt_capa_conf = 0;
2785         }
2786
2787         if (likely(rc == 0)) {
2788                 /*
2789                  * Process request, there can be two types of rc:
2790                  * 1) errors with msg unpack/pack, other failures outside the
2791                  * operation itself. This is counted as serious errors;
2792                  * 2) errors during fs operation, should be placed in rq_status
2793                  * only
2794                  */
2795                 rc = h->mh_act(info);
2796                 if (rc == 0 &&
2797                     !req->rq_no_reply && req->rq_reply_state == NULL) {
2798                         DEBUG_REQ(D_ERROR, req, "MDT \"handler\" %s did not "
2799                                   "pack reply and returned 0 error\n",
2800                                   h->mh_name);
2801                         LBUG();
2802                 }
2803                 serious = is_serious(rc);
2804                 rc = clear_serious(rc);
2805         } else
2806                 serious = 1;
2807
2808         req->rq_status = rc;
2809
2810         /*
2811          * ELDLM_* codes which > 0 should be in rq_status only as well as
2812          * all non-serious errors.
2813          */
2814         if (rc > 0 || !serious)
2815                 rc = 0;
2816
2817         LASSERT(current->journal_info == NULL);
2818
2819         if (rc == 0 && (flags & HABEO_CLAVIS) &&
2820             info->mti_mdt->mdt_opts.mo_compat_resname) {
2821                 struct ldlm_reply *dlmrep;
2822
2823                 dlmrep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
2824                 if (dlmrep != NULL)
2825                         rc = mdt_lock_reply_compat(info->mti_mdt, dlmrep);
2826         }
2827
2828         /* If we're DISCONNECTing, the mdt_export_data is already freed */
2829         if (likely(rc == 0 && req->rq_export && h->mh_opc != MDS_DISCONNECT))
2830                 target_committed_to_req(req);
2831
2832         if (unlikely(req_is_replay(req) &&
2833                      lustre_msg_get_transno(req->rq_reqmsg) == 0)) {
2834                 DEBUG_REQ(D_ERROR, req, "transno is 0 during REPLAY");
2835                 LBUG();
2836         }
2837
2838         target_send_reply(req, rc, info->mti_fail_id);
2839         RETURN(0);
2840 }
2841
2842 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
2843 {
2844         lh->mlh_type = MDT_NUL_LOCK;
2845         lh->mlh_reg_lh.cookie = 0ull;
2846         lh->mlh_reg_mode = LCK_MINMODE;
2847         lh->mlh_pdo_lh.cookie = 0ull;
2848         lh->mlh_pdo_mode = LCK_MINMODE;
2849 }
2850
2851 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
2852 {
2853         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2854         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2855 }
2856
2857 /*
2858  * Initialize fields of struct mdt_thread_info. Other fields are left in
2859  * uninitialized state, because it's too expensive to zero out whole
2860  * mdt_thread_info (> 1K) on each request arrival.
2861  */
2862 static void mdt_thread_info_init(struct ptlrpc_request *req,
2863                                  struct mdt_thread_info *info)
2864 {
2865         int i;
2866         struct md_capainfo *ci;
2867
2868         req_capsule_init(&req->rq_pill, req, RCL_SERVER);
2869         info->mti_pill = &req->rq_pill;
2870
2871         /* lock handle */
2872         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2873                 mdt_lock_handle_init(&info->mti_lh[i]);
2874
2875         /* mdt device: it can be NULL while CONNECT */
2876         if (req->rq_export) {
2877                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
2878                 info->mti_exp = req->rq_export;
2879         } else
2880                 info->mti_mdt = NULL;
2881         info->mti_env = req->rq_svc_thread->t_env;
2882         ci = md_capainfo(info->mti_env);
2883         memset(ci, 0, sizeof *ci);
2884         if (req->rq_export) {
2885                 if (exp_connect_rmtclient(req->rq_export))
2886                         ci->mc_auth = LC_ID_CONVERT;
2887                 else if (req->rq_export->exp_connect_flags &
2888                          OBD_CONNECT_MDS_CAPA)
2889                         ci->mc_auth = LC_ID_PLAIN;
2890                 else
2891                         ci->mc_auth = LC_ID_NONE;
2892         }
2893
2894         info->mti_fail_id = OBD_FAIL_MDS_ALL_REPLY_NET;
2895         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
2896         info->mti_mos = NULL;
2897
2898         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
2899         info->mti_body = NULL;
2900         info->mti_object = NULL;
2901         info->mti_dlm_req = NULL;
2902         info->mti_has_trans = 0;
2903         info->mti_no_need_trans = 0;
2904         info->mti_cross_ref = 0;
2905         info->mti_opdata = 0;
2906
2907         /* To not check for split by default. */
2908         info->mti_spec.sp_ck_split = 0;
2909         info->mti_spec.no_create = 0;
2910 }
2911
2912 static void mdt_thread_info_fini(struct mdt_thread_info *info)
2913 {
2914         int i;
2915
2916         req_capsule_fini(info->mti_pill);
2917         if (info->mti_object != NULL) {
2918                 /*
2919                  * freeing an object may lead to OSD level transaction, do not
2920                  * let it mess with MDT. bz19385.
2921                  */
2922                 info->mti_no_need_trans = 1;
2923                 mdt_object_put(info->mti_env, info->mti_object);
2924                 info->mti_object = NULL;
2925         }
2926         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2927                 mdt_lock_handle_fini(&info->mti_lh[i]);
2928         info->mti_env = NULL;
2929 }
2930
2931 static int mdt_filter_recovery_request(struct ptlrpc_request *req,
2932                                        struct obd_device *obd, int *process)
2933 {
2934         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2935         case MDS_CONNECT: /* This will never get here, but for completeness. */
2936         case OST_CONNECT: /* This will never get here, but for completeness. */
2937         case MDS_DISCONNECT:
2938         case OST_DISCONNECT:
2939                *process = 1;
2940                RETURN(0);
2941
2942         case MDS_CLOSE:
2943         case MDS_DONE_WRITING:
2944         case MDS_SYNC: /* used in unmounting */
2945         case OBD_PING:
2946         case MDS_REINT:
2947         case SEQ_QUERY:
2948         case FLD_QUERY:
2949         case LDLM_ENQUEUE:
2950                 *process = target_queue_recovery_request(req, obd);
2951                 RETURN(0);
2952
2953         default:
2954                 DEBUG_REQ(D_ERROR, req, "not permitted during recovery");
2955                 *process = -EAGAIN;
2956                 RETURN(0);
2957         }
2958 }
2959
2960 /*
2961  * Handle recovery. Return:
2962  *        +1: continue request processing;
2963  *       -ve: abort immediately with the given error code;
2964  *         0: send reply with error code in req->rq_status;
2965  */
2966 static int mdt_recovery(struct mdt_thread_info *info)
2967 {
2968         struct ptlrpc_request *req = mdt_info_req(info);
2969         struct obd_device *obd;
2970
2971         ENTRY;
2972
2973         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2974         case MDS_CONNECT:
2975         case SEC_CTX_INIT:
2976         case SEC_CTX_INIT_CONT:
2977         case SEC_CTX_FINI:
2978                 {
2979 #if 0
2980                         int rc;
2981
2982                         rc = mdt_handle_idmap(info);
2983                         if (rc)
2984                                 RETURN(rc);
2985                         else
2986 #endif
2987                                 RETURN(+1);
2988                 }
2989         }
2990
2991         if (unlikely(!class_connected_export(req->rq_export))) {
2992                 CERROR("operation %d on unconnected MDS from %s\n",
2993                        lustre_msg_get_opc(req->rq_reqmsg),
2994                        libcfs_id2str(req->rq_peer));
2995                 /* FIXME: For CMD cleanup, when mds_B stop, the req from
2996                  * mds_A will get -ENOTCONN(especially for ping req),
2997                  * which will cause that mds_A deactive timeout, then when
2998                  * mds_A cleanup, the cleanup process will be suspended since
2999                  * deactive timeout is not zero.
3000                  */
3001                 req->rq_status = -ENOTCONN;
3002                 target_send_reply(req, -ENOTCONN, info->mti_fail_id);
3003                 RETURN(0);
3004         }
3005
3006         /* sanity check: if the xid matches, the request must be marked as a
3007          * resent or replayed */
3008         if (req_xid_is_last(req)) {
3009                 if (!(lustre_msg_get_flags(req->rq_reqmsg) &
3010                       (MSG_RESENT | MSG_REPLAY))) {
3011                         DEBUG_REQ(D_WARNING, req, "rq_xid "LPU64" matches last_xid, "
3012                                   "expected REPLAY or RESENT flag (%x)", req->rq_xid,
3013                                   lustre_msg_get_flags(req->rq_reqmsg));
3014                         LBUG();
3015                         req->rq_status = -ENOTCONN;
3016                         RETURN(-ENOTCONN);
3017                 }
3018         }
3019
3020         /* else: note the opposite is not always true; a RESENT req after a
3021          * failover will usually not match the last_xid, since it was likely
3022          * never committed. A REPLAYed request will almost never match the
3023          * last xid, however it could for a committed, but still retained,
3024          * open. */
3025
3026         obd = req->rq_export->exp_obd;
3027
3028         /* Check for aborted recovery... */
3029         if (unlikely(obd->obd_recovering)) {
3030                 int rc;
3031                 int should_process;
3032                 DEBUG_REQ(D_INFO, req, "Got new replay");
3033                 rc = mdt_filter_recovery_request(req, obd, &should_process);
3034                 if (rc != 0 || !should_process)
3035                         RETURN(rc);
3036                 else if (should_process < 0) {
3037                         req->rq_status = should_process;
3038                         rc = ptlrpc_error(req);
3039                         RETURN(rc);
3040                 }
3041         }
3042         RETURN(+1);
3043 }
3044
3045 static int mdt_msg_check_version(struct lustre_msg *msg)
3046 {
3047         int rc;
3048
3049         switch (lustre_msg_get_opc(msg)) {
3050         case MDS_CONNECT:
3051         case MDS_DISCONNECT:
3052         case OBD_PING:
3053         case SEC_CTX_INIT:
3054         case SEC_CTX_INIT_CONT:
3055         case SEC_CTX_FINI:
3056         case OBD_IDX_READ:
3057                 rc = lustre_msg_check_version(msg, LUSTRE_OBD_VERSION);
3058                 if (rc)
3059                         CERROR("bad opc %u version %08x, expecting %08x\n",
3060                                lustre_msg_get_opc(msg),
3061                                lustre_msg_get_version(msg),
3062                                LUSTRE_OBD_VERSION);
3063                 break;
3064         case MDS_GETSTATUS:
3065         case MDS_GETATTR:
3066         case MDS_GETATTR_NAME:
3067         case MDS_STATFS:
3068         case MDS_READPAGE:
3069         case MDS_WRITEPAGE:
3070         case MDS_IS_SUBDIR:
3071         case MDS_REINT:
3072         case MDS_CLOSE:
3073         case MDS_DONE_WRITING:
3074         case MDS_PIN:
3075         case MDS_SYNC:
3076         case MDS_GETXATTR:
3077         case MDS_SETXATTR:
3078         case MDS_SET_INFO:
3079         case MDS_GET_INFO:
3080         case MDS_QUOTACHECK:
3081         case MDS_QUOTACTL:
3082         case QUOTA_DQACQ:
3083         case QUOTA_DQREL:
3084         case SEQ_QUERY:
3085         case FLD_QUERY:
3086                 rc = lustre_msg_check_version(msg, LUSTRE_MDS_VERSION);
3087                 if (rc)
3088                         CERROR("bad opc %u version %08x, expecting %08x\n",
3089                                lustre_msg_get_opc(msg),
3090                                lustre_msg_get_version(msg),
3091                                LUSTRE_MDS_VERSION);
3092                 break;
3093         case LDLM_ENQUEUE:
3094         case LDLM_CONVERT:
3095         case LDLM_BL_CALLBACK:
3096         case LDLM_CP_CALLBACK:
3097                 rc = lustre_msg_check_version(msg, LUSTRE_DLM_VERSION);
3098                 if (rc)
3099                         CERROR("bad opc %u version %08x, expecting %08x\n",
3100                                lustre_msg_get_opc(msg),
3101                                lustre_msg_get_version(msg),
3102                                LUSTRE_DLM_VERSION);
3103                 break;
3104         case OBD_LOG_CANCEL:
3105         case LLOG_ORIGIN_HANDLE_CREATE:
3106         case LLOG_ORIGIN_HANDLE_NEXT_BLOCK:
3107         case LLOG_ORIGIN_HANDLE_READ_HEADER:
3108         case LLOG_ORIGIN_HANDLE_CLOSE:
3109         case LLOG_ORIGIN_HANDLE_DESTROY:
3110         case LLOG_ORIGIN_HANDLE_PREV_BLOCK:
3111         case LLOG_CATINFO:
3112                 rc = lustre_msg_check_version(msg, LUSTRE_LOG_VERSION);
3113                 if (rc)
3114                         CERROR("bad opc %u version %08x, expecting %08x\n",
3115                                lustre_msg_get_opc(msg),
3116                                lustre_msg_get_version(msg),
3117                                LUSTRE_LOG_VERSION);
3118                 break;
3119         default:
3120                 CERROR("MDS unknown opcode %d\n", lustre_msg_get_opc(msg));
3121                 rc = -ENOTSUPP;
3122         }
3123         return rc;
3124 }
3125
3126 static int mdt_handle0(struct ptlrpc_request *req,
3127                        struct mdt_thread_info *info,
3128                        struct mdt_opc_slice *supported)
3129 {
3130         struct mdt_handler *h;
3131         struct lustre_msg  *msg;
3132         int                 rc;
3133
3134         ENTRY;
3135
3136         if (OBD_FAIL_CHECK_ORSET(OBD_FAIL_MDS_ALL_REQUEST_NET, OBD_FAIL_ONCE))
3137                 RETURN(0);
3138
3139         LASSERT(current->journal_info == NULL);
3140
3141         msg = req->rq_reqmsg;
3142         rc = mdt_msg_check_version(msg);
3143         if (likely(rc == 0)) {
3144                 rc = mdt_recovery(info);
3145                 if (likely(rc == +1)) {
3146                         h = mdt_handler_find(lustre_msg_get_opc(msg),
3147                                              supported);
3148                         if (likely(h != NULL)) {
3149                                 rc = mdt_req_handle(info, h, req);
3150                         } else {
3151                                 CERROR("The unsupported opc: 0x%x\n",
3152                                        lustre_msg_get_opc(msg) );
3153                                 req->rq_status = -ENOTSUPP;
3154                                 rc = ptlrpc_error(req);
3155                                 RETURN(rc);
3156                         }
3157                 }
3158         } else
3159                 CERROR(LUSTRE_MDT_NAME" drops mal-formed request\n");
3160         RETURN(rc);
3161 }
3162
3163 /*
3164  * MDT handler function called by ptlrpc service thread when request comes.
3165  *
3166  * XXX common "target" functionality should be factored into separate module
3167  * shared by mdt, ost and stand-alone services like fld.
3168  */
3169 static int mdt_handle_common(struct ptlrpc_request *req,
3170                              struct mdt_opc_slice *supported)
3171 {
3172         struct lu_env          *env;
3173         struct mdt_thread_info *info;
3174         int                     rc;
3175         ENTRY;
3176
3177         env = req->rq_svc_thread->t_env;
3178         LASSERT(env != NULL);
3179         LASSERT(env->le_ses != NULL);
3180         LASSERT(env->le_ctx.lc_thread == req->rq_svc_thread);
3181         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3182         LASSERT(info != NULL);
3183
3184         mdt_thread_info_init(req, info);
3185
3186         rc = mdt_handle0(req, info, supported);
3187
3188         mdt_thread_info_fini(info);
3189         RETURN(rc);
3190 }
3191
3192 /*
3193  * This is called from recovery code as handler of _all_ RPC types, FLD and SEQ
3194  * as well.
3195  */
3196 int mdt_recovery_handle(struct ptlrpc_request *req)
3197 {
3198         int rc;
3199         ENTRY;
3200
3201         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
3202         case FLD_QUERY:
3203                 rc = mdt_handle_common(req, mdt_fld_handlers);
3204                 break;
3205         case SEQ_QUERY:
3206                 rc = mdt_handle_common(req, mdt_seq_handlers);
3207                 break;
3208         default:
3209                 rc = mdt_handle_common(req, mdt_regular_handlers);
3210                 break;
3211         }
3212
3213         RETURN(rc);
3214 }
3215
3216 static int mdt_regular_handle(struct ptlrpc_request *req)
3217 {
3218         return mdt_handle_common(req, mdt_regular_handlers);
3219 }
3220
3221 static int mdt_readpage_handle(struct ptlrpc_request *req)
3222 {
3223         return mdt_handle_common(req, mdt_readpage_handlers);
3224 }
3225
3226 static int mdt_xmds_handle(struct ptlrpc_request *req)
3227 {
3228         return mdt_handle_common(req, mdt_xmds_handlers);
3229 }
3230
3231 static int mdt_mdsc_handle(struct ptlrpc_request *req)
3232 {
3233         return mdt_handle_common(req, mdt_seq_handlers);
3234 }
3235
3236 static int mdt_mdss_handle(struct ptlrpc_request *req)
3237 {
3238         return mdt_handle_common(req, mdt_seq_handlers);
3239 }
3240
3241 static int mdt_dtss_handle(struct ptlrpc_request *req)
3242 {
3243         return mdt_handle_common(req, mdt_seq_handlers);
3244 }
3245
3246 static int mdt_fld_handle(struct ptlrpc_request *req)
3247 {
3248         return mdt_handle_common(req, mdt_fld_handlers);
3249 }
3250
3251 enum mdt_it_code {
3252         MDT_IT_OPEN,
3253         MDT_IT_OCREAT,
3254         MDT_IT_CREATE,
3255         MDT_IT_GETATTR,
3256         MDT_IT_READDIR,
3257         MDT_IT_LOOKUP,
3258         MDT_IT_UNLINK,
3259         MDT_IT_TRUNC,
3260         MDT_IT_GETXATTR,
3261         MDT_IT_LAYOUT,
3262         MDT_IT_NR
3263 };
3264
3265 static int mdt_intent_getattr(enum mdt_it_code opcode,
3266                               struct mdt_thread_info *info,
3267                               struct ldlm_lock **,
3268                               int);
3269 static int mdt_intent_reint(enum mdt_it_code opcode,
3270                             struct mdt_thread_info *info,
3271                             struct ldlm_lock **,
3272                             int);
3273
3274 static struct mdt_it_flavor {
3275         const struct req_format *it_fmt;
3276         __u32                    it_flags;
3277         int                    (*it_act)(enum mdt_it_code ,
3278                                          struct mdt_thread_info *,
3279                                          struct ldlm_lock **,
3280                                          int);
3281         long                     it_reint;
3282 } mdt_it_flavor[] = {
3283         [MDT_IT_OPEN]     = {
3284                 .it_fmt   = &RQF_LDLM_INTENT,
3285                 /*.it_flags = HABEO_REFERO,*/
3286                 .it_flags = 0,
3287                 .it_act   = mdt_intent_reint,
3288                 .it_reint = REINT_OPEN
3289         },
3290         [MDT_IT_OCREAT]   = {
3291                 .it_fmt   = &RQF_LDLM_INTENT,
3292                 .it_flags = MUTABOR,
3293                 .it_act   = mdt_intent_reint,
3294                 .it_reint = REINT_OPEN
3295         },
3296         [MDT_IT_CREATE]   = {
3297                 .it_fmt   = &RQF_LDLM_INTENT,
3298                 .it_flags = MUTABOR,
3299                 .it_act   = mdt_intent_reint,
3300                 .it_reint = REINT_CREATE
3301         },
3302         [MDT_IT_GETATTR]  = {
3303                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3304                 .it_flags = HABEO_REFERO,
3305                 .it_act   = mdt_intent_getattr
3306         },
3307         [MDT_IT_READDIR]  = {
3308                 .it_fmt   = NULL,
3309                 .it_flags = 0,
3310                 .it_act   = NULL
3311         },
3312         [MDT_IT_LOOKUP]   = {
3313                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3314                 .it_flags = HABEO_REFERO,
3315                 .it_act   = mdt_intent_getattr
3316         },
3317         [MDT_IT_UNLINK]   = {
3318                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
3319                 .it_flags = MUTABOR,
3320                 .it_act   = NULL,
3321                 .it_reint = REINT_UNLINK
3322         },
3323         [MDT_IT_TRUNC]    = {
3324                 .it_fmt   = NULL,
3325                 .it_flags = MUTABOR,
3326                 .it_act   = NULL
3327         },
3328         [MDT_IT_GETXATTR] = {
3329                 .it_fmt   = NULL,
3330                 .it_flags = 0,
3331                 .it_act   = NULL
3332         },
3333         [MDT_IT_LAYOUT] = {
3334                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
3335                 .it_flags = HABEO_REFERO,
3336                 .it_act   = mdt_intent_getattr
3337         }
3338 };
3339
3340 int mdt_intent_lock_replace(struct mdt_thread_info *info,
3341                             struct ldlm_lock **lockp,
3342                             struct ldlm_lock *new_lock,
3343                             struct mdt_lock_handle *lh,
3344                             int flags)
3345 {
3346         struct ptlrpc_request  *req = mdt_info_req(info);
3347         struct ldlm_lock       *lock = *lockp;
3348
3349         /*
3350          * Get new lock only for cases when possible resent did not find any
3351          * lock.
3352          */
3353         if (new_lock == NULL)
3354                 new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
3355
3356         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
3357                 lh->mlh_reg_lh.cookie = 0;
3358                 RETURN(0);
3359         }
3360
3361         LASSERTF(new_lock != NULL,
3362                  "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
3363
3364         /*
3365          * If we've already given this lock to a client once, then we should
3366          * have no readers or writers.  Otherwise, we should have one reader
3367          * _or_ writer ref (which will be zeroed below) before returning the
3368          * lock to a client.
3369          */
3370         if (new_lock->l_export == req->rq_export) {
3371                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3372         } else {
3373                 LASSERT(new_lock->l_export == NULL);
3374                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3375         }
3376
3377         *lockp = new_lock;
3378
3379         if (new_lock->l_export == req->rq_export) {
3380                 /*
3381                  * Already gave this to the client, which means that we
3382                  * reconstructed a reply.
3383                  */
3384                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3385                         MSG_RESENT);
3386                 lh->mlh_reg_lh.cookie = 0;
3387                 RETURN(ELDLM_LOCK_REPLACED);
3388         }
3389
3390         /*
3391          * Fixup the lock to be given to the client.
3392          */
3393         lock_res_and_lock(new_lock);
3394         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3395          * possible blocking AST. */
3396         while (new_lock->l_readers > 0) {
3397                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3398                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3399                 new_lock->l_readers--;
3400         }
3401         while (new_lock->l_writers > 0) {
3402                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3403                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3404                 new_lock->l_writers--;
3405         }
3406
3407         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
3408         new_lock->l_blocking_ast = lock->l_blocking_ast;
3409         new_lock->l_completion_ast = lock->l_completion_ast;
3410         new_lock->l_remote_handle = lock->l_remote_handle;
3411         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3412
3413         unlock_res_and_lock(new_lock);
3414
3415         cfs_hash_add(new_lock->l_export->exp_lock_hash,
3416                      &new_lock->l_remote_handle,
3417                      &new_lock->l_exp_hash);
3418
3419         LDLM_LOCK_RELEASE(new_lock);
3420         lh->mlh_reg_lh.cookie = 0;
3421
3422         RETURN(ELDLM_LOCK_REPLACED);
3423 }
3424
3425 static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3426                                     struct ldlm_lock *new_lock,
3427                                     struct ldlm_lock **old_lock,
3428                                     struct mdt_lock_handle *lh)
3429 {
3430         struct ptlrpc_request  *req = mdt_info_req(info);
3431         struct obd_export      *exp = req->rq_export;
3432         struct lustre_handle    remote_hdl;
3433         struct ldlm_request    *dlmreq;
3434         struct ldlm_lock       *lock;
3435
3436         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3437                 return;
3438
3439         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3440         remote_hdl = dlmreq->lock_handle[0];
3441
3442         /* In the function below, .hs_keycmp resolves to
3443          * ldlm_export_lock_keycmp() */
3444         /* coverity[overrun-buffer-val] */
3445         lock = cfs_hash_lookup(exp->exp_lock_hash, &remote_hdl);
3446         if (lock) {
3447                 if (lock != new_lock) {
3448                         lh->mlh_reg_lh.cookie = lock->l_handle.h_cookie;
3449                         lh->mlh_reg_mode = lock->l_granted_mode;
3450
3451                         LDLM_DEBUG(lock, "Restoring lock cookie");
3452                         DEBUG_REQ(D_DLMTRACE, req,
3453                                   "restoring lock cookie "LPX64,
3454                                   lh->mlh_reg_lh.cookie);
3455                         if (old_lock)
3456                                 *old_lock = LDLM_LOCK_GET(lock);
3457                         cfs_hash_put(exp->exp_lock_hash, &lock->l_exp_hash);
3458                         return;
3459                 }
3460
3461                 cfs_hash_put(exp->exp_lock_hash, &lock->l_exp_hash);
3462         }
3463
3464         /*
3465          * If the xid matches, then we know this is a resent request, and allow
3466          * it. (It's probably an OPEN, for which we don't send a lock.
3467          */
3468         if (req_xid_is_last(req))
3469                 return;
3470
3471         /*
3472          * This remote handle isn't enqueued, so we never received or processed
3473          * this request.  Clear MSG_RESENT, because it can be handled like any
3474          * normal request now.
3475          */
3476         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3477
3478         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
3479                   remote_hdl.cookie);
3480 }
3481
3482 static int mdt_intent_getattr(enum mdt_it_code opcode,
3483                               struct mdt_thread_info *info,
3484                               struct ldlm_lock **lockp,
3485                               int flags)
3486 {
3487         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3488         struct ldlm_lock       *new_lock = NULL;
3489         __u64                   child_bits;
3490         struct ldlm_reply      *ldlm_rep;
3491         struct ptlrpc_request  *req;
3492         struct mdt_body        *reqbody;
3493         struct mdt_body        *repbody;
3494         int                     rc, rc2;
3495         ENTRY;
3496
3497         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3498         LASSERT(reqbody);
3499
3500         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3501         LASSERT(repbody);
3502
3503         info->mti_spec.sp_ck_split = !!(reqbody->valid & OBD_MD_FLCKSPLIT);
3504         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
3505         repbody->eadatasize = 0;
3506         repbody->aclsize = 0;
3507
3508         switch (opcode) {
3509         case MDT_IT_LOOKUP:
3510                 child_bits = MDS_INODELOCK_LOOKUP;
3511                 break;
3512         case MDT_IT_GETATTR:
3513                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE;
3514                 break;
3515         case MDT_IT_LAYOUT: {
3516                 static int printed = 0;
3517
3518                 if (!printed) {
3519                         CERROR("layout lock not supported by this version\n");
3520                         printed = 1;
3521                 }
3522                 GOTO(out_shrink, rc = -EINVAL);
3523                 break;
3524         }
3525         default:
3526                 CERROR("Unsupported intent (%d)\n", opcode);
3527                 GOTO(out_shrink, rc = -EINVAL);
3528         }
3529
3530         rc = mdt_init_ucred(info, reqbody);
3531         if (rc)
3532                 GOTO(out_shrink, rc);
3533
3534         req = info->mti_pill->rc_req;
3535         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3536         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3537
3538         /* Get lock from request for possible resent case. */
3539         mdt_intent_fixup_resent(info, *lockp, &new_lock, lhc);
3540
3541         ldlm_rep->lock_policy_res2 =
3542                 mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3543
3544         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3545                 ldlm_rep->lock_policy_res2 = 0;
3546         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3547             ldlm_rep->lock_policy_res2) {
3548                 lhc->mlh_reg_lh.cookie = 0ull;
3549                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3550         }
3551
3552         rc = mdt_intent_lock_replace(info, lockp, new_lock, lhc, flags);
3553         EXIT;
3554 out_ucred:
3555         mdt_exit_ucred(info);
3556 out_shrink:
3557         mdt_client_compatibility(info);
3558         rc2 = mdt_fix_reply(info);
3559         if (rc == 0)
3560                 rc = rc2;
3561         return rc;
3562 }
3563
3564 static int mdt_intent_reint(enum mdt_it_code opcode,
3565                             struct mdt_thread_info *info,
3566                             struct ldlm_lock **lockp,
3567                             int flags)
3568 {
3569         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3570         struct ldlm_reply      *rep = NULL;
3571         long                    opc;
3572         int                     rc;
3573
3574         static const struct req_format *intent_fmts[REINT_MAX] = {
3575                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3576                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3577         };
3578
3579         ENTRY;
3580
3581         opc = mdt_reint_opcode(info, intent_fmts);
3582         if (opc < 0)
3583                 RETURN(opc);
3584
3585         if (mdt_it_flavor[opcode].it_reint != opc) {
3586                 CERROR("Reint code %ld doesn't match intent: %d\n",
3587                        opc, opcode);
3588                 RETURN(err_serious(-EPROTO));
3589         }
3590
3591         /* Get lock from request for possible resent case. */
3592         mdt_intent_fixup_resent(info, *lockp, NULL, lhc);
3593
3594         rc = mdt_reint_internal(info, lhc, opc);
3595
3596         /* Check whether the reply has been packed successfully. */
3597         if (mdt_info_req(info)->rq_repmsg != NULL)
3598                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3599         if (rep == NULL)
3600                 RETURN(err_serious(-EFAULT));
3601
3602         /* MDC expects this in any case */
3603         if (rc != 0)
3604                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3605
3606         /* Cross-ref case, the lock should be returned to the client */
3607         if (rc == -EREMOTE) {
3608                 LASSERT(lustre_handle_is_used(&lhc->mlh_reg_lh));
3609                 rep->lock_policy_res2 = 0;
3610                 rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3611                 RETURN(rc);
3612         }
3613         rep->lock_policy_res2 = clear_serious(rc);
3614
3615         if (rep->lock_policy_res2 == -ENOENT &&
3616             mdt_get_disposition(rep, DISP_LOOKUP_NEG))
3617                 rep->lock_policy_res2 = 0;
3618
3619         if (rc == -ENOTCONN || rc == -ENODEV ||
3620             rc == -EOVERFLOW) { /**< if VBR failure then return error */
3621                 /*
3622                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3623                  * will be returned by rq_status, and client at ptlrpc layer
3624                  * will detect this, then disconnect, reconnect the import
3625                  * immediately, instead of impacting the following the rpc.
3626                  */
3627                 lhc->mlh_reg_lh.cookie = 0ull;
3628                 RETURN(rc);
3629         } else {
3630                 /*
3631                  * For other cases, the error will be returned by intent.
3632                  * and client will retrieve the result from intent.
3633                  */
3634                  /*
3635                   * FIXME: when open lock is finished, that should be
3636                   * checked here.
3637                   */
3638                 if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3639                         LASSERTF(rc == 0, "Error occurred but lock handle "
3640                                  "is still in use\n");
3641                         rep->lock_policy_res2 = 0;
3642                         rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3643                         RETURN(rc);
3644                 } else {
3645                         lhc->mlh_reg_lh.cookie = 0ull;
3646                         RETURN(ELDLM_LOCK_ABORTED);
3647                 }
3648         }
3649 }
3650
3651 static int mdt_intent_code(long itcode)
3652 {
3653         int rc;
3654
3655         switch(itcode) {
3656         case IT_OPEN:
3657                 rc = MDT_IT_OPEN;
3658                 break;
3659         case IT_OPEN|IT_CREAT:
3660                 rc = MDT_IT_OCREAT;
3661                 break;
3662         case IT_CREAT:
3663                 rc = MDT_IT_CREATE;
3664                 break;
3665         case IT_READDIR:
3666                 rc = MDT_IT_READDIR;
3667                 break;
3668         case IT_GETATTR:
3669                 rc = MDT_IT_GETATTR;
3670                 break;
3671         case IT_LOOKUP:
3672                 rc = MDT_IT_LOOKUP;
3673                 break;
3674         case IT_UNLINK:
3675                 rc = MDT_IT_UNLINK;
3676                 break;
3677         case IT_TRUNC:
3678                 rc = MDT_IT_TRUNC;
3679                 break;
3680         case IT_GETXATTR:
3681                 rc = MDT_IT_GETXATTR;
3682                 break;
3683         case IT_LAYOUT:
3684                 rc = MDT_IT_LAYOUT;
3685                 break;
3686         default:
3687                 CERROR("Unknown intent opcode: %ld\n", itcode);
3688                 rc = -EINVAL;
3689                 break;
3690         }
3691         return rc;
3692 }
3693
3694 static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
3695                           struct ldlm_lock **lockp, int flags)
3696 {
3697         struct req_capsule   *pill;
3698         struct mdt_it_flavor *flv;
3699         int opc;
3700         int rc;
3701         ENTRY;
3702
3703         opc = mdt_intent_code(itopc);
3704         if (opc < 0)
3705                 RETURN(-EINVAL);
3706
3707         pill = info->mti_pill;
3708         flv  = &mdt_it_flavor[opc];
3709
3710         if (flv->it_fmt != NULL)
3711                 req_capsule_extend(pill, flv->it_fmt);
3712
3713         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
3714         if (rc == 0) {
3715                 struct ptlrpc_request *req = mdt_info_req(info);
3716                 if (flv->it_flags & MUTABOR &&
3717                     req->rq_export->exp_connect_flags & OBD_CONNECT_RDONLY)
3718                         RETURN(-EROFS);
3719         }
3720         if (rc == 0 && flv->it_act != NULL) {
3721                 /* execute policy */
3722                 rc = flv->it_act(opc, info, lockp, flags);
3723         } else {
3724                 rc = -EOPNOTSUPP;
3725         }
3726         RETURN(rc);
3727 }
3728
3729 static int mdt_intent_policy(struct ldlm_namespace *ns,
3730                              struct ldlm_lock **lockp, void *req_cookie,
3731                              ldlm_mode_t mode, int flags, void *data)
3732 {
3733         struct mdt_thread_info *info;
3734         struct ptlrpc_request  *req  =  req_cookie;
3735         struct ldlm_intent     *it;
3736         struct req_capsule     *pill;
3737         int rc;
3738
3739         ENTRY;
3740
3741         LASSERT(req != NULL);
3742
3743         info = lu_context_key_get(&req->rq_svc_thread->t_env->le_ctx,
3744                                   &mdt_thread_key);
3745         LASSERT(info != NULL);
3746         pill = info->mti_pill;
3747         LASSERT(pill->rc_req == req);
3748
3749         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
3750                 req_capsule_extend(pill, &RQF_LDLM_INTENT);
3751                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
3752                 if (it != NULL) {
3753                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
3754                         if (rc == 0)
3755                                 rc = ELDLM_OK;
3756
3757                         /* Lock without inodebits makes no sense and will oops
3758                          * later in ldlm. Let's check it now to see if we have
3759                          * ibits corrupted somewhere in mdt_intent_opc().
3760                          * The case for client miss to set ibits has been
3761                          * processed by others. */
3762                         LASSERT(ergo(info->mti_dlm_req->lock_desc.l_resource.\
3763                                         lr_type == LDLM_IBITS,
3764                                      info->mti_dlm_req->lock_desc.\
3765                                         l_policy_data.l_inodebits.bits != 0));
3766                 } else
3767                         rc = err_serious(-EFAULT);
3768         } else {
3769                 /* No intent was provided */
3770                 LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
3771                 rc = req_capsule_server_pack(pill);
3772                 if (rc)
3773                         rc = err_serious(rc);
3774         }
3775         RETURN(rc);
3776 }
3777
3778 static int mdt_seq_fini(const struct lu_env *env,
3779                         struct mdt_device *m)
3780 {
3781         struct md_site *ms = mdt_md_site(m);
3782         ENTRY;
3783
3784         if (ms != NULL) {
3785                 if (ms->ms_server_seq) {
3786                         seq_server_fini(ms->ms_server_seq, env);
3787                         OBD_FREE_PTR(ms->ms_server_seq);
3788                         ms->ms_server_seq = NULL;
3789         }
3790
3791                 if (ms->ms_control_seq) {
3792                         seq_server_fini(ms->ms_control_seq, env);
3793                         OBD_FREE_PTR(ms->ms_control_seq);
3794                         ms->ms_control_seq = NULL;
3795         }
3796
3797                 if (ms->ms_client_seq) {
3798                         seq_client_fini(ms->ms_client_seq);
3799                         OBD_FREE_PTR(ms->ms_client_seq);
3800                         ms->ms_client_seq = NULL;
3801                 }
3802         }
3803
3804         RETURN(0);
3805 }
3806
3807 static int mdt_seq_init(const struct lu_env *env,
3808                         const char *uuid,
3809                         struct mdt_device *m)
3810 {
3811         struct md_site *ms;
3812         char *prefix;
3813         int rc;
3814         ENTRY;
3815
3816         ms = mdt_md_site(m);
3817
3818         /*
3819          * This is sequence-controller node. Init seq-controller server on local
3820          * MDT.
3821          */
3822         if (ms->ms_node_id == 0) {
3823                 LASSERT(ms->ms_control_seq == NULL);
3824
3825                 OBD_ALLOC_PTR(ms->ms_control_seq);
3826                 if (ms->ms_control_seq == NULL)
3827                         RETURN(-ENOMEM);
3828
3829                 rc = seq_server_init(ms->ms_control_seq,
3830                                      m->mdt_bottom, uuid,
3831                                      LUSTRE_SEQ_CONTROLLER,
3832                                      ms,
3833                                      env);
3834
3835                 if (rc)
3836                         GOTO(out_seq_fini, rc);
3837
3838                 OBD_ALLOC_PTR(ms->ms_client_seq);
3839                 if (ms->ms_client_seq == NULL)
3840                         GOTO(out_seq_fini, rc = -ENOMEM);
3841
3842                 OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3843                 if (prefix == NULL) {
3844                         OBD_FREE_PTR(ms->ms_client_seq);
3845                         GOTO(out_seq_fini, rc = -ENOMEM);
3846                 }
3847
3848                 snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
3849                          uuid);
3850
3851                 /*
3852                  * Init seq-controller client after seq-controller server is
3853                  * ready. Pass ms->ms_control_seq to it for direct talking.
3854                  */
3855                 rc = seq_client_init(ms->ms_client_seq, NULL,
3856                                      LUSTRE_SEQ_METADATA, prefix,
3857                                      ms->ms_control_seq);
3858                 OBD_FREE(prefix, MAX_OBD_NAME + 5);
3859
3860                 if (rc)
3861                         GOTO(out_seq_fini, rc);
3862         }
3863
3864         /* Init seq-server on local MDT */
3865         LASSERT(ms->ms_server_seq == NULL);
3866
3867         OBD_ALLOC_PTR(ms->ms_server_seq);
3868         if (ms->ms_server_seq == NULL)
3869                 GOTO(out_seq_fini, rc = -ENOMEM);
3870
3871         rc = seq_server_init(ms->ms_server_seq,
3872                              m->mdt_bottom, uuid,
3873                              LUSTRE_SEQ_SERVER,
3874                              ms,
3875                              env);
3876         if (rc)
3877                 GOTO(out_seq_fini, rc = -ENOMEM);
3878
3879         /* Assign seq-controller client to local seq-server. */
3880         if (ms->ms_node_id == 0) {
3881                 LASSERT(ms->ms_client_seq != NULL);
3882
3883                 rc = seq_server_set_cli(ms->ms_server_seq,
3884                                         ms->ms_client_seq,
3885                                         env);
3886         }
3887
3888         EXIT;
3889 out_seq_fini:
3890         if (rc)
3891                 mdt_seq_fini(env, m);
3892
3893         return rc;
3894 }
3895 /*
3896  * Init client sequence manager which is used by local MDS to talk to sequence
3897  * controller on remote node.
3898  */
3899 static int mdt_seq_init_cli(const struct lu_env *env,
3900                             struct mdt_device *m,
3901                             struct lustre_cfg *cfg)
3902 {
3903         struct md_site    *ms = mdt_md_site(m);
3904         struct obd_device *mdc;
3905         struct obd_uuid   *uuidp, *mdcuuidp;
3906         char              *uuid_str, *mdc_uuid_str;
3907         int                rc;
3908         int                index;
3909         struct mdt_thread_info *info;
3910         char *p, *index_string = lustre_cfg_string(cfg, 2);
3911         ENTRY;
3912
3913         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3914         uuidp = &info->mti_u.uuid[0];
3915         mdcuuidp = &info->mti_u.uuid[1];
3916
3917         LASSERT(index_string);
3918
3919         index = simple_strtol(index_string, &p, 10);
3920         if (*p) {
3921                 CERROR("Invalid index in lustre_cgf, offset 2\n");
3922                 RETURN(-EINVAL);
3923         }
3924
3925         /* check if this is adding the first MDC and controller is not yet
3926          * initialized. */
3927         if (index != 0 || ms->ms_client_seq)
3928                 RETURN(0);
3929
3930         uuid_str = lustre_cfg_string(cfg, 1);
3931         mdc_uuid_str = lustre_cfg_string(cfg, 4);
3932         obd_str2uuid(uuidp, uuid_str);
3933         obd_str2uuid(mdcuuidp, mdc_uuid_str);
3934
3935         mdc = class_find_client_obd(uuidp, LUSTRE_MDC_NAME, mdcuuidp);
3936         if (!mdc) {
3937                 CERROR("can't find controller MDC by uuid %s\n",
3938                        uuid_str);
3939                 rc = -ENOENT;
3940         } else if (!mdc->obd_set_up) {
3941                 CERROR("target %s not set up\n", mdc->obd_name);
3942                 rc = -EINVAL;
3943         } else {
3944                 LASSERT(ms->ms_control_exp);
3945                 OBD_ALLOC_PTR(ms->ms_client_seq);
3946                 if (ms->ms_client_seq != NULL) {
3947                         char *prefix;
3948
3949                         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3950                         if (!prefix)
3951                                 RETURN(-ENOMEM);
3952
3953                         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s",
3954                                  mdc->obd_name);
3955
3956                         rc = seq_client_init(ms->ms_client_seq,
3957                                              ms->ms_control_exp,
3958                                              LUSTRE_SEQ_METADATA,
3959                                              prefix, NULL);
3960                         OBD_FREE(prefix, MAX_OBD_NAME + 5);
3961                 } else
3962                         rc = -ENOMEM;
3963
3964                 if (rc)
3965                         RETURN(rc);
3966
3967                 LASSERT(ms->ms_server_seq != NULL);
3968                 rc = seq_server_set_cli(ms->ms_server_seq, ms->ms_client_seq,
3969                                         env);
3970         }
3971
3972         RETURN(rc);
3973 }
3974
3975 static void mdt_seq_fini_cli(struct mdt_device *m)
3976 {
3977         struct md_site *ms;
3978
3979         ENTRY;
3980
3981         ms = mdt_md_site(m);
3982
3983         if (ms != NULL) {
3984                 if (ms->ms_server_seq)
3985                         seq_server_set_cli(ms->ms_server_seq,
3986                                    NULL, NULL);
3987
3988                 if (ms->ms_control_exp) {
3989                         class_export_put(ms->ms_control_exp);
3990                         ms->ms_control_exp = NULL;
3991                 }
3992         }
3993         EXIT;
3994 }
3995
3996 /*
3997  * FLD wrappers
3998  */
3999 static int mdt_fld_fini(const struct lu_env *env,
4000                         struct mdt_device *m)
4001 {
4002         struct md_site *ms = mdt_md_site(m);
4003         ENTRY;
4004
4005         if (ms && ms->ms_server_fld) {
4006                 fld_server_fini(ms->ms_server_fld, env);
4007                 OBD_FREE_PTR(ms->ms_server_fld);
4008                 ms->ms_server_fld = NULL;
4009         }
4010
4011         RETURN(0);
4012 }
4013
4014 static int mdt_fld_init(const struct lu_env *env,
4015                         const char *uuid,
4016                         struct mdt_device *m)
4017 {
4018         struct md_site *ms;
4019         int rc;
4020         ENTRY;
4021
4022         ms = mdt_md_site(m);
4023
4024         OBD_ALLOC_PTR(ms->ms_server_fld);
4025         if (ms->ms_server_fld == NULL)
4026                 RETURN(rc = -ENOMEM);
4027
4028         rc = fld_server_init(ms->ms_server_fld,
4029                              m->mdt_bottom, uuid,
4030                              env, ms->ms_node_id);
4031         if (rc) {
4032                 OBD_FREE_PTR(ms->ms_server_fld);
4033                 ms->ms_server_fld = NULL;
4034                 RETURN(rc);
4035         }
4036
4037         RETURN(0);
4038 }
4039
4040 /* device init/fini methods */
4041 static void mdt_stop_ptlrpc_service(struct mdt_device *m)
4042 {
4043         ENTRY;
4044         if (m->mdt_regular_service != NULL) {
4045                 ptlrpc_unregister_service(m->mdt_regular_service);
4046                 m->mdt_regular_service = NULL;
4047         }
4048         if (m->mdt_readpage_service != NULL) {
4049                 ptlrpc_unregister_service(m->mdt_readpage_service);
4050                 m->mdt_readpage_service = NULL;
4051         }
4052         if (m->mdt_xmds_service != NULL) {
4053                 ptlrpc_unregister_service(m->mdt_xmds_service);
4054                 m->mdt_xmds_service = NULL;
4055         }
4056         if (m->mdt_setattr_service != NULL) {
4057                 ptlrpc_unregister_service(m->mdt_setattr_service);
4058                 m->mdt_setattr_service = NULL;
4059         }
4060         if (m->mdt_mdsc_service != NULL) {
4061                 ptlrpc_unregister_service(m->mdt_mdsc_service);
4062                 m->mdt_mdsc_service = NULL;
4063         }
4064         if (m->mdt_mdss_service != NULL) {
4065                 ptlrpc_unregister_service(m->mdt_mdss_service);
4066                 m->mdt_mdss_service = NULL;
4067         }
4068         if (m->mdt_dtss_service != NULL) {
4069                 ptlrpc_unregister_service(m->mdt_dtss_service);
4070                 m->mdt_dtss_service = NULL;
4071         }
4072         if (m->mdt_fld_service != NULL) {
4073                 ptlrpc_unregister_service(m->mdt_fld_service);
4074                 m->mdt_fld_service = NULL;
4075         }
4076         EXIT;
4077 }
4078
4079 static int mdt_start_ptlrpc_service(struct mdt_device *m)
4080 {
4081         static struct ptlrpc_service_conf conf;
4082         cfs_proc_dir_entry_t *procfs_entry;
4083         int rc = 0;
4084         ENTRY;
4085
4086         m->mdt_ldlm_client = &m->mdt_md_dev.md_lu_dev.ld_obd->obd_ldlm_client;
4087         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
4088                            "mdt_ldlm_client", m->mdt_ldlm_client);
4089
4090         procfs_entry = m->mdt_md_dev.md_lu_dev.ld_obd->obd_proc_entry;
4091
4092         conf = (typeof(conf)) {
4093                 .psc_name               = LUSTRE_MDT_NAME,
4094                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4095                 .psc_buf                = {
4096                         .bc_nbufs               = MDS_NBUFS,
4097                         .bc_buf_size            = MDS_BUFSIZE,
4098                         .bc_req_max_size        = MDS_MAXREQSIZE,
4099                         .bc_rep_max_size        = MDS_MAXREPSIZE,
4100                         .bc_req_portal          = MDS_REQUEST_PORTAL,
4101                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4102                 },
4103                 /*
4104                  * We'd like to have a mechanism to set this on a per-device
4105                  * basis, but alas...
4106                  */
4107                 .psc_thr                = {
4108                         .tc_thr_name            = LUSTRE_MDT_NAME,
4109                         .tc_thr_factor          = MDT_THR_FACTOR,
4110                         .tc_nthrs_init          = MDT_NTHRS_INIT,
4111                         .tc_nthrs_base          = MDT_NTHRS_BASE,
4112                         .tc_nthrs_max           = MDT_NTHRS_MAX,
4113                         .tc_nthrs_user          = mds_num_threads,
4114                         .tc_cpu_affinity        = 1,
4115                         .tc_ctx_tags            = LCT_MD_THREAD,
4116                 },
4117                 .psc_cpt                = {
4118                         .cc_pattern             = mds_num_cpts,
4119                 },
4120                 .psc_ops                = {
4121                         .so_req_handler         = mdt_regular_handle,
4122                         .so_req_printer         = target_print_req,
4123                         .so_hpreq_handler       = ptlrpc_hpreq_handler,
4124                 },
4125         };
4126         m->mdt_regular_service = ptlrpc_register_service(&conf, procfs_entry);
4127         if (IS_ERR(m->mdt_regular_service)) {
4128                 rc = PTR_ERR(m->mdt_regular_service);
4129                 CERROR("failed to start regular mdt service: %d\n", rc);
4130                 m->mdt_regular_service = NULL;
4131
4132                 RETURN(rc);
4133         }
4134
4135         /*
4136          * readpage service configuration. Parameters have to be adjusted,
4137          * ideally.
4138          */
4139         memset(&conf, 0, sizeof(conf));
4140         conf = (typeof(conf)) {
4141                 .psc_name               = LUSTRE_MDT_NAME "_readpage",
4142                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4143                 .psc_buf                = {
4144                         .bc_nbufs               = MDS_NBUFS,
4145                         .bc_buf_size            = MDS_BUFSIZE,
4146                         .bc_req_max_size        = MDS_MAXREQSIZE,
4147                         .bc_rep_max_size        = MDS_MAXREPSIZE,
4148                         .bc_req_portal          = MDS_READPAGE_PORTAL,
4149                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4150                 },
4151                 .psc_thr                = {
4152                         .tc_thr_name            = "mdt_rdpg",
4153                         .tc_thr_factor          = MDT_RDPG_THR_FACTOR,
4154                         .tc_nthrs_init          = MDT_RDPG_NTHRS_INIT,
4155                         .tc_nthrs_base          = MDT_RDPG_NTHRS_BASE,
4156                         .tc_nthrs_max           = MDT_RDPG_NTHRS_MAX,
4157                         .tc_nthrs_user          = mds_rdpg_num_threads,
4158                         .tc_cpu_affinity        = 1,
4159                         .tc_ctx_tags            = LCT_MD_THREAD,
4160                 },
4161                 .psc_cpt                = {
4162                         .cc_pattern             = mds_rdpg_num_cpts,
4163                 },
4164                 .psc_ops                = {
4165                         .so_req_handler         = mdt_readpage_handle,
4166                         .so_req_printer         = target_print_req,
4167                         .so_hpreq_handler       = NULL,
4168                 },
4169         };
4170         m->mdt_readpage_service = ptlrpc_register_service(&conf, procfs_entry);
4171         if (IS_ERR(m->mdt_readpage_service)) {
4172                 rc = PTR_ERR(m->mdt_readpage_service);
4173                 CERROR("failed to start readpage service: %d\n", rc);
4174                 m->mdt_readpage_service = NULL;
4175
4176                 GOTO(err_mdt_svc, rc);
4177         }
4178
4179         /*
4180          * setattr service configuration.
4181          *
4182          * XXX To keep the compatibility with old client(< 2.2), we need to
4183          * preserve this portal for a certain time, it should be removed
4184          * eventually. LU-617.
4185          */
4186         memset(&conf, 0, sizeof(conf));
4187         conf = (typeof(conf)) {
4188                 .psc_name               = LUSTRE_MDT_NAME "_setattr",
4189                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4190                 .psc_buf                = {
4191                         .bc_nbufs               = MDS_NBUFS,
4192                         .bc_buf_size            = MDS_BUFSIZE,
4193                         .bc_req_max_size        = MDS_MAXREQSIZE,
4194                         .bc_rep_max_size        = MDS_MAXREPSIZE,
4195                         .bc_req_portal          = MDS_SETATTR_PORTAL,
4196                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4197                 },
4198                 .psc_thr                = {
4199                         .tc_thr_name            = "mdt_attr",
4200                         .tc_thr_factor          = MDT_SETA_THR_FACTOR,
4201                         .tc_nthrs_init          = MDT_SETA_NTHRS_INIT,
4202                         .tc_nthrs_base          = MDT_SETA_NTHRS_BASE,
4203                         .tc_nthrs_max           = MDT_SETA_NTHRS_MAX,
4204                         .tc_nthrs_user          = mds_attr_num_threads,
4205                         .tc_cpu_affinity        = 1,
4206                         .tc_ctx_tags            = LCT_MD_THREAD,
4207                 },
4208                 .psc_cpt                = {
4209                         .cc_pattern             = mds_attr_num_cpts,
4210                 },
4211                 .psc_ops                = {
4212                         .so_req_handler         = mdt_regular_handle,
4213                         .so_req_printer         = target_print_req,
4214                         .so_hpreq_handler       = NULL,
4215                 },
4216         };
4217         m->mdt_setattr_service = ptlrpc_register_service(&conf, procfs_entry);
4218         if (IS_ERR(m->mdt_setattr_service)) {
4219                 rc = PTR_ERR(m->mdt_setattr_service);
4220                 CERROR("failed to start setattr service: %d\n", rc);
4221                 m->mdt_setattr_service = NULL;
4222
4223                 GOTO(err_mdt_svc, rc);
4224         }
4225
4226         /*
4227          * sequence controller service configuration
4228          */
4229         memset(&conf, 0, sizeof(conf));
4230         conf = (typeof(conf)) {
4231                 .psc_name               = LUSTRE_MDT_NAME "_mdsc",
4232                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4233                 .psc_buf                = {
4234                         .bc_nbufs               = MDS_NBUFS,
4235                         .bc_buf_size            = MDS_BUFSIZE,
4236                         .bc_req_max_size        = SEQ_MAXREQSIZE,
4237                         .bc_rep_max_size        = SEQ_MAXREPSIZE,
4238                         .bc_req_portal          = SEQ_CONTROLLER_PORTAL,
4239                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4240                 },
4241                 .psc_thr                = {
4242                         .tc_thr_name            = "mdt_mdsc",
4243                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4244                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4245                         .tc_ctx_tags            = LCT_MD_THREAD,
4246                 },
4247                 .psc_ops                = {
4248                         .so_req_handler         = mdt_mdsc_handle,
4249                         .so_req_printer         = target_print_req,
4250                         .so_hpreq_handler       = NULL,
4251                 },
4252         };
4253         m->mdt_mdsc_service = ptlrpc_register_service(&conf, procfs_entry);
4254         if (IS_ERR(m->mdt_mdsc_service)) {
4255                 rc = PTR_ERR(m->mdt_mdsc_service);
4256                 CERROR("failed to start seq controller service: %d\n", rc);
4257                 m->mdt_mdsc_service = NULL;
4258
4259                 GOTO(err_mdt_svc, rc);
4260         }
4261
4262         /*
4263          * metadata sequence server service configuration
4264          */
4265         memset(&conf, 0, sizeof(conf));
4266         conf = (typeof(conf)) {
4267                 .psc_name               = LUSTRE_MDT_NAME "_mdss",
4268                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4269                 .psc_buf                = {
4270                         .bc_nbufs               = MDS_NBUFS,
4271                         .bc_buf_size            = MDS_BUFSIZE,
4272                         .bc_req_max_size        = SEQ_MAXREQSIZE,
4273                         .bc_rep_max_size        = SEQ_MAXREPSIZE,
4274                         .bc_req_portal          = SEQ_METADATA_PORTAL,
4275                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4276                 },
4277                 .psc_thr                = {
4278                         .tc_thr_name            = "mdt_mdss",
4279                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4280                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4281                         .tc_ctx_tags            = LCT_MD_THREAD | LCT_DT_THREAD
4282                 },
4283                 .psc_ops                = {
4284                         .so_req_handler         = mdt_mdss_handle,
4285                         .so_req_printer         = target_print_req,
4286                         .so_hpreq_handler       = NULL,
4287                 },
4288         };
4289         m->mdt_mdss_service = ptlrpc_register_service(&conf, procfs_entry);
4290         if (IS_ERR(m->mdt_mdss_service)) {
4291                 rc = PTR_ERR(m->mdt_mdss_service);
4292                 CERROR("failed to start metadata seq server service: %d\n", rc);
4293                 m->mdt_mdss_service = NULL;
4294
4295                 GOTO(err_mdt_svc, rc);
4296         }
4297
4298         /*
4299          * Data sequence server service configuration. We want to have really
4300          * cluster-wide sequences space. This is why we start only one sequence
4301          * controller which manages space.
4302          */
4303         memset(&conf, 0, sizeof(conf));
4304         conf = (typeof(conf)) {
4305                 .psc_name               = LUSTRE_MDT_NAME "_dtss",
4306                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4307                 .psc_buf                = {
4308                         .bc_nbufs               = MDS_NBUFS,
4309                         .bc_buf_size            = MDS_BUFSIZE,
4310                         .bc_req_max_size        = SEQ_MAXREQSIZE,
4311                         .bc_rep_max_size        = SEQ_MAXREPSIZE,
4312                         .bc_req_portal          = SEQ_DATA_PORTAL,
4313                         .bc_rep_portal          = OSC_REPLY_PORTAL,
4314                 },
4315                 .psc_thr                = {
4316                         .tc_thr_name            = "mdt_dtss",
4317                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4318                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4319                         .tc_ctx_tags            = LCT_MD_THREAD | LCT_DT_THREAD
4320                 },
4321                 .psc_ops                = {
4322                         .so_req_handler         = mdt_dtss_handle,
4323                         .so_req_printer         = target_print_req,
4324                         .so_hpreq_handler       = NULL,
4325                 },
4326         };
4327         m->mdt_dtss_service = ptlrpc_register_service(&conf, procfs_entry);
4328         if (IS_ERR(m->mdt_dtss_service)) {
4329                 rc = PTR_ERR(m->mdt_dtss_service);
4330                 CERROR("failed to start data seq server service: %d\n", rc);
4331                 m->mdt_dtss_service = NULL;
4332
4333                 GOTO(err_mdt_svc, rc);
4334         }
4335
4336         /* FLD service start */
4337         memset(&conf, 0, sizeof(conf));
4338         conf = (typeof(conf)) {
4339                 .psc_name            = LUSTRE_MDT_NAME "_fld",
4340                 .psc_watchdog_factor = MDT_SERVICE_WATCHDOG_FACTOR,
4341                 .psc_buf                = {
4342                         .bc_nbufs               = MDS_NBUFS,
4343                         .bc_buf_size            = MDS_BUFSIZE,
4344                         .bc_req_max_size        = FLD_MAXREQSIZE,
4345                         .bc_rep_max_size        = FLD_MAXREPSIZE,
4346                         .bc_req_portal          = FLD_REQUEST_PORTAL,
4347                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4348                 },
4349                 .psc_thr                = {
4350                         .tc_thr_name            = "mdt_fld",
4351                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4352                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4353                         .tc_ctx_tags            = LCT_DT_THREAD | LCT_MD_THREAD
4354                 },
4355                 .psc_ops                = {
4356                         .so_req_handler         = mdt_fld_handle,
4357                         .so_req_printer         = target_print_req,
4358                         .so_hpreq_handler       = NULL,
4359                 },
4360         };
4361         m->mdt_fld_service = ptlrpc_register_service(&conf, procfs_entry);
4362         if (IS_ERR(m->mdt_fld_service)) {
4363                 rc = PTR_ERR(m->mdt_fld_service);
4364                 CERROR("failed to start fld service: %d\n", rc);
4365                 m->mdt_fld_service = NULL;
4366
4367                 GOTO(err_mdt_svc, rc);
4368         }
4369
4370         /*
4371          * mds-mds service configuration. Separate portal is used to allow
4372          * mds-mds requests be not blocked during recovery.
4373          */
4374         memset(&conf, 0, sizeof(conf));
4375         conf = (typeof(conf)) {
4376                 .psc_name               = LUSTRE_MDT_NAME "_mds",
4377                 .psc_watchdog_factor    = MDT_SERVICE_WATCHDOG_FACTOR,
4378                 .psc_buf                = {
4379                         .bc_nbufs               = MDS_NBUFS,
4380                         .bc_buf_size            = MDS_BUFSIZE,
4381                         .bc_req_max_size        = MDS_MAXREQSIZE,
4382                         .bc_rep_max_size        = MDS_MAXREPSIZE,
4383                         .bc_req_portal          = MDS_MDS_PORTAL,
4384                         .bc_rep_portal          = MDC_REPLY_PORTAL,
4385                 },
4386                 .psc_thr                = {
4387                         .tc_thr_name            = "mdt_mds",
4388                         .tc_nthrs_init          = MDT_OTHR_NTHRS_INIT,
4389                         .tc_nthrs_max           = MDT_OTHR_NTHRS_MAX,
4390                         .tc_ctx_tags            = LCT_MD_THREAD,
4391                 },
4392                 .psc_ops                = {
4393                         .so_req_handler         = mdt_xmds_handle,
4394                         .so_req_printer         = target_print_req,
4395                         .so_hpreq_handler       = ptlrpc_hpreq_handler,
4396                 },
4397         };
4398         m->mdt_xmds_service = ptlrpc_register_service(&conf, procfs_entry);
4399         if (IS_ERR(m->mdt_xmds_service)) {
4400                 rc = PTR_ERR(m->mdt_xmds_service);
4401                 CERROR("failed to start xmds service: %d\n", rc);
4402                 m->mdt_xmds_service = NULL;
4403
4404                 GOTO(err_mdt_svc, rc);
4405         }
4406
4407         EXIT;
4408 err_mdt_svc:
4409         if (rc)
4410                 mdt_stop_ptlrpc_service(m);
4411
4412         return rc;
4413 }
4414
4415 static void mdt_stack_fini(const struct lu_env *env,
4416                            struct mdt_device *m, struct lu_device *top)
4417 {
4418         struct obd_device       *obd = mdt2obd_dev(m);
4419         struct lustre_cfg_bufs  *bufs;
4420         struct lustre_cfg       *lcfg;
4421         struct mdt_thread_info  *info;
4422         char flags[3]="";
4423         ENTRY;
4424
4425         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4426         LASSERT(info != NULL);
4427
4428         lu_dev_del_linkage(top->ld_site, top);
4429
4430         bufs = &info->mti_u.bufs;
4431         /* process cleanup, pass mdt obd name to get obd umount flags */
4432         lustre_cfg_bufs_reset(bufs, obd->obd_name);
4433         if (obd->obd_force)
4434                 strcat(flags, "F");
4435         if (obd->obd_fail)
4436                 strcat(flags, "A");
4437         lustre_cfg_bufs_set_string(bufs, 1, flags);
4438         lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
4439         if (!lcfg) {
4440                 CERROR("Cannot alloc lcfg!\n");
4441                 return;
4442         }
4443         LASSERT(top);
4444         top->ld_ops->ldo_process_config(env, top, lcfg);
4445         lustre_cfg_free(lcfg);
4446
4447         lu_stack_fini(env, top);
4448         m->mdt_child = NULL;
4449         m->mdt_bottom = NULL;
4450
4451         obd_disconnect(m->mdt_bottom_exp);
4452 }
4453
4454 static struct lu_device *mdt_layer_setup(struct lu_env *env,
4455                                          const char *typename,
4456                                          struct lu_device *child,
4457                                          struct lustre_cfg *cfg)
4458 {
4459         const char            *dev = lustre_cfg_string(cfg, 0);
4460         struct obd_type       *type;
4461         struct lu_device_type *ldt;
4462         struct lu_device      *d;
4463         int rc;
4464         ENTRY;
4465
4466         /* find the type */
4467         type = class_get_type(typename);
4468         if (!type) {
4469                 CERROR("Unknown type: '%s'\n", typename);
4470                 GOTO(out, rc = -ENODEV);
4471         }
4472
4473         rc = lu_env_refill((struct lu_env *)env);
4474         if (rc != 0) {
4475                 CERROR("Failure to refill session: '%d'\n", rc);
4476                 GOTO(out_type, rc);
4477         }
4478
4479         ldt = type->typ_lu;
4480         if (ldt == NULL) {
4481                 CERROR("type: '%s'\n", typename);
4482                 GOTO(out_type, rc = -EINVAL);
4483         }
4484
4485         ldt->ldt_obd_type = type;
4486         d = ldt->ldt_ops->ldto_device_alloc(env, ldt, cfg);
4487         if (IS_ERR(d)) {
4488                 CERROR("Cannot allocate device: '%s'\n", typename);
4489                 GOTO(out_type, rc = -ENODEV);
4490         }
4491
4492         LASSERT(child->ld_site);
4493         d->ld_site = child->ld_site;
4494
4495         type->typ_refcnt++;
4496         rc = ldt->ldt_ops->ldto_device_init(env, d, dev, child);
4497         if (rc) {
4498                 CERROR("can't init device '%s', rc %d\n", typename, rc);
4499                 GOTO(out_alloc, rc);
4500         }
4501         lu_device_get(d);
4502         lu_ref_add(&d->ld_reference, "lu-stack", &lu_site_init);
4503
4504         lu_dev_add_linkage(d->ld_site, d);
4505         RETURN(d);
4506 out_alloc:
4507         ldt->ldt_ops->ldto_device_free(env, d);
4508         type->typ_refcnt--;
4509 out_type:
4510         class_put_type(type);
4511 out:
4512         return ERR_PTR(rc);
4513 }
4514
4515 static int mdt_connect_to_next(const struct lu_env *env, struct mdt_device *m,
4516                                const char *next, struct obd_export **exp)
4517 {
4518         struct obd_connect_data *data = NULL;
4519         struct obd_device       *obd;
4520         int                      rc;
4521         ENTRY;
4522
4523         OBD_ALLOC_PTR(data);
4524         if (data == NULL)
4525                 GOTO(out, rc = -ENOMEM);
4526
4527         obd = class_name2obd(next);
4528         if (obd == NULL) {
4529                 CERROR("%s: can't locate next device: %s\n",
4530                        m->mdt_md_dev.md_lu_dev.ld_obd->obd_name, next);
4531                 GOTO(out, rc = -ENOTCONN);
4532         }
4533
4534         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4535         data->ocd_version = LUSTRE_VERSION_CODE;
4536
4537         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
4538         if (rc) {
4539                 CERROR("%s: cannot connect to next dev %s (%d)\n",
4540                        m->mdt_md_dev.md_lu_dev.ld_obd->obd_name, next, rc);
4541                 GOTO(out, rc);
4542         }
4543
4544 out:
4545         if (data)
4546                 OBD_FREE_PTR(data);
4547         RETURN(rc);
4548 }
4549
4550 static int mdt_stack_init(struct lu_env *env,
4551                           struct mdt_device *m,
4552                           struct lustre_cfg *cfg,
4553                           struct lustre_mount_info  *lmi)
4554 {
4555         struct lu_device  *d = &m->mdt_md_dev.md_lu_dev;
4556         struct lu_device  *tmp;
4557         struct md_device  *md;
4558         struct lu_device  *child_lu_dev;
4559         char              *osdname;
4560         int rc;
4561         ENTRY;
4562
4563         /* find bottom osd */
4564         OBD_ALLOC(osdname, MTI_NAME_MAXLEN);
4565         if (osdname == NULL)
4566                 RETURN(-ENOMEM);
4567
4568         snprintf(osdname, MTI_NAME_MAXLEN, "%s-osd", lustre_cfg_string(cfg, 0));
4569         rc = mdt_connect_to_next(env, m, osdname, &m->mdt_bottom_exp);
4570         OBD_FREE(osdname, MTI_NAME_MAXLEN);
4571         if (rc)
4572                 RETURN(rc);
4573
4574         tmp = m->mdt_bottom_exp->exp_obd->obd_lu_dev;
4575         LASSERT(tmp);
4576         m->mdt_bottom = lu2dt_dev(tmp);
4577
4578         /* initialize site's pointers: md_site, top device */
4579         d->ld_site = tmp->ld_site;
4580         d->ld_site->ls_top_dev = d;
4581         m->mdt_mite.ms_lu = tmp->ld_site;
4582         tmp->ld_site->ld_md_site = &m->mdt_mite;
4583         LASSERT(d->ld_site);
4584         d = tmp;
4585
4586         tmp = mdt_layer_setup(env, LUSTRE_MDD_NAME, d, cfg);
4587         if (IS_ERR(tmp)) {
4588                 GOTO(out, rc = PTR_ERR(tmp));
4589         }
4590         d = tmp;
4591         md = lu2md_dev(d);
4592
4593         tmp = mdt_layer_setup(env, LUSTRE_CMM_NAME, d, cfg);
4594         if (IS_ERR(tmp)) {
4595                 GOTO(out, rc = PTR_ERR(tmp));
4596         }
4597         d = tmp;
4598         /*set mdd upcall device*/
4599         md_upcall_dev_set(md, lu2md_dev(d));
4600
4601         md = lu2md_dev(d);
4602         /*set cmm upcall device*/
4603         md_upcall_dev_set(md, &m->mdt_md_dev);
4604
4605         m->mdt_child = lu2md_dev(d);
4606
4607         /* process setup config */
4608         tmp = &m->mdt_md_dev.md_lu_dev;
4609         rc = tmp->ld_ops->ldo_process_config(env, tmp, cfg);
4610         if (rc)
4611                 GOTO(out, rc);
4612
4613         /* initialize local objects */
4614         child_lu_dev = &m->mdt_child->md_lu_dev;
4615
4616         rc = child_lu_dev->ld_ops->ldo_prepare(env,
4617                                                &m->mdt_md_dev.md_lu_dev,
4618                                                child_lu_dev);
4619 out:
4620         /* fini from last known good lu_device */
4621         if (rc)
4622                 mdt_stack_fini(env, m, d);
4623
4624         return rc;
4625 }
4626
4627 /**
4628  * setup CONFIG_ORIG context, used to access local config log.
4629  * this may need to be rewrite as part of llog rewrite for lu-api.
4630  */
4631 static int mdt_obd_llog_setup(struct obd_device *obd,
4632                               struct lustre_sb_info *lsi)
4633 {
4634         int     rc;
4635
4636         LASSERT(obd->obd_fsops == NULL);
4637
4638         obd->obd_fsops = fsfilt_get_ops(lsi->lsi_fstype);
4639         if (IS_ERR(obd->obd_fsops))
4640                 return PTR_ERR(obd->obd_fsops);
4641
4642         rc = fsfilt_setup(obd, lsi->lsi_srv_mnt->mnt_sb);
4643         if (rc) {
4644                 fsfilt_put_ops(obd->obd_fsops);
4645                 return rc;
4646         }
4647
4648         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
4649         obd->obd_lvfs_ctxt.pwdmnt = lsi->lsi_srv_mnt;
4650         obd->obd_lvfs_ctxt.pwd = lsi->lsi_srv_mnt->mnt_root;
4651         obd->obd_lvfs_ctxt.fs = get_ds();
4652
4653         rc = llog_setup(obd, &obd->obd_olg, LLOG_CONFIG_ORIG_CTXT, obd,
4654                         0, NULL, &llog_lvfs_ops);
4655         if (rc) {
4656                 CERROR("llog_setup() failed: %d\n", rc);
4657                 fsfilt_put_ops(obd->obd_fsops);
4658         }
4659
4660         return rc;
4661 }
4662
4663 static void mdt_obd_llog_cleanup(struct obd_device *obd)
4664 {
4665         struct llog_ctxt *ctxt;
4666
4667         ctxt = llog_get_context(obd, LLOG_CONFIG_ORIG_CTXT);
4668         if (ctxt)
4669                 llog_cleanup(ctxt);
4670
4671         if (obd->obd_fsops) {
4672                 fsfilt_put_ops(obd->obd_fsops);
4673                 obd->obd_fsops = NULL;
4674         }
4675 }
4676
4677 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4678 {
4679         struct md_device  *next = m->mdt_child;
4680         struct lu_device  *d    = &m->mdt_md_dev.md_lu_dev;
4681         struct obd_device *obd = mdt2obd_dev(m);
4682         ENTRY;
4683
4684         target_recovery_fini(obd);
4685
4686         ping_evictor_stop();
4687
4688         mdt_stop_ptlrpc_service(m);
4689         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4690         mdt_obd_llog_cleanup(obd);
4691         obd_exports_barrier(obd);
4692         obd_zombie_barrier();
4693
4694         mdt_procfs_fini(m);
4695
4696 #ifdef HAVE_QUOTA_SUPPORT
4697         next->md_ops->mdo_quota.mqo_cleanup(env, next);
4698 #endif
4699         lut_fini(env, &m->mdt_lut);
4700         mdt_fs_cleanup(env, m);
4701         upcall_cache_cleanup(m->mdt_identity_cache);
4702         m->mdt_identity_cache = NULL;
4703
4704         if (m->mdt_namespace != NULL) {
4705                 ldlm_namespace_free(m->mdt_namespace, NULL,
4706                                     d->ld_obd->obd_force);
4707                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4708         }
4709
4710         cfs_free_nidlist(&m->mdt_nosquash_nids);
4711         if (m->mdt_nosquash_str) {
4712                 OBD_FREE(m->mdt_nosquash_str, m->mdt_nosquash_strlen);
4713                 m->mdt_nosquash_str = NULL;
4714                 m->mdt_nosquash_strlen = 0;
4715         }
4716
4717         mdt_seq_fini(env, m);
4718         mdt_seq_fini_cli(m);
4719         mdt_fld_fini(env, m);
4720         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4721
4722         next->md_ops->mdo_init_capa_ctxt(env, next, 0, 0, 0, NULL);
4723         cfs_timer_disarm(&m->mdt_ck_timer);
4724         mdt_ck_thread_stop(m);
4725
4726         /*
4727          * Finish the stack
4728          */
4729         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4730
4731         LASSERT(cfs_atomic_read(&d->ld_ref) == 0);
4732
4733         server_put_mount(mdt2obd_dev(m)->obd_name, NULL);
4734
4735         EXIT;
4736 }
4737
4738 static int mdt_adapt_sptlrpc_conf(struct obd_device *obd, int initial)
4739 {
4740         struct mdt_device       *m = mdt_dev(obd->obd_lu_dev);
4741         struct sptlrpc_rule_set  tmp_rset;
4742         int                      rc;
4743
4744         sptlrpc_rule_set_init(&tmp_rset);
4745         rc = sptlrpc_conf_target_get_rules(obd, &tmp_rset, initial);
4746         if (rc) {
4747                 CERROR("mdt %s: failed get sptlrpc rules: %d\n",
4748                        obd->obd_name, rc);
4749                 return rc;
4750         }
4751
4752         sptlrpc_target_update_exp_flavor(obd, &tmp_rset);
4753
4754         cfs_write_lock(&m->mdt_sptlrpc_lock);
4755         sptlrpc_rule_set_free(&m->mdt_sptlrpc_rset);
4756         m->mdt_sptlrpc_rset = tmp_rset;
4757         cfs_write_unlock(&m->mdt_sptlrpc_lock);
4758
4759         return 0;
4760 }
4761
4762 int mdt_postrecov(const struct lu_env *, struct mdt_device *);
4763
4764 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
4765                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
4766 {
4767         struct mdt_thread_info    *info;
4768         struct obd_device         *obd;
4769         const char                *dev = lustre_cfg_string(cfg, 0);
4770         const char                *num = lustre_cfg_string(cfg, 2);
4771         struct lustre_mount_info  *lmi = NULL;
4772         struct lustre_sb_info     *lsi;
4773         struct lu_site            *s;
4774         struct md_site            *mite;
4775         const char                *identity_upcall = "NONE";
4776         struct md_device          *next;
4777         int                        rc;
4778         int                        node_id;
4779         mntopt_t                   mntopts;
4780         ENTRY;
4781
4782         md_device_init(&m->mdt_md_dev, ldt);
4783         /*
4784          * Environment (env) might be missing mdt_thread_key values at that
4785          * point, if device is allocated when mdt_thread_key is in QUIESCENT
4786          * mode.
4787          *
4788          * Usually device allocation path doesn't use module key values, but
4789          * mdt has to do a lot of work here, so allocate key value.
4790          */
4791         rc = lu_env_refill((struct lu_env *)env);
4792         if (rc != 0)
4793                 RETURN(rc);
4794
4795         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4796         LASSERT(info != NULL);
4797
4798         obd = class_name2obd(dev);
4799         LASSERT(obd != NULL);
4800
4801         m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
4802         m->mdt_max_cookiesize = sizeof(struct llog_cookie);
4803
4804         m->mdt_som_conf = 0;
4805
4806         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
4807         lmi = server_get_mount(dev);
4808         if (lmi == NULL) {
4809                 CERROR("Cannot get mount info for %s!\n", dev);
4810                 RETURN(-EFAULT);
4811         } else {
4812                 lsi = s2lsi(lmi->lmi_sb);
4813                 /* CMD is supported only in IAM mode */
4814                 LASSERT(num);
4815                 node_id = simple_strtol(num, NULL, 10);
4816                 if (!(lsi->lsi_flags & LDD_F_IAM_DIR) && node_id) {
4817                         CERROR("CMD Operation not allowed in IOP mode\n");
4818                         GOTO(err_lmi, rc = -EINVAL);
4819                 }
4820
4821                 obd->u.obt.obt_magic = OBT_MAGIC;
4822         }
4823
4824         cfs_rwlock_init(&m->mdt_sptlrpc_lock);
4825         sptlrpc_rule_set_init(&m->mdt_sptlrpc_rset);
4826
4827         cfs_spin_lock_init(&m->mdt_ioepoch_lock);
4828         m->mdt_opts.mo_compat_resname = 0;
4829         m->mdt_opts.mo_mds_capa = 1;
4830         m->mdt_opts.mo_oss_capa = 1;
4831         m->mdt_capa_timeout = CAPA_TIMEOUT;
4832         m->mdt_capa_alg = CAPA_HMAC_ALG_SHA1;
4833         m->mdt_ck_timeout = CAPA_KEY_TIMEOUT;
4834         m->mdt_squash_uid = 0;
4835         m->mdt_squash_gid = 0;
4836         CFS_INIT_LIST_HEAD(&m->mdt_nosquash_nids);
4837         m->mdt_nosquash_str = NULL;
4838         m->mdt_nosquash_strlen = 0;
4839         cfs_init_rwsem(&m->mdt_squash_sem);
4840         cfs_spin_lock_init(&m->mdt_osfs_lock);
4841         m->mdt_osfs_age = cfs_time_shift_64(-1000);
4842
4843         m->mdt_md_dev.md_lu_dev.ld_ops = &mdt_lu_ops;
4844         m->mdt_md_dev.md_lu_dev.ld_obd = obd;
4845         /* set this lu_device to obd, because error handling need it */
4846         obd->obd_lu_dev = &m->mdt_md_dev.md_lu_dev;
4847
4848         /* init the stack */
4849         rc = mdt_stack_init((struct lu_env *)env, m, cfg, lmi);
4850         if (rc) {
4851                 CERROR("Can't init device stack, rc %d\n", rc);
4852                 RETURN(rc);
4853         }
4854
4855         s = m->mdt_md_dev.md_lu_dev.ld_site;
4856         mite = &m->mdt_mite;
4857
4858         /* set server index */
4859         mite->ms_node_id = node_id;
4860
4861         /* failover is the default
4862          * FIXME: we do not failout mds0/mgs, which may cause some problems.
4863          * assumed whose ms_node_id == 0 XXX
4864          * */
4865         obd->obd_replayable = 1;
4866         /* No connection accepted until configurations will finish */
4867         obd->obd_no_conn = 1;
4868
4869         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
4870                 char *str = lustre_cfg_string(cfg, 4);
4871                 if (strchr(str, 'n')) {
4872                         CWARN("%s: recovery disabled\n", obd->obd_name);
4873                         obd->obd_replayable = 0;
4874                 }
4875         }
4876
4877         rc = lut_init(env, &m->mdt_lut, obd, m->mdt_bottom);
4878         if (rc)
4879                 GOTO(err_fini_stack, rc);
4880
4881         rc = mdt_fld_init(env, obd->obd_name, m);
4882         if (rc)
4883                 GOTO(err_lut, rc);
4884
4885         rc = mdt_seq_init(env, obd->obd_name, m);
4886         if (rc)
4887                 GOTO(err_fini_fld, rc);
4888
4889         snprintf(info->mti_u.ns_name, sizeof info->mti_u.ns_name,
4890                  LUSTRE_MDT_NAME"-%p", m);
4891         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
4892                                               LDLM_NAMESPACE_SERVER,
4893                                               LDLM_NAMESPACE_GREEDY,
4894                                               LDLM_NS_TYPE_MDT);
4895         if (m->mdt_namespace == NULL)
4896                 GOTO(err_fini_seq, rc = -ENOMEM);
4897
4898         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
4899         /* set obd_namespace for compatibility with old code */
4900         obd->obd_namespace = m->mdt_namespace;
4901
4902         cfs_timer_init(&m->mdt_ck_timer, mdt_ck_timer_callback, m);
4903
4904         rc = mdt_ck_thread_start(m);
4905         if (rc)
4906                 GOTO(err_free_ns, rc);
4907
4908         rc = mdt_fs_setup(env, m, obd, lsi);
4909         if (rc)
4910                 GOTO(err_capa, rc);
4911
4912         rc = mdt_obd_llog_setup(obd, lsi);
4913         if (rc)
4914                 GOTO(err_fs_cleanup, rc);
4915
4916         rc = mdt_llog_ctxt_clone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4917         if (rc)
4918                 GOTO(err_llog_cleanup, rc);
4919
4920         mdt_adapt_sptlrpc_conf(obd, 1);
4921
4922         next = m->mdt_child;
4923 #ifdef HAVE_QUOTA_SUPPORT
4924         rc = next->md_ops->mdo_quota.mqo_setup(env, next, lmi->lmi_mnt);
4925         if (rc)
4926                 GOTO(err_llog_cleanup, rc);
4927 #endif
4928
4929         rc = next->md_ops->mdo_iocontrol(env, next, OBD_IOC_GET_MNTOPT, 0,
4930                                          &mntopts);
4931         if (rc)
4932                 GOTO(err_quota, rc);
4933
4934         if (mntopts & MNTOPT_USERXATTR)
4935                 m->mdt_opts.mo_user_xattr = 1;
4936         else
4937                 m->mdt_opts.mo_user_xattr = 0;
4938
4939         if (mntopts & MNTOPT_ACL)
4940                 m->mdt_opts.mo_acl = 1;
4941         else
4942                 m->mdt_opts.mo_acl = 0;
4943
4944         /* XXX: to support suppgid for ACL, we enable identity_upcall
4945          * by default, otherwise, maybe got unexpected -EACCESS. */
4946         if (m->mdt_opts.mo_acl)
4947                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
4948
4949         m->mdt_identity_cache = upcall_cache_init(obd->obd_name,identity_upcall,
4950                                                 &mdt_identity_upcall_cache_ops);
4951         if (IS_ERR(m->mdt_identity_cache)) {
4952                 rc = PTR_ERR(m->mdt_identity_cache);
4953                 m->mdt_identity_cache = NULL;
4954                 GOTO(err_quota, rc);
4955         }
4956
4957         target_recovery_init(&m->mdt_lut, mdt_recovery_handle);
4958
4959         rc = mdt_procfs_init(m, dev);
4960         if (rc) {
4961                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
4962                 GOTO(err_recovery, rc);
4963         }
4964
4965         rc = mdt_start_ptlrpc_service(m);
4966         if (rc)
4967                 GOTO(err_procfs, rc);
4968
4969         ping_evictor_start();
4970
4971         if (obd->obd_recovering == 0)
4972                 mdt_postrecov(env, m);
4973
4974         mdt_init_capa_ctxt(env, m);
4975
4976         /* Reduce the initial timeout on an MDS because it doesn't need such
4977          * a long timeout as an OST does. Adaptive timeouts will adjust this
4978          * value appropriately. */
4979         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
4980                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
4981
4982         RETURN(0);
4983
4984         ping_evictor_stop();
4985         mdt_stop_ptlrpc_service(m);
4986 err_procfs:
4987         mdt_procfs_fini(m);
4988 err_recovery:
4989         target_recovery_fini(obd);
4990         upcall_cache_cleanup(m->mdt_identity_cache);
4991         m->mdt_identity_cache = NULL;
4992 err_quota:
4993 #ifdef HAVE_QUOTA_SUPPORT
4994         next->md_ops->mdo_quota.mqo_cleanup(env, next);
4995 #endif
4996 err_llog_cleanup:
4997         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4998         mdt_obd_llog_cleanup(obd);
4999 err_fs_cleanup:
5000         mdt_fs_cleanup(env, m);
5001 err_capa:
5002         cfs_timer_disarm(&m->mdt_ck_timer);
5003         mdt_ck_thread_stop(m);
5004 err_free_ns:
5005         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
5006         obd->obd_namespace = m->mdt_namespace = NULL;
5007 err_fini_seq:
5008         mdt_seq_fini(env, m);
5009 err_fini_fld:
5010         mdt_fld_fini(env, m);
5011 err_lut:
5012         lut_fini(env, &m->mdt_lut);
5013 err_fini_stack:
5014         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
5015 err_lmi:
5016         if (lmi)
5017                 server_put_mount(dev, lmi->lmi_mnt);
5018         return (rc);
5019 }
5020
5021 /* For interoperability between 1.8 and 2.0. */
5022 static struct cfg_interop_param mdt_interop_param[] = {
5023         { "mdt.group_upcall",   NULL },
5024         { "mdt.quota_type",     "mdd.quota_type" },
5025         { "mdt.rootsquash",     "mdt.root_squash" },
5026         { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
5027         { NULL }
5028 };
5029
5030 /* used by MGS to process specific configurations */
5031 static int mdt_process_config(const struct lu_env *env,
5032                               struct lu_device *d, struct lustre_cfg *cfg)
5033 {
5034         struct mdt_device *m = mdt_dev(d);
5035         struct md_device *md_next = m->mdt_child;
5036         struct lu_device *next = md2lu_dev(md_next);
5037         int rc = 0;
5038         ENTRY;
5039
5040         switch (cfg->lcfg_command) {
5041         case LCFG_PARAM: {
5042                 struct lprocfs_static_vars  lvars;
5043                 struct obd_device          *obd = d->ld_obd;
5044
5045                 /* For interoperability between 1.8 and 2.0. */
5046                 struct cfg_interop_param   *ptr = NULL;
5047                 struct lustre_cfg          *old_cfg = NULL;
5048                 char                       *param = NULL;
5049
5050                 param = lustre_cfg_string(cfg, 1);
5051                 if (param == NULL) {
5052                         CERROR("param is empty\n");
5053                         rc = -EINVAL;
5054                         break;
5055                 }
5056
5057                 ptr = class_find_old_param(param, mdt_interop_param);
5058                 if (ptr != NULL) {
5059                         if (ptr->new_param == NULL) {
5060                                 CWARN("For 1.8 interoperability, skip this %s."
5061                                       " It is obsolete.\n", ptr->old_param);
5062                                         break;
5063                         }
5064
5065                         CWARN("Found old param %s, changed it to %s.\n",
5066                               ptr->old_param, ptr->new_param);
5067
5068                         old_cfg = cfg;
5069                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
5070                         if (IS_ERR(cfg)) {
5071                                 rc = PTR_ERR(cfg);
5072                                 break;
5073                         }
5074                 }
5075
5076                 lprocfs_mdt_init_vars(&lvars);
5077                 rc = class_process_proc_param(PARAM_MDT, lvars.obd_vars,
5078                                               cfg, obd);
5079                 if (rc > 0 || rc == -ENOSYS)
5080                         /* we don't understand; pass it on */
5081                         rc = next->ld_ops->ldo_process_config(env, next, cfg);
5082
5083                 if (old_cfg != NULL)
5084                         lustre_cfg_free(cfg);
5085
5086                 break;
5087         }
5088         case LCFG_ADD_MDC:
5089                 /*
5090                  * Add mdc hook to get first MDT uuid and connect it to
5091                  * ls->controller to use for seq manager.
5092                  */
5093                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
5094                 if (rc)
5095                         CERROR("Can't add mdc, rc %d\n", rc);
5096                 else
5097                         rc = mdt_seq_init_cli(env, mdt_dev(d), cfg);
5098                 break;
5099         default:
5100                 /* others are passed further */
5101                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
5102                 break;
5103         }
5104         RETURN(rc);
5105 }
5106
5107 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
5108                                           const struct lu_object_header *hdr,
5109                                           struct lu_device *d)
5110 {
5111         struct mdt_object *mo;
5112
5113         ENTRY;
5114
5115         OBD_SLAB_ALLOC_PTR_GFP(mo, mdt_object_kmem, CFS_ALLOC_IO);
5116         if (mo != NULL) {
5117                 struct lu_object *o;
5118                 struct lu_object_header *h;
5119
5120                 o = &mo->mot_obj.mo_lu;
5121                 h = &mo->mot_header;
5122                 lu_object_header_init(h);
5123                 lu_object_init(o, h, d);
5124                 lu_object_add_top(h, o);
5125                 o->lo_ops = &mdt_obj_ops;
5126                 cfs_mutex_init(&mo->mot_ioepoch_mutex);
5127                 cfs_mutex_init(&mo->mot_lov_mutex);
5128                 RETURN(o);
5129         } else
5130                 RETURN(NULL);
5131 }
5132
5133 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
5134                            const struct lu_object_conf *unused)
5135 {
5136         struct mdt_device *d = mdt_dev(o->lo_dev);
5137         struct lu_device  *under;
5138         struct lu_object  *below;
5139         int                rc = 0;
5140         ENTRY;
5141
5142         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
5143                PFID(lu_object_fid(o)));
5144
5145         under = &d->mdt_child->md_lu_dev;
5146         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
5147         if (below != NULL) {
5148                 lu_object_add(o, below);
5149         } else
5150                 rc = -ENOMEM;
5151
5152         RETURN(rc);
5153 }
5154
5155 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
5156 {
5157         struct mdt_object *mo = mdt_obj(o);
5158         struct lu_object_header *h;
5159         ENTRY;
5160
5161         h = o->lo_header;
5162         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
5163                PFID(lu_object_fid(o)));
5164
5165         lu_object_fini(o);
5166         lu_object_header_fini(h);
5167         OBD_SLAB_FREE_PTR(mo, mdt_object_kmem);
5168
5169         EXIT;
5170 }
5171
5172 static int mdt_object_print(const struct lu_env *env, void *cookie,
5173                             lu_printer_t p, const struct lu_object *o)
5174 {
5175         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
5176         return (*p)(env, cookie, LUSTRE_MDT_NAME"-object@%p(ioepoch="LPU64" "
5177                     "flags="LPX64", epochcount=%d, writecount=%d)",
5178                     mdto, mdto->mot_ioepoch, mdto->mot_flags,
5179                     mdto->mot_ioepoch_count, mdto->mot_writecount);
5180 }
5181
5182 static const struct lu_device_operations mdt_lu_ops = {
5183         .ldo_object_alloc   = mdt_object_alloc,
5184         .ldo_process_config = mdt_process_config,
5185 };
5186
5187 static const struct lu_object_operations mdt_obj_ops = {
5188         .loo_object_init    = mdt_object_init,
5189         .loo_object_free    = mdt_object_free,
5190         .loo_object_print   = mdt_object_print
5191 };
5192
5193 static int mdt_obd_set_info_async(const struct lu_env *env,
5194                                   struct obd_export *exp,
5195                                   __u32 keylen, void *key,
5196                                   __u32 vallen, void *val,
5197                                   struct ptlrpc_request_set *set)
5198 {
5199         struct obd_device     *obd = exp->exp_obd;
5200         int                    rc;
5201         ENTRY;
5202
5203         LASSERT(obd);
5204
5205         if (KEY_IS(KEY_SPTLRPC_CONF)) {
5206                 rc = mdt_adapt_sptlrpc_conf(obd, 0);
5207                 RETURN(rc);
5208         }
5209
5210         RETURN(0);
5211 }
5212
5213 /* mds_connect_internal */
5214 static int mdt_connect_internal(struct obd_export *exp,
5215                                 struct mdt_device *mdt,
5216                                 struct obd_connect_data *data)
5217 {
5218         if (data != NULL) {
5219                 data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
5220                 data->ocd_ibits_known &= MDS_INODELOCK_FULL;
5221
5222                 /* If no known bits (which should not happen, probably,
5223                    as everybody should support LOOKUP and UPDATE bits at least)
5224                    revert to compat mode with plain locks. */
5225                 if (!data->ocd_ibits_known &&
5226                     data->ocd_connect_flags & OBD_CONNECT_IBITS)
5227                         data->ocd_connect_flags &= ~OBD_CONNECT_IBITS;
5228
5229                 if (!mdt->mdt_opts.mo_acl)
5230                         data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
5231
5232                 if (!mdt->mdt_opts.mo_user_xattr)
5233                         data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
5234
5235                 if (!mdt->mdt_som_conf)
5236                         data->ocd_connect_flags &= ~OBD_CONNECT_SOM;
5237
5238                 if (data->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
5239                         data->ocd_brw_size = min(data->ocd_brw_size,
5240                                (__u32)(PTLRPC_MAX_BRW_PAGES << CFS_PAGE_SHIFT));
5241                         if (data->ocd_brw_size == 0) {
5242                                 CERROR("%s: cli %s/%p ocd_connect_flags: "LPX64
5243                                        " ocd_version: %x ocd_grant: %d "
5244                                        "ocd_index: %u ocd_brw_size is "
5245                                        "unexpectedly zero, network data "
5246                                        "corruption? Refusing connection of this"
5247                                        " client\n",
5248                                        exp->exp_obd->obd_name,
5249                                        exp->exp_client_uuid.uuid,
5250                                        exp, data->ocd_connect_flags, data->ocd_version,
5251                                        data->ocd_grant, data->ocd_index);
5252                                 return -EPROTO;
5253                         }
5254                 }
5255
5256                 cfs_spin_lock(&exp->exp_lock);
5257                 exp->exp_connect_flags = data->ocd_connect_flags;
5258                 cfs_spin_unlock(&exp->exp_lock);
5259                 data->ocd_version = LUSTRE_VERSION_CODE;
5260                 exp->exp_mdt_data.med_ibits_known = data->ocd_ibits_known;
5261         }
5262
5263 #if 0
5264         if (mdt->mdt_opts.mo_acl &&
5265             ((exp->exp_connect_flags & OBD_CONNECT_ACL) == 0)) {
5266                 CWARN("%s: MDS requires ACL support but client does not\n",
5267                       mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
5268                 return -EBADE;
5269         }
5270 #endif
5271
5272         if ((exp->exp_connect_flags & OBD_CONNECT_FID) == 0) {
5273                 CWARN("%s: MDS requires FID support, but client not\n",
5274                       mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
5275                 return -EBADE;
5276         }
5277
5278         if (mdt->mdt_som_conf && !exp_connect_som(exp) &&
5279             !(exp->exp_connect_flags & OBD_CONNECT_MDS_MDS)) {
5280                 CWARN("%s: MDS has SOM enabled, but client does not support "
5281                       "it\n", mdt->mdt_md_dev.md_lu_dev.ld_obd->obd_name);
5282                 return -EBADE;
5283         }
5284
5285         return 0;
5286 }
5287
5288 static int mdt_connect_check_sptlrpc(struct mdt_device *mdt,
5289                                      struct obd_export *exp,
5290                                      struct ptlrpc_request *req)
5291 {
5292         struct sptlrpc_flavor   flvr;
5293         int                     rc = 0;
5294
5295         if (exp->exp_flvr.sf_rpc == SPTLRPC_FLVR_INVALID) {
5296                 cfs_read_lock(&mdt->mdt_sptlrpc_lock);
5297                 sptlrpc_target_choose_flavor(&mdt->mdt_sptlrpc_rset,
5298                                              req->rq_sp_from,
5299                                              req->rq_peer.nid,
5300                                              &flvr);
5301                 cfs_read_unlock(&mdt->mdt_sptlrpc_lock);
5302
5303                 cfs_spin_lock(&exp->exp_lock);
5304
5305                 exp->exp_sp_peer = req->rq_sp_from;
5306                 exp->exp_flvr = flvr;
5307
5308                 if (exp->exp_flvr.sf_rpc != SPTLRPC_FLVR_ANY &&
5309                     exp->exp_flvr.sf_rpc != req->rq_flvr.sf_rpc) {
5310                         CERROR("unauthorized rpc flavor %x from %s, "
5311                                "expect %x\n", req->rq_flvr.sf_rpc,
5312                                libcfs_nid2str(req->rq_peer.nid),
5313                                exp->exp_flvr.sf_rpc);
5314                         rc = -EACCES;
5315                 }
5316
5317                 cfs_spin_unlock(&exp->exp_lock);
5318         } else {
5319                 if (exp->exp_sp_peer != req->rq_sp_from) {
5320                         CERROR("RPC source %s doesn't match %s\n",
5321                                sptlrpc_part2name(req->rq_sp_from),
5322                                sptlrpc_part2name(exp->exp_sp_peer));
5323                         rc = -EACCES;
5324                 } else {
5325                         rc = sptlrpc_target_export_check(exp, req);
5326                 }
5327         }
5328
5329         return rc;
5330 }
5331
5332 /* mds_connect copy */
5333 static int mdt_obd_connect(const struct lu_env *env,
5334                            struct obd_export **exp, struct obd_device *obd,
5335                            struct obd_uuid *cluuid,
5336                            struct obd_connect_data *data,
5337                            void *localdata)
5338 {
5339         struct mdt_thread_info *info;
5340         struct obd_export      *lexp;
5341         struct lustre_handle    conn = { 0 };
5342         struct mdt_device      *mdt;
5343         struct ptlrpc_request  *req;
5344         int                     rc;
5345         ENTRY;
5346
5347         LASSERT(env != NULL);
5348         if (!exp || !obd || !cluuid)
5349                 RETURN(-EINVAL);
5350
5351         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5352         req = info->mti_pill->rc_req;
5353         mdt = mdt_dev(obd->obd_lu_dev);
5354
5355         rc = class_connect(&conn, obd, cluuid);
5356         if (rc)
5357                 RETURN(rc);
5358
5359         lexp = class_conn2export(&conn);
5360         LASSERT(lexp != NULL);
5361
5362         rc = mdt_connect_check_sptlrpc(mdt, lexp, req);
5363         if (rc)
5364                 GOTO(out, rc);
5365
5366         if (OBD_FAIL_CHECK(OBD_FAIL_TGT_RCVG_FLAG))
5367                 lustre_msg_add_op_flags(req->rq_repmsg, MSG_CONNECT_RECOVERING);
5368
5369         rc = mdt_connect_internal(lexp, mdt, data);
5370         if (rc == 0) {
5371                 struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
5372
5373                 LASSERT(lcd);
5374                 info->mti_exp = lexp;
5375                 memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
5376                 rc = lut_client_new(env, lexp);
5377                 if (rc == 0)
5378                         mdt_export_stats_init(obd, lexp, localdata);
5379         }
5380
5381 out:
5382         if (rc != 0) {
5383                 class_disconnect(lexp);
5384                 *exp = NULL;
5385         } else {
5386                 *exp = lexp;
5387         }
5388
5389         RETURN(rc);
5390 }
5391
5392 static int mdt_obd_reconnect(const struct lu_env *env,
5393                              struct obd_export *exp, struct obd_device *obd,
5394                              struct obd_uuid *cluuid,
5395                              struct obd_connect_data *data,
5396                              void *localdata)
5397 {
5398         struct mdt_thread_info *info;
5399         struct mdt_device      *mdt;
5400         struct ptlrpc_request  *req;
5401         int                     rc;
5402         ENTRY;
5403
5404         if (exp == NULL || obd == NULL || cluuid == NULL)
5405                 RETURN(-EINVAL);
5406
5407         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5408         req = info->mti_pill->rc_req;
5409         mdt = mdt_dev(obd->obd_lu_dev);
5410
5411         rc = mdt_connect_check_sptlrpc(mdt, exp, req);
5412         if (rc)
5413                 RETURN(rc);
5414
5415         rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
5416         if (rc == 0)
5417                 mdt_export_stats_init(obd, exp, localdata);
5418
5419         RETURN(rc);
5420 }
5421
5422 static int mdt_export_cleanup(struct obd_export *exp)
5423 {
5424         struct mdt_export_data *med = &exp->exp_mdt_data;
5425         struct obd_device      *obd = exp->exp_obd;
5426         struct mdt_device      *mdt;
5427         struct mdt_thread_info *info;
5428         struct lu_env           env;
5429         CFS_LIST_HEAD(closing_list);
5430         struct mdt_file_data *mfd, *n;
5431         int rc = 0;
5432         ENTRY;
5433
5434         cfs_spin_lock(&med->med_open_lock);
5435         while (!cfs_list_empty(&med->med_open_head)) {
5436                 cfs_list_t *tmp = med->med_open_head.next;
5437                 mfd = cfs_list_entry(tmp, struct mdt_file_data, mfd_list);
5438
5439                 /* Remove mfd handle so it can't be found again.
5440                  * We are consuming the mfd_list reference here. */
5441                 class_handle_unhash(&mfd->mfd_handle);
5442                 cfs_list_move_tail(&mfd->mfd_list, &closing_list);
5443         }
5444         cfs_spin_unlock(&med->med_open_lock);
5445         mdt = mdt_dev(obd->obd_lu_dev);
5446         LASSERT(mdt != NULL);
5447
5448         rc = lu_env_init(&env, LCT_MD_THREAD);
5449         if (rc)
5450                 RETURN(rc);
5451
5452         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5453         LASSERT(info != NULL);
5454         memset(info, 0, sizeof *info);
5455         info->mti_env = &env;
5456         info->mti_mdt = mdt;
5457         info->mti_exp = exp;
5458
5459         if (!cfs_list_empty(&closing_list)) {
5460                 struct md_attr *ma = &info->mti_attr;
5461                 int lmm_size;
5462                 int cookie_size;
5463
5464                 lmm_size = mdt->mdt_max_mdsize;
5465                 OBD_ALLOC_LARGE(ma->ma_lmm, lmm_size);
5466                 if (ma->ma_lmm == NULL)
5467                         GOTO(out_lmm, rc = -ENOMEM);
5468
5469                 cookie_size = mdt->mdt_max_cookiesize;
5470                 OBD_ALLOC_LARGE(ma->ma_cookie, cookie_size);
5471                 if (ma->ma_cookie == NULL)
5472                         GOTO(out_cookie, rc = -ENOMEM);
5473
5474                 /* Close any open files (which may also cause orphan unlinking). */
5475                 cfs_list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5476                         cfs_list_del_init(&mfd->mfd_list);
5477                         memset(&ma->ma_attr, 0, sizeof(ma->ma_attr));
5478                         ma->ma_lmm_size = lmm_size;
5479                         ma->ma_cookie_size = cookie_size;
5480                         ma->ma_need = 0;
5481                         /* It is not for setattr, just tell MDD to send
5482                          * DESTROY RPC to OSS if needed */
5483                         ma->ma_valid = MA_FLAGS;
5484                         ma->ma_attr_flags = MDS_CLOSE_CLEANUP;
5485                         /* Don't unlink orphan on failover umount, LU-184 */
5486                         if (exp->exp_flags & OBD_OPT_FAILOVER)
5487                                 ma->ma_attr_flags |= MDS_KEEP_ORPHAN;
5488                         mdt_mfd_close(info, mfd);
5489                 }
5490                 OBD_FREE_LARGE(ma->ma_cookie, cookie_size);
5491                 ma->ma_cookie = NULL;
5492 out_cookie:
5493                 OBD_FREE_LARGE(ma->ma_lmm, lmm_size);
5494                 ma->ma_lmm = NULL;
5495         }
5496 out_lmm:
5497         info->mti_mdt = NULL;
5498         /* cleanup client slot early */
5499         /* Do not erase record for recoverable client. */
5500         if (!(exp->exp_flags & OBD_OPT_FAILOVER) || exp->exp_failed)
5501                 lut_client_del(&env, exp);
5502         lu_env_fini(&env);
5503
5504         RETURN(rc);
5505 }
5506
5507 static int mdt_obd_disconnect(struct obd_export *exp)
5508 {
5509         int rc;
5510         ENTRY;
5511
5512         LASSERT(exp);
5513         class_export_get(exp);
5514
5515         rc = server_disconnect_export(exp);
5516         if (rc != 0)
5517                 CDEBUG(D_IOCTL, "server disconnect error: %d\n", rc);
5518
5519         rc = mdt_export_cleanup(exp);
5520         class_export_put(exp);
5521         RETURN(rc);
5522 }
5523
5524 /* FIXME: Can we avoid using these two interfaces? */
5525 static int mdt_init_export(struct obd_export *exp)
5526 {
5527         struct mdt_export_data *med = &exp->exp_mdt_data;
5528         int                     rc;
5529         ENTRY;
5530
5531         CFS_INIT_LIST_HEAD(&med->med_open_head);
5532         cfs_spin_lock_init(&med->med_open_lock);
5533         cfs_mutex_init(&med->med_idmap_mutex);
5534         med->med_idmap = NULL;
5535         cfs_spin_lock(&exp->exp_lock);
5536         exp->exp_connecting = 1;
5537         cfs_spin_unlock(&exp->exp_lock);
5538
5539         /* self-export doesn't need client data and ldlm initialization */
5540         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5541                                      &exp->exp_client_uuid)))
5542                 RETURN(0);
5543
5544         rc = lut_client_alloc(exp);
5545         if (rc)
5546                 GOTO(err, rc);
5547
5548         rc = ldlm_init_export(exp);
5549         if (rc)
5550                 GOTO(err_free, rc);
5551
5552         RETURN(rc);
5553
5554 err_free:
5555         lut_client_free(exp);
5556 err:
5557         CERROR("%s: Failed to initialize export: rc = %d\n",
5558                exp->exp_obd->obd_name, rc);
5559         return rc;
5560 }
5561
5562 static int mdt_destroy_export(struct obd_export *exp)
5563 {
5564         ENTRY;
5565
5566         if (exp_connect_rmtclient(exp))
5567                 mdt_cleanup_idmap(&exp->exp_mdt_data);
5568
5569         target_destroy_export(exp);
5570         /* destroy can be called from failed obd_setup, so
5571          * checking uuid is safer than obd_self_export */
5572         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5573                                      &exp->exp_client_uuid)))
5574                 RETURN(0);
5575
5576         ldlm_destroy_export(exp);
5577         lut_client_free(exp);
5578
5579         LASSERT(cfs_list_empty(&exp->exp_outstanding_replies));
5580         LASSERT(cfs_list_empty(&exp->exp_mdt_data.med_open_head));
5581
5582         RETURN(0);
5583 }
5584
5585 static void mdt_allow_cli(struct mdt_device *m, unsigned int flag)
5586 {
5587         if (flag & CONFIG_LOG)
5588                 cfs_set_bit(MDT_FL_CFGLOG, &m->mdt_state);
5589
5590         /* also notify active event */
5591         if (flag & CONFIG_SYNC)
5592                 cfs_set_bit(MDT_FL_SYNCED, &m->mdt_state);
5593
5594         if (cfs_test_bit(MDT_FL_CFGLOG, &m->mdt_state) &&
5595             cfs_test_bit(MDT_FL_SYNCED, &m->mdt_state)) {
5596                 struct obd_device *obd = m->mdt_md_dev.md_lu_dev.ld_obd;
5597
5598                 /* Open for clients */
5599                 if (obd->obd_no_conn) {
5600                         cfs_spin_lock(&obd->obd_dev_lock);
5601                         obd->obd_no_conn = 0;
5602                         cfs_spin_unlock(&obd->obd_dev_lock);
5603                 }
5604         }
5605 }
5606
5607 static int mdt_upcall(const struct lu_env *env, struct md_device *md,
5608                       enum md_upcall_event ev, void *data)
5609 {
5610         struct mdt_device *m = mdt_dev(&md->md_lu_dev);
5611         struct md_device  *next  = m->mdt_child;
5612         struct mdt_thread_info *mti;
5613         int rc = 0;
5614         ENTRY;
5615
5616         switch (ev) {
5617                 case MD_LOV_SYNC:
5618                         rc = next->md_ops->mdo_maxsize_get(env, next,
5619                                         &m->mdt_max_mdsize,
5620                                         &m->mdt_max_cookiesize);
5621                         CDEBUG(D_INFO, "get max mdsize %d max cookiesize %d\n",
5622                                      m->mdt_max_mdsize, m->mdt_max_cookiesize);
5623                         mdt_allow_cli(m, CONFIG_SYNC);
5624                         if (data)
5625                                 (*(__u64 *)data) =
5626                                       m->mdt_lut.lut_obd->u.obt.obt_mount_count;
5627                         break;
5628                 case MD_NO_TRANS:
5629                         mti = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
5630                         mti->mti_no_need_trans = 1;
5631                         CDEBUG(D_INFO, "disable mdt trans for this thread\n");
5632                         break;
5633                 case MD_LOV_CONFIG:
5634                         /* Check that MDT is not yet configured */
5635                         LASSERT(!cfs_test_bit(MDT_FL_CFGLOG, &m->mdt_state));
5636                         break;
5637 #ifdef HAVE_QUOTA_SUPPORT
5638                 case MD_LOV_QUOTA:
5639                         if (md->md_lu_dev.ld_obd->obd_recovering == 0 &&
5640                             likely(md->md_lu_dev.ld_obd->obd_stopping == 0))
5641                                 next->md_ops->mdo_quota.mqo_recovery(env, next);
5642                         break;
5643 #endif
5644                 default:
5645                         CERROR("invalid event\n");
5646                         rc = -EINVAL;
5647                         break;
5648         }
5649         RETURN(rc);
5650 }
5651
5652 static int mdt_obd_notify(struct obd_device *obd,
5653                           struct obd_device *watched,
5654                           enum obd_notify_event ev, void *data)
5655 {
5656         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5657 #ifdef HAVE_QUOTA_SUPPORT
5658         struct md_device *next = mdt->mdt_child;
5659 #endif
5660         ENTRY;
5661
5662         switch (ev) {
5663         case OBD_NOTIFY_CONFIG:
5664                 mdt_allow_cli(mdt, (unsigned long)data);
5665
5666 #ifdef HAVE_QUOTA_SUPPORT
5667                /* quota_type has been processed, we can now handle
5668                 * incoming quota requests */
5669                 next->md_ops->mdo_quota.mqo_notify(NULL, next);
5670 #endif
5671                 break;
5672         default:
5673                 CDEBUG(D_INFO, "Unhandled notification %#x\n", ev);
5674         }
5675         RETURN(0);
5676 }
5677
5678 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
5679                             void *val, int vallen)
5680 {
5681         struct mdt_device *mdt = mdt_dev(info->mti_exp->exp_obd->obd_lu_dev);
5682         struct getinfo_fid2path *fpout, *fpin;
5683         int rc = 0;
5684
5685         fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
5686         fpout = val;
5687
5688         if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
5689                 lustre_swab_fid2path(fpin);
5690
5691         memcpy(fpout, fpin, sizeof(*fpin));
5692         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
5693                 RETURN(-EINVAL);
5694
5695         rc = mdt_fid2path(info->mti_env, mdt, fpout);
5696         RETURN(rc);
5697 }
5698
5699 static int mdt_fid2path(const struct lu_env *env, struct mdt_device *mdt,
5700                         struct getinfo_fid2path *fp)
5701 {
5702         struct mdt_object *obj;
5703         int    rc;
5704         ENTRY;
5705
5706         CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
5707                PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
5708
5709         if (!fid_is_sane(&fp->gf_fid))
5710                 RETURN(-EINVAL);
5711
5712         obj = mdt_object_find(env, mdt, &fp->gf_fid);
5713         if (obj == NULL || IS_ERR(obj)) {
5714                 CDEBUG(D_IOCTL, "no object "DFID": %ld\n", PFID(&fp->gf_fid),
5715                        PTR_ERR(obj));
5716                 RETURN(-EINVAL);
5717         }
5718
5719         rc = lu_object_exists(&obj->mot_obj.mo_lu);
5720         if (rc <= 0) {
5721                 if (rc == -1)
5722                         rc = -EREMOTE;
5723                 else
5724                         rc = -ENOENT;
5725                 mdt_object_put(env, obj);
5726                 CDEBUG(D_IOCTL, "nonlocal object "DFID": %d\n",
5727                        PFID(&fp->gf_fid), rc);
5728                 RETURN(rc);
5729         }
5730
5731         rc = mo_path(env, md_object_next(&obj->mot_obj), fp->gf_path,
5732                      fp->gf_pathlen, &fp->gf_recno, &fp->gf_linkno);
5733         mdt_object_put(env, obj);
5734
5735         RETURN(rc);
5736 }
5737
5738 static int mdt_get_info(struct mdt_thread_info *info)
5739 {
5740         struct ptlrpc_request *req = mdt_info_req(info);
5741         char *key;
5742         int keylen;
5743         __u32 *vallen;
5744         void *valout;
5745         int rc;
5746         ENTRY;
5747
5748         key = req_capsule_client_get(info->mti_pill, &RMF_GETINFO_KEY);
5749         if (key == NULL) {
5750                 CDEBUG(D_IOCTL, "No GETINFO key");
5751                 RETURN(-EFAULT);
5752         }
5753         keylen = req_capsule_get_size(info->mti_pill, &RMF_GETINFO_KEY,
5754                                       RCL_CLIENT);
5755
5756         vallen = req_capsule_client_get(info->mti_pill, &RMF_GETINFO_VALLEN);
5757         if (vallen == NULL) {
5758                 CDEBUG(D_IOCTL, "Unable to get RMF_GETINFO_VALLEN buffer");
5759                 RETURN(-EFAULT);
5760         }
5761
5762         req_capsule_set_size(info->mti_pill, &RMF_GETINFO_VAL, RCL_SERVER,
5763                              *vallen);
5764         rc = req_capsule_server_pack(info->mti_pill);
5765         valout = req_capsule_server_get(info->mti_pill, &RMF_GETINFO_VAL);
5766         if (valout == NULL) {
5767                 CDEBUG(D_IOCTL, "Unable to get get-info RPC out buffer");
5768                 RETURN(-EFAULT);
5769         }
5770
5771         if (KEY_IS(KEY_FID2PATH))
5772                 rc = mdt_rpc_fid2path(info, key, valout, *vallen);
5773         else
5774                 rc = -EINVAL;
5775
5776         lustre_msg_set_status(req->rq_repmsg, rc);
5777
5778         RETURN(rc);
5779 }
5780
5781 /* Pass the ioc down */
5782 static int mdt_ioc_child(struct lu_env *env, struct mdt_device *mdt,
5783                          unsigned int cmd, int len, void *data)
5784 {
5785         struct lu_context ioctl_session;
5786         struct md_device *next = mdt->mdt_child;
5787         int rc;
5788         ENTRY;
5789
5790         rc = lu_context_init(&ioctl_session, LCT_SESSION);
5791         if (rc)
5792                 RETURN(rc);
5793         ioctl_session.lc_thread = (struct ptlrpc_thread *)cfs_current();
5794         lu_context_enter(&ioctl_session);
5795         env->le_ses = &ioctl_session;
5796
5797         LASSERT(next->md_ops->mdo_iocontrol);
5798         rc = next->md_ops->mdo_iocontrol(env, next, cmd, len, data);
5799
5800         lu_context_exit(&ioctl_session);
5801         lu_context_fini(&ioctl_session);
5802         RETURN(rc);
5803 }
5804
5805 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
5806 {
5807         struct obd_ioctl_data *data = karg;
5808         struct lu_fid *fid = (struct lu_fid *)data->ioc_inlbuf1;
5809         __u64 version;
5810         struct mdt_object *obj;
5811         struct mdt_lock_handle  *lh;
5812         int rc;
5813         ENTRY;
5814
5815         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
5816         if (!fid_is_sane(fid))
5817                 RETURN(-EINVAL);
5818
5819         lh = &mti->mti_lh[MDT_LH_PARENT];
5820         mdt_lock_reg_init(lh, LCK_CR);
5821
5822         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
5823         if (IS_ERR(obj))
5824                 RETURN(PTR_ERR(obj));
5825
5826         rc = mdt_object_exists(obj);
5827         if (rc < 0) {
5828                 rc = -EREMOTE;
5829                 /**
5830                  * before calling version get the correct MDS should be
5831                  * fid, this is error to find remote object here
5832                  */
5833                 CERROR("nonlocal object "DFID"\n", PFID(fid));
5834         } else if (rc == 0) {
5835                 *(__u64 *)data->ioc_inlbuf2 = ENOENT_VERSION;
5836                 rc = -ENOENT;
5837         } else {
5838                 version = dt_version_get(mti->mti_env, mdt_obj2dt(obj));
5839                *(__u64 *)data->ioc_inlbuf2 = version;
5840                 rc = 0;
5841         }
5842         mdt_object_unlock_put(mti, obj, lh, 1);
5843         RETURN(rc);
5844 }
5845
5846 /* ioctls on obd dev */
5847 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
5848                          void *karg, void *uarg)
5849 {
5850         struct lu_env      env;
5851         struct obd_device *obd = exp->exp_obd;
5852         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5853         struct dt_device  *dt = mdt->mdt_bottom;
5854         int rc;
5855
5856         ENTRY;
5857         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
5858         rc = lu_env_init(&env, LCT_MD_THREAD);
5859         if (rc)
5860                 RETURN(rc);
5861
5862         switch (cmd) {
5863         case OBD_IOC_SYNC:
5864                 rc = mdt_device_sync(&env, mdt);
5865                 break;
5866         case OBD_IOC_SET_READONLY:
5867                 rc = dt->dd_ops->dt_ro(&env, dt);
5868                 break;
5869         case OBD_IOC_ABORT_RECOVERY:
5870                 CERROR("Aborting recovery for device %s\n", obd->obd_name);
5871                 target_stop_recovery_thread(obd);
5872                 rc = 0;
5873                 break;
5874         case OBD_IOC_CHANGELOG_REG:
5875         case OBD_IOC_CHANGELOG_DEREG:
5876         case OBD_IOC_CHANGELOG_CLEAR:
5877                 rc = mdt_ioc_child(&env, mdt, cmd, len, karg);
5878                 break;
5879         case OBD_IOC_START_LFSCK:
5880         case OBD_IOC_STOP_LFSCK: {
5881                 struct md_device *next = mdt->mdt_child;
5882                 struct obd_ioctl_data *data = karg;
5883
5884                 if (unlikely(data == NULL)) {
5885                         rc = -EINVAL;
5886                         break;
5887                 }
5888
5889                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd,
5890                                                  data->ioc_inllen1,
5891                                                  data->ioc_inlbuf1);
5892                 break;
5893         }
5894         case OBD_IOC_GET_OBJ_VERSION: {
5895                 struct mdt_thread_info *mti;
5896                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5897                 memset(mti, 0, sizeof *mti);
5898                 mti->mti_env = &env;
5899                 mti->mti_mdt = mdt;
5900                 mti->mti_exp = exp;
5901
5902                 rc = mdt_ioc_version_get(mti, karg);
5903                 break;
5904         }
5905         default:
5906                 CERROR("Not supported cmd = %d for device %s\n",
5907                        cmd, obd->obd_name);
5908                 rc = -EOPNOTSUPP;
5909         }
5910
5911         lu_env_fini(&env);
5912         RETURN(rc);
5913 }
5914
5915 int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
5916 {
5917         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
5918 #ifdef HAVE_QUOTA_SUPPORT
5919         struct obd_device *obd = mdt2obd_dev(mdt);
5920         struct md_device *next = mdt->mdt_child;
5921 #endif
5922         int rc;
5923         ENTRY;
5924
5925         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
5926 #ifdef HAVE_QUOTA_SUPPORT
5927         if (likely(obd->obd_stopping == 0))
5928                 next->md_ops->mdo_quota.mqo_recovery(env, next);
5929 #endif
5930         RETURN(rc);
5931 }
5932
5933 int mdt_obd_postrecov(struct obd_device *obd)
5934 {
5935         struct lu_env env;
5936         int rc;
5937
5938         rc = lu_env_init(&env, LCT_MD_THREAD);
5939         if (rc)
5940                 RETURN(rc);
5941         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
5942         lu_env_fini(&env);
5943         return rc;
5944 }
5945
5946 /**
5947  * Send a copytool req to a client
5948  * Note this sends a request RPC from a server (MDT) to a client (MDC),
5949  * backwards of normal comms.
5950  */
5951 int mdt_hsm_copytool_send(struct obd_export *exp)
5952 {
5953         struct kuc_hdr *lh;
5954         struct hsm_action_list *hal;
5955         struct hsm_action_item *hai;
5956         int rc, len;
5957         ENTRY;
5958
5959         CWARN("%s: writing to mdc at %s\n", exp->exp_obd->obd_name,
5960               libcfs_nid2str(exp->exp_connection->c_peer.nid));
5961
5962         len = sizeof(*lh) + sizeof(*hal) + MTI_NAME_MAXLEN +
5963                 /* for mockup below */ 2 * cfs_size_round(sizeof(*hai));
5964         OBD_ALLOC(lh, len);
5965         if (lh == NULL)
5966                 RETURN(-ENOMEM);
5967
5968         lh->kuc_magic = KUC_MAGIC;
5969         lh->kuc_transport = KUC_TRANSPORT_HSM;
5970         lh->kuc_msgtype = HMT_ACTION_LIST;
5971         lh->kuc_msglen = len;
5972
5973         hal = (struct hsm_action_list *)(lh + 1);
5974         hal->hal_version = HAL_VERSION;
5975         hal->hal_archive_num = 1;
5976         obd_uuid2fsname(hal->hal_fsname, exp->exp_obd->obd_name,
5977                         MTI_NAME_MAXLEN);
5978
5979         /* mock up an action list */
5980         hal->hal_count = 2;
5981         hai = hai_zero(hal);
5982         hai->hai_action = HSMA_ARCHIVE;
5983         hai->hai_fid.f_oid = 0xA00A;
5984         hai->hai_len = sizeof(*hai);
5985         hai = hai_next(hai);
5986         hai->hai_action = HSMA_RESTORE;
5987         hai->hai_fid.f_oid = 0xB00B;
5988         hai->hai_len = sizeof(*hai);
5989
5990         /* Uses the ldlm reverse import; this rpc will be seen by
5991           the ldlm_callback_handler */
5992         rc = do_set_info_async(exp->exp_imp_reverse,
5993                                LDLM_SET_INFO, LUSTRE_OBD_VERSION,
5994                                sizeof(KEY_HSM_COPYTOOL_SEND),
5995                                KEY_HSM_COPYTOOL_SEND,
5996                                len, lh, NULL);
5997
5998         OBD_FREE(lh, len);
5999
6000         RETURN(rc);
6001 }
6002
6003 static struct obd_ops mdt_obd_device_ops = {
6004         .o_owner          = THIS_MODULE,
6005         .o_set_info_async = mdt_obd_set_info_async,
6006         .o_connect        = mdt_obd_connect,
6007         .o_reconnect      = mdt_obd_reconnect,
6008         .o_disconnect     = mdt_obd_disconnect,
6009         .o_init_export    = mdt_init_export,
6010         .o_destroy_export = mdt_destroy_export,
6011         .o_iocontrol      = mdt_iocontrol,
6012         .o_postrecov      = mdt_obd_postrecov,
6013         .o_notify         = mdt_obd_notify
6014 };
6015
6016 static struct lu_device* mdt_device_fini(const struct lu_env *env,
6017                                          struct lu_device *d)
6018 {
6019         struct mdt_device *m = mdt_dev(d);
6020         ENTRY;
6021
6022         mdt_fini(env, m);
6023         RETURN(NULL);
6024 }
6025
6026 static struct lu_device *mdt_device_free(const struct lu_env *env,
6027                                          struct lu_device *d)
6028 {
6029         struct mdt_device *m = mdt_dev(d);
6030         ENTRY;
6031
6032         md_device_fini(&m->mdt_md_dev);
6033         OBD_FREE_PTR(m);
6034         RETURN(NULL);
6035 }
6036
6037 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
6038                                           struct lu_device_type *t,
6039                                           struct lustre_cfg *cfg)
6040 {
6041         struct lu_device  *l;
6042         struct mdt_device *m;
6043
6044         OBD_ALLOC_PTR(m);
6045         if (m != NULL) {
6046                 int rc;
6047
6048                 l = &m->mdt_md_dev.md_lu_dev;
6049                 rc = mdt_init0(env, m, t, cfg);
6050                 if (rc != 0) {
6051                         mdt_device_free(env, l);
6052                         l = ERR_PTR(rc);
6053                         return l;
6054                 }
6055                 md_upcall_init(&m->mdt_md_dev, mdt_upcall);
6056         } else
6057                 l = ERR_PTR(-ENOMEM);
6058         return l;
6059 }
6060
6061 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
6062 LU_KEY_INIT_FINI(mdt, struct mdt_thread_info);
6063
6064 /* context key: mdt_thread_key */
6065 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
6066
6067 struct md_ucred *mdt_ucred(const struct mdt_thread_info *info)
6068 {
6069         return md_ucred(info->mti_env);
6070 }
6071
6072 /**
6073  * Enable/disable COS (Commit On Sharing).
6074  *
6075  * Set/Clear the COS flag in mdt options.
6076  *
6077  * \param mdt mdt device
6078  * \param val 0 disables COS, other values enable COS
6079  */
6080 void mdt_enable_cos(struct mdt_device *mdt, int val)
6081 {
6082         struct lu_env env;
6083         int rc;
6084
6085         mdt->mdt_opts.mo_cos = !!val;
6086         rc = lu_env_init(&env, LCT_LOCAL);
6087         if (unlikely(rc != 0)) {
6088                 CWARN("lu_env initialization failed with rc = %d,"
6089                       "cannot sync\n", rc);
6090                 return;
6091         }
6092         mdt_device_sync(&env, mdt);
6093         lu_env_fini(&env);
6094 }
6095
6096 /**
6097  * Check COS (Commit On Sharing) status.
6098  *
6099  * Return COS flag status.
6100  *
6101  * \param mdt mdt device
6102  */
6103 int mdt_cos_is_enabled(struct mdt_device *mdt)
6104 {
6105         return mdt->mdt_opts.mo_cos != 0;
6106 }
6107
6108 /* type constructor/destructor: mdt_type_init, mdt_type_fini */
6109 LU_TYPE_INIT_FINI(mdt, &mdt_thread_key);
6110
6111 static struct lu_device_type_operations mdt_device_type_ops = {
6112         .ldto_init = mdt_type_init,
6113         .ldto_fini = mdt_type_fini,
6114
6115         .ldto_start = mdt_type_start,
6116         .ldto_stop  = mdt_type_stop,
6117
6118         .ldto_device_alloc = mdt_device_alloc,
6119         .ldto_device_free  = mdt_device_free,
6120         .ldto_device_fini  = mdt_device_fini
6121 };
6122
6123 static struct lu_device_type mdt_device_type = {
6124         .ldt_tags     = LU_DEVICE_MD,
6125         .ldt_name     = LUSTRE_MDT_NAME,
6126         .ldt_ops      = &mdt_device_type_ops,
6127         .ldt_ctx_tags = LCT_MD_THREAD
6128 };
6129
6130 static int __init mdt_mod_init(void)
6131 {
6132         struct lprocfs_static_vars lvars;
6133         int rc;
6134
6135         rc = lu_kmem_init(mdt_caches);
6136         if (rc)
6137                 return rc;
6138
6139         if (mdt_num_threads != 0 && mds_num_threads == 0) {
6140                 LCONSOLE_INFO("mdt_num_threads module parameter is deprecated,"
6141                               "use mds_num_threads instead or unset both for"
6142                               "dynamic thread startup\n");
6143                 mds_num_threads = mdt_num_threads;
6144         }
6145
6146         lprocfs_mdt_init_vars(&lvars);
6147         rc = class_register_type(&mdt_obd_device_ops, NULL,
6148                                  lvars.module_vars, LUSTRE_MDT_NAME,
6149                                  &mdt_device_type);
6150
6151         if (rc)
6152                 lu_kmem_fini(mdt_caches);
6153         return rc;
6154 }
6155
6156 static void __exit mdt_mod_exit(void)
6157 {
6158         class_unregister_type(LUSTRE_MDT_NAME);
6159         lu_kmem_fini(mdt_caches);
6160 }
6161
6162
6163 #define DEF_HNDL(prefix, base, suffix, flags, opc, fn, fmt)             \
6164 [prefix ## _ ## opc - prefix ## _ ## base] = {                          \
6165         .mh_name    = #opc,                                             \
6166         .mh_fail_id = OBD_FAIL_ ## prefix ## _  ## opc ## suffix,       \
6167         .mh_opc     = prefix ## _  ## opc,                              \
6168         .mh_flags   = flags,                                            \
6169         .mh_act     = fn,                                               \
6170         .mh_fmt     = fmt                                               \
6171 }
6172
6173 #define DEF_MDT_HNDL(flags, name, fn, fmt)                                  \
6174         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, fmt)
6175
6176 #define DEF_SEQ_HNDL(flags, name, fn, fmt)                      \
6177         DEF_HNDL(SEQ, QUERY, _NET, flags, name, fn, fmt)
6178
6179 #define DEF_FLD_HNDL(flags, name, fn, fmt)                      \
6180         DEF_HNDL(FLD, QUERY, _NET, flags, name, fn, fmt)
6181 /*
6182  * Request with a format known in advance
6183  */
6184 #define DEF_MDT_HNDL_F(flags, name, fn)                                 \
6185         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, &RQF_MDS_ ## name)
6186
6187 #define DEF_SEQ_HNDL_F(flags, name, fn)                                 \
6188         DEF_HNDL(SEQ, QUERY, _NET, flags, name, fn, &RQF_SEQ_ ## name)
6189
6190 #define DEF_FLD_HNDL_F(flags, name, fn)                                 \
6191         DEF_HNDL(FLD, QUERY, _NET, flags, name, fn, &RQF_FLD_ ## name)
6192 /*
6193  * Request with a format we do not yet know
6194  */
6195 #define DEF_MDT_HNDL_0(flags, name, fn)                                 \
6196         DEF_HNDL(MDS, GETATTR, _NET, flags, name, fn, NULL)
6197
6198 static struct mdt_handler mdt_mds_ops[] = {
6199 DEF_MDT_HNDL_F(0,                         CONNECT,      mdt_connect),
6200 DEF_MDT_HNDL_F(0,                         DISCONNECT,   mdt_disconnect),
6201 DEF_MDT_HNDL  (0,                         SET_INFO,     mdt_set_info,
6202                                                              &RQF_OBD_SET_INFO),
6203 DEF_MDT_HNDL_F(0,                         GET_INFO,     mdt_get_info),
6204 DEF_MDT_HNDL_F(0           |HABEO_REFERO, GETSTATUS,    mdt_getstatus),
6205 DEF_MDT_HNDL_F(HABEO_CORPUS,              GETATTR,      mdt_getattr),
6206 DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, GETATTR_NAME, mdt_getattr_name),
6207 DEF_MDT_HNDL_F(HABEO_CORPUS,              GETXATTR,     mdt_getxattr),
6208 DEF_MDT_HNDL_F(0           |HABEO_REFERO, STATFS,       mdt_statfs),
6209 DEF_MDT_HNDL_F(0           |MUTABOR,      REINT,        mdt_reint),
6210 DEF_MDT_HNDL_F(HABEO_CORPUS,              CLOSE,        mdt_close),
6211 DEF_MDT_HNDL_F(HABEO_CORPUS,              DONE_WRITING, mdt_done_writing),
6212 DEF_MDT_HNDL_F(0           |HABEO_REFERO, PIN,          mdt_pin),
6213 DEF_MDT_HNDL_0(0,                         SYNC,         mdt_sync),
6214 DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, IS_SUBDIR,    mdt_is_subdir),
6215 #ifdef HAVE_QUOTA_SUPPORT
6216 DEF_MDT_HNDL_F(0,                         QUOTACHECK,   mdt_quotacheck_handle),
6217 DEF_MDT_HNDL_F(0,                         QUOTACTL,     mdt_quotactl_handle)
6218 #endif
6219 };
6220
6221 #define DEF_OBD_HNDL(flags, name, fn)                   \
6222         DEF_HNDL(OBD, PING, _NET, flags, name, fn, NULL)
6223
6224
6225 static struct mdt_handler mdt_obd_ops[] = {
6226         DEF_OBD_HNDL(0, PING,           mdt_obd_ping),
6227         DEF_OBD_HNDL(0, LOG_CANCEL,     mdt_obd_log_cancel),
6228         DEF_OBD_HNDL(0, QC_CALLBACK,    mdt_obd_qc_callback),
6229         DEF_OBD_HNDL(0, IDX_READ,       mdt_obd_idx_read)
6230 };
6231
6232 #define DEF_DLM_HNDL_0(flags, name, fn)                   \
6233         DEF_HNDL(LDLM, ENQUEUE, , flags, name, fn, NULL)
6234 #define DEF_DLM_HNDL_F(flags, name, fn)                   \
6235         DEF_HNDL(LDLM, ENQUEUE, , flags, name, fn, &RQF_LDLM_ ## name)
6236
6237 static struct mdt_handler mdt_dlm_ops[] = {
6238         DEF_DLM_HNDL_F(HABEO_CLAVIS, ENQUEUE,        mdt_enqueue),
6239         DEF_DLM_HNDL_0(HABEO_CLAVIS, CONVERT,        mdt_convert),
6240         DEF_DLM_HNDL_0(0,            BL_CALLBACK,    mdt_bl_callback),
6241         DEF_DLM_HNDL_0(0,            CP_CALLBACK,    mdt_cp_callback)
6242 };
6243
6244 #define DEF_LLOG_HNDL(flags, name, fn)                   \
6245         DEF_HNDL(LLOG, ORIGIN_HANDLE_CREATE, _NET, flags, name, fn, NULL)
6246
6247 static struct mdt_handler mdt_llog_ops[] = {
6248         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_CREATE,      mdt_llog_create),
6249         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_NEXT_BLOCK,  mdt_llog_next_block),
6250         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_READ_HEADER, mdt_llog_read_header),
6251         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_WRITE_REC,   NULL),
6252         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_CLOSE,       NULL),
6253         DEF_LLOG_HNDL(0, ORIGIN_CONNECT,            NULL),
6254         DEF_LLOG_HNDL(0, CATINFO,                   NULL),
6255         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_PREV_BLOCK,  mdt_llog_prev_block),
6256         DEF_LLOG_HNDL(0, ORIGIN_HANDLE_DESTROY,     mdt_llog_destroy),
6257 };
6258
6259 #define DEF_SEC_CTX_HNDL(name, fn)                      \
6260         DEF_HNDL(SEC_CTX, INIT, _NET, 0, name, fn, NULL)
6261
6262 static struct mdt_handler mdt_sec_ctx_ops[] = {
6263         DEF_SEC_CTX_HNDL(INIT,          mdt_sec_ctx_handle),
6264         DEF_SEC_CTX_HNDL(INIT_CONT,     mdt_sec_ctx_handle),
6265         DEF_SEC_CTX_HNDL(FINI,          mdt_sec_ctx_handle)
6266 };
6267
6268 static struct mdt_opc_slice mdt_regular_handlers[] = {
6269         {
6270                 .mos_opc_start = MDS_GETATTR,
6271                 .mos_opc_end   = MDS_LAST_OPC,
6272                 .mos_hs        = mdt_mds_ops
6273         },
6274         {
6275                 .mos_opc_start = OBD_PING,
6276                 .mos_opc_end   = OBD_LAST_OPC,
6277                 .mos_hs        = mdt_obd_ops
6278         },
6279         {
6280                 .mos_opc_start = LDLM_ENQUEUE,
6281                 .mos_opc_end   = LDLM_LAST_OPC,
6282                 .mos_hs        = mdt_dlm_ops
6283         },
6284         {
6285                 .mos_opc_start = LLOG_ORIGIN_HANDLE_CREATE,
6286                 .mos_opc_end   = LLOG_LAST_OPC,
6287                 .mos_hs        = mdt_llog_ops
6288         },
6289         {
6290                 .mos_opc_start = SEC_CTX_INIT,
6291                 .mos_opc_end   = SEC_LAST_OPC,
6292                 .mos_hs        = mdt_sec_ctx_ops
6293         },
6294         {
6295                 .mos_hs        = NULL
6296         }
6297 };
6298
6299 static struct mdt_handler mdt_readpage_ops[] = {
6300         DEF_MDT_HNDL_F(0,                         CONNECT,  mdt_connect),
6301         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, READPAGE, mdt_readpage),
6302 #ifdef HAVE_SPLIT_SUPPORT
6303         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, WRITEPAGE, mdt_writepage),
6304 #endif
6305
6306         /*
6307          * XXX: this is ugly and should be fixed one day, see mdc_close() for
6308          * detailed comments. --umka
6309          */
6310         DEF_MDT_HNDL_F(HABEO_CORPUS,              CLOSE,    mdt_close),
6311         DEF_MDT_HNDL_F(HABEO_CORPUS,              DONE_WRITING,    mdt_done_writing),
6312 };
6313
6314 static struct mdt_opc_slice mdt_readpage_handlers[] = {
6315         {
6316                 .mos_opc_start = MDS_GETATTR,
6317                 .mos_opc_end   = MDS_LAST_OPC,
6318                 .mos_hs        = mdt_readpage_ops
6319         },
6320         {
6321                 .mos_opc_start = OBD_FIRST_OPC,
6322                 .mos_opc_end   = OBD_LAST_OPC,
6323                 .mos_hs        = mdt_obd_ops
6324         },
6325         {
6326                 .mos_hs        = NULL
6327         }
6328 };
6329
6330 static struct mdt_handler mdt_xmds_ops[] = {
6331         DEF_MDT_HNDL_F(0,                         CONNECT,      mdt_connect),
6332         DEF_MDT_HNDL_F(HABEO_CORPUS             , GETATTR,      mdt_getattr),
6333         DEF_MDT_HNDL_F(0 | MUTABOR              , REINT,        mdt_reint),
6334         DEF_MDT_HNDL_F(HABEO_CORPUS|HABEO_REFERO, IS_SUBDIR,    mdt_is_subdir),
6335 };
6336
6337 static struct mdt_opc_slice mdt_xmds_handlers[] = {
6338         {
6339                 .mos_opc_start = MDS_GETATTR,
6340                 .mos_opc_end   = MDS_LAST_OPC,
6341                 .mos_hs        = mdt_xmds_ops
6342         },
6343         {
6344                 .mos_opc_start = OBD_PING,
6345                 .mos_opc_end   = OBD_LAST_OPC,
6346                 .mos_hs        = mdt_obd_ops
6347         },
6348         {
6349                 .mos_opc_start = SEC_CTX_INIT,
6350                 .mos_opc_end   = SEC_LAST_OPC,
6351                 .mos_hs        = mdt_sec_ctx_ops
6352         },
6353         {
6354                 .mos_hs        = NULL
6355         }
6356 };
6357
6358 static struct mdt_handler mdt_seq_ops[] = {
6359         DEF_SEQ_HNDL_F(0, QUERY, (int (*)(struct mdt_thread_info *))seq_query)
6360 };
6361
6362 static struct mdt_opc_slice mdt_seq_handlers[] = {
6363         {
6364                 .mos_opc_start = SEQ_QUERY,
6365                 .mos_opc_end   = SEQ_LAST_OPC,
6366                 .mos_hs        = mdt_seq_ops
6367         },
6368         {
6369                 .mos_hs        = NULL
6370         }
6371 };
6372
6373 static struct mdt_handler mdt_fld_ops[] = {
6374         DEF_FLD_HNDL_F(0, QUERY, (int (*)(struct mdt_thread_info *))fld_query)
6375 };
6376
6377 static struct mdt_opc_slice mdt_fld_handlers[] = {
6378         {
6379                 .mos_opc_start = FLD_QUERY,
6380                 .mos_opc_end   = FLD_LAST_OPC,
6381                 .mos_hs        = mdt_fld_ops
6382         },
6383         {
6384                 .mos_hs        = NULL
6385         }
6386 };
6387
6388 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6389 MODULE_DESCRIPTION("Lustre Meta-data Target ("LUSTRE_MDT_NAME")");
6390 MODULE_LICENSE("GPL");
6391
6392 cfs_module(mdt, "0.2.0", mdt_mod_init, mdt_mod_exit);