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