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