Whamcloud - gitweb
1b9a566d6bd8d1019eebe0c7a07270d040f7c345
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_handler.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  *
31  * lustre/osd/osd_handler.c
32  *
33  * Top-level entry points into osd module
34  *
35  * Author: Nikita Danilov <nikita@clusterfs.com>
36  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
37  */
38
39 #define DEBUG_SUBSYSTEM S_OSD
40
41 #include <linux/fs_struct.h>
42 #include <linux/kallsyms.h>
43 #include <linux/module.h>
44 #include <linux/user_namespace.h>
45 #include <linux/uidgid.h>
46
47 /* prerequisite for linux/xattr.h */
48 #include <linux/types.h>
49 /* prerequisite for linux/xattr.h */
50 #include <linux/fs.h>
51 /* XATTR_{REPLACE,CREATE} */
52 #include <linux/xattr.h>
53
54 #include <ldiskfs/ldiskfs.h>
55 #include <ldiskfs/xattr.h>
56 #include <ldiskfs/ldiskfs_extents.h>
57 #undef ENTRY
58 /*
59  * struct OBD_{ALLOC,FREE}*()
60  * OBD_FAIL_CHECK
61  */
62 #include <obd_support.h>
63 /* struct ptlrpc_thread */
64 #include <lustre_net.h>
65 #include <lustre_fid.h>
66 /* process_config */
67 #include <uapi/linux/lustre/lustre_param.h>
68
69 #include "osd_internal.h"
70 #include "osd_dynlocks.h"
71
72 /* llo_* api support */
73 #include <md_object.h>
74 #include <lustre_quota.h>
75
76 #include <lustre_linkea.h>
77
78 /* encoding routines */
79 #include <lustre_crypto.h>
80
81 /* Maximum EA size is limited by LNET_MTU for remote objects */
82 #define OSD_MAX_EA_SIZE 1048364
83
84 int ldiskfs_pdo = 1;
85 module_param(ldiskfs_pdo, int, 0644);
86 MODULE_PARM_DESC(ldiskfs_pdo, "ldiskfs with parallel directory operations");
87
88 int ldiskfs_track_declares_assert;
89 module_param(ldiskfs_track_declares_assert, int, 0644);
90 MODULE_PARM_DESC(ldiskfs_track_declares_assert, "LBUG during tracking of declares");
91
92 /* Slab to allocate dynlocks */
93 struct kmem_cache *dynlock_cachep;
94
95 /* Slab to allocate osd_it_ea */
96 struct kmem_cache *osd_itea_cachep;
97
98 static struct lu_kmem_descr ldiskfs_caches[] = {
99         {
100                 .ckd_cache = &dynlock_cachep,
101                 .ckd_name  = "dynlock_cache",
102                 .ckd_size  = sizeof(struct dynlock_handle)
103         },
104         {
105                 .ckd_cache = &osd_itea_cachep,
106                 .ckd_name  = "osd_itea_cache",
107                 .ckd_size  = sizeof(struct osd_it_ea)
108         },
109         {
110                 .ckd_cache = NULL
111         }
112 };
113
114 static const char dot[] = ".";
115 static const char dotdot[] = "..";
116
117 static const struct lu_object_operations      osd_lu_obj_ops;
118 static const struct dt_object_operations      osd_obj_ops;
119 static const struct dt_object_operations      osd_obj_otable_it_ops;
120 static const struct dt_index_operations       osd_index_iam_ops;
121 static const struct dt_index_operations       osd_index_ea_ops;
122
123 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
124                           const struct lu_fid *fid);
125 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
126                                                 struct osd_device *osd);
127
128 int osd_trans_declare_op2rb[] = {
129         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
130         [OSD_OT_PUNCH]          = OSD_OT_MAX,
131         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
132         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
133         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
134         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
135         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
136         [OSD_OT_WRITE]          = OSD_OT_WRITE,
137         [OSD_OT_INSERT]         = OSD_OT_DELETE,
138         [OSD_OT_DELETE]         = OSD_OT_INSERT,
139         [OSD_OT_QUOTA]          = OSD_OT_MAX,
140 };
141
142 static int osd_has_index(const struct osd_object *obj)
143 {
144         return obj->oo_dt.do_index_ops != NULL;
145 }
146
147 static int osd_object_invariant(const struct lu_object *l)
148 {
149         return osd_invariant(osd_obj(l));
150 }
151
152 /*
153  * Concurrency: doesn't matter
154  */
155 static int osd_is_write_locked(const struct lu_env *env, struct osd_object *o)
156 {
157         struct osd_thread_info *oti = osd_oti_get(env);
158
159         return oti->oti_w_locks > 0 && o->oo_owner == env;
160 }
161
162 /*
163  * Concurrency: doesn't access mutable data
164  */
165 static int osd_root_get(const struct lu_env *env,
166                         struct dt_device *dev, struct lu_fid *f)
167 {
168         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
169         return 0;
170 }
171
172 /*
173  * the following set of functions are used to maintain per-thread
174  * cache of FID->ino mapping. this mechanism is needed to resolve
175  * FID to inode at dt_insert() which in turn stores ino in the
176  * directory entries to keep ldiskfs compatible with ext[34].
177  * due to locking-originated restrictions we can't lookup ino
178  * using LU cache (deadlock is possible). lookup using OI is quite
179  * expensive. so instead we maintain this cache and methods like
180  * dt_create() fill it. so in the majority of cases dt_insert() is
181  * able to find needed mapping in lockless manner.
182  */
183 static struct osd_idmap_cache *
184 osd_idc_find(const struct lu_env *env, struct osd_device *osd,
185              const struct lu_fid *fid)
186 {
187         struct osd_thread_info *oti = osd_oti_get(env);
188         struct osd_idmap_cache *idc = oti->oti_ins_cache;
189         int i;
190
191         for (i = 0; i < oti->oti_ins_cache_used; i++) {
192                 if (!lu_fid_eq(&idc[i].oic_fid, fid))
193                         continue;
194                 if (idc[i].oic_dev != osd)
195                         continue;
196
197                 return idc + i;
198         }
199
200         return NULL;
201 }
202
203 static struct osd_idmap_cache *
204 osd_idc_add(const struct lu_env *env, struct osd_device *osd,
205             const struct lu_fid *fid)
206 {
207         struct osd_thread_info *oti   = osd_oti_get(env);
208         struct osd_idmap_cache *idc;
209         int i;
210
211         if (unlikely(oti->oti_ins_cache_used >= oti->oti_ins_cache_size)) {
212                 i = oti->oti_ins_cache_size * 2;
213                 if (i == 0)
214                         i = OSD_INS_CACHE_SIZE;
215                 OBD_ALLOC_PTR_ARRAY(idc, i);
216                 if (idc == NULL)
217                         return ERR_PTR(-ENOMEM);
218                 if (oti->oti_ins_cache != NULL) {
219                         memcpy(idc, oti->oti_ins_cache,
220                                oti->oti_ins_cache_used * sizeof(*idc));
221                         OBD_FREE_PTR_ARRAY(oti->oti_ins_cache,
222                                            oti->oti_ins_cache_used);
223                 }
224                 oti->oti_ins_cache = idc;
225                 oti->oti_ins_cache_size = i;
226         }
227
228         idc = oti->oti_ins_cache + oti->oti_ins_cache_used++;
229         idc->oic_fid = *fid;
230         idc->oic_dev = osd;
231         idc->oic_lid.oii_ino = 0;
232         idc->oic_lid.oii_gen = 0;
233         idc->oic_remote = 0;
234
235         return idc;
236 }
237
238 /*
239  * lookup mapping for the given fid in the cache, initialize a
240  * new one if not found. the initialization checks whether the
241  * object is local or remote. for local objects, OI is used to
242  * learn ino/generation. the function is used when the caller
243  * has no information about the object, e.g. at dt_insert().
244  */
245 static struct osd_idmap_cache *
246 osd_idc_find_or_init(const struct lu_env *env, struct osd_device *osd,
247                      const struct lu_fid *fid)
248 {
249         struct osd_idmap_cache *idc;
250         int rc;
251
252         idc = osd_idc_find(env, osd, fid);
253         LASSERT(!IS_ERR(idc));
254         if (idc != NULL)
255                 return idc;
256
257         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
258                osd->od_svname, PFID(fid));
259
260         /* new mapping is needed */
261         idc = osd_idc_add(env, osd, fid);
262         if (IS_ERR(idc)) {
263                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
264                        osd->od_svname, PFID(fid), PTR_ERR(idc));
265                 return idc;
266         }
267
268         /* initialize it */
269         rc = osd_remote_fid(env, osd, fid);
270         if (unlikely(rc < 0))
271                 return ERR_PTR(rc);
272
273         if (rc == 0) {
274                 /* the object is local, lookup in OI */
275                 /* XXX: probably cheaper to lookup in LU first? */
276                 rc = osd_oi_lookup(osd_oti_get(env), osd, fid,
277                                    &idc->oic_lid, 0);
278                 if (unlikely(rc < 0)) {
279                         CERROR("can't lookup: rc = %d\n", rc);
280                         return ERR_PTR(rc);
281                 }
282         } else {
283                 /* the object is remote */
284                 idc->oic_remote = 1;
285         }
286
287         return idc;
288 }
289
290 static void osd_idc_dump_lma(const struct lu_env *env,
291                                 struct osd_device *osd,
292                                 unsigned long ino,
293                                 bool check_in_oi)
294 {
295         struct osd_thread_info *info = osd_oti_get(env);
296         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
297         const struct lu_fid *fid;
298         struct osd_inode_id lid;
299         struct inode *inode;
300         int rc;
301
302         inode = osd_ldiskfs_iget(osd_sb(osd), ino);
303         if (IS_ERR(inode)) {
304                 CERROR("%s: can't get inode %lu: rc = %d\n",
305                        osd->od_svname, ino, (int)PTR_ERR(inode));
306                 return;
307         }
308         if (is_bad_inode(inode)) {
309                 CERROR("%s: bad inode %lu\n", osd->od_svname, ino);
310                 goto put;
311         }
312         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
313         if (rc) {
314                 CERROR("%s: can't get LMA for %lu: rc = %d\n",
315                        osd->od_svname, ino, rc);
316                 goto put;
317         }
318         fid = &loa->loa_lma.lma_self_fid;
319         LCONSOLE(D_INFO, "%s: "DFID" in inode %lu/%u\n", osd->od_svname,
320                       PFID(fid), ino, (unsigned)inode->i_generation);
321         if (!check_in_oi)
322                 goto put;
323         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
324         if (rc) {
325                 CERROR("%s: can't lookup "DFID": rc = %d\n",
326                        osd->od_svname, PFID(fid), rc);
327                 goto put;
328         }
329         LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n", osd->od_svname,
330                       PFID(fid), lid.oii_ino, lid.oii_gen);
331 put:
332         iput(inode);
333 }
334
335 static void osd_idc_dump_debug(const struct lu_env *env,
336                                 struct osd_device *osd,
337                                 const struct lu_fid *fid,
338                                 unsigned long ino1,
339                                 unsigned long ino2)
340 {
341         struct osd_inode_id lid;
342
343         int rc;
344
345         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
346         if (!rc) {
347                 LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n",
348                         osd->od_svname, PFID(fid), lid.oii_ino, lid.oii_gen);
349                 osd_idc_dump_lma(env, osd, lid.oii_ino, false);
350         } else {
351                 CERROR("%s: can't lookup "DFID": rc = %d\n",
352                        osd->od_svname, PFID(fid), rc);
353         }
354         if (ino1)
355                 osd_idc_dump_lma(env, osd, ino1, true);
356         if (ino2)
357                 osd_idc_dump_lma(env, osd, ino2, true);
358 }
359
360 /*
361  * lookup mapping for given FID and fill it from the given object.
362  * the object is lolcal by definition.
363  */
364 static int osd_idc_find_and_init(const struct lu_env *env,
365                                  struct osd_device *osd,
366                                  struct osd_object *obj)
367 {
368         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
369         struct osd_idmap_cache *idc;
370
371         idc = osd_idc_find(env, osd, fid);
372         LASSERT(!IS_ERR(idc));
373         if (idc != NULL) {
374                 if (obj->oo_inode == NULL)
375                         return 0;
376                 if (idc->oic_lid.oii_ino != obj->oo_inode->i_ino) {
377                         if (idc->oic_lid.oii_ino) {
378                                 osd_idc_dump_debug(env, osd, fid,
379                                                    idc->oic_lid.oii_ino,
380                                                    obj->oo_inode->i_ino);
381                                 return -EINVAL;
382                         }
383                         idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
384                         idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
385                 }
386                 return 0;
387         }
388
389         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
390                osd->od_svname, PFID(fid));
391
392         /* new mapping is needed */
393         idc = osd_idc_add(env, osd, fid);
394         if (IS_ERR(idc)) {
395                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
396                        osd->od_svname, PFID(fid), PTR_ERR(idc));
397                 return PTR_ERR(idc);
398         }
399
400         if (obj->oo_inode != NULL) {
401                 idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
402                 idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
403         }
404         return 0;
405 }
406
407 /*
408  * OSD object methods.
409  */
410
411 /*
412  * Concurrency: no concurrent access is possible that early in object
413  * life-cycle.
414  */
415 static struct lu_object *osd_object_alloc(const struct lu_env *env,
416                                           const struct lu_object_header *hdr,
417                                           struct lu_device *d)
418 {
419         struct osd_object *mo;
420
421         OBD_ALLOC_PTR(mo);
422         if (mo != NULL) {
423                 struct lu_object *l;
424                 struct lu_object_header *h;
425                 struct osd_device *o = osd_dev(d);
426
427                 l = &mo->oo_dt.do_lu;
428                 if (unlikely(o->od_in_init)) {
429                         OBD_ALLOC_PTR(h);
430                         if (!h) {
431                                 OBD_FREE_PTR(mo);
432                                 return NULL;
433                         }
434
435                         lu_object_header_init(h);
436                         lu_object_init(l, h, d);
437                         lu_object_add_top(h, l);
438                         mo->oo_header = h;
439                 } else {
440                         dt_object_init(&mo->oo_dt, NULL, d);
441                         mo->oo_header = NULL;
442                 }
443
444                 mo->oo_dt.do_ops = &osd_obj_ops;
445                 l->lo_ops = &osd_lu_obj_ops;
446                 init_rwsem(&mo->oo_sem);
447                 init_rwsem(&mo->oo_ext_idx_sem);
448                 spin_lock_init(&mo->oo_guard);
449                 INIT_LIST_HEAD(&mo->oo_xattr_list);
450                 return l;
451         }
452         return NULL;
453 }
454
455 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
456                 struct dentry *dentry, struct lustre_ost_attrs *loa)
457 {
458         int rc;
459
460         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
461                              (void *)loa, sizeof(*loa));
462         if (rc > 0) {
463                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
464
465                 if (rc < sizeof(*lma))
466                         return -EINVAL;
467
468                 rc = 0;
469                 lustre_loa_swab(loa, true);
470                 /* Check LMA compatibility */
471                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
472                         rc = -EOPNOTSUPP;
473                         CWARN("%s: unsupported incompat LMA feature(s) %#x for fid = "DFID", ino = %lu: rc = %d\n",
474                               osd_ino2name(inode),
475                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
476                               PFID(&lma->lma_self_fid), inode->i_ino, rc);
477                 }
478         } else if (rc == 0) {
479                 rc = -ENODATA;
480         }
481
482         return rc;
483 }
484
485 /*
486  * retrieve object from backend ext fs.
487  **/
488 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
489                        struct osd_inode_id *id)
490 {
491         int rc;
492         struct inode *inode = NULL;
493
494         /*
495          * if we look for an inode withing a running
496          * transaction, then we risk to deadlock
497          * osd_dirent_check_repair() breaks this
498          */
499          /* LASSERT(current->journal_info == NULL); */
500
501         inode = osd_ldiskfs_iget(osd_sb(dev), id->oii_ino);
502         if (IS_ERR(inode)) {
503                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
504                        id->oii_ino, PTR_ERR(inode));
505         } else if (id->oii_gen != OSD_OII_NOGEN &&
506                    inode->i_generation != id->oii_gen) {
507                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
508                        "i_generation = %u\n",
509                        id->oii_ino, id->oii_gen, inode->i_generation);
510                 iput(inode);
511                 inode = ERR_PTR(-ESTALE);
512         } else if (inode->i_nlink == 0) {
513                 /*
514                  * due to parallel readdir and unlink,
515                  * we can have dead inode here.
516                  */
517                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
518                 iput(inode);
519                 inode = ERR_PTR(-ESTALE);
520         } else if (is_bad_inode(inode)) {
521                 rc = -ENOENT;
522                 CWARN("%s: bad inode: ino = %u: rc = %d\n",
523                       osd_dev2name(dev), id->oii_ino, rc);
524                 iput(inode);
525                 inode = ERR_PTR(rc);
526         } else if ((rc = osd_attach_jinode(inode))) {
527                 iput(inode);
528                 inode = ERR_PTR(rc);
529         } else {
530                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
531                 if (id->oii_gen == OSD_OII_NOGEN)
532                         osd_id_gen(id, inode->i_ino, inode->i_generation);
533
534                 /*
535                  * Do not update file c/mtime in ldiskfs.
536                  * NB: we don't have any lock to protect this because we don't
537                  * have reference on osd_object now, but contention with
538                  * another lookup + attr_set can't happen in the tiny window
539                  * between if (...) and set S_NOCMTIME.
540                  */
541                 if (!(inode->i_flags & S_NOCMTIME))
542                         inode->i_flags |= S_NOCMTIME;
543         }
544         return inode;
545 }
546
547 int osd_ldiskfs_add_entry(struct osd_thread_info *info, struct osd_device *osd,
548                           handle_t *handle, struct dentry *child,
549                           struct inode *inode, struct htree_lock *hlock)
550 {
551         int rc, rc2;
552
553         rc = __ldiskfs_add_entry(handle, child, inode, hlock);
554         if (rc == -ENOBUFS || rc == -ENOSPC) {
555                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
556                 struct inode *parent = child->d_parent->d_inode;
557                 struct lu_fid *fid = NULL;
558                 char fidstr[FID_LEN + 1] = "unknown";
559
560                 rc2 = osd_get_lma(info, parent, child->d_parent, loa);
561                 if (!rc2) {
562                         fid = &loa->loa_lma.lma_self_fid;
563                 } else if (rc2 == -ENODATA) {
564                         if (unlikely(is_root_inode(parent))) {
565                                 fid = &info->oti_fid3;
566                                 lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
567                         } else if (!osd->od_is_ost && osd->od_index == 0) {
568                                 fid = &info->oti_fid3;
569                                 lu_igif_build(fid, parent->i_ino,
570                                               parent->i_generation);
571                         }
572                 }
573
574                 if (fid != NULL)
575                         snprintf(fidstr, sizeof(fidstr), DFID, PFID(fid));
576
577                 /* below message is checked in sanity.sh test_129 */
578                 if (rc == -ENOSPC) {
579                         CWARN("%s: directory (inode: %lu, FID: %s) has reached max size limit\n",
580                               osd_name(osd), parent->i_ino, fidstr);
581                 } else {
582                         rc = 0; /* ignore such error now */
583                         CWARN("%s: directory (inode: %lu, FID: %s) is approaching max size limit\n",
584                               osd_name(osd), parent->i_ino, fidstr);
585                 }
586
587         }
588
589         return rc;
590 }
591
592
593 struct inode *
594 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
595              struct osd_inode_id *id, struct lu_fid *fid)
596 {
597         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
598         struct inode *inode;
599         int rc;
600
601         inode = osd_iget(info, dev, id);
602         if (IS_ERR(inode))
603                 return inode;
604
605         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
606         if (!rc) {
607                 *fid = loa->loa_lma.lma_self_fid;
608         } else if (rc == -ENODATA) {
609                 if (unlikely(is_root_inode(inode)))
610                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
611                 else
612                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
613         } else {
614                 iput(inode);
615                 inode = ERR_PTR(rc);
616         }
617         return inode;
618 }
619
620 static struct inode *osd_iget_check(struct osd_thread_info *info,
621                                     struct osd_device *dev,
622                                     const struct lu_fid *fid,
623                                     struct osd_inode_id *id,
624                                     bool trusted)
625 {
626         struct inode *inode;
627         int rc = 0;
628
629         ENTRY;
630
631         /*
632          * The cached OI mapping is trustable. If we cannot locate the inode
633          * via the cached OI mapping, then return the failure to the caller
634          * directly without further OI checking.
635          */
636
637 again:
638         inode = osd_ldiskfs_iget(osd_sb(dev), id->oii_ino);
639         if (IS_ERR(inode)) {
640                 rc = PTR_ERR(inode);
641                 if (!trusted && (rc == -ENOENT || rc == -ESTALE))
642                         goto check_oi;
643
644                 CDEBUG(D_INODE, "no inode for FID: "DFID", ino = %u, rc = %d\n",
645                        PFID(fid), id->oii_ino, rc);
646                 GOTO(put, rc);
647         }
648
649         if (is_bad_inode(inode)) {
650                 rc = -ENOENT;
651                 if (!trusted)
652                         goto check_oi;
653
654                 CDEBUG(D_INODE, "bad inode for FID: "DFID", ino = %u\n",
655                        PFID(fid), id->oii_ino);
656                 GOTO(put, rc);
657         }
658
659         if (id->oii_gen != OSD_OII_NOGEN &&
660             inode->i_generation != id->oii_gen) {
661                 rc = -ESTALE;
662                 if (!trusted)
663                         goto check_oi;
664
665                 CDEBUG(D_INODE, "unmatched inode for FID: "DFID", ino = %u, "
666                        "oii_gen = %u, i_generation = %u\n", PFID(fid),
667                        id->oii_ino, id->oii_gen, inode->i_generation);
668                 GOTO(put, rc);
669         }
670
671         if (inode->i_nlink == 0) {
672                 rc = -ENOENT;
673                 if (!trusted)
674                         goto check_oi;
675
676                 CDEBUG(D_INODE, "stale inode for FID: "DFID", ino = %u\n",
677                        PFID(fid), id->oii_ino);
678                 GOTO(put, rc);
679         }
680
681         ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
682
683 check_oi:
684         if (rc != 0) {
685                 __u32 saved_ino = id->oii_ino;
686                 __u32 saved_gen = id->oii_gen;
687
688                 LASSERT(!trusted);
689                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
690
691                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
692                 /*
693                  * XXX: There are four possible cases:
694                  *      1. rc = 0.
695                  *         Backup/restore caused the OI invalid.
696                  *      2. rc = 0.
697                  *         Someone unlinked the object but NOT removed
698                  *         the OI mapping, such as mount target device
699                  *         as ldiskfs, and modify something directly.
700                  *      3. rc = -ENOENT.
701                  *         Someone just removed the object between the
702                  *         former oi_lookup and the iget. It is normal.
703                  *      4. Other failure cases.
704                  *
705                  *      Generally, when the device is mounted, it will
706                  *      auto check whether the system is restored from
707                  *      file-level backup or not. We trust such detect
708                  *      to distinguish the 1st case from the 2nd case:
709                  *      if the OI files are consistent but may contain
710                  *      stale OI mappings because of case 2, if iget()
711                  *      returns -ENOENT or -ESTALE, then it should be
712                  *      the case 2.
713                  */
714                 if (rc != 0)
715                         /*
716                          * If the OI mapping was in OI file before the
717                          * osd_iget_check(), but now, it is disappear,
718                          * then it must be removed by race. That is a
719                          * normal race case.
720                          */
721                         GOTO(put, rc);
722
723                 /*
724                  * It is the OI scrub updated the OI mapping by race.
725                  * The new OI mapping must be valid.
726                  */
727                 if (saved_ino != id->oii_ino ||
728                     (saved_gen != id->oii_gen && saved_gen != OSD_OII_NOGEN)) {
729                         if (!IS_ERR(inode))
730                                 iput(inode);
731
732                         trusted = true;
733                         goto again;
734                 }
735
736                 if (IS_ERR(inode)) {
737                         if (dev->od_scrub.os_scrub.os_file.sf_flags &
738                             SF_INCONSISTENT)
739                                 /*
740                                  * It still can be the case 2, but we cannot
741                                  * distinguish it from the case 1. So return
742                                  * -EREMCHG to block current operation until
743                                  *  OI scrub rebuilt the OI mappings.
744                                  */
745                                 rc = -EREMCHG;
746                         else
747                                 rc = -ENOENT;
748
749                         GOTO(put, rc);
750                 }
751
752                 if (inode->i_generation == id->oii_gen)
753                         rc = -ENOENT;
754                 else
755                         rc = -EREMCHG;
756         } else {
757                 if (id->oii_gen == OSD_OII_NOGEN)
758                         osd_id_gen(id, inode->i_ino, inode->i_generation);
759
760                 /*
761                  * Do not update file c/mtime in ldiskfs.
762                  * NB: we don't have any lock to protect this because we don't
763                  * have reference on osd_object now, but contention with
764                  * another lookup + attr_set can't happen in the tiny window
765                  * between if (...) and set S_NOCMTIME.
766                  */
767                 if (!(inode->i_flags & S_NOCMTIME))
768                         inode->i_flags |= S_NOCMTIME;
769         }
770
771         GOTO(put, rc);
772
773 put:
774         if (rc != 0) {
775                 if (!IS_ERR(inode))
776                         iput(inode);
777
778                 inode = ERR_PTR(rc);
779         }
780
781         return inode;
782 }
783
784 /**
785  * \retval +v: new filter_fid does not contain self-fid
786  * \retval 0:  filter_fid_18_23, contains self-fid
787  * \retval -v: other failure cases
788  */
789 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
790                  struct dentry *dentry, struct lu_fid *fid)
791 {
792         struct filter_fid *ff = &info->oti_ff;
793         struct ost_id *ostid = &info->oti_ostid;
794         int rc;
795
796         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
797         if (rc == sizeof(struct filter_fid_18_23)) {
798                 struct filter_fid_18_23 *ff_old = (void *)ff;
799
800                 ostid_set_seq(ostid, le64_to_cpu(ff_old->ff_seq));
801                 rc = ostid_set_id(ostid, le64_to_cpu(ff_old->ff_objid));
802                 /*
803                  * XXX: use 0 as the index for compatibility, the caller will
804                  * handle index related issues when necessary.
805                  */
806                 if (!rc)
807                         ostid_to_fid(fid, ostid, 0);
808         } else if (rc >= (int)sizeof(struct filter_fid_24_29)) {
809                 rc = 1;
810         } else if (rc >= 0) {
811                 rc = -EINVAL;
812         }
813
814         return rc;
815 }
816
817 static int osd_lma_self_repair(struct osd_thread_info *info,
818                                struct osd_device *osd, struct inode *inode,
819                                const struct lu_fid *fid, __u32 compat)
820 {
821         handle_t *jh;
822         int rc;
823
824         LASSERT(current->journal_info == NULL);
825
826         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
827                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
828         if (IS_ERR(jh)) {
829                 rc = PTR_ERR(jh);
830                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
831                       osd_name(osd), rc);
832                 return rc;
833         }
834
835         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
836         if (rc != 0)
837                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
838                       osd_name(osd), rc);
839         ldiskfs_journal_stop(jh);
840         return rc;
841 }
842
843 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
844 {
845         struct osd_thread_info *info = osd_oti_get(env);
846         struct osd_device *osd = osd_obj2dev(obj);
847         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
848         struct lustre_mdt_attrs *lma = &loa->loa_lma;
849         struct inode *inode = obj->oo_inode;
850         struct dentry *dentry = &info->oti_obj_dentry;
851         struct lu_fid *fid = NULL;
852         const struct lu_fid *rfid = lu_object_fid(&obj->oo_dt.do_lu);
853         int rc;
854
855         ENTRY;
856
857         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
858                              (void *)loa, sizeof(*loa));
859         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
860                 fid = &lma->lma_self_fid;
861                 rc = osd_get_idif(info, inode, dentry, fid);
862                 if (rc > 0 || (rc == -ENODATA && osd->od_index_in_idif)) {
863                         /*
864                          * For the given OST-object, if it has neither LMA nor
865                          * FID in XATTR_NAME_FID, then the given FID (which is
866                          * contained in the @obj, from client RPC for locating
867                          * the OST-object) is trusted. We use it to generate
868                          * the LMA.
869                          */
870                         osd_lma_self_repair(info, osd, inode, rfid,
871                                             LMAC_FID_ON_OST);
872                         RETURN(0);
873                 }
874         }
875
876         if (rc < 0)
877                 RETURN(rc);
878
879         if (rc > 0) {
880                 rc = 0;
881                 lustre_lma_swab(lma);
882                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
883                              (CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT) &&
884                               S_ISREG(inode->i_mode)))) {
885                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
886                               "fid = "DFID", ino = %lu\n", osd_name(osd),
887                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
888                               PFID(rfid), inode->i_ino);
889                         rc = -EOPNOTSUPP;
890                 } else {
891                         fid = &lma->lma_self_fid;
892                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
893                             osd->od_is_ost)
894                                 obj->oo_pfid_in_lma = 1;
895                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
896                             !osd->od_is_ost)
897                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
898                 }
899         }
900
901         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
902                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
903                         struct ost_id   *oi   = &info->oti_ostid;
904                         struct lu_fid   *fid1 = &info->oti_fid3;
905                         __u32            idx  = fid_idif_ost_idx(rfid);
906
907                         /*
908                          * For old IDIF, the OST index is not part of the IDIF,
909                          * Means that different OSTs may have the same IDIFs.
910                          * Under such case, we need to make some compatible
911                          * check to make sure to trigger OI scrub properly.
912                          */
913                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
914                                 /* Given @rfid is new, LMA is old. */
915                                 fid_to_ostid(fid, oi);
916                                 ostid_to_fid(fid1, oi, idx);
917                                 if (lu_fid_eq(fid1, rfid)) {
918                                         if (osd->od_index_in_idif)
919                                                 osd_lma_self_repair(info, osd,
920                                                         inode, rfid,
921                                                         LMAC_FID_ON_OST);
922                                         RETURN(0);
923                                 }
924                         }
925                 }
926
927                 rc = -EREMCHG;
928         }
929
930         RETURN(rc);
931 }
932
933 struct osd_check_lmv_buf {
934         /* please keep it as first member */
935         struct dir_context ctx;
936         struct osd_thread_info *oclb_info;
937         struct osd_device *oclb_dev;
938         int oclb_items;
939         bool oclb_found;
940 };
941
942 /**
943  * It is called internally by ->iterate*() to filter out the
944  * local slave object's FID of the striped directory.
945  *
946  * \retval      1 found the local slave's FID
947  * \retval      0 continue to check next item
948  * \retval      -ve for failure
949  */
950 #ifdef HAVE_FILLDIR_USE_CTX
951 static int osd_stripe_dir_filldir(struct dir_context *buf,
952 #else
953 static int osd_stripe_dir_filldir(void *buf,
954 #endif
955                                   const char *name, int namelen,
956                                   loff_t offset, __u64 ino, unsigned int d_type)
957 {
958         struct osd_check_lmv_buf *oclb = (struct osd_check_lmv_buf *)buf;
959         struct osd_thread_info *oti = oclb->oclb_info;
960         struct lu_fid *fid = &oti->oti_fid3;
961         struct osd_inode_id *id = &oti->oti_id3;
962         struct osd_device *dev = oclb->oclb_dev;
963         struct inode *inode;
964
965         oclb->oclb_items++;
966
967         if (name[0] == '.')
968                 return 0;
969
970         fid_zero(fid);
971         sscanf(name + 1, SFID, RFID(fid));
972         if (!fid_is_sane(fid))
973                 return 0;
974
975         if (osd_remote_fid(oti->oti_env, dev, fid))
976                 return 0;
977
978         osd_id_gen(id, ino, OSD_OII_NOGEN);
979         inode = osd_iget(oti, dev, id);
980         if (IS_ERR(inode))
981                 return PTR_ERR(inode);
982
983         iput(inode);
984         osd_add_oi_cache(oti, dev, id, fid);
985         osd_oii_insert(dev, fid, id, true);
986         oclb->oclb_found = true;
987
988         return 1;
989 }
990
991 /*
992  * When lookup item under striped directory, we need to locate the master
993  * MDT-object of the striped directory firstly, then the client will send
994  * lookup (getattr_by_name) RPC to the MDT with some slave MDT-object's FID
995  * and the item's name. If the system is restored from MDT file level backup,
996  * then before the OI scrub completely built the OI files, the OI mappings of
997  * the master MDT-object and slave MDT-object may be invalid. Usually, it is
998  * not a problem for the master MDT-object. Because when locate the master
999  * MDT-object, we will do name based lookup (for the striped directory itself)
1000  * firstly, during such process we can setup the correct OI mapping for the
1001  * master MDT-object. But it will be trouble for the slave MDT-object. Because
1002  * the client will not trigger name based lookup on the MDT to locate the slave
1003  * MDT-object before locating item under the striped directory, then when
1004  * osd_fid_lookup(), it will find that the OI mapping for the slave MDT-object
1005  * is invalid and does not know what the right OI mapping is, then the MDT has
1006  * to return -EINPROGRESS to the client to notify that the OI scrub is rebuiding
1007  * the OI file, related OI mapping is unknown yet, please try again later. And
1008  * then client will re-try the RPC again and again until related OI mapping has
1009  * been updated. That is quite inefficient.
1010  *
1011  * To resolve above trouble, we will handle it as the following two cases:
1012  *
1013  * 1) The slave MDT-object and the master MDT-object are on different MDTs.
1014  *    It is relative easy. Be as one of remote MDT-objects, the slave MDT-object
1015  *    is linked under /REMOTE_PARENT_DIR with the name of its FID string.
1016  *    We can locate the slave MDT-object via lookup the /REMOTE_PARENT_DIR
1017  *    directly. Please check osd_fid_lookup().
1018  *
1019  * 2) The slave MDT-object and the master MDT-object reside on the same MDT.
1020  *    Under such case, during lookup the master MDT-object, we will lookup the
1021  *    slave MDT-object via readdir against the master MDT-object, because the
1022  *    slave MDT-objects information are stored as sub-directories with the name
1023  *    "${FID}:${index}". Then when find the local slave MDT-object, its OI
1024  *    mapping will be recorded. Then subsequent osd_fid_lookup() will know
1025  *    the correct OI mapping for the slave MDT-object.
1026  */
1027 static int osd_check_lmv(struct osd_thread_info *oti, struct osd_device *dev,
1028                          struct inode *inode)
1029 {
1030         struct lu_buf *buf = &oti->oti_big_buf;
1031         struct dentry *dentry = &oti->oti_obj_dentry;
1032         struct file *filp;
1033         struct lmv_mds_md_v1 *lmv1;
1034         struct osd_check_lmv_buf oclb = {
1035                 .ctx.actor = osd_stripe_dir_filldir,
1036                 .oclb_info = oti,
1037                 .oclb_dev = dev,
1038                 .oclb_found = false,
1039         };
1040         int rc = 0;
1041
1042         ENTRY;
1043
1044 again:
1045         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, buf->lb_buf,
1046                              buf->lb_len);
1047         if (rc == -ERANGE) {
1048                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, NULL, 0);
1049                 if (rc > 0) {
1050                         lu_buf_realloc(buf, rc);
1051                         if (buf->lb_buf == NULL)
1052                                 GOTO(out, rc = -ENOMEM);
1053
1054                         goto again;
1055                 }
1056         }
1057
1058         if (unlikely(rc == 0 || rc == -ENODATA))
1059                 GOTO(out, rc = 0);
1060
1061         if (rc < 0)
1062                 GOTO(out, rc);
1063
1064         if (unlikely(buf->lb_buf == NULL)) {
1065                 lu_buf_realloc(buf, rc);
1066                 if (buf->lb_buf == NULL)
1067                         GOTO(out, rc = -ENOMEM);
1068
1069                 goto again;
1070         }
1071
1072         lmv1 = buf->lb_buf;
1073         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1074                 GOTO(out, rc = 0);
1075
1076         filp = osd_quasi_file(oti->oti_env, inode);
1077         rc = osd_security_file_alloc(filp);
1078         if (rc)
1079                 goto out;
1080
1081         do {
1082                 oclb.oclb_items = 0;
1083                 rc = iterate_dir(filp, &oclb.ctx);
1084         } while (rc >= 0 && oclb.oclb_items > 0 && !oclb.oclb_found &&
1085                  filp->f_pos != LDISKFS_HTREE_EOF_64BIT);
1086         inode->i_fop->release(inode, filp);
1087
1088 out:
1089         if (rc < 0)
1090                 CDEBUG(D_LFSCK,
1091                        "%s: cannot check LMV, ino = %lu/%u: rc = %d\n",
1092                        osd_ino2name(inode), inode->i_ino, inode->i_generation,
1093                        rc);
1094         else
1095                 rc = 0;
1096
1097         RETURN(rc);
1098 }
1099
1100 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
1101                           const struct lu_fid *fid,
1102                           const struct lu_object_conf *conf)
1103 {
1104         struct osd_thread_info *info;
1105         struct lu_device *ldev = obj->oo_dt.do_lu.lo_dev;
1106         struct osd_device *dev;
1107         struct osd_idmap_cache *oic;
1108         struct osd_inode_id *id;
1109         struct inode *inode = NULL;
1110         struct lustre_scrub *scrub;
1111         struct scrub_file *sf;
1112         __u32 flags = SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT | SS_AUTO_FULL;
1113         __u32 saved_ino;
1114         __u32 saved_gen;
1115         int result = 0;
1116         int rc1 = 0;
1117         bool remote = false;
1118         bool trusted = true;
1119         bool updated = false;
1120         bool checked = false;
1121
1122         ENTRY;
1123
1124         LINVRNT(osd_invariant(obj));
1125         LASSERT(obj->oo_inode == NULL);
1126
1127         if (fid_is_sane(fid) == 0) {
1128                 CERROR("%s: invalid FID "DFID"\n", ldev->ld_obd->obd_name,
1129                        PFID(fid));
1130                 dump_stack();
1131                 RETURN(-EINVAL);
1132         }
1133
1134         dev = osd_dev(ldev);
1135         scrub = &dev->od_scrub.os_scrub;
1136         sf = &scrub->os_file;
1137         info = osd_oti_get(env);
1138         LASSERT(info);
1139         oic = &info->oti_cache;
1140
1141         if (OBD_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
1142                 RETURN(-ENOENT);
1143
1144         /*
1145          * For the object is created as locking anchor, or for the object to
1146          * be created on disk. No need to osd_oi_lookup() at here because FID
1147          * shouldn't never be re-used, if it's really a duplicate FID from
1148          * unexpected reason, we should be able to detect it later by calling
1149          * do_create->osd_oi_insert().
1150          */
1151         if (conf && conf->loc_flags & LOC_F_NEW)
1152                 GOTO(out, result = 0);
1153
1154         /* Search order: 1. per-thread cache. */
1155         if (lu_fid_eq(fid, &oic->oic_fid) && likely(oic->oic_dev == dev)) {
1156                 id = &oic->oic_lid;
1157                 goto iget;
1158         }
1159
1160         id = &info->oti_id;
1161         if (!list_empty(&scrub->os_inconsistent_items)) {
1162                 /* Search order: 2. OI scrub pending list. */
1163                 result = osd_oii_lookup(dev, fid, id);
1164                 if (!result)
1165                         goto iget;
1166         }
1167
1168         /*
1169          * The OI mapping in the OI file can be updated by the OI scrub
1170          * when we locate the inode via FID. So it may be not trustable.
1171          */
1172         trusted = false;
1173
1174         /* Search order: 3. OI files. */
1175         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1176         if (result == -ENOENT) {
1177                 if (!(fid_is_norm(fid) || fid_is_igif(fid)) ||
1178                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
1179                     !ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
1180                                       sf->sf_oi_bitmap))
1181                         GOTO(out, result = 0);
1182
1183                 goto trigger;
1184         }
1185
1186         /* -ESTALE is returned if inode of OST object doesn't exist */
1187         if (result == -ESTALE &&
1188             fid_is_on_ost(info, dev, fid, OI_CHECK_FLD)) {
1189                 GOTO(out, result = 0);
1190         }
1191
1192         if (result)
1193                 GOTO(out, result);
1194
1195 iget:
1196         obj->oo_inode = NULL;
1197         /* for later passes through checks, not true on first pass */
1198         if (!IS_ERR_OR_NULL(inode))
1199                 iput(inode);
1200
1201         inode = osd_iget_check(info, dev, fid, id, trusted);
1202         if (!IS_ERR(inode)) {
1203                 obj->oo_inode = inode;
1204                 result = 0;
1205                 if (remote)
1206                         goto trigger;
1207
1208                 goto check_lma;
1209         }
1210
1211         result = PTR_ERR(inode);
1212         if (result == -ENOENT || result == -ESTALE)
1213                 GOTO(out, result = 0);
1214
1215         if (result != -EREMCHG)
1216                 GOTO(out, result);
1217
1218 trigger:
1219         /*
1220          * We still have chance to get the valid inode: for the
1221          * object which is referenced by remote name entry, the
1222          * object on the local MDT will be linked under the dir
1223          * of "/REMOTE_PARENT_DIR" with its FID string as name.
1224          *
1225          * We do not know whether the object for the given FID
1226          * is referenced by some remote name entry or not, and
1227          * especially for DNE II, a multiple-linked object may
1228          * have many name entries reside on many MDTs.
1229          *
1230          * To simplify the operation, OSD will not distinguish
1231          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
1232          * only happened for the RPC from other MDT during the
1233          * OI scrub, or for the client side RPC with FID only,
1234          * such as FID to path, or from old connected client.
1235          */
1236         if (!remote) {
1237                 rc1 = osd_lookup_in_remote_parent(info, dev, fid, id);
1238                 if (!rc1) {
1239                         remote = true;
1240                         trusted = true;
1241                         flags |= SS_AUTO_PARTIAL;
1242                         flags &= ~SS_AUTO_FULL;
1243                         goto iget;
1244                 }
1245         }
1246
1247         if (scrub->os_running) {
1248                 if (scrub->os_partial_scan && !scrub->os_in_join)
1249                         goto join;
1250
1251                 if (IS_ERR_OR_NULL(inode) || result) {
1252                         osd_oii_insert(dev, fid, id, result == -ENOENT);
1253                         GOTO(out, result = -EINPROGRESS);
1254                 }
1255
1256                 LASSERT(remote);
1257                 LASSERT(obj->oo_inode == inode);
1258
1259                 osd_oii_insert(dev, fid, id, true);
1260                 goto found;
1261         }
1262
1263         if (dev->od_auto_scrub_interval == AS_NEVER) {
1264                 if (!remote)
1265                         GOTO(out, result = -EREMCHG);
1266
1267                 LASSERT(!result);
1268                 LASSERT(obj->oo_inode == inode);
1269
1270                 osd_add_oi_cache(info, dev, id, fid);
1271                 goto found;
1272         }
1273
1274 join:
1275         rc1 = osd_scrub_start(env, dev, flags);
1276         CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
1277                      "%s: trigger OI scrub by RPC for "DFID"/%u with flags %#x: rc = %d\n",
1278                      osd_name(dev), PFID(fid), id->oii_ino, flags, rc1);
1279         if (rc1 && rc1 != -EALREADY)
1280                 GOTO(out, result = -EREMCHG);
1281
1282         if (IS_ERR_OR_NULL(inode) || result) {
1283                 osd_oii_insert(dev, fid, id, result == -ENOENT);
1284                 GOTO(out, result = -EINPROGRESS);
1285         }
1286
1287         LASSERT(remote);
1288         LASSERT(obj->oo_inode == inode);
1289
1290         osd_oii_insert(dev, fid, id, true);
1291         goto found;
1292
1293 check_lma:
1294         checked = true;
1295         if (unlikely(obj->oo_header))
1296                 goto found;
1297
1298         result = osd_check_lma(env, obj);
1299         if (!result)
1300                 goto found;
1301
1302         LASSERTF(id->oii_ino == inode->i_ino &&
1303                  id->oii_gen == inode->i_generation,
1304                  "locate wrong inode for FID: "DFID", %u/%u => %ld/%u\n",
1305                  PFID(fid), id->oii_ino, id->oii_gen,
1306                  inode->i_ino, inode->i_generation);
1307
1308         saved_ino = inode->i_ino;
1309         saved_gen = inode->i_generation;
1310
1311         if (unlikely(result == -ENODATA)) {
1312                 /*
1313                  * If the OI scrub updated the OI mapping by race, it
1314                  * must be valid. Trust the inode that has no LMA EA.
1315                  */
1316                 if (updated)
1317                         goto found;
1318
1319                 result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1320                 if (!result) {
1321                         /*
1322                          * The OI mapping is still there, the inode is still
1323                          * valid. It is just becaues the inode has no LMA EA.
1324                          */
1325                         if (saved_ino == id->oii_ino &&
1326                             saved_gen == id->oii_gen)
1327                                 goto found;
1328
1329                         /*
1330                          * It is the OI scrub updated the OI mapping by race.
1331                          * The new OI mapping must be valid.
1332                          */
1333                         trusted = true;
1334                         updated = true;
1335                         goto iget;
1336                 }
1337
1338                 /*
1339                  * "result == -ENOENT" means that the OI mappinghas been
1340                  * removed by race, so the inode belongs to other object.
1341                  *
1342                  * Others error can be returned  directly.
1343                  */
1344                 if (result == -ENOENT) {
1345                         LASSERT(trusted);
1346
1347                         obj->oo_inode = NULL;
1348                         result = 0;
1349                 }
1350         }
1351
1352         if (result != -EREMCHG)
1353                 GOTO(out, result);
1354
1355         LASSERT(!updated);
1356
1357         /*
1358          * if two OST objects map to the same inode, and inode mode is
1359          * (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666), which means it's
1360          * reserved by precreate, and not written yet, in this case, don't
1361          * set inode for the object whose FID mismatch, so that it can create
1362          * inode and not block precreate.
1363          */
1364         if (fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) &&
1365             inode->i_mode == (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666)) {
1366                 obj->oo_inode = NULL;
1367                 GOTO(out, result = 0);
1368         }
1369
1370         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1371         /*
1372          * "result == -ENOENT" means the cached OI mapping has been removed
1373          * from the OI file by race, above inode belongs to other object.
1374          */
1375         if (result == -ENOENT) {
1376                 LASSERT(trusted);
1377
1378                 obj->oo_inode = NULL;
1379                 GOTO(out, result = 0);
1380         }
1381
1382         if (result)
1383                 GOTO(out, result);
1384
1385         if (saved_ino == id->oii_ino && saved_gen == id->oii_gen) {
1386                 result = -EREMCHG;
1387                 osd_scrub_refresh_mapping(info, dev, fid, id, DTO_INDEX_DELETE,
1388                                           true, 0, NULL);
1389                 goto trigger;
1390         }
1391
1392         /*
1393          * It is the OI scrub updated the OI mapping by race.
1394          * The new OI mapping must be valid.
1395          */
1396         trusted = true;
1397         updated = true;
1398         goto iget;
1399
1400 found:
1401         if (!checked) {
1402                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
1403                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
1404
1405                 result = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
1406                 if (!result) {
1407                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
1408                             dev->od_is_ost)
1409                                 obj->oo_pfid_in_lma = 1;
1410                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
1411                             !dev->od_is_ost)
1412                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
1413                 } else if (result != -ENODATA) {
1414                         GOTO(out, result);
1415                 }
1416         }
1417
1418         obj->oo_compat_dot_created = 1;
1419         obj->oo_compat_dotdot_created = 1;
1420
1421         if (S_ISDIR(inode->i_mode) &&
1422             (flags & SS_AUTO_PARTIAL || sf->sf_status == SS_SCANNING))
1423                 osd_check_lmv(info, dev, inode);
1424
1425         result = osd_attach_jinode(inode);
1426         if (result)
1427                 GOTO(out, result);
1428
1429         if (!ldiskfs_pdo)
1430                 GOTO(out, result = 0);
1431
1432         LASSERT(!obj->oo_hl_head);
1433         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1434
1435         GOTO(out, result = (!obj->oo_hl_head ? -ENOMEM : 0));
1436
1437 out:
1438         if (result || !obj->oo_inode) {
1439                 if (!IS_ERR_OR_NULL(inode))
1440                         iput(inode);
1441
1442                 obj->oo_inode = NULL;
1443                 if (trusted)
1444                         fid_zero(&oic->oic_fid);
1445         }
1446
1447         LINVRNT(osd_invariant(obj));
1448         return result;
1449 }
1450
1451 /*
1452  * Concurrency: shouldn't matter.
1453  */
1454 static void osd_object_init0(struct osd_object *obj)
1455 {
1456         LASSERT(obj->oo_inode != NULL);
1457         obj->oo_dt.do_body_ops = &osd_body_ops;
1458         obj->oo_dt.do_lu.lo_header->loh_attr |=
1459                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
1460 }
1461
1462 /*
1463  * Concurrency: no concurrent access is possible that early in object
1464  * life-cycle.
1465  */
1466 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1467                            const struct lu_object_conf *conf)
1468 {
1469         struct osd_object *obj = osd_obj(l);
1470         int result;
1471
1472         LINVRNT(osd_invariant(obj));
1473
1474         if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_LLOG_UMOUNT_RACE) &&
1475             cfs_fail_val == 2) {
1476                 struct osd_thread_info *info = osd_oti_get(env);
1477                 struct osd_idmap_cache *oic = &info->oti_cache;
1478                 /* invalidate thread cache */
1479                 memset(&oic->oic_fid, 0, sizeof(oic->oic_fid));
1480         }
1481         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1482                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1483                 l->lo_header->loh_attr |= LOHA_EXISTS;
1484                 return 0;
1485         }
1486
1487         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1488         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1489         if (result == 0 && obj->oo_inode != NULL) {
1490                 struct osd_thread_info *oti = osd_oti_get(env);
1491                 struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
1492
1493                 osd_object_init0(obj);
1494                 if (unlikely(obj->oo_header))
1495                         return 0;
1496
1497                 result = osd_get_lma(oti, obj->oo_inode,
1498                                      &oti->oti_obj_dentry, loa);
1499                 if (!result) {
1500                         /*
1501                          * Convert LMAI flags to lustre LMA flags
1502                          * and cache it to oo_lma_flags
1503                          */
1504                         obj->oo_lma_flags =
1505                                 lma_to_lustre_flags(loa->loa_lma.lma_incompat);
1506                 } else if (result == -ENODATA) {
1507                         result = 0;
1508                 }
1509         }
1510         obj->oo_dirent_count = LU_DIRENT_COUNT_UNSET;
1511
1512         LINVRNT(osd_invariant(obj));
1513         return result;
1514 }
1515
1516 /*
1517  * The first part of oxe_buf is xattr name, and is '\0' terminated.
1518  * The left part is for value, binary mode.
1519  */
1520 struct osd_xattr_entry {
1521         struct list_head        oxe_list;
1522         size_t                  oxe_len;
1523         size_t                  oxe_namelen;
1524         bool                    oxe_exist;
1525         struct rcu_head         oxe_rcu;
1526         char                    oxe_buf[0];
1527 };
1528
1529 static int osd_oxc_get(struct osd_object *obj, const char *name,
1530                        struct lu_buf *buf)
1531 {
1532         struct osd_xattr_entry *tmp;
1533         struct osd_xattr_entry *oxe = NULL;
1534         size_t namelen = strlen(name);
1535         int rc;
1536
1537         rcu_read_lock();
1538         list_for_each_entry_rcu(tmp, &obj->oo_xattr_list, oxe_list) {
1539                 if (namelen == tmp->oxe_namelen &&
1540                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1541                         oxe = tmp;
1542                         break;
1543                 }
1544         }
1545
1546         if (oxe == NULL)
1547                 GOTO(out, rc = -ENOENT);
1548
1549         if (!oxe->oxe_exist)
1550                 GOTO(out, rc = -ENODATA);
1551
1552         /* vallen */
1553         rc = oxe->oxe_len - sizeof(*oxe) - oxe->oxe_namelen - 1;
1554         LASSERT(rc > 0);
1555
1556         if (buf->lb_buf == NULL)
1557                 GOTO(out, rc);
1558
1559         if (buf->lb_len < rc)
1560                 GOTO(out, rc = -ERANGE);
1561
1562         memcpy(buf->lb_buf, &oxe->oxe_buf[namelen + 1], rc);
1563 out:
1564         rcu_read_unlock();
1565
1566         return rc;
1567 }
1568
1569 static void osd_oxc_free(struct rcu_head *head)
1570 {
1571         struct osd_xattr_entry *oxe;
1572
1573         oxe = container_of(head, struct osd_xattr_entry, oxe_rcu);
1574         OBD_FREE(oxe, oxe->oxe_len);
1575 }
1576
1577 static void osd_oxc_add(struct osd_object *obj, const char *name,
1578                         const char *buf, int buflen)
1579 {
1580         struct osd_xattr_entry *oxe;
1581         struct osd_xattr_entry *old = NULL;
1582         struct osd_xattr_entry *tmp;
1583         size_t namelen = strlen(name);
1584         size_t len = sizeof(*oxe) + namelen + 1 + buflen;
1585
1586         OBD_ALLOC(oxe, len);
1587         if (oxe == NULL)
1588                 return;
1589
1590         INIT_LIST_HEAD(&oxe->oxe_list);
1591         oxe->oxe_len = len;
1592         oxe->oxe_namelen = namelen;
1593         memcpy(oxe->oxe_buf, name, namelen);
1594         if (buflen > 0) {
1595                 LASSERT(buf != NULL);
1596                 memcpy(oxe->oxe_buf + namelen + 1, buf, buflen);
1597                 oxe->oxe_exist = true;
1598         } else {
1599                 oxe->oxe_exist = false;
1600         }
1601
1602         /* this should be rarely called, just remove old and add new */
1603         spin_lock(&obj->oo_guard);
1604         list_for_each_entry(tmp, &obj->oo_xattr_list, oxe_list) {
1605                 if (namelen == tmp->oxe_namelen &&
1606                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1607                         old = tmp;
1608                         break;
1609                 }
1610         }
1611         if (old != NULL) {
1612                 list_replace_rcu(&old->oxe_list, &oxe->oxe_list);
1613                 call_rcu(&old->oxe_rcu, osd_oxc_free);
1614         } else {
1615                 list_add_tail_rcu(&oxe->oxe_list, &obj->oo_xattr_list);
1616         }
1617         spin_unlock(&obj->oo_guard);
1618 }
1619
1620 static void osd_oxc_del(struct osd_object *obj, const char *name)
1621 {
1622         struct osd_xattr_entry *oxe;
1623         size_t namelen = strlen(name);
1624
1625         spin_lock(&obj->oo_guard);
1626         list_for_each_entry(oxe, &obj->oo_xattr_list, oxe_list) {
1627                 if (namelen == oxe->oxe_namelen &&
1628                     strncmp(name, oxe->oxe_buf, namelen) == 0) {
1629                         list_del_rcu(&oxe->oxe_list);
1630                         call_rcu(&oxe->oxe_rcu, osd_oxc_free);
1631                         break;
1632                 }
1633         }
1634         spin_unlock(&obj->oo_guard);
1635 }
1636
1637 static void osd_oxc_fini(struct osd_object *obj)
1638 {
1639         struct osd_xattr_entry *oxe, *next;
1640
1641         list_for_each_entry_safe(oxe, next, &obj->oo_xattr_list, oxe_list) {
1642                 list_del(&oxe->oxe_list);
1643                 OBD_FREE(oxe, oxe->oxe_len);
1644         }
1645 }
1646
1647 /*
1648  * Concurrency: no concurrent access is possible that late in object
1649  * life-cycle.
1650  */
1651 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1652 {
1653         struct osd_object *obj = osd_obj(l);
1654         struct lu_object_header *h = obj->oo_header;
1655
1656         LINVRNT(osd_invariant(obj));
1657
1658         osd_oxc_fini(obj);
1659         dt_object_fini(&obj->oo_dt);
1660         if (obj->oo_hl_head != NULL)
1661                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1662         /* obj doesn't contain an lu_object_header, so we don't need call_rcu */
1663         OBD_FREE_PTR(obj);
1664         if (unlikely(h))
1665                 lu_object_header_free(h);
1666 }
1667
1668 /*
1669  * Concurrency: no concurrent access is possible that late in object
1670  * life-cycle.
1671  */
1672 static void osd_index_fini(struct osd_object *o)
1673 {
1674         struct iam_container *bag;
1675
1676         if (o->oo_dir != NULL) {
1677                 bag = &o->oo_dir->od_container;
1678                 if (o->oo_inode != NULL) {
1679                         if (bag->ic_object == o->oo_inode)
1680                                 iam_container_fini(bag);
1681                 }
1682                 OBD_FREE_PTR(o->oo_dir);
1683                 o->oo_dir = NULL;
1684         }
1685 }
1686
1687 enum {
1688         OSD_TXN_OI_DELETE_CREDITS    = 20,
1689         OSD_TXN_INODE_DELETE_CREDITS = 20
1690 };
1691
1692 /*
1693  * Journal
1694  */
1695
1696 #if OSD_THANDLE_STATS
1697 /**
1698  * Set time when the handle is allocated
1699  */
1700 static void osd_th_alloced(struct osd_thandle *oth)
1701 {
1702         oth->oth_alloced = ktime_get();
1703 }
1704
1705 /**
1706  * Set time when the handle started
1707  */
1708 static void osd_th_started(struct osd_thandle *oth)
1709 {
1710         oth->oth_started = ktime_get();
1711 }
1712
1713 /**
1714  * Check whether the we deal with this handle for too long.
1715  */
1716 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1717                                 ktime_t alloced, ktime_t started,
1718                                 ktime_t closed)
1719 {
1720         ktime_t now = ktime_get();
1721
1722         LASSERT(dev != NULL);
1723
1724         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1725                             ktime_us_delta(started, alloced));
1726         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1727                             ktime_us_delta(closed, started));
1728         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1729                             ktime_us_delta(now, closed));
1730
1731         if (ktime_before(ktime_add_ns(alloced, 30 * NSEC_PER_SEC), now)) {
1732                 CWARN("transaction handle %p was open for too long: now %lld, alloced %lld, started %lld, closed %lld\n",
1733                                 oth, now, alloced, started, closed);
1734                 libcfs_debug_dumpstack(NULL);
1735         }
1736 }
1737
1738 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1739 {                                                                       \
1740         ktime_t __closed = ktime_get();                                 \
1741         ktime_t __alloced = oth->oth_alloced;                           \
1742         ktime_t __started = oth->oth_started;                           \
1743                                                                         \
1744         expr;                                                           \
1745         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1746 }
1747
1748 #else /* OSD_THANDLE_STATS */
1749
1750 #define osd_th_alloced(h)                  do {} while(0)
1751 #define osd_th_started(h)                  do {} while(0)
1752 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1753
1754 #endif /* OSD_THANDLE_STATS */
1755
1756 /*
1757  * Concurrency: doesn't access mutable data.
1758  */
1759 static int osd_param_is_not_sane(const struct osd_device *dev,
1760                                  const struct thandle *th)
1761 {
1762         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1763
1764         return oh->ot_credits > osd_transaction_size(dev);
1765 }
1766
1767 /*
1768  * Concurrency: shouldn't matter.
1769  */
1770 static void osd_trans_commit_cb(struct super_block *sb,
1771                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1772 {
1773         struct osd_thandle *oh = container_of(jcb, struct osd_thandle, ot_jcb);
1774         struct thandle *th = &oh->ot_super;
1775         struct lu_device *lud = &th->th_dev->dd_lu_dev;
1776         struct osd_device *osd = osd_dev(lud);
1777         struct dt_txn_commit_cb *dcb, *tmp;
1778
1779         LASSERT(oh->ot_handle == NULL);
1780
1781         if (error)
1782                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1783
1784         OBD_FAIL_TIMEOUT(OBD_FAIL_OST_DELAY_TRANS, 40);
1785         /* call per-transaction callbacks if any */
1786         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1787                                  dcb_linkage) {
1788                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1789                          "commit callback entry: magic=%x name='%s'\n",
1790                          dcb->dcb_magic, dcb->dcb_name);
1791                 list_del_init(&dcb->dcb_linkage);
1792                 dcb->dcb_func(NULL, th, dcb, error);
1793         }
1794
1795         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1796         if (atomic_dec_and_test(&osd->od_commit_cb_in_flight))
1797                 wake_up(&osd->od_commit_cb_done);
1798         th->th_dev = NULL;
1799
1800         OBD_FREE_PTR(oh);
1801 }
1802
1803 static struct thandle *osd_trans_create(const struct lu_env *env,
1804                                         struct dt_device *d)
1805 {
1806         struct osd_thread_info *oti = osd_oti_get(env);
1807         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1808         struct osd_thandle *oh;
1809         struct thandle *th;
1810
1811         ENTRY;
1812
1813         if (d->dd_rdonly) {
1814                 CERROR("%s: someone try to start transaction under "
1815                        "readonly mode, should be disabled.\n",
1816                        osd_name(osd_dt_dev(d)));
1817                 dump_stack();
1818                 RETURN(ERR_PTR(-EROFS));
1819         }
1820
1821         /* on pending IO in this thread should left from prev. request */
1822         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1823
1824         sb_start_write(osd_sb(osd_dt_dev(d)));
1825
1826         OBD_ALLOC_GFP(oh, sizeof(*oh), GFP_NOFS);
1827         if (!oh) {
1828                 sb_end_write(osd_sb(osd_dt_dev(d)));
1829                 RETURN(ERR_PTR(-ENOMEM));
1830         }
1831
1832         oh->ot_quota_trans = &oti->oti_quota_trans;
1833         memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1834         th = &oh->ot_super;
1835         th->th_dev = d;
1836         th->th_result = 0;
1837         oh->ot_credits = 0;
1838         oh->oh_declared_ext = 0;
1839         INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1840         INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1841         INIT_LIST_HEAD(&oh->ot_trunc_locks);
1842         osd_th_alloced(oh);
1843
1844         memset(oti->oti_declare_ops, 0,
1845                sizeof(oti->oti_declare_ops));
1846         memset(oti->oti_declare_ops_cred, 0,
1847                sizeof(oti->oti_declare_ops_cred));
1848         memset(oti->oti_declare_ops_used, 0,
1849                sizeof(oti->oti_declare_ops_used));
1850
1851         oti->oti_ins_cache_depth++;
1852
1853         RETURN(th);
1854 }
1855
1856 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1857 {
1858         struct osd_thread_info *oti = osd_oti_get(env);
1859         struct osd_thandle *oh;
1860
1861         oh = container_of(th, struct osd_thandle, ot_super);
1862         LASSERT(oh != NULL);
1863
1864         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1865               oti->oti_declare_ops[OSD_OT_CREATE],
1866               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1867               oti->oti_declare_ops_used[OSD_OT_CREATE],
1868               oti->oti_declare_ops[OSD_OT_DESTROY],
1869               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1870               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1871         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1872               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1873               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1874               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1875               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1876               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1877               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1878         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1879               oti->oti_declare_ops[OSD_OT_WRITE],
1880               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1881               oti->oti_declare_ops_used[OSD_OT_WRITE],
1882               oti->oti_declare_ops[OSD_OT_PUNCH],
1883               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1884               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1885               oti->oti_declare_ops[OSD_OT_QUOTA],
1886               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1887               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1888         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1889               oti->oti_declare_ops[OSD_OT_INSERT],
1890               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1891               oti->oti_declare_ops_used[OSD_OT_INSERT],
1892               oti->oti_declare_ops[OSD_OT_DELETE],
1893               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1894               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1895         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1896               oti->oti_declare_ops[OSD_OT_REF_ADD],
1897               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1898               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
1899               oti->oti_declare_ops[OSD_OT_REF_DEL],
1900               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
1901               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
1902 }
1903
1904 /*
1905  * Concurrency: shouldn't matter.
1906  */
1907 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1908                            struct thandle *th)
1909 {
1910         struct osd_thread_info *oti = osd_oti_get(env);
1911         struct osd_device *dev = osd_dt_dev(d);
1912         handle_t *jh;
1913         struct osd_thandle *oh;
1914         int rc;
1915
1916         ENTRY;
1917
1918         LASSERT(current->journal_info == NULL);
1919
1920         oh = container_of(th, struct osd_thandle, ot_super);
1921         LASSERT(oh != NULL);
1922         LASSERT(oh->ot_handle == NULL);
1923
1924         rc = dt_txn_hook_start(env, d, th);
1925         if (rc != 0)
1926                 GOTO(out, rc);
1927
1928         if (unlikely(osd_param_is_not_sane(dev, th))) {
1929                 static unsigned long last_printed;
1930                 static int last_credits;
1931
1932                 /*
1933                  * don't make noise on a tiny testing systems
1934                  * actual credits misuse will be caught anyway
1935                  */
1936                 if (last_credits != oh->ot_credits &&
1937                     time_after(jiffies, last_printed +
1938                                cfs_time_seconds(60)) &&
1939                     osd_transaction_size(dev) > 512) {
1940                         CWARN("%s: credits %u > trans_max %u\n", osd_name(dev),
1941                               oh->ot_credits, osd_transaction_size(dev));
1942                         osd_trans_dump_creds(env, th);
1943                         libcfs_debug_dumpstack(NULL);
1944                         last_credits = oh->ot_credits;
1945                         last_printed = jiffies;
1946                 }
1947                 /*
1948                  * XXX Limit the credits to 'max_transaction_buffers', and
1949                  *     let the underlying filesystem to catch the error if
1950                  *     we really need so many credits.
1951                  *
1952                  *     This should be removed when we can calculate the
1953                  *     credits precisely.
1954                  */
1955                 oh->ot_credits = osd_transaction_size(dev);
1956         } else if (ldiskfs_track_declares_assert != 0) {
1957                 /*
1958                  * reserve few credits to prevent an assertion in JBD
1959                  * our debugging mechanism will be able to detected
1960                  * overuse. this can help to debug single-update
1961                  * transactions
1962                  */
1963                 oh->ot_credits += 10;
1964                 if (unlikely(osd_param_is_not_sane(dev, th)))
1965                         oh->ot_credits = osd_transaction_size(dev);
1966         }
1967
1968         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_TXN_START))
1969                 GOTO(out, rc = -EIO);
1970
1971         /*
1972          * XXX temporary stuff. Some abstraction layer should
1973          * be used.
1974          */
1975         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1976         osd_th_started(oh);
1977         if (!IS_ERR(jh)) {
1978                 oh->ot_handle = jh;
1979                 LASSERT(oti->oti_txns == 0);
1980
1981                 atomic_inc(&dev->od_commit_cb_in_flight);
1982                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
1983                               "osd-tx", th);
1984                 oti->oti_txns++;
1985                 rc = 0;
1986         } else {
1987                 rc = PTR_ERR(jh);
1988         }
1989 out:
1990         RETURN(rc);
1991 }
1992
1993 static int osd_seq_exists(const struct lu_env *env,
1994                           struct osd_device *osd, u64 seq)
1995 {
1996         struct lu_seq_range *range = &osd_oti_get(env)->oti_seq_range;
1997         struct seq_server_site *ss = osd_seq_site(osd);
1998         int rc;
1999
2000         ENTRY;
2001
2002         LASSERT(ss != NULL);
2003         LASSERT(ss->ss_server_fld != NULL);
2004
2005         rc = osd_fld_lookup(env, osd, seq, range);
2006         if (rc != 0) {
2007                 if (rc != -ENOENT)
2008                         CERROR("%s: can't lookup FLD sequence %#llx: rc = %d\n",
2009                                osd_name(osd), seq, rc);
2010                 RETURN(0);
2011         }
2012
2013         RETURN(ss->ss_node_id == range->lsr_index);
2014 }
2015
2016 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
2017 {
2018         struct dt_txn_commit_cb *dcb;
2019         struct dt_txn_commit_cb *tmp;
2020
2021         /* call per-transaction stop callbacks if any */
2022         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
2023                                  dcb_linkage) {
2024                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
2025                          "commit callback entry: magic=%x name='%s'\n",
2026                          dcb->dcb_magic, dcb->dcb_name);
2027                 list_del_init(&dcb->dcb_linkage);
2028                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
2029         }
2030 }
2031
2032 /*
2033  * Concurrency: shouldn't matter.
2034  */
2035 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
2036                           struct thandle *th)
2037 {
2038         struct osd_thread_info *oti = osd_oti_get(env);
2039         struct osd_thandle *oh;
2040         struct osd_iobuf *iobuf = &oti->oti_iobuf;
2041         struct osd_device *osd = osd_dt_dev(th->th_dev);
2042         struct qsd_instance *qsd = osd_def_qsd(osd);
2043         struct lquota_trans *qtrans;
2044         LIST_HEAD(truncates);
2045         int rc = 0, remove_agents = 0;
2046
2047         ENTRY;
2048
2049         oh = container_of(th, struct osd_thandle, ot_super);
2050
2051         remove_agents = oh->ot_remove_agents;
2052
2053         qtrans = oh->ot_quota_trans;
2054         oh->ot_quota_trans = NULL;
2055
2056         /* move locks to local list, stop tx, execute truncates */
2057         list_splice(&oh->ot_trunc_locks, &truncates);
2058
2059         if (oh->ot_handle != NULL) {
2060                 int rc2;
2061
2062                 handle_t *hdl = oh->ot_handle;
2063
2064                 /*
2065                  * add commit callback
2066                  * notice we don't do this in osd_trans_start()
2067                  * as underlying transaction can change during truncate
2068                  */
2069                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
2070                                              &oh->ot_jcb);
2071
2072                 LASSERT(oti->oti_txns == 1);
2073                 oti->oti_txns--;
2074
2075                 rc = dt_txn_hook_stop(env, th);
2076                 if (rc != 0)
2077                         CERROR("%s: failed in transaction hook: rc = %d\n",
2078                                osd_name(osd), rc);
2079
2080                 osd_trans_stop_cb(oh, rc);
2081                 /* hook functions might modify th_sync */
2082                 hdl->h_sync = th->th_sync;
2083
2084                 oh->ot_handle = NULL;
2085                 OSD_CHECK_SLOW_TH(oh, osd, rc2 = ldiskfs_journal_stop(hdl));
2086                 if (rc2 != 0)
2087                         CERROR("%s: failed to stop transaction: rc = %d\n",
2088                                osd_name(osd), rc2);
2089                 if (!rc)
2090                         rc = rc2;
2091
2092                 osd_process_truncates(env, &truncates);
2093         } else {
2094                 osd_trans_stop_cb(oh, th->th_result);
2095                 OBD_FREE_PTR(oh);
2096         }
2097
2098         osd_trunc_unlock_all(env, &truncates);
2099
2100         /* inform the quota slave device that the transaction is stopping */
2101         qsd_op_end(env, qsd, qtrans);
2102
2103         /*
2104          * as we want IO to journal and data IO be concurrent, we don't block
2105          * awaiting data IO completion in osd_do_bio(), instead we wait here
2106          * once transaction is submitted to the journal. all reqular requests
2107          * don't do direct IO (except read/write), thus this wait_event becomes
2108          * no-op for them.
2109          *
2110          * IMPORTANT: we have to wait till any IO submited by the thread is
2111          * completed otherwise iobuf may be corrupted by different request
2112          */
2113         wait_event(iobuf->dr_wait,
2114                        atomic_read(&iobuf->dr_numreqs) == 0);
2115         osd_fini_iobuf(osd, iobuf);
2116         if (!rc)
2117                 rc = iobuf->dr_error;
2118
2119         if (unlikely(remove_agents != 0))
2120                 osd_process_scheduled_agent_removals(env, osd);
2121
2122         LASSERT(oti->oti_ins_cache_depth > 0);
2123         oti->oti_ins_cache_depth--;
2124         /* reset OI cache for safety */
2125         if (oti->oti_ins_cache_depth == 0)
2126                 oti->oti_ins_cache_used = 0;
2127
2128         sb_end_write(osd_sb(osd));
2129
2130         RETURN(rc);
2131 }
2132
2133 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
2134 {
2135         struct osd_thandle *oh = container_of(th, struct osd_thandle,
2136                                               ot_super);
2137
2138         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
2139         LASSERT(&dcb->dcb_func != NULL);
2140         if (dcb->dcb_flags & DCB_TRANS_STOP)
2141                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
2142         else
2143                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
2144
2145         return 0;
2146 }
2147
2148 /*
2149  * Called just before object is freed. Releases all resources except for
2150  * object itself (that is released by osd_object_free()).
2151  *
2152  * Concurrency: no concurrent access is possible that late in object
2153  * life-cycle.
2154  */
2155 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
2156 {
2157         struct osd_object *obj = osd_obj(l);
2158         struct qsd_instance *qsd = osd_def_qsd(osd_obj2dev(obj));
2159         struct inode *inode = obj->oo_inode;
2160         __u64 projid;
2161         qid_t uid;
2162         qid_t gid;
2163
2164         LINVRNT(osd_invariant(obj));
2165
2166         /*
2167          * If object is unlinked remove fid->ino mapping from object index.
2168          */
2169
2170         osd_index_fini(obj);
2171
2172         if (!inode)
2173                 return;
2174
2175         if (osd_has_index(obj) &&  obj->oo_dt.do_index_ops == &osd_index_iam_ops)
2176                 ldiskfs_set_inode_flag(inode, LDISKFS_INODE_JOURNAL_DATA);
2177
2178         uid = i_uid_read(inode);
2179         gid = i_gid_read(inode);
2180         projid = i_projid_read(inode);
2181
2182         obj->oo_inode = NULL;
2183         iput(inode);
2184
2185         /* do not rebalance quota if the caller needs to release memory
2186          * otherwise qsd_refresh_usage() may went into a new ldiskfs
2187          * transaction and risk to deadlock - LU-12178 */
2188         if (current->flags & (PF_MEMALLOC | PF_KSWAPD))
2189                 return;
2190
2191         if (!obj->oo_header && qsd) {
2192                 struct osd_thread_info *info = osd_oti_get(env);
2193                 struct lquota_id_info *qi = &info->oti_qi;
2194
2195                 /* Release granted quota to master if necessary */
2196                 qi->lqi_id.qid_uid = uid;
2197                 qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
2198
2199                 qi->lqi_id.qid_uid = gid;
2200                 qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
2201
2202                 qi->lqi_id.qid_uid = projid;
2203                 qsd_op_adjust(env, qsd, &qi->lqi_id, PRJQUOTA);
2204         }
2205 }
2206
2207 /*
2208  * Concurrency: ->loo_object_release() is called under site spin-lock.
2209  */
2210 static void osd_object_release(const struct lu_env *env,
2211                                struct lu_object *l)
2212 {
2213         struct osd_object *o = osd_obj(l);
2214
2215         /*
2216          * nobody should be releasing a non-destroyed object with nlink=0
2217          * the API allows this, but ldiskfs doesn't like and then report
2218          * this inode as deleted
2219          */
2220         LASSERT(!(o->oo_destroyed == 0 && o->oo_inode &&
2221                   o->oo_inode->i_nlink == 0));
2222 }
2223
2224 /*
2225  * Concurrency: shouldn't matter.
2226  */
2227 static int osd_object_print(const struct lu_env *env, void *cookie,
2228                             lu_printer_t p, const struct lu_object *l)
2229 {
2230         struct osd_object *o = osd_obj(l);
2231         struct iam_descr *d;
2232
2233         if (o->oo_dir != NULL)
2234                 d = o->oo_dir->od_container.ic_descr;
2235         else
2236                 d = NULL;
2237         return (*p)(env, cookie,
2238                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
2239                     o, o->oo_inode,
2240                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
2241                     o->oo_inode ? o->oo_inode->i_generation : 0,
2242                     d ? d->id_ops->id_name : "plain");
2243 }
2244
2245 /*
2246  * Concurrency: shouldn't matter.
2247  */
2248 int osd_statfs(const struct lu_env *env, struct dt_device *d,
2249                 struct obd_statfs *sfs, struct obd_statfs_info *info)
2250 {
2251         struct osd_device *osd = osd_dt_dev(d);
2252         struct super_block *sb = osd_sb(osd);
2253         struct kstatfs *ksfs;
2254         __u64 reserved;
2255         int result = 0;
2256
2257         if (unlikely(osd->od_mnt == NULL))
2258                 return -EINPROGRESS;
2259
2260         /* osd_lproc.c call this without env, allocate ksfs for that case */
2261         if (unlikely(env == NULL)) {
2262                 OBD_ALLOC_PTR(ksfs);
2263                 if (ksfs == NULL)
2264                         return -ENOMEM;
2265         } else {
2266                 ksfs = &osd_oti_get(env)->oti_ksfs;
2267         }
2268
2269         result = sb->s_op->statfs(sb->s_root, ksfs);
2270         if (result)
2271                 goto out;
2272
2273         statfs_pack(sfs, ksfs);
2274         if (unlikely(sb->s_flags & SB_RDONLY))
2275                 sfs->os_state |= OS_STATFS_READONLY;
2276
2277         sfs->os_state |= osd->od_nonrotational ? OS_STATFS_NONROT : 0;
2278
2279         if (ldiskfs_has_feature_extents(sb))
2280                 sfs->os_maxbytes = sb->s_maxbytes;
2281         else
2282                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2283
2284         /*
2285          * Reserve some space so to avoid fragmenting the filesystem too much.
2286          * Fragmentation not only impacts performance, but can also increase
2287          * metadata overhead significantly, causing grant calculation to be
2288          * wrong.
2289          *
2290          * Reserve 0.78% of total space, at least 8MB for small filesystems.
2291          */
2292         BUILD_BUG_ON(OSD_STATFS_RESERVED <= LDISKFS_MAX_BLOCK_SIZE);
2293         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
2294         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
2295                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
2296
2297         sfs->os_blocks -= reserved;
2298         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
2299         sfs->os_bavail -= min(reserved, sfs->os_bavail);
2300
2301 out:
2302         if (unlikely(env == NULL))
2303                 OBD_FREE_PTR(ksfs);
2304         return result;
2305 }
2306
2307 /**
2308  * Estimate space needed for file creations. We assume the largest filename
2309  * which is 2^64 - 1, hence a filename of 20 chars.
2310  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
2311  */
2312 #ifdef __LDISKFS_DIR_REC_LEN
2313 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
2314 #else
2315 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
2316 #endif
2317
2318 /*
2319  * Concurrency: doesn't access mutable data.
2320  */
2321 static void osd_conf_get(const struct lu_env *env,
2322                          const struct dt_device *dev,
2323                          struct dt_device_param *param)
2324 {
2325         struct osd_device *d = osd_dt_dev(dev);
2326         struct super_block *sb = osd_sb(d);
2327         struct blk_integrity *bi = bdev_get_integrity(sb->s_bdev);
2328         const char *name;
2329         int ea_overhead;
2330
2331         /*
2332          * XXX should be taken from not-yet-existing fs abstraction layer.
2333          */
2334         param->ddp_max_name_len = LDISKFS_NAME_LEN;
2335         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
2336         param->ddp_symlink_max  = sb->s_blocksize;
2337         param->ddp_mount_type   = LDD_MT_LDISKFS;
2338         if (ldiskfs_has_feature_extents(sb))
2339                 param->ddp_maxbytes = sb->s_maxbytes;
2340         else
2341                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2342         /*
2343          * inode are statically allocated, so per-inode space consumption
2344          * is the space consumed by the directory entry
2345          */
2346         param->ddp_inodespace     = PER_OBJ_USAGE;
2347         /*
2348          * EXT_INIT_MAX_LEN is the theoretical maximum extent size (32k blocks
2349          * is 128MB) which is unlikely to be hit in real life. Report a smaller
2350          * maximum length to not under-count the actual number of extents
2351          * needed for writing a file if there are sub-optimal block allocations.
2352          */
2353         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 1;
2354         /* worst-case extent insertion metadata overhead */
2355         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
2356         param->ddp_mntopts = 0;
2357         if (test_opt(sb, XATTR_USER))
2358                 param->ddp_mntopts |= MNTOPT_USERXATTR;
2359         if (test_opt(sb, POSIX_ACL))
2360                 param->ddp_mntopts |= MNTOPT_ACL;
2361
2362         /*
2363          * LOD might calculate the max stripe count based on max_ea_size,
2364          * so we need take account in the overhead as well,
2365          * xattr_header + magic + xattr_entry_head
2366          */
2367         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
2368                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
2369
2370 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
2371         if (ldiskfs_has_feature_ea_inode(sb))
2372                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
2373                                                                 ea_overhead;
2374         else
2375 #endif
2376                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
2377
2378         if (param->ddp_max_ea_size > OBD_MAX_EA_SIZE)
2379                 param->ddp_max_ea_size = OBD_MAX_EA_SIZE;
2380
2381         /*
2382          * Preferred RPC size for efficient disk IO.  4MB shows good
2383          * all-around performance for ldiskfs, but use bigalloc chunk size
2384          * by default if larger.
2385          */
2386 #if defined(LDISKFS_CLUSTER_SIZE)
2387         if (LDISKFS_CLUSTER_SIZE(sb) > DT_DEF_BRW_SIZE)
2388                 param->ddp_brw_size = LDISKFS_CLUSTER_SIZE(sb);
2389         else
2390 #endif
2391                 param->ddp_brw_size = DT_DEF_BRW_SIZE;
2392
2393         param->ddp_t10_cksum_type = 0;
2394         if (bi) {
2395                 unsigned short interval = blk_integrity_interval(bi);
2396                 name = blk_integrity_name(bi);
2397                 /*
2398                  * Expected values:
2399                  * T10-DIF-TYPE1-CRC
2400                  * T10-DIF-TYPE3-CRC
2401                  * T10-DIF-TYPE1-IP
2402                  * T10-DIF-TYPE3-IP
2403                  */
2404                 if (strncmp(name, "T10-DIF-TYPE",
2405                             sizeof("T10-DIF-TYPE") - 1) == 0) {
2406                         /* also skip "1/3-" at end */
2407                         const int type_off = sizeof("T10-DIF-TYPE.");
2408                         char type_number = name[type_off - 2];
2409
2410                         if (interval != 512 && interval != 4096) {
2411                                 CERROR("%s: unsupported T10PI sector size %u\n",
2412                                        d->od_svname, interval);
2413                         } else if (type_number != '1' && type_number != '3') {
2414                                 CERROR("%s: unsupported T10PI type %s\n",
2415                                        d->od_svname, name);
2416                         } else if (strcmp(name + type_off, "CRC") == 0) {
2417                                 d->od_t10_type = type_number == '1' ?
2418                                         OSD_T10_TYPE1_CRC : OSD_T10_TYPE3_CRC;
2419                                 param->ddp_t10_cksum_type = interval == 512 ?
2420                                         OBD_CKSUM_T10CRC512 :
2421                                         OBD_CKSUM_T10CRC4K;
2422                         } else if (strcmp(name + type_off, "IP") == 0) {
2423                                 d->od_t10_type = type_number == '1' ?
2424                                         OSD_T10_TYPE1_IP : OSD_T10_TYPE3_IP;
2425                                 param->ddp_t10_cksum_type = interval == 512 ?
2426                                         OBD_CKSUM_T10IP512 :
2427                                         OBD_CKSUM_T10IP4K;
2428                         } else {
2429                                 CERROR("%s: unsupported checksum type of T10PI type '%s'\n",
2430                                        d->od_svname, name);
2431                         }
2432
2433                 } else {
2434                         CERROR("%s: unsupported T10PI type '%s'\n",
2435                                d->od_svname, name);
2436                 }
2437         }
2438
2439         param->ddp_has_lseek_data_hole = true;
2440 }
2441
2442 static struct super_block *osd_mnt_sb_get(const struct dt_device *d)
2443 {
2444         return osd_sb(osd_dt_dev(d));
2445 }
2446
2447 /*
2448  * Concurrency: shouldn't matter.
2449  */
2450 static int osd_sync(const struct lu_env *env, struct dt_device *d)
2451 {
2452         int rc;
2453         struct super_block *s = osd_sb(osd_dt_dev(d));
2454         ENTRY;
2455
2456         down_read(&s->s_umount);
2457         rc = s->s_op->sync_fs(s, 1);
2458         up_read(&s->s_umount);
2459
2460         CDEBUG(D_CACHE, "%s: synced OSD: rc = %d\n", osd_dt_dev(d)->od_svname,
2461                rc);
2462
2463         return rc;
2464 }
2465
2466 /**
2467  * Start commit for OSD device.
2468  *
2469  * An implementation of dt_commit_async method for OSD device.
2470  * Asychronously starts underlayng fs sync and thereby a transaction
2471  * commit.
2472  *
2473  * \param env environment
2474  * \param d dt device
2475  *
2476  * \see dt_device_operations
2477  */
2478 static int osd_commit_async(const struct lu_env *env,
2479                             struct dt_device *d)
2480 {
2481         struct super_block *s = osd_sb(osd_dt_dev(d));
2482         int rc;
2483
2484         ENTRY;
2485
2486         CDEBUG(D_HA, "%s: async commit OSD\n", osd_dt_dev(d)->od_svname);
2487         down_read(&s->s_umount);
2488         rc = s->s_op->sync_fs(s, 0);
2489         up_read(&s->s_umount);
2490
2491         RETURN(rc);
2492 }
2493
2494 static int (*priv_security_file_alloc)(struct file *file);
2495
2496 int osd_security_file_alloc(struct file *file)
2497 {
2498         if (priv_security_file_alloc)
2499                 return priv_security_file_alloc(file);
2500         return 0;
2501 }
2502
2503 /*
2504  * Concurrency: shouldn't matter.
2505  */
2506 static int osd_ro(const struct lu_env *env, struct dt_device *d)
2507 {
2508         struct super_block *sb = osd_sb(osd_dt_dev(d));
2509         struct block_device *dev = sb->s_bdev;
2510         int rc = -EOPNOTSUPP;
2511
2512         ENTRY;
2513
2514         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
2515                osd_dt_dev(d)->od_svname, (long)dev, rc);
2516
2517         RETURN(rc);
2518 }
2519
2520 /**
2521  * Note: we do not count into QUOTA here.
2522  * If we mount with --data_journal we may need more.
2523  */
2524 const int osd_dto_credits_noquota[DTO_NR] = {
2525         /**
2526          * Insert.
2527          * INDEX_EXTRA_TRANS_BLOCKS(8) +
2528          * SINGLEDATA_TRANS_BLOCKS(8)
2529          * XXX Note: maybe iam need more, since iam have more level than
2530          *           EXT3 htree.
2531          */
2532         [DTO_INDEX_INSERT]  = 16,
2533         /**
2534          * Delete
2535          * just modify a single entry, probably merge few within a block
2536          */
2537         [DTO_INDEX_DELETE]  = 1,
2538         /**
2539          * Used for OI scrub
2540          */
2541         [DTO_INDEX_UPDATE]  = 16,
2542         /**
2543          * 4(inode, inode bits, groups, GDT)
2544          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
2545          */
2546         [DTO_OBJECT_CREATE] = 4,
2547         /**
2548          * 4(inode, inode bits, groups, GDT)
2549          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
2550          */
2551         [DTO_OBJECT_DELETE] = 4,
2552         /**
2553          * Attr set credits (inode)
2554          */
2555         [DTO_ATTR_SET_BASE] = 1,
2556         /**
2557          * Xattr set. The same as xattr of EXT3.
2558          * DATA_TRANS_BLOCKS(14)
2559          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
2560          * are also counted in. Do not know why?
2561          */
2562         [DTO_XATTR_SET]     = 14,
2563         /**
2564          * credits for inode change during write.
2565          */
2566         [DTO_WRITE_BASE]    = 3,
2567         /**
2568          * credits for single block write.
2569          */
2570         [DTO_WRITE_BLOCK]   = 14,
2571         /**
2572          * Attr set credits for chown.
2573          * This is extra credits for setattr, and it is null without quota
2574          */
2575         [DTO_ATTR_SET_CHOWN] = 0
2576 };
2577
2578 /* reserve or free quota for some operation */
2579 static int osd_reserve_or_free_quota(const struct lu_env *env,
2580                                      struct dt_device *dev,
2581                                      enum quota_type type, __u64 uid,
2582                                      __u64 gid, __s64 count, bool is_md)
2583 {
2584         int rc;
2585         struct osd_device       *osd = osd_dt_dev(dev);
2586         struct osd_thread_info  *info = osd_oti_get(env);
2587         struct lquota_id_info   *qi = &info->oti_qi;
2588         struct qsd_instance     *qsd = NULL;
2589
2590         ENTRY;
2591
2592         if (is_md)
2593                 qsd = osd->od_quota_slave_md;
2594         else
2595                 qsd = osd->od_quota_slave_dt;
2596
2597         rc = quota_reserve_or_free(env, qsd, qi, type, uid, gid, count, is_md);
2598         RETURN(rc);
2599 }
2600
2601 static const struct dt_device_operations osd_dt_ops = {
2602         .dt_root_get              = osd_root_get,
2603         .dt_statfs                = osd_statfs,
2604         .dt_trans_create          = osd_trans_create,
2605         .dt_trans_start           = osd_trans_start,
2606         .dt_trans_stop            = osd_trans_stop,
2607         .dt_trans_cb_add          = osd_trans_cb_add,
2608         .dt_conf_get              = osd_conf_get,
2609         .dt_mnt_sb_get            = osd_mnt_sb_get,
2610         .dt_sync                  = osd_sync,
2611         .dt_ro                    = osd_ro,
2612         .dt_commit_async          = osd_commit_async,
2613         .dt_reserve_or_free_quota = osd_reserve_or_free_quota,
2614 };
2615
2616 static void osd_read_lock(const struct lu_env *env, struct dt_object *dt,
2617                           unsigned int role)
2618 {
2619         struct osd_object *obj = osd_dt_obj(dt);
2620         struct osd_thread_info *oti = osd_oti_get(env);
2621
2622         LINVRNT(osd_invariant(obj));
2623
2624         LASSERT(obj->oo_owner != env);
2625         down_read_nested(&obj->oo_sem, role);
2626
2627         LASSERT(obj->oo_owner == NULL);
2628         oti->oti_r_locks++;
2629 }
2630
2631 static void osd_write_lock(const struct lu_env *env, struct dt_object *dt,
2632                            unsigned int role)
2633 {
2634         struct osd_object *obj = osd_dt_obj(dt);
2635         struct osd_thread_info *oti = osd_oti_get(env);
2636
2637         LINVRNT(osd_invariant(obj));
2638
2639         LASSERT(obj->oo_owner != env);
2640         down_write_nested(&obj->oo_sem, role);
2641
2642         LASSERT(obj->oo_owner == NULL);
2643         obj->oo_owner = env;
2644         oti->oti_w_locks++;
2645 }
2646
2647 static void osd_read_unlock(const struct lu_env *env, struct dt_object *dt)
2648 {
2649         struct osd_object *obj = osd_dt_obj(dt);
2650         struct osd_thread_info *oti = osd_oti_get(env);
2651
2652         LINVRNT(osd_invariant(obj));
2653
2654         LASSERT(oti->oti_r_locks > 0);
2655         oti->oti_r_locks--;
2656         up_read(&obj->oo_sem);
2657 }
2658
2659 static void osd_write_unlock(const struct lu_env *env, struct dt_object *dt)
2660 {
2661         struct osd_object *obj = osd_dt_obj(dt);
2662         struct osd_thread_info *oti = osd_oti_get(env);
2663
2664         LINVRNT(osd_invariant(obj));
2665
2666         LASSERT(obj->oo_owner == env);
2667         LASSERT(oti->oti_w_locks > 0);
2668         oti->oti_w_locks--;
2669         obj->oo_owner = NULL;
2670         up_write(&obj->oo_sem);
2671 }
2672
2673 static int osd_write_locked(const struct lu_env *env, struct dt_object *dt)
2674 {
2675         struct osd_object *obj = osd_dt_obj(dt);
2676
2677         LINVRNT(osd_invariant(obj));
2678
2679         return obj->oo_owner == env;
2680 }
2681
2682 static void osd_inode_getattr(const struct lu_env *env,
2683                               struct inode *inode, struct lu_attr *attr)
2684 {
2685         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
2686                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
2687                            LA_PROJID | LA_FLAGS | LA_NLINK | LA_RDEV |
2688                            LA_BLKSIZE | LA_TYPE | LA_BTIME;
2689
2690         attr->la_atime = inode->i_atime.tv_sec;
2691         attr->la_mtime = inode->i_mtime.tv_sec;
2692         attr->la_ctime = inode->i_ctime.tv_sec;
2693         attr->la_btime = LDISKFS_I(inode)->i_crtime.tv_sec;
2694         attr->la_mode    = inode->i_mode;
2695         attr->la_size    = i_size_read(inode);
2696         attr->la_blocks  = inode->i_blocks;
2697         attr->la_uid     = i_uid_read(inode);
2698         attr->la_gid     = i_gid_read(inode);
2699         attr->la_projid  = i_projid_read(inode);
2700         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
2701         attr->la_nlink   = inode->i_nlink;
2702         attr->la_rdev    = inode->i_rdev;
2703         attr->la_blksize = 1 << inode->i_blkbits;
2704         attr->la_blkbits = inode->i_blkbits;
2705         /*
2706          * Ext4 did not transfer inherit flags from raw inode
2707          * to inode flags, and ext4 internally test raw inode
2708          * @i_flags directly. Instead of patching ext4, we do it here.
2709          */
2710         if (LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL)
2711                 attr->la_flags |= LUSTRE_PROJINHERIT_FL;
2712 }
2713
2714 static int osd_dirent_count(const struct lu_env *env, struct dt_object *dt,
2715                             u64 *count)
2716 {
2717         struct osd_object *obj = osd_dt_obj(dt);
2718         const struct dt_it_ops *iops;
2719         struct dt_it *it;
2720         int rc;
2721
2722         ENTRY;
2723
2724         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
2725         LASSERT(fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)));
2726
2727         if (obj->oo_dirent_count != LU_DIRENT_COUNT_UNSET) {
2728                 *count = obj->oo_dirent_count;
2729                 RETURN(0);
2730         }
2731
2732         /* directory not initialized yet */
2733         if (!dt->do_index_ops) {
2734                 *count = 0;
2735                 RETURN(0);
2736         }
2737
2738         iops = &dt->do_index_ops->dio_it;
2739         it = iops->init(env, dt, LUDA_64BITHASH);
2740         if (IS_ERR(it))
2741                 RETURN(PTR_ERR(it));
2742
2743         rc = iops->load(env, it, 0);
2744         if (rc < 0) {
2745                 if (rc == -ENODATA) {
2746                         rc = 0;
2747                         *count = 0;
2748                 }
2749                 GOTO(out, rc);
2750         }
2751         if (rc > 0)
2752                 rc = iops->next(env, it);
2753
2754         for (*count = 0; rc == 0 || rc == -ESTALE; rc = iops->next(env, it)) {
2755                 if (rc == -ESTALE)
2756                         continue;
2757
2758                 if (iops->key_size(env, it) == 0)
2759                         continue;
2760
2761                 (*count)++;
2762         }
2763         if (rc == 1) {
2764                 obj->oo_dirent_count = *count;
2765                 rc = 0;
2766         }
2767 out:
2768         iops->put(env, it);
2769         iops->fini(env, it);
2770
2771         RETURN(rc);
2772 }
2773
2774 static int osd_attr_get(const struct lu_env *env, struct dt_object *dt,
2775                         struct lu_attr *attr)
2776 {
2777         struct osd_object *obj = osd_dt_obj(dt);
2778         int rc = 0;
2779
2780         if (unlikely(!dt_object_exists(dt)))
2781                 return -ENOENT;
2782         if (unlikely(obj->oo_destroyed))
2783                 return -ENOENT;
2784
2785         LASSERT(!dt_object_remote(dt));
2786         LINVRNT(osd_invariant(obj));
2787
2788         spin_lock(&obj->oo_guard);
2789         osd_inode_getattr(env, obj->oo_inode, attr);
2790         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL) {
2791                 attr->la_valid |= LA_FLAGS;
2792                 attr->la_flags |= LUSTRE_ORPHAN_FL;
2793         }
2794         if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL) {
2795                 attr->la_valid |= LA_FLAGS;
2796                 attr->la_flags |= LUSTRE_ENCRYPT_FL;
2797         }
2798         spin_unlock(&obj->oo_guard);
2799
2800         if (S_ISDIR(obj->oo_inode->i_mode) &&
2801             fid_is_namespace_visible(lu_object_fid(&dt->do_lu)))
2802                 rc = osd_dirent_count(env, dt, &attr->la_dirent_count);
2803
2804         return rc;
2805 }
2806
2807 static int osd_declare_attr_qid(const struct lu_env *env,
2808                                 struct osd_object *obj,
2809                                 struct osd_thandle *oh, long long bspace,
2810                                 qid_t old_id, qid_t new_id, bool enforce,
2811                                 unsigned int type)
2812 {
2813         int rc;
2814         struct osd_thread_info *info = osd_oti_get(env);
2815         struct lquota_id_info  *qi = &info->oti_qi;
2816
2817         qi->lqi_type = type;
2818         /* inode accounting */
2819         qi->lqi_is_blk = false;
2820
2821         /* one more inode for the new id ... */
2822         qi->lqi_id.qid_uid = new_id;
2823         qi->lqi_space      = 1;
2824         /* Reserve credits for the new id */
2825         rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2826         if (rc == -EDQUOT || rc == -EINPROGRESS)
2827                 rc = 0;
2828         if (rc)
2829                 RETURN(rc);
2830
2831         /* and one less inode for the current id */
2832         qi->lqi_id.qid_uid = old_id;
2833         qi->lqi_space = -1;
2834         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2835         if (rc == -EDQUOT || rc == -EINPROGRESS)
2836                 rc = 0;
2837         if (rc)
2838                 RETURN(rc);
2839
2840         /* block accounting */
2841         qi->lqi_is_blk = true;
2842
2843         /* more blocks for the new id ... */
2844         qi->lqi_id.qid_uid = new_id;
2845         qi->lqi_space      = bspace;
2846         /*
2847          * Credits for the new uid has been reserved, re-use "obj"
2848          * to save credit reservation.
2849          */
2850         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2851         if (rc == -EDQUOT || rc == -EINPROGRESS)
2852                 rc = 0;
2853         if (rc)
2854                 RETURN(rc);
2855
2856         /* and finally less blocks for the current uid */
2857         qi->lqi_id.qid_uid = old_id;
2858         qi->lqi_space      = -bspace;
2859         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2860         if (rc == -EDQUOT || rc == -EINPROGRESS)
2861                 rc = 0;
2862
2863         RETURN(rc);
2864 }
2865
2866 static int osd_declare_attr_set(const struct lu_env *env,
2867                                 struct dt_object *dt,
2868                                 const struct lu_attr *attr,
2869                                 struct thandle *handle)
2870 {
2871         struct osd_thandle *oh;
2872         struct osd_object *obj;
2873         qid_t uid;
2874         qid_t gid;
2875         long long bspace;
2876         int rc = 0;
2877         bool enforce;
2878
2879         ENTRY;
2880
2881         LASSERT(dt != NULL);
2882         LASSERT(handle != NULL);
2883
2884         obj = osd_dt_obj(dt);
2885         LASSERT(osd_invariant(obj));
2886
2887         oh = container_of(handle, struct osd_thandle, ot_super);
2888         LASSERT(oh->ot_handle == NULL);
2889
2890         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
2891                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2892
2893         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2894                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2895
2896         if (attr == NULL || obj->oo_inode == NULL)
2897                 RETURN(rc);
2898
2899         bspace   = obj->oo_inode->i_blocks << 9;
2900         bspace   = toqb(bspace);
2901
2902         /*
2903          * Changing ownership is always preformed by super user, it should not
2904          * fail with EDQUOT unless required explicitly.
2905          *
2906          * We still need to call the osd_declare_qid() to calculate the journal
2907          * credits for updating quota accounting files and to trigger quota
2908          * space adjustment once the operation is completed.
2909          */
2910         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
2911                 /* USERQUOTA */
2912                 uid = i_uid_read(obj->oo_inode);
2913                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
2914                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
2915                                           attr->la_uid, enforce, USRQUOTA);
2916                 if (rc)
2917                         RETURN(rc);
2918
2919                 gid = i_gid_read(obj->oo_inode);
2920                 CDEBUG(D_QUOTA, "declare uid %d -> %d gid %d -> %d\n", uid,
2921                        attr->la_uid, gid, attr->la_gid);
2922                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
2923                 rc = osd_declare_attr_qid(env, obj, oh, bspace, gid,
2924                                           attr->la_gid, enforce, GRPQUOTA);
2925                 if (rc)
2926                         RETURN(rc);
2927
2928         }
2929 #ifdef HAVE_PROJECT_QUOTA
2930         if (attr->la_valid & LA_PROJID) {
2931                 __u32 projid = i_projid_read(obj->oo_inode);
2932
2933                 enforce = (attr->la_valid & LA_PROJID) &&
2934                                         (attr->la_projid != projid);
2935                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2936                                           (qid_t)projid, (qid_t)attr->la_projid,
2937                                           enforce, PRJQUOTA);
2938                 if (rc)
2939                         RETURN(rc);
2940         }
2941 #endif
2942         RETURN(rc);
2943 }
2944
2945 static int osd_inode_setattr(const struct lu_env *env,
2946                              struct inode *inode, const struct lu_attr *attr)
2947 {
2948         __u64 bits = attr->la_valid;
2949
2950         /* Only allow set size for regular file */
2951         if (!S_ISREG(inode->i_mode))
2952                 bits &= ~(LA_SIZE | LA_BLOCKS);
2953
2954         if (bits == 0)
2955                 return 0;
2956
2957         if (bits & LA_ATIME)
2958                 inode->i_atime = osd_inode_time(inode, attr->la_atime);
2959         if (bits & LA_CTIME)
2960                 inode->i_ctime = osd_inode_time(inode, attr->la_ctime);
2961         if (bits & LA_MTIME)
2962                 inode->i_mtime = osd_inode_time(inode, attr->la_mtime);
2963         if (bits & LA_SIZE) {
2964                 spin_lock(&inode->i_lock);
2965                 LDISKFS_I(inode)->i_disksize = attr->la_size;
2966                 i_size_write(inode, attr->la_size);
2967                 spin_unlock(&inode->i_lock);
2968         }
2969
2970         /*
2971          * OSD should not change "i_blocks" which is used by quota.
2972          * "i_blocks" should be changed by ldiskfs only.
2973          */
2974         if (bits & LA_MODE)
2975                 inode->i_mode = (inode->i_mode & S_IFMT) |
2976                                 (attr->la_mode & ~S_IFMT);
2977         if (bits & LA_UID)
2978                 i_uid_write(inode, attr->la_uid);
2979         if (bits & LA_GID)
2980                 i_gid_write(inode, attr->la_gid);
2981         if (bits & LA_PROJID)
2982                 i_projid_write(inode, attr->la_projid);
2983         if (bits & LA_NLINK)
2984                 set_nlink(inode, attr->la_nlink);
2985         if (bits & LA_RDEV)
2986                 inode->i_rdev = attr->la_rdev;
2987
2988         if (bits & LA_FLAGS) {
2989                 /* always keep S_NOCMTIME */
2990                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
2991                                  S_NOCMTIME;
2992 #if defined(S_ENCRYPTED)
2993                 /* Always remove S_ENCRYPTED, because ldiskfs must not be
2994                  * aware of encryption status. It is just stored into LMA
2995                  * so that it can be forwared to client side.
2996                  */
2997                 inode->i_flags &= ~S_ENCRYPTED;
2998 #endif
2999                 /*
3000                  * Ext4 did not transfer inherit flags from
3001                  * @inode->i_flags to raw inode i_flags when writing
3002                  * flags, we do it explictly here.
3003                  */
3004                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
3005                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
3006                 else
3007                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
3008         }
3009         return 0;
3010 }
3011
3012 #ifdef HAVE_PROJECT_QUOTA
3013 static int osd_transfer_project(struct inode *inode, __u32 projid,
3014                                 struct thandle *handle)
3015 {
3016         struct super_block *sb = inode->i_sb;
3017         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
3018         int err;
3019         kprojid_t kprojid;
3020         struct ldiskfs_iloc iloc;
3021         struct ldiskfs_inode *raw_inode;
3022         struct dquot *transfer_to[LDISKFS_MAXQUOTAS] = { };
3023
3024         if (!ldiskfs_has_feature_project(sb)) {
3025                 LASSERT(__kprojid_val(LDISKFS_I(inode)->i_projid)
3026                         == LDISKFS_DEF_PROJID);
3027                 if (projid != LDISKFS_DEF_PROJID)
3028                         return -EOPNOTSUPP;
3029                 else
3030                         return 0;
3031         }
3032
3033         if (LDISKFS_INODE_SIZE(sb) <= LDISKFS_GOOD_OLD_INODE_SIZE)
3034                 return -EOPNOTSUPP;
3035
3036         kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3037         if (projid_eq(kprojid, LDISKFS_I(inode)->i_projid))
3038                 return 0;
3039
3040         err = ldiskfs_get_inode_loc(inode, &iloc);
3041         if (err)
3042                 return err;
3043
3044         raw_inode = ldiskfs_raw_inode(&iloc);
3045         if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3046                 struct osd_thandle *oh = container_of(handle,
3047                                                       struct osd_thandle,
3048                                                       ot_super);
3049                 /**
3050                  * try to expand inode size automatically.
3051                  */
3052                 ldiskfs_mark_inode_dirty(oh->ot_handle, inode);
3053                 if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3054                         err = -EOVERFLOW;
3055                         brelse(iloc.bh);
3056                         return err;
3057                 }
3058         }
3059         brelse(iloc.bh);
3060
3061         dquot_initialize(inode);
3062         transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3063         if (transfer_to[PRJQUOTA]) {
3064                 err = __dquot_transfer(inode, transfer_to);
3065                 dqput(transfer_to[PRJQUOTA]);
3066                 if (err)
3067                         return err;
3068         }
3069
3070         return err;
3071 }
3072 #endif
3073
3074 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr,
3075                               struct thandle *handle)
3076 {
3077         int rc;
3078
3079         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
3080             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
3081                 struct iattr iattr;
3082
3083                 CDEBUG(D_QUOTA,
3084                        "executing dquot_transfer inode %ld uid %d -> %d gid %d -> %d\n",
3085                        inode->i_ino, i_uid_read(inode), attr->la_uid,
3086                        i_gid_read(inode), attr->la_gid);
3087
3088                 dquot_initialize(inode);
3089                 iattr.ia_valid = 0;
3090                 if (attr->la_valid & LA_UID)
3091                         iattr.ia_valid |= ATTR_UID;
3092                 if (attr->la_valid & LA_GID)
3093                         iattr.ia_valid |= ATTR_GID;
3094                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3095                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3096
3097                 rc = dquot_transfer(inode, &iattr);
3098                 if (rc) {
3099                         CERROR("%s: quota transfer failed. Is quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3100                                osd_ino2name(inode), rc);
3101                         return rc;
3102                 }
3103         }
3104
3105         /* Handle project id transfer here properly */
3106         if (attr->la_valid & LA_PROJID &&
3107             attr->la_projid != i_projid_read(inode)) {
3108                 if (!projid_valid(make_kprojid(&init_user_ns, attr->la_projid)))
3109                         return -EINVAL;
3110 #ifdef HAVE_PROJECT_QUOTA
3111                 rc = osd_transfer_project(inode, attr->la_projid, handle);
3112 #else
3113                 rc = -ENOTSUPP;
3114 #endif
3115                 if (rc) {
3116                         CERROR("%s: quota transfer failed. Is project enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3117                                osd_ino2name(inode), rc);
3118                         return rc;
3119                 }
3120         }
3121         return 0;
3122 }
3123
3124 static int osd_attr_set(const struct lu_env *env,
3125                         struct dt_object *dt,
3126                         const struct lu_attr *attr,
3127                         struct thandle *handle)
3128 {
3129         struct osd_object *obj = osd_dt_obj(dt);
3130         struct inode *inode;
3131         int rc;
3132
3133         if (!dt_object_exists(dt))
3134                 return -ENOENT;
3135
3136         LASSERT(handle != NULL);
3137         LASSERT(!dt_object_remote(dt));
3138         LASSERT(osd_invariant(obj));
3139
3140         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
3141
3142         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
3143             !osd_obj2dev(obj)->od_is_ost) {
3144                 struct osd_thread_info *oti = osd_oti_get(env);
3145                 const struct lu_fid *fid0 = lu_object_fid(&dt->do_lu);
3146                 struct lu_fid *fid1 = &oti->oti_fid;
3147                 struct osd_inode_id *id = &oti->oti_id;
3148                 struct iam_path_descr *ipd;
3149                 struct iam_container *bag;
3150                 struct osd_thandle *oh;
3151                 int rc;
3152
3153                 fid_cpu_to_be(fid1, fid0);
3154                 memset(id, 1, sizeof(*id));
3155                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
3156                                   fid0)->oi_dir.od_container;
3157                 ipd = osd_idx_ipd_get(env, bag);
3158                 if (unlikely(ipd == NULL))
3159                         RETURN(-ENOMEM);
3160
3161                 oh = container_of(handle, struct osd_thandle, ot_super);
3162                 rc = iam_update(oh->ot_handle, bag,
3163                                 (const struct iam_key *)fid1,
3164                                 (const struct iam_rec *)id, ipd);
3165                 osd_ipd_put(env, bag, ipd);
3166                 return(rc > 0 ? 0 : rc);
3167         }
3168
3169         inode = obj->oo_inode;
3170
3171         rc = osd_quota_transfer(inode, attr, handle);
3172         if (rc)
3173                 return rc;
3174
3175         spin_lock(&obj->oo_guard);
3176         rc = osd_inode_setattr(env, inode, attr);
3177         spin_unlock(&obj->oo_guard);
3178         if (rc != 0)
3179                 GOTO(out, rc);
3180
3181         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3182
3183         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
3184
3185         if (!(attr->la_valid & LA_FLAGS))
3186                 GOTO(out, rc);
3187
3188         /* Let's check if there are extra flags need to be set into LMA */
3189         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
3190                 struct osd_thread_info *info = osd_oti_get(env);
3191                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
3192
3193                 LASSERT(!obj->oo_pfid_in_lma);
3194
3195                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
3196                                  &info->oti_ost_attrs);
3197                 if (rc)
3198                         GOTO(out, rc);
3199
3200                 lma->lma_incompat |=
3201                         lustre_to_lma_flags(attr->la_flags);
3202                 lustre_lma_swab(lma);
3203
3204                 osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3205
3206                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
3207                                      lma, sizeof(*lma), XATTR_REPLACE);
3208                 if (rc != 0) {
3209                         struct osd_device *osd = osd_obj2dev(obj);
3210
3211                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
3212                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3213                               lma->lma_incompat, rc);
3214                 } else {
3215                         obj->oo_lma_flags =
3216                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
3217                 }
3218                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3219         }
3220 out:
3221
3222         return rc;
3223 }
3224
3225 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
3226                                            struct osd_object *obj,
3227                                            const char *name, const int namelen)
3228 {
3229         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
3230 }
3231
3232 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
3233                       umode_t mode, struct dt_allocation_hint *hint,
3234                       struct thandle *th, struct lu_attr *attr)
3235 {
3236         int result;
3237         struct osd_device *osd = osd_obj2dev(obj);
3238         struct osd_thandle *oth;
3239         struct dt_object *parent = NULL;
3240         struct inode *inode;
3241         struct iattr iattr = {
3242                 .ia_valid = ATTR_UID | ATTR_GID |
3243                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
3244                 .ia_ctime.tv_sec = attr->la_ctime,
3245                 .ia_mtime.tv_sec = attr->la_mtime,
3246                 .ia_atime.tv_sec = attr->la_atime,
3247                 .ia_uid = GLOBAL_ROOT_UID,
3248                 .ia_gid = GLOBAL_ROOT_GID,
3249         };
3250         const struct osd_timespec omit = { .tv_nsec = UTIME_OMIT };
3251
3252         if (attr->la_valid & LA_UID)
3253                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3254         if (attr->la_valid & LA_GID)
3255                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3256
3257         LINVRNT(osd_invariant(obj));
3258         LASSERT(obj->oo_inode == NULL);
3259         LASSERT(obj->oo_hl_head == NULL);
3260
3261         if (S_ISDIR(mode) && ldiskfs_pdo) {
3262                 obj->oo_hl_head =
3263                         ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
3264                 if (obj->oo_hl_head == NULL)
3265                         return -ENOMEM;
3266         }
3267
3268         oth = container_of(th, struct osd_thandle, ot_super);
3269         LASSERT(oth->ot_handle->h_transaction != NULL);
3270
3271         if (hint != NULL && hint->dah_parent != NULL &&
3272             !dt_object_remote(hint->dah_parent))
3273                 parent = hint->dah_parent;
3274
3275         /* if a time component is not valid set it to UTIME_OMIT */
3276         if (!(attr->la_valid & LA_CTIME))
3277                 iattr.ia_ctime = omit;
3278         if (!(attr->la_valid & LA_MTIME))
3279                 iattr.ia_mtime = omit;
3280         if (!(attr->la_valid & LA_ATIME))
3281                 iattr.ia_atime = omit;
3282
3283         inode = ldiskfs_create_inode(oth->ot_handle,
3284                                      parent ? osd_dt_obj(parent)->oo_inode :
3285                                               osd_sb(osd)->s_root->d_inode,
3286                                      mode, &iattr);
3287         if (!IS_ERR(inode)) {
3288                 /* Do not update file c/mtime in ldiskfs. */
3289                 inode->i_flags |= S_NOCMTIME;
3290
3291                 /*
3292                  * For new created object, it must be consistent,
3293                  * and it is unnecessary to scrub against it.
3294                  */
3295                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
3296
3297                 obj->oo_inode = inode;
3298                 result = 0;
3299         } else {
3300                 if (obj->oo_hl_head != NULL) {
3301                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
3302                         obj->oo_hl_head = NULL;
3303                 }
3304                 result = PTR_ERR(inode);
3305         }
3306         LINVRNT(osd_invariant(obj));
3307         return result;
3308 }
3309
3310 enum {
3311         OSD_NAME_LEN = 255
3312 };
3313
3314 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
3315                      struct lu_attr *attr,
3316                      struct dt_allocation_hint *hint,
3317                      struct dt_object_format *dof,
3318                      struct thandle *th)
3319 {
3320         int result;
3321         struct osd_thandle *oth;
3322         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
3323
3324         LASSERT(S_ISDIR(attr->la_mode));
3325
3326         oth = container_of(th, struct osd_thandle, ot_super);
3327         LASSERT(oth->ot_handle->h_transaction != NULL);
3328         if (fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)))
3329                 obj->oo_dirent_count = 0;
3330         result = osd_mkfile(info, obj, mode, hint, th, attr);
3331
3332         return result;
3333 }
3334
3335 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
3336                         struct lu_attr *attr,
3337                         struct dt_allocation_hint *hint,
3338                         struct dt_object_format *dof,
3339                         struct thandle *th)
3340 {
3341         int result;
3342         struct osd_thandle *oth;
3343         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
3344
3345         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
3346
3347         LASSERT(S_ISREG(attr->la_mode));
3348
3349         oth = container_of(th, struct osd_thandle, ot_super);
3350         LASSERT(oth->ot_handle->h_transaction != NULL);
3351
3352         result = osd_mkfile(info, obj, mode, hint, th, attr);
3353         if (result == 0) {
3354                 LASSERT(obj->oo_inode != NULL);
3355                 if (feat->dif_flags & DT_IND_VARKEY)
3356                         result = iam_lvar_create(obj->oo_inode,
3357                                                  feat->dif_keysize_max,
3358                                                  feat->dif_ptrsize,
3359                                                  feat->dif_recsize_max,
3360                                                  oth->ot_handle);
3361                 else
3362                         result = iam_lfix_create(obj->oo_inode,
3363                                                  feat->dif_keysize_max,
3364                                                  feat->dif_ptrsize,
3365                                                  feat->dif_recsize_max,
3366                                                  oth->ot_handle);
3367         }
3368         return result;
3369 }
3370
3371 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
3372                      struct lu_attr *attr,
3373                      struct dt_allocation_hint *hint,
3374                      struct dt_object_format *dof,
3375                      struct thandle *th)
3376 {
3377         LASSERT(S_ISREG(attr->la_mode));
3378         return osd_mkfile(info, obj, (attr->la_mode &
3379                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3380                           attr);
3381 }
3382
3383 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
3384                      struct lu_attr *attr,
3385                      struct dt_allocation_hint *hint,
3386                      struct dt_object_format *dof,
3387                      struct thandle *th)
3388 {
3389         LASSERT(S_ISLNK(attr->la_mode));
3390         return osd_mkfile(info, obj, (attr->la_mode &
3391                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3392                           attr);
3393 }
3394
3395 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
3396                      struct lu_attr *attr,
3397                      struct dt_allocation_hint *hint,
3398                      struct dt_object_format *dof,
3399                      struct thandle *th)
3400 {
3401         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
3402         int result;
3403
3404         LINVRNT(osd_invariant(obj));
3405         LASSERT(obj->oo_inode == NULL);
3406         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
3407                 S_ISFIFO(mode) || S_ISSOCK(mode));
3408
3409         result = osd_mkfile(info, obj, mode, hint, th, attr);
3410         if (result == 0) {
3411                 LASSERT(obj->oo_inode != NULL);
3412                 /*
3413                  * This inode should be marked dirty for i_rdev.  Currently
3414                  * that is done in the osd_attr_init().
3415                  */
3416                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
3417                                    attr->la_rdev);
3418         }
3419         LINVRNT(osd_invariant(obj));
3420         return result;
3421 }
3422
3423 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
3424                               struct lu_attr *,
3425                               struct dt_allocation_hint *hint,
3426                               struct dt_object_format *dof,
3427                               struct thandle *);
3428
3429 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
3430 {
3431         osd_obj_type_f result;
3432
3433         switch (type) {
3434         case DFT_DIR:
3435                 result = osd_mkdir;
3436                 break;
3437         case DFT_REGULAR:
3438                 result = osd_mkreg;
3439                 break;
3440         case DFT_SYM:
3441                 result = osd_mksym;
3442                 break;
3443         case DFT_NODE:
3444                 result = osd_mknod;
3445                 break;
3446         case DFT_INDEX:
3447                 result = osd_mk_index;
3448                 break;
3449
3450         default:
3451                 LBUG();
3452                 break;
3453         }
3454         return result;
3455 }
3456
3457 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3458                         struct dt_object *parent, struct dt_object *child,
3459                         umode_t child_mode)
3460 {
3461         LASSERT(ah);
3462
3463         ah->dah_parent = parent;
3464         ah->dah_mode = child_mode;
3465
3466         if (parent != NULL && !dt_object_remote(parent)) {
3467                 /* will help to find FID->ino at dt_insert("..") */
3468                 struct osd_object *pobj = osd_dt_obj(parent);
3469
3470                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3471         }
3472 }
3473
3474 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3475                           struct lu_attr *attr, struct dt_object_format *dof,
3476                           struct thandle *handle)
3477 {
3478         struct inode *inode = obj->oo_inode;
3479         __u64 valid = attr->la_valid;
3480         int result;
3481
3482         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3483
3484         if (dof->dof_type != DFT_NODE)
3485                 attr->la_valid &= ~LA_RDEV;
3486         if ((valid & LA_ATIME) && (attr->la_atime == inode->i_atime.tv_sec))
3487                 attr->la_valid &= ~LA_ATIME;
3488         if ((valid & LA_CTIME) && (attr->la_ctime == inode->i_ctime.tv_sec))
3489                 attr->la_valid &= ~LA_CTIME;
3490         if ((valid & LA_MTIME) && (attr->la_mtime == inode->i_mtime.tv_sec))
3491                 attr->la_valid &= ~LA_MTIME;
3492
3493         result = osd_quota_transfer(inode, attr, handle);
3494         if (result)
3495                 return;
3496
3497         if (attr->la_valid != 0) {
3498                 result = osd_inode_setattr(info->oti_env, inode, attr);
3499                 /*
3500                  * The osd_inode_setattr() should always succeed here.  The
3501                  * only error that could be returned is EDQUOT when we are
3502                  * trying to change the UID or GID of the inode. However, this
3503                  * should not happen since quota enforcement is no longer
3504                  * enabled on ldiskfs (lquota takes care of it).
3505                  */
3506                 LASSERTF(result == 0, "%d\n", result);
3507                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3508         }
3509
3510         attr->la_valid = valid;
3511 }
3512
3513 /**
3514  * Helper function for osd_create()
3515  *
3516  * \retval 0, on success
3517  */
3518 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3519                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3520                         struct dt_object_format *dof, struct thandle *th)
3521 {
3522         int result;
3523         __u32 umask;
3524
3525         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3526
3527         /* we drop umask so that permissions we pass are not affected */
3528         umask = current->fs->umask;
3529         current->fs->umask = 0;
3530
3531         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3532                                                   th);
3533         if (likely(obj->oo_inode != NULL)) {
3534                 LASSERT(obj->oo_inode->i_state & I_NEW);
3535
3536                 /*
3537                  * Unlock the inode before attr initialization to avoid
3538                  * unnecessary dqget operations. LU-6378
3539                  */
3540                 unlock_new_inode(obj->oo_inode);
3541         }
3542
3543         if (likely(result == 0)) {
3544                 osd_attr_init(info, obj, attr, dof, th);
3545                 osd_object_init0(obj);
3546         }
3547
3548         /* restore previous umask value */
3549         current->fs->umask = umask;
3550
3551         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3552
3553         return result;
3554 }
3555
3556 /**
3557  * Helper function for osd_create()
3558  *
3559  * \retval 0, on success
3560  */
3561 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3562                            const struct lu_fid *fid, struct thandle *th)
3563 {
3564         struct osd_thread_info *info = osd_oti_get(env);
3565         struct osd_inode_id    *id   = &info->oti_id;
3566         struct osd_device      *osd  = osd_obj2dev(obj);
3567         struct osd_thandle     *oh;
3568         int rc;
3569
3570         LASSERT(obj->oo_inode != NULL);
3571
3572         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_OI_ENOSPC))
3573                 return -ENOSPC;
3574
3575         oh = container_of(th, struct osd_thandle, ot_super);
3576         LASSERT(oh->ot_handle);
3577         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3578
3579         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3580         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3581                            OI_CHECK_FLD, NULL);
3582         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP) && osd->od_is_ost) {
3583                 struct lu_fid next_fid = *fid;
3584
3585                 /* insert next object in advance, and map to the same inode */
3586                 next_fid.f_oid++;
3587                 if (next_fid.f_oid != 0) {
3588                         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3589                         osd_oi_insert(info, osd, &next_fid, id, oh->ot_handle,
3590                                       OI_CHECK_FLD, NULL);
3591                         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3592                 }
3593         }
3594
3595         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3596
3597         return rc;
3598 }
3599
3600 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3601                    u64 seq, struct lu_seq_range *range)
3602 {
3603         struct seq_server_site *ss = osd_seq_site(osd);
3604
3605         if (fid_seq_is_idif(seq)) {
3606                 fld_range_set_ost(range);
3607                 range->lsr_index = idif_ost_idx(seq);
3608                 return 0;
3609         }
3610
3611         if (!fid_seq_in_fldb(seq)) {
3612                 fld_range_set_mdt(range);
3613                 if (ss != NULL)
3614                         /*
3615                          * FIXME: If ss is NULL, it suppose not get lsr_index
3616                          * at all
3617                          */
3618                         range->lsr_index = ss->ss_node_id;
3619                 return 0;
3620         }
3621
3622         LASSERT(ss != NULL);
3623         fld_range_set_any(range);
3624         /* OSD will only do local fld lookup */
3625         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3626 }
3627
3628 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3629                               struct lu_attr *attr,
3630                               struct dt_allocation_hint *hint,
3631                               struct dt_object_format *dof,
3632                               struct thandle *handle)
3633 {
3634         struct osd_thandle *oh;
3635         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3636         int credits;
3637         int rc;
3638
3639         ENTRY;
3640
3641         LASSERT(handle != NULL);
3642
3643         oh = container_of(handle, struct osd_thandle, ot_super);
3644         LASSERT(oh->ot_handle == NULL);
3645
3646         /*
3647          * EA object consumes more credits than regular object: osd_mk_index
3648          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3649          * leaf_node, could involves the block, block bitmap, groups, GDT
3650          * change for each block, so add 4 * 2 credits in that case.
3651          *
3652          * The default ACL initialization may consume an additional 16 blocks
3653          */
3654         credits = osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3655                   ((dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3656
3657         /**
3658          * While ldiskfs_new_inode() calls ldiskfs_init_acl() we have to add
3659          * credits for possible default ACL creation in new inode
3660          */
3661         if (hint && hint->dah_acl_len)
3662                 credits += osd_calc_bkmap_credits(sb, NULL, 0, -1,
3663                                 (hint->dah_acl_len + sb->s_blocksize - 1) >>
3664                                 sb->s_blocksize_bits);
3665
3666         osd_trans_declare_op(env, oh, OSD_OT_CREATE, credits);
3667
3668         /*
3669          * Reuse idle OI block may cause additional one OI block
3670          * to be changed.
3671          */
3672