Whamcloud - gitweb
LU-4461 mdt: correct test in mdt_seq_fini_cli()
[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) 2010, 2013, Intel Corporation.
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_log.h>
66 #include "mdt_internal.h"
67 #include <lustre_acl.h>
68 #include <lustre_param.h>
69 #include <lustre_quota.h>
70 #include <lustre_lfsck.h>
71
72 mdl_mode_t mdt_mdl_lock_modes[] = {
73         [LCK_MINMODE] = MDL_MINMODE,
74         [LCK_EX]      = MDL_EX,
75         [LCK_PW]      = MDL_PW,
76         [LCK_PR]      = MDL_PR,
77         [LCK_CW]      = MDL_CW,
78         [LCK_CR]      = MDL_CR,
79         [LCK_NL]      = MDL_NL,
80         [LCK_GROUP]   = MDL_GROUP
81 };
82
83 ldlm_mode_t mdt_dlm_lock_modes[] = {
84         [MDL_MINMODE] = LCK_MINMODE,
85         [MDL_EX]      = LCK_EX,
86         [MDL_PW]      = LCK_PW,
87         [MDL_PR]      = LCK_PR,
88         [MDL_CW]      = LCK_CW,
89         [MDL_CR]      = LCK_CR,
90         [MDL_NL]      = LCK_NL,
91         [MDL_GROUP]   = LCK_GROUP
92 };
93
94 static struct mdt_device *mdt_dev(struct lu_device *d);
95 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags);
96
97 static const struct lu_object_operations mdt_obj_ops;
98
99 /* Slab for MDT object allocation */
100 static struct kmem_cache *mdt_object_kmem;
101
102 /* For HSM restore handles */
103 struct kmem_cache *mdt_hsm_cdt_kmem;
104
105 /* For HSM request handles */
106 struct kmem_cache *mdt_hsm_car_kmem;
107
108 static struct lu_kmem_descr mdt_caches[] = {
109         {
110                 .ckd_cache = &mdt_object_kmem,
111                 .ckd_name  = "mdt_obj",
112                 .ckd_size  = sizeof(struct mdt_object)
113         },
114         {
115                 .ckd_cache      = &mdt_hsm_cdt_kmem,
116                 .ckd_name       = "mdt_cdt_restore_handle",
117                 .ckd_size       = sizeof(struct cdt_restore_handle)
118         },
119         {
120                 .ckd_cache      = &mdt_hsm_car_kmem,
121                 .ckd_name       = "mdt_cdt_agent_req",
122                 .ckd_size       = sizeof(struct cdt_agent_req)
123         },
124         {
125                 .ckd_cache = NULL
126         }
127 };
128
129 int mdt_get_disposition(struct ldlm_reply *rep, int flag)
130 {
131         if (!rep)
132                 return 0;
133         return (rep->lock_policy_res1 & flag);
134 }
135
136 void mdt_clear_disposition(struct mdt_thread_info *info,
137                            struct ldlm_reply *rep, int flag)
138 {
139         if (info) {
140                 info->mti_opdata &= ~flag;
141                 tgt_opdata_clear(info->mti_env, flag);
142         }
143         if (rep)
144                 rep->lock_policy_res1 &= ~flag;
145 }
146
147 void mdt_set_disposition(struct mdt_thread_info *info,
148                          struct ldlm_reply *rep, int flag)
149 {
150         if (info) {
151                 info->mti_opdata |= flag;
152                 tgt_opdata_set(info->mti_env, flag);
153         }
154         if (rep)
155                 rep->lock_policy_res1 |= flag;
156 }
157
158 void mdt_lock_reg_init(struct mdt_lock_handle *lh, ldlm_mode_t lm)
159 {
160         lh->mlh_pdo_hash = 0;
161         lh->mlh_reg_mode = lm;
162         lh->mlh_rreg_mode = lm;
163         lh->mlh_type = MDT_REG_LOCK;
164 }
165
166 void mdt_lock_pdo_init(struct mdt_lock_handle *lh, ldlm_mode_t lock_mode,
167                        const struct lu_name *lname)
168 {
169         lh->mlh_reg_mode = lock_mode;
170         lh->mlh_rreg_mode = lock_mode;
171         lh->mlh_type = MDT_PDO_LOCK;
172
173         if (lu_name_is_valid(lname)) {
174                 lh->mlh_pdo_hash = full_name_hash(lname->ln_name,
175                                                   lname->ln_namelen);
176                 /* XXX Workaround for LU-2856
177                  *
178                  * Zero is a valid return value of full_name_hash, but
179                  * several users of mlh_pdo_hash assume a non-zero
180                  * hash value. We therefore map zero onto an
181                  * arbitrary, but consistent value (1) to avoid
182                  * problems further down the road. */
183                 if (unlikely(lh->mlh_pdo_hash == 0))
184                         lh->mlh_pdo_hash = 1;
185         } else {
186                 lh->mlh_pdo_hash = 0;
187         }
188 }
189
190 static void mdt_lock_pdo_mode(struct mdt_thread_info *info, struct mdt_object *o,
191                               struct mdt_lock_handle *lh)
192 {
193         mdl_mode_t mode;
194         ENTRY;
195
196         /*
197          * Any dir access needs couple of locks:
198          *
199          * 1) on part of dir we gonna take lookup/modify;
200          *
201          * 2) on whole dir to protect it from concurrent splitting and/or to
202          * flush client's cache for readdir().
203          *
204          * so, for a given mode and object this routine decides what lock mode
205          * to use for lock #2:
206          *
207          * 1) if caller's gonna lookup in dir then we need to protect dir from
208          * being splitted only - LCK_CR
209          *
210          * 2) if caller's gonna modify dir then we need to protect dir from
211          * being splitted and to flush cache - LCK_CW
212          *
213          * 3) if caller's gonna modify dir and that dir seems ready for
214          * splitting then we need to protect it from any type of access
215          * (lookup/modify/split) - LCK_EX --bzzz
216          */
217
218         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
219         LASSERT(lh->mlh_pdo_mode == LCK_MINMODE);
220
221         /*
222          * Ask underlaying level its opinion about preferable PDO lock mode
223          * having access type passed as regular lock mode:
224          *
225          * - MDL_MINMODE means that lower layer does not want to specify lock
226          * mode;
227          *
228          * - MDL_NL means that no PDO lock should be taken. This is used in some
229          * cases. Say, for non-splittable directories no need to use PDO locks
230          * at all.
231          */
232         mode = mdo_lock_mode(info->mti_env, mdt_object_child(o),
233                              mdt_dlm_mode2mdl_mode(lh->mlh_reg_mode));
234
235         if (mode != MDL_MINMODE) {
236                 lh->mlh_pdo_mode = mdt_mdl_mode2dlm_mode(mode);
237         } else {
238                 /*
239                  * Lower layer does not want to specify locking mode. We do it
240                  * our selves. No special protection is needed, just flush
241                  * client's cache on modification and allow concurrent
242                  * mondification.
243                  */
244                 switch (lh->mlh_reg_mode) {
245                 case LCK_EX:
246                         lh->mlh_pdo_mode = LCK_EX;
247                         break;
248                 case LCK_PR:
249                         lh->mlh_pdo_mode = LCK_CR;
250                         break;
251                 case LCK_PW:
252                         lh->mlh_pdo_mode = LCK_CW;
253                         break;
254                 default:
255                         CERROR("Not expected lock type (0x%x)\n",
256                                (int)lh->mlh_reg_mode);
257                         LBUG();
258                 }
259         }
260
261         LASSERT(lh->mlh_pdo_mode != LCK_MINMODE);
262         EXIT;
263 }
264
265 static int mdt_getstatus(struct tgt_session_info *tsi)
266 {
267         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
268         struct mdt_device       *mdt = info->mti_mdt;
269         struct mdt_body         *repbody;
270         int                      rc;
271
272         ENTRY;
273
274         rc = mdt_check_ucred(info);
275         if (rc)
276                 GOTO(out, rc = err_serious(rc));
277
278         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETSTATUS_PACK))
279                 GOTO(out, rc = err_serious(-ENOMEM));
280
281         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
282         repbody->fid1 = mdt->mdt_md_root_fid;
283         repbody->valid |= OBD_MD_FLID;
284
285         if (tsi->tsi_tgt->lut_mds_capa &&
286             exp_connect_flags(info->mti_exp) & OBD_CONNECT_MDS_CAPA) {
287                 struct mdt_object       *root;
288                 struct lustre_capa      *capa;
289
290                 root = mdt_object_find(info->mti_env, mdt, &repbody->fid1);
291                 if (IS_ERR(root))
292                         GOTO(out, rc = PTR_ERR(root));
293
294                 capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA1);
295                 LASSERT(capa);
296                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
297                 rc = mo_capa_get(info->mti_env, mdt_object_child(root), capa,
298                                  0);
299                 mdt_object_put(info->mti_env, root);
300                 if (rc == 0)
301                         repbody->valid |= OBD_MD_FLMDSCAPA;
302         }
303         EXIT;
304 out:
305         mdt_thread_info_fini(info);
306         return rc;
307 }
308
309 static int mdt_statfs(struct tgt_session_info *tsi)
310 {
311         struct ptlrpc_request           *req = tgt_ses_req(tsi);
312         struct mdt_thread_info          *info = tsi2mdt_info(tsi);
313         struct md_device                *next = info->mti_mdt->mdt_child;
314         struct ptlrpc_service_part      *svcpt;
315         struct obd_statfs               *osfs;
316         int                             rc;
317
318         ENTRY;
319
320         svcpt = req->rq_rqbd->rqbd_svcpt;
321
322         /* This will trigger a watchdog timeout */
323         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_STATFS_LCW_SLEEP,
324                          (MDT_SERVICE_WATCHDOG_FACTOR *
325                           at_get(&svcpt->scp_at_estimate)) + 1);
326
327         rc = mdt_check_ucred(info);
328         if (rc)
329                 GOTO(out, rc = err_serious(rc));
330
331         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_STATFS_PACK))
332                 GOTO(out, rc = err_serious(-ENOMEM));
333
334         osfs = req_capsule_server_get(info->mti_pill, &RMF_OBD_STATFS);
335         if (!osfs)
336                 GOTO(out, rc = -EPROTO);
337
338         /** statfs information are cached in the mdt_device */
339         if (cfs_time_before_64(info->mti_mdt->mdt_osfs_age,
340                                cfs_time_shift_64(-OBD_STATFS_CACHE_SECONDS))) {
341                 /** statfs data is too old, get up-to-date one */
342                 rc = next->md_ops->mdo_statfs(info->mti_env, next, osfs);
343                 if (rc)
344                         GOTO(out, rc);
345                 spin_lock(&info->mti_mdt->mdt_osfs_lock);
346                 info->mti_mdt->mdt_osfs = *osfs;
347                 info->mti_mdt->mdt_osfs_age = cfs_time_current_64();
348                 spin_unlock(&info->mti_mdt->mdt_osfs_lock);
349         } else {
350                 /** use cached statfs data */
351                 spin_lock(&info->mti_mdt->mdt_osfs_lock);
352                 *osfs = info->mti_mdt->mdt_osfs;
353                 spin_unlock(&info->mti_mdt->mdt_osfs_lock);
354         }
355
356         if (rc == 0)
357                 mdt_counter_incr(req, LPROC_MDT_STATFS);
358 out:
359         mdt_thread_info_fini(info);
360         RETURN(rc);
361 }
362
363 /**
364  * Pack SOM attributes into the reply.
365  * Call under a DLM UPDATE lock.
366  */
367 static void mdt_pack_size2body(struct mdt_thread_info *info,
368                                struct mdt_object *mo)
369 {
370         struct mdt_body *b;
371         struct md_attr *ma = &info->mti_attr;
372
373         LASSERT(ma->ma_attr.la_valid & LA_MODE);
374         b = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
375
376         /* Check if Size-on-MDS is supported, if this is a regular file,
377          * if SOM is enabled on the object and if SOM cache exists and valid.
378          * Otherwise do not pack Size-on-MDS attributes to the reply. */
379         if (!(mdt_conn_flags(info) & OBD_CONNECT_SOM) ||
380             !S_ISREG(ma->ma_attr.la_mode) ||
381             !mdt_object_is_som_enabled(mo) ||
382             !(ma->ma_valid & MA_SOM))
383                 return;
384
385         b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
386         b->size = ma->ma_som->msd_size;
387         b->blocks = ma->ma_som->msd_blocks;
388 }
389
390 void mdt_pack_attr2body(struct mdt_thread_info *info, struct mdt_body *b,
391                         const struct lu_attr *attr, const struct lu_fid *fid)
392 {
393         struct md_attr *ma = &info->mti_attr;
394
395         LASSERT(ma->ma_valid & MA_INODE);
396
397         b->atime      = attr->la_atime;
398         b->mtime      = attr->la_mtime;
399         b->ctime      = attr->la_ctime;
400         b->mode       = attr->la_mode;
401         b->size       = attr->la_size;
402         b->blocks     = attr->la_blocks;
403         b->uid        = attr->la_uid;
404         b->gid        = attr->la_gid;
405         b->flags      = attr->la_flags;
406         b->nlink      = attr->la_nlink;
407         b->rdev       = attr->la_rdev;
408
409         /*XXX should pack the reply body according to lu_valid*/
410         b->valid |= OBD_MD_FLCTIME | OBD_MD_FLUID   |
411                     OBD_MD_FLGID   | OBD_MD_FLTYPE  |
412                     OBD_MD_FLMODE  | OBD_MD_FLNLINK | OBD_MD_FLFLAGS |
413                     OBD_MD_FLATIME | OBD_MD_FLMTIME ;
414
415         if (!S_ISREG(attr->la_mode)) {
416                 b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS | OBD_MD_FLRDEV;
417         } else if (ma->ma_need & MA_LOV && !(ma->ma_valid & MA_LOV)) {
418                 /* means no objects are allocated on osts. */
419                 LASSERT(!(ma->ma_valid & MA_LOV));
420                 /* just ignore blocks occupied by extend attributes on MDS */
421                 b->blocks = 0;
422                 /* if no object is allocated on osts, the size on mds is valid. b=22272 */
423                 b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
424         } else if ((ma->ma_valid & MA_LOV) && ma->ma_lmm != NULL &&
425                    ma->ma_lmm->lmm_pattern & LOV_PATTERN_F_RELEASED) {
426                 /* A released file stores its size on MDS. */
427                 /* But return 1 block for released file, unless tools like tar
428                  * will consider it fully sparse. (LU-3864)
429                  */
430                 if (unlikely(b->size == 0))
431                         b->blocks = 0;
432                 else
433                         b->blocks = 1;
434                 b->valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
435         }
436
437         if (fid) {
438                 b->fid1 = *fid;
439                 b->valid |= OBD_MD_FLID;
440                 CDEBUG(D_INODE, DFID": nlink=%d, mode=%o, size="LPU64"\n",
441                                 PFID(fid), b->nlink, b->mode, b->size);
442         }
443
444         if (info)
445                 mdt_body_reverse_idmap(info, b);
446
447         if (fid != NULL && (b->valid & OBD_MD_FLSIZE))
448                 CDEBUG(D_VFSTRACE, DFID": returning size %llu\n",
449                        PFID(fid), (unsigned long long)b->size);
450 }
451
452 static inline int mdt_body_has_lov(const struct lu_attr *la,
453                                    const struct mdt_body *body)
454 {
455         return ((S_ISREG(la->la_mode) && (body->valid & OBD_MD_FLEASIZE)) ||
456                 (S_ISDIR(la->la_mode) && (body->valid & OBD_MD_FLDIREA )) );
457 }
458
459 void mdt_client_compatibility(struct mdt_thread_info *info)
460 {
461         struct mdt_body       *body;
462         struct ptlrpc_request *req = mdt_info_req(info);
463         struct obd_export     *exp = req->rq_export;
464         struct md_attr        *ma = &info->mti_attr;
465         struct lu_attr        *la = &ma->ma_attr;
466         ENTRY;
467
468         if (exp_connect_layout(exp))
469                 /* the client can deal with 16-bit lmm_stripe_count */
470                 RETURN_EXIT;
471
472         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
473
474         if (!mdt_body_has_lov(la, body))
475                 RETURN_EXIT;
476
477         /* now we have a reply with a lov for a client not compatible with the
478          * layout lock so we have to clean the layout generation number */
479         if (S_ISREG(la->la_mode))
480                 ma->ma_lmm->lmm_layout_gen = 0;
481         EXIT;
482 }
483
484 int mdt_attr_get_eabuf_size(struct mdt_thread_info *info, struct mdt_object *o)
485 {
486         const struct lu_env *env = info->mti_env;
487         int rc, rc2;
488
489         rc = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL,
490                           XATTR_NAME_LOV);
491
492         if (rc == -ENODATA)
493                 rc = 0;
494
495         if (rc < 0)
496                 goto out;
497
498         /* Is it a directory? Let's check for the LMV as well */
499         if (S_ISDIR(lu_object_attr(&mdt_object_child(o)->mo_lu))) {
500                 rc2 = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL,
501                                    XATTR_NAME_LMV);
502                 if ((rc2 < 0 && rc2 != -ENODATA) || (rc2 > rc))
503                         rc = rc2;
504         }
505
506 out:
507         return rc;
508 }
509
510 static int mdt_big_xattr_get(struct mdt_thread_info *info, struct mdt_object *o,
511                              const char *name)
512 {
513         const struct lu_env *env = info->mti_env;
514         int rc;
515         ENTRY;
516
517         LASSERT(info->mti_big_lmm_used == 0);
518         rc = mo_xattr_get(env, mdt_object_child(o), &LU_BUF_NULL, name);
519         if (rc < 0)
520                 RETURN(rc);
521
522         /* big_lmm may need to be grown */
523         if (info->mti_big_lmmsize < rc) {
524                 int size = size_roundup_power2(rc);
525
526                 if (info->mti_big_lmmsize > 0) {
527                         /* free old buffer */
528                         LASSERT(info->mti_big_lmm);
529                         OBD_FREE_LARGE(info->mti_big_lmm,
530                                        info->mti_big_lmmsize);
531                         info->mti_big_lmm = NULL;
532                         info->mti_big_lmmsize = 0;
533                 }
534
535                 OBD_ALLOC_LARGE(info->mti_big_lmm, size);
536                 if (info->mti_big_lmm == NULL)
537                         RETURN(-ENOMEM);
538                 info->mti_big_lmmsize = size;
539         }
540         LASSERT(info->mti_big_lmmsize >= rc);
541
542         info->mti_buf.lb_buf = info->mti_big_lmm;
543         info->mti_buf.lb_len = info->mti_big_lmmsize;
544         rc = mo_xattr_get(env, mdt_object_child(o), &info->mti_buf, name);
545
546         RETURN(rc);
547 }
548
549 int mdt_stripe_get(struct mdt_thread_info *info, struct mdt_object *o,
550                    struct md_attr *ma, const char *name)
551 {
552         struct md_object *next = mdt_object_child(o);
553         struct lu_buf    *buf = &info->mti_buf;
554         int rc;
555
556         if (strcmp(name, XATTR_NAME_LOV) == 0) {
557                 buf->lb_buf = ma->ma_lmm;
558                 buf->lb_len = ma->ma_lmm_size;
559                 LASSERT(!(ma->ma_valid & MA_LOV));
560         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
561                 buf->lb_buf = ma->ma_lmv;
562                 buf->lb_len = ma->ma_lmv_size;
563                 LASSERT(!(ma->ma_valid & MA_LMV));
564         } else if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
565                 buf->lb_buf = ma->ma_lmv;
566                 buf->lb_len = ma->ma_lmv_size;
567                 LASSERT(!(ma->ma_valid & MA_LMV_DEF));
568         } else {
569                 return -EINVAL;
570         }
571
572         rc = mo_xattr_get(info->mti_env, next, buf, name);
573         if (rc > 0) {
574                 if (strcmp(name, XATTR_NAME_LOV) == 0) {
575                         ma->ma_lmm_size = rc;
576                         ma->ma_valid |= MA_LOV;
577                 } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
578                         ma->ma_lmv_size = rc;
579                         ma->ma_valid |= MA_LMV;
580                 } else if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0) {
581                         ma->ma_lmv_size = rc;
582                         ma->ma_valid |= MA_LMV_DEF;
583                 }
584
585                 rc = 0;
586         } else if (rc == -ENODATA) {
587                 /* no LOV EA */
588                 rc = 0;
589         } else if (rc == -ERANGE) {
590                 /* Default LMV has fixed size, so it must be able to fit
591                  * in the original buffer */
592                 if (strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
593                         return rc;
594                 rc = mdt_big_xattr_get(info, o, name);
595                 if (rc > 0) {
596                         info->mti_big_lmm_used = 1;
597                         if (!strcmp(name, XATTR_NAME_LOV)) {
598                                 ma->ma_valid |= MA_LOV;
599                                 ma->ma_lmm = info->mti_big_lmm;
600                                 ma->ma_lmm_size = rc;
601                         } else if (!strcmp(name, XATTR_NAME_LMV)) {
602                                 ma->ma_valid |= MA_LMV;
603                                 ma->ma_lmv = info->mti_big_lmm;
604                                 ma->ma_lmv_size = rc;
605                         } else {
606                                 return -EINVAL;
607                         }
608
609                         /* update mdt_max_mdsize so all clients
610                          * will be aware about that */
611                         if (info->mti_mdt->mdt_max_mdsize < rc)
612                                 info->mti_mdt->mdt_max_mdsize = rc;
613                         rc = 0;
614                 }
615         }
616
617         return rc;
618 }
619
620 static int mdt_attr_get_pfid(struct mdt_thread_info *info,
621                              struct mdt_object *o, struct lu_fid *pfid)
622 {
623         struct lu_buf           *buf = &info->mti_buf;
624         struct link_ea_header   *leh;
625         struct link_ea_entry    *lee;
626         int                      rc;
627         ENTRY;
628
629         buf->lb_buf = info->mti_big_lmm;
630         buf->lb_len = info->mti_big_lmmsize;
631         rc = mo_xattr_get(info->mti_env, mdt_object_child(o),
632                           buf, XATTR_NAME_LINK);
633         /* ignore errors, MA_PFID won't be set and it is
634          * up to the caller to treat this as an error */
635         if (rc == -ERANGE || buf->lb_len == 0) {
636                 rc = mdt_big_xattr_get(info, o, XATTR_NAME_LINK);
637                 buf->lb_buf = info->mti_big_lmm;
638                 buf->lb_len = info->mti_big_lmmsize;
639         }
640
641         if (rc < 0)
642                 RETURN(rc);
643         if (rc < sizeof(*leh)) {
644                 CERROR("short LinkEA on "DFID": rc = %d\n",
645                        PFID(mdt_object_fid(o)), rc);
646                 RETURN(-ENODATA);
647         }
648
649         leh = (struct link_ea_header *) buf->lb_buf;
650         lee = (struct link_ea_entry *)(leh + 1);
651         if (leh->leh_magic == __swab32(LINK_EA_MAGIC)) {
652                 leh->leh_magic = LINK_EA_MAGIC;
653                 leh->leh_reccount = __swab32(leh->leh_reccount);
654                 leh->leh_len = __swab64(leh->leh_len);
655         }
656         if (leh->leh_magic != LINK_EA_MAGIC)
657                 RETURN(-EINVAL);
658         if (leh->leh_reccount == 0)
659                 RETURN(-ENODATA);
660
661         memcpy(pfid, &lee->lee_parent_fid, sizeof(*pfid));
662         fid_be_to_cpu(pfid, pfid);
663
664         RETURN(0);
665 }
666
667 int mdt_attr_get_complex(struct mdt_thread_info *info,
668                          struct mdt_object *o, struct md_attr *ma)
669 {
670         const struct lu_env *env = info->mti_env;
671         struct md_object    *next = mdt_object_child(o);
672         struct lu_buf       *buf = &info->mti_buf;
673         u32                  mode = lu_object_attr(&next->mo_lu);
674         int                  need = ma->ma_need;
675         int                  rc = 0, rc2;
676         ENTRY;
677
678         ma->ma_valid = 0;
679
680         if (need & MA_INODE) {
681                 ma->ma_need = MA_INODE;
682                 rc = mo_attr_get(env, next, ma);
683                 if (rc)
684                         GOTO(out, rc);
685                 ma->ma_valid |= MA_INODE;
686         }
687
688         if (need & MA_PFID) {
689                 rc = mdt_attr_get_pfid(info, o, &ma->ma_pfid);
690                 if (rc == 0)
691                         ma->ma_valid |= MA_PFID;
692                 /* ignore this error, parent fid is not mandatory */
693                 rc = 0;
694         }
695
696         if (need & MA_LOV && (S_ISREG(mode) || S_ISDIR(mode))) {
697                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_LOV);
698                 if (rc)
699                         GOTO(out, rc);
700         }
701
702         if (need & MA_LMV && S_ISDIR(mode)) {
703                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_LMV);
704                 if (rc != 0)
705                         GOTO(out, rc);
706         }
707
708         if (need & MA_LMV_DEF && S_ISDIR(mode)) {
709                 rc = mdt_stripe_get(info, o, ma, XATTR_NAME_DEFAULT_LMV);
710                 if (rc != 0)
711                         GOTO(out, rc);
712         }
713
714         if (need & MA_SOM && S_ISREG(mode)) {
715                 buf->lb_buf = info->mti_xattr_buf;
716                 buf->lb_len = sizeof(info->mti_xattr_buf);
717                 CLASSERT(sizeof(struct som_attrs) <=
718                          sizeof(info->mti_xattr_buf));
719                 rc2 = mo_xattr_get(info->mti_env, next, buf, XATTR_NAME_SOM);
720                 rc2 = lustre_buf2som(info->mti_xattr_buf, rc2, ma->ma_som);
721                 if (rc2 == 0)
722                         ma->ma_valid |= MA_SOM;
723                 else if (rc2 < 0 && rc2 != -ENODATA)
724                         GOTO(out, rc = rc2);
725         }
726
727         if (need & MA_HSM && S_ISREG(mode)) {
728                 buf->lb_buf = info->mti_xattr_buf;
729                 buf->lb_len = sizeof(info->mti_xattr_buf);
730                 CLASSERT(sizeof(struct hsm_attrs) <=
731                          sizeof(info->mti_xattr_buf));
732                 rc2 = mo_xattr_get(info->mti_env, next, buf, XATTR_NAME_HSM);
733                 rc2 = lustre_buf2hsm(info->mti_xattr_buf, rc2, &ma->ma_hsm);
734                 if (rc2 == 0)
735                         ma->ma_valid |= MA_HSM;
736                 else if (rc2 < 0 && rc2 != -ENODATA)
737                         GOTO(out, rc = rc2);
738         }
739
740 #ifdef CONFIG_FS_POSIX_ACL
741         if (need & MA_ACL_DEF && S_ISDIR(mode)) {
742                 buf->lb_buf = ma->ma_acl;
743                 buf->lb_len = ma->ma_acl_size;
744                 rc2 = mo_xattr_get(env, next, buf, XATTR_NAME_ACL_DEFAULT);
745                 if (rc2 > 0) {
746                         ma->ma_acl_size = rc2;
747                         ma->ma_valid |= MA_ACL_DEF;
748                 } else if (rc2 == -ENODATA) {
749                         /* no ACLs */
750                         ma->ma_acl_size = 0;
751                 } else
752                         GOTO(out, rc = rc2);
753         }
754 #endif
755 out:
756         ma->ma_need = need;
757         CDEBUG(D_INODE, "after getattr rc = %d, ma_valid = "LPX64" ma_lmm=%p\n",
758                rc, ma->ma_valid, ma->ma_lmm);
759         RETURN(rc);
760 }
761
762 static int mdt_getattr_internal(struct mdt_thread_info *info,
763                                 struct mdt_object *o, int ma_need)
764 {
765         struct md_object        *next = mdt_object_child(o);
766         const struct mdt_body   *reqbody = info->mti_body;
767         struct ptlrpc_request   *req = mdt_info_req(info);
768         struct md_attr          *ma = &info->mti_attr;
769         struct lu_attr          *la = &ma->ma_attr;
770         struct req_capsule      *pill = info->mti_pill;
771         const struct lu_env     *env = info->mti_env;
772         struct mdt_body         *repbody;
773         struct lu_buf           *buffer = &info->mti_buf;
774         int                     rc;
775         int                     is_root;
776         ENTRY;
777
778         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_GETATTR_PACK))
779                 RETURN(err_serious(-ENOMEM));
780
781         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
782
783         ma->ma_valid = 0;
784
785         if (mdt_object_remote(o)) {
786                 /* This object is located on remote node.*/
787                 /* Return -EIO for old client */
788                 if (!mdt_is_dne_client(req->rq_export))
789                         GOTO(out, rc = -EIO);
790
791                 repbody->fid1 = *mdt_object_fid(o);
792                 repbody->valid = OBD_MD_FLID | OBD_MD_MDS;
793                 GOTO(out, rc = 0);
794         }
795
796         if (reqbody->eadatasize > 0) {
797                 buffer->lb_buf = req_capsule_server_get(pill, &RMF_MDT_MD);
798                 if (buffer->lb_buf == NULL)
799                         GOTO(out, rc = -EPROTO);
800                 buffer->lb_len = req_capsule_get_size(pill, &RMF_MDT_MD,
801                                                       RCL_SERVER);
802         } else {
803                 buffer->lb_buf = NULL;
804                 buffer->lb_len = 0;
805                 ma_need &= ~(MA_LOV | MA_LMV);
806                 CDEBUG(D_INFO, "%s: RPC from %s: does not need LOVEA.\n",
807                        mdt_obd_name(info->mti_mdt),
808                        req->rq_export->exp_client_uuid.uuid);
809         }
810
811         /* If it is dir object and client require MEA, then we got MEA */
812         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
813             (reqbody->valid & (OBD_MD_MEA | OBD_MD_DEFAULT_MEA))) {
814                 /* Assumption: MDT_MD size is enough for lmv size. */
815                 ma->ma_lmv = buffer->lb_buf;
816                 ma->ma_lmv_size = buffer->lb_len;
817                 ma->ma_need = MA_INODE;
818                 if (ma->ma_lmv_size > 0) {
819                         if (reqbody->valid & OBD_MD_MEA)
820                                 ma->ma_need |= MA_LMV;
821                         else if (reqbody->valid & OBD_MD_DEFAULT_MEA)
822                                 ma->ma_need |= MA_LMV_DEF;
823                 }
824         } else {
825                 ma->ma_lmm = buffer->lb_buf;
826                 ma->ma_lmm_size = buffer->lb_len;
827                 ma->ma_need = MA_INODE | MA_HSM;
828                 if (ma->ma_lmm_size > 0)
829                         ma->ma_need |= MA_LOV;
830         }
831
832         if (S_ISDIR(lu_object_attr(&next->mo_lu)) &&
833             reqbody->valid & OBD_MD_FLDIREA  &&
834             lustre_msg_get_opc(req->rq_reqmsg) == MDS_GETATTR) {
835                 /* get default stripe info for this dir. */
836                 ma->ma_need |= MA_LOV_DEF;
837         }
838         ma->ma_need |= ma_need;
839         if (ma->ma_need & MA_SOM)
840                 ma->ma_som = &info->mti_u.som.data;
841
842         rc = mdt_attr_get_complex(info, o, ma);
843         if (unlikely(rc)) {
844                 CERROR("%s: getattr error for "DFID": rc = %d\n",
845                        mdt_obd_name(info->mti_mdt),
846                        PFID(mdt_object_fid(o)), rc);
847                 RETURN(rc);
848         }
849
850         /* if file is released, check if a restore is running */
851         if ((ma->ma_valid & MA_HSM) && (ma->ma_hsm.mh_flags & HS_RELEASED) &&
852             mdt_hsm_restore_is_running(info, mdt_object_fid(o))) {
853                 repbody->t_state = MS_RESTORE;
854                 repbody->valid |= OBD_MD_TSTATE;
855         }
856
857         is_root = lu_fid_eq(mdt_object_fid(o), &info->mti_mdt->mdt_md_root_fid);
858
859         /* the Lustre protocol supposes to return default striping
860          * on the user-visible root if explicitly requested */
861         if ((ma->ma_valid & MA_LOV) == 0 && S_ISDIR(la->la_mode) &&
862             (ma->ma_need & MA_LOV_DEF && is_root) && ma->ma_need & MA_LOV) {
863                 struct lu_fid      rootfid;
864                 struct mdt_object *root;
865                 struct mdt_device *mdt = info->mti_mdt;
866
867                 rc = dt_root_get(env, mdt->mdt_bottom, &rootfid);
868                 if (rc)
869                         RETURN(rc);
870                 root = mdt_object_find(env, mdt, &rootfid);
871                 if (IS_ERR(root))
872                         RETURN(PTR_ERR(root));
873                 rc = mdt_stripe_get(info, root, ma, XATTR_NAME_LOV);
874                 mdt_object_put(info->mti_env, root);
875                 if (unlikely(rc)) {
876                         CERROR("%s: getattr error for "DFID": rc = %d\n",
877                                mdt_obd_name(info->mti_mdt),
878                                PFID(mdt_object_fid(o)), rc);
879                         RETURN(rc);
880                 }
881         }
882
883         if (likely(ma->ma_valid & MA_INODE))
884                 mdt_pack_attr2body(info, repbody, la, mdt_object_fid(o));
885         else
886                 RETURN(-EFAULT);
887
888         if (mdt_body_has_lov(la, reqbody)) {
889                 if (ma->ma_valid & MA_LOV) {
890                         LASSERT(ma->ma_lmm_size);
891                         repbody->eadatasize = ma->ma_lmm_size;
892                         if (S_ISDIR(la->la_mode))
893                                 repbody->valid |= OBD_MD_FLDIREA;
894                         else
895                                 repbody->valid |= OBD_MD_FLEASIZE;
896                         mdt_dump_lmm(D_INFO, ma->ma_lmm, repbody->valid);
897                 }
898                 if (ma->ma_valid & MA_LMV) {
899                         LASSERT(S_ISDIR(la->la_mode));
900                         mdt_dump_lmv(D_INFO, ma->ma_lmv);
901                         repbody->eadatasize = ma->ma_lmv_size;
902                         repbody->valid |= (OBD_MD_FLDIREA|OBD_MD_MEA);
903                 }
904                 if (ma->ma_valid & MA_LMV_DEF) {
905                         LASSERT(S_ISDIR(la->la_mode));
906                         repbody->eadatasize = ma->ma_lmv_size;
907                         repbody->valid |= (OBD_MD_FLDIREA|OBD_MD_DEFAULT_MEA);
908                 }
909         } else if (S_ISLNK(la->la_mode) &&
910                    reqbody->valid & OBD_MD_LINKNAME) {
911                 buffer->lb_buf = ma->ma_lmm;
912                 /* eadatasize from client includes NULL-terminator, so
913                  * there is no need to read it */
914                 buffer->lb_len = reqbody->eadatasize - 1;
915                 rc = mo_readlink(env, next, buffer);
916                 if (unlikely(rc <= 0)) {
917                         CERROR("%s: readlink failed for "DFID": rc = %d\n",
918                                mdt_obd_name(info->mti_mdt),
919                                PFID(mdt_object_fid(o)), rc);
920                         rc = -EFAULT;
921                 } else {
922                         int print_limit = min_t(int, PAGE_CACHE_SIZE - 128, rc);
923
924                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READLINK_EPROTO))
925                                 rc -= 2;
926                         repbody->valid |= OBD_MD_LINKNAME;
927                         /* we need to report back size with NULL-terminator
928                          * because client expects that */
929                         repbody->eadatasize = rc + 1;
930                         if (repbody->eadatasize != reqbody->eadatasize)
931                                 CDEBUG(D_INODE, "%s: Read shorter symlink %d "
932                                        "on "DFID ", expected %d\n",
933                                        mdt_obd_name(info->mti_mdt),
934                                        rc, PFID(mdt_object_fid(o)),
935                                        reqbody->eadatasize - 1);
936                         /* NULL terminate */
937                         ((char *)ma->ma_lmm)[rc] = 0;
938
939                         /* If the total CDEBUG() size is larger than a page, it
940                          * will print a warning to the console, avoid this by
941                          * printing just the last part of the symlink. */
942                         CDEBUG(D_INODE, "symlink dest %s%.*s, len = %d\n",
943                                print_limit < rc ? "..." : "", print_limit,
944                                (char *)ma->ma_lmm + rc - print_limit, rc);
945                         rc = 0;
946                 }
947         }
948
949         if (reqbody->valid & OBD_MD_FLMODEASIZE) {
950                 repbody->max_cookiesize = 0;
951                 repbody->max_mdsize = info->mti_mdt->mdt_max_mdsize;
952                 repbody->valid |= OBD_MD_FLMODEASIZE;
953                 CDEBUG(D_INODE, "I am going to change the MAX_MD_SIZE & "
954                        "MAX_COOKIE to : %d:%d\n", repbody->max_mdsize,
955                        repbody->max_cookiesize);
956         }
957
958         if (exp_connect_rmtclient(info->mti_exp) &&
959             reqbody->valid & OBD_MD_FLRMTPERM) {
960                 void *buf = req_capsule_server_get(pill, &RMF_ACL);
961
962                 /* mdt_getattr_lock only */
963                 rc = mdt_pack_remote_perm(info, o, buf);
964                 if (rc) {
965                         repbody->valid &= ~OBD_MD_FLRMTPERM;
966                         repbody->aclsize = 0;
967                         RETURN(rc);
968                 } else {
969                         repbody->valid |= OBD_MD_FLRMTPERM;
970                         repbody->aclsize = sizeof(struct mdt_remote_perm);
971                 }
972         }
973 #ifdef CONFIG_FS_POSIX_ACL
974         else if ((exp_connect_flags(req->rq_export) & OBD_CONNECT_ACL) &&
975                  (reqbody->valid & OBD_MD_FLACL)) {
976                 buffer->lb_buf = req_capsule_server_get(pill, &RMF_ACL);
977                 buffer->lb_len = req_capsule_get_size(pill,
978                                                       &RMF_ACL, RCL_SERVER);
979                 if (buffer->lb_len > 0) {
980                         rc = mo_xattr_get(env, next, buffer,
981                                           XATTR_NAME_ACL_ACCESS);
982                         if (rc < 0) {
983                                 if (rc == -ENODATA) {
984                                         repbody->aclsize = 0;
985                                         repbody->valid |= OBD_MD_FLACL;
986                                         rc = 0;
987                                 } else if (rc == -EOPNOTSUPP) {
988                                         rc = 0;
989                                 } else {
990                                         CERROR("%s: unable to read "DFID
991                                                " ACL: rc = %d\n",
992                                                mdt_obd_name(info->mti_mdt),
993                                                PFID(mdt_object_fid(o)), rc);
994                                 }
995                         } else {
996                                 repbody->aclsize = rc;
997                                 repbody->valid |= OBD_MD_FLACL;
998                                 rc = 0;
999                         }
1000                 }
1001         }
1002 #endif
1003
1004         if (reqbody->valid & OBD_MD_FLMDSCAPA &&
1005             info->mti_mdt->mdt_lut.lut_mds_capa &&
1006             exp_connect_flags(info->mti_exp) & OBD_CONNECT_MDS_CAPA) {
1007                 struct lustre_capa *capa;
1008
1009                 capa = req_capsule_server_get(pill, &RMF_CAPA1);
1010                 LASSERT(capa);
1011                 capa->lc_opc = CAPA_OPC_MDS_DEFAULT;
1012                 rc = mo_capa_get(env, next, capa, 0);
1013                 if (rc)
1014                         RETURN(rc);
1015                 repbody->valid |= OBD_MD_FLMDSCAPA;
1016         }
1017
1018 out:
1019         if (rc == 0)
1020                 mdt_counter_incr(req, LPROC_MDT_GETATTR);
1021
1022         RETURN(rc);
1023 }
1024
1025 static int mdt_renew_capa(struct mdt_thread_info *info)
1026 {
1027         struct mdt_object  *obj = info->mti_object;
1028         struct mdt_body    *body;
1029         struct lustre_capa *capa, *c;
1030         int rc;
1031         ENTRY;
1032
1033         /* if object doesn't exist, or server has disabled capability,
1034          * return directly, client will find body->valid OBD_MD_FLOSSCAPA
1035          * flag not set.
1036          */
1037         if (!obj || !info->mti_mdt->mdt_lut.lut_oss_capa ||
1038             !(exp_connect_flags(info->mti_exp) & OBD_CONNECT_OSS_CAPA))
1039                 RETURN(0);
1040
1041         body = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1042         LASSERT(body != NULL);
1043
1044         c = req_capsule_client_get(info->mti_pill, &RMF_CAPA1);
1045         LASSERT(c);
1046
1047         capa = req_capsule_server_get(info->mti_pill, &RMF_CAPA2);
1048         LASSERT(capa);
1049
1050         *capa = *c;
1051         rc = mo_capa_get(info->mti_env, mdt_object_child(obj), capa, 1);
1052         if (rc == 0)
1053                 body->valid |= OBD_MD_FLOSSCAPA;
1054         RETURN(rc);
1055 }
1056
1057 static int mdt_getattr(struct tgt_session_info *tsi)
1058 {
1059         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
1060         struct mdt_object       *obj = info->mti_object;
1061         struct req_capsule      *pill = info->mti_pill;
1062         struct mdt_body         *reqbody;
1063         struct mdt_body         *repbody;
1064         int rc, rc2;
1065         ENTRY;
1066
1067         reqbody = req_capsule_client_get(pill, &RMF_MDT_BODY);
1068         LASSERT(reqbody);
1069
1070         if (reqbody->valid & OBD_MD_FLOSSCAPA) {
1071                 rc = req_capsule_server_pack(pill);
1072                 if (unlikely(rc))
1073                         RETURN(err_serious(rc));
1074                 rc = mdt_renew_capa(info);
1075                 GOTO(out_shrink, rc);
1076         }
1077
1078         LASSERT(obj != NULL);
1079         LASSERT(lu_object_assert_exists(&obj->mot_obj));
1080
1081         /* Readlink */
1082         if (reqbody->valid & OBD_MD_LINKNAME) {
1083                 /* No easy way to know how long is the symlink, but it cannot
1084                  * be more than PATH_MAX, so we allocate +1 */
1085                 rc = PATH_MAX + 1;
1086
1087         /* A special case for fs ROOT: getattr there might fetch
1088          * default EA for entire fs, not just for this dir!
1089          */
1090         } else if (lu_fid_eq(mdt_object_fid(obj),
1091                              &info->mti_mdt->mdt_md_root_fid) &&
1092                    (reqbody->valid & OBD_MD_FLDIREA) &&
1093                    (lustre_msg_get_opc(mdt_info_req(info)->rq_reqmsg) ==
1094                                                                  MDS_GETATTR)) {
1095                 /* Should the default strping be bigger, mdt_fix_reply
1096                  * will reallocate */
1097                 rc = DEF_REP_MD_SIZE;
1098         } else {
1099                 /* Hopefully no race in EA change for either file or directory?
1100                  */
1101                 rc = mdt_attr_get_eabuf_size(info, obj);
1102         }
1103
1104         if (rc < 0)
1105                 GOTO(out_shrink, rc);
1106
1107         /* old clients may not report needed easize, use max value then */
1108         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, rc);
1109
1110         rc = req_capsule_server_pack(pill);
1111         if (unlikely(rc != 0))
1112                 GOTO(out, rc = err_serious(rc));
1113
1114         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1115         LASSERT(repbody != NULL);
1116         repbody->eadatasize = 0;
1117         repbody->aclsize = 0;
1118
1119         if (reqbody->valid & OBD_MD_FLRMTPERM)
1120                 rc = mdt_init_ucred(info, reqbody);
1121         else
1122                 rc = mdt_check_ucred(info);
1123         if (unlikely(rc))
1124                 GOTO(out_shrink, rc);
1125
1126         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
1127
1128         /*
1129          * Don't check capability at all, because rename might getattr for
1130          * remote obj, and at that time no capability is available.
1131          */
1132         mdt_set_capainfo(info, 1, &reqbody->fid1, BYPASS_CAPA);
1133         rc = mdt_getattr_internal(info, obj, 0);
1134         if (reqbody->valid & OBD_MD_FLRMTPERM)
1135                 mdt_exit_ucred(info);
1136         EXIT;
1137 out_shrink:
1138         mdt_client_compatibility(info);
1139         rc2 = mdt_fix_reply(info);
1140         if (rc == 0)
1141                 rc = rc2;
1142 out:
1143         mdt_thread_info_fini(info);
1144         return rc;
1145 }
1146
1147 static int mdt_is_subdir(struct tgt_session_info *tsi)
1148 {
1149         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
1150         struct mdt_object     *o = info->mti_object;
1151         struct req_capsule    *pill = info->mti_pill;
1152         const struct mdt_body *body = info->mti_body;
1153         struct mdt_body       *repbody;
1154         int                    rc;
1155         ENTRY;
1156
1157         LASSERT(o != NULL);
1158
1159         repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1160
1161         /*
1162          * We save last checked parent fid to @repbody->fid1 for remote
1163          * directory case.
1164          */
1165         LASSERT(fid_is_sane(&body->fid2));
1166         LASSERT(mdt_object_exists(o) && !mdt_object_remote(o));
1167         rc = mdo_is_subdir(info->mti_env, mdt_object_child(o),
1168                            &body->fid2, &repbody->fid1);
1169         if (rc == 0 || rc == -EREMOTE)
1170                 repbody->valid |= OBD_MD_FLID;
1171
1172         mdt_thread_info_fini(info);
1173         RETURN(rc);
1174 }
1175
1176 static int mdt_swap_layouts(struct tgt_session_info *tsi)
1177 {
1178         struct mdt_thread_info  *info;
1179         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1180         struct obd_export       *exp = req->rq_export;
1181         struct mdt_object       *o1, *o2, *o;
1182         struct mdt_lock_handle  *lh1, *lh2;
1183         struct mdc_swap_layouts *msl;
1184         int                      rc;
1185         ENTRY;
1186
1187         /* client does not support layout lock, so layout swaping
1188          * is disabled.
1189          * FIXME: there is a problem for old clients which don't support
1190          * layout lock yet. If those clients have already opened the file
1191          * they won't be notified at all so that old layout may still be
1192          * used to do IO. This can be fixed after file release is landed by
1193          * doing exclusive open and taking full EX ibits lock. - Jinshan */
1194         if (!exp_connect_layout(exp))
1195                 RETURN(-EOPNOTSUPP);
1196
1197         info = tsi2mdt_info(tsi);
1198
1199         if (info->mti_dlm_req != NULL)
1200                 ldlm_request_cancel(req, info->mti_dlm_req, 0);
1201
1202         if (req_capsule_get_size(info->mti_pill, &RMF_CAPA1, RCL_CLIENT))
1203                 mdt_set_capainfo(info, 0, &info->mti_body->fid1,
1204                                  req_capsule_client_get(info->mti_pill,
1205                                                         &RMF_CAPA1));
1206
1207         if (req_capsule_get_size(info->mti_pill, &RMF_CAPA2, RCL_CLIENT))
1208                 mdt_set_capainfo(info, 1, &info->mti_body->fid2,
1209                                  req_capsule_client_get(info->mti_pill,
1210                                                         &RMF_CAPA2));
1211
1212         o1 = info->mti_object;
1213         o = o2 = mdt_object_find(info->mti_env, info->mti_mdt,
1214                                 &info->mti_body->fid2);
1215         if (IS_ERR(o))
1216                 GOTO(out, rc = PTR_ERR(o));
1217
1218         if (mdt_object_remote(o) || !mdt_object_exists(o)) /* remote object */
1219                 GOTO(put, rc = -ENOENT);
1220
1221         rc = lu_fid_cmp(&info->mti_body->fid1, &info->mti_body->fid2);
1222         if (unlikely(rc == 0)) /* same file, you kidding me? no-op. */
1223                 GOTO(put, rc);
1224
1225         if (rc < 0)
1226                 swap(o1, o2);
1227
1228         /* permission check. Make sure the calling process having permission
1229          * to write both files. */
1230         rc = mo_permission(info->mti_env, NULL, mdt_object_child(o1), NULL,
1231                                 MAY_WRITE);
1232         if (rc < 0)
1233                 GOTO(put, rc);
1234
1235         rc = mo_permission(info->mti_env, NULL, mdt_object_child(o2), NULL,
1236                                 MAY_WRITE);
1237         if (rc < 0)
1238                 GOTO(put, rc);
1239
1240         msl = req_capsule_client_get(info->mti_pill, &RMF_SWAP_LAYOUTS);
1241         if (msl == NULL)
1242                 GOTO(put, rc = -EPROTO);
1243
1244         lh1 = &info->mti_lh[MDT_LH_NEW];
1245         mdt_lock_reg_init(lh1, LCK_EX);
1246         lh2 = &info->mti_lh[MDT_LH_OLD];
1247         mdt_lock_reg_init(lh2, LCK_EX);
1248
1249         rc = mdt_object_lock(info, o1, lh1, MDS_INODELOCK_LAYOUT |
1250                              MDS_INODELOCK_XATTR, MDT_LOCAL_LOCK);
1251         if (rc < 0)
1252                 GOTO(put, rc);
1253
1254         rc = mdt_object_lock(info, o2, lh2, MDS_INODELOCK_LAYOUT |
1255                              MDS_INODELOCK_XATTR, MDT_LOCAL_LOCK);
1256         if (rc < 0)
1257                 GOTO(unlock1, rc);
1258
1259         rc = mo_swap_layouts(info->mti_env, mdt_object_child(o1),
1260                              mdt_object_child(o2), msl->msl_flags);
1261         GOTO(unlock2, rc);
1262 unlock2:
1263         mdt_object_unlock(info, o2, lh2, rc);
1264 unlock1:
1265         mdt_object_unlock(info, o1, lh1, rc);
1266 put:
1267         mdt_object_put(info->mti_env, o);
1268 out:
1269         mdt_thread_info_fini(info);
1270         RETURN(rc);
1271 }
1272
1273 static int mdt_raw_lookup(struct mdt_thread_info *info,
1274                           struct mdt_object *parent,
1275                           const struct lu_name *lname,
1276                           struct ldlm_reply *ldlm_rep)
1277 {
1278         struct md_object *next = mdt_object_child(info->mti_object);
1279         const struct mdt_body *reqbody = info->mti_body;
1280         struct lu_fid *child_fid = &info->mti_tmp_fid1;
1281         struct mdt_body *repbody;
1282         int rc;
1283         ENTRY;
1284
1285         if (reqbody->valid != OBD_MD_FLID)
1286                 RETURN(0);
1287
1288         LASSERT(!info->mti_cross_ref);
1289
1290         /* Only got the fid of this obj by name */
1291         fid_zero(child_fid);
1292         rc = mdo_lookup(info->mti_env, next, lname, child_fid,
1293                         &info->mti_spec);
1294 #if 0
1295         /* XXX is raw_lookup possible as intent operation? */
1296         if (rc != 0) {
1297                 if (rc == -ENOENT)
1298                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
1299                 RETURN(rc);
1300         } else
1301                 mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1302
1303         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1304 #endif
1305         if (rc == 0) {
1306                 repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1307                 repbody->fid1 = *child_fid;
1308                 repbody->valid = OBD_MD_FLID;
1309         }
1310         RETURN(1);
1311 }
1312
1313 /*
1314  * UPDATE lock should be taken against parent, and be release before exit;
1315  * child_bits lock should be taken against child, and be returned back:
1316  *            (1)normal request should release the child lock;
1317  *            (2)intent request will grant the lock to client.
1318  */
1319 static int mdt_getattr_name_lock(struct mdt_thread_info *info,
1320                                  struct mdt_lock_handle *lhc,
1321                                  __u64 child_bits,
1322                                  struct ldlm_reply *ldlm_rep)
1323 {
1324         struct ptlrpc_request  *req       = mdt_info_req(info);
1325         struct mdt_body        *reqbody   = NULL;
1326         struct mdt_object      *parent    = info->mti_object;
1327         struct mdt_object      *child;
1328         struct md_object       *next      = mdt_object_child(parent);
1329         struct lu_fid          *child_fid = &info->mti_tmp_fid1;
1330         struct lu_name         *lname     = NULL;
1331         struct mdt_lock_handle *lhp       = NULL;
1332         struct ldlm_lock       *lock;
1333         bool                    is_resent;
1334         bool                    try_layout;
1335         int                     ma_need = 0;
1336         int                     rc;
1337         ENTRY;
1338
1339         is_resent = lustre_handle_is_used(&lhc->mlh_reg_lh);
1340         LASSERT(ergo(is_resent,
1341                      lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT));
1342
1343         LASSERT(parent != NULL);
1344
1345         if (info->mti_cross_ref) {
1346                 /* Only getattr on the child. Parent is on another node. */
1347                 mdt_set_disposition(info, ldlm_rep,
1348                                     DISP_LOOKUP_EXECD | DISP_LOOKUP_POS);
1349                 child = parent;
1350                 CDEBUG(D_INODE, "partial getattr_name child_fid = "DFID", "
1351                        "ldlm_rep = %p\n",
1352                        PFID(mdt_object_fid(child)), ldlm_rep);
1353
1354                 if (is_resent) {
1355                         /* Do not take lock for resent case. */
1356                         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1357                         LASSERTF(lock != NULL, "Invalid lock handle "LPX64"\n",
1358                                  lhc->mlh_reg_lh.cookie);
1359                         LASSERT(fid_res_name_eq(mdt_object_fid(child),
1360                                                 &lock->l_resource->lr_name));
1361                         LDLM_LOCK_PUT(lock);
1362                 } else {
1363                         mdt_lock_handle_init(lhc);
1364                         mdt_lock_reg_init(lhc, LCK_PR);
1365
1366                         /*
1367                          * Object's name is on another MDS, no lookup or layout
1368                          * lock is needed here but update lock is.
1369                          */
1370                         child_bits &= ~(MDS_INODELOCK_LOOKUP |
1371                                         MDS_INODELOCK_LAYOUT);
1372                         child_bits |= MDS_INODELOCK_PERM | MDS_INODELOCK_UPDATE;
1373
1374                         rc = mdt_object_lock(info, child, lhc, child_bits,
1375                                              MDT_LOCAL_LOCK);
1376                         if (rc < 0)
1377                                 RETURN(rc);
1378                 }
1379
1380                 /* Finally, we can get attr for child. */
1381                 if (!mdt_object_exists(child)) {
1382                         LU_OBJECT_DEBUG(D_INFO, info->mti_env,
1383                                         &child->mot_obj,
1384                                         "remote object doesn't exist.\n");
1385                         mdt_object_unlock(info, child, lhc, 1);
1386                         RETURN(-ENOENT);
1387                 }
1388
1389                 mdt_set_capainfo(info, 0, mdt_object_fid(child), BYPASS_CAPA);
1390                 rc = mdt_getattr_internal(info, child, 0);
1391                 if (unlikely(rc != 0))
1392                         mdt_object_unlock(info, child, lhc, 1);
1393
1394                 RETURN(rc);
1395         }
1396
1397         lname = &info->mti_name;
1398         mdt_name_unpack(info->mti_pill, &RMF_NAME, lname, MNF_FIX_ANON);
1399
1400         if (lu_name_is_valid(lname)) {
1401                 CDEBUG(D_INODE, "getattr with lock for "DFID"/"DNAME", "
1402                        "ldlm_rep = %p\n", PFID(mdt_object_fid(parent)),
1403                        PNAME(lname), ldlm_rep);
1404         } else {
1405                 reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1406                 if (unlikely(reqbody == NULL))
1407                         RETURN(err_serious(-EPROTO));
1408
1409                 *child_fid = reqbody->fid2;
1410
1411                 if (unlikely(!fid_is_sane(child_fid)))
1412                         RETURN(err_serious(-EINVAL));
1413
1414                 CDEBUG(D_INODE, "getattr with lock for "DFID"/"DFID", "
1415                        "ldlm_rep = %p\n",
1416                        PFID(mdt_object_fid(parent)),
1417                        PFID(&reqbody->fid2), ldlm_rep);
1418         }
1419
1420         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_EXECD);
1421
1422         if (unlikely(!mdt_object_exists(parent)) && lu_name_is_valid(lname)) {
1423                 LU_OBJECT_DEBUG(D_INODE, info->mti_env,
1424                                 &parent->mot_obj,
1425                                 "Parent doesn't exist!\n");
1426                 RETURN(-ESTALE);
1427         }
1428
1429         if (mdt_object_remote(parent)) {
1430                 CERROR("%s: parent "DFID" is on remote target\n",
1431                        mdt_obd_name(info->mti_mdt),
1432                        PFID(mdt_object_fid(parent)));
1433                 RETURN(-EIO);
1434         }
1435
1436         if (lu_name_is_valid(lname)) {
1437                 rc = mdt_raw_lookup(info, parent, lname, ldlm_rep);
1438                 if (rc != 0) {
1439                         if (rc > 0)
1440                                 rc = 0;
1441                         RETURN(rc);
1442                 }
1443
1444                 /* step 1: lock parent only if parent is a directory */
1445                 if (S_ISDIR(lu_object_attr(&parent->mot_obj))) {
1446                         lhp = &info->mti_lh[MDT_LH_PARENT];
1447                         mdt_lock_pdo_init(lhp, LCK_PR, lname);
1448                         rc = mdt_object_lock(info, parent, lhp,
1449                                              MDS_INODELOCK_UPDATE,
1450                                              MDT_LOCAL_LOCK);
1451                         if (unlikely(rc != 0))
1452                                 RETURN(rc);
1453                 }
1454
1455                 /* step 2: lookup child's fid by name */
1456                 fid_zero(child_fid);
1457                 rc = mdo_lookup(info->mti_env, next, lname, child_fid,
1458                                 &info->mti_spec);
1459                 if (rc == -ENOENT)
1460                         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_NEG);
1461
1462                 if (rc != 0)
1463                         GOTO(out_parent, rc);
1464         }
1465
1466         mdt_set_disposition(info, ldlm_rep, DISP_LOOKUP_POS);
1467
1468         /*
1469          *step 3: find the child object by fid & lock it.
1470          *        regardless if it is local or remote.
1471          *
1472          *Note: LU-3240 (commit 762f2114d282a98ebfa4dbbeea9298a8088ad24e)
1473          *      set parent dir fid the same as child fid in getattr by fid case
1474          *      we should not lu_object_find() the object again, could lead
1475          *      to hung if there is a concurrent unlink destroyed the object.
1476          */
1477         if (lu_fid_eq(mdt_object_fid(parent), child_fid)) {
1478                 mdt_object_get(info->mti_env, parent);
1479                 child = parent;
1480         } else {
1481                 child = mdt_object_find(info->mti_env, info->mti_mdt,
1482                                         child_fid);
1483         }
1484
1485         if (unlikely(IS_ERR(child)))
1486                 GOTO(out_parent, rc = PTR_ERR(child));
1487         if (is_resent) {
1488                 /* Do not take lock for resent case. */
1489                 lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1490                 LASSERTF(lock != NULL, "Invalid lock handle "LPX64"\n",
1491                          lhc->mlh_reg_lh.cookie);
1492
1493                 if (!fid_res_name_eq(mdt_object_fid(child),
1494                                      &lock->l_resource->lr_name)) {
1495                         LASSERTF(fid_res_name_eq(mdt_object_fid(parent),
1496                                                  &lock->l_resource->lr_name),
1497                                  "Lock res_id: "DLDLMRES", fid: "DFID"\n",
1498                                  PLDLMRES(lock->l_resource),
1499                                  PFID(mdt_object_fid(parent)));
1500                         CWARN("Although resent, but still not get child lock"
1501                               "parent:"DFID" child:"DFID"\n",
1502                               PFID(mdt_object_fid(parent)),
1503                               PFID(mdt_object_fid(child)));
1504                         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
1505                         LDLM_LOCK_PUT(lock);
1506                         GOTO(relock, 0);
1507                 }
1508                 LDLM_LOCK_PUT(lock);
1509         } else {
1510 relock:
1511                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_RESEND, obd_timeout*2);
1512                 mdt_lock_handle_init(lhc);
1513                 mdt_lock_reg_init(lhc, LCK_PR);
1514                 try_layout = false;
1515
1516                 if (!mdt_object_exists(child)) {
1517                         LU_OBJECT_DEBUG(D_INODE, info->mti_env,
1518                                         &child->mot_obj,
1519                                         "Object doesn't exist!\n");
1520                         GOTO(out_child, rc = -ENOENT);
1521                 }
1522
1523                 if (!(child_bits & MDS_INODELOCK_UPDATE) &&
1524                       mdt_object_exists(child) && !mdt_object_remote(child)) {
1525                         struct md_attr *ma = &info->mti_attr;
1526
1527                         ma->ma_valid = 0;
1528                         ma->ma_need = MA_INODE;
1529                         rc = mdt_attr_get_complex(info, child, ma);
1530                         if (unlikely(rc != 0))
1531                                 GOTO(out_child, rc);
1532
1533                         /* If the file has not been changed for some time, we
1534                          * return not only a LOOKUP lock, but also an UPDATE
1535                          * lock and this might save us RPC on later STAT. For
1536                          * directories, it also let negative dentry cache start
1537                          * working for this dir. */
1538                         if (ma->ma_valid & MA_INODE &&
1539                             ma->ma_attr.la_valid & LA_CTIME &&
1540                             info->mti_mdt->mdt_namespace->ns_ctime_age_limit +
1541                                 ma->ma_attr.la_ctime < cfs_time_current_sec())
1542                                 child_bits |= MDS_INODELOCK_UPDATE;
1543                 }
1544
1545                 /* layout lock must be granted in a best-effort way
1546                  * for IT operations */
1547                 LASSERT(!(child_bits & MDS_INODELOCK_LAYOUT));
1548                 if (!OBD_FAIL_CHECK(OBD_FAIL_MDS_NO_LL_GETATTR) &&
1549                     exp_connect_layout(info->mti_exp) &&
1550                     S_ISREG(lu_object_attr(&child->mot_obj)) &&
1551                     !mdt_object_remote(child) && ldlm_rep != NULL) {
1552                         /* try to grant layout lock for regular file. */
1553                         try_layout = true;
1554                 }
1555
1556                 rc = 0;
1557                 if (try_layout) {
1558                         child_bits |= MDS_INODELOCK_LAYOUT;
1559                         /* try layout lock, it may fail to be granted due to
1560                          * contention at LOOKUP or UPDATE */
1561                         if (!mdt_object_lock_try(info, child, lhc, child_bits,
1562                                                  MDT_CROSS_LOCK)) {
1563                                 child_bits &= ~MDS_INODELOCK_LAYOUT;
1564                                 LASSERT(child_bits != 0);
1565                                 rc = mdt_object_lock(info, child, lhc,
1566                                                 child_bits, MDT_CROSS_LOCK);
1567                         } else {
1568                                 ma_need |= MA_LOV;
1569                         }
1570                 } else {
1571                         /* Do not enqueue the UPDATE lock from MDT(cross-MDT),
1572                          * client will enqueue the lock to the remote MDT */
1573                         if (mdt_object_remote(child))
1574                                 child_bits &= ~MDS_INODELOCK_UPDATE;
1575                         rc = mdt_object_lock(info, child, lhc, child_bits,
1576                                                 MDT_CROSS_LOCK);
1577                 }
1578                 if (unlikely(rc != 0))
1579                         GOTO(out_child, rc);
1580         }
1581
1582         lock = ldlm_handle2lock(&lhc->mlh_reg_lh);
1583         /* Get MA_SOM attributes if update lock is given. */
1584         if (lock &&
1585             lock->l_policy_data.l_inodebits.bits & MDS_INODELOCK_UPDATE &&
1586             S_ISREG(lu_object_attr(&mdt_object_child(child)->mo_lu)))
1587                 ma_need |= MA_SOM;
1588
1589         /* finally, we can get attr for child. */
1590         mdt_set_capainfo(info, 1, child_fid, BYPASS_CAPA);
1591         rc = mdt_getattr_internal(info, child, ma_need);
1592         if (unlikely(rc != 0)) {
1593                 mdt_object_unlock(info, child, lhc, 1);
1594         } else if (lock) {
1595                 /* Debugging code. */
1596                 LDLM_DEBUG(lock, "Returning lock to client");
1597                 LASSERTF(fid_res_name_eq(mdt_object_fid(child),
1598                                          &lock->l_resource->lr_name),
1599                          "Lock res_id: "DLDLMRES", fid: "DFID"\n",
1600                          PLDLMRES(lock->l_resource),
1601                          PFID(mdt_object_fid(child)));
1602                 if (mdt_object_exists(child) && !mdt_object_remote(child))
1603                         mdt_pack_size2body(info, child);
1604         }
1605         if (lock)
1606                 LDLM_LOCK_PUT(lock);
1607
1608         EXIT;
1609 out_child:
1610         mdt_object_put(info->mti_env, child);
1611 out_parent:
1612         if (lhp)
1613                 mdt_object_unlock(info, parent, lhp, 1);
1614         return rc;
1615 }
1616
1617 /* normal handler: should release the child lock */
1618 static int mdt_getattr_name(struct tgt_session_info *tsi)
1619 {
1620         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
1621         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_CHILD];
1622         struct mdt_body        *reqbody;
1623         struct mdt_body        *repbody;
1624         int rc, rc2;
1625         ENTRY;
1626
1627         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
1628         LASSERT(reqbody != NULL);
1629         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
1630         LASSERT(repbody != NULL);
1631
1632         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
1633         repbody->eadatasize = 0;
1634         repbody->aclsize = 0;
1635
1636         rc = mdt_init_ucred(info, reqbody);
1637         if (unlikely(rc))
1638                 GOTO(out_shrink, rc);
1639
1640         rc = mdt_getattr_name_lock(info, lhc, MDS_INODELOCK_UPDATE, NULL);
1641         if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
1642                 ldlm_lock_decref(&lhc->mlh_reg_lh, lhc->mlh_reg_mode);
1643                 lhc->mlh_reg_lh.cookie = 0;
1644         }
1645         mdt_exit_ucred(info);
1646         EXIT;
1647 out_shrink:
1648         mdt_client_compatibility(info);
1649         rc2 = mdt_fix_reply(info);
1650         if (rc == 0)
1651                 rc = rc2;
1652         mdt_thread_info_fini(info);
1653         return rc;
1654 }
1655
1656 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
1657                          void *karg, void *uarg);
1658
1659 static int mdt_set_info(struct tgt_session_info *tsi)
1660 {
1661         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1662         char                    *key;
1663         void                    *val;
1664         int                      keylen, vallen, rc = 0;
1665
1666         ENTRY;
1667
1668         key = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_KEY);
1669         if (key == NULL) {
1670                 DEBUG_REQ(D_HA, req, "no set_info key");
1671                 RETURN(err_serious(-EFAULT));
1672         }
1673
1674         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_KEY,
1675                                       RCL_CLIENT);
1676
1677         val = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_VAL);
1678         if (val == NULL) {
1679                 DEBUG_REQ(D_HA, req, "no set_info val");
1680                 RETURN(err_serious(-EFAULT));
1681         }
1682
1683         vallen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_VAL,
1684                                       RCL_CLIENT);
1685
1686         /* Swab any part of val you need to here */
1687         if (KEY_IS(KEY_READ_ONLY)) {
1688                 spin_lock(&req->rq_export->exp_lock);
1689                 if (*(__u32 *)val)
1690                         *exp_connect_flags_ptr(req->rq_export) |=
1691                                 OBD_CONNECT_RDONLY;
1692                 else
1693                         *exp_connect_flags_ptr(req->rq_export) &=
1694                                 ~OBD_CONNECT_RDONLY;
1695                 spin_unlock(&req->rq_export->exp_lock);
1696         } else if (KEY_IS(KEY_CHANGELOG_CLEAR)) {
1697                 struct changelog_setinfo *cs = val;
1698
1699                 if (vallen != sizeof(*cs)) {
1700                         CERROR("%s: bad changelog_clear setinfo size %d\n",
1701                                tgt_name(tsi->tsi_tgt), vallen);
1702                         RETURN(-EINVAL);
1703                 }
1704                 if (ptlrpc_req_need_swab(req)) {
1705                         __swab64s(&cs->cs_recno);
1706                         __swab32s(&cs->cs_id);
1707                 }
1708
1709                 rc = mdt_iocontrol(OBD_IOC_CHANGELOG_CLEAR, req->rq_export,
1710                                    vallen, val, NULL);
1711         } else {
1712                 RETURN(-EINVAL);
1713         }
1714         RETURN(rc);
1715 }
1716
1717 static int mdt_readpage(struct tgt_session_info *tsi)
1718 {
1719         struct mdt_thread_info  *info = mdt_th_info(tsi->tsi_env);
1720         struct mdt_object       *object = mdt_obj(tsi->tsi_corpus);
1721         struct lu_rdpg          *rdpg = &info->mti_u.rdpg.mti_rdpg;
1722         const struct mdt_body   *reqbody = tsi->tsi_mdt_body;
1723         struct mdt_body         *repbody;
1724         int                      rc;
1725         int                      i;
1726
1727         ENTRY;
1728
1729         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_READPAGE_PACK))
1730                 RETURN(err_serious(-ENOMEM));
1731
1732         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_MDT_BODY);
1733         if (repbody == NULL || reqbody == NULL)
1734                 RETURN(err_serious(-EFAULT));
1735
1736         /*
1737          * prepare @rdpg before calling lower layers and transfer itself. Here
1738          * reqbody->size contains offset of where to start to read and
1739          * reqbody->nlink contains number bytes to read.
1740          */
1741         rdpg->rp_hash = reqbody->size;
1742         if (rdpg->rp_hash != reqbody->size) {
1743                 CERROR("Invalid hash: "LPX64" != "LPX64"\n",
1744                        rdpg->rp_hash, reqbody->size);
1745                 RETURN(-EFAULT);
1746         }
1747
1748         rdpg->rp_attrs = reqbody->mode;
1749         if (exp_connect_flags(tsi->tsi_exp) & OBD_CONNECT_64BITHASH)
1750                 rdpg->rp_attrs |= LUDA_64BITHASH;
1751         rdpg->rp_count  = min_t(unsigned int, reqbody->nlink,
1752                                 exp_max_brw_size(tsi->tsi_exp));
1753         rdpg->rp_npages = (rdpg->rp_count + PAGE_CACHE_SIZE - 1) >>
1754                           PAGE_CACHE_SHIFT;
1755         OBD_ALLOC(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1756         if (rdpg->rp_pages == NULL)
1757                 RETURN(-ENOMEM);
1758
1759         for (i = 0; i < rdpg->rp_npages; ++i) {
1760                 rdpg->rp_pages[i] = alloc_page(GFP_IOFS);
1761                 if (rdpg->rp_pages[i] == NULL)
1762                         GOTO(free_rdpg, rc = -ENOMEM);
1763         }
1764
1765         /* call lower layers to fill allocated pages with directory data */
1766         rc = mo_readpage(tsi->tsi_env, mdt_object_child(object), rdpg);
1767         if (rc < 0)
1768                 GOTO(free_rdpg, rc);
1769
1770         /* send pages to client */
1771         rc = tgt_sendpage(tsi, rdpg, rc);
1772
1773         EXIT;
1774 free_rdpg:
1775
1776         for (i = 0; i < rdpg->rp_npages; i++)
1777                 if (rdpg->rp_pages[i] != NULL)
1778                         __free_page(rdpg->rp_pages[i]);
1779         OBD_FREE(rdpg->rp_pages, rdpg->rp_npages * sizeof rdpg->rp_pages[0]);
1780
1781         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SENDPAGE))
1782                 RETURN(0);
1783
1784         return rc;
1785 }
1786
1787 static int mdt_reint_internal(struct mdt_thread_info *info,
1788                               struct mdt_lock_handle *lhc,
1789                               __u32 op)
1790 {
1791         struct req_capsule      *pill = info->mti_pill;
1792         struct mdt_body         *repbody;
1793         int                      rc = 0, rc2;
1794
1795         ENTRY;
1796
1797         rc = mdt_reint_unpack(info, op);
1798         if (rc != 0) {
1799                 CERROR("Can't unpack reint, rc %d\n", rc);
1800                 RETURN(err_serious(rc));
1801         }
1802
1803         /* for replay (no_create) lmm is not needed, client has it already */
1804         if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1805                 req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
1806                                      DEF_REP_MD_SIZE);
1807
1808         /* llog cookies are always 0, the field is kept for compatibility */
1809         if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
1810                 req_capsule_set_size(pill, &RMF_LOGCOOKIES, RCL_SERVER, 0);
1811
1812         rc = req_capsule_server_pack(pill);
1813         if (rc != 0) {
1814                 CERROR("Can't pack response, rc %d\n", rc);
1815                 RETURN(err_serious(rc));
1816         }
1817
1818         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_SERVER)) {
1819                 repbody = req_capsule_server_get(pill, &RMF_MDT_BODY);
1820                 LASSERT(repbody);
1821                 repbody->eadatasize = 0;
1822                 repbody->aclsize = 0;
1823         }
1824
1825         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_REINT_DELAY, 10);
1826
1827         /* for replay no cookkie / lmm need, because client have this already */
1828         if (info->mti_spec.no_create)
1829                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
1830                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER, 0);
1831
1832         rc = mdt_init_ucred_reint(info);
1833         if (rc)
1834                 GOTO(out_shrink, rc);
1835
1836         rc = mdt_fix_attr_ucred(info, op);
1837         if (rc != 0)
1838                 GOTO(out_ucred, rc = err_serious(rc));
1839
1840         if (mdt_check_resent(info, mdt_reconstruct, lhc)) {
1841                 DEBUG_REQ(D_INODE, mdt_info_req(info), "resent opt.");
1842                 rc = lustre_msg_get_status(mdt_info_req(info)->rq_repmsg);
1843                 GOTO(out_ucred, rc);
1844         }
1845         rc = mdt_reint_rec(info, lhc);
1846         EXIT;
1847 out_ucred:
1848         mdt_exit_ucred(info);
1849 out_shrink:
1850         mdt_client_compatibility(info);
1851         rc2 = mdt_fix_reply(info);
1852         if (rc == 0)
1853                 rc = rc2;
1854         return rc;
1855 }
1856
1857 static long mdt_reint_opcode(struct ptlrpc_request *req,
1858                              const struct req_format **fmt)
1859 {
1860         struct mdt_device       *mdt;
1861         struct mdt_rec_reint    *rec;
1862         long                     opc;
1863
1864         rec = req_capsule_client_get(&req->rq_pill, &RMF_REC_REINT);
1865         if (rec != NULL) {
1866                 opc = rec->rr_opcode;
1867                 DEBUG_REQ(D_INODE, req, "reint opt = %ld", opc);
1868                 if (opc < REINT_MAX && fmt[opc] != NULL)
1869                         req_capsule_extend(&req->rq_pill, fmt[opc]);
1870                 else {
1871                         mdt = mdt_exp2dev(req->rq_export);
1872                         CERROR("%s: Unsupported opcode '%ld' from client '%s':"
1873                                " rc = %d\n", req->rq_export->exp_obd->obd_name,
1874                                opc, mdt->mdt_ldlm_client->cli_name, -EFAULT);
1875                         opc = err_serious(-EFAULT);
1876                 }
1877         } else {
1878                 opc = err_serious(-EFAULT);
1879         }
1880         return opc;
1881 }
1882
1883 static int mdt_reint(struct tgt_session_info *tsi)
1884 {
1885         long opc;
1886         int  rc;
1887         static const struct req_format *reint_fmts[REINT_MAX] = {
1888                 [REINT_SETATTR]  = &RQF_MDS_REINT_SETATTR,
1889                 [REINT_CREATE]   = &RQF_MDS_REINT_CREATE,
1890                 [REINT_LINK]     = &RQF_MDS_REINT_LINK,
1891                 [REINT_UNLINK]   = &RQF_MDS_REINT_UNLINK,
1892                 [REINT_RENAME]   = &RQF_MDS_REINT_RENAME,
1893                 [REINT_OPEN]     = &RQF_MDS_REINT_OPEN,
1894                 [REINT_SETXATTR] = &RQF_MDS_REINT_SETXATTR,
1895                 [REINT_RMENTRY]  = &RQF_MDS_REINT_UNLINK,
1896                 [REINT_MIGRATE]  = &RQF_MDS_REINT_RENAME
1897         };
1898
1899         ENTRY;
1900
1901         opc = mdt_reint_opcode(tgt_ses_req(tsi), reint_fmts);
1902         if (opc >= 0) {
1903                 struct mdt_thread_info *info = tsi2mdt_info(tsi);
1904                 /*
1905                  * No lock possible here from client to pass it to reint code
1906                  * path.
1907                  */
1908                 rc = mdt_reint_internal(info, NULL, opc);
1909                 mdt_thread_info_fini(info);
1910         } else {
1911                 rc = opc;
1912         }
1913
1914         tsi->tsi_reply_fail_id = OBD_FAIL_MDS_REINT_NET_REP;
1915         RETURN(rc);
1916 }
1917
1918 /* this should sync the whole device */
1919 static int mdt_device_sync(const struct lu_env *env, struct mdt_device *mdt)
1920 {
1921         struct dt_device *dt = mdt->mdt_bottom;
1922         int rc;
1923         ENTRY;
1924
1925         rc = dt->dd_ops->dt_sync(env, dt);
1926         RETURN(rc);
1927 }
1928
1929 /* this should sync this object */
1930 static int mdt_object_sync(struct mdt_thread_info *info)
1931 {
1932         struct md_object *next;
1933         int rc;
1934         ENTRY;
1935
1936         if (!mdt_object_exists(info->mti_object)) {
1937                 CWARN("Non existing object  "DFID"!\n",
1938                       PFID(mdt_object_fid(info->mti_object)));
1939                 RETURN(-ESTALE);
1940         }
1941         next = mdt_object_child(info->mti_object);
1942         rc = mo_object_sync(info->mti_env, next);
1943
1944         RETURN(rc);
1945 }
1946
1947 static int mdt_sync(struct tgt_session_info *tsi)
1948 {
1949         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1950         struct req_capsule      *pill = tsi->tsi_pill;
1951         struct mdt_body         *body;
1952         int                      rc;
1953
1954         ENTRY;
1955
1956         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_SYNC_PACK))
1957                 RETURN(err_serious(-ENOMEM));
1958
1959         if (fid_seq(&tsi->tsi_mdt_body->fid1) == 0) {
1960                 rc = mdt_device_sync(tsi->tsi_env, mdt_exp2dev(tsi->tsi_exp));
1961         } else {
1962                 struct mdt_thread_info *info = tsi2mdt_info(tsi);
1963
1964                 /* sync an object */
1965                 rc = mdt_object_sync(info);
1966                 if (rc == 0) {
1967                         const struct lu_fid *fid;
1968                         struct lu_attr *la = &info->mti_attr.ma_attr;
1969
1970                         info->mti_attr.ma_need = MA_INODE;
1971                         info->mti_attr.ma_valid = 0;
1972                         rc = mdt_attr_get_complex(info, info->mti_object,
1973                                                   &info->mti_attr);
1974                         if (rc == 0) {
1975                                 body = req_capsule_server_get(pill,
1976                                                               &RMF_MDT_BODY);
1977                                 fid = mdt_object_fid(info->mti_object);
1978                                 mdt_pack_attr2body(info, body, la, fid);
1979                         }
1980                 }
1981                 mdt_thread_info_fini(info);
1982         }
1983         if (rc == 0)
1984                 mdt_counter_incr(req, LPROC_MDT_SYNC);
1985
1986         RETURN(rc);
1987 }
1988
1989 /*
1990  * Handle quota control requests to consult current usage/limit, but also
1991  * to configure quota enforcement
1992  */
1993 static int mdt_quotactl(struct tgt_session_info *tsi)
1994 {
1995         struct obd_export       *exp  = tsi->tsi_exp;
1996         struct req_capsule      *pill = tsi->tsi_pill;
1997         struct obd_quotactl     *oqctl, *repoqc;
1998         int                      id, rc;
1999         struct mdt_device       *mdt = mdt_exp2dev(exp);
2000         struct lu_device        *qmt = mdt->mdt_qmt_dev;
2001         ENTRY;
2002
2003         oqctl = req_capsule_client_get(pill, &RMF_OBD_QUOTACTL);
2004         if (oqctl == NULL)
2005                 RETURN(err_serious(-EPROTO));
2006
2007         rc = req_capsule_server_pack(pill);
2008         if (rc)
2009                 RETURN(err_serious(rc));
2010
2011         switch (oqctl->qc_cmd) {
2012         case Q_QUOTACHECK:
2013         case LUSTRE_Q_INVALIDATE:
2014         case LUSTRE_Q_FINVALIDATE:
2015         case Q_QUOTAON:
2016         case Q_QUOTAOFF:
2017         case Q_INITQUOTA:
2018                 /* deprecated, not used any more */
2019                 RETURN(-EOPNOTSUPP);
2020                 /* master quotactl */
2021         case Q_GETINFO:
2022         case Q_SETINFO:
2023         case Q_SETQUOTA:
2024         case Q_GETQUOTA:
2025                 if (qmt == NULL)
2026                         RETURN(-EOPNOTSUPP);
2027                 /* slave quotactl */
2028         case Q_GETOINFO:
2029         case Q_GETOQUOTA:
2030                 break;
2031         default:
2032                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
2033                 RETURN(-EFAULT);
2034         }
2035
2036         /* map uid/gid for remote client */
2037         id = oqctl->qc_id;
2038         if (exp_connect_rmtclient(exp)) {
2039                 struct lustre_idmap_table *idmap;
2040
2041                 idmap = exp->exp_mdt_data.med_idmap;
2042
2043                 if (unlikely(oqctl->qc_cmd != Q_GETQUOTA &&
2044                              oqctl->qc_cmd != Q_GETINFO))
2045                         RETURN(-EPERM);
2046
2047                 if (oqctl->qc_type == USRQUOTA)
2048                         id = lustre_idmap_lookup_uid(NULL, idmap, 0,
2049                                                      oqctl->qc_id);
2050                 else if (oqctl->qc_type == GRPQUOTA)
2051                         id = lustre_idmap_lookup_gid(NULL, idmap, 0,
2052                                                      oqctl->qc_id);
2053                 else
2054                         RETURN(-EINVAL);
2055
2056                 if (id == CFS_IDMAP_NOTFOUND) {
2057                         CDEBUG(D_QUOTA, "no mapping for id %u\n", oqctl->qc_id);
2058                         RETURN(-EACCES);
2059                 }
2060         }
2061
2062         repoqc = req_capsule_server_get(pill, &RMF_OBD_QUOTACTL);
2063         if (repoqc == NULL)
2064                 RETURN(err_serious(-EFAULT));
2065
2066         if (oqctl->qc_id != id)
2067                 swap(oqctl->qc_id, id);
2068
2069         switch (oqctl->qc_cmd) {
2070
2071         case Q_GETINFO:
2072         case Q_SETINFO:
2073         case Q_SETQUOTA:
2074         case Q_GETQUOTA:
2075                 /* forward quotactl request to QMT */
2076                 rc = qmt_hdls.qmth_quotactl(tsi->tsi_env, qmt, oqctl);
2077                 break;
2078
2079         case Q_GETOINFO:
2080         case Q_GETOQUOTA:
2081                 /* slave quotactl */
2082                 rc = lquotactl_slv(tsi->tsi_env, tsi->tsi_tgt->lut_bottom,
2083                                    oqctl);
2084                 break;
2085
2086         default:
2087                 CERROR("Unsupported quotactl command: %d\n", oqctl->qc_cmd);
2088                 RETURN(-EFAULT);
2089         }
2090
2091         if (oqctl->qc_id != id)
2092                 swap(oqctl->qc_id, id);
2093
2094         *repoqc = *oqctl;
2095         RETURN(rc);
2096 }
2097
2098 /** clone llog ctxt from child (mdd)
2099  * This allows remote llog (replicator) access.
2100  * We can either pass all llog RPCs (eg mdt_llog_create) on to child where the
2101  * context was originally set up, or we can handle them directly.
2102  * I choose the latter, but that means I need any llog
2103  * contexts set up by child to be accessable by the mdt.  So we clone the
2104  * context into our context list here.
2105  */
2106 static int mdt_llog_ctxt_clone(const struct lu_env *env, struct mdt_device *mdt,
2107                                int idx)
2108 {
2109         struct md_device  *next = mdt->mdt_child;
2110         struct llog_ctxt *ctxt;
2111         int rc;
2112
2113         if (!llog_ctxt_null(mdt2obd_dev(mdt), idx))
2114                 return 0;
2115
2116         rc = next->md_ops->mdo_llog_ctxt_get(env, next, idx, (void **)&ctxt);
2117         if (rc || ctxt == NULL) {
2118                 return 0;
2119         }
2120
2121         rc = llog_group_set_ctxt(&mdt2obd_dev(mdt)->obd_olg, ctxt, idx);
2122         if (rc)
2123                 CERROR("Can't set mdt ctxt %d\n", rc);
2124
2125         return rc;
2126 }
2127
2128 static int mdt_llog_ctxt_unclone(const struct lu_env *env,
2129                                  struct mdt_device *mdt, int idx)
2130 {
2131         struct llog_ctxt *ctxt;
2132
2133         ctxt = llog_get_context(mdt2obd_dev(mdt), idx);
2134         if (ctxt == NULL)
2135                 return 0;
2136         /* Put once for the get we just did, and once for the clone */
2137         llog_ctxt_put(ctxt);
2138         llog_ctxt_put(ctxt);
2139         return 0;
2140 }
2141
2142 /*
2143  * sec context handlers
2144  */
2145 static int mdt_sec_ctx_handle(struct tgt_session_info *tsi)
2146 {
2147         int rc;
2148
2149         rc = mdt_handle_idmap(tsi);
2150         if (unlikely(rc)) {
2151                 struct ptlrpc_request   *req = tgt_ses_req(tsi);
2152                 __u32                    opc;
2153
2154                 opc = lustre_msg_get_opc(req->rq_reqmsg);
2155                 if (opc == SEC_CTX_INIT || opc == SEC_CTX_INIT_CONT)
2156                         sptlrpc_svc_ctx_invalidate(req);
2157         }
2158
2159         CFS_FAIL_TIMEOUT(OBD_FAIL_SEC_CTX_HDL_PAUSE, cfs_fail_val);
2160
2161         return rc;
2162 }
2163
2164 /*
2165  * quota request handlers
2166  */
2167 static int mdt_quota_dqacq(struct tgt_session_info *tsi)
2168 {
2169         struct mdt_device       *mdt = mdt_exp2dev(tsi->tsi_exp);
2170         struct lu_device        *qmt = mdt->mdt_qmt_dev;
2171         int                      rc;
2172         ENTRY;
2173
2174         if (qmt == NULL)
2175                 RETURN(err_serious(-EOPNOTSUPP));
2176
2177         rc = qmt_hdls.qmth_dqacq(tsi->tsi_env, qmt, tgt_ses_req(tsi));
2178         RETURN(rc);
2179 }
2180
2181 struct mdt_object *mdt_object_new(const struct lu_env *env,
2182                                   struct mdt_device *d,
2183                                   const struct lu_fid *f)
2184 {
2185         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
2186         struct lu_object *o;
2187         struct mdt_object *m;
2188         ENTRY;
2189
2190         CDEBUG(D_INFO, "Allocate object for "DFID"\n", PFID(f));
2191         o = lu_object_find(env, &d->mdt_lu_dev, f, &conf);
2192         if (unlikely(IS_ERR(o)))
2193                 m = (struct mdt_object *)o;
2194         else
2195                 m = mdt_obj(o);
2196         RETURN(m);
2197 }
2198
2199 struct mdt_object *mdt_object_find(const struct lu_env *env,
2200                                    struct mdt_device *d,
2201                                    const struct lu_fid *f)
2202 {
2203         struct lu_object *o;
2204         struct mdt_object *m;
2205         ENTRY;
2206
2207         CDEBUG(D_INFO, "Find object for "DFID"\n", PFID(f));
2208         o = lu_object_find(env, &d->mdt_lu_dev, f, NULL);
2209         if (unlikely(IS_ERR(o)))
2210                 m = (struct mdt_object *)o;
2211         else
2212                 m = mdt_obj(o);
2213
2214         RETURN(m);
2215 }
2216
2217 /**
2218  * Asyncronous commit for mdt device.
2219  *
2220  * Pass asynchonous commit call down the MDS stack.
2221  *
2222  * \param env environment
2223  * \param mdt the mdt device
2224  */
2225 static void mdt_device_commit_async(const struct lu_env *env,
2226                                     struct mdt_device *mdt)
2227 {
2228         struct dt_device *dt = mdt->mdt_bottom;
2229         int rc;
2230
2231         rc = dt->dd_ops->dt_commit_async(env, dt);
2232         if (unlikely(rc != 0))
2233                 CWARN("async commit start failed with rc = %d", rc);
2234 }
2235
2236 /**
2237  * Mark the lock as "synchonous".
2238  *
2239  * Mark the lock to deffer transaction commit to the unlock time.
2240  *
2241  * \param lock the lock to mark as "synchonous"
2242  *
2243  * \see mdt_is_lock_sync
2244  * \see mdt_save_lock
2245  */
2246 static inline void mdt_set_lock_sync(struct ldlm_lock *lock)
2247 {
2248         lock->l_ast_data = (void*)1;
2249 }
2250
2251 /**
2252  * Check whehter the lock "synchonous" or not.
2253  *
2254  * \param lock the lock to check
2255  * \retval 1 the lock is "synchonous"
2256  * \retval 0 the lock isn't "synchronous"
2257  *
2258  * \see mdt_set_lock_sync
2259  * \see mdt_save_lock
2260  */
2261 static inline int mdt_is_lock_sync(struct ldlm_lock *lock)
2262 {
2263         return lock->l_ast_data != NULL;
2264 }
2265
2266 /**
2267  * Blocking AST for mdt locks.
2268  *
2269  * Starts transaction commit if in case of COS lock conflict or
2270  * deffers such a commit to the mdt_save_lock.
2271  *
2272  * \param lock the lock which blocks a request or cancelling lock
2273  * \param desc unused
2274  * \param data unused
2275  * \param flag indicates whether this cancelling or blocking callback
2276  * \retval 0
2277  * \see ldlm_blocking_ast_nocheck
2278  */
2279 int mdt_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2280                      void *data, int flag)
2281 {
2282         struct obd_device *obd = ldlm_lock_to_ns(lock)->ns_obd;
2283         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2284         int rc;
2285         ENTRY;
2286
2287         if (flag == LDLM_CB_CANCELING)
2288                 RETURN(0);
2289         lock_res_and_lock(lock);
2290         if (lock->l_blocking_ast != mdt_blocking_ast) {
2291                 unlock_res_and_lock(lock);
2292                 RETURN(0);
2293         }
2294         if (mdt_cos_is_enabled(mdt) &&
2295             lock->l_req_mode & (LCK_PW | LCK_EX) &&
2296             lock->l_blocking_lock != NULL &&
2297             lock->l_client_cookie != lock->l_blocking_lock->l_client_cookie) {
2298                 mdt_set_lock_sync(lock);
2299         }
2300         rc = ldlm_blocking_ast_nocheck(lock);
2301
2302         /* There is no lock conflict if l_blocking_lock == NULL,
2303          * it indicates a blocking ast sent from ldlm_lock_decref_internal
2304          * when the last reference to a local lock was released */
2305         if (lock->l_req_mode == LCK_COS && lock->l_blocking_lock != NULL) {
2306                 struct lu_env env;
2307
2308                 rc = lu_env_init(&env, LCT_LOCAL);
2309                 if (unlikely(rc != 0))
2310                         CWARN("lu_env initialization failed with rc = %d,"
2311                               "cannot start asynchronous commit\n", rc);
2312                 else
2313                         mdt_device_commit_async(&env, mdt);
2314                 lu_env_fini(&env);
2315         }
2316         RETURN(rc);
2317 }
2318
2319 /* Used for cross-MDT lock */
2320 int mdt_remote_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
2321                             void *data, int flag)
2322 {
2323         struct lustre_handle lockh;
2324         int               rc;
2325
2326         switch (flag) {
2327         case LDLM_CB_BLOCKING:
2328                 ldlm_lock2handle(lock, &lockh);
2329                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
2330                 if (rc < 0) {
2331                         CDEBUG(D_INODE, "ldlm_cli_cancel: %d\n", rc);
2332                         RETURN(rc);
2333                 }
2334                 break;
2335         case LDLM_CB_CANCELING:
2336                 LDLM_DEBUG(lock, "Revoke remote lock\n");
2337                 break;
2338         default:
2339                 LBUG();
2340         }
2341         RETURN(0);
2342 }
2343
2344 int mdt_remote_object_lock(struct mdt_thread_info *mti,
2345                            struct mdt_object *o, const struct lu_fid *fid,
2346                            struct lustre_handle *lh, ldlm_mode_t mode,
2347                            __u64 ibits)
2348 {
2349         struct ldlm_enqueue_info *einfo = &mti->mti_einfo;
2350         ldlm_policy_data_t *policy = &mti->mti_policy;
2351         struct ldlm_res_id *res_id = &mti->mti_res_id;
2352         int rc = 0;
2353         ENTRY;
2354
2355         LASSERT(mdt_object_remote(o));
2356
2357         LASSERT(ibits == MDS_INODELOCK_UPDATE);
2358
2359         fid_build_reg_res_name(fid, res_id);
2360
2361         memset(einfo, 0, sizeof(*einfo));
2362         einfo->ei_type = LDLM_IBITS;
2363         einfo->ei_mode = mode;
2364         einfo->ei_cb_bl = mdt_remote_blocking_ast;
2365         einfo->ei_cb_cp = ldlm_completion_ast;
2366         einfo->ei_enq_slave = 0;
2367         einfo->ei_res_id = res_id;
2368
2369         memset(policy, 0, sizeof(*policy));
2370         policy->l_inodebits.bits = ibits;
2371
2372         rc = mo_object_lock(mti->mti_env, mdt_object_child(o), lh, einfo,
2373                             policy);
2374         RETURN(rc);
2375 }
2376
2377 static int mdt_object_local_lock(struct mdt_thread_info *info,
2378                                  struct mdt_object *o,
2379                                  struct mdt_lock_handle *lh, __u64 ibits,
2380                                  bool nonblock, int locality)
2381 {
2382         struct ldlm_namespace *ns = info->mti_mdt->mdt_namespace;
2383         ldlm_policy_data_t *policy = &info->mti_policy;
2384         struct ldlm_res_id *res_id = &info->mti_res_id;
2385         __u64 dlmflags;
2386         int rc;
2387         ENTRY;
2388
2389         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2390         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2391         LASSERT(lh->mlh_reg_mode != LCK_MINMODE);
2392         LASSERT(lh->mlh_type != MDT_NUL_LOCK);
2393
2394         /* Only enqueue LOOKUP lock for remote object */
2395         if (mdt_object_remote(o))
2396                 LASSERT(ibits == MDS_INODELOCK_LOOKUP);
2397
2398         if (lh->mlh_type == MDT_PDO_LOCK) {
2399                 /* check for exists after object is locked */
2400                 if (mdt_object_exists(o) == 0) {
2401                         /* Non-existent object shouldn't have PDO lock */
2402                         RETURN(-ESTALE);
2403                 } else {
2404                         /* Non-dir object shouldn't have PDO lock */
2405                         if (!S_ISDIR(lu_object_attr(&o->mot_obj)))
2406                                 RETURN(-ENOTDIR);
2407                 }
2408         }
2409
2410         memset(policy, 0, sizeof(*policy));
2411         fid_build_reg_res_name(mdt_object_fid(o), res_id);
2412
2413         dlmflags = LDLM_FL_ATOMIC_CB;
2414         if (nonblock)
2415                 dlmflags |= LDLM_FL_BLOCK_NOWAIT;
2416
2417         /*
2418          * Take PDO lock on whole directory and build correct @res_id for lock
2419          * on part of directory.
2420          */
2421         if (lh->mlh_pdo_hash != 0) {
2422                 LASSERT(lh->mlh_type == MDT_PDO_LOCK);
2423                 mdt_lock_pdo_mode(info, o, lh);
2424                 if (lh->mlh_pdo_mode != LCK_NL) {
2425                         /*
2426                          * Do not use LDLM_FL_LOCAL_ONLY for parallel lock, it
2427                          * is never going to be sent to client and we do not
2428                          * want it slowed down due to possible cancels.
2429                          */
2430                         policy->l_inodebits.bits = MDS_INODELOCK_UPDATE;
2431                         rc = mdt_fid_lock(ns, &lh->mlh_pdo_lh, lh->mlh_pdo_mode,
2432                                           policy, res_id, dlmflags,
2433                                           info->mti_exp == NULL ? NULL :
2434                                           &info->mti_exp->exp_handle.h_cookie);
2435                         if (unlikely(rc))
2436                                 RETURN(rc);
2437                 }
2438
2439                 /*
2440                  * Finish res_id initializing by name hash marking part of
2441                  * directory which is taking modification.
2442                  */
2443                 res_id->name[LUSTRE_RES_ID_HSH_OFF] = lh->mlh_pdo_hash;
2444         }
2445
2446         policy->l_inodebits.bits = ibits;
2447
2448         /*
2449          * Use LDLM_FL_LOCAL_ONLY for this lock. We do not know yet if it is
2450          * going to be sent to client. If it is - mdt_intent_policy() path will
2451          * fix it up and turn FL_LOCAL flag off.
2452          */
2453         rc = mdt_fid_lock(ns, &lh->mlh_reg_lh, lh->mlh_reg_mode, policy,
2454                           res_id, LDLM_FL_LOCAL_ONLY | dlmflags,
2455                           info->mti_exp == NULL ? NULL :
2456                           &info->mti_exp->exp_handle.h_cookie);
2457         if (rc)
2458                 mdt_object_unlock(info, o, lh, 1);
2459         else if (unlikely(OBD_FAIL_PRECHECK(OBD_FAIL_MDS_PDO_LOCK)) &&
2460                  lh->mlh_pdo_hash != 0 &&
2461                  (lh->mlh_reg_mode == LCK_PW || lh->mlh_reg_mode == LCK_EX)) {
2462                 OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_PDO_LOCK, 15);
2463         }
2464
2465         RETURN(rc);
2466 }
2467
2468 static int
2469 mdt_object_lock_internal(struct mdt_thread_info *info, struct mdt_object *o,
2470                          struct mdt_lock_handle *lh, __u64 ibits,
2471                          bool nonblock, int locality)
2472 {
2473         int rc;
2474         ENTRY;
2475
2476         if (!mdt_object_remote(o))
2477                 return mdt_object_local_lock(info, o, lh, ibits, nonblock,
2478                                              locality);
2479
2480         if (locality == MDT_LOCAL_LOCK) {
2481                 CERROR("%s: try to get local lock for remote object"
2482                        DFID".\n", mdt_obd_name(info->mti_mdt),
2483                        PFID(mdt_object_fid(o)));
2484                 RETURN(-EPROTO);
2485         }
2486
2487         /* XXX do not support PERM/LAYOUT/XATTR lock for remote object yet */
2488         ibits &= ~(MDS_INODELOCK_PERM | MDS_INODELOCK_LAYOUT |
2489                    MDS_INODELOCK_XATTR);
2490         if (ibits & MDS_INODELOCK_UPDATE) {
2491                 /* Sigh, PDO needs to enqueue 2 locks right now, but
2492                  * enqueue RPC can only request 1 lock, to avoid extra
2493                  * RPC, so it will instead enqueue EX lock for remote
2494                  * object anyway XXX*/
2495                 if (lh->mlh_type == MDT_PDO_LOCK &&
2496                     lh->mlh_pdo_hash != 0) {
2497                         CDEBUG(D_INFO, "%s: "DFID" convert PDO lock to"
2498                                "EX lock.\n", mdt_obd_name(info->mti_mdt),
2499                                PFID(mdt_object_fid(o)));
2500                         lh->mlh_pdo_hash = 0;
2501                         lh->mlh_rreg_mode = LCK_EX;
2502                         lh->mlh_type = MDT_REG_LOCK;
2503                 }
2504                 rc = mdt_remote_object_lock(info, o, mdt_object_fid(o),
2505                                             &lh->mlh_rreg_lh,
2506                                             lh->mlh_rreg_mode,
2507                                             MDS_INODELOCK_UPDATE);
2508                 if (rc != ELDLM_OK)
2509                         RETURN(rc);
2510         }
2511
2512         /* Only enqueue LOOKUP lock for remote object */
2513         if (ibits & MDS_INODELOCK_LOOKUP) {
2514                 rc = mdt_object_local_lock(info, o, lh,
2515                                            MDS_INODELOCK_LOOKUP,
2516                                            nonblock, locality);
2517                 if (rc != ELDLM_OK)
2518                         RETURN(rc);
2519         }
2520
2521         RETURN(0);
2522 }
2523
2524 int mdt_object_lock(struct mdt_thread_info *info, struct mdt_object *o,
2525                     struct mdt_lock_handle *lh, __u64 ibits, int locality)
2526 {
2527         return mdt_object_lock_internal(info, o, lh, ibits, false, locality);
2528 }
2529
2530 int mdt_object_lock_try(struct mdt_thread_info *info, struct mdt_object *o,
2531                         struct mdt_lock_handle *lh, __u64 ibits, int locality)
2532 {
2533         struct mdt_lock_handle tmp = *lh;
2534         int rc;
2535
2536         rc = mdt_object_lock_internal(info, o, &tmp, ibits, true, locality);
2537         if (rc == 0)
2538                 *lh = tmp;
2539
2540         return rc == 0;
2541 }
2542
2543 /**
2544  * Save a lock within request object.
2545  *
2546  * Keep the lock referenced until whether client ACK or transaction
2547  * commit happens or release the lock immediately depending on input
2548  * parameters. If COS is ON, a write lock is converted to COS lock
2549  * before saving.
2550  *
2551  * \param info thead info object
2552  * \param h lock handle
2553  * \param mode lock mode
2554  * \param decref force immediate lock releasing
2555  */
2556 static
2557 void mdt_save_lock(struct mdt_thread_info *info, struct lustre_handle *h,
2558                    ldlm_mode_t mode, int decref)
2559 {
2560         ENTRY;
2561
2562         if (lustre_handle_is_used(h)) {
2563                 if (decref || !info->mti_has_trans ||
2564                     !(mode & (LCK_PW | LCK_EX))){
2565                         mdt_fid_unlock(h, mode);
2566                 } else {
2567                         struct mdt_device *mdt = info->mti_mdt;
2568                         struct ldlm_lock *lock = ldlm_handle2lock(h);
2569                         struct ptlrpc_request *req = mdt_info_req(info);
2570                         int no_ack = 0;
2571
2572                         LASSERTF(lock != NULL, "no lock for cookie "LPX64"\n",
2573                                  h->cookie);
2574                         /* there is no request if mdt_object_unlock() is called
2575                          * from mdt_export_cleanup()->mdt_add_dirty_flag() */
2576                         if (likely(req != NULL)) {
2577                                 CDEBUG(D_HA, "request = %p reply state = %p"
2578                                        " transno = "LPD64"\n", req,
2579                                        req->rq_reply_state, req->rq_transno);
2580                                 if (mdt_cos_is_enabled(mdt)) {
2581                                         no_ack = 1;
2582                                         ldlm_lock_downgrade(lock, LCK_COS);
2583                                         mode = LCK_COS;
2584                                 }
2585                                 ptlrpc_save_lock(req, h, mode, no_ack);
2586                         } else {
2587                                 ldlm_lock_decref(h, mode);
2588                         }
2589                         if (mdt_is_lock_sync(lock)) {
2590                                 CDEBUG(D_HA, "found sync-lock,"
2591                                        " async commit started\n");
2592                                 mdt_device_commit_async(info->mti_env,
2593                                                         mdt);
2594                         }
2595                         LDLM_LOCK_PUT(lock);
2596                 }
2597                 h->cookie = 0ull;
2598         }
2599
2600         EXIT;
2601 }
2602
2603 /**
2604  * Unlock mdt object.
2605  *
2606  * Immeditely release the regular lock and the PDO lock or save the
2607  * lock in reqeuest and keep them referenced until client ACK or
2608  * transaction commit.
2609  *
2610  * \param info thread info object
2611  * \param o mdt object
2612  * \param lh mdt lock handle referencing regular and PDO locks
2613  * \param decref force immediate lock releasing
2614  */
2615 void mdt_object_unlock(struct mdt_thread_info *info, struct mdt_object *o,
2616                        struct mdt_lock_handle *lh, int decref)
2617 {
2618         ENTRY;
2619
2620         mdt_save_lock(info, &lh->mlh_pdo_lh, lh->mlh_pdo_mode, decref);
2621         mdt_save_lock(info, &lh->mlh_reg_lh, lh->mlh_reg_mode, decref);
2622
2623         if (lustre_handle_is_used(&lh->mlh_rreg_lh))
2624                 ldlm_lock_decref(&lh->mlh_rreg_lh, lh->mlh_rreg_mode);
2625
2626         EXIT;
2627 }
2628
2629 struct mdt_object *mdt_object_find_lock(struct mdt_thread_info *info,
2630                                         const struct lu_fid *f,
2631                                         struct mdt_lock_handle *lh,
2632                                         __u64 ibits)
2633 {
2634         struct mdt_object *o;
2635
2636         o = mdt_object_find(info->mti_env, info->mti_mdt, f);
2637         if (!IS_ERR(o)) {
2638                 int rc;
2639
2640                 rc = mdt_object_lock(info, o, lh, ibits,
2641                                      MDT_LOCAL_LOCK);
2642                 if (rc != 0) {
2643                         mdt_object_put(info->mti_env, o);
2644                         o = ERR_PTR(rc);
2645                 }
2646         }
2647         return o;
2648 }
2649
2650 void mdt_object_unlock_put(struct mdt_thread_info * info,
2651                            struct mdt_object * o,
2652                            struct mdt_lock_handle *lh,
2653                            int decref)
2654 {
2655         mdt_object_unlock(info, o, lh, decref);
2656         mdt_object_put(info->mti_env, o);
2657 }
2658
2659 /*
2660  * Generic code handling requests that have struct mdt_body passed in:
2661  *
2662  *  - extract mdt_body from request and save it in @info, if present;
2663  *
2664  *  - create lu_object, corresponding to the fid in mdt_body, and save it in
2665  *  @info;
2666  *
2667  *  - if HABEO_CORPUS flag is set for this request type check whether object
2668  *  actually exists on storage (lu_object_exists()).
2669  *
2670  */
2671 static int mdt_body_unpack(struct mdt_thread_info *info, __u32 flags)
2672 {
2673         const struct mdt_body    *body;
2674         struct mdt_object        *obj;
2675         const struct lu_env      *env;
2676         struct req_capsule       *pill;
2677         int                       rc;
2678         ENTRY;
2679
2680         env = info->mti_env;
2681         pill = info->mti_pill;
2682
2683         body = info->mti_body = req_capsule_client_get(pill, &RMF_MDT_BODY);
2684         if (body == NULL)
2685                 RETURN(-EFAULT);
2686
2687         if (!(body->valid & OBD_MD_FLID))
2688                 RETURN(0);
2689
2690         if (!fid_is_sane(&body->fid1)) {
2691                 CERROR("Invalid fid: "DFID"\n", PFID(&body->fid1));
2692                 RETURN(-EINVAL);
2693         }
2694
2695         /*
2696          * Do not get size or any capa fields before we check that request
2697          * contains capa actually. There are some requests which do not, for
2698          * instance MDS_IS_SUBDIR.
2699          */
2700         if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2701             req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT))
2702                 mdt_set_capainfo(info, 0, &body->fid1,
2703                                  req_capsule_client_get(pill, &RMF_CAPA1));
2704
2705         obj = mdt_object_find(env, info->mti_mdt, &body->fid1);
2706         if (!IS_ERR(obj)) {
2707                 if ((flags & HABEO_CORPUS) &&
2708                     !mdt_object_exists(obj)) {
2709                         mdt_object_put(env, obj);
2710                         /* for capability renew ENOENT will be handled in
2711                          * mdt_renew_capa */
2712                         if (body->valid & OBD_MD_FLOSSCAPA)
2713                                 rc = 0;
2714                         else
2715                                 rc = -ENOENT;
2716                 } else {
2717                         info->mti_object = obj;
2718                         rc = 0;
2719                 }
2720         } else
2721                 rc = PTR_ERR(obj);
2722
2723         RETURN(rc);
2724 }
2725
2726 static int mdt_unpack_req_pack_rep(struct mdt_thread_info *info, __u32 flags)
2727 {
2728         struct req_capsule *pill = info->mti_pill;
2729         int rc;
2730         ENTRY;
2731
2732         if (req_capsule_has_field(pill, &RMF_MDT_BODY, RCL_CLIENT))
2733                 rc = mdt_body_unpack(info, flags);
2734         else
2735                 rc = 0;
2736
2737         if (rc == 0 && (flags & HABEO_REFERO)) {
2738                 /* Pack reply. */
2739                 if (req_capsule_has_field(pill, &RMF_MDT_MD, RCL_SERVER))
2740                         req_capsule_set_size(pill, &RMF_MDT_MD, RCL_SERVER,
2741                                              DEF_REP_MD_SIZE);
2742                 if (req_capsule_has_field(pill, &RMF_LOGCOOKIES, RCL_SERVER))
2743                         req_capsule_set_size(pill, &RMF_LOGCOOKIES,
2744                                              RCL_SERVER, 0);
2745
2746                 rc = req_capsule_server_pack(pill);
2747         }
2748         RETURN(rc);
2749 }
2750
2751 static int mdt_init_capa_ctxt(const struct lu_env *env, struct mdt_device *m)
2752 {
2753         struct md_device *next = m->mdt_child;
2754
2755         return next->md_ops->mdo_init_capa_ctxt(env, next,
2756                                                 m->mdt_lut.lut_mds_capa,
2757                                                 m->mdt_capa_timeout,
2758                                                 m->mdt_capa_alg,
2759                                                 m->mdt_capa_keys);
2760 }
2761
2762 void mdt_lock_handle_init(struct mdt_lock_handle *lh)
2763 {
2764         lh->mlh_type = MDT_NUL_LOCK;
2765         lh->mlh_reg_lh.cookie = 0ull;
2766         lh->mlh_reg_mode = LCK_MINMODE;
2767         lh->mlh_pdo_lh.cookie = 0ull;
2768         lh->mlh_pdo_mode = LCK_MINMODE;
2769         lh->mlh_rreg_lh.cookie = 0ull;
2770         lh->mlh_rreg_mode = LCK_MINMODE;
2771 }
2772
2773 void mdt_lock_handle_fini(struct mdt_lock_handle *lh)
2774 {
2775         LASSERT(!lustre_handle_is_used(&lh->mlh_reg_lh));
2776         LASSERT(!lustre_handle_is_used(&lh->mlh_pdo_lh));
2777 }
2778
2779 /*
2780  * Initialize fields of struct mdt_thread_info. Other fields are left in
2781  * uninitialized state, because it's too expensive to zero out whole
2782  * mdt_thread_info (> 1K) on each request arrival.
2783  */
2784 void mdt_thread_info_init(struct ptlrpc_request *req,
2785                           struct mdt_thread_info *info)
2786 {
2787         int i;
2788
2789         info->mti_pill = &req->rq_pill;
2790
2791         /* lock handle */
2792         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2793                 mdt_lock_handle_init(&info->mti_lh[i]);
2794
2795         /* mdt device: it can be NULL while CONNECT */
2796         if (req->rq_export) {
2797                 info->mti_mdt = mdt_dev(req->rq_export->exp_obd->obd_lu_dev);
2798                 info->mti_exp = req->rq_export;
2799         } else
2800                 info->mti_mdt = NULL;
2801         info->mti_env = req->rq_svc_thread->t_env;
2802         info->mti_transno = lustre_msg_get_transno(req->rq_reqmsg);
2803
2804         memset(&info->mti_attr, 0, sizeof(info->mti_attr));
2805         info->mti_big_buf = LU_BUF_NULL;
2806         info->mti_body = NULL;
2807         info->mti_object = NULL;
2808         info->mti_dlm_req = NULL;
2809         info->mti_has_trans = 0;
2810         info->mti_cross_ref = 0;
2811         info->mti_opdata = 0;
2812         info->mti_big_lmm_used = 0;
2813
2814         info->mti_spec.no_create = 0;
2815         info->mti_spec.sp_rm_entry = 0;
2816
2817         info->mti_spec.u.sp_ea.eadata = NULL;
2818         info->mti_spec.u.sp_ea.eadatalen = 0;
2819 }
2820
2821 void mdt_thread_info_fini(struct mdt_thread_info *info)
2822 {
2823         int i;
2824
2825         if (info->mti_object != NULL) {
2826                 mdt_object_put(info->mti_env, info->mti_object);
2827                 info->mti_object = NULL;
2828         }
2829
2830         for (i = 0; i < ARRAY_SIZE(info->mti_lh); i++)
2831                 mdt_lock_handle_fini(&info->mti_lh[i]);
2832         info->mti_env = NULL;
2833         info->mti_pill = NULL;
2834         info->mti_exp = NULL;
2835
2836         if (unlikely(info->mti_big_buf.lb_buf != NULL))
2837                 lu_buf_free(&info->mti_big_buf);
2838 }
2839
2840 struct mdt_thread_info *tsi2mdt_info(struct tgt_session_info *tsi)
2841 {
2842         struct mdt_thread_info  *mti;
2843         struct lustre_capa      *lc;
2844
2845         mti = mdt_th_info(tsi->tsi_env);
2846         LASSERT(mti != NULL);
2847
2848         mdt_thread_info_init(tgt_ses_req(tsi), mti);
2849         if (tsi->tsi_corpus != NULL) {
2850                 struct req_capsule *pill = tsi->tsi_pill;
2851
2852                 mti->mti_object = mdt_obj(tsi->tsi_corpus);
2853                 lu_object_get(tsi->tsi_corpus);
2854
2855                 /*
2856                  * XXX: must be part of tgt_mdt_body_unpack but moved here
2857                  * due to mdt_set_capainfo().
2858                  */
2859                 if (req_capsule_has_field(pill, &RMF_CAPA1, RCL_CLIENT) &&
2860                     req_capsule_get_size(pill, &RMF_CAPA1, RCL_CLIENT) > 0) {
2861                         lc = req_capsule_client_get(pill, &RMF_CAPA1);
2862                         mdt_set_capainfo(mti, 0, &tsi->tsi_mdt_body->fid1, lc);
2863                 }
2864         }
2865         mti->mti_body = tsi->tsi_mdt_body;
2866         mti->mti_dlm_req = tsi->tsi_dlm_req;
2867
2868         return mti;
2869 }
2870
2871 static int mdt_tgt_connect(struct tgt_session_info *tsi)
2872 {
2873         struct ptlrpc_request   *req = tgt_ses_req(tsi);
2874         int                      rc;
2875
2876         ENTRY;
2877
2878         rc = tgt_connect(tsi);
2879         if (rc != 0)
2880                 RETURN(rc);
2881
2882         rc = mdt_init_idmap(tsi);
2883         if (rc != 0)
2884                 GOTO(err, rc);
2885         RETURN(0);
2886 err:
2887         obd_disconnect(class_export_get(req->rq_export));
2888         return rc;
2889 }
2890
2891 enum mdt_it_code {
2892         MDT_IT_OPEN,
2893         MDT_IT_OCREAT,
2894         MDT_IT_CREATE,
2895         MDT_IT_GETATTR,
2896         MDT_IT_READDIR,
2897         MDT_IT_LOOKUP,
2898         MDT_IT_UNLINK,
2899         MDT_IT_TRUNC,
2900         MDT_IT_GETXATTR,
2901         MDT_IT_LAYOUT,
2902         MDT_IT_QUOTA,
2903         MDT_IT_NR
2904 };
2905
2906 static int mdt_intent_getattr(enum mdt_it_code opcode,
2907                               struct mdt_thread_info *info,
2908                               struct ldlm_lock **,
2909                               __u64);
2910
2911 static int mdt_intent_getxattr(enum mdt_it_code opcode,
2912                                 struct mdt_thread_info *info,
2913                                 struct ldlm_lock **lockp,
2914                                 __u64 flags);
2915
2916 static int mdt_intent_layout(enum mdt_it_code opcode,
2917                              struct mdt_thread_info *info,
2918                              struct ldlm_lock **,
2919                              __u64);
2920 static int mdt_intent_reint(enum mdt_it_code opcode,
2921                             struct mdt_thread_info *info,
2922                             struct ldlm_lock **,
2923                             __u64);
2924
2925 static struct mdt_it_flavor {
2926         const struct req_format *it_fmt;
2927         __u32                    it_flags;
2928         int                    (*it_act)(enum mdt_it_code ,
2929                                          struct mdt_thread_info *,
2930                                          struct ldlm_lock **,
2931                                          __u64);
2932         long                     it_reint;
2933 } mdt_it_flavor[] = {
2934         [MDT_IT_OPEN]     = {
2935                 .it_fmt   = &RQF_LDLM_INTENT,
2936                 /*.it_flags = HABEO_REFERO,*/
2937                 .it_flags = 0,
2938                 .it_act   = mdt_intent_reint,
2939                 .it_reint = REINT_OPEN
2940         },
2941         [MDT_IT_OCREAT]   = {
2942                 .it_fmt   = &RQF_LDLM_INTENT,
2943                 /*
2944                  * OCREAT is not a MUTABOR request as if the file
2945                  * already exists.
2946                  * We do the extra check of OBD_CONNECT_RDONLY in
2947                  * mdt_reint_open() when we really need to create
2948                  * the object.
2949                  */
2950                 .it_flags = 0,
2951                 .it_act   = mdt_intent_reint,
2952                 .it_reint = REINT_OPEN
2953         },
2954         [MDT_IT_CREATE]   = {
2955                 .it_fmt   = &RQF_LDLM_INTENT,
2956                 .it_flags = MUTABOR,
2957                 .it_act   = mdt_intent_reint,
2958                 .it_reint = REINT_CREATE
2959         },
2960         [MDT_IT_GETATTR]  = {
2961                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
2962                 .it_flags = HABEO_REFERO,
2963                 .it_act   = mdt_intent_getattr
2964         },
2965         [MDT_IT_READDIR]  = {
2966                 .it_fmt   = NULL,
2967                 .it_flags = 0,
2968                 .it_act   = NULL
2969         },
2970         [MDT_IT_LOOKUP]   = {
2971                 .it_fmt   = &RQF_LDLM_INTENT_GETATTR,
2972                 .it_flags = HABEO_REFERO,
2973                 .it_act   = mdt_intent_getattr
2974         },
2975         [MDT_IT_UNLINK]   = {
2976                 .it_fmt   = &RQF_LDLM_INTENT_UNLINK,
2977                 .it_flags = MUTABOR,
2978                 .it_act   = NULL,
2979                 .it_reint = REINT_UNLINK
2980         },
2981         [MDT_IT_TRUNC]    = {
2982                 .it_fmt   = NULL,
2983                 .it_flags = MUTABOR,
2984                 .it_act   = NULL
2985         },
2986         [MDT_IT_GETXATTR] = {
2987                 .it_fmt   = &RQF_LDLM_INTENT_GETXATTR,
2988                 .it_flags = HABEO_CORPUS,
2989                 .it_act   = mdt_intent_getxattr
2990         },
2991         [MDT_IT_LAYOUT] = {
2992                 .it_fmt   = &RQF_LDLM_INTENT_LAYOUT,
2993                 .it_flags = 0,
2994                 .it_act   = mdt_intent_layout
2995         }
2996 };
2997
2998 static int
2999 mdt_intent_lock_replace(struct mdt_thread_info *info, struct ldlm_lock **lockp,
3000                         struct ldlm_lock *new_lock, struct mdt_lock_handle *lh,
3001                         __u64 flags)
3002 {
3003         struct ptlrpc_request  *req = mdt_info_req(info);
3004         struct ldlm_lock       *lock = *lockp;
3005
3006         /*
3007          * Get new lock only for cases when possible resent did not find any
3008          * lock.
3009          */
3010         if (new_lock == NULL)
3011                 new_lock = ldlm_handle2lock_long(&lh->mlh_reg_lh, 0);
3012
3013         if (new_lock == NULL && (flags & LDLM_FL_INTENT_ONLY)) {
3014                 lh->mlh_reg_lh.cookie = 0;
3015                 RETURN(0);
3016         }
3017
3018         LASSERTF(new_lock != NULL,
3019                  "lockh "LPX64"\n", lh->mlh_reg_lh.cookie);
3020
3021         /*
3022          * If we've already given this lock to a client once, then we should
3023          * have no readers or writers.  Otherwise, we should have one reader
3024          * _or_ writer ref (which will be zeroed below) before returning the
3025          * lock to a client.
3026          */
3027         if (new_lock->l_export == req->rq_export) {
3028                 LASSERT(new_lock->l_readers + new_lock->l_writers == 0);
3029         } else {
3030                 LASSERT(new_lock->l_export == NULL);
3031                 LASSERT(new_lock->l_readers + new_lock->l_writers == 1);
3032         }
3033
3034         *lockp = new_lock;
3035
3036         if (new_lock->l_export == req->rq_export) {
3037                 /*
3038                  * Already gave this to the client, which means that we
3039                  * reconstructed a reply.
3040                  */
3041                 LASSERT(lustre_msg_get_flags(req->rq_reqmsg) &
3042                         MSG_RESENT);
3043                 lh->mlh_reg_lh.cookie = 0;
3044                 RETURN(ELDLM_LOCK_REPLACED);
3045         }
3046
3047         /*
3048          * Fixup the lock to be given to the client.
3049          */
3050         lock_res_and_lock(new_lock);
3051         /* Zero new_lock->l_readers and new_lock->l_writers without triggering
3052          * possible blocking AST. */
3053         while (new_lock->l_readers > 0) {
3054                 lu_ref_del(&new_lock->l_reference, "reader", new_lock);
3055                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3056                 new_lock->l_readers--;
3057         }
3058         while (new_lock->l_writers > 0) {
3059                 lu_ref_del(&new_lock->l_reference, "writer", new_lock);
3060                 lu_ref_del(&new_lock->l_reference, "user", new_lock);
3061                 new_lock->l_writers--;
3062         }
3063
3064         new_lock->l_export = class_export_lock_get(req->rq_export, new_lock);
3065         new_lock->l_blocking_ast = lock->l_blocking_ast;
3066         new_lock->l_completion_ast = lock->l_completion_ast;
3067         new_lock->l_remote_handle = lock->l_remote_handle;
3068         new_lock->l_flags &= ~LDLM_FL_LOCAL;
3069
3070         unlock_res_and_lock(new_lock);
3071
3072         cfs_hash_add(new_lock->l_export->exp_lock_hash,
3073                      &new_lock->l_remote_handle,
3074                      &new_lock->l_exp_hash);
3075
3076         LDLM_LOCK_RELEASE(new_lock);
3077         lh->mlh_reg_lh.cookie = 0;
3078
3079         RETURN(ELDLM_LOCK_REPLACED);
3080 }
3081
3082 static void mdt_intent_fixup_resent(struct mdt_thread_info *info,
3083                                     struct ldlm_lock *new_lock,
3084                                     struct ldlm_lock **old_lock,
3085                                     struct mdt_lock_handle *lh,
3086                                     enum mdt_it_code opcode)
3087 {
3088         struct ptlrpc_request  *req = mdt_info_req(info);
3089         struct obd_export      *exp = req->rq_export;
3090         struct lustre_handle    remote_hdl;
3091         struct ldlm_request    *dlmreq;
3092         struct ldlm_lock       *lock;
3093
3094         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT))
3095                 return;
3096
3097         dlmreq = req_capsule_client_get(info->mti_pill, &RMF_DLM_REQ);
3098         remote_hdl = dlmreq->lock_handle[0];
3099         /* If the client does not require open lock, it does not need to
3100          * search lock in exp_lock_hash, since the server thread will
3101          * make sure the lock will be released, and the resend request
3102          * can always re-enqueue the lock */
3103         if ((opcode != MDT_IT_OPEN) || (opcode == MDT_IT_OPEN &&
3104             info->mti_spec.sp_cr_flags & MDS_OPEN_LOCK)) {
3105                 /* In the function below, .hs_keycmp resolves to
3106                  * ldlm_export_lock_keycmp() */
3107                 /* coverity[overrun-buffer-val] */
3108                 lock = cfs_hash_lookup(exp->exp_lock_hash, &remote_hdl);
3109                 if (lock) {
3110                         lock_res_and_lock(lock);
3111                         if (lock != new_lock) {
3112                                 lh->mlh_reg_lh.cookie = lock->l_handle.h_cookie;
3113                                 lh->mlh_reg_mode = lock->l_granted_mode;
3114
3115                                 LDLM_DEBUG(lock, "Restoring lock cookie");
3116                                 DEBUG_REQ(D_DLMTRACE, req,
3117                                           "restoring lock cookie "LPX64,
3118                                           lh->mlh_reg_lh.cookie);
3119                                 if (old_lock)
3120                                         *old_lock = LDLM_LOCK_GET(lock);
3121                                 cfs_hash_put(exp->exp_lock_hash,
3122                                              &lock->l_exp_hash);
3123                                 unlock_res_and_lock(lock);
3124                                 return;
3125                         }
3126                         cfs_hash_put(exp->exp_lock_hash, &lock->l_exp_hash);
3127                         unlock_res_and_lock(lock);
3128                 }
3129         }
3130         /*
3131          * If the xid matches, then we know this is a resent request, and allow
3132          * it. (It's probably an OPEN, for which we don't send a lock.
3133          */
3134         if (req_xid_is_last(req))
3135                 return;
3136
3137         /*
3138          * This remote handle isn't enqueued, so we never received or processed
3139          * this request.  Clear MSG_RESENT, because it can be handled like any
3140          * normal request now.
3141          */
3142         lustre_msg_clear_flags(req->rq_reqmsg, MSG_RESENT);
3143
3144         DEBUG_REQ(D_DLMTRACE, req, "no existing lock with rhandle "LPX64,
3145                   remote_hdl.cookie);
3146 }
3147
3148 static int mdt_intent_getxattr(enum mdt_it_code opcode,
3149                                 struct mdt_thread_info *info,
3150                                 struct ldlm_lock **lockp,
3151                                 __u64 flags)
3152 {
3153         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3154         struct ldlm_reply      *ldlm_rep = NULL;
3155         int rc, grc;
3156
3157         /*
3158          * Initialize lhc->mlh_reg_lh either from a previously granted lock
3159          * (for the resend case) or a new lock. Below we will use it to
3160          * replace the original lock.
3161          */
3162         mdt_intent_fixup_resent(info, *lockp, NULL, lhc, opcode);
3163         if (!lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3164                 mdt_lock_reg_init(lhc, (*lockp)->l_req_mode);
3165                 rc = mdt_object_lock(info, info->mti_object, lhc,
3166                                         MDS_INODELOCK_XATTR,
3167                                         MDT_LOCAL_LOCK);
3168                 if (rc)
3169                         return rc;
3170         }
3171
3172         grc = mdt_getxattr(info);
3173
3174         rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3175
3176         if (mdt_info_req(info)->rq_repmsg != NULL)
3177                 ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3178         if (ldlm_rep == NULL)
3179                 RETURN(err_serious(-EFAULT));
3180
3181         ldlm_rep->lock_policy_res2 = grc;
3182
3183         return rc;
3184 }
3185
3186 static int mdt_intent_getattr(enum mdt_it_code opcode,
3187                               struct mdt_thread_info *info,
3188                               struct ldlm_lock **lockp,
3189                               __u64 flags)
3190 {
3191         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3192         struct ldlm_lock       *new_lock = NULL;
3193         __u64                   child_bits;
3194         struct ldlm_reply      *ldlm_rep;
3195         struct mdt_body        *reqbody;
3196         struct mdt_body        *repbody;
3197         int                     rc, rc2;
3198         ENTRY;
3199
3200         reqbody = req_capsule_client_get(info->mti_pill, &RMF_MDT_BODY);
3201         LASSERT(reqbody);
3202
3203         repbody = req_capsule_server_get(info->mti_pill, &RMF_MDT_BODY);
3204         LASSERT(repbody);
3205
3206         info->mti_cross_ref = !!(reqbody->valid & OBD_MD_FLCROSSREF);
3207         repbody->eadatasize = 0;
3208         repbody->aclsize = 0;
3209
3210         switch (opcode) {
3211         case MDT_IT_LOOKUP:
3212                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_PERM;
3213                 break;
3214         case MDT_IT_GETATTR:
3215                 child_bits = MDS_INODELOCK_LOOKUP | MDS_INODELOCK_UPDATE |
3216                              MDS_INODELOCK_PERM;
3217                 break;
3218         default:
3219                 CERROR("Unsupported intent (%d)\n", opcode);
3220                 GOTO(out_shrink, rc = -EINVAL);
3221         }
3222
3223         rc = mdt_init_ucred(info, reqbody);
3224         if (rc)
3225                 GOTO(out_shrink, rc);
3226
3227         ldlm_rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3228         mdt_set_disposition(info, ldlm_rep, DISP_IT_EXECD);
3229
3230         /* Get lock from request for possible resent case. */
3231         mdt_intent_fixup_resent(info, *lockp, &new_lock, lhc, opcode);
3232
3233         rc = mdt_getattr_name_lock(info, lhc, child_bits, ldlm_rep);
3234         ldlm_rep->lock_policy_res2 = clear_serious(rc);
3235
3236         if (mdt_get_disposition(ldlm_rep, DISP_LOOKUP_NEG))
3237                 ldlm_rep->lock_policy_res2 = 0;
3238         if (!mdt_get_disposition(ldlm_rep, DISP_LOOKUP_POS) ||
3239             ldlm_rep->lock_policy_res2) {
3240                 lhc->mlh_reg_lh.cookie = 0ull;
3241                 GOTO(out_ucred, rc = ELDLM_LOCK_ABORTED);
3242         }
3243
3244         rc = mdt_intent_lock_replace(info, lockp, new_lock, lhc, flags);
3245         EXIT;
3246 out_ucred:
3247         mdt_exit_ucred(info);
3248 out_shrink:
3249         mdt_client_compatibility(info);
3250         rc2 = mdt_fix_reply(info);
3251         if (rc == 0)
3252                 rc = rc2;
3253         return rc;
3254 }
3255
3256 static int mdt_intent_layout(enum mdt_it_code opcode,
3257                              struct mdt_thread_info *info,
3258                              struct ldlm_lock **lockp,
3259                              __u64 flags)
3260 {
3261         struct layout_intent *layout;
3262         struct lu_fid *fid;
3263         struct mdt_object *obj = NULL;
3264         int rc = 0;
3265         ENTRY;
3266
3267         if (opcode != MDT_IT_LAYOUT) {
3268                 CERROR("%s: Unknown intent (%d)\n", mdt_obd_name(info->mti_mdt),
3269                         opcode);
3270                 RETURN(-EINVAL);
3271         }
3272
3273         fid = &info->mti_tmp_fid2;
3274         fid_extract_from_res_name(fid, &(*lockp)->l_resource->lr_name);
3275
3276         obj = mdt_object_find(info->mti_env, info->mti_mdt, fid);
3277         if (IS_ERR(obj))
3278                 RETURN(PTR_ERR(obj));
3279
3280         if (mdt_object_exists(obj) && !mdt_object_remote(obj)) {
3281                 /* get the length of lsm */
3282                 rc = mdt_attr_get_eabuf_size(info, obj);
3283                 if (rc < 0)
3284                         RETURN(rc);
3285
3286                 if (rc > info->mti_mdt->mdt_max_mdsize)
3287                         info->mti_mdt->mdt_max_mdsize = rc;
3288         }
3289
3290         mdt_object_put(info->mti_env, obj);
3291
3292         (*lockp)->l_lvb_type = LVB_T_LAYOUT;
3293         req_capsule_set_size(info->mti_pill, &RMF_DLM_LVB, RCL_SERVER, rc);
3294         rc = req_capsule_server_pack(info->mti_pill);
3295         if (rc != 0)
3296                 RETURN(-EINVAL);
3297
3298         layout = req_capsule_client_get(info->mti_pill, &RMF_LAYOUT_INTENT);
3299         LASSERT(layout != NULL);
3300         if (layout->li_opc == LAYOUT_INTENT_ACCESS)
3301                 /* return to normal ldlm handling */
3302                 RETURN(0);
3303
3304         CERROR("%s: Unsupported layout intent (%d)\n",
3305                 mdt_obd_name(info->mti_mdt), layout->li_opc);
3306         RETURN(-EINVAL);
3307 }
3308
3309 static int mdt_intent_reint(enum mdt_it_code opcode,
3310                             struct mdt_thread_info *info,
3311                             struct ldlm_lock **lockp,
3312                             __u64 flags)
3313 {
3314         struct mdt_lock_handle *lhc = &info->mti_lh[MDT_LH_RMT];
3315         struct ldlm_reply      *rep = NULL;
3316         long                    opc;
3317         int                     rc;
3318
3319         static const struct req_format *intent_fmts[REINT_MAX] = {
3320                 [REINT_CREATE]  = &RQF_LDLM_INTENT_CREATE,
3321                 [REINT_OPEN]    = &RQF_LDLM_INTENT_OPEN
3322         };
3323
3324         ENTRY;
3325
3326         opc = mdt_reint_opcode(mdt_info_req(info), intent_fmts);
3327         if (opc < 0)
3328                 RETURN(opc);
3329
3330         if (mdt_it_flavor[opcode].it_reint != opc) {
3331                 CERROR("Reint code %ld doesn't match intent: %d\n",
3332                        opc, opcode);
3333                 RETURN(err_serious(-EPROTO));
3334         }
3335
3336         /* Get lock from request for possible resent case. */
3337         mdt_intent_fixup_resent(info, *lockp, NULL, lhc, opcode);
3338
3339         rc = mdt_reint_internal(info, lhc, opc);
3340
3341         /* Check whether the reply has been packed successfully. */
3342         if (mdt_info_req(info)->rq_repmsg != NULL)
3343                 rep = req_capsule_server_get(info->mti_pill, &RMF_DLM_REP);
3344         if (rep == NULL)
3345                 RETURN(err_serious(-EFAULT));
3346
3347         /* MDC expects this in any case */
3348         if (rc != 0)
3349                 mdt_set_disposition(info, rep, DISP_LOOKUP_EXECD);
3350
3351         /* the open lock or the lock for cross-ref object should be
3352          * returned to the client */
3353         if (rc == -EREMOTE || mdt_get_disposition(rep, DISP_OPEN_LOCK)) {
3354                 LASSERT(lustre_handle_is_used(&lhc->mlh_reg_lh));
3355                 rep->lock_policy_res2 = 0;
3356                 rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3357                 RETURN(rc);
3358         }
3359
3360         rep->lock_policy_res2 = clear_serious(rc);
3361
3362         if (rep->lock_policy_res2 == -ENOENT &&
3363             mdt_get_disposition(rep, DISP_LOOKUP_NEG))
3364                 rep->lock_policy_res2 = 0;
3365
3366         if (rc == -ENOTCONN || rc == -ENODEV ||
3367             rc == -EOVERFLOW) { /**< if VBR failure then return error */
3368                 /*
3369                  * If it is the disconnect error (ENODEV & ENOCONN), the error
3370                  * will be returned by rq_status, and client at ptlrpc layer
3371                  * will detect this, then disconnect, reconnect the import
3372                  * immediately, instead of impacting the following the rpc.
3373                  */
3374                 lhc->mlh_reg_lh.cookie = 0ull;
3375                 RETURN(rc);
3376         } else {
3377                 /*
3378                  * For other cases, the error will be returned by intent.
3379                  * and client will retrieve the result from intent.
3380                  */
3381                  /*
3382                   * FIXME: when open lock is finished, that should be
3383                   * checked here.
3384                   */
3385                 if (lustre_handle_is_used(&lhc->mlh_reg_lh)) {
3386                         LASSERTF(rc == 0, "Error occurred but lock handle "
3387                                  "is still in use, rc = %d\n", rc);
3388                         rep->lock_policy_res2 = 0;
3389                         rc = mdt_intent_lock_replace(info, lockp, NULL, lhc, flags);
3390                         RETURN(rc);
3391                 } else {
3392                         lhc->mlh_reg_lh.cookie = 0ull;
3393                         RETURN(ELDLM_LOCK_ABORTED);
3394                 }
3395         }
3396 }
3397
3398 static int mdt_intent_code(long itcode)
3399 {
3400         int rc;
3401
3402         switch(itcode) {
3403         case IT_OPEN:
3404                 rc = MDT_IT_OPEN;
3405                 break;
3406         case IT_OPEN|IT_CREAT:
3407                 rc = MDT_IT_OCREAT;
3408                 break;
3409         case IT_CREAT:
3410                 rc = MDT_IT_CREATE;
3411                 break;
3412         case IT_READDIR:
3413                 rc = MDT_IT_READDIR;
3414                 break;
3415         case IT_GETATTR:
3416                 rc = MDT_IT_GETATTR;
3417                 break;
3418         case IT_LOOKUP:
3419                 rc = MDT_IT_LOOKUP;
3420                 break;
3421         case IT_UNLINK:
3422                 rc = MDT_IT_UNLINK;
3423                 break;
3424         case IT_TRUNC:
3425                 rc = MDT_IT_TRUNC;
3426                 break;
3427         case IT_GETXATTR:
3428                 rc = MDT_IT_GETXATTR;
3429                 break;
3430         case IT_LAYOUT:
3431                 rc = MDT_IT_LAYOUT;
3432                 break;
3433         case IT_QUOTA_DQACQ:
3434         case IT_QUOTA_CONN:
3435                 rc = MDT_IT_QUOTA;
3436                 break;
3437         default:
3438                 CERROR("Unknown intent opcode: %ld\n", itcode);
3439                 rc = -EINVAL;
3440                 break;
3441         }
3442         return rc;
3443 }
3444
3445 static int mdt_intent_opc(long itopc, struct mdt_thread_info *info,
3446                           struct ldlm_lock **lockp, __u64 flags)
3447 {
3448         struct req_capsule   *pill;
3449         struct mdt_it_flavor *flv;
3450         int opc;
3451         int rc;
3452         ENTRY;
3453
3454         opc = mdt_intent_code(itopc);
3455         if (opc < 0)
3456                 RETURN(-EINVAL);
3457
3458         pill = info->mti_pill;
3459
3460         if (opc == MDT_IT_QUOTA) {
3461                 struct lu_device *qmt = info->mti_mdt->mdt_qmt_dev;
3462
3463                 if (qmt == NULL)
3464                         RETURN(-EOPNOTSUPP);
3465
3466                 (*lockp)->l_lvb_type = LVB_T_LQUOTA;
3467                 /* pass the request to quota master */
3468                 rc = qmt_hdls.qmth_intent_policy(info->mti_env, qmt,
3469                                                  mdt_info_req(info), lockp,
3470                                                  flags);
3471                 RETURN(rc);
3472         }
3473
3474         flv  = &mdt_it_flavor[opc];
3475         if (flv->it_fmt != NULL)
3476                 req_capsule_extend(pill, flv->it_fmt);
3477
3478         rc = mdt_unpack_req_pack_rep(info, flv->it_flags);
3479         if (rc == 0) {
3480                 struct ptlrpc_request *req = mdt_info_req(info);
3481                 if (flv->it_flags & MUTABOR &&
3482                     exp_connect_flags(req->rq_export) & OBD_CONNECT_RDONLY)
3483                         RETURN(-EROFS);
3484         }
3485         if (rc == 0 && flv->it_act != NULL) {
3486                 struct ldlm_reply *rep;
3487
3488                 /* execute policy */
3489                 rc = flv->it_act(opc, info, lockp, flags);
3490
3491                 /* Check whether the reply has been packed successfully. */
3492                 if (mdt_info_req(info)->rq_repmsg != NULL) {
3493                         rep = req_capsule_server_get(info->mti_pill,
3494                                                      &RMF_DLM_REP);
3495                         rep->lock_policy_res2 =
3496                                 ptlrpc_status_hton(rep->lock_policy_res2);
3497                 }
3498         } else {
3499                 rc = -EPROTO;
3500         }
3501         RETURN(rc);
3502 }
3503
3504 static int mdt_intent_policy(struct ldlm_namespace *ns,
3505                              struct ldlm_lock **lockp, void *req_cookie,
3506                              ldlm_mode_t mode, __u64 flags, void *data)
3507 {
3508         struct tgt_session_info *tsi;
3509         struct mdt_thread_info  *info;
3510         struct ptlrpc_request   *req  =  req_cookie;
3511         struct ldlm_intent      *it;
3512         struct req_capsule      *pill;
3513         int rc;
3514
3515         ENTRY;
3516
3517         LASSERT(req != NULL);
3518
3519         tsi = tgt_ses_info(req->rq_svc_thread->t_env);
3520
3521         info = tsi2mdt_info(tsi);
3522         LASSERT(info != NULL);
3523         pill = info->mti_pill;
3524         LASSERT(pill->rc_req == req);
3525
3526         if (req->rq_reqmsg->lm_bufcount > DLM_INTENT_IT_OFF) {
3527                 req_capsule_extend(pill, &RQF_LDLM_INTENT_BASIC);
3528                 it = req_capsule_client_get(pill, &RMF_LDLM_INTENT);
3529                 if (it != NULL) {
3530                         rc = mdt_intent_opc(it->opc, info, lockp, flags);
3531                         if (rc == 0)
3532                                 rc = ELDLM_OK;
3533
3534                         /* Lock without inodebits makes no sense and will oops
3535                          * later in ldlm. Let's check it now to see if we have
3536                          * ibits corrupted somewhere in mdt_intent_opc().
3537                          * The case for client miss to set ibits has been
3538                          * processed by others. */
3539                         LASSERT(ergo(info->mti_dlm_req->lock_desc.l_resource.\
3540                                         lr_type == LDLM_IBITS,
3541                                      info->mti_dlm_req->lock_desc.\
3542                                         l_policy_data.l_inodebits.bits != 0));
3543                 } else
3544                         rc = err_serious(-EFAULT);
3545         } else {
3546                 /* No intent was provided */
3547                 LASSERT(pill->rc_fmt == &RQF_LDLM_ENQUEUE);
3548                 req_capsule_set_size(pill, &RMF_DLM_LVB, RCL_SERVER, 0);
3549                 rc = req_capsule_server_pack(pill);
3550                 if (rc)
3551                         rc = err_serious(rc);
3552         }
3553         mdt_thread_info_fini(info);
3554         RETURN(rc);
3555 }
3556
3557 static void mdt_deregister_seq_exp(struct mdt_device *mdt)
3558 {
3559         struct seq_server_site  *ss = mdt_seq_site(mdt);
3560
3561         if (ss->ss_node_id == 0)
3562                 return;
3563
3564         if (ss->ss_client_seq != NULL) {
3565                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
3566                 ss->ss_client_seq->lcs_exp = NULL;
3567         }
3568
3569         if (ss->ss_server_fld != NULL) {
3570                 lustre_deregister_lwp_item(&ss->ss_server_fld->lsf_control_exp);
3571                 ss->ss_server_fld->lsf_control_exp = NULL;
3572         }
3573 }
3574
3575 static void mdt_seq_fini_cli(struct mdt_device *mdt)
3576 {
3577         struct seq_server_site *ss = mdt_seq_site(mdt);
3578
3579         if (ss == NULL)
3580                 return;
3581
3582         if (ss->ss_server_seq != NULL)
3583                 seq_server_set_cli(NULL, ss->ss_server_seq, NULL);
3584 }
3585
3586 static int mdt_seq_fini(const struct lu_env *env, struct mdt_device *mdt)
3587 {
3588         mdt_seq_fini_cli(mdt);
3589         mdt_deregister_seq_exp(mdt);
3590
3591         return seq_site_fini(env, mdt_seq_site(mdt));
3592 }
3593
3594 /**
3595  * It will retrieve its FLDB entries from MDT0, and it only happens
3596  * when upgrading existent FS to 2.6 or when local FLDB is corrupted,
3597  * and it needs to refresh FLDB from the MDT0.
3598  **/
3599 static int mdt_register_lwp_callback(void *data)
3600 {
3601         struct lu_env           env;
3602         struct mdt_device       *mdt = data;
3603         struct lu_server_fld    *fld = mdt_seq_site(mdt)->ss_server_fld;
3604         int                     rc;
3605         ENTRY;
3606
3607         LASSERT(mdt_seq_site(mdt)->ss_node_id != 0);
3608
3609         if (!likely(fld->lsf_new))
3610                 RETURN(0);
3611
3612         rc = lu_env_init(&env, LCT_MD_THREAD);
3613         if (rc) {
3614                 CERROR("%s: cannot init env: rc = %d\n", mdt_obd_name(mdt), rc);
3615                 RETURN(rc);
3616         }
3617
3618         rc = fld_update_from_controller(&env, fld);
3619         if (rc != 0) {
3620                 CERROR("%s: cannot update controller: rc = %d\n",
3621                        mdt_obd_name(mdt), rc);
3622                 GOTO(out, rc);
3623         }
3624 out:
3625         lu_env_fini(&env);
3626         RETURN(rc);
3627 }
3628
3629 static int mdt_register_seq_exp(struct mdt_device *mdt)
3630 {
3631         struct seq_server_site  *ss = mdt_seq_site(mdt);
3632         char                    *lwp_name = NULL;
3633         int                     rc;
3634
3635         if (ss->ss_node_id == 0)
3636                 return 0;
3637
3638         OBD_ALLOC(lwp_name, MAX_OBD_NAME);
3639         if (lwp_name == NULL)
3640                 GOTO(out_free, rc = -ENOMEM);
3641
3642         rc = tgt_name2lwp_name(mdt_obd_name(mdt), lwp_name, MAX_OBD_NAME, 0);
3643         if (rc != 0)
3644                 GOTO(out_free, rc);
3645
3646         rc = lustre_register_lwp_item(lwp_name, &ss->ss_client_seq->lcs_exp,
3647                                       NULL, NULL);
3648         if (rc != 0)
3649                 GOTO(out_free, rc);
3650
3651         rc = lustre_register_lwp_item(lwp_name,
3652                                       &ss->ss_server_fld->lsf_control_exp,
3653                                       mdt_register_lwp_callback, mdt);
3654         if (rc != 0) {
3655                 lustre_deregister_lwp_item(&ss->ss_client_seq->lcs_exp);
3656                 ss->ss_client_seq->lcs_exp = NULL;
3657                 GOTO(out_free, rc);
3658         }
3659 out_free:
3660         if (lwp_name != NULL)
3661                 OBD_FREE(lwp_name, MAX_OBD_NAME);
3662
3663         return rc;
3664 }
3665
3666 /*
3667  * Init client sequence manager which is used by local MDS to talk to sequence
3668  * controller on remote node.
3669  */
3670 static int mdt_seq_init_cli(const struct lu_env *env, struct mdt_device *mdt)
3671 {
3672         struct seq_server_site  *ss = mdt_seq_site(mdt);
3673         int                     rc;
3674         char                    *prefix;
3675         ENTRY;
3676
3677         /* check if this is adding the first MDC and controller is not yet
3678          * initialized. */
3679         OBD_ALLOC_PTR(ss->ss_client_seq);
3680         if (ss->ss_client_seq == NULL)
3681                 RETURN(-ENOMEM);
3682
3683         OBD_ALLOC(prefix, MAX_OBD_NAME + 5);
3684         if (prefix == NULL) {
3685                 OBD_FREE_PTR(ss->ss_client_seq);
3686                 ss->ss_client_seq = NULL;
3687                 RETURN(-ENOMEM);
3688         }
3689
3690         /* Note: seq_client_fini will be called in seq_site_fini */
3691         snprintf(prefix, MAX_OBD_NAME + 5, "ctl-%s", mdt_obd_name(mdt));
3692         rc = seq_client_init(ss->ss_client_seq, NULL, LUSTRE_SEQ_METADATA,
3693                              prefix, ss->ss_node_id == 0 ?  ss->ss_control_seq :
3694                                                             NULL);
3695         OBD_FREE(prefix, MAX_OBD_NAME + 5);
3696         if (rc != 0) {
3697                 OBD_FREE_PTR(ss->ss_client_seq);
3698                 ss->ss_client_seq = NULL;
3699                 RETURN(rc);
3700         }
3701
3702         rc = seq_server_set_cli(env, ss->ss_server_seq, ss->ss_client_seq);
3703
3704         RETURN(rc);
3705 }
3706
3707 static int mdt_seq_init(const struct lu_env *env, struct mdt_device *mdt)
3708 {
3709         struct seq_server_site  *ss;
3710         int                     rc;
3711         ENTRY;
3712
3713         ss = mdt_seq_site(mdt);
3714         /* init sequence controller server(MDT0) */
3715         if (ss->ss_node_id == 0) {
3716                 OBD_ALLOC_PTR(ss->ss_control_seq);
3717                 if (ss->ss_control_seq == NULL)
3718                         RETURN(-ENOMEM);
3719
3720                 rc = seq_server_init(env, ss->ss_control_seq, mdt->mdt_bottom,
3721                                      mdt_obd_name(mdt), LUSTRE_SEQ_CONTROLLER,
3722                                      ss);
3723                 if (rc)
3724                         GOTO(out_seq_fini, rc);
3725         }
3726
3727         /* Init normal sequence server */
3728         OBD_ALLOC_PTR(ss->ss_server_seq);
3729         if (ss->ss_server_seq == NULL)
3730                 GOTO(out_seq_fini, rc = -ENOMEM);
3731
3732         rc = seq_server_init(env, ss->ss_server_seq, mdt->mdt_bottom,
3733                              mdt_obd_name(mdt), LUSTRE_SEQ_SERVER, ss);
3734         if (rc)
3735                 GOTO(out_seq_fini, rc);
3736
3737         /* init seq client for seq server to talk to seq controller(MDT0) */
3738         rc = mdt_seq_init_cli(env, mdt);
3739         if (rc != 0)
3740                 GOTO(out_seq_fini, rc);
3741
3742         if (ss->ss_node_id != 0)
3743                 /* register controler export through lwp */
3744                 rc = mdt_register_seq_exp(mdt);
3745
3746         EXIT;
3747 out_seq_fini:
3748         if (rc)
3749                 mdt_seq_fini(env, mdt);
3750
3751         return rc;
3752 }
3753
3754 /*
3755  * FLD wrappers
3756  */
3757 static int mdt_fld_fini(const struct lu_env *env,
3758                         struct mdt_device *m)
3759 {
3760         struct seq_server_site *ss = mdt_seq_site(m);
3761         ENTRY;
3762
3763         if (ss && ss->ss_server_fld) {
3764                 fld_server_fini(env, ss->ss_server_fld);
3765                 OBD_FREE_PTR(ss->ss_server_fld);
3766                 ss->ss_server_fld = NULL;
3767         }
3768
3769         RETURN(0);
3770 }
3771
3772 static int mdt_fld_init(const struct lu_env *env,
3773                         const char *uuid,
3774                         struct mdt_device *m)
3775 {
3776         struct seq_server_site *ss;
3777         int rc;
3778         ENTRY;
3779
3780         ss = mdt_seq_site(m);
3781
3782         OBD_ALLOC_PTR(ss->ss_server_fld);
3783         if (ss->ss_server_fld == NULL)
3784                 RETURN(rc = -ENOMEM);
3785
3786         rc = fld_server_init(env, ss->ss_server_fld, m->mdt_bottom, uuid,
3787                              LU_SEQ_RANGE_MDT);
3788         if (rc) {
3789                 OBD_FREE_PTR(ss->ss_server_fld);
3790                 ss->ss_server_fld = NULL;
3791                 RETURN(rc);
3792         }
3793
3794         RETURN(0);
3795 }
3796
3797 static void mdt_stack_pre_fini(const struct lu_env *env,
3798                            struct mdt_device *m, struct lu_device *top)
3799 {
3800         struct lustre_cfg_bufs  *bufs;
3801         struct lustre_cfg       *lcfg;
3802         struct mdt_thread_info  *info;
3803         ENTRY;
3804
3805         LASSERT(top);
3806
3807         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3808         LASSERT(info != NULL);
3809
3810         bufs = &info->mti_u.bufs;
3811
3812         LASSERT(m->mdt_child_exp);
3813         LASSERT(m->mdt_child_exp->exp_obd);
3814
3815         /* process cleanup, pass mdt obd name to get obd umount flags */
3816         /* XXX: this is needed because all layers are referenced by
3817          * objects (some of them are pinned by osd, for example *
3818          * the proper solution should be a model where object used
3819          * by osd only doesn't have mdt/mdd slices -bzzz */
3820         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
3821         lustre_cfg_bufs_set_string(bufs, 1, NULL);
3822         lcfg = lustre_cfg_new(LCFG_PRE_CLEANUP, bufs);
3823         if (!lcfg) {
3824                 CERROR("%s:Cannot alloc lcfg!\n", mdt_obd_name(m));
3825                 return;
3826         }
3827         top->ld_ops->ldo_process_config(env, top, lcfg);
3828         lustre_cfg_free(lcfg);
3829         EXIT;
3830 }
3831
3832 static void mdt_stack_fini(const struct lu_env *env,
3833                            struct mdt_device *m, struct lu_device *top)
3834 {
3835         struct obd_device       *obd = mdt2obd_dev(m);
3836         struct lustre_cfg_bufs  *bufs;
3837         struct lustre_cfg       *lcfg;
3838         struct mdt_thread_info  *info;
3839         char                     flags[3] = "";
3840         ENTRY;
3841
3842         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
3843         LASSERT(info != NULL);
3844
3845         lu_dev_del_linkage(top->ld_site, top);
3846
3847         lu_site_purge(env, top->ld_site, -1);
3848
3849         bufs = &info->mti_u.bufs;
3850         /* process cleanup, pass mdt obd name to get obd umount flags */
3851         /* another purpose is to let all layers to release their objects */
3852         lustre_cfg_bufs_reset(bufs, mdt_obd_name(m));
3853         if (obd->obd_force)
3854                 strcat(flags, "F");
3855         if (obd->obd_fail)
3856                 strcat(flags, "A");
3857         lustre_cfg_bufs_set_string(bufs, 1, flags);
3858         lcfg = lustre_cfg_new(LCFG_CLEANUP, bufs);
3859         if (!lcfg) {
3860                 CERROR("Cannot alloc lcfg!\n");
3861                 return;
3862         }
3863         LASSERT(top);
3864         top->ld_ops->ldo_process_config(env, top, lcfg);
3865         lustre_cfg_free(lcfg);
3866
3867         lu_site_purge(env, top->ld_site, -1);
3868
3869         m->mdt_child = NULL;
3870         m->mdt_bottom = NULL;
3871
3872         obd_disconnect(m->mdt_child_exp);
3873         m->mdt_child_exp = NULL;
3874
3875         obd_disconnect(m->mdt_bottom_exp);
3876         m->mdt_child_exp = NULL;
3877 }
3878
3879 static int mdt_connect_to_next(const struct lu_env *env, struct mdt_device *m,
3880                                const char *next, struct obd_export **exp)
3881 {
3882         struct obd_connect_data *data = NULL;
3883         struct obd_device       *obd;
3884         int                      rc;
3885         ENTRY;
3886
3887         OBD_ALLOC_PTR(data);
3888         if (data == NULL)
3889                 GOTO(out, rc = -ENOMEM);
3890
3891         obd = class_name2obd(next);
3892         if (obd == NULL) {
3893                 CERROR("%s: can't locate next device: %s\n",
3894                        mdt_obd_name(m), next);
3895                 GOTO(out, rc = -ENOTCONN);
3896         }
3897
3898         data->ocd_connect_flags = OBD_CONNECT_VERSION;
3899         data->ocd_version = LUSTRE_VERSION_CODE;
3900
3901         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
3902         if (rc) {
3903                 CERROR("%s: cannot connect to next dev %s (%d)\n",
3904                        mdt_obd_name(m), next, rc);
3905                 GOTO(out, rc);
3906         }
3907
3908 out:
3909         if (data)
3910                 OBD_FREE_PTR(data);
3911         RETURN(rc);
3912 }
3913
3914 static int mdt_stack_init(const struct lu_env *env, struct mdt_device *mdt,
3915                           struct lustre_cfg *cfg)
3916 {
3917         char                   *dev = lustre_cfg_string(cfg, 0);
3918         int                     rc, name_size, uuid_size;
3919         char                   *name, *uuid, *p;
3920         struct lustre_cfg_bufs *bufs;
3921         struct lustre_cfg      *lcfg;
3922         struct obd_device      *obd;
3923         struct lustre_profile  *lprof;
3924         struct lu_site         *site;
3925         ENTRY;
3926
3927         /* in 1.8 we had the only device in the stack - MDS.
3928          * 2.0 introduces MDT, MDD, OSD; MDT starts others internally.
3929          * in 2.3 OSD is instantiated by obd_mount.c, so we need
3930          * to generate names and setup MDT, MDD. MDT will be using
3931          * generated name to connect to MDD. for MDD the next device
3932          * will be LOD with name taken from so called "profile" which
3933          * is generated by mount_option line
3934          *
3935          * 1.8 MGS generates config. commands like this:
3936          *   #06 (104)mount_option 0:  1:lustre-MDT0000  2:lustre-mdtlov
3937          *   #08 (120)setup   0:lustre-MDT0000  1:dev 2:type 3:lustre-MDT0000
3938          * 2.0 MGS generates config. commands like this:
3939          *   #07 (112)mount_option 0:  1:lustre-MDT0000  2:lustre-MDT0000-mdtlov
3940          *   #08 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
3941          *                    3:lustre-MDT0000-mdtlov  4:f
3942          *
3943          * we generate MDD name from MDT one, just replacing T with D
3944          *
3945          * after all the preparations, the logical equivalent will be
3946          *   #01 (160)setup   0:lustre-MDD0000  1:lustre-MDD0000_UUID  2:0
3947          *                    3:lustre-MDT0000-mdtlov  4:f
3948          *   #02 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
3949          *                    3:lustre-MDD0000  4:f
3950          *
3951          *  notice we build the stack from down to top: MDD first, then MDT */
3952
3953         name_size = MAX_OBD_NAME;
3954         uuid_size = MAX_OBD_NAME;
3955
3956         OBD_ALLOC(name, name_size);
3957         OBD_ALLOC(uuid, uuid_size);
3958         if (name == NULL || uuid == NULL)
3959                 GOTO(cleanup_mem, rc = -ENOMEM);
3960
3961         OBD_ALLOC_PTR(bufs);
3962         if (!bufs)
3963                 GOTO(cleanup_mem, rc = -ENOMEM);
3964
3965         strcpy(name, dev);
3966         p = strstr(name, "-MDT");
3967         if (p == NULL)
3968                 GOTO(free_bufs, rc = -ENOMEM);
3969         p[3] = 'D';
3970
3971         snprintf(uuid, MAX_OBD_NAME, "%s_UUID", name);
3972
3973         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
3974         if (lprof == NULL || lprof->lp_dt == NULL) {
3975                 CERROR("can't find the profile: %s\n",
3976                        lustre_cfg_string(cfg, 0));
3977                 GOTO(free_bufs, rc = -EINVAL);
3978         }
3979
3980         lustre_cfg_bufs_reset(bufs, name);
3981         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_MDD_NAME);
3982         lustre_cfg_bufs_set_string(bufs, 2, uuid);
3983         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
3984
3985         lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
3986         if (!lcfg)
3987                 GOTO(free_bufs, rc = -ENOMEM);
3988
3989         rc = class_attach(lcfg);
3990         if (rc)
3991                 GOTO(lcfg_cleanup, rc);
3992
3993         obd = class_name2obd(name);
3994         if (!obd) {
3995                 CERROR("Can not find obd %s (%s in config)\n",
3996                        MDD_OBD_NAME, lustre_cfg_string(cfg, 0));
3997                 GOTO(class_detach, rc = -EINVAL);
3998         }
3999
4000         lustre_cfg_free(lcfg);
4001
4002         lustre_cfg_bufs_reset(bufs, name);
4003         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4004         lustre_cfg_bufs_set_string(bufs, 2, dev);
4005         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4006
4007         lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
4008
4009         rc = class_setup(obd, lcfg);
4010         if (rc)
4011                 GOTO(class_detach, rc);
4012
4013         /* connect to MDD we just setup */
4014         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_child_exp);
4015         if (rc)
4016                 GOTO(class_detach, rc);
4017
4018         site = mdt->mdt_child_exp->exp_obd->obd_lu_dev->ld_site;
4019         LASSERT(site);
4020         LASSERT(mdt_lu_site(mdt) == NULL);
4021         mdt->mdt_lu_dev.ld_site = site;
4022         site->ls_top_dev = &mdt->mdt_lu_dev;
4023         mdt->mdt_child = lu2md_dev(mdt->mdt_child_exp->exp_obd->obd_lu_dev);
4024
4025         /* now connect to bottom OSD */
4026         snprintf(name, MAX_OBD_NAME, "%s-osd", dev);
4027         rc = mdt_connect_to_next(env, mdt, name, &mdt->mdt_bottom_exp);
4028         if (rc)
4029                 GOTO(class_detach, rc);
4030         mdt->mdt_bottom =
4031                 lu2dt_dev(mdt->mdt_bottom_exp->exp_obd->obd_lu_dev);
4032
4033         rc = lu_env_refill((struct lu_env *)env);
4034         if (rc != 0)
4035                 CERROR("Failure to refill session: '%d'\n", rc);
4036
4037         lu_dev_add_linkage(site, &mdt->mdt_lu_dev);
4038
4039         EXIT;
4040 class_detach:
4041         if (rc)
4042                 class_detach(obd, lcfg);
4043 lcfg_cleanup:
4044         lustre_cfg_free(lcfg);
4045 free_bufs:
4046         OBD_FREE_PTR(bufs);
4047 cleanup_mem:
4048         if (name)
4049                 OBD_FREE(name, name_size);
4050         if (uuid)
4051                 OBD_FREE(uuid, uuid_size);
4052         RETURN(rc);
4053 }
4054
4055 /* setup quota master target on MDT0 */
4056 static int mdt_quota_init(const struct lu_env *env, struct mdt_device *mdt,
4057                           struct lustre_cfg *cfg)
4058 {
4059         struct obd_device       *obd;
4060         char                    *dev = lustre_cfg_string(cfg, 0);
4061         char                    *qmtname, *uuid, *p;
4062         struct lustre_cfg_bufs  *bufs;
4063         struct lustre_cfg       *lcfg;
4064         struct lustre_profile   *lprof;
4065         struct obd_connect_data *data;
4066         int                      rc;
4067         ENTRY;
4068
4069         LASSERT(mdt->mdt_qmt_exp == NULL);
4070         LASSERT(mdt->mdt_qmt_dev == NULL);
4071
4072         /* quota master is on MDT0 only for now */
4073         if (mdt->mdt_seq_site.ss_node_id != 0)
4074                 RETURN(0);
4075
4076         /* MGS generates config commands which look as follows:
4077          *   #01 (160)setup   0:lustre-MDT0000  1:lustre-MDT0000_UUID  2:0
4078          *                    3:lustre-MDT0000-mdtlov  4:f
4079          *
4080          * We generate the QMT name from the MDT one, just replacing MD with QM
4081          * after all the preparations, the logical equivalent will be:
4082          *   #01 (160)setup   0:lustre-QMT0000  1:lustre-QMT0000_UUID  2:0
4083          *                    3:lustre-MDT0000-osd  4:f */
4084         OBD_ALLOC(qmtname, MAX_OBD_NAME);
4085         OBD_ALLOC(uuid, UUID_MAX);
4086         OBD_ALLOC_PTR(bufs);
4087         OBD_ALLOC_PTR(data);
4088         if (qmtname == NULL || uuid == NULL || bufs == NULL || data == NULL)
4089                 GOTO(cleanup_mem, rc = -ENOMEM);
4090
4091         strcpy(qmtname, dev);
4092         p = strstr(qmtname, "-MDT");
4093         if (p == NULL)
4094                 GOTO(cleanup_mem, rc = -ENOMEM);
4095         /* replace MD with QM */
4096         p[1] = 'Q';
4097         p[2] = 'M';
4098
4099         snprintf(uuid, UUID_MAX, "%s_UUID", qmtname);
4100
4101         lprof = class_get_profile(lustre_cfg_string(cfg, 0));
4102         if (lprof == NULL || lprof->lp_dt == NULL) {
4103                 CERROR("can't find profile for %s\n",
4104                        lustre_cfg_string(cfg, 0));
4105                 GOTO(cleanup_mem, rc = -EINVAL);
4106         }
4107
4108         lustre_cfg_bufs_reset(bufs, qmtname);
4109         lustre_cfg_bufs_set_string(bufs, 1, LUSTRE_QMT_NAME);
4110         lustre_cfg_bufs_set_string(bufs, 2, uuid);
4111         lustre_cfg_bufs_set_string(bufs, 3, lprof->lp_dt);
4112
4113         lcfg = lustre_cfg_new(LCFG_ATTACH, bufs);
4114         if (!lcfg)
4115                 GOTO(cleanup_mem, rc = -ENOMEM);
4116
4117         rc = class_attach(lcfg);
4118         if (rc)
4119                 GOTO(lcfg_cleanup, rc);
4120
4121         obd = class_name2obd(qmtname);
4122         if (!obd) {
4123                 CERROR("Can not find obd %s (%s in config)\n", qmtname,
4124                        lustre_cfg_string(cfg, 0));
4125                 GOTO(class_detach, rc = -EINVAL);
4126         }
4127
4128         lustre_cfg_free(lcfg);
4129
4130         lustre_cfg_bufs_reset(bufs, qmtname);
4131         lustre_cfg_bufs_set_string(bufs, 1, uuid);
4132         lustre_cfg_bufs_set_string(bufs, 2, dev);
4133
4134         /* for quota, the next device should be the OSD device */
4135         lustre_cfg_bufs_set_string(bufs, 3,
4136                                    mdt->mdt_bottom->dd_lu_dev.ld_obd->obd_name);
4137
4138         lcfg = lustre_cfg_new(LCFG_SETUP, bufs);
4139
4140         rc = class_setup(obd, lcfg);
4141         if (rc)
4142                 GOTO(class_detach, rc);
4143
4144         mdt->mdt_qmt_dev = obd->obd_lu_dev;
4145
4146         /* configure local quota objects */
4147         rc = mdt->mdt_qmt_dev->ld_ops->ldo_prepare(env,
4148                                                    &mdt->mdt_lu_dev,
4149                                                    mdt->mdt_qmt_dev);
4150         if (rc)
4151                 GOTO(class_cleanup, rc);
4152
4153         /* connect to quota master target */
4154         data->ocd_connect_flags = OBD_CONNECT_VERSION;
4155         data->ocd_version = LUSTRE_VERSION_CODE;
4156         rc = obd_connect(NULL, &mdt->mdt_qmt_exp, obd, &obd->obd_uuid,
4157                          data, NULL);
4158         if (rc) {
4159                 CERROR("cannot connect to quota master device %s (%d)\n",
4160                        qmtname, rc);
4161                 GOTO(class_cleanup, rc);
4162         }
4163
4164         EXIT;
4165 class_cleanup:
4166         if (rc) {
4167                 class_manual_cleanup(obd);
4168                 mdt->mdt_qmt_dev = NULL;
4169         }
4170 class_detach:
4171         if (rc)
4172                 class_detach(obd, lcfg);
4173 lcfg_cleanup:
4174         lustre_cfg_free(lcfg);
4175 cleanup_mem:
4176         if (bufs)
4177                 OBD_FREE_PTR(bufs);
4178         if (qmtname)
4179                 OBD_FREE(qmtname, MAX_OBD_NAME);
4180         if (uuid)
4181                 OBD_FREE(uuid, UUID_MAX);
4182         if (data)
4183                 OBD_FREE_PTR(data);
4184         return rc;
4185 }
4186
4187 /* Shutdown quota master target associated with mdt */
4188 static void mdt_quota_fini(const struct lu_env *env, struct mdt_device *mdt)
4189 {
4190         ENTRY;
4191
4192         if (mdt->mdt_qmt_exp == NULL)
4193                 RETURN_EXIT;
4194         LASSERT(mdt->mdt_qmt_dev != NULL);
4195
4196         /* the qmt automatically shuts down when the mdt disconnects */
4197         obd_disconnect(mdt->mdt_qmt_exp);
4198         mdt->mdt_qmt_exp = NULL;
4199         mdt->mdt_qmt_dev = NULL;
4200         EXIT;
4201 }
4202
4203 /* mdt_getxattr() is used from mdt_intent_getxattr(), use this wrapper
4204  * for now. This will be removed along with converting rest of MDT code
4205  * to use tgt_session_info */
4206 int mdt_tgt_getxattr(struct tgt_session_info *tsi)
4207 {
4208         struct mdt_thread_info  *info = tsi2mdt_info(tsi);
4209         int                      rc;
4210
4211         rc = mdt_getxattr(info);
4212
4213         mdt_thread_info_fini(info);
4214         return rc;
4215 }
4216
4217 static struct tgt_handler mdt_tgt_handlers[] = {
4218 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4219                 0,                      MDS_CONNECT,    mdt_tgt_connect,
4220                 &RQF_CONNECT, LUSTRE_OBD_VERSION),
4221 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4222                 0,                      MDS_DISCONNECT, tgt_disconnect,
4223                 &RQF_MDS_DISCONNECT, LUSTRE_OBD_VERSION),
4224 TGT_RPC_HANDLER(MDS_FIRST_OPC,
4225                 HABEO_REFERO,           MDS_SET_INFO,   mdt_set_info,
4226                 &RQF_OBD_SET_INFO, LUSTRE_MDS_VERSION),
4227 TGT_MDT_HDL(0,                          MDS_GET_INFO,   mdt_get_info),
4228 TGT_MDT_HDL(0           | HABEO_REFERO, MDS_GETSTATUS,  mdt_getstatus),
4229 TGT_MDT_HDL(HABEO_CORPUS,               MDS_GETATTR,    mdt_getattr),
4230 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_GETATTR_NAME,
4231                                                         mdt_getattr_name),
4232 TGT_MDT_HDL(HABEO_CORPUS,               MDS_GETXATTR,   mdt_tgt_getxattr),
4233 TGT_MDT_HDL(0           | HABEO_REFERO, MDS_STATFS,     mdt_statfs),
4234 TGT_MDT_HDL(0           | MUTABOR,      MDS_REINT,      mdt_reint),
4235 TGT_MDT_HDL(HABEO_CORPUS,               MDS_CLOSE,      mdt_close),
4236 TGT_MDT_HDL(HABEO_CORPUS,               MDS_DONE_WRITING,
4237                                                         mdt_done_writing),
4238 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_READPAGE,   mdt_readpage),
4239 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_SYNC,       mdt_sync),
4240 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_IS_SUBDIR,  mdt_is_subdir),
4241 TGT_MDT_HDL(0,                          MDS_QUOTACTL,   mdt_quotactl),
4242 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_PROGRESS,
4243                                                         mdt_hsm_progress),
4244 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_CT_REGISTER,
4245                                                         mdt_hsm_ct_register),
4246 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_CT_UNREGISTER,
4247                                                         mdt_hsm_ct_unregister),
4248 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_STATE_GET,
4249                                                         mdt_hsm_state_get),
4250 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO | MUTABOR, MDS_HSM_STATE_SET,
4251                                                         mdt_hsm_state_set),
4252 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_ACTION, mdt_hsm_action),
4253 TGT_MDT_HDL(HABEO_CORPUS| HABEO_REFERO, MDS_HSM_REQUEST,
4254                                                         mdt_hsm_request),
4255 TGT_MDT_HDL(HABEO_CLAVIS | HABEO_CORPUS | HABEO_REFERO | MUTABOR,
4256             MDS_SWAP_LAYOUTS,
4257             mdt_swap_layouts),
4258 };
4259
4260 static struct tgt_handler mdt_sec_ctx_ops[] = {
4261 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT,     mdt_sec_ctx_handle),
4262 TGT_SEC_HDL_VAR(0,                      SEC_CTX_INIT_CONT,mdt_sec_ctx_handle),
4263 TGT_SEC_HDL_VAR(0,                      SEC_CTX_FINI,     mdt_sec_ctx_handle)
4264 };
4265
4266 static struct tgt_handler mdt_quota_ops[] = {
4267 TGT_QUOTA_HDL(HABEO_REFERO,             QUOTA_DQACQ,      mdt_quota_dqacq),
4268 };
4269
4270 static struct tgt_opc_slice mdt_common_slice[] = {
4271         {
4272                 .tos_opc_start  = MDS_FIRST_OPC,
4273                 .tos_opc_end    = MDS_LAST_OPC,
4274                 .tos_hs         = mdt_tgt_handlers
4275         },
4276         {
4277                 .tos_opc_start  = OBD_FIRST_OPC,
4278                 .tos_opc_end    = OBD_LAST_OPC,
4279                 .tos_hs         = tgt_obd_handlers
4280         },
4281         {
4282                 .tos_opc_start  = LDLM_FIRST_OPC,
4283                 .tos_opc_end    = LDLM_LAST_OPC,
4284                 .tos_hs         = tgt_dlm_handlers
4285         },
4286         {
4287                 .tos_opc_start  = SEC_FIRST_OPC,
4288                 .tos_opc_end    = SEC_LAST_OPC,
4289                 .tos_hs         = mdt_sec_ctx_ops
4290         },
4291         {
4292                 .tos_opc_start  = OUT_UPDATE_FIRST_OPC,
4293                 .tos_opc_end    = OUT_UPDATE_LAST_OPC,
4294                 .tos_hs         = tgt_out_handlers
4295         },
4296         {
4297                 .tos_opc_start  = FLD_FIRST_OPC,
4298                 .tos_opc_end    = FLD_LAST_OPC,
4299                 .tos_hs         = fld_handlers
4300         },
4301         {
4302                 .tos_opc_start  = SEQ_FIRST_OPC,
4303                 .tos_opc_end    = SEQ_LAST_OPC,
4304                 .tos_hs         = seq_handlers
4305         },
4306         {
4307                 .tos_opc_start  = QUOTA_DQACQ,
4308                 .tos_opc_end    = QUOTA_LAST_OPC,
4309                 .tos_hs         = mdt_quota_ops
4310         },
4311         {
4312                 .tos_opc_start  = LLOG_FIRST_OPC,
4313                 .tos_opc_end    = LLOG_LAST_OPC,
4314                 .tos_hs         = tgt_llog_handlers
4315         },
4316         {
4317                 .tos_opc_start  = LFSCK_FIRST_OPC,
4318                 .tos_opc_end    = LFSCK_LAST_OPC,
4319                 .tos_hs         = tgt_lfsck_handlers
4320         },
4321
4322         {
4323                 .tos_hs         = NULL
4324         }
4325 };
4326
4327 static void mdt_fini(const struct lu_env *env, struct mdt_device *m)
4328 {
4329         struct md_device        *next = m->mdt_child;
4330         struct lu_device        *d    = &m->mdt_lu_dev;
4331         struct obd_device       *obd  = mdt2obd_dev(m);
4332         struct lfsck_stop        stop;
4333         ENTRY;
4334
4335         stop.ls_status = LS_PAUSED;
4336         stop.ls_flags = 0;
4337         next->md_ops->mdo_iocontrol(env, next, OBD_IOC_STOP_LFSCK, 0, &stop);
4338
4339         target_recovery_fini(obd);
4340         ping_evictor_stop();
4341         mdt_stack_pre_fini(env, m, md2lu_dev(m->mdt_child));
4342
4343         if (m->mdt_opts.mo_coordinator)
4344                 mdt_hsm_cdt_stop(m);
4345
4346         mdt_hsm_cdt_fini(m);
4347
4348         mdt_llog_ctxt_unclone(env, m, LLOG_AGENT_ORIG_CTXT);
4349         mdt_llog_ctxt_unclone(env, m, LLOG_CHANGELOG_ORIG_CTXT);
4350         obd_exports_barrier(obd);
4351         obd_zombie_barrier();
4352
4353         mdt_procfs_fini(m);
4354
4355         tgt_fini(env, &m->mdt_lut);
4356         mdt_fs_cleanup(env, m);
4357         upcall_cache_cleanup(m->mdt_identity_cache);
4358         m->mdt_identity_cache = NULL;
4359
4360         if (m->mdt_namespace != NULL) {
4361                 ldlm_namespace_free(m->mdt_namespace, NULL,
4362                                     d->ld_obd->obd_force);
4363                 d->ld_obd->obd_namespace = m->mdt_namespace = NULL;
4364         }
4365
4366         mdt_quota_fini(env, m);
4367
4368         cfs_free_nidlist(&m->mdt_nosquash_nids);
4369         if (m->mdt_nosquash_str) {
4370                 OBD_FREE(m->mdt_nosquash_str, m->mdt_nosquash_strlen);
4371                 m->mdt_nosquash_str = NULL;
4372                 m->mdt_nosquash_strlen = 0;
4373         }
4374
4375         mdt_seq_fini(env, m);
4376         mdt_fld_fini(env, m);
4377
4378         next->md_ops->mdo_init_capa_ctxt(env, next, 0, 0, 0, NULL);
4379         cfs_timer_disarm(&m->mdt_ck_timer);
4380         mdt_ck_thread_stop(m);
4381
4382         /*
4383          * Finish the stack
4384          */
4385         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4386
4387         LASSERT(atomic_read(&d->ld_ref) == 0);
4388
4389         server_put_mount(mdt_obd_name(m));
4390
4391         EXIT;
4392 }
4393
4394 static int mdt_postrecov(const struct lu_env *, struct mdt_device *);
4395
4396 static int mdt_init0(const struct lu_env *env, struct mdt_device *m,
4397                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
4398 {
4399         struct mdt_thread_info    *info;
4400         struct obd_device         *obd;
4401         const char                *dev = lustre_cfg_string(cfg, 0);
4402         const char                *num = lustre_cfg_string(cfg, 2);
4403         struct lustre_mount_info  *lmi = NULL;
4404         struct lustre_sb_info     *lsi;
4405         struct lu_site            *s;
4406         struct seq_server_site    *ss_site;
4407         const char                *identity_upcall = "NONE";
4408         struct md_device          *next;
4409         int                        rc;
4410         long                       node_id;
4411         mntopt_t                   mntopts;
4412         ENTRY;
4413
4414         lu_device_init(&m->mdt_lu_dev, ldt);
4415         /*
4416          * Environment (env) might be missing mdt_thread_key values at that
4417          * point, if device is allocated when mdt_thread_key is in QUIESCENT
4418          * mode.
4419          *
4420          * Usually device allocation path doesn't use module key values, but
4421          * mdt has to do a lot of work here, so allocate key value.
4422          */
4423         rc = lu_env_refill((struct lu_env *)env);
4424         if (rc != 0)
4425                 RETURN(rc);
4426
4427         info = lu_context_key_get(&env->le_ctx, &mdt_thread_key);
4428         LASSERT(info != NULL);
4429
4430         obd = class_name2obd(dev);
4431         LASSERT(obd != NULL);
4432
4433         m->mdt_max_mdsize = MAX_MD_SIZE; /* 4 stripes */
4434
4435         m->mdt_som_conf = 0;
4436
4437         m->mdt_opts.mo_cos = MDT_COS_DEFAULT;
4438
4439         /* default is coordinator off, it is started through conf_param
4440          * or /proc */
4441         m->mdt_opts.mo_coordinator = 0;
4442
4443         lmi = server_get_mount(dev);
4444         if (lmi == NULL) {
4445                 CERROR("Cannot get mount info for %s!\n", dev);
4446                 RETURN(-EFAULT);
4447         } else {
4448                 lsi = s2lsi(lmi->lmi_sb);
4449                 /* CMD is supported only in IAM mode */
4450                 LASSERT(num);
4451                 node_id = simple_strtol(num, NULL, 10);
4452                 obd->u.obt.obt_magic = OBT_MAGIC;
4453         }
4454
4455         spin_lock_init(&m->mdt_ioepoch_lock);
4456         m->mdt_capa_timeout = CAPA_TIMEOUT;
4457         m->mdt_capa_alg = CAPA_HMAC_ALG_SHA1;
4458         m->mdt_ck_timeout = CAPA_KEY_TIMEOUT;
4459         m->mdt_squash_uid = 0;
4460         m->mdt_squash_gid = 0;
4461         CFS_INIT_LIST_HEAD(&m->mdt_nosquash_nids);
4462         m->mdt_nosquash_str = NULL;
4463         m->mdt_nosquash_strlen = 0;
4464         init_rwsem(&m->mdt_squash_sem);
4465         spin_lock_init(&m->mdt_osfs_lock);
4466         m->mdt_osfs_age = cfs_time_shift_64(-1000);
4467         m->mdt_enable_remote_dir = 0;
4468         m->mdt_enable_remote_dir_gid = 0;
4469
4470         m->mdt_lu_dev.ld_ops = &mdt_lu_ops;
4471         m->mdt_lu_dev.ld_obd = obd;
4472         /* Set this lu_device to obd for error handling purposes. */
4473         obd->obd_lu_dev = &m->mdt_lu_dev;
4474
4475         /* init the stack */
4476         rc = mdt_stack_init((struct lu_env *)env, m, cfg);
4477         if (rc) {
4478                 CERROR("%s: Can't init device stack, rc %d\n",
4479                        mdt_obd_name(m), rc);
4480                 GOTO(err_lmi, rc);
4481         }
4482
4483         s = mdt_lu_site(m);
4484         ss_site = mdt_seq_site(m);
4485         s->ld_seq_site = ss_site;
4486         ss_site->ss_lu = s;
4487
4488         /* set server index */
4489         ss_site->ss_node_id = node_id;
4490
4491         /* failover is the default
4492          * FIXME: we do not failout mds0/mgs, which may cause some problems.
4493          * assumed whose ss_node_id == 0 XXX
4494          * */
4495         obd->obd_replayable = 1;
4496         /* No connection accepted until configurations will finish */
4497         obd->obd_no_conn = 1;
4498
4499         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
4500                 char *str = lustre_cfg_string(cfg, 4);
4501                 if (strchr(str, 'n')) {
4502                         CWARN("%s: recovery disabled\n", mdt_obd_name(m));
4503                         obd->obd_replayable = 0;
4504                 }
4505         }
4506
4507         rc = mdt_fld_init(env, mdt_obd_name(m), m);
4508         if (rc)
4509                 GOTO(err_fini_stack, rc);
4510
4511         rc = mdt_seq_init(env, m);
4512         if (rc)
4513                 GOTO(err_fini_fld, rc);
4514
4515         snprintf(info->mti_u.ns_name, sizeof(info->mti_u.ns_name), "%s-%s",
4516                  LUSTRE_MDT_NAME, obd->obd_uuid.uuid);
4517         m->mdt_namespace = ldlm_namespace_new(obd, info->mti_u.ns_name,
4518                                               LDLM_NAMESPACE_SERVER,
4519                                               LDLM_NAMESPACE_GREEDY,
4520                                               LDLM_NS_TYPE_MDT);
4521         if (m->mdt_namespace == NULL)
4522                 GOTO(err_fini_seq, rc = -ENOMEM);
4523
4524         m->mdt_namespace->ns_lvbp = m;
4525         m->mdt_namespace->ns_lvbo = &mdt_lvbo;
4526
4527         ldlm_register_intent(m->mdt_namespace, mdt_intent_policy);
4528         /* set obd_namespace for compatibility with old code */
4529         obd->obd_namespace = m->mdt_namespace;
4530
4531         cfs_timer_init(&m->mdt_ck_timer, mdt_ck_timer_callback, m);
4532
4533         rc = mdt_hsm_cdt_init(m);
4534         if (rc != 0) {
4535                 CERROR("%s: error initializing coordinator, rc %d\n",
4536                        mdt_obd_name(m), rc);
4537                 GOTO(err_free_ns, rc);
4538         }
4539
4540         rc = mdt_ck_thread_start(m);
4541         if (rc)
4542                 GOTO(err_free_hsm, rc);
4543
4544         rc = tgt_init(env, &m->mdt_lut, obd, m->mdt_bottom, mdt_common_slice,
4545                       OBD_FAIL_MDS_ALL_REQUEST_NET,
4546                       OBD_FAIL_MDS_ALL_REPLY_NET);
4547         if (rc)
4548                 GOTO(err_capa, rc);
4549
4550         rc = mdt_fs_setup(env, m, obd, lsi);
4551         if (rc)
4552                 GOTO(err_tgt, rc);
4553
4554         tgt_adapt_sptlrpc_conf(&m->mdt_lut, 1);
4555
4556         next = m->mdt_child;
4557         rc = next->md_ops->mdo_iocontrol(env, next, OBD_IOC_GET_MNTOPT, 0,
4558                                          &mntopts);
4559         if (rc)
4560                 GOTO(err_fs_cleanup, rc);
4561
4562         if (mntopts & MNTOPT_USERXATTR)
4563                 m->mdt_opts.mo_user_xattr = 1;
4564         else
4565                 m->mdt_opts.mo_user_xattr = 0;
4566
4567         rc = next->md_ops->mdo_maxeasize_get(env, next, &m->mdt_max_ea_size);
4568         if (rc)
4569                 GOTO(err_fs_cleanup, rc);
4570
4571         if (mntopts & MNTOPT_ACL)
4572                 m->mdt_opts.mo_acl = 1;
4573         else
4574                 m->mdt_opts.mo_acl = 0;
4575
4576         /* XXX: to support suppgid for ACL, we enable identity_upcall
4577          * by default, otherwise, maybe got unexpected -EACCESS. */
4578         if (m->mdt_opts.mo_acl)
4579                 identity_upcall = MDT_IDENTITY_UPCALL_PATH;
4580
4581         m->mdt_identity_cache = upcall_cache_init(mdt_obd_name(m),
4582                                                 identity_upcall,
4583                                                 &mdt_identity_upcall_cache_ops);
4584         if (IS_ERR(m->mdt_identity_cache)) {
4585                 rc = PTR_ERR(m->mdt_identity_cache);
4586                 m->mdt_identity_cache = NULL;
4587                 GOTO(err_fs_cleanup, rc);
4588         }
4589
4590         rc = mdt_procfs_init(m, dev);
4591         if (rc) {
4592                 CERROR("Can't init MDT lprocfs, rc %d\n", rc);
4593                 GOTO(err_recovery, rc);
4594         }
4595
4596         rc = mdt_quota_init(env, m, cfg);
4597         if (rc)
4598                 GOTO(err_procfs, rc);
4599
4600         m->mdt_ldlm_client = &mdt2obd_dev(m)->obd_ldlm_client;
4601         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
4602                            "mdt_ldlm_client", m->mdt_ldlm_client);
4603
4604         ping_evictor_start();
4605
4606         /* recovery will be started upon mdt_prepare()
4607          * when the whole stack is complete and ready
4608          * to serve the requests */
4609
4610         mdt_init_capa_ctxt(env, m);
4611
4612         /* Reduce the initial timeout on an MDS because it doesn't need such
4613          * a long timeout as an OST does. Adaptive timeouts will adjust this
4614          * value appropriately. */
4615         if (ldlm_timeout == LDLM_TIMEOUT_DEFAULT)
4616                 ldlm_timeout = MDS_LDLM_TIMEOUT_DEFAULT;
4617
4618         RETURN(0);
4619 err_procfs:
4620         mdt_procfs_fini(m);
4621 err_recovery:
4622         target_recovery_fini(obd);
4623         upcall_cache_cleanup(m->mdt_identity_cache);
4624         m->mdt_identity_cache = NULL;
4625 err_fs_cleanup:
4626         mdt_fs_cleanup(env, m);
4627 err_tgt:
4628         tgt_fini(env, &m->mdt_lut);
4629 err_capa:
4630         cfs_timer_disarm(&m->mdt_ck_timer);
4631         mdt_ck_thread_stop(m);
4632 err_free_hsm:
4633         mdt_hsm_cdt_fini(m);
4634 err_free_ns:
4635         ldlm_namespace_free(m->mdt_namespace, NULL, 0);
4636         obd->obd_namespace = m->mdt_namespace = NULL;
4637 err_fini_seq:
4638         mdt_seq_fini(env, m);
4639 err_fini_fld:
4640         mdt_fld_fini(env, m);
4641 err_fini_stack:
4642         mdt_stack_fini(env, m, md2lu_dev(m->mdt_child));
4643 err_lmi:
4644         if (lmi)
4645                 server_put_mount(dev);
4646         return(rc);
4647 }
4648
4649 /* For interoperability, the left element is old parameter, the right one
4650  * is the new version of the parameter, if some parameter is deprecated,
4651  * the new version should be set as NULL. */
4652 static struct cfg_interop_param mdt_interop_param[] = {
4653         { "mdt.group_upcall",   NULL },
4654         { "mdt.quota_type",     NULL },
4655         { "mdd.quota_type",     NULL },
4656         { "mdt.rootsquash",     "mdt.root_squash" },
4657         { "mdt.nosquash_nid",   "mdt.nosquash_nids" },
4658         { NULL }
4659 };
4660
4661 /* used by MGS to process specific configurations */
4662 static int mdt_process_config(const struct lu_env *env,
4663                               struct lu_device *d, struct lustre_cfg *cfg)
4664 {
4665         struct mdt_device *m = mdt_dev(d);
4666         struct md_device *md_next = m->mdt_child;
4667         struct lu_device *next = md2lu_dev(md_next);
4668         int rc;
4669         ENTRY;
4670
4671         switch (cfg->lcfg_command) {
4672         case LCFG_PARAM: {
4673                 struct lprocfs_static_vars  lvars;
4674                 struct obd_device          *obd = d->ld_obd;
4675
4676                 /* For interoperability */
4677                 struct cfg_interop_param   *ptr = NULL;
4678                 struct lustre_cfg          *old_cfg = NULL;
4679                 char                       *param = NULL;
4680
4681                 param = lustre_cfg_string(cfg, 1);
4682                 if (param == NULL) {
4683                         CERROR("param is empty\n");
4684                         rc = -EINVAL;
4685                         break;
4686                 }
4687
4688                 ptr = class_find_old_param(param, mdt_interop_param);
4689                 if (ptr != NULL) {
4690                         if (ptr->new_param == NULL) {
4691                                 rc = 0;
4692                                 CWARN("For interoperability, skip this %s."
4693                                       " It is obsolete.\n", ptr->old_param);
4694                                 break;
4695                         }
4696
4697                         CWARN("Found old param %s, changed it to %s.\n",
4698                               ptr->old_param, ptr->new_param);
4699
4700                         old_cfg = cfg;
4701                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
4702                         if (IS_ERR(cfg)) {
4703                                 rc = PTR_ERR(cfg);
4704                                 break;
4705                         }
4706                 }
4707
4708                 lprocfs_mdt_init_vars(&lvars);
4709                 rc = class_process_proc_param(PARAM_MDT, lvars.obd_vars,
4710                                               cfg, obd);
4711                 if (rc > 0 || rc == -ENOSYS) {
4712                         /* is it an HSM var ? */
4713                         rc = class_process_proc_param(PARAM_HSM,
4714                                                       hsm_cdt_get_proc_vars(),
4715                                                       cfg, obd);
4716                         if (rc > 0 || rc == -ENOSYS)
4717                                 /* we don't understand; pass it on */
4718                                 rc = next->ld_ops->ldo_process_config(env, next,
4719                                                                       cfg);
4720                 }
4721
4722                 if (old_cfg != NULL)
4723                         lustre_cfg_free(cfg);
4724
4725                 break;
4726         }
4727         default:
4728                 /* others are passed further */
4729                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
4730                 break;
4731         }
4732         RETURN(rc);
4733 }
4734
4735 static struct lu_object *mdt_object_alloc(const struct lu_env *env,
4736                                           const struct lu_object_header *hdr,
4737                                           struct lu_device *d)
4738 {
4739         struct mdt_object *mo;
4740
4741         ENTRY;
4742
4743         OBD_SLAB_ALLOC_PTR_GFP(mo, mdt_object_kmem, GFP_NOFS);
4744         if (mo != NULL) {
4745                 struct lu_object *o;
4746                 struct lu_object_header *h;
4747
4748                 o = &mo->mot_obj;
4749                 h = &mo->mot_header;
4750                 lu_object_header_init(h);
4751                 lu_object_init(o, h, d);
4752                 lu_object_add_top(h, o);
4753                 o->lo_ops = &mdt_obj_ops;
4754                 mutex_init(&mo->mot_ioepoch_mutex);
4755                 mutex_init(&mo->mot_lov_mutex);
4756                 init_rwsem(&mo->mot_open_sem);
4757                 RETURN(o);
4758         }
4759         RETURN(NULL);
4760 }
4761
4762 static int mdt_object_init(const struct lu_env *env, struct lu_object *o,
4763                            const struct lu_object_conf *unused)
4764 {
4765         struct mdt_device *d = mdt_dev(o->lo_dev);
4766         struct lu_device  *under;
4767         struct lu_object  *below;
4768         int                rc = 0;
4769         ENTRY;
4770
4771         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
4772                PFID(lu_object_fid(o)));
4773
4774         under = &d->mdt_child->md_lu_dev;
4775         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
4776         if (below != NULL) {
4777                 lu_object_add(o, below);
4778         } else
4779                 rc = -ENOMEM;
4780
4781         RETURN(rc);
4782 }
4783
4784 static void mdt_object_free(const struct lu_env *env, struct lu_object *o)
4785 {
4786         struct mdt_object *mo = mdt_obj(o);
4787         struct lu_object_header *h;
4788         ENTRY;
4789
4790         h = o->lo_header;
4791         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
4792                PFID(lu_object_fid(o)));
4793
4794         LASSERT(atomic_read(&mo->mot_open_count) == 0);
4795         LASSERT(atomic_read(&mo->mot_lease_count) == 0);
4796
4797         lu_object_fini(o);
4798         lu_object_header_fini(h);
4799         OBD_SLAB_FREE_PTR(mo, mdt_object_kmem);
4800
4801         EXIT;
4802 }
4803
4804 static int mdt_object_print(const struct lu_env *env, void *cookie,
4805                             lu_printer_t p, const struct lu_object *o)
4806 {
4807         struct mdt_object *mdto = mdt_obj((struct lu_object *)o);
4808         return (*p)(env, cookie, LUSTRE_MDT_NAME"-object@%p(ioepoch="LPU64" "
4809                     "flags="LPX64", epochcount=%d, writecount=%d)",
4810                     mdto, mdto->mot_ioepoch, mdto->mot_flags,
4811                     mdto->mot_ioepoch_count, mdto->mot_writecount);
4812 }
4813
4814 static int mdt_prepare(const struct lu_env *env,
4815                 struct lu_device *pdev,
4816                 struct lu_device *cdev)
4817 {
4818         struct mdt_device *mdt = mdt_dev(cdev);
4819         struct lu_device *next = &mdt->mdt_child->md_lu_dev;
4820         struct obd_device *obd = cdev->ld_obd;
4821         struct lfsck_start_param lsp;
4822         int rc;
4823
4824         ENTRY;
4825
4826         LASSERT(obd);
4827
4828         rc = next->ld_ops->ldo_prepare(env, cdev, next);
4829         if (rc)
4830                 RETURN(rc);
4831
4832         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_CHANGELOG_ORIG_CTXT);
4833         if (rc)
4834                 RETURN(rc);
4835
4836         rc = mdt_llog_ctxt_clone(env, mdt, LLOG_AGENT_ORIG_CTXT);
4837         if (rc)
4838                 RETURN(rc);
4839
4840         rc = lfsck_register_namespace(env, mdt->mdt_bottom, mdt->mdt_namespace);
4841         /* The LFSCK instance is registered just now, so it must be there when
4842          * register the namespace to such instance. */
4843         LASSERTF(rc == 0, "register namespace failed: rc = %d\n", rc);
4844
4845         lsp.lsp_start = NULL;
4846         lsp.lsp_index_valid = 0;
4847         rc = mdt->mdt_child->md_ops->mdo_iocontrol(env, mdt->mdt_child,
4848                                                    OBD_IOC_START_LFSCK,
4849                                                    0, &lsp);
4850         if (rc != 0) {
4851                 CWARN("%s: auto trigger paused LFSCK failed: rc = %d\n",
4852                       mdt_obd_name(mdt), rc);
4853                 rc = 0;
4854         }
4855
4856         if (mdt->mdt_seq_site.ss_node_id == 0) {
4857                 rc = mdt->mdt_child->md_ops->mdo_root_get(env, mdt->mdt_child,
4858                                                          &mdt->mdt_md_root_fid);
4859                 if (rc)
4860                         RETURN(rc);
4861         }
4862
4863         LASSERT(!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state));
4864         target_recovery_init(&mdt->mdt_lut, tgt_request_handle);
4865         set_bit(MDT_FL_CFGLOG, &mdt->mdt_state);
4866         LASSERT(obd->obd_no_conn);
4867         spin_lock(&obd->obd_dev_lock);
4868         obd->obd_no_conn = 0;
4869         spin_unlock(&obd->obd_dev_lock);
4870
4871         if (obd->obd_recovering == 0)
4872                 mdt_postrecov(env, mdt);
4873
4874         RETURN(rc);
4875 }
4876
4877 const struct lu_device_operations mdt_lu_ops = {
4878         .ldo_object_alloc   = mdt_object_alloc,
4879         .ldo_process_config = mdt_process_config,
4880         .ldo_prepare        = mdt_prepare,
4881 };
4882
4883 static const struct lu_object_operations mdt_obj_ops = {
4884         .loo_object_init    = mdt_object_init,
4885         .loo_object_free    = mdt_object_free,
4886         .loo_object_print   = mdt_object_print
4887 };
4888
4889 static int mdt_obd_set_info_async(const struct lu_env *env,
4890                                   struct obd_export *exp,
4891                                   __u32 keylen, void *key,
4892                                   __u32 vallen, void *val,
4893                                   struct ptlrpc_request_set *set)
4894 {
4895         int rc;
4896
4897         ENTRY;
4898
4899         if (KEY_IS(KEY_SPTLRPC_CONF)) {
4900                 rc = tgt_adapt_sptlrpc_conf(class_exp2tgt(exp), 0);
4901                 RETURN(rc);
4902         }
4903
4904         RETURN(0);
4905 }
4906
4907 /**
4908  * Match client and server connection feature flags.
4909  *
4910  * Compute the compatibility flags for a connection request based on
4911  * features mutually supported by client and server.
4912  *
4913  * The obd_export::exp_connect_data.ocd_connect_flags field in \a exp
4914  * must not be updated here, otherwise a partially initialized value may
4915  * be exposed. After the connection request is successfully processed,
4916  * the top-level MDT connect request handler atomically updates the export
4917  * connect flags from the obd_connect_data::ocd_connect_flags field of the
4918  * reply. \see mdt_connect().
4919  *
4920  * \param exp   the obd_export associated with this client/target pair
4921  * \param mdt   the target device for the connection
4922  * \param data  stores data for this connect request
4923  *
4924  * \retval 0       success
4925  * \retval -EPROTO \a data unexpectedly has zero obd_connect_data::ocd_brw_size
4926  * \retval -EBADE  client and server feature requirements are incompatible
4927  */
4928 static int mdt_connect_internal(struct obd_export *exp,
4929                                 struct mdt_device *mdt,
4930                                 struct obd_connect_data *data)
4931 {
4932         LASSERT(data != NULL);
4933
4934         data->ocd_connect_flags &= MDT_CONNECT_SUPPORTED;
4935         data->ocd_ibits_known &= MDS_INODELOCK_FULL;
4936
4937         /* If no known bits (which should not happen, probably,
4938            as everybody should support LOOKUP and UPDATE bits at least)
4939            revert to compat mode with plain locks. */
4940         if (!data->ocd_ibits_known &&
4941             data->ocd_connect_flags & OBD_CONNECT_IBITS)
4942                 data->ocd_connect_flags &= ~OBD_CONNECT_IBITS;
4943
4944         if (!mdt->mdt_opts.mo_acl)
4945                 data->ocd_connect_flags &= ~OBD_CONNECT_ACL;
4946
4947         if (!mdt->mdt_opts.mo_user_xattr)
4948                 data->ocd_connect_flags &= ~OBD_CONNECT_XATTR;
4949
4950         if (!mdt->mdt_som_conf)
4951                 data->ocd_connect_flags &= ~OBD_CONNECT_SOM;
4952
4953         if (data->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
4954                 data->ocd_brw_size = min(data->ocd_brw_size,
4955                                          (__u32)MD_MAX_BRW_SIZE);
4956                 if (data->ocd_brw_size == 0) {
4957                         CERROR("%s: cli %s/%p ocd_connect_flags: "LPX64
4958                                " ocd_version: %x ocd_grant: %d "
4959                                "ocd_index: %u ocd_brw_size is "
4960                                "unexpectedly zero, network data "
4961                                "corruption? Refusing connection of this"
4962                                " client\n",
4963                                mdt_obd_name(mdt),
4964                                exp->exp_client_uuid.uuid,
4965                                exp, data->ocd_connect_flags, data->ocd_version,
4966                                data->ocd_grant, data->ocd_index);
4967                         return -EPROTO;
4968                 }
4969         }
4970
4971         /* NB: Disregard the rule against updating
4972          * exp_connect_data.ocd_connect_flags in this case, since
4973          * tgt_client_new() needs to know if this is a lightweight
4974          * connection, and it is safe to expose this flag before
4975          * connection processing completes. */
4976         if (data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT) {
4977                 spin_lock(&exp->exp_lock);
4978                 *exp_connect_flags_ptr(exp) |= OBD_CONNECT_LIGHTWEIGHT;
4979                 spin_unlock(&exp->exp_lock);
4980         }
4981
4982         data->ocd_version = LUSTRE_VERSION_CODE;
4983
4984         if ((data->ocd_connect_flags & OBD_CONNECT_FID) == 0) {
4985                 CWARN("%s: MDS requires FID support, but client not\n",
4986                       mdt_obd_name(mdt));
4987                 return -EBADE;
4988         }
4989
4990         if (mdt->mdt_som_conf &&
4991             !(data->ocd_connect_flags & (OBD_CONNECT_LIGHTWEIGHT |
4992                                          OBD_CONNECT_MDS_MDS |
4993                                          OBD_CONNECT_SOM))) {
4994                 CWARN("%s: MDS has SOM enabled, but client does not support "
4995                       "it\n", mdt_obd_name(mdt));
4996                 return -EBADE;
4997         }
4998
4999         if (OCD_HAS_FLAG(data, PINGLESS)) {
5000                 if (ptlrpc_pinger_suppress_pings()) {
5001                         spin_lock(&exp->exp_obd->obd_dev_lock);
5002                         list_del_init(&exp->exp_obd_chain_timed);
5003                         spin_unlock(&exp->exp_obd->obd_dev_lock);
5004                 } else {
5005                         data->ocd_connect_flags &= ~OBD_CONNECT_PINGLESS;
5006                 }
5007         }
5008
5009         data->ocd_max_easize = mdt->mdt_max_ea_size;
5010
5011         return 0;
5012 }
5013
5014 /* mds_connect copy */
5015 static int mdt_obd_connect(const struct lu_env *env,
5016                            struct obd_export **exp, struct obd_device *obd,
5017                            struct obd_uuid *cluuid,
5018                            struct obd_connect_data *data,
5019                            void *localdata)
5020 {
5021         struct obd_export      *lexp;
5022         struct lustre_handle    conn = { 0 };
5023         struct mdt_device      *mdt;
5024         int                     rc;
5025         ENTRY;
5026
5027         LASSERT(env != NULL);
5028         if (!exp || !obd || !cluuid)
5029                 RETURN(-EINVAL);
5030
5031         mdt = mdt_dev(obd->obd_lu_dev);
5032
5033         /*
5034          * first, check whether the stack is ready to handle requests
5035          * XXX: probably not very appropriate method is used now
5036          *      at some point we should find a better one
5037          */
5038         if (!test_bit(MDT_FL_SYNCED, &mdt->mdt_state) && data != NULL &&
5039             !(data->ocd_connect_flags & OBD_CONNECT_LIGHTWEIGHT)) {
5040                 rc = obd_get_info(env, mdt->mdt_child_exp,
5041                                   sizeof(KEY_OSP_CONNECTED),
5042                                   KEY_OSP_CONNECTED, NULL, NULL, NULL);
5043                 if (rc)
5044                         RETURN(-EAGAIN);
5045                 set_bit(MDT_FL_SYNCED, &mdt->mdt_state);
5046         }
5047
5048         rc = class_connect(&conn, obd, cluuid);
5049         if (rc)
5050                 RETURN(rc);
5051
5052         lexp = class_conn2export(&conn);
5053         LASSERT(lexp != NULL);
5054
5055         rc = mdt_connect_internal(lexp, mdt, data);
5056         if (rc == 0) {
5057                 struct lsd_client_data *lcd = lexp->exp_target_data.ted_lcd;
5058
5059                 LASSERT(lcd);
5060                 memcpy(lcd->lcd_uuid, cluuid, sizeof lcd->lcd_uuid);
5061                 rc = tgt_client_new(env, lexp);
5062                 if (rc == 0)
5063                         mdt_export_stats_init(obd, lexp, localdata);
5064
5065                 /* For phase I, sync for cross-ref operation. */
5066                 lexp->exp_keep_sync = 1;
5067         }
5068
5069         if (rc != 0) {
5070                 class_disconnect(lexp);
5071                 *exp = NULL;
5072         } else {
5073                 *exp = lexp;
5074         }
5075
5076         RETURN(rc);
5077 }
5078
5079 static int mdt_obd_reconnect(const struct lu_env *env,
5080                              struct obd_export *exp, struct obd_device *obd,
5081                              struct obd_uuid *cluuid,
5082                              struct obd_connect_data *data,
5083                              void *localdata)
5084 {
5085         int                     rc;
5086         ENTRY;
5087
5088         if (exp == NULL || obd == NULL || cluuid == NULL)
5089                 RETURN(-EINVAL);
5090
5091         rc = mdt_connect_internal(exp, mdt_dev(obd->obd_lu_dev), data);
5092         if (rc == 0)
5093                 mdt_export_stats_init(obd, exp, localdata);
5094
5095         RETURN(rc);
5096 }
5097
5098 static int mdt_ctxt_add_dirty_flag(struct lu_env *env,
5099                                    struct mdt_thread_info *info,
5100                                    struct mdt_file_data *mfd)
5101 {
5102         struct lu_context ses;
5103         int rc;
5104         ENTRY;
5105
5106         rc = lu_context_init(&ses, LCT_SERVER_SESSION);
5107         if (rc)
5108                 RETURN(rc);
5109
5110         env->le_ses = &ses;
5111         lu_context_enter(&ses);
5112
5113         mdt_ucred(info)->uc_valid = UCRED_OLD;
5114         rc = mdt_add_dirty_flag(info, mfd->mfd_object, &info->mti_attr);
5115
5116         lu_context_exit(&ses);
5117         lu_context_fini(&ses);
5118         env->le_ses = NULL;
5119
5120         RETURN(rc);
5121 }
5122
5123 static int mdt_export_cleanup(struct obd_export *exp)
5124 {
5125         struct mdt_export_data *med = &exp->exp_mdt_data;
5126         struct obd_device      *obd = exp->exp_obd;
5127         struct mdt_device      *mdt;
5128         struct mdt_thread_info *info;
5129         struct lu_env           env;
5130         CFS_LIST_HEAD(closing_list);
5131         struct mdt_file_data *mfd, *n;
5132         int rc = 0;
5133         ENTRY;
5134
5135         spin_lock(&med->med_open_lock);
5136         while (!cfs_list_empty(&med->med_open_head)) {
5137                 cfs_list_t *tmp = med->med_open_head.next;
5138                 mfd = cfs_list_entry(tmp, struct mdt_file_data, mfd_list);
5139
5140                 /* Remove mfd handle so it can't be found again.
5141                  * We are consuming the mfd_list reference here. */
5142                 class_handle_unhash(&mfd->mfd_handle);
5143                 cfs_list_move_tail(&mfd->mfd_list, &closing_list);
5144         }
5145         spin_unlock(&med->med_open_lock);
5146         mdt = mdt_dev(obd->obd_lu_dev);
5147         LASSERT(mdt != NULL);
5148
5149         rc = lu_env_init(&env, LCT_MD_THREAD);
5150         if (rc)
5151                 RETURN(rc);
5152
5153         info = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5154         LASSERT(info != NULL);
5155         memset(info, 0, sizeof *info);
5156         info->mti_env = &env;
5157         info->mti_mdt = mdt;
5158         info->mti_exp = exp;
5159
5160         if (!cfs_list_empty(&closing_list)) {
5161                 struct md_attr *ma = &info->mti_attr;
5162
5163                 /* Close any open files (which may also cause orphan unlinking). */
5164                 cfs_list_for_each_entry_safe(mfd, n, &closing_list, mfd_list) {
5165                         cfs_list_del_init(&mfd->mfd_list);
5166                         ma->ma_need = ma->ma_valid = 0;
5167
5168                         /* This file is being closed due to an eviction, it
5169                          * could have been modified and now dirty regarding to
5170                          * HSM archive, check this!
5171                          * The logic here is to mark a file dirty if there's a
5172                          * chance it was dirtied before the client was evicted,
5173                          * so that we don't have to wait for a release attempt
5174                          * before finding out the file was actually dirty and
5175                          * fail the release. Aggressively marking it dirty here
5176                          * will cause the policy engine to attempt to
5177                          * re-archive it; when rearchiving, we can compare the
5178                          * current version to the HSM data_version and make the
5179                          * archive request into a noop if it's not actually
5180                          * dirty.
5181                          */
5182                         if (mfd->mfd_mode & (FMODE_WRITE|MDS_FMODE_TRUNC))
5183                                 rc = mdt_ctxt_add_dirty_flag(&env, info, mfd);
5184
5185                         /* Don't unlink orphan on failover umount, LU-184 */
5186                         if (exp->exp_flags & OBD_OPT_FAILOVER) {
5187                                 ma->ma_valid = MA_FLAGS;
5188                                 ma->ma_attr_flags |= MDS_KEEP_ORPHAN;
5189                         }
5190                         mdt_mfd_close(info, mfd);
5191                 }
5192         }
5193         info->mti_mdt = NULL;
5194         /* cleanup client slot early */
5195         /* Do not erase record for recoverable client. */
5196         if (!(exp->exp_flags & OBD_OPT_FAILOVER) || exp->exp_failed)
5197                 tgt_client_del(&env, exp);
5198         lu_env_fini(&env);
5199
5200         RETURN(rc);
5201 }
5202
5203 static int mdt_obd_disconnect(struct obd_export *exp)
5204 {
5205         int rc;
5206         ENTRY;
5207
5208         LASSERT(exp);
5209         class_export_get(exp);
5210
5211         rc = server_disconnect_export(exp);
5212         if (rc != 0)
5213                 CDEBUG(D_IOCTL, "server disconnect error: %d\n", rc);
5214
5215         rc = mdt_export_cleanup(exp);
5216         class_export_put(exp);
5217         RETURN(rc);
5218 }
5219
5220 /* FIXME: Can we avoid using these two interfaces? */
5221 static int mdt_init_export(struct obd_export *exp)
5222 {
5223         struct mdt_export_data *med = &exp->exp_mdt_data;
5224         int                     rc;
5225         ENTRY;
5226
5227         CFS_INIT_LIST_HEAD(&med->med_open_head);
5228         spin_lock_init(&med->med_open_lock);
5229         mutex_init(&med->med_idmap_mutex);
5230         med->med_idmap = NULL;
5231         spin_lock(&exp->exp_lock);
5232         exp->exp_connecting = 1;
5233         spin_unlock(&exp->exp_lock);
5234
5235         /* self-export doesn't need client data and ldlm initialization */
5236         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5237                                      &exp->exp_client_uuid)))
5238                 RETURN(0);
5239
5240         rc = tgt_client_alloc(exp);
5241         if (rc)
5242                 GOTO(err, rc);
5243
5244         rc = ldlm_init_export(exp);
5245         if (rc)
5246                 GOTO(err_free, rc);
5247
5248         RETURN(rc);
5249
5250 err_free:
5251         tgt_client_free(exp);
5252 err:
5253         CERROR("%s: Failed to initialize export: rc = %d\n",
5254                exp->exp_obd->obd_name, rc);
5255         return rc;
5256 }
5257
5258 static int mdt_destroy_export(struct obd_export *exp)
5259 {
5260         ENTRY;
5261
5262         if (exp_connect_rmtclient(exp))
5263                 mdt_cleanup_idmap(&exp->exp_mdt_data);
5264
5265         target_destroy_export(exp);
5266         /* destroy can be called from failed obd_setup, so
5267          * checking uuid is safer than obd_self_export */
5268         if (unlikely(obd_uuid_equals(&exp->exp_obd->obd_uuid,
5269                                      &exp->exp_client_uuid)))
5270                 RETURN(0);
5271
5272         ldlm_destroy_export(exp);
5273         tgt_client_free(exp);
5274
5275         LASSERT(cfs_list_empty(&exp->exp_outstanding_replies));
5276         LASSERT(cfs_list_empty(&exp->exp_mdt_data.med_open_head));
5277
5278         RETURN(0);
5279 }
5280
5281 /** The maximum depth that fid2path() will search.
5282  * This is limited only because we want to store the fids for
5283  * historical path lookup purposes.
5284  */
5285 #define MAX_PATH_DEPTH 100
5286
5287 /** mdt_path() lookup structure. */
5288 struct path_lookup_info {
5289         __u64                   pli_recno;      /**< history point */
5290         __u64                   pli_currec;     /**< current record */
5291         struct lu_fid           pli_fid;
5292         struct lu_fid           pli_fids[MAX_PATH_DEPTH]; /**< path, in fids */
5293         struct mdt_object       *pli_mdt_obj;
5294         char                    *pli_path;      /**< full path */
5295         int                     pli_pathlen;
5296         int                     pli_linkno;     /**< which hardlink to follow */
5297         int                     pli_fidcount;   /**< number of \a pli_fids */
5298 };
5299
5300 int mdt_links_read(struct mdt_thread_info *info, struct mdt_object *mdt_obj,
5301                    struct linkea_data *ldata)
5302 {
5303         int rc;
5304
5305         LASSERT(ldata->ld_buf->lb_buf != NULL);
5306
5307         if (!mdt_object_exists(mdt_obj))
5308                 return -ENODATA;
5309
5310         rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5311                           ldata->ld_buf, XATTR_NAME_LINK);
5312         if (rc == -ERANGE) {
5313                 /* Buf was too small, figure out what we need. */
5314                 lu_buf_free(ldata->ld_buf);
5315                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5316                                   ldata->ld_buf, XATTR_NAME_LINK);
5317                 if (rc < 0)
5318                         return rc;
5319                 ldata->ld_buf = lu_buf_check_and_alloc(ldata->ld_buf, rc);
5320                 if (ldata->ld_buf->lb_buf == NULL)
5321                         return -ENOMEM;
5322                 rc = mo_xattr_get(info->mti_env, mdt_object_child(mdt_obj),
5323                                   ldata->ld_buf, XATTR_NAME_LINK);
5324         }
5325         if (rc < 0)
5326                 return rc;
5327
5328         return linkea_init(ldata);
5329 }
5330
5331 static int mdt_path_current(struct mdt_thread_info *info,
5332                             struct path_lookup_info *pli)
5333 {
5334         struct mdt_device       *mdt = info->mti_mdt;
5335         struct mdt_object       *mdt_obj;
5336         struct link_ea_header   *leh;
5337         struct link_ea_entry    *lee;
5338         struct lu_name          *tmpname = &info->mti_name;
5339         struct lu_fid           *tmpfid = &info->mti_tmp_fid1;
5340         struct lu_buf           *buf = &info->mti_big_buf;
5341         char                    *ptr;
5342         int                     reclen;
5343         struct linkea_data      ldata = { 0 };
5344         int                     rc = 0;
5345         ENTRY;
5346
5347         /* temp buffer for path element, the buffer will be finally freed
5348          * in mdt_thread_info_fini */
5349         buf = lu_buf_check_and_alloc(buf, PATH_MAX);
5350         if (buf->lb_buf == NULL)
5351                 RETURN(-ENOMEM);
5352
5353         ldata.ld_buf = buf;
5354         ptr = pli->pli_path + pli->pli_pathlen - 1;
5355         *ptr = 0;
5356         --ptr;
5357         pli->pli_fidcount = 0;
5358         pli->pli_fids[0] = *(struct lu_fid *)mdt_object_fid(pli->pli_mdt_obj);
5359
5360         /* root FID only exists on MDT0, and fid2path should also ends at MDT0,
5361          * so checking root_fid can only happen on MDT0. */
5362         while (!lu_fid_eq(&mdt->mdt_md_root_fid,
5363                           &pli->pli_fids[pli->pli_fidcount])) {
5364                 mdt_obj = mdt_object_find(info->mti_env, mdt,
5365                                           &pli->pli_fids[pli->pli_fidcount]);
5366                 if (IS_ERR(mdt_obj))
5367                         GOTO(out, rc = PTR_ERR(mdt_obj));
5368                 if (mdt_object_remote(mdt_obj)) {
5369                         mdt_object_put(info->mti_env, mdt_obj);
5370                         GOTO(remote_out, rc = -EREMOTE);
5371                 }
5372                 if (!mdt_object_exists(mdt_obj)) {
5373                         mdt_object_put(info->mti_env, mdt_obj);
5374                         GOTO(out, rc = -ENOENT);
5375                 }
5376
5377                 rc = mdt_links_read(info, mdt_obj, &ldata);
5378                 mdt_object_put(info->mti_env, mdt_obj);
5379                 if (rc != 0)
5380                         GOTO(out, rc);
5381
5382                 leh = buf->lb_buf;
5383                 lee = (struct link_ea_entry *)(leh + 1); /* link #0 */
5384                 linkea_entry_unpack(lee, &reclen, tmpname, tmpfid);
5385                 /* If set, use link #linkno for path lookup, otherwise use
5386                    link #0.  Only do this for the final path element. */
5387                 if (pli->pli_fidcount == 0 &&
5388                     pli->pli_linkno < leh->leh_reccount) {
5389                         int count;
5390                         for (count = 0; count < pli->pli_linkno; count++) {
5391                                 lee = (struct link_ea_entry *)
5392                                      ((char *)lee + reclen);
5393                                 linkea_entry_unpack(lee, &reclen, tmpname,
5394                                                     tmpfid);
5395                         }
5396                         if (pli->pli_linkno < leh->leh_reccount - 1)
5397                                 /* indicate to user there are more links */
5398                                 pli->pli_linkno++;
5399                 }
5400
5401                 /* Pack the name in the end of the buffer */
5402                 ptr -= tmpname->ln_namelen;
5403                 if (ptr - 1 <= pli->pli_path)
5404                         GOTO(out, rc = -EOVERFLOW);
5405                 strncpy(ptr, tmpname->ln_name, tmpname->ln_namelen);
5406                 *(--ptr) = '/';
5407
5408                 /* Store the parent fid for historic lookup */
5409                 if (++pli->pli_fidcount >= MAX_PATH_DEPTH)
5410                         GOTO(out, rc = -EOVERFLOW);
5411                 pli->pli_fids[pli->pli_fidcount] = *tmpfid;
5412         }
5413
5414 remote_out:
5415         ptr++; /* skip leading / */
5416         memmove(pli->pli_path, ptr, pli->pli_path + pli->pli_pathlen - ptr);
5417
5418         EXIT;
5419 out:
5420         return rc;
5421 }
5422
5423 /* Returns the full path to this fid, as of changelog record recno. */
5424 static int mdt_path(struct mdt_thread_info *info, struct mdt_object *obj,
5425                     char *path, int pathlen, __u64 *recno, int *linkno,
5426                     struct lu_fid *fid)
5427 {
5428         struct mdt_device       *mdt = info->mti_mdt;
5429         struct path_lookup_info *pli;
5430         int                     tries = 3;
5431         int                     rc = -EAGAIN;
5432         ENTRY;
5433
5434         if (pathlen < 3)
5435                 RETURN(-EOVERFLOW);
5436
5437         if (lu_fid_eq(&mdt->mdt_md_root_fid, mdt_object_fid(obj))) {
5438                 path[0] = '\0';
5439                 RETURN(0);
5440         }
5441
5442         OBD_ALLOC_PTR(pli);
5443         if (pli == NULL)
5444                 RETURN(-ENOMEM);
5445
5446         pli->pli_mdt_obj = obj;
5447         pli->pli_recno = *recno;
5448         pli->pli_path = path;
5449         pli->pli_pathlen = pathlen;
5450         pli->pli_linkno = *linkno;
5451
5452         /* Retry multiple times in case file is being moved */
5453         while (tries-- && rc == -EAGAIN)
5454                 rc = mdt_path_current(info, pli);
5455
5456         /* return the last resolved fids to the client, so the client will
5457          * build the left path on another MDT for remote object */
5458         *fid = pli->pli_fids[pli->pli_fidcount];
5459
5460         *recno = pli->pli_currec;
5461         /* Return next link index to caller */
5462         *linkno = pli->pli_linkno;
5463
5464         OBD_FREE_PTR(pli);
5465
5466         RETURN(rc);
5467 }
5468
5469 static int mdt_fid2path(struct mdt_thread_info *info,
5470                         struct getinfo_fid2path *fp)
5471 {
5472         struct mdt_device *mdt = info->mti_mdt;
5473         struct mdt_object *obj;
5474         int    rc;
5475         ENTRY;
5476
5477         CDEBUG(D_IOCTL, "path get "DFID" from "LPU64" #%d\n",
5478                 PFID(&fp->gf_fid), fp->gf_recno, fp->gf_linkno);
5479
5480         if (!fid_is_sane(&fp->gf_fid))
5481                 RETURN(-EINVAL);
5482
5483         if (!fid_is_namespace_visible(&fp->gf_fid)) {
5484                 CWARN("%s: "DFID" is invalid, sequence should be "
5485                       ">= "LPX64"\n", mdt_obd_name(mdt),
5486                       PFID(&fp->gf_fid), (__u64)FID_SEQ_NORMAL);
5487                 RETURN(-EINVAL);
5488         }
5489
5490         obj = mdt_object_find(info->mti_env, mdt, &fp->gf_fid);
5491         if (obj == NULL || IS_ERR(obj)) {
5492                 CDEBUG(D_IOCTL, "no object "DFID": %ld\n", PFID(&fp->gf_fid),
5493                        PTR_ERR(obj));
5494                 RETURN(-EINVAL);
5495         }
5496
5497         if (mdt_object_remote(obj))
5498                 rc = -EREMOTE;
5499         else if (!mdt_object_exists(obj))
5500                 rc = -ENOENT;
5501         else
5502                 rc = 0;
5503
5504         if (rc < 0) {
5505                 mdt_object_put(info->mti_env, obj);
5506                 CDEBUG(D_IOCTL, "nonlocal object "DFID": %d\n",
5507                        PFID(&fp->gf_fid), rc);
5508                 RETURN(rc);
5509         }
5510
5511         rc = mdt_path(info, obj, fp->gf_path, fp->gf_pathlen, &fp->gf_recno,
5512                       &fp->gf_linkno, &fp->gf_fid);
5513
5514         CDEBUG(D_INFO, "fid "DFID", path %s recno "LPX64" linkno %u\n",
5515                PFID(&fp->gf_fid), fp->gf_path, fp->gf_recno, fp->gf_linkno);
5516
5517         mdt_object_put(info->mti_env, obj);
5518
5519         RETURN(rc);
5520 }
5521
5522 static int mdt_rpc_fid2path(struct mdt_thread_info *info, void *key,
5523                             void *val, int vallen)
5524 {
5525         struct getinfo_fid2path *fpout, *fpin;
5526         int rc = 0;
5527
5528         fpin = key + cfs_size_round(sizeof(KEY_FID2PATH));
5529         fpout = val;
5530
5531         if (ptlrpc_req_need_swab(info->mti_pill->rc_req))
5532                 lustre_swab_fid2path(fpin);
5533
5534         memcpy(fpout, fpin, sizeof(*fpin));
5535         if (fpout->gf_pathlen != vallen - sizeof(*fpin))
5536                 RETURN(-EINVAL);
5537
5538         rc = mdt_fid2path(info, fpout);
5539         RETURN(rc);
5540 }
5541
5542 int mdt_get_info(struct tgt_session_info *tsi)
5543 {
5544         char    *key;
5545         int      keylen;
5546         __u32   *vallen;
5547         void    *valout;
5548         int      rc;
5549
5550         ENTRY;
5551
5552         key = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_KEY);
5553         if (key == NULL) {
5554                 CDEBUG(D_IOCTL, "No GETINFO key");
5555                 RETURN(err_serious(-EFAULT));
5556         }
5557         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_GETINFO_KEY,
5558                                       RCL_CLIENT);
5559
5560         vallen = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_VALLEN);
5561         if (vallen == NULL) {
5562                 CDEBUG(D_IOCTL, "Unable to get RMF_GETINFO_VALLEN buffer");
5563                 RETURN(err_serious(-EFAULT));
5564         }
5565
5566         req_capsule_set_size(tsi->tsi_pill, &RMF_GETINFO_VAL, RCL_SERVER,
5567                              *vallen);
5568         rc = req_capsule_server_pack(tsi->tsi_pill);
5569         if (rc)
5570                 RETURN(err_serious(rc));
5571
5572         valout = req_capsule_server_get(tsi->tsi_pill, &RMF_GETINFO_VAL);
5573         if (valout == NULL) {
5574                 CDEBUG(D_IOCTL, "Unable to get get-info RPC out buffer");
5575                 RETURN(err_serious(-EFAULT));
5576         }
5577
5578         if (KEY_IS(KEY_FID2PATH)) {
5579                 struct mdt_thread_info  *info = tsi2mdt_info(tsi);
5580
5581                 rc = mdt_rpc_fid2path(info, key, valout, *vallen);
5582                 mdt_thread_info_fini(info);
5583         } else {
5584                 rc = -EINVAL;
5585         }
5586         RETURN(rc);
5587 }
5588
5589 /* Pass the ioc down */
5590 static int mdt_ioc_child(struct lu_env *env, struct mdt_device *mdt,
5591                          unsigned int cmd, int len, void *data)
5592 {
5593         struct lu_context ioctl_session;
5594         struct md_device *next = mdt->mdt_child;
5595         int rc;
5596         ENTRY;
5597
5598         rc = lu_context_init(&ioctl_session, LCT_SERVER_SESSION);
5599         if (rc)
5600                 RETURN(rc);
5601         ioctl_session.lc_thread = (struct ptlrpc_thread *)current;
5602         lu_context_enter(&ioctl_session);
5603         env->le_ses = &ioctl_session;
5604
5605         LASSERT(next->md_ops->mdo_iocontrol);
5606         rc = next->md_ops->mdo_iocontrol(env, next, cmd, len, data);
5607
5608         lu_context_exit(&ioctl_session);
5609         lu_context_fini(&ioctl_session);
5610         RETURN(rc);
5611 }
5612
5613 static int mdt_ioc_version_get(struct mdt_thread_info *mti, void *karg)
5614 {
5615         struct obd_ioctl_data *data = karg;
5616         struct lu_fid *fid;
5617         __u64 version;
5618         struct mdt_object *obj;
5619         struct mdt_lock_handle  *lh;
5620         int rc;
5621         ENTRY;
5622
5623         if (data->ioc_inlbuf1 == NULL || data->ioc_inllen1 != sizeof(*fid) ||
5624             data->ioc_inlbuf2 == NULL || data->ioc_inllen2 != sizeof(version))
5625                 RETURN(-EINVAL);
5626
5627         fid = (struct lu_fid *)data->ioc_inlbuf1;
5628
5629         if (!fid_is_sane(fid))
5630                 RETURN(-EINVAL);
5631
5632         CDEBUG(D_IOCTL, "getting version for "DFID"\n", PFID(fid));
5633
5634         lh = &mti->mti_lh[MDT_LH_PARENT];
5635         mdt_lock_reg_init(lh, LCK_CR);
5636
5637         obj = mdt_object_find_lock(mti, fid, lh, MDS_INODELOCK_UPDATE);
5638         if (IS_ERR(obj))
5639                 RETURN(PTR_ERR(obj));
5640
5641         if (mdt_object_remote(obj)) {
5642                 rc = -EREMOTE;
5643                 /**
5644                  * before calling version get the correct MDS should be
5645                  * fid, this is error to find remote object here
5646                  */
5647                 CERROR("nonlocal object "DFID"\n", PFID(fid));
5648         } else if (!mdt_object_exists(obj)) {
5649                 *(__u64 *)data->ioc_inlbuf2 = ENOENT_VERSION;
5650                 rc = -ENOENT;
5651         } else {
5652                 version = dt_version_get(mti->mti_env, mdt_obj2dt(obj));
5653                *(__u64 *)data->ioc_inlbuf2 = version;
5654                 rc = 0;
5655         }
5656         mdt_object_unlock_put(mti, obj, lh, 1);
5657         RETURN(rc);
5658 }
5659
5660 /* ioctls on obd dev */
5661 static int mdt_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
5662                          void *karg, void *uarg)
5663 {
5664         struct lu_env      env;
5665         struct obd_device *obd = exp->exp_obd;
5666         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
5667         struct dt_device  *dt = mdt->mdt_bottom;
5668         int rc;
5669
5670         ENTRY;
5671         CDEBUG(D_IOCTL, "handling ioctl cmd %#x\n", cmd);
5672         rc = lu_env_init(&env, LCT_MD_THREAD);
5673         if (rc)
5674                 RETURN(rc);
5675
5676         switch (cmd) {
5677         case OBD_IOC_SYNC:
5678                 rc = mdt_device_sync(&env, mdt);
5679                 break;
5680         case OBD_IOC_SET_READONLY:
5681                 rc = dt->dd_ops->dt_ro(&env, dt);
5682                 break;
5683         case OBD_IOC_ABORT_RECOVERY:
5684                 CERROR("%s: Aborting recovery for device\n", mdt_obd_name(mdt));
5685                 target_stop_recovery_thread(obd);
5686                 rc = 0;
5687                 break;
5688         case OBD_IOC_CHANGELOG_REG:
5689         case OBD_IOC_CHANGELOG_DEREG:
5690         case OBD_IOC_CHANGELOG_CLEAR:
5691                 rc = mdt_ioc_child(&env, mdt, cmd, len, karg);
5692                 break;
5693         case OBD_IOC_START_LFSCK: {
5694                 struct md_device *next = mdt->mdt_child;
5695                 struct obd_ioctl_data *data = karg;
5696                 struct lfsck_start_param lsp;
5697
5698                 if (unlikely(data == NULL)) {
5699                         rc = -EINVAL;
5700                         break;
5701                 }
5702
5703                 lsp.lsp_start = (struct lfsck_start *)(data->ioc_inlbuf1);
5704                 lsp.lsp_index_valid = 0;
5705                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &lsp);
5706                 break;
5707         }
5708         case OBD_IOC_STOP_LFSCK: {
5709                 struct md_device        *next = mdt->mdt_child;
5710                 struct obd_ioctl_data   *data = karg;
5711                 struct lfsck_stop        stop;
5712
5713                 stop.ls_status = LS_STOPPED;
5714                 /* Old lfsck utils may pass NULL @stop. */
5715                 if (data->ioc_inlbuf1 == NULL)
5716                         stop.ls_flags = 0;
5717                 else
5718                         stop.ls_flags =
5719                         ((struct lfsck_stop *)(data->ioc_inlbuf1))->ls_flags;
5720
5721                 rc = next->md_ops->mdo_iocontrol(&env, next, cmd, 0, &stop);
5722                 break;
5723         }
5724         case OBD_IOC_GET_OBJ_VERSION: {
5725                 struct mdt_thread_info *mti;
5726                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5727                 memset(mti, 0, sizeof *mti);
5728                 mti->mti_env = &env;
5729                 mti->mti_mdt = mdt;
5730                 mti->mti_exp = exp;
5731
5732                 rc = mdt_ioc_version_get(mti, karg);
5733                 break;
5734         }
5735         case OBD_IOC_CATLOGLIST: {
5736                 struct mdt_thread_info *mti;
5737
5738                 mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
5739                 lu_local_obj_fid(&mti->mti_tmp_fid1, LLOG_CATALOGS_OID);
5740                 rc = llog_catalog_list(&env, mdt->mdt_bottom, 0, karg,
5741                                        &mti->mti_tmp_fid1);
5742                 break;
5743          }
5744         default:
5745                 rc = -EOPNOTSUPP;
5746                 CERROR("%s: Not supported cmd = %d, rc = %d\n",
5747                         mdt_obd_name(mdt), cmd, rc);
5748         }
5749
5750         lu_env_fini(&env);
5751         RETURN(rc);
5752 }
5753
5754 static int mdt_postrecov(const struct lu_env *env, struct mdt_device *mdt)
5755 {
5756         struct lu_device *ld = md2lu_dev(mdt->mdt_child);
5757         int rc;
5758         ENTRY;
5759
5760         rc = ld->ld_ops->ldo_recovery_complete(env, ld);
5761         RETURN(rc);
5762 }
5763
5764 static int mdt_obd_postrecov(struct obd_device *obd)
5765 {
5766         struct lu_env env;
5767         int rc;
5768
5769         rc = lu_env_init(&env, LCT_MD_THREAD);
5770         if (rc)
5771                 RETURN(rc);
5772         rc = mdt_postrecov(&env, mdt_dev(obd->obd_lu_dev));
5773         lu_env_fini(&env);
5774         return rc;
5775 }
5776
5777 static struct obd_ops mdt_obd_device_ops = {
5778         .o_owner          = THIS_MODULE,
5779         .o_set_info_async = mdt_obd_set_info_async,
5780         .o_connect        = mdt_obd_connect,
5781         .o_reconnect      = mdt_obd_reconnect,
5782         .o_disconnect     = mdt_obd_disconnect,
5783         .o_init_export    = mdt_init_export,
5784         .o_destroy_export = mdt_destroy_export,
5785         .o_iocontrol      = mdt_iocontrol,
5786         .o_postrecov      = mdt_obd_postrecov,
5787 };
5788
5789 static struct lu_device* mdt_device_fini(const struct lu_env *env,
5790                                          struct lu_device *d)
5791 {
5792         struct mdt_device *m = mdt_dev(d);
5793         ENTRY;
5794
5795         mdt_fini(env, m);
5796         RETURN(NULL);
5797 }
5798
5799 static struct lu_device *mdt_device_free(const struct lu_env *env,
5800                                          struct lu_device *d)
5801 {
5802         struct mdt_device *m = mdt_dev(d);
5803         ENTRY;
5804
5805         lu_device_fini(&m->mdt_lu_dev);
5806         OBD_FREE_PTR(m);
5807
5808         RETURN(NULL);
5809 }
5810
5811 static struct lu_device *mdt_device_alloc(const struct lu_env *env,
5812                                           struct lu_device_type *t,
5813                                           struct lustre_cfg *cfg)
5814 {
5815         struct lu_device  *l;
5816         struct mdt_device *m;
5817
5818         OBD_ALLOC_PTR(m);
5819         if (m != NULL) {
5820                 int rc;
5821
5822                 l = &m->mdt_lu_dev;
5823                 rc = mdt_init0(env, m, t, cfg);
5824                 if (rc != 0) {
5825                         mdt_device_free(env, l);
5826                         l = ERR_PTR(rc);
5827                         return l;
5828                 }
5829         } else
5830                 l = ERR_PTR(-ENOMEM);
5831         return l;
5832 }
5833
5834 /* context key constructor/destructor: mdt_key_init, mdt_key_fini */
5835 LU_KEY_INIT(mdt, struct mdt_thread_info);
5836
5837 static void mdt_key_fini(const struct lu_context *ctx,
5838                          struct lu_context_key *key, void* data)
5839 {
5840         struct mdt_thread_info *info = data;
5841
5842         if (info->mti_big_lmm) {
5843                 OBD_FREE_LARGE(info->mti_big_lmm, info->mti_big_lmmsize);
5844                 info->mti_big_lmm = NULL;
5845                 info->mti_big_lmmsize = 0;
5846         }
5847         OBD_FREE_PTR(info);
5848 }
5849
5850 /* context key: mdt_thread_key */
5851 LU_CONTEXT_KEY_DEFINE(mdt, LCT_MD_THREAD);
5852
5853 struct lu_ucred *mdt_ucred(const struct mdt_thread_info *info)
5854 {
5855         return lu_ucred(info->mti_env);
5856 }
5857
5858 struct lu_ucred *mdt_ucred_check(const struct mdt_thread_info *info)
5859 {
5860         return lu_ucred_check(info->mti_env);
5861 }
5862
5863 /**
5864  * Enable/disable COS (Commit On Sharing).
5865  *
5866  * Set/Clear the COS flag in mdt options.
5867  *
5868  * \param mdt mdt device
5869  * \param val 0 disables COS, other values enable COS
5870  */
5871 void mdt_enable_cos(struct mdt_device *mdt, int val)
5872 {
5873         struct lu_env env;
5874         int rc;
5875
5876         mdt->mdt_opts.mo_cos = !!val;
5877         rc = lu_env_init(&env, LCT_LOCAL);
5878         if (unlikely(rc != 0)) {
5879                 CWARN("lu_env initialization failed with rc = %d,"
5880                       "cannot sync\n", rc);
5881                 return;
5882         }
5883         mdt_device_sync(&env, mdt);
5884         lu_env_fini(&env);
5885 }
5886
5887 /**
5888  * Check COS (Commit On Sharing) status.
5889  *
5890  * Return COS flag status.
5891  *
5892  * \param mdt mdt device
5893  */
5894 int mdt_cos_is_enabled(struct mdt_device *mdt)
5895 {
5896         return mdt->mdt_opts.mo_cos != 0;
5897 }
5898
5899 static struct lu_device_type_operations mdt_device_type_ops = {
5900         .ldto_device_alloc = mdt_device_alloc,
5901         .ldto_device_free  = mdt_device_free,
5902         .ldto_device_fini  = mdt_device_fini
5903 };
5904
5905 static struct lu_device_type mdt_device_type = {
5906         .ldt_tags     = LU_DEVICE_MD,
5907         .ldt_name     = LUSTRE_MDT_NAME,
5908         .ldt_ops      = &mdt_device_type_ops,
5909         .ldt_ctx_tags = LCT_MD_THREAD
5910 };
5911
5912 static int __init mdt_mod_init(void)
5913 {
5914         struct lprocfs_static_vars lvars;
5915         int rc;
5916
5917         CLASSERT(sizeof("0x0123456789ABCDEF:0x01234567:0x01234567") ==
5918                  FID_NOBRACE_LEN + 1);
5919         CLASSERT(sizeof("[0x0123456789ABCDEF:0x01234567:0x01234567]") ==
5920                  FID_LEN + 1);
5921         rc = lu_kmem_init(mdt_caches);
5922         if (rc)
5923                 return rc;
5924
5925         rc = mds_mod_init();
5926         if (rc)
5927                 GOTO(lu_fini, rc);
5928
5929         lprocfs_mdt_init_vars(&lvars);
5930         rc = class_register_type(&mdt_obd_device_ops, NULL, true, NULL,
5931 #ifndef HAVE_ONLY_PROCFS_SEQ
5932                                  lvars.module_vars,
5933 #endif
5934                                  LUSTRE_MDT_NAME, &mdt_device_type);
5935         if (rc)
5936                 GOTO(mds_fini, rc);
5937 lu_fini:
5938         if (rc)
5939                 lu_kmem_fini(mdt_caches);
5940 mds_fini:
5941         if (rc)
5942                 mds_mod_exit();
5943         return rc;
5944 }
5945
5946 static void __exit mdt_mod_exit(void)
5947 {
5948         class_unregister_type(LUSTRE_MDT_NAME);
5949         mds_mod_exit();
5950         lu_kmem_fini(mdt_caches);
5951 }
5952
5953 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
5954 MODULE_DESCRIPTION("Lustre Metadata Target ("LUSTRE_MDT_NAME")");
5955 MODULE_LICENSE("GPL");
5956
5957 cfs_module(mdt, LUSTRE_VERSION_STRING, mdt_mod_init, mdt_mod_exit);