Whamcloud - gitweb
LU-10030 idl: use proper ATTR/MDS_ATTR/MDS_OPEN flags
[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 struct mdd_object_user {
57         struct list_head        mou_list;       /**< linked off mod_users */
58         u64                     mou_open_flags; /**< open mode by client */
59         __u64                   mou_uidgid;     /**< uid_gid on client */
60         int                     mou_opencount;  /**< # opened */
61         ktime_t                 mou_deniednext; /**< time of next access denied
62                                                  * notfication
63                                                  */
64 };
65
66 static int mdd_xattr_get(const struct lu_env *env,
67                          struct md_object *obj, struct lu_buf *buf,
68                          const char *name);
69
70 static int mdd_changelog_data_store_by_fid(const struct lu_env *env,
71                                            struct mdd_device *mdd,
72                                            enum changelog_rec_type type,
73                                            int flags, const struct lu_fid *fid,
74                                            const char *xattr_name,
75                                            struct thandle *handle);
76
77 static inline bool has_prefix(const char *str, const char *prefix);
78
79
80 static u32 flags_helper(u64 open_flags)
81 {
82         u32 open_mode = 0;
83
84         if (open_flags & MDS_FMODE_EXEC) {
85                 open_mode = MDS_FMODE_EXEC;
86         } else {
87                 if (open_flags & MDS_FMODE_READ)
88                         open_mode = MDS_FMODE_READ;
89                 if (open_flags &
90                     (MDS_FMODE_WRITE | MDS_OPEN_TRUNC | MDS_OPEN_APPEND))
91                         open_mode |= MDS_FMODE_WRITE;
92         }
93
94         return open_mode;
95 }
96
97 /** Allocate/init a user and its sub-structures.
98  *
99  * \param flags [IN]
100  * \param uid [IN]
101  * \param gid [IN]
102  * \retval mou [OUT] success valid structure
103  * \retval mou [OUT]
104  */
105 static struct mdd_object_user *mdd_obj_user_alloc(u64 open_flags,
106                                                   uid_t uid, gid_t gid)
107 {
108         struct mdd_object_user *mou;
109
110         ENTRY;
111
112         OBD_SLAB_ALLOC_PTR(mou, mdd_object_kmem);
113         if (mou == NULL)
114                 RETURN(ERR_PTR(-ENOMEM));
115
116         mou->mou_open_flags = open_flags;
117         mou->mou_uidgid = ((__u64)uid << 32) | gid;
118         mou->mou_opencount = 0;
119         mou->mou_deniednext = ktime_set(0, 0);
120
121         RETURN(mou);
122 }
123
124 /**
125  * Free a user and its sub-structures.
126  *
127  * \param mou [IN]  user to be freed.
128  */
129 static void mdd_obj_user_free(struct mdd_object_user *mou)
130 {
131         OBD_SLAB_FREE_PTR(mou, mdd_object_kmem);
132 }
133
134 /**
135  * Find if UID/GID already has this file open
136  *
137  * Caller should have write-locked \param mdd_obj.
138  * \param mdd_obj [IN] mdd_obj
139  * \param uid [IN] client uid
140  * \param gid [IN] client gid
141  * \retval user pointer or NULL if not found
142  */
143 static
144 struct mdd_object_user *mdd_obj_user_find(struct mdd_object *mdd_obj,
145                                           uid_t uid, gid_t gid,
146                                           u64 open_flags)
147 {
148         struct mdd_object_user *mou;
149         __u64 uidgid;
150
151         ENTRY;
152
153         uidgid = ((__u64)uid << 32) | gid;
154         list_for_each_entry(mou, &mdd_obj->mod_users, mou_list) {
155                 if (mou->mou_uidgid == uidgid &&
156                     flags_helper(mou->mou_open_flags) ==
157                     flags_helper(open_flags))
158                         RETURN(mou);
159         }
160         RETURN(NULL);
161 }
162
163 /**
164  * Add a user to the list of openers for this file
165  *
166  * Caller should have write-locked \param mdd_obj.
167  * \param mdd_obj [IN] mdd_obj
168  * \param mou [IN] user
169  * \retval 0 success
170  * \retval -ve failure
171  */
172 static int mdd_obj_user_add(struct mdd_object *mdd_obj,
173                             struct mdd_object_user *mou,
174                             bool denied)
175 {
176         struct mdd_device *mdd = mdd_obj2mdd_dev(mdd_obj);
177         struct mdd_object_user *tmp;
178         __u32 uid = mou->mou_uidgid >> 32;
179         __u32 gid = mou->mou_uidgid & ((1UL << 32) - 1);
180
181         ENTRY;
182
183         tmp = mdd_obj_user_find(mdd_obj, uid, gid, mou->mou_open_flags);
184         if (tmp != NULL)
185                 RETURN(-EEXIST);
186
187         list_add_tail(&mou->mou_list, &mdd_obj->mod_users);
188
189         if (denied)
190                 /* next 'access denied' notification cannot happen before
191                  * mou_deniednext
192                  */
193                 mou->mou_deniednext =
194                         ktime_add(ktime_get(),
195                                   ktime_set(mdd->mdd_cl.mc_deniednext, 0));
196         else
197                 mou->mou_opencount++;
198
199         RETURN(0);
200 }
201 /**
202  * Remove UID from the list
203  *
204  * Caller should have write-locked \param mdd_obj.
205  * \param mdd_obj [IN] mdd_obj
206  * \param uid [IN] user
207  * \retval -ve failure
208  */
209 static int mdd_obj_user_remove(struct mdd_object *mdd_obj,
210                                struct mdd_object_user *mou)
211 {
212         ENTRY;
213
214         if (mou == NULL)
215                 RETURN(-ENOENT);
216
217         list_del_init(&mou->mou_list);
218
219         mdd_obj_user_free(mou);
220
221         RETURN(0);
222 }
223 int mdd_la_get(const struct lu_env *env, struct mdd_object *obj,
224                struct lu_attr *la)
225 {
226         int rc;
227
228         if (mdd_object_exists(obj) == 0)
229                 return -ENOENT;
230
231         rc = mdo_attr_get(env, obj, la);
232         if (unlikely(rc != 0)) {
233                 if (rc == -ENOENT)
234                         obj->mod_flags |= DEAD_OBJ;
235                 return rc;
236         }
237
238         if (la->la_valid & LA_FLAGS &&
239             la->la_flags & LUSTRE_ORPHAN_FL)
240                 obj->mod_flags |= ORPHAN_OBJ | DEAD_OBJ;
241
242         return 0;
243 }
244
245 struct mdd_thread_info *mdd_env_info(const struct lu_env *env)
246 {
247         struct mdd_thread_info *info;
248
249         lu_env_refill((struct lu_env *)env);
250         info = lu_context_key_get(&env->le_ctx, &mdd_thread_key);
251         LASSERT(info != NULL);
252         return info;
253 }
254
255 struct lu_buf *mdd_buf_get(const struct lu_env *env, void *area, ssize_t len)
256 {
257         struct lu_buf *buf;
258
259         buf = &mdd_env_info(env)->mti_buf[0];
260         buf->lb_buf = area;
261         buf->lb_len = len;
262         return buf;
263 }
264
265 const struct lu_buf *mdd_buf_get_const(const struct lu_env *env,
266                                        const void *area, ssize_t len)
267 {
268         struct lu_buf *buf;
269
270         buf = &mdd_env_info(env)->mti_buf[0];
271         buf->lb_buf = (void *)area;
272         buf->lb_len = len;
273         return buf;
274 }
275
276 struct lu_object *mdd_object_alloc(const struct lu_env *env,
277                                    const struct lu_object_header *hdr,
278                                    struct lu_device *d)
279 {
280         struct mdd_object *mdd_obj;
281         struct lu_object *o;
282
283         OBD_SLAB_ALLOC_PTR_GFP(mdd_obj, mdd_object_kmem, GFP_NOFS);
284         if (!mdd_obj)
285                 return NULL;
286
287         o = mdd2lu_obj(mdd_obj);
288         lu_object_init(o, NULL, d);
289         mdd_obj->mod_obj.mo_ops = &mdd_obj_ops;
290         mdd_obj->mod_obj.mo_dir_ops = &mdd_dir_ops;
291         mdd_obj->mod_count = 0;
292         o->lo_ops = &mdd_lu_obj_ops;
293         INIT_LIST_HEAD(&mdd_obj->mod_users);
294
295         return o;
296 }
297
298 static int mdd_object_init(const struct lu_env *env, struct lu_object *o,
299                            const struct lu_object_conf *unused)
300 {
301         struct mdd_device *d = lu2mdd_dev(o->lo_dev);
302         struct mdd_object *mdd_obj = lu2mdd_obj(o);
303         struct lu_object  *below;
304         struct lu_device  *under;
305         ENTRY;
306
307         mdd_obj->mod_cltime = ktime_set(0, 0);
308         under = &d->mdd_child->dd_lu_dev;
309         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
310         if (IS_ERR(below))
311                 RETURN(PTR_ERR(below));
312
313         lu_object_add(o, below);
314
315         RETURN(0);
316 }
317
318 static int mdd_object_start(const struct lu_env *env, struct lu_object *o)
319 {
320         int rc = 0;
321
322         if (lu_object_exists(o)) {
323                 struct mdd_object *mdd_obj = lu2mdd_obj(o);
324                 struct lu_attr *attr = MDD_ENV_VAR(env, la_for_start);
325
326                 rc = mdd_la_get(env, mdd_obj, attr);
327         }
328
329         return rc;
330 }
331
332 static void mdd_object_free(const struct lu_env *env, struct lu_object *o)
333 {
334         struct mdd_object *mdd = lu2mdd_obj(o);
335         struct mdd_object_user *mou, *tmp2;
336
337         /* free user list */
338         list_for_each_entry_safe(mou, tmp2, &mdd->mod_users, mou_list) {
339                 list_del(&mou->mou_list);
340                 mdd_obj_user_free(mou);
341         }
342
343         lu_object_fini(o);
344         OBD_SLAB_FREE_PTR(mdd, mdd_object_kmem);
345 }
346
347 static int mdd_object_print(const struct lu_env *env, void *cookie,
348                             lu_printer_t p, const struct lu_object *o)
349 {
350         struct mdd_object *mdd = lu2mdd_obj((struct lu_object *)o);
351
352         return (*p)(env, cookie,
353                     LUSTRE_MDD_NAME"-object@%p(open_count=%d, valid=%x, cltime=%lldns, flags=%lx)",
354                     mdd, mdd->mod_count, mdd->mod_valid,
355                     ktime_to_ns(mdd->mod_cltime), mdd->mod_flags);
356 }
357
358 static const struct lu_object_operations mdd_lu_obj_ops = {
359         .loo_object_init    = mdd_object_init,
360         .loo_object_start   = mdd_object_start,
361         .loo_object_free    = mdd_object_free,
362         .loo_object_print   = mdd_object_print,
363 };
364
365 struct mdd_object *mdd_object_find(const struct lu_env *env,
366                                    struct mdd_device *d,
367                                    const struct lu_fid *f)
368 {
369         return md2mdd_obj(md_object_find_slice(env, &d->mdd_md_dev, f));
370 }
371
372 /*
373  * No permission check is needed.
374  */
375 int mdd_attr_get(const struct lu_env *env, struct md_object *obj,
376                  struct md_attr *ma)
377 {
378         struct mdd_object *mdd_obj = md2mdd_obj(obj);
379         int               rc;
380
381         ENTRY;
382
383         rc = mdd_la_get(env, mdd_obj, &ma->ma_attr);
384         if ((ma->ma_need & MA_INODE) != 0 && mdd_is_dead_obj(mdd_obj))
385                 ma->ma_attr.la_nlink = 0;
386
387         RETURN(rc);
388 }
389
390 /*
391  * No permission check is needed.
392  */
393 static int mdd_xattr_get(const struct lu_env *env,
394                          struct md_object *obj, struct lu_buf *buf,
395                          const char *name)
396 {
397         struct mdd_object *mdd_obj = md2mdd_obj(obj);
398         struct mdd_device *mdd;
399         int rc;
400
401         ENTRY;
402
403         if (mdd_object_exists(mdd_obj) == 0) {
404                 CERROR("%s: object "DFID" not found: rc = -2\n",
405                        mdd_obj_dev_name(mdd_obj),
406                        PFID(mdd_object_fid(mdd_obj)));
407                 return -ENOENT;
408         }
409
410         /* If the object has been destroyed, then do not get LMVEA, because
411          * it needs to load stripes from the iteration of the master object,
412          * and it will cause problem if master object has been destroyed, see
413          * LU-6427 */
414         if (unlikely((mdd_obj->mod_flags & DEAD_OBJ) &&
415                      !(mdd_obj->mod_flags & ORPHAN_OBJ) &&
416                       strcmp(name, XATTR_NAME_LMV) == 0))
417                 RETURN(-ENOENT);
418
419         /* If the object has been delete from the namespace, then
420          * get linkEA should return -ENOENT as well */
421         if (unlikely((mdd_obj->mod_flags & (DEAD_OBJ | ORPHAN_OBJ)) &&
422                       strcmp(name, XATTR_NAME_LINK) == 0))
423                 RETURN(-ENOENT);
424
425         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
426         rc = mdo_xattr_get(env, mdd_obj, buf, name);
427         mdd_read_unlock(env, mdd_obj);
428
429         mdd = mdo2mdd(obj);
430
431         /* record only getting user xattrs and acls */
432         if (rc >= 0 &&
433             mdd_changelog_enabled(env, mdd, CL_GETXATTR) &&
434             (has_prefix(name, XATTR_USER_PREFIX) ||
435              has_prefix(name, XATTR_NAME_POSIX_ACL_ACCESS) ||
436              has_prefix(name, XATTR_NAME_POSIX_ACL_DEFAULT))) {
437                 struct thandle *handle;
438                 int rc2;
439
440                 LASSERT(mdo2fid(mdd_obj) != NULL);
441
442                 handle = mdd_trans_create(env, mdd);
443                 if (IS_ERR(handle))
444                         RETURN(PTR_ERR(handle));
445
446                 rc2 = mdd_declare_changelog_store(env, mdd, CL_GETXATTR, NULL,
447                                                   NULL, handle);
448                 if (rc2)
449                         GOTO(stop, rc2);
450
451                 rc2 = mdd_trans_start(env, mdd, handle);
452                 if (rc2)
453                         GOTO(stop, rc2);
454
455                 rc2 = mdd_changelog_data_store_by_fid(env, mdd, CL_GETXATTR, 0,
456                                                       mdo2fid(mdd_obj), name,
457                                                       handle);
458
459 stop:
460                 rc2 = mdd_trans_stop(env, mdd, rc2, handle);
461                 if (rc2)
462                         rc = rc2;
463         }
464
465         RETURN(rc);
466 }
467
468 /*
469  * Permission check is done when open,
470  * no need check again.
471  */
472 int mdd_readlink(const struct lu_env *env, struct md_object *obj,
473                  struct lu_buf *buf)
474 {
475         struct mdd_object *mdd_obj = md2mdd_obj(obj);
476         struct dt_object  *next;
477         loff_t             pos = 0;
478         int                rc;
479         ENTRY;
480
481         if (mdd_object_exists(mdd_obj) == 0) {
482                 CERROR("%s: object "DFID" not found: rc = -2\n",
483                        mdd_obj_dev_name(mdd_obj),PFID(mdd_object_fid(mdd_obj)));
484                 return -ENOENT;
485         }
486
487         next = mdd_object_child(mdd_obj);
488         LASSERT(next != NULL);
489         LASSERT(next->do_body_ops != NULL);
490         LASSERT(next->do_body_ops->dbo_read != NULL);
491         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
492         rc = dt_read(env, next, buf, &pos);
493         mdd_read_unlock(env, mdd_obj);
494         RETURN(rc);
495 }
496
497 /*
498  * No permission check is needed.
499  */
500 static int mdd_xattr_list(const struct lu_env *env, struct md_object *obj,
501                           struct lu_buf *buf)
502 {
503         struct mdd_object *mdd_obj = md2mdd_obj(obj);
504         int rc;
505
506         ENTRY;
507
508         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
509         rc = mdo_xattr_list(env, mdd_obj, buf);
510         mdd_read_unlock(env, mdd_obj);
511
512         /* If the buffer is NULL then we are only here to get the
513          * length of the xattr name list. */
514         if (rc < 0 || buf->lb_buf == NULL)
515                 RETURN(rc);
516
517         /*
518          * Filter out XATTR_NAME_LINK if this is an orphan object.  See
519          * mdd_xattr_get().
520          */
521         if (unlikely(mdd_obj->mod_flags & (DEAD_OBJ | ORPHAN_OBJ))) {
522                 char   *end = (char *)buf->lb_buf + rc;
523                 char   *p = buf->lb_buf;
524
525                 while (p < end) {
526                         char   *next = p + strlen(p) + 1;
527
528                         if (strcmp(p, XATTR_NAME_LINK) == 0) {
529                                 if (end - next > 0)
530                                         memmove(p, next, end - next);
531                                 rc -= next - p;
532                                 CDEBUG(D_INFO, "Filtered out "XATTR_NAME_LINK
533                                        " of orphan "DFID"\n",
534                                        PFID(mdd_object_fid(mdd_obj)));
535                                 break;
536                         }
537
538                         p = next;
539                 }
540         }
541
542         RETURN(rc);
543 }
544
545 int mdd_invalidate(const struct lu_env *env, struct md_object *obj)
546 {
547         return mdo_invalidate(env, md2mdd_obj(obj));
548 }
549
550 int mdd_declare_create_object_internal(const struct lu_env *env,
551                                        struct mdd_object *p,
552                                        struct mdd_object *c,
553                                        struct lu_attr *attr,
554                                        struct thandle *handle,
555                                        const struct md_op_spec *spec,
556                                        struct dt_allocation_hint *hint)
557 {
558         struct dt_object_format *dof = &mdd_env_info(env)->mti_dof;
559         const struct dt_index_features *feat = spec->sp_feat;
560         int rc;
561         ENTRY;
562
563         if (feat != &dt_directory_features && feat != NULL) {
564                 dof->dof_type = DFT_INDEX;
565                 dof->u.dof_idx.di_feat = feat;
566         } else {
567                 dof->dof_type = dt_mode_to_dft(attr->la_mode);
568                 if (dof->dof_type == DFT_REGULAR) {
569                         dof->u.dof_reg.striped =
570                                 md_should_create(spec->sp_cr_flags);
571                         if (spec->sp_cr_flags & MDS_OPEN_HAS_EA)
572                                 dof->u.dof_reg.striped = 0;
573                         /* is this replay? */
574                         if (spec->no_create)
575                                 dof->u.dof_reg.striped = 0;
576                 }
577         }
578
579         rc = mdo_declare_create_object(env, c, attr, hint, dof, handle);
580
581         RETURN(rc);
582 }
583
584 int mdd_create_object_internal(const struct lu_env *env, struct mdd_object *p,
585                                struct mdd_object *c, struct lu_attr *attr,
586                                struct thandle *handle,
587                                const struct md_op_spec *spec,
588                                struct dt_allocation_hint *hint)
589 {
590         struct dt_object_format *dof = &mdd_env_info(env)->mti_dof;
591         int rc;
592         ENTRY;
593
594         LASSERT(!mdd_object_exists(c));
595
596         rc = mdo_create_object(env, c, attr, hint, dof, handle);
597
598         RETURN(rc);
599 }
600
601 int mdd_attr_set_internal(const struct lu_env *env, struct mdd_object *obj,
602                           const struct lu_attr *attr, struct thandle *handle,
603                           int needacl)
604 {
605         int rc;
606         ENTRY;
607
608         rc = mdo_attr_set(env, obj, attr, handle);
609 #ifdef CONFIG_FS_POSIX_ACL
610         if (!rc && (attr->la_valid & LA_MODE) && needacl)
611                 rc = mdd_acl_chmod(env, obj, attr->la_mode, handle);
612 #endif
613         RETURN(rc);
614 }
615
616 int mdd_update_time(const struct lu_env *env, struct mdd_object *obj,
617                     const struct lu_attr *oattr, struct lu_attr *attr,
618                     struct thandle *handle)
619 {
620         int rc = 0;
621         ENTRY;
622
623         LASSERT(attr->la_valid & LA_CTIME);
624         LASSERT(oattr != NULL);
625
626         /* Make sure the ctime is increased only, however, it's not strictly
627          * reliable at here because there is not guarantee to hold lock on
628          * object, so we just bypass some unnecessary cmtime setting first
629          * and OSD has to check it again. */
630         if (attr->la_ctime < oattr->la_ctime)
631                 attr->la_valid &= ~(LA_MTIME | LA_CTIME);
632         else if (attr->la_valid == LA_CTIME &&
633                  attr->la_ctime == oattr->la_ctime)
634                 attr->la_valid &= ~LA_CTIME;
635
636         if (attr->la_valid != 0)
637                 rc = mdd_attr_set_internal(env, obj, attr, handle, 0);
638         RETURN(rc);
639 }
640
641 /*
642  * This gives the same functionality as the code between
643  * sys_chmod and inode_setattr
644  * chown_common and inode_setattr
645  * utimes and inode_setattr
646  * This API is ported from mds_fix_attr but remove some unnecesssary stuff.
647  */
648 static int mdd_fix_attr(const struct lu_env *env, struct mdd_object *obj,
649                         const struct lu_attr *oattr, struct lu_attr *la,
650                         const unsigned long flags)
651 {
652         struct lu_ucred  *uc;
653         int               rc = 0;
654         ENTRY;
655
656         if (!la->la_valid)
657                 RETURN(0);
658
659         /* Do not permit change file type */
660         if (la->la_valid & LA_TYPE)
661                 RETURN(-EPERM);
662
663         /* They should not be processed by setattr */
664         if (la->la_valid & (LA_NLINK | LA_RDEV | LA_BLKSIZE))
665                 RETURN(-EPERM);
666
667         LASSERT(oattr != NULL);
668
669         uc = lu_ucred_check(env);
670         if (uc == NULL)
671                 RETURN(0);
672
673         if (la->la_valid == LA_CTIME) {
674                 if (!(flags & MDS_PERM_BYPASS))
675                         /* This is only for set ctime when rename's source is
676                          * on remote MDS. */
677                         rc = mdd_may_delete(env, NULL, NULL, obj, oattr, NULL,
678                                             1, 0);
679                 if (rc == 0 && la->la_ctime <= oattr->la_ctime)
680                         la->la_valid &= ~LA_CTIME;
681                 RETURN(rc);
682         }
683
684         if (la->la_valid == LA_ATIME) {
685                 /* This is an atime-only attribute update for close RPCs. */
686                 if (la->la_atime < (oattr->la_atime +
687                                 mdd_obj2mdd_dev(obj)->mdd_atime_diff))
688                         la->la_valid &= ~LA_ATIME;
689                 RETURN(0);
690         }
691
692         /* Check if flags change. */
693         if (la->la_valid & LA_FLAGS) {
694                 unsigned int oldflags = oattr->la_flags &
695                                 (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL);
696                 unsigned int newflags = la->la_flags &
697                                 (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL);
698
699                 if ((uc->uc_fsuid != oattr->la_uid) &&
700                     !md_capable(uc, CFS_CAP_FOWNER))
701                         RETURN(-EPERM);
702
703                 /* The IMMUTABLE and APPEND_ONLY flags can
704                  * only be changed by the relevant capability. */
705                 if ((oldflags ^ newflags) &&
706                     !md_capable(uc, CFS_CAP_LINUX_IMMUTABLE))
707                         RETURN(-EPERM);
708
709                 if (!S_ISDIR(oattr->la_mode))
710                         la->la_flags &= ~(LUSTRE_DIRSYNC_FL | LUSTRE_TOPDIR_FL);
711         }
712
713         if (oattr->la_flags & (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL) &&
714             (la->la_valid & ~LA_FLAGS) &&
715             !(flags & MDS_PERM_BYPASS))
716                 RETURN(-EPERM);
717
718         /* Check for setting the obj time. */
719         if ((la->la_valid & (LA_MTIME | LA_ATIME | LA_CTIME)) &&
720             !(la->la_valid & ~(LA_MTIME | LA_ATIME | LA_CTIME))) {
721                 if ((uc->uc_fsuid != oattr->la_uid) &&
722                     !md_capable(uc, CFS_CAP_FOWNER)) {
723                         rc = mdd_permission_internal(env, obj, oattr,
724                                                      MAY_WRITE);
725                         if (rc)
726                                 RETURN(rc);
727                 }
728         }
729
730         if (la->la_valid & LA_KILL_SUID) {
731                 la->la_valid &= ~LA_KILL_SUID;
732                 if ((oattr->la_mode & S_ISUID) &&
733                     !(la->la_valid & LA_MODE)) {
734                         la->la_mode = oattr->la_mode;
735                         la->la_valid |= LA_MODE;
736                 }
737                 la->la_mode &= ~S_ISUID;
738         }
739
740         if (la->la_valid & LA_KILL_SGID) {
741                 la->la_valid &= ~LA_KILL_SGID;
742                 if (((oattr->la_mode & (S_ISGID | S_IXGRP)) ==
743                         (S_ISGID | S_IXGRP)) &&
744                     !(la->la_valid & LA_MODE)) {
745                         la->la_mode = oattr->la_mode;
746                         la->la_valid |= LA_MODE;
747                 }
748                 la->la_mode &= ~S_ISGID;
749         }
750
751         /* Make sure a caller can chmod. */
752         if (la->la_valid & LA_MODE) {
753                 if (!(flags & MDS_PERM_BYPASS) &&
754                     (uc->uc_fsuid != oattr->la_uid) &&
755                     !md_capable(uc, CFS_CAP_FOWNER))
756                         RETURN(-EPERM);
757
758                 if (la->la_mode == (umode_t) -1)
759                         la->la_mode = oattr->la_mode;
760                 else
761                         la->la_mode = (la->la_mode & S_IALLUGO) |
762                                         (oattr->la_mode & ~S_IALLUGO);
763
764                 /* Also check the setgid bit! */
765                 if (!lustre_in_group_p(uc, (la->la_valid & LA_GID) ?
766                                        la->la_gid : oattr->la_gid) &&
767                     !md_capable(uc, CFS_CAP_FSETID))
768                         la->la_mode &= ~S_ISGID;
769         } else {
770                la->la_mode = oattr->la_mode;
771         }
772
773         /* Make sure a caller can chown. */
774         if (la->la_valid & LA_UID) {
775                 if (la->la_uid == (uid_t) -1)
776                         la->la_uid = oattr->la_uid;
777                 if (((uc->uc_fsuid != oattr->la_uid) ||
778                      (la->la_uid != oattr->la_uid)) &&
779                     !md_capable(uc, CFS_CAP_CHOWN))
780                         RETURN(-EPERM);
781
782                 /* If the user or group of a non-directory has been
783                  * changed by a non-root user, remove the setuid bit.
784                  * 19981026 David C Niemi <niemi@tux.org>
785                  *
786                  * Changed this to apply to all users, including root,
787                  * to avoid some races. This is the behavior we had in
788                  * 2.0. The check for non-root was definitely wrong
789                  * for 2.2 anyway, as it should have been using
790                  * CAP_FSETID rather than fsuid -- 19990830 SD. */
791                 if (((oattr->la_mode & S_ISUID) == S_ISUID) &&
792                 !S_ISDIR(oattr->la_mode)) {
793                         la->la_mode &= ~S_ISUID;
794                         la->la_valid |= LA_MODE;
795                 }
796         }
797
798         /* Make sure caller can chgrp. */
799         if (la->la_valid & LA_GID) {
800                 if (la->la_gid == (gid_t) -1)
801                         la->la_gid = oattr->la_gid;
802                 if (((uc->uc_fsuid != oattr->la_uid) ||
803                      ((la->la_gid != oattr->la_gid) &&
804                       !lustre_in_group_p(uc, la->la_gid))) &&
805                     !md_capable(uc, CFS_CAP_CHOWN))
806                         RETURN(-EPERM);
807
808                 /* Likewise, if the user or group of a non-directory
809                  * has been changed by a non-root user, remove the
810                  * setgid bit UNLESS there is no group execute bit
811                  * (this would be a file marked for mandatory
812                  * locking).  19981026 David C Niemi <niemi@tux.org>
813                  *
814                  * Removed the fsuid check (see the comment above) --
815                  * 19990830 SD. */
816                 if (((oattr->la_mode & (S_ISGID | S_IXGRP)) ==
817                     (S_ISGID | S_IXGRP)) && !S_ISDIR(oattr->la_mode)) {
818                         la->la_mode &= ~S_ISGID;
819                         la->la_valid |= LA_MODE;
820                 }
821         }
822
823         if (la->la_valid & (LA_SIZE | LA_BLOCKS)) {
824                 if (!((flags & MDS_OWNEROVERRIDE) &&
825                       (uc->uc_fsuid == oattr->la_uid)) &&
826                     !(flags & MDS_PERM_BYPASS)) {
827                         rc = mdd_permission_internal(env, obj, oattr,
828                                                      MAY_WRITE);
829                         if (rc != 0)
830                                 RETURN(rc);
831                 }
832         }
833
834         if (la->la_valid & LA_CTIME) {
835                 /* The pure setattr, it has the priority over what is
836                  * already set, do not drop it if ctime is equal. */
837                 if (la->la_ctime < oattr->la_ctime)
838                         la->la_valid &= ~(LA_ATIME | LA_MTIME | LA_CTIME);
839         }
840
841         RETURN(0);
842 }
843
844 static int mdd_changelog_data_store_by_fid(const struct lu_env *env,
845                                            struct mdd_device *mdd,
846                                            enum changelog_rec_type type,
847                                            int flags, const struct lu_fid *fid,
848                                            const char *xattr_name,
849                                            struct thandle *handle)
850 {
851         const struct lu_ucred *uc = lu_ucred(env);
852         struct llog_changelog_rec *rec;
853         struct lu_buf *buf;
854         int reclen;
855         int xflags = CLFE_INVALID;
856         int rc;
857
858         flags = (flags & CLF_FLAGMASK) | CLF_VERSION | CLF_EXTRA_FLAGS;
859
860         if (uc) {
861                 if (uc->uc_jobid[0] != '\0')
862                         flags |= CLF_JOBID;
863                 xflags |= CLFE_UIDGID;
864                 xflags |= CLFE_NID;
865         }
866         if (type == CL_OPEN || type == CL_DN_OPEN)
867                 xflags |= CLFE_OPEN;
868         if (type == CL_SETXATTR || type == CL_GETXATTR)
869                 xflags |= CLFE_XATTR;
870
871         reclen = llog_data_len(LLOG_CHANGELOG_HDR_SZ +
872                                changelog_rec_offset(flags & CLF_SUPPORTED,
873                                                     xflags & CLFE_SUPPORTED));
874         buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf, reclen);
875         if (buf->lb_buf == NULL)
876                 RETURN(-ENOMEM);
877         rec = buf->lb_buf;
878
879         rec->cr_hdr.lrh_len = reclen;
880         rec->cr.cr_flags = flags;
881         rec->cr.cr_type = (__u32)type;
882         rec->cr.cr_tfid = *fid;
883         rec->cr.cr_namelen = 0;
884
885         if (flags & CLF_JOBID)
886                 mdd_changelog_rec_ext_jobid(&rec->cr, uc->uc_jobid);
887
888         if (flags & CLF_EXTRA_FLAGS) {
889                 mdd_changelog_rec_ext_extra_flags(&rec->cr, xflags);
890                 if (xflags & CLFE_UIDGID)
891                         mdd_changelog_rec_extra_uidgid(&rec->cr,
892                                                        uc->uc_uid, uc->uc_gid);
893                 if (xflags & CLFE_NID)
894                         mdd_changelog_rec_extra_nid(&rec->cr, uc->uc_nid);
895                 if (xflags & CLFE_OPEN)
896                         mdd_changelog_rec_extra_omode(&rec->cr, flags);
897                 if (xflags & CLFE_XATTR) {
898                         if (xattr_name == NULL)
899                                 RETURN(-EINVAL);
900                         mdd_changelog_rec_extra_xattr(&rec->cr, xattr_name);
901                 }
902         }
903
904         rc = mdd_changelog_store(env, mdd, rec, handle);
905         RETURN(rc);
906 }
907
908
909 /** Store a data change changelog record
910  * If this fails, we must fail the whole transaction; we don't
911  * want the change to commit without the log entry.
912  * \param mdd_obj - mdd_object of change
913  * \param handle - transaction handle
914  */
915 int mdd_changelog_data_store(const struct lu_env *env, struct mdd_device *mdd,
916                              enum changelog_rec_type type, int flags,
917                              struct mdd_object *mdd_obj, struct thandle *handle)
918 {
919         int                              rc;
920
921         LASSERT(mdd_obj != NULL);
922         LASSERT(handle != NULL);
923
924         if (!mdd_changelog_enabled(env, mdd, type))
925                 RETURN(0);
926
927         if (mdd_is_volatile_obj(mdd_obj))
928                 RETURN(0);
929
930         if ((type >= CL_MTIME) && (type <= CL_ATIME) &&
931             ktime_before(mdd->mdd_cl.mc_starttime, mdd_obj->mod_cltime)) {
932                 /* Don't need multiple updates in this log */
933                 /* Don't check under lock - no big deal if we get an extra
934                    entry */
935                 RETURN(0);
936         }
937
938         rc = mdd_changelog_data_store_by_fid(env, mdd, type, flags,
939                                              mdo2fid(mdd_obj), NULL, handle);
940         if (rc == 0)
941                 mdd_obj->mod_cltime = ktime_get();
942
943         RETURN(rc);
944 }
945
946 int mdd_changelog_data_store_xattr(const struct lu_env *env,
947                                    struct mdd_device *mdd,
948                                    enum changelog_rec_type type,
949                                    int flags, struct mdd_object *mdd_obj,
950                                    const char *xattr_name,
951                                    struct thandle *handle)
952 {
953         int                              rc;
954
955         LASSERT(mdd_obj != NULL);
956         LASSERT(handle != NULL);
957
958         if (!mdd_changelog_enabled(env, mdd, type))
959                 RETURN(0);
960
961         if (mdd_is_volatile_obj(mdd_obj))
962                 RETURN(0);
963
964         if ((type >= CL_MTIME) && (type <= CL_ATIME) &&
965             ktime_before(mdd->mdd_cl.mc_starttime, mdd_obj->mod_cltime)) {
966                 /* Don't need multiple updates in this log */
967                 /* Don't check under lock - no big deal if we get an extra
968                  * entry
969                  */
970                 RETURN(0);
971         }
972
973         rc = mdd_changelog_data_store_by_fid(env, mdd, type, flags,
974                                              mdo2fid(mdd_obj), xattr_name,
975                                              handle);
976         if (rc == 0)
977                 mdd_obj->mod_cltime = ktime_get();
978
979         RETURN(rc);
980 }
981
982 static int mdd_changelog(const struct lu_env *env, enum changelog_rec_type type,
983                   int flags, struct md_device *m, const struct lu_fid *fid)
984 {
985         struct thandle *handle;
986         struct mdd_device *mdd = lu2mdd_dev(&m->md_lu_dev);
987         int rc;
988         ENTRY;
989
990         LASSERT(fid != NULL);
991
992         /* We'll check this again below, but we check now before we
993          * start a transaction. */
994         if (!mdd_changelog_enabled(env, mdd, type))
995                 RETURN(0);
996
997         handle = mdd_trans_create(env, mdd);
998         if (IS_ERR(handle))
999                 RETURN(PTR_ERR(handle));
1000
1001         rc = mdd_declare_changelog_store(env, mdd, type, NULL, NULL, handle);
1002         if (rc)
1003                 GOTO(stop, rc);
1004
1005         rc = mdd_trans_start(env, mdd, handle);
1006         if (rc)
1007                 GOTO(stop, rc);
1008
1009         rc = mdd_changelog_data_store_by_fid(env, mdd, type, flags,
1010                                              fid, NULL, handle);
1011
1012 stop:
1013         rc = mdd_trans_stop(env, mdd, rc, handle);
1014
1015         RETURN(rc);
1016 }
1017
1018 /**
1019  * Save LMA extended attributes with data from \a ma.
1020  *
1021  * HSM and Size-On-MDS data will be extracted from \ma if they are valid, if
1022  * not, LMA EA will be first read from disk, modified and write back.
1023  *
1024  */
1025 /* Precedence for choosing record type when multiple
1026  * attributes change: setattr > mtime > ctime > atime
1027  * (ctime changes when mtime does, plus chmod/chown.
1028  * atime and ctime are independent.) */
1029 static int mdd_attr_set_changelog(const struct lu_env *env,
1030                                   struct md_object *obj, struct thandle *handle,
1031                                   __u64 valid)
1032 {
1033         struct mdd_device *mdd = mdo2mdd(obj);
1034         int bits, type = 0;
1035
1036         bits =  (valid & LA_SIZE)  ? 1 << CL_TRUNC : 0;
1037         bits |= (valid & ~(LA_CTIME|LA_MTIME|LA_ATIME)) ? 1 << CL_SETATTR : 0;
1038         bits |= (valid & LA_MTIME) ? 1 << CL_MTIME : 0;
1039         bits |= (valid & LA_CTIME) ? 1 << CL_CTIME : 0;
1040         bits |= (valid & LA_ATIME) ? 1 << CL_ATIME : 0;
1041         bits = bits & mdd->mdd_cl.mc_mask;
1042         /* This is an implementation limit rather than a protocol limit */
1043         CLASSERT(CL_LAST <= sizeof(int) * 8);
1044         if (bits == 0)
1045                 return 0;
1046
1047         /* The record type is the lowest non-masked set bit */
1048         type = __ffs(bits);
1049
1050         /* FYI we only store the first CLF_FLAGMASK bits of la_valid */
1051         return mdd_changelog_data_store(env, mdd, type, (int)valid,
1052                                         md2mdd_obj(obj), handle);
1053 }
1054
1055 static int mdd_declare_attr_set(const struct lu_env *env,
1056                                 struct mdd_device *mdd,
1057                                 struct mdd_object *obj,
1058                                 const struct lu_attr *attr,
1059                                 struct thandle *handle)
1060 {
1061         int rc;
1062
1063         rc = mdo_declare_attr_set(env, obj, attr, handle);
1064         if (rc)
1065                 return rc;
1066
1067 #ifdef CONFIG_FS_POSIX_ACL
1068         if (attr->la_valid & LA_MODE) {
1069                 mdd_read_lock(env, obj, MOR_TGT_CHILD);
1070                 rc = mdo_xattr_get(env, obj, &LU_BUF_NULL,
1071                                    XATTR_NAME_ACL_ACCESS);
1072                 mdd_read_unlock(env, obj);
1073                 if (rc == -EOPNOTSUPP || rc == -ENODATA)
1074                         rc = 0;
1075                 else if (rc < 0)
1076                         return rc;
1077
1078                 if (rc != 0) {
1079                         struct lu_buf *buf = mdd_buf_get(env, NULL, rc);
1080                         rc = mdo_declare_xattr_set(env, obj, buf,
1081                                                    XATTR_NAME_ACL_ACCESS, 0,
1082                                                    handle);
1083                         if (rc)
1084                                 return rc;
1085                 }
1086         }
1087 #endif
1088
1089         rc = mdd_declare_changelog_store(env, mdd, CL_SETXATTR, NULL, NULL,
1090                                          handle);
1091         return rc;
1092 }
1093
1094 /*
1095  * LU-3671
1096  *
1097  * permission changes may require sync operation, to mitigate performance
1098  * impact, only do this for dir and when permission is reduced.
1099  *
1100  * For regular files, version is updated with permission change (see VBR), async
1101  * permission won't cause any issue, while missing permission change on
1102  * directory may affect accessibility of other objects after recovery.
1103  */
1104 static inline bool permission_needs_sync(const struct lu_attr *old,
1105                                          const struct lu_attr *new)
1106 {
1107         if (!S_ISDIR(old->la_mode))
1108                 return false;
1109
1110         if (new->la_valid & (LA_UID | LA_GID))
1111                 return true;
1112
1113         if (new->la_valid & LA_MODE &&
1114             new->la_mode & (S_ISUID | S_ISGID | S_ISVTX))
1115                 return true;
1116
1117         if ((new->la_valid & LA_MODE) &&
1118             ((new->la_mode & old->la_mode) & S_IRWXUGO) !=
1119              (old->la_mode & S_IRWXUGO))
1120                 return true;
1121
1122         return false;
1123 }
1124
1125 static inline __u64 mdd_lmm_dom_size(void *buf)
1126 {
1127         struct lov_mds_md *lmm = buf;
1128         struct lov_comp_md_v1 *comp_v1;
1129         struct lov_mds_md *v1;
1130         __u32 off;
1131
1132         if (lmm == NULL)
1133                 return 0;
1134
1135         if (le32_to_cpu(lmm->lmm_magic) != LOV_MAGIC_COMP_V1)
1136                 return 0;
1137
1138         comp_v1 = (struct lov_comp_md_v1 *)lmm;
1139         off = le32_to_cpu(comp_v1->lcm_entries[0].lcme_offset);
1140         v1 = (struct lov_mds_md *)((char *)comp_v1 + off);
1141
1142         /* DoM entry is the first entry always */
1143         if (lov_pattern(le32_to_cpu(v1->lmm_pattern)) == LOV_PATTERN_MDT)
1144                 return le64_to_cpu(comp_v1->lcm_entries[0].lcme_extent.e_end);
1145
1146         return 0;
1147 }
1148
1149 /* set attr and LOV EA at once, return updated attr */
1150 int mdd_attr_set(const struct lu_env *env, struct md_object *obj,
1151                  const struct md_attr *ma)
1152 {
1153         struct mdd_object *mdd_obj = md2mdd_obj(obj);
1154         struct mdd_device *mdd = mdo2mdd(obj);
1155         struct thandle *handle = NULL;
1156         struct lu_attr *la_copy = &mdd_env_info(env)->mti_la_for_fix;
1157         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
1158         const struct lu_attr *la = &ma->ma_attr;
1159         struct lu_ucred  *uc;
1160         int rc;
1161         ENTRY;
1162
1163         /* we do not use ->attr_set() for LOV/HSM EA any more */
1164         LASSERT((ma->ma_valid & MA_LOV) == 0);
1165         LASSERT((ma->ma_valid & MA_HSM) == 0);
1166
1167         rc = mdd_la_get(env, mdd_obj, attr);
1168         if (rc)
1169                 RETURN(rc);
1170
1171         *la_copy = ma->ma_attr;
1172         rc = mdd_fix_attr(env, mdd_obj, attr, la_copy, ma->ma_attr_flags);
1173         if (rc)
1174                 RETURN(rc);
1175
1176         /* no need to setattr anymore */
1177         if (la_copy->la_valid == 0) {
1178                 CDEBUG(D_INODE, "%s: no valid attribute on "DFID", previous"
1179                        "valid is %#llx\n", mdd2obd_dev(mdd)->obd_name,
1180                        PFID(mdo2fid(mdd_obj)), la->la_valid);
1181
1182                 RETURN(0);
1183         }
1184
1185         /* If an unprivileged user changes group of some file,
1186          * the setattr operation will be processed synchronously to
1187          * honor the quota limit of the corresponding group. see LU-5152 */
1188         uc = lu_ucred_check(env);
1189         if (S_ISREG(attr->la_mode) && la->la_valid & LA_GID &&
1190             la->la_gid != attr->la_gid && uc != NULL && uc->uc_fsuid != 0) {
1191                 la_copy->la_valid |= LA_FLAGS;
1192                 la_copy->la_flags |= LUSTRE_SET_SYNC_FL;
1193
1194                 /* Flush the possible existing sync requests to OSTs to
1195                  * keep the order of sync for the current setattr operation
1196                  * will be sent directly to OSTs. see LU-5152 */
1197                 rc = dt_sync(env, mdd->mdd_child);
1198                 if (rc)
1199                         GOTO(out, rc);
1200         }
1201
1202         handle = mdd_trans_create(env, mdd);
1203         if (IS_ERR(handle)) {
1204                 rc = PTR_ERR(handle);
1205                 handle = NULL;
1206
1207                 GOTO(out, rc);
1208         }
1209
1210         rc = mdd_declare_attr_set(env, mdd, mdd_obj, la_copy, handle);
1211         if (rc)
1212                 GOTO(out, rc);
1213
1214         rc = mdd_trans_start(env, mdd, handle);
1215         if (rc)
1216                 GOTO(out, rc);
1217
1218         if (mdd->mdd_sync_permission && permission_needs_sync(attr, la))
1219                 handle->th_sync = 1;
1220
1221         if (la->la_valid & (LA_MTIME | LA_CTIME))
1222                 CDEBUG(D_INODE, "setting mtime %llu, ctime %llu\n",
1223                        la->la_mtime, la->la_ctime);
1224
1225         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
1226
1227         /* LU-10509: setattr of LA_SIZE should be skipped case of DOM,
1228          * otherwise following truncate will do nothing and truncated
1229          * data may be read again. This is a quick fix until LU-11033
1230          * will be resolved.
1231          */
1232         if (la_copy->la_valid & LA_SIZE) {
1233                 struct lu_buf *lov_buf = mdd_buf_get(env, NULL, 0);
1234
1235                 rc = mdd_stripe_get(env, mdd_obj, lov_buf, XATTR_NAME_LOV);
1236                 if (rc) {
1237                         rc = 0;
1238                 } else {
1239                         if (mdd_lmm_dom_size(lov_buf->lb_buf) > 0)
1240                                 la_copy->la_valid &= ~LA_SIZE;
1241                         lu_buf_free(lov_buf);
1242                 }
1243         }
1244
1245         if (la_copy->la_valid) {
1246                 rc = mdd_attr_set_internal(env, mdd_obj, la_copy, handle, 1);
1247
1248                 if (rc == -EDQUOT && la_copy->la_flags & LUSTRE_SET_SYNC_FL) {
1249                         /* rollback to the original gid */
1250                         la_copy->la_flags &= ~LUSTRE_SET_SYNC_FL;
1251                         la_copy->la_gid = attr->la_gid;
1252                         mdd_attr_set_internal(env, mdd_obj, la_copy, handle, 1);
1253                 }
1254         }
1255         mdd_write_unlock(env, mdd_obj);
1256
1257 out:
1258         if (rc == 0)
1259                 rc = mdd_attr_set_changelog(env, obj, handle,
1260                                             la_copy->la_valid);
1261
1262         if (handle != NULL)
1263                 rc = mdd_trans_stop(env, mdd, rc, handle);
1264
1265         return rc;
1266 }
1267
1268 static int mdd_xattr_sanity_check(const struct lu_env *env,
1269                                   struct mdd_object *obj,
1270                                   const struct lu_attr *attr,
1271                                   const char *name)
1272 {
1273         struct lu_ucred *uc     = lu_ucred_assert(env);
1274         ENTRY;
1275
1276         if (attr->la_flags & (LUSTRE_IMMUTABLE_FL | LUSTRE_APPEND_FL))
1277                 RETURN(-EPERM);
1278
1279         if (strncmp(XATTR_USER_PREFIX, name,
1280                     sizeof(XATTR_USER_PREFIX) - 1) == 0) {
1281                 /* For sticky directories, only the owner and privileged user
1282                  * can write attributes. */
1283                 if (S_ISDIR(attr->la_mode) && (attr->la_mode & S_ISVTX) &&
1284                     (uc->uc_fsuid != attr->la_uid) &&
1285                     !md_capable(uc, CFS_CAP_FOWNER))
1286                         RETURN(-EPERM);
1287         } else if (strcmp(name, XATTR_NAME_SOM) != 0 &&
1288                    (uc->uc_fsuid != attr->la_uid) &&
1289                    !md_capable(uc, CFS_CAP_FOWNER)) {
1290                 RETURN(-EPERM);
1291         }
1292
1293         RETURN(0);
1294 }
1295
1296 /**
1297  * Check if a string begins with a given prefix.
1298  *
1299  * \param str     String to check
1300  * \param prefix  Substring to check at the beginning of \a str
1301  * \return true/false whether the condition is verified.
1302  */
1303 static inline bool has_prefix(const char *str, const char *prefix)
1304 {
1305         return strncmp(prefix, str, strlen(prefix)) == 0;
1306 }
1307
1308 /**
1309  * Indicate the kind of changelog to store (if any) for a xattr set/del.
1310  *
1311  * \param[in]  xattr_name  Full extended attribute name.
1312  *
1313  * \return The type of changelog to use, or -1 if no changelog is to be emitted.
1314  */
1315 static enum changelog_rec_type
1316 mdd_xattr_changelog_type(const struct lu_env *env, struct mdd_device *mdd,
1317                          const char *xattr_name)
1318 {
1319         /* Layout changes systematically recorded */
1320         if (strcmp(XATTR_NAME_LOV, xattr_name) == 0 ||
1321             strncmp(XATTR_LUSTRE_LOV, xattr_name,
1322                     strlen(XATTR_LUSTRE_LOV)) == 0)
1323                 return CL_LAYOUT;
1324
1325         /* HSM information changes systematically recorded */
1326         if (strcmp(XATTR_NAME_HSM, xattr_name) == 0)
1327                 return CL_HSM;
1328
1329         /* Avoid logging SOM xattr for every file */
1330         if (strcmp(XATTR_NAME_SOM, xattr_name) == 0)
1331                 return CL_NONE;
1332
1333         if (has_prefix(xattr_name, XATTR_USER_PREFIX) ||
1334             has_prefix(xattr_name, XATTR_NAME_POSIX_ACL_ACCESS) ||
1335             has_prefix(xattr_name, XATTR_NAME_POSIX_ACL_DEFAULT) ||
1336             has_prefix(xattr_name, XATTR_TRUSTED_PREFIX) ||
1337             has_prefix(xattr_name, XATTR_SECURITY_PREFIX))
1338                 return CL_SETXATTR;
1339
1340         return CL_NONE;
1341 }
1342
1343 static int mdd_declare_xattr_set(const struct lu_env *env,
1344                                  struct mdd_device *mdd,
1345                                  struct mdd_object *obj,
1346                                  const struct lu_buf *buf,
1347                                  const char *name,
1348                                  int fl, struct thandle *handle)
1349 {
1350         enum changelog_rec_type type;
1351         int rc;
1352
1353         rc = mdo_declare_xattr_set(env, obj, buf, name, fl, handle);
1354         if (rc)
1355                 return rc;
1356
1357         type = mdd_xattr_changelog_type(env, mdd, name);
1358         if (type < 0)
1359                 return 0; /* no changelog to store */
1360
1361         return mdd_declare_changelog_store(env, mdd, type, NULL, NULL, handle);
1362 }
1363
1364 /*
1365  * Compare current and future data of HSM EA and add a changelog if needed.
1366  *
1367  * Caller should have write-locked \param obj.
1368  *
1369  * \param buf - Future HSM EA content.
1370  * \retval 0 if no changelog is needed or changelog was added properly.
1371  * \retval -ve errno if there was a problem
1372  */
1373 static int mdd_hsm_update_locked(const struct lu_env *env,
1374                                  struct md_object *obj,
1375                                  const struct lu_buf *buf,
1376                                  struct thandle *handle, int *cl_flags)
1377 {
1378         struct mdd_thread_info *info = mdd_env_info(env);
1379         struct mdd_object      *mdd_obj = md2mdd_obj(obj);
1380         struct lu_buf          *current_buf;
1381         struct md_hsm          *current_mh;
1382         struct md_hsm          *new_mh;
1383         int                     rc;
1384         ENTRY;
1385
1386         OBD_ALLOC_PTR(current_mh);
1387         if (current_mh == NULL)
1388                 RETURN(-ENOMEM);
1389
1390         /* Read HSM attrs from disk */
1391         current_buf = lu_buf_check_and_alloc(&info->mti_xattr_buf,
1392                                 mdo2mdd(obj)->mdd_dt_conf.ddp_max_ea_size);
1393         rc = mdo_xattr_get(env, mdd_obj, current_buf, XATTR_NAME_HSM);
1394         rc = lustre_buf2hsm(current_buf->lb_buf, rc, current_mh);
1395         if (rc < 0 && rc != -ENODATA)
1396                 GOTO(free, rc);
1397         else if (rc == -ENODATA)
1398                 current_mh->mh_flags = 0;
1399
1400         /* Map future HSM xattr */
1401         OBD_ALLOC_PTR(new_mh);
1402         if (new_mh == NULL)
1403                 GOTO(free, rc = -ENOMEM);
1404         lustre_buf2hsm(buf->lb_buf, buf->lb_len, new_mh);
1405
1406         rc = 0;
1407
1408         /* Flags differ, set flags for the changelog that will be added */
1409         if (current_mh->mh_flags != new_mh->mh_flags) {
1410                 hsm_set_cl_event(cl_flags, HE_STATE);
1411                 if (new_mh->mh_flags & HS_DIRTY)
1412                         hsm_set_cl_flags(cl_flags, CLF_HSM_DIRTY);
1413         }
1414
1415         OBD_FREE_PTR(new_mh);
1416         EXIT;
1417 free:
1418         OBD_FREE_PTR(current_mh);
1419         return rc;
1420 }
1421
1422 static int mdd_object_pfid_replace(const struct lu_env *env,
1423                                    struct mdd_object *o)
1424 {
1425         struct mdd_device *mdd = mdo2mdd(&o->mod_obj);
1426         struct thandle *handle;
1427         int rc;
1428
1429         handle = mdd_trans_create(env, mdd);
1430         if (IS_ERR(handle))
1431                 RETURN(PTR_ERR(handle));
1432
1433         handle->th_complex = 1;
1434
1435         /* it doesn't need to track the PFID update via llog, because LFSCK
1436          * will repair it even it goes wrong */
1437         rc = mdd_declare_xattr_set(env, mdd, o, NULL, XATTR_NAME_FID,
1438                                    0, handle);
1439         if (rc)
1440                 GOTO(out, rc);
1441
1442         rc = mdd_trans_start(env, mdd, handle);
1443         if (rc != 0)
1444                 GOTO(out, rc);
1445
1446         rc = mdo_xattr_set(env, o, NULL, XATTR_NAME_FID, 0, handle);
1447         if (rc)
1448                 GOTO(out, rc);
1449
1450 out:
1451         mdd_trans_stop(env, mdd, rc, handle);
1452         return rc;
1453 }
1454
1455
1456 static int mdd_declare_xattr_del(const struct lu_env *env,
1457                                  struct mdd_device *mdd,
1458                                  struct mdd_object *obj,
1459                                  const char *name,
1460                                  struct thandle *handle);
1461
1462 static int mdd_xattr_del(const struct lu_env *env, struct md_object *obj,
1463                          const char *name);
1464
1465 static int mdd_xattr_merge(const struct lu_env *env, struct md_object *md_obj,
1466                            struct md_object *md_vic)
1467 {
1468         struct mdd_device *mdd = mdo2mdd(md_obj);
1469         struct mdd_object *obj = md2mdd_obj(md_obj);
1470         struct mdd_object *vic = md2mdd_obj(md_vic);
1471         struct lu_buf *buf = &mdd_env_info(env)->mti_buf[0];
1472         struct lu_buf *buf_vic = &mdd_env_info(env)->mti_buf[1];
1473         struct lov_mds_md *lmm;
1474         struct thandle *handle;
1475         int rc;
1476         ENTRY;
1477
1478         rc = lu_fid_cmp(mdo2fid(obj), mdo2fid(vic));
1479         if (rc == 0) /* same fid */
1480                 RETURN(-EPERM);
1481
1482         handle = mdd_trans_create(env, mdd);
1483         if (IS_ERR(handle))
1484                 RETURN(PTR_ERR(handle));
1485
1486         if (rc > 0) {
1487                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1488                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1489         } else {
1490                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1491                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1492         }
1493
1494         /* get EA of victim file */
1495         memset(buf_vic, 0, sizeof(*buf_vic));
1496         rc = mdd_stripe_get(env, vic, buf_vic, XATTR_NAME_LOV);
1497         if (rc < 0) {
1498                 if (rc == -ENODATA)
1499                         rc = 0;
1500                 GOTO(out, rc);
1501         }
1502
1503         /* parse the layout of victim file */
1504         lmm = buf_vic->lb_buf;
1505         if (le32_to_cpu(lmm->lmm_magic) != LOV_MAGIC_COMP_V1)
1506                 GOTO(out, rc = -EINVAL);
1507
1508         /* save EA of target file for restore */
1509         memset(buf, 0, sizeof(*buf));
1510         rc = mdd_stripe_get(env, obj, buf, XATTR_NAME_LOV);
1511         if (rc < 0)
1512                 GOTO(out, rc);
1513
1514         /* Get rid of the layout from victim object */
1515         rc = mdd_declare_xattr_del(env, mdd, vic, XATTR_NAME_LOV, handle);
1516         if (rc)
1517                 GOTO(out, rc);
1518
1519         rc = mdd_declare_xattr_set(env, mdd, obj, buf_vic, XATTR_LUSTRE_LOV,
1520                                    LU_XATTR_MERGE, handle);
1521         if (rc)
1522                 GOTO(out, rc);
1523
1524         rc = mdd_trans_start(env, mdd, handle);
1525         if (rc != 0)
1526                 GOTO(out, rc);
1527
1528         rc = mdo_xattr_set(env, obj, buf_vic, XATTR_LUSTRE_LOV, LU_XATTR_MERGE,
1529                            handle);
1530         if (rc)
1531                 GOTO(out, rc);
1532
1533         rc = mdo_xattr_del(env, vic, XATTR_NAME_LOV, handle);
1534         if (rc) /* wtf? */
1535                 GOTO(out_restore, rc);
1536
1537         (void)mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, obj, handle);
1538         (void)mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, vic, handle);
1539         EXIT;
1540
1541 out_restore:
1542         if (rc) {
1543                 int rc2 = mdo_xattr_set(env, obj, buf, XATTR_NAME_LOV,
1544                                         LU_XATTR_REPLACE, handle);
1545                 if (rc2)
1546                         CERROR("%s: failed to rollback of layout of: "DFID
1547                                ": %d, file state unknown\n",
1548                                mdd_obj_dev_name(obj), PFID(mdo2fid(obj)), rc2);
1549         }
1550
1551 out:
1552         mdd_trans_stop(env, mdd, rc, handle);
1553         mdd_write_unlock(env, obj);
1554         mdd_write_unlock(env, vic);
1555         lu_buf_free(buf);
1556         lu_buf_free(buf_vic);
1557
1558         if (!rc)
1559                 (void) mdd_object_pfid_replace(env, obj);
1560
1561         return rc;
1562 }
1563
1564 /**
1565  * Extract the mirror with specified mirror id, and store the splitted
1566  * mirror layout to @buf.
1567  *
1568  * \param[in] comp_v1   mirrored layout
1569  * \param[in] mirror_id the mirror with mirror_id to be extracted
1570  * \param[out] buf      store the layout excluding the extracted mirror,
1571  *                      caller free the buffer we allocated in this function
1572  * \param[out] buf_vic  store the extracted layout, caller free the buffer
1573  *                      we allocated in this function
1574  *
1575  * \retval      0 on success; < 0 if error happens
1576  */
1577 static int mdd_split_ea(struct lov_comp_md_v1 *comp_v1, __u16 mirror_id,
1578                         struct lu_buf *buf, struct lu_buf *buf_vic)
1579 {
1580         struct lov_comp_md_v1 *comp_rem;
1581         struct lov_comp_md_v1 *comp_vic;
1582         struct lov_comp_md_entry_v1 *entry;
1583         struct lov_comp_md_entry_v1 *entry_rem;
1584         struct lov_comp_md_entry_v1 *entry_vic;
1585         __u16 mirror_cnt;
1586         __u16 comp_cnt, count = 0;
1587         int lmm_size, lmm_size_vic = 0;
1588         int i, j, k;
1589         int offset, offset_rem, offset_vic;
1590
1591         mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1592         /* comp_v1 should contains more than 1 mirror */
1593         if (mirror_cnt <= 1)
1594                 return -EINVAL;
1595         comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1596         lmm_size = le32_to_cpu(comp_v1->lcm_size);
1597
1598         for (i = 0; i < comp_cnt; i++) {
1599                 entry = &comp_v1->lcm_entries[i];
1600                 if (mirror_id_of(le32_to_cpu(entry->lcme_id)) == mirror_id) {
1601                         count++;
1602                         lmm_size_vic += sizeof(*entry);
1603                         lmm_size_vic += le32_to_cpu(entry->lcme_size);
1604                 } else if (count > 0) {
1605                         /* find the specified mirror */
1606                         break;
1607                 }
1608         }
1609
1610         if (count == 0)
1611                 return -EINVAL;
1612
1613         lu_buf_alloc(buf, lmm_size - lmm_size_vic);
1614         if (!buf->lb_buf)
1615                 return -ENOMEM;
1616
1617         lu_buf_alloc(buf_vic, sizeof(*comp_vic) + lmm_size_vic);
1618         if (!buf_vic->lb_buf) {
1619                 lu_buf_free(buf);
1620                 return -ENOMEM;
1621         }
1622
1623         comp_rem = (struct lov_comp_md_v1 *)buf->lb_buf;
1624         comp_vic = (struct lov_comp_md_v1 *)buf_vic->lb_buf;
1625
1626         memcpy(comp_rem, comp_v1, sizeof(*comp_v1));
1627         comp_rem->lcm_mirror_count = cpu_to_le16(mirror_cnt - 2);
1628         comp_rem->lcm_entry_count = cpu_to_le32(comp_cnt - count);
1629         comp_rem->lcm_size = cpu_to_le32(lmm_size - lmm_size_vic);
1630         if (!comp_rem->lcm_mirror_count)
1631                 comp_rem->lcm_flags = cpu_to_le16(LCM_FL_NONE);
1632
1633         memset(comp_vic, 0, sizeof(*comp_v1));
1634         comp_vic->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
1635         comp_vic->lcm_mirror_count = 0;
1636         comp_vic->lcm_entry_count = cpu_to_le32(count);
1637         comp_vic->lcm_size = cpu_to_le32(lmm_size_vic + sizeof(*comp_vic));
1638         comp_vic->lcm_flags = cpu_to_le16(LCM_FL_NONE);
1639         comp_vic->lcm_layout_gen = 0;
1640
1641         offset = sizeof(*comp_v1) + sizeof(*entry) * comp_cnt;
1642         offset_rem = sizeof(*comp_rem) +
1643                      sizeof(*entry_rem) * (comp_cnt - count);
1644         offset_vic = sizeof(*comp_vic) + sizeof(*entry_vic) * count;
1645         for (i = j = k = 0; i < comp_cnt; i++) {
1646                 struct lov_mds_md *lmm, *lmm_dst;
1647                 bool vic = false;
1648
1649                 entry = &comp_v1->lcm_entries[i];
1650                 entry_vic = &comp_vic->lcm_entries[j];
1651                 entry_rem = &comp_rem->lcm_entries[k];
1652
1653                 if (mirror_id_of(le32_to_cpu(entry->lcme_id)) == mirror_id)
1654                         vic = true;
1655
1656                 /* copy component entry */
1657                 if (vic) {
1658                         memcpy(entry_vic, entry, sizeof(*entry));
1659                         entry_vic->lcme_flags &= cpu_to_le32(LCME_FL_INIT);
1660                         entry_vic->lcme_offset = cpu_to_le32(offset_vic);
1661                         j++;
1662                 } else {
1663                         memcpy(entry_rem, entry, sizeof(*entry));
1664                         entry_rem->lcme_offset = cpu_to_le32(offset_rem);
1665                         k++;
1666                 }
1667
1668                 lmm = (struct lov_mds_md *)((char *)comp_v1 + offset);
1669                 if (vic)
1670                         lmm_dst = (struct lov_mds_md *)
1671                                         ((char *)comp_vic + offset_vic);
1672                 else
1673                         lmm_dst = (struct lov_mds_md *)
1674                                         ((char *)comp_rem + offset_rem);
1675
1676                 /* copy component entry blob */
1677                 memcpy(lmm_dst, lmm, le32_to_cpu(entry->lcme_size));
1678
1679                 /* blob offset advance */
1680                 offset += le32_to_cpu(entry->lcme_size);
1681                 if (vic)
1682                         offset_vic += le32_to_cpu(entry->lcme_size);
1683                 else
1684                         offset_rem += le32_to_cpu(entry->lcme_size);
1685         }
1686
1687         return 0;
1688 }
1689
1690 static int mdd_xattr_split(const struct lu_env *env, struct md_object *md_obj,
1691                            struct md_rejig_data *mrd)
1692 {
1693         struct mdd_device *mdd = mdo2mdd(md_obj);
1694         struct mdd_object *obj = md2mdd_obj(md_obj);
1695         struct mdd_object *vic = md2mdd_obj(mrd->mrd_obj);
1696         struct lu_buf *buf = &mdd_env_info(env)->mti_buf[0];
1697         struct lu_buf *buf_save = &mdd_env_info(env)->mti_buf[1];
1698         struct lu_buf *buf_vic = &mdd_env_info(env)->mti_buf[2];
1699         struct lov_comp_md_v1 *lcm;
1700         struct thandle *handle;
1701         int rc;
1702         ENTRY;
1703
1704         rc = lu_fid_cmp(mdo2fid(obj), mdo2fid(vic));
1705         if (rc == 0) /* same fid */
1706                 RETURN(-EPERM);
1707
1708         handle = mdd_trans_create(env, mdd);
1709         if (IS_ERR(handle))
1710                 RETURN(PTR_ERR(handle));
1711
1712         if (rc > 0) {
1713                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1714                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1715         } else {
1716                 mdd_write_lock(env, vic, MOR_TGT_CHILD);
1717                 mdd_write_lock(env, obj, MOR_TGT_CHILD);
1718         }
1719
1720         /* get EA of mirrored file */
1721         memset(buf_save, 0, sizeof(*buf));
1722         rc = mdd_stripe_get(env, obj, buf_save, XATTR_NAME_LOV);
1723         if (rc < 0)
1724                 GOTO(out, rc);
1725
1726         lcm = buf_save->lb_buf;
1727         if (le32_to_cpu(lcm->lcm_magic) != LOV_MAGIC_COMP_V1)
1728                 GOTO(out, rc = -EINVAL);
1729
1730         /**
1731          * Extract the mirror with specified mirror id, and store the splitted
1732          * mirror layout to the victim file.
1733          */
1734         memset(buf, 0, sizeof(*buf));
1735         memset(buf_vic, 0, sizeof(*buf_vic));
1736         rc = mdd_split_ea(lcm, mrd->mrd_mirror_id, buf, buf_vic);
1737         if (rc < 0)
1738                 GOTO(out, rc);
1739
1740         rc = mdd_declare_xattr_set(env, mdd, obj, buf, XATTR_NAME_LOV,
1741                                    LU_XATTR_SPLIT, handle);
1742         if (rc)
1743                 GOTO(out, rc);
1744         rc = mdd_declare_xattr_set(env, mdd, vic, buf_vic, XATTR_NAME_LOV,
1745                                    LU_XATTR_SPLIT, handle);
1746         if (rc)
1747                 GOTO(out, rc);
1748
1749         rc = mdd_trans_start(env, mdd, handle);
1750         if (rc)
1751                 GOTO(out, rc);
1752
1753         rc = mdo_xattr_set(env, obj, buf, XATTR_NAME_LOV, LU_XATTR_REPLACE,
1754                            handle);
1755         if (rc)
1756                 GOTO(out, rc);
1757
1758         rc = mdo_xattr_set(env, vic, buf_vic, XATTR_NAME_LOV, LU_XATTR_CREATE,
1759                            handle);
1760         if (rc)
1761                 GOTO(out_restore, rc);
1762
1763         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, obj, handle);
1764         if (rc)
1765                 GOTO(out, rc);
1766
1767         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, vic, handle);
1768         if (rc)
1769                 GOTO(out, rc);
1770         EXIT;
1771
1772 out_restore:
1773         if (rc) {
1774                 /* restore obj's layout */
1775                 int rc2 = mdo_xattr_set(env, obj, buf_save, XATTR_NAME_LOV,
1776                                         LU_XATTR_REPLACE, handle);
1777                 if (rc2)
1778                         CERROR("%s: failed to rollback of layout of: "DFID
1779                                ": %d, file state unkonwn.\n",
1780                                mdd_obj_dev_name(obj), PFID(mdo2fid(obj)), rc2);
1781         }
1782 out:
1783         mdd_trans_stop(env, mdd, rc, handle);
1784         mdd_write_unlock(env, obj);
1785         mdd_write_unlock(env, vic);
1786         lu_buf_free(buf_save);
1787         lu_buf_free(buf);
1788         lu_buf_free(buf_vic);
1789
1790         if (!rc)
1791                 (void) mdd_object_pfid_replace(env, obj);
1792
1793         return rc;
1794 }
1795
1796 static int mdd_layout_merge_allowed(const struct lu_env *env,
1797                                     struct md_object *target,
1798                                     struct md_object *victim)
1799 {
1800         struct mdd_object *o1 = md2mdd_obj(target);
1801
1802         /* cannot extend directory's LOVEA */
1803         if (S_ISDIR(mdd_object_type(o1))) {
1804                 CERROR("%s: Don't extend directory's LOVEA, just set it.\n",
1805                        mdd_obj_dev_name(o1));
1806                 RETURN(-EISDIR);
1807         }
1808
1809         RETURN(0);
1810 }
1811
1812 /**
1813  * The caller should guarantee to update the object ctime
1814  * after xattr_set if needed.
1815  */
1816 static int mdd_xattr_set(const struct lu_env *env, struct md_object *obj,
1817                          const struct lu_buf *buf, const char *name,
1818                          int fl)
1819 {
1820         struct mdd_object       *mdd_obj = md2mdd_obj(obj);
1821         struct lu_attr          *attr = MDD_ENV_VAR(env, cattr);
1822         struct mdd_device       *mdd = mdo2mdd(obj);
1823         struct thandle          *handle;
1824         enum changelog_rec_type  cl_type;
1825         int                      cl_flags = 0;
1826         int                      rc;
1827         ENTRY;
1828
1829         rc = mdd_la_get(env, mdd_obj, attr);
1830         if (rc)
1831                 RETURN(rc);
1832
1833         rc = mdd_xattr_sanity_check(env, mdd_obj, attr, name);
1834         if (rc)
1835                 RETURN(rc);
1836
1837         if (strcmp(name, XATTR_LUSTRE_LOV) == 0 &&
1838             (fl == LU_XATTR_MERGE || fl == LU_XATTR_SPLIT)) {
1839                 struct md_rejig_data *mrd = buf->lb_buf;
1840                 struct md_object *victim = mrd->mrd_obj;
1841
1842                 if (buf->lb_len != sizeof(*mrd))
1843                         RETURN(-EINVAL);
1844
1845                 rc = mdd_layout_merge_allowed(env, obj, victim);
1846                 if (rc)
1847                         RETURN(rc);
1848
1849                 if (fl == LU_XATTR_MERGE)
1850                         /* merge layout of victim as a mirror of obj's. */
1851                         rc = mdd_xattr_merge(env, obj, victim);
1852                 else
1853                         rc = mdd_xattr_split(env, obj, mrd);
1854                 RETURN(rc);
1855         }
1856
1857         if (strcmp(name, XATTR_NAME_LMV) == 0) {
1858                 rc = mdd_dir_layout_shrink(env, obj, buf);
1859                 RETURN(rc);
1860         }
1861
1862         if (strcmp(name, XATTR_NAME_ACL_ACCESS) == 0 ||
1863             strcmp(name, XATTR_NAME_ACL_DEFAULT) == 0) {
1864                 struct posix_acl *acl;
1865
1866                 /* user may set empty ACL, which should be treated as removing
1867                  * ACL. */
1868                 acl = posix_acl_from_xattr(&init_user_ns, buf->lb_buf,
1869                                            buf->lb_len);
1870                 if (IS_ERR(acl))
1871                         RETURN(PTR_ERR(acl));
1872                 if (acl == NULL) {
1873                         rc = mdd_xattr_del(env, obj, name);
1874                         RETURN(rc);
1875                 }
1876                 posix_acl_release(acl);
1877         }
1878
1879         if (!strcmp(name, XATTR_NAME_ACL_ACCESS)) {
1880                 rc = mdd_acl_set(env, mdd_obj, attr, buf, fl);
1881                 RETURN(rc);
1882         }
1883
1884         handle = mdd_trans_create(env, mdd);
1885         if (IS_ERR(handle))
1886                 RETURN(PTR_ERR(handle));
1887
1888         rc = mdd_declare_xattr_set(env, mdd, mdd_obj, buf, name, fl, handle);
1889         if (rc)
1890                 GOTO(stop, rc);
1891
1892         rc = mdd_trans_start(env, mdd, handle);
1893         if (rc)
1894                 GOTO(stop, rc);
1895
1896         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
1897
1898         if (strcmp(XATTR_NAME_HSM, name) == 0) {
1899                 rc = mdd_hsm_update_locked(env, obj, buf, handle, &cl_flags);
1900                 if (rc) {
1901                         mdd_write_unlock(env, mdd_obj);
1902                         GOTO(stop, rc);
1903                 }
1904         }
1905
1906         rc = mdo_xattr_set(env, mdd_obj, buf, name, fl, handle);
1907         mdd_write_unlock(env, mdd_obj);
1908         if (rc)
1909                 GOTO(stop, rc);
1910
1911         cl_type = mdd_xattr_changelog_type(env, mdd, name);
1912         if (cl_type < 0)
1913                 GOTO(stop, rc = 0);
1914
1915         rc = mdd_changelog_data_store_xattr(env, mdd, cl_type, cl_flags,
1916                                             mdd_obj, name, handle);
1917
1918         EXIT;
1919 stop:
1920         return mdd_trans_stop(env, mdd, rc, handle);
1921 }
1922
1923 static int mdd_declare_xattr_del(const struct lu_env *env,
1924                                  struct mdd_device *mdd,
1925                                  struct mdd_object *obj,
1926                                  const char *name,
1927                                  struct thandle *handle)
1928 {
1929         enum changelog_rec_type type;
1930         int rc;
1931
1932         rc = mdo_declare_xattr_del(env, obj, name, handle);
1933         if (rc)
1934                 return rc;
1935
1936         type = mdd_xattr_changelog_type(env, mdd, name);
1937         if (type < 0)
1938                 return 0; /* no changelog to store */
1939
1940         return mdd_declare_changelog_store(env, mdd, type, NULL, NULL, handle);
1941 }
1942
1943 /**
1944  * The caller should guarantee to update the object ctime
1945  * after xattr_set if needed.
1946  */
1947 static int mdd_xattr_del(const struct lu_env *env, struct md_object *obj,
1948                          const char *name)
1949 {
1950         struct mdd_object *mdd_obj = md2mdd_obj(obj);
1951         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
1952         struct mdd_device *mdd = mdo2mdd(obj);
1953         struct thandle *handle;
1954         int rc;
1955         ENTRY;
1956
1957         rc = mdd_la_get(env, mdd_obj, attr);
1958         if (rc)
1959                 RETURN(rc);
1960
1961         rc = mdd_xattr_sanity_check(env, mdd_obj, attr, name);
1962         if (rc)
1963                 RETURN(rc);
1964
1965         handle = mdd_trans_create(env, mdd);
1966         if (IS_ERR(handle))
1967                 RETURN(PTR_ERR(handle));
1968
1969         rc = mdd_declare_xattr_del(env, mdd, mdd_obj, name, handle);
1970         if (rc)
1971                 GOTO(stop, rc);
1972
1973         rc = mdd_trans_start(env, mdd, handle);
1974         if (rc)
1975                 GOTO(stop, rc);
1976
1977         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
1978         rc = mdo_xattr_del(env, mdd_obj, name, handle);
1979         mdd_write_unlock(env, mdd_obj);
1980         if (rc)
1981                 GOTO(stop, rc);
1982
1983         if (mdd_xattr_changelog_type(env, mdd, name) < 0)
1984                 GOTO(stop, rc = 0);
1985
1986         rc = mdd_changelog_data_store_xattr(env, mdd, CL_SETXATTR, 0, mdd_obj,
1987                                             name, handle);
1988
1989         EXIT;
1990 stop:
1991         return mdd_trans_stop(env, mdd, rc, handle);
1992 }
1993
1994 /*
1995  * read lov/lmv EA of an object
1996  * return the lov/lmv EA in an allocated lu_buf
1997  */
1998 int mdd_stripe_get(const struct lu_env *env, struct mdd_object *obj,
1999                    struct lu_buf *lmm_buf, const char *name)
2000 {
2001         struct lu_buf *buf = &mdd_env_info(env)->mti_big_buf;
2002         int rc;
2003
2004         ENTRY;
2005
2006         if (buf->lb_buf == NULL) {
2007                 buf = lu_buf_check_and_alloc(buf, 4096);
2008                 if (buf->lb_buf == NULL)
2009                         RETURN(-ENOMEM);
2010         }
2011
2012 repeat:
2013         rc = mdo_xattr_get(env, obj, buf, name);
2014         if (rc == -ERANGE) {
2015                 /* mti_big_buf is allocated but is too small
2016                  * we need to increase it */
2017                 buf = lu_buf_check_and_alloc(&mdd_env_info(env)->mti_big_buf,
2018                                              buf->lb_len * 2);
2019                 if (buf->lb_buf == NULL)
2020                         RETURN(-ENOMEM);
2021                 goto repeat;
2022         } else if (rc < 0) {
2023                 RETURN(rc);
2024         } else if (rc == 0) {
2025                 RETURN(-ENODATA);
2026         }
2027
2028         lu_buf_alloc(lmm_buf, rc);
2029         if (lmm_buf->lb_buf == NULL)
2030                 RETURN(-ENOMEM);
2031
2032         /*
2033          * we don't use lmm_buf directly, because we don't know xattr size, so
2034          * by using mti_big_buf we can avoid calling mdo_xattr_get() twice.
2035          */
2036         memcpy(lmm_buf->lb_buf, buf->lb_buf, rc);
2037
2038         RETURN(0);
2039 }
2040
2041 static int mdd_xattr_hsm_replace(const struct lu_env *env,
2042                                  struct mdd_object *o, struct lu_buf *buf,
2043                                  struct thandle *handle)
2044 {
2045         struct hsm_attrs *attrs;
2046         __u32 hsm_flags;
2047         int flags = 0;
2048         int rc;
2049         ENTRY;
2050
2051         rc = mdo_xattr_set(env, o, buf, XATTR_NAME_HSM, LU_XATTR_REPLACE,
2052                            handle);
2053         if (rc != 0)
2054                 RETURN(rc);
2055
2056         attrs = buf->lb_buf;
2057         hsm_flags = le32_to_cpu(attrs->hsm_flags);
2058         if (!(hsm_flags & HS_RELEASED) || mdd_is_dead_obj(o))
2059                 RETURN(0);
2060
2061         /* Add a changelog record for release. */
2062         hsm_set_cl_event(&flags, HE_RELEASE);
2063         rc = mdd_changelog_data_store(env, mdo2mdd(&o->mod_obj), CL_HSM,
2064                                       flags, o, handle);
2065         RETURN(rc);
2066 }
2067
2068 /*
2069  *  check if layout swapping between 2 objects is allowed
2070  *  the rules are:
2071  *  - only normal FIDs or non-system IGIFs
2072  *  - same type of objects
2073  *  - same owner/group (so quotas are still valid) unless this is from HSM
2074  *    release.
2075  */
2076 static int mdd_layout_swap_allowed(const struct lu_env *env,
2077                                    struct mdd_object *o1,
2078                                    const struct lu_attr *attr1,
2079                                    struct mdd_object *o2,
2080                                    const struct lu_attr *attr2,
2081                                    __u64 flags)
2082 {
2083         const struct lu_fid     *fid1, *fid2;
2084         ENTRY;
2085
2086         fid1 = mdo2fid(o1);
2087         fid2 = mdo2fid(o2);
2088
2089         if (!fid_is_norm(fid1) &&
2090             (!fid_is_igif(fid1) || IS_ERR(mdd_links_get(env, o1))))
2091                 RETURN(-EBADF);
2092
2093         if (!fid_is_norm(fid2) &&
2094             (!fid_is_igif(fid2) || IS_ERR(mdd_links_get(env, o2))))
2095                 RETURN(-EBADF);
2096
2097         if (mdd_object_type(o1) != mdd_object_type(o2)) {
2098                 if (S_ISDIR(mdd_object_type(o1)))
2099                         RETURN(-ENOTDIR);
2100                 if (S_ISREG(mdd_object_type(o1)))
2101                         RETURN(-EISDIR);
2102                 RETURN(-EBADF);
2103         }
2104
2105         if (flags & SWAP_LAYOUTS_MDS_HSM)
2106                 RETURN(0);
2107
2108         if ((attr1->la_uid != attr2->la_uid) ||
2109             (attr1->la_gid != attr2->la_gid))
2110                 RETURN(-EPERM);
2111
2112         RETURN(0);
2113 }
2114
2115 /* XXX To set the proper lmm_oi & lmm_layout_gen when swap layouts, we have to
2116  *     look into the layout in MDD layer. */
2117 static int mdd_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi, bool get)
2118 {
2119         struct lov_comp_md_v1   *comp_v1;
2120         struct lov_mds_md       *v1;
2121         int                      i, ent_count;
2122         __u32                    off;
2123
2124         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_COMP_V1) {
2125                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
2126                 ent_count = le16_to_cpu(comp_v1->lcm_entry_count);
2127
2128                 if (ent_count == 0)
2129                         return -EINVAL;
2130
2131                 if (get) {
2132                         off = le32_to_cpu(comp_v1->lcm_entries[0].lcme_offset);
2133                         v1 = (struct lov_mds_md *)((char *)comp_v1 + off);
2134                         *oi = v1->lmm_oi;
2135                 } else {
2136                         for (i = 0; i < le32_to_cpu(ent_count); i++) {
2137                                 off = le32_to_cpu(comp_v1->lcm_entries[i].
2138                                                 lcme_offset);
2139                                 v1 = (struct lov_mds_md *)((char *)comp_v1 +
2140                                                 off);
2141                                 v1->lmm_oi = *oi;
2142                         }
2143                 }
2144         } else if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1 ||
2145                    le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V3) {
2146                 if (get)
2147                         *oi = lmm->lmm_oi;
2148                 else
2149                         lmm->lmm_oi = *oi;
2150         } else {
2151                 return -EINVAL;
2152         }
2153         return 0;
2154 }
2155
2156 static inline int mdd_get_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi)
2157 {
2158         return mdd_lmm_oi(lmm, oi, true);
2159 }
2160
2161 static inline int mdd_set_lmm_oi(struct lov_mds_md *lmm, struct ost_id *oi)
2162 {
2163         return mdd_lmm_oi(lmm, oi, false);
2164 }
2165
2166 static int mdd_lmm_gen(struct lov_mds_md *lmm, __u32 *gen, bool get)
2167 {
2168         struct lov_comp_md_v1 *comp_v1;
2169
2170         if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_COMP_V1) {
2171                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
2172                 if (get)
2173                         *gen = le32_to_cpu(comp_v1->lcm_layout_gen);
2174                 else
2175                         comp_v1->lcm_layout_gen = cpu_to_le32(*gen);
2176         } else if (le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V1 ||
2177                    le32_to_cpu(lmm->lmm_magic) == LOV_MAGIC_V3) {
2178                 __u16 tmp_gen = *gen;
2179                 if (get)
2180                         *gen = le16_to_cpu(lmm->lmm_layout_gen);
2181                 else
2182                         lmm->lmm_layout_gen = cpu_to_le16(tmp_gen);
2183         } else {
2184                 return -EINVAL;
2185         }
2186         return 0;
2187 }
2188
2189 static inline int mdd_get_lmm_gen(struct lov_mds_md *lmm, __u32 *gen)
2190 {
2191         return mdd_lmm_gen(lmm, gen, true);
2192 }
2193
2194 static inline int mdd_set_lmm_gen(struct lov_mds_md *lmm, __u32 *gen)
2195 {
2196         return mdd_lmm_gen(lmm, gen, false);
2197 }
2198
2199 static int mdd_dom_data_truncate(const struct lu_env *env,
2200                                  struct mdd_device *mdd, struct mdd_object *mo)
2201 {
2202         struct thandle *th;
2203         struct dt_object *dom;
2204         int rc;
2205
2206         dom = dt_object_locate(mdd_object_child(mo), mdd->mdd_bottom);
2207         if (!dom)
2208                 GOTO(out, rc = -ENODATA);
2209
2210         th = dt_trans_create(env, mdd->mdd_bottom);
2211         if (IS_ERR(th))
2212                 GOTO(out, rc = PTR_ERR(th));
2213
2214         rc = dt_declare_punch(env, dom, 0, OBD_OBJECT_EOF, th);
2215         if (rc)
2216                 GOTO(stop, rc);
2217
2218         rc = dt_trans_start_local(env, mdd->mdd_bottom, th);
2219         if (rc != 0)
2220                 GOTO(stop, rc);
2221
2222         rc = dt_punch(env, dom, 0, OBD_OBJECT_EOF, th);
2223 stop:
2224         dt_trans_stop(env, mdd->mdd_bottom, th);
2225 out:
2226         /* Ignore failure but report the error */
2227         if (rc)
2228                 CERROR("%s: "DFID" can't truncate DOM inode data, rc = %d\n",
2229                        mdd_obj_dev_name(mo), PFID(mdo2fid(mo)), rc);
2230         return rc;
2231 }
2232
2233 /**
2234  * swap layouts between 2 lustre objects
2235  */
2236 static int mdd_swap_layouts(const struct lu_env *env, struct md_object *obj1,
2237                             struct md_object *obj2, __u64 flags)
2238 {
2239         struct mdd_thread_info *info = mdd_env_info(env);
2240         struct mdd_object *fst_o = md2mdd_obj(obj1);
2241         struct mdd_object *snd_o = md2mdd_obj(obj2);
2242         struct lu_attr *fst_la = MDD_ENV_VAR(env, cattr);
2243         struct lu_attr *snd_la = MDD_ENV_VAR(env, tattr);
2244         struct mdd_device *mdd = mdo2mdd(obj1);
2245         struct lov_mds_md *fst_lmm, *snd_lmm;
2246         struct lu_buf *fst_buf = &info->mti_buf[0];
2247         struct lu_buf *snd_buf = &info->mti_buf[1];
2248         struct lu_buf *fst_hsm_buf = &info->mti_buf[2];
2249         struct lu_buf *snd_hsm_buf = &info->mti_buf[3];
2250         struct ost_id *saved_oi = NULL;
2251         struct thandle *handle;
2252         struct mdd_object *dom_o = NULL;
2253         __u64 domsize_dom, domsize_vlt;
2254         __u32 fst_gen, snd_gen, saved_gen;
2255         int fst_fl;
2256         int rc, rc2;
2257
2258         ENTRY;
2259
2260         CLASSERT(ARRAY_SIZE(info->mti_buf) >= 4);
2261         memset(info->mti_buf, 0, sizeof(info->mti_buf));
2262
2263         /* we have to sort the 2 obj, so locking will always
2264          * be in the same order, even in case of 2 concurrent swaps */
2265         rc = lu_fid_cmp(mdo2fid(fst_o), mdo2fid(snd_o));
2266         if (rc == 0) /* same fid ? */
2267                 RETURN(-EPERM);
2268
2269         if (rc < 0)
2270                 swap(fst_o, snd_o);
2271
2272         rc = mdd_la_get(env, fst_o, fst_la);
2273         if (rc != 0)
2274                 RETURN(rc);
2275
2276         rc = mdd_la_get(env, snd_o, snd_la);
2277         if (rc != 0)
2278                 RETURN(rc);
2279
2280         /* check if layout swapping is allowed */
2281         rc = mdd_layout_swap_allowed(env, fst_o, fst_la, snd_o, snd_la, flags);
2282         if (rc != 0)
2283                 RETURN(rc);
2284
2285         handle = mdd_trans_create(env, mdd);
2286         if (IS_ERR(handle))
2287                 RETURN(PTR_ERR(handle));
2288
2289         /* objects are already sorted */
2290         mdd_write_lock(env, fst_o, MOR_TGT_CHILD);
2291         mdd_write_lock(env, snd_o, MOR_TGT_CHILD);
2292
2293         rc = mdd_stripe_get(env, fst_o, fst_buf, XATTR_NAME_LOV);
2294         if (rc < 0 && rc != -ENODATA)
2295                 GOTO(stop, rc);
2296
2297         rc = mdd_stripe_get(env, snd_o, snd_buf, XATTR_NAME_LOV);
2298         if (rc < 0 && rc != -ENODATA)
2299                 GOTO(stop, rc);
2300
2301         /* check if file has DoM. DoM file can be migrated only to another
2302          * DoM layout with the same DoM component size or to an non-DOM
2303          * layout. After migration to OSTs layout, local MDT inode data
2304          * should be truncated.
2305          * Objects are sorted by FIDs, considering that original file's FID
2306          * is always smaller the snd_o is always original file we are migrating
2307          * from.
2308          */
2309         domsize_dom = mdd_lmm_dom_size(snd_buf->lb_buf);
2310         domsize_vlt = mdd_lmm_dom_size(fst_buf->lb_buf);
2311
2312         /* Only migration is supported for DoM files, not 'swap_layouts' so
2313          * target file must be volatile and orphan.
2314          */
2315         if (fst_o->mod_flags & (ORPHAN_OBJ | VOLATILE_OBJ)) {
2316                 dom_o = domsize_dom ? snd_o : NULL;
2317         } else if (snd_o->mod_flags & (ORPHAN_OBJ | VOLATILE_OBJ)) {
2318                 swap(domsize_dom, domsize_vlt);
2319                 dom_o = domsize_dom ? fst_o : NULL;
2320         } else if (domsize_dom > 0 || domsize_vlt > 0) {
2321                 /* 'lfs swap_layouts' case, neither file should have DoM */
2322                 rc = -EOPNOTSUPP;
2323                 CDEBUG(D_LAYOUT, "cannot swap layouts with DOM component, "
2324                        "use migration instead: rc = %d\n", rc);
2325                 GOTO(stop, rc);
2326         }
2327
2328         if (domsize_vlt > 0 && domsize_dom == 0) {
2329                 rc = -EOPNOTSUPP;
2330                 CDEBUG(D_LAYOUT, "cannot swap layout for "DFID": OST to DOM "
2331                        "migration is not supported: rc = %d\n",
2332                        PFID(mdo2fid(snd_o)), rc);
2333                 GOTO(stop, rc);
2334         } else if (domsize_vlt > 0 && domsize_dom != domsize_vlt) {
2335                 rc = -EOPNOTSUPP;
2336                 CDEBUG(D_LAYOUT, "cannot swap layout for "DFID": new layout "
2337                        "must have the same DoM component size: rc = %d\n",
2338                        PFID(mdo2fid(fst_o)), rc);
2339                 GOTO(stop, rc);
2340         } else if (domsize_vlt > 0) {
2341                 /* Migration with the same DOM component size, no need to
2342                  * truncate local data, it is still being used */
2343                 dom_o = NULL;
2344         }
2345
2346         /* swapping 2 non existant layouts is a success */
2347         if (fst_buf->lb_buf == NULL && snd_buf->lb_buf == NULL)
2348                 GOTO(stop, rc = 0);
2349
2350         /* to help inode migration between MDT, it is better to
2351          * start by the no layout file (if one), so we order the swap */
2352         if (snd_buf->lb_buf == NULL) {
2353                 swap(fst_o, snd_o);
2354                 swap(fst_buf, snd_buf);
2355         }
2356
2357         fst_gen = snd_gen = 0;
2358         /* lmm and generation layout initialization */
2359         if (fst_buf->lb_buf != NULL) {
2360                 fst_lmm = fst_buf->lb_buf;
2361                 mdd_get_lmm_gen(fst_lmm, &fst_gen);
2362                 fst_fl  = LU_XATTR_REPLACE;
2363         } else {
2364                 fst_lmm = NULL;
2365                 fst_gen = 0;
2366                 fst_fl  = LU_XATTR_CREATE;
2367         }
2368
2369         snd_lmm = snd_buf->lb_buf;
2370         mdd_get_lmm_gen(snd_lmm, &snd_gen);
2371
2372         saved_gen = fst_gen;
2373         /* increase the generation layout numbers */
2374         snd_gen++;
2375         fst_gen++;
2376
2377         /*
2378          * XXX The layout generation is used to generate component IDs for
2379          *     the composite file, we have to do some special tweaks to make
2380          *     sure the layout generation is always adequate for that job.
2381          */
2382
2383         /* Skip invalid generation number for composite layout */
2384         if ((snd_gen & LCME_ID_MASK) == 0)
2385                 snd_gen++;
2386         if ((fst_gen & LCME_ID_MASK) == 0)
2387                 fst_gen++;
2388         /* Make sure the generation is greater than all the component IDs */
2389         if (fst_gen < snd_gen)
2390                 fst_gen = snd_gen;
2391         else if (fst_gen > snd_gen)
2392                 snd_gen = fst_gen;
2393
2394         /* set the file specific informations in lmm */
2395         if (fst_lmm != NULL) {
2396                 saved_oi = &info->mti_oa.o_oi;
2397                 mdd_get_lmm_oi(fst_lmm, saved_oi);
2398                 mdd_set_lmm_gen(fst_lmm, &snd_gen);
2399                 mdd_set_lmm_oi(fst_lmm, &snd_lmm->lmm_oi);
2400                 mdd_set_lmm_oi(snd_lmm, saved_oi);
2401         } else {
2402                 if ((snd_lmm->lmm_magic & cpu_to_le32(LOV_MAGIC_MASK)) ==
2403                     cpu_to_le32(LOV_MAGIC_MAGIC))
2404                         snd_lmm->lmm_magic |= cpu_to_le32(LOV_MAGIC_DEFINED);
2405                 else
2406                         GOTO(stop, rc = -EPROTO);
2407         }
2408         mdd_set_lmm_gen(snd_lmm, &fst_gen);
2409
2410         /* Prepare HSM attribute if it's required */
2411         if (flags & SWAP_LAYOUTS_MDS_HSM) {
2412                 const int buflen = sizeof(struct hsm_attrs);
2413
2414                 lu_buf_alloc(fst_hsm_buf, buflen);
2415                 lu_buf_alloc(snd_hsm_buf, buflen);
2416                 if (fst_hsm_buf->lb_buf == NULL || snd_hsm_buf->lb_buf == NULL)
2417                         GOTO(stop, rc = -ENOMEM);
2418
2419                 /* Read HSM attribute */
2420                 rc = mdo_xattr_get(env, fst_o, fst_hsm_buf, XATTR_NAME_HSM);
2421                 if (rc < 0)
2422                         GOTO(stop, rc);
2423
2424                 rc = mdo_xattr_get(env, snd_o, snd_hsm_buf, XATTR_NAME_HSM);
2425                 if (rc < 0)
2426                         GOTO(stop, rc);
2427
2428                 rc = mdd_declare_xattr_set(env, mdd, fst_o, snd_hsm_buf,
2429                                            XATTR_NAME_HSM, LU_XATTR_REPLACE,
2430                                            handle);
2431                 if (rc < 0)
2432                         GOTO(stop, rc);
2433
2434                 rc = mdd_declare_xattr_set(env, mdd, snd_o, fst_hsm_buf,
2435                                            XATTR_NAME_HSM, LU_XATTR_REPLACE,
2436                                            handle);
2437                 if (rc < 0)
2438                         GOTO(stop, rc);
2439         }
2440
2441         /* prepare transaction */
2442         rc = mdd_declare_xattr_set(env, mdd, fst_o, snd_buf, XATTR_NAME_LOV,
2443                                    fst_fl, handle);
2444         if (rc != 0)
2445                 GOTO(stop, rc);
2446
2447         if (fst_buf->lb_buf != NULL)
2448                 rc = mdd_declare_xattr_set(env, mdd, snd_o, fst_buf,
2449                                            XATTR_NAME_LOV, LU_XATTR_REPLACE,
2450                                            handle);
2451         else
2452                 rc = mdd_declare_xattr_del(env, mdd, snd_o, XATTR_NAME_LOV,
2453                                            handle);
2454         if (rc != 0)
2455                 GOTO(stop, rc);
2456
2457         rc = mdd_trans_start(env, mdd, handle);
2458         if (rc != 0)
2459                 GOTO(stop, rc);
2460
2461         if (flags & SWAP_LAYOUTS_MDS_HSM) {
2462                 rc = mdd_xattr_hsm_replace(env, fst_o, snd_hsm_buf, handle);
2463                 if (rc < 0)
2464                         GOTO(stop, rc);
2465
2466                 rc = mdd_xattr_hsm_replace(env, snd_o, fst_hsm_buf, handle);
2467                 if (rc < 0) {
2468                         rc2 = mdd_xattr_hsm_replace(env, fst_o, fst_hsm_buf,
2469                                                     handle);
2470                         if (rc2 < 0)
2471                                 CERROR("%s: restore "DFID" HSM error: %d/%d\n",
2472                                        mdd_obj_dev_name(fst_o),
2473                                        PFID(mdo2fid(fst_o)), rc, rc2);
2474                         GOTO(stop, rc);
2475                 }
2476         }
2477
2478         rc = mdo_xattr_set(env, fst_o, snd_buf, XATTR_NAME_LOV, fst_fl, handle);
2479         if (rc != 0)
2480                 GOTO(stop, rc);
2481
2482         if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_MDS_HSM_SWAP_LAYOUTS))) {
2483                 rc = -EOPNOTSUPP;
2484         } else {
2485                 if (fst_buf->lb_buf != NULL)
2486                         rc = mdo_xattr_set(env, snd_o, fst_buf, XATTR_NAME_LOV,
2487                                            LU_XATTR_REPLACE, handle);
2488                 else
2489                         rc = mdo_xattr_del(env, snd_o, XATTR_NAME_LOV, handle);
2490         }
2491         if (rc != 0)
2492                 GOTO(out_restore, rc);
2493
2494         /* Issue one changelog record per file */
2495         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, fst_o, handle);
2496         if (rc)
2497                 GOTO(stop, rc);
2498
2499         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, snd_o, handle);
2500         if (rc)
2501                 GOTO(stop, rc);
2502         EXIT;
2503
2504 out_restore:
2505         if (rc != 0) {
2506                 int steps = 0;
2507
2508                 /* failure on second file, but first was done, so we have
2509                  * to roll back first. */
2510                 if (fst_buf->lb_buf != NULL) {
2511                         mdd_set_lmm_oi(fst_lmm, saved_oi);
2512                         mdd_set_lmm_gen(fst_lmm, &saved_gen);
2513                         rc2 = mdo_xattr_set(env, fst_o, fst_buf, XATTR_NAME_LOV,
2514                                             LU_XATTR_REPLACE, handle);
2515                 } else {
2516                         rc2 = mdo_xattr_del(env, fst_o, XATTR_NAME_LOV, handle);
2517                 }
2518                 if (rc2 < 0)
2519                         goto do_lbug;
2520
2521                 ++steps;
2522                 rc2 = mdd_xattr_hsm_replace(env, fst_o, fst_hsm_buf, handle);
2523                 if (rc2 < 0)
2524                         goto do_lbug;
2525
2526                 ++steps;
2527                 rc2 = mdd_xattr_hsm_replace(env, snd_o, snd_hsm_buf, handle);
2528
2529         do_lbug:
2530                 if (rc2 < 0) {
2531                         /* very bad day */
2532                         CERROR("%s: unable to roll back layout swap. FIDs: "
2533                                DFID" and "DFID "error: %d/%d, steps: %d\n",
2534                                mdd_obj_dev_name(fst_o),
2535                                PFID(mdo2fid(snd_o)), PFID(mdo2fid(fst_o)),
2536                                rc, rc2, steps);
2537                         /* a solution to avoid journal commit is to panic,
2538                          * but it has strong consequences so we use LBUG to
2539                          * allow sysdamin to choose to panic or not
2540                          */
2541                         LBUG();
2542                 }
2543         }
2544
2545 stop:
2546         rc = mdd_trans_stop(env, mdd, rc, handle);
2547
2548         /* Truncate local DOM data if all went well */
2549         if (!rc && dom_o)
2550                 mdd_dom_data_truncate(env, mdd, dom_o);
2551
2552         mdd_write_unlock(env, snd_o);
2553         mdd_write_unlock(env, fst_o);
2554
2555         lu_buf_free(fst_buf);
2556         lu_buf_free(snd_buf);
2557         lu_buf_free(fst_hsm_buf);
2558         lu_buf_free(snd_hsm_buf);
2559
2560         if (!rc) {
2561                 (void) mdd_object_pfid_replace(env, fst_o);
2562                 (void) mdd_object_pfid_replace(env, snd_o);
2563         }
2564         return rc;
2565 }
2566
2567 static int mdd_declare_layout_change(const struct lu_env *env,
2568                                      struct mdd_device *mdd,
2569                                      struct mdd_object *obj,
2570                                      struct md_layout_change *mlc,
2571                                      struct thandle *handle)
2572 {
2573         int rc;
2574
2575         rc = mdo_declare_layout_change(env, obj, mlc, handle);
2576         if (rc)
2577                 return rc;
2578
2579         return mdd_declare_changelog_store(env, mdd, CL_LAYOUT, NULL, NULL,
2580                                            handle);
2581 }
2582
2583 /* For PFL, this is used to instantiate necessary component objects. */
2584 static int
2585 mdd_layout_instantiate_component(const struct lu_env *env,
2586                 struct mdd_object *obj, struct md_layout_change *mlc,
2587                 struct thandle *handle)
2588 {
2589         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2590         int rc;
2591         ENTRY;
2592
2593         if (mlc->mlc_opc != MD_LAYOUT_WRITE)
2594                 RETURN(-ENOTSUPP);
2595
2596         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2597         /**
2598          * It's possible that another layout write intent has already
2599          * instantiated our objects, so a -EALREADY returned, and we need to
2600          * do nothing.
2601          */
2602         if (rc)
2603                 RETURN(rc == -EALREADY ? 0 : rc);
2604
2605         rc = mdd_trans_start(env, mdd, handle);
2606         if (rc)
2607                 RETURN(rc);
2608
2609         mdd_write_lock(env, obj, MOR_TGT_CHILD);
2610         rc = mdo_layout_change(env, obj, mlc, handle);
2611         mdd_write_unlock(env, obj);
2612         if (rc)
2613                 RETURN(rc);
2614
2615         rc = mdd_changelog_data_store(env, mdd, CL_LAYOUT, 0, obj, handle);
2616         RETURN(rc);
2617 }
2618
2619 /**
2620  * Change the FLR layout from RDONLY to WRITE_PENDING.
2621  *
2622  * It picks the primary mirror, and bumps the layout version, and set
2623  * layout version xattr to OST objects in a sync tx. In order to facilitate
2624  * the handling of phantom writers from evicted clients, the clients carry
2625  * layout version of the file with write RPC, so that the OSTs can verify
2626  * if the write RPCs are legitimate, meaning not from evicted clients.
2627  */
2628 static int
2629 mdd_layout_update_rdonly(const struct lu_env *env, struct mdd_object *obj,
2630                          struct md_layout_change *mlc, struct thandle *handle)
2631 {
2632         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2633         struct lu_buf *som_buf = &mdd_env_info(env)->mti_buf[1];
2634         struct lustre_som_attrs *som = &mlc->mlc_som;
2635         int fl = 0;
2636         int rc;
2637         ENTRY;
2638
2639         /* Verify acceptable operations */
2640         switch (mlc->mlc_opc) {
2641         case MD_LAYOUT_WRITE:
2642         case MD_LAYOUT_RESYNC:
2643                 /* these are legal operations - this represents the case that
2644                  * a few mirrors were missed in the last resync. */
2645                 break;
2646         case MD_LAYOUT_RESYNC_DONE:
2647         default:
2648                 RETURN(0);
2649         }
2650
2651         som_buf->lb_buf = som;
2652         som_buf->lb_len = sizeof(*som);
2653         rc = mdo_xattr_get(env, obj, som_buf, XATTR_NAME_SOM);
2654         if (rc < 0 && rc != -ENODATA)
2655                 RETURN(rc);
2656
2657         if (rc > 0) {
2658                 lustre_som_swab(som);
2659                 if (som->lsa_valid & SOM_FL_STRICT)
2660                         fl = LU_XATTR_REPLACE;
2661         }
2662
2663         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2664         if (rc)
2665                 GOTO(out, rc);
2666
2667         if (fl) {
2668                 rc = mdd_declare_xattr_set(env, mdd, obj, som_buf,
2669                                            XATTR_NAME_SOM, fl, handle);
2670                 if (rc)
2671                         GOTO(out, rc);
2672         }
2673
2674         /* record a changelog for data mover to consume */
2675         rc = mdd_declare_changelog_store(env, mdd, CL_FLRW, NULL, NULL, handle);
2676         if (rc)
2677                 GOTO(out, rc);
2678
2679         rc = mdd_trans_start(env, mdd, handle);
2680         if (rc)
2681                 GOTO(out, rc);
2682
2683         /* it needs a sync tx to make FLR to work properly */
2684         handle->th_sync = 1;
2685
2686         mdd_write_lock(env, obj, MOR_TGT_CHILD);
2687         rc = mdo_layout_change(env, obj, mlc, handle);
2688         if (!rc && fl) {
2689                 /* SOM state transition from STRICT to STALE */
2690                 som->lsa_valid = SOM_FL_STALE;
2691                 lustre_som_swab(som);
2692                 rc = mdo_xattr_set(env, obj, som_buf, XATTR_NAME_SOM,
2693                                    fl, handle);
2694         }
2695         mdd_write_unlock(env, obj);
2696         if (rc)
2697                 GOTO(out, rc);
2698
2699         rc = mdd_changelog_data_store(env, mdd, CL_FLRW, 0, obj, handle);
2700         if (rc)
2701                 GOTO(out, rc);
2702
2703         EXIT;
2704
2705 out:
2706         return rc;
2707 }
2708
2709 /**
2710  * Handle mirrored file state transition when it's in WRITE_PENDING.
2711  *
2712  * Only MD_LAYOUT_RESYNC, which represents start of resync, is allowed when
2713  * the file is in WRITE_PENDING state. If everything goes fine, the file's
2714  * layout version will be increased, and the file's state will be changed to
2715  * SYNC_PENDING.
2716  */
2717 static int
2718 mdd_layout_update_write_pending(const struct lu_env *env,
2719                 struct mdd_object *obj, struct md_layout_change *mlc,
2720                 struct thandle *handle)
2721 {
2722         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2723         int rc;
2724         ENTRY;
2725
2726         switch (mlc->mlc_opc) {
2727         case MD_LAYOUT_RESYNC:
2728                 /* Upon receiving the resync request, it should
2729                  * instantiate all stale components right away to get ready
2730                  * for mirror copy. In order to avoid layout version change,
2731                  * client should avoid sending LAYOUT_WRITE request at the
2732                  * resync state. */
2733                 break;
2734         case MD_LAYOUT_WRITE:
2735                 /* legal race for concurrent write, the file state has been
2736                  * changed by another client. */
2737                 break;
2738         default:
2739                 RETURN(-EBUSY);
2740         }
2741
2742         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2743         if (rc)
2744                 GOTO(out, rc);
2745
2746         rc = mdd_trans_start(env, mdd, handle);
2747         if (rc)
2748                 GOTO(out, rc);
2749
2750         /* it needs a sync tx to make FLR to work properly */
2751         handle->th_sync = 1;
2752
2753         mdd_write_lock(env, obj, MOR_TGT_CHILD);
2754         rc = mdo_layout_change(env, obj, mlc, handle);
2755         mdd_write_unlock(env, obj);
2756         if (rc)
2757                 GOTO(out, rc);
2758
2759         EXIT;
2760
2761 out:
2762         return rc;
2763 }
2764
2765 /**
2766  * Handle the requests when a FLR file's state is in SYNC_PENDING.
2767  *
2768  * Only concurrent write and sync complete requests are possible when the
2769  * file is in SYNC_PENDING. For the latter request, it will pass in the
2770  * mirrors that have been synchronized, then the stale bit will be cleared
2771  * to make the file's state turn into RDONLY.
2772  * For concurrent write reqeust, it just needs to change the file's state
2773  * to WRITE_PENDING in a sync tx. It doesn't have to change the layout
2774  * version because the version will be increased in the transition to
2775  * SYNC_PENDING later so that it can deny the write request from potential
2776  * evicted SYNC clients. */
2777 static int
2778 mdd_object_update_sync_pending(const struct lu_env *env, struct mdd_object *obj,
2779                 struct md_layout_change *mlc, struct thandle *handle)
2780 {
2781         struct mdd_device *mdd = mdd_obj2mdd_dev(obj);
2782         struct lu_buf *som_buf = &mdd_env_info(env)->mti_buf[1];
2783         int fl = 0;
2784         int rc;
2785         ENTRY;
2786
2787         /* operation validation */
2788         switch (mlc->mlc_opc) {
2789         case MD_LAYOUT_RESYNC_DONE:
2790                 /* resync complete. */
2791         case MD_LAYOUT_WRITE:
2792                 /* concurrent write. */
2793                 break;
2794         case MD_LAYOUT_RESYNC:
2795                 /* resync again, most likely the previous run failed.
2796                  * no-op if it's already in SYNC_PENDING state */
2797                 RETURN(0);
2798         default:
2799                 RETURN(-EBUSY);
2800         }
2801
2802         if (mlc->mlc_som.lsa_valid & SOM_FL_STRICT) {
2803                 rc = mdo_xattr_get(env, obj, &LU_BUF_NULL, XATTR_NAME_SOM);
2804                 if (rc < 0 && rc != -ENODATA)
2805                         RETURN(rc);
2806
2807                 fl = rc == -ENODATA ? LU_XATTR_CREATE : LU_XATTR_REPLACE;
2808                 lustre_som_swab(&mlc->mlc_som);
2809                 som_buf->lb_buf = &mlc->mlc_som;
2810                 som_buf->lb_len = sizeof(mlc->mlc_som);
2811         }
2812
2813         rc = mdd_declare_layout_change(env, mdd, obj, mlc, handle);
2814         if (rc)
2815                 GOTO(out, rc);
2816
2817         /* record a changelog for the completion of resync */
2818         rc = mdd_declare_changelog_store(env, mdd, CL_RESYNC, NULL, NULL,
2819                                          handle);
2820         if (rc)
2821                 GOTO(out, rc);
2822
2823         /* RESYNC_DONE has piggybacked size and blocks */
2824         if (fl) {
2825                 rc = mdd_declare_xattr_set(env, mdd, obj, som_buf,
2826                                            XATTR_NAME_SOM, fl, handle);
2827                 if (rc)
2828                         GOTO(out, rc);
2829         }
2830
2831         rc = mdd_trans_start(env, mdd, handle);
2832         if (rc)
2833                 GOTO(out, rc);
2834
2835         /* it needs a sync tx to make FLR to work properly */
2836         handle->th_sync = 1;
2837
2838         rc = mdo_layout_change(env, obj, mlc, handle);
2839         if (rc)
2840                 GOTO(out, rc);
2841
2842         if (fl) {
2843                 rc = mdo_xattr_set(env, obj, som_buf, XATTR_NAME_SOM,
2844                                    fl, handle);
2845                 if (rc)
2846                         GOTO(out, rc);
2847         }
2848
2849         rc = mdd_changelog_data_store(env, mdd, CL_RESYNC, 0, obj, handle);
2850         if (rc)
2851                 GOTO(out, rc);
2852         EXIT;
2853 out:
2854         return rc;
2855 }
2856
2857 /**
2858  * Layout change callback for object.
2859  *
2860  * This is only used by FLR for now. In the future, it can be exteneded to
2861  * handle all layout change.
2862  */
2863 static int
2864 mdd_layout_change(const struct lu_env *env, struct md_object *o,
2865                   struct md_layout_change *mlc)
2866 {
2867         struct mdd_object       *obj = md2mdd_obj(o);
2868         struct mdd_device       *mdd = mdd_obj2mdd_dev(obj);
2869         struct lu_buf           *buf = mdd_buf_get(env, NULL, 0);
2870         struct lov_comp_md_v1   *lcm;
2871         struct thandle          *handle;
2872         int flr_state;
2873         int rc;
2874         ENTRY;
2875
2876         /* Verify acceptable operations */
2877         switch (mlc->mlc_opc) {
2878         case MD_LAYOUT_WRITE:
2879         case MD_LAYOUT_RESYNC:
2880         case MD_LAYOUT_RESYNC_DONE:
2881                 break;
2882         default:
2883                 RETURN(-ENOTSUPP);
2884         }
2885
2886         handle = mdd_trans_create(env, mdd);
2887         if (IS_ERR(handle))
2888                 RETURN(PTR_ERR(handle));
2889
2890         rc = mdd_stripe_get(env, obj, buf, XATTR_NAME_LOV);
2891         if (rc < 0) {
2892                 if (rc == -ENODATA)
2893                         rc = -EINVAL;
2894                 GOTO(out, rc);
2895         }
2896
2897         /* analyze the layout to make sure it's a FLR file */
2898         lcm = buf->lb_buf;
2899         if (le32_to_cpu(lcm->lcm_magic) != LOV_MAGIC_COMP_V1)
2900                 GOTO(out, rc = -EINVAL);
2901
2902         flr_state = le16_to_cpu(lcm->lcm_flags) & LCM_FL_FLR_MASK;
2903
2904         /* please refer to HLD of FLR for state transition */
2905         switch (flr_state) {
2906         case LCM_FL_NONE:
2907                 rc = mdd_layout_instantiate_component(env, obj, mlc, handle);
2908                 break;
2909         case LCM_FL_WRITE_PENDING:
2910                 rc = mdd_layout_update_write_pending(env, obj, mlc, handle);
2911                 break;
2912         case LCM_FL_RDONLY:
2913                 rc = mdd_layout_update_rdonly(env, obj, mlc, handle);
2914                 break;
2915         case LCM_FL_SYNC_PENDING:
2916                 rc = mdd_object_update_sync_pending(env, obj, mlc, handle);
2917                 break;
2918         default:
2919                 rc = 0;
2920                 break;
2921         }
2922         EXIT;
2923
2924 out:
2925         mdd_trans_stop(env, mdd, rc, handle);
2926         lu_buf_free(buf);
2927         return rc;
2928 }
2929
2930 void mdd_object_make_hint(const struct lu_env *env, struct mdd_object *parent,
2931                           struct mdd_object *child, const struct lu_attr *attr,
2932                           const struct md_op_spec *spec,
2933                           struct dt_allocation_hint *hint)
2934 {
2935         struct dt_object *np = parent ?  mdd_object_child(parent) : NULL;
2936         struct dt_object *nc = mdd_object_child(child);
2937
2938         memset(hint, 0, sizeof(*hint));
2939
2940         /* For striped directory, give striping EA to lod_ah_init, which will
2941          * decide the stripe_offset and stripe count by it. */
2942         if (S_ISDIR(attr->la_mode) &&
2943             unlikely(spec != NULL && spec->sp_cr_flags & MDS_OPEN_HAS_EA)) {
2944                 hint->dah_eadata = spec->u.sp_ea.eadata;
2945                 hint->dah_eadata_len = spec->u.sp_ea.eadatalen;
2946         } else {
2947                 hint->dah_eadata = NULL;
2948                 hint->dah_eadata_len = 0;
2949         }
2950
2951         CDEBUG(D_INFO, DFID" eadata %p len %d\n", PFID(mdd_object_fid(child)),
2952                hint->dah_eadata, hint->dah_eadata_len);
2953         /* @hint will be initialized by underlying device. */
2954         nc->do_ops->do_ah_init(env, hint, np, nc, attr->la_mode & S_IFMT);
2955 }
2956
2957 static int accmode(const struct lu_env *env, const struct lu_attr *la,
2958                    u64 open_flags)
2959 {
2960         /* Sadly, NFSD reopens a file repeatedly during operation, so the
2961          * "acc_mode = 0" allowance for newly-created files isn't honoured.
2962          * NFSD uses the MDS_OPEN_OWNEROVERRIDE flag to say that a file
2963          * owner can write to a file even if it is marked readonly to hide
2964          * its brokenness. (bug 5781) */
2965         if (open_flags & MDS_OPEN_OWNEROVERRIDE) {
2966                 struct lu_ucred *uc = lu_ucred_check(env);
2967
2968                 if ((uc == NULL) || (la->la_uid == uc->uc_fsuid))
2969                         return 0;
2970         }
2971
2972         return mds_accmode(open_flags);
2973 }
2974
2975 static int mdd_open_sanity_check(const struct lu_env *env,
2976                                  struct mdd_object *obj,
2977                                  const struct lu_attr *attr, u64 open_flags)
2978 {
2979         int mode, rc;
2980         ENTRY;
2981
2982         /* EEXIST check, also opening of *open* orphans is allowed so we can
2983          * open-by-handle unlinked files
2984          */
2985         if (mdd_is_dead_obj(obj) &&
2986             likely(!(mdd_is_orphan_obj(obj) && obj->mod_count > 0)))
2987                 RETURN(-ENOENT);
2988
2989         if (S_ISLNK(attr->la_mode))
2990                 RETURN(-ELOOP);
2991
2992         mode = accmode(env, attr, open_flags);
2993
2994         if (S_ISDIR(attr->la_mode) && (mode & MAY_WRITE))
2995                 RETURN(-EISDIR);
2996
2997         if (!(open_flags & MDS_OPEN_CREATED)) {
2998                 rc = mdd_permission_internal(env, obj, attr, mode);
2999                 if (rc)
3000                         RETURN(rc);
3001         }
3002
3003         if (S_ISFIFO(attr->la_mode) || S_ISSOCK(attr->la_mode) ||
3004             S_ISBLK(attr->la_mode) || S_ISCHR(attr->la_mode))
3005                 open_flags &= ~MDS_OPEN_TRUNC;
3006
3007         /* For writing append-only file must open it with append mode. */
3008         if (attr->la_flags & LUSTRE_APPEND_FL) {
3009                 if ((open_flags & MDS_FMODE_WRITE) &&
3010                     !(open_flags & MDS_OPEN_APPEND))
3011                         RETURN(-EPERM);
3012                 if (open_flags & MDS_OPEN_TRUNC)
3013                         RETURN(-EPERM);
3014         }
3015
3016         RETURN(0);
3017 }
3018
3019 static int mdd_open(const struct lu_env *env, struct md_object *obj,
3020                     u64 open_flags)
3021 {
3022         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3023         struct md_device *md_dev = lu2md_dev(mdd2lu_dev(mdo2mdd(obj)));
3024         struct lu_attr *attr = MDD_ENV_VAR(env, cattr);
3025         struct mdd_object_user *mou = NULL;
3026         const struct lu_ucred *uc = lu_ucred(env);
3027         struct mdd_device *mdd = mdo2mdd(obj);
3028         enum changelog_rec_type type = CL_OPEN;
3029         int rc = 0;
3030
3031         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
3032
3033         rc = mdd_la_get(env, mdd_obj, attr);
3034         if (rc != 0)
3035                 GOTO(out, rc);
3036
3037         rc = mdd_open_sanity_check(env, mdd_obj, attr, open_flags);
3038         if ((rc == -EACCES) && (mdd->mdd_cl.mc_mask & (1 << CL_DN_OPEN)))
3039                 type = CL_DN_OPEN;
3040         else if (rc != 0)
3041                 GOTO(out, rc);
3042         else
3043                 mdd_obj->mod_count++;
3044
3045         if (!mdd_changelog_enabled(env, mdd, type))
3046                 GOTO(out, rc);
3047
3048 find:
3049         /* look for existing opener in list under mdd_write_lock */
3050         mou = mdd_obj_user_find(mdd_obj, uc->uc_uid, uc->uc_gid, open_flags);
3051
3052         if (!mou) {
3053                 int rc2;
3054
3055                 /* add user to list */
3056                 mou = mdd_obj_user_alloc(open_flags, uc->uc_uid, uc->uc_gid);
3057                 if (IS_ERR(mou)) {
3058                         if (rc == 0)
3059                                 rc = PTR_ERR(mou);
3060                         GOTO(out, rc);
3061                 }
3062                 rc2 = mdd_obj_user_add(mdd_obj, mou, type == CL_DN_OPEN);
3063                 if (rc2 != 0) {
3064                         mdd_obj_user_free(mou);
3065                         if (rc2 == -EEXIST)
3066                                 GOTO(find, rc2);
3067                 }
3068         } else {
3069                 if (type == CL_DN_OPEN) {
3070                         if (ktime_before(ktime_get(), mou->mou_deniednext))
3071                                 /* same user denied again same access within
3072                                  * time interval: do not record
3073                                  */
3074                                 GOTO(out, rc);
3075
3076                         /* this user already denied, but some time ago:
3077                          * update denied time
3078                          */
3079                         mou->mou_deniednext =
3080                                 ktime_add(ktime_get(),
3081                                           ktime_set(mdd->mdd_cl.mc_deniednext,
3082                                                     0));
3083                 } else {
3084                         mou->mou_opencount++;
3085                         /* same user opening file again with same flags:
3086                          * don't record
3087                          */
3088                         GOTO(out, rc);
3089                 }
3090         }
3091
3092         mdd_changelog(env, type, open_flags, md_dev, mdo2fid(mdd_obj));
3093
3094         EXIT;
3095 out:
3096         mdd_write_unlock(env, mdd_obj);
3097         return rc;
3098 }
3099
3100 static int mdd_declare_close(const struct lu_env *env, struct mdd_object *obj,
3101                              struct md_attr *ma, struct thandle *handle)
3102 {
3103         int rc;
3104
3105         rc = mdd_orphan_declare_delete(env, obj, handle);
3106         if (rc)
3107                 return rc;
3108
3109         return mdo_declare_destroy(env, obj, handle);
3110 }
3111
3112 /*
3113  * No permission check is needed.
3114  */
3115 static int mdd_close(const struct lu_env *env, struct md_object *obj,
3116                      struct md_attr *ma, u64 open_flags)
3117 {
3118         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3119         struct mdd_device *mdd = mdo2mdd(obj);
3120         struct thandle *handle = NULL;
3121         int is_orphan = 0;
3122         int rc;
3123         bool blocked = false;
3124         int last_close_by_uid = 0;
3125         const struct lu_ucred *uc = lu_ucred(env);
3126         ENTRY;
3127
3128         if (ma->ma_valid & MA_FLAGS && ma->ma_attr_flags & MDS_KEEP_ORPHAN) {
3129                 mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
3130                 mdd_obj->mod_count--;
3131                 mdd_write_unlock(env, mdd_obj);
3132
3133                 if (mdd_obj->mod_flags & ORPHAN_OBJ && !mdd_obj->mod_count)
3134                         CDEBUG(D_HA, "Object "DFID" is retained in orphan "
3135                                 "list\n", PFID(mdd_object_fid(mdd_obj)));
3136                 RETURN(0);
3137         }
3138
3139         /* mdd_finish_unlink() will always set orphan object as DEAD_OBJ, but
3140          * it might fail to add the object to orphan list (w/o ORPHAN_OBJ). */
3141         /* check without any lock */
3142         is_orphan = mdd_obj->mod_count == 1 &&
3143                     (mdd_obj->mod_flags & (ORPHAN_OBJ | DEAD_OBJ)) != 0;
3144
3145 again:
3146         if (is_orphan) {
3147                 /* mdd_trans_create() maybe failed because of barrier_entry(),
3148                  * under such case, the orphan MDT-object will be left in the
3149                  * orphan list, and when the MDT remount next time, the unused
3150                  * orphans will be destroyed automatically.
3151                  *
3152                  * One exception: the former mdd_finish_unlink may failed to
3153                  * add the orphan MDT-object to the orphan list, then if the
3154                  * mdd_trans_create() failed because of barrier_entry(), the
3155                  * MDT-object will become real orphan that is neither in the
3156                  * namespace nor in the orphan list. Such bad case should be
3157                  * very rare and will be handled by e2fsck/lfsck. */
3158                 handle = mdd_trans_create(env, mdo2mdd(obj));
3159                 if (IS_ERR(handle)) {
3160                         rc = PTR_ERR(handle);
3161                         if (rc != -EINPROGRESS)
3162                                 GOTO(stop, rc);
3163
3164                         handle = NULL;
3165                         blocked = true;
3166                         goto cont;
3167                 }
3168
3169                 rc = mdd_declare_close(env, mdd_obj, ma, handle);
3170                 if (rc)
3171                         GOTO(stop, rc);
3172
3173                 rc = mdd_declare_changelog_store(env, mdd, CL_CLOSE, NULL, NULL,
3174                                                  handle);
3175                 if (rc)
3176                         GOTO(stop, rc);
3177
3178                 rc = mdd_trans_start(env, mdo2mdd(obj), handle);
3179                 if (rc)
3180                         GOTO(stop, rc);
3181         }
3182
3183 cont:
3184         mdd_write_lock(env, mdd_obj, MOR_TGT_CHILD);
3185         rc = mdd_la_get(env, mdd_obj, &ma->ma_attr);
3186         if (rc != 0) {
3187                 CERROR("%s: failed to get lu_attr of "DFID": rc = %d\n",
3188                        lu_dev_name(mdd2lu_dev(mdd)),
3189                        PFID(mdd_object_fid(mdd_obj)), rc);
3190                 GOTO(out, rc);
3191         }
3192
3193         /* check again with lock */
3194         is_orphan = (mdd_obj->mod_count == 1) &&
3195                     ((mdd_obj->mod_flags & (ORPHAN_OBJ | DEAD_OBJ)) != 0 ||
3196                      ma->ma_attr.la_nlink == 0);
3197
3198         if (is_orphan && !handle && !blocked) {
3199                 mdd_write_unlock(env, mdd_obj);
3200                 goto again;
3201         }
3202
3203         mdd_obj->mod_count--; /*release open count */
3204
3205         /* under mdd write lock */
3206         /* If recording, see if we need to remove UID from list */
3207         if (mdd_changelog_enabled(env, mdd, CL_OPEN)) {
3208                 struct mdd_object_user *mou;
3209
3210                 /* look for UID in list */
3211                 /* If mou is NULL, it probably means logging was enabled after
3212                  * the user had the file open. So the corresponding close
3213                  * will not be logged.
3214                  */
3215                 mou = mdd_obj_user_find(mdd_obj, uc->uc_uid, uc->uc_gid,
3216                                         open_flags);
3217                 if (mou) {
3218                         mou->mou_opencount--;
3219                         if (mou->mou_opencount == 0) {
3220                                 mdd_obj_user_remove(mdd_obj, mou);
3221                                 last_close_by_uid = 1;
3222                         }
3223                 }
3224         }
3225
3226         if (!is_orphan || blocked)
3227                 GOTO(out, rc = 0);
3228
3229         /* Orphan object */
3230         /* NB: Object maybe not in orphan list originally, it is rare case for
3231          * mdd_finish_unlink() failure, in that case, the object doesn't have
3232          * ORPHAN_OBJ flag */
3233         if ((mdd_obj->mod_flags & ORPHAN_OBJ) != 0) {
3234                 /* remove link to object from orphan index */
3235                 LASSERT(handle != NULL);
3236                 rc = mdd_orphan_delete(env, mdd_obj, handle);
3237                 if (rc != 0) {
3238                         CERROR("%s: unable to delete "DFID" from orphan list: "
3239                                "rc = %d\n", lu_dev_name(mdd2lu_dev(mdd)),
3240                                PFID(mdd_object_fid(mdd_obj)), rc);
3241                         /* If object was not deleted from orphan list, do not
3242                          * destroy OSS objects, which will be done when next
3243                          * recovery. */
3244                         GOTO(out, rc);
3245                 }
3246
3247                 CDEBUG(D_HA, "Object "DFID" is deleted from orphan "
3248                        "list, OSS objects to be destroyed.\n",
3249                        PFID(mdd_object_fid(mdd_obj)));
3250         }
3251
3252         rc = mdo_destroy(env, mdd_obj, handle);
3253
3254         if (rc != 0) {
3255                 CERROR("%s: unable to delete "DFID" from orphan list: "
3256                        "rc = %d\n", lu_dev_name(mdd2lu_dev(mdd)),
3257                        PFID(mdd_object_fid(mdd_obj)), rc);
3258         }
3259         EXIT;
3260
3261 out:
3262         mdd_write_unlock(env, mdd_obj);
3263
3264         if (rc != 0 || blocked ||
3265             !mdd_changelog_enabled(env, mdd, CL_CLOSE))
3266                 GOTO(stop, rc);
3267
3268         /* Record CL_CLOSE in changelog only if file was opened in write mode,
3269          * or if CL_OPEN was recorded and it's last close by user.
3270          * Changelogs mask may change between open and close operations, but
3271          * this is not a big deal if we have a CL_CLOSE entry with no matching
3272          * CL_OPEN. Plus Changelogs mask may not change often.
3273          */
3274         if (((!(mdd->mdd_cl.mc_mask & (1 << CL_OPEN)) &&
3275               (open_flags & (MDS_FMODE_WRITE | MDS_OPEN_APPEND |
3276                              MDS_OPEN_TRUNC))) ||
3277              ((mdd->mdd_cl.mc_mask & (1 << CL_OPEN)) && last_close_by_uid)) &&
3278             !(ma->ma_valid & MA_FLAGS && ma->ma_attr_flags & MDS_RECOV_OPEN)) {
3279                 if (handle == NULL) {
3280                         handle = mdd_trans_create(env, mdo2mdd(obj));
3281                         if (IS_ERR(handle))
3282                                 GOTO(stop, rc = PTR_ERR(handle));
3283
3284                         rc = mdd_declare_changelog_store(env, mdd, CL_CLOSE,
3285                                                          NULL, NULL, handle);
3286                         if (rc)
3287                                 GOTO(stop, rc);
3288
3289                         rc = mdd_trans_start(env, mdo2mdd(obj), handle);
3290                         if (rc)
3291                                 GOTO(stop, rc);
3292                 }
3293
3294                 mdd_changelog_data_store(env, mdd, CL_CLOSE, open_flags,
3295                                          mdd_obj, handle);
3296         }
3297
3298 stop:
3299         if (handle != NULL && !IS_ERR(handle))
3300                 rc = mdd_trans_stop(env, mdd, rc, handle);
3301
3302         return rc;
3303 }
3304
3305 /*
3306  * Permission check is done when open,
3307  * no need check again.
3308  */
3309 static int mdd_readpage_sanity_check(const struct lu_env *env,
3310                                      struct mdd_object *obj)
3311 {
3312         struct dt_object *next = mdd_object_child(obj);
3313         int rc;
3314         ENTRY;
3315
3316         if (S_ISDIR(mdd_object_type(obj)) && dt_try_as_dir(env, next))
3317                 rc = 0;
3318         else
3319                 rc = -ENOTDIR;
3320
3321         RETURN(rc);
3322 }
3323
3324 static int mdd_dir_page_build(const struct lu_env *env, union lu_page *lp,
3325                               size_t nob, const struct dt_it_ops *iops,
3326                               struct dt_it *it, __u32 attr, void *arg)
3327 {
3328         struct lu_dirpage       *dp = &lp->lp_dir;
3329         void                    *area = dp;
3330         int                      result;
3331         __u64                    hash = 0;
3332         struct lu_dirent        *ent;
3333         struct lu_dirent        *last = NULL;
3334         struct lu_fid            fid;
3335         int                      first = 1;
3336
3337         if (nob < sizeof(*dp))
3338                 return -EINVAL;
3339
3340         memset(area, 0, sizeof (*dp));
3341         area += sizeof (*dp);
3342         nob  -= sizeof (*dp);
3343
3344         ent  = area;
3345         do {
3346                 int    len;
3347                 size_t recsize;
3348
3349                 len = iops->key_size(env, it);
3350
3351                 /* IAM iterator can return record with zero len. */
3352                 if (len == 0)
3353                         goto next;
3354
3355                 hash = iops->store(env, it);
3356                 if (unlikely(first)) {
3357                         first = 0;
3358                         dp->ldp_hash_start = cpu_to_le64(hash);
3359                 }
3360
3361                 /* calculate max space required for lu_dirent */
3362                 recsize = lu_dirent_calc_size(len, attr);
3363
3364                 if (nob >= recsize) {
3365                         result = iops->rec(env, it, (struct dt_rec *)ent, attr);
3366                         if (result == -ESTALE)
3367                                 goto next;
3368                         if (result != 0)
3369                                 goto out;
3370
3371                         /* osd might not able to pack all attributes,
3372                          * so recheck rec length */
3373                         recsize = le16_to_cpu(ent->lde_reclen);
3374
3375                         if (le32_to_cpu(ent->lde_attrs) & LUDA_FID) {
3376                                 fid_le_to_cpu(&fid, &ent->lde_fid);
3377                                 if (fid_is_dot_lustre(&fid))
3378                                         goto next;
3379                         }
3380                 } else {
3381                         result = (last != NULL) ? 0 :-EINVAL;
3382                         goto out;
3383                 }
3384                 last = ent;
3385                 ent = (void *)ent + recsize;
3386                 nob -= recsize;
3387
3388 next:
3389                 result = iops->next(env, it);
3390                 if (result == -ESTALE)
3391                         goto next;
3392         } while (result == 0);
3393
3394 out:
3395         dp->ldp_hash_end = cpu_to_le64(hash);
3396         if (last != NULL) {
3397                 if (last->lde_hash == dp->ldp_hash_end)
3398                         dp->ldp_flags |= cpu_to_le32(LDF_COLLIDE);
3399                 last->lde_reclen = 0; /* end mark */
3400         }
3401         if (result > 0)
3402                 /* end of directory */
3403                 dp->ldp_hash_end = cpu_to_le64(MDS_DIR_END_OFF);
3404         else if (result < 0)
3405                 CWARN("build page failed: %d!\n", result);
3406         return result;
3407 }
3408
3409 int mdd_readpage(const struct lu_env *env, struct md_object *obj,
3410                  const struct lu_rdpg *rdpg)
3411 {
3412         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3413         int rc;
3414         ENTRY;
3415
3416         if (mdd_object_exists(mdd_obj) == 0) {
3417                 CERROR("%s: object "DFID" not found: rc = -2\n",
3418                        mdd_obj_dev_name(mdd_obj),PFID(mdd_object_fid(mdd_obj)));
3419                 return -ENOENT;
3420         }
3421
3422         mdd_read_lock(env, mdd_obj, MOR_TGT_CHILD);
3423         rc = mdd_readpage_sanity_check(env, mdd_obj);
3424         if (rc)
3425                 GOTO(out_unlock, rc);
3426
3427         if (mdd_is_dead_obj(mdd_obj)) {
3428                 struct page *pg;
3429                 struct lu_dirpage *dp;
3430
3431                 /*
3432                  * According to POSIX, please do not return any entry to client:
3433                  * even dot and dotdot should not be returned.
3434                  */
3435                 CDEBUG(D_INODE, "readdir from dead object: "DFID"\n",
3436                        PFID(mdd_object_fid(mdd_obj)));
3437
3438                 if (rdpg->rp_count <= 0)
3439                         GOTO(out_unlock, rc = -EFAULT);
3440                 LASSERT(rdpg->rp_pages != NULL);
3441
3442                 pg = rdpg->rp_pages[0];
3443                 dp = (struct lu_dirpage *)kmap(pg);
3444                 memset(dp, 0 , sizeof(struct lu_dirpage));
3445                 dp->ldp_hash_start = cpu_to_le64(rdpg->rp_hash);
3446                 dp->ldp_hash_end   = cpu_to_le64(MDS_DIR_END_OFF);
3447                 dp->ldp_flags = cpu_to_le32(LDF_EMPTY);
3448                 kunmap(pg);
3449                 GOTO(out_unlock, rc = LU_PAGE_SIZE);
3450         }
3451
3452         rc = dt_index_walk(env, mdd_object_child(mdd_obj), rdpg,
3453                            mdd_dir_page_build, NULL);
3454         if (rc >= 0) {
3455                 struct lu_dirpage       *dp;
3456
3457                 dp = kmap(rdpg->rp_pages[0]);
3458                 dp->ldp_hash_start = cpu_to_le64(rdpg->rp_hash);
3459                 if (rc == 0) {
3460                         /*
3461                          * No pages were processed, mark this for first page
3462                          * and send back.
3463                          */
3464                         dp->ldp_hash_end = cpu_to_le64(MDS_DIR_END_OFF);
3465                         dp->ldp_flags = cpu_to_le32(LDF_EMPTY);
3466                         rc = min_t(unsigned int, LU_PAGE_SIZE, rdpg->rp_count);
3467                 }
3468                 kunmap(rdpg->rp_pages[0]);
3469         }
3470
3471         GOTO(out_unlock, rc);
3472 out_unlock:
3473         mdd_read_unlock(env, mdd_obj);
3474         return rc;
3475 }
3476
3477 static int mdd_object_sync(const struct lu_env *env, struct md_object *obj)
3478 {
3479         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3480
3481         if (mdd_object_exists(mdd_obj) == 0) {
3482                 int rc = -ENOENT;
3483
3484                 CERROR("%s: object "DFID" not found: rc = %d\n",
3485                        mdd_obj_dev_name(mdd_obj),
3486                        PFID(mdd_object_fid(mdd_obj)), rc);
3487                 return rc;
3488         }
3489         return dt_object_sync(env, mdd_object_child(mdd_obj),
3490                               0, OBD_OBJECT_EOF);
3491 }
3492
3493 static int mdd_object_lock(const struct lu_env *env,
3494                            struct md_object *obj,
3495                            struct lustre_handle *lh,
3496                            struct ldlm_enqueue_info *einfo,
3497                            union ldlm_policy_data *policy)
3498 {
3499         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3500         return dt_object_lock(env, mdd_object_child(mdd_obj), lh,
3501                               einfo, policy);
3502 }
3503
3504 static int mdd_object_unlock(const struct lu_env *env,
3505                              struct md_object *obj,
3506                              struct ldlm_enqueue_info *einfo,
3507                              union ldlm_policy_data *policy)
3508 {
3509         struct mdd_object *mdd_obj = md2mdd_obj(obj);
3510         return dt_object_unlock(env, mdd_object_child(mdd_obj), einfo, policy);
3511 }
3512
3513 const struct md_object_operations mdd_obj_ops = {
3514         .moo_permission         = mdd_permission,
3515         .moo_attr_get           = mdd_attr_get,
3516         .moo_attr_set           = mdd_attr_set,
3517         .moo_xattr_get          = mdd_xattr_get,
3518         .moo_xattr_set          = mdd_xattr_set,
3519         .moo_xattr_list         = mdd_xattr_list,
3520         .moo_invalidate         = mdd_invalidate,
3521         .moo_xattr_del          = mdd_xattr_del,
3522         .moo_swap_layouts       = mdd_swap_layouts,
3523         .moo_open               = mdd_open,
3524         .moo_close              = mdd_close,
3525         .moo_readpage           = mdd_readpage,
3526         .moo_readlink           = mdd_readlink,
3527         .moo_changelog          = mdd_changelog,
3528         .moo_object_sync        = mdd_object_sync,
3529         .moo_object_lock        = mdd_object_lock,
3530         .moo_object_unlock      = mdd_object_unlock,
3531         .moo_layout_change      = mdd_layout_change,
3532 };