Whamcloud - gitweb
2bc73a42096a408a49ca544dd4d0028e51569933
[fs/lustre-release.git] / lustre / mdd / mdd_object.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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/mdd/mdd_object.c
33  *
34  * Lustre Metadata Server (mdd) routines
35  *
36  * Author: Wang Di <wangdi@clusterfs.com>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/module.h>
42 #include <obd.h>
43 #include <obd_class.h>
44 #include <obd_support.h>
45 #include <lprocfs_status.h>
46 /* fid_be_cpu(), fid_cpu_to_be(). */
47 #include <lustre_fid.h>
48 #include <lustre_idmap.h>
49 #include <uapi/linux/lustre/lustre_param.h>
50 #include <lustre_mds.h>
51
52 #include "mdd_internal.h"
53
54 static const struct lu_object_operations mdd_lu_obj_ops;
55
56 static int mdd_xattr_get(const struct lu_env *env,
57                          struct md_object *obj, struct lu_buf *buf,
58                          const char *name);
59
60 int mdd_la_get(const struct lu_env *env, struct mdd_object *obj,
61                struct lu_attr *la)
62 {
63         int rc;
64
65         if (mdd_object_exists(obj) == 0)
66                 return -ENOENT;
67
68         rc = mdo_attr_get(env, obj, la);
69         if (unlikely(rc != 0)) {
70                 if (rc == -ENOENT)
71                         obj->mod_flags |= DEAD_OBJ;
72                 return rc;
73         }
74
75         if (la->la_valid & LA_FLAGS &&
76             la->la_flags & LUSTRE_ORPHAN_FL)
77                 obj->mod_flags |= ORPHAN_OBJ | DEAD_OBJ;
78
79         return 0;
80 }
81
82 struct mdd_thread_info *mdd_env_info(const struct lu_env *env)
83 {
84         struct mdd_thread_info *info;
85
86         lu_env_refill((struct lu_env *)env);
87         info = lu_context_key_get(&env->le_ctx, &mdd_thread_key);
88         LASSERT(info != NULL);
89         return info;
90 }
91
92 struct lu_buf *mdd_buf_get(const struct lu_env *env, void *area, ssize_t len)
93 {
94         struct lu_buf *buf;
95
96         buf = &mdd_env_info(env)->mti_buf[0];
97         buf->lb_buf = area;
98         buf->lb_len = len;
99         return buf;
100 }
101
102 const struct lu_buf *mdd_buf_get_const(const struct lu_env *env,
103                                        const void *area, ssize_t len)
104 {
105         struct lu_buf *buf;
106
107         buf = &mdd_env_info(env)->mti_buf[0];
108         buf->lb_buf = (void *)area;
109         buf->lb_len = len;
110         return buf;
111 }
112
113 struct lu_object *mdd_object_alloc(const struct lu_env *env,
114                                    const struct lu_object_header *hdr,
115                                    struct lu_device *d)
116 {
117         struct mdd_object *mdd_obj;
118
119         OBD_SLAB_ALLOC_PTR_GFP(mdd_obj, mdd_object_kmem, GFP_NOFS);
120         if (mdd_obj != NULL) {
121                 struct lu_object *o;
122
123                 o = mdd2lu_obj(mdd_obj);
124                 lu_object_init(o, NULL, d);
125                 mdd_obj->mod_obj.mo_ops = &mdd_obj_ops;
126                 mdd_obj->mod_obj.mo_dir_ops = &mdd_dir_ops;
127                 mdd_obj->mod_count = 0;
128                 o->lo_ops = &mdd_lu_obj_ops;
129                 return o;
130         } else {
131                 return NULL;
132         }
133 }
134
135 static int mdd_object_init(const struct lu_env *env, struct lu_object *o,
136                            const struct lu_object_conf *unused)
137 {
138         struct mdd_device *d = lu2mdd_dev(o->lo_dev);
139         struct mdd_object *mdd_obj = lu2mdd_obj(o);
140         struct lu_object  *below;
141         struct lu_device  *under;
142         ENTRY;
143
144         mdd_obj->mod_cltime = ktime_set(0, 0);
145         under = &d->mdd_child->dd_lu_dev;
146         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
147         if (IS_ERR(below))
148                 RETURN(PTR_ERR(below));
149
150         lu_object_add(o, below);
151
152         RETURN(0);
153 }
154
155 static int mdd_object_start(const struct lu_env *env, struct lu_object *o)
156 {
157         int rc = 0;
158
159         if (lu_object_exists(o)) {
160                 struct mdd_object *mdd_obj = lu2mdd_obj(o);
161                 struct lu_attr *attr = MDD_ENV_VAR(env, la_for_start);
162
163                 rc = mdd_la_get(env, mdd_obj, attr);
164         }
165
166         return rc;
167 }
168
169 static void mdd_object_free(const struct lu_env *env, struct lu_object *o)
170 {
171         struct mdd_object *mdd = lu2mdd_obj(o);
172
173         lu_object_fini(o);
174         OBD_SLAB_FREE_PTR(mdd, mdd_object_kmem);
175 }
176
177 static int mdd_object_print(const struct lu_env *env, void *cookie,
178                             lu_printer_t p, const struct lu_object *o)
179 {
180         struct mdd_object *mdd = lu2mdd_obj((struct lu_object *)o);
181
182         return (*p)(env, cookie,
183                     LUSTRE_MDD_NAME"-object@%p(open_count=%d, valid=%x, cltime=%lldns, flags=%lx)",
184                     mdd, mdd->mod_count, mdd->mod_valid,
185                     ktime_to_ns(mdd->mod_cltime), mdd->mod_flags);
186 }
187
188 static const struct lu_object_operations mdd_lu_obj_ops = {
189         .loo_object_init    = mdd_object_init,
190         .loo_object_start   = mdd_object_start,
191         .loo_object_free    = mdd_object_free,
192         .loo_object_print   = mdd_object_print,
193 };
194
195 struct mdd_object *mdd_object_find(const struct lu_env *env,
196                                    struct mdd_device *d,
197                                    const struct lu_fid *f)
198 {
199         return md2mdd_obj(md_object_find_slice(env, &d->mdd_md_dev, f));
200 }
201
202 /*
203  * No permission check is needed.
204  */
205 int mdd_attr_get(const struct lu_env *env, struct md_object *obj,
206                  struct md_attr *ma)
207 {
208         struct mdd_object *mdd_obj = md2mdd_obj(obj);
209         int               rc;
210
211         ENTRY;
212
213         rc = mdd_la_get(env, mdd_obj, &ma->ma_attr);
214         if ((ma->ma_need & MA_INODE) != 0 && mdd_is_dead_obj(mdd_obj))
215                 ma->ma_attr.la_nlink = 0;
216
217         RETURN(rc);
218 }
219
220 /*
221  * No permission check is needed.
222  */
223 static int mdd_xattr_get(const struct lu_env *env,
224                          struct md_object *obj, struct lu_buf *buf,
225                          const char *name)
226 {
227         struct mdd_object *mdd_obj = md2mdd_obj(obj);
228         int rc;
229
230         ENTRY;
231
232         if (mdd_object_exists(mdd_obj) == 0) {
233                 CERROR("%s: object "DFID" not found: rc = -2\n",
234                        mdd_obj_dev_name(mdd_obj),PFID(mdd_object_fid(mdd_obj)));
235                 return -ENOENT;
236         }
237
238         /* If the object has been destroyed, then do not get LMVEA, because
239          * it needs to load stripes from the iteration of the master object,
240          * and it will cause problem if master object has been destroyed, see
241          * LU-6427 */
242         if (unlikely((mdd_obj->mod_flags & DEAD_OBJ) &&
243                      !(mdd_obj->mod_flags & ORPHAN_OBJ) &&
244                       strcmp(name, XATTR_NAME_LMV) == 0))
245                 RETURN(-ENOENT);
246
247         /* If the object has been delete from the namespace, then
248          * get linkEA should return -ENOENT as well */
249         if (unlikely((mdd_obj->mod_flags & (DEAD_OBJ | ORPHAN_OBJ)) &&
250                       strcmp(name, XATTR_NAME_LINK) == 0))
251                 RETURN(-ENOENT);
252
253         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
254         rc = mdo_xattr_get(env, mdd_obj, buf, name);
255         mdd_read_unlock(env, mdd_obj);
256
257         RETURN(rc);
258 }
259
260 /*
261  * Permission check is done when open,
262  * no need check again.
263  */
264 int mdd_readlink(const struct lu_env *env, struct md_object *obj,
265                  struct lu_buf *buf)
266 {
267         struct mdd_object *mdd_obj = md2mdd_obj(obj);
268         struct dt_object  *next;
269         loff_t             pos = 0;
270         int                rc;
271         ENTRY;
272
273         if (mdd_object_exists(mdd_obj) == 0) {
274                 CERROR("%s: object "DFID" not found: rc = -2\n",
275                        mdd_obj_dev_name(mdd_obj),PFID(mdd_object_fid(mdd_obj)));
276                 return -ENOENT;
277         }
278
279         next = mdd_object_child(mdd_obj);
280         LASSERT(next != NULL);
281         LASSERT(next->do_body_ops != NULL);
282         LASSERT(next->do_body_ops->dbo_read != NULL);
283         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
284         rc = dt_read(env, next, buf, &pos);
285         mdd_read_unlock(env, mdd_obj);
286         RETURN(rc);
287 }
288
289 /*
290  * No permission check is needed.
291  */
292 static int mdd_xattr_list(const struct lu_env *env, struct md_object *obj,
293                           struct lu_buf *buf)
294 {
295         struct mdd_object *mdd_obj = md2mdd_obj(obj);
296         int rc;
297
298         ENTRY;
299
300         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
301         rc = mdo_xattr_list(env, mdd_obj, buf);
302         mdd_read_unlock(env, mdd_obj);
303
304         /* If the buffer is NULL then we are only here to get the
305          * length of the xattr name list. */
306         if (rc < 0 || buf->lb_buf == NULL)
307                 RETURN(rc);
308
309         /*
310          * Filter out XATTR_NAME_LINK if this is an orphan object.  See
311          * mdd_xattr_get().
312          */
313         if (unlikely(mdd_obj->mod_flags & (DEAD_OBJ | ORPHAN_OBJ))) {
314                 char   *end = (char *)buf->lb_buf + rc;
315                 char   *p = buf->lb_buf;
316
317                 while (p < end) {
318                         char   *next = p + strlen(p) + 1;
319
320                         if (strcmp(p, XATTR_NAME_LINK) == 0) {
321                                 if (end - next > 0)
322                                         memmove(p, next, end - next);
323                                 rc -= next - p;
324                                 CDEBUG(D_INFO, "Filtered out "XATTR_NAME_LINK
325                                        " of orphan "DFID"\n",
326                                        PFID(mdd_object_fid(mdd_obj)));
327                                 break;
328                         }
329
330                         p = next;
331                 }
332         }
333
334         RETURN(rc);
335 }
336
337 int mdd_invalidate(const struct lu_env *env, struct md_object *obj)
338 {
339         return mdo_invalidate(env, md2mdd_obj(obj));
340 }
341
342 int mdd_declare_create_object_internal(const struct lu_env *env,
343                                        struct mdd_object *p,
344                                        struct mdd_object *c,
345                                        struct lu_attr *attr,
346                                        struct thandle *handle,
347                                        const struct md_op_spec *spec,
348                                        struct dt_allocation_hint *hint)
349 {
350         struct dt_object_format *dof = &mdd_env_info(env)->mti_dof;
351         const struct dt_index_features *feat = spec->sp_feat;
352         int rc;
353         ENTRY;
354
355         if (feat != &dt_directory_features && feat != NULL) {
356                 dof->dof_type = DFT_INDEX;
357                 dof->u.dof_idx.di_feat = feat;
358         } else {
359                 dof->dof_type = dt_mode_to_dft(attr->la_mode);
360                 if (dof->dof_type == DFT_REGULAR) {
361                         dof->u.dof_reg.striped =
362                                 md_should_create(spec->sp_cr_flags);
363                         if (spec->sp_cr_flags & MDS_OPEN_HAS_EA)
364                                 dof->u.dof_reg.striped = 0;
365                         /* is this replay? */
366                         if (spec->no_create)
367                                 dof->u.dof_reg.striped = 0;
368                 }
369         }
370
371         rc = mdo_declare_create_object(env, c, attr, hint, dof, handle);
372
373         RETURN(rc);
374 }
375
376 int mdd_create_object_internal(const struct lu_env *env, struct mdd_object *p,
377                                struct mdd_object *c, struct lu_attr *attr,
378                                struct thandle *handle,
379                                const struct md_op_spec *spec,
380                                struct dt_allocation_hint *hint)
381 {
382         struct dt_object_format *dof = &mdd_env_info(env)->mti_dof;
383         int rc;
384         ENTRY;
385
386         LASSERT(!mdd_object_exists(c));
387
388         rc = mdo_create_object(env, c, attr, hint, dof, handle);
389
390         RETURN(rc);
391 }
392
393 int mdd_attr_set_internal(const struct lu_env *env, struct mdd_object *obj,
394                           const struct lu_attr *attr, struct thandle *handle,
395                           int needacl)
396 {
397         int rc;
398         ENTRY;
399
400         rc = mdo_attr_set(env, obj, attr, handle);
401 #ifdef CONFIG_FS_POSIX_ACL
402         if (!rc && (attr->la_valid & LA_MODE) && needacl)
403                 rc = mdd_acl_chmod(env, obj, attr->la_mode, handle);
404 #endif
405         RETURN(rc);
406 }
407
408 int mdd_update_time(const struct lu_env *env, struct mdd_object *obj,
409                     const struct lu_attr *oattr, struct lu_attr *attr,
410                     struct thandle *handle)
411 {
412         int rc = 0;
413         ENTRY;
414
415         LASSERT(attr->la_valid & LA_CTIME);
416         LASSERT(oattr != NULL);
417
418         /* Make sure the ctime is increased only, however, it's not strictly
419          * reliable at here because there is not guarantee to hold lock on
420          * object, so we just bypass some unnecessary cmtime setting first
421          * and OSD has to check it again. */
422         if (attr->la_ctime < oattr->la_ctime)
423                 attr->la_valid &= ~(LA_MTIME | LA_CTIME);
424         else if (attr->la_valid == LA_CTIME &&
425                  attr->la_ctime == oattr->la_ctime)
426                 attr->la_valid &= ~LA_CTIME;
427
428         if (attr->la_valid != 0)
429                 rc = mdd_attr_set_internal(env, obj, attr, handle, 0);
430         RETURN(rc);
431 }
432
433 /*
434  * This gives the same functionality as the code between
435  * sys_chmod and inode_setattr
436  * chown_common and inode_setattr
437  * utimes and inode_setattr
438  * This API is ported from mds_fix_attr but remove some unnecesssary stuff.
439  */
440 static int mdd_fix_attr(const struct lu_env *env, struct mdd_object *obj,
441                         const struct lu_attr *oattr, struct lu_attr *la,
442                         const unsigned long flags)
443 {
444         struct lu_ucred  *uc;
445         int               rc = 0;
446         ENTRY;
447
448         if (!la->la_valid)
449                 RETURN(0);
450
451         /* Do not permit change file type */
452         if (la->la_valid & LA_TYPE)
453                 RETURN(-EPERM);
454
455         /* They should not be processed by setattr */
456         if (la->la_valid & (LA_NLINK | LA_RDEV | LA_BLKSIZE))
457                 RETURN(-EPERM);
458
459         LASSERT(oattr != NULL);
460
461         uc = lu_ucred_check(env);
462         if (uc == NULL)
463                 RETURN(0);
464
465         if (la->la_valid == LA_CTIME) {
466                 if (!(flags & MDS_PERM_BYPASS))
467                         /* This is only for set ctime when rename's source is
468                          * on remote MDS. */
469                         rc = mdd_may_delete(env, NULL, NULL, obj, oattr, NULL,
470                                             1, 0);
471                 if (rc == 0 && la->la_ctime <= oattr->la_ctime)
472                         la->la_valid &= ~LA_CTIME;
473                 RETURN(rc);
474         }
475
476         if (la->la_valid == LA_ATIME) {
477                 /* This is an atime-only attribute update for close RPCs. */
478                 if (la->la_atime < (oattr->la_atime +
479                                 mdd_obj2mdd_dev(obj)->mdd_atime_diff))
480                         la->la_valid &= ~LA_ATIME;
481                 RETURN(0);
482         }
483
484         /* Check if flags change. */
485         if (la->la_valid & LA_FLAGS) {
486                 unsigned int oldflags = oattr->la_flags &
487                                 (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL);
488                 unsigned int newflags = la->la_flags &
489                                 (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL);
490
491                 if ((uc->uc_fsuid != oattr->la_uid) &&
492                     !md_capable(uc, CFS_CAP_FOWNER))
493                         RETURN(-EPERM);
494
495                 /* The IMMUTABLE and APPEND_ONLY flags can
496                  * only be changed by the relevant capability. */
497                 if ((oldflags ^ newflags) &&
498                     !md_capable(uc, CFS_CAP_LINUX_IMMUTABLE))
499                         RETURN(-EPERM);
500
501                 if (!S_ISDIR(oattr->la_mode))
502                         la->la_flags &= ~(LUSTRE_DIRSYNC_FL | LUSTRE_TOPDIR_FL);
503         }
504
505         if (oattr->la_flags & (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL) &&
506             (la->la_valid & ~LA_FLAGS) &&
507             !(flags & MDS_PERM_BYPASS))
508                 RETURN(-EPERM);
509
510         /* Check for setting the obj time. */
511         if ((la->la_valid & (LA_MTIME | LA_ATIME | LA_CTIME)) &&
512             !(la->la_valid & ~(LA_MTIME | LA_ATIME | LA_CTIME))) {
513                 if ((uc->uc_fsuid != oattr->la_uid) &&
514                     !md_capable(uc, CFS_CAP_FOWNER)) {
515                         rc = mdd_permission_internal(env, obj, oattr,
516                                                      MAY_WRITE);
517                         if (rc)
518                                 RETURN(rc);
519                 }
520         }
521
522         if (la->la_valid & LA_KILL_SUID) {
523                 la->la_valid &= ~LA_KILL_SUID;
524                 if ((oattr->la_mode & S_ISUID) &&
525                     !(la->la_valid & LA_MODE)) {
526                         la->la_mode = oattr->la_mode;
527                         la->la_valid |= LA_MODE;
528                 }
529                 la->la_mode &= ~S_ISUID;
530         }
531
532         if (la->la_valid & LA_KILL_SGID) {
533                 la->la_valid &= ~LA_KILL_SGID;
534                 if (((oattr->la_mode & (S_ISGID | S_IXGRP)) ==
535                         (S_ISGID | S_IXGRP)) &&
536                     !(la->la_valid & LA_MODE)) {
537                         la->la_mode = oattr->la_mode;
538                         la->la_valid |= LA_MODE;
539                 }
540                 la->la_mode &= ~S_ISGID;
541         }
542
543         /* Make sure a caller can chmod. */
544         if (la->la_valid & LA_MODE) {
545                 if (!(flags & MDS_PERM_BYPASS) &&
546                     (uc->uc_fsuid != oattr->la_uid) &&
547                     !md_capable(uc, CFS_CAP_FOWNER))
548                         RETURN(-EPERM);
549
550                 if (la->la_mode == (umode_t) -1)
551                         la->la_mode = oattr->la_mode;
552                 else
553                         la->la_mode = (la->la_mode & S_IALLUGO) |
554                                         (oattr->la_mode & ~S_IALLUGO);
555
556                 /* Also check the setgid bit! */
557                 if (!lustre_in_group_p(uc, (la->la_valid & LA_GID) ?
558                                        la->la_gid : oattr->la_gid) &&
559                     !md_capable(uc, CFS_CAP_FSETID))
560                         la->la_mode &= ~S_ISGID;
561         } else {
562                la->la_mode = oattr->la_mode;
563         }
564
565         /* Make sure a caller can chown. */
566         if (la->la_valid & LA_UID) {
567                 if (la->la_uid == (uid_t) -1)
568                         la->la_uid = oattr->la_uid;
569                 if (((uc->uc_fsuid != oattr->la_uid) ||
570                      (la->la_uid != oattr->la_uid)) &&
571                     !md_capable(uc, CFS_CAP_CHOWN))
572                         RETURN(-EPERM);
573
574                 /* If the user or group of a non-directory has been
575                  * changed by a non-root user, remove the setuid bit.
576                  * 19981026 David C Niemi <niemi@tux.org>
577                  *
578                  * Changed this to apply to all users, including root,
579                  * to avoid some races. This is the behavior we had in
580                  * 2.0. The check for non-root was definitely wrong
581                  * for 2.2 anyway, as it should have been using
582                  * CAP_FSETID rather than fsuid -- 19990830 SD. */
583                 if (((oattr->la_mode & S_ISUID) == S_ISUID) &&
584                 !S_ISDIR(oattr->la_mode)) {
585                         la->la_mode &= ~S_ISUID;
586                         la->la_valid |= LA_MODE;
587                 }
588         }
589
590         /* Make sure caller can chgrp. */
591         if (la->la_valid & LA_GID) {
592                 if (la->la_gid == (gid_t) -1)
593                         la->la_gid = oattr->la_gid;
594                 if (((uc->uc_fsuid != oattr->la_uid) ||
595                      ((la->la_gid != oattr->la_gid) &&
596                       !lustre_in_group_p(uc, la->la_gid))) &&
597                     !md_capable(uc, CFS_CAP_CHOWN))
598                         RETURN(-EPERM);
599
600                 /* Likewise, if the user or group of a non-directory
601                  * has been changed by a non-root user, remove the
602                  * setgid bit UNLESS there is no group execute bit
603                  * (this would be a file marked for mandatory
604                  * locking).  19981026 David C Niemi <niemi@tux.org>
605                  *
606                  * Removed the fsuid check (see the comment above) --
607                  * 19990830 SD. */
608                 if (((oattr->la_mode & (S_ISGID | S_IXGRP)) ==
609                     (S_ISGID | S_IXGRP)) && !S_ISDIR(oattr->la_mode)) {
610                         la->la_mode &= ~S_ISGID;
611                         la->la_valid |= LA_MODE;
612                 }
613         }
614
615         if (la->la_valid & (LA_SIZE | LA_BLOCKS)) {
616                 if (!((flags & MDS_OWNEROVERRIDE) &&
617                       (uc->uc_fsuid == oattr->la_uid)) &&
618                     !(flags & MDS_PERM_BYPASS)) {
619                         rc = mdd_permission_internal(env, obj, oattr,
620                                                      MAY_WRITE);
621                         if (rc != 0)
622                                 RETURN(rc);
623                 }
624         }
625
626         if (la->la_valid & LA_CTIME) {
627                 /* The pure setattr, it has the priority over what is
628                  * already set, do not drop it if ctime is equal. */
629                 if (la->la_ctime < oattr->la_ctime)
630                         la->la_valid &= ~(LA_ATIME | LA_MTIME | LA_CTIME);
631         }
632
633         RETURN(0);
634 }
635
636 static int mdd_changelog_data_store_by_fid(const struct lu_env *env,
637                                     struct mdd_device *mdd,
638                                     enum changelog_rec_type type, int flags,
639                                     const struct lu_fid *fid,
640                                     struct thandle *handle)
641 {
642         const struct lu_ucred *uc = lu_ucred(env);
643         struct llog_changelog_rec *rec;
644         struct lu_buf *buf;
645         int reclen;
646         int xflags = CLFE_INVALID;
647         int rc;
648
649         flags = (flags & CLF_FLAGMASK) | CLF_VERSION | CLF_EXTRA_FLAGS;
650
651         if (uc) {
652                 if (uc->uc_jobid[0] != '\0')
653                         flags |= CLF_JOBID;
654                 xflags |= CLFE_UIDGID;
655                 xflags |= CLFE_NID;
656         }
657         if (type == CL_OPEN)
658                 xflags |= CLFE_OPEN;
659
660         reclen = llog_data_len(LLOG_CHANGELOG_HDR_SZ +
661                                changelog_rec_offset(flags & CLF_SUPPORTED,
662                                                     xflags & CLFE_SUPPORTED));
663         buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf, reclen);
664         if (buf->lb_buf == NULL)
665                 RETURN(-ENOMEM);
666         rec = buf->lb_buf;
667
668         rec->cr_hdr.lrh_len = reclen;
669         rec->cr.cr_flags = flags;
670         rec->cr.cr_type = (__u32)type;
671         rec->cr.cr_tfid = *fid;
672         rec->cr.cr_namelen = 0;
673
674         if (flags & CLF_JOBID)
675                 mdd_changelog_rec_ext_jobid(&rec->cr, uc->uc_jobid);
676
677         if (flags & CLF_EXTRA_FLAGS) {
678                 mdd_changelog_rec_ext_extra_flags(&rec->cr, xflags);
679                 if (xflags & CLFE_UIDGID)
680                         mdd_changelog_rec_extra_uidgid(&rec->cr,
681                                                        uc->uc_uid, uc->uc_gid);
682                 if (xflags & CLFE_NID)
683                         mdd_changelog_rec_extra_nid(&rec->cr, uc->uc_nid);
684                 if (xflags & CLFE_OPEN)
685                         mdd_changelog_rec_extra_omode(&rec->cr, flags);
686         }
687
688         rc = mdd_changelog_store(env, mdd, rec, handle);
689         RETURN(rc);
690 }
691
692
693 /** Store a data change changelog record
694  * If this fails, we must fail the whole transaction; we don't
695  * want the change to commit without the log entry.
696  * \param mdd_obj - mdd_object of change
697  * \param handle - transaction handle
698  */
699 int mdd_changelog_data_store(const struct lu_env *env, struct mdd_device *mdd,
700                              enum changelog_rec_type type, int flags,
701                              struct mdd_object *mdd_obj, struct thandle *handle)
702 {
703         int                              rc;
704
705         LASSERT(mdd_obj != NULL);
706         LASSERT(handle != NULL);
707
708         /* Not recording */
709         if (!(mdd->mdd_cl.mc_flags & CLM_ON))
710                 RETURN(0);
711         if ((mdd->mdd_cl.mc_mask & (1 << type)) == 0)
712                 RETURN(0);
713
714         if (mdd_is_volatile_obj(mdd_obj))
715                 RETURN(0);
716
717         if ((type >= CL_MTIME) && (type <= CL_ATIME) &&
718             ktime_before(mdd->mdd_cl.mc_starttime, mdd_obj->mod_cltime)) {
719                 /* Don't need multiple updates in this log */
720                 /* Don't check under lock - no big deal if we get an extra
721                    entry */
722                 RETURN(0);
723         }
724
725         rc = mdd_changelog_data_store_by_fid(env, mdd, type, flags,
726                                              mdo2fid(mdd_obj), handle);
727         if (rc == 0)
728                 mdd_obj->mod_cltime = ktime_get();
729
730         RETURN(rc);
731 }
732
733 static int mdd_changelog(const struct lu_env *env, enum changelog_rec_type type,
734                   int flags, struct md_device *m, const struct lu_fid *fid)
735 {
736         struct thandle *handle;
737         struct mdd_device *mdd = lu2mdd_dev(&m->md_lu_dev);
738         int rc;
739         ENTRY;
740
741         /* Not recording */
742         if (!(mdd->mdd_cl.mc_flags & CLM_ON))
743                 RETURN(0);
744         if (!(mdd->mdd_cl.mc_mask & (1 << type)))
745                 RETURN(0);
746
747         LASSERT(fid != NULL);
748
749         handle = mdd_trans_create(env, mdd);
750         if (IS_ERR(handle))
751                 RETURN(PTR_ERR(handle));
752
753         rc = mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
754         if (rc)
755                 GOTO(stop, rc);
756
757         rc = mdd_trans_start(env, mdd, handle);
758         if (rc)
759                 GOTO(stop, rc);
760
761         rc = mdd_changelog_data_store_by_fid(env, mdd, type, flags,
762                                                      fid, handle);
763
764 stop:
765         rc = mdd_trans_stop(env, mdd, rc, handle);
766
767         RETURN(rc);
768 }
769
770 /**
771  * Save LMA extended attributes with data from \a ma.
772  *
773  * HSM and Size-On-MDS data will be extracted from \ma if they are valid, if
774  * not, LMA EA will be first read from disk, modified and write back.
775  *
776  */
777 /* Precedence for choosing record type when multiple
778  * attributes change: setattr > mtime > ctime > atime
779  * (ctime changes when mtime does, plus chmod/chown.
780  * atime and ctime are independent.) */
781 static int mdd_attr_set_changelog(const struct lu_env *env,
782                                   struct md_object *obj, struct thandle *handle,
783                                   __u64 valid)
784 {
785         struct mdd_device *mdd = mdo2mdd(obj);
786         int bits, type = 0;
787
788         bits =  (valid & LA_SIZE)  ? 1 << CL_TRUNC : 0;
789         bits |= (valid & ~(LA_CTIME|LA_MTIME|LA_ATIME)) ? 1 << CL_SETATTR : 0;
790         bits |= (valid & LA_MTIME) ? 1 << CL_MTIME : 0;
791         bits |= (valid & LA_CTIME) ? 1 << CL_CTIME : 0;
792         bits |= (valid & LA_ATIME) ? 1 << CL_ATIME : 0;
793         bits = bits & mdd->mdd_cl.mc_mask;
794         /* This is an implementation limit rather than a protocol limit */
795         CLASSERT(CL_LAST <= sizeof(int) * 8);
796         if (bits == 0)
797                 return 0;
798
799         /* The record type is the lowest non-masked set bit */
800         type = __ffs(bits);
801
802         /* FYI we only store the first CLF_FLAGMASK bits of la_valid */
803         return mdd_changelog_data_store(env, mdd, type, (int)valid,
804                                         md2mdd_obj(obj), handle);
805 }
806
807 static int mdd_declare_attr_set(const struct lu_env *env,
808                                 struct mdd_device *mdd,
809                                 struct mdd_object *obj,
810                                 const struct lu_attr *attr,
811                                 struct thandle *handle)
812 {
813         int rc;
814
815         rc = mdo_declare_attr_set(env, obj, attr, handle);
816         if (rc)
817                 return rc;
818
819 #ifdef CONFIG_FS_POSIX_ACL
820         if (attr->la_valid & LA_MODE) {
821                 mdd_read_lock(env, obj, MOR_TGT_CHILD);
822                 rc = mdo_xattr_get(env, obj, &LU_BUF_NULL,
823                                    XATTR_NAME_ACL_ACCESS);
824                 mdd_read_unlock(env, obj);
825                 if (rc == -EOPNOTSUPP || rc == -ENODATA)
826                         rc = 0;
827                 else if (rc < 0)
828                         return rc;
829
830                 if (rc != 0) {
831                         struct lu_buf *buf = mdd_buf_get(env, NULL, rc);
832                         rc = mdo_declare_xattr_set(env, obj, buf,
833                                                    XATTR_NAME_ACL_ACCESS, 0,
834                                                    handle);
835                         if (rc)
836                                 return rc;
837                 }
838         }
839 #endif
840
841         rc = mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
842         return rc;
843 }
844
845 /*
846  * LU-3671
847  *
848  * permission changes may require sync operation, to mitigate performance
849  * impact, only do this for dir and when permission is reduced.
850  *
851  * For regular files, version is updated with permission change (see VBR), async
852  * permission won't cause any issue, while missing permission change on
853  * directory may affect accessibility of other objects after recovery.
854  */
855 static inline bool permission_needs_sync(const struct lu_attr *old,
856                                          const struct lu_attr *new)
857 {
858         if (!S_ISDIR(old->la_mode))
859                 return false;
860
861         if (new->la_valid & (LA_UID | LA_GID))
862                 return true;
863
864         if (new->la_valid & LA_MODE &&
865             new->la_mode & (S_ISUID | S_ISGID | S_ISVTX))
866                 return true;
867
868         if ((new->la_valid & LA_MODE) &&
869             ((new->la_mode & old->la_mode) & S_IRWXUGO) !=
870              (old->la_mode & S_IRWXUGO))
871                 return true;
872
873         return false;
874 }
875
876 /* set attr and LOV EA at once, return updated attr */
877 int mdd_attr_set(const struct lu_env *env, struct md_object *obj,
878                  const struct md_attr *ma)
879 {
880         struct mdd_object *mdd_obj = md2mdd_obj(obj);
881         struct mdd_device *mdd = mdo2mdd(obj);
882         struct thandle *handle;
883         struct lu_attr *la_copy = &mdd_env_info(env)->mti_la_for_fix;
884         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
885         const struct lu_attr *la = &ma->ma_attr;
886         int rc;
887         ENTRY;
888
889         /* we do not use ->attr_set() for LOV/HSM EA any more */
890         LASSERT((ma->ma_valid & MA_LOV) == 0);
891         LASSERT((ma->ma_valid & MA_HSM) == 0);
892
893         rc = mdd_la_get(env, mdd_obj, attr);
894         if (rc)
895                 RETURN(rc);
896
897         *la_copy = ma->ma_attr;
898         rc = mdd_fix_attr(env, mdd_obj, attr, la_copy, ma->ma_attr_flags);
899         if (rc)
900                 RETURN(rc);
901
902         /* no need to setattr anymore */
903         if (la_copy->la_valid == 0) {
904                 CDEBUG(D_INODE, "%s: no valid attribute on "DFID", previous"
905                        "valid is %#llx\n", mdd2obd_dev(mdd)->obd_name,
906                        PFID(mdo2fid(mdd_obj)), la->la_valid);
907
908                 RETURN(0);
909         }
910
911         handle = mdd_trans_create(env, mdd);
912         if (IS_ERR(handle))
913                 RETURN(PTR_ERR(handle));
914
915         rc = mdd_declare_attr_set(env, mdd, mdd_obj, la_copy, handle);
916         if (rc)
917                 GOTO(stop, rc);
918
919         rc = mdd_trans_start(env, mdd, handle);
920         if (rc)
921                 GOTO(stop, rc);
922
923         if (mdd->mdd_sync_permission && permission_needs_sync(attr, la))
924                 handle->th_sync = 1;
925
926         if (la->la_valid & (LA_MTIME | LA_CTIME))
927                 CDEBUG(D_INODE, "setting mtime %llu, ctime %llu\n",
928                        la->la_mtime, la->la_ctime);
929
930         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
931         if (la_copy->la_valid & LA_FLAGS)
932                 rc = mdd_attr_set_internal(env, mdd_obj, la_copy, handle, 1);
933         else if (la_copy->la_valid) /* setattr */
934                 rc = mdd_attr_set_internal(env, mdd_obj, la_copy, handle, 1);
935         mdd_write_unlock(env, mdd_obj);
936
937         if (rc == 0)
938                 rc = mdd_attr_set_changelog(env, obj, handle,
939                                             la_copy->la_valid);
940
941         GOTO(stop, rc);
942
943 stop:
944         rc = mdd_trans_stop(env, mdd, rc, handle);
945
946         return rc;
947 }
948
949 static int mdd_xattr_sanity_check(const struct lu_env *env,
950                                   struct mdd_object *obj,
951                                   const struct lu_attr *attr,
952                                   const char *name)
953 {
954         struct lu_ucred *uc     = lu_ucred_assert(env);
955         ENTRY;
956
957         if (attr->la_flags & (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL))
958                 RETURN(-EPERM);
959
960         if (strncmp(XATTR_USER_PREFIX, name,
961                     sizeof(XATTR_USER_PREFIX) - 1) == 0) {
962                 /* For sticky directories, only the owner and privileged user
963                  * can write attributes. */
964                 if (S_ISDIR(attr->la_mode) && (attr->la_mode & S_ISVTX) &&
965                     (uc->uc_fsuid != attr->la_uid) &&
966                     !md_capable(uc, CFS_CAP_FOWNER))
967                         RETURN(-EPERM);
968         } else {
969                 if ((uc->uc_fsuid != attr->la_uid) &&
970                     !md_capable(uc, CFS_CAP_FOWNER))
971                         RETURN(-EPERM);
972         }
973
974         RETURN(0);
975 }
976
977 /**
978  * Check if a string begins with a given prefix.
979  *
980  * \param str     String to check
981  * \param prefix  Substring to check at the beginning of \a str
982  * \return true/false whether the condition is verified.
983  */
984 static inline bool has_prefix(const char *str, const char *prefix)
985 {
986         return strncmp(prefix, str, strlen(prefix)) == 0;
987 }
988
989 /**
990  * Indicate the kind of changelog to store (if any) for a xattr set/del.
991  *
992  * \param[in]  xattr_name  Full extended attribute name.
993  *
994  * \return The type of changelog to use, or -1 if no changelog is to be emitted.
995  */
996 static enum changelog_rec_type
997 mdd_xattr_changelog_type(const struct lu_env *env, struct mdd_device *mdd,
998                          const char *xattr_name)
999 {
1000         /* Layout changes systematically recorded */
1001         if (strcmp(XATTR_NAME_LOV, xattr_name) == 0 ||
1002             strncmp(XATTR_LUSTRE_LOV, xattr_name,
1003                     strlen(XATTR_LUSTRE_LOV)) == 0)
1004                 return CL_LAYOUT;
1005
1006         /* HSM information changes systematically recorded */
1007         if (strcmp(XATTR_NAME_HSM, xattr_name) == 0)
1008                 return CL_HSM;
1009
1010         if (has_prefix(xattr_name, XATTR_USER_PREFIX) ||
1011             has_prefix(xattr_name, XATTR_NAME_POSIX_ACL_ACCESS) ||
1012             has_prefix(xattr_name, XATTR_NAME_POSIX_ACL_DEFAULT))
1013                 return CL_XATTR;
1014
1015         return -1;
1016 }
1017
1018 static int mdd_declare_xattr_set(const struct lu_env *env,
1019                                  struct mdd_device *mdd,
1020                                  struct mdd_object *obj,
1021                                  const struct lu_buf *buf,
1022                                  const char *name,
1023                                  int fl, struct thandle *handle)
1024 {
1025         int     rc;
1026
1027         rc = mdo_declare_xattr_set(env, obj, buf, name, fl, handle);
1028         if (rc)
1029                 return rc;
1030
1031         if (mdd_xattr_changelog_type(env, mdd, name) < 0)
1032                 return 0; /* no changelog to store */
1033
1034         return mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
1035 }
1036
1037 /*
1038  * Compare current and future data of HSM EA and add a changelog if needed.
1039  *
1040  * Caller should have write-locked \param obj.
1041  *
1042  * \param buf - Future HSM EA content.
1043  * \retval 0 if no changelog is needed or changelog was added properly.
1044  * \retval -ve errno if there was a problem
1045  */
1046 static int mdd_hsm_update_locked(const struct lu_env *env,
1047                                  struct md_object *obj,
1048                                  const struct lu_buf *buf,
1049                                  struct thandle *handle, int *cl_flags)
1050 {
1051         struct mdd_thread_info *info = mdd_env_info(env);
1052         struct mdd_object      *mdd_obj = md2mdd_obj(obj);
1053         struct lu_buf          *current_buf;
1054         struct md_hsm          *current_mh;
1055         struct md_hsm          *new_mh;
1056         int                     rc;
1057         ENTRY;
1058
1059         OBD_ALLOC_PTR(current_mh);
1060         if (current_mh == NULL)
1061                 RETURN(-ENOMEM);
1062
1063         /* Read HSM attrs from disk */
1064         current_buf = lu_buf_check_and_alloc(&info->mti_xattr_buf,
1065                                 mdo2mdd(obj)->mdd_dt_conf.ddp_max_ea_size);
1066         rc = mdo_xattr_get(env, mdd_obj, current_buf, XATTR_NAME_HSM);
1067         rc = lustre_buf2hsm(current_buf->lb_buf, rc, current_mh);
1068         if (rc < 0 && rc != -ENODATA)
1069                 GOTO(free, rc);
1070         else if (rc == -ENODATA)
1071                 current_mh->mh_flags = 0;
1072
1073         /* Map future HSM xattr */
1074         OBD_ALLOC_PTR(new_mh);
1075         if (new_mh == NULL)
1076                 GOTO(free, rc = -ENOMEM);
1077         lustre_buf2hsm(buf->lb_buf, buf->lb_len, new_mh);
1078
1079         rc = 0;
1080
1081         /* Flags differ, set flags for the changelog that will be added */
1082         if (current_mh->mh_flags != new_mh->mh_flags) {
1083                 hsm_set_cl_event(cl_flags, HE_STATE);
1084                 if (new_mh->mh_flags & HS_DIRTY)
1085                         hsm_set_cl_flags(cl_flags, CLF_HSM_DIRTY);
1086         }
1087
1088         OBD_FREE_PTR(new_mh);
1089         EXIT;
1090 free:
1091         OBD_FREE_PTR(current_mh);
1092         return rc;
1093 }
1094
1095 static int mdd_object_pfid_replace(const struct lu_env *env,
1096                                    struct mdd_object *o)
1097 {
1098         struct mdd_device *mdd = mdo2mdd(&o->mod_obj);
1099         struct thandle *handle;
1100         int rc;
1101
1102         handle = mdd_trans_create(env, mdd);
1103         if (IS_ERR(handle))
1104                 RETURN(PTR_ERR(handle));
1105
1106         handle->th_complex = 1;
1107
1108         /* it doesn't need to track the PFID update via llog, because LFSCK
1109          * will repair it even it goes wrong */
1110         rc = mdd_declare_xattr_set(env, mdd, o, NULL, XATTR_NAME_FID,
1111                                    0, handle);
1112         if (rc)
1113                 GOTO(out, rc);
1114
1115         rc = mdd_trans_start(env, mdd, handle);
1116         if (rc != 0)
1117                 GOTO(out, rc);
1118
1119         rc = mdo_xattr_set(env, o, NULL, XATTR_NAME_FID, 0, handle);
1120         if (rc)
1121                 GOTO(out, rc);
1122
1123 out:
1124         mdd_trans_stop(env, mdd, rc, handle);
1125         return rc;
1126 }
1127
1128
1129 static int mdd_declare_xattr_del(const struct lu_env *env,
1130                                  struct mdd_device *mdd,
1131                                  struct mdd_object *obj,
1132                                  const char *name,
1133                                  struct thandle *handle);
1134
1135 static int mdd_xattr_del(const struct lu_env *env, struct md_object *obj,
1136                          const char *name);
1137
1138 static int mdd_xattr_merge(const struct lu_env *env, struct md_object *md_obj,
1139                            struct md_object *md_vic)
1140 {
1141         struct mdd_device *mdd = mdo2mdd(md_obj);
1142         struct mdd_object *obj = md2mdd_obj(md_obj);
1143         struct mdd_object *vic = md2mdd_obj(md_vic);
1144         struct lu_buf *buf = &mdd_env_info(env)->mti_buf[0];
1145         struct lu_buf *buf_vic = &mdd_env_info(env)->mti_buf[1];
1146         struct lov_mds_md *lmm;
1147         struct thandle *handle;
1148         int rc;
1149         ENTRY;
1150
1151         rc = lu_fid_cmp(mdo2fid(obj), mdo2fid(vic));
1152         if (rc == 0) /* same fid */
1153                 RETURN(-EPERM);
1154
1155         handle = mdd_trans_create(env, mdd);
1156         if (IS_ERR(handle))
1157                 RETURN(PTR_ERR(handle));
1158
1159         if (rc > 0) {
1160                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1161                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1162         } else {
1163                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1164                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1165         }
1166
1167         /* get EA of victim file */
1168         memset(buf_vic, 0, sizeof(*buf_vic));
1169         rc = mdd_get_lov_ea(env, vic, buf_vic);
1170         if (rc < 0) {
1171                 if (rc == -ENODATA)
1172                         rc = 0;
1173                 GOTO(out, rc);
1174         }
1175
1176         /* parse the layout of victim file */
1177         lmm = buf_vic->lb_buf;
1178         if (le32_to_cpu(lmm->lmm_magic) != LOV_MAGIC_COMP_V1)
1179                 GOTO(out, rc = -EINVAL);
1180
1181         /* save EA of target file for restore */
1182         memset(buf, 0, sizeof(*buf));
1183         rc = mdd_get_lov_ea(env, obj, buf);
1184         if (rc < 0)
1185                 GOTO(out, rc);
1186
1187         /* Get rid of the layout from victim object */
1188         rc = mdd_declare_xattr_del(env, mdd, vic, XATTR_NAME_LOV, handle);
1189         if (rc)
1190                 GOTO(out, rc);
1191
1192         rc = mdd_declare_xattr_set(env, mdd, obj, buf_vic, XATTR_LUSTRE_LOV,
1193                                    LU_XATTR_MERGE, handle);
1194         if (rc)
1195                 GOTO(out, rc);
1196
1197         rc = mdd_trans_start(env, mdd, handle);
1198         if (rc != 0)
1199                 GOTO(out, rc);
1200
1201         rc = mdo_xattr_set(env, obj, buf_vic, XATTR_LUSTRE_LOV, LU_XATTR_MERGE,
1202                            handle);
1203         if (rc)
1204                 GOTO(out, rc);
1205
1206         rc = mdo_xattr_del(env, vic, XATTR_NAME_LOV, handle);
1207         if (rc) /* wtf? */
1208                 GOTO(out_restore, rc);
1209
1210         (void)mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, obj, handle);
1211         (void)mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, vic, handle);
1212         EXIT;
1213
1214 out_restore:
1215         if (rc) {
1216                 int rc2 = mdo_xattr_set(env, obj, buf, XATTR_NAME_LOV,
1217                                         LU_XATTR_REPLACE, handle);
1218                 if (rc2)
1219                         CERROR("%s: failed to rollback of layout of: "DFID
1220                                ": %d, file state unknown\n",
1221                                mdd_obj_dev_name(obj), PFID(mdo2fid(obj)), rc2);
1222         }
1223
1224 out:
1225         mdd_trans_stop(env, mdd, rc, handle);
1226         mdd_write_unlock(env, obj);
1227         mdd_write_unlock(env, vic);
1228         lu_buf_free(buf);
1229         lu_buf_free(buf_vic);
1230
1231         if (!rc)
1232                 (void) mdd_object_pfid_replace(env, obj);
1233
1234         return rc;
1235 }
1236
1237 static int mdd_layout_merge_allowed(const struct lu_env *env,
1238                                     struct md_object *target,
1239                                     struct md_object *victim)
1240 {
1241         struct mdd_object *o1 = md2mdd_obj(target);
1242
1243         /* cannot extend directory's LOVEA */
1244         if (S_ISDIR(mdd_object_type(o1))) {
1245                 CERROR("%s: Don't extend directory's LOVEA, just set it.\n",
1246                        mdd_obj_dev_name(o1));
1247                 RETURN(-EISDIR);
1248         }
1249
1250         RETURN(0);
1251 }
1252
1253 /**
1254  * The caller should guarantee to update the object ctime
1255  * after xattr_set if needed.
1256  */
1257 static int mdd_xattr_set(const struct lu_env *env, struct md_object *obj,
1258                          const struct lu_buf *buf, const char *name,
1259                          int fl)
1260 {
1261         struct mdd_object       *mdd_obj = md2mdd_obj(obj);
1262         struct lu_attr          *attr = MDD_ENV_VAR(env, cattr);
1263         struct mdd_device       *mdd = mdo2mdd(obj);
1264         struct thandle          *handle;
1265         enum changelog_rec_type  cl_type;
1266         int                      cl_flags = 0;
1267         int                      rc;
1268         ENTRY;
1269
1270         rc = mdd_la_get(env, mdd_obj, attr);
1271         if (rc)
1272                 RETURN(rc);
1273
1274         rc = mdd_xattr_sanity_check(env, mdd_obj, attr, name);
1275         if (rc)
1276                 RETURN(rc);
1277
1278         if (strcmp(name, XATTR_LUSTRE_LOV) == 0 && fl == LU_XATTR_MERGE) {
1279                 struct md_object *victim = buf->lb_buf;
1280
1281                 if (buf->lb_len != sizeof(victim))
1282                         RETURN(-EINVAL);
1283
1284                 rc = mdd_layout_merge_allowed(env, obj, victim);
1285                 if (rc)
1286                         RETURN(rc);
1287
1288                 /* merge layout of victim as a mirror of obj's. */
1289                 rc = mdd_xattr_merge(env, obj, victim);
1290                 RETURN(rc);
1291         }
1292
1293         if (strcmp(name, XATTR_NAME_ACL_ACCESS) == 0 ||
1294             strcmp(name, XATTR_NAME_ACL_DEFAULT) == 0) {
1295                 struct posix_acl *acl;
1296
1297                 /* user may set empty ACL, which should be treated as removing
1298                  * ACL. */
1299                 acl = posix_acl_from_xattr(&init_user_ns, buf->lb_buf,
1300                                            buf->lb_len);
1301                 if (IS_ERR(acl))
1302                         RETURN(PTR_ERR(acl));
1303                 if (acl == NULL) {
1304                         rc = mdd_xattr_del(env, obj, name);
1305                         RETURN(rc);
1306                 }
1307                 posix_acl_release(acl);
1308         }
1309
1310         if (!strcmp(name, XATTR_NAME_ACL_ACCESS)) {
1311                 rc = mdd_acl_set(env, mdd_obj, attr, buf, fl);
1312                 RETURN(rc);
1313         }
1314
1315         handle = mdd_trans_create(env, mdd);
1316         if (IS_ERR(handle))
1317                 RETURN(PTR_ERR(handle));
1318
1319         rc = mdd_declare_xattr_set(env, mdd, mdd_obj, buf, name, fl, handle);
1320         if (rc)
1321                 GOTO(stop, rc);
1322
1323         rc = mdd_trans_start(env, mdd, handle);
1324         if (rc)
1325                 GOTO(stop, rc);
1326
1327         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
1328
1329         if (strcmp(XATTR_NAME_HSM, name) == 0) {
1330                 rc = mdd_hsm_update_locked(env, obj, buf, handle, &cl_flags);
1331                 if (rc) {
1332                         mdd_write_unlock(env, mdd_obj);
1333                         GOTO(stop, rc);
1334                 }
1335         }
1336
1337         rc = mdo_xattr_set(env, mdd_obj, buf, name, fl, handle);
1338         mdd_write_unlock(env, mdd_obj);
1339         if (rc)
1340                 GOTO(stop, rc);
1341
1342         cl_type = mdd_xattr_changelog_type(env, mdd, name);
1343         if (cl_type < 0)
1344                 GOTO(stop, rc = 0);
1345
1346         rc = mdd_changelog_data_store(env, mdd, cl_type, cl_flags, mdd_obj,
1347                                       handle);
1348
1349         EXIT;
1350 stop:
1351         return mdd_trans_stop(env, mdd, rc, handle);
1352 }
1353
1354 static int mdd_declare_xattr_del(const struct lu_env *env,
1355                                  struct mdd_device *mdd,
1356                                  struct mdd_object *obj,
1357                                  const char *name,
1358                                  struct thandle *handle)
1359 {
1360         int rc;
1361
1362         rc = mdo_declare_xattr_del(env, obj, name, handle);
1363         if (rc)
1364                 return rc;
1365
1366         if (mdd_xattr_changelog_type(env, mdd, name) < 0)
1367                 return 0; /* no changelog to store */
1368
1369         return mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
1370 }
1371
1372 /**
1373  * The caller should guarantee to update the object ctime
1374  * after xattr_set if needed.
1375  */
1376 static int mdd_xattr_del(const struct lu_env *env, struct md_object *obj,
1377                          const char *name)
1378 {
1379         struct mdd_object *mdd_obj = md2mdd_obj(obj);
1380         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
1381         struct mdd_device *mdd = mdo2mdd(obj);
1382         struct thandle *handle;
1383         int rc;
1384         ENTRY;
1385
1386         rc = mdd_la_get(env, mdd_obj, attr);
1387         if (rc)
1388                 RETURN(rc);
1389
1390         rc = mdd_xattr_sanity_check(env, mdd_obj, attr, name);
1391         if (rc)
1392                 RETURN(rc);
1393
1394         handle = mdd_trans_create(env, mdd);
1395         if (IS_ERR(handle))
1396                 RETURN(PTR_ERR(handle));
1397
1398         rc = mdd_declare_xattr_del(env, mdd, mdd_obj, name, handle);
1399         if (rc)
1400                 GOTO(stop, rc);
1401
1402         rc = mdd_trans_start(env, mdd, handle);
1403         if (rc)
1404                 GOTO(stop, rc);
1405
1406         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
1407         rc = mdo_xattr_del(env, mdd_obj, name, handle);
1408         mdd_write_unlock(env, mdd_obj);
1409         if (rc)
1410                 GOTO(stop, rc);
1411
1412         if (mdd_xattr_changelog_type(env, mdd, name) < 0)
1413                 GOTO(stop, rc = 0);
1414
1415         rc = mdd_changelog_data_store(env, mdd, CL_XATTR, 0, mdd_obj, handle);
1416
1417         EXIT;
1418 stop:
1419         return mdd_trans_stop(env, mdd, rc, handle);
1420 }
1421
1422 /*
1423  * read lov EA of an object
1424  * return the lov EA in an allocated lu_buf
1425  */
1426 int mdd_get_lov_ea(const struct lu_env *env, struct mdd_object *obj,
1427                    struct lu_buf *lmm_buf)
1428 {
1429         struct lu_buf   *buf = &mdd_env_info(env)->mti_big_buf;
1430         int              rc, bufsize;
1431         ENTRY;
1432
1433 repeat:
1434         rc = mdo_xattr_get(env, obj, buf, XATTR_NAME_LOV);
1435
1436         if (rc == -ERANGE) {
1437                 /* mti_big_buf is allocated but is too small
1438                  * we need to increase it */
1439                 buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf,
1440                                              buf->lb_len * 2);
1441                 if (buf->lb_buf == NULL)
1442                         GOTO(out, rc = -ENOMEM);
1443                 goto repeat;
1444         }
1445
1446         if (rc < 0)
1447                 RETURN(rc);
1448
1449         if (rc == 0)
1450                 RETURN(-ENODATA);
1451
1452         bufsize = rc;
1453         if (memcmp(buf, &LU_BUF_NULL, sizeof(*buf)) == 0) {
1454                 /* mti_big_buf was not allocated, so we have to
1455                  * allocate it based on the ea size */
1456                 buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf,
1457                                              bufsize);
1458                 if (buf->lb_buf == NULL)
1459                         GOTO(out, rc = -ENOMEM);
1460                 goto repeat;
1461         }
1462
1463         lu_buf_alloc(lmm_buf, bufsize);
1464         if (lmm_buf->lb_buf == NULL)
1465                 GOTO(out, rc = -ENOMEM);
1466
1467         memcpy(lmm_buf->lb_buf, buf->lb_buf, bufsize);
1468         rc = 0;
1469         EXIT;
1470
1471 out:
1472         if (rc < 0)
1473                 lu_buf_free(lmm_buf);
1474         return rc;
1475 }
1476
1477 static int mdd_xattr_hsm_replace(const struct lu_env *env,
1478                                  struct mdd_object *o, struct lu_buf *buf,
1479                                  struct thandle *handle)
1480 {
1481         struct hsm_attrs *attrs;
1482         __u32 hsm_flags;
1483         int flags = 0;
1484         int rc;
1485         ENTRY;
1486
1487         rc = mdo_xattr_set(env, o, buf, XATTR_NAME_HSM, LU_XATTR_REPLACE,
1488                            handle);
1489         if (rc != 0)
1490                 RETURN(rc);
1491
1492         attrs = buf->lb_buf;
1493         hsm_flags = le32_to_cpu(attrs->hsm_flags);
1494         if (!(hsm_flags & HS_RELEASED) || mdd_is_dead_obj(o))
1495                 RETURN(0);
1496
1497         /* Add a changelog record for release. */
1498         hsm_set_cl_event(&flags, HE_RELEASE);
1499         rc = mdd_changelog_data_store(env, mdo2mdd(&o->mod_obj), CL_HSM,
1500                                       flags, o, handle);
1501         RETURN(rc);
1502 }
1503
1504 /*
1505  *  check if layout swapping between 2 objects is allowed
1506  *  the rules are:
1507  *  - only normal FIDs or non-system IGIFs
1508  *  - same type of objects
1509  *  - same owner/group (so quotas are still valid) unless this is from HSM
1510  *    release.
1511  */
1512 static int mdd_layout_swap_allowed(const struct lu_env *env,
1513                                    struct mdd_object *o1,
1514                                    const struct lu_attr *attr1,
1515                                    struct mdd_object *o2,
1516                                    const struct lu_attr *attr2,
1517                                    __u64 flags)
1518 {
1519         const struct lu_fid     *fid1, *fid2;
1520         ENTRY;
1521
1522         fid1 = mdo2fid(o1);
1523         fid2 = mdo2fid(o2);
1524
1525         if (!fid_is_norm(fid1) &&
1526             (!fid_is_igif(fid1) || IS_ERR(mdd_links_get(env, o1))))
1527                 RETURN(-EBADF);
1528
1529         if (!fid_is_norm(fid2) &&
1530             (!fid_is_igif(fid2) || IS_ERR(mdd_links_get(env, o2))))
1531                 RETURN(-EBADF);
1532
1533         if (mdd_object_type(o1) != mdd_object_type(o2)) {
1534                 if (S_ISDIR(mdd_object_type(o1)))
1535                         RETURN(-ENOTDIR);
1536                 if (S_ISREG(mdd_object_type(o1)))
1537                         RETURN(-EISDIR);
1538                 RETURN(-EBADF);
1539         }
1540
1541         if (flags & SWAP_LAYOUTS_MDS_HSM)
1542                 RETURN(0);
1543
1544         if ((attr1->la_uid != attr2->la_uid) ||
1545             (attr1->la_gid != attr2->la_gid))
1546                 RETURN(-EPERM);
1547
1548         RETURN(0);
1549 }
1550
1551 /* XXX To set the proper lmm_oi & lmm_layout_gen when swap layouts, we have to
1552  *     look into the layout in MDD layer. */
1553 static int mdd_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi, bool get)
1554 {
1555         struct lov_comp_md_v1   *comp_v1;
1556         struct lov_mds_md       *v1;
1557         int                      i, ent_count;
1558         __u32                    off;
1559
1560         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_COMP_V1) {
1561                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
1562                 ent_count = le16_to_cpu(comp_v1->lcm_entry_count);
1563
1564                 if (ent_count == 0)
1565                         return -EINVAL;
1566
1567                 if (get) {
1568                         off = le32_to_cpu(comp_v1->lcm_entries[0].lcme_offset);
1569                         v1 = (struct lov_mds_md *)((char *)comp_v1 + off);
1570                         *oi = v1->lmm_oi;
1571                 } else {
1572                         for (i = 0; i < le32_to_cpu(ent_count); i++) {
1573                                 off = le32_to_cpu(comp_v1->lcm_entries[i].
1574                                                 lcme_offset);
1575                                 v1 = (struct lov_mds_md *)((char *)comp_v1 +
1576                                                 off);
1577                                 v1->lmm_oi = *oi;
1578                         }
1579                 }
1580         } else if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1 ||
1581                    le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V3) {
1582                 if (get)
1583                         *oi = lmm->lmm_oi;
1584                 else
1585                         lmm->lmm_oi = *oi;
1586         } else {
1587                 return -EINVAL;
1588         }
1589         return 0;
1590 }
1591
1592 static inline int mdd_get_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi)
1593 {
1594         return mdd_lmm_oi(lmm, oi, true);
1595 }
1596
1597 static inline int mdd_set_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi)
1598 {
1599         return mdd_lmm_oi(lmm, oi, false);
1600 }
1601
1602 static int mdd_lmm_gen(struct lov_mds_md *lmm, __u32 *gen, bool get)
1603 {
1604         struct lov_comp_md_v1 *comp_v1;
1605
1606         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_COMP_V1) {
1607                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
1608                 if (get)
1609                         *gen = le32_to_cpu(comp_v1->lcm_layout_gen);
1610                 else
1611                         comp_v1->lcm_layout_gen = cpu_to_le32(*gen);
1612         } else if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1 ||
1613                    le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V3) {
1614                 __u16 tmp_gen = *gen;
1615                 if (get)
1616                         *gen = le16_to_cpu(lmm->lmm_layout_gen);
1617                 else
1618                         lmm->lmm_layout_gen = cpu_to_le16(tmp_gen);
1619         } else {
1620                 return -EINVAL;
1621         }
1622         return 0;
1623 }
1624
1625 static inline int mdd_get_lmm_gen(struct lov_mds_md *lmm, __u32 *gen)
1626 {
1627         return mdd_lmm_gen(lmm, gen, true);
1628 }
1629
1630 static inline int mdd_set_lmm_gen(struct lov_mds_md *lmm, __u32 *gen)
1631 {
1632         return mdd_lmm_gen(lmm, gen, false);
1633 }
1634
1635 /**
1636  * swap layouts between 2 lustre objects
1637  */
1638 static int mdd_swap_layouts(const struct lu_env *env, struct md_object *obj1,
1639                             struct md_object *obj2, __u64 flags)
1640 {
1641         struct mdd_thread_info  *info = mdd_env_info(env);
1642         struct mdd_object       *fst_o = md2mdd_obj(obj1);
1643         struct mdd_object       *snd_o = md2mdd_obj(obj2);
1644         struct lu_attr          *fst_la = MDD_ENV_VAR(env, cattr);
1645         struct lu_attr          *snd_la = MDD_ENV_VAR(env, tattr);
1646         struct mdd_device       *mdd = mdo2mdd(obj1);
1647         struct lov_mds_md       *fst_lmm, *snd_lmm;
1648         struct lu_buf           *fst_buf = &info->mti_buf[0];
1649         struct lu_buf           *snd_buf = &info->mti_buf[1];
1650         struct lu_buf           *fst_hsm_buf = &info->mti_buf[2];
1651         struct lu_buf           *snd_hsm_buf = &info->mti_buf[3];
1652         struct ost_id           *saved_oi = NULL;
1653         struct thandle          *handle;
1654         __u32                    fst_gen, snd_gen, saved_gen;
1655         int                      fst_fl;
1656         int                      rc;
1657         int                      rc2;
1658         ENTRY;
1659
1660         CLASSERT(ARRAY_SIZE(info->mti_buf) >= 4);
1661         memset(info->mti_buf, 0, sizeof(info->mti_buf));
1662
1663         /* we have to sort the 2 obj, so locking will always
1664          * be in the same order, even in case of 2 concurrent swaps */
1665         rc = lu_fid_cmp(mdo2fid(fst_o), mdo2fid(snd_o));
1666         if (rc == 0) /* same fid ? */
1667                 RETURN(-EPERM);
1668
1669         if (rc < 0)
1670                 swap(fst_o, snd_o);
1671
1672         rc = mdd_la_get(env, fst_o, fst_la);
1673         if (rc != 0)
1674                 RETURN(rc);
1675
1676         rc = mdd_la_get(env, snd_o, snd_la);
1677         if (rc != 0)
1678                 RETURN(rc);
1679
1680         /* check if layout swapping is allowed */
1681         rc = mdd_layout_swap_allowed(env, fst_o, fst_la, snd_o, snd_la, flags);
1682         if (rc != 0)
1683                 RETURN(rc);
1684
1685         handle = mdd_trans_create(env, mdd);
1686         if (IS_ERR(handle))
1687                 RETURN(PTR_ERR(handle));
1688
1689         /* objects are already sorted */
1690         mdd_write_lock(env, fst_o, MOR_TGT_CHILD);
1691         mdd_write_lock(env, snd_o, MOR_TGT_CHILD);
1692
1693         rc = mdd_get_lov_ea(env, fst_o, fst_buf);
1694         if (rc < 0 && rc != -ENODATA)
1695                 GOTO(stop, rc);
1696
1697         rc = mdd_get_lov_ea(env, snd_o, snd_buf);
1698         if (rc < 0 && rc != -ENODATA)
1699                 GOTO(stop, rc);
1700
1701         /* swapping 2 non existant layouts is a success */
1702         if (fst_buf->lb_buf == NULL && snd_buf->lb_buf == NULL)
1703                 GOTO(stop, rc = 0);
1704
1705         /* to help inode migration between MDT, it is better to
1706          * start by the no layout file (if one), so we order the swap */
1707         if (snd_buf->lb_buf == NULL) {
1708                 swap(fst_o, snd_o);
1709                 swap(fst_buf, snd_buf);
1710         }
1711
1712         fst_gen = snd_gen = 0;
1713         /* lmm and generation layout initialization */
1714         if (fst_buf->lb_buf != NULL) {
1715                 fst_lmm = fst_buf->lb_buf;
1716                 mdd_get_lmm_gen(fst_lmm, &fst_gen);
1717                 fst_fl  = LU_XATTR_REPLACE;
1718         } else {
1719                 fst_lmm = NULL;
1720                 fst_gen = 0;
1721                 fst_fl  = LU_XATTR_CREATE;
1722         }
1723
1724         snd_lmm = snd_buf->lb_buf;
1725         mdd_get_lmm_gen(snd_lmm, &snd_gen);
1726
1727         saved_gen = fst_gen;
1728         /* increase the generation layout numbers */
1729         snd_gen++;
1730         fst_gen++;
1731
1732         /*
1733          * XXX The layout generation is used to generate component IDs for
1734          *     the composite file, we have to do some special tweaks to make
1735          *     sure the layout generation is always adequate for that job.
1736          */
1737
1738         /* Skip invalid generation number for composite layout */
1739         if ((snd_gen & LCME_ID_MASK) == 0)
1740                 snd_gen++;
1741         if ((fst_gen & LCME_ID_MASK) == 0)
1742                 fst_gen++;
1743         /* Make sure the generation is greater than all the component IDs */
1744         if (fst_gen < snd_gen)
1745                 fst_gen = snd_gen;
1746         else if (fst_gen > snd_gen)
1747                 snd_gen = fst_gen;
1748
1749         /* set the file specific informations in lmm */
1750         if (fst_lmm != NULL) {
1751                 saved_oi = &info->mti_oa.o_oi;
1752                 mdd_get_lmm_oi(fst_lmm, saved_oi);
1753                 mdd_set_lmm_gen(fst_lmm, &snd_gen);
1754                 mdd_set_lmm_oi(fst_lmm, &snd_lmm->lmm_oi);
1755                 mdd_set_lmm_oi(snd_lmm, saved_oi);
1756         } else {
1757                 if ((snd_lmm->lmm_magic & cpu_to_le32(LOV_MAGIC_MASK)) ==
1758                     cpu_to_le32(LOV_MAGIC_MAGIC))
1759                         snd_lmm->lmm_magic |= cpu_to_le32(LOV_MAGIC_DEFINED);
1760                 else
1761                         GOTO(stop, rc = -EPROTO);
1762         }
1763         mdd_set_lmm_gen(snd_lmm, &fst_gen);
1764
1765         /* Prepare HSM attribute if it's required */
1766         if (flags & SWAP_LAYOUTS_MDS_HSM) {
1767                 const int buflen = sizeof(struct hsm_attrs);
1768
1769                 lu_buf_alloc(fst_hsm_buf, buflen);
1770                 lu_buf_alloc(snd_hsm_buf, buflen);
1771                 if (fst_hsm_buf->lb_buf == NULL || snd_hsm_buf->lb_buf == NULL)
1772                         GOTO(stop, rc = -ENOMEM);
1773
1774                 /* Read HSM attribute */
1775                 rc = mdo_xattr_get(env, fst_o, fst_hsm_buf, XATTR_NAME_HSM);
1776                 if (rc < 0)
1777                         GOTO(stop, rc);
1778
1779                 rc = mdo_xattr_get(env, snd_o, snd_hsm_buf, XATTR_NAME_HSM);
1780                 if (rc < 0)
1781                         GOTO(stop, rc);
1782
1783                 rc = mdd_declare_xattr_set(env, mdd, fst_o, snd_hsm_buf,
1784                                            XATTR_NAME_HSM, LU_XATTR_REPLACE,
1785                                            handle);
1786                 if (rc < 0)
1787                         GOTO(stop, rc);
1788
1789                 rc = mdd_declare_xattr_set(env, mdd, snd_o, fst_hsm_buf,
1790                                            XATTR_NAME_HSM, LU_XATTR_REPLACE,
1791                                            handle);
1792                 if (rc < 0)
1793                         GOTO(stop, rc);
1794         }
1795
1796         /* prepare transaction */
1797         rc = mdd_declare_xattr_set(env, mdd, fst_o, snd_buf, XATTR_NAME_LOV,
1798                                    fst_fl, handle);
1799         if (rc != 0)
1800                 GOTO(stop, rc);
1801
1802         if (fst_buf->lb_buf != NULL)
1803                 rc = mdd_declare_xattr_set(env, mdd, snd_o, fst_buf,
1804                                            XATTR_NAME_LOV, LU_XATTR_REPLACE,
1805                                            handle);
1806         else
1807                 rc = mdd_declare_xattr_del(env, mdd, snd_o, XATTR_NAME_LOV,
1808                                            handle);
1809         if (rc != 0)
1810                 GOTO(stop, rc);
1811
1812         rc = mdd_trans_start(env, mdd, handle);
1813         if (rc != 0)
1814                 GOTO(stop, rc);
1815
1816         if (flags & SWAP_LAYOUTS_MDS_HSM) {
1817                 rc = mdd_xattr_hsm_replace(env, fst_o, snd_hsm_buf, handle);
1818                 if (rc < 0)
1819                         GOTO(stop, rc);
1820
1821                 rc = mdd_xattr_hsm_replace(env, snd_o, fst_hsm_buf, handle);
1822                 if (rc < 0) {
1823                         rc2 = mdd_xattr_hsm_replace(env, fst_o, fst_hsm_buf,
1824                                                     handle);
1825                         if (rc2 < 0)
1826                                 CERROR("%s: restore "DFID" HSM error: %d/%d\n",
1827                                        mdd_obj_dev_name(fst_o),
1828                                        PFID(mdo2fid(fst_o)), rc, rc2);
1829                         GOTO(stop, rc);
1830                 }
1831         }
1832
1833         rc = mdo_xattr_set(env, fst_o, snd_buf, XATTR_NAME_LOV, fst_fl, handle);
1834         if (rc != 0)
1835                 GOTO(stop, rc);
1836
1837         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_MDS_HSM_SWAP_LAYOUTS))) {
1838                 rc = -EOPNOTSUPP;
1839         } else {
1840                 if (fst_buf->lb_buf != NULL)
1841                         rc = mdo_xattr_set(env, snd_o, fst_buf, XATTR_NAME_LOV,
1842                                            LU_XATTR_REPLACE, handle);
1843                 else
1844                         rc = mdo_xattr_del(env, snd_o, XATTR_NAME_LOV, handle);
1845         }
1846         if (rc != 0)
1847                 GOTO(out_restore, rc);
1848
1849         /* Issue one changelog record per file */
1850         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, fst_o, handle);
1851         if (rc)
1852                 GOTO(stop, rc);
1853
1854         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, snd_o, handle);
1855         if (rc)
1856                 GOTO(stop, rc);
1857         EXIT;
1858
1859 out_restore:
1860         if (rc != 0) {
1861                 int steps = 0;
1862
1863                 /* failure on second file, but first was done, so we have
1864                  * to roll back first. */
1865                 if (fst_buf->lb_buf != NULL) {
1866                         mdd_set_lmm_oi(fst_lmm, saved_oi);
1867                         mdd_set_lmm_gen(fst_lmm, &saved_gen);
1868                         rc2 = mdo_xattr_set(env, fst_o, fst_buf, XATTR_NAME_LOV,
1869                                             LU_XATTR_REPLACE, handle);
1870                 } else {
1871                         rc2 = mdo_xattr_del(env, fst_o, XATTR_NAME_LOV, handle);
1872                 }
1873                 if (rc2 < 0)
1874                         goto do_lbug;
1875
1876                 ++steps;
1877                 rc2 = mdd_xattr_hsm_replace(env, fst_o, fst_hsm_buf, handle);
1878                 if (rc2 < 0)
1879                         goto do_lbug;
1880
1881                 ++steps;
1882                 rc2 = mdd_xattr_hsm_replace(env, snd_o, snd_hsm_buf, handle);
1883
1884         do_lbug:
1885                 if (rc2 < 0) {
1886                         /* very bad day */
1887                         CERROR("%s: unable to roll back layout swap. FIDs: "
1888                                DFID" and "DFID "error: %d/%d, steps: %d\n",
1889                                mdd_obj_dev_name(fst_o),
1890                                PFID(mdo2fid(snd_o)), PFID(mdo2fid(fst_o)),
1891                                rc, rc2, steps);
1892                         /* a solution to avoid journal commit is to panic,
1893                          * but it has strong consequences so we use LBUG to
1894                          * allow sysdamin to choose to panic or not
1895                          */
1896                         LBUG();
1897                 }
1898         }
1899
1900 stop:
1901         rc = mdd_trans_stop(env, mdd, rc, handle);
1902
1903         mdd_write_unlock(env, snd_o);
1904         mdd_write_unlock(env, fst_o);
1905
1906         lu_buf_free(fst_buf);
1907         lu_buf_free(snd_buf);
1908         lu_buf_free(fst_hsm_buf);
1909         lu_buf_free(snd_hsm_buf);
1910
1911         if (!rc) {
1912                 (void) mdd_object_pfid_replace(env, fst_o);
1913                 (void) mdd_object_pfid_replace(env, snd_o);
1914         }
1915         return rc;
1916 }
1917
1918 static int mdd_declare_layout_change(const struct lu_env *env,
1919                                      struct mdd_device *mdd,
1920                                      struct mdd_object *obj,
1921                                      struct md_layout_change *mlc,
1922                                      struct thandle *handle)
1923 {
1924         int rc;
1925
1926         rc = mdo_declare_layout_change(env, obj, mlc, handle);
1927         if (rc)
1928                 return rc;
1929
1930         return mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
1931 }
1932
1933 /* For PFL, this is used to instantiate necessary component objects. */
1934 static int
1935 mdd_layout_instantiate_component(const struct lu_env *env,
1936                 struct mdd_object *obj, struct md_layout_change *mlc,
1937                 struct thandle *handle)
1938 {
1939         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
1940         int rc;
1941         ENTRY;
1942
1943         if (mlc->mlc_opc != MD_LAYOUT_WRITE)
1944                 RETURN(-ENOTSUPP);
1945
1946         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
1947         /**
1948          * It's possible that another layout write intent has already
1949          * instantiated our objects, so a -EALREADY returned, and we need to
1950          * do nothing.
1951          */
1952         if (rc)
1953                 RETURN(rc == -EALREADY ? 0 : rc);
1954
1955         rc = mdd_trans_start(env, mdd, handle);
1956         if (rc)
1957                 RETURN(rc);
1958
1959         mdd_write_lock(env, obj, MOR_TGT_CHILD);
1960         rc = mdo_layout_change(env, obj, mlc, handle);
1961         mdd_write_unlock(env, obj);
1962         if (rc)
1963                 RETURN(rc);
1964
1965         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, obj, handle);
1966         RETURN(rc);
1967 }
1968
1969 /**
1970  * Change the FLR layout from RDONLY to WRITE_PENDING.
1971  *
1972  * It picks the primary mirror, and bumps the layout version, and set
1973  * layout version xattr to OST objects in a sync tx. In order to facilitate
1974  * the handling of phantom writers from evicted clients, the clients carry
1975  * layout version of the file with write RPC, so that the OSTs can verify
1976  * if the write RPCs are legitimate, meaning not from evicted clients.
1977  */
1978 static int
1979 mdd_layout_update_rdonly(const struct lu_env *env, struct mdd_object *obj,
1980                          struct md_layout_change *mlc, struct thandle *handle)
1981 {
1982         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
1983         int rc;
1984         ENTRY;
1985
1986         /* Verify acceptable operations */
1987         switch (mlc->mlc_opc) {
1988         case MD_LAYOUT_WRITE:
1989                 break;
1990         case MD_LAYOUT_RESYNC:
1991                 /* these are legal operations - this represents the case that
1992                  * a few mirrors were missed in the last resync.
1993                  * XXX: it will be supported later */
1994         case MD_LAYOUT_RESYNC_DONE:
1995         default:
1996                 RETURN(0);
1997         }
1998
1999         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2000         if (rc)
2001                 GOTO(out, rc);
2002
2003         rc = mdd_declare_xattr_del(env, mdd, obj, XATTR_NAME_SOM, handle);
2004         if (rc)
2005                 GOTO(out, rc);
2006
2007         /* record a changelog for data mover to consume */
2008         rc = mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
2009         if (rc)
2010                 GOTO(out, rc);
2011
2012         rc = mdd_trans_start(env, mdd, handle);
2013         if (rc)
2014                 GOTO(out, rc);
2015
2016         /* it needs a sync tx to make FLR to work properly */
2017         handle->th_sync = 1;
2018
2019         mdd_write_lock(env, obj, MOR_TGT_CHILD);
2020         rc = mdo_layout_change(env, obj, mlc, handle);
2021         if (!rc) {
2022                 rc = mdo_xattr_del(env, obj, XATTR_NAME_SOM, handle);
2023                 if (rc == -ENODATA)
2024                         rc = 0;
2025         }
2026         mdd_write_unlock(env, obj);
2027         if (rc)
2028                 GOTO(out, rc);
2029
2030         rc = mdd_changelog_data_store(env, mdd, CL_FLRW, 0, obj, handle);
2031         if (rc)
2032                 GOTO(out, rc);
2033
2034         EXIT;
2035
2036 out:
2037         return rc;
2038 }
2039
2040 /**
2041  * Handle mirrored file state transition when it's in WRITE_PENDING.
2042  *
2043  * Only MD_LAYOUT_RESYNC, which represents start of resync, is allowed when
2044  * the file is in WRITE_PENDING state. If everything goes fine, the file's
2045  * layout version will be increased, and the file's state will be changed to
2046  * SYNC_PENDING.
2047  */
2048 static int
2049 mdd_layout_update_write_pending(const struct lu_env *env,
2050                 struct mdd_object *obj, struct md_layout_change *mlc,
2051                 struct thandle *handle)
2052 {
2053         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2054         int rc;
2055         ENTRY;
2056
2057         switch (mlc->mlc_opc) {
2058         case MD_LAYOUT_RESYNC:
2059                 /* Upon receiving the resync request, it should
2060                  * instantiate all stale components right away to get ready
2061                  * for mirror copy. In order to avoid layout version change,
2062                  * client should avoid sending LAYOUT_WRITE request at the
2063                  * resync state. */
2064                 break;
2065         case MD_LAYOUT_WRITE:
2066                 /* legal race for concurrent write, the file state has been
2067                  * changed by another client. */
2068                 break;
2069         default:
2070                 RETURN(-EBUSY);
2071         }
2072
2073         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2074         if (rc)
2075                 GOTO(out, rc);
2076
2077         rc = mdd_trans_start(env, mdd, handle);
2078         if (rc)
2079                 GOTO(out, rc);
2080
2081         /* it needs a sync tx to make FLR to work properly */
2082         handle->th_sync = 1;
2083
2084         mdd_write_lock(env, obj, MOR_TGT_CHILD);
2085         rc = mdo_layout_change(env, obj, mlc, handle);
2086         mdd_write_unlock(env, obj);
2087         if (rc)
2088                 GOTO(out, rc);
2089
2090         EXIT;
2091
2092 out:
2093         return rc;
2094 }
2095
2096 /**
2097  * Handle the requests when a FLR file's state is in SYNC_PENDING.
2098  *
2099  * Only concurrent write and sync complete requests are possible when the
2100  * file is in SYNC_PENDING. For the latter request, it will pass in the
2101  * mirrors that have been synchronized, then the stale bit will be cleared
2102  * to make the file's state turn into RDONLY.
2103  * For concurrent write reqeust, it just needs to change the file's state
2104  * to WRITE_PENDING in a sync tx. It doesn't have to change the layout
2105  * version because the version will be increased in the transition to
2106  * SYNC_PENDING later so that it can deny the write request from potential
2107  * evicted SYNC clients. */
2108 static int
2109 mdd_object_update_sync_pending(const struct lu_env *env, struct mdd_object *obj,
2110                 struct md_layout_change *mlc, struct thandle *handle)
2111 {
2112         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2113         struct lu_buf *som_buf = &mdd_env_info(env)->mti_buf[1];
2114         int fl = 0;
2115         int rc;
2116         ENTRY;
2117
2118         /* operation validation */
2119         switch (mlc->mlc_opc) {
2120         case MD_LAYOUT_RESYNC_DONE:
2121                 /* resync complete. */
2122         case MD_LAYOUT_WRITE:
2123                 /* concurrent write. */
2124                 break;
2125         case MD_LAYOUT_RESYNC:
2126                 /* resync again, most likely the previous run failed.
2127                  * no-op if it's already in SYNC_PENDING state */
2128                 RETURN(0);
2129         default:
2130                 RETURN(-EBUSY);
2131         }
2132
2133         if (mlc->mlc_som.lsa_valid & LSOM_FL_VALID) {
2134                 rc = mdo_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_SOM);
2135                 if (rc && rc != -ENODATA)
2136                         RETURN(rc);
2137
2138                 fl = rc == -ENODATA ? LU_XATTR_CREATE : LU_XATTR_REPLACE;
2139                 som_buf->lb_buf = &mlc->mlc_som;
2140                 som_buf->lb_len = sizeof(mlc->mlc_som);
2141         }
2142
2143         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2144         if (rc)
2145                 GOTO(out, rc);
2146
2147         /* record a changelog for the completion of resync */
2148         rc = mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
2149         if (rc)
2150                 GOTO(out, rc);
2151
2152         /* RESYNC_DONE has piggybacked size and blocks */
2153         if (fl) {
2154                 rc = mdd_declare_xattr_set(env, mdd, obj, som_buf,
2155                                            XATTR_NAME_SOM, fl, handle);
2156                 if (rc)
2157                         GOTO(out, rc);
2158         }
2159
2160         rc = mdd_trans_start(env, mdd, handle);
2161         if (rc)
2162                 GOTO(out, rc);
2163
2164         /* it needs a sync tx to make FLR to work properly */
2165         handle->th_sync = 1;
2166
2167         rc = mdo_layout_change(env, obj, mlc, handle);
2168         if (rc)
2169                 GOTO(out, rc);
2170
2171         if (fl) {
2172                 rc = mdo_xattr_set(env, obj, som_buf, XATTR_NAME_SOM,
2173                                    fl, handle);
2174                 if (rc)
2175                         GOTO(out, rc);
2176         }
2177
2178         rc = mdd_changelog_data_store(env, mdd, CL_RESYNC, 0, obj, handle);
2179         if (rc)
2180                 GOTO(out, rc);
2181         EXIT;
2182 out:
2183         return rc;
2184 }
2185
2186 /**
2187  * Layout change callback for object.
2188  *
2189  * This is only used by FLR for now. In the future, it can be exteneded to
2190  * handle all layout change.
2191  */
2192 static int
2193 mdd_layout_change(const struct lu_env *env, struct md_object *o,
2194                   struct md_layout_change *mlc)
2195 {
2196         struct mdd_object       *obj = md2mdd_obj(o);
2197         struct mdd_device       *mdd = mdd_obj2mdd_dev(obj);
2198         struct lu_buf           *buf = mdd_buf_get(env, NULL, 0);
2199         struct lov_comp_md_v1   *lcm;
2200         struct thandle          *handle;
2201         int flr_state;
2202         int rc;
2203         ENTRY;
2204
2205         /* Verify acceptable operations */
2206         switch (mlc->mlc_opc) {
2207         case MD_LAYOUT_WRITE:
2208         case MD_LAYOUT_RESYNC:
2209         case MD_LAYOUT_RESYNC_DONE:
2210                 break;
2211         default:
2212                 RETURN(-ENOTSUPP);
2213         }
2214
2215         handle = mdd_trans_create(env, mdd);
2216         if (IS_ERR(handle))
2217                 RETURN(PTR_ERR(handle));
2218
2219         rc = mdd_get_lov_ea(env, obj, buf);
2220         if (rc < 0) {
2221                 if (rc == -ENODATA)
2222                         rc = -EINVAL;
2223                 GOTO(out, rc);
2224         }
2225
2226         /* analyze the layout to make sure it's a FLR file */
2227         lcm = buf->lb_buf;
2228         if (le32_to_cpu(lcm->lcm_magic) != LOV_MAGIC_COMP_V1)
2229                 GOTO(out, rc = -EINVAL);
2230
2231         flr_state = le16_to_cpu(lcm->lcm_flags) & LCM_FL_FLR_MASK;
2232
2233         /* please refer to HLD of FLR for state transition */
2234         switch (flr_state) {
2235         case LCM_FL_NOT_FLR:
2236                 rc = mdd_layout_instantiate_component(env, obj, mlc, handle);
2237                 break;
2238         case LCM_FL_WRITE_PENDING:
2239                 rc = mdd_layout_update_write_pending(env, obj, mlc, handle);
2240                 break;
2241         case LCM_FL_RDONLY:
2242                 rc = mdd_layout_update_rdonly(env, obj, mlc, handle);
2243                 break;
2244         case LCM_FL_SYNC_PENDING:
2245                 rc = mdd_object_update_sync_pending(env, obj, mlc, handle);
2246                 break;
2247         default:
2248                 rc = 0;
2249                 break;
2250         }
2251         EXIT;
2252
2253 out:
2254         mdd_trans_stop(env, mdd, rc, handle);
2255         lu_buf_free(buf);
2256         return rc;
2257 }
2258
2259 void mdd_object_make_hint(const struct lu_env *env, struct mdd_object *parent,
2260                           struct mdd_object *child, const struct lu_attr *attr,
2261                           const struct md_op_spec *spec,
2262                           struct dt_allocation_hint *hint)
2263 {
2264         struct dt_object *np = parent ?  mdd_object_child(parent) : NULL;
2265         struct dt_object *nc = mdd_object_child(child);
2266
2267         memset(hint, 0, sizeof(*hint));
2268
2269         /* For striped directory, give striping EA to lod_ah_init, which will
2270          * decide the stripe_offset and stripe count by it. */
2271         if (S_ISDIR(attr->la_mode) &&
2272             unlikely(spec != NULL && spec->sp_cr_flags & MDS_OPEN_HAS_EA)) {
2273                 hint->dah_eadata = spec->u.sp_ea.eadata;
2274                 hint->dah_eadata_len = spec->u.sp_ea.eadatalen;
2275         } else {
2276                 hint->dah_eadata = NULL;
2277                 hint->dah_eadata_len = 0;
2278         }
2279
2280         CDEBUG(D_INFO, DFID" eadata %p len %d\n", PFID(mdd_object_fid(child)),
2281                hint->dah_eadata, hint->dah_eadata_len);
2282         /* @hint will be initialized by underlying device. */
2283         nc->do_ops->do_ah_init(env, hint, np, nc, attr->la_mode & S_IFMT);
2284 }
2285
2286 /*
2287  * do NOT or the MAY_*'s, you'll get the weakest
2288  */
2289 int accmode(const struct lu_env *env, const struct lu_attr *la, int flags)
2290 {
2291         int res = 0;
2292
2293         /* Sadly, NFSD reopens a file repeatedly during operation, so the
2294          * "acc_mode = 0" allowance for newly-created files isn't honoured.
2295          * NFSD uses the MDS_OPEN_OWNEROVERRIDE flag to say that a file
2296          * owner can write to a file even if it is marked readonly to hide
2297          * its brokenness. (bug 5781) */
2298         if (flags & MDS_OPEN_OWNEROVERRIDE) {
2299                 struct lu_ucred *uc = lu_ucred_check(env);
2300
2301                 if ((uc == NULL) || (la->la_uid == uc->uc_fsuid))
2302                         return 0;
2303         }
2304
2305         if (flags & FMODE_READ)
2306                 res |= MAY_READ;
2307         if (flags & (FMODE_WRITE | MDS_OPEN_TRUNC | MDS_OPEN_APPEND))
2308                 res |= MAY_WRITE;
2309         if (flags & MDS_FMODE_EXEC)
2310                 res = MAY_EXEC;
2311         return res;
2312 }
2313
2314 static int mdd_open_sanity_check(const struct lu_env *env,
2315                                 struct mdd_object *obj,
2316                                 const struct lu_attr *attr, int flag)
2317 {
2318         int mode, rc;
2319         ENTRY;
2320
2321         /* EEXIST check */
2322         if (mdd_is_dead_obj(obj))
2323                 RETURN(-ENOENT);
2324
2325         if (S_ISLNK(attr->la_mode))
2326                 RETURN(-ELOOP);
2327
2328         mode = accmode(env, attr, flag);
2329
2330         if (S_ISDIR(attr->la_mode) && (mode & MAY_WRITE))
2331                 RETURN(-EISDIR);
2332
2333         if (!(flag & MDS_OPEN_CREATED)) {
2334                 rc = mdd_permission_internal(env, obj, attr, mode);
2335                 if (rc)
2336                         RETURN(rc);
2337         }
2338
2339         if (S_ISFIFO(attr->la_mode) || S_ISSOCK(attr->la_mode) ||
2340             S_ISBLK(attr->la_mode) || S_ISCHR(attr->la_mode))
2341                 flag &= ~MDS_OPEN_TRUNC;
2342
2343         /* For writing append-only file must open it with append mode. */
2344         if (attr->la_flags & LUSTRE_APPEND_FL) {
2345                 if ((flag & FMODE_WRITE) && !(flag & MDS_OPEN_APPEND))
2346                         RETURN(-EPERM);
2347                 if (flag & MDS_OPEN_TRUNC)
2348                         RETURN(-EPERM);
2349         }
2350
2351         RETURN(0);
2352 }
2353
2354 static int mdd_open(const struct lu_env *env, struct md_object *obj,
2355                     int flags)
2356 {
2357         struct mdd_object *mdd_obj = md2mdd_obj(obj);
2358         struct md_device *md_dev = lu2md_dev(mdd2lu_dev(mdo2mdd(obj)));
2359         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
2360         int rc = 0;
2361
2362         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
2363
2364         rc = mdd_la_get(env, mdd_obj, attr);
2365         if (rc != 0)
2366                 GOTO(out, rc);
2367
2368         rc = mdd_open_sanity_check(env, mdd_obj, attr, flags);
2369         if (rc != 0)
2370                 GOTO(out, rc);
2371
2372         mdd_obj->mod_count++;
2373
2374         mdd_changelog(env, CL_OPEN, flags, md_dev, mdo2fid(mdd_obj));
2375
2376         EXIT;
2377 out:
2378         mdd_write_unlock(env, mdd_obj);
2379         return rc;
2380 }
2381
2382 static int mdd_declare_close(const struct lu_env *env,
2383                              struct mdd_object *obj,
2384                              struct md_attr *ma,
2385                              struct thandle *handle)
2386 {
2387         int rc;
2388
2389         rc = orph_declare_index_delete(env, obj, handle);
2390         if (rc)
2391                 return rc;
2392
2393         return mdo_declare_destroy(env, obj, handle);
2394 }
2395
2396 /*
2397  * No permission check is needed.
2398  */
2399 static int mdd_close(const struct lu_env *env, struct md_object *obj,
2400                      struct md_attr *ma, int mode)
2401 {
2402         struct mdd_object *mdd_obj = md2mdd_obj(obj);
2403         struct mdd_device *mdd = mdo2mdd(obj);
2404         struct thandle *handle = NULL;
2405         int is_orphan = 0;
2406         int rc;
2407         bool blocked = false;
2408         ENTRY;
2409
2410         if (ma->ma_valid & MA_FLAGS && ma->ma_attr_flags & MDS_KEEP_ORPHAN) {
2411                 mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
2412                 mdd_obj->mod_count--;
2413                 mdd_write_unlock(env, mdd_obj);
2414
2415                 if (mdd_obj->mod_flags & ORPHAN_OBJ && !mdd_obj->mod_count)
2416                         CDEBUG(D_HA, "Object "DFID" is retained in orphan "
2417                                 "list\n", PFID(mdd_object_fid(mdd_obj)));
2418                 RETURN(0);
2419         }
2420
2421         /* mdd_finish_unlink() will always set orphan object as DEAD_OBJ, but
2422          * it might fail to add the object to orphan list (w/o ORPHAN_OBJ). */
2423         /* check without any lock */
2424         is_orphan = mdd_obj->mod_count == 1 &&
2425                     (mdd_obj->mod_flags & (ORPHAN_OBJ | DEAD_OBJ)) != 0;
2426
2427 again:
2428         if (is_orphan) {
2429                 /* mdd_trans_create() maybe failed because of barrier_entry(),
2430                  * under such case, the orphan MDT-object will be left in the
2431                  * orphan list, and when the MDT remount next time, the unused
2432                  * orphans will be destroyed automatically.
2433                  *
2434                  * One exception: the former mdd_finish_unlink may failed to
2435                  * add the orphan MDT-object to the orphan list, then if the
2436                  * mdd_trans_create() failed because of barrier_entry(), the
2437                  * MDT-object will become real orphan that is neither in the
2438                  * namespace nor in the orphan list. Such bad case should be
2439                  * very rare and will be handled by e2fsck/lfsck. */
2440                 handle = mdd_trans_create(env, mdo2mdd(obj));
2441                 if (IS_ERR(handle)) {
2442                         rc = PTR_ERR(handle);
2443                         if (rc != -EINPROGRESS)
2444                                 GOTO(stop, rc);
2445
2446                         handle = NULL;
2447                         blocked = true;
2448                         goto cont;
2449                 }
2450
2451                 rc = mdd_declare_close(env, mdd_obj, ma, handle);
2452                 if (rc)
2453                         GOTO(stop, rc);
2454
2455                 rc = mdd_declare_changelog_store(env, mdd, NULL, NULL, handle);
2456                 if (rc)
2457                         GOTO(stop, rc);
2458
2459                 rc = mdd_trans_start(env, mdo2mdd(obj), handle);
2460                 if (rc)
2461                         GOTO(stop, rc);
2462         }
2463
2464 cont:
2465         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
2466         rc = mdd_la_get(env, mdd_obj, &ma->ma_attr);
2467         if (rc != 0) {
2468                 CERROR("Failed to get lu_attr of "DFID": %d\n",
2469                        PFID(mdd_object_fid(mdd_obj)), rc);
2470                 GOTO(out, rc);
2471         }
2472
2473         /* check again with lock */
2474         is_orphan = (mdd_obj->mod_count == 1) &&
2475                     ((mdd_obj->mod_flags & (ORPHAN_OBJ | DEAD_OBJ)) != 0 ||
2476                      ma->ma_attr.la_nlink == 0);
2477
2478         if (is_orphan && !handle && !blocked) {
2479                 mdd_write_unlock(env, mdd_obj);
2480                 goto again;
2481         }
2482
2483         mdd_obj->mod_count--; /*release open count */
2484
2485         if (!is_orphan || blocked)
2486                 GOTO(out, rc = 0);
2487
2488         /* Orphan object */
2489         /* NB: Object maybe not in orphan list originally, it is rare case for
2490          * mdd_finish_unlink() failure, in that case, the object doesn't have
2491          * ORPHAN_OBJ flag */
2492         if ((mdd_obj->mod_flags & ORPHAN_OBJ) != 0) {
2493                 /* remove link to object from orphan index */
2494                 LASSERT(handle != NULL);
2495                 rc = __mdd_orphan_del(env, mdd_obj, handle);
2496                 if (rc != 0) {
2497                         CERROR("%s: unable to delete "DFID" from orphan list: "
2498                                "rc = %d\n", lu_dev_name(mdd2lu_dev(mdd)),
2499                                PFID(mdd_object_fid(mdd_obj)), rc);
2500                         /* If object was not deleted from orphan list, do not
2501                          * destroy OSS objects, which will be done when next
2502                          * recovery. */
2503                         GOTO(out, rc);
2504                 }
2505
2506                 CDEBUG(D_HA, "Object "DFID" is deleted from orphan "
2507                        "list, OSS objects to be destroyed.\n",
2508                        PFID(mdd_object_fid(mdd_obj)));
2509         }
2510
2511         rc = mdo_destroy(env, mdd_obj, handle);
2512
2513         if (rc != 0) {
2514                 CERROR("%s: unable to delete "DFID" from orphan list: "
2515                        "rc = %d\n", lu_dev_name(mdd2lu_dev(mdd)),
2516                        PFID(mdd_object_fid(mdd_obj)), rc);
2517         }
2518         EXIT;
2519
2520 out:
2521         mdd_write_unlock(env, mdd_obj);
2522
2523         /* Record CL_CLOSE in changelog only if file was opened in write mode,
2524          * or if CL_OPEN was recorded.
2525          * Changelogs mask may change between open and close operations, but
2526          * this is not a big deal if we have a CL_CLOSE entry with no matching
2527          * CL_OPEN. Plus Changelogs mask may not change often.
2528          */
2529         if (!rc && !blocked &&
2530             ((mode & (FMODE_WRITE | MDS_OPEN_APPEND | MDS_OPEN_TRUNC)) ||
2531              (mdd->mdd_cl.mc_mask & (1 << CL_OPEN))) &&
2532             !(ma->ma_valid & MA_FLAGS && ma->ma_attr_flags & MDS_RECOV_OPEN)) {
2533                 if (handle == NULL) {
2534                         handle = mdd_trans_create(env, mdo2mdd(obj));
2535                         if (IS_ERR(handle))
2536                                 GOTO(stop, rc = PTR_ERR(handle));
2537
2538                         rc = mdd_declare_changelog_store(env, mdd, NULL, NULL,
2539                                                          handle);
2540                         if (rc)
2541                                 GOTO(stop, rc);
2542
2543                         rc = mdd_trans_start(env, mdo2mdd(obj), handle);
2544                         if (rc)
2545                                 GOTO(stop, rc);
2546                 }
2547
2548                 mdd_changelog_data_store(env, mdd, CL_CLOSE, mode,
2549                                          mdd_obj, handle);
2550         }
2551
2552 stop:
2553         if (handle != NULL && !IS_ERR(handle))
2554                 rc = mdd_trans_stop(env, mdd, rc, handle);
2555
2556         return rc;
2557 }
2558
2559 /*
2560  * Permission check is done when open,
2561  * no need check again.
2562  */
2563 static int mdd_readpage_sanity_check(const struct lu_env *env,
2564                                      struct mdd_object *obj)
2565 {
2566         struct dt_object *next = mdd_object_child(obj);
2567         int rc;
2568         ENTRY;
2569
2570         if (S_ISDIR(mdd_object_type(obj)) && dt_try_as_dir(env, next))
2571                 rc = 0;
2572         else
2573                 rc = -ENOTDIR;
2574
2575         RETURN(rc);
2576 }
2577
2578 static int mdd_dir_page_build(const struct lu_env *env, union lu_page *lp,
2579                               size_t nob, const struct dt_it_ops *iops,
2580                               struct dt_it *it, __u32 attr, void *arg)
2581 {
2582         struct lu_dirpage       *dp = &lp->lp_dir;
2583         void                    *area = dp;
2584         int                      result;
2585         __u64                    hash = 0;
2586         struct lu_dirent        *ent;
2587         struct lu_dirent        *last = NULL;
2588         struct lu_fid            fid;
2589         int                      first = 1;
2590
2591         if (nob < sizeof(*dp))
2592                 return -EINVAL;
2593
2594         memset(area, 0, sizeof (*dp));
2595         area += sizeof (*dp);
2596         nob  -= sizeof (*dp);
2597
2598         ent  = area;
2599         do {
2600                 int    len;
2601                 size_t recsize;
2602
2603                 len = iops->key_size(env, it);
2604
2605                 /* IAM iterator can return record with zero len. */
2606                 if (len == 0)
2607                         goto next;
2608
2609                 hash = iops->store(env, it);
2610                 if (unlikely(first)) {
2611                         first = 0;
2612                         dp->ldp_hash_start = cpu_to_le64(hash);
2613                 }
2614
2615                 /* calculate max space required for lu_dirent */
2616                 recsize = lu_dirent_calc_size(len, attr);
2617
2618                 if (nob >= recsize) {
2619                         result = iops->rec(env, it, (struct dt_rec *)ent, attr);
2620                         if (result == -ESTALE)
2621                                 goto next;
2622                         if (result != 0)
2623                                 goto out;
2624
2625                         /* osd might not able to pack all attributes,
2626                          * so recheck rec length */
2627                         recsize = le16_to_cpu(ent->lde_reclen);
2628
2629                         if (le32_to_cpu(ent->lde_attrs) & LUDA_FID) {
2630                                 fid_le_to_cpu(&fid, &ent->lde_fid);
2631                                 if (fid_is_dot_lustre(&fid))
2632                                         goto next;
2633                         }
2634                 } else {
2635                         result = (last != NULL) ? 0 :-EINVAL;
2636                         goto out;
2637                 }
2638                 last = ent;
2639                 ent = (void *)ent + recsize;
2640                 nob -= recsize;
2641
2642 next:
2643                 result = iops->next(env, it);
2644                 if (result == -ESTALE)
2645                         goto next;
2646         } while (result == 0);
2647
2648 out:
2649         dp->ldp_hash_end = cpu_to_le64(hash);
2650         if (last != NULL) {
2651                 if (last->lde_hash == dp->ldp_hash_end)
2652                         dp->ldp_flags |= cpu_to_le32(LDF_COLLIDE);
2653                 last->lde_reclen = 0; /* end mark */
2654         }
2655         if (result > 0)
2656                 /* end of directory */
2657                 dp->ldp_hash_end = cpu_to_le64(MDS_DIR_END_OFF);
2658         else if (result < 0)
2659                 CWARN("build page failed: %d!\n", result);
2660         return result;
2661 }
2662
2663 int mdd_readpage(const struct lu_env *env, struct md_object *obj,
2664                  const struct lu_rdpg *rdpg)
2665 {
2666         struct mdd_object *mdd_obj = md2mdd_obj(obj);
2667         int rc;
2668         ENTRY;
2669
2670         if (mdd_object_exists(mdd_obj) == 0) {
2671                 CERROR("%s: object "DFID" not found: rc = -2\n",
2672                        mdd_obj_dev_name(mdd_obj),PFID(mdd_object_fid(mdd_obj)));
2673                 return -ENOENT;
2674         }
2675
2676         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
2677         rc = mdd_readpage_sanity_check(env, mdd_obj);
2678         if (rc)
2679                 GOTO(out_unlock, rc);
2680
2681         if (mdd_is_dead_obj(mdd_obj)) {
2682                 struct page *pg;
2683                 struct lu_dirpage *dp;
2684
2685                 /*
2686                  * According to POSIX, please do not return any entry to client:
2687                  * even dot and dotdot should not be returned.
2688                  */
2689                 CDEBUG(D_INODE, "readdir from dead object: "DFID"\n",
2690                        PFID(mdd_object_fid(mdd_obj)));
2691
2692                 if (rdpg->rp_count <= 0)
2693                         GOTO(out_unlock, rc = -EFAULT);
2694                 LASSERT(rdpg->rp_pages != NULL);
2695
2696                 pg = rdpg->rp_pages[0];
2697                 dp = (struct lu_dirpage *)kmap(pg);
2698                 memset(dp, 0 , sizeof(struct lu_dirpage));
2699                 dp->ldp_hash_start = cpu_to_le64(rdpg->rp_hash);
2700                 dp->ldp_hash_end   = cpu_to_le64(MDS_DIR_END_OFF);
2701                 dp->ldp_flags = cpu_to_le32(LDF_EMPTY);
2702                 kunmap(pg);
2703                 GOTO(out_unlock, rc = LU_PAGE_SIZE);
2704         }
2705
2706         rc = dt_index_walk(env, mdd_object_child(mdd_obj), rdpg,
2707                            mdd_dir_page_build, NULL);
2708         if (rc >= 0) {
2709                 struct lu_dirpage       *dp;
2710
2711                 dp = kmap(rdpg->rp_pages[0]);
2712                 dp->ldp_hash_start = cpu_to_le64(rdpg->rp_hash);
2713                 if (rc == 0) {
2714                         /*
2715                          * No pages were processed, mark this for first page
2716                          * and send back.
2717                          */
2718                         dp->ldp_hash_end = cpu_to_le64(MDS_DIR_END_OFF);
2719                         dp->ldp_flags = cpu_to_le32(LDF_EMPTY);
2720                         rc = min_t(unsigned int, LU_PAGE_SIZE, rdpg->rp_count);
2721                 }
2722                 kunmap(rdpg->rp_pages[0]);
2723         }
2724
2725         GOTO(out_unlock, rc);
2726 out_unlock:
2727         mdd_read_unlock(env, mdd_obj);
2728         return rc;
2729 }
2730
2731 static int mdd_object_sync(const struct lu_env *env, struct md_object *obj)
2732 {
2733         struct mdd_object *mdd_obj = md2mdd_obj(obj);
2734
2735         if (mdd_object_exists(mdd_obj) == 0) {
2736                 int rc = -ENOENT;
2737
2738                 CERROR("%s: object "DFID" not found: rc = %d\n",
2739                        mdd_obj_dev_name(mdd_obj),
2740                        PFID(mdd_object_fid(mdd_obj)), rc);
2741                 return rc;
2742         }
2743         return dt_object_sync(env, mdd_object_child(mdd_obj),
2744                               0, OBD_OBJECT_EOF);
2745 }
2746
2747 static int mdd_object_lock(const struct lu_env *env,
2748                            struct md_object *obj,
2749                            struct lustre_handle *lh,
2750                            struct ldlm_enqueue_info *einfo,
2751                            union ldlm_policy_data *policy)
2752 {
2753         struct mdd_object *mdd_obj = md2mdd_obj(obj);
2754         return dt_object_lock(env, mdd_object_child(mdd_obj), lh,
2755                               einfo, policy);
2756 }
2757
2758 static int mdd_object_unlock(const struct lu_env *env,
2759                              struct md_object *obj,
2760                              struct ldlm_enqueue_info *einfo,
2761                              union ldlm_policy_data *policy)
2762 {
2763         struct mdd_object *mdd_obj = md2mdd_obj(obj);
2764         return dt_object_unlock(env, mdd_object_child(mdd_obj), einfo, policy);
2765 }
2766
2767 const struct md_object_operations mdd_obj_ops = {
2768         .moo_permission         = mdd_permission,
2769         .moo_attr_get           = mdd_attr_get,
2770         .moo_attr_set           = mdd_attr_set,
2771         .moo_xattr_get          = mdd_xattr_get,
2772         .moo_xattr_set          = mdd_xattr_set,
2773         .moo_xattr_list         = mdd_xattr_list,
2774         .moo_invalidate         = mdd_invalidate,
2775         .moo_xattr_del          = mdd_xattr_del,
2776         .moo_swap_layouts       = mdd_swap_layouts,
2777         .moo_open               = mdd_open,
2778         .moo_close              = mdd_close,
2779         .moo_readpage           = mdd_readpage,
2780         .moo_readlink           = mdd_readlink,
2781         .moo_changelog          = mdd_changelog,
2782         .moo_object_sync        = mdd_object_sync,
2783         .moo_object_lock        = mdd_object_lock,
2784         .moo_object_unlock      = mdd_object_unlock,
2785         .moo_layout_change      = mdd_layout_change,
2786 };