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