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