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